ZTWHHH commited on
Commit
2086358
·
verified ·
1 Parent(s): 26a1559

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER +1 -0
  3. llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE +29 -0
  4. llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA +93 -0
  5. llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD +43 -0
  6. llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED +0 -0
  7. llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL +6 -0
  8. llava_video/lib/python3.10/site-packages/matplotlib/axis.py +0 -0
  9. llava_video/lib/python3.10/site-packages/matplotlib/collections.py +2582 -0
  10. llava_video/lib/python3.10/site-packages/matplotlib/font_manager.py +1645 -0
  11. llava_video/lib/python3.10/site-packages/matplotlib/offsetbox.pyi +298 -0
  12. llava_video/lib/python3.10/site-packages/matplotlib/text.pyi +181 -0
  13. llava_video/lib/python3.10/site-packages/matplotlib/textpath.pyi +74 -0
  14. llava_video/lib/python3.10/site-packages/matplotlib/transforms.pyi +341 -0
  15. llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc +3 -0
  16. llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  17. llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc +0 -0
  18. llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_pkg_resources.cpython-310.pyc +0 -0
  19. llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc +0 -0
  20. llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc +0 -0
  21. llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.cfg +0 -0
  22. llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip +3 -0
  23. llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO +10 -0
  24. llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt +1 -0
  25. llava_video/lib/python3.10/site-packages/pkg_resources/tests/test_working_set.py +501 -0
  26. llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc +0 -0
  27. llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc +0 -0
  28. llava_video/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc +0 -0
  29. llava_video/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc +0 -0
  30. llava_video/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc +0 -0
  31. llava_video/lib/python3.10/site-packages/pybind11/_version.py +12 -0
  32. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h +690 -0
  33. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h +208 -0
  34. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h +1855 -0
  35. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h +225 -0
  36. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/common.h +2 -0
  37. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/complex.h +74 -0
  38. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/class.h +767 -0
  39. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/common.h +1287 -0
  40. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/cpp_conduit.h +77 -0
  41. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/descr.h +172 -0
  42. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/exception_translation.h +71 -0
  43. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/init.h +436 -0
  44. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/internals.h +766 -0
  45. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/type_caster_base.h +1195 -0
  46. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/typeid.h +65 -0
  47. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/value_and_holder.h +77 -0
  48. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/eigen.h +12 -0
  49. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/common.h +9 -0
  50. llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/matrix.h +715 -0
.gitattributes CHANGED
@@ -665,3 +665,4 @@ llava_video/lib/python3.10/site-packages/scipy/ndimage/_nd_image.cpython-310-x86
665
  llava_video/lib/python3.10/site-packages/scipy/ndimage/_ni_label.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
666
  llava_video/lib/python3.10/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
667
  llava_video/lib/python3.10/site-packages/fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
665
  llava_video/lib/python3.10/site-packages/scipy/ndimage/_ni_label.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
666
  llava_video/lib/python3.10/site-packages/scipy/integrate/__pycache__/_lebedev.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
667
  llava_video/lib/python3.10/site-packages/fontTools/misc/bezierTools.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
668
+ llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text
llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER ADDED
@@ -0,0 +1 @@
 
 
1
+ pip
llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ BSD 3-Clause License
2
+
3
+ Copyright (c) 2021-2024, ContourPy Developers.
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
+ 1. Redistributions of source code must retain the above copyright notice, this
10
+ list of conditions and the following disclaimer.
11
+
12
+ 2. 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
+ 3. 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_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 2.1
2
+ Name: contourpy
3
+ Version: 1.3.1
4
+ Summary: Python library for calculating contours of 2D quadrilateral grids
5
+ Author-Email: Ian Thomas <ianthomas23@gmail.com>
6
+ License: BSD 3-Clause License
7
+
8
+ Copyright (c) 2021-2024, ContourPy Developers.
9
+ All rights reserved.
10
+
11
+ Redistribution and use in source and binary forms, with or without
12
+ modification, are permitted provided that the following conditions are met:
13
+
14
+ 1. Redistributions of source code must retain the above copyright notice, this
15
+ list of conditions and the following disclaimer.
16
+
17
+ 2. Redistributions in binary form must reproduce the above copyright notice,
18
+ this list of conditions and the following disclaimer in the documentation
19
+ and/or other materials provided with the distribution.
20
+
21
+ 3. Neither the name of the copyright holder nor the names of its
22
+ contributors may be used to endorse or promote products derived from
23
+ this software without specific prior written permission.
24
+
25
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
26
+ AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
27
+ IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
28
+ DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
29
+ FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
30
+ DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31
+ SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
32
+ CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
33
+ OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
34
+ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
35
+
36
+ Classifier: Development Status :: 5 - Production/Stable
37
+ Classifier: Intended Audience :: Developers
38
+ Classifier: Intended Audience :: Science/Research
39
+ Classifier: License :: OSI Approved :: BSD License
40
+ Classifier: Programming Language :: C++
41
+ Classifier: Programming Language :: Python :: 3
42
+ Classifier: Programming Language :: Python :: 3.10
43
+ Classifier: Programming Language :: Python :: 3.11
44
+ Classifier: Programming Language :: Python :: 3.12
45
+ Classifier: Programming Language :: Python :: 3.13
46
+ Classifier: Topic :: Scientific/Engineering :: Information Analysis
47
+ Classifier: Topic :: Scientific/Engineering :: Mathematics
48
+ Classifier: Topic :: Scientific/Engineering :: Visualization
49
+ Project-URL: Homepage, https://github.com/contourpy/contourpy
50
+ Project-URL: Changelog, https://contourpy.readthedocs.io/en/latest/changelog.html
51
+ Project-URL: Documentation, https://contourpy.readthedocs.io
52
+ Project-URL: Repository, https://github.com/contourpy/contourpy
53
+ Requires-Python: >=3.10
54
+ Requires-Dist: numpy>=1.23
55
+ Provides-Extra: docs
56
+ Requires-Dist: furo; extra == "docs"
57
+ Requires-Dist: sphinx>=7.2; extra == "docs"
58
+ Requires-Dist: sphinx-copybutton; extra == "docs"
59
+ Provides-Extra: bokeh
60
+ Requires-Dist: bokeh; extra == "bokeh"
61
+ Requires-Dist: selenium; extra == "bokeh"
62
+ Provides-Extra: mypy
63
+ Requires-Dist: contourpy[bokeh,docs]; extra == "mypy"
64
+ Requires-Dist: docutils-stubs; extra == "mypy"
65
+ Requires-Dist: mypy==1.11.1; extra == "mypy"
66
+ Requires-Dist: types-Pillow; extra == "mypy"
67
+ Provides-Extra: test
68
+ Requires-Dist: contourpy[test-no-images]; extra == "test"
69
+ Requires-Dist: matplotlib; extra == "test"
70
+ Requires-Dist: Pillow; extra == "test"
71
+ Provides-Extra: test-no-images
72
+ Requires-Dist: pytest; extra == "test-no-images"
73
+ Requires-Dist: pytest-cov; extra == "test-no-images"
74
+ Requires-Dist: pytest-rerunfailures; extra == "test-no-images"
75
+ Requires-Dist: pytest-xdist; extra == "test-no-images"
76
+ Requires-Dist: wurlitzer; extra == "test-no-images"
77
+ Description-Content-Type: text/markdown
78
+
79
+ <img alt="ContourPy" src="https://raw.githubusercontent.com/contourpy/contourpy/main/docs/_static/contourpy_logo_horiz.svg" height="90">
80
+
81
+ ContourPy is a Python library for calculating contours of 2D quadrilateral grids. It is written in C++11 and wrapped using pybind11.
82
+
83
+ It contains the 2005 and 2014 algorithms used in Matplotlib as well as a newer algorithm that includes more features and is available in both serial and multithreaded versions. It provides an easy way for Python libraries to use contouring algorithms without having to include Matplotlib as a dependency.
84
+
85
+ * **Documentation**: https://contourpy.readthedocs.io
86
+ * **Source code**: https://github.com/contourpy/contourpy
87
+
88
+ | | |
89
+ | --- | --- |
90
+ | Latest release | [![PyPI version](https://img.shields.io/pypi/v/contourpy.svg?label=pypi&color=fdae61)](https://pypi.python.org/pypi/contourpy) [![conda-forge version](https://img.shields.io/conda/v/conda-forge/contourpy.svg?label=conda-forge&color=a6d96a)](https://anaconda.org/conda-forge/contourpy) |
91
+ | Downloads | [![PyPi downloads](https://img.shields.io/pypi/dm/contourpy?label=pypi&style=flat&color=fdae61)](https://pepy.tech/project/contourpy) |
92
+ | Python version | [![Platforms](https://img.shields.io/pypi/pyversions/contourpy?color=fdae61)](https://pypi.org/project/contourpy/) |
93
+ | Coverage | [![Codecov](https://img.shields.io/codecov/c/gh/contourpy/contourpy?color=fdae61&label=codecov)](https://app.codecov.io/gh/contourpy/contourpy) |
llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ contourpy-1.3.1.dist-info/INSTALLER,sha256=zuuue4knoyJ-UwPPXg8fezS7VCrXJQrAP7zeNuwvFQg,4
2
+ contourpy-1.3.1.dist-info/LICENSE,sha256=x9ChU7_6oQQERGPrxjN5PUUXIu_TE4tf_SUntA8VBaI,1534
3
+ contourpy-1.3.1.dist-info/METADATA,sha256=LQNae4q9MVNwpfb0FlnTCTe2tkw22GiKEJjpks9n7jk,5423
4
+ contourpy-1.3.1.dist-info/RECORD,,
5
+ contourpy-1.3.1.dist-info/REQUESTED,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ contourpy-1.3.1.dist-info/WHEEL,sha256=sZM_NeUMz2G4fDenMf11eikcCxcLaQWiYRmjwQBavQs,137
7
+ contourpy/__init__.py,sha256=Vi2YbtUhM9VxYPY3PBvxfu0xZYr6fBysl5gQPJEo88k,11831
8
+ contourpy/__pycache__/__init__.cpython-310.pyc,,
9
+ contourpy/__pycache__/_version.cpython-310.pyc,,
10
+ contourpy/__pycache__/array.cpython-310.pyc,,
11
+ contourpy/__pycache__/chunk.cpython-310.pyc,,
12
+ contourpy/__pycache__/convert.cpython-310.pyc,,
13
+ contourpy/__pycache__/dechunk.cpython-310.pyc,,
14
+ contourpy/__pycache__/enum_util.cpython-310.pyc,,
15
+ contourpy/__pycache__/typecheck.cpython-310.pyc,,
16
+ contourpy/__pycache__/types.cpython-310.pyc,,
17
+ contourpy/_contourpy.cpython-310-x86_64-linux-gnu.so,sha256=H8GWcYv0tePHkvGU0HhmBO_d_Chj3Bs_6QYgLRKjIMI,854312
18
+ contourpy/_contourpy.pyi,sha256=fvtccxkiZwGb6qYag7Fp4E8bsFmAIjAmobf8LNxqfgc,7122
19
+ contourpy/_version.py,sha256=-ypEJktJToAL9by62JJKWEzDo_KPCQtmE5kwFgX24z4,22
20
+ contourpy/array.py,sha256=4WwLuiZe30rizn_raymmY13OzE6hlCsDOO8kuVFOP18,8979
21
+ contourpy/chunk.py,sha256=8njDQqlpuD22RjaaCyA75FXQsSQDY5hZGJSrxFpvGGU,3279
22
+ contourpy/convert.py,sha256=mhyn7prEoWCnf0igaH-VqDwlk-CegFsZ4qOy2LL-hpU,26154
23
+ contourpy/dechunk.py,sha256=EgFL6hw5H54ccuof4tJ2ehdnktT7trgZjiZqppsH8QI,7756
24
+ contourpy/enum_util.py,sha256=o8MItJRs08oqzwPP3IwC75BBAY9Qq95saIzjkXBXwqA,1519
25
+ contourpy/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
26
+ contourpy/typecheck.py,sha256=t1nvvCuKMYva1Zx4fc30EpdKFcO0Enz3n_UFfXBsq9o,10747
27
+ contourpy/types.py,sha256=2K4T5tJpMIjYrkkg1Lqh3C2ZKlnOhnMtYmtwz92l_y8,247
28
+ contourpy/util/__init__.py,sha256=eVhJ_crOHL7nkG4Kb0dOo7NL4WHMy_Px665aAN_3d-8,118
29
+ contourpy/util/__pycache__/__init__.cpython-310.pyc,,
30
+ contourpy/util/__pycache__/_build_config.cpython-310.pyc,,
31
+ contourpy/util/__pycache__/bokeh_renderer.cpython-310.pyc,,
32
+ contourpy/util/__pycache__/bokeh_util.cpython-310.pyc,,
33
+ contourpy/util/__pycache__/data.cpython-310.pyc,,
34
+ contourpy/util/__pycache__/mpl_renderer.cpython-310.pyc,,
35
+ contourpy/util/__pycache__/mpl_util.cpython-310.pyc,,
36
+ contourpy/util/__pycache__/renderer.cpython-310.pyc,,
37
+ contourpy/util/_build_config.py,sha256=jzJKkuBQpyjnX1U_eltbhIAN_i6fbzTAQXMAP1YTlG0,1848
38
+ contourpy/util/bokeh_renderer.py,sha256=wNGBghEVA4x11wrSerb3dBbdRxX6E8kuoqlaKPoHTQ8,13769
39
+ contourpy/util/bokeh_util.py,sha256=wc-S3ewBUYWyIkEv9jkhFySIergjLQl4Z0UEVnE0HhA,2804
40
+ contourpy/util/data.py,sha256=-7SSGMLX_gN-1H2JzpNSEB_EcEF_uMtYdOo_ePRIcg8,2586
41
+ contourpy/util/mpl_renderer.py,sha256=avUxO7_MQRDQM84X5PZ9GbNtGxG0EXPSVQYV00xQMvQ,20089
42
+ contourpy/util/mpl_util.py,sha256=0Jz5f-aA9XMWlpO2pDnHbkVgxIiw4SY_ysxf_gACWEo,3452
43
+ contourpy/util/renderer.py,sha256=8CBHzPmVsFPfqsWxqrxGBhqFpJhVeFHFeDzVXAgT8Fc,5118
llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED ADDED
File without changes
llava_video/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ Wheel-Version: 1.0
2
+ Generator: meson
3
+ Root-Is-Purelib: false
4
+ Tag: cp310-cp310-manylinux_2_17_x86_64
5
+ Tag: cp310-cp310-manylinux2014_x86_64
6
+
llava_video/lib/python3.10/site-packages/matplotlib/axis.py ADDED
The diff for this file is too large to render. See raw diff
 
llava_video/lib/python3.10/site-packages/matplotlib/collections.py ADDED
@@ -0,0 +1,2582 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Classes for the efficient drawing of large collections of objects that
3
+ share most properties, e.g., a large number of line segments or
4
+ polygons.
5
+
6
+ The classes are not meant to be as flexible as their single element
7
+ counterparts (e.g., you may not be able to select all line styles) but
8
+ they are meant to be fast for common use cases (e.g., a large set of solid
9
+ line segments).
10
+ """
11
+
12
+ import itertools
13
+ import functools
14
+ import math
15
+ from numbers import Number, Real
16
+ import warnings
17
+
18
+ import numpy as np
19
+
20
+ import matplotlib as mpl
21
+ from . import (_api, _path, artist, cbook, colorizer as mcolorizer, colors as mcolors,
22
+ _docstring, hatch as mhatch, lines as mlines, path as mpath, transforms)
23
+ from ._enums import JoinStyle, CapStyle
24
+
25
+
26
+ # "color" is excluded; it is a compound setter, and its docstring differs
27
+ # in LineCollection.
28
+ @_api.define_aliases({
29
+ "antialiased": ["antialiaseds", "aa"],
30
+ "edgecolor": ["edgecolors", "ec"],
31
+ "facecolor": ["facecolors", "fc"],
32
+ "linestyle": ["linestyles", "dashes", "ls"],
33
+ "linewidth": ["linewidths", "lw"],
34
+ "offset_transform": ["transOffset"],
35
+ })
36
+ class Collection(mcolorizer.ColorizingArtist):
37
+ r"""
38
+ Base class for Collections. Must be subclassed to be usable.
39
+
40
+ A Collection represents a sequence of `.Patch`\es that can be drawn
41
+ more efficiently together than individually. For example, when a single
42
+ path is being drawn repeatedly at different offsets, the renderer can
43
+ typically execute a ``draw_marker()`` call much more efficiently than a
44
+ series of repeated calls to ``draw_path()`` with the offsets put in
45
+ one-by-one.
46
+
47
+ Most properties of a collection can be configured per-element. Therefore,
48
+ Collections have "plural" versions of many of the properties of a `.Patch`
49
+ (e.g. `.Collection.get_paths` instead of `.Patch.get_path`). Exceptions are
50
+ the *zorder*, *hatch*, *pickradius*, *capstyle* and *joinstyle* properties,
51
+ which can only be set globally for the whole collection.
52
+
53
+ Besides these exceptions, all properties can be specified as single values
54
+ (applying to all elements) or sequences of values. The property of the
55
+ ``i``\th element of the collection is::
56
+
57
+ prop[i % len(prop)]
58
+
59
+ Each Collection can optionally be used as its own `.ScalarMappable` by
60
+ passing the *norm* and *cmap* parameters to its constructor. If the
61
+ Collection's `.ScalarMappable` matrix ``_A`` has been set (via a call
62
+ to `.Collection.set_array`), then at draw time this internal scalar
63
+ mappable will be used to set the ``facecolors`` and ``edgecolors``,
64
+ ignoring those that were manually passed in.
65
+ """
66
+ #: Either a list of 3x3 arrays or an Nx3x3 array (representing N
67
+ #: transforms), suitable for the `all_transforms` argument to
68
+ #: `~matplotlib.backend_bases.RendererBase.draw_path_collection`;
69
+ #: each 3x3 array is used to initialize an
70
+ #: `~matplotlib.transforms.Affine2D` object.
71
+ #: Each kind of collection defines this based on its arguments.
72
+ _transforms = np.empty((0, 3, 3))
73
+
74
+ # Whether to draw an edge by default. Set on a
75
+ # subclass-by-subclass basis.
76
+ _edge_default = False
77
+
78
+ @_docstring.interpd
79
+ def __init__(self, *,
80
+ edgecolors=None,
81
+ facecolors=None,
82
+ linewidths=None,
83
+ linestyles='solid',
84
+ capstyle=None,
85
+ joinstyle=None,
86
+ antialiaseds=None,
87
+ offsets=None,
88
+ offset_transform=None,
89
+ norm=None, # optional for ScalarMappable
90
+ cmap=None, # ditto
91
+ colorizer=None,
92
+ pickradius=5.0,
93
+ hatch=None,
94
+ urls=None,
95
+ zorder=1,
96
+ **kwargs
97
+ ):
98
+ """
99
+ Parameters
100
+ ----------
101
+ edgecolors : :mpltype:`color` or list of colors, default: :rc:`patch.edgecolor`
102
+ Edge color for each patch making up the collection. The special
103
+ value 'face' can be passed to make the edgecolor match the
104
+ facecolor.
105
+ facecolors : :mpltype:`color` or list of colors, default: :rc:`patch.facecolor`
106
+ Face color for each patch making up the collection.
107
+ linewidths : float or list of floats, default: :rc:`patch.linewidth`
108
+ Line width for each patch making up the collection.
109
+ linestyles : str or tuple or list thereof, default: 'solid'
110
+ Valid strings are ['solid', 'dashed', 'dashdot', 'dotted', '-',
111
+ '--', '-.', ':']. Dash tuples should be of the form::
112
+
113
+ (offset, onoffseq),
114
+
115
+ where *onoffseq* is an even length tuple of on and off ink lengths
116
+ in points. For examples, see
117
+ :doc:`/gallery/lines_bars_and_markers/linestyles`.
118
+ capstyle : `.CapStyle`-like, default: 'butt'
119
+ Style to use for capping lines for all paths in the collection.
120
+ Allowed values are %(CapStyle)s.
121
+ joinstyle : `.JoinStyle`-like, default: 'round'
122
+ Style to use for joining lines for all paths in the collection.
123
+ Allowed values are %(JoinStyle)s.
124
+ antialiaseds : bool or list of bool, default: :rc:`patch.antialiased`
125
+ Whether each patch in the collection should be drawn with
126
+ antialiasing.
127
+ offsets : (float, float) or list thereof, default: (0, 0)
128
+ A vector by which to translate each patch after rendering (default
129
+ is no translation). The translation is performed in screen (pixel)
130
+ coordinates (i.e. after the Artist's transform is applied).
131
+ offset_transform : `~.Transform`, default: `.IdentityTransform`
132
+ A single transform which will be applied to each *offsets* vector
133
+ before it is used.
134
+ cmap, norm
135
+ Data normalization and colormapping parameters. See
136
+ `.ScalarMappable` for a detailed description.
137
+ hatch : str, optional
138
+ Hatching pattern to use in filled paths, if any. Valid strings are
139
+ ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']. See
140
+ :doc:`/gallery/shapes_and_collections/hatch_style_reference` for
141
+ the meaning of each hatch type.
142
+ pickradius : float, default: 5.0
143
+ If ``pickradius <= 0``, then `.Collection.contains` will return
144
+ ``True`` whenever the test point is inside of one of the polygons
145
+ formed by the control points of a Path in the Collection. On the
146
+ other hand, if it is greater than 0, then we instead check if the
147
+ test point is contained in a stroke of width ``2*pickradius``
148
+ following any of the Paths in the Collection.
149
+ urls : list of str, default: None
150
+ A URL for each patch to link to once drawn. Currently only works
151
+ for the SVG backend. See :doc:`/gallery/misc/hyperlinks_sgskip` for
152
+ examples.
153
+ zorder : float, default: 1
154
+ The drawing order, shared by all Patches in the Collection. See
155
+ :doc:`/gallery/misc/zorder_demo` for all defaults and examples.
156
+ **kwargs
157
+ Remaining keyword arguments will be used to set properties as
158
+ ``Collection.set_{key}(val)`` for each key-value pair in *kwargs*.
159
+ """
160
+
161
+ super().__init__(self._get_colorizer(cmap, norm, colorizer))
162
+ # list of un-scaled dash patterns
163
+ # this is needed scaling the dash pattern by linewidth
164
+ self._us_linestyles = [(0, None)]
165
+ # list of dash patterns
166
+ self._linestyles = [(0, None)]
167
+ # list of unbroadcast/scaled linewidths
168
+ self._us_lw = [0]
169
+ self._linewidths = [0]
170
+
171
+ self._gapcolor = None # Currently only used by LineCollection.
172
+
173
+ # Flags set by _set_mappable_flags: are colors from mapping an array?
174
+ self._face_is_mapped = None
175
+ self._edge_is_mapped = None
176
+ self._mapped_colors = None # calculated in update_scalarmappable
177
+ self._hatch_color = mcolors.to_rgba(mpl.rcParams['hatch.color'])
178
+ self._hatch_linewidth = mpl.rcParams['hatch.linewidth']
179
+ self.set_facecolor(facecolors)
180
+ self.set_edgecolor(edgecolors)
181
+ self.set_linewidth(linewidths)
182
+ self.set_linestyle(linestyles)
183
+ self.set_antialiased(antialiaseds)
184
+ self.set_pickradius(pickradius)
185
+ self.set_urls(urls)
186
+ self.set_hatch(hatch)
187
+ self.set_zorder(zorder)
188
+
189
+ if capstyle:
190
+ self.set_capstyle(capstyle)
191
+ else:
192
+ self._capstyle = None
193
+
194
+ if joinstyle:
195
+ self.set_joinstyle(joinstyle)
196
+ else:
197
+ self._joinstyle = None
198
+
199
+ if offsets is not None:
200
+ offsets = np.asanyarray(offsets, float)
201
+ # Broadcast (2,) -> (1, 2) but nothing else.
202
+ if offsets.shape == (2,):
203
+ offsets = offsets[None, :]
204
+
205
+ self._offsets = offsets
206
+ self._offset_transform = offset_transform
207
+
208
+ self._path_effects = None
209
+ self._internal_update(kwargs)
210
+ self._paths = None
211
+
212
+ def get_paths(self):
213
+ return self._paths
214
+
215
+ def set_paths(self, paths):
216
+ self._paths = paths
217
+ self.stale = True
218
+
219
+ def get_transforms(self):
220
+ return self._transforms
221
+
222
+ def get_offset_transform(self):
223
+ """Return the `.Transform` instance used by this artist offset."""
224
+ if self._offset_transform is None:
225
+ self._offset_transform = transforms.IdentityTransform()
226
+ elif (not isinstance(self._offset_transform, transforms.Transform)
227
+ and hasattr(self._offset_transform, '_as_mpl_transform')):
228
+ self._offset_transform = \
229
+ self._offset_transform._as_mpl_transform(self.axes)
230
+ return self._offset_transform
231
+
232
+ def set_offset_transform(self, offset_transform):
233
+ """
234
+ Set the artist offset transform.
235
+
236
+ Parameters
237
+ ----------
238
+ offset_transform : `.Transform`
239
+ """
240
+ self._offset_transform = offset_transform
241
+
242
+ def get_datalim(self, transData):
243
+ # Calculate the data limits and return them as a `.Bbox`.
244
+ #
245
+ # This operation depends on the transforms for the data in the
246
+ # collection and whether the collection has offsets:
247
+ #
248
+ # 1. offsets = None, transform child of transData: use the paths for
249
+ # the automatic limits (i.e. for LineCollection in streamline).
250
+ # 2. offsets != None: offset_transform is child of transData:
251
+ #
252
+ # a. transform is child of transData: use the path + offset for
253
+ # limits (i.e for bar).
254
+ # b. transform is not a child of transData: just use the offsets
255
+ # for the limits (i.e. for scatter)
256
+ #
257
+ # 3. otherwise return a null Bbox.
258
+
259
+ transform = self.get_transform()
260
+ offset_trf = self.get_offset_transform()
261
+ if not (isinstance(offset_trf, transforms.IdentityTransform)
262
+ or offset_trf.contains_branch(transData)):
263
+ # if the offsets are in some coords other than data,
264
+ # then don't use them for autoscaling.
265
+ return transforms.Bbox.null()
266
+
267
+ paths = self.get_paths()
268
+ if not len(paths):
269
+ # No paths to transform
270
+ return transforms.Bbox.null()
271
+
272
+ if not transform.is_affine:
273
+ paths = [transform.transform_path_non_affine(p) for p in paths]
274
+ # Don't convert transform to transform.get_affine() here because
275
+ # we may have transform.contains_branch(transData) but not
276
+ # transforms.get_affine().contains_branch(transData). But later,
277
+ # be careful to only apply the affine part that remains.
278
+
279
+ offsets = self.get_offsets()
280
+
281
+ if any(transform.contains_branch_seperately(transData)):
282
+ # collections that are just in data units (like quiver)
283
+ # can properly have the axes limits set by their shape +
284
+ # offset. LineCollections that have no offsets can
285
+ # also use this algorithm (like streamplot).
286
+ if isinstance(offsets, np.ma.MaskedArray):
287
+ offsets = offsets.filled(np.nan)
288
+ # get_path_collection_extents handles nan but not masked arrays
289
+ return mpath.get_path_collection_extents(
290
+ transform.get_affine() - transData, paths,
291
+ self.get_transforms(),
292
+ offset_trf.transform_non_affine(offsets),
293
+ offset_trf.get_affine().frozen())
294
+
295
+ # NOTE: None is the default case where no offsets were passed in
296
+ if self._offsets is not None:
297
+ # this is for collections that have their paths (shapes)
298
+ # in physical, axes-relative, or figure-relative units
299
+ # (i.e. like scatter). We can't uniquely set limits based on
300
+ # those shapes, so we just set the limits based on their
301
+ # location.
302
+ offsets = (offset_trf - transData).transform(offsets)
303
+ # note A-B means A B^{-1}
304
+ offsets = np.ma.masked_invalid(offsets)
305
+ if not offsets.mask.all():
306
+ bbox = transforms.Bbox.null()
307
+ bbox.update_from_data_xy(offsets)
308
+ return bbox
309
+ return transforms.Bbox.null()
310
+
311
+ def get_window_extent(self, renderer=None):
312
+ # TODO: check to ensure that this does not fail for
313
+ # cases other than scatter plot legend
314
+ return self.get_datalim(transforms.IdentityTransform())
315
+
316
+ def _prepare_points(self):
317
+ # Helper for drawing and hit testing.
318
+
319
+ transform = self.get_transform()
320
+ offset_trf = self.get_offset_transform()
321
+ offsets = self.get_offsets()
322
+ paths = self.get_paths()
323
+
324
+ if self.have_units():
325
+ paths = []
326
+ for path in self.get_paths():
327
+ vertices = path.vertices
328
+ xs, ys = vertices[:, 0], vertices[:, 1]
329
+ xs = self.convert_xunits(xs)
330
+ ys = self.convert_yunits(ys)
331
+ paths.append(mpath.Path(np.column_stack([xs, ys]), path.codes))
332
+ xs = self.convert_xunits(offsets[:, 0])
333
+ ys = self.convert_yunits(offsets[:, 1])
334
+ offsets = np.ma.column_stack([xs, ys])
335
+
336
+ if not transform.is_affine:
337
+ paths = [transform.transform_path_non_affine(path)
338
+ for path in paths]
339
+ transform = transform.get_affine()
340
+ if not offset_trf.is_affine:
341
+ offsets = offset_trf.transform_non_affine(offsets)
342
+ # This might have changed an ndarray into a masked array.
343
+ offset_trf = offset_trf.get_affine()
344
+
345
+ if isinstance(offsets, np.ma.MaskedArray):
346
+ offsets = offsets.filled(np.nan)
347
+ # Changing from a masked array to nan-filled ndarray
348
+ # is probably most efficient at this point.
349
+
350
+ return transform, offset_trf, offsets, paths
351
+
352
+ @artist.allow_rasterization
353
+ def draw(self, renderer):
354
+ if not self.get_visible():
355
+ return
356
+ renderer.open_group(self.__class__.__name__, self.get_gid())
357
+
358
+ self.update_scalarmappable()
359
+
360
+ transform, offset_trf, offsets, paths = self._prepare_points()
361
+
362
+ gc = renderer.new_gc()
363
+ self._set_gc_clip(gc)
364
+ gc.set_snap(self.get_snap())
365
+
366
+ if self._hatch:
367
+ gc.set_hatch(self._hatch)
368
+ gc.set_hatch_color(self._hatch_color)
369
+ gc.set_hatch_linewidth(self._hatch_linewidth)
370
+
371
+ if self.get_sketch_params() is not None:
372
+ gc.set_sketch_params(*self.get_sketch_params())
373
+
374
+ if self.get_path_effects():
375
+ from matplotlib.patheffects import PathEffectRenderer
376
+ renderer = PathEffectRenderer(self.get_path_effects(), renderer)
377
+
378
+ # If the collection is made up of a single shape/color/stroke,
379
+ # it can be rendered once and blitted multiple times, using
380
+ # `draw_markers` rather than `draw_path_collection`. This is
381
+ # *much* faster for Agg, and results in smaller file sizes in
382
+ # PDF/SVG/PS.
383
+
384
+ trans = self.get_transforms()
385
+ facecolors = self.get_facecolor()
386
+ edgecolors = self.get_edgecolor()
387
+ do_single_path_optimization = False
388
+ if (len(paths) == 1 and len(trans) <= 1 and
389
+ len(facecolors) == 1 and len(edgecolors) == 1 and
390
+ len(self._linewidths) == 1 and
391
+ all(ls[1] is None for ls in self._linestyles) and
392
+ len(self._antialiaseds) == 1 and len(self._urls) == 1 and
393
+ self.get_hatch() is None):
394
+ if len(trans):
395
+ combined_transform = transforms.Affine2D(trans[0]) + transform
396
+ else:
397
+ combined_transform = transform
398
+ extents = paths[0].get_extents(combined_transform)
399
+ if (extents.width < self.get_figure(root=True).bbox.width
400
+ and extents.height < self.get_figure(root=True).bbox.height):
401
+ do_single_path_optimization = True
402
+
403
+ if self._joinstyle:
404
+ gc.set_joinstyle(self._joinstyle)
405
+
406
+ if self._capstyle:
407
+ gc.set_capstyle(self._capstyle)
408
+
409
+ if do_single_path_optimization:
410
+ gc.set_foreground(tuple(edgecolors[0]))
411
+ gc.set_linewidth(self._linewidths[0])
412
+ gc.set_dashes(*self._linestyles[0])
413
+ gc.set_antialiased(self._antialiaseds[0])
414
+ gc.set_url(self._urls[0])
415
+ renderer.draw_markers(
416
+ gc, paths[0], combined_transform.frozen(),
417
+ mpath.Path(offsets), offset_trf, tuple(facecolors[0]))
418
+ else:
419
+ if self._gapcolor is not None:
420
+ # First draw paths within the gaps.
421
+ ipaths, ilinestyles = self._get_inverse_paths_linestyles()
422
+ renderer.draw_path_collection(
423
+ gc, transform.frozen(), ipaths,
424
+ self.get_transforms(), offsets, offset_trf,
425
+ [mcolors.to_rgba("none")], self._gapcolor,
426
+ self._linewidths, ilinestyles,
427
+ self._antialiaseds, self._urls,
428
+ "screen")
429
+
430
+ renderer.draw_path_collection(
431
+ gc, transform.frozen(), paths,
432
+ self.get_transforms(), offsets, offset_trf,
433
+ self.get_facecolor(), self.get_edgecolor(),
434
+ self._linewidths, self._linestyles,
435
+ self._antialiaseds, self._urls,
436
+ "screen") # offset_position, kept for backcompat.
437
+
438
+ gc.restore()
439
+ renderer.close_group(self.__class__.__name__)
440
+ self.stale = False
441
+
442
+ def set_pickradius(self, pickradius):
443
+ """
444
+ Set the pick radius used for containment tests.
445
+
446
+ Parameters
447
+ ----------
448
+ pickradius : float
449
+ Pick radius, in points.
450
+ """
451
+ if not isinstance(pickradius, Real):
452
+ raise ValueError(
453
+ f"pickradius must be a real-valued number, not {pickradius!r}")
454
+ self._pickradius = pickradius
455
+
456
+ def get_pickradius(self):
457
+ return self._pickradius
458
+
459
+ def contains(self, mouseevent):
460
+ """
461
+ Test whether the mouse event occurred in the collection.
462
+
463
+ Returns ``bool, dict(ind=itemlist)``, where every item in itemlist
464
+ contains the event.
465
+ """
466
+ if self._different_canvas(mouseevent) or not self.get_visible():
467
+ return False, {}
468
+ pickradius = (
469
+ float(self._picker)
470
+ if isinstance(self._picker, Number) and
471
+ self._picker is not True # the bool, not just nonzero or 1
472
+ else self._pickradius)
473
+ if self.axes:
474
+ self.axes._unstale_viewLim()
475
+ transform, offset_trf, offsets, paths = self._prepare_points()
476
+ # Tests if the point is contained on one of the polygons formed
477
+ # by the control points of each of the paths. A point is considered
478
+ # "on" a path if it would lie within a stroke of width 2*pickradius
479
+ # following the path. If pickradius <= 0, then we instead simply check
480
+ # if the point is *inside* of the path instead.
481
+ ind = _path.point_in_path_collection(
482
+ mouseevent.x, mouseevent.y, pickradius,
483
+ transform.frozen(), paths, self.get_transforms(),
484
+ offsets, offset_trf, pickradius <= 0)
485
+ return len(ind) > 0, dict(ind=ind)
486
+
487
+ def set_urls(self, urls):
488
+ """
489
+ Parameters
490
+ ----------
491
+ urls : list of str or None
492
+
493
+ Notes
494
+ -----
495
+ URLs are currently only implemented by the SVG backend. They are
496
+ ignored by all other backends.
497
+ """
498
+ self._urls = urls if urls is not None else [None]
499
+ self.stale = True
500
+
501
+ def get_urls(self):
502
+ """
503
+ Return a list of URLs, one for each element of the collection.
504
+
505
+ The list contains *None* for elements without a URL. See
506
+ :doc:`/gallery/misc/hyperlinks_sgskip` for an example.
507
+ """
508
+ return self._urls
509
+
510
+ def set_hatch(self, hatch):
511
+ r"""
512
+ Set the hatching pattern
513
+
514
+ *hatch* can be one of::
515
+
516
+ / - diagonal hatching
517
+ \ - back diagonal
518
+ | - vertical
519
+ - - horizontal
520
+ + - crossed
521
+ x - crossed diagonal
522
+ o - small circle
523
+ O - large circle
524
+ . - dots
525
+ * - stars
526
+
527
+ Letters can be combined, in which case all the specified
528
+ hatchings are done. If same letter repeats, it increases the
529
+ density of hatching of that pattern.
530
+
531
+ Unlike other properties such as linewidth and colors, hatching
532
+ can only be specified for the collection as a whole, not separately
533
+ for each member.
534
+
535
+ Parameters
536
+ ----------
537
+ hatch : {'/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*'}
538
+ """
539
+ # Use validate_hatch(list) after deprecation.
540
+ mhatch._validate_hatch_pattern(hatch)
541
+ self._hatch = hatch
542
+ self.stale = True
543
+
544
+ def get_hatch(self):
545
+ """Return the current hatching pattern."""
546
+ return self._hatch
547
+
548
+ def set_hatch_linewidth(self, lw):
549
+ """Set the hatch linewidth."""
550
+ self._hatch_linewidth = lw
551
+
552
+ def get_hatch_linewidth(self):
553
+ """Return the hatch linewidth."""
554
+ return self._hatch_linewidth
555
+
556
+ def set_offsets(self, offsets):
557
+ """
558
+ Set the offsets for the collection.
559
+
560
+ Parameters
561
+ ----------
562
+ offsets : (N, 2) or (2,) array-like
563
+ """
564
+ offsets = np.asanyarray(offsets)
565
+ if offsets.shape == (2,): # Broadcast (2,) -> (1, 2) but nothing else.
566
+ offsets = offsets[None, :]
567
+ cstack = (np.ma.column_stack if isinstance(offsets, np.ma.MaskedArray)
568
+ else np.column_stack)
569
+ self._offsets = cstack(
570
+ (np.asanyarray(self.convert_xunits(offsets[:, 0]), float),
571
+ np.asanyarray(self.convert_yunits(offsets[:, 1]), float)))
572
+ self.stale = True
573
+
574
+ def get_offsets(self):
575
+ """Return the offsets for the collection."""
576
+ # Default to zeros in the no-offset (None) case
577
+ return np.zeros((1, 2)) if self._offsets is None else self._offsets
578
+
579
+ def _get_default_linewidth(self):
580
+ # This may be overridden in a subclass.
581
+ return mpl.rcParams['patch.linewidth'] # validated as float
582
+
583
+ def set_linewidth(self, lw):
584
+ """
585
+ Set the linewidth(s) for the collection. *lw* can be a scalar
586
+ or a sequence; if it is a sequence the patches will cycle
587
+ through the sequence
588
+
589
+ Parameters
590
+ ----------
591
+ lw : float or list of floats
592
+ """
593
+ if lw is None:
594
+ lw = self._get_default_linewidth()
595
+ # get the un-scaled/broadcast lw
596
+ self._us_lw = np.atleast_1d(lw)
597
+
598
+ # scale all of the dash patterns.
599
+ self._linewidths, self._linestyles = self._bcast_lwls(
600
+ self._us_lw, self._us_linestyles)
601
+ self.stale = True
602
+
603
+ def set_linestyle(self, ls):
604
+ """
605
+ Set the linestyle(s) for the collection.
606
+
607
+ =========================== =================
608
+ linestyle description
609
+ =========================== =================
610
+ ``'-'`` or ``'solid'`` solid line
611
+ ``'--'`` or ``'dashed'`` dashed line
612
+ ``'-.'`` or ``'dashdot'`` dash-dotted line
613
+ ``':'`` or ``'dotted'`` dotted line
614
+ =========================== =================
615
+
616
+ Alternatively a dash tuple of the following form can be provided::
617
+
618
+ (offset, onoffseq),
619
+
620
+ where ``onoffseq`` is an even length tuple of on and off ink in points.
621
+
622
+ Parameters
623
+ ----------
624
+ ls : str or tuple or list thereof
625
+ Valid values for individual linestyles include {'-', '--', '-.',
626
+ ':', '', (offset, on-off-seq)}. See `.Line2D.set_linestyle` for a
627
+ complete description.
628
+ """
629
+ try:
630
+ dashes = [mlines._get_dash_pattern(ls)]
631
+ except ValueError:
632
+ try:
633
+ dashes = [mlines._get_dash_pattern(x) for x in ls]
634
+ except ValueError as err:
635
+ emsg = f'Do not know how to convert {ls!r} to dashes'
636
+ raise ValueError(emsg) from err
637
+
638
+ # get the list of raw 'unscaled' dash patterns
639
+ self._us_linestyles = dashes
640
+
641
+ # broadcast and scale the lw and dash patterns
642
+ self._linewidths, self._linestyles = self._bcast_lwls(
643
+ self._us_lw, self._us_linestyles)
644
+
645
+ @_docstring.interpd
646
+ def set_capstyle(self, cs):
647
+ """
648
+ Set the `.CapStyle` for the collection (for all its elements).
649
+
650
+ Parameters
651
+ ----------
652
+ cs : `.CapStyle` or %(CapStyle)s
653
+ """
654
+ self._capstyle = CapStyle(cs)
655
+
656
+ @_docstring.interpd
657
+ def get_capstyle(self):
658
+ """
659
+ Return the cap style for the collection (for all its elements).
660
+
661
+ Returns
662
+ -------
663
+ %(CapStyle)s or None
664
+ """
665
+ return self._capstyle.name if self._capstyle else None
666
+
667
+ @_docstring.interpd
668
+ def set_joinstyle(self, js):
669
+ """
670
+ Set the `.JoinStyle` for the collection (for all its elements).
671
+
672
+ Parameters
673
+ ----------
674
+ js : `.JoinStyle` or %(JoinStyle)s
675
+ """
676
+ self._joinstyle = JoinStyle(js)
677
+
678
+ @_docstring.interpd
679
+ def get_joinstyle(self):
680
+ """
681
+ Return the join style for the collection (for all its elements).
682
+
683
+ Returns
684
+ -------
685
+ %(JoinStyle)s or None
686
+ """
687
+ return self._joinstyle.name if self._joinstyle else None
688
+
689
+ @staticmethod
690
+ def _bcast_lwls(linewidths, dashes):
691
+ """
692
+ Internal helper function to broadcast + scale ls/lw
693
+
694
+ In the collection drawing code, the linewidth and linestyle are cycled
695
+ through as circular buffers (via ``v[i % len(v)]``). Thus, if we are
696
+ going to scale the dash pattern at set time (not draw time) we need to
697
+ do the broadcasting now and expand both lists to be the same length.
698
+
699
+ Parameters
700
+ ----------
701
+ linewidths : list
702
+ line widths of collection
703
+ dashes : list
704
+ dash specification (offset, (dash pattern tuple))
705
+
706
+ Returns
707
+ -------
708
+ linewidths, dashes : list
709
+ Will be the same length, dashes are scaled by paired linewidth
710
+ """
711
+ if mpl.rcParams['_internal.classic_mode']:
712
+ return linewidths, dashes
713
+ # make sure they are the same length so we can zip them
714
+ if len(dashes) != len(linewidths):
715
+ l_dashes = len(dashes)
716
+ l_lw = len(linewidths)
717
+ gcd = math.gcd(l_dashes, l_lw)
718
+ dashes = list(dashes) * (l_lw // gcd)
719
+ linewidths = list(linewidths) * (l_dashes // gcd)
720
+
721
+ # scale the dash patterns
722
+ dashes = [mlines._scale_dashes(o, d, lw)
723
+ for (o, d), lw in zip(dashes, linewidths)]
724
+
725
+ return linewidths, dashes
726
+
727
+ def get_antialiased(self):
728
+ """
729
+ Get the antialiasing state for rendering.
730
+
731
+ Returns
732
+ -------
733
+ array of bools
734
+ """
735
+ return self._antialiaseds
736
+
737
+ def set_antialiased(self, aa):
738
+ """
739
+ Set the antialiasing state for rendering.
740
+
741
+ Parameters
742
+ ----------
743
+ aa : bool or list of bools
744
+ """
745
+ if aa is None:
746
+ aa = self._get_default_antialiased()
747
+ self._antialiaseds = np.atleast_1d(np.asarray(aa, bool))
748
+ self.stale = True
749
+
750
+ def _get_default_antialiased(self):
751
+ # This may be overridden in a subclass.
752
+ return mpl.rcParams['patch.antialiased']
753
+
754
+ def set_color(self, c):
755
+ """
756
+ Set both the edgecolor and the facecolor.
757
+
758
+ Parameters
759
+ ----------
760
+ c : :mpltype:`color` or list of RGBA tuples
761
+
762
+ See Also
763
+ --------
764
+ Collection.set_facecolor, Collection.set_edgecolor
765
+ For setting the edge or face color individually.
766
+ """
767
+ self.set_facecolor(c)
768
+ self.set_edgecolor(c)
769
+
770
+ def _get_default_facecolor(self):
771
+ # This may be overridden in a subclass.
772
+ return mpl.rcParams['patch.facecolor']
773
+
774
+ def _set_facecolor(self, c):
775
+ if c is None:
776
+ c = self._get_default_facecolor()
777
+
778
+ self._facecolors = mcolors.to_rgba_array(c, self._alpha)
779
+ self.stale = True
780
+
781
+ def set_facecolor(self, c):
782
+ """
783
+ Set the facecolor(s) of the collection. *c* can be a color (all patches
784
+ have same color), or a sequence of colors; if it is a sequence the
785
+ patches will cycle through the sequence.
786
+
787
+ If *c* is 'none', the patch will not be filled.
788
+
789
+ Parameters
790
+ ----------
791
+ c : :mpltype:`color` or list of :mpltype:`color`
792
+ """
793
+ if isinstance(c, str) and c.lower() in ("none", "face"):
794
+ c = c.lower()
795
+ self._original_facecolor = c
796
+ self._set_facecolor(c)
797
+
798
+ def get_facecolor(self):
799
+ return self._facecolors
800
+
801
+ def get_edgecolor(self):
802
+ if cbook._str_equal(self._edgecolors, 'face'):
803
+ return self.get_facecolor()
804
+ else:
805
+ return self._edgecolors
806
+
807
+ def _get_default_edgecolor(self):
808
+ # This may be overridden in a subclass.
809
+ return mpl.rcParams['patch.edgecolor']
810
+
811
+ def _set_edgecolor(self, c):
812
+ set_hatch_color = True
813
+ if c is None:
814
+ if (mpl.rcParams['patch.force_edgecolor']
815
+ or self._edge_default
816
+ or cbook._str_equal(self._original_facecolor, 'none')):
817
+ c = self._get_default_edgecolor()
818
+ else:
819
+ c = 'none'
820
+ set_hatch_color = False
821
+ if cbook._str_lower_equal(c, 'face'):
822
+ self._edgecolors = 'face'
823
+ self.stale = True
824
+ return
825
+ self._edgecolors = mcolors.to_rgba_array(c, self._alpha)
826
+ if set_hatch_color and len(self._edgecolors):
827
+ self._hatch_color = tuple(self._edgecolors[0])
828
+ self.stale = True
829
+
830
+ def set_edgecolor(self, c):
831
+ """
832
+ Set the edgecolor(s) of the collection.
833
+
834
+ Parameters
835
+ ----------
836
+ c : :mpltype:`color` or list of :mpltype:`color` or 'face'
837
+ The collection edgecolor(s). If a sequence, the patches cycle
838
+ through it. If 'face', match the facecolor.
839
+ """
840
+ # We pass through a default value for use in LineCollection.
841
+ # This allows us to maintain None as the default indicator in
842
+ # _original_edgecolor.
843
+ if isinstance(c, str) and c.lower() in ("none", "face"):
844
+ c = c.lower()
845
+ self._original_edgecolor = c
846
+ self._set_edgecolor(c)
847
+
848
+ def set_alpha(self, alpha):
849
+ """
850
+ Set the transparency of the collection.
851
+
852
+ Parameters
853
+ ----------
854
+ alpha : float or array of float or None
855
+ If not None, *alpha* values must be between 0 and 1, inclusive.
856
+ If an array is provided, its length must match the number of
857
+ elements in the collection. Masked values and nans are not
858
+ supported.
859
+ """
860
+ artist.Artist._set_alpha_for_array(self, alpha)
861
+ self._set_facecolor(self._original_facecolor)
862
+ self._set_edgecolor(self._original_edgecolor)
863
+
864
+ set_alpha.__doc__ = artist.Artist._set_alpha_for_array.__doc__
865
+
866
+ def get_linewidth(self):
867
+ return self._linewidths
868
+
869
+ def get_linestyle(self):
870
+ return self._linestyles
871
+
872
+ def _set_mappable_flags(self):
873
+ """
874
+ Determine whether edges and/or faces are color-mapped.
875
+
876
+ This is a helper for update_scalarmappable.
877
+ It sets Boolean flags '_edge_is_mapped' and '_face_is_mapped'.
878
+
879
+ Returns
880
+ -------
881
+ mapping_change : bool
882
+ True if either flag is True, or if a flag has changed.
883
+ """
884
+ # The flags are initialized to None to ensure this returns True
885
+ # the first time it is called.
886
+ edge0 = self._edge_is_mapped
887
+ face0 = self._face_is_mapped
888
+ # After returning, the flags must be Booleans, not None.
889
+ self._edge_is_mapped = False
890
+ self._face_is_mapped = False
891
+ if self._A is not None:
892
+ if not cbook._str_equal(self._original_facecolor, 'none'):
893
+ self._face_is_mapped = True
894
+ if cbook._str_equal(self._original_edgecolor, 'face'):
895
+ self._edge_is_mapped = True
896
+ else:
897
+ if self._original_edgecolor is None:
898
+ self._edge_is_mapped = True
899
+
900
+ mapped = self._face_is_mapped or self._edge_is_mapped
901
+ changed = (edge0 is None or face0 is None
902
+ or self._edge_is_mapped != edge0
903
+ or self._face_is_mapped != face0)
904
+ return mapped or changed
905
+
906
+ def update_scalarmappable(self):
907
+ """
908
+ Update colors from the scalar mappable array, if any.
909
+
910
+ Assign colors to edges and faces based on the array and/or
911
+ colors that were directly set, as appropriate.
912
+ """
913
+ if not self._set_mappable_flags():
914
+ return
915
+ # Allow possibility to call 'self.set_array(None)'.
916
+ if self._A is not None:
917
+ # QuadMesh can map 2d arrays (but pcolormesh supplies 1d array)
918
+ if self._A.ndim > 1 and not isinstance(self, _MeshData):
919
+ raise ValueError('Collections can only map rank 1 arrays')
920
+ if np.iterable(self._alpha):
921
+ if self._alpha.size != self._A.size:
922
+ raise ValueError(
923
+ f'Data array shape, {self._A.shape} '
924
+ 'is incompatible with alpha array shape, '
925
+ f'{self._alpha.shape}. '
926
+ 'This can occur with the deprecated '
927
+ 'behavior of the "flat" shading option, '
928
+ 'in which a row and/or column of the data '
929
+ 'array is dropped.')
930
+ # pcolormesh, scatter, maybe others flatten their _A
931
+ self._alpha = self._alpha.reshape(self._A.shape)
932
+ self._mapped_colors = self.to_rgba(self._A, self._alpha)
933
+
934
+ if self._face_is_mapped:
935
+ self._facecolors = self._mapped_colors
936
+ else:
937
+ self._set_facecolor(self._original_facecolor)
938
+ if self._edge_is_mapped:
939
+ self._edgecolors = self._mapped_colors
940
+ else:
941
+ self._set_edgecolor(self._original_edgecolor)
942
+ self.stale = True
943
+
944
+ def get_fill(self):
945
+ """Return whether face is colored."""
946
+ return not cbook._str_lower_equal(self._original_facecolor, "none")
947
+
948
+ def update_from(self, other):
949
+ """Copy properties from other to self."""
950
+
951
+ artist.Artist.update_from(self, other)
952
+ self._antialiaseds = other._antialiaseds
953
+ self._mapped_colors = other._mapped_colors
954
+ self._edge_is_mapped = other._edge_is_mapped
955
+ self._original_edgecolor = other._original_edgecolor
956
+ self._edgecolors = other._edgecolors
957
+ self._face_is_mapped = other._face_is_mapped
958
+ self._original_facecolor = other._original_facecolor
959
+ self._facecolors = other._facecolors
960
+ self._linewidths = other._linewidths
961
+ self._linestyles = other._linestyles
962
+ self._us_linestyles = other._us_linestyles
963
+ self._pickradius = other._pickradius
964
+ self._hatch = other._hatch
965
+
966
+ # update_from for scalarmappable
967
+ self._A = other._A
968
+ self.norm = other.norm
969
+ self.cmap = other.cmap
970
+ self.stale = True
971
+
972
+
973
+ class _CollectionWithSizes(Collection):
974
+ """
975
+ Base class for collections that have an array of sizes.
976
+ """
977
+ _factor = 1.0
978
+
979
+ def get_sizes(self):
980
+ """
981
+ Return the sizes ('areas') of the elements in the collection.
982
+
983
+ Returns
984
+ -------
985
+ array
986
+ The 'area' of each element.
987
+ """
988
+ return self._sizes
989
+
990
+ def set_sizes(self, sizes, dpi=72.0):
991
+ """
992
+ Set the sizes of each member of the collection.
993
+
994
+ Parameters
995
+ ----------
996
+ sizes : `numpy.ndarray` or None
997
+ The size to set for each element of the collection. The
998
+ value is the 'area' of the element.
999
+ dpi : float, default: 72
1000
+ The dpi of the canvas.
1001
+ """
1002
+ if sizes is None:
1003
+ self._sizes = np.array([])
1004
+ self._transforms = np.empty((0, 3, 3))
1005
+ else:
1006
+ self._sizes = np.asarray(sizes)
1007
+ self._transforms = np.zeros((len(self._sizes), 3, 3))
1008
+ scale = np.sqrt(self._sizes) * dpi / 72.0 * self._factor
1009
+ self._transforms[:, 0, 0] = scale
1010
+ self._transforms[:, 1, 1] = scale
1011
+ self._transforms[:, 2, 2] = 1.0
1012
+ self.stale = True
1013
+
1014
+ @artist.allow_rasterization
1015
+ def draw(self, renderer):
1016
+ self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
1017
+ super().draw(renderer)
1018
+
1019
+
1020
+ class PathCollection(_CollectionWithSizes):
1021
+ r"""
1022
+ A collection of `~.path.Path`\s, as created by e.g. `~.Axes.scatter`.
1023
+ """
1024
+
1025
+ def __init__(self, paths, sizes=None, **kwargs):
1026
+ """
1027
+ Parameters
1028
+ ----------
1029
+ paths : list of `.path.Path`
1030
+ The paths that will make up the `.Collection`.
1031
+ sizes : array-like
1032
+ The factor by which to scale each drawn `~.path.Path`. One unit
1033
+ squared in the Path's data space is scaled to be ``sizes**2``
1034
+ points when rendered.
1035
+ **kwargs
1036
+ Forwarded to `.Collection`.
1037
+ """
1038
+
1039
+ super().__init__(**kwargs)
1040
+ self.set_paths(paths)
1041
+ self.set_sizes(sizes)
1042
+ self.stale = True
1043
+
1044
+ def get_paths(self):
1045
+ return self._paths
1046
+
1047
+ def legend_elements(self, prop="colors", num="auto",
1048
+ fmt=None, func=lambda x: x, **kwargs):
1049
+ """
1050
+ Create legend handles and labels for a PathCollection.
1051
+
1052
+ Each legend handle is a `.Line2D` representing the Path that was drawn,
1053
+ and each label is a string that represents the Path.
1054
+
1055
+ This is useful for obtaining a legend for a `~.Axes.scatter` plot;
1056
+ e.g.::
1057
+
1058
+ scatter = plt.scatter([1, 2, 3], [4, 5, 6], c=[7, 2, 3], num=None)
1059
+ plt.legend(*scatter.legend_elements())
1060
+
1061
+ creates three legend elements, one for each color with the numerical
1062
+ values passed to *c* as the labels.
1063
+
1064
+ Also see the :ref:`automatedlegendcreation` example.
1065
+
1066
+ Parameters
1067
+ ----------
1068
+ prop : {"colors", "sizes"}, default: "colors"
1069
+ If "colors", the legend handles will show the different colors of
1070
+ the collection. If "sizes", the legend will show the different
1071
+ sizes. To set both, use *kwargs* to directly edit the `.Line2D`
1072
+ properties.
1073
+ num : int, None, "auto" (default), array-like, or `~.ticker.Locator`
1074
+ Target number of elements to create.
1075
+ If None, use all unique elements of the mappable array. If an
1076
+ integer, target to use *num* elements in the normed range.
1077
+ If *"auto"*, try to determine which option better suits the nature
1078
+ of the data.
1079
+ The number of created elements may slightly deviate from *num* due
1080
+ to a `~.ticker.Locator` being used to find useful locations.
1081
+ If a list or array, use exactly those elements for the legend.
1082
+ Finally, a `~.ticker.Locator` can be provided.
1083
+ fmt : str, `~matplotlib.ticker.Formatter`, or None (default)
1084
+ The format or formatter to use for the labels. If a string must be
1085
+ a valid input for a `.StrMethodFormatter`. If None (the default),
1086
+ use a `.ScalarFormatter`.
1087
+ func : function, default: ``lambda x: x``
1088
+ Function to calculate the labels. Often the size (or color)
1089
+ argument to `~.Axes.scatter` will have been pre-processed by the
1090
+ user using a function ``s = f(x)`` to make the markers visible;
1091
+ e.g. ``size = np.log10(x)``. Providing the inverse of this
1092
+ function here allows that pre-processing to be inverted, so that
1093
+ the legend labels have the correct values; e.g. ``func = lambda
1094
+ x: 10**x``.
1095
+ **kwargs
1096
+ Allowed keyword arguments are *color* and *size*. E.g. it may be
1097
+ useful to set the color of the markers if *prop="sizes"* is used;
1098
+ similarly to set the size of the markers if *prop="colors"* is
1099
+ used. Any further parameters are passed onto the `.Line2D`
1100
+ instance. This may be useful to e.g. specify a different
1101
+ *markeredgecolor* or *alpha* for the legend handles.
1102
+
1103
+ Returns
1104
+ -------
1105
+ handles : list of `.Line2D`
1106
+ Visual representation of each element of the legend.
1107
+ labels : list of str
1108
+ The string labels for elements of the legend.
1109
+ """
1110
+ handles = []
1111
+ labels = []
1112
+ hasarray = self.get_array() is not None
1113
+ if fmt is None:
1114
+ fmt = mpl.ticker.ScalarFormatter(useOffset=False, useMathText=True)
1115
+ elif isinstance(fmt, str):
1116
+ fmt = mpl.ticker.StrMethodFormatter(fmt)
1117
+ fmt.create_dummy_axis()
1118
+
1119
+ if prop == "colors":
1120
+ if not hasarray:
1121
+ warnings.warn("Collection without array used. Make sure to "
1122
+ "specify the values to be colormapped via the "
1123
+ "`c` argument.")
1124
+ return handles, labels
1125
+ u = np.unique(self.get_array())
1126
+ size = kwargs.pop("size", mpl.rcParams["lines.markersize"])
1127
+ elif prop == "sizes":
1128
+ u = np.unique(self.get_sizes())
1129
+ color = kwargs.pop("color", "k")
1130
+ else:
1131
+ raise ValueError("Valid values for `prop` are 'colors' or "
1132
+ f"'sizes'. You supplied '{prop}' instead.")
1133
+
1134
+ fu = func(u)
1135
+ fmt.axis.set_view_interval(fu.min(), fu.max())
1136
+ fmt.axis.set_data_interval(fu.min(), fu.max())
1137
+ if num == "auto":
1138
+ num = 9
1139
+ if len(u) <= num:
1140
+ num = None
1141
+ if num is None:
1142
+ values = u
1143
+ label_values = func(values)
1144
+ else:
1145
+ if prop == "colors":
1146
+ arr = self.get_array()
1147
+ elif prop == "sizes":
1148
+ arr = self.get_sizes()
1149
+ if isinstance(num, mpl.ticker.Locator):
1150
+ loc = num
1151
+ elif np.iterable(num):
1152
+ loc = mpl.ticker.FixedLocator(num)
1153
+ else:
1154
+ num = int(num)
1155
+ loc = mpl.ticker.MaxNLocator(nbins=num, min_n_ticks=num-1,
1156
+ steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
1157
+ label_values = loc.tick_values(func(arr).min(), func(arr).max())
1158
+ cond = ((label_values >= func(arr).min()) &
1159
+ (label_values <= func(arr).max()))
1160
+ label_values = label_values[cond]
1161
+ yarr = np.linspace(arr.min(), arr.max(), 256)
1162
+ xarr = func(yarr)
1163
+ ix = np.argsort(xarr)
1164
+ values = np.interp(label_values, xarr[ix], yarr[ix])
1165
+
1166
+ kw = {"markeredgewidth": self.get_linewidths()[0],
1167
+ "alpha": self.get_alpha(),
1168
+ **kwargs}
1169
+
1170
+ for val, lab in zip(values, label_values):
1171
+ if prop == "colors":
1172
+ color = self.cmap(self.norm(val))
1173
+ elif prop == "sizes":
1174
+ size = np.sqrt(val)
1175
+ if np.isclose(size, 0.0):
1176
+ continue
1177
+ h = mlines.Line2D([0], [0], ls="", color=color, ms=size,
1178
+ marker=self.get_paths()[0], **kw)
1179
+ handles.append(h)
1180
+ if hasattr(fmt, "set_locs"):
1181
+ fmt.set_locs(label_values)
1182
+ l = fmt(lab)
1183
+ labels.append(l)
1184
+
1185
+ return handles, labels
1186
+
1187
+
1188
+ class PolyCollection(_CollectionWithSizes):
1189
+
1190
+ def __init__(self, verts, sizes=None, *, closed=True, **kwargs):
1191
+ """
1192
+ Parameters
1193
+ ----------
1194
+ verts : list of array-like
1195
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
1196
+ element *verts_i* defines the vertices of polygon *i* as a 2D
1197
+ array-like of shape (M, 2).
1198
+ sizes : array-like, default: None
1199
+ Squared scaling factors for the polygons. The coordinates of each
1200
+ polygon *verts_i* are multiplied by the square-root of the
1201
+ corresponding entry in *sizes* (i.e., *sizes* specify the scaling
1202
+ of areas). The scaling is applied before the Artist master
1203
+ transform.
1204
+ closed : bool, default: True
1205
+ Whether the polygon should be closed by adding a CLOSEPOLY
1206
+ connection at the end.
1207
+ **kwargs
1208
+ Forwarded to `.Collection`.
1209
+ """
1210
+ super().__init__(**kwargs)
1211
+ self.set_sizes(sizes)
1212
+ self.set_verts(verts, closed)
1213
+ self.stale = True
1214
+
1215
+ def set_verts(self, verts, closed=True):
1216
+ """
1217
+ Set the vertices of the polygons.
1218
+
1219
+ Parameters
1220
+ ----------
1221
+ verts : list of array-like
1222
+ The sequence of polygons [*verts0*, *verts1*, ...] where each
1223
+ element *verts_i* defines the vertices of polygon *i* as a 2D
1224
+ array-like of shape (M, 2).
1225
+ closed : bool, default: True
1226
+ Whether the polygon should be closed by adding a CLOSEPOLY
1227
+ connection at the end.
1228
+ """
1229
+ self.stale = True
1230
+ if isinstance(verts, np.ma.MaskedArray):
1231
+ verts = verts.astype(float).filled(np.nan)
1232
+
1233
+ # No need to do anything fancy if the path isn't closed.
1234
+ if not closed:
1235
+ self._paths = [mpath.Path(xy) for xy in verts]
1236
+ return
1237
+
1238
+ # Fast path for arrays
1239
+ if isinstance(verts, np.ndarray) and len(verts.shape) == 3:
1240
+ verts_pad = np.concatenate((verts, verts[:, :1]), axis=1)
1241
+ # Creating the codes once is much faster than having Path do it
1242
+ # separately each time by passing closed=True.
1243
+ codes = np.empty(verts_pad.shape[1], dtype=mpath.Path.code_type)
1244
+ codes[:] = mpath.Path.LINETO
1245
+ codes[0] = mpath.Path.MOVETO
1246
+ codes[-1] = mpath.Path.CLOSEPOLY
1247
+ self._paths = [mpath.Path(xy, codes) for xy in verts_pad]
1248
+ return
1249
+
1250
+ self._paths = []
1251
+ for xy in verts:
1252
+ if len(xy):
1253
+ self._paths.append(mpath.Path._create_closed(xy))
1254
+ else:
1255
+ self._paths.append(mpath.Path(xy))
1256
+
1257
+ set_paths = set_verts
1258
+
1259
+ def set_verts_and_codes(self, verts, codes):
1260
+ """Initialize vertices with path codes."""
1261
+ if len(verts) != len(codes):
1262
+ raise ValueError("'codes' must be a 1D list or array "
1263
+ "with the same length of 'verts'")
1264
+ self._paths = [mpath.Path(xy, cds) if len(xy) else mpath.Path(xy)
1265
+ for xy, cds in zip(verts, codes)]
1266
+ self.stale = True
1267
+
1268
+
1269
+ class FillBetweenPolyCollection(PolyCollection):
1270
+ """
1271
+ `.PolyCollection` that fills the area between two x- or y-curves.
1272
+ """
1273
+ def __init__(
1274
+ self, t_direction, t, f1, f2, *,
1275
+ where=None, interpolate=False, step=None, **kwargs):
1276
+ """
1277
+ Parameters
1278
+ ----------
1279
+ t_direction : {{'x', 'y'}}
1280
+ The axes on which the variable lies.
1281
+
1282
+ - 'x': the curves are ``(t, f1)`` and ``(t, f2)``.
1283
+ - 'y': the curves are ``(f1, t)`` and ``(f2, t)``.
1284
+
1285
+ t : array (length N)
1286
+ The ``t_direction`` coordinates of the nodes defining the curves.
1287
+
1288
+ f1 : array (length N) or scalar
1289
+ The other coordinates of the nodes defining the first curve.
1290
+
1291
+ f2 : array (length N) or scalar
1292
+ The other coordinates of the nodes defining the second curve.
1293
+
1294
+ where : array of bool (length N), optional
1295
+ Define *where* to exclude some {dir} regions from being filled.
1296
+ The filled regions are defined by the coordinates ``t[where]``.
1297
+ More precisely, fill between ``t[i]`` and ``t[i+1]`` if
1298
+ ``where[i] and where[i+1]``. Note that this definition implies
1299
+ that an isolated *True* value between two *False* values in *where*
1300
+ will not result in filling. Both sides of the *True* position
1301
+ remain unfilled due to the adjacent *False* values.
1302
+
1303
+ interpolate : bool, default: False
1304
+ This option is only relevant if *where* is used and the two curves
1305
+ are crossing each other.
1306
+
1307
+ Semantically, *where* is often used for *f1* > *f2* or
1308
+ similar. By default, the nodes of the polygon defining the filled
1309
+ region will only be placed at the positions in the *t* array.
1310
+ Such a polygon cannot describe the above semantics close to the
1311
+ intersection. The t-sections containing the intersection are
1312
+ simply clipped.
1313
+
1314
+ Setting *interpolate* to *True* will calculate the actual
1315
+ intersection point and extend the filled region up to this point.
1316
+
1317
+ step : {{'pre', 'post', 'mid'}}, optional
1318
+ Define *step* if the filling should be a step function,
1319
+ i.e. constant in between *t*. The value determines where the
1320
+ step will occur:
1321
+
1322
+ - 'pre': The f value is continued constantly to the left from
1323
+ every *t* position, i.e. the interval ``(t[i-1], t[i]]`` has the
1324
+ value ``f[i]``.
1325
+ - 'post': The y value is continued constantly to the right from
1326
+ every *x* position, i.e. the interval ``[t[i], t[i+1])`` has the
1327
+ value ``f[i]``.
1328
+ - 'mid': Steps occur half-way between the *t* positions.
1329
+
1330
+ **kwargs
1331
+ Forwarded to `.PolyCollection`.
1332
+
1333
+ See Also
1334
+ --------
1335
+ .Axes.fill_between, .Axes.fill_betweenx
1336
+ """
1337
+ self.t_direction = t_direction
1338
+ self._interpolate = interpolate
1339
+ self._step = step
1340
+ verts = self._make_verts(t, f1, f2, where)
1341
+ super().__init__(verts, **kwargs)
1342
+
1343
+ @staticmethod
1344
+ def _f_dir_from_t(t_direction):
1345
+ """The direction that is other than `t_direction`."""
1346
+ if t_direction == "x":
1347
+ return "y"
1348
+ elif t_direction == "y":
1349
+ return "x"
1350
+ else:
1351
+ msg = f"t_direction must be 'x' or 'y', got {t_direction!r}"
1352
+ raise ValueError(msg)
1353
+
1354
+ @property
1355
+ def _f_direction(self):
1356
+ """The direction that is other than `self.t_direction`."""
1357
+ return self._f_dir_from_t(self.t_direction)
1358
+
1359
+ def set_data(self, t, f1, f2, *, where=None):
1360
+ """
1361
+ Set new values for the two bounding curves.
1362
+
1363
+ Parameters
1364
+ ----------
1365
+ t : array (length N)
1366
+ The ``self.t_direction`` coordinates of the nodes defining the curves.
1367
+
1368
+ f1 : array (length N) or scalar
1369
+ The other coordinates of the nodes defining the first curve.
1370
+
1371
+ f2 : array (length N) or scalar
1372
+ The other coordinates of the nodes defining the second curve.
1373
+
1374
+ where : array of bool (length N), optional
1375
+ Define *where* to exclude some {dir} regions from being filled.
1376
+ The filled regions are defined by the coordinates ``t[where]``.
1377
+ More precisely, fill between ``t[i]`` and ``t[i+1]`` if
1378
+ ``where[i] and where[i+1]``. Note that this definition implies
1379
+ that an isolated *True* value between two *False* values in *where*
1380
+ will not result in filling. Both sides of the *True* position
1381
+ remain unfilled due to the adjacent *False* values.
1382
+
1383
+ See Also
1384
+ --------
1385
+ .PolyCollection.set_verts, .Line2D.set_data
1386
+ """
1387
+ t, f1, f2 = self.axes._fill_between_process_units(
1388
+ self.t_direction, self._f_direction, t, f1, f2)
1389
+
1390
+ verts = self._make_verts(t, f1, f2, where)
1391
+ self.set_verts(verts)
1392
+
1393
+ def get_datalim(self, transData):
1394
+ """Calculate the data limits and return them as a `.Bbox`."""
1395
+ datalim = transforms.Bbox.null()
1396
+ datalim.update_from_data_xy((self.get_transform() - transData).transform(
1397
+ np.concatenate([self._bbox, [self._bbox.minpos]])))
1398
+ return datalim
1399
+
1400
+ def _make_verts(self, t, f1, f2, where):
1401
+ """
1402
+ Make verts that can be forwarded to `.PolyCollection`.
1403
+ """
1404
+ self._validate_shapes(self.t_direction, self._f_direction, t, f1, f2)
1405
+
1406
+ where = self._get_data_mask(t, f1, f2, where)
1407
+ t, f1, f2 = np.broadcast_arrays(np.atleast_1d(t), f1, f2, subok=True)
1408
+
1409
+ self._bbox = transforms.Bbox.null()
1410
+ self._bbox.update_from_data_xy(self._fix_pts_xy_order(np.concatenate([
1411
+ np.stack((t[where], f[where]), axis=-1) for f in (f1, f2)])))
1412
+
1413
+ return [
1414
+ self._make_verts_for_region(t, f1, f2, idx0, idx1)
1415
+ for idx0, idx1 in cbook.contiguous_regions(where)
1416
+ ]
1417
+
1418
+ def _get_data_mask(self, t, f1, f2, where):
1419
+ """
1420
+ Return a bool array, with True at all points that should eventually be rendered.
1421
+
1422
+ The array is True at a point if none of the data inputs
1423
+ *t*, *f1*, *f2* is masked and if the input *where* is true at that point.
1424
+ """
1425
+ if where is None:
1426
+ where = True
1427
+ else:
1428
+ where = np.asarray(where, dtype=bool)
1429
+ if where.size != t.size:
1430
+ msg = "where size ({}) does not match {!r} size ({})".format(
1431
+ where.size, self.t_direction, t.size)
1432
+ raise ValueError(msg)
1433
+ return where & ~functools.reduce(
1434
+ np.logical_or, map(np.ma.getmaskarray, [t, f1, f2]))
1435
+
1436
+ @staticmethod
1437
+ def _validate_shapes(t_dir, f_dir, t, f1, f2):
1438
+ """Validate that t, f1 and f2 are 1-dimensional and have the same length."""
1439
+ names = (d + s for d, s in zip((t_dir, f_dir, f_dir), ("", "1", "2")))
1440
+ for name, array in zip(names, [t, f1, f2]):
1441
+ if array.ndim > 1:
1442
+ raise ValueError(f"{name!r} is not 1-dimensional")
1443
+ if t.size > 1 and array.size > 1 and t.size != array.size:
1444
+ msg = "{!r} has size {}, but {!r} has an unequal size of {}".format(
1445
+ t_dir, t.size, name, array.size)
1446
+ raise ValueError(msg)
1447
+
1448
+ def _make_verts_for_region(self, t, f1, f2, idx0, idx1):
1449
+ """
1450
+ Make ``verts`` for a contiguous region between ``idx0`` and ``idx1``, taking
1451
+ into account ``step`` and ``interpolate``.
1452
+ """
1453
+ t_slice = t[idx0:idx1]
1454
+ f1_slice = f1[idx0:idx1]
1455
+ f2_slice = f2[idx0:idx1]
1456
+ if self._step is not None:
1457
+ step_func = cbook.STEP_LOOKUP_MAP["steps-" + self._step]
1458
+ t_slice, f1_slice, f2_slice = step_func(t_slice, f1_slice, f2_slice)
1459
+
1460
+ if self._interpolate:
1461
+ start = self._get_interpolating_points(t, f1, f2, idx0)
1462
+ end = self._get_interpolating_points(t, f1, f2, idx1)
1463
+ else:
1464
+ # Handle scalar f2 (e.g. 0): the fill should go all
1465
+ # the way down to 0 even if none of the dep1 sample points do.
1466
+ start = t_slice[0], f2_slice[0]
1467
+ end = t_slice[-1], f2_slice[-1]
1468
+
1469
+ pts = np.concatenate((
1470
+ np.asarray([start]),
1471
+ np.stack((t_slice, f1_slice), axis=-1),
1472
+ np.asarray([end]),
1473
+ np.stack((t_slice, f2_slice), axis=-1)[::-1]))
1474
+
1475
+ return self._fix_pts_xy_order(pts)
1476
+
1477
+ @classmethod
1478
+ def _get_interpolating_points(cls, t, f1, f2, idx):
1479
+ """Calculate interpolating points."""
1480
+ im1 = max(idx - 1, 0)
1481
+ t_values = t[im1:idx+1]
1482
+ diff_values = f1[im1:idx+1] - f2[im1:idx+1]
1483
+ f1_values = f1[im1:idx+1]
1484
+
1485
+ if len(diff_values) == 2:
1486
+ if np.ma.is_masked(diff_values[1]):
1487
+ return t[im1], f1[im1]
1488
+ elif np.ma.is_masked(diff_values[0]):
1489
+ return t[idx], f1[idx]
1490
+
1491
+ diff_root_t = cls._get_diff_root(0, diff_values, t_values)
1492
+ diff_root_f = cls._get_diff_root(diff_root_t, t_values, f1_values)
1493
+ return diff_root_t, diff_root_f
1494
+
1495
+ @staticmethod
1496
+ def _get_diff_root(x, xp, fp):
1497
+ """Calculate diff root."""
1498
+ order = xp.argsort()
1499
+ return np.interp(x, xp[order], fp[order])
1500
+
1501
+ def _fix_pts_xy_order(self, pts):
1502
+ """
1503
+ Fix pts calculation results with `self.t_direction`.
1504
+
1505
+ In the workflow, it is assumed that `self.t_direction` is 'x'. If this
1506
+ is not true, we need to exchange the coordinates.
1507
+ """
1508
+ return pts[:, ::-1] if self.t_direction == "y" else pts
1509
+
1510
+
1511
+ class RegularPolyCollection(_CollectionWithSizes):
1512
+ """A collection of n-sided regular polygons."""
1513
+
1514
+ _path_generator = mpath.Path.unit_regular_polygon
1515
+ _factor = np.pi ** (-1/2)
1516
+
1517
+ def __init__(self,
1518
+ numsides,
1519
+ *,
1520
+ rotation=0,
1521
+ sizes=(1,),
1522
+ **kwargs):
1523
+ """
1524
+ Parameters
1525
+ ----------
1526
+ numsides : int
1527
+ The number of sides of the polygon.
1528
+ rotation : float
1529
+ The rotation of the polygon in radians.
1530
+ sizes : tuple of float
1531
+ The area of the circle circumscribing the polygon in points^2.
1532
+ **kwargs
1533
+ Forwarded to `.Collection`.
1534
+
1535
+ Examples
1536
+ --------
1537
+ See :doc:`/gallery/event_handling/lasso_demo` for a complete example::
1538
+
1539
+ offsets = np.random.rand(20, 2)
1540
+ facecolors = [cm.jet(x) for x in np.random.rand(20)]
1541
+
1542
+ collection = RegularPolyCollection(
1543
+ numsides=5, # a pentagon
1544
+ rotation=0, sizes=(50,),
1545
+ facecolors=facecolors,
1546
+ edgecolors=("black",),
1547
+ linewidths=(1,),
1548
+ offsets=offsets,
1549
+ offset_transform=ax.transData,
1550
+ )
1551
+ """
1552
+ super().__init__(**kwargs)
1553
+ self.set_sizes(sizes)
1554
+ self._numsides = numsides
1555
+ self._paths = [self._path_generator(numsides)]
1556
+ self._rotation = rotation
1557
+ self.set_transform(transforms.IdentityTransform())
1558
+
1559
+ def get_numsides(self):
1560
+ return self._numsides
1561
+
1562
+ def get_rotation(self):
1563
+ return self._rotation
1564
+
1565
+ @artist.allow_rasterization
1566
+ def draw(self, renderer):
1567
+ self.set_sizes(self._sizes, self.get_figure(root=True).dpi)
1568
+ self._transforms = [
1569
+ transforms.Affine2D(x).rotate(-self._rotation).get_matrix()
1570
+ for x in self._transforms
1571
+ ]
1572
+ # Explicitly not super().draw, because set_sizes must be called before
1573
+ # updating self._transforms.
1574
+ Collection.draw(self, renderer)
1575
+
1576
+
1577
+ class StarPolygonCollection(RegularPolyCollection):
1578
+ """Draw a collection of regular stars with *numsides* points."""
1579
+ _path_generator = mpath.Path.unit_regular_star
1580
+
1581
+
1582
+ class AsteriskPolygonCollection(RegularPolyCollection):
1583
+ """Draw a collection of regular asterisks with *numsides* points."""
1584
+ _path_generator = mpath.Path.unit_regular_asterisk
1585
+
1586
+
1587
+ class LineCollection(Collection):
1588
+ r"""
1589
+ Represents a sequence of `.Line2D`\s that should be drawn together.
1590
+
1591
+ This class extends `.Collection` to represent a sequence of
1592
+ `.Line2D`\s instead of just a sequence of `.Patch`\s.
1593
+ Just as in `.Collection`, each property of a *LineCollection* may be either
1594
+ a single value or a list of values. This list is then used cyclically for
1595
+ each element of the LineCollection, so the property of the ``i``\th element
1596
+ of the collection is::
1597
+
1598
+ prop[i % len(prop)]
1599
+
1600
+ The properties of each member of a *LineCollection* default to their values
1601
+ in :rc:`lines.*` instead of :rc:`patch.*`, and the property *colors* is
1602
+ added in place of *edgecolors*.
1603
+ """
1604
+
1605
+ _edge_default = True
1606
+
1607
+ def __init__(self, segments, # Can be None.
1608
+ *,
1609
+ zorder=2, # Collection.zorder is 1
1610
+ **kwargs
1611
+ ):
1612
+ """
1613
+ Parameters
1614
+ ----------
1615
+ segments : list of (N, 2) array-like
1616
+ A sequence ``[line0, line1, ...]`` where each line is a (N, 2)-shape
1617
+ array-like containing points::
1618
+
1619
+ line0 = [(x0, y0), (x1, y1), ...]
1620
+
1621
+ Each line can contain a different number of points.
1622
+ linewidths : float or list of float, default: :rc:`lines.linewidth`
1623
+ The width of each line in points.
1624
+ colors : :mpltype:`color` or list of color, default: :rc:`lines.color`
1625
+ A sequence of RGBA tuples (e.g., arbitrary color strings, etc, not
1626
+ allowed).
1627
+ antialiaseds : bool or list of bool, default: :rc:`lines.antialiased`
1628
+ Whether to use antialiasing for each line.
1629
+ zorder : float, default: 2
1630
+ zorder of the lines once drawn.
1631
+
1632
+ facecolors : :mpltype:`color` or list of :mpltype:`color`, default: 'none'
1633
+ When setting *facecolors*, each line is interpreted as a boundary
1634
+ for an area, implicitly closing the path from the last point to the
1635
+ first point. The enclosed area is filled with *facecolor*.
1636
+ In order to manually specify what should count as the "interior" of
1637
+ each line, please use `.PathCollection` instead, where the
1638
+ "interior" can be specified by appropriate usage of
1639
+ `~.path.Path.CLOSEPOLY`.
1640
+
1641
+ **kwargs
1642
+ Forwarded to `.Collection`.
1643
+ """
1644
+ # Unfortunately, mplot3d needs this explicit setting of 'facecolors'.
1645
+ kwargs.setdefault('facecolors', 'none')
1646
+ super().__init__(
1647
+ zorder=zorder,
1648
+ **kwargs)
1649
+ self.set_segments(segments)
1650
+
1651
+ def set_segments(self, segments):
1652
+ if segments is None:
1653
+ return
1654
+
1655
+ self._paths = [mpath.Path(seg) if isinstance(seg, np.ma.MaskedArray)
1656
+ else mpath.Path(np.asarray(seg, float))
1657
+ for seg in segments]
1658
+ self.stale = True
1659
+
1660
+ set_verts = set_segments # for compatibility with PolyCollection
1661
+ set_paths = set_segments
1662
+
1663
+ def get_segments(self):
1664
+ """
1665
+ Returns
1666
+ -------
1667
+ list
1668
+ List of segments in the LineCollection. Each list item contains an
1669
+ array of vertices.
1670
+ """
1671
+ segments = []
1672
+
1673
+ for path in self._paths:
1674
+ vertices = [
1675
+ vertex
1676
+ for vertex, _
1677
+ # Never simplify here, we want to get the data-space values
1678
+ # back and there in no way to know the "right" simplification
1679
+ # threshold so never try.
1680
+ in path.iter_segments(simplify=False)
1681
+ ]
1682
+ vertices = np.asarray(vertices)
1683
+ segments.append(vertices)
1684
+
1685
+ return segments
1686
+
1687
+ def _get_default_linewidth(self):
1688
+ return mpl.rcParams['lines.linewidth']
1689
+
1690
+ def _get_default_antialiased(self):
1691
+ return mpl.rcParams['lines.antialiased']
1692
+
1693
+ def _get_default_edgecolor(self):
1694
+ return mpl.rcParams['lines.color']
1695
+
1696
+ def _get_default_facecolor(self):
1697
+ return 'none'
1698
+
1699
+ def set_alpha(self, alpha):
1700
+ # docstring inherited
1701
+ super().set_alpha(alpha)
1702
+ if self._gapcolor is not None:
1703
+ self.set_gapcolor(self._original_gapcolor)
1704
+
1705
+ def set_color(self, c):
1706
+ """
1707
+ Set the edgecolor(s) of the LineCollection.
1708
+
1709
+ Parameters
1710
+ ----------
1711
+ c : :mpltype:`color` or list of :mpltype:`color`
1712
+ Single color (all lines have same color), or a
1713
+ sequence of RGBA tuples; if it is a sequence the lines will
1714
+ cycle through the sequence.
1715
+ """
1716
+ self.set_edgecolor(c)
1717
+
1718
+ set_colors = set_color
1719
+
1720
+ def get_color(self):
1721
+ return self._edgecolors
1722
+
1723
+ get_colors = get_color # for compatibility with old versions
1724
+
1725
+ def set_gapcolor(self, gapcolor):
1726
+ """
1727
+ Set a color to fill the gaps in the dashed line style.
1728
+
1729
+ .. note::
1730
+
1731
+ Striped lines are created by drawing two interleaved dashed lines.
1732
+ There can be overlaps between those two, which may result in
1733
+ artifacts when using transparency.
1734
+
1735
+ This functionality is experimental and may change.
1736
+
1737
+ Parameters
1738
+ ----------
1739
+ gapcolor : :mpltype:`color` or list of :mpltype:`color` or None
1740
+ The color with which to fill the gaps. If None, the gaps are
1741
+ unfilled.
1742
+ """
1743
+ self._original_gapcolor = gapcolor
1744
+ self._set_gapcolor(gapcolor)
1745
+
1746
+ def _set_gapcolor(self, gapcolor):
1747
+ if gapcolor is not None:
1748
+ gapcolor = mcolors.to_rgba_array(gapcolor, self._alpha)
1749
+ self._gapcolor = gapcolor
1750
+ self.stale = True
1751
+
1752
+ def get_gapcolor(self):
1753
+ return self._gapcolor
1754
+
1755
+ def _get_inverse_paths_linestyles(self):
1756
+ """
1757
+ Returns the path and pattern for the gaps in the non-solid lines.
1758
+
1759
+ This path and pattern is the inverse of the path and pattern used to
1760
+ construct the non-solid lines. For solid lines, we set the inverse path
1761
+ to nans to prevent drawing an inverse line.
1762
+ """
1763
+ path_patterns = [
1764
+ (mpath.Path(np.full((1, 2), np.nan)), ls)
1765
+ if ls == (0, None) else
1766
+ (path, mlines._get_inverse_dash_pattern(*ls))
1767
+ for (path, ls) in
1768
+ zip(self._paths, itertools.cycle(self._linestyles))]
1769
+
1770
+ return zip(*path_patterns)
1771
+
1772
+
1773
+ class EventCollection(LineCollection):
1774
+ """
1775
+ A collection of locations along a single axis at which an "event" occurred.
1776
+
1777
+ The events are given by a 1-dimensional array. They do not have an
1778
+ amplitude and are displayed as parallel lines.
1779
+ """
1780
+
1781
+ _edge_default = True
1782
+
1783
+ def __init__(self,
1784
+ positions, # Cannot be None.
1785
+ orientation='horizontal',
1786
+ *,
1787
+ lineoffset=0,
1788
+ linelength=1,
1789
+ linewidth=None,
1790
+ color=None,
1791
+ linestyle='solid',
1792
+ antialiased=None,
1793
+ **kwargs
1794
+ ):
1795
+ """
1796
+ Parameters
1797
+ ----------
1798
+ positions : 1D array-like
1799
+ Each value is an event.
1800
+ orientation : {'horizontal', 'vertical'}, default: 'horizontal'
1801
+ The sequence of events is plotted along this direction.
1802
+ The marker lines of the single events are along the orthogonal
1803
+ direction.
1804
+ lineoffset : float, default: 0
1805
+ The offset of the center of the markers from the origin, in the
1806
+ direction orthogonal to *orientation*.
1807
+ linelength : float, default: 1
1808
+ The total height of the marker (i.e. the marker stretches from
1809
+ ``lineoffset - linelength/2`` to ``lineoffset + linelength/2``).
1810
+ linewidth : float or list thereof, default: :rc:`lines.linewidth`
1811
+ The line width of the event lines, in points.
1812
+ color : :mpltype:`color` or list of :mpltype:`color`, default: :rc:`lines.color`
1813
+ The color of the event lines.
1814
+ linestyle : str or tuple or list thereof, default: 'solid'
1815
+ Valid strings are ['solid', 'dashed', 'dashdot', 'dotted',
1816
+ '-', '--', '-.', ':']. Dash tuples should be of the form::
1817
+
1818
+ (offset, onoffseq),
1819
+
1820
+ where *onoffseq* is an even length tuple of on and off ink
1821
+ in points.
1822
+ antialiased : bool or list thereof, default: :rc:`lines.antialiased`
1823
+ Whether to use antialiasing for drawing the lines.
1824
+ **kwargs
1825
+ Forwarded to `.LineCollection`.
1826
+
1827
+ Examples
1828
+ --------
1829
+ .. plot:: gallery/lines_bars_and_markers/eventcollection_demo.py
1830
+ """
1831
+ super().__init__([],
1832
+ linewidths=linewidth, linestyles=linestyle,
1833
+ colors=color, antialiaseds=antialiased,
1834
+ **kwargs)
1835
+ self._is_horizontal = True # Initial value, may be switched below.
1836
+ self._linelength = linelength
1837
+ self._lineoffset = lineoffset
1838
+ self.set_orientation(orientation)
1839
+ self.set_positions(positions)
1840
+
1841
+ def get_positions(self):
1842
+ """
1843
+ Return an array containing the floating-point values of the positions.
1844
+ """
1845
+ pos = 0 if self.is_horizontal() else 1
1846
+ return [segment[0, pos] for segment in self.get_segments()]
1847
+
1848
+ def set_positions(self, positions):
1849
+ """Set the positions of the events."""
1850
+ if positions is None:
1851
+ positions = []
1852
+ if np.ndim(positions) != 1:
1853
+ raise ValueError('positions must be one-dimensional')
1854
+ lineoffset = self.get_lineoffset()
1855
+ linelength = self.get_linelength()
1856
+ pos_idx = 0 if self.is_horizontal() else 1
1857
+ segments = np.empty((len(positions), 2, 2))
1858
+ segments[:, :, pos_idx] = np.sort(positions)[:, None]
1859
+ segments[:, 0, 1 - pos_idx] = lineoffset + linelength / 2
1860
+ segments[:, 1, 1 - pos_idx] = lineoffset - linelength / 2
1861
+ self.set_segments(segments)
1862
+
1863
+ def add_positions(self, position):
1864
+ """Add one or more events at the specified positions."""
1865
+ if position is None or (hasattr(position, 'len') and
1866
+ len(position) == 0):
1867
+ return
1868
+ positions = self.get_positions()
1869
+ positions = np.hstack([positions, np.asanyarray(position)])
1870
+ self.set_positions(positions)
1871
+ extend_positions = append_positions = add_positions
1872
+
1873
+ def is_horizontal(self):
1874
+ """True if the eventcollection is horizontal, False if vertical."""
1875
+ return self._is_horizontal
1876
+
1877
+ def get_orientation(self):
1878
+ """
1879
+ Return the orientation of the event line ('horizontal' or 'vertical').
1880
+ """
1881
+ return 'horizontal' if self.is_horizontal() else 'vertical'
1882
+
1883
+ def switch_orientation(self):
1884
+ """
1885
+ Switch the orientation of the event line, either from vertical to
1886
+ horizontal or vice versus.
1887
+ """
1888
+ segments = self.get_segments()
1889
+ for i, segment in enumerate(segments):
1890
+ segments[i] = np.fliplr(segment)
1891
+ self.set_segments(segments)
1892
+ self._is_horizontal = not self.is_horizontal()
1893
+ self.stale = True
1894
+
1895
+ def set_orientation(self, orientation):
1896
+ """
1897
+ Set the orientation of the event line.
1898
+
1899
+ Parameters
1900
+ ----------
1901
+ orientation : {'horizontal', 'vertical'}
1902
+ """
1903
+ is_horizontal = _api.check_getitem(
1904
+ {"horizontal": True, "vertical": False},
1905
+ orientation=orientation)
1906
+ if is_horizontal == self.is_horizontal():
1907
+ return
1908
+ self.switch_orientation()
1909
+
1910
+ def get_linelength(self):
1911
+ """Return the length of the lines used to mark each event."""
1912
+ return self._linelength
1913
+
1914
+ def set_linelength(self, linelength):
1915
+ """Set the length of the lines used to mark each event."""
1916
+ if linelength == self.get_linelength():
1917
+ return
1918
+ lineoffset = self.get_lineoffset()
1919
+ segments = self.get_segments()
1920
+ pos = 1 if self.is_horizontal() else 0
1921
+ for segment in segments:
1922
+ segment[0, pos] = lineoffset + linelength / 2.
1923
+ segment[1, pos] = lineoffset - linelength / 2.
1924
+ self.set_segments(segments)
1925
+ self._linelength = linelength
1926
+
1927
+ def get_lineoffset(self):
1928
+ """Return the offset of the lines used to mark each event."""
1929
+ return self._lineoffset
1930
+
1931
+ def set_lineoffset(self, lineoffset):
1932
+ """Set the offset of the lines used to mark each event."""
1933
+ if lineoffset == self.get_lineoffset():
1934
+ return
1935
+ linelength = self.get_linelength()
1936
+ segments = self.get_segments()
1937
+ pos = 1 if self.is_horizontal() else 0
1938
+ for segment in segments:
1939
+ segment[0, pos] = lineoffset + linelength / 2.
1940
+ segment[1, pos] = lineoffset - linelength / 2.
1941
+ self.set_segments(segments)
1942
+ self._lineoffset = lineoffset
1943
+
1944
+ def get_linewidth(self):
1945
+ """Get the width of the lines used to mark each event."""
1946
+ return super().get_linewidth()[0]
1947
+
1948
+ def get_linewidths(self):
1949
+ return super().get_linewidth()
1950
+
1951
+ def get_color(self):
1952
+ """Return the color of the lines used to mark each event."""
1953
+ return self.get_colors()[0]
1954
+
1955
+
1956
+ class CircleCollection(_CollectionWithSizes):
1957
+ """A collection of circles, drawn using splines."""
1958
+
1959
+ _factor = np.pi ** (-1/2)
1960
+
1961
+ def __init__(self, sizes, **kwargs):
1962
+ """
1963
+ Parameters
1964
+ ----------
1965
+ sizes : float or array-like
1966
+ The area of each circle in points^2.
1967
+ **kwargs
1968
+ Forwarded to `.Collection`.
1969
+ """
1970
+ super().__init__(**kwargs)
1971
+ self.set_sizes(sizes)
1972
+ self.set_transform(transforms.IdentityTransform())
1973
+ self._paths = [mpath.Path.unit_circle()]
1974
+
1975
+
1976
+ class EllipseCollection(Collection):
1977
+ """A collection of ellipses, drawn using splines."""
1978
+
1979
+ def __init__(self, widths, heights, angles, *, units='points', **kwargs):
1980
+ """
1981
+ Parameters
1982
+ ----------
1983
+ widths : array-like
1984
+ The lengths of the first axes (e.g., major axis lengths).
1985
+ heights : array-like
1986
+ The lengths of second axes.
1987
+ angles : array-like
1988
+ The angles of the first axes, degrees CCW from the x-axis.
1989
+ units : {'points', 'inches', 'dots', 'width', 'height', 'x', 'y', 'xy'}
1990
+ The units in which majors and minors are given; 'width' and
1991
+ 'height' refer to the dimensions of the axes, while 'x' and 'y'
1992
+ refer to the *offsets* data units. 'xy' differs from all others in
1993
+ that the angle as plotted varies with the aspect ratio, and equals
1994
+ the specified angle only when the aspect ratio is unity. Hence
1995
+ it behaves the same as the `~.patches.Ellipse` with
1996
+ ``axes.transData`` as its transform.
1997
+ **kwargs
1998
+ Forwarded to `Collection`.
1999
+ """
2000
+ super().__init__(**kwargs)
2001
+ self.set_widths(widths)
2002
+ self.set_heights(heights)
2003
+ self.set_angles(angles)
2004
+ self._units = units
2005
+ self.set_transform(transforms.IdentityTransform())
2006
+ self._transforms = np.empty((0, 3, 3))
2007
+ self._paths = [mpath.Path.unit_circle()]
2008
+
2009
+ def _set_transforms(self):
2010
+ """Calculate transforms immediately before drawing."""
2011
+
2012
+ ax = self.axes
2013
+ fig = self.get_figure(root=False)
2014
+
2015
+ if self._units == 'xy':
2016
+ sc = 1
2017
+ elif self._units == 'x':
2018
+ sc = ax.bbox.width / ax.viewLim.width
2019
+ elif self._units == 'y':
2020
+ sc = ax.bbox.height / ax.viewLim.height
2021
+ elif self._units == 'inches':
2022
+ sc = fig.dpi
2023
+ elif self._units == 'points':
2024
+ sc = fig.dpi / 72.0
2025
+ elif self._units == 'width':
2026
+ sc = ax.bbox.width
2027
+ elif self._units == 'height':
2028
+ sc = ax.bbox.height
2029
+ elif self._units == 'dots':
2030
+ sc = 1.0
2031
+ else:
2032
+ raise ValueError(f'Unrecognized units: {self._units!r}')
2033
+
2034
+ self._transforms = np.zeros((len(self._widths), 3, 3))
2035
+ widths = self._widths * sc
2036
+ heights = self._heights * sc
2037
+ sin_angle = np.sin(self._angles)
2038
+ cos_angle = np.cos(self._angles)
2039
+ self._transforms[:, 0, 0] = widths * cos_angle
2040
+ self._transforms[:, 0, 1] = heights * -sin_angle
2041
+ self._transforms[:, 1, 0] = widths * sin_angle
2042
+ self._transforms[:, 1, 1] = heights * cos_angle
2043
+ self._transforms[:, 2, 2] = 1.0
2044
+
2045
+ _affine = transforms.Affine2D
2046
+ if self._units == 'xy':
2047
+ m = ax.transData.get_affine().get_matrix().copy()
2048
+ m[:2, 2:] = 0
2049
+ self.set_transform(_affine(m))
2050
+
2051
+ def set_widths(self, widths):
2052
+ """Set the lengths of the first axes (e.g., major axis)."""
2053
+ self._widths = 0.5 * np.asarray(widths).ravel()
2054
+ self.stale = True
2055
+
2056
+ def set_heights(self, heights):
2057
+ """Set the lengths of second axes (e.g., minor axes)."""
2058
+ self._heights = 0.5 * np.asarray(heights).ravel()
2059
+ self.stale = True
2060
+
2061
+ def set_angles(self, angles):
2062
+ """Set the angles of the first axes, degrees CCW from the x-axis."""
2063
+ self._angles = np.deg2rad(angles).ravel()
2064
+ self.stale = True
2065
+
2066
+ def get_widths(self):
2067
+ """Get the lengths of the first axes (e.g., major axis)."""
2068
+ return self._widths * 2
2069
+
2070
+ def get_heights(self):
2071
+ """Set the lengths of second axes (e.g., minor axes)."""
2072
+ return self._heights * 2
2073
+
2074
+ def get_angles(self):
2075
+ """Get the angles of the first axes, degrees CCW from the x-axis."""
2076
+ return np.rad2deg(self._angles)
2077
+
2078
+ @artist.allow_rasterization
2079
+ def draw(self, renderer):
2080
+ self._set_transforms()
2081
+ super().draw(renderer)
2082
+
2083
+
2084
+ class PatchCollection(Collection):
2085
+ """
2086
+ A generic collection of patches.
2087
+
2088
+ PatchCollection draws faster than a large number of equivalent individual
2089
+ Patches. It also makes it easier to assign a colormap to a heterogeneous
2090
+ collection of patches.
2091
+ """
2092
+
2093
+ def __init__(self, patches, *, match_original=False, **kwargs):
2094
+ """
2095
+ Parameters
2096
+ ----------
2097
+ patches : list of `.Patch`
2098
+ A sequence of Patch objects. This list may include
2099
+ a heterogeneous assortment of different patch types.
2100
+
2101
+ match_original : bool, default: False
2102
+ If True, use the colors and linewidths of the original
2103
+ patches. If False, new colors may be assigned by
2104
+ providing the standard collection arguments, facecolor,
2105
+ edgecolor, linewidths, norm or cmap.
2106
+
2107
+ **kwargs
2108
+ All other parameters are forwarded to `.Collection`.
2109
+
2110
+ If any of *edgecolors*, *facecolors*, *linewidths*, *antialiaseds*
2111
+ are None, they default to their `.rcParams` patch setting, in
2112
+ sequence form.
2113
+
2114
+ Notes
2115
+ -----
2116
+ The use of `~matplotlib.cm.ScalarMappable` functionality is optional.
2117
+ If the `~matplotlib.cm.ScalarMappable` matrix ``_A`` has been set (via
2118
+ a call to `~.ScalarMappable.set_array`), at draw time a call to scalar
2119
+ mappable will be made to set the face colors.
2120
+ """
2121
+
2122
+ if match_original:
2123
+ def determine_facecolor(patch):
2124
+ if patch.get_fill():
2125
+ return patch.get_facecolor()
2126
+ return [0, 0, 0, 0]
2127
+
2128
+ kwargs['facecolors'] = [determine_facecolor(p) for p in patches]
2129
+ kwargs['edgecolors'] = [p.get_edgecolor() for p in patches]
2130
+ kwargs['linewidths'] = [p.get_linewidth() for p in patches]
2131
+ kwargs['linestyles'] = [p.get_linestyle() for p in patches]
2132
+ kwargs['antialiaseds'] = [p.get_antialiased() for p in patches]
2133
+
2134
+ super().__init__(**kwargs)
2135
+
2136
+ self.set_paths(patches)
2137
+
2138
+ def set_paths(self, patches):
2139
+ paths = [p.get_transform().transform_path(p.get_path())
2140
+ for p in patches]
2141
+ self._paths = paths
2142
+
2143
+
2144
+ class TriMesh(Collection):
2145
+ """
2146
+ Class for the efficient drawing of a triangular mesh using Gouraud shading.
2147
+
2148
+ A triangular mesh is a `~matplotlib.tri.Triangulation` object.
2149
+ """
2150
+ def __init__(self, triangulation, **kwargs):
2151
+ super().__init__(**kwargs)
2152
+ self._triangulation = triangulation
2153
+ self._shading = 'gouraud'
2154
+
2155
+ self._bbox = transforms.Bbox.unit()
2156
+
2157
+ # Unfortunately this requires a copy, unless Triangulation
2158
+ # was rewritten.
2159
+ xy = np.hstack((triangulation.x.reshape(-1, 1),
2160
+ triangulation.y.reshape(-1, 1)))
2161
+ self._bbox.update_from_data_xy(xy)
2162
+
2163
+ def get_paths(self):
2164
+ if self._paths is None:
2165
+ self.set_paths()
2166
+ return self._paths
2167
+
2168
+ def set_paths(self):
2169
+ self._paths = self.convert_mesh_to_paths(self._triangulation)
2170
+
2171
+ @staticmethod
2172
+ def convert_mesh_to_paths(tri):
2173
+ """
2174
+ Convert a given mesh into a sequence of `.Path` objects.
2175
+
2176
+ This function is primarily of use to implementers of backends that do
2177
+ not directly support meshes.
2178
+ """
2179
+ triangles = tri.get_masked_triangles()
2180
+ verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
2181
+ return [mpath.Path(x) for x in verts]
2182
+
2183
+ @artist.allow_rasterization
2184
+ def draw(self, renderer):
2185
+ if not self.get_visible():
2186
+ return
2187
+ renderer.open_group(self.__class__.__name__, gid=self.get_gid())
2188
+ transform = self.get_transform()
2189
+
2190
+ # Get a list of triangles and the color at each vertex.
2191
+ tri = self._triangulation
2192
+ triangles = tri.get_masked_triangles()
2193
+
2194
+ verts = np.stack((tri.x[triangles], tri.y[triangles]), axis=-1)
2195
+
2196
+ self.update_scalarmappable()
2197
+ colors = self._facecolors[triangles]
2198
+
2199
+ gc = renderer.new_gc()
2200
+ self._set_gc_clip(gc)
2201
+ gc.set_linewidth(self.get_linewidth()[0])
2202
+ renderer.draw_gouraud_triangles(gc, verts, colors, transform.frozen())
2203
+ gc.restore()
2204
+ renderer.close_group(self.__class__.__name__)
2205
+
2206
+
2207
+ class _MeshData:
2208
+ r"""
2209
+ Class for managing the two dimensional coordinates of Quadrilateral meshes
2210
+ and the associated data with them. This class is a mixin and is intended to
2211
+ be used with another collection that will implement the draw separately.
2212
+
2213
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
2214
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
2215
+ defined by the vertices ::
2216
+
2217
+ (m+1, n) ----------- (m+1, n+1)
2218
+ / /
2219
+ / /
2220
+ / /
2221
+ (m, n) -------- (m, n+1)
2222
+
2223
+ The mesh need not be regular and the polygons need not be convex.
2224
+
2225
+ Parameters
2226
+ ----------
2227
+ coordinates : (M+1, N+1, 2) array-like
2228
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
2229
+ of vertex (m, n).
2230
+
2231
+ shading : {'flat', 'gouraud'}, default: 'flat'
2232
+ """
2233
+ def __init__(self, coordinates, *, shading='flat'):
2234
+ _api.check_shape((None, None, 2), coordinates=coordinates)
2235
+ self._coordinates = coordinates
2236
+ self._shading = shading
2237
+
2238
+ def set_array(self, A):
2239
+ """
2240
+ Set the data values.
2241
+
2242
+ Parameters
2243
+ ----------
2244
+ A : array-like
2245
+ The mesh data. Supported array shapes are:
2246
+
2247
+ - (M, N) or (M*N,): a mesh with scalar data. The values are mapped
2248
+ to colors using normalization and a colormap. See parameters
2249
+ *norm*, *cmap*, *vmin*, *vmax*.
2250
+ - (M, N, 3): an image with RGB values (0-1 float or 0-255 int).
2251
+ - (M, N, 4): an image with RGBA values (0-1 float or 0-255 int),
2252
+ i.e. including transparency.
2253
+
2254
+ If the values are provided as a 2D grid, the shape must match the
2255
+ coordinates grid. If the values are 1D, they are reshaped to 2D.
2256
+ M, N follow from the coordinates grid, where the coordinates grid
2257
+ shape is (M, N) for 'gouraud' *shading* and (M+1, N+1) for 'flat'
2258
+ shading.
2259
+ """
2260
+ height, width = self._coordinates.shape[0:-1]
2261
+ if self._shading == 'flat':
2262
+ h, w = height - 1, width - 1
2263
+ else:
2264
+ h, w = height, width
2265
+ ok_shapes = [(h, w, 3), (h, w, 4), (h, w), (h * w,)]
2266
+ if A is not None:
2267
+ shape = np.shape(A)
2268
+ if shape not in ok_shapes:
2269
+ raise ValueError(
2270
+ f"For X ({width}) and Y ({height}) with {self._shading} "
2271
+ f"shading, A should have shape "
2272
+ f"{' or '.join(map(str, ok_shapes))}, not {A.shape}")
2273
+ return super().set_array(A)
2274
+
2275
+ def get_coordinates(self):
2276
+ """
2277
+ Return the vertices of the mesh as an (M+1, N+1, 2) array.
2278
+
2279
+ M, N are the number of quadrilaterals in the rows / columns of the
2280
+ mesh, corresponding to (M+1, N+1) vertices.
2281
+ The last dimension specifies the components (x, y).
2282
+ """
2283
+ return self._coordinates
2284
+
2285
+ def get_edgecolor(self):
2286
+ # docstring inherited
2287
+ # Note that we want to return an array of shape (N*M, 4)
2288
+ # a flattened RGBA collection
2289
+ return super().get_edgecolor().reshape(-1, 4)
2290
+
2291
+ def get_facecolor(self):
2292
+ # docstring inherited
2293
+ # Note that we want to return an array of shape (N*M, 4)
2294
+ # a flattened RGBA collection
2295
+ return super().get_facecolor().reshape(-1, 4)
2296
+
2297
+ @staticmethod
2298
+ def _convert_mesh_to_paths(coordinates):
2299
+ """
2300
+ Convert a given mesh into a sequence of `.Path` objects.
2301
+
2302
+ This function is primarily of use to implementers of backends that do
2303
+ not directly support quadmeshes.
2304
+ """
2305
+ if isinstance(coordinates, np.ma.MaskedArray):
2306
+ c = coordinates.data
2307
+ else:
2308
+ c = coordinates
2309
+ points = np.concatenate([
2310
+ c[:-1, :-1],
2311
+ c[:-1, 1:],
2312
+ c[1:, 1:],
2313
+ c[1:, :-1],
2314
+ c[:-1, :-1]
2315
+ ], axis=2).reshape((-1, 5, 2))
2316
+ return [mpath.Path(x) for x in points]
2317
+
2318
+ def _convert_mesh_to_triangles(self, coordinates):
2319
+ """
2320
+ Convert a given mesh into a sequence of triangles, each point
2321
+ with its own color. The result can be used to construct a call to
2322
+ `~.RendererBase.draw_gouraud_triangles`.
2323
+ """
2324
+ if isinstance(coordinates, np.ma.MaskedArray):
2325
+ p = coordinates.data
2326
+ else:
2327
+ p = coordinates
2328
+
2329
+ p_a = p[:-1, :-1]
2330
+ p_b = p[:-1, 1:]
2331
+ p_c = p[1:, 1:]
2332
+ p_d = p[1:, :-1]
2333
+ p_center = (p_a + p_b + p_c + p_d) / 4.0
2334
+ triangles = np.concatenate([
2335
+ p_a, p_b, p_center,
2336
+ p_b, p_c, p_center,
2337
+ p_c, p_d, p_center,
2338
+ p_d, p_a, p_center,
2339
+ ], axis=2).reshape((-1, 3, 2))
2340
+
2341
+ c = self.get_facecolor().reshape((*coordinates.shape[:2], 4))
2342
+ z = self.get_array()
2343
+ mask = z.mask if np.ma.is_masked(z) else None
2344
+ if mask is not None:
2345
+ c[mask, 3] = np.nan
2346
+ c_a = c[:-1, :-1]
2347
+ c_b = c[:-1, 1:]
2348
+ c_c = c[1:, 1:]
2349
+ c_d = c[1:, :-1]
2350
+ c_center = (c_a + c_b + c_c + c_d) / 4.0
2351
+ colors = np.concatenate([
2352
+ c_a, c_b, c_center,
2353
+ c_b, c_c, c_center,
2354
+ c_c, c_d, c_center,
2355
+ c_d, c_a, c_center,
2356
+ ], axis=2).reshape((-1, 3, 4))
2357
+ tmask = np.isnan(colors[..., 2, 3])
2358
+ return triangles[~tmask], colors[~tmask]
2359
+
2360
+
2361
+ class QuadMesh(_MeshData, Collection):
2362
+ r"""
2363
+ Class for the efficient drawing of a quadrilateral mesh.
2364
+
2365
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
2366
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
2367
+ defined by the vertices ::
2368
+
2369
+ (m+1, n) ----------- (m+1, n+1)
2370
+ / /
2371
+ / /
2372
+ / /
2373
+ (m, n) -------- (m, n+1)
2374
+
2375
+ The mesh need not be regular and the polygons need not be convex.
2376
+
2377
+ Parameters
2378
+ ----------
2379
+ coordinates : (M+1, N+1, 2) array-like
2380
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
2381
+ of vertex (m, n).
2382
+
2383
+ antialiased : bool, default: True
2384
+
2385
+ shading : {'flat', 'gouraud'}, default: 'flat'
2386
+
2387
+ Notes
2388
+ -----
2389
+ Unlike other `.Collection`\s, the default *pickradius* of `.QuadMesh` is 0,
2390
+ i.e. `~.Artist.contains` checks whether the test point is within any of the
2391
+ mesh quadrilaterals.
2392
+
2393
+ """
2394
+
2395
+ def __init__(self, coordinates, *, antialiased=True, shading='flat',
2396
+ **kwargs):
2397
+ kwargs.setdefault("pickradius", 0)
2398
+ super().__init__(coordinates=coordinates, shading=shading)
2399
+ Collection.__init__(self, **kwargs)
2400
+
2401
+ self._antialiased = antialiased
2402
+ self._bbox = transforms.Bbox.unit()
2403
+ self._bbox.update_from_data_xy(self._coordinates.reshape(-1, 2))
2404
+ self.set_mouseover(False)
2405
+
2406
+ def get_paths(self):
2407
+ if self._paths is None:
2408
+ self.set_paths()
2409
+ return self._paths
2410
+
2411
+ def set_paths(self):
2412
+ self._paths = self._convert_mesh_to_paths(self._coordinates)
2413
+ self.stale = True
2414
+
2415
+ def get_datalim(self, transData):
2416
+ return (self.get_transform() - transData).transform_bbox(self._bbox)
2417
+
2418
+ @artist.allow_rasterization
2419
+ def draw(self, renderer):
2420
+ if not self.get_visible():
2421
+ return
2422
+ renderer.open_group(self.__class__.__name__, self.get_gid())
2423
+ transform = self.get_transform()
2424
+ offset_trf = self.get_offset_transform()
2425
+ offsets = self.get_offsets()
2426
+
2427
+ if self.have_units():
2428
+ xs = self.convert_xunits(offsets[:, 0])
2429
+ ys = self.convert_yunits(offsets[:, 1])
2430
+ offsets = np.column_stack([xs, ys])
2431
+
2432
+ self.update_scalarmappable()
2433
+
2434
+ if not transform.is_affine:
2435
+ coordinates = self._coordinates.reshape((-1, 2))
2436
+ coordinates = transform.transform(coordinates)
2437
+ coordinates = coordinates.reshape(self._coordinates.shape)
2438
+ transform = transforms.IdentityTransform()
2439
+ else:
2440
+ coordinates = self._coordinates
2441
+
2442
+ if not offset_trf.is_affine:
2443
+ offsets = offset_trf.transform_non_affine(offsets)
2444
+ offset_trf = offset_trf.get_affine()
2445
+
2446
+ gc = renderer.new_gc()
2447
+ gc.set_snap(self.get_snap())
2448
+ self._set_gc_clip(gc)
2449
+ gc.set_linewidth(self.get_linewidth()[0])
2450
+
2451
+ if self._shading == 'gouraud':
2452
+ triangles, colors = self._convert_mesh_to_triangles(coordinates)
2453
+ renderer.draw_gouraud_triangles(
2454
+ gc, triangles, colors, transform.frozen())
2455
+ else:
2456
+ renderer.draw_quad_mesh(
2457
+ gc, transform.frozen(),
2458
+ coordinates.shape[1] - 1, coordinates.shape[0] - 1,
2459
+ coordinates, offsets, offset_trf,
2460
+ # Backends expect flattened rgba arrays (n*m, 4) for fc and ec
2461
+ self.get_facecolor().reshape((-1, 4)),
2462
+ self._antialiased, self.get_edgecolors().reshape((-1, 4)))
2463
+ gc.restore()
2464
+ renderer.close_group(self.__class__.__name__)
2465
+ self.stale = False
2466
+
2467
+ def get_cursor_data(self, event):
2468
+ contained, info = self.contains(event)
2469
+ if contained and self.get_array() is not None:
2470
+ return self.get_array().ravel()[info["ind"]]
2471
+ return None
2472
+
2473
+
2474
+ class PolyQuadMesh(_MeshData, PolyCollection):
2475
+ """
2476
+ Class for drawing a quadrilateral mesh as individual Polygons.
2477
+
2478
+ A quadrilateral mesh is a grid of M by N adjacent quadrilaterals that are
2479
+ defined via a (M+1, N+1) grid of vertices. The quadrilateral (m, n) is
2480
+ defined by the vertices ::
2481
+
2482
+ (m+1, n) ----------- (m+1, n+1)
2483
+ / /
2484
+ / /
2485
+ / /
2486
+ (m, n) -------- (m, n+1)
2487
+
2488
+ The mesh need not be regular and the polygons need not be convex.
2489
+
2490
+ Parameters
2491
+ ----------
2492
+ coordinates : (M+1, N+1, 2) array-like
2493
+ The vertices. ``coordinates[m, n]`` specifies the (x, y) coordinates
2494
+ of vertex (m, n).
2495
+
2496
+ Notes
2497
+ -----
2498
+ Unlike `.QuadMesh`, this class will draw each cell as an individual Polygon.
2499
+ This is significantly slower, but allows for more flexibility when wanting
2500
+ to add additional properties to the cells, such as hatching.
2501
+
2502
+ Another difference from `.QuadMesh` is that if any of the vertices or data
2503
+ of a cell are masked, that Polygon will **not** be drawn and it won't be in
2504
+ the list of paths returned.
2505
+ """
2506
+
2507
+ def __init__(self, coordinates, **kwargs):
2508
+ super().__init__(coordinates=coordinates)
2509
+ PolyCollection.__init__(self, verts=[], **kwargs)
2510
+ # Setting the verts updates the paths of the PolyCollection
2511
+ # This is called after the initializers to make sure the kwargs
2512
+ # have all been processed and available for the masking calculations
2513
+ self._set_unmasked_verts()
2514
+
2515
+ def _get_unmasked_polys(self):
2516
+ """Get the unmasked regions using the coordinates and array"""
2517
+ # mask(X) | mask(Y)
2518
+ mask = np.any(np.ma.getmaskarray(self._coordinates), axis=-1)
2519
+
2520
+ # We want the shape of the polygon, which is the corner of each X/Y array
2521
+ mask = (mask[0:-1, 0:-1] | mask[1:, 1:] | mask[0:-1, 1:] | mask[1:, 0:-1])
2522
+ arr = self.get_array()
2523
+ if arr is not None:
2524
+ arr = np.ma.getmaskarray(arr)
2525
+ if arr.ndim == 3:
2526
+ # RGB(A) case
2527
+ mask |= np.any(arr, axis=-1)
2528
+ elif arr.ndim == 2:
2529
+ mask |= arr
2530
+ else:
2531
+ mask |= arr.reshape(self._coordinates[:-1, :-1, :].shape[:2])
2532
+ return ~mask
2533
+
2534
+ def _set_unmasked_verts(self):
2535
+ X = self._coordinates[..., 0]
2536
+ Y = self._coordinates[..., 1]
2537
+
2538
+ unmask = self._get_unmasked_polys()
2539
+ X1 = np.ma.filled(X[:-1, :-1])[unmask]
2540
+ Y1 = np.ma.filled(Y[:-1, :-1])[unmask]
2541
+ X2 = np.ma.filled(X[1:, :-1])[unmask]
2542
+ Y2 = np.ma.filled(Y[1:, :-1])[unmask]
2543
+ X3 = np.ma.filled(X[1:, 1:])[unmask]
2544
+ Y3 = np.ma.filled(Y[1:, 1:])[unmask]
2545
+ X4 = np.ma.filled(X[:-1, 1:])[unmask]
2546
+ Y4 = np.ma.filled(Y[:-1, 1:])[unmask]
2547
+ npoly = len(X1)
2548
+
2549
+ xy = np.ma.stack([X1, Y1, X2, Y2, X3, Y3, X4, Y4, X1, Y1], axis=-1)
2550
+ verts = xy.reshape((npoly, 5, 2))
2551
+ self.set_verts(verts)
2552
+
2553
+ def get_edgecolor(self):
2554
+ # docstring inherited
2555
+ # We only want to return the facecolors of the polygons
2556
+ # that were drawn.
2557
+ ec = super().get_edgecolor()
2558
+ unmasked_polys = self._get_unmasked_polys().ravel()
2559
+ if len(ec) != len(unmasked_polys):
2560
+ # Mapping is off
2561
+ return ec
2562
+ return ec[unmasked_polys, :]
2563
+
2564
+ def get_facecolor(self):
2565
+ # docstring inherited
2566
+ # We only want to return the facecolors of the polygons
2567
+ # that were drawn.
2568
+ fc = super().get_facecolor()
2569
+ unmasked_polys = self._get_unmasked_polys().ravel()
2570
+ if len(fc) != len(unmasked_polys):
2571
+ # Mapping is off
2572
+ return fc
2573
+ return fc[unmasked_polys, :]
2574
+
2575
+ def set_array(self, A):
2576
+ # docstring inherited
2577
+ prev_unmask = self._get_unmasked_polys()
2578
+ super().set_array(A)
2579
+ # If the mask has changed at all we need to update
2580
+ # the set of Polys that we are drawing
2581
+ if not np.array_equal(prev_unmask, self._get_unmasked_polys()):
2582
+ self._set_unmasked_verts()
llava_video/lib/python3.10/site-packages/matplotlib/font_manager.py ADDED
@@ -0,0 +1,1645 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ A module for finding, managing, and using fonts across platforms.
3
+
4
+ This module provides a single `FontManager` instance, ``fontManager``, that can
5
+ be shared across backends and platforms. The `findfont`
6
+ function returns the best TrueType (TTF) font file in the local or
7
+ system font path that matches the specified `FontProperties`
8
+ instance. The `FontManager` also handles Adobe Font Metrics
9
+ (AFM) font files for use by the PostScript backend.
10
+ The `FontManager.addfont` function adds a custom font from a file without
11
+ installing it into your operating system.
12
+
13
+ The design is based on the `W3C Cascading Style Sheet, Level 1 (CSS1)
14
+ font specification <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_.
15
+ Future versions may implement the Level 2 or 2.1 specifications.
16
+ """
17
+
18
+ # KNOWN ISSUES
19
+ #
20
+ # - documentation
21
+ # - font variant is untested
22
+ # - font stretch is incomplete
23
+ # - font size is incomplete
24
+ # - default font algorithm needs improvement and testing
25
+ # - setWeights function needs improvement
26
+ # - 'light' is an invalid weight value, remove it.
27
+
28
+ from __future__ import annotations
29
+
30
+ from base64 import b64encode
31
+ import copy
32
+ import dataclasses
33
+ from functools import lru_cache
34
+ import functools
35
+ from io import BytesIO
36
+ import json
37
+ import logging
38
+ from numbers import Number
39
+ import os
40
+ from pathlib import Path
41
+ import plistlib
42
+ import re
43
+ import subprocess
44
+ import sys
45
+ import threading
46
+
47
+ import matplotlib as mpl
48
+ from matplotlib import _api, _afm, cbook, ft2font
49
+ from matplotlib._fontconfig_pattern import (
50
+ parse_fontconfig_pattern, generate_fontconfig_pattern)
51
+ from matplotlib.rcsetup import _validators
52
+
53
+ _log = logging.getLogger(__name__)
54
+
55
+ font_scalings = {
56
+ 'xx-small': 0.579,
57
+ 'x-small': 0.694,
58
+ 'small': 0.833,
59
+ 'medium': 1.0,
60
+ 'large': 1.200,
61
+ 'x-large': 1.440,
62
+ 'xx-large': 1.728,
63
+ 'larger': 1.2,
64
+ 'smaller': 0.833,
65
+ None: 1.0,
66
+ }
67
+ stretch_dict = {
68
+ 'ultra-condensed': 100,
69
+ 'extra-condensed': 200,
70
+ 'condensed': 300,
71
+ 'semi-condensed': 400,
72
+ 'normal': 500,
73
+ 'semi-expanded': 600,
74
+ 'semi-extended': 600,
75
+ 'expanded': 700,
76
+ 'extended': 700,
77
+ 'extra-expanded': 800,
78
+ 'extra-extended': 800,
79
+ 'ultra-expanded': 900,
80
+ 'ultra-extended': 900,
81
+ }
82
+ weight_dict = {
83
+ 'ultralight': 100,
84
+ 'light': 200,
85
+ 'normal': 400,
86
+ 'regular': 400,
87
+ 'book': 400,
88
+ 'medium': 500,
89
+ 'roman': 500,
90
+ 'semibold': 600,
91
+ 'demibold': 600,
92
+ 'demi': 600,
93
+ 'bold': 700,
94
+ 'heavy': 800,
95
+ 'extra bold': 800,
96
+ 'black': 900,
97
+ }
98
+ _weight_regexes = [
99
+ # From fontconfig's FcFreeTypeQueryFaceInternal; not the same as
100
+ # weight_dict!
101
+ ("thin", 100),
102
+ ("extralight", 200),
103
+ ("ultralight", 200),
104
+ ("demilight", 350),
105
+ ("semilight", 350),
106
+ ("light", 300), # Needs to come *after* demi/semilight!
107
+ ("book", 380),
108
+ ("regular", 400),
109
+ ("normal", 400),
110
+ ("medium", 500),
111
+ ("demibold", 600),
112
+ ("demi", 600),
113
+ ("semibold", 600),
114
+ ("extrabold", 800),
115
+ ("superbold", 800),
116
+ ("ultrabold", 800),
117
+ ("bold", 700), # Needs to come *after* extra/super/ultrabold!
118
+ ("ultrablack", 1000),
119
+ ("superblack", 1000),
120
+ ("extrablack", 1000),
121
+ (r"\bultra", 1000),
122
+ ("black", 900), # Needs to come *after* ultra/super/extrablack!
123
+ ("heavy", 900),
124
+ ]
125
+ font_family_aliases = {
126
+ 'serif',
127
+ 'sans-serif',
128
+ 'sans serif',
129
+ 'cursive',
130
+ 'fantasy',
131
+ 'monospace',
132
+ 'sans',
133
+ }
134
+
135
+ # OS Font paths
136
+ try:
137
+ _HOME = Path.home()
138
+ except Exception: # Exceptions thrown by home() are not specified...
139
+ _HOME = Path(os.devnull) # Just an arbitrary path with no children.
140
+ MSFolders = \
141
+ r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
142
+ MSFontDirectories = [
143
+ r'SOFTWARE\Microsoft\Windows NT\CurrentVersion\Fonts',
144
+ r'SOFTWARE\Microsoft\Windows\CurrentVersion\Fonts']
145
+ MSUserFontDirectories = [
146
+ str(_HOME / 'AppData/Local/Microsoft/Windows/Fonts'),
147
+ str(_HOME / 'AppData/Roaming/Microsoft/Windows/Fonts'),
148
+ ]
149
+ X11FontDirectories = [
150
+ # an old standard installation point
151
+ "/usr/X11R6/lib/X11/fonts/TTF/",
152
+ "/usr/X11/lib/X11/fonts",
153
+ # here is the new standard location for fonts
154
+ "/usr/share/fonts/",
155
+ # documented as a good place to install new fonts
156
+ "/usr/local/share/fonts/",
157
+ # common application, not really useful
158
+ "/usr/lib/openoffice/share/fonts/truetype/",
159
+ # user fonts
160
+ str((Path(os.environ.get('XDG_DATA_HOME') or _HOME / ".local/share"))
161
+ / "fonts"),
162
+ str(_HOME / ".fonts"),
163
+ ]
164
+ OSXFontDirectories = [
165
+ "/Library/Fonts/",
166
+ "/Network/Library/Fonts/",
167
+ "/System/Library/Fonts/",
168
+ # fonts installed via MacPorts
169
+ "/opt/local/share/fonts",
170
+ # user fonts
171
+ str(_HOME / "Library/Fonts"),
172
+ ]
173
+
174
+
175
+ def get_fontext_synonyms(fontext):
176
+ """
177
+ Return a list of file extensions that are synonyms for
178
+ the given file extension *fileext*.
179
+ """
180
+ return {
181
+ 'afm': ['afm'],
182
+ 'otf': ['otf', 'ttc', 'ttf'],
183
+ 'ttc': ['otf', 'ttc', 'ttf'],
184
+ 'ttf': ['otf', 'ttc', 'ttf'],
185
+ }[fontext]
186
+
187
+
188
+ def list_fonts(directory, extensions):
189
+ """
190
+ Return a list of all fonts matching any of the extensions, found
191
+ recursively under the directory.
192
+ """
193
+ extensions = ["." + ext for ext in extensions]
194
+ return [os.path.join(dirpath, filename)
195
+ # os.walk ignores access errors, unlike Path.glob.
196
+ for dirpath, _, filenames in os.walk(directory)
197
+ for filename in filenames
198
+ if Path(filename).suffix.lower() in extensions]
199
+
200
+
201
+ def win32FontDirectory():
202
+ r"""
203
+ Return the user-specified font directory for Win32. This is
204
+ looked up from the registry key ::
205
+
206
+ \\HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders\Fonts
207
+
208
+ If the key is not found, ``%WINDIR%\Fonts`` will be returned.
209
+ """ # noqa: E501
210
+ import winreg
211
+ try:
212
+ with winreg.OpenKey(winreg.HKEY_CURRENT_USER, MSFolders) as user:
213
+ return winreg.QueryValueEx(user, 'Fonts')[0]
214
+ except OSError:
215
+ return os.path.join(os.environ['WINDIR'], 'Fonts')
216
+
217
+
218
+ def _get_win32_installed_fonts():
219
+ """List the font paths known to the Windows registry."""
220
+ import winreg
221
+ items = set()
222
+ # Search and resolve fonts listed in the registry.
223
+ for domain, base_dirs in [
224
+ (winreg.HKEY_LOCAL_MACHINE, [win32FontDirectory()]), # System.
225
+ (winreg.HKEY_CURRENT_USER, MSUserFontDirectories), # User.
226
+ ]:
227
+ for base_dir in base_dirs:
228
+ for reg_path in MSFontDirectories:
229
+ try:
230
+ with winreg.OpenKey(domain, reg_path) as local:
231
+ for j in range(winreg.QueryInfoKey(local)[1]):
232
+ # value may contain the filename of the font or its
233
+ # absolute path.
234
+ key, value, tp = winreg.EnumValue(local, j)
235
+ if not isinstance(value, str):
236
+ continue
237
+ try:
238
+ # If value contains already an absolute path,
239
+ # then it is not changed further.
240
+ path = Path(base_dir, value).resolve()
241
+ except RuntimeError:
242
+ # Don't fail with invalid entries.
243
+ continue
244
+ items.add(path)
245
+ except (OSError, MemoryError):
246
+ continue
247
+ return items
248
+
249
+
250
+ @lru_cache
251
+ def _get_fontconfig_fonts():
252
+ """Cache and list the font paths known to ``fc-list``."""
253
+ try:
254
+ if b'--format' not in subprocess.check_output(['fc-list', '--help']):
255
+ _log.warning( # fontconfig 2.7 implemented --format.
256
+ 'Matplotlib needs fontconfig>=2.7 to query system fonts.')
257
+ return []
258
+ out = subprocess.check_output(['fc-list', '--format=%{file}\\n'])
259
+ except (OSError, subprocess.CalledProcessError):
260
+ return []
261
+ return [Path(os.fsdecode(fname)) for fname in out.split(b'\n')]
262
+
263
+
264
+ @lru_cache
265
+ def _get_macos_fonts():
266
+ """Cache and list the font paths known to ``system_profiler SPFontsDataType``."""
267
+ try:
268
+ d, = plistlib.loads(
269
+ subprocess.check_output(["system_profiler", "-xml", "SPFontsDataType"]))
270
+ except (OSError, subprocess.CalledProcessError, plistlib.InvalidFileException):
271
+ return []
272
+ return [Path(entry["path"]) for entry in d["_items"]]
273
+
274
+
275
+ def findSystemFonts(fontpaths=None, fontext='ttf'):
276
+ """
277
+ Search for fonts in the specified font paths. If no paths are
278
+ given, will use a standard set of system paths, as well as the
279
+ list of fonts tracked by fontconfig if fontconfig is installed and
280
+ available. A list of TrueType fonts are returned by default with
281
+ AFM fonts as an option.
282
+ """
283
+ fontfiles = set()
284
+ fontexts = get_fontext_synonyms(fontext)
285
+
286
+ if fontpaths is None:
287
+ if sys.platform == 'win32':
288
+ installed_fonts = _get_win32_installed_fonts()
289
+ fontpaths = []
290
+ else:
291
+ installed_fonts = _get_fontconfig_fonts()
292
+ if sys.platform == 'darwin':
293
+ installed_fonts += _get_macos_fonts()
294
+ fontpaths = [*X11FontDirectories, *OSXFontDirectories]
295
+ else:
296
+ fontpaths = X11FontDirectories
297
+ fontfiles.update(str(path) for path in installed_fonts
298
+ if path.suffix.lower()[1:] in fontexts)
299
+
300
+ elif isinstance(fontpaths, str):
301
+ fontpaths = [fontpaths]
302
+
303
+ for path in fontpaths:
304
+ fontfiles.update(map(os.path.abspath, list_fonts(path, fontexts)))
305
+
306
+ return [fname for fname in fontfiles if os.path.exists(fname)]
307
+
308
+
309
+ @dataclasses.dataclass(frozen=True)
310
+ class FontEntry:
311
+ """
312
+ A class for storing Font properties.
313
+
314
+ It is used when populating the font lookup dictionary.
315
+ """
316
+
317
+ fname: str = ''
318
+ name: str = ''
319
+ style: str = 'normal'
320
+ variant: str = 'normal'
321
+ weight: str | int = 'normal'
322
+ stretch: str = 'normal'
323
+ size: str = 'medium'
324
+
325
+ def _repr_html_(self) -> str:
326
+ png_stream = self._repr_png_()
327
+ png_b64 = b64encode(png_stream).decode()
328
+ return f"<img src=\"data:image/png;base64, {png_b64}\" />"
329
+
330
+ def _repr_png_(self) -> bytes:
331
+ from matplotlib.figure import Figure # Circular import.
332
+ fig = Figure()
333
+ font_path = Path(self.fname) if self.fname != '' else None
334
+ fig.text(0, 0, self.name, font=font_path)
335
+ with BytesIO() as buf:
336
+ fig.savefig(buf, bbox_inches='tight', transparent=True)
337
+ return buf.getvalue()
338
+
339
+
340
+ def ttfFontProperty(font):
341
+ """
342
+ Extract information from a TrueType font file.
343
+
344
+ Parameters
345
+ ----------
346
+ font : `.FT2Font`
347
+ The TrueType font file from which information will be extracted.
348
+
349
+ Returns
350
+ -------
351
+ `FontEntry`
352
+ The extracted font properties.
353
+
354
+ """
355
+ name = font.family_name
356
+
357
+ # Styles are: italic, oblique, and normal (default)
358
+
359
+ sfnt = font.get_sfnt()
360
+ mac_key = (1, # platform: macintosh
361
+ 0, # id: roman
362
+ 0) # langid: english
363
+ ms_key = (3, # platform: microsoft
364
+ 1, # id: unicode_cs
365
+ 0x0409) # langid: english_united_states
366
+
367
+ # These tables are actually mac_roman-encoded, but mac_roman support may be
368
+ # missing in some alternative Python implementations and we are only going
369
+ # to look for ASCII substrings, where any ASCII-compatible encoding works
370
+ # - or big-endian UTF-16, since important Microsoft fonts use that.
371
+ sfnt2 = (sfnt.get((*mac_key, 2), b'').decode('latin-1').lower() or
372
+ sfnt.get((*ms_key, 2), b'').decode('utf_16_be').lower())
373
+ sfnt4 = (sfnt.get((*mac_key, 4), b'').decode('latin-1').lower() or
374
+ sfnt.get((*ms_key, 4), b'').decode('utf_16_be').lower())
375
+
376
+ if sfnt4.find('oblique') >= 0:
377
+ style = 'oblique'
378
+ elif sfnt4.find('italic') >= 0:
379
+ style = 'italic'
380
+ elif sfnt2.find('regular') >= 0:
381
+ style = 'normal'
382
+ elif ft2font.StyleFlags.ITALIC in font.style_flags:
383
+ style = 'italic'
384
+ else:
385
+ style = 'normal'
386
+
387
+ # Variants are: small-caps and normal (default)
388
+
389
+ # !!!! Untested
390
+ if name.lower() in ['capitals', 'small-caps']:
391
+ variant = 'small-caps'
392
+ else:
393
+ variant = 'normal'
394
+
395
+ # The weight-guessing algorithm is directly translated from fontconfig
396
+ # 2.13.1's FcFreeTypeQueryFaceInternal (fcfreetype.c).
397
+ wws_subfamily = 22
398
+ typographic_subfamily = 16
399
+ font_subfamily = 2
400
+ styles = [
401
+ sfnt.get((*mac_key, wws_subfamily), b'').decode('latin-1'),
402
+ sfnt.get((*mac_key, typographic_subfamily), b'').decode('latin-1'),
403
+ sfnt.get((*mac_key, font_subfamily), b'').decode('latin-1'),
404
+ sfnt.get((*ms_key, wws_subfamily), b'').decode('utf-16-be'),
405
+ sfnt.get((*ms_key, typographic_subfamily), b'').decode('utf-16-be'),
406
+ sfnt.get((*ms_key, font_subfamily), b'').decode('utf-16-be'),
407
+ ]
408
+ styles = [*filter(None, styles)] or [font.style_name]
409
+
410
+ def get_weight(): # From fontconfig's FcFreeTypeQueryFaceInternal.
411
+ # OS/2 table weight.
412
+ os2 = font.get_sfnt_table("OS/2")
413
+ if os2 and os2["version"] != 0xffff:
414
+ return os2["usWeightClass"]
415
+ # PostScript font info weight.
416
+ try:
417
+ ps_font_info_weight = (
418
+ font.get_ps_font_info()["weight"].replace(" ", "") or "")
419
+ except ValueError:
420
+ pass
421
+ else:
422
+ for regex, weight in _weight_regexes:
423
+ if re.fullmatch(regex, ps_font_info_weight, re.I):
424
+ return weight
425
+ # Style name weight.
426
+ for style in styles:
427
+ style = style.replace(" ", "")
428
+ for regex, weight in _weight_regexes:
429
+ if re.search(regex, style, re.I):
430
+ return weight
431
+ if ft2font.StyleFlags.BOLD in font.style_flags:
432
+ return 700 # "bold"
433
+ return 500 # "medium", not "regular"!
434
+
435
+ weight = int(get_weight())
436
+
437
+ # Stretch can be absolute and relative
438
+ # Absolute stretches are: ultra-condensed, extra-condensed, condensed,
439
+ # semi-condensed, normal, semi-expanded, expanded, extra-expanded,
440
+ # and ultra-expanded.
441
+ # Relative stretches are: wider, narrower
442
+ # Child value is: inherit
443
+
444
+ if any(word in sfnt4 for word in ['narrow', 'condensed', 'cond']):
445
+ stretch = 'condensed'
446
+ elif 'demi cond' in sfnt4:
447
+ stretch = 'semi-condensed'
448
+ elif any(word in sfnt4 for word in ['wide', 'expanded', 'extended']):
449
+ stretch = 'expanded'
450
+ else:
451
+ stretch = 'normal'
452
+
453
+ # Sizes can be absolute and relative.
454
+ # Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
455
+ # and xx-large.
456
+ # Relative sizes are: larger, smaller
457
+ # Length value is an absolute font size, e.g., 12pt
458
+ # Percentage values are in 'em's. Most robust specification.
459
+
460
+ if not font.scalable:
461
+ raise NotImplementedError("Non-scalable fonts are not supported")
462
+ size = 'scalable'
463
+
464
+ return FontEntry(font.fname, name, style, variant, weight, stretch, size)
465
+
466
+
467
+ def afmFontProperty(fontpath, font):
468
+ """
469
+ Extract information from an AFM font file.
470
+
471
+ Parameters
472
+ ----------
473
+ fontpath : str
474
+ The filename corresponding to *font*.
475
+ font : AFM
476
+ The AFM font file from which information will be extracted.
477
+
478
+ Returns
479
+ -------
480
+ `FontEntry`
481
+ The extracted font properties.
482
+ """
483
+
484
+ name = font.get_familyname()
485
+ fontname = font.get_fontname().lower()
486
+
487
+ # Styles are: italic, oblique, and normal (default)
488
+
489
+ if font.get_angle() != 0 or 'italic' in name.lower():
490
+ style = 'italic'
491
+ elif 'oblique' in name.lower():
492
+ style = 'oblique'
493
+ else:
494
+ style = 'normal'
495
+
496
+ # Variants are: small-caps and normal (default)
497
+
498
+ # !!!! Untested
499
+ if name.lower() in ['capitals', 'small-caps']:
500
+ variant = 'small-caps'
501
+ else:
502
+ variant = 'normal'
503
+
504
+ weight = font.get_weight().lower()
505
+ if weight not in weight_dict:
506
+ weight = 'normal'
507
+
508
+ # Stretch can be absolute and relative
509
+ # Absolute stretches are: ultra-condensed, extra-condensed, condensed,
510
+ # semi-condensed, normal, semi-expanded, expanded, extra-expanded,
511
+ # and ultra-expanded.
512
+ # Relative stretches are: wider, narrower
513
+ # Child value is: inherit
514
+ if 'demi cond' in fontname:
515
+ stretch = 'semi-condensed'
516
+ elif any(word in fontname for word in ['narrow', 'cond']):
517
+ stretch = 'condensed'
518
+ elif any(word in fontname for word in ['wide', 'expanded', 'extended']):
519
+ stretch = 'expanded'
520
+ else:
521
+ stretch = 'normal'
522
+
523
+ # Sizes can be absolute and relative.
524
+ # Absolute sizes are: xx-small, x-small, small, medium, large, x-large,
525
+ # and xx-large.
526
+ # Relative sizes are: larger, smaller
527
+ # Length value is an absolute font size, e.g., 12pt
528
+ # Percentage values are in 'em's. Most robust specification.
529
+
530
+ # All AFM fonts are apparently scalable.
531
+
532
+ size = 'scalable'
533
+
534
+ return FontEntry(fontpath, name, style, variant, weight, stretch, size)
535
+
536
+
537
+ def _cleanup_fontproperties_init(init_method):
538
+ """
539
+ A decorator to limit the call signature to single a positional argument
540
+ or alternatively only keyword arguments.
541
+
542
+ We still accept but deprecate all other call signatures.
543
+
544
+ When the deprecation expires we can switch the signature to::
545
+
546
+ __init__(self, pattern=None, /, *, family=None, style=None, ...)
547
+
548
+ plus a runtime check that pattern is not used alongside with the
549
+ keyword arguments. This results eventually in the two possible
550
+ call signatures::
551
+
552
+ FontProperties(pattern)
553
+ FontProperties(family=..., size=..., ...)
554
+
555
+ """
556
+ @functools.wraps(init_method)
557
+ def wrapper(self, *args, **kwargs):
558
+ # multiple args with at least some positional ones
559
+ if len(args) > 1 or len(args) == 1 and kwargs:
560
+ # Note: Both cases were previously handled as individual properties.
561
+ # Therefore, we do not mention the case of font properties here.
562
+ _api.warn_deprecated(
563
+ "3.10",
564
+ message="Passing individual properties to FontProperties() "
565
+ "positionally was deprecated in Matplotlib %(since)s and "
566
+ "will be removed in %(removal)s. Please pass all properties "
567
+ "via keyword arguments."
568
+ )
569
+ # single non-string arg -> clearly a family not a pattern
570
+ if len(args) == 1 and not kwargs and not cbook.is_scalar_or_string(args[0]):
571
+ # Case font-family list passed as single argument
572
+ _api.warn_deprecated(
573
+ "3.10",
574
+ message="Passing family as positional argument to FontProperties() "
575
+ "was deprecated in Matplotlib %(since)s and will be removed "
576
+ "in %(removal)s. Please pass family names as keyword"
577
+ "argument."
578
+ )
579
+ # Note on single string arg:
580
+ # This has been interpreted as pattern so far. We are already raising if a
581
+ # non-pattern compatible family string was given. Therefore, we do not need
582
+ # to warn for this case.
583
+ return init_method(self, *args, **kwargs)
584
+
585
+ return wrapper
586
+
587
+
588
+ class FontProperties:
589
+ """
590
+ A class for storing and manipulating font properties.
591
+
592
+ The font properties are the six properties described in the
593
+ `W3C Cascading Style Sheet, Level 1
594
+ <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ font
595
+ specification and *math_fontfamily* for math fonts:
596
+
597
+ - family: A list of font names in decreasing order of priority.
598
+ The items may include a generic font family name, either 'sans-serif',
599
+ 'serif', 'cursive', 'fantasy', or 'monospace'. In that case, the actual
600
+ font to be used will be looked up from the associated rcParam during the
601
+ search process in `.findfont`. Default: :rc:`font.family`
602
+
603
+ - style: Either 'normal', 'italic' or 'oblique'.
604
+ Default: :rc:`font.style`
605
+
606
+ - variant: Either 'normal' or 'small-caps'.
607
+ Default: :rc:`font.variant`
608
+
609
+ - stretch: A numeric value in the range 0-1000 or one of
610
+ 'ultra-condensed', 'extra-condensed', 'condensed',
611
+ 'semi-condensed', 'normal', 'semi-expanded', 'expanded',
612
+ 'extra-expanded' or 'ultra-expanded'. Default: :rc:`font.stretch`
613
+
614
+ - weight: A numeric value in the range 0-1000 or one of
615
+ 'ultralight', 'light', 'normal', 'regular', 'book', 'medium',
616
+ 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy',
617
+ 'extra bold', 'black'. Default: :rc:`font.weight`
618
+
619
+ - size: Either a relative value of 'xx-small', 'x-small',
620
+ 'small', 'medium', 'large', 'x-large', 'xx-large' or an
621
+ absolute font size, e.g., 10. Default: :rc:`font.size`
622
+
623
+ - math_fontfamily: The family of fonts used to render math text.
624
+ Supported values are: 'dejavusans', 'dejavuserif', 'cm',
625
+ 'stix', 'stixsans' and 'custom'. Default: :rc:`mathtext.fontset`
626
+
627
+ Alternatively, a font may be specified using the absolute path to a font
628
+ file, by using the *fname* kwarg. However, in this case, it is typically
629
+ simpler to just pass the path (as a `pathlib.Path`, not a `str`) to the
630
+ *font* kwarg of the `.Text` object.
631
+
632
+ The preferred usage of font sizes is to use the relative values,
633
+ e.g., 'large', instead of absolute font sizes, e.g., 12. This
634
+ approach allows all text sizes to be made larger or smaller based
635
+ on the font manager's default font size.
636
+
637
+ This class accepts a single positional string as fontconfig_ pattern_,
638
+ or alternatively individual properties as keyword arguments::
639
+
640
+ FontProperties(pattern)
641
+ FontProperties(*, family=None, style=None, variant=None, ...)
642
+
643
+ This support does not depend on fontconfig; we are merely borrowing its
644
+ pattern syntax for use here.
645
+
646
+ .. _fontconfig: https://www.freedesktop.org/wiki/Software/fontconfig/
647
+ .. _pattern:
648
+ https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
649
+
650
+ Note that Matplotlib's internal font manager and fontconfig use a
651
+ different algorithm to lookup fonts, so the results of the same pattern
652
+ may be different in Matplotlib than in other applications that use
653
+ fontconfig.
654
+ """
655
+
656
+ @_cleanup_fontproperties_init
657
+ def __init__(self, family=None, style=None, variant=None, weight=None,
658
+ stretch=None, size=None,
659
+ fname=None, # if set, it's a hardcoded filename to use
660
+ math_fontfamily=None):
661
+ self.set_family(family)
662
+ self.set_style(style)
663
+ self.set_variant(variant)
664
+ self.set_weight(weight)
665
+ self.set_stretch(stretch)
666
+ self.set_file(fname)
667
+ self.set_size(size)
668
+ self.set_math_fontfamily(math_fontfamily)
669
+ # Treat family as a fontconfig pattern if it is the only parameter
670
+ # provided. Even in that case, call the other setters first to set
671
+ # attributes not specified by the pattern to the rcParams defaults.
672
+ if (isinstance(family, str)
673
+ and style is None and variant is None and weight is None
674
+ and stretch is None and size is None and fname is None):
675
+ self.set_fontconfig_pattern(family)
676
+
677
+ @classmethod
678
+ def _from_any(cls, arg):
679
+ """
680
+ Generic constructor which can build a `.FontProperties` from any of the
681
+ following:
682
+
683
+ - a `.FontProperties`: it is passed through as is;
684
+ - `None`: a `.FontProperties` using rc values is used;
685
+ - an `os.PathLike`: it is used as path to the font file;
686
+ - a `str`: it is parsed as a fontconfig pattern;
687
+ - a `dict`: it is passed as ``**kwargs`` to `.FontProperties`.
688
+ """
689
+ if arg is None:
690
+ return cls()
691
+ elif isinstance(arg, cls):
692
+ return arg
693
+ elif isinstance(arg, os.PathLike):
694
+ return cls(fname=arg)
695
+ elif isinstance(arg, str):
696
+ return cls(arg)
697
+ else:
698
+ return cls(**arg)
699
+
700
+ def __hash__(self):
701
+ l = (tuple(self.get_family()),
702
+ self.get_slant(),
703
+ self.get_variant(),
704
+ self.get_weight(),
705
+ self.get_stretch(),
706
+ self.get_size(),
707
+ self.get_file(),
708
+ self.get_math_fontfamily())
709
+ return hash(l)
710
+
711
+ def __eq__(self, other):
712
+ return hash(self) == hash(other)
713
+
714
+ def __str__(self):
715
+ return self.get_fontconfig_pattern()
716
+
717
+ def get_family(self):
718
+ """
719
+ Return a list of individual font family names or generic family names.
720
+
721
+ The font families or generic font families (which will be resolved
722
+ from their respective rcParams when searching for a matching font) in
723
+ the order of preference.
724
+ """
725
+ return self._family
726
+
727
+ def get_name(self):
728
+ """
729
+ Return the name of the font that best matches the font properties.
730
+ """
731
+ return get_font(findfont(self)).family_name
732
+
733
+ def get_style(self):
734
+ """
735
+ Return the font style. Values are: 'normal', 'italic' or 'oblique'.
736
+ """
737
+ return self._slant
738
+
739
+ def get_variant(self):
740
+ """
741
+ Return the font variant. Values are: 'normal' or 'small-caps'.
742
+ """
743
+ return self._variant
744
+
745
+ def get_weight(self):
746
+ """
747
+ Set the font weight. Options are: A numeric value in the
748
+ range 0-1000 or one of 'light', 'normal', 'regular', 'book',
749
+ 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold',
750
+ 'heavy', 'extra bold', 'black'
751
+ """
752
+ return self._weight
753
+
754
+ def get_stretch(self):
755
+ """
756
+ Return the font stretch or width. Options are: 'ultra-condensed',
757
+ 'extra-condensed', 'condensed', 'semi-condensed', 'normal',
758
+ 'semi-expanded', 'expanded', 'extra-expanded', 'ultra-expanded'.
759
+ """
760
+ return self._stretch
761
+
762
+ def get_size(self):
763
+ """
764
+ Return the font size.
765
+ """
766
+ return self._size
767
+
768
+ def get_file(self):
769
+ """
770
+ Return the filename of the associated font.
771
+ """
772
+ return self._file
773
+
774
+ def get_fontconfig_pattern(self):
775
+ """
776
+ Get a fontconfig_ pattern_ suitable for looking up the font as
777
+ specified with fontconfig's ``fc-match`` utility.
778
+
779
+ This support does not depend on fontconfig; we are merely borrowing its
780
+ pattern syntax for use here.
781
+ """
782
+ return generate_fontconfig_pattern(self)
783
+
784
+ def set_family(self, family):
785
+ """
786
+ Change the font family. Can be either an alias (generic name
787
+ is CSS parlance), such as: 'serif', 'sans-serif', 'cursive',
788
+ 'fantasy', or 'monospace', a real font name or a list of real
789
+ font names. Real font names are not supported when
790
+ :rc:`text.usetex` is `True`. Default: :rc:`font.family`
791
+ """
792
+ if family is None:
793
+ family = mpl.rcParams['font.family']
794
+ if isinstance(family, str):
795
+ family = [family]
796
+ self._family = family
797
+
798
+ def set_style(self, style):
799
+ """
800
+ Set the font style.
801
+
802
+ Parameters
803
+ ----------
804
+ style : {'normal', 'italic', 'oblique'}, default: :rc:`font.style`
805
+ """
806
+ if style is None:
807
+ style = mpl.rcParams['font.style']
808
+ _api.check_in_list(['normal', 'italic', 'oblique'], style=style)
809
+ self._slant = style
810
+
811
+ def set_variant(self, variant):
812
+ """
813
+ Set the font variant.
814
+
815
+ Parameters
816
+ ----------
817
+ variant : {'normal', 'small-caps'}, default: :rc:`font.variant`
818
+ """
819
+ if variant is None:
820
+ variant = mpl.rcParams['font.variant']
821
+ _api.check_in_list(['normal', 'small-caps'], variant=variant)
822
+ self._variant = variant
823
+
824
+ def set_weight(self, weight):
825
+ """
826
+ Set the font weight.
827
+
828
+ Parameters
829
+ ----------
830
+ weight : int or {'ultralight', 'light', 'normal', 'regular', 'book', \
831
+ 'medium', 'roman', 'semibold', 'demibold', 'demi', 'bold', 'heavy', \
832
+ 'extra bold', 'black'}, default: :rc:`font.weight`
833
+ If int, must be in the range 0-1000.
834
+ """
835
+ if weight is None:
836
+ weight = mpl.rcParams['font.weight']
837
+ if weight in weight_dict:
838
+ self._weight = weight
839
+ return
840
+ try:
841
+ weight = int(weight)
842
+ except ValueError:
843
+ pass
844
+ else:
845
+ if 0 <= weight <= 1000:
846
+ self._weight = weight
847
+ return
848
+ raise ValueError(f"{weight=} is invalid")
849
+
850
+ def set_stretch(self, stretch):
851
+ """
852
+ Set the font stretch or width.
853
+
854
+ Parameters
855
+ ----------
856
+ stretch : int or {'ultra-condensed', 'extra-condensed', 'condensed', \
857
+ 'semi-condensed', 'normal', 'semi-expanded', 'expanded', 'extra-expanded', \
858
+ 'ultra-expanded'}, default: :rc:`font.stretch`
859
+ If int, must be in the range 0-1000.
860
+ """
861
+ if stretch is None:
862
+ stretch = mpl.rcParams['font.stretch']
863
+ if stretch in stretch_dict:
864
+ self._stretch = stretch
865
+ return
866
+ try:
867
+ stretch = int(stretch)
868
+ except ValueError:
869
+ pass
870
+ else:
871
+ if 0 <= stretch <= 1000:
872
+ self._stretch = stretch
873
+ return
874
+ raise ValueError(f"{stretch=} is invalid")
875
+
876
+ def set_size(self, size):
877
+ """
878
+ Set the font size.
879
+
880
+ Parameters
881
+ ----------
882
+ size : float or {'xx-small', 'x-small', 'small', 'medium', \
883
+ 'large', 'x-large', 'xx-large'}, default: :rc:`font.size`
884
+ If a float, the font size in points. The string values denote
885
+ sizes relative to the default font size.
886
+ """
887
+ if size is None:
888
+ size = mpl.rcParams['font.size']
889
+ try:
890
+ size = float(size)
891
+ except ValueError:
892
+ try:
893
+ scale = font_scalings[size]
894
+ except KeyError as err:
895
+ raise ValueError(
896
+ "Size is invalid. Valid font size are "
897
+ + ", ".join(map(str, font_scalings))) from err
898
+ else:
899
+ size = scale * FontManager.get_default_size()
900
+ if size < 1.0:
901
+ _log.info('Fontsize %1.2f < 1.0 pt not allowed by FreeType. '
902
+ 'Setting fontsize = 1 pt', size)
903
+ size = 1.0
904
+ self._size = size
905
+
906
+ def set_file(self, file):
907
+ """
908
+ Set the filename of the fontfile to use. In this case, all
909
+ other properties will be ignored.
910
+ """
911
+ self._file = os.fspath(file) if file is not None else None
912
+
913
+ def set_fontconfig_pattern(self, pattern):
914
+ """
915
+ Set the properties by parsing a fontconfig_ *pattern*.
916
+
917
+ This support does not depend on fontconfig; we are merely borrowing its
918
+ pattern syntax for use here.
919
+ """
920
+ for key, val in parse_fontconfig_pattern(pattern).items():
921
+ if type(val) is list:
922
+ getattr(self, "set_" + key)(val[0])
923
+ else:
924
+ getattr(self, "set_" + key)(val)
925
+
926
+ def get_math_fontfamily(self):
927
+ """
928
+ Return the name of the font family used for math text.
929
+
930
+ The default font is :rc:`mathtext.fontset`.
931
+ """
932
+ return self._math_fontfamily
933
+
934
+ def set_math_fontfamily(self, fontfamily):
935
+ """
936
+ Set the font family for text in math mode.
937
+
938
+ If not set explicitly, :rc:`mathtext.fontset` will be used.
939
+
940
+ Parameters
941
+ ----------
942
+ fontfamily : str
943
+ The name of the font family.
944
+
945
+ Available font families are defined in the
946
+ :ref:`default matplotlibrc file <customizing-with-matplotlibrc-files>`.
947
+
948
+ See Also
949
+ --------
950
+ .text.Text.get_math_fontfamily
951
+ """
952
+ if fontfamily is None:
953
+ fontfamily = mpl.rcParams['mathtext.fontset']
954
+ else:
955
+ valid_fonts = _validators['mathtext.fontset'].valid.values()
956
+ # _check_in_list() Validates the parameter math_fontfamily as
957
+ # if it were passed to rcParams['mathtext.fontset']
958
+ _api.check_in_list(valid_fonts, math_fontfamily=fontfamily)
959
+ self._math_fontfamily = fontfamily
960
+
961
+ def copy(self):
962
+ """Return a copy of self."""
963
+ return copy.copy(self)
964
+
965
+ # Aliases
966
+ set_name = set_family
967
+ get_slant = get_style
968
+ set_slant = set_style
969
+ get_size_in_points = get_size
970
+
971
+
972
+ class _JSONEncoder(json.JSONEncoder):
973
+ def default(self, o):
974
+ if isinstance(o, FontManager):
975
+ return dict(o.__dict__, __class__='FontManager')
976
+ elif isinstance(o, FontEntry):
977
+ d = dict(o.__dict__, __class__='FontEntry')
978
+ try:
979
+ # Cache paths of fonts shipped with Matplotlib relative to the
980
+ # Matplotlib data path, which helps in the presence of venvs.
981
+ d["fname"] = str(Path(d["fname"]).relative_to(mpl.get_data_path()))
982
+ except ValueError:
983
+ pass
984
+ return d
985
+ else:
986
+ return super().default(o)
987
+
988
+
989
+ def _json_decode(o):
990
+ cls = o.pop('__class__', None)
991
+ if cls is None:
992
+ return o
993
+ elif cls == 'FontManager':
994
+ r = FontManager.__new__(FontManager)
995
+ r.__dict__.update(o)
996
+ return r
997
+ elif cls == 'FontEntry':
998
+ if not os.path.isabs(o['fname']):
999
+ o['fname'] = os.path.join(mpl.get_data_path(), o['fname'])
1000
+ r = FontEntry(**o)
1001
+ return r
1002
+ else:
1003
+ raise ValueError("Don't know how to deserialize __class__=%s" % cls)
1004
+
1005
+
1006
+ def json_dump(data, filename):
1007
+ """
1008
+ Dump `FontManager` *data* as JSON to the file named *filename*.
1009
+
1010
+ See Also
1011
+ --------
1012
+ json_load
1013
+
1014
+ Notes
1015
+ -----
1016
+ File paths that are children of the Matplotlib data path (typically, fonts
1017
+ shipped with Matplotlib) are stored relative to that data path (to remain
1018
+ valid across virtualenvs).
1019
+
1020
+ This function temporarily locks the output file to prevent multiple
1021
+ processes from overwriting one another's output.
1022
+ """
1023
+ try:
1024
+ with cbook._lock_path(filename), open(filename, 'w') as fh:
1025
+ json.dump(data, fh, cls=_JSONEncoder, indent=2)
1026
+ except OSError as e:
1027
+ _log.warning('Could not save font_manager cache %s', e)
1028
+
1029
+
1030
+ def json_load(filename):
1031
+ """
1032
+ Load a `FontManager` from the JSON file named *filename*.
1033
+
1034
+ See Also
1035
+ --------
1036
+ json_dump
1037
+ """
1038
+ with open(filename) as fh:
1039
+ return json.load(fh, object_hook=_json_decode)
1040
+
1041
+
1042
+ class FontManager:
1043
+ """
1044
+ On import, the `FontManager` singleton instance creates a list of ttf and
1045
+ afm fonts and caches their `FontProperties`. The `FontManager.findfont`
1046
+ method does a nearest neighbor search to find the font that most closely
1047
+ matches the specification. If no good enough match is found, the default
1048
+ font is returned.
1049
+
1050
+ Fonts added with the `FontManager.addfont` method will not persist in the
1051
+ cache; therefore, `addfont` will need to be called every time Matplotlib is
1052
+ imported. This method should only be used if and when a font cannot be
1053
+ installed on your operating system by other means.
1054
+
1055
+ Notes
1056
+ -----
1057
+ The `FontManager.addfont` method must be called on the global `FontManager`
1058
+ instance.
1059
+
1060
+ Example usage::
1061
+
1062
+ import matplotlib.pyplot as plt
1063
+ from matplotlib import font_manager
1064
+
1065
+ font_dirs = ["/resources/fonts"] # The path to the custom font file.
1066
+ font_files = font_manager.findSystemFonts(fontpaths=font_dirs)
1067
+
1068
+ for font_file in font_files:
1069
+ font_manager.fontManager.addfont(font_file)
1070
+ """
1071
+ # Increment this version number whenever the font cache data
1072
+ # format or behavior has changed and requires an existing font
1073
+ # cache files to be rebuilt.
1074
+ __version__ = 390
1075
+
1076
+ def __init__(self, size=None, weight='normal'):
1077
+ self._version = self.__version__
1078
+
1079
+ self.__default_weight = weight
1080
+ self.default_size = size
1081
+
1082
+ # Create list of font paths.
1083
+ paths = [cbook._get_data_path('fonts', subdir)
1084
+ for subdir in ['ttf', 'afm', 'pdfcorefonts']]
1085
+ _log.debug('font search path %s', paths)
1086
+
1087
+ self.defaultFamily = {
1088
+ 'ttf': 'DejaVu Sans',
1089
+ 'afm': 'Helvetica'}
1090
+
1091
+ self.afmlist = []
1092
+ self.ttflist = []
1093
+
1094
+ # Delay the warning by 5s.
1095
+ timer = threading.Timer(5, lambda: _log.warning(
1096
+ 'Matplotlib is building the font cache; this may take a moment.'))
1097
+ timer.start()
1098
+ try:
1099
+ for fontext in ["afm", "ttf"]:
1100
+ for path in [*findSystemFonts(paths, fontext=fontext),
1101
+ *findSystemFonts(fontext=fontext)]:
1102
+ try:
1103
+ self.addfont(path)
1104
+ except OSError as exc:
1105
+ _log.info("Failed to open font file %s: %s", path, exc)
1106
+ except Exception as exc:
1107
+ _log.info("Failed to extract font properties from %s: "
1108
+ "%s", path, exc)
1109
+ finally:
1110
+ timer.cancel()
1111
+
1112
+ def addfont(self, path):
1113
+ """
1114
+ Cache the properties of the font at *path* to make it available to the
1115
+ `FontManager`. The type of font is inferred from the path suffix.
1116
+
1117
+ Parameters
1118
+ ----------
1119
+ path : str or path-like
1120
+
1121
+ Notes
1122
+ -----
1123
+ This method is useful for adding a custom font without installing it in
1124
+ your operating system. See the `FontManager` singleton instance for
1125
+ usage and caveats about this function.
1126
+ """
1127
+ # Convert to string in case of a path as
1128
+ # afmFontProperty and FT2Font expect this
1129
+ path = os.fsdecode(path)
1130
+ if Path(path).suffix.lower() == ".afm":
1131
+ with open(path, "rb") as fh:
1132
+ font = _afm.AFM(fh)
1133
+ prop = afmFontProperty(path, font)
1134
+ self.afmlist.append(prop)
1135
+ else:
1136
+ font = ft2font.FT2Font(path)
1137
+ prop = ttfFontProperty(font)
1138
+ self.ttflist.append(prop)
1139
+ self._findfont_cached.cache_clear()
1140
+
1141
+ @property
1142
+ def defaultFont(self):
1143
+ # Lazily evaluated (findfont then caches the result) to avoid including
1144
+ # the venv path in the json serialization.
1145
+ return {ext: self.findfont(family, fontext=ext)
1146
+ for ext, family in self.defaultFamily.items()}
1147
+
1148
+ def get_default_weight(self):
1149
+ """
1150
+ Return the default font weight.
1151
+ """
1152
+ return self.__default_weight
1153
+
1154
+ @staticmethod
1155
+ def get_default_size():
1156
+ """
1157
+ Return the default font size.
1158
+ """
1159
+ return mpl.rcParams['font.size']
1160
+
1161
+ def set_default_weight(self, weight):
1162
+ """
1163
+ Set the default font weight. The initial value is 'normal'.
1164
+ """
1165
+ self.__default_weight = weight
1166
+
1167
+ @staticmethod
1168
+ def _expand_aliases(family):
1169
+ if family in ('sans', 'sans serif'):
1170
+ family = 'sans-serif'
1171
+ return mpl.rcParams['font.' + family]
1172
+
1173
+ # Each of the scoring functions below should return a value between
1174
+ # 0.0 (perfect match) and 1.0 (terrible match)
1175
+ def score_family(self, families, family2):
1176
+ """
1177
+ Return a match score between the list of font families in
1178
+ *families* and the font family name *family2*.
1179
+
1180
+ An exact match at the head of the list returns 0.0.
1181
+
1182
+ A match further down the list will return between 0 and 1.
1183
+
1184
+ No match will return 1.0.
1185
+ """
1186
+ if not isinstance(families, (list, tuple)):
1187
+ families = [families]
1188
+ elif len(families) == 0:
1189
+ return 1.0
1190
+ family2 = family2.lower()
1191
+ step = 1 / len(families)
1192
+ for i, family1 in enumerate(families):
1193
+ family1 = family1.lower()
1194
+ if family1 in font_family_aliases:
1195
+ options = [*map(str.lower, self._expand_aliases(family1))]
1196
+ if family2 in options:
1197
+ idx = options.index(family2)
1198
+ return (i + (idx / len(options))) * step
1199
+ elif family1 == family2:
1200
+ # The score should be weighted by where in the
1201
+ # list the font was found.
1202
+ return i * step
1203
+ return 1.0
1204
+
1205
+ def score_style(self, style1, style2):
1206
+ """
1207
+ Return a match score between *style1* and *style2*.
1208
+
1209
+ An exact match returns 0.0.
1210
+
1211
+ A match between 'italic' and 'oblique' returns 0.1.
1212
+
1213
+ No match returns 1.0.
1214
+ """
1215
+ if style1 == style2:
1216
+ return 0.0
1217
+ elif (style1 in ('italic', 'oblique')
1218
+ and style2 in ('italic', 'oblique')):
1219
+ return 0.1
1220
+ return 1.0
1221
+
1222
+ def score_variant(self, variant1, variant2):
1223
+ """
1224
+ Return a match score between *variant1* and *variant2*.
1225
+
1226
+ An exact match returns 0.0, otherwise 1.0.
1227
+ """
1228
+ if variant1 == variant2:
1229
+ return 0.0
1230
+ else:
1231
+ return 1.0
1232
+
1233
+ def score_stretch(self, stretch1, stretch2):
1234
+ """
1235
+ Return a match score between *stretch1* and *stretch2*.
1236
+
1237
+ The result is the absolute value of the difference between the
1238
+ CSS numeric values of *stretch1* and *stretch2*, normalized
1239
+ between 0.0 and 1.0.
1240
+ """
1241
+ try:
1242
+ stretchval1 = int(stretch1)
1243
+ except ValueError:
1244
+ stretchval1 = stretch_dict.get(stretch1, 500)
1245
+ try:
1246
+ stretchval2 = int(stretch2)
1247
+ except ValueError:
1248
+ stretchval2 = stretch_dict.get(stretch2, 500)
1249
+ return abs(stretchval1 - stretchval2) / 1000.0
1250
+
1251
+ def score_weight(self, weight1, weight2):
1252
+ """
1253
+ Return a match score between *weight1* and *weight2*.
1254
+
1255
+ The result is 0.0 if both weight1 and weight 2 are given as strings
1256
+ and have the same value.
1257
+
1258
+ Otherwise, the result is the absolute value of the difference between
1259
+ the CSS numeric values of *weight1* and *weight2*, normalized between
1260
+ 0.05 and 1.0.
1261
+ """
1262
+ # exact match of the weight names, e.g. weight1 == weight2 == "regular"
1263
+ if cbook._str_equal(weight1, weight2):
1264
+ return 0.0
1265
+ w1 = weight1 if isinstance(weight1, Number) else weight_dict[weight1]
1266
+ w2 = weight2 if isinstance(weight2, Number) else weight_dict[weight2]
1267
+ return 0.95 * (abs(w1 - w2) / 1000) + 0.05
1268
+
1269
+ def score_size(self, size1, size2):
1270
+ """
1271
+ Return a match score between *size1* and *size2*.
1272
+
1273
+ If *size2* (the size specified in the font file) is 'scalable', this
1274
+ function always returns 0.0, since any font size can be generated.
1275
+
1276
+ Otherwise, the result is the absolute distance between *size1* and
1277
+ *size2*, normalized so that the usual range of font sizes (6pt -
1278
+ 72pt) will lie between 0.0 and 1.0.
1279
+ """
1280
+ if size2 == 'scalable':
1281
+ return 0.0
1282
+ # Size value should have already been
1283
+ try:
1284
+ sizeval1 = float(size1)
1285
+ except ValueError:
1286
+ sizeval1 = self.default_size * font_scalings[size1]
1287
+ try:
1288
+ sizeval2 = float(size2)
1289
+ except ValueError:
1290
+ return 1.0
1291
+ return abs(sizeval1 - sizeval2) / 72
1292
+
1293
+ def findfont(self, prop, fontext='ttf', directory=None,
1294
+ fallback_to_default=True, rebuild_if_missing=True):
1295
+ """
1296
+ Find the path to the font file most closely matching the given font properties.
1297
+
1298
+ Parameters
1299
+ ----------
1300
+ prop : str or `~matplotlib.font_manager.FontProperties`
1301
+ The font properties to search for. This can be either a
1302
+ `.FontProperties` object or a string defining a
1303
+ `fontconfig patterns`_.
1304
+
1305
+ fontext : {'ttf', 'afm'}, default: 'ttf'
1306
+ The extension of the font file:
1307
+
1308
+ - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
1309
+ - 'afm': Adobe Font Metrics (.afm)
1310
+
1311
+ directory : str, optional
1312
+ If given, only search this directory and its subdirectories.
1313
+
1314
+ fallback_to_default : bool
1315
+ If True, will fall back to the default font family (usually
1316
+ "DejaVu Sans" or "Helvetica") if the first lookup hard-fails.
1317
+
1318
+ rebuild_if_missing : bool
1319
+ Whether to rebuild the font cache and search again if the first
1320
+ match appears to point to a nonexisting font (i.e., the font cache
1321
+ contains outdated entries).
1322
+
1323
+ Returns
1324
+ -------
1325
+ str
1326
+ The filename of the best matching font.
1327
+
1328
+ Notes
1329
+ -----
1330
+ This performs a nearest neighbor search. Each font is given a
1331
+ similarity score to the target font properties. The first font with
1332
+ the highest score is returned. If no matches below a certain
1333
+ threshold are found, the default font (usually DejaVu Sans) is
1334
+ returned.
1335
+
1336
+ The result is cached, so subsequent lookups don't have to
1337
+ perform the O(n) nearest neighbor search.
1338
+
1339
+ See the `W3C Cascading Style Sheet, Level 1
1340
+ <http://www.w3.org/TR/1998/REC-CSS2-19980512/>`_ documentation
1341
+ for a description of the font finding algorithm.
1342
+
1343
+ .. _fontconfig patterns:
1344
+ https://www.freedesktop.org/software/fontconfig/fontconfig-user.html
1345
+ """
1346
+ # Pass the relevant rcParams (and the font manager, as `self`) to
1347
+ # _findfont_cached so to prevent using a stale cache entry after an
1348
+ # rcParam was changed.
1349
+ rc_params = tuple(tuple(mpl.rcParams[key]) for key in [
1350
+ "font.serif", "font.sans-serif", "font.cursive", "font.fantasy",
1351
+ "font.monospace"])
1352
+ ret = self._findfont_cached(
1353
+ prop, fontext, directory, fallback_to_default, rebuild_if_missing,
1354
+ rc_params)
1355
+ if isinstance(ret, cbook._ExceptionInfo):
1356
+ raise ret.to_exception()
1357
+ return ret
1358
+
1359
+ def get_font_names(self):
1360
+ """Return the list of available fonts."""
1361
+ return list({font.name for font in self.ttflist})
1362
+
1363
+ def _find_fonts_by_props(self, prop, fontext='ttf', directory=None,
1364
+ fallback_to_default=True, rebuild_if_missing=True):
1365
+ """
1366
+ Find the paths to the font files most closely matching the given properties.
1367
+
1368
+ Parameters
1369
+ ----------
1370
+ prop : str or `~matplotlib.font_manager.FontProperties`
1371
+ The font properties to search for. This can be either a
1372
+ `.FontProperties` object or a string defining a
1373
+ `fontconfig patterns`_.
1374
+
1375
+ fontext : {'ttf', 'afm'}, default: 'ttf'
1376
+ The extension of the font file:
1377
+
1378
+ - 'ttf': TrueType and OpenType fonts (.ttf, .ttc, .otf)
1379
+ - 'afm': Adobe Font Metrics (.afm)
1380
+
1381
+ directory : str, optional
1382
+ If given, only search this directory and its subdirectories.
1383
+
1384
+ fallback_to_default : bool
1385
+ If True, will fall back to the default font family (usually
1386
+ "DejaVu Sans" or "Helvetica") if none of the families were found.
1387
+
1388
+ rebuild_if_missing : bool
1389
+ Whether to rebuild the font cache and search again if the first
1390
+ match appears to point to a nonexisting font (i.e., the font cache
1391
+ contains outdated entries).
1392
+
1393
+ Returns
1394
+ -------
1395
+ list[str]
1396
+ The paths of the fonts found.
1397
+
1398
+ Notes
1399
+ -----
1400
+ This is an extension/wrapper of the original findfont API, which only
1401
+ returns a single font for given font properties. Instead, this API
1402
+ returns a list of filepaths of multiple fonts which closely match the
1403
+ given font properties. Since this internally uses the original API,
1404
+ there's no change to the logic of performing the nearest neighbor
1405
+ search. See `findfont` for more details.
1406
+ """
1407
+
1408
+ prop = FontProperties._from_any(prop)
1409
+
1410
+ fpaths = []
1411
+ for family in prop.get_family():
1412
+ cprop = prop.copy()
1413
+ cprop.set_family(family) # set current prop's family
1414
+
1415
+ try:
1416
+ fpaths.append(
1417
+ self.findfont(
1418
+ cprop, fontext, directory,
1419
+ fallback_to_default=False, # don't fallback to default
1420
+ rebuild_if_missing=rebuild_if_missing,
1421
+ )
1422
+ )
1423
+ except ValueError:
1424
+ if family in font_family_aliases:
1425
+ _log.warning(
1426
+ "findfont: Generic family %r not found because "
1427
+ "none of the following families were found: %s",
1428
+ family, ", ".join(self._expand_aliases(family))
1429
+ )
1430
+ else:
1431
+ _log.warning("findfont: Font family %r not found.", family)
1432
+
1433
+ # only add default family if no other font was found and
1434
+ # fallback_to_default is enabled
1435
+ if not fpaths:
1436
+ if fallback_to_default:
1437
+ dfamily = self.defaultFamily[fontext]
1438
+ cprop = prop.copy()
1439
+ cprop.set_family(dfamily)
1440
+ fpaths.append(
1441
+ self.findfont(
1442
+ cprop, fontext, directory,
1443
+ fallback_to_default=True,
1444
+ rebuild_if_missing=rebuild_if_missing,
1445
+ )
1446
+ )
1447
+ else:
1448
+ raise ValueError("Failed to find any font, and fallback "
1449
+ "to the default font was disabled")
1450
+
1451
+ return fpaths
1452
+
1453
+ @lru_cache(1024)
1454
+ def _findfont_cached(self, prop, fontext, directory, fallback_to_default,
1455
+ rebuild_if_missing, rc_params):
1456
+
1457
+ prop = FontProperties._from_any(prop)
1458
+
1459
+ fname = prop.get_file()
1460
+ if fname is not None:
1461
+ return fname
1462
+
1463
+ if fontext == 'afm':
1464
+ fontlist = self.afmlist
1465
+ else:
1466
+ fontlist = self.ttflist
1467
+
1468
+ best_score = 1e64
1469
+ best_font = None
1470
+
1471
+ _log.debug('findfont: Matching %s.', prop)
1472
+ for font in fontlist:
1473
+ if (directory is not None and
1474
+ Path(directory) not in Path(font.fname).parents):
1475
+ continue
1476
+ # Matching family should have top priority, so multiply it by 10.
1477
+ score = (self.score_family(prop.get_family(), font.name) * 10
1478
+ + self.score_style(prop.get_style(), font.style)
1479
+ + self.score_variant(prop.get_variant(), font.variant)
1480
+ + self.score_weight(prop.get_weight(), font.weight)
1481
+ + self.score_stretch(prop.get_stretch(), font.stretch)
1482
+ + self.score_size(prop.get_size(), font.size))
1483
+ _log.debug('findfont: score(%s) = %s', font, score)
1484
+ if score < best_score:
1485
+ best_score = score
1486
+ best_font = font
1487
+ if score == 0:
1488
+ break
1489
+
1490
+ if best_font is None or best_score >= 10.0:
1491
+ if fallback_to_default:
1492
+ _log.warning(
1493
+ 'findfont: Font family %s not found. Falling back to %s.',
1494
+ prop.get_family(), self.defaultFamily[fontext])
1495
+ for family in map(str.lower, prop.get_family()):
1496
+ if family in font_family_aliases:
1497
+ _log.warning(
1498
+ "findfont: Generic family %r not found because "
1499
+ "none of the following families were found: %s",
1500
+ family, ", ".join(self._expand_aliases(family)))
1501
+ default_prop = prop.copy()
1502
+ default_prop.set_family(self.defaultFamily[fontext])
1503
+ return self.findfont(default_prop, fontext, directory,
1504
+ fallback_to_default=False)
1505
+ else:
1506
+ # This return instead of raise is intentional, as we wish to
1507
+ # cache that it was not found, which will not occur if it was
1508
+ # actually raised.
1509
+ return cbook._ExceptionInfo(
1510
+ ValueError,
1511
+ f"Failed to find font {prop}, and fallback to the default font was "
1512
+ f"disabled"
1513
+ )
1514
+ else:
1515
+ _log.debug('findfont: Matching %s to %s (%r) with score of %f.',
1516
+ prop, best_font.name, best_font.fname, best_score)
1517
+ result = best_font.fname
1518
+
1519
+ if not os.path.isfile(result):
1520
+ if rebuild_if_missing:
1521
+ _log.info(
1522
+ 'findfont: Found a missing font file. Rebuilding cache.')
1523
+ new_fm = _load_fontmanager(try_read_cache=False)
1524
+ # Replace self by the new fontmanager, because users may have
1525
+ # a reference to this specific instance.
1526
+ # TODO: _load_fontmanager should really be (used by) a method
1527
+ # modifying the instance in place.
1528
+ vars(self).update(vars(new_fm))
1529
+ return self.findfont(
1530
+ prop, fontext, directory, rebuild_if_missing=False)
1531
+ else:
1532
+ # This return instead of raise is intentional, as we wish to
1533
+ # cache that it was not found, which will not occur if it was
1534
+ # actually raised.
1535
+ return cbook._ExceptionInfo(ValueError, "No valid font could be found")
1536
+
1537
+ return _cached_realpath(result)
1538
+
1539
+
1540
+ @lru_cache
1541
+ def is_opentype_cff_font(filename):
1542
+ """
1543
+ Return whether the given font is a Postscript Compact Font Format Font
1544
+ embedded in an OpenType wrapper. Used by the PostScript and PDF backends
1545
+ that cannot subset these fonts.
1546
+ """
1547
+ if os.path.splitext(filename)[1].lower() == '.otf':
1548
+ with open(filename, 'rb') as fd:
1549
+ return fd.read(4) == b"OTTO"
1550
+ else:
1551
+ return False
1552
+
1553
+
1554
+ @lru_cache(64)
1555
+ def _get_font(font_filepaths, hinting_factor, *, _kerning_factor, thread_id):
1556
+ first_fontpath, *rest = font_filepaths
1557
+ return ft2font.FT2Font(
1558
+ first_fontpath, hinting_factor,
1559
+ _fallback_list=[
1560
+ ft2font.FT2Font(
1561
+ fpath, hinting_factor,
1562
+ _kerning_factor=_kerning_factor
1563
+ )
1564
+ for fpath in rest
1565
+ ],
1566
+ _kerning_factor=_kerning_factor
1567
+ )
1568
+
1569
+
1570
+ # FT2Font objects cannot be used across fork()s because they reference the same
1571
+ # FT_Library object. While invalidating *all* existing FT2Fonts after a fork
1572
+ # would be too complicated to be worth it, the main way FT2Fonts get reused is
1573
+ # via the cache of _get_font, which we can empty upon forking (not on Windows,
1574
+ # which has no fork() or register_at_fork()).
1575
+ if hasattr(os, "register_at_fork"):
1576
+ os.register_at_fork(after_in_child=_get_font.cache_clear)
1577
+
1578
+
1579
+ @lru_cache(64)
1580
+ def _cached_realpath(path):
1581
+ # Resolving the path avoids embedding the font twice in pdf/ps output if a
1582
+ # single font is selected using two different relative paths.
1583
+ return os.path.realpath(path)
1584
+
1585
+
1586
+ def get_font(font_filepaths, hinting_factor=None):
1587
+ """
1588
+ Get an `.ft2font.FT2Font` object given a list of file paths.
1589
+
1590
+ Parameters
1591
+ ----------
1592
+ font_filepaths : Iterable[str, Path, bytes], str, Path, bytes
1593
+ Relative or absolute paths to the font files to be used.
1594
+
1595
+ If a single string, bytes, or `pathlib.Path`, then it will be treated
1596
+ as a list with that entry only.
1597
+
1598
+ If more than one filepath is passed, then the returned FT2Font object
1599
+ will fall back through the fonts, in the order given, to find a needed
1600
+ glyph.
1601
+
1602
+ Returns
1603
+ -------
1604
+ `.ft2font.FT2Font`
1605
+
1606
+ """
1607
+ if isinstance(font_filepaths, (str, Path, bytes)):
1608
+ paths = (_cached_realpath(font_filepaths),)
1609
+ else:
1610
+ paths = tuple(_cached_realpath(fname) for fname in font_filepaths)
1611
+
1612
+ if hinting_factor is None:
1613
+ hinting_factor = mpl.rcParams['text.hinting_factor']
1614
+
1615
+ return _get_font(
1616
+ # must be a tuple to be cached
1617
+ paths,
1618
+ hinting_factor,
1619
+ _kerning_factor=mpl.rcParams['text.kerning_factor'],
1620
+ # also key on the thread ID to prevent segfaults with multi-threading
1621
+ thread_id=threading.get_ident()
1622
+ )
1623
+
1624
+
1625
+ def _load_fontmanager(*, try_read_cache=True):
1626
+ fm_path = Path(
1627
+ mpl.get_cachedir(), f"fontlist-v{FontManager.__version__}.json")
1628
+ if try_read_cache:
1629
+ try:
1630
+ fm = json_load(fm_path)
1631
+ except Exception:
1632
+ pass
1633
+ else:
1634
+ if getattr(fm, "_version", object()) == FontManager.__version__:
1635
+ _log.debug("Using fontManager instance from %s", fm_path)
1636
+ return fm
1637
+ fm = FontManager()
1638
+ json_dump(fm, fm_path)
1639
+ _log.info("generated new fontManager")
1640
+ return fm
1641
+
1642
+
1643
+ fontManager = _load_fontmanager()
1644
+ findfont = fontManager.findfont
1645
+ get_font_names = fontManager.get_font_names
llava_video/lib/python3.10/site-packages/matplotlib/offsetbox.pyi ADDED
@@ -0,0 +1,298 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import matplotlib.artist as martist
2
+ from matplotlib.backend_bases import RendererBase, Event, FigureCanvasBase
3
+ from matplotlib.colors import Colormap, Normalize
4
+ import matplotlib.text as mtext
5
+ from matplotlib.figure import Figure, SubFigure
6
+ from matplotlib.font_manager import FontProperties
7
+ from matplotlib.image import BboxImage
8
+ from matplotlib.patches import FancyArrowPatch, FancyBboxPatch
9
+ from matplotlib.transforms import Bbox, BboxBase, Transform
10
+ from matplotlib.typing import CoordsType
11
+
12
+ import numpy as np
13
+ from numpy.typing import ArrayLike
14
+ from collections.abc import Callable, Sequence
15
+ from typing import Any, Literal, overload
16
+
17
+ DEBUG: bool
18
+
19
+ def _get_packed_offsets(
20
+ widths: Sequence[float],
21
+ total: float | None,
22
+ sep: float | None,
23
+ mode: Literal["fixed", "expand", "equal"] = ...,
24
+ ) -> tuple[float, np.ndarray]: ...
25
+
26
+ class OffsetBox(martist.Artist):
27
+ width: float | None
28
+ height: float | None
29
+ def __init__(self, *args, **kwargs) -> None: ...
30
+ def set_figure(self, fig: Figure | SubFigure) -> None: ...
31
+ def set_offset(
32
+ self,
33
+ xy: tuple[float, float]
34
+ | Callable[[float, float, float, float, RendererBase], tuple[float, float]],
35
+ ) -> None: ...
36
+
37
+ @overload
38
+ def get_offset(self, bbox: Bbox, renderer: RendererBase) -> tuple[float, float]: ...
39
+ @overload
40
+ def get_offset(
41
+ self,
42
+ width: float,
43
+ height: float,
44
+ xdescent: float,
45
+ ydescent: float,
46
+ renderer: RendererBase
47
+ ) -> tuple[float, float]: ...
48
+
49
+ def set_width(self, width: float) -> None: ...
50
+ def set_height(self, height: float) -> None: ...
51
+ def get_visible_children(self) -> list[martist.Artist]: ...
52
+ def get_children(self) -> list[martist.Artist]: ...
53
+ def get_bbox(self, renderer: RendererBase) -> Bbox: ...
54
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
55
+
56
+ class PackerBase(OffsetBox):
57
+ height: float | None
58
+ width: float | None
59
+ sep: float | None
60
+ pad: float | None
61
+ mode: Literal["fixed", "expand", "equal"]
62
+ align: Literal["top", "bottom", "left", "right", "center", "baseline"]
63
+ def __init__(
64
+ self,
65
+ pad: float | None = ...,
66
+ sep: float | None = ...,
67
+ width: float | None = ...,
68
+ height: float | None = ...,
69
+ align: Literal["top", "bottom", "left", "right", "center", "baseline"] = ...,
70
+ mode: Literal["fixed", "expand", "equal"] = ...,
71
+ children: list[martist.Artist] | None = ...,
72
+ ) -> None: ...
73
+
74
+ class VPacker(PackerBase): ...
75
+ class HPacker(PackerBase): ...
76
+
77
+ class PaddedBox(OffsetBox):
78
+ pad: float | None
79
+ patch: FancyBboxPatch
80
+ def __init__(
81
+ self,
82
+ child: martist.Artist,
83
+ pad: float | None = ...,
84
+ *,
85
+ draw_frame: bool = ...,
86
+ patch_attrs: dict[str, Any] | None = ...,
87
+ ) -> None: ...
88
+ def update_frame(self, bbox: Bbox, fontsize: float | None = ...) -> None: ...
89
+ def draw_frame(self, renderer: RendererBase) -> None: ...
90
+
91
+ class DrawingArea(OffsetBox):
92
+ width: float
93
+ height: float
94
+ xdescent: float
95
+ ydescent: float
96
+ offset_transform: Transform
97
+ dpi_transform: Transform
98
+ def __init__(
99
+ self,
100
+ width: float,
101
+ height: float,
102
+ xdescent: float = ...,
103
+ ydescent: float = ...,
104
+ clip: bool = ...,
105
+ ) -> None: ...
106
+ @property
107
+ def clip_children(self) -> bool: ...
108
+ @clip_children.setter
109
+ def clip_children(self, val: bool) -> None: ...
110
+ def get_transform(self) -> Transform: ...
111
+
112
+ # does not accept all options of superclass
113
+ def set_offset(self, xy: tuple[float, float]) -> None: ... # type: ignore[override]
114
+ def get_offset(self) -> tuple[float, float]: ... # type: ignore[override]
115
+ def add_artist(self, a: martist.Artist) -> None: ...
116
+
117
+ class TextArea(OffsetBox):
118
+ offset_transform: Transform
119
+ def __init__(
120
+ self,
121
+ s: str,
122
+ *,
123
+ textprops: dict[str, Any] | None = ...,
124
+ multilinebaseline: bool = ...,
125
+ ) -> None: ...
126
+ def set_text(self, s: str) -> None: ...
127
+ def get_text(self) -> str: ...
128
+ def set_multilinebaseline(self, t: bool) -> None: ...
129
+ def get_multilinebaseline(self) -> bool: ...
130
+
131
+ # does not accept all options of superclass
132
+ def set_offset(self, xy: tuple[float, float]) -> None: ... # type: ignore[override]
133
+ def get_offset(self) -> tuple[float, float]: ... # type: ignore[override]
134
+
135
+ class AuxTransformBox(OffsetBox):
136
+ aux_transform: Transform
137
+ offset_transform: Transform
138
+ ref_offset_transform: Transform
139
+ def __init__(self, aux_transform: Transform) -> None: ...
140
+ def add_artist(self, a: martist.Artist) -> None: ...
141
+ def get_transform(self) -> Transform: ...
142
+
143
+ # does not accept all options of superclass
144
+ def set_offset(self, xy: tuple[float, float]) -> None: ... # type: ignore[override]
145
+ def get_offset(self) -> tuple[float, float]: ... # type: ignore[override]
146
+
147
+ class AnchoredOffsetbox(OffsetBox):
148
+ zorder: float
149
+ codes: dict[str, int]
150
+ loc: int
151
+ borderpad: float
152
+ pad: float
153
+ prop: FontProperties
154
+ patch: FancyBboxPatch
155
+ def __init__(
156
+ self,
157
+ loc: str,
158
+ *,
159
+ pad: float = ...,
160
+ borderpad: float = ...,
161
+ child: OffsetBox | None = ...,
162
+ prop: FontProperties | None = ...,
163
+ frameon: bool = ...,
164
+ bbox_to_anchor: BboxBase
165
+ | tuple[float, float]
166
+ | tuple[float, float, float, float]
167
+ | None = ...,
168
+ bbox_transform: Transform | None = ...,
169
+ **kwargs
170
+ ) -> None: ...
171
+ def set_child(self, child: OffsetBox | None) -> None: ...
172
+ def get_child(self) -> OffsetBox | None: ...
173
+ def get_children(self) -> list[martist.Artist]: ...
174
+ def get_bbox_to_anchor(self) -> Bbox: ...
175
+ def set_bbox_to_anchor(
176
+ self, bbox: BboxBase, transform: Transform | None = ...
177
+ ) -> None: ...
178
+ def update_frame(self, bbox: Bbox, fontsize: float | None = ...) -> None: ...
179
+
180
+ class AnchoredText(AnchoredOffsetbox):
181
+ txt: TextArea
182
+ def __init__(
183
+ self,
184
+ s: str,
185
+ loc: str,
186
+ *,
187
+ pad: float = ...,
188
+ borderpad: float = ...,
189
+ prop: dict[str, Any] | None = ...,
190
+ **kwargs
191
+ ) -> None: ...
192
+
193
+ class OffsetImage(OffsetBox):
194
+ image: BboxImage
195
+ def __init__(
196
+ self,
197
+ arr: ArrayLike,
198
+ *,
199
+ zoom: float = ...,
200
+ cmap: Colormap | str | None = ...,
201
+ norm: Normalize | str | None = ...,
202
+ interpolation: str | None = ...,
203
+ origin: Literal["upper", "lower"] | None = ...,
204
+ filternorm: bool = ...,
205
+ filterrad: float = ...,
206
+ resample: bool = ...,
207
+ dpi_cor: bool = ...,
208
+ **kwargs
209
+ ) -> None: ...
210
+ stale: bool
211
+ def set_data(self, arr: ArrayLike | None) -> None: ...
212
+ def get_data(self) -> ArrayLike | None: ...
213
+ def set_zoom(self, zoom: float) -> None: ...
214
+ def get_zoom(self) -> float: ...
215
+ def get_children(self) -> list[martist.Artist]: ...
216
+ def get_offset(self) -> tuple[float, float]: ... # type: ignore[override]
217
+
218
+ class AnnotationBbox(martist.Artist, mtext._AnnotationBase):
219
+ zorder: float
220
+ offsetbox: OffsetBox
221
+ arrowprops: dict[str, Any] | None
222
+ xybox: tuple[float, float]
223
+ boxcoords: CoordsType
224
+ arrow_patch: FancyArrowPatch | None
225
+ patch: FancyBboxPatch
226
+ prop: FontProperties
227
+ def __init__(
228
+ self,
229
+ offsetbox: OffsetBox,
230
+ xy: tuple[float, float],
231
+ xybox: tuple[float, float] | None = ...,
232
+ xycoords: CoordsType = ...,
233
+ boxcoords: CoordsType | None = ...,
234
+ *,
235
+ frameon: bool = ...,
236
+ pad: float = ...,
237
+ annotation_clip: bool | None = ...,
238
+ box_alignment: tuple[float, float] = ...,
239
+ bboxprops: dict[str, Any] | None = ...,
240
+ arrowprops: dict[str, Any] | None = ...,
241
+ fontsize: float | str | None = ...,
242
+ **kwargs
243
+ ) -> None: ...
244
+ @property
245
+ def xyann(self) -> tuple[float, float]: ...
246
+ @xyann.setter
247
+ def xyann(self, xyann: tuple[float, float]) -> None: ...
248
+ @property
249
+ def anncoords(
250
+ self,
251
+ ) -> CoordsType: ...
252
+ @anncoords.setter
253
+ def anncoords(
254
+ self,
255
+ coords: CoordsType,
256
+ ) -> None: ...
257
+ def get_children(self) -> list[martist.Artist]: ...
258
+ def set_figure(self, fig: Figure | SubFigure) -> None: ...
259
+ def set_fontsize(self, s: str | float | None = ...) -> None: ...
260
+ def get_fontsize(self) -> float: ...
261
+ def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox: ...
262
+ def update_positions(self, renderer: RendererBase) -> None: ...
263
+
264
+ class DraggableBase:
265
+ ref_artist: martist.Artist
266
+ got_artist: bool
267
+ mouse_x: int
268
+ mouse_y: int
269
+ background: Any
270
+
271
+ @property
272
+ def canvas(self) -> FigureCanvasBase: ...
273
+ @property
274
+ def cids(self) -> list[int]: ...
275
+
276
+ def __init__(self, ref_artist: martist.Artist, use_blit: bool = ...) -> None: ...
277
+ def on_motion(self, evt: Event) -> None: ...
278
+ def on_pick(self, evt: Event) -> None: ...
279
+ def on_release(self, event: Event) -> None: ...
280
+ def disconnect(self) -> None: ...
281
+ def save_offset(self) -> None: ...
282
+ def update_offset(self, dx: float, dy: float) -> None: ...
283
+ def finalize_offset(self) -> None: ...
284
+
285
+ class DraggableOffsetBox(DraggableBase):
286
+ offsetbox: OffsetBox
287
+ def __init__(
288
+ self, ref_artist: martist.Artist, offsetbox: OffsetBox, use_blit: bool = ...
289
+ ) -> None: ...
290
+ def save_offset(self) -> None: ...
291
+ def update_offset(self, dx: float, dy: float) -> None: ...
292
+ def get_loc_in_canvas(self) -> tuple[float, float]: ...
293
+
294
+ class DraggableAnnotation(DraggableBase):
295
+ annotation: mtext.Annotation
296
+ def __init__(self, annotation: mtext.Annotation, use_blit: bool = ...) -> None: ...
297
+ def save_offset(self) -> None: ...
298
+ def update_offset(self, dx: float, dy: float) -> None: ...
llava_video/lib/python3.10/site-packages/matplotlib/text.pyi ADDED
@@ -0,0 +1,181 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .artist import Artist
2
+ from .backend_bases import RendererBase
3
+ from .font_manager import FontProperties
4
+ from .offsetbox import DraggableAnnotation
5
+ from .path import Path
6
+ from .patches import FancyArrowPatch, FancyBboxPatch
7
+ from .textpath import ( # noqa: F401, reexported API
8
+ TextPath as TextPath,
9
+ TextToPath as TextToPath,
10
+ )
11
+ from .transforms import (
12
+ Bbox,
13
+ BboxBase,
14
+ Transform,
15
+ )
16
+
17
+ from collections.abc import Callable, Iterable
18
+ from typing import Any, Literal
19
+ from .typing import ColorType, CoordsType
20
+
21
+ class Text(Artist):
22
+ zorder: float
23
+ def __init__(
24
+ self,
25
+ x: float = ...,
26
+ y: float = ...,
27
+ text: Any = ...,
28
+ *,
29
+ color: ColorType | None = ...,
30
+ verticalalignment: Literal[
31
+ "bottom", "baseline", "center", "center_baseline", "top"
32
+ ] = ...,
33
+ horizontalalignment: Literal["left", "center", "right"] = ...,
34
+ multialignment: Literal["left", "center", "right"] | None = ...,
35
+ fontproperties: str | Path | FontProperties | None = ...,
36
+ rotation: float | Literal["vertical", "horizontal"] | None = ...,
37
+ linespacing: float | None = ...,
38
+ rotation_mode: Literal["default", "anchor"] | None = ...,
39
+ usetex: bool | None = ...,
40
+ wrap: bool = ...,
41
+ transform_rotates_text: bool = ...,
42
+ parse_math: bool | None = ...,
43
+ antialiased: bool | None = ...,
44
+ **kwargs
45
+ ) -> None: ...
46
+ def update(self, kwargs: dict[str, Any]) -> list[Any]: ...
47
+ def get_rotation(self) -> float: ...
48
+ def get_transform_rotates_text(self) -> bool: ...
49
+ def set_rotation_mode(self, m: None | Literal["default", "anchor"]) -> None: ...
50
+ def get_rotation_mode(self) -> Literal["default", "anchor"]: ...
51
+ def set_bbox(self, rectprops: dict[str, Any]) -> None: ...
52
+ def get_bbox_patch(self) -> None | FancyBboxPatch: ...
53
+ def update_bbox_position_size(self, renderer: RendererBase) -> None: ...
54
+ def get_wrap(self) -> bool: ...
55
+ def set_wrap(self, wrap: bool) -> None: ...
56
+ def get_color(self) -> ColorType: ...
57
+ def get_fontproperties(self) -> FontProperties: ...
58
+ def get_fontfamily(self) -> list[str]: ...
59
+ def get_fontname(self) -> str: ...
60
+ def get_fontstyle(self) -> Literal["normal", "italic", "oblique"]: ...
61
+ def get_fontsize(self) -> float | str: ...
62
+ def get_fontvariant(self) -> Literal["normal", "small-caps"]: ...
63
+ def get_fontweight(self) -> int | str: ...
64
+ def get_stretch(self) -> int | str: ...
65
+ def get_horizontalalignment(self) -> Literal["left", "center", "right"]: ...
66
+ def get_unitless_position(self) -> tuple[float, float]: ...
67
+ def get_position(self) -> tuple[float, float]: ...
68
+ def get_text(self) -> str: ...
69
+ def get_verticalalignment(
70
+ self,
71
+ ) -> Literal["bottom", "baseline", "center", "center_baseline", "top"]: ...
72
+ def get_window_extent(
73
+ self, renderer: RendererBase | None = ..., dpi: float | None = ...
74
+ ) -> Bbox: ...
75
+ def set_backgroundcolor(self, color: ColorType) -> None: ...
76
+ def set_color(self, color: ColorType) -> None: ...
77
+ def set_horizontalalignment(
78
+ self, align: Literal["left", "center", "right"]
79
+ ) -> None: ...
80
+ def set_multialignment(self, align: Literal["left", "center", "right"]) -> None: ...
81
+ def set_linespacing(self, spacing: float) -> None: ...
82
+ def set_fontfamily(self, fontname: str | Iterable[str]) -> None: ...
83
+ def set_fontvariant(self, variant: Literal["normal", "small-caps"]) -> None: ...
84
+ def set_fontstyle(
85
+ self, fontstyle: Literal["normal", "italic", "oblique"]
86
+ ) -> None: ...
87
+ def set_fontsize(self, fontsize: float | str) -> None: ...
88
+ def get_math_fontfamily(self) -> str: ...
89
+ def set_math_fontfamily(self, fontfamily: str) -> None: ...
90
+ def set_fontweight(self, weight: int | str) -> None: ...
91
+ def set_fontstretch(self, stretch: int | str) -> None: ...
92
+ def set_position(self, xy: tuple[float, float]) -> None: ...
93
+ def set_x(self, x: float) -> None: ...
94
+ def set_y(self, y: float) -> None: ...
95
+ def set_rotation(self, s: float) -> None: ...
96
+ def set_transform_rotates_text(self, t: bool) -> None: ...
97
+ def set_verticalalignment(
98
+ self, align: Literal["bottom", "baseline", "center", "center_baseline", "top"]
99
+ ) -> None: ...
100
+ def set_text(self, s: Any) -> None: ...
101
+ def set_fontproperties(self, fp: FontProperties | str | Path | None) -> None: ...
102
+ def set_usetex(self, usetex: bool | None) -> None: ...
103
+ def get_usetex(self) -> bool: ...
104
+ def set_parse_math(self, parse_math: bool) -> None: ...
105
+ def get_parse_math(self) -> bool: ...
106
+ def set_fontname(self, fontname: str | Iterable[str]) -> None: ...
107
+ def get_antialiased(self) -> bool: ...
108
+ def set_antialiased(self, antialiased: bool) -> None: ...
109
+
110
+ class OffsetFrom:
111
+ def __init__(
112
+ self,
113
+ artist: Artist | BboxBase | Transform,
114
+ ref_coord: tuple[float, float],
115
+ unit: Literal["points", "pixels"] = ...,
116
+ ) -> None: ...
117
+ def set_unit(self, unit: Literal["points", "pixels"]) -> None: ...
118
+ def get_unit(self) -> Literal["points", "pixels"]: ...
119
+ def __call__(self, renderer: RendererBase) -> Transform: ...
120
+
121
+ class _AnnotationBase:
122
+ xy: tuple[float, float]
123
+ xycoords: CoordsType
124
+ def __init__(
125
+ self,
126
+ xy,
127
+ xycoords: CoordsType = ...,
128
+ annotation_clip: bool | None = ...,
129
+ ) -> None: ...
130
+ def set_annotation_clip(self, b: bool | None) -> None: ...
131
+ def get_annotation_clip(self) -> bool | None: ...
132
+ def draggable(
133
+ self, state: bool | None = ..., use_blit: bool = ...
134
+ ) -> DraggableAnnotation | None: ...
135
+
136
+ class Annotation(Text, _AnnotationBase):
137
+ arrowprops: dict[str, Any] | None
138
+ arrow_patch: FancyArrowPatch | None
139
+ def __init__(
140
+ self,
141
+ text: str,
142
+ xy: tuple[float, float],
143
+ xytext: tuple[float, float] | None = ...,
144
+ xycoords: CoordsType = ...,
145
+ textcoords: CoordsType | None = ...,
146
+ arrowprops: dict[str, Any] | None = ...,
147
+ annotation_clip: bool | None = ...,
148
+ **kwargs
149
+ ) -> None: ...
150
+ @property
151
+ def xycoords(
152
+ self,
153
+ ) -> CoordsType: ...
154
+ @xycoords.setter
155
+ def xycoords(
156
+ self,
157
+ xycoords: CoordsType,
158
+ ) -> None: ...
159
+ @property
160
+ def xyann(self) -> tuple[float, float]: ...
161
+ @xyann.setter
162
+ def xyann(self, xytext: tuple[float, float]) -> None: ...
163
+ def get_anncoords(
164
+ self,
165
+ ) -> CoordsType: ...
166
+ def set_anncoords(
167
+ self,
168
+ coords: CoordsType,
169
+ ) -> None: ...
170
+ @property
171
+ def anncoords(
172
+ self,
173
+ ) -> CoordsType: ...
174
+ @anncoords.setter
175
+ def anncoords(
176
+ self,
177
+ coords: CoordsType,
178
+ ) -> None: ...
179
+ def update_positions(self, renderer: RendererBase) -> None: ...
180
+ # Drops `dpi` parameter from superclass
181
+ def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ... # type: ignore[override]
llava_video/lib/python3.10/site-packages/matplotlib/textpath.pyi ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from matplotlib.font_manager import FontProperties
2
+ from matplotlib.ft2font import FT2Font
3
+ from matplotlib.mathtext import MathTextParser, VectorParse
4
+ from matplotlib.path import Path
5
+
6
+ import numpy as np
7
+
8
+ from typing import Literal
9
+
10
+ class TextToPath:
11
+ FONT_SCALE: float
12
+ DPI: float
13
+ mathtext_parser: MathTextParser[VectorParse]
14
+ def __init__(self) -> None: ...
15
+ def get_text_width_height_descent(
16
+ self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"]
17
+ ) -> tuple[float, float, float]: ...
18
+ def get_text_path(
19
+ self, prop: FontProperties, s: str, ismath: bool | Literal["TeX"] = ...
20
+ ) -> list[np.ndarray]: ...
21
+ def get_glyphs_with_font(
22
+ self,
23
+ font: FT2Font,
24
+ s: str,
25
+ glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ...,
26
+ return_new_glyphs_only: bool = ...,
27
+ ) -> tuple[
28
+ list[tuple[str, float, float, float]],
29
+ dict[str, tuple[np.ndarray, np.ndarray]],
30
+ list[tuple[list[tuple[float, float]], list[int]]],
31
+ ]: ...
32
+ def get_glyphs_mathtext(
33
+ self,
34
+ prop: FontProperties,
35
+ s: str,
36
+ glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ...,
37
+ return_new_glyphs_only: bool = ...,
38
+ ) -> tuple[
39
+ list[tuple[str, float, float, float]],
40
+ dict[str, tuple[np.ndarray, np.ndarray]],
41
+ list[tuple[list[tuple[float, float]], list[int]]],
42
+ ]: ...
43
+ def get_glyphs_tex(
44
+ self,
45
+ prop: FontProperties,
46
+ s: str,
47
+ glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ...,
48
+ return_new_glyphs_only: bool = ...,
49
+ ) -> tuple[
50
+ list[tuple[str, float, float, float]],
51
+ dict[str, tuple[np.ndarray, np.ndarray]],
52
+ list[tuple[list[tuple[float, float]], list[int]]],
53
+ ]: ...
54
+
55
+ text_to_path: TextToPath
56
+
57
+ class TextPath(Path):
58
+ def __init__(
59
+ self,
60
+ xy: tuple[float, float],
61
+ s: str,
62
+ size: float | None = ...,
63
+ prop: FontProperties | None = ...,
64
+ _interpolation_steps: int = ...,
65
+ usetex: bool = ...,
66
+ ) -> None: ...
67
+ def set_size(self, size: float | None) -> None: ...
68
+ def get_size(self) -> float | None: ...
69
+
70
+ # These are read only... there actually are protections in the base class, so probably can be deleted...
71
+ @property # type: ignore[misc]
72
+ def vertices(self) -> np.ndarray: ... # type: ignore[override]
73
+ @property # type: ignore[misc]
74
+ def codes(self) -> np.ndarray: ... # type: ignore[override]
llava_video/lib/python3.10/site-packages/matplotlib/transforms.pyi ADDED
@@ -0,0 +1,341 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .path import Path
2
+ from .patches import Patch
3
+ from .figure import Figure
4
+ import numpy as np
5
+ from numpy.typing import ArrayLike
6
+ from collections.abc import Iterable, Sequence
7
+ from typing import Literal
8
+
9
+ DEBUG: bool
10
+
11
+ class TransformNode:
12
+ INVALID_NON_AFFINE: int
13
+ INVALID_AFFINE: int
14
+ INVALID: int
15
+ is_bbox: bool
16
+ # Implemented as a standard attr in base class, but functionally readonly and some subclasses implement as such
17
+ @property
18
+ def is_affine(self) -> bool: ...
19
+ pass_through: bool
20
+ def __init__(self, shorthand_name: str | None = ...) -> None: ...
21
+ def __copy__(self) -> TransformNode: ...
22
+ def invalidate(self) -> None: ...
23
+ def set_children(self, *children: TransformNode) -> None: ...
24
+ def frozen(self) -> TransformNode: ...
25
+
26
+ class BboxBase(TransformNode):
27
+ is_bbox: bool
28
+ is_affine: bool
29
+ def frozen(self) -> Bbox: ...
30
+ def __array__(self, *args, **kwargs): ...
31
+ @property
32
+ def x0(self) -> float: ...
33
+ @property
34
+ def y0(self) -> float: ...
35
+ @property
36
+ def x1(self) -> float: ...
37
+ @property
38
+ def y1(self) -> float: ...
39
+ @property
40
+ def p0(self) -> tuple[float, float]: ...
41
+ @property
42
+ def p1(self) -> tuple[float, float]: ...
43
+ @property
44
+ def xmin(self) -> float: ...
45
+ @property
46
+ def ymin(self) -> float: ...
47
+ @property
48
+ def xmax(self) -> float: ...
49
+ @property
50
+ def ymax(self) -> float: ...
51
+ @property
52
+ def min(self) -> tuple[float, float]: ...
53
+ @property
54
+ def max(self) -> tuple[float, float]: ...
55
+ @property
56
+ def intervalx(self) -> tuple[float, float]: ...
57
+ @property
58
+ def intervaly(self) -> tuple[float, float]: ...
59
+ @property
60
+ def width(self) -> float: ...
61
+ @property
62
+ def height(self) -> float: ...
63
+ @property
64
+ def size(self) -> tuple[float, float]: ...
65
+ @property
66
+ def bounds(self) -> tuple[float, float, float, float]: ...
67
+ @property
68
+ def extents(self) -> tuple[float, float, float, float]: ...
69
+ def get_points(self) -> np.ndarray: ...
70
+ def containsx(self, x: float) -> bool: ...
71
+ def containsy(self, y: float) -> bool: ...
72
+ def contains(self, x: float, y: float) -> bool: ...
73
+ def overlaps(self, other: BboxBase) -> bool: ...
74
+ def fully_containsx(self, x: float) -> bool: ...
75
+ def fully_containsy(self, y: float) -> bool: ...
76
+ def fully_contains(self, x: float, y: float) -> bool: ...
77
+ def fully_overlaps(self, other: BboxBase) -> bool: ...
78
+ def transformed(self, transform: Transform) -> Bbox: ...
79
+ coefs: dict[str, tuple[float, float]]
80
+ def anchored(
81
+ self,
82
+ c: tuple[float, float] | Literal['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'],
83
+ container: BboxBase,
84
+ ) -> Bbox: ...
85
+ def shrunk(self, mx: float, my: float) -> Bbox: ...
86
+ def shrunk_to_aspect(
87
+ self,
88
+ box_aspect: float,
89
+ container: BboxBase | None = ...,
90
+ fig_aspect: float = ...,
91
+ ) -> Bbox: ...
92
+ def splitx(self, *args: float) -> list[Bbox]: ...
93
+ def splity(self, *args: float) -> list[Bbox]: ...
94
+ def count_contains(self, vertices: ArrayLike) -> int: ...
95
+ def count_overlaps(self, bboxes: Iterable[BboxBase]) -> int: ...
96
+ def expanded(self, sw: float, sh: float) -> Bbox: ...
97
+ def padded(self, w_pad: float, h_pad: float | None = ...) -> Bbox: ...
98
+ def translated(self, tx: float, ty: float) -> Bbox: ...
99
+ def corners(self) -> np.ndarray: ...
100
+ def rotated(self, radians: float) -> Bbox: ...
101
+ @staticmethod
102
+ def union(bboxes: Sequence[BboxBase]) -> Bbox: ...
103
+ @staticmethod
104
+ def intersection(bbox1: BboxBase, bbox2: BboxBase) -> Bbox | None: ...
105
+
106
+ class Bbox(BboxBase):
107
+ def __init__(self, points: ArrayLike, **kwargs) -> None: ...
108
+ @staticmethod
109
+ def unit() -> Bbox: ...
110
+ @staticmethod
111
+ def null() -> Bbox: ...
112
+ @staticmethod
113
+ def from_bounds(x0: float, y0: float, width: float, height: float) -> Bbox: ...
114
+ @staticmethod
115
+ def from_extents(*args: float, minpos: float | None = ...) -> Bbox: ...
116
+ def __format__(self, fmt: str) -> str: ...
117
+ def ignore(self, value: bool) -> None: ...
118
+ def update_from_path(
119
+ self,
120
+ path: Path,
121
+ ignore: bool | None = ...,
122
+ updatex: bool = ...,
123
+ updatey: bool = ...,
124
+ ) -> None: ...
125
+ def update_from_data_x(self, x: ArrayLike, ignore: bool | None = ...) -> None: ...
126
+ def update_from_data_y(self, y: ArrayLike, ignore: bool | None = ...) -> None: ...
127
+ def update_from_data_xy(
128
+ self,
129
+ xy: ArrayLike,
130
+ ignore: bool | None = ...,
131
+ updatex: bool = ...,
132
+ updatey: bool = ...,
133
+ ) -> None: ...
134
+ @property
135
+ def minpos(self) -> float: ...
136
+ @property
137
+ def minposx(self) -> float: ...
138
+ @property
139
+ def minposy(self) -> float: ...
140
+ def get_points(self) -> np.ndarray: ...
141
+ def set_points(self, points: ArrayLike) -> None: ...
142
+ def set(self, other: Bbox) -> None: ...
143
+ def mutated(self) -> bool: ...
144
+ def mutatedx(self) -> bool: ...
145
+ def mutatedy(self) -> bool: ...
146
+
147
+ class TransformedBbox(BboxBase):
148
+ def __init__(self, bbox: Bbox, transform: Transform, **kwargs) -> None: ...
149
+ def get_points(self) -> np.ndarray: ...
150
+
151
+ class LockableBbox(BboxBase):
152
+ def __init__(
153
+ self,
154
+ bbox: BboxBase,
155
+ x0: float | None = ...,
156
+ y0: float | None = ...,
157
+ x1: float | None = ...,
158
+ y1: float | None = ...,
159
+ **kwargs
160
+ ) -> None: ...
161
+ @property
162
+ def locked_x0(self) -> float | None: ...
163
+ @locked_x0.setter
164
+ def locked_x0(self, x0: float | None) -> None: ...
165
+ @property
166
+ def locked_y0(self) -> float | None: ...
167
+ @locked_y0.setter
168
+ def locked_y0(self, y0: float | None) -> None: ...
169
+ @property
170
+ def locked_x1(self) -> float | None: ...
171
+ @locked_x1.setter
172
+ def locked_x1(self, x1: float | None) -> None: ...
173
+ @property
174
+ def locked_y1(self) -> float | None: ...
175
+ @locked_y1.setter
176
+ def locked_y1(self, y1: float | None) -> None: ...
177
+
178
+ class Transform(TransformNode):
179
+
180
+ # Implemented as a standard attrs in base class, but functionally readonly and some subclasses implement as such
181
+ @property
182
+ def input_dims(self) -> int | None: ...
183
+ @property
184
+ def output_dims(self) -> int | None: ...
185
+ @property
186
+ def is_separable(self) -> bool: ...
187
+ @property
188
+ def has_inverse(self) -> bool: ...
189
+
190
+ def __add__(self, other: Transform) -> Transform: ...
191
+ @property
192
+ def depth(self) -> int: ...
193
+ def contains_branch(self, other: Transform) -> bool: ...
194
+ def contains_branch_seperately(
195
+ self, other_transform: Transform
196
+ ) -> Sequence[bool]: ...
197
+ def __sub__(self, other: Transform) -> Transform: ...
198
+ def __array__(self, *args, **kwargs) -> np.ndarray: ...
199
+ def transform(self, values: ArrayLike) -> np.ndarray: ...
200
+ def transform_affine(self, values: ArrayLike) -> np.ndarray: ...
201
+ def transform_non_affine(self, values: ArrayLike) -> ArrayLike: ...
202
+ def transform_bbox(self, bbox: BboxBase) -> Bbox: ...
203
+ def get_affine(self) -> Transform: ...
204
+ def get_matrix(self) -> np.ndarray: ...
205
+ def transform_point(self, point: ArrayLike) -> np.ndarray: ...
206
+ def transform_path(self, path: Path) -> Path: ...
207
+ def transform_path_affine(self, path: Path) -> Path: ...
208
+ def transform_path_non_affine(self, path: Path) -> Path: ...
209
+ def transform_angles(
210
+ self,
211
+ angles: ArrayLike,
212
+ pts: ArrayLike,
213
+ radians: bool = ...,
214
+ pushoff: float = ...,
215
+ ) -> np.ndarray: ...
216
+ def inverted(self) -> Transform: ...
217
+
218
+ class TransformWrapper(Transform):
219
+ pass_through: bool
220
+ def __init__(self, child: Transform) -> None: ...
221
+ def __eq__(self, other: object) -> bool: ...
222
+ def frozen(self) -> Transform: ...
223
+ def set(self, child: Transform) -> None: ...
224
+
225
+ class AffineBase(Transform):
226
+ is_affine: Literal[True]
227
+ def __init__(self, *args, **kwargs) -> None: ...
228
+ def __eq__(self, other: object) -> bool: ...
229
+
230
+ class Affine2DBase(AffineBase):
231
+ input_dims: Literal[2]
232
+ output_dims: Literal[2]
233
+ def frozen(self) -> Affine2D: ...
234
+ def to_values(self) -> tuple[float, float, float, float, float, float]: ...
235
+
236
+ class Affine2D(Affine2DBase):
237
+ def __init__(self, matrix: ArrayLike | None = ..., **kwargs) -> None: ...
238
+ @staticmethod
239
+ def from_values(
240
+ a: float, b: float, c: float, d: float, e: float, f: float
241
+ ) -> Affine2D: ...
242
+ def set_matrix(self, mtx: ArrayLike) -> None: ...
243
+ def clear(self) -> Affine2D: ...
244
+ def rotate(self, theta: float) -> Affine2D: ...
245
+ def rotate_deg(self, degrees: float) -> Affine2D: ...
246
+ def rotate_around(self, x: float, y: float, theta: float) -> Affine2D: ...
247
+ def rotate_deg_around(self, x: float, y: float, degrees: float) -> Affine2D: ...
248
+ def translate(self, tx: float, ty: float) -> Affine2D: ...
249
+ def scale(self, sx: float, sy: float | None = ...) -> Affine2D: ...
250
+ def skew(self, xShear: float, yShear: float) -> Affine2D: ...
251
+ def skew_deg(self, xShear: float, yShear: float) -> Affine2D: ...
252
+
253
+ class IdentityTransform(Affine2DBase): ...
254
+
255
+ class _BlendedMixin:
256
+ def __eq__(self, other: object) -> bool: ...
257
+ def contains_branch_seperately(self, transform: Transform) -> Sequence[bool]: ...
258
+
259
+ class BlendedGenericTransform(_BlendedMixin, Transform):
260
+ input_dims: Literal[2]
261
+ output_dims: Literal[2]
262
+ pass_through: bool
263
+ def __init__(
264
+ self, x_transform: Transform, y_transform: Transform, **kwargs
265
+ ) -> None: ...
266
+ @property
267
+ def depth(self) -> int: ...
268
+ def contains_branch(self, other: Transform) -> Literal[False]: ...
269
+ @property
270
+ def is_affine(self) -> bool: ...
271
+
272
+ class BlendedAffine2D(_BlendedMixin, Affine2DBase):
273
+ def __init__(
274
+ self, x_transform: Transform, y_transform: Transform, **kwargs
275
+ ) -> None: ...
276
+
277
+ def blended_transform_factory(
278
+ x_transform: Transform, y_transform: Transform
279
+ ) -> BlendedGenericTransform | BlendedAffine2D: ...
280
+
281
+ class CompositeGenericTransform(Transform):
282
+ pass_through: bool
283
+ def __init__(self, a: Transform, b: Transform, **kwargs) -> None: ...
284
+
285
+ class CompositeAffine2D(Affine2DBase):
286
+ def __init__(self, a: Affine2DBase, b: Affine2DBase, **kwargs) -> None: ...
287
+ @property
288
+ def depth(self) -> int: ...
289
+
290
+ def composite_transform_factory(a: Transform, b: Transform) -> Transform: ...
291
+
292
+ class BboxTransform(Affine2DBase):
293
+ def __init__(self, boxin: BboxBase, boxout: BboxBase, **kwargs) -> None: ...
294
+
295
+ class BboxTransformTo(Affine2DBase):
296
+ def __init__(self, boxout: BboxBase, **kwargs) -> None: ...
297
+
298
+ class BboxTransformToMaxOnly(BboxTransformTo): ...
299
+
300
+ class BboxTransformFrom(Affine2DBase):
301
+ def __init__(self, boxin: BboxBase, **kwargs) -> None: ...
302
+
303
+ class ScaledTranslation(Affine2DBase):
304
+ def __init__(
305
+ self, xt: float, yt: float, scale_trans: Affine2DBase, **kwargs
306
+ ) -> None: ...
307
+
308
+ class AffineDeltaTransform(Affine2DBase):
309
+ def __init__(self, transform: Affine2DBase, **kwargs) -> None: ...
310
+
311
+ class TransformedPath(TransformNode):
312
+ def __init__(self, path: Path, transform: Transform) -> None: ...
313
+ def get_transformed_points_and_affine(self) -> tuple[Path, Transform]: ...
314
+ def get_transformed_path_and_affine(self) -> tuple[Path, Transform]: ...
315
+ def get_fully_transformed_path(self) -> Path: ...
316
+ def get_affine(self) -> Transform: ...
317
+
318
+ class TransformedPatchPath(TransformedPath):
319
+ def __init__(self, patch: Patch) -> None: ...
320
+
321
+ def nonsingular(
322
+ vmin: float,
323
+ vmax: float,
324
+ expander: float = ...,
325
+ tiny: float = ...,
326
+ increasing: bool = ...,
327
+ ) -> tuple[float, float]: ...
328
+ def interval_contains(interval: tuple[float, float], val: float) -> bool: ...
329
+ def interval_contains_open(interval: tuple[float, float], val: float) -> bool: ...
330
+ def offset_copy(
331
+ trans: Transform,
332
+ fig: Figure | None = ...,
333
+ x: float = ...,
334
+ y: float = ...,
335
+ units: Literal["inches", "points", "dots"] = ...,
336
+ ) -> Transform: ...
337
+
338
+
339
+ class _ScaledRotation(Affine2DBase):
340
+ def __init__(self, theta: float, trans_shift: Transform) -> None: ...
341
+ def get_matrix(self) -> np.ndarray: ...
llava_video/lib/python3.10/site-packages/pkg_resources/__pycache__/__init__.cpython-310.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:191fd421685d609268ca1cf8363261f6cc101d545a1bc2b3ba669e28e3512464
3
+ size 115599
llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (153 Bytes). View file
 
llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc ADDED
Binary file (2.35 kB). View file
 
llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_pkg_resources.cpython-310.pyc ADDED
Binary file (13.6 kB). View file
 
llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc ADDED
Binary file (28.2 kB). View file
 
llava_video/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc ADDED
Binary file (8.41 kB). View file
 
llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.cfg ADDED
File without changes
llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01845c437f4655e3cf9cc4fc4e49cfd607431f22675e1b611129a90239f34822
3
+ size 1809
llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/PKG-INFO ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ Metadata-Version: 1.0
2
+ Name: my-test-package
3
+ Version: 1.0
4
+ Summary: UNKNOWN
5
+ Home-page: UNKNOWN
6
+ Author: UNKNOWN
7
+ Author-email: UNKNOWN
8
+ License: UNKNOWN
9
+ Description: UNKNOWN
10
+ Platform: UNKNOWN
llava_video/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/top_level.txt ADDED
@@ -0,0 +1 @@
 
 
1
+
llava_video/lib/python3.10/site-packages/pkg_resources/tests/test_working_set.py ADDED
@@ -0,0 +1,501 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import inspect
3
+ import re
4
+ import textwrap
5
+
6
+ import pytest
7
+
8
+ import pkg_resources
9
+
10
+ from .test_resources import Metadata
11
+
12
+
13
+ def strip_comments(s):
14
+ return '\n'.join(
15
+ line
16
+ for line in s.split('\n')
17
+ if line.strip() and not line.strip().startswith('#')
18
+ )
19
+
20
+
21
+ def parse_distributions(s):
22
+ """
23
+ Parse a series of distribution specs of the form:
24
+ {project_name}-{version}
25
+ [optional, indented requirements specification]
26
+
27
+ Example:
28
+
29
+ foo-0.2
30
+ bar-1.0
31
+ foo>=3.0
32
+ [feature]
33
+ baz
34
+
35
+ yield 2 distributions:
36
+ - project_name=foo, version=0.2
37
+ - project_name=bar, version=1.0,
38
+ requires=['foo>=3.0', 'baz; extra=="feature"']
39
+ """
40
+ s = s.strip()
41
+ for spec in re.split(r'\n(?=[^\s])', s):
42
+ if not spec:
43
+ continue
44
+ fields = spec.split('\n', 1)
45
+ assert 1 <= len(fields) <= 2
46
+ name, version = fields.pop(0).rsplit('-', 1)
47
+ if fields:
48
+ requires = textwrap.dedent(fields.pop(0))
49
+ metadata = Metadata(('requires.txt', requires))
50
+ else:
51
+ metadata = None
52
+ dist = pkg_resources.Distribution(
53
+ project_name=name, version=version, metadata=metadata
54
+ )
55
+ yield dist
56
+
57
+
58
+ class FakeInstaller:
59
+ def __init__(self, installable_dists) -> None:
60
+ self._installable_dists = installable_dists
61
+
62
+ def __call__(self, req):
63
+ return next(
64
+ iter(filter(lambda dist: dist in req, self._installable_dists)), None
65
+ )
66
+
67
+
68
+ def parametrize_test_working_set_resolve(*test_list):
69
+ idlist = []
70
+ argvalues = []
71
+ for test in test_list:
72
+ (
73
+ name,
74
+ installed_dists,
75
+ installable_dists,
76
+ requirements,
77
+ expected1,
78
+ expected2,
79
+ ) = (
80
+ strip_comments(s.lstrip())
81
+ for s in textwrap.dedent(test).lstrip().split('\n\n', 5)
82
+ )
83
+ installed_dists = list(parse_distributions(installed_dists))
84
+ installable_dists = list(parse_distributions(installable_dists))
85
+ requirements = list(pkg_resources.parse_requirements(requirements))
86
+ for id_, replace_conflicting, expected in (
87
+ (name, False, expected1),
88
+ (name + '_replace_conflicting', True, expected2),
89
+ ):
90
+ idlist.append(id_)
91
+ expected = strip_comments(expected.strip())
92
+ if re.match(r'\w+$', expected):
93
+ expected = getattr(pkg_resources, expected)
94
+ assert issubclass(expected, Exception)
95
+ else:
96
+ expected = list(parse_distributions(expected))
97
+ argvalues.append(
98
+ pytest.param(
99
+ installed_dists,
100
+ installable_dists,
101
+ requirements,
102
+ replace_conflicting,
103
+ expected,
104
+ )
105
+ )
106
+ return pytest.mark.parametrize(
107
+ 'installed_dists,installable_dists,'
108
+ 'requirements,replace_conflicting,'
109
+ 'resolved_dists_or_exception',
110
+ argvalues,
111
+ ids=idlist,
112
+ )
113
+
114
+
115
+ @parametrize_test_working_set_resolve(
116
+ """
117
+ # id
118
+ noop
119
+
120
+ # installed
121
+
122
+ # installable
123
+
124
+ # wanted
125
+
126
+ # resolved
127
+
128
+ # resolved [replace conflicting]
129
+ """,
130
+ """
131
+ # id
132
+ already_installed
133
+
134
+ # installed
135
+ foo-3.0
136
+
137
+ # installable
138
+
139
+ # wanted
140
+ foo>=2.1,!=3.1,<4
141
+
142
+ # resolved
143
+ foo-3.0
144
+
145
+ # resolved [replace conflicting]
146
+ foo-3.0
147
+ """,
148
+ """
149
+ # id
150
+ installable_not_installed
151
+
152
+ # installed
153
+
154
+ # installable
155
+ foo-3.0
156
+ foo-4.0
157
+
158
+ # wanted
159
+ foo>=2.1,!=3.1,<4
160
+
161
+ # resolved
162
+ foo-3.0
163
+
164
+ # resolved [replace conflicting]
165
+ foo-3.0
166
+ """,
167
+ """
168
+ # id
169
+ not_installable
170
+
171
+ # installed
172
+
173
+ # installable
174
+
175
+ # wanted
176
+ foo>=2.1,!=3.1,<4
177
+
178
+ # resolved
179
+ DistributionNotFound
180
+
181
+ # resolved [replace conflicting]
182
+ DistributionNotFound
183
+ """,
184
+ """
185
+ # id
186
+ no_matching_version
187
+
188
+ # installed
189
+
190
+ # installable
191
+ foo-3.1
192
+
193
+ # wanted
194
+ foo>=2.1,!=3.1,<4
195
+
196
+ # resolved
197
+ DistributionNotFound
198
+
199
+ # resolved [replace conflicting]
200
+ DistributionNotFound
201
+ """,
202
+ """
203
+ # id
204
+ installable_with_installed_conflict
205
+
206
+ # installed
207
+ foo-3.1
208
+
209
+ # installable
210
+ foo-3.5
211
+
212
+ # wanted
213
+ foo>=2.1,!=3.1,<4
214
+
215
+ # resolved
216
+ VersionConflict
217
+
218
+ # resolved [replace conflicting]
219
+ foo-3.5
220
+ """,
221
+ """
222
+ # id
223
+ not_installable_with_installed_conflict
224
+
225
+ # installed
226
+ foo-3.1
227
+
228
+ # installable
229
+
230
+ # wanted
231
+ foo>=2.1,!=3.1,<4
232
+
233
+ # resolved
234
+ VersionConflict
235
+
236
+ # resolved [replace conflicting]
237
+ DistributionNotFound
238
+ """,
239
+ """
240
+ # id
241
+ installed_with_installed_require
242
+
243
+ # installed
244
+ foo-3.9
245
+ baz-0.1
246
+ foo>=2.1,!=3.1,<4
247
+
248
+ # installable
249
+
250
+ # wanted
251
+ baz
252
+
253
+ # resolved
254
+ foo-3.9
255
+ baz-0.1
256
+
257
+ # resolved [replace conflicting]
258
+ foo-3.9
259
+ baz-0.1
260
+ """,
261
+ """
262
+ # id
263
+ installed_with_conflicting_installed_require
264
+
265
+ # installed
266
+ foo-5
267
+ baz-0.1
268
+ foo>=2.1,!=3.1,<4
269
+
270
+ # installable
271
+
272
+ # wanted
273
+ baz
274
+
275
+ # resolved
276
+ VersionConflict
277
+
278
+ # resolved [replace conflicting]
279
+ DistributionNotFound
280
+ """,
281
+ """
282
+ # id
283
+ installed_with_installable_conflicting_require
284
+
285
+ # installed
286
+ foo-5
287
+ baz-0.1
288
+ foo>=2.1,!=3.1,<4
289
+
290
+ # installable
291
+ foo-2.9
292
+
293
+ # wanted
294
+ baz
295
+
296
+ # resolved
297
+ VersionConflict
298
+
299
+ # resolved [replace conflicting]
300
+ baz-0.1
301
+ foo-2.9
302
+ """,
303
+ """
304
+ # id
305
+ installed_with_installable_require
306
+
307
+ # installed
308
+ baz-0.1
309
+ foo>=2.1,!=3.1,<4
310
+
311
+ # installable
312
+ foo-3.9
313
+
314
+ # wanted
315
+ baz
316
+
317
+ # resolved
318
+ foo-3.9
319
+ baz-0.1
320
+
321
+ # resolved [replace conflicting]
322
+ foo-3.9
323
+ baz-0.1
324
+ """,
325
+ """
326
+ # id
327
+ installable_with_installed_require
328
+
329
+ # installed
330
+ foo-3.9
331
+
332
+ # installable
333
+ baz-0.1
334
+ foo>=2.1,!=3.1,<4
335
+
336
+ # wanted
337
+ baz
338
+
339
+ # resolved
340
+ foo-3.9
341
+ baz-0.1
342
+
343
+ # resolved [replace conflicting]
344
+ foo-3.9
345
+ baz-0.1
346
+ """,
347
+ """
348
+ # id
349
+ installable_with_installable_require
350
+
351
+ # installed
352
+
353
+ # installable
354
+ foo-3.9
355
+ baz-0.1
356
+ foo>=2.1,!=3.1,<4
357
+
358
+ # wanted
359
+ baz
360
+
361
+ # resolved
362
+ foo-3.9
363
+ baz-0.1
364
+
365
+ # resolved [replace conflicting]
366
+ foo-3.9
367
+ baz-0.1
368
+ """,
369
+ """
370
+ # id
371
+ installable_with_conflicting_installable_require
372
+
373
+ # installed
374
+ foo-5
375
+
376
+ # installable
377
+ foo-2.9
378
+ baz-0.1
379
+ foo>=2.1,!=3.1,<4
380
+
381
+ # wanted
382
+ baz
383
+
384
+ # resolved
385
+ VersionConflict
386
+
387
+ # resolved [replace conflicting]
388
+ baz-0.1
389
+ foo-2.9
390
+ """,
391
+ """
392
+ # id
393
+ conflicting_installables
394
+
395
+ # installed
396
+
397
+ # installable
398
+ foo-2.9
399
+ foo-5.0
400
+
401
+ # wanted
402
+ foo>=2.1,!=3.1,<4
403
+ foo>=4
404
+
405
+ # resolved
406
+ VersionConflict
407
+
408
+ # resolved [replace conflicting]
409
+ VersionConflict
410
+ """,
411
+ """
412
+ # id
413
+ installables_with_conflicting_requires
414
+
415
+ # installed
416
+
417
+ # installable
418
+ foo-2.9
419
+ dep==1.0
420
+ baz-5.0
421
+ dep==2.0
422
+ dep-1.0
423
+ dep-2.0
424
+
425
+ # wanted
426
+ foo
427
+ baz
428
+
429
+ # resolved
430
+ VersionConflict
431
+
432
+ # resolved [replace conflicting]
433
+ VersionConflict
434
+ """,
435
+ """
436
+ # id
437
+ installables_with_conflicting_nested_requires
438
+
439
+ # installed
440
+
441
+ # installable
442
+ foo-2.9
443
+ dep1
444
+ dep1-1.0
445
+ subdep<1.0
446
+ baz-5.0
447
+ dep2
448
+ dep2-1.0
449
+ subdep>1.0
450
+ subdep-0.9
451
+ subdep-1.1
452
+
453
+ # wanted
454
+ foo
455
+ baz
456
+
457
+ # resolved
458
+ VersionConflict
459
+
460
+ # resolved [replace conflicting]
461
+ VersionConflict
462
+ """,
463
+ """
464
+ # id
465
+ wanted_normalized_name_installed_canonical
466
+
467
+ # installed
468
+ foo.bar-3.6
469
+
470
+ # installable
471
+
472
+ # wanted
473
+ foo-bar==3.6
474
+
475
+ # resolved
476
+ foo.bar-3.6
477
+
478
+ # resolved [replace conflicting]
479
+ foo.bar-3.6
480
+ """,
481
+ )
482
+ def test_working_set_resolve(
483
+ installed_dists,
484
+ installable_dists,
485
+ requirements,
486
+ replace_conflicting,
487
+ resolved_dists_or_exception,
488
+ ):
489
+ ws = pkg_resources.WorkingSet([])
490
+ list(map(ws.add, installed_dists))
491
+ resolve_call = functools.partial(
492
+ ws.resolve,
493
+ requirements,
494
+ installer=FakeInstaller(installable_dists),
495
+ replace_conflicting=replace_conflicting,
496
+ )
497
+ if inspect.isclass(resolved_dists_or_exception):
498
+ with pytest.raises(resolved_dists_or_exception):
499
+ resolve_call()
500
+ else:
501
+ assert sorted(resolve_call()) == sorted(resolved_dists_or_exception)
llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (585 Bytes). View file
 
llava_video/lib/python3.10/site-packages/pybind11/__pycache__/__main__.cpython-310.pyc ADDED
Binary file (2.18 kB). View file
 
llava_video/lib/python3.10/site-packages/pybind11/__pycache__/_version.cpython-310.pyc ADDED
Binary file (623 Bytes). View file
 
llava_video/lib/python3.10/site-packages/pybind11/__pycache__/commands.cpython-310.pyc ADDED
Binary file (1.44 kB). View file
 
llava_video/lib/python3.10/site-packages/pybind11/__pycache__/setup_helpers.cpython-310.pyc ADDED
Binary file (15.4 kB). View file
 
llava_video/lib/python3.10/site-packages/pybind11/_version.py ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+
4
+ def _to_int(s: str) -> int | str:
5
+ try:
6
+ return int(s)
7
+ except ValueError:
8
+ return s
9
+
10
+
11
+ __version__ = "2.13.6"
12
+ version_info = tuple(_to_int(s) for s in __version__.split("."))
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/attr.h ADDED
@@ -0,0 +1,690 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/attr.h: Infrastructure for processing custom
3
+ type and function attributes
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "detail/common.h"
14
+ #include "cast.h"
15
+
16
+ #include <functional>
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
19
+
20
+ /// \addtogroup annotations
21
+ /// @{
22
+
23
+ /// Annotation for methods
24
+ struct is_method {
25
+ handle class_;
26
+ explicit is_method(const handle &c) : class_(c) {}
27
+ };
28
+
29
+ /// Annotation for setters
30
+ struct is_setter {};
31
+
32
+ /// Annotation for operators
33
+ struct is_operator {};
34
+
35
+ /// Annotation for classes that cannot be subclassed
36
+ struct is_final {};
37
+
38
+ /// Annotation for parent scope
39
+ struct scope {
40
+ handle value;
41
+ explicit scope(const handle &s) : value(s) {}
42
+ };
43
+
44
+ /// Annotation for documentation
45
+ struct doc {
46
+ const char *value;
47
+ explicit doc(const char *value) : value(value) {}
48
+ };
49
+
50
+ /// Annotation for function names
51
+ struct name {
52
+ const char *value;
53
+ explicit name(const char *value) : value(value) {}
54
+ };
55
+
56
+ /// Annotation indicating that a function is an overload associated with a given "sibling"
57
+ struct sibling {
58
+ handle value;
59
+ explicit sibling(const handle &value) : value(value.ptr()) {}
60
+ };
61
+
62
+ /// Annotation indicating that a class derives from another given type
63
+ template <typename T>
64
+ struct base {
65
+
66
+ PYBIND11_DEPRECATED(
67
+ "base<T>() was deprecated in favor of specifying 'T' as a template argument to class_")
68
+ base() = default;
69
+ };
70
+
71
+ /// Keep patient alive while nurse lives
72
+ template <size_t Nurse, size_t Patient>
73
+ struct keep_alive {};
74
+
75
+ /// Annotation indicating that a class is involved in a multiple inheritance relationship
76
+ struct multiple_inheritance {};
77
+
78
+ /// Annotation which enables dynamic attributes, i.e. adds `__dict__` to a class
79
+ struct dynamic_attr {};
80
+
81
+ /// Annotation which enables the buffer protocol for a type
82
+ struct buffer_protocol {};
83
+
84
+ /// Annotation which requests that a special metaclass is created for a type
85
+ struct metaclass {
86
+ handle value;
87
+
88
+ PYBIND11_DEPRECATED("py::metaclass() is no longer required. It's turned on by default now.")
89
+ metaclass() = default;
90
+
91
+ /// Override pybind11's default metaclass
92
+ explicit metaclass(handle value) : value(value) {}
93
+ };
94
+
95
+ /// Specifies a custom callback with signature `void (PyHeapTypeObject*)` that
96
+ /// may be used to customize the Python type.
97
+ ///
98
+ /// The callback is invoked immediately before `PyType_Ready`.
99
+ ///
100
+ /// Note: This is an advanced interface, and uses of it may require changes to
101
+ /// work with later versions of pybind11. You may wish to consult the
102
+ /// implementation of `make_new_python_type` in `detail/classes.h` to understand
103
+ /// the context in which the callback will be run.
104
+ struct custom_type_setup {
105
+ using callback = std::function<void(PyHeapTypeObject *heap_type)>;
106
+
107
+ explicit custom_type_setup(callback value) : value(std::move(value)) {}
108
+
109
+ callback value;
110
+ };
111
+
112
+ /// Annotation that marks a class as local to the module:
113
+ struct module_local {
114
+ const bool value;
115
+ constexpr explicit module_local(bool v = true) : value(v) {}
116
+ };
117
+
118
+ /// Annotation to mark enums as an arithmetic type
119
+ struct arithmetic {};
120
+
121
+ /// Mark a function for addition at the beginning of the existing overload chain instead of the end
122
+ struct prepend {};
123
+
124
+ /** \rst
125
+ A call policy which places one or more guard variables (``Ts...``) around the function call.
126
+
127
+ For example, this definition:
128
+
129
+ .. code-block:: cpp
130
+
131
+ m.def("foo", foo, py::call_guard<T>());
132
+
133
+ is equivalent to the following pseudocode:
134
+
135
+ .. code-block:: cpp
136
+
137
+ m.def("foo", [](args...) {
138
+ T scope_guard;
139
+ return foo(args...); // forwarded arguments
140
+ });
141
+ \endrst */
142
+ template <typename... Ts>
143
+ struct call_guard;
144
+
145
+ template <>
146
+ struct call_guard<> {
147
+ using type = detail::void_type;
148
+ };
149
+
150
+ template <typename T>
151
+ struct call_guard<T> {
152
+ static_assert(std::is_default_constructible<T>::value,
153
+ "The guard type must be default constructible");
154
+
155
+ using type = T;
156
+ };
157
+
158
+ template <typename T, typename... Ts>
159
+ struct call_guard<T, Ts...> {
160
+ struct type {
161
+ T guard{}; // Compose multiple guard types with left-to-right default-constructor order
162
+ typename call_guard<Ts...>::type next{};
163
+ };
164
+ };
165
+
166
+ /// @} annotations
167
+
168
+ PYBIND11_NAMESPACE_BEGIN(detail)
169
+ /* Forward declarations */
170
+ enum op_id : int;
171
+ enum op_type : int;
172
+ struct undefined_t;
173
+ template <op_id id, op_type ot, typename L = undefined_t, typename R = undefined_t>
174
+ struct op_;
175
+ void keep_alive_impl(size_t Nurse, size_t Patient, function_call &call, handle ret);
176
+
177
+ /// Internal data structure which holds metadata about a keyword argument
178
+ struct argument_record {
179
+ const char *name; ///< Argument name
180
+ const char *descr; ///< Human-readable version of the argument value
181
+ handle value; ///< Associated Python object
182
+ bool convert : 1; ///< True if the argument is allowed to convert when loading
183
+ bool none : 1; ///< True if None is allowed when loading
184
+
185
+ argument_record(const char *name, const char *descr, handle value, bool convert, bool none)
186
+ : name(name), descr(descr), value(value), convert(convert), none(none) {}
187
+ };
188
+
189
+ /// Internal data structure which holds metadata about a bound function (signature, overloads,
190
+ /// etc.)
191
+ struct function_record {
192
+ function_record()
193
+ : is_constructor(false), is_new_style_constructor(false), is_stateless(false),
194
+ is_operator(false), is_method(false), is_setter(false), has_args(false),
195
+ has_kwargs(false), prepend(false) {}
196
+
197
+ /// Function name
198
+ char *name = nullptr; /* why no C++ strings? They generate heavier code.. */
199
+
200
+ // User-specified documentation string
201
+ char *doc = nullptr;
202
+
203
+ /// Human-readable version of the function signature
204
+ char *signature = nullptr;
205
+
206
+ /// List of registered keyword arguments
207
+ std::vector<argument_record> args;
208
+
209
+ /// Pointer to lambda function which converts arguments and performs the actual call
210
+ handle (*impl)(function_call &) = nullptr;
211
+
212
+ /// Storage for the wrapped function pointer and captured data, if any
213
+ void *data[3] = {};
214
+
215
+ /// Pointer to custom destructor for 'data' (if needed)
216
+ void (*free_data)(function_record *ptr) = nullptr;
217
+
218
+ /// Return value policy associated with this function
219
+ return_value_policy policy = return_value_policy::automatic;
220
+
221
+ /// True if name == '__init__'
222
+ bool is_constructor : 1;
223
+
224
+ /// True if this is a new-style `__init__` defined in `detail/init.h`
225
+ bool is_new_style_constructor : 1;
226
+
227
+ /// True if this is a stateless function pointer
228
+ bool is_stateless : 1;
229
+
230
+ /// True if this is an operator (__add__), etc.
231
+ bool is_operator : 1;
232
+
233
+ /// True if this is a method
234
+ bool is_method : 1;
235
+
236
+ /// True if this is a setter
237
+ bool is_setter : 1;
238
+
239
+ /// True if the function has a '*args' argument
240
+ bool has_args : 1;
241
+
242
+ /// True if the function has a '**kwargs' argument
243
+ bool has_kwargs : 1;
244
+
245
+ /// True if this function is to be inserted at the beginning of the overload resolution chain
246
+ bool prepend : 1;
247
+
248
+ /// Number of arguments (including py::args and/or py::kwargs, if present)
249
+ std::uint16_t nargs;
250
+
251
+ /// Number of leading positional arguments, which are terminated by a py::args or py::kwargs
252
+ /// argument or by a py::kw_only annotation.
253
+ std::uint16_t nargs_pos = 0;
254
+
255
+ /// Number of leading arguments (counted in `nargs`) that are positional-only
256
+ std::uint16_t nargs_pos_only = 0;
257
+
258
+ /// Python method object
259
+ PyMethodDef *def = nullptr;
260
+
261
+ /// Python handle to the parent scope (a class or a module)
262
+ handle scope;
263
+
264
+ /// Python handle to the sibling function representing an overload chain
265
+ handle sibling;
266
+
267
+ /// Pointer to next overload
268
+ function_record *next = nullptr;
269
+ };
270
+
271
+ /// Special data structure which (temporarily) holds metadata about a bound class
272
+ struct type_record {
273
+ PYBIND11_NOINLINE type_record()
274
+ : multiple_inheritance(false), dynamic_attr(false), buffer_protocol(false),
275
+ default_holder(true), module_local(false), is_final(false) {}
276
+
277
+ /// Handle to the parent scope
278
+ handle scope;
279
+
280
+ /// Name of the class
281
+ const char *name = nullptr;
282
+
283
+ // Pointer to RTTI type_info data structure
284
+ const std::type_info *type = nullptr;
285
+
286
+ /// How large is the underlying C++ type?
287
+ size_t type_size = 0;
288
+
289
+ /// What is the alignment of the underlying C++ type?
290
+ size_t type_align = 0;
291
+
292
+ /// How large is the type's holder?
293
+ size_t holder_size = 0;
294
+
295
+ /// The global operator new can be overridden with a class-specific variant
296
+ void *(*operator_new)(size_t) = nullptr;
297
+
298
+ /// Function pointer to class_<..>::init_instance
299
+ void (*init_instance)(instance *, const void *) = nullptr;
300
+
301
+ /// Function pointer to class_<..>::dealloc
302
+ void (*dealloc)(detail::value_and_holder &) = nullptr;
303
+
304
+ /// List of base classes of the newly created type
305
+ list bases;
306
+
307
+ /// Optional docstring
308
+ const char *doc = nullptr;
309
+
310
+ /// Custom metaclass (optional)
311
+ handle metaclass;
312
+
313
+ /// Custom type setup.
314
+ custom_type_setup::callback custom_type_setup_callback;
315
+
316
+ /// Multiple inheritance marker
317
+ bool multiple_inheritance : 1;
318
+
319
+ /// Does the class manage a __dict__?
320
+ bool dynamic_attr : 1;
321
+
322
+ /// Does the class implement the buffer protocol?
323
+ bool buffer_protocol : 1;
324
+
325
+ /// Is the default (unique_ptr) holder type used?
326
+ bool default_holder : 1;
327
+
328
+ /// Is the class definition local to the module shared object?
329
+ bool module_local : 1;
330
+
331
+ /// Is the class inheritable from python classes?
332
+ bool is_final : 1;
333
+
334
+ PYBIND11_NOINLINE void add_base(const std::type_info &base, void *(*caster)(void *) ) {
335
+ auto *base_info = detail::get_type_info(base, false);
336
+ if (!base_info) {
337
+ std::string tname(base.name());
338
+ detail::clean_type_id(tname);
339
+ pybind11_fail("generic_type: type \"" + std::string(name)
340
+ + "\" referenced unknown base type \"" + tname + "\"");
341
+ }
342
+
343
+ if (default_holder != base_info->default_holder) {
344
+ std::string tname(base.name());
345
+ detail::clean_type_id(tname);
346
+ pybind11_fail("generic_type: type \"" + std::string(name) + "\" "
347
+ + (default_holder ? "does not have" : "has")
348
+ + " a non-default holder type while its base \"" + tname + "\" "
349
+ + (base_info->default_holder ? "does not" : "does"));
350
+ }
351
+
352
+ bases.append((PyObject *) base_info->type);
353
+
354
+ #if PY_VERSION_HEX < 0x030B0000
355
+ dynamic_attr |= base_info->type->tp_dictoffset != 0;
356
+ #else
357
+ dynamic_attr |= (base_info->type->tp_flags & Py_TPFLAGS_MANAGED_DICT) != 0;
358
+ #endif
359
+
360
+ if (caster) {
361
+ base_info->implicit_casts.emplace_back(type, caster);
362
+ }
363
+ }
364
+ };
365
+
366
+ inline function_call::function_call(const function_record &f, handle p) : func(f), parent(p) {
367
+ args.reserve(f.nargs);
368
+ args_convert.reserve(f.nargs);
369
+ }
370
+
371
+ /// Tag for a new-style `__init__` defined in `detail/init.h`
372
+ struct is_new_style_constructor {};
373
+
374
+ /**
375
+ * Partial template specializations to process custom attributes provided to
376
+ * cpp_function_ and class_. These are either used to initialize the respective
377
+ * fields in the type_record and function_record data structures or executed at
378
+ * runtime to deal with custom call policies (e.g. keep_alive).
379
+ */
380
+ template <typename T, typename SFINAE = void>
381
+ struct process_attribute;
382
+
383
+ template <typename T>
384
+ struct process_attribute_default {
385
+ /// Default implementation: do nothing
386
+ static void init(const T &, function_record *) {}
387
+ static void init(const T &, type_record *) {}
388
+ static void precall(function_call &) {}
389
+ static void postcall(function_call &, handle) {}
390
+ };
391
+
392
+ /// Process an attribute specifying the function's name
393
+ template <>
394
+ struct process_attribute<name> : process_attribute_default<name> {
395
+ static void init(const name &n, function_record *r) { r->name = const_cast<char *>(n.value); }
396
+ };
397
+
398
+ /// Process an attribute specifying the function's docstring
399
+ template <>
400
+ struct process_attribute<doc> : process_attribute_default<doc> {
401
+ static void init(const doc &n, function_record *r) { r->doc = const_cast<char *>(n.value); }
402
+ };
403
+
404
+ /// Process an attribute specifying the function's docstring (provided as a C-style string)
405
+ template <>
406
+ struct process_attribute<const char *> : process_attribute_default<const char *> {
407
+ static void init(const char *d, function_record *r) { r->doc = const_cast<char *>(d); }
408
+ static void init(const char *d, type_record *r) { r->doc = d; }
409
+ };
410
+ template <>
411
+ struct process_attribute<char *> : process_attribute<const char *> {};
412
+
413
+ /// Process an attribute indicating the function's return value policy
414
+ template <>
415
+ struct process_attribute<return_value_policy> : process_attribute_default<return_value_policy> {
416
+ static void init(const return_value_policy &p, function_record *r) { r->policy = p; }
417
+ };
418
+
419
+ /// Process an attribute which indicates that this is an overloaded function associated with a
420
+ /// given sibling
421
+ template <>
422
+ struct process_attribute<sibling> : process_attribute_default<sibling> {
423
+ static void init(const sibling &s, function_record *r) { r->sibling = s.value; }
424
+ };
425
+
426
+ /// Process an attribute which indicates that this function is a method
427
+ template <>
428
+ struct process_attribute<is_method> : process_attribute_default<is_method> {
429
+ static void init(const is_method &s, function_record *r) {
430
+ r->is_method = true;
431
+ r->scope = s.class_;
432
+ }
433
+ };
434
+
435
+ /// Process an attribute which indicates that this function is a setter
436
+ template <>
437
+ struct process_attribute<is_setter> : process_attribute_default<is_setter> {
438
+ static void init(const is_setter &, function_record *r) { r->is_setter = true; }
439
+ };
440
+
441
+ /// Process an attribute which indicates the parent scope of a method
442
+ template <>
443
+ struct process_attribute<scope> : process_attribute_default<scope> {
444
+ static void init(const scope &s, function_record *r) { r->scope = s.value; }
445
+ };
446
+
447
+ /// Process an attribute which indicates that this function is an operator
448
+ template <>
449
+ struct process_attribute<is_operator> : process_attribute_default<is_operator> {
450
+ static void init(const is_operator &, function_record *r) { r->is_operator = true; }
451
+ };
452
+
453
+ template <>
454
+ struct process_attribute<is_new_style_constructor>
455
+ : process_attribute_default<is_new_style_constructor> {
456
+ static void init(const is_new_style_constructor &, function_record *r) {
457
+ r->is_new_style_constructor = true;
458
+ }
459
+ };
460
+
461
+ inline void check_kw_only_arg(const arg &a, function_record *r) {
462
+ if (r->args.size() > r->nargs_pos && (!a.name || a.name[0] == '\0')) {
463
+ pybind11_fail("arg(): cannot specify an unnamed argument after a kw_only() annotation or "
464
+ "args() argument");
465
+ }
466
+ }
467
+
468
+ inline void append_self_arg_if_needed(function_record *r) {
469
+ if (r->is_method && r->args.empty()) {
470
+ r->args.emplace_back("self", nullptr, handle(), /*convert=*/true, /*none=*/false);
471
+ }
472
+ }
473
+
474
+ /// Process a keyword argument attribute (*without* a default value)
475
+ template <>
476
+ struct process_attribute<arg> : process_attribute_default<arg> {
477
+ static void init(const arg &a, function_record *r) {
478
+ append_self_arg_if_needed(r);
479
+ r->args.emplace_back(a.name, nullptr, handle(), !a.flag_noconvert, a.flag_none);
480
+
481
+ check_kw_only_arg(a, r);
482
+ }
483
+ };
484
+
485
+ /// Process a keyword argument attribute (*with* a default value)
486
+ template <>
487
+ struct process_attribute<arg_v> : process_attribute_default<arg_v> {
488
+ static void init(const arg_v &a, function_record *r) {
489
+ if (r->is_method && r->args.empty()) {
490
+ r->args.emplace_back(
491
+ "self", /*descr=*/nullptr, /*parent=*/handle(), /*convert=*/true, /*none=*/false);
492
+ }
493
+
494
+ if (!a.value) {
495
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
496
+ std::string descr("'");
497
+ if (a.name) {
498
+ descr += std::string(a.name) + ": ";
499
+ }
500
+ descr += a.type + "'";
501
+ if (r->is_method) {
502
+ if (r->name) {
503
+ descr += " in method '" + (std::string) str(r->scope) + "."
504
+ + (std::string) r->name + "'";
505
+ } else {
506
+ descr += " in method of '" + (std::string) str(r->scope) + "'";
507
+ }
508
+ } else if (r->name) {
509
+ descr += " in function '" + (std::string) r->name + "'";
510
+ }
511
+ pybind11_fail("arg(): could not convert default argument " + descr
512
+ + " into a Python object (type not registered yet?)");
513
+ #else
514
+ pybind11_fail("arg(): could not convert default argument "
515
+ "into a Python object (type not registered yet?). "
516
+ "#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
517
+ "more information.");
518
+ #endif
519
+ }
520
+ r->args.emplace_back(a.name, a.descr, a.value.inc_ref(), !a.flag_noconvert, a.flag_none);
521
+
522
+ check_kw_only_arg(a, r);
523
+ }
524
+ };
525
+
526
+ /// Process a keyword-only-arguments-follow pseudo argument
527
+ template <>
528
+ struct process_attribute<kw_only> : process_attribute_default<kw_only> {
529
+ static void init(const kw_only &, function_record *r) {
530
+ append_self_arg_if_needed(r);
531
+ if (r->has_args && r->nargs_pos != static_cast<std::uint16_t>(r->args.size())) {
532
+ pybind11_fail("Mismatched args() and kw_only(): they must occur at the same relative "
533
+ "argument location (or omit kw_only() entirely)");
534
+ }
535
+ r->nargs_pos = static_cast<std::uint16_t>(r->args.size());
536
+ }
537
+ };
538
+
539
+ /// Process a positional-only-argument maker
540
+ template <>
541
+ struct process_attribute<pos_only> : process_attribute_default<pos_only> {
542
+ static void init(const pos_only &, function_record *r) {
543
+ append_self_arg_if_needed(r);
544
+ r->nargs_pos_only = static_cast<std::uint16_t>(r->args.size());
545
+ if (r->nargs_pos_only > r->nargs_pos) {
546
+ pybind11_fail("pos_only(): cannot follow a py::args() argument");
547
+ }
548
+ // It also can't follow a kw_only, but a static_assert in pybind11.h checks that
549
+ }
550
+ };
551
+
552
+ /// Process a parent class attribute. Single inheritance only (class_ itself already guarantees
553
+ /// that)
554
+ template <typename T>
555
+ struct process_attribute<T, enable_if_t<is_pyobject<T>::value>>
556
+ : process_attribute_default<handle> {
557
+ static void init(const handle &h, type_record *r) { r->bases.append(h); }
558
+ };
559
+
560
+ /// Process a parent class attribute (deprecated, does not support multiple inheritance)
561
+ template <typename T>
562
+ struct process_attribute<base<T>> : process_attribute_default<base<T>> {
563
+ static void init(const base<T> &, type_record *r) { r->add_base(typeid(T), nullptr); }
564
+ };
565
+
566
+ /// Process a multiple inheritance attribute
567
+ template <>
568
+ struct process_attribute<multiple_inheritance> : process_attribute_default<multiple_inheritance> {
569
+ static void init(const multiple_inheritance &, type_record *r) {
570
+ r->multiple_inheritance = true;
571
+ }
572
+ };
573
+
574
+ template <>
575
+ struct process_attribute<dynamic_attr> : process_attribute_default<dynamic_attr> {
576
+ static void init(const dynamic_attr &, type_record *r) { r->dynamic_attr = true; }
577
+ };
578
+
579
+ template <>
580
+ struct process_attribute<custom_type_setup> {
581
+ static void init(const custom_type_setup &value, type_record *r) {
582
+ r->custom_type_setup_callback = value.value;
583
+ }
584
+ };
585
+
586
+ template <>
587
+ struct process_attribute<is_final> : process_attribute_default<is_final> {
588
+ static void init(const is_final &, type_record *r) { r->is_final = true; }
589
+ };
590
+
591
+ template <>
592
+ struct process_attribute<buffer_protocol> : process_attribute_default<buffer_protocol> {
593
+ static void init(const buffer_protocol &, type_record *r) { r->buffer_protocol = true; }
594
+ };
595
+
596
+ template <>
597
+ struct process_attribute<metaclass> : process_attribute_default<metaclass> {
598
+ static void init(const metaclass &m, type_record *r) { r->metaclass = m.value; }
599
+ };
600
+
601
+ template <>
602
+ struct process_attribute<module_local> : process_attribute_default<module_local> {
603
+ static void init(const module_local &l, type_record *r) { r->module_local = l.value; }
604
+ };
605
+
606
+ /// Process a 'prepend' attribute, putting this at the beginning of the overload chain
607
+ template <>
608
+ struct process_attribute<prepend> : process_attribute_default<prepend> {
609
+ static void init(const prepend &, function_record *r) { r->prepend = true; }
610
+ };
611
+
612
+ /// Process an 'arithmetic' attribute for enums (does nothing here)
613
+ template <>
614
+ struct process_attribute<arithmetic> : process_attribute_default<arithmetic> {};
615
+
616
+ template <typename... Ts>
617
+ struct process_attribute<call_guard<Ts...>> : process_attribute_default<call_guard<Ts...>> {};
618
+
619
+ /**
620
+ * Process a keep_alive call policy -- invokes keep_alive_impl during the
621
+ * pre-call handler if both Nurse, Patient != 0 and use the post-call handler
622
+ * otherwise
623
+ */
624
+ template <size_t Nurse, size_t Patient>
625
+ struct process_attribute<keep_alive<Nurse, Patient>>
626
+ : public process_attribute_default<keep_alive<Nurse, Patient>> {
627
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
628
+ static void precall(function_call &call) {
629
+ keep_alive_impl(Nurse, Patient, call, handle());
630
+ }
631
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N != 0 && P != 0, int> = 0>
632
+ static void postcall(function_call &, handle) {}
633
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
634
+ static void precall(function_call &) {}
635
+ template <size_t N = Nurse, size_t P = Patient, enable_if_t<N == 0 || P == 0, int> = 0>
636
+ static void postcall(function_call &call, handle ret) {
637
+ keep_alive_impl(Nurse, Patient, call, ret);
638
+ }
639
+ };
640
+
641
+ /// Recursively iterate over variadic template arguments
642
+ template <typename... Args>
643
+ struct process_attributes {
644
+ static void init(const Args &...args, function_record *r) {
645
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
646
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
647
+ using expander = int[];
648
+ (void) expander{
649
+ 0, ((void) process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
650
+ }
651
+ static void init(const Args &...args, type_record *r) {
652
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(r);
653
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(r);
654
+ using expander = int[];
655
+ (void) expander{0,
656
+ (process_attribute<typename std::decay<Args>::type>::init(args, r), 0)...};
657
+ }
658
+ static void precall(function_call &call) {
659
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call);
660
+ using expander = int[];
661
+ (void) expander{0,
662
+ (process_attribute<typename std::decay<Args>::type>::precall(call), 0)...};
663
+ }
664
+ static void postcall(function_call &call, handle fn_ret) {
665
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(call, fn_ret);
666
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(fn_ret);
667
+ using expander = int[];
668
+ (void) expander{
669
+ 0, (process_attribute<typename std::decay<Args>::type>::postcall(call, fn_ret), 0)...};
670
+ }
671
+ };
672
+
673
+ template <typename T>
674
+ using is_call_guard = is_instantiation<call_guard, T>;
675
+
676
+ /// Extract the ``type`` from the first `call_guard` in `Extras...` (or `void_type` if none found)
677
+ template <typename... Extra>
678
+ using extract_guard_t = typename exactly_one_t<is_call_guard, call_guard<>, Extra...>::type;
679
+
680
+ /// Check the number of named arguments at compile time
681
+ template <typename... Extra,
682
+ size_t named = constexpr_sum(std::is_base_of<arg, Extra>::value...),
683
+ size_t self = constexpr_sum(std::is_same<is_method, Extra>::value...)>
684
+ constexpr bool expected_num_args(size_t nargs, bool has_args, bool has_kwargs) {
685
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(nargs, has_args, has_kwargs);
686
+ return named == 0 || (self + named + size_t(has_args) + size_t(has_kwargs)) == nargs;
687
+ }
688
+
689
+ PYBIND11_NAMESPACE_END(detail)
690
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/buffer_info.h ADDED
@@ -0,0 +1,208 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/buffer_info.h: Python buffer object interface
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "detail/common.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+
16
+ PYBIND11_NAMESPACE_BEGIN(detail)
17
+
18
+ // Default, C-style strides
19
+ inline std::vector<ssize_t> c_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
20
+ auto ndim = shape.size();
21
+ std::vector<ssize_t> strides(ndim, itemsize);
22
+ if (ndim > 0) {
23
+ for (size_t i = ndim - 1; i > 0; --i) {
24
+ strides[i - 1] = strides[i] * shape[i];
25
+ }
26
+ }
27
+ return strides;
28
+ }
29
+
30
+ // F-style strides; default when constructing an array_t with `ExtraFlags & f_style`
31
+ inline std::vector<ssize_t> f_strides(const std::vector<ssize_t> &shape, ssize_t itemsize) {
32
+ auto ndim = shape.size();
33
+ std::vector<ssize_t> strides(ndim, itemsize);
34
+ for (size_t i = 1; i < ndim; ++i) {
35
+ strides[i] = strides[i - 1] * shape[i - 1];
36
+ }
37
+ return strides;
38
+ }
39
+
40
+ template <typename T, typename SFINAE = void>
41
+ struct compare_buffer_info;
42
+
43
+ PYBIND11_NAMESPACE_END(detail)
44
+
45
+ /// Information record describing a Python buffer object
46
+ struct buffer_info {
47
+ void *ptr = nullptr; // Pointer to the underlying storage
48
+ ssize_t itemsize = 0; // Size of individual items in bytes
49
+ ssize_t size = 0; // Total number of entries
50
+ std::string format; // For homogeneous buffers, this should be set to
51
+ // format_descriptor<T>::format()
52
+ ssize_t ndim = 0; // Number of dimensions
53
+ std::vector<ssize_t> shape; // Shape of the tensor (1 entry per dimension)
54
+ std::vector<ssize_t> strides; // Number of bytes between adjacent entries
55
+ // (for each per dimension)
56
+ bool readonly = false; // flag to indicate if the underlying storage may be written to
57
+
58
+ buffer_info() = default;
59
+
60
+ buffer_info(void *ptr,
61
+ ssize_t itemsize,
62
+ const std::string &format,
63
+ ssize_t ndim,
64
+ detail::any_container<ssize_t> shape_in,
65
+ detail::any_container<ssize_t> strides_in,
66
+ bool readonly = false)
67
+ : ptr(ptr), itemsize(itemsize), size(1), format(format), ndim(ndim),
68
+ shape(std::move(shape_in)), strides(std::move(strides_in)), readonly(readonly) {
69
+ if (ndim != (ssize_t) shape.size() || ndim != (ssize_t) strides.size()) {
70
+ pybind11_fail("buffer_info: ndim doesn't match shape and/or strides length");
71
+ }
72
+ for (size_t i = 0; i < (size_t) ndim; ++i) {
73
+ size *= shape[i];
74
+ }
75
+ }
76
+
77
+ template <typename T>
78
+ buffer_info(T *ptr,
79
+ detail::any_container<ssize_t> shape_in,
80
+ detail::any_container<ssize_t> strides_in,
81
+ bool readonly = false)
82
+ : buffer_info(private_ctr_tag(),
83
+ ptr,
84
+ sizeof(T),
85
+ format_descriptor<T>::format(),
86
+ static_cast<ssize_t>(shape_in->size()),
87
+ std::move(shape_in),
88
+ std::move(strides_in),
89
+ readonly) {}
90
+
91
+ buffer_info(void *ptr,
92
+ ssize_t itemsize,
93
+ const std::string &format,
94
+ ssize_t size,
95
+ bool readonly = false)
96
+ : buffer_info(ptr, itemsize, format, 1, {size}, {itemsize}, readonly) {}
97
+
98
+ template <typename T>
99
+ buffer_info(T *ptr, ssize_t size, bool readonly = false)
100
+ : buffer_info(ptr, sizeof(T), format_descriptor<T>::format(), size, readonly) {}
101
+
102
+ template <typename T>
103
+ buffer_info(const T *ptr, ssize_t size, bool readonly = true)
104
+ : buffer_info(
105
+ const_cast<T *>(ptr), sizeof(T), format_descriptor<T>::format(), size, readonly) {}
106
+
107
+ explicit buffer_info(Py_buffer *view, bool ownview = true)
108
+ : buffer_info(
109
+ view->buf,
110
+ view->itemsize,
111
+ view->format,
112
+ view->ndim,
113
+ {view->shape, view->shape + view->ndim},
114
+ /* Though buffer::request() requests PyBUF_STRIDES, ctypes objects
115
+ * ignore this flag and return a view with NULL strides.
116
+ * When strides are NULL, build them manually. */
117
+ view->strides
118
+ ? std::vector<ssize_t>(view->strides, view->strides + view->ndim)
119
+ : detail::c_strides({view->shape, view->shape + view->ndim}, view->itemsize),
120
+ (view->readonly != 0)) {
121
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
122
+ this->m_view = view;
123
+ // NOLINTNEXTLINE(cppcoreguidelines-prefer-member-initializer)
124
+ this->ownview = ownview;
125
+ }
126
+
127
+ buffer_info(const buffer_info &) = delete;
128
+ buffer_info &operator=(const buffer_info &) = delete;
129
+
130
+ buffer_info(buffer_info &&other) noexcept { (*this) = std::move(other); }
131
+
132
+ buffer_info &operator=(buffer_info &&rhs) noexcept {
133
+ ptr = rhs.ptr;
134
+ itemsize = rhs.itemsize;
135
+ size = rhs.size;
136
+ format = std::move(rhs.format);
137
+ ndim = rhs.ndim;
138
+ shape = std::move(rhs.shape);
139
+ strides = std::move(rhs.strides);
140
+ std::swap(m_view, rhs.m_view);
141
+ std::swap(ownview, rhs.ownview);
142
+ readonly = rhs.readonly;
143
+ return *this;
144
+ }
145
+
146
+ ~buffer_info() {
147
+ if (m_view && ownview) {
148
+ PyBuffer_Release(m_view);
149
+ delete m_view;
150
+ }
151
+ }
152
+
153
+ Py_buffer *view() const { return m_view; }
154
+ Py_buffer *&view() { return m_view; }
155
+
156
+ /* True if the buffer item type is equivalent to `T`. */
157
+ // To define "equivalent" by example:
158
+ // `buffer_info::item_type_is_equivalent_to<int>(b)` and
159
+ // `buffer_info::item_type_is_equivalent_to<long>(b)` may both be true
160
+ // on some platforms, but `int` and `unsigned` will never be equivalent.
161
+ // For the ground truth, please inspect `detail::compare_buffer_info<>`.
162
+ template <typename T>
163
+ bool item_type_is_equivalent_to() const {
164
+ return detail::compare_buffer_info<T>::compare(*this);
165
+ }
166
+
167
+ private:
168
+ struct private_ctr_tag {};
169
+
170
+ buffer_info(private_ctr_tag,
171
+ void *ptr,
172
+ ssize_t itemsize,
173
+ const std::string &format,
174
+ ssize_t ndim,
175
+ detail::any_container<ssize_t> &&shape_in,
176
+ detail::any_container<ssize_t> &&strides_in,
177
+ bool readonly)
178
+ : buffer_info(
179
+ ptr, itemsize, format, ndim, std::move(shape_in), std::move(strides_in), readonly) {}
180
+
181
+ Py_buffer *m_view = nullptr;
182
+ bool ownview = false;
183
+ };
184
+
185
+ PYBIND11_NAMESPACE_BEGIN(detail)
186
+
187
+ template <typename T, typename SFINAE>
188
+ struct compare_buffer_info {
189
+ static bool compare(const buffer_info &b) {
190
+ // NOLINTNEXTLINE(bugprone-sizeof-expression) Needed for `PyObject *`
191
+ return b.format == format_descriptor<T>::format() && b.itemsize == (ssize_t) sizeof(T);
192
+ }
193
+ };
194
+
195
+ template <typename T>
196
+ struct compare_buffer_info<T, detail::enable_if_t<std::is_integral<T>::value>> {
197
+ static bool compare(const buffer_info &b) {
198
+ return (size_t) b.itemsize == sizeof(T)
199
+ && (b.format == format_descriptor<T>::value
200
+ || ((sizeof(T) == sizeof(long))
201
+ && b.format == (std::is_unsigned<T>::value ? "L" : "l"))
202
+ || ((sizeof(T) == sizeof(size_t))
203
+ && b.format == (std::is_unsigned<T>::value ? "N" : "n")));
204
+ }
205
+ };
206
+
207
+ PYBIND11_NAMESPACE_END(detail)
208
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/cast.h ADDED
@@ -0,0 +1,1855 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/cast.h: Partial template specializations to cast between
3
+ C++ and Python types
4
+
5
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "detail/common.h"
14
+ #include "detail/descr.h"
15
+ #include "detail/type_caster_base.h"
16
+ #include "detail/typeid.h"
17
+ #include "pytypes.h"
18
+
19
+ #include <array>
20
+ #include <cstring>
21
+ #include <functional>
22
+ #include <iosfwd>
23
+ #include <iterator>
24
+ #include <memory>
25
+ #include <string>
26
+ #include <tuple>
27
+ #include <type_traits>
28
+ #include <utility>
29
+ #include <vector>
30
+
31
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
32
+
33
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
34
+
35
+ PYBIND11_NAMESPACE_BEGIN(detail)
36
+
37
+ template <typename type, typename SFINAE = void>
38
+ class type_caster : public type_caster_base<type> {};
39
+ template <typename type>
40
+ using make_caster = type_caster<intrinsic_t<type>>;
41
+
42
+ // Shortcut for calling a caster's `cast_op_type` cast operator for casting a type_caster to a T
43
+ template <typename T>
44
+ typename make_caster<T>::template cast_op_type<T> cast_op(make_caster<T> &caster) {
45
+ using result_t = typename make_caster<T>::template cast_op_type<T>; // See PR #4893
46
+ return caster.operator result_t();
47
+ }
48
+ template <typename T>
49
+ typename make_caster<T>::template cast_op_type<typename std::add_rvalue_reference<T>::type>
50
+ cast_op(make_caster<T> &&caster) {
51
+ using result_t = typename make_caster<T>::template cast_op_type<
52
+ typename std::add_rvalue_reference<T>::type>; // See PR #4893
53
+ return std::move(caster).operator result_t();
54
+ }
55
+
56
+ template <typename type>
57
+ class type_caster<std::reference_wrapper<type>> {
58
+ private:
59
+ using caster_t = make_caster<type>;
60
+ caster_t subcaster;
61
+ using reference_t = type &;
62
+ using subcaster_cast_op_type = typename caster_t::template cast_op_type<reference_t>;
63
+
64
+ static_assert(
65
+ std::is_same<typename std::remove_const<type>::type &, subcaster_cast_op_type>::value
66
+ || std::is_same<reference_t, subcaster_cast_op_type>::value,
67
+ "std::reference_wrapper<T> caster requires T to have a caster with an "
68
+ "`operator T &()` or `operator const T &()`");
69
+
70
+ public:
71
+ bool load(handle src, bool convert) { return subcaster.load(src, convert); }
72
+ static constexpr auto name = caster_t::name;
73
+ static handle
74
+ cast(const std::reference_wrapper<type> &src, return_value_policy policy, handle parent) {
75
+ // It is definitely wrong to take ownership of this pointer, so mask that rvp
76
+ if (policy == return_value_policy::take_ownership
77
+ || policy == return_value_policy::automatic) {
78
+ policy = return_value_policy::automatic_reference;
79
+ }
80
+ return caster_t::cast(&src.get(), policy, parent);
81
+ }
82
+ template <typename T>
83
+ using cast_op_type = std::reference_wrapper<type>;
84
+ explicit operator std::reference_wrapper<type>() { return cast_op<type &>(subcaster); }
85
+ };
86
+
87
+ #define PYBIND11_TYPE_CASTER(type, py_name) \
88
+ protected: \
89
+ type value; \
90
+ \
91
+ public: \
92
+ static constexpr auto name = py_name; \
93
+ template <typename T_, \
94
+ ::pybind11::detail::enable_if_t< \
95
+ std::is_same<type, ::pybind11::detail::remove_cv_t<T_>>::value, \
96
+ int> \
97
+ = 0> \
98
+ static ::pybind11::handle cast( \
99
+ T_ *src, ::pybind11::return_value_policy policy, ::pybind11::handle parent) { \
100
+ if (!src) \
101
+ return ::pybind11::none().release(); \
102
+ if (policy == ::pybind11::return_value_policy::take_ownership) { \
103
+ auto h = cast(std::move(*src), policy, parent); \
104
+ delete src; \
105
+ return h; \
106
+ } \
107
+ return cast(*src, policy, parent); \
108
+ } \
109
+ operator type *() { return &value; } /* NOLINT(bugprone-macro-parentheses) */ \
110
+ operator type &() { return value; } /* NOLINT(bugprone-macro-parentheses) */ \
111
+ operator type &&() && { return std::move(value); } /* NOLINT(bugprone-macro-parentheses) */ \
112
+ template <typename T_> \
113
+ using cast_op_type = ::pybind11::detail::movable_cast_op_type<T_>
114
+
115
+ template <typename CharT>
116
+ using is_std_char_type = any_of<std::is_same<CharT, char>, /* std::string */
117
+ #if defined(PYBIND11_HAS_U8STRING)
118
+ std::is_same<CharT, char8_t>, /* std::u8string */
119
+ #endif
120
+ std::is_same<CharT, char16_t>, /* std::u16string */
121
+ std::is_same<CharT, char32_t>, /* std::u32string */
122
+ std::is_same<CharT, wchar_t> /* std::wstring */
123
+ >;
124
+
125
+ template <typename T>
126
+ struct type_caster<T, enable_if_t<std::is_arithmetic<T>::value && !is_std_char_type<T>::value>> {
127
+ using _py_type_0 = conditional_t<sizeof(T) <= sizeof(long), long, long long>;
128
+ using _py_type_1 = conditional_t<std::is_signed<T>::value,
129
+ _py_type_0,
130
+ typename std::make_unsigned<_py_type_0>::type>;
131
+ using py_type = conditional_t<std::is_floating_point<T>::value, double, _py_type_1>;
132
+
133
+ public:
134
+ bool load(handle src, bool convert) {
135
+ py_type py_value;
136
+
137
+ if (!src) {
138
+ return false;
139
+ }
140
+
141
+ #if !defined(PYPY_VERSION)
142
+ auto index_check = [](PyObject *o) { return PyIndex_Check(o); };
143
+ #else
144
+ // In PyPy 7.3.3, `PyIndex_Check` is implemented by calling `__index__`,
145
+ // while CPython only considers the existence of `nb_index`/`__index__`.
146
+ auto index_check = [](PyObject *o) { return hasattr(o, "__index__"); };
147
+ #endif
148
+
149
+ if (std::is_floating_point<T>::value) {
150
+ if (convert || PyFloat_Check(src.ptr())) {
151
+ py_value = (py_type) PyFloat_AsDouble(src.ptr());
152
+ } else {
153
+ return false;
154
+ }
155
+ } else if (PyFloat_Check(src.ptr())
156
+ || (!convert && !PYBIND11_LONG_CHECK(src.ptr()) && !index_check(src.ptr()))) {
157
+ return false;
158
+ } else {
159
+ handle src_or_index = src;
160
+ // PyPy: 7.3.7's 3.8 does not implement PyLong_*'s __index__ calls.
161
+ #if PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
162
+ object index;
163
+ if (!PYBIND11_LONG_CHECK(src.ptr())) { // So: index_check(src.ptr())
164
+ index = reinterpret_steal<object>(PyNumber_Index(src.ptr()));
165
+ if (!index) {
166
+ PyErr_Clear();
167
+ if (!convert)
168
+ return false;
169
+ } else {
170
+ src_or_index = index;
171
+ }
172
+ }
173
+ #endif
174
+ if (std::is_unsigned<py_type>::value) {
175
+ py_value = as_unsigned<py_type>(src_or_index.ptr());
176
+ } else { // signed integer:
177
+ py_value = sizeof(T) <= sizeof(long)
178
+ ? (py_type) PyLong_AsLong(src_or_index.ptr())
179
+ : (py_type) PYBIND11_LONG_AS_LONGLONG(src_or_index.ptr());
180
+ }
181
+ }
182
+
183
+ // Python API reported an error
184
+ bool py_err = py_value == (py_type) -1 && PyErr_Occurred();
185
+
186
+ // Check to see if the conversion is valid (integers should match exactly)
187
+ // Signed/unsigned checks happen elsewhere
188
+ if (py_err
189
+ || (std::is_integral<T>::value && sizeof(py_type) != sizeof(T)
190
+ && py_value != (py_type) (T) py_value)) {
191
+ PyErr_Clear();
192
+ if (py_err && convert && (PyNumber_Check(src.ptr()) != 0)) {
193
+ auto tmp = reinterpret_steal<object>(std::is_floating_point<T>::value
194
+ ? PyNumber_Float(src.ptr())
195
+ : PyNumber_Long(src.ptr()));
196
+ PyErr_Clear();
197
+ return load(tmp, false);
198
+ }
199
+ return false;
200
+ }
201
+
202
+ value = (T) py_value;
203
+ return true;
204
+ }
205
+
206
+ template <typename U = T>
207
+ static typename std::enable_if<std::is_floating_point<U>::value, handle>::type
208
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
209
+ return PyFloat_FromDouble((double) src);
210
+ }
211
+
212
+ template <typename U = T>
213
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
214
+ && (sizeof(U) <= sizeof(long)),
215
+ handle>::type
216
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
217
+ return PYBIND11_LONG_FROM_SIGNED((long) src);
218
+ }
219
+
220
+ template <typename U = T>
221
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
222
+ && (sizeof(U) <= sizeof(unsigned long)),
223
+ handle>::type
224
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
225
+ return PYBIND11_LONG_FROM_UNSIGNED((unsigned long) src);
226
+ }
227
+
228
+ template <typename U = T>
229
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_signed<U>::value
230
+ && (sizeof(U) > sizeof(long)),
231
+ handle>::type
232
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
233
+ return PyLong_FromLongLong((long long) src);
234
+ }
235
+
236
+ template <typename U = T>
237
+ static typename std::enable_if<!std::is_floating_point<U>::value && std::is_unsigned<U>::value
238
+ && (sizeof(U) > sizeof(unsigned long)),
239
+ handle>::type
240
+ cast(U src, return_value_policy /* policy */, handle /* parent */) {
241
+ return PyLong_FromUnsignedLongLong((unsigned long long) src);
242
+ }
243
+
244
+ PYBIND11_TYPE_CASTER(T, const_name<std::is_integral<T>::value>("int", "float"));
245
+ };
246
+
247
+ template <typename T>
248
+ struct void_caster {
249
+ public:
250
+ bool load(handle src, bool) {
251
+ if (src && src.is_none()) {
252
+ return true;
253
+ }
254
+ return false;
255
+ }
256
+ static handle cast(T, return_value_policy /* policy */, handle /* parent */) {
257
+ return none().release();
258
+ }
259
+ PYBIND11_TYPE_CASTER(T, const_name("None"));
260
+ };
261
+
262
+ template <>
263
+ class type_caster<void_type> : public void_caster<void_type> {};
264
+
265
+ template <>
266
+ class type_caster<void> : public type_caster<void_type> {
267
+ public:
268
+ using type_caster<void_type>::cast;
269
+
270
+ bool load(handle h, bool) {
271
+ if (!h) {
272
+ return false;
273
+ }
274
+ if (h.is_none()) {
275
+ value = nullptr;
276
+ return true;
277
+ }
278
+
279
+ /* Check if this is a capsule */
280
+ if (isinstance<capsule>(h)) {
281
+ value = reinterpret_borrow<capsule>(h);
282
+ return true;
283
+ }
284
+
285
+ /* Check if this is a C++ type */
286
+ const auto &bases = all_type_info((PyTypeObject *) type::handle_of(h).ptr());
287
+ if (bases.size() == 1) { // Only allowing loading from a single-value type
288
+ value = values_and_holders(reinterpret_cast<instance *>(h.ptr())).begin()->value_ptr();
289
+ return true;
290
+ }
291
+
292
+ /* Fail */
293
+ return false;
294
+ }
295
+
296
+ static handle cast(const void *ptr, return_value_policy /* policy */, handle /* parent */) {
297
+ if (ptr) {
298
+ return capsule(ptr).release();
299
+ }
300
+ return none().release();
301
+ }
302
+
303
+ template <typename T>
304
+ using cast_op_type = void *&;
305
+ explicit operator void *&() { return value; }
306
+ static constexpr auto name = const_name("capsule");
307
+
308
+ private:
309
+ void *value = nullptr;
310
+ };
311
+
312
+ template <>
313
+ class type_caster<std::nullptr_t> : public void_caster<std::nullptr_t> {};
314
+
315
+ template <>
316
+ class type_caster<bool> {
317
+ public:
318
+ bool load(handle src, bool convert) {
319
+ if (!src) {
320
+ return false;
321
+ }
322
+ if (src.ptr() == Py_True) {
323
+ value = true;
324
+ return true;
325
+ }
326
+ if (src.ptr() == Py_False) {
327
+ value = false;
328
+ return true;
329
+ }
330
+ if (convert || is_numpy_bool(src)) {
331
+ // (allow non-implicit conversion for numpy booleans), use strncmp
332
+ // since NumPy 1.x had an additional trailing underscore.
333
+
334
+ Py_ssize_t res = -1;
335
+ if (src.is_none()) {
336
+ res = 0; // None is implicitly converted to False
337
+ }
338
+ #if defined(PYPY_VERSION)
339
+ // On PyPy, check that "__bool__" attr exists
340
+ else if (hasattr(src, PYBIND11_BOOL_ATTR)) {
341
+ res = PyObject_IsTrue(src.ptr());
342
+ }
343
+ #else
344
+ // Alternate approach for CPython: this does the same as the above, but optimized
345
+ // using the CPython API so as to avoid an unneeded attribute lookup.
346
+ else if (auto *tp_as_number = src.ptr()->ob_type->tp_as_number) {
347
+ if (PYBIND11_NB_BOOL(tp_as_number)) {
348
+ res = (*PYBIND11_NB_BOOL(tp_as_number))(src.ptr());
349
+ }
350
+ }
351
+ #endif
352
+ if (res == 0 || res == 1) {
353
+ value = (res != 0);
354
+ return true;
355
+ }
356
+ PyErr_Clear();
357
+ }
358
+ return false;
359
+ }
360
+ static handle cast(bool src, return_value_policy /* policy */, handle /* parent */) {
361
+ return handle(src ? Py_True : Py_False).inc_ref();
362
+ }
363
+ PYBIND11_TYPE_CASTER(bool, const_name("bool"));
364
+
365
+ private:
366
+ // Test if an object is a NumPy boolean (without fetching the type).
367
+ static inline bool is_numpy_bool(handle object) {
368
+ const char *type_name = Py_TYPE(object.ptr())->tp_name;
369
+ // Name changed to `numpy.bool` in NumPy 2, `numpy.bool_` is needed for 1.x support
370
+ return std::strcmp("numpy.bool", type_name) == 0
371
+ || std::strcmp("numpy.bool_", type_name) == 0;
372
+ }
373
+ };
374
+
375
+ // Helper class for UTF-{8,16,32} C++ stl strings:
376
+ template <typename StringType, bool IsView = false>
377
+ struct string_caster {
378
+ using CharT = typename StringType::value_type;
379
+
380
+ // Simplify life by being able to assume standard char sizes (the standard only guarantees
381
+ // minimums, but Python requires exact sizes)
382
+ static_assert(!std::is_same<CharT, char>::value || sizeof(CharT) == 1,
383
+ "Unsupported char size != 1");
384
+ #if defined(PYBIND11_HAS_U8STRING)
385
+ static_assert(!std::is_same<CharT, char8_t>::value || sizeof(CharT) == 1,
386
+ "Unsupported char8_t size != 1");
387
+ #endif
388
+ static_assert(!std::is_same<CharT, char16_t>::value || sizeof(CharT) == 2,
389
+ "Unsupported char16_t size != 2");
390
+ static_assert(!std::is_same<CharT, char32_t>::value || sizeof(CharT) == 4,
391
+ "Unsupported char32_t size != 4");
392
+ // wchar_t can be either 16 bits (Windows) or 32 (everywhere else)
393
+ static_assert(!std::is_same<CharT, wchar_t>::value || sizeof(CharT) == 2 || sizeof(CharT) == 4,
394
+ "Unsupported wchar_t size != 2/4");
395
+ static constexpr size_t UTF_N = 8 * sizeof(CharT);
396
+
397
+ bool load(handle src, bool) {
398
+ handle load_src = src;
399
+ if (!src) {
400
+ return false;
401
+ }
402
+ if (!PyUnicode_Check(load_src.ptr())) {
403
+ return load_raw(load_src);
404
+ }
405
+
406
+ // For UTF-8 we avoid the need for a temporary `bytes` object by using
407
+ // `PyUnicode_AsUTF8AndSize`.
408
+ if (UTF_N == 8) {
409
+ Py_ssize_t size = -1;
410
+ const auto *buffer
411
+ = reinterpret_cast<const CharT *>(PyUnicode_AsUTF8AndSize(load_src.ptr(), &size));
412
+ if (!buffer) {
413
+ PyErr_Clear();
414
+ return false;
415
+ }
416
+ value = StringType(buffer, static_cast<size_t>(size));
417
+ return true;
418
+ }
419
+
420
+ auto utfNbytes
421
+ = reinterpret_steal<object>(PyUnicode_AsEncodedString(load_src.ptr(),
422
+ UTF_N == 8 ? "utf-8"
423
+ : UTF_N == 16 ? "utf-16"
424
+ : "utf-32",
425
+ nullptr));
426
+ if (!utfNbytes) {
427
+ PyErr_Clear();
428
+ return false;
429
+ }
430
+
431
+ const auto *buffer
432
+ = reinterpret_cast<const CharT *>(PYBIND11_BYTES_AS_STRING(utfNbytes.ptr()));
433
+ size_t length = (size_t) PYBIND11_BYTES_SIZE(utfNbytes.ptr()) / sizeof(CharT);
434
+ // Skip BOM for UTF-16/32
435
+ if (UTF_N > 8) {
436
+ buffer++;
437
+ length--;
438
+ }
439
+ value = StringType(buffer, length);
440
+
441
+ // If we're loading a string_view we need to keep the encoded Python object alive:
442
+ if (IsView) {
443
+ loader_life_support::add_patient(utfNbytes);
444
+ }
445
+
446
+ return true;
447
+ }
448
+
449
+ static handle
450
+ cast(const StringType &src, return_value_policy /* policy */, handle /* parent */) {
451
+ const char *buffer = reinterpret_cast<const char *>(src.data());
452
+ auto nbytes = ssize_t(src.size() * sizeof(CharT));
453
+ handle s = decode_utfN(buffer, nbytes);
454
+ if (!s) {
455
+ throw error_already_set();
456
+ }
457
+ return s;
458
+ }
459
+
460
+ PYBIND11_TYPE_CASTER(StringType, const_name(PYBIND11_STRING_NAME));
461
+
462
+ private:
463
+ static handle decode_utfN(const char *buffer, ssize_t nbytes) {
464
+ #if !defined(PYPY_VERSION)
465
+ return UTF_N == 8 ? PyUnicode_DecodeUTF8(buffer, nbytes, nullptr)
466
+ : UTF_N == 16 ? PyUnicode_DecodeUTF16(buffer, nbytes, nullptr, nullptr)
467
+ : PyUnicode_DecodeUTF32(buffer, nbytes, nullptr, nullptr);
468
+ #else
469
+ // PyPy segfaults when on PyUnicode_DecodeUTF16 (and possibly on PyUnicode_DecodeUTF32 as
470
+ // well), so bypass the whole thing by just passing the encoding as a string value, which
471
+ // works properly:
472
+ return PyUnicode_Decode(buffer,
473
+ nbytes,
474
+ UTF_N == 8 ? "utf-8"
475
+ : UTF_N == 16 ? "utf-16"
476
+ : "utf-32",
477
+ nullptr);
478
+ #endif
479
+ }
480
+
481
+ // When loading into a std::string or char*, accept a bytes/bytearray object as-is (i.e.
482
+ // without any encoding/decoding attempt). For other C++ char sizes this is a no-op.
483
+ // which supports loading a unicode from a str, doesn't take this path.
484
+ template <typename C = CharT>
485
+ bool load_raw(enable_if_t<std::is_same<C, char>::value, handle> src) {
486
+ if (PYBIND11_BYTES_CHECK(src.ptr())) {
487
+ // We were passed raw bytes; accept it into a std::string or char*
488
+ // without any encoding attempt.
489
+ const char *bytes = PYBIND11_BYTES_AS_STRING(src.ptr());
490
+ if (!bytes) {
491
+ pybind11_fail("Unexpected PYBIND11_BYTES_AS_STRING() failure.");
492
+ }
493
+ value = StringType(bytes, (size_t) PYBIND11_BYTES_SIZE(src.ptr()));
494
+ return true;
495
+ }
496
+ if (PyByteArray_Check(src.ptr())) {
497
+ // We were passed a bytearray; accept it into a std::string or char*
498
+ // without any encoding attempt.
499
+ const char *bytearray = PyByteArray_AsString(src.ptr());
500
+ if (!bytearray) {
501
+ pybind11_fail("Unexpected PyByteArray_AsString() failure.");
502
+ }
503
+ value = StringType(bytearray, (size_t) PyByteArray_Size(src.ptr()));
504
+ return true;
505
+ }
506
+
507
+ return false;
508
+ }
509
+
510
+ template <typename C = CharT>
511
+ bool load_raw(enable_if_t<!std::is_same<C, char>::value, handle>) {
512
+ return false;
513
+ }
514
+ };
515
+
516
+ template <typename CharT, class Traits, class Allocator>
517
+ struct type_caster<std::basic_string<CharT, Traits, Allocator>,
518
+ enable_if_t<is_std_char_type<CharT>::value>>
519
+ : string_caster<std::basic_string<CharT, Traits, Allocator>> {};
520
+
521
+ #ifdef PYBIND11_HAS_STRING_VIEW
522
+ template <typename CharT, class Traits>
523
+ struct type_caster<std::basic_string_view<CharT, Traits>,
524
+ enable_if_t<is_std_char_type<CharT>::value>>
525
+ : string_caster<std::basic_string_view<CharT, Traits>, true> {};
526
+ #endif
527
+
528
+ // Type caster for C-style strings. We basically use a std::string type caster, but also add the
529
+ // ability to use None as a nullptr char* (which the string caster doesn't allow).
530
+ template <typename CharT>
531
+ struct type_caster<CharT, enable_if_t<is_std_char_type<CharT>::value>> {
532
+ using StringType = std::basic_string<CharT>;
533
+ using StringCaster = make_caster<StringType>;
534
+ StringCaster str_caster;
535
+ bool none = false;
536
+ CharT one_char = 0;
537
+
538
+ public:
539
+ bool load(handle src, bool convert) {
540
+ if (!src) {
541
+ return false;
542
+ }
543
+ if (src.is_none()) {
544
+ // Defer accepting None to other overloads (if we aren't in convert mode):
545
+ if (!convert) {
546
+ return false;
547
+ }
548
+ none = true;
549
+ return true;
550
+ }
551
+ return str_caster.load(src, convert);
552
+ }
553
+
554
+ static handle cast(const CharT *src, return_value_policy policy, handle parent) {
555
+ if (src == nullptr) {
556
+ return pybind11::none().release();
557
+ }
558
+ return StringCaster::cast(StringType(src), policy, parent);
559
+ }
560
+
561
+ static handle cast(CharT src, return_value_policy policy, handle parent) {
562
+ if (std::is_same<char, CharT>::value) {
563
+ handle s = PyUnicode_DecodeLatin1((const char *) &src, 1, nullptr);
564
+ if (!s) {
565
+ throw error_already_set();
566
+ }
567
+ return s;
568
+ }
569
+ return StringCaster::cast(StringType(1, src), policy, parent);
570
+ }
571
+
572
+ explicit operator CharT *() {
573
+ return none ? nullptr : const_cast<CharT *>(static_cast<StringType &>(str_caster).c_str());
574
+ }
575
+ explicit operator CharT &() {
576
+ if (none) {
577
+ throw value_error("Cannot convert None to a character");
578
+ }
579
+
580
+ auto &value = static_cast<StringType &>(str_caster);
581
+ size_t str_len = value.size();
582
+ if (str_len == 0) {
583
+ throw value_error("Cannot convert empty string to a character");
584
+ }
585
+
586
+ // If we're in UTF-8 mode, we have two possible failures: one for a unicode character that
587
+ // is too high, and one for multiple unicode characters (caught later), so we need to
588
+ // figure out how long the first encoded character is in bytes to distinguish between these
589
+ // two errors. We also allow want to allow unicode characters U+0080 through U+00FF, as
590
+ // those can fit into a single char value.
591
+ if (StringCaster::UTF_N == 8 && str_len > 1 && str_len <= 4) {
592
+ auto v0 = static_cast<unsigned char>(value[0]);
593
+ // low bits only: 0-127
594
+ // 0b110xxxxx - start of 2-byte sequence
595
+ // 0b1110xxxx - start of 3-byte sequence
596
+ // 0b11110xxx - start of 4-byte sequence
597
+ size_t char0_bytes = (v0 & 0x80) == 0 ? 1
598
+ : (v0 & 0xE0) == 0xC0 ? 2
599
+ : (v0 & 0xF0) == 0xE0 ? 3
600
+ : 4;
601
+
602
+ if (char0_bytes == str_len) {
603
+ // If we have a 128-255 value, we can decode it into a single char:
604
+ if (char0_bytes == 2 && (v0 & 0xFC) == 0xC0) { // 0x110000xx 0x10xxxxxx
605
+ one_char = static_cast<CharT>(((v0 & 3) << 6)
606
+ + (static_cast<unsigned char>(value[1]) & 0x3F));
607
+ return one_char;
608
+ }
609
+ // Otherwise we have a single character, but it's > U+00FF
610
+ throw value_error("Character code point not in range(0x100)");
611
+ }
612
+ }
613
+
614
+ // UTF-16 is much easier: we can only have a surrogate pair for values above U+FFFF, thus a
615
+ // surrogate pair with total length 2 instantly indicates a range error (but not a "your
616
+ // string was too long" error).
617
+ else if (StringCaster::UTF_N == 16 && str_len == 2) {
618
+ one_char = static_cast<CharT>(value[0]);
619
+ if (one_char >= 0xD800 && one_char < 0xE000) {
620
+ throw value_error("Character code point not in range(0x10000)");
621
+ }
622
+ }
623
+
624
+ if (str_len != 1) {
625
+ throw value_error("Expected a character, but multi-character string found");
626
+ }
627
+
628
+ one_char = value[0];
629
+ return one_char;
630
+ }
631
+
632
+ static constexpr auto name = const_name(PYBIND11_STRING_NAME);
633
+ template <typename _T>
634
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
635
+ };
636
+
637
+ // Base implementation for std::tuple and std::pair
638
+ template <template <typename...> class Tuple, typename... Ts>
639
+ class tuple_caster {
640
+ using type = Tuple<Ts...>;
641
+ static constexpr auto size = sizeof...(Ts);
642
+ using indices = make_index_sequence<size>;
643
+
644
+ public:
645
+ bool load(handle src, bool convert) {
646
+ if (!isinstance<sequence>(src)) {
647
+ return false;
648
+ }
649
+ const auto seq = reinterpret_borrow<sequence>(src);
650
+ if (seq.size() != size) {
651
+ return false;
652
+ }
653
+ return load_impl(seq, convert, indices{});
654
+ }
655
+
656
+ template <typename T>
657
+ static handle cast(T &&src, return_value_policy policy, handle parent) {
658
+ return cast_impl(std::forward<T>(src), policy, parent, indices{});
659
+ }
660
+
661
+ // copied from the PYBIND11_TYPE_CASTER macro
662
+ template <typename T>
663
+ static handle cast(T *src, return_value_policy policy, handle parent) {
664
+ if (!src) {
665
+ return none().release();
666
+ }
667
+ if (policy == return_value_policy::take_ownership) {
668
+ auto h = cast(std::move(*src), policy, parent);
669
+ delete src;
670
+ return h;
671
+ }
672
+ return cast(*src, policy, parent);
673
+ }
674
+
675
+ static constexpr auto name = const_name("tuple[")
676
+ + ::pybind11::detail::concat(make_caster<Ts>::name...)
677
+ + const_name("]");
678
+
679
+ template <typename T>
680
+ using cast_op_type = type;
681
+
682
+ explicit operator type() & { return implicit_cast(indices{}); }
683
+ explicit operator type() && { return std::move(*this).implicit_cast(indices{}); }
684
+
685
+ protected:
686
+ template <size_t... Is>
687
+ type implicit_cast(index_sequence<Is...>) & {
688
+ return type(cast_op<Ts>(std::get<Is>(subcasters))...);
689
+ }
690
+ template <size_t... Is>
691
+ type implicit_cast(index_sequence<Is...>) && {
692
+ return type(cast_op<Ts>(std::move(std::get<Is>(subcasters)))...);
693
+ }
694
+
695
+ static constexpr bool load_impl(const sequence &, bool, index_sequence<>) { return true; }
696
+
697
+ template <size_t... Is>
698
+ bool load_impl(const sequence &seq, bool convert, index_sequence<Is...>) {
699
+ #ifdef __cpp_fold_expressions
700
+ if ((... || !std::get<Is>(subcasters).load(seq[Is], convert))) {
701
+ return false;
702
+ }
703
+ #else
704
+ for (bool r : {std::get<Is>(subcasters).load(seq[Is], convert)...}) {
705
+ if (!r) {
706
+ return false;
707
+ }
708
+ }
709
+ #endif
710
+ return true;
711
+ }
712
+
713
+ /* Implementation: Convert a C++ tuple into a Python tuple */
714
+ template <typename T, size_t... Is>
715
+ static handle
716
+ cast_impl(T &&src, return_value_policy policy, handle parent, index_sequence<Is...>) {
717
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(src, policy, parent);
718
+ PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(policy, parent);
719
+ std::array<object, size> entries{{reinterpret_steal<object>(
720
+ make_caster<Ts>::cast(std::get<Is>(std::forward<T>(src)), policy, parent))...}};
721
+ for (const auto &entry : entries) {
722
+ if (!entry) {
723
+ return handle();
724
+ }
725
+ }
726
+ tuple result(size);
727
+ int counter = 0;
728
+ for (auto &entry : entries) {
729
+ PyTuple_SET_ITEM(result.ptr(), counter++, entry.release().ptr());
730
+ }
731
+ return result.release();
732
+ }
733
+
734
+ Tuple<make_caster<Ts>...> subcasters;
735
+ };
736
+
737
+ template <typename T1, typename T2>
738
+ class type_caster<std::pair<T1, T2>> : public tuple_caster<std::pair, T1, T2> {};
739
+
740
+ template <typename... Ts>
741
+ class type_caster<std::tuple<Ts...>> : public tuple_caster<std::tuple, Ts...> {};
742
+
743
+ template <>
744
+ class type_caster<std::tuple<>> : public tuple_caster<std::tuple> {
745
+ public:
746
+ // PEP 484 specifies this syntax for an empty tuple
747
+ static constexpr auto name = const_name("tuple[()]");
748
+ };
749
+
750
+ /// Helper class which abstracts away certain actions. Users can provide specializations for
751
+ /// custom holders, but it's only necessary if the type has a non-standard interface.
752
+ template <typename T>
753
+ struct holder_helper {
754
+ static auto get(const T &p) -> decltype(p.get()) { return p.get(); }
755
+ };
756
+
757
+ /// Type caster for holder types like std::shared_ptr, etc.
758
+ /// The SFINAE hook is provided to help work around the current lack of support
759
+ /// for smart-pointer interoperability. Please consider it an implementation
760
+ /// detail that may change in the future, as formal support for smart-pointer
761
+ /// interoperability is added into pybind11.
762
+ template <typename type, typename holder_type, typename SFINAE = void>
763
+ struct copyable_holder_caster : public type_caster_base<type> {
764
+ public:
765
+ using base = type_caster_base<type>;
766
+ static_assert(std::is_base_of<base, type_caster<type>>::value,
767
+ "Holder classes are only supported for custom types");
768
+ using base::base;
769
+ using base::cast;
770
+ using base::typeinfo;
771
+ using base::value;
772
+
773
+ bool load(handle src, bool convert) {
774
+ return base::template load_impl<copyable_holder_caster<type, holder_type>>(src, convert);
775
+ }
776
+
777
+ explicit operator type *() { return this->value; }
778
+ // static_cast works around compiler error with MSVC 17 and CUDA 10.2
779
+ // see issue #2180
780
+ explicit operator type &() { return *(static_cast<type *>(this->value)); }
781
+ explicit operator holder_type *() { return std::addressof(holder); }
782
+ explicit operator holder_type &() { return holder; }
783
+
784
+ static handle cast(const holder_type &src, return_value_policy, handle) {
785
+ const auto *ptr = holder_helper<holder_type>::get(src);
786
+ return type_caster_base<type>::cast_holder(ptr, &src);
787
+ }
788
+
789
+ protected:
790
+ friend class type_caster_generic;
791
+ void check_holder_compat() {
792
+ if (typeinfo->default_holder) {
793
+ throw cast_error("Unable to load a custom holder type from a default-holder instance");
794
+ }
795
+ }
796
+
797
+ void load_value(value_and_holder &&v_h) {
798
+ if (v_h.holder_constructed()) {
799
+ value = v_h.value_ptr();
800
+ holder = v_h.template holder<holder_type>();
801
+ return;
802
+ }
803
+ throw cast_error("Unable to cast from non-held to held instance (T& to Holder<T>) "
804
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
805
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for "
806
+ "type information)");
807
+ #else
808
+ "of type '"
809
+ + type_id<holder_type>() + "''");
810
+ #endif
811
+ }
812
+
813
+ template <typename T = holder_type,
814
+ detail::enable_if_t<!std::is_constructible<T, const T &, type *>::value, int> = 0>
815
+ bool try_implicit_casts(handle, bool) {
816
+ return false;
817
+ }
818
+
819
+ template <typename T = holder_type,
820
+ detail::enable_if_t<std::is_constructible<T, const T &, type *>::value, int> = 0>
821
+ bool try_implicit_casts(handle src, bool convert) {
822
+ for (auto &cast : typeinfo->implicit_casts) {
823
+ copyable_holder_caster sub_caster(*cast.first);
824
+ if (sub_caster.load(src, convert)) {
825
+ value = cast.second(sub_caster.value);
826
+ holder = holder_type(sub_caster.holder, (type *) value);
827
+ return true;
828
+ }
829
+ }
830
+ return false;
831
+ }
832
+
833
+ static bool try_direct_conversions(handle) { return false; }
834
+
835
+ holder_type holder;
836
+ };
837
+
838
+ /// Specialize for the common std::shared_ptr, so users don't need to
839
+ template <typename T>
840
+ class type_caster<std::shared_ptr<T>> : public copyable_holder_caster<T, std::shared_ptr<T>> {};
841
+
842
+ /// Type caster for holder types like std::unique_ptr.
843
+ /// Please consider the SFINAE hook an implementation detail, as explained
844
+ /// in the comment for the copyable_holder_caster.
845
+ template <typename type, typename holder_type, typename SFINAE = void>
846
+ struct move_only_holder_caster {
847
+ static_assert(std::is_base_of<type_caster_base<type>, type_caster<type>>::value,
848
+ "Holder classes are only supported for custom types");
849
+
850
+ static handle cast(holder_type &&src, return_value_policy, handle) {
851
+ auto *ptr = holder_helper<holder_type>::get(src);
852
+ return type_caster_base<type>::cast_holder(ptr, std::addressof(src));
853
+ }
854
+ static constexpr auto name = type_caster_base<type>::name;
855
+ };
856
+
857
+ template <typename type, typename deleter>
858
+ class type_caster<std::unique_ptr<type, deleter>>
859
+ : public move_only_holder_caster<type, std::unique_ptr<type, deleter>> {};
860
+
861
+ template <typename type, typename holder_type>
862
+ using type_caster_holder = conditional_t<is_copy_constructible<holder_type>::value,
863
+ copyable_holder_caster<type, holder_type>,
864
+ move_only_holder_caster<type, holder_type>>;
865
+
866
+ template <typename T, bool Value = false>
867
+ struct always_construct_holder {
868
+ static constexpr bool value = Value;
869
+ };
870
+
871
+ /// Create a specialization for custom holder types (silently ignores std::shared_ptr)
872
+ #define PYBIND11_DECLARE_HOLDER_TYPE(type, holder_type, ...) \
873
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
874
+ namespace detail { \
875
+ template <typename type> \
876
+ struct always_construct_holder<holder_type> : always_construct_holder<void, ##__VA_ARGS__> { \
877
+ }; \
878
+ template <typename type> \
879
+ class type_caster<holder_type, enable_if_t<!is_shared_ptr<holder_type>::value>> \
880
+ : public type_caster_holder<type, holder_type> {}; \
881
+ } \
882
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
883
+
884
+ // PYBIND11_DECLARE_HOLDER_TYPE holder types:
885
+ template <typename base, typename holder>
886
+ struct is_holder_type
887
+ : std::is_base_of<detail::type_caster_holder<base, holder>, detail::type_caster<holder>> {};
888
+ // Specialization for always-supported unique_ptr holders:
889
+ template <typename base, typename deleter>
890
+ struct is_holder_type<base, std::unique_ptr<base, deleter>> : std::true_type {};
891
+
892
+ #ifdef PYBIND11_DISABLE_HANDLE_TYPE_NAME_DEFAULT_IMPLEMENTATION // See PR #4888
893
+
894
+ // This leads to compilation errors if a specialization is missing.
895
+ template <typename T>
896
+ struct handle_type_name;
897
+
898
+ #else
899
+
900
+ template <typename T>
901
+ struct handle_type_name {
902
+ static constexpr auto name = const_name<T>();
903
+ };
904
+
905
+ #endif
906
+
907
+ template <>
908
+ struct handle_type_name<object> {
909
+ static constexpr auto name = const_name("object");
910
+ };
911
+ template <>
912
+ struct handle_type_name<list> {
913
+ static constexpr auto name = const_name("list");
914
+ };
915
+ template <>
916
+ struct handle_type_name<dict> {
917
+ static constexpr auto name = const_name("dict");
918
+ };
919
+ template <>
920
+ struct handle_type_name<anyset> {
921
+ static constexpr auto name = const_name("Union[set, frozenset]");
922
+ };
923
+ template <>
924
+ struct handle_type_name<set> {
925
+ static constexpr auto name = const_name("set");
926
+ };
927
+ template <>
928
+ struct handle_type_name<frozenset> {
929
+ static constexpr auto name = const_name("frozenset");
930
+ };
931
+ template <>
932
+ struct handle_type_name<str> {
933
+ static constexpr auto name = const_name("str");
934
+ };
935
+ template <>
936
+ struct handle_type_name<tuple> {
937
+ static constexpr auto name = const_name("tuple");
938
+ };
939
+ template <>
940
+ struct handle_type_name<bool_> {
941
+ static constexpr auto name = const_name("bool");
942
+ };
943
+ template <>
944
+ struct handle_type_name<bytes> {
945
+ static constexpr auto name = const_name(PYBIND11_BYTES_NAME);
946
+ };
947
+ template <>
948
+ struct handle_type_name<buffer> {
949
+ static constexpr auto name = const_name("Buffer");
950
+ };
951
+ template <>
952
+ struct handle_type_name<int_> {
953
+ static constexpr auto name = const_name("int");
954
+ };
955
+ template <>
956
+ struct handle_type_name<iterable> {
957
+ static constexpr auto name = const_name("Iterable");
958
+ };
959
+ template <>
960
+ struct handle_type_name<iterator> {
961
+ static constexpr auto name = const_name("Iterator");
962
+ };
963
+ template <>
964
+ struct handle_type_name<float_> {
965
+ static constexpr auto name = const_name("float");
966
+ };
967
+ template <>
968
+ struct handle_type_name<function> {
969
+ static constexpr auto name = const_name("Callable");
970
+ };
971
+ template <>
972
+ struct handle_type_name<handle> {
973
+ static constexpr auto name = handle_type_name<object>::name;
974
+ };
975
+ template <>
976
+ struct handle_type_name<none> {
977
+ static constexpr auto name = const_name("None");
978
+ };
979
+ template <>
980
+ struct handle_type_name<sequence> {
981
+ static constexpr auto name = const_name("Sequence");
982
+ };
983
+ template <>
984
+ struct handle_type_name<bytearray> {
985
+ static constexpr auto name = const_name("bytearray");
986
+ };
987
+ template <>
988
+ struct handle_type_name<memoryview> {
989
+ static constexpr auto name = const_name("memoryview");
990
+ };
991
+ template <>
992
+ struct handle_type_name<slice> {
993
+ static constexpr auto name = const_name("slice");
994
+ };
995
+ template <>
996
+ struct handle_type_name<type> {
997
+ static constexpr auto name = const_name("type");
998
+ };
999
+ template <>
1000
+ struct handle_type_name<capsule> {
1001
+ static constexpr auto name = const_name("capsule");
1002
+ };
1003
+ template <>
1004
+ struct handle_type_name<ellipsis> {
1005
+ static constexpr auto name = const_name("ellipsis");
1006
+ };
1007
+ template <>
1008
+ struct handle_type_name<weakref> {
1009
+ static constexpr auto name = const_name("weakref");
1010
+ };
1011
+ template <>
1012
+ struct handle_type_name<args> {
1013
+ static constexpr auto name = const_name("*args");
1014
+ };
1015
+ template <>
1016
+ struct handle_type_name<kwargs> {
1017
+ static constexpr auto name = const_name("**kwargs");
1018
+ };
1019
+ template <>
1020
+ struct handle_type_name<obj_attr_accessor> {
1021
+ static constexpr auto name = const_name<obj_attr_accessor>();
1022
+ };
1023
+ template <>
1024
+ struct handle_type_name<str_attr_accessor> {
1025
+ static constexpr auto name = const_name<str_attr_accessor>();
1026
+ };
1027
+ template <>
1028
+ struct handle_type_name<item_accessor> {
1029
+ static constexpr auto name = const_name<item_accessor>();
1030
+ };
1031
+ template <>
1032
+ struct handle_type_name<sequence_accessor> {
1033
+ static constexpr auto name = const_name<sequence_accessor>();
1034
+ };
1035
+ template <>
1036
+ struct handle_type_name<list_accessor> {
1037
+ static constexpr auto name = const_name<list_accessor>();
1038
+ };
1039
+ template <>
1040
+ struct handle_type_name<tuple_accessor> {
1041
+ static constexpr auto name = const_name<tuple_accessor>();
1042
+ };
1043
+
1044
+ template <typename type>
1045
+ struct pyobject_caster {
1046
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1047
+ pyobject_caster() : value() {}
1048
+
1049
+ // `type` may not be default constructible (e.g. frozenset, anyset). Initializing `value`
1050
+ // to a nil handle is safe since it will only be accessed if `load` succeeds.
1051
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1052
+ pyobject_caster() : value(reinterpret_steal<type>(handle())) {}
1053
+
1054
+ template <typename T = type, enable_if_t<std::is_same<T, handle>::value, int> = 0>
1055
+ bool load(handle src, bool /* convert */) {
1056
+ value = src;
1057
+ return static_cast<bool>(value);
1058
+ }
1059
+
1060
+ template <typename T = type, enable_if_t<std::is_base_of<object, T>::value, int> = 0>
1061
+ bool load(handle src, bool /* convert */) {
1062
+ if (!isinstance<type>(src)) {
1063
+ return false;
1064
+ }
1065
+ value = reinterpret_borrow<type>(src);
1066
+ return true;
1067
+ }
1068
+
1069
+ static handle cast(const handle &src, return_value_policy /* policy */, handle /* parent */) {
1070
+ return src.inc_ref();
1071
+ }
1072
+ PYBIND11_TYPE_CASTER(type, handle_type_name<type>::name);
1073
+ };
1074
+
1075
+ template <typename T>
1076
+ class type_caster<T, enable_if_t<is_pyobject<T>::value>> : public pyobject_caster<T> {};
1077
+
1078
+ // Our conditions for enabling moving are quite restrictive:
1079
+ // At compile time:
1080
+ // - T needs to be a non-const, non-pointer, non-reference type
1081
+ // - type_caster<T>::operator T&() must exist
1082
+ // - the type must be move constructible (obviously)
1083
+ // At run-time:
1084
+ // - if the type is non-copy-constructible, the object must be the sole owner of the type (i.e. it
1085
+ // must have ref_count() == 1)h
1086
+ // If any of the above are not satisfied, we fall back to copying.
1087
+ template <typename T>
1088
+ using move_is_plain_type
1089
+ = satisfies_none_of<T, std::is_void, std::is_pointer, std::is_reference, std::is_const>;
1090
+ template <typename T, typename SFINAE = void>
1091
+ struct move_always : std::false_type {};
1092
+ template <typename T>
1093
+ struct move_always<
1094
+ T,
1095
+ enable_if_t<
1096
+ all_of<move_is_plain_type<T>,
1097
+ negation<is_copy_constructible<T>>,
1098
+ is_move_constructible<T>,
1099
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1100
+ : std::true_type {};
1101
+ template <typename T, typename SFINAE = void>
1102
+ struct move_if_unreferenced : std::false_type {};
1103
+ template <typename T>
1104
+ struct move_if_unreferenced<
1105
+ T,
1106
+ enable_if_t<
1107
+ all_of<move_is_plain_type<T>,
1108
+ negation<move_always<T>>,
1109
+ is_move_constructible<T>,
1110
+ std::is_same<decltype(std::declval<make_caster<T>>().operator T &()), T &>>::value>>
1111
+ : std::true_type {};
1112
+ template <typename T>
1113
+ using move_never = none_of<move_always<T>, move_if_unreferenced<T>>;
1114
+
1115
+ // Detect whether returning a `type` from a cast on type's type_caster is going to result in a
1116
+ // reference or pointer to a local variable of the type_caster. Basically, only
1117
+ // non-reference/pointer `type`s and reference/pointers from a type_caster_generic are safe;
1118
+ // everything else returns a reference/pointer to a local variable.
1119
+ template <typename type>
1120
+ using cast_is_temporary_value_reference
1121
+ = bool_constant<(std::is_reference<type>::value || std::is_pointer<type>::value)
1122
+ && !std::is_base_of<type_caster_generic, make_caster<type>>::value
1123
+ && !std::is_same<intrinsic_t<type>, void>::value>;
1124
+
1125
+ // When a value returned from a C++ function is being cast back to Python, we almost always want to
1126
+ // force `policy = move`, regardless of the return value policy the function/method was declared
1127
+ // with.
1128
+ template <typename Return, typename SFINAE = void>
1129
+ struct return_value_policy_override {
1130
+ static return_value_policy policy(return_value_policy p) { return p; }
1131
+ };
1132
+
1133
+ template <typename Return>
1134
+ struct return_value_policy_override<
1135
+ Return,
1136
+ detail::enable_if_t<std::is_base_of<type_caster_generic, make_caster<Return>>::value, void>> {
1137
+ static return_value_policy policy(return_value_policy p) {
1138
+ return !std::is_lvalue_reference<Return>::value && !std::is_pointer<Return>::value
1139
+ ? return_value_policy::move
1140
+ : p;
1141
+ }
1142
+ };
1143
+
1144
+ // Basic python -> C++ casting; throws if casting fails
1145
+ template <typename T, typename SFINAE>
1146
+ type_caster<T, SFINAE> &load_type(type_caster<T, SFINAE> &conv, const handle &handle) {
1147
+ static_assert(!detail::is_pyobject<T>::value,
1148
+ "Internal error: type_caster should only be used for C++ types");
1149
+ if (!conv.load(handle, true)) {
1150
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1151
+ throw cast_error(
1152
+ "Unable to cast Python instance of type "
1153
+ + str(type::handle_of(handle)).cast<std::string>()
1154
+ + " to C++ type '?' (#define "
1155
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1156
+ #else
1157
+ throw cast_error("Unable to cast Python instance of type "
1158
+ + str(type::handle_of(handle)).cast<std::string>() + " to C++ type '"
1159
+ + type_id<T>() + "'");
1160
+ #endif
1161
+ }
1162
+ return conv;
1163
+ }
1164
+ // Wrapper around the above that also constructs and returns a type_caster
1165
+ template <typename T>
1166
+ make_caster<T> load_type(const handle &handle) {
1167
+ make_caster<T> conv;
1168
+ load_type(conv, handle);
1169
+ return conv;
1170
+ }
1171
+
1172
+ PYBIND11_NAMESPACE_END(detail)
1173
+
1174
+ // pytype -> C++ type
1175
+ template <typename T,
1176
+ detail::enable_if_t<!detail::is_pyobject<T>::value
1177
+ && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1178
+ int>
1179
+ = 0>
1180
+ T cast(const handle &handle) {
1181
+ using namespace detail;
1182
+ static_assert(!cast_is_temporary_value_reference<T>::value,
1183
+ "Unable to cast type to reference: value is local to type caster");
1184
+ return cast_op<T>(load_type<T>(handle));
1185
+ }
1186
+
1187
+ // pytype -> pytype (calls converting constructor)
1188
+ template <typename T, detail::enable_if_t<detail::is_pyobject<T>::value, int> = 0>
1189
+ T cast(const handle &handle) {
1190
+ return T(reinterpret_borrow<object>(handle));
1191
+ }
1192
+
1193
+ // Note that `cast<PyObject *>(obj)` increments the reference count of `obj`.
1194
+ // This is necessary for the case that `obj` is a temporary, and could
1195
+ // not possibly be different, given
1196
+ // 1. the established convention that the passed `handle` is borrowed, and
1197
+ // 2. we don't want to force all generic code using `cast<T>()` to special-case
1198
+ // handling of `T` = `PyObject *` (to increment the reference count there).
1199
+ // It is the responsibility of the caller to ensure that the reference count
1200
+ // is decremented.
1201
+ template <typename T,
1202
+ typename Handle,
1203
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1204
+ && detail::is_same_ignoring_cvref<Handle, handle>::value,
1205
+ int>
1206
+ = 0>
1207
+ T cast(Handle &&handle) {
1208
+ return handle.inc_ref().ptr();
1209
+ }
1210
+ // To optimize way an inc_ref/dec_ref cycle:
1211
+ template <typename T,
1212
+ typename Object,
1213
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value
1214
+ && detail::is_same_ignoring_cvref<Object, object>::value,
1215
+ int>
1216
+ = 0>
1217
+ T cast(Object &&obj) {
1218
+ return obj.release().ptr();
1219
+ }
1220
+
1221
+ // C++ type -> py::object
1222
+ template <typename T, detail::enable_if_t<!detail::is_pyobject<T>::value, int> = 0>
1223
+ object cast(T &&value,
1224
+ return_value_policy policy = return_value_policy::automatic_reference,
1225
+ handle parent = handle()) {
1226
+ using no_ref_T = typename std::remove_reference<T>::type;
1227
+ if (policy == return_value_policy::automatic) {
1228
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::take_ownership
1229
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1230
+ : return_value_policy::move;
1231
+ } else if (policy == return_value_policy::automatic_reference) {
1232
+ policy = std::is_pointer<no_ref_T>::value ? return_value_policy::reference
1233
+ : std::is_lvalue_reference<T>::value ? return_value_policy::copy
1234
+ : return_value_policy::move;
1235
+ }
1236
+ return reinterpret_steal<object>(
1237
+ detail::make_caster<T>::cast(std::forward<T>(value), policy, parent));
1238
+ }
1239
+
1240
+ template <typename T>
1241
+ T handle::cast() const {
1242
+ return pybind11::cast<T>(*this);
1243
+ }
1244
+ template <>
1245
+ inline void handle::cast() const {
1246
+ return;
1247
+ }
1248
+
1249
+ template <typename T>
1250
+ detail::enable_if_t<!detail::move_never<T>::value, T> move(object &&obj) {
1251
+ if (obj.ref_count() > 1) {
1252
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1253
+ throw cast_error(
1254
+ "Unable to cast Python " + str(type::handle_of(obj)).cast<std::string>()
1255
+ + " instance to C++ rvalue: instance has multiple references"
1256
+ " (#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1257
+ #else
1258
+ throw cast_error("Unable to move from Python "
1259
+ + str(type::handle_of(obj)).cast<std::string>() + " instance to C++ "
1260
+ + type_id<T>() + " instance: instance has multiple references");
1261
+ #endif
1262
+ }
1263
+
1264
+ // Move into a temporary and return that, because the reference may be a local value of `conv`
1265
+ T ret = std::move(detail::load_type<T>(obj).operator T &());
1266
+ return ret;
1267
+ }
1268
+
1269
+ // Calling cast() on an rvalue calls pybind11::cast with the object rvalue, which does:
1270
+ // - If we have to move (because T has no copy constructor), do it. This will fail if the moved
1271
+ // object has multiple references, but trying to copy will fail to compile.
1272
+ // - If both movable and copyable, check ref count: if 1, move; otherwise copy
1273
+ // - Otherwise (not movable), copy.
1274
+ template <typename T>
1275
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_always<T>::value, T>
1276
+ cast(object &&object) {
1277
+ return move<T>(std::move(object));
1278
+ }
1279
+ template <typename T>
1280
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_if_unreferenced<T>::value, T>
1281
+ cast(object &&object) {
1282
+ if (object.ref_count() > 1) {
1283
+ return cast<T>(object);
1284
+ }
1285
+ return move<T>(std::move(object));
1286
+ }
1287
+ template <typename T>
1288
+ detail::enable_if_t<!detail::is_pyobject<T>::value && detail::move_never<T>::value, T>
1289
+ cast(object &&object) {
1290
+ return cast<T>(object);
1291
+ }
1292
+
1293
+ // pytype rvalue -> pytype (calls converting constructor)
1294
+ template <typename T>
1295
+ detail::enable_if_t<detail::is_pyobject<T>::value, T> cast(object &&object) {
1296
+ return T(std::move(object));
1297
+ }
1298
+
1299
+ template <typename T>
1300
+ T object::cast() const & {
1301
+ return pybind11::cast<T>(*this);
1302
+ }
1303
+ template <typename T>
1304
+ T object::cast() && {
1305
+ return pybind11::cast<T>(std::move(*this));
1306
+ }
1307
+ template <>
1308
+ inline void object::cast() const & {
1309
+ return;
1310
+ }
1311
+ template <>
1312
+ inline void object::cast() && {
1313
+ return;
1314
+ }
1315
+
1316
+ PYBIND11_NAMESPACE_BEGIN(detail)
1317
+
1318
+ // Declared in pytypes.h:
1319
+ template <typename T, enable_if_t<!is_pyobject<T>::value, int>>
1320
+ object object_or_cast(T &&o) {
1321
+ return pybind11::cast(std::forward<T>(o));
1322
+ }
1323
+
1324
+ // Placeholder type for the unneeded (and dead code) static variable in the
1325
+ // PYBIND11_OVERRIDE_OVERRIDE macro
1326
+ struct override_unused {};
1327
+ template <typename ret_type>
1328
+ using override_caster_t = conditional_t<cast_is_temporary_value_reference<ret_type>::value,
1329
+ make_caster<ret_type>,
1330
+ override_unused>;
1331
+
1332
+ // Trampoline use: for reference/pointer types to value-converted values, we do a value cast, then
1333
+ // store the result in the given variable. For other types, this is a no-op.
1334
+ template <typename T>
1335
+ enable_if_t<cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&o,
1336
+ make_caster<T> &caster) {
1337
+ return cast_op<T>(load_type(caster, o));
1338
+ }
1339
+ template <typename T>
1340
+ enable_if_t<!cast_is_temporary_value_reference<T>::value, T> cast_ref(object &&,
1341
+ override_unused &) {
1342
+ pybind11_fail("Internal error: cast_ref fallback invoked");
1343
+ }
1344
+
1345
+ // Trampoline use: Having a pybind11::cast with an invalid reference type is going to
1346
+ // static_assert, even though if it's in dead code, so we provide a "trampoline" to pybind11::cast
1347
+ // that only does anything in cases where pybind11::cast is valid.
1348
+ template <typename T>
1349
+ enable_if_t<cast_is_temporary_value_reference<T>::value
1350
+ && !detail::is_same_ignoring_cvref<T, PyObject *>::value,
1351
+ T>
1352
+ cast_safe(object &&) {
1353
+ pybind11_fail("Internal error: cast_safe fallback invoked");
1354
+ }
1355
+ template <typename T>
1356
+ enable_if_t<std::is_void<T>::value, void> cast_safe(object &&) {}
1357
+ template <typename T>
1358
+ enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value, PyObject *>
1359
+ cast_safe(object &&o) {
1360
+ return o.release().ptr();
1361
+ }
1362
+ template <typename T>
1363
+ enable_if_t<detail::none_of<cast_is_temporary_value_reference<T>,
1364
+ detail::is_same_ignoring_cvref<T, PyObject *>,
1365
+ std::is_void<T>>::value,
1366
+ T>
1367
+ cast_safe(object &&o) {
1368
+ return pybind11::cast<T>(std::move(o));
1369
+ }
1370
+
1371
+ PYBIND11_NAMESPACE_END(detail)
1372
+
1373
+ // The overloads could coexist, i.e. the #if is not strictly speaking needed,
1374
+ // but it is an easy minor optimization.
1375
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1376
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name) {
1377
+ return cast_error("Unable to convert call argument '" + name
1378
+ + "' to Python object (#define "
1379
+ "PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1380
+ }
1381
+ #else
1382
+ inline cast_error cast_error_unable_to_convert_call_arg(const std::string &name,
1383
+ const std::string &type) {
1384
+ return cast_error("Unable to convert call argument '" + name + "' of type '" + type
1385
+ + "' to Python object");
1386
+ }
1387
+ #endif
1388
+
1389
+ template <return_value_policy policy = return_value_policy::automatic_reference>
1390
+ tuple make_tuple() {
1391
+ return tuple(0);
1392
+ }
1393
+
1394
+ template <return_value_policy policy = return_value_policy::automatic_reference, typename... Args>
1395
+ tuple make_tuple(Args &&...args_) {
1396
+ constexpr size_t size = sizeof...(Args);
1397
+ std::array<object, size> args{{reinterpret_steal<object>(
1398
+ detail::make_caster<Args>::cast(std::forward<Args>(args_), policy, nullptr))...}};
1399
+ for (size_t i = 0; i < args.size(); i++) {
1400
+ if (!args[i]) {
1401
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1402
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i));
1403
+ #else
1404
+ std::array<std::string, size> argtypes{{type_id<Args>()...}};
1405
+ throw cast_error_unable_to_convert_call_arg(std::to_string(i), argtypes[i]);
1406
+ #endif
1407
+ }
1408
+ }
1409
+ tuple result(size);
1410
+ int counter = 0;
1411
+ for (auto &arg_value : args) {
1412
+ PyTuple_SET_ITEM(result.ptr(), counter++, arg_value.release().ptr());
1413
+ }
1414
+ return result;
1415
+ }
1416
+
1417
+ /// \ingroup annotations
1418
+ /// Annotation for arguments
1419
+ struct arg {
1420
+ /// Constructs an argument with the name of the argument; if null or omitted, this is a
1421
+ /// positional argument.
1422
+ constexpr explicit arg(const char *name = nullptr)
1423
+ : name(name), flag_noconvert(false), flag_none(true) {}
1424
+ /// Assign a value to this argument
1425
+ template <typename T>
1426
+ arg_v operator=(T &&value) const;
1427
+ /// Indicate that the type should not be converted in the type caster
1428
+ arg &noconvert(bool flag = true) {
1429
+ flag_noconvert = flag;
1430
+ return *this;
1431
+ }
1432
+ /// Indicates that the argument should/shouldn't allow None (e.g. for nullable pointer args)
1433
+ arg &none(bool flag = true) {
1434
+ flag_none = flag;
1435
+ return *this;
1436
+ }
1437
+
1438
+ const char *name; ///< If non-null, this is a named kwargs argument
1439
+ bool flag_noconvert : 1; ///< If set, do not allow conversion (requires a supporting type
1440
+ ///< caster!)
1441
+ bool flag_none : 1; ///< If set (the default), allow None to be passed to this argument
1442
+ };
1443
+
1444
+ /// \ingroup annotations
1445
+ /// Annotation for arguments with values
1446
+ struct arg_v : arg {
1447
+ private:
1448
+ template <typename T>
1449
+ arg_v(arg &&base, T &&x, const char *descr = nullptr)
1450
+ : arg(base), value(reinterpret_steal<object>(detail::make_caster<T>::cast(
1451
+ std::forward<T>(x), return_value_policy::automatic, {}))),
1452
+ descr(descr)
1453
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1454
+ ,
1455
+ type(type_id<T>())
1456
+ #endif
1457
+ {
1458
+ // Workaround! See:
1459
+ // https://github.com/pybind/pybind11/issues/2336
1460
+ // https://github.com/pybind/pybind11/pull/2685#issuecomment-731286700
1461
+ if (PyErr_Occurred()) {
1462
+ PyErr_Clear();
1463
+ }
1464
+ }
1465
+
1466
+ public:
1467
+ /// Direct construction with name, default, and description
1468
+ template <typename T>
1469
+ arg_v(const char *name, T &&x, const char *descr = nullptr)
1470
+ : arg_v(arg(name), std::forward<T>(x), descr) {}
1471
+
1472
+ /// Called internally when invoking `py::arg("a") = value`
1473
+ template <typename T>
1474
+ arg_v(const arg &base, T &&x, const char *descr = nullptr)
1475
+ : arg_v(arg(base), std::forward<T>(x), descr) {}
1476
+
1477
+ /// Same as `arg::noconvert()`, but returns *this as arg_v&, not arg&
1478
+ arg_v &noconvert(bool flag = true) {
1479
+ arg::noconvert(flag);
1480
+ return *this;
1481
+ }
1482
+
1483
+ /// Same as `arg::nonone()`, but returns *this as arg_v&, not arg&
1484
+ arg_v &none(bool flag = true) {
1485
+ arg::none(flag);
1486
+ return *this;
1487
+ }
1488
+
1489
+ /// The default value
1490
+ object value;
1491
+ /// The (optional) description of the default value
1492
+ const char *descr;
1493
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1494
+ /// The C++ type name of the default value (only available when compiled in debug mode)
1495
+ std::string type;
1496
+ #endif
1497
+ };
1498
+
1499
+ /// \ingroup annotations
1500
+ /// Annotation indicating that all following arguments are keyword-only; the is the equivalent of
1501
+ /// an unnamed '*' argument
1502
+ struct kw_only {};
1503
+
1504
+ /// \ingroup annotations
1505
+ /// Annotation indicating that all previous arguments are positional-only; the is the equivalent of
1506
+ /// an unnamed '/' argument (in Python 3.8)
1507
+ struct pos_only {};
1508
+
1509
+ template <typename T>
1510
+ arg_v arg::operator=(T &&value) const {
1511
+ return {*this, std::forward<T>(value)};
1512
+ }
1513
+
1514
+ /// Alias for backward compatibility -- to be removed in version 2.0
1515
+ template <typename /*unused*/>
1516
+ using arg_t = arg_v;
1517
+
1518
+ inline namespace literals {
1519
+ /** \rst
1520
+ String literal version of `arg`
1521
+ \endrst */
1522
+ constexpr arg
1523
+ #if !defined(__clang__) && defined(__GNUC__) && __GNUC__ < 5
1524
+ operator"" _a // gcc 4.8.5 insists on having a space (hard error).
1525
+ #else
1526
+ operator""_a // clang 17 generates a deprecation warning if there is a space.
1527
+ #endif
1528
+ (const char *name, size_t) {
1529
+ return arg(name);
1530
+ }
1531
+ } // namespace literals
1532
+
1533
+ PYBIND11_NAMESPACE_BEGIN(detail)
1534
+
1535
+ template <typename T>
1536
+ using is_kw_only = std::is_same<intrinsic_t<T>, kw_only>;
1537
+ template <typename T>
1538
+ using is_pos_only = std::is_same<intrinsic_t<T>, pos_only>;
1539
+
1540
+ // forward declaration (definition in attr.h)
1541
+ struct function_record;
1542
+
1543
+ /// Internal data associated with a single function call
1544
+ struct function_call {
1545
+ function_call(const function_record &f, handle p); // Implementation in attr.h
1546
+
1547
+ /// The function data:
1548
+ const function_record &func;
1549
+
1550
+ /// Arguments passed to the function:
1551
+ std::vector<handle> args;
1552
+
1553
+ /// The `convert` value the arguments should be loaded with
1554
+ std::vector<bool> args_convert;
1555
+
1556
+ /// Extra references for the optional `py::args` and/or `py::kwargs` arguments (which, if
1557
+ /// present, are also in `args` but without a reference).
1558
+ object args_ref, kwargs_ref;
1559
+
1560
+ /// The parent, if any
1561
+ handle parent;
1562
+
1563
+ /// If this is a call to an initializer, this argument contains `self`
1564
+ handle init_self;
1565
+ };
1566
+
1567
+ /// Helper class which loads arguments for C++ functions called from Python
1568
+ template <typename... Args>
1569
+ class argument_loader {
1570
+ using indices = make_index_sequence<sizeof...(Args)>;
1571
+
1572
+ template <typename Arg>
1573
+ using argument_is_args = std::is_same<intrinsic_t<Arg>, args>;
1574
+ template <typename Arg>
1575
+ using argument_is_kwargs = std::is_same<intrinsic_t<Arg>, kwargs>;
1576
+ // Get kwargs argument position, or -1 if not present:
1577
+ static constexpr auto kwargs_pos = constexpr_last<argument_is_kwargs, Args...>();
1578
+
1579
+ static_assert(kwargs_pos == -1 || kwargs_pos == (int) sizeof...(Args) - 1,
1580
+ "py::kwargs is only permitted as the last argument of a function");
1581
+
1582
+ public:
1583
+ static constexpr bool has_kwargs = kwargs_pos != -1;
1584
+
1585
+ // py::args argument position; -1 if not present.
1586
+ static constexpr int args_pos = constexpr_last<argument_is_args, Args...>();
1587
+
1588
+ static_assert(args_pos == -1 || args_pos == constexpr_first<argument_is_args, Args...>(),
1589
+ "py::args cannot be specified more than once");
1590
+
1591
+ static constexpr auto arg_names
1592
+ = ::pybind11::detail::concat(type_descr(make_caster<Args>::name)...);
1593
+
1594
+ bool load_args(function_call &call) { return load_impl_sequence(call, indices{}); }
1595
+
1596
+ template <typename Return, typename Guard, typename Func>
1597
+ // NOLINTNEXTLINE(readability-const-return-type)
1598
+ enable_if_t<!std::is_void<Return>::value, Return> call(Func &&f) && {
1599
+ return std::move(*this).template call_impl<remove_cv_t<Return>>(
1600
+ std::forward<Func>(f), indices{}, Guard{});
1601
+ }
1602
+
1603
+ template <typename Return, typename Guard, typename Func>
1604
+ enable_if_t<std::is_void<Return>::value, void_type> call(Func &&f) && {
1605
+ std::move(*this).template call_impl<remove_cv_t<Return>>(
1606
+ std::forward<Func>(f), indices{}, Guard{});
1607
+ return void_type();
1608
+ }
1609
+
1610
+ private:
1611
+ static bool load_impl_sequence(function_call &, index_sequence<>) { return true; }
1612
+
1613
+ template <size_t... Is>
1614
+ bool load_impl_sequence(function_call &call, index_sequence<Is...>) {
1615
+ #ifdef __cpp_fold_expressions
1616
+ if ((... || !std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is]))) {
1617
+ return false;
1618
+ }
1619
+ #else
1620
+ for (bool r : {std::get<Is>(argcasters).load(call.args[Is], call.args_convert[Is])...}) {
1621
+ if (!r) {
1622
+ return false;
1623
+ }
1624
+ }
1625
+ #endif
1626
+ return true;
1627
+ }
1628
+
1629
+ template <typename Return, typename Func, size_t... Is, typename Guard>
1630
+ Return call_impl(Func &&f, index_sequence<Is...>, Guard &&) && {
1631
+ return std::forward<Func>(f)(cast_op<Args>(std::move(std::get<Is>(argcasters)))...);
1632
+ }
1633
+
1634
+ std::tuple<make_caster<Args>...> argcasters;
1635
+ };
1636
+
1637
+ /// Helper class which collects only positional arguments for a Python function call.
1638
+ /// A fancier version below can collect any argument, but this one is optimal for simple calls.
1639
+ template <return_value_policy policy>
1640
+ class simple_collector {
1641
+ public:
1642
+ template <typename... Ts>
1643
+ explicit simple_collector(Ts &&...values)
1644
+ : m_args(pybind11::make_tuple<policy>(std::forward<Ts>(values)...)) {}
1645
+
1646
+ const tuple &args() const & { return m_args; }
1647
+ dict kwargs() const { return {}; }
1648
+
1649
+ tuple args() && { return std::move(m_args); }
1650
+
1651
+ /// Call a Python function and pass the collected arguments
1652
+ object call(PyObject *ptr) const {
1653
+ PyObject *result = PyObject_CallObject(ptr, m_args.ptr());
1654
+ if (!result) {
1655
+ throw error_already_set();
1656
+ }
1657
+ return reinterpret_steal<object>(result);
1658
+ }
1659
+
1660
+ private:
1661
+ tuple m_args;
1662
+ };
1663
+
1664
+ /// Helper class which collects positional, keyword, * and ** arguments for a Python function call
1665
+ template <return_value_policy policy>
1666
+ class unpacking_collector {
1667
+ public:
1668
+ template <typename... Ts>
1669
+ explicit unpacking_collector(Ts &&...values) {
1670
+ // Tuples aren't (easily) resizable so a list is needed for collection,
1671
+ // but the actual function call strictly requires a tuple.
1672
+ auto args_list = list();
1673
+ using expander = int[];
1674
+ (void) expander{0, (process(args_list, std::forward<Ts>(values)), 0)...};
1675
+
1676
+ m_args = std::move(args_list);
1677
+ }
1678
+
1679
+ const tuple &args() const & { return m_args; }
1680
+ const dict &kwargs() const & { return m_kwargs; }
1681
+
1682
+ tuple args() && { return std::move(m_args); }
1683
+ dict kwargs() && { return std::move(m_kwargs); }
1684
+
1685
+ /// Call a Python function and pass the collected arguments
1686
+ object call(PyObject *ptr) const {
1687
+ PyObject *result = PyObject_Call(ptr, m_args.ptr(), m_kwargs.ptr());
1688
+ if (!result) {
1689
+ throw error_already_set();
1690
+ }
1691
+ return reinterpret_steal<object>(result);
1692
+ }
1693
+
1694
+ private:
1695
+ template <typename T>
1696
+ void process(list &args_list, T &&x) {
1697
+ auto o = reinterpret_steal<object>(
1698
+ detail::make_caster<T>::cast(std::forward<T>(x), policy, {}));
1699
+ if (!o) {
1700
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1701
+ throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()));
1702
+ #else
1703
+ throw cast_error_unable_to_convert_call_arg(std::to_string(args_list.size()),
1704
+ type_id<T>());
1705
+ #endif
1706
+ }
1707
+ args_list.append(std::move(o));
1708
+ }
1709
+
1710
+ void process(list &args_list, detail::args_proxy ap) {
1711
+ for (auto a : ap) {
1712
+ args_list.append(a);
1713
+ }
1714
+ }
1715
+
1716
+ void process(list & /*args_list*/, arg_v a) {
1717
+ if (!a.name) {
1718
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1719
+ nameless_argument_error();
1720
+ #else
1721
+ nameless_argument_error(a.type);
1722
+ #endif
1723
+ }
1724
+ if (m_kwargs.contains(a.name)) {
1725
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1726
+ multiple_values_error();
1727
+ #else
1728
+ multiple_values_error(a.name);
1729
+ #endif
1730
+ }
1731
+ if (!a.value) {
1732
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1733
+ throw cast_error_unable_to_convert_call_arg(a.name);
1734
+ #else
1735
+ throw cast_error_unable_to_convert_call_arg(a.name, a.type);
1736
+ #endif
1737
+ }
1738
+ m_kwargs[a.name] = std::move(a.value);
1739
+ }
1740
+
1741
+ void process(list & /*args_list*/, detail::kwargs_proxy kp) {
1742
+ if (!kp) {
1743
+ return;
1744
+ }
1745
+ for (auto k : reinterpret_borrow<dict>(kp)) {
1746
+ if (m_kwargs.contains(k.first)) {
1747
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES)
1748
+ multiple_values_error();
1749
+ #else
1750
+ multiple_values_error(str(k.first));
1751
+ #endif
1752
+ }
1753
+ m_kwargs[k.first] = k.second;
1754
+ }
1755
+ }
1756
+
1757
+ [[noreturn]] static void nameless_argument_error() {
1758
+ throw type_error(
1759
+ "Got kwargs without a name; only named arguments "
1760
+ "may be passed via py::arg() to a python function call. "
1761
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1762
+ }
1763
+ [[noreturn]] static void nameless_argument_error(const std::string &type) {
1764
+ throw type_error("Got kwargs without a name of type '" + type
1765
+ + "'; only named "
1766
+ "arguments may be passed via py::arg() to a python function call. ");
1767
+ }
1768
+ [[noreturn]] static void multiple_values_error() {
1769
+ throw type_error(
1770
+ "Got multiple values for keyword argument "
1771
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for details)");
1772
+ }
1773
+
1774
+ [[noreturn]] static void multiple_values_error(const std::string &name) {
1775
+ throw type_error("Got multiple values for keyword argument '" + name + "'");
1776
+ }
1777
+
1778
+ private:
1779
+ tuple m_args;
1780
+ dict m_kwargs;
1781
+ };
1782
+
1783
+ // [workaround(intel)] Separate function required here
1784
+ // We need to put this into a separate function because the Intel compiler
1785
+ // fails to compile enable_if_t<!all_of<is_positional<Args>...>::value>
1786
+ // (tested with ICC 2021.1 Beta 20200827).
1787
+ template <typename... Args>
1788
+ constexpr bool args_are_all_positional() {
1789
+ return all_of<is_positional<Args>...>::value;
1790
+ }
1791
+
1792
+ /// Collect only positional arguments for a Python function call
1793
+ template <return_value_policy policy,
1794
+ typename... Args,
1795
+ typename = enable_if_t<args_are_all_positional<Args...>()>>
1796
+ simple_collector<policy> collect_arguments(Args &&...args) {
1797
+ return simple_collector<policy>(std::forward<Args>(args)...);
1798
+ }
1799
+
1800
+ /// Collect all arguments, including keywords and unpacking (only instantiated when needed)
1801
+ template <return_value_policy policy,
1802
+ typename... Args,
1803
+ typename = enable_if_t<!args_are_all_positional<Args...>()>>
1804
+ unpacking_collector<policy> collect_arguments(Args &&...args) {
1805
+ // Following argument order rules for generalized unpacking according to PEP 448
1806
+ static_assert(constexpr_last<is_positional, Args...>()
1807
+ < constexpr_first<is_keyword_or_ds, Args...>()
1808
+ && constexpr_last<is_s_unpacking, Args...>()
1809
+ < constexpr_first<is_ds_unpacking, Args...>(),
1810
+ "Invalid function call: positional args must precede keywords and ** unpacking; "
1811
+ "* unpacking must precede ** unpacking");
1812
+ return unpacking_collector<policy>(std::forward<Args>(args)...);
1813
+ }
1814
+
1815
+ template <typename Derived>
1816
+ template <return_value_policy policy, typename... Args>
1817
+ object object_api<Derived>::operator()(Args &&...args) const {
1818
+ #ifndef NDEBUG
1819
+ if (!PyGILState_Check()) {
1820
+ pybind11_fail("pybind11::object_api<>::operator() PyGILState_Check() failure.");
1821
+ }
1822
+ #endif
1823
+ return detail::collect_arguments<policy>(std::forward<Args>(args)...).call(derived().ptr());
1824
+ }
1825
+
1826
+ template <typename Derived>
1827
+ template <return_value_policy policy, typename... Args>
1828
+ object object_api<Derived>::call(Args &&...args) const {
1829
+ return operator()<policy>(std::forward<Args>(args)...);
1830
+ }
1831
+
1832
+ PYBIND11_NAMESPACE_END(detail)
1833
+
1834
+ template <typename T>
1835
+ handle type::handle_of() {
1836
+ static_assert(std::is_base_of<detail::type_caster_generic, detail::make_caster<T>>::value,
1837
+ "py::type::of<T> only supports the case where T is a registered C++ types.");
1838
+
1839
+ return detail::get_type_handle(typeid(T), true);
1840
+ }
1841
+
1842
+ #define PYBIND11_MAKE_OPAQUE(...) \
1843
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE) \
1844
+ namespace detail { \
1845
+ template <> \
1846
+ class type_caster<__VA_ARGS__> : public type_caster_base<__VA_ARGS__> {}; \
1847
+ } \
1848
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
1849
+
1850
+ /// Lets you pass a type containing a `,` through a macro parameter without needing a separate
1851
+ /// typedef, e.g.:
1852
+ /// `PYBIND11_OVERRIDE(PYBIND11_TYPE(ReturnType<A, B>), PYBIND11_TYPE(Parent<C, D>), f, arg)`
1853
+ #define PYBIND11_TYPE(...) __VA_ARGS__
1854
+
1855
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/chrono.h ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/chrono.h: Transparent conversion between std::chrono and python's datetime
3
+
4
+ Copyright (c) 2016 Trent Houliston <trent@houliston.me> and
5
+ Wenzel Jakob <wenzel.jakob@epfl.ch>
6
+
7
+ All rights reserved. Use of this source code is governed by a
8
+ BSD-style license that can be found in the LICENSE file.
9
+ */
10
+
11
+ #pragma once
12
+
13
+ #include "pybind11.h"
14
+
15
+ #include <chrono>
16
+ #include <cmath>
17
+ #include <ctime>
18
+ #include <datetime.h>
19
+ #include <mutex>
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+ PYBIND11_NAMESPACE_BEGIN(detail)
23
+
24
+ template <typename type>
25
+ class duration_caster {
26
+ public:
27
+ using rep = typename type::rep;
28
+ using period = typename type::period;
29
+
30
+ // signed 25 bits required by the standard.
31
+ using days = std::chrono::duration<int_least32_t, std::ratio<86400>>;
32
+
33
+ bool load(handle src, bool) {
34
+ using namespace std::chrono;
35
+
36
+ // Lazy initialise the PyDateTime import
37
+ if (!PyDateTimeAPI) {
38
+ PyDateTime_IMPORT;
39
+ }
40
+
41
+ if (!src) {
42
+ return false;
43
+ }
44
+ // If invoked with datetime.delta object
45
+ if (PyDelta_Check(src.ptr())) {
46
+ value = type(duration_cast<duration<rep, period>>(
47
+ days(PyDateTime_DELTA_GET_DAYS(src.ptr()))
48
+ + seconds(PyDateTime_DELTA_GET_SECONDS(src.ptr()))
49
+ + microseconds(PyDateTime_DELTA_GET_MICROSECONDS(src.ptr()))));
50
+ return true;
51
+ }
52
+ // If invoked with a float we assume it is seconds and convert
53
+ if (PyFloat_Check(src.ptr())) {
54
+ value = type(duration_cast<duration<rep, period>>(
55
+ duration<double>(PyFloat_AsDouble(src.ptr()))));
56
+ return true;
57
+ }
58
+ return false;
59
+ }
60
+
61
+ // If this is a duration just return it back
62
+ static const std::chrono::duration<rep, period> &
63
+ get_duration(const std::chrono::duration<rep, period> &src) {
64
+ return src;
65
+ }
66
+
67
+ // If this is a time_point get the time_since_epoch
68
+ template <typename Clock>
69
+ static std::chrono::duration<rep, period>
70
+ get_duration(const std::chrono::time_point<Clock, std::chrono::duration<rep, period>> &src) {
71
+ return src.time_since_epoch();
72
+ }
73
+
74
+ static handle cast(const type &src, return_value_policy /* policy */, handle /* parent */) {
75
+ using namespace std::chrono;
76
+
77
+ // Use overloaded function to get our duration from our source
78
+ // Works out if it is a duration or time_point and get the duration
79
+ auto d = get_duration(src);
80
+
81
+ // Lazy initialise the PyDateTime import
82
+ if (!PyDateTimeAPI) {
83
+ PyDateTime_IMPORT;
84
+ }
85
+
86
+ // Declare these special duration types so the conversions happen with the correct
87
+ // primitive types (int)
88
+ using dd_t = duration<int, std::ratio<86400>>;
89
+ using ss_t = duration<int, std::ratio<1>>;
90
+ using us_t = duration<int, std::micro>;
91
+
92
+ auto dd = duration_cast<dd_t>(d);
93
+ auto subd = d - dd;
94
+ auto ss = duration_cast<ss_t>(subd);
95
+ auto us = duration_cast<us_t>(subd - ss);
96
+ return PyDelta_FromDSU(dd.count(), ss.count(), us.count());
97
+ }
98
+
99
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.timedelta"));
100
+ };
101
+
102
+ inline std::tm *localtime_thread_safe(const std::time_t *time, std::tm *buf) {
103
+ #if (defined(__STDC_LIB_EXT1__) && defined(__STDC_WANT_LIB_EXT1__)) || defined(_MSC_VER)
104
+ if (localtime_s(buf, time))
105
+ return nullptr;
106
+ return buf;
107
+ #else
108
+ static std::mutex mtx;
109
+ std::lock_guard<std::mutex> lock(mtx);
110
+ std::tm *tm_ptr = std::localtime(time);
111
+ if (tm_ptr != nullptr) {
112
+ *buf = *tm_ptr;
113
+ }
114
+ return tm_ptr;
115
+ #endif
116
+ }
117
+
118
+ // This is for casting times on the system clock into datetime.datetime instances
119
+ template <typename Duration>
120
+ class type_caster<std::chrono::time_point<std::chrono::system_clock, Duration>> {
121
+ public:
122
+ using type = std::chrono::time_point<std::chrono::system_clock, Duration>;
123
+ bool load(handle src, bool) {
124
+ using namespace std::chrono;
125
+
126
+ // Lazy initialise the PyDateTime import
127
+ if (!PyDateTimeAPI) {
128
+ PyDateTime_IMPORT;
129
+ }
130
+
131
+ if (!src) {
132
+ return false;
133
+ }
134
+
135
+ std::tm cal;
136
+ microseconds msecs;
137
+
138
+ if (PyDateTime_Check(src.ptr())) {
139
+ cal.tm_sec = PyDateTime_DATE_GET_SECOND(src.ptr());
140
+ cal.tm_min = PyDateTime_DATE_GET_MINUTE(src.ptr());
141
+ cal.tm_hour = PyDateTime_DATE_GET_HOUR(src.ptr());
142
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
143
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
144
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
145
+ cal.tm_isdst = -1;
146
+ msecs = microseconds(PyDateTime_DATE_GET_MICROSECOND(src.ptr()));
147
+ } else if (PyDate_Check(src.ptr())) {
148
+ cal.tm_sec = 0;
149
+ cal.tm_min = 0;
150
+ cal.tm_hour = 0;
151
+ cal.tm_mday = PyDateTime_GET_DAY(src.ptr());
152
+ cal.tm_mon = PyDateTime_GET_MONTH(src.ptr()) - 1;
153
+ cal.tm_year = PyDateTime_GET_YEAR(src.ptr()) - 1900;
154
+ cal.tm_isdst = -1;
155
+ msecs = microseconds(0);
156
+ } else if (PyTime_Check(src.ptr())) {
157
+ cal.tm_sec = PyDateTime_TIME_GET_SECOND(src.ptr());
158
+ cal.tm_min = PyDateTime_TIME_GET_MINUTE(src.ptr());
159
+ cal.tm_hour = PyDateTime_TIME_GET_HOUR(src.ptr());
160
+ cal.tm_mday = 1; // This date (day, month, year) = (1, 0, 70)
161
+ cal.tm_mon = 0; // represents 1-Jan-1970, which is the first
162
+ cal.tm_year = 70; // earliest available date for Python's datetime
163
+ cal.tm_isdst = -1;
164
+ msecs = microseconds(PyDateTime_TIME_GET_MICROSECOND(src.ptr()));
165
+ } else {
166
+ return false;
167
+ }
168
+
169
+ value = time_point_cast<Duration>(system_clock::from_time_t(std::mktime(&cal)) + msecs);
170
+ return true;
171
+ }
172
+
173
+ static handle cast(const std::chrono::time_point<std::chrono::system_clock, Duration> &src,
174
+ return_value_policy /* policy */,
175
+ handle /* parent */) {
176
+ using namespace std::chrono;
177
+
178
+ // Lazy initialise the PyDateTime import
179
+ if (!PyDateTimeAPI) {
180
+ PyDateTime_IMPORT;
181
+ }
182
+
183
+ // Get out microseconds, and make sure they are positive, to avoid bug in eastern
184
+ // hemisphere time zones (cfr. https://github.com/pybind/pybind11/issues/2417)
185
+ using us_t = duration<int, std::micro>;
186
+ auto us = duration_cast<us_t>(src.time_since_epoch() % seconds(1));
187
+ if (us.count() < 0) {
188
+ us += seconds(1);
189
+ }
190
+
191
+ // Subtract microseconds BEFORE `system_clock::to_time_t`, because:
192
+ // > If std::time_t has lower precision, it is implementation-defined whether the value is
193
+ // rounded or truncated. (https://en.cppreference.com/w/cpp/chrono/system_clock/to_time_t)
194
+ std::time_t tt
195
+ = system_clock::to_time_t(time_point_cast<system_clock::duration>(src - us));
196
+
197
+ std::tm localtime;
198
+ std::tm *localtime_ptr = localtime_thread_safe(&tt, &localtime);
199
+ if (!localtime_ptr) {
200
+ throw cast_error("Unable to represent system_clock in local time");
201
+ }
202
+ return PyDateTime_FromDateAndTime(localtime.tm_year + 1900,
203
+ localtime.tm_mon + 1,
204
+ localtime.tm_mday,
205
+ localtime.tm_hour,
206
+ localtime.tm_min,
207
+ localtime.tm_sec,
208
+ us.count());
209
+ }
210
+ PYBIND11_TYPE_CASTER(type, const_name("datetime.datetime"));
211
+ };
212
+
213
+ // Other clocks that are not the system clock are not measured as datetime.datetime objects
214
+ // since they are not measured on calendar time. So instead we just make them timedeltas
215
+ // Or if they have passed us a time as a float we convert that
216
+ template <typename Clock, typename Duration>
217
+ class type_caster<std::chrono::time_point<Clock, Duration>>
218
+ : public duration_caster<std::chrono::time_point<Clock, Duration>> {};
219
+
220
+ template <typename Rep, typename Period>
221
+ class type_caster<std::chrono::duration<Rep, Period>>
222
+ : public duration_caster<std::chrono::duration<Rep, Period>> {};
223
+
224
+ PYBIND11_NAMESPACE_END(detail)
225
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/common.h ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ #include "detail/common.h"
2
+ #warning "Including 'common.h' is deprecated. It will be removed in v3.0. Use 'pybind11.h'."
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/complex.h ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/complex.h: Complex number support
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "pybind11.h"
13
+
14
+ #include <complex>
15
+
16
+ /// glibc defines I as a macro which breaks things, e.g., boost template names
17
+ #ifdef I
18
+ # undef I
19
+ #endif
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+
23
+ template <typename T>
24
+ struct format_descriptor<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
25
+ static constexpr const char c = format_descriptor<T>::c;
26
+ static constexpr const char value[3] = {'Z', c, '\0'};
27
+ static std::string format() { return std::string(value); }
28
+ };
29
+
30
+ #ifndef PYBIND11_CPP17
31
+
32
+ template <typename T>
33
+ constexpr const char
34
+ format_descriptor<std::complex<T>,
35
+ detail::enable_if_t<std::is_floating_point<T>::value>>::value[3];
36
+
37
+ #endif
38
+
39
+ PYBIND11_NAMESPACE_BEGIN(detail)
40
+
41
+ template <typename T>
42
+ struct is_fmt_numeric<std::complex<T>, detail::enable_if_t<std::is_floating_point<T>::value>> {
43
+ static constexpr bool value = true;
44
+ static constexpr int index = is_fmt_numeric<T>::index + 3;
45
+ };
46
+
47
+ template <typename T>
48
+ class type_caster<std::complex<T>> {
49
+ public:
50
+ bool load(handle src, bool convert) {
51
+ if (!src) {
52
+ return false;
53
+ }
54
+ if (!convert && !PyComplex_Check(src.ptr())) {
55
+ return false;
56
+ }
57
+ Py_complex result = PyComplex_AsCComplex(src.ptr());
58
+ if (result.real == -1.0 && PyErr_Occurred()) {
59
+ PyErr_Clear();
60
+ return false;
61
+ }
62
+ value = std::complex<T>((T) result.real, (T) result.imag);
63
+ return true;
64
+ }
65
+
66
+ static handle
67
+ cast(const std::complex<T> &src, return_value_policy /* policy */, handle /* parent */) {
68
+ return PyComplex_FromDoubles((double) src.real(), (double) src.imag());
69
+ }
70
+
71
+ PYBIND11_TYPE_CASTER(std::complex<T>, const_name("complex"));
72
+ };
73
+ PYBIND11_NAMESPACE_END(detail)
74
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/class.h ADDED
@@ -0,0 +1,767 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/class.h: Python C API implementation details for py::class_
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <pybind11/attr.h>
13
+ #include <pybind11/options.h>
14
+
15
+ #include "exception_translation.h"
16
+
17
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
18
+ PYBIND11_NAMESPACE_BEGIN(detail)
19
+
20
+ #if !defined(PYPY_VERSION)
21
+ # define PYBIND11_BUILTIN_QUALNAME
22
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj)
23
+ #else
24
+ // In PyPy, we still set __qualname__ so that we can produce reliable function type
25
+ // signatures; in CPython this macro expands to nothing:
26
+ # define PYBIND11_SET_OLDPY_QUALNAME(obj, nameobj) \
27
+ setattr((PyObject *) obj, "__qualname__", nameobj)
28
+ #endif
29
+
30
+ inline std::string get_fully_qualified_tp_name(PyTypeObject *type) {
31
+ #if !defined(PYPY_VERSION)
32
+ return type->tp_name;
33
+ #else
34
+ auto module_name = handle((PyObject *) type).attr("__module__").cast<std::string>();
35
+ if (module_name == PYBIND11_BUILTINS_MODULE)
36
+ return type->tp_name;
37
+ else
38
+ return std::move(module_name) + "." + type->tp_name;
39
+ #endif
40
+ }
41
+
42
+ inline PyTypeObject *type_incref(PyTypeObject *type) {
43
+ Py_INCREF(type);
44
+ return type;
45
+ }
46
+
47
+ #if !defined(PYPY_VERSION)
48
+
49
+ /// `pybind11_static_property.__get__()`: Always pass the class instead of the instance.
50
+ extern "C" inline PyObject *pybind11_static_get(PyObject *self, PyObject * /*ob*/, PyObject *cls) {
51
+ return PyProperty_Type.tp_descr_get(self, cls, cls);
52
+ }
53
+
54
+ /// `pybind11_static_property.__set__()`: Just like the above `__get__()`.
55
+ extern "C" inline int pybind11_static_set(PyObject *self, PyObject *obj, PyObject *value) {
56
+ PyObject *cls = PyType_Check(obj) ? obj : (PyObject *) Py_TYPE(obj);
57
+ return PyProperty_Type.tp_descr_set(self, cls, value);
58
+ }
59
+
60
+ // Forward declaration to use in `make_static_property_type()`
61
+ inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type);
62
+
63
+ /** A `static_property` is the same as a `property` but the `__get__()` and `__set__()`
64
+ methods are modified to always use the object type instead of a concrete instance.
65
+ Return value: New reference. */
66
+ inline PyTypeObject *make_static_property_type() {
67
+ constexpr auto *name = "pybind11_static_property";
68
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
69
+
70
+ /* Danger zone: from now (and until PyType_Ready), make sure to
71
+ issue no Python C API calls which could potentially invoke the
72
+ garbage collector (the GC will call type_traverse(), which will in
73
+ turn find the newly constructed type in an invalid state) */
74
+ auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
75
+ if (!heap_type) {
76
+ pybind11_fail("make_static_property_type(): error allocating type!");
77
+ }
78
+
79
+ heap_type->ht_name = name_obj.inc_ref().ptr();
80
+ # ifdef PYBIND11_BUILTIN_QUALNAME
81
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
82
+ # endif
83
+
84
+ auto *type = &heap_type->ht_type;
85
+ type->tp_name = name;
86
+ type->tp_base = type_incref(&PyProperty_Type);
87
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
88
+ type->tp_descr_get = pybind11_static_get;
89
+ type->tp_descr_set = pybind11_static_set;
90
+
91
+ # if PY_VERSION_HEX >= 0x030C0000
92
+ // Since Python-3.12 property-derived types are required to
93
+ // have dynamic attributes (to set `__doc__`)
94
+ enable_dynamic_attributes(heap_type);
95
+ # endif
96
+
97
+ if (PyType_Ready(type) < 0) {
98
+ pybind11_fail("make_static_property_type(): failure in PyType_Ready()!");
99
+ }
100
+
101
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
102
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
103
+
104
+ return type;
105
+ }
106
+
107
+ #else // PYPY
108
+
109
+ /** PyPy has some issues with the above C API, so we evaluate Python code instead.
110
+ This function will only be called once so performance isn't really a concern.
111
+ Return value: New reference. */
112
+ inline PyTypeObject *make_static_property_type() {
113
+ auto d = dict();
114
+ PyObject *result = PyRun_String(R"(\
115
+ class pybind11_static_property(property):
116
+ def __get__(self, obj, cls):
117
+ return property.__get__(self, cls, cls)
118
+
119
+ def __set__(self, obj, value):
120
+ cls = obj if isinstance(obj, type) else type(obj)
121
+ property.__set__(self, cls, value)
122
+ )",
123
+ Py_file_input,
124
+ d.ptr(),
125
+ d.ptr());
126
+ if (result == nullptr)
127
+ throw error_already_set();
128
+ Py_DECREF(result);
129
+ return (PyTypeObject *) d["pybind11_static_property"].cast<object>().release().ptr();
130
+ }
131
+
132
+ #endif // PYPY
133
+
134
+ /** Types with static properties need to handle `Type.static_prop = x` in a specific way.
135
+ By default, Python replaces the `static_property` itself, but for wrapped C++ types
136
+ we need to call `static_property.__set__()` in order to propagate the new value to
137
+ the underlying C++ data structure. */
138
+ extern "C" inline int pybind11_meta_setattro(PyObject *obj, PyObject *name, PyObject *value) {
139
+ // Use `_PyType_Lookup()` instead of `PyObject_GetAttr()` in order to get the raw
140
+ // descriptor (`property`) instead of calling `tp_descr_get` (`property.__get__()`).
141
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
142
+
143
+ // The following assignment combinations are possible:
144
+ // 1. `Type.static_prop = value` --> descr_set: `Type.static_prop.__set__(value)`
145
+ // 2. `Type.static_prop = other_static_prop` --> setattro: replace existing `static_prop`
146
+ // 3. `Type.regular_attribute = value` --> setattro: regular attribute assignment
147
+ auto *const static_prop = (PyObject *) get_internals().static_property_type;
148
+ const auto call_descr_set = (descr != nullptr) && (value != nullptr)
149
+ && (PyObject_IsInstance(descr, static_prop) != 0)
150
+ && (PyObject_IsInstance(value, static_prop) == 0);
151
+ if (call_descr_set) {
152
+ // Call `static_property.__set__()` instead of replacing the `static_property`.
153
+ #if !defined(PYPY_VERSION)
154
+ return Py_TYPE(descr)->tp_descr_set(descr, obj, value);
155
+ #else
156
+ if (PyObject *result = PyObject_CallMethod(descr, "__set__", "OO", obj, value)) {
157
+ Py_DECREF(result);
158
+ return 0;
159
+ } else {
160
+ return -1;
161
+ }
162
+ #endif
163
+ } else {
164
+ // Replace existing attribute.
165
+ return PyType_Type.tp_setattro(obj, name, value);
166
+ }
167
+ }
168
+
169
+ /**
170
+ * Python 3's PyInstanceMethod_Type hides itself via its tp_descr_get, which prevents aliasing
171
+ * methods via cls.attr("m2") = cls.attr("m1"): instead the tp_descr_get returns a plain function,
172
+ * when called on a class, or a PyMethod, when called on an instance. Override that behaviour here
173
+ * to do a special case bypass for PyInstanceMethod_Types.
174
+ */
175
+ extern "C" inline PyObject *pybind11_meta_getattro(PyObject *obj, PyObject *name) {
176
+ PyObject *descr = _PyType_Lookup((PyTypeObject *) obj, name);
177
+ if (descr && PyInstanceMethod_Check(descr)) {
178
+ Py_INCREF(descr);
179
+ return descr;
180
+ }
181
+ return PyType_Type.tp_getattro(obj, name);
182
+ }
183
+
184
+ /// metaclass `__call__` function that is used to create all pybind11 objects.
185
+ extern "C" inline PyObject *pybind11_meta_call(PyObject *type, PyObject *args, PyObject *kwargs) {
186
+
187
+ // use the default metaclass call to create/initialize the object
188
+ PyObject *self = PyType_Type.tp_call(type, args, kwargs);
189
+ if (self == nullptr) {
190
+ return nullptr;
191
+ }
192
+
193
+ // Ensure that the base __init__ function(s) were called
194
+ values_and_holders vhs(self);
195
+ for (const auto &vh : vhs) {
196
+ if (!vh.holder_constructed() && !vhs.is_redundant_value_and_holder(vh)) {
197
+ PyErr_Format(PyExc_TypeError,
198
+ "%.200s.__init__() must be called when overriding __init__",
199
+ get_fully_qualified_tp_name(vh.type->type).c_str());
200
+ Py_DECREF(self);
201
+ return nullptr;
202
+ }
203
+ }
204
+
205
+ return self;
206
+ }
207
+
208
+ /// Cleanup the type-info for a pybind11-registered type.
209
+ extern "C" inline void pybind11_meta_dealloc(PyObject *obj) {
210
+ with_internals([obj](internals &internals) {
211
+ auto *type = (PyTypeObject *) obj;
212
+
213
+ // A pybind11-registered type will:
214
+ // 1) be found in internals.registered_types_py
215
+ // 2) have exactly one associated `detail::type_info`
216
+ auto found_type = internals.registered_types_py.find(type);
217
+ if (found_type != internals.registered_types_py.end() && found_type->second.size() == 1
218
+ && found_type->second[0]->type == type) {
219
+
220
+ auto *tinfo = found_type->second[0];
221
+ auto tindex = std::type_index(*tinfo->cpptype);
222
+ internals.direct_conversions.erase(tindex);
223
+
224
+ if (tinfo->module_local) {
225
+ get_local_internals().registered_types_cpp.erase(tindex);
226
+ } else {
227
+ internals.registered_types_cpp.erase(tindex);
228
+ }
229
+ internals.registered_types_py.erase(tinfo->type);
230
+
231
+ // Actually just `std::erase_if`, but that's only available in C++20
232
+ auto &cache = internals.inactive_override_cache;
233
+ for (auto it = cache.begin(), last = cache.end(); it != last;) {
234
+ if (it->first == (PyObject *) tinfo->type) {
235
+ it = cache.erase(it);
236
+ } else {
237
+ ++it;
238
+ }
239
+ }
240
+
241
+ delete tinfo;
242
+ }
243
+ });
244
+
245
+ PyType_Type.tp_dealloc(obj);
246
+ }
247
+
248
+ /** This metaclass is assigned by default to all pybind11 types and is required in order
249
+ for static properties to function correctly. Users may override this using `py::metaclass`.
250
+ Return value: New reference. */
251
+ inline PyTypeObject *make_default_metaclass() {
252
+ constexpr auto *name = "pybind11_type";
253
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
254
+
255
+ /* Danger zone: from now (and until PyType_Ready), make sure to
256
+ issue no Python C API calls which could potentially invoke the
257
+ garbage collector (the GC will call type_traverse(), which will in
258
+ turn find the newly constructed type in an invalid state) */
259
+ auto *heap_type = (PyHeapTypeObject *) PyType_Type.tp_alloc(&PyType_Type, 0);
260
+ if (!heap_type) {
261
+ pybind11_fail("make_default_metaclass(): error allocating metaclass!");
262
+ }
263
+
264
+ heap_type->ht_name = name_obj.inc_ref().ptr();
265
+ #ifdef PYBIND11_BUILTIN_QUALNAME
266
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
267
+ #endif
268
+
269
+ auto *type = &heap_type->ht_type;
270
+ type->tp_name = name;
271
+ type->tp_base = type_incref(&PyType_Type);
272
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
273
+
274
+ type->tp_call = pybind11_meta_call;
275
+
276
+ type->tp_setattro = pybind11_meta_setattro;
277
+ type->tp_getattro = pybind11_meta_getattro;
278
+
279
+ type->tp_dealloc = pybind11_meta_dealloc;
280
+
281
+ if (PyType_Ready(type) < 0) {
282
+ pybind11_fail("make_default_metaclass(): failure in PyType_Ready()!");
283
+ }
284
+
285
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
286
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
287
+
288
+ return type;
289
+ }
290
+
291
+ /// For multiple inheritance types we need to recursively register/deregister base pointers for any
292
+ /// base classes with pointers that are difference from the instance value pointer so that we can
293
+ /// correctly recognize an offset base class pointer. This calls a function with any offset base
294
+ /// ptrs.
295
+ inline void traverse_offset_bases(void *valueptr,
296
+ const detail::type_info *tinfo,
297
+ instance *self,
298
+ bool (*f)(void * /*parentptr*/, instance * /*self*/)) {
299
+ for (handle h : reinterpret_borrow<tuple>(tinfo->type->tp_bases)) {
300
+ if (auto *parent_tinfo = get_type_info((PyTypeObject *) h.ptr())) {
301
+ for (auto &c : parent_tinfo->implicit_casts) {
302
+ if (c.first == tinfo->cpptype) {
303
+ auto *parentptr = c.second(valueptr);
304
+ if (parentptr != valueptr) {
305
+ f(parentptr, self);
306
+ }
307
+ traverse_offset_bases(parentptr, parent_tinfo, self, f);
308
+ break;
309
+ }
310
+ }
311
+ }
312
+ }
313
+ }
314
+
315
+ inline bool register_instance_impl(void *ptr, instance *self) {
316
+ with_instance_map(ptr, [&](instance_map &instances) { instances.emplace(ptr, self); });
317
+ return true; // unused, but gives the same signature as the deregister func
318
+ }
319
+ inline bool deregister_instance_impl(void *ptr, instance *self) {
320
+ return with_instance_map(ptr, [&](instance_map &instances) {
321
+ auto range = instances.equal_range(ptr);
322
+ for (auto it = range.first; it != range.second; ++it) {
323
+ if (self == it->second) {
324
+ instances.erase(it);
325
+ return true;
326
+ }
327
+ }
328
+ return false;
329
+ });
330
+ }
331
+
332
+ inline void register_instance(instance *self, void *valptr, const type_info *tinfo) {
333
+ register_instance_impl(valptr, self);
334
+ if (!tinfo->simple_ancestors) {
335
+ traverse_offset_bases(valptr, tinfo, self, register_instance_impl);
336
+ }
337
+ }
338
+
339
+ inline bool deregister_instance(instance *self, void *valptr, const type_info *tinfo) {
340
+ bool ret = deregister_instance_impl(valptr, self);
341
+ if (!tinfo->simple_ancestors) {
342
+ traverse_offset_bases(valptr, tinfo, self, deregister_instance_impl);
343
+ }
344
+ return ret;
345
+ }
346
+
347
+ /// Instance creation function for all pybind11 types. It allocates the internal instance layout
348
+ /// for holding C++ objects and holders. Allocation is done lazily (the first time the instance is
349
+ /// cast to a reference or pointer), and initialization is done by an `__init__` function.
350
+ inline PyObject *make_new_instance(PyTypeObject *type) {
351
+ #if defined(PYPY_VERSION)
352
+ // PyPy gets tp_basicsize wrong (issue 2482) under multiple inheritance when the first
353
+ // inherited object is a plain Python type (i.e. not derived from an extension type). Fix it.
354
+ ssize_t instance_size = static_cast<ssize_t>(sizeof(instance));
355
+ if (type->tp_basicsize < instance_size) {
356
+ type->tp_basicsize = instance_size;
357
+ }
358
+ #endif
359
+ PyObject *self = type->tp_alloc(type, 0);
360
+ auto *inst = reinterpret_cast<instance *>(self);
361
+ // Allocate the value/holder internals:
362
+ inst->allocate_layout();
363
+
364
+ return self;
365
+ }
366
+
367
+ /// Instance creation function for all pybind11 types. It only allocates space for the
368
+ /// C++ object, but doesn't call the constructor -- an `__init__` function must do that.
369
+ extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *) {
370
+ return make_new_instance(type);
371
+ }
372
+
373
+ /// An `__init__` function constructs the C++ object. Users should provide at least one
374
+ /// of these using `py::init` or directly with `.def(__init__, ...)`. Otherwise, the
375
+ /// following default function will be used which simply throws an exception.
376
+ extern "C" inline int pybind11_object_init(PyObject *self, PyObject *, PyObject *) {
377
+ PyTypeObject *type = Py_TYPE(self);
378
+ std::string msg = get_fully_qualified_tp_name(type) + ": No constructor defined!";
379
+ set_error(PyExc_TypeError, msg.c_str());
380
+ return -1;
381
+ }
382
+
383
+ inline void add_patient(PyObject *nurse, PyObject *patient) {
384
+ auto *instance = reinterpret_cast<detail::instance *>(nurse);
385
+ instance->has_patients = true;
386
+ Py_INCREF(patient);
387
+
388
+ with_internals([&](internals &internals) { internals.patients[nurse].push_back(patient); });
389
+ }
390
+
391
+ inline void clear_patients(PyObject *self) {
392
+ auto *instance = reinterpret_cast<detail::instance *>(self);
393
+ std::vector<PyObject *> patients;
394
+
395
+ with_internals([&](internals &internals) {
396
+ auto pos = internals.patients.find(self);
397
+
398
+ if (pos == internals.patients.end()) {
399
+ pybind11_fail(
400
+ "FATAL: Internal consistency check failed: Invalid clear_patients() call.");
401
+ }
402
+
403
+ // Clearing the patients can cause more Python code to run, which
404
+ // can invalidate the iterator. Extract the vector of patients
405
+ // from the unordered_map first.
406
+ patients = std::move(pos->second);
407
+ internals.patients.erase(pos);
408
+ });
409
+
410
+ instance->has_patients = false;
411
+ for (PyObject *&patient : patients) {
412
+ Py_CLEAR(patient);
413
+ }
414
+ }
415
+
416
+ /// Clears all internal data from the instance and removes it from registered instances in
417
+ /// preparation for deallocation.
418
+ inline void clear_instance(PyObject *self) {
419
+ auto *instance = reinterpret_cast<detail::instance *>(self);
420
+
421
+ // Deallocate any values/holders, if present:
422
+ for (auto &v_h : values_and_holders(instance)) {
423
+ if (v_h) {
424
+
425
+ // We have to deregister before we call dealloc because, for virtual MI types, we still
426
+ // need to be able to get the parent pointers.
427
+ if (v_h.instance_registered()
428
+ && !deregister_instance(instance, v_h.value_ptr(), v_h.type)) {
429
+ pybind11_fail(
430
+ "pybind11_object_dealloc(): Tried to deallocate unregistered instance!");
431
+ }
432
+
433
+ if (instance->owned || v_h.holder_constructed()) {
434
+ v_h.type->dealloc(v_h);
435
+ }
436
+ }
437
+ }
438
+ // Deallocate the value/holder layout internals:
439
+ instance->deallocate_layout();
440
+
441
+ if (instance->weakrefs) {
442
+ PyObject_ClearWeakRefs(self);
443
+ }
444
+
445
+ PyObject **dict_ptr = _PyObject_GetDictPtr(self);
446
+ if (dict_ptr) {
447
+ Py_CLEAR(*dict_ptr);
448
+ }
449
+
450
+ if (instance->has_patients) {
451
+ clear_patients(self);
452
+ }
453
+ }
454
+
455
+ /// Instance destructor function for all pybind11 types. It calls `type_info.dealloc`
456
+ /// to destroy the C++ object itself, while the rest is Python bookkeeping.
457
+ extern "C" inline void pybind11_object_dealloc(PyObject *self) {
458
+ auto *type = Py_TYPE(self);
459
+
460
+ // If this is a GC tracked object, untrack it first
461
+ // Note that the track call is implicitly done by the
462
+ // default tp_alloc, which we never override.
463
+ if (PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC) != 0) {
464
+ PyObject_GC_UnTrack(self);
465
+ }
466
+
467
+ clear_instance(self);
468
+
469
+ type->tp_free(self);
470
+
471
+ #if PY_VERSION_HEX < 0x03080000
472
+ // `type->tp_dealloc != pybind11_object_dealloc` means that we're being called
473
+ // as part of a derived type's dealloc, in which case we're not allowed to decref
474
+ // the type here. For cross-module compatibility, we shouldn't compare directly
475
+ // with `pybind11_object_dealloc`, but with the common one stashed in internals.
476
+ auto pybind11_object_type = (PyTypeObject *) get_internals().instance_base;
477
+ if (type->tp_dealloc == pybind11_object_type->tp_dealloc)
478
+ Py_DECREF(type);
479
+ #else
480
+ // This was not needed before Python 3.8 (Python issue 35810)
481
+ // https://github.com/pybind/pybind11/issues/1946
482
+ Py_DECREF(type);
483
+ #endif
484
+ }
485
+
486
+ std::string error_string();
487
+
488
+ /** Create the type which can be used as a common base for all classes. This is
489
+ needed in order to satisfy Python's requirements for multiple inheritance.
490
+ Return value: New reference. */
491
+ inline PyObject *make_object_base_type(PyTypeObject *metaclass) {
492
+ constexpr auto *name = "pybind11_object";
493
+ auto name_obj = reinterpret_steal<object>(PYBIND11_FROM_STRING(name));
494
+
495
+ /* Danger zone: from now (and until PyType_Ready), make sure to
496
+ issue no Python C API calls which could potentially invoke the
497
+ garbage collector (the GC will call type_traverse(), which will in
498
+ turn find the newly constructed type in an invalid state) */
499
+ auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
500
+ if (!heap_type) {
501
+ pybind11_fail("make_object_base_type(): error allocating type!");
502
+ }
503
+
504
+ heap_type->ht_name = name_obj.inc_ref().ptr();
505
+ #ifdef PYBIND11_BUILTIN_QUALNAME
506
+ heap_type->ht_qualname = name_obj.inc_ref().ptr();
507
+ #endif
508
+
509
+ auto *type = &heap_type->ht_type;
510
+ type->tp_name = name;
511
+ type->tp_base = type_incref(&PyBaseObject_Type);
512
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
513
+ type->tp_flags = Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HEAPTYPE;
514
+
515
+ type->tp_new = pybind11_object_new;
516
+ type->tp_init = pybind11_object_init;
517
+ type->tp_dealloc = pybind11_object_dealloc;
518
+
519
+ /* Support weak references (needed for the keep_alive feature) */
520
+ type->tp_weaklistoffset = offsetof(instance, weakrefs);
521
+
522
+ if (PyType_Ready(type) < 0) {
523
+ pybind11_fail("PyType_Ready failed in make_object_base_type(): " + error_string());
524
+ }
525
+
526
+ setattr((PyObject *) type, "__module__", str("pybind11_builtins"));
527
+ PYBIND11_SET_OLDPY_QUALNAME(type, name_obj);
528
+
529
+ assert(!PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
530
+ return (PyObject *) heap_type;
531
+ }
532
+
533
+ /// dynamic_attr: Allow the garbage collector to traverse the internal instance `__dict__`.
534
+ extern "C" inline int pybind11_traverse(PyObject *self, visitproc visit, void *arg) {
535
+ #if PY_VERSION_HEX >= 0x030D0000
536
+ PyObject_VisitManagedDict(self, visit, arg);
537
+ #else
538
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
539
+ Py_VISIT(dict);
540
+ #endif
541
+ // https://docs.python.org/3/c-api/typeobj.html#c.PyTypeObject.tp_traverse
542
+ #if PY_VERSION_HEX >= 0x03090000
543
+ Py_VISIT(Py_TYPE(self));
544
+ #endif
545
+ return 0;
546
+ }
547
+
548
+ /// dynamic_attr: Allow the GC to clear the dictionary.
549
+ extern "C" inline int pybind11_clear(PyObject *self) {
550
+ #if PY_VERSION_HEX >= 0x030D0000
551
+ PyObject_ClearManagedDict(self);
552
+ #else
553
+ PyObject *&dict = *_PyObject_GetDictPtr(self);
554
+ Py_CLEAR(dict);
555
+ #endif
556
+ return 0;
557
+ }
558
+
559
+ /// Give instances of this type a `__dict__` and opt into garbage collection.
560
+ inline void enable_dynamic_attributes(PyHeapTypeObject *heap_type) {
561
+ auto *type = &heap_type->ht_type;
562
+ type->tp_flags |= Py_TPFLAGS_HAVE_GC;
563
+ #if PY_VERSION_HEX < 0x030B0000
564
+ type->tp_dictoffset = type->tp_basicsize; // place dict at the end
565
+ type->tp_basicsize += (ssize_t) sizeof(PyObject *); // and allocate enough space for it
566
+ #else
567
+ type->tp_flags |= Py_TPFLAGS_MANAGED_DICT;
568
+ #endif
569
+ type->tp_traverse = pybind11_traverse;
570
+ type->tp_clear = pybind11_clear;
571
+
572
+ static PyGetSetDef getset[]
573
+ = {{"__dict__", PyObject_GenericGetDict, PyObject_GenericSetDict, nullptr, nullptr},
574
+ {nullptr, nullptr, nullptr, nullptr, nullptr}};
575
+ type->tp_getset = getset;
576
+ }
577
+
578
+ /// buffer_protocol: Fill in the view as specified by flags.
579
+ extern "C" inline int pybind11_getbuffer(PyObject *obj, Py_buffer *view, int flags) {
580
+ // Look for a `get_buffer` implementation in this type's info or any bases (following MRO).
581
+ type_info *tinfo = nullptr;
582
+ for (auto type : reinterpret_borrow<tuple>(Py_TYPE(obj)->tp_mro)) {
583
+ tinfo = get_type_info((PyTypeObject *) type.ptr());
584
+ if (tinfo && tinfo->get_buffer) {
585
+ break;
586
+ }
587
+ }
588
+ if (view == nullptr || !tinfo || !tinfo->get_buffer) {
589
+ if (view) {
590
+ view->obj = nullptr;
591
+ }
592
+ set_error(PyExc_BufferError, "pybind11_getbuffer(): Internal error");
593
+ return -1;
594
+ }
595
+ std::memset(view, 0, sizeof(Py_buffer));
596
+ buffer_info *info = nullptr;
597
+ try {
598
+ info = tinfo->get_buffer(obj, tinfo->get_buffer_data);
599
+ } catch (...) {
600
+ try_translate_exceptions();
601
+ raise_from(PyExc_BufferError, "Error getting buffer");
602
+ return -1;
603
+ }
604
+ if (info == nullptr) {
605
+ pybind11_fail("FATAL UNEXPECTED SITUATION: tinfo->get_buffer() returned nullptr.");
606
+ }
607
+
608
+ if ((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE && info->readonly) {
609
+ delete info;
610
+ // view->obj = nullptr; // Was just memset to 0, so not necessary
611
+ set_error(PyExc_BufferError, "Writable buffer requested for readonly storage");
612
+ return -1;
613
+ }
614
+ view->obj = obj;
615
+ view->ndim = 1;
616
+ view->internal = info;
617
+ view->buf = info->ptr;
618
+ view->itemsize = info->itemsize;
619
+ view->len = view->itemsize;
620
+ for (auto s : info->shape) {
621
+ view->len *= s;
622
+ }
623
+ view->readonly = static_cast<int>(info->readonly);
624
+ if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT) {
625
+ view->format = const_cast<char *>(info->format.c_str());
626
+ }
627
+ if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES) {
628
+ view->ndim = (int) info->ndim;
629
+ view->strides = info->strides.data();
630
+ view->shape = info->shape.data();
631
+ }
632
+ Py_INCREF(view->obj);
633
+ return 0;
634
+ }
635
+
636
+ /// buffer_protocol: Release the resources of the buffer.
637
+ extern "C" inline void pybind11_releasebuffer(PyObject *, Py_buffer *view) {
638
+ delete (buffer_info *) view->internal;
639
+ }
640
+
641
+ /// Give this type a buffer interface.
642
+ inline void enable_buffer_protocol(PyHeapTypeObject *heap_type) {
643
+ heap_type->ht_type.tp_as_buffer = &heap_type->as_buffer;
644
+
645
+ heap_type->as_buffer.bf_getbuffer = pybind11_getbuffer;
646
+ heap_type->as_buffer.bf_releasebuffer = pybind11_releasebuffer;
647
+ }
648
+
649
+ /** Create a brand new Python type according to the `type_record` specification.
650
+ Return value: New reference. */
651
+ inline PyObject *make_new_python_type(const type_record &rec) {
652
+ auto name = reinterpret_steal<object>(PYBIND11_FROM_STRING(rec.name));
653
+
654
+ auto qualname = name;
655
+ if (rec.scope && !PyModule_Check(rec.scope.ptr()) && hasattr(rec.scope, "__qualname__")) {
656
+ qualname = reinterpret_steal<object>(
657
+ PyUnicode_FromFormat("%U.%U", rec.scope.attr("__qualname__").ptr(), name.ptr()));
658
+ }
659
+
660
+ object module_;
661
+ if (rec.scope) {
662
+ if (hasattr(rec.scope, "__module__")) {
663
+ module_ = rec.scope.attr("__module__");
664
+ } else if (hasattr(rec.scope, "__name__")) {
665
+ module_ = rec.scope.attr("__name__");
666
+ }
667
+ }
668
+
669
+ const auto *full_name = c_str(
670
+ #if !defined(PYPY_VERSION)
671
+ module_ ? str(module_).cast<std::string>() + "." + rec.name :
672
+ #endif
673
+ rec.name);
674
+
675
+ char *tp_doc = nullptr;
676
+ if (rec.doc && options::show_user_defined_docstrings()) {
677
+ /* Allocate memory for docstring (Python will free this later on) */
678
+ size_t size = std::strlen(rec.doc) + 1;
679
+ #if PY_VERSION_HEX >= 0x030D0000
680
+ tp_doc = (char *) PyMem_MALLOC(size);
681
+ #else
682
+ tp_doc = (char *) PyObject_MALLOC(size);
683
+ #endif
684
+ std::memcpy((void *) tp_doc, rec.doc, size);
685
+ }
686
+
687
+ auto &internals = get_internals();
688
+ auto bases = tuple(rec.bases);
689
+ auto *base = (bases.empty()) ? internals.instance_base : bases[0].ptr();
690
+
691
+ /* Danger zone: from now (and until PyType_Ready), make sure to
692
+ issue no Python C API calls which could potentially invoke the
693
+ garbage collector (the GC will call type_traverse(), which will in
694
+ turn find the newly constructed type in an invalid state) */
695
+ auto *metaclass
696
+ = rec.metaclass.ptr() ? (PyTypeObject *) rec.metaclass.ptr() : internals.default_metaclass;
697
+
698
+ auto *heap_type = (PyHeapTypeObject *) metaclass->tp_alloc(metaclass, 0);
699
+ if (!heap_type) {
700
+ pybind11_fail(std::string(rec.name) + ": Unable to create type object!");
701
+ }
702
+
703
+ heap_type->ht_name = name.release().ptr();
704
+ #ifdef PYBIND11_BUILTIN_QUALNAME
705
+ heap_type->ht_qualname = qualname.inc_ref().ptr();
706
+ #endif
707
+
708
+ auto *type = &heap_type->ht_type;
709
+ type->tp_name = full_name;
710
+ type->tp_doc = tp_doc;
711
+ type->tp_base = type_incref((PyTypeObject *) base);
712
+ type->tp_basicsize = static_cast<ssize_t>(sizeof(instance));
713
+ if (!bases.empty()) {
714
+ type->tp_bases = bases.release().ptr();
715
+ }
716
+
717
+ /* Don't inherit base __init__ */
718
+ type->tp_init = pybind11_object_init;
719
+
720
+ /* Supported protocols */
721
+ type->tp_as_number = &heap_type->as_number;
722
+ type->tp_as_sequence = &heap_type->as_sequence;
723
+ type->tp_as_mapping = &heap_type->as_mapping;
724
+ type->tp_as_async = &heap_type->as_async;
725
+
726
+ /* Flags */
727
+ type->tp_flags |= Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HEAPTYPE;
728
+ if (!rec.is_final) {
729
+ type->tp_flags |= Py_TPFLAGS_BASETYPE;
730
+ }
731
+
732
+ if (rec.dynamic_attr) {
733
+ enable_dynamic_attributes(heap_type);
734
+ }
735
+
736
+ if (rec.buffer_protocol) {
737
+ enable_buffer_protocol(heap_type);
738
+ }
739
+
740
+ if (rec.custom_type_setup_callback) {
741
+ rec.custom_type_setup_callback(heap_type);
742
+ }
743
+
744
+ if (PyType_Ready(type) < 0) {
745
+ pybind11_fail(std::string(rec.name) + ": PyType_Ready failed: " + error_string());
746
+ }
747
+
748
+ assert(!rec.dynamic_attr || PyType_HasFeature(type, Py_TPFLAGS_HAVE_GC));
749
+
750
+ /* Register type with the parent scope */
751
+ if (rec.scope) {
752
+ setattr(rec.scope, rec.name, (PyObject *) type);
753
+ } else {
754
+ Py_INCREF(type); // Keep it alive forever (reference leak)
755
+ }
756
+
757
+ if (module_) { // Needed by pydoc
758
+ setattr((PyObject *) type, "__module__", module_);
759
+ }
760
+
761
+ PYBIND11_SET_OLDPY_QUALNAME(type, qualname);
762
+
763
+ return (PyObject *) type;
764
+ }
765
+
766
+ PYBIND11_NAMESPACE_END(detail)
767
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/common.h ADDED
@@ -0,0 +1,1287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/common.h -- Basic macros
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #define PYBIND11_VERSION_MAJOR 2
13
+ #define PYBIND11_VERSION_MINOR 13
14
+ #define PYBIND11_VERSION_PATCH 6
15
+
16
+ // Similar to Python's convention: https://docs.python.org/3/c-api/apiabiversion.html
17
+ // Additional convention: 0xD = dev
18
+ #define PYBIND11_VERSION_HEX 0x020D0600
19
+
20
+ // Define some generic pybind11 helper macros for warning management.
21
+ //
22
+ // Note that compiler-specific push/pop pairs are baked into the
23
+ // PYBIND11_NAMESPACE_BEGIN/PYBIND11_NAMESPACE_END pair of macros. Therefore manual
24
+ // PYBIND11_WARNING_PUSH/PYBIND11_WARNING_POP are usually only needed in `#include` sections.
25
+ //
26
+ // If you find you need to suppress a warning, please try to make the suppression as local as
27
+ // possible using these macros. Please also be sure to push/pop with the pybind11 macros. Please
28
+ // only use compiler specifics if you need to check specific versions, e.g. Apple Clang vs. vanilla
29
+ // Clang.
30
+ #if defined(_MSC_VER)
31
+ # define PYBIND11_COMPILER_MSVC
32
+ # define PYBIND11_PRAGMA(...) __pragma(__VA_ARGS__)
33
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning(push))
34
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning(pop))
35
+ #elif defined(__INTEL_COMPILER)
36
+ # define PYBIND11_COMPILER_INTEL
37
+ # define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
38
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(warning push)
39
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(warning pop)
40
+ #elif defined(__clang__)
41
+ # define PYBIND11_COMPILER_CLANG
42
+ # define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
43
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(clang diagnostic push)
44
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(clang diagnostic push)
45
+ #elif defined(__GNUC__)
46
+ # define PYBIND11_COMPILER_GCC
47
+ # define PYBIND11_PRAGMA(...) _Pragma(#__VA_ARGS__)
48
+ # define PYBIND11_WARNING_PUSH PYBIND11_PRAGMA(GCC diagnostic push)
49
+ # define PYBIND11_WARNING_POP PYBIND11_PRAGMA(GCC diagnostic pop)
50
+ #endif
51
+
52
+ #ifdef PYBIND11_COMPILER_MSVC
53
+ # define PYBIND11_WARNING_DISABLE_MSVC(name) PYBIND11_PRAGMA(warning(disable : name))
54
+ #else
55
+ # define PYBIND11_WARNING_DISABLE_MSVC(name)
56
+ #endif
57
+
58
+ #ifdef PYBIND11_COMPILER_CLANG
59
+ # define PYBIND11_WARNING_DISABLE_CLANG(name) PYBIND11_PRAGMA(clang diagnostic ignored name)
60
+ #else
61
+ # define PYBIND11_WARNING_DISABLE_CLANG(name)
62
+ #endif
63
+
64
+ #ifdef PYBIND11_COMPILER_GCC
65
+ # define PYBIND11_WARNING_DISABLE_GCC(name) PYBIND11_PRAGMA(GCC diagnostic ignored name)
66
+ #else
67
+ # define PYBIND11_WARNING_DISABLE_GCC(name)
68
+ #endif
69
+
70
+ #ifdef PYBIND11_COMPILER_INTEL
71
+ # define PYBIND11_WARNING_DISABLE_INTEL(name) PYBIND11_PRAGMA(warning disable name)
72
+ #else
73
+ # define PYBIND11_WARNING_DISABLE_INTEL(name)
74
+ #endif
75
+
76
+ #define PYBIND11_NAMESPACE_BEGIN(name) \
77
+ namespace name { \
78
+ PYBIND11_WARNING_PUSH
79
+
80
+ #define PYBIND11_NAMESPACE_END(name) \
81
+ PYBIND11_WARNING_POP \
82
+ }
83
+
84
+ // Robust support for some features and loading modules compiled against different pybind versions
85
+ // requires forcing hidden visibility on pybind code, so we enforce this by setting the attribute
86
+ // on the main `pybind11` namespace.
87
+ #if !defined(PYBIND11_NAMESPACE)
88
+ # ifdef __GNUG__
89
+ # define PYBIND11_NAMESPACE pybind11 __attribute__((visibility("hidden")))
90
+ # else
91
+ # define PYBIND11_NAMESPACE pybind11
92
+ # endif
93
+ #endif
94
+
95
+ #if !(defined(_MSC_VER) && __cplusplus == 199711L)
96
+ # if __cplusplus >= 201402L
97
+ # define PYBIND11_CPP14
98
+ # if __cplusplus >= 201703L
99
+ # define PYBIND11_CPP17
100
+ # if __cplusplus >= 202002L
101
+ # define PYBIND11_CPP20
102
+ // Please update tests/pybind11_tests.cpp `cpp_std()` when adding a macro here.
103
+ # endif
104
+ # endif
105
+ # endif
106
+ #elif defined(_MSC_VER) && __cplusplus == 199711L
107
+ // MSVC sets _MSVC_LANG rather than __cplusplus (supposedly until the standard is fully
108
+ // implemented). Unless you use the /Zc:__cplusplus flag on Visual Studio 2017 15.7 Preview 3
109
+ // or newer.
110
+ # if _MSVC_LANG >= 201402L
111
+ # define PYBIND11_CPP14
112
+ # if _MSVC_LANG > 201402L
113
+ # define PYBIND11_CPP17
114
+ # if _MSVC_LANG >= 202002L
115
+ # define PYBIND11_CPP20
116
+ # endif
117
+ # endif
118
+ # endif
119
+ #endif
120
+
121
+ #if defined(PYBIND11_CPP20)
122
+ # define PYBIND11_CONSTINIT constinit
123
+ # define PYBIND11_DTOR_CONSTEXPR constexpr
124
+ #else
125
+ # define PYBIND11_CONSTINIT
126
+ # define PYBIND11_DTOR_CONSTEXPR
127
+ #endif
128
+
129
+ // Compiler version assertions
130
+ #if defined(__INTEL_COMPILER)
131
+ # if __INTEL_COMPILER < 1800
132
+ # error pybind11 requires Intel C++ compiler v18 or newer
133
+ # elif __INTEL_COMPILER < 1900 && defined(PYBIND11_CPP14)
134
+ # error pybind11 supports only C++11 with Intel C++ compiler v18. Use v19 or newer for C++14.
135
+ # endif
136
+ /* The following pragma cannot be pop'ed:
137
+ https://community.intel.com/t5/Intel-C-Compiler/Inline-and-no-inline-warning/td-p/1216764 */
138
+ # pragma warning disable 2196 // warning #2196: routine is both "inline" and "noinline"
139
+ #elif defined(__clang__) && !defined(__apple_build_version__)
140
+ # if __clang_major__ < 3 || (__clang_major__ == 3 && __clang_minor__ < 3)
141
+ # error pybind11 requires clang 3.3 or newer
142
+ # endif
143
+ #elif defined(__clang__)
144
+ // Apple changes clang version macros to its Xcode version; the first Xcode release based on
145
+ // (upstream) clang 3.3 was Xcode 5:
146
+ # if __clang_major__ < 5
147
+ # error pybind11 requires Xcode/clang 5.0 or newer
148
+ # endif
149
+ #elif defined(__GNUG__)
150
+ # if __GNUC__ < 4 || (__GNUC__ == 4 && __GNUC_MINOR__ < 8)
151
+ # error pybind11 requires gcc 4.8 or newer
152
+ # endif
153
+ #elif defined(_MSC_VER)
154
+ # if _MSC_VER < 1910
155
+ # error pybind11 2.10+ requires MSVC 2017 or newer
156
+ # endif
157
+ #endif
158
+
159
+ #if !defined(PYBIND11_EXPORT)
160
+ # if defined(WIN32) || defined(_WIN32)
161
+ # define PYBIND11_EXPORT __declspec(dllexport)
162
+ # else
163
+ # define PYBIND11_EXPORT __attribute__((visibility("default")))
164
+ # endif
165
+ #endif
166
+
167
+ #if !defined(PYBIND11_EXPORT_EXCEPTION)
168
+ # if defined(__apple_build_version__)
169
+ # define PYBIND11_EXPORT_EXCEPTION PYBIND11_EXPORT
170
+ # else
171
+ # define PYBIND11_EXPORT_EXCEPTION
172
+ # endif
173
+ #endif
174
+
175
+ // For CUDA, GCC7, GCC8:
176
+ // PYBIND11_NOINLINE_FORCED is incompatible with `-Wattributes -Werror`.
177
+ // When defining PYBIND11_NOINLINE_FORCED, it is best to also use `-Wno-attributes`.
178
+ // However, the measured shared-library size saving when using noinline are only
179
+ // 1.7% for CUDA, -0.2% for GCC7, and 0.0% for GCC8 (using -DCMAKE_BUILD_TYPE=MinSizeRel,
180
+ // the default under pybind11/tests).
181
+ #if !defined(PYBIND11_NOINLINE_FORCED) \
182
+ && (defined(__CUDACC__) || (defined(__GNUC__) && (__GNUC__ == 7 || __GNUC__ == 8)))
183
+ # define PYBIND11_NOINLINE_DISABLED
184
+ #endif
185
+
186
+ // The PYBIND11_NOINLINE macro is for function DEFINITIONS.
187
+ // In contrast, FORWARD DECLARATIONS should never use this macro:
188
+ // https://stackoverflow.com/questions/9317473/forward-declaration-of-inline-functions
189
+ #if defined(PYBIND11_NOINLINE_DISABLED) // Option for maximum portability and experimentation.
190
+ # define PYBIND11_NOINLINE inline
191
+ #elif defined(_MSC_VER)
192
+ # define PYBIND11_NOINLINE __declspec(noinline) inline
193
+ #else
194
+ # define PYBIND11_NOINLINE __attribute__((noinline)) inline
195
+ #endif
196
+
197
+ #if defined(__MINGW32__)
198
+ // For unknown reasons all PYBIND11_DEPRECATED member trigger a warning when declared
199
+ // whether it is used or not
200
+ # define PYBIND11_DEPRECATED(reason)
201
+ #elif defined(PYBIND11_CPP14)
202
+ # define PYBIND11_DEPRECATED(reason) [[deprecated(reason)]]
203
+ #else
204
+ # define PYBIND11_DEPRECATED(reason) __attribute__((deprecated(reason)))
205
+ #endif
206
+
207
+ #if defined(PYBIND11_CPP17)
208
+ # define PYBIND11_MAYBE_UNUSED [[maybe_unused]]
209
+ #elif defined(_MSC_VER) && !defined(__clang__)
210
+ # define PYBIND11_MAYBE_UNUSED
211
+ #else
212
+ # define PYBIND11_MAYBE_UNUSED __attribute__((__unused__))
213
+ #endif
214
+
215
+ /* Don't let Python.h #define (v)snprintf as macro because they are implemented
216
+ properly in Visual Studio since 2015. */
217
+ #if defined(_MSC_VER)
218
+ # define HAVE_SNPRINTF 1
219
+ #endif
220
+
221
+ /// Include Python header, disable linking to pythonX_d.lib on Windows in debug mode
222
+ #if defined(_MSC_VER)
223
+ PYBIND11_WARNING_PUSH
224
+ PYBIND11_WARNING_DISABLE_MSVC(4505)
225
+ // C4505: 'PySlice_GetIndicesEx': unreferenced local function has been removed (PyPy only)
226
+ # if defined(_DEBUG) && !defined(Py_DEBUG)
227
+ // Workaround for a VS 2022 issue.
228
+ // NOTE: This workaround knowingly violates the Python.h include order requirement:
229
+ // https://docs.python.org/3/c-api/intro.html#include-files
230
+ // See https://github.com/pybind/pybind11/pull/3497 for full context.
231
+ # include <yvals.h>
232
+ # if _MSVC_STL_VERSION >= 143
233
+ # include <crtdefs.h>
234
+ # endif
235
+ # define PYBIND11_DEBUG_MARKER
236
+ # undef _DEBUG
237
+ # endif
238
+ #endif
239
+
240
+ // https://en.cppreference.com/w/c/chrono/localtime
241
+ #if defined(__STDC_LIB_EXT1__) && !defined(__STDC_WANT_LIB_EXT1__)
242
+ # define __STDC_WANT_LIB_EXT1__
243
+ #endif
244
+
245
+ #ifdef __has_include
246
+ // std::optional (but including it in c++14 mode isn't allowed)
247
+ # if defined(PYBIND11_CPP17) && __has_include(<optional>)
248
+ # define PYBIND11_HAS_OPTIONAL 1
249
+ # endif
250
+ // std::experimental::optional (but not allowed in c++11 mode)
251
+ # if defined(PYBIND11_CPP14) && (__has_include(<experimental/optional>) && \
252
+ !__has_include(<optional>))
253
+ # define PYBIND11_HAS_EXP_OPTIONAL 1
254
+ # endif
255
+ // std::variant
256
+ # if defined(PYBIND11_CPP17) && __has_include(<variant>)
257
+ # define PYBIND11_HAS_VARIANT 1
258
+ # endif
259
+ #elif defined(_MSC_VER) && defined(PYBIND11_CPP17)
260
+ # define PYBIND11_HAS_OPTIONAL 1
261
+ # define PYBIND11_HAS_VARIANT 1
262
+ #endif
263
+
264
+ #if defined(PYBIND11_CPP17)
265
+ # if defined(__has_include)
266
+ # if __has_include(<string_view>)
267
+ # define PYBIND11_HAS_STRING_VIEW
268
+ # endif
269
+ # elif defined(_MSC_VER)
270
+ # define PYBIND11_HAS_STRING_VIEW
271
+ # endif
272
+ #endif
273
+
274
+ #include <Python.h>
275
+ #if PY_VERSION_HEX < 0x03070000
276
+ # error "PYTHON < 3.7 IS UNSUPPORTED. pybind11 v2.12 was the last to support Python 3.6."
277
+ #endif
278
+ #include <frameobject.h>
279
+ #include <pythread.h>
280
+
281
+ /* Python #defines overrides on all sorts of core functions, which
282
+ tends to weak havok in C++ codebases that expect these to work
283
+ like regular functions (potentially with several overloads) */
284
+ #if defined(isalnum)
285
+ # undef isalnum
286
+ # undef isalpha
287
+ # undef islower
288
+ # undef isspace
289
+ # undef isupper
290
+ # undef tolower
291
+ # undef toupper
292
+ #endif
293
+
294
+ #if defined(copysign)
295
+ # undef copysign
296
+ #endif
297
+
298
+ #if defined(PYBIND11_NUMPY_1_ONLY)
299
+ # define PYBIND11_INTERNAL_NUMPY_1_ONLY_DETECTED
300
+ #endif
301
+
302
+ #if defined(PYPY_VERSION) && !defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
303
+ # define PYBIND11_SIMPLE_GIL_MANAGEMENT
304
+ #endif
305
+
306
+ #if defined(_MSC_VER)
307
+ # if defined(PYBIND11_DEBUG_MARKER)
308
+ # define _DEBUG
309
+ # undef PYBIND11_DEBUG_MARKER
310
+ # endif
311
+ PYBIND11_WARNING_POP
312
+ #endif
313
+
314
+ #include <cstddef>
315
+ #include <cstring>
316
+ #include <exception>
317
+ #include <forward_list>
318
+ #include <memory>
319
+ #include <stdexcept>
320
+ #include <string>
321
+ #include <type_traits>
322
+ #include <typeindex>
323
+ #include <unordered_map>
324
+ #include <unordered_set>
325
+ #include <vector>
326
+ #if defined(__has_include)
327
+ # if __has_include(<version>)
328
+ # include <version>
329
+ # endif
330
+ #endif
331
+
332
+ // Must be after including <version> or one of the other headers specified by the standard
333
+ #if defined(__cpp_lib_char8_t) && __cpp_lib_char8_t >= 201811L
334
+ # define PYBIND11_HAS_U8STRING
335
+ #endif
336
+
337
+ // See description of PR #4246:
338
+ #if !defined(PYBIND11_NO_ASSERT_GIL_HELD_INCREF_DECREF) && !defined(NDEBUG) \
339
+ && !defined(PYPY_VERSION) && !defined(PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF)
340
+ # define PYBIND11_ASSERT_GIL_HELD_INCREF_DECREF
341
+ #endif
342
+
343
+ // #define PYBIND11_STR_LEGACY_PERMISSIVE
344
+ // If DEFINED, pybind11::str can hold PyUnicodeObject or PyBytesObject
345
+ // (probably surprising and never documented, but this was the
346
+ // legacy behavior until and including v2.6.x). As a side-effect,
347
+ // pybind11::isinstance<str>() is true for both pybind11::str and
348
+ // pybind11::bytes.
349
+ // If UNDEFINED, pybind11::str can only hold PyUnicodeObject, and
350
+ // pybind11::isinstance<str>() is true only for pybind11::str.
351
+ // However, for Python 2 only (!), the pybind11::str caster
352
+ // implicitly decoded bytes to PyUnicodeObject. This was to ease
353
+ // the transition from the legacy behavior to the non-permissive
354
+ // behavior.
355
+
356
+ /// Compatibility macros for Python 2 / Python 3 versions TODO: remove
357
+ #define PYBIND11_INSTANCE_METHOD_NEW(ptr, class_) PyInstanceMethod_New(ptr)
358
+ #define PYBIND11_INSTANCE_METHOD_CHECK PyInstanceMethod_Check
359
+ #define PYBIND11_INSTANCE_METHOD_GET_FUNCTION PyInstanceMethod_GET_FUNCTION
360
+ #define PYBIND11_BYTES_CHECK PyBytes_Check
361
+ #define PYBIND11_BYTES_FROM_STRING PyBytes_FromString
362
+ #define PYBIND11_BYTES_FROM_STRING_AND_SIZE PyBytes_FromStringAndSize
363
+ #define PYBIND11_BYTES_AS_STRING_AND_SIZE PyBytes_AsStringAndSize
364
+ #define PYBIND11_BYTES_AS_STRING PyBytes_AsString
365
+ #define PYBIND11_BYTES_SIZE PyBytes_Size
366
+ #define PYBIND11_LONG_CHECK(o) PyLong_Check(o)
367
+ #define PYBIND11_LONG_AS_LONGLONG(o) PyLong_AsLongLong(o)
368
+ #define PYBIND11_LONG_FROM_SIGNED(o) PyLong_FromSsize_t((ssize_t) (o))
369
+ #define PYBIND11_LONG_FROM_UNSIGNED(o) PyLong_FromSize_t((size_t) (o))
370
+ #define PYBIND11_BYTES_NAME "bytes"
371
+ #define PYBIND11_STRING_NAME "str"
372
+ #define PYBIND11_SLICE_OBJECT PyObject
373
+ #define PYBIND11_FROM_STRING PyUnicode_FromString
374
+ #define PYBIND11_STR_TYPE ::pybind11::str
375
+ #define PYBIND11_BOOL_ATTR "__bool__"
376
+ #define PYBIND11_NB_BOOL(ptr) ((ptr)->nb_bool)
377
+ #define PYBIND11_BUILTINS_MODULE "builtins"
378
+ // Providing a separate declaration to make Clang's -Wmissing-prototypes happy.
379
+ // See comment for PYBIND11_MODULE below for why this is marked "maybe unused".
380
+ #define PYBIND11_PLUGIN_IMPL(name) \
381
+ extern "C" PYBIND11_MAYBE_UNUSED PYBIND11_EXPORT PyObject *PyInit_##name(); \
382
+ extern "C" PYBIND11_EXPORT PyObject *PyInit_##name()
383
+
384
+ #define PYBIND11_TRY_NEXT_OVERLOAD ((PyObject *) 1) // special failure return code
385
+ #define PYBIND11_STRINGIFY(x) #x
386
+ #define PYBIND11_TOSTRING(x) PYBIND11_STRINGIFY(x)
387
+ #define PYBIND11_CONCAT(first, second) first##second
388
+ #define PYBIND11_ENSURE_INTERNALS_READY pybind11::detail::get_internals();
389
+
390
+ #define PYBIND11_CHECK_PYTHON_VERSION \
391
+ { \
392
+ const char *compiled_ver \
393
+ = PYBIND11_TOSTRING(PY_MAJOR_VERSION) "." PYBIND11_TOSTRING(PY_MINOR_VERSION); \
394
+ const char *runtime_ver = Py_GetVersion(); \
395
+ size_t len = std::strlen(compiled_ver); \
396
+ if (std::strncmp(runtime_ver, compiled_ver, len) != 0 \
397
+ || (runtime_ver[len] >= '0' && runtime_ver[len] <= '9')) { \
398
+ PyErr_Format(PyExc_ImportError, \
399
+ "Python version mismatch: module was compiled for Python %s, " \
400
+ "but the interpreter version is incompatible: %s.", \
401
+ compiled_ver, \
402
+ runtime_ver); \
403
+ return nullptr; \
404
+ } \
405
+ }
406
+
407
+ #define PYBIND11_CATCH_INIT_EXCEPTIONS \
408
+ catch (pybind11::error_already_set & e) { \
409
+ pybind11::raise_from(e, PyExc_ImportError, "initialization failed"); \
410
+ return nullptr; \
411
+ } \
412
+ catch (const std::exception &e) { \
413
+ ::pybind11::set_error(PyExc_ImportError, e.what()); \
414
+ return nullptr; \
415
+ }
416
+
417
+ /** \rst
418
+ ***Deprecated in favor of PYBIND11_MODULE***
419
+
420
+ This macro creates the entry point that will be invoked when the Python interpreter
421
+ imports a plugin library. Please create a `module_` in the function body and return
422
+ the pointer to its underlying Python object at the end.
423
+
424
+ .. code-block:: cpp
425
+
426
+ PYBIND11_PLUGIN(example) {
427
+ pybind11::module_ m("example", "pybind11 example plugin");
428
+ /// Set up bindings here
429
+ return m.ptr();
430
+ }
431
+ \endrst */
432
+ #define PYBIND11_PLUGIN(name) \
433
+ PYBIND11_DEPRECATED("PYBIND11_PLUGIN is deprecated, use PYBIND11_MODULE") \
434
+ static PyObject *pybind11_init(); \
435
+ PYBIND11_PLUGIN_IMPL(name) { \
436
+ PYBIND11_CHECK_PYTHON_VERSION \
437
+ PYBIND11_ENSURE_INTERNALS_READY \
438
+ try { \
439
+ return pybind11_init(); \
440
+ } \
441
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
442
+ } \
443
+ PyObject *pybind11_init()
444
+
445
+ /** \rst
446
+ This macro creates the entry point that will be invoked when the Python interpreter
447
+ imports an extension module. The module name is given as the first argument and it
448
+ should not be in quotes. The second macro argument defines a variable of type
449
+ `py::module_` which can be used to initialize the module.
450
+
451
+ The entry point is marked as "maybe unused" to aid dead-code detection analysis:
452
+ since the entry point is typically only looked up at runtime and not referenced
453
+ during translation, it would otherwise appear as unused ("dead") code.
454
+
455
+ .. code-block:: cpp
456
+
457
+ PYBIND11_MODULE(example, m) {
458
+ m.doc() = "pybind11 example module";
459
+
460
+ // Add bindings here
461
+ m.def("foo", []() {
462
+ return "Hello, World!";
463
+ });
464
+ }
465
+
466
+ The third macro argument is optional (available since 2.13.0), and can be used to
467
+ mark the extension module as safe to run without the GIL under a free-threaded CPython
468
+ interpreter. Passing this argument has no effect on other interpreters.
469
+
470
+ .. code-block:: cpp
471
+
472
+ PYBIND11_MODULE(example, m, py::mod_gil_not_used()) {
473
+ m.doc() = "pybind11 example module safe to run without the GIL";
474
+
475
+ // Add bindings here
476
+ m.def("foo", []() {
477
+ return "Hello, Free-threaded World!";
478
+ });
479
+ }
480
+
481
+ \endrst */
482
+ PYBIND11_WARNING_PUSH
483
+ PYBIND11_WARNING_DISABLE_CLANG("-Wgnu-zero-variadic-macro-arguments")
484
+ #define PYBIND11_MODULE(name, variable, ...) \
485
+ static ::pybind11::module_::module_def PYBIND11_CONCAT(pybind11_module_def_, name) \
486
+ PYBIND11_MAYBE_UNUSED; \
487
+ PYBIND11_MAYBE_UNUSED \
488
+ static void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ &); \
489
+ PYBIND11_PLUGIN_IMPL(name) { \
490
+ PYBIND11_CHECK_PYTHON_VERSION \
491
+ PYBIND11_ENSURE_INTERNALS_READY \
492
+ auto m = ::pybind11::module_::create_extension_module( \
493
+ PYBIND11_TOSTRING(name), \
494
+ nullptr, \
495
+ &PYBIND11_CONCAT(pybind11_module_def_, name), \
496
+ ##__VA_ARGS__); \
497
+ try { \
498
+ PYBIND11_CONCAT(pybind11_init_, name)(m); \
499
+ return m.ptr(); \
500
+ } \
501
+ PYBIND11_CATCH_INIT_EXCEPTIONS \
502
+ } \
503
+ void PYBIND11_CONCAT(pybind11_init_, name)(::pybind11::module_ & (variable))
504
+ PYBIND11_WARNING_POP
505
+
506
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
507
+
508
+ using ssize_t = Py_ssize_t;
509
+ using size_t = std::size_t;
510
+
511
+ template <typename IntType>
512
+ inline ssize_t ssize_t_cast(const IntType &val) {
513
+ static_assert(sizeof(IntType) <= sizeof(ssize_t), "Implicit narrowing is not permitted.");
514
+ return static_cast<ssize_t>(val);
515
+ }
516
+
517
+ /// Approach used to cast a previously unknown C++ instance into a Python object
518
+ enum class return_value_policy : uint8_t {
519
+ /** This is the default return value policy, which falls back to the policy
520
+ return_value_policy::take_ownership when the return value is a pointer.
521
+ Otherwise, it uses return_value::move or return_value::copy for rvalue
522
+ and lvalue references, respectively. See below for a description of what
523
+ all of these different policies do. */
524
+ automatic = 0,
525
+
526
+ /** As above, but use policy return_value_policy::reference when the return
527
+ value is a pointer. This is the default conversion policy for function
528
+ arguments when calling Python functions manually from C++ code (i.e. via
529
+ handle::operator()). You probably won't need to use this. */
530
+ automatic_reference,
531
+
532
+ /** Reference an existing object (i.e. do not create a new copy) and take
533
+ ownership. Python will call the destructor and delete operator when the
534
+ object's reference count reaches zero. Undefined behavior ensues when
535
+ the C++ side does the same.. */
536
+ take_ownership,
537
+
538
+ /** Create a new copy of the returned object, which will be owned by
539
+ Python. This policy is comparably safe because the lifetimes of the two
540
+ instances are decoupled. */
541
+ copy,
542
+
543
+ /** Use std::move to move the return value contents into a new instance
544
+ that will be owned by Python. This policy is comparably safe because the
545
+ lifetimes of the two instances (move source and destination) are
546
+ decoupled. */
547
+ move,
548
+
549
+ /** Reference an existing object, but do not take ownership. The C++ side
550
+ is responsible for managing the object's lifetime and deallocating it
551
+ when it is no longer used. Warning: undefined behavior will ensue when
552
+ the C++ side deletes an object that is still referenced and used by
553
+ Python. */
554
+ reference,
555
+
556
+ /** This policy only applies to methods and properties. It references the
557
+ object without taking ownership similar to the above
558
+ return_value_policy::reference policy. In contrast to that policy, the
559
+ function or property's implicit this argument (called the parent) is
560
+ considered to be the owner of the return value (the child).
561
+ pybind11 then couples the lifetime of the parent to the child via a
562
+ reference relationship that ensures that the parent cannot be garbage
563
+ collected while Python is still using the child. More advanced
564
+ variations of this scheme are also possible using combinations of
565
+ return_value_policy::reference and the keep_alive call policy */
566
+ reference_internal
567
+ };
568
+
569
+ PYBIND11_NAMESPACE_BEGIN(detail)
570
+
571
+ inline static constexpr int log2(size_t n, int k = 0) {
572
+ return (n <= 1) ? k : log2(n >> 1, k + 1);
573
+ }
574
+
575
+ // Returns the size as a multiple of sizeof(void *), rounded up.
576
+ inline static constexpr size_t size_in_ptrs(size_t s) {
577
+ return 1 + ((s - 1) >> log2(sizeof(void *)));
578
+ }
579
+
580
+ /**
581
+ * The space to allocate for simple layout instance holders (see below) in multiple of the size of
582
+ * a pointer (e.g. 2 means 16 bytes on 64-bit architectures). The default is the minimum required
583
+ * to holder either a std::unique_ptr or std::shared_ptr (which is almost always
584
+ * sizeof(std::shared_ptr<T>)).
585
+ */
586
+ constexpr size_t instance_simple_holder_in_ptrs() {
587
+ static_assert(sizeof(std::shared_ptr<int>) >= sizeof(std::unique_ptr<int>),
588
+ "pybind assumes std::shared_ptrs are at least as big as std::unique_ptrs");
589
+ return size_in_ptrs(sizeof(std::shared_ptr<int>));
590
+ }
591
+
592
+ // Forward declarations
593
+ struct type_info;
594
+ struct value_and_holder;
595
+
596
+ struct nonsimple_values_and_holders {
597
+ void **values_and_holders;
598
+ uint8_t *status;
599
+ };
600
+
601
+ /// The 'instance' type which needs to be standard layout (need to be able to use 'offsetof')
602
+ struct instance {
603
+ PyObject_HEAD
604
+ /// Storage for pointers and holder; see simple_layout, below, for a description
605
+ union {
606
+ void *simple_value_holder[1 + instance_simple_holder_in_ptrs()];
607
+ nonsimple_values_and_holders nonsimple;
608
+ };
609
+ /// Weak references
610
+ PyObject *weakrefs;
611
+ /// If true, the pointer is owned which means we're free to manage it with a holder.
612
+ bool owned : 1;
613
+ /**
614
+ * An instance has two possible value/holder layouts.
615
+ *
616
+ * Simple layout (when this flag is true), means the `simple_value_holder` is set with a
617
+ * pointer and the holder object governing that pointer, i.e. [val1*][holder]. This layout is
618
+ * applied whenever there is no python-side multiple inheritance of bound C++ types *and* the
619
+ * type's holder will fit in the default space (which is large enough to hold either a
620
+ * std::unique_ptr or std::shared_ptr).
621
+ *
622
+ * Non-simple layout applies when using custom holders that require more space than
623
+ * `shared_ptr` (which is typically the size of two pointers), or when multiple inheritance is
624
+ * used on the python side. Non-simple layout allocates the required amount of memory to have
625
+ * multiple bound C++ classes as parents. Under this layout, `nonsimple.values_and_holders` is
626
+ * set to a pointer to allocated space of the required space to hold a sequence of value
627
+ * pointers and holders followed `status`, a set of bit flags (1 byte each), i.e.
628
+ * [val1*][holder1][val2*][holder2]...[bb...] where each [block] is rounded up to a multiple
629
+ * of `sizeof(void *)`. `nonsimple.status` is, for convenience, a pointer to the beginning of
630
+ * the [bb...] block (but not independently allocated).
631
+ *
632
+ * Status bits indicate whether the associated holder is constructed (&
633
+ * status_holder_constructed) and whether the value pointer is registered (&
634
+ * status_instance_registered) in `registered_instances`.
635
+ */
636
+ bool simple_layout : 1;
637
+ /// For simple layout, tracks whether the holder has been constructed
638
+ bool simple_holder_constructed : 1;
639
+ /// For simple layout, tracks whether the instance is registered in `registered_instances`
640
+ bool simple_instance_registered : 1;
641
+ /// If true, get_internals().patients has an entry for this object
642
+ bool has_patients : 1;
643
+
644
+ /// Initializes all of the above type/values/holders data (but not the instance values
645
+ /// themselves)
646
+ void allocate_layout();
647
+
648
+ /// Destroys/deallocates all of the above
649
+ void deallocate_layout();
650
+
651
+ /// Returns the value_and_holder wrapper for the given type (or the first, if `find_type`
652
+ /// omitted). Returns a default-constructed (with `.inst = nullptr`) object on failure if
653
+ /// `throw_if_missing` is false.
654
+ value_and_holder get_value_and_holder(const type_info *find_type = nullptr,
655
+ bool throw_if_missing = true);
656
+
657
+ /// Bit values for the non-simple status flags
658
+ static constexpr uint8_t status_holder_constructed = 1;
659
+ static constexpr uint8_t status_instance_registered = 2;
660
+ };
661
+
662
+ static_assert(std::is_standard_layout<instance>::value,
663
+ "Internal error: `pybind11::detail::instance` is not standard layout!");
664
+
665
+ /// from __cpp_future__ import (convenient aliases from C++14/17)
666
+ #if defined(PYBIND11_CPP14)
667
+ using std::conditional_t;
668
+ using std::enable_if_t;
669
+ using std::remove_cv_t;
670
+ using std::remove_reference_t;
671
+ #else
672
+ template <bool B, typename T = void>
673
+ using enable_if_t = typename std::enable_if<B, T>::type;
674
+ template <bool B, typename T, typename F>
675
+ using conditional_t = typename std::conditional<B, T, F>::type;
676
+ template <typename T>
677
+ using remove_cv_t = typename std::remove_cv<T>::type;
678
+ template <typename T>
679
+ using remove_reference_t = typename std::remove_reference<T>::type;
680
+ #endif
681
+
682
+ #if defined(PYBIND11_CPP20)
683
+ using std::remove_cvref;
684
+ using std::remove_cvref_t;
685
+ #else
686
+ template <class T>
687
+ struct remove_cvref {
688
+ using type = remove_cv_t<remove_reference_t<T>>;
689
+ };
690
+ template <class T>
691
+ using remove_cvref_t = typename remove_cvref<T>::type;
692
+ #endif
693
+
694
+ /// Example usage: is_same_ignoring_cvref<T, PyObject *>::value
695
+ template <typename T, typename U>
696
+ using is_same_ignoring_cvref = std::is_same<detail::remove_cvref_t<T>, U>;
697
+
698
+ /// Index sequences
699
+ #if defined(PYBIND11_CPP14)
700
+ using std::index_sequence;
701
+ using std::make_index_sequence;
702
+ #else
703
+ template <size_t...>
704
+ struct index_sequence {};
705
+ template <size_t N, size_t... S>
706
+ struct make_index_sequence_impl : make_index_sequence_impl<N - 1, N - 1, S...> {};
707
+ template <size_t... S>
708
+ struct make_index_sequence_impl<0, S...> {
709
+ using type = index_sequence<S...>;
710
+ };
711
+ template <size_t N>
712
+ using make_index_sequence = typename make_index_sequence_impl<N>::type;
713
+ #endif
714
+
715
+ /// Make an index sequence of the indices of true arguments
716
+ template <typename ISeq, size_t, bool...>
717
+ struct select_indices_impl {
718
+ using type = ISeq;
719
+ };
720
+ template <size_t... IPrev, size_t I, bool B, bool... Bs>
721
+ struct select_indices_impl<index_sequence<IPrev...>, I, B, Bs...>
722
+ : select_indices_impl<conditional_t<B, index_sequence<IPrev..., I>, index_sequence<IPrev...>>,
723
+ I + 1,
724
+ Bs...> {};
725
+ template <bool... Bs>
726
+ using select_indices = typename select_indices_impl<index_sequence<>, 0, Bs...>::type;
727
+
728
+ /// Backports of std::bool_constant and std::negation to accommodate older compilers
729
+ template <bool B>
730
+ using bool_constant = std::integral_constant<bool, B>;
731
+ template <typename T>
732
+ struct negation : bool_constant<!T::value> {};
733
+
734
+ // PGI/Intel cannot detect operator delete with the "compatible" void_t impl, so
735
+ // using the new one (C++14 defect, so generally works on newer compilers, even
736
+ // if not in C++17 mode)
737
+ #if defined(__PGIC__) || defined(__INTEL_COMPILER)
738
+ template <typename...>
739
+ using void_t = void;
740
+ #else
741
+ template <typename...>
742
+ struct void_t_impl {
743
+ using type = void;
744
+ };
745
+ template <typename... Ts>
746
+ using void_t = typename void_t_impl<Ts...>::type;
747
+ #endif
748
+
749
+ /// Compile-time all/any/none of that check the boolean value of all template types
750
+ #if defined(__cpp_fold_expressions) && !(defined(_MSC_VER) && (_MSC_VER < 1916))
751
+ template <class... Ts>
752
+ using all_of = bool_constant<(Ts::value && ...)>;
753
+ template <class... Ts>
754
+ using any_of = bool_constant<(Ts::value || ...)>;
755
+ #elif !defined(_MSC_VER)
756
+ template <bool...>
757
+ struct bools {};
758
+ template <class... Ts>
759
+ using all_of = std::is_same<bools<Ts::value..., true>, bools<true, Ts::value...>>;
760
+ template <class... Ts>
761
+ using any_of = negation<all_of<negation<Ts>...>>;
762
+ #else
763
+ // MSVC has trouble with the above, but supports std::conjunction, which we can use instead (albeit
764
+ // at a slight loss of compilation efficiency).
765
+ template <class... Ts>
766
+ using all_of = std::conjunction<Ts...>;
767
+ template <class... Ts>
768
+ using any_of = std::disjunction<Ts...>;
769
+ #endif
770
+ template <class... Ts>
771
+ using none_of = negation<any_of<Ts...>>;
772
+
773
+ template <class T, template <class> class... Predicates>
774
+ using satisfies_all_of = all_of<Predicates<T>...>;
775
+ template <class T, template <class> class... Predicates>
776
+ using satisfies_any_of = any_of<Predicates<T>...>;
777
+ template <class T, template <class> class... Predicates>
778
+ using satisfies_none_of = none_of<Predicates<T>...>;
779
+
780
+ /// Strip the class from a method type
781
+ template <typename T>
782
+ struct remove_class {};
783
+ template <typename C, typename R, typename... A>
784
+ struct remove_class<R (C::*)(A...)> {
785
+ using type = R(A...);
786
+ };
787
+ template <typename C, typename R, typename... A>
788
+ struct remove_class<R (C::*)(A...) const> {
789
+ using type = R(A...);
790
+ };
791
+ #ifdef __cpp_noexcept_function_type
792
+ template <typename C, typename R, typename... A>
793
+ struct remove_class<R (C::*)(A...) noexcept> {
794
+ using type = R(A...);
795
+ };
796
+ template <typename C, typename R, typename... A>
797
+ struct remove_class<R (C::*)(A...) const noexcept> {
798
+ using type = R(A...);
799
+ };
800
+ #endif
801
+ /// Helper template to strip away type modifiers
802
+ template <typename T>
803
+ struct intrinsic_type {
804
+ using type = T;
805
+ };
806
+ template <typename T>
807
+ struct intrinsic_type<const T> {
808
+ using type = typename intrinsic_type<T>::type;
809
+ };
810
+ template <typename T>
811
+ struct intrinsic_type<T *> {
812
+ using type = typename intrinsic_type<T>::type;
813
+ };
814
+ template <typename T>
815
+ struct intrinsic_type<T &> {
816
+ using type = typename intrinsic_type<T>::type;
817
+ };
818
+ template <typename T>
819
+ struct intrinsic_type<T &&> {
820
+ using type = typename intrinsic_type<T>::type;
821
+ };
822
+ template <typename T, size_t N>
823
+ struct intrinsic_type<const T[N]> {
824
+ using type = typename intrinsic_type<T>::type;
825
+ };
826
+ template <typename T, size_t N>
827
+ struct intrinsic_type<T[N]> {
828
+ using type = typename intrinsic_type<T>::type;
829
+ };
830
+ template <typename T>
831
+ using intrinsic_t = typename intrinsic_type<T>::type;
832
+
833
+ /// Helper type to replace 'void' in some expressions
834
+ struct void_type {};
835
+
836
+ /// Helper template which holds a list of types
837
+ template <typename...>
838
+ struct type_list {};
839
+
840
+ /// Compile-time integer sum
841
+ #ifdef __cpp_fold_expressions
842
+ template <typename... Ts>
843
+ constexpr size_t constexpr_sum(Ts... ns) {
844
+ return (0 + ... + size_t{ns});
845
+ }
846
+ #else
847
+ constexpr size_t constexpr_sum() { return 0; }
848
+ template <typename T, typename... Ts>
849
+ constexpr size_t constexpr_sum(T n, Ts... ns) {
850
+ return size_t{n} + constexpr_sum(ns...);
851
+ }
852
+ #endif
853
+
854
+ PYBIND11_NAMESPACE_BEGIN(constexpr_impl)
855
+ /// Implementation details for constexpr functions
856
+ constexpr int first(int i) { return i; }
857
+ template <typename T, typename... Ts>
858
+ constexpr int first(int i, T v, Ts... vs) {
859
+ return v ? i : first(i + 1, vs...);
860
+ }
861
+
862
+ constexpr int last(int /*i*/, int result) { return result; }
863
+ template <typename T, typename... Ts>
864
+ constexpr int last(int i, int result, T v, Ts... vs) {
865
+ return last(i + 1, v ? i : result, vs...);
866
+ }
867
+ PYBIND11_NAMESPACE_END(constexpr_impl)
868
+
869
+ /// Return the index of the first type in Ts which satisfies Predicate<T>.
870
+ /// Returns sizeof...(Ts) if none match.
871
+ template <template <typename> class Predicate, typename... Ts>
872
+ constexpr int constexpr_first() {
873
+ return constexpr_impl::first(0, Predicate<Ts>::value...);
874
+ }
875
+
876
+ /// Return the index of the last type in Ts which satisfies Predicate<T>, or -1 if none match.
877
+ template <template <typename> class Predicate, typename... Ts>
878
+ constexpr int constexpr_last() {
879
+ return constexpr_impl::last(0, -1, Predicate<Ts>::value...);
880
+ }
881
+
882
+ /// Return the Nth element from the parameter pack
883
+ template <size_t N, typename T, typename... Ts>
884
+ struct pack_element {
885
+ using type = typename pack_element<N - 1, Ts...>::type;
886
+ };
887
+ template <typename T, typename... Ts>
888
+ struct pack_element<0, T, Ts...> {
889
+ using type = T;
890
+ };
891
+
892
+ /// Return the one and only type which matches the predicate, or Default if none match.
893
+ /// If more than one type matches the predicate, fail at compile-time.
894
+ template <template <typename> class Predicate, typename Default, typename... Ts>
895
+ struct exactly_one {
896
+ static constexpr auto found = constexpr_sum(Predicate<Ts>::value...);
897
+ static_assert(found <= 1, "Found more than one type matching the predicate");
898
+
899
+ static constexpr auto index = found ? constexpr_first<Predicate, Ts...>() : 0;
900
+ using type = conditional_t<found, typename pack_element<index, Ts...>::type, Default>;
901
+ };
902
+ template <template <typename> class P, typename Default>
903
+ struct exactly_one<P, Default> {
904
+ using type = Default;
905
+ };
906
+
907
+ template <template <typename> class Predicate, typename Default, typename... Ts>
908
+ using exactly_one_t = typename exactly_one<Predicate, Default, Ts...>::type;
909
+
910
+ /// Defer the evaluation of type T until types Us are instantiated
911
+ template <typename T, typename... /*Us*/>
912
+ struct deferred_type {
913
+ using type = T;
914
+ };
915
+ template <typename T, typename... Us>
916
+ using deferred_t = typename deferred_type<T, Us...>::type;
917
+
918
+ /// Like is_base_of, but requires a strict base (i.e. `is_strict_base_of<T, T>::value == false`,
919
+ /// unlike `std::is_base_of`)
920
+ template <typename Base, typename Derived>
921
+ using is_strict_base_of
922
+ = bool_constant<std::is_base_of<Base, Derived>::value && !std::is_same<Base, Derived>::value>;
923
+
924
+ /// Like is_base_of, but also requires that the base type is accessible (i.e. that a Derived
925
+ /// pointer can be converted to a Base pointer) For unions, `is_base_of<T, T>::value` is False, so
926
+ /// we need to check `is_same` as well.
927
+ template <typename Base, typename Derived>
928
+ using is_accessible_base_of
929
+ = bool_constant<(std::is_same<Base, Derived>::value || std::is_base_of<Base, Derived>::value)
930
+ && std::is_convertible<Derived *, Base *>::value>;
931
+
932
+ template <template <typename...> class Base>
933
+ struct is_template_base_of_impl {
934
+ template <typename... Us>
935
+ static std::true_type check(Base<Us...> *);
936
+ static std::false_type check(...);
937
+ };
938
+
939
+ /// Check if a template is the base of a type. For example:
940
+ /// `is_template_base_of<Base, T>` is true if `struct T : Base<U> {}` where U can be anything
941
+ template <template <typename...> class Base, typename T>
942
+ // Sadly, all MSVC versions incl. 2022 need the workaround, even in C++20 mode.
943
+ // See also: https://github.com/pybind/pybind11/pull/3741
944
+ #if !defined(_MSC_VER)
945
+ using is_template_base_of
946
+ = decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr));
947
+ #else
948
+ struct is_template_base_of
949
+ : decltype(is_template_base_of_impl<Base>::check((intrinsic_t<T> *) nullptr)){};
950
+ #endif
951
+
952
+ /// Check if T is an instantiation of the template `Class`. For example:
953
+ /// `is_instantiation<shared_ptr, T>` is true if `T == shared_ptr<U>` where U can be anything.
954
+ template <template <typename...> class Class, typename T>
955
+ struct is_instantiation : std::false_type {};
956
+ template <template <typename...> class Class, typename... Us>
957
+ struct is_instantiation<Class, Class<Us...>> : std::true_type {};
958
+
959
+ /// Check if T is std::shared_ptr<U> where U can be anything
960
+ template <typename T>
961
+ using is_shared_ptr = is_instantiation<std::shared_ptr, T>;
962
+
963
+ /// Check if T looks like an input iterator
964
+ template <typename T, typename = void>
965
+ struct is_input_iterator : std::false_type {};
966
+ template <typename T>
967
+ struct is_input_iterator<T,
968
+ void_t<decltype(*std::declval<T &>()), decltype(++std::declval<T &>())>>
969
+ : std::true_type {};
970
+
971
+ template <typename T>
972
+ using is_function_pointer
973
+ = bool_constant<std::is_pointer<T>::value
974
+ && std::is_function<typename std::remove_pointer<T>::type>::value>;
975
+
976
+ template <typename F>
977
+ struct strip_function_object {
978
+ // If you are encountering an
979
+ // 'error: name followed by "::" must be a class or namespace name'
980
+ // with the Intel compiler and a noexcept function here,
981
+ // try to use noexcept(true) instead of plain noexcept.
982
+ using type = typename remove_class<decltype(&F::operator())>::type;
983
+ };
984
+
985
+ // Extracts the function signature from a function, function pointer or lambda.
986
+ template <typename Function, typename F = remove_reference_t<Function>>
987
+ using function_signature_t = conditional_t<
988
+ std::is_function<F>::value,
989
+ F,
990
+ typename conditional_t<std::is_pointer<F>::value || std::is_member_pointer<F>::value,
991
+ std::remove_pointer<F>,
992
+ strip_function_object<F>>::type>;
993
+
994
+ /// Returns true if the type looks like a lambda: that is, isn't a function, pointer or member
995
+ /// pointer. Note that this can catch all sorts of other things, too; this is intended to be used
996
+ /// in a place where passing a lambda makes sense.
997
+ template <typename T>
998
+ using is_lambda = satisfies_none_of<remove_reference_t<T>,
999
+ std::is_function,
1000
+ std::is_pointer,
1001
+ std::is_member_pointer>;
1002
+
1003
+ // [workaround(intel)] Internal error on fold expression
1004
+ /// Apply a function over each element of a parameter pack
1005
+ #if defined(__cpp_fold_expressions) && !defined(__INTEL_COMPILER)
1006
+ // Intel compiler produces an internal error on this fold expression (tested with ICC 19.0.2)
1007
+ # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) (((PATTERN), void()), ...)
1008
+ #else
1009
+ using expand_side_effects = bool[];
1010
+ # define PYBIND11_EXPAND_SIDE_EFFECTS(PATTERN) \
1011
+ (void) pybind11::detail::expand_side_effects { ((PATTERN), void(), false)..., false }
1012
+ #endif
1013
+
1014
+ PYBIND11_NAMESPACE_END(detail)
1015
+
1016
+ /// C++ bindings of builtin Python exceptions
1017
+ class PYBIND11_EXPORT_EXCEPTION builtin_exception : public std::runtime_error {
1018
+ public:
1019
+ using std::runtime_error::runtime_error;
1020
+ /// Set the error using the Python C API
1021
+ virtual void set_error() const = 0;
1022
+ };
1023
+
1024
+ #define PYBIND11_RUNTIME_EXCEPTION(name, type) \
1025
+ class PYBIND11_EXPORT_EXCEPTION name : public builtin_exception { \
1026
+ public: \
1027
+ using builtin_exception::builtin_exception; \
1028
+ name() : name("") {} \
1029
+ void set_error() const override { PyErr_SetString(type, what()); } \
1030
+ };
1031
+
1032
+ PYBIND11_RUNTIME_EXCEPTION(stop_iteration, PyExc_StopIteration)
1033
+ PYBIND11_RUNTIME_EXCEPTION(index_error, PyExc_IndexError)
1034
+ PYBIND11_RUNTIME_EXCEPTION(key_error, PyExc_KeyError)
1035
+ PYBIND11_RUNTIME_EXCEPTION(value_error, PyExc_ValueError)
1036
+ PYBIND11_RUNTIME_EXCEPTION(type_error, PyExc_TypeError)
1037
+ PYBIND11_RUNTIME_EXCEPTION(buffer_error, PyExc_BufferError)
1038
+ PYBIND11_RUNTIME_EXCEPTION(import_error, PyExc_ImportError)
1039
+ PYBIND11_RUNTIME_EXCEPTION(attribute_error, PyExc_AttributeError)
1040
+ PYBIND11_RUNTIME_EXCEPTION(cast_error, PyExc_RuntimeError) /// Thrown when pybind11::cast or
1041
+ /// handle::call fail due to a type
1042
+ /// casting error
1043
+ PYBIND11_RUNTIME_EXCEPTION(reference_cast_error, PyExc_RuntimeError) /// Used internally
1044
+
1045
+ [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const char *reason) {
1046
+ assert(!PyErr_Occurred());
1047
+ throw std::runtime_error(reason);
1048
+ }
1049
+ [[noreturn]] PYBIND11_NOINLINE void pybind11_fail(const std::string &reason) {
1050
+ assert(!PyErr_Occurred());
1051
+ throw std::runtime_error(reason);
1052
+ }
1053
+
1054
+ template <typename T, typename SFINAE = void>
1055
+ struct format_descriptor {};
1056
+
1057
+ template <typename T>
1058
+ struct format_descriptor<
1059
+ T,
1060
+ detail::enable_if_t<detail::is_same_ignoring_cvref<T, PyObject *>::value>> {
1061
+ static constexpr const char c = 'O';
1062
+ static constexpr const char value[2] = {c, '\0'};
1063
+ static std::string format() { return std::string(1, c); }
1064
+ };
1065
+
1066
+ PYBIND11_NAMESPACE_BEGIN(detail)
1067
+ // Returns the index of the given type in the type char array below, and in the list in numpy.h
1068
+ // The order here is: bool; 8 ints ((signed,unsigned)x(8,16,32,64)bits); float,double,long double;
1069
+ // complex float,double,long double. Note that the long double types only participate when long
1070
+ // double is actually longer than double (it isn't under MSVC).
1071
+ // NB: not only the string below but also complex.h and numpy.h rely on this order.
1072
+ template <typename T, typename SFINAE = void>
1073
+ struct is_fmt_numeric {
1074
+ static constexpr bool value = false;
1075
+ };
1076
+ template <typename T>
1077
+ struct is_fmt_numeric<T, enable_if_t<std::is_arithmetic<T>::value>> {
1078
+ static constexpr bool value = true;
1079
+ static constexpr int index
1080
+ = std::is_same<T, bool>::value
1081
+ ? 0
1082
+ : 1
1083
+ + (std::is_integral<T>::value
1084
+ ? detail::log2(sizeof(T)) * 2 + std::is_unsigned<T>::value
1085
+ : 8
1086
+ + (std::is_same<T, double>::value ? 1
1087
+ : std::is_same<T, long double>::value ? 2
1088
+ : 0));
1089
+ };
1090
+ PYBIND11_NAMESPACE_END(detail)
1091
+
1092
+ template <typename T>
1093
+ struct format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>> {
1094
+ static constexpr const char c = "?bBhHiIqQfdg"[detail::is_fmt_numeric<T>::index];
1095
+ static constexpr const char value[2] = {c, '\0'};
1096
+ static std::string format() { return std::string(1, c); }
1097
+ };
1098
+
1099
+ #if !defined(PYBIND11_CPP17)
1100
+
1101
+ template <typename T>
1102
+ constexpr const char
1103
+ format_descriptor<T, detail::enable_if_t<std::is_arithmetic<T>::value>>::value[2];
1104
+
1105
+ #endif
1106
+
1107
+ /// RAII wrapper that temporarily clears any Python error state
1108
+ struct error_scope {
1109
+ PyObject *type, *value, *trace;
1110
+ error_scope() { PyErr_Fetch(&type, &value, &trace); }
1111
+ error_scope(const error_scope &) = delete;
1112
+ error_scope &operator=(const error_scope &) = delete;
1113
+ ~error_scope() { PyErr_Restore(type, value, trace); }
1114
+ };
1115
+
1116
+ /// Dummy destructor wrapper that can be used to expose classes with a private destructor
1117
+ struct nodelete {
1118
+ template <typename T>
1119
+ void operator()(T *) {}
1120
+ };
1121
+
1122
+ PYBIND11_NAMESPACE_BEGIN(detail)
1123
+ template <typename... Args>
1124
+ struct overload_cast_impl {
1125
+ template <typename Return>
1126
+ constexpr auto operator()(Return (*pf)(Args...)) const noexcept -> decltype(pf) {
1127
+ return pf;
1128
+ }
1129
+
1130
+ template <typename Return, typename Class>
1131
+ constexpr auto operator()(Return (Class::*pmf)(Args...),
1132
+ std::false_type = {}) const noexcept -> decltype(pmf) {
1133
+ return pmf;
1134
+ }
1135
+
1136
+ template <typename Return, typename Class>
1137
+ constexpr auto operator()(Return (Class::*pmf)(Args...) const,
1138
+ std::true_type) const noexcept -> decltype(pmf) {
1139
+ return pmf;
1140
+ }
1141
+ };
1142
+ PYBIND11_NAMESPACE_END(detail)
1143
+
1144
+ // overload_cast requires variable templates: C++14
1145
+ #if defined(PYBIND11_CPP14)
1146
+ # define PYBIND11_OVERLOAD_CAST 1
1147
+ /// Syntax sugar for resolving overloaded function pointers:
1148
+ /// - regular: static_cast<Return (Class::*)(Arg0, Arg1, Arg2)>(&Class::func)
1149
+ /// - sweet: overload_cast<Arg0, Arg1, Arg2>(&Class::func)
1150
+ template <typename... Args>
1151
+ static constexpr detail::overload_cast_impl<Args...> overload_cast{};
1152
+ #endif
1153
+
1154
+ /// Const member function selector for overload_cast
1155
+ /// - regular: static_cast<Return (Class::*)(Arg) const>(&Class::func)
1156
+ /// - sweet: overload_cast<Arg>(&Class::func, const_)
1157
+ static constexpr auto const_ = std::true_type{};
1158
+
1159
+ #if !defined(PYBIND11_CPP14) // no overload_cast: providing something that static_assert-fails:
1160
+ template <typename... Args>
1161
+ struct overload_cast {
1162
+ static_assert(detail::deferred_t<std::false_type, Args...>::value,
1163
+ "pybind11::overload_cast<...> requires compiling in C++14 mode");
1164
+ };
1165
+ #endif // overload_cast
1166
+
1167
+ PYBIND11_NAMESPACE_BEGIN(detail)
1168
+
1169
+ // Adaptor for converting arbitrary container arguments into a vector; implicitly convertible from
1170
+ // any standard container (or C-style array) supporting std::begin/std::end, any singleton
1171
+ // arithmetic type (if T is arithmetic), or explicitly constructible from an iterator pair.
1172
+ template <typename T>
1173
+ class any_container {
1174
+ std::vector<T> v;
1175
+
1176
+ public:
1177
+ any_container() = default;
1178
+
1179
+ // Can construct from a pair of iterators
1180
+ template <typename It, typename = enable_if_t<is_input_iterator<It>::value>>
1181
+ any_container(It first, It last) : v(first, last) {}
1182
+
1183
+ // Implicit conversion constructor from any arbitrary container type
1184
+ // with values convertible to T
1185
+ template <typename Container,
1186
+ typename = enable_if_t<
1187
+ std::is_convertible<decltype(*std::begin(std::declval<const Container &>())),
1188
+ T>::value>>
1189
+ // NOLINTNEXTLINE(google-explicit-constructor)
1190
+ any_container(const Container &c) : any_container(std::begin(c), std::end(c)) {}
1191
+
1192
+ // initializer_list's aren't deducible, so don't get matched by the above template;
1193
+ // we need this to explicitly allow implicit conversion from one:
1194
+ template <typename TIn, typename = enable_if_t<std::is_convertible<TIn, T>::value>>
1195
+ any_container(const std::initializer_list<TIn> &c) : any_container(c.begin(), c.end()) {}
1196
+
1197
+ // Avoid copying if given an rvalue vector of the correct type.
1198
+ // NOLINTNEXTLINE(google-explicit-constructor)
1199
+ any_container(std::vector<T> &&v) : v(std::move(v)) {}
1200
+
1201
+ // Moves the vector out of an rvalue any_container
1202
+ // NOLINTNEXTLINE(google-explicit-constructor)
1203
+ operator std::vector<T> &&() && { return std::move(v); }
1204
+
1205
+ // Dereferencing obtains a reference to the underlying vector
1206
+ std::vector<T> &operator*() { return v; }
1207
+ const std::vector<T> &operator*() const { return v; }
1208
+
1209
+ // -> lets you call methods on the underlying vector
1210
+ std::vector<T> *operator->() { return &v; }
1211
+ const std::vector<T> *operator->() const { return &v; }
1212
+ };
1213
+
1214
+ // Forward-declaration; see detail/class.h
1215
+ std::string get_fully_qualified_tp_name(PyTypeObject *);
1216
+
1217
+ template <typename T>
1218
+ inline static std::shared_ptr<T>
1219
+ try_get_shared_from_this(std::enable_shared_from_this<T> *holder_value_ptr) {
1220
+ // Pre C++17, this code path exploits undefined behavior, but is known to work on many platforms.
1221
+ // Use at your own risk!
1222
+ // See also https://en.cppreference.com/w/cpp/memory/enable_shared_from_this, and in particular
1223
+ // the `std::shared_ptr<Good> gp1 = not_so_good.getptr();` and `try`-`catch` parts of the example.
1224
+ #if defined(__cpp_lib_enable_shared_from_this) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
1225
+ return holder_value_ptr->weak_from_this().lock();
1226
+ #else
1227
+ try {
1228
+ return holder_value_ptr->shared_from_this();
1229
+ } catch (const std::bad_weak_ptr &) {
1230
+ return nullptr;
1231
+ }
1232
+ #endif
1233
+ }
1234
+
1235
+ // For silencing "unused" compiler warnings in special situations.
1236
+ template <typename... Args>
1237
+ #if defined(_MSC_VER) && _MSC_VER < 1920 // MSVC 2017
1238
+ constexpr
1239
+ #endif
1240
+ inline void
1241
+ silence_unused_warnings(Args &&...) {
1242
+ }
1243
+
1244
+ // MSVC warning C4100: Unreferenced formal parameter
1245
+ #if defined(_MSC_VER) && _MSC_VER <= 1916
1246
+ # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...) \
1247
+ detail::silence_unused_warnings(__VA_ARGS__)
1248
+ #else
1249
+ # define PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(...)
1250
+ #endif
1251
+
1252
+ // GCC -Wunused-but-set-parameter All GCC versions (as of July 2021).
1253
+ #if defined(__GNUG__) && !defined(__clang__) && !defined(__INTEL_COMPILER)
1254
+ # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...) \
1255
+ detail::silence_unused_warnings(__VA_ARGS__)
1256
+ #else
1257
+ # define PYBIND11_WORKAROUND_INCORRECT_GCC_UNUSED_BUT_SET_PARAMETER(...)
1258
+ #endif
1259
+
1260
+ #if defined(__clang__) \
1261
+ && (defined(__apple_build_version__) /* AppleClang 13.0.0.13000029 was the only data point \
1262
+ available. */ \
1263
+ || (__clang_major__ >= 7 \
1264
+ && __clang_major__ <= 12) /* Clang 3, 5, 13, 14, 15 do not generate the warning. */ \
1265
+ )
1266
+ # define PYBIND11_DETECTED_CLANG_WITH_MISLEADING_CALL_STD_MOVE_EXPLICITLY_WARNING
1267
+ // Example:
1268
+ // tests/test_kwargs_and_defaults.cpp:46:68: error: local variable 'args' will be copied despite
1269
+ // being returned by name [-Werror,-Wreturn-std-move]
1270
+ // m.def("args_function", [](py::args args) -> py::tuple { return args; });
1271
+ // ^~~~
1272
+ // test_kwargs_and_defaults.cpp:46:68: note: call 'std::move' explicitly to avoid copying
1273
+ // m.def("args_function", [](py::args args) -> py::tuple { return args; });
1274
+ // ^~~~
1275
+ // std::move(args)
1276
+ #endif
1277
+
1278
+ // Pybind offers detailed error messages by default for all builts that are debug (through the
1279
+ // negation of NDEBUG). This can also be manually enabled by users, for any builds, through
1280
+ // defining PYBIND11_DETAILED_ERROR_MESSAGES. This information is primarily useful for those
1281
+ // who are writing (as opposed to merely using) libraries that use pybind11.
1282
+ #if !defined(PYBIND11_DETAILED_ERROR_MESSAGES) && !defined(NDEBUG)
1283
+ # define PYBIND11_DETAILED_ERROR_MESSAGES
1284
+ #endif
1285
+
1286
+ PYBIND11_NAMESPACE_END(detail)
1287
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/cpp_conduit.h ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2024 The pybind Community.
2
+
3
+ #pragma once
4
+
5
+ #include <pybind11/pytypes.h>
6
+
7
+ #include "common.h"
8
+ #include "internals.h"
9
+
10
+ #include <typeinfo>
11
+
12
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13
+ PYBIND11_NAMESPACE_BEGIN(detail)
14
+
15
+ // Forward declaration needed here: Refactoring opportunity.
16
+ extern "C" inline PyObject *pybind11_object_new(PyTypeObject *type, PyObject *, PyObject *);
17
+
18
+ inline bool type_is_managed_by_our_internals(PyTypeObject *type_obj) {
19
+ #if defined(PYPY_VERSION)
20
+ auto &internals = get_internals();
21
+ return bool(internals.registered_types_py.find(type_obj)
22
+ != internals.registered_types_py.end());
23
+ #else
24
+ return bool(type_obj->tp_new == pybind11_object_new);
25
+ #endif
26
+ }
27
+
28
+ inline bool is_instance_method_of_type(PyTypeObject *type_obj, PyObject *attr_name) {
29
+ PyObject *descr = _PyType_Lookup(type_obj, attr_name);
30
+ return bool((descr != nullptr) && PyInstanceMethod_Check(descr));
31
+ }
32
+
33
+ inline object try_get_cpp_conduit_method(PyObject *obj) {
34
+ if (PyType_Check(obj)) {
35
+ return object();
36
+ }
37
+ PyTypeObject *type_obj = Py_TYPE(obj);
38
+ str attr_name("_pybind11_conduit_v1_");
39
+ bool assumed_to_be_callable = false;
40
+ if (type_is_managed_by_our_internals(type_obj)) {
41
+ if (!is_instance_method_of_type(type_obj, attr_name.ptr())) {
42
+ return object();
43
+ }
44
+ assumed_to_be_callable = true;
45
+ }
46
+ PyObject *method = PyObject_GetAttr(obj, attr_name.ptr());
47
+ if (method == nullptr) {
48
+ PyErr_Clear();
49
+ return object();
50
+ }
51
+ if (!assumed_to_be_callable && PyCallable_Check(method) == 0) {
52
+ Py_DECREF(method);
53
+ return object();
54
+ }
55
+ return reinterpret_steal<object>(method);
56
+ }
57
+
58
+ inline void *try_raw_pointer_ephemeral_from_cpp_conduit(handle src,
59
+ const std::type_info *cpp_type_info) {
60
+ object method = try_get_cpp_conduit_method(src.ptr());
61
+ if (method) {
62
+ capsule cpp_type_info_capsule(const_cast<void *>(static_cast<const void *>(cpp_type_info)),
63
+ typeid(std::type_info).name());
64
+ object cpp_conduit = method(bytes(PYBIND11_PLATFORM_ABI_ID),
65
+ cpp_type_info_capsule,
66
+ bytes("raw_pointer_ephemeral"));
67
+ if (isinstance<capsule>(cpp_conduit)) {
68
+ return reinterpret_borrow<capsule>(cpp_conduit).get_pointer();
69
+ }
70
+ }
71
+ return nullptr;
72
+ }
73
+
74
+ #define PYBIND11_HAS_CPP_CONDUIT 1
75
+
76
+ PYBIND11_NAMESPACE_END(detail)
77
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/descr.h ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/descr.h: Helper type for concatenating type signatures at compile time
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "common.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+ PYBIND11_NAMESPACE_BEGIN(detail)
16
+
17
+ #if !defined(_MSC_VER)
18
+ # define PYBIND11_DESCR_CONSTEXPR static constexpr
19
+ #else
20
+ # define PYBIND11_DESCR_CONSTEXPR const
21
+ #endif
22
+
23
+ /* Concatenate type signatures at compile time */
24
+ template <size_t N, typename... Ts>
25
+ struct descr {
26
+ char text[N + 1]{'\0'};
27
+
28
+ constexpr descr() = default;
29
+ // NOLINTNEXTLINE(google-explicit-constructor)
30
+ constexpr descr(char const (&s)[N + 1]) : descr(s, make_index_sequence<N>()) {}
31
+
32
+ template <size_t... Is>
33
+ constexpr descr(char const (&s)[N + 1], index_sequence<Is...>) : text{s[Is]..., '\0'} {}
34
+
35
+ template <typename... Chars>
36
+ // NOLINTNEXTLINE(google-explicit-constructor)
37
+ constexpr descr(char c, Chars... cs) : text{c, static_cast<char>(cs)..., '\0'} {}
38
+
39
+ static constexpr std::array<const std::type_info *, sizeof...(Ts) + 1> types() {
40
+ return {{&typeid(Ts)..., nullptr}};
41
+ }
42
+ };
43
+
44
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2, size_t... Is1, size_t... Is2>
45
+ constexpr descr<N1 + N2, Ts1..., Ts2...> plus_impl(const descr<N1, Ts1...> &a,
46
+ const descr<N2, Ts2...> &b,
47
+ index_sequence<Is1...>,
48
+ index_sequence<Is2...>) {
49
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(b);
50
+ return {a.text[Is1]..., b.text[Is2]...};
51
+ }
52
+
53
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
54
+ constexpr descr<N1 + N2, Ts1..., Ts2...> operator+(const descr<N1, Ts1...> &a,
55
+ const descr<N2, Ts2...> &b) {
56
+ return plus_impl(a, b, make_index_sequence<N1>(), make_index_sequence<N2>());
57
+ }
58
+
59
+ template <size_t N>
60
+ constexpr descr<N - 1> const_name(char const (&text)[N]) {
61
+ return descr<N - 1>(text);
62
+ }
63
+ constexpr descr<0> const_name(char const (&)[1]) { return {}; }
64
+
65
+ template <size_t Rem, size_t... Digits>
66
+ struct int_to_str : int_to_str<Rem / 10, Rem % 10, Digits...> {};
67
+ template <size_t... Digits>
68
+ struct int_to_str<0, Digits...> {
69
+ // WARNING: This only works with C++17 or higher.
70
+ static constexpr auto digits = descr<sizeof...(Digits)>(('0' + Digits)...);
71
+ };
72
+
73
+ // Ternary description (like std::conditional)
74
+ template <bool B, size_t N1, size_t N2>
75
+ constexpr enable_if_t<B, descr<N1 - 1>> const_name(char const (&text1)[N1], char const (&)[N2]) {
76
+ return const_name(text1);
77
+ }
78
+ template <bool B, size_t N1, size_t N2>
79
+ constexpr enable_if_t<!B, descr<N2 - 1>> const_name(char const (&)[N1], char const (&text2)[N2]) {
80
+ return const_name(text2);
81
+ }
82
+
83
+ template <bool B, typename T1, typename T2>
84
+ constexpr enable_if_t<B, T1> const_name(const T1 &d, const T2 &) {
85
+ return d;
86
+ }
87
+ template <bool B, typename T1, typename T2>
88
+ constexpr enable_if_t<!B, T2> const_name(const T1 &, const T2 &d) {
89
+ return d;
90
+ }
91
+
92
+ template <size_t Size>
93
+ auto constexpr const_name() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
94
+ return int_to_str<Size / 10, Size % 10>::digits;
95
+ }
96
+
97
+ template <typename Type>
98
+ constexpr descr<1, Type> const_name() {
99
+ return {'%'};
100
+ }
101
+
102
+ // If "_" is defined as a macro, py::detail::_ cannot be provided.
103
+ // It is therefore best to use py::detail::const_name universally.
104
+ // This block is for backward compatibility only.
105
+ // (The const_name code is repeated to avoid introducing a "_" #define ourselves.)
106
+ #ifndef _
107
+ # define PYBIND11_DETAIL_UNDERSCORE_BACKWARD_COMPATIBILITY
108
+ template <size_t N>
109
+ constexpr descr<N - 1> _(char const (&text)[N]) {
110
+ return const_name<N>(text);
111
+ }
112
+ template <bool B, size_t N1, size_t N2>
113
+ constexpr enable_if_t<B, descr<N1 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
114
+ return const_name<B, N1, N2>(text1, text2);
115
+ }
116
+ template <bool B, size_t N1, size_t N2>
117
+ constexpr enable_if_t<!B, descr<N2 - 1>> _(char const (&text1)[N1], char const (&text2)[N2]) {
118
+ return const_name<B, N1, N2>(text1, text2);
119
+ }
120
+ template <bool B, typename T1, typename T2>
121
+ constexpr enable_if_t<B, T1> _(const T1 &d1, const T2 &d2) {
122
+ return const_name<B, T1, T2>(d1, d2);
123
+ }
124
+ template <bool B, typename T1, typename T2>
125
+ constexpr enable_if_t<!B, T2> _(const T1 &d1, const T2 &d2) {
126
+ return const_name<B, T1, T2>(d1, d2);
127
+ }
128
+
129
+ template <size_t Size>
130
+ auto constexpr _() -> remove_cv_t<decltype(int_to_str<Size / 10, Size % 10>::digits)> {
131
+ return const_name<Size>();
132
+ }
133
+ template <typename Type>
134
+ constexpr descr<1, Type> _() {
135
+ return const_name<Type>();
136
+ }
137
+ #endif // #ifndef _
138
+
139
+ constexpr descr<0> concat() { return {}; }
140
+
141
+ template <size_t N, typename... Ts>
142
+ constexpr descr<N, Ts...> concat(const descr<N, Ts...> &descr) {
143
+ return descr;
144
+ }
145
+
146
+ #ifdef __cpp_fold_expressions
147
+ template <size_t N1, size_t N2, typename... Ts1, typename... Ts2>
148
+ constexpr descr<N1 + N2 + 2, Ts1..., Ts2...> operator,(const descr<N1, Ts1...> &a,
149
+ const descr<N2, Ts2...> &b) {
150
+ return a + const_name(", ") + b;
151
+ }
152
+
153
+ template <size_t N, typename... Ts, typename... Args>
154
+ constexpr auto concat(const descr<N, Ts...> &d, const Args &...args) {
155
+ return (d, ..., args);
156
+ }
157
+ #else
158
+ template <size_t N, typename... Ts, typename... Args>
159
+ constexpr auto concat(const descr<N, Ts...> &d,
160
+ const Args &...args) -> decltype(std::declval<descr<N + 2, Ts...>>()
161
+ + concat(args...)) {
162
+ return d + const_name(", ") + concat(args...);
163
+ }
164
+ #endif
165
+
166
+ template <size_t N, typename... Ts>
167
+ constexpr descr<N + 2, Ts...> type_descr(const descr<N, Ts...> &descr) {
168
+ return const_name("{") + descr + const_name("}");
169
+ }
170
+
171
+ PYBIND11_NAMESPACE_END(detail)
172
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/exception_translation.h ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/exception_translation.h: means to translate C++ exceptions to Python exceptions
3
+
4
+ Copyright (c) 2024 The Pybind Development Team.
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "common.h"
13
+ #include "internals.h"
14
+
15
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
16
+ PYBIND11_NAMESPACE_BEGIN(detail)
17
+
18
+ // Apply all the extensions translators from a list
19
+ // Return true if one of the translators completed without raising an exception
20
+ // itself. Return of false indicates that if there are other translators
21
+ // available, they should be tried.
22
+ inline bool apply_exception_translators(std::forward_list<ExceptionTranslator> &translators) {
23
+ auto last_exception = std::current_exception();
24
+
25
+ for (auto &translator : translators) {
26
+ try {
27
+ translator(last_exception);
28
+ return true;
29
+ } catch (...) {
30
+ last_exception = std::current_exception();
31
+ }
32
+ }
33
+ return false;
34
+ }
35
+
36
+ inline void try_translate_exceptions() {
37
+ /* When an exception is caught, give each registered exception
38
+ translator a chance to translate it to a Python exception. First
39
+ all module-local translators will be tried in reverse order of
40
+ registration. If none of the module-locale translators handle
41
+ the exception (or there are no module-locale translators) then
42
+ the global translators will be tried, also in reverse order of
43
+ registration.
44
+
45
+ A translator may choose to do one of the following:
46
+
47
+ - catch the exception and call py::set_error()
48
+ to set a standard (or custom) Python exception, or
49
+ - do nothing and let the exception fall through to the next translator, or
50
+ - delegate translation to the next translator by throwing a new type of exception.
51
+ */
52
+
53
+ bool handled = with_internals([&](internals &internals) {
54
+ auto &local_exception_translators = get_local_internals().registered_exception_translators;
55
+ if (detail::apply_exception_translators(local_exception_translators)) {
56
+ return true;
57
+ }
58
+ auto &exception_translators = internals.registered_exception_translators;
59
+ if (detail::apply_exception_translators(exception_translators)) {
60
+ return true;
61
+ }
62
+ return false;
63
+ });
64
+
65
+ if (!handled) {
66
+ set_error(PyExc_SystemError, "Exception escaped from default exception translator!");
67
+ }
68
+ }
69
+
70
+ PYBIND11_NAMESPACE_END(detail)
71
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/init.h ADDED
@@ -0,0 +1,436 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/init.h: init factory function implementation and support code.
3
+
4
+ Copyright (c) 2017 Jason Rhinelander <jason@imaginary.ca>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "class.h"
13
+
14
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
15
+
16
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
17
+
18
+ PYBIND11_NAMESPACE_BEGIN(detail)
19
+
20
+ template <>
21
+ class type_caster<value_and_holder> {
22
+ public:
23
+ bool load(handle h, bool) {
24
+ value = reinterpret_cast<value_and_holder *>(h.ptr());
25
+ return true;
26
+ }
27
+
28
+ template <typename>
29
+ using cast_op_type = value_and_holder &;
30
+ explicit operator value_and_holder &() { return *value; }
31
+ static constexpr auto name = const_name<value_and_holder>();
32
+
33
+ private:
34
+ value_and_holder *value = nullptr;
35
+ };
36
+
37
+ PYBIND11_NAMESPACE_BEGIN(initimpl)
38
+
39
+ inline void no_nullptr(void *ptr) {
40
+ if (!ptr) {
41
+ throw type_error("pybind11::init(): factory function returned nullptr");
42
+ }
43
+ }
44
+
45
+ // Implementing functions for all forms of py::init<...> and py::init(...)
46
+ template <typename Class>
47
+ using Cpp = typename Class::type;
48
+ template <typename Class>
49
+ using Alias = typename Class::type_alias;
50
+ template <typename Class>
51
+ using Holder = typename Class::holder_type;
52
+
53
+ template <typename Class>
54
+ using is_alias_constructible = std::is_constructible<Alias<Class>, Cpp<Class> &&>;
55
+
56
+ // Takes a Cpp pointer and returns true if it actually is a polymorphic Alias instance.
57
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
58
+ bool is_alias(Cpp<Class> *ptr) {
59
+ return dynamic_cast<Alias<Class> *>(ptr) != nullptr;
60
+ }
61
+ // Failing fallback version of the above for a no-alias class (always returns false)
62
+ template <typename /*Class*/>
63
+ constexpr bool is_alias(void *) {
64
+ return false;
65
+ }
66
+
67
+ // Constructs and returns a new object; if the given arguments don't map to a constructor, we fall
68
+ // back to brace aggregate initialization so that for aggregate initialization can be used with
69
+ // py::init, e.g. `py::init<int, int>` to initialize a `struct T { int a; int b; }`. For
70
+ // non-aggregate types, we need to use an ordinary T(...) constructor (invoking as `T{...}` usually
71
+ // works, but will not do the expected thing when `T` has an `initializer_list<T>` constructor).
72
+ template <typename Class,
73
+ typename... Args,
74
+ detail::enable_if_t<std::is_constructible<Class, Args...>::value, int> = 0>
75
+ inline Class *construct_or_initialize(Args &&...args) {
76
+ return new Class(std::forward<Args>(args)...);
77
+ }
78
+ template <typename Class,
79
+ typename... Args,
80
+ detail::enable_if_t<!std::is_constructible<Class, Args...>::value, int> = 0>
81
+ inline Class *construct_or_initialize(Args &&...args) {
82
+ return new Class{std::forward<Args>(args)...};
83
+ }
84
+
85
+ // Attempts to constructs an alias using a `Alias(Cpp &&)` constructor. This allows types with
86
+ // an alias to provide only a single Cpp factory function as long as the Alias can be
87
+ // constructed from an rvalue reference of the base Cpp type. This means that Alias classes
88
+ // can, when appropriate, simply define a `Alias(Cpp &&)` constructor rather than needing to
89
+ // inherit all the base class constructors.
90
+ template <typename Class>
91
+ void construct_alias_from_cpp(std::true_type /*is_alias_constructible*/,
92
+ value_and_holder &v_h,
93
+ Cpp<Class> &&base) {
94
+ v_h.value_ptr() = new Alias<Class>(std::move(base));
95
+ }
96
+ template <typename Class>
97
+ [[noreturn]] void construct_alias_from_cpp(std::false_type /*!is_alias_constructible*/,
98
+ value_and_holder &,
99
+ Cpp<Class> &&) {
100
+ throw type_error("pybind11::init(): unable to convert returned instance to required "
101
+ "alias class: no `Alias<Class>(Class &&)` constructor available");
102
+ }
103
+
104
+ // Error-generating fallback for factories that don't match one of the below construction
105
+ // mechanisms.
106
+ template <typename Class>
107
+ void construct(...) {
108
+ static_assert(!std::is_same<Class, Class>::value /* always false */,
109
+ "pybind11::init(): init function must return a compatible pointer, "
110
+ "holder, or value");
111
+ }
112
+
113
+ // Pointer return v1: the factory function returns a class pointer for a registered class.
114
+ // If we don't need an alias (because this class doesn't have one, or because the final type is
115
+ // inherited on the Python side) we can simply take over ownership. Otherwise we need to try to
116
+ // construct an Alias from the returned base instance.
117
+ template <typename Class>
118
+ void construct(value_and_holder &v_h, Cpp<Class> *ptr, bool need_alias) {
119
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
120
+ no_nullptr(ptr);
121
+ if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
122
+ // We're going to try to construct an alias by moving the cpp type. Whether or not
123
+ // that succeeds, we still need to destroy the original cpp pointer (either the
124
+ // moved away leftover, if the alias construction works, or the value itself if we
125
+ // throw an error), but we can't just call `delete ptr`: it might have a special
126
+ // deleter, or might be shared_from_this. So we construct a holder around it as if
127
+ // it was a normal instance, then steal the holder away into a local variable; thus
128
+ // the holder and destruction happens when we leave the C++ scope, and the holder
129
+ // class gets to handle the destruction however it likes.
130
+ v_h.value_ptr() = ptr;
131
+ v_h.set_instance_registered(true); // Trick to prevent init_instance from registering it
132
+ // DANGER ZONE BEGIN: exceptions will leave v_h in an invalid state.
133
+ v_h.type->init_instance(v_h.inst, nullptr); // Set up the holder
134
+ Holder<Class> temp_holder(std::move(v_h.holder<Holder<Class>>())); // Steal the holder
135
+ v_h.type->dealloc(v_h); // Destroys the moved-out holder remains, resets value ptr to null
136
+ v_h.set_instance_registered(false);
137
+ // DANGER ZONE END.
138
+
139
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(*ptr));
140
+ } else {
141
+ // Otherwise the type isn't inherited, so we don't need an Alias
142
+ v_h.value_ptr() = ptr;
143
+ }
144
+ }
145
+
146
+ // Pointer return v2: a factory that always returns an alias instance ptr. We simply take over
147
+ // ownership of the pointer.
148
+ template <typename Class, enable_if_t<Class::has_alias, int> = 0>
149
+ void construct(value_and_holder &v_h, Alias<Class> *alias_ptr, bool) {
150
+ no_nullptr(alias_ptr);
151
+ v_h.value_ptr() = static_cast<Cpp<Class> *>(alias_ptr);
152
+ }
153
+
154
+ // Holder return: copy its pointer, and move or copy the returned holder into the new instance's
155
+ // holder. This also handles types like std::shared_ptr<T> and std::unique_ptr<T> where T is a
156
+ // derived type (through those holder's implicit conversion from derived class holder
157
+ // constructors).
158
+ template <typename Class>
159
+ void construct(value_and_holder &v_h, Holder<Class> holder, bool need_alias) {
160
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
161
+ auto *ptr = holder_helper<Holder<Class>>::get(holder);
162
+ no_nullptr(ptr);
163
+ // If we need an alias, check that the held pointer is actually an alias instance
164
+ if (Class::has_alias && need_alias && !is_alias<Class>(ptr)) {
165
+ throw type_error("pybind11::init(): construction failed: returned holder-wrapped instance "
166
+ "is not an alias instance");
167
+ }
168
+
169
+ v_h.value_ptr() = ptr;
170
+ v_h.type->init_instance(v_h.inst, &holder);
171
+ }
172
+
173
+ // return-by-value version 1: returning a cpp class by value. If the class has an alias and an
174
+ // alias is required the alias must have an `Alias(Cpp &&)` constructor so that we can construct
175
+ // the alias from the base when needed (i.e. because of Python-side inheritance). When we don't
176
+ // need it, we simply move-construct the cpp value into a new instance.
177
+ template <typename Class>
178
+ void construct(value_and_holder &v_h, Cpp<Class> &&result, bool need_alias) {
179
+ PYBIND11_WORKAROUND_INCORRECT_MSVC_C4100(need_alias);
180
+ static_assert(is_move_constructible<Cpp<Class>>::value,
181
+ "pybind11::init() return-by-value factory function requires a movable class");
182
+ if (Class::has_alias && need_alias) {
183
+ construct_alias_from_cpp<Class>(is_alias_constructible<Class>{}, v_h, std::move(result));
184
+ } else {
185
+ v_h.value_ptr() = new Cpp<Class>(std::move(result));
186
+ }
187
+ }
188
+
189
+ // return-by-value version 2: returning a value of the alias type itself. We move-construct an
190
+ // Alias instance (even if no the python-side inheritance is involved). The is intended for
191
+ // cases where Alias initialization is always desired.
192
+ template <typename Class>
193
+ void construct(value_and_holder &v_h, Alias<Class> &&result, bool) {
194
+ static_assert(
195
+ is_move_constructible<Alias<Class>>::value,
196
+ "pybind11::init() return-by-alias-value factory function requires a movable alias class");
197
+ v_h.value_ptr() = new Alias<Class>(std::move(result));
198
+ }
199
+
200
+ // Implementing class for py::init<...>()
201
+ template <typename... Args>
202
+ struct constructor {
203
+ template <typename Class, typename... Extra, enable_if_t<!Class::has_alias, int> = 0>
204
+ static void execute(Class &cl, const Extra &...extra) {
205
+ cl.def(
206
+ "__init__",
207
+ [](value_and_holder &v_h, Args... args) {
208
+ v_h.value_ptr() = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
209
+ },
210
+ is_new_style_constructor(),
211
+ extra...);
212
+ }
213
+
214
+ template <
215
+ typename Class,
216
+ typename... Extra,
217
+ enable_if_t<Class::has_alias && std::is_constructible<Cpp<Class>, Args...>::value, int>
218
+ = 0>
219
+ static void execute(Class &cl, const Extra &...extra) {
220
+ cl.def(
221
+ "__init__",
222
+ [](value_and_holder &v_h, Args... args) {
223
+ if (Py_TYPE(v_h.inst) == v_h.type->type) {
224
+ v_h.value_ptr()
225
+ = construct_or_initialize<Cpp<Class>>(std::forward<Args>(args)...);
226
+ } else {
227
+ v_h.value_ptr()
228
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
229
+ }
230
+ },
231
+ is_new_style_constructor(),
232
+ extra...);
233
+ }
234
+
235
+ template <
236
+ typename Class,
237
+ typename... Extra,
238
+ enable_if_t<Class::has_alias && !std::is_constructible<Cpp<Class>, Args...>::value, int>
239
+ = 0>
240
+ static void execute(Class &cl, const Extra &...extra) {
241
+ cl.def(
242
+ "__init__",
243
+ [](value_and_holder &v_h, Args... args) {
244
+ v_h.value_ptr()
245
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
246
+ },
247
+ is_new_style_constructor(),
248
+ extra...);
249
+ }
250
+ };
251
+
252
+ // Implementing class for py::init_alias<...>()
253
+ template <typename... Args>
254
+ struct alias_constructor {
255
+ template <
256
+ typename Class,
257
+ typename... Extra,
258
+ enable_if_t<Class::has_alias && std::is_constructible<Alias<Class>, Args...>::value, int>
259
+ = 0>
260
+ static void execute(Class &cl, const Extra &...extra) {
261
+ cl.def(
262
+ "__init__",
263
+ [](value_and_holder &v_h, Args... args) {
264
+ v_h.value_ptr()
265
+ = construct_or_initialize<Alias<Class>>(std::forward<Args>(args)...);
266
+ },
267
+ is_new_style_constructor(),
268
+ extra...);
269
+ }
270
+ };
271
+
272
+ // Implementation class for py::init(Func) and py::init(Func, AliasFunc)
273
+ template <typename CFunc,
274
+ typename AFunc = void_type (*)(),
275
+ typename = function_signature_t<CFunc>,
276
+ typename = function_signature_t<AFunc>>
277
+ struct factory;
278
+
279
+ // Specialization for py::init(Func)
280
+ template <typename Func, typename Return, typename... Args>
281
+ struct factory<Func, void_type (*)(), Return(Args...)> {
282
+ remove_reference_t<Func> class_factory;
283
+
284
+ // NOLINTNEXTLINE(google-explicit-constructor)
285
+ factory(Func &&f) : class_factory(std::forward<Func>(f)) {}
286
+
287
+ // The given class either has no alias or has no separate alias factory;
288
+ // this always constructs the class itself. If the class is registered with an alias
289
+ // type and an alias instance is needed (i.e. because the final type is a Python class
290
+ // inheriting from the C++ type) the returned value needs to either already be an alias
291
+ // instance, or the alias needs to be constructible from a `Class &&` argument.
292
+ template <typename Class, typename... Extra>
293
+ void execute(Class &cl, const Extra &...extra) && {
294
+ #if defined(PYBIND11_CPP14)
295
+ cl.def(
296
+ "__init__",
297
+ [func = std::move(class_factory)]
298
+ #else
299
+ auto &func = class_factory;
300
+ cl.def(
301
+ "__init__",
302
+ [func]
303
+ #endif
304
+ (value_and_holder &v_h, Args... args) {
305
+ construct<Class>(
306
+ v_h, func(std::forward<Args>(args)...), Py_TYPE(v_h.inst) != v_h.type->type);
307
+ },
308
+ is_new_style_constructor(),
309
+ extra...);
310
+ }
311
+ };
312
+
313
+ // Specialization for py::init(Func, AliasFunc)
314
+ template <typename CFunc,
315
+ typename AFunc,
316
+ typename CReturn,
317
+ typename... CArgs,
318
+ typename AReturn,
319
+ typename... AArgs>
320
+ struct factory<CFunc, AFunc, CReturn(CArgs...), AReturn(AArgs...)> {
321
+ static_assert(sizeof...(CArgs) == sizeof...(AArgs),
322
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
323
+ "must have identical argument signatures");
324
+ static_assert(all_of<std::is_same<CArgs, AArgs>...>::value,
325
+ "pybind11::init(class_factory, alias_factory): class and alias factories "
326
+ "must have identical argument signatures");
327
+
328
+ remove_reference_t<CFunc> class_factory;
329
+ remove_reference_t<AFunc> alias_factory;
330
+
331
+ factory(CFunc &&c, AFunc &&a)
332
+ : class_factory(std::forward<CFunc>(c)), alias_factory(std::forward<AFunc>(a)) {}
333
+
334
+ // The class factory is called when the `self` type passed to `__init__` is the direct
335
+ // class (i.e. not inherited), the alias factory when `self` is a Python-side subtype.
336
+ template <typename Class, typename... Extra>
337
+ void execute(Class &cl, const Extra &...extra) && {
338
+ static_assert(Class::has_alias,
339
+ "The two-argument version of `py::init()` can "
340
+ "only be used if the class has an alias");
341
+ #if defined(PYBIND11_CPP14)
342
+ cl.def(
343
+ "__init__",
344
+ [class_func = std::move(class_factory), alias_func = std::move(alias_factory)]
345
+ #else
346
+ auto &class_func = class_factory;
347
+ auto &alias_func = alias_factory;
348
+ cl.def(
349
+ "__init__",
350
+ [class_func, alias_func]
351
+ #endif
352
+ (value_and_holder &v_h, CArgs... args) {
353
+ if (Py_TYPE(v_h.inst) == v_h.type->type) {
354
+ // If the instance type equals the registered type we don't have inheritance,
355
+ // so don't need the alias and can construct using the class function:
356
+ construct<Class>(v_h, class_func(std::forward<CArgs>(args)...), false);
357
+ } else {
358
+ construct<Class>(v_h, alias_func(std::forward<CArgs>(args)...), true);
359
+ }
360
+ },
361
+ is_new_style_constructor(),
362
+ extra...);
363
+ }
364
+ };
365
+
366
+ /// Set just the C++ state. Same as `__init__`.
367
+ template <typename Class, typename T>
368
+ void setstate(value_and_holder &v_h, T &&result, bool need_alias) {
369
+ construct<Class>(v_h, std::forward<T>(result), need_alias);
370
+ }
371
+
372
+ /// Set both the C++ and Python states
373
+ template <typename Class,
374
+ typename T,
375
+ typename O,
376
+ enable_if_t<std::is_convertible<O, handle>::value, int> = 0>
377
+ void setstate(value_and_holder &v_h, std::pair<T, O> &&result, bool need_alias) {
378
+ construct<Class>(v_h, std::move(result.first), need_alias);
379
+ auto d = handle(result.second);
380
+ if (PyDict_Check(d.ptr()) && PyDict_Size(d.ptr()) == 0) {
381
+ // Skipping setattr below, to not force use of py::dynamic_attr() for Class unnecessarily.
382
+ // See PR #2972 for details.
383
+ return;
384
+ }
385
+ setattr((PyObject *) v_h.inst, "__dict__", d);
386
+ }
387
+
388
+ /// Implementation for py::pickle(GetState, SetState)
389
+ template <typename Get,
390
+ typename Set,
391
+ typename = function_signature_t<Get>,
392
+ typename = function_signature_t<Set>>
393
+ struct pickle_factory;
394
+
395
+ template <typename Get,
396
+ typename Set,
397
+ typename RetState,
398
+ typename Self,
399
+ typename NewInstance,
400
+ typename ArgState>
401
+ struct pickle_factory<Get, Set, RetState(Self), NewInstance(ArgState)> {
402
+ static_assert(std::is_same<intrinsic_t<RetState>, intrinsic_t<ArgState>>::value,
403
+ "The type returned by `__getstate__` must be the same "
404
+ "as the argument accepted by `__setstate__`");
405
+
406
+ remove_reference_t<Get> get;
407
+ remove_reference_t<Set> set;
408
+
409
+ pickle_factory(Get get, Set set) : get(std::forward<Get>(get)), set(std::forward<Set>(set)) {}
410
+
411
+ template <typename Class, typename... Extra>
412
+ void execute(Class &cl, const Extra &...extra) && {
413
+ cl.def("__getstate__", std::move(get));
414
+
415
+ #if defined(PYBIND11_CPP14)
416
+ cl.def(
417
+ "__setstate__",
418
+ [func = std::move(set)]
419
+ #else
420
+ auto &func = set;
421
+ cl.def(
422
+ "__setstate__",
423
+ [func]
424
+ #endif
425
+ (value_and_holder &v_h, ArgState state) {
426
+ setstate<Class>(
427
+ v_h, func(std::forward<ArgState>(state)), Py_TYPE(v_h.inst) != v_h.type->type);
428
+ },
429
+ is_new_style_constructor(),
430
+ extra...);
431
+ }
432
+ };
433
+
434
+ PYBIND11_NAMESPACE_END(initimpl)
435
+ PYBIND11_NAMESPACE_END(detail)
436
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/internals.h ADDED
@@ -0,0 +1,766 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/internals.h: Internal data structure and related functions
3
+
4
+ Copyright (c) 2017 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "common.h"
13
+
14
+ #if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
15
+ # include <pybind11/gil.h>
16
+ #endif
17
+
18
+ #include <pybind11/pytypes.h>
19
+
20
+ #include <exception>
21
+ #include <mutex>
22
+ #include <thread>
23
+
24
+ /// Tracks the `internals` and `type_info` ABI version independent of the main library version.
25
+ ///
26
+ /// Some portions of the code use an ABI that is conditional depending on this
27
+ /// version number. That allows ABI-breaking changes to be "pre-implemented".
28
+ /// Once the default version number is incremented, the conditional logic that
29
+ /// no longer applies can be removed. Additionally, users that need not
30
+ /// maintain ABI compatibility can increase the version number in order to take
31
+ /// advantage of any functionality/efficiency improvements that depend on the
32
+ /// newer ABI.
33
+ ///
34
+ /// WARNING: If you choose to manually increase the ABI version, note that
35
+ /// pybind11 may not be tested as thoroughly with a non-default ABI version, and
36
+ /// further ABI-incompatible changes may be made before the ABI is officially
37
+ /// changed to the new version.
38
+ #ifndef PYBIND11_INTERNALS_VERSION
39
+ # if PY_VERSION_HEX >= 0x030C0000 || defined(_MSC_VER)
40
+ // Version bump for Python 3.12+, before first 3.12 beta release.
41
+ // Version bump for MSVC piggy-backed on PR #4779. See comments there.
42
+ # define PYBIND11_INTERNALS_VERSION 5
43
+ # else
44
+ # define PYBIND11_INTERNALS_VERSION 4
45
+ # endif
46
+ #endif
47
+
48
+ // This requirement is mainly to reduce the support burden (see PR #4570).
49
+ static_assert(PY_VERSION_HEX < 0x030C0000 || PYBIND11_INTERNALS_VERSION >= 5,
50
+ "pybind11 ABI version 5 is the minimum for Python 3.12+");
51
+
52
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
53
+
54
+ using ExceptionTranslator = void (*)(std::exception_ptr);
55
+
56
+ PYBIND11_NAMESPACE_BEGIN(detail)
57
+
58
+ constexpr const char *internals_function_record_capsule_name = "pybind11_function_record_capsule";
59
+
60
+ // Forward declarations
61
+ inline PyTypeObject *make_static_property_type();
62
+ inline PyTypeObject *make_default_metaclass();
63
+ inline PyObject *make_object_base_type(PyTypeObject *metaclass);
64
+
65
+ // The old Python Thread Local Storage (TLS) API is deprecated in Python 3.7 in favor of the new
66
+ // Thread Specific Storage (TSS) API.
67
+ // Avoid unnecessary allocation of `Py_tss_t`, since we cannot use
68
+ // `Py_LIMITED_API` anyway.
69
+ #if PYBIND11_INTERNALS_VERSION > 4
70
+ # define PYBIND11_TLS_KEY_REF Py_tss_t &
71
+ # if defined(__clang__)
72
+ # define PYBIND11_TLS_KEY_INIT(var) \
73
+ _Pragma("clang diagnostic push") /**/ \
74
+ _Pragma("clang diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
75
+ Py_tss_t var \
76
+ = Py_tss_NEEDS_INIT; \
77
+ _Pragma("clang diagnostic pop")
78
+ # elif defined(__GNUC__) && !defined(__INTEL_COMPILER)
79
+ # define PYBIND11_TLS_KEY_INIT(var) \
80
+ _Pragma("GCC diagnostic push") /**/ \
81
+ _Pragma("GCC diagnostic ignored \"-Wmissing-field-initializers\"") /**/ \
82
+ Py_tss_t var \
83
+ = Py_tss_NEEDS_INIT; \
84
+ _Pragma("GCC diagnostic pop")
85
+ # else
86
+ # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t var = Py_tss_NEEDS_INIT;
87
+ # endif
88
+ # define PYBIND11_TLS_KEY_CREATE(var) (PyThread_tss_create(&(var)) == 0)
89
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get(&(key))
90
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set(&(key), (value))
91
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set(&(key), nullptr)
92
+ # define PYBIND11_TLS_FREE(key) PyThread_tss_delete(&(key))
93
+ #else
94
+ # define PYBIND11_TLS_KEY_REF Py_tss_t *
95
+ # define PYBIND11_TLS_KEY_INIT(var) Py_tss_t *var = nullptr;
96
+ # define PYBIND11_TLS_KEY_CREATE(var) \
97
+ (((var) = PyThread_tss_alloc()) != nullptr && (PyThread_tss_create((var)) == 0))
98
+ # define PYBIND11_TLS_GET_VALUE(key) PyThread_tss_get((key))
99
+ # define PYBIND11_TLS_REPLACE_VALUE(key, value) PyThread_tss_set((key), (value))
100
+ # define PYBIND11_TLS_DELETE_VALUE(key) PyThread_tss_set((key), nullptr)
101
+ # define PYBIND11_TLS_FREE(key) PyThread_tss_free(key)
102
+ #endif
103
+
104
+ // Python loads modules by default with dlopen with the RTLD_LOCAL flag; under libc++ and possibly
105
+ // other STLs, this means `typeid(A)` from one module won't equal `typeid(A)` from another module
106
+ // even when `A` is the same, non-hidden-visibility type (e.g. from a common include). Under
107
+ // libstdc++, this doesn't happen: equality and the type_index hash are based on the type name,
108
+ // which works. If not under a known-good stl, provide our own name-based hash and equality
109
+ // functions that use the type name.
110
+ #if (PYBIND11_INTERNALS_VERSION <= 4 && defined(__GLIBCXX__)) \
111
+ || (PYBIND11_INTERNALS_VERSION >= 5 && !defined(_LIBCPP_VERSION))
112
+ inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) { return lhs == rhs; }
113
+ using type_hash = std::hash<std::type_index>;
114
+ using type_equal_to = std::equal_to<std::type_index>;
115
+ #else
116
+ inline bool same_type(const std::type_info &lhs, const std::type_info &rhs) {
117
+ return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
118
+ }
119
+
120
+ struct type_hash {
121
+ size_t operator()(const std::type_index &t) const {
122
+ size_t hash = 5381;
123
+ const char *ptr = t.name();
124
+ while (auto c = static_cast<unsigned char>(*ptr++)) {
125
+ hash = (hash * 33) ^ c;
126
+ }
127
+ return hash;
128
+ }
129
+ };
130
+
131
+ struct type_equal_to {
132
+ bool operator()(const std::type_index &lhs, const std::type_index &rhs) const {
133
+ return lhs.name() == rhs.name() || std::strcmp(lhs.name(), rhs.name()) == 0;
134
+ }
135
+ };
136
+ #endif
137
+
138
+ template <typename value_type>
139
+ using type_map = std::unordered_map<std::type_index, value_type, type_hash, type_equal_to>;
140
+
141
+ struct override_hash {
142
+ inline size_t operator()(const std::pair<const PyObject *, const char *> &v) const {
143
+ size_t value = std::hash<const void *>()(v.first);
144
+ value ^= std::hash<const void *>()(v.second) + 0x9e3779b9 + (value << 6) + (value >> 2);
145
+ return value;
146
+ }
147
+ };
148
+
149
+ using instance_map = std::unordered_multimap<const void *, instance *>;
150
+
151
+ #ifdef Py_GIL_DISABLED
152
+ // Wrapper around PyMutex to provide BasicLockable semantics
153
+ class pymutex {
154
+ PyMutex mutex;
155
+
156
+ public:
157
+ pymutex() : mutex({}) {}
158
+ void lock() { PyMutex_Lock(&mutex); }
159
+ void unlock() { PyMutex_Unlock(&mutex); }
160
+ };
161
+
162
+ // Instance map shards are used to reduce mutex contention in free-threaded Python.
163
+ struct instance_map_shard {
164
+ instance_map registered_instances;
165
+ pymutex mutex;
166
+ // alignas(64) would be better, but causes compile errors in macOS before 10.14 (see #5200)
167
+ char padding[64 - (sizeof(instance_map) + sizeof(pymutex)) % 64];
168
+ };
169
+
170
+ static_assert(sizeof(instance_map_shard) % 64 == 0,
171
+ "instance_map_shard size is not a multiple of 64 bytes");
172
+ #endif
173
+
174
+ /// Internal data structure used to track registered instances and types.
175
+ /// Whenever binary incompatible changes are made to this structure,
176
+ /// `PYBIND11_INTERNALS_VERSION` must be incremented.
177
+ struct internals {
178
+ #ifdef Py_GIL_DISABLED
179
+ pymutex mutex;
180
+ #endif
181
+ // std::type_index -> pybind11's type information
182
+ type_map<type_info *> registered_types_cpp;
183
+ // PyTypeObject* -> base type_info(s)
184
+ std::unordered_map<PyTypeObject *, std::vector<type_info *>> registered_types_py;
185
+ #ifdef Py_GIL_DISABLED
186
+ std::unique_ptr<instance_map_shard[]> instance_shards; // void * -> instance*
187
+ size_t instance_shards_mask;
188
+ #else
189
+ instance_map registered_instances; // void * -> instance*
190
+ #endif
191
+ std::unordered_set<std::pair<const PyObject *, const char *>, override_hash>
192
+ inactive_override_cache;
193
+ type_map<std::vector<bool (*)(PyObject *, void *&)>> direct_conversions;
194
+ std::unordered_map<const PyObject *, std::vector<PyObject *>> patients;
195
+ std::forward_list<ExceptionTranslator> registered_exception_translators;
196
+ std::unordered_map<std::string, void *> shared_data; // Custom data to be shared across
197
+ // extensions
198
+ #if PYBIND11_INTERNALS_VERSION == 4
199
+ std::vector<PyObject *> unused_loader_patient_stack_remove_at_v5;
200
+ #endif
201
+ std::forward_list<std::string> static_strings; // Stores the std::strings backing
202
+ // detail::c_str()
203
+ PyTypeObject *static_property_type;
204
+ PyTypeObject *default_metaclass;
205
+ PyObject *instance_base;
206
+ // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
207
+ PYBIND11_TLS_KEY_INIT(tstate)
208
+ #if PYBIND11_INTERNALS_VERSION > 4
209
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
210
+ #endif // PYBIND11_INTERNALS_VERSION > 4
211
+ // Unused if PYBIND11_SIMPLE_GIL_MANAGEMENT is defined:
212
+ PyInterpreterState *istate = nullptr;
213
+
214
+ #if PYBIND11_INTERNALS_VERSION > 4
215
+ // Note that we have to use a std::string to allocate memory to ensure a unique address
216
+ // We want unique addresses since we use pointer equality to compare function records
217
+ std::string function_record_capsule_name = internals_function_record_capsule_name;
218
+ #endif
219
+
220
+ internals() = default;
221
+ internals(const internals &other) = delete;
222
+ internals &operator=(const internals &other) = delete;
223
+ ~internals() {
224
+ #if PYBIND11_INTERNALS_VERSION > 4
225
+ PYBIND11_TLS_FREE(loader_life_support_tls_key);
226
+ #endif // PYBIND11_INTERNALS_VERSION > 4
227
+
228
+ // This destructor is called *after* Py_Finalize() in finalize_interpreter().
229
+ // That *SHOULD BE* fine. The following details what happens when PyThread_tss_free is
230
+ // called. PYBIND11_TLS_FREE is PyThread_tss_free on python 3.7+. On older python, it does
231
+ // nothing. PyThread_tss_free calls PyThread_tss_delete and PyMem_RawFree.
232
+ // PyThread_tss_delete just calls TlsFree (on Windows) or pthread_key_delete (on *NIX).
233
+ // Neither of those have anything to do with CPython internals. PyMem_RawFree *requires*
234
+ // that the `tstate` be allocated with the CPython allocator.
235
+ PYBIND11_TLS_FREE(tstate);
236
+ }
237
+ };
238
+
239
+ /// Additional type information which does not fit into the PyTypeObject.
240
+ /// Changes to this struct also require bumping `PYBIND11_INTERNALS_VERSION`.
241
+ struct type_info {
242
+ PyTypeObject *type;
243
+ const std::type_info *cpptype;
244
+ size_t type_size, type_align, holder_size_in_ptrs;
245
+ void *(*operator_new)(size_t);
246
+ void (*init_instance)(instance *, const void *);
247
+ void (*dealloc)(value_and_holder &v_h);
248
+ std::vector<PyObject *(*) (PyObject *, PyTypeObject *)> implicit_conversions;
249
+ std::vector<std::pair<const std::type_info *, void *(*) (void *)>> implicit_casts;
250
+ std::vector<bool (*)(PyObject *, void *&)> *direct_conversions;
251
+ buffer_info *(*get_buffer)(PyObject *, void *) = nullptr;
252
+ void *get_buffer_data = nullptr;
253
+ void *(*module_local_load)(PyObject *, const type_info *) = nullptr;
254
+ /* A simple type never occurs as a (direct or indirect) parent
255
+ * of a class that makes use of multiple inheritance.
256
+ * A type can be simple even if it has non-simple ancestors as long as it has no descendants.
257
+ */
258
+ bool simple_type : 1;
259
+ /* True if there is no multiple inheritance in this type's inheritance tree */
260
+ bool simple_ancestors : 1;
261
+ /* for base vs derived holder_type checks */
262
+ bool default_holder : 1;
263
+ /* true if this is a type registered with py::module_local */
264
+ bool module_local : 1;
265
+ };
266
+
267
+ /// On MSVC, debug and release builds are not ABI-compatible!
268
+ #if defined(_MSC_VER) && defined(_DEBUG)
269
+ # define PYBIND11_BUILD_TYPE "_debug"
270
+ #else
271
+ # define PYBIND11_BUILD_TYPE ""
272
+ #endif
273
+
274
+ /// Let's assume that different compilers are ABI-incompatible.
275
+ /// A user can manually set this string if they know their
276
+ /// compiler is compatible.
277
+ #ifndef PYBIND11_COMPILER_TYPE
278
+ # if defined(_MSC_VER)
279
+ # define PYBIND11_COMPILER_TYPE "_msvc"
280
+ # elif defined(__INTEL_COMPILER)
281
+ # define PYBIND11_COMPILER_TYPE "_icc"
282
+ # elif defined(__clang__)
283
+ # define PYBIND11_COMPILER_TYPE "_clang"
284
+ # elif defined(__PGI)
285
+ # define PYBIND11_COMPILER_TYPE "_pgi"
286
+ # elif defined(__MINGW32__)
287
+ # define PYBIND11_COMPILER_TYPE "_mingw"
288
+ # elif defined(__CYGWIN__)
289
+ # define PYBIND11_COMPILER_TYPE "_gcc_cygwin"
290
+ # elif defined(__GNUC__)
291
+ # define PYBIND11_COMPILER_TYPE "_gcc"
292
+ # else
293
+ # define PYBIND11_COMPILER_TYPE "_unknown"
294
+ # endif
295
+ #endif
296
+
297
+ /// Also standard libs
298
+ #ifndef PYBIND11_STDLIB
299
+ # if defined(_LIBCPP_VERSION)
300
+ # define PYBIND11_STDLIB "_libcpp"
301
+ # elif defined(__GLIBCXX__) || defined(__GLIBCPP__)
302
+ # define PYBIND11_STDLIB "_libstdcpp"
303
+ # else
304
+ # define PYBIND11_STDLIB ""
305
+ # endif
306
+ #endif
307
+
308
+ /// On Linux/OSX, changes in __GXX_ABI_VERSION__ indicate ABI incompatibility.
309
+ /// On MSVC, changes in _MSC_VER may indicate ABI incompatibility (#2898).
310
+ #ifndef PYBIND11_BUILD_ABI
311
+ # if defined(__GXX_ABI_VERSION)
312
+ # define PYBIND11_BUILD_ABI "_cxxabi" PYBIND11_TOSTRING(__GXX_ABI_VERSION)
313
+ # elif defined(_MSC_VER)
314
+ # define PYBIND11_BUILD_ABI "_mscver" PYBIND11_TOSTRING(_MSC_VER)
315
+ # else
316
+ # define PYBIND11_BUILD_ABI ""
317
+ # endif
318
+ #endif
319
+
320
+ #ifndef PYBIND11_INTERNALS_KIND
321
+ # define PYBIND11_INTERNALS_KIND ""
322
+ #endif
323
+
324
+ #define PYBIND11_PLATFORM_ABI_ID \
325
+ PYBIND11_INTERNALS_KIND PYBIND11_COMPILER_TYPE PYBIND11_STDLIB PYBIND11_BUILD_ABI \
326
+ PYBIND11_BUILD_TYPE
327
+
328
+ #define PYBIND11_INTERNALS_ID \
329
+ "__pybind11_internals_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
330
+ PYBIND11_PLATFORM_ABI_ID "__"
331
+
332
+ #define PYBIND11_MODULE_LOCAL_ID \
333
+ "__pybind11_module_local_v" PYBIND11_TOSTRING(PYBIND11_INTERNALS_VERSION) \
334
+ PYBIND11_PLATFORM_ABI_ID "__"
335
+
336
+ /// Each module locally stores a pointer to the `internals` data. The data
337
+ /// itself is shared among modules with the same `PYBIND11_INTERNALS_ID`.
338
+ inline internals **&get_internals_pp() {
339
+ static internals **internals_pp = nullptr;
340
+ return internals_pp;
341
+ }
342
+
343
+ // forward decl
344
+ inline void translate_exception(std::exception_ptr);
345
+
346
+ template <class T,
347
+ enable_if_t<std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
348
+ bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
349
+ std::exception_ptr nested = exc.nested_ptr();
350
+ if (nested != nullptr && nested != p) {
351
+ translate_exception(nested);
352
+ return true;
353
+ }
354
+ return false;
355
+ }
356
+
357
+ template <class T,
358
+ enable_if_t<!std::is_same<std::nested_exception, remove_cvref_t<T>>::value, int> = 0>
359
+ bool handle_nested_exception(const T &exc, const std::exception_ptr &p) {
360
+ if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(exc))) {
361
+ return handle_nested_exception(*nep, p);
362
+ }
363
+ return false;
364
+ }
365
+
366
+ inline bool raise_err(PyObject *exc_type, const char *msg) {
367
+ if (PyErr_Occurred()) {
368
+ raise_from(exc_type, msg);
369
+ return true;
370
+ }
371
+ set_error(exc_type, msg);
372
+ return false;
373
+ }
374
+
375
+ inline void translate_exception(std::exception_ptr p) {
376
+ if (!p) {
377
+ return;
378
+ }
379
+ try {
380
+ std::rethrow_exception(p);
381
+ } catch (error_already_set &e) {
382
+ handle_nested_exception(e, p);
383
+ e.restore();
384
+ return;
385
+ } catch (const builtin_exception &e) {
386
+ // Could not use template since it's an abstract class.
387
+ if (const auto *nep = dynamic_cast<const std::nested_exception *>(std::addressof(e))) {
388
+ handle_nested_exception(*nep, p);
389
+ }
390
+ e.set_error();
391
+ return;
392
+ } catch (const std::bad_alloc &e) {
393
+ handle_nested_exception(e, p);
394
+ raise_err(PyExc_MemoryError, e.what());
395
+ return;
396
+ } catch (const std::domain_error &e) {
397
+ handle_nested_exception(e, p);
398
+ raise_err(PyExc_ValueError, e.what());
399
+ return;
400
+ } catch (const std::invalid_argument &e) {
401
+ handle_nested_exception(e, p);
402
+ raise_err(PyExc_ValueError, e.what());
403
+ return;
404
+ } catch (const std::length_error &e) {
405
+ handle_nested_exception(e, p);
406
+ raise_err(PyExc_ValueError, e.what());
407
+ return;
408
+ } catch (const std::out_of_range &e) {
409
+ handle_nested_exception(e, p);
410
+ raise_err(PyExc_IndexError, e.what());
411
+ return;
412
+ } catch (const std::range_error &e) {
413
+ handle_nested_exception(e, p);
414
+ raise_err(PyExc_ValueError, e.what());
415
+ return;
416
+ } catch (const std::overflow_error &e) {
417
+ handle_nested_exception(e, p);
418
+ raise_err(PyExc_OverflowError, e.what());
419
+ return;
420
+ } catch (const std::exception &e) {
421
+ handle_nested_exception(e, p);
422
+ raise_err(PyExc_RuntimeError, e.what());
423
+ return;
424
+ } catch (const std::nested_exception &e) {
425
+ handle_nested_exception(e, p);
426
+ raise_err(PyExc_RuntimeError, "Caught an unknown nested exception!");
427
+ return;
428
+ } catch (...) {
429
+ raise_err(PyExc_RuntimeError, "Caught an unknown exception!");
430
+ return;
431
+ }
432
+ }
433
+
434
+ #if !defined(__GLIBCXX__)
435
+ inline void translate_local_exception(std::exception_ptr p) {
436
+ try {
437
+ if (p) {
438
+ std::rethrow_exception(p);
439
+ }
440
+ } catch (error_already_set &e) {
441
+ e.restore();
442
+ return;
443
+ } catch (const builtin_exception &e) {
444
+ e.set_error();
445
+ return;
446
+ }
447
+ }
448
+ #endif
449
+
450
+ inline object get_python_state_dict() {
451
+ object state_dict;
452
+ #if PYBIND11_INTERNALS_VERSION <= 4 || PY_VERSION_HEX < 0x03080000 || defined(PYPY_VERSION)
453
+ state_dict = reinterpret_borrow<object>(PyEval_GetBuiltins());
454
+ #else
455
+ # if PY_VERSION_HEX < 0x03090000
456
+ PyInterpreterState *istate = _PyInterpreterState_Get();
457
+ # else
458
+ PyInterpreterState *istate = PyInterpreterState_Get();
459
+ # endif
460
+ if (istate) {
461
+ state_dict = reinterpret_borrow<object>(PyInterpreterState_GetDict(istate));
462
+ }
463
+ #endif
464
+ if (!state_dict) {
465
+ raise_from(PyExc_SystemError, "pybind11::detail::get_python_state_dict() FAILED");
466
+ throw error_already_set();
467
+ }
468
+ return state_dict;
469
+ }
470
+
471
+ inline object get_internals_obj_from_state_dict(handle state_dict) {
472
+ return reinterpret_steal<object>(
473
+ dict_getitemstringref(state_dict.ptr(), PYBIND11_INTERNALS_ID));
474
+ }
475
+
476
+ inline internals **get_internals_pp_from_capsule(handle obj) {
477
+ void *raw_ptr = PyCapsule_GetPointer(obj.ptr(), /*name=*/nullptr);
478
+ if (raw_ptr == nullptr) {
479
+ raise_from(PyExc_SystemError, "pybind11::detail::get_internals_pp_from_capsule() FAILED");
480
+ throw error_already_set();
481
+ }
482
+ return static_cast<internals **>(raw_ptr);
483
+ }
484
+
485
+ inline uint64_t round_up_to_next_pow2(uint64_t x) {
486
+ // Round-up to the next power of two.
487
+ // See https://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
488
+ x--;
489
+ x |= (x >> 1);
490
+ x |= (x >> 2);
491
+ x |= (x >> 4);
492
+ x |= (x >> 8);
493
+ x |= (x >> 16);
494
+ x |= (x >> 32);
495
+ x++;
496
+ return x;
497
+ }
498
+
499
+ /// Return a reference to the current `internals` data
500
+ PYBIND11_NOINLINE internals &get_internals() {
501
+ auto **&internals_pp = get_internals_pp();
502
+ if (internals_pp && *internals_pp) {
503
+ return **internals_pp;
504
+ }
505
+
506
+ #if defined(PYBIND11_SIMPLE_GIL_MANAGEMENT)
507
+ gil_scoped_acquire gil;
508
+ #else
509
+ // Ensure that the GIL is held since we will need to make Python calls.
510
+ // Cannot use py::gil_scoped_acquire here since that constructor calls get_internals.
511
+ struct gil_scoped_acquire_local {
512
+ gil_scoped_acquire_local() : state(PyGILState_Ensure()) {}
513
+ gil_scoped_acquire_local(const gil_scoped_acquire_local &) = delete;
514
+ gil_scoped_acquire_local &operator=(const gil_scoped_acquire_local &) = delete;
515
+ ~gil_scoped_acquire_local() { PyGILState_Release(state); }
516
+ const PyGILState_STATE state;
517
+ } gil;
518
+ #endif
519
+ error_scope err_scope;
520
+
521
+ dict state_dict = get_python_state_dict();
522
+ if (object internals_obj = get_internals_obj_from_state_dict(state_dict)) {
523
+ internals_pp = get_internals_pp_from_capsule(internals_obj);
524
+ }
525
+ if (internals_pp && *internals_pp) {
526
+ // We loaded the internals through `state_dict`, which means that our `error_already_set`
527
+ // and `builtin_exception` may be different local classes than the ones set up in the
528
+ // initial exception translator, below, so add another for our local exception classes.
529
+ //
530
+ // libstdc++ doesn't require this (types there are identified only by name)
531
+ // libc++ with CPython doesn't require this (types are explicitly exported)
532
+ // libc++ with PyPy still need it, awaiting further investigation
533
+ #if !defined(__GLIBCXX__)
534
+ (*internals_pp)->registered_exception_translators.push_front(&translate_local_exception);
535
+ #endif
536
+ } else {
537
+ if (!internals_pp) {
538
+ internals_pp = new internals *();
539
+ }
540
+ auto *&internals_ptr = *internals_pp;
541
+ internals_ptr = new internals();
542
+
543
+ PyThreadState *tstate = PyThreadState_Get();
544
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
545
+ if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->tstate)) {
546
+ pybind11_fail("get_internals: could not successfully initialize the tstate TSS key!");
547
+ }
548
+ PYBIND11_TLS_REPLACE_VALUE(internals_ptr->tstate, tstate);
549
+
550
+ #if PYBIND11_INTERNALS_VERSION > 4
551
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
552
+ if (!PYBIND11_TLS_KEY_CREATE(internals_ptr->loader_life_support_tls_key)) {
553
+ pybind11_fail("get_internals: could not successfully initialize the "
554
+ "loader_life_support TSS key!");
555
+ }
556
+ #endif
557
+ internals_ptr->istate = tstate->interp;
558
+ state_dict[PYBIND11_INTERNALS_ID] = capsule(reinterpret_cast<void *>(internals_pp));
559
+ internals_ptr->registered_exception_translators.push_front(&translate_exception);
560
+ internals_ptr->static_property_type = make_static_property_type();
561
+ internals_ptr->default_metaclass = make_default_metaclass();
562
+ internals_ptr->instance_base = make_object_base_type(internals_ptr->default_metaclass);
563
+ #ifdef Py_GIL_DISABLED
564
+ // Scale proportional to the number of cores. 2x is a heuristic to reduce contention.
565
+ auto num_shards
566
+ = static_cast<size_t>(round_up_to_next_pow2(2 * std::thread::hardware_concurrency()));
567
+ if (num_shards == 0) {
568
+ num_shards = 1;
569
+ }
570
+ internals_ptr->instance_shards.reset(new instance_map_shard[num_shards]);
571
+ internals_ptr->instance_shards_mask = num_shards - 1;
572
+ #endif // Py_GIL_DISABLED
573
+ }
574
+ return **internals_pp;
575
+ }
576
+
577
+ // the internals struct (above) is shared between all the modules. local_internals are only
578
+ // for a single module. Any changes made to internals may require an update to
579
+ // PYBIND11_INTERNALS_VERSION, breaking backwards compatibility. local_internals is, by design,
580
+ // restricted to a single module. Whether a module has local internals or not should not
581
+ // impact any other modules, because the only things accessing the local internals is the
582
+ // module that contains them.
583
+ struct local_internals {
584
+ type_map<type_info *> registered_types_cpp;
585
+ std::forward_list<ExceptionTranslator> registered_exception_translators;
586
+ #if PYBIND11_INTERNALS_VERSION == 4
587
+
588
+ // For ABI compatibility, we can't store the loader_life_support TLS key in
589
+ // the `internals` struct directly. Instead, we store it in `shared_data` and
590
+ // cache a copy in `local_internals`. If we allocated a separate TLS key for
591
+ // each instance of `local_internals`, we could end up allocating hundreds of
592
+ // TLS keys if hundreds of different pybind11 modules are loaded (which is a
593
+ // plausible number).
594
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
595
+
596
+ // Holds the shared TLS key for the loader_life_support stack.
597
+ struct shared_loader_life_support_data {
598
+ PYBIND11_TLS_KEY_INIT(loader_life_support_tls_key)
599
+ shared_loader_life_support_data() {
600
+ // NOLINTNEXTLINE(bugprone-assignment-in-if-condition)
601
+ if (!PYBIND11_TLS_KEY_CREATE(loader_life_support_tls_key)) {
602
+ pybind11_fail("local_internals: could not successfully initialize the "
603
+ "loader_life_support TLS key!");
604
+ }
605
+ }
606
+ // We can't help but leak the TLS key, because Python never unloads extension modules.
607
+ };
608
+
609
+ local_internals() {
610
+ auto &internals = get_internals();
611
+ // Get or create the `loader_life_support_stack_key`.
612
+ auto &ptr = internals.shared_data["_life_support"];
613
+ if (!ptr) {
614
+ ptr = new shared_loader_life_support_data;
615
+ }
616
+ loader_life_support_tls_key
617
+ = static_cast<shared_loader_life_support_data *>(ptr)->loader_life_support_tls_key;
618
+ }
619
+ #endif // PYBIND11_INTERNALS_VERSION == 4
620
+ };
621
+
622
+ /// Works like `get_internals`, but for things which are locally registered.
623
+ inline local_internals &get_local_internals() {
624
+ // Current static can be created in the interpreter finalization routine. If the later will be
625
+ // destroyed in another static variable destructor, creation of this static there will cause
626
+ // static deinitialization fiasco. In order to avoid it we avoid destruction of the
627
+ // local_internals static. One can read more about the problem and current solution here:
628
+ // https://google.github.io/styleguide/cppguide.html#Static_and_Global_Variables
629
+ static auto *locals = new local_internals();
630
+ return *locals;
631
+ }
632
+
633
+ #ifdef Py_GIL_DISABLED
634
+ # define PYBIND11_LOCK_INTERNALS(internals) std::unique_lock<pymutex> lock((internals).mutex)
635
+ #else
636
+ # define PYBIND11_LOCK_INTERNALS(internals)
637
+ #endif
638
+
639
+ template <typename F>
640
+ inline auto with_internals(const F &cb) -> decltype(cb(get_internals())) {
641
+ auto &internals = get_internals();
642
+ PYBIND11_LOCK_INTERNALS(internals);
643
+ return cb(internals);
644
+ }
645
+
646
+ inline std::uint64_t mix64(std::uint64_t z) {
647
+ // David Stafford's variant 13 of the MurmurHash3 finalizer popularized
648
+ // by the SplitMix PRNG.
649
+ // https://zimbry.blogspot.com/2011/09/better-bit-mixing-improving-on.html
650
+ z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9;
651
+ z = (z ^ (z >> 27)) * 0x94d049bb133111eb;
652
+ return z ^ (z >> 31);
653
+ }
654
+
655
+ template <typename F>
656
+ inline auto with_instance_map(const void *ptr,
657
+ const F &cb) -> decltype(cb(std::declval<instance_map &>())) {
658
+ auto &internals = get_internals();
659
+
660
+ #ifdef Py_GIL_DISABLED
661
+ // Hash address to compute shard, but ignore low bits. We'd like allocations
662
+ // from the same thread/core to map to the same shard and allocations from
663
+ // other threads/cores to map to other shards. Using the high bits is a good
664
+ // heuristic because memory allocators often have a per-thread
665
+ // arena/superblock/segment from which smaller allocations are served.
666
+ auto addr = reinterpret_cast<std::uintptr_t>(ptr);
667
+ auto hash = mix64(static_cast<std::uint64_t>(addr >> 20));
668
+ auto idx = static_cast<size_t>(hash & internals.instance_shards_mask);
669
+
670
+ auto &shard = internals.instance_shards[idx];
671
+ std::unique_lock<pymutex> lock(shard.mutex);
672
+ return cb(shard.registered_instances);
673
+ #else
674
+ (void) ptr;
675
+ return cb(internals.registered_instances);
676
+ #endif
677
+ }
678
+
679
+ // Returns the number of registered instances for testing purposes. The result may not be
680
+ // consistent if other threads are registering or unregistering instances concurrently.
681
+ inline size_t num_registered_instances() {
682
+ auto &internals = get_internals();
683
+ #ifdef Py_GIL_DISABLED
684
+ size_t count = 0;
685
+ for (size_t i = 0; i <= internals.instance_shards_mask; ++i) {
686
+ auto &shard = internals.instance_shards[i];
687
+ std::unique_lock<pymutex> lock(shard.mutex);
688
+ count += shard.registered_instances.size();
689
+ }
690
+ return count;
691
+ #else
692
+ return internals.registered_instances.size();
693
+ #endif
694
+ }
695
+
696
+ /// Constructs a std::string with the given arguments, stores it in `internals`, and returns its
697
+ /// `c_str()`. Such strings objects have a long storage duration -- the internal strings are only
698
+ /// cleared when the program exits or after interpreter shutdown (when embedding), and so are
699
+ /// suitable for c-style strings needed by Python internals (such as PyTypeObject's tp_name).
700
+ template <typename... Args>
701
+ const char *c_str(Args &&...args) {
702
+ // GCC 4.8 doesn't like parameter unpack within lambda capture, so use
703
+ // PYBIND11_LOCK_INTERNALS.
704
+ auto &internals = get_internals();
705
+ PYBIND11_LOCK_INTERNALS(internals);
706
+ auto &strings = internals.static_strings;
707
+ strings.emplace_front(std::forward<Args>(args)...);
708
+ return strings.front().c_str();
709
+ }
710
+
711
+ inline const char *get_function_record_capsule_name() {
712
+ #if PYBIND11_INTERNALS_VERSION > 4
713
+ return get_internals().function_record_capsule_name.c_str();
714
+ #else
715
+ return nullptr;
716
+ #endif
717
+ }
718
+
719
+ // Determine whether or not the following capsule contains a pybind11 function record.
720
+ // Note that we use `internals` to make sure that only ABI compatible records are touched.
721
+ //
722
+ // This check is currently used in two places:
723
+ // - An important optimization in functional.h to avoid overhead in C++ -> Python -> C++
724
+ // - The sibling feature of cpp_function to allow overloads
725
+ inline bool is_function_record_capsule(const capsule &cap) {
726
+ // Pointer equality as we rely on internals() to ensure unique pointers
727
+ return cap.name() == get_function_record_capsule_name();
728
+ }
729
+
730
+ PYBIND11_NAMESPACE_END(detail)
731
+
732
+ /// Returns a named pointer that is shared among all extension modules (using the same
733
+ /// pybind11 version) running in the current interpreter. Names starting with underscores
734
+ /// are reserved for internal usage. Returns `nullptr` if no matching entry was found.
735
+ PYBIND11_NOINLINE void *get_shared_data(const std::string &name) {
736
+ return detail::with_internals([&](detail::internals &internals) {
737
+ auto it = internals.shared_data.find(name);
738
+ return it != internals.shared_data.end() ? it->second : nullptr;
739
+ });
740
+ }
741
+
742
+ /// Set the shared data that can be later recovered by `get_shared_data()`.
743
+ PYBIND11_NOINLINE void *set_shared_data(const std::string &name, void *data) {
744
+ return detail::with_internals([&](detail::internals &internals) {
745
+ internals.shared_data[name] = data;
746
+ return data;
747
+ });
748
+ }
749
+
750
+ /// Returns a typed reference to a shared data entry (by using `get_shared_data()`) if
751
+ /// such entry exists. Otherwise, a new object of default-constructible type `T` is
752
+ /// added to the shared data under the given name and a reference to it is returned.
753
+ template <typename T>
754
+ T &get_or_create_shared_data(const std::string &name) {
755
+ return *detail::with_internals([&](detail::internals &internals) {
756
+ auto it = internals.shared_data.find(name);
757
+ T *ptr = (T *) (it != internals.shared_data.end() ? it->second : nullptr);
758
+ if (!ptr) {
759
+ ptr = new T();
760
+ internals.shared_data[name] = ptr;
761
+ }
762
+ return ptr;
763
+ });
764
+ }
765
+
766
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/type_caster_base.h ADDED
@@ -0,0 +1,1195 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/type_caster_base.h (originally first part of pybind11/cast.h)
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <pybind11/pytypes.h>
13
+
14
+ #include "common.h"
15
+ #include "cpp_conduit.h"
16
+ #include "descr.h"
17
+ #include "internals.h"
18
+ #include "typeid.h"
19
+ #include "value_and_holder.h"
20
+
21
+ #include <cstdint>
22
+ #include <cstring>
23
+ #include <iterator>
24
+ #include <new>
25
+ #include <stdexcept>
26
+ #include <string>
27
+ #include <type_traits>
28
+ #include <typeindex>
29
+ #include <typeinfo>
30
+ #include <unordered_map>
31
+ #include <utility>
32
+ #include <vector>
33
+
34
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
35
+ PYBIND11_NAMESPACE_BEGIN(detail)
36
+
37
+ /// A life support system for temporary objects created by `type_caster::load()`.
38
+ /// Adding a patient will keep it alive up until the enclosing function returns.
39
+ class loader_life_support {
40
+ private:
41
+ loader_life_support *parent = nullptr;
42
+ std::unordered_set<PyObject *> keep_alive;
43
+
44
+ // Store stack pointer in thread-local storage.
45
+ static PYBIND11_TLS_KEY_REF get_stack_tls_key() {
46
+ #if PYBIND11_INTERNALS_VERSION == 4
47
+ return get_local_internals().loader_life_support_tls_key;
48
+ #else
49
+ return get_internals().loader_life_support_tls_key;
50
+ #endif
51
+ }
52
+ static loader_life_support *get_stack_top() {
53
+ return static_cast<loader_life_support *>(PYBIND11_TLS_GET_VALUE(get_stack_tls_key()));
54
+ }
55
+ static void set_stack_top(loader_life_support *value) {
56
+ PYBIND11_TLS_REPLACE_VALUE(get_stack_tls_key(), value);
57
+ }
58
+
59
+ public:
60
+ /// A new patient frame is created when a function is entered
61
+ loader_life_support() : parent{get_stack_top()} { set_stack_top(this); }
62
+
63
+ /// ... and destroyed after it returns
64
+ ~loader_life_support() {
65
+ if (get_stack_top() != this) {
66
+ pybind11_fail("loader_life_support: internal error");
67
+ }
68
+ set_stack_top(parent);
69
+ for (auto *item : keep_alive) {
70
+ Py_DECREF(item);
71
+ }
72
+ }
73
+
74
+ /// This can only be used inside a pybind11-bound function, either by `argument_loader`
75
+ /// at argument preparation time or by `py::cast()` at execution time.
76
+ PYBIND11_NOINLINE static void add_patient(handle h) {
77
+ loader_life_support *frame = get_stack_top();
78
+ if (!frame) {
79
+ // NOTE: It would be nice to include the stack frames here, as this indicates
80
+ // use of pybind11::cast<> outside the normal call framework, finding such
81
+ // a location is challenging. Developers could consider printing out
82
+ // stack frame addresses here using something like __builtin_frame_address(0)
83
+ throw cast_error("When called outside a bound function, py::cast() cannot "
84
+ "do Python -> C++ conversions which require the creation "
85
+ "of temporary values");
86
+ }
87
+
88
+ if (frame->keep_alive.insert(h.ptr()).second) {
89
+ Py_INCREF(h.ptr());
90
+ }
91
+ }
92
+ };
93
+
94
+ // Gets the cache entry for the given type, creating it if necessary. The return value is the pair
95
+ // returned by emplace, i.e. an iterator for the entry and a bool set to `true` if the entry was
96
+ // just created.
97
+ inline std::pair<decltype(internals::registered_types_py)::iterator, bool>
98
+ all_type_info_get_cache(PyTypeObject *type);
99
+
100
+ // Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.
101
+ inline void all_type_info_add_base_most_derived_first(std::vector<type_info *> &bases,
102
+ type_info *addl_base) {
103
+ for (auto it = bases.begin(); it != bases.end(); it++) {
104
+ type_info *existing_base = *it;
105
+ if (PyType_IsSubtype(addl_base->type, existing_base->type) != 0) {
106
+ bases.insert(it, addl_base);
107
+ return;
108
+ }
109
+ }
110
+ bases.push_back(addl_base);
111
+ }
112
+
113
+ // Populates a just-created cache entry.
114
+ PYBIND11_NOINLINE void all_type_info_populate(PyTypeObject *t, std::vector<type_info *> &bases) {
115
+ assert(bases.empty());
116
+ std::vector<PyTypeObject *> check;
117
+ for (handle parent : reinterpret_borrow<tuple>(t->tp_bases)) {
118
+ check.push_back((PyTypeObject *) parent.ptr());
119
+ }
120
+
121
+ auto const &type_dict = get_internals().registered_types_py;
122
+ for (size_t i = 0; i < check.size(); i++) {
123
+ auto *type = check[i];
124
+ // Ignore Python2 old-style class super type:
125
+ if (!PyType_Check((PyObject *) type)) {
126
+ continue;
127
+ }
128
+
129
+ // Check `type` in the current set of registered python types:
130
+ auto it = type_dict.find(type);
131
+ if (it != type_dict.end()) {
132
+ // We found a cache entry for it, so it's either pybind-registered or has pre-computed
133
+ // pybind bases, but we have to make sure we haven't already seen the type(s) before:
134
+ // we want to follow Python/virtual C++ rules that there should only be one instance of
135
+ // a common base.
136
+ for (auto *tinfo : it->second) {
137
+ // NB: Could use a second set here, rather than doing a linear search, but since
138
+ // having a large number of immediate pybind11-registered types seems fairly
139
+ // unlikely, that probably isn't worthwhile.
140
+ bool found = false;
141
+ for (auto *known : bases) {
142
+ if (known == tinfo) {
143
+ found = true;
144
+ break;
145
+ }
146
+ }
147
+ if (!found) {
148
+ all_type_info_add_base_most_derived_first(bases, tinfo);
149
+ }
150
+ }
151
+ } else if (type->tp_bases) {
152
+ // It's some python type, so keep follow its bases classes to look for one or more
153
+ // registered types
154
+ if (i + 1 == check.size()) {
155
+ // When we're at the end, we can pop off the current element to avoid growing
156
+ // `check` when adding just one base (which is typical--i.e. when there is no
157
+ // multiple inheritance)
158
+ check.pop_back();
159
+ i--;
160
+ }
161
+ for (handle parent : reinterpret_borrow<tuple>(type->tp_bases)) {
162
+ check.push_back((PyTypeObject *) parent.ptr());
163
+ }
164
+ }
165
+ }
166
+ }
167
+
168
+ /**
169
+ * Extracts vector of type_info pointers of pybind-registered roots of the given Python type. Will
170
+ * be just 1 pybind type for the Python type of a pybind-registered class, or for any Python-side
171
+ * derived class that uses single inheritance. Will contain as many types as required for a Python
172
+ * class that uses multiple inheritance to inherit (directly or indirectly) from multiple
173
+ * pybind-registered classes. Will be empty if neither the type nor any base classes are
174
+ * pybind-registered.
175
+ *
176
+ * The value is cached for the lifetime of the Python type.
177
+ */
178
+ inline const std::vector<detail::type_info *> &all_type_info(PyTypeObject *type) {
179
+ auto ins = all_type_info_get_cache(type);
180
+ if (ins.second) {
181
+ // New cache entry: populate it
182
+ all_type_info_populate(type, ins.first->second);
183
+ }
184
+
185
+ return ins.first->second;
186
+ }
187
+
188
+ /**
189
+ * Gets a single pybind11 type info for a python type. Returns nullptr if neither the type nor any
190
+ * ancestors are pybind11-registered. Throws an exception if there are multiple bases--use
191
+ * `all_type_info` instead if you want to support multiple bases.
192
+ */
193
+ PYBIND11_NOINLINE detail::type_info *get_type_info(PyTypeObject *type) {
194
+ const auto &bases = all_type_info(type);
195
+ if (bases.empty()) {
196
+ return nullptr;
197
+ }
198
+ if (bases.size() > 1) {
199
+ pybind11_fail(
200
+ "pybind11::detail::get_type_info: type has multiple pybind11-registered bases");
201
+ }
202
+ return bases.front();
203
+ }
204
+
205
+ inline detail::type_info *get_local_type_info(const std::type_index &tp) {
206
+ auto &locals = get_local_internals().registered_types_cpp;
207
+ auto it = locals.find(tp);
208
+ if (it != locals.end()) {
209
+ return it->second;
210
+ }
211
+ return nullptr;
212
+ }
213
+
214
+ inline detail::type_info *get_global_type_info(const std::type_index &tp) {
215
+ return with_internals([&](internals &internals) {
216
+ detail::type_info *type_info = nullptr;
217
+ auto &types = internals.registered_types_cpp;
218
+ auto it = types.find(tp);
219
+ if (it != types.end()) {
220
+ type_info = it->second;
221
+ }
222
+ return type_info;
223
+ });
224
+ }
225
+
226
+ /// Return the type info for a given C++ type; on lookup failure can either throw or return
227
+ /// nullptr.
228
+ PYBIND11_NOINLINE detail::type_info *get_type_info(const std::type_index &tp,
229
+ bool throw_if_missing = false) {
230
+ if (auto *ltype = get_local_type_info(tp)) {
231
+ return ltype;
232
+ }
233
+ if (auto *gtype = get_global_type_info(tp)) {
234
+ return gtype;
235
+ }
236
+
237
+ if (throw_if_missing) {
238
+ std::string tname = tp.name();
239
+ detail::clean_type_id(tname);
240
+ pybind11_fail("pybind11::detail::get_type_info: unable to find type info for \""
241
+ + std::move(tname) + '"');
242
+ }
243
+ return nullptr;
244
+ }
245
+
246
+ PYBIND11_NOINLINE handle get_type_handle(const std::type_info &tp, bool throw_if_missing) {
247
+ detail::type_info *type_info = get_type_info(tp, throw_if_missing);
248
+ return handle(type_info ? ((PyObject *) type_info->type) : nullptr);
249
+ }
250
+
251
+ // Searches the inheritance graph for a registered Python instance, using all_type_info().
252
+ PYBIND11_NOINLINE handle find_registered_python_instance(void *src,
253
+ const detail::type_info *tinfo) {
254
+ return with_instance_map(src, [&](instance_map &instances) {
255
+ auto it_instances = instances.equal_range(src);
256
+ for (auto it_i = it_instances.first; it_i != it_instances.second; ++it_i) {
257
+ for (auto *instance_type : detail::all_type_info(Py_TYPE(it_i->second))) {
258
+ if (instance_type && same_type(*instance_type->cpptype, *tinfo->cpptype)) {
259
+ return handle((PyObject *) it_i->second).inc_ref();
260
+ }
261
+ }
262
+ }
263
+ return handle();
264
+ });
265
+ }
266
+
267
+ // Container for accessing and iterating over an instance's values/holders
268
+ struct values_and_holders {
269
+ private:
270
+ instance *inst;
271
+ using type_vec = std::vector<detail::type_info *>;
272
+ const type_vec &tinfo;
273
+
274
+ public:
275
+ explicit values_and_holders(instance *inst)
276
+ : inst{inst}, tinfo(all_type_info(Py_TYPE(inst))) {}
277
+
278
+ explicit values_and_holders(PyObject *obj)
279
+ : inst{nullptr}, tinfo(all_type_info(Py_TYPE(obj))) {
280
+ if (!tinfo.empty()) {
281
+ inst = reinterpret_cast<instance *>(obj);
282
+ }
283
+ }
284
+
285
+ struct iterator {
286
+ private:
287
+ instance *inst = nullptr;
288
+ const type_vec *types = nullptr;
289
+ value_and_holder curr;
290
+ friend struct values_and_holders;
291
+ iterator(instance *inst, const type_vec *tinfo) : inst{inst}, types{tinfo} {
292
+ if (inst != nullptr) {
293
+ assert(!types->empty());
294
+ curr = value_and_holder(
295
+ inst /* instance */,
296
+ (*types)[0] /* type info */,
297
+ 0, /* vpos: (non-simple types only): the first vptr comes first */
298
+ 0 /* index */);
299
+ }
300
+ }
301
+ // Past-the-end iterator:
302
+ explicit iterator(size_t end) : curr(end) {}
303
+
304
+ public:
305
+ bool operator==(const iterator &other) const { return curr.index == other.curr.index; }
306
+ bool operator!=(const iterator &other) const { return curr.index != other.curr.index; }
307
+ iterator &operator++() {
308
+ if (!inst->simple_layout) {
309
+ curr.vh += 1 + (*types)[curr.index]->holder_size_in_ptrs;
310
+ }
311
+ ++curr.index;
312
+ curr.type = curr.index < types->size() ? (*types)[curr.index] : nullptr;
313
+ return *this;
314
+ }
315
+ value_and_holder &operator*() { return curr; }
316
+ value_and_holder *operator->() { return &curr; }
317
+ };
318
+
319
+ iterator begin() { return iterator(inst, &tinfo); }
320
+ iterator end() { return iterator(tinfo.size()); }
321
+
322
+ iterator find(const type_info *find_type) {
323
+ auto it = begin(), endit = end();
324
+ while (it != endit && it->type != find_type) {
325
+ ++it;
326
+ }
327
+ return it;
328
+ }
329
+
330
+ size_t size() { return tinfo.size(); }
331
+
332
+ // Band-aid workaround to fix a subtle but serious bug in a minimalistic fashion. See PR #4762.
333
+ bool is_redundant_value_and_holder(const value_and_holder &vh) {
334
+ for (size_t i = 0; i < vh.index; i++) {
335
+ if (PyType_IsSubtype(tinfo[i]->type, tinfo[vh.index]->type) != 0) {
336
+ return true;
337
+ }
338
+ }
339
+ return false;
340
+ }
341
+ };
342
+
343
+ /**
344
+ * Extracts C++ value and holder pointer references from an instance (which may contain multiple
345
+ * values/holders for python-side multiple inheritance) that match the given type. Throws an error
346
+ * if the given type (or ValueType, if omitted) is not a pybind11 base of the given instance. If
347
+ * `find_type` is omitted (or explicitly specified as nullptr) the first value/holder are returned,
348
+ * regardless of type (and the resulting .type will be nullptr).
349
+ *
350
+ * The returned object should be short-lived: in particular, it must not outlive the called-upon
351
+ * instance.
352
+ */
353
+ PYBIND11_NOINLINE value_and_holder
354
+ instance::get_value_and_holder(const type_info *find_type /*= nullptr default in common.h*/,
355
+ bool throw_if_missing /*= true in common.h*/) {
356
+ // Optimize common case:
357
+ if (!find_type || Py_TYPE(this) == find_type->type) {
358
+ return value_and_holder(this, find_type, 0, 0);
359
+ }
360
+
361
+ detail::values_and_holders vhs(this);
362
+ auto it = vhs.find(find_type);
363
+ if (it != vhs.end()) {
364
+ return *it;
365
+ }
366
+
367
+ if (!throw_if_missing) {
368
+ return value_and_holder();
369
+ }
370
+
371
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
372
+ pybind11_fail("pybind11::detail::instance::get_value_and_holder: `"
373
+ + get_fully_qualified_tp_name(find_type->type)
374
+ + "' is not a pybind11 base of the given `"
375
+ + get_fully_qualified_tp_name(Py_TYPE(this)) + "' instance");
376
+ #else
377
+ pybind11_fail(
378
+ "pybind11::detail::instance::get_value_and_holder: "
379
+ "type is not a pybind11 base of the given instance "
380
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in debug mode for type details)");
381
+ #endif
382
+ }
383
+
384
+ PYBIND11_NOINLINE void instance::allocate_layout() {
385
+ const auto &tinfo = all_type_info(Py_TYPE(this));
386
+
387
+ const size_t n_types = tinfo.size();
388
+
389
+ if (n_types == 0) {
390
+ pybind11_fail(
391
+ "instance allocation failed: new instance has no pybind11-registered base types");
392
+ }
393
+
394
+ simple_layout
395
+ = n_types == 1 && tinfo.front()->holder_size_in_ptrs <= instance_simple_holder_in_ptrs();
396
+
397
+ // Simple path: no python-side multiple inheritance, and a small-enough holder
398
+ if (simple_layout) {
399
+ simple_value_holder[0] = nullptr;
400
+ simple_holder_constructed = false;
401
+ simple_instance_registered = false;
402
+ } else { // multiple base types or a too-large holder
403
+ // Allocate space to hold: [v1*][h1][v2*][h2]...[bb...] where [vN*] is a value pointer,
404
+ // [hN] is the (uninitialized) holder instance for value N, and [bb...] is a set of bool
405
+ // values that tracks whether each associated holder has been initialized. Each [block] is
406
+ // padded, if necessary, to an integer multiple of sizeof(void *).
407
+ size_t space = 0;
408
+ for (auto *t : tinfo) {
409
+ space += 1; // value pointer
410
+ space += t->holder_size_in_ptrs; // holder instance
411
+ }
412
+ size_t flags_at = space;
413
+ space += size_in_ptrs(n_types); // status bytes (holder_constructed and
414
+ // instance_registered)
415
+
416
+ // Allocate space for flags, values, and holders, and initialize it to 0 (flags and values,
417
+ // in particular, need to be 0). Use Python's memory allocation
418
+ // functions: Python is using pymalloc, which is designed to be
419
+ // efficient for small allocations like the one we're doing here;
420
+ // for larger allocations they are just wrappers around malloc.
421
+ // TODO: is this still true for pure Python 3.6?
422
+ nonsimple.values_and_holders = (void **) PyMem_Calloc(space, sizeof(void *));
423
+ if (!nonsimple.values_and_holders) {
424
+ throw std::bad_alloc();
425
+ }
426
+ nonsimple.status
427
+ = reinterpret_cast<std::uint8_t *>(&nonsimple.values_and_holders[flags_at]);
428
+ }
429
+ owned = true;
430
+ }
431
+
432
+ // NOLINTNEXTLINE(readability-make-member-function-const)
433
+ PYBIND11_NOINLINE void instance::deallocate_layout() {
434
+ if (!simple_layout) {
435
+ PyMem_Free(reinterpret_cast<void *>(nonsimple.values_and_holders));
436
+ }
437
+ }
438
+
439
+ PYBIND11_NOINLINE bool isinstance_generic(handle obj, const std::type_info &tp) {
440
+ handle type = detail::get_type_handle(tp, false);
441
+ if (!type) {
442
+ return false;
443
+ }
444
+ return isinstance(obj, type);
445
+ }
446
+
447
+ PYBIND11_NOINLINE handle get_object_handle(const void *ptr, const detail::type_info *type) {
448
+ return with_instance_map(ptr, [&](instance_map &instances) {
449
+ auto range = instances.equal_range(ptr);
450
+ for (auto it = range.first; it != range.second; ++it) {
451
+ for (const auto &vh : values_and_holders(it->second)) {
452
+ if (vh.type == type) {
453
+ return handle((PyObject *) it->second);
454
+ }
455
+ }
456
+ }
457
+ return handle();
458
+ });
459
+ }
460
+
461
+ inline PyThreadState *get_thread_state_unchecked() {
462
+ #if defined(PYPY_VERSION)
463
+ return PyThreadState_GET();
464
+ #elif PY_VERSION_HEX < 0x030D0000
465
+ return _PyThreadState_UncheckedGet();
466
+ #else
467
+ return PyThreadState_GetUnchecked();
468
+ #endif
469
+ }
470
+
471
+ // Forward declarations
472
+ void keep_alive_impl(handle nurse, handle patient);
473
+ inline PyObject *make_new_instance(PyTypeObject *type);
474
+
475
+ class type_caster_generic {
476
+ public:
477
+ PYBIND11_NOINLINE explicit type_caster_generic(const std::type_info &type_info)
478
+ : typeinfo(get_type_info(type_info)), cpptype(&type_info) {}
479
+
480
+ explicit type_caster_generic(const type_info *typeinfo)
481
+ : typeinfo(typeinfo), cpptype(typeinfo ? typeinfo->cpptype : nullptr) {}
482
+
483
+ bool load(handle src, bool convert) { return load_impl<type_caster_generic>(src, convert); }
484
+
485
+ PYBIND11_NOINLINE static handle cast(const void *_src,
486
+ return_value_policy policy,
487
+ handle parent,
488
+ const detail::type_info *tinfo,
489
+ void *(*copy_constructor)(const void *),
490
+ void *(*move_constructor)(const void *),
491
+ const void *existing_holder = nullptr) {
492
+ if (!tinfo) { // no type info: error will be set already
493
+ return handle();
494
+ }
495
+
496
+ void *src = const_cast<void *>(_src);
497
+ if (src == nullptr) {
498
+ return none().release();
499
+ }
500
+
501
+ if (handle registered_inst = find_registered_python_instance(src, tinfo)) {
502
+ return registered_inst;
503
+ }
504
+
505
+ auto inst = reinterpret_steal<object>(make_new_instance(tinfo->type));
506
+ auto *wrapper = reinterpret_cast<instance *>(inst.ptr());
507
+ wrapper->owned = false;
508
+ void *&valueptr = values_and_holders(wrapper).begin()->value_ptr();
509
+
510
+ switch (policy) {
511
+ case return_value_policy::automatic:
512
+ case return_value_policy::take_ownership:
513
+ valueptr = src;
514
+ wrapper->owned = true;
515
+ break;
516
+
517
+ case return_value_policy::automatic_reference:
518
+ case return_value_policy::reference:
519
+ valueptr = src;
520
+ wrapper->owned = false;
521
+ break;
522
+
523
+ case return_value_policy::copy:
524
+ if (copy_constructor) {
525
+ valueptr = copy_constructor(src);
526
+ } else {
527
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
528
+ std::string type_name(tinfo->cpptype->name());
529
+ detail::clean_type_id(type_name);
530
+ throw cast_error("return_value_policy = copy, but type " + type_name
531
+ + " is non-copyable!");
532
+ #else
533
+ throw cast_error("return_value_policy = copy, but type is "
534
+ "non-copyable! (#define PYBIND11_DETAILED_ERROR_MESSAGES or "
535
+ "compile in debug mode for details)");
536
+ #endif
537
+ }
538
+ wrapper->owned = true;
539
+ break;
540
+
541
+ case return_value_policy::move:
542
+ if (move_constructor) {
543
+ valueptr = move_constructor(src);
544
+ } else if (copy_constructor) {
545
+ valueptr = copy_constructor(src);
546
+ } else {
547
+ #if defined(PYBIND11_DETAILED_ERROR_MESSAGES)
548
+ std::string type_name(tinfo->cpptype->name());
549
+ detail::clean_type_id(type_name);
550
+ throw cast_error("return_value_policy = move, but type " + type_name
551
+ + " is neither movable nor copyable!");
552
+ #else
553
+ throw cast_error("return_value_policy = move, but type is neither "
554
+ "movable nor copyable! "
555
+ "(#define PYBIND11_DETAILED_ERROR_MESSAGES or compile in "
556
+ "debug mode for details)");
557
+ #endif
558
+ }
559
+ wrapper->owned = true;
560
+ break;
561
+
562
+ case return_value_policy::reference_internal:
563
+ valueptr = src;
564
+ wrapper->owned = false;
565
+ keep_alive_impl(inst, parent);
566
+ break;
567
+
568
+ default:
569
+ throw cast_error("unhandled return_value_policy: should not happen!");
570
+ }
571
+
572
+ tinfo->init_instance(wrapper, existing_holder);
573
+
574
+ return inst.release();
575
+ }
576
+
577
+ // Base methods for generic caster; there are overridden in copyable_holder_caster
578
+ void load_value(value_and_holder &&v_h) {
579
+ auto *&vptr = v_h.value_ptr();
580
+ // Lazy allocation for unallocated values:
581
+ if (vptr == nullptr) {
582
+ const auto *type = v_h.type ? v_h.type : typeinfo;
583
+ if (type->operator_new) {
584
+ vptr = type->operator_new(type->type_size);
585
+ } else {
586
+ #if defined(__cpp_aligned_new) && (!defined(_MSC_VER) || _MSC_VER >= 1912)
587
+ if (type->type_align > __STDCPP_DEFAULT_NEW_ALIGNMENT__) {
588
+ vptr = ::operator new(type->type_size, std::align_val_t(type->type_align));
589
+ } else {
590
+ vptr = ::operator new(type->type_size);
591
+ }
592
+ #else
593
+ vptr = ::operator new(type->type_size);
594
+ #endif
595
+ }
596
+ }
597
+ value = vptr;
598
+ }
599
+ bool try_implicit_casts(handle src, bool convert) {
600
+ for (const auto &cast : typeinfo->implicit_casts) {
601
+ type_caster_generic sub_caster(*cast.first);
602
+ if (sub_caster.load(src, convert)) {
603
+ value = cast.second(sub_caster.value);
604
+ return true;
605
+ }
606
+ }
607
+ return false;
608
+ }
609
+ bool try_direct_conversions(handle src) {
610
+ for (auto &converter : *typeinfo->direct_conversions) {
611
+ if (converter(src.ptr(), value)) {
612
+ return true;
613
+ }
614
+ }
615
+ return false;
616
+ }
617
+ bool try_cpp_conduit(handle src) {
618
+ value = try_raw_pointer_ephemeral_from_cpp_conduit(src, cpptype);
619
+ if (value != nullptr) {
620
+ return true;
621
+ }
622
+ return false;
623
+ }
624
+ void check_holder_compat() {}
625
+
626
+ PYBIND11_NOINLINE static void *local_load(PyObject *src, const type_info *ti) {
627
+ auto caster = type_caster_generic(ti);
628
+ if (caster.load(src, false)) {
629
+ return caster.value;
630
+ }
631
+ return nullptr;
632
+ }
633
+
634
+ /// Try to load with foreign typeinfo, if available. Used when there is no
635
+ /// native typeinfo, or when the native one wasn't able to produce a value.
636
+ PYBIND11_NOINLINE bool try_load_foreign_module_local(handle src) {
637
+ constexpr auto *local_key = PYBIND11_MODULE_LOCAL_ID;
638
+ const auto pytype = type::handle_of(src);
639
+ if (!hasattr(pytype, local_key)) {
640
+ return false;
641
+ }
642
+
643
+ type_info *foreign_typeinfo = reinterpret_borrow<capsule>(getattr(pytype, local_key));
644
+ // Only consider this foreign loader if actually foreign and is a loader of the correct cpp
645
+ // type
646
+ if (foreign_typeinfo->module_local_load == &local_load
647
+ || (cpptype && !same_type(*cpptype, *foreign_typeinfo->cpptype))) {
648
+ return false;
649
+ }
650
+
651
+ if (auto *result = foreign_typeinfo->module_local_load(src.ptr(), foreign_typeinfo)) {
652
+ value = result;
653
+ return true;
654
+ }
655
+ return false;
656
+ }
657
+
658
+ // Implementation of `load`; this takes the type of `this` so that it can dispatch the relevant
659
+ // bits of code between here and copyable_holder_caster where the two classes need different
660
+ // logic (without having to resort to virtual inheritance).
661
+ template <typename ThisT>
662
+ PYBIND11_NOINLINE bool load_impl(handle src, bool convert) {
663
+ if (!src) {
664
+ return false;
665
+ }
666
+ if (!typeinfo) {
667
+ return try_load_foreign_module_local(src);
668
+ }
669
+
670
+ auto &this_ = static_cast<ThisT &>(*this);
671
+ this_.check_holder_compat();
672
+
673
+ PyTypeObject *srctype = Py_TYPE(src.ptr());
674
+
675
+ // Case 1: If src is an exact type match for the target type then we can reinterpret_cast
676
+ // the instance's value pointer to the target type:
677
+ if (srctype == typeinfo->type) {
678
+ this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
679
+ return true;
680
+ }
681
+ // Case 2: We have a derived class
682
+ if (PyType_IsSubtype(srctype, typeinfo->type)) {
683
+ const auto &bases = all_type_info(srctype);
684
+ bool no_cpp_mi = typeinfo->simple_type;
685
+
686
+ // Case 2a: the python type is a Python-inherited derived class that inherits from just
687
+ // one simple (no MI) pybind11 class, or is an exact match, so the C++ instance is of
688
+ // the right type and we can use reinterpret_cast.
689
+ // (This is essentially the same as case 2b, but because not using multiple inheritance
690
+ // is extremely common, we handle it specially to avoid the loop iterator and type
691
+ // pointer lookup overhead)
692
+ if (bases.size() == 1 && (no_cpp_mi || bases.front()->type == typeinfo->type)) {
693
+ this_.load_value(reinterpret_cast<instance *>(src.ptr())->get_value_and_holder());
694
+ return true;
695
+ }
696
+ // Case 2b: the python type inherits from multiple C++ bases. Check the bases to see
697
+ // if we can find an exact match (or, for a simple C++ type, an inherited match); if
698
+ // so, we can safely reinterpret_cast to the relevant pointer.
699
+ if (bases.size() > 1) {
700
+ for (auto *base : bases) {
701
+ if (no_cpp_mi ? PyType_IsSubtype(base->type, typeinfo->type)
702
+ : base->type == typeinfo->type) {
703
+ this_.load_value(
704
+ reinterpret_cast<instance *>(src.ptr())->get_value_and_holder(base));
705
+ return true;
706
+ }
707
+ }
708
+ }
709
+
710
+ // Case 2c: C++ multiple inheritance is involved and we couldn't find an exact type
711
+ // match in the registered bases, above, so try implicit casting (needed for proper C++
712
+ // casting when MI is involved).
713
+ if (this_.try_implicit_casts(src, convert)) {
714
+ return true;
715
+ }
716
+ }
717
+
718
+ // Perform an implicit conversion
719
+ if (convert) {
720
+ for (const auto &converter : typeinfo->implicit_conversions) {
721
+ auto temp = reinterpret_steal<object>(converter(src.ptr(), typeinfo->type));
722
+ if (load_impl<ThisT>(temp, false)) {
723
+ loader_life_support::add_patient(temp);
724
+ return true;
725
+ }
726
+ }
727
+ if (this_.try_direct_conversions(src)) {
728
+ return true;
729
+ }
730
+ }
731
+
732
+ // Failed to match local typeinfo. Try again with global.
733
+ if (typeinfo->module_local) {
734
+ if (auto *gtype = get_global_type_info(*typeinfo->cpptype)) {
735
+ typeinfo = gtype;
736
+ return load(src, false);
737
+ }
738
+ }
739
+
740
+ // Global typeinfo has precedence over foreign module_local
741
+ if (try_load_foreign_module_local(src)) {
742
+ return true;
743
+ }
744
+
745
+ // Custom converters didn't take None, now we convert None to nullptr.
746
+ if (src.is_none()) {
747
+ // Defer accepting None to other overloads (if we aren't in convert mode):
748
+ if (!convert) {
749
+ return false;
750
+ }
751
+ value = nullptr;
752
+ return true;
753
+ }
754
+
755
+ if (convert && cpptype && this_.try_cpp_conduit(src)) {
756
+ return true;
757
+ }
758
+
759
+ return false;
760
+ }
761
+
762
+ // Called to do type lookup and wrap the pointer and type in a pair when a dynamic_cast
763
+ // isn't needed or can't be used. If the type is unknown, sets the error and returns a pair
764
+ // with .second = nullptr. (p.first = nullptr is not an error: it becomes None).
765
+ PYBIND11_NOINLINE static std::pair<const void *, const type_info *>
766
+ src_and_type(const void *src,
767
+ const std::type_info &cast_type,
768
+ const std::type_info *rtti_type = nullptr) {
769
+ if (auto *tpi = get_type_info(cast_type)) {
770
+ return {src, const_cast<const type_info *>(tpi)};
771
+ }
772
+
773
+ // Not found, set error:
774
+ std::string tname = rtti_type ? rtti_type->name() : cast_type.name();
775
+ detail::clean_type_id(tname);
776
+ std::string msg = "Unregistered type : " + tname;
777
+ set_error(PyExc_TypeError, msg.c_str());
778
+ return {nullptr, nullptr};
779
+ }
780
+
781
+ const type_info *typeinfo = nullptr;
782
+ const std::type_info *cpptype = nullptr;
783
+ void *value = nullptr;
784
+ };
785
+
786
+ inline object cpp_conduit_method(handle self,
787
+ const bytes &pybind11_platform_abi_id,
788
+ const capsule &cpp_type_info_capsule,
789
+ const bytes &pointer_kind) {
790
+ #ifdef PYBIND11_HAS_STRING_VIEW
791
+ using cpp_str = std::string_view;
792
+ #else
793
+ using cpp_str = std::string;
794
+ #endif
795
+ if (cpp_str(pybind11_platform_abi_id) != PYBIND11_PLATFORM_ABI_ID) {
796
+ return none();
797
+ }
798
+ if (std::strcmp(cpp_type_info_capsule.name(), typeid(std::type_info).name()) != 0) {
799
+ return none();
800
+ }
801
+ if (cpp_str(pointer_kind) != "raw_pointer_ephemeral") {
802
+ throw std::runtime_error("Invalid pointer_kind: \"" + std::string(pointer_kind) + "\"");
803
+ }
804
+ const auto *cpp_type_info = cpp_type_info_capsule.get_pointer<const std::type_info>();
805
+ type_caster_generic caster(*cpp_type_info);
806
+ if (!caster.load(self, false)) {
807
+ return none();
808
+ }
809
+ return capsule(caster.value, cpp_type_info->name());
810
+ }
811
+
812
+ /**
813
+ * Determine suitable casting operator for pointer-or-lvalue-casting type casters. The type caster
814
+ * needs to provide `operator T*()` and `operator T&()` operators.
815
+ *
816
+ * If the type supports moving the value away via an `operator T&&() &&` method, it should use
817
+ * `movable_cast_op_type` instead.
818
+ */
819
+ template <typename T>
820
+ using cast_op_type = conditional_t<std::is_pointer<remove_reference_t<T>>::value,
821
+ typename std::add_pointer<intrinsic_t<T>>::type,
822
+ typename std::add_lvalue_reference<intrinsic_t<T>>::type>;
823
+
824
+ /**
825
+ * Determine suitable casting operator for a type caster with a movable value. Such a type caster
826
+ * needs to provide `operator T*()`, `operator T&()`, and `operator T&&() &&`. The latter will be
827
+ * called in appropriate contexts where the value can be moved rather than copied.
828
+ *
829
+ * These operator are automatically provided when using the PYBIND11_TYPE_CASTER macro.
830
+ */
831
+ template <typename T>
832
+ using movable_cast_op_type
833
+ = conditional_t<std::is_pointer<typename std::remove_reference<T>::type>::value,
834
+ typename std::add_pointer<intrinsic_t<T>>::type,
835
+ conditional_t<std::is_rvalue_reference<T>::value,
836
+ typename std::add_rvalue_reference<intrinsic_t<T>>::type,
837
+ typename std::add_lvalue_reference<intrinsic_t<T>>::type>>;
838
+
839
+ // Does the container have a mapped type and is it recursive?
840
+ // Implemented by specializations below.
841
+ template <typename Container, typename SFINAE = void>
842
+ struct container_mapped_type_traits {
843
+ static constexpr bool has_mapped_type = false;
844
+ static constexpr bool has_recursive_mapped_type = false;
845
+ };
846
+
847
+ template <typename Container>
848
+ struct container_mapped_type_traits<
849
+ Container,
850
+ typename std::enable_if<
851
+ std::is_same<typename Container::mapped_type, Container>::value>::type> {
852
+ static constexpr bool has_mapped_type = true;
853
+ static constexpr bool has_recursive_mapped_type = true;
854
+ };
855
+
856
+ template <typename Container>
857
+ struct container_mapped_type_traits<
858
+ Container,
859
+ typename std::enable_if<
860
+ negation<std::is_same<typename Container::mapped_type, Container>>::value>::type> {
861
+ static constexpr bool has_mapped_type = true;
862
+ static constexpr bool has_recursive_mapped_type = false;
863
+ };
864
+
865
+ // Does the container have a value type and is it recursive?
866
+ // Implemented by specializations below.
867
+ template <typename Container, typename SFINAE = void>
868
+ struct container_value_type_traits : std::false_type {
869
+ static constexpr bool has_value_type = false;
870
+ static constexpr bool has_recursive_value_type = false;
871
+ };
872
+
873
+ template <typename Container>
874
+ struct container_value_type_traits<
875
+ Container,
876
+ typename std::enable_if<
877
+ std::is_same<typename Container::value_type, Container>::value>::type> {
878
+ static constexpr bool has_value_type = true;
879
+ static constexpr bool has_recursive_value_type = true;
880
+ };
881
+
882
+ template <typename Container>
883
+ struct container_value_type_traits<
884
+ Container,
885
+ typename std::enable_if<
886
+ negation<std::is_same<typename Container::value_type, Container>>::value>::type> {
887
+ static constexpr bool has_value_type = true;
888
+ static constexpr bool has_recursive_value_type = false;
889
+ };
890
+
891
+ /*
892
+ * Tag to be used for representing the bottom of recursively defined types.
893
+ * Define this tag so we don't have to use void.
894
+ */
895
+ struct recursive_bottom {};
896
+
897
+ /*
898
+ * Implementation detail of `recursive_container_traits` below.
899
+ * `T` is the `value_type` of the container, which might need to be modified to
900
+ * avoid recursive types and const types.
901
+ */
902
+ template <typename T, bool is_this_a_map>
903
+ struct impl_type_to_check_recursively {
904
+ /*
905
+ * If the container is recursive, then no further recursion should be done.
906
+ */
907
+ using if_recursive = recursive_bottom;
908
+ /*
909
+ * Otherwise yield `T` unchanged.
910
+ */
911
+ using if_not_recursive = T;
912
+ };
913
+
914
+ /*
915
+ * For pairs - only as value type of a map -, the first type should remove the `const`.
916
+ * Also, if the map is recursive, then the recursive checking should consider
917
+ * the first type only.
918
+ */
919
+ template <typename A, typename B>
920
+ struct impl_type_to_check_recursively<std::pair<A, B>, /* is_this_a_map = */ true> {
921
+ using if_recursive = typename std::remove_const<A>::type;
922
+ using if_not_recursive = std::pair<typename std::remove_const<A>::type, B>;
923
+ };
924
+
925
+ /*
926
+ * Implementation of `recursive_container_traits` below.
927
+ */
928
+ template <typename Container, typename SFINAE = void>
929
+ struct impl_recursive_container_traits {
930
+ using type_to_check_recursively = recursive_bottom;
931
+ };
932
+
933
+ template <typename Container>
934
+ struct impl_recursive_container_traits<
935
+ Container,
936
+ typename std::enable_if<container_value_type_traits<Container>::has_value_type>::type> {
937
+ static constexpr bool is_recursive
938
+ = container_mapped_type_traits<Container>::has_recursive_mapped_type
939
+ || container_value_type_traits<Container>::has_recursive_value_type;
940
+ /*
941
+ * This member dictates which type Pybind11 should check recursively in traits
942
+ * such as `is_move_constructible`, `is_copy_constructible`, `is_move_assignable`, ...
943
+ * Direct access to `value_type` should be avoided:
944
+ * 1. `value_type` might recursively contain the type again
945
+ * 2. `value_type` of STL map types is `std::pair<A const, B>`, the `const`
946
+ * should be removed.
947
+ *
948
+ */
949
+ using type_to_check_recursively = typename std::conditional<
950
+ is_recursive,
951
+ typename impl_type_to_check_recursively<
952
+ typename Container::value_type,
953
+ container_mapped_type_traits<Container>::has_mapped_type>::if_recursive,
954
+ typename impl_type_to_check_recursively<
955
+ typename Container::value_type,
956
+ container_mapped_type_traits<Container>::has_mapped_type>::if_not_recursive>::type;
957
+ };
958
+
959
+ /*
960
+ * This trait defines the `type_to_check_recursively` which is needed to properly
961
+ * handle recursively defined traits such as `is_move_constructible` without going
962
+ * into an infinite recursion.
963
+ * Should be used instead of directly accessing the `value_type`.
964
+ * It cancels the recursion by returning the `recursive_bottom` tag.
965
+ *
966
+ * The default definition of `type_to_check_recursively` is as follows:
967
+ *
968
+ * 1. By default, it is `recursive_bottom`, so that the recursion is canceled.
969
+ * 2. If the type is non-recursive and defines a `value_type`, then the `value_type` is used.
970
+ * If the `value_type` is a pair and a `mapped_type` is defined,
971
+ * then the `const` is removed from the first type.
972
+ * 3. If the type is recursive and `value_type` is not a pair, then `recursive_bottom` is returned.
973
+ * 4. If the type is recursive and `value_type` is a pair and a `mapped_type` is defined,
974
+ * then `const` is removed from the first type and the first type is returned.
975
+ *
976
+ * This behavior can be extended by the user as seen in test_stl_binders.cpp.
977
+ *
978
+ * This struct is exactly the same as impl_recursive_container_traits.
979
+ * The duplication achieves that user-defined specializations don't compete
980
+ * with internal specializations, but take precedence.
981
+ */
982
+ template <typename Container, typename SFINAE = void>
983
+ struct recursive_container_traits : impl_recursive_container_traits<Container> {};
984
+
985
+ template <typename T>
986
+ struct is_move_constructible
987
+ : all_of<std::is_move_constructible<T>,
988
+ is_move_constructible<
989
+ typename recursive_container_traits<T>::type_to_check_recursively>> {};
990
+
991
+ template <>
992
+ struct is_move_constructible<recursive_bottom> : std::true_type {};
993
+
994
+ // Likewise for std::pair
995
+ // (after C++17 it is mandatory that the move constructor not exist when the two types aren't
996
+ // themselves move constructible, but this can not be relied upon when T1 or T2 are themselves
997
+ // containers).
998
+ template <typename T1, typename T2>
999
+ struct is_move_constructible<std::pair<T1, T2>>
1000
+ : all_of<is_move_constructible<T1>, is_move_constructible<T2>> {};
1001
+
1002
+ // std::is_copy_constructible isn't quite enough: it lets std::vector<T> (and similar) through when
1003
+ // T is non-copyable, but code containing such a copy constructor fails to actually compile.
1004
+ template <typename T>
1005
+ struct is_copy_constructible
1006
+ : all_of<std::is_copy_constructible<T>,
1007
+ is_copy_constructible<
1008
+ typename recursive_container_traits<T>::type_to_check_recursively>> {};
1009
+
1010
+ template <>
1011
+ struct is_copy_constructible<recursive_bottom> : std::true_type {};
1012
+
1013
+ // Likewise for std::pair
1014
+ // (after C++17 it is mandatory that the copy constructor not exist when the two types aren't
1015
+ // themselves copy constructible, but this can not be relied upon when T1 or T2 are themselves
1016
+ // containers).
1017
+ template <typename T1, typename T2>
1018
+ struct is_copy_constructible<std::pair<T1, T2>>
1019
+ : all_of<is_copy_constructible<T1>, is_copy_constructible<T2>> {};
1020
+
1021
+ // The same problems arise with std::is_copy_assignable, so we use the same workaround.
1022
+ template <typename T>
1023
+ struct is_copy_assignable
1024
+ : all_of<
1025
+ std::is_copy_assignable<T>,
1026
+ is_copy_assignable<typename recursive_container_traits<T>::type_to_check_recursively>> {
1027
+ };
1028
+
1029
+ template <>
1030
+ struct is_copy_assignable<recursive_bottom> : std::true_type {};
1031
+
1032
+ template <typename T1, typename T2>
1033
+ struct is_copy_assignable<std::pair<T1, T2>>
1034
+ : all_of<is_copy_assignable<T1>, is_copy_assignable<T2>> {};
1035
+
1036
+ PYBIND11_NAMESPACE_END(detail)
1037
+
1038
+ // polymorphic_type_hook<itype>::get(src, tinfo) determines whether the object pointed
1039
+ // to by `src` actually is an instance of some class derived from `itype`.
1040
+ // If so, it sets `tinfo` to point to the std::type_info representing that derived
1041
+ // type, and returns a pointer to the start of the most-derived object of that type
1042
+ // (in which `src` is a subobject; this will be the same address as `src` in most
1043
+ // single inheritance cases). If not, or if `src` is nullptr, it simply returns `src`
1044
+ // and leaves `tinfo` at its default value of nullptr.
1045
+ //
1046
+ // The default polymorphic_type_hook just returns src. A specialization for polymorphic
1047
+ // types determines the runtime type of the passed object and adjusts the this-pointer
1048
+ // appropriately via dynamic_cast<void*>. This is what enables a C++ Animal* to appear
1049
+ // to Python as a Dog (if Dog inherits from Animal, Animal is polymorphic, Dog is
1050
+ // registered with pybind11, and this Animal is in fact a Dog).
1051
+ //
1052
+ // You may specialize polymorphic_type_hook yourself for types that want to appear
1053
+ // polymorphic to Python but do not use C++ RTTI. (This is a not uncommon pattern
1054
+ // in performance-sensitive applications, used most notably in LLVM.)
1055
+ //
1056
+ // polymorphic_type_hook_base allows users to specialize polymorphic_type_hook with
1057
+ // std::enable_if. User provided specializations will always have higher priority than
1058
+ // the default implementation and specialization provided in polymorphic_type_hook_base.
1059
+ template <typename itype, typename SFINAE = void>
1060
+ struct polymorphic_type_hook_base {
1061
+ static const void *get(const itype *src, const std::type_info *&) { return src; }
1062
+ };
1063
+ template <typename itype>
1064
+ struct polymorphic_type_hook_base<itype, detail::enable_if_t<std::is_polymorphic<itype>::value>> {
1065
+ static const void *get(const itype *src, const std::type_info *&type) {
1066
+ type = src ? &typeid(*src) : nullptr;
1067
+ return dynamic_cast<const void *>(src);
1068
+ }
1069
+ };
1070
+ template <typename itype, typename SFINAE = void>
1071
+ struct polymorphic_type_hook : public polymorphic_type_hook_base<itype> {};
1072
+
1073
+ PYBIND11_NAMESPACE_BEGIN(detail)
1074
+
1075
+ /// Generic type caster for objects stored on the heap
1076
+ template <typename type>
1077
+ class type_caster_base : public type_caster_generic {
1078
+ using itype = intrinsic_t<type>;
1079
+
1080
+ public:
1081
+ static constexpr auto name = const_name<type>();
1082
+
1083
+ type_caster_base() : type_caster_base(typeid(type)) {}
1084
+ explicit type_caster_base(const std::type_info &info) : type_caster_generic(info) {}
1085
+
1086
+ static handle cast(const itype &src, return_value_policy policy, handle parent) {
1087
+ if (policy == return_value_policy::automatic
1088
+ || policy == return_value_policy::automatic_reference) {
1089
+ policy = return_value_policy::copy;
1090
+ }
1091
+ return cast(std::addressof(src), policy, parent);
1092
+ }
1093
+
1094
+ static handle cast(itype &&src, return_value_policy, handle parent) {
1095
+ return cast(std::addressof(src), return_value_policy::move, parent);
1096
+ }
1097
+
1098
+ // Returns a (pointer, type_info) pair taking care of necessary type lookup for a
1099
+ // polymorphic type (using RTTI by default, but can be overridden by specializing
1100
+ // polymorphic_type_hook). If the instance isn't derived, returns the base version.
1101
+ static std::pair<const void *, const type_info *> src_and_type(const itype *src) {
1102
+ const auto &cast_type = typeid(itype);
1103
+ const std::type_info *instance_type = nullptr;
1104
+ const void *vsrc = polymorphic_type_hook<itype>::get(src, instance_type);
1105
+ if (instance_type && !same_type(cast_type, *instance_type)) {
1106
+ // This is a base pointer to a derived type. If the derived type is registered
1107
+ // with pybind11, we want to make the full derived object available.
1108
+ // In the typical case where itype is polymorphic, we get the correct
1109
+ // derived pointer (which may be != base pointer) by a dynamic_cast to
1110
+ // most derived type. If itype is not polymorphic, we won't get here
1111
+ // except via a user-provided specialization of polymorphic_type_hook,
1112
+ // and the user has promised that no this-pointer adjustment is
1113
+ // required in that case, so it's OK to use static_cast.
1114
+ if (const auto *tpi = get_type_info(*instance_type)) {
1115
+ return {vsrc, tpi};
1116
+ }
1117
+ }
1118
+ // Otherwise we have either a nullptr, an `itype` pointer, or an unknown derived pointer,
1119
+ // so don't do a cast
1120
+ return type_caster_generic::src_and_type(src, cast_type, instance_type);
1121
+ }
1122
+
1123
+ static handle cast(const itype *src, return_value_policy policy, handle parent) {
1124
+ auto st = src_and_type(src);
1125
+ return type_caster_generic::cast(st.first,
1126
+ policy,
1127
+ parent,
1128
+ st.second,
1129
+ make_copy_constructor(src),
1130
+ make_move_constructor(src));
1131
+ }
1132
+
1133
+ static handle cast_holder(const itype *src, const void *holder) {
1134
+ auto st = src_and_type(src);
1135
+ return type_caster_generic::cast(st.first,
1136
+ return_value_policy::take_ownership,
1137
+ {},
1138
+ st.second,
1139
+ nullptr,
1140
+ nullptr,
1141
+ holder);
1142
+ }
1143
+
1144
+ template <typename T>
1145
+ using cast_op_type = detail::cast_op_type<T>;
1146
+
1147
+ // NOLINTNEXTLINE(google-explicit-constructor)
1148
+ operator itype *() { return (type *) value; }
1149
+ // NOLINTNEXTLINE(google-explicit-constructor)
1150
+ operator itype &() {
1151
+ if (!value) {
1152
+ throw reference_cast_error();
1153
+ }
1154
+ return *((itype *) value);
1155
+ }
1156
+
1157
+ protected:
1158
+ using Constructor = void *(*) (const void *);
1159
+
1160
+ /* Only enabled when the types are {copy,move}-constructible *and* when the type
1161
+ does not have a private operator new implementation. A comma operator is used in the
1162
+ decltype argument to apply SFINAE to the public copy/move constructors.*/
1163
+ template <typename T, typename = enable_if_t<is_copy_constructible<T>::value>>
1164
+ static auto make_copy_constructor(const T *) -> decltype(new T(std::declval<const T>()),
1165
+ Constructor{}) {
1166
+ return [](const void *arg) -> void * { return new T(*reinterpret_cast<const T *>(arg)); };
1167
+ }
1168
+
1169
+ template <typename T, typename = enable_if_t<is_move_constructible<T>::value>>
1170
+ static auto make_move_constructor(const T *) -> decltype(new T(std::declval<T &&>()),
1171
+ Constructor{}) {
1172
+ return [](const void *arg) -> void * {
1173
+ return new T(std::move(*const_cast<T *>(reinterpret_cast<const T *>(arg))));
1174
+ };
1175
+ }
1176
+
1177
+ static Constructor make_copy_constructor(...) { return nullptr; }
1178
+ static Constructor make_move_constructor(...) { return nullptr; }
1179
+ };
1180
+
1181
+ inline std::string quote_cpp_type_name(const std::string &cpp_type_name) {
1182
+ return cpp_type_name; // No-op for now. See PR #4888
1183
+ }
1184
+
1185
+ PYBIND11_NOINLINE std::string type_info_description(const std::type_info &ti) {
1186
+ if (auto *type_data = get_type_info(ti)) {
1187
+ handle th((PyObject *) type_data->type);
1188
+ return th.attr("__module__").cast<std::string>() + '.'
1189
+ + th.attr("__qualname__").cast<std::string>();
1190
+ }
1191
+ return quote_cpp_type_name(clean_type_id(ti.name()));
1192
+ }
1193
+
1194
+ PYBIND11_NAMESPACE_END(detail)
1195
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/typeid.h ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/detail/typeid.h: Compiler-independent access to type identifiers
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <cstdio>
13
+ #include <cstdlib>
14
+
15
+ #if defined(__GNUG__)
16
+ # include <cxxabi.h>
17
+ #endif
18
+
19
+ #include "common.h"
20
+
21
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
22
+ PYBIND11_NAMESPACE_BEGIN(detail)
23
+
24
+ /// Erase all occurrences of a substring
25
+ inline void erase_all(std::string &string, const std::string &search) {
26
+ for (size_t pos = 0;;) {
27
+ pos = string.find(search, pos);
28
+ if (pos == std::string::npos) {
29
+ break;
30
+ }
31
+ string.erase(pos, search.length());
32
+ }
33
+ }
34
+
35
+ PYBIND11_NOINLINE void clean_type_id(std::string &name) {
36
+ #if defined(__GNUG__)
37
+ int status = 0;
38
+ std::unique_ptr<char, void (*)(void *)> res{
39
+ abi::__cxa_demangle(name.c_str(), nullptr, nullptr, &status), std::free};
40
+ if (status == 0) {
41
+ name = res.get();
42
+ }
43
+ #else
44
+ detail::erase_all(name, "class ");
45
+ detail::erase_all(name, "struct ");
46
+ detail::erase_all(name, "enum ");
47
+ #endif
48
+ detail::erase_all(name, "pybind11::");
49
+ }
50
+
51
+ inline std::string clean_type_id(const char *typeid_name) {
52
+ std::string name(typeid_name);
53
+ detail::clean_type_id(name);
54
+ return name;
55
+ }
56
+
57
+ PYBIND11_NAMESPACE_END(detail)
58
+
59
+ /// Return a string representation of a C++ type
60
+ template <typename T>
61
+ static std::string type_id() {
62
+ return detail::clean_type_id(typeid(T).name());
63
+ }
64
+
65
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/detail/value_and_holder.h ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2016-2024 The Pybind Development Team.
2
+ // All rights reserved. Use of this source code is governed by a
3
+ // BSD-style license that can be found in the LICENSE file.
4
+
5
+ #pragma once
6
+
7
+ #include "common.h"
8
+
9
+ #include <cstddef>
10
+ #include <typeinfo>
11
+
12
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
13
+ PYBIND11_NAMESPACE_BEGIN(detail)
14
+
15
+ struct value_and_holder {
16
+ instance *inst = nullptr;
17
+ size_t index = 0u;
18
+ const detail::type_info *type = nullptr;
19
+ void **vh = nullptr;
20
+
21
+ // Main constructor for a found value/holder:
22
+ value_and_holder(instance *i, const detail::type_info *type, size_t vpos, size_t index)
23
+ : inst{i}, index{index}, type{type},
24
+ vh{inst->simple_layout ? inst->simple_value_holder
25
+ : &inst->nonsimple.values_and_holders[vpos]} {}
26
+
27
+ // Default constructor (used to signal a value-and-holder not found by get_value_and_holder())
28
+ value_and_holder() = default;
29
+
30
+ // Used for past-the-end iterator
31
+ explicit value_and_holder(size_t index) : index{index} {}
32
+
33
+ template <typename V = void>
34
+ V *&value_ptr() const {
35
+ return reinterpret_cast<V *&>(vh[0]);
36
+ }
37
+ // True if this `value_and_holder` has a non-null value pointer
38
+ explicit operator bool() const { return value_ptr() != nullptr; }
39
+
40
+ template <typename H>
41
+ H &holder() const {
42
+ return reinterpret_cast<H &>(vh[1]);
43
+ }
44
+ bool holder_constructed() const {
45
+ return inst->simple_layout
46
+ ? inst->simple_holder_constructed
47
+ : (inst->nonsimple.status[index] & instance::status_holder_constructed) != 0u;
48
+ }
49
+ // NOLINTNEXTLINE(readability-make-member-function-const)
50
+ void set_holder_constructed(bool v = true) {
51
+ if (inst->simple_layout) {
52
+ inst->simple_holder_constructed = v;
53
+ } else if (v) {
54
+ inst->nonsimple.status[index] |= instance::status_holder_constructed;
55
+ } else {
56
+ inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_holder_constructed;
57
+ }
58
+ }
59
+ bool instance_registered() const {
60
+ return inst->simple_layout
61
+ ? inst->simple_instance_registered
62
+ : ((inst->nonsimple.status[index] & instance::status_instance_registered) != 0);
63
+ }
64
+ // NOLINTNEXTLINE(readability-make-member-function-const)
65
+ void set_instance_registered(bool v = true) {
66
+ if (inst->simple_layout) {
67
+ inst->simple_instance_registered = v;
68
+ } else if (v) {
69
+ inst->nonsimple.status[index] |= instance::status_instance_registered;
70
+ } else {
71
+ inst->nonsimple.status[index] &= (std::uint8_t) ~instance::status_instance_registered;
72
+ }
73
+ }
74
+ };
75
+
76
+ PYBIND11_NAMESPACE_END(detail)
77
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/eigen.h ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eigen.h: Transparent conversion for dense and sparse Eigen matrices
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include "eigen/matrix.h"
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/common.h ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ // Copyright (c) 2023 The pybind Community.
2
+
3
+ #pragma once
4
+
5
+ // Common message for `static_assert()`s, which are useful to easily
6
+ // preempt much less obvious errors.
7
+ #define PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED \
8
+ "Pointer types (in particular `PyObject *`) are not supported as scalar types for Eigen " \
9
+ "types."
llava_video/lib/python3.10/site-packages/pybind11/include/pybind11/eigen/matrix.h ADDED
@@ -0,0 +1,715 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*
2
+ pybind11/eigen/matrix.h: Transparent conversion for dense and sparse Eigen matrices
3
+
4
+ Copyright (c) 2016 Wenzel Jakob <wenzel.jakob@epfl.ch>
5
+
6
+ All rights reserved. Use of this source code is governed by a
7
+ BSD-style license that can be found in the LICENSE file.
8
+ */
9
+
10
+ #pragma once
11
+
12
+ #include <pybind11/numpy.h>
13
+
14
+ #include "common.h"
15
+
16
+ /* HINT: To suppress warnings originating from the Eigen headers, use -isystem.
17
+ See also:
18
+ https://stackoverflow.com/questions/2579576/i-dir-vs-isystem-dir
19
+ https://stackoverflow.com/questions/1741816/isystem-for-ms-visual-studio-c-compiler
20
+ */
21
+ PYBIND11_WARNING_PUSH
22
+ PYBIND11_WARNING_DISABLE_MSVC(5054) // https://github.com/pybind/pybind11/pull/3741
23
+ // C5054: operator '&': deprecated between enumerations of different types
24
+ #if defined(__MINGW32__)
25
+ PYBIND11_WARNING_DISABLE_GCC("-Wmaybe-uninitialized")
26
+ #endif
27
+
28
+ #include <Eigen/Core>
29
+ #include <Eigen/SparseCore>
30
+
31
+ PYBIND11_WARNING_POP
32
+
33
+ // Eigen prior to 3.2.7 doesn't have proper move constructors--but worse, some classes get implicit
34
+ // move constructors that break things. We could detect this an explicitly copy, but an extra copy
35
+ // of matrices seems highly undesirable.
36
+ static_assert(EIGEN_VERSION_AT_LEAST(3, 2, 7),
37
+ "Eigen matrix support in pybind11 requires Eigen >= 3.2.7");
38
+
39
+ PYBIND11_NAMESPACE_BEGIN(PYBIND11_NAMESPACE)
40
+
41
+ PYBIND11_WARNING_DISABLE_MSVC(4127)
42
+
43
+ // Provide a convenience alias for easier pass-by-ref usage with fully dynamic strides:
44
+ using EigenDStride = Eigen::Stride<Eigen::Dynamic, Eigen::Dynamic>;
45
+ template <typename MatrixType>
46
+ using EigenDRef = Eigen::Ref<MatrixType, 0, EigenDStride>;
47
+ template <typename MatrixType>
48
+ using EigenDMap = Eigen::Map<MatrixType, 0, EigenDStride>;
49
+
50
+ PYBIND11_NAMESPACE_BEGIN(detail)
51
+
52
+ #if EIGEN_VERSION_AT_LEAST(3, 3, 0)
53
+ using EigenIndex = Eigen::Index;
54
+ template <typename Scalar, int Flags, typename StorageIndex>
55
+ using EigenMapSparseMatrix = Eigen::Map<Eigen::SparseMatrix<Scalar, Flags, StorageIndex>>;
56
+ #else
57
+ using EigenIndex = EIGEN_DEFAULT_DENSE_INDEX_TYPE;
58
+ template <typename Scalar, int Flags, typename StorageIndex>
59
+ using EigenMapSparseMatrix = Eigen::MappedSparseMatrix<Scalar, Flags, StorageIndex>;
60
+ #endif
61
+
62
+ // Matches Eigen::Map, Eigen::Ref, blocks, etc:
63
+ template <typename T>
64
+ using is_eigen_dense_map = all_of<is_template_base_of<Eigen::DenseBase, T>,
65
+ std::is_base_of<Eigen::MapBase<T, Eigen::ReadOnlyAccessors>, T>>;
66
+ template <typename T>
67
+ using is_eigen_mutable_map = std::is_base_of<Eigen::MapBase<T, Eigen::WriteAccessors>, T>;
68
+ template <typename T>
69
+ using is_eigen_dense_plain
70
+ = all_of<negation<is_eigen_dense_map<T>>, is_template_base_of<Eigen::PlainObjectBase, T>>;
71
+ template <typename T>
72
+ using is_eigen_sparse = is_template_base_of<Eigen::SparseMatrixBase, T>;
73
+ // Test for objects inheriting from EigenBase<Derived> that aren't captured by the above. This
74
+ // basically covers anything that can be assigned to a dense matrix but that don't have a typical
75
+ // matrix data layout that can be copied from their .data(). For example, DiagonalMatrix and
76
+ // SelfAdjointView fall into this category.
77
+ template <typename T>
78
+ using is_eigen_other
79
+ = all_of<is_template_base_of<Eigen::EigenBase, T>,
80
+ negation<any_of<is_eigen_dense_map<T>, is_eigen_dense_plain<T>, is_eigen_sparse<T>>>>;
81
+
82
+ // Captures numpy/eigen conformability status (returned by EigenProps::conformable()):
83
+ template <bool EigenRowMajor>
84
+ struct EigenConformable {
85
+ bool conformable = false;
86
+ EigenIndex rows = 0, cols = 0;
87
+ EigenDStride stride{0, 0}; // Only valid if negativestrides is false!
88
+ bool negativestrides = false; // If true, do not use stride!
89
+
90
+ // NOLINTNEXTLINE(google-explicit-constructor)
91
+ EigenConformable(bool fits = false) : conformable{fits} {}
92
+ // Matrix type:
93
+ EigenConformable(EigenIndex r, EigenIndex c, EigenIndex rstride, EigenIndex cstride)
94
+ : conformable{true}, rows{r}, cols{c},
95
+ // TODO: when Eigen bug #747 is fixed, remove the tests for non-negativity.
96
+ // http://eigen.tuxfamily.org/bz/show_bug.cgi?id=747
97
+ stride{EigenRowMajor ? (rstride > 0 ? rstride : 0)
98
+ : (cstride > 0 ? cstride : 0) /* outer stride */,
99
+ EigenRowMajor ? (cstride > 0 ? cstride : 0)
100
+ : (rstride > 0 ? rstride : 0) /* inner stride */},
101
+ negativestrides{rstride < 0 || cstride < 0} {}
102
+ // Vector type:
103
+ EigenConformable(EigenIndex r, EigenIndex c, EigenIndex stride)
104
+ : EigenConformable(r, c, r == 1 ? c * stride : stride, c == 1 ? r : r * stride) {}
105
+
106
+ template <typename props>
107
+ bool stride_compatible() const {
108
+ // To have compatible strides, we need (on both dimensions) one of fully dynamic strides,
109
+ // matching strides, or a dimension size of 1 (in which case the stride value is
110
+ // irrelevant). Alternatively, if any dimension size is 0, the strides are not relevant
111
+ // (and numpy ≥ 1.23 sets the strides to 0 in that case, so we need to check explicitly).
112
+ if (negativestrides) {
113
+ return false;
114
+ }
115
+ if (rows == 0 || cols == 0) {
116
+ return true;
117
+ }
118
+ return (props::inner_stride == Eigen::Dynamic || props::inner_stride == stride.inner()
119
+ || (EigenRowMajor ? cols : rows) == 1)
120
+ && (props::outer_stride == Eigen::Dynamic || props::outer_stride == stride.outer()
121
+ || (EigenRowMajor ? rows : cols) == 1);
122
+ }
123
+ // NOLINTNEXTLINE(google-explicit-constructor)
124
+ operator bool() const { return conformable; }
125
+ };
126
+
127
+ template <typename Type>
128
+ struct eigen_extract_stride {
129
+ using type = Type;
130
+ };
131
+ template <typename PlainObjectType, int MapOptions, typename StrideType>
132
+ struct eigen_extract_stride<Eigen::Map<PlainObjectType, MapOptions, StrideType>> {
133
+ using type = StrideType;
134
+ };
135
+ template <typename PlainObjectType, int Options, typename StrideType>
136
+ struct eigen_extract_stride<Eigen::Ref<PlainObjectType, Options, StrideType>> {
137
+ using type = StrideType;
138
+ };
139
+
140
+ // Helper struct for extracting information from an Eigen type
141
+ template <typename Type_>
142
+ struct EigenProps {
143
+ using Type = Type_;
144
+ using Scalar = typename Type::Scalar;
145
+ using StrideType = typename eigen_extract_stride<Type>::type;
146
+ static constexpr EigenIndex rows = Type::RowsAtCompileTime, cols = Type::ColsAtCompileTime,
147
+ size = Type::SizeAtCompileTime;
148
+ static constexpr bool row_major = Type::IsRowMajor,
149
+ vector
150
+ = Type::IsVectorAtCompileTime, // At least one dimension has fixed size 1
151
+ fixed_rows = rows != Eigen::Dynamic, fixed_cols = cols != Eigen::Dynamic,
152
+ fixed = size != Eigen::Dynamic, // Fully-fixed size
153
+ dynamic = !fixed_rows && !fixed_cols; // Fully-dynamic size
154
+
155
+ template <EigenIndex i, EigenIndex ifzero>
156
+ using if_zero = std::integral_constant<EigenIndex, i == 0 ? ifzero : i>;
157
+ static constexpr EigenIndex inner_stride
158
+ = if_zero<StrideType::InnerStrideAtCompileTime, 1>::value,
159
+ outer_stride = if_zero < StrideType::OuterStrideAtCompileTime,
160
+ vector ? size
161
+ : row_major ? cols
162
+ : rows > ::value;
163
+ static constexpr bool dynamic_stride
164
+ = inner_stride == Eigen::Dynamic && outer_stride == Eigen::Dynamic;
165
+ static constexpr bool requires_row_major
166
+ = !dynamic_stride && !vector && (row_major ? inner_stride : outer_stride) == 1;
167
+ static constexpr bool requires_col_major
168
+ = !dynamic_stride && !vector && (row_major ? outer_stride : inner_stride) == 1;
169
+
170
+ // Takes an input array and determines whether we can make it fit into the Eigen type. If
171
+ // the array is a vector, we attempt to fit it into either an Eigen 1xN or Nx1 vector
172
+ // (preferring the latter if it will fit in either, i.e. for a fully dynamic matrix type).
173
+ static EigenConformable<row_major> conformable(const array &a) {
174
+ const auto dims = a.ndim();
175
+ if (dims < 1 || dims > 2) {
176
+ return false;
177
+ }
178
+
179
+ if (dims == 2) { // Matrix type: require exact match (or dynamic)
180
+
181
+ EigenIndex np_rows = a.shape(0), np_cols = a.shape(1),
182
+ np_rstride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar)),
183
+ np_cstride = a.strides(1) / static_cast<ssize_t>(sizeof(Scalar));
184
+ if ((fixed_rows && np_rows != rows) || (fixed_cols && np_cols != cols)) {
185
+ return false;
186
+ }
187
+
188
+ return {np_rows, np_cols, np_rstride, np_cstride};
189
+ }
190
+
191
+ // Otherwise we're storing an n-vector. Only one of the strides will be used, but
192
+ // whichever is used, we want the (single) numpy stride value.
193
+ const EigenIndex n = a.shape(0),
194
+ stride = a.strides(0) / static_cast<ssize_t>(sizeof(Scalar));
195
+
196
+ if (vector) { // Eigen type is a compile-time vector
197
+ if (fixed && size != n) {
198
+ return false; // Vector size mismatch
199
+ }
200
+ return {rows == 1 ? 1 : n, cols == 1 ? 1 : n, stride};
201
+ }
202
+ if (fixed) {
203
+ // The type has a fixed size, but is not a vector: abort
204
+ return false;
205
+ }
206
+ if (fixed_cols) {
207
+ // Since this isn't a vector, cols must be != 1. We allow this only if it exactly
208
+ // equals the number of elements (rows is Dynamic, and so 1 row is allowed).
209
+ if (cols != n) {
210
+ return false;
211
+ }
212
+ return {1, n, stride};
213
+ } // Otherwise it's either fully dynamic, or column dynamic; both become a column vector
214
+ if (fixed_rows && rows != n) {
215
+ return false;
216
+ }
217
+ return {n, 1, stride};
218
+ }
219
+
220
+ static constexpr bool show_writeable
221
+ = is_eigen_dense_map<Type>::value && is_eigen_mutable_map<Type>::value;
222
+ static constexpr bool show_order = is_eigen_dense_map<Type>::value;
223
+ static constexpr bool show_c_contiguous = show_order && requires_row_major;
224
+ static constexpr bool show_f_contiguous
225
+ = !show_c_contiguous && show_order && requires_col_major;
226
+
227
+ static constexpr auto descriptor
228
+ = const_name("numpy.ndarray[") + npy_format_descriptor<Scalar>::name + const_name("[")
229
+ + const_name<fixed_rows>(const_name<(size_t) rows>(), const_name("m")) + const_name(", ")
230
+ + const_name<fixed_cols>(const_name<(size_t) cols>(), const_name("n")) + const_name("]")
231
+ +
232
+ // For a reference type (e.g. Ref<MatrixXd>) we have other constraints that might need to
233
+ // be satisfied: writeable=True (for a mutable reference), and, depending on the map's
234
+ // stride options, possibly f_contiguous or c_contiguous. We include them in the
235
+ // descriptor output to provide some hint as to why a TypeError is occurring (otherwise
236
+ // it can be confusing to see that a function accepts a 'numpy.ndarray[float64[3,2]]' and
237
+ // an error message that you *gave* a numpy.ndarray of the right type and dimensions.
238
+ const_name<show_writeable>(", flags.writeable", "")
239
+ + const_name<show_c_contiguous>(", flags.c_contiguous", "")
240
+ + const_name<show_f_contiguous>(", flags.f_contiguous", "") + const_name("]");
241
+ };
242
+
243
+ // Casts an Eigen type to numpy array. If given a base, the numpy array references the src data,
244
+ // otherwise it'll make a copy. writeable lets you turn off the writeable flag for the array.
245
+ template <typename props>
246
+ handle
247
+ eigen_array_cast(typename props::Type const &src, handle base = handle(), bool writeable = true) {
248
+ constexpr ssize_t elem_size = sizeof(typename props::Scalar);
249
+ array a;
250
+ if (props::vector) {
251
+ a = array({src.size()}, {elem_size * src.innerStride()}, src.data(), base);
252
+ } else {
253
+ a = array({src.rows(), src.cols()},
254
+ {elem_size * src.rowStride(), elem_size * src.colStride()},
255
+ src.data(),
256
+ base);
257
+ }
258
+
259
+ if (!writeable) {
260
+ array_proxy(a.ptr())->flags &= ~detail::npy_api::NPY_ARRAY_WRITEABLE_;
261
+ }
262
+
263
+ return a.release();
264
+ }
265
+
266
+ // Takes an lvalue ref to some Eigen type and a (python) base object, creating a numpy array that
267
+ // reference the Eigen object's data with `base` as the python-registered base class (if omitted,
268
+ // the base will be set to None, and lifetime management is up to the caller). The numpy array is
269
+ // non-writeable if the given type is const.
270
+ template <typename props, typename Type>
271
+ handle eigen_ref_array(Type &src, handle parent = none()) {
272
+ // none here is to get past array's should-we-copy detection, which currently always
273
+ // copies when there is no base. Setting the base to None should be harmless.
274
+ return eigen_array_cast<props>(src, parent, !std::is_const<Type>::value);
275
+ }
276
+
277
+ // Takes a pointer to some dense, plain Eigen type, builds a capsule around it, then returns a
278
+ // numpy array that references the encapsulated data with a python-side reference to the capsule to
279
+ // tie its destruction to that of any dependent python objects. Const-ness is determined by
280
+ // whether or not the Type of the pointer given is const.
281
+ template <typename props, typename Type, typename = enable_if_t<is_eigen_dense_plain<Type>::value>>
282
+ handle eigen_encapsulate(Type *src) {
283
+ capsule base(src, [](void *o) { delete static_cast<Type *>(o); });
284
+ return eigen_ref_array<props>(*src, base);
285
+ }
286
+
287
+ // Type caster for regular, dense matrix types (e.g. MatrixXd), but not maps/refs/etc. of dense
288
+ // types.
289
+ template <typename Type>
290
+ struct type_caster<Type, enable_if_t<is_eigen_dense_plain<Type>::value>> {
291
+ using Scalar = typename Type::Scalar;
292
+ static_assert(!std::is_pointer<Scalar>::value,
293
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
294
+ using props = EigenProps<Type>;
295
+
296
+ bool load(handle src, bool convert) {
297
+ // If we're in no-convert mode, only load if given an array of the correct type
298
+ if (!convert && !isinstance<array_t<Scalar>>(src)) {
299
+ return false;
300
+ }
301
+
302
+ // Coerce into an array, but don't do type conversion yet; the copy below handles it.
303
+ auto buf = array::ensure(src);
304
+
305
+ if (!buf) {
306
+ return false;
307
+ }
308
+
309
+ auto dims = buf.ndim();
310
+ if (dims < 1 || dims > 2) {
311
+ return false;
312
+ }
313
+
314
+ auto fits = props::conformable(buf);
315
+ if (!fits) {
316
+ return false;
317
+ }
318
+
319
+ // Allocate the new type, then build a numpy reference into it
320
+ value = Type(fits.rows, fits.cols);
321
+ auto ref = reinterpret_steal<array>(eigen_ref_array<props>(value));
322
+ if (dims == 1) {
323
+ ref = ref.squeeze();
324
+ } else if (ref.ndim() == 1) {
325
+ buf = buf.squeeze();
326
+ }
327
+
328
+ int result = detail::npy_api::get().PyArray_CopyInto_(ref.ptr(), buf.ptr());
329
+
330
+ if (result < 0) { // Copy failed!
331
+ PyErr_Clear();
332
+ return false;
333
+ }
334
+
335
+ return true;
336
+ }
337
+
338
+ private:
339
+ // Cast implementation
340
+ template <typename CType>
341
+ static handle cast_impl(CType *src, return_value_policy policy, handle parent) {
342
+ switch (policy) {
343
+ case return_value_policy::take_ownership:
344
+ case return_value_policy::automatic:
345
+ return eigen_encapsulate<props>(src);
346
+ case return_value_policy::move:
347
+ return eigen_encapsulate<props>(new CType(std::move(*src)));
348
+ case return_value_policy::copy:
349
+ return eigen_array_cast<props>(*src);
350
+ case return_value_policy::reference:
351
+ case return_value_policy::automatic_reference:
352
+ return eigen_ref_array<props>(*src);
353
+ case return_value_policy::reference_internal:
354
+ return eigen_ref_array<props>(*src, parent);
355
+ default:
356
+ throw cast_error("unhandled return_value_policy: should not happen!");
357
+ };
358
+ }
359
+
360
+ public:
361
+ // Normal returned non-reference, non-const value:
362
+ static handle cast(Type &&src, return_value_policy /* policy */, handle parent) {
363
+ return cast_impl(&src, return_value_policy::move, parent);
364
+ }
365
+ // If you return a non-reference const, we mark the numpy array readonly:
366
+ static handle cast(const Type &&src, return_value_policy /* policy */, handle parent) {
367
+ return cast_impl(&src, return_value_policy::move, parent);
368
+ }
369
+ // lvalue reference return; default (automatic) becomes copy
370
+ static handle cast(Type &src, return_value_policy policy, handle parent) {
371
+ if (policy == return_value_policy::automatic
372
+ || policy == return_value_policy::automatic_reference) {
373
+ policy = return_value_policy::copy;
374
+ }
375
+ return cast_impl(&src, policy, parent);
376
+ }
377
+ // const lvalue reference return; default (automatic) becomes copy
378
+ static handle cast(const Type &src, return_value_policy policy, handle parent) {
379
+ if (policy == return_value_policy::automatic
380
+ || policy == return_value_policy::automatic_reference) {
381
+ policy = return_value_policy::copy;
382
+ }
383
+ return cast(&src, policy, parent);
384
+ }
385
+ // non-const pointer return
386
+ static handle cast(Type *src, return_value_policy policy, handle parent) {
387
+ return cast_impl(src, policy, parent);
388
+ }
389
+ // const pointer return
390
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
391
+ return cast_impl(src, policy, parent);
392
+ }
393
+
394
+ static constexpr auto name = props::descriptor;
395
+
396
+ // NOLINTNEXTLINE(google-explicit-constructor)
397
+ operator Type *() { return &value; }
398
+ // NOLINTNEXTLINE(google-explicit-constructor)
399
+ operator Type &() { return value; }
400
+ // NOLINTNEXTLINE(google-explicit-constructor)
401
+ operator Type &&() && { return std::move(value); }
402
+ template <typename T>
403
+ using cast_op_type = movable_cast_op_type<T>;
404
+
405
+ private:
406
+ Type value;
407
+ };
408
+
409
+ // Base class for casting reference/map/block/etc. objects back to python.
410
+ template <typename MapType>
411
+ struct eigen_map_caster {
412
+ static_assert(!std::is_pointer<typename MapType::Scalar>::value,
413
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
414
+
415
+ private:
416
+ using props = EigenProps<MapType>;
417
+
418
+ public:
419
+ // Directly referencing a ref/map's data is a bit dangerous (whatever the map/ref points to has
420
+ // to stay around), but we'll allow it under the assumption that you know what you're doing
421
+ // (and have an appropriate keep_alive in place). We return a numpy array pointing directly at
422
+ // the ref's data (The numpy array ends up read-only if the ref was to a const matrix type.)
423
+ // Note that this means you need to ensure you don't destroy the object in some other way (e.g.
424
+ // with an appropriate keep_alive, or with a reference to a statically allocated matrix).
425
+ static handle cast(const MapType &src, return_value_policy policy, handle parent) {
426
+ switch (policy) {
427
+ case return_value_policy::copy:
428
+ return eigen_array_cast<props>(src);
429
+ case return_value_policy::reference_internal:
430
+ return eigen_array_cast<props>(src, parent, is_eigen_mutable_map<MapType>::value);
431
+ case return_value_policy::reference:
432
+ case return_value_policy::automatic:
433
+ case return_value_policy::automatic_reference:
434
+ return eigen_array_cast<props>(src, none(), is_eigen_mutable_map<MapType>::value);
435
+ default:
436
+ // move, take_ownership don't make any sense for a ref/map:
437
+ pybind11_fail("Invalid return_value_policy for Eigen Map/Ref/Block type");
438
+ }
439
+ }
440
+
441
+ static constexpr auto name = props::descriptor;
442
+
443
+ // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
444
+ // types but not bound arguments). We still provide them (with an explicitly delete) so that
445
+ // you end up here if you try anyway.
446
+ bool load(handle, bool) = delete;
447
+ operator MapType() = delete;
448
+ template <typename>
449
+ using cast_op_type = MapType;
450
+ };
451
+
452
+ // We can return any map-like object (but can only load Refs, specialized next):
453
+ template <typename Type>
454
+ struct type_caster<Type, enable_if_t<is_eigen_dense_map<Type>::value>> : eigen_map_caster<Type> {};
455
+
456
+ // Loader for Ref<...> arguments. See the documentation for info on how to make this work without
457
+ // copying (it requires some extra effort in many cases).
458
+ template <typename PlainObjectType, typename StrideType>
459
+ struct type_caster<
460
+ Eigen::Ref<PlainObjectType, 0, StrideType>,
461
+ enable_if_t<is_eigen_dense_map<Eigen::Ref<PlainObjectType, 0, StrideType>>::value>>
462
+ : public eigen_map_caster<Eigen::Ref<PlainObjectType, 0, StrideType>> {
463
+ private:
464
+ using Type = Eigen::Ref<PlainObjectType, 0, StrideType>;
465
+ using props = EigenProps<Type>;
466
+ using Scalar = typename props::Scalar;
467
+ static_assert(!std::is_pointer<Scalar>::value,
468
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
469
+ using MapType = Eigen::Map<PlainObjectType, 0, StrideType>;
470
+ using Array
471
+ = array_t<Scalar,
472
+ array::forcecast
473
+ | ((props::row_major ? props::inner_stride : props::outer_stride) == 1
474
+ ? array::c_style
475
+ : (props::row_major ? props::outer_stride : props::inner_stride) == 1
476
+ ? array::f_style
477
+ : 0)>;
478
+ static constexpr bool need_writeable = is_eigen_mutable_map<Type>::value;
479
+ // Delay construction (these have no default constructor)
480
+ std::unique_ptr<MapType> map;
481
+ std::unique_ptr<Type> ref;
482
+ // Our array. When possible, this is just a numpy array pointing to the source data, but
483
+ // sometimes we can't avoid copying (e.g. input is not a numpy array at all, has an
484
+ // incompatible layout, or is an array of a type that needs to be converted). Using a numpy
485
+ // temporary (rather than an Eigen temporary) saves an extra copy when we need both type
486
+ // conversion and storage order conversion. (Note that we refuse to use this temporary copy
487
+ // when loading an argument for a Ref<M> with M non-const, i.e. a read-write reference).
488
+ Array copy_or_ref;
489
+
490
+ public:
491
+ bool load(handle src, bool convert) {
492
+ // First check whether what we have is already an array of the right type. If not, we
493
+ // can't avoid a copy (because the copy is also going to do type conversion).
494
+ bool need_copy = !isinstance<Array>(src);
495
+
496
+ EigenConformable<props::row_major> fits;
497
+ if (!need_copy) {
498
+ // We don't need a converting copy, but we also need to check whether the strides are
499
+ // compatible with the Ref's stride requirements
500
+ auto aref = reinterpret_borrow<Array>(src);
501
+
502
+ if (aref && (!need_writeable || aref.writeable())) {
503
+ fits = props::conformable(aref);
504
+ if (!fits) {
505
+ return false; // Incompatible dimensions
506
+ }
507
+ if (!fits.template stride_compatible<props>()) {
508
+ need_copy = true;
509
+ } else {
510
+ copy_or_ref = std::move(aref);
511
+ }
512
+ } else {
513
+ need_copy = true;
514
+ }
515
+ }
516
+
517
+ if (need_copy) {
518
+ // We need to copy: If we need a mutable reference, or we're not supposed to convert
519
+ // (either because we're in the no-convert overload pass, or because we're explicitly
520
+ // instructed not to copy (via `py::arg().noconvert()`) we have to fail loading.
521
+ if (!convert || need_writeable) {
522
+ return false;
523
+ }
524
+
525
+ Array copy = Array::ensure(src);
526
+ if (!copy) {
527
+ return false;
528
+ }
529
+ fits = props::conformable(copy);
530
+ if (!fits || !fits.template stride_compatible<props>()) {
531
+ return false;
532
+ }
533
+ copy_or_ref = std::move(copy);
534
+ loader_life_support::add_patient(copy_or_ref);
535
+ }
536
+
537
+ ref.reset();
538
+ map.reset(new MapType(data(copy_or_ref),
539
+ fits.rows,
540
+ fits.cols,
541
+ make_stride(fits.stride.outer(), fits.stride.inner())));
542
+ ref.reset(new Type(*map));
543
+
544
+ return true;
545
+ }
546
+
547
+ // NOLINTNEXTLINE(google-explicit-constructor)
548
+ operator Type *() { return ref.get(); }
549
+ // NOLINTNEXTLINE(google-explicit-constructor)
550
+ operator Type &() { return *ref; }
551
+ template <typename _T>
552
+ using cast_op_type = pybind11::detail::cast_op_type<_T>;
553
+
554
+ private:
555
+ template <typename T = Type, enable_if_t<is_eigen_mutable_map<T>::value, int> = 0>
556
+ Scalar *data(Array &a) {
557
+ return a.mutable_data();
558
+ }
559
+
560
+ template <typename T = Type, enable_if_t<!is_eigen_mutable_map<T>::value, int> = 0>
561
+ const Scalar *data(Array &a) {
562
+ return a.data();
563
+ }
564
+
565
+ // Attempt to figure out a constructor of `Stride` that will work.
566
+ // If both strides are fixed, use a default constructor:
567
+ template <typename S>
568
+ using stride_ctor_default = bool_constant<S::InnerStrideAtCompileTime != Eigen::Dynamic
569
+ && S::OuterStrideAtCompileTime != Eigen::Dynamic
570
+ && std::is_default_constructible<S>::value>;
571
+ // Otherwise, if there is a two-index constructor, assume it is (outer,inner) like
572
+ // Eigen::Stride, and use it:
573
+ template <typename S>
574
+ using stride_ctor_dual
575
+ = bool_constant<!stride_ctor_default<S>::value
576
+ && std::is_constructible<S, EigenIndex, EigenIndex>::value>;
577
+ // Otherwise, if there is a one-index constructor, and just one of the strides is dynamic, use
578
+ // it (passing whichever stride is dynamic).
579
+ template <typename S>
580
+ using stride_ctor_outer
581
+ = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
582
+ && S::OuterStrideAtCompileTime == Eigen::Dynamic
583
+ && S::InnerStrideAtCompileTime != Eigen::Dynamic
584
+ && std::is_constructible<S, EigenIndex>::value>;
585
+ template <typename S>
586
+ using stride_ctor_inner
587
+ = bool_constant<!any_of<stride_ctor_default<S>, stride_ctor_dual<S>>::value
588
+ && S::InnerStrideAtCompileTime == Eigen::Dynamic
589
+ && S::OuterStrideAtCompileTime != Eigen::Dynamic
590
+ && std::is_constructible<S, EigenIndex>::value>;
591
+
592
+ template <typename S = StrideType, enable_if_t<stride_ctor_default<S>::value, int> = 0>
593
+ static S make_stride(EigenIndex, EigenIndex) {
594
+ return S();
595
+ }
596
+ template <typename S = StrideType, enable_if_t<stride_ctor_dual<S>::value, int> = 0>
597
+ static S make_stride(EigenIndex outer, EigenIndex inner) {
598
+ return S(outer, inner);
599
+ }
600
+ template <typename S = StrideType, enable_if_t<stride_ctor_outer<S>::value, int> = 0>
601
+ static S make_stride(EigenIndex outer, EigenIndex) {
602
+ return S(outer);
603
+ }
604
+ template <typename S = StrideType, enable_if_t<stride_ctor_inner<S>::value, int> = 0>
605
+ static S make_stride(EigenIndex, EigenIndex inner) {
606
+ return S(inner);
607
+ }
608
+ };
609
+
610
+ // type_caster for special matrix types (e.g. DiagonalMatrix), which are EigenBase, but not
611
+ // EigenDense (i.e. they don't have a data(), at least not with the usual matrix layout).
612
+ // load() is not supported, but we can cast them into the python domain by first copying to a
613
+ // regular Eigen::Matrix, then casting that.
614
+ template <typename Type>
615
+ struct type_caster<Type, enable_if_t<is_eigen_other<Type>::value>> {
616
+ static_assert(!std::is_pointer<typename Type::Scalar>::value,
617
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
618
+
619
+ protected:
620
+ using Matrix
621
+ = Eigen::Matrix<typename Type::Scalar, Type::RowsAtCompileTime, Type::ColsAtCompileTime>;
622
+ using props = EigenProps<Matrix>;
623
+
624
+ public:
625
+ static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
626
+ handle h = eigen_encapsulate<props>(new Matrix(src));
627
+ return h;
628
+ }
629
+ static handle cast(const Type *src, return_value_policy policy, handle parent) {
630
+ return cast(*src, policy, parent);
631
+ }
632
+
633
+ static constexpr auto name = props::descriptor;
634
+
635
+ // Explicitly delete these: support python -> C++ conversion on these (i.e. these can be return
636
+ // types but not bound arguments). We still provide them (with an explicitly delete) so that
637
+ // you end up here if you try anyway.
638
+ bool load(handle, bool) = delete;
639
+ operator Type() = delete;
640
+ template <typename>
641
+ using cast_op_type = Type;
642
+ };
643
+
644
+ template <typename Type>
645
+ struct type_caster<Type, enable_if_t<is_eigen_sparse<Type>::value>> {
646
+ using Scalar = typename Type::Scalar;
647
+ static_assert(!std::is_pointer<Scalar>::value,
648
+ PYBIND11_EIGEN_MESSAGE_POINTER_TYPES_ARE_NOT_SUPPORTED);
649
+ using StorageIndex = remove_reference_t<decltype(*std::declval<Type>().outerIndexPtr())>;
650
+ using Index = typename Type::Index;
651
+ static constexpr bool rowMajor = Type::IsRowMajor;
652
+
653
+ bool load(handle src, bool) {
654
+ if (!src) {
655
+ return false;
656
+ }
657
+
658
+ auto obj = reinterpret_borrow<object>(src);
659
+ object sparse_module = module_::import("scipy.sparse");
660
+ object matrix_type = sparse_module.attr(rowMajor ? "csr_matrix" : "csc_matrix");
661
+
662
+ if (!type::handle_of(obj).is(matrix_type)) {
663
+ try {
664
+ obj = matrix_type(obj);
665
+ } catch (const error_already_set &) {
666
+ return false;
667
+ }
668
+ }
669
+
670
+ auto values = array_t<Scalar>((object) obj.attr("data"));
671
+ auto innerIndices = array_t<StorageIndex>((object) obj.attr("indices"));
672
+ auto outerIndices = array_t<StorageIndex>((object) obj.attr("indptr"));
673
+ auto shape = pybind11::tuple((pybind11::object) obj.attr("shape"));
674
+ auto nnz = obj.attr("nnz").cast<Index>();
675
+
676
+ if (!values || !innerIndices || !outerIndices) {
677
+ return false;
678
+ }
679
+
680
+ value = EigenMapSparseMatrix<Scalar,
681
+ Type::Flags &(Eigen::RowMajor | Eigen::ColMajor),
682
+ StorageIndex>(shape[0].cast<Index>(),
683
+ shape[1].cast<Index>(),
684
+ std::move(nnz),
685
+ outerIndices.mutable_data(),
686
+ innerIndices.mutable_data(),
687
+ values.mutable_data());
688
+
689
+ return true;
690
+ }
691
+
692
+ static handle cast(const Type &src, return_value_policy /* policy */, handle /* parent */) {
693
+ const_cast<Type &>(src).makeCompressed();
694
+
695
+ object matrix_type
696
+ = module_::import("scipy.sparse").attr(rowMajor ? "csr_matrix" : "csc_matrix");
697
+
698
+ array data(src.nonZeros(), src.valuePtr());
699
+ array outerIndices((rowMajor ? src.rows() : src.cols()) + 1, src.outerIndexPtr());
700
+ array innerIndices(src.nonZeros(), src.innerIndexPtr());
701
+
702
+ return matrix_type(pybind11::make_tuple(
703
+ std::move(data), std::move(innerIndices), std::move(outerIndices)),
704
+ pybind11::make_tuple(src.rows(), src.cols()))
705
+ .release();
706
+ }
707
+
708
+ PYBIND11_TYPE_CASTER(Type,
709
+ const_name<(Type::IsRowMajor) != 0>("scipy.sparse.csr_matrix[",
710
+ "scipy.sparse.csc_matrix[")
711
+ + npy_format_descriptor<Scalar>::name + const_name("]"));
712
+ };
713
+
714
+ PYBIND11_NAMESPACE_END(detail)
715
+ PYBIND11_NAMESPACE_END(PYBIND11_NAMESPACE)