matplotlib-rs 0.0.8__cp315-cp315-win_amd64.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- docs/releases/0.0.1.md +268 -0
- docs/releases/0.0.2.md +69 -0
- docs/releases/0.0.3.md +80 -0
- docs/releases/0.0.4.md +73 -0
- docs/releases/0.0.5.md +24 -0
- docs/releases/0.0.6.md +24 -0
- docs/releases/0.0.7.md +24 -0
- docs/releases/0.0.8.md +16 -0
- licenses/LICENSE_CONTOURPY +29 -0
- licenses/LICENSE_CYCLER +27 -0
- licenses/LICENSE_DATEUTIL +54 -0
- licenses/LICENSE_KIWISOLVER +71 -0
- licenses/LICENSE_LIBWEBP +56 -0
- licenses/LICENSE_MATPLOTLIB +1253 -0
- licenses/LICENSE_PYPARSING +20 -0
- licenses/LICENSE_QHULL +39 -0
- licenses/LICENSE_SIX +18 -0
- matplotlib_rs/__init__.py +1683 -0
- matplotlib_rs/__main__.py +27 -0
- matplotlib_rs/_afm.py +500 -0
- matplotlib_rs/_animation_data.py +263 -0
- matplotlib_rs/_api/__init__.py +495 -0
- matplotlib_rs/_api/deprecation.py +534 -0
- matplotlib_rs/_axis_py.py +2991 -0
- matplotlib_rs/_blocking_input.py +31 -0
- matplotlib_rs/_cm.py +1500 -0
- matplotlib_rs/_cm_bivar.py +1289 -0
- matplotlib_rs/_cm_listed.py +2848 -0
- matplotlib_rs/_cm_multivar.py +167 -0
- matplotlib_rs/_color_data.py +1142 -0
- matplotlib_rs/_colormap.py +132 -0
- matplotlib_rs/_constrained_layout.py +825 -0
- matplotlib_rs/_contour.py +108 -0
- matplotlib_rs/_doc_cache.py +12214 -0
- matplotlib_rs/_docstring.py +142 -0
- matplotlib_rs/_enums.py +178 -0
- matplotlib_rs/_figure_rs.py +294 -0
- matplotlib_rs/_fontconfig_pattern.py +129 -0
- matplotlib_rs/_foreign.py +220 -0
- matplotlib_rs/_hook.py +94 -0
- matplotlib_rs/_image.py +160 -0
- matplotlib_rs/_imageio.py +229 -0
- matplotlib_rs/_internal_utils.py +65 -0
- matplotlib_rs/_kiwi.py +484 -0
- matplotlib_rs/_layoutgrid.py +549 -0
- matplotlib_rs/_live.py +192 -0
- matplotlib_rs/_mathtext.py +3103 -0
- matplotlib_rs/_mathtext_data.py +1811 -0
- matplotlib_rs/_mplrs.cp315-win_amd64.pyd +0 -0
- matplotlib_rs/_path.py +25 -0
- matplotlib_rs/_png.py +162 -0
- matplotlib_rs/_pylab_helpers.py +137 -0
- matplotlib_rs/_qhull.py +66 -0
- matplotlib_rs/_rcpush.py +84 -0
- matplotlib_rs/_spines_rs.py +108 -0
- matplotlib_rs/_style_helpers.py +52 -0
- matplotlib_rs/_text_helpers.py +51 -0
- matplotlib_rs/_tight_bbox.py +85 -0
- matplotlib_rs/_tight_layout.py +302 -0
- matplotlib_rs/_tri.py +140 -0
- matplotlib_rs/_type1font.py +1228 -0
- matplotlib_rs/_vendor/__init__.py +8 -0
- matplotlib_rs/_vendor/cycler.py +574 -0
- matplotlib_rs/_vendor/dateutil/__init__.py +27 -0
- matplotlib_rs/_vendor/dateutil/_common.py +44 -0
- matplotlib_rs/_vendor/dateutil/_tzdata_impl.py +148 -0
- matplotlib_rs/_vendor/dateutil/_version.py +5 -0
- matplotlib_rs/_vendor/dateutil/easter.py +90 -0
- matplotlib_rs/_vendor/dateutil/parser/__init__.py +62 -0
- matplotlib_rs/_vendor/dateutil/parser/_parser.py +1614 -0
- matplotlib_rs/_vendor/dateutil/parser/isoparser.py +417 -0
- matplotlib_rs/_vendor/dateutil/relativedelta.py +597 -0
- matplotlib_rs/_vendor/dateutil/rrule.py +1765 -0
- matplotlib_rs/_vendor/dateutil/tz/__init__.py +61 -0
- matplotlib_rs/_vendor/dateutil/tz/_common.py +420 -0
- matplotlib_rs/_vendor/dateutil/tz/_factories.py +81 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzfile.py +1429 -0
- matplotlib_rs/_vendor/dateutil/tz/_tzpath.py +105 -0
- matplotlib_rs/_vendor/dateutil/tz/tz.py +1473 -0
- matplotlib_rs/_vendor/dateutil/tz/win.py +371 -0
- matplotlib_rs/_vendor/dateutil/tzwin.py +3 -0
- matplotlib_rs/_vendor/dateutil/utils.py +72 -0
- matplotlib_rs/_vendor/dateutil/zoneinfo/__init__.py +234 -0
- matplotlib_rs/_vendor/pyparsing/__init__.py +414 -0
- matplotlib_rs/_vendor/pyparsing/actions.py +265 -0
- matplotlib_rs/_vendor/pyparsing/common.py +571 -0
- matplotlib_rs/_vendor/pyparsing/core.py +6973 -0
- matplotlib_rs/_vendor/pyparsing/exceptions.py +354 -0
- matplotlib_rs/_vendor/pyparsing/helpers.py +1770 -0
- matplotlib_rs/_vendor/pyparsing/results.py +929 -0
- matplotlib_rs/_vendor/pyparsing/testing.py +399 -0
- matplotlib_rs/_vendor/pyparsing/unicode.py +357 -0
- matplotlib_rs/_vendor/pyparsing/util.py +515 -0
- matplotlib_rs/_vendor/pyparsing/warnings.py +11 -0
- matplotlib_rs/_vendor/six.py +1004 -0
- matplotlib_rs/animation.py +1843 -0
- matplotlib_rs/artist.py +2302 -0
- matplotlib_rs/axes/__init__.py +19 -0
- matplotlib_rs/axes/_axes.py +9402 -0
- matplotlib_rs/axes/_bar.py +185 -0
- matplotlib_rs/axes/_base.py +5236 -0
- matplotlib_rs/axes/_base_rs.py +727 -0
- matplotlib_rs/axes/_boxplot.py +391 -0
- matplotlib_rs/axes/_hist.py +99 -0
- matplotlib_rs/axes/_secondary_axes.py +357 -0
- matplotlib_rs/axis.py +1963 -0
- matplotlib_rs/backend_bases.py +3760 -0
- matplotlib_rs/backend_managers.py +388 -0
- matplotlib_rs/backend_tools.py +1002 -0
- matplotlib_rs/backends/__init__.py +6 -0
- matplotlib_rs/backends/_backend_pdf_ps.py +451 -0
- matplotlib_rs/backends/backend_agg.py +552 -0
- matplotlib_rs/backends/backend_mixed.py +123 -0
- matplotlib_rs/backends/backend_pdf.py +2711 -0
- matplotlib_rs/backends/backend_pgf.py +1031 -0
- matplotlib_rs/backends/backend_ps.py +1491 -0
- matplotlib_rs/backends/backend_svg.py +1395 -0
- matplotlib_rs/backends/backend_template.py +214 -0
- matplotlib_rs/backends/registry.py +423 -0
- matplotlib_rs/bezier.py +691 -0
- matplotlib_rs/category.py +236 -0
- matplotlib_rs/cbook.py +2762 -0
- matplotlib_rs/cm.py +251 -0
- matplotlib_rs/collections.py +2711 -0
- matplotlib_rs/colorbar.py +1586 -0
- matplotlib_rs/colorizer.py +909 -0
- matplotlib_rs/colors.py +4278 -0
- matplotlib_rs/container.py +256 -0
- matplotlib_rs/contour.py +1756 -0
- matplotlib_rs/dates.py +1847 -0
- matplotlib_rs/dviread.py +1386 -0
- matplotlib_rs/figure.py +3815 -0
- matplotlib_rs/font_manager.py +1855 -0
- matplotlib_rs/ft2font.py +515 -0
- matplotlib_rs/gridspec.py +808 -0
- matplotlib_rs/hatch.py +244 -0
- matplotlib_rs/image.py +1863 -0
- matplotlib_rs/inset.py +291 -0
- matplotlib_rs/layout_engine.py +310 -0
- matplotlib_rs/legend.py +1480 -0
- matplotlib_rs/legend_handler.py +812 -0
- matplotlib_rs/lines.py +1886 -0
- matplotlib_rs/markers.py +908 -0
- matplotlib_rs/mathtext.py +141 -0
- matplotlib_rs/mlab.py +959 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSans.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-BoldOblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono-Oblique.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSansMono.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Bold.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-BoldItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif-Italic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerif.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/DejaVuSerifDisplay.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_DEJAVU +99 -0
- matplotlib_rs/mpl-data/fonts/ttf/LICENSE_STIX +124 -0
- matplotlib_rs/mpl-data/fonts/ttf/LastResortHE-Regular.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneral.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXGeneralItalic.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUni.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniBolIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXNonUniIta.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFiveSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizFourSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizOneSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizThreeSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymBol.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/STIXSizTwoSymReg.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmb10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmex10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmmi10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmr10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmss10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmsy10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmti10.ttf +0 -0
- matplotlib_rs/mpl-data/fonts/ttf/cmtt10.ttf +0 -0
- matplotlib_rs/mpl-data/images/back-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/back.pdf +0 -0
- matplotlib_rs/mpl-data/images/back.png +0 -0
- matplotlib_rs/mpl-data/images/back.svg +46 -0
- matplotlib_rs/mpl-data/images/back_large.png +0 -0
- matplotlib_rs/mpl-data/images/filesave-symbolic.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave.pdf +72 -0
- matplotlib_rs/mpl-data/images/filesave.png +0 -0
- matplotlib_rs/mpl-data/images/filesave.svg +68 -0
- matplotlib_rs/mpl-data/images/filesave_large.png +0 -0
- matplotlib_rs/mpl-data/images/forward-symbolic.svg +46 -0
- matplotlib_rs/mpl-data/images/forward.pdf +0 -0
- matplotlib_rs/mpl-data/images/forward.png +0 -0
- matplotlib_rs/mpl-data/images/forward.svg +46 -0
- matplotlib_rs/mpl-data/images/forward_large.png +0 -0
- matplotlib_rs/mpl-data/images/hand.pdf +0 -0
- matplotlib_rs/mpl-data/images/hand.png +0 -0
- matplotlib_rs/mpl-data/images/hand.svg +130 -0
- matplotlib_rs/mpl-data/images/help-symbolic.svg +52 -0
- matplotlib_rs/mpl-data/images/help.pdf +71 -0
- matplotlib_rs/mpl-data/images/help.png +0 -0
- matplotlib_rs/mpl-data/images/help.svg +52 -0
- matplotlib_rs/mpl-data/images/help_large.png +0 -0
- matplotlib_rs/mpl-data/images/home-symbolic.svg +59 -0
- matplotlib_rs/mpl-data/images/home.pdf +0 -0
- matplotlib_rs/mpl-data/images/home.png +0 -0
- matplotlib_rs/mpl-data/images/home.svg +59 -0
- matplotlib_rs/mpl-data/images/home_large.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.pdf +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.png +0 -0
- matplotlib_rs/mpl-data/images/matplotlib.svg +3171 -0
- matplotlib_rs/mpl-data/images/matplotlib_large.png +0 -0
- matplotlib_rs/mpl-data/images/move-symbolic.svg +73 -0
- matplotlib_rs/mpl-data/images/move.pdf +0 -0
- matplotlib_rs/mpl-data/images/move.png +0 -0
- matplotlib_rs/mpl-data/images/move.svg +73 -0
- matplotlib_rs/mpl-data/images/move_large.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.pdf +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.png +0 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options.svg +48 -0
- matplotlib_rs/mpl-data/images/qt4_editor_options_large.png +0 -0
- matplotlib_rs/mpl-data/images/subplots-symbolic.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots.pdf +0 -0
- matplotlib_rs/mpl-data/images/subplots.png +0 -0
- matplotlib_rs/mpl-data/images/subplots.svg +81 -0
- matplotlib_rs/mpl-data/images/subplots_large.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect-symbolic.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.pdf +69 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.png +0 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect.svg +40 -0
- matplotlib_rs/mpl-data/images/zoom_to_rect_large.png +0 -0
- matplotlib_rs/mpl-data/kpsewhich.lua +4 -0
- matplotlib_rs/mpl-data/matplotlibrc +849 -0
- matplotlib_rs/mpl-data/plot_directive/plot_directive.css +16 -0
- matplotlib_rs/mpl-data/sample_data/Minduka_Present_Blue_Pack.png +0 -0
- matplotlib_rs/mpl-data/sample_data/README.txt +2 -0
- matplotlib_rs/mpl-data/sample_data/Stocks.csv +526 -0
- matplotlib_rs/mpl-data/sample_data/axes_grid/bivariate_normal.npy +0 -0
- matplotlib_rs/mpl-data/sample_data/data_x_x2_x3.csv +11 -0
- matplotlib_rs/mpl-data/sample_data/eeg.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/embedding_in_wx3.xrc +65 -0
- matplotlib_rs/mpl-data/sample_data/goog.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/grace_hopper.jpg +0 -0
- matplotlib_rs/mpl-data/sample_data/jacksboro_fault_dem.npz +0 -0
- matplotlib_rs/mpl-data/sample_data/logo2.png +0 -0
- matplotlib_rs/mpl-data/sample_data/membrane.dat +0 -0
- matplotlib_rs/mpl-data/sample_data/msft.csv +66 -0
- matplotlib_rs/mpl-data/sample_data/s1045.ima.gz +0 -0
- matplotlib_rs/mpl-data/sample_data/topobathy.npz +0 -0
- matplotlib_rs/mpl-data/stylelib/Solarize_Light2.mplstyle +53 -0
- matplotlib_rs/mpl-data/stylelib/_classic_test_patch.mplstyle +8 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery-nogrid.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/_mpl-gallery.mplstyle +19 -0
- matplotlib_rs/mpl-data/stylelib/bmh.mplstyle +27 -0
- matplotlib_rs/mpl-data/stylelib/classic.mplstyle +491 -0
- matplotlib_rs/mpl-data/stylelib/dark_background.mplstyle +26 -0
- matplotlib_rs/mpl-data/stylelib/fast.mplstyle +11 -0
- matplotlib_rs/mpl-data/stylelib/fivethirtyeight.mplstyle +37 -0
- matplotlib_rs/mpl-data/stylelib/ggplot.mplstyle +39 -0
- matplotlib_rs/mpl-data/stylelib/grayscale.mplstyle +29 -0
- matplotlib_rs/mpl-data/stylelib/petroff10.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff6.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/petroff8.mplstyle +5 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-bright.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-colorblind.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark-palette.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-dark.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-darkgrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-deep.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-muted.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-notebook.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-paper.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-pastel.mplstyle +3 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-poster.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-talk.mplstyle +21 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-ticks.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-white.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8-whitegrid.mplstyle +30 -0
- matplotlib_rs/mpl-data/stylelib/seaborn-v0_8.mplstyle +57 -0
- matplotlib_rs/mpl-data/stylelib/tableau-colorblind10.mplstyle +3 -0
- matplotlib_rs/mpl_toolkits/__init__.py +3 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/__init__.py +11 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/anchored_artists.py +415 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_divider.py +619 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_grid.py +565 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_rgb.py +158 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/axes_size.py +272 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/inset_locator.py +525 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/mpl_axes.py +129 -0
- matplotlib_rs/mpl_toolkits/axes_grid1/parasite_axes.py +261 -0
- matplotlib_rs/mpl_toolkits/axisartist/__init__.py +15 -0
- matplotlib_rs/mpl_toolkits/axisartist/angle_helper.py +396 -0
- matplotlib_rs/mpl_toolkits/axisartist/axes_divider.py +3 -0
- matplotlib_rs/mpl_toolkits/axisartist/axis_artist.py +1148 -0
- matplotlib_rs/mpl_toolkits/axisartist/axisline_style.py +193 -0
- matplotlib_rs/mpl_toolkits/axisartist/axislines.py +475 -0
- matplotlib_rs/mpl_toolkits/axisartist/floating_axes.py +265 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_finder.py +329 -0
- matplotlib_rs/mpl_toolkits/axisartist/grid_helper_curvelinear.py +353 -0
- matplotlib_rs/mpl_toolkits/axisartist/parasite_axes.py +8 -0
- matplotlib_rs/mpl_toolkits/mplot3d/__init__.py +4 -0
- matplotlib_rs/mpl_toolkits/mplot3d/art3d.py +1758 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axes3d.py +4462 -0
- matplotlib_rs/mpl_toolkits/mplot3d/axis3d.py +807 -0
- matplotlib_rs/mpl_toolkits/mplot3d/proj3d.py +270 -0
- matplotlib_rs/offsetbox.py +1726 -0
- matplotlib_rs/patches.py +5049 -0
- matplotlib_rs/path.py +1147 -0
- matplotlib_rs/patheffects.py +512 -0
- matplotlib_rs/projections/__init__.py +126 -0
- matplotlib_rs/projections/geo.py +512 -0
- matplotlib_rs/projections/polar.py +1518 -0
- matplotlib_rs/pylab.py +68 -0
- matplotlib_rs/pyplot.py +4834 -0
- matplotlib_rs/quiver.py +1236 -0
- matplotlib_rs/rcsetup.py +3435 -0
- matplotlib_rs/sankey.py +815 -0
- matplotlib_rs/scale.py +1002 -0
- matplotlib_rs/spines.py +618 -0
- matplotlib_rs/stackplot.py +144 -0
- matplotlib_rs/streamplot.py +768 -0
- matplotlib_rs/style/__init__.py +269 -0
- matplotlib_rs/style/core.py +28 -0
- matplotlib_rs/table.py +860 -0
- matplotlib_rs/texmanager.py +375 -0
- matplotlib_rs/text.py +2412 -0
- matplotlib_rs/textpath.py +377 -0
- matplotlib_rs/ticker.py +3111 -0
- matplotlib_rs/transforms.py +3069 -0
- matplotlib_rs/tri/__init__.py +24 -0
- matplotlib_rs/tri/_triangulation.py +248 -0
- matplotlib_rs/tri/_tricontour.py +271 -0
- matplotlib_rs/tri/_trifinder.py +97 -0
- matplotlib_rs/tri/_triinterpolate.py +1575 -0
- matplotlib_rs/tri/_tripcolor.py +170 -0
- matplotlib_rs/tri/_triplot.py +87 -0
- matplotlib_rs/tri/_trirefine.py +308 -0
- matplotlib_rs/tri/_tritools.py +264 -0
- matplotlib_rs/typing.py +597 -0
- matplotlib_rs/units.py +196 -0
- matplotlib_rs/widgets.py +4455 -0
- matplotlib_rs-0.0.8.dist-info/METADATA +392 -0
- matplotlib_rs-0.0.8.dist-info/RECORD +352 -0
- matplotlib_rs-0.0.8.dist-info/WHEEL +4 -0
- matplotlib_rs-0.0.8.dist-info/sboms/matplotlib-rs.cyclonedx.json +4390 -0
matplotlib_rs/cbook.py
ADDED
|
@@ -0,0 +1,2762 @@
|
|
|
1
|
+
# Vendored from matplotlib 3.11 (see licenses/LICENSE_MATPLOTLIB), adapted for matplotlib_rs.
|
|
2
|
+
"""
|
|
3
|
+
A collection of utility functions and classes. Originally, many
|
|
4
|
+
(but not all) were from the Python Cookbook -- hence the name cbook.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import collections
|
|
8
|
+
import collections.abc
|
|
9
|
+
import contextlib
|
|
10
|
+
import functools
|
|
11
|
+
import gzip
|
|
12
|
+
import itertools
|
|
13
|
+
import math
|
|
14
|
+
import numbers
|
|
15
|
+
import operator
|
|
16
|
+
import os
|
|
17
|
+
from pathlib import Path
|
|
18
|
+
import shlex
|
|
19
|
+
import subprocess
|
|
20
|
+
import sys
|
|
21
|
+
import time
|
|
22
|
+
import traceback
|
|
23
|
+
import types
|
|
24
|
+
import weakref
|
|
25
|
+
|
|
26
|
+
import numpy as np
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
from numpy.exceptions import VisibleDeprecationWarning # numpy >= 1.25
|
|
30
|
+
except ImportError:
|
|
31
|
+
from numpy import VisibleDeprecationWarning
|
|
32
|
+
|
|
33
|
+
import matplotlib_rs as matplotlib
|
|
34
|
+
from . import _api
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
class _LazyMod:
|
|
38
|
+
def __init__(self, name):
|
|
39
|
+
self._name = name
|
|
40
|
+
|
|
41
|
+
def __getattr__(self, attr):
|
|
42
|
+
import importlib
|
|
43
|
+
return getattr(importlib.import_module(self._name, 'matplotlib_rs'), attr)
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
mlab = _LazyMod('.mlab')
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _c_internal_utils:
|
|
50
|
+
@staticmethod
|
|
51
|
+
def display_is_valid():
|
|
52
|
+
return bool(os.environ.get('DISPLAY') or os.environ.get('WAYLAND_DISPLAY'))
|
|
53
|
+
|
|
54
|
+
@staticmethod
|
|
55
|
+
def Win32_GetCurrentProcessExplicitAppUserModelID():
|
|
56
|
+
return None
|
|
57
|
+
|
|
58
|
+
@staticmethod
|
|
59
|
+
def Win32_SetCurrentProcessExplicitAppUserModelID(appid):
|
|
60
|
+
pass
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
class _ExceptionInfo:
|
|
64
|
+
"""
|
|
65
|
+
A class to carry exception information around.
|
|
66
|
+
|
|
67
|
+
This is used to store and later raise exceptions. It's an alternative to
|
|
68
|
+
directly storing Exception instances that circumvents traceback-related
|
|
69
|
+
issues: caching tracebacks can keep user's objects in local namespaces
|
|
70
|
+
alive indefinitely, which can lead to very surprising memory issues for
|
|
71
|
+
users and result in incorrect tracebacks.
|
|
72
|
+
"""
|
|
73
|
+
|
|
74
|
+
def __init__(self, cls, *args, notes=None):
|
|
75
|
+
self._cls = cls
|
|
76
|
+
self._args = args
|
|
77
|
+
self._notes = notes if notes is not None else []
|
|
78
|
+
|
|
79
|
+
@classmethod
|
|
80
|
+
def from_exception(cls, exc):
|
|
81
|
+
return cls(type(exc), *exc.args, notes=getattr(exc, "__notes__", []))
|
|
82
|
+
|
|
83
|
+
def to_exception(self):
|
|
84
|
+
exc = self._cls(*self._args)
|
|
85
|
+
for note in self._notes:
|
|
86
|
+
_add_note(exc, note)
|
|
87
|
+
return exc
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
def _add_note(exc, note):
|
|
91
|
+
"""``exc.add_note(note)``, also on Python 3.10 (which lacks it)."""
|
|
92
|
+
if hasattr(exc, "add_note"):
|
|
93
|
+
exc.add_note(note)
|
|
94
|
+
else:
|
|
95
|
+
exc.__notes__ = [*getattr(exc, "__notes__", []), note]
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def _get_running_interactive_framework():
|
|
99
|
+
"""
|
|
100
|
+
Return the interactive framework whose event loop is currently running, if
|
|
101
|
+
any, or "headless" if no event loop can be started, or None.
|
|
102
|
+
|
|
103
|
+
Returns
|
|
104
|
+
-------
|
|
105
|
+
Optional[str]
|
|
106
|
+
One of the following values: "qt", "gtk3", "gtk4", "wx", "tk",
|
|
107
|
+
"macosx", "headless", ``None``.
|
|
108
|
+
"""
|
|
109
|
+
# Use ``sys.modules.get(name)`` rather than ``name in sys.modules`` as
|
|
110
|
+
# entries can also have been explicitly set to None.
|
|
111
|
+
QtWidgets = (
|
|
112
|
+
sys.modules.get("PyQt6.QtWidgets")
|
|
113
|
+
or sys.modules.get("PySide6.QtWidgets")
|
|
114
|
+
or sys.modules.get("PyQt5.QtWidgets")
|
|
115
|
+
or sys.modules.get("PySide2.QtWidgets")
|
|
116
|
+
)
|
|
117
|
+
if QtWidgets and QtWidgets.QApplication.instance():
|
|
118
|
+
return "qt"
|
|
119
|
+
Gtk = sys.modules.get("gi.repository.Gtk")
|
|
120
|
+
if Gtk:
|
|
121
|
+
if Gtk.MAJOR_VERSION == 4:
|
|
122
|
+
from gi.repository import GLib
|
|
123
|
+
if GLib.main_depth():
|
|
124
|
+
return "gtk4"
|
|
125
|
+
if Gtk.MAJOR_VERSION == 3 and Gtk.main_level():
|
|
126
|
+
return "gtk3"
|
|
127
|
+
wx = sys.modules.get("wx")
|
|
128
|
+
if wx and wx.GetApp():
|
|
129
|
+
return "wx"
|
|
130
|
+
tkinter = sys.modules.get("tkinter")
|
|
131
|
+
if tkinter:
|
|
132
|
+
codes = {tkinter.mainloop.__code__, tkinter.Misc.mainloop.__code__}
|
|
133
|
+
for frame in sys._current_frames().values():
|
|
134
|
+
while frame:
|
|
135
|
+
if frame.f_code in codes:
|
|
136
|
+
return "tk"
|
|
137
|
+
frame = frame.f_back
|
|
138
|
+
# Preemptively break reference cycle between locals and the frame.
|
|
139
|
+
del frame
|
|
140
|
+
macosx = sys.modules.get("matplotlib.backends._macosx")
|
|
141
|
+
if macosx and macosx.event_loop_is_running():
|
|
142
|
+
return "macosx"
|
|
143
|
+
if not _c_internal_utils.display_is_valid():
|
|
144
|
+
return "headless"
|
|
145
|
+
return None
|
|
146
|
+
|
|
147
|
+
|
|
148
|
+
def _exception_printer(exc):
|
|
149
|
+
if _get_running_interactive_framework() in ["headless", None]:
|
|
150
|
+
raise exc
|
|
151
|
+
else:
|
|
152
|
+
traceback.print_exc()
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class _StrongRef:
|
|
156
|
+
"""
|
|
157
|
+
Wrapper similar to a weakref, but keeping a strong reference to the object.
|
|
158
|
+
"""
|
|
159
|
+
|
|
160
|
+
def __init__(self, obj):
|
|
161
|
+
self._obj = obj
|
|
162
|
+
|
|
163
|
+
def __call__(self):
|
|
164
|
+
return self._obj
|
|
165
|
+
|
|
166
|
+
def __eq__(self, other):
|
|
167
|
+
return isinstance(other, _StrongRef) and self._obj == other._obj
|
|
168
|
+
|
|
169
|
+
def __hash__(self):
|
|
170
|
+
return hash(self._obj)
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
def _weak_or_strong_ref(func, callback):
|
|
174
|
+
"""
|
|
175
|
+
Return a `WeakMethod` wrapping *func* if possible, else a `_StrongRef`.
|
|
176
|
+
"""
|
|
177
|
+
try:
|
|
178
|
+
return weakref.WeakMethod(func, callback)
|
|
179
|
+
except TypeError:
|
|
180
|
+
return _StrongRef(func)
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
class _UnhashDict:
|
|
184
|
+
"""
|
|
185
|
+
A minimal dict-like class that also supports unhashable keys, storing them
|
|
186
|
+
in a list of key-value pairs.
|
|
187
|
+
|
|
188
|
+
This class only implements the interface needed for `CallbackRegistry`, and
|
|
189
|
+
tries to minimize the overhead for the hashable case.
|
|
190
|
+
"""
|
|
191
|
+
|
|
192
|
+
def __init__(self, pairs):
|
|
193
|
+
self._dict = {}
|
|
194
|
+
self._pairs = []
|
|
195
|
+
for k, v in pairs:
|
|
196
|
+
self[k] = v
|
|
197
|
+
|
|
198
|
+
def __setitem__(self, key, value):
|
|
199
|
+
try:
|
|
200
|
+
self._dict[key] = value
|
|
201
|
+
except TypeError:
|
|
202
|
+
for i, (k, v) in enumerate(self._pairs):
|
|
203
|
+
if k == key:
|
|
204
|
+
self._pairs[i] = (key, value)
|
|
205
|
+
break
|
|
206
|
+
else:
|
|
207
|
+
self._pairs.append((key, value))
|
|
208
|
+
|
|
209
|
+
def __getitem__(self, key):
|
|
210
|
+
try:
|
|
211
|
+
return self._dict[key]
|
|
212
|
+
except TypeError:
|
|
213
|
+
pass
|
|
214
|
+
for k, v in self._pairs:
|
|
215
|
+
if k == key:
|
|
216
|
+
return v
|
|
217
|
+
raise KeyError(key)
|
|
218
|
+
|
|
219
|
+
def pop(self, key, *args):
|
|
220
|
+
try:
|
|
221
|
+
if key in self._dict:
|
|
222
|
+
return self._dict.pop(key)
|
|
223
|
+
except TypeError:
|
|
224
|
+
for i, (k, v) in enumerate(self._pairs):
|
|
225
|
+
if k == key:
|
|
226
|
+
del self._pairs[i]
|
|
227
|
+
return v
|
|
228
|
+
if args:
|
|
229
|
+
return args[0]
|
|
230
|
+
raise KeyError(key)
|
|
231
|
+
|
|
232
|
+
def __iter__(self):
|
|
233
|
+
yield from self._dict
|
|
234
|
+
for k, v in self._pairs:
|
|
235
|
+
yield k
|
|
236
|
+
|
|
237
|
+
|
|
238
|
+
class CallbackRegistry:
|
|
239
|
+
"""
|
|
240
|
+
Handle registering, processing, blocking, and disconnecting
|
|
241
|
+
for a set of signals and callbacks:
|
|
242
|
+
|
|
243
|
+
>>> def oneat(x):
|
|
244
|
+
... print('eat', x)
|
|
245
|
+
>>> def ondrink(x):
|
|
246
|
+
... print('drink', x)
|
|
247
|
+
|
|
248
|
+
>>> from matplotlib.cbook import CallbackRegistry
|
|
249
|
+
>>> callbacks = CallbackRegistry()
|
|
250
|
+
|
|
251
|
+
>>> id_eat = callbacks.connect('eat', oneat)
|
|
252
|
+
>>> id_drink = callbacks.connect('drink', ondrink)
|
|
253
|
+
|
|
254
|
+
>>> callbacks.process('drink', 123)
|
|
255
|
+
drink 123
|
|
256
|
+
>>> callbacks.process('eat', 456)
|
|
257
|
+
eat 456
|
|
258
|
+
>>> callbacks.process('be merry', 456) # nothing will be called
|
|
259
|
+
|
|
260
|
+
>>> callbacks.disconnect(id_eat)
|
|
261
|
+
>>> callbacks.process('eat', 456) # nothing will be called
|
|
262
|
+
|
|
263
|
+
>>> with callbacks.blocked(signal='drink'):
|
|
264
|
+
... callbacks.process('drink', 123) # nothing will be called
|
|
265
|
+
>>> callbacks.process('drink', 123)
|
|
266
|
+
drink 123
|
|
267
|
+
|
|
268
|
+
>>> callbacks.disconnect(ondrink, signal='drink') # disconnect by func
|
|
269
|
+
>>> callbacks.process('drink', 123) # nothing will be called
|
|
270
|
+
|
|
271
|
+
In practice, one should always disconnect all callbacks when they are
|
|
272
|
+
no longer needed to avoid dangling references (and thus memory leaks).
|
|
273
|
+
However, real code in Matplotlib rarely does so, and due to its design,
|
|
274
|
+
it is rather difficult to place this kind of code. To get around this,
|
|
275
|
+
and prevent this class of memory leaks, we instead store weak references
|
|
276
|
+
to bound methods only, so when the destination object needs to die, the
|
|
277
|
+
CallbackRegistry won't keep it alive.
|
|
278
|
+
|
|
279
|
+
Parameters
|
|
280
|
+
----------
|
|
281
|
+
exception_handler : callable, optional
|
|
282
|
+
If not None, *exception_handler* must be a function that takes an
|
|
283
|
+
`Exception` as single parameter. It gets called with any `Exception`
|
|
284
|
+
raised by the callbacks during `CallbackRegistry.process`, and may
|
|
285
|
+
either re-raise the exception or handle it in another manner.
|
|
286
|
+
|
|
287
|
+
The default handler prints the exception (with `traceback.print_exc`) if
|
|
288
|
+
an interactive event loop is running; it re-raises the exception if no
|
|
289
|
+
interactive event loop is running.
|
|
290
|
+
|
|
291
|
+
signals : list, optional
|
|
292
|
+
If not None, *signals* is a list of signals that this registry handles:
|
|
293
|
+
attempting to `process` or to `connect` to a signal not in the list
|
|
294
|
+
throws a `ValueError`. The default, None, does not restrict the
|
|
295
|
+
handled signals.
|
|
296
|
+
"""
|
|
297
|
+
|
|
298
|
+
# We maintain two mappings:
|
|
299
|
+
# callbacks: signal -> {cid -> weakref-to-callback}
|
|
300
|
+
# _func_cid_map: {(signal, weakref-to-callback) -> cid}
|
|
301
|
+
|
|
302
|
+
def __init__(self, exception_handler=_exception_printer, *, signals=None):
|
|
303
|
+
self._signals = None if signals is None else list(signals) # Copy it.
|
|
304
|
+
self.exception_handler = exception_handler
|
|
305
|
+
self.callbacks = {}
|
|
306
|
+
self._cid_gen = itertools.count()
|
|
307
|
+
self._func_cid_map = _UnhashDict([])
|
|
308
|
+
# A hidden variable that marks cids that need to be pickled.
|
|
309
|
+
self._pickled_cids = set()
|
|
310
|
+
|
|
311
|
+
def __getstate__(self):
|
|
312
|
+
return {
|
|
313
|
+
**vars(self),
|
|
314
|
+
# In general, callbacks may not be pickled, so we just drop them,
|
|
315
|
+
# unless directed otherwise by self._pickled_cids.
|
|
316
|
+
"callbacks": {s: {cid: proxy() for cid, proxy in d.items()
|
|
317
|
+
if cid in self._pickled_cids}
|
|
318
|
+
for s, d in self.callbacks.items()},
|
|
319
|
+
# It is simpler to reconstruct this from callbacks in __setstate__.
|
|
320
|
+
"_func_cid_map": None,
|
|
321
|
+
"_cid_gen": next(self._cid_gen)
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
def __setstate__(self, state):
|
|
325
|
+
cid_count = state.pop('_cid_gen')
|
|
326
|
+
vars(self).update(state)
|
|
327
|
+
self.callbacks = {
|
|
328
|
+
s: {cid: _weak_or_strong_ref(func, functools.partial(self._remove_proxy, s))
|
|
329
|
+
for cid, func in d.items()}
|
|
330
|
+
for s, d in self.callbacks.items()}
|
|
331
|
+
self._func_cid_map = _UnhashDict(
|
|
332
|
+
((s, proxy), cid)
|
|
333
|
+
for s, d in self.callbacks.items() for cid, proxy in d.items())
|
|
334
|
+
self._cid_gen = itertools.count(cid_count)
|
|
335
|
+
|
|
336
|
+
def connect(self, signal, func):
|
|
337
|
+
"""Register *func* to be called when signal *signal* is generated."""
|
|
338
|
+
if self._signals is not None:
|
|
339
|
+
_api.check_in_list(self._signals, signal=signal)
|
|
340
|
+
proxy = _weak_or_strong_ref(func, functools.partial(self._remove_proxy, signal))
|
|
341
|
+
try:
|
|
342
|
+
return self._func_cid_map[signal, proxy]
|
|
343
|
+
except KeyError:
|
|
344
|
+
cid = self._func_cid_map[signal, proxy] = next(self._cid_gen)
|
|
345
|
+
self.callbacks.setdefault(signal, {})[cid] = proxy
|
|
346
|
+
return cid
|
|
347
|
+
|
|
348
|
+
def _connect_picklable(self, signal, func):
|
|
349
|
+
"""
|
|
350
|
+
Like `.connect`, but the callback is kept when pickling/unpickling.
|
|
351
|
+
|
|
352
|
+
Currently internal-use only.
|
|
353
|
+
"""
|
|
354
|
+
cid = self.connect(signal, func)
|
|
355
|
+
self._pickled_cids.add(cid)
|
|
356
|
+
return cid
|
|
357
|
+
|
|
358
|
+
# Keep a reference to sys.is_finalizing, as sys may have been cleared out
|
|
359
|
+
# at that point.
|
|
360
|
+
def _remove_proxy(self, signal, proxy, *, _is_finalizing=sys.is_finalizing):
|
|
361
|
+
if _is_finalizing():
|
|
362
|
+
# Weakrefs can't be properly torn down at that point anymore.
|
|
363
|
+
return
|
|
364
|
+
cid = self._func_cid_map.pop((signal, proxy), None)
|
|
365
|
+
if cid is not None:
|
|
366
|
+
del self.callbacks[signal][cid]
|
|
367
|
+
self._pickled_cids.discard(cid)
|
|
368
|
+
else: # Not found
|
|
369
|
+
return
|
|
370
|
+
if len(self.callbacks[signal]) == 0: # Clean up empty dicts
|
|
371
|
+
del self.callbacks[signal]
|
|
372
|
+
|
|
373
|
+
@_api.rename_parameter("3.11", "cid", "cid_or_func")
|
|
374
|
+
def disconnect(self, cid_or_func, *, signal=None):
|
|
375
|
+
"""
|
|
376
|
+
Disconnect a callback.
|
|
377
|
+
|
|
378
|
+
Parameters
|
|
379
|
+
----------
|
|
380
|
+
cid_or_func : int or callable
|
|
381
|
+
If an int, disconnect the callback with that connection id.
|
|
382
|
+
If a callable, disconnect that function from signals.
|
|
383
|
+
signal : optional
|
|
384
|
+
Only used when *cid_or_func* is a callable. If given, disconnect
|
|
385
|
+
the function only from that specific signal. If not given,
|
|
386
|
+
disconnect from all signals the function is connected to.
|
|
387
|
+
|
|
388
|
+
Notes
|
|
389
|
+
-----
|
|
390
|
+
No error is raised if such a callback does not exist.
|
|
391
|
+
"""
|
|
392
|
+
if isinstance(cid_or_func, int):
|
|
393
|
+
if signal is not None:
|
|
394
|
+
raise ValueError(
|
|
395
|
+
"signal cannot be specified when disconnecting by cid")
|
|
396
|
+
for sig, proxy in self._func_cid_map:
|
|
397
|
+
if self._func_cid_map[sig, proxy] == cid_or_func:
|
|
398
|
+
break
|
|
399
|
+
else: # Not found
|
|
400
|
+
return
|
|
401
|
+
self._remove_proxy(sig, proxy)
|
|
402
|
+
elif signal is not None:
|
|
403
|
+
# Disconnect from a specific signal
|
|
404
|
+
proxy = _weak_or_strong_ref(cid_or_func, None)
|
|
405
|
+
self._remove_proxy(signal, proxy)
|
|
406
|
+
else:
|
|
407
|
+
# Disconnect from all signals
|
|
408
|
+
proxy = _weak_or_strong_ref(cid_or_func, None)
|
|
409
|
+
for sig, prx in list(self._func_cid_map):
|
|
410
|
+
if prx == proxy:
|
|
411
|
+
self._remove_proxy(sig, proxy)
|
|
412
|
+
|
|
413
|
+
def process(self, s, *args, **kwargs):
|
|
414
|
+
"""
|
|
415
|
+
Process signal *s*.
|
|
416
|
+
|
|
417
|
+
All of the functions registered to receive callbacks on *s* will be
|
|
418
|
+
called with ``*args`` and ``**kwargs``.
|
|
419
|
+
"""
|
|
420
|
+
if self._signals is not None:
|
|
421
|
+
_api.check_in_list(self._signals, signal=s)
|
|
422
|
+
for ref in list(self.callbacks.get(s, {}).values()):
|
|
423
|
+
func = ref()
|
|
424
|
+
if func is not None:
|
|
425
|
+
try:
|
|
426
|
+
func(*args, **kwargs)
|
|
427
|
+
# this does not capture KeyboardInterrupt, SystemExit,
|
|
428
|
+
# and GeneratorExit
|
|
429
|
+
except Exception as exc:
|
|
430
|
+
if self.exception_handler is not None:
|
|
431
|
+
self.exception_handler(exc)
|
|
432
|
+
else:
|
|
433
|
+
raise
|
|
434
|
+
|
|
435
|
+
@contextlib.contextmanager
|
|
436
|
+
def blocked(self, *, signal=None):
|
|
437
|
+
"""
|
|
438
|
+
Block callback signals from being processed.
|
|
439
|
+
|
|
440
|
+
A context manager to temporarily block/disable callback signals
|
|
441
|
+
from being processed by the registered listeners.
|
|
442
|
+
|
|
443
|
+
Parameters
|
|
444
|
+
----------
|
|
445
|
+
signal : str, optional
|
|
446
|
+
The callback signal to block. The default is to block all signals.
|
|
447
|
+
"""
|
|
448
|
+
orig = self.callbacks
|
|
449
|
+
try:
|
|
450
|
+
if signal is None:
|
|
451
|
+
# Empty out the callbacks
|
|
452
|
+
self.callbacks = {}
|
|
453
|
+
else:
|
|
454
|
+
# Only remove the specific signal
|
|
455
|
+
self.callbacks = {k: orig[k] for k in orig if k != signal}
|
|
456
|
+
yield
|
|
457
|
+
finally:
|
|
458
|
+
self.callbacks = orig
|
|
459
|
+
|
|
460
|
+
|
|
461
|
+
class silent_list(list):
|
|
462
|
+
"""
|
|
463
|
+
A list with a short ``repr()``.
|
|
464
|
+
|
|
465
|
+
This is meant to be used for a homogeneous list of artists, so that they
|
|
466
|
+
don't cause long, meaningless output.
|
|
467
|
+
|
|
468
|
+
Instead of ::
|
|
469
|
+
|
|
470
|
+
[<matplotlib.lines.Line2D object at 0x7f5749fed3c8>,
|
|
471
|
+
<matplotlib.lines.Line2D object at 0x7f5749fed4e0>,
|
|
472
|
+
<matplotlib.lines.Line2D object at 0x7f5758016550>]
|
|
473
|
+
|
|
474
|
+
one will get ::
|
|
475
|
+
|
|
476
|
+
<a list of 3 Line2D objects>
|
|
477
|
+
|
|
478
|
+
If ``self.type`` is None, the type name is obtained from the first item in
|
|
479
|
+
the list (if any).
|
|
480
|
+
"""
|
|
481
|
+
|
|
482
|
+
def __init__(self, type, seq=None):
|
|
483
|
+
self.type = type
|
|
484
|
+
if seq is not None:
|
|
485
|
+
self.extend(seq)
|
|
486
|
+
|
|
487
|
+
def __repr__(self):
|
|
488
|
+
if self.type is not None or len(self) != 0:
|
|
489
|
+
tp = self.type if self.type is not None else type(self[0]).__name__
|
|
490
|
+
return f"<a list of {len(self)} {tp} objects>"
|
|
491
|
+
else:
|
|
492
|
+
return "<an empty list>"
|
|
493
|
+
|
|
494
|
+
|
|
495
|
+
def _local_over_kwdict(
|
|
496
|
+
local_var, kwargs, *keys,
|
|
497
|
+
warning_cls=_api.MatplotlibDeprecationWarning):
|
|
498
|
+
out = local_var
|
|
499
|
+
for key in keys:
|
|
500
|
+
kwarg_val = kwargs.pop(key, None)
|
|
501
|
+
if kwarg_val is not None:
|
|
502
|
+
if out is None:
|
|
503
|
+
out = kwarg_val
|
|
504
|
+
else:
|
|
505
|
+
_api.warn_external(f'"{key}" keyword argument will be ignored',
|
|
506
|
+
warning_cls)
|
|
507
|
+
return out
|
|
508
|
+
|
|
509
|
+
|
|
510
|
+
def strip_math(s):
|
|
511
|
+
"""
|
|
512
|
+
Remove latex formatting from mathtext.
|
|
513
|
+
|
|
514
|
+
Only handles fully math and fully non-math strings.
|
|
515
|
+
"""
|
|
516
|
+
if len(s) >= 2 and s[0] == s[-1] == "$":
|
|
517
|
+
s = s[1:-1]
|
|
518
|
+
for tex, plain in [
|
|
519
|
+
(r"\times", "x"), # Specifically for Formatter support.
|
|
520
|
+
(r"\mathdefault", ""),
|
|
521
|
+
(r"\rm", ""),
|
|
522
|
+
(r"\cal", ""),
|
|
523
|
+
(r"\tt", ""),
|
|
524
|
+
(r"\it", ""),
|
|
525
|
+
("\\", ""),
|
|
526
|
+
("{", ""),
|
|
527
|
+
("}", ""),
|
|
528
|
+
]:
|
|
529
|
+
s = s.replace(tex, plain)
|
|
530
|
+
return s
|
|
531
|
+
|
|
532
|
+
|
|
533
|
+
def _strip_comment(s):
|
|
534
|
+
"""Strip everything from the first unquoted #."""
|
|
535
|
+
pos = 0
|
|
536
|
+
while True:
|
|
537
|
+
quote_pos = s.find('"', pos)
|
|
538
|
+
hash_pos = s.find('#', pos)
|
|
539
|
+
if quote_pos < 0:
|
|
540
|
+
without_comment = s if hash_pos < 0 else s[:hash_pos]
|
|
541
|
+
return without_comment.strip()
|
|
542
|
+
elif 0 <= hash_pos < quote_pos:
|
|
543
|
+
return s[:hash_pos].strip()
|
|
544
|
+
else:
|
|
545
|
+
closing_quote_pos = s.find('"', quote_pos + 1)
|
|
546
|
+
if closing_quote_pos < 0:
|
|
547
|
+
raise ValueError(
|
|
548
|
+
f"Missing closing quote in: {s!r}. If you need a double-"
|
|
549
|
+
'quote inside a string, use escaping: e.g. "the \" char"')
|
|
550
|
+
pos = closing_quote_pos + 1 # behind closing quote
|
|
551
|
+
|
|
552
|
+
|
|
553
|
+
def is_writable_file_like(obj):
|
|
554
|
+
"""Return whether *obj* looks like a file object with a *write* method."""
|
|
555
|
+
return callable(getattr(obj, 'write', None))
|
|
556
|
+
|
|
557
|
+
|
|
558
|
+
def file_requires_unicode(x):
|
|
559
|
+
"""
|
|
560
|
+
Return whether the given writable file-like object requires Unicode to be
|
|
561
|
+
written to it.
|
|
562
|
+
"""
|
|
563
|
+
try:
|
|
564
|
+
x.write(b'')
|
|
565
|
+
except TypeError:
|
|
566
|
+
return True
|
|
567
|
+
else:
|
|
568
|
+
return False
|
|
569
|
+
|
|
570
|
+
|
|
571
|
+
def to_filehandle(fname, flag='r', return_opened=False, encoding=None):
|
|
572
|
+
"""
|
|
573
|
+
Convert a path to an open file handle or pass-through a file-like object.
|
|
574
|
+
|
|
575
|
+
Consider using `open_file_cm` instead, as it allows one to properly close
|
|
576
|
+
newly created file objects more easily.
|
|
577
|
+
|
|
578
|
+
Parameters
|
|
579
|
+
----------
|
|
580
|
+
fname : str or path-like or file-like
|
|
581
|
+
If `str` or `os.PathLike`, the file is opened using the flags specified
|
|
582
|
+
by *flag* and *encoding*. If a file-like object, it is passed through.
|
|
583
|
+
flag : str, default: 'r'
|
|
584
|
+
Passed as the *mode* argument to `open` when *fname* is `str` or
|
|
585
|
+
`os.PathLike`; ignored if *fname* is file-like.
|
|
586
|
+
return_opened : bool, default: False
|
|
587
|
+
If True, return both the file object and a boolean indicating whether
|
|
588
|
+
this was a new file (that the caller needs to close). If False, return
|
|
589
|
+
only the new file.
|
|
590
|
+
encoding : str or None, default: None
|
|
591
|
+
Passed as the *mode* argument to `open` when *fname* is `str` or
|
|
592
|
+
`os.PathLike`; ignored if *fname* is file-like.
|
|
593
|
+
|
|
594
|
+
Returns
|
|
595
|
+
-------
|
|
596
|
+
fh : file-like
|
|
597
|
+
opened : bool
|
|
598
|
+
*opened* is only returned if *return_opened* is True.
|
|
599
|
+
"""
|
|
600
|
+
if isinstance(fname, os.PathLike):
|
|
601
|
+
fname = os.fspath(fname)
|
|
602
|
+
if isinstance(fname, str):
|
|
603
|
+
if fname.endswith('.gz'):
|
|
604
|
+
fh = gzip.open(fname, flag)
|
|
605
|
+
elif fname.endswith('.bz2'):
|
|
606
|
+
# python may not be compiled with bz2 support,
|
|
607
|
+
# bury import until we need it
|
|
608
|
+
import bz2
|
|
609
|
+
fh = bz2.BZ2File(fname, flag)
|
|
610
|
+
else:
|
|
611
|
+
fh = open(fname, flag, encoding=encoding)
|
|
612
|
+
opened = True
|
|
613
|
+
elif hasattr(fname, 'seek'):
|
|
614
|
+
fh = fname
|
|
615
|
+
opened = False
|
|
616
|
+
else:
|
|
617
|
+
raise ValueError('fname must be a PathLike or file handle')
|
|
618
|
+
if return_opened:
|
|
619
|
+
return fh, opened
|
|
620
|
+
return fh
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
def open_file_cm(path_or_file, mode="r", encoding=None):
|
|
624
|
+
r"""Pass through file objects and context-manage path-likes."""
|
|
625
|
+
fh, opened = to_filehandle(path_or_file, mode, True, encoding)
|
|
626
|
+
return fh if opened else contextlib.nullcontext(fh)
|
|
627
|
+
|
|
628
|
+
|
|
629
|
+
def is_scalar_or_string(val):
|
|
630
|
+
"""Return whether the given object is a scalar or string like."""
|
|
631
|
+
return isinstance(val, str) or not np.iterable(val)
|
|
632
|
+
|
|
633
|
+
|
|
634
|
+
def get_sample_data(fname, asfileobj=True):
|
|
635
|
+
"""
|
|
636
|
+
Return a sample data file. *fname* is a path relative to the
|
|
637
|
+
:file:`mpl-data/sample_data` directory. If *asfileobj* is `True`
|
|
638
|
+
return a file object, otherwise just a file path.
|
|
639
|
+
|
|
640
|
+
Sample data files are stored in the 'mpl-data/sample_data' directory within
|
|
641
|
+
the Matplotlib package.
|
|
642
|
+
|
|
643
|
+
If the filename ends in .gz, the file is implicitly ungzipped. If the
|
|
644
|
+
filename ends with .npy or .npz, and *asfileobj* is `True`, the file is
|
|
645
|
+
loaded with `numpy.load`.
|
|
646
|
+
"""
|
|
647
|
+
path = _get_data_path('sample_data', fname)
|
|
648
|
+
if asfileobj:
|
|
649
|
+
suffix = path.suffix.lower()
|
|
650
|
+
if suffix == '.gz':
|
|
651
|
+
return gzip.open(path)
|
|
652
|
+
elif suffix in ['.npy', '.npz']:
|
|
653
|
+
return np.load(path)
|
|
654
|
+
elif suffix in ['.csv', '.xrc', '.txt']:
|
|
655
|
+
return path.open('r')
|
|
656
|
+
else:
|
|
657
|
+
return path.open('rb')
|
|
658
|
+
else:
|
|
659
|
+
return str(path)
|
|
660
|
+
|
|
661
|
+
|
|
662
|
+
def _get_data_path(*args):
|
|
663
|
+
"""
|
|
664
|
+
Return the `pathlib.Path` to a resource file provided by Matplotlib.
|
|
665
|
+
|
|
666
|
+
``*args`` specify a path relative to the base data path.
|
|
667
|
+
"""
|
|
668
|
+
return Path(matplotlib.get_data_path(), *args)
|
|
669
|
+
|
|
670
|
+
|
|
671
|
+
def flatten(seq, scalarp=is_scalar_or_string):
|
|
672
|
+
"""
|
|
673
|
+
Return a generator of flattened nested containers.
|
|
674
|
+
|
|
675
|
+
For example:
|
|
676
|
+
|
|
677
|
+
>>> from matplotlib.cbook import flatten
|
|
678
|
+
>>> l = (('John', ['Hunter']), (1, 23), [[([42, (5, 23)], )]])
|
|
679
|
+
>>> print(list(flatten(l)))
|
|
680
|
+
['John', 'Hunter', 1, 23, 42, 5, 23]
|
|
681
|
+
|
|
682
|
+
By: Composite of Holger Krekel and Luther Blissett
|
|
683
|
+
From: https://code.activestate.com/recipes/121294-simple-generator-for-flattening-nested-containers/
|
|
684
|
+
and Recipe 1.12 in cookbook
|
|
685
|
+
""" # noqa: E501
|
|
686
|
+
for item in seq:
|
|
687
|
+
if scalarp(item) or item is None:
|
|
688
|
+
yield item
|
|
689
|
+
else:
|
|
690
|
+
yield from flatten(item, scalarp)
|
|
691
|
+
|
|
692
|
+
|
|
693
|
+
class _Stack:
|
|
694
|
+
"""
|
|
695
|
+
Stack of elements with a movable cursor.
|
|
696
|
+
|
|
697
|
+
Mimics home/back/forward in a web browser.
|
|
698
|
+
"""
|
|
699
|
+
|
|
700
|
+
def __init__(self):
|
|
701
|
+
self._pos = -1
|
|
702
|
+
self._elements = []
|
|
703
|
+
|
|
704
|
+
def clear(self):
|
|
705
|
+
"""Empty the stack."""
|
|
706
|
+
self._pos = -1
|
|
707
|
+
self._elements = []
|
|
708
|
+
|
|
709
|
+
def __call__(self):
|
|
710
|
+
"""Return the current element, or None."""
|
|
711
|
+
return self._elements[self._pos] if self._elements else None
|
|
712
|
+
|
|
713
|
+
def __len__(self):
|
|
714
|
+
return len(self._elements)
|
|
715
|
+
|
|
716
|
+
def __getitem__(self, ind):
|
|
717
|
+
return self._elements[ind]
|
|
718
|
+
|
|
719
|
+
def forward(self):
|
|
720
|
+
"""Move the position forward and return the current element."""
|
|
721
|
+
self._pos = min(self._pos + 1, len(self._elements) - 1)
|
|
722
|
+
return self()
|
|
723
|
+
|
|
724
|
+
def back(self):
|
|
725
|
+
"""Move the position back and return the current element."""
|
|
726
|
+
self._pos = max(self._pos - 1, 0)
|
|
727
|
+
return self()
|
|
728
|
+
|
|
729
|
+
def push(self, o):
|
|
730
|
+
"""
|
|
731
|
+
Push *o* to the stack after the current position, and return *o*.
|
|
732
|
+
|
|
733
|
+
Discard all later elements.
|
|
734
|
+
"""
|
|
735
|
+
self._elements[self._pos + 1:] = [o]
|
|
736
|
+
self._pos = len(self._elements) - 1
|
|
737
|
+
return o
|
|
738
|
+
|
|
739
|
+
def home(self):
|
|
740
|
+
"""
|
|
741
|
+
Push the first element onto the top of the stack.
|
|
742
|
+
|
|
743
|
+
The first element is returned.
|
|
744
|
+
"""
|
|
745
|
+
return self.push(self._elements[0]) if self._elements else None
|
|
746
|
+
|
|
747
|
+
|
|
748
|
+
def safe_masked_invalid(x, copy=False):
|
|
749
|
+
x = np.array(x, subok=True, copy=copy)
|
|
750
|
+
if not x.dtype.isnative:
|
|
751
|
+
# If we have already made a copy, do the byteswap in place, else make a
|
|
752
|
+
# copy with the byte order swapped.
|
|
753
|
+
# Swap to native order.
|
|
754
|
+
x = x.byteswap(inplace=copy).view(x.dtype.newbyteorder('N'))
|
|
755
|
+
try:
|
|
756
|
+
xm = np.ma.masked_where(~(np.isfinite(x)), x, copy=False)
|
|
757
|
+
except TypeError:
|
|
758
|
+
if len(x.dtype.descr) == 1:
|
|
759
|
+
# Arrays with dtype 'object' get returned here.
|
|
760
|
+
# For example the 'c' kwarg of scatter, which supports multiple types.
|
|
761
|
+
# `plt.scatter([3, 4], [2, 5], c=[(1, 0, 0), 'y'])`
|
|
762
|
+
return x
|
|
763
|
+
else:
|
|
764
|
+
# In case of a dtype with multiple fields
|
|
765
|
+
# for example image data using a MultiNorm
|
|
766
|
+
try:
|
|
767
|
+
mask = np.empty(x.shape, dtype=np.dtype('bool, '*len(x.dtype.descr)))
|
|
768
|
+
for dd, dm in zip(x.dtype.descr, mask.dtype.descr):
|
|
769
|
+
mask[dm[0]] = ~np.isfinite(x[dd[0]])
|
|
770
|
+
xm = np.ma.array(x, mask=mask, copy=False)
|
|
771
|
+
except TypeError:
|
|
772
|
+
return x
|
|
773
|
+
return xm
|
|
774
|
+
|
|
775
|
+
|
|
776
|
+
def print_cycles(objects, outstream=sys.stdout, show_progress=False):
|
|
777
|
+
"""
|
|
778
|
+
Print loops of cyclic references in the given *objects*.
|
|
779
|
+
|
|
780
|
+
It is often useful to pass in ``gc.garbage`` to find the cycles that are
|
|
781
|
+
preventing some objects from being garbage collected.
|
|
782
|
+
|
|
783
|
+
Parameters
|
|
784
|
+
----------
|
|
785
|
+
objects
|
|
786
|
+
A list of objects to find cycles in.
|
|
787
|
+
outstream
|
|
788
|
+
The stream for output.
|
|
789
|
+
show_progress : bool
|
|
790
|
+
If True, print the number of objects reached as they are found.
|
|
791
|
+
"""
|
|
792
|
+
import gc
|
|
793
|
+
|
|
794
|
+
def print_path(path):
|
|
795
|
+
for i, step in enumerate(path):
|
|
796
|
+
# next "wraps around"
|
|
797
|
+
next = path[(i + 1) % len(path)]
|
|
798
|
+
|
|
799
|
+
outstream.write(" %s -- " % type(step))
|
|
800
|
+
if isinstance(step, dict):
|
|
801
|
+
for key, val in step.items():
|
|
802
|
+
if val is next:
|
|
803
|
+
outstream.write(f"[{key!r}]")
|
|
804
|
+
break
|
|
805
|
+
if key is next:
|
|
806
|
+
outstream.write(f"[key] = {val!r}")
|
|
807
|
+
break
|
|
808
|
+
elif isinstance(step, list):
|
|
809
|
+
outstream.write("[%d]" % step.index(next))
|
|
810
|
+
elif isinstance(step, tuple):
|
|
811
|
+
outstream.write("( tuple )")
|
|
812
|
+
else:
|
|
813
|
+
outstream.write(repr(step))
|
|
814
|
+
outstream.write(" ->\n")
|
|
815
|
+
outstream.write("\n")
|
|
816
|
+
|
|
817
|
+
def recurse(obj, start, all, current_path):
|
|
818
|
+
if show_progress:
|
|
819
|
+
outstream.write("%d\r" % len(all))
|
|
820
|
+
|
|
821
|
+
all[id(obj)] = None
|
|
822
|
+
|
|
823
|
+
referents = gc.get_referents(obj)
|
|
824
|
+
for referent in referents:
|
|
825
|
+
# If we've found our way back to the start, this is
|
|
826
|
+
# a cycle, so print it out
|
|
827
|
+
if referent is start:
|
|
828
|
+
print_path(current_path)
|
|
829
|
+
|
|
830
|
+
# Don't go back through the original list of objects, or
|
|
831
|
+
# through temporary references to the object, since those
|
|
832
|
+
# are just an artifact of the cycle detector itself.
|
|
833
|
+
elif referent is objects or isinstance(referent, types.FrameType):
|
|
834
|
+
continue
|
|
835
|
+
|
|
836
|
+
# We haven't seen this object before, so recurse
|
|
837
|
+
elif id(referent) not in all:
|
|
838
|
+
recurse(referent, start, all, current_path + [obj])
|
|
839
|
+
|
|
840
|
+
for obj in objects:
|
|
841
|
+
outstream.write(f"Examining: {obj!r}\n")
|
|
842
|
+
recurse(obj, obj, {}, [])
|
|
843
|
+
|
|
844
|
+
|
|
845
|
+
class Grouper:
|
|
846
|
+
"""
|
|
847
|
+
A disjoint-set data structure.
|
|
848
|
+
|
|
849
|
+
Objects can be joined using :meth:`join`, tested for connectedness
|
|
850
|
+
using :meth:`joined`, and all disjoint sets can be retrieved by
|
|
851
|
+
using the object as an iterator.
|
|
852
|
+
|
|
853
|
+
The objects being joined must be hashable and weak-referenceable.
|
|
854
|
+
|
|
855
|
+
Examples
|
|
856
|
+
--------
|
|
857
|
+
>>> from matplotlib.cbook import Grouper
|
|
858
|
+
>>> class Foo:
|
|
859
|
+
... def __init__(self, s):
|
|
860
|
+
... self.s = s
|
|
861
|
+
... def __repr__(self):
|
|
862
|
+
... return self.s
|
|
863
|
+
...
|
|
864
|
+
>>> a, b, c, d, e, f = [Foo(x) for x in 'abcdef']
|
|
865
|
+
>>> grp = Grouper()
|
|
866
|
+
>>> grp.join(a, b)
|
|
867
|
+
>>> grp.join(b, c)
|
|
868
|
+
>>> grp.join(d, e)
|
|
869
|
+
>>> list(grp)
|
|
870
|
+
[[a, b, c], [d, e]]
|
|
871
|
+
>>> grp.joined(a, b)
|
|
872
|
+
True
|
|
873
|
+
>>> grp.joined(a, c)
|
|
874
|
+
True
|
|
875
|
+
>>> grp.joined(a, d)
|
|
876
|
+
False
|
|
877
|
+
"""
|
|
878
|
+
|
|
879
|
+
def __init__(self, init=()):
|
|
880
|
+
self._mapping = weakref.WeakKeyDictionary(
|
|
881
|
+
{x: weakref.WeakSet([x]) for x in init})
|
|
882
|
+
self._ordering = weakref.WeakKeyDictionary()
|
|
883
|
+
for x in init:
|
|
884
|
+
if x not in self._ordering:
|
|
885
|
+
self._ordering[x] = len(self._ordering)
|
|
886
|
+
self._next_order = len(self._ordering) # Plain int to simplify pickling.
|
|
887
|
+
|
|
888
|
+
def __getstate__(self):
|
|
889
|
+
return {
|
|
890
|
+
**vars(self),
|
|
891
|
+
# Convert weak refs to strong ones.
|
|
892
|
+
"_mapping": {k: set(v) for k, v in self._mapping.items()},
|
|
893
|
+
"_ordering": {**self._ordering},
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
def __setstate__(self, state):
|
|
897
|
+
vars(self).update(state)
|
|
898
|
+
# Convert strong refs to weak ones.
|
|
899
|
+
self._mapping = weakref.WeakKeyDictionary(
|
|
900
|
+
{k: weakref.WeakSet(v) for k, v in self._mapping.items()})
|
|
901
|
+
self._ordering = weakref.WeakKeyDictionary(self._ordering)
|
|
902
|
+
|
|
903
|
+
def __contains__(self, item):
|
|
904
|
+
return item in self._mapping
|
|
905
|
+
|
|
906
|
+
def join(self, a, *args):
|
|
907
|
+
"""
|
|
908
|
+
Join given arguments into the same set. Accepts one or more arguments.
|
|
909
|
+
"""
|
|
910
|
+
mapping = self._mapping
|
|
911
|
+
try:
|
|
912
|
+
set_a = mapping[a]
|
|
913
|
+
except KeyError:
|
|
914
|
+
set_a = mapping[a] = weakref.WeakSet([a])
|
|
915
|
+
self._ordering[a] = self._next_order
|
|
916
|
+
self._next_order += 1
|
|
917
|
+
for arg in args:
|
|
918
|
+
try:
|
|
919
|
+
set_b = mapping[arg]
|
|
920
|
+
except KeyError:
|
|
921
|
+
set_b = mapping[arg] = weakref.WeakSet([arg])
|
|
922
|
+
self._ordering[arg] = self._next_order
|
|
923
|
+
self._next_order += 1
|
|
924
|
+
if set_b is not set_a:
|
|
925
|
+
if len(set_b) > len(set_a):
|
|
926
|
+
set_a, set_b = set_b, set_a
|
|
927
|
+
set_a.update(set_b)
|
|
928
|
+
for elem in set_b:
|
|
929
|
+
mapping[elem] = set_a
|
|
930
|
+
|
|
931
|
+
def joined(self, a, b):
|
|
932
|
+
"""Return whether *a* and *b* are members of the same set."""
|
|
933
|
+
return (self._mapping.get(a, object()) is self._mapping.get(b))
|
|
934
|
+
|
|
935
|
+
def remove(self, a):
|
|
936
|
+
"""Remove *a* from the grouper, doing nothing if it is not there."""
|
|
937
|
+
self._mapping.pop(a, {a}).remove(a)
|
|
938
|
+
self._ordering.pop(a, None)
|
|
939
|
+
|
|
940
|
+
def __iter__(self):
|
|
941
|
+
"""
|
|
942
|
+
Iterate over each of the disjoint sets as a list.
|
|
943
|
+
|
|
944
|
+
The iterator is invalid if interleaved with calls to join().
|
|
945
|
+
"""
|
|
946
|
+
unique_groups = {id(group): group for group in self._mapping.values()}
|
|
947
|
+
for group in unique_groups.values():
|
|
948
|
+
yield sorted(group, key=self._ordering.__getitem__)
|
|
949
|
+
|
|
950
|
+
def get_siblings(self, a, *, include_self=True):
|
|
951
|
+
"""
|
|
952
|
+
Return all the items joined with *a*.
|
|
953
|
+
|
|
954
|
+
*a* is included in the list if *include_self* is True.
|
|
955
|
+
"""
|
|
956
|
+
siblings = self._mapping.get(a, [a])
|
|
957
|
+
result = sorted(siblings, key=self._ordering.get)
|
|
958
|
+
if not include_self:
|
|
959
|
+
result.remove(a)
|
|
960
|
+
return result
|
|
961
|
+
|
|
962
|
+
|
|
963
|
+
class GrouperView:
|
|
964
|
+
"""Immutable view over a `.Grouper`."""
|
|
965
|
+
|
|
966
|
+
def __init__(self, grouper): self._grouper = grouper
|
|
967
|
+
def __contains__(self, item): return item in self._grouper
|
|
968
|
+
def __iter__(self): return iter(self._grouper)
|
|
969
|
+
|
|
970
|
+
def joined(self, a, b):
|
|
971
|
+
"""
|
|
972
|
+
Return whether *a* and *b* are members of the same set.
|
|
973
|
+
"""
|
|
974
|
+
return self._grouper.joined(a, b)
|
|
975
|
+
|
|
976
|
+
def get_siblings(self, a, *, include_self=True):
|
|
977
|
+
"""
|
|
978
|
+
Return all the items joined with *a*.
|
|
979
|
+
|
|
980
|
+
*a* is included in the list if *include_self* is True.
|
|
981
|
+
"""
|
|
982
|
+
return self._grouper.get_siblings(a, include_self=include_self)
|
|
983
|
+
|
|
984
|
+
|
|
985
|
+
def simple_linear_interpolation(a, steps):
|
|
986
|
+
"""
|
|
987
|
+
Resample an array with ``steps - 1`` points between original point pairs.
|
|
988
|
+
|
|
989
|
+
Along each column of *a*, ``(steps - 1)`` points are introduced between
|
|
990
|
+
each original values; the values are linearly interpolated.
|
|
991
|
+
|
|
992
|
+
Parameters
|
|
993
|
+
----------
|
|
994
|
+
a : array, shape (n, ...)
|
|
995
|
+
steps : int
|
|
996
|
+
|
|
997
|
+
Returns
|
|
998
|
+
-------
|
|
999
|
+
array
|
|
1000
|
+
shape ``((n - 1) * steps + 1, ...)``
|
|
1001
|
+
"""
|
|
1002
|
+
fps = a.reshape((len(a), -1))
|
|
1003
|
+
xp = np.arange(len(a)) * steps
|
|
1004
|
+
x = np.arange((len(a) - 1) * steps + 1)
|
|
1005
|
+
return (np.column_stack([np.interp(x, xp, fp) for fp in fps.T])
|
|
1006
|
+
.reshape((len(x),) + a.shape[1:]))
|
|
1007
|
+
|
|
1008
|
+
|
|
1009
|
+
def delete_masked_points(*args):
|
|
1010
|
+
"""
|
|
1011
|
+
Find all masked and/or non-finite points in a set of arguments,
|
|
1012
|
+
and return the arguments with only the unmasked points remaining.
|
|
1013
|
+
|
|
1014
|
+
Arguments can be in any of 5 categories:
|
|
1015
|
+
|
|
1016
|
+
1) 1-D masked arrays
|
|
1017
|
+
2) 1-D ndarrays
|
|
1018
|
+
3) ndarrays with more than one dimension
|
|
1019
|
+
4) other non-string iterables
|
|
1020
|
+
5) anything else
|
|
1021
|
+
|
|
1022
|
+
The first argument must be in one of the first four categories;
|
|
1023
|
+
any argument with a length differing from that of the first
|
|
1024
|
+
argument (and hence anything in category 5) then will be
|
|
1025
|
+
passed through unchanged.
|
|
1026
|
+
|
|
1027
|
+
Masks are obtained from all arguments of the correct length
|
|
1028
|
+
in categories 1, 2, and 4; a point is bad if masked in a masked
|
|
1029
|
+
array or if it is a nan or inf. No attempt is made to
|
|
1030
|
+
extract a mask from categories 2, 3, and 4 if `numpy.isfinite`
|
|
1031
|
+
does not yield a Boolean array.
|
|
1032
|
+
|
|
1033
|
+
All input arguments that are not passed unchanged are returned
|
|
1034
|
+
as ndarrays after removing the points or rows corresponding to
|
|
1035
|
+
masks in any of the arguments.
|
|
1036
|
+
|
|
1037
|
+
A vastly simpler version of this function was originally
|
|
1038
|
+
written as a helper for Axes.scatter().
|
|
1039
|
+
|
|
1040
|
+
"""
|
|
1041
|
+
if not len(args):
|
|
1042
|
+
return ()
|
|
1043
|
+
if is_scalar_or_string(args[0]):
|
|
1044
|
+
raise ValueError("First argument must be a sequence")
|
|
1045
|
+
nrecs = len(args[0])
|
|
1046
|
+
margs = []
|
|
1047
|
+
seqlist = [False] * len(args)
|
|
1048
|
+
for i, x in enumerate(args):
|
|
1049
|
+
if not isinstance(x, str) and np.iterable(x) and len(x) == nrecs:
|
|
1050
|
+
seqlist[i] = True
|
|
1051
|
+
if isinstance(x, np.ma.MaskedArray):
|
|
1052
|
+
if x.ndim > 1:
|
|
1053
|
+
raise ValueError("Masked arrays must be 1-D")
|
|
1054
|
+
else:
|
|
1055
|
+
x = np.asarray(x)
|
|
1056
|
+
margs.append(x)
|
|
1057
|
+
masks = [] # List of masks that are True where good.
|
|
1058
|
+
for i, x in enumerate(margs):
|
|
1059
|
+
if seqlist[i]:
|
|
1060
|
+
if x.ndim > 1:
|
|
1061
|
+
continue # Don't try to get nan locations unless 1-D.
|
|
1062
|
+
if isinstance(x, np.ma.MaskedArray):
|
|
1063
|
+
masks.append(~np.ma.getmaskarray(x)) # invert the mask
|
|
1064
|
+
xd = x.data
|
|
1065
|
+
else:
|
|
1066
|
+
xd = x
|
|
1067
|
+
try:
|
|
1068
|
+
mask = np.isfinite(xd)
|
|
1069
|
+
if isinstance(mask, np.ndarray):
|
|
1070
|
+
masks.append(mask)
|
|
1071
|
+
except (TypeError, ValueError):
|
|
1072
|
+
pass
|
|
1073
|
+
if len(masks):
|
|
1074
|
+
mask = np.logical_and.reduce(masks)
|
|
1075
|
+
igood = mask.nonzero()[0]
|
|
1076
|
+
if len(igood) < nrecs:
|
|
1077
|
+
for i, x in enumerate(margs):
|
|
1078
|
+
if seqlist[i]:
|
|
1079
|
+
margs[i] = x[igood]
|
|
1080
|
+
for i, x in enumerate(margs):
|
|
1081
|
+
if seqlist[i] and isinstance(x, np.ma.MaskedArray):
|
|
1082
|
+
margs[i] = x.filled()
|
|
1083
|
+
return margs
|
|
1084
|
+
|
|
1085
|
+
|
|
1086
|
+
def _combine_masks(*args):
|
|
1087
|
+
"""
|
|
1088
|
+
Find all masked and/or non-finite points in a set of arguments,
|
|
1089
|
+
and return the arguments as masked arrays with a common mask.
|
|
1090
|
+
|
|
1091
|
+
Arguments can be in any of 5 categories:
|
|
1092
|
+
|
|
1093
|
+
1) 1-D masked arrays
|
|
1094
|
+
2) 1-D ndarrays
|
|
1095
|
+
3) ndarrays with more than one dimension
|
|
1096
|
+
4) other non-string iterables
|
|
1097
|
+
5) anything else
|
|
1098
|
+
|
|
1099
|
+
The first argument must be in one of the first four categories;
|
|
1100
|
+
any argument with a length differing from that of the first
|
|
1101
|
+
argument (and hence anything in category 5) then will be
|
|
1102
|
+
passed through unchanged.
|
|
1103
|
+
|
|
1104
|
+
Masks are obtained from all arguments of the correct length
|
|
1105
|
+
in categories 1, 2, and 4; a point is bad if masked in a masked
|
|
1106
|
+
array or if it is a nan or inf. No attempt is made to
|
|
1107
|
+
extract a mask from categories 2 and 4 if `numpy.isfinite`
|
|
1108
|
+
does not yield a Boolean array. Category 3 is included to
|
|
1109
|
+
support RGB or RGBA ndarrays, which are assumed to have only
|
|
1110
|
+
valid values and which are passed through unchanged.
|
|
1111
|
+
|
|
1112
|
+
All input arguments that are not passed unchanged are returned
|
|
1113
|
+
as masked arrays if any masked points are found, otherwise as
|
|
1114
|
+
ndarrays.
|
|
1115
|
+
|
|
1116
|
+
"""
|
|
1117
|
+
if not len(args):
|
|
1118
|
+
return ()
|
|
1119
|
+
if is_scalar_or_string(args[0]):
|
|
1120
|
+
raise ValueError("First argument must be a sequence")
|
|
1121
|
+
nrecs = len(args[0])
|
|
1122
|
+
margs = [] # Output args; some may be modified.
|
|
1123
|
+
seqlist = [False] * len(args) # Flags: True if output will be masked.
|
|
1124
|
+
masks = [] # List of masks.
|
|
1125
|
+
for i, x in enumerate(args):
|
|
1126
|
+
if is_scalar_or_string(x) or len(x) != nrecs:
|
|
1127
|
+
margs.append(x) # Leave it unmodified.
|
|
1128
|
+
else:
|
|
1129
|
+
if isinstance(x, np.ma.MaskedArray) and x.ndim > 1:
|
|
1130
|
+
raise ValueError("Masked arrays must be 1-D")
|
|
1131
|
+
try:
|
|
1132
|
+
x = np.asanyarray(x)
|
|
1133
|
+
except (VisibleDeprecationWarning, ValueError):
|
|
1134
|
+
# NumPy 1.19 raises a warning about ragged arrays, but we want
|
|
1135
|
+
# to accept basically anything here.
|
|
1136
|
+
x = np.asanyarray(x, dtype=object)
|
|
1137
|
+
if x.ndim == 1:
|
|
1138
|
+
x = safe_masked_invalid(x)
|
|
1139
|
+
seqlist[i] = True
|
|
1140
|
+
if np.ma.is_masked(x):
|
|
1141
|
+
masks.append(np.ma.getmaskarray(x))
|
|
1142
|
+
margs.append(x) # Possibly modified.
|
|
1143
|
+
if len(masks):
|
|
1144
|
+
mask = np.logical_or.reduce(masks)
|
|
1145
|
+
for i, x in enumerate(margs):
|
|
1146
|
+
if seqlist[i]:
|
|
1147
|
+
margs[i] = np.ma.array(x, mask=mask)
|
|
1148
|
+
return margs
|
|
1149
|
+
|
|
1150
|
+
|
|
1151
|
+
def _broadcast_with_masks(*args, compress=False):
|
|
1152
|
+
"""
|
|
1153
|
+
Broadcast inputs, combining all masked arrays.
|
|
1154
|
+
|
|
1155
|
+
Parameters
|
|
1156
|
+
----------
|
|
1157
|
+
*args : array-like
|
|
1158
|
+
The inputs to broadcast.
|
|
1159
|
+
compress : bool, default: False
|
|
1160
|
+
Whether to compress the masked arrays. If False, the masked values
|
|
1161
|
+
are replaced by NaNs.
|
|
1162
|
+
|
|
1163
|
+
Returns
|
|
1164
|
+
-------
|
|
1165
|
+
list of array-like
|
|
1166
|
+
The broadcasted and masked inputs.
|
|
1167
|
+
"""
|
|
1168
|
+
# extract the masks, if any
|
|
1169
|
+
masks = [k.mask for k in args if isinstance(k, np.ma.MaskedArray)]
|
|
1170
|
+
# broadcast to match the shape
|
|
1171
|
+
bcast = np.broadcast_arrays(*args, *masks)
|
|
1172
|
+
inputs = bcast[:len(args)]
|
|
1173
|
+
masks = bcast[len(args):]
|
|
1174
|
+
if masks:
|
|
1175
|
+
# combine the masks into one
|
|
1176
|
+
mask = np.logical_or.reduce(masks)
|
|
1177
|
+
# put mask on and compress
|
|
1178
|
+
if compress:
|
|
1179
|
+
inputs = [np.ma.array(k, mask=mask).compressed()
|
|
1180
|
+
for k in inputs]
|
|
1181
|
+
else:
|
|
1182
|
+
inputs = [np.ma.array(k, mask=mask, dtype=float).filled(np.nan).ravel()
|
|
1183
|
+
for k in inputs]
|
|
1184
|
+
else:
|
|
1185
|
+
inputs = [np.ravel(k) for k in inputs]
|
|
1186
|
+
return inputs
|
|
1187
|
+
|
|
1188
|
+
|
|
1189
|
+
def _gc_paused(func):
|
|
1190
|
+
"""
|
|
1191
|
+
Run *func* with the cyclic garbage collector paused (and then restored).
|
|
1192
|
+
|
|
1193
|
+
Creating tens of thousands of artists (e.g. by boxplot) otherwise triggers
|
|
1194
|
+
many collections, each traversing all the live artists created so far;
|
|
1195
|
+
the collector only runs later instead.
|
|
1196
|
+
"""
|
|
1197
|
+
import gc
|
|
1198
|
+
|
|
1199
|
+
@functools.wraps(func)
|
|
1200
|
+
def wrapper(*args, **kwargs):
|
|
1201
|
+
enabled = gc.isenabled()
|
|
1202
|
+
gc.disable()
|
|
1203
|
+
try:
|
|
1204
|
+
return func(*args, **kwargs)
|
|
1205
|
+
finally:
|
|
1206
|
+
if enabled:
|
|
1207
|
+
gc.enable()
|
|
1208
|
+
return wrapper
|
|
1209
|
+
|
|
1210
|
+
|
|
1211
|
+
def _fills_when_read(cls):
|
|
1212
|
+
"""
|
|
1213
|
+
Class decorator for a list whose items are made when they are first
|
|
1214
|
+
needed: every way to read or change the list calls ``cls._fill`` first,
|
|
1215
|
+
except ``len`` (and what the class defines itself).
|
|
1216
|
+
"""
|
|
1217
|
+
def filled(name):
|
|
1218
|
+
method = getattr(list, name)
|
|
1219
|
+
|
|
1220
|
+
@functools.wraps(method)
|
|
1221
|
+
def wrapper(self, *args, **kwargs):
|
|
1222
|
+
self._fill()
|
|
1223
|
+
return method(self, *args, **kwargs)
|
|
1224
|
+
|
|
1225
|
+
return wrapper
|
|
1226
|
+
|
|
1227
|
+
def filled_both(name):
|
|
1228
|
+
# (list's own methods read the items of another list directly)
|
|
1229
|
+
method = getattr(list, name)
|
|
1230
|
+
|
|
1231
|
+
@functools.wraps(method)
|
|
1232
|
+
def wrapper(self, other):
|
|
1233
|
+
self._fill()
|
|
1234
|
+
fill = getattr(other, "_fill", None)
|
|
1235
|
+
if fill is not None:
|
|
1236
|
+
fill()
|
|
1237
|
+
return method(self, other)
|
|
1238
|
+
|
|
1239
|
+
return wrapper
|
|
1240
|
+
|
|
1241
|
+
def __radd__(self, other):
|
|
1242
|
+
# (``[...] + self``, which list would do by reading the items directly)
|
|
1243
|
+
self._fill()
|
|
1244
|
+
if isinstance(other, list):
|
|
1245
|
+
return other + list.copy(self)
|
|
1246
|
+
return NotImplemented
|
|
1247
|
+
|
|
1248
|
+
for name in ("__iter__", "__getitem__", "__setitem__", "__delitem__", "__contains__",
|
|
1249
|
+
"__reversed__", "__mul__", "__rmul__", "__imul__", "__repr__",
|
|
1250
|
+
"__sizeof__", "append", "extend", "insert", "remove", "pop", "clear",
|
|
1251
|
+
"index", "count", "sort", "reverse", "copy"):
|
|
1252
|
+
if name not in cls.__dict__:
|
|
1253
|
+
setattr(cls, name, filled(name))
|
|
1254
|
+
for name in ("__eq__", "__ne__", "__lt__", "__le__", "__gt__", "__ge__", "__add__", "__iadd__"):
|
|
1255
|
+
if name not in cls.__dict__:
|
|
1256
|
+
setattr(cls, name, filled_both(name))
|
|
1257
|
+
if "__radd__" not in cls.__dict__:
|
|
1258
|
+
cls.__radd__ = __radd__
|
|
1259
|
+
return cls
|
|
1260
|
+
|
|
1261
|
+
|
|
1262
|
+
@_fills_when_read
|
|
1263
|
+
class _BoxplotStats(list):
|
|
1264
|
+
"""
|
|
1265
|
+
The statistics of `boxplot_stats` for a regular float array, kept as
|
|
1266
|
+
arrays: ``columns[key][i]`` is ``self[i][key]``, the fliers of box *i* are
|
|
1267
|
+
the next ``counts[i]`` of ``fliers`` and its label is ``labels[i]``
|
|
1268
|
+
(*labels* may be None, as its items).
|
|
1269
|
+
|
|
1270
|
+
The dicts are made when the list is first read; the arrays are dropped
|
|
1271
|
+
then (``columns`` is None), as the dicts may be changed. Only
|
|
1272
|
+
`.Axes.boxplot` gets such a list, which it passes on to `.Axes.bxp`.
|
|
1273
|
+
"""
|
|
1274
|
+
|
|
1275
|
+
__slots__ = ("columns", "fliers", "counts", "labels", "_n")
|
|
1276
|
+
|
|
1277
|
+
def __init__(self, columns, fliers, counts, labels):
|
|
1278
|
+
super().__init__()
|
|
1279
|
+
self.columns = columns
|
|
1280
|
+
self.fliers = fliers
|
|
1281
|
+
self.counts = counts
|
|
1282
|
+
self.labels = labels
|
|
1283
|
+
self._n = len(counts)
|
|
1284
|
+
|
|
1285
|
+
def __len__(self):
|
|
1286
|
+
return self._n if self.columns is not None else list.__len__(self)
|
|
1287
|
+
|
|
1288
|
+
def __reduce_ex__(self, protocol):
|
|
1289
|
+
self._fill()
|
|
1290
|
+
return (list, (list(self),))
|
|
1291
|
+
|
|
1292
|
+
def _fill(self):
|
|
1293
|
+
columns = self.columns
|
|
1294
|
+
if columns is None:
|
|
1295
|
+
return
|
|
1296
|
+
self.columns = None
|
|
1297
|
+
labels = self.labels
|
|
1298
|
+
fliers = [f.copy() for f in np.split(self.fliers, np.cumsum(self.counts)[:-1])]
|
|
1299
|
+
keys = ('mean', 'iqr', 'cilo', 'cihi', 'whishi', 'whislo', 'fliers', 'q1', 'med', 'q3')
|
|
1300
|
+
values = [fliers if key == 'fliers' else columns[key] for key in keys]
|
|
1301
|
+
result = []
|
|
1302
|
+
for i, stat in enumerate(zip(*values)):
|
|
1303
|
+
stats = {}
|
|
1304
|
+
if labels is not None and labels[i] is not None:
|
|
1305
|
+
stats['label'] = labels[i]
|
|
1306
|
+
stats.update(zip(keys, stat))
|
|
1307
|
+
result.append(stats)
|
|
1308
|
+
list.extend(self, result)
|
|
1309
|
+
|
|
1310
|
+
|
|
1311
|
+
def _boxplot_stats_dense(X, whis, labels):
|
|
1312
|
+
"""The regular finite float64 case, with the same per-column arithmetic.
|
|
1313
|
+
|
|
1314
|
+
Keep each sample contiguous so mean/percentile use the same reduction
|
|
1315
|
+
and interpolation order as the individual 1-D arrays in boxplot_stats.
|
|
1316
|
+
"""
|
|
1317
|
+
columns = np.ascontiguousarray(X.T)
|
|
1318
|
+
ncols, nsamples = columns.shape
|
|
1319
|
+
if labels is not None and len(labels) != ncols:
|
|
1320
|
+
raise ValueError(f"The number of labels ({len(labels)}) must match the"
|
|
1321
|
+
f" number of columns ({ncols}).")
|
|
1322
|
+
q1, med, q3 = np.percentile(columns, [25, 50, 75], axis=1)
|
|
1323
|
+
means = np.mean(columns, axis=1)
|
|
1324
|
+
iqr = q3 - q1
|
|
1325
|
+
delta = 1.57 * iqr / np.sqrt(nsamples)
|
|
1326
|
+
cilo, cihi = med - delta, med + delta
|
|
1327
|
+
loval, hival = q1 - whis * iqr, q3 + whis * iqr
|
|
1328
|
+
lo = np.min(columns, axis=1, where=columns >= loval[:, None], initial=np.inf)
|
|
1329
|
+
hi = np.max(columns, axis=1, where=columns <= hival[:, None], initial=-np.inf)
|
|
1330
|
+
lo = np.where((lo == np.inf) | (lo > q1), q1, lo)
|
|
1331
|
+
hi = np.where((hi == -np.inf) | (hi < q3), q3, hi)
|
|
1332
|
+
# The fliers of each column: those below lo, then those above hi, each
|
|
1333
|
+
# in sample order (as concatenating x[x < lo] and x[x > hi]).
|
|
1334
|
+
low = columns < lo[:, None]
|
|
1335
|
+
high = columns > hi[:, None]
|
|
1336
|
+
rows, cols = np.nonzero(low | high)
|
|
1337
|
+
order = np.lexsort((cols, high[rows, cols], rows))
|
|
1338
|
+
values = columns[rows[order], cols[order]]
|
|
1339
|
+
counts = np.bincount(rows, minlength=ncols)
|
|
1340
|
+
return _BoxplotStats(
|
|
1341
|
+
dict(mean=means, iqr=iqr, cilo=cilo, cihi=cihi, whishi=hi, whislo=lo,
|
|
1342
|
+
q1=q1, med=med, q3=q3),
|
|
1343
|
+
values, counts, labels)
|
|
1344
|
+
|
|
1345
|
+
|
|
1346
|
+
def _boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False):
|
|
1347
|
+
"""`boxplot_stats`, as a `_BoxplotStats` where it can be one."""
|
|
1348
|
+
if (type(X) is np.ndarray and X.ndim == 2 and X.dtype == np.float64
|
|
1349
|
+
and X.shape[0] and X.shape[1] > 1 and bootstrap is None
|
|
1350
|
+
and not autorange and isinstance(whis, numbers.Real)
|
|
1351
|
+
and np.isfinite(X).all()):
|
|
1352
|
+
return _boxplot_stats_dense(X, whis, labels)
|
|
1353
|
+
return boxplot_stats(X, whis=whis, bootstrap=bootstrap, labels=labels,
|
|
1354
|
+
autorange=autorange)
|
|
1355
|
+
|
|
1356
|
+
|
|
1357
|
+
def boxplot_stats(X, whis=1.5, bootstrap=None, labels=None, autorange=False):
|
|
1358
|
+
r"""
|
|
1359
|
+
Return a list of dictionaries of statistics used to draw a series of box
|
|
1360
|
+
and whisker plots using `~.Axes.bxp`.
|
|
1361
|
+
|
|
1362
|
+
Parameters
|
|
1363
|
+
----------
|
|
1364
|
+
X : array-like
|
|
1365
|
+
Data that will be represented in the boxplots. Should have 2 or
|
|
1366
|
+
fewer dimensions.
|
|
1367
|
+
|
|
1368
|
+
whis : float or (float, float), default: 1.5
|
|
1369
|
+
The position of the whiskers.
|
|
1370
|
+
|
|
1371
|
+
If a float, the lower whisker is at the lowest datum above
|
|
1372
|
+
``Q1 - whis*(Q3-Q1)``, and the upper whisker at the highest datum below
|
|
1373
|
+
``Q3 + whis*(Q3-Q1)``, where Q1 and Q3 are the first and third
|
|
1374
|
+
quartiles. The default value of ``whis = 1.5`` corresponds to Tukey's
|
|
1375
|
+
original definition of boxplots.
|
|
1376
|
+
|
|
1377
|
+
If a pair of floats, they indicate the percentiles at which to draw the
|
|
1378
|
+
whiskers (e.g., (5, 95)). In particular, setting this to (0, 100)
|
|
1379
|
+
results in whiskers covering the whole range of the data.
|
|
1380
|
+
|
|
1381
|
+
In the edge case where ``Q1 == Q3``, *whis* is automatically set to
|
|
1382
|
+
(0, 100) (cover the whole range of the data) if *autorange* is True.
|
|
1383
|
+
|
|
1384
|
+
Beyond the whiskers, data are considered outliers and are plotted as
|
|
1385
|
+
individual points.
|
|
1386
|
+
|
|
1387
|
+
bootstrap : int, optional
|
|
1388
|
+
Number of times the confidence intervals around the median
|
|
1389
|
+
should be bootstrapped (percentile method).
|
|
1390
|
+
|
|
1391
|
+
labels : list of str, optional
|
|
1392
|
+
Labels for each dataset. Length must be compatible with
|
|
1393
|
+
dimensions of *X*.
|
|
1394
|
+
|
|
1395
|
+
autorange : bool, optional (False)
|
|
1396
|
+
When `True` and the data are distributed such that the 25th and 75th
|
|
1397
|
+
percentiles are equal, ``whis`` is set to (0, 100) such that the
|
|
1398
|
+
whisker ends are at the minimum and maximum of the data.
|
|
1399
|
+
|
|
1400
|
+
Returns
|
|
1401
|
+
-------
|
|
1402
|
+
list of dict
|
|
1403
|
+
A list of dictionaries containing the results for each column
|
|
1404
|
+
of data. Keys of each dictionary are the following:
|
|
1405
|
+
|
|
1406
|
+
======== ===================================
|
|
1407
|
+
Key Value Description
|
|
1408
|
+
======== ===================================
|
|
1409
|
+
label tick label for the boxplot
|
|
1410
|
+
mean arithmetic mean value
|
|
1411
|
+
med 50th percentile
|
|
1412
|
+
q1 first quartile (25th percentile)
|
|
1413
|
+
q3 third quartile (75th percentile)
|
|
1414
|
+
iqr interquartile range
|
|
1415
|
+
cilo lower notch around the median
|
|
1416
|
+
cihi upper notch around the median
|
|
1417
|
+
whislo end of the lower whisker
|
|
1418
|
+
whishi end of the upper whisker
|
|
1419
|
+
fliers outliers
|
|
1420
|
+
======== ===================================
|
|
1421
|
+
|
|
1422
|
+
Notes
|
|
1423
|
+
-----
|
|
1424
|
+
Non-bootstrapping approach to confidence interval uses Gaussian-based
|
|
1425
|
+
asymptotic approximation:
|
|
1426
|
+
|
|
1427
|
+
.. math::
|
|
1428
|
+
|
|
1429
|
+
\mathrm{med} \pm 1.57 \times \frac{\mathrm{iqr}}{\sqrt{N}}
|
|
1430
|
+
|
|
1431
|
+
General approach from:
|
|
1432
|
+
McGill, R., Tukey, J.W., and Larsen, W.A. (1978) "Variations of
|
|
1433
|
+
Boxplots", The American Statistician, 32:12-16.
|
|
1434
|
+
"""
|
|
1435
|
+
|
|
1436
|
+
if (type(X) is np.ndarray and X.ndim == 2 and X.dtype == np.float64
|
|
1437
|
+
and X.shape[0] and X.shape[1] > 1 and bootstrap is None
|
|
1438
|
+
and not autorange and isinstance(whis, numbers.Real)
|
|
1439
|
+
and np.isfinite(X).all()):
|
|
1440
|
+
return list(_boxplot_stats_dense(X, whis, labels))
|
|
1441
|
+
|
|
1442
|
+
def _bootstrap_median(data, N=5000):
|
|
1443
|
+
# determine 95% confidence intervals of the median
|
|
1444
|
+
M = len(data)
|
|
1445
|
+
percentiles = [2.5, 97.5]
|
|
1446
|
+
|
|
1447
|
+
bs_index = np.random.randint(M, size=(N, M))
|
|
1448
|
+
bsData = data[bs_index]
|
|
1449
|
+
estimate = np.median(bsData, axis=1, overwrite_input=True)
|
|
1450
|
+
|
|
1451
|
+
CI = np.percentile(estimate, percentiles)
|
|
1452
|
+
return CI
|
|
1453
|
+
|
|
1454
|
+
def _compute_conf_interval(data, med, iqr, bootstrap):
|
|
1455
|
+
if bootstrap is not None:
|
|
1456
|
+
# Do a bootstrap estimate of notch locations.
|
|
1457
|
+
# get conf. intervals around median
|
|
1458
|
+
CI = _bootstrap_median(data, N=bootstrap)
|
|
1459
|
+
notch_min = CI[0]
|
|
1460
|
+
notch_max = CI[1]
|
|
1461
|
+
else:
|
|
1462
|
+
|
|
1463
|
+
N = len(data)
|
|
1464
|
+
notch_min = med - 1.57 * iqr / np.sqrt(N)
|
|
1465
|
+
notch_max = med + 1.57 * iqr / np.sqrt(N)
|
|
1466
|
+
|
|
1467
|
+
return notch_min, notch_max
|
|
1468
|
+
|
|
1469
|
+
# output is a list of dicts
|
|
1470
|
+
bxpstats = []
|
|
1471
|
+
|
|
1472
|
+
# convert X to a list of lists
|
|
1473
|
+
X = _reshape_2D(X, "X")
|
|
1474
|
+
|
|
1475
|
+
ncols = len(X)
|
|
1476
|
+
if labels is None:
|
|
1477
|
+
labels = itertools.repeat(None)
|
|
1478
|
+
elif len(labels) != ncols:
|
|
1479
|
+
raise ValueError(f"The number of labels ({len(labels)}) must match the"
|
|
1480
|
+
f" number of columns ({ncols}).")
|
|
1481
|
+
|
|
1482
|
+
input_whis = whis
|
|
1483
|
+
for ii, (x, label) in enumerate(zip(X, labels)):
|
|
1484
|
+
|
|
1485
|
+
# empty dict
|
|
1486
|
+
stats = {}
|
|
1487
|
+
if label is not None:
|
|
1488
|
+
stats['label'] = label
|
|
1489
|
+
|
|
1490
|
+
# restore whis to the input values in case it got changed in the loop
|
|
1491
|
+
whis = input_whis
|
|
1492
|
+
|
|
1493
|
+
# note tricksiness, append up here and then mutate below
|
|
1494
|
+
bxpstats.append(stats)
|
|
1495
|
+
|
|
1496
|
+
# if empty, bail
|
|
1497
|
+
if len(x) == 0:
|
|
1498
|
+
stats['fliers'] = np.array([])
|
|
1499
|
+
stats['mean'] = np.nan
|
|
1500
|
+
stats['med'] = np.nan
|
|
1501
|
+
stats['q1'] = np.nan
|
|
1502
|
+
stats['q3'] = np.nan
|
|
1503
|
+
stats['iqr'] = np.nan
|
|
1504
|
+
stats['cilo'] = np.nan
|
|
1505
|
+
stats['cihi'] = np.nan
|
|
1506
|
+
stats['whislo'] = np.nan
|
|
1507
|
+
stats['whishi'] = np.nan
|
|
1508
|
+
continue
|
|
1509
|
+
|
|
1510
|
+
# up-convert to an array, just to be safe
|
|
1511
|
+
x = np.ma.asarray(x)
|
|
1512
|
+
x = x.data[~x.mask].ravel()
|
|
1513
|
+
|
|
1514
|
+
# arithmetic mean
|
|
1515
|
+
stats['mean'] = np.mean(x)
|
|
1516
|
+
|
|
1517
|
+
# medians and quartiles
|
|
1518
|
+
q1, med, q3 = np.percentile(x, [25, 50, 75])
|
|
1519
|
+
|
|
1520
|
+
# interquartile range
|
|
1521
|
+
stats['iqr'] = q3 - q1
|
|
1522
|
+
if stats['iqr'] == 0 and autorange:
|
|
1523
|
+
whis = (0, 100)
|
|
1524
|
+
|
|
1525
|
+
# conf. interval around median
|
|
1526
|
+
stats['cilo'], stats['cihi'] = _compute_conf_interval(
|
|
1527
|
+
x, med, stats['iqr'], bootstrap
|
|
1528
|
+
)
|
|
1529
|
+
|
|
1530
|
+
# lowest/highest non-outliers
|
|
1531
|
+
if np.iterable(whis) and not isinstance(whis, str):
|
|
1532
|
+
loval, hival = np.percentile(x, whis)
|
|
1533
|
+
elif np.isreal(whis):
|
|
1534
|
+
loval = q1 - whis * stats['iqr']
|
|
1535
|
+
hival = q3 + whis * stats['iqr']
|
|
1536
|
+
else:
|
|
1537
|
+
raise ValueError('whis must be a float or list of percentiles')
|
|
1538
|
+
|
|
1539
|
+
# get high extreme
|
|
1540
|
+
wiskhi = x[x <= hival]
|
|
1541
|
+
if len(wiskhi) == 0 or np.max(wiskhi) < q3:
|
|
1542
|
+
stats['whishi'] = q3
|
|
1543
|
+
else:
|
|
1544
|
+
stats['whishi'] = np.max(wiskhi)
|
|
1545
|
+
|
|
1546
|
+
# get low extreme
|
|
1547
|
+
wisklo = x[x >= loval]
|
|
1548
|
+
if len(wisklo) == 0 or np.min(wisklo) > q1:
|
|
1549
|
+
stats['whislo'] = q1
|
|
1550
|
+
else:
|
|
1551
|
+
stats['whislo'] = np.min(wisklo)
|
|
1552
|
+
|
|
1553
|
+
# compute a single array of outliers
|
|
1554
|
+
stats['fliers'] = np.concatenate([
|
|
1555
|
+
x[x < stats['whislo']],
|
|
1556
|
+
x[x > stats['whishi']],
|
|
1557
|
+
])
|
|
1558
|
+
|
|
1559
|
+
# add in the remaining stats
|
|
1560
|
+
stats['q1'], stats['med'], stats['q3'] = q1, med, q3
|
|
1561
|
+
|
|
1562
|
+
return bxpstats
|
|
1563
|
+
|
|
1564
|
+
|
|
1565
|
+
#: Maps short codes for line style to their full name used by backends.
|
|
1566
|
+
ls_mapper = {'-': 'solid', '--': 'dashed', '-.': 'dashdot', ':': 'dotted'}
|
|
1567
|
+
#: Maps full names for line styles used by backends to their short codes.
|
|
1568
|
+
ls_mapper_r = {v: k for k, v in ls_mapper.items()}
|
|
1569
|
+
|
|
1570
|
+
|
|
1571
|
+
def contiguous_regions(mask):
|
|
1572
|
+
"""
|
|
1573
|
+
Return a list of (ind0, ind1) such that ``mask[ind0:ind1].all()`` is
|
|
1574
|
+
True and we cover all such regions.
|
|
1575
|
+
"""
|
|
1576
|
+
mask = np.asarray(mask, dtype=bool)
|
|
1577
|
+
|
|
1578
|
+
if not mask.size:
|
|
1579
|
+
return []
|
|
1580
|
+
|
|
1581
|
+
# Find the indices of region changes, and correct offset
|
|
1582
|
+
idx, = np.nonzero(mask[:-1] != mask[1:])
|
|
1583
|
+
idx += 1
|
|
1584
|
+
|
|
1585
|
+
# List operations are faster for moderately sized arrays
|
|
1586
|
+
idx = idx.tolist()
|
|
1587
|
+
|
|
1588
|
+
# Add first and/or last index if needed
|
|
1589
|
+
if mask[0]:
|
|
1590
|
+
idx = [0] + idx
|
|
1591
|
+
if mask[-1]:
|
|
1592
|
+
idx.append(len(mask))
|
|
1593
|
+
|
|
1594
|
+
return list(zip(idx[::2], idx[1::2]))
|
|
1595
|
+
|
|
1596
|
+
|
|
1597
|
+
def is_math_text(s):
|
|
1598
|
+
"""
|
|
1599
|
+
Return whether the string *s* contains math expressions.
|
|
1600
|
+
|
|
1601
|
+
This is done by checking whether *s* contains an even number of
|
|
1602
|
+
non-escaped dollar signs.
|
|
1603
|
+
"""
|
|
1604
|
+
s = str(s)
|
|
1605
|
+
dollar_count = s.count(r'$') - s.count(r'\$')
|
|
1606
|
+
even_dollars = (dollar_count > 0 and dollar_count % 2 == 0)
|
|
1607
|
+
return even_dollars
|
|
1608
|
+
|
|
1609
|
+
|
|
1610
|
+
def _to_unmasked_float_array(x):
|
|
1611
|
+
"""
|
|
1612
|
+
Convert a sequence to a float array; if input was a masked array, masked
|
|
1613
|
+
values are converted to nans.
|
|
1614
|
+
"""
|
|
1615
|
+
if hasattr(x, 'mask'):
|
|
1616
|
+
return np.ma.asanyarray(x, float).filled(np.nan)
|
|
1617
|
+
else:
|
|
1618
|
+
return np.asanyarray(x, float)
|
|
1619
|
+
|
|
1620
|
+
|
|
1621
|
+
def _check_1d(x):
|
|
1622
|
+
"""Convert scalars to 1D arrays; pass-through arrays as is."""
|
|
1623
|
+
# Unpack in case of e.g. Pandas or xarray object
|
|
1624
|
+
x = _unpack_to_numpy(x)
|
|
1625
|
+
# plot requires `shape` and `ndim`. If passed an
|
|
1626
|
+
# object that doesn't provide them, then force to numpy array.
|
|
1627
|
+
# Note this will strip unit information.
|
|
1628
|
+
if (not hasattr(x, 'shape') or
|
|
1629
|
+
not hasattr(x, 'ndim') or
|
|
1630
|
+
len(x.shape) < 1):
|
|
1631
|
+
return np.atleast_1d(x)
|
|
1632
|
+
else:
|
|
1633
|
+
return x
|
|
1634
|
+
|
|
1635
|
+
|
|
1636
|
+
def _reshape_2D(X, name):
|
|
1637
|
+
"""
|
|
1638
|
+
Use Fortran ordering to convert ndarrays and lists of iterables to lists of
|
|
1639
|
+
1D arrays.
|
|
1640
|
+
|
|
1641
|
+
Lists of iterables are converted by applying `numpy.asanyarray` to each of
|
|
1642
|
+
their elements. 1D ndarrays are returned in a singleton list containing
|
|
1643
|
+
them. 2D ndarrays are converted to the list of their *columns*.
|
|
1644
|
+
|
|
1645
|
+
*name* is used to generate the error message for invalid inputs.
|
|
1646
|
+
"""
|
|
1647
|
+
|
|
1648
|
+
# Unpack in case of e.g. Pandas or xarray object
|
|
1649
|
+
X = _unpack_to_numpy(X)
|
|
1650
|
+
|
|
1651
|
+
# Iterate over columns for ndarrays.
|
|
1652
|
+
if isinstance(X, np.ndarray):
|
|
1653
|
+
X = X.transpose()
|
|
1654
|
+
|
|
1655
|
+
if len(X) == 0:
|
|
1656
|
+
return [[]]
|
|
1657
|
+
elif X.ndim == 1 and np.ndim(X[0]) == 0:
|
|
1658
|
+
# 1D array of scalars: directly return it.
|
|
1659
|
+
return [X]
|
|
1660
|
+
elif X.ndim in [1, 2]:
|
|
1661
|
+
# 2D array, or 1D array of iterables: flatten them first.
|
|
1662
|
+
return [np.reshape(x, -1) for x in X]
|
|
1663
|
+
else:
|
|
1664
|
+
raise ValueError(f'{name} must have 2 or fewer dimensions')
|
|
1665
|
+
|
|
1666
|
+
# Iterate over list of iterables.
|
|
1667
|
+
if len(X) == 0:
|
|
1668
|
+
return [[]]
|
|
1669
|
+
|
|
1670
|
+
result = []
|
|
1671
|
+
is_1d = True
|
|
1672
|
+
for xi in X:
|
|
1673
|
+
# check if this is iterable, except for strings which we
|
|
1674
|
+
# treat as singletons.
|
|
1675
|
+
if not isinstance(xi, str):
|
|
1676
|
+
try:
|
|
1677
|
+
iter(xi)
|
|
1678
|
+
except TypeError:
|
|
1679
|
+
pass
|
|
1680
|
+
else:
|
|
1681
|
+
is_1d = False
|
|
1682
|
+
xi = np.asanyarray(xi)
|
|
1683
|
+
nd = np.ndim(xi)
|
|
1684
|
+
if nd > 1:
|
|
1685
|
+
raise ValueError(f'{name} must have 2 or fewer dimensions')
|
|
1686
|
+
result.append(xi.reshape(-1))
|
|
1687
|
+
|
|
1688
|
+
if is_1d:
|
|
1689
|
+
# 1D array of scalars: directly return it.
|
|
1690
|
+
return [np.reshape(result, -1)]
|
|
1691
|
+
else:
|
|
1692
|
+
# 2D array, or 1D array of iterables: use flattened version.
|
|
1693
|
+
return result
|
|
1694
|
+
|
|
1695
|
+
|
|
1696
|
+
def violin_stats(X, method=("GaussianKDE", "scott"), points=100, quantiles=None):
|
|
1697
|
+
"""
|
|
1698
|
+
Return a list of dictionaries of data which can be used to draw a series
|
|
1699
|
+
of violin plots.
|
|
1700
|
+
|
|
1701
|
+
See the ``Returns`` section below to view the required keys of the
|
|
1702
|
+
dictionary.
|
|
1703
|
+
|
|
1704
|
+
Users can skip this function and pass a user-defined set of dictionaries
|
|
1705
|
+
with the same keys to `~.axes.Axes.violin` instead of using Matplotlib
|
|
1706
|
+
to do the calculations. See the *Returns* section below for the keys
|
|
1707
|
+
that must be present in the dictionaries.
|
|
1708
|
+
|
|
1709
|
+
Parameters
|
|
1710
|
+
----------
|
|
1711
|
+
X : 1D array or sequence of 1D arrays or 2D array
|
|
1712
|
+
Sample data that will be used to produce the gaussian kernel density
|
|
1713
|
+
estimates. Non-finite and masked values are ignored.
|
|
1714
|
+
Possible values:
|
|
1715
|
+
|
|
1716
|
+
- 1D array: Statistics are computed for that array.
|
|
1717
|
+
- sequence of 1D arrays: Statistics are computed for each array in the sequence.
|
|
1718
|
+
- 2D array: Statistics are computed for each column in the array.
|
|
1719
|
+
|
|
1720
|
+
method : (name, bw_method) or callable,
|
|
1721
|
+
The method used to calculate the kernel density estimate for each
|
|
1722
|
+
column of data. Valid values:
|
|
1723
|
+
|
|
1724
|
+
- a tuple of the form ``(name, bw_method)`` where *name* currently must
|
|
1725
|
+
always be ``"GaussianKDE"`` and *bw_method* is the method used to
|
|
1726
|
+
calculate the estimator bandwidth. Supported values are 'scott',
|
|
1727
|
+
'silverman' or a float or a callable. If a float, this will be used
|
|
1728
|
+
directly as `!kde.factor`. If a callable, it should take a
|
|
1729
|
+
`matplotlib.mlab.GaussianKDE` instance as its only parameter and
|
|
1730
|
+
return a float.
|
|
1731
|
+
|
|
1732
|
+
- a callable with the signature ::
|
|
1733
|
+
|
|
1734
|
+
def method(data: ndarray, coords: ndarray) -> ndarray
|
|
1735
|
+
|
|
1736
|
+
It should return the KDE of *data* evaluated at *coords*.
|
|
1737
|
+
|
|
1738
|
+
.. versionadded:: 3.11
|
|
1739
|
+
Support for ``(name, bw_method)`` tuple.
|
|
1740
|
+
|
|
1741
|
+
points : int, default: 100
|
|
1742
|
+
Defines the number of points to evaluate each of the gaussian kernel
|
|
1743
|
+
density estimates at.
|
|
1744
|
+
|
|
1745
|
+
quantiles : array-like, default: None
|
|
1746
|
+
Defines (if not None) a list of floats in interval [0, 1] for each
|
|
1747
|
+
column of data, which represents the quantiles that will be rendered
|
|
1748
|
+
for that column of data. Must have 2 or fewer dimensions. 1D array will
|
|
1749
|
+
be treated as a singleton list containing them.
|
|
1750
|
+
|
|
1751
|
+
Returns
|
|
1752
|
+
-------
|
|
1753
|
+
list of dict
|
|
1754
|
+
A list of dictionaries containing the results for each column of data.
|
|
1755
|
+
The dictionaries contain at least the following:
|
|
1756
|
+
|
|
1757
|
+
- coords: A list of scalars containing the coordinates this particular
|
|
1758
|
+
kernel density estimate was evaluated at.
|
|
1759
|
+
- vals: A list of scalars containing the values of the kernel density
|
|
1760
|
+
estimate at each of the coordinates given in *coords*.
|
|
1761
|
+
- mean: The mean value for this column of data.
|
|
1762
|
+
- median: The median value for this column of data.
|
|
1763
|
+
- min: The minimum value for this column of data.
|
|
1764
|
+
- max: The maximum value for this column of data.
|
|
1765
|
+
- quantiles: The quantile values for this column of data.
|
|
1766
|
+
"""
|
|
1767
|
+
if isinstance(method, tuple):
|
|
1768
|
+
name, bw_method = method
|
|
1769
|
+
if name != "GaussianKDE":
|
|
1770
|
+
raise ValueError(f"Unknown KDE method name {name!r}. The only supported "
|
|
1771
|
+
'named method is "GaussianKDE"')
|
|
1772
|
+
|
|
1773
|
+
def _kde_method(x, coords):
|
|
1774
|
+
# fallback gracefully if the vector contains only one value
|
|
1775
|
+
if np.all(x[0] == x):
|
|
1776
|
+
return (x[0] == coords).astype(float)
|
|
1777
|
+
kde = mlab.GaussianKDE(x, bw_method)
|
|
1778
|
+
return kde.evaluate(coords)
|
|
1779
|
+
|
|
1780
|
+
method = _kde_method
|
|
1781
|
+
|
|
1782
|
+
# List of dictionaries describing each of the violins.
|
|
1783
|
+
vpstats = []
|
|
1784
|
+
|
|
1785
|
+
# Want X to be a list of data sequences
|
|
1786
|
+
X = _reshape_2D(X, "X")
|
|
1787
|
+
|
|
1788
|
+
# Want quantiles to be as the same shape as data sequences
|
|
1789
|
+
if quantiles is not None and len(quantiles) != 0:
|
|
1790
|
+
quantiles = _reshape_2D(quantiles, "quantiles")
|
|
1791
|
+
# Else, mock quantiles if it's none or empty
|
|
1792
|
+
else:
|
|
1793
|
+
quantiles = [[]] * len(X)
|
|
1794
|
+
|
|
1795
|
+
# quantiles should have the same size as dataset
|
|
1796
|
+
if len(X) != len(quantiles):
|
|
1797
|
+
raise ValueError("List of violinplot statistics and quantiles values"
|
|
1798
|
+
" must have the same length")
|
|
1799
|
+
|
|
1800
|
+
# Zip x and quantiles
|
|
1801
|
+
for (x, quantile) in zip(X, quantiles):
|
|
1802
|
+
x = np.asarray(x)
|
|
1803
|
+
x, = delete_masked_points(x)
|
|
1804
|
+
|
|
1805
|
+
if len(x) == 0:
|
|
1806
|
+
vpstats.append({
|
|
1807
|
+
'vals': np.array([]),
|
|
1808
|
+
'coords': np.array([]),
|
|
1809
|
+
'mean': np.nan,
|
|
1810
|
+
'median': np.nan,
|
|
1811
|
+
'min': np.nan,
|
|
1812
|
+
'max': np.nan,
|
|
1813
|
+
'quantiles': np.array([]),
|
|
1814
|
+
})
|
|
1815
|
+
else:
|
|
1816
|
+
min_val = np.min(x)
|
|
1817
|
+
max_val = np.max(x)
|
|
1818
|
+
coords = np.linspace(min_val, max_val, points)
|
|
1819
|
+
|
|
1820
|
+
vpstats.append({
|
|
1821
|
+
'vals': method(x, coords),
|
|
1822
|
+
'coords': coords,
|
|
1823
|
+
'mean': np.mean(x),
|
|
1824
|
+
'median': np.median(x),
|
|
1825
|
+
'min': min_val,
|
|
1826
|
+
'max': max_val,
|
|
1827
|
+
'quantiles': np.atleast_1d(np.percentile(x, 100 * quantile))
|
|
1828
|
+
})
|
|
1829
|
+
|
|
1830
|
+
return vpstats
|
|
1831
|
+
|
|
1832
|
+
|
|
1833
|
+
def pts_to_prestep(x, *args):
|
|
1834
|
+
"""
|
|
1835
|
+
Convert continuous line to pre-steps.
|
|
1836
|
+
|
|
1837
|
+
Given a set of ``N`` points, convert to ``2N - 1`` points, which when
|
|
1838
|
+
connected linearly give a step function which changes values at the
|
|
1839
|
+
beginning of the intervals.
|
|
1840
|
+
|
|
1841
|
+
Parameters
|
|
1842
|
+
----------
|
|
1843
|
+
x : array
|
|
1844
|
+
The x location of the steps. May be empty.
|
|
1845
|
+
|
|
1846
|
+
y1, ..., yp : array
|
|
1847
|
+
y arrays to be turned into steps; all must be the same length as ``x``.
|
|
1848
|
+
|
|
1849
|
+
Returns
|
|
1850
|
+
-------
|
|
1851
|
+
array
|
|
1852
|
+
The x and y values converted to steps in the same order as the input;
|
|
1853
|
+
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
|
|
1854
|
+
length ``N``, each of these arrays will be length ``2N + 1``. For
|
|
1855
|
+
``N=0``, the length will be 0.
|
|
1856
|
+
|
|
1857
|
+
Examples
|
|
1858
|
+
--------
|
|
1859
|
+
>>> x_s, y1_s, y2_s = pts_to_prestep(x, y1, y2)
|
|
1860
|
+
"""
|
|
1861
|
+
steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
|
|
1862
|
+
# In all `pts_to_*step` functions, only assign once using *x* and *args*,
|
|
1863
|
+
# as converting to an array may be expensive.
|
|
1864
|
+
steps[0, 0::2] = x
|
|
1865
|
+
steps[0, 1::2] = steps[0, 0:-2:2]
|
|
1866
|
+
steps[1:, 0::2] = args
|
|
1867
|
+
steps[1:, 1::2] = steps[1:, 2::2]
|
|
1868
|
+
return steps
|
|
1869
|
+
|
|
1870
|
+
|
|
1871
|
+
def pts_to_poststep(x, *args):
|
|
1872
|
+
"""
|
|
1873
|
+
Convert continuous line to post-steps.
|
|
1874
|
+
|
|
1875
|
+
Given a set of ``N`` points convert to ``2N + 1`` points, which when
|
|
1876
|
+
connected linearly give a step function which changes values at the end of
|
|
1877
|
+
the intervals.
|
|
1878
|
+
|
|
1879
|
+
Parameters
|
|
1880
|
+
----------
|
|
1881
|
+
x : array
|
|
1882
|
+
The x location of the steps. May be empty.
|
|
1883
|
+
|
|
1884
|
+
y1, ..., yp : array
|
|
1885
|
+
y arrays to be turned into steps; all must be the same length as ``x``.
|
|
1886
|
+
|
|
1887
|
+
Returns
|
|
1888
|
+
-------
|
|
1889
|
+
array
|
|
1890
|
+
The x and y values converted to steps in the same order as the input;
|
|
1891
|
+
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
|
|
1892
|
+
length ``N``, each of these arrays will be length ``2N + 1``. For
|
|
1893
|
+
``N=0``, the length will be 0.
|
|
1894
|
+
|
|
1895
|
+
Examples
|
|
1896
|
+
--------
|
|
1897
|
+
>>> x_s, y1_s, y2_s = pts_to_poststep(x, y1, y2)
|
|
1898
|
+
"""
|
|
1899
|
+
steps = np.zeros((1 + len(args), max(2 * len(x) - 1, 0)))
|
|
1900
|
+
steps[0, 0::2] = x
|
|
1901
|
+
steps[0, 1::2] = steps[0, 2::2]
|
|
1902
|
+
steps[1:, 0::2] = args
|
|
1903
|
+
steps[1:, 1::2] = steps[1:, 0:-2:2]
|
|
1904
|
+
return steps
|
|
1905
|
+
|
|
1906
|
+
|
|
1907
|
+
def pts_to_midstep(x, *args):
|
|
1908
|
+
"""
|
|
1909
|
+
Convert continuous line to mid-steps.
|
|
1910
|
+
|
|
1911
|
+
Given a set of ``N`` points convert to ``2N`` points which when connected
|
|
1912
|
+
linearly give a step function which changes values at the middle of the
|
|
1913
|
+
intervals.
|
|
1914
|
+
|
|
1915
|
+
Parameters
|
|
1916
|
+
----------
|
|
1917
|
+
x : array
|
|
1918
|
+
The x location of the steps. May be empty.
|
|
1919
|
+
|
|
1920
|
+
y1, ..., yp : array
|
|
1921
|
+
y arrays to be turned into steps; all must be the same length as
|
|
1922
|
+
``x``.
|
|
1923
|
+
|
|
1924
|
+
Returns
|
|
1925
|
+
-------
|
|
1926
|
+
array
|
|
1927
|
+
The x and y values converted to steps in the same order as the input;
|
|
1928
|
+
can be unpacked as ``x_out, y1_out, ..., yp_out``. If the input is
|
|
1929
|
+
length ``N``, each of these arrays will be length ``2N``.
|
|
1930
|
+
|
|
1931
|
+
Examples
|
|
1932
|
+
--------
|
|
1933
|
+
>>> x_s, y1_s, y2_s = pts_to_midstep(x, y1, y2)
|
|
1934
|
+
"""
|
|
1935
|
+
steps = np.zeros((1 + len(args), 2 * len(x)))
|
|
1936
|
+
x = np.asanyarray(x)
|
|
1937
|
+
steps[0, 1:-1:2] = steps[0, 2::2] = (x[:-1] + x[1:]) / 2
|
|
1938
|
+
steps[0, :1] = x[:1] # Also works for zero-sized input.
|
|
1939
|
+
steps[0, -1:] = x[-1:]
|
|
1940
|
+
steps[1:, 0::2] = args
|
|
1941
|
+
steps[1:, 1::2] = steps[1:, 0::2]
|
|
1942
|
+
return steps
|
|
1943
|
+
|
|
1944
|
+
|
|
1945
|
+
STEP_LOOKUP_MAP = {'default': lambda x, y: (x, y),
|
|
1946
|
+
'steps': pts_to_prestep,
|
|
1947
|
+
'steps-pre': pts_to_prestep,
|
|
1948
|
+
'steps-post': pts_to_poststep,
|
|
1949
|
+
'steps-mid': pts_to_midstep}
|
|
1950
|
+
|
|
1951
|
+
|
|
1952
|
+
def index_of(y):
|
|
1953
|
+
"""
|
|
1954
|
+
A helper function to create reasonable x values for the given *y*.
|
|
1955
|
+
|
|
1956
|
+
This is used for plotting (x, y) if x values are not explicitly given.
|
|
1957
|
+
|
|
1958
|
+
First try ``y.index`` (assuming *y* is a `pandas.Series`), if that
|
|
1959
|
+
fails, use ``range(len(y))``.
|
|
1960
|
+
|
|
1961
|
+
This will be extended in the future to deal with more types of
|
|
1962
|
+
labeled data.
|
|
1963
|
+
|
|
1964
|
+
Parameters
|
|
1965
|
+
----------
|
|
1966
|
+
y : float or array-like
|
|
1967
|
+
|
|
1968
|
+
Returns
|
|
1969
|
+
-------
|
|
1970
|
+
x, y : ndarray
|
|
1971
|
+
The x and y values to plot.
|
|
1972
|
+
"""
|
|
1973
|
+
try:
|
|
1974
|
+
return y.index.to_numpy(), y.to_numpy()
|
|
1975
|
+
except AttributeError:
|
|
1976
|
+
pass
|
|
1977
|
+
try:
|
|
1978
|
+
y = _check_1d(y)
|
|
1979
|
+
except (VisibleDeprecationWarning, ValueError):
|
|
1980
|
+
# NumPy 1.19 will warn on ragged input, and we can't actually use it.
|
|
1981
|
+
pass
|
|
1982
|
+
else:
|
|
1983
|
+
return np.arange(y.shape[0], dtype=float), y
|
|
1984
|
+
raise ValueError('Input could not be cast to an at-least-1D NumPy array')
|
|
1985
|
+
|
|
1986
|
+
|
|
1987
|
+
def safe_first_element(obj):
|
|
1988
|
+
"""
|
|
1989
|
+
Return the first element in *obj*.
|
|
1990
|
+
|
|
1991
|
+
This is a type-independent way of obtaining the first element,
|
|
1992
|
+
supporting both index access and the iterator protocol.
|
|
1993
|
+
"""
|
|
1994
|
+
if isinstance(obj, collections.abc.Iterator):
|
|
1995
|
+
# needed to accept `array.flat` as input.
|
|
1996
|
+
# np.flatiter reports as an instance of collections.Iterator but can still be
|
|
1997
|
+
# indexed via []. This has the side effect of re-setting the iterator, but
|
|
1998
|
+
# that is acceptable.
|
|
1999
|
+
try:
|
|
2000
|
+
return obj[0]
|
|
2001
|
+
except TypeError:
|
|
2002
|
+
pass
|
|
2003
|
+
raise RuntimeError("matplotlib does not support generators as input")
|
|
2004
|
+
return next(iter(obj))
|
|
2005
|
+
|
|
2006
|
+
|
|
2007
|
+
def _safe_first_finite(obj):
|
|
2008
|
+
"""
|
|
2009
|
+
Return the first finite element in *obj* if one is available and skip_nonfinite is
|
|
2010
|
+
True. Otherwise, return the first element.
|
|
2011
|
+
|
|
2012
|
+
This is a method for internal use.
|
|
2013
|
+
|
|
2014
|
+
This is a type-independent way of obtaining the first finite element, supporting
|
|
2015
|
+
both index access and the iterator protocol.
|
|
2016
|
+
"""
|
|
2017
|
+
def safe_isfinite(val):
|
|
2018
|
+
if val is None:
|
|
2019
|
+
return False
|
|
2020
|
+
try:
|
|
2021
|
+
return math.isfinite(val)
|
|
2022
|
+
except (TypeError, ValueError):
|
|
2023
|
+
# if the outer object is 2d, then val is a 1d array, and
|
|
2024
|
+
# - math.isfinite(numpy.zeros(3)) raises TypeError
|
|
2025
|
+
# - math.isfinite(torch.zeros(3)) raises ValueError
|
|
2026
|
+
pass
|
|
2027
|
+
try:
|
|
2028
|
+
return np.isfinite(val) if np.isscalar(val) else True
|
|
2029
|
+
except TypeError:
|
|
2030
|
+
# This is something that NumPy cannot make heads or tails of,
|
|
2031
|
+
# assume "finite"
|
|
2032
|
+
return True
|
|
2033
|
+
|
|
2034
|
+
if isinstance(obj, np.flatiter):
|
|
2035
|
+
# TODO do the finite filtering on this
|
|
2036
|
+
return obj[0]
|
|
2037
|
+
elif isinstance(obj, collections.abc.Iterator):
|
|
2038
|
+
raise RuntimeError("matplotlib does not support generators as input")
|
|
2039
|
+
else:
|
|
2040
|
+
for val in obj:
|
|
2041
|
+
if safe_isfinite(val):
|
|
2042
|
+
return val
|
|
2043
|
+
return safe_first_element(obj)
|
|
2044
|
+
|
|
2045
|
+
|
|
2046
|
+
def sanitize_sequence(data):
|
|
2047
|
+
"""
|
|
2048
|
+
Convert dictview objects to list. Other inputs are returned unchanged.
|
|
2049
|
+
"""
|
|
2050
|
+
return (list(data) if isinstance(data, collections.abc.MappingView)
|
|
2051
|
+
else data)
|
|
2052
|
+
|
|
2053
|
+
|
|
2054
|
+
def _resize_sequence(seq, N):
|
|
2055
|
+
"""
|
|
2056
|
+
Trim the given sequence to exactly N elements.
|
|
2057
|
+
|
|
2058
|
+
If there are more elements in the sequence, cut it.
|
|
2059
|
+
If there are less elements in the sequence, repeat them.
|
|
2060
|
+
|
|
2061
|
+
Implementation detail: We maintain type stability for the output for
|
|
2062
|
+
N <= len(seq). We simply return a list for N > len(seq); this was good
|
|
2063
|
+
enough for the present use cases but is not a fixed design decision.
|
|
2064
|
+
"""
|
|
2065
|
+
num_elements = len(seq)
|
|
2066
|
+
if N == num_elements:
|
|
2067
|
+
return seq
|
|
2068
|
+
elif N < num_elements:
|
|
2069
|
+
return seq[:N]
|
|
2070
|
+
else:
|
|
2071
|
+
return list(itertools.islice(itertools.cycle(seq), N))
|
|
2072
|
+
|
|
2073
|
+
|
|
2074
|
+
def normalize_kwargs(kw, alias_mapping=None):
|
|
2075
|
+
"""
|
|
2076
|
+
Helper function to normalize kwarg inputs.
|
|
2077
|
+
|
|
2078
|
+
Parameters
|
|
2079
|
+
----------
|
|
2080
|
+
kw : dict or None
|
|
2081
|
+
A dict of keyword arguments. None is explicitly supported and treated
|
|
2082
|
+
as an empty dict, to support functions with an optional parameter of
|
|
2083
|
+
the form ``props=None``.
|
|
2084
|
+
|
|
2085
|
+
alias_mapping : Artist subclass or Artist instance
|
|
2086
|
+
A mapping between a canonical name to a list of aliases, in order of
|
|
2087
|
+
precedence from lowest to highest.
|
|
2088
|
+
|
|
2089
|
+
If the canonical value is not in the list it is assumed to have the
|
|
2090
|
+
highest priority.
|
|
2091
|
+
|
|
2092
|
+
If an Artist subclass or instance is passed, use its properties alias
|
|
2093
|
+
mapping.
|
|
2094
|
+
|
|
2095
|
+
Raises
|
|
2096
|
+
------
|
|
2097
|
+
TypeError
|
|
2098
|
+
To match what Python raises if invalid arguments/keyword arguments are
|
|
2099
|
+
passed to a callable.
|
|
2100
|
+
"""
|
|
2101
|
+
from .artist import Artist
|
|
2102
|
+
|
|
2103
|
+
# deal with default value of alias_mapping
|
|
2104
|
+
if (isinstance(alias_mapping, type) and issubclass(alias_mapping, Artist)
|
|
2105
|
+
or isinstance(alias_mapping, Artist)):
|
|
2106
|
+
alias_to_prop = getattr(alias_mapping, "_alias_to_prop", {})
|
|
2107
|
+
else:
|
|
2108
|
+
if alias_mapping is None:
|
|
2109
|
+
alias_mapping = {}
|
|
2110
|
+
_api.warn_deprecated("3.11", message=(
|
|
2111
|
+
"Passing a dict or None as alias_mapping to normalize_kwargs is "
|
|
2112
|
+
"deprecated since %(since)s and support will be removed "
|
|
2113
|
+
"%(removal)s; pass an Artist instance or type instead."))
|
|
2114
|
+
# Convert old format to new format.
|
|
2115
|
+
alias_to_prop = {alias: prop for prop, aliases in alias_mapping.items()
|
|
2116
|
+
for alias in aliases}
|
|
2117
|
+
|
|
2118
|
+
if kw is None:
|
|
2119
|
+
return {}
|
|
2120
|
+
|
|
2121
|
+
canonicalized = {alias_to_prop.get(k, k): v for k, v in kw.items()}
|
|
2122
|
+
if len(canonicalized) == len(kw):
|
|
2123
|
+
return canonicalized
|
|
2124
|
+
|
|
2125
|
+
canonical_to_seen = {}
|
|
2126
|
+
for k in kw:
|
|
2127
|
+
canonical = alias_to_prop.get(k, k)
|
|
2128
|
+
if canonical in canonical_to_seen:
|
|
2129
|
+
raise TypeError(f"Got both {canonical_to_seen[canonical]!r} and "
|
|
2130
|
+
f"{k!r}, which are aliases of one another")
|
|
2131
|
+
canonical_to_seen[canonical] = k
|
|
2132
|
+
|
|
2133
|
+
|
|
2134
|
+
@contextlib.contextmanager
|
|
2135
|
+
def _lock_path(path):
|
|
2136
|
+
"""
|
|
2137
|
+
Context manager for locking a path.
|
|
2138
|
+
|
|
2139
|
+
Usage::
|
|
2140
|
+
|
|
2141
|
+
with _lock_path(path):
|
|
2142
|
+
...
|
|
2143
|
+
|
|
2144
|
+
Another thread or process that attempts to lock the same path will wait
|
|
2145
|
+
until this context manager is exited.
|
|
2146
|
+
|
|
2147
|
+
The lock is implemented by creating a temporary file in the parent
|
|
2148
|
+
directory, so that directory must exist and be writable.
|
|
2149
|
+
"""
|
|
2150
|
+
path = Path(path)
|
|
2151
|
+
lock_path = path.with_name(path.name + ".matplotlib-lock")
|
|
2152
|
+
retries = 50
|
|
2153
|
+
sleeptime = 0.1
|
|
2154
|
+
for _ in range(retries):
|
|
2155
|
+
try:
|
|
2156
|
+
with lock_path.open("xb"):
|
|
2157
|
+
break
|
|
2158
|
+
except FileExistsError:
|
|
2159
|
+
time.sleep(sleeptime)
|
|
2160
|
+
else:
|
|
2161
|
+
raise TimeoutError("""\
|
|
2162
|
+
Lock error: Matplotlib failed to acquire the following lock file:
|
|
2163
|
+
{}
|
|
2164
|
+
This maybe due to another process holding this lock file. If you are sure no
|
|
2165
|
+
other Matplotlib process is running, remove this file and try again.""".format(
|
|
2166
|
+
lock_path))
|
|
2167
|
+
try:
|
|
2168
|
+
yield
|
|
2169
|
+
finally:
|
|
2170
|
+
lock_path.unlink()
|
|
2171
|
+
|
|
2172
|
+
|
|
2173
|
+
def _topmost_artist(
|
|
2174
|
+
artists,
|
|
2175
|
+
_cached_max=functools.partial(max, key=operator.attrgetter("zorder"))):
|
|
2176
|
+
"""
|
|
2177
|
+
Get the topmost artist of a list.
|
|
2178
|
+
|
|
2179
|
+
In case of a tie, return the *last* of the tied artists, as it will be
|
|
2180
|
+
drawn on top of the others. `max` returns the first maximum in case of
|
|
2181
|
+
ties, so we need to iterate over the list in reverse order.
|
|
2182
|
+
"""
|
|
2183
|
+
return _cached_max(reversed(artists))
|
|
2184
|
+
|
|
2185
|
+
|
|
2186
|
+
def _str_equal(obj, s):
|
|
2187
|
+
"""
|
|
2188
|
+
Return whether *obj* is a string equal to string *s*.
|
|
2189
|
+
|
|
2190
|
+
This helper solely exists to handle the case where *obj* is a numpy array,
|
|
2191
|
+
because in such cases, a naive ``obj == s`` would yield an array, which
|
|
2192
|
+
cannot be used in a boolean context.
|
|
2193
|
+
"""
|
|
2194
|
+
return isinstance(obj, str) and obj == s
|
|
2195
|
+
|
|
2196
|
+
|
|
2197
|
+
def _str_lower_equal(obj, s):
|
|
2198
|
+
"""
|
|
2199
|
+
Return whether *obj* is a string equal, when lowercased, to string *s*.
|
|
2200
|
+
|
|
2201
|
+
This helper solely exists to handle the case where *obj* is a numpy array,
|
|
2202
|
+
because in such cases, a naive ``obj == s`` would yield an array, which
|
|
2203
|
+
cannot be used in a boolean context.
|
|
2204
|
+
"""
|
|
2205
|
+
return isinstance(obj, str) and obj.lower() == s
|
|
2206
|
+
|
|
2207
|
+
|
|
2208
|
+
def _array_perimeter(arr):
|
|
2209
|
+
"""
|
|
2210
|
+
Get the elements on the perimeter of *arr*.
|
|
2211
|
+
|
|
2212
|
+
Parameters
|
|
2213
|
+
----------
|
|
2214
|
+
arr : ndarray, shape (M, N)
|
|
2215
|
+
The input array.
|
|
2216
|
+
|
|
2217
|
+
Returns
|
|
2218
|
+
-------
|
|
2219
|
+
ndarray, shape (2*(M - 1) + 2*(N - 1),)
|
|
2220
|
+
The elements on the perimeter of the array::
|
|
2221
|
+
|
|
2222
|
+
[arr[0, 0], ..., arr[0, -1], ..., arr[-1, -1], ..., arr[-1, 0], ...]
|
|
2223
|
+
|
|
2224
|
+
Examples
|
|
2225
|
+
--------
|
|
2226
|
+
>>> i, j = np.ogrid[:3, :4]
|
|
2227
|
+
>>> a = i*10 + j
|
|
2228
|
+
>>> a
|
|
2229
|
+
array([[ 0, 1, 2, 3],
|
|
2230
|
+
[10, 11, 12, 13],
|
|
2231
|
+
[20, 21, 22, 23]])
|
|
2232
|
+
>>> _array_perimeter(a)
|
|
2233
|
+
array([ 0, 1, 2, 3, 13, 23, 22, 21, 20, 10])
|
|
2234
|
+
"""
|
|
2235
|
+
# note we use Python's half-open ranges to avoid repeating
|
|
2236
|
+
# the corners
|
|
2237
|
+
forward = np.s_[0:-1] # [0 ... -1)
|
|
2238
|
+
backward = np.s_[-1:0:-1] # [-1 ... 0)
|
|
2239
|
+
return np.concatenate((
|
|
2240
|
+
arr[0, forward],
|
|
2241
|
+
arr[forward, -1],
|
|
2242
|
+
arr[-1, backward],
|
|
2243
|
+
arr[backward, 0],
|
|
2244
|
+
))
|
|
2245
|
+
|
|
2246
|
+
|
|
2247
|
+
def _unfold(arr, axis, size, step):
|
|
2248
|
+
"""
|
|
2249
|
+
Append an extra dimension containing sliding windows along *axis*.
|
|
2250
|
+
|
|
2251
|
+
All windows are of size *size* and begin with every *step* elements.
|
|
2252
|
+
|
|
2253
|
+
Parameters
|
|
2254
|
+
----------
|
|
2255
|
+
arr : ndarray, shape (N_1, ..., N_k)
|
|
2256
|
+
The input array
|
|
2257
|
+
axis : int
|
|
2258
|
+
Axis along which the windows are extracted
|
|
2259
|
+
size : int
|
|
2260
|
+
Size of the windows
|
|
2261
|
+
step : int
|
|
2262
|
+
Stride between first elements of subsequent windows.
|
|
2263
|
+
|
|
2264
|
+
Returns
|
|
2265
|
+
-------
|
|
2266
|
+
ndarray, shape (N_1, ..., 1 + (N_axis-size)/step, ..., N_k, size)
|
|
2267
|
+
|
|
2268
|
+
Examples
|
|
2269
|
+
--------
|
|
2270
|
+
>>> i, j = np.ogrid[:3, :7]
|
|
2271
|
+
>>> a = i*10 + j
|
|
2272
|
+
>>> a
|
|
2273
|
+
array([[ 0, 1, 2, 3, 4, 5, 6],
|
|
2274
|
+
[10, 11, 12, 13, 14, 15, 16],
|
|
2275
|
+
[20, 21, 22, 23, 24, 25, 26]])
|
|
2276
|
+
>>> _unfold(a, axis=1, size=3, step=2)
|
|
2277
|
+
array([[[ 0, 1, 2],
|
|
2278
|
+
[ 2, 3, 4],
|
|
2279
|
+
[ 4, 5, 6]],
|
|
2280
|
+
[[10, 11, 12],
|
|
2281
|
+
[12, 13, 14],
|
|
2282
|
+
[14, 15, 16]],
|
|
2283
|
+
[[20, 21, 22],
|
|
2284
|
+
[22, 23, 24],
|
|
2285
|
+
[24, 25, 26]]])
|
|
2286
|
+
"""
|
|
2287
|
+
new_shape = [*arr.shape, size]
|
|
2288
|
+
new_strides = [*arr.strides, arr.strides[axis]]
|
|
2289
|
+
new_shape[axis] = (new_shape[axis] - size) // step + 1
|
|
2290
|
+
new_strides[axis] = new_strides[axis] * step
|
|
2291
|
+
return np.lib.stride_tricks.as_strided(arr,
|
|
2292
|
+
shape=new_shape,
|
|
2293
|
+
strides=new_strides,
|
|
2294
|
+
writeable=False)
|
|
2295
|
+
|
|
2296
|
+
|
|
2297
|
+
def _array_patch_perimeters(x, rstride, cstride):
|
|
2298
|
+
"""
|
|
2299
|
+
Extract perimeters of patches from *arr*.
|
|
2300
|
+
|
|
2301
|
+
Extracted patches are of size (*rstride* + 1) x (*cstride* + 1) and
|
|
2302
|
+
share perimeters with their neighbors. The ordering of the vertices matches
|
|
2303
|
+
that returned by ``_array_perimeter``.
|
|
2304
|
+
|
|
2305
|
+
Parameters
|
|
2306
|
+
----------
|
|
2307
|
+
x : ndarray, shape (N, M)
|
|
2308
|
+
Input array
|
|
2309
|
+
rstride : int
|
|
2310
|
+
Vertical (row) stride between corresponding elements of each patch
|
|
2311
|
+
cstride : int
|
|
2312
|
+
Horizontal (column) stride between corresponding elements of each patch
|
|
2313
|
+
|
|
2314
|
+
Returns
|
|
2315
|
+
-------
|
|
2316
|
+
ndarray, shape (N/rstride * M/cstride, 2 * (rstride + cstride))
|
|
2317
|
+
"""
|
|
2318
|
+
assert rstride > 0 and cstride > 0
|
|
2319
|
+
assert (x.shape[0] - 1) % rstride == 0
|
|
2320
|
+
assert (x.shape[1] - 1) % cstride == 0
|
|
2321
|
+
# We build up each perimeter from four half-open intervals. Here is an
|
|
2322
|
+
# illustrated explanation for rstride == cstride == 3
|
|
2323
|
+
#
|
|
2324
|
+
# T T T R
|
|
2325
|
+
# L R
|
|
2326
|
+
# L R
|
|
2327
|
+
# L B B B
|
|
2328
|
+
#
|
|
2329
|
+
# where T means that this element will be in the top array, R for right,
|
|
2330
|
+
# B for bottom and L for left. Each of the arrays below has a shape of:
|
|
2331
|
+
#
|
|
2332
|
+
# (number of perimeters that can be extracted vertically,
|
|
2333
|
+
# number of perimeters that can be extracted horizontally,
|
|
2334
|
+
# cstride for top and bottom and rstride for left and right)
|
|
2335
|
+
#
|
|
2336
|
+
# Note that _unfold doesn't incur any memory copies, so the only costly
|
|
2337
|
+
# operation here is the np.concatenate.
|
|
2338
|
+
top = _unfold(x[:-1:rstride, :-1], 1, cstride, cstride)
|
|
2339
|
+
bottom = _unfold(x[rstride::rstride, 1:], 1, cstride, cstride)[..., ::-1]
|
|
2340
|
+
right = _unfold(x[:-1, cstride::cstride], 0, rstride, rstride)
|
|
2341
|
+
left = _unfold(x[1:, :-1:cstride], 0, rstride, rstride)[..., ::-1]
|
|
2342
|
+
return (np.concatenate((top, right, bottom, left), axis=2)
|
|
2343
|
+
.reshape(-1, 2 * (rstride + cstride)))
|
|
2344
|
+
|
|
2345
|
+
|
|
2346
|
+
@contextlib.contextmanager
|
|
2347
|
+
def _setattr_cm(obj, **kwargs):
|
|
2348
|
+
"""
|
|
2349
|
+
Temporarily set some attributes; restore original state at context exit.
|
|
2350
|
+
"""
|
|
2351
|
+
sentinel = object()
|
|
2352
|
+
origs = {}
|
|
2353
|
+
for attr in kwargs:
|
|
2354
|
+
orig = getattr(obj, attr, sentinel)
|
|
2355
|
+
if attr in obj.__dict__ or orig is sentinel:
|
|
2356
|
+
# if we are pulling from the instance dict or the object
|
|
2357
|
+
# does not have this attribute we can trust the above
|
|
2358
|
+
origs[attr] = orig
|
|
2359
|
+
else:
|
|
2360
|
+
# if the attribute is not in the instance dict it must be
|
|
2361
|
+
# from the class level
|
|
2362
|
+
cls_orig = getattr(type(obj), attr)
|
|
2363
|
+
# if we are dealing with a property (but not a general descriptor)
|
|
2364
|
+
# we want to set the original value back.
|
|
2365
|
+
if isinstance(cls_orig, property):
|
|
2366
|
+
origs[attr] = orig
|
|
2367
|
+
# otherwise this is _something_ we are going to shadow at
|
|
2368
|
+
# the instance dict level from higher up in the MRO. We
|
|
2369
|
+
# are going to assume we can delattr(obj, attr) to clean
|
|
2370
|
+
# up after ourselves. It is possible that this code will
|
|
2371
|
+
# fail if used with a non-property custom descriptor which
|
|
2372
|
+
# implements __set__ (and __delete__ does not act like a
|
|
2373
|
+
# stack). However, this is an internal tool and we do not
|
|
2374
|
+
# currently have any custom descriptors.
|
|
2375
|
+
else:
|
|
2376
|
+
origs[attr] = sentinel
|
|
2377
|
+
|
|
2378
|
+
try:
|
|
2379
|
+
for attr, val in kwargs.items():
|
|
2380
|
+
setattr(obj, attr, val)
|
|
2381
|
+
yield
|
|
2382
|
+
finally:
|
|
2383
|
+
for attr, orig in origs.items():
|
|
2384
|
+
if orig is sentinel:
|
|
2385
|
+
delattr(obj, attr)
|
|
2386
|
+
else:
|
|
2387
|
+
setattr(obj, attr, orig)
|
|
2388
|
+
|
|
2389
|
+
|
|
2390
|
+
class _OrderedSet(collections.abc.MutableSet):
|
|
2391
|
+
def __init__(self):
|
|
2392
|
+
self._od = collections.OrderedDict()
|
|
2393
|
+
|
|
2394
|
+
def __contains__(self, key):
|
|
2395
|
+
return key in self._od
|
|
2396
|
+
|
|
2397
|
+
def __iter__(self):
|
|
2398
|
+
return iter(self._od)
|
|
2399
|
+
|
|
2400
|
+
def __len__(self):
|
|
2401
|
+
return len(self._od)
|
|
2402
|
+
|
|
2403
|
+
def add(self, key):
|
|
2404
|
+
self._od.pop(key, None)
|
|
2405
|
+
self._od[key] = None
|
|
2406
|
+
|
|
2407
|
+
def discard(self, key):
|
|
2408
|
+
self._od.pop(key, None)
|
|
2409
|
+
|
|
2410
|
+
|
|
2411
|
+
# Agg's buffers are unmultiplied RGBA8888, which neither PyQt<=5.1 nor cairo
|
|
2412
|
+
# support; however, both do support premultiplied ARGB32.
|
|
2413
|
+
|
|
2414
|
+
|
|
2415
|
+
def _premultiplied_argb32_to_unmultiplied_rgba8888(buf):
|
|
2416
|
+
"""
|
|
2417
|
+
Convert a premultiplied ARGB32 buffer to an unmultiplied RGBA8888 buffer.
|
|
2418
|
+
"""
|
|
2419
|
+
rgba = np.take( # .take() ensures C-contiguity of the result.
|
|
2420
|
+
buf,
|
|
2421
|
+
[2, 1, 0, 3] if sys.byteorder == "little" else [1, 2, 3, 0], axis=2)
|
|
2422
|
+
rgb = rgba[..., :-1]
|
|
2423
|
+
alpha = rgba[..., -1]
|
|
2424
|
+
if alpha.min() == 0xff:
|
|
2425
|
+
return rgba
|
|
2426
|
+
# Un-premultiply alpha. The formula is the same as in cairo-png.c.
|
|
2427
|
+
mask = alpha != 0
|
|
2428
|
+
for channel in np.rollaxis(rgb, -1):
|
|
2429
|
+
channel[mask] = (
|
|
2430
|
+
(channel[mask].astype(int) * 255 + alpha[mask] // 2)
|
|
2431
|
+
// alpha[mask])
|
|
2432
|
+
return rgba
|
|
2433
|
+
|
|
2434
|
+
|
|
2435
|
+
def _unmultiplied_rgba8888_to_premultiplied_argb32(rgba8888):
|
|
2436
|
+
"""
|
|
2437
|
+
Convert an unmultiplied RGBA8888 buffer to a premultiplied ARGB32 buffer.
|
|
2438
|
+
"""
|
|
2439
|
+
if sys.byteorder == "little":
|
|
2440
|
+
argb32 = np.take(rgba8888, [2, 1, 0, 3], axis=2)
|
|
2441
|
+
rgb24 = argb32[..., :-1]
|
|
2442
|
+
alpha8 = argb32[..., -1:]
|
|
2443
|
+
else:
|
|
2444
|
+
argb32 = np.take(rgba8888, [3, 0, 1, 2], axis=2)
|
|
2445
|
+
alpha8 = argb32[..., :1]
|
|
2446
|
+
rgb24 = argb32[..., 1:]
|
|
2447
|
+
# Only bother premultiplying when the alpha channel is not fully opaque,
|
|
2448
|
+
# as the cost is not negligible. The unsafe cast is needed to do the
|
|
2449
|
+
# multiplication in-place in an integer buffer.
|
|
2450
|
+
if alpha8.min() != 0xff:
|
|
2451
|
+
np.multiply(rgb24, alpha8 / 0xff, out=rgb24, casting="unsafe")
|
|
2452
|
+
return argb32
|
|
2453
|
+
|
|
2454
|
+
|
|
2455
|
+
def _get_nonzero_slices(buf):
|
|
2456
|
+
"""
|
|
2457
|
+
Return the bounds of the nonzero region of a 2D array as a pair of slices.
|
|
2458
|
+
|
|
2459
|
+
``buf[_get_nonzero_slices(buf)]`` is the smallest sub-rectangle in *buf*
|
|
2460
|
+
that encloses all non-zero entries in *buf*. If *buf* is fully zero, then
|
|
2461
|
+
``(slice(0, 0), slice(0, 0))`` is returned.
|
|
2462
|
+
"""
|
|
2463
|
+
x_nz, = buf.any(axis=0).nonzero()
|
|
2464
|
+
y_nz, = buf.any(axis=1).nonzero()
|
|
2465
|
+
if len(x_nz) and len(y_nz):
|
|
2466
|
+
l, r = x_nz[[0, -1]]
|
|
2467
|
+
b, t = y_nz[[0, -1]]
|
|
2468
|
+
return slice(b, t + 1), slice(l, r + 1)
|
|
2469
|
+
else:
|
|
2470
|
+
return slice(0, 0), slice(0, 0)
|
|
2471
|
+
|
|
2472
|
+
|
|
2473
|
+
def _pformat_subprocess(command):
|
|
2474
|
+
"""Pretty-format a subprocess command for printing/logging purposes."""
|
|
2475
|
+
return (command if isinstance(command, str)
|
|
2476
|
+
else " ".join(shlex.quote(os.fspath(arg)) for arg in command))
|
|
2477
|
+
|
|
2478
|
+
|
|
2479
|
+
def _check_and_log_subprocess(command, logger, **kwargs):
|
|
2480
|
+
"""
|
|
2481
|
+
Run *command*, returning its stdout output if it succeeds.
|
|
2482
|
+
|
|
2483
|
+
If it fails (exits with nonzero return code), raise an exception whose text
|
|
2484
|
+
includes the failed command and captured stdout and stderr output.
|
|
2485
|
+
|
|
2486
|
+
Regardless of the return code, the command is logged at DEBUG level on
|
|
2487
|
+
*logger*. In case of success, the output is likewise logged.
|
|
2488
|
+
"""
|
|
2489
|
+
logger.debug('%s', _pformat_subprocess(command))
|
|
2490
|
+
proc = subprocess.run(command, capture_output=True, **kwargs)
|
|
2491
|
+
if proc.returncode:
|
|
2492
|
+
stdout = proc.stdout
|
|
2493
|
+
if isinstance(stdout, bytes):
|
|
2494
|
+
stdout = stdout.decode()
|
|
2495
|
+
stderr = proc.stderr
|
|
2496
|
+
if isinstance(stderr, bytes):
|
|
2497
|
+
stderr = stderr.decode()
|
|
2498
|
+
raise RuntimeError(
|
|
2499
|
+
f"The command\n"
|
|
2500
|
+
f" {_pformat_subprocess(command)}\n"
|
|
2501
|
+
f"failed and generated the following output:\n"
|
|
2502
|
+
f"{stdout}\n"
|
|
2503
|
+
f"and the following error:\n"
|
|
2504
|
+
f"{stderr}")
|
|
2505
|
+
if proc.stdout:
|
|
2506
|
+
logger.debug("stdout:\n%s", proc.stdout)
|
|
2507
|
+
if proc.stderr:
|
|
2508
|
+
logger.debug("stderr:\n%s", proc.stderr)
|
|
2509
|
+
return proc.stdout
|
|
2510
|
+
|
|
2511
|
+
|
|
2512
|
+
def _setup_new_guiapp():
|
|
2513
|
+
"""
|
|
2514
|
+
Perform OS-dependent setup when Matplotlib creates a new GUI application.
|
|
2515
|
+
"""
|
|
2516
|
+
# Windows: If not explicit app user model id has been set yet (so we're not
|
|
2517
|
+
# already embedded), then set it to "matplotlib", so that taskbar icons are
|
|
2518
|
+
# correct.
|
|
2519
|
+
try:
|
|
2520
|
+
_c_internal_utils.Win32_GetCurrentProcessExplicitAppUserModelID()
|
|
2521
|
+
except OSError:
|
|
2522
|
+
_c_internal_utils.Win32_SetCurrentProcessExplicitAppUserModelID(
|
|
2523
|
+
"matplotlib")
|
|
2524
|
+
|
|
2525
|
+
|
|
2526
|
+
def _format_approx(number, precision):
|
|
2527
|
+
"""
|
|
2528
|
+
Format the number with at most the number of decimals given as precision.
|
|
2529
|
+
Remove trailing zeros and possibly the decimal point.
|
|
2530
|
+
"""
|
|
2531
|
+
return f'{number:.{precision}f}'.rstrip('0').rstrip('.') or '0'
|
|
2532
|
+
|
|
2533
|
+
|
|
2534
|
+
def _g_sig_digits(value, delta):
|
|
2535
|
+
"""
|
|
2536
|
+
Return the number of significant digits to %g-format *value*, assuming that
|
|
2537
|
+
it is known with an error of *delta*.
|
|
2538
|
+
"""
|
|
2539
|
+
# For inf or nan, the precision doesn't matter.
|
|
2540
|
+
if not math.isfinite(value):
|
|
2541
|
+
return 0
|
|
2542
|
+
if delta == 0:
|
|
2543
|
+
if value == 0:
|
|
2544
|
+
# if both value and delta are 0, np.spacing below returns 5e-324
|
|
2545
|
+
# which results in rather silly results
|
|
2546
|
+
return 3
|
|
2547
|
+
# delta = 0 may occur when trying to format values over a tiny range;
|
|
2548
|
+
# in that case, replace it by the distance to the closest float.
|
|
2549
|
+
delta = abs(np.spacing(value))
|
|
2550
|
+
# If e.g. value = 45.67 and delta = 0.02, then we want to round to 2 digits
|
|
2551
|
+
# after the decimal point (floor(log10(0.02)) = -2); 45.67 contributes 2
|
|
2552
|
+
# digits before the decimal point (floor(log10(45.67)) + 1 = 2): the total
|
|
2553
|
+
# is 4 significant digits. A value of 0 contributes 1 "digit" before the
|
|
2554
|
+
# decimal point.
|
|
2555
|
+
return max(
|
|
2556
|
+
0,
|
|
2557
|
+
(math.floor(math.log10(abs(value))) + 1 if value else 1)
|
|
2558
|
+
- math.floor(math.log10(delta)))
|
|
2559
|
+
|
|
2560
|
+
|
|
2561
|
+
def _unikey_or_keysym_to_mplkey(unikey, keysym):
|
|
2562
|
+
"""
|
|
2563
|
+
Convert a Unicode key or X keysym to a Matplotlib key name.
|
|
2564
|
+
|
|
2565
|
+
The Unicode key is checked first; this avoids having to list most printable
|
|
2566
|
+
keysyms such as ``EuroSign``.
|
|
2567
|
+
"""
|
|
2568
|
+
# For non-printable characters, gtk3 passes "\0" whereas tk passes an "".
|
|
2569
|
+
if unikey and unikey.isprintable():
|
|
2570
|
+
return unikey
|
|
2571
|
+
key = keysym.lower()
|
|
2572
|
+
if key.startswith("kp_"): # keypad_x (including kp_enter).
|
|
2573
|
+
key = key[3:]
|
|
2574
|
+
if key.startswith("page_"): # page_{up,down}
|
|
2575
|
+
key = key.replace("page_", "page")
|
|
2576
|
+
if key.endswith(("_l", "_r")): # alt_l, ctrl_l, shift_l.
|
|
2577
|
+
key = key[:-2]
|
|
2578
|
+
if sys.platform == "darwin" and key == "meta":
|
|
2579
|
+
# meta should be reported as command on mac
|
|
2580
|
+
key = "cmd"
|
|
2581
|
+
key = {
|
|
2582
|
+
"return": "enter",
|
|
2583
|
+
"prior": "pageup", # Used by tk.
|
|
2584
|
+
"next": "pagedown", # Used by tk.
|
|
2585
|
+
}.get(key, key)
|
|
2586
|
+
return key
|
|
2587
|
+
|
|
2588
|
+
|
|
2589
|
+
@functools.cache
|
|
2590
|
+
def _make_class_factory(mixin_class, fmt, attr_name=None):
|
|
2591
|
+
"""
|
|
2592
|
+
Return a function that creates picklable classes inheriting from a mixin.
|
|
2593
|
+
|
|
2594
|
+
After ::
|
|
2595
|
+
|
|
2596
|
+
factory = _make_class_factory(FooMixin, fmt, attr_name)
|
|
2597
|
+
FooAxes = factory(Axes)
|
|
2598
|
+
|
|
2599
|
+
``Foo`` is a class that inherits from ``FooMixin`` and ``Axes`` and **is
|
|
2600
|
+
picklable** (picklability is what differentiates this from a plain call to
|
|
2601
|
+
`type`). Its ``__name__`` is set to ``fmt.format(Axes.__name__)`` and the
|
|
2602
|
+
base class is stored in the ``attr_name`` attribute, if not None.
|
|
2603
|
+
|
|
2604
|
+
Moreover, the return value of ``factory`` is memoized: calls with the same
|
|
2605
|
+
``Axes`` class always return the same subclass.
|
|
2606
|
+
"""
|
|
2607
|
+
|
|
2608
|
+
@functools.cache
|
|
2609
|
+
def class_factory(axes_class):
|
|
2610
|
+
# if we have already wrapped this class, declare victory!
|
|
2611
|
+
if issubclass(axes_class, mixin_class):
|
|
2612
|
+
return axes_class
|
|
2613
|
+
|
|
2614
|
+
# The parameter is named "axes_class" for backcompat but is really just
|
|
2615
|
+
# a base class; no axes semantics are used.
|
|
2616
|
+
base_class = axes_class
|
|
2617
|
+
|
|
2618
|
+
class subcls(mixin_class, base_class):
|
|
2619
|
+
# Better approximation than __module__ = "matplotlib.cbook".
|
|
2620
|
+
__module__ = mixin_class.__module__
|
|
2621
|
+
|
|
2622
|
+
def __reduce__(self):
|
|
2623
|
+
return (_picklable_class_constructor,
|
|
2624
|
+
(mixin_class, fmt, attr_name, base_class),
|
|
2625
|
+
self.__getstate__())
|
|
2626
|
+
|
|
2627
|
+
subcls.__name__ = subcls.__qualname__ = fmt.format(base_class.__name__)
|
|
2628
|
+
if attr_name is not None:
|
|
2629
|
+
setattr(subcls, attr_name, base_class)
|
|
2630
|
+
return subcls
|
|
2631
|
+
|
|
2632
|
+
class_factory.__module__ = mixin_class.__module__
|
|
2633
|
+
return class_factory
|
|
2634
|
+
|
|
2635
|
+
|
|
2636
|
+
def _picklable_class_constructor(mixin_class, fmt, attr_name, base_class):
|
|
2637
|
+
"""Internal helper for _make_class_factory."""
|
|
2638
|
+
factory = _make_class_factory(mixin_class, fmt, attr_name)
|
|
2639
|
+
cls = factory(base_class)
|
|
2640
|
+
return cls.__new__(cls)
|
|
2641
|
+
|
|
2642
|
+
|
|
2643
|
+
def _is_torch_array(x):
|
|
2644
|
+
"""Return whether *x* is a PyTorch Tensor."""
|
|
2645
|
+
try:
|
|
2646
|
+
# We're intentionally not attempting to import torch. If somebody
|
|
2647
|
+
# has created a torch array, torch should already be in sys.modules.
|
|
2648
|
+
tp = sys.modules.get("torch").Tensor
|
|
2649
|
+
except AttributeError:
|
|
2650
|
+
return False # Module not imported or a nonstandard module with no Tensor attr.
|
|
2651
|
+
return (isinstance(tp, type) # Just in case it's a very nonstandard module.
|
|
2652
|
+
and isinstance(x, tp))
|
|
2653
|
+
|
|
2654
|
+
|
|
2655
|
+
def _is_jax_array(x):
|
|
2656
|
+
"""Return whether *x* is a JAX Array."""
|
|
2657
|
+
try:
|
|
2658
|
+
# We're intentionally not attempting to import jax. If somebody
|
|
2659
|
+
# has created a jax array, jax should already be in sys.modules.
|
|
2660
|
+
tp = sys.modules.get("jax").Array
|
|
2661
|
+
except AttributeError:
|
|
2662
|
+
return False # Module not imported or a nonstandard module with no Array attr.
|
|
2663
|
+
return (isinstance(tp, type) # Just in case it's a very nonstandard module.
|
|
2664
|
+
and isinstance(x, tp))
|
|
2665
|
+
|
|
2666
|
+
|
|
2667
|
+
def _is_mlx_array(x):
|
|
2668
|
+
"""Return whether *x* is a MLX Array."""
|
|
2669
|
+
try:
|
|
2670
|
+
# We're intentionally not attempting to import mlx. If somebody
|
|
2671
|
+
# has created a mlx array, mlx should already be in sys.modules.
|
|
2672
|
+
tp = sys.modules.get("mlx.core").array
|
|
2673
|
+
except AttributeError:
|
|
2674
|
+
return False # Module not imported or a nonstandard module with no Array attr.
|
|
2675
|
+
return (isinstance(tp, type) # Just in case it's a very nonstandard module.
|
|
2676
|
+
and isinstance(x, tp))
|
|
2677
|
+
|
|
2678
|
+
|
|
2679
|
+
def _is_pandas_dataframe(x):
|
|
2680
|
+
"""Check if *x* is a Pandas DataFrame."""
|
|
2681
|
+
try:
|
|
2682
|
+
# We're intentionally not attempting to import Pandas. If somebody
|
|
2683
|
+
# has created a Pandas DataFrame, Pandas should already be in sys.modules.
|
|
2684
|
+
tp = sys.modules.get("pandas").DataFrame
|
|
2685
|
+
except AttributeError:
|
|
2686
|
+
return False # Module not imported or a nonstandard module with no Array attr.
|
|
2687
|
+
return (isinstance(tp, type) # Just in case it's a very nonstandard module.
|
|
2688
|
+
and isinstance(x, tp))
|
|
2689
|
+
|
|
2690
|
+
|
|
2691
|
+
def _is_tensorflow_array(x):
|
|
2692
|
+
"""Return whether *x* is a TensorFlow Tensor or Variable."""
|
|
2693
|
+
try:
|
|
2694
|
+
# We're intentionally not attempting to import TensorFlow. If somebody
|
|
2695
|
+
# has created a TensorFlow array, TensorFlow should already be in
|
|
2696
|
+
# sys.modules we use `is_tensor` to not depend on the class structure
|
|
2697
|
+
# of TensorFlow arrays, as `tf.Variables` are not instances of
|
|
2698
|
+
# `tf.Tensor` (they both convert the same way).
|
|
2699
|
+
is_tensor = sys.modules.get("tensorflow").is_tensor
|
|
2700
|
+
except AttributeError:
|
|
2701
|
+
return False
|
|
2702
|
+
try:
|
|
2703
|
+
return is_tensor(x)
|
|
2704
|
+
except Exception:
|
|
2705
|
+
return False # Just in case it's a very nonstandard module.
|
|
2706
|
+
|
|
2707
|
+
|
|
2708
|
+
def _unpack_to_numpy(x):
|
|
2709
|
+
"""Internal helper to extract data from e.g. pandas and xarray objects."""
|
|
2710
|
+
if isinstance(x, np.ndarray):
|
|
2711
|
+
# If numpy, return directly
|
|
2712
|
+
return x
|
|
2713
|
+
if hasattr(x, 'to_numpy'):
|
|
2714
|
+
# Assume that any to_numpy() method actually returns a numpy array
|
|
2715
|
+
return x.to_numpy()
|
|
2716
|
+
if hasattr(x, 'values'):
|
|
2717
|
+
xtmp = x.values
|
|
2718
|
+
# For example a dict has a 'values' attribute, but it is not a property
|
|
2719
|
+
# so in this case we do not want to return a function
|
|
2720
|
+
if isinstance(xtmp, np.ndarray):
|
|
2721
|
+
return xtmp
|
|
2722
|
+
if _is_torch_array(x) \
|
|
2723
|
+
or _is_jax_array(x) \
|
|
2724
|
+
or _is_tensorflow_array(x) \
|
|
2725
|
+
or _is_mlx_array(x):
|
|
2726
|
+
# using np.asarray() instead of explicitly __array__(), as the latter is
|
|
2727
|
+
# only _one_ of many methods, and it's the last resort, see also
|
|
2728
|
+
# https://numpy.org/devdocs/user/basics.interoperability.html#using-arbitrary-objects-in-numpy
|
|
2729
|
+
# therefore, let arrays do better if they can
|
|
2730
|
+
xtmp = np.asarray(x)
|
|
2731
|
+
|
|
2732
|
+
# In case np.asarray method does not return a numpy array in future
|
|
2733
|
+
if isinstance(xtmp, np.ndarray):
|
|
2734
|
+
return xtmp
|
|
2735
|
+
return x
|
|
2736
|
+
|
|
2737
|
+
|
|
2738
|
+
def _auto_format_str(fmt, value):
|
|
2739
|
+
"""
|
|
2740
|
+
Apply *value* to the format string *fmt*.
|
|
2741
|
+
|
|
2742
|
+
This works both with unnamed %-style formatting and
|
|
2743
|
+
unnamed {}-style formatting. %-style formatting has priority.
|
|
2744
|
+
If *fmt* is %-style formattable that will be used. Otherwise,
|
|
2745
|
+
{}-formatting is applied. Strings without formatting placeholders
|
|
2746
|
+
are passed through as is.
|
|
2747
|
+
|
|
2748
|
+
Examples
|
|
2749
|
+
--------
|
|
2750
|
+
>>> _auto_format_str('%.2f m', 0.2)
|
|
2751
|
+
'0.20 m'
|
|
2752
|
+
>>> _auto_format_str('{} m', 0.2)
|
|
2753
|
+
'0.2 m'
|
|
2754
|
+
>>> _auto_format_str('const', 0.2)
|
|
2755
|
+
'const'
|
|
2756
|
+
>>> _auto_format_str('%d or {}', 0.2)
|
|
2757
|
+
'0 or {}'
|
|
2758
|
+
"""
|
|
2759
|
+
try:
|
|
2760
|
+
return fmt % (value,)
|
|
2761
|
+
except (TypeError, ValueError):
|
|
2762
|
+
return fmt.format(value)
|