Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER +1 -0
- infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/LICENSE +29 -0
- infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/METADATA +93 -0
- infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/RECORD +43 -0
- infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED +0 -0
- infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/WHEEL +6 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/_identifier.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/filters.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/__init__.py +1576 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi +8 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/_cm_multivar.py +166 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/_tight_bbox.py +84 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/artist.pyi +199 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/backend_tools.py +998 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/bezier.py +602 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/category.py +235 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/cbook.py +2405 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/collections.py +2582 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/font_manager.py +1645 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/inset.pyi +25 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/offsetbox.pyi +298 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/patches.py +0 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/pylab.py +67 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/texmanager.pyi +38 -0
- infer_4_37_2/lib/python3.10/site-packages/matplotlib/ticker.pyi +297 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_integration_zope_interface.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.cfg +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.py +7 -0
- infer_4_37_2/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
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/SOURCES.txt +7 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/dependency_links.txt +1 -0
- infer_4_37_2/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
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/zip-safe +1 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_zipped-egg/my_test_package-1.0-py3.7.egg +0 -0
- infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/test_working_set.py +501 -0
- infer_4_37_2/lib/python3.10/site-packages/prometheus_client-0.21.1.dist-info/INSTALLER +1 -0
- infer_4_37_2/lib/python3.10/site-packages/prometheus_client-0.21.1.dist-info/LICENSE +201 -0
infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
infer_4_37_2/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.
|
infer_4_37_2/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 | [](https://pypi.python.org/pypi/contourpy) [](https://anaconda.org/conda-forge/contourpy) |
|
| 91 |
+
| Downloads | [](https://pepy.tech/project/contourpy) |
|
| 92 |
+
| Python version | [](https://pypi.org/project/contourpy/) |
|
| 93 |
+
| Coverage | [](https://app.codecov.io/gh/contourpy/contourpy) |
|
infer_4_37_2/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
|
infer_4_37_2/lib/python3.10/site-packages/contourpy-1.3.1.dist-info/REQUESTED
ADDED
|
File without changes
|
infer_4_37_2/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 |
+
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/_identifier.cpython-310.pyc
ADDED
|
Binary file (2.07 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/compiler.cpython-310.pyc
ADDED
|
Binary file (54.6 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/debug.cpython-310.pyc
ADDED
|
Binary file (3.98 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/environment.cpython-310.pyc
ADDED
|
Binary file (53.5 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/ext.cpython-310.pyc
ADDED
|
Binary file (25.9 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/filters.cpython-310.pyc
ADDED
|
Binary file (51.9 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/idtracking.cpython-310.pyc
ADDED
|
Binary file (11.1 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/nativetypes.cpython-310.pyc
ADDED
|
Binary file (5 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/nodes.cpython-310.pyc
ADDED
|
Binary file (40.3 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/jinja2/__pycache__/sandbox.cpython-310.pyc
ADDED
|
Binary file (12 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/__init__.py
ADDED
|
@@ -0,0 +1,1576 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
An object-oriented plotting library.
|
| 3 |
+
|
| 4 |
+
A procedural interface is provided by the companion pyplot module,
|
| 5 |
+
which may be imported directly, e.g.::
|
| 6 |
+
|
| 7 |
+
import matplotlib.pyplot as plt
|
| 8 |
+
|
| 9 |
+
or using ipython::
|
| 10 |
+
|
| 11 |
+
ipython
|
| 12 |
+
|
| 13 |
+
at your terminal, followed by::
|
| 14 |
+
|
| 15 |
+
In [1]: %matplotlib
|
| 16 |
+
In [2]: import matplotlib.pyplot as plt
|
| 17 |
+
|
| 18 |
+
at the ipython shell prompt.
|
| 19 |
+
|
| 20 |
+
For the most part, direct use of the explicit object-oriented library is
|
| 21 |
+
encouraged when programming; the implicit pyplot interface is primarily for
|
| 22 |
+
working interactively. The exceptions to this suggestion are the pyplot
|
| 23 |
+
functions `.pyplot.figure`, `.pyplot.subplot`, `.pyplot.subplots`, and
|
| 24 |
+
`.pyplot.savefig`, which can greatly simplify scripting. See
|
| 25 |
+
:ref:`api_interfaces` for an explanation of the tradeoffs between the implicit
|
| 26 |
+
and explicit interfaces.
|
| 27 |
+
|
| 28 |
+
Modules include:
|
| 29 |
+
|
| 30 |
+
:mod:`matplotlib.axes`
|
| 31 |
+
The `~.axes.Axes` class. Most pyplot functions are wrappers for
|
| 32 |
+
`~.axes.Axes` methods. The axes module is the highest level of OO
|
| 33 |
+
access to the library.
|
| 34 |
+
|
| 35 |
+
:mod:`matplotlib.figure`
|
| 36 |
+
The `.Figure` class.
|
| 37 |
+
|
| 38 |
+
:mod:`matplotlib.artist`
|
| 39 |
+
The `.Artist` base class for all classes that draw things.
|
| 40 |
+
|
| 41 |
+
:mod:`matplotlib.lines`
|
| 42 |
+
The `.Line2D` class for drawing lines and markers.
|
| 43 |
+
|
| 44 |
+
:mod:`matplotlib.patches`
|
| 45 |
+
Classes for drawing polygons.
|
| 46 |
+
|
| 47 |
+
:mod:`matplotlib.text`
|
| 48 |
+
The `.Text` and `.Annotation` classes.
|
| 49 |
+
|
| 50 |
+
:mod:`matplotlib.image`
|
| 51 |
+
The `.AxesImage` and `.FigureImage` classes.
|
| 52 |
+
|
| 53 |
+
:mod:`matplotlib.collections`
|
| 54 |
+
Classes for efficient drawing of groups of lines or polygons.
|
| 55 |
+
|
| 56 |
+
:mod:`matplotlib.colors`
|
| 57 |
+
Color specifications and making colormaps.
|
| 58 |
+
|
| 59 |
+
:mod:`matplotlib.cm`
|
| 60 |
+
Colormaps, and the `.ScalarMappable` mixin class for providing color
|
| 61 |
+
mapping functionality to other classes.
|
| 62 |
+
|
| 63 |
+
:mod:`matplotlib.ticker`
|
| 64 |
+
Calculation of tick mark locations and formatting of tick labels.
|
| 65 |
+
|
| 66 |
+
:mod:`matplotlib.backends`
|
| 67 |
+
A subpackage with modules for various GUI libraries and output formats.
|
| 68 |
+
|
| 69 |
+
The base matplotlib namespace includes:
|
| 70 |
+
|
| 71 |
+
`~matplotlib.rcParams`
|
| 72 |
+
Default configuration settings; their defaults may be overridden using
|
| 73 |
+
a :file:`matplotlibrc` file.
|
| 74 |
+
|
| 75 |
+
`~matplotlib.use`
|
| 76 |
+
Setting the Matplotlib backend. This should be called before any
|
| 77 |
+
figure is created, because it is not possible to switch between
|
| 78 |
+
different GUI backends after that.
|
| 79 |
+
|
| 80 |
+
The following environment variables can be used to customize the behavior:
|
| 81 |
+
|
| 82 |
+
:envvar:`MPLBACKEND`
|
| 83 |
+
This optional variable can be set to choose the Matplotlib backend. See
|
| 84 |
+
:ref:`what-is-a-backend`.
|
| 85 |
+
|
| 86 |
+
:envvar:`MPLCONFIGDIR`
|
| 87 |
+
This is the directory used to store user customizations to
|
| 88 |
+
Matplotlib, as well as some caches to improve performance. If
|
| 89 |
+
:envvar:`MPLCONFIGDIR` is not defined, :file:`{HOME}/.config/matplotlib`
|
| 90 |
+
and :file:`{HOME}/.cache/matplotlib` are used on Linux, and
|
| 91 |
+
:file:`{HOME}/.matplotlib` on other platforms, if they are
|
| 92 |
+
writable. Otherwise, the Python standard library's `tempfile.gettempdir`
|
| 93 |
+
is used to find a base directory in which the :file:`matplotlib`
|
| 94 |
+
subdirectory is created.
|
| 95 |
+
|
| 96 |
+
Matplotlib was initially written by John D. Hunter (1968-2012) and is now
|
| 97 |
+
developed and maintained by a host of others.
|
| 98 |
+
|
| 99 |
+
Occasionally the internal documentation (python docstrings) will refer
|
| 100 |
+
to MATLAB®, a registered trademark of The MathWorks, Inc.
|
| 101 |
+
|
| 102 |
+
"""
|
| 103 |
+
|
| 104 |
+
__all__ = [
|
| 105 |
+
"__bibtex__",
|
| 106 |
+
"__version__",
|
| 107 |
+
"__version_info__",
|
| 108 |
+
"set_loglevel",
|
| 109 |
+
"ExecutableNotFoundError",
|
| 110 |
+
"get_configdir",
|
| 111 |
+
"get_cachedir",
|
| 112 |
+
"get_data_path",
|
| 113 |
+
"matplotlib_fname",
|
| 114 |
+
"MatplotlibDeprecationWarning",
|
| 115 |
+
"RcParams",
|
| 116 |
+
"rc_params",
|
| 117 |
+
"rc_params_from_file",
|
| 118 |
+
"rcParamsDefault",
|
| 119 |
+
"rcParams",
|
| 120 |
+
"rcParamsOrig",
|
| 121 |
+
"defaultParams",
|
| 122 |
+
"rc",
|
| 123 |
+
"rcdefaults",
|
| 124 |
+
"rc_file_defaults",
|
| 125 |
+
"rc_file",
|
| 126 |
+
"rc_context",
|
| 127 |
+
"use",
|
| 128 |
+
"get_backend",
|
| 129 |
+
"interactive",
|
| 130 |
+
"is_interactive",
|
| 131 |
+
"colormaps",
|
| 132 |
+
"multivar_colormaps",
|
| 133 |
+
"bivar_colormaps",
|
| 134 |
+
"color_sequences",
|
| 135 |
+
]
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
import atexit
|
| 139 |
+
from collections import namedtuple
|
| 140 |
+
from collections.abc import MutableMapping
|
| 141 |
+
import contextlib
|
| 142 |
+
import functools
|
| 143 |
+
import importlib
|
| 144 |
+
import inspect
|
| 145 |
+
from inspect import Parameter
|
| 146 |
+
import locale
|
| 147 |
+
import logging
|
| 148 |
+
import os
|
| 149 |
+
from pathlib import Path
|
| 150 |
+
import pprint
|
| 151 |
+
import re
|
| 152 |
+
import shutil
|
| 153 |
+
import subprocess
|
| 154 |
+
import sys
|
| 155 |
+
import tempfile
|
| 156 |
+
|
| 157 |
+
from packaging.version import parse as parse_version
|
| 158 |
+
|
| 159 |
+
# cbook must import matplotlib only within function
|
| 160 |
+
# definitions, so it is safe to import from it here.
|
| 161 |
+
from . import _api, _version, cbook, _docstring, rcsetup
|
| 162 |
+
from matplotlib._api import MatplotlibDeprecationWarning
|
| 163 |
+
from matplotlib.rcsetup import cycler # noqa: F401
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
_log = logging.getLogger(__name__)
|
| 167 |
+
|
| 168 |
+
__bibtex__ = r"""@Article{Hunter:2007,
|
| 169 |
+
Author = {Hunter, J. D.},
|
| 170 |
+
Title = {Matplotlib: A 2D graphics environment},
|
| 171 |
+
Journal = {Computing in Science \& Engineering},
|
| 172 |
+
Volume = {9},
|
| 173 |
+
Number = {3},
|
| 174 |
+
Pages = {90--95},
|
| 175 |
+
abstract = {Matplotlib is a 2D graphics package used for Python
|
| 176 |
+
for application development, interactive scripting, and
|
| 177 |
+
publication-quality image generation across user
|
| 178 |
+
interfaces and operating systems.},
|
| 179 |
+
publisher = {IEEE COMPUTER SOC},
|
| 180 |
+
year = 2007
|
| 181 |
+
}"""
|
| 182 |
+
|
| 183 |
+
# modelled after sys.version_info
|
| 184 |
+
_VersionInfo = namedtuple('_VersionInfo',
|
| 185 |
+
'major, minor, micro, releaselevel, serial')
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
def _parse_to_version_info(version_str):
|
| 189 |
+
"""
|
| 190 |
+
Parse a version string to a namedtuple analogous to sys.version_info.
|
| 191 |
+
|
| 192 |
+
See:
|
| 193 |
+
https://packaging.pypa.io/en/latest/version.html#packaging.version.parse
|
| 194 |
+
https://docs.python.org/3/library/sys.html#sys.version_info
|
| 195 |
+
"""
|
| 196 |
+
v = parse_version(version_str)
|
| 197 |
+
if v.pre is None and v.post is None and v.dev is None:
|
| 198 |
+
return _VersionInfo(v.major, v.minor, v.micro, 'final', 0)
|
| 199 |
+
elif v.dev is not None:
|
| 200 |
+
return _VersionInfo(v.major, v.minor, v.micro, 'alpha', v.dev)
|
| 201 |
+
elif v.pre is not None:
|
| 202 |
+
releaselevel = {
|
| 203 |
+
'a': 'alpha',
|
| 204 |
+
'b': 'beta',
|
| 205 |
+
'rc': 'candidate'}.get(v.pre[0], 'alpha')
|
| 206 |
+
return _VersionInfo(v.major, v.minor, v.micro, releaselevel, v.pre[1])
|
| 207 |
+
else:
|
| 208 |
+
# fallback for v.post: guess-next-dev scheme from setuptools_scm
|
| 209 |
+
return _VersionInfo(v.major, v.minor, v.micro + 1, 'alpha', v.post)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
def _get_version():
|
| 213 |
+
"""Return the version string used for __version__."""
|
| 214 |
+
# Only shell out to a git subprocess if really needed, i.e. when we are in
|
| 215 |
+
# a matplotlib git repo but not in a shallow clone, such as those used by
|
| 216 |
+
# CI, as the latter would trigger a warning from setuptools_scm.
|
| 217 |
+
root = Path(__file__).resolve().parents[2]
|
| 218 |
+
if ((root / ".matplotlib-repo").exists()
|
| 219 |
+
and (root / ".git").exists()
|
| 220 |
+
and not (root / ".git/shallow").exists()):
|
| 221 |
+
try:
|
| 222 |
+
import setuptools_scm
|
| 223 |
+
except ImportError:
|
| 224 |
+
pass
|
| 225 |
+
else:
|
| 226 |
+
return setuptools_scm.get_version(
|
| 227 |
+
root=root,
|
| 228 |
+
dist_name="matplotlib",
|
| 229 |
+
version_scheme="release-branch-semver",
|
| 230 |
+
local_scheme="node-and-date",
|
| 231 |
+
fallback_version=_version.version,
|
| 232 |
+
)
|
| 233 |
+
# Get the version from the _version.py file if not in repo or setuptools_scm is
|
| 234 |
+
# unavailable.
|
| 235 |
+
return _version.version
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@_api.caching_module_getattr
|
| 239 |
+
class __getattr__:
|
| 240 |
+
__version__ = property(lambda self: _get_version())
|
| 241 |
+
__version_info__ = property(
|
| 242 |
+
lambda self: _parse_to_version_info(self.__version__))
|
| 243 |
+
|
| 244 |
+
|
| 245 |
+
def _check_versions():
|
| 246 |
+
|
| 247 |
+
# Quickfix to ensure Microsoft Visual C++ redistributable
|
| 248 |
+
# DLLs are loaded before importing kiwisolver
|
| 249 |
+
from . import ft2font # noqa: F401
|
| 250 |
+
|
| 251 |
+
for modname, minver in [
|
| 252 |
+
("cycler", "0.10"),
|
| 253 |
+
("dateutil", "2.7"),
|
| 254 |
+
("kiwisolver", "1.3.1"),
|
| 255 |
+
("numpy", "1.23"),
|
| 256 |
+
("pyparsing", "2.3.1"),
|
| 257 |
+
]:
|
| 258 |
+
module = importlib.import_module(modname)
|
| 259 |
+
if parse_version(module.__version__) < parse_version(minver):
|
| 260 |
+
raise ImportError(f"Matplotlib requires {modname}>={minver}; "
|
| 261 |
+
f"you have {module.__version__}")
|
| 262 |
+
|
| 263 |
+
|
| 264 |
+
_check_versions()
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
# The decorator ensures this always returns the same handler (and it is only
|
| 268 |
+
# attached once).
|
| 269 |
+
@functools.cache
|
| 270 |
+
def _ensure_handler():
|
| 271 |
+
"""
|
| 272 |
+
The first time this function is called, attach a `StreamHandler` using the
|
| 273 |
+
same format as `logging.basicConfig` to the Matplotlib root logger.
|
| 274 |
+
|
| 275 |
+
Return this handler every time this function is called.
|
| 276 |
+
"""
|
| 277 |
+
handler = logging.StreamHandler()
|
| 278 |
+
handler.setFormatter(logging.Formatter(logging.BASIC_FORMAT))
|
| 279 |
+
_log.addHandler(handler)
|
| 280 |
+
return handler
|
| 281 |
+
|
| 282 |
+
|
| 283 |
+
def set_loglevel(level):
|
| 284 |
+
"""
|
| 285 |
+
Configure Matplotlib's logging levels.
|
| 286 |
+
|
| 287 |
+
Matplotlib uses the standard library `logging` framework under the root
|
| 288 |
+
logger 'matplotlib'. This is a helper function to:
|
| 289 |
+
|
| 290 |
+
- set Matplotlib's root logger level
|
| 291 |
+
- set the root logger handler's level, creating the handler
|
| 292 |
+
if it does not exist yet
|
| 293 |
+
|
| 294 |
+
Typically, one should call ``set_loglevel("info")`` or
|
| 295 |
+
``set_loglevel("debug")`` to get additional debugging information.
|
| 296 |
+
|
| 297 |
+
Users or applications that are installing their own logging handlers
|
| 298 |
+
may want to directly manipulate ``logging.getLogger('matplotlib')`` rather
|
| 299 |
+
than use this function.
|
| 300 |
+
|
| 301 |
+
Parameters
|
| 302 |
+
----------
|
| 303 |
+
level : {"notset", "debug", "info", "warning", "error", "critical"}
|
| 304 |
+
The log level of the handler.
|
| 305 |
+
|
| 306 |
+
Notes
|
| 307 |
+
-----
|
| 308 |
+
The first time this function is called, an additional handler is attached
|
| 309 |
+
to Matplotlib's root handler; this handler is reused every time and this
|
| 310 |
+
function simply manipulates the logger and handler's level.
|
| 311 |
+
|
| 312 |
+
"""
|
| 313 |
+
_log.setLevel(level.upper())
|
| 314 |
+
_ensure_handler().setLevel(level.upper())
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def _logged_cached(fmt, func=None):
|
| 318 |
+
"""
|
| 319 |
+
Decorator that logs a function's return value, and memoizes that value.
|
| 320 |
+
|
| 321 |
+
After ::
|
| 322 |
+
|
| 323 |
+
@_logged_cached(fmt)
|
| 324 |
+
def func(): ...
|
| 325 |
+
|
| 326 |
+
the first call to *func* will log its return value at the DEBUG level using
|
| 327 |
+
%-format string *fmt*, and memoize it; later calls to *func* will directly
|
| 328 |
+
return that value.
|
| 329 |
+
"""
|
| 330 |
+
if func is None: # Return the actual decorator.
|
| 331 |
+
return functools.partial(_logged_cached, fmt)
|
| 332 |
+
|
| 333 |
+
called = False
|
| 334 |
+
ret = None
|
| 335 |
+
|
| 336 |
+
@functools.wraps(func)
|
| 337 |
+
def wrapper(**kwargs):
|
| 338 |
+
nonlocal called, ret
|
| 339 |
+
if not called:
|
| 340 |
+
ret = func(**kwargs)
|
| 341 |
+
called = True
|
| 342 |
+
_log.debug(fmt, ret)
|
| 343 |
+
return ret
|
| 344 |
+
|
| 345 |
+
return wrapper
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
_ExecInfo = namedtuple("_ExecInfo", "executable raw_version version")
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
class ExecutableNotFoundError(FileNotFoundError):
|
| 352 |
+
"""
|
| 353 |
+
Error raised when an executable that Matplotlib optionally
|
| 354 |
+
depends on can't be found.
|
| 355 |
+
"""
|
| 356 |
+
pass
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
@functools.cache
|
| 360 |
+
def _get_executable_info(name):
|
| 361 |
+
"""
|
| 362 |
+
Get the version of some executable that Matplotlib optionally depends on.
|
| 363 |
+
|
| 364 |
+
.. warning::
|
| 365 |
+
The list of executables that this function supports is set according to
|
| 366 |
+
Matplotlib's internal needs, and may change without notice.
|
| 367 |
+
|
| 368 |
+
Parameters
|
| 369 |
+
----------
|
| 370 |
+
name : str
|
| 371 |
+
The executable to query. The following values are currently supported:
|
| 372 |
+
"dvipng", "gs", "inkscape", "magick", "pdftocairo", "pdftops". This
|
| 373 |
+
list is subject to change without notice.
|
| 374 |
+
|
| 375 |
+
Returns
|
| 376 |
+
-------
|
| 377 |
+
tuple
|
| 378 |
+
A namedtuple with fields ``executable`` (`str`) and ``version``
|
| 379 |
+
(`packaging.Version`, or ``None`` if the version cannot be determined).
|
| 380 |
+
|
| 381 |
+
Raises
|
| 382 |
+
------
|
| 383 |
+
ExecutableNotFoundError
|
| 384 |
+
If the executable is not found or older than the oldest version
|
| 385 |
+
supported by Matplotlib. For debugging purposes, it is also
|
| 386 |
+
possible to "hide" an executable from Matplotlib by adding it to the
|
| 387 |
+
:envvar:`_MPLHIDEEXECUTABLES` environment variable (a comma-separated
|
| 388 |
+
list), which must be set prior to any calls to this function.
|
| 389 |
+
ValueError
|
| 390 |
+
If the executable is not one that we know how to query.
|
| 391 |
+
"""
|
| 392 |
+
|
| 393 |
+
def impl(args, regex, min_ver=None, ignore_exit_code=False):
|
| 394 |
+
# Execute the subprocess specified by args; capture stdout and stderr.
|
| 395 |
+
# Search for a regex match in the output; if the match succeeds, the
|
| 396 |
+
# first group of the match is the version.
|
| 397 |
+
# Return an _ExecInfo if the executable exists, and has a version of
|
| 398 |
+
# at least min_ver (if set); else, raise ExecutableNotFoundError.
|
| 399 |
+
try:
|
| 400 |
+
output = subprocess.check_output(
|
| 401 |
+
args, stderr=subprocess.STDOUT,
|
| 402 |
+
text=True, errors="replace")
|
| 403 |
+
except subprocess.CalledProcessError as _cpe:
|
| 404 |
+
if ignore_exit_code:
|
| 405 |
+
output = _cpe.output
|
| 406 |
+
else:
|
| 407 |
+
raise ExecutableNotFoundError(str(_cpe)) from _cpe
|
| 408 |
+
except OSError as _ose:
|
| 409 |
+
raise ExecutableNotFoundError(str(_ose)) from _ose
|
| 410 |
+
match = re.search(regex, output)
|
| 411 |
+
if match:
|
| 412 |
+
raw_version = match.group(1)
|
| 413 |
+
version = parse_version(raw_version)
|
| 414 |
+
if min_ver is not None and version < parse_version(min_ver):
|
| 415 |
+
raise ExecutableNotFoundError(
|
| 416 |
+
f"You have {args[0]} version {version} but the minimum "
|
| 417 |
+
f"version supported by Matplotlib is {min_ver}")
|
| 418 |
+
return _ExecInfo(args[0], raw_version, version)
|
| 419 |
+
else:
|
| 420 |
+
raise ExecutableNotFoundError(
|
| 421 |
+
f"Failed to determine the version of {args[0]} from "
|
| 422 |
+
f"{' '.join(args)}, which output {output}")
|
| 423 |
+
|
| 424 |
+
if name in os.environ.get("_MPLHIDEEXECUTABLES", "").split(","):
|
| 425 |
+
raise ExecutableNotFoundError(f"{name} was hidden")
|
| 426 |
+
|
| 427 |
+
if name == "dvipng":
|
| 428 |
+
return impl(["dvipng", "-version"], "(?m)^dvipng(?: .*)? (.+)", "1.6")
|
| 429 |
+
elif name == "gs":
|
| 430 |
+
execs = (["gswin32c", "gswin64c", "mgs", "gs"] # "mgs" for miktex.
|
| 431 |
+
if sys.platform == "win32" else
|
| 432 |
+
["gs"])
|
| 433 |
+
for e in execs:
|
| 434 |
+
try:
|
| 435 |
+
return impl([e, "--version"], "(.*)", "9")
|
| 436 |
+
except ExecutableNotFoundError:
|
| 437 |
+
pass
|
| 438 |
+
message = "Failed to find a Ghostscript installation"
|
| 439 |
+
raise ExecutableNotFoundError(message)
|
| 440 |
+
elif name == "inkscape":
|
| 441 |
+
try:
|
| 442 |
+
# Try headless option first (needed for Inkscape version < 1.0):
|
| 443 |
+
return impl(["inkscape", "--without-gui", "-V"],
|
| 444 |
+
"Inkscape ([^ ]*)")
|
| 445 |
+
except ExecutableNotFoundError:
|
| 446 |
+
pass # Suppress exception chaining.
|
| 447 |
+
# If --without-gui is not accepted, we may be using Inkscape >= 1.0 so
|
| 448 |
+
# try without it:
|
| 449 |
+
return impl(["inkscape", "-V"], "Inkscape ([^ ]*)")
|
| 450 |
+
elif name == "magick":
|
| 451 |
+
if sys.platform == "win32":
|
| 452 |
+
# Check the registry to avoid confusing ImageMagick's convert with
|
| 453 |
+
# Windows's builtin convert.exe.
|
| 454 |
+
import winreg
|
| 455 |
+
binpath = ""
|
| 456 |
+
for flag in [0, winreg.KEY_WOW64_32KEY, winreg.KEY_WOW64_64KEY]:
|
| 457 |
+
try:
|
| 458 |
+
with winreg.OpenKeyEx(
|
| 459 |
+
winreg.HKEY_LOCAL_MACHINE,
|
| 460 |
+
r"Software\Imagemagick\Current",
|
| 461 |
+
0, winreg.KEY_QUERY_VALUE | flag) as hkey:
|
| 462 |
+
binpath = winreg.QueryValueEx(hkey, "BinPath")[0]
|
| 463 |
+
except OSError:
|
| 464 |
+
pass
|
| 465 |
+
path = None
|
| 466 |
+
if binpath:
|
| 467 |
+
for name in ["convert.exe", "magick.exe"]:
|
| 468 |
+
candidate = Path(binpath, name)
|
| 469 |
+
if candidate.exists():
|
| 470 |
+
path = str(candidate)
|
| 471 |
+
break
|
| 472 |
+
if path is None:
|
| 473 |
+
raise ExecutableNotFoundError(
|
| 474 |
+
"Failed to find an ImageMagick installation")
|
| 475 |
+
else:
|
| 476 |
+
path = "convert"
|
| 477 |
+
info = impl([path, "--version"], r"^Version: ImageMagick (\S*)")
|
| 478 |
+
if info.raw_version == "7.0.10-34":
|
| 479 |
+
# https://github.com/ImageMagick/ImageMagick/issues/2720
|
| 480 |
+
raise ExecutableNotFoundError(
|
| 481 |
+
f"You have ImageMagick {info.version}, which is unsupported")
|
| 482 |
+
return info
|
| 483 |
+
elif name == "pdftocairo":
|
| 484 |
+
return impl(["pdftocairo", "-v"], "pdftocairo version (.*)")
|
| 485 |
+
elif name == "pdftops":
|
| 486 |
+
info = impl(["pdftops", "-v"], "^pdftops version (.*)",
|
| 487 |
+
ignore_exit_code=True)
|
| 488 |
+
if info and not (
|
| 489 |
+
3 <= info.version.major or
|
| 490 |
+
# poppler version numbers.
|
| 491 |
+
parse_version("0.9") <= info.version < parse_version("1.0")):
|
| 492 |
+
raise ExecutableNotFoundError(
|
| 493 |
+
f"You have pdftops version {info.version} but the minimum "
|
| 494 |
+
f"version supported by Matplotlib is 3.0")
|
| 495 |
+
return info
|
| 496 |
+
else:
|
| 497 |
+
raise ValueError(f"Unknown executable: {name!r}")
|
| 498 |
+
|
| 499 |
+
|
| 500 |
+
def _get_xdg_config_dir():
|
| 501 |
+
"""
|
| 502 |
+
Return the XDG configuration directory, according to the XDG base
|
| 503 |
+
directory spec:
|
| 504 |
+
|
| 505 |
+
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
| 506 |
+
"""
|
| 507 |
+
return os.environ.get('XDG_CONFIG_HOME') or str(Path.home() / ".config")
|
| 508 |
+
|
| 509 |
+
|
| 510 |
+
def _get_xdg_cache_dir():
|
| 511 |
+
"""
|
| 512 |
+
Return the XDG cache directory, according to the XDG base directory spec:
|
| 513 |
+
|
| 514 |
+
https://specifications.freedesktop.org/basedir-spec/basedir-spec-latest.html
|
| 515 |
+
"""
|
| 516 |
+
return os.environ.get('XDG_CACHE_HOME') or str(Path.home() / ".cache")
|
| 517 |
+
|
| 518 |
+
|
| 519 |
+
def _get_config_or_cache_dir(xdg_base_getter):
|
| 520 |
+
configdir = os.environ.get('MPLCONFIGDIR')
|
| 521 |
+
if configdir:
|
| 522 |
+
configdir = Path(configdir)
|
| 523 |
+
elif sys.platform.startswith(('linux', 'freebsd')):
|
| 524 |
+
# Only call _xdg_base_getter here so that MPLCONFIGDIR is tried first,
|
| 525 |
+
# as _xdg_base_getter can throw.
|
| 526 |
+
configdir = Path(xdg_base_getter(), "matplotlib")
|
| 527 |
+
else:
|
| 528 |
+
configdir = Path.home() / ".matplotlib"
|
| 529 |
+
# Resolve the path to handle potential issues with inaccessible symlinks.
|
| 530 |
+
configdir = configdir.resolve()
|
| 531 |
+
try:
|
| 532 |
+
configdir.mkdir(parents=True, exist_ok=True)
|
| 533 |
+
except OSError as exc:
|
| 534 |
+
_log.warning("mkdir -p failed for path %s: %s", configdir, exc)
|
| 535 |
+
else:
|
| 536 |
+
if os.access(str(configdir), os.W_OK) and configdir.is_dir():
|
| 537 |
+
return str(configdir)
|
| 538 |
+
_log.warning("%s is not a writable directory", configdir)
|
| 539 |
+
# If the config or cache directory cannot be created or is not a writable
|
| 540 |
+
# directory, create a temporary one.
|
| 541 |
+
try:
|
| 542 |
+
tmpdir = tempfile.mkdtemp(prefix="matplotlib-")
|
| 543 |
+
except OSError as exc:
|
| 544 |
+
raise OSError(
|
| 545 |
+
f"Matplotlib requires access to a writable cache directory, but there "
|
| 546 |
+
f"was an issue with the default path ({configdir}), and a temporary "
|
| 547 |
+
f"directory could not be created; set the MPLCONFIGDIR environment "
|
| 548 |
+
f"variable to a writable directory") from exc
|
| 549 |
+
os.environ["MPLCONFIGDIR"] = tmpdir
|
| 550 |
+
atexit.register(shutil.rmtree, tmpdir)
|
| 551 |
+
_log.warning(
|
| 552 |
+
"Matplotlib created a temporary cache directory at %s because there was "
|
| 553 |
+
"an issue with the default path (%s); it is highly recommended to set the "
|
| 554 |
+
"MPLCONFIGDIR environment variable to a writable directory, in particular to "
|
| 555 |
+
"speed up the import of Matplotlib and to better support multiprocessing.",
|
| 556 |
+
tmpdir, configdir)
|
| 557 |
+
return tmpdir
|
| 558 |
+
|
| 559 |
+
|
| 560 |
+
@_logged_cached('CONFIGDIR=%s')
|
| 561 |
+
def get_configdir():
|
| 562 |
+
"""
|
| 563 |
+
Return the string path of the configuration directory.
|
| 564 |
+
|
| 565 |
+
The directory is chosen as follows:
|
| 566 |
+
|
| 567 |
+
1. If the MPLCONFIGDIR environment variable is supplied, choose that.
|
| 568 |
+
2. On Linux, follow the XDG specification and look first in
|
| 569 |
+
``$XDG_CONFIG_HOME``, if defined, or ``$HOME/.config``. On other
|
| 570 |
+
platforms, choose ``$HOME/.matplotlib``.
|
| 571 |
+
3. If the chosen directory exists and is writable, use that as the
|
| 572 |
+
configuration directory.
|
| 573 |
+
4. Else, create a temporary directory, and use it as the configuration
|
| 574 |
+
directory.
|
| 575 |
+
"""
|
| 576 |
+
return _get_config_or_cache_dir(_get_xdg_config_dir)
|
| 577 |
+
|
| 578 |
+
|
| 579 |
+
@_logged_cached('CACHEDIR=%s')
|
| 580 |
+
def get_cachedir():
|
| 581 |
+
"""
|
| 582 |
+
Return the string path of the cache directory.
|
| 583 |
+
|
| 584 |
+
The procedure used to find the directory is the same as for
|
| 585 |
+
`get_configdir`, except using ``$XDG_CACHE_HOME``/``$HOME/.cache`` instead.
|
| 586 |
+
"""
|
| 587 |
+
return _get_config_or_cache_dir(_get_xdg_cache_dir)
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
@_logged_cached('matplotlib data path: %s')
|
| 591 |
+
def get_data_path():
|
| 592 |
+
"""Return the path to Matplotlib data."""
|
| 593 |
+
return str(Path(__file__).with_name("mpl-data"))
|
| 594 |
+
|
| 595 |
+
|
| 596 |
+
def matplotlib_fname():
|
| 597 |
+
"""
|
| 598 |
+
Get the location of the config file.
|
| 599 |
+
|
| 600 |
+
The file location is determined in the following order
|
| 601 |
+
|
| 602 |
+
- ``$PWD/matplotlibrc``
|
| 603 |
+
- ``$MATPLOTLIBRC`` if it is not a directory
|
| 604 |
+
- ``$MATPLOTLIBRC/matplotlibrc``
|
| 605 |
+
- ``$MPLCONFIGDIR/matplotlibrc``
|
| 606 |
+
- On Linux,
|
| 607 |
+
- ``$XDG_CONFIG_HOME/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
|
| 608 |
+
is defined)
|
| 609 |
+
- or ``$HOME/.config/matplotlib/matplotlibrc`` (if ``$XDG_CONFIG_HOME``
|
| 610 |
+
is not defined)
|
| 611 |
+
- On other platforms,
|
| 612 |
+
- ``$HOME/.matplotlib/matplotlibrc`` if ``$HOME`` is defined
|
| 613 |
+
- Lastly, it looks in ``$MATPLOTLIBDATA/matplotlibrc``, which should always
|
| 614 |
+
exist.
|
| 615 |
+
"""
|
| 616 |
+
|
| 617 |
+
def gen_candidates():
|
| 618 |
+
# rely on down-stream code to make absolute. This protects us
|
| 619 |
+
# from having to directly get the current working directory
|
| 620 |
+
# which can fail if the user has ended up with a cwd that is
|
| 621 |
+
# non-existent.
|
| 622 |
+
yield 'matplotlibrc'
|
| 623 |
+
try:
|
| 624 |
+
matplotlibrc = os.environ['MATPLOTLIBRC']
|
| 625 |
+
except KeyError:
|
| 626 |
+
pass
|
| 627 |
+
else:
|
| 628 |
+
yield matplotlibrc
|
| 629 |
+
yield os.path.join(matplotlibrc, 'matplotlibrc')
|
| 630 |
+
yield os.path.join(get_configdir(), 'matplotlibrc')
|
| 631 |
+
yield os.path.join(get_data_path(), 'matplotlibrc')
|
| 632 |
+
|
| 633 |
+
for fname in gen_candidates():
|
| 634 |
+
if os.path.exists(fname) and not os.path.isdir(fname):
|
| 635 |
+
return fname
|
| 636 |
+
|
| 637 |
+
raise RuntimeError("Could not find matplotlibrc file; your Matplotlib "
|
| 638 |
+
"install is broken")
|
| 639 |
+
|
| 640 |
+
|
| 641 |
+
# rcParams deprecated and automatically mapped to another key.
|
| 642 |
+
# Values are tuples of (version, new_name, f_old2new, f_new2old).
|
| 643 |
+
_deprecated_map = {}
|
| 644 |
+
# rcParams deprecated; some can manually be mapped to another key.
|
| 645 |
+
# Values are tuples of (version, new_name_or_None).
|
| 646 |
+
_deprecated_ignore_map = {}
|
| 647 |
+
# rcParams deprecated; can use None to suppress warnings; remain actually
|
| 648 |
+
# listed in the rcParams.
|
| 649 |
+
# Values are tuples of (version,)
|
| 650 |
+
_deprecated_remain_as_none = {}
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
@_docstring.Substitution(
|
| 654 |
+
"\n".join(map("- {}".format, sorted(rcsetup._validators, key=str.lower)))
|
| 655 |
+
)
|
| 656 |
+
class RcParams(MutableMapping, dict):
|
| 657 |
+
"""
|
| 658 |
+
A dict-like key-value store for config parameters, including validation.
|
| 659 |
+
|
| 660 |
+
Validating functions are defined and associated with rc parameters in
|
| 661 |
+
:mod:`matplotlib.rcsetup`.
|
| 662 |
+
|
| 663 |
+
The list of rcParams is:
|
| 664 |
+
|
| 665 |
+
%s
|
| 666 |
+
|
| 667 |
+
See Also
|
| 668 |
+
--------
|
| 669 |
+
:ref:`customizing-with-matplotlibrc-files`
|
| 670 |
+
"""
|
| 671 |
+
|
| 672 |
+
validate = rcsetup._validators
|
| 673 |
+
|
| 674 |
+
# validate values on the way in
|
| 675 |
+
def __init__(self, *args, **kwargs):
|
| 676 |
+
self.update(*args, **kwargs)
|
| 677 |
+
|
| 678 |
+
def _set(self, key, val):
|
| 679 |
+
"""
|
| 680 |
+
Directly write data bypassing deprecation and validation logic.
|
| 681 |
+
|
| 682 |
+
Notes
|
| 683 |
+
-----
|
| 684 |
+
As end user or downstream library you almost always should use
|
| 685 |
+
``rcParams[key] = val`` and not ``_set()``.
|
| 686 |
+
|
| 687 |
+
There are only very few special cases that need direct data access.
|
| 688 |
+
These cases previously used ``dict.__setitem__(rcParams, key, val)``,
|
| 689 |
+
which is now deprecated and replaced by ``rcParams._set(key, val)``.
|
| 690 |
+
|
| 691 |
+
Even though private, we guarantee API stability for ``rcParams._set``,
|
| 692 |
+
i.e. it is subject to Matplotlib's API and deprecation policy.
|
| 693 |
+
|
| 694 |
+
:meta public:
|
| 695 |
+
"""
|
| 696 |
+
dict.__setitem__(self, key, val)
|
| 697 |
+
|
| 698 |
+
def _get(self, key):
|
| 699 |
+
"""
|
| 700 |
+
Directly read data bypassing deprecation, backend and validation
|
| 701 |
+
logic.
|
| 702 |
+
|
| 703 |
+
Notes
|
| 704 |
+
-----
|
| 705 |
+
As end user or downstream library you almost always should use
|
| 706 |
+
``val = rcParams[key]`` and not ``_get()``.
|
| 707 |
+
|
| 708 |
+
There are only very few special cases that need direct data access.
|
| 709 |
+
These cases previously used ``dict.__getitem__(rcParams, key, val)``,
|
| 710 |
+
which is now deprecated and replaced by ``rcParams._get(key)``.
|
| 711 |
+
|
| 712 |
+
Even though private, we guarantee API stability for ``rcParams._get``,
|
| 713 |
+
i.e. it is subject to Matplotlib's API and deprecation policy.
|
| 714 |
+
|
| 715 |
+
:meta public:
|
| 716 |
+
"""
|
| 717 |
+
return dict.__getitem__(self, key)
|
| 718 |
+
|
| 719 |
+
def _update_raw(self, other_params):
|
| 720 |
+
"""
|
| 721 |
+
Directly update the data from *other_params*, bypassing deprecation,
|
| 722 |
+
backend and validation logic on both sides.
|
| 723 |
+
|
| 724 |
+
This ``rcParams._update_raw(params)`` replaces the previous pattern
|
| 725 |
+
``dict.update(rcParams, params)``.
|
| 726 |
+
|
| 727 |
+
Parameters
|
| 728 |
+
----------
|
| 729 |
+
other_params : dict or `.RcParams`
|
| 730 |
+
The input mapping from which to update.
|
| 731 |
+
"""
|
| 732 |
+
if isinstance(other_params, RcParams):
|
| 733 |
+
other_params = dict.items(other_params)
|
| 734 |
+
dict.update(self, other_params)
|
| 735 |
+
|
| 736 |
+
def _ensure_has_backend(self):
|
| 737 |
+
"""
|
| 738 |
+
Ensure that a "backend" entry exists.
|
| 739 |
+
|
| 740 |
+
Normally, the default matplotlibrc file contains *no* entry for "backend" (the
|
| 741 |
+
corresponding line starts with ##, not #; we fill in _auto_backend_sentinel
|
| 742 |
+
in that case. However, packagers can set a different default backend
|
| 743 |
+
(resulting in a normal `#backend: foo` line) in which case we should *not*
|
| 744 |
+
fill in _auto_backend_sentinel.
|
| 745 |
+
"""
|
| 746 |
+
dict.setdefault(self, "backend", rcsetup._auto_backend_sentinel)
|
| 747 |
+
|
| 748 |
+
def __setitem__(self, key, val):
|
| 749 |
+
try:
|
| 750 |
+
if key in _deprecated_map:
|
| 751 |
+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
|
| 752 |
+
_api.warn_deprecated(
|
| 753 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 754 |
+
key = alt_key
|
| 755 |
+
val = alt_val(val)
|
| 756 |
+
elif key in _deprecated_remain_as_none and val is not None:
|
| 757 |
+
version, = _deprecated_remain_as_none[key]
|
| 758 |
+
_api.warn_deprecated(version, name=key, obj_type="rcparam")
|
| 759 |
+
elif key in _deprecated_ignore_map:
|
| 760 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 761 |
+
_api.warn_deprecated(
|
| 762 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 763 |
+
return
|
| 764 |
+
elif key == 'backend':
|
| 765 |
+
if val is rcsetup._auto_backend_sentinel:
|
| 766 |
+
if 'backend' in self:
|
| 767 |
+
return
|
| 768 |
+
try:
|
| 769 |
+
cval = self.validate[key](val)
|
| 770 |
+
except ValueError as ve:
|
| 771 |
+
raise ValueError(f"Key {key}: {ve}") from None
|
| 772 |
+
self._set(key, cval)
|
| 773 |
+
except KeyError as err:
|
| 774 |
+
raise KeyError(
|
| 775 |
+
f"{key} is not a valid rc parameter (see rcParams.keys() for "
|
| 776 |
+
f"a list of valid parameters)") from err
|
| 777 |
+
|
| 778 |
+
def __getitem__(self, key):
|
| 779 |
+
if key in _deprecated_map:
|
| 780 |
+
version, alt_key, alt_val, inverse_alt = _deprecated_map[key]
|
| 781 |
+
_api.warn_deprecated(
|
| 782 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 783 |
+
return inverse_alt(self._get(alt_key))
|
| 784 |
+
|
| 785 |
+
elif key in _deprecated_ignore_map:
|
| 786 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 787 |
+
_api.warn_deprecated(
|
| 788 |
+
version, name=key, obj_type="rcparam", alternative=alt_key)
|
| 789 |
+
return self._get(alt_key) if alt_key else None
|
| 790 |
+
|
| 791 |
+
# In theory, this should only ever be used after the global rcParams
|
| 792 |
+
# has been set up, but better be safe e.g. in presence of breakpoints.
|
| 793 |
+
elif key == "backend" and self is globals().get("rcParams"):
|
| 794 |
+
val = self._get(key)
|
| 795 |
+
if val is rcsetup._auto_backend_sentinel:
|
| 796 |
+
from matplotlib import pyplot as plt
|
| 797 |
+
plt.switch_backend(rcsetup._auto_backend_sentinel)
|
| 798 |
+
|
| 799 |
+
return self._get(key)
|
| 800 |
+
|
| 801 |
+
def _get_backend_or_none(self):
|
| 802 |
+
"""Get the requested backend, if any, without triggering resolution."""
|
| 803 |
+
backend = self._get("backend")
|
| 804 |
+
return None if backend is rcsetup._auto_backend_sentinel else backend
|
| 805 |
+
|
| 806 |
+
def __repr__(self):
|
| 807 |
+
class_name = self.__class__.__name__
|
| 808 |
+
indent = len(class_name) + 1
|
| 809 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 810 |
+
repr_split = pprint.pformat(dict(self), indent=1,
|
| 811 |
+
width=80 - indent).split('\n')
|
| 812 |
+
repr_indented = ('\n' + ' ' * indent).join(repr_split)
|
| 813 |
+
return f'{class_name}({repr_indented})'
|
| 814 |
+
|
| 815 |
+
def __str__(self):
|
| 816 |
+
return '\n'.join(map('{0[0]}: {0[1]}'.format, sorted(self.items())))
|
| 817 |
+
|
| 818 |
+
def __iter__(self):
|
| 819 |
+
"""Yield sorted list of keys."""
|
| 820 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 821 |
+
yield from sorted(dict.__iter__(self))
|
| 822 |
+
|
| 823 |
+
def __len__(self):
|
| 824 |
+
return dict.__len__(self)
|
| 825 |
+
|
| 826 |
+
def find_all(self, pattern):
|
| 827 |
+
"""
|
| 828 |
+
Return the subset of this RcParams dictionary whose keys match,
|
| 829 |
+
using :func:`re.search`, the given ``pattern``.
|
| 830 |
+
|
| 831 |
+
.. note::
|
| 832 |
+
|
| 833 |
+
Changes to the returned dictionary are *not* propagated to
|
| 834 |
+
the parent RcParams dictionary.
|
| 835 |
+
|
| 836 |
+
"""
|
| 837 |
+
pattern_re = re.compile(pattern)
|
| 838 |
+
return RcParams((key, value)
|
| 839 |
+
for key, value in self.items()
|
| 840 |
+
if pattern_re.search(key))
|
| 841 |
+
|
| 842 |
+
def copy(self):
|
| 843 |
+
"""Copy this RcParams instance."""
|
| 844 |
+
rccopy = RcParams()
|
| 845 |
+
for k in self: # Skip deprecations and revalidation.
|
| 846 |
+
rccopy._set(k, self._get(k))
|
| 847 |
+
return rccopy
|
| 848 |
+
|
| 849 |
+
|
| 850 |
+
def rc_params(fail_on_error=False):
|
| 851 |
+
"""Construct a `RcParams` instance from the default Matplotlib rc file."""
|
| 852 |
+
return rc_params_from_file(matplotlib_fname(), fail_on_error)
|
| 853 |
+
|
| 854 |
+
|
| 855 |
+
@functools.cache
|
| 856 |
+
def _get_ssl_context():
|
| 857 |
+
try:
|
| 858 |
+
import certifi
|
| 859 |
+
except ImportError:
|
| 860 |
+
_log.debug("Could not import certifi.")
|
| 861 |
+
return None
|
| 862 |
+
import ssl
|
| 863 |
+
return ssl.create_default_context(cafile=certifi.where())
|
| 864 |
+
|
| 865 |
+
|
| 866 |
+
@contextlib.contextmanager
|
| 867 |
+
def _open_file_or_url(fname):
|
| 868 |
+
if (isinstance(fname, str)
|
| 869 |
+
and fname.startswith(('http://', 'https://', 'ftp://', 'file:'))):
|
| 870 |
+
import urllib.request
|
| 871 |
+
ssl_ctx = _get_ssl_context()
|
| 872 |
+
if ssl_ctx is None:
|
| 873 |
+
_log.debug(
|
| 874 |
+
"Could not get certifi ssl context, https may not work."
|
| 875 |
+
)
|
| 876 |
+
with urllib.request.urlopen(fname, context=ssl_ctx) as f:
|
| 877 |
+
yield (line.decode('utf-8') for line in f)
|
| 878 |
+
else:
|
| 879 |
+
fname = os.path.expanduser(fname)
|
| 880 |
+
with open(fname, encoding='utf-8') as f:
|
| 881 |
+
yield f
|
| 882 |
+
|
| 883 |
+
|
| 884 |
+
def _rc_params_in_file(fname, transform=lambda x: x, fail_on_error=False):
|
| 885 |
+
"""
|
| 886 |
+
Construct a `RcParams` instance from file *fname*.
|
| 887 |
+
|
| 888 |
+
Unlike `rc_params_from_file`, the configuration class only contains the
|
| 889 |
+
parameters specified in the file (i.e. default values are not filled in).
|
| 890 |
+
|
| 891 |
+
Parameters
|
| 892 |
+
----------
|
| 893 |
+
fname : path-like
|
| 894 |
+
The loaded file.
|
| 895 |
+
transform : callable, default: the identity function
|
| 896 |
+
A function called on each individual line of the file to transform it,
|
| 897 |
+
before further parsing.
|
| 898 |
+
fail_on_error : bool, default: False
|
| 899 |
+
Whether invalid entries should result in an exception or a warning.
|
| 900 |
+
"""
|
| 901 |
+
import matplotlib as mpl
|
| 902 |
+
rc_temp = {}
|
| 903 |
+
with _open_file_or_url(fname) as fd:
|
| 904 |
+
try:
|
| 905 |
+
for line_no, line in enumerate(fd, 1):
|
| 906 |
+
line = transform(line)
|
| 907 |
+
strippedline = cbook._strip_comment(line)
|
| 908 |
+
if not strippedline:
|
| 909 |
+
continue
|
| 910 |
+
tup = strippedline.split(':', 1)
|
| 911 |
+
if len(tup) != 2:
|
| 912 |
+
_log.warning('Missing colon in file %r, line %d (%r)',
|
| 913 |
+
fname, line_no, line.rstrip('\n'))
|
| 914 |
+
continue
|
| 915 |
+
key, val = tup
|
| 916 |
+
key = key.strip()
|
| 917 |
+
val = val.strip()
|
| 918 |
+
if val.startswith('"') and val.endswith('"'):
|
| 919 |
+
val = val[1:-1] # strip double quotes
|
| 920 |
+
if key in rc_temp:
|
| 921 |
+
_log.warning('Duplicate key in file %r, line %d (%r)',
|
| 922 |
+
fname, line_no, line.rstrip('\n'))
|
| 923 |
+
rc_temp[key] = (val, line, line_no)
|
| 924 |
+
except UnicodeDecodeError:
|
| 925 |
+
_log.warning('Cannot decode configuration file %r as utf-8.',
|
| 926 |
+
fname)
|
| 927 |
+
raise
|
| 928 |
+
|
| 929 |
+
config = RcParams()
|
| 930 |
+
|
| 931 |
+
for key, (val, line, line_no) in rc_temp.items():
|
| 932 |
+
if key in rcsetup._validators:
|
| 933 |
+
if fail_on_error:
|
| 934 |
+
config[key] = val # try to convert to proper type or raise
|
| 935 |
+
else:
|
| 936 |
+
try:
|
| 937 |
+
config[key] = val # try to convert to proper type or skip
|
| 938 |
+
except Exception as msg:
|
| 939 |
+
_log.warning('Bad value in file %r, line %d (%r): %s',
|
| 940 |
+
fname, line_no, line.rstrip('\n'), msg)
|
| 941 |
+
elif key in _deprecated_ignore_map:
|
| 942 |
+
version, alt_key = _deprecated_ignore_map[key]
|
| 943 |
+
_api.warn_deprecated(
|
| 944 |
+
version, name=key, alternative=alt_key, obj_type='rcparam',
|
| 945 |
+
addendum="Please update your matplotlibrc.")
|
| 946 |
+
else:
|
| 947 |
+
# __version__ must be looked up as an attribute to trigger the
|
| 948 |
+
# module-level __getattr__.
|
| 949 |
+
version = ('main' if '.post' in mpl.__version__
|
| 950 |
+
else f'v{mpl.__version__}')
|
| 951 |
+
_log.warning("""
|
| 952 |
+
Bad key %(key)s in file %(fname)s, line %(line_no)s (%(line)r)
|
| 953 |
+
You probably need to get an updated matplotlibrc file from
|
| 954 |
+
https://github.com/matplotlib/matplotlib/blob/%(version)s/lib/matplotlib/mpl-data/matplotlibrc
|
| 955 |
+
or from the matplotlib source distribution""",
|
| 956 |
+
dict(key=key, fname=fname, line_no=line_no,
|
| 957 |
+
line=line.rstrip('\n'), version=version))
|
| 958 |
+
return config
|
| 959 |
+
|
| 960 |
+
|
| 961 |
+
def rc_params_from_file(fname, fail_on_error=False, use_default_template=True):
|
| 962 |
+
"""
|
| 963 |
+
Construct a `RcParams` from file *fname*.
|
| 964 |
+
|
| 965 |
+
Parameters
|
| 966 |
+
----------
|
| 967 |
+
fname : str or path-like
|
| 968 |
+
A file with Matplotlib rc settings.
|
| 969 |
+
fail_on_error : bool
|
| 970 |
+
If True, raise an error when the parser fails to convert a parameter.
|
| 971 |
+
use_default_template : bool
|
| 972 |
+
If True, initialize with default parameters before updating with those
|
| 973 |
+
in the given file. If False, the configuration class only contains the
|
| 974 |
+
parameters specified in the file. (Useful for updating dicts.)
|
| 975 |
+
"""
|
| 976 |
+
config_from_file = _rc_params_in_file(fname, fail_on_error=fail_on_error)
|
| 977 |
+
|
| 978 |
+
if not use_default_template:
|
| 979 |
+
return config_from_file
|
| 980 |
+
|
| 981 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 982 |
+
config = RcParams({**rcParamsDefault, **config_from_file})
|
| 983 |
+
|
| 984 |
+
if "".join(config['text.latex.preamble']):
|
| 985 |
+
_log.info("""
|
| 986 |
+
*****************************************************************
|
| 987 |
+
You have the following UNSUPPORTED LaTeX preamble customizations:
|
| 988 |
+
%s
|
| 989 |
+
Please do not ask for support with these customizations active.
|
| 990 |
+
*****************************************************************
|
| 991 |
+
""", '\n'.join(config['text.latex.preamble']))
|
| 992 |
+
_log.debug('loaded rc file %s', fname)
|
| 993 |
+
|
| 994 |
+
return config
|
| 995 |
+
|
| 996 |
+
|
| 997 |
+
rcParamsDefault = _rc_params_in_file(
|
| 998 |
+
cbook._get_data_path("matplotlibrc"),
|
| 999 |
+
# Strip leading comment.
|
| 1000 |
+
transform=lambda line: line[1:] if line.startswith("#") else line,
|
| 1001 |
+
fail_on_error=True)
|
| 1002 |
+
rcParamsDefault._update_raw(rcsetup._hardcoded_defaults)
|
| 1003 |
+
rcParamsDefault._ensure_has_backend()
|
| 1004 |
+
|
| 1005 |
+
rcParams = RcParams() # The global instance.
|
| 1006 |
+
rcParams._update_raw(rcParamsDefault)
|
| 1007 |
+
rcParams._update_raw(_rc_params_in_file(matplotlib_fname()))
|
| 1008 |
+
rcParamsOrig = rcParams.copy()
|
| 1009 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1010 |
+
# This also checks that all rcParams are indeed listed in the template.
|
| 1011 |
+
# Assigning to rcsetup.defaultParams is left only for backcompat.
|
| 1012 |
+
defaultParams = rcsetup.defaultParams = {
|
| 1013 |
+
# We want to resolve deprecated rcParams, but not backend...
|
| 1014 |
+
key: [(rcsetup._auto_backend_sentinel if key == "backend" else
|
| 1015 |
+
rcParamsDefault[key]),
|
| 1016 |
+
validator]
|
| 1017 |
+
for key, validator in rcsetup._validators.items()}
|
| 1018 |
+
if rcParams['axes.formatter.use_locale']:
|
| 1019 |
+
locale.setlocale(locale.LC_ALL, '')
|
| 1020 |
+
|
| 1021 |
+
|
| 1022 |
+
def rc(group, **kwargs):
|
| 1023 |
+
"""
|
| 1024 |
+
Set the current `.rcParams`. *group* is the grouping for the rc, e.g.,
|
| 1025 |
+
for ``lines.linewidth`` the group is ``lines``, for
|
| 1026 |
+
``axes.facecolor``, the group is ``axes``, and so on. Group may
|
| 1027 |
+
also be a list or tuple of group names, e.g., (*xtick*, *ytick*).
|
| 1028 |
+
*kwargs* is a dictionary attribute name/value pairs, e.g.,::
|
| 1029 |
+
|
| 1030 |
+
rc('lines', linewidth=2, color='r')
|
| 1031 |
+
|
| 1032 |
+
sets the current `.rcParams` and is equivalent to::
|
| 1033 |
+
|
| 1034 |
+
rcParams['lines.linewidth'] = 2
|
| 1035 |
+
rcParams['lines.color'] = 'r'
|
| 1036 |
+
|
| 1037 |
+
The following aliases are available to save typing for interactive users:
|
| 1038 |
+
|
| 1039 |
+
===== =================
|
| 1040 |
+
Alias Property
|
| 1041 |
+
===== =================
|
| 1042 |
+
'lw' 'linewidth'
|
| 1043 |
+
'ls' 'linestyle'
|
| 1044 |
+
'c' 'color'
|
| 1045 |
+
'fc' 'facecolor'
|
| 1046 |
+
'ec' 'edgecolor'
|
| 1047 |
+
'mew' 'markeredgewidth'
|
| 1048 |
+
'aa' 'antialiased'
|
| 1049 |
+
===== =================
|
| 1050 |
+
|
| 1051 |
+
Thus you could abbreviate the above call as::
|
| 1052 |
+
|
| 1053 |
+
rc('lines', lw=2, c='r')
|
| 1054 |
+
|
| 1055 |
+
Note you can use python's kwargs dictionary facility to store
|
| 1056 |
+
dictionaries of default parameters. e.g., you can customize the
|
| 1057 |
+
font rc as follows::
|
| 1058 |
+
|
| 1059 |
+
font = {'family' : 'monospace',
|
| 1060 |
+
'weight' : 'bold',
|
| 1061 |
+
'size' : 'larger'}
|
| 1062 |
+
rc('font', **font) # pass in the font dict as kwargs
|
| 1063 |
+
|
| 1064 |
+
This enables you to easily switch between several configurations. Use
|
| 1065 |
+
``matplotlib.style.use('default')`` or :func:`~matplotlib.rcdefaults` to
|
| 1066 |
+
restore the default `.rcParams` after changes.
|
| 1067 |
+
|
| 1068 |
+
Notes
|
| 1069 |
+
-----
|
| 1070 |
+
Similar functionality is available by using the normal dict interface, i.e.
|
| 1071 |
+
``rcParams.update({"lines.linewidth": 2, ...})`` (but ``rcParams.update``
|
| 1072 |
+
does not support abbreviations or grouping).
|
| 1073 |
+
"""
|
| 1074 |
+
|
| 1075 |
+
aliases = {
|
| 1076 |
+
'lw': 'linewidth',
|
| 1077 |
+
'ls': 'linestyle',
|
| 1078 |
+
'c': 'color',
|
| 1079 |
+
'fc': 'facecolor',
|
| 1080 |
+
'ec': 'edgecolor',
|
| 1081 |
+
'mew': 'markeredgewidth',
|
| 1082 |
+
'aa': 'antialiased',
|
| 1083 |
+
}
|
| 1084 |
+
|
| 1085 |
+
if isinstance(group, str):
|
| 1086 |
+
group = (group,)
|
| 1087 |
+
for g in group:
|
| 1088 |
+
for k, v in kwargs.items():
|
| 1089 |
+
name = aliases.get(k) or k
|
| 1090 |
+
key = f'{g}.{name}'
|
| 1091 |
+
try:
|
| 1092 |
+
rcParams[key] = v
|
| 1093 |
+
except KeyError as err:
|
| 1094 |
+
raise KeyError(('Unrecognized key "%s" for group "%s" and '
|
| 1095 |
+
'name "%s"') % (key, g, name)) from err
|
| 1096 |
+
|
| 1097 |
+
|
| 1098 |
+
def rcdefaults():
|
| 1099 |
+
"""
|
| 1100 |
+
Restore the `.rcParams` from Matplotlib's internal default style.
|
| 1101 |
+
|
| 1102 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1103 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1104 |
+
|
| 1105 |
+
See Also
|
| 1106 |
+
--------
|
| 1107 |
+
matplotlib.rc_file_defaults
|
| 1108 |
+
Restore the `.rcParams` from the rc file originally loaded by
|
| 1109 |
+
Matplotlib.
|
| 1110 |
+
matplotlib.style.use
|
| 1111 |
+
Use a specific style file. Call ``style.use('default')`` to restore
|
| 1112 |
+
the default style.
|
| 1113 |
+
"""
|
| 1114 |
+
# Deprecation warnings were already handled when creating rcParamsDefault,
|
| 1115 |
+
# no need to reemit them here.
|
| 1116 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1117 |
+
from .style.core import STYLE_BLACKLIST
|
| 1118 |
+
rcParams.clear()
|
| 1119 |
+
rcParams.update({k: v for k, v in rcParamsDefault.items()
|
| 1120 |
+
if k not in STYLE_BLACKLIST})
|
| 1121 |
+
|
| 1122 |
+
|
| 1123 |
+
def rc_file_defaults():
|
| 1124 |
+
"""
|
| 1125 |
+
Restore the `.rcParams` from the original rc file loaded by Matplotlib.
|
| 1126 |
+
|
| 1127 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1128 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1129 |
+
"""
|
| 1130 |
+
# Deprecation warnings were already handled when creating rcParamsOrig, no
|
| 1131 |
+
# need to reemit them here.
|
| 1132 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1133 |
+
from .style.core import STYLE_BLACKLIST
|
| 1134 |
+
rcParams.update({k: rcParamsOrig[k] for k in rcParamsOrig
|
| 1135 |
+
if k not in STYLE_BLACKLIST})
|
| 1136 |
+
|
| 1137 |
+
|
| 1138 |
+
def rc_file(fname, *, use_default_template=True):
|
| 1139 |
+
"""
|
| 1140 |
+
Update `.rcParams` from file.
|
| 1141 |
+
|
| 1142 |
+
Style-blacklisted `.rcParams` (defined in
|
| 1143 |
+
``matplotlib.style.core.STYLE_BLACKLIST``) are not updated.
|
| 1144 |
+
|
| 1145 |
+
Parameters
|
| 1146 |
+
----------
|
| 1147 |
+
fname : str or path-like
|
| 1148 |
+
A file with Matplotlib rc settings.
|
| 1149 |
+
|
| 1150 |
+
use_default_template : bool
|
| 1151 |
+
If True, initialize with default parameters before updating with those
|
| 1152 |
+
in the given file. If False, the current configuration persists
|
| 1153 |
+
and only the parameters specified in the file are updated.
|
| 1154 |
+
"""
|
| 1155 |
+
# Deprecation warnings were already handled in rc_params_from_file, no need
|
| 1156 |
+
# to reemit them here.
|
| 1157 |
+
with _api.suppress_matplotlib_deprecation_warning():
|
| 1158 |
+
from .style.core import STYLE_BLACKLIST
|
| 1159 |
+
rc_from_file = rc_params_from_file(
|
| 1160 |
+
fname, use_default_template=use_default_template)
|
| 1161 |
+
rcParams.update({k: rc_from_file[k] for k in rc_from_file
|
| 1162 |
+
if k not in STYLE_BLACKLIST})
|
| 1163 |
+
|
| 1164 |
+
|
| 1165 |
+
@contextlib.contextmanager
|
| 1166 |
+
def rc_context(rc=None, fname=None):
|
| 1167 |
+
"""
|
| 1168 |
+
Return a context manager for temporarily changing rcParams.
|
| 1169 |
+
|
| 1170 |
+
The :rc:`backend` will not be reset by the context manager.
|
| 1171 |
+
|
| 1172 |
+
rcParams changed both through the context manager invocation and
|
| 1173 |
+
in the body of the context will be reset on context exit.
|
| 1174 |
+
|
| 1175 |
+
Parameters
|
| 1176 |
+
----------
|
| 1177 |
+
rc : dict
|
| 1178 |
+
The rcParams to temporarily set.
|
| 1179 |
+
fname : str or path-like
|
| 1180 |
+
A file with Matplotlib rc settings. If both *fname* and *rc* are given,
|
| 1181 |
+
settings from *rc* take precedence.
|
| 1182 |
+
|
| 1183 |
+
See Also
|
| 1184 |
+
--------
|
| 1185 |
+
:ref:`customizing-with-matplotlibrc-files`
|
| 1186 |
+
|
| 1187 |
+
Examples
|
| 1188 |
+
--------
|
| 1189 |
+
Passing explicit values via a dict::
|
| 1190 |
+
|
| 1191 |
+
with mpl.rc_context({'interactive': False}):
|
| 1192 |
+
fig, ax = plt.subplots()
|
| 1193 |
+
ax.plot(range(3), range(3))
|
| 1194 |
+
fig.savefig('example.png')
|
| 1195 |
+
plt.close(fig)
|
| 1196 |
+
|
| 1197 |
+
Loading settings from a file::
|
| 1198 |
+
|
| 1199 |
+
with mpl.rc_context(fname='print.rc'):
|
| 1200 |
+
plt.plot(x, y) # uses 'print.rc'
|
| 1201 |
+
|
| 1202 |
+
Setting in the context body::
|
| 1203 |
+
|
| 1204 |
+
with mpl.rc_context():
|
| 1205 |
+
# will be reset
|
| 1206 |
+
mpl.rcParams['lines.linewidth'] = 5
|
| 1207 |
+
plt.plot(x, y)
|
| 1208 |
+
|
| 1209 |
+
"""
|
| 1210 |
+
orig = dict(rcParams.copy())
|
| 1211 |
+
del orig['backend']
|
| 1212 |
+
try:
|
| 1213 |
+
if fname:
|
| 1214 |
+
rc_file(fname)
|
| 1215 |
+
if rc:
|
| 1216 |
+
rcParams.update(rc)
|
| 1217 |
+
yield
|
| 1218 |
+
finally:
|
| 1219 |
+
rcParams._update_raw(orig) # Revert to the original rcs.
|
| 1220 |
+
|
| 1221 |
+
|
| 1222 |
+
def use(backend, *, force=True):
|
| 1223 |
+
"""
|
| 1224 |
+
Select the backend used for rendering and GUI integration.
|
| 1225 |
+
|
| 1226 |
+
If pyplot is already imported, `~matplotlib.pyplot.switch_backend` is used
|
| 1227 |
+
and if the new backend is different than the current backend, all Figures
|
| 1228 |
+
will be closed.
|
| 1229 |
+
|
| 1230 |
+
Parameters
|
| 1231 |
+
----------
|
| 1232 |
+
backend : str
|
| 1233 |
+
The backend to switch to. This can either be one of the standard
|
| 1234 |
+
backend names, which are case-insensitive:
|
| 1235 |
+
|
| 1236 |
+
- interactive backends:
|
| 1237 |
+
GTK3Agg, GTK3Cairo, GTK4Agg, GTK4Cairo, MacOSX, nbAgg, notebook, QtAgg,
|
| 1238 |
+
QtCairo, TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo, Qt5Agg, Qt5Cairo
|
| 1239 |
+
|
| 1240 |
+
- non-interactive backends:
|
| 1241 |
+
agg, cairo, pdf, pgf, ps, svg, template
|
| 1242 |
+
|
| 1243 |
+
or a string of the form: ``module://my.module.name``.
|
| 1244 |
+
|
| 1245 |
+
notebook is a synonym for nbAgg.
|
| 1246 |
+
|
| 1247 |
+
Switching to an interactive backend is not possible if an unrelated
|
| 1248 |
+
event loop has already been started (e.g., switching to GTK3Agg if a
|
| 1249 |
+
TkAgg window has already been opened). Switching to a non-interactive
|
| 1250 |
+
backend is always possible.
|
| 1251 |
+
|
| 1252 |
+
force : bool, default: True
|
| 1253 |
+
If True (the default), raise an `ImportError` if the backend cannot be
|
| 1254 |
+
set up (either because it fails to import, or because an incompatible
|
| 1255 |
+
GUI interactive framework is already running); if False, silently
|
| 1256 |
+
ignore the failure.
|
| 1257 |
+
|
| 1258 |
+
See Also
|
| 1259 |
+
--------
|
| 1260 |
+
:ref:`backends`
|
| 1261 |
+
matplotlib.get_backend
|
| 1262 |
+
matplotlib.pyplot.switch_backend
|
| 1263 |
+
|
| 1264 |
+
"""
|
| 1265 |
+
name = rcsetup.validate_backend(backend)
|
| 1266 |
+
# don't (prematurely) resolve the "auto" backend setting
|
| 1267 |
+
if rcParams._get_backend_or_none() == name:
|
| 1268 |
+
# Nothing to do if the requested backend is already set
|
| 1269 |
+
pass
|
| 1270 |
+
else:
|
| 1271 |
+
# if pyplot is not already imported, do not import it. Doing
|
| 1272 |
+
# so may trigger a `plt.switch_backend` to the _default_ backend
|
| 1273 |
+
# before we get a chance to change to the one the user just requested
|
| 1274 |
+
plt = sys.modules.get('matplotlib.pyplot')
|
| 1275 |
+
# if pyplot is imported, then try to change backends
|
| 1276 |
+
if plt is not None:
|
| 1277 |
+
try:
|
| 1278 |
+
# we need this import check here to re-raise if the
|
| 1279 |
+
# user does not have the libraries to support their
|
| 1280 |
+
# chosen backend installed.
|
| 1281 |
+
plt.switch_backend(name)
|
| 1282 |
+
except ImportError:
|
| 1283 |
+
if force:
|
| 1284 |
+
raise
|
| 1285 |
+
# if we have not imported pyplot, then we can set the rcParam
|
| 1286 |
+
# value which will be respected when the user finally imports
|
| 1287 |
+
# pyplot
|
| 1288 |
+
else:
|
| 1289 |
+
rcParams['backend'] = backend
|
| 1290 |
+
# if the user has asked for a given backend, do not helpfully
|
| 1291 |
+
# fallback
|
| 1292 |
+
rcParams['backend_fallback'] = False
|
| 1293 |
+
|
| 1294 |
+
|
| 1295 |
+
if os.environ.get('MPLBACKEND'):
|
| 1296 |
+
rcParams['backend'] = os.environ.get('MPLBACKEND')
|
| 1297 |
+
|
| 1298 |
+
|
| 1299 |
+
def get_backend(*, auto_select=True):
|
| 1300 |
+
"""
|
| 1301 |
+
Return the name of the current backend.
|
| 1302 |
+
|
| 1303 |
+
Parameters
|
| 1304 |
+
----------
|
| 1305 |
+
auto_select : bool, default: True
|
| 1306 |
+
Whether to trigger backend resolution if no backend has been
|
| 1307 |
+
selected so far. If True, this ensures that a valid backend
|
| 1308 |
+
is returned. If False, this returns None if no backend has been
|
| 1309 |
+
selected so far.
|
| 1310 |
+
|
| 1311 |
+
.. versionadded:: 3.10
|
| 1312 |
+
|
| 1313 |
+
.. admonition:: Provisional
|
| 1314 |
+
|
| 1315 |
+
The *auto_select* flag is provisional. It may be changed or removed
|
| 1316 |
+
without prior warning.
|
| 1317 |
+
|
| 1318 |
+
See Also
|
| 1319 |
+
--------
|
| 1320 |
+
matplotlib.use
|
| 1321 |
+
"""
|
| 1322 |
+
if auto_select:
|
| 1323 |
+
return rcParams['backend']
|
| 1324 |
+
else:
|
| 1325 |
+
backend = rcParams._get('backend')
|
| 1326 |
+
if backend is rcsetup._auto_backend_sentinel:
|
| 1327 |
+
return None
|
| 1328 |
+
else:
|
| 1329 |
+
return backend
|
| 1330 |
+
|
| 1331 |
+
|
| 1332 |
+
def interactive(b):
|
| 1333 |
+
"""
|
| 1334 |
+
Set whether to redraw after every plotting command (e.g. `.pyplot.xlabel`).
|
| 1335 |
+
"""
|
| 1336 |
+
rcParams['interactive'] = b
|
| 1337 |
+
|
| 1338 |
+
|
| 1339 |
+
def is_interactive():
|
| 1340 |
+
"""
|
| 1341 |
+
Return whether to redraw after every plotting command.
|
| 1342 |
+
|
| 1343 |
+
.. note::
|
| 1344 |
+
|
| 1345 |
+
This function is only intended for use in backends. End users should
|
| 1346 |
+
use `.pyplot.isinteractive` instead.
|
| 1347 |
+
"""
|
| 1348 |
+
return rcParams['interactive']
|
| 1349 |
+
|
| 1350 |
+
|
| 1351 |
+
def _val_or_rc(val, rc_name):
|
| 1352 |
+
"""
|
| 1353 |
+
If *val* is None, return ``mpl.rcParams[rc_name]``, otherwise return val.
|
| 1354 |
+
"""
|
| 1355 |
+
return val if val is not None else rcParams[rc_name]
|
| 1356 |
+
|
| 1357 |
+
|
| 1358 |
+
def _init_tests():
|
| 1359 |
+
# The version of FreeType to install locally for running the tests. This must match
|
| 1360 |
+
# the value in `meson.build`.
|
| 1361 |
+
LOCAL_FREETYPE_VERSION = '2.6.1'
|
| 1362 |
+
|
| 1363 |
+
from matplotlib import ft2font
|
| 1364 |
+
if (ft2font.__freetype_version__ != LOCAL_FREETYPE_VERSION or
|
| 1365 |
+
ft2font.__freetype_build_type__ != 'local'):
|
| 1366 |
+
_log.warning(
|
| 1367 |
+
"Matplotlib is not built with the correct FreeType version to run tests. "
|
| 1368 |
+
"Rebuild without setting system-freetype=true in Meson setup options. "
|
| 1369 |
+
"Expect many image comparison failures below. "
|
| 1370 |
+
"Expected freetype version %s. "
|
| 1371 |
+
"Found freetype version %s. "
|
| 1372 |
+
"Freetype build type is %slocal.",
|
| 1373 |
+
LOCAL_FREETYPE_VERSION,
|
| 1374 |
+
ft2font.__freetype_version__,
|
| 1375 |
+
"" if ft2font.__freetype_build_type__ == 'local' else "not ")
|
| 1376 |
+
|
| 1377 |
+
|
| 1378 |
+
def _replacer(data, value):
|
| 1379 |
+
"""
|
| 1380 |
+
Either returns ``data[value]`` or passes ``data`` back, converts either to
|
| 1381 |
+
a sequence.
|
| 1382 |
+
"""
|
| 1383 |
+
try:
|
| 1384 |
+
# if key isn't a string don't bother
|
| 1385 |
+
if isinstance(value, str):
|
| 1386 |
+
# try to use __getitem__
|
| 1387 |
+
value = data[value]
|
| 1388 |
+
except Exception:
|
| 1389 |
+
# key does not exist, silently fall back to key
|
| 1390 |
+
pass
|
| 1391 |
+
return cbook.sanitize_sequence(value)
|
| 1392 |
+
|
| 1393 |
+
|
| 1394 |
+
def _label_from_arg(y, default_name):
|
| 1395 |
+
try:
|
| 1396 |
+
return y.name
|
| 1397 |
+
except AttributeError:
|
| 1398 |
+
if isinstance(default_name, str):
|
| 1399 |
+
return default_name
|
| 1400 |
+
return None
|
| 1401 |
+
|
| 1402 |
+
|
| 1403 |
+
def _add_data_doc(docstring, replace_names):
|
| 1404 |
+
"""
|
| 1405 |
+
Add documentation for a *data* field to the given docstring.
|
| 1406 |
+
|
| 1407 |
+
Parameters
|
| 1408 |
+
----------
|
| 1409 |
+
docstring : str
|
| 1410 |
+
The input docstring.
|
| 1411 |
+
replace_names : list of str or None
|
| 1412 |
+
The list of parameter names which arguments should be replaced by
|
| 1413 |
+
``data[name]`` (if ``data[name]`` does not throw an exception). If
|
| 1414 |
+
None, replacement is attempted for all arguments.
|
| 1415 |
+
|
| 1416 |
+
Returns
|
| 1417 |
+
-------
|
| 1418 |
+
str
|
| 1419 |
+
The augmented docstring.
|
| 1420 |
+
"""
|
| 1421 |
+
if (docstring is None
|
| 1422 |
+
or replace_names is not None and len(replace_names) == 0):
|
| 1423 |
+
return docstring
|
| 1424 |
+
docstring = inspect.cleandoc(docstring)
|
| 1425 |
+
|
| 1426 |
+
data_doc = ("""\
|
| 1427 |
+
If given, all parameters also accept a string ``s``, which is
|
| 1428 |
+
interpreted as ``data[s]`` if ``s`` is a key in ``data``."""
|
| 1429 |
+
if replace_names is None else f"""\
|
| 1430 |
+
If given, the following parameters also accept a string ``s``, which is
|
| 1431 |
+
interpreted as ``data[s]`` if ``s`` is a key in ``data``:
|
| 1432 |
+
|
| 1433 |
+
{', '.join(map('*{}*'.format, replace_names))}""")
|
| 1434 |
+
# using string replacement instead of formatting has the advantages
|
| 1435 |
+
# 1) simpler indent handling
|
| 1436 |
+
# 2) prevent problems with formatting characters '{', '%' in the docstring
|
| 1437 |
+
if _log.level <= logging.DEBUG:
|
| 1438 |
+
# test_data_parameter_replacement() tests against these log messages
|
| 1439 |
+
# make sure to keep message and test in sync
|
| 1440 |
+
if "data : indexable object, optional" not in docstring:
|
| 1441 |
+
_log.debug("data parameter docstring error: no data parameter")
|
| 1442 |
+
if 'DATA_PARAMETER_PLACEHOLDER' not in docstring:
|
| 1443 |
+
_log.debug("data parameter docstring error: missing placeholder")
|
| 1444 |
+
return docstring.replace(' DATA_PARAMETER_PLACEHOLDER', data_doc)
|
| 1445 |
+
|
| 1446 |
+
|
| 1447 |
+
def _preprocess_data(func=None, *, replace_names=None, label_namer=None):
|
| 1448 |
+
"""
|
| 1449 |
+
A decorator to add a 'data' kwarg to a function.
|
| 1450 |
+
|
| 1451 |
+
When applied::
|
| 1452 |
+
|
| 1453 |
+
@_preprocess_data()
|
| 1454 |
+
def func(ax, *args, **kwargs): ...
|
| 1455 |
+
|
| 1456 |
+
the signature is modified to ``decorated(ax, *args, data=None, **kwargs)``
|
| 1457 |
+
with the following behavior:
|
| 1458 |
+
|
| 1459 |
+
- if called with ``data=None``, forward the other arguments to ``func``;
|
| 1460 |
+
- otherwise, *data* must be a mapping; for any argument passed in as a
|
| 1461 |
+
string ``name``, replace the argument by ``data[name]`` (if this does not
|
| 1462 |
+
throw an exception), then forward the arguments to ``func``.
|
| 1463 |
+
|
| 1464 |
+
In either case, any argument that is a `MappingView` is also converted to a
|
| 1465 |
+
list.
|
| 1466 |
+
|
| 1467 |
+
Parameters
|
| 1468 |
+
----------
|
| 1469 |
+
replace_names : list of str or None, default: None
|
| 1470 |
+
The list of parameter names for which lookup into *data* should be
|
| 1471 |
+
attempted. If None, replacement is attempted for all arguments.
|
| 1472 |
+
label_namer : str, default: None
|
| 1473 |
+
If set e.g. to "namer" (which must be a kwarg in the function's
|
| 1474 |
+
signature -- not as ``**kwargs``), if the *namer* argument passed in is
|
| 1475 |
+
a (string) key of *data* and no *label* kwarg is passed, then use the
|
| 1476 |
+
(string) value of the *namer* as *label*. ::
|
| 1477 |
+
|
| 1478 |
+
@_preprocess_data(label_namer="foo")
|
| 1479 |
+
def func(foo, label=None): ...
|
| 1480 |
+
|
| 1481 |
+
func("key", data={"key": value})
|
| 1482 |
+
# is equivalent to
|
| 1483 |
+
func.__wrapped__(value, label="key")
|
| 1484 |
+
"""
|
| 1485 |
+
|
| 1486 |
+
if func is None: # Return the actual decorator.
|
| 1487 |
+
return functools.partial(
|
| 1488 |
+
_preprocess_data,
|
| 1489 |
+
replace_names=replace_names, label_namer=label_namer)
|
| 1490 |
+
|
| 1491 |
+
sig = inspect.signature(func)
|
| 1492 |
+
varargs_name = None
|
| 1493 |
+
varkwargs_name = None
|
| 1494 |
+
arg_names = []
|
| 1495 |
+
params = list(sig.parameters.values())
|
| 1496 |
+
for p in params:
|
| 1497 |
+
if p.kind is Parameter.VAR_POSITIONAL:
|
| 1498 |
+
varargs_name = p.name
|
| 1499 |
+
elif p.kind is Parameter.VAR_KEYWORD:
|
| 1500 |
+
varkwargs_name = p.name
|
| 1501 |
+
else:
|
| 1502 |
+
arg_names.append(p.name)
|
| 1503 |
+
data_param = Parameter("data", Parameter.KEYWORD_ONLY, default=None)
|
| 1504 |
+
if varkwargs_name:
|
| 1505 |
+
params.insert(-1, data_param)
|
| 1506 |
+
else:
|
| 1507 |
+
params.append(data_param)
|
| 1508 |
+
new_sig = sig.replace(parameters=params)
|
| 1509 |
+
arg_names = arg_names[1:] # remove the first "ax" / self arg
|
| 1510 |
+
|
| 1511 |
+
assert {*arg_names}.issuperset(replace_names or []) or varkwargs_name, (
|
| 1512 |
+
"Matplotlib internal error: invalid replace_names "
|
| 1513 |
+
f"({replace_names!r}) for {func.__name__!r}")
|
| 1514 |
+
assert label_namer is None or label_namer in arg_names, (
|
| 1515 |
+
"Matplotlib internal error: invalid label_namer "
|
| 1516 |
+
f"({label_namer!r}) for {func.__name__!r}")
|
| 1517 |
+
|
| 1518 |
+
@functools.wraps(func)
|
| 1519 |
+
def inner(ax, *args, data=None, **kwargs):
|
| 1520 |
+
if data is None:
|
| 1521 |
+
return func(
|
| 1522 |
+
ax,
|
| 1523 |
+
*map(cbook.sanitize_sequence, args),
|
| 1524 |
+
**{k: cbook.sanitize_sequence(v) for k, v in kwargs.items()})
|
| 1525 |
+
|
| 1526 |
+
bound = new_sig.bind(ax, *args, **kwargs)
|
| 1527 |
+
auto_label = (bound.arguments.get(label_namer)
|
| 1528 |
+
or bound.kwargs.get(label_namer))
|
| 1529 |
+
|
| 1530 |
+
for k, v in bound.arguments.items():
|
| 1531 |
+
if k == varkwargs_name:
|
| 1532 |
+
for k1, v1 in v.items():
|
| 1533 |
+
if replace_names is None or k1 in replace_names:
|
| 1534 |
+
v[k1] = _replacer(data, v1)
|
| 1535 |
+
elif k == varargs_name:
|
| 1536 |
+
if replace_names is None:
|
| 1537 |
+
bound.arguments[k] = tuple(_replacer(data, v1) for v1 in v)
|
| 1538 |
+
else:
|
| 1539 |
+
if replace_names is None or k in replace_names:
|
| 1540 |
+
bound.arguments[k] = _replacer(data, v)
|
| 1541 |
+
|
| 1542 |
+
new_args = bound.args
|
| 1543 |
+
new_kwargs = bound.kwargs
|
| 1544 |
+
|
| 1545 |
+
args_and_kwargs = {**bound.arguments, **bound.kwargs}
|
| 1546 |
+
if label_namer and "label" not in args_and_kwargs:
|
| 1547 |
+
new_kwargs["label"] = _label_from_arg(
|
| 1548 |
+
args_and_kwargs.get(label_namer), auto_label)
|
| 1549 |
+
|
| 1550 |
+
return func(*new_args, **new_kwargs)
|
| 1551 |
+
|
| 1552 |
+
inner.__doc__ = _add_data_doc(inner.__doc__, replace_names)
|
| 1553 |
+
inner.__signature__ = new_sig
|
| 1554 |
+
return inner
|
| 1555 |
+
|
| 1556 |
+
|
| 1557 |
+
_log.debug('interactive is %s', is_interactive())
|
| 1558 |
+
_log.debug('platform is %s', sys.platform)
|
| 1559 |
+
|
| 1560 |
+
|
| 1561 |
+
@_api.deprecated("3.10", alternative="matplotlib.cbook.sanitize_sequence")
|
| 1562 |
+
def sanitize_sequence(data):
|
| 1563 |
+
return cbook.sanitize_sequence(data)
|
| 1564 |
+
|
| 1565 |
+
|
| 1566 |
+
@_api.deprecated("3.10", alternative="matplotlib.rcsetup.validate_backend")
|
| 1567 |
+
def validate_backend(s):
|
| 1568 |
+
return rcsetup.validate_backend(s)
|
| 1569 |
+
|
| 1570 |
+
|
| 1571 |
+
# workaround: we must defer colormaps import to after loading rcParams, because
|
| 1572 |
+
# colormap creation depends on rcParams
|
| 1573 |
+
from matplotlib.cm import _colormaps as colormaps # noqa: E402
|
| 1574 |
+
from matplotlib.cm import _multivar_colormaps as multivar_colormaps # noqa: E402
|
| 1575 |
+
from matplotlib.cm import _bivar_colormaps as bivar_colormaps # noqa: E402
|
| 1576 |
+
from matplotlib.colors import _color_sequences as color_sequences # noqa: E402
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/_c_internal_utils.pyi
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def display_is_valid() -> bool: ...
|
| 2 |
+
def xdisplay_is_valid() -> bool: ...
|
| 3 |
+
|
| 4 |
+
def Win32_GetForegroundWindow() -> int | None: ...
|
| 5 |
+
def Win32_SetForegroundWindow(hwnd: int) -> None: ...
|
| 6 |
+
def Win32_SetProcessDpiAwareness_max() -> None: ...
|
| 7 |
+
def Win32_SetCurrentProcessExplicitAppUserModelID(appid: str) -> None: ...
|
| 8 |
+
def Win32_GetCurrentProcessExplicitAppUserModelID() -> str | None: ...
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib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|
|
|
|
|
|
|
| 1 |
+
# auto-generated by https://github.com/trygvrad/multivariate_colormaps
|
| 2 |
+
# date: 2024-05-28
|
| 3 |
+
|
| 4 |
+
from .colors import LinearSegmentedColormap, MultivarColormap
|
| 5 |
+
import matplotlib as mpl
|
| 6 |
+
_LUTSIZE = mpl.rcParams['image.lut']
|
| 7 |
+
|
| 8 |
+
_2VarAddA0_data = [[0.000, 0.000, 0.000],
|
| 9 |
+
[0.020, 0.026, 0.031],
|
| 10 |
+
[0.049, 0.068, 0.085],
|
| 11 |
+
[0.075, 0.107, 0.135],
|
| 12 |
+
[0.097, 0.144, 0.183],
|
| 13 |
+
[0.116, 0.178, 0.231],
|
| 14 |
+
[0.133, 0.212, 0.279],
|
| 15 |
+
[0.148, 0.244, 0.326],
|
| 16 |
+
[0.161, 0.276, 0.374],
|
| 17 |
+
[0.173, 0.308, 0.422],
|
| 18 |
+
[0.182, 0.339, 0.471],
|
| 19 |
+
[0.190, 0.370, 0.521],
|
| 20 |
+
[0.197, 0.400, 0.572],
|
| 21 |
+
[0.201, 0.431, 0.623],
|
| 22 |
+
[0.204, 0.461, 0.675],
|
| 23 |
+
[0.204, 0.491, 0.728],
|
| 24 |
+
[0.202, 0.520, 0.783],
|
| 25 |
+
[0.197, 0.549, 0.838],
|
| 26 |
+
[0.187, 0.577, 0.895]]
|
| 27 |
+
|
| 28 |
+
_2VarAddA1_data = [[0.000, 0.000, 0.000],
|
| 29 |
+
[0.030, 0.023, 0.018],
|
| 30 |
+
[0.079, 0.060, 0.043],
|
| 31 |
+
[0.125, 0.093, 0.065],
|
| 32 |
+
[0.170, 0.123, 0.083],
|
| 33 |
+
[0.213, 0.151, 0.098],
|
| 34 |
+
[0.255, 0.177, 0.110],
|
| 35 |
+
[0.298, 0.202, 0.120],
|
| 36 |
+
[0.341, 0.226, 0.128],
|
| 37 |
+
[0.384, 0.249, 0.134],
|
| 38 |
+
[0.427, 0.271, 0.138],
|
| 39 |
+
[0.472, 0.292, 0.141],
|
| 40 |
+
[0.517, 0.313, 0.142],
|
| 41 |
+
[0.563, 0.333, 0.141],
|
| 42 |
+
[0.610, 0.353, 0.139],
|
| 43 |
+
[0.658, 0.372, 0.134],
|
| 44 |
+
[0.708, 0.390, 0.127],
|
| 45 |
+
[0.759, 0.407, 0.118],
|
| 46 |
+
[0.813, 0.423, 0.105]]
|
| 47 |
+
|
| 48 |
+
_2VarSubA0_data = [[1.000, 1.000, 1.000],
|
| 49 |
+
[0.959, 0.973, 0.986],
|
| 50 |
+
[0.916, 0.948, 0.974],
|
| 51 |
+
[0.874, 0.923, 0.965],
|
| 52 |
+
[0.832, 0.899, 0.956],
|
| 53 |
+
[0.790, 0.875, 0.948],
|
| 54 |
+
[0.748, 0.852, 0.940],
|
| 55 |
+
[0.707, 0.829, 0.934],
|
| 56 |
+
[0.665, 0.806, 0.927],
|
| 57 |
+
[0.624, 0.784, 0.921],
|
| 58 |
+
[0.583, 0.762, 0.916],
|
| 59 |
+
[0.541, 0.740, 0.910],
|
| 60 |
+
[0.500, 0.718, 0.905],
|
| 61 |
+
[0.457, 0.697, 0.901],
|
| 62 |
+
[0.414, 0.675, 0.896],
|
| 63 |
+
[0.369, 0.652, 0.892],
|
| 64 |
+
[0.320, 0.629, 0.888],
|
| 65 |
+
[0.266, 0.604, 0.884],
|
| 66 |
+
[0.199, 0.574, 0.881]]
|
| 67 |
+
|
| 68 |
+
_2VarSubA1_data = [[1.000, 1.000, 1.000],
|
| 69 |
+
[0.982, 0.967, 0.955],
|
| 70 |
+
[0.966, 0.935, 0.908],
|
| 71 |
+
[0.951, 0.902, 0.860],
|
| 72 |
+
[0.937, 0.870, 0.813],
|
| 73 |
+
[0.923, 0.838, 0.765],
|
| 74 |
+
[0.910, 0.807, 0.718],
|
| 75 |
+
[0.898, 0.776, 0.671],
|
| 76 |
+
[0.886, 0.745, 0.624],
|
| 77 |
+
[0.874, 0.714, 0.577],
|
| 78 |
+
[0.862, 0.683, 0.530],
|
| 79 |
+
[0.851, 0.653, 0.483],
|
| 80 |
+
[0.841, 0.622, 0.435],
|
| 81 |
+
[0.831, 0.592, 0.388],
|
| 82 |
+
[0.822, 0.561, 0.340],
|
| 83 |
+
[0.813, 0.530, 0.290],
|
| 84 |
+
[0.806, 0.498, 0.239],
|
| 85 |
+
[0.802, 0.464, 0.184],
|
| 86 |
+
[0.801, 0.426, 0.119]]
|
| 87 |
+
|
| 88 |
+
_3VarAddA0_data = [[0.000, 0.000, 0.000],
|
| 89 |
+
[0.018, 0.023, 0.028],
|
| 90 |
+
[0.040, 0.056, 0.071],
|
| 91 |
+
[0.059, 0.087, 0.110],
|
| 92 |
+
[0.074, 0.114, 0.147],
|
| 93 |
+
[0.086, 0.139, 0.183],
|
| 94 |
+
[0.095, 0.163, 0.219],
|
| 95 |
+
[0.101, 0.187, 0.255],
|
| 96 |
+
[0.105, 0.209, 0.290],
|
| 97 |
+
[0.107, 0.230, 0.326],
|
| 98 |
+
[0.105, 0.251, 0.362],
|
| 99 |
+
[0.101, 0.271, 0.398],
|
| 100 |
+
[0.091, 0.291, 0.434],
|
| 101 |
+
[0.075, 0.309, 0.471],
|
| 102 |
+
[0.046, 0.325, 0.507],
|
| 103 |
+
[0.021, 0.341, 0.546],
|
| 104 |
+
[0.021, 0.363, 0.584],
|
| 105 |
+
[0.022, 0.385, 0.622],
|
| 106 |
+
[0.023, 0.408, 0.661]]
|
| 107 |
+
|
| 108 |
+
_3VarAddA1_data = [[0.000, 0.000, 0.000],
|
| 109 |
+
[0.020, 0.024, 0.016],
|
| 110 |
+
[0.047, 0.058, 0.034],
|
| 111 |
+
[0.072, 0.088, 0.048],
|
| 112 |
+
[0.093, 0.116, 0.059],
|
| 113 |
+
[0.113, 0.142, 0.067],
|
| 114 |
+
[0.131, 0.167, 0.071],
|
| 115 |
+
[0.149, 0.190, 0.074],
|
| 116 |
+
[0.166, 0.213, 0.074],
|
| 117 |
+
[0.182, 0.235, 0.072],
|
| 118 |
+
[0.198, 0.256, 0.068],
|
| 119 |
+
[0.215, 0.276, 0.061],
|
| 120 |
+
[0.232, 0.296, 0.051],
|
| 121 |
+
[0.249, 0.314, 0.037],
|
| 122 |
+
[0.270, 0.330, 0.018],
|
| 123 |
+
[0.288, 0.347, 0.000],
|
| 124 |
+
[0.302, 0.369, 0.000],
|
| 125 |
+
[0.315, 0.391, 0.000],
|
| 126 |
+
[0.328, 0.414, 0.000]]
|
| 127 |
+
|
| 128 |
+
_3VarAddA2_data = [[0.000, 0.000, 0.000],
|
| 129 |
+
[0.029, 0.020, 0.023],
|
| 130 |
+
[0.072, 0.045, 0.055],
|
| 131 |
+
[0.111, 0.067, 0.084],
|
| 132 |
+
[0.148, 0.085, 0.109],
|
| 133 |
+
[0.184, 0.101, 0.133],
|
| 134 |
+
[0.219, 0.115, 0.155],
|
| 135 |
+
[0.254, 0.127, 0.176],
|
| 136 |
+
[0.289, 0.138, 0.195],
|
| 137 |
+
[0.323, 0.147, 0.214],
|
| 138 |
+
[0.358, 0.155, 0.232],
|
| 139 |
+
[0.393, 0.161, 0.250],
|
| 140 |
+
[0.429, 0.166, 0.267],
|
| 141 |
+
[0.467, 0.169, 0.283],
|
| 142 |
+
[0.507, 0.168, 0.298],
|
| 143 |
+
[0.546, 0.168, 0.313],
|
| 144 |
+
[0.580, 0.172, 0.328],
|
| 145 |
+
[0.615, 0.175, 0.341],
|
| 146 |
+
[0.649, 0.178, 0.355]]
|
| 147 |
+
|
| 148 |
+
cmaps = {
|
| 149 |
+
name: LinearSegmentedColormap.from_list(name, data, _LUTSIZE) for name, data in [
|
| 150 |
+
('2VarAddA0', _2VarAddA0_data),
|
| 151 |
+
('2VarAddA1', _2VarAddA1_data),
|
| 152 |
+
('2VarSubA0', _2VarSubA0_data),
|
| 153 |
+
('2VarSubA1', _2VarSubA1_data),
|
| 154 |
+
('3VarAddA0', _3VarAddA0_data),
|
| 155 |
+
('3VarAddA1', _3VarAddA1_data),
|
| 156 |
+
('3VarAddA2', _3VarAddA2_data),
|
| 157 |
+
]}
|
| 158 |
+
|
| 159 |
+
cmap_families = {
|
| 160 |
+
'2VarAddA': MultivarColormap([cmaps[f'2VarAddA{i}'] for i in range(2)],
|
| 161 |
+
'sRGB_add', name='2VarAddA'),
|
| 162 |
+
'2VarSubA': MultivarColormap([cmaps[f'2VarSubA{i}'] for i in range(2)],
|
| 163 |
+
'sRGB_sub', name='2VarSubA'),
|
| 164 |
+
'3VarAddA': MultivarColormap([cmaps[f'3VarAddA{i}'] for i in range(3)],
|
| 165 |
+
'sRGB_add', name='3VarAddA'),
|
| 166 |
+
}
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/_tight_bbox.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Helper module for the *bbox_inches* parameter in `.Figure.savefig`.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from matplotlib.transforms import Bbox, TransformedBbox, Affine2D
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
def adjust_bbox(fig, bbox_inches, fixed_dpi=None):
|
| 9 |
+
"""
|
| 10 |
+
Temporarily adjust the figure so that only the specified area
|
| 11 |
+
(bbox_inches) is saved.
|
| 12 |
+
|
| 13 |
+
It modifies fig.bbox, fig.bbox_inches,
|
| 14 |
+
fig.transFigure._boxout, and fig.patch. While the figure size
|
| 15 |
+
changes, the scale of the original figure is conserved. A
|
| 16 |
+
function which restores the original values are returned.
|
| 17 |
+
"""
|
| 18 |
+
origBbox = fig.bbox
|
| 19 |
+
origBboxInches = fig.bbox_inches
|
| 20 |
+
_boxout = fig.transFigure._boxout
|
| 21 |
+
|
| 22 |
+
old_aspect = []
|
| 23 |
+
locator_list = []
|
| 24 |
+
sentinel = object()
|
| 25 |
+
for ax in fig.axes:
|
| 26 |
+
locator = ax.get_axes_locator()
|
| 27 |
+
if locator is not None:
|
| 28 |
+
ax.apply_aspect(locator(ax, None))
|
| 29 |
+
locator_list.append(locator)
|
| 30 |
+
current_pos = ax.get_position(original=False).frozen()
|
| 31 |
+
ax.set_axes_locator(lambda a, r, _pos=current_pos: _pos)
|
| 32 |
+
# override the method that enforces the aspect ratio on the Axes
|
| 33 |
+
if 'apply_aspect' in ax.__dict__:
|
| 34 |
+
old_aspect.append(ax.apply_aspect)
|
| 35 |
+
else:
|
| 36 |
+
old_aspect.append(sentinel)
|
| 37 |
+
ax.apply_aspect = lambda pos=None: None
|
| 38 |
+
|
| 39 |
+
def restore_bbox():
|
| 40 |
+
for ax, loc, aspect in zip(fig.axes, locator_list, old_aspect):
|
| 41 |
+
ax.set_axes_locator(loc)
|
| 42 |
+
if aspect is sentinel:
|
| 43 |
+
# delete our no-op function which un-hides the original method
|
| 44 |
+
del ax.apply_aspect
|
| 45 |
+
else:
|
| 46 |
+
ax.apply_aspect = aspect
|
| 47 |
+
|
| 48 |
+
fig.bbox = origBbox
|
| 49 |
+
fig.bbox_inches = origBboxInches
|
| 50 |
+
fig.transFigure._boxout = _boxout
|
| 51 |
+
fig.transFigure.invalidate()
|
| 52 |
+
fig.patch.set_bounds(0, 0, 1, 1)
|
| 53 |
+
|
| 54 |
+
if fixed_dpi is None:
|
| 55 |
+
fixed_dpi = fig.dpi
|
| 56 |
+
tr = Affine2D().scale(fixed_dpi)
|
| 57 |
+
dpi_scale = fixed_dpi / fig.dpi
|
| 58 |
+
|
| 59 |
+
fig.bbox_inches = Bbox.from_bounds(0, 0, *bbox_inches.size)
|
| 60 |
+
x0, y0 = tr.transform(bbox_inches.p0)
|
| 61 |
+
w1, h1 = fig.bbox.size * dpi_scale
|
| 62 |
+
fig.transFigure._boxout = Bbox.from_bounds(-x0, -y0, w1, h1)
|
| 63 |
+
fig.transFigure.invalidate()
|
| 64 |
+
|
| 65 |
+
fig.bbox = TransformedBbox(fig.bbox_inches, tr)
|
| 66 |
+
|
| 67 |
+
fig.patch.set_bounds(x0 / w1, y0 / h1,
|
| 68 |
+
fig.bbox.width / w1, fig.bbox.height / h1)
|
| 69 |
+
|
| 70 |
+
return restore_bbox
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def process_figure_for_rasterizing(fig, bbox_inches_restore, fixed_dpi=None):
|
| 74 |
+
"""
|
| 75 |
+
A function that needs to be called when figure dpi changes during the
|
| 76 |
+
drawing (e.g., rasterizing). It recovers the bbox and re-adjust it with
|
| 77 |
+
the new dpi.
|
| 78 |
+
"""
|
| 79 |
+
|
| 80 |
+
bbox_inches, restore_bbox = bbox_inches_restore
|
| 81 |
+
restore_bbox()
|
| 82 |
+
r = adjust_bbox(fig, bbox_inches, fixed_dpi)
|
| 83 |
+
|
| 84 |
+
return bbox_inches, r
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/artist.pyi
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .axes._base import _AxesBase
|
| 2 |
+
from .backend_bases import RendererBase, MouseEvent
|
| 3 |
+
from .figure import Figure, SubFigure
|
| 4 |
+
from .path import Path
|
| 5 |
+
from .patches import Patch
|
| 6 |
+
from .patheffects import AbstractPathEffect
|
| 7 |
+
from .transforms import (
|
| 8 |
+
BboxBase,
|
| 9 |
+
Bbox,
|
| 10 |
+
Transform,
|
| 11 |
+
TransformedPatchPath,
|
| 12 |
+
TransformedPath,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
import numpy as np
|
| 16 |
+
|
| 17 |
+
from collections.abc import Callable, Iterable
|
| 18 |
+
from typing import Any, Literal, NamedTuple, TextIO, overload, TypeVar
|
| 19 |
+
from numpy.typing import ArrayLike
|
| 20 |
+
|
| 21 |
+
_T_Artist = TypeVar("_T_Artist", bound=Artist)
|
| 22 |
+
|
| 23 |
+
def allow_rasterization(draw): ...
|
| 24 |
+
|
| 25 |
+
class _XYPair(NamedTuple):
|
| 26 |
+
x: ArrayLike
|
| 27 |
+
y: ArrayLike
|
| 28 |
+
|
| 29 |
+
class _Unset: ...
|
| 30 |
+
|
| 31 |
+
class Artist:
|
| 32 |
+
zorder: float
|
| 33 |
+
stale_callback: Callable[[Artist, bool], None] | None
|
| 34 |
+
@property
|
| 35 |
+
def figure(self) -> Figure | SubFigure: ...
|
| 36 |
+
clipbox: BboxBase | None
|
| 37 |
+
def __init__(self) -> None: ...
|
| 38 |
+
def remove(self) -> None: ...
|
| 39 |
+
def have_units(self) -> bool: ...
|
| 40 |
+
# TODO units
|
| 41 |
+
def convert_xunits(self, x): ...
|
| 42 |
+
def convert_yunits(self, y): ...
|
| 43 |
+
@property
|
| 44 |
+
def axes(self) -> _AxesBase | None: ...
|
| 45 |
+
@axes.setter
|
| 46 |
+
def axes(self, new_axes: _AxesBase | None) -> None: ...
|
| 47 |
+
@property
|
| 48 |
+
def stale(self) -> bool: ...
|
| 49 |
+
@stale.setter
|
| 50 |
+
def stale(self, val: bool) -> None: ...
|
| 51 |
+
def get_window_extent(self, renderer: RendererBase | None = ...) -> Bbox: ...
|
| 52 |
+
def get_tightbbox(self, renderer: RendererBase | None = ...) -> Bbox | None: ...
|
| 53 |
+
def add_callback(self, func: Callable[[Artist], Any]) -> int: ...
|
| 54 |
+
def remove_callback(self, oid: int) -> None: ...
|
| 55 |
+
def pchanged(self) -> None: ...
|
| 56 |
+
def is_transform_set(self) -> bool: ...
|
| 57 |
+
def set_transform(self, t: Transform | None) -> None: ...
|
| 58 |
+
def get_transform(self) -> Transform: ...
|
| 59 |
+
def get_children(self) -> list[Artist]: ...
|
| 60 |
+
# TODO can these dicts be type narrowed? e.g. str keys
|
| 61 |
+
def contains(self, mouseevent: MouseEvent) -> tuple[bool, dict[Any, Any]]: ...
|
| 62 |
+
def pickable(self) -> bool: ...
|
| 63 |
+
def pick(self, mouseevent: MouseEvent) -> None: ...
|
| 64 |
+
def set_picker(
|
| 65 |
+
self,
|
| 66 |
+
picker: None
|
| 67 |
+
| bool
|
| 68 |
+
| float
|
| 69 |
+
| Callable[[Artist, MouseEvent], tuple[bool, dict[Any, Any]]],
|
| 70 |
+
) -> None: ...
|
| 71 |
+
def get_picker(
|
| 72 |
+
self,
|
| 73 |
+
) -> None | bool | float | Callable[
|
| 74 |
+
[Artist, MouseEvent], tuple[bool, dict[Any, Any]]
|
| 75 |
+
]: ...
|
| 76 |
+
def get_url(self) -> str | None: ...
|
| 77 |
+
def set_url(self, url: str | None) -> None: ...
|
| 78 |
+
def get_gid(self) -> str | None: ...
|
| 79 |
+
def set_gid(self, gid: str | None) -> None: ...
|
| 80 |
+
def get_snap(self) -> bool | None: ...
|
| 81 |
+
def set_snap(self, snap: bool | None) -> None: ...
|
| 82 |
+
def get_sketch_params(self) -> tuple[float, float, float] | None: ...
|
| 83 |
+
def set_sketch_params(
|
| 84 |
+
self,
|
| 85 |
+
scale: float | None = ...,
|
| 86 |
+
length: float | None = ...,
|
| 87 |
+
randomness: float | None = ...,
|
| 88 |
+
) -> None: ...
|
| 89 |
+
def set_path_effects(self, path_effects: list[AbstractPathEffect]) -> None: ...
|
| 90 |
+
def get_path_effects(self) -> list[AbstractPathEffect]: ...
|
| 91 |
+
@overload
|
| 92 |
+
def get_figure(self, root: Literal[True]) -> Figure | None: ...
|
| 93 |
+
@overload
|
| 94 |
+
def get_figure(self, root: Literal[False]) -> Figure | SubFigure | None: ...
|
| 95 |
+
@overload
|
| 96 |
+
def get_figure(self, root: bool = ...) -> Figure | SubFigure | None: ...
|
| 97 |
+
def set_figure(self, fig: Figure | SubFigure) -> None: ...
|
| 98 |
+
def set_clip_box(self, clipbox: BboxBase | None) -> None: ...
|
| 99 |
+
def set_clip_path(
|
| 100 |
+
self,
|
| 101 |
+
path: Patch | Path | TransformedPath | TransformedPatchPath | None,
|
| 102 |
+
transform: Transform | None = ...,
|
| 103 |
+
) -> None: ...
|
| 104 |
+
def get_alpha(self) -> float | None: ...
|
| 105 |
+
def get_visible(self) -> bool: ...
|
| 106 |
+
def get_animated(self) -> bool: ...
|
| 107 |
+
def get_in_layout(self) -> bool: ...
|
| 108 |
+
def get_clip_on(self) -> bool: ...
|
| 109 |
+
def get_clip_box(self) -> Bbox | None: ...
|
| 110 |
+
def get_clip_path(
|
| 111 |
+
self,
|
| 112 |
+
) -> Patch | Path | TransformedPath | TransformedPatchPath | None: ...
|
| 113 |
+
def get_transformed_clip_path_and_affine(
|
| 114 |
+
self,
|
| 115 |
+
) -> tuple[None, None] | tuple[Path, Transform]: ...
|
| 116 |
+
def set_clip_on(self, b: bool) -> None: ...
|
| 117 |
+
def get_rasterized(self) -> bool: ...
|
| 118 |
+
def set_rasterized(self, rasterized: bool) -> None: ...
|
| 119 |
+
def get_agg_filter(self) -> Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None: ...
|
| 120 |
+
def set_agg_filter(
|
| 121 |
+
self, filter_func: Callable[[ArrayLike, float], tuple[np.ndarray, float, float]] | None
|
| 122 |
+
) -> None: ...
|
| 123 |
+
def draw(self, renderer: RendererBase) -> None: ...
|
| 124 |
+
def set_alpha(self, alpha: float | None) -> None: ...
|
| 125 |
+
def set_visible(self, b: bool) -> None: ...
|
| 126 |
+
def set_animated(self, b: bool) -> None: ...
|
| 127 |
+
def set_in_layout(self, in_layout: bool) -> None: ...
|
| 128 |
+
def get_label(self) -> object: ...
|
| 129 |
+
def set_label(self, s: object) -> None: ...
|
| 130 |
+
def get_zorder(self) -> float: ...
|
| 131 |
+
def set_zorder(self, level: float) -> None: ...
|
| 132 |
+
@property
|
| 133 |
+
def sticky_edges(self) -> _XYPair: ...
|
| 134 |
+
def update_from(self, other: Artist) -> None: ...
|
| 135 |
+
def properties(self) -> dict[str, Any]: ...
|
| 136 |
+
def update(self, props: dict[str, Any]) -> list[Any]: ...
|
| 137 |
+
def _internal_update(self, kwargs: Any) -> list[Any]: ...
|
| 138 |
+
def set(self, **kwargs: Any) -> list[Any]: ...
|
| 139 |
+
|
| 140 |
+
@overload
|
| 141 |
+
def findobj(
|
| 142 |
+
self,
|
| 143 |
+
match: None | Callable[[Artist], bool] = ...,
|
| 144 |
+
include_self: bool = ...,
|
| 145 |
+
) -> list[Artist]: ...
|
| 146 |
+
|
| 147 |
+
@overload
|
| 148 |
+
def findobj(
|
| 149 |
+
self,
|
| 150 |
+
match: type[_T_Artist],
|
| 151 |
+
include_self: bool = ...,
|
| 152 |
+
) -> list[_T_Artist]: ...
|
| 153 |
+
|
| 154 |
+
def get_cursor_data(self, event: MouseEvent) -> Any: ...
|
| 155 |
+
def format_cursor_data(self, data: Any) -> str: ...
|
| 156 |
+
def get_mouseover(self) -> bool: ...
|
| 157 |
+
def set_mouseover(self, mouseover: bool) -> None: ...
|
| 158 |
+
@property
|
| 159 |
+
def mouseover(self) -> bool: ...
|
| 160 |
+
@mouseover.setter
|
| 161 |
+
def mouseover(self, mouseover: bool) -> None: ...
|
| 162 |
+
|
| 163 |
+
class ArtistInspector:
|
| 164 |
+
oorig: Artist | type[Artist]
|
| 165 |
+
o: type[Artist]
|
| 166 |
+
aliasd: dict[str, set[str]]
|
| 167 |
+
def __init__(
|
| 168 |
+
self, o: Artist | type[Artist] | Iterable[Artist | type[Artist]]
|
| 169 |
+
) -> None: ...
|
| 170 |
+
def get_aliases(self) -> dict[str, set[str]]: ...
|
| 171 |
+
def get_valid_values(self, attr: str) -> str | None: ...
|
| 172 |
+
def get_setters(self) -> list[str]: ...
|
| 173 |
+
@staticmethod
|
| 174 |
+
def number_of_parameters(func: Callable) -> int: ...
|
| 175 |
+
@staticmethod
|
| 176 |
+
def is_alias(method: Callable) -> bool: ...
|
| 177 |
+
def aliased_name(self, s: str) -> str: ...
|
| 178 |
+
def aliased_name_rest(self, s: str, target: str) -> str: ...
|
| 179 |
+
@overload
|
| 180 |
+
def pprint_setters(
|
| 181 |
+
self, prop: None = ..., leadingspace: int = ...
|
| 182 |
+
) -> list[str]: ...
|
| 183 |
+
@overload
|
| 184 |
+
def pprint_setters(self, prop: str, leadingspace: int = ...) -> str: ...
|
| 185 |
+
@overload
|
| 186 |
+
def pprint_setters_rest(
|
| 187 |
+
self, prop: None = ..., leadingspace: int = ...
|
| 188 |
+
) -> list[str]: ...
|
| 189 |
+
@overload
|
| 190 |
+
def pprint_setters_rest(self, prop: str, leadingspace: int = ...) -> str: ...
|
| 191 |
+
def properties(self) -> dict[str, Any]: ...
|
| 192 |
+
def pprint_getters(self) -> list[str]: ...
|
| 193 |
+
|
| 194 |
+
def getp(obj: Artist, property: str | None = ...) -> Any: ...
|
| 195 |
+
|
| 196 |
+
get = getp
|
| 197 |
+
|
| 198 |
+
def setp(obj: Artist, *args, file: TextIO | None = ..., **kwargs) -> list[Any] | None: ...
|
| 199 |
+
def kwdoc(artist: Artist | type[Artist] | Iterable[Artist | type[Artist]]) -> str: ...
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/backend_tools.py
ADDED
|
@@ -0,0 +1,998 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Abstract base classes define the primitives for Tools.
|
| 3 |
+
These tools are used by `matplotlib.backend_managers.ToolManager`
|
| 4 |
+
|
| 5 |
+
:class:`ToolBase`
|
| 6 |
+
Simple stateless tool
|
| 7 |
+
|
| 8 |
+
:class:`ToolToggleBase`
|
| 9 |
+
Tool that has two states, only one Toggle tool can be
|
| 10 |
+
active at any given time for the same
|
| 11 |
+
`matplotlib.backend_managers.ToolManager`
|
| 12 |
+
"""
|
| 13 |
+
|
| 14 |
+
import enum
|
| 15 |
+
import functools
|
| 16 |
+
import re
|
| 17 |
+
import time
|
| 18 |
+
from types import SimpleNamespace
|
| 19 |
+
import uuid
|
| 20 |
+
from weakref import WeakKeyDictionary
|
| 21 |
+
|
| 22 |
+
import numpy as np
|
| 23 |
+
|
| 24 |
+
import matplotlib as mpl
|
| 25 |
+
from matplotlib._pylab_helpers import Gcf
|
| 26 |
+
from matplotlib import _api, cbook
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class Cursors(enum.IntEnum): # Must subclass int for the macOS backend.
|
| 30 |
+
"""Backend-independent cursor types."""
|
| 31 |
+
POINTER = enum.auto()
|
| 32 |
+
HAND = enum.auto()
|
| 33 |
+
SELECT_REGION = enum.auto()
|
| 34 |
+
MOVE = enum.auto()
|
| 35 |
+
WAIT = enum.auto()
|
| 36 |
+
RESIZE_HORIZONTAL = enum.auto()
|
| 37 |
+
RESIZE_VERTICAL = enum.auto()
|
| 38 |
+
cursors = Cursors # Backcompat.
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
# _tool_registry, _register_tool_class, and _find_tool_class implement a
|
| 42 |
+
# mechanism through which ToolManager.add_tool can determine whether a subclass
|
| 43 |
+
# of the requested tool class has been registered (either for the current
|
| 44 |
+
# canvas class or for a parent class), in which case that tool subclass will be
|
| 45 |
+
# instantiated instead. This is the mechanism used e.g. to allow different
|
| 46 |
+
# GUI backends to implement different specializations for ConfigureSubplots.
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
_tool_registry = set()
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def _register_tool_class(canvas_cls, tool_cls=None):
|
| 53 |
+
"""Decorator registering *tool_cls* as a tool class for *canvas_cls*."""
|
| 54 |
+
if tool_cls is None:
|
| 55 |
+
return functools.partial(_register_tool_class, canvas_cls)
|
| 56 |
+
_tool_registry.add((canvas_cls, tool_cls))
|
| 57 |
+
return tool_cls
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _find_tool_class(canvas_cls, tool_cls):
|
| 61 |
+
"""Find a subclass of *tool_cls* registered for *canvas_cls*."""
|
| 62 |
+
for canvas_parent in canvas_cls.__mro__:
|
| 63 |
+
for tool_child in _api.recursive_subclasses(tool_cls):
|
| 64 |
+
if (canvas_parent, tool_child) in _tool_registry:
|
| 65 |
+
return tool_child
|
| 66 |
+
return tool_cls
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
# Views positions tool
|
| 70 |
+
_views_positions = 'viewpos'
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class ToolBase:
|
| 74 |
+
"""
|
| 75 |
+
Base tool class.
|
| 76 |
+
|
| 77 |
+
A base tool, only implements `trigger` method or no method at all.
|
| 78 |
+
The tool is instantiated by `matplotlib.backend_managers.ToolManager`.
|
| 79 |
+
"""
|
| 80 |
+
|
| 81 |
+
default_keymap = None
|
| 82 |
+
"""
|
| 83 |
+
Keymap to associate with this tool.
|
| 84 |
+
|
| 85 |
+
``list[str]``: List of keys that will trigger this tool when a keypress
|
| 86 |
+
event is emitted on ``self.figure.canvas``. Note that this attribute is
|
| 87 |
+
looked up on the instance, and can therefore be a property (this is used
|
| 88 |
+
e.g. by the built-in tools to load the rcParams at instantiation time).
|
| 89 |
+
"""
|
| 90 |
+
|
| 91 |
+
description = None
|
| 92 |
+
"""
|
| 93 |
+
Description of the Tool.
|
| 94 |
+
|
| 95 |
+
`str`: Tooltip used if the Tool is included in a Toolbar.
|
| 96 |
+
"""
|
| 97 |
+
|
| 98 |
+
image = None
|
| 99 |
+
"""
|
| 100 |
+
Icon filename.
|
| 101 |
+
|
| 102 |
+
``str | None``: Filename of the Toolbar icon; either absolute, or relative to the
|
| 103 |
+
directory containing the Python source file where the ``Tool.image`` class attribute
|
| 104 |
+
is defined (in the latter case, this cannot be defined as an instance attribute).
|
| 105 |
+
In either case, the extension is optional; leaving it off lets individual backends
|
| 106 |
+
select the icon format they prefer. If None, the *name* is used as a label in the
|
| 107 |
+
toolbar button.
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def __init__(self, toolmanager, name):
|
| 111 |
+
self._name = name
|
| 112 |
+
self._toolmanager = toolmanager
|
| 113 |
+
self._figure = None
|
| 114 |
+
|
| 115 |
+
name = property(
|
| 116 |
+
lambda self: self._name,
|
| 117 |
+
doc="The tool id (str, must be unique among tools of a tool manager).")
|
| 118 |
+
toolmanager = property(
|
| 119 |
+
lambda self: self._toolmanager,
|
| 120 |
+
doc="The `.ToolManager` that controls this tool.")
|
| 121 |
+
canvas = property(
|
| 122 |
+
lambda self: self._figure.canvas if self._figure is not None else None,
|
| 123 |
+
doc="The canvas of the figure affected by this tool, or None.")
|
| 124 |
+
|
| 125 |
+
def set_figure(self, figure):
|
| 126 |
+
self._figure = figure
|
| 127 |
+
|
| 128 |
+
figure = property(
|
| 129 |
+
lambda self: self._figure,
|
| 130 |
+
# The setter must explicitly call self.set_figure so that subclasses can
|
| 131 |
+
# meaningfully override it.
|
| 132 |
+
lambda self, figure: self.set_figure(figure),
|
| 133 |
+
doc="The Figure affected by this tool, or None.")
|
| 134 |
+
|
| 135 |
+
def _make_classic_style_pseudo_toolbar(self):
|
| 136 |
+
"""
|
| 137 |
+
Return a placeholder object with a single `canvas` attribute.
|
| 138 |
+
|
| 139 |
+
This is useful to reuse the implementations of tools already provided
|
| 140 |
+
by the classic Toolbars.
|
| 141 |
+
"""
|
| 142 |
+
return SimpleNamespace(canvas=self.canvas)
|
| 143 |
+
|
| 144 |
+
def trigger(self, sender, event, data=None):
|
| 145 |
+
"""
|
| 146 |
+
Called when this tool gets used.
|
| 147 |
+
|
| 148 |
+
This method is called by `.ToolManager.trigger_tool`.
|
| 149 |
+
|
| 150 |
+
Parameters
|
| 151 |
+
----------
|
| 152 |
+
event : `.Event`
|
| 153 |
+
The canvas event that caused this tool to be called.
|
| 154 |
+
sender : object
|
| 155 |
+
Object that requested the tool to be triggered.
|
| 156 |
+
data : object
|
| 157 |
+
Extra data.
|
| 158 |
+
"""
|
| 159 |
+
pass
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
class ToolToggleBase(ToolBase):
|
| 163 |
+
"""
|
| 164 |
+
Toggleable tool.
|
| 165 |
+
|
| 166 |
+
Every time it is triggered, it switches between enable and disable.
|
| 167 |
+
|
| 168 |
+
Parameters
|
| 169 |
+
----------
|
| 170 |
+
``*args``
|
| 171 |
+
Variable length argument to be used by the Tool.
|
| 172 |
+
``**kwargs``
|
| 173 |
+
`toggled` if present and True, sets the initial state of the Tool
|
| 174 |
+
Arbitrary keyword arguments to be consumed by the Tool
|
| 175 |
+
"""
|
| 176 |
+
|
| 177 |
+
radio_group = None
|
| 178 |
+
"""
|
| 179 |
+
Attribute to group 'radio' like tools (mutually exclusive).
|
| 180 |
+
|
| 181 |
+
`str` that identifies the group or **None** if not belonging to a group.
|
| 182 |
+
"""
|
| 183 |
+
|
| 184 |
+
cursor = None
|
| 185 |
+
"""Cursor to use when the tool is active."""
|
| 186 |
+
|
| 187 |
+
default_toggled = False
|
| 188 |
+
"""Default of toggled state."""
|
| 189 |
+
|
| 190 |
+
def __init__(self, *args, **kwargs):
|
| 191 |
+
self._toggled = kwargs.pop('toggled', self.default_toggled)
|
| 192 |
+
super().__init__(*args, **kwargs)
|
| 193 |
+
|
| 194 |
+
def trigger(self, sender, event, data=None):
|
| 195 |
+
"""Calls `enable` or `disable` based on `toggled` value."""
|
| 196 |
+
if self._toggled:
|
| 197 |
+
self.disable(event)
|
| 198 |
+
else:
|
| 199 |
+
self.enable(event)
|
| 200 |
+
self._toggled = not self._toggled
|
| 201 |
+
|
| 202 |
+
def enable(self, event=None):
|
| 203 |
+
"""
|
| 204 |
+
Enable the toggle tool.
|
| 205 |
+
|
| 206 |
+
`trigger` calls this method when `toggled` is False.
|
| 207 |
+
"""
|
| 208 |
+
pass
|
| 209 |
+
|
| 210 |
+
def disable(self, event=None):
|
| 211 |
+
"""
|
| 212 |
+
Disable the toggle tool.
|
| 213 |
+
|
| 214 |
+
`trigger` call this method when `toggled` is True.
|
| 215 |
+
|
| 216 |
+
This can happen in different circumstances.
|
| 217 |
+
|
| 218 |
+
* Click on the toolbar tool button.
|
| 219 |
+
* Call to `matplotlib.backend_managers.ToolManager.trigger_tool`.
|
| 220 |
+
* Another `ToolToggleBase` derived tool is triggered
|
| 221 |
+
(from the same `.ToolManager`).
|
| 222 |
+
"""
|
| 223 |
+
pass
|
| 224 |
+
|
| 225 |
+
@property
|
| 226 |
+
def toggled(self):
|
| 227 |
+
"""State of the toggled tool."""
|
| 228 |
+
return self._toggled
|
| 229 |
+
|
| 230 |
+
def set_figure(self, figure):
|
| 231 |
+
toggled = self.toggled
|
| 232 |
+
if toggled:
|
| 233 |
+
if self.figure:
|
| 234 |
+
self.trigger(self, None)
|
| 235 |
+
else:
|
| 236 |
+
# if no figure the internal state is not changed
|
| 237 |
+
# we change it here so next call to trigger will change it back
|
| 238 |
+
self._toggled = False
|
| 239 |
+
super().set_figure(figure)
|
| 240 |
+
if toggled:
|
| 241 |
+
if figure:
|
| 242 |
+
self.trigger(self, None)
|
| 243 |
+
else:
|
| 244 |
+
# if there is no figure, trigger won't change the internal
|
| 245 |
+
# state we change it back
|
| 246 |
+
self._toggled = True
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
class ToolSetCursor(ToolBase):
|
| 250 |
+
"""
|
| 251 |
+
Change to the current cursor while inaxes.
|
| 252 |
+
|
| 253 |
+
This tool, keeps track of all `ToolToggleBase` derived tools, and updates
|
| 254 |
+
the cursor when a tool gets triggered.
|
| 255 |
+
"""
|
| 256 |
+
def __init__(self, *args, **kwargs):
|
| 257 |
+
super().__init__(*args, **kwargs)
|
| 258 |
+
self._id_drag = None
|
| 259 |
+
self._current_tool = None
|
| 260 |
+
self._default_cursor = cursors.POINTER
|
| 261 |
+
self._last_cursor = self._default_cursor
|
| 262 |
+
self.toolmanager.toolmanager_connect('tool_added_event',
|
| 263 |
+
self._add_tool_cbk)
|
| 264 |
+
for tool in self.toolmanager.tools.values(): # process current tools
|
| 265 |
+
self._add_tool_cbk(mpl.backend_managers.ToolEvent(
|
| 266 |
+
'tool_added_event', self.toolmanager, tool))
|
| 267 |
+
|
| 268 |
+
def set_figure(self, figure):
|
| 269 |
+
if self._id_drag:
|
| 270 |
+
self.canvas.mpl_disconnect(self._id_drag)
|
| 271 |
+
super().set_figure(figure)
|
| 272 |
+
if figure:
|
| 273 |
+
self._id_drag = self.canvas.mpl_connect(
|
| 274 |
+
'motion_notify_event', self._set_cursor_cbk)
|
| 275 |
+
|
| 276 |
+
def _add_tool_cbk(self, event):
|
| 277 |
+
"""Process every newly added tool."""
|
| 278 |
+
if getattr(event.tool, 'cursor', None) is not None:
|
| 279 |
+
self.toolmanager.toolmanager_connect(
|
| 280 |
+
f'tool_trigger_{event.tool.name}', self._tool_trigger_cbk)
|
| 281 |
+
|
| 282 |
+
def _tool_trigger_cbk(self, event):
|
| 283 |
+
self._current_tool = event.tool if event.tool.toggled else None
|
| 284 |
+
self._set_cursor_cbk(event.canvasevent)
|
| 285 |
+
|
| 286 |
+
def _set_cursor_cbk(self, event):
|
| 287 |
+
if not event or not self.canvas:
|
| 288 |
+
return
|
| 289 |
+
if (self._current_tool and getattr(event, "inaxes", None)
|
| 290 |
+
and event.inaxes.get_navigate()):
|
| 291 |
+
if self._last_cursor != self._current_tool.cursor:
|
| 292 |
+
self.canvas.set_cursor(self._current_tool.cursor)
|
| 293 |
+
self._last_cursor = self._current_tool.cursor
|
| 294 |
+
elif self._last_cursor != self._default_cursor:
|
| 295 |
+
self.canvas.set_cursor(self._default_cursor)
|
| 296 |
+
self._last_cursor = self._default_cursor
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
class ToolCursorPosition(ToolBase):
|
| 300 |
+
"""
|
| 301 |
+
Send message with the current pointer position.
|
| 302 |
+
|
| 303 |
+
This tool runs in the background reporting the position of the cursor.
|
| 304 |
+
"""
|
| 305 |
+
def __init__(self, *args, **kwargs):
|
| 306 |
+
self._id_drag = None
|
| 307 |
+
super().__init__(*args, **kwargs)
|
| 308 |
+
|
| 309 |
+
def set_figure(self, figure):
|
| 310 |
+
if self._id_drag:
|
| 311 |
+
self.canvas.mpl_disconnect(self._id_drag)
|
| 312 |
+
super().set_figure(figure)
|
| 313 |
+
if figure:
|
| 314 |
+
self._id_drag = self.canvas.mpl_connect(
|
| 315 |
+
'motion_notify_event', self.send_message)
|
| 316 |
+
|
| 317 |
+
def send_message(self, event):
|
| 318 |
+
"""Call `matplotlib.backend_managers.ToolManager.message_event`."""
|
| 319 |
+
if self.toolmanager.messagelock.locked():
|
| 320 |
+
return
|
| 321 |
+
|
| 322 |
+
from matplotlib.backend_bases import NavigationToolbar2
|
| 323 |
+
message = NavigationToolbar2._mouse_event_to_message(event)
|
| 324 |
+
self.toolmanager.message_event(message, self)
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
class RubberbandBase(ToolBase):
|
| 328 |
+
"""Draw and remove a rubberband."""
|
| 329 |
+
def trigger(self, sender, event, data=None):
|
| 330 |
+
"""Call `draw_rubberband` or `remove_rubberband` based on data."""
|
| 331 |
+
if not self.figure.canvas.widgetlock.available(sender):
|
| 332 |
+
return
|
| 333 |
+
if data is not None:
|
| 334 |
+
self.draw_rubberband(*data)
|
| 335 |
+
else:
|
| 336 |
+
self.remove_rubberband()
|
| 337 |
+
|
| 338 |
+
def draw_rubberband(self, *data):
|
| 339 |
+
"""
|
| 340 |
+
Draw rubberband.
|
| 341 |
+
|
| 342 |
+
This method must get implemented per backend.
|
| 343 |
+
"""
|
| 344 |
+
raise NotImplementedError
|
| 345 |
+
|
| 346 |
+
def remove_rubberband(self):
|
| 347 |
+
"""
|
| 348 |
+
Remove rubberband.
|
| 349 |
+
|
| 350 |
+
This method should get implemented per backend.
|
| 351 |
+
"""
|
| 352 |
+
pass
|
| 353 |
+
|
| 354 |
+
|
| 355 |
+
class ToolQuit(ToolBase):
|
| 356 |
+
"""Tool to call the figure manager destroy method."""
|
| 357 |
+
|
| 358 |
+
description = 'Quit the figure'
|
| 359 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.quit'])
|
| 360 |
+
|
| 361 |
+
def trigger(self, sender, event, data=None):
|
| 362 |
+
Gcf.destroy_fig(self.figure)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
class ToolQuitAll(ToolBase):
|
| 366 |
+
"""Tool to call the figure manager destroy method."""
|
| 367 |
+
|
| 368 |
+
description = 'Quit all figures'
|
| 369 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.quit_all'])
|
| 370 |
+
|
| 371 |
+
def trigger(self, sender, event, data=None):
|
| 372 |
+
Gcf.destroy_all()
|
| 373 |
+
|
| 374 |
+
|
| 375 |
+
class ToolGrid(ToolBase):
|
| 376 |
+
"""Tool to toggle the major grids of the figure."""
|
| 377 |
+
|
| 378 |
+
description = 'Toggle major grids'
|
| 379 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.grid'])
|
| 380 |
+
|
| 381 |
+
def trigger(self, sender, event, data=None):
|
| 382 |
+
sentinel = str(uuid.uuid4())
|
| 383 |
+
# Trigger grid switching by temporarily setting :rc:`keymap.grid`
|
| 384 |
+
# to a unique key and sending an appropriate event.
|
| 385 |
+
with (cbook._setattr_cm(event, key=sentinel),
|
| 386 |
+
mpl.rc_context({'keymap.grid': sentinel})):
|
| 387 |
+
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
class ToolMinorGrid(ToolBase):
|
| 391 |
+
"""Tool to toggle the major and minor grids of the figure."""
|
| 392 |
+
|
| 393 |
+
description = 'Toggle major and minor grids'
|
| 394 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.grid_minor'])
|
| 395 |
+
|
| 396 |
+
def trigger(self, sender, event, data=None):
|
| 397 |
+
sentinel = str(uuid.uuid4())
|
| 398 |
+
# Trigger grid switching by temporarily setting :rc:`keymap.grid_minor`
|
| 399 |
+
# to a unique key and sending an appropriate event.
|
| 400 |
+
with (cbook._setattr_cm(event, key=sentinel),
|
| 401 |
+
mpl.rc_context({'keymap.grid_minor': sentinel})):
|
| 402 |
+
mpl.backend_bases.key_press_handler(event, self.figure.canvas)
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
class ToolFullScreen(ToolBase):
|
| 406 |
+
"""Tool to toggle full screen."""
|
| 407 |
+
|
| 408 |
+
description = 'Toggle fullscreen mode'
|
| 409 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.fullscreen'])
|
| 410 |
+
|
| 411 |
+
def trigger(self, sender, event, data=None):
|
| 412 |
+
self.figure.canvas.manager.full_screen_toggle()
|
| 413 |
+
|
| 414 |
+
|
| 415 |
+
class AxisScaleBase(ToolToggleBase):
|
| 416 |
+
"""Base Tool to toggle between linear and logarithmic."""
|
| 417 |
+
|
| 418 |
+
def trigger(self, sender, event, data=None):
|
| 419 |
+
if event.inaxes is None:
|
| 420 |
+
return
|
| 421 |
+
super().trigger(sender, event, data)
|
| 422 |
+
|
| 423 |
+
def enable(self, event=None):
|
| 424 |
+
self.set_scale(event.inaxes, 'log')
|
| 425 |
+
self.figure.canvas.draw_idle()
|
| 426 |
+
|
| 427 |
+
def disable(self, event=None):
|
| 428 |
+
self.set_scale(event.inaxes, 'linear')
|
| 429 |
+
self.figure.canvas.draw_idle()
|
| 430 |
+
|
| 431 |
+
|
| 432 |
+
class ToolYScale(AxisScaleBase):
|
| 433 |
+
"""Tool to toggle between linear and logarithmic scales on the Y axis."""
|
| 434 |
+
|
| 435 |
+
description = 'Toggle scale Y axis'
|
| 436 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.yscale'])
|
| 437 |
+
|
| 438 |
+
def set_scale(self, ax, scale):
|
| 439 |
+
ax.set_yscale(scale)
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
class ToolXScale(AxisScaleBase):
|
| 443 |
+
"""Tool to toggle between linear and logarithmic scales on the X axis."""
|
| 444 |
+
|
| 445 |
+
description = 'Toggle scale X axis'
|
| 446 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.xscale'])
|
| 447 |
+
|
| 448 |
+
def set_scale(self, ax, scale):
|
| 449 |
+
ax.set_xscale(scale)
|
| 450 |
+
|
| 451 |
+
|
| 452 |
+
class ToolViewsPositions(ToolBase):
|
| 453 |
+
"""
|
| 454 |
+
Auxiliary Tool to handle changes in views and positions.
|
| 455 |
+
|
| 456 |
+
Runs in the background and should get used by all the tools that
|
| 457 |
+
need to access the figure's history of views and positions, e.g.
|
| 458 |
+
|
| 459 |
+
* `ToolZoom`
|
| 460 |
+
* `ToolPan`
|
| 461 |
+
* `ToolHome`
|
| 462 |
+
* `ToolBack`
|
| 463 |
+
* `ToolForward`
|
| 464 |
+
"""
|
| 465 |
+
|
| 466 |
+
def __init__(self, *args, **kwargs):
|
| 467 |
+
self.views = WeakKeyDictionary()
|
| 468 |
+
self.positions = WeakKeyDictionary()
|
| 469 |
+
self.home_views = WeakKeyDictionary()
|
| 470 |
+
super().__init__(*args, **kwargs)
|
| 471 |
+
|
| 472 |
+
def add_figure(self, figure):
|
| 473 |
+
"""Add the current figure to the stack of views and positions."""
|
| 474 |
+
|
| 475 |
+
if figure not in self.views:
|
| 476 |
+
self.views[figure] = cbook._Stack()
|
| 477 |
+
self.positions[figure] = cbook._Stack()
|
| 478 |
+
self.home_views[figure] = WeakKeyDictionary()
|
| 479 |
+
# Define Home
|
| 480 |
+
self.push_current(figure)
|
| 481 |
+
# Make sure we add a home view for new Axes as they're added
|
| 482 |
+
figure.add_axobserver(lambda fig: self.update_home_views(fig))
|
| 483 |
+
|
| 484 |
+
def clear(self, figure):
|
| 485 |
+
"""Reset the Axes stack."""
|
| 486 |
+
if figure in self.views:
|
| 487 |
+
self.views[figure].clear()
|
| 488 |
+
self.positions[figure].clear()
|
| 489 |
+
self.home_views[figure].clear()
|
| 490 |
+
self.update_home_views()
|
| 491 |
+
|
| 492 |
+
def update_view(self):
|
| 493 |
+
"""
|
| 494 |
+
Update the view limits and position for each Axes from the current
|
| 495 |
+
stack position. If any Axes are present in the figure that aren't in
|
| 496 |
+
the current stack position, use the home view limits for those Axes and
|
| 497 |
+
don't update *any* positions.
|
| 498 |
+
"""
|
| 499 |
+
|
| 500 |
+
views = self.views[self.figure]()
|
| 501 |
+
if views is None:
|
| 502 |
+
return
|
| 503 |
+
pos = self.positions[self.figure]()
|
| 504 |
+
if pos is None:
|
| 505 |
+
return
|
| 506 |
+
home_views = self.home_views[self.figure]
|
| 507 |
+
all_axes = self.figure.get_axes()
|
| 508 |
+
for a in all_axes:
|
| 509 |
+
if a in views:
|
| 510 |
+
cur_view = views[a]
|
| 511 |
+
else:
|
| 512 |
+
cur_view = home_views[a]
|
| 513 |
+
a._set_view(cur_view)
|
| 514 |
+
|
| 515 |
+
if set(all_axes).issubset(pos):
|
| 516 |
+
for a in all_axes:
|
| 517 |
+
# Restore both the original and modified positions
|
| 518 |
+
a._set_position(pos[a][0], 'original')
|
| 519 |
+
a._set_position(pos[a][1], 'active')
|
| 520 |
+
|
| 521 |
+
self.figure.canvas.draw_idle()
|
| 522 |
+
|
| 523 |
+
def push_current(self, figure=None):
|
| 524 |
+
"""
|
| 525 |
+
Push the current view limits and position onto their respective stacks.
|
| 526 |
+
"""
|
| 527 |
+
if not figure:
|
| 528 |
+
figure = self.figure
|
| 529 |
+
views = WeakKeyDictionary()
|
| 530 |
+
pos = WeakKeyDictionary()
|
| 531 |
+
for a in figure.get_axes():
|
| 532 |
+
views[a] = a._get_view()
|
| 533 |
+
pos[a] = self._axes_pos(a)
|
| 534 |
+
self.views[figure].push(views)
|
| 535 |
+
self.positions[figure].push(pos)
|
| 536 |
+
|
| 537 |
+
def _axes_pos(self, ax):
|
| 538 |
+
"""
|
| 539 |
+
Return the original and modified positions for the specified Axes.
|
| 540 |
+
|
| 541 |
+
Parameters
|
| 542 |
+
----------
|
| 543 |
+
ax : matplotlib.axes.Axes
|
| 544 |
+
The `.Axes` to get the positions for.
|
| 545 |
+
|
| 546 |
+
Returns
|
| 547 |
+
-------
|
| 548 |
+
original_position, modified_position
|
| 549 |
+
A tuple of the original and modified positions.
|
| 550 |
+
"""
|
| 551 |
+
|
| 552 |
+
return (ax.get_position(True).frozen(),
|
| 553 |
+
ax.get_position().frozen())
|
| 554 |
+
|
| 555 |
+
def update_home_views(self, figure=None):
|
| 556 |
+
"""
|
| 557 |
+
Make sure that ``self.home_views`` has an entry for all Axes present
|
| 558 |
+
in the figure.
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
if not figure:
|
| 562 |
+
figure = self.figure
|
| 563 |
+
for a in figure.get_axes():
|
| 564 |
+
if a not in self.home_views[figure]:
|
| 565 |
+
self.home_views[figure][a] = a._get_view()
|
| 566 |
+
|
| 567 |
+
def home(self):
|
| 568 |
+
"""Recall the first view and position from the stack."""
|
| 569 |
+
self.views[self.figure].home()
|
| 570 |
+
self.positions[self.figure].home()
|
| 571 |
+
|
| 572 |
+
def back(self):
|
| 573 |
+
"""Back one step in the stack of views and positions."""
|
| 574 |
+
self.views[self.figure].back()
|
| 575 |
+
self.positions[self.figure].back()
|
| 576 |
+
|
| 577 |
+
def forward(self):
|
| 578 |
+
"""Forward one step in the stack of views and positions."""
|
| 579 |
+
self.views[self.figure].forward()
|
| 580 |
+
self.positions[self.figure].forward()
|
| 581 |
+
|
| 582 |
+
|
| 583 |
+
class ViewsPositionsBase(ToolBase):
|
| 584 |
+
"""Base class for `ToolHome`, `ToolBack` and `ToolForward`."""
|
| 585 |
+
|
| 586 |
+
_on_trigger = None
|
| 587 |
+
|
| 588 |
+
def trigger(self, sender, event, data=None):
|
| 589 |
+
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
|
| 590 |
+
getattr(self.toolmanager.get_tool(_views_positions),
|
| 591 |
+
self._on_trigger)()
|
| 592 |
+
self.toolmanager.get_tool(_views_positions).update_view()
|
| 593 |
+
|
| 594 |
+
|
| 595 |
+
class ToolHome(ViewsPositionsBase):
|
| 596 |
+
"""Restore the original view limits."""
|
| 597 |
+
|
| 598 |
+
description = 'Reset original view'
|
| 599 |
+
image = 'mpl-data/images/home'
|
| 600 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.home'])
|
| 601 |
+
_on_trigger = 'home'
|
| 602 |
+
|
| 603 |
+
|
| 604 |
+
class ToolBack(ViewsPositionsBase):
|
| 605 |
+
"""Move back up the view limits stack."""
|
| 606 |
+
|
| 607 |
+
description = 'Back to previous view'
|
| 608 |
+
image = 'mpl-data/images/back'
|
| 609 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.back'])
|
| 610 |
+
_on_trigger = 'back'
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
class ToolForward(ViewsPositionsBase):
|
| 614 |
+
"""Move forward in the view lim stack."""
|
| 615 |
+
|
| 616 |
+
description = 'Forward to next view'
|
| 617 |
+
image = 'mpl-data/images/forward'
|
| 618 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.forward'])
|
| 619 |
+
_on_trigger = 'forward'
|
| 620 |
+
|
| 621 |
+
|
| 622 |
+
class ConfigureSubplotsBase(ToolBase):
|
| 623 |
+
"""Base tool for the configuration of subplots."""
|
| 624 |
+
|
| 625 |
+
description = 'Configure subplots'
|
| 626 |
+
image = 'mpl-data/images/subplots'
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
class SaveFigureBase(ToolBase):
|
| 630 |
+
"""Base tool for figure saving."""
|
| 631 |
+
|
| 632 |
+
description = 'Save the figure'
|
| 633 |
+
image = 'mpl-data/images/filesave'
|
| 634 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.save'])
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
class ZoomPanBase(ToolToggleBase):
|
| 638 |
+
"""Base class for `ToolZoom` and `ToolPan`."""
|
| 639 |
+
def __init__(self, *args):
|
| 640 |
+
super().__init__(*args)
|
| 641 |
+
self._button_pressed = None
|
| 642 |
+
self._xypress = None
|
| 643 |
+
self._idPress = None
|
| 644 |
+
self._idRelease = None
|
| 645 |
+
self._idScroll = None
|
| 646 |
+
self.base_scale = 2.
|
| 647 |
+
self.scrollthresh = .5 # .5 second scroll threshold
|
| 648 |
+
self.lastscroll = time.time()-self.scrollthresh
|
| 649 |
+
|
| 650 |
+
def enable(self, event=None):
|
| 651 |
+
"""Connect press/release events and lock the canvas."""
|
| 652 |
+
self.figure.canvas.widgetlock(self)
|
| 653 |
+
self._idPress = self.figure.canvas.mpl_connect(
|
| 654 |
+
'button_press_event', self._press)
|
| 655 |
+
self._idRelease = self.figure.canvas.mpl_connect(
|
| 656 |
+
'button_release_event', self._release)
|
| 657 |
+
self._idScroll = self.figure.canvas.mpl_connect(
|
| 658 |
+
'scroll_event', self.scroll_zoom)
|
| 659 |
+
|
| 660 |
+
def disable(self, event=None):
|
| 661 |
+
"""Release the canvas and disconnect press/release events."""
|
| 662 |
+
self._cancel_action()
|
| 663 |
+
self.figure.canvas.widgetlock.release(self)
|
| 664 |
+
self.figure.canvas.mpl_disconnect(self._idPress)
|
| 665 |
+
self.figure.canvas.mpl_disconnect(self._idRelease)
|
| 666 |
+
self.figure.canvas.mpl_disconnect(self._idScroll)
|
| 667 |
+
|
| 668 |
+
def trigger(self, sender, event, data=None):
|
| 669 |
+
self.toolmanager.get_tool(_views_positions).add_figure(self.figure)
|
| 670 |
+
super().trigger(sender, event, data)
|
| 671 |
+
new_navigate_mode = self.name.upper() if self.toggled else None
|
| 672 |
+
for ax in self.figure.axes:
|
| 673 |
+
ax.set_navigate_mode(new_navigate_mode)
|
| 674 |
+
|
| 675 |
+
def scroll_zoom(self, event):
|
| 676 |
+
# https://gist.github.com/tacaswell/3144287
|
| 677 |
+
if event.inaxes is None:
|
| 678 |
+
return
|
| 679 |
+
|
| 680 |
+
if event.button == 'up':
|
| 681 |
+
# deal with zoom in
|
| 682 |
+
scl = self.base_scale
|
| 683 |
+
elif event.button == 'down':
|
| 684 |
+
# deal with zoom out
|
| 685 |
+
scl = 1/self.base_scale
|
| 686 |
+
else:
|
| 687 |
+
# deal with something that should never happen
|
| 688 |
+
scl = 1
|
| 689 |
+
|
| 690 |
+
ax = event.inaxes
|
| 691 |
+
ax._set_view_from_bbox([event.x, event.y, scl])
|
| 692 |
+
|
| 693 |
+
# If last scroll was done within the timing threshold, delete the
|
| 694 |
+
# previous view
|
| 695 |
+
if (time.time()-self.lastscroll) < self.scrollthresh:
|
| 696 |
+
self.toolmanager.get_tool(_views_positions).back()
|
| 697 |
+
|
| 698 |
+
self.figure.canvas.draw_idle() # force re-draw
|
| 699 |
+
|
| 700 |
+
self.lastscroll = time.time()
|
| 701 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 702 |
+
|
| 703 |
+
|
| 704 |
+
class ToolZoom(ZoomPanBase):
|
| 705 |
+
"""A Tool for zooming using a rectangle selector."""
|
| 706 |
+
|
| 707 |
+
description = 'Zoom to rectangle'
|
| 708 |
+
image = 'mpl-data/images/zoom_to_rect'
|
| 709 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.zoom'])
|
| 710 |
+
cursor = cursors.SELECT_REGION
|
| 711 |
+
radio_group = 'default'
|
| 712 |
+
|
| 713 |
+
def __init__(self, *args):
|
| 714 |
+
super().__init__(*args)
|
| 715 |
+
self._ids_zoom = []
|
| 716 |
+
|
| 717 |
+
def _cancel_action(self):
|
| 718 |
+
for zoom_id in self._ids_zoom:
|
| 719 |
+
self.figure.canvas.mpl_disconnect(zoom_id)
|
| 720 |
+
self.toolmanager.trigger_tool('rubberband', self)
|
| 721 |
+
self.figure.canvas.draw_idle()
|
| 722 |
+
self._xypress = None
|
| 723 |
+
self._button_pressed = None
|
| 724 |
+
self._ids_zoom = []
|
| 725 |
+
return
|
| 726 |
+
|
| 727 |
+
def _press(self, event):
|
| 728 |
+
"""Callback for mouse button presses in zoom-to-rectangle mode."""
|
| 729 |
+
|
| 730 |
+
# If we're already in the middle of a zoom, pressing another
|
| 731 |
+
# button works to "cancel"
|
| 732 |
+
if self._ids_zoom:
|
| 733 |
+
self._cancel_action()
|
| 734 |
+
|
| 735 |
+
if event.button == 1:
|
| 736 |
+
self._button_pressed = 1
|
| 737 |
+
elif event.button == 3:
|
| 738 |
+
self._button_pressed = 3
|
| 739 |
+
else:
|
| 740 |
+
self._cancel_action()
|
| 741 |
+
return
|
| 742 |
+
|
| 743 |
+
x, y = event.x, event.y
|
| 744 |
+
|
| 745 |
+
self._xypress = []
|
| 746 |
+
for i, a in enumerate(self.figure.get_axes()):
|
| 747 |
+
if (x is not None and y is not None and a.in_axes(event) and
|
| 748 |
+
a.get_navigate() and a.can_zoom()):
|
| 749 |
+
self._xypress.append((x, y, a, i, a._get_view()))
|
| 750 |
+
|
| 751 |
+
id1 = self.figure.canvas.mpl_connect(
|
| 752 |
+
'motion_notify_event', self._mouse_move)
|
| 753 |
+
id2 = self.figure.canvas.mpl_connect(
|
| 754 |
+
'key_press_event', self._switch_on_zoom_mode)
|
| 755 |
+
id3 = self.figure.canvas.mpl_connect(
|
| 756 |
+
'key_release_event', self._switch_off_zoom_mode)
|
| 757 |
+
|
| 758 |
+
self._ids_zoom = id1, id2, id3
|
| 759 |
+
self._zoom_mode = event.key
|
| 760 |
+
|
| 761 |
+
def _switch_on_zoom_mode(self, event):
|
| 762 |
+
self._zoom_mode = event.key
|
| 763 |
+
self._mouse_move(event)
|
| 764 |
+
|
| 765 |
+
def _switch_off_zoom_mode(self, event):
|
| 766 |
+
self._zoom_mode = None
|
| 767 |
+
self._mouse_move(event)
|
| 768 |
+
|
| 769 |
+
def _mouse_move(self, event):
|
| 770 |
+
"""Callback for mouse moves in zoom-to-rectangle mode."""
|
| 771 |
+
|
| 772 |
+
if self._xypress:
|
| 773 |
+
x, y = event.x, event.y
|
| 774 |
+
lastx, lasty, a, ind, view = self._xypress[0]
|
| 775 |
+
(x1, y1), (x2, y2) = np.clip(
|
| 776 |
+
[[lastx, lasty], [x, y]], a.bbox.min, a.bbox.max)
|
| 777 |
+
if self._zoom_mode == "x":
|
| 778 |
+
y1, y2 = a.bbox.intervaly
|
| 779 |
+
elif self._zoom_mode == "y":
|
| 780 |
+
x1, x2 = a.bbox.intervalx
|
| 781 |
+
self.toolmanager.trigger_tool(
|
| 782 |
+
'rubberband', self, data=(x1, y1, x2, y2))
|
| 783 |
+
|
| 784 |
+
def _release(self, event):
|
| 785 |
+
"""Callback for mouse button releases in zoom-to-rectangle mode."""
|
| 786 |
+
|
| 787 |
+
for zoom_id in self._ids_zoom:
|
| 788 |
+
self.figure.canvas.mpl_disconnect(zoom_id)
|
| 789 |
+
self._ids_zoom = []
|
| 790 |
+
|
| 791 |
+
if not self._xypress:
|
| 792 |
+
self._cancel_action()
|
| 793 |
+
return
|
| 794 |
+
|
| 795 |
+
done_ax = []
|
| 796 |
+
|
| 797 |
+
for cur_xypress in self._xypress:
|
| 798 |
+
x, y = event.x, event.y
|
| 799 |
+
lastx, lasty, a, _ind, view = cur_xypress
|
| 800 |
+
# ignore singular clicks - 5 pixels is a threshold
|
| 801 |
+
if abs(x - lastx) < 5 or abs(y - lasty) < 5:
|
| 802 |
+
self._cancel_action()
|
| 803 |
+
return
|
| 804 |
+
|
| 805 |
+
# detect twinx, twiny Axes and avoid double zooming
|
| 806 |
+
twinx = any(a.get_shared_x_axes().joined(a, a1) for a1 in done_ax)
|
| 807 |
+
twiny = any(a.get_shared_y_axes().joined(a, a1) for a1 in done_ax)
|
| 808 |
+
done_ax.append(a)
|
| 809 |
+
|
| 810 |
+
if self._button_pressed == 1:
|
| 811 |
+
direction = 'in'
|
| 812 |
+
elif self._button_pressed == 3:
|
| 813 |
+
direction = 'out'
|
| 814 |
+
else:
|
| 815 |
+
continue
|
| 816 |
+
|
| 817 |
+
a._set_view_from_bbox((lastx, lasty, x, y), direction,
|
| 818 |
+
self._zoom_mode, twinx, twiny)
|
| 819 |
+
|
| 820 |
+
self._zoom_mode = None
|
| 821 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 822 |
+
self._cancel_action()
|
| 823 |
+
|
| 824 |
+
|
| 825 |
+
class ToolPan(ZoomPanBase):
|
| 826 |
+
"""Pan Axes with left mouse, zoom with right."""
|
| 827 |
+
|
| 828 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.pan'])
|
| 829 |
+
description = 'Pan axes with left mouse, zoom with right'
|
| 830 |
+
image = 'mpl-data/images/move'
|
| 831 |
+
cursor = cursors.MOVE
|
| 832 |
+
radio_group = 'default'
|
| 833 |
+
|
| 834 |
+
def __init__(self, *args):
|
| 835 |
+
super().__init__(*args)
|
| 836 |
+
self._id_drag = None
|
| 837 |
+
|
| 838 |
+
def _cancel_action(self):
|
| 839 |
+
self._button_pressed = None
|
| 840 |
+
self._xypress = []
|
| 841 |
+
self.figure.canvas.mpl_disconnect(self._id_drag)
|
| 842 |
+
self.toolmanager.messagelock.release(self)
|
| 843 |
+
self.figure.canvas.draw_idle()
|
| 844 |
+
|
| 845 |
+
def _press(self, event):
|
| 846 |
+
if event.button == 1:
|
| 847 |
+
self._button_pressed = 1
|
| 848 |
+
elif event.button == 3:
|
| 849 |
+
self._button_pressed = 3
|
| 850 |
+
else:
|
| 851 |
+
self._cancel_action()
|
| 852 |
+
return
|
| 853 |
+
|
| 854 |
+
x, y = event.x, event.y
|
| 855 |
+
|
| 856 |
+
self._xypress = []
|
| 857 |
+
for i, a in enumerate(self.figure.get_axes()):
|
| 858 |
+
if (x is not None and y is not None and a.in_axes(event) and
|
| 859 |
+
a.get_navigate() and a.can_pan()):
|
| 860 |
+
a.start_pan(x, y, event.button)
|
| 861 |
+
self._xypress.append((a, i))
|
| 862 |
+
self.toolmanager.messagelock(self)
|
| 863 |
+
self._id_drag = self.figure.canvas.mpl_connect(
|
| 864 |
+
'motion_notify_event', self._mouse_move)
|
| 865 |
+
|
| 866 |
+
def _release(self, event):
|
| 867 |
+
if self._button_pressed is None:
|
| 868 |
+
self._cancel_action()
|
| 869 |
+
return
|
| 870 |
+
|
| 871 |
+
self.figure.canvas.mpl_disconnect(self._id_drag)
|
| 872 |
+
self.toolmanager.messagelock.release(self)
|
| 873 |
+
|
| 874 |
+
for a, _ind in self._xypress:
|
| 875 |
+
a.end_pan()
|
| 876 |
+
if not self._xypress:
|
| 877 |
+
self._cancel_action()
|
| 878 |
+
return
|
| 879 |
+
|
| 880 |
+
self.toolmanager.get_tool(_views_positions).push_current()
|
| 881 |
+
self._cancel_action()
|
| 882 |
+
|
| 883 |
+
def _mouse_move(self, event):
|
| 884 |
+
for a, _ind in self._xypress:
|
| 885 |
+
# safer to use the recorded button at the _press than current
|
| 886 |
+
# button: # multiple button can get pressed during motion...
|
| 887 |
+
a.drag_pan(self._button_pressed, event.key, event.x, event.y)
|
| 888 |
+
self.toolmanager.canvas.draw_idle()
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
class ToolHelpBase(ToolBase):
|
| 892 |
+
description = 'Print tool list, shortcuts and description'
|
| 893 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.help'])
|
| 894 |
+
image = 'mpl-data/images/help'
|
| 895 |
+
|
| 896 |
+
@staticmethod
|
| 897 |
+
def format_shortcut(key_sequence):
|
| 898 |
+
"""
|
| 899 |
+
Convert a shortcut string from the notation used in rc config to the
|
| 900 |
+
standard notation for displaying shortcuts, e.g. 'ctrl+a' -> 'Ctrl+A'.
|
| 901 |
+
"""
|
| 902 |
+
return (key_sequence if len(key_sequence) == 1 else
|
| 903 |
+
re.sub(r"\+[A-Z]", r"+Shift\g<0>", key_sequence).title())
|
| 904 |
+
|
| 905 |
+
def _format_tool_keymap(self, name):
|
| 906 |
+
keymaps = self.toolmanager.get_tool_keymap(name)
|
| 907 |
+
return ", ".join(self.format_shortcut(keymap) for keymap in keymaps)
|
| 908 |
+
|
| 909 |
+
def _get_help_entries(self):
|
| 910 |
+
return [(name, self._format_tool_keymap(name), tool.description)
|
| 911 |
+
for name, tool in sorted(self.toolmanager.tools.items())
|
| 912 |
+
if tool.description]
|
| 913 |
+
|
| 914 |
+
def _get_help_text(self):
|
| 915 |
+
entries = self._get_help_entries()
|
| 916 |
+
entries = ["{}: {}\n\t{}".format(*entry) for entry in entries]
|
| 917 |
+
return "\n".join(entries)
|
| 918 |
+
|
| 919 |
+
def _get_help_html(self):
|
| 920 |
+
fmt = "<tr><td>{}</td><td>{}</td><td>{}</td></tr>"
|
| 921 |
+
rows = [fmt.format(
|
| 922 |
+
"<b>Action</b>", "<b>Shortcuts</b>", "<b>Description</b>")]
|
| 923 |
+
rows += [fmt.format(*row) for row in self._get_help_entries()]
|
| 924 |
+
return ("<style>td {padding: 0px 4px}</style>"
|
| 925 |
+
"<table><thead>" + rows[0] + "</thead>"
|
| 926 |
+
"<tbody>".join(rows[1:]) + "</tbody></table>")
|
| 927 |
+
|
| 928 |
+
|
| 929 |
+
class ToolCopyToClipboardBase(ToolBase):
|
| 930 |
+
"""Tool to copy the figure to the clipboard."""
|
| 931 |
+
|
| 932 |
+
description = 'Copy the canvas figure to clipboard'
|
| 933 |
+
default_keymap = property(lambda self: mpl.rcParams['keymap.copy'])
|
| 934 |
+
|
| 935 |
+
def trigger(self, *args, **kwargs):
|
| 936 |
+
message = "Copy tool is not available"
|
| 937 |
+
self.toolmanager.message_event(message, self)
|
| 938 |
+
|
| 939 |
+
|
| 940 |
+
default_tools = {'home': ToolHome, 'back': ToolBack, 'forward': ToolForward,
|
| 941 |
+
'zoom': ToolZoom, 'pan': ToolPan,
|
| 942 |
+
'subplots': ConfigureSubplotsBase,
|
| 943 |
+
'save': SaveFigureBase,
|
| 944 |
+
'grid': ToolGrid,
|
| 945 |
+
'grid_minor': ToolMinorGrid,
|
| 946 |
+
'fullscreen': ToolFullScreen,
|
| 947 |
+
'quit': ToolQuit,
|
| 948 |
+
'quit_all': ToolQuitAll,
|
| 949 |
+
'xscale': ToolXScale,
|
| 950 |
+
'yscale': ToolYScale,
|
| 951 |
+
'position': ToolCursorPosition,
|
| 952 |
+
_views_positions: ToolViewsPositions,
|
| 953 |
+
'cursor': ToolSetCursor,
|
| 954 |
+
'rubberband': RubberbandBase,
|
| 955 |
+
'help': ToolHelpBase,
|
| 956 |
+
'copy': ToolCopyToClipboardBase,
|
| 957 |
+
}
|
| 958 |
+
|
| 959 |
+
default_toolbar_tools = [['navigation', ['home', 'back', 'forward']],
|
| 960 |
+
['zoompan', ['pan', 'zoom', 'subplots']],
|
| 961 |
+
['io', ['save', 'help']]]
|
| 962 |
+
|
| 963 |
+
|
| 964 |
+
def add_tools_to_manager(toolmanager, tools=default_tools):
|
| 965 |
+
"""
|
| 966 |
+
Add multiple tools to a `.ToolManager`.
|
| 967 |
+
|
| 968 |
+
Parameters
|
| 969 |
+
----------
|
| 970 |
+
toolmanager : `.backend_managers.ToolManager`
|
| 971 |
+
Manager to which the tools are added.
|
| 972 |
+
tools : {str: class_like}, optional
|
| 973 |
+
The tools to add in a {name: tool} dict, see
|
| 974 |
+
`.backend_managers.ToolManager.add_tool` for more info.
|
| 975 |
+
"""
|
| 976 |
+
|
| 977 |
+
for name, tool in tools.items():
|
| 978 |
+
toolmanager.add_tool(name, tool)
|
| 979 |
+
|
| 980 |
+
|
| 981 |
+
def add_tools_to_container(container, tools=default_toolbar_tools):
|
| 982 |
+
"""
|
| 983 |
+
Add multiple tools to the container.
|
| 984 |
+
|
| 985 |
+
Parameters
|
| 986 |
+
----------
|
| 987 |
+
container : Container
|
| 988 |
+
`.backend_bases.ToolContainerBase` object that will get the tools
|
| 989 |
+
added.
|
| 990 |
+
tools : list, optional
|
| 991 |
+
List in the form ``[[group1, [tool1, tool2 ...]], [group2, [...]]]``
|
| 992 |
+
where the tools ``[tool1, tool2, ...]`` will display in group1.
|
| 993 |
+
See `.backend_bases.ToolContainerBase.add_tool` for details.
|
| 994 |
+
"""
|
| 995 |
+
|
| 996 |
+
for group, grouptools in tools:
|
| 997 |
+
for position, tool in enumerate(grouptools):
|
| 998 |
+
container.add_tool(tool, group, position)
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/bezier.py
ADDED
|
@@ -0,0 +1,602 @@
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A module providing some utility functions regarding Bézier path manipulation.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
from functools import lru_cache
|
| 6 |
+
import math
|
| 7 |
+
import warnings
|
| 8 |
+
|
| 9 |
+
import numpy as np
|
| 10 |
+
|
| 11 |
+
from matplotlib import _api
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
# same algorithm as 3.8's math.comb
|
| 15 |
+
@np.vectorize
|
| 16 |
+
@lru_cache(maxsize=128)
|
| 17 |
+
def _comb(n, k):
|
| 18 |
+
if k > n:
|
| 19 |
+
return 0
|
| 20 |
+
k = min(k, n - k)
|
| 21 |
+
i = np.arange(1, k + 1)
|
| 22 |
+
return np.prod((n + 1 - i)/i).astype(int)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class NonIntersectingPathException(ValueError):
|
| 26 |
+
pass
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# some functions
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_intersection(cx1, cy1, cos_t1, sin_t1,
|
| 33 |
+
cx2, cy2, cos_t2, sin_t2):
|
| 34 |
+
"""
|
| 35 |
+
Return the intersection between the line through (*cx1*, *cy1*) at angle
|
| 36 |
+
*t1* and the line through (*cx2*, *cy2*) at angle *t2*.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
# line1 => sin_t1 * (x - cx1) - cos_t1 * (y - cy1) = 0.
|
| 40 |
+
# line1 => sin_t1 * x + cos_t1 * y = sin_t1*cx1 - cos_t1*cy1
|
| 41 |
+
|
| 42 |
+
line1_rhs = sin_t1 * cx1 - cos_t1 * cy1
|
| 43 |
+
line2_rhs = sin_t2 * cx2 - cos_t2 * cy2
|
| 44 |
+
|
| 45 |
+
# rhs matrix
|
| 46 |
+
a, b = sin_t1, -cos_t1
|
| 47 |
+
c, d = sin_t2, -cos_t2
|
| 48 |
+
|
| 49 |
+
ad_bc = a * d - b * c
|
| 50 |
+
if abs(ad_bc) < 1e-12:
|
| 51 |
+
raise ValueError("Given lines do not intersect. Please verify that "
|
| 52 |
+
"the angles are not equal or differ by 180 degrees.")
|
| 53 |
+
|
| 54 |
+
# rhs_inverse
|
| 55 |
+
a_, b_ = d, -b
|
| 56 |
+
c_, d_ = -c, a
|
| 57 |
+
a_, b_, c_, d_ = (k / ad_bc for k in [a_, b_, c_, d_])
|
| 58 |
+
|
| 59 |
+
x = a_ * line1_rhs + b_ * line2_rhs
|
| 60 |
+
y = c_ * line1_rhs + d_ * line2_rhs
|
| 61 |
+
|
| 62 |
+
return x, y
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def get_normal_points(cx, cy, cos_t, sin_t, length):
|
| 66 |
+
"""
|
| 67 |
+
For a line passing through (*cx*, *cy*) and having an angle *t*, return
|
| 68 |
+
locations of the two points located along its perpendicular line at the
|
| 69 |
+
distance of *length*.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
if length == 0.:
|
| 73 |
+
return cx, cy, cx, cy
|
| 74 |
+
|
| 75 |
+
cos_t1, sin_t1 = sin_t, -cos_t
|
| 76 |
+
cos_t2, sin_t2 = -sin_t, cos_t
|
| 77 |
+
|
| 78 |
+
x1, y1 = length * cos_t1 + cx, length * sin_t1 + cy
|
| 79 |
+
x2, y2 = length * cos_t2 + cx, length * sin_t2 + cy
|
| 80 |
+
|
| 81 |
+
return x1, y1, x2, y2
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
# BEZIER routines
|
| 85 |
+
|
| 86 |
+
# subdividing bezier curve
|
| 87 |
+
# http://www.cs.mtu.edu/~shene/COURSES/cs3621/NOTES/spline/Bezier/bezier-sub.html
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def _de_casteljau1(beta, t):
|
| 91 |
+
next_beta = beta[:-1] * (1 - t) + beta[1:] * t
|
| 92 |
+
return next_beta
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def split_de_casteljau(beta, t):
|
| 96 |
+
"""
|
| 97 |
+
Split a Bézier segment defined by its control points *beta* into two
|
| 98 |
+
separate segments divided at *t* and return their control points.
|
| 99 |
+
"""
|
| 100 |
+
beta = np.asarray(beta)
|
| 101 |
+
beta_list = [beta]
|
| 102 |
+
while True:
|
| 103 |
+
beta = _de_casteljau1(beta, t)
|
| 104 |
+
beta_list.append(beta)
|
| 105 |
+
if len(beta) == 1:
|
| 106 |
+
break
|
| 107 |
+
left_beta = [beta[0] for beta in beta_list]
|
| 108 |
+
right_beta = [beta[-1] for beta in reversed(beta_list)]
|
| 109 |
+
|
| 110 |
+
return left_beta, right_beta
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def find_bezier_t_intersecting_with_closedpath(
|
| 114 |
+
bezier_point_at_t, inside_closedpath, t0=0., t1=1., tolerance=0.01):
|
| 115 |
+
"""
|
| 116 |
+
Find the intersection of the Bézier curve with a closed path.
|
| 117 |
+
|
| 118 |
+
The intersection point *t* is approximated by two parameters *t0*, *t1*
|
| 119 |
+
such that *t0* <= *t* <= *t1*.
|
| 120 |
+
|
| 121 |
+
Search starts from *t0* and *t1* and uses a simple bisecting algorithm
|
| 122 |
+
therefore one of the end points must be inside the path while the other
|
| 123 |
+
doesn't. The search stops when the distance of the points parametrized by
|
| 124 |
+
*t0* and *t1* gets smaller than the given *tolerance*.
|
| 125 |
+
|
| 126 |
+
Parameters
|
| 127 |
+
----------
|
| 128 |
+
bezier_point_at_t : callable
|
| 129 |
+
A function returning x, y coordinates of the Bézier at parameter *t*.
|
| 130 |
+
It must have the signature::
|
| 131 |
+
|
| 132 |
+
bezier_point_at_t(t: float) -> tuple[float, float]
|
| 133 |
+
|
| 134 |
+
inside_closedpath : callable
|
| 135 |
+
A function returning True if a given point (x, y) is inside the
|
| 136 |
+
closed path. It must have the signature::
|
| 137 |
+
|
| 138 |
+
inside_closedpath(point: tuple[float, float]) -> bool
|
| 139 |
+
|
| 140 |
+
t0, t1 : float
|
| 141 |
+
Start parameters for the search.
|
| 142 |
+
|
| 143 |
+
tolerance : float
|
| 144 |
+
Maximal allowed distance between the final points.
|
| 145 |
+
|
| 146 |
+
Returns
|
| 147 |
+
-------
|
| 148 |
+
t0, t1 : float
|
| 149 |
+
The Bézier path parameters.
|
| 150 |
+
"""
|
| 151 |
+
start = bezier_point_at_t(t0)
|
| 152 |
+
end = bezier_point_at_t(t1)
|
| 153 |
+
|
| 154 |
+
start_inside = inside_closedpath(start)
|
| 155 |
+
end_inside = inside_closedpath(end)
|
| 156 |
+
|
| 157 |
+
if start_inside == end_inside and start != end:
|
| 158 |
+
raise NonIntersectingPathException(
|
| 159 |
+
"Both points are on the same side of the closed path")
|
| 160 |
+
|
| 161 |
+
while True:
|
| 162 |
+
|
| 163 |
+
# return if the distance is smaller than the tolerance
|
| 164 |
+
if np.hypot(start[0] - end[0], start[1] - end[1]) < tolerance:
|
| 165 |
+
return t0, t1
|
| 166 |
+
|
| 167 |
+
# calculate the middle point
|
| 168 |
+
middle_t = 0.5 * (t0 + t1)
|
| 169 |
+
middle = bezier_point_at_t(middle_t)
|
| 170 |
+
middle_inside = inside_closedpath(middle)
|
| 171 |
+
|
| 172 |
+
if start_inside ^ middle_inside:
|
| 173 |
+
t1 = middle_t
|
| 174 |
+
if end == middle:
|
| 175 |
+
# Edge case where infinite loop is possible
|
| 176 |
+
# Caused by large numbers relative to tolerance
|
| 177 |
+
return t0, t1
|
| 178 |
+
end = middle
|
| 179 |
+
else:
|
| 180 |
+
t0 = middle_t
|
| 181 |
+
if start == middle:
|
| 182 |
+
# Edge case where infinite loop is possible
|
| 183 |
+
# Caused by large numbers relative to tolerance
|
| 184 |
+
return t0, t1
|
| 185 |
+
start = middle
|
| 186 |
+
start_inside = middle_inside
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
class BezierSegment:
|
| 190 |
+
"""
|
| 191 |
+
A d-dimensional Bézier segment.
|
| 192 |
+
|
| 193 |
+
Parameters
|
| 194 |
+
----------
|
| 195 |
+
control_points : (N, d) array
|
| 196 |
+
Location of the *N* control points.
|
| 197 |
+
"""
|
| 198 |
+
|
| 199 |
+
def __init__(self, control_points):
|
| 200 |
+
self._cpoints = np.asarray(control_points)
|
| 201 |
+
self._N, self._d = self._cpoints.shape
|
| 202 |
+
self._orders = np.arange(self._N)
|
| 203 |
+
coeff = [math.factorial(self._N - 1)
|
| 204 |
+
// (math.factorial(i) * math.factorial(self._N - 1 - i))
|
| 205 |
+
for i in range(self._N)]
|
| 206 |
+
self._px = (self._cpoints.T * coeff).T
|
| 207 |
+
|
| 208 |
+
def __call__(self, t):
|
| 209 |
+
"""
|
| 210 |
+
Evaluate the Bézier curve at point(s) *t* in [0, 1].
|
| 211 |
+
|
| 212 |
+
Parameters
|
| 213 |
+
----------
|
| 214 |
+
t : (k,) array-like
|
| 215 |
+
Points at which to evaluate the curve.
|
| 216 |
+
|
| 217 |
+
Returns
|
| 218 |
+
-------
|
| 219 |
+
(k, d) array
|
| 220 |
+
Value of the curve for each point in *t*.
|
| 221 |
+
"""
|
| 222 |
+
t = np.asarray(t)
|
| 223 |
+
return (np.power.outer(1 - t, self._orders[::-1])
|
| 224 |
+
* np.power.outer(t, self._orders)) @ self._px
|
| 225 |
+
|
| 226 |
+
def point_at_t(self, t):
|
| 227 |
+
"""
|
| 228 |
+
Evaluate the curve at a single point, returning a tuple of *d* floats.
|
| 229 |
+
"""
|
| 230 |
+
return tuple(self(t))
|
| 231 |
+
|
| 232 |
+
@property
|
| 233 |
+
def control_points(self):
|
| 234 |
+
"""The control points of the curve."""
|
| 235 |
+
return self._cpoints
|
| 236 |
+
|
| 237 |
+
@property
|
| 238 |
+
def dimension(self):
|
| 239 |
+
"""The dimension of the curve."""
|
| 240 |
+
return self._d
|
| 241 |
+
|
| 242 |
+
@property
|
| 243 |
+
def degree(self):
|
| 244 |
+
"""Degree of the polynomial. One less the number of control points."""
|
| 245 |
+
return self._N - 1
|
| 246 |
+
|
| 247 |
+
@property
|
| 248 |
+
def polynomial_coefficients(self):
|
| 249 |
+
r"""
|
| 250 |
+
The polynomial coefficients of the Bézier curve.
|
| 251 |
+
|
| 252 |
+
.. warning:: Follows opposite convention from `numpy.polyval`.
|
| 253 |
+
|
| 254 |
+
Returns
|
| 255 |
+
-------
|
| 256 |
+
(n+1, d) array
|
| 257 |
+
Coefficients after expanding in polynomial basis, where :math:`n`
|
| 258 |
+
is the degree of the Bézier curve and :math:`d` its dimension.
|
| 259 |
+
These are the numbers (:math:`C_j`) such that the curve can be
|
| 260 |
+
written :math:`\sum_{j=0}^n C_j t^j`.
|
| 261 |
+
|
| 262 |
+
Notes
|
| 263 |
+
-----
|
| 264 |
+
The coefficients are calculated as
|
| 265 |
+
|
| 266 |
+
.. math::
|
| 267 |
+
|
| 268 |
+
{n \choose j} \sum_{i=0}^j (-1)^{i+j} {j \choose i} P_i
|
| 269 |
+
|
| 270 |
+
where :math:`P_i` are the control points of the curve.
|
| 271 |
+
"""
|
| 272 |
+
n = self.degree
|
| 273 |
+
# matplotlib uses n <= 4. overflow plausible starting around n = 15.
|
| 274 |
+
if n > 10:
|
| 275 |
+
warnings.warn("Polynomial coefficients formula unstable for high "
|
| 276 |
+
"order Bezier curves!", RuntimeWarning)
|
| 277 |
+
P = self.control_points
|
| 278 |
+
j = np.arange(n+1)[:, None]
|
| 279 |
+
i = np.arange(n+1)[None, :] # _comb is non-zero for i <= j
|
| 280 |
+
prefactor = (-1)**(i + j) * _comb(j, i) # j on axis 0, i on axis 1
|
| 281 |
+
return _comb(n, j) * prefactor @ P # j on axis 0, self.dimension on 1
|
| 282 |
+
|
| 283 |
+
def axis_aligned_extrema(self):
|
| 284 |
+
"""
|
| 285 |
+
Return the dimension and location of the curve's interior extrema.
|
| 286 |
+
|
| 287 |
+
The extrema are the points along the curve where one of its partial
|
| 288 |
+
derivatives is zero.
|
| 289 |
+
|
| 290 |
+
Returns
|
| 291 |
+
-------
|
| 292 |
+
dims : array of int
|
| 293 |
+
Index :math:`i` of the partial derivative which is zero at each
|
| 294 |
+
interior extrema.
|
| 295 |
+
dzeros : array of float
|
| 296 |
+
Of same size as dims. The :math:`t` such that :math:`d/dx_i B(t) =
|
| 297 |
+
0`
|
| 298 |
+
"""
|
| 299 |
+
n = self.degree
|
| 300 |
+
if n <= 1:
|
| 301 |
+
return np.array([]), np.array([])
|
| 302 |
+
Cj = self.polynomial_coefficients
|
| 303 |
+
dCj = np.arange(1, n+1)[:, None] * Cj[1:]
|
| 304 |
+
dims = []
|
| 305 |
+
roots = []
|
| 306 |
+
for i, pi in enumerate(dCj.T):
|
| 307 |
+
r = np.roots(pi[::-1])
|
| 308 |
+
roots.append(r)
|
| 309 |
+
dims.append(np.full_like(r, i))
|
| 310 |
+
roots = np.concatenate(roots)
|
| 311 |
+
dims = np.concatenate(dims)
|
| 312 |
+
in_range = np.isreal(roots) & (roots >= 0) & (roots <= 1)
|
| 313 |
+
return dims[in_range], np.real(roots)[in_range]
|
| 314 |
+
|
| 315 |
+
|
| 316 |
+
def split_bezier_intersecting_with_closedpath(
|
| 317 |
+
bezier, inside_closedpath, tolerance=0.01):
|
| 318 |
+
"""
|
| 319 |
+
Split a Bézier curve into two at the intersection with a closed path.
|
| 320 |
+
|
| 321 |
+
Parameters
|
| 322 |
+
----------
|
| 323 |
+
bezier : (N, 2) array-like
|
| 324 |
+
Control points of the Bézier segment. See `.BezierSegment`.
|
| 325 |
+
inside_closedpath : callable
|
| 326 |
+
A function returning True if a given point (x, y) is inside the
|
| 327 |
+
closed path. See also `.find_bezier_t_intersecting_with_closedpath`.
|
| 328 |
+
tolerance : float
|
| 329 |
+
The tolerance for the intersection. See also
|
| 330 |
+
`.find_bezier_t_intersecting_with_closedpath`.
|
| 331 |
+
|
| 332 |
+
Returns
|
| 333 |
+
-------
|
| 334 |
+
left, right
|
| 335 |
+
Lists of control points for the two Bézier segments.
|
| 336 |
+
"""
|
| 337 |
+
|
| 338 |
+
bz = BezierSegment(bezier)
|
| 339 |
+
bezier_point_at_t = bz.point_at_t
|
| 340 |
+
|
| 341 |
+
t0, t1 = find_bezier_t_intersecting_with_closedpath(
|
| 342 |
+
bezier_point_at_t, inside_closedpath, tolerance=tolerance)
|
| 343 |
+
|
| 344 |
+
_left, _right = split_de_casteljau(bezier, (t0 + t1) / 2.)
|
| 345 |
+
return _left, _right
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
# matplotlib specific
|
| 349 |
+
|
| 350 |
+
|
| 351 |
+
def split_path_inout(path, inside, tolerance=0.01, reorder_inout=False):
|
| 352 |
+
"""
|
| 353 |
+
Divide a path into two segments at the point where ``inside(x, y)`` becomes
|
| 354 |
+
False.
|
| 355 |
+
"""
|
| 356 |
+
from .path import Path
|
| 357 |
+
path_iter = path.iter_segments()
|
| 358 |
+
|
| 359 |
+
ctl_points, command = next(path_iter)
|
| 360 |
+
begin_inside = inside(ctl_points[-2:]) # true if begin point is inside
|
| 361 |
+
|
| 362 |
+
ctl_points_old = ctl_points
|
| 363 |
+
|
| 364 |
+
iold = 0
|
| 365 |
+
i = 1
|
| 366 |
+
|
| 367 |
+
for ctl_points, command in path_iter:
|
| 368 |
+
iold = i
|
| 369 |
+
i += len(ctl_points) // 2
|
| 370 |
+
if inside(ctl_points[-2:]) != begin_inside:
|
| 371 |
+
bezier_path = np.concatenate([ctl_points_old[-2:], ctl_points])
|
| 372 |
+
break
|
| 373 |
+
ctl_points_old = ctl_points
|
| 374 |
+
else:
|
| 375 |
+
raise ValueError("The path does not intersect with the patch")
|
| 376 |
+
|
| 377 |
+
bp = bezier_path.reshape((-1, 2))
|
| 378 |
+
left, right = split_bezier_intersecting_with_closedpath(
|
| 379 |
+
bp, inside, tolerance)
|
| 380 |
+
if len(left) == 2:
|
| 381 |
+
codes_left = [Path.LINETO]
|
| 382 |
+
codes_right = [Path.MOVETO, Path.LINETO]
|
| 383 |
+
elif len(left) == 3:
|
| 384 |
+
codes_left = [Path.CURVE3, Path.CURVE3]
|
| 385 |
+
codes_right = [Path.MOVETO, Path.CURVE3, Path.CURVE3]
|
| 386 |
+
elif len(left) == 4:
|
| 387 |
+
codes_left = [Path.CURVE4, Path.CURVE4, Path.CURVE4]
|
| 388 |
+
codes_right = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]
|
| 389 |
+
else:
|
| 390 |
+
raise AssertionError("This should never be reached")
|
| 391 |
+
|
| 392 |
+
verts_left = left[1:]
|
| 393 |
+
verts_right = right[:]
|
| 394 |
+
|
| 395 |
+
if path.codes is None:
|
| 396 |
+
path_in = Path(np.concatenate([path.vertices[:i], verts_left]))
|
| 397 |
+
path_out = Path(np.concatenate([verts_right, path.vertices[i:]]))
|
| 398 |
+
|
| 399 |
+
else:
|
| 400 |
+
path_in = Path(np.concatenate([path.vertices[:iold], verts_left]),
|
| 401 |
+
np.concatenate([path.codes[:iold], codes_left]))
|
| 402 |
+
|
| 403 |
+
path_out = Path(np.concatenate([verts_right, path.vertices[i:]]),
|
| 404 |
+
np.concatenate([codes_right, path.codes[i:]]))
|
| 405 |
+
|
| 406 |
+
if reorder_inout and not begin_inside:
|
| 407 |
+
path_in, path_out = path_out, path_in
|
| 408 |
+
|
| 409 |
+
return path_in, path_out
|
| 410 |
+
|
| 411 |
+
|
| 412 |
+
def inside_circle(cx, cy, r):
|
| 413 |
+
"""
|
| 414 |
+
Return a function that checks whether a point is in a circle with center
|
| 415 |
+
(*cx*, *cy*) and radius *r*.
|
| 416 |
+
|
| 417 |
+
The returned function has the signature::
|
| 418 |
+
|
| 419 |
+
f(xy: tuple[float, float]) -> bool
|
| 420 |
+
"""
|
| 421 |
+
r2 = r ** 2
|
| 422 |
+
|
| 423 |
+
def _f(xy):
|
| 424 |
+
x, y = xy
|
| 425 |
+
return (x - cx) ** 2 + (y - cy) ** 2 < r2
|
| 426 |
+
return _f
|
| 427 |
+
|
| 428 |
+
|
| 429 |
+
# quadratic Bezier lines
|
| 430 |
+
|
| 431 |
+
def get_cos_sin(x0, y0, x1, y1):
|
| 432 |
+
dx, dy = x1 - x0, y1 - y0
|
| 433 |
+
d = (dx * dx + dy * dy) ** .5
|
| 434 |
+
# Account for divide by zero
|
| 435 |
+
if d == 0:
|
| 436 |
+
return 0.0, 0.0
|
| 437 |
+
return dx / d, dy / d
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def check_if_parallel(dx1, dy1, dx2, dy2, tolerance=1.e-5):
|
| 441 |
+
"""
|
| 442 |
+
Check if two lines are parallel.
|
| 443 |
+
|
| 444 |
+
Parameters
|
| 445 |
+
----------
|
| 446 |
+
dx1, dy1, dx2, dy2 : float
|
| 447 |
+
The gradients *dy*/*dx* of the two lines.
|
| 448 |
+
tolerance : float
|
| 449 |
+
The angular tolerance in radians up to which the lines are considered
|
| 450 |
+
parallel.
|
| 451 |
+
|
| 452 |
+
Returns
|
| 453 |
+
-------
|
| 454 |
+
is_parallel
|
| 455 |
+
- 1 if two lines are parallel in same direction.
|
| 456 |
+
- -1 if two lines are parallel in opposite direction.
|
| 457 |
+
- False otherwise.
|
| 458 |
+
"""
|
| 459 |
+
theta1 = np.arctan2(dx1, dy1)
|
| 460 |
+
theta2 = np.arctan2(dx2, dy2)
|
| 461 |
+
dtheta = abs(theta1 - theta2)
|
| 462 |
+
if dtheta < tolerance:
|
| 463 |
+
return 1
|
| 464 |
+
elif abs(dtheta - np.pi) < tolerance:
|
| 465 |
+
return -1
|
| 466 |
+
else:
|
| 467 |
+
return False
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
def get_parallels(bezier2, width):
|
| 471 |
+
"""
|
| 472 |
+
Given the quadratic Bézier control points *bezier2*, returns
|
| 473 |
+
control points of quadratic Bézier lines roughly parallel to given
|
| 474 |
+
one separated by *width*.
|
| 475 |
+
"""
|
| 476 |
+
|
| 477 |
+
# The parallel Bezier lines are constructed by following ways.
|
| 478 |
+
# c1 and c2 are control points representing the start and end of the
|
| 479 |
+
# Bezier line.
|
| 480 |
+
# cm is the middle point
|
| 481 |
+
|
| 482 |
+
c1x, c1y = bezier2[0]
|
| 483 |
+
cmx, cmy = bezier2[1]
|
| 484 |
+
c2x, c2y = bezier2[2]
|
| 485 |
+
|
| 486 |
+
parallel_test = check_if_parallel(c1x - cmx, c1y - cmy,
|
| 487 |
+
cmx - c2x, cmy - c2y)
|
| 488 |
+
|
| 489 |
+
if parallel_test == -1:
|
| 490 |
+
_api.warn_external(
|
| 491 |
+
"Lines do not intersect. A straight line is used instead.")
|
| 492 |
+
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, c2x, c2y)
|
| 493 |
+
cos_t2, sin_t2 = cos_t1, sin_t1
|
| 494 |
+
else:
|
| 495 |
+
# t1 and t2 is the angle between c1 and cm, cm, c2. They are
|
| 496 |
+
# also an angle of the tangential line of the path at c1 and c2
|
| 497 |
+
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
|
| 498 |
+
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c2x, c2y)
|
| 499 |
+
|
| 500 |
+
# find c1_left, c1_right which are located along the lines
|
| 501 |
+
# through c1 and perpendicular to the tangential lines of the
|
| 502 |
+
# Bezier path at a distance of width. Same thing for c2_left and
|
| 503 |
+
# c2_right with respect to c2.
|
| 504 |
+
c1x_left, c1y_left, c1x_right, c1y_right = (
|
| 505 |
+
get_normal_points(c1x, c1y, cos_t1, sin_t1, width)
|
| 506 |
+
)
|
| 507 |
+
c2x_left, c2y_left, c2x_right, c2y_right = (
|
| 508 |
+
get_normal_points(c2x, c2y, cos_t2, sin_t2, width)
|
| 509 |
+
)
|
| 510 |
+
|
| 511 |
+
# find cm_left which is the intersecting point of a line through
|
| 512 |
+
# c1_left with angle t1 and a line through c2_left with angle
|
| 513 |
+
# t2. Same with cm_right.
|
| 514 |
+
try:
|
| 515 |
+
cmx_left, cmy_left = get_intersection(c1x_left, c1y_left, cos_t1,
|
| 516 |
+
sin_t1, c2x_left, c2y_left,
|
| 517 |
+
cos_t2, sin_t2)
|
| 518 |
+
cmx_right, cmy_right = get_intersection(c1x_right, c1y_right, cos_t1,
|
| 519 |
+
sin_t1, c2x_right, c2y_right,
|
| 520 |
+
cos_t2, sin_t2)
|
| 521 |
+
except ValueError:
|
| 522 |
+
# Special case straight lines, i.e., angle between two lines is
|
| 523 |
+
# less than the threshold used by get_intersection (we don't use
|
| 524 |
+
# check_if_parallel as the threshold is not the same).
|
| 525 |
+
cmx_left, cmy_left = (
|
| 526 |
+
0.5 * (c1x_left + c2x_left), 0.5 * (c1y_left + c2y_left)
|
| 527 |
+
)
|
| 528 |
+
cmx_right, cmy_right = (
|
| 529 |
+
0.5 * (c1x_right + c2x_right), 0.5 * (c1y_right + c2y_right)
|
| 530 |
+
)
|
| 531 |
+
|
| 532 |
+
# the parallel Bezier lines are created with control points of
|
| 533 |
+
# [c1_left, cm_left, c2_left] and [c1_right, cm_right, c2_right]
|
| 534 |
+
path_left = [(c1x_left, c1y_left),
|
| 535 |
+
(cmx_left, cmy_left),
|
| 536 |
+
(c2x_left, c2y_left)]
|
| 537 |
+
path_right = [(c1x_right, c1y_right),
|
| 538 |
+
(cmx_right, cmy_right),
|
| 539 |
+
(c2x_right, c2y_right)]
|
| 540 |
+
|
| 541 |
+
return path_left, path_right
|
| 542 |
+
|
| 543 |
+
|
| 544 |
+
def find_control_points(c1x, c1y, mmx, mmy, c2x, c2y):
|
| 545 |
+
"""
|
| 546 |
+
Find control points of the Bézier curve passing through (*c1x*, *c1y*),
|
| 547 |
+
(*mmx*, *mmy*), and (*c2x*, *c2y*), at parametric values 0, 0.5, and 1.
|
| 548 |
+
"""
|
| 549 |
+
cmx = .5 * (4 * mmx - (c1x + c2x))
|
| 550 |
+
cmy = .5 * (4 * mmy - (c1y + c2y))
|
| 551 |
+
return [(c1x, c1y), (cmx, cmy), (c2x, c2y)]
|
| 552 |
+
|
| 553 |
+
|
| 554 |
+
def make_wedged_bezier2(bezier2, width, w1=1., wm=0.5, w2=0.):
|
| 555 |
+
"""
|
| 556 |
+
Being similar to `get_parallels`, returns control points of two quadratic
|
| 557 |
+
Bézier lines having a width roughly parallel to given one separated by
|
| 558 |
+
*width*.
|
| 559 |
+
"""
|
| 560 |
+
|
| 561 |
+
# c1, cm, c2
|
| 562 |
+
c1x, c1y = bezier2[0]
|
| 563 |
+
cmx, cmy = bezier2[1]
|
| 564 |
+
c3x, c3y = bezier2[2]
|
| 565 |
+
|
| 566 |
+
# t1 and t2 is the angle between c1 and cm, cm, c3.
|
| 567 |
+
# They are also an angle of the tangential line of the path at c1 and c3
|
| 568 |
+
cos_t1, sin_t1 = get_cos_sin(c1x, c1y, cmx, cmy)
|
| 569 |
+
cos_t2, sin_t2 = get_cos_sin(cmx, cmy, c3x, c3y)
|
| 570 |
+
|
| 571 |
+
# find c1_left, c1_right which are located along the lines
|
| 572 |
+
# through c1 and perpendicular to the tangential lines of the
|
| 573 |
+
# Bezier path at a distance of width. Same thing for c3_left and
|
| 574 |
+
# c3_right with respect to c3.
|
| 575 |
+
c1x_left, c1y_left, c1x_right, c1y_right = (
|
| 576 |
+
get_normal_points(c1x, c1y, cos_t1, sin_t1, width * w1)
|
| 577 |
+
)
|
| 578 |
+
c3x_left, c3y_left, c3x_right, c3y_right = (
|
| 579 |
+
get_normal_points(c3x, c3y, cos_t2, sin_t2, width * w2)
|
| 580 |
+
)
|
| 581 |
+
|
| 582 |
+
# find c12, c23 and c123 which are middle points of c1-cm, cm-c3 and
|
| 583 |
+
# c12-c23
|
| 584 |
+
c12x, c12y = (c1x + cmx) * .5, (c1y + cmy) * .5
|
| 585 |
+
c23x, c23y = (cmx + c3x) * .5, (cmy + c3y) * .5
|
| 586 |
+
c123x, c123y = (c12x + c23x) * .5, (c12y + c23y) * .5
|
| 587 |
+
|
| 588 |
+
# tangential angle of c123 (angle between c12 and c23)
|
| 589 |
+
cos_t123, sin_t123 = get_cos_sin(c12x, c12y, c23x, c23y)
|
| 590 |
+
|
| 591 |
+
c123x_left, c123y_left, c123x_right, c123y_right = (
|
| 592 |
+
get_normal_points(c123x, c123y, cos_t123, sin_t123, width * wm)
|
| 593 |
+
)
|
| 594 |
+
|
| 595 |
+
path_left = find_control_points(c1x_left, c1y_left,
|
| 596 |
+
c123x_left, c123y_left,
|
| 597 |
+
c3x_left, c3y_left)
|
| 598 |
+
path_right = find_control_points(c1x_right, c1y_right,
|
| 599 |
+
c123x_right, c123y_right,
|
| 600 |
+
c3x_right, c3y_right)
|
| 601 |
+
|
| 602 |
+
return path_left, path_right
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/category.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Plotting of string "category" data: ``plot(['d', 'f', 'a'], [1, 2, 3])`` will
|
| 3 |
+
plot three points with x-axis values of 'd', 'f', 'a'.
|
| 4 |
+
|
| 5 |
+
See :doc:`/gallery/lines_bars_and_markers/categorical_variables` for an
|
| 6 |
+
example.
|
| 7 |
+
|
| 8 |
+
The module uses Matplotlib's `matplotlib.units` mechanism to convert from
|
| 9 |
+
strings to integers and provides a tick locator, a tick formatter, and the
|
| 10 |
+
`.UnitData` class that creates and stores the string-to-integer mapping.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
from collections import OrderedDict
|
| 14 |
+
import dateutil.parser
|
| 15 |
+
import itertools
|
| 16 |
+
import logging
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
|
| 20 |
+
from matplotlib import _api, cbook, ticker, units
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_log = logging.getLogger(__name__)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class StrCategoryConverter(units.ConversionInterface):
|
| 27 |
+
@staticmethod
|
| 28 |
+
def convert(value, unit, axis):
|
| 29 |
+
"""
|
| 30 |
+
Convert strings in *value* to floats using mapping information stored
|
| 31 |
+
in the *unit* object.
|
| 32 |
+
|
| 33 |
+
Parameters
|
| 34 |
+
----------
|
| 35 |
+
value : str or iterable
|
| 36 |
+
Value or list of values to be converted.
|
| 37 |
+
unit : `.UnitData`
|
| 38 |
+
An object mapping strings to integers.
|
| 39 |
+
axis : `~matplotlib.axis.Axis`
|
| 40 |
+
The axis on which the converted value is plotted.
|
| 41 |
+
|
| 42 |
+
.. note:: *axis* is unused.
|
| 43 |
+
|
| 44 |
+
Returns
|
| 45 |
+
-------
|
| 46 |
+
float or `~numpy.ndarray` of float
|
| 47 |
+
"""
|
| 48 |
+
if unit is None:
|
| 49 |
+
raise ValueError(
|
| 50 |
+
'Missing category information for StrCategoryConverter; '
|
| 51 |
+
'this might be caused by unintendedly mixing categorical and '
|
| 52 |
+
'numeric data')
|
| 53 |
+
StrCategoryConverter._validate_unit(unit)
|
| 54 |
+
# dtype = object preserves numerical pass throughs
|
| 55 |
+
values = np.atleast_1d(np.array(value, dtype=object))
|
| 56 |
+
# force an update so it also does type checking
|
| 57 |
+
unit.update(values)
|
| 58 |
+
s = np.vectorize(unit._mapping.__getitem__, otypes=[float])(values)
|
| 59 |
+
return s if not cbook.is_scalar_or_string(value) else s[0]
|
| 60 |
+
|
| 61 |
+
@staticmethod
|
| 62 |
+
def axisinfo(unit, axis):
|
| 63 |
+
"""
|
| 64 |
+
Set the default axis ticks and labels.
|
| 65 |
+
|
| 66 |
+
Parameters
|
| 67 |
+
----------
|
| 68 |
+
unit : `.UnitData`
|
| 69 |
+
object string unit information for value
|
| 70 |
+
axis : `~matplotlib.axis.Axis`
|
| 71 |
+
axis for which information is being set
|
| 72 |
+
|
| 73 |
+
.. note:: *axis* is not used
|
| 74 |
+
|
| 75 |
+
Returns
|
| 76 |
+
-------
|
| 77 |
+
`~matplotlib.units.AxisInfo`
|
| 78 |
+
Information to support default tick labeling
|
| 79 |
+
|
| 80 |
+
"""
|
| 81 |
+
StrCategoryConverter._validate_unit(unit)
|
| 82 |
+
# locator and formatter take mapping dict because
|
| 83 |
+
# args need to be pass by reference for updates
|
| 84 |
+
majloc = StrCategoryLocator(unit._mapping)
|
| 85 |
+
majfmt = StrCategoryFormatter(unit._mapping)
|
| 86 |
+
return units.AxisInfo(majloc=majloc, majfmt=majfmt)
|
| 87 |
+
|
| 88 |
+
@staticmethod
|
| 89 |
+
def default_units(data, axis):
|
| 90 |
+
"""
|
| 91 |
+
Set and update the `~matplotlib.axis.Axis` units.
|
| 92 |
+
|
| 93 |
+
Parameters
|
| 94 |
+
----------
|
| 95 |
+
data : str or iterable of str
|
| 96 |
+
axis : `~matplotlib.axis.Axis`
|
| 97 |
+
axis on which the data is plotted
|
| 98 |
+
|
| 99 |
+
Returns
|
| 100 |
+
-------
|
| 101 |
+
`.UnitData`
|
| 102 |
+
object storing string to integer mapping
|
| 103 |
+
"""
|
| 104 |
+
# the conversion call stack is default_units -> axis_info -> convert
|
| 105 |
+
if axis.units is None:
|
| 106 |
+
axis.set_units(UnitData(data))
|
| 107 |
+
else:
|
| 108 |
+
axis.units.update(data)
|
| 109 |
+
return axis.units
|
| 110 |
+
|
| 111 |
+
@staticmethod
|
| 112 |
+
def _validate_unit(unit):
|
| 113 |
+
if not hasattr(unit, '_mapping'):
|
| 114 |
+
raise ValueError(
|
| 115 |
+
f'Provided unit "{unit}" is not valid for a categorical '
|
| 116 |
+
'converter, as it does not have a _mapping attribute.')
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class StrCategoryLocator(ticker.Locator):
|
| 120 |
+
"""Tick at every integer mapping of the string data."""
|
| 121 |
+
def __init__(self, units_mapping):
|
| 122 |
+
"""
|
| 123 |
+
Parameters
|
| 124 |
+
----------
|
| 125 |
+
units_mapping : dict
|
| 126 |
+
Mapping of category names (str) to indices (int).
|
| 127 |
+
"""
|
| 128 |
+
self._units = units_mapping
|
| 129 |
+
|
| 130 |
+
def __call__(self):
|
| 131 |
+
# docstring inherited
|
| 132 |
+
return list(self._units.values())
|
| 133 |
+
|
| 134 |
+
def tick_values(self, vmin, vmax):
|
| 135 |
+
# docstring inherited
|
| 136 |
+
return self()
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class StrCategoryFormatter(ticker.Formatter):
|
| 140 |
+
"""String representation of the data at every tick."""
|
| 141 |
+
def __init__(self, units_mapping):
|
| 142 |
+
"""
|
| 143 |
+
Parameters
|
| 144 |
+
----------
|
| 145 |
+
units_mapping : dict
|
| 146 |
+
Mapping of category names (str) to indices (int).
|
| 147 |
+
"""
|
| 148 |
+
self._units = units_mapping
|
| 149 |
+
|
| 150 |
+
def __call__(self, x, pos=None):
|
| 151 |
+
# docstring inherited
|
| 152 |
+
return self.format_ticks([x])[0]
|
| 153 |
+
|
| 154 |
+
def format_ticks(self, values):
|
| 155 |
+
# docstring inherited
|
| 156 |
+
r_mapping = {v: self._text(k) for k, v in self._units.items()}
|
| 157 |
+
return [r_mapping.get(round(val), '') for val in values]
|
| 158 |
+
|
| 159 |
+
@staticmethod
|
| 160 |
+
def _text(value):
|
| 161 |
+
"""Convert text values into utf-8 or ascii strings."""
|
| 162 |
+
if isinstance(value, bytes):
|
| 163 |
+
value = value.decode(encoding='utf-8')
|
| 164 |
+
elif not isinstance(value, str):
|
| 165 |
+
value = str(value)
|
| 166 |
+
return value
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
class UnitData:
|
| 170 |
+
def __init__(self, data=None):
|
| 171 |
+
"""
|
| 172 |
+
Create mapping between unique categorical values and integer ids.
|
| 173 |
+
|
| 174 |
+
Parameters
|
| 175 |
+
----------
|
| 176 |
+
data : iterable
|
| 177 |
+
sequence of string values
|
| 178 |
+
"""
|
| 179 |
+
self._mapping = OrderedDict()
|
| 180 |
+
self._counter = itertools.count()
|
| 181 |
+
if data is not None:
|
| 182 |
+
self.update(data)
|
| 183 |
+
|
| 184 |
+
@staticmethod
|
| 185 |
+
def _str_is_convertible(val):
|
| 186 |
+
"""
|
| 187 |
+
Helper method to check whether a string can be parsed as float or date.
|
| 188 |
+
"""
|
| 189 |
+
try:
|
| 190 |
+
float(val)
|
| 191 |
+
except ValueError:
|
| 192 |
+
try:
|
| 193 |
+
dateutil.parser.parse(val)
|
| 194 |
+
except (ValueError, TypeError):
|
| 195 |
+
# TypeError if dateutil >= 2.8.1 else ValueError
|
| 196 |
+
return False
|
| 197 |
+
return True
|
| 198 |
+
|
| 199 |
+
def update(self, data):
|
| 200 |
+
"""
|
| 201 |
+
Map new values to integer identifiers.
|
| 202 |
+
|
| 203 |
+
Parameters
|
| 204 |
+
----------
|
| 205 |
+
data : iterable of str or bytes
|
| 206 |
+
|
| 207 |
+
Raises
|
| 208 |
+
------
|
| 209 |
+
TypeError
|
| 210 |
+
If elements in *data* are neither str nor bytes.
|
| 211 |
+
"""
|
| 212 |
+
data = np.atleast_1d(np.array(data, dtype=object))
|
| 213 |
+
# check if convertible to number:
|
| 214 |
+
convertible = True
|
| 215 |
+
for val in OrderedDict.fromkeys(data):
|
| 216 |
+
# OrderedDict just iterates over unique values in data.
|
| 217 |
+
_api.check_isinstance((str, bytes), value=val)
|
| 218 |
+
if convertible:
|
| 219 |
+
# this will only be called so long as convertible is True.
|
| 220 |
+
convertible = self._str_is_convertible(val)
|
| 221 |
+
if val not in self._mapping:
|
| 222 |
+
self._mapping[val] = next(self._counter)
|
| 223 |
+
if data.size and convertible:
|
| 224 |
+
_log.info('Using categorical units to plot a list of strings '
|
| 225 |
+
'that are all parsable as floats or dates. If these '
|
| 226 |
+
'strings should be plotted as numbers, cast to the '
|
| 227 |
+
'appropriate data type before plotting.')
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
# Register the converter with Matplotlib's unit framework
|
| 231 |
+
# Intentionally set to a single instance
|
| 232 |
+
units.registry[str] = \
|
| 233 |
+
units.registry[np.str_] = \
|
| 234 |
+
units.registry[bytes] = \
|
| 235 |
+
units.registry[np.bytes_] = StrCategoryConverter()
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/cbook.py
ADDED
|
@@ -0,0 +1,2405 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
A collection of utility functions and classes. Originally, many
|
| 3 |
+
(but not all) were from the Python Cookbook -- hence the name cbook.
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import collections
|
| 7 |
+
import collections.abc
|
| 8 |
+
import contextlib
|
| 9 |
+
import functools
|
| 10 |
+
import gzip
|
| 11 |
+
import itertools
|
| 12 |
+
import math
|
| 13 |
+
import operator
|
| 14 |
+
import os
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import shlex
|
| 17 |
+
import subprocess
|
| 18 |
+
import sys
|
| 19 |
+
import time
|
| 20 |
+
import traceback
|
| 21 |
+
import types
|
| 22 |
+
import weakref
|
| 23 |
+
|
| 24 |
+
import numpy as np
|
| 25 |
+
|
| 26 |
+
try:
|
| 27 |
+
from numpy.exceptions import VisibleDeprecationWarning # numpy >= 1.25
|
| 28 |
+
except ImportError:
|
| 29 |
+
from numpy import VisibleDeprecationWarning
|
| 30 |
+
|
| 31 |
+
import matplotlib
|
| 32 |
+
from matplotlib import _api, _c_internal_utils
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class _ExceptionInfo:
|
| 36 |
+
"""
|
| 37 |
+
A class to carry exception information around.
|
| 38 |
+
|
| 39 |
+
This is used to store and later raise exceptions. It's an alternative to
|
| 40 |
+
directly storing Exception instances that circumvents traceback-related
|
| 41 |
+
issues: caching tracebacks can keep user's objects in local namespaces
|
| 42 |
+
alive indefinitely, which can lead to very surprising memory issues for
|
| 43 |
+
users and result in incorrect tracebacks.
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
def __init__(self, cls, *args):
|
| 47 |
+
self._cls = cls
|
| 48 |
+
self._args = args
|
| 49 |
+
|
| 50 |
+
@classmethod
|
| 51 |
+
def from_exception(cls, exc):
|
| 52 |
+
return cls(type(exc), *exc.args)
|
| 53 |
+
|
| 54 |
+
def to_exception(self):
|
| 55 |
+
return self._cls(*self._args)
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _get_running_interactive_framework():
|
| 59 |
+
"""
|
| 60 |
+
Return the interactive framework whose event loop is currently running, if
|
| 61 |
+
any, or "headless" if no event loop can be started, or None.
|
| 62 |
+
|
| 63 |
+
Returns
|
| 64 |
+
-------
|
| 65 |
+
Optional[str]
|
| 66 |
+
One of the following values: "qt", "gtk3", "gtk4", "wx", "tk",
|
| 67 |
+
"macosx", "headless", ``None``.
|
| 68 |
+
"""
|
| 69 |
+
# Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
|
| 70 |
+
# entries can also have been explicitly set to None.
|
| 71 |
+
QtWidgets = (
|
| 72 |
+
sys.modules.get("PyQt6.QtWidgets")
|
| 73 |
+
or sys.modules.get("PySide6.QtWidgets")
|
| 74 |
+
or sys.modules.get("PyQt5.QtWidgets")
|
| 75 |
+
or sys.modules.get("PySide2.QtWidgets")
|
| 76 |
+
)
|
| 77 |
+
if QtWidgets and QtWidgets.QApplication.instance():
|
| 78 |
+
return "qt"
|
| 79 |
+
Gtk = sys.modules.get("gi.repository.Gtk")
|
| 80 |
+
if Gtk:
|
| 81 |
+
if Gtk.MAJOR_VERSION == 4:
|
| 82 |
+
from gi.repository import GLib
|
| 83 |
+
if GLib.main_depth():
|
| 84 |
+
return "gtk4"
|
| 85 |
+
if Gtk.MAJOR_VERSION == 3 and Gtk.main_level():
|
| 86 |
+
return "gtk3"
|
| 87 |
+
wx = sys.modules.get("wx")
|
| 88 |
+
if wx and wx.GetApp():
|
| 89 |
+
return "wx"
|
| 90 |
+
tkinter = sys.modules.get("tkinter")
|
| 91 |
+
if tkinter:
|
| 92 |
+
codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
|
| 93 |
+
for frame in sys._current_frames().values():
|
| 94 |
+
while frame:
|
| 95 |
+
if frame.f_code in codes:
|
| 96 |
+
return "tk"
|
| 97 |
+
frame = frame.f_back
|
| 98 |
+
# Preemptively break reference cycle between locals and the frame.
|
| 99 |
+
del frame
|
| 100 |
+
macosx = sys.modules.get("matplotlib.backends._macosx")
|
| 101 |
+
if macosx and macosx.event_loop_is_running():
|
| 102 |
+
return "macosx"
|
| 103 |
+
if not _c_internal_utils.display_is_valid():
|
| 104 |
+
return "headless"
|
| 105 |
+
return None
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _exception_printer(exc):
|
| 109 |
+
if _get_running_interactive_framework() in ["headless", None]:
|
| 110 |
+
raise exc
|
| 111 |
+
else:
|
| 112 |
+
traceback.print_exc()
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
class _StrongRef:
|
| 116 |
+
"""
|
| 117 |
+
Wrapper similar to a weakref, but keeping a strong reference to the object.
|
| 118 |
+
"""
|
| 119 |
+
|
| 120 |
+
def __init__(self, obj):
|
| 121 |
+
self._obj = obj
|
| 122 |
+
|
| 123 |
+
def __call__(self):
|
| 124 |
+
return self._obj
|
| 125 |
+
|
| 126 |
+
def __eq__(self, other):
|
| 127 |
+
return isinstance(other, _StrongRef) and self._obj == other._obj
|
| 128 |
+
|
| 129 |
+
def __hash__(self):
|
| 130 |
+
return hash(self._obj)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _weak_or_strong_ref(func, callback):
|
| 134 |
+
"""
|
| 135 |
+
Return a `WeakMethod` wrapping *func* if possible, else a `_StrongRef`.
|
| 136 |
+
"""
|
| 137 |
+
try:
|
| 138 |
+
return weakref.WeakMethod(func, callback)
|
| 139 |
+
except TypeError:
|
| 140 |
+
return _StrongRef(func)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
class _UnhashDict:
|
| 144 |
+
"""
|
| 145 |
+
A minimal dict-like class that also supports unhashable keys, storing them
|
| 146 |
+
in a list of key-value pairs.
|
| 147 |
+
|
| 148 |
+
This class only implements the interface needed for `CallbackRegistry`, and
|
| 149 |
+
tries to minimize the overhead for the hashable case.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
def __init__(self, pairs):
|
| 153 |
+
self._dict = {}
|
| 154 |
+
self._pairs = []
|
| 155 |
+
for k, v in pairs:
|
| 156 |
+
self[k] = v
|
| 157 |
+
|
| 158 |
+
def __setitem__(self, key, value):
|
| 159 |
+
try:
|
| 160 |
+
self._dict[key] = value
|
| 161 |
+
except TypeError:
|
| 162 |
+
for i, (k, v) in enumerate(self._pairs):
|
| 163 |
+
if k == key:
|
| 164 |
+
self._pairs[i] = (key, value)
|
| 165 |
+
break
|
| 166 |
+
else:
|
| 167 |
+
self._pairs.append((key, value))
|
| 168 |
+
|
| 169 |
+
def __getitem__(self, key):
|
| 170 |
+
try:
|
| 171 |
+
return self._dict[key]
|
| 172 |
+
except TypeError:
|
| 173 |
+
pass
|
| 174 |
+
for k, v in self._pairs:
|
| 175 |
+
if k == key:
|
| 176 |
+
return v
|
| 177 |
+
raise KeyError(key)
|
| 178 |
+
|
| 179 |
+
def pop(self, key, *args):
|
| 180 |
+
try:
|
| 181 |
+
if key in self._dict:
|
| 182 |
+
return self._dict.pop(key)
|
| 183 |
+
except TypeError:
|
| 184 |
+
for i, (k, v) in enumerate(self._pairs):
|
| 185 |
+
if k == key:
|
| 186 |
+
del self._pairs[i]
|
| 187 |
+
return v
|
| 188 |
+
if args:
|
| 189 |
+
return args[0]
|
| 190 |
+
raise KeyError(key)
|
| 191 |
+
|
| 192 |
+
def __iter__(self):
|
| 193 |
+
yield from self._dict
|
| 194 |
+
for k, v in self._pairs:
|
| 195 |
+
yield k
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
class CallbackRegistry:
|
| 199 |
+
"""
|
| 200 |
+
Handle registering, processing, blocking, and disconnecting
|
| 201 |
+
for a set of signals and callbacks:
|
| 202 |
+
|
| 203 |
+
>>> def oneat(x):
|
| 204 |
+
... print('eat', x)
|
| 205 |
+
>>> def ondrink(x):
|
| 206 |
+
... print('drink', x)
|
| 207 |
+
|
| 208 |
+
>>> from matplotlib.cbook import CallbackRegistry
|
| 209 |
+
>>> callbacks = CallbackRegistry()
|
| 210 |
+
|
| 211 |
+
>>> id_eat = callbacks.connect('eat', oneat)
|
| 212 |
+
>>> id_drink = callbacks.connect('drink', ondrink)
|
| 213 |
+
|
| 214 |
+
>>> callbacks.process('drink', 123)
|
| 215 |
+
drink 123
|
| 216 |
+
>>> callbacks.process('eat', 456)
|
| 217 |
+
eat 456
|
| 218 |
+
>>> callbacks.process('be merry', 456) # nothing will be called
|
| 219 |
+
|
| 220 |
+
>>> callbacks.disconnect(id_eat)
|
| 221 |
+
>>> callbacks.process('eat', 456) # nothing will be called
|
| 222 |
+
|
| 223 |
+
>>> with callbacks.blocked(signal='drink'):
|
| 224 |
+
... callbacks.process('drink', 123) # nothing will be called
|
| 225 |
+
>>> callbacks.process('drink', 123)
|
| 226 |
+
drink 123
|
| 227 |
+
|
| 228 |
+
In practice, one should always disconnect all callbacks when they are
|
| 229 |
+
no longer needed to avoid dangling references (and thus memory leaks).
|
| 230 |
+
However, real code in Matplotlib rarely does so, and due to its design,
|
| 231 |
+
it is rather difficult to place this kind of code. To get around this,
|
| 232 |
+
and prevent this class of memory leaks, we instead store weak references
|
| 233 |
+
to bound methods only, so when the destination object needs to die, the
|
| 234 |
+
CallbackRegistry won't keep it alive.
|
| 235 |
+
|
| 236 |
+
Parameters
|
| 237 |
+
----------
|
| 238 |
+
exception_handler : callable, optional
|
| 239 |
+
If not None, *exception_handler* must be a function that takes an
|
| 240 |
+
`Exception` as single parameter. It gets called with any `Exception`
|
| 241 |
+
raised by the callbacks during `CallbackRegistry.process`, and may
|
| 242 |
+
either re-raise the exception or handle it in another manner.
|
| 243 |
+
|
| 244 |
+
The default handler prints the exception (with `traceback.print_exc`) if
|
| 245 |
+
an interactive event loop is running; it re-raises the exception if no
|
| 246 |
+
interactive event loop is running.
|
| 247 |
+
|
| 248 |
+
signals : list, optional
|
| 249 |
+
If not None, *signals* is a list of signals that this registry handles:
|
| 250 |
+
attempting to `process` or to `connect` to a signal not in the list
|
| 251 |
+
throws a `ValueError`. The default, None, does not restrict the
|
| 252 |
+
handled signals.
|
| 253 |
+
"""
|
| 254 |
+
|
| 255 |
+
# We maintain two mappings:
|
| 256 |
+
# callbacks: signal -> {cid -> weakref-to-callback}
|
| 257 |
+
# _func_cid_map: {(signal, weakref-to-callback) -> cid}
|
| 258 |
+
|
| 259 |
+
def __init__(self, exception_handler=_exception_printer, *, signals=None):
|
| 260 |
+
self._signals = None if signals is None else list(signals) # Copy it.
|
| 261 |
+
self.exception_handler = exception_handler
|
| 262 |
+
self.callbacks = {}
|
| 263 |
+
self._cid_gen = itertools.count()
|
| 264 |
+
self._func_cid_map = _UnhashDict([])
|
| 265 |
+
# A hidden variable that marks cids that need to be pickled.
|
| 266 |
+
self._pickled_cids = set()
|
| 267 |
+
|
| 268 |
+
def __getstate__(self):
|
| 269 |
+
return {
|
| 270 |
+
**vars(self),
|
| 271 |
+
# In general, callbacks may not be pickled, so we just drop them,
|
| 272 |
+
# unless directed otherwise by self._pickled_cids.
|
| 273 |
+
"callbacks": {s: {cid: proxy() for cid, proxy in d.items()
|
| 274 |
+
if cid in self._pickled_cids}
|
| 275 |
+
for s, d in self.callbacks.items()},
|
| 276 |
+
# It is simpler to reconstruct this from callbacks in __setstate__.
|
| 277 |
+
"_func_cid_map": None,
|
| 278 |
+
"_cid_gen": next(self._cid_gen)
|
| 279 |
+
}
|
| 280 |
+
|
| 281 |
+
def __setstate__(self, state):
|
| 282 |
+
cid_count = state.pop('_cid_gen')
|
| 283 |
+
vars(self).update(state)
|
| 284 |
+
self.callbacks = {
|
| 285 |
+
s: {cid: _weak_or_strong_ref(func, functools.partial(self._remove_proxy, s))
|
| 286 |
+
for cid, func in d.items()}
|
| 287 |
+
for s, d in self.callbacks.items()}
|
| 288 |
+
self._func_cid_map = _UnhashDict(
|
| 289 |
+
((s, proxy), cid)
|
| 290 |
+
for s, d in self.callbacks.items() for cid, proxy in d.items())
|
| 291 |
+
self._cid_gen = itertools.count(cid_count)
|
| 292 |
+
|
| 293 |
+
def connect(self, signal, func):
|
| 294 |
+
"""Register *func* to be called when signal *signal* is generated."""
|
| 295 |
+
if self._signals is not None:
|
| 296 |
+
_api.check_in_list(self._signals, signal=signal)
|
| 297 |
+
proxy = _weak_or_strong_ref(func, functools.partial(self._remove_proxy, signal))
|
| 298 |
+
try:
|
| 299 |
+
return self._func_cid_map[signal, proxy]
|
| 300 |
+
except KeyError:
|
| 301 |
+
cid = self._func_cid_map[signal, proxy] = next(self._cid_gen)
|
| 302 |
+
self.callbacks.setdefault(signal, {})[cid] = proxy
|
| 303 |
+
return cid
|
| 304 |
+
|
| 305 |
+
def _connect_picklable(self, signal, func):
|
| 306 |
+
"""
|
| 307 |
+
Like `.connect`, but the callback is kept when pickling/unpickling.
|
| 308 |
+
|
| 309 |
+
Currently internal-use only.
|
| 310 |
+
"""
|
| 311 |
+
cid = self.connect(signal, func)
|
| 312 |
+
self._pickled_cids.add(cid)
|
| 313 |
+
return cid
|
| 314 |
+
|
| 315 |
+
# Keep a reference to sys.is_finalizing, as sys may have been cleared out
|
| 316 |
+
# at that point.
|
| 317 |
+
def _remove_proxy(self, signal, proxy, *, _is_finalizing=sys.is_finalizing):
|
| 318 |
+
if _is_finalizing():
|
| 319 |
+
# Weakrefs can't be properly torn down at that point anymore.
|
| 320 |
+
return
|
| 321 |
+
cid = self._func_cid_map.pop((signal, proxy), None)
|
| 322 |
+
if cid is not None:
|
| 323 |
+
del self.callbacks[signal][cid]
|
| 324 |
+
self._pickled_cids.discard(cid)
|
| 325 |
+
else: # Not found
|
| 326 |
+
return
|
| 327 |
+
if len(self.callbacks[signal]) == 0: # Clean up empty dicts
|
| 328 |
+
del self.callbacks[signal]
|
| 329 |
+
|
| 330 |
+
def disconnect(self, cid):
|
| 331 |
+
"""
|
| 332 |
+
Disconnect the callback registered with callback id *cid*.
|
| 333 |
+
|
| 334 |
+
No error is raised if such a callback does not exist.
|
| 335 |
+
"""
|
| 336 |
+
self._pickled_cids.discard(cid)
|
| 337 |
+
for signal, proxy in self._func_cid_map:
|
| 338 |
+
if self._func_cid_map[signal, proxy] == cid:
|
| 339 |
+
break
|
| 340 |
+
else: # Not found
|
| 341 |
+
return
|
| 342 |
+
assert self.callbacks[signal][cid] == proxy
|
| 343 |
+
del self.callbacks[signal][cid]
|
| 344 |
+
self._func_cid_map.pop((signal, proxy))
|
| 345 |
+
if len(self.callbacks[signal]) == 0: # Clean up empty dicts
|
| 346 |
+
del self.callbacks[signal]
|
| 347 |
+
|
| 348 |
+
def process(self, s, *args, **kwargs):
|
| 349 |
+
"""
|
| 350 |
+
Process signal *s*.
|
| 351 |
+
|
| 352 |
+
All of the functions registered to receive callbacks on *s* will be
|
| 353 |
+
called with ``*args`` and ``**kwargs``.
|
| 354 |
+
"""
|
| 355 |
+
if self._signals is not None:
|
| 356 |
+
_api.check_in_list(self._signals, signal=s)
|
| 357 |
+
for ref in list(self.callbacks.get(s, {}).values()):
|
| 358 |
+
func = ref()
|
| 359 |
+
if func is not None:
|
| 360 |
+
try:
|
| 361 |
+
func(*args, **kwargs)
|
| 362 |
+
# this does not capture KeyboardInterrupt, SystemExit,
|
| 363 |
+
# and GeneratorExit
|
| 364 |
+
except Exception as exc:
|
| 365 |
+
if self.exception_handler is not None:
|
| 366 |
+
self.exception_handler(exc)
|
| 367 |
+
else:
|
| 368 |
+
raise
|
| 369 |
+
|
| 370 |
+
@contextlib.contextmanager
|
| 371 |
+
def blocked(self, *, signal=None):
|
| 372 |
+
"""
|
| 373 |
+
Block callback signals from being processed.
|
| 374 |
+
|
| 375 |
+
A context manager to temporarily block/disable callback signals
|
| 376 |
+
from being processed by the registered listeners.
|
| 377 |
+
|
| 378 |
+
Parameters
|
| 379 |
+
----------
|
| 380 |
+
signal : str, optional
|
| 381 |
+
The callback signal to block. The default is to block all signals.
|
| 382 |
+
"""
|
| 383 |
+
orig = self.callbacks
|
| 384 |
+
try:
|
| 385 |
+
if signal is None:
|
| 386 |
+
# Empty out the callbacks
|
| 387 |
+
self.callbacks = {}
|
| 388 |
+
else:
|
| 389 |
+
# Only remove the specific signal
|
| 390 |
+
self.callbacks = {k: orig[k] for k in orig if k != signal}
|
| 391 |
+
yield
|
| 392 |
+
finally:
|
| 393 |
+
self.callbacks = orig
|
| 394 |
+
|
| 395 |
+
|
| 396 |
+
class silent_list(list):
|
| 397 |
+
"""
|
| 398 |
+
A list with a short ``repr()``.
|
| 399 |
+
|
| 400 |
+
This is meant to be used for a homogeneous list of artists, so that they
|
| 401 |
+
don't cause long, meaningless output.
|
| 402 |
+
|
| 403 |
+
Instead of ::
|
| 404 |
+
|
| 405 |
+
[<matplotlib.lines.Line2D object at 0x7f5749fed3c8>,
|
| 406 |
+
<matplotlib.lines.Line2D object at 0x7f5749fed4e0>,
|
| 407 |
+
<matplotlib.lines.Line2D object at 0x7f5758016550>]
|
| 408 |
+
|
| 409 |
+
one will get ::
|
| 410 |
+
|
| 411 |
+
<a list of 3 Line2D objects>
|
| 412 |
+
|
| 413 |
+
If ``self.type`` is None, the type name is obtained from the first item in
|
| 414 |
+
the list (if any).
|
| 415 |
+
"""
|
| 416 |
+
|
| 417 |
+
def __init__(self, type, seq=None):
|
| 418 |
+
self.type = type
|
| 419 |
+
if seq is not None:
|
| 420 |
+
self.extend(seq)
|
| 421 |
+
|
| 422 |
+
def __repr__(self):
|
| 423 |
+
if self.type is not None or len(self) != 0:
|
| 424 |
+
tp = self.type if self.type is not None else type(self[0]).__name__
|
| 425 |
+
return f"<a list of {len(self)} {tp} objects>"
|
| 426 |
+
else:
|
| 427 |
+
return "<an empty list>"
|
| 428 |
+
|
| 429 |
+
|
| 430 |
+
def _local_over_kwdict(
|
| 431 |
+
local_var, kwargs, *keys,
|
| 432 |
+
warning_cls=_api.MatplotlibDeprecationWarning):
|
| 433 |
+
out = local_var
|
| 434 |
+
for key in keys:
|
| 435 |
+
kwarg_val = kwargs.pop(key, None)
|
| 436 |
+
if kwarg_val is not None:
|
| 437 |
+
if out is None:
|
| 438 |
+
out = kwarg_val
|
| 439 |
+
else:
|
| 440 |
+
_api.warn_external(f'"{key}" keyword argument will be ignored',
|
| 441 |
+
warning_cls)
|
| 442 |
+
return out
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
def strip_math(s):
|
| 446 |
+
"""
|
| 447 |
+
Remove latex formatting from mathtext.
|
| 448 |
+
|
| 449 |
+
Only handles fully math and fully non-math strings.
|
| 450 |
+
"""
|
| 451 |
+
if len(s) >= 2 and s[0] == s[-1] == "$":
|
| 452 |
+
s = s[1:-1]
|
| 453 |
+
for tex, plain in [
|
| 454 |
+
(r"\times", "x"), # Specifically for Formatter support.
|
| 455 |
+
(r"\mathdefault", ""),
|
| 456 |
+
(r"\rm", ""),
|
| 457 |
+
(r"\cal", ""),
|
| 458 |
+
(r"\tt", ""),
|
| 459 |
+
(r"\it", ""),
|
| 460 |
+
("\\", ""),
|
| 461 |
+
("{", ""),
|
| 462 |
+
("}", ""),
|
| 463 |
+
]:
|
| 464 |
+
s = s.replace(tex, plain)
|
| 465 |
+
return s
|
| 466 |
+
|
| 467 |
+
|
| 468 |
+
def _strip_comment(s):
|
| 469 |
+
"""Strip everything from the first unquoted #."""
|
| 470 |
+
pos = 0
|
| 471 |
+
while True:
|
| 472 |
+
quote_pos = s.find('"', pos)
|
| 473 |
+
hash_pos = s.find('#', pos)
|
| 474 |
+
if quote_pos < 0:
|
| 475 |
+
without_comment = s if hash_pos < 0 else s[:hash_pos]
|
| 476 |
+
return without_comment.strip()
|
| 477 |
+
elif 0 <= hash_pos < quote_pos:
|
| 478 |
+
return s[:hash_pos].strip()
|
| 479 |
+
else:
|
| 480 |
+
closing_quote_pos = s.find('"', quote_pos + 1)
|
| 481 |
+
if closing_quote_pos < 0:
|
| 482 |
+
raise ValueError(
|
| 483 |
+
f"Missing closing quote in: {s!r}. If you need a double-"
|
| 484 |
+
'quote inside a string, use escaping: e.g. "the \" char"')
|
| 485 |
+
pos = closing_quote_pos + 1 # behind closing quote
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
def is_writable_file_like(obj):
|
| 489 |
+
"""Return whether *obj* looks like a file object with a *write* method."""
|
| 490 |
+
return callable(getattr(obj, 'write', None))
|
| 491 |
+
|
| 492 |
+
|
| 493 |
+
def file_requires_unicode(x):
|
| 494 |
+
"""
|
| 495 |
+
Return whether the given writable file-like object requires Unicode to be
|
| 496 |
+
written to it.
|
| 497 |
+
"""
|
| 498 |
+
try:
|
| 499 |
+
x.write(b'')
|
| 500 |
+
except TypeError:
|
| 501 |
+
return True
|
| 502 |
+
else:
|
| 503 |
+
return False
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
def to_filehandle(fname, flag='r', return_opened=False, encoding=None):
|
| 507 |
+
"""
|
| 508 |
+
Convert a path to an open file handle or pass-through a file-like object.
|
| 509 |
+
|
| 510 |
+
Consider using `open_file_cm` instead, as it allows one to properly close
|
| 511 |
+
newly created file objects more easily.
|
| 512 |
+
|
| 513 |
+
Parameters
|
| 514 |
+
----------
|
| 515 |
+
fname : str or path-like or file-like
|
| 516 |
+
If `str` or `os.PathLike`, the file is opened using the flags specified
|
| 517 |
+
by *flag* and *encoding*. If a file-like object, it is passed through.
|
| 518 |
+
flag : str, default: 'r'
|
| 519 |
+
Passed as the *mode* argument to `open` when *fname* is `str` or
|
| 520 |
+
`os.PathLike`; ignored if *fname* is file-like.
|
| 521 |
+
return_opened : bool, default: False
|
| 522 |
+
If True, return both the file object and a boolean indicating whether
|
| 523 |
+
this was a new file (that the caller needs to close). If False, return
|
| 524 |
+
only the new file.
|
| 525 |
+
encoding : str or None, default: None
|
| 526 |
+
Passed as the *mode* argument to `open` when *fname* is `str` or
|
| 527 |
+
`os.PathLike`; ignored if *fname* is file-like.
|
| 528 |
+
|
| 529 |
+
Returns
|
| 530 |
+
-------
|
| 531 |
+
fh : file-like
|
| 532 |
+
opened : bool
|
| 533 |
+
*opened* is only returned if *return_opened* is True.
|
| 534 |
+
"""
|
| 535 |
+
if isinstance(fname, os.PathLike):
|
| 536 |
+
fname = os.fspath(fname)
|
| 537 |
+
if isinstance(fname, str):
|
| 538 |
+
if fname.endswith('.gz'):
|
| 539 |
+
fh = gzip.open(fname, flag)
|
| 540 |
+
elif fname.endswith('.bz2'):
|
| 541 |
+
# python may not be compiled with bz2 support,
|
| 542 |
+
# bury import until we need it
|
| 543 |
+
import bz2
|
| 544 |
+
fh = bz2.BZ2File(fname, flag)
|
| 545 |
+
else:
|
| 546 |
+
fh = open(fname, flag, encoding=encoding)
|
| 547 |
+
opened = True
|
| 548 |
+
elif hasattr(fname, 'seek'):
|
| 549 |
+
fh = fname
|
| 550 |
+
opened = False
|
| 551 |
+
else:
|
| 552 |
+
raise ValueError('fname must be a PathLike or file handle')
|
| 553 |
+
if return_opened:
|
| 554 |
+
return fh, opened
|
| 555 |
+
return fh
|
| 556 |
+
|
| 557 |
+
|
| 558 |
+
def open_file_cm(path_or_file, mode="r", encoding=None):
|
| 559 |
+
r"""Pass through file objects and context-manage path-likes."""
|
| 560 |
+
fh, opened = to_filehandle(path_or_file, mode, True, encoding)
|
| 561 |
+
return fh if opened else contextlib.nullcontext(fh)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
def is_scalar_or_string(val):
|
| 565 |
+
"""Return whether the given object is a scalar or string like."""
|
| 566 |
+
return isinstance(val, str) or not np.iterable(val)
|
| 567 |
+
|
| 568 |
+
|
| 569 |
+
def get_sample_data(fname, asfileobj=True):
|
| 570 |
+
"""
|
| 571 |
+
Return a sample data file. *fname* is a path relative to the
|
| 572 |
+
:file:`mpl-data/sample_data` directory. If *asfileobj* is `True`
|
| 573 |
+
return a file object, otherwise just a file path.
|
| 574 |
+
|
| 575 |
+
Sample data files are stored in the 'mpl-data/sample_data' directory within
|
| 576 |
+
the Matplotlib package.
|
| 577 |
+
|
| 578 |
+
If the filename ends in .gz, the file is implicitly ungzipped. If the
|
| 579 |
+
filename ends with .npy or .npz, and *asfileobj* is `True`, the file is
|
| 580 |
+
loaded with `numpy.load`.
|
| 581 |
+
"""
|
| 582 |
+
path = _get_data_path('sample_data', fname)
|
| 583 |
+
if asfileobj:
|
| 584 |
+
suffix = path.suffix.lower()
|
| 585 |
+
if suffix == '.gz':
|
| 586 |
+
return gzip.open(path)
|
| 587 |
+
elif suffix in ['.npy', '.npz']:
|
| 588 |
+
return np.load(path)
|
| 589 |
+
elif suffix in ['.csv', '.xrc', '.txt']:
|
| 590 |
+
return path.open('r')
|
| 591 |
+
else:
|
| 592 |
+
return path.open('rb')
|
| 593 |
+
else:
|
| 594 |
+
return str(path)
|
| 595 |
+
|
| 596 |
+
|
| 597 |
+
def _get_data_path(*args):
|
| 598 |
+
"""
|
| 599 |
+
Return the `pathlib.Path` to a resource file provided by Matplotlib.
|
| 600 |
+
|
| 601 |
+
``*args`` specify a path relative to the base data path.
|
| 602 |
+
"""
|
| 603 |
+
return Path(matplotlib.get_data_path(), *args)
|
| 604 |
+
|
| 605 |
+
|
| 606 |
+
def flatten(seq, scalarp=is_scalar_or_string):
|
| 607 |
+
"""
|
| 608 |
+
Return a generator of flattened nested containers.
|
| 609 |
+
|
| 610 |
+
For example:
|
| 611 |
+
|
| 612 |
+
>>> from matplotlib.cbook import flatten
|
| 613 |
+
>>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
|
| 614 |
+
>>> print(list(flatten(l)))
|
| 615 |
+
['John', 'Hunter', 1, 23, 42, 5, 23]
|
| 616 |
+
|
| 617 |
+
By: Composite of Holger Krekel and Luther Blissett
|
| 618 |
+
From: https://code.activestate.com/recipes/121294-simple-generator-for-flattening-nested-containers/
|
| 619 |
+
and Recipe 1.12 in cookbook
|
| 620 |
+
""" # noqa: E501
|
| 621 |
+
for item in seq:
|
| 622 |
+
if scalarp(item) or item is None:
|
| 623 |
+
yield item
|
| 624 |
+
else:
|
| 625 |
+
yield from flatten(item, scalarp)
|
| 626 |
+
|
| 627 |
+
|
| 628 |
+
class _Stack:
|
| 629 |
+
"""
|
| 630 |
+
Stack of elements with a movable cursor.
|
| 631 |
+
|
| 632 |
+
Mimics home/back/forward in a web browser.
|
| 633 |
+
"""
|
| 634 |
+
|
| 635 |
+
def __init__(self):
|
| 636 |
+
self._pos = -1
|
| 637 |
+
self._elements = []
|
| 638 |
+
|
| 639 |
+
def clear(self):
|
| 640 |
+
"""Empty the stack."""
|
| 641 |
+
self._pos = -1
|
| 642 |
+
self._elements = []
|
| 643 |
+
|
| 644 |
+
def __call__(self):
|
| 645 |
+
"""Return the current element, or None."""
|
| 646 |
+
return self._elements[self._pos] if self._elements else None
|
| 647 |
+
|
| 648 |
+
def __len__(self):
|
| 649 |
+
return len(self._elements)
|
| 650 |
+
|
| 651 |
+
def __getitem__(self, ind):
|
| 652 |
+
return self._elements[ind]
|
| 653 |
+
|
| 654 |
+
def forward(self):
|
| 655 |
+
"""Move the position forward and return the current element."""
|
| 656 |
+
self._pos = min(self._pos + 1, len(self._elements) - 1)
|
| 657 |
+
return self()
|
| 658 |
+
|
| 659 |
+
def back(self):
|
| 660 |
+
"""Move the position back and return the current element."""
|
| 661 |
+
self._pos = max(self._pos - 1, 0)
|
| 662 |
+
return self()
|
| 663 |
+
|
| 664 |
+
def push(self, o):
|
| 665 |
+
"""
|
| 666 |
+
Push *o* to the stack after the current position, and return *o*.
|
| 667 |
+
|
| 668 |
+
Discard all later elements.
|
| 669 |
+
"""
|
| 670 |
+
self._elements[self._pos + 1:] = [o]
|
| 671 |
+
self._pos = len(self._elements) - 1
|
| 672 |
+
return o
|
| 673 |
+
|
| 674 |
+
def home(self):
|
| 675 |
+
"""
|
| 676 |
+
Push the first element onto the top of the stack.
|
| 677 |
+
|
| 678 |
+
The first element is returned.
|
| 679 |
+
"""
|
| 680 |
+
return self.push(self._elements[0]) if self._elements else None
|
| 681 |
+
|
| 682 |
+
|
| 683 |
+
def safe_masked_invalid(x, copy=False):
|
| 684 |
+
x = np.array(x, subok=True, copy=copy)
|
| 685 |
+
if not x.dtype.isnative:
|
| 686 |
+
# If we have already made a copy, do the byteswap in place, else make a
|
| 687 |
+
# copy with the byte order swapped.
|
| 688 |
+
# Swap to native order.
|
| 689 |
+
x = x.byteswap(inplace=copy).view(x.dtype.newbyteorder('N'))
|
| 690 |
+
try:
|
| 691 |
+
xm = np.ma.masked_where(~(np.isfinite(x)), x, copy=False)
|
| 692 |
+
except TypeError:
|
| 693 |
+
return x
|
| 694 |
+
return xm
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
def print_cycles(objects, outstream=sys.stdout, show_progress=False):
|
| 698 |
+
"""
|
| 699 |
+
Print loops of cyclic references in the given *objects*.
|
| 700 |
+
|
| 701 |
+
It is often useful to pass in ``gc.garbage`` to find the cycles that are
|
| 702 |
+
preventing some objects from being garbage collected.
|
| 703 |
+
|
| 704 |
+
Parameters
|
| 705 |
+
----------
|
| 706 |
+
objects
|
| 707 |
+
A list of objects to find cycles in.
|
| 708 |
+
outstream
|
| 709 |
+
The stream for output.
|
| 710 |
+
show_progress : bool
|
| 711 |
+
If True, print the number of objects reached as they are found.
|
| 712 |
+
"""
|
| 713 |
+
import gc
|
| 714 |
+
|
| 715 |
+
def print_path(path):
|
| 716 |
+
for i, step in enumerate(path):
|
| 717 |
+
# next "wraps around"
|
| 718 |
+
next = path[(i + 1) % len(path)]
|
| 719 |
+
|
| 720 |
+
outstream.write(" %s -- " % type(step))
|
| 721 |
+
if isinstance(step, dict):
|
| 722 |
+
for key, val in step.items():
|
| 723 |
+
if val is next:
|
| 724 |
+
outstream.write(f"[{key!r}]")
|
| 725 |
+
break
|
| 726 |
+
if key is next:
|
| 727 |
+
outstream.write(f"[key] = {val!r}")
|
| 728 |
+
break
|
| 729 |
+
elif isinstance(step, list):
|
| 730 |
+
outstream.write("[%d]" % step.index(next))
|
| 731 |
+
elif isinstance(step, tuple):
|
| 732 |
+
outstream.write("( tuple )")
|
| 733 |
+
else:
|
| 734 |
+
outstream.write(repr(step))
|
| 735 |
+
outstream.write(" ->\n")
|
| 736 |
+
outstream.write("\n")
|
| 737 |
+
|
| 738 |
+
def recurse(obj, start, all, current_path):
|
| 739 |
+
if show_progress:
|
| 740 |
+
outstream.write("%d\r" % len(all))
|
| 741 |
+
|
| 742 |
+
all[id(obj)] = None
|
| 743 |
+
|
| 744 |
+
referents = gc.get_referents(obj)
|
| 745 |
+
for referent in referents:
|
| 746 |
+
# If we've found our way back to the start, this is
|
| 747 |
+
# a cycle, so print it out
|
| 748 |
+
if referent is start:
|
| 749 |
+
print_path(current_path)
|
| 750 |
+
|
| 751 |
+
# Don't go back through the original list of objects, or
|
| 752 |
+
# through temporary references to the object, since those
|
| 753 |
+
# are just an artifact of the cycle detector itself.
|
| 754 |
+
elif referent is objects or isinstance(referent, types.FrameType):
|
| 755 |
+
continue
|
| 756 |
+
|
| 757 |
+
# We haven't seen this object before, so recurse
|
| 758 |
+
elif id(referent) not in all:
|
| 759 |
+
recurse(referent, start, all, current_path + [obj])
|
| 760 |
+
|
| 761 |
+
for obj in objects:
|
| 762 |
+
outstream.write(f"Examining: {obj!r}\n")
|
| 763 |
+
recurse(obj, obj, {}, [])
|
| 764 |
+
|
| 765 |
+
|
| 766 |
+
class Grouper:
|
| 767 |
+
"""
|
| 768 |
+
A disjoint-set data structure.
|
| 769 |
+
|
| 770 |
+
Objects can be joined using :meth:`join`, tested for connectedness
|
| 771 |
+
using :meth:`joined`, and all disjoint sets can be retrieved by
|
| 772 |
+
using the object as an iterator.
|
| 773 |
+
|
| 774 |
+
The objects being joined must be hashable and weak-referenceable.
|
| 775 |
+
|
| 776 |
+
Examples
|
| 777 |
+
--------
|
| 778 |
+
>>> from matplotlib.cbook import Grouper
|
| 779 |
+
>>> class Foo:
|
| 780 |
+
... def __init__(self, s):
|
| 781 |
+
... self.s = s
|
| 782 |
+
... def __repr__(self):
|
| 783 |
+
... return self.s
|
| 784 |
+
...
|
| 785 |
+
>>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
|
| 786 |
+
>>> grp = Grouper()
|
| 787 |
+
>>> grp.join(a, b)
|
| 788 |
+
>>> grp.join(b, c)
|
| 789 |
+
>>> grp.join(d, e)
|
| 790 |
+
>>> list(grp)
|
| 791 |
+
[[a, b, c], [d, e]]
|
| 792 |
+
>>> grp.joined(a, b)
|
| 793 |
+
True
|
| 794 |
+
>>> grp.joined(a, c)
|
| 795 |
+
True
|
| 796 |
+
>>> grp.joined(a, d)
|
| 797 |
+
False
|
| 798 |
+
"""
|
| 799 |
+
|
| 800 |
+
def __init__(self, init=()):
|
| 801 |
+
self._mapping = weakref.WeakKeyDictionary(
|
| 802 |
+
{x: weakref.WeakSet([x]) for x in init})
|
| 803 |
+
self._ordering = weakref.WeakKeyDictionary()
|
| 804 |
+
for x in init:
|
| 805 |
+
if x not in self._ordering:
|
| 806 |
+
self._ordering[x] = len(self._ordering)
|
| 807 |
+
self._next_order = len(self._ordering) # Plain int to simplify pickling.
|
| 808 |
+
|
| 809 |
+
def __getstate__(self):
|
| 810 |
+
return {
|
| 811 |
+
**vars(self),
|
| 812 |
+
# Convert weak refs to strong ones.
|
| 813 |
+
"_mapping": {k: set(v) for k, v in self._mapping.items()},
|
| 814 |
+
"_ordering": {**self._ordering},
|
| 815 |
+
}
|
| 816 |
+
|
| 817 |
+
def __setstate__(self, state):
|
| 818 |
+
vars(self).update(state)
|
| 819 |
+
# Convert strong refs to weak ones.
|
| 820 |
+
self._mapping = weakref.WeakKeyDictionary(
|
| 821 |
+
{k: weakref.WeakSet(v) for k, v in self._mapping.items()})
|
| 822 |
+
self._ordering = weakref.WeakKeyDictionary(self._ordering)
|
| 823 |
+
|
| 824 |
+
def __contains__(self, item):
|
| 825 |
+
return item in self._mapping
|
| 826 |
+
|
| 827 |
+
def join(self, a, *args):
|
| 828 |
+
"""
|
| 829 |
+
Join given arguments into the same set. Accepts one or more arguments.
|
| 830 |
+
"""
|
| 831 |
+
mapping = self._mapping
|
| 832 |
+
try:
|
| 833 |
+
set_a = mapping[a]
|
| 834 |
+
except KeyError:
|
| 835 |
+
set_a = mapping[a] = weakref.WeakSet([a])
|
| 836 |
+
self._ordering[a] = self._next_order
|
| 837 |
+
self._next_order += 1
|
| 838 |
+
for arg in args:
|
| 839 |
+
try:
|
| 840 |
+
set_b = mapping[arg]
|
| 841 |
+
except KeyError:
|
| 842 |
+
set_b = mapping[arg] = weakref.WeakSet([arg])
|
| 843 |
+
self._ordering[arg] = self._next_order
|
| 844 |
+
self._next_order += 1
|
| 845 |
+
if set_b is not set_a:
|
| 846 |
+
if len(set_b) > len(set_a):
|
| 847 |
+
set_a, set_b = set_b, set_a
|
| 848 |
+
set_a.update(set_b)
|
| 849 |
+
for elem in set_b:
|
| 850 |
+
mapping[elem] = set_a
|
| 851 |
+
|
| 852 |
+
def joined(self, a, b):
|
| 853 |
+
"""Return whether *a* and *b* are members of the same set."""
|
| 854 |
+
return (self._mapping.get(a, object()) is self._mapping.get(b))
|
| 855 |
+
|
| 856 |
+
def remove(self, a):
|
| 857 |
+
"""Remove *a* from the grouper, doing nothing if it is not there."""
|
| 858 |
+
self._mapping.pop(a, {a}).remove(a)
|
| 859 |
+
self._ordering.pop(a, None)
|
| 860 |
+
|
| 861 |
+
def __iter__(self):
|
| 862 |
+
"""
|
| 863 |
+
Iterate over each of the disjoint sets as a list.
|
| 864 |
+
|
| 865 |
+
The iterator is invalid if interleaved with calls to join().
|
| 866 |
+
"""
|
| 867 |
+
unique_groups = {id(group): group for group in self._mapping.values()}
|
| 868 |
+
for group in unique_groups.values():
|
| 869 |
+
yield sorted(group, key=self._ordering.__getitem__)
|
| 870 |
+
|
| 871 |
+
def get_siblings(self, a):
|
| 872 |
+
"""Return all of the items joined with *a*, including itself."""
|
| 873 |
+
siblings = self._mapping.get(a, [a])
|
| 874 |
+
return sorted(siblings, key=self._ordering.get)
|
| 875 |
+
|
| 876 |
+
|
| 877 |
+
class GrouperView:
|
| 878 |
+
"""Immutable view over a `.Grouper`."""
|
| 879 |
+
|
| 880 |
+
def __init__(self, grouper): self._grouper = grouper
|
| 881 |
+
def __contains__(self, item): return item in self._grouper
|
| 882 |
+
def __iter__(self): return iter(self._grouper)
|
| 883 |
+
def joined(self, a, b): return self._grouper.joined(a, b)
|
| 884 |
+
def get_siblings(self, a): return self._grouper.get_siblings(a)
|
| 885 |
+
|
| 886 |
+
|
| 887 |
+
def simple_linear_interpolation(a, steps):
|
| 888 |
+
"""
|
| 889 |
+
Resample an array with ``steps - 1`` points between original point pairs.
|
| 890 |
+
|
| 891 |
+
Along each column of *a*, ``(steps - 1)`` points are introduced between
|
| 892 |
+
each original values; the values are linearly interpolated.
|
| 893 |
+
|
| 894 |
+
Parameters
|
| 895 |
+
----------
|
| 896 |
+
a : array, shape (n, ...)
|
| 897 |
+
steps : int
|
| 898 |
+
|
| 899 |
+
Returns
|
| 900 |
+
-------
|
| 901 |
+
array
|
| 902 |
+
shape ``((n - 1) * steps + 1, ...)``
|
| 903 |
+
"""
|
| 904 |
+
fps = a.reshape((len(a), -1))
|
| 905 |
+
xp = np.arange(len(a)) * steps
|
| 906 |
+
x = np.arange((len(a) - 1) * steps + 1)
|
| 907 |
+
return (np.column_stack([np.interp(x, xp, fp) for fp in fps.T])
|
| 908 |
+
.reshape((len(x),) + a.shape[1:]))
|
| 909 |
+
|
| 910 |
+
|
| 911 |
+
def delete_masked_points(*args):
|
| 912 |
+
"""
|
| 913 |
+
Find all masked and/or non-finite points in a set of arguments,
|
| 914 |
+
and return the arguments with only the unmasked points remaining.
|
| 915 |
+
|
| 916 |
+
Arguments can be in any of 5 categories:
|
| 917 |
+
|
| 918 |
+
1) 1-D masked arrays
|
| 919 |
+
2) 1-D ndarrays
|
| 920 |
+
3) ndarrays with more than one dimension
|
| 921 |
+
4) other non-string iterables
|
| 922 |
+
5) anything else
|
| 923 |
+
|
| 924 |
+
The first argument must be in one of the first four categories;
|
| 925 |
+
any argument with a length differing from that of the first
|
| 926 |
+
argument (and hence anything in category 5) then will be
|
| 927 |
+
passed through unchanged.
|
| 928 |
+
|
| 929 |
+
Masks are obtained from all arguments of the correct length
|
| 930 |
+
in categories 1, 2, and 4; a point is bad if masked in a masked
|
| 931 |
+
array or if it is a nan or inf. No attempt is made to
|
| 932 |
+
extract a mask from categories 2, 3, and 4 if `numpy.isfinite`
|
| 933 |
+
does not yield a Boolean array.
|
| 934 |
+
|
| 935 |
+
All input arguments that are not passed unchanged are returned
|
| 936 |
+
as ndarrays after removing the points or rows corresponding to
|
| 937 |
+
masks in any of the arguments.
|
| 938 |
+
|
| 939 |
+
A vastly simpler version of this function was originally
|
| 940 |
+
written as a helper for Axes.scatter().
|
| 941 |
+
|
| 942 |
+
"""
|
| 943 |
+
if not len(args):
|
| 944 |
+
return ()
|
| 945 |
+
if is_scalar_or_string(args[0]):
|
| 946 |
+
raise ValueError("First argument must be a sequence")
|
| 947 |
+
nrecs = len(args[0])
|
| 948 |
+
margs = []
|
| 949 |
+
seqlist = [False] * len(args)
|
| 950 |
+
for i, x in enumerate(args):
|
| 951 |
+
if not isinstance(x, str) and np.iterable(x) and len(x) == nrecs:
|
| 952 |
+
seqlist[i] = True
|
| 953 |
+
if isinstance(x, np.ma.MaskedArray):
|
| 954 |
+
if x.ndim > 1:
|
| 955 |
+
raise ValueError("Masked arrays must be 1-D")
|
| 956 |
+
else:
|
| 957 |
+
x = np.asarray(x)
|
| 958 |
+
margs.append(x)
|
| 959 |
+
masks = [] # List of masks that are True where good.
|
| 960 |
+
for i, x in enumerate(margs):
|
| 961 |
+
if seqlist[i]:
|
| 962 |
+
if x.ndim > 1:
|
| 963 |
+
continue # Don't try to get nan locations unless 1-D.
|
| 964 |
+
if isinstance(x, np.ma.MaskedArray):
|
| 965 |
+
masks.append(~np.ma.getmaskarray(x)) # invert the mask
|
| 966 |
+
xd = x.data
|
| 967 |
+
else:
|
| 968 |
+
xd = x
|
| 969 |
+
try:
|
| 970 |
+
mask = np.isfinite(xd)
|
| 971 |
+
if isinstance(mask, np.ndarray):
|
| 972 |
+
masks.append(mask)
|
| 973 |
+
except Exception: # Fixme: put in tuple of possible exceptions?
|
| 974 |
+
pass
|
| 975 |
+
if len(masks):
|
| 976 |
+
mask = np.logical_and.reduce(masks)
|
| 977 |
+
igood = mask.nonzero()[0]
|
| 978 |
+
if len(igood) < nrecs:
|
| 979 |
+
for i, x in enumerate(margs):
|
| 980 |
+
if seqlist[i]:
|
| 981 |
+
margs[i] = x[igood]
|
| 982 |
+
for i, x in enumerate(margs):
|
| 983 |
+
if seqlist[i] and isinstance(x, np.ma.MaskedArray):
|
| 984 |
+
margs[i] = x.filled()
|
| 985 |
+
return margs
|
| 986 |
+
|
| 987 |
+
|
| 988 |
+
def _combine_masks(*args):
|
| 989 |
+
"""
|
| 990 |
+
Find all masked and/or non-finite points in a set of arguments,
|
| 991 |
+
and return the arguments as masked arrays with a common mask.
|
| 992 |
+
|
| 993 |
+
Arguments can be in any of 5 categories:
|
| 994 |
+
|
| 995 |
+
1) 1-D masked arrays
|
| 996 |
+
2) 1-D ndarrays
|
| 997 |
+
3) ndarrays with more than one dimension
|
| 998 |
+
4) other non-string iterables
|
| 999 |
+
5) anything else
|
| 1000 |
+
|
| 1001 |
+
The first argument must be in one of the first four categories;
|
| 1002 |
+
any argument with a length differing from that of the first
|
| 1003 |
+
argument (and hence anything in category 5) then will be
|
| 1004 |
+
passed through unchanged.
|
| 1005 |
+
|
| 1006 |
+
Masks are obtained from all arguments of the correct length
|
| 1007 |
+
in categories 1, 2, and 4; a point is bad if masked in a masked
|
| 1008 |
+
array or if it is a nan or inf. No attempt is made to
|
| 1009 |
+
extract a mask from categories 2 and 4 if `numpy.isfinite`
|
| 1010 |
+
does not yield a Boolean array. Category 3 is included to
|
| 1011 |
+
support RGB or RGBA ndarrays, which are assumed to have only
|
| 1012 |
+
valid values and which are passed through unchanged.
|
| 1013 |
+
|
| 1014 |
+
All input arguments that are not passed unchanged are returned
|
| 1015 |
+
as masked arrays if any masked points are found, otherwise as
|
| 1016 |
+
ndarrays.
|
| 1017 |
+
|
| 1018 |
+
"""
|
| 1019 |
+
if not len(args):
|
| 1020 |
+
return ()
|
| 1021 |
+
if is_scalar_or_string(args[0]):
|
| 1022 |
+
raise ValueError("First argument must be a sequence")
|
| 1023 |
+
nrecs = len(args[0])
|
| 1024 |
+
margs = [] # Output args; some may be modified.
|
| 1025 |
+
seqlist = [False] * len(args) # Flags: True if output will be masked.
|
| 1026 |
+
masks = [] # List of masks.
|
| 1027 |
+
for i, x in enumerate(args):
|
| 1028 |
+
if is_scalar_or_string(x) or len(x) != nrecs:
|
| 1029 |
+
margs.append(x) # Leave it unmodified.
|
| 1030 |
+
else:
|
| 1031 |
+
if isinstance(x, np.ma.MaskedArray) and x.ndim > 1:
|
| 1032 |
+
raise ValueError("Masked arrays must be 1-D")
|
| 1033 |
+
try:
|
| 1034 |
+
x = np.asanyarray(x)
|
| 1035 |
+
except (VisibleDeprecationWarning, ValueError):
|
| 1036 |
+
# NumPy 1.19 raises a warning about ragged arrays, but we want
|
| 1037 |
+
# to accept basically anything here.
|
| 1038 |
+
x = np.asanyarray(x, dtype=object)
|
| 1039 |
+
if x.ndim == 1:
|
| 1040 |
+
x = safe_masked_invalid(x)
|
| 1041 |
+
seqlist[i] = True
|
| 1042 |
+
if np.ma.is_masked(x):
|
| 1043 |
+
masks.append(np.ma.getmaskarray(x))
|
| 1044 |
+
margs.append(x) # Possibly modified.
|
| 1045 |
+
if len(masks):
|
| 1046 |
+
mask = np.logical_or.reduce(masks)
|
| 1047 |
+
for i, x in enumerate(margs):
|
| 1048 |
+
if seqlist[i]:
|
| 1049 |
+
margs[i] = np.ma.array(x, mask=mask)
|
| 1050 |
+
return margs
|
| 1051 |
+
|
| 1052 |
+
|
| 1053 |
+
def _broadcast_with_masks(*args, compress=False):
|
| 1054 |
+
"""
|
| 1055 |
+
Broadcast inputs, combining all masked arrays.
|
| 1056 |
+
|
| 1057 |
+
Parameters
|
| 1058 |
+
----------
|
| 1059 |
+
*args : array-like
|
| 1060 |
+
The inputs to broadcast.
|
| 1061 |
+
compress : bool, default: False
|
| 1062 |
+
Whether to compress the masked arrays. If False, the masked values
|
| 1063 |
+
are replaced by NaNs.
|
| 1064 |
+
|
| 1065 |
+
Returns
|
| 1066 |
+
-------
|
| 1067 |
+
list of array-like
|
| 1068 |
+
The broadcasted and masked inputs.
|
| 1069 |
+
"""
|
| 1070 |
+
# extract the masks, if any
|
| 1071 |
+
masks = [k.mask for k in args if isinstance(k, np.ma.MaskedArray)]
|
| 1072 |
+
# broadcast to match the shape
|
| 1073 |
+
bcast = np.broadcast_arrays(*args, *masks)
|
| 1074 |
+
inputs = bcast[:len(args)]
|
| 1075 |
+
masks = bcast[len(args):]
|
| 1076 |
+
if masks:
|
| 1077 |
+
# combine the masks into one
|
| 1078 |
+
mask = np.logical_or.reduce(masks)
|
| 1079 |
+
# put mask on and compress
|
| 1080 |
+
if compress:
|
| 1081 |
+
inputs = [np.ma.array(k, mask=mask).compressed()
|
| 1082 |
+
for k in inputs]
|
| 1083 |
+
else:
|
| 1084 |
+
inputs = [np.ma.array(k, mask=mask, dtype=float).filled(np.nan).ravel()
|
| 1085 |
+
for k in inputs]
|
| 1086 |
+
else:
|
| 1087 |
+
inputs = [np.ravel(k) for k in inputs]
|
| 1088 |
+
return inputs
|
| 1089 |
+
|
| 1090 |
+
|
| 1091 |
+
def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False):
|
| 1092 |
+
r"""
|
| 1093 |
+
Return a list of dictionaries of statistics used to draw a series of box
|
| 1094 |
+
and whisker plots using `~.Axes.bxp`.
|
| 1095 |
+
|
| 1096 |
+
Parameters
|
| 1097 |
+
----------
|
| 1098 |
+
X : array-like
|
| 1099 |
+
Data that will be represented in the boxplots. Should have 2 or
|
| 1100 |
+
fewer dimensions.
|
| 1101 |
+
|
| 1102 |
+
whis : float or (float, float), default: 1.5
|
| 1103 |
+
The position of the whiskers.
|
| 1104 |
+
|
| 1105 |
+
If a float, the lower whisker is at the lowest datum above
|
| 1106 |
+
``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum below
|
| 1107 |
+
``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and third
|
| 1108 |
+
quartiles. The default value of ``whis = 1.5`` corresponds to Tukey's
|
| 1109 |
+
original definition of boxplots.
|
| 1110 |
+
|
| 1111 |
+
If a pair of floats, they indicate the percentiles at which to draw the
|
| 1112 |
+
whiskers (e.g., (5, 95)). In particular, setting this to (0, 100)
|
| 1113 |
+
results in whiskers covering the whole range of the data.
|
| 1114 |
+
|
| 1115 |
+
In the edge case where ``Q1 == Q3``, *whis* is automatically set to
|
| 1116 |
+
(0, 100) (cover the whole range of the data) if *autorange* is True.
|
| 1117 |
+
|
| 1118 |
+
Beyond the whiskers, data are considered outliers and are plotted as
|
| 1119 |
+
individual points.
|
| 1120 |
+
|
| 1121 |
+
bootstrap : int, optional
|
| 1122 |
+
Number of times the confidence intervals around the median
|
| 1123 |
+
should be bootstrapped (percentile method).
|
| 1124 |
+
|
| 1125 |
+
labels : list of str, optional
|
| 1126 |
+
Labels for each dataset. Length must be compatible with
|
| 1127 |
+
dimensions of *X*.
|
| 1128 |
+
|
| 1129 |
+
autorange : bool, optional (False)
|
| 1130 |
+
When `True` and the data are distributed such that the 25th and 75th
|
| 1131 |
+
percentiles are equal, ``whis`` is set to (0, 100) such that the
|
| 1132 |
+
whisker ends are at the minimum and maximum of the data.
|
| 1133 |
+
|
| 1134 |
+
Returns
|
| 1135 |
+
-------
|
| 1136 |
+
list of dict
|
| 1137 |
+
A list of dictionaries containing the results for each column
|
| 1138 |
+
of data. Keys of each dictionary are the following:
|
| 1139 |
+
|
| 1140 |
+
======== ===================================
|
| 1141 |
+
Key Value Description
|
| 1142 |
+
======== ===================================
|
| 1143 |
+
label tick label for the boxplot
|
| 1144 |
+
mean arithmetic mean value
|
| 1145 |
+
med 50th percentile
|
| 1146 |
+
q1 first quartile (25th percentile)
|
| 1147 |
+
q3 third quartile (75th percentile)
|
| 1148 |
+
iqr interquartile range
|
| 1149 |
+
cilo lower notch around the median
|
| 1150 |
+
cihi upper notch around the median
|
| 1151 |
+
whislo end of the lower whisker
|
| 1152 |
+
whishi end of the upper whisker
|
| 1153 |
+
fliers outliers
|
| 1154 |
+
======== ===================================
|
| 1155 |
+
|
| 1156 |
+
Notes
|
| 1157 |
+
-----
|
| 1158 |
+
Non-bootstrapping approach to confidence interval uses Gaussian-based
|
| 1159 |
+
asymptotic approximation:
|
| 1160 |
+
|
| 1161 |
+
.. math::
|
| 1162 |
+
|
| 1163 |
+
\mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}}
|
| 1164 |
+
|
| 1165 |
+
General approach from:
|
| 1166 |
+
McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
|
| 1167 |
+
Boxplots", The American Statistician, 32:12-16.
|
| 1168 |
+
"""
|
| 1169 |
+
|
| 1170 |
+
def _bootstrap_median(data, N=5000):
|
| 1171 |
+
# determine 95% confidence intervals of the median
|
| 1172 |
+
M = len(data)
|
| 1173 |
+
percentiles = [2.5, 97.5]
|
| 1174 |
+
|
| 1175 |
+
bs_index = np.random.randint(M, size=(N, M))
|
| 1176 |
+
bsData = data[bs_index]
|
| 1177 |
+
estimate = np.median(bsData, axis=1, overwrite_input=True)
|
| 1178 |
+
|
| 1179 |
+
CI = np.percentile(estimate, percentiles)
|
| 1180 |
+
return CI
|
| 1181 |
+
|
| 1182 |
+
def _compute_conf_interval(data, med, iqr, bootstrap):
|
| 1183 |
+
if bootstrap is not None:
|
| 1184 |
+
# Do a bootstrap estimate of notch locations.
|
| 1185 |
+
# get conf. intervals around median
|
| 1186 |
+
CI = _bootstrap_median(data, N=bootstrap)
|
| 1187 |
+
notch_min = CI[0]
|
| 1188 |
+
notch_max = CI[1]
|
| 1189 |
+
else:
|
| 1190 |
+
|
| 1191 |
+
N = len(data)
|
| 1192 |
+
notch_min = med - 1.57 * iqr / np.sqrt(N)
|
| 1193 |
+
notch_max = med + 1.57 * iqr / np.sqrt(N)
|
| 1194 |
+
|
| 1195 |
+
return notch_min, notch_max
|
| 1196 |
+
|
| 1197 |
+
# output is a list of dicts
|
| 1198 |
+
bxpstats = []
|
| 1199 |
+
|
| 1200 |
+
# convert X to a list of lists
|
| 1201 |
+
X = _reshape_2D(X, "X")
|
| 1202 |
+
|
| 1203 |
+
ncols = len(X)
|
| 1204 |
+
if labels is None:
|
| 1205 |
+
labels = itertools.repeat(None)
|
| 1206 |
+
elif len(labels) != ncols:
|
| 1207 |
+
raise ValueError("Dimensions of labels and X must be compatible")
|
| 1208 |
+
|
| 1209 |
+
input_whis = whis
|
| 1210 |
+
for ii, (x, label) in enumerate(zip(X, labels)):
|
| 1211 |
+
|
| 1212 |
+
# empty dict
|
| 1213 |
+
stats = {}
|
| 1214 |
+
if label is not None:
|
| 1215 |
+
stats['label'] = label
|
| 1216 |
+
|
| 1217 |
+
# restore whis to the input values in case it got changed in the loop
|
| 1218 |
+
whis = input_whis
|
| 1219 |
+
|
| 1220 |
+
# note tricksiness, append up here and then mutate below
|
| 1221 |
+
bxpstats.append(stats)
|
| 1222 |
+
|
| 1223 |
+
# if empty, bail
|
| 1224 |
+
if len(x) == 0:
|
| 1225 |
+
stats['fliers'] = np.array([])
|
| 1226 |
+
stats['mean'] = np.nan
|
| 1227 |
+
stats['med'] = np.nan
|
| 1228 |
+
stats['q1'] = np.nan
|
| 1229 |
+
stats['q3'] = np.nan
|
| 1230 |
+
stats['iqr'] = np.nan
|
| 1231 |
+
stats['cilo'] = np.nan
|
| 1232 |
+
stats['cihi'] = np.nan
|
| 1233 |
+
stats['whislo'] = np.nan
|
| 1234 |
+
stats['whishi'] = np.nan
|
| 1235 |
+
continue
|
| 1236 |
+
|
| 1237 |
+
# up-convert to an array, just to be safe
|
| 1238 |
+
x = np.ma.asarray(x)
|
| 1239 |
+
x = x.data[~x.mask].ravel()
|
| 1240 |
+
|
| 1241 |
+
# arithmetic mean
|
| 1242 |
+
stats['mean'] = np.mean(x)
|
| 1243 |
+
|
| 1244 |
+
# medians and quartiles
|
| 1245 |
+
q1, med, q3 = np.percentile(x, [25, 50, 75])
|
| 1246 |
+
|
| 1247 |
+
# interquartile range
|
| 1248 |
+
stats['iqr'] = q3 - q1
|
| 1249 |
+
if stats['iqr'] == 0 and autorange:
|
| 1250 |
+
whis = (0, 100)
|
| 1251 |
+
|
| 1252 |
+
# conf. interval around median
|
| 1253 |
+
stats['cilo'], stats['cihi'] = _compute_conf_interval(
|
| 1254 |
+
x, med, stats['iqr'], bootstrap
|
| 1255 |
+
)
|
| 1256 |
+
|
| 1257 |
+
# lowest/highest non-outliers
|
| 1258 |
+
if np.iterable(whis) and not isinstance(whis, str):
|
| 1259 |
+
loval, hival = np.percentile(x, whis)
|
| 1260 |
+
elif np.isreal(whis):
|
| 1261 |
+
loval = q1 - whis * stats['iqr']
|
| 1262 |
+
hival = q3 + whis * stats['iqr']
|
| 1263 |
+
else:
|
| 1264 |
+
raise ValueError('whis must be a float or list of percentiles')
|
| 1265 |
+
|
| 1266 |
+
# get high extreme
|
| 1267 |
+
wiskhi = x[x <= hival]
|
| 1268 |
+
if len(wiskhi) == 0 or np.max(wiskhi) < q3:
|
| 1269 |
+
stats['whishi'] = q3
|
| 1270 |
+
else:
|
| 1271 |
+
stats['whishi'] = np.max(wiskhi)
|
| 1272 |
+
|
| 1273 |
+
# get low extreme
|
| 1274 |
+
wisklo = x[x >= loval]
|
| 1275 |
+
if len(wisklo) == 0 or np.min(wisklo) > q1:
|
| 1276 |
+
stats['whislo'] = q1
|
| 1277 |
+
else:
|
| 1278 |
+
stats['whislo'] = np.min(wisklo)
|
| 1279 |
+
|
| 1280 |
+
# compute a single array of outliers
|
| 1281 |
+
stats['fliers'] = np.concatenate([
|
| 1282 |
+
x[x < stats['whislo']],
|
| 1283 |
+
x[x > stats['whishi']],
|
| 1284 |
+
])
|
| 1285 |
+
|
| 1286 |
+
# add in the remaining stats
|
| 1287 |
+
stats['q1'], stats['med'], stats['q3'] = q1, med, q3
|
| 1288 |
+
|
| 1289 |
+
return bxpstats
|
| 1290 |
+
|
| 1291 |
+
|
| 1292 |
+
#: Maps short codes for line style to their full name used by backends.
|
| 1293 |
+
ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
|
| 1294 |
+
#: Maps full names for line styles used by backends to their short codes.
|
| 1295 |
+
ls_mapper_r = {v: k for k, v in ls_mapper.items()}
|
| 1296 |
+
|
| 1297 |
+
|
| 1298 |
+
def contiguous_regions(mask):
|
| 1299 |
+
"""
|
| 1300 |
+
Return a list of (ind0, ind1) such that ``mask[ind0:ind1].all()`` is
|
| 1301 |
+
True and we cover all such regions.
|
| 1302 |
+
"""
|
| 1303 |
+
mask = np.asarray(mask, dtype=bool)
|
| 1304 |
+
|
| 1305 |
+
if not mask.size:
|
| 1306 |
+
return []
|
| 1307 |
+
|
| 1308 |
+
# Find the indices of region changes, and correct offset
|
| 1309 |
+
idx, = np.nonzero(mask[:-1] != mask[1:])
|
| 1310 |
+
idx += 1
|
| 1311 |
+
|
| 1312 |
+
# List operations are faster for moderately sized arrays
|
| 1313 |
+
idx = idx.tolist()
|
| 1314 |
+
|
| 1315 |
+
# Add first and/or last index if needed
|
| 1316 |
+
if mask[0]:
|
| 1317 |
+
idx = [0] + idx
|
| 1318 |
+
if mask[-1]:
|
| 1319 |
+
idx.append(len(mask))
|
| 1320 |
+
|
| 1321 |
+
return list(zip(idx[::2], idx[1::2]))
|
| 1322 |
+
|
| 1323 |
+
|
| 1324 |
+
def is_math_text(s):
|
| 1325 |
+
"""
|
| 1326 |
+
Return whether the string *s* contains math expressions.
|
| 1327 |
+
|
| 1328 |
+
This is done by checking whether *s* contains an even number of
|
| 1329 |
+
non-escaped dollar signs.
|
| 1330 |
+
"""
|
| 1331 |
+
s = str(s)
|
| 1332 |
+
dollar_count = s.count(r'$') - s.count(r'\$')
|
| 1333 |
+
even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
|
| 1334 |
+
return even_dollars
|
| 1335 |
+
|
| 1336 |
+
|
| 1337 |
+
def _to_unmasked_float_array(x):
|
| 1338 |
+
"""
|
| 1339 |
+
Convert a sequence to a float array; if input was a masked array, masked
|
| 1340 |
+
values are converted to nans.
|
| 1341 |
+
"""
|
| 1342 |
+
if hasattr(x, 'mask'):
|
| 1343 |
+
return np.ma.asarray(x, float).filled(np.nan)
|
| 1344 |
+
else:
|
| 1345 |
+
return np.asarray(x, float)
|
| 1346 |
+
|
| 1347 |
+
|
| 1348 |
+
def _check_1d(x):
|
| 1349 |
+
"""Convert scalars to 1D arrays; pass-through arrays as is."""
|
| 1350 |
+
# Unpack in case of e.g. Pandas or xarray object
|
| 1351 |
+
x = _unpack_to_numpy(x)
|
| 1352 |
+
# plot requires `shape` and `ndim`. If passed an
|
| 1353 |
+
# object that doesn't provide them, then force to numpy array.
|
| 1354 |
+
# Note this will strip unit information.
|
| 1355 |
+
if (not hasattr(x, 'shape') or
|
| 1356 |
+
not hasattr(x, 'ndim') or
|
| 1357 |
+
len(x.shape) < 1):
|
| 1358 |
+
return np.atleast_1d(x)
|
| 1359 |
+
else:
|
| 1360 |
+
return x
|
| 1361 |
+
|
| 1362 |
+
|
| 1363 |
+
def _reshape_2D(X, name):
|
| 1364 |
+
"""
|
| 1365 |
+
Use Fortran ordering to convert ndarrays and lists of iterables to lists of
|
| 1366 |
+
1D arrays.
|
| 1367 |
+
|
| 1368 |
+
Lists of iterables are converted by applying `numpy.asanyarray` to each of
|
| 1369 |
+
their elements. 1D ndarrays are returned in a singleton list containing
|
| 1370 |
+
them. 2D ndarrays are converted to the list of their *columns*.
|
| 1371 |
+
|
| 1372 |
+
*name* is used to generate the error message for invalid inputs.
|
| 1373 |
+
"""
|
| 1374 |
+
|
| 1375 |
+
# Unpack in case of e.g. Pandas or xarray object
|
| 1376 |
+
X = _unpack_to_numpy(X)
|
| 1377 |
+
|
| 1378 |
+
# Iterate over columns for ndarrays.
|
| 1379 |
+
if isinstance(X, np.ndarray):
|
| 1380 |
+
X = X.T
|
| 1381 |
+
|
| 1382 |
+
if len(X) == 0:
|
| 1383 |
+
return [[]]
|
| 1384 |
+
elif X.ndim == 1 and np.ndim(X[0]) == 0:
|
| 1385 |
+
# 1D array of scalars: directly return it.
|
| 1386 |
+
return [X]
|
| 1387 |
+
elif X.ndim in [1, 2]:
|
| 1388 |
+
# 2D array, or 1D array of iterables: flatten them first.
|
| 1389 |
+
return [np.reshape(x, -1) for x in X]
|
| 1390 |
+
else:
|
| 1391 |
+
raise ValueError(f'{name} must have 2 or fewer dimensions')
|
| 1392 |
+
|
| 1393 |
+
# Iterate over list of iterables.
|
| 1394 |
+
if len(X) == 0:
|
| 1395 |
+
return [[]]
|
| 1396 |
+
|
| 1397 |
+
result = []
|
| 1398 |
+
is_1d = True
|
| 1399 |
+
for xi in X:
|
| 1400 |
+
# check if this is iterable, except for strings which we
|
| 1401 |
+
# treat as singletons.
|
| 1402 |
+
if not isinstance(xi, str):
|
| 1403 |
+
try:
|
| 1404 |
+
iter(xi)
|
| 1405 |
+
except TypeError:
|
| 1406 |
+
pass
|
| 1407 |
+
else:
|
| 1408 |
+
is_1d = False
|
| 1409 |
+
xi = np.asanyarray(xi)
|
| 1410 |
+
nd = np.ndim(xi)
|
| 1411 |
+
if nd > 1:
|
| 1412 |
+
raise ValueError(f'{name} must have 2 or fewer dimensions')
|
| 1413 |
+
result.append(xi.reshape(-1))
|
| 1414 |
+
|
| 1415 |
+
if is_1d:
|
| 1416 |
+
# 1D array of scalars: directly return it.
|
| 1417 |
+
return [np.reshape(result, -1)]
|
| 1418 |
+
else:
|
| 1419 |
+
# 2D array, or 1D array of iterables: use flattened version.
|
| 1420 |
+
return result
|
| 1421 |
+
|
| 1422 |
+
|
| 1423 |
+
def violin_stats(X, method, points=100, quantiles=None):
|
| 1424 |
+
"""
|
| 1425 |
+
Return a list of dictionaries of data which can be used to draw a series
|
| 1426 |
+
of violin plots.
|
| 1427 |
+
|
| 1428 |
+
See the ``Returns`` section below to view the required keys of the
|
| 1429 |
+
dictionary.
|
| 1430 |
+
|
| 1431 |
+
Users can skip this function and pass a user-defined set of dictionaries
|
| 1432 |
+
with the same keys to `~.axes.Axes.violinplot` instead of using Matplotlib
|
| 1433 |
+
to do the calculations. See the *Returns* section below for the keys
|
| 1434 |
+
that must be present in the dictionaries.
|
| 1435 |
+
|
| 1436 |
+
Parameters
|
| 1437 |
+
----------
|
| 1438 |
+
X : array-like
|
| 1439 |
+
Sample data that will be used to produce the gaussian kernel density
|
| 1440 |
+
estimates. Must have 2 or fewer dimensions.
|
| 1441 |
+
|
| 1442 |
+
method : callable
|
| 1443 |
+
The method used to calculate the kernel density estimate for each
|
| 1444 |
+
column of data. When called via ``method(v, coords)``, it should
|
| 1445 |
+
return a vector of the values of the KDE evaluated at the values
|
| 1446 |
+
specified in coords.
|
| 1447 |
+
|
| 1448 |
+
points : int, default: 100
|
| 1449 |
+
Defines the number of points to evaluate each of the gaussian kernel
|
| 1450 |
+
density estimates at.
|
| 1451 |
+
|
| 1452 |
+
quantiles : array-like, default: None
|
| 1453 |
+
Defines (if not None) a list of floats in interval [0, 1] for each
|
| 1454 |
+
column of data, which represents the quantiles that will be rendered
|
| 1455 |
+
for that column of data. Must have 2 or fewer dimensions. 1D array will
|
| 1456 |
+
be treated as a singleton list containing them.
|
| 1457 |
+
|
| 1458 |
+
Returns
|
| 1459 |
+
-------
|
| 1460 |
+
list of dict
|
| 1461 |
+
A list of dictionaries containing the results for each column of data.
|
| 1462 |
+
The dictionaries contain at least the following:
|
| 1463 |
+
|
| 1464 |
+
- coords: A list of scalars containing the coordinates this particular
|
| 1465 |
+
kernel density estimate was evaluated at.
|
| 1466 |
+
- vals: A list of scalars containing the values of the kernel density
|
| 1467 |
+
estimate at each of the coordinates given in *coords*.
|
| 1468 |
+
- mean: The mean value for this column of data.
|
| 1469 |
+
- median: The median value for this column of data.
|
| 1470 |
+
- min: The minimum value for this column of data.
|
| 1471 |
+
- max: The maximum value for this column of data.
|
| 1472 |
+
- quantiles: The quantile values for this column of data.
|
| 1473 |
+
"""
|
| 1474 |
+
|
| 1475 |
+
# List of dictionaries describing each of the violins.
|
| 1476 |
+
vpstats = []
|
| 1477 |
+
|
| 1478 |
+
# Want X to be a list of data sequences
|
| 1479 |
+
X = _reshape_2D(X, "X")
|
| 1480 |
+
|
| 1481 |
+
# Want quantiles to be as the same shape as data sequences
|
| 1482 |
+
if quantiles is not None and len(quantiles) != 0:
|
| 1483 |
+
quantiles = _reshape_2D(quantiles, "quantiles")
|
| 1484 |
+
# Else, mock quantiles if it's none or empty
|
| 1485 |
+
else:
|
| 1486 |
+
quantiles = [[]] * len(X)
|
| 1487 |
+
|
| 1488 |
+
# quantiles should have the same size as dataset
|
| 1489 |
+
if len(X) != len(quantiles):
|
| 1490 |
+
raise ValueError("List of violinplot statistics and quantiles values"
|
| 1491 |
+
" must have the same length")
|
| 1492 |
+
|
| 1493 |
+
# Zip x and quantiles
|
| 1494 |
+
for (x, q) in zip(X, quantiles):
|
| 1495 |
+
# Dictionary of results for this distribution
|
| 1496 |
+
stats = {}
|
| 1497 |
+
|
| 1498 |
+
# Calculate basic stats for the distribution
|
| 1499 |
+
min_val = np.min(x)
|
| 1500 |
+
max_val = np.max(x)
|
| 1501 |
+
quantile_val = np.percentile(x, 100 * q)
|
| 1502 |
+
|
| 1503 |
+
# Evaluate the kernel density estimate
|
| 1504 |
+
coords = np.linspace(min_val, max_val, points)
|
| 1505 |
+
stats['vals'] = method(x, coords)
|
| 1506 |
+
stats['coords'] = coords
|
| 1507 |
+
|
| 1508 |
+
# Store additional statistics for this distribution
|
| 1509 |
+
stats['mean'] = np.mean(x)
|
| 1510 |
+
stats['median'] = np.median(x)
|
| 1511 |
+
stats['min'] = min_val
|
| 1512 |
+
stats['max'] = max_val
|
| 1513 |
+
stats['quantiles'] = np.atleast_1d(quantile_val)
|
| 1514 |
+
|
| 1515 |
+
# Append to output
|
| 1516 |
+
vpstats.append(stats)
|
| 1517 |
+
|
| 1518 |
+
return vpstats
|
| 1519 |
+
|
| 1520 |
+
|
| 1521 |
+
def pts_to_prestep(x, *args):
|
| 1522 |
+
"""
|
| 1523 |
+
Convert continuous line to pre-steps.
|
| 1524 |
+
|
| 1525 |
+
Given a set of ``N`` points, convert to ``2N - 1`` points, which when
|
| 1526 |
+
connected linearly give a step function which changes values at the
|
| 1527 |
+
beginning of the intervals.
|
| 1528 |
+
|
| 1529 |
+
Parameters
|
| 1530 |
+
----------
|
| 1531 |
+
x : array
|
| 1532 |
+
The x location of the steps. May be empty.
|
| 1533 |
+
|
| 1534 |
+
y1, ..., yp : array
|
| 1535 |
+
y arrays to be turned into steps; all must be the same length as ``x``.
|
| 1536 |
+
|
| 1537 |
+
Returns
|
| 1538 |
+
-------
|
| 1539 |
+
array
|
| 1540 |
+
The x and y values converted to steps in the same order as the input;
|
| 1541 |
+
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
|
| 1542 |
+
length ``N``, each of these arrays will be length ``2N + 1``. For
|
| 1543 |
+
``N=0``, the length will be 0.
|
| 1544 |
+
|
| 1545 |
+
Examples
|
| 1546 |
+
--------
|
| 1547 |
+
>>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
|
| 1548 |
+
"""
|
| 1549 |
+
steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
|
| 1550 |
+
# In all `pts_to_*step` functions, only assign once using *x* and *args*,
|
| 1551 |
+
# as converting to an array may be expensive.
|
| 1552 |
+
steps[0, 0::2] = x
|
| 1553 |
+
steps[0, 1::2] = steps[0, 0:-2:2]
|
| 1554 |
+
steps[1:, 0::2] = args
|
| 1555 |
+
steps[1:, 1::2] = steps[1:, 2::2]
|
| 1556 |
+
return steps
|
| 1557 |
+
|
| 1558 |
+
|
| 1559 |
+
def pts_to_poststep(x, *args):
|
| 1560 |
+
"""
|
| 1561 |
+
Convert continuous line to post-steps.
|
| 1562 |
+
|
| 1563 |
+
Given a set of ``N`` points convert to ``2N + 1`` points, which when
|
| 1564 |
+
connected linearly give a step function which changes values at the end of
|
| 1565 |
+
the intervals.
|
| 1566 |
+
|
| 1567 |
+
Parameters
|
| 1568 |
+
----------
|
| 1569 |
+
x : array
|
| 1570 |
+
The x location of the steps. May be empty.
|
| 1571 |
+
|
| 1572 |
+
y1, ..., yp : array
|
| 1573 |
+
y arrays to be turned into steps; all must be the same length as ``x``.
|
| 1574 |
+
|
| 1575 |
+
Returns
|
| 1576 |
+
-------
|
| 1577 |
+
array
|
| 1578 |
+
The x and y values converted to steps in the same order as the input;
|
| 1579 |
+
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
|
| 1580 |
+
length ``N``, each of these arrays will be length ``2N + 1``. For
|
| 1581 |
+
``N=0``, the length will be 0.
|
| 1582 |
+
|
| 1583 |
+
Examples
|
| 1584 |
+
--------
|
| 1585 |
+
>>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
|
| 1586 |
+
"""
|
| 1587 |
+
steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
|
| 1588 |
+
steps[0, 0::2] = x
|
| 1589 |
+
steps[0, 1::2] = steps[0, 2::2]
|
| 1590 |
+
steps[1:, 0::2] = args
|
| 1591 |
+
steps[1:, 1::2] = steps[1:, 0:-2:2]
|
| 1592 |
+
return steps
|
| 1593 |
+
|
| 1594 |
+
|
| 1595 |
+
def pts_to_midstep(x, *args):
|
| 1596 |
+
"""
|
| 1597 |
+
Convert continuous line to mid-steps.
|
| 1598 |
+
|
| 1599 |
+
Given a set of ``N`` points convert to ``2N`` points which when connected
|
| 1600 |
+
linearly give a step function which changes values at the middle of the
|
| 1601 |
+
intervals.
|
| 1602 |
+
|
| 1603 |
+
Parameters
|
| 1604 |
+
----------
|
| 1605 |
+
x : array
|
| 1606 |
+
The x location of the steps. May be empty.
|
| 1607 |
+
|
| 1608 |
+
y1, ..., yp : array
|
| 1609 |
+
y arrays to be turned into steps; all must be the same length as
|
| 1610 |
+
``x``.
|
| 1611 |
+
|
| 1612 |
+
Returns
|
| 1613 |
+
-------
|
| 1614 |
+
array
|
| 1615 |
+
The x and y values converted to steps in the same order as the input;
|
| 1616 |
+
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
|
| 1617 |
+
length ``N``, each of these arrays will be length ``2N``.
|
| 1618 |
+
|
| 1619 |
+
Examples
|
| 1620 |
+
--------
|
| 1621 |
+
>>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
|
| 1622 |
+
"""
|
| 1623 |
+
steps = np.zeros((1 + len(args), 2 * len(x)))
|
| 1624 |
+
x = np.asanyarray(x)
|
| 1625 |
+
steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2
|
| 1626 |
+
steps[0, :1] = x[:1] # Also works for zero-sized input.
|
| 1627 |
+
steps[0, -1:] = x[-1:]
|
| 1628 |
+
steps[1:, 0::2] = args
|
| 1629 |
+
steps[1:, 1::2] = steps[1:, 0::2]
|
| 1630 |
+
return steps
|
| 1631 |
+
|
| 1632 |
+
|
| 1633 |
+
STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y),
|
| 1634 |
+
'steps': pts_to_prestep,
|
| 1635 |
+
'steps-pre': pts_to_prestep,
|
| 1636 |
+
'steps-post': pts_to_poststep,
|
| 1637 |
+
'steps-mid': pts_to_midstep}
|
| 1638 |
+
|
| 1639 |
+
|
| 1640 |
+
def index_of(y):
|
| 1641 |
+
"""
|
| 1642 |
+
A helper function to create reasonable x values for the given *y*.
|
| 1643 |
+
|
| 1644 |
+
This is used for plotting (x, y) if x values are not explicitly given.
|
| 1645 |
+
|
| 1646 |
+
First try ``y.index`` (assuming *y* is a `pandas.Series`), if that
|
| 1647 |
+
fails, use ``range(len(y))``.
|
| 1648 |
+
|
| 1649 |
+
This will be extended in the future to deal with more types of
|
| 1650 |
+
labeled data.
|
| 1651 |
+
|
| 1652 |
+
Parameters
|
| 1653 |
+
----------
|
| 1654 |
+
y : float or array-like
|
| 1655 |
+
|
| 1656 |
+
Returns
|
| 1657 |
+
-------
|
| 1658 |
+
x, y : ndarray
|
| 1659 |
+
The x and y values to plot.
|
| 1660 |
+
"""
|
| 1661 |
+
try:
|
| 1662 |
+
return y.index.to_numpy(), y.to_numpy()
|
| 1663 |
+
except AttributeError:
|
| 1664 |
+
pass
|
| 1665 |
+
try:
|
| 1666 |
+
y = _check_1d(y)
|
| 1667 |
+
except (VisibleDeprecationWarning, ValueError):
|
| 1668 |
+
# NumPy 1.19 will warn on ragged input, and we can't actually use it.
|
| 1669 |
+
pass
|
| 1670 |
+
else:
|
| 1671 |
+
return np.arange(y.shape[0], dtype=float), y
|
| 1672 |
+
raise ValueError('Input could not be cast to an at-least-1D NumPy array')
|
| 1673 |
+
|
| 1674 |
+
|
| 1675 |
+
def safe_first_element(obj):
|
| 1676 |
+
"""
|
| 1677 |
+
Return the first element in *obj*.
|
| 1678 |
+
|
| 1679 |
+
This is a type-independent way of obtaining the first element,
|
| 1680 |
+
supporting both index access and the iterator protocol.
|
| 1681 |
+
"""
|
| 1682 |
+
if isinstance(obj, collections.abc.Iterator):
|
| 1683 |
+
# needed to accept `array.flat` as input.
|
| 1684 |
+
# np.flatiter reports as an instance of collections.Iterator but can still be
|
| 1685 |
+
# indexed via []. This has the side effect of re-setting the iterator, but
|
| 1686 |
+
# that is acceptable.
|
| 1687 |
+
try:
|
| 1688 |
+
return obj[0]
|
| 1689 |
+
except TypeError:
|
| 1690 |
+
pass
|
| 1691 |
+
raise RuntimeError("matplotlib does not support generators as input")
|
| 1692 |
+
return next(iter(obj))
|
| 1693 |
+
|
| 1694 |
+
|
| 1695 |
+
def _safe_first_finite(obj):
|
| 1696 |
+
"""
|
| 1697 |
+
Return the first finite element in *obj* if one is available and skip_nonfinite is
|
| 1698 |
+
True. Otherwise, return the first element.
|
| 1699 |
+
|
| 1700 |
+
This is a method for internal use.
|
| 1701 |
+
|
| 1702 |
+
This is a type-independent way of obtaining the first finite element, supporting
|
| 1703 |
+
both index access and the iterator protocol.
|
| 1704 |
+
"""
|
| 1705 |
+
def safe_isfinite(val):
|
| 1706 |
+
if val is None:
|
| 1707 |
+
return False
|
| 1708 |
+
try:
|
| 1709 |
+
return math.isfinite(val)
|
| 1710 |
+
except (TypeError, ValueError):
|
| 1711 |
+
# if the outer object is 2d, then val is a 1d array, and
|
| 1712 |
+
# - math.isfinite(numpy.zeros(3)) raises TypeError
|
| 1713 |
+
# - math.isfinite(torch.zeros(3)) raises ValueError
|
| 1714 |
+
pass
|
| 1715 |
+
try:
|
| 1716 |
+
return np.isfinite(val) if np.isscalar(val) else True
|
| 1717 |
+
except TypeError:
|
| 1718 |
+
# This is something that NumPy cannot make heads or tails of,
|
| 1719 |
+
# assume "finite"
|
| 1720 |
+
return True
|
| 1721 |
+
|
| 1722 |
+
if isinstance(obj, np.flatiter):
|
| 1723 |
+
# TODO do the finite filtering on this
|
| 1724 |
+
return obj[0]
|
| 1725 |
+
elif isinstance(obj, collections.abc.Iterator):
|
| 1726 |
+
raise RuntimeError("matplotlib does not support generators as input")
|
| 1727 |
+
else:
|
| 1728 |
+
for val in obj:
|
| 1729 |
+
if safe_isfinite(val):
|
| 1730 |
+
return val
|
| 1731 |
+
return safe_first_element(obj)
|
| 1732 |
+
|
| 1733 |
+
|
| 1734 |
+
def sanitize_sequence(data):
|
| 1735 |
+
"""
|
| 1736 |
+
Convert dictview objects to list. Other inputs are returned unchanged.
|
| 1737 |
+
"""
|
| 1738 |
+
return (list(data) if isinstance(data, collections.abc.MappingView)
|
| 1739 |
+
else data)
|
| 1740 |
+
|
| 1741 |
+
|
| 1742 |
+
def normalize_kwargs(kw, alias_mapping=None):
|
| 1743 |
+
"""
|
| 1744 |
+
Helper function to normalize kwarg inputs.
|
| 1745 |
+
|
| 1746 |
+
Parameters
|
| 1747 |
+
----------
|
| 1748 |
+
kw : dict or None
|
| 1749 |
+
A dict of keyword arguments. None is explicitly supported and treated
|
| 1750 |
+
as an empty dict, to support functions with an optional parameter of
|
| 1751 |
+
the form ``props=None``.
|
| 1752 |
+
|
| 1753 |
+
alias_mapping : dict or Artist subclass or Artist instance, optional
|
| 1754 |
+
A mapping between a canonical name to a list of aliases, in order of
|
| 1755 |
+
precedence from lowest to highest.
|
| 1756 |
+
|
| 1757 |
+
If the canonical value is not in the list it is assumed to have the
|
| 1758 |
+
highest priority.
|
| 1759 |
+
|
| 1760 |
+
If an Artist subclass or instance is passed, use its properties alias
|
| 1761 |
+
mapping.
|
| 1762 |
+
|
| 1763 |
+
Raises
|
| 1764 |
+
------
|
| 1765 |
+
TypeError
|
| 1766 |
+
To match what Python raises if invalid arguments/keyword arguments are
|
| 1767 |
+
passed to a callable.
|
| 1768 |
+
"""
|
| 1769 |
+
from matplotlib.artist import Artist
|
| 1770 |
+
|
| 1771 |
+
if kw is None:
|
| 1772 |
+
return {}
|
| 1773 |
+
|
| 1774 |
+
# deal with default value of alias_mapping
|
| 1775 |
+
if alias_mapping is None:
|
| 1776 |
+
alias_mapping = {}
|
| 1777 |
+
elif (isinstance(alias_mapping, type) and issubclass(alias_mapping, Artist)
|
| 1778 |
+
or isinstance(alias_mapping, Artist)):
|
| 1779 |
+
alias_mapping = getattr(alias_mapping, "_alias_map", {})
|
| 1780 |
+
|
| 1781 |
+
to_canonical = {alias: canonical
|
| 1782 |
+
for canonical, alias_list in alias_mapping.items()
|
| 1783 |
+
for alias in alias_list}
|
| 1784 |
+
canonical_to_seen = {}
|
| 1785 |
+
ret = {} # output dictionary
|
| 1786 |
+
|
| 1787 |
+
for k, v in kw.items():
|
| 1788 |
+
canonical = to_canonical.get(k, k)
|
| 1789 |
+
if canonical in canonical_to_seen:
|
| 1790 |
+
raise TypeError(f"Got both {canonical_to_seen[canonical]!r} and "
|
| 1791 |
+
f"{k!r}, which are aliases of one another")
|
| 1792 |
+
canonical_to_seen[canonical] = k
|
| 1793 |
+
ret[canonical] = v
|
| 1794 |
+
|
| 1795 |
+
return ret
|
| 1796 |
+
|
| 1797 |
+
|
| 1798 |
+
@contextlib.contextmanager
|
| 1799 |
+
def _lock_path(path):
|
| 1800 |
+
"""
|
| 1801 |
+
Context manager for locking a path.
|
| 1802 |
+
|
| 1803 |
+
Usage::
|
| 1804 |
+
|
| 1805 |
+
with _lock_path(path):
|
| 1806 |
+
...
|
| 1807 |
+
|
| 1808 |
+
Another thread or process that attempts to lock the same path will wait
|
| 1809 |
+
until this context manager is exited.
|
| 1810 |
+
|
| 1811 |
+
The lock is implemented by creating a temporary file in the parent
|
| 1812 |
+
directory, so that directory must exist and be writable.
|
| 1813 |
+
"""
|
| 1814 |
+
path = Path(path)
|
| 1815 |
+
lock_path = path.with_name(path.name + ".matplotlib-lock")
|
| 1816 |
+
retries = 50
|
| 1817 |
+
sleeptime = 0.1
|
| 1818 |
+
for _ in range(retries):
|
| 1819 |
+
try:
|
| 1820 |
+
with lock_path.open("xb"):
|
| 1821 |
+
break
|
| 1822 |
+
except FileExistsError:
|
| 1823 |
+
time.sleep(sleeptime)
|
| 1824 |
+
else:
|
| 1825 |
+
raise TimeoutError("""\
|
| 1826 |
+
Lock error: Matplotlib failed to acquire the following lock file:
|
| 1827 |
+
{}
|
| 1828 |
+
This maybe due to another process holding this lock file. If you are sure no
|
| 1829 |
+
other Matplotlib process is running, remove this file and try again.""".format(
|
| 1830 |
+
lock_path))
|
| 1831 |
+
try:
|
| 1832 |
+
yield
|
| 1833 |
+
finally:
|
| 1834 |
+
lock_path.unlink()
|
| 1835 |
+
|
| 1836 |
+
|
| 1837 |
+
def _topmost_artist(
|
| 1838 |
+
artists,
|
| 1839 |
+
_cached_max=functools.partial(max, key=operator.attrgetter("zorder"))):
|
| 1840 |
+
"""
|
| 1841 |
+
Get the topmost artist of a list.
|
| 1842 |
+
|
| 1843 |
+
In case of a tie, return the *last* of the tied artists, as it will be
|
| 1844 |
+
drawn on top of the others. `max` returns the first maximum in case of
|
| 1845 |
+
ties, so we need to iterate over the list in reverse order.
|
| 1846 |
+
"""
|
| 1847 |
+
return _cached_max(reversed(artists))
|
| 1848 |
+
|
| 1849 |
+
|
| 1850 |
+
def _str_equal(obj, s):
|
| 1851 |
+
"""
|
| 1852 |
+
Return whether *obj* is a string equal to string *s*.
|
| 1853 |
+
|
| 1854 |
+
This helper solely exists to handle the case where *obj* is a numpy array,
|
| 1855 |
+
because in such cases, a naive ``obj == s`` would yield an array, which
|
| 1856 |
+
cannot be used in a boolean context.
|
| 1857 |
+
"""
|
| 1858 |
+
return isinstance(obj, str) and obj == s
|
| 1859 |
+
|
| 1860 |
+
|
| 1861 |
+
def _str_lower_equal(obj, s):
|
| 1862 |
+
"""
|
| 1863 |
+
Return whether *obj* is a string equal, when lowercased, to string *s*.
|
| 1864 |
+
|
| 1865 |
+
This helper solely exists to handle the case where *obj* is a numpy array,
|
| 1866 |
+
because in such cases, a naive ``obj == s`` would yield an array, which
|
| 1867 |
+
cannot be used in a boolean context.
|
| 1868 |
+
"""
|
| 1869 |
+
return isinstance(obj, str) and obj.lower() == s
|
| 1870 |
+
|
| 1871 |
+
|
| 1872 |
+
def _array_perimeter(arr):
|
| 1873 |
+
"""
|
| 1874 |
+
Get the elements on the perimeter of *arr*.
|
| 1875 |
+
|
| 1876 |
+
Parameters
|
| 1877 |
+
----------
|
| 1878 |
+
arr : ndarray, shape (M, N)
|
| 1879 |
+
The input array.
|
| 1880 |
+
|
| 1881 |
+
Returns
|
| 1882 |
+
-------
|
| 1883 |
+
ndarray, shape (2*(M - 1) + 2*(N - 1),)
|
| 1884 |
+
The elements on the perimeter of the array::
|
| 1885 |
+
|
| 1886 |
+
[arr[0, 0], ..., arr[0, -1], ..., arr[-1, -1], ..., arr[-1, 0], ...]
|
| 1887 |
+
|
| 1888 |
+
Examples
|
| 1889 |
+
--------
|
| 1890 |
+
>>> i, j = np.ogrid[:3, :4]
|
| 1891 |
+
>>> a = i*10 + j
|
| 1892 |
+
>>> a
|
| 1893 |
+
array([[ 0, 1, 2, 3],
|
| 1894 |
+
[10, 11, 12, 13],
|
| 1895 |
+
[20, 21, 22, 23]])
|
| 1896 |
+
>>> _array_perimeter(a)
|
| 1897 |
+
array([ 0, 1, 2, 3, 13, 23, 22, 21, 20, 10])
|
| 1898 |
+
"""
|
| 1899 |
+
# note we use Python's half-open ranges to avoid repeating
|
| 1900 |
+
# the corners
|
| 1901 |
+
forward = np.s_[0:-1] # [0 ... -1)
|
| 1902 |
+
backward = np.s_[-1:0:-1] # [-1 ... 0)
|
| 1903 |
+
return np.concatenate((
|
| 1904 |
+
arr[0, forward],
|
| 1905 |
+
arr[forward, -1],
|
| 1906 |
+
arr[-1, backward],
|
| 1907 |
+
arr[backward, 0],
|
| 1908 |
+
))
|
| 1909 |
+
|
| 1910 |
+
|
| 1911 |
+
def _unfold(arr, axis, size, step):
|
| 1912 |
+
"""
|
| 1913 |
+
Append an extra dimension containing sliding windows along *axis*.
|
| 1914 |
+
|
| 1915 |
+
All windows are of size *size* and begin with every *step* elements.
|
| 1916 |
+
|
| 1917 |
+
Parameters
|
| 1918 |
+
----------
|
| 1919 |
+
arr : ndarray, shape (N_1, ..., N_k)
|
| 1920 |
+
The input array
|
| 1921 |
+
axis : int
|
| 1922 |
+
Axis along which the windows are extracted
|
| 1923 |
+
size : int
|
| 1924 |
+
Size of the windows
|
| 1925 |
+
step : int
|
| 1926 |
+
Stride between first elements of subsequent windows.
|
| 1927 |
+
|
| 1928 |
+
Returns
|
| 1929 |
+
-------
|
| 1930 |
+
ndarray, shape (N_1, ..., 1 + (N_axis-size)/step, ..., N_k, size)
|
| 1931 |
+
|
| 1932 |
+
Examples
|
| 1933 |
+
--------
|
| 1934 |
+
>>> i, j = np.ogrid[:3, :7]
|
| 1935 |
+
>>> a = i*10 + j
|
| 1936 |
+
>>> a
|
| 1937 |
+
array([[ 0, 1, 2, 3, 4, 5, 6],
|
| 1938 |
+
[10, 11, 12, 13, 14, 15, 16],
|
| 1939 |
+
[20, 21, 22, 23, 24, 25, 26]])
|
| 1940 |
+
>>> _unfold(a, axis=1, size=3, step=2)
|
| 1941 |
+
array([[[ 0, 1, 2],
|
| 1942 |
+
[ 2, 3, 4],
|
| 1943 |
+
[ 4, 5, 6]],
|
| 1944 |
+
[[10, 11, 12],
|
| 1945 |
+
[12, 13, 14],
|
| 1946 |
+
[14, 15, 16]],
|
| 1947 |
+
[[20, 21, 22],
|
| 1948 |
+
[22, 23, 24],
|
| 1949 |
+
[24, 25, 26]]])
|
| 1950 |
+
"""
|
| 1951 |
+
new_shape = [*arr.shape, size]
|
| 1952 |
+
new_strides = [*arr.strides, arr.strides[axis]]
|
| 1953 |
+
new_shape[axis] = (new_shape[axis] - size) // step + 1
|
| 1954 |
+
new_strides[axis] = new_strides[axis] * step
|
| 1955 |
+
return np.lib.stride_tricks.as_strided(arr,
|
| 1956 |
+
shape=new_shape,
|
| 1957 |
+
strides=new_strides,
|
| 1958 |
+
writeable=False)
|
| 1959 |
+
|
| 1960 |
+
|
| 1961 |
+
def _array_patch_perimeters(x, rstride, cstride):
|
| 1962 |
+
"""
|
| 1963 |
+
Extract perimeters of patches from *arr*.
|
| 1964 |
+
|
| 1965 |
+
Extracted patches are of size (*rstride* + 1) x (*cstride* + 1) and
|
| 1966 |
+
share perimeters with their neighbors. The ordering of the vertices matches
|
| 1967 |
+
that returned by ``_array_perimeter``.
|
| 1968 |
+
|
| 1969 |
+
Parameters
|
| 1970 |
+
----------
|
| 1971 |
+
x : ndarray, shape (N, M)
|
| 1972 |
+
Input array
|
| 1973 |
+
rstride : int
|
| 1974 |
+
Vertical (row) stride between corresponding elements of each patch
|
| 1975 |
+
cstride : int
|
| 1976 |
+
Horizontal (column) stride between corresponding elements of each patch
|
| 1977 |
+
|
| 1978 |
+
Returns
|
| 1979 |
+
-------
|
| 1980 |
+
ndarray, shape (N/rstride * M/cstride, 2 * (rstride + cstride))
|
| 1981 |
+
"""
|
| 1982 |
+
assert rstride > 0 and cstride > 0
|
| 1983 |
+
assert (x.shape[0] - 1) % rstride == 0
|
| 1984 |
+
assert (x.shape[1] - 1) % cstride == 0
|
| 1985 |
+
# We build up each perimeter from four half-open intervals. Here is an
|
| 1986 |
+
# illustrated explanation for rstride == cstride == 3
|
| 1987 |
+
#
|
| 1988 |
+
# T T T R
|
| 1989 |
+
# L R
|
| 1990 |
+
# L R
|
| 1991 |
+
# L B B B
|
| 1992 |
+
#
|
| 1993 |
+
# where T means that this element will be in the top array, R for right,
|
| 1994 |
+
# B for bottom and L for left. Each of the arrays below has a shape of:
|
| 1995 |
+
#
|
| 1996 |
+
# (number of perimeters that can be extracted vertically,
|
| 1997 |
+
# number of perimeters that can be extracted horizontally,
|
| 1998 |
+
# cstride for top and bottom and rstride for left and right)
|
| 1999 |
+
#
|
| 2000 |
+
# Note that _unfold doesn't incur any memory copies, so the only costly
|
| 2001 |
+
# operation here is the np.concatenate.
|
| 2002 |
+
top = _unfold(x[:-1:rstride, :-1], 1, cstride, cstride)
|
| 2003 |
+
bottom = _unfold(x[rstride::rstride, 1:], 1, cstride, cstride)[..., ::-1]
|
| 2004 |
+
right = _unfold(x[:-1, cstride::cstride], 0, rstride, rstride)
|
| 2005 |
+
left = _unfold(x[1:, :-1:cstride], 0, rstride, rstride)[..., ::-1]
|
| 2006 |
+
return (np.concatenate((top, right, bottom, left), axis=2)
|
| 2007 |
+
.reshape(-1, 2 * (rstride + cstride)))
|
| 2008 |
+
|
| 2009 |
+
|
| 2010 |
+
@contextlib.contextmanager
|
| 2011 |
+
def _setattr_cm(obj, **kwargs):
|
| 2012 |
+
"""
|
| 2013 |
+
Temporarily set some attributes; restore original state at context exit.
|
| 2014 |
+
"""
|
| 2015 |
+
sentinel = object()
|
| 2016 |
+
origs = {}
|
| 2017 |
+
for attr in kwargs:
|
| 2018 |
+
orig = getattr(obj, attr, sentinel)
|
| 2019 |
+
if attr in obj.__dict__ or orig is sentinel:
|
| 2020 |
+
# if we are pulling from the instance dict or the object
|
| 2021 |
+
# does not have this attribute we can trust the above
|
| 2022 |
+
origs[attr] = orig
|
| 2023 |
+
else:
|
| 2024 |
+
# if the attribute is not in the instance dict it must be
|
| 2025 |
+
# from the class level
|
| 2026 |
+
cls_orig = getattr(type(obj), attr)
|
| 2027 |
+
# if we are dealing with a property (but not a general descriptor)
|
| 2028 |
+
# we want to set the original value back.
|
| 2029 |
+
if isinstance(cls_orig, property):
|
| 2030 |
+
origs[attr] = orig
|
| 2031 |
+
# otherwise this is _something_ we are going to shadow at
|
| 2032 |
+
# the instance dict level from higher up in the MRO. We
|
| 2033 |
+
# are going to assume we can delattr(obj, attr) to clean
|
| 2034 |
+
# up after ourselves. It is possible that this code will
|
| 2035 |
+
# fail if used with a non-property custom descriptor which
|
| 2036 |
+
# implements __set__ (and __delete__ does not act like a
|
| 2037 |
+
# stack). However, this is an internal tool and we do not
|
| 2038 |
+
# currently have any custom descriptors.
|
| 2039 |
+
else:
|
| 2040 |
+
origs[attr] = sentinel
|
| 2041 |
+
|
| 2042 |
+
try:
|
| 2043 |
+
for attr, val in kwargs.items():
|
| 2044 |
+
setattr(obj, attr, val)
|
| 2045 |
+
yield
|
| 2046 |
+
finally:
|
| 2047 |
+
for attr, orig in origs.items():
|
| 2048 |
+
if orig is sentinel:
|
| 2049 |
+
delattr(obj, attr)
|
| 2050 |
+
else:
|
| 2051 |
+
setattr(obj, attr, orig)
|
| 2052 |
+
|
| 2053 |
+
|
| 2054 |
+
class _OrderedSet(collections.abc.MutableSet):
|
| 2055 |
+
def __init__(self):
|
| 2056 |
+
self._od = collections.OrderedDict()
|
| 2057 |
+
|
| 2058 |
+
def __contains__(self, key):
|
| 2059 |
+
return key in self._od
|
| 2060 |
+
|
| 2061 |
+
def __iter__(self):
|
| 2062 |
+
return iter(self._od)
|
| 2063 |
+
|
| 2064 |
+
def __len__(self):
|
| 2065 |
+
return len(self._od)
|
| 2066 |
+
|
| 2067 |
+
def add(self, key):
|
| 2068 |
+
self._od.pop(key, None)
|
| 2069 |
+
self._od[key] = None
|
| 2070 |
+
|
| 2071 |
+
def discard(self, key):
|
| 2072 |
+
self._od.pop(key, None)
|
| 2073 |
+
|
| 2074 |
+
|
| 2075 |
+
# Agg's buffers are unmultiplied RGBA8888, which neither PyQt<=5.1 nor cairo
|
| 2076 |
+
# support; however, both do support premultiplied ARGB32.
|
| 2077 |
+
|
| 2078 |
+
|
| 2079 |
+
def _premultiplied_argb32_to_unmultiplied_rgba8888(buf):
|
| 2080 |
+
"""
|
| 2081 |
+
Convert a premultiplied ARGB32 buffer to an unmultiplied RGBA8888 buffer.
|
| 2082 |
+
"""
|
| 2083 |
+
rgba = np.take( # .take() ensures C-contiguity of the result.
|
| 2084 |
+
buf,
|
| 2085 |
+
[2, 1, 0, 3] if sys.byteorder == "little" else [1, 2, 3, 0], axis=2)
|
| 2086 |
+
rgb = rgba[..., :-1]
|
| 2087 |
+
alpha = rgba[..., -1]
|
| 2088 |
+
# Un-premultiply alpha. The formula is the same as in cairo-png.c.
|
| 2089 |
+
mask = alpha != 0
|
| 2090 |
+
for channel in np.rollaxis(rgb, -1):
|
| 2091 |
+
channel[mask] = (
|
| 2092 |
+
(channel[mask].astype(int) * 255 + alpha[mask] // 2)
|
| 2093 |
+
// alpha[mask])
|
| 2094 |
+
return rgba
|
| 2095 |
+
|
| 2096 |
+
|
| 2097 |
+
def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888):
|
| 2098 |
+
"""
|
| 2099 |
+
Convert an unmultiplied RGBA8888 buffer to a premultiplied ARGB32 buffer.
|
| 2100 |
+
"""
|
| 2101 |
+
if sys.byteorder == "little":
|
| 2102 |
+
argb32 = np.take(rgba8888, [2, 1, 0, 3], axis=2)
|
| 2103 |
+
rgb24 = argb32[..., :-1]
|
| 2104 |
+
alpha8 = argb32[..., -1:]
|
| 2105 |
+
else:
|
| 2106 |
+
argb32 = np.take(rgba8888, [3, 0, 1, 2], axis=2)
|
| 2107 |
+
alpha8 = argb32[..., :1]
|
| 2108 |
+
rgb24 = argb32[..., 1:]
|
| 2109 |
+
# Only bother premultiplying when the alpha channel is not fully opaque,
|
| 2110 |
+
# as the cost is not negligible. The unsafe cast is needed to do the
|
| 2111 |
+
# multiplication in-place in an integer buffer.
|
| 2112 |
+
if alpha8.min() != 0xff:
|
| 2113 |
+
np.multiply(rgb24, alpha8 / 0xff, out=rgb24, casting="unsafe")
|
| 2114 |
+
return argb32
|
| 2115 |
+
|
| 2116 |
+
|
| 2117 |
+
def _get_nonzero_slices(buf):
|
| 2118 |
+
"""
|
| 2119 |
+
Return the bounds of the nonzero region of a 2D array as a pair of slices.
|
| 2120 |
+
|
| 2121 |
+
``buf[_get_nonzero_slices(buf)]`` is the smallest sub-rectangle in *buf*
|
| 2122 |
+
that encloses all non-zero entries in *buf*. If *buf* is fully zero, then
|
| 2123 |
+
``(slice(0, 0), slice(0, 0))`` is returned.
|
| 2124 |
+
"""
|
| 2125 |
+
x_nz, = buf.any(axis=0).nonzero()
|
| 2126 |
+
y_nz, = buf.any(axis=1).nonzero()
|
| 2127 |
+
if len(x_nz) and len(y_nz):
|
| 2128 |
+
l, r = x_nz[[0, -1]]
|
| 2129 |
+
b, t = y_nz[[0, -1]]
|
| 2130 |
+
return slice(b, t + 1), slice(l, r + 1)
|
| 2131 |
+
else:
|
| 2132 |
+
return slice(0, 0), slice(0, 0)
|
| 2133 |
+
|
| 2134 |
+
|
| 2135 |
+
def _pformat_subprocess(command):
|
| 2136 |
+
"""Pretty-format a subprocess command for printing/logging purposes."""
|
| 2137 |
+
return (command if isinstance(command, str)
|
| 2138 |
+
else " ".join(shlex.quote(os.fspath(arg)) for arg in command))
|
| 2139 |
+
|
| 2140 |
+
|
| 2141 |
+
def _check_and_log_subprocess(command, logger, **kwargs):
|
| 2142 |
+
"""
|
| 2143 |
+
Run *command*, returning its stdout output if it succeeds.
|
| 2144 |
+
|
| 2145 |
+
If it fails (exits with nonzero return code), raise an exception whose text
|
| 2146 |
+
includes the failed command and captured stdout and stderr output.
|
| 2147 |
+
|
| 2148 |
+
Regardless of the return code, the command is logged at DEBUG level on
|
| 2149 |
+
*logger*. In case of success, the output is likewise logged.
|
| 2150 |
+
"""
|
| 2151 |
+
logger.debug('%s', _pformat_subprocess(command))
|
| 2152 |
+
proc = subprocess.run(command, capture_output=True, **kwargs)
|
| 2153 |
+
if proc.returncode:
|
| 2154 |
+
stdout = proc.stdout
|
| 2155 |
+
if isinstance(stdout, bytes):
|
| 2156 |
+
stdout = stdout.decode()
|
| 2157 |
+
stderr = proc.stderr
|
| 2158 |
+
if isinstance(stderr, bytes):
|
| 2159 |
+
stderr = stderr.decode()
|
| 2160 |
+
raise RuntimeError(
|
| 2161 |
+
f"The command\n"
|
| 2162 |
+
f" {_pformat_subprocess(command)}\n"
|
| 2163 |
+
f"failed and generated the following output:\n"
|
| 2164 |
+
f"{stdout}\n"
|
| 2165 |
+
f"and the following error:\n"
|
| 2166 |
+
f"{stderr}")
|
| 2167 |
+
if proc.stdout:
|
| 2168 |
+
logger.debug("stdout:\n%s", proc.stdout)
|
| 2169 |
+
if proc.stderr:
|
| 2170 |
+
logger.debug("stderr:\n%s", proc.stderr)
|
| 2171 |
+
return proc.stdout
|
| 2172 |
+
|
| 2173 |
+
|
| 2174 |
+
def _setup_new_guiapp():
|
| 2175 |
+
"""
|
| 2176 |
+
Perform OS-dependent setup when Matplotlib creates a new GUI application.
|
| 2177 |
+
"""
|
| 2178 |
+
# Windows: If not explicit app user model id has been set yet (so we're not
|
| 2179 |
+
# already embedded), then set it to "matplotlib", so that taskbar icons are
|
| 2180 |
+
# correct.
|
| 2181 |
+
try:
|
| 2182 |
+
_c_internal_utils.Win32_GetCurrentProcessExplicitAppUserModelID()
|
| 2183 |
+
except OSError:
|
| 2184 |
+
_c_internal_utils.Win32_SetCurrentProcessExplicitAppUserModelID(
|
| 2185 |
+
"matplotlib")
|
| 2186 |
+
|
| 2187 |
+
|
| 2188 |
+
def _format_approx(number, precision):
|
| 2189 |
+
"""
|
| 2190 |
+
Format the number with at most the number of decimals given as precision.
|
| 2191 |
+
Remove trailing zeros and possibly the decimal point.
|
| 2192 |
+
"""
|
| 2193 |
+
return f'{number:.{precision}f}'.rstrip('0').rstrip('.') or '0'
|
| 2194 |
+
|
| 2195 |
+
|
| 2196 |
+
def _g_sig_digits(value, delta):
|
| 2197 |
+
"""
|
| 2198 |
+
Return the number of significant digits to %g-format *value*, assuming that
|
| 2199 |
+
it is known with an error of *delta*.
|
| 2200 |
+
"""
|
| 2201 |
+
if delta == 0:
|
| 2202 |
+
if value == 0:
|
| 2203 |
+
# if both value and delta are 0, np.spacing below returns 5e-324
|
| 2204 |
+
# which results in rather silly results
|
| 2205 |
+
return 3
|
| 2206 |
+
# delta = 0 may occur when trying to format values over a tiny range;
|
| 2207 |
+
# in that case, replace it by the distance to the closest float.
|
| 2208 |
+
delta = abs(np.spacing(value))
|
| 2209 |
+
# If e.g. value = 45.67 and delta = 0.02, then we want to round to 2 digits
|
| 2210 |
+
# after the decimal point (floor(log10(0.02)) = -2); 45.67 contributes 2
|
| 2211 |
+
# digits before the decimal point (floor(log10(45.67)) + 1 = 2): the total
|
| 2212 |
+
# is 4 significant digits. A value of 0 contributes 1 "digit" before the
|
| 2213 |
+
# decimal point.
|
| 2214 |
+
# For inf or nan, the precision doesn't matter.
|
| 2215 |
+
return max(
|
| 2216 |
+
0,
|
| 2217 |
+
(math.floor(math.log10(abs(value))) + 1 if value else 1)
|
| 2218 |
+
- math.floor(math.log10(delta))) if math.isfinite(value) else 0
|
| 2219 |
+
|
| 2220 |
+
|
| 2221 |
+
def _unikey_or_keysym_to_mplkey(unikey, keysym):
|
| 2222 |
+
"""
|
| 2223 |
+
Convert a Unicode key or X keysym to a Matplotlib key name.
|
| 2224 |
+
|
| 2225 |
+
The Unicode key is checked first; this avoids having to list most printable
|
| 2226 |
+
keysyms such as ``EuroSign``.
|
| 2227 |
+
"""
|
| 2228 |
+
# For non-printable characters, gtk3 passes "\0" whereas tk passes an "".
|
| 2229 |
+
if unikey and unikey.isprintable():
|
| 2230 |
+
return unikey
|
| 2231 |
+
key = keysym.lower()
|
| 2232 |
+
if key.startswith("kp_"): # keypad_x (including kp_enter).
|
| 2233 |
+
key = key[3:]
|
| 2234 |
+
if key.startswith("page_"): # page_{up,down}
|
| 2235 |
+
key = key.replace("page_", "page")
|
| 2236 |
+
if key.endswith(("_l", "_r")): # alt_l, ctrl_l, shift_l.
|
| 2237 |
+
key = key[:-2]
|
| 2238 |
+
if sys.platform == "darwin" and key == "meta":
|
| 2239 |
+
# meta should be reported as command on mac
|
| 2240 |
+
key = "cmd"
|
| 2241 |
+
key = {
|
| 2242 |
+
"return": "enter",
|
| 2243 |
+
"prior": "pageup", # Used by tk.
|
| 2244 |
+
"next": "pagedown", # Used by tk.
|
| 2245 |
+
}.get(key, key)
|
| 2246 |
+
return key
|
| 2247 |
+
|
| 2248 |
+
|
| 2249 |
+
@functools.cache
|
| 2250 |
+
def _make_class_factory(mixin_class, fmt, attr_name=None):
|
| 2251 |
+
"""
|
| 2252 |
+
Return a function that creates picklable classes inheriting from a mixin.
|
| 2253 |
+
|
| 2254 |
+
After ::
|
| 2255 |
+
|
| 2256 |
+
factory = _make_class_factory(FooMixin, fmt, attr_name)
|
| 2257 |
+
FooAxes = factory(Axes)
|
| 2258 |
+
|
| 2259 |
+
``Foo`` is a class that inherits from ``FooMixin`` and ``Axes`` and **is
|
| 2260 |
+
picklable** (picklability is what differentiates this from a plain call to
|
| 2261 |
+
`type`). Its ``__name__`` is set to ``fmt.format(Axes.__name__)`` and the
|
| 2262 |
+
base class is stored in the ``attr_name`` attribute, if not None.
|
| 2263 |
+
|
| 2264 |
+
Moreover, the return value of ``factory`` is memoized: calls with the same
|
| 2265 |
+
``Axes`` class always return the same subclass.
|
| 2266 |
+
"""
|
| 2267 |
+
|
| 2268 |
+
@functools.cache
|
| 2269 |
+
def class_factory(axes_class):
|
| 2270 |
+
# if we have already wrapped this class, declare victory!
|
| 2271 |
+
if issubclass(axes_class, mixin_class):
|
| 2272 |
+
return axes_class
|
| 2273 |
+
|
| 2274 |
+
# The parameter is named "axes_class" for backcompat but is really just
|
| 2275 |
+
# a base class; no axes semantics are used.
|
| 2276 |
+
base_class = axes_class
|
| 2277 |
+
|
| 2278 |
+
class subcls(mixin_class, base_class):
|
| 2279 |
+
# Better approximation than __module__ = "matplotlib.cbook".
|
| 2280 |
+
__module__ = mixin_class.__module__
|
| 2281 |
+
|
| 2282 |
+
def __reduce__(self):
|
| 2283 |
+
return (_picklable_class_constructor,
|
| 2284 |
+
(mixin_class, fmt, attr_name, base_class),
|
| 2285 |
+
self.__getstate__())
|
| 2286 |
+
|
| 2287 |
+
subcls.__name__ = subcls.__qualname__ = fmt.format(base_class.__name__)
|
| 2288 |
+
if attr_name is not None:
|
| 2289 |
+
setattr(subcls, attr_name, base_class)
|
| 2290 |
+
return subcls
|
| 2291 |
+
|
| 2292 |
+
class_factory.__module__ = mixin_class.__module__
|
| 2293 |
+
return class_factory
|
| 2294 |
+
|
| 2295 |
+
|
| 2296 |
+
def _picklable_class_constructor(mixin_class, fmt, attr_name, base_class):
|
| 2297 |
+
"""Internal helper for _make_class_factory."""
|
| 2298 |
+
factory = _make_class_factory(mixin_class, fmt, attr_name)
|
| 2299 |
+
cls = factory(base_class)
|
| 2300 |
+
return cls.__new__(cls)
|
| 2301 |
+
|
| 2302 |
+
|
| 2303 |
+
def _is_torch_array(x):
|
| 2304 |
+
"""Check if 'x' is a PyTorch Tensor."""
|
| 2305 |
+
try:
|
| 2306 |
+
# we're intentionally not attempting to import torch. If somebody
|
| 2307 |
+
# has created a torch array, torch should already be in sys.modules
|
| 2308 |
+
return isinstance(x, sys.modules['torch'].Tensor)
|
| 2309 |
+
except Exception: # TypeError, KeyError, AttributeError, maybe others?
|
| 2310 |
+
# we're attempting to access attributes on imported modules which
|
| 2311 |
+
# may have arbitrary user code, so we deliberately catch all exceptions
|
| 2312 |
+
return False
|
| 2313 |
+
|
| 2314 |
+
|
| 2315 |
+
def _is_jax_array(x):
|
| 2316 |
+
"""Check if 'x' is a JAX Array."""
|
| 2317 |
+
try:
|
| 2318 |
+
# we're intentionally not attempting to import jax. If somebody
|
| 2319 |
+
# has created a jax array, jax should already be in sys.modules
|
| 2320 |
+
return isinstance(x, sys.modules['jax'].Array)
|
| 2321 |
+
except Exception: # TypeError, KeyError, AttributeError, maybe others?
|
| 2322 |
+
# we're attempting to access attributes on imported modules which
|
| 2323 |
+
# may have arbitrary user code, so we deliberately catch all exceptions
|
| 2324 |
+
return False
|
| 2325 |
+
|
| 2326 |
+
|
| 2327 |
+
def _is_tensorflow_array(x):
|
| 2328 |
+
"""Check if 'x' is a TensorFlow Tensor or Variable."""
|
| 2329 |
+
try:
|
| 2330 |
+
# we're intentionally not attempting to import TensorFlow. If somebody
|
| 2331 |
+
# has created a TensorFlow array, TensorFlow should already be in sys.modules
|
| 2332 |
+
# we use `is_tensor` to not depend on the class structure of TensorFlow
|
| 2333 |
+
# arrays, as `tf.Variables` are not instances of `tf.Tensor`
|
| 2334 |
+
# (they both convert the same way)
|
| 2335 |
+
return isinstance(x, sys.modules['tensorflow'].is_tensor(x))
|
| 2336 |
+
except Exception: # TypeError, KeyError, AttributeError, maybe others?
|
| 2337 |
+
# we're attempting to access attributes on imported modules which
|
| 2338 |
+
# may have arbitrary user code, so we deliberately catch all exceptions
|
| 2339 |
+
return False
|
| 2340 |
+
|
| 2341 |
+
|
| 2342 |
+
def _unpack_to_numpy(x):
|
| 2343 |
+
"""Internal helper to extract data from e.g. pandas and xarray objects."""
|
| 2344 |
+
if isinstance(x, np.ndarray):
|
| 2345 |
+
# If numpy, return directly
|
| 2346 |
+
return x
|
| 2347 |
+
if hasattr(x, 'to_numpy'):
|
| 2348 |
+
# Assume that any to_numpy() method actually returns a numpy array
|
| 2349 |
+
return x.to_numpy()
|
| 2350 |
+
if hasattr(x, 'values'):
|
| 2351 |
+
xtmp = x.values
|
| 2352 |
+
# For example a dict has a 'values' attribute, but it is not a property
|
| 2353 |
+
# so in this case we do not want to return a function
|
| 2354 |
+
if isinstance(xtmp, np.ndarray):
|
| 2355 |
+
return xtmp
|
| 2356 |
+
if _is_torch_array(x) or _is_jax_array(x) or _is_tensorflow_array(x):
|
| 2357 |
+
# using np.asarray() instead of explicitly __array__(), as the latter is
|
| 2358 |
+
# only _one_ of many methods, and it's the last resort, see also
|
| 2359 |
+
# https://numpy.org/devdocs/user/basics.interoperability.html#using-arbitrary-objects-in-numpy
|
| 2360 |
+
# therefore, let arrays do better if they can
|
| 2361 |
+
xtmp = np.asarray(x)
|
| 2362 |
+
|
| 2363 |
+
# In case np.asarray method does not return a numpy array in future
|
| 2364 |
+
if isinstance(xtmp, np.ndarray):
|
| 2365 |
+
return xtmp
|
| 2366 |
+
return x
|
| 2367 |
+
|
| 2368 |
+
|
| 2369 |
+
def _auto_format_str(fmt, value):
|
| 2370 |
+
"""
|
| 2371 |
+
Apply *value* to the format string *fmt*.
|
| 2372 |
+
|
| 2373 |
+
This works both with unnamed %-style formatting and
|
| 2374 |
+
unnamed {}-style formatting. %-style formatting has priority.
|
| 2375 |
+
If *fmt* is %-style formattable that will be used. Otherwise,
|
| 2376 |
+
{}-formatting is applied. Strings without formatting placeholders
|
| 2377 |
+
are passed through as is.
|
| 2378 |
+
|
| 2379 |
+
Examples
|
| 2380 |
+
--------
|
| 2381 |
+
>>> _auto_format_str('%.2f m', 0.2)
|
| 2382 |
+
'0.20 m'
|
| 2383 |
+
>>> _auto_format_str('{} m', 0.2)
|
| 2384 |
+
'0.2 m'
|
| 2385 |
+
>>> _auto_format_str('const', 0.2)
|
| 2386 |
+
'const'
|
| 2387 |
+
>>> _auto_format_str('%d or {}', 0.2)
|
| 2388 |
+
'0 or {}'
|
| 2389 |
+
"""
|
| 2390 |
+
try:
|
| 2391 |
+
return fmt % (value,)
|
| 2392 |
+
except (TypeError, ValueError):
|
| 2393 |
+
return fmt.format(value)
|
| 2394 |
+
|
| 2395 |
+
|
| 2396 |
+
def _is_pandas_dataframe(x):
|
| 2397 |
+
"""Check if 'x' is a Pandas DataFrame."""
|
| 2398 |
+
try:
|
| 2399 |
+
# we're intentionally not attempting to import Pandas. If somebody
|
| 2400 |
+
# has created a Pandas DataFrame, Pandas should already be in sys.modules
|
| 2401 |
+
return isinstance(x, sys.modules['pandas'].DataFrame)
|
| 2402 |
+
except Exception: # TypeError, KeyError, AttributeError, maybe others?
|
| 2403 |
+
# we're attempting to access attributes on imported modules which
|
| 2404 |
+
# may have arbitrary user code, so we deliberately catch all exceptions
|
| 2405 |
+
return False
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/collections.py
ADDED
|
@@ -0,0 +1,2582 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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""
|
| 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()
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/font_manager.py
ADDED
|
@@ -0,0 +1,1645 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/inset.pyi
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from . import artist
|
| 2 |
+
from .axes import Axes
|
| 3 |
+
from .backend_bases import RendererBase
|
| 4 |
+
from .patches import ConnectionPatch, Rectangle
|
| 5 |
+
|
| 6 |
+
from .typing import ColorType, LineStyleType
|
| 7 |
+
|
| 8 |
+
class InsetIndicator(artist.Artist):
|
| 9 |
+
def __init__(
|
| 10 |
+
self,
|
| 11 |
+
bounds: tuple[float, float, float, float] | None = ...,
|
| 12 |
+
inset_ax: Axes | None = ...,
|
| 13 |
+
zorder: float | None = ...,
|
| 14 |
+
**kwargs
|
| 15 |
+
) -> None: ...
|
| 16 |
+
def set_alpha(self, alpha: float | None) -> None: ...
|
| 17 |
+
def set_edgecolor(self, color: ColorType | None) -> None: ...
|
| 18 |
+
def set_color(self, c: ColorType | None) -> None: ...
|
| 19 |
+
def set_linewidth(self, w: float | None) -> None: ...
|
| 20 |
+
def set_linestyle(self, ls: LineStyleType | None) -> None: ...
|
| 21 |
+
@property
|
| 22 |
+
def rectangle(self) -> Rectangle: ...
|
| 23 |
+
@property
|
| 24 |
+
def connectors(self) -> tuple[ConnectionPatch, ConnectionPatch, ConnectionPatch, ConnectionPatch] | None: ...
|
| 25 |
+
def draw(self, renderer: RendererBase) -> None: ...
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/offsetbox.pyi
ADDED
|
@@ -0,0 +1,298 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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: ...
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/patches.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/pylab.py
ADDED
|
@@ -0,0 +1,67 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
`pylab` is a historic interface and its use is strongly discouraged. The equivalent
|
| 3 |
+
replacement is `matplotlib.pyplot`. See :ref:`api_interfaces` for a full overview
|
| 4 |
+
of Matplotlib interfaces.
|
| 5 |
+
|
| 6 |
+
`pylab` was designed to support a MATLAB-like way of working with all plotting related
|
| 7 |
+
functions directly available in the global namespace. This was achieved through a
|
| 8 |
+
wildcard import (``from pylab import *``).
|
| 9 |
+
|
| 10 |
+
.. warning::
|
| 11 |
+
The use of `pylab` is discouraged for the following reasons:
|
| 12 |
+
|
| 13 |
+
``from pylab import *`` imports all the functions from `matplotlib.pyplot`, `numpy`,
|
| 14 |
+
`numpy.fft`, `numpy.linalg`, and `numpy.random`, and some additional functions into
|
| 15 |
+
the global namespace.
|
| 16 |
+
|
| 17 |
+
Such a pattern is considered bad practice in modern python, as it clutters the global
|
| 18 |
+
namespace. Even more severely, in the case of `pylab`, this will overwrite some
|
| 19 |
+
builtin functions (e.g. the builtin `sum` will be replaced by `numpy.sum`), which
|
| 20 |
+
can lead to unexpected behavior.
|
| 21 |
+
|
| 22 |
+
"""
|
| 23 |
+
|
| 24 |
+
from matplotlib.cbook import flatten, silent_list
|
| 25 |
+
|
| 26 |
+
import matplotlib as mpl
|
| 27 |
+
|
| 28 |
+
from matplotlib.dates import (
|
| 29 |
+
date2num, num2date, datestr2num, drange, DateFormatter, DateLocator,
|
| 30 |
+
RRuleLocator, YearLocator, MonthLocator, WeekdayLocator, DayLocator,
|
| 31 |
+
HourLocator, MinuteLocator, SecondLocator, rrule, MO, TU, WE, TH, FR,
|
| 32 |
+
SA, SU, YEARLY, MONTHLY, WEEKLY, DAILY, HOURLY, MINUTELY, SECONDLY,
|
| 33 |
+
relativedelta)
|
| 34 |
+
|
| 35 |
+
# bring all the symbols in so folks can import them from
|
| 36 |
+
# pylab in one fell swoop
|
| 37 |
+
|
| 38 |
+
## We are still importing too many things from mlab; more cleanup is needed.
|
| 39 |
+
|
| 40 |
+
from matplotlib.mlab import (
|
| 41 |
+
detrend, detrend_linear, detrend_mean, detrend_none, window_hanning,
|
| 42 |
+
window_none)
|
| 43 |
+
|
| 44 |
+
from matplotlib import cbook, mlab, pyplot as plt
|
| 45 |
+
from matplotlib.pyplot import *
|
| 46 |
+
|
| 47 |
+
from numpy import *
|
| 48 |
+
from numpy.fft import *
|
| 49 |
+
from numpy.random import *
|
| 50 |
+
from numpy.linalg import *
|
| 51 |
+
|
| 52 |
+
import numpy as np
|
| 53 |
+
import numpy.ma as ma
|
| 54 |
+
|
| 55 |
+
# don't let numpy's datetime hide stdlib
|
| 56 |
+
import datetime
|
| 57 |
+
|
| 58 |
+
# This is needed, or bytes will be numpy.random.bytes from
|
| 59 |
+
# "from numpy.random import *" above
|
| 60 |
+
bytes = __import__("builtins").bytes
|
| 61 |
+
# We also don't want the numpy version of these functions
|
| 62 |
+
abs = __import__("builtins").abs
|
| 63 |
+
bool = __import__("builtins").bool
|
| 64 |
+
max = __import__("builtins").max
|
| 65 |
+
min = __import__("builtins").min
|
| 66 |
+
pow = __import__("builtins").pow
|
| 67 |
+
round = __import__("builtins").round
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/texmanager.pyi
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from .backend_bases import RendererBase
|
| 2 |
+
|
| 3 |
+
from matplotlib.typing import ColorType
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
|
| 7 |
+
class TexManager:
|
| 8 |
+
texcache: str
|
| 9 |
+
@classmethod
|
| 10 |
+
def get_basefile(
|
| 11 |
+
cls, tex: str, fontsize: float, dpi: float | None = ...
|
| 12 |
+
) -> str: ...
|
| 13 |
+
@classmethod
|
| 14 |
+
def get_font_preamble(cls) -> str: ...
|
| 15 |
+
@classmethod
|
| 16 |
+
def get_custom_preamble(cls) -> str: ...
|
| 17 |
+
@classmethod
|
| 18 |
+
def make_tex(cls, tex: str, fontsize: float) -> str: ...
|
| 19 |
+
@classmethod
|
| 20 |
+
def make_dvi(cls, tex: str, fontsize: float) -> str: ...
|
| 21 |
+
@classmethod
|
| 22 |
+
def make_png(cls, tex: str, fontsize: float, dpi: float) -> str: ...
|
| 23 |
+
@classmethod
|
| 24 |
+
def get_grey(
|
| 25 |
+
cls, tex: str, fontsize: float | None = ..., dpi: float | None = ...
|
| 26 |
+
) -> np.ndarray: ...
|
| 27 |
+
@classmethod
|
| 28 |
+
def get_rgba(
|
| 29 |
+
cls,
|
| 30 |
+
tex: str,
|
| 31 |
+
fontsize: float | None = ...,
|
| 32 |
+
dpi: float | None = ...,
|
| 33 |
+
rgb: ColorType = ...,
|
| 34 |
+
) -> np.ndarray: ...
|
| 35 |
+
@classmethod
|
| 36 |
+
def get_text_width_height_descent(
|
| 37 |
+
cls, tex: str, fontsize, renderer: RendererBase | None = ...
|
| 38 |
+
) -> tuple[int, int, int]: ...
|
infer_4_37_2/lib/python3.10/site-packages/matplotlib/ticker.pyi
ADDED
|
@@ -0,0 +1,297 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from collections.abc import Callable, Sequence
|
| 2 |
+
from typing import Any, Literal
|
| 3 |
+
|
| 4 |
+
from matplotlib.axis import Axis
|
| 5 |
+
from matplotlib.transforms import Transform
|
| 6 |
+
from matplotlib.projections.polar import _AxisWrapper
|
| 7 |
+
|
| 8 |
+
import numpy as np
|
| 9 |
+
|
| 10 |
+
class _DummyAxis:
|
| 11 |
+
__name__: str
|
| 12 |
+
def __init__(self, minpos: float = ...) -> None: ...
|
| 13 |
+
def get_view_interval(self) -> tuple[float, float]: ...
|
| 14 |
+
def set_view_interval(self, vmin: float, vmax: float) -> None: ...
|
| 15 |
+
def get_minpos(self) -> float: ...
|
| 16 |
+
def get_data_interval(self) -> tuple[float, float]: ...
|
| 17 |
+
def set_data_interval(self, vmin: float, vmax: float) -> None: ...
|
| 18 |
+
def get_tick_space(self) -> int: ...
|
| 19 |
+
|
| 20 |
+
class TickHelper:
|
| 21 |
+
axis: None | Axis | _DummyAxis | _AxisWrapper
|
| 22 |
+
def set_axis(self, axis: Axis | _DummyAxis | _AxisWrapper | None) -> None: ...
|
| 23 |
+
def create_dummy_axis(self, **kwargs) -> None: ...
|
| 24 |
+
|
| 25 |
+
class Formatter(TickHelper):
|
| 26 |
+
locs: list[float]
|
| 27 |
+
def __call__(self, x: float, pos: int | None = ...) -> str: ...
|
| 28 |
+
def format_ticks(self, values: list[float]) -> list[str]: ...
|
| 29 |
+
def format_data(self, value: float) -> str: ...
|
| 30 |
+
def format_data_short(self, value: float) -> str: ...
|
| 31 |
+
def get_offset(self) -> str: ...
|
| 32 |
+
def set_locs(self, locs: list[float]) -> None: ...
|
| 33 |
+
@staticmethod
|
| 34 |
+
def fix_minus(s: str) -> str: ...
|
| 35 |
+
|
| 36 |
+
class NullFormatter(Formatter): ...
|
| 37 |
+
|
| 38 |
+
class FixedFormatter(Formatter):
|
| 39 |
+
seq: Sequence[str]
|
| 40 |
+
offset_string: str
|
| 41 |
+
def __init__(self, seq: Sequence[str]) -> None: ...
|
| 42 |
+
def set_offset_string(self, ofs: str) -> None: ...
|
| 43 |
+
|
| 44 |
+
class FuncFormatter(Formatter):
|
| 45 |
+
func: Callable[[float, int | None], str]
|
| 46 |
+
offset_string: str
|
| 47 |
+
# Callable[[float, int | None], str] | Callable[[float], str]
|
| 48 |
+
def __init__(self, func: Callable[..., str]) -> None: ...
|
| 49 |
+
def set_offset_string(self, ofs: str) -> None: ...
|
| 50 |
+
|
| 51 |
+
class FormatStrFormatter(Formatter):
|
| 52 |
+
fmt: str
|
| 53 |
+
def __init__(self, fmt: str) -> None: ...
|
| 54 |
+
|
| 55 |
+
class StrMethodFormatter(Formatter):
|
| 56 |
+
fmt: str
|
| 57 |
+
def __init__(self, fmt: str) -> None: ...
|
| 58 |
+
|
| 59 |
+
class ScalarFormatter(Formatter):
|
| 60 |
+
orderOfMagnitude: int
|
| 61 |
+
format: str
|
| 62 |
+
def __init__(
|
| 63 |
+
self,
|
| 64 |
+
useOffset: bool | float | None = ...,
|
| 65 |
+
useMathText: bool | None = ...,
|
| 66 |
+
useLocale: bool | None = ...,
|
| 67 |
+
*,
|
| 68 |
+
usetex: bool | None = ...,
|
| 69 |
+
) -> None: ...
|
| 70 |
+
offset: float
|
| 71 |
+
def get_usetex(self) -> bool: ...
|
| 72 |
+
def set_usetex(self, val: bool) -> None: ...
|
| 73 |
+
@property
|
| 74 |
+
def usetex(self) -> bool: ...
|
| 75 |
+
@usetex.setter
|
| 76 |
+
def usetex(self, val: bool) -> None: ...
|
| 77 |
+
def get_useOffset(self) -> bool: ...
|
| 78 |
+
def set_useOffset(self, val: bool | float) -> None: ...
|
| 79 |
+
@property
|
| 80 |
+
def useOffset(self) -> bool: ...
|
| 81 |
+
@useOffset.setter
|
| 82 |
+
def useOffset(self, val: bool | float) -> None: ...
|
| 83 |
+
def get_useLocale(self) -> bool: ...
|
| 84 |
+
def set_useLocale(self, val: bool | None) -> None: ...
|
| 85 |
+
@property
|
| 86 |
+
def useLocale(self) -> bool: ...
|
| 87 |
+
@useLocale.setter
|
| 88 |
+
def useLocale(self, val: bool | None) -> None: ...
|
| 89 |
+
def get_useMathText(self) -> bool: ...
|
| 90 |
+
def set_useMathText(self, val: bool | None) -> None: ...
|
| 91 |
+
@property
|
| 92 |
+
def useMathText(self) -> bool: ...
|
| 93 |
+
@useMathText.setter
|
| 94 |
+
def useMathText(self, val: bool | None) -> None: ...
|
| 95 |
+
def set_scientific(self, b: bool) -> None: ...
|
| 96 |
+
def set_powerlimits(self, lims: tuple[int, int]) -> None: ...
|
| 97 |
+
def format_data_short(self, value: float | np.ma.MaskedArray) -> str: ...
|
| 98 |
+
def format_data(self, value: float) -> str: ...
|
| 99 |
+
|
| 100 |
+
class LogFormatter(Formatter):
|
| 101 |
+
minor_thresholds: tuple[float, float]
|
| 102 |
+
def __init__(
|
| 103 |
+
self,
|
| 104 |
+
base: float = ...,
|
| 105 |
+
labelOnlyBase: bool = ...,
|
| 106 |
+
minor_thresholds: tuple[float, float] | None = ...,
|
| 107 |
+
linthresh: float | None = ...,
|
| 108 |
+
) -> None: ...
|
| 109 |
+
def set_base(self, base: float) -> None: ...
|
| 110 |
+
labelOnlyBase: bool
|
| 111 |
+
def set_label_minor(self, labelOnlyBase: bool) -> None: ...
|
| 112 |
+
def set_locs(self, locs: Any | None = ...) -> None: ...
|
| 113 |
+
def format_data(self, value: float) -> str: ...
|
| 114 |
+
def format_data_short(self, value: float) -> str: ...
|
| 115 |
+
|
| 116 |
+
class LogFormatterExponent(LogFormatter): ...
|
| 117 |
+
class LogFormatterMathtext(LogFormatter): ...
|
| 118 |
+
class LogFormatterSciNotation(LogFormatterMathtext): ...
|
| 119 |
+
|
| 120 |
+
class LogitFormatter(Formatter):
|
| 121 |
+
def __init__(
|
| 122 |
+
self,
|
| 123 |
+
*,
|
| 124 |
+
use_overline: bool = ...,
|
| 125 |
+
one_half: str = ...,
|
| 126 |
+
minor: bool = ...,
|
| 127 |
+
minor_threshold: int = ...,
|
| 128 |
+
minor_number: int = ...
|
| 129 |
+
) -> None: ...
|
| 130 |
+
def use_overline(self, use_overline: bool) -> None: ...
|
| 131 |
+
def set_one_half(self, one_half: str) -> None: ...
|
| 132 |
+
def set_minor_threshold(self, minor_threshold: int) -> None: ...
|
| 133 |
+
def set_minor_number(self, minor_number: int) -> None: ...
|
| 134 |
+
def format_data_short(self, value: float) -> str: ...
|
| 135 |
+
|
| 136 |
+
class EngFormatter(ScalarFormatter):
|
| 137 |
+
ENG_PREFIXES: dict[int, str]
|
| 138 |
+
unit: str
|
| 139 |
+
places: int | None
|
| 140 |
+
sep: str
|
| 141 |
+
def __init__(
|
| 142 |
+
self,
|
| 143 |
+
unit: str = ...,
|
| 144 |
+
places: int | None = ...,
|
| 145 |
+
sep: str = ...,
|
| 146 |
+
*,
|
| 147 |
+
usetex: bool | None = ...,
|
| 148 |
+
useMathText: bool | None = ...,
|
| 149 |
+
useOffset: bool | float | None = ...,
|
| 150 |
+
) -> None: ...
|
| 151 |
+
def format_eng(self, num: float) -> str: ...
|
| 152 |
+
|
| 153 |
+
class PercentFormatter(Formatter):
|
| 154 |
+
xmax: float
|
| 155 |
+
decimals: int | None
|
| 156 |
+
def __init__(
|
| 157 |
+
self,
|
| 158 |
+
xmax: float = ...,
|
| 159 |
+
decimals: int | None = ...,
|
| 160 |
+
symbol: str | None = ...,
|
| 161 |
+
is_latex: bool = ...,
|
| 162 |
+
) -> None: ...
|
| 163 |
+
def format_pct(self, x: float, display_range: float) -> str: ...
|
| 164 |
+
def convert_to_pct(self, x: float) -> float: ...
|
| 165 |
+
@property
|
| 166 |
+
def symbol(self) -> str: ...
|
| 167 |
+
@symbol.setter
|
| 168 |
+
def symbol(self, symbol: str) -> None: ...
|
| 169 |
+
|
| 170 |
+
class Locator(TickHelper):
|
| 171 |
+
MAXTICKS: int
|
| 172 |
+
def tick_values(self, vmin: float, vmax: float) -> Sequence[float]: ...
|
| 173 |
+
# Implementation accepts **kwargs, but is a no-op other than a warning
|
| 174 |
+
# Typing as **kwargs would require each subclass to accept **kwargs for mypy
|
| 175 |
+
def set_params(self) -> None: ...
|
| 176 |
+
def __call__(self) -> Sequence[float]: ...
|
| 177 |
+
def raise_if_exceeds(self, locs: Sequence[float]) -> Sequence[float]: ...
|
| 178 |
+
def nonsingular(self, v0: float, v1: float) -> tuple[float, float]: ...
|
| 179 |
+
def view_limits(self, vmin: float, vmax: float) -> tuple[float, float]: ...
|
| 180 |
+
|
| 181 |
+
class IndexLocator(Locator):
|
| 182 |
+
offset: float
|
| 183 |
+
def __init__(self, base: float, offset: float) -> None: ...
|
| 184 |
+
def set_params(
|
| 185 |
+
self, base: float | None = ..., offset: float | None = ...
|
| 186 |
+
) -> None: ...
|
| 187 |
+
|
| 188 |
+
class FixedLocator(Locator):
|
| 189 |
+
nbins: int | None
|
| 190 |
+
def __init__(self, locs: Sequence[float], nbins: int | None = ...) -> None: ...
|
| 191 |
+
def set_params(self, nbins: int | None = ...) -> None: ...
|
| 192 |
+
|
| 193 |
+
class NullLocator(Locator): ...
|
| 194 |
+
|
| 195 |
+
class LinearLocator(Locator):
|
| 196 |
+
presets: dict[tuple[float, float], Sequence[float]]
|
| 197 |
+
def __init__(
|
| 198 |
+
self,
|
| 199 |
+
numticks: int | None = ...,
|
| 200 |
+
presets: dict[tuple[float, float], Sequence[float]] | None = ...,
|
| 201 |
+
) -> None: ...
|
| 202 |
+
@property
|
| 203 |
+
def numticks(self) -> int: ...
|
| 204 |
+
@numticks.setter
|
| 205 |
+
def numticks(self, numticks: int | None) -> None: ...
|
| 206 |
+
def set_params(
|
| 207 |
+
self,
|
| 208 |
+
numticks: int | None = ...,
|
| 209 |
+
presets: dict[tuple[float, float], Sequence[float]] | None = ...,
|
| 210 |
+
) -> None: ...
|
| 211 |
+
|
| 212 |
+
class MultipleLocator(Locator):
|
| 213 |
+
def __init__(self, base: float = ..., offset: float = ...) -> None: ...
|
| 214 |
+
def set_params(self, base: float | None = ..., offset: float | None = ...) -> None: ...
|
| 215 |
+
def view_limits(self, dmin: float, dmax: float) -> tuple[float, float]: ...
|
| 216 |
+
|
| 217 |
+
class _Edge_integer:
|
| 218 |
+
step: float
|
| 219 |
+
def __init__(self, step: float, offset: float) -> None: ...
|
| 220 |
+
def closeto(self, ms: float, edge: float) -> bool: ...
|
| 221 |
+
def le(self, x: float) -> float: ...
|
| 222 |
+
def ge(self, x: float) -> float: ...
|
| 223 |
+
|
| 224 |
+
class MaxNLocator(Locator):
|
| 225 |
+
default_params: dict[str, Any]
|
| 226 |
+
def __init__(self, nbins: int | Literal["auto"] | None = ..., **kwargs) -> None: ...
|
| 227 |
+
def set_params(self, **kwargs) -> None: ...
|
| 228 |
+
def view_limits(self, dmin: float, dmax: float) -> tuple[float, float]: ...
|
| 229 |
+
|
| 230 |
+
class LogLocator(Locator):
|
| 231 |
+
numticks: int | None
|
| 232 |
+
def __init__(
|
| 233 |
+
self,
|
| 234 |
+
base: float = ...,
|
| 235 |
+
subs: None | Literal["auto", "all"] | Sequence[float] = ...,
|
| 236 |
+
*,
|
| 237 |
+
numticks: int | None = ...,
|
| 238 |
+
) -> None: ...
|
| 239 |
+
def set_params(
|
| 240 |
+
self,
|
| 241 |
+
base: float | None = ...,
|
| 242 |
+
subs: Literal["auto", "all"] | Sequence[float] | None = ...,
|
| 243 |
+
*,
|
| 244 |
+
numticks: int | None = ...,
|
| 245 |
+
) -> None: ...
|
| 246 |
+
|
| 247 |
+
class SymmetricalLogLocator(Locator):
|
| 248 |
+
numticks: int
|
| 249 |
+
def __init__(
|
| 250 |
+
self,
|
| 251 |
+
transform: Transform | None = ...,
|
| 252 |
+
subs: Sequence[float] | None = ...,
|
| 253 |
+
linthresh: float | None = ...,
|
| 254 |
+
base: float | None = ...,
|
| 255 |
+
) -> None: ...
|
| 256 |
+
def set_params(
|
| 257 |
+
self, subs: Sequence[float] | None = ..., numticks: int | None = ...
|
| 258 |
+
) -> None: ...
|
| 259 |
+
|
| 260 |
+
class AsinhLocator(Locator):
|
| 261 |
+
linear_width: float
|
| 262 |
+
numticks: int
|
| 263 |
+
symthresh: float
|
| 264 |
+
base: int
|
| 265 |
+
subs: Sequence[float] | None
|
| 266 |
+
def __init__(
|
| 267 |
+
self,
|
| 268 |
+
linear_width: float,
|
| 269 |
+
numticks: int = ...,
|
| 270 |
+
symthresh: float = ...,
|
| 271 |
+
base: int = ...,
|
| 272 |
+
subs: Sequence[float] | None = ...,
|
| 273 |
+
) -> None: ...
|
| 274 |
+
def set_params(
|
| 275 |
+
self,
|
| 276 |
+
numticks: int | None = ...,
|
| 277 |
+
symthresh: float | None = ...,
|
| 278 |
+
base: int | None = ...,
|
| 279 |
+
subs: Sequence[float] | None = ...,
|
| 280 |
+
) -> None: ...
|
| 281 |
+
|
| 282 |
+
class LogitLocator(MaxNLocator):
|
| 283 |
+
def __init__(
|
| 284 |
+
self, minor: bool = ..., *, nbins: Literal["auto"] | int = ...
|
| 285 |
+
) -> None: ...
|
| 286 |
+
def set_params(self, minor: bool | None = ..., **kwargs) -> None: ...
|
| 287 |
+
@property
|
| 288 |
+
def minor(self) -> bool: ...
|
| 289 |
+
@minor.setter
|
| 290 |
+
def minor(self, value: bool) -> None: ...
|
| 291 |
+
|
| 292 |
+
class AutoLocator(MaxNLocator):
|
| 293 |
+
def __init__(self) -> None: ...
|
| 294 |
+
|
| 295 |
+
class AutoMinorLocator(Locator):
|
| 296 |
+
ndivs: int
|
| 297 |
+
def __init__(self, n: int | None = ...) -> None: ...
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/__init__.cpython-310.pyc
ADDED
|
Binary file (153 Bytes). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_find_distributions.cpython-310.pyc
ADDED
|
Binary file (2.35 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_integration_zope_interface.cpython-310.pyc
ADDED
|
Binary file (1.56 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_resources.cpython-310.pyc
ADDED
|
Binary file (28.2 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/__pycache__/test_working_set.cpython-310.pyc
ADDED
|
Binary file (8.41 kB). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/__pycache__/setup.cpython-310.pyc
ADDED
|
Binary file (283 Bytes). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.cfg
ADDED
|
File without changes
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-source/setup.py
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import setuptools
|
| 2 |
+
|
| 3 |
+
setuptools.setup(
|
| 4 |
+
name="my-test-package",
|
| 5 |
+
version="1.0",
|
| 6 |
+
zip_safe=True,
|
| 7 |
+
)
|
infer_4_37_2/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
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/SOURCES.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
setup.cfg
|
| 2 |
+
setup.py
|
| 3 |
+
my_test_package.egg-info/PKG-INFO
|
| 4 |
+
my_test_package.egg-info/SOURCES.txt
|
| 5 |
+
my_test_package.egg-info/dependency_links.txt
|
| 6 |
+
my_test_package.egg-info/top_level.txt
|
| 7 |
+
my_test_package.egg-info/zip-safe
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/dependency_links.txt
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
infer_4_37_2/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 |
+
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_unpacked-egg/my_test_package-1.0-py3.7.egg/EGG-INFO/zip-safe
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package_zipped-egg/my_test_package-1.0-py3.7.egg
ADDED
|
Binary file (843 Bytes). View file
|
|
|
infer_4_37_2/lib/python3.10/site-packages/pkg_resources/tests/test_working_set.py
ADDED
|
@@ -0,0 +1,501 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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)
|
infer_4_37_2/lib/python3.10/site-packages/prometheus_client-0.21.1.dist-info/INSTALLER
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
pip
|
infer_4_37_2/lib/python3.10/site-packages/prometheus_client-0.21.1.dist-info/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
Version 2.0, January 2004
|
| 3 |
+
http://www.apache.org/licenses/
|
| 4 |
+
|
| 5 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 6 |
+
|
| 7 |
+
1. Definitions.
|
| 8 |
+
|
| 9 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 10 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 11 |
+
|
| 12 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 13 |
+
the copyright owner that is granting the License.
|
| 14 |
+
|
| 15 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 16 |
+
other entities that control, are controlled by, or are under common
|
| 17 |
+
control with that entity. For the purposes of this definition,
|
| 18 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 19 |
+
direction or management of such entity, whether by contract or
|
| 20 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 21 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 22 |
+
|
| 23 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 24 |
+
exercising permissions granted by this License.
|
| 25 |
+
|
| 26 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 27 |
+
including but not limited to software source code, documentation
|
| 28 |
+
source, and configuration files.
|
| 29 |
+
|
| 30 |
+
"Object" form shall mean any form resulting from mechanical
|
| 31 |
+
transformation or translation of a Source form, including but
|
| 32 |
+
not limited to compiled object code, generated documentation,
|
| 33 |
+
and conversions to other media types.
|
| 34 |
+
|
| 35 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 36 |
+
Object form, made available under the License, as indicated by a
|
| 37 |
+
copyright notice that is included in or attached to the work
|
| 38 |
+
(an example is provided in the Appendix below).
|
| 39 |
+
|
| 40 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 41 |
+
form, that is based on (or derived from) the Work and for which the
|
| 42 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 43 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 44 |
+
of this License, Derivative Works shall not include works that remain
|
| 45 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 46 |
+
the Work and Derivative Works thereof.
|
| 47 |
+
|
| 48 |
+
"Contribution" shall mean any work of authorship, including
|
| 49 |
+
the original version of the Work and any modifications or additions
|
| 50 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 51 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 52 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 53 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 54 |
+
means any form of electronic, verbal, or written communication sent
|
| 55 |
+
to the Licensor or its representatives, including but not limited to
|
| 56 |
+
communication on electronic mailing lists, source code control systems,
|
| 57 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 58 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 59 |
+
excluding communication that is conspicuously marked or otherwise
|
| 60 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 61 |
+
|
| 62 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 63 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 64 |
+
subsequently incorporated within the Work.
|
| 65 |
+
|
| 66 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 67 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 68 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 69 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 70 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 71 |
+
Work and such Derivative Works in Source or Object form.
|
| 72 |
+
|
| 73 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 74 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 75 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 76 |
+
(except as stated in this section) patent license to make, have made,
|
| 77 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 78 |
+
where such license applies only to those patent claims licensable
|
| 79 |
+
by such Contributor that are necessarily infringed by their
|
| 80 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 81 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 82 |
+
institute patent litigation against any entity (including a
|
| 83 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 84 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 85 |
+
or contributory patent infringement, then any patent licenses
|
| 86 |
+
granted to You under this License for that Work shall terminate
|
| 87 |
+
as of the date such litigation is filed.
|
| 88 |
+
|
| 89 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 90 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 91 |
+
modifications, and in Source or Object form, provided that You
|
| 92 |
+
meet the following conditions:
|
| 93 |
+
|
| 94 |
+
(a) You must give any other recipients of the Work or
|
| 95 |
+
Derivative Works a copy of this License; and
|
| 96 |
+
|
| 97 |
+
(b) You must cause any modified files to carry prominent notices
|
| 98 |
+
stating that You changed the files; and
|
| 99 |
+
|
| 100 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 101 |
+
that You distribute, all copyright, patent, trademark, and
|
| 102 |
+
attribution notices from the Source form of the Work,
|
| 103 |
+
excluding those notices that do not pertain to any part of
|
| 104 |
+
the Derivative Works; and
|
| 105 |
+
|
| 106 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 107 |
+
distribution, then any Derivative Works that You distribute must
|
| 108 |
+
include a readable copy of the attribution notices contained
|
| 109 |
+
within such NOTICE file, excluding those notices that do not
|
| 110 |
+
pertain to any part of the Derivative Works, in at least one
|
| 111 |
+
of the following places: within a NOTICE text file distributed
|
| 112 |
+
as part of the Derivative Works; within the Source form or
|
| 113 |
+
documentation, if provided along with the Derivative Works; or,
|
| 114 |
+
within a display generated by the Derivative Works, if and
|
| 115 |
+
wherever such third-party notices normally appear. The contents
|
| 116 |
+
of the NOTICE file are for informational purposes only and
|
| 117 |
+
do not modify the License. You may add Your own attribution
|
| 118 |
+
notices within Derivative Works that You distribute, alongside
|
| 119 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 120 |
+
that such additional attribution notices cannot be construed
|
| 121 |
+
as modifying the License.
|
| 122 |
+
|
| 123 |
+
You may add Your own copyright statement to Your modifications and
|
| 124 |
+
may provide additional or different license terms and conditions
|
| 125 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 126 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 127 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 128 |
+
the conditions stated in this License.
|
| 129 |
+
|
| 130 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 131 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 132 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 133 |
+
this License, without any additional terms or conditions.
|
| 134 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 135 |
+
the terms of any separate license agreement you may have executed
|
| 136 |
+
with Licensor regarding such Contributions.
|
| 137 |
+
|
| 138 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 139 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 140 |
+
except as required for reasonable and customary use in describing the
|
| 141 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 142 |
+
|
| 143 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 144 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 145 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 146 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 147 |
+
implied, including, without limitation, any warranties or conditions
|
| 148 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 149 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 150 |
+
appropriateness of using or redistributing the Work and assume any
|
| 151 |
+
risks associated with Your exercise of permissions under this License.
|
| 152 |
+
|
| 153 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 154 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 155 |
+
unless required by applicable law (such as deliberate and grossly
|
| 156 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 157 |
+
liable to You for damages, including any direct, indirect, special,
|
| 158 |
+
incidental, or consequential damages of any character arising as a
|
| 159 |
+
result of this License or out of the use or inability to use the
|
| 160 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 161 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 162 |
+
other commercial damages or losses), even if such Contributor
|
| 163 |
+
has been advised of the possibility of such damages.
|
| 164 |
+
|
| 165 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 166 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 167 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 168 |
+
or other liability obligations and/or rights consistent with this
|
| 169 |
+
License. However, in accepting such obligations, You may act only
|
| 170 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 171 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 172 |
+
defend, and hold each Contributor harmless for any liability
|
| 173 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 174 |
+
of your accepting any such warranty or additional liability.
|
| 175 |
+
|
| 176 |
+
END OF TERMS AND CONDITIONS
|
| 177 |
+
|
| 178 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 179 |
+
|
| 180 |
+
To apply the Apache License to your work, attach the following
|
| 181 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 182 |
+
replaced with your own identifying information. (Don't include
|
| 183 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 184 |
+
comment syntax for the file format. We also recommend that a
|
| 185 |
+
file or class name and description of purpose be included on the
|
| 186 |
+
same "printed page" as the copyright notice for easier
|
| 187 |
+
identification within third-party archives.
|
| 188 |
+
|
| 189 |
+
Copyright [yyyy] [name of copyright owner]
|
| 190 |
+
|
| 191 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 192 |
+
you may not use this file except in compliance with the License.
|
| 193 |
+
You may obtain a copy of the License at
|
| 194 |
+
|
| 195 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 196 |
+
|
| 197 |
+
Unless required by applicable law or agreed to in writing, software
|
| 198 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 199 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 200 |
+
See the License for the specific language governing permissions and
|
| 201 |
+
limitations under the License.
|