ZTWHHH commited on
Commit
04050b0
·
verified ·
1 Parent(s): 7aeb328

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +7 -0
  2. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc +0 -0
  3. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc +0 -0
  4. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc +0 -0
  5. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc +0 -0
  6. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc +0 -0
  7. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc +0 -0
  8. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc +0 -0
  9. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc +0 -0
  10. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc +0 -0
  11. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc +0 -0
  12. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc +0 -0
  13. parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc +0 -0
  14. parrot/lib/python3.10/site-packages/matplotlib/tests/test_agg_filter.py +33 -0
  15. parrot/lib/python3.10/site-packages/matplotlib/tests/test_api.py +116 -0
  16. parrot/lib/python3.10/site-packages/matplotlib/tests/test_artist.py +564 -0
  17. parrot/lib/python3.10/site-packages/matplotlib/tests/test_axis.py +10 -0
  18. parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py +42 -0
  19. parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_pgf.py +408 -0
  20. parrot/lib/python3.10/site-packages/matplotlib/tests/test_collections.py +1338 -0
  21. parrot/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py +175 -0
  22. parrot/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py +77 -0
  23. parrot/lib/python3.10/site-packages/matplotlib/tests/test_figure.py +1759 -0
  24. parrot/lib/python3.10/site-packages/matplotlib/tests/test_lines.py +438 -0
  25. parrot/lib/python3.10/site-packages/matplotlib/tests/test_patches.py +962 -0
  26. parrot/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py +459 -0
  27. parrot/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py +225 -0
  28. parrot/lib/python3.10/site-packages/matplotlib/tests/test_subplots.py +287 -0
  29. parrot/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py +1875 -0
  30. parrot/lib/python3.10/site-packages/matplotlib/tests/test_units.py +304 -0
  31. parrot/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py +187 -0
  32. parrot/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py +1773 -0
  33. parrot/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip +3 -0
  34. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-310-x86_64-linux-gnu.so +3 -0
  35. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so +3 -0
  36. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so +3 -0
  37. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.cpython-310-x86_64-linux-gnu.so +3 -0
  38. videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so +3 -0
  39. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/__init__.cpython-310.pyc +0 -0
  40. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/confusion_matrix.cpython-310.pyc +0 -0
  41. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/det_curve.cpython-310.pyc +0 -0
  42. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/precision_recall_curve.cpython-310.pyc +0 -0
  43. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/regression.cpython-310.pyc +0 -0
  44. videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/__init__.cpython-310.pyc +0 -0
  45. videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__init__.py +0 -0
  46. videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py +1228 -0
  47. videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py +627 -0
  48. videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so +3 -0
  49. videollama2/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so +3 -0
  50. vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h +23 -0
.gitattributes CHANGED
@@ -1931,3 +1931,10 @@ videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython-
1931
  videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1932
  videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1933
  videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
 
 
 
1931
  videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1932
  videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1933
  videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1934
+ videollama2/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1935
+ videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1936
+ videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1937
+ videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1938
+ videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1939
+ videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
1940
+ videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc ADDED
Binary file (1.07 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc ADDED
Binary file (11.9 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc ADDED
Binary file (676 Bytes). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc ADDED
Binary file (20.7 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc ADDED
Binary file (35.9 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc ADDED
Binary file (51.8 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc ADDED
Binary file (1.86 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc ADDED
Binary file (3.3 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc ADDED
Binary file (7.7 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc ADDED
Binary file (9.31 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc ADDED
Binary file (5.55 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc ADDED
Binary file (6.66 kB). View file
 
parrot/lib/python3.10/site-packages/matplotlib/tests/test_agg_filter.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib.testing.decorators import image_comparison
5
+
6
+
7
+ @image_comparison(baseline_images=['agg_filter_alpha'],
8
+ extensions=['png', 'pdf'])
9
+ def test_agg_filter_alpha():
10
+ # Remove this line when this test image is regenerated.
11
+ plt.rcParams['pcolormesh.snap'] = False
12
+
13
+ ax = plt.axes()
14
+ x, y = np.mgrid[0:7, 0:8]
15
+ data = x**2 - y**2
16
+ mesh = ax.pcolormesh(data, cmap='Reds', zorder=5)
17
+
18
+ def manual_alpha(im, dpi):
19
+ im[:, :, 3] *= 0.6
20
+ print('CALLED')
21
+ return im, 0, 0
22
+
23
+ # Note: Doing alpha like this is not the same as setting alpha on
24
+ # the mesh itself. Currently meshes are drawn as independent patches,
25
+ # and we see fine borders around the blocks of color. See the SO
26
+ # question for an example: https://stackoverflow.com/q/20678817/
27
+ mesh.set_agg_filter(manual_alpha)
28
+
29
+ # Currently we must enable rasterization for this to have an effect in
30
+ # the PDF backend.
31
+ mesh.set_rasterized(True)
32
+
33
+ ax.plot([0, 4, 7], [1, 3, 8])
parrot/lib/python3.10/site-packages/matplotlib/tests/test_api.py ADDED
@@ -0,0 +1,116 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import re
4
+ import typing
5
+ from typing import Any, Callable, TypeVar
6
+
7
+ import numpy as np
8
+ import pytest
9
+
10
+ import matplotlib as mpl
11
+ from matplotlib import _api
12
+
13
+
14
+ if typing.TYPE_CHECKING:
15
+ from typing_extensions import Self
16
+
17
+ T = TypeVar('T')
18
+
19
+
20
+ @pytest.mark.parametrize('target,shape_repr,test_shape',
21
+ [((None, ), "(N,)", (1, 3)),
22
+ ((None, 3), "(N, 3)", (1,)),
23
+ ((None, 3), "(N, 3)", (1, 2)),
24
+ ((1, 5), "(1, 5)", (1, 9)),
25
+ ((None, 2, None), "(M, 2, N)", (1, 3, 1))
26
+ ])
27
+ def test_check_shape(target: tuple[int | None, ...],
28
+ shape_repr: str,
29
+ test_shape: tuple[int, ...]) -> None:
30
+ error_pattern = "^" + re.escape(
31
+ f"'aardvark' must be {len(target)}D with shape {shape_repr}, but your input "
32
+ f"has shape {test_shape}")
33
+ data = np.zeros(test_shape)
34
+ with pytest.raises(ValueError, match=error_pattern):
35
+ _api.check_shape(target, aardvark=data)
36
+
37
+
38
+ def test_classproperty_deprecation() -> None:
39
+ class A:
40
+ @_api.deprecated("0.0.0")
41
+ @_api.classproperty
42
+ def f(cls: Self) -> None:
43
+ pass
44
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
45
+ A.f
46
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
47
+ a = A()
48
+ a.f
49
+
50
+
51
+ def test_deprecate_privatize_attribute() -> None:
52
+ class C:
53
+ def __init__(self) -> None: self._attr = 1
54
+ def _meth(self, arg: T) -> T: return arg
55
+ attr: int = _api.deprecate_privatize_attribute("0.0")
56
+ meth: Callable = _api.deprecate_privatize_attribute("0.0")
57
+
58
+ c = C()
59
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
60
+ assert c.attr == 1
61
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
62
+ c.attr = 2
63
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
64
+ assert c.attr == 2
65
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
66
+ assert c.meth(42) == 42
67
+
68
+
69
+ def test_delete_parameter() -> None:
70
+ @_api.delete_parameter("3.0", "foo")
71
+ def func1(foo: Any = None) -> None:
72
+ pass
73
+
74
+ @_api.delete_parameter("3.0", "foo")
75
+ def func2(**kwargs: Any) -> None:
76
+ pass
77
+
78
+ for func in [func1, func2]: # type: ignore[list-item]
79
+ func() # No warning.
80
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
81
+ func(foo="bar")
82
+
83
+ def pyplot_wrapper(foo: Any = _api.deprecation._deprecated_parameter) -> None:
84
+ func1(foo)
85
+
86
+ pyplot_wrapper() # No warning.
87
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
88
+ func(foo="bar")
89
+
90
+
91
+ def test_make_keyword_only() -> None:
92
+ @_api.make_keyword_only("3.0", "arg")
93
+ def func(pre: Any, arg: Any, post: Any = None) -> None:
94
+ pass
95
+
96
+ func(1, arg=2) # Check that no warning is emitted.
97
+
98
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
99
+ func(1, 2)
100
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
101
+ func(1, 2, 3)
102
+
103
+
104
+ def test_deprecation_alternative() -> None:
105
+ alternative = "`.f1`, `f2`, `f3(x) <.f3>` or `f4(x)<f4>`"
106
+ @_api.deprecated("1", alternative=alternative)
107
+ def f() -> None:
108
+ pass
109
+ if f.__doc__ is None:
110
+ pytest.skip('Documentation is disabled')
111
+ assert alternative in f.__doc__
112
+
113
+
114
+ def test_empty_check_in_list() -> None:
115
+ with pytest.raises(TypeError, match="No argument to check!"):
116
+ _api.check_in_list(["a"])
parrot/lib/python3.10/site-packages/matplotlib/tests/test_artist.py ADDED
@@ -0,0 +1,564 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import io
2
+ from itertools import chain
3
+
4
+ import numpy as np
5
+
6
+ import pytest
7
+
8
+ import matplotlib.colors as mcolors
9
+ import matplotlib.pyplot as plt
10
+ import matplotlib.patches as mpatches
11
+ import matplotlib.lines as mlines
12
+ import matplotlib.path as mpath
13
+ import matplotlib.transforms as mtransforms
14
+ import matplotlib.collections as mcollections
15
+ import matplotlib.artist as martist
16
+ import matplotlib.backend_bases as mbackend_bases
17
+ import matplotlib as mpl
18
+ from matplotlib.testing.decorators import check_figures_equal, image_comparison
19
+
20
+
21
+ def test_patch_transform_of_none():
22
+ # tests the behaviour of patches added to an Axes with various transform
23
+ # specifications
24
+
25
+ ax = plt.axes()
26
+ ax.set_xlim(1, 3)
27
+ ax.set_ylim(1, 3)
28
+
29
+ # Draw an ellipse over data coord (2, 2) by specifying device coords.
30
+ xy_data = (2, 2)
31
+ xy_pix = ax.transData.transform(xy_data)
32
+
33
+ # Not providing a transform of None puts the ellipse in data coordinates .
34
+ e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5)
35
+ ax.add_patch(e)
36
+ assert e._transform == ax.transData
37
+
38
+ # Providing a transform of None puts the ellipse in device coordinates.
39
+ e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
40
+ transform=None, alpha=0.5)
41
+ assert e.is_transform_set()
42
+ ax.add_patch(e)
43
+ assert isinstance(e._transform, mtransforms.IdentityTransform)
44
+
45
+ # Providing an IdentityTransform puts the ellipse in device coordinates.
46
+ e = mpatches.Ellipse(xy_pix, width=100, height=100,
47
+ transform=mtransforms.IdentityTransform(), alpha=0.5)
48
+ ax.add_patch(e)
49
+ assert isinstance(e._transform, mtransforms.IdentityTransform)
50
+
51
+ # Not providing a transform, and then subsequently "get_transform" should
52
+ # not mean that "is_transform_set".
53
+ e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral',
54
+ alpha=0.5)
55
+ intermediate_transform = e.get_transform()
56
+ assert not e.is_transform_set()
57
+ ax.add_patch(e)
58
+ assert e.get_transform() != intermediate_transform
59
+ assert e.is_transform_set()
60
+ assert e._transform == ax.transData
61
+
62
+
63
+ def test_collection_transform_of_none():
64
+ # tests the behaviour of collections added to an Axes with various
65
+ # transform specifications
66
+
67
+ ax = plt.axes()
68
+ ax.set_xlim(1, 3)
69
+ ax.set_ylim(1, 3)
70
+
71
+ # draw an ellipse over data coord (2, 2) by specifying device coords
72
+ xy_data = (2, 2)
73
+ xy_pix = ax.transData.transform(xy_data)
74
+
75
+ # not providing a transform of None puts the ellipse in data coordinates
76
+ e = mpatches.Ellipse(xy_data, width=1, height=1)
77
+ c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5)
78
+ ax.add_collection(c)
79
+ # the collection should be in data coordinates
80
+ assert c.get_offset_transform() + c.get_transform() == ax.transData
81
+
82
+ # providing a transform of None puts the ellipse in device coordinates
83
+ e = mpatches.Ellipse(xy_pix, width=120, height=120)
84
+ c = mcollections.PatchCollection([e], facecolor='coral',
85
+ alpha=0.5)
86
+ c.set_transform(None)
87
+ ax.add_collection(c)
88
+ assert isinstance(c.get_transform(), mtransforms.IdentityTransform)
89
+
90
+ # providing an IdentityTransform puts the ellipse in device coordinates
91
+ e = mpatches.Ellipse(xy_pix, width=100, height=100)
92
+ c = mcollections.PatchCollection([e],
93
+ transform=mtransforms.IdentityTransform(),
94
+ alpha=0.5)
95
+ ax.add_collection(c)
96
+ assert isinstance(c.get_offset_transform(), mtransforms.IdentityTransform)
97
+
98
+
99
+ @image_comparison(["clip_path_clipping"], remove_text=True)
100
+ def test_clipping():
101
+ exterior = mpath.Path.unit_rectangle().deepcopy()
102
+ exterior.vertices *= 4
103
+ exterior.vertices -= 2
104
+ interior = mpath.Path.unit_circle().deepcopy()
105
+ interior.vertices = interior.vertices[::-1]
106
+ clip_path = mpath.Path.make_compound_path(exterior, interior)
107
+
108
+ star = mpath.Path.unit_regular_star(6).deepcopy()
109
+ star.vertices *= 2.6
110
+
111
+ fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
112
+
113
+ col = mcollections.PathCollection([star], lw=5, edgecolor='blue',
114
+ facecolor='red', alpha=0.7, hatch='*')
115
+ col.set_clip_path(clip_path, ax1.transData)
116
+ ax1.add_collection(col)
117
+
118
+ patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red',
119
+ alpha=0.7, hatch='*')
120
+ patch.set_clip_path(clip_path, ax2.transData)
121
+ ax2.add_patch(patch)
122
+
123
+ ax1.set_xlim([-3, 3])
124
+ ax1.set_ylim([-3, 3])
125
+
126
+
127
+ @check_figures_equal(extensions=['png'])
128
+ def test_clipping_zoom(fig_test, fig_ref):
129
+ # This test places the Axes and sets its limits such that the clip path is
130
+ # outside the figure entirely. This should not break the clip path.
131
+ ax_test = fig_test.add_axes([0, 0, 1, 1])
132
+ l, = ax_test.plot([-3, 3], [-3, 3])
133
+ # Explicit Path instead of a Rectangle uses clip path processing, instead
134
+ # of a clip box optimization.
135
+ p = mpath.Path([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
136
+ p = mpatches.PathPatch(p, transform=ax_test.transData)
137
+ l.set_clip_path(p)
138
+
139
+ ax_ref = fig_ref.add_axes([0, 0, 1, 1])
140
+ ax_ref.plot([-3, 3], [-3, 3])
141
+
142
+ ax_ref.set(xlim=(0.5, 0.75), ylim=(0.5, 0.75))
143
+ ax_test.set(xlim=(0.5, 0.75), ylim=(0.5, 0.75))
144
+
145
+
146
+ def test_cull_markers():
147
+ x = np.random.random(20000)
148
+ y = np.random.random(20000)
149
+
150
+ fig, ax = plt.subplots()
151
+ ax.plot(x, y, 'k.')
152
+ ax.set_xlim(2, 3)
153
+
154
+ pdf = io.BytesIO()
155
+ fig.savefig(pdf, format="pdf")
156
+ assert len(pdf.getvalue()) < 8000
157
+
158
+ svg = io.BytesIO()
159
+ fig.savefig(svg, format="svg")
160
+ assert len(svg.getvalue()) < 20000
161
+
162
+
163
+ @image_comparison(['hatching'], remove_text=True, style='default')
164
+ def test_hatching():
165
+ fig, ax = plt.subplots(1, 1)
166
+
167
+ # Default hatch color.
168
+ rect1 = mpatches.Rectangle((0, 0), 3, 4, hatch='/')
169
+ ax.add_patch(rect1)
170
+
171
+ rect2 = mcollections.RegularPolyCollection(
172
+ 4, sizes=[16000], offsets=[(1.5, 6.5)], offset_transform=ax.transData,
173
+ hatch='/')
174
+ ax.add_collection(rect2)
175
+
176
+ # Ensure edge color is not applied to hatching.
177
+ rect3 = mpatches.Rectangle((4, 0), 3, 4, hatch='/', edgecolor='C1')
178
+ ax.add_patch(rect3)
179
+
180
+ rect4 = mcollections.RegularPolyCollection(
181
+ 4, sizes=[16000], offsets=[(5.5, 6.5)], offset_transform=ax.transData,
182
+ hatch='/', edgecolor='C1')
183
+ ax.add_collection(rect4)
184
+
185
+ ax.set_xlim(0, 7)
186
+ ax.set_ylim(0, 9)
187
+
188
+
189
+ def test_remove():
190
+ fig, ax = plt.subplots()
191
+ im = ax.imshow(np.arange(36).reshape(6, 6))
192
+ ln, = ax.plot(range(5))
193
+
194
+ assert fig.stale
195
+ assert ax.stale
196
+
197
+ fig.canvas.draw()
198
+ assert not fig.stale
199
+ assert not ax.stale
200
+ assert not ln.stale
201
+
202
+ assert im in ax._mouseover_set
203
+ assert ln not in ax._mouseover_set
204
+ assert im.axes is ax
205
+
206
+ im.remove()
207
+ ln.remove()
208
+
209
+ for art in [im, ln]:
210
+ assert art.axes is None
211
+ assert art.figure is None
212
+
213
+ assert im not in ax._mouseover_set
214
+ assert fig.stale
215
+ assert ax.stale
216
+
217
+
218
+ @image_comparison(["default_edges.png"], remove_text=True, style='default')
219
+ def test_default_edges():
220
+ # Remove this line when this test image is regenerated.
221
+ plt.rcParams['text.kerning_factor'] = 6
222
+
223
+ fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2)
224
+
225
+ ax1.plot(np.arange(10), np.arange(10), 'x',
226
+ np.arange(10) + 1, np.arange(10), 'o')
227
+ ax2.bar(np.arange(10), np.arange(10), align='edge')
228
+ ax3.text(0, 0, "BOX", size=24, bbox=dict(boxstyle='sawtooth'))
229
+ ax3.set_xlim((-1, 1))
230
+ ax3.set_ylim((-1, 1))
231
+ pp1 = mpatches.PathPatch(
232
+ mpath.Path([(0, 0), (1, 0), (1, 1), (0, 0)],
233
+ [mpath.Path.MOVETO, mpath.Path.CURVE3,
234
+ mpath.Path.CURVE3, mpath.Path.CLOSEPOLY]),
235
+ fc="none", transform=ax4.transData)
236
+ ax4.add_patch(pp1)
237
+
238
+
239
+ def test_properties():
240
+ ln = mlines.Line2D([], [])
241
+ ln.properties() # Check that no warning is emitted.
242
+
243
+
244
+ def test_setp():
245
+ # Check empty list
246
+ plt.setp([])
247
+ plt.setp([[]])
248
+
249
+ # Check arbitrary iterables
250
+ fig, ax = plt.subplots()
251
+ lines1 = ax.plot(range(3))
252
+ lines2 = ax.plot(range(3))
253
+ martist.setp(chain(lines1, lines2), 'lw', 5)
254
+ plt.setp(ax.spines.values(), color='green')
255
+
256
+ # Check *file* argument
257
+ sio = io.StringIO()
258
+ plt.setp(lines1, 'zorder', file=sio)
259
+ assert sio.getvalue() == ' zorder: float\n'
260
+
261
+
262
+ def test_None_zorder():
263
+ fig, ax = plt.subplots()
264
+ ln, = ax.plot(range(5), zorder=None)
265
+ assert ln.get_zorder() == mlines.Line2D.zorder
266
+ ln.set_zorder(123456)
267
+ assert ln.get_zorder() == 123456
268
+ ln.set_zorder(None)
269
+ assert ln.get_zorder() == mlines.Line2D.zorder
270
+
271
+
272
+ @pytest.mark.parametrize('accept_clause, expected', [
273
+ ('', 'unknown'),
274
+ ("ACCEPTS: [ '-' | '--' | '-.' ]", "[ '-' | '--' | '-.' ]"),
275
+ ('ACCEPTS: Some description.', 'Some description.'),
276
+ ('.. ACCEPTS: Some description.', 'Some description.'),
277
+ ('arg : int', 'int'),
278
+ ('*arg : int', 'int'),
279
+ ('arg : int\nACCEPTS: Something else.', 'Something else. '),
280
+ ])
281
+ def test_artist_inspector_get_valid_values(accept_clause, expected):
282
+ class TestArtist(martist.Artist):
283
+ def set_f(self, arg):
284
+ pass
285
+
286
+ TestArtist.set_f.__doc__ = """
287
+ Some text.
288
+
289
+ %s
290
+ """ % accept_clause
291
+ valid_values = martist.ArtistInspector(TestArtist).get_valid_values('f')
292
+ assert valid_values == expected
293
+
294
+
295
+ def test_artist_inspector_get_aliases():
296
+ # test the correct format and type of get_aliases method
297
+ ai = martist.ArtistInspector(mlines.Line2D)
298
+ aliases = ai.get_aliases()
299
+ assert aliases["linewidth"] == {"lw"}
300
+
301
+
302
+ def test_set_alpha():
303
+ art = martist.Artist()
304
+ with pytest.raises(TypeError, match='^alpha must be numeric or None'):
305
+ art.set_alpha('string')
306
+ with pytest.raises(TypeError, match='^alpha must be numeric or None'):
307
+ art.set_alpha([1, 2, 3])
308
+ with pytest.raises(ValueError, match="outside 0-1 range"):
309
+ art.set_alpha(1.1)
310
+ with pytest.raises(ValueError, match="outside 0-1 range"):
311
+ art.set_alpha(np.nan)
312
+
313
+
314
+ def test_set_alpha_for_array():
315
+ art = martist.Artist()
316
+ with pytest.raises(TypeError, match='^alpha must be numeric or None'):
317
+ art._set_alpha_for_array('string')
318
+ with pytest.raises(ValueError, match="outside 0-1 range"):
319
+ art._set_alpha_for_array(1.1)
320
+ with pytest.raises(ValueError, match="outside 0-1 range"):
321
+ art._set_alpha_for_array(np.nan)
322
+ with pytest.raises(ValueError, match="alpha must be between 0 and 1"):
323
+ art._set_alpha_for_array([0.5, 1.1])
324
+ with pytest.raises(ValueError, match="alpha must be between 0 and 1"):
325
+ art._set_alpha_for_array([0.5, np.nan])
326
+
327
+
328
+ def test_callbacks():
329
+ def func(artist):
330
+ func.counter += 1
331
+
332
+ func.counter = 0
333
+
334
+ art = martist.Artist()
335
+ oid = art.add_callback(func)
336
+ assert func.counter == 0
337
+ art.pchanged() # must call the callback
338
+ assert func.counter == 1
339
+ art.set_zorder(10) # setting a property must also call the callback
340
+ assert func.counter == 2
341
+ art.remove_callback(oid)
342
+ art.pchanged() # must not call the callback anymore
343
+ assert func.counter == 2
344
+
345
+
346
+ def test_set_signature():
347
+ """Test autogenerated ``set()`` for Artist subclasses."""
348
+ class MyArtist1(martist.Artist):
349
+ def set_myparam1(self, val):
350
+ pass
351
+
352
+ assert hasattr(MyArtist1.set, '_autogenerated_signature')
353
+ assert 'myparam1' in MyArtist1.set.__doc__
354
+
355
+ class MyArtist2(MyArtist1):
356
+ def set_myparam2(self, val):
357
+ pass
358
+
359
+ assert hasattr(MyArtist2.set, '_autogenerated_signature')
360
+ assert 'myparam1' in MyArtist2.set.__doc__
361
+ assert 'myparam2' in MyArtist2.set.__doc__
362
+
363
+
364
+ def test_set_is_overwritten():
365
+ """set() defined in Artist subclasses should not be overwritten."""
366
+ class MyArtist3(martist.Artist):
367
+
368
+ def set(self, **kwargs):
369
+ """Not overwritten."""
370
+
371
+ assert not hasattr(MyArtist3.set, '_autogenerated_signature')
372
+ assert MyArtist3.set.__doc__ == "Not overwritten."
373
+
374
+ class MyArtist4(MyArtist3):
375
+ pass
376
+
377
+ assert MyArtist4.set is MyArtist3.set
378
+
379
+
380
+ def test_format_cursor_data_BoundaryNorm():
381
+ """Test if cursor data is correct when using BoundaryNorm."""
382
+ X = np.empty((3, 3))
383
+ X[0, 0] = 0.9
384
+ X[0, 1] = 0.99
385
+ X[0, 2] = 0.999
386
+ X[1, 0] = -1
387
+ X[1, 1] = 0
388
+ X[1, 2] = 1
389
+ X[2, 0] = 0.09
390
+ X[2, 1] = 0.009
391
+ X[2, 2] = 0.0009
392
+
393
+ # map range -1..1 to 0..256 in 0.1 steps
394
+ fig, ax = plt.subplots()
395
+ fig.suptitle("-1..1 to 0..256 in 0.1")
396
+ norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 20), 256)
397
+ img = ax.imshow(X, cmap='RdBu_r', norm=norm)
398
+
399
+ labels_list = [
400
+ "[0.9]",
401
+ "[1.]",
402
+ "[1.]",
403
+ "[-1.0]",
404
+ "[0.0]",
405
+ "[1.0]",
406
+ "[0.09]",
407
+ "[0.009]",
408
+ "[0.0009]",
409
+ ]
410
+ for v, label in zip(X.flat, labels_list):
411
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.1))
412
+ assert img.format_cursor_data(v) == label
413
+
414
+ plt.close()
415
+
416
+ # map range -1..1 to 0..256 in 0.01 steps
417
+ fig, ax = plt.subplots()
418
+ fig.suptitle("-1..1 to 0..256 in 0.01")
419
+ cmap = mpl.colormaps['RdBu_r'].resampled(200)
420
+ norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 200), 200)
421
+ img = ax.imshow(X, cmap=cmap, norm=norm)
422
+
423
+ labels_list = [
424
+ "[0.90]",
425
+ "[0.99]",
426
+ "[1.0]",
427
+ "[-1.00]",
428
+ "[0.00]",
429
+ "[1.00]",
430
+ "[0.09]",
431
+ "[0.009]",
432
+ "[0.0009]",
433
+ ]
434
+ for v, label in zip(X.flat, labels_list):
435
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.01))
436
+ assert img.format_cursor_data(v) == label
437
+
438
+ plt.close()
439
+
440
+ # map range -1..1 to 0..256 in 0.01 steps
441
+ fig, ax = plt.subplots()
442
+ fig.suptitle("-1..1 to 0..256 in 0.001")
443
+ cmap = mpl.colormaps['RdBu_r'].resampled(2000)
444
+ norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 2000), 2000)
445
+ img = ax.imshow(X, cmap=cmap, norm=norm)
446
+
447
+ labels_list = [
448
+ "[0.900]",
449
+ "[0.990]",
450
+ "[0.999]",
451
+ "[-1.000]",
452
+ "[0.000]",
453
+ "[1.000]",
454
+ "[0.090]",
455
+ "[0.009]",
456
+ "[0.0009]",
457
+ ]
458
+ for v, label in zip(X.flat, labels_list):
459
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.001))
460
+ assert img.format_cursor_data(v) == label
461
+
462
+ plt.close()
463
+
464
+ # different testing data set with
465
+ # out of bounds values for 0..1 range
466
+ X = np.empty((7, 1))
467
+ X[0] = -1.0
468
+ X[1] = 0.0
469
+ X[2] = 0.1
470
+ X[3] = 0.5
471
+ X[4] = 0.9
472
+ X[5] = 1.0
473
+ X[6] = 2.0
474
+
475
+ labels_list = [
476
+ "[-1.0]",
477
+ "[0.0]",
478
+ "[0.1]",
479
+ "[0.5]",
480
+ "[0.9]",
481
+ "[1.0]",
482
+ "[2.0]",
483
+ ]
484
+
485
+ fig, ax = plt.subplots()
486
+ fig.suptitle("noclip, neither")
487
+ norm = mcolors.BoundaryNorm(
488
+ np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='neither')
489
+ img = ax.imshow(X, cmap='RdBu_r', norm=norm)
490
+ for v, label in zip(X.flat, labels_list):
491
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))
492
+ assert img.format_cursor_data(v) == label
493
+
494
+ plt.close()
495
+
496
+ fig, ax = plt.subplots()
497
+ fig.suptitle("noclip, min")
498
+ norm = mcolors.BoundaryNorm(
499
+ np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='min')
500
+ img = ax.imshow(X, cmap='RdBu_r', norm=norm)
501
+ for v, label in zip(X.flat, labels_list):
502
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))
503
+ assert img.format_cursor_data(v) == label
504
+
505
+ plt.close()
506
+
507
+ fig, ax = plt.subplots()
508
+ fig.suptitle("noclip, max")
509
+ norm = mcolors.BoundaryNorm(
510
+ np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='max')
511
+ img = ax.imshow(X, cmap='RdBu_r', norm=norm)
512
+ for v, label in zip(X.flat, labels_list):
513
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))
514
+ assert img.format_cursor_data(v) == label
515
+
516
+ plt.close()
517
+
518
+ fig, ax = plt.subplots()
519
+ fig.suptitle("noclip, both")
520
+ norm = mcolors.BoundaryNorm(
521
+ np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='both')
522
+ img = ax.imshow(X, cmap='RdBu_r', norm=norm)
523
+ for v, label in zip(X.flat, labels_list):
524
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))
525
+ assert img.format_cursor_data(v) == label
526
+
527
+ plt.close()
528
+
529
+ fig, ax = plt.subplots()
530
+ fig.suptitle("clip, neither")
531
+ norm = mcolors.BoundaryNorm(
532
+ np.linspace(0, 1, 4, endpoint=True), 256, clip=True, extend='neither')
533
+ img = ax.imshow(X, cmap='RdBu_r', norm=norm)
534
+ for v, label in zip(X.flat, labels_list):
535
+ # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33))
536
+ assert img.format_cursor_data(v) == label
537
+
538
+ plt.close()
539
+
540
+
541
+ def test_auto_no_rasterize():
542
+ class Gen1(martist.Artist):
543
+ ...
544
+
545
+ assert 'draw' in Gen1.__dict__
546
+ assert Gen1.__dict__['draw'] is Gen1.draw
547
+
548
+ class Gen2(Gen1):
549
+ ...
550
+
551
+ assert 'draw' not in Gen2.__dict__
552
+ assert Gen2.draw is Gen1.draw
553
+
554
+
555
+ def test_draw_wraper_forward_input():
556
+ class TestKlass(martist.Artist):
557
+ def draw(self, renderer, extra):
558
+ return extra
559
+
560
+ art = TestKlass()
561
+ renderer = mbackend_bases.RendererBase()
562
+
563
+ assert 'aardvark' == art.draw(renderer, 'aardvark')
564
+ assert 'aardvark' == art.draw(renderer, extra='aardvark')
parrot/lib/python3.10/site-packages/matplotlib/tests/test_axis.py ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+
3
+ import matplotlib.pyplot as plt
4
+ from matplotlib.axis import XTick
5
+
6
+
7
+ def test_tick_labelcolor_array():
8
+ # Smoke test that we can instantiate a Tick with labelcolor as array.
9
+ ax = plt.axes()
10
+ XTick(ax, 0, labelcolor=np.array([1, 0, 0, 1]))
parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from pathlib import Path
3
+ from tempfile import TemporaryDirectory
4
+
5
+ import pytest
6
+
7
+ from matplotlib.testing import subprocess_run_for_testing
8
+
9
+ nbformat = pytest.importorskip('nbformat')
10
+ pytest.importorskip('nbconvert')
11
+ pytest.importorskip('ipykernel')
12
+
13
+ # From https://blog.thedataincubator.com/2016/06/testing-jupyter-notebooks/
14
+
15
+
16
+ def test_ipynb():
17
+ nb_path = Path(__file__).parent / 'test_nbagg_01.ipynb'
18
+
19
+ with TemporaryDirectory() as tmpdir:
20
+ out_path = Path(tmpdir, "out.ipynb")
21
+ subprocess_run_for_testing(
22
+ ["jupyter", "nbconvert", "--to", "notebook",
23
+ "--execute", "--ExecutePreprocessor.timeout=500",
24
+ "--output", str(out_path), str(nb_path)],
25
+ env={**os.environ, "IPYTHONDIR": tmpdir},
26
+ check=True)
27
+ with out_path.open() as out:
28
+ nb = nbformat.read(out, nbformat.current_nbformat)
29
+
30
+ errors = [output for cell in nb.cells for output in cell.get("outputs", [])
31
+ if output.output_type == "error"]
32
+ assert not errors
33
+
34
+ import IPython
35
+ if IPython.version_info[:2] >= (8, 24):
36
+ expected_backend = "notebook"
37
+ else:
38
+ # This code can be removed when Python 3.12, the latest version supported by
39
+ # IPython < 8.24, reaches end-of-life in late 2028.
40
+ expected_backend = "nbAgg"
41
+ backend_outputs = nb.cells[2]["outputs"]
42
+ assert backend_outputs[0]["data"]["text/plain"] == f"'{expected_backend}'"
parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_pgf.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import datetime
2
+ from io import BytesIO
3
+ import os
4
+ import shutil
5
+
6
+ import numpy as np
7
+ from packaging.version import parse as parse_version
8
+ import pytest
9
+
10
+ import matplotlib as mpl
11
+ import matplotlib.pyplot as plt
12
+ from matplotlib.testing import _has_tex_package, _check_for_pgf
13
+ from matplotlib.testing.exceptions import ImageComparisonFailure
14
+ from matplotlib.testing.compare import compare_images
15
+ from matplotlib.backends.backend_pgf import PdfPages
16
+ from matplotlib.testing.decorators import (
17
+ _image_directories, check_figures_equal, image_comparison)
18
+ from matplotlib.testing._markers import (
19
+ needs_ghostscript, needs_pgf_lualatex, needs_pgf_pdflatex,
20
+ needs_pgf_xelatex)
21
+
22
+
23
+ baseline_dir, result_dir = _image_directories(lambda: 'dummy func')
24
+
25
+
26
+ def compare_figure(fname, savefig_kwargs={}, tol=0):
27
+ actual = os.path.join(result_dir, fname)
28
+ plt.savefig(actual, **savefig_kwargs)
29
+
30
+ expected = os.path.join(result_dir, "expected_%s" % fname)
31
+ shutil.copyfile(os.path.join(baseline_dir, fname), expected)
32
+ err = compare_images(expected, actual, tol=tol)
33
+ if err:
34
+ raise ImageComparisonFailure(err)
35
+
36
+
37
+ @needs_pgf_xelatex
38
+ @needs_ghostscript
39
+ @pytest.mark.backend('pgf')
40
+ def test_tex_special_chars(tmp_path):
41
+ fig = plt.figure()
42
+ fig.text(.5, .5, "%_^ $a_b^c$")
43
+ buf = BytesIO()
44
+ fig.savefig(buf, format="png", backend="pgf")
45
+ buf.seek(0)
46
+ t = plt.imread(buf)
47
+ assert not (t == 1).all() # The leading "%" didn't eat up everything.
48
+
49
+
50
+ def create_figure():
51
+ plt.figure()
52
+ x = np.linspace(0, 1, 15)
53
+
54
+ # line plot
55
+ plt.plot(x, x ** 2, "b-")
56
+
57
+ # marker
58
+ plt.plot(x, 1 - x**2, "g>")
59
+
60
+ # filled paths and patterns
61
+ plt.fill_between([0., .4], [.4, 0.], hatch='//', facecolor="lightgray",
62
+ edgecolor="red")
63
+ plt.fill([3, 3, .8, .8, 3], [2, -2, -2, 0, 2], "b")
64
+
65
+ # text and typesetting
66
+ plt.plot([0.9], [0.5], "ro", markersize=3)
67
+ plt.text(0.9, 0.5, 'unicode (ü, °, \N{Section Sign}) and math ($\\mu_i = x_i^2$)',
68
+ ha='right', fontsize=20)
69
+ plt.ylabel('sans-serif, blue, $\\frac{\\sqrt{x}}{y^2}$..',
70
+ family='sans-serif', color='blue')
71
+ plt.text(1, 1, 'should be clipped as default clip_box is Axes bbox',
72
+ fontsize=20, clip_on=True)
73
+
74
+ plt.xlim(0, 1)
75
+ plt.ylim(0, 1)
76
+
77
+
78
+ # test compiling a figure to pdf with xelatex
79
+ @needs_pgf_xelatex
80
+ @pytest.mark.backend('pgf')
81
+ @image_comparison(['pgf_xelatex.pdf'], style='default')
82
+ def test_xelatex():
83
+ rc_xelatex = {'font.family': 'serif',
84
+ 'pgf.rcfonts': False}
85
+ mpl.rcParams.update(rc_xelatex)
86
+ create_figure()
87
+
88
+
89
+ try:
90
+ _old_gs_version = \
91
+ mpl._get_executable_info('gs').version < parse_version('9.50')
92
+ except mpl.ExecutableNotFoundError:
93
+ _old_gs_version = True
94
+
95
+
96
+ # test compiling a figure to pdf with pdflatex
97
+ @needs_pgf_pdflatex
98
+ @pytest.mark.skipif(not _has_tex_package('type1ec'), reason='needs type1ec.sty')
99
+ @pytest.mark.skipif(not _has_tex_package('ucs'), reason='needs ucs.sty')
100
+ @pytest.mark.backend('pgf')
101
+ @image_comparison(['pgf_pdflatex.pdf'], style='default',
102
+ tol=11.71 if _old_gs_version else 0)
103
+ def test_pdflatex():
104
+ rc_pdflatex = {'font.family': 'serif',
105
+ 'pgf.rcfonts': False,
106
+ 'pgf.texsystem': 'pdflatex',
107
+ 'pgf.preamble': ('\\usepackage[utf8x]{inputenc}'
108
+ '\\usepackage[T1]{fontenc}')}
109
+ mpl.rcParams.update(rc_pdflatex)
110
+ create_figure()
111
+
112
+
113
+ # test updating the rc parameters for each figure
114
+ @needs_pgf_xelatex
115
+ @needs_pgf_pdflatex
116
+ @mpl.style.context('default')
117
+ @pytest.mark.backend('pgf')
118
+ def test_rcupdate():
119
+ rc_sets = [{'font.family': 'sans-serif',
120
+ 'font.size': 30,
121
+ 'figure.subplot.left': .2,
122
+ 'lines.markersize': 10,
123
+ 'pgf.rcfonts': False,
124
+ 'pgf.texsystem': 'xelatex'},
125
+ {'font.family': 'monospace',
126
+ 'font.size': 10,
127
+ 'figure.subplot.left': .1,
128
+ 'lines.markersize': 20,
129
+ 'pgf.rcfonts': False,
130
+ 'pgf.texsystem': 'pdflatex',
131
+ 'pgf.preamble': ('\\usepackage[utf8x]{inputenc}'
132
+ '\\usepackage[T1]{fontenc}'
133
+ '\\usepackage{sfmath}')}]
134
+ tol = [0, 13.2] if _old_gs_version else [0, 0]
135
+ for i, rc_set in enumerate(rc_sets):
136
+ with mpl.rc_context(rc_set):
137
+ for substring, pkg in [('sfmath', 'sfmath'), ('utf8x', 'ucs')]:
138
+ if (substring in mpl.rcParams['pgf.preamble']
139
+ and not _has_tex_package(pkg)):
140
+ pytest.skip(f'needs {pkg}.sty')
141
+ create_figure()
142
+ compare_figure(f'pgf_rcupdate{i + 1}.pdf', tol=tol[i])
143
+
144
+
145
+ # test backend-side clipping, since large numbers are not supported by TeX
146
+ @needs_pgf_xelatex
147
+ @mpl.style.context('default')
148
+ @pytest.mark.backend('pgf')
149
+ def test_pathclip():
150
+ np.random.seed(19680801)
151
+ mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False})
152
+ fig, axs = plt.subplots(1, 2)
153
+
154
+ axs[0].plot([0., 1e100], [0., 1e100])
155
+ axs[0].set_xlim(0, 1)
156
+ axs[0].set_ylim(0, 1)
157
+
158
+ axs[1].scatter([0, 1], [1, 1])
159
+ axs[1].hist(np.random.normal(size=1000), bins=20, range=[-10, 10])
160
+ axs[1].set_xscale('log')
161
+
162
+ fig.savefig(BytesIO(), format="pdf") # No image comparison.
163
+
164
+
165
+ # test mixed mode rendering
166
+ @needs_pgf_xelatex
167
+ @pytest.mark.backend('pgf')
168
+ @image_comparison(['pgf_mixedmode.pdf'], style='default')
169
+ def test_mixedmode():
170
+ mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False})
171
+ Y, X = np.ogrid[-1:1:40j, -1:1:40j]
172
+ plt.pcolor(X**2 + Y**2).set_rasterized(True)
173
+
174
+
175
+ # test bbox_inches clipping
176
+ @needs_pgf_xelatex
177
+ @mpl.style.context('default')
178
+ @pytest.mark.backend('pgf')
179
+ def test_bbox_inches():
180
+ mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False})
181
+ fig, (ax1, ax2) = plt.subplots(1, 2)
182
+ ax1.plot(range(5))
183
+ ax2.plot(range(5))
184
+ plt.tight_layout()
185
+ bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
186
+ compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox},
187
+ tol=0)
188
+
189
+
190
+ @mpl.style.context('default')
191
+ @pytest.mark.backend('pgf')
192
+ @pytest.mark.parametrize('system', [
193
+ pytest.param('lualatex', marks=[needs_pgf_lualatex]),
194
+ pytest.param('pdflatex', marks=[needs_pgf_pdflatex]),
195
+ pytest.param('xelatex', marks=[needs_pgf_xelatex]),
196
+ ])
197
+ def test_pdf_pages(system):
198
+ rc_pdflatex = {
199
+ 'font.family': 'serif',
200
+ 'pgf.rcfonts': False,
201
+ 'pgf.texsystem': system,
202
+ }
203
+ mpl.rcParams.update(rc_pdflatex)
204
+
205
+ fig1, ax1 = plt.subplots()
206
+ ax1.plot(range(5))
207
+ fig1.tight_layout()
208
+
209
+ fig2, ax2 = plt.subplots(figsize=(3, 2))
210
+ ax2.plot(range(5))
211
+ fig2.tight_layout()
212
+
213
+ path = os.path.join(result_dir, f'pdfpages_{system}.pdf')
214
+ md = {
215
+ 'Author': 'me',
216
+ 'Title': 'Multipage PDF with pgf',
217
+ 'Subject': 'Test page',
218
+ 'Keywords': 'test,pdf,multipage',
219
+ 'ModDate': datetime.datetime(
220
+ 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))),
221
+ 'Trapped': 'Unknown'
222
+ }
223
+
224
+ with PdfPages(path, metadata=md) as pdf:
225
+ pdf.savefig(fig1)
226
+ pdf.savefig(fig2)
227
+ pdf.savefig(fig1)
228
+
229
+ assert pdf.get_pagecount() == 3
230
+
231
+
232
+ @mpl.style.context('default')
233
+ @pytest.mark.backend('pgf')
234
+ @pytest.mark.parametrize('system', [
235
+ pytest.param('lualatex', marks=[needs_pgf_lualatex]),
236
+ pytest.param('pdflatex', marks=[needs_pgf_pdflatex]),
237
+ pytest.param('xelatex', marks=[needs_pgf_xelatex]),
238
+ ])
239
+ def test_pdf_pages_metadata_check(monkeypatch, system):
240
+ # Basically the same as test_pdf_pages, but we keep it separate to leave
241
+ # pikepdf as an optional dependency.
242
+ pikepdf = pytest.importorskip('pikepdf')
243
+ monkeypatch.setenv('SOURCE_DATE_EPOCH', '0')
244
+
245
+ mpl.rcParams.update({'pgf.texsystem': system})
246
+
247
+ fig, ax = plt.subplots()
248
+ ax.plot(range(5))
249
+
250
+ md = {
251
+ 'Author': 'me',
252
+ 'Title': 'Multipage PDF with pgf',
253
+ 'Subject': 'Test page',
254
+ 'Keywords': 'test,pdf,multipage',
255
+ 'ModDate': datetime.datetime(
256
+ 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))),
257
+ 'Trapped': 'True'
258
+ }
259
+ path = os.path.join(result_dir, f'pdfpages_meta_check_{system}.pdf')
260
+ with PdfPages(path, metadata=md) as pdf:
261
+ pdf.savefig(fig)
262
+
263
+ with pikepdf.Pdf.open(path) as pdf:
264
+ info = {k: str(v) for k, v in pdf.docinfo.items()}
265
+
266
+ # Not set by us, so don't bother checking.
267
+ if '/PTEX.FullBanner' in info:
268
+ del info['/PTEX.FullBanner']
269
+ if '/PTEX.Fullbanner' in info:
270
+ del info['/PTEX.Fullbanner']
271
+
272
+ # Some LaTeX engines ignore this setting, and state themselves as producer.
273
+ producer = info.pop('/Producer')
274
+ assert producer == f'Matplotlib pgf backend v{mpl.__version__}' or (
275
+ system == 'lualatex' and 'LuaTeX' in producer)
276
+
277
+ assert info == {
278
+ '/Author': 'me',
279
+ '/CreationDate': 'D:19700101000000Z',
280
+ '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org',
281
+ '/Keywords': 'test,pdf,multipage',
282
+ '/ModDate': 'D:19680801000000Z',
283
+ '/Subject': 'Test page',
284
+ '/Title': 'Multipage PDF with pgf',
285
+ '/Trapped': '/True',
286
+ }
287
+
288
+
289
+ @needs_pgf_xelatex
290
+ def test_multipage_keep_empty(tmp_path):
291
+ # test empty pdf files
292
+
293
+ # an empty pdf is left behind with keep_empty unset
294
+ fn = tmp_path / "a.pdf"
295
+ with pytest.warns(mpl.MatplotlibDeprecationWarning), PdfPages(fn) as pdf:
296
+ pass
297
+ assert fn.exists()
298
+
299
+ # an empty pdf is left behind with keep_empty=True
300
+ fn = tmp_path / "b.pdf"
301
+ with pytest.warns(mpl.MatplotlibDeprecationWarning), \
302
+ PdfPages(fn, keep_empty=True) as pdf:
303
+ pass
304
+ assert fn.exists()
305
+
306
+ # an empty pdf deletes itself afterwards with keep_empty=False
307
+ fn = tmp_path / "c.pdf"
308
+ with PdfPages(fn, keep_empty=False) as pdf:
309
+ pass
310
+ assert not fn.exists()
311
+
312
+ # test pdf files with content, they should never be deleted
313
+
314
+ # a non-empty pdf is left behind with keep_empty unset
315
+ fn = tmp_path / "d.pdf"
316
+ with PdfPages(fn) as pdf:
317
+ pdf.savefig(plt.figure())
318
+ assert fn.exists()
319
+
320
+ # a non-empty pdf is left behind with keep_empty=True
321
+ fn = tmp_path / "e.pdf"
322
+ with pytest.warns(mpl.MatplotlibDeprecationWarning), \
323
+ PdfPages(fn, keep_empty=True) as pdf:
324
+ pdf.savefig(plt.figure())
325
+ assert fn.exists()
326
+
327
+ # a non-empty pdf is left behind with keep_empty=False
328
+ fn = tmp_path / "f.pdf"
329
+ with PdfPages(fn, keep_empty=False) as pdf:
330
+ pdf.savefig(plt.figure())
331
+ assert fn.exists()
332
+
333
+
334
+ @needs_pgf_xelatex
335
+ def test_tex_restart_after_error():
336
+ fig = plt.figure()
337
+ fig.suptitle(r"\oops")
338
+ with pytest.raises(ValueError):
339
+ fig.savefig(BytesIO(), format="pgf")
340
+
341
+ fig = plt.figure() # start from scratch
342
+ fig.suptitle(r"this is ok")
343
+ fig.savefig(BytesIO(), format="pgf")
344
+
345
+
346
+ @needs_pgf_xelatex
347
+ def test_bbox_inches_tight():
348
+ fig, ax = plt.subplots()
349
+ ax.imshow([[0, 1], [2, 3]])
350
+ fig.savefig(BytesIO(), format="pdf", backend="pgf", bbox_inches="tight")
351
+
352
+
353
+ @needs_pgf_xelatex
354
+ @needs_ghostscript
355
+ def test_png_transparency(): # Actually, also just testing that png works.
356
+ buf = BytesIO()
357
+ plt.figure().savefig(buf, format="png", backend="pgf", transparent=True)
358
+ buf.seek(0)
359
+ t = plt.imread(buf)
360
+ assert (t[..., 3] == 0).all() # fully transparent.
361
+
362
+
363
+ @needs_pgf_xelatex
364
+ def test_unknown_font(caplog):
365
+ with caplog.at_level("WARNING"):
366
+ mpl.rcParams["font.family"] = "this-font-does-not-exist"
367
+ plt.figtext(.5, .5, "hello, world")
368
+ plt.savefig(BytesIO(), format="pgf")
369
+ assert "Ignoring unknown font: this-font-does-not-exist" in [
370
+ r.getMessage() for r in caplog.records]
371
+
372
+
373
+ @check_figures_equal(extensions=["pdf"])
374
+ @pytest.mark.parametrize("texsystem", ("pdflatex", "xelatex", "lualatex"))
375
+ @pytest.mark.backend("pgf")
376
+ def test_minus_signs_with_tex(fig_test, fig_ref, texsystem):
377
+ if not _check_for_pgf(texsystem):
378
+ pytest.skip(texsystem + ' + pgf is required')
379
+ mpl.rcParams["pgf.texsystem"] = texsystem
380
+ fig_test.text(.5, .5, "$-1$")
381
+ fig_ref.text(.5, .5, "$\N{MINUS SIGN}1$")
382
+
383
+
384
+ @pytest.mark.backend("pgf")
385
+ def test_sketch_params():
386
+ fig, ax = plt.subplots(figsize=(3, 3))
387
+ ax.set_xticks([])
388
+ ax.set_yticks([])
389
+ ax.set_frame_on(False)
390
+ handle, = ax.plot([0, 1])
391
+ handle.set_sketch_params(scale=5, length=30, randomness=42)
392
+
393
+ with BytesIO() as fd:
394
+ fig.savefig(fd, format='pgf')
395
+ buf = fd.getvalue().decode()
396
+
397
+ baseline = r"""\pgfpathmoveto{\pgfqpoint{0.375000in}{0.300000in}}%
398
+ \pgfpathlineto{\pgfqpoint{2.700000in}{2.700000in}}%
399
+ \usepgfmodule{decorations}%
400
+ \usepgflibrary{decorations.pathmorphing}%
401
+ \pgfkeys{/pgf/decoration/.cd, """ \
402
+ r"""segment length = 0.150000in, amplitude = 0.100000in}%
403
+ \pgfmathsetseed{42}%
404
+ \pgfdecoratecurrentpath{random steps}%
405
+ \pgfusepath{stroke}%"""
406
+ # \pgfdecoratecurrentpath must be after the path definition and before the
407
+ # path is used (\pgfusepath)
408
+ assert baseline in buf
parrot/lib/python3.10/site-packages/matplotlib/tests/test_collections.py ADDED
@@ -0,0 +1,1338 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime
2
+ import io
3
+ import itertools
4
+ import platform
5
+ import re
6
+ from types import SimpleNamespace
7
+
8
+ import numpy as np
9
+ from numpy.testing import assert_array_equal, assert_array_almost_equal
10
+ import pytest
11
+
12
+ import matplotlib as mpl
13
+ import matplotlib.pyplot as plt
14
+ import matplotlib.collections as mcollections
15
+ import matplotlib.colors as mcolors
16
+ import matplotlib.path as mpath
17
+ import matplotlib.transforms as mtransforms
18
+ from matplotlib.collections import (Collection, LineCollection,
19
+ EventCollection, PolyCollection)
20
+ from matplotlib.testing.decorators import check_figures_equal, image_comparison
21
+
22
+
23
+ @pytest.fixture(params=["pcolormesh", "pcolor"])
24
+ def pcfunc(request):
25
+ return request.param
26
+
27
+
28
+ def generate_EventCollection_plot():
29
+ """Generate the initial collection and plot it."""
30
+ positions = np.array([0., 1., 2., 3., 5., 8., 13., 21.])
31
+ extra_positions = np.array([34., 55., 89.])
32
+ orientation = 'horizontal'
33
+ lineoffset = 1
34
+ linelength = .5
35
+ linewidth = 2
36
+ color = [1, 0, 0, 1]
37
+ linestyle = 'solid'
38
+ antialiased = True
39
+
40
+ coll = EventCollection(positions,
41
+ orientation=orientation,
42
+ lineoffset=lineoffset,
43
+ linelength=linelength,
44
+ linewidth=linewidth,
45
+ color=color,
46
+ linestyle=linestyle,
47
+ antialiased=antialiased
48
+ )
49
+
50
+ fig, ax = plt.subplots()
51
+ ax.add_collection(coll)
52
+ ax.set_title('EventCollection: default')
53
+ props = {'positions': positions,
54
+ 'extra_positions': extra_positions,
55
+ 'orientation': orientation,
56
+ 'lineoffset': lineoffset,
57
+ 'linelength': linelength,
58
+ 'linewidth': linewidth,
59
+ 'color': color,
60
+ 'linestyle': linestyle,
61
+ 'antialiased': antialiased
62
+ }
63
+ ax.set_xlim(-1, 22)
64
+ ax.set_ylim(0, 2)
65
+ return ax, coll, props
66
+
67
+
68
+ @image_comparison(['EventCollection_plot__default'])
69
+ def test__EventCollection__get_props():
70
+ _, coll, props = generate_EventCollection_plot()
71
+ # check that the default segments have the correct coordinates
72
+ check_segments(coll,
73
+ props['positions'],
74
+ props['linelength'],
75
+ props['lineoffset'],
76
+ props['orientation'])
77
+ # check that the default positions match the input positions
78
+ np.testing.assert_array_equal(props['positions'], coll.get_positions())
79
+ # check that the default orientation matches the input orientation
80
+ assert props['orientation'] == coll.get_orientation()
81
+ # check that the default orientation matches the input orientation
82
+ assert coll.is_horizontal()
83
+ # check that the default linelength matches the input linelength
84
+ assert props['linelength'] == coll.get_linelength()
85
+ # check that the default lineoffset matches the input lineoffset
86
+ assert props['lineoffset'] == coll.get_lineoffset()
87
+ # check that the default linestyle matches the input linestyle
88
+ assert coll.get_linestyle() == [(0, None)]
89
+ # check that the default color matches the input color
90
+ for color in [coll.get_color(), *coll.get_colors()]:
91
+ np.testing.assert_array_equal(color, props['color'])
92
+
93
+
94
+ @image_comparison(['EventCollection_plot__set_positions'])
95
+ def test__EventCollection__set_positions():
96
+ splt, coll, props = generate_EventCollection_plot()
97
+ new_positions = np.hstack([props['positions'], props['extra_positions']])
98
+ coll.set_positions(new_positions)
99
+ np.testing.assert_array_equal(new_positions, coll.get_positions())
100
+ check_segments(coll, new_positions,
101
+ props['linelength'],
102
+ props['lineoffset'],
103
+ props['orientation'])
104
+ splt.set_title('EventCollection: set_positions')
105
+ splt.set_xlim(-1, 90)
106
+
107
+
108
+ @image_comparison(['EventCollection_plot__add_positions'])
109
+ def test__EventCollection__add_positions():
110
+ splt, coll, props = generate_EventCollection_plot()
111
+ new_positions = np.hstack([props['positions'],
112
+ props['extra_positions'][0]])
113
+ coll.switch_orientation() # Test adding in the vertical orientation, too.
114
+ coll.add_positions(props['extra_positions'][0])
115
+ coll.switch_orientation()
116
+ np.testing.assert_array_equal(new_positions, coll.get_positions())
117
+ check_segments(coll,
118
+ new_positions,
119
+ props['linelength'],
120
+ props['lineoffset'],
121
+ props['orientation'])
122
+ splt.set_title('EventCollection: add_positions')
123
+ splt.set_xlim(-1, 35)
124
+
125
+
126
+ @image_comparison(['EventCollection_plot__append_positions'])
127
+ def test__EventCollection__append_positions():
128
+ splt, coll, props = generate_EventCollection_plot()
129
+ new_positions = np.hstack([props['positions'],
130
+ props['extra_positions'][2]])
131
+ coll.append_positions(props['extra_positions'][2])
132
+ np.testing.assert_array_equal(new_positions, coll.get_positions())
133
+ check_segments(coll,
134
+ new_positions,
135
+ props['linelength'],
136
+ props['lineoffset'],
137
+ props['orientation'])
138
+ splt.set_title('EventCollection: append_positions')
139
+ splt.set_xlim(-1, 90)
140
+
141
+
142
+ @image_comparison(['EventCollection_plot__extend_positions'])
143
+ def test__EventCollection__extend_positions():
144
+ splt, coll, props = generate_EventCollection_plot()
145
+ new_positions = np.hstack([props['positions'],
146
+ props['extra_positions'][1:]])
147
+ coll.extend_positions(props['extra_positions'][1:])
148
+ np.testing.assert_array_equal(new_positions, coll.get_positions())
149
+ check_segments(coll,
150
+ new_positions,
151
+ props['linelength'],
152
+ props['lineoffset'],
153
+ props['orientation'])
154
+ splt.set_title('EventCollection: extend_positions')
155
+ splt.set_xlim(-1, 90)
156
+
157
+
158
+ @image_comparison(['EventCollection_plot__switch_orientation'])
159
+ def test__EventCollection__switch_orientation():
160
+ splt, coll, props = generate_EventCollection_plot()
161
+ new_orientation = 'vertical'
162
+ coll.switch_orientation()
163
+ assert new_orientation == coll.get_orientation()
164
+ assert not coll.is_horizontal()
165
+ new_positions = coll.get_positions()
166
+ check_segments(coll,
167
+ new_positions,
168
+ props['linelength'],
169
+ props['lineoffset'], new_orientation)
170
+ splt.set_title('EventCollection: switch_orientation')
171
+ splt.set_ylim(-1, 22)
172
+ splt.set_xlim(0, 2)
173
+
174
+
175
+ @image_comparison(['EventCollection_plot__switch_orientation__2x'])
176
+ def test__EventCollection__switch_orientation_2x():
177
+ """
178
+ Check that calling switch_orientation twice sets the orientation back to
179
+ the default.
180
+ """
181
+ splt, coll, props = generate_EventCollection_plot()
182
+ coll.switch_orientation()
183
+ coll.switch_orientation()
184
+ new_positions = coll.get_positions()
185
+ assert props['orientation'] == coll.get_orientation()
186
+ assert coll.is_horizontal()
187
+ np.testing.assert_array_equal(props['positions'], new_positions)
188
+ check_segments(coll,
189
+ new_positions,
190
+ props['linelength'],
191
+ props['lineoffset'],
192
+ props['orientation'])
193
+ splt.set_title('EventCollection: switch_orientation 2x')
194
+
195
+
196
+ @image_comparison(['EventCollection_plot__set_orientation'])
197
+ def test__EventCollection__set_orientation():
198
+ splt, coll, props = generate_EventCollection_plot()
199
+ new_orientation = 'vertical'
200
+ coll.set_orientation(new_orientation)
201
+ assert new_orientation == coll.get_orientation()
202
+ assert not coll.is_horizontal()
203
+ check_segments(coll,
204
+ props['positions'],
205
+ props['linelength'],
206
+ props['lineoffset'],
207
+ new_orientation)
208
+ splt.set_title('EventCollection: set_orientation')
209
+ splt.set_ylim(-1, 22)
210
+ splt.set_xlim(0, 2)
211
+
212
+
213
+ @image_comparison(['EventCollection_plot__set_linelength'])
214
+ def test__EventCollection__set_linelength():
215
+ splt, coll, props = generate_EventCollection_plot()
216
+ new_linelength = 15
217
+ coll.set_linelength(new_linelength)
218
+ assert new_linelength == coll.get_linelength()
219
+ check_segments(coll,
220
+ props['positions'],
221
+ new_linelength,
222
+ props['lineoffset'],
223
+ props['orientation'])
224
+ splt.set_title('EventCollection: set_linelength')
225
+ splt.set_ylim(-20, 20)
226
+
227
+
228
+ @image_comparison(['EventCollection_plot__set_lineoffset'])
229
+ def test__EventCollection__set_lineoffset():
230
+ splt, coll, props = generate_EventCollection_plot()
231
+ new_lineoffset = -5.
232
+ coll.set_lineoffset(new_lineoffset)
233
+ assert new_lineoffset == coll.get_lineoffset()
234
+ check_segments(coll,
235
+ props['positions'],
236
+ props['linelength'],
237
+ new_lineoffset,
238
+ props['orientation'])
239
+ splt.set_title('EventCollection: set_lineoffset')
240
+ splt.set_ylim(-6, -4)
241
+
242
+
243
+ @image_comparison([
244
+ 'EventCollection_plot__set_linestyle',
245
+ 'EventCollection_plot__set_linestyle',
246
+ 'EventCollection_plot__set_linewidth',
247
+ ])
248
+ def test__EventCollection__set_prop():
249
+ for prop, value, expected in [
250
+ ('linestyle', 'dashed', [(0, (6.0, 6.0))]),
251
+ ('linestyle', (0, (6., 6.)), [(0, (6.0, 6.0))]),
252
+ ('linewidth', 5, 5),
253
+ ]:
254
+ splt, coll, _ = generate_EventCollection_plot()
255
+ coll.set(**{prop: value})
256
+ assert plt.getp(coll, prop) == expected
257
+ splt.set_title(f'EventCollection: set_{prop}')
258
+
259
+
260
+ @image_comparison(['EventCollection_plot__set_color'])
261
+ def test__EventCollection__set_color():
262
+ splt, coll, _ = generate_EventCollection_plot()
263
+ new_color = np.array([0, 1, 1, 1])
264
+ coll.set_color(new_color)
265
+ for color in [coll.get_color(), *coll.get_colors()]:
266
+ np.testing.assert_array_equal(color, new_color)
267
+ splt.set_title('EventCollection: set_color')
268
+
269
+
270
+ def check_segments(coll, positions, linelength, lineoffset, orientation):
271
+ """
272
+ Test helper checking that all values in the segment are correct, given a
273
+ particular set of inputs.
274
+ """
275
+ segments = coll.get_segments()
276
+ if (orientation.lower() == 'horizontal'
277
+ or orientation.lower() == 'none' or orientation is None):
278
+ # if horizontal, the position in is in the y-axis
279
+ pos1 = 1
280
+ pos2 = 0
281
+ elif orientation.lower() == 'vertical':
282
+ # if vertical, the position in is in the x-axis
283
+ pos1 = 0
284
+ pos2 = 1
285
+ else:
286
+ raise ValueError("orientation must be 'horizontal' or 'vertical'")
287
+
288
+ # test to make sure each segment is correct
289
+ for i, segment in enumerate(segments):
290
+ assert segment[0, pos1] == lineoffset + linelength / 2
291
+ assert segment[1, pos1] == lineoffset - linelength / 2
292
+ assert segment[0, pos2] == positions[i]
293
+ assert segment[1, pos2] == positions[i]
294
+
295
+
296
+ def test_collection_norm_autoscale():
297
+ # norm should be autoscaled when array is set, not deferred to draw time
298
+ lines = np.arange(24).reshape((4, 3, 2))
299
+ coll = mcollections.LineCollection(lines, array=np.arange(4))
300
+ assert coll.norm(2) == 2 / 3
301
+ # setting a new array shouldn't update the already scaled limits
302
+ coll.set_array(np.arange(4) + 5)
303
+ assert coll.norm(2) == 2 / 3
304
+
305
+
306
+ def test_null_collection_datalim():
307
+ col = mcollections.PathCollection([])
308
+ col_data_lim = col.get_datalim(mtransforms.IdentityTransform())
309
+ assert_array_equal(col_data_lim.get_points(),
310
+ mtransforms.Bbox.null().get_points())
311
+
312
+
313
+ def test_no_offsets_datalim():
314
+ # A collection with no offsets and a non transData
315
+ # transform should return a null bbox
316
+ ax = plt.axes()
317
+ coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])])
318
+ ax.add_collection(coll)
319
+ coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform())
320
+ assert_array_equal(coll_data_lim.get_points(),
321
+ mtransforms.Bbox.null().get_points())
322
+
323
+
324
+ def test_add_collection():
325
+ # Test if data limits are unchanged by adding an empty collection.
326
+ # GitHub issue #1490, pull #1497.
327
+ plt.figure()
328
+ ax = plt.axes()
329
+ ax.scatter([0, 1], [0, 1])
330
+ bounds = ax.dataLim.bounds
331
+ ax.scatter([], [])
332
+ assert ax.dataLim.bounds == bounds
333
+
334
+
335
+ @mpl.style.context('mpl20')
336
+ @check_figures_equal(extensions=['png'])
337
+ def test_collection_log_datalim(fig_test, fig_ref):
338
+ # Data limits should respect the minimum x/y when using log scale.
339
+ x_vals = [4.38462e-6, 5.54929e-6, 7.02332e-6, 8.88889e-6, 1.12500e-5,
340
+ 1.42383e-5, 1.80203e-5, 2.28070e-5, 2.88651e-5, 3.65324e-5,
341
+ 4.62363e-5, 5.85178e-5, 7.40616e-5, 9.37342e-5, 1.18632e-4]
342
+ y_vals = [0.0, 0.1, 0.182, 0.332, 0.604, 1.1, 2.0, 3.64, 6.64, 12.1, 22.0,
343
+ 39.6, 71.3]
344
+
345
+ x, y = np.meshgrid(x_vals, y_vals)
346
+ x = x.flatten()
347
+ y = y.flatten()
348
+
349
+ ax_test = fig_test.subplots()
350
+ ax_test.set_xscale('log')
351
+ ax_test.set_yscale('log')
352
+ ax_test.margins = 0
353
+ ax_test.scatter(x, y)
354
+
355
+ ax_ref = fig_ref.subplots()
356
+ ax_ref.set_xscale('log')
357
+ ax_ref.set_yscale('log')
358
+ ax_ref.plot(x, y, marker="o", ls="")
359
+
360
+
361
+ def test_quiver_limits():
362
+ ax = plt.axes()
363
+ x, y = np.arange(8), np.arange(10)
364
+ u = v = np.linspace(0, 10, 80).reshape(10, 8)
365
+ q = plt.quiver(x, y, u, v)
366
+ assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.)
367
+
368
+ plt.figure()
369
+ ax = plt.axes()
370
+ x = np.linspace(-5, 10, 20)
371
+ y = np.linspace(-2, 4, 10)
372
+ y, x = np.meshgrid(y, x)
373
+ trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
374
+ plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans)
375
+ assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0)
376
+
377
+
378
+ def test_barb_limits():
379
+ ax = plt.axes()
380
+ x = np.linspace(-5, 10, 20)
381
+ y = np.linspace(-2, 4, 10)
382
+ y, x = np.meshgrid(y, x)
383
+ trans = mtransforms.Affine2D().translate(25, 32) + ax.transData
384
+ plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans)
385
+ # The calculated bounds are approximately the bounds of the original data,
386
+ # this is because the entire path is taken into account when updating the
387
+ # datalim.
388
+ assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6),
389
+ decimal=1)
390
+
391
+
392
+ @image_comparison(['EllipseCollection_test_image.png'], remove_text=True,
393
+ tol=0.021 if platform.machine() == 'arm64' else 0)
394
+ def test_EllipseCollection():
395
+ # Test basic functionality
396
+ fig, ax = plt.subplots()
397
+ x = np.arange(4)
398
+ y = np.arange(3)
399
+ X, Y = np.meshgrid(x, y)
400
+ XY = np.vstack((X.ravel(), Y.ravel())).T
401
+
402
+ ww = X / x[-1]
403
+ hh = Y / y[-1]
404
+ aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis
405
+
406
+ ec = mcollections.EllipseCollection(
407
+ ww, hh, aa, units='x', offsets=XY, offset_transform=ax.transData,
408
+ facecolors='none')
409
+ ax.add_collection(ec)
410
+ ax.autoscale_view()
411
+
412
+
413
+ def test_EllipseCollection_setter_getter():
414
+ # Test widths, heights and angle setter
415
+ rng = np.random.default_rng(0)
416
+
417
+ widths = (2, )
418
+ heights = (3, )
419
+ angles = (45, )
420
+ offsets = rng.random((10, 2)) * 10
421
+
422
+ fig, ax = plt.subplots()
423
+
424
+ ec = mcollections.EllipseCollection(
425
+ widths=widths,
426
+ heights=heights,
427
+ angles=angles,
428
+ offsets=offsets,
429
+ units='x',
430
+ offset_transform=ax.transData,
431
+ )
432
+
433
+ assert_array_almost_equal(ec._widths, np.array(widths).ravel() * 0.5)
434
+ assert_array_almost_equal(ec._heights, np.array(heights).ravel() * 0.5)
435
+ assert_array_almost_equal(ec._angles, np.deg2rad(angles).ravel())
436
+
437
+ assert_array_almost_equal(ec.get_widths(), widths)
438
+ assert_array_almost_equal(ec.get_heights(), heights)
439
+ assert_array_almost_equal(ec.get_angles(), angles)
440
+
441
+ ax.add_collection(ec)
442
+ ax.set_xlim(-2, 12)
443
+ ax.set_ylim(-2, 12)
444
+
445
+ new_widths = rng.random((10, 2)) * 2
446
+ new_heights = rng.random((10, 2)) * 3
447
+ new_angles = rng.random((10, 2)) * 180
448
+
449
+ ec.set(widths=new_widths, heights=new_heights, angles=new_angles)
450
+
451
+ assert_array_almost_equal(ec.get_widths(), new_widths.ravel())
452
+ assert_array_almost_equal(ec.get_heights(), new_heights.ravel())
453
+ assert_array_almost_equal(ec.get_angles(), new_angles.ravel())
454
+
455
+
456
+ @image_comparison(['polycollection_close.png'], remove_text=True, style='mpl20')
457
+ def test_polycollection_close():
458
+ from mpl_toolkits.mplot3d import Axes3D # type: ignore
459
+ plt.rcParams['axes3d.automargin'] = True
460
+
461
+ vertsQuad = [
462
+ [[0., 0.], [0., 1.], [1., 1.], [1., 0.]],
463
+ [[0., 1.], [2., 3.], [2., 2.], [1., 1.]],
464
+ [[2., 2.], [2., 3.], [4., 1.], [3., 1.]],
465
+ [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]]
466
+
467
+ fig = plt.figure()
468
+ ax = fig.add_axes(Axes3D(fig))
469
+
470
+ colors = ['r', 'g', 'b', 'y', 'k']
471
+ zpos = list(range(5))
472
+
473
+ poly = mcollections.PolyCollection(
474
+ vertsQuad * len(zpos), linewidth=0.25)
475
+ poly.set_alpha(0.7)
476
+
477
+ # need to have a z-value for *each* polygon = element!
478
+ zs = []
479
+ cs = []
480
+ for z, c in zip(zpos, colors):
481
+ zs.extend([z] * len(vertsQuad))
482
+ cs.extend([c] * len(vertsQuad))
483
+
484
+ poly.set_color(cs)
485
+
486
+ ax.add_collection3d(poly, zs=zs, zdir='y')
487
+
488
+ # axis limit settings:
489
+ ax.set_xlim3d(0, 4)
490
+ ax.set_zlim3d(0, 3)
491
+ ax.set_ylim3d(0, 4)
492
+
493
+
494
+ @image_comparison(['regularpolycollection_rotate.png'], remove_text=True)
495
+ def test_regularpolycollection_rotate():
496
+ xx, yy = np.mgrid[:10, :10]
497
+ xy_points = np.transpose([xx.flatten(), yy.flatten()])
498
+ rotations = np.linspace(0, 2*np.pi, len(xy_points))
499
+
500
+ fig, ax = plt.subplots()
501
+ for xy, alpha in zip(xy_points, rotations):
502
+ col = mcollections.RegularPolyCollection(
503
+ 4, sizes=(100,), rotation=alpha,
504
+ offsets=[xy], offset_transform=ax.transData)
505
+ ax.add_collection(col, autolim=True)
506
+ ax.autoscale_view()
507
+
508
+
509
+ @image_comparison(['regularpolycollection_scale.png'], remove_text=True)
510
+ def test_regularpolycollection_scale():
511
+ # See issue #3860
512
+
513
+ class SquareCollection(mcollections.RegularPolyCollection):
514
+ def __init__(self, **kwargs):
515
+ super().__init__(4, rotation=np.pi/4., **kwargs)
516
+
517
+ def get_transform(self):
518
+ """Return transform scaling circle areas to data space."""
519
+ ax = self.axes
520
+
521
+ pts2pixels = 72.0 / ax.figure.dpi
522
+
523
+ scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width
524
+ scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height
525
+ return mtransforms.Affine2D().scale(scale_x, scale_y)
526
+
527
+ fig, ax = plt.subplots()
528
+
529
+ xy = [(0, 0)]
530
+ # Unit square has a half-diagonal of `1/sqrt(2)`, so `pi * r**2` equals...
531
+ circle_areas = [np.pi / 2]
532
+ squares = SquareCollection(
533
+ sizes=circle_areas, offsets=xy, offset_transform=ax.transData)
534
+ ax.add_collection(squares, autolim=True)
535
+ ax.axis([-1, 1, -1, 1])
536
+
537
+
538
+ def test_picking():
539
+ fig, ax = plt.subplots()
540
+ col = ax.scatter([0], [0], [1000], picker=True)
541
+ fig.savefig(io.BytesIO(), dpi=fig.dpi)
542
+ mouse_event = SimpleNamespace(x=325, y=240)
543
+ found, indices = col.contains(mouse_event)
544
+ assert found
545
+ assert_array_equal(indices['ind'], [0])
546
+
547
+
548
+ def test_quadmesh_contains():
549
+ x = np.arange(4)
550
+ X = x[:, None] * x[None, :]
551
+
552
+ fig, ax = plt.subplots()
553
+ mesh = ax.pcolormesh(X)
554
+ fig.draw_without_rendering()
555
+ xdata, ydata = 0.5, 0.5
556
+ x, y = mesh.get_transform().transform((xdata, ydata))
557
+ mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
558
+ found, indices = mesh.contains(mouse_event)
559
+ assert found
560
+ assert_array_equal(indices['ind'], [0])
561
+
562
+ xdata, ydata = 1.5, 1.5
563
+ x, y = mesh.get_transform().transform((xdata, ydata))
564
+ mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
565
+ found, indices = mesh.contains(mouse_event)
566
+ assert found
567
+ assert_array_equal(indices['ind'], [5])
568
+
569
+
570
+ def test_quadmesh_contains_concave():
571
+ # Test a concave polygon, V-like shape
572
+ x = [[0, -1], [1, 0]]
573
+ y = [[0, 1], [1, -1]]
574
+ fig, ax = plt.subplots()
575
+ mesh = ax.pcolormesh(x, y, [[0]])
576
+ fig.draw_without_rendering()
577
+ # xdata, ydata, expected
578
+ points = [(-0.5, 0.25, True), # left wing
579
+ (0, 0.25, False), # between the two wings
580
+ (0.5, 0.25, True), # right wing
581
+ (0, -0.25, True), # main body
582
+ ]
583
+ for point in points:
584
+ xdata, ydata, expected = point
585
+ x, y = mesh.get_transform().transform((xdata, ydata))
586
+ mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
587
+ found, indices = mesh.contains(mouse_event)
588
+ assert found is expected
589
+
590
+
591
+ def test_quadmesh_cursor_data():
592
+ x = np.arange(4)
593
+ X = x[:, None] * x[None, :]
594
+
595
+ fig, ax = plt.subplots()
596
+ mesh = ax.pcolormesh(X)
597
+ # Empty array data
598
+ mesh._A = None
599
+ fig.draw_without_rendering()
600
+ xdata, ydata = 0.5, 0.5
601
+ x, y = mesh.get_transform().transform((xdata, ydata))
602
+ mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
603
+ # Empty collection should return None
604
+ assert mesh.get_cursor_data(mouse_event) is None
605
+
606
+ # Now test adding the array data, to make sure we do get a value
607
+ mesh.set_array(np.ones(X.shape))
608
+ assert_array_equal(mesh.get_cursor_data(mouse_event), [1])
609
+
610
+
611
+ def test_quadmesh_cursor_data_multiple_points():
612
+ x = [1, 2, 1, 2]
613
+ fig, ax = plt.subplots()
614
+ mesh = ax.pcolormesh(x, x, np.ones((3, 3)))
615
+ fig.draw_without_rendering()
616
+ xdata, ydata = 1.5, 1.5
617
+ x, y = mesh.get_transform().transform((xdata, ydata))
618
+ mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y)
619
+ # All quads are covering the same square
620
+ assert_array_equal(mesh.get_cursor_data(mouse_event), np.ones(9))
621
+
622
+
623
+ def test_linestyle_single_dashes():
624
+ plt.scatter([0, 1, 2], [0, 1, 2], linestyle=(0., [2., 2.]))
625
+ plt.draw()
626
+
627
+
628
+ @image_comparison(['size_in_xy.png'], remove_text=True)
629
+ def test_size_in_xy():
630
+ fig, ax = plt.subplots()
631
+
632
+ widths, heights, angles = (10, 10), 10, 0
633
+ widths = 10, 10
634
+ coords = [(10, 10), (15, 15)]
635
+ e = mcollections.EllipseCollection(
636
+ widths, heights, angles, units='xy',
637
+ offsets=coords, offset_transform=ax.transData)
638
+
639
+ ax.add_collection(e)
640
+
641
+ ax.set_xlim(0, 30)
642
+ ax.set_ylim(0, 30)
643
+
644
+
645
+ def test_pandas_indexing(pd):
646
+
647
+ # Should not fail break when faced with a
648
+ # non-zero indexed series
649
+ index = [11, 12, 13]
650
+ ec = fc = pd.Series(['red', 'blue', 'green'], index=index)
651
+ lw = pd.Series([1, 2, 3], index=index)
652
+ ls = pd.Series(['solid', 'dashed', 'dashdot'], index=index)
653
+ aa = pd.Series([True, False, True], index=index)
654
+
655
+ Collection(edgecolors=ec)
656
+ Collection(facecolors=fc)
657
+ Collection(linewidths=lw)
658
+ Collection(linestyles=ls)
659
+ Collection(antialiaseds=aa)
660
+
661
+
662
+ @mpl.style.context('default')
663
+ def test_lslw_bcast():
664
+ col = mcollections.PathCollection([])
665
+ col.set_linestyles(['-', '-'])
666
+ col.set_linewidths([1, 2, 3])
667
+
668
+ assert col.get_linestyles() == [(0, None)] * 6
669
+ assert col.get_linewidths() == [1, 2, 3] * 2
670
+
671
+ col.set_linestyles(['-', '-', '-'])
672
+ assert col.get_linestyles() == [(0, None)] * 3
673
+ assert (col.get_linewidths() == [1, 2, 3]).all()
674
+
675
+
676
+ def test_set_wrong_linestyle():
677
+ c = Collection()
678
+ with pytest.raises(ValueError, match="Do not know how to convert 'fuzzy'"):
679
+ c.set_linestyle('fuzzy')
680
+
681
+
682
+ @mpl.style.context('default')
683
+ def test_capstyle():
684
+ col = mcollections.PathCollection([])
685
+ assert col.get_capstyle() is None
686
+ col = mcollections.PathCollection([], capstyle='round')
687
+ assert col.get_capstyle() == 'round'
688
+ col.set_capstyle('butt')
689
+ assert col.get_capstyle() == 'butt'
690
+
691
+
692
+ @mpl.style.context('default')
693
+ def test_joinstyle():
694
+ col = mcollections.PathCollection([])
695
+ assert col.get_joinstyle() is None
696
+ col = mcollections.PathCollection([], joinstyle='round')
697
+ assert col.get_joinstyle() == 'round'
698
+ col.set_joinstyle('miter')
699
+ assert col.get_joinstyle() == 'miter'
700
+
701
+
702
+ @image_comparison(['cap_and_joinstyle.png'])
703
+ def test_cap_and_joinstyle_image():
704
+ fig, ax = plt.subplots()
705
+ ax.set_xlim([-0.5, 1.5])
706
+ ax.set_ylim([-0.5, 2.5])
707
+
708
+ x = np.array([0.0, 1.0, 0.5])
709
+ ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]])
710
+
711
+ segs = np.zeros((3, 3, 2))
712
+ segs[:, :, 0] = x
713
+ segs[:, :, 1] = ys
714
+ line_segments = LineCollection(segs, linewidth=[10, 15, 20])
715
+ line_segments.set_capstyle("round")
716
+ line_segments.set_joinstyle("miter")
717
+
718
+ ax.add_collection(line_segments)
719
+ ax.set_title('Line collection with customized caps and joinstyle')
720
+
721
+
722
+ @image_comparison(['scatter_post_alpha.png'],
723
+ remove_text=True, style='default')
724
+ def test_scatter_post_alpha():
725
+ fig, ax = plt.subplots()
726
+ sc = ax.scatter(range(5), range(5), c=range(5))
727
+ sc.set_alpha(.1)
728
+
729
+
730
+ def test_scatter_alpha_array():
731
+ x = np.arange(5)
732
+ alpha = x / 5
733
+ # With colormapping.
734
+ fig, (ax0, ax1) = plt.subplots(2)
735
+ sc0 = ax0.scatter(x, x, c=x, alpha=alpha)
736
+ sc1 = ax1.scatter(x, x, c=x)
737
+ sc1.set_alpha(alpha)
738
+ plt.draw()
739
+ assert_array_equal(sc0.get_facecolors()[:, -1], alpha)
740
+ assert_array_equal(sc1.get_facecolors()[:, -1], alpha)
741
+ # Without colormapping.
742
+ fig, (ax0, ax1) = plt.subplots(2)
743
+ sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'], alpha=alpha)
744
+ sc1 = ax1.scatter(x, x, color='r', alpha=alpha)
745
+ plt.draw()
746
+ assert_array_equal(sc0.get_facecolors()[:, -1], alpha)
747
+ assert_array_equal(sc1.get_facecolors()[:, -1], alpha)
748
+ # Without colormapping, and set alpha afterward.
749
+ fig, (ax0, ax1) = plt.subplots(2)
750
+ sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'])
751
+ sc0.set_alpha(alpha)
752
+ sc1 = ax1.scatter(x, x, color='r')
753
+ sc1.set_alpha(alpha)
754
+ plt.draw()
755
+ assert_array_equal(sc0.get_facecolors()[:, -1], alpha)
756
+ assert_array_equal(sc1.get_facecolors()[:, -1], alpha)
757
+
758
+
759
+ def test_pathcollection_legend_elements():
760
+ np.random.seed(19680801)
761
+ x, y = np.random.rand(2, 10)
762
+ y = np.random.rand(10)
763
+ c = np.random.randint(0, 5, size=10)
764
+ s = np.random.randint(10, 300, size=10)
765
+
766
+ fig, ax = plt.subplots()
767
+ sc = ax.scatter(x, y, c=c, s=s, cmap="jet", marker="o", linewidths=0)
768
+
769
+ h, l = sc.legend_elements(fmt="{x:g}")
770
+ assert len(h) == 5
771
+ assert l == ["0", "1", "2", "3", "4"]
772
+ colors = np.array([line.get_color() for line in h])
773
+ colors2 = sc.cmap(np.arange(5)/4)
774
+ assert_array_equal(colors, colors2)
775
+ l1 = ax.legend(h, l, loc=1)
776
+
777
+ h2, lab2 = sc.legend_elements(num=9)
778
+ assert len(h2) == 9
779
+ l2 = ax.legend(h2, lab2, loc=2)
780
+
781
+ h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red")
782
+ assert all(line.get_alpha() == 0.5 for line in h)
783
+ assert all(line.get_markerfacecolor() == "red" for line in h)
784
+ l3 = ax.legend(h, l, loc=4)
785
+
786
+ h, l = sc.legend_elements(prop="sizes", num=4, fmt="{x:.2f}",
787
+ func=lambda x: 2*x)
788
+ actsizes = [line.get_markersize() for line in h]
789
+ labeledsizes = np.sqrt(np.array(l, float) / 2)
790
+ assert_array_almost_equal(actsizes, labeledsizes)
791
+ l4 = ax.legend(h, l, loc=3)
792
+
793
+ loc = mpl.ticker.MaxNLocator(nbins=9, min_n_ticks=9-1,
794
+ steps=[1, 2, 2.5, 3, 5, 6, 8, 10])
795
+ h5, lab5 = sc.legend_elements(num=loc)
796
+ assert len(h2) == len(h5)
797
+
798
+ levels = [-1, 0, 55.4, 260]
799
+ h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}")
800
+ assert [float(l) for l in lab6] == levels[2:]
801
+
802
+ for l in [l1, l2, l3, l4]:
803
+ ax.add_artist(l)
804
+
805
+ fig.canvas.draw()
806
+
807
+
808
+ def test_EventCollection_nosort():
809
+ # Check that EventCollection doesn't modify input in place
810
+ arr = np.array([3, 2, 1, 10])
811
+ coll = EventCollection(arr)
812
+ np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10]))
813
+
814
+
815
+ def test_collection_set_verts_array():
816
+ verts = np.arange(80, dtype=np.double).reshape(10, 4, 2)
817
+ col_arr = PolyCollection(verts)
818
+ col_list = PolyCollection(list(verts))
819
+ assert len(col_arr._paths) == len(col_list._paths)
820
+ for ap, lp in zip(col_arr._paths, col_list._paths):
821
+ assert np.array_equal(ap._vertices, lp._vertices)
822
+ assert np.array_equal(ap._codes, lp._codes)
823
+
824
+ verts_tuple = np.empty(10, dtype=object)
825
+ verts_tuple[:] = [tuple(tuple(y) for y in x) for x in verts]
826
+ col_arr_tuple = PolyCollection(verts_tuple)
827
+ assert len(col_arr._paths) == len(col_arr_tuple._paths)
828
+ for ap, atp in zip(col_arr._paths, col_arr_tuple._paths):
829
+ assert np.array_equal(ap._vertices, atp._vertices)
830
+ assert np.array_equal(ap._codes, atp._codes)
831
+
832
+
833
+ def test_collection_set_array():
834
+ vals = [*range(10)]
835
+
836
+ # Test set_array with list
837
+ c = Collection()
838
+ c.set_array(vals)
839
+
840
+ # Test set_array with wrong dtype
841
+ with pytest.raises(TypeError, match="^Image data of dtype"):
842
+ c.set_array("wrong_input")
843
+
844
+ # Test if array kwarg is copied
845
+ vals[5] = 45
846
+ assert np.not_equal(vals, c.get_array()).any()
847
+
848
+
849
+ def test_blended_collection_autolim():
850
+ a = [1, 2, 4]
851
+ height = .2
852
+
853
+ xy_pairs = np.column_stack([np.repeat(a, 2), np.tile([0, height], len(a))])
854
+ line_segs = xy_pairs.reshape([len(a), 2, 2])
855
+
856
+ f, ax = plt.subplots()
857
+ trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes)
858
+ ax.add_collection(LineCollection(line_segs, transform=trans))
859
+ ax.autoscale_view(scalex=True, scaley=False)
860
+ np.testing.assert_allclose(ax.get_xlim(), [1., 4.])
861
+
862
+
863
+ def test_singleton_autolim():
864
+ fig, ax = plt.subplots()
865
+ ax.scatter(0, 0)
866
+ np.testing.assert_allclose(ax.get_ylim(), [-0.06, 0.06])
867
+ np.testing.assert_allclose(ax.get_xlim(), [-0.06, 0.06])
868
+
869
+
870
+ @pytest.mark.parametrize("transform, expected", [
871
+ ("transData", (-0.5, 3.5)),
872
+ ("transAxes", (2.8, 3.2)),
873
+ ])
874
+ def test_autolim_with_zeros(transform, expected):
875
+ # 1) Test that a scatter at (0, 0) data coordinates contributes to
876
+ # autoscaling even though any(offsets) would be False in that situation.
877
+ # 2) Test that specifying transAxes for the transform does not contribute
878
+ # to the autoscaling.
879
+ fig, ax = plt.subplots()
880
+ ax.scatter(0, 0, transform=getattr(ax, transform))
881
+ ax.scatter(3, 3)
882
+ np.testing.assert_allclose(ax.get_ylim(), expected)
883
+ np.testing.assert_allclose(ax.get_xlim(), expected)
884
+
885
+
886
+ def test_quadmesh_set_array_validation(pcfunc):
887
+ x = np.arange(11)
888
+ y = np.arange(8)
889
+ z = np.random.random((7, 10))
890
+ fig, ax = plt.subplots()
891
+ coll = getattr(ax, pcfunc)(x, y, z)
892
+
893
+ with pytest.raises(ValueError, match=re.escape(
894
+ "For X (11) and Y (8) with flat shading, A should have shape "
895
+ "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (10, 7)")):
896
+ coll.set_array(z.reshape(10, 7))
897
+
898
+ z = np.arange(54).reshape((6, 9))
899
+ with pytest.raises(ValueError, match=re.escape(
900
+ "For X (11) and Y (8) with flat shading, A should have shape "
901
+ "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (6, 9)")):
902
+ coll.set_array(z)
903
+ with pytest.raises(ValueError, match=re.escape(
904
+ "For X (11) and Y (8) with flat shading, A should have shape "
905
+ "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (54,)")):
906
+ coll.set_array(z.ravel())
907
+
908
+ # RGB(A) tests
909
+ z = np.ones((9, 6, 3)) # RGB with wrong X/Y dims
910
+ with pytest.raises(ValueError, match=re.escape(
911
+ "For X (11) and Y (8) with flat shading, A should have shape "
912
+ "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 3)")):
913
+ coll.set_array(z)
914
+
915
+ z = np.ones((9, 6, 4)) # RGBA with wrong X/Y dims
916
+ with pytest.raises(ValueError, match=re.escape(
917
+ "For X (11) and Y (8) with flat shading, A should have shape "
918
+ "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 4)")):
919
+ coll.set_array(z)
920
+
921
+ z = np.ones((7, 10, 2)) # Right X/Y dims, bad 3rd dim
922
+ with pytest.raises(ValueError, match=re.escape(
923
+ "For X (11) and Y (8) with flat shading, A should have shape "
924
+ "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (7, 10, 2)")):
925
+ coll.set_array(z)
926
+
927
+ x = np.arange(10)
928
+ y = np.arange(7)
929
+ z = np.random.random((7, 10))
930
+ fig, ax = plt.subplots()
931
+ coll = ax.pcolormesh(x, y, z, shading='gouraud')
932
+
933
+
934
+ def test_polyquadmesh_masked_vertices_array():
935
+ xx, yy = np.meshgrid([0, 1, 2], [0, 1, 2, 3])
936
+ # 2 x 3 mesh data
937
+ zz = (xx*yy)[:-1, :-1]
938
+ quadmesh = plt.pcolormesh(xx, yy, zz)
939
+ quadmesh.update_scalarmappable()
940
+ quadmesh_fc = quadmesh.get_facecolor()[1:, :]
941
+ # Mask the origin vertex in x
942
+ xx = np.ma.masked_where((xx == 0) & (yy == 0), xx)
943
+ polymesh = plt.pcolor(xx, yy, zz)
944
+ polymesh.update_scalarmappable()
945
+ # One cell should be left out
946
+ assert len(polymesh.get_paths()) == 5
947
+ # Poly version should have the same facecolors as the end of the quadmesh
948
+ assert_array_equal(quadmesh_fc, polymesh.get_facecolor())
949
+
950
+ # Mask the origin vertex in y
951
+ yy = np.ma.masked_where((xx == 0) & (yy == 0), yy)
952
+ polymesh = plt.pcolor(xx, yy, zz)
953
+ polymesh.update_scalarmappable()
954
+ # One cell should be left out
955
+ assert len(polymesh.get_paths()) == 5
956
+ # Poly version should have the same facecolors as the end of the quadmesh
957
+ assert_array_equal(quadmesh_fc, polymesh.get_facecolor())
958
+
959
+ # Mask the origin cell data
960
+ zz = np.ma.masked_where((xx[:-1, :-1] == 0) & (yy[:-1, :-1] == 0), zz)
961
+ polymesh = plt.pcolor(zz)
962
+ polymesh.update_scalarmappable()
963
+ # One cell should be left out
964
+ assert len(polymesh.get_paths()) == 5
965
+ # Poly version should have the same facecolors as the end of the quadmesh
966
+ assert_array_equal(quadmesh_fc, polymesh.get_facecolor())
967
+
968
+ # Setting array with 1D compressed values is deprecated
969
+ with pytest.warns(mpl.MatplotlibDeprecationWarning,
970
+ match="Setting a PolyQuadMesh"):
971
+ polymesh.set_array(np.ones(5))
972
+
973
+ # We should also be able to call set_array with a new mask and get
974
+ # updated polys
975
+ # Remove mask, should add all polys back
976
+ zz = np.arange(6).reshape((3, 2))
977
+ polymesh.set_array(zz)
978
+ polymesh.update_scalarmappable()
979
+ assert len(polymesh.get_paths()) == 6
980
+ # Add mask should remove polys
981
+ zz = np.ma.masked_less(zz, 2)
982
+ polymesh.set_array(zz)
983
+ polymesh.update_scalarmappable()
984
+ assert len(polymesh.get_paths()) == 4
985
+
986
+
987
+ def test_quadmesh_get_coordinates(pcfunc):
988
+ x = [0, 1, 2]
989
+ y = [2, 4, 6]
990
+ z = np.ones(shape=(2, 2))
991
+ xx, yy = np.meshgrid(x, y)
992
+ coll = getattr(plt, pcfunc)(xx, yy, z)
993
+
994
+ # shape (3, 3, 2)
995
+ coords = np.stack([xx.T, yy.T]).T
996
+ assert_array_equal(coll.get_coordinates(), coords)
997
+
998
+
999
+ def test_quadmesh_set_array():
1000
+ x = np.arange(4)
1001
+ y = np.arange(4)
1002
+ z = np.arange(9).reshape((3, 3))
1003
+ fig, ax = plt.subplots()
1004
+ coll = ax.pcolormesh(x, y, np.ones(z.shape))
1005
+ # Test that the collection is able to update with a 2d array
1006
+ coll.set_array(z)
1007
+ fig.canvas.draw()
1008
+ assert np.array_equal(coll.get_array(), z)
1009
+
1010
+ # Check that pre-flattened arrays work too
1011
+ coll.set_array(np.ones(9))
1012
+ fig.canvas.draw()
1013
+ assert np.array_equal(coll.get_array(), np.ones(9))
1014
+
1015
+ z = np.arange(16).reshape((4, 4))
1016
+ fig, ax = plt.subplots()
1017
+ coll = ax.pcolormesh(x, y, np.ones(z.shape), shading='gouraud')
1018
+ # Test that the collection is able to update with a 2d array
1019
+ coll.set_array(z)
1020
+ fig.canvas.draw()
1021
+ assert np.array_equal(coll.get_array(), z)
1022
+
1023
+ # Check that pre-flattened arrays work too
1024
+ coll.set_array(np.ones(16))
1025
+ fig.canvas.draw()
1026
+ assert np.array_equal(coll.get_array(), np.ones(16))
1027
+
1028
+
1029
+ def test_quadmesh_vmin_vmax(pcfunc):
1030
+ # test when vmin/vmax on the norm changes, the quadmesh gets updated
1031
+ fig, ax = plt.subplots()
1032
+ cmap = mpl.colormaps['plasma']
1033
+ norm = mpl.colors.Normalize(vmin=0, vmax=1)
1034
+ coll = getattr(ax, pcfunc)([[1]], cmap=cmap, norm=norm)
1035
+ fig.canvas.draw()
1036
+ assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1)))
1037
+
1038
+ # Change the vmin/vmax of the norm so that the color is from
1039
+ # the bottom of the colormap now
1040
+ norm.vmin, norm.vmax = 1, 2
1041
+ fig.canvas.draw()
1042
+ assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1)))
1043
+
1044
+
1045
+ def test_quadmesh_alpha_array(pcfunc):
1046
+ x = np.arange(4)
1047
+ y = np.arange(4)
1048
+ z = np.arange(9).reshape((3, 3))
1049
+ alpha = z / z.max()
1050
+ alpha_flat = alpha.ravel()
1051
+ # Provide 2-D alpha:
1052
+ fig, (ax0, ax1) = plt.subplots(2)
1053
+ coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha)
1054
+ coll2 = getattr(ax0, pcfunc)(x, y, z)
1055
+ coll2.set_alpha(alpha)
1056
+ plt.draw()
1057
+ assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat)
1058
+ assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat)
1059
+ # Or provide 1-D alpha:
1060
+ fig, (ax0, ax1) = plt.subplots(2)
1061
+ coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha)
1062
+ coll2 = getattr(ax1, pcfunc)(x, y, z)
1063
+ coll2.set_alpha(alpha)
1064
+ plt.draw()
1065
+ assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat)
1066
+ assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat)
1067
+
1068
+
1069
+ def test_alpha_validation(pcfunc):
1070
+ # Most of the relevant testing is in test_artist and test_colors.
1071
+ fig, ax = plt.subplots()
1072
+ pc = getattr(ax, pcfunc)(np.arange(12).reshape((3, 4)))
1073
+ with pytest.raises(ValueError, match="^Data array shape"):
1074
+ pc.set_alpha([0.5, 0.6])
1075
+ pc.update_scalarmappable()
1076
+
1077
+
1078
+ def test_legend_inverse_size_label_relationship():
1079
+ """
1080
+ Ensure legend markers scale appropriately when label and size are
1081
+ inversely related.
1082
+ Here label = 5 / size
1083
+ """
1084
+
1085
+ np.random.seed(19680801)
1086
+ X = np.random.random(50)
1087
+ Y = np.random.random(50)
1088
+ C = 1 - np.random.random(50)
1089
+ S = 5 / C
1090
+
1091
+ legend_sizes = [0.2, 0.4, 0.6, 0.8]
1092
+ fig, ax = plt.subplots()
1093
+ sc = ax.scatter(X, Y, s=S)
1094
+ handles, labels = sc.legend_elements(
1095
+ prop='sizes', num=legend_sizes, func=lambda s: 5 / s
1096
+ )
1097
+
1098
+ # Convert markersize scale to 's' scale
1099
+ handle_sizes = [x.get_markersize() for x in handles]
1100
+ handle_sizes = [5 / x**2 for x in handle_sizes]
1101
+
1102
+ assert_array_almost_equal(handle_sizes, legend_sizes, decimal=1)
1103
+
1104
+
1105
+ @mpl.style.context('default')
1106
+ def test_color_logic(pcfunc):
1107
+ pcfunc = getattr(plt, pcfunc)
1108
+ z = np.arange(12).reshape(3, 4)
1109
+ # Explicitly set an edgecolor.
1110
+ pc = pcfunc(z, edgecolors='red', facecolors='none')
1111
+ pc.update_scalarmappable() # This is called in draw().
1112
+ # Define 2 reference "colors" here for multiple use.
1113
+ face_default = mcolors.to_rgba_array(pc._get_default_facecolor())
1114
+ mapped = pc.get_cmap()(pc.norm(z.ravel()))
1115
+ # GitHub issue #1302:
1116
+ assert mcolors.same_color(pc.get_edgecolor(), 'red')
1117
+ # Check setting attributes after initialization:
1118
+ pc = pcfunc(z)
1119
+ pc.set_facecolor('none')
1120
+ pc.set_edgecolor('red')
1121
+ pc.update_scalarmappable()
1122
+ assert mcolors.same_color(pc.get_facecolor(), 'none')
1123
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
1124
+ pc.set_alpha(0.5)
1125
+ pc.update_scalarmappable()
1126
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]])
1127
+ pc.set_alpha(None) # restore default alpha
1128
+ pc.update_scalarmappable()
1129
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
1130
+ # Reset edgecolor to default.
1131
+ pc.set_edgecolor(None)
1132
+ pc.update_scalarmappable()
1133
+ assert np.array_equal(pc.get_edgecolor(), mapped)
1134
+ pc.set_facecolor(None) # restore default for facecolor
1135
+ pc.update_scalarmappable()
1136
+ assert np.array_equal(pc.get_facecolor(), mapped)
1137
+ assert mcolors.same_color(pc.get_edgecolor(), 'none')
1138
+ # Turn off colormapping entirely:
1139
+ pc.set_array(None)
1140
+ pc.update_scalarmappable()
1141
+ assert mcolors.same_color(pc.get_edgecolor(), 'none')
1142
+ assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped
1143
+ # Turn it back on by restoring the array (must be 1D!):
1144
+ pc.set_array(z)
1145
+ pc.update_scalarmappable()
1146
+ assert np.array_equal(pc.get_facecolor(), mapped)
1147
+ assert mcolors.same_color(pc.get_edgecolor(), 'none')
1148
+ # Give color via tuple rather than string.
1149
+ pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0))
1150
+ pc.update_scalarmappable()
1151
+ assert np.array_equal(pc.get_facecolor(), mapped)
1152
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
1153
+ # Provide an RGB array; mapping overrides it.
1154
+ pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3)))
1155
+ pc.update_scalarmappable()
1156
+ assert np.array_equal(pc.get_facecolor(), mapped)
1157
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
1158
+ # Turn off the mapping.
1159
+ pc.set_array(None)
1160
+ pc.update_scalarmappable()
1161
+ assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3)))
1162
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
1163
+ # And an RGBA array.
1164
+ pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4)))
1165
+ pc.update_scalarmappable()
1166
+ assert np.array_equal(pc.get_facecolor(), mapped)
1167
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
1168
+ # Turn off the mapping.
1169
+ pc.set_array(None)
1170
+ pc.update_scalarmappable()
1171
+ assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4)))
1172
+ assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]])
1173
+
1174
+
1175
+ def test_LineCollection_args():
1176
+ lc = LineCollection(None, linewidth=2.2, edgecolor='r',
1177
+ zorder=3, facecolors=[0, 1, 0, 1])
1178
+ assert lc.get_linewidth()[0] == 2.2
1179
+ assert mcolors.same_color(lc.get_edgecolor(), 'r')
1180
+ assert lc.get_zorder() == 3
1181
+ assert mcolors.same_color(lc.get_facecolor(), [[0, 1, 0, 1]])
1182
+ # To avoid breaking mplot3d, LineCollection internally sets the facecolor
1183
+ # kwarg if it has not been specified. Hence we need the following test
1184
+ # for LineCollection._set_default().
1185
+ lc = LineCollection(None, facecolor=None)
1186
+ assert mcolors.same_color(lc.get_facecolor(), 'none')
1187
+
1188
+
1189
+ def test_array_dimensions(pcfunc):
1190
+ # Make sure we can set the 1D, 2D, and 3D array shapes
1191
+ z = np.arange(12).reshape(3, 4)
1192
+ pc = getattr(plt, pcfunc)(z)
1193
+ # 1D
1194
+ pc.set_array(z.ravel())
1195
+ pc.update_scalarmappable()
1196
+ # 2D
1197
+ pc.set_array(z)
1198
+ pc.update_scalarmappable()
1199
+ # 3D RGB is OK as well
1200
+ z = np.arange(36, dtype=np.uint8).reshape(3, 4, 3)
1201
+ pc.set_array(z)
1202
+ pc.update_scalarmappable()
1203
+
1204
+
1205
+ def test_get_segments():
1206
+ segments = np.tile(np.linspace(0, 1, 256), (2, 1)).T
1207
+ lc = LineCollection([segments])
1208
+
1209
+ readback, = lc.get_segments()
1210
+ # these should comeback un-changed!
1211
+ assert np.all(segments == readback)
1212
+
1213
+
1214
+ def test_set_offsets_late():
1215
+ identity = mtransforms.IdentityTransform()
1216
+ sizes = [2]
1217
+
1218
+ null = mcollections.CircleCollection(sizes=sizes)
1219
+
1220
+ init = mcollections.CircleCollection(sizes=sizes, offsets=(10, 10))
1221
+
1222
+ late = mcollections.CircleCollection(sizes=sizes)
1223
+ late.set_offsets((10, 10))
1224
+
1225
+ # Bbox.__eq__ doesn't compare bounds
1226
+ null_bounds = null.get_datalim(identity).bounds
1227
+ init_bounds = init.get_datalim(identity).bounds
1228
+ late_bounds = late.get_datalim(identity).bounds
1229
+
1230
+ # offsets and transform are applied when set after initialization
1231
+ assert null_bounds != init_bounds
1232
+ assert init_bounds == late_bounds
1233
+
1234
+
1235
+ def test_set_offset_transform():
1236
+ skew = mtransforms.Affine2D().skew(2, 2)
1237
+ init = mcollections.Collection(offset_transform=skew)
1238
+
1239
+ late = mcollections.Collection()
1240
+ late.set_offset_transform(skew)
1241
+
1242
+ assert skew == init.get_offset_transform() == late.get_offset_transform()
1243
+
1244
+
1245
+ def test_set_offset_units():
1246
+ # passing the offsets in initially (i.e. via scatter)
1247
+ # should yield the same results as `set_offsets`
1248
+ x = np.linspace(0, 10, 5)
1249
+ y = np.sin(x)
1250
+ d = x * np.timedelta64(24, 'h') + np.datetime64('2021-11-29')
1251
+
1252
+ sc = plt.scatter(d, y)
1253
+ off0 = sc.get_offsets()
1254
+ sc.set_offsets(list(zip(d, y)))
1255
+ np.testing.assert_allclose(off0, sc.get_offsets())
1256
+
1257
+ # try the other way around
1258
+ fig, ax = plt.subplots()
1259
+ sc = ax.scatter(y, d)
1260
+ off0 = sc.get_offsets()
1261
+ sc.set_offsets(list(zip(y, d)))
1262
+ np.testing.assert_allclose(off0, sc.get_offsets())
1263
+
1264
+
1265
+ @image_comparison(baseline_images=["test_check_masked_offsets"],
1266
+ extensions=["png"], remove_text=True, style="mpl20")
1267
+ def test_check_masked_offsets():
1268
+ # Check if masked data is respected by scatter
1269
+ # Ref: Issue #24545
1270
+ unmasked_x = [
1271
+ datetime(2022, 12, 15, 4, 49, 52),
1272
+ datetime(2022, 12, 15, 4, 49, 53),
1273
+ datetime(2022, 12, 15, 4, 49, 54),
1274
+ datetime(2022, 12, 15, 4, 49, 55),
1275
+ datetime(2022, 12, 15, 4, 49, 56),
1276
+ ]
1277
+
1278
+ masked_y = np.ma.array([1, 2, 3, 4, 5], mask=[0, 1, 1, 0, 0])
1279
+
1280
+ fig, ax = plt.subplots()
1281
+ ax.scatter(unmasked_x, masked_y)
1282
+
1283
+
1284
+ @check_figures_equal(extensions=["png"])
1285
+ def test_masked_set_offsets(fig_ref, fig_test):
1286
+ x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0])
1287
+ y = np.arange(1, 6)
1288
+
1289
+ ax_test = fig_test.add_subplot()
1290
+ scat = ax_test.scatter(x, y)
1291
+ scat.set_offsets(np.ma.column_stack([x, y]))
1292
+ ax_test.set_xticks([])
1293
+ ax_test.set_yticks([])
1294
+
1295
+ ax_ref = fig_ref.add_subplot()
1296
+ ax_ref.scatter([1, 2, 5], [1, 2, 5])
1297
+ ax_ref.set_xticks([])
1298
+ ax_ref.set_yticks([])
1299
+
1300
+
1301
+ def test_check_offsets_dtype():
1302
+ # Check that setting offsets doesn't change dtype
1303
+ x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0])
1304
+ y = np.arange(1, 6)
1305
+
1306
+ fig, ax = plt.subplots()
1307
+ scat = ax.scatter(x, y)
1308
+ masked_offsets = np.ma.column_stack([x, y])
1309
+ scat.set_offsets(masked_offsets)
1310
+ assert isinstance(scat.get_offsets(), type(masked_offsets))
1311
+
1312
+ unmasked_offsets = np.column_stack([x, y])
1313
+ scat.set_offsets(unmasked_offsets)
1314
+ assert isinstance(scat.get_offsets(), type(unmasked_offsets))
1315
+
1316
+
1317
+ @pytest.mark.parametrize('gapcolor', ['orange', ['r', 'k']])
1318
+ @check_figures_equal(extensions=['png'])
1319
+ @mpl.rc_context({'lines.linewidth': 20})
1320
+ def test_striped_lines(fig_test, fig_ref, gapcolor):
1321
+ ax_test = fig_test.add_subplot(111)
1322
+ ax_ref = fig_ref.add_subplot(111)
1323
+
1324
+ for ax in [ax_test, ax_ref]:
1325
+ ax.set_xlim(0, 6)
1326
+ ax.set_ylim(0, 1)
1327
+
1328
+ x = range(1, 6)
1329
+ linestyles = [':', '-', '--']
1330
+
1331
+ ax_test.vlines(x, 0, 1, linestyle=linestyles, gapcolor=gapcolor, alpha=0.5)
1332
+
1333
+ if isinstance(gapcolor, str):
1334
+ gapcolor = [gapcolor]
1335
+
1336
+ for x, gcol, ls in zip(x, itertools.cycle(gapcolor),
1337
+ itertools.cycle(linestyles)):
1338
+ ax_ref.axvline(x, 0, 1, linestyle=ls, gapcolor=gcol, alpha=0.5)
parrot/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py ADDED
@@ -0,0 +1,175 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import contextlib
2
+ from io import StringIO
3
+
4
+ import matplotlib as mpl
5
+ import matplotlib.pyplot as plt
6
+ import numpy as np
7
+ import pytest
8
+
9
+ from cycler import cycler
10
+
11
+
12
+ def test_colorcycle_basic():
13
+ fig, ax = plt.subplots()
14
+ ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']))
15
+ for _ in range(4):
16
+ ax.plot(range(10), range(10))
17
+ assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r']
18
+
19
+
20
+ def test_marker_cycle():
21
+ fig, ax = plt.subplots()
22
+ ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) +
23
+ cycler('marker', ['.', '*', 'x']))
24
+ for _ in range(4):
25
+ ax.plot(range(10), range(10))
26
+ assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r']
27
+ assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.']
28
+
29
+
30
+ def test_valid_marker_cycles():
31
+ fig, ax = plt.subplots()
32
+ ax.set_prop_cycle(cycler(marker=[1, "+", ".", 4]))
33
+
34
+
35
+ def test_marker_cycle_kwargs_arrays_iterators():
36
+ fig, ax = plt.subplots()
37
+ ax.set_prop_cycle(c=np.array(['r', 'g', 'y']),
38
+ marker=iter(['.', '*', 'x']))
39
+ for _ in range(4):
40
+ ax.plot(range(10), range(10))
41
+ assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r']
42
+ assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.']
43
+
44
+
45
+ def test_linestylecycle_basic():
46
+ fig, ax = plt.subplots()
47
+ ax.set_prop_cycle(cycler('ls', ['-', '--', ':']))
48
+ for _ in range(4):
49
+ ax.plot(range(10), range(10))
50
+ assert [l.get_linestyle() for l in ax.lines] == ['-', '--', ':', '-']
51
+
52
+
53
+ def test_fillcycle_basic():
54
+ fig, ax = plt.subplots()
55
+ ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) +
56
+ cycler('hatch', ['xx', 'O', '|-']) +
57
+ cycler('linestyle', ['-', '--', ':']))
58
+ for _ in range(4):
59
+ ax.fill(range(10), range(10))
60
+ assert ([p.get_facecolor() for p in ax.patches]
61
+ == [mpl.colors.to_rgba(c) for c in ['r', 'g', 'y', 'r']])
62
+ assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', '|-', 'xx']
63
+ assert [p.get_linestyle() for p in ax.patches] == ['-', '--', ':', '-']
64
+
65
+
66
+ def test_fillcycle_ignore():
67
+ fig, ax = plt.subplots()
68
+ ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']) +
69
+ cycler('hatch', ['xx', 'O', '|-']) +
70
+ cycler('marker', ['.', '*', 'D']))
71
+ t = range(10)
72
+ # Should not advance the cycler, even though there is an
73
+ # unspecified property in the cycler "marker".
74
+ # "marker" is not a Polygon property, and should be ignored.
75
+ ax.fill(t, t, 'r', hatch='xx')
76
+ # Allow the cycler to advance, but specify some properties
77
+ ax.fill(t, t, hatch='O')
78
+ ax.fill(t, t)
79
+ ax.fill(t, t)
80
+ assert ([p.get_facecolor() for p in ax.patches]
81
+ == [mpl.colors.to_rgba(c) for c in ['r', 'r', 'g', 'y']])
82
+ assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', 'O', '|-']
83
+
84
+
85
+ def test_property_collision_plot():
86
+ fig, ax = plt.subplots()
87
+ ax.set_prop_cycle('linewidth', [2, 4])
88
+ t = range(10)
89
+ for c in range(1, 4):
90
+ ax.plot(t, t, lw=0.1)
91
+ ax.plot(t, t)
92
+ ax.plot(t, t)
93
+ assert [l.get_linewidth() for l in ax.lines] == [0.1, 0.1, 0.1, 2, 4]
94
+
95
+
96
+ def test_property_collision_fill():
97
+ fig, ax = plt.subplots()
98
+ ax.set_prop_cycle(linewidth=[2, 3, 4, 5, 6], facecolor='bgcmy')
99
+ t = range(10)
100
+ for c in range(1, 4):
101
+ ax.fill(t, t, lw=0.1)
102
+ ax.fill(t, t)
103
+ ax.fill(t, t)
104
+ assert ([p.get_facecolor() for p in ax.patches]
105
+ == [mpl.colors.to_rgba(c) for c in 'bgcmy'])
106
+ assert [p.get_linewidth() for p in ax.patches] == [0.1, 0.1, 0.1, 5, 6]
107
+
108
+
109
+ def test_valid_input_forms():
110
+ fig, ax = plt.subplots()
111
+ # These should not raise an error.
112
+ ax.set_prop_cycle(None)
113
+ ax.set_prop_cycle(cycler('linewidth', [1, 2]))
114
+ ax.set_prop_cycle('color', 'rgywkbcm')
115
+ ax.set_prop_cycle('lw', (1, 2))
116
+ ax.set_prop_cycle('linewidth', [1, 2])
117
+ ax.set_prop_cycle('linewidth', iter([1, 2]))
118
+ ax.set_prop_cycle('linewidth', np.array([1, 2]))
119
+ ax.set_prop_cycle('color', np.array([[1, 0, 0],
120
+ [0, 1, 0],
121
+ [0, 0, 1]]))
122
+ ax.set_prop_cycle('dashes', [[], [13, 2], [8, 3, 1, 3]])
123
+ ax.set_prop_cycle(lw=[1, 2], color=['k', 'w'], ls=['-', '--'])
124
+ ax.set_prop_cycle(lw=np.array([1, 2]),
125
+ color=np.array(['k', 'w']),
126
+ ls=np.array(['-', '--']))
127
+
128
+
129
+ def test_cycle_reset():
130
+ fig, ax = plt.subplots()
131
+ prop0 = StringIO()
132
+ prop1 = StringIO()
133
+ prop2 = StringIO()
134
+
135
+ with contextlib.redirect_stdout(prop0):
136
+ plt.getp(ax.plot([1, 2], label="label")[0])
137
+
138
+ ax.set_prop_cycle(linewidth=[10, 9, 4])
139
+ with contextlib.redirect_stdout(prop1):
140
+ plt.getp(ax.plot([1, 2], label="label")[0])
141
+ assert prop1.getvalue() != prop0.getvalue()
142
+
143
+ ax.set_prop_cycle(None)
144
+ with contextlib.redirect_stdout(prop2):
145
+ plt.getp(ax.plot([1, 2], label="label")[0])
146
+ assert prop2.getvalue() == prop0.getvalue()
147
+
148
+
149
+ def test_invalid_input_forms():
150
+ fig, ax = plt.subplots()
151
+
152
+ with pytest.raises((TypeError, ValueError)):
153
+ ax.set_prop_cycle(1)
154
+ with pytest.raises((TypeError, ValueError)):
155
+ ax.set_prop_cycle([1, 2])
156
+
157
+ with pytest.raises((TypeError, ValueError)):
158
+ ax.set_prop_cycle('color', 'fish')
159
+
160
+ with pytest.raises((TypeError, ValueError)):
161
+ ax.set_prop_cycle('linewidth', 1)
162
+ with pytest.raises((TypeError, ValueError)):
163
+ ax.set_prop_cycle('linewidth', {1, 2})
164
+ with pytest.raises((TypeError, ValueError)):
165
+ ax.set_prop_cycle(linewidth=1, color='r')
166
+
167
+ with pytest.raises((TypeError, ValueError)):
168
+ ax.set_prop_cycle('foobar', [1, 2])
169
+ with pytest.raises((TypeError, ValueError)):
170
+ ax.set_prop_cycle(foobar=[1, 2])
171
+
172
+ with pytest.raises((TypeError, ValueError)):
173
+ ax.set_prop_cycle(cycler(foobar=[1, 2]))
174
+ with pytest.raises(ValueError):
175
+ ax.set_prop_cycle(cycler(color='rgb', c='cmy'))
parrot/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ from pathlib import Path
3
+ import shutil
4
+
5
+ import matplotlib.dviread as dr
6
+ import pytest
7
+
8
+
9
+ def test_PsfontsMap(monkeypatch):
10
+ monkeypatch.setattr(dr, 'find_tex_file', lambda x: x.decode())
11
+
12
+ filename = str(Path(__file__).parent / 'baseline_images/dviread/test.map')
13
+ fontmap = dr.PsfontsMap(filename)
14
+ # Check all properties of a few fonts
15
+ for n in [1, 2, 3, 4, 5]:
16
+ key = b'TeXfont%d' % n
17
+ entry = fontmap[key]
18
+ assert entry.texname == key
19
+ assert entry.psname == b'PSfont%d' % n
20
+ if n not in [3, 5]:
21
+ assert entry.encoding == 'font%d.enc' % n
22
+ elif n == 3:
23
+ assert entry.encoding == 'enc3.foo'
24
+ # We don't care about the encoding of TeXfont5, which specifies
25
+ # multiple encodings.
26
+ if n not in [1, 5]:
27
+ assert entry.filename == 'font%d.pfa' % n
28
+ else:
29
+ assert entry.filename == 'font%d.pfb' % n
30
+ if n == 4:
31
+ assert entry.effects == {'slant': -0.1, 'extend': 1.2}
32
+ else:
33
+ assert entry.effects == {}
34
+ # Some special cases
35
+ entry = fontmap[b'TeXfont6']
36
+ assert entry.filename is None
37
+ assert entry.encoding is None
38
+ entry = fontmap[b'TeXfont7']
39
+ assert entry.filename is None
40
+ assert entry.encoding == 'font7.enc'
41
+ entry = fontmap[b'TeXfont8']
42
+ assert entry.filename == 'font8.pfb'
43
+ assert entry.encoding is None
44
+ entry = fontmap[b'TeXfont9']
45
+ assert entry.psname == b'TeXfont9'
46
+ assert entry.filename == '/absolute/font9.pfb'
47
+ # First of duplicates only.
48
+ entry = fontmap[b'TeXfontA']
49
+ assert entry.psname == b'PSfontA1'
50
+ # Slant/Extend only works for T1 fonts.
51
+ entry = fontmap[b'TeXfontB']
52
+ assert entry.psname == b'PSfontB6'
53
+ # Subsetted TrueType must have encoding.
54
+ entry = fontmap[b'TeXfontC']
55
+ assert entry.psname == b'PSfontC3'
56
+ # Missing font
57
+ with pytest.raises(LookupError, match='no-such-font'):
58
+ fontmap[b'no-such-font']
59
+ with pytest.raises(LookupError, match='%'):
60
+ fontmap[b'%']
61
+
62
+
63
+ @pytest.mark.skipif(shutil.which("kpsewhich") is None,
64
+ reason="kpsewhich is not available")
65
+ def test_dviread():
66
+ dirpath = Path(__file__).parent / 'baseline_images/dviread'
67
+ with (dirpath / 'test.json').open() as f:
68
+ correct = json.load(f)
69
+ with dr.Dvi(str(dirpath / 'test.dvi'), None) as dvi:
70
+ data = [{'text': [[t.x, t.y,
71
+ chr(t.glyph),
72
+ t.font.texname.decode('ascii'),
73
+ round(t.font.size, 2)]
74
+ for t in page.text],
75
+ 'boxes': [[b.x, b.y, b.height, b.width] for b in page.boxes]}
76
+ for page in dvi]
77
+ assert data == correct
parrot/lib/python3.10/site-packages/matplotlib/tests/test_figure.py ADDED
@@ -0,0 +1,1759 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import copy
2
+ from datetime import datetime
3
+ import io
4
+ import pickle
5
+ import platform
6
+ from threading import Timer
7
+ from types import SimpleNamespace
8
+ import warnings
9
+
10
+ import numpy as np
11
+ import pytest
12
+ from PIL import Image
13
+
14
+ import matplotlib as mpl
15
+ from matplotlib import gridspec
16
+ from matplotlib.testing.decorators import image_comparison, check_figures_equal
17
+ from matplotlib.axes import Axes
18
+ from matplotlib.backend_bases import KeyEvent, MouseEvent
19
+ from matplotlib.figure import Figure, FigureBase
20
+ from matplotlib.layout_engine import (ConstrainedLayoutEngine,
21
+ TightLayoutEngine,
22
+ PlaceHolderLayoutEngine)
23
+ from matplotlib.ticker import AutoMinorLocator, FixedFormatter, ScalarFormatter
24
+ import matplotlib.pyplot as plt
25
+ import matplotlib.dates as mdates
26
+
27
+
28
+ @image_comparison(['figure_align_labels'], extensions=['png', 'svg'],
29
+ tol=0 if platform.machine() == 'x86_64' else 0.01)
30
+ def test_align_labels():
31
+ fig = plt.figure(layout='tight')
32
+ gs = gridspec.GridSpec(3, 3)
33
+
34
+ ax = fig.add_subplot(gs[0, :2])
35
+ ax.plot(np.arange(0, 1e6, 1000))
36
+ ax.set_ylabel('Ylabel0 0')
37
+ ax = fig.add_subplot(gs[0, -1])
38
+ ax.plot(np.arange(0, 1e4, 100))
39
+
40
+ for i in range(3):
41
+ ax = fig.add_subplot(gs[1, i])
42
+ ax.set_ylabel('YLabel1 %d' % i)
43
+ ax.set_xlabel('XLabel1 %d' % i)
44
+ if i in [0, 2]:
45
+ ax.xaxis.set_label_position("top")
46
+ ax.xaxis.tick_top()
47
+ if i == 0:
48
+ for tick in ax.get_xticklabels():
49
+ tick.set_rotation(90)
50
+ if i == 2:
51
+ ax.yaxis.set_label_position("right")
52
+ ax.yaxis.tick_right()
53
+
54
+ for i in range(3):
55
+ ax = fig.add_subplot(gs[2, i])
56
+ ax.set_xlabel(f'XLabel2 {i}')
57
+ ax.set_ylabel(f'YLabel2 {i}')
58
+
59
+ if i == 2:
60
+ ax.plot(np.arange(0, 1e4, 10))
61
+ ax.yaxis.set_label_position("right")
62
+ ax.yaxis.tick_right()
63
+ for tick in ax.get_xticklabels():
64
+ tick.set_rotation(90)
65
+
66
+ fig.align_labels()
67
+
68
+
69
+ @image_comparison(['figure_align_titles_tight.png',
70
+ 'figure_align_titles_constrained.png'],
71
+ tol=0 if platform.machine() == 'x86_64' else 0.022,
72
+ style='mpl20')
73
+ def test_align_titles():
74
+ for layout in ['tight', 'constrained']:
75
+ fig, axs = plt.subplots(1, 2, layout=layout, width_ratios=[2, 1])
76
+
77
+ ax = axs[0]
78
+ ax.plot(np.arange(0, 1e6, 1000))
79
+ ax.set_title('Title0 left', loc='left')
80
+ ax.set_title('Title0 center', loc='center')
81
+ ax.set_title('Title0 right', loc='right')
82
+
83
+ ax = axs[1]
84
+ ax.plot(np.arange(0, 1e4, 100))
85
+ ax.set_title('Title1')
86
+ ax.set_xlabel('Xlabel0')
87
+ ax.xaxis.set_label_position("top")
88
+ ax.xaxis.tick_top()
89
+ for tick in ax.get_xticklabels():
90
+ tick.set_rotation(90)
91
+
92
+ fig.align_titles()
93
+
94
+
95
+ def test_align_labels_stray_axes():
96
+ fig, axs = plt.subplots(2, 2)
97
+ for nn, ax in enumerate(axs.flat):
98
+ ax.set_xlabel('Boo')
99
+ ax.set_xlabel('Who')
100
+ ax.plot(np.arange(4)**nn, np.arange(4)**nn)
101
+ fig.align_ylabels()
102
+ fig.align_xlabels()
103
+ fig.draw_without_rendering()
104
+ xn = np.zeros(4)
105
+ yn = np.zeros(4)
106
+ for nn, ax in enumerate(axs.flat):
107
+ yn[nn] = ax.xaxis.label.get_position()[1]
108
+ xn[nn] = ax.yaxis.label.get_position()[0]
109
+ np.testing.assert_allclose(xn[:2], xn[2:])
110
+ np.testing.assert_allclose(yn[::2], yn[1::2])
111
+
112
+ fig, axs = plt.subplots(2, 2, constrained_layout=True)
113
+ for nn, ax in enumerate(axs.flat):
114
+ ax.set_xlabel('Boo')
115
+ ax.set_xlabel('Who')
116
+ pc = ax.pcolormesh(np.random.randn(10, 10))
117
+ fig.colorbar(pc, ax=ax)
118
+ fig.align_ylabels()
119
+ fig.align_xlabels()
120
+ fig.draw_without_rendering()
121
+ xn = np.zeros(4)
122
+ yn = np.zeros(4)
123
+ for nn, ax in enumerate(axs.flat):
124
+ yn[nn] = ax.xaxis.label.get_position()[1]
125
+ xn[nn] = ax.yaxis.label.get_position()[0]
126
+ np.testing.assert_allclose(xn[:2], xn[2:])
127
+ np.testing.assert_allclose(yn[::2], yn[1::2])
128
+
129
+
130
+ def test_figure_label():
131
+ # pyplot figure creation, selection, and closing with label/number/instance
132
+ plt.close('all')
133
+ fig_today = plt.figure('today')
134
+ plt.figure(3)
135
+ plt.figure('tomorrow')
136
+ plt.figure()
137
+ plt.figure(0)
138
+ plt.figure(1)
139
+ plt.figure(3)
140
+ assert plt.get_fignums() == [0, 1, 3, 4, 5]
141
+ assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', '']
142
+ plt.close(10)
143
+ plt.close()
144
+ plt.close(5)
145
+ plt.close('tomorrow')
146
+ assert plt.get_fignums() == [0, 1]
147
+ assert plt.get_figlabels() == ['', 'today']
148
+ plt.figure(fig_today)
149
+ assert plt.gcf() == fig_today
150
+ with pytest.raises(ValueError):
151
+ plt.figure(Figure())
152
+
153
+
154
+ def test_fignum_exists():
155
+ # pyplot figure creation, selection and closing with fignum_exists
156
+ plt.figure('one')
157
+ plt.figure(2)
158
+ plt.figure('three')
159
+ plt.figure()
160
+ assert plt.fignum_exists('one')
161
+ assert plt.fignum_exists(2)
162
+ assert plt.fignum_exists('three')
163
+ assert plt.fignum_exists(4)
164
+ plt.close('one')
165
+ plt.close(4)
166
+ assert not plt.fignum_exists('one')
167
+ assert not plt.fignum_exists(4)
168
+
169
+
170
+ def test_clf_keyword():
171
+ # test if existing figure is cleared with figure() and subplots()
172
+ text1 = 'A fancy plot'
173
+ text2 = 'Really fancy!'
174
+
175
+ fig0 = plt.figure(num=1)
176
+ fig0.suptitle(text1)
177
+ assert [t.get_text() for t in fig0.texts] == [text1]
178
+
179
+ fig1 = plt.figure(num=1, clear=False)
180
+ fig1.text(0.5, 0.5, text2)
181
+ assert fig0 is fig1
182
+ assert [t.get_text() for t in fig1.texts] == [text1, text2]
183
+
184
+ fig2, ax2 = plt.subplots(2, 1, num=1, clear=True)
185
+ assert fig0 is fig2
186
+ assert [t.get_text() for t in fig2.texts] == []
187
+
188
+
189
+ @image_comparison(['figure_today'],
190
+ tol=0.015 if platform.machine() == 'arm64' else 0)
191
+ def test_figure():
192
+ # named figure support
193
+ fig = plt.figure('today')
194
+ ax = fig.add_subplot()
195
+ ax.set_title(fig.get_label())
196
+ ax.plot(np.arange(5))
197
+ # plot red line in a different figure.
198
+ plt.figure('tomorrow')
199
+ plt.plot([0, 1], [1, 0], 'r')
200
+ # Return to the original; make sure the red line is not there.
201
+ plt.figure('today')
202
+ plt.close('tomorrow')
203
+
204
+
205
+ @image_comparison(['figure_legend'])
206
+ def test_figure_legend():
207
+ fig, axs = plt.subplots(2)
208
+ axs[0].plot([0, 1], [1, 0], label='x', color='g')
209
+ axs[0].plot([0, 1], [0, 1], label='y', color='r')
210
+ axs[0].plot([0, 1], [0.5, 0.5], label='y', color='k')
211
+
212
+ axs[1].plot([0, 1], [1, 0], label='_y', color='r')
213
+ axs[1].plot([0, 1], [0, 1], label='z', color='b')
214
+ fig.legend()
215
+
216
+
217
+ def test_gca():
218
+ fig = plt.figure()
219
+
220
+ # test that gca() picks up Axes created via add_axes()
221
+ ax0 = fig.add_axes([0, 0, 1, 1])
222
+ assert fig.gca() is ax0
223
+
224
+ # test that gca() picks up Axes created via add_subplot()
225
+ ax1 = fig.add_subplot(111)
226
+ assert fig.gca() is ax1
227
+
228
+ # add_axes on an existing Axes should not change stored order, but will
229
+ # make it current.
230
+ fig.add_axes(ax0)
231
+ assert fig.axes == [ax0, ax1]
232
+ assert fig.gca() is ax0
233
+
234
+ # sca() should not change stored order of Axes, which is order added.
235
+ fig.sca(ax0)
236
+ assert fig.axes == [ax0, ax1]
237
+
238
+ # add_subplot on an existing Axes should not change stored order, but will
239
+ # make it current.
240
+ fig.add_subplot(ax1)
241
+ assert fig.axes == [ax0, ax1]
242
+ assert fig.gca() is ax1
243
+
244
+
245
+ def test_add_subplot_subclass():
246
+ fig = plt.figure()
247
+ fig.add_subplot(axes_class=Axes)
248
+ with pytest.raises(ValueError):
249
+ fig.add_subplot(axes_class=Axes, projection="3d")
250
+ with pytest.raises(ValueError):
251
+ fig.add_subplot(axes_class=Axes, polar=True)
252
+ with pytest.raises(ValueError):
253
+ fig.add_subplot(projection="3d", polar=True)
254
+ with pytest.raises(TypeError):
255
+ fig.add_subplot(projection=42)
256
+
257
+
258
+ def test_add_subplot_invalid():
259
+ fig = plt.figure()
260
+ with pytest.raises(ValueError,
261
+ match='Number of columns must be a positive integer'):
262
+ fig.add_subplot(2, 0, 1)
263
+ with pytest.raises(ValueError,
264
+ match='Number of rows must be a positive integer'):
265
+ fig.add_subplot(0, 2, 1)
266
+ with pytest.raises(ValueError, match='num must be an integer with '
267
+ '1 <= num <= 4'):
268
+ fig.add_subplot(2, 2, 0)
269
+ with pytest.raises(ValueError, match='num must be an integer with '
270
+ '1 <= num <= 4'):
271
+ fig.add_subplot(2, 2, 5)
272
+ with pytest.raises(ValueError, match='num must be an integer with '
273
+ '1 <= num <= 4'):
274
+ fig.add_subplot(2, 2, 0.5)
275
+
276
+ with pytest.raises(ValueError, match='must be a three-digit integer'):
277
+ fig.add_subplot(42)
278
+ with pytest.raises(ValueError, match='must be a three-digit integer'):
279
+ fig.add_subplot(1000)
280
+
281
+ with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '
282
+ 'but 2 were given'):
283
+ fig.add_subplot(2, 2)
284
+ with pytest.raises(TypeError, match='takes 1 or 3 positional arguments '
285
+ 'but 4 were given'):
286
+ fig.add_subplot(1, 2, 3, 4)
287
+ with pytest.raises(ValueError,
288
+ match="Number of rows must be a positive integer, "
289
+ "not '2'"):
290
+ fig.add_subplot('2', 2, 1)
291
+ with pytest.raises(ValueError,
292
+ match='Number of columns must be a positive integer, '
293
+ 'not 2.0'):
294
+ fig.add_subplot(2, 2.0, 1)
295
+ _, ax = plt.subplots()
296
+ with pytest.raises(ValueError,
297
+ match='The Axes must have been created in the '
298
+ 'present figure'):
299
+ fig.add_subplot(ax)
300
+
301
+
302
+ @image_comparison(['figure_suptitle'])
303
+ def test_suptitle():
304
+ fig, _ = plt.subplots()
305
+ fig.suptitle('hello', color='r')
306
+ fig.suptitle('title', color='g', rotation=30)
307
+
308
+
309
+ def test_suptitle_fontproperties():
310
+ fig, ax = plt.subplots()
311
+ fps = mpl.font_manager.FontProperties(size='large', weight='bold')
312
+ txt = fig.suptitle('fontprops title', fontproperties=fps)
313
+ assert txt.get_fontsize() == fps.get_size_in_points()
314
+ assert txt.get_weight() == fps.get_weight()
315
+
316
+
317
+ def test_suptitle_subfigures():
318
+ fig = plt.figure(figsize=(4, 3))
319
+ sf1, sf2 = fig.subfigures(1, 2)
320
+ sf2.set_facecolor('white')
321
+ sf1.subplots()
322
+ sf2.subplots()
323
+ fig.suptitle("This is a visible suptitle.")
324
+
325
+ # verify the first subfigure facecolor is the default transparent
326
+ assert sf1.get_facecolor() == (0.0, 0.0, 0.0, 0.0)
327
+ # verify the second subfigure facecolor is white
328
+ assert sf2.get_facecolor() == (1.0, 1.0, 1.0, 1.0)
329
+
330
+
331
+ def test_get_suptitle_supxlabel_supylabel():
332
+ fig, ax = plt.subplots()
333
+ assert fig.get_suptitle() == ""
334
+ assert fig.get_supxlabel() == ""
335
+ assert fig.get_supylabel() == ""
336
+ fig.suptitle('suptitle')
337
+ assert fig.get_suptitle() == 'suptitle'
338
+ fig.supxlabel('supxlabel')
339
+ assert fig.get_supxlabel() == 'supxlabel'
340
+ fig.supylabel('supylabel')
341
+ assert fig.get_supylabel() == 'supylabel'
342
+
343
+
344
+ @image_comparison(['alpha_background'],
345
+ # only test png and svg. The PDF output appears correct,
346
+ # but Ghostscript does not preserve the background color.
347
+ extensions=['png', 'svg'],
348
+ savefig_kwarg={'facecolor': (0, 1, 0.4),
349
+ 'edgecolor': 'none'})
350
+ def test_alpha():
351
+ # We want an image which has a background color and an alpha of 0.4.
352
+ fig = plt.figure(figsize=[2, 1])
353
+ fig.set_facecolor((0, 1, 0.4))
354
+ fig.patch.set_alpha(0.4)
355
+ fig.patches.append(mpl.patches.CirclePolygon(
356
+ [20, 20], radius=15, alpha=0.6, facecolor='red'))
357
+
358
+
359
+ def test_too_many_figures():
360
+ with pytest.warns(RuntimeWarning):
361
+ for i in range(mpl.rcParams['figure.max_open_warning'] + 1):
362
+ plt.figure()
363
+
364
+
365
+ def test_iterability_axes_argument():
366
+
367
+ # This is a regression test for matplotlib/matplotlib#3196. If one of the
368
+ # arguments returned by _as_mpl_axes defines __getitem__ but is not
369
+ # iterable, this would raise an exception. This is because we check
370
+ # whether the arguments are iterable, and if so we try and convert them
371
+ # to a tuple. However, the ``iterable`` function returns True if
372
+ # __getitem__ is present, but some classes can define __getitem__ without
373
+ # being iterable. The tuple conversion is now done in a try...except in
374
+ # case it fails.
375
+
376
+ class MyAxes(Axes):
377
+ def __init__(self, *args, myclass=None, **kwargs):
378
+ Axes.__init__(self, *args, **kwargs)
379
+
380
+ class MyClass:
381
+
382
+ def __getitem__(self, item):
383
+ if item != 'a':
384
+ raise ValueError("item should be a")
385
+
386
+ def _as_mpl_axes(self):
387
+ return MyAxes, {'myclass': self}
388
+
389
+ fig = plt.figure()
390
+ fig.add_subplot(1, 1, 1, projection=MyClass())
391
+ plt.close(fig)
392
+
393
+
394
+ def test_set_fig_size():
395
+ fig = plt.figure()
396
+
397
+ # check figwidth
398
+ fig.set_figwidth(5)
399
+ assert fig.get_figwidth() == 5
400
+
401
+ # check figheight
402
+ fig.set_figheight(1)
403
+ assert fig.get_figheight() == 1
404
+
405
+ # check using set_size_inches
406
+ fig.set_size_inches(2, 4)
407
+ assert fig.get_figwidth() == 2
408
+ assert fig.get_figheight() == 4
409
+
410
+ # check using tuple to first argument
411
+ fig.set_size_inches((1, 3))
412
+ assert fig.get_figwidth() == 1
413
+ assert fig.get_figheight() == 3
414
+
415
+
416
+ def test_axes_remove():
417
+ fig, axs = plt.subplots(2, 2)
418
+ axs[-1, -1].remove()
419
+ for ax in axs.ravel()[:-1]:
420
+ assert ax in fig.axes
421
+ assert axs[-1, -1] not in fig.axes
422
+ assert len(fig.axes) == 3
423
+
424
+
425
+ def test_figaspect():
426
+ w, h = plt.figaspect(np.float64(2) / np.float64(1))
427
+ assert h / w == 2
428
+ w, h = plt.figaspect(2)
429
+ assert h / w == 2
430
+ w, h = plt.figaspect(np.zeros((1, 2)))
431
+ assert h / w == 0.5
432
+ w, h = plt.figaspect(np.zeros((2, 2)))
433
+ assert h / w == 1
434
+
435
+
436
+ @pytest.mark.parametrize('which', ['both', 'major', 'minor'])
437
+ def test_autofmt_xdate(which):
438
+ date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013',
439
+ '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013',
440
+ '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013']
441
+
442
+ time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00',
443
+ '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00',
444
+ '16:56:00', '16:57:00']
445
+
446
+ angle = 60
447
+ minors = [1, 2, 3, 4, 5, 6, 7]
448
+
449
+ x = mdates.datestr2num(date)
450
+ y = mdates.datestr2num(time)
451
+
452
+ fig, ax = plt.subplots()
453
+
454
+ ax.plot(x, y)
455
+ ax.yaxis_date()
456
+ ax.xaxis_date()
457
+
458
+ ax.xaxis.set_minor_locator(AutoMinorLocator(2))
459
+ with warnings.catch_warnings():
460
+ warnings.filterwarnings(
461
+ 'ignore',
462
+ 'FixedFormatter should only be used together with FixedLocator')
463
+ ax.xaxis.set_minor_formatter(FixedFormatter(minors))
464
+
465
+ fig.autofmt_xdate(0.2, angle, 'right', which)
466
+
467
+ if which in ('both', 'major'):
468
+ for label in fig.axes[0].get_xticklabels(False, 'major'):
469
+ assert int(label.get_rotation()) == angle
470
+
471
+ if which in ('both', 'minor'):
472
+ for label in fig.axes[0].get_xticklabels(True, 'minor'):
473
+ assert int(label.get_rotation()) == angle
474
+
475
+
476
+ @mpl.style.context('default')
477
+ def test_change_dpi():
478
+ fig = plt.figure(figsize=(4, 4))
479
+ fig.draw_without_rendering()
480
+ assert fig.canvas.renderer.height == 400
481
+ assert fig.canvas.renderer.width == 400
482
+ fig.dpi = 50
483
+ fig.draw_without_rendering()
484
+ assert fig.canvas.renderer.height == 200
485
+ assert fig.canvas.renderer.width == 200
486
+
487
+
488
+ @pytest.mark.parametrize('width, height', [
489
+ (1, np.nan),
490
+ (-1, 1),
491
+ (np.inf, 1)
492
+ ])
493
+ def test_invalid_figure_size(width, height):
494
+ with pytest.raises(ValueError):
495
+ plt.figure(figsize=(width, height))
496
+
497
+ fig = plt.figure()
498
+ with pytest.raises(ValueError):
499
+ fig.set_size_inches(width, height)
500
+
501
+
502
+ def test_invalid_figure_add_axes():
503
+ fig = plt.figure()
504
+ with pytest.raises(TypeError,
505
+ match="missing 1 required positional argument: 'rect'"):
506
+ fig.add_axes()
507
+
508
+ with pytest.raises(ValueError):
509
+ fig.add_axes((.1, .1, .5, np.nan))
510
+
511
+ with pytest.raises(TypeError, match="multiple values for argument 'rect'"):
512
+ fig.add_axes([0, 0, 1, 1], rect=[0, 0, 1, 1])
513
+
514
+ fig2, ax = plt.subplots()
515
+ with pytest.raises(ValueError,
516
+ match="The Axes must have been created in the present "
517
+ "figure"):
518
+ fig.add_axes(ax)
519
+
520
+ fig2.delaxes(ax)
521
+ with pytest.warns(mpl.MatplotlibDeprecationWarning,
522
+ match="Passing more than one positional argument"):
523
+ fig2.add_axes(ax, "extra positional argument")
524
+
525
+ with pytest.warns(mpl.MatplotlibDeprecationWarning,
526
+ match="Passing more than one positional argument"):
527
+ fig.add_axes([0, 0, 1, 1], "extra positional argument")
528
+
529
+
530
+ def test_subplots_shareax_loglabels():
531
+ fig, axs = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=False)
532
+ for ax in axs.flat:
533
+ ax.plot([10, 20, 30], [10, 20, 30])
534
+
535
+ ax.set_yscale("log")
536
+ ax.set_xscale("log")
537
+
538
+ for ax in axs[0, :]:
539
+ assert 0 == len(ax.xaxis.get_ticklabels(which='both'))
540
+
541
+ for ax in axs[1, :]:
542
+ assert 0 < len(ax.xaxis.get_ticklabels(which='both'))
543
+
544
+ for ax in axs[:, 1]:
545
+ assert 0 == len(ax.yaxis.get_ticklabels(which='both'))
546
+
547
+ for ax in axs[:, 0]:
548
+ assert 0 < len(ax.yaxis.get_ticklabels(which='both'))
549
+
550
+
551
+ def test_savefig():
552
+ fig = plt.figure()
553
+ msg = r"savefig\(\) takes 2 positional arguments but 3 were given"
554
+ with pytest.raises(TypeError, match=msg):
555
+ fig.savefig("fname1.png", "fname2.png")
556
+
557
+
558
+ def test_savefig_warns():
559
+ fig = plt.figure()
560
+ for format in ['png', 'pdf', 'svg', 'tif', 'jpg']:
561
+ with pytest.raises(TypeError):
562
+ fig.savefig(io.BytesIO(), format=format, non_existent_kwarg=True)
563
+
564
+
565
+ def test_savefig_backend():
566
+ fig = plt.figure()
567
+ # Intentionally use an invalid module name.
568
+ with pytest.raises(ModuleNotFoundError, match="No module named '@absent'"):
569
+ fig.savefig("test", backend="module://@absent")
570
+ with pytest.raises(ValueError,
571
+ match="The 'pdf' backend does not support png output"):
572
+ fig.savefig("test.png", backend="pdf")
573
+
574
+
575
+ @pytest.mark.parametrize('backend', [
576
+ pytest.param('Agg', marks=[pytest.mark.backend('Agg')]),
577
+ pytest.param('Cairo', marks=[pytest.mark.backend('Cairo')]),
578
+ ])
579
+ def test_savefig_pixel_ratio(backend):
580
+ fig, ax = plt.subplots()
581
+ ax.plot([1, 2, 3])
582
+ with io.BytesIO() as buf:
583
+ fig.savefig(buf, format='png')
584
+ ratio1 = Image.open(buf)
585
+ ratio1.load()
586
+
587
+ fig, ax = plt.subplots()
588
+ ax.plot([1, 2, 3])
589
+ fig.canvas._set_device_pixel_ratio(2)
590
+ with io.BytesIO() as buf:
591
+ fig.savefig(buf, format='png')
592
+ ratio2 = Image.open(buf)
593
+ ratio2.load()
594
+
595
+ assert ratio1 == ratio2
596
+
597
+
598
+ def test_savefig_preserve_layout_engine():
599
+ fig = plt.figure(layout='compressed')
600
+ fig.savefig(io.BytesIO(), bbox_inches='tight')
601
+
602
+ assert fig.get_layout_engine()._compress
603
+
604
+
605
+ def test_savefig_locate_colorbar():
606
+ fig, ax = plt.subplots()
607
+ pc = ax.pcolormesh(np.random.randn(2, 2))
608
+ cbar = fig.colorbar(pc, aspect=40)
609
+ fig.savefig(io.BytesIO(), bbox_inches=mpl.transforms.Bbox([[0, 0], [4, 4]]))
610
+
611
+ # Check that an aspect ratio has been applied.
612
+ assert (cbar.ax.get_position(original=True).bounds !=
613
+ cbar.ax.get_position(original=False).bounds)
614
+
615
+
616
+ @mpl.rc_context({"savefig.transparent": True})
617
+ @check_figures_equal(extensions=["png"])
618
+ def test_savefig_transparent(fig_test, fig_ref):
619
+ # create two transparent subfigures with corresponding transparent inset
620
+ # axes. the entire background of the image should be transparent.
621
+ gs1 = fig_test.add_gridspec(3, 3, left=0.05, wspace=0.05)
622
+ f1 = fig_test.add_subfigure(gs1[:, :])
623
+ f2 = f1.add_subfigure(gs1[0, 0])
624
+
625
+ ax12 = f2.add_subplot(gs1[:, :])
626
+
627
+ ax1 = f1.add_subplot(gs1[:-1, :])
628
+ iax1 = ax1.inset_axes([.1, .2, .3, .4])
629
+ iax2 = iax1.inset_axes([.1, .2, .3, .4])
630
+
631
+ ax2 = fig_test.add_subplot(gs1[-1, :-1])
632
+ ax3 = fig_test.add_subplot(gs1[-1, -1])
633
+
634
+ for ax in [ax12, ax1, iax1, iax2, ax2, ax3]:
635
+ ax.set(xticks=[], yticks=[])
636
+ ax.spines[:].set_visible(False)
637
+
638
+
639
+ def test_figure_repr():
640
+ fig = plt.figure(figsize=(10, 20), dpi=10)
641
+ assert repr(fig) == "<Figure size 100x200 with 0 Axes>"
642
+
643
+
644
+ def test_valid_layouts():
645
+ fig = Figure(layout=None)
646
+ assert not fig.get_tight_layout()
647
+ assert not fig.get_constrained_layout()
648
+
649
+ fig = Figure(layout='tight')
650
+ assert fig.get_tight_layout()
651
+ assert not fig.get_constrained_layout()
652
+
653
+ fig = Figure(layout='constrained')
654
+ assert not fig.get_tight_layout()
655
+ assert fig.get_constrained_layout()
656
+
657
+
658
+ def test_invalid_layouts():
659
+ fig, ax = plt.subplots(layout="constrained")
660
+ with pytest.warns(UserWarning):
661
+ # this should warn,
662
+ fig.subplots_adjust(top=0.8)
663
+ assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)
664
+
665
+ # Using layout + (tight|constrained)_layout warns, but the former takes
666
+ # precedence.
667
+ wst = "The Figure parameters 'layout' and 'tight_layout'"
668
+ with pytest.warns(UserWarning, match=wst):
669
+ fig = Figure(layout='tight', tight_layout=False)
670
+ assert isinstance(fig.get_layout_engine(), TightLayoutEngine)
671
+ wst = "The Figure parameters 'layout' and 'constrained_layout'"
672
+ with pytest.warns(UserWarning, match=wst):
673
+ fig = Figure(layout='constrained', constrained_layout=False)
674
+ assert not isinstance(fig.get_layout_engine(), TightLayoutEngine)
675
+ assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)
676
+
677
+ with pytest.raises(ValueError,
678
+ match="Invalid value for 'layout'"):
679
+ Figure(layout='foobar')
680
+
681
+ # test that layouts can be swapped if no colorbar:
682
+ fig, ax = plt.subplots(layout="constrained")
683
+ fig.set_layout_engine("tight")
684
+ assert isinstance(fig.get_layout_engine(), TightLayoutEngine)
685
+ fig.set_layout_engine("constrained")
686
+ assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine)
687
+
688
+ # test that layouts cannot be swapped if there is a colorbar:
689
+ fig, ax = plt.subplots(layout="constrained")
690
+ pc = ax.pcolormesh(np.random.randn(2, 2))
691
+ fig.colorbar(pc)
692
+ with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
693
+ fig.set_layout_engine("tight")
694
+ fig.set_layout_engine("none")
695
+ with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
696
+ fig.set_layout_engine("tight")
697
+
698
+ fig, ax = plt.subplots(layout="tight")
699
+ pc = ax.pcolormesh(np.random.randn(2, 2))
700
+ fig.colorbar(pc)
701
+ with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
702
+ fig.set_layout_engine("constrained")
703
+ fig.set_layout_engine("none")
704
+ assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine)
705
+
706
+ with pytest.raises(RuntimeError, match='Colorbar layout of new layout'):
707
+ fig.set_layout_engine("constrained")
708
+
709
+
710
+ @check_figures_equal(extensions=["png"])
711
+ def test_tightlayout_autolayout_deconflict(fig_test, fig_ref):
712
+ for fig, autolayout in zip([fig_ref, fig_test], [False, True]):
713
+ with mpl.rc_context({'figure.autolayout': autolayout}):
714
+ axes = fig.subplots(ncols=2)
715
+ fig.tight_layout(w_pad=10)
716
+ assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine)
717
+
718
+
719
+ @pytest.mark.parametrize('layout', ['constrained', 'compressed'])
720
+ def test_layout_change_warning(layout):
721
+ """
722
+ Raise a warning when a previously assigned layout changes to tight using
723
+ plt.tight_layout().
724
+ """
725
+ fig, ax = plt.subplots(layout=layout)
726
+ with pytest.warns(UserWarning, match='The figure layout has changed to'):
727
+ plt.tight_layout()
728
+
729
+
730
+ def test_repeated_tightlayout():
731
+ fig = Figure()
732
+ fig.tight_layout()
733
+ # subsequent calls should not warn
734
+ fig.tight_layout()
735
+ fig.tight_layout()
736
+
737
+
738
+ @check_figures_equal(extensions=["png", "pdf"])
739
+ def test_add_artist(fig_test, fig_ref):
740
+ fig_test.dpi = 100
741
+ fig_ref.dpi = 100
742
+
743
+ fig_test.subplots()
744
+ l1 = plt.Line2D([.2, .7], [.7, .7], gid='l1')
745
+ l2 = plt.Line2D([.2, .7], [.8, .8], gid='l2')
746
+ r1 = plt.Circle((20, 20), 100, transform=None, gid='C1')
747
+ r2 = plt.Circle((.7, .5), .05, gid='C2')
748
+ r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans,
749
+ facecolor='crimson', gid='C3')
750
+ for a in [l1, l2, r1, r2, r3]:
751
+ fig_test.add_artist(a)
752
+ l2.remove()
753
+
754
+ ax2 = fig_ref.subplots()
755
+ l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure,
756
+ gid='l1', zorder=21)
757
+ r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20,
758
+ gid='C1')
759
+ r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure, gid='C2',
760
+ zorder=20)
761
+ r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans,
762
+ facecolor='crimson', clip_on=False, zorder=20, gid='C3')
763
+ for a in [l1, r1, r2, r3]:
764
+ ax2.add_artist(a)
765
+
766
+
767
+ @pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
768
+ def test_fspath(fmt, tmp_path):
769
+ out = tmp_path / f"test.{fmt}"
770
+ plt.savefig(out)
771
+ with out.open("rb") as file:
772
+ # All the supported formats include the format name (case-insensitive)
773
+ # in the first 100 bytes.
774
+ assert fmt.encode("ascii") in file.read(100).lower()
775
+
776
+
777
+ def test_tightbbox():
778
+ fig, ax = plt.subplots()
779
+ ax.set_xlim(0, 1)
780
+ t = ax.text(1., 0.5, 'This dangles over end')
781
+ renderer = fig.canvas.get_renderer()
782
+ x1Nom0 = 9.035 # inches
783
+ assert abs(t.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
784
+ assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
785
+ assert abs(fig.get_tightbbox(renderer).x1 - x1Nom0) < 0.05
786
+ assert abs(fig.get_tightbbox(renderer).x0 - 0.679) < 0.05
787
+ # now exclude t from the tight bbox so now the bbox is quite a bit
788
+ # smaller
789
+ t.set_in_layout(False)
790
+ x1Nom = 7.333
791
+ assert abs(ax.get_tightbbox(renderer).x1 - x1Nom * fig.dpi) < 2
792
+ assert abs(fig.get_tightbbox(renderer).x1 - x1Nom) < 0.05
793
+
794
+ t.set_in_layout(True)
795
+ x1Nom = 7.333
796
+ assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2
797
+ # test bbox_extra_artists method...
798
+ assert abs(ax.get_tightbbox(renderer, bbox_extra_artists=[]).x1
799
+ - x1Nom * fig.dpi) < 2
800
+
801
+
802
+ def test_axes_removal():
803
+ # Check that units can set the formatter after an Axes removal
804
+ fig, axs = plt.subplots(1, 2, sharex=True)
805
+ axs[1].remove()
806
+ axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])
807
+ assert isinstance(axs[0].xaxis.get_major_formatter(),
808
+ mdates.AutoDateFormatter)
809
+
810
+ # Check that manually setting the formatter, then removing Axes keeps
811
+ # the set formatter.
812
+ fig, axs = plt.subplots(1, 2, sharex=True)
813
+ axs[1].xaxis.set_major_formatter(ScalarFormatter())
814
+ axs[1].remove()
815
+ axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1])
816
+ assert isinstance(axs[0].xaxis.get_major_formatter(),
817
+ ScalarFormatter)
818
+
819
+
820
+ def test_removed_axis():
821
+ # Simple smoke test to make sure removing a shared axis works
822
+ fig, axs = plt.subplots(2, sharex=True)
823
+ axs[0].remove()
824
+ fig.canvas.draw()
825
+
826
+
827
+ @pytest.mark.parametrize('clear_meth', ['clear', 'clf'])
828
+ def test_figure_clear(clear_meth):
829
+ # we test the following figure clearing scenarios:
830
+ fig = plt.figure()
831
+
832
+ # a) an empty figure
833
+ fig.clear()
834
+ assert fig.axes == []
835
+
836
+ # b) a figure with a single unnested axes
837
+ ax = fig.add_subplot(111)
838
+ getattr(fig, clear_meth)()
839
+ assert fig.axes == []
840
+
841
+ # c) a figure multiple unnested axes
842
+ axes = [fig.add_subplot(2, 1, i+1) for i in range(2)]
843
+ getattr(fig, clear_meth)()
844
+ assert fig.axes == []
845
+
846
+ # d) a figure with a subfigure
847
+ gs = fig.add_gridspec(ncols=2, nrows=1)
848
+ subfig = fig.add_subfigure(gs[0])
849
+ subaxes = subfig.add_subplot(111)
850
+ getattr(fig, clear_meth)()
851
+ assert subfig not in fig.subfigs
852
+ assert fig.axes == []
853
+
854
+ # e) a figure with a subfigure and a subplot
855
+ subfig = fig.add_subfigure(gs[0])
856
+ subaxes = subfig.add_subplot(111)
857
+ mainaxes = fig.add_subplot(gs[1])
858
+
859
+ # e.1) removing just the axes leaves the subplot
860
+ mainaxes.remove()
861
+ assert fig.axes == [subaxes]
862
+
863
+ # e.2) removing just the subaxes leaves the subplot
864
+ # and subfigure
865
+ mainaxes = fig.add_subplot(gs[1])
866
+ subaxes.remove()
867
+ assert fig.axes == [mainaxes]
868
+ assert subfig in fig.subfigs
869
+
870
+ # e.3) clearing the subfigure leaves the subplot
871
+ subaxes = subfig.add_subplot(111)
872
+ assert mainaxes in fig.axes
873
+ assert subaxes in fig.axes
874
+ getattr(subfig, clear_meth)()
875
+ assert subfig in fig.subfigs
876
+ assert subaxes not in subfig.axes
877
+ assert subaxes not in fig.axes
878
+ assert mainaxes in fig.axes
879
+
880
+ # e.4) clearing the whole thing
881
+ subaxes = subfig.add_subplot(111)
882
+ getattr(fig, clear_meth)()
883
+ assert fig.axes == []
884
+ assert fig.subfigs == []
885
+
886
+ # f) multiple subfigures
887
+ subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]]
888
+ subaxes = [sfig.add_subplot(111) for sfig in subfigs]
889
+ assert all(ax in fig.axes for ax in subaxes)
890
+ assert all(sfig in fig.subfigs for sfig in subfigs)
891
+
892
+ # f.1) clearing only one subfigure
893
+ getattr(subfigs[0], clear_meth)()
894
+ assert subaxes[0] not in fig.axes
895
+ assert subaxes[1] in fig.axes
896
+ assert subfigs[1] in fig.subfigs
897
+
898
+ # f.2) clearing the whole thing
899
+ getattr(subfigs[1], clear_meth)()
900
+ subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]]
901
+ subaxes = [sfig.add_subplot(111) for sfig in subfigs]
902
+ assert all(ax in fig.axes for ax in subaxes)
903
+ assert all(sfig in fig.subfigs for sfig in subfigs)
904
+ getattr(fig, clear_meth)()
905
+ assert fig.subfigs == []
906
+ assert fig.axes == []
907
+
908
+
909
+ def test_clf_not_redefined():
910
+ for klass in FigureBase.__subclasses__():
911
+ # check that subclasses do not get redefined in our Figure subclasses
912
+ assert 'clf' not in klass.__dict__
913
+
914
+
915
+ @mpl.style.context('mpl20')
916
+ def test_picking_does_not_stale():
917
+ fig, ax = plt.subplots()
918
+ ax.scatter([0], [0], [1000], picker=True)
919
+ fig.canvas.draw()
920
+ assert not fig.stale
921
+
922
+ mouse_event = SimpleNamespace(x=ax.bbox.x0 + ax.bbox.width / 2,
923
+ y=ax.bbox.y0 + ax.bbox.height / 2,
924
+ inaxes=ax, guiEvent=None)
925
+ fig.pick(mouse_event)
926
+ assert not fig.stale
927
+
928
+
929
+ def test_add_subplot_twotuple():
930
+ fig = plt.figure()
931
+ ax1 = fig.add_subplot(3, 2, (3, 5))
932
+ assert ax1.get_subplotspec().rowspan == range(1, 3)
933
+ assert ax1.get_subplotspec().colspan == range(0, 1)
934
+ ax2 = fig.add_subplot(3, 2, (4, 6))
935
+ assert ax2.get_subplotspec().rowspan == range(1, 3)
936
+ assert ax2.get_subplotspec().colspan == range(1, 2)
937
+ ax3 = fig.add_subplot(3, 2, (3, 6))
938
+ assert ax3.get_subplotspec().rowspan == range(1, 3)
939
+ assert ax3.get_subplotspec().colspan == range(0, 2)
940
+ ax4 = fig.add_subplot(3, 2, (4, 5))
941
+ assert ax4.get_subplotspec().rowspan == range(1, 3)
942
+ assert ax4.get_subplotspec().colspan == range(0, 2)
943
+ with pytest.raises(IndexError):
944
+ fig.add_subplot(3, 2, (6, 3))
945
+
946
+
947
+ @image_comparison(['tightbbox_box_aspect.svg'], style='mpl20',
948
+ savefig_kwarg={'bbox_inches': 'tight',
949
+ 'facecolor': 'teal'},
950
+ remove_text=True)
951
+ def test_tightbbox_box_aspect():
952
+ fig = plt.figure()
953
+ gs = fig.add_gridspec(1, 2)
954
+ ax1 = fig.add_subplot(gs[0, 0])
955
+ ax2 = fig.add_subplot(gs[0, 1], projection='3d')
956
+ ax1.set_box_aspect(.5)
957
+ ax2.set_box_aspect((2, 1, 1))
958
+
959
+
960
+ @check_figures_equal(extensions=["svg", "pdf", "eps", "png"])
961
+ def test_animated_with_canvas_change(fig_test, fig_ref):
962
+ ax_ref = fig_ref.subplots()
963
+ ax_ref.plot(range(5))
964
+
965
+ ax_test = fig_test.subplots()
966
+ ax_test.plot(range(5), animated=True)
967
+
968
+
969
+ class TestSubplotMosaic:
970
+ @check_figures_equal(extensions=["png"])
971
+ @pytest.mark.parametrize(
972
+ "x", [
973
+ [["A", "A", "B"], ["C", "D", "B"]],
974
+ [[1, 1, 2], [3, 4, 2]],
975
+ (("A", "A", "B"), ("C", "D", "B")),
976
+ ((1, 1, 2), (3, 4, 2))
977
+ ]
978
+ )
979
+ def test_basic(self, fig_test, fig_ref, x):
980
+ grid_axes = fig_test.subplot_mosaic(x)
981
+
982
+ for k, ax in grid_axes.items():
983
+ ax.set_title(k)
984
+
985
+ labels = sorted(np.unique(x))
986
+
987
+ assert len(labels) == len(grid_axes)
988
+
989
+ gs = fig_ref.add_gridspec(2, 3)
990
+ axA = fig_ref.add_subplot(gs[:1, :2])
991
+ axA.set_title(labels[0])
992
+
993
+ axB = fig_ref.add_subplot(gs[:, 2])
994
+ axB.set_title(labels[1])
995
+
996
+ axC = fig_ref.add_subplot(gs[1, 0])
997
+ axC.set_title(labels[2])
998
+
999
+ axD = fig_ref.add_subplot(gs[1, 1])
1000
+ axD.set_title(labels[3])
1001
+
1002
+ @check_figures_equal(extensions=["png"])
1003
+ def test_all_nested(self, fig_test, fig_ref):
1004
+ x = [["A", "B"], ["C", "D"]]
1005
+ y = [["E", "F"], ["G", "H"]]
1006
+
1007
+ fig_ref.set_layout_engine("constrained")
1008
+ fig_test.set_layout_engine("constrained")
1009
+
1010
+ grid_axes = fig_test.subplot_mosaic([[x, y]])
1011
+ for ax in grid_axes.values():
1012
+ ax.set_title(ax.get_label())
1013
+
1014
+ gs = fig_ref.add_gridspec(1, 2)
1015
+ gs_left = gs[0, 0].subgridspec(2, 2)
1016
+ for j, r in enumerate(x):
1017
+ for k, label in enumerate(r):
1018
+ fig_ref.add_subplot(gs_left[j, k]).set_title(label)
1019
+
1020
+ gs_right = gs[0, 1].subgridspec(2, 2)
1021
+ for j, r in enumerate(y):
1022
+ for k, label in enumerate(r):
1023
+ fig_ref.add_subplot(gs_right[j, k]).set_title(label)
1024
+
1025
+ @check_figures_equal(extensions=["png"])
1026
+ def test_nested(self, fig_test, fig_ref):
1027
+
1028
+ fig_ref.set_layout_engine("constrained")
1029
+ fig_test.set_layout_engine("constrained")
1030
+
1031
+ x = [["A", "B"], ["C", "D"]]
1032
+
1033
+ y = [["F"], [x]]
1034
+
1035
+ grid_axes = fig_test.subplot_mosaic(y)
1036
+
1037
+ for k, ax in grid_axes.items():
1038
+ ax.set_title(k)
1039
+
1040
+ gs = fig_ref.add_gridspec(2, 1)
1041
+
1042
+ gs_n = gs[1, 0].subgridspec(2, 2)
1043
+
1044
+ axA = fig_ref.add_subplot(gs_n[0, 0])
1045
+ axA.set_title("A")
1046
+
1047
+ axB = fig_ref.add_subplot(gs_n[0, 1])
1048
+ axB.set_title("B")
1049
+
1050
+ axC = fig_ref.add_subplot(gs_n[1, 0])
1051
+ axC.set_title("C")
1052
+
1053
+ axD = fig_ref.add_subplot(gs_n[1, 1])
1054
+ axD.set_title("D")
1055
+
1056
+ axF = fig_ref.add_subplot(gs[0, 0])
1057
+ axF.set_title("F")
1058
+
1059
+ @check_figures_equal(extensions=["png"])
1060
+ def test_nested_tuple(self, fig_test, fig_ref):
1061
+ x = [["A", "B", "B"], ["C", "C", "D"]]
1062
+ xt = (("A", "B", "B"), ("C", "C", "D"))
1063
+
1064
+ fig_ref.subplot_mosaic([["F"], [x]])
1065
+ fig_test.subplot_mosaic([["F"], [xt]])
1066
+
1067
+ def test_nested_width_ratios(self):
1068
+ x = [["A", [["B"],
1069
+ ["C"]]]]
1070
+ width_ratios = [2, 1]
1071
+
1072
+ fig, axd = plt.subplot_mosaic(x, width_ratios=width_ratios)
1073
+
1074
+ assert axd["A"].get_gridspec().get_width_ratios() == width_ratios
1075
+ assert axd["B"].get_gridspec().get_width_ratios() != width_ratios
1076
+
1077
+ def test_nested_height_ratios(self):
1078
+ x = [["A", [["B"],
1079
+ ["C"]]], ["D", "D"]]
1080
+ height_ratios = [1, 2]
1081
+
1082
+ fig, axd = plt.subplot_mosaic(x, height_ratios=height_ratios)
1083
+
1084
+ assert axd["D"].get_gridspec().get_height_ratios() == height_ratios
1085
+ assert axd["B"].get_gridspec().get_height_ratios() != height_ratios
1086
+
1087
+ @check_figures_equal(extensions=["png"])
1088
+ @pytest.mark.parametrize(
1089
+ "x, empty_sentinel",
1090
+ [
1091
+ ([["A", None], [None, "B"]], None),
1092
+ ([["A", "."], [".", "B"]], "SKIP"),
1093
+ ([["A", 0], [0, "B"]], 0),
1094
+ ([[1, None], [None, 2]], None),
1095
+ ([[1, "."], [".", 2]], "SKIP"),
1096
+ ([[1, 0], [0, 2]], 0),
1097
+ ],
1098
+ )
1099
+ def test_empty(self, fig_test, fig_ref, x, empty_sentinel):
1100
+ if empty_sentinel != "SKIP":
1101
+ kwargs = {"empty_sentinel": empty_sentinel}
1102
+ else:
1103
+ kwargs = {}
1104
+ grid_axes = fig_test.subplot_mosaic(x, **kwargs)
1105
+
1106
+ for k, ax in grid_axes.items():
1107
+ ax.set_title(k)
1108
+
1109
+ labels = sorted(
1110
+ {name for row in x for name in row} - {empty_sentinel, "."}
1111
+ )
1112
+
1113
+ assert len(labels) == len(grid_axes)
1114
+
1115
+ gs = fig_ref.add_gridspec(2, 2)
1116
+ axA = fig_ref.add_subplot(gs[0, 0])
1117
+ axA.set_title(labels[0])
1118
+
1119
+ axB = fig_ref.add_subplot(gs[1, 1])
1120
+ axB.set_title(labels[1])
1121
+
1122
+ def test_fail_list_of_str(self):
1123
+ with pytest.raises(ValueError, match='must be 2D'):
1124
+ plt.subplot_mosaic(['foo', 'bar'])
1125
+ with pytest.raises(ValueError, match='must be 2D'):
1126
+ plt.subplot_mosaic(['foo'])
1127
+ with pytest.raises(ValueError, match='must be 2D'):
1128
+ plt.subplot_mosaic([['foo', ('bar',)]])
1129
+ with pytest.raises(ValueError, match='must be 2D'):
1130
+ plt.subplot_mosaic([['a', 'b'], [('a', 'b'), 'c']])
1131
+
1132
+ @check_figures_equal(extensions=["png"])
1133
+ @pytest.mark.parametrize("subplot_kw", [{}, {"projection": "polar"}, None])
1134
+ def test_subplot_kw(self, fig_test, fig_ref, subplot_kw):
1135
+ x = [[1, 2]]
1136
+ grid_axes = fig_test.subplot_mosaic(x, subplot_kw=subplot_kw)
1137
+ subplot_kw = subplot_kw or {}
1138
+
1139
+ gs = fig_ref.add_gridspec(1, 2)
1140
+ axA = fig_ref.add_subplot(gs[0, 0], **subplot_kw)
1141
+
1142
+ axB = fig_ref.add_subplot(gs[0, 1], **subplot_kw)
1143
+
1144
+ @check_figures_equal(extensions=["png"])
1145
+ @pytest.mark.parametrize("multi_value", ['BC', tuple('BC')])
1146
+ def test_per_subplot_kw(self, fig_test, fig_ref, multi_value):
1147
+ x = 'AB;CD'
1148
+ grid_axes = fig_test.subplot_mosaic(
1149
+ x,
1150
+ subplot_kw={'facecolor': 'red'},
1151
+ per_subplot_kw={
1152
+ 'D': {'facecolor': 'blue'},
1153
+ multi_value: {'facecolor': 'green'},
1154
+ }
1155
+ )
1156
+
1157
+ gs = fig_ref.add_gridspec(2, 2)
1158
+ for color, spec in zip(['red', 'green', 'green', 'blue'], gs):
1159
+ fig_ref.add_subplot(spec, facecolor=color)
1160
+
1161
+ def test_string_parser(self):
1162
+ normalize = Figure._normalize_grid_string
1163
+
1164
+ assert normalize('ABC') == [['A', 'B', 'C']]
1165
+ assert normalize('AB;CC') == [['A', 'B'], ['C', 'C']]
1166
+ assert normalize('AB;CC;DE') == [['A', 'B'], ['C', 'C'], ['D', 'E']]
1167
+ assert normalize("""
1168
+ ABC
1169
+ """) == [['A', 'B', 'C']]
1170
+ assert normalize("""
1171
+ AB
1172
+ CC
1173
+ """) == [['A', 'B'], ['C', 'C']]
1174
+ assert normalize("""
1175
+ AB
1176
+ CC
1177
+ DE
1178
+ """) == [['A', 'B'], ['C', 'C'], ['D', 'E']]
1179
+
1180
+ def test_per_subplot_kw_expander(self):
1181
+ normalize = Figure._norm_per_subplot_kw
1182
+ assert normalize({"A": {}, "B": {}}) == {"A": {}, "B": {}}
1183
+ assert normalize({("A", "B"): {}}) == {"A": {}, "B": {}}
1184
+ with pytest.raises(
1185
+ ValueError, match=f'The key {"B"!r} appears multiple times'
1186
+ ):
1187
+ normalize({("A", "B"): {}, "B": {}})
1188
+ with pytest.raises(
1189
+ ValueError, match=f'The key {"B"!r} appears multiple times'
1190
+ ):
1191
+ normalize({"B": {}, ("A", "B"): {}})
1192
+
1193
+ def test_extra_per_subplot_kw(self):
1194
+ with pytest.raises(
1195
+ ValueError, match=f'The keys {set("B")!r} are in'
1196
+ ):
1197
+ Figure().subplot_mosaic("A", per_subplot_kw={"B": {}})
1198
+
1199
+ @check_figures_equal(extensions=["png"])
1200
+ @pytest.mark.parametrize("str_pattern",
1201
+ ["AAA\nBBB", "\nAAA\nBBB\n", "ABC\nDEF"]
1202
+ )
1203
+ def test_single_str_input(self, fig_test, fig_ref, str_pattern):
1204
+ grid_axes = fig_test.subplot_mosaic(str_pattern)
1205
+
1206
+ grid_axes = fig_ref.subplot_mosaic(
1207
+ [list(ln) for ln in str_pattern.strip().split("\n")]
1208
+ )
1209
+
1210
+ @pytest.mark.parametrize(
1211
+ "x,match",
1212
+ [
1213
+ (
1214
+ [["A", "."], [".", "A"]],
1215
+ (
1216
+ "(?m)we found that the label .A. specifies a "
1217
+ + "non-rectangular or non-contiguous area."
1218
+ ),
1219
+ ),
1220
+ (
1221
+ [["A", "B"], [None, [["A", "B"], ["C", "D"]]]],
1222
+ "There are duplicate keys .* between the outer layout",
1223
+ ),
1224
+ ("AAA\nc\nBBB", "All of the rows must be the same length"),
1225
+ (
1226
+ [["A", [["B", "C"], ["D"]]], ["E", "E"]],
1227
+ "All of the rows must be the same length",
1228
+ ),
1229
+ ],
1230
+ )
1231
+ def test_fail(self, x, match):
1232
+ fig = plt.figure()
1233
+ with pytest.raises(ValueError, match=match):
1234
+ fig.subplot_mosaic(x)
1235
+
1236
+ @check_figures_equal(extensions=["png"])
1237
+ def test_hashable_keys(self, fig_test, fig_ref):
1238
+ fig_test.subplot_mosaic([[object(), object()]])
1239
+ fig_ref.subplot_mosaic([["A", "B"]])
1240
+
1241
+ @pytest.mark.parametrize('str_pattern',
1242
+ ['abc', 'cab', 'bca', 'cba', 'acb', 'bac'])
1243
+ def test_user_order(self, str_pattern):
1244
+ fig = plt.figure()
1245
+ ax_dict = fig.subplot_mosaic(str_pattern)
1246
+ assert list(str_pattern) == list(ax_dict)
1247
+ assert list(fig.axes) == list(ax_dict.values())
1248
+
1249
+ def test_nested_user_order(self):
1250
+ layout = [
1251
+ ["A", [["B", "C"],
1252
+ ["D", "E"]]],
1253
+ ["F", "G"],
1254
+ [".", [["H", [["I"],
1255
+ ["."]]]]]
1256
+ ]
1257
+
1258
+ fig = plt.figure()
1259
+ ax_dict = fig.subplot_mosaic(layout)
1260
+ assert list(ax_dict) == list("ABCDEFGHI")
1261
+ assert list(fig.axes) == list(ax_dict.values())
1262
+
1263
+ def test_share_all(self):
1264
+ layout = [
1265
+ ["A", [["B", "C"],
1266
+ ["D", "E"]]],
1267
+ ["F", "G"],
1268
+ [".", [["H", [["I"],
1269
+ ["."]]]]]
1270
+ ]
1271
+ fig = plt.figure()
1272
+ ax_dict = fig.subplot_mosaic(layout, sharex=True, sharey=True)
1273
+ ax_dict["A"].set(xscale="log", yscale="logit")
1274
+ assert all(ax.get_xscale() == "log" and ax.get_yscale() == "logit"
1275
+ for ax in ax_dict.values())
1276
+
1277
+
1278
+ def test_reused_gridspec():
1279
+ """Test that these all use the same gridspec"""
1280
+ fig = plt.figure()
1281
+ ax1 = fig.add_subplot(3, 2, (3, 5))
1282
+ ax2 = fig.add_subplot(3, 2, 4)
1283
+ ax3 = plt.subplot2grid((3, 2), (2, 1), colspan=2, fig=fig)
1284
+
1285
+ gs1 = ax1.get_subplotspec().get_gridspec()
1286
+ gs2 = ax2.get_subplotspec().get_gridspec()
1287
+ gs3 = ax3.get_subplotspec().get_gridspec()
1288
+
1289
+ assert gs1 == gs2
1290
+ assert gs1 == gs3
1291
+
1292
+
1293
+ @image_comparison(['test_subfigure.png'], style='mpl20',
1294
+ savefig_kwarg={'facecolor': 'teal'})
1295
+ def test_subfigure():
1296
+ np.random.seed(19680801)
1297
+ fig = plt.figure(layout='constrained')
1298
+ sub = fig.subfigures(1, 2)
1299
+
1300
+ axs = sub[0].subplots(2, 2)
1301
+ for ax in axs.flat:
1302
+ pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)
1303
+ sub[0].colorbar(pc, ax=axs)
1304
+ sub[0].suptitle('Left Side')
1305
+ sub[0].set_facecolor('white')
1306
+
1307
+ axs = sub[1].subplots(1, 3)
1308
+ for ax in axs.flat:
1309
+ pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)
1310
+ sub[1].colorbar(pc, ax=axs, location='bottom')
1311
+ sub[1].suptitle('Right Side')
1312
+ sub[1].set_facecolor('white')
1313
+
1314
+ fig.suptitle('Figure suptitle', fontsize='xx-large')
1315
+
1316
+ # below tests for the draw zorder of subfigures.
1317
+ leg = fig.legend(handles=[plt.Line2D([0], [0], label='Line{}'.format(i))
1318
+ for i in range(5)], loc='center')
1319
+ sub[0].set_zorder(leg.get_zorder() - 1)
1320
+ sub[1].set_zorder(leg.get_zorder() + 1)
1321
+
1322
+
1323
+ def test_subfigure_tightbbox():
1324
+ # test that we can get the tightbbox with a subfigure...
1325
+ fig = plt.figure(layout='constrained')
1326
+ sub = fig.subfigures(1, 2)
1327
+
1328
+ np.testing.assert_allclose(
1329
+ fig.get_tightbbox(fig.canvas.get_renderer()).width,
1330
+ 8.0)
1331
+
1332
+
1333
+ def test_subfigure_dpi():
1334
+ fig = plt.figure(dpi=100)
1335
+ sub_fig = fig.subfigures()
1336
+ assert sub_fig.get_dpi() == fig.get_dpi()
1337
+
1338
+ sub_fig.set_dpi(200)
1339
+ assert sub_fig.get_dpi() == 200
1340
+ assert fig.get_dpi() == 200
1341
+
1342
+
1343
+ @image_comparison(['test_subfigure_ss.png'], style='mpl20',
1344
+ savefig_kwarg={'facecolor': 'teal'}, tol=0.02)
1345
+ def test_subfigure_ss():
1346
+ # test assigning the subfigure via subplotspec
1347
+ np.random.seed(19680801)
1348
+ fig = plt.figure(layout='constrained')
1349
+ gs = fig.add_gridspec(1, 2)
1350
+
1351
+ sub = fig.add_subfigure(gs[0], facecolor='pink')
1352
+
1353
+ axs = sub.subplots(2, 2)
1354
+ for ax in axs.flat:
1355
+ pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2)
1356
+ sub.colorbar(pc, ax=axs)
1357
+ sub.suptitle('Left Side')
1358
+
1359
+ ax = fig.add_subplot(gs[1])
1360
+ ax.plot(np.arange(20))
1361
+ ax.set_title('Axes')
1362
+
1363
+ fig.suptitle('Figure suptitle', fontsize='xx-large')
1364
+
1365
+
1366
+ @image_comparison(['test_subfigure_double.png'], style='mpl20',
1367
+ savefig_kwarg={'facecolor': 'teal'})
1368
+ def test_subfigure_double():
1369
+ # test assigning the subfigure via subplotspec
1370
+ np.random.seed(19680801)
1371
+
1372
+ fig = plt.figure(layout='constrained', figsize=(10, 8))
1373
+
1374
+ fig.suptitle('fig')
1375
+
1376
+ subfigs = fig.subfigures(1, 2, wspace=0.07)
1377
+
1378
+ subfigs[0].set_facecolor('coral')
1379
+ subfigs[0].suptitle('subfigs[0]')
1380
+
1381
+ subfigs[1].set_facecolor('coral')
1382
+ subfigs[1].suptitle('subfigs[1]')
1383
+
1384
+ subfigsnest = subfigs[0].subfigures(2, 1, height_ratios=[1, 1.4])
1385
+ subfigsnest[0].suptitle('subfigsnest[0]')
1386
+ subfigsnest[0].set_facecolor('r')
1387
+ axsnest0 = subfigsnest[0].subplots(1, 2, sharey=True)
1388
+ for ax in axsnest0:
1389
+ fontsize = 12
1390
+ pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2.5, vmax=2.5)
1391
+ ax.set_xlabel('x-label', fontsize=fontsize)
1392
+ ax.set_ylabel('y-label', fontsize=fontsize)
1393
+ ax.set_title('Title', fontsize=fontsize)
1394
+ subfigsnest[0].colorbar(pc, ax=axsnest0)
1395
+
1396
+ subfigsnest[1].suptitle('subfigsnest[1]')
1397
+ subfigsnest[1].set_facecolor('g')
1398
+ axsnest1 = subfigsnest[1].subplots(3, 1, sharex=True)
1399
+ for nn, ax in enumerate(axsnest1):
1400
+ ax.set_ylabel(f'ylabel{nn}')
1401
+ subfigsnest[1].supxlabel('supxlabel')
1402
+ subfigsnest[1].supylabel('supylabel')
1403
+
1404
+ axsRight = subfigs[1].subplots(2, 2)
1405
+
1406
+
1407
+ def test_subfigure_spanning():
1408
+ # test that subfigures get laid out properly...
1409
+ fig = plt.figure(constrained_layout=True)
1410
+ gs = fig.add_gridspec(3, 3)
1411
+ sub_figs = [
1412
+ fig.add_subfigure(gs[0, 0]),
1413
+ fig.add_subfigure(gs[0:2, 1]),
1414
+ fig.add_subfigure(gs[2, 1:3]),
1415
+ fig.add_subfigure(gs[0:, 1:])
1416
+ ]
1417
+
1418
+ w = 640
1419
+ h = 480
1420
+ np.testing.assert_allclose(sub_figs[0].bbox.min, [0., h * 2/3])
1421
+ np.testing.assert_allclose(sub_figs[0].bbox.max, [w / 3, h])
1422
+
1423
+ np.testing.assert_allclose(sub_figs[1].bbox.min, [w / 3, h / 3])
1424
+ np.testing.assert_allclose(sub_figs[1].bbox.max, [w * 2/3, h])
1425
+
1426
+ np.testing.assert_allclose(sub_figs[2].bbox.min, [w / 3, 0])
1427
+ np.testing.assert_allclose(sub_figs[2].bbox.max, [w, h / 3])
1428
+
1429
+ # check here that slicing actually works. Last sub_fig
1430
+ # with open slices failed, but only on draw...
1431
+ for i in range(4):
1432
+ sub_figs[i].add_subplot()
1433
+ fig.draw_without_rendering()
1434
+
1435
+
1436
+ @mpl.style.context('mpl20')
1437
+ def test_subfigure_ticks():
1438
+ # This tests a tick-spacing error that only seems applicable
1439
+ # when the subfigures are saved to file. It is very hard to replicate
1440
+ fig = plt.figure(constrained_layout=True, figsize=(10, 3))
1441
+ # create left/right subfigs nested in bottom subfig
1442
+ (subfig_bl, subfig_br) = fig.subfigures(1, 2, wspace=0.01,
1443
+ width_ratios=[7, 2])
1444
+
1445
+ # put ax1-ax3 in gridspec of bottom-left subfig
1446
+ gs = subfig_bl.add_gridspec(nrows=1, ncols=14)
1447
+
1448
+ ax1 = subfig_bl.add_subplot(gs[0, :1])
1449
+ ax1.scatter(x=[-56.46881504821776, 24.179891162109396], y=[1500, 3600])
1450
+
1451
+ ax2 = subfig_bl.add_subplot(gs[0, 1:3], sharey=ax1)
1452
+ ax2.scatter(x=[-126.5357270050049, 94.68456736755368], y=[1500, 3600])
1453
+ ax3 = subfig_bl.add_subplot(gs[0, 3:14], sharey=ax1)
1454
+
1455
+ fig.dpi = 120
1456
+ fig.draw_without_rendering()
1457
+ ticks120 = ax2.get_xticks()
1458
+ fig.dpi = 300
1459
+ fig.draw_without_rendering()
1460
+ ticks300 = ax2.get_xticks()
1461
+ np.testing.assert_allclose(ticks120, ticks300)
1462
+
1463
+
1464
+ @image_comparison(['test_subfigure_scatter_size.png'], style='mpl20',
1465
+ remove_text=True)
1466
+ def test_subfigure_scatter_size():
1467
+ # markers in the left- and right-most subplots should be the same
1468
+ fig = plt.figure()
1469
+ gs = fig.add_gridspec(1, 2)
1470
+ ax0 = fig.add_subplot(gs[1])
1471
+ ax0.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s')
1472
+ ax0.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s')
1473
+
1474
+ sfig = fig.add_subfigure(gs[0])
1475
+ axs = sfig.subplots(1, 2)
1476
+ for ax in [ax0, axs[0]]:
1477
+ ax.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s', color='r')
1478
+ ax.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s', color='g')
1479
+
1480
+
1481
+ def test_subfigure_pdf():
1482
+ fig = plt.figure(layout='constrained')
1483
+ sub_fig = fig.subfigures()
1484
+ ax = sub_fig.add_subplot(111)
1485
+ b = ax.bar(1, 1)
1486
+ ax.bar_label(b)
1487
+ buffer = io.BytesIO()
1488
+ fig.savefig(buffer, format='pdf')
1489
+
1490
+
1491
+ def test_subfigures_wspace_hspace():
1492
+ sub_figs = plt.figure().subfigures(2, 3, hspace=0.5, wspace=1/6.)
1493
+
1494
+ w = 640
1495
+ h = 480
1496
+
1497
+ np.testing.assert_allclose(sub_figs[0, 0].bbox.min, [0., h * 0.6])
1498
+ np.testing.assert_allclose(sub_figs[0, 0].bbox.max, [w * 0.3, h])
1499
+
1500
+ np.testing.assert_allclose(sub_figs[0, 1].bbox.min, [w * 0.35, h * 0.6])
1501
+ np.testing.assert_allclose(sub_figs[0, 1].bbox.max, [w * 0.65, h])
1502
+
1503
+ np.testing.assert_allclose(sub_figs[0, 2].bbox.min, [w * 0.7, h * 0.6])
1504
+ np.testing.assert_allclose(sub_figs[0, 2].bbox.max, [w, h])
1505
+
1506
+ np.testing.assert_allclose(sub_figs[1, 0].bbox.min, [0, 0])
1507
+ np.testing.assert_allclose(sub_figs[1, 0].bbox.max, [w * 0.3, h * 0.4])
1508
+
1509
+ np.testing.assert_allclose(sub_figs[1, 1].bbox.min, [w * 0.35, 0])
1510
+ np.testing.assert_allclose(sub_figs[1, 1].bbox.max, [w * 0.65, h * 0.4])
1511
+
1512
+ np.testing.assert_allclose(sub_figs[1, 2].bbox.min, [w * 0.7, 0])
1513
+ np.testing.assert_allclose(sub_figs[1, 2].bbox.max, [w, h * 0.4])
1514
+
1515
+
1516
+ def test_subfigure_remove():
1517
+ fig = plt.figure()
1518
+ sfs = fig.subfigures(2, 2)
1519
+ sfs[1, 1].remove()
1520
+ assert len(fig.subfigs) == 3
1521
+
1522
+
1523
+ def test_add_subplot_kwargs():
1524
+ # fig.add_subplot() always creates new axes, even if axes kwargs differ.
1525
+ fig = plt.figure()
1526
+ ax = fig.add_subplot(1, 1, 1)
1527
+ ax1 = fig.add_subplot(1, 1, 1)
1528
+ assert ax is not None
1529
+ assert ax1 is not ax
1530
+ plt.close()
1531
+
1532
+ fig = plt.figure()
1533
+ ax = fig.add_subplot(1, 1, 1, projection='polar')
1534
+ ax1 = fig.add_subplot(1, 1, 1, projection='polar')
1535
+ assert ax is not None
1536
+ assert ax1 is not ax
1537
+ plt.close()
1538
+
1539
+ fig = plt.figure()
1540
+ ax = fig.add_subplot(1, 1, 1, projection='polar')
1541
+ ax1 = fig.add_subplot(1, 1, 1)
1542
+ assert ax is not None
1543
+ assert ax1.name == 'rectilinear'
1544
+ assert ax1 is not ax
1545
+ plt.close()
1546
+
1547
+
1548
+ def test_add_axes_kwargs():
1549
+ # fig.add_axes() always creates new axes, even if axes kwargs differ.
1550
+ fig = plt.figure()
1551
+ ax = fig.add_axes([0, 0, 1, 1])
1552
+ ax1 = fig.add_axes([0, 0, 1, 1])
1553
+ assert ax is not None
1554
+ assert ax1 is not ax
1555
+ plt.close()
1556
+
1557
+ fig = plt.figure()
1558
+ ax = fig.add_axes([0, 0, 1, 1], projection='polar')
1559
+ ax1 = fig.add_axes([0, 0, 1, 1], projection='polar')
1560
+ assert ax is not None
1561
+ assert ax1 is not ax
1562
+ plt.close()
1563
+
1564
+ fig = plt.figure()
1565
+ ax = fig.add_axes([0, 0, 1, 1], projection='polar')
1566
+ ax1 = fig.add_axes([0, 0, 1, 1])
1567
+ assert ax is not None
1568
+ assert ax1.name == 'rectilinear'
1569
+ assert ax1 is not ax
1570
+ plt.close()
1571
+
1572
+
1573
+ def test_ginput(recwarn): # recwarn undoes warn filters at exit.
1574
+ warnings.filterwarnings("ignore", "cannot show the figure")
1575
+ fig, ax = plt.subplots()
1576
+ trans = ax.transData.transform
1577
+
1578
+ def single_press():
1579
+ MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process()
1580
+
1581
+ Timer(.1, single_press).start()
1582
+ assert fig.ginput() == [(.1, .2)]
1583
+
1584
+ def multi_presses():
1585
+ MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process()
1586
+ KeyEvent("key_press_event", fig.canvas, "backspace")._process()
1587
+ MouseEvent("button_press_event", fig.canvas, *trans((.3, .4)), 1)._process()
1588
+ MouseEvent("button_press_event", fig.canvas, *trans((.5, .6)), 1)._process()
1589
+ MouseEvent("button_press_event", fig.canvas, *trans((0, 0)), 2)._process()
1590
+
1591
+ Timer(.1, multi_presses).start()
1592
+ np.testing.assert_allclose(fig.ginput(3), [(.3, .4), (.5, .6)])
1593
+
1594
+
1595
+ def test_waitforbuttonpress(recwarn): # recwarn undoes warn filters at exit.
1596
+ warnings.filterwarnings("ignore", "cannot show the figure")
1597
+ fig = plt.figure()
1598
+ assert fig.waitforbuttonpress(timeout=.1) is None
1599
+ Timer(.1, KeyEvent("key_press_event", fig.canvas, "z")._process).start()
1600
+ assert fig.waitforbuttonpress() is True
1601
+ Timer(.1, MouseEvent("button_press_event", fig.canvas, 0, 0, 1)._process).start()
1602
+ assert fig.waitforbuttonpress() is False
1603
+
1604
+
1605
+ def test_kwargs_pass():
1606
+ fig = Figure(label='whole Figure')
1607
+ sub_fig = fig.subfigures(1, 1, label='sub figure')
1608
+
1609
+ assert fig.get_label() == 'whole Figure'
1610
+ assert sub_fig.get_label() == 'sub figure'
1611
+
1612
+
1613
+ @check_figures_equal(extensions=["png"])
1614
+ def test_rcparams(fig_test, fig_ref):
1615
+ fig_ref.supxlabel("xlabel", weight='bold', size=15)
1616
+ fig_ref.supylabel("ylabel", weight='bold', size=15)
1617
+ fig_ref.suptitle("Title", weight='light', size=20)
1618
+ with mpl.rc_context({'figure.labelweight': 'bold',
1619
+ 'figure.labelsize': 15,
1620
+ 'figure.titleweight': 'light',
1621
+ 'figure.titlesize': 20}):
1622
+ fig_test.supxlabel("xlabel")
1623
+ fig_test.supylabel("ylabel")
1624
+ fig_test.suptitle("Title")
1625
+
1626
+
1627
+ def test_deepcopy():
1628
+ fig1, ax = plt.subplots()
1629
+ ax.plot([0, 1], [2, 3])
1630
+ ax.set_yscale('log')
1631
+
1632
+ fig2 = copy.deepcopy(fig1)
1633
+
1634
+ # Make sure it is a new object
1635
+ assert fig2.axes[0] is not ax
1636
+ # And that the axis scale got propagated
1637
+ assert fig2.axes[0].get_yscale() == 'log'
1638
+ # Update the deepcopy and check the original isn't modified
1639
+ fig2.axes[0].set_yscale('linear')
1640
+ assert ax.get_yscale() == 'log'
1641
+
1642
+ # And test the limits of the axes don't get propagated
1643
+ ax.set_xlim(1e-1, 1e2)
1644
+ # Draw these to make sure limits are updated
1645
+ fig1.draw_without_rendering()
1646
+ fig2.draw_without_rendering()
1647
+
1648
+ assert ax.get_xlim() == (1e-1, 1e2)
1649
+ assert fig2.axes[0].get_xlim() == (0, 1)
1650
+
1651
+
1652
+ def test_unpickle_with_device_pixel_ratio():
1653
+ fig = Figure(dpi=42)
1654
+ fig.canvas._set_device_pixel_ratio(7)
1655
+ assert fig.dpi == 42*7
1656
+ fig2 = pickle.loads(pickle.dumps(fig))
1657
+ assert fig2.dpi == 42
1658
+
1659
+
1660
+ def test_gridspec_no_mutate_input():
1661
+ gs = {'left': .1}
1662
+ gs_orig = dict(gs)
1663
+ plt.subplots(1, 2, width_ratios=[1, 2], gridspec_kw=gs)
1664
+ assert gs == gs_orig
1665
+ plt.subplot_mosaic('AB', width_ratios=[1, 2], gridspec_kw=gs)
1666
+
1667
+
1668
+ @pytest.mark.parametrize('fmt', ['eps', 'pdf', 'png', 'ps', 'svg', 'svgz'])
1669
+ def test_savefig_metadata(fmt):
1670
+ Figure().savefig(io.BytesIO(), format=fmt, metadata={})
1671
+
1672
+
1673
+ @pytest.mark.parametrize('fmt', ['jpeg', 'jpg', 'tif', 'tiff', 'webp', "raw", "rgba"])
1674
+ def test_savefig_metadata_error(fmt):
1675
+ with pytest.raises(ValueError, match="metadata not supported"):
1676
+ Figure().savefig(io.BytesIO(), format=fmt, metadata={})
1677
+
1678
+
1679
+ def test_get_constrained_layout_pads():
1680
+ params = {'w_pad': 0.01, 'h_pad': 0.02, 'wspace': 0.03, 'hspace': 0.04}
1681
+ expected = tuple([*params.values()])
1682
+ fig = plt.figure(layout=mpl.layout_engine.ConstrainedLayoutEngine(**params))
1683
+ with pytest.warns(PendingDeprecationWarning, match="will be deprecated"):
1684
+ assert fig.get_constrained_layout_pads() == expected
1685
+
1686
+
1687
+ def test_not_visible_figure():
1688
+ fig = Figure()
1689
+
1690
+ buf = io.StringIO()
1691
+ fig.savefig(buf, format='svg')
1692
+ buf.seek(0)
1693
+ assert '<g ' in buf.read()
1694
+
1695
+ fig.set_visible(False)
1696
+ buf = io.StringIO()
1697
+ fig.savefig(buf, format='svg')
1698
+ buf.seek(0)
1699
+ assert '<g ' not in buf.read()
1700
+
1701
+
1702
+ def test_warn_colorbar_mismatch():
1703
+ fig1, ax1 = plt.subplots()
1704
+ fig2, (ax2_1, ax2_2) = plt.subplots(2)
1705
+ im = ax1.imshow([[1, 2], [3, 4]])
1706
+
1707
+ fig1.colorbar(im) # should not warn
1708
+ with pytest.warns(UserWarning, match="different Figure"):
1709
+ fig2.colorbar(im)
1710
+ # warn mismatch even when the host figure is not inferred
1711
+ with pytest.warns(UserWarning, match="different Figure"):
1712
+ fig2.colorbar(im, ax=ax1)
1713
+ with pytest.warns(UserWarning, match="different Figure"):
1714
+ fig2.colorbar(im, ax=ax2_1)
1715
+ with pytest.warns(UserWarning, match="different Figure"):
1716
+ fig2.colorbar(im, cax=ax2_2)
1717
+
1718
+ # edge case: only compare top level artist in case of subfigure
1719
+ fig3 = plt.figure()
1720
+ fig4 = plt.figure()
1721
+ subfig3_1 = fig3.subfigures()
1722
+ subfig3_2 = fig3.subfigures()
1723
+ subfig4_1 = fig4.subfigures()
1724
+ ax3_1 = subfig3_1.subplots()
1725
+ ax3_2 = subfig3_1.subplots()
1726
+ ax4_1 = subfig4_1.subplots()
1727
+ im3_1 = ax3_1.imshow([[1, 2], [3, 4]])
1728
+ im3_2 = ax3_2.imshow([[1, 2], [3, 4]])
1729
+ im4_1 = ax4_1.imshow([[1, 2], [3, 4]])
1730
+
1731
+ fig3.colorbar(im3_1) # should not warn
1732
+ subfig3_1.colorbar(im3_1) # should not warn
1733
+ subfig3_1.colorbar(im3_2) # should not warn
1734
+ with pytest.warns(UserWarning, match="different Figure"):
1735
+ subfig3_1.colorbar(im4_1)
1736
+
1737
+
1738
+ def test_subfigure_stale_propagation():
1739
+ fig = plt.figure()
1740
+
1741
+ fig.draw_without_rendering()
1742
+ assert not fig.stale
1743
+
1744
+ sfig1 = fig.subfigures()
1745
+ assert fig.stale
1746
+
1747
+ fig.draw_without_rendering()
1748
+ assert not fig.stale
1749
+ assert not sfig1.stale
1750
+
1751
+ sfig2 = sfig1.subfigures()
1752
+ assert fig.stale
1753
+
1754
+ fig.draw_without_rendering()
1755
+ assert not fig.stale
1756
+ assert not sfig2.stale
1757
+
1758
+ sfig2.stale = True
1759
+ assert fig.stale
parrot/lib/python3.10/site-packages/matplotlib/tests/test_lines.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests specific to the lines module.
3
+ """
4
+
5
+ import itertools
6
+ import platform
7
+ import timeit
8
+ from types import SimpleNamespace
9
+
10
+ from cycler import cycler
11
+ import numpy as np
12
+ from numpy.testing import assert_array_equal
13
+ import pytest
14
+
15
+ import matplotlib
16
+ import matplotlib as mpl
17
+ from matplotlib import _path
18
+ import matplotlib.lines as mlines
19
+ from matplotlib.markers import MarkerStyle
20
+ from matplotlib.path import Path
21
+ import matplotlib.pyplot as plt
22
+ import matplotlib.transforms as mtransforms
23
+ from matplotlib.testing.decorators import image_comparison, check_figures_equal
24
+
25
+
26
+ def test_segment_hits():
27
+ """Test a problematic case."""
28
+ cx, cy = 553, 902
29
+ x, y = np.array([553., 553.]), np.array([95., 947.])
30
+ radius = 6.94
31
+ assert_array_equal(mlines.segment_hits(cx, cy, x, y, radius), [0])
32
+
33
+
34
+ # Runtimes on a loaded system are inherently flaky. Not so much that a rerun
35
+ # won't help, hopefully.
36
+ @pytest.mark.flaky(reruns=3)
37
+ def test_invisible_Line_rendering():
38
+ """
39
+ GitHub issue #1256 identified a bug in Line.draw method
40
+
41
+ Despite visibility attribute set to False, the draw method was not
42
+ returning early enough and some pre-rendering code was executed
43
+ though not necessary.
44
+
45
+ Consequence was an excessive draw time for invisible Line instances
46
+ holding a large number of points (Npts> 10**6)
47
+ """
48
+ # Creates big x and y data:
49
+ N = 10**7
50
+ x = np.linspace(0, 1, N)
51
+ y = np.random.normal(size=N)
52
+
53
+ # Create a plot figure:
54
+ fig = plt.figure()
55
+ ax = plt.subplot()
56
+
57
+ # Create a "big" Line instance:
58
+ l = mlines.Line2D(x, y)
59
+ l.set_visible(False)
60
+ # but don't add it to the Axis instance `ax`
61
+
62
+ # [here Interactive panning and zooming is pretty responsive]
63
+ # Time the canvas drawing:
64
+ t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
65
+ # (gives about 25 ms)
66
+
67
+ # Add the big invisible Line:
68
+ ax.add_line(l)
69
+
70
+ # [Now interactive panning and zooming is very slow]
71
+ # Time the canvas drawing:
72
+ t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3))
73
+ # gives about 290 ms for N = 10**7 pts
74
+
75
+ slowdown_factor = t_invisible_line / t_no_line
76
+ slowdown_threshold = 2 # trying to avoid false positive failures
77
+ assert slowdown_factor < slowdown_threshold
78
+
79
+
80
+ def test_set_line_coll_dash():
81
+ fig, ax = plt.subplots()
82
+ np.random.seed(0)
83
+ # Testing setting linestyles for line collections.
84
+ # This should not produce an error.
85
+ ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
86
+
87
+
88
+ def test_invalid_line_data():
89
+ with pytest.raises(RuntimeError, match='xdata must be'):
90
+ mlines.Line2D(0, [])
91
+ with pytest.raises(RuntimeError, match='ydata must be'):
92
+ mlines.Line2D([], 1)
93
+
94
+ line = mlines.Line2D([], [])
95
+ with pytest.raises(RuntimeError, match='x must be'):
96
+ line.set_xdata(0)
97
+ with pytest.raises(RuntimeError, match='y must be'):
98
+ line.set_ydata(0)
99
+
100
+
101
+ @image_comparison(['line_dashes'], remove_text=True, tol=0.003)
102
+ def test_line_dashes():
103
+ # Tolerance introduced after reordering of floating-point operations
104
+ # Remove when regenerating the images
105
+ fig, ax = plt.subplots()
106
+
107
+ ax.plot(range(10), linestyle=(0, (3, 3)), lw=5)
108
+
109
+
110
+ def test_line_colors():
111
+ fig, ax = plt.subplots()
112
+ ax.plot(range(10), color='none')
113
+ ax.plot(range(10), color='r')
114
+ ax.plot(range(10), color='.3')
115
+ ax.plot(range(10), color=(1, 0, 0, 1))
116
+ ax.plot(range(10), color=(1, 0, 0))
117
+ fig.canvas.draw()
118
+
119
+
120
+ def test_valid_colors():
121
+ line = mlines.Line2D([], [])
122
+ with pytest.raises(ValueError):
123
+ line.set_color("foobar")
124
+
125
+
126
+ def test_linestyle_variants():
127
+ fig, ax = plt.subplots()
128
+ for ls in ["-", "solid", "--", "dashed",
129
+ "-.", "dashdot", ":", "dotted",
130
+ (0, None), (0, ()), (0, []), # gh-22930
131
+ ]:
132
+ ax.plot(range(10), linestyle=ls)
133
+ fig.canvas.draw()
134
+
135
+
136
+ def test_valid_linestyles():
137
+ line = mlines.Line2D([], [])
138
+ with pytest.raises(ValueError):
139
+ line.set_linestyle('aardvark')
140
+
141
+
142
+ @image_comparison(['drawstyle_variants.png'], remove_text=True,
143
+ tol=0.03 if platform.machine() == 'arm64' else 0)
144
+ def test_drawstyle_variants():
145
+ fig, axs = plt.subplots(6)
146
+ dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None]
147
+ # We want to check that drawstyles are properly handled even for very long
148
+ # lines (for which the subslice optimization is on); however, we need
149
+ # to zoom in so that the difference between the drawstyles is actually
150
+ # visible.
151
+ for ax, ds in zip(axs.flat, dss):
152
+ ax.plot(range(2000), drawstyle=ds)
153
+ ax.set(xlim=(0, 2), ylim=(0, 2))
154
+
155
+
156
+ @check_figures_equal(extensions=('png',))
157
+ def test_no_subslice_with_transform(fig_ref, fig_test):
158
+ ax = fig_ref.add_subplot()
159
+ x = np.arange(2000)
160
+ ax.plot(x + 2000, x)
161
+
162
+ ax = fig_test.add_subplot()
163
+ t = mtransforms.Affine2D().translate(2000.0, 0.0)
164
+ ax.plot(x, x, transform=t+ax.transData)
165
+
166
+
167
+ def test_valid_drawstyles():
168
+ line = mlines.Line2D([], [])
169
+ with pytest.raises(ValueError):
170
+ line.set_drawstyle('foobar')
171
+
172
+
173
+ def test_set_drawstyle():
174
+ x = np.linspace(0, 2*np.pi, 10)
175
+ y = np.sin(x)
176
+
177
+ fig, ax = plt.subplots()
178
+ line, = ax.plot(x, y)
179
+ line.set_drawstyle("steps-pre")
180
+ assert len(line.get_path().vertices) == 2*len(x)-1
181
+
182
+ line.set_drawstyle("default")
183
+ assert len(line.get_path().vertices) == len(x)
184
+
185
+
186
+ @image_comparison(
187
+ ['line_collection_dashes'], remove_text=True, style='mpl20',
188
+ tol=0 if platform.machine() == 'x86_64' else 0.65)
189
+ def test_set_line_coll_dash_image():
190
+ fig, ax = plt.subplots()
191
+ np.random.seed(0)
192
+ ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))])
193
+
194
+
195
+ @image_comparison(['marker_fill_styles.png'], remove_text=True)
196
+ def test_marker_fill_styles():
197
+ colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y',
198
+ np.array([0, 0, 0])])
199
+ altcolor = 'lightgreen'
200
+
201
+ y = np.array([1, 1])
202
+ x = np.array([0, 9])
203
+ fig, ax = plt.subplots()
204
+
205
+ # This hard-coded list of markers correspond to an earlier iteration of
206
+ # MarkerStyle.filled_markers; the value of that attribute has changed but
207
+ # we kept the old value here to not regenerate the baseline image.
208
+ # Replace with mlines.Line2D.filled_markers when the image is regenerated.
209
+ for j, marker in enumerate("ov^<>8sp*hHDdPX"):
210
+ for i, fs in enumerate(mlines.Line2D.fillStyles):
211
+ color = next(colors)
212
+ ax.plot(j * 10 + x, y + i + .5 * (j % 2),
213
+ marker=marker,
214
+ markersize=20,
215
+ markerfacecoloralt=altcolor,
216
+ fillstyle=fs,
217
+ label=fs,
218
+ linewidth=5,
219
+ color=color,
220
+ markeredgecolor=color,
221
+ markeredgewidth=2)
222
+
223
+ ax.set_ylim([0, 7.5])
224
+ ax.set_xlim([-5, 155])
225
+
226
+
227
+ def test_markerfacecolor_fillstyle():
228
+ """Test that markerfacecolor does not override fillstyle='none'."""
229
+ l, = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'),
230
+ markerfacecolor='red')
231
+ assert l.get_fillstyle() == 'none'
232
+ assert l.get_markerfacecolor() == 'none'
233
+
234
+
235
+ @image_comparison(['scaled_lines'], style='default')
236
+ def test_lw_scaling():
237
+ th = np.linspace(0, 32)
238
+ fig, ax = plt.subplots()
239
+ lins_styles = ['dashed', 'dotted', 'dashdot']
240
+ cy = cycler(matplotlib.rcParams['axes.prop_cycle'])
241
+ for j, (ls, sty) in enumerate(zip(lins_styles, cy)):
242
+ for lw in np.linspace(.5, 10, 10):
243
+ ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty)
244
+
245
+
246
+ def test_is_sorted_and_has_non_nan():
247
+ assert _path.is_sorted_and_has_non_nan(np.array([1, 2, 3]))
248
+ assert _path.is_sorted_and_has_non_nan(np.array([1, np.nan, 3]))
249
+ assert not _path.is_sorted_and_has_non_nan([3, 5] + [np.nan] * 100 + [0, 2])
250
+ # [2, 256] byteswapped:
251
+ assert not _path.is_sorted_and_has_non_nan(np.array([33554432, 65536], ">i4"))
252
+ n = 2 * mlines.Line2D._subslice_optim_min_size
253
+ plt.plot([np.nan] * n, range(n))
254
+
255
+
256
+ @check_figures_equal()
257
+ def test_step_markers(fig_test, fig_ref):
258
+ fig_test.subplots().step([0, 1], "-o")
259
+ fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2])
260
+
261
+
262
+ @pytest.mark.parametrize("parent", ["figure", "axes"])
263
+ @check_figures_equal(extensions=('png',))
264
+ def test_markevery(fig_test, fig_ref, parent):
265
+ np.random.seed(42)
266
+ x = np.linspace(0, 1, 14)
267
+ y = np.random.rand(len(x))
268
+
269
+ cases_test = [None, 4, (2, 5), [1, 5, 11],
270
+ [0, -1], slice(5, 10, 2),
271
+ np.arange(len(x))[y > 0.5],
272
+ 0.3, (0.3, 0.4)]
273
+ cases_ref = ["11111111111111", "10001000100010", "00100001000010",
274
+ "01000100000100", "10000000000001", "00000101010000",
275
+ "01110001110110", "11011011011110", "01010011011101"]
276
+
277
+ if parent == "figure":
278
+ # float markevery ("relative to axes size") is not supported.
279
+ cases_test = cases_test[:-2]
280
+ cases_ref = cases_ref[:-2]
281
+
282
+ def add_test(x, y, *, markevery):
283
+ fig_test.add_artist(
284
+ mlines.Line2D(x, y, marker="o", markevery=markevery))
285
+
286
+ def add_ref(x, y, *, markevery):
287
+ fig_ref.add_artist(
288
+ mlines.Line2D(x, y, marker="o", markevery=markevery))
289
+
290
+ elif parent == "axes":
291
+ axs_test = iter(fig_test.subplots(3, 3).flat)
292
+ axs_ref = iter(fig_ref.subplots(3, 3).flat)
293
+
294
+ def add_test(x, y, *, markevery):
295
+ next(axs_test).plot(x, y, "-gD", markevery=markevery)
296
+
297
+ def add_ref(x, y, *, markevery):
298
+ next(axs_ref).plot(x, y, "-gD", markevery=markevery)
299
+
300
+ for case in cases_test:
301
+ add_test(x, y, markevery=case)
302
+
303
+ for case in cases_ref:
304
+ me = np.array(list(case)).astype(int).astype(bool)
305
+ add_ref(x, y, markevery=me)
306
+
307
+
308
+ def test_markevery_figure_line_unsupported_relsize():
309
+ fig = plt.figure()
310
+ fig.add_artist(mlines.Line2D([0, 1], [0, 1], marker="o", markevery=.5))
311
+ with pytest.raises(ValueError):
312
+ fig.canvas.draw()
313
+
314
+
315
+ def test_marker_as_markerstyle():
316
+ fig, ax = plt.subplots()
317
+ line, = ax.plot([2, 4, 3], marker=MarkerStyle("D"))
318
+ fig.canvas.draw()
319
+ assert line.get_marker() == "D"
320
+
321
+ # continue with smoke tests:
322
+ line.set_marker("s")
323
+ fig.canvas.draw()
324
+ line.set_marker(MarkerStyle("o"))
325
+ fig.canvas.draw()
326
+ # test Path roundtrip
327
+ triangle1 = Path._create_closed([[-1, -1], [1, -1], [0, 2]])
328
+ line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22)
329
+ line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22)
330
+
331
+ assert_array_equal(line2.get_marker().vertices, triangle1.vertices)
332
+ assert_array_equal(line3.get_marker().vertices, triangle1.vertices)
333
+
334
+
335
+ @image_comparison(['striped_line.png'], remove_text=True, style='mpl20')
336
+ def test_striped_lines():
337
+ rng = np.random.default_rng(19680801)
338
+ _, ax = plt.subplots()
339
+ ax.plot(rng.uniform(size=12), color='orange', gapcolor='blue',
340
+ linestyle='--', lw=5, label=' ')
341
+ ax.plot(rng.uniform(size=12), color='red', gapcolor='black',
342
+ linestyle=(0, (2, 5, 4, 2)), lw=5, label=' ', alpha=0.5)
343
+ ax.legend(handlelength=5)
344
+
345
+
346
+ @check_figures_equal()
347
+ def test_odd_dashes(fig_test, fig_ref):
348
+ fig_test.add_subplot().plot([1, 2], dashes=[1, 2, 3])
349
+ fig_ref.add_subplot().plot([1, 2], dashes=[1, 2, 3, 1, 2, 3])
350
+
351
+
352
+ def test_picking():
353
+ fig, ax = plt.subplots()
354
+ mouse_event = SimpleNamespace(x=fig.bbox.width // 2,
355
+ y=fig.bbox.height // 2 + 15)
356
+
357
+ # Default pickradius is 5, so event should not pick this line.
358
+ l0, = ax.plot([0, 1], [0, 1], picker=True)
359
+ found, indices = l0.contains(mouse_event)
360
+ assert not found
361
+
362
+ # But with a larger pickradius, this should be picked.
363
+ l1, = ax.plot([0, 1], [0, 1], picker=True, pickradius=20)
364
+ found, indices = l1.contains(mouse_event)
365
+ assert found
366
+ assert_array_equal(indices['ind'], [0])
367
+
368
+ # And if we modify the pickradius after creation, it should work as well.
369
+ l2, = ax.plot([0, 1], [0, 1], picker=True)
370
+ found, indices = l2.contains(mouse_event)
371
+ assert not found
372
+ l2.set_pickradius(20)
373
+ found, indices = l2.contains(mouse_event)
374
+ assert found
375
+ assert_array_equal(indices['ind'], [0])
376
+
377
+
378
+ @check_figures_equal()
379
+ def test_input_copy(fig_test, fig_ref):
380
+
381
+ t = np.arange(0, 6, 2)
382
+ l, = fig_test.add_subplot().plot(t, t, ".-")
383
+ t[:] = range(3)
384
+ # Trigger cache invalidation
385
+ l.set_drawstyle("steps")
386
+ fig_ref.add_subplot().plot([0, 2, 4], [0, 2, 4], ".-", drawstyle="steps")
387
+
388
+
389
+ @check_figures_equal(extensions=["png"])
390
+ def test_markevery_prop_cycle(fig_test, fig_ref):
391
+ """Test that we can set markevery prop_cycle."""
392
+ cases = [None, 8, (30, 8), [16, 24, 30], [0, -1],
393
+ slice(100, 200, 3), 0.1, 0.3, 1.5,
394
+ (0.0, 0.1), (0.45, 0.1)]
395
+
396
+ cmap = mpl.colormaps['jet']
397
+ colors = cmap(np.linspace(0.2, 0.8, len(cases)))
398
+
399
+ x = np.linspace(-1, 1)
400
+ y = 5 * x**2
401
+
402
+ axs = fig_ref.add_subplot()
403
+ for i, markevery in enumerate(cases):
404
+ axs.plot(y - i, 'o-', markevery=markevery, color=colors[i])
405
+
406
+ matplotlib.rcParams['axes.prop_cycle'] = cycler(markevery=cases,
407
+ color=colors)
408
+
409
+ ax = fig_test.add_subplot()
410
+ for i, _ in enumerate(cases):
411
+ ax.plot(y - i, 'o-')
412
+
413
+
414
+ def test_axline_setters():
415
+ fig, ax = plt.subplots()
416
+ line1 = ax.axline((.1, .1), slope=0.6)
417
+ line2 = ax.axline((.1, .1), (.8, .4))
418
+ # Testing xy1, xy2 and slope setters.
419
+ # This should not produce an error.
420
+ line1.set_xy1(.2, .3)
421
+ line1.set_slope(2.4)
422
+ line2.set_xy1(.3, .2)
423
+ line2.set_xy2(.6, .8)
424
+ # Testing xy1, xy2 and slope getters.
425
+ # Should return the modified values.
426
+ assert line1.get_xy1() == (.2, .3)
427
+ assert line1.get_slope() == 2.4
428
+ assert line2.get_xy1() == (.3, .2)
429
+ assert line2.get_xy2() == (.6, .8)
430
+ # Testing setting xy2 and slope together.
431
+ # These test should raise a ValueError
432
+ with pytest.raises(ValueError,
433
+ match="Cannot set an 'xy2' value while 'slope' is set"):
434
+ line1.set_xy2(.2, .3)
435
+
436
+ with pytest.raises(ValueError,
437
+ match="Cannot set a 'slope' value while 'xy2' is set"):
438
+ line2.set_slope(3)
parrot/lib/python3.10/site-packages/matplotlib/tests/test_patches.py ADDED
@@ -0,0 +1,962 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Tests specific to the patches module.
3
+ """
4
+ import platform
5
+
6
+ import numpy as np
7
+ from numpy.testing import assert_almost_equal, assert_array_equal
8
+ import pytest
9
+
10
+ import matplotlib as mpl
11
+ from matplotlib.patches import (Annulus, Ellipse, Patch, Polygon, Rectangle,
12
+ FancyArrowPatch, FancyArrow, BoxStyle, Arc)
13
+ from matplotlib.testing.decorators import image_comparison, check_figures_equal
14
+ from matplotlib.transforms import Bbox
15
+ import matplotlib.pyplot as plt
16
+ from matplotlib import (
17
+ collections as mcollections, colors as mcolors, patches as mpatches,
18
+ path as mpath, transforms as mtransforms, rcParams)
19
+
20
+
21
+ def test_Polygon_close():
22
+ #: GitHub issue #1018 identified a bug in the Polygon handling
23
+ #: of the closed attribute; the path was not getting closed
24
+ #: when set_xy was used to set the vertices.
25
+
26
+ # open set of vertices:
27
+ xy = [[0, 0], [0, 1], [1, 1]]
28
+ # closed set:
29
+ xyclosed = xy + [[0, 0]]
30
+
31
+ # start with open path and close it:
32
+ p = Polygon(xy, closed=True)
33
+ assert p.get_closed()
34
+ assert_array_equal(p.get_xy(), xyclosed)
35
+ p.set_xy(xy)
36
+ assert_array_equal(p.get_xy(), xyclosed)
37
+
38
+ # start with closed path and open it:
39
+ p = Polygon(xyclosed, closed=False)
40
+ assert_array_equal(p.get_xy(), xy)
41
+ p.set_xy(xyclosed)
42
+ assert_array_equal(p.get_xy(), xy)
43
+
44
+ # start with open path and leave it open:
45
+ p = Polygon(xy, closed=False)
46
+ assert not p.get_closed()
47
+ assert_array_equal(p.get_xy(), xy)
48
+ p.set_xy(xy)
49
+ assert_array_equal(p.get_xy(), xy)
50
+
51
+ # start with closed path and leave it closed:
52
+ p = Polygon(xyclosed, closed=True)
53
+ assert_array_equal(p.get_xy(), xyclosed)
54
+ p.set_xy(xyclosed)
55
+ assert_array_equal(p.get_xy(), xyclosed)
56
+
57
+
58
+ def test_corner_center():
59
+ loc = [10, 20]
60
+ width = 1
61
+ height = 2
62
+
63
+ # Rectangle
64
+ # No rotation
65
+ corners = ((10, 20), (11, 20), (11, 22), (10, 22))
66
+ rect = Rectangle(loc, width, height)
67
+ assert_array_equal(rect.get_corners(), corners)
68
+ assert_array_equal(rect.get_center(), (10.5, 21))
69
+
70
+ # 90 deg rotation
71
+ corners_rot = ((10, 20), (10, 21), (8, 21), (8, 20))
72
+ rect.set_angle(90)
73
+ assert_array_equal(rect.get_corners(), corners_rot)
74
+ assert_array_equal(rect.get_center(), (9, 20.5))
75
+
76
+ # Rotation not a multiple of 90 deg
77
+ theta = 33
78
+ t = mtransforms.Affine2D().rotate_around(*loc, np.deg2rad(theta))
79
+ corners_rot = t.transform(corners)
80
+ rect.set_angle(theta)
81
+ assert_almost_equal(rect.get_corners(), corners_rot)
82
+
83
+ # Ellipse
84
+ loc = [loc[0] + width / 2,
85
+ loc[1] + height / 2]
86
+ ellipse = Ellipse(loc, width, height)
87
+
88
+ # No rotation
89
+ assert_array_equal(ellipse.get_corners(), corners)
90
+
91
+ # 90 deg rotation
92
+ corners_rot = ((11.5, 20.5), (11.5, 21.5), (9.5, 21.5), (9.5, 20.5))
93
+ ellipse.set_angle(90)
94
+ assert_array_equal(ellipse.get_corners(), corners_rot)
95
+ # Rotation shouldn't change ellipse center
96
+ assert_array_equal(ellipse.get_center(), loc)
97
+
98
+ # Rotation not a multiple of 90 deg
99
+ theta = 33
100
+ t = mtransforms.Affine2D().rotate_around(*loc, np.deg2rad(theta))
101
+ corners_rot = t.transform(corners)
102
+ ellipse.set_angle(theta)
103
+ assert_almost_equal(ellipse.get_corners(), corners_rot)
104
+
105
+
106
+ def test_ellipse_vertices():
107
+ # expect 0 for 0 ellipse width, height
108
+ ellipse = Ellipse(xy=(0, 0), width=0, height=0, angle=0)
109
+ assert_almost_equal(
110
+ ellipse.get_vertices(),
111
+ [(0.0, 0.0), (0.0, 0.0)],
112
+ )
113
+ assert_almost_equal(
114
+ ellipse.get_co_vertices(),
115
+ [(0.0, 0.0), (0.0, 0.0)],
116
+ )
117
+
118
+ ellipse = Ellipse(xy=(0, 0), width=2, height=1, angle=30)
119
+ assert_almost_equal(
120
+ ellipse.get_vertices(),
121
+ [
122
+ (
123
+ ellipse.center[0] + ellipse.width / 4 * np.sqrt(3),
124
+ ellipse.center[1] + ellipse.width / 4,
125
+ ),
126
+ (
127
+ ellipse.center[0] - ellipse.width / 4 * np.sqrt(3),
128
+ ellipse.center[1] - ellipse.width / 4,
129
+ ),
130
+ ],
131
+ )
132
+ assert_almost_equal(
133
+ ellipse.get_co_vertices(),
134
+ [
135
+ (
136
+ ellipse.center[0] - ellipse.height / 4,
137
+ ellipse.center[1] + ellipse.height / 4 * np.sqrt(3),
138
+ ),
139
+ (
140
+ ellipse.center[0] + ellipse.height / 4,
141
+ ellipse.center[1] - ellipse.height / 4 * np.sqrt(3),
142
+ ),
143
+ ],
144
+ )
145
+ v1, v2 = np.array(ellipse.get_vertices())
146
+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)
147
+ v1, v2 = np.array(ellipse.get_co_vertices())
148
+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)
149
+
150
+ ellipse = Ellipse(xy=(2.252, -10.859), width=2.265, height=1.98, angle=68.78)
151
+ v1, v2 = np.array(ellipse.get_vertices())
152
+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)
153
+ v1, v2 = np.array(ellipse.get_co_vertices())
154
+ np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center)
155
+
156
+
157
+ def test_rotate_rect():
158
+ loc = np.asarray([1.0, 2.0])
159
+ width = 2
160
+ height = 3
161
+ angle = 30.0
162
+
163
+ # A rotated rectangle
164
+ rect1 = Rectangle(loc, width, height, angle=angle)
165
+
166
+ # A non-rotated rectangle
167
+ rect2 = Rectangle(loc, width, height)
168
+
169
+ # Set up an explicit rotation matrix (in radians)
170
+ angle_rad = np.pi * angle / 180.0
171
+ rotation_matrix = np.array([[np.cos(angle_rad), -np.sin(angle_rad)],
172
+ [np.sin(angle_rad), np.cos(angle_rad)]])
173
+
174
+ # Translate to origin, rotate each vertex, and then translate back
175
+ new_verts = np.inner(rotation_matrix, rect2.get_verts() - loc).T + loc
176
+
177
+ # They should be the same
178
+ assert_almost_equal(rect1.get_verts(), new_verts)
179
+
180
+
181
+ @check_figures_equal(extensions=['png'])
182
+ def test_rotate_rect_draw(fig_test, fig_ref):
183
+ ax_test = fig_test.add_subplot()
184
+ ax_ref = fig_ref.add_subplot()
185
+
186
+ loc = (0, 0)
187
+ width, height = (1, 1)
188
+ angle = 30
189
+ rect_ref = Rectangle(loc, width, height, angle=angle)
190
+ ax_ref.add_patch(rect_ref)
191
+ assert rect_ref.get_angle() == angle
192
+
193
+ # Check that when the angle is updated after adding to an Axes, that the
194
+ # patch is marked stale and redrawn in the correct location
195
+ rect_test = Rectangle(loc, width, height)
196
+ assert rect_test.get_angle() == 0
197
+ ax_test.add_patch(rect_test)
198
+ rect_test.set_angle(angle)
199
+ assert rect_test.get_angle() == angle
200
+
201
+
202
+ @check_figures_equal(extensions=['png'])
203
+ def test_dash_offset_patch_draw(fig_test, fig_ref):
204
+ ax_test = fig_test.add_subplot()
205
+ ax_ref = fig_ref.add_subplot()
206
+
207
+ loc = (0.1, 0.1)
208
+ width, height = (0.8, 0.8)
209
+ rect_ref = Rectangle(loc, width, height, linewidth=3, edgecolor='b',
210
+ linestyle=(0, [6, 6]))
211
+ # fill the line gaps using a linestyle (0, [0, 6, 6, 0]), which is
212
+ # equivalent to (6, [6, 6]) but has 0 dash offset
213
+ rect_ref2 = Rectangle(loc, width, height, linewidth=3, edgecolor='r',
214
+ linestyle=(0, [0, 6, 6, 0]))
215
+ assert rect_ref.get_linestyle() == (0, [6, 6])
216
+ assert rect_ref2.get_linestyle() == (0, [0, 6, 6, 0])
217
+
218
+ ax_ref.add_patch(rect_ref)
219
+ ax_ref.add_patch(rect_ref2)
220
+
221
+ # Check that the dash offset of the rect is the same if we pass it in the
222
+ # init method and if we create two rects with appropriate onoff sequence
223
+ # of linestyle.
224
+
225
+ rect_test = Rectangle(loc, width, height, linewidth=3, edgecolor='b',
226
+ linestyle=(0, [6, 6]))
227
+ rect_test2 = Rectangle(loc, width, height, linewidth=3, edgecolor='r',
228
+ linestyle=(6, [6, 6]))
229
+ assert rect_test.get_linestyle() == (0, [6, 6])
230
+ assert rect_test2.get_linestyle() == (6, [6, 6])
231
+
232
+ ax_test.add_patch(rect_test)
233
+ ax_test.add_patch(rect_test2)
234
+
235
+
236
+ def test_negative_rect():
237
+ # These two rectangles have the same vertices, but starting from a
238
+ # different point. (We also drop the last vertex, which is a duplicate.)
239
+ pos_vertices = Rectangle((-3, -2), 3, 2).get_verts()[:-1]
240
+ neg_vertices = Rectangle((0, 0), -3, -2).get_verts()[:-1]
241
+ assert_array_equal(np.roll(neg_vertices, 2, 0), pos_vertices)
242
+
243
+
244
+ @image_comparison(['clip_to_bbox'])
245
+ def test_clip_to_bbox():
246
+ fig, ax = plt.subplots()
247
+ ax.set_xlim([-18, 20])
248
+ ax.set_ylim([-150, 100])
249
+
250
+ path = mpath.Path.unit_regular_star(8).deepcopy()
251
+ path.vertices *= [10, 100]
252
+ path.vertices -= [5, 25]
253
+
254
+ path2 = mpath.Path.unit_circle().deepcopy()
255
+ path2.vertices *= [10, 100]
256
+ path2.vertices += [10, -25]
257
+
258
+ combined = mpath.Path.make_compound_path(path, path2)
259
+
260
+ patch = mpatches.PathPatch(
261
+ combined, alpha=0.5, facecolor='coral', edgecolor='none')
262
+ ax.add_patch(patch)
263
+
264
+ bbox = mtransforms.Bbox([[-12, -77.5], [50, -110]])
265
+ result_path = combined.clip_to_bbox(bbox)
266
+ result_patch = mpatches.PathPatch(
267
+ result_path, alpha=0.5, facecolor='green', lw=4, edgecolor='black')
268
+
269
+ ax.add_patch(result_patch)
270
+
271
+
272
+ @image_comparison(['patch_alpha_coloring'], remove_text=True)
273
+ def test_patch_alpha_coloring():
274
+ """
275
+ Test checks that the patch and collection are rendered with the specified
276
+ alpha values in their facecolor and edgecolor.
277
+ """
278
+ star = mpath.Path.unit_regular_star(6)
279
+ circle = mpath.Path.unit_circle()
280
+ # concatenate the star with an internal cutout of the circle
281
+ verts = np.concatenate([circle.vertices, star.vertices[::-1]])
282
+ codes = np.concatenate([circle.codes, star.codes])
283
+ cut_star1 = mpath.Path(verts, codes)
284
+ cut_star2 = mpath.Path(verts + 1, codes)
285
+
286
+ ax = plt.axes()
287
+ col = mcollections.PathCollection([cut_star2],
288
+ linewidth=5, linestyles='dashdot',
289
+ facecolor=(1, 0, 0, 0.5),
290
+ edgecolor=(0, 0, 1, 0.75))
291
+ ax.add_collection(col)
292
+
293
+ patch = mpatches.PathPatch(cut_star1,
294
+ linewidth=5, linestyle='dashdot',
295
+ facecolor=(1, 0, 0, 0.5),
296
+ edgecolor=(0, 0, 1, 0.75))
297
+ ax.add_patch(patch)
298
+
299
+ ax.set_xlim(-1, 2)
300
+ ax.set_ylim(-1, 2)
301
+
302
+
303
+ @image_comparison(['patch_alpha_override'], remove_text=True)
304
+ def test_patch_alpha_override():
305
+ #: Test checks that specifying an alpha attribute for a patch or
306
+ #: collection will override any alpha component of the facecolor
307
+ #: or edgecolor.
308
+ star = mpath.Path.unit_regular_star(6)
309
+ circle = mpath.Path.unit_circle()
310
+ # concatenate the star with an internal cutout of the circle
311
+ verts = np.concatenate([circle.vertices, star.vertices[::-1]])
312
+ codes = np.concatenate([circle.codes, star.codes])
313
+ cut_star1 = mpath.Path(verts, codes)
314
+ cut_star2 = mpath.Path(verts + 1, codes)
315
+
316
+ ax = plt.axes()
317
+ col = mcollections.PathCollection([cut_star2],
318
+ linewidth=5, linestyles='dashdot',
319
+ alpha=0.25,
320
+ facecolor=(1, 0, 0, 0.5),
321
+ edgecolor=(0, 0, 1, 0.75))
322
+ ax.add_collection(col)
323
+
324
+ patch = mpatches.PathPatch(cut_star1,
325
+ linewidth=5, linestyle='dashdot',
326
+ alpha=0.25,
327
+ facecolor=(1, 0, 0, 0.5),
328
+ edgecolor=(0, 0, 1, 0.75))
329
+ ax.add_patch(patch)
330
+
331
+ ax.set_xlim(-1, 2)
332
+ ax.set_ylim(-1, 2)
333
+
334
+
335
+ @mpl.style.context('default')
336
+ def test_patch_color_none():
337
+ # Make sure the alpha kwarg does not override 'none' facecolor.
338
+ # Addresses issue #7478.
339
+ c = plt.Circle((0, 0), 1, facecolor='none', alpha=1)
340
+ assert c.get_facecolor()[0] == 0
341
+
342
+
343
+ @image_comparison(['patch_custom_linestyle'], remove_text=True)
344
+ def test_patch_custom_linestyle():
345
+ #: A test to check that patches and collections accept custom dash
346
+ #: patterns as linestyle and that they display correctly.
347
+ star = mpath.Path.unit_regular_star(6)
348
+ circle = mpath.Path.unit_circle()
349
+ # concatenate the star with an internal cutout of the circle
350
+ verts = np.concatenate([circle.vertices, star.vertices[::-1]])
351
+ codes = np.concatenate([circle.codes, star.codes])
352
+ cut_star1 = mpath.Path(verts, codes)
353
+ cut_star2 = mpath.Path(verts + 1, codes)
354
+
355
+ ax = plt.axes()
356
+ col = mcollections.PathCollection(
357
+ [cut_star2],
358
+ linewidth=5, linestyles=[(0, (5, 7, 10, 7))],
359
+ facecolor=(1, 0, 0), edgecolor=(0, 0, 1))
360
+ ax.add_collection(col)
361
+
362
+ patch = mpatches.PathPatch(
363
+ cut_star1,
364
+ linewidth=5, linestyle=(0, (5, 7, 10, 7)),
365
+ facecolor=(1, 0, 0), edgecolor=(0, 0, 1))
366
+ ax.add_patch(patch)
367
+
368
+ ax.set_xlim(-1, 2)
369
+ ax.set_ylim(-1, 2)
370
+
371
+
372
+ def test_patch_linestyle_accents():
373
+ #: Test if linestyle can also be specified with short mnemonics like "--"
374
+ #: c.f. GitHub issue #2136
375
+ star = mpath.Path.unit_regular_star(6)
376
+ circle = mpath.Path.unit_circle()
377
+ # concatenate the star with an internal cutout of the circle
378
+ verts = np.concatenate([circle.vertices, star.vertices[::-1]])
379
+ codes = np.concatenate([circle.codes, star.codes])
380
+
381
+ linestyles = ["-", "--", "-.", ":",
382
+ "solid", "dashed", "dashdot", "dotted"]
383
+
384
+ fig, ax = plt.subplots()
385
+ for i, ls in enumerate(linestyles):
386
+ star = mpath.Path(verts + i, codes)
387
+ patch = mpatches.PathPatch(star,
388
+ linewidth=3, linestyle=ls,
389
+ facecolor=(1, 0, 0),
390
+ edgecolor=(0, 0, 1))
391
+ ax.add_patch(patch)
392
+
393
+ ax.set_xlim([-1, i + 1])
394
+ ax.set_ylim([-1, i + 1])
395
+ fig.canvas.draw()
396
+
397
+
398
+ @check_figures_equal(extensions=['png'])
399
+ def test_patch_linestyle_none(fig_test, fig_ref):
400
+ circle = mpath.Path.unit_circle()
401
+
402
+ ax_test = fig_test.add_subplot()
403
+ ax_ref = fig_ref.add_subplot()
404
+ for i, ls in enumerate(['none', 'None', ' ', '']):
405
+ path = mpath.Path(circle.vertices + i, circle.codes)
406
+ patch = mpatches.PathPatch(path,
407
+ linewidth=3, linestyle=ls,
408
+ facecolor=(1, 0, 0),
409
+ edgecolor=(0, 0, 1))
410
+ ax_test.add_patch(patch)
411
+
412
+ patch = mpatches.PathPatch(path,
413
+ linewidth=3, linestyle='-',
414
+ facecolor=(1, 0, 0),
415
+ edgecolor='none')
416
+ ax_ref.add_patch(patch)
417
+
418
+ ax_test.set_xlim([-1, i + 1])
419
+ ax_test.set_ylim([-1, i + 1])
420
+ ax_ref.set_xlim([-1, i + 1])
421
+ ax_ref.set_ylim([-1, i + 1])
422
+
423
+
424
+ def test_wedge_movement():
425
+ param_dict = {'center': ((0, 0), (1, 1), 'set_center'),
426
+ 'r': (5, 8, 'set_radius'),
427
+ 'width': (2, 3, 'set_width'),
428
+ 'theta1': (0, 30, 'set_theta1'),
429
+ 'theta2': (45, 50, 'set_theta2')}
430
+
431
+ init_args = {k: v[0] for k, v in param_dict.items()}
432
+
433
+ w = mpatches.Wedge(**init_args)
434
+ for attr, (old_v, new_v, func) in param_dict.items():
435
+ assert getattr(w, attr) == old_v
436
+ getattr(w, func)(new_v)
437
+ assert getattr(w, attr) == new_v
438
+
439
+
440
+ @image_comparison(['wedge_range'], remove_text=True,
441
+ tol=0.009 if platform.machine() == 'arm64' else 0)
442
+ def test_wedge_range():
443
+ ax = plt.axes()
444
+
445
+ t1 = 2.313869244286224
446
+
447
+ args = [[52.31386924, 232.31386924],
448
+ [52.313869244286224, 232.31386924428622],
449
+ [t1, t1 + 180.0],
450
+ [0, 360],
451
+ [90, 90 + 360],
452
+ [-180, 180],
453
+ [0, 380],
454
+ [45, 46],
455
+ [46, 45]]
456
+
457
+ for i, (theta1, theta2) in enumerate(args):
458
+ x = i % 3
459
+ y = i // 3
460
+
461
+ wedge = mpatches.Wedge((x * 3, y * 3), 1, theta1, theta2,
462
+ facecolor='none', edgecolor='k', lw=3)
463
+
464
+ ax.add_artist(wedge)
465
+
466
+ ax.set_xlim(-2, 8)
467
+ ax.set_ylim(-2, 9)
468
+
469
+
470
+ def test_patch_str():
471
+ """
472
+ Check that patches have nice and working `str` representation.
473
+
474
+ Note that the logic is that `__str__` is defined such that:
475
+ str(eval(str(p))) == str(p)
476
+ """
477
+ p = mpatches.Circle(xy=(1, 2), radius=3)
478
+ assert str(p) == 'Circle(xy=(1, 2), radius=3)'
479
+
480
+ p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5)
481
+ assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)'
482
+
483
+ p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5)
484
+ assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)'
485
+
486
+ p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)
487
+ assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)'
488
+
489
+ p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)
490
+ expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)'
491
+ assert str(p) == expected
492
+
493
+ p = mpatches.Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)
494
+ expected = "Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)"
495
+ assert str(p) == expected
496
+
497
+ p = mpatches.RegularPolygon((1, 2), 20, radius=5)
498
+ assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)"
499
+
500
+ p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20)
501
+ assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)"
502
+
503
+ p = mpatches.FancyBboxPatch((1, 2), width=3, height=4)
504
+ assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)"
505
+
506
+ # Further nice __str__ which cannot be `eval`uated:
507
+ path = mpath.Path([(1, 2), (2, 2), (1, 2)], closed=True)
508
+ p = mpatches.PathPatch(path)
509
+ assert str(p) == "PathPatch3((1, 2) ...)"
510
+
511
+ p = mpatches.Polygon(np.empty((0, 2)))
512
+ assert str(p) == "Polygon0()"
513
+
514
+ data = [[1, 2], [2, 2], [1, 2]]
515
+ p = mpatches.Polygon(data)
516
+ assert str(p) == "Polygon3((1, 2) ...)"
517
+
518
+ p = mpatches.FancyArrowPatch(path=path)
519
+ assert str(p)[:27] == "FancyArrowPatch(Path(array("
520
+
521
+ p = mpatches.FancyArrowPatch((1, 2), (3, 4))
522
+ assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))"
523
+
524
+ p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data')
525
+ assert str(p) == "ConnectionPatch((1, 2), (3, 4))"
526
+
527
+ s = mpatches.Shadow(p, 1, 1)
528
+ assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))"
529
+
530
+ # Not testing Arrow, FancyArrow here
531
+ # because they seem to exist only for historical reasons.
532
+
533
+
534
+ @image_comparison(['multi_color_hatch'], remove_text=True, style='default')
535
+ def test_multi_color_hatch():
536
+ fig, ax = plt.subplots()
537
+
538
+ rects = ax.bar(range(5), range(1, 6))
539
+ for i, rect in enumerate(rects):
540
+ rect.set_facecolor('none')
541
+ rect.set_edgecolor(f'C{i}')
542
+ rect.set_hatch('/')
543
+
544
+ ax.autoscale_view()
545
+ ax.autoscale(False)
546
+
547
+ for i in range(5):
548
+ with mpl.style.context({'hatch.color': f'C{i}'}):
549
+ r = Rectangle((i - .8 / 2, 5), .8, 1, hatch='//', fc='none')
550
+ ax.add_patch(r)
551
+
552
+
553
+ @image_comparison(['units_rectangle.png'])
554
+ def test_units_rectangle():
555
+ import matplotlib.testing.jpl_units as U
556
+ U.register()
557
+
558
+ p = mpatches.Rectangle((5*U.km, 6*U.km), 1*U.km, 2*U.km)
559
+
560
+ fig, ax = plt.subplots()
561
+ ax.add_patch(p)
562
+ ax.set_xlim([4*U.km, 7*U.km])
563
+ ax.set_ylim([5*U.km, 9*U.km])
564
+
565
+
566
+ @image_comparison(['connection_patch.png'], style='mpl20', remove_text=True,
567
+ tol=0.024 if platform.machine() == 'arm64' else 0)
568
+ def test_connection_patch():
569
+ fig, (ax1, ax2) = plt.subplots(1, 2)
570
+
571
+ con = mpatches.ConnectionPatch(xyA=(0.1, 0.1), xyB=(0.9, 0.9),
572
+ coordsA='data', coordsB='data',
573
+ axesA=ax2, axesB=ax1,
574
+ arrowstyle="->")
575
+ ax2.add_artist(con)
576
+
577
+ xyA = (0.6, 1.0) # in axes coordinates
578
+ xyB = (0.0, 0.2) # x in axes coordinates, y in data coordinates
579
+ coordsA = "axes fraction"
580
+ coordsB = ax2.get_yaxis_transform()
581
+ con = mpatches.ConnectionPatch(xyA=xyA, xyB=xyB, coordsA=coordsA,
582
+ coordsB=coordsB, arrowstyle="-")
583
+ ax2.add_artist(con)
584
+
585
+
586
+ @check_figures_equal(extensions=["png"])
587
+ def test_connection_patch_fig(fig_test, fig_ref):
588
+ # Test that connection patch can be added as figure artist, and that figure
589
+ # pixels count negative values from the top right corner (this API may be
590
+ # changed in the future).
591
+ ax1, ax2 = fig_test.subplots(1, 2)
592
+ con = mpatches.ConnectionPatch(
593
+ xyA=(.3, .2), coordsA="data", axesA=ax1,
594
+ xyB=(-30, -20), coordsB="figure pixels",
595
+ arrowstyle="->", shrinkB=5)
596
+ fig_test.add_artist(con)
597
+
598
+ ax1, ax2 = fig_ref.subplots(1, 2)
599
+ bb = fig_ref.bbox
600
+ # Necessary so that pixel counts match on both sides.
601
+ plt.rcParams["savefig.dpi"] = plt.rcParams["figure.dpi"]
602
+ con = mpatches.ConnectionPatch(
603
+ xyA=(.3, .2), coordsA="data", axesA=ax1,
604
+ xyB=(bb.width - 30, bb.height - 20), coordsB="figure pixels",
605
+ arrowstyle="->", shrinkB=5)
606
+ fig_ref.add_artist(con)
607
+
608
+
609
+ def test_datetime_rectangle():
610
+ # Check that creating a rectangle with timedeltas doesn't fail
611
+ from datetime import datetime, timedelta
612
+
613
+ start = datetime(2017, 1, 1, 0, 0, 0)
614
+ delta = timedelta(seconds=16)
615
+ patch = mpatches.Rectangle((start, 0), delta, 1)
616
+
617
+ fig, ax = plt.subplots()
618
+ ax.add_patch(patch)
619
+
620
+
621
+ def test_datetime_datetime_fails():
622
+ from datetime import datetime
623
+
624
+ start = datetime(2017, 1, 1, 0, 0, 0)
625
+ dt_delta = datetime(1970, 1, 5) # Will be 5 days if units are done wrong.
626
+
627
+ with pytest.raises(TypeError):
628
+ mpatches.Rectangle((start, 0), dt_delta, 1)
629
+
630
+ with pytest.raises(TypeError):
631
+ mpatches.Rectangle((0, start), 1, dt_delta)
632
+
633
+
634
+ def test_contains_point():
635
+ ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0)
636
+ points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)]
637
+ path = ell.get_path()
638
+ transform = ell.get_transform()
639
+ radius = ell._process_radius(None)
640
+ expected = np.array([path.contains_point(point,
641
+ transform,
642
+ radius) for point in points])
643
+ result = np.array([ell.contains_point(point) for point in points])
644
+ assert np.all(result == expected)
645
+
646
+
647
+ def test_contains_points():
648
+ ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0)
649
+ points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)]
650
+ path = ell.get_path()
651
+ transform = ell.get_transform()
652
+ radius = ell._process_radius(None)
653
+ expected = path.contains_points(points, transform, radius)
654
+ result = ell.contains_points(points)
655
+ assert np.all(result == expected)
656
+
657
+
658
+ # Currently fails with pdf/svg, probably because some parts assume a dpi of 72.
659
+ @check_figures_equal(extensions=["png"])
660
+ def test_shadow(fig_test, fig_ref):
661
+ xy = np.array([.2, .3])
662
+ dxy = np.array([.1, .2])
663
+ # We need to work around the nonsensical (dpi-dependent) interpretation of
664
+ # offsets by the Shadow class...
665
+ plt.rcParams["savefig.dpi"] = "figure"
666
+ # Test image.
667
+ a1 = fig_test.subplots()
668
+ rect = mpatches.Rectangle(xy=xy, width=.5, height=.5)
669
+ shadow = mpatches.Shadow(rect, ox=dxy[0], oy=dxy[1])
670
+ a1.add_patch(rect)
671
+ a1.add_patch(shadow)
672
+ # Reference image.
673
+ a2 = fig_ref.subplots()
674
+ rect = mpatches.Rectangle(xy=xy, width=.5, height=.5)
675
+ shadow = mpatches.Rectangle(
676
+ xy=xy + fig_ref.dpi / 72 * dxy, width=.5, height=.5,
677
+ fc=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3,
678
+ ec=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3,
679
+ alpha=.5)
680
+ a2.add_patch(shadow)
681
+ a2.add_patch(rect)
682
+
683
+
684
+ def test_fancyarrow_units():
685
+ from datetime import datetime
686
+ # Smoke test to check that FancyArrowPatch works with units
687
+ dtime = datetime(2000, 1, 1)
688
+ fig, ax = plt.subplots()
689
+ arrow = FancyArrowPatch((0, dtime), (0.01, dtime))
690
+
691
+
692
+ def test_fancyarrow_setdata():
693
+ fig, ax = plt.subplots()
694
+ arrow = ax.arrow(0, 0, 10, 10, head_length=5, head_width=1, width=.5)
695
+ expected1 = np.array(
696
+ [[13.54, 13.54],
697
+ [10.35, 9.65],
698
+ [10.18, 9.82],
699
+ [0.18, -0.18],
700
+ [-0.18, 0.18],
701
+ [9.82, 10.18],
702
+ [9.65, 10.35],
703
+ [13.54, 13.54]]
704
+ )
705
+ assert np.allclose(expected1, np.round(arrow.verts, 2))
706
+
707
+ expected2 = np.array(
708
+ [[16.71, 16.71],
709
+ [16.71, 15.29],
710
+ [16.71, 15.29],
711
+ [1.71, 0.29],
712
+ [0.29, 1.71],
713
+ [15.29, 16.71],
714
+ [15.29, 16.71],
715
+ [16.71, 16.71]]
716
+ )
717
+ arrow.set_data(
718
+ x=1, y=1, dx=15, dy=15, width=2, head_width=2, head_length=1
719
+ )
720
+ assert np.allclose(expected2, np.round(arrow.verts, 2))
721
+
722
+
723
+ @image_comparison(["large_arc.svg"], style="mpl20")
724
+ def test_large_arc():
725
+ fig, (ax1, ax2) = plt.subplots(1, 2)
726
+ x = 210
727
+ y = -2115
728
+ diameter = 4261
729
+ for ax in [ax1, ax2]:
730
+ a = Arc((x, y), diameter, diameter, lw=2, color='k')
731
+ ax.add_patch(a)
732
+ ax.set_axis_off()
733
+ ax.set_aspect('equal')
734
+ # force the high accuracy case
735
+ ax1.set_xlim(7, 8)
736
+ ax1.set_ylim(5, 6)
737
+
738
+ # force the low accuracy case
739
+ ax2.set_xlim(-25000, 18000)
740
+ ax2.set_ylim(-20000, 6600)
741
+
742
+
743
+ @image_comparison(["all_quadrants_arcs.svg"], style="mpl20")
744
+ def test_rotated_arcs():
745
+ fig, ax_arr = plt.subplots(2, 2, squeeze=False, figsize=(10, 10))
746
+
747
+ scale = 10_000_000
748
+ diag_centers = ((-1, -1), (-1, 1), (1, 1), (1, -1))
749
+ on_axis_centers = ((0, 1), (1, 0), (0, -1), (-1, 0))
750
+ skews = ((2, 2), (2, 1/10), (2, 1/100), (2, 1/1000))
751
+
752
+ for ax, (sx, sy) in zip(ax_arr.ravel(), skews):
753
+ k = 0
754
+ for prescale, centers in zip((1 - .0001, (1 - .0001) / np.sqrt(2)),
755
+ (on_axis_centers, diag_centers)):
756
+ for j, (x_sign, y_sign) in enumerate(centers, start=k):
757
+ a = Arc(
758
+ (x_sign * scale * prescale,
759
+ y_sign * scale * prescale),
760
+ scale * sx,
761
+ scale * sy,
762
+ lw=4,
763
+ color=f"C{j}",
764
+ zorder=1 + j,
765
+ angle=np.rad2deg(np.arctan2(y_sign, x_sign)) % 360,
766
+ label=f'big {j}',
767
+ gid=f'big {j}'
768
+ )
769
+ ax.add_patch(a)
770
+
771
+ k = j+1
772
+ ax.set_xlim(-scale / 4000, scale / 4000)
773
+ ax.set_ylim(-scale / 4000, scale / 4000)
774
+ ax.axhline(0, color="k")
775
+ ax.axvline(0, color="k")
776
+ ax.set_axis_off()
777
+ ax.set_aspect("equal")
778
+
779
+
780
+ def test_fancyarrow_shape_error():
781
+ with pytest.raises(ValueError, match="Got unknown shape: 'foo'"):
782
+ FancyArrow(0, 0, 0.2, 0.2, shape='foo')
783
+
784
+
785
+ @pytest.mark.parametrize('fmt, match', (
786
+ ("foo", "Unknown style: 'foo'"),
787
+ ("Round,foo", "Incorrect style argument: 'Round,foo'"),
788
+ ))
789
+ def test_boxstyle_errors(fmt, match):
790
+ with pytest.raises(ValueError, match=match):
791
+ BoxStyle(fmt)
792
+
793
+
794
+ @image_comparison(baseline_images=['annulus'], extensions=['png'])
795
+ def test_annulus():
796
+
797
+ fig, ax = plt.subplots()
798
+ cir = Annulus((0.5, 0.5), 0.2, 0.05, fc='g') # circular annulus
799
+ ell = Annulus((0.5, 0.5), (0.5, 0.3), 0.1, 45, # elliptical
800
+ fc='m', ec='b', alpha=0.5, hatch='xxx')
801
+ ax.add_patch(cir)
802
+ ax.add_patch(ell)
803
+ ax.set_aspect('equal')
804
+
805
+
806
+ @image_comparison(baseline_images=['annulus'], extensions=['png'])
807
+ def test_annulus_setters():
808
+
809
+ fig, ax = plt.subplots()
810
+ cir = Annulus((0., 0.), 0.2, 0.01, fc='g') # circular annulus
811
+ ell = Annulus((0., 0.), (1, 2), 0.1, 0, # elliptical
812
+ fc='m', ec='b', alpha=0.5, hatch='xxx')
813
+ ax.add_patch(cir)
814
+ ax.add_patch(ell)
815
+ ax.set_aspect('equal')
816
+
817
+ cir.center = (0.5, 0.5)
818
+ cir.radii = 0.2
819
+ cir.width = 0.05
820
+
821
+ ell.center = (0.5, 0.5)
822
+ ell.radii = (0.5, 0.3)
823
+ ell.width = 0.1
824
+ ell.angle = 45
825
+
826
+
827
+ @image_comparison(baseline_images=['annulus'], extensions=['png'])
828
+ def test_annulus_setters2():
829
+
830
+ fig, ax = plt.subplots()
831
+ cir = Annulus((0., 0.), 0.2, 0.01, fc='g') # circular annulus
832
+ ell = Annulus((0., 0.), (1, 2), 0.1, 0, # elliptical
833
+ fc='m', ec='b', alpha=0.5, hatch='xxx')
834
+ ax.add_patch(cir)
835
+ ax.add_patch(ell)
836
+ ax.set_aspect('equal')
837
+
838
+ cir.center = (0.5, 0.5)
839
+ cir.set_semimajor(0.2)
840
+ cir.set_semiminor(0.2)
841
+ assert cir.radii == (0.2, 0.2)
842
+ cir.width = 0.05
843
+
844
+ ell.center = (0.5, 0.5)
845
+ ell.set_semimajor(0.5)
846
+ ell.set_semiminor(0.3)
847
+ assert ell.radii == (0.5, 0.3)
848
+ ell.width = 0.1
849
+ ell.angle = 45
850
+
851
+
852
+ def test_degenerate_polygon():
853
+ point = [0, 0]
854
+ correct_extents = Bbox([point, point]).extents
855
+ assert np.all(Polygon([point]).get_extents().extents == correct_extents)
856
+
857
+
858
+ @pytest.mark.parametrize('kwarg', ('edgecolor', 'facecolor'))
859
+ def test_color_override_warning(kwarg):
860
+ with pytest.warns(UserWarning,
861
+ match="Setting the 'color' property will override "
862
+ "the edgecolor or facecolor properties."):
863
+ Patch(color='black', **{kwarg: 'black'})
864
+
865
+
866
+ def test_empty_verts():
867
+ poly = Polygon(np.zeros((0, 2)))
868
+ assert poly.get_verts() == []
869
+
870
+
871
+ def test_default_antialiased():
872
+ patch = Patch()
873
+
874
+ patch.set_antialiased(not rcParams['patch.antialiased'])
875
+ assert patch.get_antialiased() == (not rcParams['patch.antialiased'])
876
+ # Check that None resets the state
877
+ patch.set_antialiased(None)
878
+ assert patch.get_antialiased() == rcParams['patch.antialiased']
879
+
880
+
881
+ def test_default_linestyle():
882
+ patch = Patch()
883
+ patch.set_linestyle('--')
884
+ patch.set_linestyle(None)
885
+ assert patch.get_linestyle() == 'solid'
886
+
887
+
888
+ def test_default_capstyle():
889
+ patch = Patch()
890
+ assert patch.get_capstyle() == 'butt'
891
+
892
+
893
+ def test_default_joinstyle():
894
+ patch = Patch()
895
+ assert patch.get_joinstyle() == 'miter'
896
+
897
+
898
+ @image_comparison(["autoscale_arc"], extensions=['png', 'svg'],
899
+ style="mpl20", remove_text=True)
900
+ def test_autoscale_arc():
901
+ fig, axs = plt.subplots(1, 3, figsize=(4, 1))
902
+ arc_lists = (
903
+ [Arc((0, 0), 1, 1, theta1=0, theta2=90)],
904
+ [Arc((0.5, 0.5), 1.5, 0.5, theta1=10, theta2=20)],
905
+ [Arc((0.5, 0.5), 1.5, 0.5, theta1=10, theta2=20),
906
+ Arc((0.5, 0.5), 2.5, 0.5, theta1=110, theta2=120),
907
+ Arc((0.5, 0.5), 3.5, 0.5, theta1=210, theta2=220),
908
+ Arc((0.5, 0.5), 4.5, 0.5, theta1=310, theta2=320)])
909
+
910
+ for ax, arcs in zip(axs, arc_lists):
911
+ for arc in arcs:
912
+ ax.add_patch(arc)
913
+ ax.autoscale()
914
+
915
+
916
+ @check_figures_equal(extensions=["png", 'svg', 'pdf', 'eps'])
917
+ def test_arc_in_collection(fig_test, fig_ref):
918
+ arc1 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20)
919
+ arc2 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20)
920
+ col = mcollections.PatchCollection(patches=[arc2], facecolors='none',
921
+ edgecolors='k')
922
+ fig_ref.subplots().add_patch(arc1)
923
+ fig_test.subplots().add_collection(col)
924
+
925
+
926
+ @check_figures_equal(extensions=["png", 'svg', 'pdf', 'eps'])
927
+ def test_modifying_arc(fig_test, fig_ref):
928
+ arc1 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20)
929
+ arc2 = Arc([.5, .5], 1.5, 1, theta1=0, theta2=60, angle=10)
930
+ fig_ref.subplots().add_patch(arc1)
931
+ fig_test.subplots().add_patch(arc2)
932
+ arc2.set_width(.5)
933
+ arc2.set_angle(20)
934
+
935
+
936
+ def test_arrow_set_data():
937
+ fig, ax = plt.subplots()
938
+ arrow = mpl.patches.Arrow(2, 0, 0, 10)
939
+ expected1 = np.array(
940
+ [[1.9, 0.],
941
+ [2.1, -0.],
942
+ [2.1, 8.],
943
+ [2.3, 8.],
944
+ [2., 10.],
945
+ [1.7, 8.],
946
+ [1.9, 8.],
947
+ [1.9, 0.]]
948
+ )
949
+ assert np.allclose(expected1, np.round(arrow.get_verts(), 2))
950
+
951
+ expected2 = np.array(
952
+ [[0.39, 0.04],
953
+ [0.61, -0.04],
954
+ [3.01, 6.36],
955
+ [3.24, 6.27],
956
+ [3.5, 8.],
957
+ [2.56, 6.53],
958
+ [2.79, 6.44],
959
+ [0.39, 0.04]]
960
+ )
961
+ arrow.set_data(x=.5, dx=3, dy=8, width=1.2)
962
+ assert np.allclose(expected2, np.round(arrow.get_verts(), 2))
parrot/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import difflib
2
+
3
+ import numpy as np
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import pytest
8
+
9
+ import matplotlib as mpl
10
+ from matplotlib.testing import subprocess_run_for_testing
11
+ from matplotlib import pyplot as plt
12
+
13
+
14
+ def test_pyplot_up_to_date(tmp_path):
15
+ pytest.importorskip("black")
16
+
17
+ gen_script = Path(mpl.__file__).parents[2] / "tools/boilerplate.py"
18
+ if not gen_script.exists():
19
+ pytest.skip("boilerplate.py not found")
20
+ orig_contents = Path(plt.__file__).read_text()
21
+ plt_file = tmp_path / 'pyplot.py'
22
+ plt_file.write_text(orig_contents, 'utf-8')
23
+
24
+ subprocess_run_for_testing(
25
+ [sys.executable, str(gen_script), str(plt_file)],
26
+ check=True)
27
+ new_contents = plt_file.read_text('utf-8')
28
+
29
+ if orig_contents != new_contents:
30
+ diff_msg = '\n'.join(
31
+ difflib.unified_diff(
32
+ orig_contents.split('\n'), new_contents.split('\n'),
33
+ fromfile='found pyplot.py',
34
+ tofile='expected pyplot.py',
35
+ n=0, lineterm=''))
36
+ pytest.fail(
37
+ "pyplot.py is not up-to-date. Please run "
38
+ "'python tools/boilerplate.py' to update pyplot.py. "
39
+ "This needs to be done from an environment where your "
40
+ "current working copy is installed (e.g. 'pip install -e'd). "
41
+ "Here is a diff of unexpected differences:\n%s" % diff_msg
42
+ )
43
+
44
+
45
+ def test_copy_docstring_and_deprecators(recwarn):
46
+ @mpl._api.rename_parameter(mpl.__version__, "old", "new")
47
+ @mpl._api.make_keyword_only(mpl.__version__, "kwo")
48
+ def func(new, kwo=None):
49
+ pass
50
+
51
+ @plt._copy_docstring_and_deprecators(func)
52
+ def wrapper_func(new, kwo=None):
53
+ pass
54
+
55
+ wrapper_func(None)
56
+ wrapper_func(new=None)
57
+ wrapper_func(None, kwo=None)
58
+ wrapper_func(new=None, kwo=None)
59
+ assert not recwarn
60
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
61
+ wrapper_func(old=None)
62
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
63
+ wrapper_func(None, None)
64
+
65
+
66
+ def test_pyplot_box():
67
+ fig, ax = plt.subplots()
68
+ plt.box(False)
69
+ assert not ax.get_frame_on()
70
+ plt.box(True)
71
+ assert ax.get_frame_on()
72
+ plt.box()
73
+ assert not ax.get_frame_on()
74
+ plt.box()
75
+ assert ax.get_frame_on()
76
+
77
+
78
+ def test_stackplot_smoke():
79
+ # Small smoke test for stackplot (see #12405)
80
+ plt.stackplot([1, 2, 3], [1, 2, 3])
81
+
82
+
83
+ def test_nrows_error():
84
+ with pytest.raises(TypeError):
85
+ plt.subplot(nrows=1)
86
+ with pytest.raises(TypeError):
87
+ plt.subplot(ncols=1)
88
+
89
+
90
+ def test_ioff():
91
+ plt.ion()
92
+ assert mpl.is_interactive()
93
+ with plt.ioff():
94
+ assert not mpl.is_interactive()
95
+ assert mpl.is_interactive()
96
+
97
+ plt.ioff()
98
+ assert not mpl.is_interactive()
99
+ with plt.ioff():
100
+ assert not mpl.is_interactive()
101
+ assert not mpl.is_interactive()
102
+
103
+
104
+ def test_ion():
105
+ plt.ioff()
106
+ assert not mpl.is_interactive()
107
+ with plt.ion():
108
+ assert mpl.is_interactive()
109
+ assert not mpl.is_interactive()
110
+
111
+ plt.ion()
112
+ assert mpl.is_interactive()
113
+ with plt.ion():
114
+ assert mpl.is_interactive()
115
+ assert mpl.is_interactive()
116
+
117
+
118
+ def test_nested_ion_ioff():
119
+ # initial state is interactive
120
+ plt.ion()
121
+
122
+ # mixed ioff/ion
123
+ with plt.ioff():
124
+ assert not mpl.is_interactive()
125
+ with plt.ion():
126
+ assert mpl.is_interactive()
127
+ assert not mpl.is_interactive()
128
+ assert mpl.is_interactive()
129
+
130
+ # redundant contexts
131
+ with plt.ioff():
132
+ with plt.ioff():
133
+ assert not mpl.is_interactive()
134
+ assert mpl.is_interactive()
135
+
136
+ with plt.ion():
137
+ plt.ioff()
138
+ assert mpl.is_interactive()
139
+
140
+ # initial state is not interactive
141
+ plt.ioff()
142
+
143
+ # mixed ioff/ion
144
+ with plt.ion():
145
+ assert mpl.is_interactive()
146
+ with plt.ioff():
147
+ assert not mpl.is_interactive()
148
+ assert mpl.is_interactive()
149
+ assert not mpl.is_interactive()
150
+
151
+ # redundant contexts
152
+ with plt.ion():
153
+ with plt.ion():
154
+ assert mpl.is_interactive()
155
+ assert not mpl.is_interactive()
156
+
157
+ with plt.ioff():
158
+ plt.ion()
159
+ assert not mpl.is_interactive()
160
+
161
+
162
+ def test_close():
163
+ try:
164
+ plt.close(1.1)
165
+ except TypeError as e:
166
+ assert str(e) == "close() argument must be a Figure, an int, " \
167
+ "a string, or None, not <class 'float'>"
168
+
169
+
170
+ def test_subplot_reuse():
171
+ ax1 = plt.subplot(121)
172
+ assert ax1 is plt.gca()
173
+ ax2 = plt.subplot(122)
174
+ assert ax2 is plt.gca()
175
+ ax3 = plt.subplot(121)
176
+ assert ax1 is plt.gca()
177
+ assert ax1 is ax3
178
+
179
+
180
+ def test_axes_kwargs():
181
+ # plt.axes() always creates new axes, even if axes kwargs differ.
182
+ plt.figure()
183
+ ax = plt.axes()
184
+ ax1 = plt.axes()
185
+ assert ax is not None
186
+ assert ax1 is not ax
187
+ plt.close()
188
+
189
+ plt.figure()
190
+ ax = plt.axes(projection='polar')
191
+ ax1 = plt.axes(projection='polar')
192
+ assert ax is not None
193
+ assert ax1 is not ax
194
+ plt.close()
195
+
196
+ plt.figure()
197
+ ax = plt.axes(projection='polar')
198
+ ax1 = plt.axes()
199
+ assert ax is not None
200
+ assert ax1.name == 'rectilinear'
201
+ assert ax1 is not ax
202
+ plt.close()
203
+
204
+
205
+ def test_subplot_replace_projection():
206
+ # plt.subplot() searches for axes with the same subplot spec, and if one
207
+ # exists, and the kwargs match returns it, create a new one if they do not
208
+ fig = plt.figure()
209
+ ax = plt.subplot(1, 2, 1)
210
+ ax1 = plt.subplot(1, 2, 1)
211
+ ax2 = plt.subplot(1, 2, 2)
212
+ ax3 = plt.subplot(1, 2, 1, projection='polar')
213
+ ax4 = plt.subplot(1, 2, 1, projection='polar')
214
+ assert ax is not None
215
+ assert ax1 is ax
216
+ assert ax2 is not ax
217
+ assert ax3 is not ax
218
+ assert ax3 is ax4
219
+
220
+ assert ax in fig.axes
221
+ assert ax2 in fig.axes
222
+ assert ax3 in fig.axes
223
+
224
+ assert ax.name == 'rectilinear'
225
+ assert ax2.name == 'rectilinear'
226
+ assert ax3.name == 'polar'
227
+
228
+
229
+ def test_subplot_kwarg_collision():
230
+ ax1 = plt.subplot(projection='polar', theta_offset=0)
231
+ ax2 = plt.subplot(projection='polar', theta_offset=0)
232
+ assert ax1 is ax2
233
+ ax1.remove()
234
+ ax3 = plt.subplot(projection='polar', theta_offset=1)
235
+ assert ax1 is not ax3
236
+ assert ax1 not in plt.gcf().axes
237
+
238
+
239
+ def test_gca():
240
+ # plt.gca() returns an existing axes, unless there were no axes.
241
+ plt.figure()
242
+ ax = plt.gca()
243
+ ax1 = plt.gca()
244
+ assert ax is not None
245
+ assert ax1 is ax
246
+ plt.close()
247
+
248
+
249
+ def test_subplot_projection_reuse():
250
+ # create an Axes
251
+ ax1 = plt.subplot(111)
252
+ # check that it is current
253
+ assert ax1 is plt.gca()
254
+ # make sure we get it back if we ask again
255
+ assert ax1 is plt.subplot(111)
256
+ # remove it
257
+ ax1.remove()
258
+ # create a polar plot
259
+ ax2 = plt.subplot(111, projection='polar')
260
+ assert ax2 is plt.gca()
261
+ # this should have deleted the first axes
262
+ assert ax1 not in plt.gcf().axes
263
+ # assert we get it back if no extra parameters passed
264
+ assert ax2 is plt.subplot(111)
265
+ ax2.remove()
266
+ # now check explicitly setting the projection to rectilinear
267
+ # makes a new axes
268
+ ax3 = plt.subplot(111, projection='rectilinear')
269
+ assert ax3 is plt.gca()
270
+ assert ax3 is not ax2
271
+ assert ax2 not in plt.gcf().axes
272
+
273
+
274
+ def test_subplot_polar_normalization():
275
+ ax1 = plt.subplot(111, projection='polar')
276
+ ax2 = plt.subplot(111, polar=True)
277
+ ax3 = plt.subplot(111, polar=True, projection='polar')
278
+ assert ax1 is ax2
279
+ assert ax1 is ax3
280
+
281
+ with pytest.raises(ValueError,
282
+ match="polar=True, yet projection='3d'"):
283
+ ax2 = plt.subplot(111, polar=True, projection='3d')
284
+
285
+
286
+ def test_subplot_change_projection():
287
+ created_axes = set()
288
+ ax = plt.subplot()
289
+ created_axes.add(ax)
290
+ projections = ('aitoff', 'hammer', 'lambert', 'mollweide',
291
+ 'polar', 'rectilinear', '3d')
292
+ for proj in projections:
293
+ ax.remove()
294
+ ax = plt.subplot(projection=proj)
295
+ assert ax is plt.subplot()
296
+ assert ax.name == proj
297
+ created_axes.add(ax)
298
+ # Check that each call created a new Axes.
299
+ assert len(created_axes) == 1 + len(projections)
300
+
301
+
302
+ def test_polar_second_call():
303
+ # the first call creates the axes with polar projection
304
+ ln1, = plt.polar(0., 1., 'ro')
305
+ assert isinstance(ln1, mpl.lines.Line2D)
306
+ # the second call should reuse the existing axes
307
+ ln2, = plt.polar(1.57, .5, 'bo')
308
+ assert isinstance(ln2, mpl.lines.Line2D)
309
+ assert ln1.axes is ln2.axes
310
+
311
+
312
+ def test_fallback_position():
313
+ # check that position kwarg works if rect not supplied
314
+ axref = plt.axes([0.2, 0.2, 0.5, 0.5])
315
+ axtest = plt.axes(position=[0.2, 0.2, 0.5, 0.5])
316
+ np.testing.assert_allclose(axtest.bbox.get_points(),
317
+ axref.bbox.get_points())
318
+
319
+ # check that position kwarg ignored if rect is supplied
320
+ axref = plt.axes([0.2, 0.2, 0.5, 0.5])
321
+ axtest = plt.axes([0.2, 0.2, 0.5, 0.5], position=[0.1, 0.1, 0.8, 0.8])
322
+ np.testing.assert_allclose(axtest.bbox.get_points(),
323
+ axref.bbox.get_points())
324
+
325
+
326
+ def test_set_current_figure_via_subfigure():
327
+ fig1 = plt.figure()
328
+ subfigs = fig1.subfigures(2)
329
+
330
+ plt.figure()
331
+ assert plt.gcf() != fig1
332
+
333
+ current = plt.figure(subfigs[1])
334
+ assert plt.gcf() == fig1
335
+ assert current == fig1
336
+
337
+
338
+ def test_set_current_axes_on_subfigure():
339
+ fig = plt.figure()
340
+ subfigs = fig.subfigures(2)
341
+
342
+ ax = subfigs[0].subplots(1, squeeze=True)
343
+ subfigs[1].subplots(1, squeeze=True)
344
+
345
+ assert plt.gca() != ax
346
+ plt.sca(ax)
347
+ assert plt.gca() == ax
348
+
349
+
350
+ def test_pylab_integration():
351
+ IPython = pytest.importorskip("IPython")
352
+ mpl.testing.subprocess_run_helper(
353
+ IPython.start_ipython,
354
+ "--pylab",
355
+ "-c",
356
+ ";".join((
357
+ "import matplotlib.pyplot as plt",
358
+ "assert plt._REPL_DISPLAYHOOK == plt._ReplDisplayHook.IPYTHON",
359
+ )),
360
+ timeout=60,
361
+ )
362
+
363
+
364
+ def test_doc_pyplot_summary():
365
+ """Test that pyplot_summary lists all the plot functions."""
366
+ pyplot_docs = Path(__file__).parent / '../../../doc/api/pyplot_summary.rst'
367
+ if not pyplot_docs.exists():
368
+ pytest.skip("Documentation sources not available")
369
+
370
+ def extract_documented_functions(lines):
371
+ """
372
+ Return a list of all the functions that are mentioned in the
373
+ autosummary blocks contained in *lines*.
374
+
375
+ An autosummary block looks like this::
376
+
377
+ .. autosummary::
378
+ :toctree: _as_gen
379
+ :template: autosummary.rst
380
+ :nosignatures:
381
+
382
+ plot
383
+ plot_date
384
+
385
+ """
386
+ functions = []
387
+ in_autosummary = False
388
+ for line in lines:
389
+ if not in_autosummary:
390
+ if line.startswith(".. autosummary::"):
391
+ in_autosummary = True
392
+ else:
393
+ if not line or line.startswith(" :"):
394
+ # empty line or autosummary parameter
395
+ continue
396
+ if not line[0].isspace():
397
+ # no more indentation: end of autosummary block
398
+ in_autosummary = False
399
+ continue
400
+ functions.append(line.strip())
401
+ return functions
402
+
403
+ lines = pyplot_docs.read_text().split("\n")
404
+ doc_functions = set(extract_documented_functions(lines))
405
+ plot_commands = set(plt._get_pyplot_commands())
406
+ missing = plot_commands.difference(doc_functions)
407
+ if missing:
408
+ raise AssertionError(
409
+ f"The following pyplot functions are not listed in the "
410
+ f"documentation. Please add them to doc/api/pyplot_summary.rst: "
411
+ f"{missing!r}")
412
+ extra = doc_functions.difference(plot_commands)
413
+ if extra:
414
+ raise AssertionError(
415
+ f"The following functions are listed in the pyplot documentation, "
416
+ f"but they do not exist in pyplot. "
417
+ f"Please remove them from doc/api/pyplot_summary.rst: {extra!r}")
418
+
419
+
420
+ def test_minor_ticks():
421
+ plt.figure()
422
+ plt.plot(np.arange(1, 10))
423
+ tick_pos, tick_labels = plt.xticks(minor=True)
424
+ assert np.all(tick_labels == np.array([], dtype=np.float64))
425
+ assert tick_labels == []
426
+
427
+ plt.yticks(ticks=[3.5, 6.5], labels=["a", "b"], minor=True)
428
+ ax = plt.gca()
429
+ tick_pos = ax.get_yticks(minor=True)
430
+ tick_labels = ax.get_yticklabels(minor=True)
431
+ assert np.all(tick_pos == np.array([3.5, 6.5]))
432
+ assert [l.get_text() for l in tick_labels] == ['a', 'b']
433
+
434
+
435
+ def test_switch_backend_no_close():
436
+ plt.switch_backend('agg')
437
+ fig = plt.figure()
438
+ fig = plt.figure()
439
+ assert len(plt.get_fignums()) == 2
440
+ plt.switch_backend('agg')
441
+ assert len(plt.get_fignums()) == 2
442
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
443
+ plt.switch_backend('svg')
444
+ assert len(plt.get_fignums()) == 0
445
+
446
+
447
+ def figure_hook_example(figure):
448
+ figure._test_was_here = True
449
+
450
+
451
+ def test_figure_hook():
452
+
453
+ test_rc = {
454
+ 'figure.hooks': ['matplotlib.tests.test_pyplot:figure_hook_example']
455
+ }
456
+ with mpl.rc_context(test_rc):
457
+ fig = plt.figure()
458
+
459
+ assert fig._test_was_here
parrot/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py ADDED
@@ -0,0 +1,225 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Tests for tinypages build using sphinx extensions."""
2
+
3
+ import filecmp
4
+ import os
5
+ from pathlib import Path
6
+ import shutil
7
+ import sys
8
+
9
+ from matplotlib.testing import subprocess_run_for_testing
10
+ import pytest
11
+
12
+
13
+ pytest.importorskip('sphinx',
14
+ minversion=None if sys.version_info < (3, 10) else '4.1.3')
15
+
16
+
17
+ def build_sphinx_html(source_dir, doctree_dir, html_dir, extra_args=None):
18
+ # Build the pages with warnings turned into errors
19
+ extra_args = [] if extra_args is None else extra_args
20
+ cmd = [sys.executable, '-msphinx', '-W', '-b', 'html',
21
+ '-d', str(doctree_dir), str(source_dir), str(html_dir), *extra_args]
22
+ proc = subprocess_run_for_testing(
23
+ cmd, capture_output=True, text=True,
24
+ env={**os.environ, "MPLBACKEND": ""})
25
+ out = proc.stdout
26
+ err = proc.stderr
27
+
28
+ assert proc.returncode == 0, \
29
+ f"sphinx build failed with stdout:\n{out}\nstderr:\n{err}\n"
30
+ if err:
31
+ pytest.fail(f"sphinx build emitted the following warnings:\n{err}")
32
+
33
+ assert html_dir.is_dir()
34
+
35
+
36
+ def test_tinypages(tmp_path):
37
+ shutil.copytree(Path(__file__).parent / 'tinypages', tmp_path,
38
+ dirs_exist_ok=True)
39
+ html_dir = tmp_path / '_build' / 'html'
40
+ img_dir = html_dir / '_images'
41
+ doctree_dir = tmp_path / 'doctrees'
42
+ # Build the pages with warnings turned into errors
43
+ cmd = [sys.executable, '-msphinx', '-W', '-b', 'html',
44
+ '-d', str(doctree_dir),
45
+ str(Path(__file__).parent / 'tinypages'), str(html_dir)]
46
+ # On CI, gcov emits warnings (due to agg headers being included with the
47
+ # same name in multiple extension modules -- but we don't care about their
48
+ # coverage anyways); hide them using GCOV_ERROR_FILE.
49
+ proc = subprocess_run_for_testing(
50
+ cmd, capture_output=True, text=True,
51
+ env={**os.environ, "MPLBACKEND": "", "GCOV_ERROR_FILE": os.devnull}
52
+ )
53
+ out = proc.stdout
54
+ err = proc.stderr
55
+
56
+ # Build the pages with warnings turned into errors
57
+ build_sphinx_html(tmp_path, doctree_dir, html_dir)
58
+
59
+ def plot_file(num):
60
+ return img_dir / f'some_plots-{num}.png'
61
+
62
+ def plot_directive_file(num):
63
+ # This is always next to the doctree dir.
64
+ return doctree_dir.parent / 'plot_directive' / f'some_plots-{num}.png'
65
+
66
+ range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)]
67
+ # Plot 5 is range(6) plot
68
+ assert filecmp.cmp(range_6, plot_file(5))
69
+ # Plot 7 is range(4) plot
70
+ assert filecmp.cmp(range_4, plot_file(7))
71
+ # Plot 11 is range(10) plot
72
+ assert filecmp.cmp(range_10, plot_file(11))
73
+ # Plot 12 uses the old range(10) figure and the new range(6) figure
74
+ assert filecmp.cmp(range_10, plot_file('12_00'))
75
+ assert filecmp.cmp(range_6, plot_file('12_01'))
76
+ # Plot 13 shows close-figs in action
77
+ assert filecmp.cmp(range_4, plot_file(13))
78
+ # Plot 14 has included source
79
+ html_contents = (html_dir / 'some_plots.html').read_bytes()
80
+
81
+ assert b'# Only a comment' in html_contents
82
+ # check plot defined in external file.
83
+ assert filecmp.cmp(range_4, img_dir / 'range4.png')
84
+ assert filecmp.cmp(range_6, img_dir / 'range6_range6.png')
85
+ # check if figure caption made it into html file
86
+ assert b'This is the caption for plot 15.' in html_contents
87
+ # check if figure caption using :caption: made it into html file
88
+ assert b'Plot 17 uses the caption option.' in html_contents
89
+ # check if figure caption made it into html file
90
+ assert b'This is the caption for plot 18.' in html_contents
91
+ # check if the custom classes made it into the html file
92
+ assert b'plot-directive my-class my-other-class' in html_contents
93
+ # check that the multi-image caption is applied twice
94
+ assert html_contents.count(b'This caption applies to both plots.') == 2
95
+ # Plot 21 is range(6) plot via an include directive. But because some of
96
+ # the previous plots are repeated, the argument to plot_file() is only 17.
97
+ assert filecmp.cmp(range_6, plot_file(17))
98
+ # plot 22 is from the range6.py file again, but a different function
99
+ assert filecmp.cmp(range_10, img_dir / 'range6_range10.png')
100
+
101
+ # Modify the included plot
102
+ contents = (tmp_path / 'included_plot_21.rst').read_bytes()
103
+ contents = contents.replace(b'plt.plot(range(6))', b'plt.plot(range(4))')
104
+ (tmp_path / 'included_plot_21.rst').write_bytes(contents)
105
+ # Build the pages again and check that the modified file was updated
106
+ modification_times = [plot_directive_file(i).stat().st_mtime
107
+ for i in (1, 2, 3, 5)]
108
+ build_sphinx_html(tmp_path, doctree_dir, html_dir)
109
+ assert filecmp.cmp(range_4, plot_file(17))
110
+ # Check that the plots in the plot_directive folder weren't changed.
111
+ # (plot_directive_file(1) won't be modified, but it will be copied to html/
112
+ # upon compilation, so plot_file(1) will be modified)
113
+ assert plot_directive_file(1).stat().st_mtime == modification_times[0]
114
+ assert plot_directive_file(2).stat().st_mtime == modification_times[1]
115
+ assert plot_directive_file(3).stat().st_mtime == modification_times[2]
116
+ assert filecmp.cmp(range_10, plot_file(1))
117
+ assert filecmp.cmp(range_6, plot_file(2))
118
+ assert filecmp.cmp(range_4, plot_file(3))
119
+ # Make sure that figures marked with context are re-created (but that the
120
+ # contents are the same)
121
+ assert plot_directive_file(5).stat().st_mtime > modification_times[3]
122
+ assert filecmp.cmp(range_6, plot_file(5))
123
+
124
+
125
+ def test_plot_html_show_source_link(tmp_path):
126
+ parent = Path(__file__).parent
127
+ shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py')
128
+ shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static')
129
+ doctree_dir = tmp_path / 'doctrees'
130
+ (tmp_path / 'index.rst').write_text("""
131
+ .. plot::
132
+
133
+ plt.plot(range(2))
134
+ """)
135
+ # Make sure source scripts are created by default
136
+ html_dir1 = tmp_path / '_build' / 'html1'
137
+ build_sphinx_html(tmp_path, doctree_dir, html_dir1)
138
+ assert len(list(html_dir1.glob("**/index-1.py"))) == 1
139
+ # Make sure source scripts are NOT created when
140
+ # plot_html_show_source_link` is False
141
+ html_dir2 = tmp_path / '_build' / 'html2'
142
+ build_sphinx_html(tmp_path, doctree_dir, html_dir2,
143
+ extra_args=['-D', 'plot_html_show_source_link=0'])
144
+ assert len(list(html_dir2.glob("**/index-1.py"))) == 0
145
+
146
+
147
+ @pytest.mark.parametrize('plot_html_show_source_link', [0, 1])
148
+ def test_show_source_link_true(tmp_path, plot_html_show_source_link):
149
+ # Test that a source link is generated if :show-source-link: is true,
150
+ # whether or not plot_html_show_source_link is true.
151
+ parent = Path(__file__).parent
152
+ shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py')
153
+ shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static')
154
+ doctree_dir = tmp_path / 'doctrees'
155
+ (tmp_path / 'index.rst').write_text("""
156
+ .. plot::
157
+ :show-source-link: true
158
+
159
+ plt.plot(range(2))
160
+ """)
161
+ html_dir = tmp_path / '_build' / 'html'
162
+ build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[
163
+ '-D', f'plot_html_show_source_link={plot_html_show_source_link}'])
164
+ assert len(list(html_dir.glob("**/index-1.py"))) == 1
165
+
166
+
167
+ @pytest.mark.parametrize('plot_html_show_source_link', [0, 1])
168
+ def test_show_source_link_false(tmp_path, plot_html_show_source_link):
169
+ # Test that a source link is NOT generated if :show-source-link: is false,
170
+ # whether or not plot_html_show_source_link is true.
171
+ parent = Path(__file__).parent
172
+ shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py')
173
+ shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static')
174
+ doctree_dir = tmp_path / 'doctrees'
175
+ (tmp_path / 'index.rst').write_text("""
176
+ .. plot::
177
+ :show-source-link: false
178
+
179
+ plt.plot(range(2))
180
+ """)
181
+ html_dir = tmp_path / '_build' / 'html'
182
+ build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[
183
+ '-D', f'plot_html_show_source_link={plot_html_show_source_link}'])
184
+ assert len(list(html_dir.glob("**/index-1.py"))) == 0
185
+
186
+
187
+ def test_srcset_version(tmp_path):
188
+ shutil.copytree(Path(__file__).parent / 'tinypages', tmp_path,
189
+ dirs_exist_ok=True)
190
+ html_dir = tmp_path / '_build' / 'html'
191
+ img_dir = html_dir / '_images'
192
+ doctree_dir = tmp_path / 'doctrees'
193
+
194
+ build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[
195
+ '-D', 'plot_srcset=2x'])
196
+
197
+ def plot_file(num, suff=''):
198
+ return img_dir / f'some_plots-{num}{suff}.png'
199
+
200
+ # check some-plots
201
+ for ind in [1, 2, 3, 5, 7, 11, 13, 15, 17]:
202
+ assert plot_file(ind).exists()
203
+ assert plot_file(ind, suff='.2x').exists()
204
+
205
+ assert (img_dir / 'nestedpage-index-1.png').exists()
206
+ assert (img_dir / 'nestedpage-index-1.2x.png').exists()
207
+ assert (img_dir / 'nestedpage-index-2.png').exists()
208
+ assert (img_dir / 'nestedpage-index-2.2x.png').exists()
209
+ assert (img_dir / 'nestedpage2-index-1.png').exists()
210
+ assert (img_dir / 'nestedpage2-index-1.2x.png').exists()
211
+ assert (img_dir / 'nestedpage2-index-2.png').exists()
212
+ assert (img_dir / 'nestedpage2-index-2.2x.png').exists()
213
+
214
+ # Check html for srcset
215
+
216
+ assert ('srcset="_images/some_plots-1.png, _images/some_plots-1.2x.png 2.00x"'
217
+ in (html_dir / 'some_plots.html').read_text(encoding='utf-8'))
218
+
219
+ st = ('srcset="../_images/nestedpage-index-1.png, '
220
+ '../_images/nestedpage-index-1.2x.png 2.00x"')
221
+ assert st in (html_dir / 'nestedpage/index.html').read_text(encoding='utf-8')
222
+
223
+ st = ('srcset="../_images/nestedpage2-index-2.png, '
224
+ '../_images/nestedpage2-index-2.2x.png 2.00x"')
225
+ assert st in (html_dir / 'nestedpage2/index.html').read_text(encoding='utf-8')
parrot/lib/python3.10/site-packages/matplotlib/tests/test_subplots.py ADDED
@@ -0,0 +1,287 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import platform
3
+
4
+ import numpy as np
5
+ import pytest
6
+
7
+ from matplotlib.axes import Axes, SubplotBase
8
+ import matplotlib.pyplot as plt
9
+ from matplotlib.testing.decorators import check_figures_equal, image_comparison
10
+
11
+
12
+ def check_shared(axs, x_shared, y_shared):
13
+ """
14
+ x_shared and y_shared are n x n boolean matrices; entry (i, j) indicates
15
+ whether the x (or y) axes of subplots i and j should be shared.
16
+ """
17
+ for (i1, ax1), (i2, ax2), (i3, (name, shared)) in itertools.product(
18
+ enumerate(axs),
19
+ enumerate(axs),
20
+ enumerate(zip("xy", [x_shared, y_shared]))):
21
+ if i2 <= i1:
22
+ continue
23
+ assert axs[0]._shared_axes[name].joined(ax1, ax2) == shared[i1, i2], \
24
+ "axes %i and %i incorrectly %ssharing %s axis" % (
25
+ i1, i2, "not " if shared[i1, i2] else "", name)
26
+
27
+
28
+ def check_ticklabel_visible(axs, x_visible, y_visible):
29
+ """Check that the x and y ticklabel visibility is as specified."""
30
+ for i, (ax, vx, vy) in enumerate(zip(axs, x_visible, y_visible)):
31
+ for l in ax.get_xticklabels() + [ax.xaxis.offsetText]:
32
+ assert l.get_visible() == vx, \
33
+ f"Visibility of x axis #{i} is incorrectly {vx}"
34
+ for l in ax.get_yticklabels() + [ax.yaxis.offsetText]:
35
+ assert l.get_visible() == vy, \
36
+ f"Visibility of y axis #{i} is incorrectly {vy}"
37
+ # axis label "visibility" is toggled by label_outer by resetting the
38
+ # label to empty, but it can also be empty to start with.
39
+ if not vx:
40
+ assert ax.get_xlabel() == ""
41
+ if not vy:
42
+ assert ax.get_ylabel() == ""
43
+
44
+
45
+ def check_tick1_visible(axs, x_visible, y_visible):
46
+ """
47
+ Check that the x and y tick visibility is as specified.
48
+
49
+ Note: This only checks the tick1line, i.e. bottom / left ticks.
50
+ """
51
+ for ax, visible, in zip(axs, x_visible):
52
+ for tick in ax.xaxis.get_major_ticks():
53
+ assert tick.tick1line.get_visible() == visible
54
+ for ax, y_visible, in zip(axs, y_visible):
55
+ for tick in ax.yaxis.get_major_ticks():
56
+ assert tick.tick1line.get_visible() == visible
57
+
58
+
59
+ def test_shared():
60
+ rdim = (4, 4, 2)
61
+ share = {
62
+ 'all': np.ones(rdim[:2], dtype=bool),
63
+ 'none': np.zeros(rdim[:2], dtype=bool),
64
+ 'row': np.array([
65
+ [False, True, False, False],
66
+ [True, False, False, False],
67
+ [False, False, False, True],
68
+ [False, False, True, False]]),
69
+ 'col': np.array([
70
+ [False, False, True, False],
71
+ [False, False, False, True],
72
+ [True, False, False, False],
73
+ [False, True, False, False]]),
74
+ }
75
+ visible = {
76
+ 'x': {
77
+ 'all': [False, False, True, True],
78
+ 'col': [False, False, True, True],
79
+ 'row': [True] * 4,
80
+ 'none': [True] * 4,
81
+ False: [True] * 4,
82
+ True: [False, False, True, True],
83
+ },
84
+ 'y': {
85
+ 'all': [True, False, True, False],
86
+ 'col': [True] * 4,
87
+ 'row': [True, False, True, False],
88
+ 'none': [True] * 4,
89
+ False: [True] * 4,
90
+ True: [True, False, True, False],
91
+ },
92
+ }
93
+ share[False] = share['none']
94
+ share[True] = share['all']
95
+
96
+ # test default
97
+ f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2)
98
+ axs = [a1, a2, a3, a4]
99
+ check_shared(axs, share['none'], share['none'])
100
+ plt.close(f)
101
+
102
+ # test all option combinations
103
+ ops = [False, True, 'all', 'none', 'row', 'col', 0, 1]
104
+ for xo in ops:
105
+ for yo in ops:
106
+ f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=xo, sharey=yo)
107
+ axs = [a1, a2, a3, a4]
108
+ check_shared(axs, share[xo], share[yo])
109
+ check_ticklabel_visible(axs, visible['x'][xo], visible['y'][yo])
110
+ plt.close(f)
111
+
112
+
113
+ @pytest.mark.parametrize('remove_ticks', [True, False])
114
+ def test_label_outer(remove_ticks):
115
+ f, axs = plt.subplots(2, 2, sharex=True, sharey=True)
116
+ for ax in axs.flat:
117
+ ax.set(xlabel="foo", ylabel="bar")
118
+ ax.label_outer(remove_inner_ticks=remove_ticks)
119
+ check_ticklabel_visible(
120
+ axs.flat, [False, False, True, True], [True, False, True, False])
121
+ if remove_ticks:
122
+ check_tick1_visible(
123
+ axs.flat, [False, False, True, True], [True, False, True, False])
124
+ else:
125
+ check_tick1_visible(
126
+ axs.flat, [True, True, True, True], [True, True, True, True])
127
+
128
+
129
+ def test_label_outer_span():
130
+ fig = plt.figure()
131
+ gs = fig.add_gridspec(3, 3)
132
+ # +---+---+---+
133
+ # | 1 | |
134
+ # +---+---+---+
135
+ # | | | 3 |
136
+ # + 2 +---+---+
137
+ # | | 4 | |
138
+ # +---+---+---+
139
+ a1 = fig.add_subplot(gs[0, 0:2])
140
+ a2 = fig.add_subplot(gs[1:3, 0])
141
+ a3 = fig.add_subplot(gs[1, 2])
142
+ a4 = fig.add_subplot(gs[2, 1])
143
+ for ax in fig.axes:
144
+ ax.label_outer()
145
+ check_ticklabel_visible(
146
+ fig.axes, [False, True, False, True], [True, True, False, False])
147
+
148
+
149
+ def test_label_outer_non_gridspec():
150
+ ax = plt.axes((0, 0, 1, 1))
151
+ ax.label_outer() # Does nothing.
152
+ check_ticklabel_visible([ax], [True], [True])
153
+
154
+
155
+ def test_shared_and_moved():
156
+ # test if sharey is on, but then tick_left is called that labels don't
157
+ # re-appear. Seaborn does this just to be sure yaxis is on left...
158
+ f, (a1, a2) = plt.subplots(1, 2, sharey=True)
159
+ check_ticklabel_visible([a2], [True], [False])
160
+ a2.yaxis.tick_left()
161
+ check_ticklabel_visible([a2], [True], [False])
162
+
163
+ f, (a1, a2) = plt.subplots(2, 1, sharex=True)
164
+ check_ticklabel_visible([a1], [False], [True])
165
+ a2.xaxis.tick_bottom()
166
+ check_ticklabel_visible([a1], [False], [True])
167
+
168
+
169
+ def test_exceptions():
170
+ # TODO should this test more options?
171
+ with pytest.raises(ValueError):
172
+ plt.subplots(2, 2, sharex='blah')
173
+ with pytest.raises(ValueError):
174
+ plt.subplots(2, 2, sharey='blah')
175
+
176
+
177
+ @image_comparison(['subplots_offset_text'],
178
+ tol=0.028 if platform.machine() == 'arm64' else 0)
179
+ def test_subplots_offsettext():
180
+ x = np.arange(0, 1e10, 1e9)
181
+ y = np.arange(0, 100, 10)+1e4
182
+ fig, axs = plt.subplots(2, 2, sharex='col', sharey='all')
183
+ axs[0, 0].plot(x, x)
184
+ axs[1, 0].plot(x, x)
185
+ axs[0, 1].plot(y, x)
186
+ axs[1, 1].plot(y, x)
187
+
188
+
189
+ @pytest.mark.parametrize("top", [True, False])
190
+ @pytest.mark.parametrize("bottom", [True, False])
191
+ @pytest.mark.parametrize("left", [True, False])
192
+ @pytest.mark.parametrize("right", [True, False])
193
+ def test_subplots_hide_ticklabels(top, bottom, left, right):
194
+ # Ideally, we would also test offset-text visibility (and remove
195
+ # test_subplots_offsettext), but currently, setting rcParams fails to move
196
+ # the offset texts as well.
197
+ with plt.rc_context({"xtick.labeltop": top, "xtick.labelbottom": bottom,
198
+ "ytick.labelleft": left, "ytick.labelright": right}):
199
+ axs = plt.figure().subplots(3, 3, sharex=True, sharey=True)
200
+ for (i, j), ax in np.ndenumerate(axs):
201
+ xtop = ax.xaxis._major_tick_kw["label2On"]
202
+ xbottom = ax.xaxis._major_tick_kw["label1On"]
203
+ yleft = ax.yaxis._major_tick_kw["label1On"]
204
+ yright = ax.yaxis._major_tick_kw["label2On"]
205
+ assert xtop == (top and i == 0)
206
+ assert xbottom == (bottom and i == 2)
207
+ assert yleft == (left and j == 0)
208
+ assert yright == (right and j == 2)
209
+
210
+
211
+ @pytest.mark.parametrize("xlabel_position", ["bottom", "top"])
212
+ @pytest.mark.parametrize("ylabel_position", ["left", "right"])
213
+ def test_subplots_hide_axislabels(xlabel_position, ylabel_position):
214
+ axs = plt.figure().subplots(3, 3, sharex=True, sharey=True)
215
+ for (i, j), ax in np.ndenumerate(axs):
216
+ ax.set(xlabel="foo", ylabel="bar")
217
+ ax.xaxis.set_label_position(xlabel_position)
218
+ ax.yaxis.set_label_position(ylabel_position)
219
+ ax.label_outer()
220
+ assert bool(ax.get_xlabel()) == (
221
+ xlabel_position == "bottom" and i == 2
222
+ or xlabel_position == "top" and i == 0)
223
+ assert bool(ax.get_ylabel()) == (
224
+ ylabel_position == "left" and j == 0
225
+ or ylabel_position == "right" and j == 2)
226
+
227
+
228
+ def test_get_gridspec():
229
+ # ahem, pretty trivial, but...
230
+ fig, ax = plt.subplots()
231
+ assert ax.get_subplotspec().get_gridspec() == ax.get_gridspec()
232
+
233
+
234
+ def test_dont_mutate_kwargs():
235
+ subplot_kw = {'sharex': 'all'}
236
+ gridspec_kw = {'width_ratios': [1, 2]}
237
+ fig, ax = plt.subplots(1, 2, subplot_kw=subplot_kw,
238
+ gridspec_kw=gridspec_kw)
239
+ assert subplot_kw == {'sharex': 'all'}
240
+ assert gridspec_kw == {'width_ratios': [1, 2]}
241
+
242
+
243
+ @pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]])
244
+ @pytest.mark.parametrize("height_ratios", [None, [1, 2]])
245
+ @check_figures_equal(extensions=['png'])
246
+ def test_width_and_height_ratios(fig_test, fig_ref,
247
+ height_ratios, width_ratios):
248
+ fig_test.subplots(2, 3, height_ratios=height_ratios,
249
+ width_ratios=width_ratios)
250
+ fig_ref.subplots(2, 3, gridspec_kw={
251
+ 'height_ratios': height_ratios,
252
+ 'width_ratios': width_ratios})
253
+
254
+
255
+ @pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]])
256
+ @pytest.mark.parametrize("height_ratios", [None, [1, 2]])
257
+ @check_figures_equal(extensions=['png'])
258
+ def test_width_and_height_ratios_mosaic(fig_test, fig_ref,
259
+ height_ratios, width_ratios):
260
+ mosaic_spec = [['A', 'B', 'B'], ['A', 'C', 'D']]
261
+ fig_test.subplot_mosaic(mosaic_spec, height_ratios=height_ratios,
262
+ width_ratios=width_ratios)
263
+ fig_ref.subplot_mosaic(mosaic_spec, gridspec_kw={
264
+ 'height_ratios': height_ratios,
265
+ 'width_ratios': width_ratios})
266
+
267
+
268
+ @pytest.mark.parametrize('method,args', [
269
+ ('subplots', (2, 3)),
270
+ ('subplot_mosaic', ('abc;def', ))
271
+ ]
272
+ )
273
+ def test_ratio_overlapping_kws(method, args):
274
+ with pytest.raises(ValueError, match='height_ratios'):
275
+ getattr(plt, method)(*args, height_ratios=[1, 2],
276
+ gridspec_kw={'height_ratios': [1, 2]})
277
+ with pytest.raises(ValueError, match='width_ratios'):
278
+ getattr(plt, method)(*args, width_ratios=[1, 2, 3],
279
+ gridspec_kw={'width_ratios': [1, 2, 3]})
280
+
281
+
282
+ def test_old_subplot_compat():
283
+ fig = plt.figure()
284
+ assert isinstance(fig.add_subplot(), SubplotBase)
285
+ assert not isinstance(fig.add_axes(rect=[0, 0, 1, 1]), SubplotBase)
286
+ with pytest.raises(TypeError):
287
+ Axes(fig, [0, 0, 1, 1], rect=[0, 0, 1, 1])
parrot/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py ADDED
@@ -0,0 +1,1875 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from contextlib import nullcontext
2
+ import itertools
3
+ import locale
4
+ import logging
5
+ import re
6
+ from packaging.version import parse as parse_version
7
+
8
+ import numpy as np
9
+ from numpy.testing import assert_almost_equal, assert_array_equal
10
+ import pytest
11
+
12
+ import matplotlib as mpl
13
+ import matplotlib.pyplot as plt
14
+ import matplotlib.ticker as mticker
15
+
16
+
17
+ class TestMaxNLocator:
18
+ basic_data = [
19
+ (20, 100, np.array([20., 40., 60., 80., 100.])),
20
+ (0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])),
21
+ (-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])),
22
+ (0, 0.85e-50, np.arange(6) * 2e-51),
23
+ (-0.85e-50, 0, np.arange(-5, 1) * 2e-51),
24
+ ]
25
+
26
+ integer_data = [
27
+ (-0.1, 1.1, None, np.array([-1, 0, 1, 2])),
28
+ (-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])),
29
+ (1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])),
30
+ ]
31
+
32
+ @pytest.mark.parametrize('vmin, vmax, expected', basic_data)
33
+ def test_basic(self, vmin, vmax, expected):
34
+ loc = mticker.MaxNLocator(nbins=5)
35
+ assert_almost_equal(loc.tick_values(vmin, vmax), expected)
36
+
37
+ @pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data)
38
+ def test_integer(self, vmin, vmax, steps, expected):
39
+ loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps)
40
+ assert_almost_equal(loc.tick_values(vmin, vmax), expected)
41
+
42
+ @pytest.mark.parametrize('kwargs, errortype, match', [
43
+ ({'foo': 0}, TypeError,
44
+ re.escape("set_params() got an unexpected keyword argument 'foo'")),
45
+ ({'steps': [2, 1]}, ValueError, "steps argument must be an increasing"),
46
+ ({'steps': 2}, ValueError, "steps argument must be an increasing"),
47
+ ({'steps': [2, 11]}, ValueError, "steps argument must be an increasing"),
48
+ ])
49
+ def test_errors(self, kwargs, errortype, match):
50
+ with pytest.raises(errortype, match=match):
51
+ mticker.MaxNLocator(**kwargs)
52
+
53
+ @pytest.mark.parametrize('steps, result', [
54
+ ([1, 2, 10], [1, 2, 10]),
55
+ ([2, 10], [1, 2, 10]),
56
+ ([1, 2], [1, 2, 10]),
57
+ ([2], [1, 2, 10]),
58
+ ])
59
+ def test_padding(self, steps, result):
60
+ loc = mticker.MaxNLocator(steps=steps)
61
+ assert (loc._steps == result).all()
62
+
63
+
64
+ class TestLinearLocator:
65
+ def test_basic(self):
66
+ loc = mticker.LinearLocator(numticks=3)
67
+ test_value = np.array([-0.8, -0.3, 0.2])
68
+ assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value)
69
+
70
+ def test_zero_numticks(self):
71
+ loc = mticker.LinearLocator(numticks=0)
72
+ loc.tick_values(-0.8, 0.2) == []
73
+
74
+ def test_set_params(self):
75
+ """
76
+ Create linear locator with presets={}, numticks=2 and change it to
77
+ something else. See if change was successful. Should not exception.
78
+ """
79
+ loc = mticker.LinearLocator(numticks=2)
80
+ loc.set_params(numticks=8, presets={(0, 1): []})
81
+ assert loc.numticks == 8
82
+ assert loc.presets == {(0, 1): []}
83
+
84
+ def test_presets(self):
85
+ loc = mticker.LinearLocator(presets={(1, 2): [1, 1.25, 1.75],
86
+ (0, 2): [0.5, 1.5]})
87
+ assert loc.tick_values(1, 2) == [1, 1.25, 1.75]
88
+ assert loc.tick_values(2, 1) == [1, 1.25, 1.75]
89
+ assert loc.tick_values(0, 2) == [0.5, 1.5]
90
+ assert loc.tick_values(0.0, 2.0) == [0.5, 1.5]
91
+ assert (loc.tick_values(0, 1) == np.linspace(0, 1, 11)).all()
92
+
93
+
94
+ class TestMultipleLocator:
95
+ def test_basic(self):
96
+ loc = mticker.MultipleLocator(base=3.147)
97
+ test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294,
98
+ 9.441, 12.588])
99
+ assert_almost_equal(loc.tick_values(-7, 10), test_value)
100
+
101
+ def test_basic_with_offset(self):
102
+ loc = mticker.MultipleLocator(base=3.147, offset=1.2)
103
+ test_value = np.array([-8.241, -5.094, -1.947, 1.2, 4.347, 7.494,
104
+ 10.641])
105
+ assert_almost_equal(loc.tick_values(-7, 10), test_value)
106
+
107
+ def test_view_limits(self):
108
+ """
109
+ Test basic behavior of view limits.
110
+ """
111
+ with mpl.rc_context({'axes.autolimit_mode': 'data'}):
112
+ loc = mticker.MultipleLocator(base=3.147)
113
+ assert_almost_equal(loc.view_limits(-5, 5), (-5, 5))
114
+
115
+ def test_view_limits_round_numbers(self):
116
+ """
117
+ Test that everything works properly with 'round_numbers' for auto
118
+ limit.
119
+ """
120
+ with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
121
+ loc = mticker.MultipleLocator(base=3.147)
122
+ assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294))
123
+
124
+ def test_view_limits_round_numbers_with_offset(self):
125
+ """
126
+ Test that everything works properly with 'round_numbers' for auto
127
+ limit.
128
+ """
129
+ with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
130
+ loc = mticker.MultipleLocator(base=3.147, offset=1.3)
131
+ assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447))
132
+
133
+ def test_view_limits_single_bin(self):
134
+ """
135
+ Test that 'round_numbers' works properly with a single bin.
136
+ """
137
+ with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}):
138
+ loc = mticker.MaxNLocator(nbins=1)
139
+ assert_almost_equal(loc.view_limits(-2.3, 2.3), (-4, 4))
140
+
141
+ def test_set_params(self):
142
+ """
143
+ Create multiple locator with 0.7 base, and change it to something else.
144
+ See if change was successful.
145
+ """
146
+ mult = mticker.MultipleLocator(base=0.7)
147
+ mult.set_params(base=1.7)
148
+ assert mult._edge.step == 1.7
149
+ mult.set_params(offset=3)
150
+ assert mult._offset == 3
151
+
152
+
153
+ class TestAutoMinorLocator:
154
+ def test_basic(self):
155
+ fig, ax = plt.subplots()
156
+ ax.set_xlim(0, 1.39)
157
+ ax.minorticks_on()
158
+ test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45,
159
+ 0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9,
160
+ 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35])
161
+ assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
162
+
163
+ # NB: the following values are assuming that *xlim* is [0, 5]
164
+ params = [
165
+ (0, 0), # no major tick => no minor tick either
166
+ (1, 0) # a single major tick => no minor tick
167
+ ]
168
+
169
+ def test_first_and_last_minorticks(self):
170
+ """
171
+ Test that first and last minor tick appear as expected.
172
+ """
173
+ # This test is related to issue #22331
174
+ fig, ax = plt.subplots()
175
+ ax.set_xlim(-1.9, 1.9)
176
+ ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
177
+ test_value = np.array([-1.9, -1.8, -1.7, -1.6, -1.4, -1.3, -1.2, -1.1,
178
+ -0.9, -0.8, -0.7, -0.6, -0.4, -0.3, -0.2, -0.1,
179
+ 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.1,
180
+ 1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9])
181
+ assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
182
+
183
+ ax.set_xlim(-5, 5)
184
+ test_value = np.array([-5.0, -4.5, -3.5, -3.0, -2.5, -1.5, -1.0, -0.5,
185
+ 0.5, 1.0, 1.5, 2.5, 3.0, 3.5, 4.5, 5.0])
186
+ assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value)
187
+
188
+ @pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params)
189
+ def test_low_number_of_majorticks(
190
+ self, nb_majorticks, expected_nb_minorticks):
191
+ # This test is related to issue #8804
192
+ fig, ax = plt.subplots()
193
+ xlims = (0, 5) # easier to test the different code paths
194
+ ax.set_xlim(*xlims)
195
+ ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks))
196
+ ax.minorticks_on()
197
+ ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
198
+ assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks
199
+
200
+ majorstep_minordivisions = [(1, 5),
201
+ (2, 4),
202
+ (2.5, 5),
203
+ (5, 5),
204
+ (10, 5)]
205
+
206
+ # This test is meant to verify the parameterization for
207
+ # test_number_of_minor_ticks
208
+ def test_using_all_default_major_steps(self):
209
+ with mpl.rc_context({'_internal.classic_mode': False}):
210
+ majorsteps = [x[0] for x in self.majorstep_minordivisions]
211
+ np.testing.assert_allclose(majorsteps,
212
+ mticker.AutoLocator()._steps)
213
+
214
+ @pytest.mark.parametrize('major_step, expected_nb_minordivisions',
215
+ majorstep_minordivisions)
216
+ def test_number_of_minor_ticks(
217
+ self, major_step, expected_nb_minordivisions):
218
+ fig, ax = plt.subplots()
219
+ xlims = (0, major_step)
220
+ ax.set_xlim(*xlims)
221
+ ax.set_xticks(xlims)
222
+ ax.minorticks_on()
223
+ ax.xaxis.set_minor_locator(mticker.AutoMinorLocator())
224
+ nb_minor_divisions = len(ax.xaxis.get_minorticklocs()) + 1
225
+ assert nb_minor_divisions == expected_nb_minordivisions
226
+
227
+ limits = [(0, 1.39), (0, 0.139),
228
+ (0, 0.11e-19), (0, 0.112e-12),
229
+ (-2.0e-07, -3.3e-08), (1.20e-06, 1.42e-06),
230
+ (-1.34e-06, -1.44e-06), (-8.76e-07, -1.51e-06)]
231
+
232
+ reference = [
233
+ [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,
234
+ 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35],
235
+ [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, 0.065,
236
+ 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, 0.125, 0.13,
237
+ 0.135],
238
+ [5.00e-22, 1.00e-21, 1.50e-21, 2.50e-21, 3.00e-21, 3.50e-21, 4.50e-21,
239
+ 5.00e-21, 5.50e-21, 6.50e-21, 7.00e-21, 7.50e-21, 8.50e-21, 9.00e-21,
240
+ 9.50e-21, 1.05e-20, 1.10e-20],
241
+ [5.00e-15, 1.00e-14, 1.50e-14, 2.50e-14, 3.00e-14, 3.50e-14, 4.50e-14,
242
+ 5.00e-14, 5.50e-14, 6.50e-14, 7.00e-14, 7.50e-14, 8.50e-14, 9.00e-14,
243
+ 9.50e-14, 1.05e-13, 1.10e-13],
244
+ [-1.95e-07, -1.90e-07, -1.85e-07, -1.75e-07, -1.70e-07, -1.65e-07,
245
+ -1.55e-07, -1.50e-07, -1.45e-07, -1.35e-07, -1.30e-07, -1.25e-07,
246
+ -1.15e-07, -1.10e-07, -1.05e-07, -9.50e-08, -9.00e-08, -8.50e-08,
247
+ -7.50e-08, -7.00e-08, -6.50e-08, -5.50e-08, -5.00e-08, -4.50e-08,
248
+ -3.50e-08],
249
+ [1.21e-06, 1.22e-06, 1.23e-06, 1.24e-06, 1.26e-06, 1.27e-06, 1.28e-06,
250
+ 1.29e-06, 1.31e-06, 1.32e-06, 1.33e-06, 1.34e-06, 1.36e-06, 1.37e-06,
251
+ 1.38e-06, 1.39e-06, 1.41e-06, 1.42e-06],
252
+ [-1.435e-06, -1.430e-06, -1.425e-06, -1.415e-06, -1.410e-06,
253
+ -1.405e-06, -1.395e-06, -1.390e-06, -1.385e-06, -1.375e-06,
254
+ -1.370e-06, -1.365e-06, -1.355e-06, -1.350e-06, -1.345e-06],
255
+ [-1.48e-06, -1.46e-06, -1.44e-06, -1.42e-06, -1.38e-06, -1.36e-06,
256
+ -1.34e-06, -1.32e-06, -1.28e-06, -1.26e-06, -1.24e-06, -1.22e-06,
257
+ -1.18e-06, -1.16e-06, -1.14e-06, -1.12e-06, -1.08e-06, -1.06e-06,
258
+ -1.04e-06, -1.02e-06, -9.80e-07, -9.60e-07, -9.40e-07, -9.20e-07,
259
+ -8.80e-07]]
260
+
261
+ additional_data = list(zip(limits, reference))
262
+
263
+ @pytest.mark.parametrize('lim, ref', additional_data)
264
+ def test_additional(self, lim, ref):
265
+ fig, ax = plt.subplots()
266
+
267
+ ax.minorticks_on()
268
+ ax.grid(True, 'minor', 'y', linewidth=1)
269
+ ax.grid(True, 'major', color='k', linewidth=1)
270
+ ax.set_ylim(lim)
271
+
272
+ assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
273
+
274
+ @pytest.mark.parametrize('use_rcparam', [False, True])
275
+ @pytest.mark.parametrize(
276
+ 'lim, ref', [
277
+ ((0, 1.39),
278
+ [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7,
279
+ 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]),
280
+ ((0, 0.139),
281
+ [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055,
282
+ 0.065, 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115,
283
+ 0.125, 0.13, 0.135]),
284
+ ])
285
+ def test_number_of_minor_ticks_auto(self, lim, ref, use_rcparam):
286
+ if use_rcparam:
287
+ context = {'xtick.minor.ndivs': 'auto', 'ytick.minor.ndivs': 'auto'}
288
+ kwargs = {}
289
+ else:
290
+ context = {}
291
+ kwargs = {'n': 'auto'}
292
+
293
+ with mpl.rc_context(context):
294
+ fig, ax = plt.subplots()
295
+ ax.set_xlim(*lim)
296
+ ax.set_ylim(*lim)
297
+ ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
298
+ ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
299
+ assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)
300
+ assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
301
+
302
+ @pytest.mark.parametrize('use_rcparam', [False, True])
303
+ @pytest.mark.parametrize(
304
+ 'n, lim, ref', [
305
+ (2, (0, 4), [0.5, 1.5, 2.5, 3.5]),
306
+ (4, (0, 2), [0.25, 0.5, 0.75, 1.25, 1.5, 1.75]),
307
+ (10, (0, 1), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]),
308
+ ])
309
+ def test_number_of_minor_ticks_int(self, n, lim, ref, use_rcparam):
310
+ if use_rcparam:
311
+ context = {'xtick.minor.ndivs': n, 'ytick.minor.ndivs': n}
312
+ kwargs = {}
313
+ else:
314
+ context = {}
315
+ kwargs = {'n': n}
316
+
317
+ with mpl.rc_context(context):
318
+ fig, ax = plt.subplots()
319
+ ax.set_xlim(*lim)
320
+ ax.set_ylim(*lim)
321
+ ax.xaxis.set_major_locator(mticker.MultipleLocator(1))
322
+ ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
323
+ ax.yaxis.set_major_locator(mticker.MultipleLocator(1))
324
+ ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs))
325
+ assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref)
326
+ assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref)
327
+
328
+
329
+ class TestLogLocator:
330
+ def test_basic(self):
331
+ loc = mticker.LogLocator(numticks=5)
332
+ with pytest.raises(ValueError):
333
+ loc.tick_values(0, 1000)
334
+
335
+ test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01,
336
+ 1.00000000e+01, 1.00000000e+03, 1.00000000e+05,
337
+ 1.00000000e+07, 1.000000000e+09])
338
+ assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value)
339
+
340
+ loc = mticker.LogLocator(base=2)
341
+ test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.])
342
+ assert_almost_equal(loc.tick_values(1, 100), test_value)
343
+
344
+ def test_polar_axes(self):
345
+ """
346
+ Polar Axes have a different ticking logic.
347
+ """
348
+ fig, ax = plt.subplots(subplot_kw={'projection': 'polar'})
349
+ ax.set_yscale('log')
350
+ ax.set_ylim(1, 100)
351
+ assert_array_equal(ax.get_yticks(), [10, 100, 1000])
352
+
353
+ def test_switch_to_autolocator(self):
354
+ loc = mticker.LogLocator(subs="all")
355
+ assert_array_equal(loc.tick_values(0.45, 0.55),
356
+ [0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56])
357
+ # check that we *skip* 1.0, and 10, because this is a minor locator
358
+ loc = mticker.LogLocator(subs=np.arange(2, 10))
359
+ assert 1.0 not in loc.tick_values(0.9, 20.)
360
+ assert 10.0 not in loc.tick_values(0.9, 20.)
361
+
362
+ def test_set_params(self):
363
+ """
364
+ Create log locator with default value, base=10.0, subs=[1.0],
365
+ numdecs=4, numticks=15 and change it to something else.
366
+ See if change was successful. Should not raise exception.
367
+ """
368
+ loc = mticker.LogLocator()
369
+ with pytest.warns(mpl.MatplotlibDeprecationWarning, match="numdecs"):
370
+ loc.set_params(numticks=7, numdecs=8, subs=[2.0], base=4)
371
+ assert loc.numticks == 7
372
+ with pytest.warns(mpl.MatplotlibDeprecationWarning, match="numdecs"):
373
+ assert loc.numdecs == 8
374
+ assert loc._base == 4
375
+ assert list(loc._subs) == [2.0]
376
+
377
+ def test_tick_values_correct(self):
378
+ ll = mticker.LogLocator(subs=(1, 2, 5))
379
+ test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,
380
+ 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,
381
+ 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,
382
+ 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,
383
+ 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08])
384
+ assert_almost_equal(ll.tick_values(1, 1e7), test_value)
385
+
386
+ def test_tick_values_not_empty(self):
387
+ mpl.rcParams['_internal.classic_mode'] = False
388
+ ll = mticker.LogLocator(subs=(1, 2, 5))
389
+ test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00,
390
+ 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02,
391
+ 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04,
392
+ 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06,
393
+ 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08,
394
+ 1.e+09, 2.e+09, 5.e+09])
395
+ assert_almost_equal(ll.tick_values(1, 1e8), test_value)
396
+
397
+ def test_multiple_shared_axes(self):
398
+ rng = np.random.default_rng(19680801)
399
+ dummy_data = [rng.normal(size=100), [], []]
400
+ fig, axes = plt.subplots(len(dummy_data), sharex=True, sharey=True)
401
+
402
+ for ax, data in zip(axes.flatten(), dummy_data):
403
+ ax.hist(data, bins=10)
404
+ ax.set_yscale('log', nonpositive='clip')
405
+
406
+ for ax in axes.flatten():
407
+ assert all(ax.get_yticks() == axes[0].get_yticks())
408
+ assert ax.get_ylim() == axes[0].get_ylim()
409
+
410
+
411
+ class TestNullLocator:
412
+ def test_set_params(self):
413
+ """
414
+ Create null locator, and attempt to call set_params() on it.
415
+ Should not exception, and should raise a warning.
416
+ """
417
+ loc = mticker.NullLocator()
418
+ with pytest.warns(UserWarning):
419
+ loc.set_params()
420
+
421
+
422
+ class _LogitHelper:
423
+ @staticmethod
424
+ def isclose(x, y):
425
+ return (np.isclose(-np.log(1/x-1), -np.log(1/y-1))
426
+ if 0 < x < 1 and 0 < y < 1 else False)
427
+
428
+ @staticmethod
429
+ def assert_almost_equal(x, y):
430
+ ax = np.array(x)
431
+ ay = np.array(y)
432
+ assert np.all(ax > 0) and np.all(ax < 1)
433
+ assert np.all(ay > 0) and np.all(ay < 1)
434
+ lx = -np.log(1/ax-1)
435
+ ly = -np.log(1/ay-1)
436
+ assert_almost_equal(lx, ly)
437
+
438
+
439
+ class TestLogitLocator:
440
+ ref_basic_limits = [
441
+ (5e-2, 1 - 5e-2),
442
+ (5e-3, 1 - 5e-3),
443
+ (5e-4, 1 - 5e-4),
444
+ (5e-5, 1 - 5e-5),
445
+ (5e-6, 1 - 5e-6),
446
+ (5e-7, 1 - 5e-7),
447
+ (5e-8, 1 - 5e-8),
448
+ (5e-9, 1 - 5e-9),
449
+ ]
450
+
451
+ ref_basic_major_ticks = [
452
+ 1 / (10 ** np.arange(1, 3)),
453
+ 1 / (10 ** np.arange(1, 4)),
454
+ 1 / (10 ** np.arange(1, 5)),
455
+ 1 / (10 ** np.arange(1, 6)),
456
+ 1 / (10 ** np.arange(1, 7)),
457
+ 1 / (10 ** np.arange(1, 8)),
458
+ 1 / (10 ** np.arange(1, 9)),
459
+ 1 / (10 ** np.arange(1, 10)),
460
+ ]
461
+
462
+ ref_maxn_limits = [(0.4, 0.6), (5e-2, 2e-1), (1 - 2e-1, 1 - 5e-2)]
463
+
464
+ @pytest.mark.parametrize(
465
+ "lims, expected_low_ticks",
466
+ zip(ref_basic_limits, ref_basic_major_ticks),
467
+ )
468
+ def test_basic_major(self, lims, expected_low_ticks):
469
+ """
470
+ Create logit locator with huge number of major, and tests ticks.
471
+ """
472
+ expected_ticks = sorted(
473
+ [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]
474
+ )
475
+ loc = mticker.LogitLocator(nbins=100)
476
+ _LogitHelper.assert_almost_equal(
477
+ loc.tick_values(*lims),
478
+ expected_ticks
479
+ )
480
+
481
+ @pytest.mark.parametrize("lims", ref_maxn_limits)
482
+ def test_maxn_major(self, lims):
483
+ """
484
+ When the axis is zoomed, the locator must have the same behavior as
485
+ MaxNLocator.
486
+ """
487
+ loc = mticker.LogitLocator(nbins=100)
488
+ maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10])
489
+ for nbins in (4, 8, 16):
490
+ loc.set_params(nbins=nbins)
491
+ maxn_loc.set_params(nbins=nbins)
492
+ ticks = loc.tick_values(*lims)
493
+ maxn_ticks = maxn_loc.tick_values(*lims)
494
+ assert ticks.shape == maxn_ticks.shape
495
+ assert (ticks == maxn_ticks).all()
496
+
497
+ @pytest.mark.parametrize("lims", ref_basic_limits + ref_maxn_limits)
498
+ def test_nbins_major(self, lims):
499
+ """
500
+ Assert logit locator for respecting nbins param.
501
+ """
502
+
503
+ basic_needed = int(-np.floor(np.log10(lims[0]))) * 2 + 1
504
+ loc = mticker.LogitLocator(nbins=100)
505
+ for nbins in range(basic_needed, 2, -1):
506
+ loc.set_params(nbins=nbins)
507
+ assert len(loc.tick_values(*lims)) <= nbins + 2
508
+
509
+ @pytest.mark.parametrize(
510
+ "lims, expected_low_ticks",
511
+ zip(ref_basic_limits, ref_basic_major_ticks),
512
+ )
513
+ def test_minor(self, lims, expected_low_ticks):
514
+ """
515
+ In large scale, test the presence of minor,
516
+ and assert no minor when major are subsampled.
517
+ """
518
+
519
+ expected_ticks = sorted(
520
+ [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)]
521
+ )
522
+ basic_needed = len(expected_ticks)
523
+ loc = mticker.LogitLocator(nbins=100)
524
+ minor_loc = mticker.LogitLocator(nbins=100, minor=True)
525
+ for nbins in range(basic_needed, 2, -1):
526
+ loc.set_params(nbins=nbins)
527
+ minor_loc.set_params(nbins=nbins)
528
+ major_ticks = loc.tick_values(*lims)
529
+ minor_ticks = minor_loc.tick_values(*lims)
530
+ if len(major_ticks) >= len(expected_ticks):
531
+ # no subsample, we must have a lot of minors ticks
532
+ assert (len(major_ticks) - 1) * 5 < len(minor_ticks)
533
+ else:
534
+ # subsample
535
+ _LogitHelper.assert_almost_equal(
536
+ sorted([*major_ticks, *minor_ticks]), expected_ticks)
537
+
538
+ def test_minor_attr(self):
539
+ loc = mticker.LogitLocator(nbins=100)
540
+ assert not loc.minor
541
+ loc.minor = True
542
+ assert loc.minor
543
+ loc.set_params(minor=False)
544
+ assert not loc.minor
545
+
546
+ acceptable_vmin_vmax = [
547
+ *(2.5 ** np.arange(-3, 0)),
548
+ *(1 - 2.5 ** np.arange(-3, 0)),
549
+ ]
550
+
551
+ @pytest.mark.parametrize(
552
+ "lims",
553
+ [
554
+ (a, b)
555
+ for (a, b) in itertools.product(acceptable_vmin_vmax, repeat=2)
556
+ if a != b
557
+ ],
558
+ )
559
+ def test_nonsingular_ok(self, lims):
560
+ """
561
+ Create logit locator, and test the nonsingular method for acceptable
562
+ value
563
+ """
564
+ loc = mticker.LogitLocator()
565
+ lims2 = loc.nonsingular(*lims)
566
+ assert sorted(lims) == sorted(lims2)
567
+
568
+ @pytest.mark.parametrize("okval", acceptable_vmin_vmax)
569
+ def test_nonsingular_nok(self, okval):
570
+ """
571
+ Create logit locator, and test the nonsingular method for non
572
+ acceptable value
573
+ """
574
+ loc = mticker.LogitLocator()
575
+ vmin, vmax = (-1, okval)
576
+ vmin2, vmax2 = loc.nonsingular(vmin, vmax)
577
+ assert vmax2 == vmax
578
+ assert 0 < vmin2 < vmax2
579
+ vmin, vmax = (okval, 2)
580
+ vmin2, vmax2 = loc.nonsingular(vmin, vmax)
581
+ assert vmin2 == vmin
582
+ assert vmin2 < vmax2 < 1
583
+
584
+
585
+ class TestFixedLocator:
586
+ def test_set_params(self):
587
+ """
588
+ Create fixed locator with 5 nbins, and change it to something else.
589
+ See if change was successful.
590
+ Should not exception.
591
+ """
592
+ fixed = mticker.FixedLocator(range(0, 24), nbins=5)
593
+ fixed.set_params(nbins=7)
594
+ assert fixed.nbins == 7
595
+
596
+
597
+ class TestIndexLocator:
598
+ def test_set_params(self):
599
+ """
600
+ Create index locator with 3 base, 4 offset. and change it to something
601
+ else. See if change was successful.
602
+ Should not exception.
603
+ """
604
+ index = mticker.IndexLocator(base=3, offset=4)
605
+ index.set_params(base=7, offset=7)
606
+ assert index._base == 7
607
+ assert index.offset == 7
608
+
609
+
610
+ class TestSymmetricalLogLocator:
611
+ def test_set_params(self):
612
+ """
613
+ Create symmetrical log locator with default subs =[1.0] numticks = 15,
614
+ and change it to something else.
615
+ See if change was successful.
616
+ Should not exception.
617
+ """
618
+ sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
619
+ sym.set_params(subs=[2.0], numticks=8)
620
+ assert sym._subs == [2.0]
621
+ assert sym.numticks == 8
622
+
623
+ @pytest.mark.parametrize(
624
+ 'vmin, vmax, expected',
625
+ [
626
+ (0, 1, [0, 1]),
627
+ (-1, 1, [-1, 0, 1]),
628
+ ],
629
+ )
630
+ def test_values(self, vmin, vmax, expected):
631
+ # https://github.com/matplotlib/matplotlib/issues/25945
632
+ sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
633
+ ticks = sym.tick_values(vmin=vmin, vmax=vmax)
634
+ assert_array_equal(ticks, expected)
635
+
636
+ def test_subs(self):
637
+ sym = mticker.SymmetricalLogLocator(base=10, linthresh=1, subs=[2.0, 4.0])
638
+ sym.create_dummy_axis()
639
+ sym.axis.set_view_interval(-10, 10)
640
+ assert (sym() == [-20., -40., -2., -4., 0., 2., 4., 20., 40.]).all()
641
+
642
+ def test_extending(self):
643
+ sym = mticker.SymmetricalLogLocator(base=10, linthresh=1)
644
+ sym.create_dummy_axis()
645
+ sym.axis.set_view_interval(8, 9)
646
+ assert (sym() == [1.0]).all()
647
+ sym.axis.set_view_interval(8, 12)
648
+ assert (sym() == [1.0, 10.0]).all()
649
+ assert sym.view_limits(10, 10) == (1, 100)
650
+ assert sym.view_limits(-10, -10) == (-100, -1)
651
+ assert sym.view_limits(0, 0) == (-0.001, 0.001)
652
+
653
+
654
+ class TestAsinhLocator:
655
+ def test_init(self):
656
+ lctr = mticker.AsinhLocator(linear_width=2.718, numticks=19)
657
+ assert lctr.linear_width == 2.718
658
+ assert lctr.numticks == 19
659
+ assert lctr.base == 10
660
+
661
+ def test_set_params(self):
662
+ lctr = mticker.AsinhLocator(linear_width=5,
663
+ numticks=17, symthresh=0.125,
664
+ base=4, subs=(2.5, 3.25))
665
+ assert lctr.numticks == 17
666
+ assert lctr.symthresh == 0.125
667
+ assert lctr.base == 4
668
+ assert lctr.subs == (2.5, 3.25)
669
+
670
+ lctr.set_params(numticks=23)
671
+ assert lctr.numticks == 23
672
+ lctr.set_params(None)
673
+ assert lctr.numticks == 23
674
+
675
+ lctr.set_params(symthresh=0.5)
676
+ assert lctr.symthresh == 0.5
677
+ lctr.set_params(symthresh=None)
678
+ assert lctr.symthresh == 0.5
679
+
680
+ lctr.set_params(base=7)
681
+ assert lctr.base == 7
682
+ lctr.set_params(base=None)
683
+ assert lctr.base == 7
684
+
685
+ lctr.set_params(subs=(2, 4.125))
686
+ assert lctr.subs == (2, 4.125)
687
+ lctr.set_params(subs=None)
688
+ assert lctr.subs == (2, 4.125)
689
+ lctr.set_params(subs=[])
690
+ assert lctr.subs is None
691
+
692
+ def test_linear_values(self):
693
+ lctr = mticker.AsinhLocator(linear_width=100, numticks=11, base=0)
694
+
695
+ assert_almost_equal(lctr.tick_values(-1, 1),
696
+ np.arange(-1, 1.01, 0.2))
697
+ assert_almost_equal(lctr.tick_values(-0.1, 0.1),
698
+ np.arange(-0.1, 0.101, 0.02))
699
+ assert_almost_equal(lctr.tick_values(-0.01, 0.01),
700
+ np.arange(-0.01, 0.0101, 0.002))
701
+
702
+ def test_wide_values(self):
703
+ lctr = mticker.AsinhLocator(linear_width=0.1, numticks=11, base=0)
704
+
705
+ assert_almost_equal(lctr.tick_values(-100, 100),
706
+ [-100, -20, -5, -1, -0.2,
707
+ 0, 0.2, 1, 5, 20, 100])
708
+ assert_almost_equal(lctr.tick_values(-1000, 1000),
709
+ [-1000, -100, -20, -3, -0.4,
710
+ 0, 0.4, 3, 20, 100, 1000])
711
+
712
+ def test_near_zero(self):
713
+ """Check that manually injected zero will supersede nearby tick"""
714
+ lctr = mticker.AsinhLocator(linear_width=100, numticks=3, base=0)
715
+
716
+ assert_almost_equal(lctr.tick_values(-1.1, 0.9), [-1.0, 0.0, 0.9])
717
+
718
+ def test_fallback(self):
719
+ lctr = mticker.AsinhLocator(1.0, numticks=11)
720
+
721
+ assert_almost_equal(lctr.tick_values(101, 102),
722
+ np.arange(101, 102.01, 0.1))
723
+
724
+ def test_symmetrizing(self):
725
+ lctr = mticker.AsinhLocator(linear_width=1, numticks=3,
726
+ symthresh=0.25, base=0)
727
+ lctr.create_dummy_axis()
728
+
729
+ lctr.axis.set_view_interval(-1, 2)
730
+ assert_almost_equal(lctr(), [-1, 0, 2])
731
+
732
+ lctr.axis.set_view_interval(-1, 0.9)
733
+ assert_almost_equal(lctr(), [-1, 0, 1])
734
+
735
+ lctr.axis.set_view_interval(-0.85, 1.05)
736
+ assert_almost_equal(lctr(), [-1, 0, 1])
737
+
738
+ lctr.axis.set_view_interval(1, 1.1)
739
+ assert_almost_equal(lctr(), [1, 1.05, 1.1])
740
+
741
+ def test_base_rounding(self):
742
+ lctr10 = mticker.AsinhLocator(linear_width=1, numticks=8,
743
+ base=10, subs=(1, 3, 5))
744
+ assert_almost_equal(lctr10.tick_values(-110, 110),
745
+ [-500, -300, -100, -50, -30, -10, -5, -3, -1,
746
+ -0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5,
747
+ 1, 3, 5, 10, 30, 50, 100, 300, 500])
748
+
749
+ lctr5 = mticker.AsinhLocator(linear_width=1, numticks=20, base=5)
750
+ assert_almost_equal(lctr5.tick_values(-1050, 1050),
751
+ [-625, -125, -25, -5, -1, -0.2, 0,
752
+ 0.2, 1, 5, 25, 125, 625])
753
+
754
+
755
+ class TestScalarFormatter:
756
+ offset_data = [
757
+ (123, 189, 0),
758
+ (-189, -123, 0),
759
+ (12341, 12349, 12340),
760
+ (-12349, -12341, -12340),
761
+ (99999.5, 100010.5, 100000),
762
+ (-100010.5, -99999.5, -100000),
763
+ (99990.5, 100000.5, 100000),
764
+ (-100000.5, -99990.5, -100000),
765
+ (1233999, 1234001, 1234000),
766
+ (-1234001, -1233999, -1234000),
767
+ (1, 1, 1),
768
+ (123, 123, 0),
769
+ # Test cases courtesy of @WeatherGod
770
+ (.4538, .4578, .45),
771
+ (3789.12, 3783.1, 3780),
772
+ (45124.3, 45831.75, 45000),
773
+ (0.000721, 0.0007243, 0.00072),
774
+ (12592.82, 12591.43, 12590),
775
+ (9., 12., 0),
776
+ (900., 1200., 0),
777
+ (1900., 1200., 0),
778
+ (0.99, 1.01, 1),
779
+ (9.99, 10.01, 10),
780
+ (99.99, 100.01, 100),
781
+ (5.99, 6.01, 6),
782
+ (15.99, 16.01, 16),
783
+ (-0.452, 0.492, 0),
784
+ (-0.492, 0.492, 0),
785
+ (12331.4, 12350.5, 12300),
786
+ (-12335.3, 12335.3, 0),
787
+ ]
788
+
789
+ use_offset_data = [True, False]
790
+
791
+ useMathText_data = [True, False]
792
+
793
+ # (sci_type, scilimits, lim, orderOfMag, fewticks)
794
+ scilimits_data = [
795
+ (False, (0, 0), (10.0, 20.0), 0, False),
796
+ (True, (-2, 2), (-10, 20), 0, False),
797
+ (True, (-2, 2), (-20, 10), 0, False),
798
+ (True, (-2, 2), (-110, 120), 2, False),
799
+ (True, (-2, 2), (-120, 110), 2, False),
800
+ (True, (-2, 2), (-.001, 0.002), -3, False),
801
+ (True, (-7, 7), (0.18e10, 0.83e10), 9, True),
802
+ (True, (0, 0), (-1e5, 1e5), 5, False),
803
+ (True, (6, 6), (-1e5, 1e5), 6, False),
804
+ ]
805
+
806
+ cursor_data = [
807
+ [0., "0.000"],
808
+ [0.0123, "0.012"],
809
+ [0.123, "0.123"],
810
+ [1.23, "1.230"],
811
+ [12.3, "12.300"],
812
+ ]
813
+
814
+ format_data = [
815
+ (.1, "1e-1"),
816
+ (.11, "1.1e-1"),
817
+ (1e8, "1e8"),
818
+ (1.1e8, "1.1e8"),
819
+ ]
820
+
821
+ @pytest.mark.parametrize('unicode_minus, result',
822
+ [(True, "\N{MINUS SIGN}1"), (False, "-1")])
823
+ def test_unicode_minus(self, unicode_minus, result):
824
+ mpl.rcParams['axes.unicode_minus'] = unicode_minus
825
+ assert (
826
+ plt.gca().xaxis.get_major_formatter().format_data_short(-1).strip()
827
+ == result)
828
+
829
+ @pytest.mark.parametrize('left, right, offset', offset_data)
830
+ def test_offset_value(self, left, right, offset):
831
+ fig, ax = plt.subplots()
832
+ formatter = ax.xaxis.get_major_formatter()
833
+
834
+ with (pytest.warns(UserWarning, match='Attempting to set identical')
835
+ if left == right else nullcontext()):
836
+ ax.set_xlim(left, right)
837
+ ax.xaxis._update_ticks()
838
+ assert formatter.offset == offset
839
+
840
+ with (pytest.warns(UserWarning, match='Attempting to set identical')
841
+ if left == right else nullcontext()):
842
+ ax.set_xlim(right, left)
843
+ ax.xaxis._update_ticks()
844
+ assert formatter.offset == offset
845
+
846
+ @pytest.mark.parametrize('use_offset', use_offset_data)
847
+ def test_use_offset(self, use_offset):
848
+ with mpl.rc_context({'axes.formatter.useoffset': use_offset}):
849
+ tmp_form = mticker.ScalarFormatter()
850
+ assert use_offset == tmp_form.get_useOffset()
851
+ assert tmp_form.offset == 0
852
+
853
+ @pytest.mark.parametrize('use_math_text', useMathText_data)
854
+ def test_useMathText(self, use_math_text):
855
+ with mpl.rc_context({'axes.formatter.use_mathtext': use_math_text}):
856
+ tmp_form = mticker.ScalarFormatter()
857
+ assert use_math_text == tmp_form.get_useMathText()
858
+
859
+ def test_set_use_offset_float(self):
860
+ tmp_form = mticker.ScalarFormatter()
861
+ tmp_form.set_useOffset(0.5)
862
+ assert not tmp_form.get_useOffset()
863
+ assert tmp_form.offset == 0.5
864
+
865
+ def test_use_locale(self):
866
+ conv = locale.localeconv()
867
+ sep = conv['thousands_sep']
868
+ if not sep or conv['grouping'][-1:] in ([], [locale.CHAR_MAX]):
869
+ pytest.skip('Locale does not apply grouping') # pragma: no cover
870
+
871
+ with mpl.rc_context({'axes.formatter.use_locale': True}):
872
+ tmp_form = mticker.ScalarFormatter()
873
+ assert tmp_form.get_useLocale()
874
+
875
+ tmp_form.create_dummy_axis()
876
+ tmp_form.axis.set_data_interval(0, 10)
877
+ tmp_form.set_locs([1, 2, 3])
878
+ assert sep in tmp_form(1e9)
879
+
880
+ @pytest.mark.parametrize(
881
+ 'sci_type, scilimits, lim, orderOfMag, fewticks', scilimits_data)
882
+ def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks):
883
+ tmp_form = mticker.ScalarFormatter()
884
+ tmp_form.set_scientific(sci_type)
885
+ tmp_form.set_powerlimits(scilimits)
886
+ fig, ax = plt.subplots()
887
+ ax.yaxis.set_major_formatter(tmp_form)
888
+ ax.set_ylim(*lim)
889
+ if fewticks:
890
+ ax.yaxis.set_major_locator(mticker.MaxNLocator(4))
891
+
892
+ tmp_form.set_locs(ax.yaxis.get_majorticklocs())
893
+ assert orderOfMag == tmp_form.orderOfMagnitude
894
+
895
+ @pytest.mark.parametrize('value, expected', format_data)
896
+ def test_format_data(self, value, expected):
897
+ mpl.rcParams['axes.unicode_minus'] = False
898
+ sf = mticker.ScalarFormatter()
899
+ assert sf.format_data(value) == expected
900
+
901
+ @pytest.mark.parametrize('data, expected', cursor_data)
902
+ def test_cursor_precision(self, data, expected):
903
+ fig, ax = plt.subplots()
904
+ ax.set_xlim(-1, 1) # Pointing precision of 0.001.
905
+ fmt = ax.xaxis.get_major_formatter().format_data_short
906
+ assert fmt(data) == expected
907
+
908
+ @pytest.mark.parametrize('data, expected', cursor_data)
909
+ def test_cursor_dummy_axis(self, data, expected):
910
+ # Issue #17624
911
+ sf = mticker.ScalarFormatter()
912
+ sf.create_dummy_axis()
913
+ sf.axis.set_view_interval(0, 10)
914
+ fmt = sf.format_data_short
915
+ assert fmt(data) == expected
916
+ assert sf.axis.get_tick_space() == 9
917
+ assert sf.axis.get_minpos() == 0
918
+
919
+ def test_mathtext_ticks(self):
920
+ mpl.rcParams.update({
921
+ 'font.family': 'serif',
922
+ 'font.serif': 'cmr10',
923
+ 'axes.formatter.use_mathtext': False
924
+ })
925
+
926
+ if parse_version(pytest.__version__).major < 8:
927
+ with pytest.warns(UserWarning, match='cmr10 font should ideally'):
928
+ fig, ax = plt.subplots()
929
+ ax.set_xticks([-1, 0, 1])
930
+ fig.canvas.draw()
931
+ else:
932
+ with (pytest.warns(UserWarning, match="Glyph 8722"),
933
+ pytest.warns(UserWarning, match='cmr10 font should ideally')):
934
+ fig, ax = plt.subplots()
935
+ ax.set_xticks([-1, 0, 1])
936
+ fig.canvas.draw()
937
+
938
+ def test_cmr10_substitutions(self, caplog):
939
+ mpl.rcParams.update({
940
+ 'font.family': 'cmr10',
941
+ 'mathtext.fontset': 'cm',
942
+ 'axes.formatter.use_mathtext': True,
943
+ })
944
+
945
+ # Test that it does not log a warning about missing glyphs.
946
+ with caplog.at_level(logging.WARNING, logger='matplotlib.mathtext'):
947
+ fig, ax = plt.subplots()
948
+ ax.plot([-0.03, 0.05], [40, 0.05])
949
+ ax.set_yscale('log')
950
+ yticks = [0.02, 0.3, 4, 50]
951
+ formatter = mticker.LogFormatterSciNotation()
952
+ ax.set_yticks(yticks, map(formatter, yticks))
953
+ fig.canvas.draw()
954
+ assert not caplog.text
955
+
956
+ def test_empty_locs(self):
957
+ sf = mticker.ScalarFormatter()
958
+ sf.set_locs([])
959
+ assert sf(0.5) == ''
960
+
961
+
962
+ class TestLogFormatterExponent:
963
+ param_data = [
964
+ (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0),
965
+ ['-3', '-2', '-1', '0', '1', '2', '3']),
966
+ # With labelOnlyBase=False, non-integer powers should be nicely
967
+ # formatted.
968
+ (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]),
969
+ range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']),
970
+ (False, 50, np.array([3, 5, 12, 42], dtype=float), range(6),
971
+ ['3', '5', '12', '42']),
972
+ ]
973
+
974
+ base_data = [2.0, 5.0, 10.0, np.pi, np.e]
975
+
976
+ @pytest.mark.parametrize(
977
+ 'labelOnlyBase, exponent, locs, positions, expected', param_data)
978
+ @pytest.mark.parametrize('base', base_data)
979
+ def test_basic(self, labelOnlyBase, base, exponent, locs, positions,
980
+ expected):
981
+ formatter = mticker.LogFormatterExponent(base=base,
982
+ labelOnlyBase=labelOnlyBase)
983
+ formatter.create_dummy_axis()
984
+ formatter.axis.set_view_interval(1, base**exponent)
985
+ vals = base**locs
986
+ labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)]
987
+ expected = [label.replace('-', '\N{Minus Sign}') for label in expected]
988
+ assert labels == expected
989
+
990
+ def test_blank(self):
991
+ # Should be a blank string for non-integer powers if labelOnlyBase=True
992
+ formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True)
993
+ formatter.create_dummy_axis()
994
+ formatter.axis.set_view_interval(1, 10)
995
+ assert formatter(10**0.1) == ''
996
+
997
+
998
+ class TestLogFormatterMathtext:
999
+ fmt = mticker.LogFormatterMathtext()
1000
+ test_data = [
1001
+ (0, 1, '$\\mathdefault{10^{0}}$'),
1002
+ (0, 1e-2, '$\\mathdefault{10^{-2}}$'),
1003
+ (0, 1e2, '$\\mathdefault{10^{2}}$'),
1004
+ (3, 1, '$\\mathdefault{1}$'),
1005
+ (3, 1e-2, '$\\mathdefault{0.01}$'),
1006
+ (3, 1e2, '$\\mathdefault{100}$'),
1007
+ (3, 1e-3, '$\\mathdefault{10^{-3}}$'),
1008
+ (3, 1e3, '$\\mathdefault{10^{3}}$'),
1009
+ ]
1010
+
1011
+ @pytest.mark.parametrize('min_exponent, value, expected', test_data)
1012
+ def test_min_exponent(self, min_exponent, value, expected):
1013
+ with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}):
1014
+ assert self.fmt(value) == expected
1015
+
1016
+
1017
+ class TestLogFormatterSciNotation:
1018
+ test_data = [
1019
+ (2, 0.03125, '$\\mathdefault{2^{-5}}$'),
1020
+ (2, 1, '$\\mathdefault{2^{0}}$'),
1021
+ (2, 32, '$\\mathdefault{2^{5}}$'),
1022
+ (2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'),
1023
+ (2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'),
1024
+ (2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'),
1025
+ (10, -1, '$\\mathdefault{-10^{0}}$'),
1026
+ (10, 1e-05, '$\\mathdefault{10^{-5}}$'),
1027
+ (10, 1, '$\\mathdefault{10^{0}}$'),
1028
+ (10, 100000, '$\\mathdefault{10^{5}}$'),
1029
+ (10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'),
1030
+ (10, 2, '$\\mathdefault{2\\times10^{0}}$'),
1031
+ (10, 200000, '$\\mathdefault{2\\times10^{5}}$'),
1032
+ (10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'),
1033
+ (10, 5, '$\\mathdefault{5\\times10^{0}}$'),
1034
+ (10, 500000, '$\\mathdefault{5\\times10^{5}}$'),
1035
+ ]
1036
+
1037
+ @mpl.style.context('default')
1038
+ @pytest.mark.parametrize('base, value, expected', test_data)
1039
+ def test_basic(self, base, value, expected):
1040
+ formatter = mticker.LogFormatterSciNotation(base=base)
1041
+ with mpl.rc_context({'text.usetex': False}):
1042
+ assert formatter(value) == expected
1043
+
1044
+
1045
+ class TestLogFormatter:
1046
+ pprint_data = [
1047
+ (3.141592654e-05, 0.001, '3.142e-5'),
1048
+ (0.0003141592654, 0.001, '3.142e-4'),
1049
+ (0.003141592654, 0.001, '3.142e-3'),
1050
+ (0.03141592654, 0.001, '3.142e-2'),
1051
+ (0.3141592654, 0.001, '3.142e-1'),
1052
+ (3.141592654, 0.001, '3.142'),
1053
+ (31.41592654, 0.001, '3.142e1'),
1054
+ (314.1592654, 0.001, '3.142e2'),
1055
+ (3141.592654, 0.001, '3.142e3'),
1056
+ (31415.92654, 0.001, '3.142e4'),
1057
+ (314159.2654, 0.001, '3.142e5'),
1058
+ (1e-05, 0.001, '1e-5'),
1059
+ (0.0001, 0.001, '1e-4'),
1060
+ (0.001, 0.001, '1e-3'),
1061
+ (0.01, 0.001, '1e-2'),
1062
+ (0.1, 0.001, '1e-1'),
1063
+ (1, 0.001, '1'),
1064
+ (10, 0.001, '10'),
1065
+ (100, 0.001, '100'),
1066
+ (1000, 0.001, '1000'),
1067
+ (10000, 0.001, '1e4'),
1068
+ (100000, 0.001, '1e5'),
1069
+ (3.141592654e-05, 0.015, '0'),
1070
+ (0.0003141592654, 0.015, '0'),
1071
+ (0.003141592654, 0.015, '0.003'),
1072
+ (0.03141592654, 0.015, '0.031'),
1073
+ (0.3141592654, 0.015, '0.314'),
1074
+ (3.141592654, 0.015, '3.142'),
1075
+ (31.41592654, 0.015, '31.416'),
1076
+ (314.1592654, 0.015, '314.159'),
1077
+ (3141.592654, 0.015, '3141.593'),
1078
+ (31415.92654, 0.015, '31415.927'),
1079
+ (314159.2654, 0.015, '314159.265'),
1080
+ (1e-05, 0.015, '0'),
1081
+ (0.0001, 0.015, '0'),
1082
+ (0.001, 0.015, '0.001'),
1083
+ (0.01, 0.015, '0.01'),
1084
+ (0.1, 0.015, '0.1'),
1085
+ (1, 0.015, '1'),
1086
+ (10, 0.015, '10'),
1087
+ (100, 0.015, '100'),
1088
+ (1000, 0.015, '1000'),
1089
+ (10000, 0.015, '10000'),
1090
+ (100000, 0.015, '100000'),
1091
+ (3.141592654e-05, 0.5, '0'),
1092
+ (0.0003141592654, 0.5, '0'),
1093
+ (0.003141592654, 0.5, '0.003'),
1094
+ (0.03141592654, 0.5, '0.031'),
1095
+ (0.3141592654, 0.5, '0.314'),
1096
+ (3.141592654, 0.5, '3.142'),
1097
+ (31.41592654, 0.5, '31.416'),
1098
+ (314.1592654, 0.5, '314.159'),
1099
+ (3141.592654, 0.5, '3141.593'),
1100
+ (31415.92654, 0.5, '31415.927'),
1101
+ (314159.2654, 0.5, '314159.265'),
1102
+ (1e-05, 0.5, '0'),
1103
+ (0.0001, 0.5, '0'),
1104
+ (0.001, 0.5, '0.001'),
1105
+ (0.01, 0.5, '0.01'),
1106
+ (0.1, 0.5, '0.1'),
1107
+ (1, 0.5, '1'),
1108
+ (10, 0.5, '10'),
1109
+ (100, 0.5, '100'),
1110
+ (1000, 0.5, '1000'),
1111
+ (10000, 0.5, '10000'),
1112
+ (100000, 0.5, '100000'),
1113
+ (3.141592654e-05, 5, '0'),
1114
+ (0.0003141592654, 5, '0'),
1115
+ (0.003141592654, 5, '0'),
1116
+ (0.03141592654, 5, '0.03'),
1117
+ (0.3141592654, 5, '0.31'),
1118
+ (3.141592654, 5, '3.14'),
1119
+ (31.41592654, 5, '31.42'),
1120
+ (314.1592654, 5, '314.16'),
1121
+ (3141.592654, 5, '3141.59'),
1122
+ (31415.92654, 5, '31415.93'),
1123
+ (314159.2654, 5, '314159.27'),
1124
+ (1e-05, 5, '0'),
1125
+ (0.0001, 5, '0'),
1126
+ (0.001, 5, '0'),
1127
+ (0.01, 5, '0.01'),
1128
+ (0.1, 5, '0.1'),
1129
+ (1, 5, '1'),
1130
+ (10, 5, '10'),
1131
+ (100, 5, '100'),
1132
+ (1000, 5, '1000'),
1133
+ (10000, 5, '10000'),
1134
+ (100000, 5, '100000'),
1135
+ (3.141592654e-05, 100, '0'),
1136
+ (0.0003141592654, 100, '0'),
1137
+ (0.003141592654, 100, '0'),
1138
+ (0.03141592654, 100, '0'),
1139
+ (0.3141592654, 100, '0.3'),
1140
+ (3.141592654, 100, '3.1'),
1141
+ (31.41592654, 100, '31.4'),
1142
+ (314.1592654, 100, '314.2'),
1143
+ (3141.592654, 100, '3141.6'),
1144
+ (31415.92654, 100, '31415.9'),
1145
+ (314159.2654, 100, '314159.3'),
1146
+ (1e-05, 100, '0'),
1147
+ (0.0001, 100, '0'),
1148
+ (0.001, 100, '0'),
1149
+ (0.01, 100, '0'),
1150
+ (0.1, 100, '0.1'),
1151
+ (1, 100, '1'),
1152
+ (10, 100, '10'),
1153
+ (100, 100, '100'),
1154
+ (1000, 100, '1000'),
1155
+ (10000, 100, '10000'),
1156
+ (100000, 100, '100000'),
1157
+ (3.141592654e-05, 1000000.0, '3.1e-5'),
1158
+ (0.0003141592654, 1000000.0, '3.1e-4'),
1159
+ (0.003141592654, 1000000.0, '3.1e-3'),
1160
+ (0.03141592654, 1000000.0, '3.1e-2'),
1161
+ (0.3141592654, 1000000.0, '3.1e-1'),
1162
+ (3.141592654, 1000000.0, '3.1'),
1163
+ (31.41592654, 1000000.0, '3.1e1'),
1164
+ (314.1592654, 1000000.0, '3.1e2'),
1165
+ (3141.592654, 1000000.0, '3.1e3'),
1166
+ (31415.92654, 1000000.0, '3.1e4'),
1167
+ (314159.2654, 1000000.0, '3.1e5'),
1168
+ (1e-05, 1000000.0, '1e-5'),
1169
+ (0.0001, 1000000.0, '1e-4'),
1170
+ (0.001, 1000000.0, '1e-3'),
1171
+ (0.01, 1000000.0, '1e-2'),
1172
+ (0.1, 1000000.0, '1e-1'),
1173
+ (1, 1000000.0, '1'),
1174
+ (10, 1000000.0, '10'),
1175
+ (100, 1000000.0, '100'),
1176
+ (1000, 1000000.0, '1000'),
1177
+ (10000, 1000000.0, '1e4'),
1178
+ (100000, 1000000.0, '1e5'),
1179
+ ]
1180
+
1181
+ @pytest.mark.parametrize('value, domain, expected', pprint_data)
1182
+ def test_pprint(self, value, domain, expected):
1183
+ fmt = mticker.LogFormatter()
1184
+ label = fmt._pprint_val(value, domain)
1185
+ assert label == expected
1186
+
1187
+ @pytest.mark.parametrize('value, long, short', [
1188
+ (0.0, "0", "0"),
1189
+ (0, "0", "0"),
1190
+ (-1.0, "-10^0", "-1"),
1191
+ (2e-10, "2x10^-10", "2e-10"),
1192
+ (1e10, "10^10", "1e+10"),
1193
+ ])
1194
+ def test_format_data(self, value, long, short):
1195
+ fig, ax = plt.subplots()
1196
+ ax.set_xscale('log')
1197
+ fmt = ax.xaxis.get_major_formatter()
1198
+ assert fmt.format_data(value) == long
1199
+ assert fmt.format_data_short(value) == short
1200
+
1201
+ def _sub_labels(self, axis, subs=()):
1202
+ """Test whether locator marks subs to be labeled."""
1203
+ fmt = axis.get_minor_formatter()
1204
+ minor_tlocs = axis.get_minorticklocs()
1205
+ fmt.set_locs(minor_tlocs)
1206
+ coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs)))
1207
+ label_expected = [round(c) in subs for c in coefs]
1208
+ label_test = [fmt(x) != '' for x in minor_tlocs]
1209
+ assert label_test == label_expected
1210
+
1211
+ @mpl.style.context('default')
1212
+ def test_sublabel(self):
1213
+ # test label locator
1214
+ fig, ax = plt.subplots()
1215
+ ax.set_xscale('log')
1216
+ ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[]))
1217
+ ax.xaxis.set_minor_locator(mticker.LogLocator(base=10,
1218
+ subs=np.arange(2, 10)))
1219
+ ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True))
1220
+ ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False))
1221
+ # axis range above 3 decades, only bases are labeled
1222
+ ax.set_xlim(1, 1e4)
1223
+ fmt = ax.xaxis.get_major_formatter()
1224
+ fmt.set_locs(ax.xaxis.get_majorticklocs())
1225
+ show_major_labels = [fmt(x) != ''
1226
+ for x in ax.xaxis.get_majorticklocs()]
1227
+ assert np.all(show_major_labels)
1228
+ self._sub_labels(ax.xaxis, subs=[])
1229
+
1230
+ # For the next two, if the numdec threshold in LogFormatter.set_locs
1231
+ # were 3, then the label sub would be 3 for 2-3 decades and (2, 5)
1232
+ # for 1-2 decades. With a threshold of 1, subs are not labeled.
1233
+ # axis range at 2 to 3 decades
1234
+ ax.set_xlim(1, 800)
1235
+ self._sub_labels(ax.xaxis, subs=[])
1236
+
1237
+ # axis range at 1 to 2 decades
1238
+ ax.set_xlim(1, 80)
1239
+ self._sub_labels(ax.xaxis, subs=[])
1240
+
1241
+ # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6
1242
+ ax.set_xlim(1, 8)
1243
+ self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6])
1244
+
1245
+ # axis range at 0 to 0.4 decades, label all
1246
+ ax.set_xlim(0.5, 0.9)
1247
+ self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int))
1248
+
1249
+ @pytest.mark.parametrize('val', [1, 10, 100, 1000])
1250
+ def test_LogFormatter_call(self, val):
1251
+ # test _num_to_string method used in __call__
1252
+ temp_lf = mticker.LogFormatter()
1253
+ temp_lf.create_dummy_axis()
1254
+ temp_lf.axis.set_view_interval(1, 10)
1255
+ assert temp_lf(val) == str(val)
1256
+
1257
+ @pytest.mark.parametrize('val', [1e-323, 2e-323, 10e-323, 11e-323])
1258
+ def test_LogFormatter_call_tiny(self, val):
1259
+ # test coeff computation in __call__
1260
+ temp_lf = mticker.LogFormatter()
1261
+ temp_lf.create_dummy_axis()
1262
+ temp_lf.axis.set_view_interval(1, 10)
1263
+ temp_lf(val)
1264
+
1265
+
1266
+ class TestLogitFormatter:
1267
+ @staticmethod
1268
+ def logit_deformatter(string):
1269
+ r"""
1270
+ Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in
1271
+ float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float
1272
+ 0.5,
1273
+ """
1274
+ match = re.match(
1275
+ r"[^\d]*"
1276
+ r"(?P<comp>1-)?"
1277
+ r"(?P<mant>\d*\.?\d*)?"
1278
+ r"(?:\\cdot)?"
1279
+ r"(?:10\^\{(?P<expo>-?\d*)})?"
1280
+ r"[^\d]*$",
1281
+ string,
1282
+ )
1283
+ if match:
1284
+ comp = match["comp"] is not None
1285
+ mantissa = float(match["mant"]) if match["mant"] else 1
1286
+ expo = int(match["expo"]) if match["expo"] is not None else 0
1287
+ value = mantissa * 10 ** expo
1288
+ if match["mant"] or match["expo"] is not None:
1289
+ if comp:
1290
+ return 1 - value
1291
+ return value
1292
+ match = re.match(
1293
+ r"[^\d]*\\frac\{(?P<num>\d+)\}\{(?P<deno>\d+)\}[^\d]*$", string
1294
+ )
1295
+ if match:
1296
+ num, deno = float(match["num"]), float(match["deno"])
1297
+ return num / deno
1298
+ raise ValueError("Not formatted by LogitFormatter")
1299
+
1300
+ @pytest.mark.parametrize(
1301
+ "fx, x",
1302
+ [
1303
+ (r"STUFF0.41OTHERSTUFF", 0.41),
1304
+ (r"STUFF1.41\cdot10^{-2}OTHERSTUFF", 1.41e-2),
1305
+ (r"STUFF1-0.41OTHERSTUFF", 1 - 0.41),
1306
+ (r"STUFF1-1.41\cdot10^{-2}OTHERSTUFF", 1 - 1.41e-2),
1307
+ (r"STUFF", None),
1308
+ (r"STUFF12.4e-3OTHERSTUFF", None),
1309
+ ],
1310
+ )
1311
+ def test_logit_deformater(self, fx, x):
1312
+ if x is None:
1313
+ with pytest.raises(ValueError):
1314
+ TestLogitFormatter.logit_deformatter(fx)
1315
+ else:
1316
+ y = TestLogitFormatter.logit_deformatter(fx)
1317
+ assert _LogitHelper.isclose(x, y)
1318
+
1319
+ decade_test = sorted(
1320
+ [10 ** (-i) for i in range(1, 10)]
1321
+ + [1 - 10 ** (-i) for i in range(1, 10)]
1322
+ + [1 / 2]
1323
+ )
1324
+
1325
+ @pytest.mark.parametrize("x", decade_test)
1326
+ def test_basic(self, x):
1327
+ """
1328
+ Test the formatted value correspond to the value for ideal ticks in
1329
+ logit space.
1330
+ """
1331
+ formatter = mticker.LogitFormatter(use_overline=False)
1332
+ formatter.set_locs(self.decade_test)
1333
+ s = formatter(x)
1334
+ x2 = TestLogitFormatter.logit_deformatter(s)
1335
+ assert _LogitHelper.isclose(x, x2)
1336
+
1337
+ @pytest.mark.parametrize("x", (-1, -0.5, -0.1, 1.1, 1.5, 2))
1338
+ def test_invalid(self, x):
1339
+ """
1340
+ Test that invalid value are formatted with empty string without
1341
+ raising exception.
1342
+ """
1343
+ formatter = mticker.LogitFormatter(use_overline=False)
1344
+ formatter.set_locs(self.decade_test)
1345
+ s = formatter(x)
1346
+ assert s == ""
1347
+
1348
+ @pytest.mark.parametrize("x", 1 / (1 + np.exp(-np.linspace(-7, 7, 10))))
1349
+ def test_variablelength(self, x):
1350
+ """
1351
+ The format length should change depending on the neighbor labels.
1352
+ """
1353
+ formatter = mticker.LogitFormatter(use_overline=False)
1354
+ for N in (10, 20, 50, 100, 200, 1000, 2000, 5000, 10000):
1355
+ if x + 1 / N < 1:
1356
+ formatter.set_locs([x - 1 / N, x, x + 1 / N])
1357
+ sx = formatter(x)
1358
+ sx1 = formatter(x + 1 / N)
1359
+ d = (
1360
+ TestLogitFormatter.logit_deformatter(sx1)
1361
+ - TestLogitFormatter.logit_deformatter(sx)
1362
+ )
1363
+ assert 0 < d < 2 / N
1364
+
1365
+ lims_minor_major = [
1366
+ (True, (5e-8, 1 - 5e-8), ((25, False), (75, False))),
1367
+ (True, (5e-5, 1 - 5e-5), ((25, False), (75, True))),
1368
+ (True, (5e-2, 1 - 5e-2), ((25, True), (75, True))),
1369
+ (False, (0.75, 0.76, 0.77), ((7, True), (25, True), (75, True))),
1370
+ ]
1371
+
1372
+ @pytest.mark.parametrize("method, lims, cases", lims_minor_major)
1373
+ def test_minor_vs_major(self, method, lims, cases):
1374
+ """
1375
+ Test minor/major displays.
1376
+ """
1377
+
1378
+ if method:
1379
+ min_loc = mticker.LogitLocator(minor=True)
1380
+ ticks = min_loc.tick_values(*lims)
1381
+ else:
1382
+ ticks = np.array(lims)
1383
+ min_form = mticker.LogitFormatter(minor=True)
1384
+ for threshold, has_minor in cases:
1385
+ min_form.set_minor_threshold(threshold)
1386
+ formatted = min_form.format_ticks(ticks)
1387
+ labelled = [f for f in formatted if len(f) > 0]
1388
+ if has_minor:
1389
+ assert len(labelled) > 0, (threshold, has_minor)
1390
+ else:
1391
+ assert len(labelled) == 0, (threshold, has_minor)
1392
+
1393
+ def test_minor_number(self):
1394
+ """
1395
+ Test the parameter minor_number
1396
+ """
1397
+ min_loc = mticker.LogitLocator(minor=True)
1398
+ min_form = mticker.LogitFormatter(minor=True)
1399
+ ticks = min_loc.tick_values(5e-2, 1 - 5e-2)
1400
+ for minor_number in (2, 4, 8, 16):
1401
+ min_form.set_minor_number(minor_number)
1402
+ formatted = min_form.format_ticks(ticks)
1403
+ labelled = [f for f in formatted if len(f) > 0]
1404
+ assert len(labelled) == minor_number
1405
+
1406
+ def test_use_overline(self):
1407
+ """
1408
+ Test the parameter use_overline
1409
+ """
1410
+ x = 1 - 1e-2
1411
+ fx1 = r"$\mathdefault{1-10^{-2}}$"
1412
+ fx2 = r"$\mathdefault{\overline{10^{-2}}}$"
1413
+ form = mticker.LogitFormatter(use_overline=False)
1414
+ assert form(x) == fx1
1415
+ form.use_overline(True)
1416
+ assert form(x) == fx2
1417
+ form.use_overline(False)
1418
+ assert form(x) == fx1
1419
+
1420
+ def test_one_half(self):
1421
+ """
1422
+ Test the parameter one_half
1423
+ """
1424
+ form = mticker.LogitFormatter()
1425
+ assert r"\frac{1}{2}" in form(1/2)
1426
+ form.set_one_half("1/2")
1427
+ assert "1/2" in form(1/2)
1428
+ form.set_one_half("one half")
1429
+ assert "one half" in form(1/2)
1430
+
1431
+ @pytest.mark.parametrize("N", (100, 253, 754))
1432
+ def test_format_data_short(self, N):
1433
+ locs = np.linspace(0, 1, N)[1:-1]
1434
+ form = mticker.LogitFormatter()
1435
+ for x in locs:
1436
+ fx = form.format_data_short(x)
1437
+ if fx.startswith("1-"):
1438
+ x2 = 1 - float(fx[2:])
1439
+ else:
1440
+ x2 = float(fx)
1441
+ assert abs(x - x2) < 1 / N
1442
+
1443
+
1444
+ class TestFormatStrFormatter:
1445
+ def test_basic(self):
1446
+ # test % style formatter
1447
+ tmp_form = mticker.FormatStrFormatter('%05d')
1448
+ assert '00002' == tmp_form(2)
1449
+
1450
+
1451
+ class TestStrMethodFormatter:
1452
+ test_data = [
1453
+ ('{x:05d}', (2,), False, '00002'),
1454
+ ('{x:05d}', (2,), True, '00002'),
1455
+ ('{x:05d}', (-2,), False, '-0002'),
1456
+ ('{x:05d}', (-2,), True, '\N{MINUS SIGN}0002'),
1457
+ ('{x:03d}-{pos:02d}', (2, 1), False, '002-01'),
1458
+ ('{x:03d}-{pos:02d}', (2, 1), True, '002-01'),
1459
+ ('{x:03d}-{pos:02d}', (-2, 1), False, '-02-01'),
1460
+ ('{x:03d}-{pos:02d}', (-2, 1), True, '\N{MINUS SIGN}02-01'),
1461
+ ]
1462
+
1463
+ @pytest.mark.parametrize('format, input, unicode_minus, expected', test_data)
1464
+ def test_basic(self, format, input, unicode_minus, expected):
1465
+ with mpl.rc_context({"axes.unicode_minus": unicode_minus}):
1466
+ fmt = mticker.StrMethodFormatter(format)
1467
+ assert fmt(*input) == expected
1468
+
1469
+
1470
+ class TestEngFormatter:
1471
+ # (unicode_minus, input, expected) where ''expected'' corresponds to the
1472
+ # outputs respectively returned when (places=None, places=0, places=2)
1473
+ # unicode_minus is a boolean value for the rcParam['axes.unicode_minus']
1474
+ raw_format_data = [
1475
+ (False, -1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')),
1476
+ (True, -1234.56789, ('\N{MINUS SIGN}1.23457 k', '\N{MINUS SIGN}1 k',
1477
+ '\N{MINUS SIGN}1.23 k')),
1478
+ (False, -1.23456789, ('-1.23457', '-1', '-1.23')),
1479
+ (True, -1.23456789, ('\N{MINUS SIGN}1.23457', '\N{MINUS SIGN}1',
1480
+ '\N{MINUS SIGN}1.23')),
1481
+ (False, -0.123456789, ('-123.457 m', '-123 m', '-123.46 m')),
1482
+ (True, -0.123456789, ('\N{MINUS SIGN}123.457 m', '\N{MINUS SIGN}123 m',
1483
+ '\N{MINUS SIGN}123.46 m')),
1484
+ (False, -0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')),
1485
+ (True, -0.00123456789, ('\N{MINUS SIGN}1.23457 m', '\N{MINUS SIGN}1 m',
1486
+ '\N{MINUS SIGN}1.23 m')),
1487
+ (True, -0.0, ('0', '0', '0.00')),
1488
+ (True, -0, ('0', '0', '0.00')),
1489
+ (True, 0, ('0', '0', '0.00')),
1490
+ (True, 1.23456789e-6, ('1.23457 µ', '1 µ', '1.23 µ')),
1491
+ (True, 0.123456789, ('123.457 m', '123 m', '123.46 m')),
1492
+ (True, 0.1, ('100 m', '100 m', '100.00 m')),
1493
+ (True, 1, ('1', '1', '1.00')),
1494
+ (True, 1.23456789, ('1.23457', '1', '1.23')),
1495
+ # places=0: corner-case rounding
1496
+ (True, 999.9, ('999.9', '1 k', '999.90')),
1497
+ # corner-case rounding for all
1498
+ (True, 999.9999, ('1 k', '1 k', '1.00 k')),
1499
+ # negative corner-case
1500
+ (False, -999.9999, ('-1 k', '-1 k', '-1.00 k')),
1501
+ (True, -999.9999, ('\N{MINUS SIGN}1 k', '\N{MINUS SIGN}1 k',
1502
+ '\N{MINUS SIGN}1.00 k')),
1503
+ (True, 1000, ('1 k', '1 k', '1.00 k')),
1504
+ (True, 1001, ('1.001 k', '1 k', '1.00 k')),
1505
+ (True, 100001, ('100.001 k', '100 k', '100.00 k')),
1506
+ (True, 987654.321, ('987.654 k', '988 k', '987.65 k')),
1507
+ # OoR value (> 1000 Q)
1508
+ (True, 1.23e33, ('1230 Q', '1230 Q', '1230.00 Q'))
1509
+ ]
1510
+
1511
+ @pytest.mark.parametrize('unicode_minus, input, expected', raw_format_data)
1512
+ def test_params(self, unicode_minus, input, expected):
1513
+ """
1514
+ Test the formatting of EngFormatter for various values of the 'places'
1515
+ argument, in several cases:
1516
+
1517
+ 0. without a unit symbol but with a (default) space separator;
1518
+ 1. with both a unit symbol and a (default) space separator;
1519
+ 2. with both a unit symbol and some non default separators;
1520
+ 3. without a unit symbol but with some non default separators.
1521
+
1522
+ Note that cases 2. and 3. are looped over several separator strings.
1523
+ """
1524
+
1525
+ plt.rcParams['axes.unicode_minus'] = unicode_minus
1526
+ UNIT = 's' # seconds
1527
+ DIGITS = '0123456789' # %timeit showed 10-20% faster search than set
1528
+
1529
+ # Case 0: unit='' (default) and sep=' ' (default).
1530
+ # 'expected' already corresponds to this reference case.
1531
+ exp_outputs = expected
1532
+ formatters = (
1533
+ mticker.EngFormatter(), # places=None (default)
1534
+ mticker.EngFormatter(places=0),
1535
+ mticker.EngFormatter(places=2)
1536
+ )
1537
+ for _formatter, _exp_output in zip(formatters, exp_outputs):
1538
+ assert _formatter(input) == _exp_output
1539
+
1540
+ # Case 1: unit=UNIT and sep=' ' (default).
1541
+ # Append a unit symbol to the reference case.
1542
+ # Beware of the values in [1, 1000), where there is no prefix!
1543
+ exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix
1544
+ else _s + UNIT for _s in expected)
1545
+ formatters = (
1546
+ mticker.EngFormatter(unit=UNIT), # places=None (default)
1547
+ mticker.EngFormatter(unit=UNIT, places=0),
1548
+ mticker.EngFormatter(unit=UNIT, places=2)
1549
+ )
1550
+ for _formatter, _exp_output in zip(formatters, exp_outputs):
1551
+ assert _formatter(input) == _exp_output
1552
+
1553
+ # Test several non default separators: no separator, a narrow
1554
+ # no-break space (Unicode character) and an extravagant string.
1555
+ for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"):
1556
+ # Case 2: unit=UNIT and sep=_sep.
1557
+ # Replace the default space separator from the reference case
1558
+ # with the tested one `_sep` and append a unit symbol to it.
1559
+ exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix
1560
+ else _s.replace(" ", _sep) + UNIT
1561
+ for _s in expected)
1562
+ formatters = (
1563
+ mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None
1564
+ mticker.EngFormatter(unit=UNIT, places=0, sep=_sep),
1565
+ mticker.EngFormatter(unit=UNIT, places=2, sep=_sep)
1566
+ )
1567
+ for _formatter, _exp_output in zip(formatters, exp_outputs):
1568
+ assert _formatter(input) == _exp_output
1569
+
1570
+ # Case 3: unit='' (default) and sep=_sep.
1571
+ # Replace the default space separator from the reference case
1572
+ # with the tested one `_sep`. Reference case is already unitless.
1573
+ exp_outputs = (_s.replace(" ", _sep) for _s in expected)
1574
+ formatters = (
1575
+ mticker.EngFormatter(sep=_sep), # places=None (default)
1576
+ mticker.EngFormatter(places=0, sep=_sep),
1577
+ mticker.EngFormatter(places=2, sep=_sep)
1578
+ )
1579
+ for _formatter, _exp_output in zip(formatters, exp_outputs):
1580
+ assert _formatter(input) == _exp_output
1581
+
1582
+
1583
+ def test_engformatter_usetex_useMathText():
1584
+ fig, ax = plt.subplots()
1585
+ ax.plot([0, 500, 1000], [0, 500, 1000])
1586
+ ax.set_xticks([0, 500, 1000])
1587
+ for formatter in (mticker.EngFormatter(usetex=True),
1588
+ mticker.EngFormatter(useMathText=True)):
1589
+ ax.xaxis.set_major_formatter(formatter)
1590
+ fig.canvas.draw()
1591
+ x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()]
1592
+ # Checking if the dollar `$` signs have been inserted around numbers
1593
+ # in tick labels.
1594
+ assert x_tick_label_text == ['$0$', '$500$', '$1$ k']
1595
+
1596
+
1597
+ class TestPercentFormatter:
1598
+ percent_data = [
1599
+ # Check explicitly set decimals over different intervals and values
1600
+ (100, 0, '%', 120, 100, '120%'),
1601
+ (100, 0, '%', 100, 90, '100%'),
1602
+ (100, 0, '%', 90, 50, '90%'),
1603
+ (100, 0, '%', -1.7, 40, '-2%'),
1604
+ (100, 1, '%', 90.0, 100, '90.0%'),
1605
+ (100, 1, '%', 80.1, 90, '80.1%'),
1606
+ (100, 1, '%', 70.23, 50, '70.2%'),
1607
+ # 60.554 instead of 60.55: see https://bugs.python.org/issue5118
1608
+ (100, 1, '%', -60.554, 40, '-60.6%'),
1609
+ # Check auto decimals over different intervals and values
1610
+ (100, None, '%', 95, 1, '95.00%'),
1611
+ (1.0, None, '%', 3, 6, '300%'),
1612
+ (17.0, None, '%', 1, 8.5, '6%'),
1613
+ (17.0, None, '%', 1, 8.4, '5.9%'),
1614
+ (5, None, '%', -100, 0.000001, '-2000.00000%'),
1615
+ # Check percent symbol
1616
+ (1.0, 2, None, 1.2, 100, '120.00'),
1617
+ (75, 3, '', 50, 100, '66.667'),
1618
+ (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'),
1619
+ ]
1620
+
1621
+ percent_ids = [
1622
+ # Check explicitly set decimals over different intervals and values
1623
+ 'decimals=0, x>100%',
1624
+ 'decimals=0, x=100%',
1625
+ 'decimals=0, x<100%',
1626
+ 'decimals=0, x<0%',
1627
+ 'decimals=1, x>100%',
1628
+ 'decimals=1, x=100%',
1629
+ 'decimals=1, x<100%',
1630
+ 'decimals=1, x<0%',
1631
+ # Check auto decimals over different intervals and values
1632
+ 'autodecimal, x<100%, display_range=1',
1633
+ 'autodecimal, x>100%, display_range=6 (custom xmax test)',
1634
+ 'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)',
1635
+ 'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)',
1636
+ 'autodecimal, x<-100%, display_range=1e-6 (tiny display range)',
1637
+ # Check percent symbol
1638
+ 'None as percent symbol',
1639
+ 'Empty percent symbol',
1640
+ 'Custom percent symbol',
1641
+ ]
1642
+
1643
+ latex_data = [
1644
+ (False, False, r'50\{t}%'),
1645
+ (False, True, r'50\\\{t\}\%'),
1646
+ (True, False, r'50\{t}%'),
1647
+ (True, True, r'50\{t}%'),
1648
+ ]
1649
+
1650
+ @pytest.mark.parametrize(
1651
+ 'xmax, decimals, symbol, x, display_range, expected',
1652
+ percent_data, ids=percent_ids)
1653
+ def test_basic(self, xmax, decimals, symbol,
1654
+ x, display_range, expected):
1655
+ formatter = mticker.PercentFormatter(xmax, decimals, symbol)
1656
+ with mpl.rc_context(rc={'text.usetex': False}):
1657
+ assert formatter.format_pct(x, display_range) == expected
1658
+
1659
+ @pytest.mark.parametrize('is_latex, usetex, expected', latex_data)
1660
+ def test_latex(self, is_latex, usetex, expected):
1661
+ fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex)
1662
+ with mpl.rc_context(rc={'text.usetex': usetex}):
1663
+ assert fmt.format_pct(50, 100) == expected
1664
+
1665
+
1666
+ def _impl_locale_comma():
1667
+ try:
1668
+ locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8')
1669
+ except locale.Error:
1670
+ print('SKIP: Locale de_DE.UTF-8 is not supported on this machine')
1671
+ return
1672
+ ticks = mticker.ScalarFormatter(useMathText=True, useLocale=True)
1673
+ fmt = '$\\mathdefault{%1.1f}$'
1674
+ x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
1675
+ assert x == '$\\mathdefault{0{,}5}$'
1676
+ # Do not change , in the format string
1677
+ fmt = ',$\\mathdefault{,%1.1f},$'
1678
+ x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
1679
+ assert x == ',$\\mathdefault{,0{,}5},$'
1680
+ # Make sure no brackets are added if not using math text
1681
+ ticks = mticker.ScalarFormatter(useMathText=False, useLocale=True)
1682
+ fmt = '%1.1f'
1683
+ x = ticks._format_maybe_minus_and_locale(fmt, 0.5)
1684
+ assert x == '0,5'
1685
+
1686
+
1687
+ def test_locale_comma():
1688
+ # On some systems/pytest versions, `pytest.skip` in an exception handler
1689
+ # does not skip, but is treated as an exception, so directly running this
1690
+ # test can incorrectly fail instead of skip.
1691
+ # Instead, run this test in a subprocess, which avoids the problem, and the
1692
+ # need to fix the locale after.
1693
+ proc = mpl.testing.subprocess_run_helper(_impl_locale_comma, timeout=60,
1694
+ extra_env={'MPLBACKEND': 'Agg'})
1695
+ skip_msg = next((line[len('SKIP:'):].strip()
1696
+ for line in proc.stdout.splitlines()
1697
+ if line.startswith('SKIP:')),
1698
+ '')
1699
+ if skip_msg:
1700
+ pytest.skip(skip_msg)
1701
+
1702
+
1703
+ def test_majformatter_type():
1704
+ fig, ax = plt.subplots()
1705
+ with pytest.raises(TypeError):
1706
+ ax.xaxis.set_major_formatter(mticker.LogLocator())
1707
+
1708
+
1709
+ def test_minformatter_type():
1710
+ fig, ax = plt.subplots()
1711
+ with pytest.raises(TypeError):
1712
+ ax.xaxis.set_minor_formatter(mticker.LogLocator())
1713
+
1714
+
1715
+ def test_majlocator_type():
1716
+ fig, ax = plt.subplots()
1717
+ with pytest.raises(TypeError):
1718
+ ax.xaxis.set_major_locator(mticker.LogFormatter())
1719
+
1720
+
1721
+ def test_minlocator_type():
1722
+ fig, ax = plt.subplots()
1723
+ with pytest.raises(TypeError):
1724
+ ax.xaxis.set_minor_locator(mticker.LogFormatter())
1725
+
1726
+
1727
+ def test_minorticks_rc():
1728
+ fig = plt.figure()
1729
+
1730
+ def minorticksubplot(xminor, yminor, i):
1731
+ rc = {'xtick.minor.visible': xminor,
1732
+ 'ytick.minor.visible': yminor}
1733
+ with plt.rc_context(rc=rc):
1734
+ ax = fig.add_subplot(2, 2, i)
1735
+
1736
+ assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor
1737
+ assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor
1738
+
1739
+ minorticksubplot(False, False, 1)
1740
+ minorticksubplot(True, False, 2)
1741
+ minorticksubplot(False, True, 3)
1742
+ minorticksubplot(True, True, 4)
1743
+
1744
+
1745
+ def test_minorticks_toggle():
1746
+ """
1747
+ Test toggling minor ticks
1748
+
1749
+ Test `.Axis.minorticks_on()` and `.Axis.minorticks_off()`. Testing is
1750
+ limited to a subset of built-in scales - `'linear'`, `'log'`, `'asinh'`
1751
+ and `'logit'`. `symlog` scale does not seem to have a working minor
1752
+ locator and is omitted. In future, this test should cover all scales in
1753
+ `matplotlib.scale.get_scale_names()`.
1754
+ """
1755
+ fig = plt.figure()
1756
+ def minortickstoggle(xminor, yminor, scale, i):
1757
+ ax = fig.add_subplot(2, 2, i)
1758
+ ax.set_xscale(scale)
1759
+ ax.set_yscale(scale)
1760
+ if not xminor and not yminor:
1761
+ ax.minorticks_off()
1762
+ if xminor and not yminor:
1763
+ ax.xaxis.minorticks_on()
1764
+ ax.yaxis.minorticks_off()
1765
+ if not xminor and yminor:
1766
+ ax.xaxis.minorticks_off()
1767
+ ax.yaxis.minorticks_on()
1768
+ if xminor and yminor:
1769
+ ax.minorticks_on()
1770
+
1771
+ assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor
1772
+ assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor
1773
+
1774
+ scales = ['linear', 'log', 'asinh', 'logit']
1775
+ for scale in scales:
1776
+ minortickstoggle(False, False, scale, 1)
1777
+ minortickstoggle(True, False, scale, 2)
1778
+ minortickstoggle(False, True, scale, 3)
1779
+ minortickstoggle(True, True, scale, 4)
1780
+ fig.clear()
1781
+
1782
+ plt.close(fig)
1783
+
1784
+
1785
+ @pytest.mark.parametrize('remove_overlapping_locs, expected_num',
1786
+ ((True, 6),
1787
+ (None, 6), # this tests the default
1788
+ (False, 9)))
1789
+ def test_remove_overlap(remove_overlapping_locs, expected_num):
1790
+ t = np.arange("2018-11-03", "2018-11-06", dtype="datetime64")
1791
+ x = np.ones(len(t))
1792
+
1793
+ fig, ax = plt.subplots()
1794
+ ax.plot(t, x)
1795
+
1796
+ ax.xaxis.set_major_locator(mpl.dates.DayLocator())
1797
+ ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%a'))
1798
+
1799
+ ax.xaxis.set_minor_locator(mpl.dates.HourLocator((0, 6, 12, 18)))
1800
+ ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%H:%M'))
1801
+ # force there to be extra ticks
1802
+ ax.xaxis.get_minor_ticks(15)
1803
+ if remove_overlapping_locs is not None:
1804
+ ax.xaxis.remove_overlapping_locs = remove_overlapping_locs
1805
+
1806
+ # check that getter/setter exists
1807
+ current = ax.xaxis.remove_overlapping_locs
1808
+ assert (current == ax.xaxis.get_remove_overlapping_locs())
1809
+ plt.setp(ax.xaxis, remove_overlapping_locs=current)
1810
+ new = ax.xaxis.remove_overlapping_locs
1811
+ assert (new == ax.xaxis.remove_overlapping_locs)
1812
+
1813
+ # check that the accessors filter correctly
1814
+ # this is the method that does the actual filtering
1815
+ assert len(ax.xaxis.get_minorticklocs()) == expected_num
1816
+ # these three are derivative
1817
+ assert len(ax.xaxis.get_minor_ticks()) == expected_num
1818
+ assert len(ax.xaxis.get_minorticklabels()) == expected_num
1819
+ assert len(ax.xaxis.get_minorticklines()) == expected_num*2
1820
+
1821
+
1822
+ @pytest.mark.parametrize('sub', [
1823
+ ['hi', 'aardvark'],
1824
+ np.zeros((2, 2))])
1825
+ def test_bad_locator_subs(sub):
1826
+ ll = mticker.LogLocator()
1827
+ with pytest.raises(ValueError):
1828
+ ll.set_params(subs=sub)
1829
+
1830
+
1831
+ @pytest.mark.parametrize('numticks', [1, 2, 3, 9])
1832
+ @mpl.style.context('default')
1833
+ def test_small_range_loglocator(numticks):
1834
+ ll = mticker.LogLocator()
1835
+ ll.set_params(numticks=numticks)
1836
+ for top in [5, 7, 9, 11, 15, 50, 100, 1000]:
1837
+ ticks = ll.tick_values(.5, top)
1838
+ assert (np.diff(np.log10(ll.tick_values(6, 150))) == 1).all()
1839
+
1840
+
1841
+ def test_NullFormatter():
1842
+ formatter = mticker.NullFormatter()
1843
+ assert formatter(1.0) == ''
1844
+ assert formatter.format_data(1.0) == ''
1845
+ assert formatter.format_data_short(1.0) == ''
1846
+
1847
+
1848
+ @pytest.mark.parametrize('formatter', (
1849
+ mticker.FuncFormatter(lambda a: f'val: {a}'),
1850
+ mticker.FixedFormatter(('foo', 'bar'))))
1851
+ def test_set_offset_string(formatter):
1852
+ assert formatter.get_offset() == ''
1853
+ formatter.set_offset_string('mpl')
1854
+ assert formatter.get_offset() == 'mpl'
1855
+
1856
+
1857
+ def test_minorticks_on_multi_fig():
1858
+ """
1859
+ Turning on minor gridlines in a multi-Axes Figure
1860
+ that contains more than one boxplot and shares the x-axis
1861
+ should not raise an exception.
1862
+ """
1863
+ fig, ax = plt.subplots()
1864
+
1865
+ ax.boxplot(np.arange(10), positions=[0])
1866
+ ax.boxplot(np.arange(10), positions=[0])
1867
+ ax.boxplot(np.arange(10), positions=[1])
1868
+
1869
+ ax.grid(which="major")
1870
+ ax.grid(which="minor")
1871
+ ax.minorticks_on()
1872
+ fig.draw_without_rendering()
1873
+
1874
+ assert ax.get_xgridlines()
1875
+ assert isinstance(ax.xaxis.get_minor_locator(), mpl.ticker.AutoMinorLocator)
parrot/lib/python3.10/site-packages/matplotlib/tests/test_units.py ADDED
@@ -0,0 +1,304 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from datetime import datetime, timezone, timedelta
2
+ import platform
3
+ from unittest.mock import MagicMock
4
+
5
+ import matplotlib.pyplot as plt
6
+ from matplotlib.testing.decorators import check_figures_equal, image_comparison
7
+ import matplotlib.units as munits
8
+ from matplotlib.category import UnitData
9
+ import numpy as np
10
+ import pytest
11
+
12
+
13
+ # Basic class that wraps numpy array and has units
14
+ class Quantity:
15
+ def __init__(self, data, units):
16
+ self.magnitude = data
17
+ self.units = units
18
+
19
+ def to(self, new_units):
20
+ factors = {('hours', 'seconds'): 3600, ('minutes', 'hours'): 1 / 60,
21
+ ('minutes', 'seconds'): 60, ('feet', 'miles'): 1 / 5280.,
22
+ ('feet', 'inches'): 12, ('miles', 'inches'): 12 * 5280}
23
+ if self.units != new_units:
24
+ mult = factors[self.units, new_units]
25
+ return Quantity(mult * self.magnitude, new_units)
26
+ else:
27
+ return Quantity(self.magnitude, self.units)
28
+
29
+ def __copy__(self):
30
+ return Quantity(self.magnitude, self.units)
31
+
32
+ def __getattr__(self, attr):
33
+ return getattr(self.magnitude, attr)
34
+
35
+ def __getitem__(self, item):
36
+ if np.iterable(self.magnitude):
37
+ return Quantity(self.magnitude[item], self.units)
38
+ else:
39
+ return Quantity(self.magnitude, self.units)
40
+
41
+ def __array__(self):
42
+ return np.asarray(self.magnitude)
43
+
44
+
45
+ @pytest.fixture
46
+ def quantity_converter():
47
+ # Create an instance of the conversion interface and
48
+ # mock so we can check methods called
49
+ qc = munits.ConversionInterface()
50
+
51
+ def convert(value, unit, axis):
52
+ if hasattr(value, 'units'):
53
+ return value.to(unit).magnitude
54
+ elif np.iterable(value):
55
+ try:
56
+ return [v.to(unit).magnitude for v in value]
57
+ except AttributeError:
58
+ return [Quantity(v, axis.get_units()).to(unit).magnitude
59
+ for v in value]
60
+ else:
61
+ return Quantity(value, axis.get_units()).to(unit).magnitude
62
+
63
+ def default_units(value, axis):
64
+ if hasattr(value, 'units'):
65
+ return value.units
66
+ elif np.iterable(value):
67
+ for v in value:
68
+ if hasattr(v, 'units'):
69
+ return v.units
70
+ return None
71
+
72
+ qc.convert = MagicMock(side_effect=convert)
73
+ qc.axisinfo = MagicMock(side_effect=lambda u, a:
74
+ munits.AxisInfo(label=u, default_limits=(0, 100)))
75
+ qc.default_units = MagicMock(side_effect=default_units)
76
+ return qc
77
+
78
+
79
+ # Tests that the conversion machinery works properly for classes that
80
+ # work as a facade over numpy arrays (like pint)
81
+ @image_comparison(['plot_pint.png'], style='mpl20',
82
+ tol=0 if platform.machine() == 'x86_64' else 0.03)
83
+ def test_numpy_facade(quantity_converter):
84
+ # use former defaults to match existing baseline image
85
+ plt.rcParams['axes.formatter.limits'] = -7, 7
86
+
87
+ # Register the class
88
+ munits.registry[Quantity] = quantity_converter
89
+
90
+ # Simple test
91
+ y = Quantity(np.linspace(0, 30), 'miles')
92
+ x = Quantity(np.linspace(0, 5), 'hours')
93
+
94
+ fig, ax = plt.subplots()
95
+ fig.subplots_adjust(left=0.15) # Make space for label
96
+ ax.plot(x, y, 'tab:blue')
97
+ ax.axhline(Quantity(26400, 'feet'), color='tab:red')
98
+ ax.axvline(Quantity(120, 'minutes'), color='tab:green')
99
+ ax.yaxis.set_units('inches')
100
+ ax.xaxis.set_units('seconds')
101
+
102
+ assert quantity_converter.convert.called
103
+ assert quantity_converter.axisinfo.called
104
+ assert quantity_converter.default_units.called
105
+
106
+
107
+ # Tests gh-8908
108
+ @image_comparison(['plot_masked_units.png'], remove_text=True, style='mpl20',
109
+ tol=0 if platform.machine() == 'x86_64' else 0.02)
110
+ def test_plot_masked_units():
111
+ data = np.linspace(-5, 5)
112
+ data_masked = np.ma.array(data, mask=(data > -2) & (data < 2))
113
+ data_masked_units = Quantity(data_masked, 'meters')
114
+
115
+ fig, ax = plt.subplots()
116
+ ax.plot(data_masked_units)
117
+
118
+
119
+ def test_empty_set_limits_with_units(quantity_converter):
120
+ # Register the class
121
+ munits.registry[Quantity] = quantity_converter
122
+
123
+ fig, ax = plt.subplots()
124
+ ax.set_xlim(Quantity(-1, 'meters'), Quantity(6, 'meters'))
125
+ ax.set_ylim(Quantity(-1, 'hours'), Quantity(16, 'hours'))
126
+
127
+
128
+ @image_comparison(['jpl_bar_units.png'],
129
+ savefig_kwarg={'dpi': 120}, style='mpl20')
130
+ def test_jpl_bar_units():
131
+ import matplotlib.testing.jpl_units as units
132
+ units.register()
133
+
134
+ day = units.Duration("ET", 24.0 * 60.0 * 60.0)
135
+ x = [0 * units.km, 1 * units.km, 2 * units.km]
136
+ w = [1 * day, 2 * day, 3 * day]
137
+ b = units.Epoch("ET", dt=datetime(2009, 4, 26))
138
+ fig, ax = plt.subplots()
139
+ ax.bar(x, w, bottom=b)
140
+ ax.set_ylim([b - 1 * day, b + w[-1] + (1.001) * day])
141
+
142
+
143
+ @image_comparison(['jpl_barh_units.png'],
144
+ savefig_kwarg={'dpi': 120}, style='mpl20')
145
+ def test_jpl_barh_units():
146
+ import matplotlib.testing.jpl_units as units
147
+ units.register()
148
+
149
+ day = units.Duration("ET", 24.0 * 60.0 * 60.0)
150
+ x = [0 * units.km, 1 * units.km, 2 * units.km]
151
+ w = [1 * day, 2 * day, 3 * day]
152
+ b = units.Epoch("ET", dt=datetime(2009, 4, 26))
153
+
154
+ fig, ax = plt.subplots()
155
+ ax.barh(x, w, left=b)
156
+ ax.set_xlim([b - 1 * day, b + w[-1] + (1.001) * day])
157
+
158
+
159
+ def test_jpl_datetime_units_consistent():
160
+ import matplotlib.testing.jpl_units as units
161
+ units.register()
162
+
163
+ dt = datetime(2009, 4, 26)
164
+ jpl = units.Epoch("ET", dt=dt)
165
+ dt_conv = munits.registry.get_converter(dt).convert(dt, None, None)
166
+ jpl_conv = munits.registry.get_converter(jpl).convert(jpl, None, None)
167
+ assert dt_conv == jpl_conv
168
+
169
+
170
+ def test_empty_arrays():
171
+ # Check that plotting an empty array with a dtype works
172
+ plt.scatter(np.array([], dtype='datetime64[ns]'), np.array([]))
173
+
174
+
175
+ def test_scatter_element0_masked():
176
+ times = np.arange('2005-02', '2005-03', dtype='datetime64[D]')
177
+ y = np.arange(len(times), dtype=float)
178
+ y[0] = np.nan
179
+ fig, ax = plt.subplots()
180
+ ax.scatter(times, y)
181
+ fig.canvas.draw()
182
+
183
+
184
+ def test_errorbar_mixed_units():
185
+ x = np.arange(10)
186
+ y = [datetime(2020, 5, i * 2 + 1) for i in x]
187
+ fig, ax = plt.subplots()
188
+ ax.errorbar(x, y, timedelta(days=0.5))
189
+ fig.canvas.draw()
190
+
191
+
192
+ @check_figures_equal(extensions=["png"])
193
+ def test_subclass(fig_test, fig_ref):
194
+ class subdate(datetime):
195
+ pass
196
+
197
+ fig_test.subplots().plot(subdate(2000, 1, 1), 0, "o")
198
+ fig_ref.subplots().plot(datetime(2000, 1, 1), 0, "o")
199
+
200
+
201
+ def test_shared_axis_quantity(quantity_converter):
202
+ munits.registry[Quantity] = quantity_converter
203
+ x = Quantity(np.linspace(0, 1, 10), "hours")
204
+ y1 = Quantity(np.linspace(1, 2, 10), "feet")
205
+ y2 = Quantity(np.linspace(3, 4, 10), "feet")
206
+ fig, (ax1, ax2) = plt.subplots(2, 1, sharex='all', sharey='all')
207
+ ax1.plot(x, y1)
208
+ ax2.plot(x, y2)
209
+ assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "hours"
210
+ assert ax2.yaxis.get_units() == ax2.yaxis.get_units() == "feet"
211
+ ax1.xaxis.set_units("seconds")
212
+ ax2.yaxis.set_units("inches")
213
+ assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "seconds"
214
+ assert ax1.yaxis.get_units() == ax2.yaxis.get_units() == "inches"
215
+
216
+
217
+ def test_shared_axis_datetime():
218
+ # datetime uses dates.DateConverter
219
+ y1 = [datetime(2020, i, 1, tzinfo=timezone.utc) for i in range(1, 13)]
220
+ y2 = [datetime(2021, i, 1, tzinfo=timezone.utc) for i in range(1, 13)]
221
+ fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True)
222
+ ax1.plot(y1)
223
+ ax2.plot(y2)
224
+ ax1.yaxis.set_units(timezone(timedelta(hours=5)))
225
+ assert ax2.yaxis.units == timezone(timedelta(hours=5))
226
+
227
+
228
+ def test_shared_axis_categorical():
229
+ # str uses category.StrCategoryConverter
230
+ d1 = {"a": 1, "b": 2}
231
+ d2 = {"a": 3, "b": 4}
232
+ fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True)
233
+ ax1.plot(d1.keys(), d1.values())
234
+ ax2.plot(d2.keys(), d2.values())
235
+ ax1.xaxis.set_units(UnitData(["c", "d"]))
236
+ assert "c" in ax2.xaxis.get_units()._mapping.keys()
237
+
238
+
239
+ def test_empty_default_limits(quantity_converter):
240
+ munits.registry[Quantity] = quantity_converter
241
+ fig, ax1 = plt.subplots()
242
+ ax1.xaxis.update_units(Quantity([10], "miles"))
243
+ fig.draw_without_rendering()
244
+ assert ax1.get_xlim() == (0, 100)
245
+ ax1.yaxis.update_units(Quantity([10], "miles"))
246
+ fig.draw_without_rendering()
247
+ assert ax1.get_ylim() == (0, 100)
248
+
249
+ fig, ax = plt.subplots()
250
+ ax.axhline(30)
251
+ ax.plot(Quantity(np.arange(0, 3), "miles"),
252
+ Quantity(np.arange(0, 6, 2), "feet"))
253
+ fig.draw_without_rendering()
254
+ assert ax.get_xlim() == (0, 2)
255
+ assert ax.get_ylim() == (0, 30)
256
+
257
+ fig, ax = plt.subplots()
258
+ ax.axvline(30)
259
+ ax.plot(Quantity(np.arange(0, 3), "miles"),
260
+ Quantity(np.arange(0, 6, 2), "feet"))
261
+ fig.draw_without_rendering()
262
+ assert ax.get_xlim() == (0, 30)
263
+ assert ax.get_ylim() == (0, 4)
264
+
265
+ fig, ax = plt.subplots()
266
+ ax.xaxis.update_units(Quantity([10], "miles"))
267
+ ax.axhline(30)
268
+ fig.draw_without_rendering()
269
+ assert ax.get_xlim() == (0, 100)
270
+ assert ax.get_ylim() == (28.5, 31.5)
271
+
272
+ fig, ax = plt.subplots()
273
+ ax.yaxis.update_units(Quantity([10], "miles"))
274
+ ax.axvline(30)
275
+ fig.draw_without_rendering()
276
+ assert ax.get_ylim() == (0, 100)
277
+ assert ax.get_xlim() == (28.5, 31.5)
278
+
279
+
280
+ # test array-like objects...
281
+ class Kernel:
282
+ def __init__(self, array):
283
+ self._array = np.asanyarray(array)
284
+
285
+ def __array__(self, dtype=None, copy=None):
286
+ if dtype is not None and dtype != self._array.dtype:
287
+ if copy is not None and not copy:
288
+ raise ValueError(
289
+ f"Converting array from {self._array.dtype} to "
290
+ f"{dtype} requires a copy"
291
+ )
292
+
293
+ arr = np.asarray(self._array, dtype=dtype)
294
+ return (arr if not copy else np.copy(arr))
295
+
296
+ @property
297
+ def shape(self):
298
+ return self._array.shape
299
+
300
+
301
+ def test_plot_kernel():
302
+ # just a smoketest that fail
303
+ kernel = Kernel([1, 2, 3, 4, 5])
304
+ plt.plot(kernel)
parrot/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from tempfile import TemporaryFile
2
+
3
+ import numpy as np
4
+ from packaging.version import parse as parse_version
5
+ import pytest
6
+
7
+ import matplotlib as mpl
8
+ from matplotlib import dviread
9
+ from matplotlib.testing import _has_tex_package
10
+ from matplotlib.testing.decorators import check_figures_equal, image_comparison
11
+ from matplotlib.testing._markers import needs_usetex
12
+ import matplotlib.pyplot as plt
13
+
14
+
15
+ pytestmark = needs_usetex
16
+
17
+
18
+ @image_comparison(
19
+ baseline_images=['test_usetex'],
20
+ extensions=['pdf', 'png'],
21
+ style="mpl20")
22
+ def test_usetex():
23
+ mpl.rcParams['text.usetex'] = True
24
+ fig, ax = plt.subplots()
25
+ kwargs = {"verticalalignment": "baseline", "size": 24,
26
+ "bbox": dict(pad=0, edgecolor="k", facecolor="none")}
27
+ ax.text(0.2, 0.7,
28
+ # the \LaTeX macro exercises character sizing and placement,
29
+ # \left[ ... \right\} draw some variable-height characters,
30
+ # \sqrt and \frac draw horizontal rules, \mathrm changes the font
31
+ r'\LaTeX\ $\left[\int\limits_e^{2e}'
32
+ r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$',
33
+ **kwargs)
34
+ ax.text(0.2, 0.3, "lg", **kwargs)
35
+ ax.text(0.4, 0.3, r"$\frac{1}{2}\pi$", **kwargs)
36
+ ax.text(0.6, 0.3, "$p^{3^A}$", **kwargs)
37
+ ax.text(0.8, 0.3, "$p_{3_2}$", **kwargs)
38
+ for x in {t.get_position()[0] for t in ax.texts}:
39
+ ax.axvline(x)
40
+ for y in {t.get_position()[1] for t in ax.texts}:
41
+ ax.axhline(y)
42
+ ax.set_axis_off()
43
+
44
+
45
+ @check_figures_equal()
46
+ def test_empty(fig_test, fig_ref):
47
+ mpl.rcParams['text.usetex'] = True
48
+ fig_test.text(.5, .5, "% a comment")
49
+
50
+
51
+ @check_figures_equal()
52
+ def test_unicode_minus(fig_test, fig_ref):
53
+ mpl.rcParams['text.usetex'] = True
54
+ fig_test.text(.5, .5, "$-$")
55
+ fig_ref.text(.5, .5, "\N{MINUS SIGN}")
56
+
57
+
58
+ def test_mathdefault():
59
+ plt.rcParams["axes.formatter.use_mathtext"] = True
60
+ fig = plt.figure()
61
+ fig.add_subplot().set_xlim(-1, 1)
62
+ # Check that \mathdefault commands generated by tickers don't cause
63
+ # problems when later switching usetex on.
64
+ mpl.rcParams['text.usetex'] = True
65
+ fig.canvas.draw()
66
+
67
+
68
+ @image_comparison(['eqnarray.png'])
69
+ def test_multiline_eqnarray():
70
+ text = (
71
+ r'\begin{eqnarray*}'
72
+ r'foo\\'
73
+ r'bar\\'
74
+ r'baz\\'
75
+ r'\end{eqnarray*}'
76
+ )
77
+
78
+ fig = plt.figure(figsize=(1, 1))
79
+ fig.text(0.5, 0.5, text, usetex=True,
80
+ horizontalalignment='center', verticalalignment='center')
81
+
82
+
83
+ @pytest.mark.parametrize("fontsize", [8, 10, 12])
84
+ def test_minus_no_descent(fontsize):
85
+ # Test special-casing of minus descent in DviFont._height_depth_of, by
86
+ # checking that overdrawing a 1 and a -1 results in an overall height
87
+ # equivalent to drawing either of them separately.
88
+ mpl.style.use("mpl20")
89
+ mpl.rcParams['font.size'] = fontsize
90
+ heights = {}
91
+ fig = plt.figure()
92
+ for vals in [(1,), (-1,), (-1, 1)]:
93
+ fig.clear()
94
+ for x in vals:
95
+ fig.text(.5, .5, f"${x}$", usetex=True)
96
+ fig.canvas.draw()
97
+ # The following counts the number of non-fully-blank pixel rows.
98
+ heights[vals] = ((np.array(fig.canvas.buffer_rgba())[..., 0] != 255)
99
+ .any(axis=1).sum())
100
+ assert len({*heights.values()}) == 1
101
+
102
+
103
+ @pytest.mark.parametrize('pkg', ['xcolor', 'chemformula'])
104
+ def test_usetex_packages(pkg):
105
+ if not _has_tex_package(pkg):
106
+ pytest.skip(f'{pkg} is not available')
107
+ mpl.rcParams['text.usetex'] = True
108
+
109
+ fig = plt.figure()
110
+ text = fig.text(0.5, 0.5, "Some text 0123456789")
111
+ fig.canvas.draw()
112
+
113
+ mpl.rcParams['text.latex.preamble'] = (
114
+ r'\PassOptionsToPackage{dvipsnames}{xcolor}\usepackage{%s}' % pkg)
115
+ fig = plt.figure()
116
+ text2 = fig.text(0.5, 0.5, "Some text 0123456789")
117
+ fig.canvas.draw()
118
+ np.testing.assert_array_equal(text2.get_window_extent(),
119
+ text.get_window_extent())
120
+
121
+
122
+ @pytest.mark.parametrize(
123
+ "preamble",
124
+ [r"\usepackage[full]{textcomp}", r"\usepackage{underscore}"],
125
+ )
126
+ def test_latex_pkg_already_loaded(preamble):
127
+ plt.rcParams["text.latex.preamble"] = preamble
128
+ fig = plt.figure()
129
+ fig.text(.5, .5, "hello, world", usetex=True)
130
+ fig.canvas.draw()
131
+
132
+
133
+ def test_usetex_with_underscore():
134
+ plt.rcParams["text.usetex"] = True
135
+ df = {"a_b": range(5)[::-1], "c": range(5)}
136
+ fig, ax = plt.subplots()
137
+ ax.plot("c", "a_b", data=df)
138
+ ax.legend()
139
+ ax.text(0, 0, "foo_bar", usetex=True)
140
+ plt.draw()
141
+
142
+
143
+ @pytest.mark.flaky(reruns=3) # Tends to hit a TeX cache lock on AppVeyor.
144
+ @pytest.mark.parametrize("fmt", ["pdf", "svg"])
145
+ def test_missing_psfont(fmt, monkeypatch):
146
+ """An error is raised if a TeX font lacks a Type-1 equivalent"""
147
+ monkeypatch.setattr(
148
+ dviread.PsfontsMap, '__getitem__',
149
+ lambda self, k: dviread.PsFont(
150
+ texname=b'texfont', psname=b'Some Font',
151
+ effects=None, encoding=None, filename=None))
152
+ mpl.rcParams['text.usetex'] = True
153
+ fig, ax = plt.subplots()
154
+ ax.text(0.5, 0.5, 'hello')
155
+ with TemporaryFile() as tmpfile, pytest.raises(ValueError):
156
+ fig.savefig(tmpfile, format=fmt)
157
+
158
+
159
+ try:
160
+ _old_gs_version = mpl._get_executable_info('gs').version < parse_version('9.55')
161
+ except mpl.ExecutableNotFoundError:
162
+ _old_gs_version = True
163
+
164
+
165
+ @image_comparison(baseline_images=['rotation'], extensions=['eps', 'pdf', 'png', 'svg'],
166
+ style='mpl20', tol=3.91 if _old_gs_version else 0)
167
+ def test_rotation():
168
+ mpl.rcParams['text.usetex'] = True
169
+
170
+ fig = plt.figure()
171
+ ax = fig.add_axes([0, 0, 1, 1])
172
+ ax.set(xlim=[-0.5, 5], xticks=[], ylim=[-0.5, 3], yticks=[], frame_on=False)
173
+
174
+ text = {val: val[0] for val in ['top', 'center', 'bottom', 'left', 'right']}
175
+ text['baseline'] = 'B'
176
+ text['center_baseline'] = 'C'
177
+
178
+ for i, va in enumerate(['top', 'center', 'bottom', 'baseline', 'center_baseline']):
179
+ for j, ha in enumerate(['left', 'center', 'right']):
180
+ for k, angle in enumerate([0, 90, 180, 270]):
181
+ k //= 2
182
+ x = i + k / 2
183
+ y = j + k / 2
184
+ ax.plot(x, y, '+', c=f'C{k}', markersize=20, markeredgewidth=0.5)
185
+ # 'My' checks full height letters plus descenders.
186
+ ax.text(x, y, f"$\\mathrm{{My {text[ha]}{text[va]} {angle}}}$",
187
+ rotation=angle, horizontalalignment=ha, verticalalignment=va)
parrot/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py ADDED
@@ -0,0 +1,1773 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import functools
2
+ import io
3
+ from unittest import mock
4
+
5
+ import matplotlib as mpl
6
+ from matplotlib.backend_bases import MouseEvent
7
+ import matplotlib.colors as mcolors
8
+ import matplotlib.widgets as widgets
9
+ import matplotlib.pyplot as plt
10
+ from matplotlib.testing.decorators import check_figures_equal, image_comparison
11
+ from matplotlib.testing.widgets import (click_and_drag, do_event, get_ax,
12
+ mock_event, noop)
13
+
14
+ import numpy as np
15
+ from numpy.testing import assert_allclose
16
+
17
+ import pytest
18
+
19
+
20
+ @pytest.fixture
21
+ def ax():
22
+ return get_ax()
23
+
24
+
25
+ def test_save_blitted_widget_as_pdf():
26
+ from matplotlib.widgets import CheckButtons, RadioButtons
27
+ from matplotlib.cbook import _get_running_interactive_framework
28
+ if _get_running_interactive_framework() not in ['headless', None]:
29
+ pytest.xfail("Callback exceptions are not raised otherwise.")
30
+
31
+ fig, ax = plt.subplots(
32
+ nrows=2, ncols=2, figsize=(5, 2), width_ratios=[1, 2]
33
+ )
34
+ default_rb = RadioButtons(ax[0, 0], ['Apples', 'Oranges'])
35
+ styled_rb = RadioButtons(
36
+ ax[0, 1], ['Apples', 'Oranges'],
37
+ label_props={'color': ['red', 'orange'],
38
+ 'fontsize': [16, 20]},
39
+ radio_props={'edgecolor': ['red', 'orange'],
40
+ 'facecolor': ['mistyrose', 'peachpuff']}
41
+ )
42
+
43
+ default_cb = CheckButtons(ax[1, 0], ['Apples', 'Oranges'],
44
+ actives=[True, True])
45
+ styled_cb = CheckButtons(
46
+ ax[1, 1], ['Apples', 'Oranges'],
47
+ actives=[True, True],
48
+ label_props={'color': ['red', 'orange'],
49
+ 'fontsize': [16, 20]},
50
+ frame_props={'edgecolor': ['red', 'orange'],
51
+ 'facecolor': ['mistyrose', 'peachpuff']},
52
+ check_props={'color': ['darkred', 'darkorange']}
53
+ )
54
+
55
+ ax[0, 0].set_title('Default')
56
+ ax[0, 1].set_title('Stylized')
57
+ # force an Agg render
58
+ fig.canvas.draw()
59
+ # force a pdf save
60
+ with io.BytesIO() as result_after:
61
+ fig.savefig(result_after, format='pdf')
62
+
63
+
64
+ @pytest.mark.parametrize('kwargs', [
65
+ dict(),
66
+ dict(useblit=True, button=1),
67
+ dict(minspanx=10, minspany=10, spancoords='pixels'),
68
+ dict(props=dict(fill=True)),
69
+ ])
70
+ def test_rectangle_selector(ax, kwargs):
71
+ onselect = mock.Mock(spec=noop, return_value=None)
72
+
73
+ tool = widgets.RectangleSelector(ax, onselect, **kwargs)
74
+ do_event(tool, 'press', xdata=100, ydata=100, button=1)
75
+ do_event(tool, 'onmove', xdata=199, ydata=199, button=1)
76
+
77
+ # purposely drag outside of axis for release
78
+ do_event(tool, 'release', xdata=250, ydata=250, button=1)
79
+
80
+ if kwargs.get('drawtype', None) not in ['line', 'none']:
81
+ assert_allclose(tool.geometry,
82
+ [[100., 100, 199, 199, 100],
83
+ [100, 199, 199, 100, 100]],
84
+ err_msg=tool.geometry)
85
+
86
+ onselect.assert_called_once()
87
+ (epress, erelease), kwargs = onselect.call_args
88
+ assert epress.xdata == 100
89
+ assert epress.ydata == 100
90
+ assert erelease.xdata == 199
91
+ assert erelease.ydata == 199
92
+ assert kwargs == {}
93
+
94
+
95
+ @pytest.mark.parametrize('spancoords', ['data', 'pixels'])
96
+ @pytest.mark.parametrize('minspanx, x1', [[0, 10], [1, 10.5], [1, 11]])
97
+ @pytest.mark.parametrize('minspany, y1', [[0, 10], [1, 10.5], [1, 11]])
98
+ def test_rectangle_minspan(ax, spancoords, minspanx, x1, minspany, y1):
99
+
100
+ onselect = mock.Mock(spec=noop, return_value=None)
101
+
102
+ x0, y0 = (10, 10)
103
+ if spancoords == 'pixels':
104
+ minspanx, minspany = (ax.transData.transform((x1, y1)) -
105
+ ax.transData.transform((x0, y0)))
106
+
107
+ tool = widgets.RectangleSelector(ax, onselect, interactive=True,
108
+ spancoords=spancoords,
109
+ minspanx=minspanx, minspany=minspany)
110
+ # Too small to create a selector
111
+ click_and_drag(tool, start=(x0, x1), end=(y0, y1))
112
+ assert not tool._selection_completed
113
+ onselect.assert_not_called()
114
+
115
+ click_and_drag(tool, start=(20, 20), end=(30, 30))
116
+ assert tool._selection_completed
117
+ onselect.assert_called_once()
118
+
119
+ # Too small to create a selector. Should clear existing selector, and
120
+ # trigger onselect because there was a preexisting selector
121
+ onselect.reset_mock()
122
+ click_and_drag(tool, start=(x0, y0), end=(x1, y1))
123
+ assert not tool._selection_completed
124
+ onselect.assert_called_once()
125
+ (epress, erelease), kwargs = onselect.call_args
126
+ assert epress.xdata == x0
127
+ assert epress.ydata == y0
128
+ assert erelease.xdata == x1
129
+ assert erelease.ydata == y1
130
+ assert kwargs == {}
131
+
132
+
133
+ def test_deprecation_selector_visible_attribute(ax):
134
+ tool = widgets.RectangleSelector(ax, lambda *args: None)
135
+
136
+ assert tool.get_visible()
137
+
138
+ with pytest.warns(mpl.MatplotlibDeprecationWarning,
139
+ match="was deprecated in Matplotlib 3.8"):
140
+ tool.visible
141
+
142
+
143
+ @pytest.mark.parametrize('drag_from_anywhere, new_center',
144
+ [[True, (60, 75)],
145
+ [False, (30, 20)]])
146
+ def test_rectangle_drag(ax, drag_from_anywhere, new_center):
147
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True,
148
+ drag_from_anywhere=drag_from_anywhere)
149
+ # Create rectangle
150
+ click_and_drag(tool, start=(0, 10), end=(100, 120))
151
+ assert tool.center == (50, 65)
152
+ # Drag inside rectangle, but away from centre handle
153
+ #
154
+ # If drag_from_anywhere == True, this will move the rectangle by (10, 10),
155
+ # giving it a new center of (60, 75)
156
+ #
157
+ # If drag_from_anywhere == False, this will create a new rectangle with
158
+ # center (30, 20)
159
+ click_and_drag(tool, start=(25, 15), end=(35, 25))
160
+ assert tool.center == new_center
161
+ # Check that in both cases, dragging outside the rectangle draws a new
162
+ # rectangle
163
+ click_and_drag(tool, start=(175, 185), end=(185, 195))
164
+ assert tool.center == (180, 190)
165
+
166
+
167
+ def test_rectangle_selector_set_props_handle_props(ax):
168
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True,
169
+ props=dict(facecolor='b', alpha=0.2),
170
+ handle_props=dict(alpha=0.5))
171
+ # Create rectangle
172
+ click_and_drag(tool, start=(0, 10), end=(100, 120))
173
+
174
+ artist = tool._selection_artist
175
+ assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2)
176
+ tool.set_props(facecolor='r', alpha=0.3)
177
+ assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3)
178
+
179
+ for artist in tool._handles_artists:
180
+ assert artist.get_markeredgecolor() == 'black'
181
+ assert artist.get_alpha() == 0.5
182
+ tool.set_handle_props(markeredgecolor='r', alpha=0.3)
183
+ for artist in tool._handles_artists:
184
+ assert artist.get_markeredgecolor() == 'r'
185
+ assert artist.get_alpha() == 0.3
186
+
187
+
188
+ def test_rectangle_resize(ax):
189
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True)
190
+ # Create rectangle
191
+ click_and_drag(tool, start=(0, 10), end=(100, 120))
192
+ assert tool.extents == (0.0, 100.0, 10.0, 120.0)
193
+
194
+ # resize NE handle
195
+ extents = tool.extents
196
+ xdata, ydata = extents[1], extents[3]
197
+ xdata_new, ydata_new = xdata + 10, ydata + 5
198
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
199
+ assert tool.extents == (extents[0], xdata_new, extents[2], ydata_new)
200
+
201
+ # resize E handle
202
+ extents = tool.extents
203
+ xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2
204
+ xdata_new, ydata_new = xdata + 10, ydata
205
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
206
+ assert tool.extents == (extents[0], xdata_new, extents[2], extents[3])
207
+
208
+ # resize W handle
209
+ extents = tool.extents
210
+ xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2
211
+ xdata_new, ydata_new = xdata + 15, ydata
212
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
213
+ assert tool.extents == (xdata_new, extents[1], extents[2], extents[3])
214
+
215
+ # resize SW handle
216
+ extents = tool.extents
217
+ xdata, ydata = extents[0], extents[2]
218
+ xdata_new, ydata_new = xdata + 20, ydata + 25
219
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
220
+ assert tool.extents == (xdata_new, extents[1], ydata_new, extents[3])
221
+
222
+
223
+ def test_rectangle_add_state(ax):
224
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True)
225
+ # Create rectangle
226
+ click_and_drag(tool, start=(70, 65), end=(125, 130))
227
+
228
+ with pytest.raises(ValueError):
229
+ tool.add_state('unsupported_state')
230
+
231
+ with pytest.raises(ValueError):
232
+ tool.add_state('clear')
233
+ tool.add_state('move')
234
+ tool.add_state('square')
235
+ tool.add_state('center')
236
+
237
+
238
+ @pytest.mark.parametrize('add_state', [True, False])
239
+ def test_rectangle_resize_center(ax, add_state):
240
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True)
241
+ # Create rectangle
242
+ click_and_drag(tool, start=(70, 65), end=(125, 130))
243
+ assert tool.extents == (70.0, 125.0, 65.0, 130.0)
244
+
245
+ if add_state:
246
+ tool.add_state('center')
247
+ use_key = None
248
+ else:
249
+ use_key = 'control'
250
+
251
+ # resize NE handle
252
+ extents = tool.extents
253
+ xdata, ydata = extents[1], extents[3]
254
+ xdiff, ydiff = 10, 5
255
+ xdata_new, ydata_new = xdata + xdiff, ydata + ydiff
256
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
257
+ key=use_key)
258
+ assert tool.extents == (extents[0] - xdiff, xdata_new,
259
+ extents[2] - ydiff, ydata_new)
260
+
261
+ # resize E handle
262
+ extents = tool.extents
263
+ xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2
264
+ xdiff = 10
265
+ xdata_new, ydata_new = xdata + xdiff, ydata
266
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
267
+ key=use_key)
268
+ assert tool.extents == (extents[0] - xdiff, xdata_new,
269
+ extents[2], extents[3])
270
+
271
+ # resize E handle negative diff
272
+ extents = tool.extents
273
+ xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2
274
+ xdiff = -20
275
+ xdata_new, ydata_new = xdata + xdiff, ydata
276
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
277
+ key=use_key)
278
+ assert tool.extents == (extents[0] - xdiff, xdata_new,
279
+ extents[2], extents[3])
280
+
281
+ # resize W handle
282
+ extents = tool.extents
283
+ xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2
284
+ xdiff = 15
285
+ xdata_new, ydata_new = xdata + xdiff, ydata
286
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
287
+ key=use_key)
288
+ assert tool.extents == (xdata_new, extents[1] - xdiff,
289
+ extents[2], extents[3])
290
+
291
+ # resize W handle negative diff
292
+ extents = tool.extents
293
+ xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2
294
+ xdiff = -25
295
+ xdata_new, ydata_new = xdata + xdiff, ydata
296
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
297
+ key=use_key)
298
+ assert tool.extents == (xdata_new, extents[1] - xdiff,
299
+ extents[2], extents[3])
300
+
301
+ # resize SW handle
302
+ extents = tool.extents
303
+ xdata, ydata = extents[0], extents[2]
304
+ xdiff, ydiff = 20, 25
305
+ xdata_new, ydata_new = xdata + xdiff, ydata + ydiff
306
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
307
+ key=use_key)
308
+ assert tool.extents == (xdata_new, extents[1] - xdiff,
309
+ ydata_new, extents[3] - ydiff)
310
+
311
+
312
+ @pytest.mark.parametrize('add_state', [True, False])
313
+ def test_rectangle_resize_square(ax, add_state):
314
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True)
315
+ # Create rectangle
316
+ click_and_drag(tool, start=(70, 65), end=(120, 115))
317
+ assert tool.extents == (70.0, 120.0, 65.0, 115.0)
318
+
319
+ if add_state:
320
+ tool.add_state('square')
321
+ use_key = None
322
+ else:
323
+ use_key = 'shift'
324
+
325
+ # resize NE handle
326
+ extents = tool.extents
327
+ xdata, ydata = extents[1], extents[3]
328
+ xdiff, ydiff = 10, 5
329
+ xdata_new, ydata_new = xdata + xdiff, ydata + ydiff
330
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
331
+ key=use_key)
332
+ assert tool.extents == (extents[0], xdata_new,
333
+ extents[2], extents[3] + xdiff)
334
+
335
+ # resize E handle
336
+ extents = tool.extents
337
+ xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2
338
+ xdiff = 10
339
+ xdata_new, ydata_new = xdata + xdiff, ydata
340
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
341
+ key=use_key)
342
+ assert tool.extents == (extents[0], xdata_new,
343
+ extents[2], extents[3] + xdiff)
344
+
345
+ # resize E handle negative diff
346
+ extents = tool.extents
347
+ xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2
348
+ xdiff = -20
349
+ xdata_new, ydata_new = xdata + xdiff, ydata
350
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
351
+ key=use_key)
352
+ assert tool.extents == (extents[0], xdata_new,
353
+ extents[2], extents[3] + xdiff)
354
+
355
+ # resize W handle
356
+ extents = tool.extents
357
+ xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2
358
+ xdiff = 15
359
+ xdata_new, ydata_new = xdata + xdiff, ydata
360
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
361
+ key=use_key)
362
+ assert tool.extents == (xdata_new, extents[1],
363
+ extents[2], extents[3] - xdiff)
364
+
365
+ # resize W handle negative diff
366
+ extents = tool.extents
367
+ xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2
368
+ xdiff = -25
369
+ xdata_new, ydata_new = xdata + xdiff, ydata
370
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
371
+ key=use_key)
372
+ assert tool.extents == (xdata_new, extents[1],
373
+ extents[2], extents[3] - xdiff)
374
+
375
+ # resize SW handle
376
+ extents = tool.extents
377
+ xdata, ydata = extents[0], extents[2]
378
+ xdiff, ydiff = 20, 25
379
+ xdata_new, ydata_new = xdata + xdiff, ydata + ydiff
380
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new),
381
+ key=use_key)
382
+ assert tool.extents == (extents[0] + ydiff, extents[1],
383
+ ydata_new, extents[3])
384
+
385
+
386
+ def test_rectangle_resize_square_center(ax):
387
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True)
388
+ # Create rectangle
389
+ click_and_drag(tool, start=(70, 65), end=(120, 115))
390
+ tool.add_state('square')
391
+ tool.add_state('center')
392
+ assert_allclose(tool.extents, (70.0, 120.0, 65.0, 115.0))
393
+
394
+ # resize NE handle
395
+ extents = tool.extents
396
+ xdata, ydata = extents[1], extents[3]
397
+ xdiff, ydiff = 10, 5
398
+ xdata_new, ydata_new = xdata + xdiff, ydata + ydiff
399
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
400
+ assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new,
401
+ extents[2] - xdiff, extents[3] + xdiff))
402
+
403
+ # resize E handle
404
+ extents = tool.extents
405
+ xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2
406
+ xdiff = 10
407
+ xdata_new, ydata_new = xdata + xdiff, ydata
408
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
409
+ assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new,
410
+ extents[2] - xdiff, extents[3] + xdiff))
411
+
412
+ # resize E handle negative diff
413
+ extents = tool.extents
414
+ xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2
415
+ xdiff = -20
416
+ xdata_new, ydata_new = xdata + xdiff, ydata
417
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
418
+ assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new,
419
+ extents[2] - xdiff, extents[3] + xdiff))
420
+
421
+ # resize W handle
422
+ extents = tool.extents
423
+ xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2
424
+ xdiff = 5
425
+ xdata_new, ydata_new = xdata + xdiff, ydata
426
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
427
+ assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff,
428
+ extents[2] + xdiff, extents[3] - xdiff))
429
+
430
+ # resize W handle negative diff
431
+ extents = tool.extents
432
+ xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2
433
+ xdiff = -25
434
+ xdata_new, ydata_new = xdata + xdiff, ydata
435
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
436
+ assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff,
437
+ extents[2] + xdiff, extents[3] - xdiff))
438
+
439
+ # resize SW handle
440
+ extents = tool.extents
441
+ xdata, ydata = extents[0], extents[2]
442
+ xdiff, ydiff = 20, 25
443
+ xdata_new, ydata_new = xdata + xdiff, ydata + ydiff
444
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
445
+ assert_allclose(tool.extents, (extents[0] + ydiff, extents[1] - ydiff,
446
+ ydata_new, extents[3] - ydiff))
447
+
448
+
449
+ @pytest.mark.parametrize('selector_class',
450
+ [widgets.RectangleSelector, widgets.EllipseSelector])
451
+ def test_rectangle_rotate(ax, selector_class):
452
+ tool = selector_class(ax, onselect=noop, interactive=True)
453
+ # Draw rectangle
454
+ click_and_drag(tool, start=(100, 100), end=(130, 140))
455
+ assert tool.extents == (100, 130, 100, 140)
456
+ assert len(tool._state) == 0
457
+
458
+ # Rotate anticlockwise using top-right corner
459
+ do_event(tool, 'on_key_press', key='r')
460
+ assert tool._state == {'rotate'}
461
+ assert len(tool._state) == 1
462
+ click_and_drag(tool, start=(130, 140), end=(120, 145))
463
+ do_event(tool, 'on_key_press', key='r')
464
+ assert len(tool._state) == 0
465
+ # Extents shouldn't change (as shape of rectangle hasn't changed)
466
+ assert tool.extents == (100, 130, 100, 140)
467
+ assert_allclose(tool.rotation, 25.56, atol=0.01)
468
+ tool.rotation = 45
469
+ assert tool.rotation == 45
470
+ # Corners should move
471
+ assert_allclose(tool.corners,
472
+ np.array([[118.53, 139.75, 111.46, 90.25],
473
+ [95.25, 116.46, 144.75, 123.54]]), atol=0.01)
474
+
475
+ # Scale using top-right corner
476
+ click_and_drag(tool, start=(110, 145), end=(110, 160))
477
+ assert_allclose(tool.extents, (100, 139.75, 100, 151.82), atol=0.01)
478
+
479
+ if selector_class == widgets.RectangleSelector:
480
+ with pytest.raises(ValueError):
481
+ tool._selection_artist.rotation_point = 'unvalid_value'
482
+
483
+
484
+ def test_rectangle_add_remove_set(ax):
485
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True)
486
+ # Draw rectangle
487
+ click_and_drag(tool, start=(100, 100), end=(130, 140))
488
+ assert tool.extents == (100, 130, 100, 140)
489
+ assert len(tool._state) == 0
490
+ for state in ['rotate', 'square', 'center']:
491
+ tool.add_state(state)
492
+ assert len(tool._state) == 1
493
+ tool.remove_state(state)
494
+ assert len(tool._state) == 0
495
+
496
+
497
+ @pytest.mark.parametrize('use_data_coordinates', [False, True])
498
+ def test_rectangle_resize_square_center_aspect(ax, use_data_coordinates):
499
+ ax.set_aspect(0.8)
500
+
501
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True,
502
+ use_data_coordinates=use_data_coordinates)
503
+ # Create rectangle
504
+ click_and_drag(tool, start=(70, 65), end=(120, 115))
505
+ assert tool.extents == (70.0, 120.0, 65.0, 115.0)
506
+ tool.add_state('square')
507
+ tool.add_state('center')
508
+
509
+ if use_data_coordinates:
510
+ # resize E handle
511
+ extents = tool.extents
512
+ xdata, ydata, width = extents[1], extents[3], extents[1] - extents[0]
513
+ xdiff, ycenter = 10, extents[2] + (extents[3] - extents[2]) / 2
514
+ xdata_new, ydata_new = xdata + xdiff, ydata
515
+ ychange = width / 2 + xdiff
516
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
517
+ assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new,
518
+ ycenter - ychange, ycenter + ychange])
519
+ else:
520
+ # resize E handle
521
+ extents = tool.extents
522
+ xdata, ydata = extents[1], extents[3]
523
+ xdiff = 10
524
+ xdata_new, ydata_new = xdata + xdiff, ydata
525
+ ychange = xdiff * 1 / tool._aspect_ratio_correction
526
+ click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new))
527
+ assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new,
528
+ 46.25, 133.75])
529
+
530
+
531
+ def test_ellipse(ax):
532
+ """For ellipse, test out the key modifiers"""
533
+ tool = widgets.EllipseSelector(ax, onselect=noop,
534
+ grab_range=10, interactive=True)
535
+ tool.extents = (100, 150, 100, 150)
536
+
537
+ # drag the rectangle
538
+ click_and_drag(tool, start=(125, 125), end=(145, 145))
539
+ assert tool.extents == (120, 170, 120, 170)
540
+
541
+ # create from center
542
+ click_and_drag(tool, start=(100, 100), end=(125, 125), key='control')
543
+ assert tool.extents == (75, 125, 75, 125)
544
+
545
+ # create a square
546
+ click_and_drag(tool, start=(10, 10), end=(35, 30), key='shift')
547
+ extents = [int(e) for e in tool.extents]
548
+ assert extents == [10, 35, 10, 35]
549
+
550
+ # create a square from center
551
+ click_and_drag(tool, start=(100, 100), end=(125, 130), key='ctrl+shift')
552
+ extents = [int(e) for e in tool.extents]
553
+ assert extents == [70, 130, 70, 130]
554
+
555
+ assert tool.geometry.shape == (2, 73)
556
+ assert_allclose(tool.geometry[:, 0], [70., 100])
557
+
558
+
559
+ def test_rectangle_handles(ax):
560
+ tool = widgets.RectangleSelector(ax, onselect=noop,
561
+ grab_range=10,
562
+ interactive=True,
563
+ handle_props={'markerfacecolor': 'r',
564
+ 'markeredgecolor': 'b'})
565
+ tool.extents = (100, 150, 100, 150)
566
+
567
+ assert_allclose(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150)))
568
+ assert tool.extents == (100, 150, 100, 150)
569
+ assert_allclose(tool.edge_centers,
570
+ ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150)))
571
+ assert tool.extents == (100, 150, 100, 150)
572
+
573
+ # grab a corner and move it
574
+ click_and_drag(tool, start=(100, 100), end=(120, 120))
575
+ assert tool.extents == (120, 150, 120, 150)
576
+
577
+ # grab the center and move it
578
+ click_and_drag(tool, start=(132, 132), end=(120, 120))
579
+ assert tool.extents == (108, 138, 108, 138)
580
+
581
+ # create a new rectangle
582
+ click_and_drag(tool, start=(10, 10), end=(100, 100))
583
+ assert tool.extents == (10, 100, 10, 100)
584
+
585
+ # Check that marker_props worked.
586
+ assert mcolors.same_color(
587
+ tool._corner_handles.artists[0].get_markerfacecolor(), 'r')
588
+ assert mcolors.same_color(
589
+ tool._corner_handles.artists[0].get_markeredgecolor(), 'b')
590
+
591
+
592
+ @pytest.mark.parametrize('interactive', [True, False])
593
+ def test_rectangle_selector_onselect(ax, interactive):
594
+ # check when press and release events take place at the same position
595
+ onselect = mock.Mock(spec=noop, return_value=None)
596
+
597
+ tool = widgets.RectangleSelector(ax, onselect, interactive=interactive)
598
+ # move outside of axis
599
+ click_and_drag(tool, start=(100, 110), end=(150, 120))
600
+
601
+ onselect.assert_called_once()
602
+ assert tool.extents == (100.0, 150.0, 110.0, 120.0)
603
+
604
+ onselect.reset_mock()
605
+ click_and_drag(tool, start=(10, 100), end=(10, 100))
606
+ onselect.assert_called_once()
607
+
608
+
609
+ @pytest.mark.parametrize('ignore_event_outside', [True, False])
610
+ def test_rectangle_selector_ignore_outside(ax, ignore_event_outside):
611
+ onselect = mock.Mock(spec=noop, return_value=None)
612
+
613
+ tool = widgets.RectangleSelector(ax, onselect,
614
+ ignore_event_outside=ignore_event_outside)
615
+ click_and_drag(tool, start=(100, 110), end=(150, 120))
616
+ onselect.assert_called_once()
617
+ assert tool.extents == (100.0, 150.0, 110.0, 120.0)
618
+
619
+ onselect.reset_mock()
620
+ # Trigger event outside of span
621
+ click_and_drag(tool, start=(150, 150), end=(160, 160))
622
+ if ignore_event_outside:
623
+ # event have been ignored and span haven't changed.
624
+ onselect.assert_not_called()
625
+ assert tool.extents == (100.0, 150.0, 110.0, 120.0)
626
+ else:
627
+ # A new shape is created
628
+ onselect.assert_called_once()
629
+ assert tool.extents == (150.0, 160.0, 150.0, 160.0)
630
+
631
+
632
+ @pytest.mark.parametrize('orientation, onmove_callback, kwargs', [
633
+ ('horizontal', False, dict(minspan=10, useblit=True)),
634
+ ('vertical', True, dict(button=1)),
635
+ ('horizontal', False, dict(props=dict(fill=True))),
636
+ ('horizontal', False, dict(interactive=True)),
637
+ ])
638
+ def test_span_selector(ax, orientation, onmove_callback, kwargs):
639
+ onselect = mock.Mock(spec=noop, return_value=None)
640
+ onmove = mock.Mock(spec=noop, return_value=None)
641
+ if onmove_callback:
642
+ kwargs['onmove_callback'] = onmove
643
+
644
+ # While at it, also test that span selectors work in the presence of twin axes on
645
+ # top of the axes that contain the selector. Note that we need to unforce the axes
646
+ # aspect here, otherwise the twin axes forces the original axes' limits (to respect
647
+ # aspect=1) which makes some of the values below go out of bounds.
648
+ ax.set_aspect("auto")
649
+ tax = ax.twinx()
650
+
651
+ tool = widgets.SpanSelector(ax, onselect, orientation, **kwargs)
652
+ do_event(tool, 'press', xdata=100, ydata=100, button=1)
653
+ # move outside of axis
654
+ do_event(tool, 'onmove', xdata=199, ydata=199, button=1)
655
+ do_event(tool, 'release', xdata=250, ydata=250, button=1)
656
+
657
+ onselect.assert_called_once_with(100, 199)
658
+ if onmove_callback:
659
+ onmove.assert_called_once_with(100, 199)
660
+
661
+
662
+ @pytest.mark.parametrize('interactive', [True, False])
663
+ def test_span_selector_onselect(ax, interactive):
664
+ onselect = mock.Mock(spec=noop, return_value=None)
665
+
666
+ tool = widgets.SpanSelector(ax, onselect, 'horizontal',
667
+ interactive=interactive)
668
+ # move outside of axis
669
+ click_and_drag(tool, start=(100, 100), end=(150, 100))
670
+ onselect.assert_called_once()
671
+ assert tool.extents == (100, 150)
672
+
673
+ onselect.reset_mock()
674
+ click_and_drag(tool, start=(10, 100), end=(10, 100))
675
+ onselect.assert_called_once()
676
+
677
+
678
+ @pytest.mark.parametrize('ignore_event_outside', [True, False])
679
+ def test_span_selector_ignore_outside(ax, ignore_event_outside):
680
+ onselect = mock.Mock(spec=noop, return_value=None)
681
+ onmove = mock.Mock(spec=noop, return_value=None)
682
+
683
+ tool = widgets.SpanSelector(ax, onselect, 'horizontal',
684
+ onmove_callback=onmove,
685
+ ignore_event_outside=ignore_event_outside)
686
+ click_and_drag(tool, start=(100, 100), end=(125, 125))
687
+ onselect.assert_called_once()
688
+ onmove.assert_called_once()
689
+ assert tool.extents == (100, 125)
690
+
691
+ onselect.reset_mock()
692
+ onmove.reset_mock()
693
+ # Trigger event outside of span
694
+ click_and_drag(tool, start=(150, 150), end=(160, 160))
695
+ if ignore_event_outside:
696
+ # event have been ignored and span haven't changed.
697
+ onselect.assert_not_called()
698
+ onmove.assert_not_called()
699
+ assert tool.extents == (100, 125)
700
+ else:
701
+ # A new shape is created
702
+ onselect.assert_called_once()
703
+ onmove.assert_called_once()
704
+ assert tool.extents == (150, 160)
705
+
706
+
707
+ @pytest.mark.parametrize('drag_from_anywhere', [True, False])
708
+ def test_span_selector_drag(ax, drag_from_anywhere):
709
+ # Create span
710
+ tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',
711
+ interactive=True,
712
+ drag_from_anywhere=drag_from_anywhere)
713
+ click_and_drag(tool, start=(10, 10), end=(100, 120))
714
+ assert tool.extents == (10, 100)
715
+ # Drag inside span
716
+ #
717
+ # If drag_from_anywhere == True, this will move the span by 10,
718
+ # giving new value extents = 20, 110
719
+ #
720
+ # If drag_from_anywhere == False, this will create a new span with
721
+ # value extents = 25, 35
722
+ click_and_drag(tool, start=(25, 15), end=(35, 25))
723
+ if drag_from_anywhere:
724
+ assert tool.extents == (20, 110)
725
+ else:
726
+ assert tool.extents == (25, 35)
727
+
728
+ # Check that in both cases, dragging outside the span draws a new span
729
+ click_and_drag(tool, start=(175, 185), end=(185, 195))
730
+ assert tool.extents == (175, 185)
731
+
732
+
733
+ def test_span_selector_direction(ax):
734
+ tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',
735
+ interactive=True)
736
+ assert tool.direction == 'horizontal'
737
+ assert tool._edge_handles.direction == 'horizontal'
738
+
739
+ with pytest.raises(ValueError):
740
+ tool = widgets.SpanSelector(ax, onselect=noop,
741
+ direction='invalid_direction')
742
+
743
+ tool.direction = 'vertical'
744
+ assert tool.direction == 'vertical'
745
+ assert tool._edge_handles.direction == 'vertical'
746
+
747
+ with pytest.raises(ValueError):
748
+ tool.direction = 'invalid_string'
749
+
750
+
751
+ def test_span_selector_set_props_handle_props(ax):
752
+ tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',
753
+ interactive=True,
754
+ props=dict(facecolor='b', alpha=0.2),
755
+ handle_props=dict(alpha=0.5))
756
+ # Create rectangle
757
+ click_and_drag(tool, start=(0, 10), end=(100, 120))
758
+
759
+ artist = tool._selection_artist
760
+ assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2)
761
+ tool.set_props(facecolor='r', alpha=0.3)
762
+ assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3)
763
+
764
+ for artist in tool._handles_artists:
765
+ assert artist.get_color() == 'b'
766
+ assert artist.get_alpha() == 0.5
767
+ tool.set_handle_props(color='r', alpha=0.3)
768
+ for artist in tool._handles_artists:
769
+ assert artist.get_color() == 'r'
770
+ assert artist.get_alpha() == 0.3
771
+
772
+
773
+ @pytest.mark.parametrize('selector', ['span', 'rectangle'])
774
+ def test_selector_clear(ax, selector):
775
+ kwargs = dict(ax=ax, onselect=noop, interactive=True)
776
+ if selector == 'span':
777
+ Selector = widgets.SpanSelector
778
+ kwargs['direction'] = 'horizontal'
779
+ else:
780
+ Selector = widgets.RectangleSelector
781
+
782
+ tool = Selector(**kwargs)
783
+ click_and_drag(tool, start=(10, 10), end=(100, 120))
784
+
785
+ # press-release event outside the selector to clear the selector
786
+ click_and_drag(tool, start=(130, 130), end=(130, 130))
787
+ assert not tool._selection_completed
788
+
789
+ kwargs['ignore_event_outside'] = True
790
+ tool = Selector(**kwargs)
791
+ assert tool.ignore_event_outside
792
+ click_and_drag(tool, start=(10, 10), end=(100, 120))
793
+
794
+ # press-release event outside the selector ignored
795
+ click_and_drag(tool, start=(130, 130), end=(130, 130))
796
+ assert tool._selection_completed
797
+
798
+ do_event(tool, 'on_key_press', key='escape')
799
+ assert not tool._selection_completed
800
+
801
+
802
+ @pytest.mark.parametrize('selector', ['span', 'rectangle'])
803
+ def test_selector_clear_method(ax, selector):
804
+ if selector == 'span':
805
+ tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal',
806
+ interactive=True,
807
+ ignore_event_outside=True)
808
+ else:
809
+ tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True)
810
+ click_and_drag(tool, start=(10, 10), end=(100, 120))
811
+ assert tool._selection_completed
812
+ assert tool.get_visible()
813
+ if selector == 'span':
814
+ assert tool.extents == (10, 100)
815
+
816
+ tool.clear()
817
+ assert not tool._selection_completed
818
+ assert not tool.get_visible()
819
+
820
+ # Do another cycle of events to make sure we can
821
+ click_and_drag(tool, start=(10, 10), end=(50, 120))
822
+ assert tool._selection_completed
823
+ assert tool.get_visible()
824
+ if selector == 'span':
825
+ assert tool.extents == (10, 50)
826
+
827
+
828
+ def test_span_selector_add_state(ax):
829
+ tool = widgets.SpanSelector(ax, noop, 'horizontal',
830
+ interactive=True)
831
+
832
+ with pytest.raises(ValueError):
833
+ tool.add_state('unsupported_state')
834
+ with pytest.raises(ValueError):
835
+ tool.add_state('center')
836
+ with pytest.raises(ValueError):
837
+ tool.add_state('square')
838
+
839
+ tool.add_state('move')
840
+
841
+
842
+ def test_tool_line_handle(ax):
843
+ positions = [20, 30, 50]
844
+ tool_line_handle = widgets.ToolLineHandles(ax, positions, 'horizontal',
845
+ useblit=False)
846
+
847
+ for artist in tool_line_handle.artists:
848
+ assert not artist.get_animated()
849
+ assert not artist.get_visible()
850
+
851
+ tool_line_handle.set_visible(True)
852
+ tool_line_handle.set_animated(True)
853
+
854
+ for artist in tool_line_handle.artists:
855
+ assert artist.get_animated()
856
+ assert artist.get_visible()
857
+
858
+ assert tool_line_handle.positions == positions
859
+
860
+
861
+ @pytest.mark.parametrize('direction', ("horizontal", "vertical"))
862
+ def test_span_selector_bound(direction):
863
+ fig, ax = plt.subplots(1, 1)
864
+ ax.plot([10, 20], [10, 30])
865
+ ax.figure.canvas.draw()
866
+ x_bound = ax.get_xbound()
867
+ y_bound = ax.get_ybound()
868
+
869
+ tool = widgets.SpanSelector(ax, print, direction, interactive=True)
870
+ assert ax.get_xbound() == x_bound
871
+ assert ax.get_ybound() == y_bound
872
+
873
+ bound = x_bound if direction == 'horizontal' else y_bound
874
+ assert tool._edge_handles.positions == list(bound)
875
+
876
+ press_data = (10.5, 11.5)
877
+ move_data = (11, 13) # Updating selector is done in onmove
878
+ release_data = move_data
879
+ click_and_drag(tool, start=press_data, end=move_data)
880
+
881
+ assert ax.get_xbound() == x_bound
882
+ assert ax.get_ybound() == y_bound
883
+
884
+ index = 0 if direction == 'horizontal' else 1
885
+ handle_positions = [press_data[index], release_data[index]]
886
+ assert tool._edge_handles.positions == handle_positions
887
+
888
+
889
+ @pytest.mark.backend('QtAgg', skip_on_importerror=True)
890
+ def test_span_selector_animated_artists_callback():
891
+ """Check that the animated artists changed in callbacks are updated."""
892
+ x = np.linspace(0, 2 * np.pi, 100)
893
+ values = np.sin(x)
894
+
895
+ fig, ax = plt.subplots()
896
+ ln, = ax.plot(x, values, animated=True)
897
+ ln2, = ax.plot([], animated=True)
898
+
899
+ # spin the event loop to let the backend process any pending operations
900
+ # before drawing artists
901
+ # See blitting tutorial
902
+ plt.pause(0.1)
903
+ ax.draw_artist(ln)
904
+ fig.canvas.blit(fig.bbox)
905
+
906
+ def mean(vmin, vmax):
907
+ # Return mean of values in x between *vmin* and *vmax*
908
+ indmin, indmax = np.searchsorted(x, (vmin, vmax))
909
+ v = values[indmin:indmax].mean()
910
+ ln2.set_data(x, np.full_like(x, v))
911
+
912
+ span = widgets.SpanSelector(ax, mean, direction='horizontal',
913
+ onmove_callback=mean,
914
+ interactive=True,
915
+ drag_from_anywhere=True,
916
+ useblit=True)
917
+
918
+ # Add span selector and check that the line is draw after it was updated
919
+ # by the callback
920
+ press_data = [1, 2]
921
+ move_data = [2, 2]
922
+ do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1)
923
+ do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1)
924
+ assert span._get_animated_artists() == (ln, ln2)
925
+ assert ln.stale is False
926
+ assert ln2.stale
927
+ assert_allclose(ln2.get_ydata(), 0.9547335049088455)
928
+ span.update()
929
+ assert ln2.stale is False
930
+
931
+ # Change span selector and check that the line is drawn/updated after its
932
+ # value was updated by the callback
933
+ press_data = [4, 0]
934
+ move_data = [5, 2]
935
+ release_data = [5, 2]
936
+ do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1)
937
+ do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1)
938
+ assert ln.stale is False
939
+ assert ln2.stale
940
+ assert_allclose(ln2.get_ydata(), -0.9424150707548072)
941
+ do_event(span, 'release', xdata=release_data[0],
942
+ ydata=release_data[1], button=1)
943
+ assert ln2.stale is False
944
+
945
+
946
+ def test_snapping_values_span_selector(ax):
947
+ def onselect(*args):
948
+ pass
949
+
950
+ tool = widgets.SpanSelector(ax, onselect, direction='horizontal',)
951
+ snap_function = tool._snap
952
+
953
+ snap_values = np.linspace(0, 5, 11)
954
+ values = np.array([-0.1, 0.1, 0.2, 0.5, 0.6, 0.7, 0.9, 4.76, 5.0, 5.5])
955
+ expect = np.array([00.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 5.00, 5.0, 5.0])
956
+ values = snap_function(values, snap_values)
957
+ assert_allclose(values, expect)
958
+
959
+
960
+ def test_span_selector_snap(ax):
961
+ def onselect(vmin, vmax):
962
+ ax._got_onselect = True
963
+
964
+ snap_values = np.arange(50) * 4
965
+
966
+ tool = widgets.SpanSelector(ax, onselect, direction='horizontal',
967
+ snap_values=snap_values)
968
+ tool.extents = (17, 35)
969
+ assert tool.extents == (16, 36)
970
+
971
+ tool.snap_values = None
972
+ assert tool.snap_values is None
973
+ tool.extents = (17, 35)
974
+ assert tool.extents == (17, 35)
975
+
976
+
977
+ def test_span_selector_extents(ax):
978
+ tool = widgets.SpanSelector(
979
+ ax, lambda a, b: None, "horizontal", ignore_event_outside=True
980
+ )
981
+ tool.extents = (5, 10)
982
+
983
+ assert tool.extents == (5, 10)
984
+ assert tool._selection_completed
985
+
986
+ # Since `ignore_event_outside=True`, this event should be ignored
987
+ press_data = (12, 14)
988
+ release_data = (20, 14)
989
+ click_and_drag(tool, start=press_data, end=release_data)
990
+
991
+ assert tool.extents == (5, 10)
992
+
993
+
994
+ @pytest.mark.parametrize('kwargs', [
995
+ dict(),
996
+ dict(useblit=False, props=dict(color='red')),
997
+ dict(useblit=True, button=1),
998
+ ])
999
+ def test_lasso_selector(ax, kwargs):
1000
+ onselect = mock.Mock(spec=noop, return_value=None)
1001
+
1002
+ tool = widgets.LassoSelector(ax, onselect, **kwargs)
1003
+ do_event(tool, 'press', xdata=100, ydata=100, button=1)
1004
+ do_event(tool, 'onmove', xdata=125, ydata=125, button=1)
1005
+ do_event(tool, 'release', xdata=150, ydata=150, button=1)
1006
+
1007
+ onselect.assert_called_once_with([(100, 100), (125, 125), (150, 150)])
1008
+
1009
+
1010
+ def test_lasso_selector_set_props(ax):
1011
+ onselect = mock.Mock(spec=noop, return_value=None)
1012
+
1013
+ tool = widgets.LassoSelector(ax, onselect, props=dict(color='b', alpha=0.2))
1014
+
1015
+ artist = tool._selection_artist
1016
+ assert mcolors.same_color(artist.get_color(), 'b')
1017
+ assert artist.get_alpha() == 0.2
1018
+ tool.set_props(color='r', alpha=0.3)
1019
+ assert mcolors.same_color(artist.get_color(), 'r')
1020
+ assert artist.get_alpha() == 0.3
1021
+
1022
+
1023
+ def test_lasso_set_props(ax):
1024
+ onselect = mock.Mock(spec=noop, return_value=None)
1025
+ tool = widgets.Lasso(ax, (100, 100), onselect)
1026
+ line = tool.line
1027
+ assert mcolors.same_color(line.get_color(), 'black')
1028
+ assert line.get_linestyle() == '-'
1029
+ assert line.get_lw() == 2
1030
+ tool = widgets.Lasso(ax, (100, 100), onselect, props=dict(
1031
+ linestyle='-', color='darkblue', alpha=0.2, lw=1))
1032
+
1033
+ line = tool.line
1034
+ assert mcolors.same_color(line.get_color(), 'darkblue')
1035
+ assert line.get_alpha() == 0.2
1036
+ assert line.get_lw() == 1
1037
+ assert line.get_linestyle() == '-'
1038
+ line.set_color('r')
1039
+ line.set_alpha(0.3)
1040
+ assert mcolors.same_color(line.get_color(), 'r')
1041
+ assert line.get_alpha() == 0.3
1042
+
1043
+
1044
+ def test_CheckButtons(ax):
1045
+ labels = ('a', 'b', 'c')
1046
+ check = widgets.CheckButtons(ax, labels, (True, False, True))
1047
+ assert check.get_status() == [True, False, True]
1048
+ check.set_active(0)
1049
+ assert check.get_status() == [False, False, True]
1050
+ assert check.get_checked_labels() == ['c']
1051
+ check.clear()
1052
+ assert check.get_status() == [False, False, False]
1053
+ assert check.get_checked_labels() == []
1054
+
1055
+ for invalid_index in [-1, len(labels), len(labels)+5]:
1056
+ with pytest.raises(ValueError):
1057
+ check.set_active(index=invalid_index)
1058
+
1059
+ for invalid_value in ['invalid', -1]:
1060
+ with pytest.raises(TypeError):
1061
+ check.set_active(1, state=invalid_value)
1062
+
1063
+ cid = check.on_clicked(lambda: None)
1064
+ check.disconnect(cid)
1065
+
1066
+
1067
+ @pytest.mark.parametrize("toolbar", ["none", "toolbar2", "toolmanager"])
1068
+ def test_TextBox(ax, toolbar):
1069
+ # Avoid "toolmanager is provisional" warning.
1070
+ plt.rcParams._set("toolbar", toolbar)
1071
+
1072
+ submit_event = mock.Mock(spec=noop, return_value=None)
1073
+ text_change_event = mock.Mock(spec=noop, return_value=None)
1074
+ tool = widgets.TextBox(ax, '')
1075
+ tool.on_submit(submit_event)
1076
+ tool.on_text_change(text_change_event)
1077
+
1078
+ assert tool.text == ''
1079
+
1080
+ do_event(tool, '_click')
1081
+
1082
+ tool.set_val('x**2')
1083
+
1084
+ assert tool.text == 'x**2'
1085
+ assert text_change_event.call_count == 1
1086
+
1087
+ tool.begin_typing()
1088
+ tool.stop_typing()
1089
+
1090
+ assert submit_event.call_count == 2
1091
+
1092
+ do_event(tool, '_click', xdata=.5, ydata=.5) # Ensure the click is in the axes.
1093
+ do_event(tool, '_keypress', key='+')
1094
+ do_event(tool, '_keypress', key='5')
1095
+
1096
+ assert text_change_event.call_count == 3
1097
+
1098
+
1099
+ def test_RadioButtons(ax):
1100
+ radio = widgets.RadioButtons(ax, ('Radio 1', 'Radio 2', 'Radio 3'))
1101
+ radio.set_active(1)
1102
+ assert radio.value_selected == 'Radio 2'
1103
+ assert radio.index_selected == 1
1104
+ radio.clear()
1105
+ assert radio.value_selected == 'Radio 1'
1106
+ assert radio.index_selected == 0
1107
+
1108
+
1109
+ @image_comparison(['check_radio_buttons.png'], style='mpl20', remove_text=True)
1110
+ def test_check_radio_buttons_image():
1111
+ ax = get_ax()
1112
+ fig = ax.figure
1113
+ fig.subplots_adjust(left=0.3)
1114
+
1115
+ rax1 = fig.add_axes((0.05, 0.7, 0.2, 0.15))
1116
+ rb1 = widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3'))
1117
+
1118
+ rax2 = fig.add_axes((0.05, 0.5, 0.2, 0.15))
1119
+ cb1 = widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'),
1120
+ (False, True, True))
1121
+
1122
+ rax3 = fig.add_axes((0.05, 0.3, 0.2, 0.15))
1123
+ rb3 = widgets.RadioButtons(
1124
+ rax3, ('Radio 1', 'Radio 2', 'Radio 3'),
1125
+ label_props={'fontsize': [8, 12, 16],
1126
+ 'color': ['red', 'green', 'blue']},
1127
+ radio_props={'edgecolor': ['red', 'green', 'blue'],
1128
+ 'facecolor': ['mistyrose', 'palegreen', 'lightblue']})
1129
+
1130
+ rax4 = fig.add_axes((0.05, 0.1, 0.2, 0.15))
1131
+ cb4 = widgets.CheckButtons(
1132
+ rax4, ('Check 1', 'Check 2', 'Check 3'), (False, True, True),
1133
+ label_props={'fontsize': [8, 12, 16],
1134
+ 'color': ['red', 'green', 'blue']},
1135
+ frame_props={'edgecolor': ['red', 'green', 'blue'],
1136
+ 'facecolor': ['mistyrose', 'palegreen', 'lightblue']},
1137
+ check_props={'color': ['red', 'green', 'blue']})
1138
+
1139
+
1140
+ @check_figures_equal(extensions=["png"])
1141
+ def test_radio_buttons(fig_test, fig_ref):
1142
+ widgets.RadioButtons(fig_test.subplots(), ["tea", "coffee"])
1143
+ ax = fig_ref.add_subplot(xticks=[], yticks=[])
1144
+ ax.scatter([.15, .15], [2/3, 1/3], transform=ax.transAxes,
1145
+ s=(plt.rcParams["font.size"] / 2) ** 2, c=["C0", "none"])
1146
+ ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center")
1147
+ ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center")
1148
+
1149
+
1150
+ @check_figures_equal(extensions=['png'])
1151
+ def test_radio_buttons_props(fig_test, fig_ref):
1152
+ label_props = {'color': ['red'], 'fontsize': [24]}
1153
+ radio_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2}
1154
+
1155
+ widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'],
1156
+ label_props=label_props, radio_props=radio_props)
1157
+
1158
+ cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'])
1159
+ cb.set_label_props(label_props)
1160
+ # Setting the label size automatically increases default marker size, so we
1161
+ # need to do that here as well.
1162
+ cb.set_radio_props({**radio_props, 's': (24 / 2)**2})
1163
+
1164
+
1165
+ def test_radio_button_active_conflict(ax):
1166
+ with pytest.warns(UserWarning,
1167
+ match=r'Both the \*activecolor\* parameter'):
1168
+ rb = widgets.RadioButtons(ax, ['tea', 'coffee'], activecolor='red',
1169
+ radio_props={'facecolor': 'green'})
1170
+ # *radio_props*' facecolor wins over *activecolor*
1171
+ assert mcolors.same_color(rb._buttons.get_facecolor(), ['green', 'none'])
1172
+
1173
+
1174
+ @check_figures_equal(extensions=['png'])
1175
+ def test_radio_buttons_activecolor_change(fig_test, fig_ref):
1176
+ widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'],
1177
+ activecolor='green')
1178
+
1179
+ # Test property setter.
1180
+ cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'],
1181
+ activecolor='red')
1182
+ cb.activecolor = 'green'
1183
+
1184
+
1185
+ @check_figures_equal(extensions=["png"])
1186
+ def test_check_buttons(fig_test, fig_ref):
1187
+ widgets.CheckButtons(fig_test.subplots(), ["tea", "coffee"], [True, True])
1188
+ ax = fig_ref.add_subplot(xticks=[], yticks=[])
1189
+ ax.scatter([.15, .15], [2/3, 1/3], marker='s', transform=ax.transAxes,
1190
+ s=(plt.rcParams["font.size"] / 2) ** 2, c=["none", "none"])
1191
+ ax.scatter([.15, .15], [2/3, 1/3], marker='x', transform=ax.transAxes,
1192
+ s=(plt.rcParams["font.size"] / 2) ** 2, c=["k", "k"])
1193
+ ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center")
1194
+ ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center")
1195
+
1196
+
1197
+ @check_figures_equal(extensions=['png'])
1198
+ def test_check_button_props(fig_test, fig_ref):
1199
+ label_props = {'color': ['red'], 'fontsize': [24]}
1200
+ frame_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2}
1201
+ check_props = {'facecolor': 'red', 'linewidth': 2}
1202
+
1203
+ widgets.CheckButtons(fig_ref.subplots(), ['tea', 'coffee'], [True, True],
1204
+ label_props=label_props, frame_props=frame_props,
1205
+ check_props=check_props)
1206
+
1207
+ cb = widgets.CheckButtons(fig_test.subplots(), ['tea', 'coffee'],
1208
+ [True, True])
1209
+ cb.set_label_props(label_props)
1210
+ # Setting the label size automatically increases default marker size, so we
1211
+ # need to do that here as well.
1212
+ cb.set_frame_props({**frame_props, 's': (24 / 2)**2})
1213
+ # FIXME: Axes.scatter promotes facecolor to edgecolor on unfilled markers,
1214
+ # but Collection.update doesn't do that (it forgot the marker already).
1215
+ # This means we cannot pass facecolor to both setters directly.
1216
+ check_props['edgecolor'] = check_props.pop('facecolor')
1217
+ cb.set_check_props({**check_props, 's': (24 / 2)**2})
1218
+
1219
+
1220
+ def test_slider_slidermin_slidermax_invalid():
1221
+ fig, ax = plt.subplots()
1222
+ # test min/max with floats
1223
+ with pytest.raises(ValueError):
1224
+ widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1225
+ slidermin=10.0)
1226
+ with pytest.raises(ValueError):
1227
+ widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1228
+ slidermax=10.0)
1229
+
1230
+
1231
+ def test_slider_slidermin_slidermax():
1232
+ fig, ax = plt.subplots()
1233
+ slider_ = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1234
+ valinit=5.0)
1235
+
1236
+ slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1237
+ valinit=1.0, slidermin=slider_)
1238
+ assert slider.val == slider_.val
1239
+
1240
+ slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1241
+ valinit=10.0, slidermax=slider_)
1242
+ assert slider.val == slider_.val
1243
+
1244
+
1245
+ def test_slider_valmin_valmax():
1246
+ fig, ax = plt.subplots()
1247
+ slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1248
+ valinit=-10.0)
1249
+ assert slider.val == slider.valmin
1250
+
1251
+ slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1252
+ valinit=25.0)
1253
+ assert slider.val == slider.valmax
1254
+
1255
+
1256
+ def test_slider_valstep_snapping():
1257
+ fig, ax = plt.subplots()
1258
+ slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1259
+ valinit=11.4, valstep=1)
1260
+ assert slider.val == 11
1261
+
1262
+ slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0,
1263
+ valinit=11.4, valstep=[0, 1, 5.5, 19.7])
1264
+ assert slider.val == 5.5
1265
+
1266
+
1267
+ def test_slider_horizontal_vertical():
1268
+ fig, ax = plt.subplots()
1269
+ slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24,
1270
+ valinit=12, orientation='horizontal')
1271
+ slider.set_val(10)
1272
+ assert slider.val == 10
1273
+ # check the dimension of the slider patch in axes units
1274
+ box = slider.poly.get_extents().transformed(ax.transAxes.inverted())
1275
+ assert_allclose(box.bounds, [0, .25, 10/24, .5])
1276
+
1277
+ fig, ax = plt.subplots()
1278
+ slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24,
1279
+ valinit=12, orientation='vertical')
1280
+ slider.set_val(10)
1281
+ assert slider.val == 10
1282
+ # check the dimension of the slider patch in axes units
1283
+ box = slider.poly.get_extents().transformed(ax.transAxes.inverted())
1284
+ assert_allclose(box.bounds, [.25, 0, .5, 10/24])
1285
+
1286
+
1287
+ def test_slider_reset():
1288
+ fig, ax = plt.subplots()
1289
+ slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=1, valinit=.5)
1290
+ slider.set_val(0.75)
1291
+ slider.reset()
1292
+ assert slider.val == 0.5
1293
+
1294
+
1295
+ @pytest.mark.parametrize("orientation", ["horizontal", "vertical"])
1296
+ def test_range_slider(orientation):
1297
+ if orientation == "vertical":
1298
+ idx = [1, 0, 3, 2]
1299
+ else:
1300
+ idx = [0, 1, 2, 3]
1301
+
1302
+ fig, ax = plt.subplots()
1303
+
1304
+ slider = widgets.RangeSlider(
1305
+ ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation,
1306
+ valinit=[0.1, 0.34]
1307
+ )
1308
+ box = slider.poly.get_extents().transformed(ax.transAxes.inverted())
1309
+ assert_allclose(box.get_points().flatten()[idx], [0.1, 0.25, 0.34, 0.75])
1310
+
1311
+ # Check initial value is set correctly
1312
+ assert_allclose(slider.val, (0.1, 0.34))
1313
+
1314
+ def handle_positions(slider):
1315
+ if orientation == "vertical":
1316
+ return [h.get_ydata()[0] for h in slider._handles]
1317
+ else:
1318
+ return [h.get_xdata()[0] for h in slider._handles]
1319
+
1320
+ slider.set_val((0.4, 0.6))
1321
+ assert_allclose(slider.val, (0.4, 0.6))
1322
+ assert_allclose(handle_positions(slider), (0.4, 0.6))
1323
+
1324
+ box = slider.poly.get_extents().transformed(ax.transAxes.inverted())
1325
+ assert_allclose(box.get_points().flatten()[idx], [0.4, .25, 0.6, .75])
1326
+
1327
+ slider.set_val((0.2, 0.1))
1328
+ assert_allclose(slider.val, (0.1, 0.2))
1329
+ assert_allclose(handle_positions(slider), (0.1, 0.2))
1330
+
1331
+ slider.set_val((-1, 10))
1332
+ assert_allclose(slider.val, (0, 1))
1333
+ assert_allclose(handle_positions(slider), (0, 1))
1334
+
1335
+ slider.reset()
1336
+ assert_allclose(slider.val, (0.1, 0.34))
1337
+ assert_allclose(handle_positions(slider), (0.1, 0.34))
1338
+
1339
+
1340
+ @pytest.mark.parametrize("orientation", ["horizontal", "vertical"])
1341
+ def test_range_slider_same_init_values(orientation):
1342
+ if orientation == "vertical":
1343
+ idx = [1, 0, 3, 2]
1344
+ else:
1345
+ idx = [0, 1, 2, 3]
1346
+
1347
+ fig, ax = plt.subplots()
1348
+
1349
+ slider = widgets.RangeSlider(
1350
+ ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation,
1351
+ valinit=[0, 0]
1352
+ )
1353
+ box = slider.poly.get_extents().transformed(ax.transAxes.inverted())
1354
+ assert_allclose(box.get_points().flatten()[idx], [0, 0.25, 0, 0.75])
1355
+
1356
+
1357
+ def check_polygon_selector(event_sequence, expected_result, selections_count,
1358
+ **kwargs):
1359
+ """
1360
+ Helper function to test Polygon Selector.
1361
+
1362
+ Parameters
1363
+ ----------
1364
+ event_sequence : list of tuples (etype, dict())
1365
+ A sequence of events to perform. The sequence is a list of tuples
1366
+ where the first element of the tuple is an etype (e.g., 'onmove',
1367
+ 'press', etc.), and the second element of the tuple is a dictionary of
1368
+ the arguments for the event (e.g., xdata=5, key='shift', etc.).
1369
+ expected_result : list of vertices (xdata, ydata)
1370
+ The list of vertices that are expected to result from the event
1371
+ sequence.
1372
+ selections_count : int
1373
+ Wait for the tool to call its `onselect` function `selections_count`
1374
+ times, before comparing the result to the `expected_result`
1375
+ **kwargs
1376
+ Keyword arguments are passed to PolygonSelector.
1377
+ """
1378
+ ax = get_ax()
1379
+
1380
+ onselect = mock.Mock(spec=noop, return_value=None)
1381
+
1382
+ tool = widgets.PolygonSelector(ax, onselect, **kwargs)
1383
+
1384
+ for (etype, event_args) in event_sequence:
1385
+ do_event(tool, etype, **event_args)
1386
+
1387
+ assert onselect.call_count == selections_count
1388
+ assert onselect.call_args == ((expected_result, ), {})
1389
+
1390
+
1391
+ def polygon_place_vertex(xdata, ydata):
1392
+ return [('onmove', dict(xdata=xdata, ydata=ydata)),
1393
+ ('press', dict(xdata=xdata, ydata=ydata)),
1394
+ ('release', dict(xdata=xdata, ydata=ydata))]
1395
+
1396
+
1397
+ def polygon_remove_vertex(xdata, ydata):
1398
+ return [('onmove', dict(xdata=xdata, ydata=ydata)),
1399
+ ('press', dict(xdata=xdata, ydata=ydata, button=3)),
1400
+ ('release', dict(xdata=xdata, ydata=ydata, button=3))]
1401
+
1402
+
1403
+ @pytest.mark.parametrize('draw_bounding_box', [False, True])
1404
+ def test_polygon_selector(draw_bounding_box):
1405
+ check_selector = functools.partial(
1406
+ check_polygon_selector, draw_bounding_box=draw_bounding_box)
1407
+
1408
+ # Simple polygon
1409
+ expected_result = [(50, 50), (150, 50), (50, 150)]
1410
+ event_sequence = [
1411
+ *polygon_place_vertex(50, 50),
1412
+ *polygon_place_vertex(150, 50),
1413
+ *polygon_place_vertex(50, 150),
1414
+ *polygon_place_vertex(50, 50),
1415
+ ]
1416
+ check_selector(event_sequence, expected_result, 1)
1417
+
1418
+ # Move first vertex before completing the polygon.
1419
+ expected_result = [(75, 50), (150, 50), (50, 150)]
1420
+ event_sequence = [
1421
+ *polygon_place_vertex(50, 50),
1422
+ *polygon_place_vertex(150, 50),
1423
+ ('on_key_press', dict(key='control')),
1424
+ ('onmove', dict(xdata=50, ydata=50)),
1425
+ ('press', dict(xdata=50, ydata=50)),
1426
+ ('onmove', dict(xdata=75, ydata=50)),
1427
+ ('release', dict(xdata=75, ydata=50)),
1428
+ ('on_key_release', dict(key='control')),
1429
+ *polygon_place_vertex(50, 150),
1430
+ *polygon_place_vertex(75, 50),
1431
+ ]
1432
+ check_selector(event_sequence, expected_result, 1)
1433
+
1434
+ # Move first two vertices at once before completing the polygon.
1435
+ expected_result = [(50, 75), (150, 75), (50, 150)]
1436
+ event_sequence = [
1437
+ *polygon_place_vertex(50, 50),
1438
+ *polygon_place_vertex(150, 50),
1439
+ ('on_key_press', dict(key='shift')),
1440
+ ('onmove', dict(xdata=100, ydata=100)),
1441
+ ('press', dict(xdata=100, ydata=100)),
1442
+ ('onmove', dict(xdata=100, ydata=125)),
1443
+ ('release', dict(xdata=100, ydata=125)),
1444
+ ('on_key_release', dict(key='shift')),
1445
+ *polygon_place_vertex(50, 150),
1446
+ *polygon_place_vertex(50, 75),
1447
+ ]
1448
+ check_selector(event_sequence, expected_result, 1)
1449
+
1450
+ # Move first vertex after completing the polygon.
1451
+ expected_result = [(75, 50), (150, 50), (50, 150)]
1452
+ event_sequence = [
1453
+ *polygon_place_vertex(50, 50),
1454
+ *polygon_place_vertex(150, 50),
1455
+ *polygon_place_vertex(50, 150),
1456
+ *polygon_place_vertex(50, 50),
1457
+ ('onmove', dict(xdata=50, ydata=50)),
1458
+ ('press', dict(xdata=50, ydata=50)),
1459
+ ('onmove', dict(xdata=75, ydata=50)),
1460
+ ('release', dict(xdata=75, ydata=50)),
1461
+ ]
1462
+ check_selector(event_sequence, expected_result, 2)
1463
+
1464
+ # Move all vertices after completing the polygon.
1465
+ expected_result = [(75, 75), (175, 75), (75, 175)]
1466
+ event_sequence = [
1467
+ *polygon_place_vertex(50, 50),
1468
+ *polygon_place_vertex(150, 50),
1469
+ *polygon_place_vertex(50, 150),
1470
+ *polygon_place_vertex(50, 50),
1471
+ ('on_key_press', dict(key='shift')),
1472
+ ('onmove', dict(xdata=100, ydata=100)),
1473
+ ('press', dict(xdata=100, ydata=100)),
1474
+ ('onmove', dict(xdata=125, ydata=125)),
1475
+ ('release', dict(xdata=125, ydata=125)),
1476
+ ('on_key_release', dict(key='shift')),
1477
+ ]
1478
+ check_selector(event_sequence, expected_result, 2)
1479
+
1480
+ # Try to move a vertex and move all before placing any vertices.
1481
+ expected_result = [(50, 50), (150, 50), (50, 150)]
1482
+ event_sequence = [
1483
+ ('on_key_press', dict(key='control')),
1484
+ ('onmove', dict(xdata=100, ydata=100)),
1485
+ ('press', dict(xdata=100, ydata=100)),
1486
+ ('onmove', dict(xdata=125, ydata=125)),
1487
+ ('release', dict(xdata=125, ydata=125)),
1488
+ ('on_key_release', dict(key='control')),
1489
+ ('on_key_press', dict(key='shift')),
1490
+ ('onmove', dict(xdata=100, ydata=100)),
1491
+ ('press', dict(xdata=100, ydata=100)),
1492
+ ('onmove', dict(xdata=125, ydata=125)),
1493
+ ('release', dict(xdata=125, ydata=125)),
1494
+ ('on_key_release', dict(key='shift')),
1495
+ *polygon_place_vertex(50, 50),
1496
+ *polygon_place_vertex(150, 50),
1497
+ *polygon_place_vertex(50, 150),
1498
+ *polygon_place_vertex(50, 50),
1499
+ ]
1500
+ check_selector(event_sequence, expected_result, 1)
1501
+
1502
+ # Try to place vertex out-of-bounds, then reset, and start a new polygon.
1503
+ expected_result = [(50, 50), (150, 50), (50, 150)]
1504
+ event_sequence = [
1505
+ *polygon_place_vertex(50, 50),
1506
+ *polygon_place_vertex(250, 50),
1507
+ ('on_key_press', dict(key='escape')),
1508
+ ('on_key_release', dict(key='escape')),
1509
+ *polygon_place_vertex(50, 50),
1510
+ *polygon_place_vertex(150, 50),
1511
+ *polygon_place_vertex(50, 150),
1512
+ *polygon_place_vertex(50, 50),
1513
+ ]
1514
+ check_selector(event_sequence, expected_result, 1)
1515
+
1516
+
1517
+ @pytest.mark.parametrize('draw_bounding_box', [False, True])
1518
+ def test_polygon_selector_set_props_handle_props(ax, draw_bounding_box):
1519
+ tool = widgets.PolygonSelector(ax, onselect=noop,
1520
+ props=dict(color='b', alpha=0.2),
1521
+ handle_props=dict(alpha=0.5),
1522
+ draw_bounding_box=draw_bounding_box)
1523
+
1524
+ event_sequence = [
1525
+ *polygon_place_vertex(50, 50),
1526
+ *polygon_place_vertex(150, 50),
1527
+ *polygon_place_vertex(50, 150),
1528
+ *polygon_place_vertex(50, 50),
1529
+ ]
1530
+
1531
+ for (etype, event_args) in event_sequence:
1532
+ do_event(tool, etype, **event_args)
1533
+
1534
+ artist = tool._selection_artist
1535
+ assert artist.get_color() == 'b'
1536
+ assert artist.get_alpha() == 0.2
1537
+ tool.set_props(color='r', alpha=0.3)
1538
+ assert artist.get_color() == 'r'
1539
+ assert artist.get_alpha() == 0.3
1540
+
1541
+ for artist in tool._handles_artists:
1542
+ assert artist.get_color() == 'b'
1543
+ assert artist.get_alpha() == 0.5
1544
+ tool.set_handle_props(color='r', alpha=0.3)
1545
+ for artist in tool._handles_artists:
1546
+ assert artist.get_color() == 'r'
1547
+ assert artist.get_alpha() == 0.3
1548
+
1549
+
1550
+ @check_figures_equal()
1551
+ def test_rect_visibility(fig_test, fig_ref):
1552
+ # Check that requesting an invisible selector makes it invisible
1553
+ ax_test = fig_test.subplots()
1554
+ _ = fig_ref.subplots()
1555
+
1556
+ tool = widgets.RectangleSelector(ax_test, onselect=noop,
1557
+ props={'visible': False})
1558
+ tool.extents = (0.2, 0.8, 0.3, 0.7)
1559
+
1560
+
1561
+ # Change the order that the extra point is inserted in
1562
+ @pytest.mark.parametrize('idx', [1, 2, 3])
1563
+ @pytest.mark.parametrize('draw_bounding_box', [False, True])
1564
+ def test_polygon_selector_remove(idx, draw_bounding_box):
1565
+ verts = [(50, 50), (150, 50), (50, 150)]
1566
+ event_sequence = [polygon_place_vertex(*verts[0]),
1567
+ polygon_place_vertex(*verts[1]),
1568
+ polygon_place_vertex(*verts[2]),
1569
+ # Finish the polygon
1570
+ polygon_place_vertex(*verts[0])]
1571
+ # Add an extra point
1572
+ event_sequence.insert(idx, polygon_place_vertex(200, 200))
1573
+ # Remove the extra point
1574
+ event_sequence.append(polygon_remove_vertex(200, 200))
1575
+ # Flatten list of lists
1576
+ event_sequence = sum(event_sequence, [])
1577
+ check_polygon_selector(event_sequence, verts, 2,
1578
+ draw_bounding_box=draw_bounding_box)
1579
+
1580
+
1581
+ @pytest.mark.parametrize('draw_bounding_box', [False, True])
1582
+ def test_polygon_selector_remove_first_point(draw_bounding_box):
1583
+ verts = [(50, 50), (150, 50), (50, 150)]
1584
+ event_sequence = [
1585
+ *polygon_place_vertex(*verts[0]),
1586
+ *polygon_place_vertex(*verts[1]),
1587
+ *polygon_place_vertex(*verts[2]),
1588
+ *polygon_place_vertex(*verts[0]),
1589
+ *polygon_remove_vertex(*verts[0]),
1590
+ ]
1591
+ check_polygon_selector(event_sequence, verts[1:], 2,
1592
+ draw_bounding_box=draw_bounding_box)
1593
+
1594
+
1595
+ @pytest.mark.parametrize('draw_bounding_box', [False, True])
1596
+ def test_polygon_selector_redraw(ax, draw_bounding_box):
1597
+ verts = [(50, 50), (150, 50), (50, 150)]
1598
+ event_sequence = [
1599
+ *polygon_place_vertex(*verts[0]),
1600
+ *polygon_place_vertex(*verts[1]),
1601
+ *polygon_place_vertex(*verts[2]),
1602
+ *polygon_place_vertex(*verts[0]),
1603
+ # Polygon completed, now remove first two verts.
1604
+ *polygon_remove_vertex(*verts[1]),
1605
+ *polygon_remove_vertex(*verts[2]),
1606
+ # At this point the tool should be reset so we can add more vertices.
1607
+ *polygon_place_vertex(*verts[1]),
1608
+ ]
1609
+
1610
+ tool = widgets.PolygonSelector(ax, onselect=noop,
1611
+ draw_bounding_box=draw_bounding_box)
1612
+ for (etype, event_args) in event_sequence:
1613
+ do_event(tool, etype, **event_args)
1614
+ # After removing two verts, only one remains, and the
1615
+ # selector should be automatically resete
1616
+ assert tool.verts == verts[0:2]
1617
+
1618
+
1619
+ @pytest.mark.parametrize('draw_bounding_box', [False, True])
1620
+ @check_figures_equal(extensions=['png'])
1621
+ def test_polygon_selector_verts_setter(fig_test, fig_ref, draw_bounding_box):
1622
+ verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)]
1623
+ ax_test = fig_test.add_subplot()
1624
+
1625
+ tool_test = widgets.PolygonSelector(
1626
+ ax_test, onselect=noop, draw_bounding_box=draw_bounding_box)
1627
+ tool_test.verts = verts
1628
+ assert tool_test.verts == verts
1629
+
1630
+ ax_ref = fig_ref.add_subplot()
1631
+ tool_ref = widgets.PolygonSelector(
1632
+ ax_ref, onselect=noop, draw_bounding_box=draw_bounding_box)
1633
+ event_sequence = [
1634
+ *polygon_place_vertex(*verts[0]),
1635
+ *polygon_place_vertex(*verts[1]),
1636
+ *polygon_place_vertex(*verts[2]),
1637
+ *polygon_place_vertex(*verts[0]),
1638
+ ]
1639
+ for (etype, event_args) in event_sequence:
1640
+ do_event(tool_ref, etype, **event_args)
1641
+
1642
+
1643
+ def test_polygon_selector_box(ax):
1644
+ # Create a diamond (adjusting axes lims s.t. the diamond lies within axes limits).
1645
+ ax.set(xlim=(-10, 50), ylim=(-10, 50))
1646
+ verts = [(20, 0), (0, 20), (20, 40), (40, 20)]
1647
+ event_sequence = [
1648
+ *polygon_place_vertex(*verts[0]),
1649
+ *polygon_place_vertex(*verts[1]),
1650
+ *polygon_place_vertex(*verts[2]),
1651
+ *polygon_place_vertex(*verts[3]),
1652
+ *polygon_place_vertex(*verts[0]),
1653
+ ]
1654
+
1655
+ # Create selector
1656
+ tool = widgets.PolygonSelector(ax, onselect=noop, draw_bounding_box=True)
1657
+ for (etype, event_args) in event_sequence:
1658
+ do_event(tool, etype, **event_args)
1659
+
1660
+ # In order to trigger the correct callbacks, trigger events on the canvas
1661
+ # instead of the individual tools
1662
+ t = ax.transData
1663
+ canvas = ax.figure.canvas
1664
+
1665
+ # Scale to half size using the top right corner of the bounding box
1666
+ MouseEvent(
1667
+ "button_press_event", canvas, *t.transform((40, 40)), 1)._process()
1668
+ MouseEvent(
1669
+ "motion_notify_event", canvas, *t.transform((20, 20)))._process()
1670
+ MouseEvent(
1671
+ "button_release_event", canvas, *t.transform((20, 20)), 1)._process()
1672
+ np.testing.assert_allclose(
1673
+ tool.verts, [(10, 0), (0, 10), (10, 20), (20, 10)])
1674
+
1675
+ # Move using the center of the bounding box
1676
+ MouseEvent(
1677
+ "button_press_event", canvas, *t.transform((10, 10)), 1)._process()
1678
+ MouseEvent(
1679
+ "motion_notify_event", canvas, *t.transform((30, 30)))._process()
1680
+ MouseEvent(
1681
+ "button_release_event", canvas, *t.transform((30, 30)), 1)._process()
1682
+ np.testing.assert_allclose(
1683
+ tool.verts, [(30, 20), (20, 30), (30, 40), (40, 30)])
1684
+
1685
+ # Remove a point from the polygon and check that the box extents update
1686
+ np.testing.assert_allclose(
1687
+ tool._box.extents, (20.0, 40.0, 20.0, 40.0))
1688
+
1689
+ MouseEvent(
1690
+ "button_press_event", canvas, *t.transform((30, 20)), 3)._process()
1691
+ MouseEvent(
1692
+ "button_release_event", canvas, *t.transform((30, 20)), 3)._process()
1693
+ np.testing.assert_allclose(
1694
+ tool.verts, [(20, 30), (30, 40), (40, 30)])
1695
+ np.testing.assert_allclose(
1696
+ tool._box.extents, (20.0, 40.0, 30.0, 40.0))
1697
+
1698
+
1699
+ def test_polygon_selector_clear_method(ax):
1700
+ onselect = mock.Mock(spec=noop, return_value=None)
1701
+ tool = widgets.PolygonSelector(ax, onselect)
1702
+
1703
+ for result in ([(50, 50), (150, 50), (50, 150), (50, 50)],
1704
+ [(50, 50), (100, 50), (50, 150), (50, 50)]):
1705
+ for x, y in result:
1706
+ for etype, event_args in polygon_place_vertex(x, y):
1707
+ do_event(tool, etype, **event_args)
1708
+
1709
+ artist = tool._selection_artist
1710
+
1711
+ assert tool._selection_completed
1712
+ assert tool.get_visible()
1713
+ assert artist.get_visible()
1714
+ np.testing.assert_equal(artist.get_xydata(), result)
1715
+ assert onselect.call_args == ((result[:-1],), {})
1716
+
1717
+ tool.clear()
1718
+ assert not tool._selection_completed
1719
+ np.testing.assert_equal(artist.get_xydata(), [(0, 0)])
1720
+
1721
+
1722
+ @pytest.mark.parametrize("horizOn", [False, True])
1723
+ @pytest.mark.parametrize("vertOn", [False, True])
1724
+ def test_MultiCursor(horizOn, vertOn):
1725
+ (ax1, ax3) = plt.figure().subplots(2, sharex=True)
1726
+ ax2 = plt.figure().subplots()
1727
+
1728
+ # useblit=false to avoid having to draw the figure to cache the renderer
1729
+ multi = widgets.MultiCursor(
1730
+ None, (ax1, ax2), useblit=False, horizOn=horizOn, vertOn=vertOn
1731
+ )
1732
+
1733
+ # Only two of the axes should have a line drawn on them.
1734
+ assert len(multi.vlines) == 2
1735
+ assert len(multi.hlines) == 2
1736
+
1737
+ # mock a motion_notify_event
1738
+ # Can't use `do_event` as that helper requires the widget
1739
+ # to have a single .ax attribute.
1740
+ event = mock_event(ax1, xdata=.5, ydata=.25)
1741
+ multi.onmove(event)
1742
+ # force a draw + draw event to exercise clear
1743
+ ax1.figure.canvas.draw()
1744
+
1745
+ # the lines in the first two ax should both move
1746
+ for l in multi.vlines:
1747
+ assert l.get_xdata() == (.5, .5)
1748
+ for l in multi.hlines:
1749
+ assert l.get_ydata() == (.25, .25)
1750
+ # The relevant lines get turned on after move.
1751
+ assert len([line for line in multi.vlines if line.get_visible()]) == (
1752
+ 2 if vertOn else 0)
1753
+ assert len([line for line in multi.hlines if line.get_visible()]) == (
1754
+ 2 if horizOn else 0)
1755
+
1756
+ # After toggling settings, the opposite lines should be visible after move.
1757
+ multi.horizOn = not multi.horizOn
1758
+ multi.vertOn = not multi.vertOn
1759
+ event = mock_event(ax1, xdata=.5, ydata=.25)
1760
+ multi.onmove(event)
1761
+ assert len([line for line in multi.vlines if line.get_visible()]) == (
1762
+ 0 if vertOn else 2)
1763
+ assert len([line for line in multi.hlines if line.get_visible()]) == (
1764
+ 0 if horizOn else 2)
1765
+
1766
+ # test a move event in an Axes not part of the MultiCursor
1767
+ # the lines in ax1 and ax2 should not have moved.
1768
+ event = mock_event(ax3, xdata=.75, ydata=.75)
1769
+ multi.onmove(event)
1770
+ for l in multi.vlines:
1771
+ assert l.get_xdata() == (.5, .5)
1772
+ for l in multi.hlines:
1773
+ assert l.get_ydata() == (.25, .25)
parrot/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:01845c437f4655e3cf9cc4fc4e49cfd607431f22675e1b611129a90239f34822
3
+ size 1809
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:f5cb8a238ff1a628d203a73c22bd86656a7c88e96641c684bb28e84f53f43bc6
3
+ size 356425
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:cb752aa50c596be8c5714e74408a28fdf8dec0e851787da0d5e8c4a8770d794a
3
+ size 328017
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ea1b26a667d7f6fe12da2642f78577782778547a635bf2e5cecfc25bb5093001
3
+ size 414937
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:54046c485bd6db36bdb266721e706edaee02f9a8b1faf3e120edd3e5204955dc
3
+ size 380369
videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:ba34d0b520a7fb16d787f3d4e442da31e92c822920c2711bd0bd466d77e19696
3
+ size 270097
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (178 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/confusion_matrix.cpython-310.pyc ADDED
Binary file (14.7 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/det_curve.cpython-310.pyc ADDED
Binary file (10.6 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/precision_recall_curve.cpython-310.pyc ADDED
Binary file (12.6 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/regression.cpython-310.pyc ADDED
Binary file (13 kB). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (184 Bytes). View file
 
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__init__.py ADDED
File without changes
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py ADDED
@@ -0,0 +1,1228 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import itertools
2
+ import re
3
+ import warnings
4
+ from collections import defaultdict
5
+
6
+ import numpy as np
7
+ import pytest
8
+ import threadpoolctl
9
+ from math import log10, floor
10
+ from scipy.sparse import csr_matrix
11
+ from scipy.spatial.distance import cdist
12
+
13
+ from sklearn.metrics._pairwise_distances_reduction import (
14
+ BaseDistancesReductionDispatcher,
15
+ ArgKmin,
16
+ RadiusNeighbors,
17
+ sqeuclidean_row_norms,
18
+ )
19
+
20
+ from sklearn.metrics import euclidean_distances
21
+ from sklearn.utils.fixes import sp_version, parse_version
22
+ from sklearn.utils._testing import (
23
+ assert_array_equal,
24
+ assert_allclose,
25
+ create_memmap_backed_data,
26
+ )
27
+
28
+ # Common supported metric between scipy.spatial.distance.cdist
29
+ # and BaseDistanceReductionDispatcher.
30
+ # This allows constructing tests to check consistency of results
31
+ # of concrete BaseDistanceReductionDispatcher on some metrics using APIs
32
+ # from scipy and numpy.
33
+ CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS = [
34
+ "braycurtis",
35
+ "canberra",
36
+ "chebyshev",
37
+ "cityblock",
38
+ "euclidean",
39
+ "minkowski",
40
+ "seuclidean",
41
+ ]
42
+
43
+
44
+ def _get_metric_params_list(metric: str, n_features: int, seed: int = 1):
45
+ """Return list of dummy DistanceMetric kwargs for tests."""
46
+
47
+ # Distinguishing on cases not to compute unneeded datastructures.
48
+ rng = np.random.RandomState(seed)
49
+
50
+ if metric == "minkowski":
51
+ minkowski_kwargs = [dict(p=1.5), dict(p=2), dict(p=3), dict(p=np.inf)]
52
+ if sp_version >= parse_version("1.8.0.dev0"):
53
+ # TODO: remove the test once we no longer support scipy < 1.8.0.
54
+ # Recent scipy versions accept weights in the Minkowski metric directly:
55
+ # type: ignore
56
+ minkowski_kwargs.append(dict(p=3, w=rng.rand(n_features)))
57
+
58
+ return minkowski_kwargs
59
+
60
+ # TODO: remove this case for "wminkowski" once we no longer support scipy < 1.8.0.
61
+ if metric == "wminkowski":
62
+ weights = rng.random_sample(n_features)
63
+ weights /= weights.sum()
64
+ wminkowski_kwargs = [dict(p=1.5, w=weights)]
65
+ if sp_version < parse_version("1.8.0.dev0"):
66
+ # wminkowski was removed in scipy 1.8.0 but should work for previous
67
+ # versions.
68
+ wminkowski_kwargs.append(dict(p=3, w=rng.rand(n_features)))
69
+ return wminkowski_kwargs
70
+
71
+ if metric == "seuclidean":
72
+ return [dict(V=rng.rand(n_features))]
73
+
74
+ # Case of: "euclidean", "manhattan", "chebyshev", "haversine" or any other metric.
75
+ # In those cases, no kwargs is needed.
76
+ return [{}]
77
+
78
+
79
+ def assert_argkmin_results_equality(ref_dist, dist, ref_indices, indices, rtol=1e-7):
80
+ assert_array_equal(
81
+ ref_indices,
82
+ indices,
83
+ err_msg="Query vectors have different neighbors' indices",
84
+ )
85
+ assert_allclose(
86
+ ref_dist,
87
+ dist,
88
+ err_msg="Query vectors have different neighbors' distances",
89
+ rtol=rtol,
90
+ )
91
+
92
+
93
+ def relative_rounding(scalar, n_significant_digits):
94
+ """Round a scalar to a number of significant digits relatively to its value."""
95
+ if scalar == 0:
96
+ return 0.0
97
+ magnitude = int(floor(log10(abs(scalar)))) + 1
98
+ return round(scalar, n_significant_digits - magnitude)
99
+
100
+
101
+ def test_relative_rounding():
102
+
103
+ assert relative_rounding(0, 1) == 0.0
104
+ assert relative_rounding(0, 10) == 0.0
105
+ assert relative_rounding(0, 123456) == 0.0
106
+
107
+ assert relative_rounding(123456789, 0) == 0
108
+ assert relative_rounding(123456789, 2) == 120000000
109
+ assert relative_rounding(123456789, 3) == 123000000
110
+ assert relative_rounding(123456789, 10) == 123456789
111
+ assert relative_rounding(123456789, 20) == 123456789
112
+
113
+ assert relative_rounding(1.23456789, 2) == 1.2
114
+ assert relative_rounding(1.23456789, 3) == 1.23
115
+ assert relative_rounding(1.23456789, 10) == 1.23456789
116
+
117
+ assert relative_rounding(123.456789, 3) == 123.0
118
+ assert relative_rounding(123.456789, 9) == 123.456789
119
+ assert relative_rounding(123.456789, 10) == 123.456789
120
+
121
+
122
+ def assert_argkmin_results_quasi_equality(
123
+ ref_dist,
124
+ dist,
125
+ ref_indices,
126
+ indices,
127
+ rtol=1e-4,
128
+ ):
129
+ """Assert that argkmin results are valid up to:
130
+ - relative tolerance on computed distance values
131
+ - permutations of indices for distances values that differ up to
132
+ a precision level
133
+
134
+ To be used for testing neighbors queries on float32 datasets: we
135
+ accept neighbors rank swaps only if they are caused by small
136
+ rounding errors on the distance computations.
137
+ """
138
+ is_sorted = lambda a: np.all(a[:-1] <= a[1:])
139
+
140
+ n_significant_digits = -(int(floor(log10(abs(rtol)))) + 1)
141
+
142
+ assert (
143
+ ref_dist.shape == dist.shape == ref_indices.shape == indices.shape
144
+ ), "Arrays of results have various shapes."
145
+
146
+ n_queries, n_neighbors = ref_dist.shape
147
+
148
+ # Asserting equality results one row at a time
149
+ for query_idx in range(n_queries):
150
+ ref_dist_row = ref_dist[query_idx]
151
+ dist_row = dist[query_idx]
152
+
153
+ assert is_sorted(
154
+ ref_dist_row
155
+ ), f"Reference distances aren't sorted on row {query_idx}"
156
+ assert is_sorted(dist_row), f"Distances aren't sorted on row {query_idx}"
157
+
158
+ assert_allclose(ref_dist_row, dist_row, rtol=rtol)
159
+
160
+ ref_indices_row = ref_indices[query_idx]
161
+ indices_row = indices[query_idx]
162
+
163
+ # Grouping indices by distances using sets on a rounded distances up
164
+ # to a given number of decimals of significant digits derived from rtol.
165
+ reference_neighbors_groups = defaultdict(set)
166
+ effective_neighbors_groups = defaultdict(set)
167
+
168
+ for neighbor_rank in range(n_neighbors):
169
+ rounded_dist = relative_rounding(
170
+ ref_dist_row[neighbor_rank],
171
+ n_significant_digits=n_significant_digits,
172
+ )
173
+ reference_neighbors_groups[rounded_dist].add(ref_indices_row[neighbor_rank])
174
+ effective_neighbors_groups[rounded_dist].add(indices_row[neighbor_rank])
175
+
176
+ # Asserting equality of groups (sets) for each distance
177
+ msg = (
178
+ f"Neighbors indices for query {query_idx} are not matching "
179
+ f"when rounding distances at {n_significant_digits} significant digits "
180
+ f"derived from rtol={rtol:.1e}"
181
+ )
182
+ for rounded_distance in reference_neighbors_groups.keys():
183
+ assert (
184
+ reference_neighbors_groups[rounded_distance]
185
+ == effective_neighbors_groups[rounded_distance]
186
+ ), msg
187
+
188
+
189
+ def assert_radius_neighbors_results_equality(
190
+ ref_dist, dist, ref_indices, indices, radius
191
+ ):
192
+ # We get arrays of arrays and we need to check for individual pairs
193
+ for i in range(ref_dist.shape[0]):
194
+ assert (ref_dist[i] <= radius).all()
195
+ assert_array_equal(
196
+ ref_indices[i],
197
+ indices[i],
198
+ err_msg=f"Query vector #{i} has different neighbors' indices",
199
+ )
200
+ assert_allclose(
201
+ ref_dist[i],
202
+ dist[i],
203
+ err_msg=f"Query vector #{i} has different neighbors' distances",
204
+ rtol=1e-7,
205
+ )
206
+
207
+
208
+ def assert_radius_neighbors_results_quasi_equality(
209
+ ref_dist,
210
+ dist,
211
+ ref_indices,
212
+ indices,
213
+ radius,
214
+ rtol=1e-4,
215
+ ):
216
+ """Assert that radius neighborhood results are valid up to:
217
+ - relative tolerance on computed distance values
218
+ - permutations of indices for distances values that differ up to
219
+ a precision level
220
+ - missing or extra last elements if their distance is
221
+ close to the radius
222
+
223
+ To be used for testing neighbors queries on float32 datasets: we
224
+ accept neighbors rank swaps only if they are caused by small
225
+ rounding errors on the distance computations.
226
+
227
+ Input arrays must be sorted w.r.t distances.
228
+ """
229
+ is_sorted = lambda a: np.all(a[:-1] <= a[1:])
230
+
231
+ n_significant_digits = -(int(floor(log10(abs(rtol)))) + 1)
232
+
233
+ assert (
234
+ len(ref_dist) == len(dist) == len(ref_indices) == len(indices)
235
+ ), "Arrays of results have various lengths."
236
+
237
+ n_queries = len(ref_dist)
238
+
239
+ # Asserting equality of results one vector at a time
240
+ for query_idx in range(n_queries):
241
+
242
+ ref_dist_row = ref_dist[query_idx]
243
+ dist_row = dist[query_idx]
244
+
245
+ assert is_sorted(
246
+ ref_dist_row
247
+ ), f"Reference distances aren't sorted on row {query_idx}"
248
+ assert is_sorted(dist_row), f"Distances aren't sorted on row {query_idx}"
249
+
250
+ # Vectors' lengths might be different due to small
251
+ # numerical differences of distance w.r.t the `radius` threshold.
252
+ largest_row = ref_dist_row if len(ref_dist_row) > len(dist_row) else dist_row
253
+
254
+ # For the longest distances vector, we check that last extra elements
255
+ # that aren't present in the other vector are all in: [radius ± rtol]
256
+ min_length = min(len(ref_dist_row), len(dist_row))
257
+ last_extra_elements = largest_row[min_length:]
258
+ if last_extra_elements.size > 0:
259
+ assert np.all(radius - rtol <= last_extra_elements <= radius + rtol), (
260
+ f"The last extra elements ({last_extra_elements}) aren't in [radius ±"
261
+ f" rtol]=[{radius} ± {rtol}]"
262
+ )
263
+
264
+ # We truncate the neighbors results list on the smallest length to
265
+ # be able to compare them, ignoring the elements checked above.
266
+ ref_dist_row = ref_dist_row[:min_length]
267
+ dist_row = dist_row[:min_length]
268
+
269
+ assert_allclose(ref_dist_row, dist_row, rtol=rtol)
270
+
271
+ ref_indices_row = ref_indices[query_idx]
272
+ indices_row = indices[query_idx]
273
+
274
+ # Grouping indices by distances using sets on a rounded distances up
275
+ # to a given number of significant digits derived from rtol.
276
+ reference_neighbors_groups = defaultdict(set)
277
+ effective_neighbors_groups = defaultdict(set)
278
+
279
+ for neighbor_rank in range(min_length):
280
+ rounded_dist = relative_rounding(
281
+ ref_dist_row[neighbor_rank],
282
+ n_significant_digits=n_significant_digits,
283
+ )
284
+ reference_neighbors_groups[rounded_dist].add(ref_indices_row[neighbor_rank])
285
+ effective_neighbors_groups[rounded_dist].add(indices_row[neighbor_rank])
286
+
287
+ # Asserting equality of groups (sets) for each distance
288
+ msg = (
289
+ f"Neighbors indices for query {query_idx} are not matching "
290
+ f"when rounding distances at {n_significant_digits} significant digits "
291
+ f"derived from rtol={rtol:.1e}"
292
+ )
293
+ for rounded_distance in reference_neighbors_groups.keys():
294
+ assert (
295
+ reference_neighbors_groups[rounded_distance]
296
+ == effective_neighbors_groups[rounded_distance]
297
+ ), msg
298
+
299
+
300
+ ASSERT_RESULT = {
301
+ # In the case of 64bit, we test for exact equality of the results rankings
302
+ # and standard tolerance levels for the computed distance values.
303
+ #
304
+ # XXX: Note that in the future we might be interested in using quasi equality
305
+ # checks also for float64 data (with a larger number of significant digits)
306
+ # as the tests could be unstable because of numerically tied distances on
307
+ # some datasets (e.g. uniform grids).
308
+ (ArgKmin, np.float64): assert_argkmin_results_equality,
309
+ (
310
+ RadiusNeighbors,
311
+ np.float64,
312
+ ): assert_radius_neighbors_results_equality,
313
+ # In the case of 32bit, indices can be permuted due to small difference
314
+ # in the computations of their associated distances, hence we test equality of
315
+ # results up to valid permutations.
316
+ (ArgKmin, np.float32): assert_argkmin_results_quasi_equality,
317
+ (
318
+ RadiusNeighbors,
319
+ np.float32,
320
+ ): assert_radius_neighbors_results_quasi_equality,
321
+ }
322
+
323
+
324
+ def test_assert_argkmin_results_quasi_equality():
325
+
326
+ rtol = 1e-7
327
+ eps = 1e-7
328
+ _1m = 1.0 - eps
329
+ _1p = 1.0 + eps
330
+
331
+ _6_1m = 6.1 - eps
332
+ _6_1p = 6.1 + eps
333
+
334
+ ref_dist = np.array(
335
+ [
336
+ [1.2, 2.5, _6_1m, 6.1, _6_1p],
337
+ [_1m, _1m, 1, _1p, _1p],
338
+ ]
339
+ )
340
+ ref_indices = np.array(
341
+ [
342
+ [1, 2, 3, 4, 5],
343
+ [6, 7, 8, 9, 10],
344
+ ]
345
+ )
346
+
347
+ # Sanity check: compare the reference results to themselves.
348
+ assert_argkmin_results_quasi_equality(
349
+ ref_dist, ref_dist, ref_indices, ref_indices, rtol
350
+ )
351
+
352
+ # Apply valid permutation on indices: the last 3 points are
353
+ # all very close to one another so we accept any permutation
354
+ # on their rankings.
355
+ assert_argkmin_results_quasi_equality(
356
+ np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]),
357
+ np.array([[1.2, 2.5, 6.1, 6.1, 6.1]]),
358
+ np.array([[1, 2, 3, 4, 5]]),
359
+ np.array([[1, 2, 4, 5, 3]]),
360
+ rtol=rtol,
361
+ )
362
+ # All points are have close distances so any ranking permutation
363
+ # is valid for this query result.
364
+ assert_argkmin_results_quasi_equality(
365
+ np.array([[_1m, _1m, 1, _1p, _1p]]),
366
+ np.array([[_1m, _1m, 1, _1p, _1p]]),
367
+ np.array([[6, 7, 8, 9, 10]]),
368
+ np.array([[6, 9, 7, 8, 10]]),
369
+ rtol=rtol,
370
+ )
371
+
372
+ # Apply invalid permutation on indices: permuting the ranks
373
+ # of the 2 nearest neighbors is invalid because the distance
374
+ # values are too different.
375
+ msg = "Neighbors indices for query 0 are not matching"
376
+ with pytest.raises(AssertionError, match=msg):
377
+ assert_argkmin_results_quasi_equality(
378
+ np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]),
379
+ np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]),
380
+ np.array([[1, 2, 3, 4, 5]]),
381
+ np.array([[2, 1, 3, 4, 5]]),
382
+ rtol=rtol,
383
+ )
384
+
385
+ # Indices aren't properly sorted w.r.t their distances
386
+ msg = "Neighbors indices for query 0 are not matching"
387
+ with pytest.raises(AssertionError, match=msg):
388
+ assert_argkmin_results_quasi_equality(
389
+ np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]),
390
+ np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]),
391
+ np.array([[1, 2, 3, 4, 5]]),
392
+ np.array([[2, 1, 4, 5, 3]]),
393
+ rtol=rtol,
394
+ )
395
+
396
+ # Distances aren't properly sorted
397
+ msg = "Distances aren't sorted on row 0"
398
+ with pytest.raises(AssertionError, match=msg):
399
+ assert_argkmin_results_quasi_equality(
400
+ np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]),
401
+ np.array([[2.5, 1.2, _6_1m, 6.1, _6_1p]]),
402
+ np.array([[1, 2, 3, 4, 5]]),
403
+ np.array([[2, 1, 4, 5, 3]]),
404
+ rtol=rtol,
405
+ )
406
+
407
+
408
+ def test_assert_radius_neighbors_results_quasi_equality():
409
+
410
+ rtol = 1e-7
411
+ eps = 1e-7
412
+ _1m = 1.0 - eps
413
+ _1p = 1.0 + eps
414
+
415
+ _6_1m = 6.1 - eps
416
+ _6_1p = 6.1 + eps
417
+
418
+ ref_dist = [
419
+ np.array([1.2, 2.5, _6_1m, 6.1, _6_1p]),
420
+ np.array([_1m, 1, _1p, _1p]),
421
+ ]
422
+
423
+ ref_indices = [
424
+ np.array([1, 2, 3, 4, 5]),
425
+ np.array([6, 7, 8, 9]),
426
+ ]
427
+
428
+ # Sanity check: compare the reference results to themselves.
429
+ assert_radius_neighbors_results_quasi_equality(
430
+ ref_dist,
431
+ ref_dist,
432
+ ref_indices,
433
+ ref_indices,
434
+ radius=6.1,
435
+ rtol=rtol,
436
+ )
437
+
438
+ # Apply valid permutation on indices
439
+ assert_radius_neighbors_results_quasi_equality(
440
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
441
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
442
+ np.array([np.array([1, 2, 3, 4, 5])]),
443
+ np.array([np.array([1, 2, 4, 5, 3])]),
444
+ radius=6.1,
445
+ rtol=rtol,
446
+ )
447
+ assert_radius_neighbors_results_quasi_equality(
448
+ np.array([np.array([_1m, _1m, 1, _1p, _1p])]),
449
+ np.array([np.array([_1m, _1m, 1, _1p, _1p])]),
450
+ np.array([np.array([6, 7, 8, 9, 10])]),
451
+ np.array([np.array([6, 9, 7, 8, 10])]),
452
+ radius=6.1,
453
+ rtol=rtol,
454
+ )
455
+
456
+ # Apply invalid permutation on indices
457
+ msg = "Neighbors indices for query 0 are not matching"
458
+ with pytest.raises(AssertionError, match=msg):
459
+ assert_radius_neighbors_results_quasi_equality(
460
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
461
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
462
+ np.array([np.array([1, 2, 3, 4, 5])]),
463
+ np.array([np.array([2, 1, 3, 4, 5])]),
464
+ radius=6.1,
465
+ rtol=rtol,
466
+ )
467
+
468
+ # Having extra last elements is valid if they are in: [radius ± rtol]
469
+ assert_radius_neighbors_results_quasi_equality(
470
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
471
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1])]),
472
+ np.array([np.array([1, 2, 3, 4, 5])]),
473
+ np.array([np.array([1, 2, 3, 4])]),
474
+ radius=6.1,
475
+ rtol=rtol,
476
+ )
477
+
478
+ # Having extra last elements is invalid if they are lesser than radius - rtol
479
+ msg = re.escape(
480
+ "The last extra elements ([6.]) aren't in [radius ± rtol]=[6.1 ± 1e-07]"
481
+ )
482
+ with pytest.raises(AssertionError, match=msg):
483
+ assert_radius_neighbors_results_quasi_equality(
484
+ np.array([np.array([1.2, 2.5, 6])]),
485
+ np.array([np.array([1.2, 2.5])]),
486
+ np.array([np.array([1, 2, 3])]),
487
+ np.array([np.array([1, 2])]),
488
+ radius=6.1,
489
+ rtol=rtol,
490
+ )
491
+
492
+ # Indices aren't properly sorted w.r.t their distances
493
+ msg = "Neighbors indices for query 0 are not matching"
494
+ with pytest.raises(AssertionError, match=msg):
495
+ assert_radius_neighbors_results_quasi_equality(
496
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
497
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
498
+ np.array([np.array([1, 2, 3, 4, 5])]),
499
+ np.array([np.array([2, 1, 4, 5, 3])]),
500
+ radius=6.1,
501
+ rtol=rtol,
502
+ )
503
+
504
+ # Distances aren't properly sorted
505
+ msg = "Distances aren't sorted on row 0"
506
+ with pytest.raises(AssertionError, match=msg):
507
+ assert_radius_neighbors_results_quasi_equality(
508
+ np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]),
509
+ np.array([np.array([2.5, 1.2, _6_1m, 6.1, _6_1p])]),
510
+ np.array([np.array([1, 2, 3, 4, 5])]),
511
+ np.array([np.array([2, 1, 4, 5, 3])]),
512
+ radius=6.1,
513
+ rtol=rtol,
514
+ )
515
+
516
+
517
+ def test_pairwise_distances_reduction_is_usable_for():
518
+ rng = np.random.RandomState(0)
519
+ X = rng.rand(100, 10)
520
+ Y = rng.rand(100, 10)
521
+ X_csr = csr_matrix(X)
522
+ Y_csr = csr_matrix(Y)
523
+ metric = "manhattan"
524
+
525
+ # Must be usable for all possible pair of {dense, sparse} datasets
526
+ assert BaseDistancesReductionDispatcher.is_usable_for(X, Y, metric)
527
+ assert BaseDistancesReductionDispatcher.is_usable_for(X_csr, Y_csr, metric)
528
+ assert BaseDistancesReductionDispatcher.is_usable_for(X_csr, Y, metric)
529
+ assert BaseDistancesReductionDispatcher.is_usable_for(X, Y_csr, metric)
530
+
531
+ assert BaseDistancesReductionDispatcher.is_usable_for(
532
+ X.astype(np.float64), Y.astype(np.float64), metric
533
+ )
534
+
535
+ assert BaseDistancesReductionDispatcher.is_usable_for(
536
+ X.astype(np.float32), Y.astype(np.float32), metric
537
+ )
538
+
539
+ assert not BaseDistancesReductionDispatcher.is_usable_for(
540
+ X.astype(np.int64), Y.astype(np.int64), metric
541
+ )
542
+
543
+ assert not BaseDistancesReductionDispatcher.is_usable_for(X, Y, metric="pyfunc")
544
+ assert not BaseDistancesReductionDispatcher.is_usable_for(
545
+ X.astype(np.float32), Y, metric
546
+ )
547
+ assert not BaseDistancesReductionDispatcher.is_usable_for(
548
+ X, Y.astype(np.int32), metric
549
+ )
550
+
551
+ # F-ordered arrays are not supported
552
+ assert not BaseDistancesReductionDispatcher.is_usable_for(
553
+ np.asfortranarray(X), Y, metric
554
+ )
555
+
556
+ # We prefer not to use those implementations for fused sparse-dense when
557
+ # metric="(sq)euclidean" because it's not yet the most efficient one on
558
+ # all configurations of datasets.
559
+ # See: https://github.com/scikit-learn/scikit-learn/pull/23585#issuecomment-1247996669 # noqa
560
+ # TODO: implement specialisation for (sq)euclidean on fused sparse-dense
561
+ # using sparse-dense routines for matrix-vector multiplications.
562
+ assert not BaseDistancesReductionDispatcher.is_usable_for(
563
+ X_csr, Y, metric="euclidean"
564
+ )
565
+ assert BaseDistancesReductionDispatcher.is_usable_for(
566
+ X_csr, Y_csr, metric="sqeuclidean"
567
+ )
568
+ assert BaseDistancesReductionDispatcher.is_usable_for(
569
+ X_csr, Y_csr, metric="euclidean"
570
+ )
571
+
572
+ # CSR matrices without non-zeros elements aren't currently supported
573
+ # TODO: support CSR matrices without non-zeros elements
574
+ X_csr_0_nnz = csr_matrix(X * 0)
575
+ assert not BaseDistancesReductionDispatcher.is_usable_for(X_csr_0_nnz, Y, metric)
576
+
577
+ # CSR matrices with int64 indices and indptr (e.g. large nnz, or large n_features)
578
+ # aren't supported as of now.
579
+ # See: https://github.com/scikit-learn/scikit-learn/issues/23653
580
+ # TODO: support CSR matrices with int64 indices and indptr
581
+ X_csr_int64 = csr_matrix(X)
582
+ X_csr_int64.indices = X_csr_int64.indices.astype(np.int64)
583
+ assert not BaseDistancesReductionDispatcher.is_usable_for(X_csr_int64, Y, metric)
584
+
585
+
586
+ def test_argkmin_factory_method_wrong_usages():
587
+ rng = np.random.RandomState(1)
588
+ X = rng.rand(100, 10)
589
+ Y = rng.rand(100, 10)
590
+ k = 5
591
+ metric = "euclidean"
592
+
593
+ msg = (
594
+ "Only float64 or float32 datasets pairs are supported at this time, "
595
+ "got: X.dtype=float32 and Y.dtype=float64"
596
+ )
597
+ with pytest.raises(ValueError, match=msg):
598
+ ArgKmin.compute(X=X.astype(np.float32), Y=Y, k=k, metric=metric)
599
+
600
+ msg = (
601
+ "Only float64 or float32 datasets pairs are supported at this time, "
602
+ "got: X.dtype=float64 and Y.dtype=int32"
603
+ )
604
+ with pytest.raises(ValueError, match=msg):
605
+ ArgKmin.compute(X=X, Y=Y.astype(np.int32), k=k, metric=metric)
606
+
607
+ with pytest.raises(ValueError, match="k == -1, must be >= 1."):
608
+ ArgKmin.compute(X=X, Y=Y, k=-1, metric=metric)
609
+
610
+ with pytest.raises(ValueError, match="k == 0, must be >= 1."):
611
+ ArgKmin.compute(X=X, Y=Y, k=0, metric=metric)
612
+
613
+ with pytest.raises(ValueError, match="Unrecognized metric"):
614
+ ArgKmin.compute(X=X, Y=Y, k=k, metric="wrong metric")
615
+
616
+ with pytest.raises(
617
+ ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)"
618
+ ):
619
+ ArgKmin.compute(X=np.array([1.0, 2.0]), Y=Y, k=k, metric=metric)
620
+
621
+ with pytest.raises(ValueError, match="ndarray is not C-contiguous"):
622
+ ArgKmin.compute(X=np.asfortranarray(X), Y=Y, k=k, metric=metric)
623
+
624
+ # A UserWarning must be raised in this case.
625
+ unused_metric_kwargs = {"p": 3}
626
+
627
+ message = r"Some metric_kwargs have been passed \({'p': 3}\) but"
628
+
629
+ with pytest.warns(UserWarning, match=message):
630
+ ArgKmin.compute(
631
+ X=X, Y=Y, k=k, metric=metric, metric_kwargs=unused_metric_kwargs
632
+ )
633
+
634
+ # A UserWarning must be raised in this case.
635
+ metric_kwargs = {
636
+ "p": 3, # unused
637
+ "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2),
638
+ }
639
+
640
+ message = r"Some metric_kwargs have been passed \({'p': 3, 'Y_norm_squared'"
641
+
642
+ with pytest.warns(UserWarning, match=message):
643
+ ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs)
644
+
645
+ # No user warning must be raised in this case.
646
+ metric_kwargs = {
647
+ "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2),
648
+ }
649
+ with warnings.catch_warnings():
650
+ warnings.simplefilter("error", category=UserWarning)
651
+ ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs)
652
+
653
+ # No user warning must be raised in this case.
654
+ metric_kwargs = {
655
+ "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2),
656
+ "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2),
657
+ }
658
+ with warnings.catch_warnings():
659
+ warnings.simplefilter("error", category=UserWarning)
660
+ ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs)
661
+
662
+
663
+ def test_radius_neighbors_factory_method_wrong_usages():
664
+ rng = np.random.RandomState(1)
665
+ X = rng.rand(100, 10)
666
+ Y = rng.rand(100, 10)
667
+ radius = 5
668
+ metric = "euclidean"
669
+
670
+ msg = (
671
+ "Only float64 or float32 datasets pairs are supported at this time, "
672
+ "got: X.dtype=float32 and Y.dtype=float64"
673
+ )
674
+ with pytest.raises(
675
+ ValueError,
676
+ match=msg,
677
+ ):
678
+ RadiusNeighbors.compute(
679
+ X=X.astype(np.float32), Y=Y, radius=radius, metric=metric
680
+ )
681
+
682
+ msg = (
683
+ "Only float64 or float32 datasets pairs are supported at this time, "
684
+ "got: X.dtype=float64 and Y.dtype=int32"
685
+ )
686
+ with pytest.raises(
687
+ ValueError,
688
+ match=msg,
689
+ ):
690
+ RadiusNeighbors.compute(X=X, Y=Y.astype(np.int32), radius=radius, metric=metric)
691
+
692
+ with pytest.raises(ValueError, match="radius == -1.0, must be >= 0."):
693
+ RadiusNeighbors.compute(X=X, Y=Y, radius=-1, metric=metric)
694
+
695
+ with pytest.raises(ValueError, match="Unrecognized metric"):
696
+ RadiusNeighbors.compute(X=X, Y=Y, radius=radius, metric="wrong metric")
697
+
698
+ with pytest.raises(
699
+ ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)"
700
+ ):
701
+ RadiusNeighbors.compute(
702
+ X=np.array([1.0, 2.0]), Y=Y, radius=radius, metric=metric
703
+ )
704
+
705
+ with pytest.raises(ValueError, match="ndarray is not C-contiguous"):
706
+ RadiusNeighbors.compute(
707
+ X=np.asfortranarray(X), Y=Y, radius=radius, metric=metric
708
+ )
709
+
710
+ unused_metric_kwargs = {"p": 3}
711
+
712
+ # A UserWarning must be raised in this case.
713
+ message = r"Some metric_kwargs have been passed \({'p': 3}\) but"
714
+
715
+ with pytest.warns(UserWarning, match=message):
716
+ RadiusNeighbors.compute(
717
+ X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=unused_metric_kwargs
718
+ )
719
+
720
+ # A UserWarning must be raised in this case.
721
+ metric_kwargs = {
722
+ "p": 3, # unused
723
+ "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2),
724
+ }
725
+
726
+ message = r"Some metric_kwargs have been passed \({'p': 3, 'Y_norm_squared'"
727
+
728
+ with pytest.warns(UserWarning, match=message):
729
+ RadiusNeighbors.compute(
730
+ X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs
731
+ )
732
+
733
+ # No user warning must be raised in this case.
734
+ metric_kwargs = {
735
+ "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2),
736
+ "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2),
737
+ }
738
+ with warnings.catch_warnings():
739
+ warnings.simplefilter("error", category=UserWarning)
740
+ RadiusNeighbors.compute(
741
+ X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs
742
+ )
743
+
744
+ # No user warning must be raised in this case.
745
+ metric_kwargs = {
746
+ "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2),
747
+ }
748
+ with warnings.catch_warnings():
749
+ warnings.simplefilter("error", category=UserWarning)
750
+ RadiusNeighbors.compute(
751
+ X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs
752
+ )
753
+
754
+
755
+ @pytest.mark.parametrize(
756
+ "n_samples_X, n_samples_Y", [(100, 100), (500, 100), (100, 500)]
757
+ )
758
+ @pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors])
759
+ @pytest.mark.parametrize("dtype", [np.float64, np.float32])
760
+ def test_chunk_size_agnosticism(
761
+ global_random_seed,
762
+ Dispatcher,
763
+ n_samples_X,
764
+ n_samples_Y,
765
+ dtype,
766
+ n_features=100,
767
+ ):
768
+ """Check that results do not depend on the chunk size."""
769
+ rng = np.random.RandomState(global_random_seed)
770
+ spread = 100
771
+ X = rng.rand(n_samples_X, n_features).astype(dtype) * spread
772
+ Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread
773
+
774
+ if Dispatcher is ArgKmin:
775
+ parameter = 10
776
+ check_parameters = {}
777
+ compute_parameters = {}
778
+ else:
779
+ # Scaling the radius slightly with the numbers of dimensions
780
+ radius = 10 ** np.log(n_features)
781
+ parameter = radius
782
+ check_parameters = {"radius": radius}
783
+ compute_parameters = {"sort_results": True}
784
+
785
+ ref_dist, ref_indices = Dispatcher.compute(
786
+ X,
787
+ Y,
788
+ parameter,
789
+ chunk_size=256, # default
790
+ metric="manhattan",
791
+ return_distance=True,
792
+ **compute_parameters,
793
+ )
794
+
795
+ dist, indices = Dispatcher.compute(
796
+ X,
797
+ Y,
798
+ parameter,
799
+ chunk_size=41,
800
+ metric="manhattan",
801
+ return_distance=True,
802
+ **compute_parameters,
803
+ )
804
+
805
+ ASSERT_RESULT[(Dispatcher, dtype)](
806
+ ref_dist, dist, ref_indices, indices, **check_parameters
807
+ )
808
+
809
+
810
+ @pytest.mark.parametrize(
811
+ "n_samples_X, n_samples_Y", [(100, 100), (500, 100), (100, 500)]
812
+ )
813
+ @pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors])
814
+ @pytest.mark.parametrize("dtype", [np.float64, np.float32])
815
+ def test_n_threads_agnosticism(
816
+ global_random_seed,
817
+ Dispatcher,
818
+ n_samples_X,
819
+ n_samples_Y,
820
+ dtype,
821
+ n_features=100,
822
+ ):
823
+ """Check that results do not depend on the number of threads."""
824
+ rng = np.random.RandomState(global_random_seed)
825
+ spread = 100
826
+ X = rng.rand(n_samples_X, n_features).astype(dtype) * spread
827
+ Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread
828
+
829
+ if Dispatcher is ArgKmin:
830
+ parameter = 10
831
+ check_parameters = {}
832
+ compute_parameters = {}
833
+ else:
834
+ # Scaling the radius slightly with the numbers of dimensions
835
+ radius = 10 ** np.log(n_features)
836
+ parameter = radius
837
+ check_parameters = {"radius": radius}
838
+ compute_parameters = {"sort_results": True}
839
+
840
+ ref_dist, ref_indices = Dispatcher.compute(
841
+ X,
842
+ Y,
843
+ parameter,
844
+ chunk_size=25, # make sure we use multiple threads
845
+ return_distance=True,
846
+ **compute_parameters,
847
+ )
848
+
849
+ with threadpoolctl.threadpool_limits(limits=1, user_api="openmp"):
850
+ dist, indices = Dispatcher.compute(
851
+ X,
852
+ Y,
853
+ parameter,
854
+ chunk_size=25,
855
+ return_distance=True,
856
+ **compute_parameters,
857
+ )
858
+
859
+ ASSERT_RESULT[(Dispatcher, dtype)](
860
+ ref_dist, dist, ref_indices, indices, **check_parameters
861
+ )
862
+
863
+
864
+ @pytest.mark.parametrize(
865
+ "Dispatcher, dtype",
866
+ [
867
+ (ArgKmin, np.float64),
868
+ (RadiusNeighbors, np.float32),
869
+ (ArgKmin, np.float32),
870
+ (RadiusNeighbors, np.float64),
871
+ ],
872
+ )
873
+ def test_format_agnosticism(
874
+ global_random_seed,
875
+ Dispatcher,
876
+ dtype,
877
+ ):
878
+ """Check that results do not depend on the format (dense, sparse) of the input."""
879
+ rng = np.random.RandomState(global_random_seed)
880
+ spread = 100
881
+ n_samples, n_features = 100, 100
882
+
883
+ X = rng.rand(n_samples, n_features).astype(dtype) * spread
884
+ Y = rng.rand(n_samples, n_features).astype(dtype) * spread
885
+
886
+ X_csr = csr_matrix(X)
887
+ Y_csr = csr_matrix(Y)
888
+
889
+ if Dispatcher is ArgKmin:
890
+ parameter = 10
891
+ check_parameters = {}
892
+ compute_parameters = {}
893
+ else:
894
+ # Scaling the radius slightly with the numbers of dimensions
895
+ radius = 10 ** np.log(n_features)
896
+ parameter = radius
897
+ check_parameters = {"radius": radius}
898
+ compute_parameters = {"sort_results": True}
899
+
900
+ dist_dense, indices_dense = Dispatcher.compute(
901
+ X,
902
+ Y,
903
+ parameter,
904
+ chunk_size=50,
905
+ return_distance=True,
906
+ **compute_parameters,
907
+ )
908
+
909
+ for _X, _Y in itertools.product((X, X_csr), (Y, Y_csr)):
910
+ if _X is X and _Y is Y:
911
+ continue
912
+ dist, indices = Dispatcher.compute(
913
+ _X,
914
+ _Y,
915
+ parameter,
916
+ chunk_size=50,
917
+ return_distance=True,
918
+ **compute_parameters,
919
+ )
920
+ ASSERT_RESULT[(Dispatcher, dtype)](
921
+ dist_dense,
922
+ dist,
923
+ indices_dense,
924
+ indices,
925
+ **check_parameters,
926
+ )
927
+
928
+
929
+ @pytest.mark.parametrize(
930
+ "n_samples_X, n_samples_Y", [(100, 100), (100, 500), (500, 100)]
931
+ )
932
+ @pytest.mark.parametrize(
933
+ "metric",
934
+ ["euclidean", "minkowski", "manhattan", "infinity", "seuclidean", "haversine"],
935
+ )
936
+ @pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors])
937
+ @pytest.mark.parametrize("dtype", [np.float64, np.float32])
938
+ def test_strategies_consistency(
939
+ global_random_seed,
940
+ Dispatcher,
941
+ metric,
942
+ n_samples_X,
943
+ n_samples_Y,
944
+ dtype,
945
+ n_features=10,
946
+ ):
947
+ """Check that the results do not depend on the strategy used."""
948
+ rng = np.random.RandomState(global_random_seed)
949
+ spread = 100
950
+ X = rng.rand(n_samples_X, n_features).astype(dtype) * spread
951
+ Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread
952
+
953
+ # Haversine distance only accepts 2D data
954
+ if metric == "haversine":
955
+ X = np.ascontiguousarray(X[:, :2])
956
+ Y = np.ascontiguousarray(Y[:, :2])
957
+
958
+ if Dispatcher is ArgKmin:
959
+ parameter = 10
960
+ check_parameters = {}
961
+ compute_parameters = {}
962
+ else:
963
+ # Scaling the radius slightly with the numbers of dimensions
964
+ radius = 10 ** np.log(n_features)
965
+ parameter = radius
966
+ check_parameters = {"radius": radius}
967
+ compute_parameters = {"sort_results": True}
968
+
969
+ dist_par_X, indices_par_X = Dispatcher.compute(
970
+ X,
971
+ Y,
972
+ parameter,
973
+ metric=metric,
974
+ # Taking the first
975
+ metric_kwargs=_get_metric_params_list(
976
+ metric, n_features, seed=global_random_seed
977
+ )[0],
978
+ # To be sure to use parallelization
979
+ chunk_size=n_samples_X // 4,
980
+ strategy="parallel_on_X",
981
+ return_distance=True,
982
+ **compute_parameters,
983
+ )
984
+
985
+ dist_par_Y, indices_par_Y = Dispatcher.compute(
986
+ X,
987
+ Y,
988
+ parameter,
989
+ metric=metric,
990
+ # Taking the first
991
+ metric_kwargs=_get_metric_params_list(
992
+ metric, n_features, seed=global_random_seed
993
+ )[0],
994
+ # To be sure to use parallelization
995
+ chunk_size=n_samples_Y // 4,
996
+ strategy="parallel_on_Y",
997
+ return_distance=True,
998
+ **compute_parameters,
999
+ )
1000
+
1001
+ ASSERT_RESULT[(Dispatcher, dtype)](
1002
+ dist_par_X, dist_par_Y, indices_par_X, indices_par_Y, **check_parameters
1003
+ )
1004
+
1005
+
1006
+ # "Concrete Dispatchers"-specific tests
1007
+
1008
+ # TODO: Remove filterwarnings in 1.3 when wminkowski is removed
1009
+ @pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")
1010
+ @pytest.mark.parametrize("n_features", [50, 500])
1011
+ @pytest.mark.parametrize("translation", [0, 1e6])
1012
+ @pytest.mark.parametrize("metric", CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS)
1013
+ @pytest.mark.parametrize("strategy", ("parallel_on_X", "parallel_on_Y"))
1014
+ @pytest.mark.parametrize("dtype", [np.float64, np.float32])
1015
+ def test_pairwise_distances_argkmin(
1016
+ global_random_seed,
1017
+ n_features,
1018
+ translation,
1019
+ metric,
1020
+ strategy,
1021
+ dtype,
1022
+ n_samples=100,
1023
+ k=10,
1024
+ ):
1025
+ # TODO: can we easily fix this discrepancy?
1026
+ edge_cases = [
1027
+ (np.float32, "chebyshev", 1000000.0),
1028
+ (np.float32, "cityblock", 1000000.0),
1029
+ ]
1030
+ if (dtype, metric, translation) in edge_cases:
1031
+ pytest.xfail("Numerical differences lead to small differences in results.")
1032
+
1033
+ rng = np.random.RandomState(global_random_seed)
1034
+ spread = 1000
1035
+ X = translation + rng.rand(n_samples, n_features).astype(dtype) * spread
1036
+ Y = translation + rng.rand(n_samples, n_features).astype(dtype) * spread
1037
+
1038
+ X_csr = csr_matrix(X)
1039
+ Y_csr = csr_matrix(Y)
1040
+
1041
+ # Haversine distance only accepts 2D data
1042
+ if metric == "haversine":
1043
+ X = np.ascontiguousarray(X[:, :2])
1044
+ Y = np.ascontiguousarray(Y[:, :2])
1045
+
1046
+ metric_kwargs = _get_metric_params_list(metric, n_features)[0]
1047
+
1048
+ # Reference for argkmin results
1049
+ if metric == "euclidean":
1050
+ # Compare to scikit-learn GEMM optimized implementation
1051
+ dist_matrix = euclidean_distances(X, Y)
1052
+ else:
1053
+ dist_matrix = cdist(X, Y, metric=metric, **metric_kwargs)
1054
+ # Taking argkmin (indices of the k smallest values)
1055
+ argkmin_indices_ref = np.argsort(dist_matrix, axis=1)[:, :k]
1056
+ # Getting the associated distances
1057
+ argkmin_distances_ref = np.zeros(argkmin_indices_ref.shape, dtype=np.float64)
1058
+ for row_idx in range(argkmin_indices_ref.shape[0]):
1059
+ argkmin_distances_ref[row_idx] = dist_matrix[
1060
+ row_idx, argkmin_indices_ref[row_idx]
1061
+ ]
1062
+
1063
+ for _X, _Y in [(X, Y), (X_csr, Y_csr)]:
1064
+ argkmin_distances, argkmin_indices = ArgKmin.compute(
1065
+ _X,
1066
+ _Y,
1067
+ k,
1068
+ metric=metric,
1069
+ metric_kwargs=metric_kwargs,
1070
+ return_distance=True,
1071
+ # So as to have more than a chunk, forcing parallelism.
1072
+ chunk_size=n_samples // 4,
1073
+ strategy=strategy,
1074
+ )
1075
+
1076
+ ASSERT_RESULT[(ArgKmin, dtype)](
1077
+ argkmin_distances,
1078
+ argkmin_distances_ref,
1079
+ argkmin_indices,
1080
+ argkmin_indices_ref,
1081
+ )
1082
+
1083
+
1084
+ # TODO: Remove filterwarnings in 1.3 when wminkowski is removed
1085
+ @pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn")
1086
+ @pytest.mark.parametrize("n_features", [50, 500])
1087
+ @pytest.mark.parametrize("translation", [0, 1e6])
1088
+ @pytest.mark.parametrize("metric", CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS)
1089
+ @pytest.mark.parametrize("strategy", ("parallel_on_X", "parallel_on_Y"))
1090
+ @pytest.mark.parametrize("dtype", [np.float64, np.float32])
1091
+ def test_pairwise_distances_radius_neighbors(
1092
+ global_random_seed,
1093
+ n_features,
1094
+ translation,
1095
+ metric,
1096
+ strategy,
1097
+ dtype,
1098
+ n_samples=100,
1099
+ ):
1100
+ rng = np.random.RandomState(global_random_seed)
1101
+ spread = 1000
1102
+ radius = spread * np.log(n_features)
1103
+ X = translation + rng.rand(n_samples, n_features).astype(dtype) * spread
1104
+ Y = translation + rng.rand(n_samples, n_features).astype(dtype) * spread
1105
+
1106
+ metric_kwargs = _get_metric_params_list(
1107
+ metric, n_features, seed=global_random_seed
1108
+ )[0]
1109
+
1110
+ # Reference for argkmin results
1111
+ if metric == "euclidean":
1112
+ # Compare to scikit-learn GEMM optimized implementation
1113
+ dist_matrix = euclidean_distances(X, Y)
1114
+ else:
1115
+ dist_matrix = cdist(X, Y, metric=metric, **metric_kwargs)
1116
+
1117
+ # Getting the neighbors for a given radius
1118
+ neigh_indices_ref = []
1119
+ neigh_distances_ref = []
1120
+
1121
+ for row in dist_matrix:
1122
+ ind = np.arange(row.shape[0])[row <= radius]
1123
+ dist = row[ind]
1124
+
1125
+ sort = np.argsort(dist)
1126
+ ind, dist = ind[sort], dist[sort]
1127
+
1128
+ neigh_indices_ref.append(ind)
1129
+ neigh_distances_ref.append(dist)
1130
+
1131
+ neigh_distances, neigh_indices = RadiusNeighbors.compute(
1132
+ X,
1133
+ Y,
1134
+ radius,
1135
+ metric=metric,
1136
+ metric_kwargs=metric_kwargs,
1137
+ return_distance=True,
1138
+ # So as to have more than a chunk, forcing parallelism.
1139
+ chunk_size=n_samples // 4,
1140
+ strategy=strategy,
1141
+ sort_results=True,
1142
+ )
1143
+
1144
+ ASSERT_RESULT[(RadiusNeighbors, dtype)](
1145
+ neigh_distances, neigh_distances_ref, neigh_indices, neigh_indices_ref, radius
1146
+ )
1147
+
1148
+
1149
+ @pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors])
1150
+ @pytest.mark.parametrize("metric", ["manhattan", "euclidean"])
1151
+ @pytest.mark.parametrize("dtype", [np.float64, np.float32])
1152
+ def test_memmap_backed_data(
1153
+ metric,
1154
+ Dispatcher,
1155
+ dtype,
1156
+ ):
1157
+ """Check that the results do not depend on the datasets writability."""
1158
+ rng = np.random.RandomState(0)
1159
+ spread = 100
1160
+ n_samples, n_features = 128, 10
1161
+ X = rng.rand(n_samples, n_features).astype(dtype) * spread
1162
+ Y = rng.rand(n_samples, n_features).astype(dtype) * spread
1163
+
1164
+ # Create read only datasets
1165
+ X_mm, Y_mm = create_memmap_backed_data([X, Y])
1166
+
1167
+ if Dispatcher is ArgKmin:
1168
+ parameter = 10
1169
+ check_parameters = {}
1170
+ compute_parameters = {}
1171
+ else:
1172
+ # Scaling the radius slightly with the numbers of dimensions
1173
+ radius = 10 ** np.log(n_features)
1174
+ parameter = radius
1175
+ check_parameters = {"radius": radius}
1176
+ compute_parameters = {"sort_results": True}
1177
+
1178
+ ref_dist, ref_indices = Dispatcher.compute(
1179
+ X,
1180
+ Y,
1181
+ parameter,
1182
+ metric=metric,
1183
+ return_distance=True,
1184
+ **compute_parameters,
1185
+ )
1186
+
1187
+ dist_mm, indices_mm = Dispatcher.compute(
1188
+ X_mm,
1189
+ Y_mm,
1190
+ parameter,
1191
+ metric=metric,
1192
+ return_distance=True,
1193
+ **compute_parameters,
1194
+ )
1195
+
1196
+ ASSERT_RESULT[(Dispatcher, dtype)](
1197
+ ref_dist, dist_mm, ref_indices, indices_mm, **check_parameters
1198
+ )
1199
+
1200
+
1201
+ @pytest.mark.parametrize("n_samples", [100, 1000])
1202
+ @pytest.mark.parametrize("n_features", [5, 10, 100])
1203
+ @pytest.mark.parametrize("num_threads", [1, 2, 8])
1204
+ @pytest.mark.parametrize("dtype", [np.float64, np.float32])
1205
+ def test_sqeuclidean_row_norms(
1206
+ global_random_seed,
1207
+ n_samples,
1208
+ n_features,
1209
+ num_threads,
1210
+ dtype,
1211
+ ):
1212
+ rng = np.random.RandomState(global_random_seed)
1213
+ spread = 100
1214
+ X = rng.rand(n_samples, n_features).astype(dtype) * spread
1215
+
1216
+ X_csr = csr_matrix(X)
1217
+
1218
+ sq_row_norm_reference = np.linalg.norm(X, axis=1) ** 2
1219
+ sq_row_norm = sqeuclidean_row_norms(X, num_threads=num_threads)
1220
+
1221
+ sq_row_norm_csr = sqeuclidean_row_norms(X_csr, num_threads=num_threads)
1222
+
1223
+ assert_allclose(sq_row_norm_reference, sq_row_norm)
1224
+ assert_allclose(sq_row_norm_reference, sq_row_norm_csr)
1225
+
1226
+ with pytest.raises(ValueError):
1227
+ X = np.asfortranarray(X)
1228
+ sqeuclidean_row_norms(X, num_threads=num_threads)
videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import numpy as np
2
+ from scipy import optimize
3
+ from numpy.testing import assert_allclose
4
+ from scipy.special import factorial, xlogy
5
+ from itertools import product
6
+ import pytest
7
+
8
+ from sklearn.utils._testing import assert_almost_equal
9
+ from sklearn.utils._testing import assert_array_equal
10
+ from sklearn.utils._testing import assert_array_almost_equal
11
+ from sklearn.dummy import DummyRegressor
12
+ from sklearn.model_selection import GridSearchCV
13
+
14
+ from sklearn.metrics import explained_variance_score
15
+ from sklearn.metrics import mean_absolute_error
16
+ from sklearn.metrics import mean_squared_error
17
+ from sklearn.metrics import mean_squared_log_error
18
+ from sklearn.metrics import median_absolute_error
19
+ from sklearn.metrics import mean_absolute_percentage_error
20
+ from sklearn.metrics import max_error
21
+ from sklearn.metrics import mean_pinball_loss
22
+ from sklearn.metrics import r2_score
23
+ from sklearn.metrics import mean_tweedie_deviance
24
+ from sklearn.metrics import d2_tweedie_score
25
+ from sklearn.metrics import d2_pinball_score
26
+ from sklearn.metrics import d2_absolute_error_score
27
+ from sklearn.metrics import make_scorer
28
+
29
+ from sklearn.metrics._regression import _check_reg_targets
30
+
31
+ from sklearn.exceptions import UndefinedMetricWarning
32
+
33
+
34
+ def test_regression_metrics(n_samples=50):
35
+ y_true = np.arange(n_samples)
36
+ y_pred = y_true + 1
37
+ y_pred_2 = y_true - 1
38
+
39
+ assert_almost_equal(mean_squared_error(y_true, y_pred), 1.0)
40
+ assert_almost_equal(
41
+ mean_squared_log_error(y_true, y_pred),
42
+ mean_squared_error(np.log(1 + y_true), np.log(1 + y_pred)),
43
+ )
44
+ assert_almost_equal(mean_absolute_error(y_true, y_pred), 1.0)
45
+ assert_almost_equal(mean_pinball_loss(y_true, y_pred), 0.5)
46
+ assert_almost_equal(mean_pinball_loss(y_true, y_pred_2), 0.5)
47
+ assert_almost_equal(mean_pinball_loss(y_true, y_pred, alpha=0.4), 0.6)
48
+ assert_almost_equal(mean_pinball_loss(y_true, y_pred_2, alpha=0.4), 0.4)
49
+ assert_almost_equal(median_absolute_error(y_true, y_pred), 1.0)
50
+ mape = mean_absolute_percentage_error(y_true, y_pred)
51
+ assert np.isfinite(mape)
52
+ assert mape > 1e6
53
+ assert_almost_equal(max_error(y_true, y_pred), 1.0)
54
+ assert_almost_equal(r2_score(y_true, y_pred), 0.995, 2)
55
+ assert_almost_equal(r2_score(y_true, y_pred, force_finite=False), 0.995, 2)
56
+ assert_almost_equal(explained_variance_score(y_true, y_pred), 1.0)
57
+ assert_almost_equal(
58
+ explained_variance_score(y_true, y_pred, force_finite=False), 1.0
59
+ )
60
+ assert_almost_equal(
61
+ mean_tweedie_deviance(y_true, y_pred, power=0),
62
+ mean_squared_error(y_true, y_pred),
63
+ )
64
+ assert_almost_equal(
65
+ d2_tweedie_score(y_true, y_pred, power=0), r2_score(y_true, y_pred)
66
+ )
67
+ dev_median = np.abs(y_true - np.median(y_true)).sum()
68
+ assert_array_almost_equal(
69
+ d2_absolute_error_score(y_true, y_pred),
70
+ 1 - np.abs(y_true - y_pred).sum() / dev_median,
71
+ )
72
+ alpha = 0.2
73
+ pinball_loss = lambda y_true, y_pred, alpha: alpha * np.maximum(
74
+ y_true - y_pred, 0
75
+ ) + (1 - alpha) * np.maximum(y_pred - y_true, 0)
76
+ y_quantile = np.percentile(y_true, q=alpha * 100)
77
+ assert_almost_equal(
78
+ d2_pinball_score(y_true, y_pred, alpha=alpha),
79
+ 1
80
+ - pinball_loss(y_true, y_pred, alpha).sum()
81
+ / pinball_loss(y_true, y_quantile, alpha).sum(),
82
+ )
83
+ assert_almost_equal(
84
+ d2_absolute_error_score(y_true, y_pred),
85
+ d2_pinball_score(y_true, y_pred, alpha=0.5),
86
+ )
87
+
88
+ # Tweedie deviance needs positive y_pred, except for p=0,
89
+ # p>=2 needs positive y_true
90
+ # results evaluated by sympy
91
+ y_true = np.arange(1, 1 + n_samples)
92
+ y_pred = 2 * y_true
93
+ n = n_samples
94
+ assert_almost_equal(
95
+ mean_tweedie_deviance(y_true, y_pred, power=-1),
96
+ 5 / 12 * n * (n**2 + 2 * n + 1),
97
+ )
98
+ assert_almost_equal(
99
+ mean_tweedie_deviance(y_true, y_pred, power=1), (n + 1) * (1 - np.log(2))
100
+ )
101
+ assert_almost_equal(
102
+ mean_tweedie_deviance(y_true, y_pred, power=2), 2 * np.log(2) - 1
103
+ )
104
+ assert_almost_equal(
105
+ mean_tweedie_deviance(y_true, y_pred, power=3 / 2),
106
+ ((6 * np.sqrt(2) - 8) / n) * np.sqrt(y_true).sum(),
107
+ )
108
+ assert_almost_equal(
109
+ mean_tweedie_deviance(y_true, y_pred, power=3), np.sum(1 / y_true) / (4 * n)
110
+ )
111
+
112
+ dev_mean = 2 * np.mean(xlogy(y_true, 2 * y_true / (n + 1)))
113
+ assert_almost_equal(
114
+ d2_tweedie_score(y_true, y_pred, power=1),
115
+ 1 - (n + 1) * (1 - np.log(2)) / dev_mean,
116
+ )
117
+
118
+ dev_mean = 2 * np.log((n + 1) / 2) - 2 / n * np.log(factorial(n))
119
+ assert_almost_equal(
120
+ d2_tweedie_score(y_true, y_pred, power=2), 1 - (2 * np.log(2) - 1) / dev_mean
121
+ )
122
+
123
+
124
+ def test_mean_squared_error_multioutput_raw_value_squared():
125
+ # non-regression test for
126
+ # https://github.com/scikit-learn/scikit-learn/pull/16323
127
+ mse1 = mean_squared_error([[1]], [[10]], multioutput="raw_values", squared=True)
128
+ mse2 = mean_squared_error([[1]], [[10]], multioutput="raw_values", squared=False)
129
+ assert np.sqrt(mse1) == pytest.approx(mse2)
130
+
131
+
132
+ def test_multioutput_regression():
133
+ y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]])
134
+ y_pred = np.array([[0, 0, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1]])
135
+
136
+ error = mean_squared_error(y_true, y_pred)
137
+ assert_almost_equal(error, (1.0 / 3 + 2.0 / 3 + 2.0 / 3) / 4.0)
138
+
139
+ error = mean_squared_error(y_true, y_pred, squared=False)
140
+ assert_almost_equal(error, 0.454, decimal=2)
141
+
142
+ error = mean_squared_log_error(y_true, y_pred)
143
+ assert_almost_equal(error, 0.200, decimal=2)
144
+
145
+ # mean_absolute_error and mean_squared_error are equal because
146
+ # it is a binary problem.
147
+ error = mean_absolute_error(y_true, y_pred)
148
+ assert_almost_equal(error, (1.0 + 2.0 / 3) / 4.0)
149
+
150
+ error = mean_pinball_loss(y_true, y_pred)
151
+ assert_almost_equal(error, (1.0 + 2.0 / 3) / 8.0)
152
+
153
+ error = np.around(mean_absolute_percentage_error(y_true, y_pred), decimals=2)
154
+ assert np.isfinite(error)
155
+ assert error > 1e6
156
+ error = median_absolute_error(y_true, y_pred)
157
+ assert_almost_equal(error, (1.0 + 1.0) / 4.0)
158
+
159
+ error = r2_score(y_true, y_pred, multioutput="variance_weighted")
160
+ assert_almost_equal(error, 1.0 - 5.0 / 2)
161
+ error = r2_score(y_true, y_pred, multioutput="uniform_average")
162
+ assert_almost_equal(error, -0.875)
163
+
164
+ score = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values")
165
+ raw_expected_score = [
166
+ 1
167
+ - np.abs(y_true[:, i] - y_pred[:, i]).sum()
168
+ / np.abs(y_true[:, i] - np.median(y_true[:, i])).sum()
169
+ for i in range(y_true.shape[1])
170
+ ]
171
+ # in the last case, the denominator vanishes and hence we get nan,
172
+ # but since the numerator vanishes as well the expected score is 1.0
173
+ raw_expected_score = np.where(np.isnan(raw_expected_score), 1, raw_expected_score)
174
+ assert_array_almost_equal(score, raw_expected_score)
175
+
176
+ score = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="uniform_average")
177
+ assert_almost_equal(score, raw_expected_score.mean())
178
+ # constant `y_true` with force_finite=True leads to 1. or 0.
179
+ yc = [5.0, 5.0]
180
+ error = r2_score(yc, [5.0, 5.0], multioutput="variance_weighted")
181
+ assert_almost_equal(error, 1.0)
182
+ error = r2_score(yc, [5.0, 5.1], multioutput="variance_weighted")
183
+ assert_almost_equal(error, 0.0)
184
+
185
+ # Setting force_finite=False results in the nan for 4th output propagating
186
+ error = r2_score(
187
+ y_true, y_pred, multioutput="variance_weighted", force_finite=False
188
+ )
189
+ assert_almost_equal(error, np.nan)
190
+ error = r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False)
191
+ assert_almost_equal(error, np.nan)
192
+
193
+ # Dropping the 4th output to check `force_finite=False` for nominal
194
+ y_true = y_true[:, :-1]
195
+ y_pred = y_pred[:, :-1]
196
+ error = r2_score(y_true, y_pred, multioutput="variance_weighted")
197
+ error2 = r2_score(
198
+ y_true, y_pred, multioutput="variance_weighted", force_finite=False
199
+ )
200
+ assert_almost_equal(error, error2)
201
+ error = r2_score(y_true, y_pred, multioutput="uniform_average")
202
+ error2 = r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False)
203
+ assert_almost_equal(error, error2)
204
+
205
+ # constant `y_true` with force_finite=False leads to NaN or -Inf.
206
+ error = r2_score(
207
+ yc, [5.0, 5.0], multioutput="variance_weighted", force_finite=False
208
+ )
209
+ assert_almost_equal(error, np.nan)
210
+ error = r2_score(
211
+ yc, [5.0, 6.0], multioutput="variance_weighted", force_finite=False
212
+ )
213
+ assert_almost_equal(error, -np.inf)
214
+
215
+
216
+ def test_regression_metrics_at_limits():
217
+ # Single-sample case
218
+ # Note: for r2 and d2_tweedie see also test_regression_single_sample
219
+ assert_almost_equal(mean_squared_error([0.0], [0.0]), 0.0)
220
+ assert_almost_equal(mean_squared_error([0.0], [0.0], squared=False), 0.0)
221
+ assert_almost_equal(mean_squared_log_error([0.0], [0.0]), 0.0)
222
+ assert_almost_equal(mean_absolute_error([0.0], [0.0]), 0.0)
223
+ assert_almost_equal(mean_pinball_loss([0.0], [0.0]), 0.0)
224
+ assert_almost_equal(mean_absolute_percentage_error([0.0], [0.0]), 0.0)
225
+ assert_almost_equal(median_absolute_error([0.0], [0.0]), 0.0)
226
+ assert_almost_equal(max_error([0.0], [0.0]), 0.0)
227
+ assert_almost_equal(explained_variance_score([0.0], [0.0]), 1.0)
228
+
229
+ # Perfect cases
230
+ assert_almost_equal(r2_score([0.0, 1], [0.0, 1]), 1.0)
231
+ assert_almost_equal(d2_pinball_score([0.0, 1], [0.0, 1]), 1.0)
232
+
233
+ # Non-finite cases
234
+ # R² and explained variance have a fix by default for non-finite cases
235
+ for s in (r2_score, explained_variance_score):
236
+ assert_almost_equal(s([0, 0], [1, -1]), 0.0)
237
+ assert_almost_equal(s([0, 0], [1, -1], force_finite=False), -np.inf)
238
+ assert_almost_equal(s([1, 1], [1, 1]), 1.0)
239
+ assert_almost_equal(s([1, 1], [1, 1], force_finite=False), np.nan)
240
+ msg = (
241
+ "Mean Squared Logarithmic Error cannot be used when targets "
242
+ "contain negative values."
243
+ )
244
+ with pytest.raises(ValueError, match=msg):
245
+ mean_squared_log_error([-1.0], [-1.0])
246
+ msg = (
247
+ "Mean Squared Logarithmic Error cannot be used when targets "
248
+ "contain negative values."
249
+ )
250
+ with pytest.raises(ValueError, match=msg):
251
+ mean_squared_log_error([1.0, 2.0, 3.0], [1.0, -2.0, 3.0])
252
+ msg = (
253
+ "Mean Squared Logarithmic Error cannot be used when targets "
254
+ "contain negative values."
255
+ )
256
+ with pytest.raises(ValueError, match=msg):
257
+ mean_squared_log_error([1.0, -2.0, 3.0], [1.0, 2.0, 3.0])
258
+
259
+ # Tweedie deviance error
260
+ power = -1.2
261
+ assert_allclose(
262
+ mean_tweedie_deviance([0], [1.0], power=power), 2 / (2 - power), rtol=1e-3
263
+ )
264
+ msg = "can only be used on strictly positive y_pred."
265
+ with pytest.raises(ValueError, match=msg):
266
+ mean_tweedie_deviance([0.0], [0.0], power=power)
267
+ with pytest.raises(ValueError, match=msg):
268
+ d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power)
269
+
270
+ assert_almost_equal(mean_tweedie_deviance([0.0], [0.0], power=0), 0.0, 2)
271
+
272
+ power = 1.0
273
+ msg = "only be used on non-negative y and strictly positive y_pred."
274
+ with pytest.raises(ValueError, match=msg):
275
+ mean_tweedie_deviance([0.0], [0.0], power=power)
276
+ with pytest.raises(ValueError, match=msg):
277
+ d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power)
278
+
279
+ power = 1.5
280
+ assert_allclose(mean_tweedie_deviance([0.0], [1.0], power=power), 2 / (2 - power))
281
+ msg = "only be used on non-negative y and strictly positive y_pred."
282
+ with pytest.raises(ValueError, match=msg):
283
+ mean_tweedie_deviance([0.0], [0.0], power=power)
284
+ with pytest.raises(ValueError, match=msg):
285
+ d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power)
286
+
287
+ power = 2.0
288
+ assert_allclose(mean_tweedie_deviance([1.0], [1.0], power=power), 0.00, atol=1e-8)
289
+ msg = "can only be used on strictly positive y and y_pred."
290
+ with pytest.raises(ValueError, match=msg):
291
+ mean_tweedie_deviance([0.0], [0.0], power=power)
292
+ with pytest.raises(ValueError, match=msg):
293
+ d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power)
294
+
295
+ power = 3.0
296
+ assert_allclose(mean_tweedie_deviance([1.0], [1.0], power=power), 0.00, atol=1e-8)
297
+ msg = "can only be used on strictly positive y and y_pred."
298
+ with pytest.raises(ValueError, match=msg):
299
+ mean_tweedie_deviance([0.0], [0.0], power=power)
300
+ with pytest.raises(ValueError, match=msg):
301
+ d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power)
302
+
303
+ power = 0.5
304
+ with pytest.raises(ValueError, match="is only defined for power<=0 and power>=1"):
305
+ mean_tweedie_deviance([0.0], [0.0], power=power)
306
+ with pytest.raises(ValueError, match="is only defined for power<=0 and power>=1"):
307
+ d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power)
308
+
309
+
310
+ def test__check_reg_targets():
311
+ # All of length 3
312
+ EXAMPLES = [
313
+ ("continuous", [1, 2, 3], 1),
314
+ ("continuous", [[1], [2], [3]], 1),
315
+ ("continuous-multioutput", [[1, 1], [2, 2], [3, 1]], 2),
316
+ ("continuous-multioutput", [[5, 1], [4, 2], [3, 1]], 2),
317
+ ("continuous-multioutput", [[1, 3, 4], [2, 2, 2], [3, 1, 1]], 3),
318
+ ]
319
+
320
+ for (type1, y1, n_out1), (type2, y2, n_out2) in product(EXAMPLES, repeat=2):
321
+
322
+ if type1 == type2 and n_out1 == n_out2:
323
+ y_type, y_check1, y_check2, multioutput = _check_reg_targets(y1, y2, None)
324
+ assert type1 == y_type
325
+ if type1 == "continuous":
326
+ assert_array_equal(y_check1, np.reshape(y1, (-1, 1)))
327
+ assert_array_equal(y_check2, np.reshape(y2, (-1, 1)))
328
+ else:
329
+ assert_array_equal(y_check1, y1)
330
+ assert_array_equal(y_check2, y2)
331
+ else:
332
+ with pytest.raises(ValueError):
333
+ _check_reg_targets(y1, y2, None)
334
+
335
+
336
+ def test__check_reg_targets_exception():
337
+ invalid_multioutput = "this_value_is_not_valid"
338
+ expected_message = (
339
+ "Allowed 'multioutput' string values are.+You provided multioutput={!r}".format(
340
+ invalid_multioutput
341
+ )
342
+ )
343
+ with pytest.raises(ValueError, match=expected_message):
344
+ _check_reg_targets([1, 2, 3], [[1], [2], [3]], invalid_multioutput)
345
+
346
+
347
+ def test_regression_multioutput_array():
348
+ y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]]
349
+ y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]]
350
+
351
+ mse = mean_squared_error(y_true, y_pred, multioutput="raw_values")
352
+ mae = mean_absolute_error(y_true, y_pred, multioutput="raw_values")
353
+ err_msg = (
354
+ "multioutput is expected to be 'raw_values' "
355
+ "or 'uniform_average' but we got 'variance_weighted' instead."
356
+ )
357
+ with pytest.raises(ValueError, match=err_msg):
358
+ mean_pinball_loss(y_true, y_pred, multioutput="variance_weighted")
359
+
360
+ with pytest.raises(ValueError, match=err_msg):
361
+ d2_pinball_score(y_true, y_pred, multioutput="variance_weighted")
362
+
363
+ pbl = mean_pinball_loss(y_true, y_pred, multioutput="raw_values")
364
+ mape = mean_absolute_percentage_error(y_true, y_pred, multioutput="raw_values")
365
+ r = r2_score(y_true, y_pred, multioutput="raw_values")
366
+ evs = explained_variance_score(y_true, y_pred, multioutput="raw_values")
367
+ d2ps = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values")
368
+ evs2 = explained_variance_score(
369
+ y_true, y_pred, multioutput="raw_values", force_finite=False
370
+ )
371
+
372
+ assert_array_almost_equal(mse, [0.125, 0.5625], decimal=2)
373
+ assert_array_almost_equal(mae, [0.25, 0.625], decimal=2)
374
+ assert_array_almost_equal(pbl, [0.25 / 2, 0.625 / 2], decimal=2)
375
+ assert_array_almost_equal(mape, [0.0778, 0.2262], decimal=2)
376
+ assert_array_almost_equal(r, [0.95, 0.93], decimal=2)
377
+ assert_array_almost_equal(evs, [0.95, 0.93], decimal=2)
378
+ assert_array_almost_equal(d2ps, [0.833, 0.722], decimal=2)
379
+ assert_array_almost_equal(evs2, [0.95, 0.93], decimal=2)
380
+
381
+ # mean_absolute_error and mean_squared_error are equal because
382
+ # it is a binary problem.
383
+ y_true = [[0, 0]] * 4
384
+ y_pred = [[1, 1]] * 4
385
+ mse = mean_squared_error(y_true, y_pred, multioutput="raw_values")
386
+ mae = mean_absolute_error(y_true, y_pred, multioutput="raw_values")
387
+ pbl = mean_pinball_loss(y_true, y_pred, multioutput="raw_values")
388
+ r = r2_score(y_true, y_pred, multioutput="raw_values")
389
+ d2ps = d2_pinball_score(y_true, y_pred, multioutput="raw_values")
390
+ assert_array_almost_equal(mse, [1.0, 1.0], decimal=2)
391
+ assert_array_almost_equal(mae, [1.0, 1.0], decimal=2)
392
+ assert_array_almost_equal(pbl, [0.5, 0.5], decimal=2)
393
+ assert_array_almost_equal(r, [0.0, 0.0], decimal=2)
394
+ assert_array_almost_equal(d2ps, [0.0, 0.0], decimal=2)
395
+
396
+ r = r2_score([[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="raw_values")
397
+ assert_array_almost_equal(r, [0, -3.5], decimal=2)
398
+ assert np.mean(r) == r2_score(
399
+ [[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="uniform_average"
400
+ )
401
+ evs = explained_variance_score(
402
+ [[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="raw_values"
403
+ )
404
+ assert_array_almost_equal(evs, [0, -1.25], decimal=2)
405
+ evs2 = explained_variance_score(
406
+ [[0, -1], [0, 1]],
407
+ [[2, 2], [1, 1]],
408
+ multioutput="raw_values",
409
+ force_finite=False,
410
+ )
411
+ assert_array_almost_equal(evs2, [-np.inf, -1.25], decimal=2)
412
+
413
+ # Checking for the condition in which both numerator and denominator is
414
+ # zero.
415
+ y_true = [[1, 3], [1, 2]]
416
+ y_pred = [[1, 4], [1, 1]]
417
+ r2 = r2_score(y_true, y_pred, multioutput="raw_values")
418
+ assert_array_almost_equal(r2, [1.0, -3.0], decimal=2)
419
+ assert np.mean(r2) == r2_score(y_true, y_pred, multioutput="uniform_average")
420
+ r22 = r2_score(y_true, y_pred, multioutput="raw_values", force_finite=False)
421
+ assert_array_almost_equal(r22, [np.nan, -3.0], decimal=2)
422
+ assert_almost_equal(
423
+ np.mean(r22),
424
+ r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False),
425
+ )
426
+
427
+ evs = explained_variance_score(y_true, y_pred, multioutput="raw_values")
428
+ assert_array_almost_equal(evs, [1.0, -3.0], decimal=2)
429
+ assert np.mean(evs) == explained_variance_score(y_true, y_pred)
430
+ d2ps = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values")
431
+ assert_array_almost_equal(d2ps, [1.0, -1.0], decimal=2)
432
+ evs2 = explained_variance_score(
433
+ y_true, y_pred, multioutput="raw_values", force_finite=False
434
+ )
435
+ assert_array_almost_equal(evs2, [np.nan, -3.0], decimal=2)
436
+ assert_almost_equal(
437
+ np.mean(evs2), explained_variance_score(y_true, y_pred, force_finite=False)
438
+ )
439
+
440
+ # Handling msle separately as it does not accept negative inputs.
441
+ y_true = np.array([[0.5, 1], [1, 2], [7, 6]])
442
+ y_pred = np.array([[0.5, 2], [1, 2.5], [8, 8]])
443
+ msle = mean_squared_log_error(y_true, y_pred, multioutput="raw_values")
444
+ msle2 = mean_squared_error(
445
+ np.log(1 + y_true), np.log(1 + y_pred), multioutput="raw_values"
446
+ )
447
+ assert_array_almost_equal(msle, msle2, decimal=2)
448
+
449
+
450
+ def test_regression_custom_weights():
451
+ y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]]
452
+ y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]]
453
+
454
+ msew = mean_squared_error(y_true, y_pred, multioutput=[0.4, 0.6])
455
+ rmsew = mean_squared_error(y_true, y_pred, multioutput=[0.4, 0.6], squared=False)
456
+ maew = mean_absolute_error(y_true, y_pred, multioutput=[0.4, 0.6])
457
+ mapew = mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.4, 0.6])
458
+ rw = r2_score(y_true, y_pred, multioutput=[0.4, 0.6])
459
+ evsw = explained_variance_score(y_true, y_pred, multioutput=[0.4, 0.6])
460
+ d2psw = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput=[0.4, 0.6])
461
+ evsw2 = explained_variance_score(
462
+ y_true, y_pred, multioutput=[0.4, 0.6], force_finite=False
463
+ )
464
+
465
+ assert_almost_equal(msew, 0.39, decimal=2)
466
+ assert_almost_equal(rmsew, 0.59, decimal=2)
467
+ assert_almost_equal(maew, 0.475, decimal=3)
468
+ assert_almost_equal(mapew, 0.1668, decimal=2)
469
+ assert_almost_equal(rw, 0.94, decimal=2)
470
+ assert_almost_equal(evsw, 0.94, decimal=2)
471
+ assert_almost_equal(d2psw, 0.766, decimal=2)
472
+ assert_almost_equal(evsw2, 0.94, decimal=2)
473
+
474
+ # Handling msle separately as it does not accept negative inputs.
475
+ y_true = np.array([[0.5, 1], [1, 2], [7, 6]])
476
+ y_pred = np.array([[0.5, 2], [1, 2.5], [8, 8]])
477
+ msle = mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7])
478
+ msle2 = mean_squared_error(
479
+ np.log(1 + y_true), np.log(1 + y_pred), multioutput=[0.3, 0.7]
480
+ )
481
+ assert_almost_equal(msle, msle2, decimal=2)
482
+
483
+
484
+ @pytest.mark.parametrize("metric", [r2_score, d2_tweedie_score, d2_pinball_score])
485
+ def test_regression_single_sample(metric):
486
+ y_true = [0]
487
+ y_pred = [1]
488
+ warning_msg = "not well-defined with less than two samples."
489
+
490
+ # Trigger the warning
491
+ with pytest.warns(UndefinedMetricWarning, match=warning_msg):
492
+ score = metric(y_true, y_pred)
493
+ assert np.isnan(score)
494
+
495
+
496
+ def test_tweedie_deviance_continuity():
497
+ n_samples = 100
498
+
499
+ y_true = np.random.RandomState(0).rand(n_samples) + 0.1
500
+ y_pred = np.random.RandomState(1).rand(n_samples) + 0.1
501
+
502
+ assert_allclose(
503
+ mean_tweedie_deviance(y_true, y_pred, power=0 - 1e-10),
504
+ mean_tweedie_deviance(y_true, y_pred, power=0),
505
+ )
506
+
507
+ # Ws we get closer to the limit, with 1e-12 difference the absolute
508
+ # tolerance to pass the below check increases. There are likely
509
+ # numerical precision issues on the edges of different definition
510
+ # regions.
511
+ assert_allclose(
512
+ mean_tweedie_deviance(y_true, y_pred, power=1 + 1e-10),
513
+ mean_tweedie_deviance(y_true, y_pred, power=1),
514
+ atol=1e-6,
515
+ )
516
+
517
+ assert_allclose(
518
+ mean_tweedie_deviance(y_true, y_pred, power=2 - 1e-10),
519
+ mean_tweedie_deviance(y_true, y_pred, power=2),
520
+ atol=1e-6,
521
+ )
522
+
523
+ assert_allclose(
524
+ mean_tweedie_deviance(y_true, y_pred, power=2 + 1e-10),
525
+ mean_tweedie_deviance(y_true, y_pred, power=2),
526
+ atol=1e-6,
527
+ )
528
+
529
+
530
+ def test_mean_absolute_percentage_error():
531
+ random_number_generator = np.random.RandomState(42)
532
+ y_true = random_number_generator.exponential(size=100)
533
+ y_pred = 1.2 * y_true
534
+ assert mean_absolute_percentage_error(y_true, y_pred) == pytest.approx(0.2)
535
+
536
+
537
+ @pytest.mark.parametrize(
538
+ "distribution", ["normal", "lognormal", "exponential", "uniform"]
539
+ )
540
+ @pytest.mark.parametrize("target_quantile", [0.05, 0.5, 0.75])
541
+ def test_mean_pinball_loss_on_constant_predictions(distribution, target_quantile):
542
+ if not hasattr(np, "quantile"):
543
+ pytest.skip(
544
+ "This test requires a more recent version of numpy "
545
+ "with support for np.quantile."
546
+ )
547
+
548
+ # Check that the pinball loss is minimized by the empirical quantile.
549
+ n_samples = 3000
550
+ rng = np.random.RandomState(42)
551
+ data = getattr(rng, distribution)(size=n_samples)
552
+
553
+ # Compute the best possible pinball loss for any constant predictor:
554
+ best_pred = np.quantile(data, target_quantile)
555
+ best_constant_pred = np.full(n_samples, fill_value=best_pred)
556
+ best_pbl = mean_pinball_loss(data, best_constant_pred, alpha=target_quantile)
557
+
558
+ # Evaluate the loss on a grid of quantiles
559
+ candidate_predictions = np.quantile(data, np.linspace(0, 1, 100))
560
+ for pred in candidate_predictions:
561
+ # Compute the pinball loss of a constant predictor:
562
+ constant_pred = np.full(n_samples, fill_value=pred)
563
+ pbl = mean_pinball_loss(data, constant_pred, alpha=target_quantile)
564
+
565
+ # Check that the loss of this constant predictor is greater or equal
566
+ # than the loss of using the optimal quantile (up to machine
567
+ # precision):
568
+ assert pbl >= best_pbl - np.finfo(best_pbl.dtype).eps
569
+
570
+ # Check that the value of the pinball loss matches the analytical
571
+ # formula.
572
+ expected_pbl = (pred - data[data < pred]).sum() * (1 - target_quantile) + (
573
+ data[data >= pred] - pred
574
+ ).sum() * target_quantile
575
+ expected_pbl /= n_samples
576
+ assert_almost_equal(expected_pbl, pbl)
577
+
578
+ # Check that we can actually recover the target_quantile by minimizing the
579
+ # pinball loss w.r.t. the constant prediction quantile.
580
+ def objective_func(x):
581
+ constant_pred = np.full(n_samples, fill_value=x)
582
+ return mean_pinball_loss(data, constant_pred, alpha=target_quantile)
583
+
584
+ result = optimize.minimize(objective_func, data.mean(), method="Nelder-Mead")
585
+ assert result.success
586
+ # The minimum is not unique with limited data, hence the large tolerance.
587
+ assert result.x == pytest.approx(best_pred, rel=1e-2)
588
+ assert result.fun == pytest.approx(best_pbl)
589
+
590
+
591
+ def test_dummy_quantile_parameter_tuning():
592
+ # Integration test to check that it is possible to use the pinball loss to
593
+ # tune the hyperparameter of a quantile regressor. This is conceptually
594
+ # similar to the previous test but using the scikit-learn estimator and
595
+ # scoring API instead.
596
+ n_samples = 1000
597
+ rng = np.random.RandomState(0)
598
+ X = rng.normal(size=(n_samples, 5)) # Ignored
599
+ y = rng.exponential(size=n_samples)
600
+
601
+ all_quantiles = [0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95]
602
+ for alpha in all_quantiles:
603
+ neg_mean_pinball_loss = make_scorer(
604
+ mean_pinball_loss,
605
+ alpha=alpha,
606
+ greater_is_better=False,
607
+ )
608
+ regressor = DummyRegressor(strategy="quantile", quantile=0.25)
609
+ grid_search = GridSearchCV(
610
+ regressor,
611
+ param_grid=dict(quantile=all_quantiles),
612
+ scoring=neg_mean_pinball_loss,
613
+ ).fit(X, y)
614
+
615
+ assert grid_search.best_params_["quantile"] == pytest.approx(alpha)
616
+
617
+
618
+ def test_pinball_loss_relation_with_mae():
619
+ # Test that mean_pinball loss with alpha=0.5 if half of mean absolute error
620
+ rng = np.random.RandomState(714)
621
+ n = 100
622
+ y_true = rng.normal(size=n)
623
+ y_pred = y_true.copy() + rng.uniform(n)
624
+ assert (
625
+ mean_absolute_error(y_true, y_pred)
626
+ == mean_pinball_loss(y_true, y_pred, alpha=0.5) * 2
627
+ )
videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:9b4f5d29a391236bb3470e30682bbaea3a86583d5d55b51018bfe38a83cd1053
3
+ size 271113
videollama2/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:aa1d4bc2bc7ae83be68a224ee6288687da6dd64e1b58b3873f8d3db5486cd730
3
+ size 204313
vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+ // @generated by torchgen/gen.py from DispatchKeyFunction.h
3
+
4
+ // NB: The implementing C++ file is RegisterDispatchKey.cpp
5
+
6
+ // The only #includes we need are for custom classes that have defaults in the C++ API
7
+ #include <c10/core/MemoryFormat.h>
8
+ #include <c10/core/Scalar.h>
9
+ #include <ATen/core/Reduction.h>
10
+
11
+ // Forward declarations of any types needed in the operator signatures.
12
+ // We can't directly include these classes because it will cause circular include dependencies.
13
+ // This file is included by TensorBody.h, which defines the Tensor class.
14
+ #include <ATen/core/ATen_fwd.h>
15
+
16
+ namespace at {
17
+
18
+ namespace compositeexplicitautogradnonfunctional {
19
+
20
+ TORCH_API at::Tensor _indices_copy(const at::Tensor & self);
21
+
22
+ } // namespace compositeexplicitautogradnonfunctional
23
+ } // namespace at