ZTWHHH commited on
Commit
b87aa96
·
verified ·
1 Parent(s): ea1ab2f

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 +3 -0
  2. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc +0 -0
  3. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc +0 -0
  4. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc +0 -0
  5. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc +0 -0
  6. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc +0 -0
  7. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc +0 -0
  8. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc +0 -0
  9. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc +0 -0
  10. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_gcutils.cpython-310.pyc +0 -0
  11. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc +0 -0
  12. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc +0 -0
  13. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc +0 -0
  14. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_tmpdirs.cpython-310.pyc +0 -0
  15. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc +0 -0
  16. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc +0 -0
  17. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc +0 -0
  18. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc +0 -0
  19. llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc +0 -0
  20. llava_next/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE +29 -0
  21. llava_next/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py +116 -0
  22. llava_next/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py +704 -0
  23. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  24. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__gcutils.cpython-310.pyc +0 -0
  25. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__pep440.cpython-310.pyc +0 -0
  26. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__testutils.cpython-310.pyc +0 -0
  27. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__threadsafety.cpython-310.pyc +0 -0
  28. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__util.cpython-310.pyc +0 -0
  29. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_array_api.cpython-310.pyc +0 -0
  30. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc +0 -0
  31. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_ccallback.cpython-310.pyc +0 -0
  32. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_deprecation.cpython-310.pyc +0 -0
  33. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_import_cycles.cpython-310.pyc +0 -0
  34. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_public_api.cpython-310.pyc +0 -0
  35. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_scipy_version.cpython-310.pyc +0 -0
  36. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_tmpdirs.cpython-310.pyc +0 -0
  37. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_warnings.cpython-310.pyc +0 -0
  38. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py +204 -0
  39. llava_next/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py +496 -0
  40. parrot/lib/python3.10/site-packages/et_xmlfile/__init__.py +11 -0
  41. parrot/lib/python3.10/site-packages/et_xmlfile/__pycache__/__init__.cpython-310.pyc +0 -0
  42. parrot/lib/python3.10/site-packages/et_xmlfile/__pycache__/xmlfile.cpython-310.pyc +0 -0
  43. parrot/lib/python3.10/site-packages/et_xmlfile/xmlfile.py +104 -0
  44. parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_divider.py +694 -0
  45. parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_rgb.py +157 -0
  46. parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_size.py +248 -0
  47. parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/inset_locator.py +561 -0
  48. parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/mpl_axes.py +128 -0
  49. parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py +257 -0
  50. parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__init__.py +10 -0
.gitattributes CHANGED
@@ -336,3 +336,6 @@ parrot/lib/python3.10/site-packages/transformers/__pycache__/modeling_tf_utils.c
336
  parrot/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
337
  moondream/lib/python3.10/site-packages/numpy.libs/libopenblas64_p-r0-0cf96a72.3.23.dev.so filter=lfs diff=lfs merge=lfs -text
338
  parrot/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
 
 
 
 
336
  parrot/lib/python3.10/site-packages/transformers/__pycache__/trainer.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
337
  moondream/lib/python3.10/site-packages/numpy.libs/libopenblas64_p-r0-0cf96a72.3.23.dev.so filter=lfs diff=lfs merge=lfs -text
338
  parrot/lib/python3.10/site-packages/sympy/combinatorics/__pycache__/perm_groups.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
