ZTWHHH commited on
Commit
5123a32
·
verified ·
1 Parent(s): 7504f38

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. llava_next/lib/python3.10/site-packages/matplotlib/__init__.pyi +115 -0
  3. llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.py +381 -0
  4. llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.pyi +59 -0
  5. llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/__init__.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/deprecation.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.py +513 -0
  8. llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.pyi +76 -0
  9. llava_next/lib/python3.10/site-packages/matplotlib/_blocking_input.py +30 -0
  10. llava_next/lib/python3.10/site-packages/matplotlib/_cm.py +1446 -0
  11. llava_next/lib/python3.10/site-packages/matplotlib/_cm_listed.py +0 -0
  12. llava_next/lib/python3.10/site-packages/matplotlib/_color_data.py +1141 -0
  13. llava_next/lib/python3.10/site-packages/matplotlib/_docstring.py +125 -0
  14. llava_next/lib/python3.10/site-packages/matplotlib/_enums.pyi +18 -0
  15. llava_next/lib/python3.10/site-packages/matplotlib/_mathtext.py +0 -0
  16. llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py +134 -0
  17. llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi +29 -0
  18. llava_next/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so +3 -0
  19. llava_next/lib/python3.10/site-packages/matplotlib/_tight_layout.py +301 -0
  20. llava_next/lib/python3.10/site-packages/matplotlib/_tri.pyi +26 -0
  21. llava_next/lib/python3.10/site-packages/matplotlib/_version.py +1 -0
  22. llava_next/lib/python3.10/site-packages/matplotlib/axis.pyi +280 -0
  23. llava_next/lib/python3.10/site-packages/matplotlib/cbook.pyi +186 -0
  24. llava_next/lib/python3.10/site-packages/matplotlib/cm.py +664 -0
  25. llava_next/lib/python3.10/site-packages/matplotlib/collections.pyi +236 -0
  26. llava_next/lib/python3.10/site-packages/matplotlib/colorbar.py +1559 -0
  27. llava_next/lib/python3.10/site-packages/matplotlib/colors.pyi +354 -0
  28. llava_next/lib/python3.10/site-packages/matplotlib/container.py +141 -0
  29. llava_next/lib/python3.10/site-packages/matplotlib/dviread.py +1107 -0
  30. llava_next/lib/python3.10/site-packages/matplotlib/dviread.pyi +90 -0
  31. llava_next/lib/python3.10/site-packages/matplotlib/gridspec.py +788 -0
  32. llava_next/lib/python3.10/site-packages/matplotlib/legend.py +1385 -0
  33. llava_next/lib/python3.10/site-packages/matplotlib/markers.pyi +51 -0
  34. llava_next/lib/python3.10/site-packages/matplotlib/offsetbox.py +1569 -0
  35. llava_next/lib/python3.10/site-packages/matplotlib/patches.pyi +755 -0
  36. llava_next/lib/python3.10/site-packages/matplotlib/path.pyi +140 -0
  37. llava_next/lib/python3.10/site-packages/matplotlib/py.typed +0 -0
  38. llava_next/lib/python3.10/site-packages/matplotlib/pyplot.py +0 -0
  39. llava_next/lib/python3.10/site-packages/matplotlib/rcsetup.py +1377 -0
  40. llava_next/lib/python3.10/site-packages/matplotlib/sankey.py +814 -0
  41. llava_next/lib/python3.10/site-packages/matplotlib/sankey.pyi +61 -0
  42. llava_next/lib/python3.10/site-packages/matplotlib/streamplot.pyi +82 -0
  43. llava_next/lib/python3.10/site-packages/matplotlib/style/__init__.py +4 -0
  44. llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/__init__.cpython-310.pyc +0 -0
  45. llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/core.cpython-310.pyc +0 -0
  46. llava_next/lib/python3.10/site-packages/matplotlib/style/core.py +245 -0
  47. llava_next/lib/python3.10/site-packages/matplotlib/style/core.pyi +19 -0
  48. llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.py +234 -0
  49. llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.pyi +54 -0
  50. llava_next/lib/python3.10/site-packages/matplotlib/testing/_markers.py +49 -0
.gitattributes CHANGED
@@ -362,3 +362,4 @@ llava_next/lib/python3.10/site-packages/scipy/optimize/_lsq/givens_elimination.c
362
  parrot/lib/python3.10/site-packages/torch/testing/_internal/generated/__pycache__/annotated_fn_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
363
  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
364
  parrot/lib/python3.10/site-packages/torchvision.libs/libpng16.7f72a3c5.so.16 filter=lfs diff=lfs merge=lfs -text
 
 
362
  parrot/lib/python3.10/site-packages/torch/testing/_internal/generated/__pycache__/annotated_fn_args.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
363
  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
364
  parrot/lib/python3.10/site-packages/torchvision.libs/libpng16.7f72a3c5.so.16 filter=lfs diff=lfs merge=lfs -text
365
+ llava_next/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
llava_next/lib/python3.10/site-packages/matplotlib/__init__.pyi ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ __all__ = [
2
+ "__bibtex__",
3
+ "__version__",
4
+ "__version_info__",
5
+ "set_loglevel",
6
+ "ExecutableNotFoundError",
7
+ "get_configdir",
8
+ "get_cachedir",
9
+ "get_data_path",
10
+ "matplotlib_fname",
11
+ "MatplotlibDeprecationWarning",
12
+ "RcParams",
13
+ "rc_params",
14
+ "rc_params_from_file",
15
+ "rcParamsDefault",
16
+ "rcParams",
17
+ "rcParamsOrig",
18
+ "defaultParams",
19
+ "rc",
20
+ "rcdefaults",
21
+ "rc_file_defaults",
22
+ "rc_file",
23
+ "rc_context",
24
+ "use",
25
+ "get_backend",
26
+ "interactive",
27
+ "is_interactive",
28
+ "colormaps",
29
+ "color_sequences",
30
+ ]
31
+
32
+ import os
33
+ from pathlib import Path
34
+
35
+ from collections.abc import Callable, Generator
36
+ import contextlib
37
+ from packaging.version import Version
38
+
39
+ from matplotlib._api import MatplotlibDeprecationWarning
40
+ from typing import Any, NamedTuple
41
+
42
+ class _VersionInfo(NamedTuple):
43
+ major: int
44
+ minor: int
45
+ micro: int
46
+ releaselevel: str
47
+ serial: int
48
+
49
+ __bibtex__: str
50
+ __version__: str
51
+ __version_info__: _VersionInfo
52
+
53
+ def set_loglevel(level: str) -> None: ...
54
+
55
+ class _ExecInfo(NamedTuple):
56
+ executable: str
57
+ raw_version: str
58
+ version: Version
59
+
60
+ class ExecutableNotFoundError(FileNotFoundError): ...
61
+
62
+ def _get_executable_info(name: str) -> _ExecInfo: ...
63
+ def get_configdir() -> str: ...
64
+ def get_cachedir() -> str: ...
65
+ def get_data_path() -> str: ...
66
+ def matplotlib_fname() -> str: ...
67
+
68
+ class RcParams(dict[str, Any]):
69
+ validate: dict[str, Callable]
70
+ def __init__(self, *args, **kwargs) -> None: ...
71
+ def _set(self, key: str, val: Any) -> None: ...
72
+ def _get(self, key: str) -> Any: ...
73
+ def __setitem__(self, key: str, val: Any) -> None: ...
74
+ def __getitem__(self, key: str) -> Any: ...
75
+ def __iter__(self) -> Generator[str, None, None]: ...
76
+ def __len__(self) -> int: ...
77
+ def find_all(self, pattern: str) -> RcParams: ...
78
+ def copy(self) -> RcParams: ...
79
+
80
+ def rc_params(fail_on_error: bool = ...) -> RcParams: ...
81
+ def rc_params_from_file(
82
+ fname: str | Path | os.PathLike,
83
+ fail_on_error: bool = ...,
84
+ use_default_template: bool = ...,
85
+ ) -> RcParams: ...
86
+
87
+ rcParamsDefault: RcParams
88
+ rcParams: RcParams
89
+ rcParamsOrig: RcParams
90
+ defaultParams: dict[str, Any]
91
+
92
+ def rc(group: str, **kwargs) -> None: ...
93
+ def rcdefaults() -> None: ...
94
+ def rc_file_defaults() -> None: ...
95
+ def rc_file(
96
+ fname: str | Path | os.PathLike, *, use_default_template: bool = ...
97
+ ) -> None: ...
98
+ @contextlib.contextmanager
99
+ def rc_context(
100
+ rc: dict[str, Any] | None = ..., fname: str | Path | os.PathLike | None = ...
101
+ ) -> Generator[None, None, None]: ...
102
+ def use(backend: str, *, force: bool = ...) -> None: ...
103
+ def get_backend() -> str: ...
104
+ def interactive(b: bool) -> None: ...
105
+ def is_interactive() -> bool: ...
106
+
107
+ def _preprocess_data(
108
+ func: Callable | None = ...,
109
+ *,
110
+ replace_names: list[str] | None = ...,
111
+ label_namer: str | None = ...
112
+ ) -> Callable: ...
113
+
114
+ from matplotlib.cm import _colormaps as colormaps
115
+ from matplotlib.colors import _color_sequences as color_sequences
llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.py ADDED
@@ -0,0 +1,381 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper functions for managing the Matplotlib API.
3
+
4
+ This documentation is only relevant for Matplotlib developers, not for users.
5
+
6
+ .. warning::
7
+
8
+ This module and its submodules are for internal use only. Do not use them
9
+ in your own code. We may change the API at any time with no warning.
10
+
11
+ """
12
+
13
+ import functools
14
+ import itertools
15
+ import re
16
+ import sys
17
+ import warnings
18
+
19
+ from .deprecation import ( # noqa: F401
20
+ deprecated, warn_deprecated,
21
+ rename_parameter, delete_parameter, make_keyword_only,
22
+ deprecate_method_override, deprecate_privatize_attribute,
23
+ suppress_matplotlib_deprecation_warning,
24
+ MatplotlibDeprecationWarning)
25
+
26
+
27
+ class classproperty:
28
+ """
29
+ Like `property`, but also triggers on access via the class, and it is the
30
+ *class* that's passed as argument.
31
+
32
+ Examples
33
+ --------
34
+ ::
35
+
36
+ class C:
37
+ @classproperty
38
+ def foo(cls):
39
+ return cls.__name__
40
+
41
+ assert C.foo == "C"
42
+ """
43
+
44
+ def __init__(self, fget, fset=None, fdel=None, doc=None):
45
+ self._fget = fget
46
+ if fset is not None or fdel is not None:
47
+ raise ValueError('classproperty only implements fget.')
48
+ self.fset = fset
49
+ self.fdel = fdel
50
+ # docs are ignored for now
51
+ self._doc = doc
52
+
53
+ def __get__(self, instance, owner):
54
+ return self._fget(owner)
55
+
56
+ @property
57
+ def fget(self):
58
+ return self._fget
59
+
60
+
61
+ # In the following check_foo() functions, the first parameter is positional-only to make
62
+ # e.g. `_api.check_isinstance([...], types=foo)` work.
63
+
64
+ def check_isinstance(types, /, **kwargs):
65
+ """
66
+ For each *key, value* pair in *kwargs*, check that *value* is an instance
67
+ of one of *types*; if not, raise an appropriate TypeError.
68
+
69
+ As a special case, a ``None`` entry in *types* is treated as NoneType.
70
+
71
+ Examples
72
+ --------
73
+ >>> _api.check_isinstance((SomeClass, None), arg=arg)
74
+ """
75
+ none_type = type(None)
76
+ types = ((types,) if isinstance(types, type) else
77
+ (none_type,) if types is None else
78
+ tuple(none_type if tp is None else tp for tp in types))
79
+
80
+ def type_name(tp):
81
+ return ("None" if tp is none_type
82
+ else tp.__qualname__ if tp.__module__ == "builtins"
83
+ else f"{tp.__module__}.{tp.__qualname__}")
84
+
85
+ for k, v in kwargs.items():
86
+ if not isinstance(v, types):
87
+ names = [*map(type_name, types)]
88
+ if "None" in names: # Move it to the end for better wording.
89
+ names.remove("None")
90
+ names.append("None")
91
+ raise TypeError(
92
+ "{!r} must be an instance of {}, not a {}".format(
93
+ k,
94
+ ", ".join(names[:-1]) + " or " + names[-1]
95
+ if len(names) > 1 else names[0],
96
+ type_name(type(v))))
97
+
98
+
99
+ def check_in_list(values, /, *, _print_supported_values=True, **kwargs):
100
+ """
101
+ For each *key, value* pair in *kwargs*, check that *value* is in *values*;
102
+ if not, raise an appropriate ValueError.
103
+
104
+ Parameters
105
+ ----------
106
+ values : iterable
107
+ Sequence of values to check on.
108
+ _print_supported_values : bool, default: True
109
+ Whether to print *values* when raising ValueError.
110
+ **kwargs : dict
111
+ *key, value* pairs as keyword arguments to find in *values*.
112
+
113
+ Raises
114
+ ------
115
+ ValueError
116
+ If any *value* in *kwargs* is not found in *values*.
117
+
118
+ Examples
119
+ --------
120
+ >>> _api.check_in_list(["foo", "bar"], arg=arg, other_arg=other_arg)
121
+ """
122
+ if not kwargs:
123
+ raise TypeError("No argument to check!")
124
+ for key, val in kwargs.items():
125
+ if val not in values:
126
+ msg = f"{val!r} is not a valid value for {key}"
127
+ if _print_supported_values:
128
+ msg += f"; supported values are {', '.join(map(repr, values))}"
129
+ raise ValueError(msg)
130
+
131
+
132
+ def check_shape(shape, /, **kwargs):
133
+ """
134
+ For each *key, value* pair in *kwargs*, check that *value* has the shape *shape*;
135
+ if not, raise an appropriate ValueError.
136
+
137
+ *None* in the shape is treated as a "free" size that can have any length.
138
+ e.g. (None, 2) -> (N, 2)
139
+
140
+ The values checked must be numpy arrays.
141
+
142
+ Examples
143
+ --------
144
+ To check for (N, 2) shaped arrays
145
+
146
+ >>> _api.check_shape((None, 2), arg=arg, other_arg=other_arg)
147
+ """
148
+ for k, v in kwargs.items():
149
+ data_shape = v.shape
150
+
151
+ if (len(data_shape) != len(shape)
152
+ or any(s != t and t is not None for s, t in zip(data_shape, shape))):
153
+ dim_labels = iter(itertools.chain(
154
+ 'NMLKJIH',
155
+ (f"D{i}" for i in itertools.count())))
156
+ text_shape = ", ".join([str(n) if n is not None else next(dim_labels)
157
+ for n in shape[::-1]][::-1])
158
+ if len(shape) == 1:
159
+ text_shape += ","
160
+
161
+ raise ValueError(
162
+ f"{k!r} must be {len(shape)}D with shape ({text_shape}), "
163
+ f"but your input has shape {v.shape}"
164
+ )
165
+
166
+
167
+ def check_getitem(mapping, /, **kwargs):
168
+ """
169
+ *kwargs* must consist of a single *key, value* pair. If *key* is in
170
+ *mapping*, return ``mapping[value]``; else, raise an appropriate
171
+ ValueError.
172
+
173
+ Examples
174
+ --------
175
+ >>> _api.check_getitem({"foo": "bar"}, arg=arg)
176
+ """
177
+ if len(kwargs) != 1:
178
+ raise ValueError("check_getitem takes a single keyword argument")
179
+ (k, v), = kwargs.items()
180
+ try:
181
+ return mapping[v]
182
+ except KeyError:
183
+ raise ValueError(
184
+ f"{v!r} is not a valid value for {k}; supported values are "
185
+ f"{', '.join(map(repr, mapping))}") from None
186
+
187
+
188
+ def caching_module_getattr(cls):
189
+ """
190
+ Helper decorator for implementing module-level ``__getattr__`` as a class.
191
+
192
+ This decorator must be used at the module toplevel as follows::
193
+
194
+ @caching_module_getattr
195
+ class __getattr__: # The class *must* be named ``__getattr__``.
196
+ @property # Only properties are taken into account.
197
+ def name(self): ...
198
+
199
+ The ``__getattr__`` class will be replaced by a ``__getattr__``
200
+ function such that trying to access ``name`` on the module will
201
+ resolve the corresponding property (which may be decorated e.g. with
202
+ ``_api.deprecated`` for deprecating module globals). The properties are
203
+ all implicitly cached. Moreover, a suitable AttributeError is generated
204
+ and raised if no property with the given name exists.
205
+ """
206
+
207
+ assert cls.__name__ == "__getattr__"
208
+ # Don't accidentally export cls dunders.
209
+ props = {name: prop for name, prop in vars(cls).items()
210
+ if isinstance(prop, property)}
211
+ instance = cls()
212
+
213
+ @functools.cache
214
+ def __getattr__(name):
215
+ if name in props:
216
+ return props[name].__get__(instance)
217
+ raise AttributeError(
218
+ f"module {cls.__module__!r} has no attribute {name!r}")
219
+
220
+ return __getattr__
221
+
222
+
223
+ def define_aliases(alias_d, cls=None):
224
+ """
225
+ Class decorator for defining property aliases.
226
+
227
+ Use as ::
228
+
229
+ @_api.define_aliases({"property": ["alias", ...], ...})
230
+ class C: ...
231
+
232
+ For each property, if the corresponding ``get_property`` is defined in the
233
+ class so far, an alias named ``get_alias`` will be defined; the same will
234
+ be done for setters. If neither the getter nor the setter exists, an
235
+ exception will be raised.
236
+
237
+ The alias map is stored as the ``_alias_map`` attribute on the class and
238
+ can be used by `.normalize_kwargs` (which assumes that higher priority
239
+ aliases come last).
240
+ """
241
+ if cls is None: # Return the actual class decorator.
242
+ return functools.partial(define_aliases, alias_d)
243
+
244
+ def make_alias(name): # Enforce a closure over *name*.
245
+ @functools.wraps(getattr(cls, name))
246
+ def method(self, *args, **kwargs):
247
+ return getattr(self, name)(*args, **kwargs)
248
+ return method
249
+
250
+ for prop, aliases in alias_d.items():
251
+ exists = False
252
+ for prefix in ["get_", "set_"]:
253
+ if prefix + prop in vars(cls):
254
+ exists = True
255
+ for alias in aliases:
256
+ method = make_alias(prefix + prop)
257
+ method.__name__ = prefix + alias
258
+ method.__doc__ = f"Alias for `{prefix + prop}`."
259
+ setattr(cls, prefix + alias, method)
260
+ if not exists:
261
+ raise ValueError(
262
+ f"Neither getter nor setter exists for {prop!r}")
263
+
264
+ def get_aliased_and_aliases(d):
265
+ return {*d, *(alias for aliases in d.values() for alias in aliases)}
266
+
267
+ preexisting_aliases = getattr(cls, "_alias_map", {})
268
+ conflicting = (get_aliased_and_aliases(preexisting_aliases)
269
+ & get_aliased_and_aliases(alias_d))
270
+ if conflicting:
271
+ # Need to decide on conflict resolution policy.
272
+ raise NotImplementedError(
273
+ f"Parent class already defines conflicting aliases: {conflicting}")
274
+ cls._alias_map = {**preexisting_aliases, **alias_d}
275
+ return cls
276
+
277
+
278
+ def select_matching_signature(funcs, *args, **kwargs):
279
+ """
280
+ Select and call the function that accepts ``*args, **kwargs``.
281
+
282
+ *funcs* is a list of functions which should not raise any exception (other
283
+ than `TypeError` if the arguments passed do not match their signature).
284
+
285
+ `select_matching_signature` tries to call each of the functions in *funcs*
286
+ with ``*args, **kwargs`` (in the order in which they are given). Calls
287
+ that fail with a `TypeError` are silently skipped. As soon as a call
288
+ succeeds, `select_matching_signature` returns its return value. If no
289
+ function accepts ``*args, **kwargs``, then the `TypeError` raised by the
290
+ last failing call is re-raised.
291
+
292
+ Callers should normally make sure that any ``*args, **kwargs`` can only
293
+ bind a single *func* (to avoid any ambiguity), although this is not checked
294
+ by `select_matching_signature`.
295
+
296
+ Notes
297
+ -----
298
+ `select_matching_signature` is intended to help implementing
299
+ signature-overloaded functions. In general, such functions should be
300
+ avoided, except for back-compatibility concerns. A typical use pattern is
301
+ ::
302
+
303
+ def my_func(*args, **kwargs):
304
+ params = select_matching_signature(
305
+ [lambda old1, old2: locals(), lambda new: locals()],
306
+ *args, **kwargs)
307
+ if "old1" in params:
308
+ warn_deprecated(...)
309
+ old1, old2 = params.values() # note that locals() is ordered.
310
+ else:
311
+ new, = params.values()
312
+ # do things with params
313
+
314
+ which allows *my_func* to be called either with two parameters (*old1* and
315
+ *old2*) or a single one (*new*). Note that the new signature is given
316
+ last, so that callers get a `TypeError` corresponding to the new signature
317
+ if the arguments they passed in do not match any signature.
318
+ """
319
+ # Rather than relying on locals() ordering, one could have just used func's
320
+ # signature (``bound = inspect.signature(func).bind(*args, **kwargs);
321
+ # bound.apply_defaults(); return bound``) but that is significantly slower.
322
+ for i, func in enumerate(funcs):
323
+ try:
324
+ return func(*args, **kwargs)
325
+ except TypeError:
326
+ if i == len(funcs) - 1:
327
+ raise
328
+
329
+
330
+ def nargs_error(name, takes, given):
331
+ """Generate a TypeError to be raised by function calls with wrong arity."""
332
+ return TypeError(f"{name}() takes {takes} positional arguments but "
333
+ f"{given} were given")
334
+
335
+
336
+ def kwarg_error(name, kw):
337
+ """
338
+ Generate a TypeError to be raised by function calls with wrong kwarg.
339
+
340
+ Parameters
341
+ ----------
342
+ name : str
343
+ The name of the calling function.
344
+ kw : str or Iterable[str]
345
+ Either the invalid keyword argument name, or an iterable yielding
346
+ invalid keyword arguments (e.g., a ``kwargs`` dict).
347
+ """
348
+ if not isinstance(kw, str):
349
+ kw = next(iter(kw))
350
+ return TypeError(f"{name}() got an unexpected keyword argument '{kw}'")
351
+
352
+
353
+ def recursive_subclasses(cls):
354
+ """Yield *cls* and direct and indirect subclasses of *cls*."""
355
+ yield cls
356
+ for subcls in cls.__subclasses__():
357
+ yield from recursive_subclasses(subcls)
358
+
359
+
360
+ def warn_external(message, category=None):
361
+ """
362
+ `warnings.warn` wrapper that sets *stacklevel* to "outside Matplotlib".
363
+
364
+ The original emitter of the warning can be obtained by patching this
365
+ function back to `warnings.warn`, i.e. ``_api.warn_external =
366
+ warnings.warn`` (or ``functools.partial(warnings.warn, stacklevel=2)``,
367
+ etc.).
368
+ """
369
+ frame = sys._getframe()
370
+ for stacklevel in itertools.count(1):
371
+ if frame is None:
372
+ # when called in embedded context may hit frame is None
373
+ break
374
+ if not re.match(r"\A(matplotlib|mpl_toolkits)(\Z|\.(?!tests\.))",
375
+ # Work around sphinx-gallery not setting __name__.
376
+ frame.f_globals.get("__name__", "")):
377
+ break
378
+ frame = frame.f_back
379
+ # preemptively break reference cycle between locals and the frame
380
+ del frame
381
+ warnings.warn(message, category, stacklevel)
llava_next/lib/python3.10/site-packages/matplotlib/_api/__init__.pyi ADDED
@@ -0,0 +1,59 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Generator, Mapping, Sequence
2
+ from typing import Any, Iterable, TypeVar, overload
3
+
4
+ from numpy.typing import NDArray
5
+
6
+ from .deprecation import ( # noqa: re-exported API
7
+ deprecated as deprecated,
8
+ warn_deprecated as warn_deprecated,
9
+ rename_parameter as rename_parameter,
10
+ delete_parameter as delete_parameter,
11
+ make_keyword_only as make_keyword_only,
12
+ deprecate_method_override as deprecate_method_override,
13
+ deprecate_privatize_attribute as deprecate_privatize_attribute,
14
+ suppress_matplotlib_deprecation_warning as suppress_matplotlib_deprecation_warning,
15
+ MatplotlibDeprecationWarning as MatplotlibDeprecationWarning,
16
+ )
17
+
18
+ _T = TypeVar("_T")
19
+
20
+ class classproperty(Any):
21
+ def __init__(
22
+ self,
23
+ fget: Callable[[_T], Any],
24
+ fset: None = ...,
25
+ fdel: None = ...,
26
+ doc: str | None = None,
27
+ ): ...
28
+ # Replace return with Self when py3.9 is dropped
29
+ @overload
30
+ def __get__(self, instance: None, owner: None) -> classproperty: ...
31
+ @overload
32
+ def __get__(self, instance: object, owner: type[object]) -> Any: ...
33
+ @property
34
+ def fget(self) -> Callable[[_T], Any]: ...
35
+
36
+ def check_isinstance(
37
+ types: type | tuple[type | None, ...], /, **kwargs: Any
38
+ ) -> None: ...
39
+ def check_in_list(
40
+ values: Sequence[Any], /, *, _print_supported_values: bool = ..., **kwargs: Any
41
+ ) -> None: ...
42
+ def check_shape(shape: tuple[int | None, ...], /, **kwargs: NDArray) -> None: ...
43
+ def check_getitem(mapping: Mapping[Any, Any], /, **kwargs: Any) -> Any: ...
44
+ def caching_module_getattr(cls: type) -> Callable[[str], Any]: ...
45
+ @overload
46
+ def define_aliases(
47
+ alias_d: dict[str, list[str]], cls: None = ...
48
+ ) -> Callable[[type[_T]], type[_T]]: ...
49
+ @overload
50
+ def define_aliases(alias_d: dict[str, list[str]], cls: type[_T]) -> type[_T]: ...
51
+ def select_matching_signature(
52
+ funcs: list[Callable], *args: Any, **kwargs: Any
53
+ ) -> Any: ...
54
+ def nargs_error(name: str, takes: int | str, given: int) -> TypeError: ...
55
+ def kwarg_error(name: str, kw: str | Iterable[str]) -> TypeError: ...
56
+ def recursive_subclasses(cls: type) -> Generator[type, None, None]: ...
57
+ def warn_external(
58
+ message: str | Warning, category: type[Warning] | None = ...
59
+ ) -> None: ...
llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (13.5 kB). View file
 
llava_next/lib/python3.10/site-packages/matplotlib/_api/__pycache__/deprecation.cpython-310.pyc ADDED
Binary file (17.7 kB). View file
 
llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.py ADDED
@@ -0,0 +1,513 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper functions for deprecating parts of the Matplotlib API.
3
+
4
+ This documentation is only relevant for Matplotlib developers, not for users.
5
+
6
+ .. warning::
7
+
8
+ This module is for internal use only. Do not use it in your own code.
9
+ We may change the API at any time with no warning.
10
+
11
+ """
12
+
13
+ import contextlib
14
+ import functools
15
+ import inspect
16
+ import math
17
+ import warnings
18
+
19
+
20
+ class MatplotlibDeprecationWarning(DeprecationWarning):
21
+ """A class for issuing deprecation warnings for Matplotlib users."""
22
+
23
+
24
+ def _generate_deprecation_warning(
25
+ since, message='', name='', alternative='', pending=False, obj_type='',
26
+ addendum='', *, removal=''):
27
+ if pending:
28
+ if removal:
29
+ raise ValueError(
30
+ "A pending deprecation cannot have a scheduled removal")
31
+ else:
32
+ if not removal:
33
+ macro, meso, *_ = since.split('.')
34
+ removal = f'{macro}.{int(meso) + 2}'
35
+ removal = f"in {removal}"
36
+ if not message:
37
+ message = (
38
+ ("The %(name)s %(obj_type)s" if obj_type else "%(name)s")
39
+ + (" will be deprecated in a future version"
40
+ if pending else
41
+ " was deprecated in Matplotlib %(since)s and will be removed %(removal)s"
42
+ )
43
+ + "."
44
+ + (" Use %(alternative)s instead." if alternative else "")
45
+ + (" %(addendum)s" if addendum else ""))
46
+ warning_cls = (PendingDeprecationWarning if pending
47
+ else MatplotlibDeprecationWarning)
48
+ return warning_cls(message % dict(
49
+ func=name, name=name, obj_type=obj_type, since=since, removal=removal,
50
+ alternative=alternative, addendum=addendum))
51
+
52
+
53
+ def warn_deprecated(
54
+ since, *, message='', name='', alternative='', pending=False,
55
+ obj_type='', addendum='', removal=''):
56
+ """
57
+ Display a standardized deprecation.
58
+
59
+ Parameters
60
+ ----------
61
+ since : str
62
+ The release at which this API became deprecated.
63
+ message : str, optional
64
+ Override the default deprecation message. The ``%(since)s``,
65
+ ``%(name)s``, ``%(alternative)s``, ``%(obj_type)s``, ``%(addendum)s``,
66
+ and ``%(removal)s`` format specifiers will be replaced by the values
67
+ of the respective arguments passed to this function.
68
+ name : str, optional
69
+ The name of the deprecated object.
70
+ alternative : str, optional
71
+ An alternative API that the user may use in place of the deprecated
72
+ API. The deprecation warning will tell the user about this alternative
73
+ if provided.
74
+ pending : bool, optional
75
+ If True, uses a PendingDeprecationWarning instead of a
76
+ DeprecationWarning. Cannot be used together with *removal*.
77
+ obj_type : str, optional
78
+ The object type being deprecated.
79
+ addendum : str, optional
80
+ Additional text appended directly to the final message.
81
+ removal : str, optional
82
+ The expected removal version. With the default (an empty string), a
83
+ removal version is automatically computed from *since*. Set to other
84
+ Falsy values to not schedule a removal date. Cannot be used together
85
+ with *pending*.
86
+
87
+ Examples
88
+ --------
89
+ ::
90
+
91
+ # To warn of the deprecation of "matplotlib.name_of_module"
92
+ warn_deprecated('1.4.0', name='matplotlib.name_of_module',
93
+ obj_type='module')
94
+ """
95
+ warning = _generate_deprecation_warning(
96
+ since, message, name, alternative, pending, obj_type, addendum,
97
+ removal=removal)
98
+ from . import warn_external
99
+ warn_external(warning, category=MatplotlibDeprecationWarning)
100
+
101
+
102
+ def deprecated(since, *, message='', name='', alternative='', pending=False,
103
+ obj_type=None, addendum='', removal=''):
104
+ """
105
+ Decorator to mark a function, a class, or a property as deprecated.
106
+
107
+ When deprecating a classmethod, a staticmethod, or a property, the
108
+ ``@deprecated`` decorator should go *under* ``@classmethod`` and
109
+ ``@staticmethod`` (i.e., `deprecated` should directly decorate the
110
+ underlying callable), but *over* ``@property``.
111
+
112
+ When deprecating a class ``C`` intended to be used as a base class in a
113
+ multiple inheritance hierarchy, ``C`` *must* define an ``__init__`` method
114
+ (if ``C`` instead inherited its ``__init__`` from its own base class, then
115
+ ``@deprecated`` would mess up ``__init__`` inheritance when installing its
116
+ own (deprecation-emitting) ``C.__init__``).
117
+
118
+ Parameters are the same as for `warn_deprecated`, except that *obj_type*
119
+ defaults to 'class' if decorating a class, 'attribute' if decorating a
120
+ property, and 'function' otherwise.
121
+
122
+ Examples
123
+ --------
124
+ ::
125
+
126
+ @deprecated('1.4.0')
127
+ def the_function_to_deprecate():
128
+ pass
129
+ """
130
+
131
+ def deprecate(obj, message=message, name=name, alternative=alternative,
132
+ pending=pending, obj_type=obj_type, addendum=addendum):
133
+ from matplotlib._api import classproperty
134
+
135
+ if isinstance(obj, type):
136
+ if obj_type is None:
137
+ obj_type = "class"
138
+ func = obj.__init__
139
+ name = name or obj.__name__
140
+ old_doc = obj.__doc__
141
+
142
+ def finalize(wrapper, new_doc):
143
+ try:
144
+ obj.__doc__ = new_doc
145
+ except AttributeError: # Can't set on some extension objects.
146
+ pass
147
+ obj.__init__ = functools.wraps(obj.__init__)(wrapper)
148
+ return obj
149
+
150
+ elif isinstance(obj, (property, classproperty)):
151
+ if obj_type is None:
152
+ obj_type = "attribute"
153
+ func = None
154
+ name = name or obj.fget.__name__
155
+ old_doc = obj.__doc__
156
+
157
+ class _deprecated_property(type(obj)):
158
+ def __get__(self, instance, owner=None):
159
+ if instance is not None or owner is not None \
160
+ and isinstance(self, classproperty):
161
+ emit_warning()
162
+ return super().__get__(instance, owner)
163
+
164
+ def __set__(self, instance, value):
165
+ if instance is not None:
166
+ emit_warning()
167
+ return super().__set__(instance, value)
168
+
169
+ def __delete__(self, instance):
170
+ if instance is not None:
171
+ emit_warning()
172
+ return super().__delete__(instance)
173
+
174
+ def __set_name__(self, owner, set_name):
175
+ nonlocal name
176
+ if name == "<lambda>":
177
+ name = set_name
178
+
179
+ def finalize(_, new_doc):
180
+ return _deprecated_property(
181
+ fget=obj.fget, fset=obj.fset, fdel=obj.fdel, doc=new_doc)
182
+
183
+ else:
184
+ if obj_type is None:
185
+ obj_type = "function"
186
+ func = obj
187
+ name = name or obj.__name__
188
+ old_doc = func.__doc__
189
+
190
+ def finalize(wrapper, new_doc):
191
+ wrapper = functools.wraps(func)(wrapper)
192
+ wrapper.__doc__ = new_doc
193
+ return wrapper
194
+
195
+ def emit_warning():
196
+ warn_deprecated(
197
+ since, message=message, name=name, alternative=alternative,
198
+ pending=pending, obj_type=obj_type, addendum=addendum,
199
+ removal=removal)
200
+
201
+ def wrapper(*args, **kwargs):
202
+ emit_warning()
203
+ return func(*args, **kwargs)
204
+
205
+ old_doc = inspect.cleandoc(old_doc or '').strip('\n')
206
+
207
+ notes_header = '\nNotes\n-----'
208
+ second_arg = ' '.join([t.strip() for t in
209
+ (message, f"Use {alternative} instead."
210
+ if alternative else "", addendum) if t])
211
+ new_doc = (f"[*Deprecated*] {old_doc}\n"
212
+ f"{notes_header if notes_header not in old_doc else ''}\n"
213
+ f".. deprecated:: {since}\n"
214
+ f" {second_arg}")
215
+
216
+ if not old_doc:
217
+ # This is to prevent a spurious 'unexpected unindent' warning from
218
+ # docutils when the original docstring was blank.
219
+ new_doc += r'\ '
220
+
221
+ return finalize(wrapper, new_doc)
222
+
223
+ return deprecate
224
+
225
+
226
+ class deprecate_privatize_attribute:
227
+ """
228
+ Helper to deprecate public access to an attribute (or method).
229
+
230
+ This helper should only be used at class scope, as follows::
231
+
232
+ class Foo:
233
+ attr = _deprecate_privatize_attribute(*args, **kwargs)
234
+
235
+ where *all* parameters are forwarded to `deprecated`. This form makes
236
+ ``attr`` a property which forwards read and write access to ``self._attr``
237
+ (same name but with a leading underscore), with a deprecation warning.
238
+ Note that the attribute name is derived from *the name this helper is
239
+ assigned to*. This helper also works for deprecating methods.
240
+ """
241
+
242
+ def __init__(self, *args, **kwargs):
243
+ self.deprecator = deprecated(*args, **kwargs)
244
+
245
+ def __set_name__(self, owner, name):
246
+ setattr(owner, name, self.deprecator(
247
+ property(lambda self: getattr(self, f"_{name}"),
248
+ lambda self, value: setattr(self, f"_{name}", value)),
249
+ name=name))
250
+
251
+
252
+ # Used by _copy_docstring_and_deprecators to redecorate pyplot wrappers and
253
+ # boilerplate.py to retrieve original signatures. It may seem natural to store
254
+ # this information as an attribute on the wrapper, but if the wrapper gets
255
+ # itself functools.wraps()ed, then such attributes are silently propagated to
256
+ # the outer wrapper, which is not desired.
257
+ DECORATORS = {}
258
+
259
+
260
+ def rename_parameter(since, old, new, func=None):
261
+ """
262
+ Decorator indicating that parameter *old* of *func* is renamed to *new*.
263
+
264
+ The actual implementation of *func* should use *new*, not *old*. If *old*
265
+ is passed to *func*, a DeprecationWarning is emitted, and its value is
266
+ used, even if *new* is also passed by keyword (this is to simplify pyplot
267
+ wrapper functions, which always pass *new* explicitly to the Axes method).
268
+ If *new* is also passed but positionally, a TypeError will be raised by the
269
+ underlying function during argument binding.
270
+
271
+ Examples
272
+ --------
273
+ ::
274
+
275
+ @_api.rename_parameter("3.1", "bad_name", "good_name")
276
+ def func(good_name): ...
277
+ """
278
+
279
+ decorator = functools.partial(rename_parameter, since, old, new)
280
+
281
+ if func is None:
282
+ return decorator
283
+
284
+ signature = inspect.signature(func)
285
+ assert old not in signature.parameters, (
286
+ f"Matplotlib internal error: {old!r} cannot be a parameter for "
287
+ f"{func.__name__}()")
288
+ assert new in signature.parameters, (
289
+ f"Matplotlib internal error: {new!r} must be a parameter for "
290
+ f"{func.__name__}()")
291
+
292
+ @functools.wraps(func)
293
+ def wrapper(*args, **kwargs):
294
+ if old in kwargs:
295
+ warn_deprecated(
296
+ since, message=f"The {old!r} parameter of {func.__name__}() "
297
+ f"has been renamed {new!r} since Matplotlib {since}; support "
298
+ f"for the old name will be dropped %(removal)s.")
299
+ kwargs[new] = kwargs.pop(old)
300
+ return func(*args, **kwargs)
301
+
302
+ # wrapper() must keep the same documented signature as func(): if we
303
+ # instead made both *old* and *new* appear in wrapper()'s signature, they
304
+ # would both show up in the pyplot function for an Axes method as well and
305
+ # pyplot would explicitly pass both arguments to the Axes method.
306
+
307
+ DECORATORS[wrapper] = decorator
308
+ return wrapper
309
+
310
+
311
+ class _deprecated_parameter_class:
312
+ def __repr__(self):
313
+ return "<deprecated parameter>"
314
+
315
+
316
+ _deprecated_parameter = _deprecated_parameter_class()
317
+
318
+
319
+ def delete_parameter(since, name, func=None, **kwargs):
320
+ """
321
+ Decorator indicating that parameter *name* of *func* is being deprecated.
322
+
323
+ The actual implementation of *func* should keep the *name* parameter in its
324
+ signature, or accept a ``**kwargs`` argument (through which *name* would be
325
+ passed).
326
+
327
+ Parameters that come after the deprecated parameter effectively become
328
+ keyword-only (as they cannot be passed positionally without triggering the
329
+ DeprecationWarning on the deprecated parameter), and should be marked as
330
+ such after the deprecation period has passed and the deprecated parameter
331
+ is removed.
332
+
333
+ Parameters other than *since*, *name*, and *func* are keyword-only and
334
+ forwarded to `.warn_deprecated`.
335
+
336
+ Examples
337
+ --------
338
+ ::
339
+
340
+ @_api.delete_parameter("3.1", "unused")
341
+ def func(used_arg, other_arg, unused, more_args): ...
342
+ """
343
+
344
+ decorator = functools.partial(delete_parameter, since, name, **kwargs)
345
+
346
+ if func is None:
347
+ return decorator
348
+
349
+ signature = inspect.signature(func)
350
+ # Name of `**kwargs` parameter of the decorated function, typically
351
+ # "kwargs" if such a parameter exists, or None if the decorated function
352
+ # doesn't accept `**kwargs`.
353
+ kwargs_name = next((param.name for param in signature.parameters.values()
354
+ if param.kind == inspect.Parameter.VAR_KEYWORD), None)
355
+ if name in signature.parameters:
356
+ kind = signature.parameters[name].kind
357
+ is_varargs = kind is inspect.Parameter.VAR_POSITIONAL
358
+ is_varkwargs = kind is inspect.Parameter.VAR_KEYWORD
359
+ if not is_varargs and not is_varkwargs:
360
+ name_idx = (
361
+ # Deprecated parameter can't be passed positionally.
362
+ math.inf if kind is inspect.Parameter.KEYWORD_ONLY
363
+ # If call site has no more than this number of parameters, the
364
+ # deprecated parameter can't have been passed positionally.
365
+ else [*signature.parameters].index(name))
366
+ func.__signature__ = signature = signature.replace(parameters=[
367
+ param.replace(default=_deprecated_parameter)
368
+ if param.name == name else param
369
+ for param in signature.parameters.values()])
370
+ else:
371
+ name_idx = -1 # Deprecated parameter can always have been passed.
372
+ else:
373
+ is_varargs = is_varkwargs = False
374
+ # Deprecated parameter can't be passed positionally.
375
+ name_idx = math.inf
376
+ assert kwargs_name, (
377
+ f"Matplotlib internal error: {name!r} must be a parameter for "
378
+ f"{func.__name__}()")
379
+
380
+ addendum = kwargs.pop('addendum', None)
381
+
382
+ @functools.wraps(func)
383
+ def wrapper(*inner_args, **inner_kwargs):
384
+ if len(inner_args) <= name_idx and name not in inner_kwargs:
385
+ # Early return in the simple, non-deprecated case (much faster than
386
+ # calling bind()).
387
+ return func(*inner_args, **inner_kwargs)
388
+ arguments = signature.bind(*inner_args, **inner_kwargs).arguments
389
+ if is_varargs and arguments.get(name):
390
+ warn_deprecated(
391
+ since, message=f"Additional positional arguments to "
392
+ f"{func.__name__}() are deprecated since %(since)s and "
393
+ f"support for them will be removed %(removal)s.")
394
+ elif is_varkwargs and arguments.get(name):
395
+ warn_deprecated(
396
+ since, message=f"Additional keyword arguments to "
397
+ f"{func.__name__}() are deprecated since %(since)s and "
398
+ f"support for them will be removed %(removal)s.")
399
+ # We cannot just check `name not in arguments` because the pyplot
400
+ # wrappers always pass all arguments explicitly.
401
+ elif any(name in d and d[name] != _deprecated_parameter
402
+ for d in [arguments, arguments.get(kwargs_name, {})]):
403
+ deprecation_addendum = (
404
+ f"If any parameter follows {name!r}, they should be passed as "
405
+ f"keyword, not positionally.")
406
+ warn_deprecated(
407
+ since,
408
+ name=repr(name),
409
+ obj_type=f"parameter of {func.__name__}()",
410
+ addendum=(addendum + " " + deprecation_addendum) if addendum
411
+ else deprecation_addendum,
412
+ **kwargs)
413
+ return func(*inner_args, **inner_kwargs)
414
+
415
+ DECORATORS[wrapper] = decorator
416
+ return wrapper
417
+
418
+
419
+ def make_keyword_only(since, name, func=None):
420
+ """
421
+ Decorator indicating that passing parameter *name* (or any of the following
422
+ ones) positionally to *func* is being deprecated.
423
+
424
+ When used on a method that has a pyplot wrapper, this should be the
425
+ outermost decorator, so that :file:`boilerplate.py` can access the original
426
+ signature.
427
+ """
428
+
429
+ decorator = functools.partial(make_keyword_only, since, name)
430
+
431
+ if func is None:
432
+ return decorator
433
+
434
+ signature = inspect.signature(func)
435
+ POK = inspect.Parameter.POSITIONAL_OR_KEYWORD
436
+ KWO = inspect.Parameter.KEYWORD_ONLY
437
+ assert (name in signature.parameters
438
+ and signature.parameters[name].kind == POK), (
439
+ f"Matplotlib internal error: {name!r} must be a positional-or-keyword "
440
+ f"parameter for {func.__name__}()")
441
+ names = [*signature.parameters]
442
+ name_idx = names.index(name)
443
+ kwonly = [name for name in names[name_idx:]
444
+ if signature.parameters[name].kind == POK]
445
+
446
+ @functools.wraps(func)
447
+ def wrapper(*args, **kwargs):
448
+ # Don't use signature.bind here, as it would fail when stacked with
449
+ # rename_parameter and an "old" argument name is passed in
450
+ # (signature.bind would fail, but the actual call would succeed).
451
+ if len(args) > name_idx:
452
+ warn_deprecated(
453
+ since, message="Passing the %(name)s %(obj_type)s "
454
+ "positionally is deprecated since Matplotlib %(since)s; the "
455
+ "parameter will become keyword-only %(removal)s.",
456
+ name=name, obj_type=f"parameter of {func.__name__}()")
457
+ return func(*args, **kwargs)
458
+
459
+ # Don't modify *func*'s signature, as boilerplate.py needs it.
460
+ wrapper.__signature__ = signature.replace(parameters=[
461
+ param.replace(kind=KWO) if param.name in kwonly else param
462
+ for param in signature.parameters.values()])
463
+ DECORATORS[wrapper] = decorator
464
+ return wrapper
465
+
466
+
467
+ def deprecate_method_override(method, obj, *, allow_empty=False, **kwargs):
468
+ """
469
+ Return ``obj.method`` with a deprecation if it was overridden, else None.
470
+
471
+ Parameters
472
+ ----------
473
+ method
474
+ An unbound method, i.e. an expression of the form
475
+ ``Class.method_name``. Remember that within the body of a method, one
476
+ can always use ``__class__`` to refer to the class that is currently
477
+ being defined.
478
+ obj
479
+ Either an object of the class where *method* is defined, or a subclass
480
+ of that class.
481
+ allow_empty : bool, default: False
482
+ Whether to allow overrides by "empty" methods without emitting a
483
+ warning.
484
+ **kwargs
485
+ Additional parameters passed to `warn_deprecated` to generate the
486
+ deprecation warning; must at least include the "since" key.
487
+ """
488
+
489
+ def empty(): pass
490
+ def empty_with_docstring(): """doc"""
491
+
492
+ name = method.__name__
493
+ bound_child = getattr(obj, name)
494
+ bound_base = (
495
+ method # If obj is a class, then we need to use unbound methods.
496
+ if isinstance(bound_child, type(empty)) and isinstance(obj, type)
497
+ else method.__get__(obj))
498
+ if (bound_child != bound_base
499
+ and (not allow_empty
500
+ or (getattr(getattr(bound_child, "__code__", None),
501
+ "co_code", None)
502
+ not in [empty.__code__.co_code,
503
+ empty_with_docstring.__code__.co_code]))):
504
+ warn_deprecated(**{"name": name, "obj_type": "method", **kwargs})
505
+ return bound_child
506
+ return None
507
+
508
+
509
+ @contextlib.contextmanager
510
+ def suppress_matplotlib_deprecation_warning():
511
+ with warnings.catch_warnings():
512
+ warnings.simplefilter("ignore", MatplotlibDeprecationWarning)
513
+ yield
llava_next/lib/python3.10/site-packages/matplotlib/_api/deprecation.pyi ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ import contextlib
3
+ from typing import Any, TypedDict, TypeVar, overload
4
+ from typing_extensions import (
5
+ ParamSpec, # < Py 3.10
6
+ Unpack, # < Py 3.11
7
+ )
8
+
9
+ _P = ParamSpec("_P")
10
+ _R = TypeVar("_R")
11
+ _T = TypeVar("_T")
12
+
13
+ class MatplotlibDeprecationWarning(DeprecationWarning): ...
14
+
15
+ class DeprecationKwargs(TypedDict, total=False):
16
+ message: str
17
+ alternative: str
18
+ pending: bool
19
+ obj_type: str
20
+ addendum: str
21
+ removal: str
22
+
23
+ class NamedDeprecationKwargs(DeprecationKwargs, total=False):
24
+ name: str
25
+
26
+ def warn_deprecated(since: str, **kwargs: Unpack[NamedDeprecationKwargs]) -> None: ...
27
+ def deprecated(
28
+ since: str, **kwargs: Unpack[NamedDeprecationKwargs]
29
+ ) -> Callable[[_T], _T]: ...
30
+
31
+ class deprecate_privatize_attribute(Any):
32
+ def __init__(self, since: str, **kwargs: Unpack[NamedDeprecationKwargs]): ...
33
+ def __set_name__(self, owner: type[object], name: str) -> None: ...
34
+
35
+ DECORATORS: dict[Callable, Callable] = ...
36
+
37
+ @overload
38
+ def rename_parameter(
39
+ since: str, old: str, new: str, func: None = ...
40
+ ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
41
+ @overload
42
+ def rename_parameter(
43
+ since: str, old: str, new: str, func: Callable[_P, _R]
44
+ ) -> Callable[_P, _R]: ...
45
+
46
+ class _deprecated_parameter_class: ...
47
+
48
+ _deprecated_parameter: _deprecated_parameter_class
49
+
50
+ @overload
51
+ def delete_parameter(
52
+ since: str, name: str, func: None = ..., **kwargs: Unpack[DeprecationKwargs]
53
+ ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
54
+ @overload
55
+ def delete_parameter(
56
+ since: str, name: str, func: Callable[_P, _R], **kwargs: Unpack[DeprecationKwargs]
57
+ ) -> Callable[_P, _R]: ...
58
+ @overload
59
+ def make_keyword_only(
60
+ since: str, name: str, func: None = ...
61
+ ) -> Callable[[Callable[_P, _R]], Callable[_P, _R]]: ...
62
+ @overload
63
+ def make_keyword_only(
64
+ since: str, name: str, func: Callable[_P, _R]
65
+ ) -> Callable[_P, _R]: ...
66
+ def deprecate_method_override(
67
+ method: Callable[_P, _R],
68
+ obj: object | type,
69
+ *,
70
+ allow_empty: bool = ...,
71
+ since: str,
72
+ **kwargs: Unpack[NamedDeprecationKwargs]
73
+ ) -> Callable[_P, _R]: ...
74
+ def suppress_matplotlib_deprecation_warning() -> (
75
+ contextlib.AbstractContextManager[None]
76
+ ): ...
llava_next/lib/python3.10/site-packages/matplotlib/_blocking_input.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ def blocking_input_loop(figure, event_names, timeout, handler):
2
+ """
3
+ Run *figure*'s event loop while listening to interactive events.
4
+
5
+ The events listed in *event_names* are passed to *handler*.
6
+
7
+ This function is used to implement `.Figure.waitforbuttonpress`,
8
+ `.Figure.ginput`, and `.Axes.clabel`.
9
+
10
+ Parameters
11
+ ----------
12
+ figure : `~matplotlib.figure.Figure`
13
+ event_names : list of str
14
+ The names of the events passed to *handler*.
15
+ timeout : float
16
+ If positive, the event loop is stopped after *timeout* seconds.
17
+ handler : Callable[[Event], Any]
18
+ Function called for each event; it can force an early exit of the event
19
+ loop by calling ``canvas.stop_event_loop()``.
20
+ """
21
+ if figure.canvas.manager:
22
+ figure.show() # Ensure that the figure is shown if we are managing it.
23
+ # Connect the events to the on_event function call.
24
+ cids = [figure.canvas.mpl_connect(name, handler) for name in event_names]
25
+ try:
26
+ figure.canvas.start_event_loop(timeout) # Start event loop.
27
+ finally: # Run even on exception like ctrl-c.
28
+ # Disconnect the callbacks.
29
+ for cid in cids:
30
+ figure.canvas.mpl_disconnect(cid)
llava_next/lib/python3.10/site-packages/matplotlib/_cm.py ADDED
@@ -0,0 +1,1446 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Nothing here but dictionaries for generating LinearSegmentedColormaps,
3
+ and a dictionary of these dictionaries.
4
+
5
+ Documentation for each is in pyplot.colormaps(). Please update this
6
+ with the purpose and type of your colormap if you add data for one here.
7
+ """
8
+
9
+ from functools import partial
10
+
11
+ import numpy as np
12
+
13
+ _binary_data = {
14
+ 'red': ((0., 1., 1.), (1., 0., 0.)),
15
+ 'green': ((0., 1., 1.), (1., 0., 0.)),
16
+ 'blue': ((0., 1., 1.), (1., 0., 0.))
17
+ }
18
+
19
+ _autumn_data = {'red': ((0., 1.0, 1.0), (1.0, 1.0, 1.0)),
20
+ 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
21
+ 'blue': ((0., 0., 0.), (1.0, 0., 0.))}
22
+
23
+ _bone_data = {'red': ((0., 0., 0.),
24
+ (0.746032, 0.652778, 0.652778),
25
+ (1.0, 1.0, 1.0)),
26
+ 'green': ((0., 0., 0.),
27
+ (0.365079, 0.319444, 0.319444),
28
+ (0.746032, 0.777778, 0.777778),
29
+ (1.0, 1.0, 1.0)),
30
+ 'blue': ((0., 0., 0.),
31
+ (0.365079, 0.444444, 0.444444),
32
+ (1.0, 1.0, 1.0))}
33
+
34
+ _cool_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),
35
+ 'green': ((0., 1., 1.), (1.0, 0., 0.)),
36
+ 'blue': ((0., 1., 1.), (1.0, 1., 1.))}
37
+
38
+ _copper_data = {'red': ((0., 0., 0.),
39
+ (0.809524, 1.000000, 1.000000),
40
+ (1.0, 1.0, 1.0)),
41
+ 'green': ((0., 0., 0.),
42
+ (1.0, 0.7812, 0.7812)),
43
+ 'blue': ((0., 0., 0.),
44
+ (1.0, 0.4975, 0.4975))}
45
+
46
+ def _flag_red(x): return 0.75 * np.sin((x * 31.5 + 0.25) * np.pi) + 0.5
47
+ def _flag_green(x): return np.sin(x * 31.5 * np.pi)
48
+ def _flag_blue(x): return 0.75 * np.sin((x * 31.5 - 0.25) * np.pi) + 0.5
49
+ _flag_data = {'red': _flag_red, 'green': _flag_green, 'blue': _flag_blue}
50
+
51
+ def _prism_red(x): return 0.75 * np.sin((x * 20.9 + 0.25) * np.pi) + 0.67
52
+ def _prism_green(x): return 0.75 * np.sin((x * 20.9 - 0.25) * np.pi) + 0.33
53
+ def _prism_blue(x): return -1.1 * np.sin((x * 20.9) * np.pi)
54
+ _prism_data = {'red': _prism_red, 'green': _prism_green, 'blue': _prism_blue}
55
+
56
+ def _ch_helper(gamma, s, r, h, p0, p1, x):
57
+ """Helper function for generating picklable cubehelix colormaps."""
58
+ # Apply gamma factor to emphasise low or high intensity values
59
+ xg = x ** gamma
60
+ # Calculate amplitude and angle of deviation from the black to white
61
+ # diagonal in the plane of constant perceived intensity.
62
+ a = h * xg * (1 - xg) / 2
63
+ phi = 2 * np.pi * (s / 3 + r * x)
64
+ return xg + a * (p0 * np.cos(phi) + p1 * np.sin(phi))
65
+
66
+ def cubehelix(gamma=1.0, s=0.5, r=-1.5, h=1.0):
67
+ """
68
+ Return custom data dictionary of (r, g, b) conversion functions, which can
69
+ be used with `.ColormapRegistry.register`, for the cubehelix color scheme.
70
+
71
+ Unlike most other color schemes cubehelix was designed by D.A. Green to
72
+ be monotonically increasing in terms of perceived brightness.
73
+ Also, when printed on a black and white postscript printer, the scheme
74
+ results in a greyscale with monotonically increasing brightness.
75
+ This color scheme is named cubehelix because the (r, g, b) values produced
76
+ can be visualised as a squashed helix around the diagonal in the
77
+ (r, g, b) color cube.
78
+
79
+ For a unit color cube (i.e. 3D coordinates for (r, g, b) each in the
80
+ range 0 to 1) the color scheme starts at (r, g, b) = (0, 0, 0), i.e. black,
81
+ and finishes at (r, g, b) = (1, 1, 1), i.e. white. For some fraction *x*,
82
+ between 0 and 1, the color is the corresponding grey value at that
83
+ fraction along the black to white diagonal (x, x, x) plus a color
84
+ element. This color element is calculated in a plane of constant
85
+ perceived intensity and controlled by the following parameters.
86
+
87
+ Parameters
88
+ ----------
89
+ gamma : float, default: 1
90
+ Gamma factor emphasizing either low intensity values (gamma < 1), or
91
+ high intensity values (gamma > 1).
92
+ s : float, default: 0.5 (purple)
93
+ The starting color.
94
+ r : float, default: -1.5
95
+ The number of r, g, b rotations in color that are made from the start
96
+ to the end of the color scheme. The default of -1.5 corresponds to ->
97
+ B -> G -> R -> B.
98
+ h : float, default: 1
99
+ The hue, i.e. how saturated the colors are. If this parameter is zero
100
+ then the color scheme is purely a greyscale.
101
+ """
102
+ return {'red': partial(_ch_helper, gamma, s, r, h, -0.14861, 1.78277),
103
+ 'green': partial(_ch_helper, gamma, s, r, h, -0.29227, -0.90649),
104
+ 'blue': partial(_ch_helper, gamma, s, r, h, 1.97294, 0.0)}
105
+
106
+ _cubehelix_data = cubehelix()
107
+
108
+ _bwr_data = ((0.0, 0.0, 1.0), (1.0, 1.0, 1.0), (1.0, 0.0, 0.0))
109
+ _brg_data = ((0.0, 0.0, 1.0), (1.0, 0.0, 0.0), (0.0, 1.0, 0.0))
110
+
111
+ # Gnuplot palette functions
112
+ def _g0(x): return 0
113
+ def _g1(x): return 0.5
114
+ def _g2(x): return 1
115
+ def _g3(x): return x
116
+ def _g4(x): return x ** 2
117
+ def _g5(x): return x ** 3
118
+ def _g6(x): return x ** 4
119
+ def _g7(x): return np.sqrt(x)
120
+ def _g8(x): return np.sqrt(np.sqrt(x))
121
+ def _g9(x): return np.sin(x * np.pi / 2)
122
+ def _g10(x): return np.cos(x * np.pi / 2)
123
+ def _g11(x): return np.abs(x - 0.5)
124
+ def _g12(x): return (2 * x - 1) ** 2
125
+ def _g13(x): return np.sin(x * np.pi)
126
+ def _g14(x): return np.abs(np.cos(x * np.pi))
127
+ def _g15(x): return np.sin(x * 2 * np.pi)
128
+ def _g16(x): return np.cos(x * 2 * np.pi)
129
+ def _g17(x): return np.abs(np.sin(x * 2 * np.pi))
130
+ def _g18(x): return np.abs(np.cos(x * 2 * np.pi))
131
+ def _g19(x): return np.abs(np.sin(x * 4 * np.pi))
132
+ def _g20(x): return np.abs(np.cos(x * 4 * np.pi))
133
+ def _g21(x): return 3 * x
134
+ def _g22(x): return 3 * x - 1
135
+ def _g23(x): return 3 * x - 2
136
+ def _g24(x): return np.abs(3 * x - 1)
137
+ def _g25(x): return np.abs(3 * x - 2)
138
+ def _g26(x): return (3 * x - 1) / 2
139
+ def _g27(x): return (3 * x - 2) / 2
140
+ def _g28(x): return np.abs((3 * x - 1) / 2)
141
+ def _g29(x): return np.abs((3 * x - 2) / 2)
142
+ def _g30(x): return x / 0.32 - 0.78125
143
+ def _g31(x): return 2 * x - 0.84
144
+ def _g32(x):
145
+ ret = np.zeros(len(x))
146
+ m = (x < 0.25)
147
+ ret[m] = 4 * x[m]
148
+ m = (x >= 0.25) & (x < 0.92)
149
+ ret[m] = -2 * x[m] + 1.84
150
+ m = (x >= 0.92)
151
+ ret[m] = x[m] / 0.08 - 11.5
152
+ return ret
153
+ def _g33(x): return np.abs(2 * x - 0.5)
154
+ def _g34(x): return 2 * x
155
+ def _g35(x): return 2 * x - 0.5
156
+ def _g36(x): return 2 * x - 1
157
+
158
+ gfunc = {i: globals()[f"_g{i}"] for i in range(37)}
159
+
160
+ _gnuplot_data = {
161
+ 'red': gfunc[7],
162
+ 'green': gfunc[5],
163
+ 'blue': gfunc[15],
164
+ }
165
+
166
+ _gnuplot2_data = {
167
+ 'red': gfunc[30],
168
+ 'green': gfunc[31],
169
+ 'blue': gfunc[32],
170
+ }
171
+
172
+ _ocean_data = {
173
+ 'red': gfunc[23],
174
+ 'green': gfunc[28],
175
+ 'blue': gfunc[3],
176
+ }
177
+
178
+ _afmhot_data = {
179
+ 'red': gfunc[34],
180
+ 'green': gfunc[35],
181
+ 'blue': gfunc[36],
182
+ }
183
+
184
+ _rainbow_data = {
185
+ 'red': gfunc[33],
186
+ 'green': gfunc[13],
187
+ 'blue': gfunc[10],
188
+ }
189
+
190
+ _seismic_data = (
191
+ (0.0, 0.0, 0.3), (0.0, 0.0, 1.0),
192
+ (1.0, 1.0, 1.0), (1.0, 0.0, 0.0),
193
+ (0.5, 0.0, 0.0))
194
+
195
+ _terrain_data = (
196
+ (0.00, (0.2, 0.2, 0.6)),
197
+ (0.15, (0.0, 0.6, 1.0)),
198
+ (0.25, (0.0, 0.8, 0.4)),
199
+ (0.50, (1.0, 1.0, 0.6)),
200
+ (0.75, (0.5, 0.36, 0.33)),
201
+ (1.00, (1.0, 1.0, 1.0)))
202
+
203
+ _gray_data = {'red': ((0., 0, 0), (1., 1, 1)),
204
+ 'green': ((0., 0, 0), (1., 1, 1)),
205
+ 'blue': ((0., 0, 0), (1., 1, 1))}
206
+
207
+ _hot_data = {'red': ((0., 0.0416, 0.0416),
208
+ (0.365079, 1.000000, 1.000000),
209
+ (1.0, 1.0, 1.0)),
210
+ 'green': ((0., 0., 0.),
211
+ (0.365079, 0.000000, 0.000000),
212
+ (0.746032, 1.000000, 1.000000),
213
+ (1.0, 1.0, 1.0)),
214
+ 'blue': ((0., 0., 0.),
215
+ (0.746032, 0.000000, 0.000000),
216
+ (1.0, 1.0, 1.0))}
217
+
218
+ _hsv_data = {'red': ((0., 1., 1.),
219
+ (0.158730, 1.000000, 1.000000),
220
+ (0.174603, 0.968750, 0.968750),
221
+ (0.333333, 0.031250, 0.031250),
222
+ (0.349206, 0.000000, 0.000000),
223
+ (0.666667, 0.000000, 0.000000),
224
+ (0.682540, 0.031250, 0.031250),
225
+ (0.841270, 0.968750, 0.968750),
226
+ (0.857143, 1.000000, 1.000000),
227
+ (1.0, 1.0, 1.0)),
228
+ 'green': ((0., 0., 0.),
229
+ (0.158730, 0.937500, 0.937500),
230
+ (0.174603, 1.000000, 1.000000),
231
+ (0.507937, 1.000000, 1.000000),
232
+ (0.666667, 0.062500, 0.062500),
233
+ (0.682540, 0.000000, 0.000000),
234
+ (1.0, 0., 0.)),
235
+ 'blue': ((0., 0., 0.),
236
+ (0.333333, 0.000000, 0.000000),
237
+ (0.349206, 0.062500, 0.062500),
238
+ (0.507937, 1.000000, 1.000000),
239
+ (0.841270, 1.000000, 1.000000),
240
+ (0.857143, 0.937500, 0.937500),
241
+ (1.0, 0.09375, 0.09375))}
242
+
243
+ _jet_data = {'red': ((0.00, 0, 0),
244
+ (0.35, 0, 0),
245
+ (0.66, 1, 1),
246
+ (0.89, 1, 1),
247
+ (1.00, 0.5, 0.5)),
248
+ 'green': ((0.000, 0, 0),
249
+ (0.125, 0, 0),
250
+ (0.375, 1, 1),
251
+ (0.640, 1, 1),
252
+ (0.910, 0, 0),
253
+ (1.000, 0, 0)),
254
+ 'blue': ((0.00, 0.5, 0.5),
255
+ (0.11, 1, 1),
256
+ (0.34, 1, 1),
257
+ (0.65, 0, 0),
258
+ (1.00, 0, 0))}
259
+
260
+ _pink_data = {'red': ((0., 0.1178, 0.1178), (0.015873, 0.195857, 0.195857),
261
+ (0.031746, 0.250661, 0.250661),
262
+ (0.047619, 0.295468, 0.295468),
263
+ (0.063492, 0.334324, 0.334324),
264
+ (0.079365, 0.369112, 0.369112),
265
+ (0.095238, 0.400892, 0.400892),
266
+ (0.111111, 0.430331, 0.430331),
267
+ (0.126984, 0.457882, 0.457882),
268
+ (0.142857, 0.483867, 0.483867),
269
+ (0.158730, 0.508525, 0.508525),
270
+ (0.174603, 0.532042, 0.532042),
271
+ (0.190476, 0.554563, 0.554563),
272
+ (0.206349, 0.576204, 0.576204),
273
+ (0.222222, 0.597061, 0.597061),
274
+ (0.238095, 0.617213, 0.617213),
275
+ (0.253968, 0.636729, 0.636729),
276
+ (0.269841, 0.655663, 0.655663),
277
+ (0.285714, 0.674066, 0.674066),
278
+ (0.301587, 0.691980, 0.691980),
279
+ (0.317460, 0.709441, 0.709441),
280
+ (0.333333, 0.726483, 0.726483),
281
+ (0.349206, 0.743134, 0.743134),
282
+ (0.365079, 0.759421, 0.759421),
283
+ (0.380952, 0.766356, 0.766356),
284
+ (0.396825, 0.773229, 0.773229),
285
+ (0.412698, 0.780042, 0.780042),
286
+ (0.428571, 0.786796, 0.786796),
287
+ (0.444444, 0.793492, 0.793492),
288
+ (0.460317, 0.800132, 0.800132),
289
+ (0.476190, 0.806718, 0.806718),
290
+ (0.492063, 0.813250, 0.813250),
291
+ (0.507937, 0.819730, 0.819730),
292
+ (0.523810, 0.826160, 0.826160),
293
+ (0.539683, 0.832539, 0.832539),
294
+ (0.555556, 0.838870, 0.838870),
295
+ (0.571429, 0.845154, 0.845154),
296
+ (0.587302, 0.851392, 0.851392),
297
+ (0.603175, 0.857584, 0.857584),
298
+ (0.619048, 0.863731, 0.863731),
299
+ (0.634921, 0.869835, 0.869835),
300
+ (0.650794, 0.875897, 0.875897),
301
+ (0.666667, 0.881917, 0.881917),
302
+ (0.682540, 0.887896, 0.887896),
303
+ (0.698413, 0.893835, 0.893835),
304
+ (0.714286, 0.899735, 0.899735),
305
+ (0.730159, 0.905597, 0.905597),
306
+ (0.746032, 0.911421, 0.911421),
307
+ (0.761905, 0.917208, 0.917208),
308
+ (0.777778, 0.922958, 0.922958),
309
+ (0.793651, 0.928673, 0.928673),
310
+ (0.809524, 0.934353, 0.934353),
311
+ (0.825397, 0.939999, 0.939999),
312
+ (0.841270, 0.945611, 0.945611),
313
+ (0.857143, 0.951190, 0.951190),
314
+ (0.873016, 0.956736, 0.956736),
315
+ (0.888889, 0.962250, 0.962250),
316
+ (0.904762, 0.967733, 0.967733),
317
+ (0.920635, 0.973185, 0.973185),
318
+ (0.936508, 0.978607, 0.978607),
319
+ (0.952381, 0.983999, 0.983999),
320
+ (0.968254, 0.989361, 0.989361),
321
+ (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),
322
+ 'green': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),
323
+ (0.031746, 0.145479, 0.145479),
324
+ (0.047619, 0.178174, 0.178174),
325
+ (0.063492, 0.205738, 0.205738),
326
+ (0.079365, 0.230022, 0.230022),
327
+ (0.095238, 0.251976, 0.251976),
328
+ (0.111111, 0.272166, 0.272166),
329
+ (0.126984, 0.290957, 0.290957),
330
+ (0.142857, 0.308607, 0.308607),
331
+ (0.158730, 0.325300, 0.325300),
332
+ (0.174603, 0.341178, 0.341178),
333
+ (0.190476, 0.356348, 0.356348),
334
+ (0.206349, 0.370899, 0.370899),
335
+ (0.222222, 0.384900, 0.384900),
336
+ (0.238095, 0.398410, 0.398410),
337
+ (0.253968, 0.411476, 0.411476),
338
+ (0.269841, 0.424139, 0.424139),
339
+ (0.285714, 0.436436, 0.436436),
340
+ (0.301587, 0.448395, 0.448395),
341
+ (0.317460, 0.460044, 0.460044),
342
+ (0.333333, 0.471405, 0.471405),
343
+ (0.349206, 0.482498, 0.482498),
344
+ (0.365079, 0.493342, 0.493342),
345
+ (0.380952, 0.517549, 0.517549),
346
+ (0.396825, 0.540674, 0.540674),
347
+ (0.412698, 0.562849, 0.562849),
348
+ (0.428571, 0.584183, 0.584183),
349
+ (0.444444, 0.604765, 0.604765),
350
+ (0.460317, 0.624669, 0.624669),
351
+ (0.476190, 0.643958, 0.643958),
352
+ (0.492063, 0.662687, 0.662687),
353
+ (0.507937, 0.680900, 0.680900),
354
+ (0.523810, 0.698638, 0.698638),
355
+ (0.539683, 0.715937, 0.715937),
356
+ (0.555556, 0.732828, 0.732828),
357
+ (0.571429, 0.749338, 0.749338),
358
+ (0.587302, 0.765493, 0.765493),
359
+ (0.603175, 0.781313, 0.781313),
360
+ (0.619048, 0.796819, 0.796819),
361
+ (0.634921, 0.812029, 0.812029),
362
+ (0.650794, 0.826960, 0.826960),
363
+ (0.666667, 0.841625, 0.841625),
364
+ (0.682540, 0.856040, 0.856040),
365
+ (0.698413, 0.870216, 0.870216),
366
+ (0.714286, 0.884164, 0.884164),
367
+ (0.730159, 0.897896, 0.897896),
368
+ (0.746032, 0.911421, 0.911421),
369
+ (0.761905, 0.917208, 0.917208),
370
+ (0.777778, 0.922958, 0.922958),
371
+ (0.793651, 0.928673, 0.928673),
372
+ (0.809524, 0.934353, 0.934353),
373
+ (0.825397, 0.939999, 0.939999),
374
+ (0.841270, 0.945611, 0.945611),
375
+ (0.857143, 0.951190, 0.951190),
376
+ (0.873016, 0.956736, 0.956736),
377
+ (0.888889, 0.962250, 0.962250),
378
+ (0.904762, 0.967733, 0.967733),
379
+ (0.920635, 0.973185, 0.973185),
380
+ (0.936508, 0.978607, 0.978607),
381
+ (0.952381, 0.983999, 0.983999),
382
+ (0.968254, 0.989361, 0.989361),
383
+ (0.984127, 0.994695, 0.994695), (1.0, 1.0, 1.0)),
384
+ 'blue': ((0., 0., 0.), (0.015873, 0.102869, 0.102869),
385
+ (0.031746, 0.145479, 0.145479),
386
+ (0.047619, 0.178174, 0.178174),
387
+ (0.063492, 0.205738, 0.205738),
388
+ (0.079365, 0.230022, 0.230022),
389
+ (0.095238, 0.251976, 0.251976),
390
+ (0.111111, 0.272166, 0.272166),
391
+ (0.126984, 0.290957, 0.290957),
392
+ (0.142857, 0.308607, 0.308607),
393
+ (0.158730, 0.325300, 0.325300),
394
+ (0.174603, 0.341178, 0.341178),
395
+ (0.190476, 0.356348, 0.356348),
396
+ (0.206349, 0.370899, 0.370899),
397
+ (0.222222, 0.384900, 0.384900),
398
+ (0.238095, 0.398410, 0.398410),
399
+ (0.253968, 0.411476, 0.411476),
400
+ (0.269841, 0.424139, 0.424139),
401
+ (0.285714, 0.436436, 0.436436),
402
+ (0.301587, 0.448395, 0.448395),
403
+ (0.317460, 0.460044, 0.460044),
404
+ (0.333333, 0.471405, 0.471405),
405
+ (0.349206, 0.482498, 0.482498),
406
+ (0.365079, 0.493342, 0.493342),
407
+ (0.380952, 0.503953, 0.503953),
408
+ (0.396825, 0.514344, 0.514344),
409
+ (0.412698, 0.524531, 0.524531),
410
+ (0.428571, 0.534522, 0.534522),
411
+ (0.444444, 0.544331, 0.544331),
412
+ (0.460317, 0.553966, 0.553966),
413
+ (0.476190, 0.563436, 0.563436),
414
+ (0.492063, 0.572750, 0.572750),
415
+ (0.507937, 0.581914, 0.581914),
416
+ (0.523810, 0.590937, 0.590937),
417
+ (0.539683, 0.599824, 0.599824),
418
+ (0.555556, 0.608581, 0.608581),
419
+ (0.571429, 0.617213, 0.617213),
420
+ (0.587302, 0.625727, 0.625727),
421
+ (0.603175, 0.634126, 0.634126),
422
+ (0.619048, 0.642416, 0.642416),
423
+ (0.634921, 0.650600, 0.650600),
424
+ (0.650794, 0.658682, 0.658682),
425
+ (0.666667, 0.666667, 0.666667),
426
+ (0.682540, 0.674556, 0.674556),
427
+ (0.698413, 0.682355, 0.682355),
428
+ (0.714286, 0.690066, 0.690066),
429
+ (0.730159, 0.697691, 0.697691),
430
+ (0.746032, 0.705234, 0.705234),
431
+ (0.761905, 0.727166, 0.727166),
432
+ (0.777778, 0.748455, 0.748455),
433
+ (0.793651, 0.769156, 0.769156),
434
+ (0.809524, 0.789314, 0.789314),
435
+ (0.825397, 0.808969, 0.808969),
436
+ (0.841270, 0.828159, 0.828159),
437
+ (0.857143, 0.846913, 0.846913),
438
+ (0.873016, 0.865261, 0.865261),
439
+ (0.888889, 0.883229, 0.883229),
440
+ (0.904762, 0.900837, 0.900837),
441
+ (0.920635, 0.918109, 0.918109),
442
+ (0.936508, 0.935061, 0.935061),
443
+ (0.952381, 0.951711, 0.951711),
444
+ (0.968254, 0.968075, 0.968075),
445
+ (0.984127, 0.984167, 0.984167), (1.0, 1.0, 1.0))}
446
+
447
+ _spring_data = {'red': ((0., 1., 1.), (1.0, 1.0, 1.0)),
448
+ 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
449
+ 'blue': ((0., 1., 1.), (1.0, 0.0, 0.0))}
450
+
451
+
452
+ _summer_data = {'red': ((0., 0., 0.), (1.0, 1.0, 1.0)),
453
+ 'green': ((0., 0.5, 0.5), (1.0, 1.0, 1.0)),
454
+ 'blue': ((0., 0.4, 0.4), (1.0, 0.4, 0.4))}
455
+
456
+
457
+ _winter_data = {'red': ((0., 0., 0.), (1.0, 0.0, 0.0)),
458
+ 'green': ((0., 0., 0.), (1.0, 1.0, 1.0)),
459
+ 'blue': ((0., 1., 1.), (1.0, 0.5, 0.5))}
460
+
461
+ _nipy_spectral_data = {
462
+ 'red': [
463
+ (0.0, 0.0, 0.0), (0.05, 0.4667, 0.4667),
464
+ (0.10, 0.5333, 0.5333), (0.15, 0.0, 0.0),
465
+ (0.20, 0.0, 0.0), (0.25, 0.0, 0.0),
466
+ (0.30, 0.0, 0.0), (0.35, 0.0, 0.0),
467
+ (0.40, 0.0, 0.0), (0.45, 0.0, 0.0),
468
+ (0.50, 0.0, 0.0), (0.55, 0.0, 0.0),
469
+ (0.60, 0.0, 0.0), (0.65, 0.7333, 0.7333),
470
+ (0.70, 0.9333, 0.9333), (0.75, 1.0, 1.0),
471
+ (0.80, 1.0, 1.0), (0.85, 1.0, 1.0),
472
+ (0.90, 0.8667, 0.8667), (0.95, 0.80, 0.80),
473
+ (1.0, 0.80, 0.80),
474
+ ],
475
+ 'green': [
476
+ (0.0, 0.0, 0.0), (0.05, 0.0, 0.0),
477
+ (0.10, 0.0, 0.0), (0.15, 0.0, 0.0),
478
+ (0.20, 0.0, 0.0), (0.25, 0.4667, 0.4667),
479
+ (0.30, 0.6000, 0.6000), (0.35, 0.6667, 0.6667),
480
+ (0.40, 0.6667, 0.6667), (0.45, 0.6000, 0.6000),
481
+ (0.50, 0.7333, 0.7333), (0.55, 0.8667, 0.8667),
482
+ (0.60, 1.0, 1.0), (0.65, 1.0, 1.0),
483
+ (0.70, 0.9333, 0.9333), (0.75, 0.8000, 0.8000),
484
+ (0.80, 0.6000, 0.6000), (0.85, 0.0, 0.0),
485
+ (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),
486
+ (1.0, 0.80, 0.80),
487
+ ],
488
+ 'blue': [
489
+ (0.0, 0.0, 0.0), (0.05, 0.5333, 0.5333),
490
+ (0.10, 0.6000, 0.6000), (0.15, 0.6667, 0.6667),
491
+ (0.20, 0.8667, 0.8667), (0.25, 0.8667, 0.8667),
492
+ (0.30, 0.8667, 0.8667), (0.35, 0.6667, 0.6667),
493
+ (0.40, 0.5333, 0.5333), (0.45, 0.0, 0.0),
494
+ (0.5, 0.0, 0.0), (0.55, 0.0, 0.0),
495
+ (0.60, 0.0, 0.0), (0.65, 0.0, 0.0),
496
+ (0.70, 0.0, 0.0), (0.75, 0.0, 0.0),
497
+ (0.80, 0.0, 0.0), (0.85, 0.0, 0.0),
498
+ (0.90, 0.0, 0.0), (0.95, 0.0, 0.0),
499
+ (1.0, 0.80, 0.80),
500
+ ],
501
+ }
502
+
503
+
504
+ # 34 colormaps based on color specifications and designs
505
+ # developed by Cynthia Brewer (https://colorbrewer2.org/).
506
+ # The ColorBrewer palettes have been included under the terms
507
+ # of an Apache-stype license (for details, see the file
508
+ # LICENSE_COLORBREWER in the license directory of the matplotlib
509
+ # source distribution).
510
+
511
+ # RGB values taken from Brewer's Excel sheet, divided by 255
512
+
513
+ _Blues_data = (
514
+ (0.96862745098039216, 0.98431372549019602, 1.0 ),
515
+ (0.87058823529411766, 0.92156862745098034, 0.96862745098039216),
516
+ (0.77647058823529413, 0.85882352941176465, 0.93725490196078431),
517
+ (0.61960784313725492, 0.792156862745098 , 0.88235294117647056),
518
+ (0.41960784313725491, 0.68235294117647061, 0.83921568627450982),
519
+ (0.25882352941176473, 0.5725490196078431 , 0.77647058823529413),
520
+ (0.12941176470588237, 0.44313725490196076, 0.70980392156862748),
521
+ (0.03137254901960784, 0.31764705882352939, 0.61176470588235299),
522
+ (0.03137254901960784, 0.18823529411764706, 0.41960784313725491)
523
+ )
524
+
525
+ _BrBG_data = (
526
+ (0.32941176470588235, 0.18823529411764706, 0.0196078431372549 ),
527
+ (0.5490196078431373 , 0.31764705882352939, 0.0392156862745098 ),
528
+ (0.74901960784313726, 0.50588235294117645, 0.17647058823529413),
529
+ (0.87450980392156863, 0.76078431372549016, 0.49019607843137253),
530
+ (0.96470588235294119, 0.90980392156862744, 0.76470588235294112),
531
+ (0.96078431372549022, 0.96078431372549022, 0.96078431372549022),
532
+ (0.7803921568627451 , 0.91764705882352937, 0.89803921568627454),
533
+ (0.50196078431372548, 0.80392156862745101, 0.75686274509803919),
534
+ (0.20784313725490197, 0.59215686274509804, 0.5607843137254902 ),
535
+ (0.00392156862745098, 0.4 , 0.36862745098039218),
536
+ (0.0 , 0.23529411764705882, 0.18823529411764706)
537
+ )
538
+
539
+ _BuGn_data = (
540
+ (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),
541
+ (0.89803921568627454, 0.96078431372549022, 0.97647058823529409),
542
+ (0.8 , 0.92549019607843142, 0.90196078431372551),
543
+ (0.6 , 0.84705882352941175, 0.78823529411764703),
544
+ (0.4 , 0.76078431372549016, 0.64313725490196083),
545
+ (0.25490196078431371, 0.68235294117647061, 0.46274509803921571),
546
+ (0.13725490196078433, 0.54509803921568623, 0.27058823529411763),
547
+ (0.0 , 0.42745098039215684, 0.17254901960784313),
548
+ (0.0 , 0.26666666666666666, 0.10588235294117647)
549
+ )
550
+
551
+ _BuPu_data = (
552
+ (0.96862745098039216, 0.9882352941176471 , 0.99215686274509807),
553
+ (0.8784313725490196 , 0.92549019607843142, 0.95686274509803926),
554
+ (0.74901960784313726, 0.82745098039215681, 0.90196078431372551),
555
+ (0.61960784313725492, 0.73725490196078436, 0.85490196078431369),
556
+ (0.5490196078431373 , 0.58823529411764708, 0.77647058823529413),
557
+ (0.5490196078431373 , 0.41960784313725491, 0.69411764705882351),
558
+ (0.53333333333333333, 0.25490196078431371, 0.61568627450980395),
559
+ (0.50588235294117645, 0.05882352941176471, 0.48627450980392156),
560
+ (0.30196078431372547, 0.0 , 0.29411764705882354)
561
+ )
562
+
563
+ _GnBu_data = (
564
+ (0.96862745098039216, 0.9882352941176471 , 0.94117647058823528),
565
+ (0.8784313725490196 , 0.95294117647058818, 0.85882352941176465),
566
+ (0.8 , 0.92156862745098034, 0.77254901960784317),
567
+ (0.6588235294117647 , 0.8666666666666667 , 0.70980392156862748),
568
+ (0.4823529411764706 , 0.8 , 0.7686274509803922 ),
569
+ (0.30588235294117649, 0.70196078431372544, 0.82745098039215681),
570
+ (0.16862745098039217, 0.5490196078431373 , 0.74509803921568629),
571
+ (0.03137254901960784, 0.40784313725490196, 0.67450980392156867),
572
+ (0.03137254901960784, 0.25098039215686274, 0.50588235294117645)
573
+ )
574
+
575
+ _Greens_data = (
576
+ (0.96862745098039216, 0.9882352941176471 , 0.96078431372549022),
577
+ (0.89803921568627454, 0.96078431372549022, 0.8784313725490196 ),
578
+ (0.7803921568627451 , 0.9137254901960784 , 0.75294117647058822),
579
+ (0.63137254901960782, 0.85098039215686272, 0.60784313725490191),
580
+ (0.45490196078431372, 0.7686274509803922 , 0.46274509803921571),
581
+ (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),
582
+ (0.13725490196078433, 0.54509803921568623, 0.27058823529411763),
583
+ (0.0 , 0.42745098039215684, 0.17254901960784313),
584
+ (0.0 , 0.26666666666666666, 0.10588235294117647)
585
+ )
586
+
587
+ _Greys_data = (
588
+ (1.0 , 1.0 , 1.0 ),
589
+ (0.94117647058823528, 0.94117647058823528, 0.94117647058823528),
590
+ (0.85098039215686272, 0.85098039215686272, 0.85098039215686272),
591
+ (0.74117647058823533, 0.74117647058823533, 0.74117647058823533),
592
+ (0.58823529411764708, 0.58823529411764708, 0.58823529411764708),
593
+ (0.45098039215686275, 0.45098039215686275, 0.45098039215686275),
594
+ (0.32156862745098042, 0.32156862745098042, 0.32156862745098042),
595
+ (0.14509803921568629, 0.14509803921568629, 0.14509803921568629),
596
+ (0.0 , 0.0 , 0.0 )
597
+ )
598
+
599
+ _Oranges_data = (
600
+ (1.0 , 0.96078431372549022, 0.92156862745098034),
601
+ (0.99607843137254903, 0.90196078431372551, 0.80784313725490198),
602
+ (0.99215686274509807, 0.81568627450980391, 0.63529411764705879),
603
+ (0.99215686274509807, 0.68235294117647061, 0.41960784313725491),
604
+ (0.99215686274509807, 0.55294117647058827, 0.23529411764705882),
605
+ (0.94509803921568625, 0.41176470588235292, 0.07450980392156863),
606
+ (0.85098039215686272, 0.28235294117647058, 0.00392156862745098),
607
+ (0.65098039215686276, 0.21176470588235294, 0.01176470588235294),
608
+ (0.49803921568627452, 0.15294117647058825, 0.01568627450980392)
609
+ )
610
+
611
+ _OrRd_data = (
612
+ (1.0 , 0.96862745098039216, 0.92549019607843142),
613
+ (0.99607843137254903, 0.90980392156862744, 0.78431372549019607),
614
+ (0.99215686274509807, 0.83137254901960789, 0.61960784313725492),
615
+ (0.99215686274509807, 0.73333333333333328, 0.51764705882352946),
616
+ (0.9882352941176471 , 0.55294117647058827, 0.34901960784313724),
617
+ (0.93725490196078431, 0.396078431372549 , 0.28235294117647058),
618
+ (0.84313725490196079, 0.18823529411764706, 0.12156862745098039),
619
+ (0.70196078431372544, 0.0 , 0.0 ),
620
+ (0.49803921568627452, 0.0 , 0.0 )
621
+ )
622
+
623
+ _PiYG_data = (
624
+ (0.55686274509803924, 0.00392156862745098, 0.32156862745098042),
625
+ (0.77254901960784317, 0.10588235294117647, 0.49019607843137253),
626
+ (0.87058823529411766, 0.46666666666666667, 0.68235294117647061),
627
+ (0.94509803921568625, 0.71372549019607845, 0.85490196078431369),
628
+ (0.99215686274509807, 0.8784313725490196 , 0.93725490196078431),
629
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
630
+ (0.90196078431372551, 0.96078431372549022, 0.81568627450980391),
631
+ (0.72156862745098038, 0.88235294117647056, 0.52549019607843139),
632
+ (0.49803921568627452, 0.73725490196078436, 0.25490196078431371),
633
+ (0.30196078431372547, 0.5725490196078431 , 0.12941176470588237),
634
+ (0.15294117647058825, 0.39215686274509803, 0.09803921568627451)
635
+ )
636
+
637
+ _PRGn_data = (
638
+ (0.25098039215686274, 0.0 , 0.29411764705882354),
639
+ (0.46274509803921571, 0.16470588235294117, 0.51372549019607838),
640
+ (0.6 , 0.4392156862745098 , 0.6705882352941176 ),
641
+ (0.76078431372549016, 0.6470588235294118 , 0.81176470588235294),
642
+ (0.90588235294117647, 0.83137254901960789, 0.90980392156862744),
643
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
644
+ (0.85098039215686272, 0.94117647058823528, 0.82745098039215681),
645
+ (0.65098039215686276, 0.85882352941176465, 0.62745098039215685),
646
+ (0.35294117647058826, 0.68235294117647061, 0.38039215686274508),
647
+ (0.10588235294117647, 0.47058823529411764, 0.21568627450980393),
648
+ (0.0 , 0.26666666666666666, 0.10588235294117647)
649
+ )
650
+
651
+ _PuBu_data = (
652
+ (1.0 , 0.96862745098039216, 0.98431372549019602),
653
+ (0.92549019607843142, 0.90588235294117647, 0.94901960784313721),
654
+ (0.81568627450980391, 0.81960784313725488, 0.90196078431372551),
655
+ (0.65098039215686276, 0.74117647058823533, 0.85882352941176465),
656
+ (0.45490196078431372, 0.66274509803921566, 0.81176470588235294),
657
+ (0.21176470588235294, 0.56470588235294117, 0.75294117647058822),
658
+ (0.0196078431372549 , 0.4392156862745098 , 0.69019607843137254),
659
+ (0.01568627450980392, 0.35294117647058826, 0.55294117647058827),
660
+ (0.00784313725490196, 0.2196078431372549 , 0.34509803921568627)
661
+ )
662
+
663
+ _PuBuGn_data = (
664
+ (1.0 , 0.96862745098039216, 0.98431372549019602),
665
+ (0.92549019607843142, 0.88627450980392153, 0.94117647058823528),
666
+ (0.81568627450980391, 0.81960784313725488, 0.90196078431372551),
667
+ (0.65098039215686276, 0.74117647058823533, 0.85882352941176465),
668
+ (0.40392156862745099, 0.66274509803921566, 0.81176470588235294),
669
+ (0.21176470588235294, 0.56470588235294117, 0.75294117647058822),
670
+ (0.00784313725490196, 0.50588235294117645, 0.54117647058823526),
671
+ (0.00392156862745098, 0.42352941176470588, 0.34901960784313724),
672
+ (0.00392156862745098, 0.27450980392156865, 0.21176470588235294)
673
+ )
674
+
675
+ _PuOr_data = (
676
+ (0.49803921568627452, 0.23137254901960785, 0.03137254901960784),
677
+ (0.70196078431372544, 0.34509803921568627, 0.02352941176470588),
678
+ (0.8784313725490196 , 0.50980392156862742, 0.07843137254901961),
679
+ (0.99215686274509807, 0.72156862745098038, 0.38823529411764707),
680
+ (0.99607843137254903, 0.8784313725490196 , 0.71372549019607845),
681
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
682
+ (0.84705882352941175, 0.85490196078431369, 0.92156862745098034),
683
+ (0.69803921568627447, 0.6705882352941176 , 0.82352941176470584),
684
+ (0.50196078431372548, 0.45098039215686275, 0.67450980392156867),
685
+ (0.32941176470588235, 0.15294117647058825, 0.53333333333333333),
686
+ (0.17647058823529413, 0.0 , 0.29411764705882354)
687
+ )
688
+
689
+ _PuRd_data = (
690
+ (0.96862745098039216, 0.95686274509803926, 0.97647058823529409),
691
+ (0.90588235294117647, 0.88235294117647056, 0.93725490196078431),
692
+ (0.83137254901960789, 0.72549019607843135, 0.85490196078431369),
693
+ (0.78823529411764703, 0.58039215686274515, 0.7803921568627451 ),
694
+ (0.87450980392156863, 0.396078431372549 , 0.69019607843137254),
695
+ (0.90588235294117647, 0.16078431372549021, 0.54117647058823526),
696
+ (0.80784313725490198, 0.07058823529411765, 0.33725490196078434),
697
+ (0.59607843137254901, 0.0 , 0.2627450980392157 ),
698
+ (0.40392156862745099, 0.0 , 0.12156862745098039)
699
+ )
700
+
701
+ _Purples_data = (
702
+ (0.9882352941176471 , 0.98431372549019602, 0.99215686274509807),
703
+ (0.93725490196078431, 0.92941176470588238, 0.96078431372549022),
704
+ (0.85490196078431369, 0.85490196078431369, 0.92156862745098034),
705
+ (0.73725490196078436, 0.74117647058823533, 0.86274509803921573),
706
+ (0.61960784313725492, 0.60392156862745094, 0.78431372549019607),
707
+ (0.50196078431372548, 0.49019607843137253, 0.72941176470588232),
708
+ (0.41568627450980394, 0.31764705882352939, 0.63921568627450975),
709
+ (0.32941176470588235, 0.15294117647058825, 0.5607843137254902 ),
710
+ (0.24705882352941178, 0.0 , 0.49019607843137253)
711
+ )
712
+
713
+ _RdBu_data = (
714
+ (0.40392156862745099, 0.0 , 0.12156862745098039),
715
+ (0.69803921568627447, 0.09411764705882353, 0.16862745098039217),
716
+ (0.83921568627450982, 0.37647058823529411, 0.30196078431372547),
717
+ (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),
718
+ (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),
719
+ (0.96862745098039216, 0.96862745098039216, 0.96862745098039216),
720
+ (0.81960784313725488, 0.89803921568627454, 0.94117647058823528),
721
+ (0.5725490196078431 , 0.77254901960784317, 0.87058823529411766),
722
+ (0.2627450980392157 , 0.57647058823529407, 0.76470588235294112),
723
+ (0.12941176470588237, 0.4 , 0.67450980392156867),
724
+ (0.0196078431372549 , 0.18823529411764706, 0.38039215686274508)
725
+ )
726
+
727
+ _RdGy_data = (
728
+ (0.40392156862745099, 0.0 , 0.12156862745098039),
729
+ (0.69803921568627447, 0.09411764705882353, 0.16862745098039217),
730
+ (0.83921568627450982, 0.37647058823529411, 0.30196078431372547),
731
+ (0.95686274509803926, 0.6470588235294118 , 0.50980392156862742),
732
+ (0.99215686274509807, 0.85882352941176465, 0.7803921568627451 ),
733
+ (1.0 , 1.0 , 1.0 ),
734
+ (0.8784313725490196 , 0.8784313725490196 , 0.8784313725490196 ),
735
+ (0.72941176470588232, 0.72941176470588232, 0.72941176470588232),
736
+ (0.52941176470588236, 0.52941176470588236, 0.52941176470588236),
737
+ (0.30196078431372547, 0.30196078431372547, 0.30196078431372547),
738
+ (0.10196078431372549, 0.10196078431372549, 0.10196078431372549)
739
+ )
740
+
741
+ _RdPu_data = (
742
+ (1.0 , 0.96862745098039216, 0.95294117647058818),
743
+ (0.99215686274509807, 0.8784313725490196 , 0.86666666666666667),
744
+ (0.9882352941176471 , 0.77254901960784317, 0.75294117647058822),
745
+ (0.98039215686274506, 0.62352941176470589, 0.70980392156862748),
746
+ (0.96862745098039216, 0.40784313725490196, 0.63137254901960782),
747
+ (0.86666666666666667, 0.20392156862745098, 0.59215686274509804),
748
+ (0.68235294117647061, 0.00392156862745098, 0.49411764705882355),
749
+ (0.47843137254901963, 0.00392156862745098, 0.46666666666666667),
750
+ (0.28627450980392155, 0.0 , 0.41568627450980394)
751
+ )
752
+
753
+ _RdYlBu_data = (
754
+ (0.6470588235294118 , 0.0 , 0.14901960784313725),
755
+ (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),
756
+ (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
757
+ (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
758
+ (0.99607843137254903, 0.8784313725490196 , 0.56470588235294117),
759
+ (1.0 , 1.0 , 0.74901960784313726),
760
+ (0.8784313725490196 , 0.95294117647058818 , 0.97254901960784312),
761
+ (0.6705882352941176 , 0.85098039215686272 , 0.9137254901960784 ),
762
+ (0.45490196078431372, 0.67843137254901964 , 0.81960784313725488),
763
+ (0.27058823529411763, 0.45882352941176469 , 0.70588235294117652),
764
+ (0.19215686274509805, 0.21176470588235294 , 0.58431372549019611)
765
+ )
766
+
767
+ _RdYlGn_data = (
768
+ (0.6470588235294118 , 0.0 , 0.14901960784313725),
769
+ (0.84313725490196079, 0.18823529411764706 , 0.15294117647058825),
770
+ (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
771
+ (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
772
+ (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),
773
+ (1.0 , 1.0 , 0.74901960784313726),
774
+ (0.85098039215686272, 0.93725490196078431 , 0.54509803921568623),
775
+ (0.65098039215686276, 0.85098039215686272 , 0.41568627450980394),
776
+ (0.4 , 0.74117647058823533 , 0.38823529411764707),
777
+ (0.10196078431372549, 0.59607843137254901 , 0.31372549019607843),
778
+ (0.0 , 0.40784313725490196 , 0.21568627450980393)
779
+ )
780
+
781
+ _Reds_data = (
782
+ (1.0 , 0.96078431372549022 , 0.94117647058823528),
783
+ (0.99607843137254903, 0.8784313725490196 , 0.82352941176470584),
784
+ (0.9882352941176471 , 0.73333333333333328 , 0.63137254901960782),
785
+ (0.9882352941176471 , 0.5725490196078431 , 0.44705882352941179),
786
+ (0.98431372549019602, 0.41568627450980394 , 0.29019607843137257),
787
+ (0.93725490196078431, 0.23137254901960785 , 0.17254901960784313),
788
+ (0.79607843137254897, 0.094117647058823528, 0.11372549019607843),
789
+ (0.6470588235294118 , 0.058823529411764705, 0.08235294117647058),
790
+ (0.40392156862745099, 0.0 , 0.05098039215686274)
791
+ )
792
+
793
+ _Spectral_data = (
794
+ (0.61960784313725492, 0.003921568627450980, 0.25882352941176473),
795
+ (0.83529411764705885, 0.24313725490196078 , 0.30980392156862746),
796
+ (0.95686274509803926, 0.42745098039215684 , 0.2627450980392157 ),
797
+ (0.99215686274509807, 0.68235294117647061 , 0.38039215686274508),
798
+ (0.99607843137254903, 0.8784313725490196 , 0.54509803921568623),
799
+ (1.0 , 1.0 , 0.74901960784313726),
800
+ (0.90196078431372551, 0.96078431372549022 , 0.59607843137254901),
801
+ (0.6705882352941176 , 0.8666666666666667 , 0.64313725490196083),
802
+ (0.4 , 0.76078431372549016 , 0.6470588235294118 ),
803
+ (0.19607843137254902, 0.53333333333333333 , 0.74117647058823533),
804
+ (0.36862745098039218, 0.30980392156862746 , 0.63529411764705879)
805
+ )
806
+
807
+ _YlGn_data = (
808
+ (1.0 , 1.0 , 0.89803921568627454),
809
+ (0.96862745098039216, 0.9882352941176471 , 0.72549019607843135),
810
+ (0.85098039215686272, 0.94117647058823528 , 0.63921568627450975),
811
+ (0.67843137254901964, 0.8666666666666667 , 0.55686274509803924),
812
+ (0.47058823529411764, 0.77647058823529413 , 0.47450980392156861),
813
+ (0.25490196078431371, 0.6705882352941176 , 0.36470588235294116),
814
+ (0.13725490196078433, 0.51764705882352946 , 0.2627450980392157 ),
815
+ (0.0 , 0.40784313725490196 , 0.21568627450980393),
816
+ (0.0 , 0.27058823529411763 , 0.16078431372549021)
817
+ )
818
+
819
+ _YlGnBu_data = (
820
+ (1.0 , 1.0 , 0.85098039215686272),
821
+ (0.92941176470588238, 0.97254901960784312 , 0.69411764705882351),
822
+ (0.7803921568627451 , 0.9137254901960784 , 0.70588235294117652),
823
+ (0.49803921568627452, 0.80392156862745101 , 0.73333333333333328),
824
+ (0.25490196078431371, 0.71372549019607845 , 0.7686274509803922 ),
825
+ (0.11372549019607843, 0.56862745098039214 , 0.75294117647058822),
826
+ (0.13333333333333333, 0.36862745098039218 , 0.6588235294117647 ),
827
+ (0.14509803921568629, 0.20392156862745098 , 0.58039215686274515),
828
+ (0.03137254901960784, 0.11372549019607843 , 0.34509803921568627)
829
+ )
830
+
831
+ _YlOrBr_data = (
832
+ (1.0 , 1.0 , 0.89803921568627454),
833
+ (1.0 , 0.96862745098039216 , 0.73725490196078436),
834
+ (0.99607843137254903, 0.8901960784313725 , 0.56862745098039214),
835
+ (0.99607843137254903, 0.7686274509803922 , 0.30980392156862746),
836
+ (0.99607843137254903, 0.6 , 0.16078431372549021),
837
+ (0.92549019607843142, 0.4392156862745098 , 0.07843137254901961),
838
+ (0.8 , 0.29803921568627451 , 0.00784313725490196),
839
+ (0.6 , 0.20392156862745098 , 0.01568627450980392),
840
+ (0.4 , 0.14509803921568629 , 0.02352941176470588)
841
+ )
842
+
843
+ _YlOrRd_data = (
844
+ (1.0 , 1.0 , 0.8 ),
845
+ (1.0 , 0.92941176470588238 , 0.62745098039215685),
846
+ (0.99607843137254903, 0.85098039215686272 , 0.46274509803921571),
847
+ (0.99607843137254903, 0.69803921568627447 , 0.29803921568627451),
848
+ (0.99215686274509807, 0.55294117647058827 , 0.23529411764705882),
849
+ (0.9882352941176471 , 0.30588235294117649 , 0.16470588235294117),
850
+ (0.8901960784313725 , 0.10196078431372549 , 0.10980392156862745),
851
+ (0.74117647058823533, 0.0 , 0.14901960784313725),
852
+ (0.50196078431372548, 0.0 , 0.14901960784313725)
853
+ )
854
+
855
+
856
+ # ColorBrewer's qualitative maps, implemented using ListedColormap
857
+ # for use with mpl.colors.NoNorm
858
+
859
+ _Accent_data = (
860
+ (0.49803921568627452, 0.78823529411764703, 0.49803921568627452),
861
+ (0.74509803921568629, 0.68235294117647061, 0.83137254901960789),
862
+ (0.99215686274509807, 0.75294117647058822, 0.52549019607843139),
863
+ (1.0, 1.0, 0.6 ),
864
+ (0.2196078431372549, 0.42352941176470588, 0.69019607843137254),
865
+ (0.94117647058823528, 0.00784313725490196, 0.49803921568627452),
866
+ (0.74901960784313726, 0.35686274509803922, 0.09019607843137254),
867
+ (0.4, 0.4, 0.4 ),
868
+ )
869
+
870
+ _Dark2_data = (
871
+ (0.10588235294117647, 0.61960784313725492, 0.46666666666666667),
872
+ (0.85098039215686272, 0.37254901960784315, 0.00784313725490196),
873
+ (0.45882352941176469, 0.4392156862745098, 0.70196078431372544),
874
+ (0.90588235294117647, 0.16078431372549021, 0.54117647058823526),
875
+ (0.4, 0.65098039215686276, 0.11764705882352941),
876
+ (0.90196078431372551, 0.6705882352941176, 0.00784313725490196),
877
+ (0.65098039215686276, 0.46274509803921571, 0.11372549019607843),
878
+ (0.4, 0.4, 0.4 ),
879
+ )
880
+
881
+ _Paired_data = (
882
+ (0.65098039215686276, 0.80784313725490198, 0.8901960784313725 ),
883
+ (0.12156862745098039, 0.47058823529411764, 0.70588235294117652),
884
+ (0.69803921568627447, 0.87450980392156863, 0.54117647058823526),
885
+ (0.2, 0.62745098039215685, 0.17254901960784313),
886
+ (0.98431372549019602, 0.60392156862745094, 0.6 ),
887
+ (0.8901960784313725, 0.10196078431372549, 0.10980392156862745),
888
+ (0.99215686274509807, 0.74901960784313726, 0.43529411764705883),
889
+ (1.0, 0.49803921568627452, 0.0 ),
890
+ (0.792156862745098, 0.69803921568627447, 0.83921568627450982),
891
+ (0.41568627450980394, 0.23921568627450981, 0.60392156862745094),
892
+ (1.0, 1.0, 0.6 ),
893
+ (0.69411764705882351, 0.34901960784313724, 0.15686274509803921),
894
+ )
895
+
896
+ _Pastel1_data = (
897
+ (0.98431372549019602, 0.70588235294117652, 0.68235294117647061),
898
+ (0.70196078431372544, 0.80392156862745101, 0.8901960784313725 ),
899
+ (0.8, 0.92156862745098034, 0.77254901960784317),
900
+ (0.87058823529411766, 0.79607843137254897, 0.89411764705882357),
901
+ (0.99607843137254903, 0.85098039215686272, 0.65098039215686276),
902
+ (1.0, 1.0, 0.8 ),
903
+ (0.89803921568627454, 0.84705882352941175, 0.74117647058823533),
904
+ (0.99215686274509807, 0.85490196078431369, 0.92549019607843142),
905
+ (0.94901960784313721, 0.94901960784313721, 0.94901960784313721),
906
+ )
907
+
908
+ _Pastel2_data = (
909
+ (0.70196078431372544, 0.88627450980392153, 0.80392156862745101),
910
+ (0.99215686274509807, 0.80392156862745101, 0.67450980392156867),
911
+ (0.79607843137254897, 0.83529411764705885, 0.90980392156862744),
912
+ (0.95686274509803926, 0.792156862745098, 0.89411764705882357),
913
+ (0.90196078431372551, 0.96078431372549022, 0.78823529411764703),
914
+ (1.0, 0.94901960784313721, 0.68235294117647061),
915
+ (0.94509803921568625, 0.88627450980392153, 0.8 ),
916
+ (0.8, 0.8, 0.8 ),
917
+ )
918
+
919
+ _Set1_data = (
920
+ (0.89411764705882357, 0.10196078431372549, 0.10980392156862745),
921
+ (0.21568627450980393, 0.49411764705882355, 0.72156862745098038),
922
+ (0.30196078431372547, 0.68627450980392157, 0.29019607843137257),
923
+ (0.59607843137254901, 0.30588235294117649, 0.63921568627450975),
924
+ (1.0, 0.49803921568627452, 0.0 ),
925
+ (1.0, 1.0, 0.2 ),
926
+ (0.65098039215686276, 0.33725490196078434, 0.15686274509803921),
927
+ (0.96862745098039216, 0.50588235294117645, 0.74901960784313726),
928
+ (0.6, 0.6, 0.6),
929
+ )
930
+
931
+ _Set2_data = (
932
+ (0.4, 0.76078431372549016, 0.6470588235294118 ),
933
+ (0.9882352941176471, 0.55294117647058827, 0.3843137254901961 ),
934
+ (0.55294117647058827, 0.62745098039215685, 0.79607843137254897),
935
+ (0.90588235294117647, 0.54117647058823526, 0.76470588235294112),
936
+ (0.65098039215686276, 0.84705882352941175, 0.32941176470588235),
937
+ (1.0, 0.85098039215686272, 0.18431372549019609),
938
+ (0.89803921568627454, 0.7686274509803922, 0.58039215686274515),
939
+ (0.70196078431372544, 0.70196078431372544, 0.70196078431372544),
940
+ )
941
+
942
+ _Set3_data = (
943
+ (0.55294117647058827, 0.82745098039215681, 0.7803921568627451 ),
944
+ (1.0, 1.0, 0.70196078431372544),
945
+ (0.74509803921568629, 0.72941176470588232, 0.85490196078431369),
946
+ (0.98431372549019602, 0.50196078431372548, 0.44705882352941179),
947
+ (0.50196078431372548, 0.69411764705882351, 0.82745098039215681),
948
+ (0.99215686274509807, 0.70588235294117652, 0.3843137254901961 ),
949
+ (0.70196078431372544, 0.87058823529411766, 0.41176470588235292),
950
+ (0.9882352941176471, 0.80392156862745101, 0.89803921568627454),
951
+ (0.85098039215686272, 0.85098039215686272, 0.85098039215686272),
952
+ (0.73725490196078436, 0.50196078431372548, 0.74117647058823533),
953
+ (0.8, 0.92156862745098034, 0.77254901960784317),
954
+ (1.0, 0.92941176470588238, 0.43529411764705883),
955
+ )
956
+
957
+
958
+ # The next 7 palettes are from the Yorick scientific visualization package,
959
+ # an evolution of the GIST package, both by David H. Munro.
960
+ # They are released under a BSD-like license (see LICENSE_YORICK in
961
+ # the license directory of the matplotlib source distribution).
962
+ #
963
+ # Most palette functions have been reduced to simple function descriptions
964
+ # by Reinier Heeres, since the rgb components were mostly straight lines.
965
+ # gist_earth_data and gist_ncar_data were simplified by a script and some
966
+ # manual effort.
967
+
968
+ _gist_earth_data = {
969
+ 'red': (
970
+ (0.0, 0.0, 0.0000),
971
+ (0.2824, 0.1882, 0.1882),
972
+ (0.4588, 0.2714, 0.2714),
973
+ (0.5490, 0.4719, 0.4719),
974
+ (0.6980, 0.7176, 0.7176),
975
+ (0.7882, 0.7553, 0.7553),
976
+ (1.0000, 0.9922, 0.9922),
977
+ ),
978
+ 'green': (
979
+ (0.0, 0.0, 0.0000),
980
+ (0.0275, 0.0000, 0.0000),
981
+ (0.1098, 0.1893, 0.1893),
982
+ (0.1647, 0.3035, 0.3035),
983
+ (0.2078, 0.3841, 0.3841),
984
+ (0.2824, 0.5020, 0.5020),
985
+ (0.5216, 0.6397, 0.6397),
986
+ (0.6980, 0.7171, 0.7171),
987
+ (0.7882, 0.6392, 0.6392),
988
+ (0.7922, 0.6413, 0.6413),
989
+ (0.8000, 0.6447, 0.6447),
990
+ (0.8078, 0.6481, 0.6481),
991
+ (0.8157, 0.6549, 0.6549),
992
+ (0.8667, 0.6991, 0.6991),
993
+ (0.8745, 0.7103, 0.7103),
994
+ (0.8824, 0.7216, 0.7216),
995
+ (0.8902, 0.7323, 0.7323),
996
+ (0.8980, 0.7430, 0.7430),
997
+ (0.9412, 0.8275, 0.8275),
998
+ (0.9569, 0.8635, 0.8635),
999
+ (0.9647, 0.8816, 0.8816),
1000
+ (0.9961, 0.9733, 0.9733),
1001
+ (1.0000, 0.9843, 0.9843),
1002
+ ),
1003
+ 'blue': (
1004
+ (0.0, 0.0, 0.0000),
1005
+ (0.0039, 0.1684, 0.1684),
1006
+ (0.0078, 0.2212, 0.2212),
1007
+ (0.0275, 0.4329, 0.4329),
1008
+ (0.0314, 0.4549, 0.4549),
1009
+ (0.2824, 0.5004, 0.5004),
1010
+ (0.4667, 0.2748, 0.2748),
1011
+ (0.5451, 0.3205, 0.3205),
1012
+ (0.7843, 0.3961, 0.3961),
1013
+ (0.8941, 0.6651, 0.6651),
1014
+ (1.0000, 0.9843, 0.9843),
1015
+ )
1016
+ }
1017
+
1018
+ _gist_gray_data = {
1019
+ 'red': gfunc[3],
1020
+ 'green': gfunc[3],
1021
+ 'blue': gfunc[3],
1022
+ }
1023
+
1024
+ def _gist_heat_red(x): return 1.5 * x
1025
+ def _gist_heat_green(x): return 2 * x - 1
1026
+ def _gist_heat_blue(x): return 4 * x - 3
1027
+ _gist_heat_data = {
1028
+ 'red': _gist_heat_red, 'green': _gist_heat_green, 'blue': _gist_heat_blue}
1029
+
1030
+ _gist_ncar_data = {
1031
+ 'red': (
1032
+ (0.0, 0.0, 0.0000),
1033
+ (0.3098, 0.0000, 0.0000),
1034
+ (0.3725, 0.3993, 0.3993),
1035
+ (0.4235, 0.5003, 0.5003),
1036
+ (0.5333, 1.0000, 1.0000),
1037
+ (0.7922, 1.0000, 1.0000),
1038
+ (0.8471, 0.6218, 0.6218),
1039
+ (0.8980, 0.9235, 0.9235),
1040
+ (1.0000, 0.9961, 0.9961),
1041
+ ),
1042
+ 'green': (
1043
+ (0.0, 0.0, 0.0000),
1044
+ (0.0510, 0.3722, 0.3722),
1045
+ (0.1059, 0.0000, 0.0000),
1046
+ (0.1569, 0.7202, 0.7202),
1047
+ (0.1608, 0.7537, 0.7537),
1048
+ (0.1647, 0.7752, 0.7752),
1049
+ (0.2157, 1.0000, 1.0000),
1050
+ (0.2588, 0.9804, 0.9804),
1051
+ (0.2706, 0.9804, 0.9804),
1052
+ (0.3176, 1.0000, 1.0000),
1053
+ (0.3686, 0.8081, 0.8081),
1054
+ (0.4275, 1.0000, 1.0000),
1055
+ (0.5216, 1.0000, 1.0000),
1056
+ (0.6314, 0.7292, 0.7292),
1057
+ (0.6863, 0.2796, 0.2796),
1058
+ (0.7451, 0.0000, 0.0000),
1059
+ (0.7922, 0.0000, 0.0000),
1060
+ (0.8431, 0.1753, 0.1753),
1061
+ (0.8980, 0.5000, 0.5000),
1062
+ (1.0000, 0.9725, 0.9725),
1063
+ ),
1064
+ 'blue': (
1065
+ (0.0, 0.5020, 0.5020),
1066
+ (0.0510, 0.0222, 0.0222),
1067
+ (0.1098, 1.0000, 1.0000),
1068
+ (0.2039, 1.0000, 1.0000),
1069
+ (0.2627, 0.6145, 0.6145),
1070
+ (0.3216, 0.0000, 0.0000),
1071
+ (0.4157, 0.0000, 0.0000),
1072
+ (0.4745, 0.2342, 0.2342),
1073
+ (0.5333, 0.0000, 0.0000),
1074
+ (0.5804, 0.0000, 0.0000),
1075
+ (0.6314, 0.0549, 0.0549),
1076
+ (0.6902, 0.0000, 0.0000),
1077
+ (0.7373, 0.0000, 0.0000),
1078
+ (0.7922, 0.9738, 0.9738),
1079
+ (0.8000, 1.0000, 1.0000),
1080
+ (0.8431, 1.0000, 1.0000),
1081
+ (0.8980, 0.9341, 0.9341),
1082
+ (1.0000, 0.9961, 0.9961),
1083
+ )
1084
+ }
1085
+
1086
+ _gist_rainbow_data = (
1087
+ (0.000, (1.00, 0.00, 0.16)),
1088
+ (0.030, (1.00, 0.00, 0.00)),
1089
+ (0.215, (1.00, 1.00, 0.00)),
1090
+ (0.400, (0.00, 1.00, 0.00)),
1091
+ (0.586, (0.00, 1.00, 1.00)),
1092
+ (0.770, (0.00, 0.00, 1.00)),
1093
+ (0.954, (1.00, 0.00, 1.00)),
1094
+ (1.000, (1.00, 0.00, 0.75))
1095
+ )
1096
+
1097
+ _gist_stern_data = {
1098
+ 'red': (
1099
+ (0.000, 0.000, 0.000), (0.0547, 1.000, 1.000),
1100
+ (0.250, 0.027, 0.250), # (0.2500, 0.250, 0.250),
1101
+ (1.000, 1.000, 1.000)),
1102
+ 'green': ((0, 0, 0), (1, 1, 1)),
1103
+ 'blue': (
1104
+ (0.000, 0.000, 0.000), (0.500, 1.000, 1.000),
1105
+ (0.735, 0.000, 0.000), (1.000, 1.000, 1.000))
1106
+ }
1107
+
1108
+ def _gist_yarg(x): return 1 - x
1109
+ _gist_yarg_data = {'red': _gist_yarg, 'green': _gist_yarg, 'blue': _gist_yarg}
1110
+
1111
+ # This bipolar colormap was generated from CoolWarmFloat33.csv of
1112
+ # "Diverging Color Maps for Scientific Visualization" by Kenneth Moreland.
1113
+ # <http://www.kennethmoreland.com/color-maps/>
1114
+ _coolwarm_data = {
1115
+ 'red': [
1116
+ (0.0, 0.2298057, 0.2298057),
1117
+ (0.03125, 0.26623388, 0.26623388),
1118
+ (0.0625, 0.30386891, 0.30386891),
1119
+ (0.09375, 0.342804478, 0.342804478),
1120
+ (0.125, 0.38301334, 0.38301334),
1121
+ (0.15625, 0.424369608, 0.424369608),
1122
+ (0.1875, 0.46666708, 0.46666708),
1123
+ (0.21875, 0.509635204, 0.509635204),
1124
+ (0.25, 0.552953156, 0.552953156),
1125
+ (0.28125, 0.596262162, 0.596262162),
1126
+ (0.3125, 0.639176211, 0.639176211),
1127
+ (0.34375, 0.681291281, 0.681291281),
1128
+ (0.375, 0.722193294, 0.722193294),
1129
+ (0.40625, 0.761464949, 0.761464949),
1130
+ (0.4375, 0.798691636, 0.798691636),
1131
+ (0.46875, 0.833466556, 0.833466556),
1132
+ (0.5, 0.865395197, 0.865395197),
1133
+ (0.53125, 0.897787179, 0.897787179),
1134
+ (0.5625, 0.924127593, 0.924127593),
1135
+ (0.59375, 0.944468518, 0.944468518),
1136
+ (0.625, 0.958852946, 0.958852946),
1137
+ (0.65625, 0.96732803, 0.96732803),
1138
+ (0.6875, 0.969954137, 0.969954137),
1139
+ (0.71875, 0.966811177, 0.966811177),
1140
+ (0.75, 0.958003065, 0.958003065),
1141
+ (0.78125, 0.943660866, 0.943660866),
1142
+ (0.8125, 0.923944917, 0.923944917),
1143
+ (0.84375, 0.89904617, 0.89904617),
1144
+ (0.875, 0.869186849, 0.869186849),
1145
+ (0.90625, 0.834620542, 0.834620542),
1146
+ (0.9375, 0.795631745, 0.795631745),
1147
+ (0.96875, 0.752534934, 0.752534934),
1148
+ (1.0, 0.705673158, 0.705673158)],
1149
+ 'green': [
1150
+ (0.0, 0.298717966, 0.298717966),
1151
+ (0.03125, 0.353094838, 0.353094838),
1152
+ (0.0625, 0.406535296, 0.406535296),
1153
+ (0.09375, 0.458757618, 0.458757618),
1154
+ (0.125, 0.50941904, 0.50941904),
1155
+ (0.15625, 0.558148092, 0.558148092),
1156
+ (0.1875, 0.604562568, 0.604562568),
1157
+ (0.21875, 0.648280772, 0.648280772),
1158
+ (0.25, 0.688929332, 0.688929332),
1159
+ (0.28125, 0.726149107, 0.726149107),
1160
+ (0.3125, 0.759599947, 0.759599947),
1161
+ (0.34375, 0.788964712, 0.788964712),
1162
+ (0.375, 0.813952739, 0.813952739),
1163
+ (0.40625, 0.834302879, 0.834302879),
1164
+ (0.4375, 0.849786142, 0.849786142),
1165
+ (0.46875, 0.860207984, 0.860207984),
1166
+ (0.5, 0.86541021, 0.86541021),
1167
+ (0.53125, 0.848937047, 0.848937047),
1168
+ (0.5625, 0.827384882, 0.827384882),
1169
+ (0.59375, 0.800927443, 0.800927443),
1170
+ (0.625, 0.769767752, 0.769767752),
1171
+ (0.65625, 0.734132809, 0.734132809),
1172
+ (0.6875, 0.694266682, 0.694266682),
1173
+ (0.71875, 0.650421156, 0.650421156),
1174
+ (0.75, 0.602842431, 0.602842431),
1175
+ (0.78125, 0.551750968, 0.551750968),
1176
+ (0.8125, 0.49730856, 0.49730856),
1177
+ (0.84375, 0.439559467, 0.439559467),
1178
+ (0.875, 0.378313092, 0.378313092),
1179
+ (0.90625, 0.312874446, 0.312874446),
1180
+ (0.9375, 0.24128379, 0.24128379),
1181
+ (0.96875, 0.157246067, 0.157246067),
1182
+ (1.0, 0.01555616, 0.01555616)],
1183
+ 'blue': [
1184
+ (0.0, 0.753683153, 0.753683153),
1185
+ (0.03125, 0.801466763, 0.801466763),
1186
+ (0.0625, 0.84495867, 0.84495867),
1187
+ (0.09375, 0.883725899, 0.883725899),
1188
+ (0.125, 0.917387822, 0.917387822),
1189
+ (0.15625, 0.945619588, 0.945619588),
1190
+ (0.1875, 0.968154911, 0.968154911),
1191
+ (0.21875, 0.98478814, 0.98478814),
1192
+ (0.25, 0.995375608, 0.995375608),
1193
+ (0.28125, 0.999836203, 0.999836203),
1194
+ (0.3125, 0.998151185, 0.998151185),
1195
+ (0.34375, 0.990363227, 0.990363227),
1196
+ (0.375, 0.976574709, 0.976574709),
1197
+ (0.40625, 0.956945269, 0.956945269),
1198
+ (0.4375, 0.931688648, 0.931688648),
1199
+ (0.46875, 0.901068838, 0.901068838),
1200
+ (0.5, 0.865395561, 0.865395561),
1201
+ (0.53125, 0.820880546, 0.820880546),
1202
+ (0.5625, 0.774508472, 0.774508472),
1203
+ (0.59375, 0.726736146, 0.726736146),
1204
+ (0.625, 0.678007945, 0.678007945),
1205
+ (0.65625, 0.628751763, 0.628751763),
1206
+ (0.6875, 0.579375448, 0.579375448),
1207
+ (0.71875, 0.530263762, 0.530263762),
1208
+ (0.75, 0.481775914, 0.481775914),
1209
+ (0.78125, 0.434243684, 0.434243684),
1210
+ (0.8125, 0.387970225, 0.387970225),
1211
+ (0.84375, 0.343229596, 0.343229596),
1212
+ (0.875, 0.300267182, 0.300267182),
1213
+ (0.90625, 0.259301199, 0.259301199),
1214
+ (0.9375, 0.220525627, 0.220525627),
1215
+ (0.96875, 0.184115123, 0.184115123),
1216
+ (1.0, 0.150232812, 0.150232812)]
1217
+ }
1218
+
1219
+ # Implementation of Carey Rappaport's CMRmap.
1220
+ # See `A Color Map for Effective Black-and-White Rendering of Color-Scale
1221
+ # Images' by Carey Rappaport
1222
+ # https://www.mathworks.com/matlabcentral/fileexchange/2662-cmrmap-m
1223
+ _CMRmap_data = {'red': ((0.000, 0.00, 0.00),
1224
+ (0.125, 0.15, 0.15),
1225
+ (0.250, 0.30, 0.30),
1226
+ (0.375, 0.60, 0.60),
1227
+ (0.500, 1.00, 1.00),
1228
+ (0.625, 0.90, 0.90),
1229
+ (0.750, 0.90, 0.90),
1230
+ (0.875, 0.90, 0.90),
1231
+ (1.000, 1.00, 1.00)),
1232
+ 'green': ((0.000, 0.00, 0.00),
1233
+ (0.125, 0.15, 0.15),
1234
+ (0.250, 0.15, 0.15),
1235
+ (0.375, 0.20, 0.20),
1236
+ (0.500, 0.25, 0.25),
1237
+ (0.625, 0.50, 0.50),
1238
+ (0.750, 0.75, 0.75),
1239
+ (0.875, 0.90, 0.90),
1240
+ (1.000, 1.00, 1.00)),
1241
+ 'blue': ((0.000, 0.00, 0.00),
1242
+ (0.125, 0.50, 0.50),
1243
+ (0.250, 0.75, 0.75),
1244
+ (0.375, 0.50, 0.50),
1245
+ (0.500, 0.15, 0.15),
1246
+ (0.625, 0.00, 0.00),
1247
+ (0.750, 0.10, 0.10),
1248
+ (0.875, 0.50, 0.50),
1249
+ (1.000, 1.00, 1.00))}
1250
+
1251
+
1252
+ # An MIT licensed, colorblind-friendly heatmap from Wistia:
1253
+ # https://github.com/wistia/heatmap-palette
1254
+ # https://wistia.com/learn/culture/heatmaps-for-colorblindness
1255
+ #
1256
+ # >>> import matplotlib.colors as c
1257
+ # >>> colors = ["#e4ff7a", "#ffe81a", "#ffbd00", "#ffa000", "#fc7f00"]
1258
+ # >>> cm = c.LinearSegmentedColormap.from_list('wistia', colors)
1259
+ # >>> _wistia_data = cm._segmentdata
1260
+ # >>> del _wistia_data['alpha']
1261
+ #
1262
+ _wistia_data = {
1263
+ 'red': [(0.0, 0.8941176470588236, 0.8941176470588236),
1264
+ (0.25, 1.0, 1.0),
1265
+ (0.5, 1.0, 1.0),
1266
+ (0.75, 1.0, 1.0),
1267
+ (1.0, 0.9882352941176471, 0.9882352941176471)],
1268
+ 'green': [(0.0, 1.0, 1.0),
1269
+ (0.25, 0.9098039215686274, 0.9098039215686274),
1270
+ (0.5, 0.7411764705882353, 0.7411764705882353),
1271
+ (0.75, 0.6274509803921569, 0.6274509803921569),
1272
+ (1.0, 0.4980392156862745, 0.4980392156862745)],
1273
+ 'blue': [(0.0, 0.47843137254901963, 0.47843137254901963),
1274
+ (0.25, 0.10196078431372549, 0.10196078431372549),
1275
+ (0.5, 0.0, 0.0),
1276
+ (0.75, 0.0, 0.0),
1277
+ (1.0, 0.0, 0.0)],
1278
+ }
1279
+
1280
+
1281
+ # Categorical palettes from Vega:
1282
+ # https://github.com/vega/vega/wiki/Scales
1283
+ # (divided by 255)
1284
+ #
1285
+
1286
+ _tab10_data = (
1287
+ (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4
1288
+ (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e
1289
+ (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c
1290
+ (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728
1291
+ (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd
1292
+ (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b
1293
+ (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2
1294
+ (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f
1295
+ (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22
1296
+ (0.09019607843137255, 0.7450980392156863, 0.8117647058823529), # 17becf
1297
+ )
1298
+
1299
+ _tab20_data = (
1300
+ (0.12156862745098039, 0.4666666666666667, 0.7058823529411765 ), # 1f77b4
1301
+ (0.6823529411764706, 0.7803921568627451, 0.9098039215686274 ), # aec7e8
1302
+ (1.0, 0.4980392156862745, 0.054901960784313725), # ff7f0e
1303
+ (1.0, 0.7333333333333333, 0.47058823529411764 ), # ffbb78
1304
+ (0.17254901960784313, 0.6274509803921569, 0.17254901960784313 ), # 2ca02c
1305
+ (0.596078431372549, 0.8745098039215686, 0.5411764705882353 ), # 98df8a
1306
+ (0.8392156862745098, 0.15294117647058825, 0.1568627450980392 ), # d62728
1307
+ (1.0, 0.596078431372549, 0.5882352941176471 ), # ff9896
1308
+ (0.5803921568627451, 0.403921568627451, 0.7411764705882353 ), # 9467bd
1309
+ (0.7725490196078432, 0.6901960784313725, 0.8352941176470589 ), # c5b0d5
1310
+ (0.5490196078431373, 0.33725490196078434, 0.29411764705882354 ), # 8c564b
1311
+ (0.7686274509803922, 0.611764705882353, 0.5803921568627451 ), # c49c94
1312
+ (0.8901960784313725, 0.4666666666666667, 0.7607843137254902 ), # e377c2
1313
+ (0.9686274509803922, 0.7137254901960784, 0.8235294117647058 ), # f7b6d2
1314
+ (0.4980392156862745, 0.4980392156862745, 0.4980392156862745 ), # 7f7f7f
1315
+ (0.7803921568627451, 0.7803921568627451, 0.7803921568627451 ), # c7c7c7
1316
+ (0.7372549019607844, 0.7411764705882353, 0.13333333333333333 ), # bcbd22
1317
+ (0.8588235294117647, 0.8588235294117647, 0.5529411764705883 ), # dbdb8d
1318
+ (0.09019607843137255, 0.7450980392156863, 0.8117647058823529 ), # 17becf
1319
+ (0.6196078431372549, 0.8549019607843137, 0.8980392156862745), # 9edae5
1320
+ )
1321
+
1322
+ _tab20b_data = (
1323
+ (0.2235294117647059, 0.23137254901960785, 0.4745098039215686 ), # 393b79
1324
+ (0.3215686274509804, 0.32941176470588235, 0.6392156862745098 ), # 5254a3
1325
+ (0.4196078431372549, 0.43137254901960786, 0.8117647058823529 ), # 6b6ecf
1326
+ (0.611764705882353, 0.6196078431372549, 0.8705882352941177 ), # 9c9ede
1327
+ (0.38823529411764707, 0.4745098039215686, 0.2235294117647059 ), # 637939
1328
+ (0.5490196078431373, 0.6352941176470588, 0.3215686274509804 ), # 8ca252
1329
+ (0.7098039215686275, 0.8117647058823529, 0.4196078431372549 ), # b5cf6b
1330
+ (0.807843137254902, 0.8588235294117647, 0.611764705882353 ), # cedb9c
1331
+ (0.5490196078431373, 0.42745098039215684, 0.19215686274509805), # 8c6d31
1332
+ (0.7411764705882353, 0.6196078431372549, 0.2235294117647059 ), # bd9e39
1333
+ (0.9058823529411765, 0.7294117647058823, 0.3215686274509804 ), # e7ba52
1334
+ (0.9058823529411765, 0.796078431372549, 0.5803921568627451 ), # e7cb94
1335
+ (0.5176470588235295, 0.23529411764705882, 0.2235294117647059 ), # 843c39
1336
+ (0.6784313725490196, 0.28627450980392155, 0.2901960784313726 ), # ad494a
1337
+ (0.8392156862745098, 0.3803921568627451, 0.4196078431372549 ), # d6616b
1338
+ (0.9058823529411765, 0.5882352941176471, 0.611764705882353 ), # e7969c
1339
+ (0.4823529411764706, 0.2549019607843137, 0.45098039215686275), # 7b4173
1340
+ (0.6470588235294118, 0.3176470588235294, 0.5803921568627451 ), # a55194
1341
+ (0.807843137254902, 0.42745098039215684, 0.7411764705882353 ), # ce6dbd
1342
+ (0.8705882352941177, 0.6196078431372549, 0.8392156862745098 ), # de9ed6
1343
+ )
1344
+
1345
+ _tab20c_data = (
1346
+ (0.19215686274509805, 0.5098039215686274, 0.7411764705882353 ), # 3182bd
1347
+ (0.4196078431372549, 0.6823529411764706, 0.8392156862745098 ), # 6baed6
1348
+ (0.6196078431372549, 0.792156862745098, 0.8823529411764706 ), # 9ecae1
1349
+ (0.7764705882352941, 0.8588235294117647, 0.9372549019607843 ), # c6dbef
1350
+ (0.9019607843137255, 0.3333333333333333, 0.050980392156862744), # e6550d
1351
+ (0.9921568627450981, 0.5529411764705883, 0.23529411764705882 ), # fd8d3c
1352
+ (0.9921568627450981, 0.6823529411764706, 0.4196078431372549 ), # fdae6b
1353
+ (0.9921568627450981, 0.8156862745098039, 0.6352941176470588 ), # fdd0a2
1354
+ (0.19215686274509805, 0.6392156862745098, 0.32941176470588235 ), # 31a354
1355
+ (0.4549019607843137, 0.7686274509803922, 0.4627450980392157 ), # 74c476
1356
+ (0.6313725490196078, 0.8509803921568627, 0.6078431372549019 ), # a1d99b
1357
+ (0.7803921568627451, 0.9137254901960784, 0.7529411764705882 ), # c7e9c0
1358
+ (0.4588235294117647, 0.4196078431372549, 0.6941176470588235 ), # 756bb1
1359
+ (0.6196078431372549, 0.6039215686274509, 0.7843137254901961 ), # 9e9ac8
1360
+ (0.7372549019607844, 0.7411764705882353, 0.8627450980392157 ), # bcbddc
1361
+ (0.8549019607843137, 0.8549019607843137, 0.9215686274509803 ), # dadaeb
1362
+ (0.38823529411764707, 0.38823529411764707, 0.38823529411764707 ), # 636363
1363
+ (0.5882352941176471, 0.5882352941176471, 0.5882352941176471 ), # 969696
1364
+ (0.7411764705882353, 0.7411764705882353, 0.7411764705882353 ), # bdbdbd
1365
+ (0.8509803921568627, 0.8509803921568627, 0.8509803921568627 ), # d9d9d9
1366
+ )
1367
+
1368
+
1369
+ datad = {
1370
+ 'Blues': _Blues_data,
1371
+ 'BrBG': _BrBG_data,
1372
+ 'BuGn': _BuGn_data,
1373
+ 'BuPu': _BuPu_data,
1374
+ 'CMRmap': _CMRmap_data,
1375
+ 'GnBu': _GnBu_data,
1376
+ 'Greens': _Greens_data,
1377
+ 'Greys': _Greys_data,
1378
+ 'OrRd': _OrRd_data,
1379
+ 'Oranges': _Oranges_data,
1380
+ 'PRGn': _PRGn_data,
1381
+ 'PiYG': _PiYG_data,
1382
+ 'PuBu': _PuBu_data,
1383
+ 'PuBuGn': _PuBuGn_data,
1384
+ 'PuOr': _PuOr_data,
1385
+ 'PuRd': _PuRd_data,
1386
+ 'Purples': _Purples_data,
1387
+ 'RdBu': _RdBu_data,
1388
+ 'RdGy': _RdGy_data,
1389
+ 'RdPu': _RdPu_data,
1390
+ 'RdYlBu': _RdYlBu_data,
1391
+ 'RdYlGn': _RdYlGn_data,
1392
+ 'Reds': _Reds_data,
1393
+ 'Spectral': _Spectral_data,
1394
+ 'Wistia': _wistia_data,
1395
+ 'YlGn': _YlGn_data,
1396
+ 'YlGnBu': _YlGnBu_data,
1397
+ 'YlOrBr': _YlOrBr_data,
1398
+ 'YlOrRd': _YlOrRd_data,
1399
+ 'afmhot': _afmhot_data,
1400
+ 'autumn': _autumn_data,
1401
+ 'binary': _binary_data,
1402
+ 'bone': _bone_data,
1403
+ 'brg': _brg_data,
1404
+ 'bwr': _bwr_data,
1405
+ 'cool': _cool_data,
1406
+ 'coolwarm': _coolwarm_data,
1407
+ 'copper': _copper_data,
1408
+ 'cubehelix': _cubehelix_data,
1409
+ 'flag': _flag_data,
1410
+ 'gist_earth': _gist_earth_data,
1411
+ 'gist_gray': _gist_gray_data,
1412
+ 'gist_heat': _gist_heat_data,
1413
+ 'gist_ncar': _gist_ncar_data,
1414
+ 'gist_rainbow': _gist_rainbow_data,
1415
+ 'gist_stern': _gist_stern_data,
1416
+ 'gist_yarg': _gist_yarg_data,
1417
+ 'gnuplot': _gnuplot_data,
1418
+ 'gnuplot2': _gnuplot2_data,
1419
+ 'gray': _gray_data,
1420
+ 'hot': _hot_data,
1421
+ 'hsv': _hsv_data,
1422
+ 'jet': _jet_data,
1423
+ 'nipy_spectral': _nipy_spectral_data,
1424
+ 'ocean': _ocean_data,
1425
+ 'pink': _pink_data,
1426
+ 'prism': _prism_data,
1427
+ 'rainbow': _rainbow_data,
1428
+ 'seismic': _seismic_data,
1429
+ 'spring': _spring_data,
1430
+ 'summer': _summer_data,
1431
+ 'terrain': _terrain_data,
1432
+ 'winter': _winter_data,
1433
+ # Qualitative
1434
+ 'Accent': {'listed': _Accent_data},
1435
+ 'Dark2': {'listed': _Dark2_data},
1436
+ 'Paired': {'listed': _Paired_data},
1437
+ 'Pastel1': {'listed': _Pastel1_data},
1438
+ 'Pastel2': {'listed': _Pastel2_data},
1439
+ 'Set1': {'listed': _Set1_data},
1440
+ 'Set2': {'listed': _Set2_data},
1441
+ 'Set3': {'listed': _Set3_data},
1442
+ 'tab10': {'listed': _tab10_data},
1443
+ 'tab20': {'listed': _tab20_data},
1444
+ 'tab20b': {'listed': _tab20b_data},
1445
+ 'tab20c': {'listed': _tab20c_data},
1446
+ }
llava_next/lib/python3.10/site-packages/matplotlib/_cm_listed.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/matplotlib/_color_data.py ADDED
@@ -0,0 +1,1141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BASE_COLORS = {
2
+ 'b': (0, 0, 1), # blue
3
+ 'g': (0, 0.5, 0), # green
4
+ 'r': (1, 0, 0), # red
5
+ 'c': (0, 0.75, 0.75), # cyan
6
+ 'm': (0.75, 0, 0.75), # magenta
7
+ 'y': (0.75, 0.75, 0), # yellow
8
+ 'k': (0, 0, 0), # black
9
+ 'w': (1, 1, 1), # white
10
+ }
11
+
12
+
13
+ # These colors are from Tableau
14
+ TABLEAU_COLORS = {
15
+ 'tab:blue': '#1f77b4',
16
+ 'tab:orange': '#ff7f0e',
17
+ 'tab:green': '#2ca02c',
18
+ 'tab:red': '#d62728',
19
+ 'tab:purple': '#9467bd',
20
+ 'tab:brown': '#8c564b',
21
+ 'tab:pink': '#e377c2',
22
+ 'tab:gray': '#7f7f7f',
23
+ 'tab:olive': '#bcbd22',
24
+ 'tab:cyan': '#17becf',
25
+ }
26
+
27
+
28
+ # This mapping of color names -> hex values is taken from
29
+ # a survey run by Randall Munroe see:
30
+ # https://blog.xkcd.com/2010/05/03/color-survey-results/
31
+ # for more details. The results are hosted at
32
+ # https://xkcd.com/color/rgb/
33
+ # and also available as a text file at
34
+ # https://xkcd.com/color/rgb.txt
35
+ #
36
+ # License: https://creativecommons.org/publicdomain/zero/1.0/
37
+ XKCD_COLORS = {
38
+ 'cloudy blue': '#acc2d9',
39
+ 'dark pastel green': '#56ae57',
40
+ 'dust': '#b2996e',
41
+ 'electric lime': '#a8ff04',
42
+ 'fresh green': '#69d84f',
43
+ 'light eggplant': '#894585',
44
+ 'nasty green': '#70b23f',
45
+ 'really light blue': '#d4ffff',
46
+ 'tea': '#65ab7c',
47
+ 'warm purple': '#952e8f',
48
+ 'yellowish tan': '#fcfc81',
49
+ 'cement': '#a5a391',
50
+ 'dark grass green': '#388004',
51
+ 'dusty teal': '#4c9085',
52
+ 'grey teal': '#5e9b8a',
53
+ 'macaroni and cheese': '#efb435',
54
+ 'pinkish tan': '#d99b82',
55
+ 'spruce': '#0a5f38',
56
+ 'strong blue': '#0c06f7',
57
+ 'toxic green': '#61de2a',
58
+ 'windows blue': '#3778bf',
59
+ 'blue blue': '#2242c7',
60
+ 'blue with a hint of purple': '#533cc6',
61
+ 'booger': '#9bb53c',
62
+ 'bright sea green': '#05ffa6',
63
+ 'dark green blue': '#1f6357',
64
+ 'deep turquoise': '#017374',
65
+ 'green teal': '#0cb577',
66
+ 'strong pink': '#ff0789',
67
+ 'bland': '#afa88b',
68
+ 'deep aqua': '#08787f',
69
+ 'lavender pink': '#dd85d7',
70
+ 'light moss green': '#a6c875',
71
+ 'light seafoam green': '#a7ffb5',
72
+ 'olive yellow': '#c2b709',
73
+ 'pig pink': '#e78ea5',
74
+ 'deep lilac': '#966ebd',
75
+ 'desert': '#ccad60',
76
+ 'dusty lavender': '#ac86a8',
77
+ 'purpley grey': '#947e94',
78
+ 'purply': '#983fb2',
79
+ 'candy pink': '#ff63e9',
80
+ 'light pastel green': '#b2fba5',
81
+ 'boring green': '#63b365',
82
+ 'kiwi green': '#8ee53f',
83
+ 'light grey green': '#b7e1a1',
84
+ 'orange pink': '#ff6f52',
85
+ 'tea green': '#bdf8a3',
86
+ 'very light brown': '#d3b683',
87
+ 'egg shell': '#fffcc4',
88
+ 'eggplant purple': '#430541',
89
+ 'powder pink': '#ffb2d0',
90
+ 'reddish grey': '#997570',
91
+ 'baby shit brown': '#ad900d',
92
+ 'liliac': '#c48efd',
93
+ 'stormy blue': '#507b9c',
94
+ 'ugly brown': '#7d7103',
95
+ 'custard': '#fffd78',
96
+ 'darkish pink': '#da467d',
97
+ 'deep brown': '#410200',
98
+ 'greenish beige': '#c9d179',
99
+ 'manilla': '#fffa86',
100
+ 'off blue': '#5684ae',
101
+ 'battleship grey': '#6b7c85',
102
+ 'browny green': '#6f6c0a',
103
+ 'bruise': '#7e4071',
104
+ 'kelley green': '#009337',
105
+ 'sickly yellow': '#d0e429',
106
+ 'sunny yellow': '#fff917',
107
+ 'azul': '#1d5dec',
108
+ 'darkgreen': '#054907',
109
+ 'green/yellow': '#b5ce08',
110
+ 'lichen': '#8fb67b',
111
+ 'light light green': '#c8ffb0',
112
+ 'pale gold': '#fdde6c',
113
+ 'sun yellow': '#ffdf22',
114
+ 'tan green': '#a9be70',
115
+ 'burple': '#6832e3',
116
+ 'butterscotch': '#fdb147',
117
+ 'toupe': '#c7ac7d',
118
+ 'dark cream': '#fff39a',
119
+ 'indian red': '#850e04',
120
+ 'light lavendar': '#efc0fe',
121
+ 'poison green': '#40fd14',
122
+ 'baby puke green': '#b6c406',
123
+ 'bright yellow green': '#9dff00',
124
+ 'charcoal grey': '#3c4142',
125
+ 'squash': '#f2ab15',
126
+ 'cinnamon': '#ac4f06',
127
+ 'light pea green': '#c4fe82',
128
+ 'radioactive green': '#2cfa1f',
129
+ 'raw sienna': '#9a6200',
130
+ 'baby purple': '#ca9bf7',
131
+ 'cocoa': '#875f42',
132
+ 'light royal blue': '#3a2efe',
133
+ 'orangeish': '#fd8d49',
134
+ 'rust brown': '#8b3103',
135
+ 'sand brown': '#cba560',
136
+ 'swamp': '#698339',
137
+ 'tealish green': '#0cdc73',
138
+ 'burnt siena': '#b75203',
139
+ 'camo': '#7f8f4e',
140
+ 'dusk blue': '#26538d',
141
+ 'fern': '#63a950',
142
+ 'old rose': '#c87f89',
143
+ 'pale light green': '#b1fc99',
144
+ 'peachy pink': '#ff9a8a',
145
+ 'rosy pink': '#f6688e',
146
+ 'light bluish green': '#76fda8',
147
+ 'light bright green': '#53fe5c',
148
+ 'light neon green': '#4efd54',
149
+ 'light seafoam': '#a0febf',
150
+ 'tiffany blue': '#7bf2da',
151
+ 'washed out green': '#bcf5a6',
152
+ 'browny orange': '#ca6b02',
153
+ 'nice blue': '#107ab0',
154
+ 'sapphire': '#2138ab',
155
+ 'greyish teal': '#719f91',
156
+ 'orangey yellow': '#fdb915',
157
+ 'parchment': '#fefcaf',
158
+ 'straw': '#fcf679',
159
+ 'very dark brown': '#1d0200',
160
+ 'terracota': '#cb6843',
161
+ 'ugly blue': '#31668a',
162
+ 'clear blue': '#247afd',
163
+ 'creme': '#ffffb6',
164
+ 'foam green': '#90fda9',
165
+ 'grey/green': '#86a17d',
166
+ 'light gold': '#fddc5c',
167
+ 'seafoam blue': '#78d1b6',
168
+ 'topaz': '#13bbaf',
169
+ 'violet pink': '#fb5ffc',
170
+ 'wintergreen': '#20f986',
171
+ 'yellow tan': '#ffe36e',
172
+ 'dark fuchsia': '#9d0759',
173
+ 'indigo blue': '#3a18b1',
174
+ 'light yellowish green': '#c2ff89',
175
+ 'pale magenta': '#d767ad',
176
+ 'rich purple': '#720058',
177
+ 'sunflower yellow': '#ffda03',
178
+ 'green/blue': '#01c08d',
179
+ 'leather': '#ac7434',
180
+ 'racing green': '#014600',
181
+ 'vivid purple': '#9900fa',
182
+ 'dark royal blue': '#02066f',
183
+ 'hazel': '#8e7618',
184
+ 'muted pink': '#d1768f',
185
+ 'booger green': '#96b403',
186
+ 'canary': '#fdff63',
187
+ 'cool grey': '#95a3a6',
188
+ 'dark taupe': '#7f684e',
189
+ 'darkish purple': '#751973',
190
+ 'true green': '#089404',
191
+ 'coral pink': '#ff6163',
192
+ 'dark sage': '#598556',
193
+ 'dark slate blue': '#214761',
194
+ 'flat blue': '#3c73a8',
195
+ 'mushroom': '#ba9e88',
196
+ 'rich blue': '#021bf9',
197
+ 'dirty purple': '#734a65',
198
+ 'greenblue': '#23c48b',
199
+ 'icky green': '#8fae22',
200
+ 'light khaki': '#e6f2a2',
201
+ 'warm blue': '#4b57db',
202
+ 'dark hot pink': '#d90166',
203
+ 'deep sea blue': '#015482',
204
+ 'carmine': '#9d0216',
205
+ 'dark yellow green': '#728f02',
206
+ 'pale peach': '#ffe5ad',
207
+ 'plum purple': '#4e0550',
208
+ 'golden rod': '#f9bc08',
209
+ 'neon red': '#ff073a',
210
+ 'old pink': '#c77986',
211
+ 'very pale blue': '#d6fffe',
212
+ 'blood orange': '#fe4b03',
213
+ 'grapefruit': '#fd5956',
214
+ 'sand yellow': '#fce166',
215
+ 'clay brown': '#b2713d',
216
+ 'dark blue grey': '#1f3b4d',
217
+ 'flat green': '#699d4c',
218
+ 'light green blue': '#56fca2',
219
+ 'warm pink': '#fb5581',
220
+ 'dodger blue': '#3e82fc',
221
+ 'gross green': '#a0bf16',
222
+ 'ice': '#d6fffa',
223
+ 'metallic blue': '#4f738e',
224
+ 'pale salmon': '#ffb19a',
225
+ 'sap green': '#5c8b15',
226
+ 'algae': '#54ac68',
227
+ 'bluey grey': '#89a0b0',
228
+ 'greeny grey': '#7ea07a',
229
+ 'highlighter green': '#1bfc06',
230
+ 'light light blue': '#cafffb',
231
+ 'light mint': '#b6ffbb',
232
+ 'raw umber': '#a75e09',
233
+ 'vivid blue': '#152eff',
234
+ 'deep lavender': '#8d5eb7',
235
+ 'dull teal': '#5f9e8f',
236
+ 'light greenish blue': '#63f7b4',
237
+ 'mud green': '#606602',
238
+ 'pinky': '#fc86aa',
239
+ 'red wine': '#8c0034',
240
+ 'shit green': '#758000',
241
+ 'tan brown': '#ab7e4c',
242
+ 'darkblue': '#030764',
243
+ 'rosa': '#fe86a4',
244
+ 'lipstick': '#d5174e',
245
+ 'pale mauve': '#fed0fc',
246
+ 'claret': '#680018',
247
+ 'dandelion': '#fedf08',
248
+ 'orangered': '#fe420f',
249
+ 'poop green': '#6f7c00',
250
+ 'ruby': '#ca0147',
251
+ 'dark': '#1b2431',
252
+ 'greenish turquoise': '#00fbb0',
253
+ 'pastel red': '#db5856',
254
+ 'piss yellow': '#ddd618',
255
+ 'bright cyan': '#41fdfe',
256
+ 'dark coral': '#cf524e',
257
+ 'algae green': '#21c36f',
258
+ 'darkish red': '#a90308',
259
+ 'reddy brown': '#6e1005',
260
+ 'blush pink': '#fe828c',
261
+ 'camouflage green': '#4b6113',
262
+ 'lawn green': '#4da409',
263
+ 'putty': '#beae8a',
264
+ 'vibrant blue': '#0339f8',
265
+ 'dark sand': '#a88f59',
266
+ 'purple/blue': '#5d21d0',
267
+ 'saffron': '#feb209',
268
+ 'twilight': '#4e518b',
269
+ 'warm brown': '#964e02',
270
+ 'bluegrey': '#85a3b2',
271
+ 'bubble gum pink': '#ff69af',
272
+ 'duck egg blue': '#c3fbf4',
273
+ 'greenish cyan': '#2afeb7',
274
+ 'petrol': '#005f6a',
275
+ 'royal': '#0c1793',
276
+ 'butter': '#ffff81',
277
+ 'dusty orange': '#f0833a',
278
+ 'off yellow': '#f1f33f',
279
+ 'pale olive green': '#b1d27b',
280
+ 'orangish': '#fc824a',
281
+ 'leaf': '#71aa34',
282
+ 'light blue grey': '#b7c9e2',
283
+ 'dried blood': '#4b0101',
284
+ 'lightish purple': '#a552e6',
285
+ 'rusty red': '#af2f0d',
286
+ 'lavender blue': '#8b88f8',
287
+ 'light grass green': '#9af764',
288
+ 'light mint green': '#a6fbb2',
289
+ 'sunflower': '#ffc512',
290
+ 'velvet': '#750851',
291
+ 'brick orange': '#c14a09',
292
+ 'lightish red': '#fe2f4a',
293
+ 'pure blue': '#0203e2',
294
+ 'twilight blue': '#0a437a',
295
+ 'violet red': '#a50055',
296
+ 'yellowy brown': '#ae8b0c',
297
+ 'carnation': '#fd798f',
298
+ 'muddy yellow': '#bfac05',
299
+ 'dark seafoam green': '#3eaf76',
300
+ 'deep rose': '#c74767',
301
+ 'dusty red': '#b9484e',
302
+ 'grey/blue': '#647d8e',
303
+ 'lemon lime': '#bffe28',
304
+ 'purple/pink': '#d725de',
305
+ 'brown yellow': '#b29705',
306
+ 'purple brown': '#673a3f',
307
+ 'wisteria': '#a87dc2',
308
+ 'banana yellow': '#fafe4b',
309
+ 'lipstick red': '#c0022f',
310
+ 'water blue': '#0e87cc',
311
+ 'brown grey': '#8d8468',
312
+ 'vibrant purple': '#ad03de',
313
+ 'baby green': '#8cff9e',
314
+ 'barf green': '#94ac02',
315
+ 'eggshell blue': '#c4fff7',
316
+ 'sandy yellow': '#fdee73',
317
+ 'cool green': '#33b864',
318
+ 'pale': '#fff9d0',
319
+ 'blue/grey': '#758da3',
320
+ 'hot magenta': '#f504c9',
321
+ 'greyblue': '#77a1b5',
322
+ 'purpley': '#8756e4',
323
+ 'baby shit green': '#889717',
324
+ 'brownish pink': '#c27e79',
325
+ 'dark aquamarine': '#017371',
326
+ 'diarrhea': '#9f8303',
327
+ 'light mustard': '#f7d560',
328
+ 'pale sky blue': '#bdf6fe',
329
+ 'turtle green': '#75b84f',
330
+ 'bright olive': '#9cbb04',
331
+ 'dark grey blue': '#29465b',
332
+ 'greeny brown': '#696006',
333
+ 'lemon green': '#adf802',
334
+ 'light periwinkle': '#c1c6fc',
335
+ 'seaweed green': '#35ad6b',
336
+ 'sunshine yellow': '#fffd37',
337
+ 'ugly purple': '#a442a0',
338
+ 'medium pink': '#f36196',
339
+ 'puke brown': '#947706',
340
+ 'very light pink': '#fff4f2',
341
+ 'viridian': '#1e9167',
342
+ 'bile': '#b5c306',
343
+ 'faded yellow': '#feff7f',
344
+ 'very pale green': '#cffdbc',
345
+ 'vibrant green': '#0add08',
346
+ 'bright lime': '#87fd05',
347
+ 'spearmint': '#1ef876',
348
+ 'light aquamarine': '#7bfdc7',
349
+ 'light sage': '#bcecac',
350
+ 'yellowgreen': '#bbf90f',
351
+ 'baby poo': '#ab9004',
352
+ 'dark seafoam': '#1fb57a',
353
+ 'deep teal': '#00555a',
354
+ 'heather': '#a484ac',
355
+ 'rust orange': '#c45508',
356
+ 'dirty blue': '#3f829d',
357
+ 'fern green': '#548d44',
358
+ 'bright lilac': '#c95efb',
359
+ 'weird green': '#3ae57f',
360
+ 'peacock blue': '#016795',
361
+ 'avocado green': '#87a922',
362
+ 'faded orange': '#f0944d',
363
+ 'grape purple': '#5d1451',
364
+ 'hot green': '#25ff29',
365
+ 'lime yellow': '#d0fe1d',
366
+ 'mango': '#ffa62b',
367
+ 'shamrock': '#01b44c',
368
+ 'bubblegum': '#ff6cb5',
369
+ 'purplish brown': '#6b4247',
370
+ 'vomit yellow': '#c7c10c',
371
+ 'pale cyan': '#b7fffa',
372
+ 'key lime': '#aeff6e',
373
+ 'tomato red': '#ec2d01',
374
+ 'lightgreen': '#76ff7b',
375
+ 'merlot': '#730039',
376
+ 'night blue': '#040348',
377
+ 'purpleish pink': '#df4ec8',
378
+ 'apple': '#6ecb3c',
379
+ 'baby poop green': '#8f9805',
380
+ 'green apple': '#5edc1f',
381
+ 'heliotrope': '#d94ff5',
382
+ 'yellow/green': '#c8fd3d',
383
+ 'almost black': '#070d0d',
384
+ 'cool blue': '#4984b8',
385
+ 'leafy green': '#51b73b',
386
+ 'mustard brown': '#ac7e04',
387
+ 'dusk': '#4e5481',
388
+ 'dull brown': '#876e4b',
389
+ 'frog green': '#58bc08',
390
+ 'vivid green': '#2fef10',
391
+ 'bright light green': '#2dfe54',
392
+ 'fluro green': '#0aff02',
393
+ 'kiwi': '#9cef43',
394
+ 'seaweed': '#18d17b',
395
+ 'navy green': '#35530a',
396
+ 'ultramarine blue': '#1805db',
397
+ 'iris': '#6258c4',
398
+ 'pastel orange': '#ff964f',
399
+ 'yellowish orange': '#ffab0f',
400
+ 'perrywinkle': '#8f8ce7',
401
+ 'tealish': '#24bca8',
402
+ 'dark plum': '#3f012c',
403
+ 'pear': '#cbf85f',
404
+ 'pinkish orange': '#ff724c',
405
+ 'midnight purple': '#280137',
406
+ 'light urple': '#b36ff6',
407
+ 'dark mint': '#48c072',
408
+ 'greenish tan': '#bccb7a',
409
+ 'light burgundy': '#a8415b',
410
+ 'turquoise blue': '#06b1c4',
411
+ 'ugly pink': '#cd7584',
412
+ 'sandy': '#f1da7a',
413
+ 'electric pink': '#ff0490',
414
+ 'muted purple': '#805b87',
415
+ 'mid green': '#50a747',
416
+ 'greyish': '#a8a495',
417
+ 'neon yellow': '#cfff04',
418
+ 'banana': '#ffff7e',
419
+ 'carnation pink': '#ff7fa7',
420
+ 'tomato': '#ef4026',
421
+ 'sea': '#3c9992',
422
+ 'muddy brown': '#886806',
423
+ 'turquoise green': '#04f489',
424
+ 'buff': '#fef69e',
425
+ 'fawn': '#cfaf7b',
426
+ 'muted blue': '#3b719f',
427
+ 'pale rose': '#fdc1c5',
428
+ 'dark mint green': '#20c073',
429
+ 'amethyst': '#9b5fc0',
430
+ 'blue/green': '#0f9b8e',
431
+ 'chestnut': '#742802',
432
+ 'sick green': '#9db92c',
433
+ 'pea': '#a4bf20',
434
+ 'rusty orange': '#cd5909',
435
+ 'stone': '#ada587',
436
+ 'rose red': '#be013c',
437
+ 'pale aqua': '#b8ffeb',
438
+ 'deep orange': '#dc4d01',
439
+ 'earth': '#a2653e',
440
+ 'mossy green': '#638b27',
441
+ 'grassy green': '#419c03',
442
+ 'pale lime green': '#b1ff65',
443
+ 'light grey blue': '#9dbcd4',
444
+ 'pale grey': '#fdfdfe',
445
+ 'asparagus': '#77ab56',
446
+ 'blueberry': '#464196',
447
+ 'purple red': '#990147',
448
+ 'pale lime': '#befd73',
449
+ 'greenish teal': '#32bf84',
450
+ 'caramel': '#af6f09',
451
+ 'deep magenta': '#a0025c',
452
+ 'light peach': '#ffd8b1',
453
+ 'milk chocolate': '#7f4e1e',
454
+ 'ocher': '#bf9b0c',
455
+ 'off green': '#6ba353',
456
+ 'purply pink': '#f075e6',
457
+ 'lightblue': '#7bc8f6',
458
+ 'dusky blue': '#475f94',
459
+ 'golden': '#f5bf03',
460
+ 'light beige': '#fffeb6',
461
+ 'butter yellow': '#fffd74',
462
+ 'dusky purple': '#895b7b',
463
+ 'french blue': '#436bad',
464
+ 'ugly yellow': '#d0c101',
465
+ 'greeny yellow': '#c6f808',
466
+ 'orangish red': '#f43605',
467
+ 'shamrock green': '#02c14d',
468
+ 'orangish brown': '#b25f03',
469
+ 'tree green': '#2a7e19',
470
+ 'deep violet': '#490648',
471
+ 'gunmetal': '#536267',
472
+ 'blue/purple': '#5a06ef',
473
+ 'cherry': '#cf0234',
474
+ 'sandy brown': '#c4a661',
475
+ 'warm grey': '#978a84',
476
+ 'dark indigo': '#1f0954',
477
+ 'midnight': '#03012d',
478
+ 'bluey green': '#2bb179',
479
+ 'grey pink': '#c3909b',
480
+ 'soft purple': '#a66fb5',
481
+ 'blood': '#770001',
482
+ 'brown red': '#922b05',
483
+ 'medium grey': '#7d7f7c',
484
+ 'berry': '#990f4b',
485
+ 'poo': '#8f7303',
486
+ 'purpley pink': '#c83cb9',
487
+ 'light salmon': '#fea993',
488
+ 'snot': '#acbb0d',
489
+ 'easter purple': '#c071fe',
490
+ 'light yellow green': '#ccfd7f',
491
+ 'dark navy blue': '#00022e',
492
+ 'drab': '#828344',
493
+ 'light rose': '#ffc5cb',
494
+ 'rouge': '#ab1239',
495
+ 'purplish red': '#b0054b',
496
+ 'slime green': '#99cc04',
497
+ 'baby poop': '#937c00',
498
+ 'irish green': '#019529',
499
+ 'pink/purple': '#ef1de7',
500
+ 'dark navy': '#000435',
501
+ 'greeny blue': '#42b395',
502
+ 'light plum': '#9d5783',
503
+ 'pinkish grey': '#c8aca9',
504
+ 'dirty orange': '#c87606',
505
+ 'rust red': '#aa2704',
506
+ 'pale lilac': '#e4cbff',
507
+ 'orangey red': '#fa4224',
508
+ 'primary blue': '#0804f9',
509
+ 'kermit green': '#5cb200',
510
+ 'brownish purple': '#76424e',
511
+ 'murky green': '#6c7a0e',
512
+ 'wheat': '#fbdd7e',
513
+ 'very dark purple': '#2a0134',
514
+ 'bottle green': '#044a05',
515
+ 'watermelon': '#fd4659',
516
+ 'deep sky blue': '#0d75f8',
517
+ 'fire engine red': '#fe0002',
518
+ 'yellow ochre': '#cb9d06',
519
+ 'pumpkin orange': '#fb7d07',
520
+ 'pale olive': '#b9cc81',
521
+ 'light lilac': '#edc8ff',
522
+ 'lightish green': '#61e160',
523
+ 'carolina blue': '#8ab8fe',
524
+ 'mulberry': '#920a4e',
525
+ 'shocking pink': '#fe02a2',
526
+ 'auburn': '#9a3001',
527
+ 'bright lime green': '#65fe08',
528
+ 'celadon': '#befdb7',
529
+ 'pinkish brown': '#b17261',
530
+ 'poo brown': '#885f01',
531
+ 'bright sky blue': '#02ccfe',
532
+ 'celery': '#c1fd95',
533
+ 'dirt brown': '#836539',
534
+ 'strawberry': '#fb2943',
535
+ 'dark lime': '#84b701',
536
+ 'copper': '#b66325',
537
+ 'medium brown': '#7f5112',
538
+ 'muted green': '#5fa052',
539
+ "robin's egg": '#6dedfd',
540
+ 'bright aqua': '#0bf9ea',
541
+ 'bright lavender': '#c760ff',
542
+ 'ivory': '#ffffcb',
543
+ 'very light purple': '#f6cefc',
544
+ 'light navy': '#155084',
545
+ 'pink red': '#f5054f',
546
+ 'olive brown': '#645403',
547
+ 'poop brown': '#7a5901',
548
+ 'mustard green': '#a8b504',
549
+ 'ocean green': '#3d9973',
550
+ 'very dark blue': '#000133',
551
+ 'dusty green': '#76a973',
552
+ 'light navy blue': '#2e5a88',
553
+ 'minty green': '#0bf77d',
554
+ 'adobe': '#bd6c48',
555
+ 'barney': '#ac1db8',
556
+ 'jade green': '#2baf6a',
557
+ 'bright light blue': '#26f7fd',
558
+ 'light lime': '#aefd6c',
559
+ 'dark khaki': '#9b8f55',
560
+ 'orange yellow': '#ffad01',
561
+ 'ocre': '#c69c04',
562
+ 'maize': '#f4d054',
563
+ 'faded pink': '#de9dac',
564
+ 'british racing green': '#05480d',
565
+ 'sandstone': '#c9ae74',
566
+ 'mud brown': '#60460f',
567
+ 'light sea green': '#98f6b0',
568
+ 'robin egg blue': '#8af1fe',
569
+ 'aqua marine': '#2ee8bb',
570
+ 'dark sea green': '#11875d',
571
+ 'soft pink': '#fdb0c0',
572
+ 'orangey brown': '#b16002',
573
+ 'cherry red': '#f7022a',
574
+ 'burnt yellow': '#d5ab09',
575
+ 'brownish grey': '#86775f',
576
+ 'camel': '#c69f59',
577
+ 'purplish grey': '#7a687f',
578
+ 'marine': '#042e60',
579
+ 'greyish pink': '#c88d94',
580
+ 'pale turquoise': '#a5fbd5',
581
+ 'pastel yellow': '#fffe71',
582
+ 'bluey purple': '#6241c7',
583
+ 'canary yellow': '#fffe40',
584
+ 'faded red': '#d3494e',
585
+ 'sepia': '#985e2b',
586
+ 'coffee': '#a6814c',
587
+ 'bright magenta': '#ff08e8',
588
+ 'mocha': '#9d7651',
589
+ 'ecru': '#feffca',
590
+ 'purpleish': '#98568d',
591
+ 'cranberry': '#9e003a',
592
+ 'darkish green': '#287c37',
593
+ 'brown orange': '#b96902',
594
+ 'dusky rose': '#ba6873',
595
+ 'melon': '#ff7855',
596
+ 'sickly green': '#94b21c',
597
+ 'silver': '#c5c9c7',
598
+ 'purply blue': '#661aee',
599
+ 'purpleish blue': '#6140ef',
600
+ 'hospital green': '#9be5aa',
601
+ 'shit brown': '#7b5804',
602
+ 'mid blue': '#276ab3',
603
+ 'amber': '#feb308',
604
+ 'easter green': '#8cfd7e',
605
+ 'soft blue': '#6488ea',
606
+ 'cerulean blue': '#056eee',
607
+ 'golden brown': '#b27a01',
608
+ 'bright turquoise': '#0ffef9',
609
+ 'red pink': '#fa2a55',
610
+ 'red purple': '#820747',
611
+ 'greyish brown': '#7a6a4f',
612
+ 'vermillion': '#f4320c',
613
+ 'russet': '#a13905',
614
+ 'steel grey': '#6f828a',
615
+ 'lighter purple': '#a55af4',
616
+ 'bright violet': '#ad0afd',
617
+ 'prussian blue': '#004577',
618
+ 'slate green': '#658d6d',
619
+ 'dirty pink': '#ca7b80',
620
+ 'dark blue green': '#005249',
621
+ 'pine': '#2b5d34',
622
+ 'yellowy green': '#bff128',
623
+ 'dark gold': '#b59410',
624
+ 'bluish': '#2976bb',
625
+ 'darkish blue': '#014182',
626
+ 'dull red': '#bb3f3f',
627
+ 'pinky red': '#fc2647',
628
+ 'bronze': '#a87900',
629
+ 'pale teal': '#82cbb2',
630
+ 'military green': '#667c3e',
631
+ 'barbie pink': '#fe46a5',
632
+ 'bubblegum pink': '#fe83cc',
633
+ 'pea soup green': '#94a617',
634
+ 'dark mustard': '#a88905',
635
+ 'shit': '#7f5f00',
636
+ 'medium purple': '#9e43a2',
637
+ 'very dark green': '#062e03',
638
+ 'dirt': '#8a6e45',
639
+ 'dusky pink': '#cc7a8b',
640
+ 'red violet': '#9e0168',
641
+ 'lemon yellow': '#fdff38',
642
+ 'pistachio': '#c0fa8b',
643
+ 'dull yellow': '#eedc5b',
644
+ 'dark lime green': '#7ebd01',
645
+ 'denim blue': '#3b5b92',
646
+ 'teal blue': '#01889f',
647
+ 'lightish blue': '#3d7afd',
648
+ 'purpley blue': '#5f34e7',
649
+ 'light indigo': '#6d5acf',
650
+ 'swamp green': '#748500',
651
+ 'brown green': '#706c11',
652
+ 'dark maroon': '#3c0008',
653
+ 'hot purple': '#cb00f5',
654
+ 'dark forest green': '#002d04',
655
+ 'faded blue': '#658cbb',
656
+ 'drab green': '#749551',
657
+ 'light lime green': '#b9ff66',
658
+ 'snot green': '#9dc100',
659
+ 'yellowish': '#faee66',
660
+ 'light blue green': '#7efbb3',
661
+ 'bordeaux': '#7b002c',
662
+ 'light mauve': '#c292a1',
663
+ 'ocean': '#017b92',
664
+ 'marigold': '#fcc006',
665
+ 'muddy green': '#657432',
666
+ 'dull orange': '#d8863b',
667
+ 'steel': '#738595',
668
+ 'electric purple': '#aa23ff',
669
+ 'fluorescent green': '#08ff08',
670
+ 'yellowish brown': '#9b7a01',
671
+ 'blush': '#f29e8e',
672
+ 'soft green': '#6fc276',
673
+ 'bright orange': '#ff5b00',
674
+ 'lemon': '#fdff52',
675
+ 'purple grey': '#866f85',
676
+ 'acid green': '#8ffe09',
677
+ 'pale lavender': '#eecffe',
678
+ 'violet blue': '#510ac9',
679
+ 'light forest green': '#4f9153',
680
+ 'burnt red': '#9f2305',
681
+ 'khaki green': '#728639',
682
+ 'cerise': '#de0c62',
683
+ 'faded purple': '#916e99',
684
+ 'apricot': '#ffb16d',
685
+ 'dark olive green': '#3c4d03',
686
+ 'grey brown': '#7f7053',
687
+ 'green grey': '#77926f',
688
+ 'true blue': '#010fcc',
689
+ 'pale violet': '#ceaefa',
690
+ 'periwinkle blue': '#8f99fb',
691
+ 'light sky blue': '#c6fcff',
692
+ 'blurple': '#5539cc',
693
+ 'green brown': '#544e03',
694
+ 'bluegreen': '#017a79',
695
+ 'bright teal': '#01f9c6',
696
+ 'brownish yellow': '#c9b003',
697
+ 'pea soup': '#929901',
698
+ 'forest': '#0b5509',
699
+ 'barney purple': '#a00498',
700
+ 'ultramarine': '#2000b1',
701
+ 'purplish': '#94568c',
702
+ 'puke yellow': '#c2be0e',
703
+ 'bluish grey': '#748b97',
704
+ 'dark periwinkle': '#665fd1',
705
+ 'dark lilac': '#9c6da5',
706
+ 'reddish': '#c44240',
707
+ 'light maroon': '#a24857',
708
+ 'dusty purple': '#825f87',
709
+ 'terra cotta': '#c9643b',
710
+ 'avocado': '#90b134',
711
+ 'marine blue': '#01386a',
712
+ 'teal green': '#25a36f',
713
+ 'slate grey': '#59656d',
714
+ 'lighter green': '#75fd63',
715
+ 'electric green': '#21fc0d',
716
+ 'dusty blue': '#5a86ad',
717
+ 'golden yellow': '#fec615',
718
+ 'bright yellow': '#fffd01',
719
+ 'light lavender': '#dfc5fe',
720
+ 'umber': '#b26400',
721
+ 'poop': '#7f5e00',
722
+ 'dark peach': '#de7e5d',
723
+ 'jungle green': '#048243',
724
+ 'eggshell': '#ffffd4',
725
+ 'denim': '#3b638c',
726
+ 'yellow brown': '#b79400',
727
+ 'dull purple': '#84597e',
728
+ 'chocolate brown': '#411900',
729
+ 'wine red': '#7b0323',
730
+ 'neon blue': '#04d9ff',
731
+ 'dirty green': '#667e2c',
732
+ 'light tan': '#fbeeac',
733
+ 'ice blue': '#d7fffe',
734
+ 'cadet blue': '#4e7496',
735
+ 'dark mauve': '#874c62',
736
+ 'very light blue': '#d5ffff',
737
+ 'grey purple': '#826d8c',
738
+ 'pastel pink': '#ffbacd',
739
+ 'very light green': '#d1ffbd',
740
+ 'dark sky blue': '#448ee4',
741
+ 'evergreen': '#05472a',
742
+ 'dull pink': '#d5869d',
743
+ 'aubergine': '#3d0734',
744
+ 'mahogany': '#4a0100',
745
+ 'reddish orange': '#f8481c',
746
+ 'deep green': '#02590f',
747
+ 'vomit green': '#89a203',
748
+ 'purple pink': '#e03fd8',
749
+ 'dusty pink': '#d58a94',
750
+ 'faded green': '#7bb274',
751
+ 'camo green': '#526525',
752
+ 'pinky purple': '#c94cbe',
753
+ 'pink purple': '#db4bda',
754
+ 'brownish red': '#9e3623',
755
+ 'dark rose': '#b5485d',
756
+ 'mud': '#735c12',
757
+ 'brownish': '#9c6d57',
758
+ 'emerald green': '#028f1e',
759
+ 'pale brown': '#b1916e',
760
+ 'dull blue': '#49759c',
761
+ 'burnt umber': '#a0450e',
762
+ 'medium green': '#39ad48',
763
+ 'clay': '#b66a50',
764
+ 'light aqua': '#8cffdb',
765
+ 'light olive green': '#a4be5c',
766
+ 'brownish orange': '#cb7723',
767
+ 'dark aqua': '#05696b',
768
+ 'purplish pink': '#ce5dae',
769
+ 'dark salmon': '#c85a53',
770
+ 'greenish grey': '#96ae8d',
771
+ 'jade': '#1fa774',
772
+ 'ugly green': '#7a9703',
773
+ 'dark beige': '#ac9362',
774
+ 'emerald': '#01a049',
775
+ 'pale red': '#d9544d',
776
+ 'light magenta': '#fa5ff7',
777
+ 'sky': '#82cafc',
778
+ 'light cyan': '#acfffc',
779
+ 'yellow orange': '#fcb001',
780
+ 'reddish purple': '#910951',
781
+ 'reddish pink': '#fe2c54',
782
+ 'orchid': '#c875c4',
783
+ 'dirty yellow': '#cdc50a',
784
+ 'orange red': '#fd411e',
785
+ 'deep red': '#9a0200',
786
+ 'orange brown': '#be6400',
787
+ 'cobalt blue': '#030aa7',
788
+ 'neon pink': '#fe019a',
789
+ 'rose pink': '#f7879a',
790
+ 'greyish purple': '#887191',
791
+ 'raspberry': '#b00149',
792
+ 'aqua green': '#12e193',
793
+ 'salmon pink': '#fe7b7c',
794
+ 'tangerine': '#ff9408',
795
+ 'brownish green': '#6a6e09',
796
+ 'red brown': '#8b2e16',
797
+ 'greenish brown': '#696112',
798
+ 'pumpkin': '#e17701',
799
+ 'pine green': '#0a481e',
800
+ 'charcoal': '#343837',
801
+ 'baby pink': '#ffb7ce',
802
+ 'cornflower': '#6a79f7',
803
+ 'blue violet': '#5d06e9',
804
+ 'chocolate': '#3d1c02',
805
+ 'greyish green': '#82a67d',
806
+ 'scarlet': '#be0119',
807
+ 'green yellow': '#c9ff27',
808
+ 'dark olive': '#373e02',
809
+ 'sienna': '#a9561e',
810
+ 'pastel purple': '#caa0ff',
811
+ 'terracotta': '#ca6641',
812
+ 'aqua blue': '#02d8e9',
813
+ 'sage green': '#88b378',
814
+ 'blood red': '#980002',
815
+ 'deep pink': '#cb0162',
816
+ 'grass': '#5cac2d',
817
+ 'moss': '#769958',
818
+ 'pastel blue': '#a2bffe',
819
+ 'bluish green': '#10a674',
820
+ 'green blue': '#06b48b',
821
+ 'dark tan': '#af884a',
822
+ 'greenish blue': '#0b8b87',
823
+ 'pale orange': '#ffa756',
824
+ 'vomit': '#a2a415',
825
+ 'forrest green': '#154406',
826
+ 'dark lavender': '#856798',
827
+ 'dark violet': '#34013f',
828
+ 'purple blue': '#632de9',
829
+ 'dark cyan': '#0a888a',
830
+ 'olive drab': '#6f7632',
831
+ 'pinkish': '#d46a7e',
832
+ 'cobalt': '#1e488f',
833
+ 'neon purple': '#bc13fe',
834
+ 'light turquoise': '#7ef4cc',
835
+ 'apple green': '#76cd26',
836
+ 'dull green': '#74a662',
837
+ 'wine': '#80013f',
838
+ 'powder blue': '#b1d1fc',
839
+ 'off white': '#ffffe4',
840
+ 'electric blue': '#0652ff',
841
+ 'dark turquoise': '#045c5a',
842
+ 'blue purple': '#5729ce',
843
+ 'azure': '#069af3',
844
+ 'bright red': '#ff000d',
845
+ 'pinkish red': '#f10c45',
846
+ 'cornflower blue': '#5170d7',
847
+ 'light olive': '#acbf69',
848
+ 'grape': '#6c3461',
849
+ 'greyish blue': '#5e819d',
850
+ 'purplish blue': '#601ef9',
851
+ 'yellowish green': '#b0dd16',
852
+ 'greenish yellow': '#cdfd02',
853
+ 'medium blue': '#2c6fbb',
854
+ 'dusty rose': '#c0737a',
855
+ 'light violet': '#d6b4fc',
856
+ 'midnight blue': '#020035',
857
+ 'bluish purple': '#703be7',
858
+ 'red orange': '#fd3c06',
859
+ 'dark magenta': '#960056',
860
+ 'greenish': '#40a368',
861
+ 'ocean blue': '#03719c',
862
+ 'coral': '#fc5a50',
863
+ 'cream': '#ffffc2',
864
+ 'reddish brown': '#7f2b0a',
865
+ 'burnt sienna': '#b04e0f',
866
+ 'brick': '#a03623',
867
+ 'sage': '#87ae73',
868
+ 'grey green': '#789b73',
869
+ 'white': '#ffffff',
870
+ "robin's egg blue": '#98eff9',
871
+ 'moss green': '#658b38',
872
+ 'steel blue': '#5a7d9a',
873
+ 'eggplant': '#380835',
874
+ 'light yellow': '#fffe7a',
875
+ 'leaf green': '#5ca904',
876
+ 'light grey': '#d8dcd6',
877
+ 'puke': '#a5a502',
878
+ 'pinkish purple': '#d648d7',
879
+ 'sea blue': '#047495',
880
+ 'pale purple': '#b790d4',
881
+ 'slate blue': '#5b7c99',
882
+ 'blue grey': '#607c8e',
883
+ 'hunter green': '#0b4008',
884
+ 'fuchsia': '#ed0dd9',
885
+ 'crimson': '#8c000f',
886
+ 'pale yellow': '#ffff84',
887
+ 'ochre': '#bf9005',
888
+ 'mustard yellow': '#d2bd0a',
889
+ 'light red': '#ff474c',
890
+ 'cerulean': '#0485d1',
891
+ 'pale pink': '#ffcfdc',
892
+ 'deep blue': '#040273',
893
+ 'rust': '#a83c09',
894
+ 'light teal': '#90e4c1',
895
+ 'slate': '#516572',
896
+ 'goldenrod': '#fac205',
897
+ 'dark yellow': '#d5b60a',
898
+ 'dark grey': '#363737',
899
+ 'army green': '#4b5d16',
900
+ 'grey blue': '#6b8ba4',
901
+ 'seafoam': '#80f9ad',
902
+ 'puce': '#a57e52',
903
+ 'spring green': '#a9f971',
904
+ 'dark orange': '#c65102',
905
+ 'sand': '#e2ca76',
906
+ 'pastel green': '#b0ff9d',
907
+ 'mint': '#9ffeb0',
908
+ 'light orange': '#fdaa48',
909
+ 'bright pink': '#fe01b1',
910
+ 'chartreuse': '#c1f80a',
911
+ 'deep purple': '#36013f',
912
+ 'dark brown': '#341c02',
913
+ 'taupe': '#b9a281',
914
+ 'pea green': '#8eab12',
915
+ 'puke green': '#9aae07',
916
+ 'kelly green': '#02ab2e',
917
+ 'seafoam green': '#7af9ab',
918
+ 'blue green': '#137e6d',
919
+ 'khaki': '#aaa662',
920
+ 'burgundy': '#610023',
921
+ 'dark teal': '#014d4e',
922
+ 'brick red': '#8f1402',
923
+ 'royal purple': '#4b006e',
924
+ 'plum': '#580f41',
925
+ 'mint green': '#8fff9f',
926
+ 'gold': '#dbb40c',
927
+ 'baby blue': '#a2cffe',
928
+ 'yellow green': '#c0fb2d',
929
+ 'bright purple': '#be03fd',
930
+ 'dark red': '#840000',
931
+ 'pale blue': '#d0fefe',
932
+ 'grass green': '#3f9b0b',
933
+ 'navy': '#01153e',
934
+ 'aquamarine': '#04d8b2',
935
+ 'burnt orange': '#c04e01',
936
+ 'neon green': '#0cff0c',
937
+ 'bright blue': '#0165fc',
938
+ 'rose': '#cf6275',
939
+ 'light pink': '#ffd1df',
940
+ 'mustard': '#ceb301',
941
+ 'indigo': '#380282',
942
+ 'lime': '#aaff32',
943
+ 'sea green': '#53fca1',
944
+ 'periwinkle': '#8e82fe',
945
+ 'dark pink': '#cb416b',
946
+ 'olive green': '#677a04',
947
+ 'peach': '#ffb07c',
948
+ 'pale green': '#c7fdb5',
949
+ 'light brown': '#ad8150',
950
+ 'hot pink': '#ff028d',
951
+ 'black': '#000000',
952
+ 'lilac': '#cea2fd',
953
+ 'navy blue': '#001146',
954
+ 'royal blue': '#0504aa',
955
+ 'beige': '#e6daa6',
956
+ 'salmon': '#ff796c',
957
+ 'olive': '#6e750e',
958
+ 'maroon': '#650021',
959
+ 'bright green': '#01ff07',
960
+ 'dark purple': '#35063e',
961
+ 'mauve': '#ae7181',
962
+ 'forest green': '#06470c',
963
+ 'aqua': '#13eac9',
964
+ 'cyan': '#00ffff',
965
+ 'tan': '#d1b26f',
966
+ 'dark blue': '#00035b',
967
+ 'lavender': '#c79fef',
968
+ 'turquoise': '#06c2ac',
969
+ 'dark green': '#033500',
970
+ 'violet': '#9a0eea',
971
+ 'light purple': '#bf77f6',
972
+ 'lime green': '#89fe05',
973
+ 'grey': '#929591',
974
+ 'sky blue': '#75bbfd',
975
+ 'yellow': '#ffff14',
976
+ 'magenta': '#c20078',
977
+ 'light green': '#96f97b',
978
+ 'orange': '#f97306',
979
+ 'teal': '#029386',
980
+ 'light blue': '#95d0fc',
981
+ 'red': '#e50000',
982
+ 'brown': '#653700',
983
+ 'pink': '#ff81c0',
984
+ 'blue': '#0343df',
985
+ 'green': '#15b01a',
986
+ 'purple': '#7e1e9c'}
987
+
988
+ # Normalize name to "xkcd:<name>" to avoid name collisions.
989
+ XKCD_COLORS = {'xkcd:' + name: value for name, value in XKCD_COLORS.items()}
990
+
991
+
992
+ # https://drafts.csswg.org/css-color-4/#named-colors
993
+ CSS4_COLORS = {
994
+ 'aliceblue': '#F0F8FF',
995
+ 'antiquewhite': '#FAEBD7',
996
+ 'aqua': '#00FFFF',
997
+ 'aquamarine': '#7FFFD4',
998
+ 'azure': '#F0FFFF',
999
+ 'beige': '#F5F5DC',
1000
+ 'bisque': '#FFE4C4',
1001
+ 'black': '#000000',
1002
+ 'blanchedalmond': '#FFEBCD',
1003
+ 'blue': '#0000FF',
1004
+ 'blueviolet': '#8A2BE2',
1005
+ 'brown': '#A52A2A',
1006
+ 'burlywood': '#DEB887',
1007
+ 'cadetblue': '#5F9EA0',
1008
+ 'chartreuse': '#7FFF00',
1009
+ 'chocolate': '#D2691E',
1010
+ 'coral': '#FF7F50',
1011
+ 'cornflowerblue': '#6495ED',
1012
+ 'cornsilk': '#FFF8DC',
1013
+ 'crimson': '#DC143C',
1014
+ 'cyan': '#00FFFF',
1015
+ 'darkblue': '#00008B',
1016
+ 'darkcyan': '#008B8B',
1017
+ 'darkgoldenrod': '#B8860B',
1018
+ 'darkgray': '#A9A9A9',
1019
+ 'darkgreen': '#006400',
1020
+ 'darkgrey': '#A9A9A9',
1021
+ 'darkkhaki': '#BDB76B',
1022
+ 'darkmagenta': '#8B008B',
1023
+ 'darkolivegreen': '#556B2F',
1024
+ 'darkorange': '#FF8C00',
1025
+ 'darkorchid': '#9932CC',
1026
+ 'darkred': '#8B0000',
1027
+ 'darksalmon': '#E9967A',
1028
+ 'darkseagreen': '#8FBC8F',
1029
+ 'darkslateblue': '#483D8B',
1030
+ 'darkslategray': '#2F4F4F',
1031
+ 'darkslategrey': '#2F4F4F',
1032
+ 'darkturquoise': '#00CED1',
1033
+ 'darkviolet': '#9400D3',
1034
+ 'deeppink': '#FF1493',
1035
+ 'deepskyblue': '#00BFFF',
1036
+ 'dimgray': '#696969',
1037
+ 'dimgrey': '#696969',
1038
+ 'dodgerblue': '#1E90FF',
1039
+ 'firebrick': '#B22222',
1040
+ 'floralwhite': '#FFFAF0',
1041
+ 'forestgreen': '#228B22',
1042
+ 'fuchsia': '#FF00FF',
1043
+ 'gainsboro': '#DCDCDC',
1044
+ 'ghostwhite': '#F8F8FF',
1045
+ 'gold': '#FFD700',
1046
+ 'goldenrod': '#DAA520',
1047
+ 'gray': '#808080',
1048
+ 'green': '#008000',
1049
+ 'greenyellow': '#ADFF2F',
1050
+ 'grey': '#808080',
1051
+ 'honeydew': '#F0FFF0',
1052
+ 'hotpink': '#FF69B4',
1053
+ 'indianred': '#CD5C5C',
1054
+ 'indigo': '#4B0082',
1055
+ 'ivory': '#FFFFF0',
1056
+ 'khaki': '#F0E68C',
1057
+ 'lavender': '#E6E6FA',
1058
+ 'lavenderblush': '#FFF0F5',
1059
+ 'lawngreen': '#7CFC00',
1060
+ 'lemonchiffon': '#FFFACD',
1061
+ 'lightblue': '#ADD8E6',
1062
+ 'lightcoral': '#F08080',
1063
+ 'lightcyan': '#E0FFFF',
1064
+ 'lightgoldenrodyellow': '#FAFAD2',
1065
+ 'lightgray': '#D3D3D3',
1066
+ 'lightgreen': '#90EE90',
1067
+ 'lightgrey': '#D3D3D3',
1068
+ 'lightpink': '#FFB6C1',
1069
+ 'lightsalmon': '#FFA07A',
1070
+ 'lightseagreen': '#20B2AA',
1071
+ 'lightskyblue': '#87CEFA',
1072
+ 'lightslategray': '#778899',
1073
+ 'lightslategrey': '#778899',
1074
+ 'lightsteelblue': '#B0C4DE',
1075
+ 'lightyellow': '#FFFFE0',
1076
+ 'lime': '#00FF00',
1077
+ 'limegreen': '#32CD32',
1078
+ 'linen': '#FAF0E6',
1079
+ 'magenta': '#FF00FF',
1080
+ 'maroon': '#800000',
1081
+ 'mediumaquamarine': '#66CDAA',
1082
+ 'mediumblue': '#0000CD',
1083
+ 'mediumorchid': '#BA55D3',
1084
+ 'mediumpurple': '#9370DB',
1085
+ 'mediumseagreen': '#3CB371',
1086
+ 'mediumslateblue': '#7B68EE',
1087
+ 'mediumspringgreen': '#00FA9A',
1088
+ 'mediumturquoise': '#48D1CC',
1089
+ 'mediumvioletred': '#C71585',
1090
+ 'midnightblue': '#191970',
1091
+ 'mintcream': '#F5FFFA',
1092
+ 'mistyrose': '#FFE4E1',
1093
+ 'moccasin': '#FFE4B5',
1094
+ 'navajowhite': '#FFDEAD',
1095
+ 'navy': '#000080',
1096
+ 'oldlace': '#FDF5E6',
1097
+ 'olive': '#808000',
1098
+ 'olivedrab': '#6B8E23',
1099
+ 'orange': '#FFA500',
1100
+ 'orangered': '#FF4500',
1101
+ 'orchid': '#DA70D6',
1102
+ 'palegoldenrod': '#EEE8AA',
1103
+ 'palegreen': '#98FB98',
1104
+ 'paleturquoise': '#AFEEEE',
1105
+ 'palevioletred': '#DB7093',
1106
+ 'papayawhip': '#FFEFD5',
1107
+ 'peachpuff': '#FFDAB9',
1108
+ 'peru': '#CD853F',
1109
+ 'pink': '#FFC0CB',
1110
+ 'plum': '#DDA0DD',
1111
+ 'powderblue': '#B0E0E6',
1112
+ 'purple': '#800080',
1113
+ 'rebeccapurple': '#663399',
1114
+ 'red': '#FF0000',
1115
+ 'rosybrown': '#BC8F8F',
1116
+ 'royalblue': '#4169E1',
1117
+ 'saddlebrown': '#8B4513',
1118
+ 'salmon': '#FA8072',
1119
+ 'sandybrown': '#F4A460',
1120
+ 'seagreen': '#2E8B57',
1121
+ 'seashell': '#FFF5EE',
1122
+ 'sienna': '#A0522D',
1123
+ 'silver': '#C0C0C0',
1124
+ 'skyblue': '#87CEEB',
1125
+ 'slateblue': '#6A5ACD',
1126
+ 'slategray': '#708090',
1127
+ 'slategrey': '#708090',
1128
+ 'snow': '#FFFAFA',
1129
+ 'springgreen': '#00FF7F',
1130
+ 'steelblue': '#4682B4',
1131
+ 'tan': '#D2B48C',
1132
+ 'teal': '#008080',
1133
+ 'thistle': '#D8BFD8',
1134
+ 'tomato': '#FF6347',
1135
+ 'turquoise': '#40E0D0',
1136
+ 'violet': '#EE82EE',
1137
+ 'wheat': '#F5DEB3',
1138
+ 'white': '#FFFFFF',
1139
+ 'whitesmoke': '#F5F5F5',
1140
+ 'yellow': '#FFFF00',
1141
+ 'yellowgreen': '#9ACD32'}
llava_next/lib/python3.10/site-packages/matplotlib/_docstring.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+
3
+ from . import _api
4
+
5
+
6
+ def kwarg_doc(text):
7
+ """
8
+ Decorator for defining the kwdoc documentation of artist properties.
9
+
10
+ This decorator can be applied to artist property setter methods.
11
+ The given text is stored in a private attribute ``_kwarg_doc`` on
12
+ the method. It is used to overwrite auto-generated documentation
13
+ in the *kwdoc list* for artists. The kwdoc list is used to document
14
+ ``**kwargs`` when they are properties of an artist. See e.g. the
15
+ ``**kwargs`` section in `.Axes.text`.
16
+
17
+ The text should contain the supported types, as well as the default
18
+ value if applicable, e.g.:
19
+
20
+ @_docstring.kwarg_doc("bool, default: :rc:`text.usetex`")
21
+ def set_usetex(self, usetex):
22
+
23
+ See Also
24
+ --------
25
+ matplotlib.artist.kwdoc
26
+
27
+ """
28
+ def decorator(func):
29
+ func._kwarg_doc = text
30
+ return func
31
+ return decorator
32
+
33
+
34
+ class Substitution:
35
+ """
36
+ A decorator that performs %-substitution on an object's docstring.
37
+
38
+ This decorator should be robust even if ``obj.__doc__`` is None (for
39
+ example, if -OO was passed to the interpreter).
40
+
41
+ Usage: construct a docstring.Substitution with a sequence or dictionary
42
+ suitable for performing substitution; then decorate a suitable function
43
+ with the constructed object, e.g.::
44
+
45
+ sub_author_name = Substitution(author='Jason')
46
+
47
+ @sub_author_name
48
+ def some_function(x):
49
+ "%(author)s wrote this function"
50
+
51
+ # note that some_function.__doc__ is now "Jason wrote this function"
52
+
53
+ One can also use positional arguments::
54
+
55
+ sub_first_last_names = Substitution('Edgar Allen', 'Poe')
56
+
57
+ @sub_first_last_names
58
+ def some_function(x):
59
+ "%s %s wrote the Raven"
60
+ """
61
+ def __init__(self, *args, **kwargs):
62
+ if args and kwargs:
63
+ raise TypeError("Only positional or keyword args are allowed")
64
+ self.params = args or kwargs
65
+
66
+ def __call__(self, func):
67
+ if func.__doc__:
68
+ func.__doc__ = inspect.cleandoc(func.__doc__) % self.params
69
+ return func
70
+
71
+ def update(self, *args, **kwargs):
72
+ """
73
+ Update ``self.params`` (which must be a dict) with the supplied args.
74
+ """
75
+ self.params.update(*args, **kwargs)
76
+
77
+
78
+ class _ArtistKwdocLoader(dict):
79
+ def __missing__(self, key):
80
+ if not key.endswith(":kwdoc"):
81
+ raise KeyError(key)
82
+ name = key[:-len(":kwdoc")]
83
+ from matplotlib.artist import Artist, kwdoc
84
+ try:
85
+ cls, = [cls for cls in _api.recursive_subclasses(Artist)
86
+ if cls.__name__ == name]
87
+ except ValueError as e:
88
+ raise KeyError(key) from e
89
+ return self.setdefault(key, kwdoc(cls))
90
+
91
+
92
+ class _ArtistPropertiesSubstitution(Substitution):
93
+ """
94
+ A `.Substitution` with two additional features:
95
+
96
+ - Substitutions of the form ``%(classname:kwdoc)s`` (ending with the
97
+ literal ":kwdoc" suffix) trigger lookup of an Artist subclass with the
98
+ given *classname*, and are substituted with the `.kwdoc` of that class.
99
+ - Decorating a class triggers substitution both on the class docstring and
100
+ on the class' ``__init__`` docstring (which is a commonly required
101
+ pattern for Artist subclasses).
102
+ """
103
+
104
+ def __init__(self):
105
+ self.params = _ArtistKwdocLoader()
106
+
107
+ def __call__(self, obj):
108
+ super().__call__(obj)
109
+ if isinstance(obj, type) and obj.__init__ != object.__init__:
110
+ self(obj.__init__)
111
+ return obj
112
+
113
+
114
+ def copy(source):
115
+ """Copy a docstring from another source function (if present)."""
116
+ def do_copy(target):
117
+ if source.__doc__:
118
+ target.__doc__ = source.__doc__
119
+ return target
120
+ return do_copy
121
+
122
+
123
+ # Create a decorator that will house the various docstring snippets reused
124
+ # throughout Matplotlib.
125
+ dedent_interpd = interpd = _ArtistPropertiesSubstitution()
llava_next/lib/python3.10/site-packages/matplotlib/_enums.pyi ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from enum import Enum
2
+
3
+ class _AutoStringNameEnum(Enum):
4
+ def __hash__(self) -> int: ...
5
+
6
+ class JoinStyle(str, _AutoStringNameEnum):
7
+ miter: str
8
+ round: str
9
+ bevel: str
10
+ @staticmethod
11
+ def demo() -> None: ...
12
+
13
+ class CapStyle(str, _AutoStringNameEnum):
14
+ butt: str
15
+ projecting: str
16
+ round: str
17
+ @staticmethod
18
+ def demo() -> None: ...
llava_next/lib/python3.10/site-packages/matplotlib/_mathtext.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.py ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Manage figures for the pyplot interface.
3
+ """
4
+
5
+ import atexit
6
+ from collections import OrderedDict
7
+
8
+
9
+ class Gcf:
10
+ """
11
+ Singleton to maintain the relation between figures and their managers, and
12
+ keep track of and "active" figure and manager.
13
+
14
+ The canvas of a figure created through pyplot is associated with a figure
15
+ manager, which handles the interaction between the figure and the backend.
16
+ pyplot keeps track of figure managers using an identifier, the "figure
17
+ number" or "manager number" (which can actually be any hashable value);
18
+ this number is available as the :attr:`number` attribute of the manager.
19
+
20
+ This class is never instantiated; it consists of an `OrderedDict` mapping
21
+ figure/manager numbers to managers, and a set of class methods that
22
+ manipulate this `OrderedDict`.
23
+
24
+ Attributes
25
+ ----------
26
+ figs : OrderedDict
27
+ `OrderedDict` mapping numbers to managers; the active manager is at the
28
+ end.
29
+ """
30
+
31
+ figs = OrderedDict()
32
+
33
+ @classmethod
34
+ def get_fig_manager(cls, num):
35
+ """
36
+ If manager number *num* exists, make it the active one and return it;
37
+ otherwise return *None*.
38
+ """
39
+ manager = cls.figs.get(num, None)
40
+ if manager is not None:
41
+ cls.set_active(manager)
42
+ return manager
43
+
44
+ @classmethod
45
+ def destroy(cls, num):
46
+ """
47
+ Destroy manager *num* -- either a manager instance or a manager number.
48
+
49
+ In the interactive backends, this is bound to the window "destroy" and
50
+ "delete" events.
51
+
52
+ It is recommended to pass a manager instance, to avoid confusion when
53
+ two managers share the same number.
54
+ """
55
+ if all(hasattr(num, attr) for attr in ["num", "destroy"]):
56
+ manager = num
57
+ if cls.figs.get(manager.num) is manager:
58
+ cls.figs.pop(manager.num)
59
+ else:
60
+ try:
61
+ manager = cls.figs.pop(num)
62
+ except KeyError:
63
+ return
64
+ if hasattr(manager, "_cidgcf"):
65
+ manager.canvas.mpl_disconnect(manager._cidgcf)
66
+ manager.destroy()
67
+
68
+ @classmethod
69
+ def destroy_fig(cls, fig):
70
+ """Destroy figure *fig*."""
71
+ num = next((manager.num for manager in cls.figs.values()
72
+ if manager.canvas.figure == fig), None)
73
+ if num is not None:
74
+ cls.destroy(num)
75
+
76
+ @classmethod
77
+ def destroy_all(cls):
78
+ """Destroy all figures."""
79
+ for manager in list(cls.figs.values()):
80
+ manager.canvas.mpl_disconnect(manager._cidgcf)
81
+ manager.destroy()
82
+ cls.figs.clear()
83
+
84
+ @classmethod
85
+ def has_fignum(cls, num):
86
+ """Return whether figure number *num* exists."""
87
+ return num in cls.figs
88
+
89
+ @classmethod
90
+ def get_all_fig_managers(cls):
91
+ """Return a list of figure managers."""
92
+ return list(cls.figs.values())
93
+
94
+ @classmethod
95
+ def get_num_fig_managers(cls):
96
+ """Return the number of figures being managed."""
97
+ return len(cls.figs)
98
+
99
+ @classmethod
100
+ def get_active(cls):
101
+ """Return the active manager, or *None* if there is no manager."""
102
+ return next(reversed(cls.figs.values())) if cls.figs else None
103
+
104
+ @classmethod
105
+ def _set_new_active_manager(cls, manager):
106
+ """Adopt *manager* into pyplot and make it the active manager."""
107
+ if not hasattr(manager, "_cidgcf"):
108
+ manager._cidgcf = manager.canvas.mpl_connect(
109
+ "button_press_event", lambda event: cls.set_active(manager))
110
+ fig = manager.canvas.figure
111
+ fig.number = manager.num
112
+ label = fig.get_label()
113
+ if label:
114
+ manager.set_window_title(label)
115
+ cls.set_active(manager)
116
+
117
+ @classmethod
118
+ def set_active(cls, manager):
119
+ """Make *manager* the active manager."""
120
+ cls.figs[manager.num] = manager
121
+ cls.figs.move_to_end(manager.num)
122
+
123
+ @classmethod
124
+ def draw_all(cls, force=False):
125
+ """
126
+ Redraw all stale managed figures, or, if *force* is True, all managed
127
+ figures.
128
+ """
129
+ for manager in cls.get_all_fig_managers():
130
+ if force or manager.canvas.figure.stale:
131
+ manager.canvas.draw_idle()
132
+
133
+
134
+ atexit.register(Gcf.destroy_all)
llava_next/lib/python3.10/site-packages/matplotlib/_pylab_helpers.pyi ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections import OrderedDict
2
+
3
+ from matplotlib.backend_bases import FigureManagerBase
4
+ from matplotlib.figure import Figure
5
+
6
+ class Gcf:
7
+ figs: OrderedDict[int, FigureManagerBase]
8
+ @classmethod
9
+ def get_fig_manager(cls, num: int) -> FigureManagerBase | None: ...
10
+ @classmethod
11
+ def destroy(cls, num: int | FigureManagerBase) -> None: ...
12
+ @classmethod
13
+ def destroy_fig(cls, fig: Figure) -> None: ...
14
+ @classmethod
15
+ def destroy_all(cls) -> None: ...
16
+ @classmethod
17
+ def has_fignum(cls, num: int) -> bool: ...
18
+ @classmethod
19
+ def get_all_fig_managers(cls) -> list[FigureManagerBase]: ...
20
+ @classmethod
21
+ def get_num_fig_managers(cls) -> int: ...
22
+ @classmethod
23
+ def get_active(cls) -> FigureManagerBase | None: ...
24
+ @classmethod
25
+ def _set_new_active_manager(cls, manager: FigureManagerBase) -> None: ...
26
+ @classmethod
27
+ def set_active(cls, manager: FigureManagerBase) -> None: ...
28
+ @classmethod
29
+ def draw_all(cls, force: bool = ...) -> None: ...
llava_next/lib/python3.10/site-packages/matplotlib/_qhull.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:a836803f31df00f7f280085ab7873f39703c0e3c3eb5335690e8a119121145ad
3
+ size 745280
llava_next/lib/python3.10/site-packages/matplotlib/_tight_layout.py ADDED
@@ -0,0 +1,301 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Routines to adjust subplot params so that subplots are
3
+ nicely fit in the figure. In doing so, only axis labels, tick labels, Axes
4
+ titles and offsetboxes that are anchored to Axes are currently considered.
5
+
6
+ Internally, this module assumes that the margins (left margin, etc.) which are
7
+ differences between ``Axes.get_tightbbox`` and ``Axes.bbox`` are independent of
8
+ Axes position. This may fail if ``Axes.adjustable`` is ``datalim`` as well as
9
+ such cases as when left or right margin are affected by xlabel.
10
+ """
11
+
12
+ import numpy as np
13
+
14
+ import matplotlib as mpl
15
+ from matplotlib import _api, artist as martist
16
+ from matplotlib.font_manager import FontProperties
17
+ from matplotlib.transforms import Bbox
18
+
19
+
20
+ def _auto_adjust_subplotpars(
21
+ fig, renderer, shape, span_pairs, subplot_list,
22
+ ax_bbox_list=None, pad=1.08, h_pad=None, w_pad=None, rect=None):
23
+ """
24
+ Return a dict of subplot parameters to adjust spacing between subplots
25
+ or ``None`` if resulting Axes would have zero height or width.
26
+
27
+ Note that this function ignores geometry information of subplot itself, but
28
+ uses what is given by the *shape* and *subplot_list* parameters. Also, the
29
+ results could be incorrect if some subplots have ``adjustable=datalim``.
30
+
31
+ Parameters
32
+ ----------
33
+ shape : tuple[int, int]
34
+ Number of rows and columns of the grid.
35
+ span_pairs : list[tuple[slice, slice]]
36
+ List of rowspans and colspans occupied by each subplot.
37
+ subplot_list : list of subplots
38
+ List of subplots that will be used to calculate optimal subplot_params.
39
+ pad : float
40
+ Padding between the figure edge and the edges of subplots, as a
41
+ fraction of the font size.
42
+ h_pad, w_pad : float
43
+ Padding (height/width) between edges of adjacent subplots, as a
44
+ fraction of the font size. Defaults to *pad*.
45
+ rect : tuple
46
+ (left, bottom, right, top), default: None.
47
+ """
48
+ rows, cols = shape
49
+
50
+ font_size_inch = (FontProperties(
51
+ size=mpl.rcParams["font.size"]).get_size_in_points() / 72)
52
+ pad_inch = pad * font_size_inch
53
+ vpad_inch = h_pad * font_size_inch if h_pad is not None else pad_inch
54
+ hpad_inch = w_pad * font_size_inch if w_pad is not None else pad_inch
55
+
56
+ if len(span_pairs) != len(subplot_list) or len(subplot_list) == 0:
57
+ raise ValueError
58
+
59
+ if rect is None:
60
+ margin_left = margin_bottom = margin_right = margin_top = None
61
+ else:
62
+ margin_left, margin_bottom, _right, _top = rect
63
+ margin_right = 1 - _right if _right else None
64
+ margin_top = 1 - _top if _top else None
65
+
66
+ vspaces = np.zeros((rows + 1, cols))
67
+ hspaces = np.zeros((rows, cols + 1))
68
+
69
+ if ax_bbox_list is None:
70
+ ax_bbox_list = [
71
+ Bbox.union([ax.get_position(original=True) for ax in subplots])
72
+ for subplots in subplot_list]
73
+
74
+ for subplots, ax_bbox, (rowspan, colspan) in zip(
75
+ subplot_list, ax_bbox_list, span_pairs):
76
+ if all(not ax.get_visible() for ax in subplots):
77
+ continue
78
+
79
+ bb = []
80
+ for ax in subplots:
81
+ if ax.get_visible():
82
+ bb += [martist._get_tightbbox_for_layout_only(ax, renderer)]
83
+
84
+ tight_bbox_raw = Bbox.union(bb)
85
+ tight_bbox = fig.transFigure.inverted().transform_bbox(tight_bbox_raw)
86
+
87
+ hspaces[rowspan, colspan.start] += ax_bbox.xmin - tight_bbox.xmin # l
88
+ hspaces[rowspan, colspan.stop] += tight_bbox.xmax - ax_bbox.xmax # r
89
+ vspaces[rowspan.start, colspan] += tight_bbox.ymax - ax_bbox.ymax # t
90
+ vspaces[rowspan.stop, colspan] += ax_bbox.ymin - tight_bbox.ymin # b
91
+
92
+ fig_width_inch, fig_height_inch = fig.get_size_inches()
93
+
94
+ # margins can be negative for Axes with aspect applied, so use max(, 0) to
95
+ # make them nonnegative.
96
+ if not margin_left:
97
+ margin_left = max(hspaces[:, 0].max(), 0) + pad_inch/fig_width_inch
98
+ suplabel = fig._supylabel
99
+ if suplabel and suplabel.get_in_layout():
100
+ rel_width = fig.transFigure.inverted().transform_bbox(
101
+ suplabel.get_window_extent(renderer)).width
102
+ margin_left += rel_width + pad_inch/fig_width_inch
103
+ if not margin_right:
104
+ margin_right = max(hspaces[:, -1].max(), 0) + pad_inch/fig_width_inch
105
+ if not margin_top:
106
+ margin_top = max(vspaces[0, :].max(), 0) + pad_inch/fig_height_inch
107
+ if fig._suptitle and fig._suptitle.get_in_layout():
108
+ rel_height = fig.transFigure.inverted().transform_bbox(
109
+ fig._suptitle.get_window_extent(renderer)).height
110
+ margin_top += rel_height + pad_inch/fig_height_inch
111
+ if not margin_bottom:
112
+ margin_bottom = max(vspaces[-1, :].max(), 0) + pad_inch/fig_height_inch
113
+ suplabel = fig._supxlabel
114
+ if suplabel and suplabel.get_in_layout():
115
+ rel_height = fig.transFigure.inverted().transform_bbox(
116
+ suplabel.get_window_extent(renderer)).height
117
+ margin_bottom += rel_height + pad_inch/fig_height_inch
118
+
119
+ if margin_left + margin_right >= 1:
120
+ _api.warn_external('Tight layout not applied. The left and right '
121
+ 'margins cannot be made large enough to '
122
+ 'accommodate all Axes decorations.')
123
+ return None
124
+ if margin_bottom + margin_top >= 1:
125
+ _api.warn_external('Tight layout not applied. The bottom and top '
126
+ 'margins cannot be made large enough to '
127
+ 'accommodate all Axes decorations.')
128
+ return None
129
+
130
+ kwargs = dict(left=margin_left,
131
+ right=1 - margin_right,
132
+ bottom=margin_bottom,
133
+ top=1 - margin_top)
134
+
135
+ if cols > 1:
136
+ hspace = hspaces[:, 1:-1].max() + hpad_inch / fig_width_inch
137
+ # axes widths:
138
+ h_axes = (1 - margin_right - margin_left - hspace * (cols - 1)) / cols
139
+ if h_axes < 0:
140
+ _api.warn_external('Tight layout not applied. tight_layout '
141
+ 'cannot make Axes width small enough to '
142
+ 'accommodate all Axes decorations')
143
+ return None
144
+ else:
145
+ kwargs["wspace"] = hspace / h_axes
146
+ if rows > 1:
147
+ vspace = vspaces[1:-1, :].max() + vpad_inch / fig_height_inch
148
+ v_axes = (1 - margin_top - margin_bottom - vspace * (rows - 1)) / rows
149
+ if v_axes < 0:
150
+ _api.warn_external('Tight layout not applied. tight_layout '
151
+ 'cannot make Axes height small enough to '
152
+ 'accommodate all Axes decorations.')
153
+ return None
154
+ else:
155
+ kwargs["hspace"] = vspace / v_axes
156
+
157
+ return kwargs
158
+
159
+
160
+ def get_subplotspec_list(axes_list, grid_spec=None):
161
+ """
162
+ Return a list of subplotspec from the given list of Axes.
163
+
164
+ For an instance of Axes that does not support subplotspec, None is inserted
165
+ in the list.
166
+
167
+ If grid_spec is given, None is inserted for those not from the given
168
+ grid_spec.
169
+ """
170
+ subplotspec_list = []
171
+ for ax in axes_list:
172
+ axes_or_locator = ax.get_axes_locator()
173
+ if axes_or_locator is None:
174
+ axes_or_locator = ax
175
+
176
+ if hasattr(axes_or_locator, "get_subplotspec"):
177
+ subplotspec = axes_or_locator.get_subplotspec()
178
+ if subplotspec is not None:
179
+ subplotspec = subplotspec.get_topmost_subplotspec()
180
+ gs = subplotspec.get_gridspec()
181
+ if grid_spec is not None:
182
+ if gs != grid_spec:
183
+ subplotspec = None
184
+ elif gs.locally_modified_subplot_params():
185
+ subplotspec = None
186
+ else:
187
+ subplotspec = None
188
+
189
+ subplotspec_list.append(subplotspec)
190
+
191
+ return subplotspec_list
192
+
193
+
194
+ def get_tight_layout_figure(fig, axes_list, subplotspec_list, renderer,
195
+ pad=1.08, h_pad=None, w_pad=None, rect=None):
196
+ """
197
+ Return subplot parameters for tight-layouted-figure with specified padding.
198
+
199
+ Parameters
200
+ ----------
201
+ fig : Figure
202
+ axes_list : list of Axes
203
+ subplotspec_list : list of `.SubplotSpec`
204
+ The subplotspecs of each Axes.
205
+ renderer : renderer
206
+ pad : float
207
+ Padding between the figure edge and the edges of subplots, as a
208
+ fraction of the font size.
209
+ h_pad, w_pad : float
210
+ Padding (height/width) between edges of adjacent subplots. Defaults to
211
+ *pad*.
212
+ rect : tuple (left, bottom, right, top), default: None.
213
+ rectangle in normalized figure coordinates
214
+ that the whole subplots area (including labels) will fit into.
215
+ Defaults to using the entire figure.
216
+
217
+ Returns
218
+ -------
219
+ subplotspec or None
220
+ subplotspec kwargs to be passed to `.Figure.subplots_adjust` or
221
+ None if tight_layout could not be accomplished.
222
+ """
223
+
224
+ # Multiple Axes can share same subplotspec (e.g., if using axes_grid1);
225
+ # we need to group them together.
226
+ ss_to_subplots = {ss: [] for ss in subplotspec_list}
227
+ for ax, ss in zip(axes_list, subplotspec_list):
228
+ ss_to_subplots[ss].append(ax)
229
+ if ss_to_subplots.pop(None, None):
230
+ _api.warn_external(
231
+ "This figure includes Axes that are not compatible with "
232
+ "tight_layout, so results might be incorrect.")
233
+ if not ss_to_subplots:
234
+ return {}
235
+ subplot_list = list(ss_to_subplots.values())
236
+ ax_bbox_list = [ss.get_position(fig) for ss in ss_to_subplots]
237
+
238
+ max_nrows = max(ss.get_gridspec().nrows for ss in ss_to_subplots)
239
+ max_ncols = max(ss.get_gridspec().ncols for ss in ss_to_subplots)
240
+
241
+ span_pairs = []
242
+ for ss in ss_to_subplots:
243
+ # The intent here is to support Axes from different gridspecs where
244
+ # one's nrows (or ncols) is a multiple of the other (e.g. 2 and 4),
245
+ # but this doesn't actually work because the computed wspace, in
246
+ # relative-axes-height, corresponds to different physical spacings for
247
+ # the 2-row grid and the 4-row grid. Still, this code is left, mostly
248
+ # for backcompat.
249
+ rows, cols = ss.get_gridspec().get_geometry()
250
+ div_row, mod_row = divmod(max_nrows, rows)
251
+ div_col, mod_col = divmod(max_ncols, cols)
252
+ if mod_row != 0:
253
+ _api.warn_external('tight_layout not applied: number of rows '
254
+ 'in subplot specifications must be '
255
+ 'multiples of one another.')
256
+ return {}
257
+ if mod_col != 0:
258
+ _api.warn_external('tight_layout not applied: number of '
259
+ 'columns in subplot specifications must be '
260
+ 'multiples of one another.')
261
+ return {}
262
+ span_pairs.append((
263
+ slice(ss.rowspan.start * div_row, ss.rowspan.stop * div_row),
264
+ slice(ss.colspan.start * div_col, ss.colspan.stop * div_col)))
265
+
266
+ kwargs = _auto_adjust_subplotpars(fig, renderer,
267
+ shape=(max_nrows, max_ncols),
268
+ span_pairs=span_pairs,
269
+ subplot_list=subplot_list,
270
+ ax_bbox_list=ax_bbox_list,
271
+ pad=pad, h_pad=h_pad, w_pad=w_pad)
272
+
273
+ # kwargs can be none if tight_layout fails...
274
+ if rect is not None and kwargs is not None:
275
+ # if rect is given, the whole subplots area (including
276
+ # labels) will fit into the rect instead of the
277
+ # figure. Note that the rect argument of
278
+ # *auto_adjust_subplotpars* specify the area that will be
279
+ # covered by the total area of axes.bbox. Thus we call
280
+ # auto_adjust_subplotpars twice, where the second run
281
+ # with adjusted rect parameters.
282
+
283
+ left, bottom, right, top = rect
284
+ if left is not None:
285
+ left += kwargs["left"]
286
+ if bottom is not None:
287
+ bottom += kwargs["bottom"]
288
+ if right is not None:
289
+ right -= (1 - kwargs["right"])
290
+ if top is not None:
291
+ top -= (1 - kwargs["top"])
292
+
293
+ kwargs = _auto_adjust_subplotpars(fig, renderer,
294
+ shape=(max_nrows, max_ncols),
295
+ span_pairs=span_pairs,
296
+ subplot_list=subplot_list,
297
+ ax_bbox_list=ax_bbox_list,
298
+ pad=pad, h_pad=h_pad, w_pad=w_pad,
299
+ rect=(left, bottom, right, top))
300
+
301
+ return kwargs
llava_next/lib/python3.10/site-packages/matplotlib/_tri.pyi ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # This is a private module implemented in C++
2
+ # As such these type stubs are overly generic, but here to allow these types
3
+ # as return types for public methods
4
+ from typing import Any, final
5
+
6
+ @final
7
+ class TrapezoidMapTriFinder:
8
+ def __init__(self, *args, **kwargs) -> None: ...
9
+ def find_many(self, *args, **kwargs) -> Any: ...
10
+ def get_tree_stats(self, *args, **kwargs) -> Any: ...
11
+ def initialize(self, *args, **kwargs) -> Any: ...
12
+ def print_tree(self, *args, **kwargs) -> Any: ...
13
+
14
+ @final
15
+ class TriContourGenerator:
16
+ def __init__(self, *args, **kwargs) -> None: ...
17
+ def create_contour(self, *args, **kwargs) -> Any: ...
18
+ def create_filled_contour(self, *args, **kwargs) -> Any: ...
19
+
20
+ @final
21
+ class Triangulation:
22
+ def __init__(self, *args, **kwargs) -> None: ...
23
+ def calculate_plane_coefficients(self, *args, **kwargs) -> Any: ...
24
+ def get_edges(self, *args, **kwargs) -> Any: ...
25
+ def get_neighbors(self, *args, **kwargs) -> Any: ...
26
+ def set_mask(self, *args, **kwargs) -> Any: ...
llava_next/lib/python3.10/site-packages/matplotlib/_version.py ADDED
@@ -0,0 +1 @@
 
 
1
+ version = "3.9.2"
llava_next/lib/python3.10/site-packages/matplotlib/axis.pyi ADDED
@@ -0,0 +1,280 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Iterable, Sequence
2
+ import datetime
3
+ from typing import Any, Literal, overload
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike
7
+
8
+ import matplotlib.artist as martist
9
+ from matplotlib import cbook
10
+ from matplotlib.axes import Axes
11
+ from matplotlib.backend_bases import RendererBase
12
+ from matplotlib.lines import Line2D
13
+ from matplotlib.text import Text
14
+ from matplotlib.ticker import Locator, Formatter
15
+ from matplotlib.transforms import Transform, Bbox
16
+ from matplotlib.typing import ColorType
17
+
18
+
19
+ GRIDLINE_INTERPOLATION_STEPS: int
20
+
21
+ class Tick(martist.Artist):
22
+ axes: Axes
23
+ tick1line: Line2D
24
+ tick2line: Line2D
25
+ gridline: Line2D
26
+ label1: Text
27
+ label2: Text
28
+ def __init__(
29
+ self,
30
+ axes: Axes,
31
+ loc: float,
32
+ *,
33
+ size: float | None = ...,
34
+ width: float | None = ...,
35
+ color: ColorType | None = ...,
36
+ tickdir: Literal["in", "inout", "out"] | None = ...,
37
+ pad: float | None = ...,
38
+ labelsize: float | None = ...,
39
+ labelcolor: ColorType | None = ...,
40
+ labelfontfamily: str | Sequence[str] | None = ...,
41
+ zorder: float | None = ...,
42
+ gridOn: bool | None = ...,
43
+ tick1On: bool = ...,
44
+ tick2On: bool = ...,
45
+ label1On: bool = ...,
46
+ label2On: bool = ...,
47
+ major: bool = ...,
48
+ labelrotation: float = ...,
49
+ grid_color: ColorType | None = ...,
50
+ grid_linestyle: str | None = ...,
51
+ grid_linewidth: float | None = ...,
52
+ grid_alpha: float | None = ...,
53
+ **kwargs
54
+ ) -> None: ...
55
+ def get_tickdir(self) -> Literal["in", "inout", "out"]: ...
56
+ def get_tick_padding(self) -> float: ...
57
+ def get_children(self) -> list[martist.Artist]: ...
58
+ stale: bool
59
+ def set_pad(self, val: float) -> None: ...
60
+ def get_pad(self) -> None: ...
61
+ def get_loc(self) -> float: ...
62
+ def set_label1(self, s: object) -> None: ...
63
+ def set_label(self, s: object) -> None: ...
64
+ def set_label2(self, s: object) -> None: ...
65
+ def set_url(self, url: str | None) -> None: ...
66
+ def get_view_interval(self) -> ArrayLike: ...
67
+ def update_position(self, loc: float) -> None: ...
68
+
69
+ class XTick(Tick):
70
+ __name__: str
71
+ def __init__(self, *args, **kwargs) -> None: ...
72
+ stale: bool
73
+ def update_position(self, loc: float) -> None: ...
74
+ def get_view_interval(self) -> np.ndarray: ...
75
+
76
+ class YTick(Tick):
77
+ __name__: str
78
+ def __init__(self, *args, **kwargs) -> None: ...
79
+ stale: bool
80
+ def update_position(self, loc: float) -> None: ...
81
+ def get_view_interval(self) -> np.ndarray: ...
82
+
83
+ class Ticker:
84
+ def __init__(self) -> None: ...
85
+ @property
86
+ def locator(self) -> Locator | None: ...
87
+ @locator.setter
88
+ def locator(self, locator: Locator) -> None: ...
89
+ @property
90
+ def formatter(self) -> Formatter | None: ...
91
+ @formatter.setter
92
+ def formatter(self, formatter: Formatter) -> None: ...
93
+
94
+ class _LazyTickList:
95
+ def __init__(self, major: bool) -> None: ...
96
+ # Replace return with Self when py3.9 is dropped
97
+ @overload
98
+ def __get__(self, instance: None, owner: None) -> _LazyTickList: ...
99
+ @overload
100
+ def __get__(self, instance: Axis, owner: type[Axis]) -> list[Tick]: ...
101
+
102
+ class Axis(martist.Artist):
103
+ OFFSETTEXTPAD: int
104
+ isDefault_label: bool
105
+ axes: Axes
106
+ major: Ticker
107
+ minor: Ticker
108
+ callbacks: cbook.CallbackRegistry
109
+ label: Text
110
+ offsetText: Text
111
+ labelpad: float
112
+ pickradius: float
113
+ def __init__(self, axes, *, pickradius: float = ...,
114
+ clear: bool = ...) -> None: ...
115
+ @property
116
+ def isDefault_majloc(self) -> bool: ...
117
+ @isDefault_majloc.setter
118
+ def isDefault_majloc(self, value: bool) -> None: ...
119
+ @property
120
+ def isDefault_majfmt(self) -> bool: ...
121
+ @isDefault_majfmt.setter
122
+ def isDefault_majfmt(self, value: bool) -> None: ...
123
+ @property
124
+ def isDefault_minloc(self) -> bool: ...
125
+ @isDefault_minloc.setter
126
+ def isDefault_minloc(self, value: bool) -> None: ...
127
+ @property
128
+ def isDefault_minfmt(self) -> bool: ...
129
+ @isDefault_minfmt.setter
130
+ def isDefault_minfmt(self, value: bool) -> None: ...
131
+ majorTicks: _LazyTickList
132
+ minorTicks: _LazyTickList
133
+ def get_remove_overlapping_locs(self) -> bool: ...
134
+ def set_remove_overlapping_locs(self, val: bool) -> None: ...
135
+ @property
136
+ def remove_overlapping_locs(self) -> bool: ...
137
+ @remove_overlapping_locs.setter
138
+ def remove_overlapping_locs(self, val: bool) -> None: ...
139
+ stale: bool
140
+ def set_label_coords(
141
+ self, x: float, y: float, transform: Transform | None = ...
142
+ ) -> None: ...
143
+ def get_transform(self) -> Transform: ...
144
+ def get_scale(self) -> str: ...
145
+ def limit_range_for_scale(
146
+ self, vmin: float, vmax: float
147
+ ) -> tuple[float, float]: ...
148
+ def get_children(self) -> list[martist.Artist]: ...
149
+ # TODO units
150
+ converter: Any
151
+ units: Any
152
+ def clear(self) -> None: ...
153
+ def reset_ticks(self) -> None: ...
154
+ def minorticks_on(self) -> None: ...
155
+ def minorticks_off(self) -> None: ...
156
+ def set_tick_params(
157
+ self,
158
+ which: Literal["major", "minor", "both"] = ...,
159
+ reset: bool = ...,
160
+ **kwargs
161
+ ) -> None: ...
162
+ def get_tick_params(
163
+ self, which: Literal["major", "minor"] = ...
164
+ ) -> dict[str, Any]: ...
165
+ def get_view_interval(self) -> tuple[float, float]: ...
166
+ def set_view_interval(
167
+ self, vmin: float, vmax: float, ignore: bool = ...
168
+ ) -> None: ...
169
+ def get_data_interval(self) -> tuple[float, float]: ...
170
+ def set_data_interval(
171
+ self, vmin: float, vmax: float, ignore: bool = ...
172
+ ) -> None: ...
173
+ def get_inverted(self) -> bool: ...
174
+ def set_inverted(self, inverted: bool) -> None: ...
175
+ def set_default_intervals(self) -> None: ...
176
+ def get_tightbbox(
177
+ self, renderer: RendererBase | None = ..., *, for_layout_only: bool = ...
178
+ ) -> Bbox | None: ...
179
+ def get_tick_padding(self) -> float: ...
180
+ def get_gridlines(self) -> list[Line2D]: ...
181
+ def get_label(self) -> Text: ...
182
+ def get_offset_text(self) -> Text: ...
183
+ def get_pickradius(self) -> float: ...
184
+ def get_majorticklabels(self) -> list[Text]: ...
185
+ def get_minorticklabels(self) -> list[Text]: ...
186
+ def get_ticklabels(
187
+ self, minor: bool = ..., which: Literal["major", "minor", "both"] | None = ...
188
+ ) -> list[Text]: ...
189
+ def get_majorticklines(self) -> list[Line2D]: ...
190
+ def get_minorticklines(self) -> list[Line2D]: ...
191
+ def get_ticklines(self, minor: bool = ...) -> list[Line2D]: ...
192
+ def get_majorticklocs(self) -> np.ndarray: ...
193
+ def get_minorticklocs(self) -> np.ndarray: ...
194
+ def get_ticklocs(self, *, minor: bool = ...) -> np.ndarray: ...
195
+ def get_ticks_direction(self, minor: bool = ...) -> np.ndarray: ...
196
+ def get_label_text(self) -> str: ...
197
+ def get_major_locator(self) -> Locator: ...
198
+ def get_minor_locator(self) -> Locator: ...
199
+ def get_major_formatter(self) -> Formatter: ...
200
+ def get_minor_formatter(self) -> Formatter: ...
201
+ def get_major_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
202
+ def get_minor_ticks(self, numticks: int | None = ...) -> list[Tick]: ...
203
+ def grid(
204
+ self,
205
+ visible: bool | None = ...,
206
+ which: Literal["major", "minor", "both"] = ...,
207
+ **kwargs
208
+ ) -> None: ...
209
+ # TODO units
210
+ def update_units(self, data): ...
211
+ def have_units(self) -> bool: ...
212
+ def convert_units(self, x): ...
213
+ def set_units(self, u) -> None: ...
214
+ def get_units(self): ...
215
+ def set_label_text(
216
+ self, label: str, fontdict: dict[str, Any] | None = ..., **kwargs
217
+ ) -> Text: ...
218
+ def set_major_formatter(
219
+ self, formatter: Formatter | str | Callable[[float, float], str]
220
+ ) -> None: ...
221
+ def set_minor_formatter(
222
+ self, formatter: Formatter | str | Callable[[float, float], str]
223
+ ) -> None: ...
224
+ def set_major_locator(self, locator: Locator) -> None: ...
225
+ def set_minor_locator(self, locator: Locator) -> None: ...
226
+ def set_pickradius(self, pickradius: float) -> None: ...
227
+ def set_ticklabels(
228
+ self,
229
+ labels: Iterable[str | Text],
230
+ *,
231
+ minor: bool = ...,
232
+ fontdict: dict[str, Any] | None = ...,
233
+ **kwargs
234
+ ) -> list[Text]: ...
235
+ def set_ticks(
236
+ self,
237
+ ticks: ArrayLike,
238
+ labels: Iterable[str] | None = ...,
239
+ *,
240
+ minor: bool = ...,
241
+ **kwargs
242
+ ) -> list[Tick]: ...
243
+ def axis_date(self, tz: str | datetime.tzinfo | None = ...) -> None: ...
244
+ def get_tick_space(self) -> int: ...
245
+ def get_label_position(self) -> Literal["top", "bottom"]: ...
246
+ def set_label_position(
247
+ self, position: Literal["top", "bottom", "left", "right"]
248
+ ) -> None: ...
249
+ def get_minpos(self) -> float: ...
250
+
251
+ class XAxis(Axis):
252
+ __name__: str
253
+ axis_name: str
254
+ def __init__(self, *args, **kwargs) -> None: ...
255
+ label_position: Literal["bottom", "top"]
256
+ stale: bool
257
+ def set_label_position(self, position: Literal["bottom", "top"]) -> None: ... # type: ignore[override]
258
+ def set_ticks_position(
259
+ self, position: Literal["top", "bottom", "both", "default", "none"]
260
+ ) -> None: ...
261
+ def tick_top(self) -> None: ...
262
+ def tick_bottom(self) -> None: ...
263
+ def get_ticks_position(self) -> Literal["top", "bottom", "default", "unknown"]: ...
264
+ def get_tick_space(self) -> int: ...
265
+
266
+ class YAxis(Axis):
267
+ __name__: str
268
+ axis_name: str
269
+ def __init__(self, *args, **kwargs) -> None: ...
270
+ label_position: Literal["left", "right"]
271
+ stale: bool
272
+ def set_label_position(self, position: Literal["left", "right"]) -> None: ... # type: ignore[override]
273
+ def set_offset_position(self, position: Literal["left", "right"]) -> None: ...
274
+ def set_ticks_position(
275
+ self, position: Literal["left", "right", "both", "default", "none"]
276
+ ) -> None: ...
277
+ def tick_right(self) -> None: ...
278
+ def tick_left(self) -> None: ...
279
+ def get_ticks_position(self) -> Literal["left", "right", "default", "unknown"]: ...
280
+ def get_tick_space(self) -> int: ...
llava_next/lib/python3.10/site-packages/matplotlib/cbook.pyi ADDED
@@ -0,0 +1,186 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import collections.abc
2
+ from collections.abc import Callable, Collection, Generator, Iterable, Iterator
3
+ import contextlib
4
+ import os
5
+ from pathlib import Path
6
+
7
+ from matplotlib.artist import Artist
8
+
9
+ import numpy as np
10
+ from numpy.typing import ArrayLike
11
+
12
+ from typing import (
13
+ Any,
14
+ Generic,
15
+ IO,
16
+ Literal,
17
+ TypeVar,
18
+ overload,
19
+ )
20
+
21
+ _T = TypeVar("_T")
22
+
23
+ def _get_running_interactive_framework() -> str | None: ...
24
+
25
+ class CallbackRegistry:
26
+ exception_handler: Callable[[Exception], Any]
27
+ callbacks: dict[Any, dict[int, Any]]
28
+ def __init__(
29
+ self,
30
+ exception_handler: Callable[[Exception], Any] | None = ...,
31
+ *,
32
+ signals: Iterable[Any] | None = ...,
33
+ ) -> None: ...
34
+ def connect(self, signal: Any, func: Callable) -> int: ...
35
+ def disconnect(self, cid: int) -> None: ...
36
+ def process(self, s: Any, *args, **kwargs) -> None: ...
37
+ def blocked(
38
+ self, *, signal: Any | None = ...
39
+ ) -> contextlib.AbstractContextManager[None]: ...
40
+
41
+ class silent_list(list[_T]):
42
+ type: str | None
43
+ def __init__(self, type: str | None, seq: Iterable[_T] | None = ...) -> None: ...
44
+
45
+ def strip_math(s: str) -> str: ...
46
+ def is_writable_file_like(obj: Any) -> bool: ...
47
+ def file_requires_unicode(x: Any) -> bool: ...
48
+ @overload
49
+ def to_filehandle(
50
+ fname: str | os.PathLike | IO,
51
+ flag: str = ...,
52
+ return_opened: Literal[False] = ...,
53
+ encoding: str | None = ...,
54
+ ) -> IO: ...
55
+ @overload
56
+ def to_filehandle(
57
+ fname: str | os.PathLike | IO,
58
+ flag: str,
59
+ return_opened: Literal[True],
60
+ encoding: str | None = ...,
61
+ ) -> tuple[IO, bool]: ...
62
+ @overload
63
+ def to_filehandle(
64
+ fname: str | os.PathLike | IO,
65
+ *, # if flag given, will match previous sig
66
+ return_opened: Literal[True],
67
+ encoding: str | None = ...,
68
+ ) -> tuple[IO, bool]: ...
69
+ def open_file_cm(
70
+ path_or_file: str | os.PathLike | IO,
71
+ mode: str = ...,
72
+ encoding: str | None = ...,
73
+ ) -> contextlib.AbstractContextManager[IO]: ...
74
+ def is_scalar_or_string(val: Any) -> bool: ...
75
+ @overload
76
+ def get_sample_data(
77
+ fname: str | os.PathLike, asfileobj: Literal[True] = ..., *, np_load: Literal[True]
78
+ ) -> np.ndarray: ...
79
+ @overload
80
+ def get_sample_data(
81
+ fname: str | os.PathLike,
82
+ asfileobj: Literal[True] = ...,
83
+ *,
84
+ np_load: Literal[False] = ...,
85
+ ) -> IO: ...
86
+ @overload
87
+ def get_sample_data(
88
+ fname: str | os.PathLike, asfileobj: Literal[False], *, np_load: bool = ...
89
+ ) -> str: ...
90
+ def _get_data_path(*args: Path | str) -> Path: ...
91
+ def flatten(
92
+ seq: Iterable[Any], scalarp: Callable[[Any], bool] = ...
93
+ ) -> Generator[Any, None, None]: ...
94
+
95
+ class Stack(Generic[_T]):
96
+ def __init__(self, default: _T | None = ...) -> None: ...
97
+ def __call__(self) -> _T: ...
98
+ def __len__(self) -> int: ...
99
+ def __getitem__(self, ind: int) -> _T: ...
100
+ def forward(self) -> _T: ...
101
+ def back(self) -> _T: ...
102
+ def push(self, o: _T) -> _T: ...
103
+ def home(self) -> _T: ...
104
+ def empty(self) -> bool: ...
105
+ def clear(self) -> None: ...
106
+ def bubble(self, o: _T) -> _T: ...
107
+ def remove(self, o: _T) -> None: ...
108
+
109
+ def safe_masked_invalid(x: ArrayLike, copy: bool = ...) -> np.ndarray: ...
110
+ def print_cycles(
111
+ objects: Iterable[Any], outstream: IO = ..., show_progress: bool = ...
112
+ ) -> None: ...
113
+
114
+ class Grouper(Generic[_T]):
115
+ def __init__(self, init: Iterable[_T] = ...) -> None: ...
116
+ def __contains__(self, item: _T) -> bool: ...
117
+ def clean(self) -> None: ...
118
+ def join(self, a: _T, *args: _T) -> None: ...
119
+ def joined(self, a: _T, b: _T) -> bool: ...
120
+ def remove(self, a: _T) -> None: ...
121
+ def __iter__(self) -> Iterator[list[_T]]: ...
122
+ def get_siblings(self, a: _T) -> list[_T]: ...
123
+
124
+ class GrouperView(Generic[_T]):
125
+ def __init__(self, grouper: Grouper[_T]) -> None: ...
126
+ def __contains__(self, item: _T) -> bool: ...
127
+ def __iter__(self) -> Iterator[list[_T]]: ...
128
+ def joined(self, a: _T, b: _T) -> bool: ...
129
+ def get_siblings(self, a: _T) -> list[_T]: ...
130
+
131
+ def simple_linear_interpolation(a: ArrayLike, steps: int) -> np.ndarray: ...
132
+ def delete_masked_points(*args): ...
133
+ def _broadcast_with_masks(*args: ArrayLike, compress: bool = ...) -> list[ArrayLike]: ...
134
+ def boxplot_stats(
135
+ X: ArrayLike,
136
+ whis: float | tuple[float, float] = ...,
137
+ bootstrap: int | None = ...,
138
+ labels: ArrayLike | None = ...,
139
+ autorange: bool = ...,
140
+ ) -> list[dict[str, Any]]: ...
141
+
142
+ ls_mapper: dict[str, str]
143
+ ls_mapper_r: dict[str, str]
144
+
145
+ def contiguous_regions(mask: ArrayLike) -> list[np.ndarray]: ...
146
+ def is_math_text(s: str) -> bool: ...
147
+ def violin_stats(
148
+ X: ArrayLike, method: Callable, points: int = ..., quantiles: ArrayLike | None = ...
149
+ ) -> list[dict[str, Any]]: ...
150
+ def pts_to_prestep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ...
151
+ def pts_to_poststep(x: ArrayLike, *args: ArrayLike) -> np.ndarray: ...
152
+ def pts_to_midstep(x: np.ndarray, *args: np.ndarray) -> np.ndarray: ...
153
+
154
+ STEP_LOOKUP_MAP: dict[str, Callable]
155
+
156
+ def index_of(y: float | ArrayLike) -> tuple[np.ndarray, np.ndarray]: ...
157
+ def safe_first_element(obj: Collection[_T]) -> _T: ...
158
+ def sanitize_sequence(data): ...
159
+ def normalize_kwargs(
160
+ kw: dict[str, Any],
161
+ alias_mapping: dict[str, list[str]] | type[Artist] | Artist | None = ...,
162
+ ) -> dict[str, Any]: ...
163
+ def _lock_path(path: str | os.PathLike) -> contextlib.AbstractContextManager[None]: ...
164
+ def _str_equal(obj: Any, s: str) -> bool: ...
165
+ def _str_lower_equal(obj: Any, s: str) -> bool: ...
166
+ def _array_perimeter(arr: np.ndarray) -> np.ndarray: ...
167
+ def _unfold(arr: np.ndarray, axis: int, size: int, step: int) -> np.ndarray: ...
168
+ def _array_patch_perimeters(x: np.ndarray, rstride: int, cstride: int) -> np.ndarray: ...
169
+ def _setattr_cm(obj: Any, **kwargs) -> contextlib.AbstractContextManager[None]: ...
170
+
171
+ class _OrderedSet(collections.abc.MutableSet):
172
+ def __init__(self) -> None: ...
173
+ def __contains__(self, key) -> bool: ...
174
+ def __iter__(self): ...
175
+ def __len__(self) -> int: ...
176
+ def add(self, key) -> None: ...
177
+ def discard(self, key) -> None: ...
178
+
179
+ def _setup_new_guiapp() -> None: ...
180
+ def _format_approx(number: float, precision: int) -> str: ...
181
+ def _g_sig_digits(value: float, delta: float) -> int: ...
182
+ def _unikey_or_keysym_to_mplkey(unikey: str, keysym: str) -> str: ...
183
+ def _is_torch_array(x: Any) -> bool: ...
184
+ def _is_jax_array(x: Any) -> bool: ...
185
+ def _unpack_to_numpy(x: Any) -> Any: ...
186
+ def _auto_format_str(fmt: str, value: Any) -> str: ...
llava_next/lib/python3.10/site-packages/matplotlib/cm.py ADDED
@@ -0,0 +1,664 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Builtin colormaps, colormap handling utilities, and the `ScalarMappable` mixin.
3
+
4
+ .. seealso::
5
+
6
+ :doc:`/gallery/color/colormap_reference` for a list of builtin colormaps.
7
+
8
+ :ref:`colormap-manipulation` for examples of how to make
9
+ colormaps.
10
+
11
+ :ref:`colormaps` an in-depth discussion of choosing
12
+ colormaps.
13
+
14
+ :ref:`colormapnorms` for more details about data normalization.
15
+ """
16
+
17
+ from collections.abc import Mapping
18
+ import functools
19
+
20
+ import numpy as np
21
+ from numpy import ma
22
+
23
+ import matplotlib as mpl
24
+ from matplotlib import _api, colors, cbook, scale
25
+ from matplotlib._cm import datad
26
+ from matplotlib._cm_listed import cmaps as cmaps_listed
27
+
28
+
29
+ _LUTSIZE = mpl.rcParams['image.lut']
30
+
31
+
32
+ def _gen_cmap_registry():
33
+ """
34
+ Generate a dict mapping standard colormap names to standard colormaps, as
35
+ well as the reversed colormaps.
36
+ """
37
+ cmap_d = {**cmaps_listed}
38
+ for name, spec in datad.items():
39
+ cmap_d[name] = ( # Precache the cmaps at a fixed lutsize..
40
+ colors.LinearSegmentedColormap(name, spec, _LUTSIZE)
41
+ if 'red' in spec else
42
+ colors.ListedColormap(spec['listed'], name)
43
+ if 'listed' in spec else
44
+ colors.LinearSegmentedColormap.from_list(name, spec, _LUTSIZE))
45
+
46
+ # Register colormap aliases for gray and grey.
47
+ cmap_d['grey'] = cmap_d['gray']
48
+ cmap_d['gist_grey'] = cmap_d['gist_gray']
49
+ cmap_d['gist_yerg'] = cmap_d['gist_yarg']
50
+ cmap_d['Grays'] = cmap_d['Greys']
51
+
52
+ # Generate reversed cmaps.
53
+ for cmap in list(cmap_d.values()):
54
+ rmap = cmap.reversed()
55
+ cmap_d[rmap.name] = rmap
56
+ return cmap_d
57
+
58
+
59
+ class ColormapRegistry(Mapping):
60
+ r"""
61
+ Container for colormaps that are known to Matplotlib by name.
62
+
63
+ The universal registry instance is `matplotlib.colormaps`. There should be
64
+ no need for users to instantiate `.ColormapRegistry` themselves.
65
+
66
+ Read access uses a dict-like interface mapping names to `.Colormap`\s::
67
+
68
+ import matplotlib as mpl
69
+ cmap = mpl.colormaps['viridis']
70
+
71
+ Returned `.Colormap`\s are copies, so that their modification does not
72
+ change the global definition of the colormap.
73
+
74
+ Additional colormaps can be added via `.ColormapRegistry.register`::
75
+
76
+ mpl.colormaps.register(my_colormap)
77
+
78
+ To get a list of all registered colormaps, you can do::
79
+
80
+ from matplotlib import colormaps
81
+ list(colormaps)
82
+ """
83
+ def __init__(self, cmaps):
84
+ self._cmaps = cmaps
85
+ self._builtin_cmaps = tuple(cmaps)
86
+
87
+ def __getitem__(self, item):
88
+ try:
89
+ return self._cmaps[item].copy()
90
+ except KeyError:
91
+ raise KeyError(f"{item!r} is not a known colormap name") from None
92
+
93
+ def __iter__(self):
94
+ return iter(self._cmaps)
95
+
96
+ def __len__(self):
97
+ return len(self._cmaps)
98
+
99
+ def __str__(self):
100
+ return ('ColormapRegistry; available colormaps:\n' +
101
+ ', '.join(f"'{name}'" for name in self))
102
+
103
+ def __call__(self):
104
+ """
105
+ Return a list of the registered colormap names.
106
+
107
+ This exists only for backward-compatibility in `.pyplot` which had a
108
+ ``plt.colormaps()`` method. The recommended way to get this list is
109
+ now ``list(colormaps)``.
110
+ """
111
+ return list(self)
112
+
113
+ def register(self, cmap, *, name=None, force=False):
114
+ """
115
+ Register a new colormap.
116
+
117
+ The colormap name can then be used as a string argument to any ``cmap``
118
+ parameter in Matplotlib. It is also available in ``pyplot.get_cmap``.
119
+
120
+ The colormap registry stores a copy of the given colormap, so that
121
+ future changes to the original colormap instance do not affect the
122
+ registered colormap. Think of this as the registry taking a snapshot
123
+ of the colormap at registration.
124
+
125
+ Parameters
126
+ ----------
127
+ cmap : matplotlib.colors.Colormap
128
+ The colormap to register.
129
+
130
+ name : str, optional
131
+ The name for the colormap. If not given, ``cmap.name`` is used.
132
+
133
+ force : bool, default: False
134
+ If False, a ValueError is raised if trying to overwrite an already
135
+ registered name. True supports overwriting registered colormaps
136
+ other than the builtin colormaps.
137
+ """
138
+ _api.check_isinstance(colors.Colormap, cmap=cmap)
139
+
140
+ name = name or cmap.name
141
+ if name in self:
142
+ if not force:
143
+ # don't allow registering an already existing cmap
144
+ # unless explicitly asked to
145
+ raise ValueError(
146
+ f'A colormap named "{name}" is already registered.')
147
+ elif name in self._builtin_cmaps:
148
+ # We don't allow overriding a builtin.
149
+ raise ValueError("Re-registering the builtin cmap "
150
+ f"{name!r} is not allowed.")
151
+
152
+ # Warn that we are updating an already existing colormap
153
+ _api.warn_external(f"Overwriting the cmap {name!r} "
154
+ "that was already in the registry.")
155
+
156
+ self._cmaps[name] = cmap.copy()
157
+ # Someone may set the extremes of a builtin colormap and want to register it
158
+ # with a different name for future lookups. The object would still have the
159
+ # builtin name, so we should update it to the registered name
160
+ if self._cmaps[name].name != name:
161
+ self._cmaps[name].name = name
162
+
163
+ def unregister(self, name):
164
+ """
165
+ Remove a colormap from the registry.
166
+
167
+ You cannot remove built-in colormaps.
168
+
169
+ If the named colormap is not registered, returns with no error, raises
170
+ if you try to de-register a default colormap.
171
+
172
+ .. warning::
173
+
174
+ Colormap names are currently a shared namespace that may be used
175
+ by multiple packages. Use `unregister` only if you know you
176
+ have registered that name before. In particular, do not
177
+ unregister just in case to clean the name before registering a
178
+ new colormap.
179
+
180
+ Parameters
181
+ ----------
182
+ name : str
183
+ The name of the colormap to be removed.
184
+
185
+ Raises
186
+ ------
187
+ ValueError
188
+ If you try to remove a default built-in colormap.
189
+ """
190
+ if name in self._builtin_cmaps:
191
+ raise ValueError(f"cannot unregister {name!r} which is a builtin "
192
+ "colormap.")
193
+ self._cmaps.pop(name, None)
194
+
195
+ def get_cmap(self, cmap):
196
+ """
197
+ Return a color map specified through *cmap*.
198
+
199
+ Parameters
200
+ ----------
201
+ cmap : str or `~matplotlib.colors.Colormap` or None
202
+
203
+ - if a `.Colormap`, return it
204
+ - if a string, look it up in ``mpl.colormaps``
205
+ - if None, return the Colormap defined in :rc:`image.cmap`
206
+
207
+ Returns
208
+ -------
209
+ Colormap
210
+ """
211
+ # get the default color map
212
+ if cmap is None:
213
+ return self[mpl.rcParams["image.cmap"]]
214
+
215
+ # if the user passed in a Colormap, simply return it
216
+ if isinstance(cmap, colors.Colormap):
217
+ return cmap
218
+ if isinstance(cmap, str):
219
+ _api.check_in_list(sorted(_colormaps), cmap=cmap)
220
+ # otherwise, it must be a string so look it up
221
+ return self[cmap]
222
+ raise TypeError(
223
+ 'get_cmap expects None or an instance of a str or Colormap . ' +
224
+ f'you passed {cmap!r} of type {type(cmap)}'
225
+ )
226
+
227
+
228
+ # public access to the colormaps should be via `matplotlib.colormaps`. For now,
229
+ # we still create the registry here, but that should stay an implementation
230
+ # detail.
231
+ _colormaps = ColormapRegistry(_gen_cmap_registry())
232
+ globals().update(_colormaps)
233
+
234
+
235
+ # This is an exact copy of pyplot.get_cmap(). It was removed in 3.9, but apparently
236
+ # caused more user trouble than expected. Re-added for 3.9.1 and extended the
237
+ # deprecation period for two additional minor releases.
238
+ @_api.deprecated(
239
+ '3.7',
240
+ removal='3.11',
241
+ alternative="``matplotlib.colormaps[name]`` or ``matplotlib.colormaps.get_cmap()``"
242
+ " or ``pyplot.get_cmap()``"
243
+ )
244
+ def get_cmap(name=None, lut=None):
245
+ """
246
+ Get a colormap instance, defaulting to rc values if *name* is None.
247
+
248
+ Parameters
249
+ ----------
250
+ name : `~matplotlib.colors.Colormap` or str or None, default: None
251
+ If a `.Colormap` instance, it will be returned. Otherwise, the name of
252
+ a colormap known to Matplotlib, which will be resampled by *lut*. The
253
+ default, None, means :rc:`image.cmap`.
254
+ lut : int or None, default: None
255
+ If *name* is not already a Colormap instance and *lut* is not None, the
256
+ colormap will be resampled to have *lut* entries in the lookup table.
257
+
258
+ Returns
259
+ -------
260
+ Colormap
261
+ """
262
+ if name is None:
263
+ name = mpl.rcParams['image.cmap']
264
+ if isinstance(name, colors.Colormap):
265
+ return name
266
+ _api.check_in_list(sorted(_colormaps), name=name)
267
+ if lut is None:
268
+ return _colormaps[name]
269
+ else:
270
+ return _colormaps[name].resampled(lut)
271
+
272
+
273
+ def _auto_norm_from_scale(scale_cls):
274
+ """
275
+ Automatically generate a norm class from *scale_cls*.
276
+
277
+ This differs from `.colors.make_norm_from_scale` in the following points:
278
+
279
+ - This function is not a class decorator, but directly returns a norm class
280
+ (as if decorating `.Normalize`).
281
+ - The scale is automatically constructed with ``nonpositive="mask"``, if it
282
+ supports such a parameter, to work around the difference in defaults
283
+ between standard scales (which use "clip") and norms (which use "mask").
284
+
285
+ Note that ``make_norm_from_scale`` caches the generated norm classes
286
+ (not the instances) and reuses them for later calls. For example,
287
+ ``type(_auto_norm_from_scale("log")) == LogNorm``.
288
+ """
289
+ # Actually try to construct an instance, to verify whether
290
+ # ``nonpositive="mask"`` is supported.
291
+ try:
292
+ norm = colors.make_norm_from_scale(
293
+ functools.partial(scale_cls, nonpositive="mask"))(
294
+ colors.Normalize)()
295
+ except TypeError:
296
+ norm = colors.make_norm_from_scale(scale_cls)(
297
+ colors.Normalize)()
298
+ return type(norm)
299
+
300
+
301
+ class ScalarMappable:
302
+ """
303
+ A mixin class to map scalar data to RGBA.
304
+
305
+ The ScalarMappable applies data normalization before returning RGBA colors
306
+ from the given colormap.
307
+ """
308
+
309
+ def __init__(self, norm=None, cmap=None):
310
+ """
311
+ Parameters
312
+ ----------
313
+ norm : `.Normalize` (or subclass thereof) or str or None
314
+ The normalizing object which scales data, typically into the
315
+ interval ``[0, 1]``.
316
+ If a `str`, a `.Normalize` subclass is dynamically generated based
317
+ on the scale with the corresponding name.
318
+ If *None*, *norm* defaults to a *colors.Normalize* object which
319
+ initializes its scaling based on the first data processed.
320
+ cmap : str or `~matplotlib.colors.Colormap`
321
+ The colormap used to map normalized data values to RGBA colors.
322
+ """
323
+ self._A = None
324
+ self._norm = None # So that the setter knows we're initializing.
325
+ self.set_norm(norm) # The Normalize instance of this ScalarMappable.
326
+ self.cmap = None # So that the setter knows we're initializing.
327
+ self.set_cmap(cmap) # The Colormap instance of this ScalarMappable.
328
+ #: The last colorbar associated with this ScalarMappable. May be None.
329
+ self.colorbar = None
330
+ self.callbacks = cbook.CallbackRegistry(signals=["changed"])
331
+
332
+ def _scale_norm(self, norm, vmin, vmax):
333
+ """
334
+ Helper for initial scaling.
335
+
336
+ Used by public functions that create a ScalarMappable and support
337
+ parameters *vmin*, *vmax* and *norm*. This makes sure that a *norm*
338
+ will take precedence over *vmin*, *vmax*.
339
+
340
+ Note that this method does not set the norm.
341
+ """
342
+ if vmin is not None or vmax is not None:
343
+ self.set_clim(vmin, vmax)
344
+ if isinstance(norm, colors.Normalize):
345
+ raise ValueError(
346
+ "Passing a Normalize instance simultaneously with "
347
+ "vmin/vmax is not supported. Please pass vmin/vmax "
348
+ "directly to the norm when creating it.")
349
+
350
+ # always resolve the autoscaling so we have concrete limits
351
+ # rather than deferring to draw time.
352
+ self.autoscale_None()
353
+
354
+ def to_rgba(self, x, alpha=None, bytes=False, norm=True):
355
+ """
356
+ Return a normalized RGBA array corresponding to *x*.
357
+
358
+ In the normal case, *x* is a 1D or 2D sequence of scalars, and
359
+ the corresponding `~numpy.ndarray` of RGBA values will be returned,
360
+ based on the norm and colormap set for this ScalarMappable.
361
+
362
+ There is one special case, for handling images that are already
363
+ RGB or RGBA, such as might have been read from an image file.
364
+ If *x* is an `~numpy.ndarray` with 3 dimensions,
365
+ and the last dimension is either 3 or 4, then it will be
366
+ treated as an RGB or RGBA array, and no mapping will be done.
367
+ The array can be `~numpy.uint8`, or it can be floats with
368
+ values in the 0-1 range; otherwise a ValueError will be raised.
369
+ Any NaNs or masked elements will be set to 0 alpha.
370
+ If the last dimension is 3, the *alpha* kwarg (defaulting to 1)
371
+ will be used to fill in the transparency. If the last dimension
372
+ is 4, the *alpha* kwarg is ignored; it does not
373
+ replace the preexisting alpha. A ValueError will be raised
374
+ if the third dimension is other than 3 or 4.
375
+
376
+ In either case, if *bytes* is *False* (default), the RGBA
377
+ array will be floats in the 0-1 range; if it is *True*,
378
+ the returned RGBA array will be `~numpy.uint8` in the 0 to 255 range.
379
+
380
+ If norm is False, no normalization of the input data is
381
+ performed, and it is assumed to be in the range (0-1).
382
+
383
+ """
384
+ # First check for special case, image input:
385
+ try:
386
+ if x.ndim == 3:
387
+ if x.shape[2] == 3:
388
+ if alpha is None:
389
+ alpha = 1
390
+ if x.dtype == np.uint8:
391
+ alpha = np.uint8(alpha * 255)
392
+ m, n = x.shape[:2]
393
+ xx = np.empty(shape=(m, n, 4), dtype=x.dtype)
394
+ xx[:, :, :3] = x
395
+ xx[:, :, 3] = alpha
396
+ elif x.shape[2] == 4:
397
+ xx = x
398
+ else:
399
+ raise ValueError("Third dimension must be 3 or 4")
400
+ if xx.dtype.kind == 'f':
401
+ # If any of R, G, B, or A is nan, set to 0
402
+ if np.any(nans := np.isnan(x)):
403
+ if x.shape[2] == 4:
404
+ xx = xx.copy()
405
+ xx[np.any(nans, axis=2), :] = 0
406
+
407
+ if norm and (xx.max() > 1 or xx.min() < 0):
408
+ raise ValueError("Floating point image RGB values "
409
+ "must be in the 0..1 range.")
410
+ if bytes:
411
+ xx = (xx * 255).astype(np.uint8)
412
+ elif xx.dtype == np.uint8:
413
+ if not bytes:
414
+ xx = xx.astype(np.float32) / 255
415
+ else:
416
+ raise ValueError("Image RGB array must be uint8 or "
417
+ "floating point; found %s" % xx.dtype)
418
+ # Account for any masked entries in the original array
419
+ # If any of R, G, B, or A are masked for an entry, we set alpha to 0
420
+ if np.ma.is_masked(x):
421
+ xx[np.any(np.ma.getmaskarray(x), axis=2), 3] = 0
422
+ return xx
423
+ except AttributeError:
424
+ # e.g., x is not an ndarray; so try mapping it
425
+ pass
426
+
427
+ # This is the normal case, mapping a scalar array:
428
+ x = ma.asarray(x)
429
+ if norm:
430
+ x = self.norm(x)
431
+ rgba = self.cmap(x, alpha=alpha, bytes=bytes)
432
+ return rgba
433
+
434
+ def set_array(self, A):
435
+ """
436
+ Set the value array from array-like *A*.
437
+
438
+ Parameters
439
+ ----------
440
+ A : array-like or None
441
+ The values that are mapped to colors.
442
+
443
+ The base class `.ScalarMappable` does not make any assumptions on
444
+ the dimensionality and shape of the value array *A*.
445
+ """
446
+ if A is None:
447
+ self._A = None
448
+ return
449
+
450
+ A = cbook.safe_masked_invalid(A, copy=True)
451
+ if not np.can_cast(A.dtype, float, "same_kind"):
452
+ raise TypeError(f"Image data of dtype {A.dtype} cannot be "
453
+ "converted to float")
454
+
455
+ self._A = A
456
+ if not self.norm.scaled():
457
+ self.norm.autoscale_None(A)
458
+
459
+ def get_array(self):
460
+ """
461
+ Return the array of values, that are mapped to colors.
462
+
463
+ The base class `.ScalarMappable` does not make any assumptions on
464
+ the dimensionality and shape of the array.
465
+ """
466
+ return self._A
467
+
468
+ def get_cmap(self):
469
+ """Return the `.Colormap` instance."""
470
+ return self.cmap
471
+
472
+ def get_clim(self):
473
+ """
474
+ Return the values (min, max) that are mapped to the colormap limits.
475
+ """
476
+ return self.norm.vmin, self.norm.vmax
477
+
478
+ def set_clim(self, vmin=None, vmax=None):
479
+ """
480
+ Set the norm limits for image scaling.
481
+
482
+ Parameters
483
+ ----------
484
+ vmin, vmax : float
485
+ The limits.
486
+
487
+ The limits may also be passed as a tuple (*vmin*, *vmax*) as a
488
+ single positional argument.
489
+
490
+ .. ACCEPTS: (vmin: float, vmax: float)
491
+ """
492
+ # If the norm's limits are updated self.changed() will be called
493
+ # through the callbacks attached to the norm
494
+ if vmax is None:
495
+ try:
496
+ vmin, vmax = vmin
497
+ except (TypeError, ValueError):
498
+ pass
499
+ if vmin is not None:
500
+ self.norm.vmin = colors._sanitize_extrema(vmin)
501
+ if vmax is not None:
502
+ self.norm.vmax = colors._sanitize_extrema(vmax)
503
+
504
+ def get_alpha(self):
505
+ """
506
+ Returns
507
+ -------
508
+ float
509
+ Always returns 1.
510
+ """
511
+ # This method is intended to be overridden by Artist sub-classes
512
+ return 1.
513
+
514
+ def set_cmap(self, cmap):
515
+ """
516
+ Set the colormap for luminance data.
517
+
518
+ Parameters
519
+ ----------
520
+ cmap : `.Colormap` or str or None
521
+ """
522
+ in_init = self.cmap is None
523
+
524
+ self.cmap = _ensure_cmap(cmap)
525
+ if not in_init:
526
+ self.changed() # Things are not set up properly yet.
527
+
528
+ @property
529
+ def norm(self):
530
+ return self._norm
531
+
532
+ @norm.setter
533
+ def norm(self, norm):
534
+ _api.check_isinstance((colors.Normalize, str, None), norm=norm)
535
+ if norm is None:
536
+ norm = colors.Normalize()
537
+ elif isinstance(norm, str):
538
+ try:
539
+ scale_cls = scale._scale_mapping[norm]
540
+ except KeyError:
541
+ raise ValueError(
542
+ "Invalid norm str name; the following values are "
543
+ f"supported: {', '.join(scale._scale_mapping)}"
544
+ ) from None
545
+ norm = _auto_norm_from_scale(scale_cls)()
546
+
547
+ if norm is self.norm:
548
+ # We aren't updating anything
549
+ return
550
+
551
+ in_init = self.norm is None
552
+ # Remove the current callback and connect to the new one
553
+ if not in_init:
554
+ self.norm.callbacks.disconnect(self._id_norm)
555
+ self._norm = norm
556
+ self._id_norm = self.norm.callbacks.connect('changed',
557
+ self.changed)
558
+ if not in_init:
559
+ self.changed()
560
+
561
+ def set_norm(self, norm):
562
+ """
563
+ Set the normalization instance.
564
+
565
+ Parameters
566
+ ----------
567
+ norm : `.Normalize` or str or None
568
+
569
+ Notes
570
+ -----
571
+ If there are any colorbars using the mappable for this norm, setting
572
+ the norm of the mappable will reset the norm, locator, and formatters
573
+ on the colorbar to default.
574
+ """
575
+ self.norm = norm
576
+
577
+ def autoscale(self):
578
+ """
579
+ Autoscale the scalar limits on the norm instance using the
580
+ current array
581
+ """
582
+ if self._A is None:
583
+ raise TypeError('You must first set_array for mappable')
584
+ # If the norm's limits are updated self.changed() will be called
585
+ # through the callbacks attached to the norm
586
+ self.norm.autoscale(self._A)
587
+
588
+ def autoscale_None(self):
589
+ """
590
+ Autoscale the scalar limits on the norm instance using the
591
+ current array, changing only limits that are None
592
+ """
593
+ if self._A is None:
594
+ raise TypeError('You must first set_array for mappable')
595
+ # If the norm's limits are updated self.changed() will be called
596
+ # through the callbacks attached to the norm
597
+ self.norm.autoscale_None(self._A)
598
+
599
+ def changed(self):
600
+ """
601
+ Call this whenever the mappable is changed to notify all the
602
+ callbackSM listeners to the 'changed' signal.
603
+ """
604
+ self.callbacks.process('changed', self)
605
+ self.stale = True
606
+
607
+
608
+ # The docstrings here must be generic enough to apply to all relevant methods.
609
+ mpl._docstring.interpd.update(
610
+ cmap_doc="""\
611
+ cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
612
+ The Colormap instance or registered colormap name used to map scalar data
613
+ to colors.""",
614
+ norm_doc="""\
615
+ norm : str or `~matplotlib.colors.Normalize`, optional
616
+ The normalization method used to scale scalar data to the [0, 1] range
617
+ before mapping to colors using *cmap*. By default, a linear scaling is
618
+ used, mapping the lowest value to 0 and the highest to 1.
619
+
620
+ If given, this can be one of the following:
621
+
622
+ - An instance of `.Normalize` or one of its subclasses
623
+ (see :ref:`colormapnorms`).
624
+ - A scale name, i.e. one of "linear", "log", "symlog", "logit", etc. For a
625
+ list of available scales, call `matplotlib.scale.get_scale_names()`.
626
+ In that case, a suitable `.Normalize` subclass is dynamically generated
627
+ and instantiated.""",
628
+ vmin_vmax_doc="""\
629
+ vmin, vmax : float, optional
630
+ When using scalar data and no explicit *norm*, *vmin* and *vmax* define
631
+ the data range that the colormap covers. By default, the colormap covers
632
+ the complete value range of the supplied data. It is an error to use
633
+ *vmin*/*vmax* when a *norm* instance is given (but using a `str` *norm*
634
+ name together with *vmin*/*vmax* is acceptable).""",
635
+ )
636
+
637
+
638
+ def _ensure_cmap(cmap):
639
+ """
640
+ Ensure that we have a `.Colormap` object.
641
+
642
+ For internal use to preserve type stability of errors.
643
+
644
+ Parameters
645
+ ----------
646
+ cmap : None, str, Colormap
647
+
648
+ - if a `Colormap`, return it
649
+ - if a string, look it up in mpl.colormaps
650
+ - if None, look up the default color map in mpl.colormaps
651
+
652
+ Returns
653
+ -------
654
+ Colormap
655
+
656
+ """
657
+ if isinstance(cmap, colors.Colormap):
658
+ return cmap
659
+ cmap_name = cmap if cmap is not None else mpl.rcParams["image.cmap"]
660
+ # use check_in_list to ensure type stability of the exception raised by
661
+ # the internal usage of this (ValueError vs KeyError)
662
+ if cmap_name not in _colormaps:
663
+ _api.check_in_list(sorted(_colormaps), cmap=cmap_name)
664
+ return mpl.colormaps[cmap_name]
llava_next/lib/python3.10/site-packages/matplotlib/collections.pyi ADDED
@@ -0,0 +1,236 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Iterable, Sequence
2
+ from typing import Literal
3
+
4
+ import numpy as np
5
+ from numpy.typing import ArrayLike, NDArray
6
+
7
+ from . import artist, cm, transforms
8
+ from .backend_bases import MouseEvent
9
+ from .artist import Artist
10
+ from .colors import Normalize, Colormap
11
+ from .lines import Line2D
12
+ from .path import Path
13
+ from .patches import Patch
14
+ from .ticker import Locator, Formatter
15
+ from .tri import Triangulation
16
+ from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
17
+
18
+ class Collection(artist.Artist, cm.ScalarMappable):
19
+ def __init__(
20
+ self,
21
+ *,
22
+ edgecolors: ColorType | Sequence[ColorType] | None = ...,
23
+ facecolors: ColorType | Sequence[ColorType] | None = ...,
24
+ linewidths: float | Sequence[float] | None = ...,
25
+ linestyles: LineStyleType | Sequence[LineStyleType] = ...,
26
+ capstyle: CapStyleType | None = ...,
27
+ joinstyle: JoinStyleType | None = ...,
28
+ antialiaseds: bool | Sequence[bool] | None = ...,
29
+ offsets: tuple[float, float] | Sequence[tuple[float, float]] | None = ...,
30
+ offset_transform: transforms.Transform | None = ...,
31
+ norm: Normalize | None = ...,
32
+ cmap: Colormap | None = ...,
33
+ pickradius: float = ...,
34
+ hatch: str | None = ...,
35
+ urls: Sequence[str] | None = ...,
36
+ zorder: float = ...,
37
+ **kwargs
38
+ ) -> None: ...
39
+ def get_paths(self) -> Sequence[Path]: ...
40
+ def set_paths(self, paths: Sequence[Path]) -> None: ...
41
+ def get_transforms(self) -> Sequence[transforms.Transform]: ...
42
+ def get_offset_transform(self) -> transforms.Transform: ...
43
+ def set_offset_transform(self, offset_transform: transforms.Transform) -> None: ...
44
+ def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ...
45
+ def set_pickradius(self, pickradius: float) -> None: ...
46
+ def get_pickradius(self) -> float: ...
47
+ def set_urls(self, urls: Sequence[str | None]) -> None: ...
48
+ def get_urls(self) -> Sequence[str | None]: ...
49
+ def set_hatch(self, hatch: str) -> None: ...
50
+ def get_hatch(self) -> str: ...
51
+ def set_offsets(self, offsets: ArrayLike) -> None: ...
52
+ def get_offsets(self) -> ArrayLike: ...
53
+ def set_linewidth(self, lw: float | Sequence[float]) -> None: ...
54
+ def set_linestyle(self, ls: LineStyleType | Sequence[LineStyleType]) -> None: ...
55
+ def set_capstyle(self, cs: CapStyleType) -> None: ...
56
+ def get_capstyle(self) -> Literal["butt", "projecting", "round"] | None: ...
57
+ def set_joinstyle(self, js: JoinStyleType) -> None: ...
58
+ def get_joinstyle(self) -> Literal["miter", "round", "bevel"] | None: ...
59
+ def set_antialiased(self, aa: bool | Sequence[bool]) -> None: ...
60
+ def get_antialiased(self) -> NDArray[np.bool_]: ...
61
+ def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ...
62
+ def set_facecolor(self, c: ColorType | Sequence[ColorType]) -> None: ...
63
+ def get_facecolor(self) -> ColorType | Sequence[ColorType]: ...
64
+ def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ...
65
+ def set_edgecolor(self, c: ColorType | Sequence[ColorType]) -> None: ...
66
+ def set_alpha(self, alpha: float | Sequence[float] | None) -> None: ...
67
+ def get_linewidth(self) -> float | Sequence[float]: ...
68
+ def get_linestyle(self) -> LineStyleType | Sequence[LineStyleType]: ...
69
+ def update_scalarmappable(self) -> None: ...
70
+ def get_fill(self) -> bool: ...
71
+ def update_from(self, other: Artist) -> None: ...
72
+
73
+ class _CollectionWithSizes(Collection):
74
+ def get_sizes(self) -> np.ndarray: ...
75
+ def set_sizes(self, sizes: ArrayLike | None, dpi: float = ...) -> None: ...
76
+
77
+ class PathCollection(_CollectionWithSizes):
78
+ def __init__(
79
+ self, paths: Sequence[Path], sizes: ArrayLike | None = ..., **kwargs
80
+ ) -> None: ...
81
+ def set_paths(self, paths: Sequence[Path]) -> None: ...
82
+ def get_paths(self) -> Sequence[Path]: ...
83
+ def legend_elements(
84
+ self,
85
+ prop: Literal["colors", "sizes"] = ...,
86
+ num: int | Literal["auto"] | ArrayLike | Locator = ...,
87
+ fmt: str | Formatter | None = ...,
88
+ func: Callable[[ArrayLike], ArrayLike] = ...,
89
+ **kwargs,
90
+ ) -> tuple[list[Line2D], list[str]]: ...
91
+
92
+ class PolyCollection(_CollectionWithSizes):
93
+ def __init__(
94
+ self,
95
+ verts: Sequence[ArrayLike],
96
+ sizes: ArrayLike | None = ...,
97
+ *,
98
+ closed: bool = ...,
99
+ **kwargs
100
+ ) -> None: ...
101
+ def set_verts(
102
+ self, verts: Sequence[ArrayLike | Path], closed: bool = ...
103
+ ) -> None: ...
104
+ def set_paths(self, verts: Sequence[Path], closed: bool = ...) -> None: ...
105
+ def set_verts_and_codes(
106
+ self, verts: Sequence[ArrayLike | Path], codes: Sequence[int]
107
+ ) -> None: ...
108
+
109
+ class RegularPolyCollection(_CollectionWithSizes):
110
+ def __init__(
111
+ self, numsides: int, *, rotation: float = ..., sizes: ArrayLike = ..., **kwargs
112
+ ) -> None: ...
113
+ def get_numsides(self) -> int: ...
114
+ def get_rotation(self) -> float: ...
115
+
116
+ class StarPolygonCollection(RegularPolyCollection): ...
117
+ class AsteriskPolygonCollection(RegularPolyCollection): ...
118
+
119
+ class LineCollection(Collection):
120
+ def __init__(
121
+ self, segments: Sequence[ArrayLike], *, zorder: float = ..., **kwargs
122
+ ) -> None: ...
123
+ def set_segments(self, segments: Sequence[ArrayLike] | None) -> None: ...
124
+ def set_verts(self, segments: Sequence[ArrayLike] | None) -> None: ...
125
+ def set_paths(self, segments: Sequence[ArrayLike] | None) -> None: ... # type: ignore[override]
126
+ def get_segments(self) -> list[np.ndarray]: ...
127
+ def set_color(self, c: ColorType | Sequence[ColorType]) -> None: ...
128
+ def set_colors(self, c: ColorType | Sequence[ColorType]) -> None: ...
129
+ def set_gapcolor(self, gapcolor: ColorType | Sequence[ColorType] | None) -> None: ...
130
+ def get_color(self) -> ColorType | Sequence[ColorType]: ...
131
+ def get_colors(self) -> ColorType | Sequence[ColorType]: ...
132
+ def get_gapcolor(self) -> ColorType | Sequence[ColorType] | None: ...
133
+
134
+
135
+ class EventCollection(LineCollection):
136
+ def __init__(
137
+ self,
138
+ positions: ArrayLike,
139
+ orientation: Literal["horizontal", "vertical"] = ...,
140
+ *,
141
+ lineoffset: float = ...,
142
+ linelength: float = ...,
143
+ linewidth: float | Sequence[float] | None = ...,
144
+ color: ColorType | Sequence[ColorType] | None = ...,
145
+ linestyle: LineStyleType | Sequence[LineStyleType] = ...,
146
+ antialiased: bool | Sequence[bool] | None = ...,
147
+ **kwargs
148
+ ) -> None: ...
149
+ def get_positions(self) -> list[float]: ...
150
+ def set_positions(self, positions: Sequence[float] | None) -> None: ...
151
+ def add_positions(self, position: Sequence[float] | None) -> None: ...
152
+ def extend_positions(self, position: Sequence[float] | None) -> None: ...
153
+ def append_positions(self, position: Sequence[float] | None) -> None: ...
154
+ def is_horizontal(self) -> bool: ...
155
+ def get_orientation(self) -> Literal["horizontal", "vertical"]: ...
156
+ def switch_orientation(self) -> None: ...
157
+ def set_orientation(
158
+ self, orientation: Literal["horizontal", "vertical"]
159
+ ) -> None: ...
160
+ def get_linelength(self) -> float | Sequence[float]: ...
161
+ def set_linelength(self, linelength: float | Sequence[float]) -> None: ...
162
+ def get_lineoffset(self) -> float: ...
163
+ def set_lineoffset(self, lineoffset: float) -> None: ...
164
+ def get_linewidth(self) -> float: ...
165
+ def get_linewidths(self) -> Sequence[float]: ...
166
+ def get_color(self) -> ColorType: ...
167
+
168
+ class CircleCollection(_CollectionWithSizes):
169
+ def __init__(self, sizes: float | ArrayLike, **kwargs) -> None: ...
170
+
171
+ class EllipseCollection(Collection):
172
+ def __init__(
173
+ self,
174
+ widths: ArrayLike,
175
+ heights: ArrayLike,
176
+ angles: ArrayLike,
177
+ *,
178
+ units: Literal[
179
+ "points", "inches", "dots", "width", "height", "x", "y", "xy"
180
+ ] = ...,
181
+ **kwargs
182
+ ) -> None: ...
183
+ def set_widths(self, widths: ArrayLike) -> None: ...
184
+ def set_heights(self, heights: ArrayLike) -> None: ...
185
+ def set_angles(self, angles: ArrayLike) -> None: ...
186
+ def get_widths(self) -> ArrayLike: ...
187
+ def get_heights(self) -> ArrayLike: ...
188
+ def get_angles(self) -> ArrayLike: ...
189
+
190
+ class PatchCollection(Collection):
191
+ def __init__(
192
+ self, patches: Iterable[Patch], *, match_original: bool = ..., **kwargs
193
+ ) -> None: ...
194
+ def set_paths(self, patches: Iterable[Patch]) -> None: ... # type: ignore[override]
195
+
196
+ class TriMesh(Collection):
197
+ def __init__(self, triangulation: Triangulation, **kwargs) -> None: ...
198
+ def get_paths(self) -> list[Path]: ...
199
+ # Parent class has an argument, perhaps add a noop arg?
200
+ def set_paths(self) -> None: ... # type: ignore[override]
201
+ @staticmethod
202
+ def convert_mesh_to_paths(tri: Triangulation) -> list[Path]: ...
203
+
204
+ class _MeshData:
205
+ def __init__(
206
+ self,
207
+ coordinates: ArrayLike,
208
+ *,
209
+ shading: Literal["flat", "gouraud"] = ...,
210
+ ) -> None: ...
211
+ def set_array(self, A: ArrayLike | None) -> None: ...
212
+ def get_coordinates(self) -> ArrayLike: ...
213
+ def get_facecolor(self) -> ColorType | Sequence[ColorType]: ...
214
+ def get_edgecolor(self) -> ColorType | Sequence[ColorType]: ...
215
+
216
+ class QuadMesh(_MeshData, Collection):
217
+ def __init__(
218
+ self,
219
+ coordinates: ArrayLike,
220
+ *,
221
+ antialiased: bool = ...,
222
+ shading: Literal["flat", "gouraud"] = ...,
223
+ **kwargs
224
+ ) -> None: ...
225
+ def get_paths(self) -> list[Path]: ...
226
+ # Parent class has an argument, perhaps add a noop arg?
227
+ def set_paths(self) -> None: ... # type: ignore[override]
228
+ def get_datalim(self, transData: transforms.Transform) -> transforms.Bbox: ...
229
+ def get_cursor_data(self, event: MouseEvent) -> float: ...
230
+
231
+ class PolyQuadMesh(_MeshData, PolyCollection):
232
+ def __init__(
233
+ self,
234
+ coordinates: ArrayLike,
235
+ **kwargs
236
+ ) -> None: ...
llava_next/lib/python3.10/site-packages/matplotlib/colorbar.py ADDED
@@ -0,0 +1,1559 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Colorbars are a visualization of the mapping from scalar values to colors.
3
+ In Matplotlib they are drawn into a dedicated `~.axes.Axes`.
4
+
5
+ .. note::
6
+ Colorbars are typically created through `.Figure.colorbar` or its pyplot
7
+ wrapper `.pyplot.colorbar`, which internally use `.Colorbar` together with
8
+ `.make_axes_gridspec` (for `.GridSpec`-positioned Axes) or `.make_axes` (for
9
+ non-`.GridSpec`-positioned Axes).
10
+
11
+ End-users most likely won't need to directly use this module's API.
12
+ """
13
+
14
+ import logging
15
+
16
+ import numpy as np
17
+
18
+ import matplotlib as mpl
19
+ from matplotlib import _api, cbook, collections, cm, colors, contour, ticker
20
+ import matplotlib.artist as martist
21
+ import matplotlib.patches as mpatches
22
+ import matplotlib.path as mpath
23
+ import matplotlib.spines as mspines
24
+ import matplotlib.transforms as mtransforms
25
+ from matplotlib import _docstring
26
+
27
+ _log = logging.getLogger(__name__)
28
+
29
+ _docstring.interpd.update(
30
+ _make_axes_kw_doc="""
31
+ location : None or {'left', 'right', 'top', 'bottom'}
32
+ The location, relative to the parent Axes, where the colorbar Axes
33
+ is created. It also determines the *orientation* of the colorbar
34
+ (colorbars on the left and right are vertical, colorbars at the top
35
+ and bottom are horizontal). If None, the location will come from the
36
+ *orientation* if it is set (vertical colorbars on the right, horizontal
37
+ ones at the bottom), or default to 'right' if *orientation* is unset.
38
+
39
+ orientation : None or {'vertical', 'horizontal'}
40
+ The orientation of the colorbar. It is preferable to set the *location*
41
+ of the colorbar, as that also determines the *orientation*; passing
42
+ incompatible values for *location* and *orientation* raises an exception.
43
+
44
+ fraction : float, default: 0.15
45
+ Fraction of original Axes to use for colorbar.
46
+
47
+ shrink : float, default: 1.0
48
+ Fraction by which to multiply the size of the colorbar.
49
+
50
+ aspect : float, default: 20
51
+ Ratio of long to short dimensions.
52
+
53
+ pad : float, default: 0.05 if vertical, 0.15 if horizontal
54
+ Fraction of original Axes between colorbar and new image Axes.
55
+
56
+ anchor : (float, float), optional
57
+ The anchor point of the colorbar Axes.
58
+ Defaults to (0.0, 0.5) if vertical; (0.5, 1.0) if horizontal.
59
+
60
+ panchor : (float, float), or *False*, optional
61
+ The anchor point of the colorbar parent Axes. If *False*, the parent
62
+ axes' anchor will be unchanged.
63
+ Defaults to (1.0, 0.5) if vertical; (0.5, 0.0) if horizontal.""",
64
+ _colormap_kw_doc="""
65
+ extend : {'neither', 'both', 'min', 'max'}
66
+ Make pointed end(s) for out-of-range values (unless 'neither'). These are
67
+ set for a given colormap using the colormap set_under and set_over methods.
68
+
69
+ extendfrac : {*None*, 'auto', length, lengths}
70
+ If set to *None*, both the minimum and maximum triangular colorbar
71
+ extensions will have a length of 5% of the interior colorbar length (this
72
+ is the default setting).
73
+
74
+ If set to 'auto', makes the triangular colorbar extensions the same lengths
75
+ as the interior boxes (when *spacing* is set to 'uniform') or the same
76
+ lengths as the respective adjacent interior boxes (when *spacing* is set to
77
+ 'proportional').
78
+
79
+ If a scalar, indicates the length of both the minimum and maximum
80
+ triangular colorbar extensions as a fraction of the interior colorbar
81
+ length. A two-element sequence of fractions may also be given, indicating
82
+ the lengths of the minimum and maximum colorbar extensions respectively as
83
+ a fraction of the interior colorbar length.
84
+
85
+ extendrect : bool
86
+ If *False* the minimum and maximum colorbar extensions will be triangular
87
+ (the default). If *True* the extensions will be rectangular.
88
+
89
+ spacing : {'uniform', 'proportional'}
90
+ For discrete colorbars (`.BoundaryNorm` or contours), 'uniform' gives each
91
+ color the same space; 'proportional' makes the space proportional to the
92
+ data interval.
93
+
94
+ ticks : None or list of ticks or Locator
95
+ If None, ticks are determined automatically from the input.
96
+
97
+ format : None or str or Formatter
98
+ If None, `~.ticker.ScalarFormatter` is used.
99
+ Format strings, e.g., ``"%4.2e"`` or ``"{x:.2e}"``, are supported.
100
+ An alternative `~.ticker.Formatter` may be given instead.
101
+
102
+ drawedges : bool
103
+ Whether to draw lines at color boundaries.
104
+
105
+ label : str
106
+ The label on the colorbar's long axis.
107
+
108
+ boundaries, values : None or a sequence
109
+ If unset, the colormap will be displayed on a 0-1 scale.
110
+ If sequences, *values* must have a length 1 less than *boundaries*. For
111
+ each region delimited by adjacent entries in *boundaries*, the color mapped
112
+ to the corresponding value in values will be used.
113
+ Normally only useful for indexed colors (i.e. ``norm=NoNorm()``) or other
114
+ unusual circumstances.""")
115
+
116
+
117
+ def _set_ticks_on_axis_warn(*args, **kwargs):
118
+ # a top level function which gets put in at the axes'
119
+ # set_xticks and set_yticks by Colorbar.__init__.
120
+ _api.warn_external("Use the colorbar set_ticks() method instead.")
121
+
122
+
123
+ class _ColorbarSpine(mspines.Spine):
124
+ def __init__(self, axes):
125
+ self._ax = axes
126
+ super().__init__(axes, 'colorbar', mpath.Path(np.empty((0, 2))))
127
+ mpatches.Patch.set_transform(self, axes.transAxes)
128
+
129
+ def get_window_extent(self, renderer=None):
130
+ # This Spine has no Axis associated with it, and doesn't need to adjust
131
+ # its location, so we can directly get the window extent from the
132
+ # super-super-class.
133
+ return mpatches.Patch.get_window_extent(self, renderer=renderer)
134
+
135
+ def set_xy(self, xy):
136
+ self._path = mpath.Path(xy, closed=True)
137
+ self._xy = xy
138
+ self.stale = True
139
+
140
+ def draw(self, renderer):
141
+ ret = mpatches.Patch.draw(self, renderer)
142
+ self.stale = False
143
+ return ret
144
+
145
+
146
+ class _ColorbarAxesLocator:
147
+ """
148
+ Shrink the Axes if there are triangular or rectangular extends.
149
+ """
150
+ def __init__(self, cbar):
151
+ self._cbar = cbar
152
+ self._orig_locator = cbar.ax._axes_locator
153
+
154
+ def __call__(self, ax, renderer):
155
+ if self._orig_locator is not None:
156
+ pos = self._orig_locator(ax, renderer)
157
+ else:
158
+ pos = ax.get_position(original=True)
159
+ if self._cbar.extend == 'neither':
160
+ return pos
161
+
162
+ y, extendlen = self._cbar._proportional_y()
163
+ if not self._cbar._extend_lower():
164
+ extendlen[0] = 0
165
+ if not self._cbar._extend_upper():
166
+ extendlen[1] = 0
167
+ len = sum(extendlen) + 1
168
+ shrink = 1 / len
169
+ offset = extendlen[0] / len
170
+ # we need to reset the aspect ratio of the axes to account
171
+ # of the extends...
172
+ if hasattr(ax, '_colorbar_info'):
173
+ aspect = ax._colorbar_info['aspect']
174
+ else:
175
+ aspect = False
176
+ # now shrink and/or offset to take into account the
177
+ # extend tri/rectangles.
178
+ if self._cbar.orientation == 'vertical':
179
+ if aspect:
180
+ self._cbar.ax.set_box_aspect(aspect*shrink)
181
+ pos = pos.shrunk(1, shrink).translated(0, offset * pos.height)
182
+ else:
183
+ if aspect:
184
+ self._cbar.ax.set_box_aspect(1/(aspect * shrink))
185
+ pos = pos.shrunk(shrink, 1).translated(offset * pos.width, 0)
186
+ return pos
187
+
188
+ def get_subplotspec(self):
189
+ # make tight_layout happy..
190
+ return (
191
+ self._cbar.ax.get_subplotspec()
192
+ or getattr(self._orig_locator, "get_subplotspec", lambda: None)())
193
+
194
+
195
+ @_docstring.interpd
196
+ class Colorbar:
197
+ r"""
198
+ Draw a colorbar in an existing Axes.
199
+
200
+ Typically, colorbars are created using `.Figure.colorbar` or
201
+ `.pyplot.colorbar` and associated with `.ScalarMappable`\s (such as an
202
+ `.AxesImage` generated via `~.axes.Axes.imshow`).
203
+
204
+ In order to draw a colorbar not associated with other elements in the
205
+ figure, e.g. when showing a colormap by itself, one can create an empty
206
+ `.ScalarMappable`, or directly pass *cmap* and *norm* instead of *mappable*
207
+ to `Colorbar`.
208
+
209
+ Useful public methods are :meth:`set_label` and :meth:`add_lines`.
210
+
211
+ Attributes
212
+ ----------
213
+ ax : `~matplotlib.axes.Axes`
214
+ The `~.axes.Axes` instance in which the colorbar is drawn.
215
+ lines : list
216
+ A list of `.LineCollection` (empty if no lines were drawn).
217
+ dividers : `.LineCollection`
218
+ A LineCollection (empty if *drawedges* is ``False``).
219
+
220
+ Parameters
221
+ ----------
222
+ ax : `~matplotlib.axes.Axes`
223
+ The `~.axes.Axes` instance in which the colorbar is drawn.
224
+
225
+ mappable : `.ScalarMappable`
226
+ The mappable whose colormap and norm will be used.
227
+
228
+ To show the under- and over- value colors, the mappable's norm should
229
+ be specified as ::
230
+
231
+ norm = colors.Normalize(clip=False)
232
+
233
+ To show the colors versus index instead of on a 0-1 scale, use::
234
+
235
+ norm=colors.NoNorm()
236
+
237
+ cmap : `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
238
+ The colormap to use. This parameter is ignored, unless *mappable* is
239
+ None.
240
+
241
+ norm : `~matplotlib.colors.Normalize`
242
+ The normalization to use. This parameter is ignored, unless *mappable*
243
+ is None.
244
+
245
+ alpha : float
246
+ The colorbar transparency between 0 (transparent) and 1 (opaque).
247
+
248
+ orientation : None or {'vertical', 'horizontal'}
249
+ If None, use the value determined by *location*. If both
250
+ *orientation* and *location* are None then defaults to 'vertical'.
251
+
252
+ ticklocation : {'auto', 'left', 'right', 'top', 'bottom'}
253
+ The location of the colorbar ticks. The *ticklocation* must match
254
+ *orientation*. For example, a horizontal colorbar can only have ticks
255
+ at the top or the bottom. If 'auto', the ticks will be the same as
256
+ *location*, so a colorbar to the left will have ticks to the left. If
257
+ *location* is None, the ticks will be at the bottom for a horizontal
258
+ colorbar and at the right for a vertical.
259
+
260
+ %(_colormap_kw_doc)s
261
+
262
+ location : None or {'left', 'right', 'top', 'bottom'}
263
+ Set the *orientation* and *ticklocation* of the colorbar using a
264
+ single argument. Colorbars on the left and right are vertical,
265
+ colorbars at the top and bottom are horizontal. The *ticklocation* is
266
+ the same as *location*, so if *location* is 'top', the ticks are on
267
+ the top. *orientation* and/or *ticklocation* can be provided as well
268
+ and overrides the value set by *location*, but there will be an error
269
+ for incompatible combinations.
270
+
271
+ .. versionadded:: 3.7
272
+ """
273
+
274
+ n_rasterize = 50 # rasterize solids if number of colors >= n_rasterize
275
+
276
+ def __init__(self, ax, mappable=None, *, cmap=None,
277
+ norm=None,
278
+ alpha=None,
279
+ values=None,
280
+ boundaries=None,
281
+ orientation=None,
282
+ ticklocation='auto',
283
+ extend=None,
284
+ spacing='uniform', # uniform or proportional
285
+ ticks=None,
286
+ format=None,
287
+ drawedges=False,
288
+ extendfrac=None,
289
+ extendrect=False,
290
+ label='',
291
+ location=None,
292
+ ):
293
+
294
+ if mappable is None:
295
+ mappable = cm.ScalarMappable(norm=norm, cmap=cmap)
296
+
297
+ self.mappable = mappable
298
+ cmap = mappable.cmap
299
+ norm = mappable.norm
300
+
301
+ filled = True
302
+ if isinstance(mappable, contour.ContourSet):
303
+ cs = mappable
304
+ alpha = cs.get_alpha()
305
+ boundaries = cs._levels
306
+ values = cs.cvalues
307
+ extend = cs.extend
308
+ filled = cs.filled
309
+ if ticks is None:
310
+ ticks = ticker.FixedLocator(cs.levels, nbins=10)
311
+ elif isinstance(mappable, martist.Artist):
312
+ alpha = mappable.get_alpha()
313
+
314
+ mappable.colorbar = self
315
+ mappable.colorbar_cid = mappable.callbacks.connect(
316
+ 'changed', self.update_normal)
317
+
318
+ location_orientation = _get_orientation_from_location(location)
319
+
320
+ _api.check_in_list(
321
+ [None, 'vertical', 'horizontal'], orientation=orientation)
322
+ _api.check_in_list(
323
+ ['auto', 'left', 'right', 'top', 'bottom'],
324
+ ticklocation=ticklocation)
325
+ _api.check_in_list(
326
+ ['uniform', 'proportional'], spacing=spacing)
327
+
328
+ if location_orientation is not None and orientation is not None:
329
+ if location_orientation != orientation:
330
+ raise TypeError(
331
+ "location and orientation are mutually exclusive")
332
+ else:
333
+ orientation = orientation or location_orientation or "vertical"
334
+
335
+ self.ax = ax
336
+ self.ax._axes_locator = _ColorbarAxesLocator(self)
337
+
338
+ if extend is None:
339
+ if (not isinstance(mappable, contour.ContourSet)
340
+ and getattr(cmap, 'colorbar_extend', False) is not False):
341
+ extend = cmap.colorbar_extend
342
+ elif hasattr(norm, 'extend'):
343
+ extend = norm.extend
344
+ else:
345
+ extend = 'neither'
346
+ self.alpha = None
347
+ # Call set_alpha to handle array-like alphas properly
348
+ self.set_alpha(alpha)
349
+ self.cmap = cmap
350
+ self.norm = norm
351
+ self.values = values
352
+ self.boundaries = boundaries
353
+ self.extend = extend
354
+ self._inside = _api.check_getitem(
355
+ {'neither': slice(0, None), 'both': slice(1, -1),
356
+ 'min': slice(1, None), 'max': slice(0, -1)},
357
+ extend=extend)
358
+ self.spacing = spacing
359
+ self.orientation = orientation
360
+ self.drawedges = drawedges
361
+ self._filled = filled
362
+ self.extendfrac = extendfrac
363
+ self.extendrect = extendrect
364
+ self._extend_patches = []
365
+ self.solids = None
366
+ self.solids_patches = []
367
+ self.lines = []
368
+
369
+ for spine in self.ax.spines.values():
370
+ spine.set_visible(False)
371
+ self.outline = self.ax.spines['outline'] = _ColorbarSpine(self.ax)
372
+
373
+ self.dividers = collections.LineCollection(
374
+ [],
375
+ colors=[mpl.rcParams['axes.edgecolor']],
376
+ linewidths=[0.5 * mpl.rcParams['axes.linewidth']],
377
+ clip_on=False)
378
+ self.ax.add_collection(self.dividers)
379
+
380
+ self._locator = None
381
+ self._minorlocator = None
382
+ self._formatter = None
383
+ self._minorformatter = None
384
+
385
+ if ticklocation == 'auto':
386
+ ticklocation = _get_ticklocation_from_orientation(
387
+ orientation) if location is None else location
388
+ self.ticklocation = ticklocation
389
+
390
+ self.set_label(label)
391
+ self._reset_locator_formatter_scale()
392
+
393
+ if np.iterable(ticks):
394
+ self._locator = ticker.FixedLocator(ticks, nbins=len(ticks))
395
+ else:
396
+ self._locator = ticks
397
+
398
+ if isinstance(format, str):
399
+ # Check format between FormatStrFormatter and StrMethodFormatter
400
+ try:
401
+ self._formatter = ticker.FormatStrFormatter(format)
402
+ _ = self._formatter(0)
403
+ except (TypeError, ValueError):
404
+ self._formatter = ticker.StrMethodFormatter(format)
405
+ else:
406
+ self._formatter = format # Assume it is a Formatter or None
407
+ self._draw_all()
408
+
409
+ if isinstance(mappable, contour.ContourSet) and not mappable.filled:
410
+ self.add_lines(mappable)
411
+
412
+ # Link the Axes and Colorbar for interactive use
413
+ self.ax._colorbar = self
414
+ # Don't navigate on any of these types of mappables
415
+ if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm)) or
416
+ isinstance(self.mappable, contour.ContourSet)):
417
+ self.ax.set_navigate(False)
418
+
419
+ # These are the functions that set up interactivity on this colorbar
420
+ self._interactive_funcs = ["_get_view", "_set_view",
421
+ "_set_view_from_bbox", "drag_pan"]
422
+ for x in self._interactive_funcs:
423
+ setattr(self.ax, x, getattr(self, x))
424
+ # Set the cla function to the cbar's method to override it
425
+ self.ax.cla = self._cbar_cla
426
+ # Callbacks for the extend calculations to handle inverting the axis
427
+ self._extend_cid1 = self.ax.callbacks.connect(
428
+ "xlim_changed", self._do_extends)
429
+ self._extend_cid2 = self.ax.callbacks.connect(
430
+ "ylim_changed", self._do_extends)
431
+
432
+ @property
433
+ def locator(self):
434
+ """Major tick `.Locator` for the colorbar."""
435
+ return self._long_axis().get_major_locator()
436
+
437
+ @locator.setter
438
+ def locator(self, loc):
439
+ self._long_axis().set_major_locator(loc)
440
+ self._locator = loc
441
+
442
+ @property
443
+ def minorlocator(self):
444
+ """Minor tick `.Locator` for the colorbar."""
445
+ return self._long_axis().get_minor_locator()
446
+
447
+ @minorlocator.setter
448
+ def minorlocator(self, loc):
449
+ self._long_axis().set_minor_locator(loc)
450
+ self._minorlocator = loc
451
+
452
+ @property
453
+ def formatter(self):
454
+ """Major tick label `.Formatter` for the colorbar."""
455
+ return self._long_axis().get_major_formatter()
456
+
457
+ @formatter.setter
458
+ def formatter(self, fmt):
459
+ self._long_axis().set_major_formatter(fmt)
460
+ self._formatter = fmt
461
+
462
+ @property
463
+ def minorformatter(self):
464
+ """Minor tick `.Formatter` for the colorbar."""
465
+ return self._long_axis().get_minor_formatter()
466
+
467
+ @minorformatter.setter
468
+ def minorformatter(self, fmt):
469
+ self._long_axis().set_minor_formatter(fmt)
470
+ self._minorformatter = fmt
471
+
472
+ def _cbar_cla(self):
473
+ """Function to clear the interactive colorbar state."""
474
+ for x in self._interactive_funcs:
475
+ delattr(self.ax, x)
476
+ # We now restore the old cla() back and can call it directly
477
+ del self.ax.cla
478
+ self.ax.cla()
479
+
480
+ def update_normal(self, mappable):
481
+ """
482
+ Update solid patches, lines, etc.
483
+
484
+ This is meant to be called when the norm of the image or contour plot
485
+ to which this colorbar belongs changes.
486
+
487
+ If the norm on the mappable is different than before, this resets the
488
+ locator and formatter for the axis, so if these have been customized,
489
+ they will need to be customized again. However, if the norm only
490
+ changes values of *vmin*, *vmax* or *cmap* then the old formatter
491
+ and locator will be preserved.
492
+ """
493
+ _log.debug('colorbar update normal %r %r', mappable.norm, self.norm)
494
+ self.mappable = mappable
495
+ self.set_alpha(mappable.get_alpha())
496
+ self.cmap = mappable.cmap
497
+ if mappable.norm != self.norm:
498
+ self.norm = mappable.norm
499
+ self._reset_locator_formatter_scale()
500
+
501
+ self._draw_all()
502
+ if isinstance(self.mappable, contour.ContourSet):
503
+ CS = self.mappable
504
+ if not CS.filled:
505
+ self.add_lines(CS)
506
+ self.stale = True
507
+
508
+ def _draw_all(self):
509
+ """
510
+ Calculate any free parameters based on the current cmap and norm,
511
+ and do all the drawing.
512
+ """
513
+ if self.orientation == 'vertical':
514
+ if mpl.rcParams['ytick.minor.visible']:
515
+ self.minorticks_on()
516
+ else:
517
+ if mpl.rcParams['xtick.minor.visible']:
518
+ self.minorticks_on()
519
+ self._long_axis().set(label_position=self.ticklocation,
520
+ ticks_position=self.ticklocation)
521
+ self._short_axis().set_ticks([])
522
+ self._short_axis().set_ticks([], minor=True)
523
+
524
+ # Set self._boundaries and self._values, including extensions.
525
+ # self._boundaries are the edges of each square of color, and
526
+ # self._values are the value to map into the norm to get the
527
+ # color:
528
+ self._process_values()
529
+ # Set self.vmin and self.vmax to first and last boundary, excluding
530
+ # extensions:
531
+ self.vmin, self.vmax = self._boundaries[self._inside][[0, -1]]
532
+ # Compute the X/Y mesh.
533
+ X, Y = self._mesh()
534
+ # draw the extend triangles, and shrink the inner Axes to accommodate.
535
+ # also adds the outline path to self.outline spine:
536
+ self._do_extends()
537
+ lower, upper = self.vmin, self.vmax
538
+ if self._long_axis().get_inverted():
539
+ # If the axis is inverted, we need to swap the vmin/vmax
540
+ lower, upper = upper, lower
541
+ if self.orientation == 'vertical':
542
+ self.ax.set_xlim(0, 1)
543
+ self.ax.set_ylim(lower, upper)
544
+ else:
545
+ self.ax.set_ylim(0, 1)
546
+ self.ax.set_xlim(lower, upper)
547
+
548
+ # set up the tick locators and formatters. A bit complicated because
549
+ # boundary norms + uniform spacing requires a manual locator.
550
+ self.update_ticks()
551
+
552
+ if self._filled:
553
+ ind = np.arange(len(self._values))
554
+ if self._extend_lower():
555
+ ind = ind[1:]
556
+ if self._extend_upper():
557
+ ind = ind[:-1]
558
+ self._add_solids(X, Y, self._values[ind, np.newaxis])
559
+
560
+ def _add_solids(self, X, Y, C):
561
+ """Draw the colors; optionally add separators."""
562
+ # Cleanup previously set artists.
563
+ if self.solids is not None:
564
+ self.solids.remove()
565
+ for solid in self.solids_patches:
566
+ solid.remove()
567
+ # Add new artist(s), based on mappable type. Use individual patches if
568
+ # hatching is needed, pcolormesh otherwise.
569
+ mappable = getattr(self, 'mappable', None)
570
+ if (isinstance(mappable, contour.ContourSet)
571
+ and any(hatch is not None for hatch in mappable.hatches)):
572
+ self._add_solids_patches(X, Y, C, mappable)
573
+ else:
574
+ self.solids = self.ax.pcolormesh(
575
+ X, Y, C, cmap=self.cmap, norm=self.norm, alpha=self.alpha,
576
+ edgecolors='none', shading='flat')
577
+ if not self.drawedges:
578
+ if len(self._y) >= self.n_rasterize:
579
+ self.solids.set_rasterized(True)
580
+ self._update_dividers()
581
+
582
+ def _update_dividers(self):
583
+ if not self.drawedges:
584
+ self.dividers.set_segments([])
585
+ return
586
+ # Place all *internal* dividers.
587
+ if self.orientation == 'vertical':
588
+ lims = self.ax.get_ylim()
589
+ bounds = (lims[0] < self._y) & (self._y < lims[1])
590
+ else:
591
+ lims = self.ax.get_xlim()
592
+ bounds = (lims[0] < self._y) & (self._y < lims[1])
593
+ y = self._y[bounds]
594
+ # And then add outer dividers if extensions are on.
595
+ if self._extend_lower():
596
+ y = np.insert(y, 0, lims[0])
597
+ if self._extend_upper():
598
+ y = np.append(y, lims[1])
599
+ X, Y = np.meshgrid([0, 1], y)
600
+ if self.orientation == 'vertical':
601
+ segments = np.dstack([X, Y])
602
+ else:
603
+ segments = np.dstack([Y, X])
604
+ self.dividers.set_segments(segments)
605
+
606
+ def _add_solids_patches(self, X, Y, C, mappable):
607
+ hatches = mappable.hatches * (len(C) + 1) # Have enough hatches.
608
+ if self._extend_lower():
609
+ # remove first hatch that goes into the extend patch
610
+ hatches = hatches[1:]
611
+ patches = []
612
+ for i in range(len(X) - 1):
613
+ xy = np.array([[X[i, 0], Y[i, 1]],
614
+ [X[i, 1], Y[i, 0]],
615
+ [X[i + 1, 1], Y[i + 1, 0]],
616
+ [X[i + 1, 0], Y[i + 1, 1]]])
617
+ patch = mpatches.PathPatch(mpath.Path(xy),
618
+ facecolor=self.cmap(self.norm(C[i][0])),
619
+ hatch=hatches[i], linewidth=0,
620
+ antialiased=False, alpha=self.alpha)
621
+ self.ax.add_patch(patch)
622
+ patches.append(patch)
623
+ self.solids_patches = patches
624
+
625
+ def _do_extends(self, ax=None):
626
+ """
627
+ Add the extend tri/rectangles on the outside of the Axes.
628
+
629
+ ax is unused, but required due to the callbacks on xlim/ylim changed
630
+ """
631
+ # Clean up any previous extend patches
632
+ for patch in self._extend_patches:
633
+ patch.remove()
634
+ self._extend_patches = []
635
+ # extend lengths are fraction of the *inner* part of colorbar,
636
+ # not the total colorbar:
637
+ _, extendlen = self._proportional_y()
638
+ bot = 0 - (extendlen[0] if self._extend_lower() else 0)
639
+ top = 1 + (extendlen[1] if self._extend_upper() else 0)
640
+
641
+ # xyout is the outline of the colorbar including the extend patches:
642
+ if not self.extendrect:
643
+ # triangle:
644
+ xyout = np.array([[0, 0], [0.5, bot], [1, 0],
645
+ [1, 1], [0.5, top], [0, 1], [0, 0]])
646
+ else:
647
+ # rectangle:
648
+ xyout = np.array([[0, 0], [0, bot], [1, bot], [1, 0],
649
+ [1, 1], [1, top], [0, top], [0, 1],
650
+ [0, 0]])
651
+
652
+ if self.orientation == 'horizontal':
653
+ xyout = xyout[:, ::-1]
654
+
655
+ # xyout is the path for the spine:
656
+ self.outline.set_xy(xyout)
657
+ if not self._filled:
658
+ return
659
+
660
+ # Make extend triangles or rectangles filled patches. These are
661
+ # defined in the outer parent axes' coordinates:
662
+ mappable = getattr(self, 'mappable', None)
663
+ if (isinstance(mappable, contour.ContourSet)
664
+ and any(hatch is not None for hatch in mappable.hatches)):
665
+ hatches = mappable.hatches * (len(self._y) + 1)
666
+ else:
667
+ hatches = [None] * (len(self._y) + 1)
668
+
669
+ if self._extend_lower():
670
+ if not self.extendrect:
671
+ # triangle
672
+ xy = np.array([[0, 0], [0.5, bot], [1, 0]])
673
+ else:
674
+ # rectangle
675
+ xy = np.array([[0, 0], [0, bot], [1., bot], [1, 0]])
676
+ if self.orientation == 'horizontal':
677
+ xy = xy[:, ::-1]
678
+ # add the patch
679
+ val = -1 if self._long_axis().get_inverted() else 0
680
+ color = self.cmap(self.norm(self._values[val]))
681
+ patch = mpatches.PathPatch(
682
+ mpath.Path(xy), facecolor=color, alpha=self.alpha,
683
+ linewidth=0, antialiased=False,
684
+ transform=self.ax.transAxes,
685
+ hatch=hatches[0], clip_on=False,
686
+ # Place it right behind the standard patches, which is
687
+ # needed if we updated the extends
688
+ zorder=np.nextafter(self.ax.patch.zorder, -np.inf))
689
+ self.ax.add_patch(patch)
690
+ self._extend_patches.append(patch)
691
+ # remove first hatch that goes into the extend patch
692
+ hatches = hatches[1:]
693
+ if self._extend_upper():
694
+ if not self.extendrect:
695
+ # triangle
696
+ xy = np.array([[0, 1], [0.5, top], [1, 1]])
697
+ else:
698
+ # rectangle
699
+ xy = np.array([[0, 1], [0, top], [1, top], [1, 1]])
700
+ if self.orientation == 'horizontal':
701
+ xy = xy[:, ::-1]
702
+ # add the patch
703
+ val = 0 if self._long_axis().get_inverted() else -1
704
+ color = self.cmap(self.norm(self._values[val]))
705
+ hatch_idx = len(self._y) - 1
706
+ patch = mpatches.PathPatch(
707
+ mpath.Path(xy), facecolor=color, alpha=self.alpha,
708
+ linewidth=0, antialiased=False,
709
+ transform=self.ax.transAxes, hatch=hatches[hatch_idx],
710
+ clip_on=False,
711
+ # Place it right behind the standard patches, which is
712
+ # needed if we updated the extends
713
+ zorder=np.nextafter(self.ax.patch.zorder, -np.inf))
714
+ self.ax.add_patch(patch)
715
+ self._extend_patches.append(patch)
716
+
717
+ self._update_dividers()
718
+
719
+ def add_lines(self, *args, **kwargs):
720
+ """
721
+ Draw lines on the colorbar.
722
+
723
+ The lines are appended to the list :attr:`lines`.
724
+
725
+ Parameters
726
+ ----------
727
+ levels : array-like
728
+ The positions of the lines.
729
+ colors : :mpltype:`color` or list of :mpltype:`color`
730
+ Either a single color applying to all lines or one color value for
731
+ each line.
732
+ linewidths : float or array-like
733
+ Either a single linewidth applying to all lines or one linewidth
734
+ for each line.
735
+ erase : bool, default: True
736
+ Whether to remove any previously added lines.
737
+
738
+ Notes
739
+ -----
740
+ Alternatively, this method can also be called with the signature
741
+ ``colorbar.add_lines(contour_set, erase=True)``, in which case
742
+ *levels*, *colors*, and *linewidths* are taken from *contour_set*.
743
+ """
744
+ params = _api.select_matching_signature(
745
+ [lambda self, CS, erase=True: locals(),
746
+ lambda self, levels, colors, linewidths, erase=True: locals()],
747
+ self, *args, **kwargs)
748
+ if "CS" in params:
749
+ self, cs, erase = params.values()
750
+ if not isinstance(cs, contour.ContourSet) or cs.filled:
751
+ raise ValueError("If a single artist is passed to add_lines, "
752
+ "it must be a ContourSet of lines")
753
+ # TODO: Make colorbar lines auto-follow changes in contour lines.
754
+ return self.add_lines(
755
+ cs.levels,
756
+ cs.to_rgba(cs.cvalues, cs.alpha),
757
+ cs.get_linewidths(),
758
+ erase=erase)
759
+ else:
760
+ self, levels, colors, linewidths, erase = params.values()
761
+
762
+ y = self._locate(levels)
763
+ rtol = (self._y[-1] - self._y[0]) * 1e-10
764
+ igood = (y < self._y[-1] + rtol) & (y > self._y[0] - rtol)
765
+ y = y[igood]
766
+ if np.iterable(colors):
767
+ colors = np.asarray(colors)[igood]
768
+ if np.iterable(linewidths):
769
+ linewidths = np.asarray(linewidths)[igood]
770
+ X, Y = np.meshgrid([0, 1], y)
771
+ if self.orientation == 'vertical':
772
+ xy = np.stack([X, Y], axis=-1)
773
+ else:
774
+ xy = np.stack([Y, X], axis=-1)
775
+ col = collections.LineCollection(xy, linewidths=linewidths,
776
+ colors=colors)
777
+
778
+ if erase and self.lines:
779
+ for lc in self.lines:
780
+ lc.remove()
781
+ self.lines = []
782
+ self.lines.append(col)
783
+
784
+ # make a clip path that is just a linewidth bigger than the Axes...
785
+ fac = np.max(linewidths) / 72
786
+ xy = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
787
+ inches = self.ax.get_figure().dpi_scale_trans
788
+ # do in inches:
789
+ xy = inches.inverted().transform(self.ax.transAxes.transform(xy))
790
+ xy[[0, 1, 4], 1] -= fac
791
+ xy[[2, 3], 1] += fac
792
+ # back to axes units...
793
+ xy = self.ax.transAxes.inverted().transform(inches.transform(xy))
794
+ col.set_clip_path(mpath.Path(xy, closed=True),
795
+ self.ax.transAxes)
796
+ self.ax.add_collection(col)
797
+ self.stale = True
798
+
799
+ def update_ticks(self):
800
+ """
801
+ Set up the ticks and ticklabels. This should not be needed by users.
802
+ """
803
+ # Get the locator and formatter; defaults to self._locator if not None.
804
+ self._get_ticker_locator_formatter()
805
+ self._long_axis().set_major_locator(self._locator)
806
+ self._long_axis().set_minor_locator(self._minorlocator)
807
+ self._long_axis().set_major_formatter(self._formatter)
808
+
809
+ def _get_ticker_locator_formatter(self):
810
+ """
811
+ Return the ``locator`` and ``formatter`` of the colorbar.
812
+
813
+ If they have not been defined (i.e. are *None*), the formatter and
814
+ locator are retrieved from the axis, or from the value of the
815
+ boundaries for a boundary norm.
816
+
817
+ Called by update_ticks...
818
+ """
819
+ locator = self._locator
820
+ formatter = self._formatter
821
+ minorlocator = self._minorlocator
822
+ if isinstance(self.norm, colors.BoundaryNorm):
823
+ b = self.norm.boundaries
824
+ if locator is None:
825
+ locator = ticker.FixedLocator(b, nbins=10)
826
+ if minorlocator is None:
827
+ minorlocator = ticker.FixedLocator(b)
828
+ elif isinstance(self.norm, colors.NoNorm):
829
+ if locator is None:
830
+ # put ticks on integers between the boundaries of NoNorm
831
+ nv = len(self._values)
832
+ base = 1 + int(nv / 10)
833
+ locator = ticker.IndexLocator(base=base, offset=.5)
834
+ elif self.boundaries is not None:
835
+ b = self._boundaries[self._inside]
836
+ if locator is None:
837
+ locator = ticker.FixedLocator(b, nbins=10)
838
+ else: # most cases:
839
+ if locator is None:
840
+ # we haven't set the locator explicitly, so use the default
841
+ # for this axis:
842
+ locator = self._long_axis().get_major_locator()
843
+ if minorlocator is None:
844
+ minorlocator = self._long_axis().get_minor_locator()
845
+
846
+ if minorlocator is None:
847
+ minorlocator = ticker.NullLocator()
848
+
849
+ if formatter is None:
850
+ formatter = self._long_axis().get_major_formatter()
851
+
852
+ self._locator = locator
853
+ self._formatter = formatter
854
+ self._minorlocator = minorlocator
855
+ _log.debug('locator: %r', locator)
856
+
857
+ def set_ticks(self, ticks, *, labels=None, minor=False, **kwargs):
858
+ """
859
+ Set tick locations.
860
+
861
+ Parameters
862
+ ----------
863
+ ticks : 1D array-like
864
+ List of tick locations.
865
+ labels : list of str, optional
866
+ List of tick labels. If not set, the labels show the data value.
867
+ minor : bool, default: False
868
+ If ``False``, set the major ticks; if ``True``, the minor ticks.
869
+ **kwargs
870
+ `.Text` properties for the labels. These take effect only if you
871
+ pass *labels*. In other cases, please use `~.Axes.tick_params`.
872
+ """
873
+ if np.iterable(ticks):
874
+ self._long_axis().set_ticks(ticks, labels=labels, minor=minor,
875
+ **kwargs)
876
+ self._locator = self._long_axis().get_major_locator()
877
+ else:
878
+ self._locator = ticks
879
+ self._long_axis().set_major_locator(self._locator)
880
+ self.stale = True
881
+
882
+ def get_ticks(self, minor=False):
883
+ """
884
+ Return the ticks as a list of locations.
885
+
886
+ Parameters
887
+ ----------
888
+ minor : boolean, default: False
889
+ if True return the minor ticks.
890
+ """
891
+ if minor:
892
+ return self._long_axis().get_minorticklocs()
893
+ else:
894
+ return self._long_axis().get_majorticklocs()
895
+
896
+ def set_ticklabels(self, ticklabels, *, minor=False, **kwargs):
897
+ """
898
+ [*Discouraged*] Set tick labels.
899
+
900
+ .. admonition:: Discouraged
901
+
902
+ The use of this method is discouraged, because of the dependency
903
+ on tick positions. In most cases, you'll want to use
904
+ ``set_ticks(positions, labels=labels)`` instead.
905
+
906
+ If you are using this method, you should always fix the tick
907
+ positions before, e.g. by using `.Colorbar.set_ticks` or by
908
+ explicitly setting a `~.ticker.FixedLocator` on the long axis
909
+ of the colorbar. Otherwise, ticks are free to move and the
910
+ labels may end up in unexpected positions.
911
+
912
+ Parameters
913
+ ----------
914
+ ticklabels : sequence of str or of `.Text`
915
+ Texts for labeling each tick location in the sequence set by
916
+ `.Colorbar.set_ticks`; the number of labels must match the number
917
+ of locations.
918
+
919
+ update_ticks : bool, default: True
920
+ This keyword argument is ignored and will be removed.
921
+ Deprecated
922
+
923
+ minor : bool
924
+ If True, set minor ticks instead of major ticks.
925
+
926
+ **kwargs
927
+ `.Text` properties for the labels.
928
+ """
929
+ self._long_axis().set_ticklabels(ticklabels, minor=minor, **kwargs)
930
+
931
+ def minorticks_on(self):
932
+ """
933
+ Turn on colorbar minor ticks.
934
+ """
935
+ self.ax.minorticks_on()
936
+ self._short_axis().set_minor_locator(ticker.NullLocator())
937
+
938
+ def minorticks_off(self):
939
+ """Turn the minor ticks of the colorbar off."""
940
+ self._minorlocator = ticker.NullLocator()
941
+ self._long_axis().set_minor_locator(self._minorlocator)
942
+
943
+ def set_label(self, label, *, loc=None, **kwargs):
944
+ """
945
+ Add a label to the long axis of the colorbar.
946
+
947
+ Parameters
948
+ ----------
949
+ label : str
950
+ The label text.
951
+ loc : str, optional
952
+ The location of the label.
953
+
954
+ - For horizontal orientation one of {'left', 'center', 'right'}
955
+ - For vertical orientation one of {'bottom', 'center', 'top'}
956
+
957
+ Defaults to :rc:`xaxis.labellocation` or :rc:`yaxis.labellocation`
958
+ depending on the orientation.
959
+ **kwargs
960
+ Keyword arguments are passed to `~.Axes.set_xlabel` /
961
+ `~.Axes.set_ylabel`.
962
+ Supported keywords are *labelpad* and `.Text` properties.
963
+ """
964
+ if self.orientation == "vertical":
965
+ self.ax.set_ylabel(label, loc=loc, **kwargs)
966
+ else:
967
+ self.ax.set_xlabel(label, loc=loc, **kwargs)
968
+ self.stale = True
969
+
970
+ def set_alpha(self, alpha):
971
+ """
972
+ Set the transparency between 0 (transparent) and 1 (opaque).
973
+
974
+ If an array is provided, *alpha* will be set to None to use the
975
+ transparency values associated with the colormap.
976
+ """
977
+ self.alpha = None if isinstance(alpha, np.ndarray) else alpha
978
+
979
+ def _set_scale(self, scale, **kwargs):
980
+ """
981
+ Set the colorbar long axis scale.
982
+
983
+ Parameters
984
+ ----------
985
+ scale : {"linear", "log", "symlog", "logit", ...} or `.ScaleBase`
986
+ The axis scale type to apply.
987
+
988
+ **kwargs
989
+ Different keyword arguments are accepted, depending on the scale.
990
+ See the respective class keyword arguments:
991
+
992
+ - `matplotlib.scale.LinearScale`
993
+ - `matplotlib.scale.LogScale`
994
+ - `matplotlib.scale.SymmetricalLogScale`
995
+ - `matplotlib.scale.LogitScale`
996
+ - `matplotlib.scale.FuncScale`
997
+ - `matplotlib.scale.AsinhScale`
998
+
999
+ Notes
1000
+ -----
1001
+ By default, Matplotlib supports the above-mentioned scales.
1002
+ Additionally, custom scales may be registered using
1003
+ `matplotlib.scale.register_scale`. These scales can then also
1004
+ be used here.
1005
+ """
1006
+ self._long_axis()._set_axes_scale(scale, **kwargs)
1007
+
1008
+ def remove(self):
1009
+ """
1010
+ Remove this colorbar from the figure.
1011
+
1012
+ If the colorbar was created with ``use_gridspec=True`` the previous
1013
+ gridspec is restored.
1014
+ """
1015
+ if hasattr(self.ax, '_colorbar_info'):
1016
+ parents = self.ax._colorbar_info['parents']
1017
+ for a in parents:
1018
+ if self.ax in a._colorbars:
1019
+ a._colorbars.remove(self.ax)
1020
+
1021
+ self.ax.remove()
1022
+
1023
+ self.mappable.callbacks.disconnect(self.mappable.colorbar_cid)
1024
+ self.mappable.colorbar = None
1025
+ self.mappable.colorbar_cid = None
1026
+ # Remove the extension callbacks
1027
+ self.ax.callbacks.disconnect(self._extend_cid1)
1028
+ self.ax.callbacks.disconnect(self._extend_cid2)
1029
+
1030
+ try:
1031
+ ax = self.mappable.axes
1032
+ except AttributeError:
1033
+ return
1034
+ try:
1035
+ subplotspec = self.ax.get_subplotspec().get_gridspec()._subplot_spec
1036
+ except AttributeError: # use_gridspec was False
1037
+ pos = ax.get_position(original=True)
1038
+ ax._set_position(pos)
1039
+ else: # use_gridspec was True
1040
+ ax.set_subplotspec(subplotspec)
1041
+
1042
+ def _process_values(self):
1043
+ """
1044
+ Set `_boundaries` and `_values` based on the self.boundaries and
1045
+ self.values if not None, or based on the size of the colormap and
1046
+ the vmin/vmax of the norm.
1047
+ """
1048
+ if self.values is not None:
1049
+ # set self._boundaries from the values...
1050
+ self._values = np.array(self.values)
1051
+ if self.boundaries is None:
1052
+ # bracket values by 1/2 dv:
1053
+ b = np.zeros(len(self.values) + 1)
1054
+ b[1:-1] = 0.5 * (self._values[:-1] + self._values[1:])
1055
+ b[0] = 2.0 * b[1] - b[2]
1056
+ b[-1] = 2.0 * b[-2] - b[-3]
1057
+ self._boundaries = b
1058
+ return
1059
+ self._boundaries = np.array(self.boundaries)
1060
+ return
1061
+
1062
+ # otherwise values are set from the boundaries
1063
+ if isinstance(self.norm, colors.BoundaryNorm):
1064
+ b = self.norm.boundaries
1065
+ elif isinstance(self.norm, colors.NoNorm):
1066
+ # NoNorm has N blocks, so N+1 boundaries, centered on integers:
1067
+ b = np.arange(self.cmap.N + 1) - .5
1068
+ elif self.boundaries is not None:
1069
+ b = self.boundaries
1070
+ else:
1071
+ # otherwise make the boundaries from the size of the cmap:
1072
+ N = self.cmap.N + 1
1073
+ b, _ = self._uniform_y(N)
1074
+ # add extra boundaries if needed:
1075
+ if self._extend_lower():
1076
+ b = np.hstack((b[0] - 1, b))
1077
+ if self._extend_upper():
1078
+ b = np.hstack((b, b[-1] + 1))
1079
+
1080
+ # transform from 0-1 to vmin-vmax:
1081
+ if self.mappable.get_array() is not None:
1082
+ self.mappable.autoscale_None()
1083
+ if not self.norm.scaled():
1084
+ # If we still aren't scaled after autoscaling, use 0, 1 as default
1085
+ self.norm.vmin = 0
1086
+ self.norm.vmax = 1
1087
+ self.norm.vmin, self.norm.vmax = mtransforms.nonsingular(
1088
+ self.norm.vmin, self.norm.vmax, expander=0.1)
1089
+ if (not isinstance(self.norm, colors.BoundaryNorm) and
1090
+ (self.boundaries is None)):
1091
+ b = self.norm.inverse(b)
1092
+
1093
+ self._boundaries = np.asarray(b, dtype=float)
1094
+ self._values = 0.5 * (self._boundaries[:-1] + self._boundaries[1:])
1095
+ if isinstance(self.norm, colors.NoNorm):
1096
+ self._values = (self._values + 0.00001).astype(np.int16)
1097
+
1098
+ def _mesh(self):
1099
+ """
1100
+ Return the coordinate arrays for the colorbar pcolormesh/patches.
1101
+
1102
+ These are scaled between vmin and vmax, and already handle colorbar
1103
+ orientation.
1104
+ """
1105
+ y, _ = self._proportional_y()
1106
+ # Use the vmin and vmax of the colorbar, which may not be the same
1107
+ # as the norm. There are situations where the colormap has a
1108
+ # narrower range than the colorbar and we want to accommodate the
1109
+ # extra contours.
1110
+ if (isinstance(self.norm, (colors.BoundaryNorm, colors.NoNorm))
1111
+ or self.boundaries is not None):
1112
+ # not using a norm.
1113
+ y = y * (self.vmax - self.vmin) + self.vmin
1114
+ else:
1115
+ # Update the norm values in a context manager as it is only
1116
+ # a temporary change and we don't want to propagate any signals
1117
+ # attached to the norm (callbacks.blocked).
1118
+ with self.norm.callbacks.blocked(), \
1119
+ cbook._setattr_cm(self.norm,
1120
+ vmin=self.vmin,
1121
+ vmax=self.vmax):
1122
+ y = self.norm.inverse(y)
1123
+ self._y = y
1124
+ X, Y = np.meshgrid([0., 1.], y)
1125
+ if self.orientation == 'vertical':
1126
+ return (X, Y)
1127
+ else:
1128
+ return (Y, X)
1129
+
1130
+ def _forward_boundaries(self, x):
1131
+ # map boundaries equally between 0 and 1...
1132
+ b = self._boundaries
1133
+ y = np.interp(x, b, np.linspace(0, 1, len(b)))
1134
+ # the following avoids ticks in the extends:
1135
+ eps = (b[-1] - b[0]) * 1e-6
1136
+ # map these _well_ out of bounds to keep any ticks out
1137
+ # of the extends region...
1138
+ y[x < b[0]-eps] = -1
1139
+ y[x > b[-1]+eps] = 2
1140
+ return y
1141
+
1142
+ def _inverse_boundaries(self, x):
1143
+ # invert the above...
1144
+ b = self._boundaries
1145
+ return np.interp(x, np.linspace(0, 1, len(b)), b)
1146
+
1147
+ def _reset_locator_formatter_scale(self):
1148
+ """
1149
+ Reset the locator et al to defaults. Any user-hardcoded changes
1150
+ need to be re-entered if this gets called (either at init, or when
1151
+ the mappable normal gets changed: Colorbar.update_normal)
1152
+ """
1153
+ self._process_values()
1154
+ self._locator = None
1155
+ self._minorlocator = None
1156
+ self._formatter = None
1157
+ self._minorformatter = None
1158
+ if (isinstance(self.mappable, contour.ContourSet) and
1159
+ isinstance(self.norm, colors.LogNorm)):
1160
+ # if contours have lognorm, give them a log scale...
1161
+ self._set_scale('log')
1162
+ elif (self.boundaries is not None or
1163
+ isinstance(self.norm, colors.BoundaryNorm)):
1164
+ if self.spacing == 'uniform':
1165
+ funcs = (self._forward_boundaries, self._inverse_boundaries)
1166
+ self._set_scale('function', functions=funcs)
1167
+ elif self.spacing == 'proportional':
1168
+ self._set_scale('linear')
1169
+ elif getattr(self.norm, '_scale', None):
1170
+ # use the norm's scale (if it exists and is not None):
1171
+ self._set_scale(self.norm._scale)
1172
+ elif type(self.norm) is colors.Normalize:
1173
+ # plain Normalize:
1174
+ self._set_scale('linear')
1175
+ else:
1176
+ # norm._scale is None or not an attr: derive the scale from
1177
+ # the Norm:
1178
+ funcs = (self.norm, self.norm.inverse)
1179
+ self._set_scale('function', functions=funcs)
1180
+
1181
+ def _locate(self, x):
1182
+ """
1183
+ Given a set of color data values, return their
1184
+ corresponding colorbar data coordinates.
1185
+ """
1186
+ if isinstance(self.norm, (colors.NoNorm, colors.BoundaryNorm)):
1187
+ b = self._boundaries
1188
+ xn = x
1189
+ else:
1190
+ # Do calculations using normalized coordinates so
1191
+ # as to make the interpolation more accurate.
1192
+ b = self.norm(self._boundaries, clip=False).filled()
1193
+ xn = self.norm(x, clip=False).filled()
1194
+
1195
+ bunique = b[self._inside]
1196
+ yunique = self._y
1197
+
1198
+ z = np.interp(xn, bunique, yunique)
1199
+ return z
1200
+
1201
+ # trivial helpers
1202
+
1203
+ def _uniform_y(self, N):
1204
+ """
1205
+ Return colorbar data coordinates for *N* uniformly
1206
+ spaced boundaries, plus extension lengths if required.
1207
+ """
1208
+ automin = automax = 1. / (N - 1.)
1209
+ extendlength = self._get_extension_lengths(self.extendfrac,
1210
+ automin, automax,
1211
+ default=0.05)
1212
+ y = np.linspace(0, 1, N)
1213
+ return y, extendlength
1214
+
1215
+ def _proportional_y(self):
1216
+ """
1217
+ Return colorbar data coordinates for the boundaries of
1218
+ a proportional colorbar, plus extension lengths if required:
1219
+ """
1220
+ if (isinstance(self.norm, colors.BoundaryNorm) or
1221
+ self.boundaries is not None):
1222
+ y = (self._boundaries - self._boundaries[self._inside][0])
1223
+ y = y / (self._boundaries[self._inside][-1] -
1224
+ self._boundaries[self._inside][0])
1225
+ # need yscaled the same as the axes scale to get
1226
+ # the extend lengths.
1227
+ if self.spacing == 'uniform':
1228
+ yscaled = self._forward_boundaries(self._boundaries)
1229
+ else:
1230
+ yscaled = y
1231
+ else:
1232
+ y = self.norm(self._boundaries.copy())
1233
+ y = np.ma.filled(y, np.nan)
1234
+ # the norm and the scale should be the same...
1235
+ yscaled = y
1236
+ y = y[self._inside]
1237
+ yscaled = yscaled[self._inside]
1238
+ # normalize from 0..1:
1239
+ norm = colors.Normalize(y[0], y[-1])
1240
+ y = np.ma.filled(norm(y), np.nan)
1241
+ norm = colors.Normalize(yscaled[0], yscaled[-1])
1242
+ yscaled = np.ma.filled(norm(yscaled), np.nan)
1243
+ # make the lower and upper extend lengths proportional to the lengths
1244
+ # of the first and last boundary spacing (if extendfrac='auto'):
1245
+ automin = yscaled[1] - yscaled[0]
1246
+ automax = yscaled[-1] - yscaled[-2]
1247
+ extendlength = [0, 0]
1248
+ if self._extend_lower() or self._extend_upper():
1249
+ extendlength = self._get_extension_lengths(
1250
+ self.extendfrac, automin, automax, default=0.05)
1251
+ return y, extendlength
1252
+
1253
+ def _get_extension_lengths(self, frac, automin, automax, default=0.05):
1254
+ """
1255
+ Return the lengths of colorbar extensions.
1256
+
1257
+ This is a helper method for _uniform_y and _proportional_y.
1258
+ """
1259
+ # Set the default value.
1260
+ extendlength = np.array([default, default])
1261
+ if isinstance(frac, str):
1262
+ _api.check_in_list(['auto'], extendfrac=frac.lower())
1263
+ # Use the provided values when 'auto' is required.
1264
+ extendlength[:] = [automin, automax]
1265
+ elif frac is not None:
1266
+ try:
1267
+ # Try to set min and max extension fractions directly.
1268
+ extendlength[:] = frac
1269
+ # If frac is a sequence containing None then NaN may
1270
+ # be encountered. This is an error.
1271
+ if np.isnan(extendlength).any():
1272
+ raise ValueError()
1273
+ except (TypeError, ValueError) as err:
1274
+ # Raise an error on encountering an invalid value for frac.
1275
+ raise ValueError('invalid value for extendfrac') from err
1276
+ return extendlength
1277
+
1278
+ def _extend_lower(self):
1279
+ """Return whether the lower limit is open ended."""
1280
+ minmax = "max" if self._long_axis().get_inverted() else "min"
1281
+ return self.extend in ('both', minmax)
1282
+
1283
+ def _extend_upper(self):
1284
+ """Return whether the upper limit is open ended."""
1285
+ minmax = "min" if self._long_axis().get_inverted() else "max"
1286
+ return self.extend in ('both', minmax)
1287
+
1288
+ def _long_axis(self):
1289
+ """Return the long axis"""
1290
+ if self.orientation == 'vertical':
1291
+ return self.ax.yaxis
1292
+ return self.ax.xaxis
1293
+
1294
+ def _short_axis(self):
1295
+ """Return the short axis"""
1296
+ if self.orientation == 'vertical':
1297
+ return self.ax.xaxis
1298
+ return self.ax.yaxis
1299
+
1300
+ def _get_view(self):
1301
+ # docstring inherited
1302
+ # An interactive view for a colorbar is the norm's vmin/vmax
1303
+ return self.norm.vmin, self.norm.vmax
1304
+
1305
+ def _set_view(self, view):
1306
+ # docstring inherited
1307
+ # An interactive view for a colorbar is the norm's vmin/vmax
1308
+ self.norm.vmin, self.norm.vmax = view
1309
+
1310
+ def _set_view_from_bbox(self, bbox, direction='in',
1311
+ mode=None, twinx=False, twiny=False):
1312
+ # docstring inherited
1313
+ # For colorbars, we use the zoom bbox to scale the norm's vmin/vmax
1314
+ new_xbound, new_ybound = self.ax._prepare_view_from_bbox(
1315
+ bbox, direction=direction, mode=mode, twinx=twinx, twiny=twiny)
1316
+ if self.orientation == 'horizontal':
1317
+ self.norm.vmin, self.norm.vmax = new_xbound
1318
+ elif self.orientation == 'vertical':
1319
+ self.norm.vmin, self.norm.vmax = new_ybound
1320
+
1321
+ def drag_pan(self, button, key, x, y):
1322
+ # docstring inherited
1323
+ points = self.ax._get_pan_points(button, key, x, y)
1324
+ if points is not None:
1325
+ if self.orientation == 'horizontal':
1326
+ self.norm.vmin, self.norm.vmax = points[:, 0]
1327
+ elif self.orientation == 'vertical':
1328
+ self.norm.vmin, self.norm.vmax = points[:, 1]
1329
+
1330
+
1331
+ ColorbarBase = Colorbar # Backcompat API
1332
+
1333
+
1334
+ def _normalize_location_orientation(location, orientation):
1335
+ if location is None:
1336
+ location = _get_ticklocation_from_orientation(orientation)
1337
+ loc_settings = _api.check_getitem({
1338
+ "left": {"location": "left", "anchor": (1.0, 0.5),
1339
+ "panchor": (0.0, 0.5), "pad": 0.10},
1340
+ "right": {"location": "right", "anchor": (0.0, 0.5),
1341
+ "panchor": (1.0, 0.5), "pad": 0.05},
1342
+ "top": {"location": "top", "anchor": (0.5, 0.0),
1343
+ "panchor": (0.5, 1.0), "pad": 0.05},
1344
+ "bottom": {"location": "bottom", "anchor": (0.5, 1.0),
1345
+ "panchor": (0.5, 0.0), "pad": 0.15},
1346
+ }, location=location)
1347
+ loc_settings["orientation"] = _get_orientation_from_location(location)
1348
+ if orientation is not None and orientation != loc_settings["orientation"]:
1349
+ # Allow the user to pass both if they are consistent.
1350
+ raise TypeError("location and orientation are mutually exclusive")
1351
+ return loc_settings
1352
+
1353
+
1354
+ def _get_orientation_from_location(location):
1355
+ return _api.check_getitem(
1356
+ {None: None, "left": "vertical", "right": "vertical",
1357
+ "top": "horizontal", "bottom": "horizontal"}, location=location)
1358
+
1359
+
1360
+ def _get_ticklocation_from_orientation(orientation):
1361
+ return _api.check_getitem(
1362
+ {None: "right", "vertical": "right", "horizontal": "bottom"},
1363
+ orientation=orientation)
1364
+
1365
+
1366
+ @_docstring.interpd
1367
+ def make_axes(parents, location=None, orientation=None, fraction=0.15,
1368
+ shrink=1.0, aspect=20, **kwargs):
1369
+ """
1370
+ Create an `~.axes.Axes` suitable for a colorbar.
1371
+
1372
+ The Axes is placed in the figure of the *parents* Axes, by resizing and
1373
+ repositioning *parents*.
1374
+
1375
+ Parameters
1376
+ ----------
1377
+ parents : `~matplotlib.axes.Axes` or iterable or `numpy.ndarray` of `~.axes.Axes`
1378
+ The Axes to use as parents for placing the colorbar.
1379
+ %(_make_axes_kw_doc)s
1380
+
1381
+ Returns
1382
+ -------
1383
+ cax : `~matplotlib.axes.Axes`
1384
+ The child Axes.
1385
+ kwargs : dict
1386
+ The reduced keyword dictionary to be passed when creating the colorbar
1387
+ instance.
1388
+ """
1389
+ loc_settings = _normalize_location_orientation(location, orientation)
1390
+ # put appropriate values into the kwargs dict for passing back to
1391
+ # the Colorbar class
1392
+ kwargs['orientation'] = loc_settings['orientation']
1393
+ location = kwargs['ticklocation'] = loc_settings['location']
1394
+
1395
+ anchor = kwargs.pop('anchor', loc_settings['anchor'])
1396
+ panchor = kwargs.pop('panchor', loc_settings['panchor'])
1397
+ aspect0 = aspect
1398
+ # turn parents into a list if it is not already. Note we cannot
1399
+ # use .flatten or .ravel as these copy the references rather than
1400
+ # reuse them, leading to a memory leak
1401
+ if isinstance(parents, np.ndarray):
1402
+ parents = list(parents.flat)
1403
+ elif np.iterable(parents):
1404
+ parents = list(parents)
1405
+ else:
1406
+ parents = [parents]
1407
+
1408
+ fig = parents[0].get_figure()
1409
+
1410
+ pad0 = 0.05 if fig.get_constrained_layout() else loc_settings['pad']
1411
+ pad = kwargs.pop('pad', pad0)
1412
+
1413
+ if not all(fig is ax.get_figure() for ax in parents):
1414
+ raise ValueError('Unable to create a colorbar Axes as not all '
1415
+ 'parents share the same figure.')
1416
+
1417
+ # take a bounding box around all of the given Axes
1418
+ parents_bbox = mtransforms.Bbox.union(
1419
+ [ax.get_position(original=True).frozen() for ax in parents])
1420
+
1421
+ pb = parents_bbox
1422
+ if location in ('left', 'right'):
1423
+ if location == 'left':
1424
+ pbcb, _, pb1 = pb.splitx(fraction, fraction + pad)
1425
+ else:
1426
+ pb1, _, pbcb = pb.splitx(1 - fraction - pad, 1 - fraction)
1427
+ pbcb = pbcb.shrunk(1.0, shrink).anchored(anchor, pbcb)
1428
+ else:
1429
+ if location == 'bottom':
1430
+ pbcb, _, pb1 = pb.splity(fraction, fraction + pad)
1431
+ else:
1432
+ pb1, _, pbcb = pb.splity(1 - fraction - pad, 1 - fraction)
1433
+ pbcb = pbcb.shrunk(shrink, 1.0).anchored(anchor, pbcb)
1434
+
1435
+ # define the aspect ratio in terms of y's per x rather than x's per y
1436
+ aspect = 1.0 / aspect
1437
+
1438
+ # define a transform which takes us from old axes coordinates to
1439
+ # new axes coordinates
1440
+ shrinking_trans = mtransforms.BboxTransform(parents_bbox, pb1)
1441
+
1442
+ # transform each of the Axes in parents using the new transform
1443
+ for ax in parents:
1444
+ new_posn = shrinking_trans.transform(ax.get_position(original=True))
1445
+ new_posn = mtransforms.Bbox(new_posn)
1446
+ ax._set_position(new_posn)
1447
+ if panchor is not False:
1448
+ ax.set_anchor(panchor)
1449
+
1450
+ cax = fig.add_axes(pbcb, label="<colorbar>")
1451
+ for a in parents:
1452
+ # tell the parent it has a colorbar
1453
+ a._colorbars += [cax]
1454
+ cax._colorbar_info = dict(
1455
+ parents=parents,
1456
+ location=location,
1457
+ shrink=shrink,
1458
+ anchor=anchor,
1459
+ panchor=panchor,
1460
+ fraction=fraction,
1461
+ aspect=aspect0,
1462
+ pad=pad)
1463
+ # and we need to set the aspect ratio by hand...
1464
+ cax.set_anchor(anchor)
1465
+ cax.set_box_aspect(aspect)
1466
+ cax.set_aspect('auto')
1467
+
1468
+ return cax, kwargs
1469
+
1470
+
1471
+ @_docstring.interpd
1472
+ def make_axes_gridspec(parent, *, location=None, orientation=None,
1473
+ fraction=0.15, shrink=1.0, aspect=20, **kwargs):
1474
+ """
1475
+ Create an `~.axes.Axes` suitable for a colorbar.
1476
+
1477
+ The Axes is placed in the figure of the *parent* Axes, by resizing and
1478
+ repositioning *parent*.
1479
+
1480
+ This function is similar to `.make_axes` and mostly compatible with it.
1481
+ Primary differences are
1482
+
1483
+ - `.make_axes_gridspec` requires the *parent* to have a subplotspec.
1484
+ - `.make_axes` positions the Axes in figure coordinates;
1485
+ `.make_axes_gridspec` positions it using a subplotspec.
1486
+ - `.make_axes` updates the position of the parent. `.make_axes_gridspec`
1487
+ replaces the parent gridspec with a new one.
1488
+
1489
+ Parameters
1490
+ ----------
1491
+ parent : `~matplotlib.axes.Axes`
1492
+ The Axes to use as parent for placing the colorbar.
1493
+ %(_make_axes_kw_doc)s
1494
+
1495
+ Returns
1496
+ -------
1497
+ cax : `~matplotlib.axes.Axes`
1498
+ The child Axes.
1499
+ kwargs : dict
1500
+ The reduced keyword dictionary to be passed when creating the colorbar
1501
+ instance.
1502
+ """
1503
+
1504
+ loc_settings = _normalize_location_orientation(location, orientation)
1505
+ kwargs['orientation'] = loc_settings['orientation']
1506
+ location = kwargs['ticklocation'] = loc_settings['location']
1507
+
1508
+ aspect0 = aspect
1509
+ anchor = kwargs.pop('anchor', loc_settings['anchor'])
1510
+ panchor = kwargs.pop('panchor', loc_settings['panchor'])
1511
+ pad = kwargs.pop('pad', loc_settings["pad"])
1512
+ wh_space = 2 * pad / (1 - pad)
1513
+
1514
+ if location in ('left', 'right'):
1515
+ gs = parent.get_subplotspec().subgridspec(
1516
+ 3, 2, wspace=wh_space, hspace=0,
1517
+ height_ratios=[(1-anchor[1])*(1-shrink), shrink, anchor[1]*(1-shrink)])
1518
+ if location == 'left':
1519
+ gs.set_width_ratios([fraction, 1 - fraction - pad])
1520
+ ss_main = gs[:, 1]
1521
+ ss_cb = gs[1, 0]
1522
+ else:
1523
+ gs.set_width_ratios([1 - fraction - pad, fraction])
1524
+ ss_main = gs[:, 0]
1525
+ ss_cb = gs[1, 1]
1526
+ else:
1527
+ gs = parent.get_subplotspec().subgridspec(
1528
+ 2, 3, hspace=wh_space, wspace=0,
1529
+ width_ratios=[anchor[0]*(1-shrink), shrink, (1-anchor[0])*(1-shrink)])
1530
+ if location == 'top':
1531
+ gs.set_height_ratios([fraction, 1 - fraction - pad])
1532
+ ss_main = gs[1, :]
1533
+ ss_cb = gs[0, 1]
1534
+ else:
1535
+ gs.set_height_ratios([1 - fraction - pad, fraction])
1536
+ ss_main = gs[0, :]
1537
+ ss_cb = gs[1, 1]
1538
+ aspect = 1 / aspect
1539
+
1540
+ parent.set_subplotspec(ss_main)
1541
+ if panchor is not False:
1542
+ parent.set_anchor(panchor)
1543
+
1544
+ fig = parent.get_figure()
1545
+ cax = fig.add_subplot(ss_cb, label="<colorbar>")
1546
+ cax.set_anchor(anchor)
1547
+ cax.set_box_aspect(aspect)
1548
+ cax.set_aspect('auto')
1549
+ cax._colorbar_info = dict(
1550
+ location=location,
1551
+ parents=[parent],
1552
+ shrink=shrink,
1553
+ anchor=anchor,
1554
+ panchor=panchor,
1555
+ fraction=fraction,
1556
+ aspect=aspect0,
1557
+ pad=pad)
1558
+
1559
+ return cax, kwargs
llava_next/lib/python3.10/site-packages/matplotlib/colors.pyi ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable, Iterable, Iterator, Mapping, Sequence
2
+ from matplotlib import cbook, scale
3
+ import re
4
+
5
+ from typing import Any, Literal, overload
6
+ from .typing import ColorType
7
+
8
+ import numpy as np
9
+ from numpy.typing import ArrayLike
10
+
11
+ # Explicitly export colors dictionaries which are imported in the impl
12
+ BASE_COLORS: dict[str, ColorType]
13
+ CSS4_COLORS: dict[str, ColorType]
14
+ TABLEAU_COLORS: dict[str, ColorType]
15
+ XKCD_COLORS: dict[str, ColorType]
16
+
17
+ class _ColorMapping(dict[str, ColorType]):
18
+ cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]]
19
+ def __init__(self, mapping) -> None: ...
20
+ def __setitem__(self, key, value) -> None: ...
21
+ def __delitem__(self, key) -> None: ...
22
+
23
+ def get_named_colors_mapping() -> _ColorMapping: ...
24
+
25
+ class ColorSequenceRegistry(Mapping):
26
+ def __init__(self) -> None: ...
27
+ def __getitem__(self, item: str) -> list[ColorType]: ...
28
+ def __iter__(self) -> Iterator[str]: ...
29
+ def __len__(self) -> int: ...
30
+ def register(self, name: str, color_list: Iterable[ColorType]) -> None: ...
31
+ def unregister(self, name: str) -> None: ...
32
+
33
+ _color_sequences: ColorSequenceRegistry = ...
34
+
35
+ def is_color_like(c: Any) -> bool: ...
36
+ def same_color(c1: ColorType, c2: ColorType) -> bool: ...
37
+ def to_rgba(
38
+ c: ColorType, alpha: float | None = ...
39
+ ) -> tuple[float, float, float, float]: ...
40
+ def to_rgba_array(
41
+ c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ...
42
+ ) -> np.ndarray: ...
43
+ def to_rgb(c: ColorType) -> tuple[float, float, float]: ...
44
+ def to_hex(c: ColorType, keep_alpha: bool = ...) -> str: ...
45
+
46
+ cnames: dict[str, ColorType]
47
+ hexColorPattern: re.Pattern
48
+ rgb2hex = to_hex
49
+ hex2color = to_rgb
50
+
51
+ class ColorConverter:
52
+ colors: _ColorMapping
53
+ cache: dict[tuple[ColorType, float | None], tuple[float, float, float, float]]
54
+ @staticmethod
55
+ def to_rgb(c: ColorType) -> tuple[float, float, float]: ...
56
+ @staticmethod
57
+ def to_rgba(
58
+ c: ColorType, alpha: float | None = ...
59
+ ) -> tuple[float, float, float, float]: ...
60
+ @staticmethod
61
+ def to_rgba_array(
62
+ c: ColorType | ArrayLike, alpha: float | ArrayLike | None = ...
63
+ ) -> np.ndarray: ...
64
+
65
+ colorConverter: ColorConverter
66
+
67
+ class Colormap:
68
+ name: str
69
+ N: int
70
+ colorbar_extend: bool
71
+ def __init__(self, name: str, N: int = ...) -> None: ...
72
+ @overload
73
+ def __call__(
74
+ self, X: Sequence[float] | np.ndarray, alpha: ArrayLike | None = ..., bytes: bool = ...
75
+ ) -> np.ndarray: ...
76
+ @overload
77
+ def __call__(
78
+ self, X: float, alpha: float | None = ..., bytes: bool = ...
79
+ ) -> tuple[float, float, float, float]: ...
80
+ @overload
81
+ def __call__(
82
+ self, X: ArrayLike, alpha: ArrayLike | None = ..., bytes: bool = ...
83
+ ) -> tuple[float, float, float, float] | np.ndarray: ...
84
+ def __copy__(self) -> Colormap: ...
85
+ def __eq__(self, other: object) -> bool: ...
86
+ def get_bad(self) -> np.ndarray: ...
87
+ def set_bad(self, color: ColorType = ..., alpha: float | None = ...) -> None: ...
88
+ def get_under(self) -> np.ndarray: ...
89
+ def set_under(self, color: ColorType = ..., alpha: float | None = ...) -> None: ...
90
+ def get_over(self) -> np.ndarray: ...
91
+ def set_over(self, color: ColorType = ..., alpha: float | None = ...) -> None: ...
92
+ def set_extremes(
93
+ self,
94
+ *,
95
+ bad: ColorType | None = ...,
96
+ under: ColorType | None = ...,
97
+ over: ColorType | None = ...
98
+ ) -> None: ...
99
+ def with_extremes(
100
+ self,
101
+ *,
102
+ bad: ColorType | None = ...,
103
+ under: ColorType | None = ...,
104
+ over: ColorType | None = ...
105
+ ) -> Colormap: ...
106
+ def is_gray(self) -> bool: ...
107
+ def resampled(self, lutsize: int) -> Colormap: ...
108
+ def reversed(self, name: str | None = ...) -> Colormap: ...
109
+ def _repr_html_(self) -> str: ...
110
+ def _repr_png_(self) -> bytes: ...
111
+ def copy(self) -> Colormap: ...
112
+
113
+ class LinearSegmentedColormap(Colormap):
114
+ monochrome: bool
115
+ def __init__(
116
+ self,
117
+ name: str,
118
+ segmentdata: dict[
119
+ Literal["red", "green", "blue", "alpha"], Sequence[tuple[float, ...]]
120
+ ],
121
+ N: int = ...,
122
+ gamma: float = ...,
123
+ ) -> None: ...
124
+ def set_gamma(self, gamma: float) -> None: ...
125
+ @staticmethod
126
+ def from_list(
127
+ name: str, colors: ArrayLike | Sequence[tuple[float, ColorType]], N: int = ..., gamma: float = ...
128
+ ) -> LinearSegmentedColormap: ...
129
+ def resampled(self, lutsize: int) -> LinearSegmentedColormap: ...
130
+ def reversed(self, name: str | None = ...) -> LinearSegmentedColormap: ...
131
+
132
+ class ListedColormap(Colormap):
133
+ monochrome: bool
134
+ colors: ArrayLike | ColorType
135
+ def __init__(
136
+ self, colors: ArrayLike | ColorType, name: str = ..., N: int | None = ...
137
+ ) -> None: ...
138
+ def resampled(self, lutsize: int) -> ListedColormap: ...
139
+ def reversed(self, name: str | None = ...) -> ListedColormap: ...
140
+
141
+ class Normalize:
142
+ callbacks: cbook.CallbackRegistry
143
+ def __init__(
144
+ self, vmin: float | None = ..., vmax: float | None = ..., clip: bool = ...
145
+ ) -> None: ...
146
+ @property
147
+ def vmin(self) -> float | None: ...
148
+ @vmin.setter
149
+ def vmin(self, value: float | None) -> None: ...
150
+ @property
151
+ def vmax(self) -> float | None: ...
152
+ @vmax.setter
153
+ def vmax(self, value: float | None) -> None: ...
154
+ @property
155
+ def clip(self) -> bool: ...
156
+ @clip.setter
157
+ def clip(self, value: bool) -> None: ...
158
+ @staticmethod
159
+ def process_value(value: ArrayLike) -> tuple[np.ma.MaskedArray, bool]: ...
160
+ @overload
161
+ def __call__(self, value: float, clip: bool | None = ...) -> float: ...
162
+ @overload
163
+ def __call__(self, value: np.ndarray, clip: bool | None = ...) -> np.ma.MaskedArray: ...
164
+ @overload
165
+ def __call__(self, value: ArrayLike, clip: bool | None = ...) -> ArrayLike: ...
166
+ @overload
167
+ def inverse(self, value: float) -> float: ...
168
+ @overload
169
+ def inverse(self, value: np.ndarray) -> np.ma.MaskedArray: ...
170
+ @overload
171
+ def inverse(self, value: ArrayLike) -> ArrayLike: ...
172
+ def autoscale(self, A: ArrayLike) -> None: ...
173
+ def autoscale_None(self, A: ArrayLike) -> None: ...
174
+ def scaled(self) -> bool: ...
175
+
176
+ class TwoSlopeNorm(Normalize):
177
+ def __init__(
178
+ self, vcenter: float, vmin: float | None = ..., vmax: float | None = ...
179
+ ) -> None: ...
180
+ @property
181
+ def vcenter(self) -> float: ...
182
+ @vcenter.setter
183
+ def vcenter(self, value: float) -> None: ...
184
+ def autoscale_None(self, A: ArrayLike) -> None: ...
185
+
186
+ class CenteredNorm(Normalize):
187
+ def __init__(
188
+ self, vcenter: float = ..., halfrange: float | None = ..., clip: bool = ...
189
+ ) -> None: ...
190
+ @property
191
+ def vcenter(self) -> float: ...
192
+ @vcenter.setter
193
+ def vcenter(self, vcenter: float) -> None: ...
194
+ @property
195
+ def halfrange(self) -> float: ...
196
+ @halfrange.setter
197
+ def halfrange(self, halfrange: float) -> None: ...
198
+
199
+ @overload
200
+ def make_norm_from_scale(
201
+ scale_cls: type[scale.ScaleBase],
202
+ base_norm_cls: type[Normalize],
203
+ *,
204
+ init: Callable | None = ...
205
+ ) -> type[Normalize]: ...
206
+ @overload
207
+ def make_norm_from_scale(
208
+ scale_cls: type[scale.ScaleBase],
209
+ base_norm_cls: None = ...,
210
+ *,
211
+ init: Callable | None = ...
212
+ ) -> Callable[[type[Normalize]], type[Normalize]]: ...
213
+
214
+ class FuncNorm(Normalize):
215
+ def __init__(
216
+ self,
217
+ functions: tuple[Callable, Callable],
218
+ vmin: float | None = ...,
219
+ vmax: float | None = ...,
220
+ clip: bool = ...,
221
+ ) -> None: ...
222
+ class LogNorm(Normalize): ...
223
+
224
+ class SymLogNorm(Normalize):
225
+ def __init__(
226
+ self,
227
+ linthresh: float,
228
+ linscale: float = ...,
229
+ vmin: float | None = ...,
230
+ vmax: float | None = ...,
231
+ clip: bool = ...,
232
+ *,
233
+ base: float = ...,
234
+ ) -> None: ...
235
+ @property
236
+ def linthresh(self) -> float: ...
237
+ @linthresh.setter
238
+ def linthresh(self, value: float) -> None: ...
239
+
240
+ class AsinhNorm(Normalize):
241
+ def __init__(
242
+ self,
243
+ linear_width: float = ...,
244
+ vmin: float | None = ...,
245
+ vmax: float | None = ...,
246
+ clip: bool = ...,
247
+ ) -> None: ...
248
+ @property
249
+ def linear_width(self) -> float: ...
250
+ @linear_width.setter
251
+ def linear_width(self, value: float) -> None: ...
252
+
253
+ class PowerNorm(Normalize):
254
+ gamma: float
255
+ def __init__(
256
+ self,
257
+ gamma: float,
258
+ vmin: float | None = ...,
259
+ vmax: float | None = ...,
260
+ clip: bool = ...,
261
+ ) -> None: ...
262
+
263
+ class BoundaryNorm(Normalize):
264
+ boundaries: np.ndarray
265
+ N: int
266
+ Ncmap: int
267
+ extend: Literal["neither", "both", "min", "max"]
268
+ def __init__(
269
+ self,
270
+ boundaries: ArrayLike,
271
+ ncolors: int,
272
+ clip: bool = ...,
273
+ *,
274
+ extend: Literal["neither", "both", "min", "max"] = ...
275
+ ) -> None: ...
276
+
277
+ class NoNorm(Normalize): ...
278
+
279
+ def rgb_to_hsv(arr: ArrayLike) -> np.ndarray: ...
280
+ def hsv_to_rgb(hsv: ArrayLike) -> np.ndarray: ...
281
+
282
+ class LightSource:
283
+ azdeg: float
284
+ altdeg: float
285
+ hsv_min_val: float
286
+ hsv_max_val: float
287
+ hsv_min_sat: float
288
+ hsv_max_sat: float
289
+ def __init__(
290
+ self,
291
+ azdeg: float = ...,
292
+ altdeg: float = ...,
293
+ hsv_min_val: float = ...,
294
+ hsv_max_val: float = ...,
295
+ hsv_min_sat: float = ...,
296
+ hsv_max_sat: float = ...,
297
+ ) -> None: ...
298
+ @property
299
+ def direction(self) -> np.ndarray: ...
300
+ def hillshade(
301
+ self,
302
+ elevation: ArrayLike,
303
+ vert_exag: float = ...,
304
+ dx: float = ...,
305
+ dy: float = ...,
306
+ fraction: float = ...,
307
+ ) -> np.ndarray: ...
308
+ def shade_normals(
309
+ self, normals: np.ndarray, fraction: float = ...
310
+ ) -> np.ndarray: ...
311
+ def shade(
312
+ self,
313
+ data: ArrayLike,
314
+ cmap: Colormap,
315
+ norm: Normalize | None = ...,
316
+ blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ...,
317
+ vmin: float | None = ...,
318
+ vmax: float | None = ...,
319
+ vert_exag: float = ...,
320
+ dx: float = ...,
321
+ dy: float = ...,
322
+ fraction: float = ...,
323
+ **kwargs
324
+ ) -> np.ndarray: ...
325
+ def shade_rgb(
326
+ self,
327
+ rgb: ArrayLike,
328
+ elevation: ArrayLike,
329
+ fraction: float = ...,
330
+ blend_mode: Literal["hsv", "overlay", "soft"] | Callable = ...,
331
+ vert_exag: float = ...,
332
+ dx: float = ...,
333
+ dy: float = ...,
334
+ **kwargs
335
+ ) -> np.ndarray: ...
336
+ def blend_hsv(
337
+ self,
338
+ rgb: ArrayLike,
339
+ intensity: ArrayLike,
340
+ hsv_max_sat: float | None = ...,
341
+ hsv_max_val: float | None = ...,
342
+ hsv_min_val: float | None = ...,
343
+ hsv_min_sat: float | None = ...,
344
+ ) -> ArrayLike: ...
345
+ def blend_soft_light(
346
+ self, rgb: np.ndarray, intensity: np.ndarray
347
+ ) -> np.ndarray: ...
348
+ def blend_overlay(self, rgb: np.ndarray, intensity: np.ndarray) -> np.ndarray: ...
349
+
350
+ def from_levels_and_colors(
351
+ levels: Sequence[float],
352
+ colors: Sequence[ColorType],
353
+ extend: Literal["neither", "min", "max", "both"] = ...,
354
+ ) -> tuple[ListedColormap, BoundaryNorm]: ...
llava_next/lib/python3.10/site-packages/matplotlib/container.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib import cbook
2
+ from matplotlib.artist import Artist
3
+
4
+
5
+ class Container(tuple):
6
+ """
7
+ Base class for containers.
8
+
9
+ Containers are classes that collect semantically related Artists such as
10
+ the bars of a bar plot.
11
+ """
12
+
13
+ def __repr__(self):
14
+ return f"<{type(self).__name__} object of {len(self)} artists>"
15
+
16
+ def __new__(cls, *args, **kwargs):
17
+ return tuple.__new__(cls, args[0])
18
+
19
+ def __init__(self, kl, label=None):
20
+ self._callbacks = cbook.CallbackRegistry(signals=["pchanged"])
21
+ self._remove_method = None
22
+ self._label = str(label) if label is not None else None
23
+
24
+ def remove(self):
25
+ for c in cbook.flatten(
26
+ self, scalarp=lambda x: isinstance(x, Artist)):
27
+ if c is not None:
28
+ c.remove()
29
+ if self._remove_method:
30
+ self._remove_method(self)
31
+
32
+ def get_children(self):
33
+ return [child for child in cbook.flatten(self) if child is not None]
34
+
35
+ get_label = Artist.get_label
36
+ set_label = Artist.set_label
37
+ add_callback = Artist.add_callback
38
+ remove_callback = Artist.remove_callback
39
+ pchanged = Artist.pchanged
40
+
41
+
42
+ class BarContainer(Container):
43
+ """
44
+ Container for the artists of bar plots (e.g. created by `.Axes.bar`).
45
+
46
+ The container can be treated as a tuple of the *patches* themselves.
47
+ Additionally, you can access these and further parameters by the
48
+ attributes.
49
+
50
+ Attributes
51
+ ----------
52
+ patches : list of :class:`~matplotlib.patches.Rectangle`
53
+ The artists of the bars.
54
+
55
+ errorbar : None or :class:`~matplotlib.container.ErrorbarContainer`
56
+ A container for the error bar artists if error bars are present.
57
+ *None* otherwise.
58
+
59
+ datavalues : None or array-like
60
+ The underlying data values corresponding to the bars.
61
+
62
+ orientation : {'vertical', 'horizontal'}, default: None
63
+ If 'vertical', the bars are assumed to be vertical.
64
+ If 'horizontal', the bars are assumed to be horizontal.
65
+
66
+ """
67
+
68
+ def __init__(self, patches, errorbar=None, *, datavalues=None,
69
+ orientation=None, **kwargs):
70
+ self.patches = patches
71
+ self.errorbar = errorbar
72
+ self.datavalues = datavalues
73
+ self.orientation = orientation
74
+ super().__init__(patches, **kwargs)
75
+
76
+
77
+ class ErrorbarContainer(Container):
78
+ """
79
+ Container for the artists of error bars (e.g. created by `.Axes.errorbar`).
80
+
81
+ The container can be treated as the *lines* tuple itself.
82
+ Additionally, you can access these and further parameters by the
83
+ attributes.
84
+
85
+ Attributes
86
+ ----------
87
+ lines : tuple
88
+ Tuple of ``(data_line, caplines, barlinecols)``.
89
+
90
+ - data_line : A `~matplotlib.lines.Line2D` instance of x, y plot markers
91
+ and/or line.
92
+ - caplines : A tuple of `~matplotlib.lines.Line2D` instances of the error
93
+ bar caps.
94
+ - barlinecols : A tuple of `~matplotlib.collections.LineCollection` with the
95
+ horizontal and vertical error ranges.
96
+
97
+ has_xerr, has_yerr : bool
98
+ ``True`` if the errorbar has x/y errors.
99
+
100
+ """
101
+
102
+ def __init__(self, lines, has_xerr=False, has_yerr=False, **kwargs):
103
+ self.lines = lines
104
+ self.has_xerr = has_xerr
105
+ self.has_yerr = has_yerr
106
+ super().__init__(lines, **kwargs)
107
+
108
+
109
+ class StemContainer(Container):
110
+ """
111
+ Container for the artists created in a :meth:`.Axes.stem` plot.
112
+
113
+ The container can be treated like a namedtuple ``(markerline, stemlines,
114
+ baseline)``.
115
+
116
+ Attributes
117
+ ----------
118
+ markerline : `~matplotlib.lines.Line2D`
119
+ The artist of the markers at the stem heads.
120
+
121
+ stemlines : `~matplotlib.collections.LineCollection`
122
+ The artists of the vertical lines for all stems.
123
+
124
+ baseline : `~matplotlib.lines.Line2D`
125
+ The artist of the horizontal baseline.
126
+ """
127
+ def __init__(self, markerline_stemlines_baseline, **kwargs):
128
+ """
129
+ Parameters
130
+ ----------
131
+ markerline_stemlines_baseline : tuple
132
+ Tuple of ``(markerline, stemlines, baseline)``.
133
+ ``markerline`` contains the `.Line2D` of the markers,
134
+ ``stemlines`` is a `.LineCollection` of the main lines,
135
+ ``baseline`` is the `.Line2D` of the baseline.
136
+ """
137
+ markerline, stemlines, baseline = markerline_stemlines_baseline
138
+ self.markerline = markerline
139
+ self.stemlines = stemlines
140
+ self.baseline = baseline
141
+ super().__init__(markerline_stemlines_baseline, **kwargs)
llava_next/lib/python3.10/site-packages/matplotlib/dviread.py ADDED
@@ -0,0 +1,1107 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module for reading dvi files output by TeX. Several limitations make
3
+ this not (currently) useful as a general-purpose dvi preprocessor, but
4
+ it is currently used by the pdf backend for processing usetex text.
5
+
6
+ Interface::
7
+
8
+ with Dvi(filename, 72) as dvi:
9
+ # iterate over pages:
10
+ for page in dvi:
11
+ w, h, d = page.width, page.height, page.descent
12
+ for x, y, font, glyph, width in page.text:
13
+ fontname = font.texname
14
+ pointsize = font.size
15
+ ...
16
+ for x, y, height, width in page.boxes:
17
+ ...
18
+ """
19
+
20
+ from collections import namedtuple
21
+ import enum
22
+ from functools import lru_cache, partial, wraps
23
+ import logging
24
+ import os
25
+ from pathlib import Path
26
+ import re
27
+ import struct
28
+ import subprocess
29
+ import sys
30
+
31
+ import numpy as np
32
+
33
+ from matplotlib import _api, cbook
34
+
35
+ _log = logging.getLogger(__name__)
36
+
37
+ # Many dvi related files are looked for by external processes, require
38
+ # additional parsing, and are used many times per rendering, which is why they
39
+ # are cached using lru_cache().
40
+
41
+ # Dvi is a bytecode format documented in
42
+ # https://ctan.org/pkg/dvitype
43
+ # https://texdoc.org/serve/dvitype.pdf/0
44
+ #
45
+ # The file consists of a preamble, some number of pages, a postamble,
46
+ # and a finale. Different opcodes are allowed in different contexts,
47
+ # so the Dvi object has a parser state:
48
+ #
49
+ # pre: expecting the preamble
50
+ # outer: between pages (followed by a page or the postamble,
51
+ # also e.g. font definitions are allowed)
52
+ # page: processing a page
53
+ # post_post: state after the postamble (our current implementation
54
+ # just stops reading)
55
+ # finale: the finale (unimplemented in our current implementation)
56
+
57
+ _dvistate = enum.Enum('DviState', 'pre outer inpage post_post finale')
58
+
59
+ # The marks on a page consist of text and boxes. A page also has dimensions.
60
+ Page = namedtuple('Page', 'text boxes height width descent')
61
+ Box = namedtuple('Box', 'x y height width')
62
+
63
+
64
+ # Also a namedtuple, for backcompat.
65
+ class Text(namedtuple('Text', 'x y font glyph width')):
66
+ """
67
+ A glyph in the dvi file.
68
+
69
+ The *x* and *y* attributes directly position the glyph. The *font*,
70
+ *glyph*, and *width* attributes are kept public for back-compatibility,
71
+ but users wanting to draw the glyph themselves are encouraged to instead
72
+ load the font specified by `font_path` at `font_size`, warp it with the
73
+ effects specified by `font_effects`, and load the glyph specified by
74
+ `glyph_name_or_index`.
75
+ """
76
+
77
+ def _get_pdftexmap_entry(self):
78
+ return PsfontsMap(find_tex_file("pdftex.map"))[self.font.texname]
79
+
80
+ @property
81
+ def font_path(self):
82
+ """The `~pathlib.Path` to the font for this glyph."""
83
+ psfont = self._get_pdftexmap_entry()
84
+ if psfont.filename is None:
85
+ raise ValueError("No usable font file found for {} ({}); "
86
+ "the font may lack a Type-1 version"
87
+ .format(psfont.psname.decode("ascii"),
88
+ psfont.texname.decode("ascii")))
89
+ return Path(psfont.filename)
90
+
91
+ @property
92
+ def font_size(self):
93
+ """The font size."""
94
+ return self.font.size
95
+
96
+ @property
97
+ def font_effects(self):
98
+ """
99
+ The "font effects" dict for this glyph.
100
+
101
+ This dict contains the values for this glyph of SlantFont and
102
+ ExtendFont (if any), read off :file:`pdftex.map`.
103
+ """
104
+ return self._get_pdftexmap_entry().effects
105
+
106
+ @property
107
+ def glyph_name_or_index(self):
108
+ """
109
+ Either the glyph name or the native charmap glyph index.
110
+
111
+ If :file:`pdftex.map` specifies an encoding for this glyph's font, that
112
+ is a mapping of glyph indices to Adobe glyph names; use it to convert
113
+ dvi indices to glyph names. Callers can then convert glyph names to
114
+ glyph indices (with FT_Get_Name_Index/get_name_index), and load the
115
+ glyph using FT_Load_Glyph/load_glyph.
116
+
117
+ If :file:`pdftex.map` specifies no encoding, the indices directly map
118
+ to the font's "native" charmap; glyphs should directly load using
119
+ FT_Load_Char/load_char after selecting the native charmap.
120
+ """
121
+ entry = self._get_pdftexmap_entry()
122
+ return (_parse_enc(entry.encoding)[self.glyph]
123
+ if entry.encoding is not None else self.glyph)
124
+
125
+
126
+ # Opcode argument parsing
127
+ #
128
+ # Each of the following functions takes a Dvi object and delta, which is the
129
+ # difference between the opcode and the minimum opcode with the same meaning.
130
+ # Dvi opcodes often encode the number of argument bytes in this delta.
131
+ _arg_mapping = dict(
132
+ # raw: Return delta as is.
133
+ raw=lambda dvi, delta: delta,
134
+ # u1: Read 1 byte as an unsigned number.
135
+ u1=lambda dvi, delta: dvi._arg(1, signed=False),
136
+ # u4: Read 4 bytes as an unsigned number.
137
+ u4=lambda dvi, delta: dvi._arg(4, signed=False),
138
+ # s4: Read 4 bytes as a signed number.
139
+ s4=lambda dvi, delta: dvi._arg(4, signed=True),
140
+ # slen: Read delta bytes as a signed number, or None if delta is None.
141
+ slen=lambda dvi, delta: dvi._arg(delta, signed=True) if delta else None,
142
+ # slen1: Read (delta + 1) bytes as a signed number.
143
+ slen1=lambda dvi, delta: dvi._arg(delta + 1, signed=True),
144
+ # ulen1: Read (delta + 1) bytes as an unsigned number.
145
+ ulen1=lambda dvi, delta: dvi._arg(delta + 1, signed=False),
146
+ # olen1: Read (delta + 1) bytes as an unsigned number if less than 4 bytes,
147
+ # as a signed number if 4 bytes.
148
+ olen1=lambda dvi, delta: dvi._arg(delta + 1, signed=(delta == 3)),
149
+ )
150
+
151
+
152
+ def _dispatch(table, min, max=None, state=None, args=('raw',)):
153
+ """
154
+ Decorator for dispatch by opcode. Sets the values in *table*
155
+ from *min* to *max* to this method, adds a check that the Dvi state
156
+ matches *state* if not None, reads arguments from the file according
157
+ to *args*.
158
+
159
+ Parameters
160
+ ----------
161
+ table : dict[int, callable]
162
+ The dispatch table to be filled in.
163
+
164
+ min, max : int
165
+ Range of opcodes that calls the registered function; *max* defaults to
166
+ *min*.
167
+
168
+ state : _dvistate, optional
169
+ State of the Dvi object in which these opcodes are allowed.
170
+
171
+ args : list[str], default: ['raw']
172
+ Sequence of argument specifications:
173
+
174
+ - 'raw': opcode minus minimum
175
+ - 'u1': read one unsigned byte
176
+ - 'u4': read four bytes, treat as an unsigned number
177
+ - 's4': read four bytes, treat as a signed number
178
+ - 'slen': read (opcode - minimum) bytes, treat as signed
179
+ - 'slen1': read (opcode - minimum + 1) bytes, treat as signed
180
+ - 'ulen1': read (opcode - minimum + 1) bytes, treat as unsigned
181
+ - 'olen1': read (opcode - minimum + 1) bytes, treat as unsigned
182
+ if under four bytes, signed if four bytes
183
+ """
184
+ def decorate(method):
185
+ get_args = [_arg_mapping[x] for x in args]
186
+
187
+ @wraps(method)
188
+ def wrapper(self, byte):
189
+ if state is not None and self.state != state:
190
+ raise ValueError("state precondition failed")
191
+ return method(self, *[f(self, byte-min) for f in get_args])
192
+ if max is None:
193
+ table[min] = wrapper
194
+ else:
195
+ for i in range(min, max+1):
196
+ assert table[i] is None
197
+ table[i] = wrapper
198
+ return wrapper
199
+ return decorate
200
+
201
+
202
+ class Dvi:
203
+ """
204
+ A reader for a dvi ("device-independent") file, as produced by TeX.
205
+
206
+ The current implementation can only iterate through pages in order,
207
+ and does not even attempt to verify the postamble.
208
+
209
+ This class can be used as a context manager to close the underlying
210
+ file upon exit. Pages can be read via iteration. Here is an overly
211
+ simple way to extract text without trying to detect whitespace::
212
+
213
+ >>> with matplotlib.dviread.Dvi('input.dvi', 72) as dvi:
214
+ ... for page in dvi:
215
+ ... print(''.join(chr(t.glyph) for t in page.text))
216
+ """
217
+ # dispatch table
218
+ _dtable = [None] * 256
219
+ _dispatch = partial(_dispatch, _dtable)
220
+
221
+ def __init__(self, filename, dpi):
222
+ """
223
+ Read the data from the file named *filename* and convert
224
+ TeX's internal units to units of *dpi* per inch.
225
+ *dpi* only sets the units and does not limit the resolution.
226
+ Use None to return TeX's internal units.
227
+ """
228
+ _log.debug('Dvi: %s', filename)
229
+ self.file = open(filename, 'rb')
230
+ self.dpi = dpi
231
+ self.fonts = {}
232
+ self.state = _dvistate.pre
233
+
234
+ def __enter__(self):
235
+ """Context manager enter method, does nothing."""
236
+ return self
237
+
238
+ def __exit__(self, etype, evalue, etrace):
239
+ """
240
+ Context manager exit method, closes the underlying file if it is open.
241
+ """
242
+ self.close()
243
+
244
+ def __iter__(self):
245
+ """
246
+ Iterate through the pages of the file.
247
+
248
+ Yields
249
+ ------
250
+ Page
251
+ Details of all the text and box objects on the page.
252
+ The Page tuple contains lists of Text and Box tuples and
253
+ the page dimensions, and the Text and Box tuples contain
254
+ coordinates transformed into a standard Cartesian
255
+ coordinate system at the dpi value given when initializing.
256
+ The coordinates are floating point numbers, but otherwise
257
+ precision is not lost and coordinate values are not clipped to
258
+ integers.
259
+ """
260
+ while self._read():
261
+ yield self._output()
262
+
263
+ def close(self):
264
+ """Close the underlying file if it is open."""
265
+ if not self.file.closed:
266
+ self.file.close()
267
+
268
+ def _output(self):
269
+ """
270
+ Output the text and boxes belonging to the most recent page.
271
+ page = dvi._output()
272
+ """
273
+ minx, miny, maxx, maxy = np.inf, np.inf, -np.inf, -np.inf
274
+ maxy_pure = -np.inf
275
+ for elt in self.text + self.boxes:
276
+ if isinstance(elt, Box):
277
+ x, y, h, w = elt
278
+ e = 0 # zero depth
279
+ else: # glyph
280
+ x, y, font, g, w = elt
281
+ h, e = font._height_depth_of(g)
282
+ minx = min(minx, x)
283
+ miny = min(miny, y - h)
284
+ maxx = max(maxx, x + w)
285
+ maxy = max(maxy, y + e)
286
+ maxy_pure = max(maxy_pure, y)
287
+ if self._baseline_v is not None:
288
+ maxy_pure = self._baseline_v # This should normally be the case.
289
+ self._baseline_v = None
290
+
291
+ if not self.text and not self.boxes: # Avoid infs/nans from inf+/-inf.
292
+ return Page(text=[], boxes=[], width=0, height=0, descent=0)
293
+
294
+ if self.dpi is None:
295
+ # special case for ease of debugging: output raw dvi coordinates
296
+ return Page(text=self.text, boxes=self.boxes,
297
+ width=maxx-minx, height=maxy_pure-miny,
298
+ descent=maxy-maxy_pure)
299
+
300
+ # convert from TeX's "scaled points" to dpi units
301
+ d = self.dpi / (72.27 * 2**16)
302
+ descent = (maxy - maxy_pure) * d
303
+
304
+ text = [Text((x-minx)*d, (maxy-y)*d - descent, f, g, w*d)
305
+ for (x, y, f, g, w) in self.text]
306
+ boxes = [Box((x-minx)*d, (maxy-y)*d - descent, h*d, w*d)
307
+ for (x, y, h, w) in self.boxes]
308
+
309
+ return Page(text=text, boxes=boxes, width=(maxx-minx)*d,
310
+ height=(maxy_pure-miny)*d, descent=descent)
311
+
312
+ def _read(self):
313
+ """
314
+ Read one page from the file. Return True if successful,
315
+ False if there were no more pages.
316
+ """
317
+ # Pages appear to start with the sequence
318
+ # bop (begin of page)
319
+ # xxx comment
320
+ # <push, ..., pop> # if using chemformula
321
+ # down
322
+ # push
323
+ # down
324
+ # <push, push, xxx, right, xxx, pop, pop> # if using xcolor
325
+ # down
326
+ # push
327
+ # down (possibly multiple)
328
+ # push <= here, v is the baseline position.
329
+ # etc.
330
+ # (dviasm is useful to explore this structure.)
331
+ # Thus, we use the vertical position at the first time the stack depth
332
+ # reaches 3, while at least three "downs" have been executed (excluding
333
+ # those popped out (corresponding to the chemformula preamble)), as the
334
+ # baseline (the "down" count is necessary to handle xcolor).
335
+ down_stack = [0]
336
+ self._baseline_v = None
337
+ while True:
338
+ byte = self.file.read(1)[0]
339
+ self._dtable[byte](self, byte)
340
+ name = self._dtable[byte].__name__
341
+ if name == "_push":
342
+ down_stack.append(down_stack[-1])
343
+ elif name == "_pop":
344
+ down_stack.pop()
345
+ elif name == "_down":
346
+ down_stack[-1] += 1
347
+ if (self._baseline_v is None
348
+ and len(getattr(self, "stack", [])) == 3
349
+ and down_stack[-1] >= 4):
350
+ self._baseline_v = self.v
351
+ if byte == 140: # end of page
352
+ return True
353
+ if self.state is _dvistate.post_post: # end of file
354
+ self.close()
355
+ return False
356
+
357
+ def _arg(self, nbytes, signed=False):
358
+ """
359
+ Read and return a big-endian integer *nbytes* long.
360
+ Signedness is determined by the *signed* keyword.
361
+ """
362
+ return int.from_bytes(self.file.read(nbytes), "big", signed=signed)
363
+
364
+ @_dispatch(min=0, max=127, state=_dvistate.inpage)
365
+ def _set_char_immediate(self, char):
366
+ self._put_char_real(char)
367
+ self.h += self.fonts[self.f]._width_of(char)
368
+
369
+ @_dispatch(min=128, max=131, state=_dvistate.inpage, args=('olen1',))
370
+ def _set_char(self, char):
371
+ self._put_char_real(char)
372
+ self.h += self.fonts[self.f]._width_of(char)
373
+
374
+ @_dispatch(132, state=_dvistate.inpage, args=('s4', 's4'))
375
+ def _set_rule(self, a, b):
376
+ self._put_rule_real(a, b)
377
+ self.h += b
378
+
379
+ @_dispatch(min=133, max=136, state=_dvistate.inpage, args=('olen1',))
380
+ def _put_char(self, char):
381
+ self._put_char_real(char)
382
+
383
+ def _put_char_real(self, char):
384
+ font = self.fonts[self.f]
385
+ if font._vf is None:
386
+ self.text.append(Text(self.h, self.v, font, char,
387
+ font._width_of(char)))
388
+ else:
389
+ scale = font._scale
390
+ for x, y, f, g, w in font._vf[char].text:
391
+ newf = DviFont(scale=_mul2012(scale, f._scale),
392
+ tfm=f._tfm, texname=f.texname, vf=f._vf)
393
+ self.text.append(Text(self.h + _mul2012(x, scale),
394
+ self.v + _mul2012(y, scale),
395
+ newf, g, newf._width_of(g)))
396
+ self.boxes.extend([Box(self.h + _mul2012(x, scale),
397
+ self.v + _mul2012(y, scale),
398
+ _mul2012(a, scale), _mul2012(b, scale))
399
+ for x, y, a, b in font._vf[char].boxes])
400
+
401
+ @_dispatch(137, state=_dvistate.inpage, args=('s4', 's4'))
402
+ def _put_rule(self, a, b):
403
+ self._put_rule_real(a, b)
404
+
405
+ def _put_rule_real(self, a, b):
406
+ if a > 0 and b > 0:
407
+ self.boxes.append(Box(self.h, self.v, a, b))
408
+
409
+ @_dispatch(138)
410
+ def _nop(self, _):
411
+ pass
412
+
413
+ @_dispatch(139, state=_dvistate.outer, args=('s4',)*11)
414
+ def _bop(self, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, p):
415
+ self.state = _dvistate.inpage
416
+ self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
417
+ self.stack = []
418
+ self.text = [] # list of Text objects
419
+ self.boxes = [] # list of Box objects
420
+
421
+ @_dispatch(140, state=_dvistate.inpage)
422
+ def _eop(self, _):
423
+ self.state = _dvistate.outer
424
+ del self.h, self.v, self.w, self.x, self.y, self.z, self.stack
425
+
426
+ @_dispatch(141, state=_dvistate.inpage)
427
+ def _push(self, _):
428
+ self.stack.append((self.h, self.v, self.w, self.x, self.y, self.z))
429
+
430
+ @_dispatch(142, state=_dvistate.inpage)
431
+ def _pop(self, _):
432
+ self.h, self.v, self.w, self.x, self.y, self.z = self.stack.pop()
433
+
434
+ @_dispatch(min=143, max=146, state=_dvistate.inpage, args=('slen1',))
435
+ def _right(self, b):
436
+ self.h += b
437
+
438
+ @_dispatch(min=147, max=151, state=_dvistate.inpage, args=('slen',))
439
+ def _right_w(self, new_w):
440
+ if new_w is not None:
441
+ self.w = new_w
442
+ self.h += self.w
443
+
444
+ @_dispatch(min=152, max=156, state=_dvistate.inpage, args=('slen',))
445
+ def _right_x(self, new_x):
446
+ if new_x is not None:
447
+ self.x = new_x
448
+ self.h += self.x
449
+
450
+ @_dispatch(min=157, max=160, state=_dvistate.inpage, args=('slen1',))
451
+ def _down(self, a):
452
+ self.v += a
453
+
454
+ @_dispatch(min=161, max=165, state=_dvistate.inpage, args=('slen',))
455
+ def _down_y(self, new_y):
456
+ if new_y is not None:
457
+ self.y = new_y
458
+ self.v += self.y
459
+
460
+ @_dispatch(min=166, max=170, state=_dvistate.inpage, args=('slen',))
461
+ def _down_z(self, new_z):
462
+ if new_z is not None:
463
+ self.z = new_z
464
+ self.v += self.z
465
+
466
+ @_dispatch(min=171, max=234, state=_dvistate.inpage)
467
+ def _fnt_num_immediate(self, k):
468
+ self.f = k
469
+
470
+ @_dispatch(min=235, max=238, state=_dvistate.inpage, args=('olen1',))
471
+ def _fnt_num(self, new_f):
472
+ self.f = new_f
473
+
474
+ @_dispatch(min=239, max=242, args=('ulen1',))
475
+ def _xxx(self, datalen):
476
+ special = self.file.read(datalen)
477
+ _log.debug(
478
+ 'Dvi._xxx: encountered special: %s',
479
+ ''.join([chr(ch) if 32 <= ch < 127 else '<%02x>' % ch
480
+ for ch in special]))
481
+
482
+ @_dispatch(min=243, max=246, args=('olen1', 'u4', 'u4', 'u4', 'u1', 'u1'))
483
+ def _fnt_def(self, k, c, s, d, a, l):
484
+ self._fnt_def_real(k, c, s, d, a, l)
485
+
486
+ def _fnt_def_real(self, k, c, s, d, a, l):
487
+ n = self.file.read(a + l)
488
+ fontname = n[-l:].decode('ascii')
489
+ tfm = _tfmfile(fontname)
490
+ if c != 0 and tfm.checksum != 0 and c != tfm.checksum:
491
+ raise ValueError('tfm checksum mismatch: %s' % n)
492
+ try:
493
+ vf = _vffile(fontname)
494
+ except FileNotFoundError:
495
+ vf = None
496
+ self.fonts[k] = DviFont(scale=s, tfm=tfm, texname=n, vf=vf)
497
+
498
+ @_dispatch(247, state=_dvistate.pre, args=('u1', 'u4', 'u4', 'u4', 'u1'))
499
+ def _pre(self, i, num, den, mag, k):
500
+ self.file.read(k) # comment in the dvi file
501
+ if i != 2:
502
+ raise ValueError("Unknown dvi format %d" % i)
503
+ if num != 25400000 or den != 7227 * 2**16:
504
+ raise ValueError("Nonstandard units in dvi file")
505
+ # meaning: TeX always uses those exact values, so it
506
+ # should be enough for us to support those
507
+ # (There are 72.27 pt to an inch so 7227 pt =
508
+ # 7227 * 2**16 sp to 100 in. The numerator is multiplied
509
+ # by 10^5 to get units of 10**-7 meters.)
510
+ if mag != 1000:
511
+ raise ValueError("Nonstandard magnification in dvi file")
512
+ # meaning: LaTeX seems to frown on setting \mag, so
513
+ # I think we can assume this is constant
514
+ self.state = _dvistate.outer
515
+
516
+ @_dispatch(248, state=_dvistate.outer)
517
+ def _post(self, _):
518
+ self.state = _dvistate.post_post
519
+ # TODO: actually read the postamble and finale?
520
+ # currently post_post just triggers closing the file
521
+
522
+ @_dispatch(249)
523
+ def _post_post(self, _):
524
+ raise NotImplementedError
525
+
526
+ @_dispatch(min=250, max=255)
527
+ def _malformed(self, offset):
528
+ raise ValueError(f"unknown command: byte {250 + offset}")
529
+
530
+
531
+ class DviFont:
532
+ """
533
+ Encapsulation of a font that a DVI file can refer to.
534
+
535
+ This class holds a font's texname and size, supports comparison,
536
+ and knows the widths of glyphs in the same units as the AFM file.
537
+ There are also internal attributes (for use by dviread.py) that
538
+ are *not* used for comparison.
539
+
540
+ The size is in Adobe points (converted from TeX points).
541
+
542
+ Parameters
543
+ ----------
544
+ scale : float
545
+ Factor by which the font is scaled from its natural size.
546
+ tfm : Tfm
547
+ TeX font metrics for this font
548
+ texname : bytes
549
+ Name of the font as used internally by TeX and friends, as an ASCII
550
+ bytestring. This is usually very different from any external font
551
+ names; `PsfontsMap` can be used to find the external name of the font.
552
+ vf : Vf
553
+ A TeX "virtual font" file, or None if this font is not virtual.
554
+
555
+ Attributes
556
+ ----------
557
+ texname : bytes
558
+ size : float
559
+ Size of the font in Adobe points, converted from the slightly
560
+ smaller TeX points.
561
+ widths : list
562
+ Widths of glyphs in glyph-space units, typically 1/1000ths of
563
+ the point size.
564
+
565
+ """
566
+ __slots__ = ('texname', 'size', 'widths', '_scale', '_vf', '_tfm')
567
+
568
+ def __init__(self, scale, tfm, texname, vf):
569
+ _api.check_isinstance(bytes, texname=texname)
570
+ self._scale = scale
571
+ self._tfm = tfm
572
+ self.texname = texname
573
+ self._vf = vf
574
+ self.size = scale * (72.0 / (72.27 * 2**16))
575
+ try:
576
+ nchars = max(tfm.width) + 1
577
+ except ValueError:
578
+ nchars = 0
579
+ self.widths = [(1000*tfm.width.get(char, 0)) >> 20
580
+ for char in range(nchars)]
581
+
582
+ def __eq__(self, other):
583
+ return (type(self) is type(other)
584
+ and self.texname == other.texname and self.size == other.size)
585
+
586
+ def __ne__(self, other):
587
+ return not self.__eq__(other)
588
+
589
+ def __repr__(self):
590
+ return f"<{type(self).__name__}: {self.texname}>"
591
+
592
+ def _width_of(self, char):
593
+ """Width of char in dvi units."""
594
+ width = self._tfm.width.get(char, None)
595
+ if width is not None:
596
+ return _mul2012(width, self._scale)
597
+ _log.debug('No width for char %d in font %s.', char, self.texname)
598
+ return 0
599
+
600
+ def _height_depth_of(self, char):
601
+ """Height and depth of char in dvi units."""
602
+ result = []
603
+ for metric, name in ((self._tfm.height, "height"),
604
+ (self._tfm.depth, "depth")):
605
+ value = metric.get(char, None)
606
+ if value is None:
607
+ _log.debug('No %s for char %d in font %s',
608
+ name, char, self.texname)
609
+ result.append(0)
610
+ else:
611
+ result.append(_mul2012(value, self._scale))
612
+ # cmsyXX (symbols font) glyph 0 ("minus") has a nonzero descent
613
+ # so that TeX aligns equations properly
614
+ # (https://tex.stackexchange.com/q/526103/)
615
+ # but we actually care about the rasterization depth to align
616
+ # the dvipng-generated images.
617
+ if re.match(br'^cmsy\d+$', self.texname) and char == 0:
618
+ result[-1] = 0
619
+ return result
620
+
621
+
622
+ class Vf(Dvi):
623
+ r"""
624
+ A virtual font (\*.vf file) containing subroutines for dvi files.
625
+
626
+ Parameters
627
+ ----------
628
+ filename : str or path-like
629
+
630
+ Notes
631
+ -----
632
+ The virtual font format is a derivative of dvi:
633
+ http://mirrors.ctan.org/info/knuth/virtual-fonts
634
+ This class reuses some of the machinery of `Dvi`
635
+ but replaces the `_read` loop and dispatch mechanism.
636
+
637
+ Examples
638
+ --------
639
+ ::
640
+
641
+ vf = Vf(filename)
642
+ glyph = vf[code]
643
+ glyph.text, glyph.boxes, glyph.width
644
+ """
645
+
646
+ def __init__(self, filename):
647
+ super().__init__(filename, 0)
648
+ try:
649
+ self._first_font = None
650
+ self._chars = {}
651
+ self._read()
652
+ finally:
653
+ self.close()
654
+
655
+ def __getitem__(self, code):
656
+ return self._chars[code]
657
+
658
+ def _read(self):
659
+ """
660
+ Read one page from the file. Return True if successful,
661
+ False if there were no more pages.
662
+ """
663
+ packet_char, packet_ends = None, None
664
+ packet_len, packet_width = None, None
665
+ while True:
666
+ byte = self.file.read(1)[0]
667
+ # If we are in a packet, execute the dvi instructions
668
+ if self.state is _dvistate.inpage:
669
+ byte_at = self.file.tell()-1
670
+ if byte_at == packet_ends:
671
+ self._finalize_packet(packet_char, packet_width)
672
+ packet_len, packet_char, packet_width = None, None, None
673
+ # fall through to out-of-packet code
674
+ elif byte_at > packet_ends:
675
+ raise ValueError("Packet length mismatch in vf file")
676
+ else:
677
+ if byte in (139, 140) or byte >= 243:
678
+ raise ValueError(
679
+ "Inappropriate opcode %d in vf file" % byte)
680
+ Dvi._dtable[byte](self, byte)
681
+ continue
682
+
683
+ # We are outside a packet
684
+ if byte < 242: # a short packet (length given by byte)
685
+ packet_len = byte
686
+ packet_char, packet_width = self._arg(1), self._arg(3)
687
+ packet_ends = self._init_packet(byte)
688
+ self.state = _dvistate.inpage
689
+ elif byte == 242: # a long packet
690
+ packet_len, packet_char, packet_width = \
691
+ [self._arg(x) for x in (4, 4, 4)]
692
+ self._init_packet(packet_len)
693
+ elif 243 <= byte <= 246:
694
+ k = self._arg(byte - 242, byte == 246)
695
+ c, s, d, a, l = [self._arg(x) for x in (4, 4, 4, 1, 1)]
696
+ self._fnt_def_real(k, c, s, d, a, l)
697
+ if self._first_font is None:
698
+ self._first_font = k
699
+ elif byte == 247: # preamble
700
+ i, k = self._arg(1), self._arg(1)
701
+ x = self.file.read(k)
702
+ cs, ds = self._arg(4), self._arg(4)
703
+ self._pre(i, x, cs, ds)
704
+ elif byte == 248: # postamble (just some number of 248s)
705
+ break
706
+ else:
707
+ raise ValueError("Unknown vf opcode %d" % byte)
708
+
709
+ def _init_packet(self, pl):
710
+ if self.state != _dvistate.outer:
711
+ raise ValueError("Misplaced packet in vf file")
712
+ self.h, self.v, self.w, self.x, self.y, self.z = 0, 0, 0, 0, 0, 0
713
+ self.stack, self.text, self.boxes = [], [], []
714
+ self.f = self._first_font
715
+ return self.file.tell() + pl
716
+
717
+ def _finalize_packet(self, packet_char, packet_width):
718
+ self._chars[packet_char] = Page(
719
+ text=self.text, boxes=self.boxes, width=packet_width,
720
+ height=None, descent=None)
721
+ self.state = _dvistate.outer
722
+
723
+ def _pre(self, i, x, cs, ds):
724
+ if self.state is not _dvistate.pre:
725
+ raise ValueError("pre command in middle of vf file")
726
+ if i != 202:
727
+ raise ValueError("Unknown vf format %d" % i)
728
+ if len(x):
729
+ _log.debug('vf file comment: %s', x)
730
+ self.state = _dvistate.outer
731
+ # cs = checksum, ds = design size
732
+
733
+
734
+ def _mul2012(num1, num2):
735
+ """Multiply two numbers in 20.12 fixed point format."""
736
+ # Separated into a function because >> has surprising precedence
737
+ return (num1*num2) >> 20
738
+
739
+
740
+ class Tfm:
741
+ """
742
+ A TeX Font Metric file.
743
+
744
+ This implementation covers only the bare minimum needed by the Dvi class.
745
+
746
+ Parameters
747
+ ----------
748
+ filename : str or path-like
749
+
750
+ Attributes
751
+ ----------
752
+ checksum : int
753
+ Used for verifying against the dvi file.
754
+ design_size : int
755
+ Design size of the font (unknown units)
756
+ width, height, depth : dict
757
+ Dimensions of each character, need to be scaled by the factor
758
+ specified in the dvi file. These are dicts because indexing may
759
+ not start from 0.
760
+ """
761
+ __slots__ = ('checksum', 'design_size', 'width', 'height', 'depth')
762
+
763
+ def __init__(self, filename):
764
+ _log.debug('opening tfm file %s', filename)
765
+ with open(filename, 'rb') as file:
766
+ header1 = file.read(24)
767
+ lh, bc, ec, nw, nh, nd = struct.unpack('!6H', header1[2:14])
768
+ _log.debug('lh=%d, bc=%d, ec=%d, nw=%d, nh=%d, nd=%d',
769
+ lh, bc, ec, nw, nh, nd)
770
+ header2 = file.read(4*lh)
771
+ self.checksum, self.design_size = struct.unpack('!2I', header2[:8])
772
+ # there is also encoding information etc.
773
+ char_info = file.read(4*(ec-bc+1))
774
+ widths = struct.unpack(f'!{nw}i', file.read(4*nw))
775
+ heights = struct.unpack(f'!{nh}i', file.read(4*nh))
776
+ depths = struct.unpack(f'!{nd}i', file.read(4*nd))
777
+ self.width, self.height, self.depth = {}, {}, {}
778
+ for idx, char in enumerate(range(bc, ec+1)):
779
+ byte0 = char_info[4*idx]
780
+ byte1 = char_info[4*idx+1]
781
+ self.width[char] = widths[byte0]
782
+ self.height[char] = heights[byte1 >> 4]
783
+ self.depth[char] = depths[byte1 & 0xf]
784
+
785
+
786
+ PsFont = namedtuple('PsFont', 'texname psname effects encoding filename')
787
+
788
+
789
+ class PsfontsMap:
790
+ """
791
+ A psfonts.map formatted file, mapping TeX fonts to PS fonts.
792
+
793
+ Parameters
794
+ ----------
795
+ filename : str or path-like
796
+
797
+ Notes
798
+ -----
799
+ For historical reasons, TeX knows many Type-1 fonts by different
800
+ names than the outside world. (For one thing, the names have to
801
+ fit in eight characters.) Also, TeX's native fonts are not Type-1
802
+ but Metafont, which is nontrivial to convert to PostScript except
803
+ as a bitmap. While high-quality conversions to Type-1 format exist
804
+ and are shipped with modern TeX distributions, we need to know
805
+ which Type-1 fonts are the counterparts of which native fonts. For
806
+ these reasons a mapping is needed from internal font names to font
807
+ file names.
808
+
809
+ A texmf tree typically includes mapping files called e.g.
810
+ :file:`psfonts.map`, :file:`pdftex.map`, or :file:`dvipdfm.map`.
811
+ The file :file:`psfonts.map` is used by :program:`dvips`,
812
+ :file:`pdftex.map` by :program:`pdfTeX`, and :file:`dvipdfm.map`
813
+ by :program:`dvipdfm`. :file:`psfonts.map` might avoid embedding
814
+ the 35 PostScript fonts (i.e., have no filename for them, as in
815
+ the Times-Bold example above), while the pdf-related files perhaps
816
+ only avoid the "Base 14" pdf fonts. But the user may have
817
+ configured these files differently.
818
+
819
+ Examples
820
+ --------
821
+ >>> map = PsfontsMap(find_tex_file('pdftex.map'))
822
+ >>> entry = map[b'ptmbo8r']
823
+ >>> entry.texname
824
+ b'ptmbo8r'
825
+ >>> entry.psname
826
+ b'Times-Bold'
827
+ >>> entry.encoding
828
+ '/usr/local/texlive/2008/texmf-dist/fonts/enc/dvips/base/8r.enc'
829
+ >>> entry.effects
830
+ {'slant': 0.16700000000000001}
831
+ >>> entry.filename
832
+ """
833
+ __slots__ = ('_filename', '_unparsed', '_parsed')
834
+
835
+ # Create a filename -> PsfontsMap cache, so that calling
836
+ # `PsfontsMap(filename)` with the same filename a second time immediately
837
+ # returns the same object.
838
+ @lru_cache
839
+ def __new__(cls, filename):
840
+ self = object.__new__(cls)
841
+ self._filename = os.fsdecode(filename)
842
+ # Some TeX distributions have enormous pdftex.map files which would
843
+ # take hundreds of milliseconds to parse, but it is easy enough to just
844
+ # store the unparsed lines (keyed by the first word, which is the
845
+ # texname) and parse them on-demand.
846
+ with open(filename, 'rb') as file:
847
+ self._unparsed = {}
848
+ for line in file:
849
+ tfmname = line.split(b' ', 1)[0]
850
+ self._unparsed.setdefault(tfmname, []).append(line)
851
+ self._parsed = {}
852
+ return self
853
+
854
+ def __getitem__(self, texname):
855
+ assert isinstance(texname, bytes)
856
+ if texname in self._unparsed:
857
+ for line in self._unparsed.pop(texname):
858
+ if self._parse_and_cache_line(line):
859
+ break
860
+ try:
861
+ return self._parsed[texname]
862
+ except KeyError:
863
+ raise LookupError(
864
+ f"An associated PostScript font (required by Matplotlib) "
865
+ f"could not be found for TeX font {texname.decode('ascii')!r} "
866
+ f"in {self._filename!r}; this problem can often be solved by "
867
+ f"installing a suitable PostScript font package in your TeX "
868
+ f"package manager") from None
869
+
870
+ def _parse_and_cache_line(self, line):
871
+ """
872
+ Parse a line in the font mapping file.
873
+
874
+ The format is (partially) documented at
875
+ http://mirrors.ctan.org/systems/doc/pdftex/manual/pdftex-a.pdf
876
+ https://tug.org/texinfohtml/dvips.html#psfonts_002emap
877
+ Each line can have the following fields:
878
+
879
+ - tfmname (first, only required field),
880
+ - psname (defaults to tfmname, must come immediately after tfmname if
881
+ present),
882
+ - fontflags (integer, must come immediately after psname if present,
883
+ ignored by us),
884
+ - special (SlantFont and ExtendFont, only field that is double-quoted),
885
+ - fontfile, encodingfile (optional, prefixed by <, <<, or <[; << always
886
+ precedes a font, <[ always precedes an encoding, < can precede either
887
+ but then an encoding file must have extension .enc; < and << also
888
+ request different font subsetting behaviors but we ignore that; < can
889
+ be separated from the filename by whitespace).
890
+
891
+ special, fontfile, and encodingfile can appear in any order.
892
+ """
893
+ # If the map file specifies multiple encodings for a font, we
894
+ # follow pdfTeX in choosing the last one specified. Such
895
+ # entries are probably mistakes but they have occurred.
896
+ # https://tex.stackexchange.com/q/10826/
897
+
898
+ if not line or line.startswith((b" ", b"%", b"*", b";", b"#")):
899
+ return
900
+ tfmname = basename = special = encodingfile = fontfile = None
901
+ is_subsetted = is_t1 = is_truetype = False
902
+ matches = re.finditer(br'"([^"]*)(?:"|$)|(\S+)', line)
903
+ for match in matches:
904
+ quoted, unquoted = match.groups()
905
+ if unquoted:
906
+ if unquoted.startswith(b"<<"): # font
907
+ fontfile = unquoted[2:]
908
+ elif unquoted.startswith(b"<["): # encoding
909
+ encodingfile = unquoted[2:]
910
+ elif unquoted.startswith(b"<"): # font or encoding
911
+ word = (
912
+ # <foo => foo
913
+ unquoted[1:]
914
+ # < by itself => read the next word
915
+ or next(filter(None, next(matches).groups())))
916
+ if word.endswith(b".enc"):
917
+ encodingfile = word
918
+ else:
919
+ fontfile = word
920
+ is_subsetted = True
921
+ elif tfmname is None:
922
+ tfmname = unquoted
923
+ elif basename is None:
924
+ basename = unquoted
925
+ elif quoted:
926
+ special = quoted
927
+ effects = {}
928
+ if special:
929
+ words = reversed(special.split())
930
+ for word in words:
931
+ if word == b"SlantFont":
932
+ effects["slant"] = float(next(words))
933
+ elif word == b"ExtendFont":
934
+ effects["extend"] = float(next(words))
935
+
936
+ # Verify some properties of the line that would cause it to be ignored
937
+ # otherwise.
938
+ if fontfile is not None:
939
+ if fontfile.endswith((b".ttf", b".ttc")):
940
+ is_truetype = True
941
+ elif not fontfile.endswith(b".otf"):
942
+ is_t1 = True
943
+ elif basename is not None:
944
+ is_t1 = True
945
+ if is_truetype and is_subsetted and encodingfile is None:
946
+ return
947
+ if not is_t1 and ("slant" in effects or "extend" in effects):
948
+ return
949
+ if abs(effects.get("slant", 0)) > 1:
950
+ return
951
+ if abs(effects.get("extend", 0)) > 2:
952
+ return
953
+
954
+ if basename is None:
955
+ basename = tfmname
956
+ if encodingfile is not None:
957
+ encodingfile = find_tex_file(encodingfile)
958
+ if fontfile is not None:
959
+ fontfile = find_tex_file(fontfile)
960
+ self._parsed[tfmname] = PsFont(
961
+ texname=tfmname, psname=basename, effects=effects,
962
+ encoding=encodingfile, filename=fontfile)
963
+ return True
964
+
965
+
966
+ def _parse_enc(path):
967
+ r"""
968
+ Parse a \*.enc file referenced from a psfonts.map style file.
969
+
970
+ The format supported by this function is a tiny subset of PostScript.
971
+
972
+ Parameters
973
+ ----------
974
+ path : `os.PathLike`
975
+
976
+ Returns
977
+ -------
978
+ list
979
+ The nth entry of the list is the PostScript glyph name of the nth
980
+ glyph.
981
+ """
982
+ no_comments = re.sub("%.*", "", Path(path).read_text(encoding="ascii"))
983
+ array = re.search(r"(?s)\[(.*)\]", no_comments).group(1)
984
+ lines = [line for line in array.split() if line]
985
+ if all(line.startswith("/") for line in lines):
986
+ return [line[1:] for line in lines]
987
+ else:
988
+ raise ValueError(f"Failed to parse {path} as Postscript encoding")
989
+
990
+
991
+ class _LuatexKpsewhich:
992
+ @lru_cache # A singleton.
993
+ def __new__(cls):
994
+ self = object.__new__(cls)
995
+ self._proc = self._new_proc()
996
+ return self
997
+
998
+ def _new_proc(self):
999
+ return subprocess.Popen(
1000
+ ["luatex", "--luaonly",
1001
+ str(cbook._get_data_path("kpsewhich.lua"))],
1002
+ stdin=subprocess.PIPE, stdout=subprocess.PIPE)
1003
+
1004
+ def search(self, filename):
1005
+ if self._proc.poll() is not None: # Dead, restart it.
1006
+ self._proc = self._new_proc()
1007
+ self._proc.stdin.write(os.fsencode(filename) + b"\n")
1008
+ self._proc.stdin.flush()
1009
+ out = self._proc.stdout.readline().rstrip()
1010
+ return None if out == b"nil" else os.fsdecode(out)
1011
+
1012
+
1013
+ @lru_cache
1014
+ def find_tex_file(filename):
1015
+ """
1016
+ Find a file in the texmf tree using kpathsea_.
1017
+
1018
+ The kpathsea library, provided by most existing TeX distributions, both
1019
+ on Unix-like systems and on Windows (MikTeX), is invoked via a long-lived
1020
+ luatex process if luatex is installed, or via kpsewhich otherwise.
1021
+
1022
+ .. _kpathsea: https://www.tug.org/kpathsea/
1023
+
1024
+ Parameters
1025
+ ----------
1026
+ filename : str or path-like
1027
+
1028
+ Raises
1029
+ ------
1030
+ FileNotFoundError
1031
+ If the file is not found.
1032
+ """
1033
+
1034
+ # we expect these to always be ascii encoded, but use utf-8
1035
+ # out of caution
1036
+ if isinstance(filename, bytes):
1037
+ filename = filename.decode('utf-8', errors='replace')
1038
+
1039
+ try:
1040
+ lk = _LuatexKpsewhich()
1041
+ except FileNotFoundError:
1042
+ lk = None # Fallback to directly calling kpsewhich, as below.
1043
+
1044
+ if lk:
1045
+ path = lk.search(filename)
1046
+ else:
1047
+ if sys.platform == 'win32':
1048
+ # On Windows only, kpathsea can use utf-8 for cmd args and output.
1049
+ # The `command_line_encoding` environment variable is set to force
1050
+ # it to always use utf-8 encoding. See Matplotlib issue #11848.
1051
+ kwargs = {'env': {**os.environ, 'command_line_encoding': 'utf-8'},
1052
+ 'encoding': 'utf-8'}
1053
+ else: # On POSIX, run through the equivalent of os.fsdecode().
1054
+ kwargs = {'encoding': sys.getfilesystemencoding(),
1055
+ 'errors': 'surrogateescape'}
1056
+
1057
+ try:
1058
+ path = (cbook._check_and_log_subprocess(['kpsewhich', filename],
1059
+ _log, **kwargs)
1060
+ .rstrip('\n'))
1061
+ except (FileNotFoundError, RuntimeError):
1062
+ path = None
1063
+
1064
+ if path:
1065
+ return path
1066
+ else:
1067
+ raise FileNotFoundError(
1068
+ f"Matplotlib's TeX implementation searched for a file named "
1069
+ f"{filename!r} in your texmf tree, but could not find it")
1070
+
1071
+
1072
+ @lru_cache
1073
+ def _fontfile(cls, suffix, texname):
1074
+ return cls(find_tex_file(texname + suffix))
1075
+
1076
+
1077
+ _tfmfile = partial(_fontfile, Tfm, ".tfm")
1078
+ _vffile = partial(_fontfile, Vf, ".vf")
1079
+
1080
+
1081
+ if __name__ == '__main__':
1082
+ from argparse import ArgumentParser
1083
+ import itertools
1084
+
1085
+ parser = ArgumentParser()
1086
+ parser.add_argument("filename")
1087
+ parser.add_argument("dpi", nargs="?", type=float, default=None)
1088
+ args = parser.parse_args()
1089
+ with Dvi(args.filename, args.dpi) as dvi:
1090
+ fontmap = PsfontsMap(find_tex_file('pdftex.map'))
1091
+ for page in dvi:
1092
+ print(f"=== new page === "
1093
+ f"(w: {page.width}, h: {page.height}, d: {page.descent})")
1094
+ for font, group in itertools.groupby(
1095
+ page.text, lambda text: text.font):
1096
+ print(f"font: {font.texname.decode('latin-1')!r}\t"
1097
+ f"scale: {font._scale / 2 ** 20}")
1098
+ print("x", "y", "glyph", "chr", "w", "(glyphs)", sep="\t")
1099
+ for text in group:
1100
+ print(text.x, text.y, text.glyph,
1101
+ chr(text.glyph) if chr(text.glyph).isprintable()
1102
+ else ".",
1103
+ text.width, sep="\t")
1104
+ if page.boxes:
1105
+ print("x", "y", "h", "w", "", "(boxes)", sep="\t")
1106
+ for box in page.boxes:
1107
+ print(box.x, box.y, box.height, box.width, sep="\t")
llava_next/lib/python3.10/site-packages/matplotlib/dviread.pyi ADDED
@@ -0,0 +1,90 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+ import io
3
+ import os
4
+ from enum import Enum
5
+ from collections.abc import Generator
6
+
7
+ from typing import NamedTuple
8
+
9
+ class _dvistate(Enum):
10
+ pre: int
11
+ outer: int
12
+ inpage: int
13
+ post_post: int
14
+ finale: int
15
+
16
+ class Page(NamedTuple):
17
+ text: list[Text]
18
+ boxes: list[Box]
19
+ height: int
20
+ width: int
21
+ descent: int
22
+
23
+ class Box(NamedTuple):
24
+ x: int
25
+ y: int
26
+ height: int
27
+ width: int
28
+
29
+ class Text(NamedTuple):
30
+ x: int
31
+ y: int
32
+ font: DviFont
33
+ glyph: int
34
+ width: int
35
+ @property
36
+ def font_path(self) -> Path: ...
37
+ @property
38
+ def font_size(self) -> float: ...
39
+ @property
40
+ def font_effects(self) -> dict[str, float]: ...
41
+ @property
42
+ def glyph_name_or_index(self) -> int | str: ...
43
+
44
+ class Dvi:
45
+ file: io.BufferedReader
46
+ dpi: float | None
47
+ fonts: dict[int, DviFont]
48
+ state: _dvistate
49
+ def __init__(self, filename: str | os.PathLike, dpi: float | None) -> None: ...
50
+ # Replace return with Self when py3.9 is dropped
51
+ def __enter__(self) -> Dvi: ...
52
+ def __exit__(self, etype, evalue, etrace) -> None: ...
53
+ def __iter__(self) -> Generator[Page, None, None]: ...
54
+ def close(self) -> None: ...
55
+
56
+ class DviFont:
57
+ texname: bytes
58
+ size: float
59
+ widths: list[int]
60
+ def __init__(
61
+ self, scale: float, tfm: Tfm, texname: bytes, vf: Vf | None
62
+ ) -> None: ...
63
+ def __eq__(self, other: object) -> bool: ...
64
+ def __ne__(self, other: object) -> bool: ...
65
+
66
+ class Vf(Dvi):
67
+ def __init__(self, filename: str | os.PathLike) -> None: ...
68
+ def __getitem__(self, code: int) -> Page: ...
69
+
70
+ class Tfm:
71
+ checksum: int
72
+ design_size: int
73
+ width: dict[int, int]
74
+ height: dict[int, int]
75
+ depth: dict[int, int]
76
+ def __init__(self, filename: str | os.PathLike) -> None: ...
77
+
78
+ class PsFont(NamedTuple):
79
+ texname: bytes
80
+ psname: bytes
81
+ effects: dict[str, float]
82
+ encoding: None | bytes
83
+ filename: str
84
+
85
+ class PsfontsMap:
86
+ # Replace return with Self when py3.9 is dropped
87
+ def __new__(cls, filename: str | os.PathLike) -> PsfontsMap: ...
88
+ def __getitem__(self, texname: bytes) -> PsFont: ...
89
+
90
+ def find_tex_file(filename: str | os.PathLike) -> str: ...
llava_next/lib/python3.10/site-packages/matplotlib/gridspec.py ADDED
@@ -0,0 +1,788 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ :mod:`~matplotlib.gridspec` contains classes that help to layout multiple
3
+ `~.axes.Axes` in a grid-like pattern within a figure.
4
+
5
+ The `GridSpec` specifies the overall grid structure. Individual cells within
6
+ the grid are referenced by `SubplotSpec`\s.
7
+
8
+ Often, users need not access this module directly, and can use higher-level
9
+ methods like `~.pyplot.subplots`, `~.pyplot.subplot_mosaic` and
10
+ `~.Figure.subfigures`. See the tutorial :ref:`arranging_axes` for a guide.
11
+ """
12
+
13
+ import copy
14
+ import logging
15
+ from numbers import Integral
16
+
17
+ import numpy as np
18
+
19
+ import matplotlib as mpl
20
+ from matplotlib import _api, _pylab_helpers, _tight_layout
21
+ from matplotlib.transforms import Bbox
22
+
23
+ _log = logging.getLogger(__name__)
24
+
25
+
26
+ class GridSpecBase:
27
+ """
28
+ A base class of GridSpec that specifies the geometry of the grid
29
+ that a subplot will be placed.
30
+ """
31
+
32
+ def __init__(self, nrows, ncols, height_ratios=None, width_ratios=None):
33
+ """
34
+ Parameters
35
+ ----------
36
+ nrows, ncols : int
37
+ The number of rows and columns of the grid.
38
+ width_ratios : array-like of length *ncols*, optional
39
+ Defines the relative widths of the columns. Each column gets a
40
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
41
+ If not given, all columns will have the same width.
42
+ height_ratios : array-like of length *nrows*, optional
43
+ Defines the relative heights of the rows. Each row gets a
44
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
45
+ If not given, all rows will have the same height.
46
+ """
47
+ if not isinstance(nrows, Integral) or nrows <= 0:
48
+ raise ValueError(
49
+ f"Number of rows must be a positive integer, not {nrows!r}")
50
+ if not isinstance(ncols, Integral) or ncols <= 0:
51
+ raise ValueError(
52
+ f"Number of columns must be a positive integer, not {ncols!r}")
53
+ self._nrows, self._ncols = nrows, ncols
54
+ self.set_height_ratios(height_ratios)
55
+ self.set_width_ratios(width_ratios)
56
+
57
+ def __repr__(self):
58
+ height_arg = (f', height_ratios={self._row_height_ratios!r}'
59
+ if len(set(self._row_height_ratios)) != 1 else '')
60
+ width_arg = (f', width_ratios={self._col_width_ratios!r}'
61
+ if len(set(self._col_width_ratios)) != 1 else '')
62
+ return '{clsname}({nrows}, {ncols}{optionals})'.format(
63
+ clsname=self.__class__.__name__,
64
+ nrows=self._nrows,
65
+ ncols=self._ncols,
66
+ optionals=height_arg + width_arg,
67
+ )
68
+
69
+ nrows = property(lambda self: self._nrows,
70
+ doc="The number of rows in the grid.")
71
+ ncols = property(lambda self: self._ncols,
72
+ doc="The number of columns in the grid.")
73
+
74
+ def get_geometry(self):
75
+ """
76
+ Return a tuple containing the number of rows and columns in the grid.
77
+ """
78
+ return self._nrows, self._ncols
79
+
80
+ def get_subplot_params(self, figure=None):
81
+ # Must be implemented in subclasses
82
+ pass
83
+
84
+ def new_subplotspec(self, loc, rowspan=1, colspan=1):
85
+ """
86
+ Create and return a `.SubplotSpec` instance.
87
+
88
+ Parameters
89
+ ----------
90
+ loc : (int, int)
91
+ The position of the subplot in the grid as
92
+ ``(row_index, column_index)``.
93
+ rowspan, colspan : int, default: 1
94
+ The number of rows and columns the subplot should span in the grid.
95
+ """
96
+ loc1, loc2 = loc
97
+ subplotspec = self[loc1:loc1+rowspan, loc2:loc2+colspan]
98
+ return subplotspec
99
+
100
+ def set_width_ratios(self, width_ratios):
101
+ """
102
+ Set the relative widths of the columns.
103
+
104
+ *width_ratios* must be of length *ncols*. Each column gets a relative
105
+ width of ``width_ratios[i] / sum(width_ratios)``.
106
+ """
107
+ if width_ratios is None:
108
+ width_ratios = [1] * self._ncols
109
+ elif len(width_ratios) != self._ncols:
110
+ raise ValueError('Expected the given number of width ratios to '
111
+ 'match the number of columns of the grid')
112
+ self._col_width_ratios = width_ratios
113
+
114
+ def get_width_ratios(self):
115
+ """
116
+ Return the width ratios.
117
+
118
+ This is *None* if no width ratios have been set explicitly.
119
+ """
120
+ return self._col_width_ratios
121
+
122
+ def set_height_ratios(self, height_ratios):
123
+ """
124
+ Set the relative heights of the rows.
125
+
126
+ *height_ratios* must be of length *nrows*. Each row gets a relative
127
+ height of ``height_ratios[i] / sum(height_ratios)``.
128
+ """
129
+ if height_ratios is None:
130
+ height_ratios = [1] * self._nrows
131
+ elif len(height_ratios) != self._nrows:
132
+ raise ValueError('Expected the given number of height ratios to '
133
+ 'match the number of rows of the grid')
134
+ self._row_height_ratios = height_ratios
135
+
136
+ def get_height_ratios(self):
137
+ """
138
+ Return the height ratios.
139
+
140
+ This is *None* if no height ratios have been set explicitly.
141
+ """
142
+ return self._row_height_ratios
143
+
144
+ def get_grid_positions(self, fig):
145
+ """
146
+ Return the positions of the grid cells in figure coordinates.
147
+
148
+ Parameters
149
+ ----------
150
+ fig : `~matplotlib.figure.Figure`
151
+ The figure the grid should be applied to. The subplot parameters
152
+ (margins and spacing between subplots) are taken from *fig*.
153
+
154
+ Returns
155
+ -------
156
+ bottoms, tops, lefts, rights : array
157
+ The bottom, top, left, right positions of the grid cells in
158
+ figure coordinates.
159
+ """
160
+ nrows, ncols = self.get_geometry()
161
+ subplot_params = self.get_subplot_params(fig)
162
+ left = subplot_params.left
163
+ right = subplot_params.right
164
+ bottom = subplot_params.bottom
165
+ top = subplot_params.top
166
+ wspace = subplot_params.wspace
167
+ hspace = subplot_params.hspace
168
+ tot_width = right - left
169
+ tot_height = top - bottom
170
+
171
+ # calculate accumulated heights of columns
172
+ cell_h = tot_height / (nrows + hspace*(nrows-1))
173
+ sep_h = hspace * cell_h
174
+ norm = cell_h * nrows / sum(self._row_height_ratios)
175
+ cell_heights = [r * norm for r in self._row_height_ratios]
176
+ sep_heights = [0] + ([sep_h] * (nrows-1))
177
+ cell_hs = np.cumsum(np.column_stack([sep_heights, cell_heights]).flat)
178
+
179
+ # calculate accumulated widths of rows
180
+ cell_w = tot_width / (ncols + wspace*(ncols-1))
181
+ sep_w = wspace * cell_w
182
+ norm = cell_w * ncols / sum(self._col_width_ratios)
183
+ cell_widths = [r * norm for r in self._col_width_ratios]
184
+ sep_widths = [0] + ([sep_w] * (ncols-1))
185
+ cell_ws = np.cumsum(np.column_stack([sep_widths, cell_widths]).flat)
186
+
187
+ fig_tops, fig_bottoms = (top - cell_hs).reshape((-1, 2)).T
188
+ fig_lefts, fig_rights = (left + cell_ws).reshape((-1, 2)).T
189
+ return fig_bottoms, fig_tops, fig_lefts, fig_rights
190
+
191
+ @staticmethod
192
+ def _check_gridspec_exists(figure, nrows, ncols):
193
+ """
194
+ Check if the figure already has a gridspec with these dimensions,
195
+ or create a new one
196
+ """
197
+ for ax in figure.get_axes():
198
+ gs = ax.get_gridspec()
199
+ if gs is not None:
200
+ if hasattr(gs, 'get_topmost_subplotspec'):
201
+ # This is needed for colorbar gridspec layouts.
202
+ # This is probably OK because this whole logic tree
203
+ # is for when the user is doing simple things with the
204
+ # add_subplot command. For complicated layouts
205
+ # like subgridspecs the proper gridspec is passed in...
206
+ gs = gs.get_topmost_subplotspec().get_gridspec()
207
+ if gs.get_geometry() == (nrows, ncols):
208
+ return gs
209
+ # else gridspec not found:
210
+ return GridSpec(nrows, ncols, figure=figure)
211
+
212
+ def __getitem__(self, key):
213
+ """Create and return a `.SubplotSpec` instance."""
214
+ nrows, ncols = self.get_geometry()
215
+
216
+ def _normalize(key, size, axis): # Includes last index.
217
+ orig_key = key
218
+ if isinstance(key, slice):
219
+ start, stop, _ = key.indices(size)
220
+ if stop > start:
221
+ return start, stop - 1
222
+ raise IndexError("GridSpec slice would result in no space "
223
+ "allocated for subplot")
224
+ else:
225
+ if key < 0:
226
+ key = key + size
227
+ if 0 <= key < size:
228
+ return key, key
229
+ elif axis is not None:
230
+ raise IndexError(f"index {orig_key} is out of bounds for "
231
+ f"axis {axis} with size {size}")
232
+ else: # flat index
233
+ raise IndexError(f"index {orig_key} is out of bounds for "
234
+ f"GridSpec with size {size}")
235
+
236
+ if isinstance(key, tuple):
237
+ try:
238
+ k1, k2 = key
239
+ except ValueError as err:
240
+ raise ValueError("Unrecognized subplot spec") from err
241
+ num1, num2 = np.ravel_multi_index(
242
+ [_normalize(k1, nrows, 0), _normalize(k2, ncols, 1)],
243
+ (nrows, ncols))
244
+ else: # Single key
245
+ num1, num2 = _normalize(key, nrows * ncols, None)
246
+
247
+ return SubplotSpec(self, num1, num2)
248
+
249
+ def subplots(self, *, sharex=False, sharey=False, squeeze=True,
250
+ subplot_kw=None):
251
+ """
252
+ Add all subplots specified by this `GridSpec` to its parent figure.
253
+
254
+ See `.Figure.subplots` for detailed documentation.
255
+ """
256
+
257
+ figure = self.figure
258
+
259
+ if figure is None:
260
+ raise ValueError("GridSpec.subplots() only works for GridSpecs "
261
+ "created with a parent figure")
262
+
263
+ if not isinstance(sharex, str):
264
+ sharex = "all" if sharex else "none"
265
+ if not isinstance(sharey, str):
266
+ sharey = "all" if sharey else "none"
267
+
268
+ _api.check_in_list(["all", "row", "col", "none", False, True],
269
+ sharex=sharex, sharey=sharey)
270
+ if subplot_kw is None:
271
+ subplot_kw = {}
272
+ # don't mutate kwargs passed by user...
273
+ subplot_kw = subplot_kw.copy()
274
+
275
+ # Create array to hold all Axes.
276
+ axarr = np.empty((self._nrows, self._ncols), dtype=object)
277
+ for row in range(self._nrows):
278
+ for col in range(self._ncols):
279
+ shared_with = {"none": None, "all": axarr[0, 0],
280
+ "row": axarr[row, 0], "col": axarr[0, col]}
281
+ subplot_kw["sharex"] = shared_with[sharex]
282
+ subplot_kw["sharey"] = shared_with[sharey]
283
+ axarr[row, col] = figure.add_subplot(
284
+ self[row, col], **subplot_kw)
285
+
286
+ # turn off redundant tick labeling
287
+ if sharex in ["col", "all"]:
288
+ for ax in axarr.flat:
289
+ ax._label_outer_xaxis(skip_non_rectangular_axes=True)
290
+ if sharey in ["row", "all"]:
291
+ for ax in axarr.flat:
292
+ ax._label_outer_yaxis(skip_non_rectangular_axes=True)
293
+
294
+ if squeeze:
295
+ # Discarding unneeded dimensions that equal 1. If we only have one
296
+ # subplot, just return it instead of a 1-element array.
297
+ return axarr.item() if axarr.size == 1 else axarr.squeeze()
298
+ else:
299
+ # Returned axis array will be always 2-d, even if nrows=ncols=1.
300
+ return axarr
301
+
302
+
303
+ class GridSpec(GridSpecBase):
304
+ """
305
+ A grid layout to place subplots within a figure.
306
+
307
+ The location of the grid cells is determined in a similar way to
308
+ `.SubplotParams` using *left*, *right*, *top*, *bottom*, *wspace*
309
+ and *hspace*.
310
+
311
+ Indexing a GridSpec instance returns a `.SubplotSpec`.
312
+ """
313
+ def __init__(self, nrows, ncols, figure=None,
314
+ left=None, bottom=None, right=None, top=None,
315
+ wspace=None, hspace=None,
316
+ width_ratios=None, height_ratios=None):
317
+ """
318
+ Parameters
319
+ ----------
320
+ nrows, ncols : int
321
+ The number of rows and columns of the grid.
322
+
323
+ figure : `.Figure`, optional
324
+ Only used for constrained layout to create a proper layoutgrid.
325
+
326
+ left, right, top, bottom : float, optional
327
+ Extent of the subplots as a fraction of figure width or height.
328
+ Left cannot be larger than right, and bottom cannot be larger than
329
+ top. If not given, the values will be inferred from a figure or
330
+ rcParams at draw time. See also `GridSpec.get_subplot_params`.
331
+
332
+ wspace : float, optional
333
+ The amount of width reserved for space between subplots,
334
+ expressed as a fraction of the average axis width.
335
+ If not given, the values will be inferred from a figure or
336
+ rcParams when necessary. See also `GridSpec.get_subplot_params`.
337
+
338
+ hspace : float, optional
339
+ The amount of height reserved for space between subplots,
340
+ expressed as a fraction of the average axis height.
341
+ If not given, the values will be inferred from a figure or
342
+ rcParams when necessary. See also `GridSpec.get_subplot_params`.
343
+
344
+ width_ratios : array-like of length *ncols*, optional
345
+ Defines the relative widths of the columns. Each column gets a
346
+ relative width of ``width_ratios[i] / sum(width_ratios)``.
347
+ If not given, all columns will have the same width.
348
+
349
+ height_ratios : array-like of length *nrows*, optional
350
+ Defines the relative heights of the rows. Each row gets a
351
+ relative height of ``height_ratios[i] / sum(height_ratios)``.
352
+ If not given, all rows will have the same height.
353
+
354
+ """
355
+ self.left = left
356
+ self.bottom = bottom
357
+ self.right = right
358
+ self.top = top
359
+ self.wspace = wspace
360
+ self.hspace = hspace
361
+ self.figure = figure
362
+
363
+ super().__init__(nrows, ncols,
364
+ width_ratios=width_ratios,
365
+ height_ratios=height_ratios)
366
+
367
+ _AllowedKeys = ["left", "bottom", "right", "top", "wspace", "hspace"]
368
+
369
+ def update(self, **kwargs):
370
+ """
371
+ Update the subplot parameters of the grid.
372
+
373
+ Parameters that are not explicitly given are not changed. Setting a
374
+ parameter to *None* resets it to :rc:`figure.subplot.*`.
375
+
376
+ Parameters
377
+ ----------
378
+ left, right, top, bottom : float or None, optional
379
+ Extent of the subplots as a fraction of figure width or height.
380
+ wspace, hspace : float, optional
381
+ Spacing between the subplots as a fraction of the average subplot
382
+ width / height.
383
+ """
384
+ for k, v in kwargs.items():
385
+ if k in self._AllowedKeys:
386
+ setattr(self, k, v)
387
+ else:
388
+ raise AttributeError(f"{k} is an unknown keyword")
389
+ for figmanager in _pylab_helpers.Gcf.figs.values():
390
+ for ax in figmanager.canvas.figure.axes:
391
+ if ax.get_subplotspec() is not None:
392
+ ss = ax.get_subplotspec().get_topmost_subplotspec()
393
+ if ss.get_gridspec() == self:
394
+ ax._set_position(
395
+ ax.get_subplotspec().get_position(ax.figure))
396
+
397
+ def get_subplot_params(self, figure=None):
398
+ """
399
+ Return the `.SubplotParams` for the GridSpec.
400
+
401
+ In order of precedence the values are taken from
402
+
403
+ - non-*None* attributes of the GridSpec
404
+ - the provided *figure*
405
+ - :rc:`figure.subplot.*`
406
+
407
+ Note that the ``figure`` attribute of the GridSpec is always ignored.
408
+ """
409
+ if figure is None:
410
+ kw = {k: mpl.rcParams["figure.subplot."+k]
411
+ for k in self._AllowedKeys}
412
+ subplotpars = SubplotParams(**kw)
413
+ else:
414
+ subplotpars = copy.copy(figure.subplotpars)
415
+
416
+ subplotpars.update(**{k: getattr(self, k) for k in self._AllowedKeys})
417
+
418
+ return subplotpars
419
+
420
+ def locally_modified_subplot_params(self):
421
+ """
422
+ Return a list of the names of the subplot parameters explicitly set
423
+ in the GridSpec.
424
+
425
+ This is a subset of the attributes of `.SubplotParams`.
426
+ """
427
+ return [k for k in self._AllowedKeys if getattr(self, k)]
428
+
429
+ def tight_layout(self, figure, renderer=None,
430
+ pad=1.08, h_pad=None, w_pad=None, rect=None):
431
+ """
432
+ Adjust subplot parameters to give specified padding.
433
+
434
+ Parameters
435
+ ----------
436
+ figure : `.Figure`
437
+ The figure.
438
+ renderer : `.RendererBase` subclass, optional
439
+ The renderer to be used.
440
+ pad : float
441
+ Padding between the figure edge and the edges of subplots, as a
442
+ fraction of the font-size.
443
+ h_pad, w_pad : float, optional
444
+ Padding (height/width) between edges of adjacent subplots.
445
+ Defaults to *pad*.
446
+ rect : tuple (left, bottom, right, top), default: None
447
+ (left, bottom, right, top) rectangle in normalized figure
448
+ coordinates that the whole subplots area (including labels) will
449
+ fit into. Default (None) is the whole figure.
450
+ """
451
+ if renderer is None:
452
+ renderer = figure._get_renderer()
453
+ kwargs = _tight_layout.get_tight_layout_figure(
454
+ figure, figure.axes,
455
+ _tight_layout.get_subplotspec_list(figure.axes, grid_spec=self),
456
+ renderer, pad=pad, h_pad=h_pad, w_pad=w_pad, rect=rect)
457
+ if kwargs:
458
+ self.update(**kwargs)
459
+
460
+
461
+ class GridSpecFromSubplotSpec(GridSpecBase):
462
+ """
463
+ GridSpec whose subplot layout parameters are inherited from the
464
+ location specified by a given SubplotSpec.
465
+ """
466
+ def __init__(self, nrows, ncols,
467
+ subplot_spec,
468
+ wspace=None, hspace=None,
469
+ height_ratios=None, width_ratios=None):
470
+ """
471
+ Parameters
472
+ ----------
473
+ nrows, ncols : int
474
+ Number of rows and number of columns of the grid.
475
+ subplot_spec : SubplotSpec
476
+ Spec from which the layout parameters are inherited.
477
+ wspace, hspace : float, optional
478
+ See `GridSpec` for more details. If not specified default values
479
+ (from the figure or rcParams) are used.
480
+ height_ratios : array-like of length *nrows*, optional
481
+ See `GridSpecBase` for details.
482
+ width_ratios : array-like of length *ncols*, optional
483
+ See `GridSpecBase` for details.
484
+ """
485
+ self._wspace = wspace
486
+ self._hspace = hspace
487
+ if isinstance(subplot_spec, SubplotSpec):
488
+ self._subplot_spec = subplot_spec
489
+ else:
490
+ raise TypeError(
491
+ "subplot_spec must be type SubplotSpec, "
492
+ "usually from GridSpec, or axes.get_subplotspec.")
493
+ self.figure = self._subplot_spec.get_gridspec().figure
494
+ super().__init__(nrows, ncols,
495
+ width_ratios=width_ratios,
496
+ height_ratios=height_ratios)
497
+
498
+ def get_subplot_params(self, figure=None):
499
+ """Return a dictionary of subplot layout parameters."""
500
+ hspace = (self._hspace if self._hspace is not None
501
+ else figure.subplotpars.hspace if figure is not None
502
+ else mpl.rcParams["figure.subplot.hspace"])
503
+ wspace = (self._wspace if self._wspace is not None
504
+ else figure.subplotpars.wspace if figure is not None
505
+ else mpl.rcParams["figure.subplot.wspace"])
506
+
507
+ figbox = self._subplot_spec.get_position(figure)
508
+ left, bottom, right, top = figbox.extents
509
+
510
+ return SubplotParams(left=left, right=right,
511
+ bottom=bottom, top=top,
512
+ wspace=wspace, hspace=hspace)
513
+
514
+ def get_topmost_subplotspec(self):
515
+ """
516
+ Return the topmost `.SubplotSpec` instance associated with the subplot.
517
+ """
518
+ return self._subplot_spec.get_topmost_subplotspec()
519
+
520
+
521
+ class SubplotSpec:
522
+ """
523
+ The location of a subplot in a `GridSpec`.
524
+
525
+ .. note::
526
+
527
+ Likely, you will never instantiate a `SubplotSpec` yourself. Instead,
528
+ you will typically obtain one from a `GridSpec` using item-access.
529
+
530
+ Parameters
531
+ ----------
532
+ gridspec : `~matplotlib.gridspec.GridSpec`
533
+ The GridSpec, which the subplot is referencing.
534
+ num1, num2 : int
535
+ The subplot will occupy the *num1*-th cell of the given
536
+ *gridspec*. If *num2* is provided, the subplot will span between
537
+ *num1*-th cell and *num2*-th cell **inclusive**.
538
+
539
+ The index starts from 0.
540
+ """
541
+ def __init__(self, gridspec, num1, num2=None):
542
+ self._gridspec = gridspec
543
+ self.num1 = num1
544
+ self.num2 = num2
545
+
546
+ def __repr__(self):
547
+ return (f"{self.get_gridspec()}["
548
+ f"{self.rowspan.start}:{self.rowspan.stop}, "
549
+ f"{self.colspan.start}:{self.colspan.stop}]")
550
+
551
+ @staticmethod
552
+ def _from_subplot_args(figure, args):
553
+ """
554
+ Construct a `.SubplotSpec` from a parent `.Figure` and either
555
+
556
+ - a `.SubplotSpec` -- returned as is;
557
+ - one or three numbers -- a MATLAB-style subplot specifier.
558
+ """
559
+ if len(args) == 1:
560
+ arg, = args
561
+ if isinstance(arg, SubplotSpec):
562
+ return arg
563
+ elif not isinstance(arg, Integral):
564
+ raise ValueError(
565
+ f"Single argument to subplot must be a three-digit "
566
+ f"integer, not {arg!r}")
567
+ try:
568
+ rows, cols, num = map(int, str(arg))
569
+ except ValueError:
570
+ raise ValueError(
571
+ f"Single argument to subplot must be a three-digit "
572
+ f"integer, not {arg!r}") from None
573
+ elif len(args) == 3:
574
+ rows, cols, num = args
575
+ else:
576
+ raise _api.nargs_error("subplot", takes="1 or 3", given=len(args))
577
+
578
+ gs = GridSpec._check_gridspec_exists(figure, rows, cols)
579
+ if gs is None:
580
+ gs = GridSpec(rows, cols, figure=figure)
581
+ if isinstance(num, tuple) and len(num) == 2:
582
+ if not all(isinstance(n, Integral) for n in num):
583
+ raise ValueError(
584
+ f"Subplot specifier tuple must contain integers, not {num}"
585
+ )
586
+ i, j = num
587
+ else:
588
+ if not isinstance(num, Integral) or num < 1 or num > rows*cols:
589
+ raise ValueError(
590
+ f"num must be an integer with 1 <= num <= {rows*cols}, "
591
+ f"not {num!r}"
592
+ )
593
+ i = j = num
594
+ return gs[i-1:j]
595
+
596
+ # num2 is a property only to handle the case where it is None and someone
597
+ # mutates num1.
598
+
599
+ @property
600
+ def num2(self):
601
+ return self.num1 if self._num2 is None else self._num2
602
+
603
+ @num2.setter
604
+ def num2(self, value):
605
+ self._num2 = value
606
+
607
+ def get_gridspec(self):
608
+ return self._gridspec
609
+
610
+ def get_geometry(self):
611
+ """
612
+ Return the subplot geometry as tuple ``(n_rows, n_cols, start, stop)``.
613
+
614
+ The indices *start* and *stop* define the range of the subplot within
615
+ the `GridSpec`. *stop* is inclusive (i.e. for a single cell
616
+ ``start == stop``).
617
+ """
618
+ rows, cols = self.get_gridspec().get_geometry()
619
+ return rows, cols, self.num1, self.num2
620
+
621
+ @property
622
+ def rowspan(self):
623
+ """The rows spanned by this subplot, as a `range` object."""
624
+ ncols = self.get_gridspec().ncols
625
+ return range(self.num1 // ncols, self.num2 // ncols + 1)
626
+
627
+ @property
628
+ def colspan(self):
629
+ """The columns spanned by this subplot, as a `range` object."""
630
+ ncols = self.get_gridspec().ncols
631
+ # We explicitly support num2 referring to a column on num1's *left*, so
632
+ # we must sort the column indices here so that the range makes sense.
633
+ c1, c2 = sorted([self.num1 % ncols, self.num2 % ncols])
634
+ return range(c1, c2 + 1)
635
+
636
+ def is_first_row(self):
637
+ return self.rowspan.start == 0
638
+
639
+ def is_last_row(self):
640
+ return self.rowspan.stop == self.get_gridspec().nrows
641
+
642
+ def is_first_col(self):
643
+ return self.colspan.start == 0
644
+
645
+ def is_last_col(self):
646
+ return self.colspan.stop == self.get_gridspec().ncols
647
+
648
+ def get_position(self, figure):
649
+ """
650
+ Update the subplot position from ``figure.subplotpars``.
651
+ """
652
+ gridspec = self.get_gridspec()
653
+ nrows, ncols = gridspec.get_geometry()
654
+ rows, cols = np.unravel_index([self.num1, self.num2], (nrows, ncols))
655
+ fig_bottoms, fig_tops, fig_lefts, fig_rights = \
656
+ gridspec.get_grid_positions(figure)
657
+
658
+ fig_bottom = fig_bottoms[rows].min()
659
+ fig_top = fig_tops[rows].max()
660
+ fig_left = fig_lefts[cols].min()
661
+ fig_right = fig_rights[cols].max()
662
+ return Bbox.from_extents(fig_left, fig_bottom, fig_right, fig_top)
663
+
664
+ def get_topmost_subplotspec(self):
665
+ """
666
+ Return the topmost `SubplotSpec` instance associated with the subplot.
667
+ """
668
+ gridspec = self.get_gridspec()
669
+ if hasattr(gridspec, "get_topmost_subplotspec"):
670
+ return gridspec.get_topmost_subplotspec()
671
+ else:
672
+ return self
673
+
674
+ def __eq__(self, other):
675
+ """
676
+ Two SubplotSpecs are considered equal if they refer to the same
677
+ position(s) in the same `GridSpec`.
678
+ """
679
+ # other may not even have the attributes we are checking.
680
+ return ((self._gridspec, self.num1, self.num2)
681
+ == (getattr(other, "_gridspec", object()),
682
+ getattr(other, "num1", object()),
683
+ getattr(other, "num2", object())))
684
+
685
+ def __hash__(self):
686
+ return hash((self._gridspec, self.num1, self.num2))
687
+
688
+ def subgridspec(self, nrows, ncols, **kwargs):
689
+ """
690
+ Create a GridSpec within this subplot.
691
+
692
+ The created `.GridSpecFromSubplotSpec` will have this `SubplotSpec` as
693
+ a parent.
694
+
695
+ Parameters
696
+ ----------
697
+ nrows : int
698
+ Number of rows in grid.
699
+
700
+ ncols : int
701
+ Number of columns in grid.
702
+
703
+ Returns
704
+ -------
705
+ `.GridSpecFromSubplotSpec`
706
+
707
+ Other Parameters
708
+ ----------------
709
+ **kwargs
710
+ All other parameters are passed to `.GridSpecFromSubplotSpec`.
711
+
712
+ See Also
713
+ --------
714
+ matplotlib.pyplot.subplots
715
+
716
+ Examples
717
+ --------
718
+ Adding three subplots in the space occupied by a single subplot::
719
+
720
+ fig = plt.figure()
721
+ gs0 = fig.add_gridspec(3, 1)
722
+ ax1 = fig.add_subplot(gs0[0])
723
+ ax2 = fig.add_subplot(gs0[1])
724
+ gssub = gs0[2].subgridspec(1, 3)
725
+ for i in range(3):
726
+ fig.add_subplot(gssub[0, i])
727
+ """
728
+ return GridSpecFromSubplotSpec(nrows, ncols, self, **kwargs)
729
+
730
+
731
+ class SubplotParams:
732
+ """
733
+ Parameters defining the positioning of a subplots grid in a figure.
734
+ """
735
+
736
+ def __init__(self, left=None, bottom=None, right=None, top=None,
737
+ wspace=None, hspace=None):
738
+ """
739
+ Defaults are given by :rc:`figure.subplot.[name]`.
740
+
741
+ Parameters
742
+ ----------
743
+ left : float
744
+ The position of the left edge of the subplots,
745
+ as a fraction of the figure width.
746
+ right : float
747
+ The position of the right edge of the subplots,
748
+ as a fraction of the figure width.
749
+ bottom : float
750
+ The position of the bottom edge of the subplots,
751
+ as a fraction of the figure height.
752
+ top : float
753
+ The position of the top edge of the subplots,
754
+ as a fraction of the figure height.
755
+ wspace : float
756
+ The width of the padding between subplots,
757
+ as a fraction of the average Axes width.
758
+ hspace : float
759
+ The height of the padding between subplots,
760
+ as a fraction of the average Axes height.
761
+ """
762
+ for key in ["left", "bottom", "right", "top", "wspace", "hspace"]:
763
+ setattr(self, key, mpl.rcParams[f"figure.subplot.{key}"])
764
+ self.update(left, bottom, right, top, wspace, hspace)
765
+
766
+ def update(self, left=None, bottom=None, right=None, top=None,
767
+ wspace=None, hspace=None):
768
+ """
769
+ Update the dimensions of the passed parameters. *None* means unchanged.
770
+ """
771
+ if ((left if left is not None else self.left)
772
+ >= (right if right is not None else self.right)):
773
+ raise ValueError('left cannot be >= right')
774
+ if ((bottom if bottom is not None else self.bottom)
775
+ >= (top if top is not None else self.top)):
776
+ raise ValueError('bottom cannot be >= top')
777
+ if left is not None:
778
+ self.left = left
779
+ if right is not None:
780
+ self.right = right
781
+ if bottom is not None:
782
+ self.bottom = bottom
783
+ if top is not None:
784
+ self.top = top
785
+ if wspace is not None:
786
+ self.wspace = wspace
787
+ if hspace is not None:
788
+ self.hspace = hspace
llava_next/lib/python3.10/site-packages/matplotlib/legend.py ADDED
@@ -0,0 +1,1385 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The legend module defines the Legend class, which is responsible for
3
+ drawing legends associated with Axes and/or figures.
4
+
5
+ .. important::
6
+
7
+ It is unlikely that you would ever create a Legend instance manually.
8
+ Most users would normally create a legend via the `~.Axes.legend`
9
+ function. For more details on legends there is also a :ref:`legend guide
10
+ <legend_guide>`.
11
+
12
+ The `Legend` class is a container of legend handles and legend texts.
13
+
14
+ The legend handler map specifies how to create legend handles from artists
15
+ (lines, patches, etc.) in the Axes or figures. Default legend handlers are
16
+ defined in the :mod:`~matplotlib.legend_handler` module. While not all artist
17
+ types are covered by the default legend handlers, custom legend handlers can be
18
+ defined to support arbitrary objects.
19
+
20
+ See the :ref`<legend_guide>` for more
21
+ information.
22
+ """
23
+
24
+ import itertools
25
+ import logging
26
+ import numbers
27
+ import time
28
+
29
+ import numpy as np
30
+
31
+ import matplotlib as mpl
32
+ from matplotlib import _api, _docstring, cbook, colors, offsetbox
33
+ from matplotlib.artist import Artist, allow_rasterization
34
+ from matplotlib.cbook import silent_list
35
+ from matplotlib.font_manager import FontProperties
36
+ from matplotlib.lines import Line2D
37
+ from matplotlib.patches import (Patch, Rectangle, Shadow, FancyBboxPatch,
38
+ StepPatch)
39
+ from matplotlib.collections import (
40
+ Collection, CircleCollection, LineCollection, PathCollection,
41
+ PolyCollection, RegularPolyCollection)
42
+ from matplotlib.text import Text
43
+ from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
44
+ from matplotlib.transforms import BboxTransformTo, BboxTransformFrom
45
+ from matplotlib.offsetbox import (
46
+ AnchoredOffsetbox, DraggableOffsetBox,
47
+ HPacker, VPacker,
48
+ DrawingArea, TextArea,
49
+ )
50
+ from matplotlib.container import ErrorbarContainer, BarContainer, StemContainer
51
+ from . import legend_handler
52
+
53
+
54
+ class DraggableLegend(DraggableOffsetBox):
55
+ def __init__(self, legend, use_blit=False, update="loc"):
56
+ """
57
+ Wrapper around a `.Legend` to support mouse dragging.
58
+
59
+ Parameters
60
+ ----------
61
+ legend : `.Legend`
62
+ The `.Legend` instance to wrap.
63
+ use_blit : bool, optional
64
+ Use blitting for faster image composition. For details see
65
+ :ref:`func-animation`.
66
+ update : {'loc', 'bbox'}, optional
67
+ If "loc", update the *loc* parameter of the legend upon finalizing.
68
+ If "bbox", update the *bbox_to_anchor* parameter.
69
+ """
70
+ self.legend = legend
71
+
72
+ _api.check_in_list(["loc", "bbox"], update=update)
73
+ self._update = update
74
+
75
+ super().__init__(legend, legend._legend_box, use_blit=use_blit)
76
+
77
+ def finalize_offset(self):
78
+ if self._update == "loc":
79
+ self._update_loc(self.get_loc_in_canvas())
80
+ elif self._update == "bbox":
81
+ self._update_bbox_to_anchor(self.get_loc_in_canvas())
82
+
83
+ def _update_loc(self, loc_in_canvas):
84
+ bbox = self.legend.get_bbox_to_anchor()
85
+ # if bbox has zero width or height, the transformation is
86
+ # ill-defined. Fall back to the default bbox_to_anchor.
87
+ if bbox.width == 0 or bbox.height == 0:
88
+ self.legend.set_bbox_to_anchor(None)
89
+ bbox = self.legend.get_bbox_to_anchor()
90
+ _bbox_transform = BboxTransformFrom(bbox)
91
+ self.legend._loc = tuple(_bbox_transform.transform(loc_in_canvas))
92
+
93
+ def _update_bbox_to_anchor(self, loc_in_canvas):
94
+ loc_in_bbox = self.legend.axes.transAxes.transform(loc_in_canvas)
95
+ self.legend.set_bbox_to_anchor(loc_in_bbox)
96
+
97
+
98
+ _legend_kw_doc_base = """
99
+ bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
100
+ Box that is used to position the legend in conjunction with *loc*.
101
+ Defaults to `axes.bbox` (if called as a method to `.Axes.legend`) or
102
+ `figure.bbox` (if `.Figure.legend`). This argument allows arbitrary
103
+ placement of the legend.
104
+
105
+ Bbox coordinates are interpreted in the coordinate system given by
106
+ *bbox_transform*, with the default transform
107
+ Axes or Figure coordinates, depending on which ``legend`` is called.
108
+
109
+ If a 4-tuple or `.BboxBase` is given, then it specifies the bbox
110
+ ``(x, y, width, height)`` that the legend is placed in.
111
+ To put the legend in the best location in the bottom right
112
+ quadrant of the Axes (or figure)::
113
+
114
+ loc='best', bbox_to_anchor=(0.5, 0., 0.5, 0.5)
115
+
116
+ A 2-tuple ``(x, y)`` places the corner of the legend specified by *loc* at
117
+ x, y. For example, to put the legend's upper right-hand corner in the
118
+ center of the Axes (or figure) the following keywords can be used::
119
+
120
+ loc='upper right', bbox_to_anchor=(0.5, 0.5)
121
+
122
+ ncols : int, default: 1
123
+ The number of columns that the legend has.
124
+
125
+ For backward compatibility, the spelling *ncol* is also supported
126
+ but it is discouraged. If both are given, *ncols* takes precedence.
127
+
128
+ prop : None or `~matplotlib.font_manager.FontProperties` or dict
129
+ The font properties of the legend. If None (default), the current
130
+ :data:`matplotlib.rcParams` will be used.
131
+
132
+ fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
133
+ 'x-large', 'xx-large'}
134
+ The font size of the legend. If the value is numeric the size will be the
135
+ absolute font size in points. String values are relative to the current
136
+ default font size. This argument is only used if *prop* is not specified.
137
+
138
+ labelcolor : str or list, default: :rc:`legend.labelcolor`
139
+ The color of the text in the legend. Either a valid color string
140
+ (for example, 'red'), or a list of color strings. The labelcolor can
141
+ also be made to match the color of the line or marker using 'linecolor',
142
+ 'markerfacecolor' (or 'mfc'), or 'markeredgecolor' (or 'mec').
143
+
144
+ Labelcolor can be set globally using :rc:`legend.labelcolor`. If None,
145
+ use :rc:`text.color`.
146
+
147
+ numpoints : int, default: :rc:`legend.numpoints`
148
+ The number of marker points in the legend when creating a legend
149
+ entry for a `.Line2D` (line).
150
+
151
+ scatterpoints : int, default: :rc:`legend.scatterpoints`
152
+ The number of marker points in the legend when creating
153
+ a legend entry for a `.PathCollection` (scatter plot).
154
+
155
+ scatteryoffsets : iterable of floats, default: ``[0.375, 0.5, 0.3125]``
156
+ The vertical offset (relative to the font size) for the markers
157
+ created for a scatter plot legend entry. 0.0 is at the base the
158
+ legend text, and 1.0 is at the top. To draw all markers at the
159
+ same height, set to ``[0.5]``.
160
+
161
+ markerscale : float, default: :rc:`legend.markerscale`
162
+ The relative size of legend markers compared to the originally drawn ones.
163
+
164
+ markerfirst : bool, default: True
165
+ If *True*, legend marker is placed to the left of the legend label.
166
+ If *False*, legend marker is placed to the right of the legend label.
167
+
168
+ reverse : bool, default: False
169
+ If *True*, the legend labels are displayed in reverse order from the input.
170
+ If *False*, the legend labels are displayed in the same order as the input.
171
+
172
+ .. versionadded:: 3.7
173
+
174
+ frameon : bool, default: :rc:`legend.frameon`
175
+ Whether the legend should be drawn on a patch (frame).
176
+
177
+ fancybox : bool, default: :rc:`legend.fancybox`
178
+ Whether round edges should be enabled around the `.FancyBboxPatch` which
179
+ makes up the legend's background.
180
+
181
+ shadow : None, bool or dict, default: :rc:`legend.shadow`
182
+ Whether to draw a shadow behind the legend.
183
+ The shadow can be configured using `.Patch` keywords.
184
+ Customization via :rc:`legend.shadow` is currently not supported.
185
+
186
+ framealpha : float, default: :rc:`legend.framealpha`
187
+ The alpha transparency of the legend's background.
188
+ If *shadow* is activated and *framealpha* is ``None``, the default value is
189
+ ignored.
190
+
191
+ facecolor : "inherit" or color, default: :rc:`legend.facecolor`
192
+ The legend's background color.
193
+ If ``"inherit"``, use :rc:`axes.facecolor`.
194
+
195
+ edgecolor : "inherit" or color, default: :rc:`legend.edgecolor`
196
+ The legend's background patch edge color.
197
+ If ``"inherit"``, use :rc:`axes.edgecolor`.
198
+
199
+ mode : {"expand", None}
200
+ If *mode* is set to ``"expand"`` the legend will be horizontally
201
+ expanded to fill the Axes area (or *bbox_to_anchor* if defines
202
+ the legend's size).
203
+
204
+ bbox_transform : None or `~matplotlib.transforms.Transform`
205
+ The transform for the bounding box (*bbox_to_anchor*). For a value
206
+ of ``None`` (default) the Axes'
207
+ :data:`~matplotlib.axes.Axes.transAxes` transform will be used.
208
+
209
+ title : str or None
210
+ The legend's title. Default is no title (``None``).
211
+
212
+ title_fontproperties : None or `~matplotlib.font_manager.FontProperties` or dict
213
+ The font properties of the legend's title. If None (default), the
214
+ *title_fontsize* argument will be used if present; if *title_fontsize* is
215
+ also None, the current :rc:`legend.title_fontsize` will be used.
216
+
217
+ title_fontsize : int or {'xx-small', 'x-small', 'small', 'medium', 'large', \
218
+ 'x-large', 'xx-large'}, default: :rc:`legend.title_fontsize`
219
+ The font size of the legend's title.
220
+ Note: This cannot be combined with *title_fontproperties*. If you want
221
+ to set the fontsize alongside other font properties, use the *size*
222
+ parameter in *title_fontproperties*.
223
+
224
+ alignment : {'center', 'left', 'right'}, default: 'center'
225
+ The alignment of the legend title and the box of entries. The entries
226
+ are aligned as a single block, so that markers always lined up.
227
+
228
+ borderpad : float, default: :rc:`legend.borderpad`
229
+ The fractional whitespace inside the legend border, in font-size units.
230
+
231
+ labelspacing : float, default: :rc:`legend.labelspacing`
232
+ The vertical space between the legend entries, in font-size units.
233
+
234
+ handlelength : float, default: :rc:`legend.handlelength`
235
+ The length of the legend handles, in font-size units.
236
+
237
+ handleheight : float, default: :rc:`legend.handleheight`
238
+ The height of the legend handles, in font-size units.
239
+
240
+ handletextpad : float, default: :rc:`legend.handletextpad`
241
+ The pad between the legend handle and text, in font-size units.
242
+
243
+ borderaxespad : float, default: :rc:`legend.borderaxespad`
244
+ The pad between the Axes and legend border, in font-size units.
245
+
246
+ columnspacing : float, default: :rc:`legend.columnspacing`
247
+ The spacing between columns, in font-size units.
248
+
249
+ handler_map : dict or None
250
+ The custom dictionary mapping instances or types to a legend
251
+ handler. This *handler_map* updates the default handler map
252
+ found at `matplotlib.legend.Legend.get_legend_handler_map`.
253
+
254
+ draggable : bool, default: False
255
+ Whether the legend can be dragged with the mouse.
256
+ """
257
+
258
+ _loc_doc_base = """
259
+ loc : str or pair of floats, default: {default}
260
+ The location of the legend.
261
+
262
+ The strings ``'upper left'``, ``'upper right'``, ``'lower left'``,
263
+ ``'lower right'`` place the legend at the corresponding corner of the
264
+ {parent}.
265
+
266
+ The strings ``'upper center'``, ``'lower center'``, ``'center left'``,
267
+ ``'center right'`` place the legend at the center of the corresponding edge
268
+ of the {parent}.
269
+
270
+ The string ``'center'`` places the legend at the center of the {parent}.
271
+ {best}
272
+ The location can also be a 2-tuple giving the coordinates of the lower-left
273
+ corner of the legend in {parent} coordinates (in which case *bbox_to_anchor*
274
+ will be ignored).
275
+
276
+ For back-compatibility, ``'center right'`` (but no other location) can also
277
+ be spelled ``'right'``, and each "string" location can also be given as a
278
+ numeric value:
279
+
280
+ ================== =============
281
+ Location String Location Code
282
+ ================== =============
283
+ 'best' (Axes only) 0
284
+ 'upper right' 1
285
+ 'upper left' 2
286
+ 'lower left' 3
287
+ 'lower right' 4
288
+ 'right' 5
289
+ 'center left' 6
290
+ 'center right' 7
291
+ 'lower center' 8
292
+ 'upper center' 9
293
+ 'center' 10
294
+ ================== =============
295
+ {outside}"""
296
+
297
+ _loc_doc_best = """
298
+ The string ``'best'`` places the legend at the location, among the nine
299
+ locations defined so far, with the minimum overlap with other drawn
300
+ artists. This option can be quite slow for plots with large amounts of
301
+ data; your plotting speed may benefit from providing a specific location.
302
+ """
303
+
304
+ _legend_kw_axes_st = (
305
+ _loc_doc_base.format(parent='axes', default=':rc:`legend.loc`',
306
+ best=_loc_doc_best, outside='') +
307
+ _legend_kw_doc_base)
308
+ _docstring.interpd.update(_legend_kw_axes=_legend_kw_axes_st)
309
+
310
+ _outside_doc = """
311
+ If a figure is using the constrained layout manager, the string codes
312
+ of the *loc* keyword argument can get better layout behaviour using the
313
+ prefix 'outside'. There is ambiguity at the corners, so 'outside
314
+ upper right' will make space for the legend above the rest of the
315
+ axes in the layout, and 'outside right upper' will make space on the
316
+ right side of the layout. In addition to the values of *loc*
317
+ listed above, we have 'outside right upper', 'outside right lower',
318
+ 'outside left upper', and 'outside left lower'. See
319
+ :ref:`legend_guide` for more details.
320
+ """
321
+
322
+ _legend_kw_figure_st = (
323
+ _loc_doc_base.format(parent='figure', default="'upper right'",
324
+ best='', outside=_outside_doc) +
325
+ _legend_kw_doc_base)
326
+ _docstring.interpd.update(_legend_kw_figure=_legend_kw_figure_st)
327
+
328
+ _legend_kw_both_st = (
329
+ _loc_doc_base.format(parent='axes/figure',
330
+ default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
331
+ best=_loc_doc_best, outside=_outside_doc) +
332
+ _legend_kw_doc_base)
333
+ _docstring.interpd.update(_legend_kw_doc=_legend_kw_both_st)
334
+
335
+ _legend_kw_set_loc_st = (
336
+ _loc_doc_base.format(parent='axes/figure',
337
+ default=":rc:`legend.loc` for Axes, 'upper right' for Figure",
338
+ best=_loc_doc_best, outside=_outside_doc))
339
+ _docstring.interpd.update(_legend_kw_set_loc_doc=_legend_kw_set_loc_st)
340
+
341
+
342
+ class Legend(Artist):
343
+ """
344
+ Place a legend on the figure/axes.
345
+ """
346
+
347
+ # 'best' is only implemented for Axes legends
348
+ codes = {'best': 0, **AnchoredOffsetbox.codes}
349
+ zorder = 5
350
+
351
+ def __str__(self):
352
+ return "Legend"
353
+
354
+ @_docstring.dedent_interpd
355
+ def __init__(
356
+ self, parent, handles, labels,
357
+ *,
358
+ loc=None,
359
+ numpoints=None, # number of points in the legend line
360
+ markerscale=None, # relative size of legend markers vs. original
361
+ markerfirst=True, # left/right ordering of legend marker and label
362
+ reverse=False, # reverse ordering of legend marker and label
363
+ scatterpoints=None, # number of scatter points
364
+ scatteryoffsets=None,
365
+ prop=None, # properties for the legend texts
366
+ fontsize=None, # keyword to set font size directly
367
+ labelcolor=None, # keyword to set the text color
368
+
369
+ # spacing & pad defined as a fraction of the font-size
370
+ borderpad=None, # whitespace inside the legend border
371
+ labelspacing=None, # vertical space between the legend entries
372
+ handlelength=None, # length of the legend handles
373
+ handleheight=None, # height of the legend handles
374
+ handletextpad=None, # pad between the legend handle and text
375
+ borderaxespad=None, # pad between the Axes and legend border
376
+ columnspacing=None, # spacing between columns
377
+
378
+ ncols=1, # number of columns
379
+ mode=None, # horizontal distribution of columns: None or "expand"
380
+
381
+ fancybox=None, # True: fancy box, False: rounded box, None: rcParam
382
+ shadow=None,
383
+ title=None, # legend title
384
+ title_fontsize=None, # legend title font size
385
+ framealpha=None, # set frame alpha
386
+ edgecolor=None, # frame patch edgecolor
387
+ facecolor=None, # frame patch facecolor
388
+
389
+ bbox_to_anchor=None, # bbox to which the legend will be anchored
390
+ bbox_transform=None, # transform for the bbox
391
+ frameon=None, # draw frame
392
+ handler_map=None,
393
+ title_fontproperties=None, # properties for the legend title
394
+ alignment="center", # control the alignment within the legend box
395
+ ncol=1, # synonym for ncols (backward compatibility)
396
+ draggable=False # whether the legend can be dragged with the mouse
397
+ ):
398
+ """
399
+ Parameters
400
+ ----------
401
+ parent : `~matplotlib.axes.Axes` or `.Figure`
402
+ The artist that contains the legend.
403
+
404
+ handles : list of (`.Artist` or tuple of `.Artist`)
405
+ A list of Artists (lines, patches) to be added to the legend.
406
+
407
+ labels : list of str
408
+ A list of labels to show next to the artists. The length of handles
409
+ and labels should be the same. If they are not, they are truncated
410
+ to the length of the shorter list.
411
+
412
+ Other Parameters
413
+ ----------------
414
+ %(_legend_kw_doc)s
415
+
416
+ Attributes
417
+ ----------
418
+ legend_handles
419
+ List of `.Artist` objects added as legend entries.
420
+
421
+ .. versionadded:: 3.7
422
+ """
423
+ # local import only to avoid circularity
424
+ from matplotlib.axes import Axes
425
+ from matplotlib.figure import FigureBase
426
+
427
+ super().__init__()
428
+
429
+ if prop is None:
430
+ self.prop = FontProperties(size=mpl._val_or_rc(fontsize, "legend.fontsize"))
431
+ else:
432
+ self.prop = FontProperties._from_any(prop)
433
+ if isinstance(prop, dict) and "size" not in prop:
434
+ self.prop.set_size(mpl.rcParams["legend.fontsize"])
435
+
436
+ self._fontsize = self.prop.get_size_in_points()
437
+
438
+ self.texts = []
439
+ self.legend_handles = []
440
+ self._legend_title_box = None
441
+
442
+ #: A dictionary with the extra handler mappings for this Legend
443
+ #: instance.
444
+ self._custom_handler_map = handler_map
445
+
446
+ self.numpoints = mpl._val_or_rc(numpoints, 'legend.numpoints')
447
+ self.markerscale = mpl._val_or_rc(markerscale, 'legend.markerscale')
448
+ self.scatterpoints = mpl._val_or_rc(scatterpoints, 'legend.scatterpoints')
449
+ self.borderpad = mpl._val_or_rc(borderpad, 'legend.borderpad')
450
+ self.labelspacing = mpl._val_or_rc(labelspacing, 'legend.labelspacing')
451
+ self.handlelength = mpl._val_or_rc(handlelength, 'legend.handlelength')
452
+ self.handleheight = mpl._val_or_rc(handleheight, 'legend.handleheight')
453
+ self.handletextpad = mpl._val_or_rc(handletextpad, 'legend.handletextpad')
454
+ self.borderaxespad = mpl._val_or_rc(borderaxespad, 'legend.borderaxespad')
455
+ self.columnspacing = mpl._val_or_rc(columnspacing, 'legend.columnspacing')
456
+ self.shadow = mpl._val_or_rc(shadow, 'legend.shadow')
457
+ # trim handles and labels if illegal label...
458
+ _lab, _hand = [], []
459
+ for label, handle in zip(labels, handles):
460
+ if isinstance(label, str) and label.startswith('_'):
461
+ _api.warn_deprecated("3.8", message=(
462
+ "An artist whose label starts with an underscore was passed to "
463
+ "legend(); such artists will no longer be ignored in the future. "
464
+ "To suppress this warning, explicitly filter out such artists, "
465
+ "e.g. with `[art for art in artists if not "
466
+ "art.get_label().startswith('_')]`."))
467
+ else:
468
+ _lab.append(label)
469
+ _hand.append(handle)
470
+ labels, handles = _lab, _hand
471
+
472
+ if reverse:
473
+ labels.reverse()
474
+ handles.reverse()
475
+
476
+ if len(handles) < 2:
477
+ ncols = 1
478
+ self._ncols = ncols if ncols != 1 else ncol
479
+
480
+ if self.numpoints <= 0:
481
+ raise ValueError("numpoints must be > 0; it was %d" % numpoints)
482
+
483
+ # introduce y-offset for handles of the scatter plot
484
+ if scatteryoffsets is None:
485
+ self._scatteryoffsets = np.array([3. / 8., 4. / 8., 2.5 / 8.])
486
+ else:
487
+ self._scatteryoffsets = np.asarray(scatteryoffsets)
488
+ reps = self.scatterpoints // len(self._scatteryoffsets) + 1
489
+ self._scatteryoffsets = np.tile(self._scatteryoffsets,
490
+ reps)[:self.scatterpoints]
491
+
492
+ # _legend_box is a VPacker instance that contains all
493
+ # legend items and will be initialized from _init_legend_box()
494
+ # method.
495
+ self._legend_box = None
496
+
497
+ if isinstance(parent, Axes):
498
+ self.isaxes = True
499
+ self.axes = parent
500
+ self.set_figure(parent.figure)
501
+ elif isinstance(parent, FigureBase):
502
+ self.isaxes = False
503
+ self.set_figure(parent)
504
+ else:
505
+ raise TypeError(
506
+ "Legend needs either Axes or FigureBase as parent"
507
+ )
508
+ self.parent = parent
509
+
510
+ self._mode = mode
511
+ self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
512
+
513
+ # Figure out if self.shadow is valid
514
+ # If shadow was None, rcParams loads False
515
+ # So it shouldn't be None here
516
+
517
+ self._shadow_props = {'ox': 2, 'oy': -2} # default location offsets
518
+ if isinstance(self.shadow, dict):
519
+ self._shadow_props.update(self.shadow)
520
+ self.shadow = True
521
+ elif self.shadow in (0, 1, True, False):
522
+ self.shadow = bool(self.shadow)
523
+ else:
524
+ raise ValueError(
525
+ 'Legend shadow must be a dict or bool, not '
526
+ f'{self.shadow!r} of type {type(self.shadow)}.'
527
+ )
528
+
529
+ # We use FancyBboxPatch to draw a legend frame. The location
530
+ # and size of the box will be updated during the drawing time.
531
+
532
+ facecolor = mpl._val_or_rc(facecolor, "legend.facecolor")
533
+ if facecolor == 'inherit':
534
+ facecolor = mpl.rcParams["axes.facecolor"]
535
+
536
+ edgecolor = mpl._val_or_rc(edgecolor, "legend.edgecolor")
537
+ if edgecolor == 'inherit':
538
+ edgecolor = mpl.rcParams["axes.edgecolor"]
539
+
540
+ fancybox = mpl._val_or_rc(fancybox, "legend.fancybox")
541
+
542
+ self.legendPatch = FancyBboxPatch(
543
+ xy=(0, 0), width=1, height=1,
544
+ facecolor=facecolor, edgecolor=edgecolor,
545
+ # If shadow is used, default to alpha=1 (#8943).
546
+ alpha=(framealpha if framealpha is not None
547
+ else 1 if shadow
548
+ else mpl.rcParams["legend.framealpha"]),
549
+ # The width and height of the legendPatch will be set (in draw())
550
+ # to the length that includes the padding. Thus we set pad=0 here.
551
+ boxstyle=("round,pad=0,rounding_size=0.2" if fancybox
552
+ else "square,pad=0"),
553
+ mutation_scale=self._fontsize,
554
+ snap=True,
555
+ visible=mpl._val_or_rc(frameon, "legend.frameon")
556
+ )
557
+ self._set_artist_props(self.legendPatch)
558
+
559
+ _api.check_in_list(["center", "left", "right"], alignment=alignment)
560
+ self._alignment = alignment
561
+
562
+ # init with null renderer
563
+ self._init_legend_box(handles, labels, markerfirst)
564
+
565
+ # Set legend location
566
+ self.set_loc(loc)
567
+
568
+ # figure out title font properties:
569
+ if title_fontsize is not None and title_fontproperties is not None:
570
+ raise ValueError(
571
+ "title_fontsize and title_fontproperties can't be specified "
572
+ "at the same time. Only use one of them. ")
573
+ title_prop_fp = FontProperties._from_any(title_fontproperties)
574
+ if isinstance(title_fontproperties, dict):
575
+ if "size" not in title_fontproperties:
576
+ title_fontsize = mpl.rcParams["legend.title_fontsize"]
577
+ title_prop_fp.set_size(title_fontsize)
578
+ elif title_fontsize is not None:
579
+ title_prop_fp.set_size(title_fontsize)
580
+ elif not isinstance(title_fontproperties, FontProperties):
581
+ title_fontsize = mpl.rcParams["legend.title_fontsize"]
582
+ title_prop_fp.set_size(title_fontsize)
583
+
584
+ self.set_title(title, prop=title_prop_fp)
585
+
586
+ self._draggable = None
587
+ self.set_draggable(state=draggable)
588
+
589
+ # set the text color
590
+
591
+ color_getters = { # getter function depends on line or patch
592
+ 'linecolor': ['get_color', 'get_facecolor'],
593
+ 'markerfacecolor': ['get_markerfacecolor', 'get_facecolor'],
594
+ 'mfc': ['get_markerfacecolor', 'get_facecolor'],
595
+ 'markeredgecolor': ['get_markeredgecolor', 'get_edgecolor'],
596
+ 'mec': ['get_markeredgecolor', 'get_edgecolor'],
597
+ }
598
+ labelcolor = mpl._val_or_rc(labelcolor, 'legend.labelcolor')
599
+ if labelcolor is None:
600
+ labelcolor = mpl.rcParams['text.color']
601
+ if isinstance(labelcolor, str) and labelcolor in color_getters:
602
+ getter_names = color_getters[labelcolor]
603
+ for handle, text in zip(self.legend_handles, self.texts):
604
+ try:
605
+ if handle.get_array() is not None:
606
+ continue
607
+ except AttributeError:
608
+ pass
609
+ for getter_name in getter_names:
610
+ try:
611
+ color = getattr(handle, getter_name)()
612
+ if isinstance(color, np.ndarray):
613
+ if (
614
+ color.shape[0] == 1
615
+ or np.isclose(color, color[0]).all()
616
+ ):
617
+ text.set_color(color[0])
618
+ else:
619
+ pass
620
+ else:
621
+ text.set_color(color)
622
+ break
623
+ except AttributeError:
624
+ pass
625
+ elif cbook._str_equal(labelcolor, 'none'):
626
+ for text in self.texts:
627
+ text.set_color(labelcolor)
628
+ elif np.iterable(labelcolor):
629
+ for text, color in zip(self.texts,
630
+ itertools.cycle(
631
+ colors.to_rgba_array(labelcolor))):
632
+ text.set_color(color)
633
+ else:
634
+ raise ValueError(f"Invalid labelcolor: {labelcolor!r}")
635
+
636
+ def _set_artist_props(self, a):
637
+ """
638
+ Set the boilerplate props for artists added to Axes.
639
+ """
640
+ a.set_figure(self.figure)
641
+ if self.isaxes:
642
+ a.axes = self.axes
643
+
644
+ a.set_transform(self.get_transform())
645
+
646
+ @_docstring.dedent_interpd
647
+ def set_loc(self, loc=None):
648
+ """
649
+ Set the location of the legend.
650
+
651
+ .. versionadded:: 3.8
652
+
653
+ Parameters
654
+ ----------
655
+ %(_legend_kw_set_loc_doc)s
656
+ """
657
+ loc0 = loc
658
+ self._loc_used_default = loc is None
659
+ if loc is None:
660
+ loc = mpl.rcParams["legend.loc"]
661
+ if not self.isaxes and loc in [0, 'best']:
662
+ loc = 'upper right'
663
+
664
+ type_err_message = ("loc must be string, coordinate tuple, or"
665
+ f" an integer 0-10, not {loc!r}")
666
+
667
+ # handle outside legends:
668
+ self._outside_loc = None
669
+ if isinstance(loc, str):
670
+ if loc.split()[0] == 'outside':
671
+ # strip outside:
672
+ loc = loc.split('outside ')[1]
673
+ # strip "center" at the beginning
674
+ self._outside_loc = loc.replace('center ', '')
675
+ # strip first
676
+ self._outside_loc = self._outside_loc.split()[0]
677
+ locs = loc.split()
678
+ if len(locs) > 1 and locs[0] in ('right', 'left'):
679
+ # locs doesn't accept "left upper", etc, so swap
680
+ if locs[0] != 'center':
681
+ locs = locs[::-1]
682
+ loc = locs[0] + ' ' + locs[1]
683
+ # check that loc is in acceptable strings
684
+ loc = _api.check_getitem(self.codes, loc=loc)
685
+ elif np.iterable(loc):
686
+ # coerce iterable into tuple
687
+ loc = tuple(loc)
688
+ # validate the tuple represents Real coordinates
689
+ if len(loc) != 2 or not all(isinstance(e, numbers.Real) for e in loc):
690
+ raise ValueError(type_err_message)
691
+ elif isinstance(loc, int):
692
+ # validate the integer represents a string numeric value
693
+ if loc < 0 or loc > 10:
694
+ raise ValueError(type_err_message)
695
+ else:
696
+ # all other cases are invalid values of loc
697
+ raise ValueError(type_err_message)
698
+
699
+ if self.isaxes and self._outside_loc:
700
+ raise ValueError(
701
+ f"'outside' option for loc='{loc0}' keyword argument only "
702
+ "works for figure legends")
703
+
704
+ if not self.isaxes and loc == 0:
705
+ raise ValueError(
706
+ "Automatic legend placement (loc='best') not implemented for "
707
+ "figure legend")
708
+
709
+ tmp = self._loc_used_default
710
+ self._set_loc(loc)
711
+ self._loc_used_default = tmp # ignore changes done by _set_loc
712
+
713
+ def _set_loc(self, loc):
714
+ # find_offset function will be provided to _legend_box and
715
+ # _legend_box will draw itself at the location of the return
716
+ # value of the find_offset.
717
+ self._loc_used_default = False
718
+ self._loc_real = loc
719
+ self.stale = True
720
+ self._legend_box.set_offset(self._findoffset)
721
+
722
+ def set_ncols(self, ncols):
723
+ """Set the number of columns."""
724
+ self._ncols = ncols
725
+
726
+ def _get_loc(self):
727
+ return self._loc_real
728
+
729
+ _loc = property(_get_loc, _set_loc)
730
+
731
+ def _findoffset(self, width, height, xdescent, ydescent, renderer):
732
+ """Helper function to locate the legend."""
733
+
734
+ if self._loc == 0: # "best".
735
+ x, y = self._find_best_position(width, height, renderer)
736
+ elif self._loc in Legend.codes.values(): # Fixed location.
737
+ bbox = Bbox.from_bounds(0, 0, width, height)
738
+ x, y = self._get_anchored_bbox(self._loc, bbox,
739
+ self.get_bbox_to_anchor(),
740
+ renderer)
741
+ else: # Axes or figure coordinates.
742
+ fx, fy = self._loc
743
+ bbox = self.get_bbox_to_anchor()
744
+ x, y = bbox.x0 + bbox.width * fx, bbox.y0 + bbox.height * fy
745
+
746
+ return x + xdescent, y + ydescent
747
+
748
+ @allow_rasterization
749
+ def draw(self, renderer):
750
+ # docstring inherited
751
+ if not self.get_visible():
752
+ return
753
+
754
+ renderer.open_group('legend', gid=self.get_gid())
755
+
756
+ fontsize = renderer.points_to_pixels(self._fontsize)
757
+
758
+ # if mode == fill, set the width of the legend_box to the
759
+ # width of the parent (minus pads)
760
+ if self._mode in ["expand"]:
761
+ pad = 2 * (self.borderaxespad + self.borderpad) * fontsize
762
+ self._legend_box.set_width(self.get_bbox_to_anchor().width - pad)
763
+
764
+ # update the location and size of the legend. This needs to
765
+ # be done in any case to clip the figure right.
766
+ bbox = self._legend_box.get_window_extent(renderer)
767
+ self.legendPatch.set_bounds(bbox.bounds)
768
+ self.legendPatch.set_mutation_scale(fontsize)
769
+
770
+ # self.shadow is validated in __init__
771
+ # So by here it is a bool and self._shadow_props contains any configs
772
+
773
+ if self.shadow:
774
+ Shadow(self.legendPatch, **self._shadow_props).draw(renderer)
775
+
776
+ self.legendPatch.draw(renderer)
777
+ self._legend_box.draw(renderer)
778
+
779
+ renderer.close_group('legend')
780
+ self.stale = False
781
+
782
+ # _default_handler_map defines the default mapping between plot
783
+ # elements and the legend handlers.
784
+
785
+ _default_handler_map = {
786
+ StemContainer: legend_handler.HandlerStem(),
787
+ ErrorbarContainer: legend_handler.HandlerErrorbar(),
788
+ Line2D: legend_handler.HandlerLine2D(),
789
+ Patch: legend_handler.HandlerPatch(),
790
+ StepPatch: legend_handler.HandlerStepPatch(),
791
+ LineCollection: legend_handler.HandlerLineCollection(),
792
+ RegularPolyCollection: legend_handler.HandlerRegularPolyCollection(),
793
+ CircleCollection: legend_handler.HandlerCircleCollection(),
794
+ BarContainer: legend_handler.HandlerPatch(
795
+ update_func=legend_handler.update_from_first_child),
796
+ tuple: legend_handler.HandlerTuple(),
797
+ PathCollection: legend_handler.HandlerPathCollection(),
798
+ PolyCollection: legend_handler.HandlerPolyCollection()
799
+ }
800
+
801
+ # (get|set|update)_default_handler_maps are public interfaces to
802
+ # modify the default handler map.
803
+
804
+ @classmethod
805
+ def get_default_handler_map(cls):
806
+ """Return the global default handler map, shared by all legends."""
807
+ return cls._default_handler_map
808
+
809
+ @classmethod
810
+ def set_default_handler_map(cls, handler_map):
811
+ """Set the global default handler map, shared by all legends."""
812
+ cls._default_handler_map = handler_map
813
+
814
+ @classmethod
815
+ def update_default_handler_map(cls, handler_map):
816
+ """Update the global default handler map, shared by all legends."""
817
+ cls._default_handler_map.update(handler_map)
818
+
819
+ def get_legend_handler_map(self):
820
+ """Return this legend instance's handler map."""
821
+ default_handler_map = self.get_default_handler_map()
822
+ return ({**default_handler_map, **self._custom_handler_map}
823
+ if self._custom_handler_map else default_handler_map)
824
+
825
+ @staticmethod
826
+ def get_legend_handler(legend_handler_map, orig_handle):
827
+ """
828
+ Return a legend handler from *legend_handler_map* that
829
+ corresponds to *orig_handler*.
830
+
831
+ *legend_handler_map* should be a dictionary object (that is
832
+ returned by the get_legend_handler_map method).
833
+
834
+ It first checks if the *orig_handle* itself is a key in the
835
+ *legend_handler_map* and return the associated value.
836
+ Otherwise, it checks for each of the classes in its
837
+ method-resolution-order. If no matching key is found, it
838
+ returns ``None``.
839
+ """
840
+ try:
841
+ return legend_handler_map[orig_handle]
842
+ except (TypeError, KeyError): # TypeError if unhashable.
843
+ pass
844
+ for handle_type in type(orig_handle).mro():
845
+ try:
846
+ return legend_handler_map[handle_type]
847
+ except KeyError:
848
+ pass
849
+ return None
850
+
851
+ def _init_legend_box(self, handles, labels, markerfirst=True):
852
+ """
853
+ Initialize the legend_box. The legend_box is an instance of
854
+ the OffsetBox, which is packed with legend handles and
855
+ texts. Once packed, their location is calculated during the
856
+ drawing time.
857
+ """
858
+
859
+ fontsize = self._fontsize
860
+
861
+ # legend_box is a HPacker, horizontally packed with columns.
862
+ # Each column is a VPacker, vertically packed with legend items.
863
+ # Each legend item is a HPacker packed with:
864
+ # - handlebox: a DrawingArea which contains the legend handle.
865
+ # - labelbox: a TextArea which contains the legend text.
866
+
867
+ text_list = [] # the list of text instances
868
+ handle_list = [] # the list of handle instances
869
+ handles_and_labels = []
870
+
871
+ # The approximate height and descent of text. These values are
872
+ # only used for plotting the legend handle.
873
+ descent = 0.35 * fontsize * (self.handleheight - 0.7) # heuristic.
874
+ height = fontsize * self.handleheight - descent
875
+ # each handle needs to be drawn inside a box of (x, y, w, h) =
876
+ # (0, -descent, width, height). And their coordinates should
877
+ # be given in the display coordinates.
878
+
879
+ # The transformation of each handle will be automatically set
880
+ # to self.get_transform(). If the artist does not use its
881
+ # default transform (e.g., Collections), you need to
882
+ # manually set their transform to the self.get_transform().
883
+ legend_handler_map = self.get_legend_handler_map()
884
+
885
+ for orig_handle, label in zip(handles, labels):
886
+ handler = self.get_legend_handler(legend_handler_map, orig_handle)
887
+ if handler is None:
888
+ _api.warn_external(
889
+ "Legend does not support handles for "
890
+ f"{type(orig_handle).__name__} "
891
+ "instances.\nA proxy artist may be used "
892
+ "instead.\nSee: https://matplotlib.org/"
893
+ "stable/users/explain/axes/legend_guide.html"
894
+ "#controlling-the-legend-entries")
895
+ # No handle for this artist, so we just defer to None.
896
+ handle_list.append(None)
897
+ else:
898
+ textbox = TextArea(label, multilinebaseline=True,
899
+ textprops=dict(
900
+ verticalalignment='baseline',
901
+ horizontalalignment='left',
902
+ fontproperties=self.prop))
903
+ handlebox = DrawingArea(width=self.handlelength * fontsize,
904
+ height=height,
905
+ xdescent=0., ydescent=descent)
906
+
907
+ text_list.append(textbox._text)
908
+ # Create the artist for the legend which represents the
909
+ # original artist/handle.
910
+ handle_list.append(handler.legend_artist(self, orig_handle,
911
+ fontsize, handlebox))
912
+ handles_and_labels.append((handlebox, textbox))
913
+
914
+ columnbox = []
915
+ # array_split splits n handles_and_labels into ncols columns, with the
916
+ # first n%ncols columns having an extra entry. filter(len, ...)
917
+ # handles the case where n < ncols: the last ncols-n columns are empty
918
+ # and get filtered out.
919
+ for handles_and_labels_column in filter(
920
+ len, np.array_split(handles_and_labels, self._ncols)):
921
+ # pack handlebox and labelbox into itembox
922
+ itemboxes = [HPacker(pad=0,
923
+ sep=self.handletextpad * fontsize,
924
+ children=[h, t] if markerfirst else [t, h],
925
+ align="baseline")
926
+ for h, t in handles_and_labels_column]
927
+ # pack columnbox
928
+ alignment = "baseline" if markerfirst else "right"
929
+ columnbox.append(VPacker(pad=0,
930
+ sep=self.labelspacing * fontsize,
931
+ align=alignment,
932
+ children=itemboxes))
933
+
934
+ mode = "expand" if self._mode == "expand" else "fixed"
935
+ sep = self.columnspacing * fontsize
936
+ self._legend_handle_box = HPacker(pad=0,
937
+ sep=sep, align="baseline",
938
+ mode=mode,
939
+ children=columnbox)
940
+ self._legend_title_box = TextArea("")
941
+ self._legend_box = VPacker(pad=self.borderpad * fontsize,
942
+ sep=self.labelspacing * fontsize,
943
+ align=self._alignment,
944
+ children=[self._legend_title_box,
945
+ self._legend_handle_box])
946
+ self._legend_box.set_figure(self.figure)
947
+ self._legend_box.axes = self.axes
948
+ self.texts = text_list
949
+ self.legend_handles = handle_list
950
+
951
+ def _auto_legend_data(self):
952
+ """
953
+ Return display coordinates for hit testing for "best" positioning.
954
+
955
+ Returns
956
+ -------
957
+ bboxes
958
+ List of bounding boxes of all patches.
959
+ lines
960
+ List of `.Path` corresponding to each line.
961
+ offsets
962
+ List of (x, y) offsets of all collection.
963
+ """
964
+ assert self.isaxes # always holds, as this is only called internally
965
+ bboxes = []
966
+ lines = []
967
+ offsets = []
968
+ for artist in self.parent._children:
969
+ if isinstance(artist, Line2D):
970
+ lines.append(
971
+ artist.get_transform().transform_path(artist.get_path()))
972
+ elif isinstance(artist, Rectangle):
973
+ bboxes.append(
974
+ artist.get_bbox().transformed(artist.get_data_transform()))
975
+ elif isinstance(artist, Patch):
976
+ lines.append(
977
+ artist.get_transform().transform_path(artist.get_path()))
978
+ elif isinstance(artist, PolyCollection):
979
+ lines.extend(artist.get_transform().transform_path(path)
980
+ for path in artist.get_paths())
981
+ elif isinstance(artist, Collection):
982
+ transform, transOffset, hoffsets, _ = artist._prepare_points()
983
+ if len(hoffsets):
984
+ offsets.extend(transOffset.transform(hoffsets))
985
+ elif isinstance(artist, Text):
986
+ bboxes.append(artist.get_window_extent())
987
+
988
+ return bboxes, lines, offsets
989
+
990
+ def get_children(self):
991
+ # docstring inherited
992
+ return [self._legend_box, self.get_frame()]
993
+
994
+ def get_frame(self):
995
+ """Return the `~.patches.Rectangle` used to frame the legend."""
996
+ return self.legendPatch
997
+
998
+ def get_lines(self):
999
+ r"""Return the list of `~.lines.Line2D`\s in the legend."""
1000
+ return [h for h in self.legend_handles if isinstance(h, Line2D)]
1001
+
1002
+ def get_patches(self):
1003
+ r"""Return the list of `~.patches.Patch`\s in the legend."""
1004
+ return silent_list('Patch',
1005
+ [h for h in self.legend_handles
1006
+ if isinstance(h, Patch)])
1007
+
1008
+ def get_texts(self):
1009
+ r"""Return the list of `~.text.Text`\s in the legend."""
1010
+ return silent_list('Text', self.texts)
1011
+
1012
+ def set_alignment(self, alignment):
1013
+ """
1014
+ Set the alignment of the legend title and the box of entries.
1015
+
1016
+ The entries are aligned as a single block, so that markers always
1017
+ lined up.
1018
+
1019
+ Parameters
1020
+ ----------
1021
+ alignment : {'center', 'left', 'right'}.
1022
+
1023
+ """
1024
+ _api.check_in_list(["center", "left", "right"], alignment=alignment)
1025
+ self._alignment = alignment
1026
+ self._legend_box.align = alignment
1027
+
1028
+ def get_alignment(self):
1029
+ """Get the alignment value of the legend box"""
1030
+ return self._legend_box.align
1031
+
1032
+ def set_title(self, title, prop=None):
1033
+ """
1034
+ Set legend title and title style.
1035
+
1036
+ Parameters
1037
+ ----------
1038
+ title : str
1039
+ The legend title.
1040
+
1041
+ prop : `.font_manager.FontProperties` or `str` or `pathlib.Path`
1042
+ The font properties of the legend title.
1043
+ If a `str`, it is interpreted as a fontconfig pattern parsed by
1044
+ `.FontProperties`. If a `pathlib.Path`, it is interpreted as the
1045
+ absolute path to a font file.
1046
+
1047
+ """
1048
+ self._legend_title_box._text.set_text(title)
1049
+ if title:
1050
+ self._legend_title_box._text.set_visible(True)
1051
+ self._legend_title_box.set_visible(True)
1052
+ else:
1053
+ self._legend_title_box._text.set_visible(False)
1054
+ self._legend_title_box.set_visible(False)
1055
+
1056
+ if prop is not None:
1057
+ self._legend_title_box._text.set_fontproperties(prop)
1058
+
1059
+ self.stale = True
1060
+
1061
+ def get_title(self):
1062
+ """Return the `.Text` instance for the legend title."""
1063
+ return self._legend_title_box._text
1064
+
1065
+ def get_window_extent(self, renderer=None):
1066
+ # docstring inherited
1067
+ if renderer is None:
1068
+ renderer = self.figure._get_renderer()
1069
+ return self._legend_box.get_window_extent(renderer=renderer)
1070
+
1071
+ def get_tightbbox(self, renderer=None):
1072
+ # docstring inherited
1073
+ return self._legend_box.get_window_extent(renderer)
1074
+
1075
+ def get_frame_on(self):
1076
+ """Get whether the legend box patch is drawn."""
1077
+ return self.legendPatch.get_visible()
1078
+
1079
+ def set_frame_on(self, b):
1080
+ """
1081
+ Set whether the legend box patch is drawn.
1082
+
1083
+ Parameters
1084
+ ----------
1085
+ b : bool
1086
+ """
1087
+ self.legendPatch.set_visible(b)
1088
+ self.stale = True
1089
+
1090
+ draw_frame = set_frame_on # Backcompat alias.
1091
+
1092
+ def get_bbox_to_anchor(self):
1093
+ """Return the bbox that the legend will be anchored to."""
1094
+ if self._bbox_to_anchor is None:
1095
+ return self.parent.bbox
1096
+ else:
1097
+ return self._bbox_to_anchor
1098
+
1099
+ def set_bbox_to_anchor(self, bbox, transform=None):
1100
+ """
1101
+ Set the bbox that the legend will be anchored to.
1102
+
1103
+ Parameters
1104
+ ----------
1105
+ bbox : `~matplotlib.transforms.BboxBase` or tuple
1106
+ The bounding box can be specified in the following ways:
1107
+
1108
+ - A `.BboxBase` instance
1109
+ - A tuple of ``(left, bottom, width, height)`` in the given
1110
+ transform (normalized axes coordinate if None)
1111
+ - A tuple of ``(left, bottom)`` where the width and height will be
1112
+ assumed to be zero.
1113
+ - *None*, to remove the bbox anchoring, and use the parent bbox.
1114
+
1115
+ transform : `~matplotlib.transforms.Transform`, optional
1116
+ A transform to apply to the bounding box. If not specified, this
1117
+ will use a transform to the bounding box of the parent.
1118
+ """
1119
+ if bbox is None:
1120
+ self._bbox_to_anchor = None
1121
+ return
1122
+ elif isinstance(bbox, BboxBase):
1123
+ self._bbox_to_anchor = bbox
1124
+ else:
1125
+ try:
1126
+ l = len(bbox)
1127
+ except TypeError as err:
1128
+ raise ValueError(f"Invalid bbox: {bbox}") from err
1129
+
1130
+ if l == 2:
1131
+ bbox = [bbox[0], bbox[1], 0, 0]
1132
+
1133
+ self._bbox_to_anchor = Bbox.from_bounds(*bbox)
1134
+
1135
+ if transform is None:
1136
+ transform = BboxTransformTo(self.parent.bbox)
1137
+
1138
+ self._bbox_to_anchor = TransformedBbox(self._bbox_to_anchor,
1139
+ transform)
1140
+ self.stale = True
1141
+
1142
+ def _get_anchored_bbox(self, loc, bbox, parentbbox, renderer):
1143
+ """
1144
+ Place the *bbox* inside the *parentbbox* according to a given
1145
+ location code. Return the (x, y) coordinate of the bbox.
1146
+
1147
+ Parameters
1148
+ ----------
1149
+ loc : int
1150
+ A location code in range(1, 11). This corresponds to the possible
1151
+ values for ``self._loc``, excluding "best".
1152
+ bbox : `~matplotlib.transforms.Bbox`
1153
+ bbox to be placed, in display coordinates.
1154
+ parentbbox : `~matplotlib.transforms.Bbox`
1155
+ A parent box which will contain the bbox, in display coordinates.
1156
+ """
1157
+ return offsetbox._get_anchored_bbox(
1158
+ loc, bbox, parentbbox,
1159
+ self.borderaxespad * renderer.points_to_pixels(self._fontsize))
1160
+
1161
+ def _find_best_position(self, width, height, renderer):
1162
+ """Determine the best location to place the legend."""
1163
+ assert self.isaxes # always holds, as this is only called internally
1164
+
1165
+ start_time = time.perf_counter()
1166
+
1167
+ bboxes, lines, offsets = self._auto_legend_data()
1168
+
1169
+ bbox = Bbox.from_bounds(0, 0, width, height)
1170
+
1171
+ candidates = []
1172
+ for idx in range(1, len(self.codes)):
1173
+ l, b = self._get_anchored_bbox(idx, bbox,
1174
+ self.get_bbox_to_anchor(),
1175
+ renderer)
1176
+ legendBox = Bbox.from_bounds(l, b, width, height)
1177
+ # XXX TODO: If markers are present, it would be good to take them
1178
+ # into account when checking vertex overlaps in the next line.
1179
+ badness = (sum(legendBox.count_contains(line.vertices)
1180
+ for line in lines)
1181
+ + legendBox.count_contains(offsets)
1182
+ + legendBox.count_overlaps(bboxes)
1183
+ + sum(line.intersects_bbox(legendBox, filled=False)
1184
+ for line in lines))
1185
+ # Include the index to favor lower codes in case of a tie.
1186
+ candidates.append((badness, idx, (l, b)))
1187
+ if badness == 0:
1188
+ break
1189
+
1190
+ _, _, (l, b) = min(candidates)
1191
+
1192
+ if self._loc_used_default and time.perf_counter() - start_time > 1:
1193
+ _api.warn_external(
1194
+ 'Creating legend with loc="best" can be slow with large '
1195
+ 'amounts of data.')
1196
+
1197
+ return l, b
1198
+
1199
+ @_api.rename_parameter("3.8", "event", "mouseevent")
1200
+ def contains(self, mouseevent):
1201
+ return self.legendPatch.contains(mouseevent)
1202
+
1203
+ def set_draggable(self, state, use_blit=False, update='loc'):
1204
+ """
1205
+ Enable or disable mouse dragging support of the legend.
1206
+
1207
+ Parameters
1208
+ ----------
1209
+ state : bool
1210
+ Whether mouse dragging is enabled.
1211
+ use_blit : bool, optional
1212
+ Use blitting for faster image composition. For details see
1213
+ :ref:`func-animation`.
1214
+ update : {'loc', 'bbox'}, optional
1215
+ The legend parameter to be changed when dragged:
1216
+
1217
+ - 'loc': update the *loc* parameter of the legend
1218
+ - 'bbox': update the *bbox_to_anchor* parameter of the legend
1219
+
1220
+ Returns
1221
+ -------
1222
+ `.DraggableLegend` or *None*
1223
+ If *state* is ``True`` this returns the `.DraggableLegend` helper
1224
+ instance. Otherwise this returns *None*.
1225
+ """
1226
+ if state:
1227
+ if self._draggable is None:
1228
+ self._draggable = DraggableLegend(self,
1229
+ use_blit,
1230
+ update=update)
1231
+ else:
1232
+ if self._draggable is not None:
1233
+ self._draggable.disconnect()
1234
+ self._draggable = None
1235
+ return self._draggable
1236
+
1237
+ def get_draggable(self):
1238
+ """Return ``True`` if the legend is draggable, ``False`` otherwise."""
1239
+ return self._draggable is not None
1240
+
1241
+
1242
+ # Helper functions to parse legend arguments for both `figure.legend` and
1243
+ # `axes.legend`:
1244
+ def _get_legend_handles(axs, legend_handler_map=None):
1245
+ """Yield artists that can be used as handles in a legend."""
1246
+ handles_original = []
1247
+ for ax in axs:
1248
+ handles_original += [
1249
+ *(a for a in ax._children
1250
+ if isinstance(a, (Line2D, Patch, Collection, Text))),
1251
+ *ax.containers]
1252
+ # support parasite Axes:
1253
+ if hasattr(ax, 'parasites'):
1254
+ for axx in ax.parasites:
1255
+ handles_original += [
1256
+ *(a for a in axx._children
1257
+ if isinstance(a, (Line2D, Patch, Collection, Text))),
1258
+ *axx.containers]
1259
+
1260
+ handler_map = {**Legend.get_default_handler_map(),
1261
+ **(legend_handler_map or {})}
1262
+ has_handler = Legend.get_legend_handler
1263
+ for handle in handles_original:
1264
+ label = handle.get_label()
1265
+ if label != '_nolegend_' and has_handler(handler_map, handle):
1266
+ yield handle
1267
+ elif (label and not label.startswith('_') and
1268
+ not has_handler(handler_map, handle)):
1269
+ _api.warn_external(
1270
+ "Legend does not support handles for "
1271
+ f"{type(handle).__name__} "
1272
+ "instances.\nSee: https://matplotlib.org/stable/"
1273
+ "tutorials/intermediate/legend_guide.html"
1274
+ "#implementing-a-custom-legend-handler")
1275
+ continue
1276
+
1277
+
1278
+ def _get_legend_handles_labels(axs, legend_handler_map=None):
1279
+ """Return handles and labels for legend."""
1280
+ handles = []
1281
+ labels = []
1282
+ for handle in _get_legend_handles(axs, legend_handler_map):
1283
+ label = handle.get_label()
1284
+ if label and not label.startswith('_'):
1285
+ handles.append(handle)
1286
+ labels.append(label)
1287
+ return handles, labels
1288
+
1289
+
1290
+ def _parse_legend_args(axs, *args, handles=None, labels=None, **kwargs):
1291
+ """
1292
+ Get the handles and labels from the calls to either ``figure.legend``
1293
+ or ``axes.legend``.
1294
+
1295
+ The parser is a bit involved because we support::
1296
+
1297
+ legend()
1298
+ legend(labels)
1299
+ legend(handles, labels)
1300
+ legend(labels=labels)
1301
+ legend(handles=handles)
1302
+ legend(handles=handles, labels=labels)
1303
+
1304
+ The behavior for a mixture of positional and keyword handles and labels
1305
+ is undefined and issues a warning; it will be an error in the future.
1306
+
1307
+ Parameters
1308
+ ----------
1309
+ axs : list of `.Axes`
1310
+ If handles are not given explicitly, the artists in these Axes are
1311
+ used as handles.
1312
+ *args : tuple
1313
+ Positional parameters passed to ``legend()``.
1314
+ handles
1315
+ The value of the keyword argument ``legend(handles=...)``, or *None*
1316
+ if that keyword argument was not used.
1317
+ labels
1318
+ The value of the keyword argument ``legend(labels=...)``, or *None*
1319
+ if that keyword argument was not used.
1320
+ **kwargs
1321
+ All other keyword arguments passed to ``legend()``.
1322
+
1323
+ Returns
1324
+ -------
1325
+ handles : list of (`.Artist` or tuple of `.Artist`)
1326
+ The legend handles.
1327
+ labels : list of str
1328
+ The legend labels.
1329
+ kwargs : dict
1330
+ *kwargs* with keywords handles and labels removed.
1331
+
1332
+ """
1333
+ log = logging.getLogger(__name__)
1334
+
1335
+ handlers = kwargs.get('handler_map')
1336
+
1337
+ if (handles is not None or labels is not None) and args:
1338
+ _api.warn_deprecated("3.9", message=(
1339
+ "You have mixed positional and keyword arguments, some input may "
1340
+ "be discarded. This is deprecated since %(since)s and will "
1341
+ "become an error %(removal)s."))
1342
+
1343
+ if (hasattr(handles, "__len__") and
1344
+ hasattr(labels, "__len__") and
1345
+ len(handles) != len(labels)):
1346
+ _api.warn_external(f"Mismatched number of handles and labels: "
1347
+ f"len(handles) = {len(handles)} "
1348
+ f"len(labels) = {len(labels)}")
1349
+ # if got both handles and labels as kwargs, make same length
1350
+ if handles and labels:
1351
+ handles, labels = zip(*zip(handles, labels))
1352
+
1353
+ elif handles is not None and labels is None:
1354
+ labels = [handle.get_label() for handle in handles]
1355
+
1356
+ elif labels is not None and handles is None:
1357
+ # Get as many handles as there are labels.
1358
+ handles = [handle for handle, label
1359
+ in zip(_get_legend_handles(axs, handlers), labels)]
1360
+
1361
+ elif len(args) == 0: # 0 args: automatically detect labels and handles.
1362
+ handles, labels = _get_legend_handles_labels(axs, handlers)
1363
+ if not handles:
1364
+ _api.warn_external(
1365
+ "No artists with labels found to put in legend. Note that "
1366
+ "artists whose label start with an underscore are ignored "
1367
+ "when legend() is called with no argument.")
1368
+
1369
+ elif len(args) == 1: # 1 arg: user defined labels, automatic handle detection.
1370
+ labels, = args
1371
+ if any(isinstance(l, Artist) for l in labels):
1372
+ raise TypeError("A single argument passed to legend() must be a "
1373
+ "list of labels, but found an Artist in there.")
1374
+
1375
+ # Get as many handles as there are labels.
1376
+ handles = [handle for handle, label
1377
+ in zip(_get_legend_handles(axs, handlers), labels)]
1378
+
1379
+ elif len(args) == 2: # 2 args: user defined handles and labels.
1380
+ handles, labels = args[:2]
1381
+
1382
+ else:
1383
+ raise _api.nargs_error('legend', '0-2', len(args))
1384
+
1385
+ return handles, labels, kwargs
llava_next/lib/python3.10/site-packages/matplotlib/markers.pyi ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Literal
2
+
3
+ from .path import Path
4
+ from .transforms import Affine2D, Transform
5
+
6
+ from numpy.typing import ArrayLike
7
+ from .typing import CapStyleType, FillStyleType, JoinStyleType
8
+
9
+ TICKLEFT: int
10
+ TICKRIGHT: int
11
+ TICKUP: int
12
+ TICKDOWN: int
13
+ CARETLEFT: int
14
+ CARETRIGHT: int
15
+ CARETUP: int
16
+ CARETDOWN: int
17
+ CARETLEFTBASE: int
18
+ CARETRIGHTBASE: int
19
+ CARETUPBASE: int
20
+ CARETDOWNBASE: int
21
+
22
+ class MarkerStyle:
23
+ markers: dict[str | int, str]
24
+ filled_markers: tuple[str, ...]
25
+ fillstyles: tuple[FillStyleType, ...]
26
+
27
+ def __init__(
28
+ self,
29
+ marker: str | ArrayLike | Path | MarkerStyle,
30
+ fillstyle: FillStyleType | None = ...,
31
+ transform: Transform | None = ...,
32
+ capstyle: CapStyleType | None = ...,
33
+ joinstyle: JoinStyleType | None = ...,
34
+ ) -> None: ...
35
+ def __bool__(self) -> bool: ...
36
+ def is_filled(self) -> bool: ...
37
+ def get_fillstyle(self) -> FillStyleType: ...
38
+ def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
39
+ def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
40
+ def get_marker(self) -> str | ArrayLike | Path | None: ...
41
+ def get_path(self) -> Path: ...
42
+ def get_transform(self) -> Transform: ...
43
+ def get_alt_path(self) -> Path | None: ...
44
+ def get_alt_transform(self) -> Transform: ...
45
+ def get_snap_threshold(self) -> float | None: ...
46
+ def get_user_transform(self) -> Transform | None: ...
47
+ def transformed(self, transform: Affine2D) -> MarkerStyle: ...
48
+ def rotated(
49
+ self, *, deg: float | None = ..., rad: float | None = ...
50
+ ) -> MarkerStyle: ...
51
+ def scaled(self, sx: float, sy: float | None = ...) -> MarkerStyle: ...
llava_next/lib/python3.10/site-packages/matplotlib/offsetbox.py ADDED
@@ -0,0 +1,1569 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ r"""
2
+ Container classes for `.Artist`\s.
3
+
4
+ `OffsetBox`
5
+ The base of all container artists defined in this module.
6
+
7
+ `AnchoredOffsetbox`, `AnchoredText`
8
+ Anchor and align an arbitrary `.Artist` or a text relative to the parent
9
+ axes or a specific anchor point.
10
+
11
+ `DrawingArea`
12
+ A container with fixed width and height. Children have a fixed position
13
+ inside the container and may be clipped.
14
+
15
+ `HPacker`, `VPacker`
16
+ Containers for layouting their children vertically or horizontally.
17
+
18
+ `PaddedBox`
19
+ A container to add a padding around an `.Artist`.
20
+
21
+ `TextArea`
22
+ Contains a single `.Text` instance.
23
+ """
24
+
25
+ import functools
26
+
27
+ import numpy as np
28
+
29
+ import matplotlib as mpl
30
+ from matplotlib import _api, _docstring
31
+ import matplotlib.artist as martist
32
+ import matplotlib.path as mpath
33
+ import matplotlib.text as mtext
34
+ import matplotlib.transforms as mtransforms
35
+ from matplotlib.font_manager import FontProperties
36
+ from matplotlib.image import BboxImage
37
+ from matplotlib.patches import (
38
+ FancyBboxPatch, FancyArrowPatch, bbox_artist as mbbox_artist)
39
+ from matplotlib.transforms import Bbox, BboxBase, TransformedBbox
40
+
41
+
42
+ DEBUG = False
43
+
44
+
45
+ def _compat_get_offset(meth):
46
+ """
47
+ Decorator for the get_offset method of OffsetBox and subclasses, that
48
+ allows supporting both the new signature (self, bbox, renderer) and the old
49
+ signature (self, width, height, xdescent, ydescent, renderer).
50
+ """
51
+ sigs = [lambda self, width, height, xdescent, ydescent, renderer: locals(),
52
+ lambda self, bbox, renderer: locals()]
53
+
54
+ @functools.wraps(meth)
55
+ def get_offset(self, *args, **kwargs):
56
+ params = _api.select_matching_signature(sigs, self, *args, **kwargs)
57
+ bbox = (params["bbox"] if "bbox" in params else
58
+ Bbox.from_bounds(-params["xdescent"], -params["ydescent"],
59
+ params["width"], params["height"]))
60
+ return meth(params["self"], bbox, params["renderer"])
61
+ return get_offset
62
+
63
+
64
+ # for debugging use
65
+ def _bbox_artist(*args, **kwargs):
66
+ if DEBUG:
67
+ mbbox_artist(*args, **kwargs)
68
+
69
+
70
+ def _get_packed_offsets(widths, total, sep, mode="fixed"):
71
+ r"""
72
+ Pack boxes specified by their *widths*.
73
+
74
+ For simplicity of the description, the terminology used here assumes a
75
+ horizontal layout, but the function works equally for a vertical layout.
76
+
77
+ There are three packing *mode*\s:
78
+
79
+ - 'fixed': The elements are packed tight to the left with a spacing of
80
+ *sep* in between. If *total* is *None* the returned total will be the
81
+ right edge of the last box. A non-*None* total will be passed unchecked
82
+ to the output. In particular this means that right edge of the last
83
+ box may be further to the right than the returned total.
84
+
85
+ - 'expand': Distribute the boxes with equal spacing so that the left edge
86
+ of the first box is at 0, and the right edge of the last box is at
87
+ *total*. The parameter *sep* is ignored in this mode. A total of *None*
88
+ is accepted and considered equal to 1. The total is returned unchanged
89
+ (except for the conversion *None* to 1). If the total is smaller than
90
+ the sum of the widths, the laid out boxes will overlap.
91
+
92
+ - 'equal': If *total* is given, the total space is divided in N equal
93
+ ranges and each box is left-aligned within its subspace.
94
+ Otherwise (*total* is *None*), *sep* must be provided and each box is
95
+ left-aligned in its subspace of width ``(max(widths) + sep)``. The
96
+ total width is then calculated to be ``N * (max(widths) + sep)``.
97
+
98
+ Parameters
99
+ ----------
100
+ widths : list of float
101
+ Widths of boxes to be packed.
102
+ total : float or None
103
+ Intended total length. *None* if not used.
104
+ sep : float or None
105
+ Spacing between boxes.
106
+ mode : {'fixed', 'expand', 'equal'}
107
+ The packing mode.
108
+
109
+ Returns
110
+ -------
111
+ total : float
112
+ The total width needed to accommodate the laid out boxes.
113
+ offsets : array of float
114
+ The left offsets of the boxes.
115
+ """
116
+ _api.check_in_list(["fixed", "expand", "equal"], mode=mode)
117
+
118
+ if mode == "fixed":
119
+ offsets_ = np.cumsum([0] + [w + sep for w in widths])
120
+ offsets = offsets_[:-1]
121
+ if total is None:
122
+ total = offsets_[-1] - sep
123
+ return total, offsets
124
+
125
+ elif mode == "expand":
126
+ # This is a bit of a hack to avoid a TypeError when *total*
127
+ # is None and used in conjugation with tight layout.
128
+ if total is None:
129
+ total = 1
130
+ if len(widths) > 1:
131
+ sep = (total - sum(widths)) / (len(widths) - 1)
132
+ else:
133
+ sep = 0
134
+ offsets_ = np.cumsum([0] + [w + sep for w in widths])
135
+ offsets = offsets_[:-1]
136
+ return total, offsets
137
+
138
+ elif mode == "equal":
139
+ maxh = max(widths)
140
+ if total is None:
141
+ if sep is None:
142
+ raise ValueError("total and sep cannot both be None when "
143
+ "using layout mode 'equal'")
144
+ total = (maxh + sep) * len(widths)
145
+ else:
146
+ sep = total / len(widths) - maxh
147
+ offsets = (maxh + sep) * np.arange(len(widths))
148
+ return total, offsets
149
+
150
+
151
+ def _get_aligned_offsets(yspans, height, align="baseline"):
152
+ """
153
+ Align boxes each specified by their ``(y0, y1)`` spans.
154
+
155
+ For simplicity of the description, the terminology used here assumes a
156
+ horizontal layout (i.e., vertical alignment), but the function works
157
+ equally for a vertical layout.
158
+
159
+ Parameters
160
+ ----------
161
+ yspans
162
+ List of (y0, y1) spans of boxes to be aligned.
163
+ height : float or None
164
+ Intended total height. If None, the maximum of the heights
165
+ (``y1 - y0``) in *yspans* is used.
166
+ align : {'baseline', 'left', 'top', 'right', 'bottom', 'center'}
167
+ The alignment anchor of the boxes.
168
+
169
+ Returns
170
+ -------
171
+ (y0, y1)
172
+ y range spanned by the packing. If a *height* was originally passed
173
+ in, then for all alignments other than "baseline", a span of ``(0,
174
+ height)`` is used without checking that it is actually large enough).
175
+ descent
176
+ The descent of the packing.
177
+ offsets
178
+ The bottom offsets of the boxes.
179
+ """
180
+
181
+ _api.check_in_list(
182
+ ["baseline", "left", "top", "right", "bottom", "center"], align=align)
183
+ if height is None:
184
+ height = max(y1 - y0 for y0, y1 in yspans)
185
+
186
+ if align == "baseline":
187
+ yspan = (min(y0 for y0, y1 in yspans), max(y1 for y0, y1 in yspans))
188
+ offsets = [0] * len(yspans)
189
+ elif align in ["left", "bottom"]:
190
+ yspan = (0, height)
191
+ offsets = [-y0 for y0, y1 in yspans]
192
+ elif align in ["right", "top"]:
193
+ yspan = (0, height)
194
+ offsets = [height - y1 for y0, y1 in yspans]
195
+ elif align == "center":
196
+ yspan = (0, height)
197
+ offsets = [(height - (y1 - y0)) * .5 - y0 for y0, y1 in yspans]
198
+
199
+ return yspan, offsets
200
+
201
+
202
+ class OffsetBox(martist.Artist):
203
+ """
204
+ The OffsetBox is a simple container artist.
205
+
206
+ The child artists are meant to be drawn at a relative position to its
207
+ parent.
208
+
209
+ Being an artist itself, all parameters are passed on to `.Artist`.
210
+ """
211
+ def __init__(self, *args, **kwargs):
212
+ super().__init__(*args)
213
+ self._internal_update(kwargs)
214
+ # Clipping has not been implemented in the OffsetBox family, so
215
+ # disable the clip flag for consistency. It can always be turned back
216
+ # on to zero effect.
217
+ self.set_clip_on(False)
218
+ self._children = []
219
+ self._offset = (0, 0)
220
+
221
+ def set_figure(self, fig):
222
+ """
223
+ Set the `.Figure` for the `.OffsetBox` and all its children.
224
+
225
+ Parameters
226
+ ----------
227
+ fig : `~matplotlib.figure.Figure`
228
+ """
229
+ super().set_figure(fig)
230
+ for c in self.get_children():
231
+ c.set_figure(fig)
232
+
233
+ @martist.Artist.axes.setter
234
+ def axes(self, ax):
235
+ # TODO deal with this better
236
+ martist.Artist.axes.fset(self, ax)
237
+ for c in self.get_children():
238
+ if c is not None:
239
+ c.axes = ax
240
+
241
+ def contains(self, mouseevent):
242
+ """
243
+ Delegate the mouse event contains-check to the children.
244
+
245
+ As a container, the `.OffsetBox` does not respond itself to
246
+ mouseevents.
247
+
248
+ Parameters
249
+ ----------
250
+ mouseevent : `~matplotlib.backend_bases.MouseEvent`
251
+
252
+ Returns
253
+ -------
254
+ contains : bool
255
+ Whether any values are within the radius.
256
+ details : dict
257
+ An artist-specific dictionary of details of the event context,
258
+ such as which points are contained in the pick radius. See the
259
+ individual Artist subclasses for details.
260
+
261
+ See Also
262
+ --------
263
+ .Artist.contains
264
+ """
265
+ if self._different_canvas(mouseevent):
266
+ return False, {}
267
+ for c in self.get_children():
268
+ a, b = c.contains(mouseevent)
269
+ if a:
270
+ return a, b
271
+ return False, {}
272
+
273
+ def set_offset(self, xy):
274
+ """
275
+ Set the offset.
276
+
277
+ Parameters
278
+ ----------
279
+ xy : (float, float) or callable
280
+ The (x, y) coordinates of the offset in display units. These can
281
+ either be given explicitly as a tuple (x, y), or by providing a
282
+ function that converts the extent into the offset. This function
283
+ must have the signature::
284
+
285
+ def offset(width, height, xdescent, ydescent, renderer) \
286
+ -> (float, float)
287
+ """
288
+ self._offset = xy
289
+ self.stale = True
290
+
291
+ @_compat_get_offset
292
+ def get_offset(self, bbox, renderer):
293
+ """
294
+ Return the offset as a tuple (x, y).
295
+
296
+ The extent parameters have to be provided to handle the case where the
297
+ offset is dynamically determined by a callable (see
298
+ `~.OffsetBox.set_offset`).
299
+
300
+ Parameters
301
+ ----------
302
+ bbox : `.Bbox`
303
+ renderer : `.RendererBase` subclass
304
+ """
305
+ return (
306
+ self._offset(bbox.width, bbox.height, -bbox.x0, -bbox.y0, renderer)
307
+ if callable(self._offset)
308
+ else self._offset)
309
+
310
+ def set_width(self, width):
311
+ """
312
+ Set the width of the box.
313
+
314
+ Parameters
315
+ ----------
316
+ width : float
317
+ """
318
+ self.width = width
319
+ self.stale = True
320
+
321
+ def set_height(self, height):
322
+ """
323
+ Set the height of the box.
324
+
325
+ Parameters
326
+ ----------
327
+ height : float
328
+ """
329
+ self.height = height
330
+ self.stale = True
331
+
332
+ def get_visible_children(self):
333
+ r"""Return a list of the visible child `.Artist`\s."""
334
+ return [c for c in self._children if c.get_visible()]
335
+
336
+ def get_children(self):
337
+ r"""Return a list of the child `.Artist`\s."""
338
+ return self._children
339
+
340
+ def _get_bbox_and_child_offsets(self, renderer):
341
+ """
342
+ Return the bbox of the offsetbox and the child offsets.
343
+
344
+ The bbox should satisfy ``x0 <= x1 and y0 <= y1``.
345
+
346
+ Parameters
347
+ ----------
348
+ renderer : `.RendererBase` subclass
349
+
350
+ Returns
351
+ -------
352
+ bbox
353
+ list of (xoffset, yoffset) pairs
354
+ """
355
+ raise NotImplementedError(
356
+ "get_bbox_and_offsets must be overridden in derived classes")
357
+
358
+ def get_bbox(self, renderer):
359
+ """Return the bbox of the offsetbox, ignoring parent offsets."""
360
+ bbox, offsets = self._get_bbox_and_child_offsets(renderer)
361
+ return bbox
362
+
363
+ def get_window_extent(self, renderer=None):
364
+ # docstring inherited
365
+ if renderer is None:
366
+ renderer = self.figure._get_renderer()
367
+ bbox = self.get_bbox(renderer)
368
+ try: # Some subclasses redefine get_offset to take no args.
369
+ px, py = self.get_offset(bbox, renderer)
370
+ except TypeError:
371
+ px, py = self.get_offset()
372
+ return bbox.translated(px, py)
373
+
374
+ def draw(self, renderer):
375
+ """
376
+ Update the location of children if necessary and draw them
377
+ to the given *renderer*.
378
+ """
379
+ bbox, offsets = self._get_bbox_and_child_offsets(renderer)
380
+ px, py = self.get_offset(bbox, renderer)
381
+ for c, (ox, oy) in zip(self.get_visible_children(), offsets):
382
+ c.set_offset((px + ox, py + oy))
383
+ c.draw(renderer)
384
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
385
+ self.stale = False
386
+
387
+
388
+ class PackerBase(OffsetBox):
389
+ def __init__(self, pad=0., sep=0., width=None, height=None,
390
+ align="baseline", mode="fixed", children=None):
391
+ """
392
+ Parameters
393
+ ----------
394
+ pad : float, default: 0.0
395
+ The boundary padding in points.
396
+
397
+ sep : float, default: 0.0
398
+ The spacing between items in points.
399
+
400
+ width, height : float, optional
401
+ Width and height of the container box in pixels, calculated if
402
+ *None*.
403
+
404
+ align : {'top', 'bottom', 'left', 'right', 'center', 'baseline'}, \
405
+ default: 'baseline'
406
+ Alignment of boxes.
407
+
408
+ mode : {'fixed', 'expand', 'equal'}, default: 'fixed'
409
+ The packing mode.
410
+
411
+ - 'fixed' packs the given `.Artist`\\s tight with *sep* spacing.
412
+ - 'expand' uses the maximal available space to distribute the
413
+ artists with equal spacing in between.
414
+ - 'equal': Each artist an equal fraction of the available space
415
+ and is left-aligned (or top-aligned) therein.
416
+
417
+ children : list of `.Artist`
418
+ The artists to pack.
419
+
420
+ Notes
421
+ -----
422
+ *pad* and *sep* are in points and will be scaled with the renderer
423
+ dpi, while *width* and *height* are in pixels.
424
+ """
425
+ super().__init__()
426
+ self.height = height
427
+ self.width = width
428
+ self.sep = sep
429
+ self.pad = pad
430
+ self.mode = mode
431
+ self.align = align
432
+ self._children = children
433
+
434
+
435
+ class VPacker(PackerBase):
436
+ """
437
+ VPacker packs its children vertically, automatically adjusting their
438
+ relative positions at draw time.
439
+ """
440
+
441
+ def _get_bbox_and_child_offsets(self, renderer):
442
+ # docstring inherited
443
+ dpicor = renderer.points_to_pixels(1.)
444
+ pad = self.pad * dpicor
445
+ sep = self.sep * dpicor
446
+
447
+ if self.width is not None:
448
+ for c in self.get_visible_children():
449
+ if isinstance(c, PackerBase) and c.mode == "expand":
450
+ c.set_width(self.width)
451
+
452
+ bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
453
+ (x0, x1), xoffsets = _get_aligned_offsets(
454
+ [bbox.intervalx for bbox in bboxes], self.width, self.align)
455
+ height, yoffsets = _get_packed_offsets(
456
+ [bbox.height for bbox in bboxes], self.height, sep, self.mode)
457
+
458
+ yoffsets = height - (yoffsets + [bbox.y1 for bbox in bboxes])
459
+ ydescent = yoffsets[0]
460
+ yoffsets = yoffsets - ydescent
461
+
462
+ return (
463
+ Bbox.from_bounds(x0, -ydescent, x1 - x0, height).padded(pad),
464
+ [*zip(xoffsets, yoffsets)])
465
+
466
+
467
+ class HPacker(PackerBase):
468
+ """
469
+ HPacker packs its children horizontally, automatically adjusting their
470
+ relative positions at draw time.
471
+ """
472
+
473
+ def _get_bbox_and_child_offsets(self, renderer):
474
+ # docstring inherited
475
+ dpicor = renderer.points_to_pixels(1.)
476
+ pad = self.pad * dpicor
477
+ sep = self.sep * dpicor
478
+
479
+ bboxes = [c.get_bbox(renderer) for c in self.get_visible_children()]
480
+ if not bboxes:
481
+ return Bbox.from_bounds(0, 0, 0, 0).padded(pad), []
482
+
483
+ (y0, y1), yoffsets = _get_aligned_offsets(
484
+ [bbox.intervaly for bbox in bboxes], self.height, self.align)
485
+ width, xoffsets = _get_packed_offsets(
486
+ [bbox.width for bbox in bboxes], self.width, sep, self.mode)
487
+
488
+ x0 = bboxes[0].x0
489
+ xoffsets -= ([bbox.x0 for bbox in bboxes] - x0)
490
+
491
+ return (Bbox.from_bounds(x0, y0, width, y1 - y0).padded(pad),
492
+ [*zip(xoffsets, yoffsets)])
493
+
494
+
495
+ class PaddedBox(OffsetBox):
496
+ """
497
+ A container to add a padding around an `.Artist`.
498
+
499
+ The `.PaddedBox` contains a `.FancyBboxPatch` that is used to visualize
500
+ it when rendering.
501
+ """
502
+
503
+ def __init__(self, child, pad=0., *, draw_frame=False, patch_attrs=None):
504
+ """
505
+ Parameters
506
+ ----------
507
+ child : `~matplotlib.artist.Artist`
508
+ The contained `.Artist`.
509
+ pad : float, default: 0.0
510
+ The padding in points. This will be scaled with the renderer dpi.
511
+ In contrast, *width* and *height* are in *pixels* and thus not
512
+ scaled.
513
+ draw_frame : bool
514
+ Whether to draw the contained `.FancyBboxPatch`.
515
+ patch_attrs : dict or None
516
+ Additional parameters passed to the contained `.FancyBboxPatch`.
517
+ """
518
+ super().__init__()
519
+ self.pad = pad
520
+ self._children = [child]
521
+ self.patch = FancyBboxPatch(
522
+ xy=(0.0, 0.0), width=1., height=1.,
523
+ facecolor='w', edgecolor='k',
524
+ mutation_scale=1, # self.prop.get_size_in_points(),
525
+ snap=True,
526
+ visible=draw_frame,
527
+ boxstyle="square,pad=0",
528
+ )
529
+ if patch_attrs is not None:
530
+ self.patch.update(patch_attrs)
531
+
532
+ def _get_bbox_and_child_offsets(self, renderer):
533
+ # docstring inherited.
534
+ pad = self.pad * renderer.points_to_pixels(1.)
535
+ return (self._children[0].get_bbox(renderer).padded(pad), [(0, 0)])
536
+
537
+ def draw(self, renderer):
538
+ # docstring inherited
539
+ bbox, offsets = self._get_bbox_and_child_offsets(renderer)
540
+ px, py = self.get_offset(bbox, renderer)
541
+ for c, (ox, oy) in zip(self.get_visible_children(), offsets):
542
+ c.set_offset((px + ox, py + oy))
543
+
544
+ self.draw_frame(renderer)
545
+
546
+ for c in self.get_visible_children():
547
+ c.draw(renderer)
548
+
549
+ self.stale = False
550
+
551
+ def update_frame(self, bbox, fontsize=None):
552
+ self.patch.set_bounds(bbox.bounds)
553
+ if fontsize:
554
+ self.patch.set_mutation_scale(fontsize)
555
+ self.stale = True
556
+
557
+ def draw_frame(self, renderer):
558
+ # update the location and size of the legend
559
+ self.update_frame(self.get_window_extent(renderer))
560
+ self.patch.draw(renderer)
561
+
562
+
563
+ class DrawingArea(OffsetBox):
564
+ """
565
+ The DrawingArea can contain any Artist as a child. The DrawingArea
566
+ has a fixed width and height. The position of children relative to
567
+ the parent is fixed. The children can be clipped at the
568
+ boundaries of the parent.
569
+ """
570
+
571
+ def __init__(self, width, height, xdescent=0., ydescent=0., clip=False):
572
+ """
573
+ Parameters
574
+ ----------
575
+ width, height : float
576
+ Width and height of the container box.
577
+ xdescent, ydescent : float
578
+ Descent of the box in x- and y-direction.
579
+ clip : bool
580
+ Whether to clip the children to the box.
581
+ """
582
+ super().__init__()
583
+ self.width = width
584
+ self.height = height
585
+ self.xdescent = xdescent
586
+ self.ydescent = ydescent
587
+ self._clip_children = clip
588
+ self.offset_transform = mtransforms.Affine2D()
589
+ self.dpi_transform = mtransforms.Affine2D()
590
+
591
+ @property
592
+ def clip_children(self):
593
+ """
594
+ If the children of this DrawingArea should be clipped
595
+ by DrawingArea bounding box.
596
+ """
597
+ return self._clip_children
598
+
599
+ @clip_children.setter
600
+ def clip_children(self, val):
601
+ self._clip_children = bool(val)
602
+ self.stale = True
603
+
604
+ def get_transform(self):
605
+ """
606
+ Return the `~matplotlib.transforms.Transform` applied to the children.
607
+ """
608
+ return self.dpi_transform + self.offset_transform
609
+
610
+ def set_transform(self, t):
611
+ """
612
+ set_transform is ignored.
613
+ """
614
+
615
+ def set_offset(self, xy):
616
+ """
617
+ Set the offset of the container.
618
+
619
+ Parameters
620
+ ----------
621
+ xy : (float, float)
622
+ The (x, y) coordinates of the offset in display units.
623
+ """
624
+ self._offset = xy
625
+ self.offset_transform.clear()
626
+ self.offset_transform.translate(xy[0], xy[1])
627
+ self.stale = True
628
+
629
+ def get_offset(self):
630
+ """Return offset of the container."""
631
+ return self._offset
632
+
633
+ def get_bbox(self, renderer):
634
+ # docstring inherited
635
+ dpi_cor = renderer.points_to_pixels(1.)
636
+ return Bbox.from_bounds(
637
+ -self.xdescent * dpi_cor, -self.ydescent * dpi_cor,
638
+ self.width * dpi_cor, self.height * dpi_cor)
639
+
640
+ def add_artist(self, a):
641
+ """Add an `.Artist` to the container box."""
642
+ self._children.append(a)
643
+ if not a.is_transform_set():
644
+ a.set_transform(self.get_transform())
645
+ if self.axes is not None:
646
+ a.axes = self.axes
647
+ fig = self.figure
648
+ if fig is not None:
649
+ a.set_figure(fig)
650
+
651
+ def draw(self, renderer):
652
+ # docstring inherited
653
+
654
+ dpi_cor = renderer.points_to_pixels(1.)
655
+ self.dpi_transform.clear()
656
+ self.dpi_transform.scale(dpi_cor)
657
+
658
+ # At this point the DrawingArea has a transform
659
+ # to the display space so the path created is
660
+ # good for clipping children
661
+ tpath = mtransforms.TransformedPath(
662
+ mpath.Path([[0, 0], [0, self.height],
663
+ [self.width, self.height],
664
+ [self.width, 0]]),
665
+ self.get_transform())
666
+ for c in self._children:
667
+ if self._clip_children and not (c.clipbox or c._clippath):
668
+ c.set_clip_path(tpath)
669
+ c.draw(renderer)
670
+
671
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
672
+ self.stale = False
673
+
674
+
675
+ class TextArea(OffsetBox):
676
+ """
677
+ The TextArea is a container artist for a single Text instance.
678
+
679
+ The text is placed at (0, 0) with baseline+left alignment, by default. The
680
+ width and height of the TextArea instance is the width and height of its
681
+ child text.
682
+ """
683
+
684
+ def __init__(self, s,
685
+ *,
686
+ textprops=None,
687
+ multilinebaseline=False,
688
+ ):
689
+ """
690
+ Parameters
691
+ ----------
692
+ s : str
693
+ The text to be displayed.
694
+ textprops : dict, default: {}
695
+ Dictionary of keyword parameters to be passed to the `.Text`
696
+ instance in the TextArea.
697
+ multilinebaseline : bool, default: False
698
+ Whether the baseline for multiline text is adjusted so that it
699
+ is (approximately) center-aligned with single-line text.
700
+ """
701
+ if textprops is None:
702
+ textprops = {}
703
+ self._text = mtext.Text(0, 0, s, **textprops)
704
+ super().__init__()
705
+ self._children = [self._text]
706
+ self.offset_transform = mtransforms.Affine2D()
707
+ self._baseline_transform = mtransforms.Affine2D()
708
+ self._text.set_transform(self.offset_transform +
709
+ self._baseline_transform)
710
+ self._multilinebaseline = multilinebaseline
711
+
712
+ def set_text(self, s):
713
+ """Set the text of this area as a string."""
714
+ self._text.set_text(s)
715
+ self.stale = True
716
+
717
+ def get_text(self):
718
+ """Return the string representation of this area's text."""
719
+ return self._text.get_text()
720
+
721
+ def set_multilinebaseline(self, t):
722
+ """
723
+ Set multilinebaseline.
724
+
725
+ If True, the baseline for multiline text is adjusted so that it is
726
+ (approximately) center-aligned with single-line text. This is used
727
+ e.g. by the legend implementation so that single-line labels are
728
+ baseline-aligned, but multiline labels are "center"-aligned with them.
729
+ """
730
+ self._multilinebaseline = t
731
+ self.stale = True
732
+
733
+ def get_multilinebaseline(self):
734
+ """
735
+ Get multilinebaseline.
736
+ """
737
+ return self._multilinebaseline
738
+
739
+ def set_transform(self, t):
740
+ """
741
+ set_transform is ignored.
742
+ """
743
+
744
+ def set_offset(self, xy):
745
+ """
746
+ Set the offset of the container.
747
+
748
+ Parameters
749
+ ----------
750
+ xy : (float, float)
751
+ The (x, y) coordinates of the offset in display units.
752
+ """
753
+ self._offset = xy
754
+ self.offset_transform.clear()
755
+ self.offset_transform.translate(xy[0], xy[1])
756
+ self.stale = True
757
+
758
+ def get_offset(self):
759
+ """Return offset of the container."""
760
+ return self._offset
761
+
762
+ def get_bbox(self, renderer):
763
+ _, h_, d_ = renderer.get_text_width_height_descent(
764
+ "lp", self._text._fontproperties,
765
+ ismath="TeX" if self._text.get_usetex() else False)
766
+
767
+ bbox, info, yd = self._text._get_layout(renderer)
768
+ w, h = bbox.size
769
+
770
+ self._baseline_transform.clear()
771
+
772
+ if len(info) > 1 and self._multilinebaseline:
773
+ yd_new = 0.5 * h - 0.5 * (h_ - d_)
774
+ self._baseline_transform.translate(0, yd - yd_new)
775
+ yd = yd_new
776
+ else: # single line
777
+ h_d = max(h_ - d_, h - yd)
778
+ h = h_d + yd
779
+
780
+ ha = self._text.get_horizontalalignment()
781
+ x0 = {"left": 0, "center": -w / 2, "right": -w}[ha]
782
+
783
+ return Bbox.from_bounds(x0, -yd, w, h)
784
+
785
+ def draw(self, renderer):
786
+ # docstring inherited
787
+ self._text.draw(renderer)
788
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
789
+ self.stale = False
790
+
791
+
792
+ class AuxTransformBox(OffsetBox):
793
+ """
794
+ Offset Box with the aux_transform. Its children will be
795
+ transformed with the aux_transform first then will be
796
+ offsetted. The absolute coordinate of the aux_transform is meaning
797
+ as it will be automatically adjust so that the left-lower corner
798
+ of the bounding box of children will be set to (0, 0) before the
799
+ offset transform.
800
+
801
+ It is similar to drawing area, except that the extent of the box
802
+ is not predetermined but calculated from the window extent of its
803
+ children. Furthermore, the extent of the children will be
804
+ calculated in the transformed coordinate.
805
+ """
806
+ def __init__(self, aux_transform):
807
+ self.aux_transform = aux_transform
808
+ super().__init__()
809
+ self.offset_transform = mtransforms.Affine2D()
810
+ # ref_offset_transform makes offset_transform always relative to the
811
+ # lower-left corner of the bbox of its children.
812
+ self.ref_offset_transform = mtransforms.Affine2D()
813
+
814
+ def add_artist(self, a):
815
+ """Add an `.Artist` to the container box."""
816
+ self._children.append(a)
817
+ a.set_transform(self.get_transform())
818
+ self.stale = True
819
+
820
+ def get_transform(self):
821
+ """
822
+ Return the :class:`~matplotlib.transforms.Transform` applied
823
+ to the children
824
+ """
825
+ return (self.aux_transform
826
+ + self.ref_offset_transform
827
+ + self.offset_transform)
828
+
829
+ def set_transform(self, t):
830
+ """
831
+ set_transform is ignored.
832
+ """
833
+
834
+ def set_offset(self, xy):
835
+ """
836
+ Set the offset of the container.
837
+
838
+ Parameters
839
+ ----------
840
+ xy : (float, float)
841
+ The (x, y) coordinates of the offset in display units.
842
+ """
843
+ self._offset = xy
844
+ self.offset_transform.clear()
845
+ self.offset_transform.translate(xy[0], xy[1])
846
+ self.stale = True
847
+
848
+ def get_offset(self):
849
+ """Return offset of the container."""
850
+ return self._offset
851
+
852
+ def get_bbox(self, renderer):
853
+ # clear the offset transforms
854
+ _off = self.offset_transform.get_matrix() # to be restored later
855
+ self.ref_offset_transform.clear()
856
+ self.offset_transform.clear()
857
+ # calculate the extent
858
+ bboxes = [c.get_window_extent(renderer) for c in self._children]
859
+ ub = Bbox.union(bboxes)
860
+ # adjust ref_offset_transform
861
+ self.ref_offset_transform.translate(-ub.x0, -ub.y0)
862
+ # restore offset transform
863
+ self.offset_transform.set_matrix(_off)
864
+ return Bbox.from_bounds(0, 0, ub.width, ub.height)
865
+
866
+ def draw(self, renderer):
867
+ # docstring inherited
868
+ for c in self._children:
869
+ c.draw(renderer)
870
+ _bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
871
+ self.stale = False
872
+
873
+
874
+ class AnchoredOffsetbox(OffsetBox):
875
+ """
876
+ An offset box placed according to location *loc*.
877
+
878
+ AnchoredOffsetbox has a single child. When multiple children are needed,
879
+ use an extra OffsetBox to enclose them. By default, the offset box is
880
+ anchored against its parent Axes. You may explicitly specify the
881
+ *bbox_to_anchor*.
882
+ """
883
+ zorder = 5 # zorder of the legend
884
+
885
+ # Location codes
886
+ codes = {'upper right': 1,
887
+ 'upper left': 2,
888
+ 'lower left': 3,
889
+ 'lower right': 4,
890
+ 'right': 5,
891
+ 'center left': 6,
892
+ 'center right': 7,
893
+ 'lower center': 8,
894
+ 'upper center': 9,
895
+ 'center': 10,
896
+ }
897
+
898
+ def __init__(self, loc, *,
899
+ pad=0.4, borderpad=0.5,
900
+ child=None, prop=None, frameon=True,
901
+ bbox_to_anchor=None,
902
+ bbox_transform=None,
903
+ **kwargs):
904
+ """
905
+ Parameters
906
+ ----------
907
+ loc : str
908
+ The box location. Valid locations are
909
+ 'upper left', 'upper center', 'upper right',
910
+ 'center left', 'center', 'center right',
911
+ 'lower left', 'lower center', 'lower right'.
912
+ For backward compatibility, numeric values are accepted as well.
913
+ See the parameter *loc* of `.Legend` for details.
914
+ pad : float, default: 0.4
915
+ Padding around the child as fraction of the fontsize.
916
+ borderpad : float, default: 0.5
917
+ Padding between the offsetbox frame and the *bbox_to_anchor*.
918
+ child : `.OffsetBox`
919
+ The box that will be anchored.
920
+ prop : `.FontProperties`
921
+ This is only used as a reference for paddings. If not given,
922
+ :rc:`legend.fontsize` is used.
923
+ frameon : bool
924
+ Whether to draw a frame around the box.
925
+ bbox_to_anchor : `.BboxBase`, 2-tuple, or 4-tuple of floats
926
+ Box that is used to position the legend in conjunction with *loc*.
927
+ bbox_transform : None or :class:`matplotlib.transforms.Transform`
928
+ The transform for the bounding box (*bbox_to_anchor*).
929
+ **kwargs
930
+ All other parameters are passed on to `.OffsetBox`.
931
+
932
+ Notes
933
+ -----
934
+ See `.Legend` for a detailed description of the anchoring mechanism.
935
+ """
936
+ super().__init__(**kwargs)
937
+
938
+ self.set_bbox_to_anchor(bbox_to_anchor, bbox_transform)
939
+ self.set_child(child)
940
+
941
+ if isinstance(loc, str):
942
+ loc = _api.check_getitem(self.codes, loc=loc)
943
+
944
+ self.loc = loc
945
+ self.borderpad = borderpad
946
+ self.pad = pad
947
+
948
+ if prop is None:
949
+ self.prop = FontProperties(size=mpl.rcParams["legend.fontsize"])
950
+ else:
951
+ self.prop = FontProperties._from_any(prop)
952
+ if isinstance(prop, dict) and "size" not in prop:
953
+ self.prop.set_size(mpl.rcParams["legend.fontsize"])
954
+
955
+ self.patch = FancyBboxPatch(
956
+ xy=(0.0, 0.0), width=1., height=1.,
957
+ facecolor='w', edgecolor='k',
958
+ mutation_scale=self.prop.get_size_in_points(),
959
+ snap=True,
960
+ visible=frameon,
961
+ boxstyle="square,pad=0",
962
+ )
963
+
964
+ def set_child(self, child):
965
+ """Set the child to be anchored."""
966
+ self._child = child
967
+ if child is not None:
968
+ child.axes = self.axes
969
+ self.stale = True
970
+
971
+ def get_child(self):
972
+ """Return the child."""
973
+ return self._child
974
+
975
+ def get_children(self):
976
+ """Return the list of children."""
977
+ return [self._child]
978
+
979
+ def get_bbox(self, renderer):
980
+ # docstring inherited
981
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
982
+ pad = self.pad * fontsize
983
+ return self.get_child().get_bbox(renderer).padded(pad)
984
+
985
+ def get_bbox_to_anchor(self):
986
+ """Return the bbox that the box is anchored to."""
987
+ if self._bbox_to_anchor is None:
988
+ return self.axes.bbox
989
+ else:
990
+ transform = self._bbox_to_anchor_transform
991
+ if transform is None:
992
+ return self._bbox_to_anchor
993
+ else:
994
+ return TransformedBbox(self._bbox_to_anchor, transform)
995
+
996
+ def set_bbox_to_anchor(self, bbox, transform=None):
997
+ """
998
+ Set the bbox that the box is anchored to.
999
+
1000
+ *bbox* can be a Bbox instance, a list of [left, bottom, width,
1001
+ height], or a list of [left, bottom] where the width and
1002
+ height will be assumed to be zero. The bbox will be
1003
+ transformed to display coordinate by the given transform.
1004
+ """
1005
+ if bbox is None or isinstance(bbox, BboxBase):
1006
+ self._bbox_to_anchor = bbox
1007
+ else:
1008
+ try:
1009
+ l = len(bbox)
1010
+ except TypeError as err:
1011
+ raise ValueError(f"Invalid bbox: {bbox}") from err
1012
+
1013
+ if l == 2:
1014
+ bbox = [bbox[0], bbox[1], 0, 0]
1015
+
1016
+ self._bbox_to_anchor = Bbox.from_bounds(*bbox)
1017
+
1018
+ self._bbox_to_anchor_transform = transform
1019
+ self.stale = True
1020
+
1021
+ @_compat_get_offset
1022
+ def get_offset(self, bbox, renderer):
1023
+ # docstring inherited
1024
+ pad = (self.borderpad
1025
+ * renderer.points_to_pixels(self.prop.get_size_in_points()))
1026
+ bbox_to_anchor = self.get_bbox_to_anchor()
1027
+ x0, y0 = _get_anchored_bbox(
1028
+ self.loc, Bbox.from_bounds(0, 0, bbox.width, bbox.height),
1029
+ bbox_to_anchor, pad)
1030
+ return x0 - bbox.x0, y0 - bbox.y0
1031
+
1032
+ def update_frame(self, bbox, fontsize=None):
1033
+ self.patch.set_bounds(bbox.bounds)
1034
+ if fontsize:
1035
+ self.patch.set_mutation_scale(fontsize)
1036
+
1037
+ def draw(self, renderer):
1038
+ # docstring inherited
1039
+ if not self.get_visible():
1040
+ return
1041
+
1042
+ # update the location and size of the legend
1043
+ bbox = self.get_window_extent(renderer)
1044
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
1045
+ self.update_frame(bbox, fontsize)
1046
+ self.patch.draw(renderer)
1047
+
1048
+ px, py = self.get_offset(self.get_bbox(renderer), renderer)
1049
+ self.get_child().set_offset((px, py))
1050
+ self.get_child().draw(renderer)
1051
+ self.stale = False
1052
+
1053
+
1054
+ def _get_anchored_bbox(loc, bbox, parentbbox, borderpad):
1055
+ """
1056
+ Return the (x, y) position of the *bbox* anchored at the *parentbbox* with
1057
+ the *loc* code with the *borderpad*.
1058
+ """
1059
+ # This is only called internally and *loc* should already have been
1060
+ # validated. If 0 (None), we just let ``bbox.anchored`` raise.
1061
+ c = [None, "NE", "NW", "SW", "SE", "E", "W", "E", "S", "N", "C"][loc]
1062
+ container = parentbbox.padded(-borderpad)
1063
+ return bbox.anchored(c, container=container).p0
1064
+
1065
+
1066
+ class AnchoredText(AnchoredOffsetbox):
1067
+ """
1068
+ AnchoredOffsetbox with Text.
1069
+ """
1070
+
1071
+ def __init__(self, s, loc, *, pad=0.4, borderpad=0.5, prop=None, **kwargs):
1072
+ """
1073
+ Parameters
1074
+ ----------
1075
+ s : str
1076
+ Text.
1077
+
1078
+ loc : str
1079
+ Location code. See `AnchoredOffsetbox`.
1080
+
1081
+ pad : float, default: 0.4
1082
+ Padding around the text as fraction of the fontsize.
1083
+
1084
+ borderpad : float, default: 0.5
1085
+ Spacing between the offsetbox frame and the *bbox_to_anchor*.
1086
+
1087
+ prop : dict, optional
1088
+ Dictionary of keyword parameters to be passed to the
1089
+ `~matplotlib.text.Text` instance contained inside AnchoredText.
1090
+
1091
+ **kwargs
1092
+ All other parameters are passed to `AnchoredOffsetbox`.
1093
+ """
1094
+
1095
+ if prop is None:
1096
+ prop = {}
1097
+ badkwargs = {'va', 'verticalalignment'}
1098
+ if badkwargs & set(prop):
1099
+ raise ValueError(
1100
+ 'Mixing verticalalignment with AnchoredText is not supported.')
1101
+
1102
+ self.txt = TextArea(s, textprops=prop)
1103
+ fp = self.txt._text.get_fontproperties()
1104
+ super().__init__(
1105
+ loc, pad=pad, borderpad=borderpad, child=self.txt, prop=fp,
1106
+ **kwargs)
1107
+
1108
+
1109
+ class OffsetImage(OffsetBox):
1110
+
1111
+ def __init__(self, arr, *,
1112
+ zoom=1,
1113
+ cmap=None,
1114
+ norm=None,
1115
+ interpolation=None,
1116
+ origin=None,
1117
+ filternorm=True,
1118
+ filterrad=4.0,
1119
+ resample=False,
1120
+ dpi_cor=True,
1121
+ **kwargs
1122
+ ):
1123
+
1124
+ super().__init__()
1125
+ self._dpi_cor = dpi_cor
1126
+
1127
+ self.image = BboxImage(bbox=self.get_window_extent,
1128
+ cmap=cmap,
1129
+ norm=norm,
1130
+ interpolation=interpolation,
1131
+ origin=origin,
1132
+ filternorm=filternorm,
1133
+ filterrad=filterrad,
1134
+ resample=resample,
1135
+ **kwargs
1136
+ )
1137
+
1138
+ self._children = [self.image]
1139
+
1140
+ self.set_zoom(zoom)
1141
+ self.set_data(arr)
1142
+
1143
+ def set_data(self, arr):
1144
+ self._data = np.asarray(arr)
1145
+ self.image.set_data(self._data)
1146
+ self.stale = True
1147
+
1148
+ def get_data(self):
1149
+ return self._data
1150
+
1151
+ def set_zoom(self, zoom):
1152
+ self._zoom = zoom
1153
+ self.stale = True
1154
+
1155
+ def get_zoom(self):
1156
+ return self._zoom
1157
+
1158
+ def get_offset(self):
1159
+ """Return offset of the container."""
1160
+ return self._offset
1161
+
1162
+ def get_children(self):
1163
+ return [self.image]
1164
+
1165
+ def get_bbox(self, renderer):
1166
+ dpi_cor = renderer.points_to_pixels(1.) if self._dpi_cor else 1.
1167
+ zoom = self.get_zoom()
1168
+ data = self.get_data()
1169
+ ny, nx = data.shape[:2]
1170
+ w, h = dpi_cor * nx * zoom, dpi_cor * ny * zoom
1171
+ return Bbox.from_bounds(0, 0, w, h)
1172
+
1173
+ def draw(self, renderer):
1174
+ # docstring inherited
1175
+ self.image.draw(renderer)
1176
+ # bbox_artist(self, renderer, fill=False, props=dict(pad=0.))
1177
+ self.stale = False
1178
+
1179
+
1180
+ class AnnotationBbox(martist.Artist, mtext._AnnotationBase):
1181
+ """
1182
+ Container for an `OffsetBox` referring to a specific position *xy*.
1183
+
1184
+ Optionally an arrow pointing from the offsetbox to *xy* can be drawn.
1185
+
1186
+ This is like `.Annotation`, but with `OffsetBox` instead of `.Text`.
1187
+ """
1188
+
1189
+ zorder = 3
1190
+
1191
+ def __str__(self):
1192
+ return f"AnnotationBbox({self.xy[0]:g},{self.xy[1]:g})"
1193
+
1194
+ @_docstring.dedent_interpd
1195
+ def __init__(self, offsetbox, xy, xybox=None, xycoords='data', boxcoords=None, *,
1196
+ frameon=True, pad=0.4, # FancyBboxPatch boxstyle.
1197
+ annotation_clip=None,
1198
+ box_alignment=(0.5, 0.5),
1199
+ bboxprops=None,
1200
+ arrowprops=None,
1201
+ fontsize=None,
1202
+ **kwargs):
1203
+ """
1204
+ Parameters
1205
+ ----------
1206
+ offsetbox : `OffsetBox`
1207
+
1208
+ xy : (float, float)
1209
+ The point *(x, y)* to annotate. The coordinate system is determined
1210
+ by *xycoords*.
1211
+
1212
+ xybox : (float, float), default: *xy*
1213
+ The position *(x, y)* to place the text at. The coordinate system
1214
+ is determined by *boxcoords*.
1215
+
1216
+ xycoords : single or two-tuple of str or `.Artist` or `.Transform` or \
1217
+ callable, default: 'data'
1218
+ The coordinate system that *xy* is given in. See the parameter
1219
+ *xycoords* in `.Annotation` for a detailed description.
1220
+
1221
+ boxcoords : single or two-tuple of str or `.Artist` or `.Transform` \
1222
+ or callable, default: value of *xycoords*
1223
+ The coordinate system that *xybox* is given in. See the parameter
1224
+ *textcoords* in `.Annotation` for a detailed description.
1225
+
1226
+ frameon : bool, default: True
1227
+ By default, the text is surrounded by a white `.FancyBboxPatch`
1228
+ (accessible as the ``patch`` attribute of the `.AnnotationBbox`).
1229
+ If *frameon* is set to False, this patch is made invisible.
1230
+
1231
+ annotation_clip: bool or None, default: None
1232
+ Whether to clip (i.e. not draw) the annotation when the annotation
1233
+ point *xy* is outside the Axes area.
1234
+
1235
+ - If *True*, the annotation will be clipped when *xy* is outside
1236
+ the Axes.
1237
+ - If *False*, the annotation will always be drawn.
1238
+ - If *None*, the annotation will be clipped when *xy* is outside
1239
+ the Axes and *xycoords* is 'data'.
1240
+
1241
+ pad : float, default: 0.4
1242
+ Padding around the offsetbox.
1243
+
1244
+ box_alignment : (float, float)
1245
+ A tuple of two floats for a vertical and horizontal alignment of
1246
+ the offset box w.r.t. the *boxcoords*.
1247
+ The lower-left corner is (0, 0) and upper-right corner is (1, 1).
1248
+
1249
+ bboxprops : dict, optional
1250
+ A dictionary of properties to set for the annotation bounding box,
1251
+ for example *boxstyle* and *alpha*. See `.FancyBboxPatch` for
1252
+ details.
1253
+
1254
+ arrowprops: dict, optional
1255
+ Arrow properties, see `.Annotation` for description.
1256
+
1257
+ fontsize: float or str, optional
1258
+ Translated to points and passed as *mutation_scale* into
1259
+ `.FancyBboxPatch` to scale attributes of the box style (e.g. pad
1260
+ or rounding_size). The name is chosen in analogy to `.Text` where
1261
+ *fontsize* defines the mutation scale as well. If not given,
1262
+ :rc:`legend.fontsize` is used. See `.Text.set_fontsize` for valid
1263
+ values.
1264
+
1265
+ **kwargs
1266
+ Other `AnnotationBbox` properties. See `.AnnotationBbox.set` for
1267
+ a list.
1268
+ """
1269
+
1270
+ martist.Artist.__init__(self)
1271
+ mtext._AnnotationBase.__init__(
1272
+ self, xy, xycoords=xycoords, annotation_clip=annotation_clip)
1273
+
1274
+ self.offsetbox = offsetbox
1275
+ self.arrowprops = arrowprops.copy() if arrowprops is not None else None
1276
+ self.set_fontsize(fontsize)
1277
+ self.xybox = xybox if xybox is not None else xy
1278
+ self.boxcoords = boxcoords if boxcoords is not None else xycoords
1279
+ self._box_alignment = box_alignment
1280
+
1281
+ if arrowprops is not None:
1282
+ self._arrow_relpos = self.arrowprops.pop("relpos", (0.5, 0.5))
1283
+ self.arrow_patch = FancyArrowPatch((0, 0), (1, 1),
1284
+ **self.arrowprops)
1285
+ else:
1286
+ self._arrow_relpos = None
1287
+ self.arrow_patch = None
1288
+
1289
+ self.patch = FancyBboxPatch( # frame
1290
+ xy=(0.0, 0.0), width=1., height=1.,
1291
+ facecolor='w', edgecolor='k',
1292
+ mutation_scale=self.prop.get_size_in_points(),
1293
+ snap=True,
1294
+ visible=frameon,
1295
+ )
1296
+ self.patch.set_boxstyle("square", pad=pad)
1297
+ if bboxprops:
1298
+ self.patch.set(**bboxprops)
1299
+
1300
+ self._internal_update(kwargs)
1301
+
1302
+ @property
1303
+ def xyann(self):
1304
+ return self.xybox
1305
+
1306
+ @xyann.setter
1307
+ def xyann(self, xyann):
1308
+ self.xybox = xyann
1309
+ self.stale = True
1310
+
1311
+ @property
1312
+ def anncoords(self):
1313
+ return self.boxcoords
1314
+
1315
+ @anncoords.setter
1316
+ def anncoords(self, coords):
1317
+ self.boxcoords = coords
1318
+ self.stale = True
1319
+
1320
+ def contains(self, mouseevent):
1321
+ if self._different_canvas(mouseevent):
1322
+ return False, {}
1323
+ if not self._check_xy(None):
1324
+ return False, {}
1325
+ return self.offsetbox.contains(mouseevent)
1326
+ # self.arrow_patch is currently not checked as this can be a line - JJ
1327
+
1328
+ def get_children(self):
1329
+ children = [self.offsetbox, self.patch]
1330
+ if self.arrow_patch:
1331
+ children.append(self.arrow_patch)
1332
+ return children
1333
+
1334
+ def set_figure(self, fig):
1335
+ if self.arrow_patch is not None:
1336
+ self.arrow_patch.set_figure(fig)
1337
+ self.offsetbox.set_figure(fig)
1338
+ martist.Artist.set_figure(self, fig)
1339
+
1340
+ def set_fontsize(self, s=None):
1341
+ """
1342
+ Set the fontsize in points.
1343
+
1344
+ If *s* is not given, reset to :rc:`legend.fontsize`.
1345
+ """
1346
+ if s is None:
1347
+ s = mpl.rcParams["legend.fontsize"]
1348
+
1349
+ self.prop = FontProperties(size=s)
1350
+ self.stale = True
1351
+
1352
+ def get_fontsize(self):
1353
+ """Return the fontsize in points."""
1354
+ return self.prop.get_size_in_points()
1355
+
1356
+ def get_window_extent(self, renderer=None):
1357
+ # docstring inherited
1358
+ if renderer is None:
1359
+ renderer = self.figure._get_renderer()
1360
+ self.update_positions(renderer)
1361
+ return Bbox.union([child.get_window_extent(renderer)
1362
+ for child in self.get_children()])
1363
+
1364
+ def get_tightbbox(self, renderer=None):
1365
+ # docstring inherited
1366
+ if renderer is None:
1367
+ renderer = self.figure._get_renderer()
1368
+ self.update_positions(renderer)
1369
+ return Bbox.union([child.get_tightbbox(renderer)
1370
+ for child in self.get_children()])
1371
+
1372
+ def update_positions(self, renderer):
1373
+ """Update pixel positions for the annotated point, the text, and the arrow."""
1374
+
1375
+ ox0, oy0 = self._get_xy(renderer, self.xybox, self.boxcoords)
1376
+ bbox = self.offsetbox.get_bbox(renderer)
1377
+ fw, fh = self._box_alignment
1378
+ self.offsetbox.set_offset(
1379
+ (ox0 - fw*bbox.width - bbox.x0, oy0 - fh*bbox.height - bbox.y0))
1380
+
1381
+ bbox = self.offsetbox.get_window_extent(renderer)
1382
+ self.patch.set_bounds(bbox.bounds)
1383
+
1384
+ mutation_scale = renderer.points_to_pixels(self.get_fontsize())
1385
+ self.patch.set_mutation_scale(mutation_scale)
1386
+
1387
+ if self.arrowprops:
1388
+ # Use FancyArrowPatch if self.arrowprops has "arrowstyle" key.
1389
+
1390
+ # Adjust the starting point of the arrow relative to the textbox.
1391
+ # TODO: Rotation needs to be accounted.
1392
+ arrow_begin = bbox.p0 + bbox.size * self._arrow_relpos
1393
+ arrow_end = self._get_position_xy(renderer)
1394
+ # The arrow (from arrow_begin to arrow_end) will be first clipped
1395
+ # by patchA and patchB, then shrunk by shrinkA and shrinkB (in
1396
+ # points). If patch A is not set, self.bbox_patch is used.
1397
+ self.arrow_patch.set_positions(arrow_begin, arrow_end)
1398
+
1399
+ if "mutation_scale" in self.arrowprops:
1400
+ mutation_scale = renderer.points_to_pixels(
1401
+ self.arrowprops["mutation_scale"])
1402
+ # Else, use fontsize-based mutation_scale defined above.
1403
+ self.arrow_patch.set_mutation_scale(mutation_scale)
1404
+
1405
+ patchA = self.arrowprops.get("patchA", self.patch)
1406
+ self.arrow_patch.set_patchA(patchA)
1407
+
1408
+ def draw(self, renderer):
1409
+ # docstring inherited
1410
+ if not self.get_visible() or not self._check_xy(renderer):
1411
+ return
1412
+ renderer.open_group(self.__class__.__name__, gid=self.get_gid())
1413
+ self.update_positions(renderer)
1414
+ if self.arrow_patch is not None:
1415
+ if self.arrow_patch.figure is None and self.figure is not None:
1416
+ self.arrow_patch.figure = self.figure
1417
+ self.arrow_patch.draw(renderer)
1418
+ self.patch.draw(renderer)
1419
+ self.offsetbox.draw(renderer)
1420
+ renderer.close_group(self.__class__.__name__)
1421
+ self.stale = False
1422
+
1423
+
1424
+ class DraggableBase:
1425
+ """
1426
+ Helper base class for a draggable artist (legend, offsetbox).
1427
+
1428
+ Derived classes must override the following methods::
1429
+
1430
+ def save_offset(self):
1431
+ '''
1432
+ Called when the object is picked for dragging; should save the
1433
+ reference position of the artist.
1434
+ '''
1435
+
1436
+ def update_offset(self, dx, dy):
1437
+ '''
1438
+ Called during the dragging; (*dx*, *dy*) is the pixel offset from
1439
+ the point where the mouse drag started.
1440
+ '''
1441
+
1442
+ Optionally, you may override the following method::
1443
+
1444
+ def finalize_offset(self):
1445
+ '''Called when the mouse is released.'''
1446
+
1447
+ In the current implementation of `.DraggableLegend` and
1448
+ `DraggableAnnotation`, `update_offset` places the artists in display
1449
+ coordinates, and `finalize_offset` recalculates their position in axes
1450
+ coordinate and set a relevant attribute.
1451
+ """
1452
+
1453
+ def __init__(self, ref_artist, use_blit=False):
1454
+ self.ref_artist = ref_artist
1455
+ if not ref_artist.pickable():
1456
+ ref_artist.set_picker(True)
1457
+ self.got_artist = False
1458
+ self._use_blit = use_blit and self.canvas.supports_blit
1459
+ callbacks = self.canvas.callbacks
1460
+ self._disconnectors = [
1461
+ functools.partial(
1462
+ callbacks.disconnect, callbacks._connect_picklable(name, func))
1463
+ for name, func in [
1464
+ ("pick_event", self.on_pick),
1465
+ ("button_release_event", self.on_release),
1466
+ ("motion_notify_event", self.on_motion),
1467
+ ]
1468
+ ]
1469
+
1470
+ # A property, not an attribute, to maintain picklability.
1471
+ canvas = property(lambda self: self.ref_artist.figure.canvas)
1472
+ cids = property(lambda self: [
1473
+ disconnect.args[0] for disconnect in self._disconnectors[:2]])
1474
+
1475
+ def on_motion(self, evt):
1476
+ if self._check_still_parented() and self.got_artist:
1477
+ dx = evt.x - self.mouse_x
1478
+ dy = evt.y - self.mouse_y
1479
+ self.update_offset(dx, dy)
1480
+ if self._use_blit:
1481
+ self.canvas.restore_region(self.background)
1482
+ self.ref_artist.draw(
1483
+ self.ref_artist.figure._get_renderer())
1484
+ self.canvas.blit()
1485
+ else:
1486
+ self.canvas.draw()
1487
+
1488
+ def on_pick(self, evt):
1489
+ if self._check_still_parented() and evt.artist == self.ref_artist:
1490
+ self.mouse_x = evt.mouseevent.x
1491
+ self.mouse_y = evt.mouseevent.y
1492
+ self.got_artist = True
1493
+ if self._use_blit:
1494
+ self.ref_artist.set_animated(True)
1495
+ self.canvas.draw()
1496
+ self.background = \
1497
+ self.canvas.copy_from_bbox(self.ref_artist.figure.bbox)
1498
+ self.ref_artist.draw(
1499
+ self.ref_artist.figure._get_renderer())
1500
+ self.canvas.blit()
1501
+ self.save_offset()
1502
+
1503
+ def on_release(self, event):
1504
+ if self._check_still_parented() and self.got_artist:
1505
+ self.finalize_offset()
1506
+ self.got_artist = False
1507
+ if self._use_blit:
1508
+ self.ref_artist.set_animated(False)
1509
+
1510
+ def _check_still_parented(self):
1511
+ if self.ref_artist.figure is None:
1512
+ self.disconnect()
1513
+ return False
1514
+ else:
1515
+ return True
1516
+
1517
+ def disconnect(self):
1518
+ """Disconnect the callbacks."""
1519
+ for disconnector in self._disconnectors:
1520
+ disconnector()
1521
+
1522
+ def save_offset(self):
1523
+ pass
1524
+
1525
+ def update_offset(self, dx, dy):
1526
+ pass
1527
+
1528
+ def finalize_offset(self):
1529
+ pass
1530
+
1531
+
1532
+ class DraggableOffsetBox(DraggableBase):
1533
+ def __init__(self, ref_artist, offsetbox, use_blit=False):
1534
+ super().__init__(ref_artist, use_blit=use_blit)
1535
+ self.offsetbox = offsetbox
1536
+
1537
+ def save_offset(self):
1538
+ offsetbox = self.offsetbox
1539
+ renderer = offsetbox.figure._get_renderer()
1540
+ offset = offsetbox.get_offset(offsetbox.get_bbox(renderer), renderer)
1541
+ self.offsetbox_x, self.offsetbox_y = offset
1542
+ self.offsetbox.set_offset(offset)
1543
+
1544
+ def update_offset(self, dx, dy):
1545
+ loc_in_canvas = self.offsetbox_x + dx, self.offsetbox_y + dy
1546
+ self.offsetbox.set_offset(loc_in_canvas)
1547
+
1548
+ def get_loc_in_canvas(self):
1549
+ offsetbox = self.offsetbox
1550
+ renderer = offsetbox.figure._get_renderer()
1551
+ bbox = offsetbox.get_bbox(renderer)
1552
+ ox, oy = offsetbox._offset
1553
+ loc_in_canvas = (ox + bbox.x0, oy + bbox.y0)
1554
+ return loc_in_canvas
1555
+
1556
+
1557
+ class DraggableAnnotation(DraggableBase):
1558
+ def __init__(self, annotation, use_blit=False):
1559
+ super().__init__(annotation, use_blit=use_blit)
1560
+ self.annotation = annotation
1561
+
1562
+ def save_offset(self):
1563
+ ann = self.annotation
1564
+ self.ox, self.oy = ann.get_transform().transform(ann.xyann)
1565
+
1566
+ def update_offset(self, dx, dy):
1567
+ ann = self.annotation
1568
+ ann.xyann = ann.get_transform().inverted().transform(
1569
+ (self.ox + dx, self.oy + dy))
llava_next/lib/python3.10/site-packages/matplotlib/patches.pyi ADDED
@@ -0,0 +1,755 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from . import artist
2
+ from .axes import Axes
3
+ from .backend_bases import RendererBase, MouseEvent
4
+ from .path import Path
5
+ from .transforms import Transform, Bbox
6
+
7
+ from typing import Any, Literal, overload
8
+
9
+ import numpy as np
10
+ from numpy.typing import ArrayLike
11
+ from .typing import ColorType, LineStyleType, CapStyleType, JoinStyleType
12
+
13
+ class Patch(artist.Artist):
14
+ zorder: float
15
+ def __init__(
16
+ self,
17
+ *,
18
+ edgecolor: ColorType | None = ...,
19
+ facecolor: ColorType | None = ...,
20
+ color: ColorType | None = ...,
21
+ linewidth: float | None = ...,
22
+ linestyle: LineStyleType | None = ...,
23
+ antialiased: bool | None = ...,
24
+ hatch: str | None = ...,
25
+ fill: bool = ...,
26
+ capstyle: CapStyleType | None = ...,
27
+ joinstyle: JoinStyleType | None = ...,
28
+ **kwargs,
29
+ ) -> None: ...
30
+ def get_verts(self) -> ArrayLike: ...
31
+ def contains(self, mouseevent: MouseEvent, radius: float | None = None) -> tuple[bool, dict[Any, Any]]: ...
32
+ def contains_point(
33
+ self, point: tuple[float, float], radius: float | None = ...
34
+ ) -> bool: ...
35
+ def contains_points(
36
+ self, points: ArrayLike, radius: float | None = ...
37
+ ) -> np.ndarray: ...
38
+ def get_extents(self) -> Bbox: ...
39
+ def get_transform(self) -> Transform: ...
40
+ def get_data_transform(self) -> Transform: ...
41
+ def get_patch_transform(self) -> Transform: ...
42
+ def get_antialiased(self) -> bool: ...
43
+ def get_edgecolor(self) -> ColorType: ...
44
+ def get_facecolor(self) -> ColorType: ...
45
+ def get_linewidth(self) -> float: ...
46
+ def get_linestyle(self) -> LineStyleType: ...
47
+ def set_antialiased(self, aa: bool | None) -> None: ...
48
+ def set_edgecolor(self, color: ColorType | None) -> None: ...
49
+ def set_facecolor(self, color: ColorType | None) -> None: ...
50
+ def set_color(self, c: ColorType | None) -> None: ...
51
+ def set_alpha(self, alpha: float | None) -> None: ...
52
+ def set_linewidth(self, w: float | None) -> None: ...
53
+ def set_linestyle(self, ls: LineStyleType | None) -> None: ...
54
+ def set_fill(self, b: bool) -> None: ...
55
+ def get_fill(self) -> bool: ...
56
+ fill = property(get_fill, set_fill)
57
+ def set_capstyle(self, s: CapStyleType) -> None: ...
58
+ def get_capstyle(self) -> Literal["butt", "projecting", "round"]: ...
59
+ def set_joinstyle(self, s: JoinStyleType) -> None: ...
60
+ def get_joinstyle(self) -> Literal["miter", "round", "bevel"]: ...
61
+ def set_hatch(self, hatch: str) -> None: ...
62
+ def get_hatch(self) -> str: ...
63
+ def get_path(self) -> Path: ...
64
+
65
+ class Shadow(Patch):
66
+ patch: Patch
67
+ def __init__(self, patch: Patch, ox: float, oy: float, *, shade: float = ..., **kwargs) -> None: ...
68
+
69
+ class Rectangle(Patch):
70
+ angle: float
71
+ def __init__(
72
+ self,
73
+ xy: tuple[float, float],
74
+ width: float,
75
+ height: float,
76
+ *,
77
+ angle: float = ...,
78
+ rotation_point: Literal["xy", "center"] | tuple[float, float] = ...,
79
+ **kwargs,
80
+ ) -> None: ...
81
+ @property
82
+ def rotation_point(self) -> Literal["xy", "center"] | tuple[float, float]: ...
83
+ @rotation_point.setter
84
+ def rotation_point(
85
+ self, value: Literal["xy", "center"] | tuple[float, float]
86
+ ) -> None: ...
87
+ def get_x(self) -> float: ...
88
+ def get_y(self) -> float: ...
89
+ def get_xy(self) -> tuple[float, float]: ...
90
+ def get_corners(self) -> np.ndarray: ...
91
+ def get_center(self) -> np.ndarray: ...
92
+ def get_width(self) -> float: ...
93
+ def get_height(self) -> float: ...
94
+ def get_angle(self) -> float: ...
95
+ def set_x(self, x: float) -> None: ...
96
+ def set_y(self, y: float) -> None: ...
97
+ def set_angle(self, angle: float) -> None: ...
98
+ def set_xy(self, xy: tuple[float, float]) -> None: ...
99
+ def set_width(self, w: float) -> None: ...
100
+ def set_height(self, h: float) -> None: ...
101
+ @overload
102
+ def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ...
103
+ @overload
104
+ def set_bounds(
105
+ self, left: float, bottom: float, width: float, height: float, /
106
+ ) -> None: ...
107
+ def get_bbox(self) -> Bbox: ...
108
+ xy = property(get_xy, set_xy)
109
+
110
+ class RegularPolygon(Patch):
111
+ xy: tuple[float, float]
112
+ numvertices: int
113
+ orientation: float
114
+ radius: float
115
+ def __init__(
116
+ self,
117
+ xy: tuple[float, float],
118
+ numVertices: int,
119
+ *,
120
+ radius: float = ...,
121
+ orientation: float = ...,
122
+ **kwargs,
123
+ ) -> None: ...
124
+
125
+ class PathPatch(Patch):
126
+ def __init__(self, path: Path, **kwargs) -> None: ...
127
+ def set_path(self, path: Path) -> None: ...
128
+
129
+ class StepPatch(PathPatch):
130
+ orientation: Literal["vertical", "horizontal"]
131
+ def __init__(
132
+ self,
133
+ values: ArrayLike,
134
+ edges: ArrayLike,
135
+ *,
136
+ orientation: Literal["vertical", "horizontal"] = ...,
137
+ baseline: float = ...,
138
+ **kwargs,
139
+ ) -> None: ...
140
+
141
+ # NamedTuple StairData, defined in body of method
142
+ def get_data(self) -> tuple[np.ndarray, np.ndarray, float]: ...
143
+ def set_data(
144
+ self,
145
+ values: ArrayLike | None = ...,
146
+ edges: ArrayLike | None = ...,
147
+ baseline: float | None = ...,
148
+ ) -> None: ...
149
+
150
+ class Polygon(Patch):
151
+ def __init__(self, xy: ArrayLike, *, closed: bool = ..., **kwargs) -> None: ...
152
+ def get_closed(self) -> bool: ...
153
+ def set_closed(self, closed: bool) -> None: ...
154
+ def get_xy(self) -> np.ndarray: ...
155
+ def set_xy(self, xy: ArrayLike) -> None: ...
156
+ xy = property(get_xy, set_xy)
157
+
158
+ class Wedge(Patch):
159
+ center: tuple[float, float]
160
+ r: float
161
+ theta1: float
162
+ theta2: float
163
+ width: float | None
164
+ def __init__(
165
+ self,
166
+ center: tuple[float, float],
167
+ r: float,
168
+ theta1: float,
169
+ theta2: float,
170
+ *,
171
+ width: float | None = ...,
172
+ **kwargs,
173
+ ) -> None: ...
174
+ def set_center(self, center: tuple[float, float]) -> None: ...
175
+ def set_radius(self, radius: float) -> None: ...
176
+ def set_theta1(self, theta1: float) -> None: ...
177
+ def set_theta2(self, theta2: float) -> None: ...
178
+ def set_width(self, width: float | None) -> None: ...
179
+
180
+ class Arrow(Patch):
181
+ def __init__(
182
+ self, x: float, y: float, dx: float, dy: float, *, width: float = ..., **kwargs
183
+ ) -> None: ...
184
+ def set_data(
185
+ self,
186
+ x: float | None = ...,
187
+ y: float | None = ...,
188
+ dx: float | None = ...,
189
+ dy: float | None = ...,
190
+ width: float | None = ...,
191
+ ) -> None: ...
192
+ class FancyArrow(Polygon):
193
+ def __init__(
194
+ self,
195
+ x: float,
196
+ y: float,
197
+ dx: float,
198
+ dy: float,
199
+ *,
200
+ width: float = ...,
201
+ length_includes_head: bool = ...,
202
+ head_width: float | None = ...,
203
+ head_length: float | None = ...,
204
+ shape: Literal["full", "left", "right"] = ...,
205
+ overhang: float = ...,
206
+ head_starts_at_zero: bool = ...,
207
+ **kwargs,
208
+ ) -> None: ...
209
+ def set_data(
210
+ self,
211
+ *,
212
+ x: float | None = ...,
213
+ y: float | None = ...,
214
+ dx: float | None = ...,
215
+ dy: float | None = ...,
216
+ width: float | None = ...,
217
+ head_width: float | None = ...,
218
+ head_length: float | None = ...,
219
+ ) -> None: ...
220
+
221
+ class CirclePolygon(RegularPolygon):
222
+ def __init__(
223
+ self,
224
+ xy: tuple[float, float],
225
+ radius: float = ...,
226
+ *,
227
+ resolution: int = ...,
228
+ **kwargs,
229
+ ) -> None: ...
230
+
231
+ class Ellipse(Patch):
232
+ def __init__(
233
+ self,
234
+ xy: tuple[float, float],
235
+ width: float,
236
+ height: float,
237
+ *,
238
+ angle: float = ...,
239
+ **kwargs,
240
+ ) -> None: ...
241
+ def set_center(self, xy: tuple[float, float]) -> None: ...
242
+ def get_center(self) -> float: ...
243
+ center = property(get_center, set_center)
244
+
245
+ def set_width(self, width: float) -> None: ...
246
+ def get_width(self) -> float: ...
247
+ width = property(get_width, set_width)
248
+
249
+ def set_height(self, height: float) -> None: ...
250
+ def get_height(self) -> float: ...
251
+ height = property(get_height, set_height)
252
+
253
+ def set_angle(self, angle: float) -> None: ...
254
+ def get_angle(self) -> float: ...
255
+ angle = property(get_angle, set_angle)
256
+
257
+ def get_corners(self) -> np.ndarray: ...
258
+
259
+ def get_vertices(self) -> list[tuple[float, float]]: ...
260
+ def get_co_vertices(self) -> list[tuple[float, float]]: ...
261
+
262
+
263
+ class Annulus(Patch):
264
+ a: float
265
+ b: float
266
+ def __init__(
267
+ self,
268
+ xy: tuple[float, float],
269
+ r: float | tuple[float, float],
270
+ width: float,
271
+ angle: float = ...,
272
+ **kwargs,
273
+ ) -> None: ...
274
+ def set_center(self, xy: tuple[float, float]) -> None: ...
275
+ def get_center(self) -> tuple[float, float]: ...
276
+ center = property(get_center, set_center)
277
+
278
+ def set_width(self, width: float) -> None: ...
279
+ def get_width(self) -> float: ...
280
+ width = property(get_width, set_width)
281
+
282
+ def set_angle(self, angle: float) -> None: ...
283
+ def get_angle(self) -> float: ...
284
+ angle = property(get_angle, set_angle)
285
+
286
+ def set_semimajor(self, a: float) -> None: ...
287
+ def set_semiminor(self, b: float) -> None: ...
288
+ def set_radii(self, r: float | tuple[float, float]) -> None: ...
289
+ def get_radii(self) -> tuple[float, float]: ...
290
+ radii = property(get_radii, set_radii)
291
+
292
+ class Circle(Ellipse):
293
+ def __init__(
294
+ self, xy: tuple[float, float], radius: float = ..., **kwargs
295
+ ) -> None: ...
296
+ def set_radius(self, radius: float) -> None: ...
297
+ def get_radius(self) -> float: ...
298
+ radius = property(get_radius, set_radius)
299
+
300
+ class Arc(Ellipse):
301
+ theta1: float
302
+ theta2: float
303
+ def __init__(
304
+ self,
305
+ xy: tuple[float, float],
306
+ width: float,
307
+ height: float,
308
+ *,
309
+ angle: float = ...,
310
+ theta1: float = ...,
311
+ theta2: float = ...,
312
+ **kwargs,
313
+ ) -> None: ...
314
+
315
+ def bbox_artist(
316
+ artist: artist.Artist,
317
+ renderer: RendererBase,
318
+ props: dict[str, Any] | None = ...,
319
+ fill: bool = ...,
320
+ ) -> None: ...
321
+ def draw_bbox(
322
+ bbox: Bbox,
323
+ renderer: RendererBase,
324
+ color: ColorType = ...,
325
+ trans: Transform | None = ...,
326
+ ) -> None: ...
327
+
328
+ class _Style:
329
+ def __new__(cls, stylename, **kwargs): ...
330
+ @classmethod
331
+ def get_styles(cls) -> dict[str, type]: ...
332
+ @classmethod
333
+ def pprint_styles(cls) -> str: ...
334
+ @classmethod
335
+ def register(cls, name: str, style: type) -> None: ...
336
+
337
+ class BoxStyle(_Style):
338
+ class Square(BoxStyle):
339
+ pad: float
340
+ def __init__(self, pad: float = ...) -> None: ...
341
+ def __call__(
342
+ self,
343
+ x0: float,
344
+ y0: float,
345
+ width: float,
346
+ height: float,
347
+ mutation_size: float,
348
+ ) -> Path: ...
349
+
350
+ class Circle(BoxStyle):
351
+ pad: float
352
+ def __init__(self, pad: float = ...) -> None: ...
353
+ def __call__(
354
+ self,
355
+ x0: float,
356
+ y0: float,
357
+ width: float,
358
+ height: float,
359
+ mutation_size: float,
360
+ ) -> Path: ...
361
+
362
+ class Ellipse(BoxStyle):
363
+ pad: float
364
+ def __init__(self, pad: float = ...) -> None: ...
365
+ def __call__(
366
+ self,
367
+ x0: float,
368
+ y0: float,
369
+ width: float,
370
+ height: float,
371
+ mutation_size: float,
372
+ ) -> Path: ...
373
+
374
+ class LArrow(BoxStyle):
375
+ pad: float
376
+ def __init__(self, pad: float = ...) -> None: ...
377
+ def __call__(
378
+ self,
379
+ x0: float,
380
+ y0: float,
381
+ width: float,
382
+ height: float,
383
+ mutation_size: float,
384
+ ) -> Path: ...
385
+
386
+ class RArrow(LArrow):
387
+ def __call__(
388
+ self,
389
+ x0: float,
390
+ y0: float,
391
+ width: float,
392
+ height: float,
393
+ mutation_size: float,
394
+ ) -> Path: ...
395
+
396
+ class DArrow(BoxStyle):
397
+ pad: float
398
+ def __init__(self, pad: float = ...) -> None: ...
399
+ def __call__(
400
+ self,
401
+ x0: float,
402
+ y0: float,
403
+ width: float,
404
+ height: float,
405
+ mutation_size: float,
406
+ ) -> Path: ...
407
+
408
+ class Round(BoxStyle):
409
+ pad: float
410
+ rounding_size: float | None
411
+ def __init__(
412
+ self, pad: float = ..., rounding_size: float | None = ...
413
+ ) -> None: ...
414
+ def __call__(
415
+ self,
416
+ x0: float,
417
+ y0: float,
418
+ width: float,
419
+ height: float,
420
+ mutation_size: float,
421
+ ) -> Path: ...
422
+
423
+ class Round4(BoxStyle):
424
+ pad: float
425
+ rounding_size: float | None
426
+ def __init__(
427
+ self, pad: float = ..., rounding_size: float | None = ...
428
+ ) -> None: ...
429
+ def __call__(
430
+ self,
431
+ x0: float,
432
+ y0: float,
433
+ width: float,
434
+ height: float,
435
+ mutation_size: float,
436
+ ) -> Path: ...
437
+
438
+ class Sawtooth(BoxStyle):
439
+ pad: float
440
+ tooth_size: float | None
441
+ def __init__(
442
+ self, pad: float = ..., tooth_size: float | None = ...
443
+ ) -> None: ...
444
+ def __call__(
445
+ self,
446
+ x0: float,
447
+ y0: float,
448
+ width: float,
449
+ height: float,
450
+ mutation_size: float,
451
+ ) -> Path: ...
452
+
453
+ class Roundtooth(Sawtooth):
454
+ def __call__(
455
+ self,
456
+ x0: float,
457
+ y0: float,
458
+ width: float,
459
+ height: float,
460
+ mutation_size: float,
461
+ ) -> Path: ...
462
+
463
+ class ConnectionStyle(_Style):
464
+ class _Base(ConnectionStyle):
465
+ def __call__(
466
+ self,
467
+ posA: tuple[float, float],
468
+ posB: tuple[float, float],
469
+ shrinkA: float = ...,
470
+ shrinkB: float = ...,
471
+ patchA: Patch | None = ...,
472
+ patchB: Patch | None = ...,
473
+ ) -> Path: ...
474
+
475
+ class Arc3(_Base):
476
+ rad: float
477
+ def __init__(self, rad: float = ...) -> None: ...
478
+ def connect(
479
+ self, posA: tuple[float, float], posB: tuple[float, float]
480
+ ) -> Path: ...
481
+
482
+ class Angle3(_Base):
483
+ angleA: float
484
+ angleB: float
485
+ def __init__(self, angleA: float = ..., angleB: float = ...) -> None: ...
486
+ def connect(
487
+ self, posA: tuple[float, float], posB: tuple[float, float]
488
+ ) -> Path: ...
489
+
490
+ class Angle(_Base):
491
+ angleA: float
492
+ angleB: float
493
+ rad: float
494
+ def __init__(
495
+ self, angleA: float = ..., angleB: float = ..., rad: float = ...
496
+ ) -> None: ...
497
+ def connect(
498
+ self, posA: tuple[float, float], posB: tuple[float, float]
499
+ ) -> Path: ...
500
+
501
+ class Arc(_Base):
502
+ angleA: float
503
+ angleB: float
504
+ armA: float | None
505
+ armB: float | None
506
+ rad: float
507
+ def __init__(
508
+ self,
509
+ angleA: float = ...,
510
+ angleB: float = ...,
511
+ armA: float | None = ...,
512
+ armB: float | None = ...,
513
+ rad: float = ...,
514
+ ) -> None: ...
515
+ def connect(
516
+ self, posA: tuple[float, float], posB: tuple[float, float]
517
+ ) -> Path: ...
518
+
519
+ class Bar(_Base):
520
+ armA: float
521
+ armB: float
522
+ fraction: float
523
+ angle: float | None
524
+ def __init__(
525
+ self,
526
+ armA: float = ...,
527
+ armB: float = ...,
528
+ fraction: float = ...,
529
+ angle: float | None = ...,
530
+ ) -> None: ...
531
+ def connect(
532
+ self, posA: tuple[float, float], posB: tuple[float, float]
533
+ ) -> Path: ...
534
+
535
+ class ArrowStyle(_Style):
536
+ class _Base(ArrowStyle):
537
+ @staticmethod
538
+ def ensure_quadratic_bezier(path: Path) -> list[float]: ...
539
+ def transmute(
540
+ self, path: Path, mutation_size: float, linewidth: float
541
+ ) -> tuple[Path, bool]: ...
542
+ def __call__(
543
+ self,
544
+ path: Path,
545
+ mutation_size: float,
546
+ linewidth: float,
547
+ aspect_ratio: float = ...,
548
+ ) -> tuple[Path, bool]: ...
549
+
550
+ class _Curve(_Base):
551
+ arrow: str
552
+ fillbegin: bool
553
+ fillend: bool
554
+ def __init__(
555
+ self,
556
+ head_length: float = ...,
557
+ head_width: float = ...,
558
+ widthA: float = ...,
559
+ widthB: float = ...,
560
+ lengthA: float = ...,
561
+ lengthB: float = ...,
562
+ angleA: float | None = ...,
563
+ angleB: float | None = ...,
564
+ scaleA: float | None = ...,
565
+ scaleB: float | None = ...,
566
+ ) -> None: ...
567
+
568
+ class Curve(_Curve):
569
+ def __init__(self) -> None: ...
570
+
571
+ class CurveA(_Curve):
572
+ arrow: str
573
+
574
+ class CurveB(_Curve):
575
+ arrow: str
576
+
577
+ class CurveAB(_Curve):
578
+ arrow: str
579
+
580
+ class CurveFilledA(_Curve):
581
+ arrow: str
582
+
583
+ class CurveFilledB(_Curve):
584
+ arrow: str
585
+
586
+ class CurveFilledAB(_Curve):
587
+ arrow: str
588
+
589
+ class BracketA(_Curve):
590
+ arrow: str
591
+ def __init__(
592
+ self, widthA: float = ..., lengthA: float = ..., angleA: float = ...
593
+ ) -> None: ...
594
+
595
+ class BracketB(_Curve):
596
+ arrow: str
597
+ def __init__(
598
+ self, widthB: float = ..., lengthB: float = ..., angleB: float = ...
599
+ ) -> None: ...
600
+
601
+ class BracketAB(_Curve):
602
+ arrow: str
603
+ def __init__(
604
+ self,
605
+ widthA: float = ...,
606
+ lengthA: float = ...,
607
+ angleA: float = ...,
608
+ widthB: float = ...,
609
+ lengthB: float = ...,
610
+ angleB: float = ...,
611
+ ) -> None: ...
612
+
613
+ class BarAB(_Curve):
614
+ arrow: str
615
+ def __init__(
616
+ self,
617
+ widthA: float = ...,
618
+ angleA: float = ...,
619
+ widthB: float = ...,
620
+ angleB: float = ...,
621
+ ) -> None: ...
622
+
623
+ class BracketCurve(_Curve):
624
+ arrow: str
625
+ def __init__(
626
+ self, widthA: float = ..., lengthA: float = ..., angleA: float | None = ...
627
+ ) -> None: ...
628
+
629
+ class CurveBracket(_Curve):
630
+ arrow: str
631
+ def __init__(
632
+ self, widthB: float = ..., lengthB: float = ..., angleB: float | None = ...
633
+ ) -> None: ...
634
+
635
+ class Simple(_Base):
636
+ def __init__(
637
+ self,
638
+ head_length: float = ...,
639
+ head_width: float = ...,
640
+ tail_width: float = ...,
641
+ ) -> None: ...
642
+
643
+ class Fancy(_Base):
644
+ def __init__(
645
+ self,
646
+ head_length: float = ...,
647
+ head_width: float = ...,
648
+ tail_width: float = ...,
649
+ ) -> None: ...
650
+
651
+ class Wedge(_Base):
652
+ tail_width: float
653
+ shrink_factor: float
654
+ def __init__(
655
+ self, tail_width: float = ..., shrink_factor: float = ...
656
+ ) -> None: ...
657
+
658
+ class FancyBboxPatch(Patch):
659
+ def __init__(
660
+ self,
661
+ xy: tuple[float, float],
662
+ width: float,
663
+ height: float,
664
+ boxstyle: str | BoxStyle = ...,
665
+ *,
666
+ mutation_scale: float = ...,
667
+ mutation_aspect: float = ...,
668
+ **kwargs,
669
+ ) -> None: ...
670
+ def set_boxstyle(self, boxstyle: str | BoxStyle | None = ..., **kwargs) -> None: ...
671
+ def get_boxstyle(self) -> BoxStyle: ...
672
+ def set_mutation_scale(self, scale: float) -> None: ...
673
+ def get_mutation_scale(self) -> float: ...
674
+ def set_mutation_aspect(self, aspect: float) -> None: ...
675
+ def get_mutation_aspect(self) -> float: ...
676
+ def get_x(self) -> float: ...
677
+ def get_y(self) -> float: ...
678
+ def get_width(self) -> float: ...
679
+ def get_height(self) -> float: ...
680
+ def set_x(self, x: float) -> None: ...
681
+ def set_y(self, y: float) -> None: ...
682
+ def set_width(self, w: float) -> None: ...
683
+ def set_height(self, h: float) -> None: ...
684
+ @overload
685
+ def set_bounds(self, args: tuple[float, float, float, float], /) -> None: ...
686
+ @overload
687
+ def set_bounds(
688
+ self, left: float, bottom: float, width: float, height: float, /
689
+ ) -> None: ...
690
+ def get_bbox(self) -> Bbox: ...
691
+
692
+ class FancyArrowPatch(Patch):
693
+ patchA: Patch
694
+ patchB: Patch
695
+ shrinkA: float
696
+ shrinkB: float
697
+ def __init__(
698
+ self,
699
+ posA: tuple[float, float] | None = ...,
700
+ posB: tuple[float, float] | None = ...,
701
+ *,
702
+ path: Path | None = ...,
703
+ arrowstyle: str | ArrowStyle = ...,
704
+ connectionstyle: str | ConnectionStyle = ...,
705
+ patchA: Patch | None = ...,
706
+ patchB: Patch | None = ...,
707
+ shrinkA: float = ...,
708
+ shrinkB: float = ...,
709
+ mutation_scale: float = ...,
710
+ mutation_aspect: float | None = ...,
711
+ **kwargs,
712
+ ) -> None: ...
713
+ def set_positions(
714
+ self, posA: tuple[float, float], posB: tuple[float, float]
715
+ ) -> None: ...
716
+ def set_patchA(self, patchA: Patch) -> None: ...
717
+ def set_patchB(self, patchB: Patch) -> None: ...
718
+ def set_connectionstyle(self, connectionstyle: str | ConnectionStyle | None = ..., **kwargs) -> None: ...
719
+ def get_connectionstyle(self) -> ConnectionStyle: ...
720
+ def set_arrowstyle(self, arrowstyle: str | ArrowStyle | None = ..., **kwargs) -> None: ...
721
+ def get_arrowstyle(self) -> ArrowStyle: ...
722
+ def set_mutation_scale(self, scale: float) -> None: ...
723
+ def get_mutation_scale(self) -> float: ...
724
+ def set_mutation_aspect(self, aspect: float | None) -> None: ...
725
+ def get_mutation_aspect(self) -> float: ...
726
+
727
+ class ConnectionPatch(FancyArrowPatch):
728
+ xy1: tuple[float, float]
729
+ xy2: tuple[float, float]
730
+ coords1: str | Transform
731
+ coords2: str | Transform | None
732
+ axesA: Axes | None
733
+ axesB: Axes | None
734
+ def __init__(
735
+ self,
736
+ xyA: tuple[float, float],
737
+ xyB: tuple[float, float],
738
+ coordsA: str | Transform,
739
+ coordsB: str | Transform | None = ...,
740
+ *,
741
+ axesA: Axes | None = ...,
742
+ axesB: Axes | None = ...,
743
+ arrowstyle: str | ArrowStyle = ...,
744
+ connectionstyle: str | ConnectionStyle = ...,
745
+ patchA: Patch | None = ...,
746
+ patchB: Patch | None = ...,
747
+ shrinkA: float = ...,
748
+ shrinkB: float = ...,
749
+ mutation_scale: float = ...,
750
+ mutation_aspect: float | None = ...,
751
+ clip_on: bool = ...,
752
+ **kwargs,
753
+ ) -> None: ...
754
+ def set_annotation_clip(self, b: bool | None) -> None: ...
755
+ def get_annotation_clip(self) -> bool | None: ...
llava_next/lib/python3.10/site-packages/matplotlib/path.pyi ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .bezier import BezierSegment
2
+ from .transforms import Affine2D, Transform, Bbox
3
+ from collections.abc import Generator, Iterable, Sequence
4
+
5
+ import numpy as np
6
+ from numpy.typing import ArrayLike
7
+
8
+ from typing import Any, overload
9
+
10
+ class Path:
11
+ code_type: type[np.uint8]
12
+ STOP: np.uint8
13
+ MOVETO: np.uint8
14
+ LINETO: np.uint8
15
+ CURVE3: np.uint8
16
+ CURVE4: np.uint8
17
+ CLOSEPOLY: np.uint8
18
+ NUM_VERTICES_FOR_CODE: dict[np.uint8, int]
19
+
20
+ def __init__(
21
+ self,
22
+ vertices: ArrayLike,
23
+ codes: ArrayLike | None = ...,
24
+ _interpolation_steps: int = ...,
25
+ closed: bool = ...,
26
+ readonly: bool = ...,
27
+ ) -> None: ...
28
+ @property
29
+ def vertices(self) -> ArrayLike: ...
30
+ @vertices.setter
31
+ def vertices(self, vertices: ArrayLike) -> None: ...
32
+ @property
33
+ def codes(self) -> ArrayLike | None: ...
34
+ @codes.setter
35
+ def codes(self, codes: ArrayLike) -> None: ...
36
+ @property
37
+ def simplify_threshold(self) -> float: ...
38
+ @simplify_threshold.setter
39
+ def simplify_threshold(self, threshold: float) -> None: ...
40
+ @property
41
+ def should_simplify(self) -> bool: ...
42
+ @should_simplify.setter
43
+ def should_simplify(self, should_simplify: bool) -> None: ...
44
+ @property
45
+ def readonly(self) -> bool: ...
46
+ def copy(self) -> Path: ...
47
+ def __deepcopy__(self, memo: dict[int, Any] | None = ...) -> Path: ...
48
+ deepcopy = __deepcopy__
49
+
50
+ @classmethod
51
+ def make_compound_path_from_polys(cls, XY: ArrayLike) -> Path: ...
52
+ @classmethod
53
+ def make_compound_path(cls, *args: Path) -> Path: ...
54
+ def __len__(self) -> int: ...
55
+ def iter_segments(
56
+ self,
57
+ transform: Transform | None = ...,
58
+ remove_nans: bool = ...,
59
+ clip: tuple[float, float, float, float] | None = ...,
60
+ snap: bool | None = ...,
61
+ stroke_width: float = ...,
62
+ simplify: bool | None = ...,
63
+ curves: bool = ...,
64
+ sketch: tuple[float, float, float] | None = ...,
65
+ ) -> Generator[tuple[np.ndarray, np.uint8], None, None]: ...
66
+ def iter_bezier(self, **kwargs) -> Generator[BezierSegment, None, None]: ...
67
+ def cleaned(
68
+ self,
69
+ transform: Transform | None = ...,
70
+ remove_nans: bool = ...,
71
+ clip: tuple[float, float, float, float] | None = ...,
72
+ *,
73
+ simplify: bool | None = ...,
74
+ curves: bool = ...,
75
+ stroke_width: float = ...,
76
+ snap: bool | None = ...,
77
+ sketch: tuple[float, float, float] | None = ...
78
+ ) -> Path: ...
79
+ def transformed(self, transform: Transform) -> Path: ...
80
+ def contains_point(
81
+ self,
82
+ point: tuple[float, float],
83
+ transform: Transform | None = ...,
84
+ radius: float = ...,
85
+ ) -> bool: ...
86
+ def contains_points(
87
+ self, points: ArrayLike, transform: Transform | None = ..., radius: float = ...
88
+ ) -> np.ndarray: ...
89
+ def contains_path(self, path: Path, transform: Transform | None = ...) -> bool: ...
90
+ def get_extents(self, transform: Transform | None = ..., **kwargs) -> Bbox: ...
91
+ def intersects_path(self, other: Path, filled: bool = ...) -> bool: ...
92
+ def intersects_bbox(self, bbox: Bbox, filled: bool = ...) -> bool: ...
93
+ def interpolated(self, steps: int) -> Path: ...
94
+ def to_polygons(
95
+ self,
96
+ transform: Transform | None = ...,
97
+ width: float = ...,
98
+ height: float = ...,
99
+ closed_only: bool = ...,
100
+ ) -> list[ArrayLike]: ...
101
+ @classmethod
102
+ def unit_rectangle(cls) -> Path: ...
103
+ @classmethod
104
+ def unit_regular_polygon(cls, numVertices: int) -> Path: ...
105
+ @classmethod
106
+ def unit_regular_star(cls, numVertices: int, innerCircle: float = ...) -> Path: ...
107
+ @classmethod
108
+ def unit_regular_asterisk(cls, numVertices: int) -> Path: ...
109
+ @classmethod
110
+ def unit_circle(cls) -> Path: ...
111
+ @classmethod
112
+ def circle(
113
+ cls,
114
+ center: tuple[float, float] = ...,
115
+ radius: float = ...,
116
+ readonly: bool = ...,
117
+ ) -> Path: ...
118
+ @classmethod
119
+ def unit_circle_righthalf(cls) -> Path: ...
120
+ @classmethod
121
+ def arc(
122
+ cls, theta1: float, theta2: float, n: int | None = ..., is_wedge: bool = ...
123
+ ) -> Path: ...
124
+ @classmethod
125
+ def wedge(cls, theta1: float, theta2: float, n: int | None = ...) -> Path: ...
126
+ @overload
127
+ @staticmethod
128
+ def hatch(hatchpattern: str, density: float = ...) -> Path: ...
129
+ @overload
130
+ @staticmethod
131
+ def hatch(hatchpattern: None, density: float = ...) -> None: ...
132
+ def clip_to_bbox(self, bbox: Bbox, inside: bool = ...) -> Path: ...
133
+
134
+ def get_path_collection_extents(
135
+ master_transform: Transform,
136
+ paths: Sequence[Path],
137
+ transforms: Iterable[Affine2D],
138
+ offsets: ArrayLike,
139
+ offset_transform: Affine2D,
140
+ ) -> Bbox: ...
llava_next/lib/python3.10/site-packages/matplotlib/py.typed ADDED
File without changes
llava_next/lib/python3.10/site-packages/matplotlib/pyplot.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_next/lib/python3.10/site-packages/matplotlib/rcsetup.py ADDED
@@ -0,0 +1,1377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The rcsetup module contains the validation code for customization using
3
+ Matplotlib's rc settings.
4
+
5
+ Each rc setting is assigned a function used to validate any attempted changes
6
+ to that setting. The validation functions are defined in the rcsetup module,
7
+ and are used to construct the rcParams global object which stores the settings
8
+ and is referenced throughout Matplotlib.
9
+
10
+ The default values of the rc settings are set in the default matplotlibrc file.
11
+ Any additions or deletions to the parameter set listed here should also be
12
+ propagated to the :file:`lib/matplotlib/mpl-data/matplotlibrc` in Matplotlib's
13
+ root source directory.
14
+ """
15
+
16
+ import ast
17
+ from functools import lru_cache, reduce
18
+ from numbers import Real
19
+ import operator
20
+ import os
21
+ import re
22
+
23
+ import numpy as np
24
+
25
+ from matplotlib import _api, cbook
26
+ from matplotlib.backends import BackendFilter, backend_registry
27
+ from matplotlib.cbook import ls_mapper
28
+ from matplotlib.colors import Colormap, is_color_like
29
+ from matplotlib._fontconfig_pattern import parse_fontconfig_pattern
30
+ from matplotlib._enums import JoinStyle, CapStyle
31
+
32
+ # Don't let the original cycler collide with our validating cycler
33
+ from cycler import Cycler, cycler as ccycler
34
+
35
+
36
+ @_api.caching_module_getattr
37
+ class __getattr__:
38
+ @_api.deprecated(
39
+ "3.9",
40
+ alternative="``matplotlib.backends.backend_registry.list_builtin"
41
+ "(matplotlib.backends.BackendFilter.INTERACTIVE)``")
42
+ @property
43
+ def interactive_bk(self):
44
+ return backend_registry.list_builtin(BackendFilter.INTERACTIVE)
45
+
46
+ @_api.deprecated(
47
+ "3.9",
48
+ alternative="``matplotlib.backends.backend_registry.list_builtin"
49
+ "(matplotlib.backends.BackendFilter.NON_INTERACTIVE)``")
50
+ @property
51
+ def non_interactive_bk(self):
52
+ return backend_registry.list_builtin(BackendFilter.NON_INTERACTIVE)
53
+
54
+ @_api.deprecated(
55
+ "3.9",
56
+ alternative="``matplotlib.backends.backend_registry.list_builtin()``")
57
+ @property
58
+ def all_backends(self):
59
+ return backend_registry.list_builtin()
60
+
61
+
62
+ class ValidateInStrings:
63
+ def __init__(self, key, valid, ignorecase=False, *,
64
+ _deprecated_since=None):
65
+ """*valid* is a list of legal strings."""
66
+ self.key = key
67
+ self.ignorecase = ignorecase
68
+ self._deprecated_since = _deprecated_since
69
+
70
+ def func(s):
71
+ if ignorecase:
72
+ return s.lower()
73
+ else:
74
+ return s
75
+ self.valid = {func(k): k for k in valid}
76
+
77
+ def __call__(self, s):
78
+ if self._deprecated_since:
79
+ name, = (k for k, v in globals().items() if v is self)
80
+ _api.warn_deprecated(
81
+ self._deprecated_since, name=name, obj_type="function")
82
+ if self.ignorecase and isinstance(s, str):
83
+ s = s.lower()
84
+ if s in self.valid:
85
+ return self.valid[s]
86
+ msg = (f"{s!r} is not a valid value for {self.key}; supported values "
87
+ f"are {[*self.valid.values()]}")
88
+ if (isinstance(s, str)
89
+ and (s.startswith('"') and s.endswith('"')
90
+ or s.startswith("'") and s.endswith("'"))
91
+ and s[1:-1] in self.valid):
92
+ msg += "; remove quotes surrounding your string"
93
+ raise ValueError(msg)
94
+
95
+
96
+ @lru_cache
97
+ def _listify_validator(scalar_validator, allow_stringlist=False, *,
98
+ n=None, doc=None):
99
+ def f(s):
100
+ if isinstance(s, str):
101
+ try:
102
+ val = [scalar_validator(v.strip()) for v in s.split(',')
103
+ if v.strip()]
104
+ except Exception:
105
+ if allow_stringlist:
106
+ # Sometimes, a list of colors might be a single string
107
+ # of single-letter colornames. So give that a shot.
108
+ val = [scalar_validator(v.strip()) for v in s if v.strip()]
109
+ else:
110
+ raise
111
+ # Allow any ordered sequence type -- generators, np.ndarray, pd.Series
112
+ # -- but not sets, whose iteration order is non-deterministic.
113
+ elif np.iterable(s) and not isinstance(s, (set, frozenset)):
114
+ # The condition on this list comprehension will preserve the
115
+ # behavior of filtering out any empty strings (behavior was
116
+ # from the original validate_stringlist()), while allowing
117
+ # any non-string/text scalar values such as numbers and arrays.
118
+ val = [scalar_validator(v) for v in s
119
+ if not isinstance(v, str) or v]
120
+ else:
121
+ raise ValueError(
122
+ f"Expected str or other non-set iterable, but got {s}")
123
+ if n is not None and len(val) != n:
124
+ raise ValueError(
125
+ f"Expected {n} values, but there are {len(val)} values in {s}")
126
+ return val
127
+
128
+ try:
129
+ f.__name__ = f"{scalar_validator.__name__}list"
130
+ except AttributeError: # class instance.
131
+ f.__name__ = f"{type(scalar_validator).__name__}List"
132
+ f.__qualname__ = f.__qualname__.rsplit(".", 1)[0] + "." + f.__name__
133
+ f.__doc__ = doc if doc is not None else scalar_validator.__doc__
134
+ return f
135
+
136
+
137
+ def validate_any(s):
138
+ return s
139
+ validate_anylist = _listify_validator(validate_any)
140
+
141
+
142
+ def _validate_date(s):
143
+ try:
144
+ np.datetime64(s)
145
+ return s
146
+ except ValueError:
147
+ raise ValueError(
148
+ f'{s!r} should be a string that can be parsed by numpy.datetime64')
149
+
150
+
151
+ def validate_bool(b):
152
+ """Convert b to ``bool`` or raise."""
153
+ if isinstance(b, str):
154
+ b = b.lower()
155
+ if b in ('t', 'y', 'yes', 'on', 'true', '1', 1, True):
156
+ return True
157
+ elif b in ('f', 'n', 'no', 'off', 'false', '0', 0, False):
158
+ return False
159
+ else:
160
+ raise ValueError(f'Cannot convert {b!r} to bool')
161
+
162
+
163
+ def validate_axisbelow(s):
164
+ try:
165
+ return validate_bool(s)
166
+ except ValueError:
167
+ if isinstance(s, str):
168
+ if s == 'line':
169
+ return 'line'
170
+ raise ValueError(f'{s!r} cannot be interpreted as'
171
+ ' True, False, or "line"')
172
+
173
+
174
+ def validate_dpi(s):
175
+ """Confirm s is string 'figure' or convert s to float or raise."""
176
+ if s == 'figure':
177
+ return s
178
+ try:
179
+ return float(s)
180
+ except ValueError as e:
181
+ raise ValueError(f'{s!r} is not string "figure" and '
182
+ f'could not convert {s!r} to float') from e
183
+
184
+
185
+ def _make_type_validator(cls, *, allow_none=False):
186
+ """
187
+ Return a validator that converts inputs to *cls* or raises (and possibly
188
+ allows ``None`` as well).
189
+ """
190
+
191
+ def validator(s):
192
+ if (allow_none and
193
+ (s is None or cbook._str_lower_equal(s, "none"))):
194
+ return None
195
+ if cls is str and not isinstance(s, str):
196
+ raise ValueError(f'Could not convert {s!r} to str')
197
+ try:
198
+ return cls(s)
199
+ except (TypeError, ValueError) as e:
200
+ raise ValueError(
201
+ f'Could not convert {s!r} to {cls.__name__}') from e
202
+
203
+ validator.__name__ = f"validate_{cls.__name__}"
204
+ if allow_none:
205
+ validator.__name__ += "_or_None"
206
+ validator.__qualname__ = (
207
+ validator.__qualname__.rsplit(".", 1)[0] + "." + validator.__name__)
208
+ return validator
209
+
210
+
211
+ validate_string = _make_type_validator(str)
212
+ validate_string_or_None = _make_type_validator(str, allow_none=True)
213
+ validate_stringlist = _listify_validator(
214
+ validate_string, doc='return a list of strings')
215
+ validate_int = _make_type_validator(int)
216
+ validate_int_or_None = _make_type_validator(int, allow_none=True)
217
+ validate_float = _make_type_validator(float)
218
+ validate_float_or_None = _make_type_validator(float, allow_none=True)
219
+ validate_floatlist = _listify_validator(
220
+ validate_float, doc='return a list of floats')
221
+
222
+
223
+ def _validate_marker(s):
224
+ try:
225
+ return validate_int(s)
226
+ except ValueError as e:
227
+ try:
228
+ return validate_string(s)
229
+ except ValueError as e:
230
+ raise ValueError('Supported markers are [string, int]') from e
231
+
232
+
233
+ _validate_markerlist = _listify_validator(
234
+ _validate_marker, doc='return a list of markers')
235
+
236
+
237
+ def _validate_pathlike(s):
238
+ if isinstance(s, (str, os.PathLike)):
239
+ # Store value as str because savefig.directory needs to distinguish
240
+ # between "" (cwd) and "." (cwd, but gets updated by user selections).
241
+ return os.fsdecode(s)
242
+ else:
243
+ return validate_string(s)
244
+
245
+
246
+ def validate_fonttype(s):
247
+ """
248
+ Confirm that this is a Postscript or PDF font type that we know how to
249
+ convert to.
250
+ """
251
+ fonttypes = {'type3': 3,
252
+ 'truetype': 42}
253
+ try:
254
+ fonttype = validate_int(s)
255
+ except ValueError:
256
+ try:
257
+ return fonttypes[s.lower()]
258
+ except KeyError as e:
259
+ raise ValueError('Supported Postscript/PDF font types are %s'
260
+ % list(fonttypes)) from e
261
+ else:
262
+ if fonttype not in fonttypes.values():
263
+ raise ValueError(
264
+ 'Supported Postscript/PDF font types are %s' %
265
+ list(fonttypes.values()))
266
+ return fonttype
267
+
268
+
269
+ _auto_backend_sentinel = object()
270
+
271
+
272
+ def validate_backend(s):
273
+ if s is _auto_backend_sentinel or backend_registry.is_valid_backend(s):
274
+ return s
275
+ else:
276
+ msg = (f"'{s}' is not a valid value for backend; supported values are "
277
+ f"{backend_registry.list_all()}")
278
+ raise ValueError(msg)
279
+
280
+
281
+ def _validate_toolbar(s):
282
+ s = ValidateInStrings(
283
+ 'toolbar', ['None', 'toolbar2', 'toolmanager'], ignorecase=True)(s)
284
+ if s == 'toolmanager':
285
+ _api.warn_external(
286
+ "Treat the new Tool classes introduced in v1.5 as experimental "
287
+ "for now; the API and rcParam may change in future versions.")
288
+ return s
289
+
290
+
291
+ def validate_color_or_inherit(s):
292
+ """Return a valid color arg."""
293
+ if cbook._str_equal(s, 'inherit'):
294
+ return s
295
+ return validate_color(s)
296
+
297
+
298
+ def validate_color_or_auto(s):
299
+ if cbook._str_equal(s, 'auto'):
300
+ return s
301
+ return validate_color(s)
302
+
303
+
304
+ def validate_color_for_prop_cycle(s):
305
+ # N-th color cycle syntax can't go into the color cycle.
306
+ if isinstance(s, str) and re.match("^C[0-9]$", s):
307
+ raise ValueError(f"Cannot put cycle reference ({s!r}) in prop_cycler")
308
+ return validate_color(s)
309
+
310
+
311
+ def _validate_color_or_linecolor(s):
312
+ if cbook._str_equal(s, 'linecolor'):
313
+ return s
314
+ elif cbook._str_equal(s, 'mfc') or cbook._str_equal(s, 'markerfacecolor'):
315
+ return 'markerfacecolor'
316
+ elif cbook._str_equal(s, 'mec') or cbook._str_equal(s, 'markeredgecolor'):
317
+ return 'markeredgecolor'
318
+ elif s is None:
319
+ return None
320
+ elif isinstance(s, str) and len(s) == 6 or len(s) == 8:
321
+ stmp = '#' + s
322
+ if is_color_like(stmp):
323
+ return stmp
324
+ if s.lower() == 'none':
325
+ return None
326
+ elif is_color_like(s):
327
+ return s
328
+
329
+ raise ValueError(f'{s!r} does not look like a color arg')
330
+
331
+
332
+ def validate_color(s):
333
+ """Return a valid color arg."""
334
+ if isinstance(s, str):
335
+ if s.lower() == 'none':
336
+ return 'none'
337
+ if len(s) == 6 or len(s) == 8:
338
+ stmp = '#' + s
339
+ if is_color_like(stmp):
340
+ return stmp
341
+
342
+ if is_color_like(s):
343
+ return s
344
+
345
+ # If it is still valid, it must be a tuple (as a string from matplotlibrc).
346
+ try:
347
+ color = ast.literal_eval(s)
348
+ except (SyntaxError, ValueError):
349
+ pass
350
+ else:
351
+ if is_color_like(color):
352
+ return color
353
+
354
+ raise ValueError(f'{s!r} does not look like a color arg')
355
+
356
+
357
+ validate_colorlist = _listify_validator(
358
+ validate_color, allow_stringlist=True, doc='return a list of colorspecs')
359
+
360
+
361
+ def _validate_cmap(s):
362
+ _api.check_isinstance((str, Colormap), cmap=s)
363
+ return s
364
+
365
+
366
+ def validate_aspect(s):
367
+ if s in ('auto', 'equal'):
368
+ return s
369
+ try:
370
+ return float(s)
371
+ except ValueError as e:
372
+ raise ValueError('not a valid aspect specification') from e
373
+
374
+
375
+ def validate_fontsize_None(s):
376
+ if s is None or s == 'None':
377
+ return None
378
+ else:
379
+ return validate_fontsize(s)
380
+
381
+
382
+ def validate_fontsize(s):
383
+ fontsizes = ['xx-small', 'x-small', 'small', 'medium', 'large',
384
+ 'x-large', 'xx-large', 'smaller', 'larger']
385
+ if isinstance(s, str):
386
+ s = s.lower()
387
+ if s in fontsizes:
388
+ return s
389
+ try:
390
+ return float(s)
391
+ except ValueError as e:
392
+ raise ValueError("%s is not a valid font size. Valid font sizes "
393
+ "are %s." % (s, ", ".join(fontsizes))) from e
394
+
395
+
396
+ validate_fontsizelist = _listify_validator(validate_fontsize)
397
+
398
+
399
+ def validate_fontweight(s):
400
+ weights = [
401
+ 'ultralight', 'light', 'normal', 'regular', 'book', 'medium', 'roman',
402
+ 'semibold', 'demibold', 'demi', 'bold', 'heavy', 'extra bold', 'black']
403
+ # Note: Historically, weights have been case-sensitive in Matplotlib
404
+ if s in weights:
405
+ return s
406
+ try:
407
+ return int(s)
408
+ except (ValueError, TypeError) as e:
409
+ raise ValueError(f'{s} is not a valid font weight.') from e
410
+
411
+
412
+ def validate_fontstretch(s):
413
+ stretchvalues = [
414
+ 'ultra-condensed', 'extra-condensed', 'condensed', 'semi-condensed',
415
+ 'normal', 'semi-expanded', 'expanded', 'extra-expanded',
416
+ 'ultra-expanded']
417
+ # Note: Historically, stretchvalues have been case-sensitive in Matplotlib
418
+ if s in stretchvalues:
419
+ return s
420
+ try:
421
+ return int(s)
422
+ except (ValueError, TypeError) as e:
423
+ raise ValueError(f'{s} is not a valid font stretch.') from e
424
+
425
+
426
+ def validate_font_properties(s):
427
+ parse_fontconfig_pattern(s)
428
+ return s
429
+
430
+
431
+ def _validate_mathtext_fallback(s):
432
+ _fallback_fonts = ['cm', 'stix', 'stixsans']
433
+ if isinstance(s, str):
434
+ s = s.lower()
435
+ if s is None or s == 'none':
436
+ return None
437
+ elif s.lower() in _fallback_fonts:
438
+ return s
439
+ else:
440
+ raise ValueError(
441
+ f"{s} is not a valid fallback font name. Valid fallback font "
442
+ f"names are {','.join(_fallback_fonts)}. Passing 'None' will turn "
443
+ "fallback off.")
444
+
445
+
446
+ def validate_whiskers(s):
447
+ try:
448
+ return _listify_validator(validate_float, n=2)(s)
449
+ except (TypeError, ValueError):
450
+ try:
451
+ return float(s)
452
+ except ValueError as e:
453
+ raise ValueError("Not a valid whisker value [float, "
454
+ "(float, float)]") from e
455
+
456
+
457
+ def validate_ps_distiller(s):
458
+ if isinstance(s, str):
459
+ s = s.lower()
460
+ if s in ('none', None, 'false', False):
461
+ return None
462
+ else:
463
+ return ValidateInStrings('ps.usedistiller', ['ghostscript', 'xpdf'])(s)
464
+
465
+
466
+ def _validate_papersize(s):
467
+ # Re-inline this validator when the 'auto' deprecation expires.
468
+ s = ValidateInStrings("ps.papersize",
469
+ ["figure", "auto", "letter", "legal", "ledger",
470
+ *[f"{ab}{i}" for ab in "ab" for i in range(11)]],
471
+ ignorecase=True)(s)
472
+ if s == "auto":
473
+ _api.warn_deprecated("3.8", name="ps.papersize='auto'",
474
+ addendum="Pass an explicit paper type, figure, or omit "
475
+ "the *ps.papersize* rcParam entirely.")
476
+ return s
477
+
478
+
479
+ # A validator dedicated to the named line styles, based on the items in
480
+ # ls_mapper, and a list of possible strings read from Line2D.set_linestyle
481
+ _validate_named_linestyle = ValidateInStrings(
482
+ 'linestyle',
483
+ [*ls_mapper.keys(), *ls_mapper.values(), 'None', 'none', ' ', ''],
484
+ ignorecase=True)
485
+
486
+
487
+ def _validate_linestyle(ls):
488
+ """
489
+ A validator for all possible line styles, the named ones *and*
490
+ the on-off ink sequences.
491
+ """
492
+ if isinstance(ls, str):
493
+ try: # Look first for a valid named line style, like '--' or 'solid'.
494
+ return _validate_named_linestyle(ls)
495
+ except ValueError:
496
+ pass
497
+ try:
498
+ ls = ast.literal_eval(ls) # Parsing matplotlibrc.
499
+ except (SyntaxError, ValueError):
500
+ pass # Will error with the ValueError at the end.
501
+
502
+ def _is_iterable_not_string_like(x):
503
+ # Explicitly exclude bytes/bytearrays so that they are not
504
+ # nonsensically interpreted as sequences of numbers (codepoints).
505
+ return np.iterable(x) and not isinstance(x, (str, bytes, bytearray))
506
+
507
+ if _is_iterable_not_string_like(ls):
508
+ if len(ls) == 2 and _is_iterable_not_string_like(ls[1]):
509
+ # (offset, (on, off, on, off, ...))
510
+ offset, onoff = ls
511
+ else:
512
+ # For backcompat: (on, off, on, off, ...); the offset is implicit.
513
+ offset = 0
514
+ onoff = ls
515
+
516
+ if (isinstance(offset, Real)
517
+ and len(onoff) % 2 == 0
518
+ and all(isinstance(elem, Real) for elem in onoff)):
519
+ return (offset, onoff)
520
+
521
+ raise ValueError(f"linestyle {ls!r} is not a valid on-off ink sequence.")
522
+
523
+
524
+ validate_fillstyle = ValidateInStrings(
525
+ 'markers.fillstyle', ['full', 'left', 'right', 'bottom', 'top', 'none'])
526
+
527
+
528
+ validate_fillstylelist = _listify_validator(validate_fillstyle)
529
+
530
+
531
+ def validate_markevery(s):
532
+ """
533
+ Validate the markevery property of a Line2D object.
534
+
535
+ Parameters
536
+ ----------
537
+ s : None, int, (int, int), slice, float, (float, float), or list[int]
538
+
539
+ Returns
540
+ -------
541
+ None, int, (int, int), slice, float, (float, float), or list[int]
542
+ """
543
+ # Validate s against type slice float int and None
544
+ if isinstance(s, (slice, float, int, type(None))):
545
+ return s
546
+ # Validate s against type tuple
547
+ if isinstance(s, tuple):
548
+ if (len(s) == 2
549
+ and (all(isinstance(e, int) for e in s)
550
+ or all(isinstance(e, float) for e in s))):
551
+ return s
552
+ else:
553
+ raise TypeError(
554
+ "'markevery' tuple must be pair of ints or of floats")
555
+ # Validate s against type list
556
+ if isinstance(s, list):
557
+ if all(isinstance(e, int) for e in s):
558
+ return s
559
+ else:
560
+ raise TypeError(
561
+ "'markevery' list must have all elements of type int")
562
+ raise TypeError("'markevery' is of an invalid type")
563
+
564
+
565
+ validate_markeverylist = _listify_validator(validate_markevery)
566
+
567
+
568
+ def validate_bbox(s):
569
+ if isinstance(s, str):
570
+ s = s.lower()
571
+ if s == 'tight':
572
+ return s
573
+ if s == 'standard':
574
+ return None
575
+ raise ValueError("bbox should be 'tight' or 'standard'")
576
+ elif s is not None:
577
+ # Backwards compatibility. None is equivalent to 'standard'.
578
+ raise ValueError("bbox should be 'tight' or 'standard'")
579
+ return s
580
+
581
+
582
+ def validate_sketch(s):
583
+
584
+ if isinstance(s, str):
585
+ s = s.lower().strip()
586
+ if s.startswith("(") and s.endswith(")"):
587
+ s = s[1:-1]
588
+ if s == 'none' or s is None:
589
+ return None
590
+ try:
591
+ return tuple(_listify_validator(validate_float, n=3)(s))
592
+ except ValueError as exc:
593
+ raise ValueError("Expected a (scale, length, randomness) tuple") from exc
594
+
595
+
596
+ def _validate_greaterthan_minushalf(s):
597
+ s = validate_float(s)
598
+ if s > -0.5:
599
+ return s
600
+ else:
601
+ raise RuntimeError(f'Value must be >-0.5; got {s}')
602
+
603
+
604
+ def _validate_greaterequal0_lessequal1(s):
605
+ s = validate_float(s)
606
+ if 0 <= s <= 1:
607
+ return s
608
+ else:
609
+ raise RuntimeError(f'Value must be >=0 and <=1; got {s}')
610
+
611
+
612
+ def _validate_int_greaterequal0(s):
613
+ s = validate_int(s)
614
+ if s >= 0:
615
+ return s
616
+ else:
617
+ raise RuntimeError(f'Value must be >=0; got {s}')
618
+
619
+
620
+ def validate_hatch(s):
621
+ r"""
622
+ Validate a hatch pattern.
623
+ A hatch pattern string can have any sequence of the following
624
+ characters: ``\ / | - + * . x o O``.
625
+ """
626
+ if not isinstance(s, str):
627
+ raise ValueError("Hatch pattern must be a string")
628
+ _api.check_isinstance(str, hatch_pattern=s)
629
+ unknown = set(s) - {'\\', '/', '|', '-', '+', '*', '.', 'x', 'o', 'O'}
630
+ if unknown:
631
+ raise ValueError("Unknown hatch symbol(s): %s" % list(unknown))
632
+ return s
633
+
634
+
635
+ validate_hatchlist = _listify_validator(validate_hatch)
636
+ validate_dashlist = _listify_validator(validate_floatlist)
637
+
638
+
639
+ def _validate_minor_tick_ndivs(n):
640
+ """
641
+ Validate ndiv parameter related to the minor ticks.
642
+ It controls the number of minor ticks to be placed between
643
+ two major ticks.
644
+ """
645
+
646
+ if cbook._str_lower_equal(n, 'auto'):
647
+ return n
648
+ try:
649
+ n = _validate_int_greaterequal0(n)
650
+ return n
651
+ except (RuntimeError, ValueError):
652
+ pass
653
+
654
+ raise ValueError("'tick.minor.ndivs' must be 'auto' or non-negative int")
655
+
656
+
657
+ _prop_validators = {
658
+ 'color': _listify_validator(validate_color_for_prop_cycle,
659
+ allow_stringlist=True),
660
+ 'linewidth': validate_floatlist,
661
+ 'linestyle': _listify_validator(_validate_linestyle),
662
+ 'facecolor': validate_colorlist,
663
+ 'edgecolor': validate_colorlist,
664
+ 'joinstyle': _listify_validator(JoinStyle),
665
+ 'capstyle': _listify_validator(CapStyle),
666
+ 'fillstyle': validate_fillstylelist,
667
+ 'markerfacecolor': validate_colorlist,
668
+ 'markersize': validate_floatlist,
669
+ 'markeredgewidth': validate_floatlist,
670
+ 'markeredgecolor': validate_colorlist,
671
+ 'markevery': validate_markeverylist,
672
+ 'alpha': validate_floatlist,
673
+ 'marker': _validate_markerlist,
674
+ 'hatch': validate_hatchlist,
675
+ 'dashes': validate_dashlist,
676
+ }
677
+ _prop_aliases = {
678
+ 'c': 'color',
679
+ 'lw': 'linewidth',
680
+ 'ls': 'linestyle',
681
+ 'fc': 'facecolor',
682
+ 'ec': 'edgecolor',
683
+ 'mfc': 'markerfacecolor',
684
+ 'mec': 'markeredgecolor',
685
+ 'mew': 'markeredgewidth',
686
+ 'ms': 'markersize',
687
+ }
688
+
689
+
690
+ def cycler(*args, **kwargs):
691
+ """
692
+ Create a `~cycler.Cycler` object much like :func:`cycler.cycler`,
693
+ but includes input validation.
694
+
695
+ Call signatures::
696
+
697
+ cycler(cycler)
698
+ cycler(label=values[, label2=values2[, ...]])
699
+ cycler(label, values)
700
+
701
+ Form 1 copies a given `~cycler.Cycler` object.
702
+
703
+ Form 2 creates a `~cycler.Cycler` which cycles over one or more
704
+ properties simultaneously. If multiple properties are given, their
705
+ value lists must have the same length.
706
+
707
+ Form 3 creates a `~cycler.Cycler` for a single property. This form
708
+ exists for compatibility with the original cycler. Its use is
709
+ discouraged in favor of the kwarg form, i.e. ``cycler(label=values)``.
710
+
711
+ Parameters
712
+ ----------
713
+ cycler : Cycler
714
+ Copy constructor for Cycler.
715
+
716
+ label : str
717
+ The property key. Must be a valid `.Artist` property.
718
+ For example, 'color' or 'linestyle'. Aliases are allowed,
719
+ such as 'c' for 'color' and 'lw' for 'linewidth'.
720
+
721
+ values : iterable
722
+ Finite-length iterable of the property values. These values
723
+ are validated and will raise a ValueError if invalid.
724
+
725
+ Returns
726
+ -------
727
+ Cycler
728
+ A new :class:`~cycler.Cycler` for the given properties.
729
+
730
+ Examples
731
+ --------
732
+ Creating a cycler for a single property:
733
+
734
+ >>> c = cycler(color=['red', 'green', 'blue'])
735
+
736
+ Creating a cycler for simultaneously cycling over multiple properties
737
+ (e.g. red circle, green plus, blue cross):
738
+
739
+ >>> c = cycler(color=['red', 'green', 'blue'],
740
+ ... marker=['o', '+', 'x'])
741
+
742
+ """
743
+ if args and kwargs:
744
+ raise TypeError("cycler() can only accept positional OR keyword "
745
+ "arguments -- not both.")
746
+ elif not args and not kwargs:
747
+ raise TypeError("cycler() must have positional OR keyword arguments")
748
+
749
+ if len(args) == 1:
750
+ if not isinstance(args[0], Cycler):
751
+ raise TypeError("If only one positional argument given, it must "
752
+ "be a Cycler instance.")
753
+ return validate_cycler(args[0])
754
+ elif len(args) == 2:
755
+ pairs = [(args[0], args[1])]
756
+ elif len(args) > 2:
757
+ raise _api.nargs_error('cycler', '0-2', len(args))
758
+ else:
759
+ pairs = kwargs.items()
760
+
761
+ validated = []
762
+ for prop, vals in pairs:
763
+ norm_prop = _prop_aliases.get(prop, prop)
764
+ validator = _prop_validators.get(norm_prop, None)
765
+ if validator is None:
766
+ raise TypeError("Unknown artist property: %s" % prop)
767
+ vals = validator(vals)
768
+ # We will normalize the property names as well to reduce
769
+ # the amount of alias handling code elsewhere.
770
+ validated.append((norm_prop, vals))
771
+
772
+ return reduce(operator.add, (ccycler(k, v) for k, v in validated))
773
+
774
+
775
+ class _DunderChecker(ast.NodeVisitor):
776
+ def visit_Attribute(self, node):
777
+ if node.attr.startswith("__") and node.attr.endswith("__"):
778
+ raise ValueError("cycler strings with dunders are forbidden")
779
+ self.generic_visit(node)
780
+
781
+
782
+ # A validator dedicated to the named legend loc
783
+ _validate_named_legend_loc = ValidateInStrings(
784
+ 'legend.loc',
785
+ [
786
+ "best",
787
+ "upper right", "upper left", "lower left", "lower right", "right",
788
+ "center left", "center right", "lower center", "upper center",
789
+ "center"],
790
+ ignorecase=True)
791
+
792
+
793
+ def _validate_legend_loc(loc):
794
+ """
795
+ Confirm that loc is a type which rc.Params["legend.loc"] supports.
796
+
797
+ .. versionadded:: 3.8
798
+
799
+ Parameters
800
+ ----------
801
+ loc : str | int | (float, float) | str((float, float))
802
+ The location of the legend.
803
+
804
+ Returns
805
+ -------
806
+ loc : str | int | (float, float) or raise ValueError exception
807
+ The location of the legend.
808
+ """
809
+ if isinstance(loc, str):
810
+ try:
811
+ return _validate_named_legend_loc(loc)
812
+ except ValueError:
813
+ pass
814
+ try:
815
+ loc = ast.literal_eval(loc)
816
+ except (SyntaxError, ValueError):
817
+ pass
818
+ if isinstance(loc, int):
819
+ if 0 <= loc <= 10:
820
+ return loc
821
+ if isinstance(loc, tuple):
822
+ if len(loc) == 2 and all(isinstance(e, Real) for e in loc):
823
+ return loc
824
+ raise ValueError(f"{loc} is not a valid legend location.")
825
+
826
+
827
+ def validate_cycler(s):
828
+ """Return a Cycler object from a string repr or the object itself."""
829
+ if isinstance(s, str):
830
+ # TODO: We might want to rethink this...
831
+ # While I think I have it quite locked down, it is execution of
832
+ # arbitrary code without sanitation.
833
+ # Combine this with the possibility that rcparams might come from the
834
+ # internet (future plans), this could be downright dangerous.
835
+ # I locked it down by only having the 'cycler()' function available.
836
+ # UPDATE: Partly plugging a security hole.
837
+ # I really should have read this:
838
+ # https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html
839
+ # We should replace this eval with a combo of PyParsing and
840
+ # ast.literal_eval()
841
+ try:
842
+ _DunderChecker().visit(ast.parse(s))
843
+ s = eval(s, {'cycler': cycler, '__builtins__': {}})
844
+ except BaseException as e:
845
+ raise ValueError(f"{s!r} is not a valid cycler construction: {e}"
846
+ ) from e
847
+ # Should make sure what comes from the above eval()
848
+ # is a Cycler object.
849
+ if isinstance(s, Cycler):
850
+ cycler_inst = s
851
+ else:
852
+ raise ValueError(f"Object is not a string or Cycler instance: {s!r}")
853
+
854
+ unknowns = cycler_inst.keys - (set(_prop_validators) | set(_prop_aliases))
855
+ if unknowns:
856
+ raise ValueError("Unknown artist properties: %s" % unknowns)
857
+
858
+ # Not a full validation, but it'll at least normalize property names
859
+ # A fuller validation would require v0.10 of cycler.
860
+ checker = set()
861
+ for prop in cycler_inst.keys:
862
+ norm_prop = _prop_aliases.get(prop, prop)
863
+ if norm_prop != prop and norm_prop in cycler_inst.keys:
864
+ raise ValueError(f"Cannot specify both {norm_prop!r} and alias "
865
+ f"{prop!r} in the same prop_cycle")
866
+ if norm_prop in checker:
867
+ raise ValueError(f"Another property was already aliased to "
868
+ f"{norm_prop!r}. Collision normalizing {prop!r}.")
869
+ checker.update([norm_prop])
870
+
871
+ # This is just an extra-careful check, just in case there is some
872
+ # edge-case I haven't thought of.
873
+ assert len(checker) == len(cycler_inst.keys)
874
+
875
+ # Now, it should be safe to mutate this cycler
876
+ for prop in cycler_inst.keys:
877
+ norm_prop = _prop_aliases.get(prop, prop)
878
+ cycler_inst.change_key(prop, norm_prop)
879
+
880
+ for key, vals in cycler_inst.by_key().items():
881
+ _prop_validators[key](vals)
882
+
883
+ return cycler_inst
884
+
885
+
886
+ def validate_hist_bins(s):
887
+ valid_strs = ["auto", "sturges", "fd", "doane", "scott", "rice", "sqrt"]
888
+ if isinstance(s, str) and s in valid_strs:
889
+ return s
890
+ try:
891
+ return int(s)
892
+ except (TypeError, ValueError):
893
+ pass
894
+ try:
895
+ return validate_floatlist(s)
896
+ except ValueError:
897
+ pass
898
+ raise ValueError(f"'hist.bins' must be one of {valid_strs}, an int or"
899
+ " a sequence of floats")
900
+
901
+
902
+ class _ignorecase(list):
903
+ """A marker class indicating that a list-of-str is case-insensitive."""
904
+
905
+
906
+ def _convert_validator_spec(key, conv):
907
+ if isinstance(conv, list):
908
+ ignorecase = isinstance(conv, _ignorecase)
909
+ return ValidateInStrings(key, conv, ignorecase=ignorecase)
910
+ else:
911
+ return conv
912
+
913
+
914
+ # Mapping of rcParams to validators.
915
+ # Converters given as lists or _ignorecase are converted to ValidateInStrings
916
+ # immediately below.
917
+ # The rcParams defaults are defined in lib/matplotlib/mpl-data/matplotlibrc, which
918
+ # gets copied to matplotlib/mpl-data/matplotlibrc by the setup script.
919
+ _validators = {
920
+ "backend": validate_backend,
921
+ "backend_fallback": validate_bool,
922
+ "figure.hooks": validate_stringlist,
923
+ "toolbar": _validate_toolbar,
924
+ "interactive": validate_bool,
925
+ "timezone": validate_string,
926
+
927
+ "webagg.port": validate_int,
928
+ "webagg.address": validate_string,
929
+ "webagg.open_in_browser": validate_bool,
930
+ "webagg.port_retries": validate_int,
931
+
932
+ # line props
933
+ "lines.linewidth": validate_float, # line width in points
934
+ "lines.linestyle": _validate_linestyle, # solid line
935
+ "lines.color": validate_color, # first color in color cycle
936
+ "lines.marker": _validate_marker, # marker name
937
+ "lines.markerfacecolor": validate_color_or_auto, # default color
938
+ "lines.markeredgecolor": validate_color_or_auto, # default color
939
+ "lines.markeredgewidth": validate_float,
940
+ "lines.markersize": validate_float, # markersize, in points
941
+ "lines.antialiased": validate_bool, # antialiased (no jaggies)
942
+ "lines.dash_joinstyle": JoinStyle,
943
+ "lines.solid_joinstyle": JoinStyle,
944
+ "lines.dash_capstyle": CapStyle,
945
+ "lines.solid_capstyle": CapStyle,
946
+ "lines.dashed_pattern": validate_floatlist,
947
+ "lines.dashdot_pattern": validate_floatlist,
948
+ "lines.dotted_pattern": validate_floatlist,
949
+ "lines.scale_dashes": validate_bool,
950
+
951
+ # marker props
952
+ "markers.fillstyle": validate_fillstyle,
953
+
954
+ ## pcolor(mesh) props:
955
+ "pcolor.shading": ["auto", "flat", "nearest", "gouraud"],
956
+ "pcolormesh.snap": validate_bool,
957
+
958
+ ## patch props
959
+ "patch.linewidth": validate_float, # line width in points
960
+ "patch.edgecolor": validate_color,
961
+ "patch.force_edgecolor": validate_bool,
962
+ "patch.facecolor": validate_color, # first color in cycle
963
+ "patch.antialiased": validate_bool, # antialiased (no jaggies)
964
+
965
+ ## hatch props
966
+ "hatch.color": validate_color,
967
+ "hatch.linewidth": validate_float,
968
+
969
+ ## Histogram properties
970
+ "hist.bins": validate_hist_bins,
971
+
972
+ ## Boxplot properties
973
+ "boxplot.notch": validate_bool,
974
+ "boxplot.vertical": validate_bool,
975
+ "boxplot.whiskers": validate_whiskers,
976
+ "boxplot.bootstrap": validate_int_or_None,
977
+ "boxplot.patchartist": validate_bool,
978
+ "boxplot.showmeans": validate_bool,
979
+ "boxplot.showcaps": validate_bool,
980
+ "boxplot.showbox": validate_bool,
981
+ "boxplot.showfliers": validate_bool,
982
+ "boxplot.meanline": validate_bool,
983
+
984
+ "boxplot.flierprops.color": validate_color,
985
+ "boxplot.flierprops.marker": _validate_marker,
986
+ "boxplot.flierprops.markerfacecolor": validate_color_or_auto,
987
+ "boxplot.flierprops.markeredgecolor": validate_color,
988
+ "boxplot.flierprops.markeredgewidth": validate_float,
989
+ "boxplot.flierprops.markersize": validate_float,
990
+ "boxplot.flierprops.linestyle": _validate_linestyle,
991
+ "boxplot.flierprops.linewidth": validate_float,
992
+
993
+ "boxplot.boxprops.color": validate_color,
994
+ "boxplot.boxprops.linewidth": validate_float,
995
+ "boxplot.boxprops.linestyle": _validate_linestyle,
996
+
997
+ "boxplot.whiskerprops.color": validate_color,
998
+ "boxplot.whiskerprops.linewidth": validate_float,
999
+ "boxplot.whiskerprops.linestyle": _validate_linestyle,
1000
+
1001
+ "boxplot.capprops.color": validate_color,
1002
+ "boxplot.capprops.linewidth": validate_float,
1003
+ "boxplot.capprops.linestyle": _validate_linestyle,
1004
+
1005
+ "boxplot.medianprops.color": validate_color,
1006
+ "boxplot.medianprops.linewidth": validate_float,
1007
+ "boxplot.medianprops.linestyle": _validate_linestyle,
1008
+
1009
+ "boxplot.meanprops.color": validate_color,
1010
+ "boxplot.meanprops.marker": _validate_marker,
1011
+ "boxplot.meanprops.markerfacecolor": validate_color,
1012
+ "boxplot.meanprops.markeredgecolor": validate_color,
1013
+ "boxplot.meanprops.markersize": validate_float,
1014
+ "boxplot.meanprops.linestyle": _validate_linestyle,
1015
+ "boxplot.meanprops.linewidth": validate_float,
1016
+
1017
+ ## font props
1018
+ "font.family": validate_stringlist, # used by text object
1019
+ "font.style": validate_string,
1020
+ "font.variant": validate_string,
1021
+ "font.stretch": validate_fontstretch,
1022
+ "font.weight": validate_fontweight,
1023
+ "font.size": validate_float, # Base font size in points
1024
+ "font.serif": validate_stringlist,
1025
+ "font.sans-serif": validate_stringlist,
1026
+ "font.cursive": validate_stringlist,
1027
+ "font.fantasy": validate_stringlist,
1028
+ "font.monospace": validate_stringlist,
1029
+
1030
+ # text props
1031
+ "text.color": validate_color,
1032
+ "text.usetex": validate_bool,
1033
+ "text.latex.preamble": validate_string,
1034
+ "text.hinting": ["default", "no_autohint", "force_autohint",
1035
+ "no_hinting", "auto", "native", "either", "none"],
1036
+ "text.hinting_factor": validate_int,
1037
+ "text.kerning_factor": validate_int,
1038
+ "text.antialiased": validate_bool,
1039
+ "text.parse_math": validate_bool,
1040
+
1041
+ "mathtext.cal": validate_font_properties,
1042
+ "mathtext.rm": validate_font_properties,
1043
+ "mathtext.tt": validate_font_properties,
1044
+ "mathtext.it": validate_font_properties,
1045
+ "mathtext.bf": validate_font_properties,
1046
+ "mathtext.bfit": validate_font_properties,
1047
+ "mathtext.sf": validate_font_properties,
1048
+ "mathtext.fontset": ["dejavusans", "dejavuserif", "cm", "stix",
1049
+ "stixsans", "custom"],
1050
+ "mathtext.default": ["rm", "cal", "bfit", "it", "tt", "sf", "bf", "default",
1051
+ "bb", "frak", "scr", "regular"],
1052
+ "mathtext.fallback": _validate_mathtext_fallback,
1053
+
1054
+ "image.aspect": validate_aspect, # equal, auto, a number
1055
+ "image.interpolation": validate_string,
1056
+ "image.interpolation_stage": ["data", "rgba"],
1057
+ "image.cmap": _validate_cmap, # gray, jet, etc.
1058
+ "image.lut": validate_int, # lookup table
1059
+ "image.origin": ["upper", "lower"],
1060
+ "image.resample": validate_bool,
1061
+ # Specify whether vector graphics backends will combine all images on a
1062
+ # set of Axes into a single composite image
1063
+ "image.composite_image": validate_bool,
1064
+
1065
+ # contour props
1066
+ "contour.negative_linestyle": _validate_linestyle,
1067
+ "contour.corner_mask": validate_bool,
1068
+ "contour.linewidth": validate_float_or_None,
1069
+ "contour.algorithm": ["mpl2005", "mpl2014", "serial", "threaded"],
1070
+
1071
+ # errorbar props
1072
+ "errorbar.capsize": validate_float,
1073
+
1074
+ # axis props
1075
+ # alignment of x/y axis title
1076
+ "xaxis.labellocation": ["left", "center", "right"],
1077
+ "yaxis.labellocation": ["bottom", "center", "top"],
1078
+
1079
+ # Axes props
1080
+ "axes.axisbelow": validate_axisbelow,
1081
+ "axes.facecolor": validate_color, # background color
1082
+ "axes.edgecolor": validate_color, # edge color
1083
+ "axes.linewidth": validate_float, # edge linewidth
1084
+
1085
+ "axes.spines.left": validate_bool, # Set visibility of axes spines,
1086
+ "axes.spines.right": validate_bool, # i.e., the lines around the chart
1087
+ "axes.spines.bottom": validate_bool, # denoting data boundary.
1088
+ "axes.spines.top": validate_bool,
1089
+
1090
+ "axes.titlesize": validate_fontsize, # Axes title fontsize
1091
+ "axes.titlelocation": ["left", "center", "right"], # Axes title alignment
1092
+ "axes.titleweight": validate_fontweight, # Axes title font weight
1093
+ "axes.titlecolor": validate_color_or_auto, # Axes title font color
1094
+ # title location, axes units, None means auto
1095
+ "axes.titley": validate_float_or_None,
1096
+ # pad from Axes top decoration to title in points
1097
+ "axes.titlepad": validate_float,
1098
+ "axes.grid": validate_bool, # display grid or not
1099
+ "axes.grid.which": ["minor", "both", "major"], # which grids are drawn
1100
+ "axes.grid.axis": ["x", "y", "both"], # grid type
1101
+ "axes.labelsize": validate_fontsize, # fontsize of x & y labels
1102
+ "axes.labelpad": validate_float, # space between label and axis
1103
+ "axes.labelweight": validate_fontweight, # fontsize of x & y labels
1104
+ "axes.labelcolor": validate_color, # color of axis label
1105
+ # use scientific notation if log10 of the axis range is smaller than the
1106
+ # first or larger than the second
1107
+ "axes.formatter.limits": _listify_validator(validate_int, n=2),
1108
+ # use current locale to format ticks
1109
+ "axes.formatter.use_locale": validate_bool,
1110
+ "axes.formatter.use_mathtext": validate_bool,
1111
+ # minimum exponent to format in scientific notation
1112
+ "axes.formatter.min_exponent": validate_int,
1113
+ "axes.formatter.useoffset": validate_bool,
1114
+ "axes.formatter.offset_threshold": validate_int,
1115
+ "axes.unicode_minus": validate_bool,
1116
+ # This entry can be either a cycler object or a string repr of a
1117
+ # cycler-object, which gets eval()'ed to create the object.
1118
+ "axes.prop_cycle": validate_cycler,
1119
+ # If "data", axes limits are set close to the data.
1120
+ # If "round_numbers" axes limits are set to the nearest round numbers.
1121
+ "axes.autolimit_mode": ["data", "round_numbers"],
1122
+ "axes.xmargin": _validate_greaterthan_minushalf, # margin added to xaxis
1123
+ "axes.ymargin": _validate_greaterthan_minushalf, # margin added to yaxis
1124
+ "axes.zmargin": _validate_greaterthan_minushalf, # margin added to zaxis
1125
+
1126
+ "polaraxes.grid": validate_bool, # display polar grid or not
1127
+ "axes3d.grid": validate_bool, # display 3d grid
1128
+ "axes3d.automargin": validate_bool, # automatically add margin when
1129
+ # manually setting 3D axis limits
1130
+
1131
+ "axes3d.xaxis.panecolor": validate_color, # 3d background pane
1132
+ "axes3d.yaxis.panecolor": validate_color, # 3d background pane
1133
+ "axes3d.zaxis.panecolor": validate_color, # 3d background pane
1134
+
1135
+ # scatter props
1136
+ "scatter.marker": _validate_marker,
1137
+ "scatter.edgecolors": validate_string,
1138
+
1139
+ "date.epoch": _validate_date,
1140
+ "date.autoformatter.year": validate_string,
1141
+ "date.autoformatter.month": validate_string,
1142
+ "date.autoformatter.day": validate_string,
1143
+ "date.autoformatter.hour": validate_string,
1144
+ "date.autoformatter.minute": validate_string,
1145
+ "date.autoformatter.second": validate_string,
1146
+ "date.autoformatter.microsecond": validate_string,
1147
+
1148
+ 'date.converter': ['auto', 'concise'],
1149
+ # for auto date locator, choose interval_multiples
1150
+ 'date.interval_multiples': validate_bool,
1151
+
1152
+ # legend properties
1153
+ "legend.fancybox": validate_bool,
1154
+ "legend.loc": _validate_legend_loc,
1155
+
1156
+ # the number of points in the legend line
1157
+ "legend.numpoints": validate_int,
1158
+ # the number of points in the legend line for scatter
1159
+ "legend.scatterpoints": validate_int,
1160
+ "legend.fontsize": validate_fontsize,
1161
+ "legend.title_fontsize": validate_fontsize_None,
1162
+ # color of the legend
1163
+ "legend.labelcolor": _validate_color_or_linecolor,
1164
+ # the relative size of legend markers vs. original
1165
+ "legend.markerscale": validate_float,
1166
+ # using dict in rcParams not yet supported, so make sure it is bool
1167
+ "legend.shadow": validate_bool,
1168
+ # whether or not to draw a frame around legend
1169
+ "legend.frameon": validate_bool,
1170
+ # alpha value of the legend frame
1171
+ "legend.framealpha": validate_float_or_None,
1172
+
1173
+ ## the following dimensions are in fraction of the font size
1174
+ "legend.borderpad": validate_float, # units are fontsize
1175
+ # the vertical space between the legend entries
1176
+ "legend.labelspacing": validate_float,
1177
+ # the length of the legend lines
1178
+ "legend.handlelength": validate_float,
1179
+ # the length of the legend lines
1180
+ "legend.handleheight": validate_float,
1181
+ # the space between the legend line and legend text
1182
+ "legend.handletextpad": validate_float,
1183
+ # the border between the Axes and legend edge
1184
+ "legend.borderaxespad": validate_float,
1185
+ # the border between the Axes and legend edge
1186
+ "legend.columnspacing": validate_float,
1187
+ "legend.facecolor": validate_color_or_inherit,
1188
+ "legend.edgecolor": validate_color_or_inherit,
1189
+
1190
+ # tick properties
1191
+ "xtick.top": validate_bool, # draw ticks on top side
1192
+ "xtick.bottom": validate_bool, # draw ticks on bottom side
1193
+ "xtick.labeltop": validate_bool, # draw label on top
1194
+ "xtick.labelbottom": validate_bool, # draw label on bottom
1195
+ "xtick.major.size": validate_float, # major xtick size in points
1196
+ "xtick.minor.size": validate_float, # minor xtick size in points
1197
+ "xtick.major.width": validate_float, # major xtick width in points
1198
+ "xtick.minor.width": validate_float, # minor xtick width in points
1199
+ "xtick.major.pad": validate_float, # distance to label in points
1200
+ "xtick.minor.pad": validate_float, # distance to label in points
1201
+ "xtick.color": validate_color, # color of xticks
1202
+ "xtick.labelcolor": validate_color_or_inherit, # color of xtick labels
1203
+ "xtick.minor.visible": validate_bool, # visibility of minor xticks
1204
+ "xtick.minor.top": validate_bool, # draw top minor xticks
1205
+ "xtick.minor.bottom": validate_bool, # draw bottom minor xticks
1206
+ "xtick.major.top": validate_bool, # draw top major xticks
1207
+ "xtick.major.bottom": validate_bool, # draw bottom major xticks
1208
+ # number of minor xticks
1209
+ "xtick.minor.ndivs": _validate_minor_tick_ndivs,
1210
+ "xtick.labelsize": validate_fontsize, # fontsize of xtick labels
1211
+ "xtick.direction": ["out", "in", "inout"], # direction of xticks
1212
+ "xtick.alignment": ["center", "right", "left"],
1213
+
1214
+ "ytick.left": validate_bool, # draw ticks on left side
1215
+ "ytick.right": validate_bool, # draw ticks on right side
1216
+ "ytick.labelleft": validate_bool, # draw tick labels on left side
1217
+ "ytick.labelright": validate_bool, # draw tick labels on right side
1218
+ "ytick.major.size": validate_float, # major ytick size in points
1219
+ "ytick.minor.size": validate_float, # minor ytick size in points
1220
+ "ytick.major.width": validate_float, # major ytick width in points
1221
+ "ytick.minor.width": validate_float, # minor ytick width in points
1222
+ "ytick.major.pad": validate_float, # distance to label in points
1223
+ "ytick.minor.pad": validate_float, # distance to label in points
1224
+ "ytick.color": validate_color, # color of yticks
1225
+ "ytick.labelcolor": validate_color_or_inherit, # color of ytick labels
1226
+ "ytick.minor.visible": validate_bool, # visibility of minor yticks
1227
+ "ytick.minor.left": validate_bool, # draw left minor yticks
1228
+ "ytick.minor.right": validate_bool, # draw right minor yticks
1229
+ "ytick.major.left": validate_bool, # draw left major yticks
1230
+ "ytick.major.right": validate_bool, # draw right major yticks
1231
+ # number of minor yticks
1232
+ "ytick.minor.ndivs": _validate_minor_tick_ndivs,
1233
+ "ytick.labelsize": validate_fontsize, # fontsize of ytick labels
1234
+ "ytick.direction": ["out", "in", "inout"], # direction of yticks
1235
+ "ytick.alignment": [
1236
+ "center", "top", "bottom", "baseline", "center_baseline"],
1237
+
1238
+ "grid.color": validate_color, # grid color
1239
+ "grid.linestyle": _validate_linestyle, # solid
1240
+ "grid.linewidth": validate_float, # in points
1241
+ "grid.alpha": validate_float,
1242
+
1243
+ ## figure props
1244
+ # figure title
1245
+ "figure.titlesize": validate_fontsize,
1246
+ "figure.titleweight": validate_fontweight,
1247
+
1248
+ # figure labels
1249
+ "figure.labelsize": validate_fontsize,
1250
+ "figure.labelweight": validate_fontweight,
1251
+
1252
+ # figure size in inches: width by height
1253
+ "figure.figsize": _listify_validator(validate_float, n=2),
1254
+ "figure.dpi": validate_float,
1255
+ "figure.facecolor": validate_color,
1256
+ "figure.edgecolor": validate_color,
1257
+ "figure.frameon": validate_bool,
1258
+ "figure.autolayout": validate_bool,
1259
+ "figure.max_open_warning": validate_int,
1260
+ "figure.raise_window": validate_bool,
1261
+ "macosx.window_mode": ["system", "tab", "window"],
1262
+
1263
+ "figure.subplot.left": validate_float,
1264
+ "figure.subplot.right": validate_float,
1265
+ "figure.subplot.bottom": validate_float,
1266
+ "figure.subplot.top": validate_float,
1267
+ "figure.subplot.wspace": validate_float,
1268
+ "figure.subplot.hspace": validate_float,
1269
+
1270
+ "figure.constrained_layout.use": validate_bool, # run constrained_layout?
1271
+ # wspace and hspace are fraction of adjacent subplots to use for space.
1272
+ # Much smaller than above because we don't need room for the text.
1273
+ "figure.constrained_layout.hspace": validate_float,
1274
+ "figure.constrained_layout.wspace": validate_float,
1275
+ # buffer around the Axes, in inches.
1276
+ "figure.constrained_layout.h_pad": validate_float,
1277
+ "figure.constrained_layout.w_pad": validate_float,
1278
+
1279
+ ## Saving figure's properties
1280
+ 'savefig.dpi': validate_dpi,
1281
+ 'savefig.facecolor': validate_color_or_auto,
1282
+ 'savefig.edgecolor': validate_color_or_auto,
1283
+ 'savefig.orientation': ['landscape', 'portrait'],
1284
+ "savefig.format": validate_string,
1285
+ "savefig.bbox": validate_bbox, # "tight", or "standard" (= None)
1286
+ "savefig.pad_inches": validate_float,
1287
+ # default directory in savefig dialog box
1288
+ "savefig.directory": _validate_pathlike,
1289
+ "savefig.transparent": validate_bool,
1290
+
1291
+ "tk.window_focus": validate_bool, # Maintain shell focus for TkAgg
1292
+
1293
+ # Set the papersize/type
1294
+ "ps.papersize": _validate_papersize,
1295
+ "ps.useafm": validate_bool,
1296
+ # use ghostscript or xpdf to distill ps output
1297
+ "ps.usedistiller": validate_ps_distiller,
1298
+ "ps.distiller.res": validate_int, # dpi
1299
+ "ps.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
1300
+ "pdf.compression": validate_int, # 0-9 compression level; 0 to disable
1301
+ "pdf.inheritcolor": validate_bool, # skip color setting commands
1302
+ # use only the 14 PDF core fonts embedded in every PDF viewing application
1303
+ "pdf.use14corefonts": validate_bool,
1304
+ "pdf.fonttype": validate_fonttype, # 3 (Type3) or 42 (Truetype)
1305
+
1306
+ "pgf.texsystem": ["xelatex", "lualatex", "pdflatex"], # latex variant used
1307
+ "pgf.rcfonts": validate_bool, # use mpl's rc settings for font config
1308
+ "pgf.preamble": validate_string, # custom LaTeX preamble
1309
+
1310
+ # write raster image data into the svg file
1311
+ "svg.image_inline": validate_bool,
1312
+ "svg.fonttype": ["none", "path"], # save text as text ("none") or "paths"
1313
+ "svg.hashsalt": validate_string_or_None,
1314
+
1315
+ # set this when you want to generate hardcopy docstring
1316
+ "docstring.hardcopy": validate_bool,
1317
+
1318
+ "path.simplify": validate_bool,
1319
+ "path.simplify_threshold": _validate_greaterequal0_lessequal1,
1320
+ "path.snap": validate_bool,
1321
+ "path.sketch": validate_sketch,
1322
+ "path.effects": validate_anylist,
1323
+ "agg.path.chunksize": validate_int, # 0 to disable chunking
1324
+
1325
+ # key-mappings (multi-character mappings should be a list/tuple)
1326
+ "keymap.fullscreen": validate_stringlist,
1327
+ "keymap.home": validate_stringlist,
1328
+ "keymap.back": validate_stringlist,
1329
+ "keymap.forward": validate_stringlist,
1330
+ "keymap.pan": validate_stringlist,
1331
+ "keymap.zoom": validate_stringlist,
1332
+ "keymap.save": validate_stringlist,
1333
+ "keymap.quit": validate_stringlist,
1334
+ "keymap.quit_all": validate_stringlist, # e.g.: "W", "cmd+W", "Q"
1335
+ "keymap.grid": validate_stringlist,
1336
+ "keymap.grid_minor": validate_stringlist,
1337
+ "keymap.yscale": validate_stringlist,
1338
+ "keymap.xscale": validate_stringlist,
1339
+ "keymap.help": validate_stringlist,
1340
+ "keymap.copy": validate_stringlist,
1341
+
1342
+ # Animation settings
1343
+ "animation.html": ["html5", "jshtml", "none"],
1344
+ # Limit, in MB, of size of base64 encoded animation in HTML
1345
+ # (i.e. IPython notebook)
1346
+ "animation.embed_limit": validate_float,
1347
+ "animation.writer": validate_string,
1348
+ "animation.codec": validate_string,
1349
+ "animation.bitrate": validate_int,
1350
+ # Controls image format when frames are written to disk
1351
+ "animation.frame_format": ["png", "jpeg", "tiff", "raw", "rgba", "ppm",
1352
+ "sgi", "bmp", "pbm", "svg"],
1353
+ # Path to ffmpeg binary. If just binary name, subprocess uses $PATH.
1354
+ "animation.ffmpeg_path": _validate_pathlike,
1355
+ # Additional arguments for ffmpeg movie writer (using pipes)
1356
+ "animation.ffmpeg_args": validate_stringlist,
1357
+ # Path to convert binary. If just binary name, subprocess uses $PATH.
1358
+ "animation.convert_path": _validate_pathlike,
1359
+ # Additional arguments for convert movie writer (using pipes)
1360
+ "animation.convert_args": validate_stringlist,
1361
+
1362
+ # Classic (pre 2.0) compatibility mode
1363
+ # This is used for things that are hard to make backward compatible
1364
+ # with a sane rcParam alone. This does *not* turn on classic mode
1365
+ # altogether. For that use `matplotlib.style.use("classic")`.
1366
+ "_internal.classic_mode": validate_bool
1367
+ }
1368
+ _hardcoded_defaults = { # Defaults not inferred from
1369
+ # lib/matplotlib/mpl-data/matplotlibrc...
1370
+ # ... because they are private:
1371
+ "_internal.classic_mode": False,
1372
+ # ... because they are deprecated:
1373
+ # No current deprecations.
1374
+ # backend is handled separately when constructing rcParamsDefault.
1375
+ }
1376
+ _validators = {k: _convert_validator_spec(k, conv)
1377
+ for k, conv in _validators.items()}
llava_next/lib/python3.10/site-packages/matplotlib/sankey.py ADDED
@@ -0,0 +1,814 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Module for creating Sankey diagrams using Matplotlib.
3
+ """
4
+
5
+ import logging
6
+ from types import SimpleNamespace
7
+
8
+ import numpy as np
9
+
10
+ import matplotlib as mpl
11
+ from matplotlib.path import Path
12
+ from matplotlib.patches import PathPatch
13
+ from matplotlib.transforms import Affine2D
14
+ from matplotlib import _docstring
15
+
16
+ _log = logging.getLogger(__name__)
17
+
18
+ __author__ = "Kevin L. Davies"
19
+ __credits__ = ["Yannick Copin"]
20
+ __license__ = "BSD"
21
+ __version__ = "2011/09/16"
22
+
23
+ # Angles [deg/90]
24
+ RIGHT = 0
25
+ UP = 1
26
+ # LEFT = 2
27
+ DOWN = 3
28
+
29
+
30
+ class Sankey:
31
+ """
32
+ Sankey diagram.
33
+
34
+ Sankey diagrams are a specific type of flow diagram, in which
35
+ the width of the arrows is shown proportionally to the flow
36
+ quantity. They are typically used to visualize energy or
37
+ material or cost transfers between processes.
38
+ `Wikipedia (6/1/2011) <https://en.wikipedia.org/wiki/Sankey_diagram>`_
39
+
40
+ """
41
+
42
+ def __init__(self, ax=None, scale=1.0, unit='', format='%G', gap=0.25,
43
+ radius=0.1, shoulder=0.03, offset=0.15, head_angle=100,
44
+ margin=0.4, tolerance=1e-6, **kwargs):
45
+ """
46
+ Create a new Sankey instance.
47
+
48
+ The optional arguments listed below are applied to all subdiagrams so
49
+ that there is consistent alignment and formatting.
50
+
51
+ In order to draw a complex Sankey diagram, create an instance of
52
+ `Sankey` by calling it without any kwargs::
53
+
54
+ sankey = Sankey()
55
+
56
+ Then add simple Sankey sub-diagrams::
57
+
58
+ sankey.add() # 1
59
+ sankey.add() # 2
60
+ #...
61
+ sankey.add() # n
62
+
63
+ Finally, create the full diagram::
64
+
65
+ sankey.finish()
66
+
67
+ Or, instead, simply daisy-chain those calls::
68
+
69
+ Sankey().add().add... .add().finish()
70
+
71
+ Other Parameters
72
+ ----------------
73
+ ax : `~matplotlib.axes.Axes`
74
+ Axes onto which the data should be plotted. If *ax* isn't
75
+ provided, new Axes will be created.
76
+ scale : float
77
+ Scaling factor for the flows. *scale* sizes the width of the paths
78
+ in order to maintain proper layout. The same scale is applied to
79
+ all subdiagrams. The value should be chosen such that the product
80
+ of the scale and the sum of the inputs is approximately 1.0 (and
81
+ the product of the scale and the sum of the outputs is
82
+ approximately -1.0).
83
+ unit : str
84
+ The physical unit associated with the flow quantities. If *unit*
85
+ is None, then none of the quantities are labeled.
86
+ format : str or callable
87
+ A Python number formatting string or callable used to label the
88
+ flows with their quantities (i.e., a number times a unit, where the
89
+ unit is given). If a format string is given, the label will be
90
+ ``format % quantity``. If a callable is given, it will be called
91
+ with ``quantity`` as an argument.
92
+ gap : float
93
+ Space between paths that break in/break away to/from the top or
94
+ bottom.
95
+ radius : float
96
+ Inner radius of the vertical paths.
97
+ shoulder : float
98
+ Size of the shoulders of output arrows.
99
+ offset : float
100
+ Text offset (from the dip or tip of the arrow).
101
+ head_angle : float
102
+ Angle, in degrees, of the arrow heads (and negative of the angle of
103
+ the tails).
104
+ margin : float
105
+ Minimum space between Sankey outlines and the edge of the plot
106
+ area.
107
+ tolerance : float
108
+ Acceptable maximum of the magnitude of the sum of flows. The
109
+ magnitude of the sum of connected flows cannot be greater than
110
+ *tolerance*.
111
+ **kwargs
112
+ Any additional keyword arguments will be passed to `add`, which
113
+ will create the first subdiagram.
114
+
115
+ See Also
116
+ --------
117
+ Sankey.add
118
+ Sankey.finish
119
+
120
+ Examples
121
+ --------
122
+ .. plot:: gallery/specialty_plots/sankey_basics.py
123
+ """
124
+ # Check the arguments.
125
+ if gap < 0:
126
+ raise ValueError(
127
+ "'gap' is negative, which is not allowed because it would "
128
+ "cause the paths to overlap")
129
+ if radius > gap:
130
+ raise ValueError(
131
+ "'radius' is greater than 'gap', which is not allowed because "
132
+ "it would cause the paths to overlap")
133
+ if head_angle < 0:
134
+ raise ValueError(
135
+ "'head_angle' is negative, which is not allowed because it "
136
+ "would cause inputs to look like outputs and vice versa")
137
+ if tolerance < 0:
138
+ raise ValueError(
139
+ "'tolerance' is negative, but it must be a magnitude")
140
+
141
+ # Create Axes if necessary.
142
+ if ax is None:
143
+ import matplotlib.pyplot as plt
144
+ fig = plt.figure()
145
+ ax = fig.add_subplot(1, 1, 1, xticks=[], yticks=[])
146
+
147
+ self.diagrams = []
148
+
149
+ # Store the inputs.
150
+ self.ax = ax
151
+ self.unit = unit
152
+ self.format = format
153
+ self.scale = scale
154
+ self.gap = gap
155
+ self.radius = radius
156
+ self.shoulder = shoulder
157
+ self.offset = offset
158
+ self.margin = margin
159
+ self.pitch = np.tan(np.pi * (1 - head_angle / 180.0) / 2.0)
160
+ self.tolerance = tolerance
161
+
162
+ # Initialize the vertices of tight box around the diagram(s).
163
+ self.extent = np.array((np.inf, -np.inf, np.inf, -np.inf))
164
+
165
+ # If there are any kwargs, create the first subdiagram.
166
+ if len(kwargs):
167
+ self.add(**kwargs)
168
+
169
+ def _arc(self, quadrant=0, cw=True, radius=1, center=(0, 0)):
170
+ """
171
+ Return the codes and vertices for a rotated, scaled, and translated
172
+ 90 degree arc.
173
+
174
+ Other Parameters
175
+ ----------------
176
+ quadrant : {0, 1, 2, 3}, default: 0
177
+ Uses 0-based indexing (0, 1, 2, or 3).
178
+ cw : bool, default: True
179
+ If True, the arc vertices are produced clockwise; counter-clockwise
180
+ otherwise.
181
+ radius : float, default: 1
182
+ The radius of the arc.
183
+ center : (float, float), default: (0, 0)
184
+ (x, y) tuple of the arc's center.
185
+ """
186
+ # Note: It would be possible to use matplotlib's transforms to rotate,
187
+ # scale, and translate the arc, but since the angles are discrete,
188
+ # it's just as easy and maybe more efficient to do it here.
189
+ ARC_CODES = [Path.LINETO,
190
+ Path.CURVE4,
191
+ Path.CURVE4,
192
+ Path.CURVE4,
193
+ Path.CURVE4,
194
+ Path.CURVE4,
195
+ Path.CURVE4]
196
+ # Vertices of a cubic Bezier curve approximating a 90 deg arc
197
+ # These can be determined by Path.arc(0, 90).
198
+ ARC_VERTICES = np.array([[1.00000000e+00, 0.00000000e+00],
199
+ [1.00000000e+00, 2.65114773e-01],
200
+ [8.94571235e-01, 5.19642327e-01],
201
+ [7.07106781e-01, 7.07106781e-01],
202
+ [5.19642327e-01, 8.94571235e-01],
203
+ [2.65114773e-01, 1.00000000e+00],
204
+ # Insignificant
205
+ # [6.12303177e-17, 1.00000000e+00]])
206
+ [0.00000000e+00, 1.00000000e+00]])
207
+ if quadrant in (0, 2):
208
+ if cw:
209
+ vertices = ARC_VERTICES
210
+ else:
211
+ vertices = ARC_VERTICES[:, ::-1] # Swap x and y.
212
+ else: # 1, 3
213
+ # Negate x.
214
+ if cw:
215
+ # Swap x and y.
216
+ vertices = np.column_stack((-ARC_VERTICES[:, 1],
217
+ ARC_VERTICES[:, 0]))
218
+ else:
219
+ vertices = np.column_stack((-ARC_VERTICES[:, 0],
220
+ ARC_VERTICES[:, 1]))
221
+ if quadrant > 1:
222
+ radius = -radius # Rotate 180 deg.
223
+ return list(zip(ARC_CODES, radius * vertices +
224
+ np.tile(center, (ARC_VERTICES.shape[0], 1))))
225
+
226
+ def _add_input(self, path, angle, flow, length):
227
+ """
228
+ Add an input to a path and return its tip and label locations.
229
+ """
230
+ if angle is None:
231
+ return [0, 0], [0, 0]
232
+ else:
233
+ x, y = path[-1][1] # Use the last point as a reference.
234
+ dipdepth = (flow / 2) * self.pitch
235
+ if angle == RIGHT:
236
+ x -= length
237
+ dip = [x + dipdepth, y + flow / 2.0]
238
+ path.extend([(Path.LINETO, [x, y]),
239
+ (Path.LINETO, dip),
240
+ (Path.LINETO, [x, y + flow]),
241
+ (Path.LINETO, [x + self.gap, y + flow])])
242
+ label_location = [dip[0] - self.offset, dip[1]]
243
+ else: # Vertical
244
+ x -= self.gap
245
+ if angle == UP:
246
+ sign = 1
247
+ else:
248
+ sign = -1
249
+
250
+ dip = [x - flow / 2, y - sign * (length - dipdepth)]
251
+ if angle == DOWN:
252
+ quadrant = 2
253
+ else:
254
+ quadrant = 1
255
+
256
+ # Inner arc isn't needed if inner radius is zero
257
+ if self.radius:
258
+ path.extend(self._arc(quadrant=quadrant,
259
+ cw=angle == UP,
260
+ radius=self.radius,
261
+ center=(x + self.radius,
262
+ y - sign * self.radius)))
263
+ else:
264
+ path.append((Path.LINETO, [x, y]))
265
+ path.extend([(Path.LINETO, [x, y - sign * length]),
266
+ (Path.LINETO, dip),
267
+ (Path.LINETO, [x - flow, y - sign * length])])
268
+ path.extend(self._arc(quadrant=quadrant,
269
+ cw=angle == DOWN,
270
+ radius=flow + self.radius,
271
+ center=(x + self.radius,
272
+ y - sign * self.radius)))
273
+ path.append((Path.LINETO, [x - flow, y + sign * flow]))
274
+ label_location = [dip[0], dip[1] - sign * self.offset]
275
+
276
+ return dip, label_location
277
+
278
+ def _add_output(self, path, angle, flow, length):
279
+ """
280
+ Append an output to a path and return its tip and label locations.
281
+
282
+ .. note:: *flow* is negative for an output.
283
+ """
284
+ if angle is None:
285
+ return [0, 0], [0, 0]
286
+ else:
287
+ x, y = path[-1][1] # Use the last point as a reference.
288
+ tipheight = (self.shoulder - flow / 2) * self.pitch
289
+ if angle == RIGHT:
290
+ x += length
291
+ tip = [x + tipheight, y + flow / 2.0]
292
+ path.extend([(Path.LINETO, [x, y]),
293
+ (Path.LINETO, [x, y + self.shoulder]),
294
+ (Path.LINETO, tip),
295
+ (Path.LINETO, [x, y - self.shoulder + flow]),
296
+ (Path.LINETO, [x, y + flow]),
297
+ (Path.LINETO, [x - self.gap, y + flow])])
298
+ label_location = [tip[0] + self.offset, tip[1]]
299
+ else: # Vertical
300
+ x += self.gap
301
+ if angle == UP:
302
+ sign, quadrant = 1, 3
303
+ else:
304
+ sign, quadrant = -1, 0
305
+
306
+ tip = [x - flow / 2.0, y + sign * (length + tipheight)]
307
+ # Inner arc isn't needed if inner radius is zero
308
+ if self.radius:
309
+ path.extend(self._arc(quadrant=quadrant,
310
+ cw=angle == UP,
311
+ radius=self.radius,
312
+ center=(x - self.radius,
313
+ y + sign * self.radius)))
314
+ else:
315
+ path.append((Path.LINETO, [x, y]))
316
+ path.extend([(Path.LINETO, [x, y + sign * length]),
317
+ (Path.LINETO, [x - self.shoulder,
318
+ y + sign * length]),
319
+ (Path.LINETO, tip),
320
+ (Path.LINETO, [x + self.shoulder - flow,
321
+ y + sign * length]),
322
+ (Path.LINETO, [x - flow, y + sign * length])])
323
+ path.extend(self._arc(quadrant=quadrant,
324
+ cw=angle == DOWN,
325
+ radius=self.radius - flow,
326
+ center=(x - self.radius,
327
+ y + sign * self.radius)))
328
+ path.append((Path.LINETO, [x - flow, y + sign * flow]))
329
+ label_location = [tip[0], tip[1] + sign * self.offset]
330
+ return tip, label_location
331
+
332
+ def _revert(self, path, first_action=Path.LINETO):
333
+ """
334
+ A path is not simply reversible by path[::-1] since the code
335
+ specifies an action to take from the **previous** point.
336
+ """
337
+ reverse_path = []
338
+ next_code = first_action
339
+ for code, position in path[::-1]:
340
+ reverse_path.append((next_code, position))
341
+ next_code = code
342
+ return reverse_path
343
+ # This might be more efficient, but it fails because 'tuple' object
344
+ # doesn't support item assignment:
345
+ # path[1] = path[1][-1:0:-1]
346
+ # path[1][0] = first_action
347
+ # path[2] = path[2][::-1]
348
+ # return path
349
+
350
+ @_docstring.dedent_interpd
351
+ def add(self, patchlabel='', flows=None, orientations=None, labels='',
352
+ trunklength=1.0, pathlengths=0.25, prior=None, connect=(0, 0),
353
+ rotation=0, **kwargs):
354
+ """
355
+ Add a simple Sankey diagram with flows at the same hierarchical level.
356
+
357
+ Parameters
358
+ ----------
359
+ patchlabel : str
360
+ Label to be placed at the center of the diagram.
361
+ Note that *label* (not *patchlabel*) can be passed as keyword
362
+ argument to create an entry in the legend.
363
+
364
+ flows : list of float
365
+ Array of flow values. By convention, inputs are positive and
366
+ outputs are negative.
367
+
368
+ Flows are placed along the top of the diagram from the inside out
369
+ in order of their index within *flows*. They are placed along the
370
+ sides of the diagram from the top down and along the bottom from
371
+ the outside in.
372
+
373
+ If the sum of the inputs and outputs is
374
+ nonzero, the discrepancy will appear as a cubic B��zier curve along
375
+ the top and bottom edges of the trunk.
376
+
377
+ orientations : list of {-1, 0, 1}
378
+ List of orientations of the flows (or a single orientation to be
379
+ used for all flows). Valid values are 0 (inputs from
380
+ the left, outputs to the right), 1 (from and to the top) or -1
381
+ (from and to the bottom).
382
+
383
+ labels : list of (str or None)
384
+ List of labels for the flows (or a single label to be used for all
385
+ flows). Each label may be *None* (no label), or a labeling string.
386
+ If an entry is a (possibly empty) string, then the quantity for the
387
+ corresponding flow will be shown below the string. However, if
388
+ the *unit* of the main diagram is None, then quantities are never
389
+ shown, regardless of the value of this argument.
390
+
391
+ trunklength : float
392
+ Length between the bases of the input and output groups (in
393
+ data-space units).
394
+
395
+ pathlengths : list of float
396
+ List of lengths of the vertical arrows before break-in or after
397
+ break-away. If a single value is given, then it will be applied to
398
+ the first (inside) paths on the top and bottom, and the length of
399
+ all other arrows will be justified accordingly. The *pathlengths*
400
+ are not applied to the horizontal inputs and outputs.
401
+
402
+ prior : int
403
+ Index of the prior diagram to which this diagram should be
404
+ connected.
405
+
406
+ connect : (int, int)
407
+ A (prior, this) tuple indexing the flow of the prior diagram and
408
+ the flow of this diagram which should be connected. If this is the
409
+ first diagram or *prior* is *None*, *connect* will be ignored.
410
+
411
+ rotation : float
412
+ Angle of rotation of the diagram in degrees. The interpretation of
413
+ the *orientations* argument will be rotated accordingly (e.g., if
414
+ *rotation* == 90, an *orientations* entry of 1 means to/from the
415
+ left). *rotation* is ignored if this diagram is connected to an
416
+ existing one (using *prior* and *connect*).
417
+
418
+ Returns
419
+ -------
420
+ Sankey
421
+ The current `.Sankey` instance.
422
+
423
+ Other Parameters
424
+ ----------------
425
+ **kwargs
426
+ Additional keyword arguments set `matplotlib.patches.PathPatch`
427
+ properties, listed below. For example, one may want to use
428
+ ``fill=False`` or ``label="A legend entry"``.
429
+
430
+ %(Patch:kwdoc)s
431
+
432
+ See Also
433
+ --------
434
+ Sankey.finish
435
+ """
436
+ # Check and preprocess the arguments.
437
+ flows = np.array([1.0, -1.0]) if flows is None else np.array(flows)
438
+ n = flows.shape[0] # Number of flows
439
+ if rotation is None:
440
+ rotation = 0
441
+ else:
442
+ # In the code below, angles are expressed in deg/90.
443
+ rotation /= 90.0
444
+ if orientations is None:
445
+ orientations = 0
446
+ try:
447
+ orientations = np.broadcast_to(orientations, n)
448
+ except ValueError:
449
+ raise ValueError(
450
+ f"The shapes of 'flows' {np.shape(flows)} and 'orientations' "
451
+ f"{np.shape(orientations)} are incompatible"
452
+ ) from None
453
+ try:
454
+ labels = np.broadcast_to(labels, n)
455
+ except ValueError:
456
+ raise ValueError(
457
+ f"The shapes of 'flows' {np.shape(flows)} and 'labels' "
458
+ f"{np.shape(labels)} are incompatible"
459
+ ) from None
460
+ if trunklength < 0:
461
+ raise ValueError(
462
+ "'trunklength' is negative, which is not allowed because it "
463
+ "would cause poor layout")
464
+ if abs(np.sum(flows)) > self.tolerance:
465
+ _log.info("The sum of the flows is nonzero (%f; patchlabel=%r); "
466
+ "is the system not at steady state?",
467
+ np.sum(flows), patchlabel)
468
+ scaled_flows = self.scale * flows
469
+ gain = sum(max(flow, 0) for flow in scaled_flows)
470
+ loss = sum(min(flow, 0) for flow in scaled_flows)
471
+ if prior is not None:
472
+ if prior < 0:
473
+ raise ValueError("The index of the prior diagram is negative")
474
+ if min(connect) < 0:
475
+ raise ValueError(
476
+ "At least one of the connection indices is negative")
477
+ if prior >= len(self.diagrams):
478
+ raise ValueError(
479
+ f"The index of the prior diagram is {prior}, but there "
480
+ f"are only {len(self.diagrams)} other diagrams")
481
+ if connect[0] >= len(self.diagrams[prior].flows):
482
+ raise ValueError(
483
+ "The connection index to the source diagram is {}, but "
484
+ "that diagram has only {} flows".format(
485
+ connect[0], len(self.diagrams[prior].flows)))
486
+ if connect[1] >= n:
487
+ raise ValueError(
488
+ f"The connection index to this diagram is {connect[1]}, "
489
+ f"but this diagram has only {n} flows")
490
+ if self.diagrams[prior].angles[connect[0]] is None:
491
+ raise ValueError(
492
+ f"The connection cannot be made, which may occur if the "
493
+ f"magnitude of flow {connect[0]} of diagram {prior} is "
494
+ f"less than the specified tolerance")
495
+ flow_error = (self.diagrams[prior].flows[connect[0]] +
496
+ flows[connect[1]])
497
+ if abs(flow_error) >= self.tolerance:
498
+ raise ValueError(
499
+ f"The scaled sum of the connected flows is {flow_error}, "
500
+ f"which is not within the tolerance ({self.tolerance})")
501
+
502
+ # Determine if the flows are inputs.
503
+ are_inputs = [None] * n
504
+ for i, flow in enumerate(flows):
505
+ if flow >= self.tolerance:
506
+ are_inputs[i] = True
507
+ elif flow <= -self.tolerance:
508
+ are_inputs[i] = False
509
+ else:
510
+ _log.info(
511
+ "The magnitude of flow %d (%f) is below the tolerance "
512
+ "(%f).\nIt will not be shown, and it cannot be used in a "
513
+ "connection.", i, flow, self.tolerance)
514
+
515
+ # Determine the angles of the arrows (before rotation).
516
+ angles = [None] * n
517
+ for i, (orient, is_input) in enumerate(zip(orientations, are_inputs)):
518
+ if orient == 1:
519
+ if is_input:
520
+ angles[i] = DOWN
521
+ elif is_input is False:
522
+ # Be specific since is_input can be None.
523
+ angles[i] = UP
524
+ elif orient == 0:
525
+ if is_input is not None:
526
+ angles[i] = RIGHT
527
+ else:
528
+ if orient != -1:
529
+ raise ValueError(
530
+ f"The value of orientations[{i}] is {orient}, "
531
+ f"but it must be -1, 0, or 1")
532
+ if is_input:
533
+ angles[i] = UP
534
+ elif is_input is False:
535
+ angles[i] = DOWN
536
+
537
+ # Justify the lengths of the paths.
538
+ if np.iterable(pathlengths):
539
+ if len(pathlengths) != n:
540
+ raise ValueError(
541
+ f"The lengths of 'flows' ({n}) and 'pathlengths' "
542
+ f"({len(pathlengths)}) are incompatible")
543
+ else: # Make pathlengths into a list.
544
+ urlength = pathlengths
545
+ ullength = pathlengths
546
+ lrlength = pathlengths
547
+ lllength = pathlengths
548
+ d = dict(RIGHT=pathlengths)
549
+ pathlengths = [d.get(angle, 0) for angle in angles]
550
+ # Determine the lengths of the top-side arrows
551
+ # from the middle outwards.
552
+ for i, (angle, is_input, flow) in enumerate(zip(angles, are_inputs,
553
+ scaled_flows)):
554
+ if angle == DOWN and is_input:
555
+ pathlengths[i] = ullength
556
+ ullength += flow
557
+ elif angle == UP and is_input is False:
558
+ pathlengths[i] = urlength
559
+ urlength -= flow # Flow is negative for outputs.
560
+ # Determine the lengths of the bottom-side arrows
561
+ # from the middle outwards.
562
+ for i, (angle, is_input, flow) in enumerate(reversed(list(zip(
563
+ angles, are_inputs, scaled_flows)))):
564
+ if angle == UP and is_input:
565
+ pathlengths[n - i - 1] = lllength
566
+ lllength += flow
567
+ elif angle == DOWN and is_input is False:
568
+ pathlengths[n - i - 1] = lrlength
569
+ lrlength -= flow
570
+ # Determine the lengths of the left-side arrows
571
+ # from the bottom upwards.
572
+ has_left_input = False
573
+ for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
574
+ angles, are_inputs, zip(scaled_flows, pathlengths))))):
575
+ if angle == RIGHT:
576
+ if is_input:
577
+ if has_left_input:
578
+ pathlengths[n - i - 1] = 0
579
+ else:
580
+ has_left_input = True
581
+ # Determine the lengths of the right-side arrows
582
+ # from the top downwards.
583
+ has_right_output = False
584
+ for i, (angle, is_input, spec) in enumerate(zip(
585
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
586
+ if angle == RIGHT:
587
+ if is_input is False:
588
+ if has_right_output:
589
+ pathlengths[i] = 0
590
+ else:
591
+ has_right_output = True
592
+
593
+ # Begin the subpaths, and smooth the transition if the sum of the flows
594
+ # is nonzero.
595
+ urpath = [(Path.MOVETO, [(self.gap - trunklength / 2.0), # Upper right
596
+ gain / 2.0]),
597
+ (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
598
+ gain / 2.0]),
599
+ (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
600
+ gain / 2.0]),
601
+ (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
602
+ -loss / 2.0]),
603
+ (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
604
+ -loss / 2.0]),
605
+ (Path.LINETO, [(trunklength / 2.0 - self.gap),
606
+ -loss / 2.0])]
607
+ llpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower left
608
+ loss / 2.0]),
609
+ (Path.LINETO, [(trunklength / 2.0 - self.gap) / 2.0,
610
+ loss / 2.0]),
611
+ (Path.CURVE4, [(trunklength / 2.0 - self.gap) / 8.0,
612
+ loss / 2.0]),
613
+ (Path.CURVE4, [(self.gap - trunklength / 2.0) / 8.0,
614
+ -gain / 2.0]),
615
+ (Path.LINETO, [(self.gap - trunklength / 2.0) / 2.0,
616
+ -gain / 2.0]),
617
+ (Path.LINETO, [(self.gap - trunklength / 2.0),
618
+ -gain / 2.0])]
619
+ lrpath = [(Path.LINETO, [(trunklength / 2.0 - self.gap), # Lower right
620
+ loss / 2.0])]
621
+ ulpath = [(Path.LINETO, [self.gap - trunklength / 2.0, # Upper left
622
+ gain / 2.0])]
623
+
624
+ # Add the subpaths and assign the locations of the tips and labels.
625
+ tips = np.zeros((n, 2))
626
+ label_locations = np.zeros((n, 2))
627
+ # Add the top-side inputs and outputs from the middle outwards.
628
+ for i, (angle, is_input, spec) in enumerate(zip(
629
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
630
+ if angle == DOWN and is_input:
631
+ tips[i, :], label_locations[i, :] = self._add_input(
632
+ ulpath, angle, *spec)
633
+ elif angle == UP and is_input is False:
634
+ tips[i, :], label_locations[i, :] = self._add_output(
635
+ urpath, angle, *spec)
636
+ # Add the bottom-side inputs and outputs from the middle outwards.
637
+ for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
638
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
639
+ if angle == UP and is_input:
640
+ tip, label_location = self._add_input(llpath, angle, *spec)
641
+ tips[n - i - 1, :] = tip
642
+ label_locations[n - i - 1, :] = label_location
643
+ elif angle == DOWN and is_input is False:
644
+ tip, label_location = self._add_output(lrpath, angle, *spec)
645
+ tips[n - i - 1, :] = tip
646
+ label_locations[n - i - 1, :] = label_location
647
+ # Add the left-side inputs from the bottom upwards.
648
+ has_left_input = False
649
+ for i, (angle, is_input, spec) in enumerate(reversed(list(zip(
650
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))))):
651
+ if angle == RIGHT and is_input:
652
+ if not has_left_input:
653
+ # Make sure the lower path extends
654
+ # at least as far as the upper one.
655
+ if llpath[-1][1][0] > ulpath[-1][1][0]:
656
+ llpath.append((Path.LINETO, [ulpath[-1][1][0],
657
+ llpath[-1][1][1]]))
658
+ has_left_input = True
659
+ tip, label_location = self._add_input(llpath, angle, *spec)
660
+ tips[n - i - 1, :] = tip
661
+ label_locations[n - i - 1, :] = label_location
662
+ # Add the right-side outputs from the top downwards.
663
+ has_right_output = False
664
+ for i, (angle, is_input, spec) in enumerate(zip(
665
+ angles, are_inputs, list(zip(scaled_flows, pathlengths)))):
666
+ if angle == RIGHT and is_input is False:
667
+ if not has_right_output:
668
+ # Make sure the upper path extends
669
+ # at least as far as the lower one.
670
+ if urpath[-1][1][0] < lrpath[-1][1][0]:
671
+ urpath.append((Path.LINETO, [lrpath[-1][1][0],
672
+ urpath[-1][1][1]]))
673
+ has_right_output = True
674
+ tips[i, :], label_locations[i, :] = self._add_output(
675
+ urpath, angle, *spec)
676
+ # Trim any hanging vertices.
677
+ if not has_left_input:
678
+ ulpath.pop()
679
+ llpath.pop()
680
+ if not has_right_output:
681
+ lrpath.pop()
682
+ urpath.pop()
683
+
684
+ # Concatenate the subpaths in the correct order (clockwise from top).
685
+ path = (urpath + self._revert(lrpath) + llpath + self._revert(ulpath) +
686
+ [(Path.CLOSEPOLY, urpath[0][1])])
687
+
688
+ # Create a patch with the Sankey outline.
689
+ codes, vertices = zip(*path)
690
+ vertices = np.array(vertices)
691
+
692
+ def _get_angle(a, r):
693
+ if a is None:
694
+ return None
695
+ else:
696
+ return a + r
697
+
698
+ if prior is None:
699
+ if rotation != 0: # By default, none of this is needed.
700
+ angles = [_get_angle(angle, rotation) for angle in angles]
701
+ rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
702
+ tips = rotate(tips)
703
+ label_locations = rotate(label_locations)
704
+ vertices = rotate(vertices)
705
+ text = self.ax.text(0, 0, s=patchlabel, ha='center', va='center')
706
+ else:
707
+ rotation = (self.diagrams[prior].angles[connect[0]] -
708
+ angles[connect[1]])
709
+ angles = [_get_angle(angle, rotation) for angle in angles]
710
+ rotate = Affine2D().rotate_deg(rotation * 90).transform_affine
711
+ tips = rotate(tips)
712
+ offset = self.diagrams[prior].tips[connect[0]] - tips[connect[1]]
713
+ translate = Affine2D().translate(*offset).transform_affine
714
+ tips = translate(tips)
715
+ label_locations = translate(rotate(label_locations))
716
+ vertices = translate(rotate(vertices))
717
+ kwds = dict(s=patchlabel, ha='center', va='center')
718
+ text = self.ax.text(*offset, **kwds)
719
+ if mpl.rcParams['_internal.classic_mode']:
720
+ fc = kwargs.pop('fc', kwargs.pop('facecolor', '#bfd1d4'))
721
+ lw = kwargs.pop('lw', kwargs.pop('linewidth', 0.5))
722
+ else:
723
+ fc = kwargs.pop('fc', kwargs.pop('facecolor', None))
724
+ lw = kwargs.pop('lw', kwargs.pop('linewidth', None))
725
+ if fc is None:
726
+ fc = self.ax._get_patches_for_fill.get_next_color()
727
+ patch = PathPatch(Path(vertices, codes), fc=fc, lw=lw, **kwargs)
728
+ self.ax.add_patch(patch)
729
+
730
+ # Add the path labels.
731
+ texts = []
732
+ for number, angle, label, location in zip(flows, angles, labels,
733
+ label_locations):
734
+ if label is None or angle is None:
735
+ label = ''
736
+ elif self.unit is not None:
737
+ if isinstance(self.format, str):
738
+ quantity = self.format % abs(number) + self.unit
739
+ elif callable(self.format):
740
+ quantity = self.format(number)
741
+ else:
742
+ raise TypeError(
743
+ 'format must be callable or a format string')
744
+ if label != '':
745
+ label += "\n"
746
+ label += quantity
747
+ texts.append(self.ax.text(x=location[0], y=location[1],
748
+ s=label,
749
+ ha='center', va='center'))
750
+ # Text objects are placed even they are empty (as long as the magnitude
751
+ # of the corresponding flow is larger than the tolerance) in case the
752
+ # user wants to provide labels later.
753
+
754
+ # Expand the size of the diagram if necessary.
755
+ self.extent = (min(np.min(vertices[:, 0]),
756
+ np.min(label_locations[:, 0]),
757
+ self.extent[0]),
758
+ max(np.max(vertices[:, 0]),
759
+ np.max(label_locations[:, 0]),
760
+ self.extent[1]),
761
+ min(np.min(vertices[:, 1]),
762
+ np.min(label_locations[:, 1]),
763
+ self.extent[2]),
764
+ max(np.max(vertices[:, 1]),
765
+ np.max(label_locations[:, 1]),
766
+ self.extent[3]))
767
+ # Include both vertices _and_ label locations in the extents; there are
768
+ # where either could determine the margins (e.g., arrow shoulders).
769
+
770
+ # Add this diagram as a subdiagram.
771
+ self.diagrams.append(
772
+ SimpleNamespace(patch=patch, flows=flows, angles=angles, tips=tips,
773
+ text=text, texts=texts))
774
+
775
+ # Allow a daisy-chained call structure (see docstring for the class).
776
+ return self
777
+
778
+ def finish(self):
779
+ """
780
+ Adjust the Axes and return a list of information about the Sankey
781
+ subdiagram(s).
782
+
783
+ Returns a list of subdiagrams with the following fields:
784
+
785
+ ======== =============================================================
786
+ Field Description
787
+ ======== =============================================================
788
+ *patch* Sankey outline (a `~matplotlib.patches.PathPatch`).
789
+ *flows* Flow values (positive for input, negative for output).
790
+ *angles* List of angles of the arrows [deg/90].
791
+ For example, if the diagram has not been rotated,
792
+ an input to the top side has an angle of 3 (DOWN),
793
+ and an output from the top side has an angle of 1 (UP).
794
+ If a flow has been skipped (because its magnitude is less
795
+ than *tolerance*), then its angle will be *None*.
796
+ *tips* (N, 2)-array of the (x, y) positions of the tips (or "dips")
797
+ of the flow paths.
798
+ If the magnitude of a flow is less the *tolerance* of this
799
+ `Sankey` instance, the flow is skipped and its tip will be at
800
+ the center of the diagram.
801
+ *text* `.Text` instance for the diagram label.
802
+ *texts* List of `.Text` instances for the flow labels.
803
+ ======== =============================================================
804
+
805
+ See Also
806
+ --------
807
+ Sankey.add
808
+ """
809
+ self.ax.axis([self.extent[0] - self.margin,
810
+ self.extent[1] + self.margin,
811
+ self.extent[2] - self.margin,
812
+ self.extent[3] + self.margin])
813
+ self.ax.set_aspect('equal', adjustable='datalim')
814
+ return self.diagrams
llava_next/lib/python3.10/site-packages/matplotlib/sankey.pyi ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib.axes import Axes
2
+
3
+ from collections.abc import Callable, Iterable
4
+ from typing import Any
5
+
6
+ import numpy as np
7
+
8
+ __license__: str
9
+ __credits__: list[str]
10
+ __author__: str
11
+ __version__: str
12
+
13
+ RIGHT: int
14
+ UP: int
15
+ DOWN: int
16
+
17
+ # TODO typing units
18
+ class Sankey:
19
+ diagrams: list[Any]
20
+ ax: Axes
21
+ unit: Any
22
+ format: str | Callable[[float], str]
23
+ scale: float
24
+ gap: float
25
+ radius: float
26
+ shoulder: float
27
+ offset: float
28
+ margin: float
29
+ pitch: float
30
+ tolerance: float
31
+ extent: np.ndarray
32
+ def __init__(
33
+ self,
34
+ ax: Axes | None = ...,
35
+ scale: float = ...,
36
+ unit: Any = ...,
37
+ format: str | Callable[[float], str] = ...,
38
+ gap: float = ...,
39
+ radius: float = ...,
40
+ shoulder: float = ...,
41
+ offset: float = ...,
42
+ head_angle: float = ...,
43
+ margin: float = ...,
44
+ tolerance: float = ...,
45
+ **kwargs
46
+ ) -> None: ...
47
+ def add(
48
+ self,
49
+ patchlabel: str = ...,
50
+ flows: Iterable[float] | None = ...,
51
+ orientations: Iterable[int] | None = ...,
52
+ labels: str | Iterable[str | None] = ...,
53
+ trunklength: float = ...,
54
+ pathlengths: float | Iterable[float] = ...,
55
+ prior: int | None = ...,
56
+ connect: tuple[int, int] = ...,
57
+ rotation: float = ...,
58
+ **kwargs
59
+ # Replace return with Self when py3.9 is dropped
60
+ ) -> Sankey: ...
61
+ def finish(self) -> list[Any]: ...
llava_next/lib/python3.10/site-packages/matplotlib/streamplot.pyi ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib.axes import Axes
2
+ from matplotlib.colors import Normalize, Colormap
3
+ from matplotlib.collections import LineCollection, PatchCollection
4
+ from matplotlib.patches import ArrowStyle
5
+ from matplotlib.transforms import Transform
6
+
7
+ from typing import Literal
8
+ from numpy.typing import ArrayLike
9
+ from .typing import ColorType
10
+
11
+ def streamplot(
12
+ axes: Axes,
13
+ x: ArrayLike,
14
+ y: ArrayLike,
15
+ u: ArrayLike,
16
+ v: ArrayLike,
17
+ density: float | tuple[float, float] = ...,
18
+ linewidth: float | ArrayLike | None = ...,
19
+ color: ColorType | ArrayLike | None = ...,
20
+ cmap: str | Colormap | None = ...,
21
+ norm: str | Normalize | None = ...,
22
+ arrowsize: float = ...,
23
+ arrowstyle: str | ArrowStyle = ...,
24
+ minlength: float = ...,
25
+ transform: Transform | None = ...,
26
+ zorder: float | None = ...,
27
+ start_points: ArrayLike | None = ...,
28
+ maxlength: float = ...,
29
+ integration_direction: Literal["forward", "backward", "both"] = ...,
30
+ broken_streamlines: bool = ...,
31
+ ) -> StreamplotSet: ...
32
+
33
+ class StreamplotSet:
34
+ lines: LineCollection
35
+ arrows: PatchCollection
36
+ def __init__(self, lines: LineCollection, arrows: PatchCollection) -> None: ...
37
+
38
+ class DomainMap:
39
+ grid: Grid
40
+ mask: StreamMask
41
+ x_grid2mask: float
42
+ y_grid2mask: float
43
+ x_mask2grid: float
44
+ y_mask2grid: float
45
+ x_data2grid: float
46
+ y_data2grid: float
47
+ def __init__(self, grid: Grid, mask: StreamMask) -> None: ...
48
+ def grid2mask(self, xi: float, yi: float) -> tuple[int, int]: ...
49
+ def mask2grid(self, xm: float, ym: float) -> tuple[float, float]: ...
50
+ def data2grid(self, xd: float, yd: float) -> tuple[float, float]: ...
51
+ def grid2data(self, xg: float, yg: float) -> tuple[float, float]: ...
52
+ def start_trajectory(
53
+ self, xg: float, yg: float, broken_streamlines: bool = ...
54
+ ) -> None: ...
55
+ def reset_start_point(self, xg: float, yg: float) -> None: ...
56
+ def update_trajectory(self, xg, yg, broken_streamlines: bool = ...) -> None: ...
57
+ def undo_trajectory(self) -> None: ...
58
+
59
+ class Grid:
60
+ nx: int
61
+ ny: int
62
+ dx: float
63
+ dy: float
64
+ x_origin: float
65
+ y_origin: float
66
+ width: float
67
+ height: float
68
+ def __init__(self, x: ArrayLike, y: ArrayLike) -> None: ...
69
+ @property
70
+ def shape(self) -> tuple[int, int]: ...
71
+ def within_grid(self, xi: float, yi: float) -> bool: ...
72
+
73
+ class StreamMask:
74
+ nx: int
75
+ ny: int
76
+ shape: tuple[int, int]
77
+ def __init__(self, density: float | tuple[float, float]) -> None: ...
78
+ def __getitem__(self, args): ...
79
+
80
+ class InvalidIndexError(Exception): ...
81
+ class TerminateTrajectory(Exception): ...
82
+ class OutOfBounds(IndexError): ...
llava_next/lib/python3.10/site-packages/matplotlib/style/__init__.py ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ from .core import available, context, library, reload_library, use
2
+
3
+
4
+ __all__ = ["available", "context", "library", "reload_library", "use"]
llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (304 Bytes). View file
 
llava_next/lib/python3.10/site-packages/matplotlib/style/__pycache__/core.cpython-310.pyc ADDED
Binary file (7.33 kB). View file
 
llava_next/lib/python3.10/site-packages/matplotlib/style/core.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Core functions and attributes for the matplotlib style library:
3
+
4
+ ``use``
5
+ Select style sheet to override the current matplotlib settings.
6
+ ``context``
7
+ Context manager to use a style sheet temporarily.
8
+ ``available``
9
+ List available style sheets.
10
+ ``library``
11
+ A dictionary of style names and matplotlib settings.
12
+ """
13
+
14
+ import contextlib
15
+ import logging
16
+ import os
17
+ from pathlib import Path
18
+ import sys
19
+ import warnings
20
+
21
+ if sys.version_info >= (3, 10):
22
+ import importlib.resources as importlib_resources
23
+ else:
24
+ # Even though Py3.9 has importlib.resources, it doesn't properly handle
25
+ # modules added in sys.path.
26
+ import importlib_resources
27
+
28
+ import matplotlib as mpl
29
+ from matplotlib import _api, _docstring, _rc_params_in_file, rcParamsDefault
30
+
31
+ _log = logging.getLogger(__name__)
32
+
33
+ __all__ = ['use', 'context', 'available', 'library', 'reload_library']
34
+
35
+
36
+ BASE_LIBRARY_PATH = os.path.join(mpl.get_data_path(), 'stylelib')
37
+ # Users may want multiple library paths, so store a list of paths.
38
+ USER_LIBRARY_PATHS = [os.path.join(mpl.get_configdir(), 'stylelib')]
39
+ STYLE_EXTENSION = 'mplstyle'
40
+ # A list of rcParams that should not be applied from styles
41
+ STYLE_BLACKLIST = {
42
+ 'interactive', 'backend', 'webagg.port', 'webagg.address',
43
+ 'webagg.port_retries', 'webagg.open_in_browser', 'backend_fallback',
44
+ 'toolbar', 'timezone', 'figure.max_open_warning',
45
+ 'figure.raise_window', 'savefig.directory', 'tk.window_focus',
46
+ 'docstring.hardcopy', 'date.epoch'}
47
+
48
+
49
+ @_docstring.Substitution(
50
+ "\n".join(map("- {}".format, sorted(STYLE_BLACKLIST, key=str.lower)))
51
+ )
52
+ def use(style):
53
+ """
54
+ Use Matplotlib style settings from a style specification.
55
+
56
+ The style name of 'default' is reserved for reverting back to
57
+ the default style settings.
58
+
59
+ .. note::
60
+
61
+ This updates the `.rcParams` with the settings from the style.
62
+ `.rcParams` not defined in the style are kept.
63
+
64
+ Parameters
65
+ ----------
66
+ style : str, dict, Path or list
67
+
68
+ A style specification. Valid options are:
69
+
70
+ str
71
+ - One of the style names in `.style.available` (a builtin style or
72
+ a style installed in the user library path).
73
+
74
+ - A dotted name of the form "package.style_name"; in that case,
75
+ "package" should be an importable Python package name, e.g. at
76
+ ``/path/to/package/__init__.py``; the loaded style file is
77
+ ``/path/to/package/style_name.mplstyle``. (Style files in
78
+ subpackages are likewise supported.)
79
+
80
+ - The path or URL to a style file, which gets loaded by
81
+ `.rc_params_from_file`.
82
+
83
+ dict
84
+ A mapping of key/value pairs for `matplotlib.rcParams`.
85
+
86
+ Path
87
+ The path to a style file, which gets loaded by
88
+ `.rc_params_from_file`.
89
+
90
+ list
91
+ A list of style specifiers (str, Path or dict), which are applied
92
+ from first to last in the list.
93
+
94
+ Notes
95
+ -----
96
+ The following `.rcParams` are not related to style and will be ignored if
97
+ found in a style specification:
98
+
99
+ %s
100
+ """
101
+ if isinstance(style, (str, Path)) or hasattr(style, 'keys'):
102
+ # If name is a single str, Path or dict, make it a single element list.
103
+ styles = [style]
104
+ else:
105
+ styles = style
106
+
107
+ style_alias = {'mpl20': 'default', 'mpl15': 'classic'}
108
+
109
+ for style in styles:
110
+ if isinstance(style, str):
111
+ style = style_alias.get(style, style)
112
+ if style == "default":
113
+ # Deprecation warnings were already handled when creating
114
+ # rcParamsDefault, no need to reemit them here.
115
+ with _api.suppress_matplotlib_deprecation_warning():
116
+ # don't trigger RcParams.__getitem__('backend')
117
+ style = {k: rcParamsDefault[k] for k in rcParamsDefault
118
+ if k not in STYLE_BLACKLIST}
119
+ elif style in library:
120
+ style = library[style]
121
+ elif "." in style:
122
+ pkg, _, name = style.rpartition(".")
123
+ try:
124
+ path = (importlib_resources.files(pkg)
125
+ / f"{name}.{STYLE_EXTENSION}")
126
+ style = _rc_params_in_file(path)
127
+ except (ModuleNotFoundError, OSError, TypeError) as exc:
128
+ # There is an ambiguity whether a dotted name refers to a
129
+ # package.style_name or to a dotted file path. Currently,
130
+ # we silently try the first form and then the second one;
131
+ # in the future, we may consider forcing file paths to
132
+ # either use Path objects or be prepended with "./" and use
133
+ # the slash as marker for file paths.
134
+ pass
135
+ if isinstance(style, (str, Path)):
136
+ try:
137
+ style = _rc_params_in_file(style)
138
+ except OSError as err:
139
+ raise OSError(
140
+ f"{style!r} is not a valid package style, path of style "
141
+ f"file, URL of style file, or library style name (library "
142
+ f"styles are listed in `style.available`)") from err
143
+ filtered = {}
144
+ for k in style: # don't trigger RcParams.__getitem__('backend')
145
+ if k in STYLE_BLACKLIST:
146
+ _api.warn_external(
147
+ f"Style includes a parameter, {k!r}, that is not "
148
+ f"related to style. Ignoring this parameter.")
149
+ else:
150
+ filtered[k] = style[k]
151
+ mpl.rcParams.update(filtered)
152
+
153
+
154
+ @contextlib.contextmanager
155
+ def context(style, after_reset=False):
156
+ """
157
+ Context manager for using style settings temporarily.
158
+
159
+ Parameters
160
+ ----------
161
+ style : str, dict, Path or list
162
+ A style specification. Valid options are:
163
+
164
+ str
165
+ - One of the style names in `.style.available` (a builtin style or
166
+ a style installed in the user library path).
167
+
168
+ - A dotted name of the form "package.style_name"; in that case,
169
+ "package" should be an importable Python package name, e.g. at
170
+ ``/path/to/package/__init__.py``; the loaded style file is
171
+ ``/path/to/package/style_name.mplstyle``. (Style files in
172
+ subpackages are likewise supported.)
173
+
174
+ - The path or URL to a style file, which gets loaded by
175
+ `.rc_params_from_file`.
176
+ dict
177
+ A mapping of key/value pairs for `matplotlib.rcParams`.
178
+
179
+ Path
180
+ The path to a style file, which gets loaded by
181
+ `.rc_params_from_file`.
182
+
183
+ list
184
+ A list of style specifiers (str, Path or dict), which are applied
185
+ from first to last in the list.
186
+
187
+ after_reset : bool
188
+ If True, apply style after resetting settings to their defaults;
189
+ otherwise, apply style on top of the current settings.
190
+ """
191
+ with mpl.rc_context():
192
+ if after_reset:
193
+ mpl.rcdefaults()
194
+ use(style)
195
+ yield
196
+
197
+
198
+ def update_user_library(library):
199
+ """Update style library with user-defined rc files."""
200
+ for stylelib_path in map(os.path.expanduser, USER_LIBRARY_PATHS):
201
+ styles = read_style_directory(stylelib_path)
202
+ update_nested_dict(library, styles)
203
+ return library
204
+
205
+
206
+ def read_style_directory(style_dir):
207
+ """Return dictionary of styles defined in *style_dir*."""
208
+ styles = dict()
209
+ for path in Path(style_dir).glob(f"*.{STYLE_EXTENSION}"):
210
+ with warnings.catch_warnings(record=True) as warns:
211
+ styles[path.stem] = _rc_params_in_file(path)
212
+ for w in warns:
213
+ _log.warning('In %s: %s', path, w.message)
214
+ return styles
215
+
216
+
217
+ def update_nested_dict(main_dict, new_dict):
218
+ """
219
+ Update nested dict (only level of nesting) with new values.
220
+
221
+ Unlike `dict.update`, this assumes that the values of the parent dict are
222
+ dicts (or dict-like), so you shouldn't replace the nested dict if it
223
+ already exists. Instead you should update the sub-dict.
224
+ """
225
+ # update named styles specified by user
226
+ for name, rc_dict in new_dict.items():
227
+ main_dict.setdefault(name, {}).update(rc_dict)
228
+ return main_dict
229
+
230
+
231
+ # Load style library
232
+ # ==================
233
+ _base_library = read_style_directory(BASE_LIBRARY_PATH)
234
+ library = {}
235
+ available = []
236
+
237
+
238
+ def reload_library():
239
+ """Reload the style library."""
240
+ library.clear()
241
+ library.update(update_user_library(_base_library))
242
+ available[:] = sorted(library.keys())
243
+
244
+
245
+ reload_library()
llava_next/lib/python3.10/site-packages/matplotlib/style/core.pyi ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Generator
2
+ import contextlib
3
+
4
+ from matplotlib import RcParams
5
+ from matplotlib.typing import RcStyleType
6
+
7
+ USER_LIBRARY_PATHS: list[str] = ...
8
+ STYLE_EXTENSION: str = ...
9
+
10
+ def use(style: RcStyleType) -> None: ...
11
+ @contextlib.contextmanager
12
+ def context(
13
+ style: RcStyleType, after_reset: bool = ...
14
+ ) -> Generator[None, None, None]: ...
15
+
16
+ library: dict[str, RcParams]
17
+ available: list[str]
18
+
19
+ def reload_library() -> None: ...
llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.py ADDED
@@ -0,0 +1,234 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper functions for testing.
3
+ """
4
+ from pathlib import Path
5
+ from tempfile import TemporaryDirectory
6
+ import locale
7
+ import logging
8
+ import os
9
+ import subprocess
10
+ import sys
11
+
12
+ import matplotlib as mpl
13
+ from matplotlib import _api
14
+
15
+ _log = logging.getLogger(__name__)
16
+
17
+
18
+ def set_font_settings_for_testing():
19
+ mpl.rcParams['font.family'] = 'DejaVu Sans'
20
+ mpl.rcParams['text.hinting'] = 'none'
21
+ mpl.rcParams['text.hinting_factor'] = 8
22
+
23
+
24
+ def set_reproducibility_for_testing():
25
+ mpl.rcParams['svg.hashsalt'] = 'matplotlib'
26
+
27
+
28
+ def setup():
29
+ # The baseline images are created in this locale, so we should use
30
+ # it during all of the tests.
31
+
32
+ try:
33
+ locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
34
+ except locale.Error:
35
+ try:
36
+ locale.setlocale(locale.LC_ALL, 'English_United States.1252')
37
+ except locale.Error:
38
+ _log.warning(
39
+ "Could not set locale to English/United States. "
40
+ "Some date-related tests may fail.")
41
+
42
+ mpl.use('Agg')
43
+
44
+ with _api.suppress_matplotlib_deprecation_warning():
45
+ mpl.rcdefaults() # Start with all defaults
46
+
47
+ # These settings *must* be hardcoded for running the comparison tests and
48
+ # are not necessarily the default values as specified in rcsetup.py.
49
+ set_font_settings_for_testing()
50
+ set_reproducibility_for_testing()
51
+
52
+
53
+ def subprocess_run_for_testing(command, env=None, timeout=60, stdout=None,
54
+ stderr=None, check=False, text=True,
55
+ capture_output=False):
56
+ """
57
+ Create and run a subprocess.
58
+
59
+ Thin wrapper around `subprocess.run`, intended for testing. Will
60
+ mark fork() failures on Cygwin as expected failures: not a
61
+ success, but not indicating a problem with the code either.
62
+
63
+ Parameters
64
+ ----------
65
+ args : list of str
66
+ env : dict[str, str]
67
+ timeout : float
68
+ stdout, stderr
69
+ check : bool
70
+ text : bool
71
+ Also called ``universal_newlines`` in subprocess. I chose this
72
+ name since the main effect is returning bytes (`False`) vs. str
73
+ (`True`), though it also tries to normalize newlines across
74
+ platforms.
75
+ capture_output : bool
76
+ Set stdout and stderr to subprocess.PIPE
77
+
78
+ Returns
79
+ -------
80
+ proc : subprocess.Popen
81
+
82
+ See Also
83
+ --------
84
+ subprocess.run
85
+
86
+ Raises
87
+ ------
88
+ pytest.xfail
89
+ If platform is Cygwin and subprocess reports a fork() failure.
90
+ """
91
+ if capture_output:
92
+ stdout = stderr = subprocess.PIPE
93
+ try:
94
+ proc = subprocess.run(
95
+ command, env=env,
96
+ timeout=timeout, check=check,
97
+ stdout=stdout, stderr=stderr,
98
+ text=text
99
+ )
100
+ except BlockingIOError:
101
+ if sys.platform == "cygwin":
102
+ # Might want to make this more specific
103
+ import pytest
104
+ pytest.xfail("Fork failure")
105
+ raise
106
+ return proc
107
+
108
+
109
+ def subprocess_run_helper(func, *args, timeout, extra_env=None):
110
+ """
111
+ Run a function in a sub-process.
112
+
113
+ Parameters
114
+ ----------
115
+ func : function
116
+ The function to be run. It must be in a module that is importable.
117
+ *args : str
118
+ Any additional command line arguments to be passed in
119
+ the first argument to ``subprocess.run``.
120
+ extra_env : dict[str, str]
121
+ Any additional environment variables to be set for the subprocess.
122
+ """
123
+ target = func.__name__
124
+ module = func.__module__
125
+ file = func.__code__.co_filename
126
+ proc = subprocess_run_for_testing(
127
+ [
128
+ sys.executable,
129
+ "-c",
130
+ f"import importlib.util;"
131
+ f"_spec = importlib.util.spec_from_file_location({module!r}, {file!r});"
132
+ f"_module = importlib.util.module_from_spec(_spec);"
133
+ f"_spec.loader.exec_module(_module);"
134
+ f"_module.{target}()",
135
+ *args
136
+ ],
137
+ env={**os.environ, "SOURCE_DATE_EPOCH": "0", **(extra_env or {})},
138
+ timeout=timeout, check=True,
139
+ stdout=subprocess.PIPE,
140
+ stderr=subprocess.PIPE,
141
+ text=True
142
+ )
143
+ return proc
144
+
145
+
146
+ def _check_for_pgf(texsystem):
147
+ """
148
+ Check if a given TeX system + pgf is available
149
+
150
+ Parameters
151
+ ----------
152
+ texsystem : str
153
+ The executable name to check
154
+ """
155
+ with TemporaryDirectory() as tmpdir:
156
+ tex_path = Path(tmpdir, "test.tex")
157
+ tex_path.write_text(r"""
158
+ \documentclass{article}
159
+ \usepackage{pgf}
160
+ \begin{document}
161
+ \typeout{pgfversion=\pgfversion}
162
+ \makeatletter
163
+ \@@end
164
+ """, encoding="utf-8")
165
+ try:
166
+ subprocess.check_call(
167
+ [texsystem, "-halt-on-error", str(tex_path)], cwd=tmpdir,
168
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
169
+ except (OSError, subprocess.CalledProcessError):
170
+ return False
171
+ return True
172
+
173
+
174
+ def _has_tex_package(package):
175
+ try:
176
+ mpl.dviread.find_tex_file(f"{package}.sty")
177
+ return True
178
+ except FileNotFoundError:
179
+ return False
180
+
181
+
182
+ def ipython_in_subprocess(requested_backend_or_gui_framework, all_expected_backends):
183
+ import pytest
184
+ IPython = pytest.importorskip("IPython")
185
+
186
+ if sys.platform == "win32":
187
+ pytest.skip("Cannot change backend running IPython in subprocess on Windows")
188
+
189
+ if (IPython.version_info[:3] == (8, 24, 0) and
190
+ requested_backend_or_gui_framework == "osx"):
191
+ pytest.skip("Bug using macosx backend in IPython 8.24.0 fixed in 8.24.1")
192
+
193
+ # This code can be removed when Python 3.12, the latest version supported
194
+ # by IPython < 8.24, reaches end-of-life in late 2028.
195
+ for min_version, backend in all_expected_backends.items():
196
+ if IPython.version_info[:2] >= min_version:
197
+ expected_backend = backend
198
+ break
199
+
200
+ code = ("import matplotlib as mpl, matplotlib.pyplot as plt;"
201
+ "fig, ax=plt.subplots(); ax.plot([1, 3, 2]); mpl.get_backend()")
202
+ proc = subprocess_run_for_testing(
203
+ [
204
+ "ipython",
205
+ "--no-simple-prompt",
206
+ f"--matplotlib={requested_backend_or_gui_framework}",
207
+ "-c", code,
208
+ ],
209
+ check=True,
210
+ capture_output=True,
211
+ )
212
+
213
+ assert proc.stdout.strip().endswith(f"'{expected_backend}'")
214
+
215
+
216
+ def is_ci_environment():
217
+ # Common CI variables
218
+ ci_environment_variables = [
219
+ 'CI', # Generic CI environment variable
220
+ 'CONTINUOUS_INTEGRATION', # Generic CI environment variable
221
+ 'TRAVIS', # Travis CI
222
+ 'CIRCLECI', # CircleCI
223
+ 'JENKINS', # Jenkins
224
+ 'GITLAB_CI', # GitLab CI
225
+ 'GITHUB_ACTIONS', # GitHub Actions
226
+ 'TEAMCITY_VERSION' # TeamCity
227
+ # Add other CI environment variables as needed
228
+ ]
229
+
230
+ for env_var in ci_environment_variables:
231
+ if os.getenv(env_var):
232
+ return True
233
+
234
+ return False
llava_next/lib/python3.10/site-packages/matplotlib/testing/__init__.pyi ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from collections.abc import Callable
2
+ import subprocess
3
+ from typing import Any, IO, Literal, overload
4
+
5
+ def set_font_settings_for_testing() -> None: ...
6
+ def set_reproducibility_for_testing() -> None: ...
7
+ def setup() -> None: ...
8
+ @overload
9
+ def subprocess_run_for_testing(
10
+ command: list[str],
11
+ env: dict[str, str] | None = ...,
12
+ timeout: float | None = ...,
13
+ stdout: int | IO[Any] | None = ...,
14
+ stderr: int | IO[Any] | None = ...,
15
+ check: bool = ...,
16
+ *,
17
+ text: Literal[True],
18
+ capture_output: bool = ...,
19
+ ) -> subprocess.CompletedProcess[str]: ...
20
+ @overload
21
+ def subprocess_run_for_testing(
22
+ command: list[str],
23
+ env: dict[str, str] | None = ...,
24
+ timeout: float | None = ...,
25
+ stdout: int | IO[Any] | None = ...,
26
+ stderr: int | IO[Any] | None = ...,
27
+ check: bool = ...,
28
+ text: Literal[False] = ...,
29
+ capture_output: bool = ...,
30
+ ) -> subprocess.CompletedProcess[bytes]: ...
31
+ @overload
32
+ def subprocess_run_for_testing(
33
+ command: list[str],
34
+ env: dict[str, str] | None = ...,
35
+ timeout: float | None = ...,
36
+ stdout: int | IO[Any] | None = ...,
37
+ stderr: int | IO[Any] | None = ...,
38
+ check: bool = ...,
39
+ text: bool = ...,
40
+ capture_output: bool = ...,
41
+ ) -> subprocess.CompletedProcess[bytes] | subprocess.CompletedProcess[str]: ...
42
+ def subprocess_run_helper(
43
+ func: Callable[[], None],
44
+ *args: Any,
45
+ timeout: float,
46
+ extra_env: dict[str, str] | None = ...,
47
+ ) -> subprocess.CompletedProcess[str]: ...
48
+ def _check_for_pgf(texsystem: str) -> bool: ...
49
+ def _has_tex_package(package: str) -> bool: ...
50
+ def ipython_in_subprocess(
51
+ requested_backend_or_gui_framework: str,
52
+ all_expected_backends: dict[tuple[int, int], str],
53
+ ) -> None: ...
54
+ def is_ci_environment() -> bool: ...
llava_next/lib/python3.10/site-packages/matplotlib/testing/_markers.py ADDED
@@ -0,0 +1,49 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ pytest markers for the internal Matplotlib test suite.
3
+ """
4
+
5
+ import logging
6
+ import shutil
7
+
8
+ import pytest
9
+
10
+ import matplotlib.testing
11
+ import matplotlib.testing.compare
12
+ from matplotlib import _get_executable_info, ExecutableNotFoundError
13
+
14
+
15
+ _log = logging.getLogger(__name__)
16
+
17
+
18
+ def _checkdep_usetex() -> bool:
19
+ if not shutil.which("tex"):
20
+ _log.warning("usetex mode requires TeX.")
21
+ return False
22
+ try:
23
+ _get_executable_info("dvipng")
24
+ except ExecutableNotFoundError:
25
+ _log.warning("usetex mode requires dvipng.")
26
+ return False
27
+ try:
28
+ _get_executable_info("gs")
29
+ except ExecutableNotFoundError:
30
+ _log.warning("usetex mode requires ghostscript.")
31
+ return False
32
+ return True
33
+
34
+
35
+ needs_ghostscript = pytest.mark.skipif(
36
+ "eps" not in matplotlib.testing.compare.converter,
37
+ reason="This test needs a ghostscript installation")
38
+ needs_pgf_lualatex = pytest.mark.skipif(
39
+ not matplotlib.testing._check_for_pgf('lualatex'),
40
+ reason='lualatex + pgf is required')
41
+ needs_pgf_pdflatex = pytest.mark.skipif(
42
+ not matplotlib.testing._check_for_pgf('pdflatex'),
43
+ reason='pdflatex + pgf is required')
44
+ needs_pgf_xelatex = pytest.mark.skipif(
45
+ not matplotlib.testing._check_for_pgf('xelatex'),
46
+ reason='xelatex + pgf is required')
47
+ needs_usetex = pytest.mark.skipif(
48
+ not _checkdep_usetex(),
49
+ reason="This test needs a TeX installation")