339
+ parrot/lib/python3.10/site-packages/sympy/solvers/diophantine/__pycache__/diophantine.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
340
+ parrot/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
341
+ parrot/lib/python3.10/site-packages/sympy/tensor/__pycache__/tensor.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (523 Bytes). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_array_api.cpython-310.pyc ADDED
Binary file (13.7 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_bunch.cpython-310.pyc ADDED
Binary file (6.9 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_ccallback.cpython-310.pyc ADDED
Binary file (7 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_disjoint_set.cpython-310.pyc ADDED
Binary file (6.41 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_docscrape.cpython-310.pyc ADDED
Binary file (19 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_elementwise_iterative_method.cpython-310.pyc ADDED
Binary file (11.1 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_finite_differences.cpython-310.pyc ADDED
Binary file (4.03 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_gcutils.cpython-310.pyc ADDED
Binary file (3.04 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_pep440.cpython-310.pyc ADDED
Binary file (12.7 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_testutils.cpython-310.pyc ADDED
Binary file (9.88 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_threadsafety.cpython-310.pyc ADDED
Binary file (2.28 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_tmpdirs.cpython-310.pyc ADDED
Binary file (2.74 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/_util.cpython-310.pyc ADDED
Binary file (30.5 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/decorator.cpython-310.pyc ADDED
Binary file (11.4 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/deprecation.cpython-310.pyc ADDED
Binary file (7.39 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/doccer.cpython-310.pyc ADDED
Binary file (7.78 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/__pycache__/uarray.cpython-310.pyc ADDED
Binary file (783 Bytes). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/_uarray/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2018, Quansight-Labs
4
+ All rights reserved.
5
+
6
+ Redistribution and use in source and binary forms, with or without
7
+ modification, are permitted provided that the following conditions are met:
8
+
9
+ * Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ * Redistributions in binary form must reproduce the above copyright notice,
13
+ this list of conditions and the following disclaimer in the documentation
14
+ and/or other materials provided with the distribution.
15
+
16
+ * Neither the name of the copyright holder nor the names of its
17
+ contributors may be used to endorse or promote products derived from
18
+ this software without specific prior written permission.
19
+
20
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
21
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
23
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
24
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
26
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
27
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
28
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
29
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
llava_next/lib/python3.10/site-packages/scipy/_lib/_uarray/__init__.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ .. note:
3
+ If you are looking for overrides for NumPy-specific methods, see the
4
+ documentation for :obj:`unumpy`. This page explains how to write
5
+ back-ends and multimethods.
6
+
7
+ ``uarray`` is built around a back-end protocol, and overridable multimethods.
8
+ It is necessary to define multimethods for back-ends to be able to override them.
9
+ See the documentation of :obj:`generate_multimethod` on how to write multimethods.
10
+
11
+
12
+
13
+ Let's start with the simplest:
14
+
15
+ ``__ua_domain__`` defines the back-end *domain*. The domain consists of period-
16
+ separated string consisting of the modules you extend plus the submodule. For
17
+ example, if a submodule ``module2.submodule`` extends ``module1``
18
+ (i.e., it exposes dispatchables marked as types available in ``module1``),
19
+ then the domain string should be ``"module1.module2.submodule"``.
20
+
21
+
22
+ For the purpose of this demonstration, we'll be creating an object and setting
23
+ its attributes directly. However, note that you can use a module or your own type
24
+ as a backend as well.
25
+
26
+ >>> class Backend: pass
27
+ >>> be = Backend()
28
+ >>> be.__ua_domain__ = "ua_examples"
29
+
30
+ It might be useful at this point to sidetrack to the documentation of
31
+ :obj:`generate_multimethod` to find out how to generate a multimethod
32
+ overridable by :obj:`uarray`. Needless to say, writing a backend and
33
+ creating multimethods are mostly orthogonal activities, and knowing
34
+ one doesn't necessarily require knowledge of the other, although it
35
+ is certainly helpful. We expect core API designers/specifiers to write the
36
+ multimethods, and implementors to override them. But, as is often the case,
37
+ similar people write both.
38
+
39
+ Without further ado, here's an example multimethod:
40
+
41
+ >>> import uarray as ua
42
+ >>> from uarray import Dispatchable
43
+ >>> def override_me(a, b):
44
+ ... return Dispatchable(a, int),
45
+ >>> def override_replacer(args, kwargs, dispatchables):
46
+ ... return (dispatchables[0], args[1]), {}
47
+ >>> overridden_me = ua.generate_multimethod(
48
+ ... override_me, override_replacer, "ua_examples"
49
+ ... )
50
+
51
+ Next comes the part about overriding the multimethod. This requires
52
+ the ``__ua_function__`` protocol, and the ``__ua_convert__``
53
+ protocol. The ``__ua_function__`` protocol has the signature
54
+ ``(method, args, kwargs)`` where ``method`` is the passed
55
+ multimethod, ``args``/``kwargs`` specify the arguments and ``dispatchables``
56
+ is the list of converted dispatchables passed in.
57
+
58
+ >>> def __ua_function__(method, args, kwargs):
59
+ ... return method.__name__, args, kwargs
60
+ >>> be.__ua_function__ = __ua_function__
61
+
62
+ The other protocol of interest is the ``__ua_convert__`` protocol. It has the
63
+ signature ``(dispatchables, coerce)``. When ``coerce`` is ``False``, conversion
64
+ between the formats should ideally be an ``O(1)`` operation, but it means that
65
+ no memory copying should be involved, only views of the existing data.
66
+
67
+ >>> def __ua_convert__(dispatchables, coerce):
68
+ ... for d in dispatchables:
69
+ ... if d.type is int:
70
+ ... if coerce and d.coercible:
71
+ ... yield str(d.value)
72
+ ... else:
73
+ ... yield d.value
74
+ >>> be.__ua_convert__ = __ua_convert__
75
+
76
+ Now that we have defined the backend, the next thing to do is to call the multimethod.
77
+
78
+ >>> with ua.set_backend(be):
79
+ ... overridden_me(1, "2")
80
+ ('override_me', (1, '2'), {})
81
+
82
+ Note that the marked type has no effect on the actual type of the passed object.
83
+ We can also coerce the type of the input.
84
+
85
+ >>> with ua.set_backend(be, coerce=True):
86
+ ... overridden_me(1, "2")
87
+ ... overridden_me(1.0, "2")
88
+ ('override_me', ('1', '2'), {})
89
+ ('override_me', ('1.0', '2'), {})
90
+
91
+ Another feature is that if you remove ``__ua_convert__``, the arguments are not
92
+ converted at all and it's up to the backend to handle that.
93
+
94
+ >>> del be.__ua_convert__
95
+ >>> with ua.set_backend(be):
96
+ ... overridden_me(1, "2")
97
+ ('override_me', (1, '2'), {})
98
+
99
+ You also have the option to return ``NotImplemented``, in which case processing moves on
100
+ to the next back-end, which in this case, doesn't exist. The same applies to
101
+ ``__ua_convert__``.
102
+
103
+ >>> be.__ua_function__ = lambda *a, **kw: NotImplemented
104
+ >>> with ua.set_backend(be):
105
+ ... overridden_me(1, "2")
106
+ Traceback (most recent call last):
107
+ ...
108
+ uarray.BackendNotImplementedError: ...
109
+
110
+ The last possibility is if we don't have ``__ua_convert__``, in which case the job is
111
+ left up to ``__ua_function__``, but putting things back into arrays after conversion
112
+ will not be possible.
113
+ """
114
+
115
+ from ._backend import *
116
+ __version__ = '0.8.8.dev0+aa94c5a4.scipy'
llava_next/lib/python3.10/site-packages/scipy/_lib/_uarray/_backend.py ADDED
@@ -0,0 +1,704 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import typing
2
+ import types
3
+ import inspect
4
+ import functools
5
+ from . import _uarray
6
+ import copyreg
7
+ import pickle
8
+ import contextlib
9
+
10
+ from ._uarray import ( # type: ignore
11
+ BackendNotImplementedError,
12
+ _Function,
13
+ _SkipBackendContext,
14
+ _SetBackendContext,
15
+ _BackendState,
16
+ )
17
+
18
+ __all__ = [
19
+ "set_backend",
20
+ "set_global_backend",
21
+ "skip_backend",
22
+ "register_backend",
23
+ "determine_backend",
24
+ "determine_backend_multi",
25
+ "clear_backends",
26
+ "create_multimethod",
27
+ "generate_multimethod",
28
+ "_Function",
29
+ "BackendNotImplementedError",
30
+ "Dispatchable",
31
+ "wrap_single_convertor",
32
+ "wrap_single_convertor_instance",
33
+ "all_of_type",
34
+ "mark_as",
35
+ "set_state",
36
+ "get_state",
37
+ "reset_state",
38
+ "_BackendState",
39
+ "_SkipBackendContext",
40
+ "_SetBackendContext",
41
+ ]
42
+
43
+ ArgumentExtractorType = typing.Callable[..., tuple["Dispatchable", ...]]
44
+ ArgumentReplacerType = typing.Callable[
45
+ [tuple, dict, tuple], tuple[tuple, dict]
46
+ ]
47
+
48
+ def unpickle_function(mod_name, qname, self_):
49
+ import importlib
50
+
51
+ try:
52
+ module = importlib.import_module(mod_name)
53
+ qname = qname.split(".")
54
+ func = module
55
+ for q in qname:
56
+ func = getattr(func, q)
57
+
58
+ if self_ is not None:
59
+ func = types.MethodType(func, self_)
60
+
61
+ return func
62
+ except (ImportError, AttributeError) as e:
63
+ from pickle import UnpicklingError
64
+
65
+ raise UnpicklingError from e
66
+
67
+
68
+ def pickle_function(func):
69
+ mod_name = getattr(func, "__module__", None)
70
+ qname = getattr(func, "__qualname__", None)
71
+ self_ = getattr(func, "__self__", None)
72
+
73
+ try:
74
+ test = unpickle_function(mod_name, qname, self_)
75
+ except pickle.UnpicklingError:
76
+ test = None
77
+
78
+ if test is not func:
79
+ raise pickle.PicklingError(
80
+ f"Can't pickle {func}: it's not the same object as {test}"
81
+ )
82
+
83
+ return unpickle_function, (mod_name, qname, self_)
84
+
85
+
86
+ def pickle_state(state):
87
+ return _uarray._BackendState._unpickle, state._pickle()
88
+
89
+
90
+ def pickle_set_backend_context(ctx):
91
+ return _SetBackendContext, ctx._pickle()
92
+
93
+
94
+ def pickle_skip_backend_context(ctx):
95
+ return _SkipBackendContext, ctx._pickle()
96
+
97
+
98
+ copyreg.pickle(_Function, pickle_function)
99
+ copyreg.pickle(_uarray._BackendState, pickle_state)
100
+ copyreg.pickle(_SetBackendContext, pickle_set_backend_context)
101
+ copyreg.pickle(_SkipBackendContext, pickle_skip_backend_context)
102
+
103
+
104
+ def get_state():
105
+ """
106
+ Returns an opaque object containing the current state of all the backends.
107
+
108
+ Can be used for synchronization between threads/processes.
109
+
110
+ See Also
111
+ --------
112
+ set_state
113
+ Sets the state returned by this function.
114
+ """
115
+ return _uarray.get_state()
116
+
117
+
118
+ @contextlib.contextmanager
119
+ def reset_state():
120
+ """
121
+ Returns a context manager that resets all state once exited.
122
+
123
+ See Also
124
+ --------
125
+ set_state
126
+ Context manager that sets the backend state.
127
+ get_state
128
+ Gets a state to be set by this context manager.
129
+ """
130
+ with set_state(get_state()):
131
+ yield
132
+
133
+
134
+ @contextlib.contextmanager
135
+ def set_state(state):
136
+ """
137
+ A context manager that sets the state of the backends to one returned by :obj:`get_state`.
138
+
139
+ See Also
140
+ --------
141
+ get_state
142
+ Gets a state to be set by this context manager.
143
+ """ # noqa: E501
144
+ old_state = get_state()
145
+ _uarray.set_state(state)
146
+ try:
147
+ yield
148
+ finally:
149
+ _uarray.set_state(old_state, True)
150
+
151
+
152
+ def create_multimethod(*args, **kwargs):
153
+ """
154
+ Creates a decorator for generating multimethods.
155
+
156
+ This function creates a decorator that can be used with an argument
157
+ extractor in order to generate a multimethod. Other than for the
158
+ argument extractor, all arguments are passed on to
159
+ :obj:`generate_multimethod`.
160
+
161
+ See Also
162
+ --------
163
+ generate_multimethod
164
+ Generates a multimethod.
165
+ """
166
+
167
+ def wrapper(a):
168
+ return generate_multimethod(a, *args, **kwargs)
169
+
170
+ return wrapper
171
+
172
+
173
+ def generate_multimethod(
174
+ argument_extractor: ArgumentExtractorType,
175
+ argument_replacer: ArgumentReplacerType,
176
+ domain: str,
177
+ default: typing.Optional[typing.Callable] = None,
178
+ ):
179
+ """
180
+ Generates a multimethod.
181
+
182
+ Parameters
183
+ ----------
184
+ argument_extractor : ArgumentExtractorType
185
+ A callable which extracts the dispatchable arguments. Extracted arguments
186
+ should be marked by the :obj:`Dispatchable` class. It has the same signature
187
+ as the desired multimethod.
188
+ argument_replacer : ArgumentReplacerType
189
+ A callable with the signature (args, kwargs, dispatchables), which should also
190
+ return an (args, kwargs) pair with the dispatchables replaced inside the
191
+ args/kwargs.
192
+ domain : str
193
+ A string value indicating the domain of this multimethod.
194
+ default: Optional[Callable], optional
195
+ The default implementation of this multimethod, where ``None`` (the default)
196
+ specifies there is no default implementation.
197
+
198
+ Examples
199
+ --------
200
+ In this example, ``a`` is to be dispatched over, so we return it, while marking it
201
+ as an ``int``.
202
+ The trailing comma is needed because the args have to be returned as an iterable.
203
+
204
+ >>> def override_me(a, b):
205
+ ... return Dispatchable(a, int),
206
+
207
+ Next, we define the argument replacer that replaces the dispatchables inside
208
+ args/kwargs with the supplied ones.
209
+
210
+ >>> def override_replacer(args, kwargs, dispatchables):
211
+ ... return (dispatchables[0], args[1]), {}
212
+
213
+ Next, we define the multimethod.
214
+
215
+ >>> overridden_me = generate_multimethod(
216
+ ... override_me, override_replacer, "ua_examples"
217
+ ... )
218
+
219
+ Notice that there's no default implementation, unless you supply one.
220
+
221
+ >>> overridden_me(1, "a")
222
+ Traceback (most recent call last):
223
+ ...
224
+ uarray.BackendNotImplementedError: ...
225
+
226
+ >>> overridden_me2 = generate_multimethod(
227
+ ... override_me, override_replacer, "ua_examples", default=lambda x, y: (x, y)
228
+ ... )
229
+ >>> overridden_me2(1, "a")
230
+ (1, 'a')
231
+
232
+ See Also
233
+ --------
234
+ uarray
235
+ See the module documentation for how to override the method by creating
236
+ backends.
237
+ """
238
+ kw_defaults, arg_defaults, opts = get_defaults(argument_extractor)
239
+ ua_func = _Function(
240
+ argument_extractor,
241
+ argument_replacer,
242
+ domain,
243
+ arg_defaults,
244
+ kw_defaults,
245
+ default,
246
+ )
247
+
248
+ return functools.update_wrapper(ua_func, argument_extractor)
249
+
250
+
251
+ def set_backend(backend, coerce=False, only=False):
252
+ """
253
+ A context manager that sets the preferred backend.
254
+
255
+ Parameters
256
+ ----------
257
+ backend
258
+ The backend to set.
259
+ coerce
260
+ Whether or not to coerce to a specific backend's types. Implies ``only``.
261
+ only
262
+ Whether or not this should be the last backend to try.
263
+
264
+ See Also
265
+ --------
266
+ skip_backend: A context manager that allows skipping of backends.
267
+ set_global_backend: Set a single, global backend for a domain.
268
+ """
269
+ try:
270
+ return backend.__ua_cache__["set", coerce, only]
271
+ except AttributeError:
272
+ backend.__ua_cache__ = {}
273
+ except KeyError:
274
+ pass
275
+
276
+ ctx = _SetBackendContext(backend, coerce, only)
277
+ backend.__ua_cache__["set", coerce, only] = ctx
278
+ return ctx
279
+
280
+
281
+ def skip_backend(backend):
282
+ """
283
+ A context manager that allows one to skip a given backend from processing
284
+ entirely. This allows one to use another backend's code in a library that
285
+ is also a consumer of the same backend.
286
+
287
+ Parameters
288
+ ----------
289
+ backend
290
+ The backend to skip.
291
+
292
+ See Also
293
+ --------
294
+ set_backend: A context manager that allows setting of backends.
295
+ set_global_backend: Set a single, global backend for a domain.
296
+ """
297
+ try:
298
+ return backend.__ua_cache__["skip"]
299
+ except AttributeError:
300
+ backend.__ua_cache__ = {}
301
+ except KeyError:
302
+ pass
303
+
304
+ ctx = _SkipBackendContext(backend)
305
+ backend.__ua_cache__["skip"] = ctx
306
+ return ctx
307
+
308
+
309
+ def get_defaults(f):
310
+ sig = inspect.signature(f)
311
+ kw_defaults = {}
312
+ arg_defaults = []
313
+ opts = set()
314
+ for k, v in sig.parameters.items():
315
+ if v.default is not inspect.Parameter.empty:
316
+ kw_defaults[k] = v.default
317
+ if v.kind in (
318
+ inspect.Parameter.POSITIONAL_ONLY,
319
+ inspect.Parameter.POSITIONAL_OR_KEYWORD,
320
+ ):
321
+ arg_defaults.append(v.default)
322
+ opts.add(k)
323
+
324
+ return kw_defaults, tuple(arg_defaults), opts
325
+
326
+
327
+ def set_global_backend(backend, coerce=False, only=False, *, try_last=False):
328
+ """
329
+ This utility method replaces the default backend for permanent use. It
330
+ will be tried in the list of backends automatically, unless the
331
+ ``only`` flag is set on a backend. This will be the first tried
332
+ backend outside the :obj:`set_backend` context manager.
333
+
334
+ Note that this method is not thread-safe.
335
+
336
+ .. warning::
337
+ We caution library authors against using this function in
338
+ their code. We do *not* support this use-case. This function
339
+ is meant to be used only by users themselves, or by a reference
340
+ implementation, if one exists.
341
+
342
+ Parameters
343
+ ----------
344
+ backend
345
+ The backend to register.
346
+ coerce : bool
347
+ Whether to coerce input types when trying this backend.
348
+ only : bool
349
+ If ``True``, no more backends will be tried if this fails.
350
+ Implied by ``coerce=True``.
351
+ try_last : bool
352
+ If ``True``, the global backend is tried after registered backends.
353
+
354
+ See Also
355
+ --------
356
+ set_backend: A context manager that allows setting of backends.
357
+ skip_backend: A context manager that allows skipping of backends.
358
+ """
359
+ _uarray.set_global_backend(backend, coerce, only, try_last)
360
+
361
+
362
+ def register_backend(backend):
363
+ """
364
+ This utility method sets registers backend for permanent use. It
365
+ will be tried in the list of backends automatically, unless the
366
+ ``only`` flag is set on a backend.
367
+
368
+ Note that this method is not thread-safe.
369
+
370
+ Parameters
371
+ ----------
372
+ backend
373
+ The backend to register.
374
+ """
375
+ _uarray.register_backend(backend)
376
+
377
+
378
+ def clear_backends(domain, registered=True, globals=False):
379
+ """
380
+ This utility method clears registered backends.
381
+
382
+ .. warning::
383
+ We caution library authors against using this function in
384
+ their code. We do *not* support this use-case. This function
385
+ is meant to be used only by users themselves.
386
+
387
+ .. warning::
388
+ Do NOT use this method inside a multimethod call, or the
389
+ program is likely to crash.
390
+
391
+ Parameters
392
+ ----------
393
+ domain : Optional[str]
394
+ The domain for which to de-register backends. ``None`` means
395
+ de-register for all domains.
396
+ registered : bool
397
+ Whether or not to clear registered backends. See :obj:`register_backend`.
398
+ globals : bool
399
+ Whether or not to clear global backends. See :obj:`set_global_backend`.
400
+
401
+ See Also
402
+ --------
403
+ register_backend : Register a backend globally.
404
+ set_global_backend : Set a global backend.
405
+ """
406
+ _uarray.clear_backends(domain, registered, globals)
407
+
408
+
409
+ class Dispatchable:
410
+ """
411
+ A utility class which marks an argument with a specific dispatch type.
412
+
413
+
414
+ Attributes
415
+ ----------
416
+ value
417
+ The value of the Dispatchable.
418
+
419
+ type
420
+ The type of the Dispatchable.
421
+
422
+ Examples
423
+ --------
424
+ >>> x = Dispatchable(1, str)
425
+ >>> x
426
+ <Dispatchable: type=<class 'str'>, value=1>
427
+
428
+ See Also
429
+ --------
430
+ all_of_type
431
+ Marks all unmarked parameters of a function.
432
+
433
+ mark_as
434
+ Allows one to create a utility function to mark as a given type.
435
+ """
436
+
437
+ def __init__(self, value, dispatch_type, coercible=True):
438
+ self.value = value
439
+ self.type = dispatch_type
440
+ self.coercible = coercible
441
+
442
+ def __getitem__(self, index):
443
+ return (self.type, self.value)[index]
444
+
445
+ def __str__(self):
446
+ return f"<{type(self).__name__}: type={self.type!r}, value={self.value!r}>"
447
+
448
+ __repr__ = __str__
449
+
450
+
451
+ def mark_as(dispatch_type):
452
+ """
453
+ Creates a utility function to mark something as a specific type.
454
+
455
+ Examples
456
+ --------
457
+ >>> mark_int = mark_as(int)
458
+ >>> mark_int(1)
459
+ <Dispatchable: type=<class 'int'>, value=1>
460
+ """
461
+ return functools.partial(Dispatchable, dispatch_type=dispatch_type)
462
+
463
+
464
+ def all_of_type(arg_type):
465
+ """
466
+ Marks all unmarked arguments as a given type.
467
+
468
+ Examples
469
+ --------
470
+ >>> @all_of_type(str)
471
+ ... def f(a, b):
472
+ ... return a, Dispatchable(b, int)
473
+ >>> f('a', 1)
474
+ (<Dispatchable: type=<class 'str'>, value='a'>,
475
+ <Dispatchable: type=<class 'int'>, value=1>)
476
+ """
477
+
478
+ def outer(func):
479
+ @functools.wraps(func)
480
+ def inner(*args, **kwargs):
481
+ extracted_args = func(*args, **kwargs)
482
+ return tuple(
483
+ Dispatchable(arg, arg_type)
484
+ if not isinstance(arg, Dispatchable)
485
+ else arg
486
+ for arg in extracted_args
487
+ )
488
+
489
+ return inner
490
+
491
+ return outer
492
+
493
+
494
+ def wrap_single_convertor(convert_single):
495
+ """
496
+ Wraps a ``__ua_convert__`` defined for a single element to all elements.
497
+ If any of them return ``NotImplemented``, the operation is assumed to be
498
+ undefined.
499
+
500
+ Accepts a signature of (value, type, coerce).
501
+ """
502
+
503
+ @functools.wraps(convert_single)
504
+ def __ua_convert__(dispatchables, coerce):
505
+ converted = []
506
+ for d in dispatchables:
507
+ c = convert_single(d.value, d.type, coerce and d.coercible)
508
+
509
+ if c is NotImplemented:
510
+ return NotImplemented
511
+
512
+ converted.append(c)
513
+
514
+ return converted
515
+
516
+ return __ua_convert__
517
+
518
+
519
+ def wrap_single_convertor_instance(convert_single):
520
+ """
521
+ Wraps a ``__ua_convert__`` defined for a single element to all elements.
522
+ If any of them return ``NotImplemented``, the operation is assumed to be
523
+ undefined.
524
+
525
+ Accepts a signature of (value, type, coerce).
526
+ """
527
+
528
+ @functools.wraps(convert_single)
529
+ def __ua_convert__(self, dispatchables, coerce):
530
+ converted = []
531
+ for d in dispatchables:
532
+ c = convert_single(self, d.value, d.type, coerce and d.coercible)
533
+
534
+ if c is NotImplemented:
535
+ return NotImplemented
536
+
537
+ converted.append(c)
538
+
539
+ return converted
540
+
541
+ return __ua_convert__
542
+
543
+
544
+ def determine_backend(value, dispatch_type, *, domain, only=True, coerce=False):
545
+ """Set the backend to the first active backend that supports ``value``
546
+
547
+ This is useful for functions that call multimethods without any dispatchable
548
+ arguments. You can use :func:`determine_backend` to ensure the same backend
549
+ is used everywhere in a block of multimethod calls.
550
+
551
+ Parameters
552
+ ----------
553
+ value
554
+ The value being tested
555
+ dispatch_type
556
+ The dispatch type associated with ``value``, aka
557
+ ":ref:`marking <MarkingGlossary>`".
558
+ domain: string
559
+ The domain to query for backends and set.
560
+ coerce: bool
561
+ Whether or not to allow coercion to the backend's types. Implies ``only``.
562
+ only: bool
563
+ Whether or not this should be the last backend to try.
564
+
565
+ See Also
566
+ --------
567
+ set_backend: For when you know which backend to set
568
+
569
+ Notes
570
+ -----
571
+
572
+ Support is determined by the ``__ua_convert__`` protocol. Backends not
573
+ supporting the type must return ``NotImplemented`` from their
574
+ ``__ua_convert__`` if they don't support input of that type.
575
+
576
+ Examples
577
+ --------
578
+
579
+ Suppose we have two backends ``BackendA`` and ``BackendB`` each supporting
580
+ different types, ``TypeA`` and ``TypeB``. Neither supporting the other type:
581
+
582
+ >>> with ua.set_backend(ex.BackendA):
583
+ ... ex.call_multimethod(ex.TypeB(), ex.TypeB())
584
+ Traceback (most recent call last):
585
+ ...
586
+ uarray.BackendNotImplementedError: ...
587
+
588
+ Now consider a multimethod that creates a new object of ``TypeA``, or
589
+ ``TypeB`` depending on the active backend.
590
+
591
+ >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
592
+ ... res = ex.creation_multimethod()
593
+ ... ex.call_multimethod(res, ex.TypeA())
594
+ Traceback (most recent call last):
595
+ ...
596
+ uarray.BackendNotImplementedError: ...
597
+
598
+ ``res`` is an object of ``TypeB`` because ``BackendB`` is set in the
599
+ innermost with statement. So, ``call_multimethod`` fails since the types
600
+ don't match.
601
+
602
+ Instead, we need to first find a backend suitable for all of our objects.
603
+
604
+ >>> with ua.set_backend(ex.BackendA), ua.set_backend(ex.BackendB):
605
+ ... x = ex.TypeA()
606
+ ... with ua.determine_backend(x, "mark", domain="ua_examples"):
607
+ ... res = ex.creation_multimethod()
608
+ ... ex.call_multimethod(res, x)
609
+ TypeA
610
+
611
+ """
612
+ dispatchables = (Dispatchable(value, dispatch_type, coerce),)
613
+ backend = _uarray.determine_backend(domain, dispatchables, coerce)
614
+
615
+ return set_backend(backend, coerce=coerce, only=only)
616
+
617
+
618
+ def determine_backend_multi(
619
+ dispatchables, *, domain, only=True, coerce=False, **kwargs
620
+ ):
621
+ """Set a backend supporting all ``dispatchables``
622
+
623
+ This is useful for functions that call multimethods without any dispatchable
624
+ arguments. You can use :func:`determine_backend_multi` to ensure the same
625
+ backend is used everywhere in a block of multimethod calls involving
626
+ multiple arrays.
627
+
628
+ Parameters
629
+ ----------
630
+ dispatchables: Sequence[Union[uarray.Dispatchable, Any]]
631
+ The dispatchables that must be supported
632
+ domain: string
633
+ The domain to query for backends and set.
634
+ coerce: bool
635
+ Whether or not to allow coercion to the backend's types. Implies ``only``.
636
+ only: bool
637
+ Whether or not this should be the last backend to try.
638
+ dispatch_type: Optional[Any]
639
+ The default dispatch type associated with ``dispatchables``, aka
640
+ ":ref:`marking <MarkingGlossary>`".
641
+
642
+ See Also
643
+ --------
644
+ determine_backend: For a single dispatch value
645
+ set_backend: For when you know which backend to set
646
+
647
+ Notes
648
+ -----
649
+
650
+ Support is determined by the ``__ua_convert__`` protocol. Backends not
651
+ supporting the type must return ``NotImplemented`` from their
652
+ ``__ua_convert__`` if they don't support input of that type.
653
+
654
+ Examples
655
+ --------
656
+
657
+ :func:`determine_backend` allows the backend to be set from a single
658
+ object. :func:`determine_backend_multi` allows multiple objects to be
659
+ checked simultaneously for support in the backend. Suppose we have a
660
+ ``BackendAB`` which supports ``TypeA`` and ``TypeB`` in the same call,
661
+ and a ``BackendBC`` that doesn't support ``TypeA``.
662
+
663
+ >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
664
+ ... a, b = ex.TypeA(), ex.TypeB()
665
+ ... with ua.determine_backend_multi(
666
+ ... [ua.Dispatchable(a, "mark"), ua.Dispatchable(b, "mark")],
667
+ ... domain="ua_examples"
668
+ ... ):
669
+ ... res = ex.creation_multimethod()
670
+ ... ex.call_multimethod(res, a, b)
671
+ TypeA
672
+
673
+ This won't call ``BackendBC`` because it doesn't support ``TypeA``.
674
+
675
+ We can also use leave out the ``ua.Dispatchable`` if we specify the
676
+ default ``dispatch_type`` for the ``dispatchables`` argument.
677
+
678
+ >>> with ua.set_backend(ex.BackendAB), ua.set_backend(ex.BackendBC):
679
+ ... a, b = ex.TypeA(), ex.TypeB()
680
+ ... with ua.determine_backend_multi(
681
+ ... [a, b], dispatch_type="mark", domain="ua_examples"
682
+ ... ):
683
+ ... res = ex.creation_multimethod()
684
+ ... ex.call_multimethod(res, a, b)
685
+ TypeA
686
+
687
+ """
688
+ if "dispatch_type" in kwargs:
689
+ disp_type = kwargs.pop("dispatch_type")
690
+ dispatchables = tuple(
691
+ d if isinstance(d, Dispatchable) else Dispatchable(d, disp_type)
692
+ for d in dispatchables
693
+ )
694
+ else:
695
+ dispatchables = tuple(dispatchables)
696
+ if not all(isinstance(d, Dispatchable) for d in dispatchables):
697
+ raise TypeError("dispatchables must be instances of uarray.Dispatchable")
698
+
699
+ if len(kwargs) != 0:
700
+ raise TypeError(f"Received unexpected keyword arguments: {kwargs}")
701
+
702
+ backend = _uarray.determine_backend(domain, dispatchables, coerce)
703
+
704
+ return set_backend(backend, coerce=coerce, only=only)
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (172 Bytes). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__gcutils.cpython-310.pyc ADDED
Binary file (3.6 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__pep440.cpython-310.pyc ADDED
Binary file (2.32 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__testutils.cpython-310.pyc ADDED
Binary file (971 Bytes). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__threadsafety.cpython-310.pyc ADDED
Binary file (1.76 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test__util.cpython-310.pyc ADDED
Binary file (14.2 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_array_api.cpython-310.pyc ADDED
Binary file (4.25 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_bunch.cpython-310.pyc ADDED
Binary file (6.98 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_ccallback.cpython-310.pyc ADDED
Binary file (6.56 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_deprecation.cpython-310.pyc ADDED
Binary file (619 Bytes). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_import_cycles.cpython-310.pyc ADDED
Binary file (819 Bytes). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_public_api.cpython-310.pyc ADDED
Binary file (9.61 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_scipy_version.cpython-310.pyc ADDED
Binary file (618 Bytes). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_tmpdirs.cpython-310.pyc ADDED
Binary file (1.6 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/__pycache__/test_warnings.cpython-310.pyc ADDED
Binary file (4.29 kB). View file
 
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/test_ccallback.py ADDED
@@ -0,0 +1,204 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from numpy.testing import assert_equal, assert_
2
+ from pytest import raises as assert_raises
3
+
4
+ import time
5
+ import pytest
6
+ import ctypes
7
+ import threading
8
+ from scipy._lib import _ccallback_c as _test_ccallback_cython
9
+ from scipy._lib import _test_ccallback
10
+ from scipy._lib._ccallback import LowLevelCallable
11
+
12
+ try:
13
+ import cffi
14
+ HAVE_CFFI = True
15
+ except ImportError:
16
+ HAVE_CFFI = False
17
+
18
+
19
+ ERROR_VALUE = 2.0
20
+
21
+
22
+ def callback_python(a, user_data=None):
23
+ if a == ERROR_VALUE:
24
+ raise ValueError("bad value")
25
+
26
+ if user_data is None:
27
+ return a + 1
28
+ else:
29
+ return a + user_data
30
+
31
+ def _get_cffi_func(base, signature):
32
+ if not HAVE_CFFI:
33
+ pytest.skip("cffi not installed")
34
+
35
+ # Get function address
36
+ voidp = ctypes.cast(base, ctypes.c_void_p)
37
+ address = voidp.value
38
+
39
+ # Create corresponding cffi handle
40
+ ffi = cffi.FFI()
41
+ func = ffi.cast(signature, address)
42
+ return func
43
+
44
+
45
+ def _get_ctypes_data():
46
+ value = ctypes.c_double(2.0)
47
+ return ctypes.cast(ctypes.pointer(value), ctypes.c_voidp)
48
+
49
+
50
+ def _get_cffi_data():
51
+ if not HAVE_CFFI:
52
+ pytest.skip("cffi not installed")
53
+ ffi = cffi.FFI()
54
+ return ffi.new('double *', 2.0)
55
+
56
+
57
+ CALLERS = {
58
+ 'simple': _test_ccallback.test_call_simple,
59
+ 'nodata': _test_ccallback.test_call_nodata,
60
+ 'nonlocal': _test_ccallback.test_call_nonlocal,
61
+ 'cython': _test_ccallback_cython.test_call_cython,
62
+ }
63
+
64
+ # These functions have signatures known to the callers
65
+ FUNCS = {
66
+ 'python': lambda: callback_python,
67
+ 'capsule': lambda: _test_ccallback.test_get_plus1_capsule(),
68
+ 'cython': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
69
+ "plus1_cython"),
70
+ 'ctypes': lambda: _test_ccallback_cython.plus1_ctypes,
71
+ 'cffi': lambda: _get_cffi_func(_test_ccallback_cython.plus1_ctypes,
72
+ 'double (*)(double, int *, void *)'),
73
+ 'capsule_b': lambda: _test_ccallback.test_get_plus1b_capsule(),
74
+ 'cython_b': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
75
+ "plus1b_cython"),
76
+ 'ctypes_b': lambda: _test_ccallback_cython.plus1b_ctypes,
77
+ 'cffi_b': lambda: _get_cffi_func(_test_ccallback_cython.plus1b_ctypes,
78
+ 'double (*)(double, double, int *, void *)'),
79
+ }
80
+
81
+ # These functions have signatures the callers don't know
82
+ BAD_FUNCS = {
83
+ 'capsule_bc': lambda: _test_ccallback.test_get_plus1bc_capsule(),
84
+ 'cython_bc': lambda: LowLevelCallable.from_cython(_test_ccallback_cython,
85
+ "plus1bc_cython"),
86
+ 'ctypes_bc': lambda: _test_ccallback_cython.plus1bc_ctypes,
87
+ 'cffi_bc': lambda: _get_cffi_func(
88
+ _test_ccallback_cython.plus1bc_ctypes,
89
+ 'double (*)(double, double, double, int *, void *)'
90
+ ),
91
+ }
92
+
93
+ USER_DATAS = {
94
+ 'ctypes': _get_ctypes_data,
95
+ 'cffi': _get_cffi_data,
96
+ 'capsule': _test_ccallback.test_get_data_capsule,
97
+ }
98
+
99
+
100
+ def test_callbacks():
101
+ def check(caller, func, user_data):
102
+ caller = CALLERS[caller]
103
+ func = FUNCS[func]()
104
+ user_data = USER_DATAS[user_data]()
105
+
106
+ if func is callback_python:
107
+ def func2(x):
108
+ return func(x, 2.0)
109
+ else:
110
+ func2 = LowLevelCallable(func, user_data)
111
+ func = LowLevelCallable(func)
112
+
113
+ # Test basic call
114
+ assert_equal(caller(func, 1.0), 2.0)
115
+
116
+ # Test 'bad' value resulting to an error
117
+ assert_raises(ValueError, caller, func, ERROR_VALUE)
118
+
119
+ # Test passing in user_data
120
+ assert_equal(caller(func2, 1.0), 3.0)
121
+
122
+ for caller in sorted(CALLERS.keys()):
123
+ for func in sorted(FUNCS.keys()):
124
+ for user_data in sorted(USER_DATAS.keys()):
125
+ check(caller, func, user_data)
126
+
127
+
128
+ def test_bad_callbacks():
129
+ def check(caller, func, user_data):
130
+ caller = CALLERS[caller]
131
+ user_data = USER_DATAS[user_data]()
132
+ func = BAD_FUNCS[func]()
133
+
134
+ if func is callback_python:
135
+ def func2(x):
136
+ return func(x, 2.0)
137
+ else:
138
+ func2 = LowLevelCallable(func, user_data)
139
+ func = LowLevelCallable(func)
140
+
141
+ # Test that basic call fails
142
+ assert_raises(ValueError, caller, LowLevelCallable(func), 1.0)
143
+
144
+ # Test that passing in user_data also fails
145
+ assert_raises(ValueError, caller, func2, 1.0)
146
+
147
+ # Test error message
148
+ llfunc = LowLevelCallable(func)
149
+ try:
150
+ caller(llfunc, 1.0)
151
+ except ValueError as err:
152
+ msg = str(err)
153
+ assert_(llfunc.signature in msg, msg)
154
+ assert_('double (double, double, int *, void *)' in msg, msg)
155
+
156
+ for caller in sorted(CALLERS.keys()):
157
+ for func in sorted(BAD_FUNCS.keys()):
158
+ for user_data in sorted(USER_DATAS.keys()):
159
+ check(caller, func, user_data)
160
+
161
+
162
+ def test_signature_override():
163
+ caller = _test_ccallback.test_call_simple
164
+ func = _test_ccallback.test_get_plus1_capsule()
165
+
166
+ llcallable = LowLevelCallable(func, signature="bad signature")
167
+ assert_equal(llcallable.signature, "bad signature")
168
+ assert_raises(ValueError, caller, llcallable, 3)
169
+
170
+ llcallable = LowLevelCallable(func, signature="double (double, int *, void *)")
171
+ assert_equal(llcallable.signature, "double (double, int *, void *)")
172
+ assert_equal(caller(llcallable, 3), 4)
173
+
174
+
175
+ def test_threadsafety():
176
+ def callback(a, caller):
177
+ if a <= 0:
178
+ return 1
179
+ else:
180
+ res = caller(lambda x: callback(x, caller), a - 1)
181
+ return 2*res
182
+
183
+ def check(caller):
184
+ caller = CALLERS[caller]
185
+
186
+ results = []
187
+
188
+ count = 10
189
+
190
+ def run():
191
+ time.sleep(0.01)
192
+ r = caller(lambda x: callback(x, caller), count)
193
+ results.append(r)
194
+
195
+ threads = [threading.Thread(target=run) for j in range(20)]
196
+ for thread in threads:
197
+ thread.start()
198
+ for thread in threads:
199
+ thread.join()
200
+
201
+ assert_equal(results, [2.0**count]*len(threads))
202
+
203
+ for caller in CALLERS.keys():
204
+ check(caller)
llava_next/lib/python3.10/site-packages/scipy/_lib/tests/test_public_api.py ADDED
@@ -0,0 +1,496 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ This test script is adopted from:
3
+ https://github.com/numpy/numpy/blob/main/numpy/tests/test_public_api.py
4
+ """
5
+
6
+ import pkgutil
7
+ import types
8
+ import importlib
9
+ import warnings
10
+ from importlib import import_module
11
+
12
+ import pytest
13
+
14
+ import scipy
15
+
16
+ from scipy.conftest import xp_available_backends
17
+
18
+
19
+ def test_dir_testing():
20
+ """Assert that output of dir has only one "testing/tester"
21
+ attribute without duplicate"""
22
+ assert len(dir(scipy)) == len(set(dir(scipy)))
23
+
24
+
25
+ # Historically SciPy has not used leading underscores for private submodules
26
+ # much. This has resulted in lots of things that look like public modules
27
+ # (i.e. things that can be imported as `import scipy.somesubmodule.somefile`),
28
+ # but were never intended to be public. The PUBLIC_MODULES list contains
29
+ # modules that are either public because they were meant to be, or because they
30
+ # contain public functions/objects that aren't present in any other namespace
31
+ # for whatever reason and therefore should be treated as public.
32
+ PUBLIC_MODULES = ["scipy." + s for s in [
33
+ "cluster",
34
+ "cluster.vq",
35
+ "cluster.hierarchy",
36
+ "constants",
37
+ "datasets",
38
+ "fft",
39
+ "fftpack",
40
+ "integrate",
41
+ "interpolate",
42
+ "io",
43
+ "io.arff",
44
+ "io.matlab",
45
+ "io.wavfile",
46
+ "linalg",
47
+ "linalg.blas",
48
+ "linalg.cython_blas",
49
+ "linalg.lapack",
50
+ "linalg.cython_lapack",
51
+ "linalg.interpolative",
52
+ "misc",
53
+ "ndimage",
54
+ "odr",
55
+ "optimize",
56
+ "signal",
57
+ "signal.windows",
58
+ "sparse",
59
+ "sparse.linalg",
60
+ "sparse.csgraph",
61
+ "spatial",
62
+ "spatial.distance",
63
+ "spatial.transform",
64
+ "special",
65
+ "stats",
66
+ "stats.contingency",
67
+ "stats.distributions",
68
+ "stats.mstats",
69
+ "stats.qmc",
70
+ "stats.sampling"
71
+ ]]
72
+
73
+ # The PRIVATE_BUT_PRESENT_MODULES list contains modules that lacked underscores
74
+ # in their name and hence looked public, but weren't meant to be. All these
75
+ # namespace were deprecated in the 1.8.0 release - see "clear split between
76
+ # public and private API" in the 1.8.0 release notes.
77
+ # These private modules support will be removed in SciPy v2.0.0, as the
78
+ # deprecation messages emitted by each of these modules say.
79
+ PRIVATE_BUT_PRESENT_MODULES = [
80
+ 'scipy.constants.codata',
81
+ 'scipy.constants.constants',
82
+ 'scipy.fftpack.basic',
83
+ 'scipy.fftpack.convolve',
84
+ 'scipy.fftpack.helper',
85
+ 'scipy.fftpack.pseudo_diffs',
86
+ 'scipy.fftpack.realtransforms',
87
+ 'scipy.integrate.dop',
88
+ 'scipy.integrate.lsoda',
89
+ 'scipy.integrate.odepack',
90
+ 'scipy.integrate.quadpack',
91
+ 'scipy.integrate.vode',
92
+ 'scipy.interpolate.dfitpack',
93
+ 'scipy.interpolate.fitpack',
94
+ 'scipy.interpolate.fitpack2',
95
+ 'scipy.interpolate.interpnd',
96
+ 'scipy.interpolate.interpolate',
97
+ 'scipy.interpolate.ndgriddata',
98
+ 'scipy.interpolate.polyint',
99
+ 'scipy.interpolate.rbf',
100
+ 'scipy.io.arff.arffread',
101
+ 'scipy.io.harwell_boeing',
102
+ 'scipy.io.idl',
103
+ 'scipy.io.matlab.byteordercodes',
104
+ 'scipy.io.matlab.mio',
105
+ 'scipy.io.matlab.mio4',
106
+ 'scipy.io.matlab.mio5',
107
+ 'scipy.io.matlab.mio5_params',
108
+ 'scipy.io.matlab.mio5_utils',
109
+ 'scipy.io.matlab.mio_utils',
110
+ 'scipy.io.matlab.miobase',
111
+ 'scipy.io.matlab.streams',
112
+ 'scipy.io.mmio',
113
+ 'scipy.io.netcdf',
114
+ 'scipy.linalg.basic',
115
+ 'scipy.linalg.decomp',
116
+ 'scipy.linalg.decomp_cholesky',
117
+ 'scipy.linalg.decomp_lu',
118
+ 'scipy.linalg.decomp_qr',
119
+ 'scipy.linalg.decomp_schur',
120
+ 'scipy.linalg.decomp_svd',
121
+ 'scipy.linalg.matfuncs',
122
+ 'scipy.linalg.misc',
123
+ 'scipy.linalg.special_matrices',
124
+ 'scipy.misc.common',
125
+ 'scipy.misc.doccer',
126
+ 'scipy.ndimage.filters',
127
+ 'scipy.ndimage.fourier',
128
+ 'scipy.ndimage.interpolation',
129
+ 'scipy.ndimage.measurements',
130
+ 'scipy.ndimage.morphology',
131
+ 'scipy.odr.models',
132
+ 'scipy.odr.odrpack',
133
+ 'scipy.optimize.cobyla',
134
+ 'scipy.optimize.cython_optimize',
135
+ 'scipy.optimize.lbfgsb',
136
+ 'scipy.optimize.linesearch',
137
+ 'scipy.optimize.minpack',
138
+ 'scipy.optimize.minpack2',
139
+ 'scipy.optimize.moduleTNC',
140
+ 'scipy.optimize.nonlin',
141
+ 'scipy.optimize.optimize',
142
+ 'scipy.optimize.slsqp',
143
+ 'scipy.optimize.tnc',
144
+ 'scipy.optimize.zeros',
145
+ 'scipy.signal.bsplines',
146
+ 'scipy.signal.filter_design',
147
+ 'scipy.signal.fir_filter_design',
148
+ 'scipy.signal.lti_conversion',
149
+ 'scipy.signal.ltisys',
150
+ 'scipy.signal.signaltools',
151
+ 'scipy.signal.spectral',
152
+ 'scipy.signal.spline',
153
+ 'scipy.signal.waveforms',
154
+ 'scipy.signal.wavelets',
155
+ 'scipy.signal.windows.windows',
156
+ 'scipy.sparse.base',
157
+ 'scipy.sparse.bsr',
158
+ 'scipy.sparse.compressed',
159
+ 'scipy.sparse.construct',
160
+ 'scipy.sparse.coo',
161
+ 'scipy.sparse.csc',
162
+ 'scipy.sparse.csr',
163
+ 'scipy.sparse.data',
164
+ 'scipy.sparse.dia',
165
+ 'scipy.sparse.dok',
166
+ 'scipy.sparse.extract',
167
+ 'scipy.sparse.lil',
168
+ 'scipy.sparse.linalg.dsolve',
169
+ 'scipy.sparse.linalg.eigen',
170
+ 'scipy.sparse.linalg.interface',
171
+ 'scipy.sparse.linalg.isolve',
172
+ 'scipy.sparse.linalg.matfuncs',
173
+ 'scipy.sparse.sparsetools',
174
+ 'scipy.sparse.spfuncs',
175
+ 'scipy.sparse.sputils',
176
+ 'scipy.spatial.ckdtree',
177
+ 'scipy.spatial.kdtree',
178
+ 'scipy.spatial.qhull',
179
+ 'scipy.spatial.transform.rotation',
180
+ 'scipy.special.add_newdocs',
181
+ 'scipy.special.basic',
182
+ 'scipy.special.cython_special',
183
+ 'scipy.special.orthogonal',
184
+ 'scipy.special.sf_error',
185
+ 'scipy.special.specfun',
186
+ 'scipy.special.spfun_stats',
187
+ 'scipy.stats.biasedurn',
188
+ 'scipy.stats.kde',
189
+ 'scipy.stats.morestats',
190
+ 'scipy.stats.mstats_basic',
191
+ 'scipy.stats.mstats_extras',
192
+ 'scipy.stats.mvn',
193
+ 'scipy.stats.stats',
194
+ ]
195
+
196
+
197
+ def is_unexpected(name):
198
+ """Check if this needs to be considered."""
199
+ if '._' in name or '.tests' in name or '.setup' in name:
200
+ return False
201
+
202
+ if name in PUBLIC_MODULES:
203
+ return False
204
+
205
+ if name in PRIVATE_BUT_PRESENT_MODULES:
206
+ return False
207
+
208
+ return True
209
+
210
+
211
+ SKIP_LIST = [
212
+ 'scipy.conftest',
213
+ 'scipy.version',
214
+ 'scipy.special.libsf_error_state'
215
+ ]
216
+
217
+
218
+ # XXX: this test does more than it says on the tin - in using `pkgutil.walk_packages`,
219
+ # it will raise if it encounters any exceptions which are not handled by `ignore_errors`
220
+ # while attempting to import each discovered package.
221
+ # For now, `ignore_errors` only ignores what is necessary, but this could be expanded -
222
+ # for example, to all errors from private modules or git subpackages - if desired.
223
+ def test_all_modules_are_expected():
224
+ """
225
+ Test that we don't add anything that looks like a new public module by
226
+ accident. Check is based on filenames.
227
+ """
228
+
229
+ def ignore_errors(name):
230
+ # if versions of other array libraries are installed which are incompatible
231
+ # with the installed NumPy version, there can be errors on importing
232
+ # `array_api_compat`. This should only raise if SciPy is configured with
233
+ # that library as an available backend.
234
+ backends = {'cupy': 'cupy',
235
+ 'pytorch': 'torch',
236
+ 'dask.array': 'dask.array'}
237
+ for backend, dir_name in backends.items():
238
+ path = f'array_api_compat.{dir_name}'
239
+ if path in name and backend not in xp_available_backends:
240
+ return
241
+ raise
242
+
243
+ modnames = []
244
+
245
+ for _, modname, _ in pkgutil.walk_packages(path=scipy.__path__,
246
+ prefix=scipy.__name__ + '.',
247
+ onerror=ignore_errors):
248
+ if is_unexpected(modname) and modname not in SKIP_LIST:
249
+ # We have a name that is new. If that's on purpose, add it to
250
+ # PUBLIC_MODULES. We don't expect to have to add anything to
251
+ # PRIVATE_BUT_PRESENT_MODULES. Use an underscore in the name!
252
+ modnames.append(modname)
253
+
254
+ if modnames:
255
+ raise AssertionError(f'Found unexpected modules: {modnames}')
256
+
257
+
258
+ # Stuff that clearly shouldn't be in the API and is detected by the next test
259
+ # below
260
+ SKIP_LIST_2 = [
261
+ 'scipy.char',
262
+ 'scipy.rec',
263
+ 'scipy.emath',
264
+ 'scipy.math',
265
+ 'scipy.random',
266
+ 'scipy.ctypeslib',
267
+ 'scipy.ma'
268
+ ]
269
+
270
+
271
+ def test_all_modules_are_expected_2():
272
+ """
273
+ Method checking all objects. The pkgutil-based method in
274
+ `test_all_modules_are_expected` does not catch imports into a namespace,
275
+ only filenames.
276
+ """
277
+
278
+ def find_unexpected_members(mod_name):
279
+ members = []
280
+ module = importlib.import_module(mod_name)
281
+ if hasattr(module, '__all__'):
282
+ objnames = module.__all__
283
+ else:
284
+ objnames = dir(module)
285
+
286
+ for objname in objnames:
287
+ if not objname.startswith('_'):
288
+ fullobjname = mod_name + '.' + objname
289
+ if isinstance(getattr(module, objname), types.ModuleType):
290
+ if is_unexpected(fullobjname) and fullobjname not in SKIP_LIST_2:
291
+ members.append(fullobjname)
292
+
293
+ return members
294
+
295
+ unexpected_members = find_unexpected_members("scipy")
296
+ for modname in PUBLIC_MODULES:
297
+ unexpected_members.extend(find_unexpected_members(modname))
298
+
299
+ if unexpected_members:
300
+ raise AssertionError("Found unexpected object(s) that look like "
301
+ f"modules: {unexpected_members}")
302
+
303
+
304
+ def test_api_importable():
305
+ """
306
+ Check that all submodules listed higher up in this file can be imported
307
+ Note that if a PRIVATE_BUT_PRESENT_MODULES entry goes missing, it may
308
+ simply need to be removed from the list (deprecation may or may not be
309
+ needed - apply common sense).
310
+ """
311
+ def check_importable(module_name):
312
+ try:
313
+ importlib.import_module(module_name)
314
+ except (ImportError, AttributeError):
315
+ return False
316
+
317
+ return True
318
+
319
+ module_names = []
320
+ for module_name in PUBLIC_MODULES:
321
+ if not check_importable(module_name):
322
+ module_names.append(module_name)
323
+
324
+ if module_names:
325
+ raise AssertionError("Modules in the public API that cannot be "
326
+ f"imported: {module_names}")
327
+
328
+ with warnings.catch_warnings(record=True):
329
+ warnings.filterwarnings('always', category=DeprecationWarning)
330
+ warnings.filterwarnings('always', category=ImportWarning)
331
+ for module_name in PRIVATE_BUT_PRESENT_MODULES:
332
+ if not check_importable(module_name):
333
+ module_names.append(module_name)
334
+
335
+ if module_names:
336
+ raise AssertionError("Modules that are not really public but looked "
337
+ "public and can not be imported: "
338
+ f"{module_names}")
339
+
340
+
341
+ @pytest.mark.parametrize(("module_name", "correct_module"),
342
+ [('scipy.constants.codata', None),
343
+ ('scipy.constants.constants', None),
344
+ ('scipy.fftpack.basic', None),
345
+ ('scipy.fftpack.helper', None),
346
+ ('scipy.fftpack.pseudo_diffs', None),
347
+ ('scipy.fftpack.realtransforms', None),
348
+ ('scipy.integrate.dop', None),
349
+ ('scipy.integrate.lsoda', None),
350
+ ('scipy.integrate.odepack', None),
351
+ ('scipy.integrate.quadpack', None),
352
+ ('scipy.integrate.vode', None),
353
+ ('scipy.interpolate.fitpack', None),
354
+ ('scipy.interpolate.fitpack2', None),
355
+ ('scipy.interpolate.interpolate', None),
356
+ ('scipy.interpolate.ndgriddata', None),
357
+ ('scipy.interpolate.polyint', None),
358
+ ('scipy.interpolate.rbf', None),
359
+ ('scipy.io.harwell_boeing', None),
360
+ ('scipy.io.idl', None),
361
+ ('scipy.io.mmio', None),
362
+ ('scipy.io.netcdf', None),
363
+ ('scipy.io.arff.arffread', 'arff'),
364
+ ('scipy.io.matlab.byteordercodes', 'matlab'),
365
+ ('scipy.io.matlab.mio_utils', 'matlab'),
366
+ ('scipy.io.matlab.mio', 'matlab'),
367
+ ('scipy.io.matlab.mio4', 'matlab'),
368
+ ('scipy.io.matlab.mio5_params', 'matlab'),
369
+ ('scipy.io.matlab.mio5_utils', 'matlab'),
370
+ ('scipy.io.matlab.mio5', 'matlab'),
371
+ ('scipy.io.matlab.miobase', 'matlab'),
372
+ ('scipy.io.matlab.streams', 'matlab'),
373
+ ('scipy.linalg.basic', None),
374
+ ('scipy.linalg.decomp', None),
375
+ ('scipy.linalg.decomp_cholesky', None),
376
+ ('scipy.linalg.decomp_lu', None),
377
+ ('scipy.linalg.decomp_qr', None),
378
+ ('scipy.linalg.decomp_schur', None),
379
+ ('scipy.linalg.decomp_svd', None),
380
+ ('scipy.linalg.matfuncs', None),
381
+ ('scipy.linalg.misc', None),
382
+ ('scipy.linalg.special_matrices', None),
383
+ ('scipy.misc.common', None),
384
+ ('scipy.ndimage.filters', None),
385
+ ('scipy.ndimage.fourier', None),
386
+ ('scipy.ndimage.interpolation', None),
387
+ ('scipy.ndimage.measurements', None),
388
+ ('scipy.ndimage.morphology', None),
389
+ ('scipy.odr.models', None),
390
+ ('scipy.odr.odrpack', None),
391
+ ('scipy.optimize.cobyla', None),
392
+ ('scipy.optimize.lbfgsb', None),
393
+ ('scipy.optimize.linesearch', None),
394
+ ('scipy.optimize.minpack', None),
395
+ ('scipy.optimize.minpack2', None),
396
+ ('scipy.optimize.moduleTNC', None),
397
+ ('scipy.optimize.nonlin', None),
398
+ ('scipy.optimize.optimize', None),
399
+ ('scipy.optimize.slsqp', None),
400
+ ('scipy.optimize.tnc', None),
401
+ ('scipy.optimize.zeros', None),
402
+ ('scipy.signal.bsplines', None),
403
+ ('scipy.signal.filter_design', None),
404
+ ('scipy.signal.fir_filter_design', None),
405
+ ('scipy.signal.lti_conversion', None),
406
+ ('scipy.signal.ltisys', None),
407
+ ('scipy.signal.signaltools', None),
408
+ ('scipy.signal.spectral', None),
409
+ ('scipy.signal.waveforms', None),
410
+ ('scipy.signal.wavelets', None),
411
+ ('scipy.signal.windows.windows', 'windows'),
412
+ ('scipy.sparse.lil', None),
413
+ ('scipy.sparse.linalg.dsolve', 'linalg'),
414
+ ('scipy.sparse.linalg.eigen', 'linalg'),
415
+ ('scipy.sparse.linalg.interface', 'linalg'),
416
+ ('scipy.sparse.linalg.isolve', 'linalg'),
417
+ ('scipy.sparse.linalg.matfuncs', 'linalg'),
418
+ ('scipy.sparse.sparsetools', None),
419
+ ('scipy.sparse.spfuncs', None),
420
+ ('scipy.sparse.sputils', None),
421
+ ('scipy.spatial.ckdtree', None),
422
+ ('scipy.spatial.kdtree', None),
423
+ ('scipy.spatial.qhull', None),
424
+ ('scipy.spatial.transform.rotation', 'transform'),
425
+ ('scipy.special.add_newdocs', None),
426
+ ('scipy.special.basic', None),
427
+ ('scipy.special.orthogonal', None),
428
+ ('scipy.special.sf_error', None),
429
+ ('scipy.special.specfun', None),
430
+ ('scipy.special.spfun_stats', None),
431
+ ('scipy.stats.biasedurn', None),
432
+ ('scipy.stats.kde', None),
433
+ ('scipy.stats.morestats', None),
434
+ ('scipy.stats.mstats_basic', 'mstats'),
435
+ ('scipy.stats.mstats_extras', 'mstats'),
436
+ ('scipy.stats.mvn', None),
437
+ ('scipy.stats.stats', None)])
438
+ def test_private_but_present_deprecation(module_name, correct_module):
439
+ # gh-18279, gh-17572, gh-17771 noted that deprecation warnings
440
+ # for imports from private modules
441
+ # were misleading. Check that this is resolved.
442
+ module = import_module(module_name)
443
+ if correct_module is None:
444
+ import_name = f'scipy.{module_name.split(".")[1]}'
445
+ else:
446
+ import_name = f'scipy.{module_name.split(".")[1]}.{correct_module}'
447
+
448
+ correct_import = import_module(import_name)
449
+
450
+ # Attributes that were formerly in `module_name` can still be imported from
451
+ # `module_name`, albeit with a deprecation warning.
452
+ for attr_name in module.__all__:
453
+ if attr_name == "varmats_from_mat":
454
+ # defer handling this case, see
455
+ # https://github.com/scipy/scipy/issues/19223
456
+ continue
457
+ # ensure attribute is present where the warning is pointing
458
+ assert getattr(correct_import, attr_name, None) is not None
459
+ message = f"Please import `{attr_name}` from the `{import_name}`..."
460
+ with pytest.deprecated_call(match=message):
461
+ getattr(module, attr_name)
462
+
463
+ # Attributes that were not in `module_name` get an error notifying the user
464
+ # that the attribute is not in `module_name` and that `module_name` is deprecated.
465
+ message = f"`{module_name}` is deprecated..."
466
+ with pytest.raises(AttributeError, match=message):
467
+ getattr(module, "ekki")
468
+
469
+
470
+ def test_misc_doccer_deprecation():
471
+ # gh-18279, gh-17572, gh-17771 noted that deprecation warnings
472
+ # for imports from private modules were misleading.
473
+ # Check that this is resolved.
474
+ # `test_private_but_present_deprecation` cannot be used since `correct_import`
475
+ # is a different subpackage (`_lib` instead of `misc`).
476
+ module = import_module('scipy.misc.doccer')
477
+ correct_import = import_module('scipy._lib.doccer')
478
+
479
+ # Attributes that were formerly in `scipy.misc.doccer` can still be imported from
480
+ # `scipy.misc.doccer`, albeit with a deprecation warning. The specific message
481
+ # depends on whether the attribute is in `scipy._lib.doccer` or not.
482
+ for attr_name in module.__all__:
483
+ attr = getattr(correct_import, attr_name, None)
484
+ if attr is None:
485
+ message = f"`scipy.misc.{attr_name}` is deprecated..."
486
+ else:
487
+ message = f"Please import `{attr_name}` from the `scipy._lib.doccer`..."
488
+ with pytest.deprecated_call(match=message):
489
+ getattr(module, attr_name)
490
+
491
+ # Attributes that were not in `scipy.misc.doccer` get an error
492
+ # notifying the user that the attribute is not in `scipy.misc.doccer`
493
+ # and that `scipy.misc.doccer` is deprecated.
494
+ message = "`scipy.misc.doccer` is deprecated..."
495
+ with pytest.raises(AttributeError, match=message):
496
+ getattr(module, "ekki")
parrot/lib/python3.10/site-packages/et_xmlfile/__init__.py ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+
3
+ from .xmlfile import xmlfile
4
+
5
+ # constants
6
+ __version__ = '1.1.0'
7
+
8
+ __author__ = 'See ATUHORS.txt'
9
+ __license__ = 'MIT'
10
+ __author_email__ = 'charlie.clark@clark-consulting.eu'
11
+ __url__ = 'https://foss.heptapod.net/openpyxl/et_xmlfile'
parrot/lib/python3.10/site-packages/et_xmlfile/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (453 Bytes). View file
 
parrot/lib/python3.10/site-packages/et_xmlfile/__pycache__/xmlfile.cpython-310.pyc ADDED
Binary file (3.25 kB). View file
 
parrot/lib/python3.10/site-packages/et_xmlfile/xmlfile.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import absolute_import
2
+ # Copyright (c) 2010-2015 openpyxl
3
+
4
+ """Implements the lxml.etree.xmlfile API using the standard library xml.etree"""
5
+
6
+
7
+ from contextlib import contextmanager
8
+
9
+ from xml.etree.ElementTree import Element, tostring
10
+
11
+
12
+ class LxmlSyntaxError(Exception):
13
+ pass
14
+
15
+
16
+ class _FakeIncrementalFileWriter(object):
17
+ """Replacement for _IncrementalFileWriter of lxml.
18
+ Uses ElementTree to build xml in memory."""
19
+ def __init__(self, output_file):
20
+ self._element_stack = []
21
+ self._top_element = None
22
+ self._file = output_file
23
+ self._have_root = False
24
+
25
+ @contextmanager
26
+ def element(self, tag, attrib=None, nsmap=None, **_extra):
27
+ """Create a new xml element using a context manager.
28
+ The elements are written when the top level context is left.
29
+
30
+ This is for code compatibility only as it is quite slow.
31
+ """
32
+
33
+ # __enter__ part
34
+ self._have_root = True
35
+ if attrib is None:
36
+ attrib = {}
37
+ self._top_element = Element(tag, attrib=attrib, **_extra)
38
+ self._top_element.text = ''
39
+ self._top_element.tail = ''
40
+ self._element_stack.append(self._top_element)
41
+ yield
42
+
43
+ # __exit__ part
44
+ el = self._element_stack.pop()
45
+ if self._element_stack:
46
+ parent = self._element_stack[-1]
47
+ parent.append(self._top_element)
48
+ self._top_element = parent
49
+ else:
50
+ self._write_element(el)
51
+ self._top_element = None
52
+
53
+ def write(self, arg):
54
+ """Write a string or subelement."""
55
+
56
+ if isinstance(arg, str):
57
+ # it is not allowed to write a string outside of an element
58
+ if self._top_element is None:
59
+ raise LxmlSyntaxError()
60
+
61
+ if len(self._top_element) == 0:
62
+ # element has no children: add string to text
63
+ self._top_element.text += arg
64
+ else:
65
+ # element has children: add string to tail of last child
66
+ self._top_element[-1].tail += arg
67
+
68
+ else:
69
+ if self._top_element is not None:
70
+ self._top_element.append(arg)
71
+ elif not self._have_root:
72
+ self._write_element(arg)
73
+ else:
74
+ raise LxmlSyntaxError()
75
+
76
+ def _write_element(self, element):
77
+ xml = tostring(element)
78
+ self._file.write(xml)
79
+
80
+ def __enter__(self):
81
+ pass
82
+
83
+ def __exit__(self, type, value, traceback):
84
+ # without root the xml document is incomplete
85
+ if not self._have_root:
86
+ raise LxmlSyntaxError()
87
+
88
+
89
+ class xmlfile(object):
90
+ """Context manager that can replace lxml.etree.xmlfile."""
91
+ def __init__(self, output_file, buffered=False, encoding=None, close=False):
92
+ if isinstance(output_file, str):
93
+ self._file = open(output_file, 'wb')
94
+ self._close = True
95
+ else:
96
+ self._file = output_file
97
+ self._close = close
98
+
99
+ def __enter__(self):
100
+ return _FakeIncrementalFileWriter(self._file)
101
+
102
+ def __exit__(self, type, value, traceback):
103
+ if self._close == True:
104
+ self._file.close()
parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_divider.py ADDED
@@ -0,0 +1,694 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Helper classes to adjust the positions of multiple axes at drawing time.
3
+ """
4
+
5
+ import functools
6
+
7
+ import numpy as np
8
+
9
+ import matplotlib as mpl
10
+ from matplotlib import _api
11
+ from matplotlib.gridspec import SubplotSpec
12
+ import matplotlib.transforms as mtransforms
13
+ from . import axes_size as Size
14
+
15
+
16
+ class Divider:
17
+ """
18
+ An Axes positioning class.
19
+
20
+ The divider is initialized with lists of horizontal and vertical sizes
21
+ (:mod:`mpl_toolkits.axes_grid1.axes_size`) based on which a given
22
+ rectangular area will be divided.
23
+
24
+ The `new_locator` method then creates a callable object
25
+ that can be used as the *axes_locator* of the axes.
26
+ """
27
+
28
+ def __init__(self, fig, pos, horizontal, vertical,
29
+ aspect=None, anchor="C"):
30
+ """
31
+ Parameters
32
+ ----------
33
+ fig : Figure
34
+ pos : tuple of 4 floats
35
+ Position of the rectangle that will be divided.
36
+ horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
37
+ Sizes for horizontal division.
38
+ vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
39
+ Sizes for vertical division.
40
+ aspect : bool, optional
41
+ Whether overall rectangular area is reduced so that the relative
42
+ part of the horizontal and vertical scales have the same scale.
43
+ anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
44
+ 'NW', 'W'}, default: 'C'
45
+ Placement of the reduced rectangle, when *aspect* is True.
46
+ """
47
+
48
+ self._fig = fig
49
+ self._pos = pos
50
+ self._horizontal = horizontal
51
+ self._vertical = vertical
52
+ self._anchor = anchor
53
+ self.set_anchor(anchor)
54
+ self._aspect = aspect
55
+ self._xrefindex = 0
56
+ self._yrefindex = 0
57
+ self._locator = None
58
+
59
+ def get_horizontal_sizes(self, renderer):
60
+ return np.array([s.get_size(renderer) for s in self.get_horizontal()])
61
+
62
+ def get_vertical_sizes(self, renderer):
63
+ return np.array([s.get_size(renderer) for s in self.get_vertical()])
64
+
65
+ def set_position(self, pos):
66
+ """
67
+ Set the position of the rectangle.
68
+
69
+ Parameters
70
+ ----------
71
+ pos : tuple of 4 floats
72
+ position of the rectangle that will be divided
73
+ """
74
+ self._pos = pos
75
+
76
+ def get_position(self):
77
+ """Return the position of the rectangle."""
78
+ return self._pos
79
+
80
+ def set_anchor(self, anchor):
81
+ """
82
+ Parameters
83
+ ----------
84
+ anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
85
+ 'NW', 'W'}
86
+ Either an (*x*, *y*) pair of relative coordinates (0 is left or
87
+ bottom, 1 is right or top), 'C' (center), or a cardinal direction
88
+ ('SW', southwest, is bottom left, etc.).
89
+
90
+ See Also
91
+ --------
92
+ .Axes.set_anchor
93
+ """
94
+ if isinstance(anchor, str):
95
+ _api.check_in_list(mtransforms.Bbox.coefs, anchor=anchor)
96
+ elif not isinstance(anchor, (tuple, list)) or len(anchor) != 2:
97
+ raise TypeError("anchor must be str or 2-tuple")
98
+ self._anchor = anchor
99
+
100
+ def get_anchor(self):
101
+ """Return the anchor."""
102
+ return self._anchor
103
+
104
+ def get_subplotspec(self):
105
+ return None
106
+
107
+ def set_horizontal(self, h):
108
+ """
109
+ Parameters
110
+ ----------
111
+ h : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
112
+ sizes for horizontal division
113
+ """
114
+ self._horizontal = h
115
+
116
+ def get_horizontal(self):
117
+ """Return horizontal sizes."""
118
+ return self._horizontal
119
+
120
+ def set_vertical(self, v):
121
+ """
122
+ Parameters
123
+ ----------
124
+ v : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`
125
+ sizes for vertical division
126
+ """
127
+ self._vertical = v
128
+
129
+ def get_vertical(self):
130
+ """Return vertical sizes."""
131
+ return self._vertical
132
+
133
+ def set_aspect(self, aspect=False):
134
+ """
135
+ Parameters
136
+ ----------
137
+ aspect : bool
138
+ """
139
+ self._aspect = aspect
140
+
141
+ def get_aspect(self):
142
+ """Return aspect."""
143
+ return self._aspect
144
+
145
+ def set_locator(self, _locator):
146
+ self._locator = _locator
147
+
148
+ def get_locator(self):
149
+ return self._locator
150
+
151
+ def get_position_runtime(self, ax, renderer):
152
+ if self._locator is None:
153
+ return self.get_position()
154
+ else:
155
+ return self._locator(ax, renderer).bounds
156
+
157
+ @staticmethod
158
+ def _calc_k(sizes, total):
159
+ # sizes is a (n, 2) array of (rel_size, abs_size); this method finds
160
+ # the k factor such that sum(rel_size * k + abs_size) == total.
161
+ rel_sum, abs_sum = sizes.sum(0)
162
+ return (total - abs_sum) / rel_sum if rel_sum else 0
163
+
164
+ @staticmethod
165
+ def _calc_offsets(sizes, k):
166
+ # Apply k factors to (n, 2) sizes array of (rel_size, abs_size); return
167
+ # the resulting cumulative offset positions.
168
+ return np.cumsum([0, *(sizes @ [k, 1])])
169
+
170
+ def new_locator(self, nx, ny, nx1=None, ny1=None):
171
+ """
172
+ Return an axes locator callable for the specified cell.
173
+
174
+ Parameters
175
+ ----------
176
+ nx, nx1 : int
177
+ Integers specifying the column-position of the
178
+ cell. When *nx1* is None, a single *nx*-th column is
179
+ specified. Otherwise, location of columns spanning between *nx*
180
+ to *nx1* (but excluding *nx1*-th column) is specified.
181
+ ny, ny1 : int
182
+ Same as *nx* and *nx1*, but for row positions.
183
+ """
184
+ if nx1 is None:
185
+ nx1 = nx + 1
186
+ if ny1 is None:
187
+ ny1 = ny + 1
188
+ # append_size("left") adds a new size at the beginning of the
189
+ # horizontal size lists; this shift transforms e.g.
190
+ # new_locator(nx=2, ...) into effectively new_locator(nx=3, ...). To
191
+ # take that into account, instead of recording nx, we record
192
+ # nx-self._xrefindex, where _xrefindex is shifted by 1 by each
193
+ # append_size("left"), and re-add self._xrefindex back to nx in
194
+ # _locate, when the actual axes position is computed. Ditto for y.
195
+ xref = self._xrefindex
196
+ yref = self._yrefindex
197
+ locator = functools.partial(
198
+ self._locate, nx - xref, ny - yref, nx1 - xref, ny1 - yref)
199
+ locator.get_subplotspec = self.get_subplotspec
200
+ return locator
201
+
202
+ @_api.deprecated(
203
+ "3.8", alternative="divider.new_locator(...)(ax, renderer)")
204
+ def locate(self, nx, ny, nx1=None, ny1=None, axes=None, renderer=None):
205
+ """
206
+ Implementation of ``divider.new_locator().__call__``.
207
+
208
+ Parameters
209
+ ----------
210
+ nx, nx1 : int
211
+ Integers specifying the column-position of the cell. When *nx1* is
212
+ None, a single *nx*-th column is specified. Otherwise, the
213
+ location of columns spanning between *nx* to *nx1* (but excluding
214
+ *nx1*-th column) is specified.
215
+ ny, ny1 : int
216
+ Same as *nx* and *nx1*, but for row positions.
217
+ axes
218
+ renderer
219
+ """
220
+ xref = self._xrefindex
221
+ yref = self._yrefindex
222
+ return self._locate(
223
+ nx - xref, (nx + 1 if nx1 is None else nx1) - xref,
224
+ ny - yref, (ny + 1 if ny1 is None else ny1) - yref,
225
+ axes, renderer)
226
+
227
+ def _locate(self, nx, ny, nx1, ny1, axes, renderer):
228
+ """
229
+ Implementation of ``divider.new_locator().__call__``.
230
+
231
+ The axes locator callable returned by ``new_locator()`` is created as
232
+ a `functools.partial` of this method with *nx*, *ny*, *nx1*, and *ny1*
233
+ specifying the requested cell.
234
+ """
235
+ nx += self._xrefindex
236
+ nx1 += self._xrefindex
237
+ ny += self._yrefindex
238
+ ny1 += self._yrefindex
239
+
240
+ fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
241
+ x, y, w, h = self.get_position_runtime(axes, renderer)
242
+
243
+ hsizes = self.get_horizontal_sizes(renderer)
244
+ vsizes = self.get_vertical_sizes(renderer)
245
+ k_h = self._calc_k(hsizes, fig_w * w)
246
+ k_v = self._calc_k(vsizes, fig_h * h)
247
+
248
+ if self.get_aspect():
249
+ k = min(k_h, k_v)
250
+ ox = self._calc_offsets(hsizes, k)
251
+ oy = self._calc_offsets(vsizes, k)
252
+
253
+ ww = (ox[-1] - ox[0]) / fig_w
254
+ hh = (oy[-1] - oy[0]) / fig_h
255
+ pb = mtransforms.Bbox.from_bounds(x, y, w, h)
256
+ pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
257
+ x0, y0 = pb1.anchored(self.get_anchor(), pb).p0
258
+
259
+ else:
260
+ ox = self._calc_offsets(hsizes, k_h)
261
+ oy = self._calc_offsets(vsizes, k_v)
262
+ x0, y0 = x, y
263
+
264
+ if nx1 is None:
265
+ nx1 = -1
266
+ if ny1 is None:
267
+ ny1 = -1
268
+
269
+ x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
270
+ y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
271
+
272
+ return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
273
+
274
+ def append_size(self, position, size):
275
+ _api.check_in_list(["left", "right", "bottom", "top"],
276
+ position=position)
277
+ if position == "left":
278
+ self._horizontal.insert(0, size)
279
+ self._xrefindex += 1
280
+ elif position == "right":
281
+ self._horizontal.append(size)
282
+ elif position == "bottom":
283
+ self._vertical.insert(0, size)
284
+ self._yrefindex += 1
285
+ else: # 'top'
286
+ self._vertical.append(size)
287
+
288
+ def add_auto_adjustable_area(self, use_axes, pad=0.1, adjust_dirs=None):
289
+ """
290
+ Add auto-adjustable padding around *use_axes* to take their decorations
291
+ (title, labels, ticks, ticklabels) into account during layout.
292
+
293
+ Parameters
294
+ ----------
295
+ use_axes : `~matplotlib.axes.Axes` or list of `~matplotlib.axes.Axes`
296
+ The Axes whose decorations are taken into account.
297
+ pad : float, default: 0.1
298
+ Additional padding in inches.
299
+ adjust_dirs : list of {"left", "right", "bottom", "top"}, optional
300
+ The sides where padding is added; defaults to all four sides.
301
+ """
302
+ if adjust_dirs is None:
303
+ adjust_dirs = ["left", "right", "bottom", "top"]
304
+ for d in adjust_dirs:
305
+ self.append_size(d, Size._AxesDecorationsSize(use_axes, d) + pad)
306
+
307
+
308
+ @_api.deprecated("3.8")
309
+ class AxesLocator:
310
+ """
311
+ A callable object which returns the position and size of a given
312
+ `.AxesDivider` cell.
313
+ """
314
+
315
+ def __init__(self, axes_divider, nx, ny, nx1=None, ny1=None):
316
+ """
317
+ Parameters
318
+ ----------
319
+ axes_divider : `~mpl_toolkits.axes_grid1.axes_divider.AxesDivider`
320
+ nx, nx1 : int
321
+ Integers specifying the column-position of the
322
+ cell. When *nx1* is None, a single *nx*-th column is
323
+ specified. Otherwise, location of columns spanning between *nx*
324
+ to *nx1* (but excluding *nx1*-th column) is specified.
325
+ ny, ny1 : int
326
+ Same as *nx* and *nx1*, but for row positions.
327
+ """
328
+ self._axes_divider = axes_divider
329
+
330
+ _xrefindex = axes_divider._xrefindex
331
+ _yrefindex = axes_divider._yrefindex
332
+
333
+ self._nx, self._ny = nx - _xrefindex, ny - _yrefindex
334
+
335
+ if nx1 is None:
336
+ nx1 = len(self._axes_divider)
337
+ if ny1 is None:
338
+ ny1 = len(self._axes_divider[0])
339
+
340
+ self._nx1 = nx1 - _xrefindex
341
+ self._ny1 = ny1 - _yrefindex
342
+
343
+ def __call__(self, axes, renderer):
344
+
345
+ _xrefindex = self._axes_divider._xrefindex
346
+ _yrefindex = self._axes_divider._yrefindex
347
+
348
+ return self._axes_divider.locate(self._nx + _xrefindex,
349
+ self._ny + _yrefindex,
350
+ self._nx1 + _xrefindex,
351
+ self._ny1 + _yrefindex,
352
+ axes,
353
+ renderer)
354
+
355
+ def get_subplotspec(self):
356
+ return self._axes_divider.get_subplotspec()
357
+
358
+
359
+ class SubplotDivider(Divider):
360
+ """
361
+ The Divider class whose rectangle area is specified as a subplot geometry.
362
+ """
363
+
364
+ def __init__(self, fig, *args, horizontal=None, vertical=None,
365
+ aspect=None, anchor='C'):
366
+ """
367
+ Parameters
368
+ ----------
369
+ fig : `~matplotlib.figure.Figure`
370
+
371
+ *args : tuple (*nrows*, *ncols*, *index*) or int
372
+ The array of subplots in the figure has dimensions ``(nrows,
373
+ ncols)``, and *index* is the index of the subplot being created.
374
+ *index* starts at 1 in the upper left corner and increases to the
375
+ right.
376
+
377
+ If *nrows*, *ncols*, and *index* are all single digit numbers, then
378
+ *args* can be passed as a single 3-digit number (e.g. 234 for
379
+ (2, 3, 4)).
380
+ horizontal : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
381
+ Sizes for horizontal division.
382
+ vertical : list of :mod:`~mpl_toolkits.axes_grid1.axes_size`, optional
383
+ Sizes for vertical division.
384
+ aspect : bool, optional
385
+ Whether overall rectangular area is reduced so that the relative
386
+ part of the horizontal and vertical scales have the same scale.
387
+ anchor : (float, float) or {'C', 'SW', 'S', 'SE', 'E', 'NE', 'N', \
388
+ 'NW', 'W'}, default: 'C'
389
+ Placement of the reduced rectangle, when *aspect* is True.
390
+ """
391
+ self.figure = fig
392
+ super().__init__(fig, [0, 0, 1, 1],
393
+ horizontal=horizontal or [], vertical=vertical or [],
394
+ aspect=aspect, anchor=anchor)
395
+ self.set_subplotspec(SubplotSpec._from_subplot_args(fig, args))
396
+
397
+ def get_position(self):
398
+ """Return the bounds of the subplot box."""
399
+ return self.get_subplotspec().get_position(self.figure).bounds
400
+
401
+ def get_subplotspec(self):
402
+ """Get the SubplotSpec instance."""
403
+ return self._subplotspec
404
+
405
+ def set_subplotspec(self, subplotspec):
406
+ """Set the SubplotSpec instance."""
407
+ self._subplotspec = subplotspec
408
+ self.set_position(subplotspec.get_position(self.figure))
409
+
410
+
411
+ class AxesDivider(Divider):
412
+ """
413
+ Divider based on the preexisting axes.
414
+ """
415
+
416
+ def __init__(self, axes, xref=None, yref=None):
417
+ """
418
+ Parameters
419
+ ----------
420
+ axes : :class:`~matplotlib.axes.Axes`
421
+ xref
422
+ yref
423
+ """
424
+ self._axes = axes
425
+ if xref is None:
426
+ self._xref = Size.AxesX(axes)
427
+ else:
428
+ self._xref = xref
429
+ if yref is None:
430
+ self._yref = Size.AxesY(axes)
431
+ else:
432
+ self._yref = yref
433
+
434
+ super().__init__(fig=axes.get_figure(), pos=None,
435
+ horizontal=[self._xref], vertical=[self._yref],
436
+ aspect=None, anchor="C")
437
+
438
+ def _get_new_axes(self, *, axes_class=None, **kwargs):
439
+ axes = self._axes
440
+ if axes_class is None:
441
+ axes_class = type(axes)
442
+ return axes_class(axes.get_figure(), axes.get_position(original=True),
443
+ **kwargs)
444
+
445
+ def new_horizontal(self, size, pad=None, pack_start=False, **kwargs):
446
+ """
447
+ Helper method for ``append_axes("left")`` and ``append_axes("right")``.
448
+
449
+ See the documentation of `append_axes` for more details.
450
+
451
+ :meta private:
452
+ """
453
+ if pad is None:
454
+ pad = mpl.rcParams["figure.subplot.wspace"] * self._xref
455
+ pos = "left" if pack_start else "right"
456
+ if pad:
457
+ if not isinstance(pad, Size._Base):
458
+ pad = Size.from_any(pad, fraction_ref=self._xref)
459
+ self.append_size(pos, pad)
460
+ if not isinstance(size, Size._Base):
461
+ size = Size.from_any(size, fraction_ref=self._xref)
462
+ self.append_size(pos, size)
463
+ locator = self.new_locator(
464
+ nx=0 if pack_start else len(self._horizontal) - 1,
465
+ ny=self._yrefindex)
466
+ ax = self._get_new_axes(**kwargs)
467
+ ax.set_axes_locator(locator)
468
+ return ax
469
+
470
+ def new_vertical(self, size, pad=None, pack_start=False, **kwargs):
471
+ """
472
+ Helper method for ``append_axes("top")`` and ``append_axes("bottom")``.
473
+
474
+ See the documentation of `append_axes` for more details.
475
+
476
+ :meta private:
477
+ """
478
+ if pad is None:
479
+ pad = mpl.rcParams["figure.subplot.hspace"] * self._yref
480
+ pos = "bottom" if pack_start else "top"
481
+ if pad:
482
+ if not isinstance(pad, Size._Base):
483
+ pad = Size.from_any(pad, fraction_ref=self._yref)
484
+ self.append_size(pos, pad)
485
+ if not isinstance(size, Size._Base):
486
+ size = Size.from_any(size, fraction_ref=self._yref)
487
+ self.append_size(pos, size)
488
+ locator = self.new_locator(
489
+ nx=self._xrefindex,
490
+ ny=0 if pack_start else len(self._vertical) - 1)
491
+ ax = self._get_new_axes(**kwargs)
492
+ ax.set_axes_locator(locator)
493
+ return ax
494
+
495
+ def append_axes(self, position, size, pad=None, *, axes_class=None,
496
+ **kwargs):
497
+ """
498
+ Add a new axes on a given side of the main axes.
499
+
500
+ Parameters
501
+ ----------
502
+ position : {"left", "right", "bottom", "top"}
503
+ Where the new axes is positioned relative to the main axes.
504
+ size : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
505
+ The axes width or height. float or str arguments are interpreted
506
+ as ``axes_size.from_any(size, AxesX(<main_axes>))`` for left or
507
+ right axes, and likewise with ``AxesY`` for bottom or top axes.
508
+ pad : :mod:`~mpl_toolkits.axes_grid1.axes_size` or float or str
509
+ Padding between the axes. float or str arguments are interpreted
510
+ as for *size*. Defaults to :rc:`figure.subplot.wspace` times the
511
+ main Axes width (left or right axes) or :rc:`figure.subplot.hspace`
512
+ times the main Axes height (bottom or top axes).
513
+ axes_class : subclass type of `~.axes.Axes`, optional
514
+ The type of the new axes. Defaults to the type of the main axes.
515
+ **kwargs
516
+ All extra keywords arguments are passed to the created axes.
517
+ """
518
+ create_axes, pack_start = _api.check_getitem({
519
+ "left": (self.new_horizontal, True),
520
+ "right": (self.new_horizontal, False),
521
+ "bottom": (self.new_vertical, True),
522
+ "top": (self.new_vertical, False),
523
+ }, position=position)
524
+ ax = create_axes(
525
+ size, pad, pack_start=pack_start, axes_class=axes_class, **kwargs)
526
+ self._fig.add_axes(ax)
527
+ return ax
528
+
529
+ def get_aspect(self):
530
+ if self._aspect is None:
531
+ aspect = self._axes.get_aspect()
532
+ if aspect == "auto":
533
+ return False
534
+ else:
535
+ return True
536
+ else:
537
+ return self._aspect
538
+
539
+ def get_position(self):
540
+ if self._pos is None:
541
+ bbox = self._axes.get_position(original=True)
542
+ return bbox.bounds
543
+ else:
544
+ return self._pos
545
+
546
+ def get_anchor(self):
547
+ if self._anchor is None:
548
+ return self._axes.get_anchor()
549
+ else:
550
+ return self._anchor
551
+
552
+ def get_subplotspec(self):
553
+ return self._axes.get_subplotspec()
554
+
555
+
556
+ # Helper for HBoxDivider/VBoxDivider.
557
+ # The variable names are written for a horizontal layout, but the calculations
558
+ # work identically for vertical layouts.
559
+ def _locate(x, y, w, h, summed_widths, equal_heights, fig_w, fig_h, anchor):
560
+
561
+ total_width = fig_w * w
562
+ max_height = fig_h * h
563
+
564
+ # Determine the k factors.
565
+ n = len(equal_heights)
566
+ eq_rels, eq_abss = equal_heights.T
567
+ sm_rels, sm_abss = summed_widths.T
568
+ A = np.diag([*eq_rels, 0])
569
+ A[:n, -1] = -1
570
+ A[-1, :-1] = sm_rels
571
+ B = [*(-eq_abss), total_width - sm_abss.sum()]
572
+ # A @ K = B: This finds factors {k_0, ..., k_{N-1}, H} so that
573
+ # eq_rel_i * k_i + eq_abs_i = H for all i: all axes have the same height
574
+ # sum(sm_rel_i * k_i + sm_abs_i) = total_width: fixed total width
575
+ # (foo_rel_i * k_i + foo_abs_i will end up being the size of foo.)
576
+ *karray, height = np.linalg.solve(A, B)
577
+ if height > max_height: # Additionally, upper-bound the height.
578
+ karray = (max_height - eq_abss) / eq_rels
579
+
580
+ # Compute the offsets corresponding to these factors.
581
+ ox = np.cumsum([0, *(sm_rels * karray + sm_abss)])
582
+ ww = (ox[-1] - ox[0]) / fig_w
583
+ h0_rel, h0_abs = equal_heights[0]
584
+ hh = (karray[0]*h0_rel + h0_abs) / fig_h
585
+ pb = mtransforms.Bbox.from_bounds(x, y, w, h)
586
+ pb1 = mtransforms.Bbox.from_bounds(x, y, ww, hh)
587
+ x0, y0 = pb1.anchored(anchor, pb).p0
588
+
589
+ return x0, y0, ox, hh
590
+
591
+
592
+ class HBoxDivider(SubplotDivider):
593
+ """
594
+ A `.SubplotDivider` for laying out axes horizontally, while ensuring that
595
+ they have equal heights.
596
+
597
+ Examples
598
+ --------
599
+ .. plot:: gallery/axes_grid1/demo_axes_hbox_divider.py
600
+ """
601
+
602
+ def new_locator(self, nx, nx1=None):
603
+ """
604
+ Create an axes locator callable for the specified cell.
605
+
606
+ Parameters
607
+ ----------
608
+ nx, nx1 : int
609
+ Integers specifying the column-position of the
610
+ cell. When *nx1* is None, a single *nx*-th column is
611
+ specified. Otherwise, location of columns spanning between *nx*
612
+ to *nx1* (but excluding *nx1*-th column) is specified.
613
+ """
614
+ return super().new_locator(nx, 0, nx1, 0)
615
+
616
+ def _locate(self, nx, ny, nx1, ny1, axes, renderer):
617
+ # docstring inherited
618
+ nx += self._xrefindex
619
+ nx1 += self._xrefindex
620
+ fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
621
+ x, y, w, h = self.get_position_runtime(axes, renderer)
622
+ summed_ws = self.get_horizontal_sizes(renderer)
623
+ equal_hs = self.get_vertical_sizes(renderer)
624
+ x0, y0, ox, hh = _locate(
625
+ x, y, w, h, summed_ws, equal_hs, fig_w, fig_h, self.get_anchor())
626
+ if nx1 is None:
627
+ nx1 = -1
628
+ x1, w1 = x0 + ox[nx] / fig_w, (ox[nx1] - ox[nx]) / fig_w
629
+ y1, h1 = y0, hh
630
+ return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
631
+
632
+
633
+ class VBoxDivider(SubplotDivider):
634
+ """
635
+ A `.SubplotDivider` for laying out axes vertically, while ensuring that
636
+ they have equal widths.
637
+ """
638
+
639
+ def new_locator(self, ny, ny1=None):
640
+ """
641
+ Create an axes locator callable for the specified cell.
642
+
643
+ Parameters
644
+ ----------
645
+ ny, ny1 : int
646
+ Integers specifying the row-position of the
647
+ cell. When *ny1* is None, a single *ny*-th row is
648
+ specified. Otherwise, location of rows spanning between *ny*
649
+ to *ny1* (but excluding *ny1*-th row) is specified.
650
+ """
651
+ return super().new_locator(0, ny, 0, ny1)
652
+
653
+ def _locate(self, nx, ny, nx1, ny1, axes, renderer):
654
+ # docstring inherited
655
+ ny += self._yrefindex
656
+ ny1 += self._yrefindex
657
+ fig_w, fig_h = self._fig.bbox.size / self._fig.dpi
658
+ x, y, w, h = self.get_position_runtime(axes, renderer)
659
+ summed_hs = self.get_vertical_sizes(renderer)
660
+ equal_ws = self.get_horizontal_sizes(renderer)
661
+ y0, x0, oy, ww = _locate(
662
+ y, x, h, w, summed_hs, equal_ws, fig_h, fig_w, self.get_anchor())
663
+ if ny1 is None:
664
+ ny1 = -1
665
+ x1, w1 = x0, ww
666
+ y1, h1 = y0 + oy[ny] / fig_h, (oy[ny1] - oy[ny]) / fig_h
667
+ return mtransforms.Bbox.from_bounds(x1, y1, w1, h1)
668
+
669
+
670
+ def make_axes_locatable(axes):
671
+ divider = AxesDivider(axes)
672
+ locator = divider.new_locator(nx=0, ny=0)
673
+ axes.set_axes_locator(locator)
674
+
675
+ return divider
676
+
677
+
678
+ def make_axes_area_auto_adjustable(
679
+ ax, use_axes=None, pad=0.1, adjust_dirs=None):
680
+ """
681
+ Add auto-adjustable padding around *ax* to take its decorations (title,
682
+ labels, ticks, ticklabels) into account during layout, using
683
+ `.Divider.add_auto_adjustable_area`.
684
+
685
+ By default, padding is determined from the decorations of *ax*.
686
+ Pass *use_axes* to consider the decorations of other Axes instead.
687
+ """
688
+ if adjust_dirs is None:
689
+ adjust_dirs = ["left", "right", "bottom", "top"]
690
+ divider = make_axes_locatable(ax)
691
+ if use_axes is None:
692
+ use_axes = ax
693
+ divider.add_auto_adjustable_area(use_axes=use_axes, pad=pad,
694
+ adjust_dirs=adjust_dirs)
parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_rgb.py ADDED
@@ -0,0 +1,157 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from types import MethodType
2
+
3
+ import numpy as np
4
+
5
+ from .axes_divider import make_axes_locatable, Size
6
+ from .mpl_axes import Axes, SimpleAxisArtist
7
+
8
+
9
+ def make_rgb_axes(ax, pad=0.01, axes_class=None, **kwargs):
10
+ """
11
+ Parameters
12
+ ----------
13
+ ax : `~matplotlib.axes.Axes`
14
+ Axes instance to create the RGB Axes in.
15
+ pad : float, optional
16
+ Fraction of the Axes height to pad.
17
+ axes_class : `matplotlib.axes.Axes` or None, optional
18
+ Axes class to use for the R, G, and B Axes. If None, use
19
+ the same class as *ax*.
20
+ **kwargs
21
+ Forwarded to *axes_class* init for the R, G, and B Axes.
22
+ """
23
+
24
+ divider = make_axes_locatable(ax)
25
+
26
+ pad_size = pad * Size.AxesY(ax)
27
+
28
+ xsize = ((1-2*pad)/3) * Size.AxesX(ax)
29
+ ysize = ((1-2*pad)/3) * Size.AxesY(ax)
30
+
31
+ divider.set_horizontal([Size.AxesX(ax), pad_size, xsize])
32
+ divider.set_vertical([ysize, pad_size, ysize, pad_size, ysize])
33
+
34
+ ax.set_axes_locator(divider.new_locator(0, 0, ny1=-1))
35
+
36
+ ax_rgb = []
37
+ if axes_class is None:
38
+ axes_class = type(ax)
39
+
40
+ for ny in [4, 2, 0]:
41
+ ax1 = axes_class(ax.get_figure(), ax.get_position(original=True),
42
+ sharex=ax, sharey=ax, **kwargs)
43
+ locator = divider.new_locator(nx=2, ny=ny)
44
+ ax1.set_axes_locator(locator)
45
+ for t in ax1.yaxis.get_ticklabels() + ax1.xaxis.get_ticklabels():
46
+ t.set_visible(False)
47
+ try:
48
+ for axis in ax1.axis.values():
49
+ axis.major_ticklabels.set_visible(False)
50
+ except AttributeError:
51
+ pass
52
+
53
+ ax_rgb.append(ax1)
54
+
55
+ fig = ax.get_figure()
56
+ for ax1 in ax_rgb:
57
+ fig.add_axes(ax1)
58
+
59
+ return ax_rgb
60
+
61
+
62
+ class RGBAxes:
63
+ """
64
+ 4-panel `~.Axes.imshow` (RGB, R, G, B).
65
+
66
+ Layout::
67
+
68
+ ┌───────────────┬─────┐
69
+ │ │ R │
70
+ │ ├─────┤
71
+ │ RGB │ G │
72
+ │ ├─────┤
73
+ │ │ B │
74
+ └───────────────┴─────┘
75
+
76
+ Subclasses can override the ``_defaultAxesClass`` attribute.
77
+ By default RGBAxes uses `.mpl_axes.Axes`.
78
+
79
+ Attributes
80
+ ----------
81
+ RGB : ``_defaultAxesClass``
82
+ The Axes object for the three-channel `~.Axes.imshow`.
83
+ R : ``_defaultAxesClass``
84
+ The Axes object for the red channel `~.Axes.imshow`.
85
+ G : ``_defaultAxesClass``
86
+ The Axes object for the green channel `~.Axes.imshow`.
87
+ B : ``_defaultAxesClass``
88
+ The Axes object for the blue channel `~.Axes.imshow`.
89
+ """
90
+
91
+ _defaultAxesClass = Axes
92
+
93
+ def __init__(self, *args, pad=0, **kwargs):
94
+ """
95
+ Parameters
96
+ ----------
97
+ pad : float, default: 0
98
+ Fraction of the Axes height to put as padding.
99
+ axes_class : `~matplotlib.axes.Axes`
100
+ Axes class to use. If not provided, ``_defaultAxesClass`` is used.
101
+ *args
102
+ Forwarded to *axes_class* init for the RGB Axes
103
+ **kwargs
104
+ Forwarded to *axes_class* init for the RGB, R, G, and B Axes
105
+ """
106
+ axes_class = kwargs.pop("axes_class", self._defaultAxesClass)
107
+ self.RGB = ax = axes_class(*args, **kwargs)
108
+ ax.get_figure().add_axes(ax)
109
+ self.R, self.G, self.B = make_rgb_axes(
110
+ ax, pad=pad, axes_class=axes_class, **kwargs)
111
+ # Set the line color and ticks for the axes.
112
+ for ax1 in [self.RGB, self.R, self.G, self.B]:
113
+ if isinstance(ax1.axis, MethodType):
114
+ ad = Axes.AxisDict(self)
115
+ ad.update(
116
+ bottom=SimpleAxisArtist(ax1.xaxis, 1, ax1.spines["bottom"]),
117
+ top=SimpleAxisArtist(ax1.xaxis, 2, ax1.spines["top"]),
118
+ left=SimpleAxisArtist(ax1.yaxis, 1, ax1.spines["left"]),
119
+ right=SimpleAxisArtist(ax1.yaxis, 2, ax1.spines["right"]))
120
+ else:
121
+ ad = ax1.axis
122
+ ad[:].line.set_color("w")
123
+ ad[:].major_ticks.set_markeredgecolor("w")
124
+
125
+ def imshow_rgb(self, r, g, b, **kwargs):
126
+ """
127
+ Create the four images {rgb, r, g, b}.
128
+
129
+ Parameters
130
+ ----------
131
+ r, g, b : array-like
132
+ The red, green, and blue arrays.
133
+ **kwargs
134
+ Forwarded to `~.Axes.imshow` calls for the four images.
135
+
136
+ Returns
137
+ -------
138
+ rgb : `~matplotlib.image.AxesImage`
139
+ r : `~matplotlib.image.AxesImage`
140
+ g : `~matplotlib.image.AxesImage`
141
+ b : `~matplotlib.image.AxesImage`
142
+ """
143
+ if not (r.shape == g.shape == b.shape):
144
+ raise ValueError(
145
+ f'Input shapes ({r.shape}, {g.shape}, {b.shape}) do not match')
146
+ RGB = np.dstack([r, g, b])
147
+ R = np.zeros_like(RGB)
148
+ R[:, :, 0] = r
149
+ G = np.zeros_like(RGB)
150
+ G[:, :, 1] = g
151
+ B = np.zeros_like(RGB)
152
+ B[:, :, 2] = b
153
+ im_rgb = self.RGB.imshow(RGB, **kwargs)
154
+ im_r = self.R.imshow(R, **kwargs)
155
+ im_g = self.G.imshow(G, **kwargs)
156
+ im_b = self.B.imshow(B, **kwargs)
157
+ return im_rgb, im_r, im_g, im_b
parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/axes_size.py ADDED
@@ -0,0 +1,248 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Provides classes of simple units that will be used with `.AxesDivider`
3
+ class (or others) to determine the size of each Axes. The unit
4
+ classes define `get_size` method that returns a tuple of two floats,
5
+ meaning relative and absolute sizes, respectively.
6
+
7
+ Note that this class is nothing more than a simple tuple of two
8
+ floats. Take a look at the Divider class to see how these two
9
+ values are used.
10
+ """
11
+
12
+ from numbers import Real
13
+
14
+ from matplotlib import _api
15
+ from matplotlib.axes import Axes
16
+
17
+
18
+ class _Base:
19
+ def __rmul__(self, other):
20
+ return Fraction(other, self)
21
+
22
+ def __add__(self, other):
23
+ if isinstance(other, _Base):
24
+ return Add(self, other)
25
+ else:
26
+ return Add(self, Fixed(other))
27
+
28
+ def get_size(self, renderer):
29
+ """
30
+ Return two-float tuple with relative and absolute sizes.
31
+ """
32
+ raise NotImplementedError("Subclasses must implement")
33
+
34
+
35
+ class Add(_Base):
36
+ """
37
+ Sum of two sizes.
38
+ """
39
+
40
+ def __init__(self, a, b):
41
+ self._a = a
42
+ self._b = b
43
+
44
+ def get_size(self, renderer):
45
+ a_rel_size, a_abs_size = self._a.get_size(renderer)
46
+ b_rel_size, b_abs_size = self._b.get_size(renderer)
47
+ return a_rel_size + b_rel_size, a_abs_size + b_abs_size
48
+
49
+
50
+ class Fixed(_Base):
51
+ """
52
+ Simple fixed size with absolute part = *fixed_size* and relative part = 0.
53
+ """
54
+
55
+ def __init__(self, fixed_size):
56
+ _api.check_isinstance(Real, fixed_size=fixed_size)
57
+ self.fixed_size = fixed_size
58
+
59
+ def get_size(self, renderer):
60
+ rel_size = 0.
61
+ abs_size = self.fixed_size
62
+ return rel_size, abs_size
63
+
64
+
65
+ class Scaled(_Base):
66
+ """
67
+ Simple scaled(?) size with absolute part = 0 and
68
+ relative part = *scalable_size*.
69
+ """
70
+
71
+ def __init__(self, scalable_size):
72
+ self._scalable_size = scalable_size
73
+
74
+ def get_size(self, renderer):
75
+ rel_size = self._scalable_size
76
+ abs_size = 0.
77
+ return rel_size, abs_size
78
+
79
+ Scalable = Scaled
80
+
81
+
82
+ def _get_axes_aspect(ax):
83
+ aspect = ax.get_aspect()
84
+ if aspect == "auto":
85
+ aspect = 1.
86
+ return aspect
87
+
88
+
89
+ class AxesX(_Base):
90
+ """
91
+ Scaled size whose relative part corresponds to the data width
92
+ of the *axes* multiplied by the *aspect*.
93
+ """
94
+
95
+ def __init__(self, axes, aspect=1., ref_ax=None):
96
+ self._axes = axes
97
+ self._aspect = aspect
98
+ if aspect == "axes" and ref_ax is None:
99
+ raise ValueError("ref_ax must be set when aspect='axes'")
100
+ self._ref_ax = ref_ax
101
+
102
+ def get_size(self, renderer):
103
+ l1, l2 = self._axes.get_xlim()
104
+ if self._aspect == "axes":
105
+ ref_aspect = _get_axes_aspect(self._ref_ax)
106
+ aspect = ref_aspect / _get_axes_aspect(self._axes)
107
+ else:
108
+ aspect = self._aspect
109
+
110
+ rel_size = abs(l2-l1)*aspect
111
+ abs_size = 0.
112
+ return rel_size, abs_size
113
+
114
+
115
+ class AxesY(_Base):
116
+ """
117
+ Scaled size whose relative part corresponds to the data height
118
+ of the *axes* multiplied by the *aspect*.
119
+ """
120
+
121
+ def __init__(self, axes, aspect=1., ref_ax=None):
122
+ self._axes = axes
123
+ self._aspect = aspect
124
+ if aspect == "axes" and ref_ax is None:
125
+ raise ValueError("ref_ax must be set when aspect='axes'")
126
+ self._ref_ax = ref_ax
127
+
128
+ def get_size(self, renderer):
129
+ l1, l2 = self._axes.get_ylim()
130
+
131
+ if self._aspect == "axes":
132
+ ref_aspect = _get_axes_aspect(self._ref_ax)
133
+ aspect = _get_axes_aspect(self._axes)
134
+ else:
135
+ aspect = self._aspect
136
+
137
+ rel_size = abs(l2-l1)*aspect
138
+ abs_size = 0.
139
+ return rel_size, abs_size
140
+
141
+
142
+ class MaxExtent(_Base):
143
+ """
144
+ Size whose absolute part is either the largest width or the largest height
145
+ of the given *artist_list*.
146
+ """
147
+
148
+ def __init__(self, artist_list, w_or_h):
149
+ self._artist_list = artist_list
150
+ _api.check_in_list(["width", "height"], w_or_h=w_or_h)
151
+ self._w_or_h = w_or_h
152
+
153
+ def add_artist(self, a):
154
+ self._artist_list.append(a)
155
+
156
+ def get_size(self, renderer):
157
+ rel_size = 0.
158
+ extent_list = [
159
+ getattr(a.get_window_extent(renderer), self._w_or_h) / a.figure.dpi
160
+ for a in self._artist_list]
161
+ abs_size = max(extent_list, default=0)
162
+ return rel_size, abs_size
163
+
164
+
165
+ class MaxWidth(MaxExtent):
166
+ """
167
+ Size whose absolute part is the largest width of the given *artist_list*.
168
+ """
169
+
170
+ def __init__(self, artist_list):
171
+ super().__init__(artist_list, "width")
172
+
173
+
174
+ class MaxHeight(MaxExtent):
175
+ """
176
+ Size whose absolute part is the largest height of the given *artist_list*.
177
+ """
178
+
179
+ def __init__(self, artist_list):
180
+ super().__init__(artist_list, "height")
181
+
182
+
183
+ class Fraction(_Base):
184
+ """
185
+ An instance whose size is a *fraction* of the *ref_size*.
186
+
187
+ >>> s = Fraction(0.3, AxesX(ax))
188
+ """
189
+
190
+ def __init__(self, fraction, ref_size):
191
+ _api.check_isinstance(Real, fraction=fraction)
192
+ self._fraction_ref = ref_size
193
+ self._fraction = fraction
194
+
195
+ def get_size(self, renderer):
196
+ if self._fraction_ref is None:
197
+ return self._fraction, 0.
198
+ else:
199
+ r, a = self._fraction_ref.get_size(renderer)
200
+ rel_size = r*self._fraction
201
+ abs_size = a*self._fraction
202
+ return rel_size, abs_size
203
+
204
+
205
+ def from_any(size, fraction_ref=None):
206
+ """
207
+ Create a Fixed unit when the first argument is a float, or a
208
+ Fraction unit if that is a string that ends with %. The second
209
+ argument is only meaningful when Fraction unit is created.
210
+
211
+ >>> from mpl_toolkits.axes_grid1.axes_size import from_any
212
+ >>> a = from_any(1.2) # => Fixed(1.2)
213
+ >>> from_any("50%", a) # => Fraction(0.5, a)
214
+ """
215
+ if isinstance(size, Real):
216
+ return Fixed(size)
217
+ elif isinstance(size, str):
218
+ if size[-1] == "%":
219
+ return Fraction(float(size[:-1]) / 100, fraction_ref)
220
+ raise ValueError("Unknown format")
221
+
222
+
223
+ class _AxesDecorationsSize(_Base):
224
+ """
225
+ Fixed size, corresponding to the size of decorations on a given Axes side.
226
+ """
227
+
228
+ _get_size_map = {
229
+ "left": lambda tight_bb, axes_bb: axes_bb.xmin - tight_bb.xmin,
230
+ "right": lambda tight_bb, axes_bb: tight_bb.xmax - axes_bb.xmax,
231
+ "bottom": lambda tight_bb, axes_bb: axes_bb.ymin - tight_bb.ymin,
232
+ "top": lambda tight_bb, axes_bb: tight_bb.ymax - axes_bb.ymax,
233
+ }
234
+
235
+ def __init__(self, ax, direction):
236
+ _api.check_in_list(self._get_size_map, direction=direction)
237
+ self._direction = direction
238
+ self._ax_list = [ax] if isinstance(ax, Axes) else ax
239
+
240
+ def get_size(self, renderer):
241
+ sz = max([
242
+ self._get_size_map[self._direction](
243
+ ax.get_tightbbox(renderer, call_axes_locator=False), ax.bbox)
244
+ for ax in self._ax_list])
245
+ dpi = renderer.points_to_pixels(72)
246
+ abs_size = sz / dpi
247
+ rel_size = 0
248
+ return rel_size, abs_size
parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/inset_locator.py ADDED
@@ -0,0 +1,561 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A collection of functions and objects for creating or placing inset axes.
3
+ """
4
+
5
+ from matplotlib import _api, _docstring
6
+ from matplotlib.offsetbox import AnchoredOffsetbox
7
+ from matplotlib.patches import Patch, Rectangle
8
+ from matplotlib.path import Path
9
+ from matplotlib.transforms import Bbox, BboxTransformTo
10
+ from matplotlib.transforms import IdentityTransform, TransformedBbox
11
+
12
+ from . import axes_size as Size
13
+ from .parasite_axes import HostAxes
14
+
15
+
16
+ @_api.deprecated("3.8", alternative="Axes.inset_axes")
17
+ class InsetPosition:
18
+ @_docstring.dedent_interpd
19
+ def __init__(self, parent, lbwh):
20
+ """
21
+ An object for positioning an inset axes.
22
+
23
+ This is created by specifying the normalized coordinates in the axes,
24
+ instead of the figure.
25
+
26
+ Parameters
27
+ ----------
28
+ parent : `~matplotlib.axes.Axes`
29
+ Axes to use for normalizing coordinates.
30
+
31
+ lbwh : iterable of four floats
32
+ The left edge, bottom edge, width, and height of the inset axes, in
33
+ units of the normalized coordinate of the *parent* axes.
34
+
35
+ See Also
36
+ --------
37
+ :meth:`matplotlib.axes.Axes.set_axes_locator`
38
+
39
+ Examples
40
+ --------
41
+ The following bounds the inset axes to a box with 20%% of the parent
42
+ axes height and 40%% of the width. The size of the axes specified
43
+ ([0, 0, 1, 1]) ensures that the axes completely fills the bounding box:
44
+
45
+ >>> parent_axes = plt.gca()
46
+ >>> ax_ins = plt.axes([0, 0, 1, 1])
47
+ >>> ip = InsetPosition(parent_axes, [0.5, 0.1, 0.4, 0.2])
48
+ >>> ax_ins.set_axes_locator(ip)
49
+ """
50
+ self.parent = parent
51
+ self.lbwh = lbwh
52
+
53
+ def __call__(self, ax, renderer):
54
+ bbox_parent = self.parent.get_position(original=False)
55
+ trans = BboxTransformTo(bbox_parent)
56
+ bbox_inset = Bbox.from_bounds(*self.lbwh)
57
+ bb = TransformedBbox(bbox_inset, trans)
58
+ return bb
59
+
60
+
61
+ class AnchoredLocatorBase(AnchoredOffsetbox):
62
+ def __init__(self, bbox_to_anchor, offsetbox, loc,
63
+ borderpad=0.5, bbox_transform=None):
64
+ super().__init__(
65
+ loc, pad=0., child=None, borderpad=borderpad,
66
+ bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform
67
+ )
68
+
69
+ def draw(self, renderer):
70
+ raise RuntimeError("No draw method should be called")
71
+
72
+ def __call__(self, ax, renderer):
73
+ if renderer is None:
74
+ renderer = ax.figure._get_renderer()
75
+ self.axes = ax
76
+ bbox = self.get_window_extent(renderer)
77
+ px, py = self.get_offset(bbox.width, bbox.height, 0, 0, renderer)
78
+ bbox_canvas = Bbox.from_bounds(px, py, bbox.width, bbox.height)
79
+ tr = ax.figure.transSubfigure.inverted()
80
+ return TransformedBbox(bbox_canvas, tr)
81
+
82
+
83
+ class AnchoredSizeLocator(AnchoredLocatorBase):
84
+ def __init__(self, bbox_to_anchor, x_size, y_size, loc,
85
+ borderpad=0.5, bbox_transform=None):
86
+ super().__init__(
87
+ bbox_to_anchor, None, loc,
88
+ borderpad=borderpad, bbox_transform=bbox_transform
89
+ )
90
+
91
+ self.x_size = Size.from_any(x_size)
92
+ self.y_size = Size.from_any(y_size)
93
+
94
+ def get_bbox(self, renderer):
95
+ bbox = self.get_bbox_to_anchor()
96
+ dpi = renderer.points_to_pixels(72.)
97
+
98
+ r, a = self.x_size.get_size(renderer)
99
+ width = bbox.width * r + a * dpi
100
+ r, a = self.y_size.get_size(renderer)
101
+ height = bbox.height * r + a * dpi
102
+
103
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
104
+ pad = self.pad * fontsize
105
+
106
+ return Bbox.from_bounds(0, 0, width, height).padded(pad)
107
+
108
+
109
+ class AnchoredZoomLocator(AnchoredLocatorBase):
110
+ def __init__(self, parent_axes, zoom, loc,
111
+ borderpad=0.5,
112
+ bbox_to_anchor=None,
113
+ bbox_transform=None):
114
+ self.parent_axes = parent_axes
115
+ self.zoom = zoom
116
+ if bbox_to_anchor is None:
117
+ bbox_to_anchor = parent_axes.bbox
118
+ super().__init__(
119
+ bbox_to_anchor, None, loc, borderpad=borderpad,
120
+ bbox_transform=bbox_transform)
121
+
122
+ def get_bbox(self, renderer):
123
+ bb = self.parent_axes.transData.transform_bbox(self.axes.viewLim)
124
+ fontsize = renderer.points_to_pixels(self.prop.get_size_in_points())
125
+ pad = self.pad * fontsize
126
+ return (
127
+ Bbox.from_bounds(
128
+ 0, 0, abs(bb.width * self.zoom), abs(bb.height * self.zoom))
129
+ .padded(pad))
130
+
131
+
132
+ class BboxPatch(Patch):
133
+ @_docstring.dedent_interpd
134
+ def __init__(self, bbox, **kwargs):
135
+ """
136
+ Patch showing the shape bounded by a Bbox.
137
+
138
+ Parameters
139
+ ----------
140
+ bbox : `~matplotlib.transforms.Bbox`
141
+ Bbox to use for the extents of this patch.
142
+
143
+ **kwargs
144
+ Patch properties. Valid arguments include:
145
+
146
+ %(Patch:kwdoc)s
147
+ """
148
+ if "transform" in kwargs:
149
+ raise ValueError("transform should not be set")
150
+
151
+ kwargs["transform"] = IdentityTransform()
152
+ super().__init__(**kwargs)
153
+ self.bbox = bbox
154
+
155
+ def get_path(self):
156
+ # docstring inherited
157
+ x0, y0, x1, y1 = self.bbox.extents
158
+ return Path._create_closed([(x0, y0), (x1, y0), (x1, y1), (x0, y1)])
159
+
160
+
161
+ class BboxConnector(Patch):
162
+ @staticmethod
163
+ def get_bbox_edge_pos(bbox, loc):
164
+ """
165
+ Return the ``(x, y)`` coordinates of corner *loc* of *bbox*; parameters
166
+ behave as documented for the `.BboxConnector` constructor.
167
+ """
168
+ x0, y0, x1, y1 = bbox.extents
169
+ if loc == 1:
170
+ return x1, y1
171
+ elif loc == 2:
172
+ return x0, y1
173
+ elif loc == 3:
174
+ return x0, y0
175
+ elif loc == 4:
176
+ return x1, y0
177
+
178
+ @staticmethod
179
+ def connect_bbox(bbox1, bbox2, loc1, loc2=None):
180
+ """
181
+ Construct a `.Path` connecting corner *loc1* of *bbox1* to corner
182
+ *loc2* of *bbox2*, where parameters behave as documented as for the
183
+ `.BboxConnector` constructor.
184
+ """
185
+ if isinstance(bbox1, Rectangle):
186
+ bbox1 = TransformedBbox(Bbox.unit(), bbox1.get_transform())
187
+ if isinstance(bbox2, Rectangle):
188
+ bbox2 = TransformedBbox(Bbox.unit(), bbox2.get_transform())
189
+ if loc2 is None:
190
+ loc2 = loc1
191
+ x1, y1 = BboxConnector.get_bbox_edge_pos(bbox1, loc1)
192
+ x2, y2 = BboxConnector.get_bbox_edge_pos(bbox2, loc2)
193
+ return Path([[x1, y1], [x2, y2]])
194
+
195
+ @_docstring.dedent_interpd
196
+ def __init__(self, bbox1, bbox2, loc1, loc2=None, **kwargs):
197
+ """
198
+ Connect two bboxes with a straight line.
199
+
200
+ Parameters
201
+ ----------
202
+ bbox1, bbox2 : `~matplotlib.transforms.Bbox`
203
+ Bounding boxes to connect.
204
+
205
+ loc1, loc2 : {1, 2, 3, 4}
206
+ Corner of *bbox1* and *bbox2* to draw the line. Valid values are::
207
+
208
+ 'upper right' : 1,
209
+ 'upper left' : 2,
210
+ 'lower left' : 3,
211
+ 'lower right' : 4
212
+
213
+ *loc2* is optional and defaults to *loc1*.
214
+
215
+ **kwargs
216
+ Patch properties for the line drawn. Valid arguments include:
217
+
218
+ %(Patch:kwdoc)s
219
+ """
220
+ if "transform" in kwargs:
221
+ raise ValueError("transform should not be set")
222
+
223
+ kwargs["transform"] = IdentityTransform()
224
+ kwargs.setdefault(
225
+ "fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs)))
226
+ super().__init__(**kwargs)
227
+ self.bbox1 = bbox1
228
+ self.bbox2 = bbox2
229
+ self.loc1 = loc1
230
+ self.loc2 = loc2
231
+
232
+ def get_path(self):
233
+ # docstring inherited
234
+ return self.connect_bbox(self.bbox1, self.bbox2,
235
+ self.loc1, self.loc2)
236
+
237
+
238
+ class BboxConnectorPatch(BboxConnector):
239
+ @_docstring.dedent_interpd
240
+ def __init__(self, bbox1, bbox2, loc1a, loc2a, loc1b, loc2b, **kwargs):
241
+ """
242
+ Connect two bboxes with a quadrilateral.
243
+
244
+ The quadrilateral is specified by two lines that start and end at
245
+ corners of the bboxes. The four sides of the quadrilateral are defined
246
+ by the two lines given, the line between the two corners specified in
247
+ *bbox1* and the line between the two corners specified in *bbox2*.
248
+
249
+ Parameters
250
+ ----------
251
+ bbox1, bbox2 : `~matplotlib.transforms.Bbox`
252
+ Bounding boxes to connect.
253
+
254
+ loc1a, loc2a, loc1b, loc2b : {1, 2, 3, 4}
255
+ The first line connects corners *loc1a* of *bbox1* and *loc2a* of
256
+ *bbox2*; the second line connects corners *loc1b* of *bbox1* and
257
+ *loc2b* of *bbox2*. Valid values are::
258
+
259
+ 'upper right' : 1,
260
+ 'upper left' : 2,
261
+ 'lower left' : 3,
262
+ 'lower right' : 4
263
+
264
+ **kwargs
265
+ Patch properties for the line drawn:
266
+
267
+ %(Patch:kwdoc)s
268
+ """
269
+ if "transform" in kwargs:
270
+ raise ValueError("transform should not be set")
271
+ super().__init__(bbox1, bbox2, loc1a, loc2a, **kwargs)
272
+ self.loc1b = loc1b
273
+ self.loc2b = loc2b
274
+
275
+ def get_path(self):
276
+ # docstring inherited
277
+ path1 = self.connect_bbox(self.bbox1, self.bbox2, self.loc1, self.loc2)
278
+ path2 = self.connect_bbox(self.bbox2, self.bbox1,
279
+ self.loc2b, self.loc1b)
280
+ path_merged = [*path1.vertices, *path2.vertices, path1.vertices[0]]
281
+ return Path(path_merged)
282
+
283
+
284
+ def _add_inset_axes(parent_axes, axes_class, axes_kwargs, axes_locator):
285
+ """Helper function to add an inset axes and disable navigation in it."""
286
+ if axes_class is None:
287
+ axes_class = HostAxes
288
+ if axes_kwargs is None:
289
+ axes_kwargs = {}
290
+ inset_axes = axes_class(
291
+ parent_axes.figure, parent_axes.get_position(),
292
+ **{"navigate": False, **axes_kwargs, "axes_locator": axes_locator})
293
+ return parent_axes.figure.add_axes(inset_axes)
294
+
295
+
296
+ @_docstring.dedent_interpd
297
+ def inset_axes(parent_axes, width, height, loc='upper right',
298
+ bbox_to_anchor=None, bbox_transform=None,
299
+ axes_class=None, axes_kwargs=None,
300
+ borderpad=0.5):
301
+ """
302
+ Create an inset axes with a given width and height.
303
+
304
+ Both sizes used can be specified either in inches or percentage.
305
+ For example,::
306
+
307
+ inset_axes(parent_axes, width='40%%', height='30%%', loc='lower left')
308
+
309
+ creates in inset axes in the lower left corner of *parent_axes* which spans
310
+ over 30%% in height and 40%% in width of the *parent_axes*. Since the usage
311
+ of `.inset_axes` may become slightly tricky when exceeding such standard
312
+ cases, it is recommended to read :doc:`the examples
313
+ </gallery/axes_grid1/inset_locator_demo>`.
314
+
315
+ Notes
316
+ -----
317
+ The meaning of *bbox_to_anchor* and *bbox_to_transform* is interpreted
318
+ differently from that of legend. The value of bbox_to_anchor
319
+ (or the return value of its get_points method; the default is
320
+ *parent_axes.bbox*) is transformed by the bbox_transform (the default
321
+ is Identity transform) and then interpreted as points in the pixel
322
+ coordinate (which is dpi dependent).
323
+
324
+ Thus, following three calls are identical and creates an inset axes
325
+ with respect to the *parent_axes*::
326
+
327
+ axins = inset_axes(parent_axes, "30%%", "40%%")
328
+ axins = inset_axes(parent_axes, "30%%", "40%%",
329
+ bbox_to_anchor=parent_axes.bbox)
330
+ axins = inset_axes(parent_axes, "30%%", "40%%",
331
+ bbox_to_anchor=(0, 0, 1, 1),
332
+ bbox_transform=parent_axes.transAxes)
333
+
334
+ Parameters
335
+ ----------
336
+ parent_axes : `matplotlib.axes.Axes`
337
+ Axes to place the inset axes.
338
+
339
+ width, height : float or str
340
+ Size of the inset axes to create. If a float is provided, it is
341
+ the size in inches, e.g. *width=1.3*. If a string is provided, it is
342
+ the size in relative units, e.g. *width='40%%'*. By default, i.e. if
343
+ neither *bbox_to_anchor* nor *bbox_transform* are specified, those
344
+ are relative to the parent_axes. Otherwise, they are to be understood
345
+ relative to the bounding box provided via *bbox_to_anchor*.
346
+
347
+ loc : str, default: 'upper right'
348
+ Location to place the inset axes. Valid locations are
349
+ 'upper left', 'upper center', 'upper right',
350
+ 'center left', 'center', 'center right',
351
+ 'lower left', 'lower center', 'lower right'.
352
+ For backward compatibility, numeric values are accepted as well.
353
+ See the parameter *loc* of `.Legend` for details.
354
+
355
+ bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
356
+ Bbox that the inset axes will be anchored to. If None,
357
+ a tuple of (0, 0, 1, 1) is used if *bbox_transform* is set
358
+ to *parent_axes.transAxes* or *parent_axes.figure.transFigure*.
359
+ Otherwise, *parent_axes.bbox* is used. If a tuple, can be either
360
+ [left, bottom, width, height], or [left, bottom].
361
+ If the kwargs *width* and/or *height* are specified in relative units,
362
+ the 2-tuple [left, bottom] cannot be used. Note that,
363
+ unless *bbox_transform* is set, the units of the bounding box
364
+ are interpreted in the pixel coordinate. When using *bbox_to_anchor*
365
+ with tuple, it almost always makes sense to also specify
366
+ a *bbox_transform*. This might often be the axes transform
367
+ *parent_axes.transAxes*.
368
+
369
+ bbox_transform : `~matplotlib.transforms.Transform`, optional
370
+ Transformation for the bbox that contains the inset axes.
371
+ If None, a `.transforms.IdentityTransform` is used. The value
372
+ of *bbox_to_anchor* (or the return value of its get_points method)
373
+ is transformed by the *bbox_transform* and then interpreted
374
+ as points in the pixel coordinate (which is dpi dependent).
375
+ You may provide *bbox_to_anchor* in some normalized coordinate,
376
+ and give an appropriate transform (e.g., *parent_axes.transAxes*).
377
+
378
+ axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
379
+ The type of the newly created inset axes.
380
+
381
+ axes_kwargs : dict, optional
382
+ Keyword arguments to pass to the constructor of the inset axes.
383
+ Valid arguments include:
384
+
385
+ %(Axes:kwdoc)s
386
+
387
+ borderpad : float, default: 0.5
388
+ Padding between inset axes and the bbox_to_anchor.
389
+ The units are axes font size, i.e. for a default font size of 10 points
390
+ *borderpad = 0.5* is equivalent to a padding of 5 points.
391
+
392
+ Returns
393
+ -------
394
+ inset_axes : *axes_class*
395
+ Inset axes object created.
396
+ """
397
+
398
+ if (bbox_transform in [parent_axes.transAxes, parent_axes.figure.transFigure]
399
+ and bbox_to_anchor is None):
400
+ _api.warn_external("Using the axes or figure transform requires a "
401
+ "bounding box in the respective coordinates. "
402
+ "Using bbox_to_anchor=(0, 0, 1, 1) now.")
403
+ bbox_to_anchor = (0, 0, 1, 1)
404
+ if bbox_to_anchor is None:
405
+ bbox_to_anchor = parent_axes.bbox
406
+ if (isinstance(bbox_to_anchor, tuple) and
407
+ (isinstance(width, str) or isinstance(height, str))):
408
+ if len(bbox_to_anchor) != 4:
409
+ raise ValueError("Using relative units for width or height "
410
+ "requires to provide a 4-tuple or a "
411
+ "`Bbox` instance to `bbox_to_anchor.")
412
+ return _add_inset_axes(
413
+ parent_axes, axes_class, axes_kwargs,
414
+ AnchoredSizeLocator(
415
+ bbox_to_anchor, width, height, loc=loc,
416
+ bbox_transform=bbox_transform, borderpad=borderpad))
417
+
418
+
419
+ @_docstring.dedent_interpd
420
+ def zoomed_inset_axes(parent_axes, zoom, loc='upper right',
421
+ bbox_to_anchor=None, bbox_transform=None,
422
+ axes_class=None, axes_kwargs=None,
423
+ borderpad=0.5):
424
+ """
425
+ Create an anchored inset axes by scaling a parent axes. For usage, also see
426
+ :doc:`the examples </gallery/axes_grid1/inset_locator_demo2>`.
427
+
428
+ Parameters
429
+ ----------
430
+ parent_axes : `~matplotlib.axes.Axes`
431
+ Axes to place the inset axes.
432
+
433
+ zoom : float
434
+ Scaling factor of the data axes. *zoom* > 1 will enlarge the
435
+ coordinates (i.e., "zoomed in"), while *zoom* < 1 will shrink the
436
+ coordinates (i.e., "zoomed out").
437
+
438
+ loc : str, default: 'upper right'
439
+ Location to place the inset axes. Valid locations are
440
+ 'upper left', 'upper center', 'upper right',
441
+ 'center left', 'center', 'center right',
442
+ 'lower left', 'lower center', 'lower right'.
443
+ For backward compatibility, numeric values are accepted as well.
444
+ See the parameter *loc* of `.Legend` for details.
445
+
446
+ bbox_to_anchor : tuple or `~matplotlib.transforms.BboxBase`, optional
447
+ Bbox that the inset axes will be anchored to. If None,
448
+ *parent_axes.bbox* is used. If a tuple, can be either
449
+ [left, bottom, width, height], or [left, bottom].
450
+ If the kwargs *width* and/or *height* are specified in relative units,
451
+ the 2-tuple [left, bottom] cannot be used. Note that
452
+ the units of the bounding box are determined through the transform
453
+ in use. When using *bbox_to_anchor* it almost always makes sense to
454
+ also specify a *bbox_transform*. This might often be the axes transform
455
+ *parent_axes.transAxes*.
456
+
457
+ bbox_transform : `~matplotlib.transforms.Transform`, optional
458
+ Transformation for the bbox that contains the inset axes.
459
+ If None, a `.transforms.IdentityTransform` is used (i.e. pixel
460
+ coordinates). This is useful when not providing any argument to
461
+ *bbox_to_anchor*. When using *bbox_to_anchor* it almost always makes
462
+ sense to also specify a *bbox_transform*. This might often be the
463
+ axes transform *parent_axes.transAxes*. Inversely, when specifying
464
+ the axes- or figure-transform here, be aware that not specifying
465
+ *bbox_to_anchor* will use *parent_axes.bbox*, the units of which are
466
+ in display (pixel) coordinates.
467
+
468
+ axes_class : `~matplotlib.axes.Axes` type, default: `.HostAxes`
469
+ The type of the newly created inset axes.
470
+
471
+ axes_kwargs : dict, optional
472
+ Keyword arguments to pass to the constructor of the inset axes.
473
+ Valid arguments include:
474
+
475
+ %(Axes:kwdoc)s
476
+
477
+ borderpad : float, default: 0.5
478
+ Padding between inset axes and the bbox_to_anchor.
479
+ The units are axes font size, i.e. for a default font size of 10 points
480
+ *borderpad = 0.5* is equivalent to a padding of 5 points.
481
+
482
+ Returns
483
+ -------
484
+ inset_axes : *axes_class*
485
+ Inset axes object created.
486
+ """
487
+
488
+ return _add_inset_axes(
489
+ parent_axes, axes_class, axes_kwargs,
490
+ AnchoredZoomLocator(
491
+ parent_axes, zoom=zoom, loc=loc,
492
+ bbox_to_anchor=bbox_to_anchor, bbox_transform=bbox_transform,
493
+ borderpad=borderpad))
494
+
495
+
496
+ class _TransformedBboxWithCallback(TransformedBbox):
497
+ """
498
+ Variant of `.TransformBbox` which calls *callback* before returning points.
499
+
500
+ Used by `.mark_inset` to unstale the parent axes' viewlim as needed.
501
+ """
502
+
503
+ def __init__(self, *args, callback, **kwargs):
504
+ super().__init__(*args, **kwargs)
505
+ self._callback = callback
506
+
507
+ def get_points(self):
508
+ self._callback()
509
+ return super().get_points()
510
+
511
+
512
+ @_docstring.dedent_interpd
513
+ def mark_inset(parent_axes, inset_axes, loc1, loc2, **kwargs):
514
+ """
515
+ Draw a box to mark the location of an area represented by an inset axes.
516
+
517
+ This function draws a box in *parent_axes* at the bounding box of
518
+ *inset_axes*, and shows a connection with the inset axes by drawing lines
519
+ at the corners, giving a "zoomed in" effect.
520
+
521
+ Parameters
522
+ ----------
523
+ parent_axes : `~matplotlib.axes.Axes`
524
+ Axes which contains the area of the inset axes.
525
+
526
+ inset_axes : `~matplotlib.axes.Axes`
527
+ The inset axes.
528
+
529
+ loc1, loc2 : {1, 2, 3, 4}
530
+ Corners to use for connecting the inset axes and the area in the
531
+ parent axes.
532
+
533
+ **kwargs
534
+ Patch properties for the lines and box drawn:
535
+
536
+ %(Patch:kwdoc)s
537
+
538
+ Returns
539
+ -------
540
+ pp : `~matplotlib.patches.Patch`
541
+ The patch drawn to represent the area of the inset axes.
542
+
543
+ p1, p2 : `~matplotlib.patches.Patch`
544
+ The patches connecting two corners of the inset axes and its area.
545
+ """
546
+ rect = _TransformedBboxWithCallback(
547
+ inset_axes.viewLim, parent_axes.transData,
548
+ callback=parent_axes._unstale_viewLim)
549
+
550
+ kwargs.setdefault("fill", bool({'fc', 'facecolor', 'color'}.intersection(kwargs)))
551
+ pp = BboxPatch(rect, **kwargs)
552
+ parent_axes.add_patch(pp)
553
+
554
+ p1 = BboxConnector(inset_axes.bbox, rect, loc1=loc1, **kwargs)
555
+ inset_axes.add_patch(p1)
556
+ p1.set_clip_on(False)
557
+ p2 = BboxConnector(inset_axes.bbox, rect, loc1=loc2, **kwargs)
558
+ inset_axes.add_patch(p2)
559
+ p2.set_clip_on(False)
560
+
561
+ return pp, p1, p2
parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/mpl_axes.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.axes as maxes
2
+ from matplotlib.artist import Artist
3
+ from matplotlib.axis import XAxis, YAxis
4
+
5
+
6
+ class SimpleChainedObjects:
7
+ def __init__(self, objects):
8
+ self._objects = objects
9
+
10
+ def __getattr__(self, k):
11
+ _a = SimpleChainedObjects([getattr(a, k) for a in self._objects])
12
+ return _a
13
+
14
+ def __call__(self, *args, **kwargs):
15
+ for m in self._objects:
16
+ m(*args, **kwargs)
17
+
18
+
19
+ class Axes(maxes.Axes):
20
+
21
+ class AxisDict(dict):
22
+ def __init__(self, axes):
23
+ self.axes = axes
24
+ super().__init__()
25
+
26
+ def __getitem__(self, k):
27
+ if isinstance(k, tuple):
28
+ r = SimpleChainedObjects(
29
+ # super() within a list comprehension needs explicit args.
30
+ [super(Axes.AxisDict, self).__getitem__(k1) for k1 in k])
31
+ return r
32
+ elif isinstance(k, slice):
33
+ if k.start is None and k.stop is None and k.step is None:
34
+ return SimpleChainedObjects(list(self.values()))
35
+ else:
36
+ raise ValueError("Unsupported slice")
37
+ else:
38
+ return dict.__getitem__(self, k)
39
+
40
+ def __call__(self, *v, **kwargs):
41
+ return maxes.Axes.axis(self.axes, *v, **kwargs)
42
+
43
+ @property
44
+ def axis(self):
45
+ return self._axislines
46
+
47
+ def clear(self):
48
+ # docstring inherited
49
+ super().clear()
50
+ # Init axis artists.
51
+ self._axislines = self.AxisDict(self)
52
+ self._axislines.update(
53
+ bottom=SimpleAxisArtist(self.xaxis, 1, self.spines["bottom"]),
54
+ top=SimpleAxisArtist(self.xaxis, 2, self.spines["top"]),
55
+ left=SimpleAxisArtist(self.yaxis, 1, self.spines["left"]),
56
+ right=SimpleAxisArtist(self.yaxis, 2, self.spines["right"]))
57
+
58
+
59
+ class SimpleAxisArtist(Artist):
60
+ def __init__(self, axis, axisnum, spine):
61
+ self._axis = axis
62
+ self._axisnum = axisnum
63
+ self.line = spine
64
+
65
+ if isinstance(axis, XAxis):
66
+ self._axis_direction = ["bottom", "top"][axisnum-1]
67
+ elif isinstance(axis, YAxis):
68
+ self._axis_direction = ["left", "right"][axisnum-1]
69
+ else:
70
+ raise ValueError(
71
+ f"axis must be instance of XAxis or YAxis, but got {axis}")
72
+ super().__init__()
73
+
74
+ @property
75
+ def major_ticks(self):
76
+ tickline = "tick%dline" % self._axisnum
77
+ return SimpleChainedObjects([getattr(tick, tickline)
78
+ for tick in self._axis.get_major_ticks()])
79
+
80
+ @property
81
+ def major_ticklabels(self):
82
+ label = "label%d" % self._axisnum
83
+ return SimpleChainedObjects([getattr(tick, label)
84
+ for tick in self._axis.get_major_ticks()])
85
+
86
+ @property
87
+ def label(self):
88
+ return self._axis.label
89
+
90
+ def set_visible(self, b):
91
+ self.toggle(all=b)
92
+ self.line.set_visible(b)
93
+ self._axis.set_visible(True)
94
+ super().set_visible(b)
95
+
96
+ def set_label(self, txt):
97
+ self._axis.set_label_text(txt)
98
+
99
+ def toggle(self, all=None, ticks=None, ticklabels=None, label=None):
100
+
101
+ if all:
102
+ _ticks, _ticklabels, _label = True, True, True
103
+ elif all is not None:
104
+ _ticks, _ticklabels, _label = False, False, False
105
+ else:
106
+ _ticks, _ticklabels, _label = None, None, None
107
+
108
+ if ticks is not None:
109
+ _ticks = ticks
110
+ if ticklabels is not None:
111
+ _ticklabels = ticklabels
112
+ if label is not None:
113
+ _label = label
114
+
115
+ if _ticks is not None:
116
+ tickparam = {f"tick{self._axisnum}On": _ticks}
117
+ self._axis.set_tick_params(**tickparam)
118
+ if _ticklabels is not None:
119
+ tickparam = {f"label{self._axisnum}On": _ticklabels}
120
+ self._axis.set_tick_params(**tickparam)
121
+
122
+ if _label is not None:
123
+ pos = self._axis.get_label_position()
124
+ if (pos == self._axis_direction) and not _label:
125
+ self._axis.label.set_visible(False)
126
+ elif _label:
127
+ self._axis.label.set_visible(True)
128
+ self._axis.set_label_position(self._axis_direction)
parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/parasite_axes.py ADDED
@@ -0,0 +1,257 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib import _api, cbook
2
+ import matplotlib.artist as martist
3
+ import matplotlib.transforms as mtransforms
4
+ from matplotlib.transforms import Bbox
5
+ from .mpl_axes import Axes
6
+
7
+
8
+ class ParasiteAxesBase:
9
+
10
+ def __init__(self, parent_axes, aux_transform=None,
11
+ *, viewlim_mode=None, **kwargs):
12
+ self._parent_axes = parent_axes
13
+ self.transAux = aux_transform
14
+ self.set_viewlim_mode(viewlim_mode)
15
+ kwargs["frameon"] = False
16
+ super().__init__(parent_axes.figure, parent_axes._position, **kwargs)
17
+
18
+ def clear(self):
19
+ super().clear()
20
+ martist.setp(self.get_children(), visible=False)
21
+ self._get_lines = self._parent_axes._get_lines
22
+ self._parent_axes.callbacks._connect_picklable(
23
+ "xlim_changed", self._sync_lims)
24
+ self._parent_axes.callbacks._connect_picklable(
25
+ "ylim_changed", self._sync_lims)
26
+
27
+ def pick(self, mouseevent):
28
+ # This most likely goes to Artist.pick (depending on axes_class given
29
+ # to the factory), which only handles pick events registered on the
30
+ # axes associated with each child:
31
+ super().pick(mouseevent)
32
+ # But parasite axes are additionally given pick events from their host
33
+ # axes (cf. HostAxesBase.pick), which we handle here:
34
+ for a in self.get_children():
35
+ if (hasattr(mouseevent.inaxes, "parasites")
36
+ and self in mouseevent.inaxes.parasites):
37
+ a.pick(mouseevent)
38
+
39
+ # aux_transform support
40
+
41
+ def _set_lim_and_transforms(self):
42
+ if self.transAux is not None:
43
+ self.transAxes = self._parent_axes.transAxes
44
+ self.transData = self.transAux + self._parent_axes.transData
45
+ self._xaxis_transform = mtransforms.blended_transform_factory(
46
+ self.transData, self.transAxes)
47
+ self._yaxis_transform = mtransforms.blended_transform_factory(
48
+ self.transAxes, self.transData)
49
+ else:
50
+ super()._set_lim_and_transforms()
51
+
52
+ def set_viewlim_mode(self, mode):
53
+ _api.check_in_list([None, "equal", "transform"], mode=mode)
54
+ self._viewlim_mode = mode
55
+
56
+ def get_viewlim_mode(self):
57
+ return self._viewlim_mode
58
+
59
+ def _sync_lims(self, parent):
60
+ viewlim = parent.viewLim.frozen()
61
+ mode = self.get_viewlim_mode()
62
+ if mode is None:
63
+ pass
64
+ elif mode == "equal":
65
+ self.viewLim.set(viewlim)
66
+ elif mode == "transform":
67
+ self.viewLim.set(viewlim.transformed(self.transAux.inverted()))
68
+ else:
69
+ _api.check_in_list([None, "equal", "transform"], mode=mode)
70
+
71
+ # end of aux_transform support
72
+
73
+
74
+ parasite_axes_class_factory = cbook._make_class_factory(
75
+ ParasiteAxesBase, "{}Parasite")
76
+ ParasiteAxes = parasite_axes_class_factory(Axes)
77
+
78
+
79
+ class HostAxesBase:
80
+ def __init__(self, *args, **kwargs):
81
+ self.parasites = []
82
+ super().__init__(*args, **kwargs)
83
+
84
+ def get_aux_axes(
85
+ self, tr=None, viewlim_mode="equal", axes_class=None, **kwargs):
86
+ """
87
+ Add a parasite axes to this host.
88
+
89
+ Despite this method's name, this should actually be thought of as an
90
+ ``add_parasite_axes`` method.
91
+
92
+ .. versionchanged:: 3.7
93
+ Defaults to same base axes class as host axes.
94
+
95
+ Parameters
96
+ ----------
97
+ tr : `~matplotlib.transforms.Transform` or None, default: None
98
+ If a `.Transform`, the following relation will hold:
99
+ ``parasite.transData = tr + host.transData``.
100
+ If None, the parasite's and the host's ``transData`` are unrelated.
101
+ viewlim_mode : {"equal", "transform", None}, default: "equal"
102
+ How the parasite's view limits are set: directly equal to the
103
+ parent axes ("equal"), equal after application of *tr*
104
+ ("transform"), or independently (None).
105
+ axes_class : subclass type of `~matplotlib.axes.Axes`, optional
106
+ The `~.axes.Axes` subclass that is instantiated. If None, the base
107
+ class of the host axes is used.
108
+ **kwargs
109
+ Other parameters are forwarded to the parasite axes constructor.
110
+ """
111
+ if axes_class is None:
112
+ axes_class = self._base_axes_class
113
+ parasite_axes_class = parasite_axes_class_factory(axes_class)
114
+ ax2 = parasite_axes_class(
115
+ self, tr, viewlim_mode=viewlim_mode, **kwargs)
116
+ # note that ax2.transData == tr + ax1.transData
117
+ # Anything you draw in ax2 will match the ticks and grids of ax1.
118
+ self.parasites.append(ax2)
119
+ ax2._remove_method = self.parasites.remove
120
+ return ax2
121
+
122
+ def draw(self, renderer):
123
+ orig_children_len = len(self._children)
124
+
125
+ locator = self.get_axes_locator()
126
+ if locator:
127
+ pos = locator(self, renderer)
128
+ self.set_position(pos, which="active")
129
+ self.apply_aspect(pos)
130
+ else:
131
+ self.apply_aspect()
132
+
133
+ rect = self.get_position()
134
+ for ax in self.parasites:
135
+ ax.apply_aspect(rect)
136
+ self._children.extend(ax.get_children())
137
+
138
+ super().draw(renderer)
139
+ del self._children[orig_children_len:]
140
+
141
+ def clear(self):
142
+ super().clear()
143
+ for ax in self.parasites:
144
+ ax.clear()
145
+
146
+ def pick(self, mouseevent):
147
+ super().pick(mouseevent)
148
+ # Also pass pick events on to parasite axes and, in turn, their
149
+ # children (cf. ParasiteAxesBase.pick)
150
+ for a in self.parasites:
151
+ a.pick(mouseevent)
152
+
153
+ def twinx(self, axes_class=None):
154
+ """
155
+ Create a twin of Axes with a shared x-axis but independent y-axis.
156
+
157
+ The y-axis of self will have ticks on the left and the returned axes
158
+ will have ticks on the right.
159
+ """
160
+ ax = self._add_twin_axes(axes_class, sharex=self)
161
+ self.axis["right"].set_visible(False)
162
+ ax.axis["right"].set_visible(True)
163
+ ax.axis["left", "top", "bottom"].set_visible(False)
164
+ return ax
165
+
166
+ def twiny(self, axes_class=None):
167
+ """
168
+ Create a twin of Axes with a shared y-axis but independent x-axis.
169
+
170
+ The x-axis of self will have ticks on the bottom and the returned axes
171
+ will have ticks on the top.
172
+ """
173
+ ax = self._add_twin_axes(axes_class, sharey=self)
174
+ self.axis["top"].set_visible(False)
175
+ ax.axis["top"].set_visible(True)
176
+ ax.axis["left", "right", "bottom"].set_visible(False)
177
+ return ax
178
+
179
+ def twin(self, aux_trans=None, axes_class=None):
180
+ """
181
+ Create a twin of Axes with no shared axis.
182
+
183
+ While self will have ticks on the left and bottom axis, the returned
184
+ axes will have ticks on the top and right axis.
185
+ """
186
+ if aux_trans is None:
187
+ aux_trans = mtransforms.IdentityTransform()
188
+ ax = self._add_twin_axes(
189
+ axes_class, aux_transform=aux_trans, viewlim_mode="transform")
190
+ self.axis["top", "right"].set_visible(False)
191
+ ax.axis["top", "right"].set_visible(True)
192
+ ax.axis["left", "bottom"].set_visible(False)
193
+ return ax
194
+
195
+ def _add_twin_axes(self, axes_class, **kwargs):
196
+ """
197
+ Helper for `.twinx`/`.twiny`/`.twin`.
198
+
199
+ *kwargs* are forwarded to the parasite axes constructor.
200
+ """
201
+ if axes_class is None:
202
+ axes_class = self._base_axes_class
203
+ ax = parasite_axes_class_factory(axes_class)(self, **kwargs)
204
+ self.parasites.append(ax)
205
+ ax._remove_method = self._remove_any_twin
206
+ return ax
207
+
208
+ def _remove_any_twin(self, ax):
209
+ self.parasites.remove(ax)
210
+ restore = ["top", "right"]
211
+ if ax._sharex:
212
+ restore.remove("top")
213
+ if ax._sharey:
214
+ restore.remove("right")
215
+ self.axis[tuple(restore)].set_visible(True)
216
+ self.axis[tuple(restore)].toggle(ticklabels=False, label=False)
217
+
218
+ @_api.make_keyword_only("3.8", "call_axes_locator")
219
+ def get_tightbbox(self, renderer=None, call_axes_locator=True,
220
+ bbox_extra_artists=None):
221
+ bbs = [
222
+ *[ax.get_tightbbox(renderer, call_axes_locator=call_axes_locator)
223
+ for ax in self.parasites],
224
+ super().get_tightbbox(renderer,
225
+ call_axes_locator=call_axes_locator,
226
+ bbox_extra_artists=bbox_extra_artists)]
227
+ return Bbox.union([b for b in bbs if b.width != 0 or b.height != 0])
228
+
229
+
230
+ host_axes_class_factory = host_subplot_class_factory = \
231
+ cbook._make_class_factory(HostAxesBase, "{}HostAxes", "_base_axes_class")
232
+ HostAxes = SubplotHost = host_axes_class_factory(Axes)
233
+
234
+
235
+ def host_axes(*args, axes_class=Axes, figure=None, **kwargs):
236
+ """
237
+ Create axes that can act as a hosts to parasitic axes.
238
+
239
+ Parameters
240
+ ----------
241
+ figure : `~matplotlib.figure.Figure`
242
+ Figure to which the axes will be added. Defaults to the current figure
243
+ `.pyplot.gcf()`.
244
+
245
+ *args, **kwargs
246
+ Will be passed on to the underlying `~.axes.Axes` object creation.
247
+ """
248
+ import matplotlib.pyplot as plt
249
+ host_axes_class = host_axes_class_factory(axes_class)
250
+ if figure is None:
251
+ figure = plt.gcf()
252
+ ax = host_axes_class(figure, *args, **kwargs)
253
+ figure.add_axes(ax)
254
+ return ax
255
+
256
+
257
+ host_subplot = host_axes
parrot/lib/python3.10/site-packages/mpl_toolkits/axes_grid1/tests/__init__.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ from pathlib import Path
2
+
3
+
4
+ # Check that the test directories exist
5
+ if not (Path(__file__).parent / "baseline_images").exists():
6
+ raise OSError(
7
+ 'The baseline image directory does not exist. '
8
+ 'This is most likely because the test data is not installed. '
9
+ 'You may need to install matplotlib from source to get the '
10
+ 'test data.')