diff --git a/.gitattributes b/.gitattributes index 9d332d422ce5a31637be86a75acc0bcd53911894..bcf3e055155d4f42efb29a7d3f7021eeac51873e 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1931,3 +1931,10 @@ videollama2/lib/python3.10/site-packages/sklearn/linear_model/_sag_fast.cpython- videollama2/lib/python3.10/site-packages/sklearn/utils/_isfinite.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text videollama2/lib/python3.10/site-packages/sklearn/utils/_vector_sentinel.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text videollama2/lib/python3.10/site-packages/sklearn/tree/_utils.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +videollama2/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +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 +videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +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 +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 +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 +videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ae331a6bc2ae23e83df530cbbff7d1b353699465 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_agg_filter.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00bbf4e02ff71f53f7ea6b894009af1f908f899e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_pgf.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bf08aeb43b38edc1f86b739e4ae35537d2af1704 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backend_tools.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..64fb2eb9b0606dba358041b741c774709bdd9140 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_backends_interactive.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d784aaacd668149c6bd26bf9ed7dab9ce808fc8c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_colorbar.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0f758211e2ac87ea43cf1839032ee98733f8362c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_figure.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1354fab632a50dbdca00a5709115a6b24a277fd0 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_gridspec.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..771b8dcbbdcaf2443310257b0a42faeec31ea90c Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_matplotlib.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1635ff92669ffd977824f924ebcd688b2a98cf51 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_patheffects.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0517c591b86e8dd8e94f61c6e37c19e4ab9dae99 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_preprocess_data.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ea8c1ba74645fe45f4bd97fe6e4e1d9ff83da5e Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_skew.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..860c562ec2caaad0f8e72033767206c6cfa4b6a2 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/matplotlib/tests/__pycache__/test_style.cpython-310.pyc differ diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_agg_filter.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_agg_filter.py new file mode 100644 index 0000000000000000000000000000000000000000..dc8cff6858ae52a85028b4f8b3266b4d1880f687 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_agg_filter.py @@ -0,0 +1,33 @@ +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import image_comparison + + +@image_comparison(baseline_images=['agg_filter_alpha'], + extensions=['png', 'pdf']) +def test_agg_filter_alpha(): + # Remove this line when this test image is regenerated. + plt.rcParams['pcolormesh.snap'] = False + + ax = plt.axes() + x, y = np.mgrid[0:7, 0:8] + data = x**2 - y**2 + mesh = ax.pcolormesh(data, cmap='Reds', zorder=5) + + def manual_alpha(im, dpi): + im[:, :, 3] *= 0.6 + print('CALLED') + return im, 0, 0 + + # Note: Doing alpha like this is not the same as setting alpha on + # the mesh itself. Currently meshes are drawn as independent patches, + # and we see fine borders around the blocks of color. See the SO + # question for an example: https://stackoverflow.com/q/20678817/ + mesh.set_agg_filter(manual_alpha) + + # Currently we must enable rasterization for this to have an effect in + # the PDF backend. + mesh.set_rasterized(True) + + ax.plot([0, 4, 7], [1, 3, 8]) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_api.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_api.py new file mode 100644 index 0000000000000000000000000000000000000000..8b0f1e70114ee7e0dd74aafe8324df6b14bdef5e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_api.py @@ -0,0 +1,116 @@ +from __future__ import annotations + +import re +import typing +from typing import Any, Callable, TypeVar + +import numpy as np +import pytest + +import matplotlib as mpl +from matplotlib import _api + + +if typing.TYPE_CHECKING: + from typing_extensions import Self + +T = TypeVar('T') + + +@pytest.mark.parametrize('target,shape_repr,test_shape', + [((None, ), "(N,)", (1, 3)), + ((None, 3), "(N, 3)", (1,)), + ((None, 3), "(N, 3)", (1, 2)), + ((1, 5), "(1, 5)", (1, 9)), + ((None, 2, None), "(M, 2, N)", (1, 3, 1)) + ]) +def test_check_shape(target: tuple[int | None, ...], + shape_repr: str, + test_shape: tuple[int, ...]) -> None: + error_pattern = "^" + re.escape( + f"'aardvark' must be {len(target)}D with shape {shape_repr}, but your input " + f"has shape {test_shape}") + data = np.zeros(test_shape) + with pytest.raises(ValueError, match=error_pattern): + _api.check_shape(target, aardvark=data) + + +def test_classproperty_deprecation() -> None: + class A: + @_api.deprecated("0.0.0") + @_api.classproperty + def f(cls: Self) -> None: + pass + with pytest.warns(mpl.MatplotlibDeprecationWarning): + A.f + with pytest.warns(mpl.MatplotlibDeprecationWarning): + a = A() + a.f + + +def test_deprecate_privatize_attribute() -> None: + class C: + def __init__(self) -> None: self._attr = 1 + def _meth(self, arg: T) -> T: return arg + attr: int = _api.deprecate_privatize_attribute("0.0") + meth: Callable = _api.deprecate_privatize_attribute("0.0") + + c = C() + with pytest.warns(mpl.MatplotlibDeprecationWarning): + assert c.attr == 1 + with pytest.warns(mpl.MatplotlibDeprecationWarning): + c.attr = 2 + with pytest.warns(mpl.MatplotlibDeprecationWarning): + assert c.attr == 2 + with pytest.warns(mpl.MatplotlibDeprecationWarning): + assert c.meth(42) == 42 + + +def test_delete_parameter() -> None: + @_api.delete_parameter("3.0", "foo") + def func1(foo: Any = None) -> None: + pass + + @_api.delete_parameter("3.0", "foo") + def func2(**kwargs: Any) -> None: + pass + + for func in [func1, func2]: # type: ignore[list-item] + func() # No warning. + with pytest.warns(mpl.MatplotlibDeprecationWarning): + func(foo="bar") + + def pyplot_wrapper(foo: Any = _api.deprecation._deprecated_parameter) -> None: + func1(foo) + + pyplot_wrapper() # No warning. + with pytest.warns(mpl.MatplotlibDeprecationWarning): + func(foo="bar") + + +def test_make_keyword_only() -> None: + @_api.make_keyword_only("3.0", "arg") + def func(pre: Any, arg: Any, post: Any = None) -> None: + pass + + func(1, arg=2) # Check that no warning is emitted. + + with pytest.warns(mpl.MatplotlibDeprecationWarning): + func(1, 2) + with pytest.warns(mpl.MatplotlibDeprecationWarning): + func(1, 2, 3) + + +def test_deprecation_alternative() -> None: + alternative = "`.f1`, `f2`, `f3(x) <.f3>` or `f4(x)`" + @_api.deprecated("1", alternative=alternative) + def f() -> None: + pass + if f.__doc__ is None: + pytest.skip('Documentation is disabled') + assert alternative in f.__doc__ + + +def test_empty_check_in_list() -> None: + with pytest.raises(TypeError, match="No argument to check!"): + _api.check_in_list(["a"]) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_artist.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_artist.py new file mode 100644 index 0000000000000000000000000000000000000000..dbb5dd2305e03fd3972daf72fde6d02719f3bcfe --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_artist.py @@ -0,0 +1,564 @@ +import io +from itertools import chain + +import numpy as np + +import pytest + +import matplotlib.colors as mcolors +import matplotlib.pyplot as plt +import matplotlib.patches as mpatches +import matplotlib.lines as mlines +import matplotlib.path as mpath +import matplotlib.transforms as mtransforms +import matplotlib.collections as mcollections +import matplotlib.artist as martist +import matplotlib.backend_bases as mbackend_bases +import matplotlib as mpl +from matplotlib.testing.decorators import check_figures_equal, image_comparison + + +def test_patch_transform_of_none(): + # tests the behaviour of patches added to an Axes with various transform + # specifications + + ax = plt.axes() + ax.set_xlim(1, 3) + ax.set_ylim(1, 3) + + # Draw an ellipse over data coord (2, 2) by specifying device coords. + xy_data = (2, 2) + xy_pix = ax.transData.transform(xy_data) + + # Not providing a transform of None puts the ellipse in data coordinates . + e = mpatches.Ellipse(xy_data, width=1, height=1, fc='yellow', alpha=0.5) + ax.add_patch(e) + assert e._transform == ax.transData + + # Providing a transform of None puts the ellipse in device coordinates. + e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral', + transform=None, alpha=0.5) + assert e.is_transform_set() + ax.add_patch(e) + assert isinstance(e._transform, mtransforms.IdentityTransform) + + # Providing an IdentityTransform puts the ellipse in device coordinates. + e = mpatches.Ellipse(xy_pix, width=100, height=100, + transform=mtransforms.IdentityTransform(), alpha=0.5) + ax.add_patch(e) + assert isinstance(e._transform, mtransforms.IdentityTransform) + + # Not providing a transform, and then subsequently "get_transform" should + # not mean that "is_transform_set". + e = mpatches.Ellipse(xy_pix, width=120, height=120, fc='coral', + alpha=0.5) + intermediate_transform = e.get_transform() + assert not e.is_transform_set() + ax.add_patch(e) + assert e.get_transform() != intermediate_transform + assert e.is_transform_set() + assert e._transform == ax.transData + + +def test_collection_transform_of_none(): + # tests the behaviour of collections added to an Axes with various + # transform specifications + + ax = plt.axes() + ax.set_xlim(1, 3) + ax.set_ylim(1, 3) + + # draw an ellipse over data coord (2, 2) by specifying device coords + xy_data = (2, 2) + xy_pix = ax.transData.transform(xy_data) + + # not providing a transform of None puts the ellipse in data coordinates + e = mpatches.Ellipse(xy_data, width=1, height=1) + c = mcollections.PatchCollection([e], facecolor='yellow', alpha=0.5) + ax.add_collection(c) + # the collection should be in data coordinates + assert c.get_offset_transform() + c.get_transform() == ax.transData + + # providing a transform of None puts the ellipse in device coordinates + e = mpatches.Ellipse(xy_pix, width=120, height=120) + c = mcollections.PatchCollection([e], facecolor='coral', + alpha=0.5) + c.set_transform(None) + ax.add_collection(c) + assert isinstance(c.get_transform(), mtransforms.IdentityTransform) + + # providing an IdentityTransform puts the ellipse in device coordinates + e = mpatches.Ellipse(xy_pix, width=100, height=100) + c = mcollections.PatchCollection([e], + transform=mtransforms.IdentityTransform(), + alpha=0.5) + ax.add_collection(c) + assert isinstance(c.get_offset_transform(), mtransforms.IdentityTransform) + + +@image_comparison(["clip_path_clipping"], remove_text=True) +def test_clipping(): + exterior = mpath.Path.unit_rectangle().deepcopy() + exterior.vertices *= 4 + exterior.vertices -= 2 + interior = mpath.Path.unit_circle().deepcopy() + interior.vertices = interior.vertices[::-1] + clip_path = mpath.Path.make_compound_path(exterior, interior) + + star = mpath.Path.unit_regular_star(6).deepcopy() + star.vertices *= 2.6 + + fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) + + col = mcollections.PathCollection([star], lw=5, edgecolor='blue', + facecolor='red', alpha=0.7, hatch='*') + col.set_clip_path(clip_path, ax1.transData) + ax1.add_collection(col) + + patch = mpatches.PathPatch(star, lw=5, edgecolor='blue', facecolor='red', + alpha=0.7, hatch='*') + patch.set_clip_path(clip_path, ax2.transData) + ax2.add_patch(patch) + + ax1.set_xlim([-3, 3]) + ax1.set_ylim([-3, 3]) + + +@check_figures_equal(extensions=['png']) +def test_clipping_zoom(fig_test, fig_ref): + # This test places the Axes and sets its limits such that the clip path is + # outside the figure entirely. This should not break the clip path. + ax_test = fig_test.add_axes([0, 0, 1, 1]) + l, = ax_test.plot([-3, 3], [-3, 3]) + # Explicit Path instead of a Rectangle uses clip path processing, instead + # of a clip box optimization. + p = mpath.Path([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]) + p = mpatches.PathPatch(p, transform=ax_test.transData) + l.set_clip_path(p) + + ax_ref = fig_ref.add_axes([0, 0, 1, 1]) + ax_ref.plot([-3, 3], [-3, 3]) + + ax_ref.set(xlim=(0.5, 0.75), ylim=(0.5, 0.75)) + ax_test.set(xlim=(0.5, 0.75), ylim=(0.5, 0.75)) + + +def test_cull_markers(): + x = np.random.random(20000) + y = np.random.random(20000) + + fig, ax = plt.subplots() + ax.plot(x, y, 'k.') + ax.set_xlim(2, 3) + + pdf = io.BytesIO() + fig.savefig(pdf, format="pdf") + assert len(pdf.getvalue()) < 8000 + + svg = io.BytesIO() + fig.savefig(svg, format="svg") + assert len(svg.getvalue()) < 20000 + + +@image_comparison(['hatching'], remove_text=True, style='default') +def test_hatching(): + fig, ax = plt.subplots(1, 1) + + # Default hatch color. + rect1 = mpatches.Rectangle((0, 0), 3, 4, hatch='/') + ax.add_patch(rect1) + + rect2 = mcollections.RegularPolyCollection( + 4, sizes=[16000], offsets=[(1.5, 6.5)], offset_transform=ax.transData, + hatch='/') + ax.add_collection(rect2) + + # Ensure edge color is not applied to hatching. + rect3 = mpatches.Rectangle((4, 0), 3, 4, hatch='/', edgecolor='C1') + ax.add_patch(rect3) + + rect4 = mcollections.RegularPolyCollection( + 4, sizes=[16000], offsets=[(5.5, 6.5)], offset_transform=ax.transData, + hatch='/', edgecolor='C1') + ax.add_collection(rect4) + + ax.set_xlim(0, 7) + ax.set_ylim(0, 9) + + +def test_remove(): + fig, ax = plt.subplots() + im = ax.imshow(np.arange(36).reshape(6, 6)) + ln, = ax.plot(range(5)) + + assert fig.stale + assert ax.stale + + fig.canvas.draw() + assert not fig.stale + assert not ax.stale + assert not ln.stale + + assert im in ax._mouseover_set + assert ln not in ax._mouseover_set + assert im.axes is ax + + im.remove() + ln.remove() + + for art in [im, ln]: + assert art.axes is None + assert art.figure is None + + assert im not in ax._mouseover_set + assert fig.stale + assert ax.stale + + +@image_comparison(["default_edges.png"], remove_text=True, style='default') +def test_default_edges(): + # Remove this line when this test image is regenerated. + plt.rcParams['text.kerning_factor'] = 6 + + fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(2, 2) + + ax1.plot(np.arange(10), np.arange(10), 'x', + np.arange(10) + 1, np.arange(10), 'o') + ax2.bar(np.arange(10), np.arange(10), align='edge') + ax3.text(0, 0, "BOX", size=24, bbox=dict(boxstyle='sawtooth')) + ax3.set_xlim((-1, 1)) + ax3.set_ylim((-1, 1)) + pp1 = mpatches.PathPatch( + mpath.Path([(0, 0), (1, 0), (1, 1), (0, 0)], + [mpath.Path.MOVETO, mpath.Path.CURVE3, + mpath.Path.CURVE3, mpath.Path.CLOSEPOLY]), + fc="none", transform=ax4.transData) + ax4.add_patch(pp1) + + +def test_properties(): + ln = mlines.Line2D([], []) + ln.properties() # Check that no warning is emitted. + + +def test_setp(): + # Check empty list + plt.setp([]) + plt.setp([[]]) + + # Check arbitrary iterables + fig, ax = plt.subplots() + lines1 = ax.plot(range(3)) + lines2 = ax.plot(range(3)) + martist.setp(chain(lines1, lines2), 'lw', 5) + plt.setp(ax.spines.values(), color='green') + + # Check *file* argument + sio = io.StringIO() + plt.setp(lines1, 'zorder', file=sio) + assert sio.getvalue() == ' zorder: float\n' + + +def test_None_zorder(): + fig, ax = plt.subplots() + ln, = ax.plot(range(5), zorder=None) + assert ln.get_zorder() == mlines.Line2D.zorder + ln.set_zorder(123456) + assert ln.get_zorder() == 123456 + ln.set_zorder(None) + assert ln.get_zorder() == mlines.Line2D.zorder + + +@pytest.mark.parametrize('accept_clause, expected', [ + ('', 'unknown'), + ("ACCEPTS: [ '-' | '--' | '-.' ]", "[ '-' | '--' | '-.' ]"), + ('ACCEPTS: Some description.', 'Some description.'), + ('.. ACCEPTS: Some description.', 'Some description.'), + ('arg : int', 'int'), + ('*arg : int', 'int'), + ('arg : int\nACCEPTS: Something else.', 'Something else. '), +]) +def test_artist_inspector_get_valid_values(accept_clause, expected): + class TestArtist(martist.Artist): + def set_f(self, arg): + pass + + TestArtist.set_f.__doc__ = """ + Some text. + + %s + """ % accept_clause + valid_values = martist.ArtistInspector(TestArtist).get_valid_values('f') + assert valid_values == expected + + +def test_artist_inspector_get_aliases(): + # test the correct format and type of get_aliases method + ai = martist.ArtistInspector(mlines.Line2D) + aliases = ai.get_aliases() + assert aliases["linewidth"] == {"lw"} + + +def test_set_alpha(): + art = martist.Artist() + with pytest.raises(TypeError, match='^alpha must be numeric or None'): + art.set_alpha('string') + with pytest.raises(TypeError, match='^alpha must be numeric or None'): + art.set_alpha([1, 2, 3]) + with pytest.raises(ValueError, match="outside 0-1 range"): + art.set_alpha(1.1) + with pytest.raises(ValueError, match="outside 0-1 range"): + art.set_alpha(np.nan) + + +def test_set_alpha_for_array(): + art = martist.Artist() + with pytest.raises(TypeError, match='^alpha must be numeric or None'): + art._set_alpha_for_array('string') + with pytest.raises(ValueError, match="outside 0-1 range"): + art._set_alpha_for_array(1.1) + with pytest.raises(ValueError, match="outside 0-1 range"): + art._set_alpha_for_array(np.nan) + with pytest.raises(ValueError, match="alpha must be between 0 and 1"): + art._set_alpha_for_array([0.5, 1.1]) + with pytest.raises(ValueError, match="alpha must be between 0 and 1"): + art._set_alpha_for_array([0.5, np.nan]) + + +def test_callbacks(): + def func(artist): + func.counter += 1 + + func.counter = 0 + + art = martist.Artist() + oid = art.add_callback(func) + assert func.counter == 0 + art.pchanged() # must call the callback + assert func.counter == 1 + art.set_zorder(10) # setting a property must also call the callback + assert func.counter == 2 + art.remove_callback(oid) + art.pchanged() # must not call the callback anymore + assert func.counter == 2 + + +def test_set_signature(): + """Test autogenerated ``set()`` for Artist subclasses.""" + class MyArtist1(martist.Artist): + def set_myparam1(self, val): + pass + + assert hasattr(MyArtist1.set, '_autogenerated_signature') + assert 'myparam1' in MyArtist1.set.__doc__ + + class MyArtist2(MyArtist1): + def set_myparam2(self, val): + pass + + assert hasattr(MyArtist2.set, '_autogenerated_signature') + assert 'myparam1' in MyArtist2.set.__doc__ + assert 'myparam2' in MyArtist2.set.__doc__ + + +def test_set_is_overwritten(): + """set() defined in Artist subclasses should not be overwritten.""" + class MyArtist3(martist.Artist): + + def set(self, **kwargs): + """Not overwritten.""" + + assert not hasattr(MyArtist3.set, '_autogenerated_signature') + assert MyArtist3.set.__doc__ == "Not overwritten." + + class MyArtist4(MyArtist3): + pass + + assert MyArtist4.set is MyArtist3.set + + +def test_format_cursor_data_BoundaryNorm(): + """Test if cursor data is correct when using BoundaryNorm.""" + X = np.empty((3, 3)) + X[0, 0] = 0.9 + X[0, 1] = 0.99 + X[0, 2] = 0.999 + X[1, 0] = -1 + X[1, 1] = 0 + X[1, 2] = 1 + X[2, 0] = 0.09 + X[2, 1] = 0.009 + X[2, 2] = 0.0009 + + # map range -1..1 to 0..256 in 0.1 steps + fig, ax = plt.subplots() + fig.suptitle("-1..1 to 0..256 in 0.1") + norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 20), 256) + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + + labels_list = [ + "[0.9]", + "[1.]", + "[1.]", + "[-1.0]", + "[0.0]", + "[1.0]", + "[0.09]", + "[0.009]", + "[0.0009]", + ] + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.1)) + assert img.format_cursor_data(v) == label + + plt.close() + + # map range -1..1 to 0..256 in 0.01 steps + fig, ax = plt.subplots() + fig.suptitle("-1..1 to 0..256 in 0.01") + cmap = mpl.colormaps['RdBu_r'].resampled(200) + norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 200), 200) + img = ax.imshow(X, cmap=cmap, norm=norm) + + labels_list = [ + "[0.90]", + "[0.99]", + "[1.0]", + "[-1.00]", + "[0.00]", + "[1.00]", + "[0.09]", + "[0.009]", + "[0.0009]", + ] + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.01)) + assert img.format_cursor_data(v) == label + + plt.close() + + # map range -1..1 to 0..256 in 0.01 steps + fig, ax = plt.subplots() + fig.suptitle("-1..1 to 0..256 in 0.001") + cmap = mpl.colormaps['RdBu_r'].resampled(2000) + norm = mcolors.BoundaryNorm(np.linspace(-1, 1, 2000), 2000) + img = ax.imshow(X, cmap=cmap, norm=norm) + + labels_list = [ + "[0.900]", + "[0.990]", + "[0.999]", + "[-1.000]", + "[0.000]", + "[1.000]", + "[0.090]", + "[0.009]", + "[0.0009]", + ] + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.001)) + assert img.format_cursor_data(v) == label + + plt.close() + + # different testing data set with + # out of bounds values for 0..1 range + X = np.empty((7, 1)) + X[0] = -1.0 + X[1] = 0.0 + X[2] = 0.1 + X[3] = 0.5 + X[4] = 0.9 + X[5] = 1.0 + X[6] = 2.0 + + labels_list = [ + "[-1.0]", + "[0.0]", + "[0.1]", + "[0.5]", + "[0.9]", + "[1.0]", + "[2.0]", + ] + + fig, ax = plt.subplots() + fig.suptitle("noclip, neither") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='neither') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("noclip, min") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='min') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("noclip, max") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='max') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("noclip, both") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=False, extend='both') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + fig, ax = plt.subplots() + fig.suptitle("clip, neither") + norm = mcolors.BoundaryNorm( + np.linspace(0, 1, 4, endpoint=True), 256, clip=True, extend='neither') + img = ax.imshow(X, cmap='RdBu_r', norm=norm) + for v, label in zip(X.flat, labels_list): + # label = "[{:-#.{}g}]".format(v, cbook._g_sig_digits(v, 0.33)) + assert img.format_cursor_data(v) == label + + plt.close() + + +def test_auto_no_rasterize(): + class Gen1(martist.Artist): + ... + + assert 'draw' in Gen1.__dict__ + assert Gen1.__dict__['draw'] is Gen1.draw + + class Gen2(Gen1): + ... + + assert 'draw' not in Gen2.__dict__ + assert Gen2.draw is Gen1.draw + + +def test_draw_wraper_forward_input(): + class TestKlass(martist.Artist): + def draw(self, renderer, extra): + return extra + + art = TestKlass() + renderer = mbackend_bases.RendererBase() + + assert 'aardvark' == art.draw(renderer, 'aardvark') + assert 'aardvark' == art.draw(renderer, extra='aardvark') diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_axis.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_axis.py new file mode 100644 index 0000000000000000000000000000000000000000..97b5f88dede17ebde9aa828b55a2d1707981865e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_axis.py @@ -0,0 +1,10 @@ +import numpy as np + +import matplotlib.pyplot as plt +from matplotlib.axis import XTick + + +def test_tick_labelcolor_array(): + # Smoke test that we can instantiate a Tick with labelcolor as array. + ax = plt.axes() + XTick(ax, 0, labelcolor=np.array([1, 0, 0, 1])) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py new file mode 100644 index 0000000000000000000000000000000000000000..23af88d9508677d799d6546b1b49fa10d34822b2 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_nbagg.py @@ -0,0 +1,42 @@ +import os +from pathlib import Path +from tempfile import TemporaryDirectory + +import pytest + +from matplotlib.testing import subprocess_run_for_testing + +nbformat = pytest.importorskip('nbformat') +pytest.importorskip('nbconvert') +pytest.importorskip('ipykernel') + +# From https://blog.thedataincubator.com/2016/06/testing-jupyter-notebooks/ + + +def test_ipynb(): + nb_path = Path(__file__).parent / 'test_nbagg_01.ipynb' + + with TemporaryDirectory() as tmpdir: + out_path = Path(tmpdir, "out.ipynb") + subprocess_run_for_testing( + ["jupyter", "nbconvert", "--to", "notebook", + "--execute", "--ExecutePreprocessor.timeout=500", + "--output", str(out_path), str(nb_path)], + env={**os.environ, "IPYTHONDIR": tmpdir}, + check=True) + with out_path.open() as out: + nb = nbformat.read(out, nbformat.current_nbformat) + + errors = [output for cell in nb.cells for output in cell.get("outputs", []) + if output.output_type == "error"] + assert not errors + + import IPython + if IPython.version_info[:2] >= (8, 24): + expected_backend = "notebook" + else: + # This code can be removed when Python 3.12, the latest version supported by + # IPython < 8.24, reaches end-of-life in late 2028. + expected_backend = "nbAgg" + backend_outputs = nb.cells[2]["outputs"] + assert backend_outputs[0]["data"]["text/plain"] == f"'{expected_backend}'" diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_pgf.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_pgf.py new file mode 100644 index 0000000000000000000000000000000000000000..8a83515f161c70327104b5f4531d73a8a71d2e57 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_backend_pgf.py @@ -0,0 +1,408 @@ +import datetime +from io import BytesIO +import os +import shutil + +import numpy as np +from packaging.version import parse as parse_version +import pytest + +import matplotlib as mpl +import matplotlib.pyplot as plt +from matplotlib.testing import _has_tex_package, _check_for_pgf +from matplotlib.testing.exceptions import ImageComparisonFailure +from matplotlib.testing.compare import compare_images +from matplotlib.backends.backend_pgf import PdfPages +from matplotlib.testing.decorators import ( + _image_directories, check_figures_equal, image_comparison) +from matplotlib.testing._markers import ( + needs_ghostscript, needs_pgf_lualatex, needs_pgf_pdflatex, + needs_pgf_xelatex) + + +baseline_dir, result_dir = _image_directories(lambda: 'dummy func') + + +def compare_figure(fname, savefig_kwargs={}, tol=0): + actual = os.path.join(result_dir, fname) + plt.savefig(actual, **savefig_kwargs) + + expected = os.path.join(result_dir, "expected_%s" % fname) + shutil.copyfile(os.path.join(baseline_dir, fname), expected) + err = compare_images(expected, actual, tol=tol) + if err: + raise ImageComparisonFailure(err) + + +@needs_pgf_xelatex +@needs_ghostscript +@pytest.mark.backend('pgf') +def test_tex_special_chars(tmp_path): + fig = plt.figure() + fig.text(.5, .5, "%_^ $a_b^c$") + buf = BytesIO() + fig.savefig(buf, format="png", backend="pgf") + buf.seek(0) + t = plt.imread(buf) + assert not (t == 1).all() # The leading "%" didn't eat up everything. + + +def create_figure(): + plt.figure() + x = np.linspace(0, 1, 15) + + # line plot + plt.plot(x, x ** 2, "b-") + + # marker + plt.plot(x, 1 - x**2, "g>") + + # filled paths and patterns + plt.fill_between([0., .4], [.4, 0.], hatch='//', facecolor="lightgray", + edgecolor="red") + plt.fill([3, 3, .8, .8, 3], [2, -2, -2, 0, 2], "b") + + # text and typesetting + plt.plot([0.9], [0.5], "ro", markersize=3) + plt.text(0.9, 0.5, 'unicode (ü, °, \N{Section Sign}) and math ($\\mu_i = x_i^2$)', + ha='right', fontsize=20) + plt.ylabel('sans-serif, blue, $\\frac{\\sqrt{x}}{y^2}$..', + family='sans-serif', color='blue') + plt.text(1, 1, 'should be clipped as default clip_box is Axes bbox', + fontsize=20, clip_on=True) + + plt.xlim(0, 1) + plt.ylim(0, 1) + + +# test compiling a figure to pdf with xelatex +@needs_pgf_xelatex +@pytest.mark.backend('pgf') +@image_comparison(['pgf_xelatex.pdf'], style='default') +def test_xelatex(): + rc_xelatex = {'font.family': 'serif', + 'pgf.rcfonts': False} + mpl.rcParams.update(rc_xelatex) + create_figure() + + +try: + _old_gs_version = \ + mpl._get_executable_info('gs').version < parse_version('9.50') +except mpl.ExecutableNotFoundError: + _old_gs_version = True + + +# test compiling a figure to pdf with pdflatex +@needs_pgf_pdflatex +@pytest.mark.skipif(not _has_tex_package('type1ec'), reason='needs type1ec.sty') +@pytest.mark.skipif(not _has_tex_package('ucs'), reason='needs ucs.sty') +@pytest.mark.backend('pgf') +@image_comparison(['pgf_pdflatex.pdf'], style='default', + tol=11.71 if _old_gs_version else 0) +def test_pdflatex(): + rc_pdflatex = {'font.family': 'serif', + 'pgf.rcfonts': False, + 'pgf.texsystem': 'pdflatex', + 'pgf.preamble': ('\\usepackage[utf8x]{inputenc}' + '\\usepackage[T1]{fontenc}')} + mpl.rcParams.update(rc_pdflatex) + create_figure() + + +# test updating the rc parameters for each figure +@needs_pgf_xelatex +@needs_pgf_pdflatex +@mpl.style.context('default') +@pytest.mark.backend('pgf') +def test_rcupdate(): + rc_sets = [{'font.family': 'sans-serif', + 'font.size': 30, + 'figure.subplot.left': .2, + 'lines.markersize': 10, + 'pgf.rcfonts': False, + 'pgf.texsystem': 'xelatex'}, + {'font.family': 'monospace', + 'font.size': 10, + 'figure.subplot.left': .1, + 'lines.markersize': 20, + 'pgf.rcfonts': False, + 'pgf.texsystem': 'pdflatex', + 'pgf.preamble': ('\\usepackage[utf8x]{inputenc}' + '\\usepackage[T1]{fontenc}' + '\\usepackage{sfmath}')}] + tol = [0, 13.2] if _old_gs_version else [0, 0] + for i, rc_set in enumerate(rc_sets): + with mpl.rc_context(rc_set): + for substring, pkg in [('sfmath', 'sfmath'), ('utf8x', 'ucs')]: + if (substring in mpl.rcParams['pgf.preamble'] + and not _has_tex_package(pkg)): + pytest.skip(f'needs {pkg}.sty') + create_figure() + compare_figure(f'pgf_rcupdate{i + 1}.pdf', tol=tol[i]) + + +# test backend-side clipping, since large numbers are not supported by TeX +@needs_pgf_xelatex +@mpl.style.context('default') +@pytest.mark.backend('pgf') +def test_pathclip(): + np.random.seed(19680801) + mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False}) + fig, axs = plt.subplots(1, 2) + + axs[0].plot([0., 1e100], [0., 1e100]) + axs[0].set_xlim(0, 1) + axs[0].set_ylim(0, 1) + + axs[1].scatter([0, 1], [1, 1]) + axs[1].hist(np.random.normal(size=1000), bins=20, range=[-10, 10]) + axs[1].set_xscale('log') + + fig.savefig(BytesIO(), format="pdf") # No image comparison. + + +# test mixed mode rendering +@needs_pgf_xelatex +@pytest.mark.backend('pgf') +@image_comparison(['pgf_mixedmode.pdf'], style='default') +def test_mixedmode(): + mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False}) + Y, X = np.ogrid[-1:1:40j, -1:1:40j] + plt.pcolor(X**2 + Y**2).set_rasterized(True) + + +# test bbox_inches clipping +@needs_pgf_xelatex +@mpl.style.context('default') +@pytest.mark.backend('pgf') +def test_bbox_inches(): + mpl.rcParams.update({'font.family': 'serif', 'pgf.rcfonts': False}) + fig, (ax1, ax2) = plt.subplots(1, 2) + ax1.plot(range(5)) + ax2.plot(range(5)) + plt.tight_layout() + bbox = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted()) + compare_figure('pgf_bbox_inches.pdf', savefig_kwargs={'bbox_inches': bbox}, + tol=0) + + +@mpl.style.context('default') +@pytest.mark.backend('pgf') +@pytest.mark.parametrize('system', [ + pytest.param('lualatex', marks=[needs_pgf_lualatex]), + pytest.param('pdflatex', marks=[needs_pgf_pdflatex]), + pytest.param('xelatex', marks=[needs_pgf_xelatex]), +]) +def test_pdf_pages(system): + rc_pdflatex = { + 'font.family': 'serif', + 'pgf.rcfonts': False, + 'pgf.texsystem': system, + } + mpl.rcParams.update(rc_pdflatex) + + fig1, ax1 = plt.subplots() + ax1.plot(range(5)) + fig1.tight_layout() + + fig2, ax2 = plt.subplots(figsize=(3, 2)) + ax2.plot(range(5)) + fig2.tight_layout() + + path = os.path.join(result_dir, f'pdfpages_{system}.pdf') + md = { + 'Author': 'me', + 'Title': 'Multipage PDF with pgf', + 'Subject': 'Test page', + 'Keywords': 'test,pdf,multipage', + 'ModDate': datetime.datetime( + 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))), + 'Trapped': 'Unknown' + } + + with PdfPages(path, metadata=md) as pdf: + pdf.savefig(fig1) + pdf.savefig(fig2) + pdf.savefig(fig1) + + assert pdf.get_pagecount() == 3 + + +@mpl.style.context('default') +@pytest.mark.backend('pgf') +@pytest.mark.parametrize('system', [ + pytest.param('lualatex', marks=[needs_pgf_lualatex]), + pytest.param('pdflatex', marks=[needs_pgf_pdflatex]), + pytest.param('xelatex', marks=[needs_pgf_xelatex]), +]) +def test_pdf_pages_metadata_check(monkeypatch, system): + # Basically the same as test_pdf_pages, but we keep it separate to leave + # pikepdf as an optional dependency. + pikepdf = pytest.importorskip('pikepdf') + monkeypatch.setenv('SOURCE_DATE_EPOCH', '0') + + mpl.rcParams.update({'pgf.texsystem': system}) + + fig, ax = plt.subplots() + ax.plot(range(5)) + + md = { + 'Author': 'me', + 'Title': 'Multipage PDF with pgf', + 'Subject': 'Test page', + 'Keywords': 'test,pdf,multipage', + 'ModDate': datetime.datetime( + 1968, 8, 1, tzinfo=datetime.timezone(datetime.timedelta(0))), + 'Trapped': 'True' + } + path = os.path.join(result_dir, f'pdfpages_meta_check_{system}.pdf') + with PdfPages(path, metadata=md) as pdf: + pdf.savefig(fig) + + with pikepdf.Pdf.open(path) as pdf: + info = {k: str(v) for k, v in pdf.docinfo.items()} + + # Not set by us, so don't bother checking. + if '/PTEX.FullBanner' in info: + del info['/PTEX.FullBanner'] + if '/PTEX.Fullbanner' in info: + del info['/PTEX.Fullbanner'] + + # Some LaTeX engines ignore this setting, and state themselves as producer. + producer = info.pop('/Producer') + assert producer == f'Matplotlib pgf backend v{mpl.__version__}' or ( + system == 'lualatex' and 'LuaTeX' in producer) + + assert info == { + '/Author': 'me', + '/CreationDate': 'D:19700101000000Z', + '/Creator': f'Matplotlib v{mpl.__version__}, https://matplotlib.org', + '/Keywords': 'test,pdf,multipage', + '/ModDate': 'D:19680801000000Z', + '/Subject': 'Test page', + '/Title': 'Multipage PDF with pgf', + '/Trapped': '/True', + } + + +@needs_pgf_xelatex +def test_multipage_keep_empty(tmp_path): + # test empty pdf files + + # an empty pdf is left behind with keep_empty unset + fn = tmp_path / "a.pdf" + with pytest.warns(mpl.MatplotlibDeprecationWarning), PdfPages(fn) as pdf: + pass + assert fn.exists() + + # an empty pdf is left behind with keep_empty=True + fn = tmp_path / "b.pdf" + with pytest.warns(mpl.MatplotlibDeprecationWarning), \ + PdfPages(fn, keep_empty=True) as pdf: + pass + assert fn.exists() + + # an empty pdf deletes itself afterwards with keep_empty=False + fn = tmp_path / "c.pdf" + with PdfPages(fn, keep_empty=False) as pdf: + pass + assert not fn.exists() + + # test pdf files with content, they should never be deleted + + # a non-empty pdf is left behind with keep_empty unset + fn = tmp_path / "d.pdf" + with PdfPages(fn) as pdf: + pdf.savefig(plt.figure()) + assert fn.exists() + + # a non-empty pdf is left behind with keep_empty=True + fn = tmp_path / "e.pdf" + with pytest.warns(mpl.MatplotlibDeprecationWarning), \ + PdfPages(fn, keep_empty=True) as pdf: + pdf.savefig(plt.figure()) + assert fn.exists() + + # a non-empty pdf is left behind with keep_empty=False + fn = tmp_path / "f.pdf" + with PdfPages(fn, keep_empty=False) as pdf: + pdf.savefig(plt.figure()) + assert fn.exists() + + +@needs_pgf_xelatex +def test_tex_restart_after_error(): + fig = plt.figure() + fig.suptitle(r"\oops") + with pytest.raises(ValueError): + fig.savefig(BytesIO(), format="pgf") + + fig = plt.figure() # start from scratch + fig.suptitle(r"this is ok") + fig.savefig(BytesIO(), format="pgf") + + +@needs_pgf_xelatex +def test_bbox_inches_tight(): + fig, ax = plt.subplots() + ax.imshow([[0, 1], [2, 3]]) + fig.savefig(BytesIO(), format="pdf", backend="pgf", bbox_inches="tight") + + +@needs_pgf_xelatex +@needs_ghostscript +def test_png_transparency(): # Actually, also just testing that png works. + buf = BytesIO() + plt.figure().savefig(buf, format="png", backend="pgf", transparent=True) + buf.seek(0) + t = plt.imread(buf) + assert (t[..., 3] == 0).all() # fully transparent. + + +@needs_pgf_xelatex +def test_unknown_font(caplog): + with caplog.at_level("WARNING"): + mpl.rcParams["font.family"] = "this-font-does-not-exist" + plt.figtext(.5, .5, "hello, world") + plt.savefig(BytesIO(), format="pgf") + assert "Ignoring unknown font: this-font-does-not-exist" in [ + r.getMessage() for r in caplog.records] + + +@check_figures_equal(extensions=["pdf"]) +@pytest.mark.parametrize("texsystem", ("pdflatex", "xelatex", "lualatex")) +@pytest.mark.backend("pgf") +def test_minus_signs_with_tex(fig_test, fig_ref, texsystem): + if not _check_for_pgf(texsystem): + pytest.skip(texsystem + ' + pgf is required') + mpl.rcParams["pgf.texsystem"] = texsystem + fig_test.text(.5, .5, "$-1$") + fig_ref.text(.5, .5, "$\N{MINUS SIGN}1$") + + +@pytest.mark.backend("pgf") +def test_sketch_params(): + fig, ax = plt.subplots(figsize=(3, 3)) + ax.set_xticks([]) + ax.set_yticks([]) + ax.set_frame_on(False) + handle, = ax.plot([0, 1]) + handle.set_sketch_params(scale=5, length=30, randomness=42) + + with BytesIO() as fd: + fig.savefig(fd, format='pgf') + buf = fd.getvalue().decode() + + baseline = r"""\pgfpathmoveto{\pgfqpoint{0.375000in}{0.300000in}}% +\pgfpathlineto{\pgfqpoint{2.700000in}{2.700000in}}% +\usepgfmodule{decorations}% +\usepgflibrary{decorations.pathmorphing}% +\pgfkeys{/pgf/decoration/.cd, """ \ + r"""segment length = 0.150000in, amplitude = 0.100000in}% +\pgfmathsetseed{42}% +\pgfdecoratecurrentpath{random steps}% +\pgfusepath{stroke}%""" + # \pgfdecoratecurrentpath must be after the path definition and before the + # path is used (\pgfusepath) + assert baseline in buf diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_collections.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_collections.py new file mode 100644 index 0000000000000000000000000000000000000000..23e951b17a2f263bce432d83adcf25b03f20d636 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_collections.py @@ -0,0 +1,1338 @@ +from datetime import datetime +import io +import itertools +import platform +import re +from types import SimpleNamespace + +import numpy as np +from numpy.testing import assert_array_equal, assert_array_almost_equal +import pytest + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.collections as mcollections +import matplotlib.colors as mcolors +import matplotlib.path as mpath +import matplotlib.transforms as mtransforms +from matplotlib.collections import (Collection, LineCollection, + EventCollection, PolyCollection) +from matplotlib.testing.decorators import check_figures_equal, image_comparison + + +@pytest.fixture(params=["pcolormesh", "pcolor"]) +def pcfunc(request): + return request.param + + +def generate_EventCollection_plot(): + """Generate the initial collection and plot it.""" + positions = np.array([0., 1., 2., 3., 5., 8., 13., 21.]) + extra_positions = np.array([34., 55., 89.]) + orientation = 'horizontal' + lineoffset = 1 + linelength = .5 + linewidth = 2 + color = [1, 0, 0, 1] + linestyle = 'solid' + antialiased = True + + coll = EventCollection(positions, + orientation=orientation, + lineoffset=lineoffset, + linelength=linelength, + linewidth=linewidth, + color=color, + linestyle=linestyle, + antialiased=antialiased + ) + + fig, ax = plt.subplots() + ax.add_collection(coll) + ax.set_title('EventCollection: default') + props = {'positions': positions, + 'extra_positions': extra_positions, + 'orientation': orientation, + 'lineoffset': lineoffset, + 'linelength': linelength, + 'linewidth': linewidth, + 'color': color, + 'linestyle': linestyle, + 'antialiased': antialiased + } + ax.set_xlim(-1, 22) + ax.set_ylim(0, 2) + return ax, coll, props + + +@image_comparison(['EventCollection_plot__default']) +def test__EventCollection__get_props(): + _, coll, props = generate_EventCollection_plot() + # check that the default segments have the correct coordinates + check_segments(coll, + props['positions'], + props['linelength'], + props['lineoffset'], + props['orientation']) + # check that the default positions match the input positions + np.testing.assert_array_equal(props['positions'], coll.get_positions()) + # check that the default orientation matches the input orientation + assert props['orientation'] == coll.get_orientation() + # check that the default orientation matches the input orientation + assert coll.is_horizontal() + # check that the default linelength matches the input linelength + assert props['linelength'] == coll.get_linelength() + # check that the default lineoffset matches the input lineoffset + assert props['lineoffset'] == coll.get_lineoffset() + # check that the default linestyle matches the input linestyle + assert coll.get_linestyle() == [(0, None)] + # check that the default color matches the input color + for color in [coll.get_color(), *coll.get_colors()]: + np.testing.assert_array_equal(color, props['color']) + + +@image_comparison(['EventCollection_plot__set_positions']) +def test__EventCollection__set_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], props['extra_positions']]) + coll.set_positions(new_positions) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: set_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__add_positions']) +def test__EventCollection__add_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][0]]) + coll.switch_orientation() # Test adding in the vertical orientation, too. + coll.add_positions(props['extra_positions'][0]) + coll.switch_orientation() + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: add_positions') + splt.set_xlim(-1, 35) + + +@image_comparison(['EventCollection_plot__append_positions']) +def test__EventCollection__append_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][2]]) + coll.append_positions(props['extra_positions'][2]) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: append_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__extend_positions']) +def test__EventCollection__extend_positions(): + splt, coll, props = generate_EventCollection_plot() + new_positions = np.hstack([props['positions'], + props['extra_positions'][1:]]) + coll.extend_positions(props['extra_positions'][1:]) + np.testing.assert_array_equal(new_positions, coll.get_positions()) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: extend_positions') + splt.set_xlim(-1, 90) + + +@image_comparison(['EventCollection_plot__switch_orientation']) +def test__EventCollection__switch_orientation(): + splt, coll, props = generate_EventCollection_plot() + new_orientation = 'vertical' + coll.switch_orientation() + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() + new_positions = coll.get_positions() + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], new_orientation) + splt.set_title('EventCollection: switch_orientation') + splt.set_ylim(-1, 22) + splt.set_xlim(0, 2) + + +@image_comparison(['EventCollection_plot__switch_orientation__2x']) +def test__EventCollection__switch_orientation_2x(): + """ + Check that calling switch_orientation twice sets the orientation back to + the default. + """ + splt, coll, props = generate_EventCollection_plot() + coll.switch_orientation() + coll.switch_orientation() + new_positions = coll.get_positions() + assert props['orientation'] == coll.get_orientation() + assert coll.is_horizontal() + np.testing.assert_array_equal(props['positions'], new_positions) + check_segments(coll, + new_positions, + props['linelength'], + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: switch_orientation 2x') + + +@image_comparison(['EventCollection_plot__set_orientation']) +def test__EventCollection__set_orientation(): + splt, coll, props = generate_EventCollection_plot() + new_orientation = 'vertical' + coll.set_orientation(new_orientation) + assert new_orientation == coll.get_orientation() + assert not coll.is_horizontal() + check_segments(coll, + props['positions'], + props['linelength'], + props['lineoffset'], + new_orientation) + splt.set_title('EventCollection: set_orientation') + splt.set_ylim(-1, 22) + splt.set_xlim(0, 2) + + +@image_comparison(['EventCollection_plot__set_linelength']) +def test__EventCollection__set_linelength(): + splt, coll, props = generate_EventCollection_plot() + new_linelength = 15 + coll.set_linelength(new_linelength) + assert new_linelength == coll.get_linelength() + check_segments(coll, + props['positions'], + new_linelength, + props['lineoffset'], + props['orientation']) + splt.set_title('EventCollection: set_linelength') + splt.set_ylim(-20, 20) + + +@image_comparison(['EventCollection_plot__set_lineoffset']) +def test__EventCollection__set_lineoffset(): + splt, coll, props = generate_EventCollection_plot() + new_lineoffset = -5. + coll.set_lineoffset(new_lineoffset) + assert new_lineoffset == coll.get_lineoffset() + check_segments(coll, + props['positions'], + props['linelength'], + new_lineoffset, + props['orientation']) + splt.set_title('EventCollection: set_lineoffset') + splt.set_ylim(-6, -4) + + +@image_comparison([ + 'EventCollection_plot__set_linestyle', + 'EventCollection_plot__set_linestyle', + 'EventCollection_plot__set_linewidth', +]) +def test__EventCollection__set_prop(): + for prop, value, expected in [ + ('linestyle', 'dashed', [(0, (6.0, 6.0))]), + ('linestyle', (0, (6., 6.)), [(0, (6.0, 6.0))]), + ('linewidth', 5, 5), + ]: + splt, coll, _ = generate_EventCollection_plot() + coll.set(**{prop: value}) + assert plt.getp(coll, prop) == expected + splt.set_title(f'EventCollection: set_{prop}') + + +@image_comparison(['EventCollection_plot__set_color']) +def test__EventCollection__set_color(): + splt, coll, _ = generate_EventCollection_plot() + new_color = np.array([0, 1, 1, 1]) + coll.set_color(new_color) + for color in [coll.get_color(), *coll.get_colors()]: + np.testing.assert_array_equal(color, new_color) + splt.set_title('EventCollection: set_color') + + +def check_segments(coll, positions, linelength, lineoffset, orientation): + """ + Test helper checking that all values in the segment are correct, given a + particular set of inputs. + """ + segments = coll.get_segments() + if (orientation.lower() == 'horizontal' + or orientation.lower() == 'none' or orientation is None): + # if horizontal, the position in is in the y-axis + pos1 = 1 + pos2 = 0 + elif orientation.lower() == 'vertical': + # if vertical, the position in is in the x-axis + pos1 = 0 + pos2 = 1 + else: + raise ValueError("orientation must be 'horizontal' or 'vertical'") + + # test to make sure each segment is correct + for i, segment in enumerate(segments): + assert segment[0, pos1] == lineoffset + linelength / 2 + assert segment[1, pos1] == lineoffset - linelength / 2 + assert segment[0, pos2] == positions[i] + assert segment[1, pos2] == positions[i] + + +def test_collection_norm_autoscale(): + # norm should be autoscaled when array is set, not deferred to draw time + lines = np.arange(24).reshape((4, 3, 2)) + coll = mcollections.LineCollection(lines, array=np.arange(4)) + assert coll.norm(2) == 2 / 3 + # setting a new array shouldn't update the already scaled limits + coll.set_array(np.arange(4) + 5) + assert coll.norm(2) == 2 / 3 + + +def test_null_collection_datalim(): + col = mcollections.PathCollection([]) + col_data_lim = col.get_datalim(mtransforms.IdentityTransform()) + assert_array_equal(col_data_lim.get_points(), + mtransforms.Bbox.null().get_points()) + + +def test_no_offsets_datalim(): + # A collection with no offsets and a non transData + # transform should return a null bbox + ax = plt.axes() + coll = mcollections.PathCollection([mpath.Path([(0, 0), (1, 0)])]) + ax.add_collection(coll) + coll_data_lim = coll.get_datalim(mtransforms.IdentityTransform()) + assert_array_equal(coll_data_lim.get_points(), + mtransforms.Bbox.null().get_points()) + + +def test_add_collection(): + # Test if data limits are unchanged by adding an empty collection. + # GitHub issue #1490, pull #1497. + plt.figure() + ax = plt.axes() + ax.scatter([0, 1], [0, 1]) + bounds = ax.dataLim.bounds + ax.scatter([], []) + assert ax.dataLim.bounds == bounds + + +@mpl.style.context('mpl20') +@check_figures_equal(extensions=['png']) +def test_collection_log_datalim(fig_test, fig_ref): + # Data limits should respect the minimum x/y when using log scale. + x_vals = [4.38462e-6, 5.54929e-6, 7.02332e-6, 8.88889e-6, 1.12500e-5, + 1.42383e-5, 1.80203e-5, 2.28070e-5, 2.88651e-5, 3.65324e-5, + 4.62363e-5, 5.85178e-5, 7.40616e-5, 9.37342e-5, 1.18632e-4] + y_vals = [0.0, 0.1, 0.182, 0.332, 0.604, 1.1, 2.0, 3.64, 6.64, 12.1, 22.0, + 39.6, 71.3] + + x, y = np.meshgrid(x_vals, y_vals) + x = x.flatten() + y = y.flatten() + + ax_test = fig_test.subplots() + ax_test.set_xscale('log') + ax_test.set_yscale('log') + ax_test.margins = 0 + ax_test.scatter(x, y) + + ax_ref = fig_ref.subplots() + ax_ref.set_xscale('log') + ax_ref.set_yscale('log') + ax_ref.plot(x, y, marker="o", ls="") + + +def test_quiver_limits(): + ax = plt.axes() + x, y = np.arange(8), np.arange(10) + u = v = np.linspace(0, 10, 80).reshape(10, 8) + q = plt.quiver(x, y, u, v) + assert q.get_datalim(ax.transData).bounds == (0., 0., 7., 9.) + + plt.figure() + ax = plt.axes() + x = np.linspace(-5, 10, 20) + y = np.linspace(-2, 4, 10) + y, x = np.meshgrid(y, x) + trans = mtransforms.Affine2D().translate(25, 32) + ax.transData + plt.quiver(x, y, np.sin(x), np.cos(y), transform=trans) + assert ax.dataLim.bounds == (20.0, 30.0, 15.0, 6.0) + + +def test_barb_limits(): + ax = plt.axes() + x = np.linspace(-5, 10, 20) + y = np.linspace(-2, 4, 10) + y, x = np.meshgrid(y, x) + trans = mtransforms.Affine2D().translate(25, 32) + ax.transData + plt.barbs(x, y, np.sin(x), np.cos(y), transform=trans) + # The calculated bounds are approximately the bounds of the original data, + # this is because the entire path is taken into account when updating the + # datalim. + assert_array_almost_equal(ax.dataLim.bounds, (20, 30, 15, 6), + decimal=1) + + +@image_comparison(['EllipseCollection_test_image.png'], remove_text=True, + tol=0.021 if platform.machine() == 'arm64' else 0) +def test_EllipseCollection(): + # Test basic functionality + fig, ax = plt.subplots() + x = np.arange(4) + y = np.arange(3) + X, Y = np.meshgrid(x, y) + XY = np.vstack((X.ravel(), Y.ravel())).T + + ww = X / x[-1] + hh = Y / y[-1] + aa = np.ones_like(ww) * 20 # first axis is 20 degrees CCW from x axis + + ec = mcollections.EllipseCollection( + ww, hh, aa, units='x', offsets=XY, offset_transform=ax.transData, + facecolors='none') + ax.add_collection(ec) + ax.autoscale_view() + + +def test_EllipseCollection_setter_getter(): + # Test widths, heights and angle setter + rng = np.random.default_rng(0) + + widths = (2, ) + heights = (3, ) + angles = (45, ) + offsets = rng.random((10, 2)) * 10 + + fig, ax = plt.subplots() + + ec = mcollections.EllipseCollection( + widths=widths, + heights=heights, + angles=angles, + offsets=offsets, + units='x', + offset_transform=ax.transData, + ) + + assert_array_almost_equal(ec._widths, np.array(widths).ravel() * 0.5) + assert_array_almost_equal(ec._heights, np.array(heights).ravel() * 0.5) + assert_array_almost_equal(ec._angles, np.deg2rad(angles).ravel()) + + assert_array_almost_equal(ec.get_widths(), widths) + assert_array_almost_equal(ec.get_heights(), heights) + assert_array_almost_equal(ec.get_angles(), angles) + + ax.add_collection(ec) + ax.set_xlim(-2, 12) + ax.set_ylim(-2, 12) + + new_widths = rng.random((10, 2)) * 2 + new_heights = rng.random((10, 2)) * 3 + new_angles = rng.random((10, 2)) * 180 + + ec.set(widths=new_widths, heights=new_heights, angles=new_angles) + + assert_array_almost_equal(ec.get_widths(), new_widths.ravel()) + assert_array_almost_equal(ec.get_heights(), new_heights.ravel()) + assert_array_almost_equal(ec.get_angles(), new_angles.ravel()) + + +@image_comparison(['polycollection_close.png'], remove_text=True, style='mpl20') +def test_polycollection_close(): + from mpl_toolkits.mplot3d import Axes3D # type: ignore + plt.rcParams['axes3d.automargin'] = True + + vertsQuad = [ + [[0., 0.], [0., 1.], [1., 1.], [1., 0.]], + [[0., 1.], [2., 3.], [2., 2.], [1., 1.]], + [[2., 2.], [2., 3.], [4., 1.], [3., 1.]], + [[3., 0.], [3., 1.], [4., 1.], [4., 0.]]] + + fig = plt.figure() + ax = fig.add_axes(Axes3D(fig)) + + colors = ['r', 'g', 'b', 'y', 'k'] + zpos = list(range(5)) + + poly = mcollections.PolyCollection( + vertsQuad * len(zpos), linewidth=0.25) + poly.set_alpha(0.7) + + # need to have a z-value for *each* polygon = element! + zs = [] + cs = [] + for z, c in zip(zpos, colors): + zs.extend([z] * len(vertsQuad)) + cs.extend([c] * len(vertsQuad)) + + poly.set_color(cs) + + ax.add_collection3d(poly, zs=zs, zdir='y') + + # axis limit settings: + ax.set_xlim3d(0, 4) + ax.set_zlim3d(0, 3) + ax.set_ylim3d(0, 4) + + +@image_comparison(['regularpolycollection_rotate.png'], remove_text=True) +def test_regularpolycollection_rotate(): + xx, yy = np.mgrid[:10, :10] + xy_points = np.transpose([xx.flatten(), yy.flatten()]) + rotations = np.linspace(0, 2*np.pi, len(xy_points)) + + fig, ax = plt.subplots() + for xy, alpha in zip(xy_points, rotations): + col = mcollections.RegularPolyCollection( + 4, sizes=(100,), rotation=alpha, + offsets=[xy], offset_transform=ax.transData) + ax.add_collection(col, autolim=True) + ax.autoscale_view() + + +@image_comparison(['regularpolycollection_scale.png'], remove_text=True) +def test_regularpolycollection_scale(): + # See issue #3860 + + class SquareCollection(mcollections.RegularPolyCollection): + def __init__(self, **kwargs): + super().__init__(4, rotation=np.pi/4., **kwargs) + + def get_transform(self): + """Return transform scaling circle areas to data space.""" + ax = self.axes + + pts2pixels = 72.0 / ax.figure.dpi + + scale_x = pts2pixels * ax.bbox.width / ax.viewLim.width + scale_y = pts2pixels * ax.bbox.height / ax.viewLim.height + return mtransforms.Affine2D().scale(scale_x, scale_y) + + fig, ax = plt.subplots() + + xy = [(0, 0)] + # Unit square has a half-diagonal of `1/sqrt(2)`, so `pi * r**2` equals... + circle_areas = [np.pi / 2] + squares = SquareCollection( + sizes=circle_areas, offsets=xy, offset_transform=ax.transData) + ax.add_collection(squares, autolim=True) + ax.axis([-1, 1, -1, 1]) + + +def test_picking(): + fig, ax = plt.subplots() + col = ax.scatter([0], [0], [1000], picker=True) + fig.savefig(io.BytesIO(), dpi=fig.dpi) + mouse_event = SimpleNamespace(x=325, y=240) + found, indices = col.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + +def test_quadmesh_contains(): + x = np.arange(4) + X = x[:, None] * x[None, :] + + fig, ax = plt.subplots() + mesh = ax.pcolormesh(X) + fig.draw_without_rendering() + xdata, ydata = 0.5, 0.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + xdata, ydata = 1.5, 1.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [5]) + + +def test_quadmesh_contains_concave(): + # Test a concave polygon, V-like shape + x = [[0, -1], [1, 0]] + y = [[0, 1], [1, -1]] + fig, ax = plt.subplots() + mesh = ax.pcolormesh(x, y, [[0]]) + fig.draw_without_rendering() + # xdata, ydata, expected + points = [(-0.5, 0.25, True), # left wing + (0, 0.25, False), # between the two wings + (0.5, 0.25, True), # right wing + (0, -0.25, True), # main body + ] + for point in points: + xdata, ydata, expected = point + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + found, indices = mesh.contains(mouse_event) + assert found is expected + + +def test_quadmesh_cursor_data(): + x = np.arange(4) + X = x[:, None] * x[None, :] + + fig, ax = plt.subplots() + mesh = ax.pcolormesh(X) + # Empty array data + mesh._A = None + fig.draw_without_rendering() + xdata, ydata = 0.5, 0.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + # Empty collection should return None + assert mesh.get_cursor_data(mouse_event) is None + + # Now test adding the array data, to make sure we do get a value + mesh.set_array(np.ones(X.shape)) + assert_array_equal(mesh.get_cursor_data(mouse_event), [1]) + + +def test_quadmesh_cursor_data_multiple_points(): + x = [1, 2, 1, 2] + fig, ax = plt.subplots() + mesh = ax.pcolormesh(x, x, np.ones((3, 3))) + fig.draw_without_rendering() + xdata, ydata = 1.5, 1.5 + x, y = mesh.get_transform().transform((xdata, ydata)) + mouse_event = SimpleNamespace(xdata=xdata, ydata=ydata, x=x, y=y) + # All quads are covering the same square + assert_array_equal(mesh.get_cursor_data(mouse_event), np.ones(9)) + + +def test_linestyle_single_dashes(): + plt.scatter([0, 1, 2], [0, 1, 2], linestyle=(0., [2., 2.])) + plt.draw() + + +@image_comparison(['size_in_xy.png'], remove_text=True) +def test_size_in_xy(): + fig, ax = plt.subplots() + + widths, heights, angles = (10, 10), 10, 0 + widths = 10, 10 + coords = [(10, 10), (15, 15)] + e = mcollections.EllipseCollection( + widths, heights, angles, units='xy', + offsets=coords, offset_transform=ax.transData) + + ax.add_collection(e) + + ax.set_xlim(0, 30) + ax.set_ylim(0, 30) + + +def test_pandas_indexing(pd): + + # Should not fail break when faced with a + # non-zero indexed series + index = [11, 12, 13] + ec = fc = pd.Series(['red', 'blue', 'green'], index=index) + lw = pd.Series([1, 2, 3], index=index) + ls = pd.Series(['solid', 'dashed', 'dashdot'], index=index) + aa = pd.Series([True, False, True], index=index) + + Collection(edgecolors=ec) + Collection(facecolors=fc) + Collection(linewidths=lw) + Collection(linestyles=ls) + Collection(antialiaseds=aa) + + +@mpl.style.context('default') +def test_lslw_bcast(): + col = mcollections.PathCollection([]) + col.set_linestyles(['-', '-']) + col.set_linewidths([1, 2, 3]) + + assert col.get_linestyles() == [(0, None)] * 6 + assert col.get_linewidths() == [1, 2, 3] * 2 + + col.set_linestyles(['-', '-', '-']) + assert col.get_linestyles() == [(0, None)] * 3 + assert (col.get_linewidths() == [1, 2, 3]).all() + + +def test_set_wrong_linestyle(): + c = Collection() + with pytest.raises(ValueError, match="Do not know how to convert 'fuzzy'"): + c.set_linestyle('fuzzy') + + +@mpl.style.context('default') +def test_capstyle(): + col = mcollections.PathCollection([]) + assert col.get_capstyle() is None + col = mcollections.PathCollection([], capstyle='round') + assert col.get_capstyle() == 'round' + col.set_capstyle('butt') + assert col.get_capstyle() == 'butt' + + +@mpl.style.context('default') +def test_joinstyle(): + col = mcollections.PathCollection([]) + assert col.get_joinstyle() is None + col = mcollections.PathCollection([], joinstyle='round') + assert col.get_joinstyle() == 'round' + col.set_joinstyle('miter') + assert col.get_joinstyle() == 'miter' + + +@image_comparison(['cap_and_joinstyle.png']) +def test_cap_and_joinstyle_image(): + fig, ax = plt.subplots() + ax.set_xlim([-0.5, 1.5]) + ax.set_ylim([-0.5, 2.5]) + + x = np.array([0.0, 1.0, 0.5]) + ys = np.array([[0.0], [0.5], [1.0]]) + np.array([[0.0, 0.0, 1.0]]) + + segs = np.zeros((3, 3, 2)) + segs[:, :, 0] = x + segs[:, :, 1] = ys + line_segments = LineCollection(segs, linewidth=[10, 15, 20]) + line_segments.set_capstyle("round") + line_segments.set_joinstyle("miter") + + ax.add_collection(line_segments) + ax.set_title('Line collection with customized caps and joinstyle') + + +@image_comparison(['scatter_post_alpha.png'], + remove_text=True, style='default') +def test_scatter_post_alpha(): + fig, ax = plt.subplots() + sc = ax.scatter(range(5), range(5), c=range(5)) + sc.set_alpha(.1) + + +def test_scatter_alpha_array(): + x = np.arange(5) + alpha = x / 5 + # With colormapping. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, c=x, alpha=alpha) + sc1 = ax1.scatter(x, x, c=x) + sc1.set_alpha(alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + # Without colormapping. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm'], alpha=alpha) + sc1 = ax1.scatter(x, x, color='r', alpha=alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + # Without colormapping, and set alpha afterward. + fig, (ax0, ax1) = plt.subplots(2) + sc0 = ax0.scatter(x, x, color=['r', 'g', 'b', 'c', 'm']) + sc0.set_alpha(alpha) + sc1 = ax1.scatter(x, x, color='r') + sc1.set_alpha(alpha) + plt.draw() + assert_array_equal(sc0.get_facecolors()[:, -1], alpha) + assert_array_equal(sc1.get_facecolors()[:, -1], alpha) + + +def test_pathcollection_legend_elements(): + np.random.seed(19680801) + x, y = np.random.rand(2, 10) + y = np.random.rand(10) + c = np.random.randint(0, 5, size=10) + s = np.random.randint(10, 300, size=10) + + fig, ax = plt.subplots() + sc = ax.scatter(x, y, c=c, s=s, cmap="jet", marker="o", linewidths=0) + + h, l = sc.legend_elements(fmt="{x:g}") + assert len(h) == 5 + assert l == ["0", "1", "2", "3", "4"] + colors = np.array([line.get_color() for line in h]) + colors2 = sc.cmap(np.arange(5)/4) + assert_array_equal(colors, colors2) + l1 = ax.legend(h, l, loc=1) + + h2, lab2 = sc.legend_elements(num=9) + assert len(h2) == 9 + l2 = ax.legend(h2, lab2, loc=2) + + h, l = sc.legend_elements(prop="sizes", alpha=0.5, color="red") + assert all(line.get_alpha() == 0.5 for line in h) + assert all(line.get_markerfacecolor() == "red" for line in h) + l3 = ax.legend(h, l, loc=4) + + h, l = sc.legend_elements(prop="sizes", num=4, fmt="{x:.2f}", + func=lambda x: 2*x) + actsizes = [line.get_markersize() for line in h] + labeledsizes = np.sqrt(np.array(l, float) / 2) + assert_array_almost_equal(actsizes, labeledsizes) + l4 = ax.legend(h, l, loc=3) + + loc = mpl.ticker.MaxNLocator(nbins=9, min_n_ticks=9-1, + steps=[1, 2, 2.5, 3, 5, 6, 8, 10]) + h5, lab5 = sc.legend_elements(num=loc) + assert len(h2) == len(h5) + + levels = [-1, 0, 55.4, 260] + h6, lab6 = sc.legend_elements(num=levels, prop="sizes", fmt="{x:g}") + assert [float(l) for l in lab6] == levels[2:] + + for l in [l1, l2, l3, l4]: + ax.add_artist(l) + + fig.canvas.draw() + + +def test_EventCollection_nosort(): + # Check that EventCollection doesn't modify input in place + arr = np.array([3, 2, 1, 10]) + coll = EventCollection(arr) + np.testing.assert_array_equal(arr, np.array([3, 2, 1, 10])) + + +def test_collection_set_verts_array(): + verts = np.arange(80, dtype=np.double).reshape(10, 4, 2) + col_arr = PolyCollection(verts) + col_list = PolyCollection(list(verts)) + assert len(col_arr._paths) == len(col_list._paths) + for ap, lp in zip(col_arr._paths, col_list._paths): + assert np.array_equal(ap._vertices, lp._vertices) + assert np.array_equal(ap._codes, lp._codes) + + verts_tuple = np.empty(10, dtype=object) + verts_tuple[:] = [tuple(tuple(y) for y in x) for x in verts] + col_arr_tuple = PolyCollection(verts_tuple) + assert len(col_arr._paths) == len(col_arr_tuple._paths) + for ap, atp in zip(col_arr._paths, col_arr_tuple._paths): + assert np.array_equal(ap._vertices, atp._vertices) + assert np.array_equal(ap._codes, atp._codes) + + +def test_collection_set_array(): + vals = [*range(10)] + + # Test set_array with list + c = Collection() + c.set_array(vals) + + # Test set_array with wrong dtype + with pytest.raises(TypeError, match="^Image data of dtype"): + c.set_array("wrong_input") + + # Test if array kwarg is copied + vals[5] = 45 + assert np.not_equal(vals, c.get_array()).any() + + +def test_blended_collection_autolim(): + a = [1, 2, 4] + height = .2 + + xy_pairs = np.column_stack([np.repeat(a, 2), np.tile([0, height], len(a))]) + line_segs = xy_pairs.reshape([len(a), 2, 2]) + + f, ax = plt.subplots() + trans = mtransforms.blended_transform_factory(ax.transData, ax.transAxes) + ax.add_collection(LineCollection(line_segs, transform=trans)) + ax.autoscale_view(scalex=True, scaley=False) + np.testing.assert_allclose(ax.get_xlim(), [1., 4.]) + + +def test_singleton_autolim(): + fig, ax = plt.subplots() + ax.scatter(0, 0) + np.testing.assert_allclose(ax.get_ylim(), [-0.06, 0.06]) + np.testing.assert_allclose(ax.get_xlim(), [-0.06, 0.06]) + + +@pytest.mark.parametrize("transform, expected", [ + ("transData", (-0.5, 3.5)), + ("transAxes", (2.8, 3.2)), +]) +def test_autolim_with_zeros(transform, expected): + # 1) Test that a scatter at (0, 0) data coordinates contributes to + # autoscaling even though any(offsets) would be False in that situation. + # 2) Test that specifying transAxes for the transform does not contribute + # to the autoscaling. + fig, ax = plt.subplots() + ax.scatter(0, 0, transform=getattr(ax, transform)) + ax.scatter(3, 3) + np.testing.assert_allclose(ax.get_ylim(), expected) + np.testing.assert_allclose(ax.get_xlim(), expected) + + +def test_quadmesh_set_array_validation(pcfunc): + x = np.arange(11) + y = np.arange(8) + z = np.random.random((7, 10)) + fig, ax = plt.subplots() + coll = getattr(ax, pcfunc)(x, y, z) + + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (10, 7)")): + coll.set_array(z.reshape(10, 7)) + + z = np.arange(54).reshape((6, 9)) + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (6, 9)")): + coll.set_array(z) + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (54,)")): + coll.set_array(z.ravel()) + + # RGB(A) tests + z = np.ones((9, 6, 3)) # RGB with wrong X/Y dims + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 3)")): + coll.set_array(z) + + z = np.ones((9, 6, 4)) # RGBA with wrong X/Y dims + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (9, 6, 4)")): + coll.set_array(z) + + z = np.ones((7, 10, 2)) # Right X/Y dims, bad 3rd dim + with pytest.raises(ValueError, match=re.escape( + "For X (11) and Y (8) with flat shading, A should have shape " + "(7, 10, 3) or (7, 10, 4) or (7, 10) or (70,), not (7, 10, 2)")): + coll.set_array(z) + + x = np.arange(10) + y = np.arange(7) + z = np.random.random((7, 10)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, z, shading='gouraud') + + +def test_polyquadmesh_masked_vertices_array(): + xx, yy = np.meshgrid([0, 1, 2], [0, 1, 2, 3]) + # 2 x 3 mesh data + zz = (xx*yy)[:-1, :-1] + quadmesh = plt.pcolormesh(xx, yy, zz) + quadmesh.update_scalarmappable() + quadmesh_fc = quadmesh.get_facecolor()[1:, :] + # Mask the origin vertex in x + xx = np.ma.masked_where((xx == 0) & (yy == 0), xx) + polymesh = plt.pcolor(xx, yy, zz) + polymesh.update_scalarmappable() + # One cell should be left out + assert len(polymesh.get_paths()) == 5 + # Poly version should have the same facecolors as the end of the quadmesh + assert_array_equal(quadmesh_fc, polymesh.get_facecolor()) + + # Mask the origin vertex in y + yy = np.ma.masked_where((xx == 0) & (yy == 0), yy) + polymesh = plt.pcolor(xx, yy, zz) + polymesh.update_scalarmappable() + # One cell should be left out + assert len(polymesh.get_paths()) == 5 + # Poly version should have the same facecolors as the end of the quadmesh + assert_array_equal(quadmesh_fc, polymesh.get_facecolor()) + + # Mask the origin cell data + zz = np.ma.masked_where((xx[:-1, :-1] == 0) & (yy[:-1, :-1] == 0), zz) + polymesh = plt.pcolor(zz) + polymesh.update_scalarmappable() + # One cell should be left out + assert len(polymesh.get_paths()) == 5 + # Poly version should have the same facecolors as the end of the quadmesh + assert_array_equal(quadmesh_fc, polymesh.get_facecolor()) + + # Setting array with 1D compressed values is deprecated + with pytest.warns(mpl.MatplotlibDeprecationWarning, + match="Setting a PolyQuadMesh"): + polymesh.set_array(np.ones(5)) + + # We should also be able to call set_array with a new mask and get + # updated polys + # Remove mask, should add all polys back + zz = np.arange(6).reshape((3, 2)) + polymesh.set_array(zz) + polymesh.update_scalarmappable() + assert len(polymesh.get_paths()) == 6 + # Add mask should remove polys + zz = np.ma.masked_less(zz, 2) + polymesh.set_array(zz) + polymesh.update_scalarmappable() + assert len(polymesh.get_paths()) == 4 + + +def test_quadmesh_get_coordinates(pcfunc): + x = [0, 1, 2] + y = [2, 4, 6] + z = np.ones(shape=(2, 2)) + xx, yy = np.meshgrid(x, y) + coll = getattr(plt, pcfunc)(xx, yy, z) + + # shape (3, 3, 2) + coords = np.stack([xx.T, yy.T]).T + assert_array_equal(coll.get_coordinates(), coords) + + +def test_quadmesh_set_array(): + x = np.arange(4) + y = np.arange(4) + z = np.arange(9).reshape((3, 3)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, np.ones(z.shape)) + # Test that the collection is able to update with a 2d array + coll.set_array(z) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), z) + + # Check that pre-flattened arrays work too + coll.set_array(np.ones(9)) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), np.ones(9)) + + z = np.arange(16).reshape((4, 4)) + fig, ax = plt.subplots() + coll = ax.pcolormesh(x, y, np.ones(z.shape), shading='gouraud') + # Test that the collection is able to update with a 2d array + coll.set_array(z) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), z) + + # Check that pre-flattened arrays work too + coll.set_array(np.ones(16)) + fig.canvas.draw() + assert np.array_equal(coll.get_array(), np.ones(16)) + + +def test_quadmesh_vmin_vmax(pcfunc): + # test when vmin/vmax on the norm changes, the quadmesh gets updated + fig, ax = plt.subplots() + cmap = mpl.colormaps['plasma'] + norm = mpl.colors.Normalize(vmin=0, vmax=1) + coll = getattr(ax, pcfunc)([[1]], cmap=cmap, norm=norm) + fig.canvas.draw() + assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1))) + + # Change the vmin/vmax of the norm so that the color is from + # the bottom of the colormap now + norm.vmin, norm.vmax = 1, 2 + fig.canvas.draw() + assert np.array_equal(coll.get_facecolors()[0, :], cmap(norm(1))) + + +def test_quadmesh_alpha_array(pcfunc): + x = np.arange(4) + y = np.arange(4) + z = np.arange(9).reshape((3, 3)) + alpha = z / z.max() + alpha_flat = alpha.ravel() + # Provide 2-D alpha: + fig, (ax0, ax1) = plt.subplots(2) + coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha) + coll2 = getattr(ax0, pcfunc)(x, y, z) + coll2.set_alpha(alpha) + plt.draw() + assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat) + assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat) + # Or provide 1-D alpha: + fig, (ax0, ax1) = plt.subplots(2) + coll1 = getattr(ax0, pcfunc)(x, y, z, alpha=alpha) + coll2 = getattr(ax1, pcfunc)(x, y, z) + coll2.set_alpha(alpha) + plt.draw() + assert_array_equal(coll1.get_facecolors()[:, -1], alpha_flat) + assert_array_equal(coll2.get_facecolors()[:, -1], alpha_flat) + + +def test_alpha_validation(pcfunc): + # Most of the relevant testing is in test_artist and test_colors. + fig, ax = plt.subplots() + pc = getattr(ax, pcfunc)(np.arange(12).reshape((3, 4))) + with pytest.raises(ValueError, match="^Data array shape"): + pc.set_alpha([0.5, 0.6]) + pc.update_scalarmappable() + + +def test_legend_inverse_size_label_relationship(): + """ + Ensure legend markers scale appropriately when label and size are + inversely related. + Here label = 5 / size + """ + + np.random.seed(19680801) + X = np.random.random(50) + Y = np.random.random(50) + C = 1 - np.random.random(50) + S = 5 / C + + legend_sizes = [0.2, 0.4, 0.6, 0.8] + fig, ax = plt.subplots() + sc = ax.scatter(X, Y, s=S) + handles, labels = sc.legend_elements( + prop='sizes', num=legend_sizes, func=lambda s: 5 / s + ) + + # Convert markersize scale to 's' scale + handle_sizes = [x.get_markersize() for x in handles] + handle_sizes = [5 / x**2 for x in handle_sizes] + + assert_array_almost_equal(handle_sizes, legend_sizes, decimal=1) + + +@mpl.style.context('default') +def test_color_logic(pcfunc): + pcfunc = getattr(plt, pcfunc) + z = np.arange(12).reshape(3, 4) + # Explicitly set an edgecolor. + pc = pcfunc(z, edgecolors='red', facecolors='none') + pc.update_scalarmappable() # This is called in draw(). + # Define 2 reference "colors" here for multiple use. + face_default = mcolors.to_rgba_array(pc._get_default_facecolor()) + mapped = pc.get_cmap()(pc.norm(z.ravel())) + # GitHub issue #1302: + assert mcolors.same_color(pc.get_edgecolor(), 'red') + # Check setting attributes after initialization: + pc = pcfunc(z) + pc.set_facecolor('none') + pc.set_edgecolor('red') + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), 'none') + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + pc.set_alpha(0.5) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 0.5]]) + pc.set_alpha(None) # restore default alpha + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Reset edgecolor to default. + pc.set_edgecolor(None) + pc.update_scalarmappable() + assert np.array_equal(pc.get_edgecolor(), mapped) + pc.set_facecolor(None) # restore default for facecolor + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), 'none') + # Turn off colormapping entirely: + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_edgecolor(), 'none') + assert mcolors.same_color(pc.get_facecolor(), face_default) # not mapped + # Turn it back on by restoring the array (must be 1D!): + pc.set_array(z) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), 'none') + # Give color via tuple rather than string. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=(0, 1, 0)) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Provide an RGB array; mapping overrides it. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 3))) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Turn off the mapping. + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 3))) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # And an RGBA array. + pc = pcfunc(z, edgecolors=(1, 0, 0), facecolors=np.ones((12, 4))) + pc.update_scalarmappable() + assert np.array_equal(pc.get_facecolor(), mapped) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + # Turn off the mapping. + pc.set_array(None) + pc.update_scalarmappable() + assert mcolors.same_color(pc.get_facecolor(), np.ones((12, 4))) + assert mcolors.same_color(pc.get_edgecolor(), [[1, 0, 0, 1]]) + + +def test_LineCollection_args(): + lc = LineCollection(None, linewidth=2.2, edgecolor='r', + zorder=3, facecolors=[0, 1, 0, 1]) + assert lc.get_linewidth()[0] == 2.2 + assert mcolors.same_color(lc.get_edgecolor(), 'r') + assert lc.get_zorder() == 3 + assert mcolors.same_color(lc.get_facecolor(), [[0, 1, 0, 1]]) + # To avoid breaking mplot3d, LineCollection internally sets the facecolor + # kwarg if it has not been specified. Hence we need the following test + # for LineCollection._set_default(). + lc = LineCollection(None, facecolor=None) + assert mcolors.same_color(lc.get_facecolor(), 'none') + + +def test_array_dimensions(pcfunc): + # Make sure we can set the 1D, 2D, and 3D array shapes + z = np.arange(12).reshape(3, 4) + pc = getattr(plt, pcfunc)(z) + # 1D + pc.set_array(z.ravel()) + pc.update_scalarmappable() + # 2D + pc.set_array(z) + pc.update_scalarmappable() + # 3D RGB is OK as well + z = np.arange(36, dtype=np.uint8).reshape(3, 4, 3) + pc.set_array(z) + pc.update_scalarmappable() + + +def test_get_segments(): + segments = np.tile(np.linspace(0, 1, 256), (2, 1)).T + lc = LineCollection([segments]) + + readback, = lc.get_segments() + # these should comeback un-changed! + assert np.all(segments == readback) + + +def test_set_offsets_late(): + identity = mtransforms.IdentityTransform() + sizes = [2] + + null = mcollections.CircleCollection(sizes=sizes) + + init = mcollections.CircleCollection(sizes=sizes, offsets=(10, 10)) + + late = mcollections.CircleCollection(sizes=sizes) + late.set_offsets((10, 10)) + + # Bbox.__eq__ doesn't compare bounds + null_bounds = null.get_datalim(identity).bounds + init_bounds = init.get_datalim(identity).bounds + late_bounds = late.get_datalim(identity).bounds + + # offsets and transform are applied when set after initialization + assert null_bounds != init_bounds + assert init_bounds == late_bounds + + +def test_set_offset_transform(): + skew = mtransforms.Affine2D().skew(2, 2) + init = mcollections.Collection(offset_transform=skew) + + late = mcollections.Collection() + late.set_offset_transform(skew) + + assert skew == init.get_offset_transform() == late.get_offset_transform() + + +def test_set_offset_units(): + # passing the offsets in initially (i.e. via scatter) + # should yield the same results as `set_offsets` + x = np.linspace(0, 10, 5) + y = np.sin(x) + d = x * np.timedelta64(24, 'h') + np.datetime64('2021-11-29') + + sc = plt.scatter(d, y) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(d, y))) + np.testing.assert_allclose(off0, sc.get_offsets()) + + # try the other way around + fig, ax = plt.subplots() + sc = ax.scatter(y, d) + off0 = sc.get_offsets() + sc.set_offsets(list(zip(y, d))) + np.testing.assert_allclose(off0, sc.get_offsets()) + + +@image_comparison(baseline_images=["test_check_masked_offsets"], + extensions=["png"], remove_text=True, style="mpl20") +def test_check_masked_offsets(): + # Check if masked data is respected by scatter + # Ref: Issue #24545 + unmasked_x = [ + datetime(2022, 12, 15, 4, 49, 52), + datetime(2022, 12, 15, 4, 49, 53), + datetime(2022, 12, 15, 4, 49, 54), + datetime(2022, 12, 15, 4, 49, 55), + datetime(2022, 12, 15, 4, 49, 56), + ] + + masked_y = np.ma.array([1, 2, 3, 4, 5], mask=[0, 1, 1, 0, 0]) + + fig, ax = plt.subplots() + ax.scatter(unmasked_x, masked_y) + + +@check_figures_equal(extensions=["png"]) +def test_masked_set_offsets(fig_ref, fig_test): + x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0]) + y = np.arange(1, 6) + + ax_test = fig_test.add_subplot() + scat = ax_test.scatter(x, y) + scat.set_offsets(np.ma.column_stack([x, y])) + ax_test.set_xticks([]) + ax_test.set_yticks([]) + + ax_ref = fig_ref.add_subplot() + ax_ref.scatter([1, 2, 5], [1, 2, 5]) + ax_ref.set_xticks([]) + ax_ref.set_yticks([]) + + +def test_check_offsets_dtype(): + # Check that setting offsets doesn't change dtype + x = np.ma.array([1, 2, 3, 4, 5], mask=[0, 0, 1, 1, 0]) + y = np.arange(1, 6) + + fig, ax = plt.subplots() + scat = ax.scatter(x, y) + masked_offsets = np.ma.column_stack([x, y]) + scat.set_offsets(masked_offsets) + assert isinstance(scat.get_offsets(), type(masked_offsets)) + + unmasked_offsets = np.column_stack([x, y]) + scat.set_offsets(unmasked_offsets) + assert isinstance(scat.get_offsets(), type(unmasked_offsets)) + + +@pytest.mark.parametrize('gapcolor', ['orange', ['r', 'k']]) +@check_figures_equal(extensions=['png']) +@mpl.rc_context({'lines.linewidth': 20}) +def test_striped_lines(fig_test, fig_ref, gapcolor): + ax_test = fig_test.add_subplot(111) + ax_ref = fig_ref.add_subplot(111) + + for ax in [ax_test, ax_ref]: + ax.set_xlim(0, 6) + ax.set_ylim(0, 1) + + x = range(1, 6) + linestyles = [':', '-', '--'] + + ax_test.vlines(x, 0, 1, linestyle=linestyles, gapcolor=gapcolor, alpha=0.5) + + if isinstance(gapcolor, str): + gapcolor = [gapcolor] + + for x, gcol, ls in zip(x, itertools.cycle(gapcolor), + itertools.cycle(linestyles)): + ax_ref.axvline(x, 0, 1, linestyle=ls, gapcolor=gcol, alpha=0.5) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py new file mode 100644 index 0000000000000000000000000000000000000000..4fa261619490ba73cb08bf953f3e385c2d99fc5c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_cycles.py @@ -0,0 +1,175 @@ +import contextlib +from io import StringIO + +import matplotlib as mpl +import matplotlib.pyplot as plt +import numpy as np +import pytest + +from cycler import cycler + + +def test_colorcycle_basic(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('color', ['r', 'g', 'y'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r'] + + +def test_marker_cycle(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + + cycler('marker', ['.', '*', 'x'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r'] + assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.'] + + +def test_valid_marker_cycles(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler(marker=[1, "+", ".", 4])) + + +def test_marker_cycle_kwargs_arrays_iterators(): + fig, ax = plt.subplots() + ax.set_prop_cycle(c=np.array(['r', 'g', 'y']), + marker=iter(['.', '*', 'x'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_color() for l in ax.lines] == ['r', 'g', 'y', 'r'] + assert [l.get_marker() for l in ax.lines] == ['.', '*', 'x', '.'] + + +def test_linestylecycle_basic(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('ls', ['-', '--', ':'])) + for _ in range(4): + ax.plot(range(10), range(10)) + assert [l.get_linestyle() for l in ax.lines] == ['-', '--', ':', '-'] + + +def test_fillcycle_basic(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('c', ['r', 'g', 'y']) + + cycler('hatch', ['xx', 'O', '|-']) + + cycler('linestyle', ['-', '--', ':'])) + for _ in range(4): + ax.fill(range(10), range(10)) + assert ([p.get_facecolor() for p in ax.patches] + == [mpl.colors.to_rgba(c) for c in ['r', 'g', 'y', 'r']]) + assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', '|-', 'xx'] + assert [p.get_linestyle() for p in ax.patches] == ['-', '--', ':', '-'] + + +def test_fillcycle_ignore(): + fig, ax = plt.subplots() + ax.set_prop_cycle(cycler('color', ['r', 'g', 'y']) + + cycler('hatch', ['xx', 'O', '|-']) + + cycler('marker', ['.', '*', 'D'])) + t = range(10) + # Should not advance the cycler, even though there is an + # unspecified property in the cycler "marker". + # "marker" is not a Polygon property, and should be ignored. + ax.fill(t, t, 'r', hatch='xx') + # Allow the cycler to advance, but specify some properties + ax.fill(t, t, hatch='O') + ax.fill(t, t) + ax.fill(t, t) + assert ([p.get_facecolor() for p in ax.patches] + == [mpl.colors.to_rgba(c) for c in ['r', 'r', 'g', 'y']]) + assert [p.get_hatch() for p in ax.patches] == ['xx', 'O', 'O', '|-'] + + +def test_property_collision_plot(): + fig, ax = plt.subplots() + ax.set_prop_cycle('linewidth', [2, 4]) + t = range(10) + for c in range(1, 4): + ax.plot(t, t, lw=0.1) + ax.plot(t, t) + ax.plot(t, t) + assert [l.get_linewidth() for l in ax.lines] == [0.1, 0.1, 0.1, 2, 4] + + +def test_property_collision_fill(): + fig, ax = plt.subplots() + ax.set_prop_cycle(linewidth=[2, 3, 4, 5, 6], facecolor='bgcmy') + t = range(10) + for c in range(1, 4): + ax.fill(t, t, lw=0.1) + ax.fill(t, t) + ax.fill(t, t) + assert ([p.get_facecolor() for p in ax.patches] + == [mpl.colors.to_rgba(c) for c in 'bgcmy']) + assert [p.get_linewidth() for p in ax.patches] == [0.1, 0.1, 0.1, 5, 6] + + +def test_valid_input_forms(): + fig, ax = plt.subplots() + # These should not raise an error. + ax.set_prop_cycle(None) + ax.set_prop_cycle(cycler('linewidth', [1, 2])) + ax.set_prop_cycle('color', 'rgywkbcm') + ax.set_prop_cycle('lw', (1, 2)) + ax.set_prop_cycle('linewidth', [1, 2]) + ax.set_prop_cycle('linewidth', iter([1, 2])) + ax.set_prop_cycle('linewidth', np.array([1, 2])) + ax.set_prop_cycle('color', np.array([[1, 0, 0], + [0, 1, 0], + [0, 0, 1]])) + ax.set_prop_cycle('dashes', [[], [13, 2], [8, 3, 1, 3]]) + ax.set_prop_cycle(lw=[1, 2], color=['k', 'w'], ls=['-', '--']) + ax.set_prop_cycle(lw=np.array([1, 2]), + color=np.array(['k', 'w']), + ls=np.array(['-', '--'])) + + +def test_cycle_reset(): + fig, ax = plt.subplots() + prop0 = StringIO() + prop1 = StringIO() + prop2 = StringIO() + + with contextlib.redirect_stdout(prop0): + plt.getp(ax.plot([1, 2], label="label")[0]) + + ax.set_prop_cycle(linewidth=[10, 9, 4]) + with contextlib.redirect_stdout(prop1): + plt.getp(ax.plot([1, 2], label="label")[0]) + assert prop1.getvalue() != prop0.getvalue() + + ax.set_prop_cycle(None) + with contextlib.redirect_stdout(prop2): + plt.getp(ax.plot([1, 2], label="label")[0]) + assert prop2.getvalue() == prop0.getvalue() + + +def test_invalid_input_forms(): + fig, ax = plt.subplots() + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(1) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle([1, 2]) + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('color', 'fish') + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('linewidth', 1) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('linewidth', {1, 2}) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(linewidth=1, color='r') + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle('foobar', [1, 2]) + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(foobar=[1, 2]) + + with pytest.raises((TypeError, ValueError)): + ax.set_prop_cycle(cycler(foobar=[1, 2])) + with pytest.raises(ValueError): + ax.set_prop_cycle(cycler(color='rgb', c='cmy')) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py new file mode 100644 index 0000000000000000000000000000000000000000..7b7ff151be1847671e2fe3be0759dedb31b863d4 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_dviread.py @@ -0,0 +1,77 @@ +import json +from pathlib import Path +import shutil + +import matplotlib.dviread as dr +import pytest + + +def test_PsfontsMap(monkeypatch): + monkeypatch.setattr(dr, 'find_tex_file', lambda x: x.decode()) + + filename = str(Path(__file__).parent / 'baseline_images/dviread/test.map') + fontmap = dr.PsfontsMap(filename) + # Check all properties of a few fonts + for n in [1, 2, 3, 4, 5]: + key = b'TeXfont%d' % n + entry = fontmap[key] + assert entry.texname == key + assert entry.psname == b'PSfont%d' % n + if n not in [3, 5]: + assert entry.encoding == 'font%d.enc' % n + elif n == 3: + assert entry.encoding == 'enc3.foo' + # We don't care about the encoding of TeXfont5, which specifies + # multiple encodings. + if n not in [1, 5]: + assert entry.filename == 'font%d.pfa' % n + else: + assert entry.filename == 'font%d.pfb' % n + if n == 4: + assert entry.effects == {'slant': -0.1, 'extend': 1.2} + else: + assert entry.effects == {} + # Some special cases + entry = fontmap[b'TeXfont6'] + assert entry.filename is None + assert entry.encoding is None + entry = fontmap[b'TeXfont7'] + assert entry.filename is None + assert entry.encoding == 'font7.enc' + entry = fontmap[b'TeXfont8'] + assert entry.filename == 'font8.pfb' + assert entry.encoding is None + entry = fontmap[b'TeXfont9'] + assert entry.psname == b'TeXfont9' + assert entry.filename == '/absolute/font9.pfb' + # First of duplicates only. + entry = fontmap[b'TeXfontA'] + assert entry.psname == b'PSfontA1' + # Slant/Extend only works for T1 fonts. + entry = fontmap[b'TeXfontB'] + assert entry.psname == b'PSfontB6' + # Subsetted TrueType must have encoding. + entry = fontmap[b'TeXfontC'] + assert entry.psname == b'PSfontC3' + # Missing font + with pytest.raises(LookupError, match='no-such-font'): + fontmap[b'no-such-font'] + with pytest.raises(LookupError, match='%'): + fontmap[b'%'] + + +@pytest.mark.skipif(shutil.which("kpsewhich") is None, + reason="kpsewhich is not available") +def test_dviread(): + dirpath = Path(__file__).parent / 'baseline_images/dviread' + with (dirpath / 'test.json').open() as f: + correct = json.load(f) + with dr.Dvi(str(dirpath / 'test.dvi'), None) as dvi: + data = [{'text': [[t.x, t.y, + chr(t.glyph), + t.font.texname.decode('ascii'), + round(t.font.size, 2)] + for t in page.text], + 'boxes': [[b.x, b.y, b.height, b.width] for b in page.boxes]} + for page in dvi] + assert data == correct diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_figure.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_figure.py new file mode 100644 index 0000000000000000000000000000000000000000..6e6daa77062df1739d2ee85856c2d9c0c5dcc5ad --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_figure.py @@ -0,0 +1,1759 @@ +import copy +from datetime import datetime +import io +import pickle +import platform +from threading import Timer +from types import SimpleNamespace +import warnings + +import numpy as np +import pytest +from PIL import Image + +import matplotlib as mpl +from matplotlib import gridspec +from matplotlib.testing.decorators import image_comparison, check_figures_equal +from matplotlib.axes import Axes +from matplotlib.backend_bases import KeyEvent, MouseEvent +from matplotlib.figure import Figure, FigureBase +from matplotlib.layout_engine import (ConstrainedLayoutEngine, + TightLayoutEngine, + PlaceHolderLayoutEngine) +from matplotlib.ticker import AutoMinorLocator, FixedFormatter, ScalarFormatter +import matplotlib.pyplot as plt +import matplotlib.dates as mdates + + +@image_comparison(['figure_align_labels'], extensions=['png', 'svg'], + tol=0 if platform.machine() == 'x86_64' else 0.01) +def test_align_labels(): + fig = plt.figure(layout='tight') + gs = gridspec.GridSpec(3, 3) + + ax = fig.add_subplot(gs[0, :2]) + ax.plot(np.arange(0, 1e6, 1000)) + ax.set_ylabel('Ylabel0 0') + ax = fig.add_subplot(gs[0, -1]) + ax.plot(np.arange(0, 1e4, 100)) + + for i in range(3): + ax = fig.add_subplot(gs[1, i]) + ax.set_ylabel('YLabel1 %d' % i) + ax.set_xlabel('XLabel1 %d' % i) + if i in [0, 2]: + ax.xaxis.set_label_position("top") + ax.xaxis.tick_top() + if i == 0: + for tick in ax.get_xticklabels(): + tick.set_rotation(90) + if i == 2: + ax.yaxis.set_label_position("right") + ax.yaxis.tick_right() + + for i in range(3): + ax = fig.add_subplot(gs[2, i]) + ax.set_xlabel(f'XLabel2 {i}') + ax.set_ylabel(f'YLabel2 {i}') + + if i == 2: + ax.plot(np.arange(0, 1e4, 10)) + ax.yaxis.set_label_position("right") + ax.yaxis.tick_right() + for tick in ax.get_xticklabels(): + tick.set_rotation(90) + + fig.align_labels() + + +@image_comparison(['figure_align_titles_tight.png', + 'figure_align_titles_constrained.png'], + tol=0 if platform.machine() == 'x86_64' else 0.022, + style='mpl20') +def test_align_titles(): + for layout in ['tight', 'constrained']: + fig, axs = plt.subplots(1, 2, layout=layout, width_ratios=[2, 1]) + + ax = axs[0] + ax.plot(np.arange(0, 1e6, 1000)) + ax.set_title('Title0 left', loc='left') + ax.set_title('Title0 center', loc='center') + ax.set_title('Title0 right', loc='right') + + ax = axs[1] + ax.plot(np.arange(0, 1e4, 100)) + ax.set_title('Title1') + ax.set_xlabel('Xlabel0') + ax.xaxis.set_label_position("top") + ax.xaxis.tick_top() + for tick in ax.get_xticklabels(): + tick.set_rotation(90) + + fig.align_titles() + + +def test_align_labels_stray_axes(): + fig, axs = plt.subplots(2, 2) + for nn, ax in enumerate(axs.flat): + ax.set_xlabel('Boo') + ax.set_xlabel('Who') + ax.plot(np.arange(4)**nn, np.arange(4)**nn) + fig.align_ylabels() + fig.align_xlabels() + fig.draw_without_rendering() + xn = np.zeros(4) + yn = np.zeros(4) + for nn, ax in enumerate(axs.flat): + yn[nn] = ax.xaxis.label.get_position()[1] + xn[nn] = ax.yaxis.label.get_position()[0] + np.testing.assert_allclose(xn[:2], xn[2:]) + np.testing.assert_allclose(yn[::2], yn[1::2]) + + fig, axs = plt.subplots(2, 2, constrained_layout=True) + for nn, ax in enumerate(axs.flat): + ax.set_xlabel('Boo') + ax.set_xlabel('Who') + pc = ax.pcolormesh(np.random.randn(10, 10)) + fig.colorbar(pc, ax=ax) + fig.align_ylabels() + fig.align_xlabels() + fig.draw_without_rendering() + xn = np.zeros(4) + yn = np.zeros(4) + for nn, ax in enumerate(axs.flat): + yn[nn] = ax.xaxis.label.get_position()[1] + xn[nn] = ax.yaxis.label.get_position()[0] + np.testing.assert_allclose(xn[:2], xn[2:]) + np.testing.assert_allclose(yn[::2], yn[1::2]) + + +def test_figure_label(): + # pyplot figure creation, selection, and closing with label/number/instance + plt.close('all') + fig_today = plt.figure('today') + plt.figure(3) + plt.figure('tomorrow') + plt.figure() + plt.figure(0) + plt.figure(1) + plt.figure(3) + assert plt.get_fignums() == [0, 1, 3, 4, 5] + assert plt.get_figlabels() == ['', 'today', '', 'tomorrow', ''] + plt.close(10) + plt.close() + plt.close(5) + plt.close('tomorrow') + assert plt.get_fignums() == [0, 1] + assert plt.get_figlabels() == ['', 'today'] + plt.figure(fig_today) + assert plt.gcf() == fig_today + with pytest.raises(ValueError): + plt.figure(Figure()) + + +def test_fignum_exists(): + # pyplot figure creation, selection and closing with fignum_exists + plt.figure('one') + plt.figure(2) + plt.figure('three') + plt.figure() + assert plt.fignum_exists('one') + assert plt.fignum_exists(2) + assert plt.fignum_exists('three') + assert plt.fignum_exists(4) + plt.close('one') + plt.close(4) + assert not plt.fignum_exists('one') + assert not plt.fignum_exists(4) + + +def test_clf_keyword(): + # test if existing figure is cleared with figure() and subplots() + text1 = 'A fancy plot' + text2 = 'Really fancy!' + + fig0 = plt.figure(num=1) + fig0.suptitle(text1) + assert [t.get_text() for t in fig0.texts] == [text1] + + fig1 = plt.figure(num=1, clear=False) + fig1.text(0.5, 0.5, text2) + assert fig0 is fig1 + assert [t.get_text() for t in fig1.texts] == [text1, text2] + + fig2, ax2 = plt.subplots(2, 1, num=1, clear=True) + assert fig0 is fig2 + assert [t.get_text() for t in fig2.texts] == [] + + +@image_comparison(['figure_today'], + tol=0.015 if platform.machine() == 'arm64' else 0) +def test_figure(): + # named figure support + fig = plt.figure('today') + ax = fig.add_subplot() + ax.set_title(fig.get_label()) + ax.plot(np.arange(5)) + # plot red line in a different figure. + plt.figure('tomorrow') + plt.plot([0, 1], [1, 0], 'r') + # Return to the original; make sure the red line is not there. + plt.figure('today') + plt.close('tomorrow') + + +@image_comparison(['figure_legend']) +def test_figure_legend(): + fig, axs = plt.subplots(2) + axs[0].plot([0, 1], [1, 0], label='x', color='g') + axs[0].plot([0, 1], [0, 1], label='y', color='r') + axs[0].plot([0, 1], [0.5, 0.5], label='y', color='k') + + axs[1].plot([0, 1], [1, 0], label='_y', color='r') + axs[1].plot([0, 1], [0, 1], label='z', color='b') + fig.legend() + + +def test_gca(): + fig = plt.figure() + + # test that gca() picks up Axes created via add_axes() + ax0 = fig.add_axes([0, 0, 1, 1]) + assert fig.gca() is ax0 + + # test that gca() picks up Axes created via add_subplot() + ax1 = fig.add_subplot(111) + assert fig.gca() is ax1 + + # add_axes on an existing Axes should not change stored order, but will + # make it current. + fig.add_axes(ax0) + assert fig.axes == [ax0, ax1] + assert fig.gca() is ax0 + + # sca() should not change stored order of Axes, which is order added. + fig.sca(ax0) + assert fig.axes == [ax0, ax1] + + # add_subplot on an existing Axes should not change stored order, but will + # make it current. + fig.add_subplot(ax1) + assert fig.axes == [ax0, ax1] + assert fig.gca() is ax1 + + +def test_add_subplot_subclass(): + fig = plt.figure() + fig.add_subplot(axes_class=Axes) + with pytest.raises(ValueError): + fig.add_subplot(axes_class=Axes, projection="3d") + with pytest.raises(ValueError): + fig.add_subplot(axes_class=Axes, polar=True) + with pytest.raises(ValueError): + fig.add_subplot(projection="3d", polar=True) + with pytest.raises(TypeError): + fig.add_subplot(projection=42) + + +def test_add_subplot_invalid(): + fig = plt.figure() + with pytest.raises(ValueError, + match='Number of columns must be a positive integer'): + fig.add_subplot(2, 0, 1) + with pytest.raises(ValueError, + match='Number of rows must be a positive integer'): + fig.add_subplot(0, 2, 1) + with pytest.raises(ValueError, match='num must be an integer with ' + '1 <= num <= 4'): + fig.add_subplot(2, 2, 0) + with pytest.raises(ValueError, match='num must be an integer with ' + '1 <= num <= 4'): + fig.add_subplot(2, 2, 5) + with pytest.raises(ValueError, match='num must be an integer with ' + '1 <= num <= 4'): + fig.add_subplot(2, 2, 0.5) + + with pytest.raises(ValueError, match='must be a three-digit integer'): + fig.add_subplot(42) + with pytest.raises(ValueError, match='must be a three-digit integer'): + fig.add_subplot(1000) + + with pytest.raises(TypeError, match='takes 1 or 3 positional arguments ' + 'but 2 were given'): + fig.add_subplot(2, 2) + with pytest.raises(TypeError, match='takes 1 or 3 positional arguments ' + 'but 4 were given'): + fig.add_subplot(1, 2, 3, 4) + with pytest.raises(ValueError, + match="Number of rows must be a positive integer, " + "not '2'"): + fig.add_subplot('2', 2, 1) + with pytest.raises(ValueError, + match='Number of columns must be a positive integer, ' + 'not 2.0'): + fig.add_subplot(2, 2.0, 1) + _, ax = plt.subplots() + with pytest.raises(ValueError, + match='The Axes must have been created in the ' + 'present figure'): + fig.add_subplot(ax) + + +@image_comparison(['figure_suptitle']) +def test_suptitle(): + fig, _ = plt.subplots() + fig.suptitle('hello', color='r') + fig.suptitle('title', color='g', rotation=30) + + +def test_suptitle_fontproperties(): + fig, ax = plt.subplots() + fps = mpl.font_manager.FontProperties(size='large', weight='bold') + txt = fig.suptitle('fontprops title', fontproperties=fps) + assert txt.get_fontsize() == fps.get_size_in_points() + assert txt.get_weight() == fps.get_weight() + + +def test_suptitle_subfigures(): + fig = plt.figure(figsize=(4, 3)) + sf1, sf2 = fig.subfigures(1, 2) + sf2.set_facecolor('white') + sf1.subplots() + sf2.subplots() + fig.suptitle("This is a visible suptitle.") + + # verify the first subfigure facecolor is the default transparent + assert sf1.get_facecolor() == (0.0, 0.0, 0.0, 0.0) + # verify the second subfigure facecolor is white + assert sf2.get_facecolor() == (1.0, 1.0, 1.0, 1.0) + + +def test_get_suptitle_supxlabel_supylabel(): + fig, ax = plt.subplots() + assert fig.get_suptitle() == "" + assert fig.get_supxlabel() == "" + assert fig.get_supylabel() == "" + fig.suptitle('suptitle') + assert fig.get_suptitle() == 'suptitle' + fig.supxlabel('supxlabel') + assert fig.get_supxlabel() == 'supxlabel' + fig.supylabel('supylabel') + assert fig.get_supylabel() == 'supylabel' + + +@image_comparison(['alpha_background'], + # only test png and svg. The PDF output appears correct, + # but Ghostscript does not preserve the background color. + extensions=['png', 'svg'], + savefig_kwarg={'facecolor': (0, 1, 0.4), + 'edgecolor': 'none'}) +def test_alpha(): + # We want an image which has a background color and an alpha of 0.4. + fig = plt.figure(figsize=[2, 1]) + fig.set_facecolor((0, 1, 0.4)) + fig.patch.set_alpha(0.4) + fig.patches.append(mpl.patches.CirclePolygon( + [20, 20], radius=15, alpha=0.6, facecolor='red')) + + +def test_too_many_figures(): + with pytest.warns(RuntimeWarning): + for i in range(mpl.rcParams['figure.max_open_warning'] + 1): + plt.figure() + + +def test_iterability_axes_argument(): + + # This is a regression test for matplotlib/matplotlib#3196. If one of the + # arguments returned by _as_mpl_axes defines __getitem__ but is not + # iterable, this would raise an exception. This is because we check + # whether the arguments are iterable, and if so we try and convert them + # to a tuple. However, the ``iterable`` function returns True if + # __getitem__ is present, but some classes can define __getitem__ without + # being iterable. The tuple conversion is now done in a try...except in + # case it fails. + + class MyAxes(Axes): + def __init__(self, *args, myclass=None, **kwargs): + Axes.__init__(self, *args, **kwargs) + + class MyClass: + + def __getitem__(self, item): + if item != 'a': + raise ValueError("item should be a") + + def _as_mpl_axes(self): + return MyAxes, {'myclass': self} + + fig = plt.figure() + fig.add_subplot(1, 1, 1, projection=MyClass()) + plt.close(fig) + + +def test_set_fig_size(): + fig = plt.figure() + + # check figwidth + fig.set_figwidth(5) + assert fig.get_figwidth() == 5 + + # check figheight + fig.set_figheight(1) + assert fig.get_figheight() == 1 + + # check using set_size_inches + fig.set_size_inches(2, 4) + assert fig.get_figwidth() == 2 + assert fig.get_figheight() == 4 + + # check using tuple to first argument + fig.set_size_inches((1, 3)) + assert fig.get_figwidth() == 1 + assert fig.get_figheight() == 3 + + +def test_axes_remove(): + fig, axs = plt.subplots(2, 2) + axs[-1, -1].remove() + for ax in axs.ravel()[:-1]: + assert ax in fig.axes + assert axs[-1, -1] not in fig.axes + assert len(fig.axes) == 3 + + +def test_figaspect(): + w, h = plt.figaspect(np.float64(2) / np.float64(1)) + assert h / w == 2 + w, h = plt.figaspect(2) + assert h / w == 2 + w, h = plt.figaspect(np.zeros((1, 2))) + assert h / w == 0.5 + w, h = plt.figaspect(np.zeros((2, 2))) + assert h / w == 1 + + +@pytest.mark.parametrize('which', ['both', 'major', 'minor']) +def test_autofmt_xdate(which): + date = ['3 Jan 2013', '4 Jan 2013', '5 Jan 2013', '6 Jan 2013', + '7 Jan 2013', '8 Jan 2013', '9 Jan 2013', '10 Jan 2013', + '11 Jan 2013', '12 Jan 2013', '13 Jan 2013', '14 Jan 2013'] + + time = ['16:44:00', '16:45:00', '16:46:00', '16:47:00', '16:48:00', + '16:49:00', '16:51:00', '16:52:00', '16:53:00', '16:55:00', + '16:56:00', '16:57:00'] + + angle = 60 + minors = [1, 2, 3, 4, 5, 6, 7] + + x = mdates.datestr2num(date) + y = mdates.datestr2num(time) + + fig, ax = plt.subplots() + + ax.plot(x, y) + ax.yaxis_date() + ax.xaxis_date() + + ax.xaxis.set_minor_locator(AutoMinorLocator(2)) + with warnings.catch_warnings(): + warnings.filterwarnings( + 'ignore', + 'FixedFormatter should only be used together with FixedLocator') + ax.xaxis.set_minor_formatter(FixedFormatter(minors)) + + fig.autofmt_xdate(0.2, angle, 'right', which) + + if which in ('both', 'major'): + for label in fig.axes[0].get_xticklabels(False, 'major'): + assert int(label.get_rotation()) == angle + + if which in ('both', 'minor'): + for label in fig.axes[0].get_xticklabels(True, 'minor'): + assert int(label.get_rotation()) == angle + + +@mpl.style.context('default') +def test_change_dpi(): + fig = plt.figure(figsize=(4, 4)) + fig.draw_without_rendering() + assert fig.canvas.renderer.height == 400 + assert fig.canvas.renderer.width == 400 + fig.dpi = 50 + fig.draw_without_rendering() + assert fig.canvas.renderer.height == 200 + assert fig.canvas.renderer.width == 200 + + +@pytest.mark.parametrize('width, height', [ + (1, np.nan), + (-1, 1), + (np.inf, 1) +]) +def test_invalid_figure_size(width, height): + with pytest.raises(ValueError): + plt.figure(figsize=(width, height)) + + fig = plt.figure() + with pytest.raises(ValueError): + fig.set_size_inches(width, height) + + +def test_invalid_figure_add_axes(): + fig = plt.figure() + with pytest.raises(TypeError, + match="missing 1 required positional argument: 'rect'"): + fig.add_axes() + + with pytest.raises(ValueError): + fig.add_axes((.1, .1, .5, np.nan)) + + with pytest.raises(TypeError, match="multiple values for argument 'rect'"): + fig.add_axes([0, 0, 1, 1], rect=[0, 0, 1, 1]) + + fig2, ax = plt.subplots() + with pytest.raises(ValueError, + match="The Axes must have been created in the present " + "figure"): + fig.add_axes(ax) + + fig2.delaxes(ax) + with pytest.warns(mpl.MatplotlibDeprecationWarning, + match="Passing more than one positional argument"): + fig2.add_axes(ax, "extra positional argument") + + with pytest.warns(mpl.MatplotlibDeprecationWarning, + match="Passing more than one positional argument"): + fig.add_axes([0, 0, 1, 1], "extra positional argument") + + +def test_subplots_shareax_loglabels(): + fig, axs = plt.subplots(2, 2, sharex=True, sharey=True, squeeze=False) + for ax in axs.flat: + ax.plot([10, 20, 30], [10, 20, 30]) + + ax.set_yscale("log") + ax.set_xscale("log") + + for ax in axs[0, :]: + assert 0 == len(ax.xaxis.get_ticklabels(which='both')) + + for ax in axs[1, :]: + assert 0 < len(ax.xaxis.get_ticklabels(which='both')) + + for ax in axs[:, 1]: + assert 0 == len(ax.yaxis.get_ticklabels(which='both')) + + for ax in axs[:, 0]: + assert 0 < len(ax.yaxis.get_ticklabels(which='both')) + + +def test_savefig(): + fig = plt.figure() + msg = r"savefig\(\) takes 2 positional arguments but 3 were given" + with pytest.raises(TypeError, match=msg): + fig.savefig("fname1.png", "fname2.png") + + +def test_savefig_warns(): + fig = plt.figure() + for format in ['png', 'pdf', 'svg', 'tif', 'jpg']: + with pytest.raises(TypeError): + fig.savefig(io.BytesIO(), format=format, non_existent_kwarg=True) + + +def test_savefig_backend(): + fig = plt.figure() + # Intentionally use an invalid module name. + with pytest.raises(ModuleNotFoundError, match="No module named '@absent'"): + fig.savefig("test", backend="module://@absent") + with pytest.raises(ValueError, + match="The 'pdf' backend does not support png output"): + fig.savefig("test.png", backend="pdf") + + +@pytest.mark.parametrize('backend', [ + pytest.param('Agg', marks=[pytest.mark.backend('Agg')]), + pytest.param('Cairo', marks=[pytest.mark.backend('Cairo')]), +]) +def test_savefig_pixel_ratio(backend): + fig, ax = plt.subplots() + ax.plot([1, 2, 3]) + with io.BytesIO() as buf: + fig.savefig(buf, format='png') + ratio1 = Image.open(buf) + ratio1.load() + + fig, ax = plt.subplots() + ax.plot([1, 2, 3]) + fig.canvas._set_device_pixel_ratio(2) + with io.BytesIO() as buf: + fig.savefig(buf, format='png') + ratio2 = Image.open(buf) + ratio2.load() + + assert ratio1 == ratio2 + + +def test_savefig_preserve_layout_engine(): + fig = plt.figure(layout='compressed') + fig.savefig(io.BytesIO(), bbox_inches='tight') + + assert fig.get_layout_engine()._compress + + +def test_savefig_locate_colorbar(): + fig, ax = plt.subplots() + pc = ax.pcolormesh(np.random.randn(2, 2)) + cbar = fig.colorbar(pc, aspect=40) + fig.savefig(io.BytesIO(), bbox_inches=mpl.transforms.Bbox([[0, 0], [4, 4]])) + + # Check that an aspect ratio has been applied. + assert (cbar.ax.get_position(original=True).bounds != + cbar.ax.get_position(original=False).bounds) + + +@mpl.rc_context({"savefig.transparent": True}) +@check_figures_equal(extensions=["png"]) +def test_savefig_transparent(fig_test, fig_ref): + # create two transparent subfigures with corresponding transparent inset + # axes. the entire background of the image should be transparent. + gs1 = fig_test.add_gridspec(3, 3, left=0.05, wspace=0.05) + f1 = fig_test.add_subfigure(gs1[:, :]) + f2 = f1.add_subfigure(gs1[0, 0]) + + ax12 = f2.add_subplot(gs1[:, :]) + + ax1 = f1.add_subplot(gs1[:-1, :]) + iax1 = ax1.inset_axes([.1, .2, .3, .4]) + iax2 = iax1.inset_axes([.1, .2, .3, .4]) + + ax2 = fig_test.add_subplot(gs1[-1, :-1]) + ax3 = fig_test.add_subplot(gs1[-1, -1]) + + for ax in [ax12, ax1, iax1, iax2, ax2, ax3]: + ax.set(xticks=[], yticks=[]) + ax.spines[:].set_visible(False) + + +def test_figure_repr(): + fig = plt.figure(figsize=(10, 20), dpi=10) + assert repr(fig) == "
" + + +def test_valid_layouts(): + fig = Figure(layout=None) + assert not fig.get_tight_layout() + assert not fig.get_constrained_layout() + + fig = Figure(layout='tight') + assert fig.get_tight_layout() + assert not fig.get_constrained_layout() + + fig = Figure(layout='constrained') + assert not fig.get_tight_layout() + assert fig.get_constrained_layout() + + +def test_invalid_layouts(): + fig, ax = plt.subplots(layout="constrained") + with pytest.warns(UserWarning): + # this should warn, + fig.subplots_adjust(top=0.8) + assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine) + + # Using layout + (tight|constrained)_layout warns, but the former takes + # precedence. + wst = "The Figure parameters 'layout' and 'tight_layout'" + with pytest.warns(UserWarning, match=wst): + fig = Figure(layout='tight', tight_layout=False) + assert isinstance(fig.get_layout_engine(), TightLayoutEngine) + wst = "The Figure parameters 'layout' and 'constrained_layout'" + with pytest.warns(UserWarning, match=wst): + fig = Figure(layout='constrained', constrained_layout=False) + assert not isinstance(fig.get_layout_engine(), TightLayoutEngine) + assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine) + + with pytest.raises(ValueError, + match="Invalid value for 'layout'"): + Figure(layout='foobar') + + # test that layouts can be swapped if no colorbar: + fig, ax = plt.subplots(layout="constrained") + fig.set_layout_engine("tight") + assert isinstance(fig.get_layout_engine(), TightLayoutEngine) + fig.set_layout_engine("constrained") + assert isinstance(fig.get_layout_engine(), ConstrainedLayoutEngine) + + # test that layouts cannot be swapped if there is a colorbar: + fig, ax = plt.subplots(layout="constrained") + pc = ax.pcolormesh(np.random.randn(2, 2)) + fig.colorbar(pc) + with pytest.raises(RuntimeError, match='Colorbar layout of new layout'): + fig.set_layout_engine("tight") + fig.set_layout_engine("none") + with pytest.raises(RuntimeError, match='Colorbar layout of new layout'): + fig.set_layout_engine("tight") + + fig, ax = plt.subplots(layout="tight") + pc = ax.pcolormesh(np.random.randn(2, 2)) + fig.colorbar(pc) + with pytest.raises(RuntimeError, match='Colorbar layout of new layout'): + fig.set_layout_engine("constrained") + fig.set_layout_engine("none") + assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine) + + with pytest.raises(RuntimeError, match='Colorbar layout of new layout'): + fig.set_layout_engine("constrained") + + +@check_figures_equal(extensions=["png"]) +def test_tightlayout_autolayout_deconflict(fig_test, fig_ref): + for fig, autolayout in zip([fig_ref, fig_test], [False, True]): + with mpl.rc_context({'figure.autolayout': autolayout}): + axes = fig.subplots(ncols=2) + fig.tight_layout(w_pad=10) + assert isinstance(fig.get_layout_engine(), PlaceHolderLayoutEngine) + + +@pytest.mark.parametrize('layout', ['constrained', 'compressed']) +def test_layout_change_warning(layout): + """ + Raise a warning when a previously assigned layout changes to tight using + plt.tight_layout(). + """ + fig, ax = plt.subplots(layout=layout) + with pytest.warns(UserWarning, match='The figure layout has changed to'): + plt.tight_layout() + + +def test_repeated_tightlayout(): + fig = Figure() + fig.tight_layout() + # subsequent calls should not warn + fig.tight_layout() + fig.tight_layout() + + +@check_figures_equal(extensions=["png", "pdf"]) +def test_add_artist(fig_test, fig_ref): + fig_test.dpi = 100 + fig_ref.dpi = 100 + + fig_test.subplots() + l1 = plt.Line2D([.2, .7], [.7, .7], gid='l1') + l2 = plt.Line2D([.2, .7], [.8, .8], gid='l2') + r1 = plt.Circle((20, 20), 100, transform=None, gid='C1') + r2 = plt.Circle((.7, .5), .05, gid='C2') + r3 = plt.Circle((4.5, .8), .55, transform=fig_test.dpi_scale_trans, + facecolor='crimson', gid='C3') + for a in [l1, l2, r1, r2, r3]: + fig_test.add_artist(a) + l2.remove() + + ax2 = fig_ref.subplots() + l1 = plt.Line2D([.2, .7], [.7, .7], transform=fig_ref.transFigure, + gid='l1', zorder=21) + r1 = plt.Circle((20, 20), 100, transform=None, clip_on=False, zorder=20, + gid='C1') + r2 = plt.Circle((.7, .5), .05, transform=fig_ref.transFigure, gid='C2', + zorder=20) + r3 = plt.Circle((4.5, .8), .55, transform=fig_ref.dpi_scale_trans, + facecolor='crimson', clip_on=False, zorder=20, gid='C3') + for a in [l1, r1, r2, r3]: + ax2.add_artist(a) + + +@pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"]) +def test_fspath(fmt, tmp_path): + out = tmp_path / f"test.{fmt}" + plt.savefig(out) + with out.open("rb") as file: + # All the supported formats include the format name (case-insensitive) + # in the first 100 bytes. + assert fmt.encode("ascii") in file.read(100).lower() + + +def test_tightbbox(): + fig, ax = plt.subplots() + ax.set_xlim(0, 1) + t = ax.text(1., 0.5, 'This dangles over end') + renderer = fig.canvas.get_renderer() + x1Nom0 = 9.035 # inches + assert abs(t.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2 + assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2 + assert abs(fig.get_tightbbox(renderer).x1 - x1Nom0) < 0.05 + assert abs(fig.get_tightbbox(renderer).x0 - 0.679) < 0.05 + # now exclude t from the tight bbox so now the bbox is quite a bit + # smaller + t.set_in_layout(False) + x1Nom = 7.333 + assert abs(ax.get_tightbbox(renderer).x1 - x1Nom * fig.dpi) < 2 + assert abs(fig.get_tightbbox(renderer).x1 - x1Nom) < 0.05 + + t.set_in_layout(True) + x1Nom = 7.333 + assert abs(ax.get_tightbbox(renderer).x1 - x1Nom0 * fig.dpi) < 2 + # test bbox_extra_artists method... + assert abs(ax.get_tightbbox(renderer, bbox_extra_artists=[]).x1 + - x1Nom * fig.dpi) < 2 + + +def test_axes_removal(): + # Check that units can set the formatter after an Axes removal + fig, axs = plt.subplots(1, 2, sharex=True) + axs[1].remove() + axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1]) + assert isinstance(axs[0].xaxis.get_major_formatter(), + mdates.AutoDateFormatter) + + # Check that manually setting the formatter, then removing Axes keeps + # the set formatter. + fig, axs = plt.subplots(1, 2, sharex=True) + axs[1].xaxis.set_major_formatter(ScalarFormatter()) + axs[1].remove() + axs[0].plot([datetime(2000, 1, 1), datetime(2000, 2, 1)], [0, 1]) + assert isinstance(axs[0].xaxis.get_major_formatter(), + ScalarFormatter) + + +def test_removed_axis(): + # Simple smoke test to make sure removing a shared axis works + fig, axs = plt.subplots(2, sharex=True) + axs[0].remove() + fig.canvas.draw() + + +@pytest.mark.parametrize('clear_meth', ['clear', 'clf']) +def test_figure_clear(clear_meth): + # we test the following figure clearing scenarios: + fig = plt.figure() + + # a) an empty figure + fig.clear() + assert fig.axes == [] + + # b) a figure with a single unnested axes + ax = fig.add_subplot(111) + getattr(fig, clear_meth)() + assert fig.axes == [] + + # c) a figure multiple unnested axes + axes = [fig.add_subplot(2, 1, i+1) for i in range(2)] + getattr(fig, clear_meth)() + assert fig.axes == [] + + # d) a figure with a subfigure + gs = fig.add_gridspec(ncols=2, nrows=1) + subfig = fig.add_subfigure(gs[0]) + subaxes = subfig.add_subplot(111) + getattr(fig, clear_meth)() + assert subfig not in fig.subfigs + assert fig.axes == [] + + # e) a figure with a subfigure and a subplot + subfig = fig.add_subfigure(gs[0]) + subaxes = subfig.add_subplot(111) + mainaxes = fig.add_subplot(gs[1]) + + # e.1) removing just the axes leaves the subplot + mainaxes.remove() + assert fig.axes == [subaxes] + + # e.2) removing just the subaxes leaves the subplot + # and subfigure + mainaxes = fig.add_subplot(gs[1]) + subaxes.remove() + assert fig.axes == [mainaxes] + assert subfig in fig.subfigs + + # e.3) clearing the subfigure leaves the subplot + subaxes = subfig.add_subplot(111) + assert mainaxes in fig.axes + assert subaxes in fig.axes + getattr(subfig, clear_meth)() + assert subfig in fig.subfigs + assert subaxes not in subfig.axes + assert subaxes not in fig.axes + assert mainaxes in fig.axes + + # e.4) clearing the whole thing + subaxes = subfig.add_subplot(111) + getattr(fig, clear_meth)() + assert fig.axes == [] + assert fig.subfigs == [] + + # f) multiple subfigures + subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]] + subaxes = [sfig.add_subplot(111) for sfig in subfigs] + assert all(ax in fig.axes for ax in subaxes) + assert all(sfig in fig.subfigs for sfig in subfigs) + + # f.1) clearing only one subfigure + getattr(subfigs[0], clear_meth)() + assert subaxes[0] not in fig.axes + assert subaxes[1] in fig.axes + assert subfigs[1] in fig.subfigs + + # f.2) clearing the whole thing + getattr(subfigs[1], clear_meth)() + subfigs = [fig.add_subfigure(gs[i]) for i in [0, 1]] + subaxes = [sfig.add_subplot(111) for sfig in subfigs] + assert all(ax in fig.axes for ax in subaxes) + assert all(sfig in fig.subfigs for sfig in subfigs) + getattr(fig, clear_meth)() + assert fig.subfigs == [] + assert fig.axes == [] + + +def test_clf_not_redefined(): + for klass in FigureBase.__subclasses__(): + # check that subclasses do not get redefined in our Figure subclasses + assert 'clf' not in klass.__dict__ + + +@mpl.style.context('mpl20') +def test_picking_does_not_stale(): + fig, ax = plt.subplots() + ax.scatter([0], [0], [1000], picker=True) + fig.canvas.draw() + assert not fig.stale + + mouse_event = SimpleNamespace(x=ax.bbox.x0 + ax.bbox.width / 2, + y=ax.bbox.y0 + ax.bbox.height / 2, + inaxes=ax, guiEvent=None) + fig.pick(mouse_event) + assert not fig.stale + + +def test_add_subplot_twotuple(): + fig = plt.figure() + ax1 = fig.add_subplot(3, 2, (3, 5)) + assert ax1.get_subplotspec().rowspan == range(1, 3) + assert ax1.get_subplotspec().colspan == range(0, 1) + ax2 = fig.add_subplot(3, 2, (4, 6)) + assert ax2.get_subplotspec().rowspan == range(1, 3) + assert ax2.get_subplotspec().colspan == range(1, 2) + ax3 = fig.add_subplot(3, 2, (3, 6)) + assert ax3.get_subplotspec().rowspan == range(1, 3) + assert ax3.get_subplotspec().colspan == range(0, 2) + ax4 = fig.add_subplot(3, 2, (4, 5)) + assert ax4.get_subplotspec().rowspan == range(1, 3) + assert ax4.get_subplotspec().colspan == range(0, 2) + with pytest.raises(IndexError): + fig.add_subplot(3, 2, (6, 3)) + + +@image_comparison(['tightbbox_box_aspect.svg'], style='mpl20', + savefig_kwarg={'bbox_inches': 'tight', + 'facecolor': 'teal'}, + remove_text=True) +def test_tightbbox_box_aspect(): + fig = plt.figure() + gs = fig.add_gridspec(1, 2) + ax1 = fig.add_subplot(gs[0, 0]) + ax2 = fig.add_subplot(gs[0, 1], projection='3d') + ax1.set_box_aspect(.5) + ax2.set_box_aspect((2, 1, 1)) + + +@check_figures_equal(extensions=["svg", "pdf", "eps", "png"]) +def test_animated_with_canvas_change(fig_test, fig_ref): + ax_ref = fig_ref.subplots() + ax_ref.plot(range(5)) + + ax_test = fig_test.subplots() + ax_test.plot(range(5), animated=True) + + +class TestSubplotMosaic: + @check_figures_equal(extensions=["png"]) + @pytest.mark.parametrize( + "x", [ + [["A", "A", "B"], ["C", "D", "B"]], + [[1, 1, 2], [3, 4, 2]], + (("A", "A", "B"), ("C", "D", "B")), + ((1, 1, 2), (3, 4, 2)) + ] + ) + def test_basic(self, fig_test, fig_ref, x): + grid_axes = fig_test.subplot_mosaic(x) + + for k, ax in grid_axes.items(): + ax.set_title(k) + + labels = sorted(np.unique(x)) + + assert len(labels) == len(grid_axes) + + gs = fig_ref.add_gridspec(2, 3) + axA = fig_ref.add_subplot(gs[:1, :2]) + axA.set_title(labels[0]) + + axB = fig_ref.add_subplot(gs[:, 2]) + axB.set_title(labels[1]) + + axC = fig_ref.add_subplot(gs[1, 0]) + axC.set_title(labels[2]) + + axD = fig_ref.add_subplot(gs[1, 1]) + axD.set_title(labels[3]) + + @check_figures_equal(extensions=["png"]) + def test_all_nested(self, fig_test, fig_ref): + x = [["A", "B"], ["C", "D"]] + y = [["E", "F"], ["G", "H"]] + + fig_ref.set_layout_engine("constrained") + fig_test.set_layout_engine("constrained") + + grid_axes = fig_test.subplot_mosaic([[x, y]]) + for ax in grid_axes.values(): + ax.set_title(ax.get_label()) + + gs = fig_ref.add_gridspec(1, 2) + gs_left = gs[0, 0].subgridspec(2, 2) + for j, r in enumerate(x): + for k, label in enumerate(r): + fig_ref.add_subplot(gs_left[j, k]).set_title(label) + + gs_right = gs[0, 1].subgridspec(2, 2) + for j, r in enumerate(y): + for k, label in enumerate(r): + fig_ref.add_subplot(gs_right[j, k]).set_title(label) + + @check_figures_equal(extensions=["png"]) + def test_nested(self, fig_test, fig_ref): + + fig_ref.set_layout_engine("constrained") + fig_test.set_layout_engine("constrained") + + x = [["A", "B"], ["C", "D"]] + + y = [["F"], [x]] + + grid_axes = fig_test.subplot_mosaic(y) + + for k, ax in grid_axes.items(): + ax.set_title(k) + + gs = fig_ref.add_gridspec(2, 1) + + gs_n = gs[1, 0].subgridspec(2, 2) + + axA = fig_ref.add_subplot(gs_n[0, 0]) + axA.set_title("A") + + axB = fig_ref.add_subplot(gs_n[0, 1]) + axB.set_title("B") + + axC = fig_ref.add_subplot(gs_n[1, 0]) + axC.set_title("C") + + axD = fig_ref.add_subplot(gs_n[1, 1]) + axD.set_title("D") + + axF = fig_ref.add_subplot(gs[0, 0]) + axF.set_title("F") + + @check_figures_equal(extensions=["png"]) + def test_nested_tuple(self, fig_test, fig_ref): + x = [["A", "B", "B"], ["C", "C", "D"]] + xt = (("A", "B", "B"), ("C", "C", "D")) + + fig_ref.subplot_mosaic([["F"], [x]]) + fig_test.subplot_mosaic([["F"], [xt]]) + + def test_nested_width_ratios(self): + x = [["A", [["B"], + ["C"]]]] + width_ratios = [2, 1] + + fig, axd = plt.subplot_mosaic(x, width_ratios=width_ratios) + + assert axd["A"].get_gridspec().get_width_ratios() == width_ratios + assert axd["B"].get_gridspec().get_width_ratios() != width_ratios + + def test_nested_height_ratios(self): + x = [["A", [["B"], + ["C"]]], ["D", "D"]] + height_ratios = [1, 2] + + fig, axd = plt.subplot_mosaic(x, height_ratios=height_ratios) + + assert axd["D"].get_gridspec().get_height_ratios() == height_ratios + assert axd["B"].get_gridspec().get_height_ratios() != height_ratios + + @check_figures_equal(extensions=["png"]) + @pytest.mark.parametrize( + "x, empty_sentinel", + [ + ([["A", None], [None, "B"]], None), + ([["A", "."], [".", "B"]], "SKIP"), + ([["A", 0], [0, "B"]], 0), + ([[1, None], [None, 2]], None), + ([[1, "."], [".", 2]], "SKIP"), + ([[1, 0], [0, 2]], 0), + ], + ) + def test_empty(self, fig_test, fig_ref, x, empty_sentinel): + if empty_sentinel != "SKIP": + kwargs = {"empty_sentinel": empty_sentinel} + else: + kwargs = {} + grid_axes = fig_test.subplot_mosaic(x, **kwargs) + + for k, ax in grid_axes.items(): + ax.set_title(k) + + labels = sorted( + {name for row in x for name in row} - {empty_sentinel, "."} + ) + + assert len(labels) == len(grid_axes) + + gs = fig_ref.add_gridspec(2, 2) + axA = fig_ref.add_subplot(gs[0, 0]) + axA.set_title(labels[0]) + + axB = fig_ref.add_subplot(gs[1, 1]) + axB.set_title(labels[1]) + + def test_fail_list_of_str(self): + with pytest.raises(ValueError, match='must be 2D'): + plt.subplot_mosaic(['foo', 'bar']) + with pytest.raises(ValueError, match='must be 2D'): + plt.subplot_mosaic(['foo']) + with pytest.raises(ValueError, match='must be 2D'): + plt.subplot_mosaic([['foo', ('bar',)]]) + with pytest.raises(ValueError, match='must be 2D'): + plt.subplot_mosaic([['a', 'b'], [('a', 'b'), 'c']]) + + @check_figures_equal(extensions=["png"]) + @pytest.mark.parametrize("subplot_kw", [{}, {"projection": "polar"}, None]) + def test_subplot_kw(self, fig_test, fig_ref, subplot_kw): + x = [[1, 2]] + grid_axes = fig_test.subplot_mosaic(x, subplot_kw=subplot_kw) + subplot_kw = subplot_kw or {} + + gs = fig_ref.add_gridspec(1, 2) + axA = fig_ref.add_subplot(gs[0, 0], **subplot_kw) + + axB = fig_ref.add_subplot(gs[0, 1], **subplot_kw) + + @check_figures_equal(extensions=["png"]) + @pytest.mark.parametrize("multi_value", ['BC', tuple('BC')]) + def test_per_subplot_kw(self, fig_test, fig_ref, multi_value): + x = 'AB;CD' + grid_axes = fig_test.subplot_mosaic( + x, + subplot_kw={'facecolor': 'red'}, + per_subplot_kw={ + 'D': {'facecolor': 'blue'}, + multi_value: {'facecolor': 'green'}, + } + ) + + gs = fig_ref.add_gridspec(2, 2) + for color, spec in zip(['red', 'green', 'green', 'blue'], gs): + fig_ref.add_subplot(spec, facecolor=color) + + def test_string_parser(self): + normalize = Figure._normalize_grid_string + + assert normalize('ABC') == [['A', 'B', 'C']] + assert normalize('AB;CC') == [['A', 'B'], ['C', 'C']] + assert normalize('AB;CC;DE') == [['A', 'B'], ['C', 'C'], ['D', 'E']] + assert normalize(""" + ABC + """) == [['A', 'B', 'C']] + assert normalize(""" + AB + CC + """) == [['A', 'B'], ['C', 'C']] + assert normalize(""" + AB + CC + DE + """) == [['A', 'B'], ['C', 'C'], ['D', 'E']] + + def test_per_subplot_kw_expander(self): + normalize = Figure._norm_per_subplot_kw + assert normalize({"A": {}, "B": {}}) == {"A": {}, "B": {}} + assert normalize({("A", "B"): {}}) == {"A": {}, "B": {}} + with pytest.raises( + ValueError, match=f'The key {"B"!r} appears multiple times' + ): + normalize({("A", "B"): {}, "B": {}}) + with pytest.raises( + ValueError, match=f'The key {"B"!r} appears multiple times' + ): + normalize({"B": {}, ("A", "B"): {}}) + + def test_extra_per_subplot_kw(self): + with pytest.raises( + ValueError, match=f'The keys {set("B")!r} are in' + ): + Figure().subplot_mosaic("A", per_subplot_kw={"B": {}}) + + @check_figures_equal(extensions=["png"]) + @pytest.mark.parametrize("str_pattern", + ["AAA\nBBB", "\nAAA\nBBB\n", "ABC\nDEF"] + ) + def test_single_str_input(self, fig_test, fig_ref, str_pattern): + grid_axes = fig_test.subplot_mosaic(str_pattern) + + grid_axes = fig_ref.subplot_mosaic( + [list(ln) for ln in str_pattern.strip().split("\n")] + ) + + @pytest.mark.parametrize( + "x,match", + [ + ( + [["A", "."], [".", "A"]], + ( + "(?m)we found that the label .A. specifies a " + + "non-rectangular or non-contiguous area." + ), + ), + ( + [["A", "B"], [None, [["A", "B"], ["C", "D"]]]], + "There are duplicate keys .* between the outer layout", + ), + ("AAA\nc\nBBB", "All of the rows must be the same length"), + ( + [["A", [["B", "C"], ["D"]]], ["E", "E"]], + "All of the rows must be the same length", + ), + ], + ) + def test_fail(self, x, match): + fig = plt.figure() + with pytest.raises(ValueError, match=match): + fig.subplot_mosaic(x) + + @check_figures_equal(extensions=["png"]) + def test_hashable_keys(self, fig_test, fig_ref): + fig_test.subplot_mosaic([[object(), object()]]) + fig_ref.subplot_mosaic([["A", "B"]]) + + @pytest.mark.parametrize('str_pattern', + ['abc', 'cab', 'bca', 'cba', 'acb', 'bac']) + def test_user_order(self, str_pattern): + fig = plt.figure() + ax_dict = fig.subplot_mosaic(str_pattern) + assert list(str_pattern) == list(ax_dict) + assert list(fig.axes) == list(ax_dict.values()) + + def test_nested_user_order(self): + layout = [ + ["A", [["B", "C"], + ["D", "E"]]], + ["F", "G"], + [".", [["H", [["I"], + ["."]]]]] + ] + + fig = plt.figure() + ax_dict = fig.subplot_mosaic(layout) + assert list(ax_dict) == list("ABCDEFGHI") + assert list(fig.axes) == list(ax_dict.values()) + + def test_share_all(self): + layout = [ + ["A", [["B", "C"], + ["D", "E"]]], + ["F", "G"], + [".", [["H", [["I"], + ["."]]]]] + ] + fig = plt.figure() + ax_dict = fig.subplot_mosaic(layout, sharex=True, sharey=True) + ax_dict["A"].set(xscale="log", yscale="logit") + assert all(ax.get_xscale() == "log" and ax.get_yscale() == "logit" + for ax in ax_dict.values()) + + +def test_reused_gridspec(): + """Test that these all use the same gridspec""" + fig = plt.figure() + ax1 = fig.add_subplot(3, 2, (3, 5)) + ax2 = fig.add_subplot(3, 2, 4) + ax3 = plt.subplot2grid((3, 2), (2, 1), colspan=2, fig=fig) + + gs1 = ax1.get_subplotspec().get_gridspec() + gs2 = ax2.get_subplotspec().get_gridspec() + gs3 = ax3.get_subplotspec().get_gridspec() + + assert gs1 == gs2 + assert gs1 == gs3 + + +@image_comparison(['test_subfigure.png'], style='mpl20', + savefig_kwarg={'facecolor': 'teal'}) +def test_subfigure(): + np.random.seed(19680801) + fig = plt.figure(layout='constrained') + sub = fig.subfigures(1, 2) + + axs = sub[0].subplots(2, 2) + for ax in axs.flat: + pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2) + sub[0].colorbar(pc, ax=axs) + sub[0].suptitle('Left Side') + sub[0].set_facecolor('white') + + axs = sub[1].subplots(1, 3) + for ax in axs.flat: + pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2) + sub[1].colorbar(pc, ax=axs, location='bottom') + sub[1].suptitle('Right Side') + sub[1].set_facecolor('white') + + fig.suptitle('Figure suptitle', fontsize='xx-large') + + # below tests for the draw zorder of subfigures. + leg = fig.legend(handles=[plt.Line2D([0], [0], label='Line{}'.format(i)) + for i in range(5)], loc='center') + sub[0].set_zorder(leg.get_zorder() - 1) + sub[1].set_zorder(leg.get_zorder() + 1) + + +def test_subfigure_tightbbox(): + # test that we can get the tightbbox with a subfigure... + fig = plt.figure(layout='constrained') + sub = fig.subfigures(1, 2) + + np.testing.assert_allclose( + fig.get_tightbbox(fig.canvas.get_renderer()).width, + 8.0) + + +def test_subfigure_dpi(): + fig = plt.figure(dpi=100) + sub_fig = fig.subfigures() + assert sub_fig.get_dpi() == fig.get_dpi() + + sub_fig.set_dpi(200) + assert sub_fig.get_dpi() == 200 + assert fig.get_dpi() == 200 + + +@image_comparison(['test_subfigure_ss.png'], style='mpl20', + savefig_kwarg={'facecolor': 'teal'}, tol=0.02) +def test_subfigure_ss(): + # test assigning the subfigure via subplotspec + np.random.seed(19680801) + fig = plt.figure(layout='constrained') + gs = fig.add_gridspec(1, 2) + + sub = fig.add_subfigure(gs[0], facecolor='pink') + + axs = sub.subplots(2, 2) + for ax in axs.flat: + pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2, vmax=2) + sub.colorbar(pc, ax=axs) + sub.suptitle('Left Side') + + ax = fig.add_subplot(gs[1]) + ax.plot(np.arange(20)) + ax.set_title('Axes') + + fig.suptitle('Figure suptitle', fontsize='xx-large') + + +@image_comparison(['test_subfigure_double.png'], style='mpl20', + savefig_kwarg={'facecolor': 'teal'}) +def test_subfigure_double(): + # test assigning the subfigure via subplotspec + np.random.seed(19680801) + + fig = plt.figure(layout='constrained', figsize=(10, 8)) + + fig.suptitle('fig') + + subfigs = fig.subfigures(1, 2, wspace=0.07) + + subfigs[0].set_facecolor('coral') + subfigs[0].suptitle('subfigs[0]') + + subfigs[1].set_facecolor('coral') + subfigs[1].suptitle('subfigs[1]') + + subfigsnest = subfigs[0].subfigures(2, 1, height_ratios=[1, 1.4]) + subfigsnest[0].suptitle('subfigsnest[0]') + subfigsnest[0].set_facecolor('r') + axsnest0 = subfigsnest[0].subplots(1, 2, sharey=True) + for ax in axsnest0: + fontsize = 12 + pc = ax.pcolormesh(np.random.randn(30, 30), vmin=-2.5, vmax=2.5) + ax.set_xlabel('x-label', fontsize=fontsize) + ax.set_ylabel('y-label', fontsize=fontsize) + ax.set_title('Title', fontsize=fontsize) + subfigsnest[0].colorbar(pc, ax=axsnest0) + + subfigsnest[1].suptitle('subfigsnest[1]') + subfigsnest[1].set_facecolor('g') + axsnest1 = subfigsnest[1].subplots(3, 1, sharex=True) + for nn, ax in enumerate(axsnest1): + ax.set_ylabel(f'ylabel{nn}') + subfigsnest[1].supxlabel('supxlabel') + subfigsnest[1].supylabel('supylabel') + + axsRight = subfigs[1].subplots(2, 2) + + +def test_subfigure_spanning(): + # test that subfigures get laid out properly... + fig = plt.figure(constrained_layout=True) + gs = fig.add_gridspec(3, 3) + sub_figs = [ + fig.add_subfigure(gs[0, 0]), + fig.add_subfigure(gs[0:2, 1]), + fig.add_subfigure(gs[2, 1:3]), + fig.add_subfigure(gs[0:, 1:]) + ] + + w = 640 + h = 480 + np.testing.assert_allclose(sub_figs[0].bbox.min, [0., h * 2/3]) + np.testing.assert_allclose(sub_figs[0].bbox.max, [w / 3, h]) + + np.testing.assert_allclose(sub_figs[1].bbox.min, [w / 3, h / 3]) + np.testing.assert_allclose(sub_figs[1].bbox.max, [w * 2/3, h]) + + np.testing.assert_allclose(sub_figs[2].bbox.min, [w / 3, 0]) + np.testing.assert_allclose(sub_figs[2].bbox.max, [w, h / 3]) + + # check here that slicing actually works. Last sub_fig + # with open slices failed, but only on draw... + for i in range(4): + sub_figs[i].add_subplot() + fig.draw_without_rendering() + + +@mpl.style.context('mpl20') +def test_subfigure_ticks(): + # This tests a tick-spacing error that only seems applicable + # when the subfigures are saved to file. It is very hard to replicate + fig = plt.figure(constrained_layout=True, figsize=(10, 3)) + # create left/right subfigs nested in bottom subfig + (subfig_bl, subfig_br) = fig.subfigures(1, 2, wspace=0.01, + width_ratios=[7, 2]) + + # put ax1-ax3 in gridspec of bottom-left subfig + gs = subfig_bl.add_gridspec(nrows=1, ncols=14) + + ax1 = subfig_bl.add_subplot(gs[0, :1]) + ax1.scatter(x=[-56.46881504821776, 24.179891162109396], y=[1500, 3600]) + + ax2 = subfig_bl.add_subplot(gs[0, 1:3], sharey=ax1) + ax2.scatter(x=[-126.5357270050049, 94.68456736755368], y=[1500, 3600]) + ax3 = subfig_bl.add_subplot(gs[0, 3:14], sharey=ax1) + + fig.dpi = 120 + fig.draw_without_rendering() + ticks120 = ax2.get_xticks() + fig.dpi = 300 + fig.draw_without_rendering() + ticks300 = ax2.get_xticks() + np.testing.assert_allclose(ticks120, ticks300) + + +@image_comparison(['test_subfigure_scatter_size.png'], style='mpl20', + remove_text=True) +def test_subfigure_scatter_size(): + # markers in the left- and right-most subplots should be the same + fig = plt.figure() + gs = fig.add_gridspec(1, 2) + ax0 = fig.add_subplot(gs[1]) + ax0.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s') + ax0.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s') + + sfig = fig.add_subfigure(gs[0]) + axs = sfig.subplots(1, 2) + for ax in [ax0, axs[0]]: + ax.scatter([1, 2, 3], [1, 2, 3], s=30, marker='s', color='r') + ax.scatter([3, 4, 5], [1, 2, 3], s=[20, 30, 40], marker='s', color='g') + + +def test_subfigure_pdf(): + fig = plt.figure(layout='constrained') + sub_fig = fig.subfigures() + ax = sub_fig.add_subplot(111) + b = ax.bar(1, 1) + ax.bar_label(b) + buffer = io.BytesIO() + fig.savefig(buffer, format='pdf') + + +def test_subfigures_wspace_hspace(): + sub_figs = plt.figure().subfigures(2, 3, hspace=0.5, wspace=1/6.) + + w = 640 + h = 480 + + np.testing.assert_allclose(sub_figs[0, 0].bbox.min, [0., h * 0.6]) + np.testing.assert_allclose(sub_figs[0, 0].bbox.max, [w * 0.3, h]) + + np.testing.assert_allclose(sub_figs[0, 1].bbox.min, [w * 0.35, h * 0.6]) + np.testing.assert_allclose(sub_figs[0, 1].bbox.max, [w * 0.65, h]) + + np.testing.assert_allclose(sub_figs[0, 2].bbox.min, [w * 0.7, h * 0.6]) + np.testing.assert_allclose(sub_figs[0, 2].bbox.max, [w, h]) + + np.testing.assert_allclose(sub_figs[1, 0].bbox.min, [0, 0]) + np.testing.assert_allclose(sub_figs[1, 0].bbox.max, [w * 0.3, h * 0.4]) + + np.testing.assert_allclose(sub_figs[1, 1].bbox.min, [w * 0.35, 0]) + np.testing.assert_allclose(sub_figs[1, 1].bbox.max, [w * 0.65, h * 0.4]) + + np.testing.assert_allclose(sub_figs[1, 2].bbox.min, [w * 0.7, 0]) + np.testing.assert_allclose(sub_figs[1, 2].bbox.max, [w, h * 0.4]) + + +def test_subfigure_remove(): + fig = plt.figure() + sfs = fig.subfigures(2, 2) + sfs[1, 1].remove() + assert len(fig.subfigs) == 3 + + +def test_add_subplot_kwargs(): + # fig.add_subplot() always creates new axes, even if axes kwargs differ. + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1) + ax1 = fig.add_subplot(1, 1, 1) + assert ax is not None + assert ax1 is not ax + plt.close() + + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, projection='polar') + ax1 = fig.add_subplot(1, 1, 1, projection='polar') + assert ax is not None + assert ax1 is not ax + plt.close() + + fig = plt.figure() + ax = fig.add_subplot(1, 1, 1, projection='polar') + ax1 = fig.add_subplot(1, 1, 1) + assert ax is not None + assert ax1.name == 'rectilinear' + assert ax1 is not ax + plt.close() + + +def test_add_axes_kwargs(): + # fig.add_axes() always creates new axes, even if axes kwargs differ. + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1]) + ax1 = fig.add_axes([0, 0, 1, 1]) + assert ax is not None + assert ax1 is not ax + plt.close() + + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1], projection='polar') + ax1 = fig.add_axes([0, 0, 1, 1], projection='polar') + assert ax is not None + assert ax1 is not ax + plt.close() + + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1], projection='polar') + ax1 = fig.add_axes([0, 0, 1, 1]) + assert ax is not None + assert ax1.name == 'rectilinear' + assert ax1 is not ax + plt.close() + + +def test_ginput(recwarn): # recwarn undoes warn filters at exit. + warnings.filterwarnings("ignore", "cannot show the figure") + fig, ax = plt.subplots() + trans = ax.transData.transform + + def single_press(): + MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process() + + Timer(.1, single_press).start() + assert fig.ginput() == [(.1, .2)] + + def multi_presses(): + MouseEvent("button_press_event", fig.canvas, *trans((.1, .2)), 1)._process() + KeyEvent("key_press_event", fig.canvas, "backspace")._process() + MouseEvent("button_press_event", fig.canvas, *trans((.3, .4)), 1)._process() + MouseEvent("button_press_event", fig.canvas, *trans((.5, .6)), 1)._process() + MouseEvent("button_press_event", fig.canvas, *trans((0, 0)), 2)._process() + + Timer(.1, multi_presses).start() + np.testing.assert_allclose(fig.ginput(3), [(.3, .4), (.5, .6)]) + + +def test_waitforbuttonpress(recwarn): # recwarn undoes warn filters at exit. + warnings.filterwarnings("ignore", "cannot show the figure") + fig = plt.figure() + assert fig.waitforbuttonpress(timeout=.1) is None + Timer(.1, KeyEvent("key_press_event", fig.canvas, "z")._process).start() + assert fig.waitforbuttonpress() is True + Timer(.1, MouseEvent("button_press_event", fig.canvas, 0, 0, 1)._process).start() + assert fig.waitforbuttonpress() is False + + +def test_kwargs_pass(): + fig = Figure(label='whole Figure') + sub_fig = fig.subfigures(1, 1, label='sub figure') + + assert fig.get_label() == 'whole Figure' + assert sub_fig.get_label() == 'sub figure' + + +@check_figures_equal(extensions=["png"]) +def test_rcparams(fig_test, fig_ref): + fig_ref.supxlabel("xlabel", weight='bold', size=15) + fig_ref.supylabel("ylabel", weight='bold', size=15) + fig_ref.suptitle("Title", weight='light', size=20) + with mpl.rc_context({'figure.labelweight': 'bold', + 'figure.labelsize': 15, + 'figure.titleweight': 'light', + 'figure.titlesize': 20}): + fig_test.supxlabel("xlabel") + fig_test.supylabel("ylabel") + fig_test.suptitle("Title") + + +def test_deepcopy(): + fig1, ax = plt.subplots() + ax.plot([0, 1], [2, 3]) + ax.set_yscale('log') + + fig2 = copy.deepcopy(fig1) + + # Make sure it is a new object + assert fig2.axes[0] is not ax + # And that the axis scale got propagated + assert fig2.axes[0].get_yscale() == 'log' + # Update the deepcopy and check the original isn't modified + fig2.axes[0].set_yscale('linear') + assert ax.get_yscale() == 'log' + + # And test the limits of the axes don't get propagated + ax.set_xlim(1e-1, 1e2) + # Draw these to make sure limits are updated + fig1.draw_without_rendering() + fig2.draw_without_rendering() + + assert ax.get_xlim() == (1e-1, 1e2) + assert fig2.axes[0].get_xlim() == (0, 1) + + +def test_unpickle_with_device_pixel_ratio(): + fig = Figure(dpi=42) + fig.canvas._set_device_pixel_ratio(7) + assert fig.dpi == 42*7 + fig2 = pickle.loads(pickle.dumps(fig)) + assert fig2.dpi == 42 + + +def test_gridspec_no_mutate_input(): + gs = {'left': .1} + gs_orig = dict(gs) + plt.subplots(1, 2, width_ratios=[1, 2], gridspec_kw=gs) + assert gs == gs_orig + plt.subplot_mosaic('AB', width_ratios=[1, 2], gridspec_kw=gs) + + +@pytest.mark.parametrize('fmt', ['eps', 'pdf', 'png', 'ps', 'svg', 'svgz']) +def test_savefig_metadata(fmt): + Figure().savefig(io.BytesIO(), format=fmt, metadata={}) + + +@pytest.mark.parametrize('fmt', ['jpeg', 'jpg', 'tif', 'tiff', 'webp', "raw", "rgba"]) +def test_savefig_metadata_error(fmt): + with pytest.raises(ValueError, match="metadata not supported"): + Figure().savefig(io.BytesIO(), format=fmt, metadata={}) + + +def test_get_constrained_layout_pads(): + params = {'w_pad': 0.01, 'h_pad': 0.02, 'wspace': 0.03, 'hspace': 0.04} + expected = tuple([*params.values()]) + fig = plt.figure(layout=mpl.layout_engine.ConstrainedLayoutEngine(**params)) + with pytest.warns(PendingDeprecationWarning, match="will be deprecated"): + assert fig.get_constrained_layout_pads() == expected + + +def test_not_visible_figure(): + fig = Figure() + + buf = io.StringIO() + fig.savefig(buf, format='svg') + buf.seek(0) + assert ' 10**6) + """ + # Creates big x and y data: + N = 10**7 + x = np.linspace(0, 1, N) + y = np.random.normal(size=N) + + # Create a plot figure: + fig = plt.figure() + ax = plt.subplot() + + # Create a "big" Line instance: + l = mlines.Line2D(x, y) + l.set_visible(False) + # but don't add it to the Axis instance `ax` + + # [here Interactive panning and zooming is pretty responsive] + # Time the canvas drawing: + t_no_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3)) + # (gives about 25 ms) + + # Add the big invisible Line: + ax.add_line(l) + + # [Now interactive panning and zooming is very slow] + # Time the canvas drawing: + t_invisible_line = min(timeit.repeat(fig.canvas.draw, number=1, repeat=3)) + # gives about 290 ms for N = 10**7 pts + + slowdown_factor = t_invisible_line / t_no_line + slowdown_threshold = 2 # trying to avoid false positive failures + assert slowdown_factor < slowdown_threshold + + +def test_set_line_coll_dash(): + fig, ax = plt.subplots() + np.random.seed(0) + # Testing setting linestyles for line collections. + # This should not produce an error. + ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) + + +def test_invalid_line_data(): + with pytest.raises(RuntimeError, match='xdata must be'): + mlines.Line2D(0, []) + with pytest.raises(RuntimeError, match='ydata must be'): + mlines.Line2D([], 1) + + line = mlines.Line2D([], []) + with pytest.raises(RuntimeError, match='x must be'): + line.set_xdata(0) + with pytest.raises(RuntimeError, match='y must be'): + line.set_ydata(0) + + +@image_comparison(['line_dashes'], remove_text=True, tol=0.003) +def test_line_dashes(): + # Tolerance introduced after reordering of floating-point operations + # Remove when regenerating the images + fig, ax = plt.subplots() + + ax.plot(range(10), linestyle=(0, (3, 3)), lw=5) + + +def test_line_colors(): + fig, ax = plt.subplots() + ax.plot(range(10), color='none') + ax.plot(range(10), color='r') + ax.plot(range(10), color='.3') + ax.plot(range(10), color=(1, 0, 0, 1)) + ax.plot(range(10), color=(1, 0, 0)) + fig.canvas.draw() + + +def test_valid_colors(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_color("foobar") + + +def test_linestyle_variants(): + fig, ax = plt.subplots() + for ls in ["-", "solid", "--", "dashed", + "-.", "dashdot", ":", "dotted", + (0, None), (0, ()), (0, []), # gh-22930 + ]: + ax.plot(range(10), linestyle=ls) + fig.canvas.draw() + + +def test_valid_linestyles(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_linestyle('aardvark') + + +@image_comparison(['drawstyle_variants.png'], remove_text=True, + tol=0.03 if platform.machine() == 'arm64' else 0) +def test_drawstyle_variants(): + fig, axs = plt.subplots(6) + dss = ["default", "steps-mid", "steps-pre", "steps-post", "steps", None] + # We want to check that drawstyles are properly handled even for very long + # lines (for which the subslice optimization is on); however, we need + # to zoom in so that the difference between the drawstyles is actually + # visible. + for ax, ds in zip(axs.flat, dss): + ax.plot(range(2000), drawstyle=ds) + ax.set(xlim=(0, 2), ylim=(0, 2)) + + +@check_figures_equal(extensions=('png',)) +def test_no_subslice_with_transform(fig_ref, fig_test): + ax = fig_ref.add_subplot() + x = np.arange(2000) + ax.plot(x + 2000, x) + + ax = fig_test.add_subplot() + t = mtransforms.Affine2D().translate(2000.0, 0.0) + ax.plot(x, x, transform=t+ax.transData) + + +def test_valid_drawstyles(): + line = mlines.Line2D([], []) + with pytest.raises(ValueError): + line.set_drawstyle('foobar') + + +def test_set_drawstyle(): + x = np.linspace(0, 2*np.pi, 10) + y = np.sin(x) + + fig, ax = plt.subplots() + line, = ax.plot(x, y) + line.set_drawstyle("steps-pre") + assert len(line.get_path().vertices) == 2*len(x)-1 + + line.set_drawstyle("default") + assert len(line.get_path().vertices) == len(x) + + +@image_comparison( + ['line_collection_dashes'], remove_text=True, style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.65) +def test_set_line_coll_dash_image(): + fig, ax = plt.subplots() + np.random.seed(0) + ax.contour(np.random.randn(20, 30), linestyles=[(0, (3, 3))]) + + +@image_comparison(['marker_fill_styles.png'], remove_text=True) +def test_marker_fill_styles(): + colors = itertools.cycle([[0, 0, 1], 'g', '#ff0000', 'c', 'm', 'y', + np.array([0, 0, 0])]) + altcolor = 'lightgreen' + + y = np.array([1, 1]) + x = np.array([0, 9]) + fig, ax = plt.subplots() + + # This hard-coded list of markers correspond to an earlier iteration of + # MarkerStyle.filled_markers; the value of that attribute has changed but + # we kept the old value here to not regenerate the baseline image. + # Replace with mlines.Line2D.filled_markers when the image is regenerated. + for j, marker in enumerate("ov^<>8sp*hHDdPX"): + for i, fs in enumerate(mlines.Line2D.fillStyles): + color = next(colors) + ax.plot(j * 10 + x, y + i + .5 * (j % 2), + marker=marker, + markersize=20, + markerfacecoloralt=altcolor, + fillstyle=fs, + label=fs, + linewidth=5, + color=color, + markeredgecolor=color, + markeredgewidth=2) + + ax.set_ylim([0, 7.5]) + ax.set_xlim([-5, 155]) + + +def test_markerfacecolor_fillstyle(): + """Test that markerfacecolor does not override fillstyle='none'.""" + l, = plt.plot([1, 3, 2], marker=MarkerStyle('o', fillstyle='none'), + markerfacecolor='red') + assert l.get_fillstyle() == 'none' + assert l.get_markerfacecolor() == 'none' + + +@image_comparison(['scaled_lines'], style='default') +def test_lw_scaling(): + th = np.linspace(0, 32) + fig, ax = plt.subplots() + lins_styles = ['dashed', 'dotted', 'dashdot'] + cy = cycler(matplotlib.rcParams['axes.prop_cycle']) + for j, (ls, sty) in enumerate(zip(lins_styles, cy)): + for lw in np.linspace(.5, 10, 10): + ax.plot(th, j*np.ones(50) + .1 * lw, linestyle=ls, lw=lw, **sty) + + +def test_is_sorted_and_has_non_nan(): + assert _path.is_sorted_and_has_non_nan(np.array([1, 2, 3])) + assert _path.is_sorted_and_has_non_nan(np.array([1, np.nan, 3])) + assert not _path.is_sorted_and_has_non_nan([3, 5] + [np.nan] * 100 + [0, 2]) + # [2, 256] byteswapped: + assert not _path.is_sorted_and_has_non_nan(np.array([33554432, 65536], ">i4")) + n = 2 * mlines.Line2D._subslice_optim_min_size + plt.plot([np.nan] * n, range(n)) + + +@check_figures_equal() +def test_step_markers(fig_test, fig_ref): + fig_test.subplots().step([0, 1], "-o") + fig_ref.subplots().plot([0, 0, 1], [0, 1, 1], "-o", markevery=[0, 2]) + + +@pytest.mark.parametrize("parent", ["figure", "axes"]) +@check_figures_equal(extensions=('png',)) +def test_markevery(fig_test, fig_ref, parent): + np.random.seed(42) + x = np.linspace(0, 1, 14) + y = np.random.rand(len(x)) + + cases_test = [None, 4, (2, 5), [1, 5, 11], + [0, -1], slice(5, 10, 2), + np.arange(len(x))[y > 0.5], + 0.3, (0.3, 0.4)] + cases_ref = ["11111111111111", "10001000100010", "00100001000010", + "01000100000100", "10000000000001", "00000101010000", + "01110001110110", "11011011011110", "01010011011101"] + + if parent == "figure": + # float markevery ("relative to axes size") is not supported. + cases_test = cases_test[:-2] + cases_ref = cases_ref[:-2] + + def add_test(x, y, *, markevery): + fig_test.add_artist( + mlines.Line2D(x, y, marker="o", markevery=markevery)) + + def add_ref(x, y, *, markevery): + fig_ref.add_artist( + mlines.Line2D(x, y, marker="o", markevery=markevery)) + + elif parent == "axes": + axs_test = iter(fig_test.subplots(3, 3).flat) + axs_ref = iter(fig_ref.subplots(3, 3).flat) + + def add_test(x, y, *, markevery): + next(axs_test).plot(x, y, "-gD", markevery=markevery) + + def add_ref(x, y, *, markevery): + next(axs_ref).plot(x, y, "-gD", markevery=markevery) + + for case in cases_test: + add_test(x, y, markevery=case) + + for case in cases_ref: + me = np.array(list(case)).astype(int).astype(bool) + add_ref(x, y, markevery=me) + + +def test_markevery_figure_line_unsupported_relsize(): + fig = plt.figure() + fig.add_artist(mlines.Line2D([0, 1], [0, 1], marker="o", markevery=.5)) + with pytest.raises(ValueError): + fig.canvas.draw() + + +def test_marker_as_markerstyle(): + fig, ax = plt.subplots() + line, = ax.plot([2, 4, 3], marker=MarkerStyle("D")) + fig.canvas.draw() + assert line.get_marker() == "D" + + # continue with smoke tests: + line.set_marker("s") + fig.canvas.draw() + line.set_marker(MarkerStyle("o")) + fig.canvas.draw() + # test Path roundtrip + triangle1 = Path._create_closed([[-1, -1], [1, -1], [0, 2]]) + line2, = ax.plot([1, 3, 2], marker=MarkerStyle(triangle1), ms=22) + line3, = ax.plot([0, 2, 1], marker=triangle1, ms=22) + + assert_array_equal(line2.get_marker().vertices, triangle1.vertices) + assert_array_equal(line3.get_marker().vertices, triangle1.vertices) + + +@image_comparison(['striped_line.png'], remove_text=True, style='mpl20') +def test_striped_lines(): + rng = np.random.default_rng(19680801) + _, ax = plt.subplots() + ax.plot(rng.uniform(size=12), color='orange', gapcolor='blue', + linestyle='--', lw=5, label=' ') + ax.plot(rng.uniform(size=12), color='red', gapcolor='black', + linestyle=(0, (2, 5, 4, 2)), lw=5, label=' ', alpha=0.5) + ax.legend(handlelength=5) + + +@check_figures_equal() +def test_odd_dashes(fig_test, fig_ref): + fig_test.add_subplot().plot([1, 2], dashes=[1, 2, 3]) + fig_ref.add_subplot().plot([1, 2], dashes=[1, 2, 3, 1, 2, 3]) + + +def test_picking(): + fig, ax = plt.subplots() + mouse_event = SimpleNamespace(x=fig.bbox.width // 2, + y=fig.bbox.height // 2 + 15) + + # Default pickradius is 5, so event should not pick this line. + l0, = ax.plot([0, 1], [0, 1], picker=True) + found, indices = l0.contains(mouse_event) + assert not found + + # But with a larger pickradius, this should be picked. + l1, = ax.plot([0, 1], [0, 1], picker=True, pickradius=20) + found, indices = l1.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + # And if we modify the pickradius after creation, it should work as well. + l2, = ax.plot([0, 1], [0, 1], picker=True) + found, indices = l2.contains(mouse_event) + assert not found + l2.set_pickradius(20) + found, indices = l2.contains(mouse_event) + assert found + assert_array_equal(indices['ind'], [0]) + + +@check_figures_equal() +def test_input_copy(fig_test, fig_ref): + + t = np.arange(0, 6, 2) + l, = fig_test.add_subplot().plot(t, t, ".-") + t[:] = range(3) + # Trigger cache invalidation + l.set_drawstyle("steps") + fig_ref.add_subplot().plot([0, 2, 4], [0, 2, 4], ".-", drawstyle="steps") + + +@check_figures_equal(extensions=["png"]) +def test_markevery_prop_cycle(fig_test, fig_ref): + """Test that we can set markevery prop_cycle.""" + cases = [None, 8, (30, 8), [16, 24, 30], [0, -1], + slice(100, 200, 3), 0.1, 0.3, 1.5, + (0.0, 0.1), (0.45, 0.1)] + + cmap = mpl.colormaps['jet'] + colors = cmap(np.linspace(0.2, 0.8, len(cases))) + + x = np.linspace(-1, 1) + y = 5 * x**2 + + axs = fig_ref.add_subplot() + for i, markevery in enumerate(cases): + axs.plot(y - i, 'o-', markevery=markevery, color=colors[i]) + + matplotlib.rcParams['axes.prop_cycle'] = cycler(markevery=cases, + color=colors) + + ax = fig_test.add_subplot() + for i, _ in enumerate(cases): + ax.plot(y - i, 'o-') + + +def test_axline_setters(): + fig, ax = plt.subplots() + line1 = ax.axline((.1, .1), slope=0.6) + line2 = ax.axline((.1, .1), (.8, .4)) + # Testing xy1, xy2 and slope setters. + # This should not produce an error. + line1.set_xy1(.2, .3) + line1.set_slope(2.4) + line2.set_xy1(.3, .2) + line2.set_xy2(.6, .8) + # Testing xy1, xy2 and slope getters. + # Should return the modified values. + assert line1.get_xy1() == (.2, .3) + assert line1.get_slope() == 2.4 + assert line2.get_xy1() == (.3, .2) + assert line2.get_xy2() == (.6, .8) + # Testing setting xy2 and slope together. + # These test should raise a ValueError + with pytest.raises(ValueError, + match="Cannot set an 'xy2' value while 'slope' is set"): + line1.set_xy2(.2, .3) + + with pytest.raises(ValueError, + match="Cannot set a 'slope' value while 'xy2' is set"): + line2.set_slope(3) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_patches.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_patches.py new file mode 100644 index 0000000000000000000000000000000000000000..3544ce8cb10c3853d8a339dc6781cb0bc7543a9f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_patches.py @@ -0,0 +1,962 @@ +""" +Tests specific to the patches module. +""" +import platform + +import numpy as np +from numpy.testing import assert_almost_equal, assert_array_equal +import pytest + +import matplotlib as mpl +from matplotlib.patches import (Annulus, Ellipse, Patch, Polygon, Rectangle, + FancyArrowPatch, FancyArrow, BoxStyle, Arc) +from matplotlib.testing.decorators import image_comparison, check_figures_equal +from matplotlib.transforms import Bbox +import matplotlib.pyplot as plt +from matplotlib import ( + collections as mcollections, colors as mcolors, patches as mpatches, + path as mpath, transforms as mtransforms, rcParams) + + +def test_Polygon_close(): + #: GitHub issue #1018 identified a bug in the Polygon handling + #: of the closed attribute; the path was not getting closed + #: when set_xy was used to set the vertices. + + # open set of vertices: + xy = [[0, 0], [0, 1], [1, 1]] + # closed set: + xyclosed = xy + [[0, 0]] + + # start with open path and close it: + p = Polygon(xy, closed=True) + assert p.get_closed() + assert_array_equal(p.get_xy(), xyclosed) + p.set_xy(xy) + assert_array_equal(p.get_xy(), xyclosed) + + # start with closed path and open it: + p = Polygon(xyclosed, closed=False) + assert_array_equal(p.get_xy(), xy) + p.set_xy(xyclosed) + assert_array_equal(p.get_xy(), xy) + + # start with open path and leave it open: + p = Polygon(xy, closed=False) + assert not p.get_closed() + assert_array_equal(p.get_xy(), xy) + p.set_xy(xy) + assert_array_equal(p.get_xy(), xy) + + # start with closed path and leave it closed: + p = Polygon(xyclosed, closed=True) + assert_array_equal(p.get_xy(), xyclosed) + p.set_xy(xyclosed) + assert_array_equal(p.get_xy(), xyclosed) + + +def test_corner_center(): + loc = [10, 20] + width = 1 + height = 2 + + # Rectangle + # No rotation + corners = ((10, 20), (11, 20), (11, 22), (10, 22)) + rect = Rectangle(loc, width, height) + assert_array_equal(rect.get_corners(), corners) + assert_array_equal(rect.get_center(), (10.5, 21)) + + # 90 deg rotation + corners_rot = ((10, 20), (10, 21), (8, 21), (8, 20)) + rect.set_angle(90) + assert_array_equal(rect.get_corners(), corners_rot) + assert_array_equal(rect.get_center(), (9, 20.5)) + + # Rotation not a multiple of 90 deg + theta = 33 + t = mtransforms.Affine2D().rotate_around(*loc, np.deg2rad(theta)) + corners_rot = t.transform(corners) + rect.set_angle(theta) + assert_almost_equal(rect.get_corners(), corners_rot) + + # Ellipse + loc = [loc[0] + width / 2, + loc[1] + height / 2] + ellipse = Ellipse(loc, width, height) + + # No rotation + assert_array_equal(ellipse.get_corners(), corners) + + # 90 deg rotation + corners_rot = ((11.5, 20.5), (11.5, 21.5), (9.5, 21.5), (9.5, 20.5)) + ellipse.set_angle(90) + assert_array_equal(ellipse.get_corners(), corners_rot) + # Rotation shouldn't change ellipse center + assert_array_equal(ellipse.get_center(), loc) + + # Rotation not a multiple of 90 deg + theta = 33 + t = mtransforms.Affine2D().rotate_around(*loc, np.deg2rad(theta)) + corners_rot = t.transform(corners) + ellipse.set_angle(theta) + assert_almost_equal(ellipse.get_corners(), corners_rot) + + +def test_ellipse_vertices(): + # expect 0 for 0 ellipse width, height + ellipse = Ellipse(xy=(0, 0), width=0, height=0, angle=0) + assert_almost_equal( + ellipse.get_vertices(), + [(0.0, 0.0), (0.0, 0.0)], + ) + assert_almost_equal( + ellipse.get_co_vertices(), + [(0.0, 0.0), (0.0, 0.0)], + ) + + ellipse = Ellipse(xy=(0, 0), width=2, height=1, angle=30) + assert_almost_equal( + ellipse.get_vertices(), + [ + ( + ellipse.center[0] + ellipse.width / 4 * np.sqrt(3), + ellipse.center[1] + ellipse.width / 4, + ), + ( + ellipse.center[0] - ellipse.width / 4 * np.sqrt(3), + ellipse.center[1] - ellipse.width / 4, + ), + ], + ) + assert_almost_equal( + ellipse.get_co_vertices(), + [ + ( + ellipse.center[0] - ellipse.height / 4, + ellipse.center[1] + ellipse.height / 4 * np.sqrt(3), + ), + ( + ellipse.center[0] + ellipse.height / 4, + ellipse.center[1] - ellipse.height / 4 * np.sqrt(3), + ), + ], + ) + v1, v2 = np.array(ellipse.get_vertices()) + np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center) + v1, v2 = np.array(ellipse.get_co_vertices()) + np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center) + + ellipse = Ellipse(xy=(2.252, -10.859), width=2.265, height=1.98, angle=68.78) + v1, v2 = np.array(ellipse.get_vertices()) + np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center) + v1, v2 = np.array(ellipse.get_co_vertices()) + np.testing.assert_almost_equal((v1 + v2) / 2, ellipse.center) + + +def test_rotate_rect(): + loc = np.asarray([1.0, 2.0]) + width = 2 + height = 3 + angle = 30.0 + + # A rotated rectangle + rect1 = Rectangle(loc, width, height, angle=angle) + + # A non-rotated rectangle + rect2 = Rectangle(loc, width, height) + + # Set up an explicit rotation matrix (in radians) + angle_rad = np.pi * angle / 180.0 + rotation_matrix = np.array([[np.cos(angle_rad), -np.sin(angle_rad)], + [np.sin(angle_rad), np.cos(angle_rad)]]) + + # Translate to origin, rotate each vertex, and then translate back + new_verts = np.inner(rotation_matrix, rect2.get_verts() - loc).T + loc + + # They should be the same + assert_almost_equal(rect1.get_verts(), new_verts) + + +@check_figures_equal(extensions=['png']) +def test_rotate_rect_draw(fig_test, fig_ref): + ax_test = fig_test.add_subplot() + ax_ref = fig_ref.add_subplot() + + loc = (0, 0) + width, height = (1, 1) + angle = 30 + rect_ref = Rectangle(loc, width, height, angle=angle) + ax_ref.add_patch(rect_ref) + assert rect_ref.get_angle() == angle + + # Check that when the angle is updated after adding to an Axes, that the + # patch is marked stale and redrawn in the correct location + rect_test = Rectangle(loc, width, height) + assert rect_test.get_angle() == 0 + ax_test.add_patch(rect_test) + rect_test.set_angle(angle) + assert rect_test.get_angle() == angle + + +@check_figures_equal(extensions=['png']) +def test_dash_offset_patch_draw(fig_test, fig_ref): + ax_test = fig_test.add_subplot() + ax_ref = fig_ref.add_subplot() + + loc = (0.1, 0.1) + width, height = (0.8, 0.8) + rect_ref = Rectangle(loc, width, height, linewidth=3, edgecolor='b', + linestyle=(0, [6, 6])) + # fill the line gaps using a linestyle (0, [0, 6, 6, 0]), which is + # equivalent to (6, [6, 6]) but has 0 dash offset + rect_ref2 = Rectangle(loc, width, height, linewidth=3, edgecolor='r', + linestyle=(0, [0, 6, 6, 0])) + assert rect_ref.get_linestyle() == (0, [6, 6]) + assert rect_ref2.get_linestyle() == (0, [0, 6, 6, 0]) + + ax_ref.add_patch(rect_ref) + ax_ref.add_patch(rect_ref2) + + # Check that the dash offset of the rect is the same if we pass it in the + # init method and if we create two rects with appropriate onoff sequence + # of linestyle. + + rect_test = Rectangle(loc, width, height, linewidth=3, edgecolor='b', + linestyle=(0, [6, 6])) + rect_test2 = Rectangle(loc, width, height, linewidth=3, edgecolor='r', + linestyle=(6, [6, 6])) + assert rect_test.get_linestyle() == (0, [6, 6]) + assert rect_test2.get_linestyle() == (6, [6, 6]) + + ax_test.add_patch(rect_test) + ax_test.add_patch(rect_test2) + + +def test_negative_rect(): + # These two rectangles have the same vertices, but starting from a + # different point. (We also drop the last vertex, which is a duplicate.) + pos_vertices = Rectangle((-3, -2), 3, 2).get_verts()[:-1] + neg_vertices = Rectangle((0, 0), -3, -2).get_verts()[:-1] + assert_array_equal(np.roll(neg_vertices, 2, 0), pos_vertices) + + +@image_comparison(['clip_to_bbox']) +def test_clip_to_bbox(): + fig, ax = plt.subplots() + ax.set_xlim([-18, 20]) + ax.set_ylim([-150, 100]) + + path = mpath.Path.unit_regular_star(8).deepcopy() + path.vertices *= [10, 100] + path.vertices -= [5, 25] + + path2 = mpath.Path.unit_circle().deepcopy() + path2.vertices *= [10, 100] + path2.vertices += [10, -25] + + combined = mpath.Path.make_compound_path(path, path2) + + patch = mpatches.PathPatch( + combined, alpha=0.5, facecolor='coral', edgecolor='none') + ax.add_patch(patch) + + bbox = mtransforms.Bbox([[-12, -77.5], [50, -110]]) + result_path = combined.clip_to_bbox(bbox) + result_patch = mpatches.PathPatch( + result_path, alpha=0.5, facecolor='green', lw=4, edgecolor='black') + + ax.add_patch(result_patch) + + +@image_comparison(['patch_alpha_coloring'], remove_text=True) +def test_patch_alpha_coloring(): + """ + Test checks that the patch and collection are rendered with the specified + alpha values in their facecolor and edgecolor. + """ + star = mpath.Path.unit_regular_star(6) + circle = mpath.Path.unit_circle() + # concatenate the star with an internal cutout of the circle + verts = np.concatenate([circle.vertices, star.vertices[::-1]]) + codes = np.concatenate([circle.codes, star.codes]) + cut_star1 = mpath.Path(verts, codes) + cut_star2 = mpath.Path(verts + 1, codes) + + ax = plt.axes() + col = mcollections.PathCollection([cut_star2], + linewidth=5, linestyles='dashdot', + facecolor=(1, 0, 0, 0.5), + edgecolor=(0, 0, 1, 0.75)) + ax.add_collection(col) + + patch = mpatches.PathPatch(cut_star1, + linewidth=5, linestyle='dashdot', + facecolor=(1, 0, 0, 0.5), + edgecolor=(0, 0, 1, 0.75)) + ax.add_patch(patch) + + ax.set_xlim(-1, 2) + ax.set_ylim(-1, 2) + + +@image_comparison(['patch_alpha_override'], remove_text=True) +def test_patch_alpha_override(): + #: Test checks that specifying an alpha attribute for a patch or + #: collection will override any alpha component of the facecolor + #: or edgecolor. + star = mpath.Path.unit_regular_star(6) + circle = mpath.Path.unit_circle() + # concatenate the star with an internal cutout of the circle + verts = np.concatenate([circle.vertices, star.vertices[::-1]]) + codes = np.concatenate([circle.codes, star.codes]) + cut_star1 = mpath.Path(verts, codes) + cut_star2 = mpath.Path(verts + 1, codes) + + ax = plt.axes() + col = mcollections.PathCollection([cut_star2], + linewidth=5, linestyles='dashdot', + alpha=0.25, + facecolor=(1, 0, 0, 0.5), + edgecolor=(0, 0, 1, 0.75)) + ax.add_collection(col) + + patch = mpatches.PathPatch(cut_star1, + linewidth=5, linestyle='dashdot', + alpha=0.25, + facecolor=(1, 0, 0, 0.5), + edgecolor=(0, 0, 1, 0.75)) + ax.add_patch(patch) + + ax.set_xlim(-1, 2) + ax.set_ylim(-1, 2) + + +@mpl.style.context('default') +def test_patch_color_none(): + # Make sure the alpha kwarg does not override 'none' facecolor. + # Addresses issue #7478. + c = plt.Circle((0, 0), 1, facecolor='none', alpha=1) + assert c.get_facecolor()[0] == 0 + + +@image_comparison(['patch_custom_linestyle'], remove_text=True) +def test_patch_custom_linestyle(): + #: A test to check that patches and collections accept custom dash + #: patterns as linestyle and that they display correctly. + star = mpath.Path.unit_regular_star(6) + circle = mpath.Path.unit_circle() + # concatenate the star with an internal cutout of the circle + verts = np.concatenate([circle.vertices, star.vertices[::-1]]) + codes = np.concatenate([circle.codes, star.codes]) + cut_star1 = mpath.Path(verts, codes) + cut_star2 = mpath.Path(verts + 1, codes) + + ax = plt.axes() + col = mcollections.PathCollection( + [cut_star2], + linewidth=5, linestyles=[(0, (5, 7, 10, 7))], + facecolor=(1, 0, 0), edgecolor=(0, 0, 1)) + ax.add_collection(col) + + patch = mpatches.PathPatch( + cut_star1, + linewidth=5, linestyle=(0, (5, 7, 10, 7)), + facecolor=(1, 0, 0), edgecolor=(0, 0, 1)) + ax.add_patch(patch) + + ax.set_xlim(-1, 2) + ax.set_ylim(-1, 2) + + +def test_patch_linestyle_accents(): + #: Test if linestyle can also be specified with short mnemonics like "--" + #: c.f. GitHub issue #2136 + star = mpath.Path.unit_regular_star(6) + circle = mpath.Path.unit_circle() + # concatenate the star with an internal cutout of the circle + verts = np.concatenate([circle.vertices, star.vertices[::-1]]) + codes = np.concatenate([circle.codes, star.codes]) + + linestyles = ["-", "--", "-.", ":", + "solid", "dashed", "dashdot", "dotted"] + + fig, ax = plt.subplots() + for i, ls in enumerate(linestyles): + star = mpath.Path(verts + i, codes) + patch = mpatches.PathPatch(star, + linewidth=3, linestyle=ls, + facecolor=(1, 0, 0), + edgecolor=(0, 0, 1)) + ax.add_patch(patch) + + ax.set_xlim([-1, i + 1]) + ax.set_ylim([-1, i + 1]) + fig.canvas.draw() + + +@check_figures_equal(extensions=['png']) +def test_patch_linestyle_none(fig_test, fig_ref): + circle = mpath.Path.unit_circle() + + ax_test = fig_test.add_subplot() + ax_ref = fig_ref.add_subplot() + for i, ls in enumerate(['none', 'None', ' ', '']): + path = mpath.Path(circle.vertices + i, circle.codes) + patch = mpatches.PathPatch(path, + linewidth=3, linestyle=ls, + facecolor=(1, 0, 0), + edgecolor=(0, 0, 1)) + ax_test.add_patch(patch) + + patch = mpatches.PathPatch(path, + linewidth=3, linestyle='-', + facecolor=(1, 0, 0), + edgecolor='none') + ax_ref.add_patch(patch) + + ax_test.set_xlim([-1, i + 1]) + ax_test.set_ylim([-1, i + 1]) + ax_ref.set_xlim([-1, i + 1]) + ax_ref.set_ylim([-1, i + 1]) + + +def test_wedge_movement(): + param_dict = {'center': ((0, 0), (1, 1), 'set_center'), + 'r': (5, 8, 'set_radius'), + 'width': (2, 3, 'set_width'), + 'theta1': (0, 30, 'set_theta1'), + 'theta2': (45, 50, 'set_theta2')} + + init_args = {k: v[0] for k, v in param_dict.items()} + + w = mpatches.Wedge(**init_args) + for attr, (old_v, new_v, func) in param_dict.items(): + assert getattr(w, attr) == old_v + getattr(w, func)(new_v) + assert getattr(w, attr) == new_v + + +@image_comparison(['wedge_range'], remove_text=True, + tol=0.009 if platform.machine() == 'arm64' else 0) +def test_wedge_range(): + ax = plt.axes() + + t1 = 2.313869244286224 + + args = [[52.31386924, 232.31386924], + [52.313869244286224, 232.31386924428622], + [t1, t1 + 180.0], + [0, 360], + [90, 90 + 360], + [-180, 180], + [0, 380], + [45, 46], + [46, 45]] + + for i, (theta1, theta2) in enumerate(args): + x = i % 3 + y = i // 3 + + wedge = mpatches.Wedge((x * 3, y * 3), 1, theta1, theta2, + facecolor='none', edgecolor='k', lw=3) + + ax.add_artist(wedge) + + ax.set_xlim(-2, 8) + ax.set_ylim(-2, 9) + + +def test_patch_str(): + """ + Check that patches have nice and working `str` representation. + + Note that the logic is that `__str__` is defined such that: + str(eval(str(p))) == str(p) + """ + p = mpatches.Circle(xy=(1, 2), radius=3) + assert str(p) == 'Circle(xy=(1, 2), radius=3)' + + p = mpatches.Ellipse(xy=(1, 2), width=3, height=4, angle=5) + assert str(p) == 'Ellipse(xy=(1, 2), width=3, height=4, angle=5)' + + p = mpatches.Rectangle(xy=(1, 2), width=3, height=4, angle=5) + assert str(p) == 'Rectangle(xy=(1, 2), width=3, height=4, angle=5)' + + p = mpatches.Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6) + assert str(p) == 'Wedge(center=(1, 2), r=3, theta1=4, theta2=5, width=6)' + + p = mpatches.Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7) + expected = 'Arc(xy=(1, 2), width=3, height=4, angle=5, theta1=6, theta2=7)' + assert str(p) == expected + + p = mpatches.Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2) + expected = "Annulus(xy=(1, 2), r=(3, 4), width=1, angle=2)" + assert str(p) == expected + + p = mpatches.RegularPolygon((1, 2), 20, radius=5) + assert str(p) == "RegularPolygon((1, 2), 20, radius=5, orientation=0)" + + p = mpatches.CirclePolygon(xy=(1, 2), radius=5, resolution=20) + assert str(p) == "CirclePolygon((1, 2), radius=5, resolution=20)" + + p = mpatches.FancyBboxPatch((1, 2), width=3, height=4) + assert str(p) == "FancyBboxPatch((1, 2), width=3, height=4)" + + # Further nice __str__ which cannot be `eval`uated: + path = mpath.Path([(1, 2), (2, 2), (1, 2)], closed=True) + p = mpatches.PathPatch(path) + assert str(p) == "PathPatch3((1, 2) ...)" + + p = mpatches.Polygon(np.empty((0, 2))) + assert str(p) == "Polygon0()" + + data = [[1, 2], [2, 2], [1, 2]] + p = mpatches.Polygon(data) + assert str(p) == "Polygon3((1, 2) ...)" + + p = mpatches.FancyArrowPatch(path=path) + assert str(p)[:27] == "FancyArrowPatch(Path(array(" + + p = mpatches.FancyArrowPatch((1, 2), (3, 4)) + assert str(p) == "FancyArrowPatch((1, 2)->(3, 4))" + + p = mpatches.ConnectionPatch((1, 2), (3, 4), 'data') + assert str(p) == "ConnectionPatch((1, 2), (3, 4))" + + s = mpatches.Shadow(p, 1, 1) + assert str(s) == "Shadow(ConnectionPatch((1, 2), (3, 4)))" + + # Not testing Arrow, FancyArrow here + # because they seem to exist only for historical reasons. + + +@image_comparison(['multi_color_hatch'], remove_text=True, style='default') +def test_multi_color_hatch(): + fig, ax = plt.subplots() + + rects = ax.bar(range(5), range(1, 6)) + for i, rect in enumerate(rects): + rect.set_facecolor('none') + rect.set_edgecolor(f'C{i}') + rect.set_hatch('/') + + ax.autoscale_view() + ax.autoscale(False) + + for i in range(5): + with mpl.style.context({'hatch.color': f'C{i}'}): + r = Rectangle((i - .8 / 2, 5), .8, 1, hatch='//', fc='none') + ax.add_patch(r) + + +@image_comparison(['units_rectangle.png']) +def test_units_rectangle(): + import matplotlib.testing.jpl_units as U + U.register() + + p = mpatches.Rectangle((5*U.km, 6*U.km), 1*U.km, 2*U.km) + + fig, ax = plt.subplots() + ax.add_patch(p) + ax.set_xlim([4*U.km, 7*U.km]) + ax.set_ylim([5*U.km, 9*U.km]) + + +@image_comparison(['connection_patch.png'], style='mpl20', remove_text=True, + tol=0.024 if platform.machine() == 'arm64' else 0) +def test_connection_patch(): + fig, (ax1, ax2) = plt.subplots(1, 2) + + con = mpatches.ConnectionPatch(xyA=(0.1, 0.1), xyB=(0.9, 0.9), + coordsA='data', coordsB='data', + axesA=ax2, axesB=ax1, + arrowstyle="->") + ax2.add_artist(con) + + xyA = (0.6, 1.0) # in axes coordinates + xyB = (0.0, 0.2) # x in axes coordinates, y in data coordinates + coordsA = "axes fraction" + coordsB = ax2.get_yaxis_transform() + con = mpatches.ConnectionPatch(xyA=xyA, xyB=xyB, coordsA=coordsA, + coordsB=coordsB, arrowstyle="-") + ax2.add_artist(con) + + +@check_figures_equal(extensions=["png"]) +def test_connection_patch_fig(fig_test, fig_ref): + # Test that connection patch can be added as figure artist, and that figure + # pixels count negative values from the top right corner (this API may be + # changed in the future). + ax1, ax2 = fig_test.subplots(1, 2) + con = mpatches.ConnectionPatch( + xyA=(.3, .2), coordsA="data", axesA=ax1, + xyB=(-30, -20), coordsB="figure pixels", + arrowstyle="->", shrinkB=5) + fig_test.add_artist(con) + + ax1, ax2 = fig_ref.subplots(1, 2) + bb = fig_ref.bbox + # Necessary so that pixel counts match on both sides. + plt.rcParams["savefig.dpi"] = plt.rcParams["figure.dpi"] + con = mpatches.ConnectionPatch( + xyA=(.3, .2), coordsA="data", axesA=ax1, + xyB=(bb.width - 30, bb.height - 20), coordsB="figure pixels", + arrowstyle="->", shrinkB=5) + fig_ref.add_artist(con) + + +def test_datetime_rectangle(): + # Check that creating a rectangle with timedeltas doesn't fail + from datetime import datetime, timedelta + + start = datetime(2017, 1, 1, 0, 0, 0) + delta = timedelta(seconds=16) + patch = mpatches.Rectangle((start, 0), delta, 1) + + fig, ax = plt.subplots() + ax.add_patch(patch) + + +def test_datetime_datetime_fails(): + from datetime import datetime + + start = datetime(2017, 1, 1, 0, 0, 0) + dt_delta = datetime(1970, 1, 5) # Will be 5 days if units are done wrong. + + with pytest.raises(TypeError): + mpatches.Rectangle((start, 0), dt_delta, 1) + + with pytest.raises(TypeError): + mpatches.Rectangle((0, start), 1, dt_delta) + + +def test_contains_point(): + ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0) + points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)] + path = ell.get_path() + transform = ell.get_transform() + radius = ell._process_radius(None) + expected = np.array([path.contains_point(point, + transform, + radius) for point in points]) + result = np.array([ell.contains_point(point) for point in points]) + assert np.all(result == expected) + + +def test_contains_points(): + ell = mpatches.Ellipse((0.5, 0.5), 0.5, 1.0) + points = [(0.0, 0.5), (0.2, 0.5), (0.25, 0.5), (0.5, 0.5)] + path = ell.get_path() + transform = ell.get_transform() + radius = ell._process_radius(None) + expected = path.contains_points(points, transform, radius) + result = ell.contains_points(points) + assert np.all(result == expected) + + +# Currently fails with pdf/svg, probably because some parts assume a dpi of 72. +@check_figures_equal(extensions=["png"]) +def test_shadow(fig_test, fig_ref): + xy = np.array([.2, .3]) + dxy = np.array([.1, .2]) + # We need to work around the nonsensical (dpi-dependent) interpretation of + # offsets by the Shadow class... + plt.rcParams["savefig.dpi"] = "figure" + # Test image. + a1 = fig_test.subplots() + rect = mpatches.Rectangle(xy=xy, width=.5, height=.5) + shadow = mpatches.Shadow(rect, ox=dxy[0], oy=dxy[1]) + a1.add_patch(rect) + a1.add_patch(shadow) + # Reference image. + a2 = fig_ref.subplots() + rect = mpatches.Rectangle(xy=xy, width=.5, height=.5) + shadow = mpatches.Rectangle( + xy=xy + fig_ref.dpi / 72 * dxy, width=.5, height=.5, + fc=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3, + ec=np.asarray(mcolors.to_rgb(rect.get_facecolor())) * .3, + alpha=.5) + a2.add_patch(shadow) + a2.add_patch(rect) + + +def test_fancyarrow_units(): + from datetime import datetime + # Smoke test to check that FancyArrowPatch works with units + dtime = datetime(2000, 1, 1) + fig, ax = plt.subplots() + arrow = FancyArrowPatch((0, dtime), (0.01, dtime)) + + +def test_fancyarrow_setdata(): + fig, ax = plt.subplots() + arrow = ax.arrow(0, 0, 10, 10, head_length=5, head_width=1, width=.5) + expected1 = np.array( + [[13.54, 13.54], + [10.35, 9.65], + [10.18, 9.82], + [0.18, -0.18], + [-0.18, 0.18], + [9.82, 10.18], + [9.65, 10.35], + [13.54, 13.54]] + ) + assert np.allclose(expected1, np.round(arrow.verts, 2)) + + expected2 = np.array( + [[16.71, 16.71], + [16.71, 15.29], + [16.71, 15.29], + [1.71, 0.29], + [0.29, 1.71], + [15.29, 16.71], + [15.29, 16.71], + [16.71, 16.71]] + ) + arrow.set_data( + x=1, y=1, dx=15, dy=15, width=2, head_width=2, head_length=1 + ) + assert np.allclose(expected2, np.round(arrow.verts, 2)) + + +@image_comparison(["large_arc.svg"], style="mpl20") +def test_large_arc(): + fig, (ax1, ax2) = plt.subplots(1, 2) + x = 210 + y = -2115 + diameter = 4261 + for ax in [ax1, ax2]: + a = Arc((x, y), diameter, diameter, lw=2, color='k') + ax.add_patch(a) + ax.set_axis_off() + ax.set_aspect('equal') + # force the high accuracy case + ax1.set_xlim(7, 8) + ax1.set_ylim(5, 6) + + # force the low accuracy case + ax2.set_xlim(-25000, 18000) + ax2.set_ylim(-20000, 6600) + + +@image_comparison(["all_quadrants_arcs.svg"], style="mpl20") +def test_rotated_arcs(): + fig, ax_arr = plt.subplots(2, 2, squeeze=False, figsize=(10, 10)) + + scale = 10_000_000 + diag_centers = ((-1, -1), (-1, 1), (1, 1), (1, -1)) + on_axis_centers = ((0, 1), (1, 0), (0, -1), (-1, 0)) + skews = ((2, 2), (2, 1/10), (2, 1/100), (2, 1/1000)) + + for ax, (sx, sy) in zip(ax_arr.ravel(), skews): + k = 0 + for prescale, centers in zip((1 - .0001, (1 - .0001) / np.sqrt(2)), + (on_axis_centers, diag_centers)): + for j, (x_sign, y_sign) in enumerate(centers, start=k): + a = Arc( + (x_sign * scale * prescale, + y_sign * scale * prescale), + scale * sx, + scale * sy, + lw=4, + color=f"C{j}", + zorder=1 + j, + angle=np.rad2deg(np.arctan2(y_sign, x_sign)) % 360, + label=f'big {j}', + gid=f'big {j}' + ) + ax.add_patch(a) + + k = j+1 + ax.set_xlim(-scale / 4000, scale / 4000) + ax.set_ylim(-scale / 4000, scale / 4000) + ax.axhline(0, color="k") + ax.axvline(0, color="k") + ax.set_axis_off() + ax.set_aspect("equal") + + +def test_fancyarrow_shape_error(): + with pytest.raises(ValueError, match="Got unknown shape: 'foo'"): + FancyArrow(0, 0, 0.2, 0.2, shape='foo') + + +@pytest.mark.parametrize('fmt, match', ( + ("foo", "Unknown style: 'foo'"), + ("Round,foo", "Incorrect style argument: 'Round,foo'"), +)) +def test_boxstyle_errors(fmt, match): + with pytest.raises(ValueError, match=match): + BoxStyle(fmt) + + +@image_comparison(baseline_images=['annulus'], extensions=['png']) +def test_annulus(): + + fig, ax = plt.subplots() + cir = Annulus((0.5, 0.5), 0.2, 0.05, fc='g') # circular annulus + ell = Annulus((0.5, 0.5), (0.5, 0.3), 0.1, 45, # elliptical + fc='m', ec='b', alpha=0.5, hatch='xxx') + ax.add_patch(cir) + ax.add_patch(ell) + ax.set_aspect('equal') + + +@image_comparison(baseline_images=['annulus'], extensions=['png']) +def test_annulus_setters(): + + fig, ax = plt.subplots() + cir = Annulus((0., 0.), 0.2, 0.01, fc='g') # circular annulus + ell = Annulus((0., 0.), (1, 2), 0.1, 0, # elliptical + fc='m', ec='b', alpha=0.5, hatch='xxx') + ax.add_patch(cir) + ax.add_patch(ell) + ax.set_aspect('equal') + + cir.center = (0.5, 0.5) + cir.radii = 0.2 + cir.width = 0.05 + + ell.center = (0.5, 0.5) + ell.radii = (0.5, 0.3) + ell.width = 0.1 + ell.angle = 45 + + +@image_comparison(baseline_images=['annulus'], extensions=['png']) +def test_annulus_setters2(): + + fig, ax = plt.subplots() + cir = Annulus((0., 0.), 0.2, 0.01, fc='g') # circular annulus + ell = Annulus((0., 0.), (1, 2), 0.1, 0, # elliptical + fc='m', ec='b', alpha=0.5, hatch='xxx') + ax.add_patch(cir) + ax.add_patch(ell) + ax.set_aspect('equal') + + cir.center = (0.5, 0.5) + cir.set_semimajor(0.2) + cir.set_semiminor(0.2) + assert cir.radii == (0.2, 0.2) + cir.width = 0.05 + + ell.center = (0.5, 0.5) + ell.set_semimajor(0.5) + ell.set_semiminor(0.3) + assert ell.radii == (0.5, 0.3) + ell.width = 0.1 + ell.angle = 45 + + +def test_degenerate_polygon(): + point = [0, 0] + correct_extents = Bbox([point, point]).extents + assert np.all(Polygon([point]).get_extents().extents == correct_extents) + + +@pytest.mark.parametrize('kwarg', ('edgecolor', 'facecolor')) +def test_color_override_warning(kwarg): + with pytest.warns(UserWarning, + match="Setting the 'color' property will override " + "the edgecolor or facecolor properties."): + Patch(color='black', **{kwarg: 'black'}) + + +def test_empty_verts(): + poly = Polygon(np.zeros((0, 2))) + assert poly.get_verts() == [] + + +def test_default_antialiased(): + patch = Patch() + + patch.set_antialiased(not rcParams['patch.antialiased']) + assert patch.get_antialiased() == (not rcParams['patch.antialiased']) + # Check that None resets the state + patch.set_antialiased(None) + assert patch.get_antialiased() == rcParams['patch.antialiased'] + + +def test_default_linestyle(): + patch = Patch() + patch.set_linestyle('--') + patch.set_linestyle(None) + assert patch.get_linestyle() == 'solid' + + +def test_default_capstyle(): + patch = Patch() + assert patch.get_capstyle() == 'butt' + + +def test_default_joinstyle(): + patch = Patch() + assert patch.get_joinstyle() == 'miter' + + +@image_comparison(["autoscale_arc"], extensions=['png', 'svg'], + style="mpl20", remove_text=True) +def test_autoscale_arc(): + fig, axs = plt.subplots(1, 3, figsize=(4, 1)) + arc_lists = ( + [Arc((0, 0), 1, 1, theta1=0, theta2=90)], + [Arc((0.5, 0.5), 1.5, 0.5, theta1=10, theta2=20)], + [Arc((0.5, 0.5), 1.5, 0.5, theta1=10, theta2=20), + Arc((0.5, 0.5), 2.5, 0.5, theta1=110, theta2=120), + Arc((0.5, 0.5), 3.5, 0.5, theta1=210, theta2=220), + Arc((0.5, 0.5), 4.5, 0.5, theta1=310, theta2=320)]) + + for ax, arcs in zip(axs, arc_lists): + for arc in arcs: + ax.add_patch(arc) + ax.autoscale() + + +@check_figures_equal(extensions=["png", 'svg', 'pdf', 'eps']) +def test_arc_in_collection(fig_test, fig_ref): + arc1 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20) + arc2 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20) + col = mcollections.PatchCollection(patches=[arc2], facecolors='none', + edgecolors='k') + fig_ref.subplots().add_patch(arc1) + fig_test.subplots().add_collection(col) + + +@check_figures_equal(extensions=["png", 'svg', 'pdf', 'eps']) +def test_modifying_arc(fig_test, fig_ref): + arc1 = Arc([.5, .5], .5, 1, theta1=0, theta2=60, angle=20) + arc2 = Arc([.5, .5], 1.5, 1, theta1=0, theta2=60, angle=10) + fig_ref.subplots().add_patch(arc1) + fig_test.subplots().add_patch(arc2) + arc2.set_width(.5) + arc2.set_angle(20) + + +def test_arrow_set_data(): + fig, ax = plt.subplots() + arrow = mpl.patches.Arrow(2, 0, 0, 10) + expected1 = np.array( + [[1.9, 0.], + [2.1, -0.], + [2.1, 8.], + [2.3, 8.], + [2., 10.], + [1.7, 8.], + [1.9, 8.], + [1.9, 0.]] + ) + assert np.allclose(expected1, np.round(arrow.get_verts(), 2)) + + expected2 = np.array( + [[0.39, 0.04], + [0.61, -0.04], + [3.01, 6.36], + [3.24, 6.27], + [3.5, 8.], + [2.56, 6.53], + [2.79, 6.44], + [0.39, 0.04]] + ) + arrow.set_data(x=.5, dx=3, dy=8, width=1.2) + assert np.allclose(expected2, np.round(arrow.get_verts(), 2)) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py new file mode 100644 index 0000000000000000000000000000000000000000..a077aede8f8b0164dccd9d58c71fa17dfcf35cc7 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_pyplot.py @@ -0,0 +1,459 @@ +import difflib + +import numpy as np +import sys +from pathlib import Path + +import pytest + +import matplotlib as mpl +from matplotlib.testing import subprocess_run_for_testing +from matplotlib import pyplot as plt + + +def test_pyplot_up_to_date(tmp_path): + pytest.importorskip("black") + + gen_script = Path(mpl.__file__).parents[2] / "tools/boilerplate.py" + if not gen_script.exists(): + pytest.skip("boilerplate.py not found") + orig_contents = Path(plt.__file__).read_text() + plt_file = tmp_path / 'pyplot.py' + plt_file.write_text(orig_contents, 'utf-8') + + subprocess_run_for_testing( + [sys.executable, str(gen_script), str(plt_file)], + check=True) + new_contents = plt_file.read_text('utf-8') + + if orig_contents != new_contents: + diff_msg = '\n'.join( + difflib.unified_diff( + orig_contents.split('\n'), new_contents.split('\n'), + fromfile='found pyplot.py', + tofile='expected pyplot.py', + n=0, lineterm='')) + pytest.fail( + "pyplot.py is not up-to-date. Please run " + "'python tools/boilerplate.py' to update pyplot.py. " + "This needs to be done from an environment where your " + "current working copy is installed (e.g. 'pip install -e'd). " + "Here is a diff of unexpected differences:\n%s" % diff_msg + ) + + +def test_copy_docstring_and_deprecators(recwarn): + @mpl._api.rename_parameter(mpl.__version__, "old", "new") + @mpl._api.make_keyword_only(mpl.__version__, "kwo") + def func(new, kwo=None): + pass + + @plt._copy_docstring_and_deprecators(func) + def wrapper_func(new, kwo=None): + pass + + wrapper_func(None) + wrapper_func(new=None) + wrapper_func(None, kwo=None) + wrapper_func(new=None, kwo=None) + assert not recwarn + with pytest.warns(mpl.MatplotlibDeprecationWarning): + wrapper_func(old=None) + with pytest.warns(mpl.MatplotlibDeprecationWarning): + wrapper_func(None, None) + + +def test_pyplot_box(): + fig, ax = plt.subplots() + plt.box(False) + assert not ax.get_frame_on() + plt.box(True) + assert ax.get_frame_on() + plt.box() + assert not ax.get_frame_on() + plt.box() + assert ax.get_frame_on() + + +def test_stackplot_smoke(): + # Small smoke test for stackplot (see #12405) + plt.stackplot([1, 2, 3], [1, 2, 3]) + + +def test_nrows_error(): + with pytest.raises(TypeError): + plt.subplot(nrows=1) + with pytest.raises(TypeError): + plt.subplot(ncols=1) + + +def test_ioff(): + plt.ion() + assert mpl.is_interactive() + with plt.ioff(): + assert not mpl.is_interactive() + assert mpl.is_interactive() + + plt.ioff() + assert not mpl.is_interactive() + with plt.ioff(): + assert not mpl.is_interactive() + assert not mpl.is_interactive() + + +def test_ion(): + plt.ioff() + assert not mpl.is_interactive() + with plt.ion(): + assert mpl.is_interactive() + assert not mpl.is_interactive() + + plt.ion() + assert mpl.is_interactive() + with plt.ion(): + assert mpl.is_interactive() + assert mpl.is_interactive() + + +def test_nested_ion_ioff(): + # initial state is interactive + plt.ion() + + # mixed ioff/ion + with plt.ioff(): + assert not mpl.is_interactive() + with plt.ion(): + assert mpl.is_interactive() + assert not mpl.is_interactive() + assert mpl.is_interactive() + + # redundant contexts + with plt.ioff(): + with plt.ioff(): + assert not mpl.is_interactive() + assert mpl.is_interactive() + + with plt.ion(): + plt.ioff() + assert mpl.is_interactive() + + # initial state is not interactive + plt.ioff() + + # mixed ioff/ion + with plt.ion(): + assert mpl.is_interactive() + with plt.ioff(): + assert not mpl.is_interactive() + assert mpl.is_interactive() + assert not mpl.is_interactive() + + # redundant contexts + with plt.ion(): + with plt.ion(): + assert mpl.is_interactive() + assert not mpl.is_interactive() + + with plt.ioff(): + plt.ion() + assert not mpl.is_interactive() + + +def test_close(): + try: + plt.close(1.1) + except TypeError as e: + assert str(e) == "close() argument must be a Figure, an int, " \ + "a string, or None, not " + + +def test_subplot_reuse(): + ax1 = plt.subplot(121) + assert ax1 is plt.gca() + ax2 = plt.subplot(122) + assert ax2 is plt.gca() + ax3 = plt.subplot(121) + assert ax1 is plt.gca() + assert ax1 is ax3 + + +def test_axes_kwargs(): + # plt.axes() always creates new axes, even if axes kwargs differ. + plt.figure() + ax = plt.axes() + ax1 = plt.axes() + assert ax is not None + assert ax1 is not ax + plt.close() + + plt.figure() + ax = plt.axes(projection='polar') + ax1 = plt.axes(projection='polar') + assert ax is not None + assert ax1 is not ax + plt.close() + + plt.figure() + ax = plt.axes(projection='polar') + ax1 = plt.axes() + assert ax is not None + assert ax1.name == 'rectilinear' + assert ax1 is not ax + plt.close() + + +def test_subplot_replace_projection(): + # plt.subplot() searches for axes with the same subplot spec, and if one + # exists, and the kwargs match returns it, create a new one if they do not + fig = plt.figure() + ax = plt.subplot(1, 2, 1) + ax1 = plt.subplot(1, 2, 1) + ax2 = plt.subplot(1, 2, 2) + ax3 = plt.subplot(1, 2, 1, projection='polar') + ax4 = plt.subplot(1, 2, 1, projection='polar') + assert ax is not None + assert ax1 is ax + assert ax2 is not ax + assert ax3 is not ax + assert ax3 is ax4 + + assert ax in fig.axes + assert ax2 in fig.axes + assert ax3 in fig.axes + + assert ax.name == 'rectilinear' + assert ax2.name == 'rectilinear' + assert ax3.name == 'polar' + + +def test_subplot_kwarg_collision(): + ax1 = plt.subplot(projection='polar', theta_offset=0) + ax2 = plt.subplot(projection='polar', theta_offset=0) + assert ax1 is ax2 + ax1.remove() + ax3 = plt.subplot(projection='polar', theta_offset=1) + assert ax1 is not ax3 + assert ax1 not in plt.gcf().axes + + +def test_gca(): + # plt.gca() returns an existing axes, unless there were no axes. + plt.figure() + ax = plt.gca() + ax1 = plt.gca() + assert ax is not None + assert ax1 is ax + plt.close() + + +def test_subplot_projection_reuse(): + # create an Axes + ax1 = plt.subplot(111) + # check that it is current + assert ax1 is plt.gca() + # make sure we get it back if we ask again + assert ax1 is plt.subplot(111) + # remove it + ax1.remove() + # create a polar plot + ax2 = plt.subplot(111, projection='polar') + assert ax2 is plt.gca() + # this should have deleted the first axes + assert ax1 not in plt.gcf().axes + # assert we get it back if no extra parameters passed + assert ax2 is plt.subplot(111) + ax2.remove() + # now check explicitly setting the projection to rectilinear + # makes a new axes + ax3 = plt.subplot(111, projection='rectilinear') + assert ax3 is plt.gca() + assert ax3 is not ax2 + assert ax2 not in plt.gcf().axes + + +def test_subplot_polar_normalization(): + ax1 = plt.subplot(111, projection='polar') + ax2 = plt.subplot(111, polar=True) + ax3 = plt.subplot(111, polar=True, projection='polar') + assert ax1 is ax2 + assert ax1 is ax3 + + with pytest.raises(ValueError, + match="polar=True, yet projection='3d'"): + ax2 = plt.subplot(111, polar=True, projection='3d') + + +def test_subplot_change_projection(): + created_axes = set() + ax = plt.subplot() + created_axes.add(ax) + projections = ('aitoff', 'hammer', 'lambert', 'mollweide', + 'polar', 'rectilinear', '3d') + for proj in projections: + ax.remove() + ax = plt.subplot(projection=proj) + assert ax is plt.subplot() + assert ax.name == proj + created_axes.add(ax) + # Check that each call created a new Axes. + assert len(created_axes) == 1 + len(projections) + + +def test_polar_second_call(): + # the first call creates the axes with polar projection + ln1, = plt.polar(0., 1., 'ro') + assert isinstance(ln1, mpl.lines.Line2D) + # the second call should reuse the existing axes + ln2, = plt.polar(1.57, .5, 'bo') + assert isinstance(ln2, mpl.lines.Line2D) + assert ln1.axes is ln2.axes + + +def test_fallback_position(): + # check that position kwarg works if rect not supplied + axref = plt.axes([0.2, 0.2, 0.5, 0.5]) + axtest = plt.axes(position=[0.2, 0.2, 0.5, 0.5]) + np.testing.assert_allclose(axtest.bbox.get_points(), + axref.bbox.get_points()) + + # check that position kwarg ignored if rect is supplied + axref = plt.axes([0.2, 0.2, 0.5, 0.5]) + axtest = plt.axes([0.2, 0.2, 0.5, 0.5], position=[0.1, 0.1, 0.8, 0.8]) + np.testing.assert_allclose(axtest.bbox.get_points(), + axref.bbox.get_points()) + + +def test_set_current_figure_via_subfigure(): + fig1 = plt.figure() + subfigs = fig1.subfigures(2) + + plt.figure() + assert plt.gcf() != fig1 + + current = plt.figure(subfigs[1]) + assert plt.gcf() == fig1 + assert current == fig1 + + +def test_set_current_axes_on_subfigure(): + fig = plt.figure() + subfigs = fig.subfigures(2) + + ax = subfigs[0].subplots(1, squeeze=True) + subfigs[1].subplots(1, squeeze=True) + + assert plt.gca() != ax + plt.sca(ax) + assert plt.gca() == ax + + +def test_pylab_integration(): + IPython = pytest.importorskip("IPython") + mpl.testing.subprocess_run_helper( + IPython.start_ipython, + "--pylab", + "-c", + ";".join(( + "import matplotlib.pyplot as plt", + "assert plt._REPL_DISPLAYHOOK == plt._ReplDisplayHook.IPYTHON", + )), + timeout=60, + ) + + +def test_doc_pyplot_summary(): + """Test that pyplot_summary lists all the plot functions.""" + pyplot_docs = Path(__file__).parent / '../../../doc/api/pyplot_summary.rst' + if not pyplot_docs.exists(): + pytest.skip("Documentation sources not available") + + def extract_documented_functions(lines): + """ + Return a list of all the functions that are mentioned in the + autosummary blocks contained in *lines*. + + An autosummary block looks like this:: + + .. autosummary:: + :toctree: _as_gen + :template: autosummary.rst + :nosignatures: + + plot + plot_date + + """ + functions = [] + in_autosummary = False + for line in lines: + if not in_autosummary: + if line.startswith(".. autosummary::"): + in_autosummary = True + else: + if not line or line.startswith(" :"): + # empty line or autosummary parameter + continue + if not line[0].isspace(): + # no more indentation: end of autosummary block + in_autosummary = False + continue + functions.append(line.strip()) + return functions + + lines = pyplot_docs.read_text().split("\n") + doc_functions = set(extract_documented_functions(lines)) + plot_commands = set(plt._get_pyplot_commands()) + missing = plot_commands.difference(doc_functions) + if missing: + raise AssertionError( + f"The following pyplot functions are not listed in the " + f"documentation. Please add them to doc/api/pyplot_summary.rst: " + f"{missing!r}") + extra = doc_functions.difference(plot_commands) + if extra: + raise AssertionError( + f"The following functions are listed in the pyplot documentation, " + f"but they do not exist in pyplot. " + f"Please remove them from doc/api/pyplot_summary.rst: {extra!r}") + + +def test_minor_ticks(): + plt.figure() + plt.plot(np.arange(1, 10)) + tick_pos, tick_labels = plt.xticks(minor=True) + assert np.all(tick_labels == np.array([], dtype=np.float64)) + assert tick_labels == [] + + plt.yticks(ticks=[3.5, 6.5], labels=["a", "b"], minor=True) + ax = plt.gca() + tick_pos = ax.get_yticks(minor=True) + tick_labels = ax.get_yticklabels(minor=True) + assert np.all(tick_pos == np.array([3.5, 6.5])) + assert [l.get_text() for l in tick_labels] == ['a', 'b'] + + +def test_switch_backend_no_close(): + plt.switch_backend('agg') + fig = plt.figure() + fig = plt.figure() + assert len(plt.get_fignums()) == 2 + plt.switch_backend('agg') + assert len(plt.get_fignums()) == 2 + with pytest.warns(mpl.MatplotlibDeprecationWarning): + plt.switch_backend('svg') + assert len(plt.get_fignums()) == 0 + + +def figure_hook_example(figure): + figure._test_was_here = True + + +def test_figure_hook(): + + test_rc = { + 'figure.hooks': ['matplotlib.tests.test_pyplot:figure_hook_example'] + } + with mpl.rc_context(test_rc): + fig = plt.figure() + + assert fig._test_was_here diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py new file mode 100644 index 0000000000000000000000000000000000000000..6624e3b17ba52e680e7f7e2037fdac334977b14e --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_sphinxext.py @@ -0,0 +1,225 @@ +"""Tests for tinypages build using sphinx extensions.""" + +import filecmp +import os +from pathlib import Path +import shutil +import sys + +from matplotlib.testing import subprocess_run_for_testing +import pytest + + +pytest.importorskip('sphinx', + minversion=None if sys.version_info < (3, 10) else '4.1.3') + + +def build_sphinx_html(source_dir, doctree_dir, html_dir, extra_args=None): + # Build the pages with warnings turned into errors + extra_args = [] if extra_args is None else extra_args + cmd = [sys.executable, '-msphinx', '-W', '-b', 'html', + '-d', str(doctree_dir), str(source_dir), str(html_dir), *extra_args] + proc = subprocess_run_for_testing( + cmd, capture_output=True, text=True, + env={**os.environ, "MPLBACKEND": ""}) + out = proc.stdout + err = proc.stderr + + assert proc.returncode == 0, \ + f"sphinx build failed with stdout:\n{out}\nstderr:\n{err}\n" + if err: + pytest.fail(f"sphinx build emitted the following warnings:\n{err}") + + assert html_dir.is_dir() + + +def test_tinypages(tmp_path): + shutil.copytree(Path(__file__).parent / 'tinypages', tmp_path, + dirs_exist_ok=True) + html_dir = tmp_path / '_build' / 'html' + img_dir = html_dir / '_images' + doctree_dir = tmp_path / 'doctrees' + # Build the pages with warnings turned into errors + cmd = [sys.executable, '-msphinx', '-W', '-b', 'html', + '-d', str(doctree_dir), + str(Path(__file__).parent / 'tinypages'), str(html_dir)] + # On CI, gcov emits warnings (due to agg headers being included with the + # same name in multiple extension modules -- but we don't care about their + # coverage anyways); hide them using GCOV_ERROR_FILE. + proc = subprocess_run_for_testing( + cmd, capture_output=True, text=True, + env={**os.environ, "MPLBACKEND": "", "GCOV_ERROR_FILE": os.devnull} + ) + out = proc.stdout + err = proc.stderr + + # Build the pages with warnings turned into errors + build_sphinx_html(tmp_path, doctree_dir, html_dir) + + def plot_file(num): + return img_dir / f'some_plots-{num}.png' + + def plot_directive_file(num): + # This is always next to the doctree dir. + return doctree_dir.parent / 'plot_directive' / f'some_plots-{num}.png' + + range_10, range_6, range_4 = [plot_file(i) for i in range(1, 4)] + # Plot 5 is range(6) plot + assert filecmp.cmp(range_6, plot_file(5)) + # Plot 7 is range(4) plot + assert filecmp.cmp(range_4, plot_file(7)) + # Plot 11 is range(10) plot + assert filecmp.cmp(range_10, plot_file(11)) + # Plot 12 uses the old range(10) figure and the new range(6) figure + assert filecmp.cmp(range_10, plot_file('12_00')) + assert filecmp.cmp(range_6, plot_file('12_01')) + # Plot 13 shows close-figs in action + assert filecmp.cmp(range_4, plot_file(13)) + # Plot 14 has included source + html_contents = (html_dir / 'some_plots.html').read_bytes() + + assert b'# Only a comment' in html_contents + # check plot defined in external file. + assert filecmp.cmp(range_4, img_dir / 'range4.png') + assert filecmp.cmp(range_6, img_dir / 'range6_range6.png') + # check if figure caption made it into html file + assert b'This is the caption for plot 15.' in html_contents + # check if figure caption using :caption: made it into html file + assert b'Plot 17 uses the caption option.' in html_contents + # check if figure caption made it into html file + assert b'This is the caption for plot 18.' in html_contents + # check if the custom classes made it into the html file + assert b'plot-directive my-class my-other-class' in html_contents + # check that the multi-image caption is applied twice + assert html_contents.count(b'This caption applies to both plots.') == 2 + # Plot 21 is range(6) plot via an include directive. But because some of + # the previous plots are repeated, the argument to plot_file() is only 17. + assert filecmp.cmp(range_6, plot_file(17)) + # plot 22 is from the range6.py file again, but a different function + assert filecmp.cmp(range_10, img_dir / 'range6_range10.png') + + # Modify the included plot + contents = (tmp_path / 'included_plot_21.rst').read_bytes() + contents = contents.replace(b'plt.plot(range(6))', b'plt.plot(range(4))') + (tmp_path / 'included_plot_21.rst').write_bytes(contents) + # Build the pages again and check that the modified file was updated + modification_times = [plot_directive_file(i).stat().st_mtime + for i in (1, 2, 3, 5)] + build_sphinx_html(tmp_path, doctree_dir, html_dir) + assert filecmp.cmp(range_4, plot_file(17)) + # Check that the plots in the plot_directive folder weren't changed. + # (plot_directive_file(1) won't be modified, but it will be copied to html/ + # upon compilation, so plot_file(1) will be modified) + assert plot_directive_file(1).stat().st_mtime == modification_times[0] + assert plot_directive_file(2).stat().st_mtime == modification_times[1] + assert plot_directive_file(3).stat().st_mtime == modification_times[2] + assert filecmp.cmp(range_10, plot_file(1)) + assert filecmp.cmp(range_6, plot_file(2)) + assert filecmp.cmp(range_4, plot_file(3)) + # Make sure that figures marked with context are re-created (but that the + # contents are the same) + assert plot_directive_file(5).stat().st_mtime > modification_times[3] + assert filecmp.cmp(range_6, plot_file(5)) + + +def test_plot_html_show_source_link(tmp_path): + parent = Path(__file__).parent + shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py') + shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static') + doctree_dir = tmp_path / 'doctrees' + (tmp_path / 'index.rst').write_text(""" +.. plot:: + + plt.plot(range(2)) +""") + # Make sure source scripts are created by default + html_dir1 = tmp_path / '_build' / 'html1' + build_sphinx_html(tmp_path, doctree_dir, html_dir1) + assert len(list(html_dir1.glob("**/index-1.py"))) == 1 + # Make sure source scripts are NOT created when + # plot_html_show_source_link` is False + html_dir2 = tmp_path / '_build' / 'html2' + build_sphinx_html(tmp_path, doctree_dir, html_dir2, + extra_args=['-D', 'plot_html_show_source_link=0']) + assert len(list(html_dir2.glob("**/index-1.py"))) == 0 + + +@pytest.mark.parametrize('plot_html_show_source_link', [0, 1]) +def test_show_source_link_true(tmp_path, plot_html_show_source_link): + # Test that a source link is generated if :show-source-link: is true, + # whether or not plot_html_show_source_link is true. + parent = Path(__file__).parent + shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py') + shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static') + doctree_dir = tmp_path / 'doctrees' + (tmp_path / 'index.rst').write_text(""" +.. plot:: + :show-source-link: true + + plt.plot(range(2)) +""") + html_dir = tmp_path / '_build' / 'html' + build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[ + '-D', f'plot_html_show_source_link={plot_html_show_source_link}']) + assert len(list(html_dir.glob("**/index-1.py"))) == 1 + + +@pytest.mark.parametrize('plot_html_show_source_link', [0, 1]) +def test_show_source_link_false(tmp_path, plot_html_show_source_link): + # Test that a source link is NOT generated if :show-source-link: is false, + # whether or not plot_html_show_source_link is true. + parent = Path(__file__).parent + shutil.copyfile(parent / 'tinypages/conf.py', tmp_path / 'conf.py') + shutil.copytree(parent / 'tinypages/_static', tmp_path / '_static') + doctree_dir = tmp_path / 'doctrees' + (tmp_path / 'index.rst').write_text(""" +.. plot:: + :show-source-link: false + + plt.plot(range(2)) +""") + html_dir = tmp_path / '_build' / 'html' + build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[ + '-D', f'plot_html_show_source_link={plot_html_show_source_link}']) + assert len(list(html_dir.glob("**/index-1.py"))) == 0 + + +def test_srcset_version(tmp_path): + shutil.copytree(Path(__file__).parent / 'tinypages', tmp_path, + dirs_exist_ok=True) + html_dir = tmp_path / '_build' / 'html' + img_dir = html_dir / '_images' + doctree_dir = tmp_path / 'doctrees' + + build_sphinx_html(tmp_path, doctree_dir, html_dir, extra_args=[ + '-D', 'plot_srcset=2x']) + + def plot_file(num, suff=''): + return img_dir / f'some_plots-{num}{suff}.png' + + # check some-plots + for ind in [1, 2, 3, 5, 7, 11, 13, 15, 17]: + assert plot_file(ind).exists() + assert plot_file(ind, suff='.2x').exists() + + assert (img_dir / 'nestedpage-index-1.png').exists() + assert (img_dir / 'nestedpage-index-1.2x.png').exists() + assert (img_dir / 'nestedpage-index-2.png').exists() + assert (img_dir / 'nestedpage-index-2.2x.png').exists() + assert (img_dir / 'nestedpage2-index-1.png').exists() + assert (img_dir / 'nestedpage2-index-1.2x.png').exists() + assert (img_dir / 'nestedpage2-index-2.png').exists() + assert (img_dir / 'nestedpage2-index-2.2x.png').exists() + + # Check html for srcset + + assert ('srcset="_images/some_plots-1.png, _images/some_plots-1.2x.png 2.00x"' + in (html_dir / 'some_plots.html').read_text(encoding='utf-8')) + + st = ('srcset="../_images/nestedpage-index-1.png, ' + '../_images/nestedpage-index-1.2x.png 2.00x"') + assert st in (html_dir / 'nestedpage/index.html').read_text(encoding='utf-8') + + st = ('srcset="../_images/nestedpage2-index-2.png, ' + '../_images/nestedpage2-index-2.2x.png 2.00x"') + assert st in (html_dir / 'nestedpage2/index.html').read_text(encoding='utf-8') diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_subplots.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_subplots.py new file mode 100644 index 0000000000000000000000000000000000000000..70215c9531ba00ec3951e66e629e62f637016acf --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_subplots.py @@ -0,0 +1,287 @@ +import itertools +import platform + +import numpy as np +import pytest + +from matplotlib.axes import Axes, SubplotBase +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import check_figures_equal, image_comparison + + +def check_shared(axs, x_shared, y_shared): + """ + x_shared and y_shared are n x n boolean matrices; entry (i, j) indicates + whether the x (or y) axes of subplots i and j should be shared. + """ + for (i1, ax1), (i2, ax2), (i3, (name, shared)) in itertools.product( + enumerate(axs), + enumerate(axs), + enumerate(zip("xy", [x_shared, y_shared]))): + if i2 <= i1: + continue + assert axs[0]._shared_axes[name].joined(ax1, ax2) == shared[i1, i2], \ + "axes %i and %i incorrectly %ssharing %s axis" % ( + i1, i2, "not " if shared[i1, i2] else "", name) + + +def check_ticklabel_visible(axs, x_visible, y_visible): + """Check that the x and y ticklabel visibility is as specified.""" + for i, (ax, vx, vy) in enumerate(zip(axs, x_visible, y_visible)): + for l in ax.get_xticklabels() + [ax.xaxis.offsetText]: + assert l.get_visible() == vx, \ + f"Visibility of x axis #{i} is incorrectly {vx}" + for l in ax.get_yticklabels() + [ax.yaxis.offsetText]: + assert l.get_visible() == vy, \ + f"Visibility of y axis #{i} is incorrectly {vy}" + # axis label "visibility" is toggled by label_outer by resetting the + # label to empty, but it can also be empty to start with. + if not vx: + assert ax.get_xlabel() == "" + if not vy: + assert ax.get_ylabel() == "" + + +def check_tick1_visible(axs, x_visible, y_visible): + """ + Check that the x and y tick visibility is as specified. + + Note: This only checks the tick1line, i.e. bottom / left ticks. + """ + for ax, visible, in zip(axs, x_visible): + for tick in ax.xaxis.get_major_ticks(): + assert tick.tick1line.get_visible() == visible + for ax, y_visible, in zip(axs, y_visible): + for tick in ax.yaxis.get_major_ticks(): + assert tick.tick1line.get_visible() == visible + + +def test_shared(): + rdim = (4, 4, 2) + share = { + 'all': np.ones(rdim[:2], dtype=bool), + 'none': np.zeros(rdim[:2], dtype=bool), + 'row': np.array([ + [False, True, False, False], + [True, False, False, False], + [False, False, False, True], + [False, False, True, False]]), + 'col': np.array([ + [False, False, True, False], + [False, False, False, True], + [True, False, False, False], + [False, True, False, False]]), + } + visible = { + 'x': { + 'all': [False, False, True, True], + 'col': [False, False, True, True], + 'row': [True] * 4, + 'none': [True] * 4, + False: [True] * 4, + True: [False, False, True, True], + }, + 'y': { + 'all': [True, False, True, False], + 'col': [True] * 4, + 'row': [True, False, True, False], + 'none': [True] * 4, + False: [True] * 4, + True: [True, False, True, False], + }, + } + share[False] = share['none'] + share[True] = share['all'] + + # test default + f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2) + axs = [a1, a2, a3, a4] + check_shared(axs, share['none'], share['none']) + plt.close(f) + + # test all option combinations + ops = [False, True, 'all', 'none', 'row', 'col', 0, 1] + for xo in ops: + for yo in ops: + f, ((a1, a2), (a3, a4)) = plt.subplots(2, 2, sharex=xo, sharey=yo) + axs = [a1, a2, a3, a4] + check_shared(axs, share[xo], share[yo]) + check_ticklabel_visible(axs, visible['x'][xo], visible['y'][yo]) + plt.close(f) + + +@pytest.mark.parametrize('remove_ticks', [True, False]) +def test_label_outer(remove_ticks): + f, axs = plt.subplots(2, 2, sharex=True, sharey=True) + for ax in axs.flat: + ax.set(xlabel="foo", ylabel="bar") + ax.label_outer(remove_inner_ticks=remove_ticks) + check_ticklabel_visible( + axs.flat, [False, False, True, True], [True, False, True, False]) + if remove_ticks: + check_tick1_visible( + axs.flat, [False, False, True, True], [True, False, True, False]) + else: + check_tick1_visible( + axs.flat, [True, True, True, True], [True, True, True, True]) + + +def test_label_outer_span(): + fig = plt.figure() + gs = fig.add_gridspec(3, 3) + # +---+---+---+ + # | 1 | | + # +---+---+---+ + # | | | 3 | + # + 2 +---+---+ + # | | 4 | | + # +---+---+---+ + a1 = fig.add_subplot(gs[0, 0:2]) + a2 = fig.add_subplot(gs[1:3, 0]) + a3 = fig.add_subplot(gs[1, 2]) + a4 = fig.add_subplot(gs[2, 1]) + for ax in fig.axes: + ax.label_outer() + check_ticklabel_visible( + fig.axes, [False, True, False, True], [True, True, False, False]) + + +def test_label_outer_non_gridspec(): + ax = plt.axes((0, 0, 1, 1)) + ax.label_outer() # Does nothing. + check_ticklabel_visible([ax], [True], [True]) + + +def test_shared_and_moved(): + # test if sharey is on, but then tick_left is called that labels don't + # re-appear. Seaborn does this just to be sure yaxis is on left... + f, (a1, a2) = plt.subplots(1, 2, sharey=True) + check_ticklabel_visible([a2], [True], [False]) + a2.yaxis.tick_left() + check_ticklabel_visible([a2], [True], [False]) + + f, (a1, a2) = plt.subplots(2, 1, sharex=True) + check_ticklabel_visible([a1], [False], [True]) + a2.xaxis.tick_bottom() + check_ticklabel_visible([a1], [False], [True]) + + +def test_exceptions(): + # TODO should this test more options? + with pytest.raises(ValueError): + plt.subplots(2, 2, sharex='blah') + with pytest.raises(ValueError): + plt.subplots(2, 2, sharey='blah') + + +@image_comparison(['subplots_offset_text'], + tol=0.028 if platform.machine() == 'arm64' else 0) +def test_subplots_offsettext(): + x = np.arange(0, 1e10, 1e9) + y = np.arange(0, 100, 10)+1e4 + fig, axs = plt.subplots(2, 2, sharex='col', sharey='all') + axs[0, 0].plot(x, x) + axs[1, 0].plot(x, x) + axs[0, 1].plot(y, x) + axs[1, 1].plot(y, x) + + +@pytest.mark.parametrize("top", [True, False]) +@pytest.mark.parametrize("bottom", [True, False]) +@pytest.mark.parametrize("left", [True, False]) +@pytest.mark.parametrize("right", [True, False]) +def test_subplots_hide_ticklabels(top, bottom, left, right): + # Ideally, we would also test offset-text visibility (and remove + # test_subplots_offsettext), but currently, setting rcParams fails to move + # the offset texts as well. + with plt.rc_context({"xtick.labeltop": top, "xtick.labelbottom": bottom, + "ytick.labelleft": left, "ytick.labelright": right}): + axs = plt.figure().subplots(3, 3, sharex=True, sharey=True) + for (i, j), ax in np.ndenumerate(axs): + xtop = ax.xaxis._major_tick_kw["label2On"] + xbottom = ax.xaxis._major_tick_kw["label1On"] + yleft = ax.yaxis._major_tick_kw["label1On"] + yright = ax.yaxis._major_tick_kw["label2On"] + assert xtop == (top and i == 0) + assert xbottom == (bottom and i == 2) + assert yleft == (left and j == 0) + assert yright == (right and j == 2) + + +@pytest.mark.parametrize("xlabel_position", ["bottom", "top"]) +@pytest.mark.parametrize("ylabel_position", ["left", "right"]) +def test_subplots_hide_axislabels(xlabel_position, ylabel_position): + axs = plt.figure().subplots(3, 3, sharex=True, sharey=True) + for (i, j), ax in np.ndenumerate(axs): + ax.set(xlabel="foo", ylabel="bar") + ax.xaxis.set_label_position(xlabel_position) + ax.yaxis.set_label_position(ylabel_position) + ax.label_outer() + assert bool(ax.get_xlabel()) == ( + xlabel_position == "bottom" and i == 2 + or xlabel_position == "top" and i == 0) + assert bool(ax.get_ylabel()) == ( + ylabel_position == "left" and j == 0 + or ylabel_position == "right" and j == 2) + + +def test_get_gridspec(): + # ahem, pretty trivial, but... + fig, ax = plt.subplots() + assert ax.get_subplotspec().get_gridspec() == ax.get_gridspec() + + +def test_dont_mutate_kwargs(): + subplot_kw = {'sharex': 'all'} + gridspec_kw = {'width_ratios': [1, 2]} + fig, ax = plt.subplots(1, 2, subplot_kw=subplot_kw, + gridspec_kw=gridspec_kw) + assert subplot_kw == {'sharex': 'all'} + assert gridspec_kw == {'width_ratios': [1, 2]} + + +@pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]]) +@pytest.mark.parametrize("height_ratios", [None, [1, 2]]) +@check_figures_equal(extensions=['png']) +def test_width_and_height_ratios(fig_test, fig_ref, + height_ratios, width_ratios): + fig_test.subplots(2, 3, height_ratios=height_ratios, + width_ratios=width_ratios) + fig_ref.subplots(2, 3, gridspec_kw={ + 'height_ratios': height_ratios, + 'width_ratios': width_ratios}) + + +@pytest.mark.parametrize("width_ratios", [None, [1, 3, 2]]) +@pytest.mark.parametrize("height_ratios", [None, [1, 2]]) +@check_figures_equal(extensions=['png']) +def test_width_and_height_ratios_mosaic(fig_test, fig_ref, + height_ratios, width_ratios): + mosaic_spec = [['A', 'B', 'B'], ['A', 'C', 'D']] + fig_test.subplot_mosaic(mosaic_spec, height_ratios=height_ratios, + width_ratios=width_ratios) + fig_ref.subplot_mosaic(mosaic_spec, gridspec_kw={ + 'height_ratios': height_ratios, + 'width_ratios': width_ratios}) + + +@pytest.mark.parametrize('method,args', [ + ('subplots', (2, 3)), + ('subplot_mosaic', ('abc;def', )) + ] +) +def test_ratio_overlapping_kws(method, args): + with pytest.raises(ValueError, match='height_ratios'): + getattr(plt, method)(*args, height_ratios=[1, 2], + gridspec_kw={'height_ratios': [1, 2]}) + with pytest.raises(ValueError, match='width_ratios'): + getattr(plt, method)(*args, width_ratios=[1, 2, 3], + gridspec_kw={'width_ratios': [1, 2, 3]}) + + +def test_old_subplot_compat(): + fig = plt.figure() + assert isinstance(fig.add_subplot(), SubplotBase) + assert not isinstance(fig.add_axes(rect=[0, 0, 1, 1]), SubplotBase) + with pytest.raises(TypeError): + Axes(fig, [0, 0, 1, 1], rect=[0, 0, 1, 1]) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py new file mode 100644 index 0000000000000000000000000000000000000000..ac68a5d90b1477f1f97257f2d63f40ade82173a3 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_ticker.py @@ -0,0 +1,1875 @@ +from contextlib import nullcontext +import itertools +import locale +import logging +import re +from packaging.version import parse as parse_version + +import numpy as np +from numpy.testing import assert_almost_equal, assert_array_equal +import pytest + +import matplotlib as mpl +import matplotlib.pyplot as plt +import matplotlib.ticker as mticker + + +class TestMaxNLocator: + basic_data = [ + (20, 100, np.array([20., 40., 60., 80., 100.])), + (0.001, 0.0001, np.array([0., 0.0002, 0.0004, 0.0006, 0.0008, 0.001])), + (-1e15, 1e15, np.array([-1.0e+15, -5.0e+14, 0e+00, 5e+14, 1.0e+15])), + (0, 0.85e-50, np.arange(6) * 2e-51), + (-0.85e-50, 0, np.arange(-5, 1) * 2e-51), + ] + + integer_data = [ + (-0.1, 1.1, None, np.array([-1, 0, 1, 2])), + (-0.1, 0.95, None, np.array([-0.25, 0, 0.25, 0.5, 0.75, 1.0])), + (1, 55, [1, 1.5, 5, 6, 10], np.array([0, 15, 30, 45, 60])), + ] + + @pytest.mark.parametrize('vmin, vmax, expected', basic_data) + def test_basic(self, vmin, vmax, expected): + loc = mticker.MaxNLocator(nbins=5) + assert_almost_equal(loc.tick_values(vmin, vmax), expected) + + @pytest.mark.parametrize('vmin, vmax, steps, expected', integer_data) + def test_integer(self, vmin, vmax, steps, expected): + loc = mticker.MaxNLocator(nbins=5, integer=True, steps=steps) + assert_almost_equal(loc.tick_values(vmin, vmax), expected) + + @pytest.mark.parametrize('kwargs, errortype, match', [ + ({'foo': 0}, TypeError, + re.escape("set_params() got an unexpected keyword argument 'foo'")), + ({'steps': [2, 1]}, ValueError, "steps argument must be an increasing"), + ({'steps': 2}, ValueError, "steps argument must be an increasing"), + ({'steps': [2, 11]}, ValueError, "steps argument must be an increasing"), + ]) + def test_errors(self, kwargs, errortype, match): + with pytest.raises(errortype, match=match): + mticker.MaxNLocator(**kwargs) + + @pytest.mark.parametrize('steps, result', [ + ([1, 2, 10], [1, 2, 10]), + ([2, 10], [1, 2, 10]), + ([1, 2], [1, 2, 10]), + ([2], [1, 2, 10]), + ]) + def test_padding(self, steps, result): + loc = mticker.MaxNLocator(steps=steps) + assert (loc._steps == result).all() + + +class TestLinearLocator: + def test_basic(self): + loc = mticker.LinearLocator(numticks=3) + test_value = np.array([-0.8, -0.3, 0.2]) + assert_almost_equal(loc.tick_values(-0.8, 0.2), test_value) + + def test_zero_numticks(self): + loc = mticker.LinearLocator(numticks=0) + loc.tick_values(-0.8, 0.2) == [] + + def test_set_params(self): + """ + Create linear locator with presets={}, numticks=2 and change it to + something else. See if change was successful. Should not exception. + """ + loc = mticker.LinearLocator(numticks=2) + loc.set_params(numticks=8, presets={(0, 1): []}) + assert loc.numticks == 8 + assert loc.presets == {(0, 1): []} + + def test_presets(self): + loc = mticker.LinearLocator(presets={(1, 2): [1, 1.25, 1.75], + (0, 2): [0.5, 1.5]}) + assert loc.tick_values(1, 2) == [1, 1.25, 1.75] + assert loc.tick_values(2, 1) == [1, 1.25, 1.75] + assert loc.tick_values(0, 2) == [0.5, 1.5] + assert loc.tick_values(0.0, 2.0) == [0.5, 1.5] + assert (loc.tick_values(0, 1) == np.linspace(0, 1, 11)).all() + + +class TestMultipleLocator: + def test_basic(self): + loc = mticker.MultipleLocator(base=3.147) + test_value = np.array([-9.441, -6.294, -3.147, 0., 3.147, 6.294, + 9.441, 12.588]) + assert_almost_equal(loc.tick_values(-7, 10), test_value) + + def test_basic_with_offset(self): + loc = mticker.MultipleLocator(base=3.147, offset=1.2) + test_value = np.array([-8.241, -5.094, -1.947, 1.2, 4.347, 7.494, + 10.641]) + assert_almost_equal(loc.tick_values(-7, 10), test_value) + + def test_view_limits(self): + """ + Test basic behavior of view limits. + """ + with mpl.rc_context({'axes.autolimit_mode': 'data'}): + loc = mticker.MultipleLocator(base=3.147) + assert_almost_equal(loc.view_limits(-5, 5), (-5, 5)) + + def test_view_limits_round_numbers(self): + """ + Test that everything works properly with 'round_numbers' for auto + limit. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MultipleLocator(base=3.147) + assert_almost_equal(loc.view_limits(-4, 4), (-6.294, 6.294)) + + def test_view_limits_round_numbers_with_offset(self): + """ + Test that everything works properly with 'round_numbers' for auto + limit. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MultipleLocator(base=3.147, offset=1.3) + assert_almost_equal(loc.view_limits(-4, 4), (-4.994, 4.447)) + + def test_view_limits_single_bin(self): + """ + Test that 'round_numbers' works properly with a single bin. + """ + with mpl.rc_context({'axes.autolimit_mode': 'round_numbers'}): + loc = mticker.MaxNLocator(nbins=1) + assert_almost_equal(loc.view_limits(-2.3, 2.3), (-4, 4)) + + def test_set_params(self): + """ + Create multiple locator with 0.7 base, and change it to something else. + See if change was successful. + """ + mult = mticker.MultipleLocator(base=0.7) + mult.set_params(base=1.7) + assert mult._edge.step == 1.7 + mult.set_params(offset=3) + assert mult._offset == 3 + + +class TestAutoMinorLocator: + def test_basic(self): + fig, ax = plt.subplots() + ax.set_xlim(0, 1.39) + ax.minorticks_on() + test_value = np.array([0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, + 0.5, 0.55, 0.65, 0.7, 0.75, 0.85, 0.9, + 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) + + # NB: the following values are assuming that *xlim* is [0, 5] + params = [ + (0, 0), # no major tick => no minor tick either + (1, 0) # a single major tick => no minor tick + ] + + def test_first_and_last_minorticks(self): + """ + Test that first and last minor tick appear as expected. + """ + # This test is related to issue #22331 + fig, ax = plt.subplots() + ax.set_xlim(-1.9, 1.9) + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + test_value = np.array([-1.9, -1.8, -1.7, -1.6, -1.4, -1.3, -1.2, -1.1, + -0.9, -0.8, -0.7, -0.6, -0.4, -0.3, -0.2, -0.1, + 0.1, 0.2, 0.3, 0.4, 0.6, 0.7, 0.8, 0.9, 1.1, + 1.2, 1.3, 1.4, 1.6, 1.7, 1.8, 1.9]) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) + + ax.set_xlim(-5, 5) + test_value = np.array([-5.0, -4.5, -3.5, -3.0, -2.5, -1.5, -1.0, -0.5, + 0.5, 1.0, 1.5, 2.5, 3.0, 3.5, 4.5, 5.0]) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), test_value) + + @pytest.mark.parametrize('nb_majorticks, expected_nb_minorticks', params) + def test_low_number_of_majorticks( + self, nb_majorticks, expected_nb_minorticks): + # This test is related to issue #8804 + fig, ax = plt.subplots() + xlims = (0, 5) # easier to test the different code paths + ax.set_xlim(*xlims) + ax.set_xticks(np.linspace(xlims[0], xlims[1], nb_majorticks)) + ax.minorticks_on() + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + assert len(ax.xaxis.get_minorticklocs()) == expected_nb_minorticks + + majorstep_minordivisions = [(1, 5), + (2, 4), + (2.5, 5), + (5, 5), + (10, 5)] + + # This test is meant to verify the parameterization for + # test_number_of_minor_ticks + def test_using_all_default_major_steps(self): + with mpl.rc_context({'_internal.classic_mode': False}): + majorsteps = [x[0] for x in self.majorstep_minordivisions] + np.testing.assert_allclose(majorsteps, + mticker.AutoLocator()._steps) + + @pytest.mark.parametrize('major_step, expected_nb_minordivisions', + majorstep_minordivisions) + def test_number_of_minor_ticks( + self, major_step, expected_nb_minordivisions): + fig, ax = plt.subplots() + xlims = (0, major_step) + ax.set_xlim(*xlims) + ax.set_xticks(xlims) + ax.minorticks_on() + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator()) + nb_minor_divisions = len(ax.xaxis.get_minorticklocs()) + 1 + assert nb_minor_divisions == expected_nb_minordivisions + + limits = [(0, 1.39), (0, 0.139), + (0, 0.11e-19), (0, 0.112e-12), + (-2.0e-07, -3.3e-08), (1.20e-06, 1.42e-06), + (-1.34e-06, -1.44e-06), (-8.76e-07, -1.51e-06)] + + reference = [ + [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7, + 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35], + [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, 0.065, + 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, 0.125, 0.13, + 0.135], + [5.00e-22, 1.00e-21, 1.50e-21, 2.50e-21, 3.00e-21, 3.50e-21, 4.50e-21, + 5.00e-21, 5.50e-21, 6.50e-21, 7.00e-21, 7.50e-21, 8.50e-21, 9.00e-21, + 9.50e-21, 1.05e-20, 1.10e-20], + [5.00e-15, 1.00e-14, 1.50e-14, 2.50e-14, 3.00e-14, 3.50e-14, 4.50e-14, + 5.00e-14, 5.50e-14, 6.50e-14, 7.00e-14, 7.50e-14, 8.50e-14, 9.00e-14, + 9.50e-14, 1.05e-13, 1.10e-13], + [-1.95e-07, -1.90e-07, -1.85e-07, -1.75e-07, -1.70e-07, -1.65e-07, + -1.55e-07, -1.50e-07, -1.45e-07, -1.35e-07, -1.30e-07, -1.25e-07, + -1.15e-07, -1.10e-07, -1.05e-07, -9.50e-08, -9.00e-08, -8.50e-08, + -7.50e-08, -7.00e-08, -6.50e-08, -5.50e-08, -5.00e-08, -4.50e-08, + -3.50e-08], + [1.21e-06, 1.22e-06, 1.23e-06, 1.24e-06, 1.26e-06, 1.27e-06, 1.28e-06, + 1.29e-06, 1.31e-06, 1.32e-06, 1.33e-06, 1.34e-06, 1.36e-06, 1.37e-06, + 1.38e-06, 1.39e-06, 1.41e-06, 1.42e-06], + [-1.435e-06, -1.430e-06, -1.425e-06, -1.415e-06, -1.410e-06, + -1.405e-06, -1.395e-06, -1.390e-06, -1.385e-06, -1.375e-06, + -1.370e-06, -1.365e-06, -1.355e-06, -1.350e-06, -1.345e-06], + [-1.48e-06, -1.46e-06, -1.44e-06, -1.42e-06, -1.38e-06, -1.36e-06, + -1.34e-06, -1.32e-06, -1.28e-06, -1.26e-06, -1.24e-06, -1.22e-06, + -1.18e-06, -1.16e-06, -1.14e-06, -1.12e-06, -1.08e-06, -1.06e-06, + -1.04e-06, -1.02e-06, -9.80e-07, -9.60e-07, -9.40e-07, -9.20e-07, + -8.80e-07]] + + additional_data = list(zip(limits, reference)) + + @pytest.mark.parametrize('lim, ref', additional_data) + def test_additional(self, lim, ref): + fig, ax = plt.subplots() + + ax.minorticks_on() + ax.grid(True, 'minor', 'y', linewidth=1) + ax.grid(True, 'major', color='k', linewidth=1) + ax.set_ylim(lim) + + assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref) + + @pytest.mark.parametrize('use_rcparam', [False, True]) + @pytest.mark.parametrize( + 'lim, ref', [ + ((0, 1.39), + [0.05, 0.1, 0.15, 0.25, 0.3, 0.35, 0.45, 0.5, 0.55, 0.65, 0.7, + 0.75, 0.85, 0.9, 0.95, 1.05, 1.1, 1.15, 1.25, 1.3, 1.35]), + ((0, 0.139), + [0.005, 0.01, 0.015, 0.025, 0.03, 0.035, 0.045, 0.05, 0.055, + 0.065, 0.07, 0.075, 0.085, 0.09, 0.095, 0.105, 0.11, 0.115, + 0.125, 0.13, 0.135]), + ]) + def test_number_of_minor_ticks_auto(self, lim, ref, use_rcparam): + if use_rcparam: + context = {'xtick.minor.ndivs': 'auto', 'ytick.minor.ndivs': 'auto'} + kwargs = {} + else: + context = {} + kwargs = {'n': 'auto'} + + with mpl.rc_context(context): + fig, ax = plt.subplots() + ax.set_xlim(*lim) + ax.set_ylim(*lim) + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref) + assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref) + + @pytest.mark.parametrize('use_rcparam', [False, True]) + @pytest.mark.parametrize( + 'n, lim, ref', [ + (2, (0, 4), [0.5, 1.5, 2.5, 3.5]), + (4, (0, 2), [0.25, 0.5, 0.75, 1.25, 1.5, 1.75]), + (10, (0, 1), [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]), + ]) + def test_number_of_minor_ticks_int(self, n, lim, ref, use_rcparam): + if use_rcparam: + context = {'xtick.minor.ndivs': n, 'ytick.minor.ndivs': n} + kwargs = {} + else: + context = {} + kwargs = {'n': n} + + with mpl.rc_context(context): + fig, ax = plt.subplots() + ax.set_xlim(*lim) + ax.set_ylim(*lim) + ax.xaxis.set_major_locator(mticker.MultipleLocator(1)) + ax.xaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + ax.yaxis.set_major_locator(mticker.MultipleLocator(1)) + ax.yaxis.set_minor_locator(mticker.AutoMinorLocator(**kwargs)) + assert_almost_equal(ax.xaxis.get_ticklocs(minor=True), ref) + assert_almost_equal(ax.yaxis.get_ticklocs(minor=True), ref) + + +class TestLogLocator: + def test_basic(self): + loc = mticker.LogLocator(numticks=5) + with pytest.raises(ValueError): + loc.tick_values(0, 1000) + + test_value = np.array([1.00000000e-05, 1.00000000e-03, 1.00000000e-01, + 1.00000000e+01, 1.00000000e+03, 1.00000000e+05, + 1.00000000e+07, 1.000000000e+09]) + assert_almost_equal(loc.tick_values(0.001, 1.1e5), test_value) + + loc = mticker.LogLocator(base=2) + test_value = np.array([0.5, 1., 2., 4., 8., 16., 32., 64., 128., 256.]) + assert_almost_equal(loc.tick_values(1, 100), test_value) + + def test_polar_axes(self): + """ + Polar Axes have a different ticking logic. + """ + fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) + ax.set_yscale('log') + ax.set_ylim(1, 100) + assert_array_equal(ax.get_yticks(), [10, 100, 1000]) + + def test_switch_to_autolocator(self): + loc = mticker.LogLocator(subs="all") + assert_array_equal(loc.tick_values(0.45, 0.55), + [0.44, 0.46, 0.48, 0.5, 0.52, 0.54, 0.56]) + # check that we *skip* 1.0, and 10, because this is a minor locator + loc = mticker.LogLocator(subs=np.arange(2, 10)) + assert 1.0 not in loc.tick_values(0.9, 20.) + assert 10.0 not in loc.tick_values(0.9, 20.) + + def test_set_params(self): + """ + Create log locator with default value, base=10.0, subs=[1.0], + numdecs=4, numticks=15 and change it to something else. + See if change was successful. Should not raise exception. + """ + loc = mticker.LogLocator() + with pytest.warns(mpl.MatplotlibDeprecationWarning, match="numdecs"): + loc.set_params(numticks=7, numdecs=8, subs=[2.0], base=4) + assert loc.numticks == 7 + with pytest.warns(mpl.MatplotlibDeprecationWarning, match="numdecs"): + assert loc.numdecs == 8 + assert loc._base == 4 + assert list(loc._subs) == [2.0] + + def test_tick_values_correct(self): + ll = mticker.LogLocator(subs=(1, 2, 5)) + test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00, + 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02, + 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04, + 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06, + 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08]) + assert_almost_equal(ll.tick_values(1, 1e7), test_value) + + def test_tick_values_not_empty(self): + mpl.rcParams['_internal.classic_mode'] = False + ll = mticker.LogLocator(subs=(1, 2, 5)) + test_value = np.array([1.e-01, 2.e-01, 5.e-01, 1.e+00, 2.e+00, 5.e+00, + 1.e+01, 2.e+01, 5.e+01, 1.e+02, 2.e+02, 5.e+02, + 1.e+03, 2.e+03, 5.e+03, 1.e+04, 2.e+04, 5.e+04, + 1.e+05, 2.e+05, 5.e+05, 1.e+06, 2.e+06, 5.e+06, + 1.e+07, 2.e+07, 5.e+07, 1.e+08, 2.e+08, 5.e+08, + 1.e+09, 2.e+09, 5.e+09]) + assert_almost_equal(ll.tick_values(1, 1e8), test_value) + + def test_multiple_shared_axes(self): + rng = np.random.default_rng(19680801) + dummy_data = [rng.normal(size=100), [], []] + fig, axes = plt.subplots(len(dummy_data), sharex=True, sharey=True) + + for ax, data in zip(axes.flatten(), dummy_data): + ax.hist(data, bins=10) + ax.set_yscale('log', nonpositive='clip') + + for ax in axes.flatten(): + assert all(ax.get_yticks() == axes[0].get_yticks()) + assert ax.get_ylim() == axes[0].get_ylim() + + +class TestNullLocator: + def test_set_params(self): + """ + Create null locator, and attempt to call set_params() on it. + Should not exception, and should raise a warning. + """ + loc = mticker.NullLocator() + with pytest.warns(UserWarning): + loc.set_params() + + +class _LogitHelper: + @staticmethod + def isclose(x, y): + return (np.isclose(-np.log(1/x-1), -np.log(1/y-1)) + if 0 < x < 1 and 0 < y < 1 else False) + + @staticmethod + def assert_almost_equal(x, y): + ax = np.array(x) + ay = np.array(y) + assert np.all(ax > 0) and np.all(ax < 1) + assert np.all(ay > 0) and np.all(ay < 1) + lx = -np.log(1/ax-1) + ly = -np.log(1/ay-1) + assert_almost_equal(lx, ly) + + +class TestLogitLocator: + ref_basic_limits = [ + (5e-2, 1 - 5e-2), + (5e-3, 1 - 5e-3), + (5e-4, 1 - 5e-4), + (5e-5, 1 - 5e-5), + (5e-6, 1 - 5e-6), + (5e-7, 1 - 5e-7), + (5e-8, 1 - 5e-8), + (5e-9, 1 - 5e-9), + ] + + ref_basic_major_ticks = [ + 1 / (10 ** np.arange(1, 3)), + 1 / (10 ** np.arange(1, 4)), + 1 / (10 ** np.arange(1, 5)), + 1 / (10 ** np.arange(1, 6)), + 1 / (10 ** np.arange(1, 7)), + 1 / (10 ** np.arange(1, 8)), + 1 / (10 ** np.arange(1, 9)), + 1 / (10 ** np.arange(1, 10)), + ] + + ref_maxn_limits = [(0.4, 0.6), (5e-2, 2e-1), (1 - 2e-1, 1 - 5e-2)] + + @pytest.mark.parametrize( + "lims, expected_low_ticks", + zip(ref_basic_limits, ref_basic_major_ticks), + ) + def test_basic_major(self, lims, expected_low_ticks): + """ + Create logit locator with huge number of major, and tests ticks. + """ + expected_ticks = sorted( + [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)] + ) + loc = mticker.LogitLocator(nbins=100) + _LogitHelper.assert_almost_equal( + loc.tick_values(*lims), + expected_ticks + ) + + @pytest.mark.parametrize("lims", ref_maxn_limits) + def test_maxn_major(self, lims): + """ + When the axis is zoomed, the locator must have the same behavior as + MaxNLocator. + """ + loc = mticker.LogitLocator(nbins=100) + maxn_loc = mticker.MaxNLocator(nbins=100, steps=[1, 2, 5, 10]) + for nbins in (4, 8, 16): + loc.set_params(nbins=nbins) + maxn_loc.set_params(nbins=nbins) + ticks = loc.tick_values(*lims) + maxn_ticks = maxn_loc.tick_values(*lims) + assert ticks.shape == maxn_ticks.shape + assert (ticks == maxn_ticks).all() + + @pytest.mark.parametrize("lims", ref_basic_limits + ref_maxn_limits) + def test_nbins_major(self, lims): + """ + Assert logit locator for respecting nbins param. + """ + + basic_needed = int(-np.floor(np.log10(lims[0]))) * 2 + 1 + loc = mticker.LogitLocator(nbins=100) + for nbins in range(basic_needed, 2, -1): + loc.set_params(nbins=nbins) + assert len(loc.tick_values(*lims)) <= nbins + 2 + + @pytest.mark.parametrize( + "lims, expected_low_ticks", + zip(ref_basic_limits, ref_basic_major_ticks), + ) + def test_minor(self, lims, expected_low_ticks): + """ + In large scale, test the presence of minor, + and assert no minor when major are subsampled. + """ + + expected_ticks = sorted( + [*expected_low_ticks, 0.5, *(1 - expected_low_ticks)] + ) + basic_needed = len(expected_ticks) + loc = mticker.LogitLocator(nbins=100) + minor_loc = mticker.LogitLocator(nbins=100, minor=True) + for nbins in range(basic_needed, 2, -1): + loc.set_params(nbins=nbins) + minor_loc.set_params(nbins=nbins) + major_ticks = loc.tick_values(*lims) + minor_ticks = minor_loc.tick_values(*lims) + if len(major_ticks) >= len(expected_ticks): + # no subsample, we must have a lot of minors ticks + assert (len(major_ticks) - 1) * 5 < len(minor_ticks) + else: + # subsample + _LogitHelper.assert_almost_equal( + sorted([*major_ticks, *minor_ticks]), expected_ticks) + + def test_minor_attr(self): + loc = mticker.LogitLocator(nbins=100) + assert not loc.minor + loc.minor = True + assert loc.minor + loc.set_params(minor=False) + assert not loc.minor + + acceptable_vmin_vmax = [ + *(2.5 ** np.arange(-3, 0)), + *(1 - 2.5 ** np.arange(-3, 0)), + ] + + @pytest.mark.parametrize( + "lims", + [ + (a, b) + for (a, b) in itertools.product(acceptable_vmin_vmax, repeat=2) + if a != b + ], + ) + def test_nonsingular_ok(self, lims): + """ + Create logit locator, and test the nonsingular method for acceptable + value + """ + loc = mticker.LogitLocator() + lims2 = loc.nonsingular(*lims) + assert sorted(lims) == sorted(lims2) + + @pytest.mark.parametrize("okval", acceptable_vmin_vmax) + def test_nonsingular_nok(self, okval): + """ + Create logit locator, and test the nonsingular method for non + acceptable value + """ + loc = mticker.LogitLocator() + vmin, vmax = (-1, okval) + vmin2, vmax2 = loc.nonsingular(vmin, vmax) + assert vmax2 == vmax + assert 0 < vmin2 < vmax2 + vmin, vmax = (okval, 2) + vmin2, vmax2 = loc.nonsingular(vmin, vmax) + assert vmin2 == vmin + assert vmin2 < vmax2 < 1 + + +class TestFixedLocator: + def test_set_params(self): + """ + Create fixed locator with 5 nbins, and change it to something else. + See if change was successful. + Should not exception. + """ + fixed = mticker.FixedLocator(range(0, 24), nbins=5) + fixed.set_params(nbins=7) + assert fixed.nbins == 7 + + +class TestIndexLocator: + def test_set_params(self): + """ + Create index locator with 3 base, 4 offset. and change it to something + else. See if change was successful. + Should not exception. + """ + index = mticker.IndexLocator(base=3, offset=4) + index.set_params(base=7, offset=7) + assert index._base == 7 + assert index.offset == 7 + + +class TestSymmetricalLogLocator: + def test_set_params(self): + """ + Create symmetrical log locator with default subs =[1.0] numticks = 15, + and change it to something else. + See if change was successful. + Should not exception. + """ + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) + sym.set_params(subs=[2.0], numticks=8) + assert sym._subs == [2.0] + assert sym.numticks == 8 + + @pytest.mark.parametrize( + 'vmin, vmax, expected', + [ + (0, 1, [0, 1]), + (-1, 1, [-1, 0, 1]), + ], + ) + def test_values(self, vmin, vmax, expected): + # https://github.com/matplotlib/matplotlib/issues/25945 + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) + ticks = sym.tick_values(vmin=vmin, vmax=vmax) + assert_array_equal(ticks, expected) + + def test_subs(self): + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1, subs=[2.0, 4.0]) + sym.create_dummy_axis() + sym.axis.set_view_interval(-10, 10) + assert (sym() == [-20., -40., -2., -4., 0., 2., 4., 20., 40.]).all() + + def test_extending(self): + sym = mticker.SymmetricalLogLocator(base=10, linthresh=1) + sym.create_dummy_axis() + sym.axis.set_view_interval(8, 9) + assert (sym() == [1.0]).all() + sym.axis.set_view_interval(8, 12) + assert (sym() == [1.0, 10.0]).all() + assert sym.view_limits(10, 10) == (1, 100) + assert sym.view_limits(-10, -10) == (-100, -1) + assert sym.view_limits(0, 0) == (-0.001, 0.001) + + +class TestAsinhLocator: + def test_init(self): + lctr = mticker.AsinhLocator(linear_width=2.718, numticks=19) + assert lctr.linear_width == 2.718 + assert lctr.numticks == 19 + assert lctr.base == 10 + + def test_set_params(self): + lctr = mticker.AsinhLocator(linear_width=5, + numticks=17, symthresh=0.125, + base=4, subs=(2.5, 3.25)) + assert lctr.numticks == 17 + assert lctr.symthresh == 0.125 + assert lctr.base == 4 + assert lctr.subs == (2.5, 3.25) + + lctr.set_params(numticks=23) + assert lctr.numticks == 23 + lctr.set_params(None) + assert lctr.numticks == 23 + + lctr.set_params(symthresh=0.5) + assert lctr.symthresh == 0.5 + lctr.set_params(symthresh=None) + assert lctr.symthresh == 0.5 + + lctr.set_params(base=7) + assert lctr.base == 7 + lctr.set_params(base=None) + assert lctr.base == 7 + + lctr.set_params(subs=(2, 4.125)) + assert lctr.subs == (2, 4.125) + lctr.set_params(subs=None) + assert lctr.subs == (2, 4.125) + lctr.set_params(subs=[]) + assert lctr.subs is None + + def test_linear_values(self): + lctr = mticker.AsinhLocator(linear_width=100, numticks=11, base=0) + + assert_almost_equal(lctr.tick_values(-1, 1), + np.arange(-1, 1.01, 0.2)) + assert_almost_equal(lctr.tick_values(-0.1, 0.1), + np.arange(-0.1, 0.101, 0.02)) + assert_almost_equal(lctr.tick_values(-0.01, 0.01), + np.arange(-0.01, 0.0101, 0.002)) + + def test_wide_values(self): + lctr = mticker.AsinhLocator(linear_width=0.1, numticks=11, base=0) + + assert_almost_equal(lctr.tick_values(-100, 100), + [-100, -20, -5, -1, -0.2, + 0, 0.2, 1, 5, 20, 100]) + assert_almost_equal(lctr.tick_values(-1000, 1000), + [-1000, -100, -20, -3, -0.4, + 0, 0.4, 3, 20, 100, 1000]) + + def test_near_zero(self): + """Check that manually injected zero will supersede nearby tick""" + lctr = mticker.AsinhLocator(linear_width=100, numticks=3, base=0) + + assert_almost_equal(lctr.tick_values(-1.1, 0.9), [-1.0, 0.0, 0.9]) + + def test_fallback(self): + lctr = mticker.AsinhLocator(1.0, numticks=11) + + assert_almost_equal(lctr.tick_values(101, 102), + np.arange(101, 102.01, 0.1)) + + def test_symmetrizing(self): + lctr = mticker.AsinhLocator(linear_width=1, numticks=3, + symthresh=0.25, base=0) + lctr.create_dummy_axis() + + lctr.axis.set_view_interval(-1, 2) + assert_almost_equal(lctr(), [-1, 0, 2]) + + lctr.axis.set_view_interval(-1, 0.9) + assert_almost_equal(lctr(), [-1, 0, 1]) + + lctr.axis.set_view_interval(-0.85, 1.05) + assert_almost_equal(lctr(), [-1, 0, 1]) + + lctr.axis.set_view_interval(1, 1.1) + assert_almost_equal(lctr(), [1, 1.05, 1.1]) + + def test_base_rounding(self): + lctr10 = mticker.AsinhLocator(linear_width=1, numticks=8, + base=10, subs=(1, 3, 5)) + assert_almost_equal(lctr10.tick_values(-110, 110), + [-500, -300, -100, -50, -30, -10, -5, -3, -1, + -0.5, -0.3, -0.1, 0, 0.1, 0.3, 0.5, + 1, 3, 5, 10, 30, 50, 100, 300, 500]) + + lctr5 = mticker.AsinhLocator(linear_width=1, numticks=20, base=5) + assert_almost_equal(lctr5.tick_values(-1050, 1050), + [-625, -125, -25, -5, -1, -0.2, 0, + 0.2, 1, 5, 25, 125, 625]) + + +class TestScalarFormatter: + offset_data = [ + (123, 189, 0), + (-189, -123, 0), + (12341, 12349, 12340), + (-12349, -12341, -12340), + (99999.5, 100010.5, 100000), + (-100010.5, -99999.5, -100000), + (99990.5, 100000.5, 100000), + (-100000.5, -99990.5, -100000), + (1233999, 1234001, 1234000), + (-1234001, -1233999, -1234000), + (1, 1, 1), + (123, 123, 0), + # Test cases courtesy of @WeatherGod + (.4538, .4578, .45), + (3789.12, 3783.1, 3780), + (45124.3, 45831.75, 45000), + (0.000721, 0.0007243, 0.00072), + (12592.82, 12591.43, 12590), + (9., 12., 0), + (900., 1200., 0), + (1900., 1200., 0), + (0.99, 1.01, 1), + (9.99, 10.01, 10), + (99.99, 100.01, 100), + (5.99, 6.01, 6), + (15.99, 16.01, 16), + (-0.452, 0.492, 0), + (-0.492, 0.492, 0), + (12331.4, 12350.5, 12300), + (-12335.3, 12335.3, 0), + ] + + use_offset_data = [True, False] + + useMathText_data = [True, False] + + # (sci_type, scilimits, lim, orderOfMag, fewticks) + scilimits_data = [ + (False, (0, 0), (10.0, 20.0), 0, False), + (True, (-2, 2), (-10, 20), 0, False), + (True, (-2, 2), (-20, 10), 0, False), + (True, (-2, 2), (-110, 120), 2, False), + (True, (-2, 2), (-120, 110), 2, False), + (True, (-2, 2), (-.001, 0.002), -3, False), + (True, (-7, 7), (0.18e10, 0.83e10), 9, True), + (True, (0, 0), (-1e5, 1e5), 5, False), + (True, (6, 6), (-1e5, 1e5), 6, False), + ] + + cursor_data = [ + [0., "0.000"], + [0.0123, "0.012"], + [0.123, "0.123"], + [1.23, "1.230"], + [12.3, "12.300"], + ] + + format_data = [ + (.1, "1e-1"), + (.11, "1.1e-1"), + (1e8, "1e8"), + (1.1e8, "1.1e8"), + ] + + @pytest.mark.parametrize('unicode_minus, result', + [(True, "\N{MINUS SIGN}1"), (False, "-1")]) + def test_unicode_minus(self, unicode_minus, result): + mpl.rcParams['axes.unicode_minus'] = unicode_minus + assert ( + plt.gca().xaxis.get_major_formatter().format_data_short(-1).strip() + == result) + + @pytest.mark.parametrize('left, right, offset', offset_data) + def test_offset_value(self, left, right, offset): + fig, ax = plt.subplots() + formatter = ax.xaxis.get_major_formatter() + + with (pytest.warns(UserWarning, match='Attempting to set identical') + if left == right else nullcontext()): + ax.set_xlim(left, right) + ax.xaxis._update_ticks() + assert formatter.offset == offset + + with (pytest.warns(UserWarning, match='Attempting to set identical') + if left == right else nullcontext()): + ax.set_xlim(right, left) + ax.xaxis._update_ticks() + assert formatter.offset == offset + + @pytest.mark.parametrize('use_offset', use_offset_data) + def test_use_offset(self, use_offset): + with mpl.rc_context({'axes.formatter.useoffset': use_offset}): + tmp_form = mticker.ScalarFormatter() + assert use_offset == tmp_form.get_useOffset() + assert tmp_form.offset == 0 + + @pytest.mark.parametrize('use_math_text', useMathText_data) + def test_useMathText(self, use_math_text): + with mpl.rc_context({'axes.formatter.use_mathtext': use_math_text}): + tmp_form = mticker.ScalarFormatter() + assert use_math_text == tmp_form.get_useMathText() + + def test_set_use_offset_float(self): + tmp_form = mticker.ScalarFormatter() + tmp_form.set_useOffset(0.5) + assert not tmp_form.get_useOffset() + assert tmp_form.offset == 0.5 + + def test_use_locale(self): + conv = locale.localeconv() + sep = conv['thousands_sep'] + if not sep or conv['grouping'][-1:] in ([], [locale.CHAR_MAX]): + pytest.skip('Locale does not apply grouping') # pragma: no cover + + with mpl.rc_context({'axes.formatter.use_locale': True}): + tmp_form = mticker.ScalarFormatter() + assert tmp_form.get_useLocale() + + tmp_form.create_dummy_axis() + tmp_form.axis.set_data_interval(0, 10) + tmp_form.set_locs([1, 2, 3]) + assert sep in tmp_form(1e9) + + @pytest.mark.parametrize( + 'sci_type, scilimits, lim, orderOfMag, fewticks', scilimits_data) + def test_scilimits(self, sci_type, scilimits, lim, orderOfMag, fewticks): + tmp_form = mticker.ScalarFormatter() + tmp_form.set_scientific(sci_type) + tmp_form.set_powerlimits(scilimits) + fig, ax = plt.subplots() + ax.yaxis.set_major_formatter(tmp_form) + ax.set_ylim(*lim) + if fewticks: + ax.yaxis.set_major_locator(mticker.MaxNLocator(4)) + + tmp_form.set_locs(ax.yaxis.get_majorticklocs()) + assert orderOfMag == tmp_form.orderOfMagnitude + + @pytest.mark.parametrize('value, expected', format_data) + def test_format_data(self, value, expected): + mpl.rcParams['axes.unicode_minus'] = False + sf = mticker.ScalarFormatter() + assert sf.format_data(value) == expected + + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_precision(self, data, expected): + fig, ax = plt.subplots() + ax.set_xlim(-1, 1) # Pointing precision of 0.001. + fmt = ax.xaxis.get_major_formatter().format_data_short + assert fmt(data) == expected + + @pytest.mark.parametrize('data, expected', cursor_data) + def test_cursor_dummy_axis(self, data, expected): + # Issue #17624 + sf = mticker.ScalarFormatter() + sf.create_dummy_axis() + sf.axis.set_view_interval(0, 10) + fmt = sf.format_data_short + assert fmt(data) == expected + assert sf.axis.get_tick_space() == 9 + assert sf.axis.get_minpos() == 0 + + def test_mathtext_ticks(self): + mpl.rcParams.update({ + 'font.family': 'serif', + 'font.serif': 'cmr10', + 'axes.formatter.use_mathtext': False + }) + + if parse_version(pytest.__version__).major < 8: + with pytest.warns(UserWarning, match='cmr10 font should ideally'): + fig, ax = plt.subplots() + ax.set_xticks([-1, 0, 1]) + fig.canvas.draw() + else: + with (pytest.warns(UserWarning, match="Glyph 8722"), + pytest.warns(UserWarning, match='cmr10 font should ideally')): + fig, ax = plt.subplots() + ax.set_xticks([-1, 0, 1]) + fig.canvas.draw() + + def test_cmr10_substitutions(self, caplog): + mpl.rcParams.update({ + 'font.family': 'cmr10', + 'mathtext.fontset': 'cm', + 'axes.formatter.use_mathtext': True, + }) + + # Test that it does not log a warning about missing glyphs. + with caplog.at_level(logging.WARNING, logger='matplotlib.mathtext'): + fig, ax = plt.subplots() + ax.plot([-0.03, 0.05], [40, 0.05]) + ax.set_yscale('log') + yticks = [0.02, 0.3, 4, 50] + formatter = mticker.LogFormatterSciNotation() + ax.set_yticks(yticks, map(formatter, yticks)) + fig.canvas.draw() + assert not caplog.text + + def test_empty_locs(self): + sf = mticker.ScalarFormatter() + sf.set_locs([]) + assert sf(0.5) == '' + + +class TestLogFormatterExponent: + param_data = [ + (True, 4, np.arange(-3, 4.0), np.arange(-3, 4.0), + ['-3', '-2', '-1', '0', '1', '2', '3']), + # With labelOnlyBase=False, non-integer powers should be nicely + # formatted. + (False, 10, np.array([0.1, 0.00001, np.pi, 0.2, -0.2, -0.00001]), + range(6), ['0.1', '1e-05', '3.14', '0.2', '-0.2', '-1e-05']), + (False, 50, np.array([3, 5, 12, 42], dtype=float), range(6), + ['3', '5', '12', '42']), + ] + + base_data = [2.0, 5.0, 10.0, np.pi, np.e] + + @pytest.mark.parametrize( + 'labelOnlyBase, exponent, locs, positions, expected', param_data) + @pytest.mark.parametrize('base', base_data) + def test_basic(self, labelOnlyBase, base, exponent, locs, positions, + expected): + formatter = mticker.LogFormatterExponent(base=base, + labelOnlyBase=labelOnlyBase) + formatter.create_dummy_axis() + formatter.axis.set_view_interval(1, base**exponent) + vals = base**locs + labels = [formatter(x, pos) for (x, pos) in zip(vals, positions)] + expected = [label.replace('-', '\N{Minus Sign}') for label in expected] + assert labels == expected + + def test_blank(self): + # Should be a blank string for non-integer powers if labelOnlyBase=True + formatter = mticker.LogFormatterExponent(base=10, labelOnlyBase=True) + formatter.create_dummy_axis() + formatter.axis.set_view_interval(1, 10) + assert formatter(10**0.1) == '' + + +class TestLogFormatterMathtext: + fmt = mticker.LogFormatterMathtext() + test_data = [ + (0, 1, '$\\mathdefault{10^{0}}$'), + (0, 1e-2, '$\\mathdefault{10^{-2}}$'), + (0, 1e2, '$\\mathdefault{10^{2}}$'), + (3, 1, '$\\mathdefault{1}$'), + (3, 1e-2, '$\\mathdefault{0.01}$'), + (3, 1e2, '$\\mathdefault{100}$'), + (3, 1e-3, '$\\mathdefault{10^{-3}}$'), + (3, 1e3, '$\\mathdefault{10^{3}}$'), + ] + + @pytest.mark.parametrize('min_exponent, value, expected', test_data) + def test_min_exponent(self, min_exponent, value, expected): + with mpl.rc_context({'axes.formatter.min_exponent': min_exponent}): + assert self.fmt(value) == expected + + +class TestLogFormatterSciNotation: + test_data = [ + (2, 0.03125, '$\\mathdefault{2^{-5}}$'), + (2, 1, '$\\mathdefault{2^{0}}$'), + (2, 32, '$\\mathdefault{2^{5}}$'), + (2, 0.0375, '$\\mathdefault{1.2\\times2^{-5}}$'), + (2, 1.2, '$\\mathdefault{1.2\\times2^{0}}$'), + (2, 38.4, '$\\mathdefault{1.2\\times2^{5}}$'), + (10, -1, '$\\mathdefault{-10^{0}}$'), + (10, 1e-05, '$\\mathdefault{10^{-5}}$'), + (10, 1, '$\\mathdefault{10^{0}}$'), + (10, 100000, '$\\mathdefault{10^{5}}$'), + (10, 2e-05, '$\\mathdefault{2\\times10^{-5}}$'), + (10, 2, '$\\mathdefault{2\\times10^{0}}$'), + (10, 200000, '$\\mathdefault{2\\times10^{5}}$'), + (10, 5e-05, '$\\mathdefault{5\\times10^{-5}}$'), + (10, 5, '$\\mathdefault{5\\times10^{0}}$'), + (10, 500000, '$\\mathdefault{5\\times10^{5}}$'), + ] + + @mpl.style.context('default') + @pytest.mark.parametrize('base, value, expected', test_data) + def test_basic(self, base, value, expected): + formatter = mticker.LogFormatterSciNotation(base=base) + with mpl.rc_context({'text.usetex': False}): + assert formatter(value) == expected + + +class TestLogFormatter: + pprint_data = [ + (3.141592654e-05, 0.001, '3.142e-5'), + (0.0003141592654, 0.001, '3.142e-4'), + (0.003141592654, 0.001, '3.142e-3'), + (0.03141592654, 0.001, '3.142e-2'), + (0.3141592654, 0.001, '3.142e-1'), + (3.141592654, 0.001, '3.142'), + (31.41592654, 0.001, '3.142e1'), + (314.1592654, 0.001, '3.142e2'), + (3141.592654, 0.001, '3.142e3'), + (31415.92654, 0.001, '3.142e4'), + (314159.2654, 0.001, '3.142e5'), + (1e-05, 0.001, '1e-5'), + (0.0001, 0.001, '1e-4'), + (0.001, 0.001, '1e-3'), + (0.01, 0.001, '1e-2'), + (0.1, 0.001, '1e-1'), + (1, 0.001, '1'), + (10, 0.001, '10'), + (100, 0.001, '100'), + (1000, 0.001, '1000'), + (10000, 0.001, '1e4'), + (100000, 0.001, '1e5'), + (3.141592654e-05, 0.015, '0'), + (0.0003141592654, 0.015, '0'), + (0.003141592654, 0.015, '0.003'), + (0.03141592654, 0.015, '0.031'), + (0.3141592654, 0.015, '0.314'), + (3.141592654, 0.015, '3.142'), + (31.41592654, 0.015, '31.416'), + (314.1592654, 0.015, '314.159'), + (3141.592654, 0.015, '3141.593'), + (31415.92654, 0.015, '31415.927'), + (314159.2654, 0.015, '314159.265'), + (1e-05, 0.015, '0'), + (0.0001, 0.015, '0'), + (0.001, 0.015, '0.001'), + (0.01, 0.015, '0.01'), + (0.1, 0.015, '0.1'), + (1, 0.015, '1'), + (10, 0.015, '10'), + (100, 0.015, '100'), + (1000, 0.015, '1000'), + (10000, 0.015, '10000'), + (100000, 0.015, '100000'), + (3.141592654e-05, 0.5, '0'), + (0.0003141592654, 0.5, '0'), + (0.003141592654, 0.5, '0.003'), + (0.03141592654, 0.5, '0.031'), + (0.3141592654, 0.5, '0.314'), + (3.141592654, 0.5, '3.142'), + (31.41592654, 0.5, '31.416'), + (314.1592654, 0.5, '314.159'), + (3141.592654, 0.5, '3141.593'), + (31415.92654, 0.5, '31415.927'), + (314159.2654, 0.5, '314159.265'), + (1e-05, 0.5, '0'), + (0.0001, 0.5, '0'), + (0.001, 0.5, '0.001'), + (0.01, 0.5, '0.01'), + (0.1, 0.5, '0.1'), + (1, 0.5, '1'), + (10, 0.5, '10'), + (100, 0.5, '100'), + (1000, 0.5, '1000'), + (10000, 0.5, '10000'), + (100000, 0.5, '100000'), + (3.141592654e-05, 5, '0'), + (0.0003141592654, 5, '0'), + (0.003141592654, 5, '0'), + (0.03141592654, 5, '0.03'), + (0.3141592654, 5, '0.31'), + (3.141592654, 5, '3.14'), + (31.41592654, 5, '31.42'), + (314.1592654, 5, '314.16'), + (3141.592654, 5, '3141.59'), + (31415.92654, 5, '31415.93'), + (314159.2654, 5, '314159.27'), + (1e-05, 5, '0'), + (0.0001, 5, '0'), + (0.001, 5, '0'), + (0.01, 5, '0.01'), + (0.1, 5, '0.1'), + (1, 5, '1'), + (10, 5, '10'), + (100, 5, '100'), + (1000, 5, '1000'), + (10000, 5, '10000'), + (100000, 5, '100000'), + (3.141592654e-05, 100, '0'), + (0.0003141592654, 100, '0'), + (0.003141592654, 100, '0'), + (0.03141592654, 100, '0'), + (0.3141592654, 100, '0.3'), + (3.141592654, 100, '3.1'), + (31.41592654, 100, '31.4'), + (314.1592654, 100, '314.2'), + (3141.592654, 100, '3141.6'), + (31415.92654, 100, '31415.9'), + (314159.2654, 100, '314159.3'), + (1e-05, 100, '0'), + (0.0001, 100, '0'), + (0.001, 100, '0'), + (0.01, 100, '0'), + (0.1, 100, '0.1'), + (1, 100, '1'), + (10, 100, '10'), + (100, 100, '100'), + (1000, 100, '1000'), + (10000, 100, '10000'), + (100000, 100, '100000'), + (3.141592654e-05, 1000000.0, '3.1e-5'), + (0.0003141592654, 1000000.0, '3.1e-4'), + (0.003141592654, 1000000.0, '3.1e-3'), + (0.03141592654, 1000000.0, '3.1e-2'), + (0.3141592654, 1000000.0, '3.1e-1'), + (3.141592654, 1000000.0, '3.1'), + (31.41592654, 1000000.0, '3.1e1'), + (314.1592654, 1000000.0, '3.1e2'), + (3141.592654, 1000000.0, '3.1e3'), + (31415.92654, 1000000.0, '3.1e4'), + (314159.2654, 1000000.0, '3.1e5'), + (1e-05, 1000000.0, '1e-5'), + (0.0001, 1000000.0, '1e-4'), + (0.001, 1000000.0, '1e-3'), + (0.01, 1000000.0, '1e-2'), + (0.1, 1000000.0, '1e-1'), + (1, 1000000.0, '1'), + (10, 1000000.0, '10'), + (100, 1000000.0, '100'), + (1000, 1000000.0, '1000'), + (10000, 1000000.0, '1e4'), + (100000, 1000000.0, '1e5'), + ] + + @pytest.mark.parametrize('value, domain, expected', pprint_data) + def test_pprint(self, value, domain, expected): + fmt = mticker.LogFormatter() + label = fmt._pprint_val(value, domain) + assert label == expected + + @pytest.mark.parametrize('value, long, short', [ + (0.0, "0", "0"), + (0, "0", "0"), + (-1.0, "-10^0", "-1"), + (2e-10, "2x10^-10", "2e-10"), + (1e10, "10^10", "1e+10"), + ]) + def test_format_data(self, value, long, short): + fig, ax = plt.subplots() + ax.set_xscale('log') + fmt = ax.xaxis.get_major_formatter() + assert fmt.format_data(value) == long + assert fmt.format_data_short(value) == short + + def _sub_labels(self, axis, subs=()): + """Test whether locator marks subs to be labeled.""" + fmt = axis.get_minor_formatter() + minor_tlocs = axis.get_minorticklocs() + fmt.set_locs(minor_tlocs) + coefs = minor_tlocs / 10**(np.floor(np.log10(minor_tlocs))) + label_expected = [round(c) in subs for c in coefs] + label_test = [fmt(x) != '' for x in minor_tlocs] + assert label_test == label_expected + + @mpl.style.context('default') + def test_sublabel(self): + # test label locator + fig, ax = plt.subplots() + ax.set_xscale('log') + ax.xaxis.set_major_locator(mticker.LogLocator(base=10, subs=[])) + ax.xaxis.set_minor_locator(mticker.LogLocator(base=10, + subs=np.arange(2, 10))) + ax.xaxis.set_major_formatter(mticker.LogFormatter(labelOnlyBase=True)) + ax.xaxis.set_minor_formatter(mticker.LogFormatter(labelOnlyBase=False)) + # axis range above 3 decades, only bases are labeled + ax.set_xlim(1, 1e4) + fmt = ax.xaxis.get_major_formatter() + fmt.set_locs(ax.xaxis.get_majorticklocs()) + show_major_labels = [fmt(x) != '' + for x in ax.xaxis.get_majorticklocs()] + assert np.all(show_major_labels) + self._sub_labels(ax.xaxis, subs=[]) + + # For the next two, if the numdec threshold in LogFormatter.set_locs + # were 3, then the label sub would be 3 for 2-3 decades and (2, 5) + # for 1-2 decades. With a threshold of 1, subs are not labeled. + # axis range at 2 to 3 decades + ax.set_xlim(1, 800) + self._sub_labels(ax.xaxis, subs=[]) + + # axis range at 1 to 2 decades + ax.set_xlim(1, 80) + self._sub_labels(ax.xaxis, subs=[]) + + # axis range at 0.4 to 1 decades, label subs 2, 3, 4, 6 + ax.set_xlim(1, 8) + self._sub_labels(ax.xaxis, subs=[2, 3, 4, 6]) + + # axis range at 0 to 0.4 decades, label all + ax.set_xlim(0.5, 0.9) + self._sub_labels(ax.xaxis, subs=np.arange(2, 10, dtype=int)) + + @pytest.mark.parametrize('val', [1, 10, 100, 1000]) + def test_LogFormatter_call(self, val): + # test _num_to_string method used in __call__ + temp_lf = mticker.LogFormatter() + temp_lf.create_dummy_axis() + temp_lf.axis.set_view_interval(1, 10) + assert temp_lf(val) == str(val) + + @pytest.mark.parametrize('val', [1e-323, 2e-323, 10e-323, 11e-323]) + def test_LogFormatter_call_tiny(self, val): + # test coeff computation in __call__ + temp_lf = mticker.LogFormatter() + temp_lf.create_dummy_axis() + temp_lf.axis.set_view_interval(1, 10) + temp_lf(val) + + +class TestLogitFormatter: + @staticmethod + def logit_deformatter(string): + r""" + Parser to convert string as r'$\mathdefault{1.41\cdot10^{-4}}$' in + float 1.41e-4, as '0.5' or as r'$\mathdefault{\frac{1}{2}}$' in float + 0.5, + """ + match = re.match( + r"[^\d]*" + r"(?P1-)?" + r"(?P\d*\.?\d*)?" + r"(?:\\cdot)?" + r"(?:10\^\{(?P-?\d*)})?" + r"[^\d]*$", + string, + ) + if match: + comp = match["comp"] is not None + mantissa = float(match["mant"]) if match["mant"] else 1 + expo = int(match["expo"]) if match["expo"] is not None else 0 + value = mantissa * 10 ** expo + if match["mant"] or match["expo"] is not None: + if comp: + return 1 - value + return value + match = re.match( + r"[^\d]*\\frac\{(?P\d+)\}\{(?P\d+)\}[^\d]*$", string + ) + if match: + num, deno = float(match["num"]), float(match["deno"]) + return num / deno + raise ValueError("Not formatted by LogitFormatter") + + @pytest.mark.parametrize( + "fx, x", + [ + (r"STUFF0.41OTHERSTUFF", 0.41), + (r"STUFF1.41\cdot10^{-2}OTHERSTUFF", 1.41e-2), + (r"STUFF1-0.41OTHERSTUFF", 1 - 0.41), + (r"STUFF1-1.41\cdot10^{-2}OTHERSTUFF", 1 - 1.41e-2), + (r"STUFF", None), + (r"STUFF12.4e-3OTHERSTUFF", None), + ], + ) + def test_logit_deformater(self, fx, x): + if x is None: + with pytest.raises(ValueError): + TestLogitFormatter.logit_deformatter(fx) + else: + y = TestLogitFormatter.logit_deformatter(fx) + assert _LogitHelper.isclose(x, y) + + decade_test = sorted( + [10 ** (-i) for i in range(1, 10)] + + [1 - 10 ** (-i) for i in range(1, 10)] + + [1 / 2] + ) + + @pytest.mark.parametrize("x", decade_test) + def test_basic(self, x): + """ + Test the formatted value correspond to the value for ideal ticks in + logit space. + """ + formatter = mticker.LogitFormatter(use_overline=False) + formatter.set_locs(self.decade_test) + s = formatter(x) + x2 = TestLogitFormatter.logit_deformatter(s) + assert _LogitHelper.isclose(x, x2) + + @pytest.mark.parametrize("x", (-1, -0.5, -0.1, 1.1, 1.5, 2)) + def test_invalid(self, x): + """ + Test that invalid value are formatted with empty string without + raising exception. + """ + formatter = mticker.LogitFormatter(use_overline=False) + formatter.set_locs(self.decade_test) + s = formatter(x) + assert s == "" + + @pytest.mark.parametrize("x", 1 / (1 + np.exp(-np.linspace(-7, 7, 10)))) + def test_variablelength(self, x): + """ + The format length should change depending on the neighbor labels. + """ + formatter = mticker.LogitFormatter(use_overline=False) + for N in (10, 20, 50, 100, 200, 1000, 2000, 5000, 10000): + if x + 1 / N < 1: + formatter.set_locs([x - 1 / N, x, x + 1 / N]) + sx = formatter(x) + sx1 = formatter(x + 1 / N) + d = ( + TestLogitFormatter.logit_deformatter(sx1) + - TestLogitFormatter.logit_deformatter(sx) + ) + assert 0 < d < 2 / N + + lims_minor_major = [ + (True, (5e-8, 1 - 5e-8), ((25, False), (75, False))), + (True, (5e-5, 1 - 5e-5), ((25, False), (75, True))), + (True, (5e-2, 1 - 5e-2), ((25, True), (75, True))), + (False, (0.75, 0.76, 0.77), ((7, True), (25, True), (75, True))), + ] + + @pytest.mark.parametrize("method, lims, cases", lims_minor_major) + def test_minor_vs_major(self, method, lims, cases): + """ + Test minor/major displays. + """ + + if method: + min_loc = mticker.LogitLocator(minor=True) + ticks = min_loc.tick_values(*lims) + else: + ticks = np.array(lims) + min_form = mticker.LogitFormatter(minor=True) + for threshold, has_minor in cases: + min_form.set_minor_threshold(threshold) + formatted = min_form.format_ticks(ticks) + labelled = [f for f in formatted if len(f) > 0] + if has_minor: + assert len(labelled) > 0, (threshold, has_minor) + else: + assert len(labelled) == 0, (threshold, has_minor) + + def test_minor_number(self): + """ + Test the parameter minor_number + """ + min_loc = mticker.LogitLocator(minor=True) + min_form = mticker.LogitFormatter(minor=True) + ticks = min_loc.tick_values(5e-2, 1 - 5e-2) + for minor_number in (2, 4, 8, 16): + min_form.set_minor_number(minor_number) + formatted = min_form.format_ticks(ticks) + labelled = [f for f in formatted if len(f) > 0] + assert len(labelled) == minor_number + + def test_use_overline(self): + """ + Test the parameter use_overline + """ + x = 1 - 1e-2 + fx1 = r"$\mathdefault{1-10^{-2}}$" + fx2 = r"$\mathdefault{\overline{10^{-2}}}$" + form = mticker.LogitFormatter(use_overline=False) + assert form(x) == fx1 + form.use_overline(True) + assert form(x) == fx2 + form.use_overline(False) + assert form(x) == fx1 + + def test_one_half(self): + """ + Test the parameter one_half + """ + form = mticker.LogitFormatter() + assert r"\frac{1}{2}" in form(1/2) + form.set_one_half("1/2") + assert "1/2" in form(1/2) + form.set_one_half("one half") + assert "one half" in form(1/2) + + @pytest.mark.parametrize("N", (100, 253, 754)) + def test_format_data_short(self, N): + locs = np.linspace(0, 1, N)[1:-1] + form = mticker.LogitFormatter() + for x in locs: + fx = form.format_data_short(x) + if fx.startswith("1-"): + x2 = 1 - float(fx[2:]) + else: + x2 = float(fx) + assert abs(x - x2) < 1 / N + + +class TestFormatStrFormatter: + def test_basic(self): + # test % style formatter + tmp_form = mticker.FormatStrFormatter('%05d') + assert '00002' == tmp_form(2) + + +class TestStrMethodFormatter: + test_data = [ + ('{x:05d}', (2,), False, '00002'), + ('{x:05d}', (2,), True, '00002'), + ('{x:05d}', (-2,), False, '-0002'), + ('{x:05d}', (-2,), True, '\N{MINUS SIGN}0002'), + ('{x:03d}-{pos:02d}', (2, 1), False, '002-01'), + ('{x:03d}-{pos:02d}', (2, 1), True, '002-01'), + ('{x:03d}-{pos:02d}', (-2, 1), False, '-02-01'), + ('{x:03d}-{pos:02d}', (-2, 1), True, '\N{MINUS SIGN}02-01'), + ] + + @pytest.mark.parametrize('format, input, unicode_minus, expected', test_data) + def test_basic(self, format, input, unicode_minus, expected): + with mpl.rc_context({"axes.unicode_minus": unicode_minus}): + fmt = mticker.StrMethodFormatter(format) + assert fmt(*input) == expected + + +class TestEngFormatter: + # (unicode_minus, input, expected) where ''expected'' corresponds to the + # outputs respectively returned when (places=None, places=0, places=2) + # unicode_minus is a boolean value for the rcParam['axes.unicode_minus'] + raw_format_data = [ + (False, -1234.56789, ('-1.23457 k', '-1 k', '-1.23 k')), + (True, -1234.56789, ('\N{MINUS SIGN}1.23457 k', '\N{MINUS SIGN}1 k', + '\N{MINUS SIGN}1.23 k')), + (False, -1.23456789, ('-1.23457', '-1', '-1.23')), + (True, -1.23456789, ('\N{MINUS SIGN}1.23457', '\N{MINUS SIGN}1', + '\N{MINUS SIGN}1.23')), + (False, -0.123456789, ('-123.457 m', '-123 m', '-123.46 m')), + (True, -0.123456789, ('\N{MINUS SIGN}123.457 m', '\N{MINUS SIGN}123 m', + '\N{MINUS SIGN}123.46 m')), + (False, -0.00123456789, ('-1.23457 m', '-1 m', '-1.23 m')), + (True, -0.00123456789, ('\N{MINUS SIGN}1.23457 m', '\N{MINUS SIGN}1 m', + '\N{MINUS SIGN}1.23 m')), + (True, -0.0, ('0', '0', '0.00')), + (True, -0, ('0', '0', '0.00')), + (True, 0, ('0', '0', '0.00')), + (True, 1.23456789e-6, ('1.23457 µ', '1 µ', '1.23 µ')), + (True, 0.123456789, ('123.457 m', '123 m', '123.46 m')), + (True, 0.1, ('100 m', '100 m', '100.00 m')), + (True, 1, ('1', '1', '1.00')), + (True, 1.23456789, ('1.23457', '1', '1.23')), + # places=0: corner-case rounding + (True, 999.9, ('999.9', '1 k', '999.90')), + # corner-case rounding for all + (True, 999.9999, ('1 k', '1 k', '1.00 k')), + # negative corner-case + (False, -999.9999, ('-1 k', '-1 k', '-1.00 k')), + (True, -999.9999, ('\N{MINUS SIGN}1 k', '\N{MINUS SIGN}1 k', + '\N{MINUS SIGN}1.00 k')), + (True, 1000, ('1 k', '1 k', '1.00 k')), + (True, 1001, ('1.001 k', '1 k', '1.00 k')), + (True, 100001, ('100.001 k', '100 k', '100.00 k')), + (True, 987654.321, ('987.654 k', '988 k', '987.65 k')), + # OoR value (> 1000 Q) + (True, 1.23e33, ('1230 Q', '1230 Q', '1230.00 Q')) + ] + + @pytest.mark.parametrize('unicode_minus, input, expected', raw_format_data) + def test_params(self, unicode_minus, input, expected): + """ + Test the formatting of EngFormatter for various values of the 'places' + argument, in several cases: + + 0. without a unit symbol but with a (default) space separator; + 1. with both a unit symbol and a (default) space separator; + 2. with both a unit symbol and some non default separators; + 3. without a unit symbol but with some non default separators. + + Note that cases 2. and 3. are looped over several separator strings. + """ + + plt.rcParams['axes.unicode_minus'] = unicode_minus + UNIT = 's' # seconds + DIGITS = '0123456789' # %timeit showed 10-20% faster search than set + + # Case 0: unit='' (default) and sep=' ' (default). + # 'expected' already corresponds to this reference case. + exp_outputs = expected + formatters = ( + mticker.EngFormatter(), # places=None (default) + mticker.EngFormatter(places=0), + mticker.EngFormatter(places=2) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Case 1: unit=UNIT and sep=' ' (default). + # Append a unit symbol to the reference case. + # Beware of the values in [1, 1000), where there is no prefix! + exp_outputs = (_s + " " + UNIT if _s[-1] in DIGITS # case w/o prefix + else _s + UNIT for _s in expected) + formatters = ( + mticker.EngFormatter(unit=UNIT), # places=None (default) + mticker.EngFormatter(unit=UNIT, places=0), + mticker.EngFormatter(unit=UNIT, places=2) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Test several non default separators: no separator, a narrow + # no-break space (Unicode character) and an extravagant string. + for _sep in ("", "\N{NARROW NO-BREAK SPACE}", "@_@"): + # Case 2: unit=UNIT and sep=_sep. + # Replace the default space separator from the reference case + # with the tested one `_sep` and append a unit symbol to it. + exp_outputs = (_s + _sep + UNIT if _s[-1] in DIGITS # no prefix + else _s.replace(" ", _sep) + UNIT + for _s in expected) + formatters = ( + mticker.EngFormatter(unit=UNIT, sep=_sep), # places=None + mticker.EngFormatter(unit=UNIT, places=0, sep=_sep), + mticker.EngFormatter(unit=UNIT, places=2, sep=_sep) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + # Case 3: unit='' (default) and sep=_sep. + # Replace the default space separator from the reference case + # with the tested one `_sep`. Reference case is already unitless. + exp_outputs = (_s.replace(" ", _sep) for _s in expected) + formatters = ( + mticker.EngFormatter(sep=_sep), # places=None (default) + mticker.EngFormatter(places=0, sep=_sep), + mticker.EngFormatter(places=2, sep=_sep) + ) + for _formatter, _exp_output in zip(formatters, exp_outputs): + assert _formatter(input) == _exp_output + + +def test_engformatter_usetex_useMathText(): + fig, ax = plt.subplots() + ax.plot([0, 500, 1000], [0, 500, 1000]) + ax.set_xticks([0, 500, 1000]) + for formatter in (mticker.EngFormatter(usetex=True), + mticker.EngFormatter(useMathText=True)): + ax.xaxis.set_major_formatter(formatter) + fig.canvas.draw() + x_tick_label_text = [labl.get_text() for labl in ax.get_xticklabels()] + # Checking if the dollar `$` signs have been inserted around numbers + # in tick labels. + assert x_tick_label_text == ['$0$', '$500$', '$1$ k'] + + +class TestPercentFormatter: + percent_data = [ + # Check explicitly set decimals over different intervals and values + (100, 0, '%', 120, 100, '120%'), + (100, 0, '%', 100, 90, '100%'), + (100, 0, '%', 90, 50, '90%'), + (100, 0, '%', -1.7, 40, '-2%'), + (100, 1, '%', 90.0, 100, '90.0%'), + (100, 1, '%', 80.1, 90, '80.1%'), + (100, 1, '%', 70.23, 50, '70.2%'), + # 60.554 instead of 60.55: see https://bugs.python.org/issue5118 + (100, 1, '%', -60.554, 40, '-60.6%'), + # Check auto decimals over different intervals and values + (100, None, '%', 95, 1, '95.00%'), + (1.0, None, '%', 3, 6, '300%'), + (17.0, None, '%', 1, 8.5, '6%'), + (17.0, None, '%', 1, 8.4, '5.9%'), + (5, None, '%', -100, 0.000001, '-2000.00000%'), + # Check percent symbol + (1.0, 2, None, 1.2, 100, '120.00'), + (75, 3, '', 50, 100, '66.667'), + (42, None, '^^Foobar$$', 21, 12, '50.0^^Foobar$$'), + ] + + percent_ids = [ + # Check explicitly set decimals over different intervals and values + 'decimals=0, x>100%', + 'decimals=0, x=100%', + 'decimals=0, x<100%', + 'decimals=0, x<0%', + 'decimals=1, x>100%', + 'decimals=1, x=100%', + 'decimals=1, x<100%', + 'decimals=1, x<0%', + # Check auto decimals over different intervals and values + 'autodecimal, x<100%, display_range=1', + 'autodecimal, x>100%, display_range=6 (custom xmax test)', + 'autodecimal, x<100%, display_range=8.5 (autodecimal test 1)', + 'autodecimal, x<100%, display_range=8.4 (autodecimal test 2)', + 'autodecimal, x<-100%, display_range=1e-6 (tiny display range)', + # Check percent symbol + 'None as percent symbol', + 'Empty percent symbol', + 'Custom percent symbol', + ] + + latex_data = [ + (False, False, r'50\{t}%'), + (False, True, r'50\\\{t\}\%'), + (True, False, r'50\{t}%'), + (True, True, r'50\{t}%'), + ] + + @pytest.mark.parametrize( + 'xmax, decimals, symbol, x, display_range, expected', + percent_data, ids=percent_ids) + def test_basic(self, xmax, decimals, symbol, + x, display_range, expected): + formatter = mticker.PercentFormatter(xmax, decimals, symbol) + with mpl.rc_context(rc={'text.usetex': False}): + assert formatter.format_pct(x, display_range) == expected + + @pytest.mark.parametrize('is_latex, usetex, expected', latex_data) + def test_latex(self, is_latex, usetex, expected): + fmt = mticker.PercentFormatter(symbol='\\{t}%', is_latex=is_latex) + with mpl.rc_context(rc={'text.usetex': usetex}): + assert fmt.format_pct(50, 100) == expected + + +def _impl_locale_comma(): + try: + locale.setlocale(locale.LC_ALL, 'de_DE.UTF-8') + except locale.Error: + print('SKIP: Locale de_DE.UTF-8 is not supported on this machine') + return + ticks = mticker.ScalarFormatter(useMathText=True, useLocale=True) + fmt = '$\\mathdefault{%1.1f}$' + x = ticks._format_maybe_minus_and_locale(fmt, 0.5) + assert x == '$\\mathdefault{0{,}5}$' + # Do not change , in the format string + fmt = ',$\\mathdefault{,%1.1f},$' + x = ticks._format_maybe_minus_and_locale(fmt, 0.5) + assert x == ',$\\mathdefault{,0{,}5},$' + # Make sure no brackets are added if not using math text + ticks = mticker.ScalarFormatter(useMathText=False, useLocale=True) + fmt = '%1.1f' + x = ticks._format_maybe_minus_and_locale(fmt, 0.5) + assert x == '0,5' + + +def test_locale_comma(): + # On some systems/pytest versions, `pytest.skip` in an exception handler + # does not skip, but is treated as an exception, so directly running this + # test can incorrectly fail instead of skip. + # Instead, run this test in a subprocess, which avoids the problem, and the + # need to fix the locale after. + proc = mpl.testing.subprocess_run_helper(_impl_locale_comma, timeout=60, + extra_env={'MPLBACKEND': 'Agg'}) + skip_msg = next((line[len('SKIP:'):].strip() + for line in proc.stdout.splitlines() + if line.startswith('SKIP:')), + '') + if skip_msg: + pytest.skip(skip_msg) + + +def test_majformatter_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_major_formatter(mticker.LogLocator()) + + +def test_minformatter_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_minor_formatter(mticker.LogLocator()) + + +def test_majlocator_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_major_locator(mticker.LogFormatter()) + + +def test_minlocator_type(): + fig, ax = plt.subplots() + with pytest.raises(TypeError): + ax.xaxis.set_minor_locator(mticker.LogFormatter()) + + +def test_minorticks_rc(): + fig = plt.figure() + + def minorticksubplot(xminor, yminor, i): + rc = {'xtick.minor.visible': xminor, + 'ytick.minor.visible': yminor} + with plt.rc_context(rc=rc): + ax = fig.add_subplot(2, 2, i) + + assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor + assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor + + minorticksubplot(False, False, 1) + minorticksubplot(True, False, 2) + minorticksubplot(False, True, 3) + minorticksubplot(True, True, 4) + + +def test_minorticks_toggle(): + """ + Test toggling minor ticks + + Test `.Axis.minorticks_on()` and `.Axis.minorticks_off()`. Testing is + limited to a subset of built-in scales - `'linear'`, `'log'`, `'asinh'` + and `'logit'`. `symlog` scale does not seem to have a working minor + locator and is omitted. In future, this test should cover all scales in + `matplotlib.scale.get_scale_names()`. + """ + fig = plt.figure() + def minortickstoggle(xminor, yminor, scale, i): + ax = fig.add_subplot(2, 2, i) + ax.set_xscale(scale) + ax.set_yscale(scale) + if not xminor and not yminor: + ax.minorticks_off() + if xminor and not yminor: + ax.xaxis.minorticks_on() + ax.yaxis.minorticks_off() + if not xminor and yminor: + ax.xaxis.minorticks_off() + ax.yaxis.minorticks_on() + if xminor and yminor: + ax.minorticks_on() + + assert (len(ax.xaxis.get_minor_ticks()) > 0) == xminor + assert (len(ax.yaxis.get_minor_ticks()) > 0) == yminor + + scales = ['linear', 'log', 'asinh', 'logit'] + for scale in scales: + minortickstoggle(False, False, scale, 1) + minortickstoggle(True, False, scale, 2) + minortickstoggle(False, True, scale, 3) + minortickstoggle(True, True, scale, 4) + fig.clear() + + plt.close(fig) + + +@pytest.mark.parametrize('remove_overlapping_locs, expected_num', + ((True, 6), + (None, 6), # this tests the default + (False, 9))) +def test_remove_overlap(remove_overlapping_locs, expected_num): + t = np.arange("2018-11-03", "2018-11-06", dtype="datetime64") + x = np.ones(len(t)) + + fig, ax = plt.subplots() + ax.plot(t, x) + + ax.xaxis.set_major_locator(mpl.dates.DayLocator()) + ax.xaxis.set_major_formatter(mpl.dates.DateFormatter('\n%a')) + + ax.xaxis.set_minor_locator(mpl.dates.HourLocator((0, 6, 12, 18))) + ax.xaxis.set_minor_formatter(mpl.dates.DateFormatter('%H:%M')) + # force there to be extra ticks + ax.xaxis.get_minor_ticks(15) + if remove_overlapping_locs is not None: + ax.xaxis.remove_overlapping_locs = remove_overlapping_locs + + # check that getter/setter exists + current = ax.xaxis.remove_overlapping_locs + assert (current == ax.xaxis.get_remove_overlapping_locs()) + plt.setp(ax.xaxis, remove_overlapping_locs=current) + new = ax.xaxis.remove_overlapping_locs + assert (new == ax.xaxis.remove_overlapping_locs) + + # check that the accessors filter correctly + # this is the method that does the actual filtering + assert len(ax.xaxis.get_minorticklocs()) == expected_num + # these three are derivative + assert len(ax.xaxis.get_minor_ticks()) == expected_num + assert len(ax.xaxis.get_minorticklabels()) == expected_num + assert len(ax.xaxis.get_minorticklines()) == expected_num*2 + + +@pytest.mark.parametrize('sub', [ + ['hi', 'aardvark'], + np.zeros((2, 2))]) +def test_bad_locator_subs(sub): + ll = mticker.LogLocator() + with pytest.raises(ValueError): + ll.set_params(subs=sub) + + +@pytest.mark.parametrize('numticks', [1, 2, 3, 9]) +@mpl.style.context('default') +def test_small_range_loglocator(numticks): + ll = mticker.LogLocator() + ll.set_params(numticks=numticks) + for top in [5, 7, 9, 11, 15, 50, 100, 1000]: + ticks = ll.tick_values(.5, top) + assert (np.diff(np.log10(ll.tick_values(6, 150))) == 1).all() + + +def test_NullFormatter(): + formatter = mticker.NullFormatter() + assert formatter(1.0) == '' + assert formatter.format_data(1.0) == '' + assert formatter.format_data_short(1.0) == '' + + +@pytest.mark.parametrize('formatter', ( + mticker.FuncFormatter(lambda a: f'val: {a}'), + mticker.FixedFormatter(('foo', 'bar')))) +def test_set_offset_string(formatter): + assert formatter.get_offset() == '' + formatter.set_offset_string('mpl') + assert formatter.get_offset() == 'mpl' + + +def test_minorticks_on_multi_fig(): + """ + Turning on minor gridlines in a multi-Axes Figure + that contains more than one boxplot and shares the x-axis + should not raise an exception. + """ + fig, ax = plt.subplots() + + ax.boxplot(np.arange(10), positions=[0]) + ax.boxplot(np.arange(10), positions=[0]) + ax.boxplot(np.arange(10), positions=[1]) + + ax.grid(which="major") + ax.grid(which="minor") + ax.minorticks_on() + fig.draw_without_rendering() + + assert ax.get_xgridlines() + assert isinstance(ax.xaxis.get_minor_locator(), mpl.ticker.AutoMinorLocator) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_units.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_units.py new file mode 100644 index 0000000000000000000000000000000000000000..ae6372fea1e19ad9e1bf9ac1e12c86ea1551943a --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_units.py @@ -0,0 +1,304 @@ +from datetime import datetime, timezone, timedelta +import platform +from unittest.mock import MagicMock + +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import check_figures_equal, image_comparison +import matplotlib.units as munits +from matplotlib.category import UnitData +import numpy as np +import pytest + + +# Basic class that wraps numpy array and has units +class Quantity: + def __init__(self, data, units): + self.magnitude = data + self.units = units + + def to(self, new_units): + factors = {('hours', 'seconds'): 3600, ('minutes', 'hours'): 1 / 60, + ('minutes', 'seconds'): 60, ('feet', 'miles'): 1 / 5280., + ('feet', 'inches'): 12, ('miles', 'inches'): 12 * 5280} + if self.units != new_units: + mult = factors[self.units, new_units] + return Quantity(mult * self.magnitude, new_units) + else: + return Quantity(self.magnitude, self.units) + + def __copy__(self): + return Quantity(self.magnitude, self.units) + + def __getattr__(self, attr): + return getattr(self.magnitude, attr) + + def __getitem__(self, item): + if np.iterable(self.magnitude): + return Quantity(self.magnitude[item], self.units) + else: + return Quantity(self.magnitude, self.units) + + def __array__(self): + return np.asarray(self.magnitude) + + +@pytest.fixture +def quantity_converter(): + # Create an instance of the conversion interface and + # mock so we can check methods called + qc = munits.ConversionInterface() + + def convert(value, unit, axis): + if hasattr(value, 'units'): + return value.to(unit).magnitude + elif np.iterable(value): + try: + return [v.to(unit).magnitude for v in value] + except AttributeError: + return [Quantity(v, axis.get_units()).to(unit).magnitude + for v in value] + else: + return Quantity(value, axis.get_units()).to(unit).magnitude + + def default_units(value, axis): + if hasattr(value, 'units'): + return value.units + elif np.iterable(value): + for v in value: + if hasattr(v, 'units'): + return v.units + return None + + qc.convert = MagicMock(side_effect=convert) + qc.axisinfo = MagicMock(side_effect=lambda u, a: + munits.AxisInfo(label=u, default_limits=(0, 100))) + qc.default_units = MagicMock(side_effect=default_units) + return qc + + +# Tests that the conversion machinery works properly for classes that +# work as a facade over numpy arrays (like pint) +@image_comparison(['plot_pint.png'], style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.03) +def test_numpy_facade(quantity_converter): + # use former defaults to match existing baseline image + plt.rcParams['axes.formatter.limits'] = -7, 7 + + # Register the class + munits.registry[Quantity] = quantity_converter + + # Simple test + y = Quantity(np.linspace(0, 30), 'miles') + x = Quantity(np.linspace(0, 5), 'hours') + + fig, ax = plt.subplots() + fig.subplots_adjust(left=0.15) # Make space for label + ax.plot(x, y, 'tab:blue') + ax.axhline(Quantity(26400, 'feet'), color='tab:red') + ax.axvline(Quantity(120, 'minutes'), color='tab:green') + ax.yaxis.set_units('inches') + ax.xaxis.set_units('seconds') + + assert quantity_converter.convert.called + assert quantity_converter.axisinfo.called + assert quantity_converter.default_units.called + + +# Tests gh-8908 +@image_comparison(['plot_masked_units.png'], remove_text=True, style='mpl20', + tol=0 if platform.machine() == 'x86_64' else 0.02) +def test_plot_masked_units(): + data = np.linspace(-5, 5) + data_masked = np.ma.array(data, mask=(data > -2) & (data < 2)) + data_masked_units = Quantity(data_masked, 'meters') + + fig, ax = plt.subplots() + ax.plot(data_masked_units) + + +def test_empty_set_limits_with_units(quantity_converter): + # Register the class + munits.registry[Quantity] = quantity_converter + + fig, ax = plt.subplots() + ax.set_xlim(Quantity(-1, 'meters'), Quantity(6, 'meters')) + ax.set_ylim(Quantity(-1, 'hours'), Quantity(16, 'hours')) + + +@image_comparison(['jpl_bar_units.png'], + savefig_kwarg={'dpi': 120}, style='mpl20') +def test_jpl_bar_units(): + import matplotlib.testing.jpl_units as units + units.register() + + day = units.Duration("ET", 24.0 * 60.0 * 60.0) + x = [0 * units.km, 1 * units.km, 2 * units.km] + w = [1 * day, 2 * day, 3 * day] + b = units.Epoch("ET", dt=datetime(2009, 4, 26)) + fig, ax = plt.subplots() + ax.bar(x, w, bottom=b) + ax.set_ylim([b - 1 * day, b + w[-1] + (1.001) * day]) + + +@image_comparison(['jpl_barh_units.png'], + savefig_kwarg={'dpi': 120}, style='mpl20') +def test_jpl_barh_units(): + import matplotlib.testing.jpl_units as units + units.register() + + day = units.Duration("ET", 24.0 * 60.0 * 60.0) + x = [0 * units.km, 1 * units.km, 2 * units.km] + w = [1 * day, 2 * day, 3 * day] + b = units.Epoch("ET", dt=datetime(2009, 4, 26)) + + fig, ax = plt.subplots() + ax.barh(x, w, left=b) + ax.set_xlim([b - 1 * day, b + w[-1] + (1.001) * day]) + + +def test_jpl_datetime_units_consistent(): + import matplotlib.testing.jpl_units as units + units.register() + + dt = datetime(2009, 4, 26) + jpl = units.Epoch("ET", dt=dt) + dt_conv = munits.registry.get_converter(dt).convert(dt, None, None) + jpl_conv = munits.registry.get_converter(jpl).convert(jpl, None, None) + assert dt_conv == jpl_conv + + +def test_empty_arrays(): + # Check that plotting an empty array with a dtype works + plt.scatter(np.array([], dtype='datetime64[ns]'), np.array([])) + + +def test_scatter_element0_masked(): + times = np.arange('2005-02', '2005-03', dtype='datetime64[D]') + y = np.arange(len(times), dtype=float) + y[0] = np.nan + fig, ax = plt.subplots() + ax.scatter(times, y) + fig.canvas.draw() + + +def test_errorbar_mixed_units(): + x = np.arange(10) + y = [datetime(2020, 5, i * 2 + 1) for i in x] + fig, ax = plt.subplots() + ax.errorbar(x, y, timedelta(days=0.5)) + fig.canvas.draw() + + +@check_figures_equal(extensions=["png"]) +def test_subclass(fig_test, fig_ref): + class subdate(datetime): + pass + + fig_test.subplots().plot(subdate(2000, 1, 1), 0, "o") + fig_ref.subplots().plot(datetime(2000, 1, 1), 0, "o") + + +def test_shared_axis_quantity(quantity_converter): + munits.registry[Quantity] = quantity_converter + x = Quantity(np.linspace(0, 1, 10), "hours") + y1 = Quantity(np.linspace(1, 2, 10), "feet") + y2 = Quantity(np.linspace(3, 4, 10), "feet") + fig, (ax1, ax2) = plt.subplots(2, 1, sharex='all', sharey='all') + ax1.plot(x, y1) + ax2.plot(x, y2) + assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "hours" + assert ax2.yaxis.get_units() == ax2.yaxis.get_units() == "feet" + ax1.xaxis.set_units("seconds") + ax2.yaxis.set_units("inches") + assert ax1.xaxis.get_units() == ax2.xaxis.get_units() == "seconds" + assert ax1.yaxis.get_units() == ax2.yaxis.get_units() == "inches" + + +def test_shared_axis_datetime(): + # datetime uses dates.DateConverter + y1 = [datetime(2020, i, 1, tzinfo=timezone.utc) for i in range(1, 13)] + y2 = [datetime(2021, i, 1, tzinfo=timezone.utc) for i in range(1, 13)] + fig, (ax1, ax2) = plt.subplots(1, 2, sharey=True) + ax1.plot(y1) + ax2.plot(y2) + ax1.yaxis.set_units(timezone(timedelta(hours=5))) + assert ax2.yaxis.units == timezone(timedelta(hours=5)) + + +def test_shared_axis_categorical(): + # str uses category.StrCategoryConverter + d1 = {"a": 1, "b": 2} + d2 = {"a": 3, "b": 4} + fig, (ax1, ax2) = plt.subplots(1, 2, sharex=True, sharey=True) + ax1.plot(d1.keys(), d1.values()) + ax2.plot(d2.keys(), d2.values()) + ax1.xaxis.set_units(UnitData(["c", "d"])) + assert "c" in ax2.xaxis.get_units()._mapping.keys() + + +def test_empty_default_limits(quantity_converter): + munits.registry[Quantity] = quantity_converter + fig, ax1 = plt.subplots() + ax1.xaxis.update_units(Quantity([10], "miles")) + fig.draw_without_rendering() + assert ax1.get_xlim() == (0, 100) + ax1.yaxis.update_units(Quantity([10], "miles")) + fig.draw_without_rendering() + assert ax1.get_ylim() == (0, 100) + + fig, ax = plt.subplots() + ax.axhline(30) + ax.plot(Quantity(np.arange(0, 3), "miles"), + Quantity(np.arange(0, 6, 2), "feet")) + fig.draw_without_rendering() + assert ax.get_xlim() == (0, 2) + assert ax.get_ylim() == (0, 30) + + fig, ax = plt.subplots() + ax.axvline(30) + ax.plot(Quantity(np.arange(0, 3), "miles"), + Quantity(np.arange(0, 6, 2), "feet")) + fig.draw_without_rendering() + assert ax.get_xlim() == (0, 30) + assert ax.get_ylim() == (0, 4) + + fig, ax = plt.subplots() + ax.xaxis.update_units(Quantity([10], "miles")) + ax.axhline(30) + fig.draw_without_rendering() + assert ax.get_xlim() == (0, 100) + assert ax.get_ylim() == (28.5, 31.5) + + fig, ax = plt.subplots() + ax.yaxis.update_units(Quantity([10], "miles")) + ax.axvline(30) + fig.draw_without_rendering() + assert ax.get_ylim() == (0, 100) + assert ax.get_xlim() == (28.5, 31.5) + + +# test array-like objects... +class Kernel: + def __init__(self, array): + self._array = np.asanyarray(array) + + def __array__(self, dtype=None, copy=None): + if dtype is not None and dtype != self._array.dtype: + if copy is not None and not copy: + raise ValueError( + f"Converting array from {self._array.dtype} to " + f"{dtype} requires a copy" + ) + + arr = np.asarray(self._array, dtype=dtype) + return (arr if not copy else np.copy(arr)) + + @property + def shape(self): + return self._array.shape + + +def test_plot_kernel(): + # just a smoketest that fail + kernel = Kernel([1, 2, 3, 4, 5]) + plt.plot(kernel) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py new file mode 100644 index 0000000000000000000000000000000000000000..342face4504fbc444c530fa08335cf19b3c98e6f --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_usetex.py @@ -0,0 +1,187 @@ +from tempfile import TemporaryFile + +import numpy as np +from packaging.version import parse as parse_version +import pytest + +import matplotlib as mpl +from matplotlib import dviread +from matplotlib.testing import _has_tex_package +from matplotlib.testing.decorators import check_figures_equal, image_comparison +from matplotlib.testing._markers import needs_usetex +import matplotlib.pyplot as plt + + +pytestmark = needs_usetex + + +@image_comparison( + baseline_images=['test_usetex'], + extensions=['pdf', 'png'], + style="mpl20") +def test_usetex(): + mpl.rcParams['text.usetex'] = True + fig, ax = plt.subplots() + kwargs = {"verticalalignment": "baseline", "size": 24, + "bbox": dict(pad=0, edgecolor="k", facecolor="none")} + ax.text(0.2, 0.7, + # the \LaTeX macro exercises character sizing and placement, + # \left[ ... \right\} draw some variable-height characters, + # \sqrt and \frac draw horizontal rules, \mathrm changes the font + r'\LaTeX\ $\left[\int\limits_e^{2e}' + r'\sqrt\frac{\log^3 x}{x}\,\mathrm{d}x \right\}$', + **kwargs) + ax.text(0.2, 0.3, "lg", **kwargs) + ax.text(0.4, 0.3, r"$\frac{1}{2}\pi$", **kwargs) + ax.text(0.6, 0.3, "$p^{3^A}$", **kwargs) + ax.text(0.8, 0.3, "$p_{3_2}$", **kwargs) + for x in {t.get_position()[0] for t in ax.texts}: + ax.axvline(x) + for y in {t.get_position()[1] for t in ax.texts}: + ax.axhline(y) + ax.set_axis_off() + + +@check_figures_equal() +def test_empty(fig_test, fig_ref): + mpl.rcParams['text.usetex'] = True + fig_test.text(.5, .5, "% a comment") + + +@check_figures_equal() +def test_unicode_minus(fig_test, fig_ref): + mpl.rcParams['text.usetex'] = True + fig_test.text(.5, .5, "$-$") + fig_ref.text(.5, .5, "\N{MINUS SIGN}") + + +def test_mathdefault(): + plt.rcParams["axes.formatter.use_mathtext"] = True + fig = plt.figure() + fig.add_subplot().set_xlim(-1, 1) + # Check that \mathdefault commands generated by tickers don't cause + # problems when later switching usetex on. + mpl.rcParams['text.usetex'] = True + fig.canvas.draw() + + +@image_comparison(['eqnarray.png']) +def test_multiline_eqnarray(): + text = ( + r'\begin{eqnarray*}' + r'foo\\' + r'bar\\' + r'baz\\' + r'\end{eqnarray*}' + ) + + fig = plt.figure(figsize=(1, 1)) + fig.text(0.5, 0.5, text, usetex=True, + horizontalalignment='center', verticalalignment='center') + + +@pytest.mark.parametrize("fontsize", [8, 10, 12]) +def test_minus_no_descent(fontsize): + # Test special-casing of minus descent in DviFont._height_depth_of, by + # checking that overdrawing a 1 and a -1 results in an overall height + # equivalent to drawing either of them separately. + mpl.style.use("mpl20") + mpl.rcParams['font.size'] = fontsize + heights = {} + fig = plt.figure() + for vals in [(1,), (-1,), (-1, 1)]: + fig.clear() + for x in vals: + fig.text(.5, .5, f"${x}$", usetex=True) + fig.canvas.draw() + # The following counts the number of non-fully-blank pixel rows. + heights[vals] = ((np.array(fig.canvas.buffer_rgba())[..., 0] != 255) + .any(axis=1).sum()) + assert len({*heights.values()}) == 1 + + +@pytest.mark.parametrize('pkg', ['xcolor', 'chemformula']) +def test_usetex_packages(pkg): + if not _has_tex_package(pkg): + pytest.skip(f'{pkg} is not available') + mpl.rcParams['text.usetex'] = True + + fig = plt.figure() + text = fig.text(0.5, 0.5, "Some text 0123456789") + fig.canvas.draw() + + mpl.rcParams['text.latex.preamble'] = ( + r'\PassOptionsToPackage{dvipsnames}{xcolor}\usepackage{%s}' % pkg) + fig = plt.figure() + text2 = fig.text(0.5, 0.5, "Some text 0123456789") + fig.canvas.draw() + np.testing.assert_array_equal(text2.get_window_extent(), + text.get_window_extent()) + + +@pytest.mark.parametrize( + "preamble", + [r"\usepackage[full]{textcomp}", r"\usepackage{underscore}"], +) +def test_latex_pkg_already_loaded(preamble): + plt.rcParams["text.latex.preamble"] = preamble + fig = plt.figure() + fig.text(.5, .5, "hello, world", usetex=True) + fig.canvas.draw() + + +def test_usetex_with_underscore(): + plt.rcParams["text.usetex"] = True + df = {"a_b": range(5)[::-1], "c": range(5)} + fig, ax = plt.subplots() + ax.plot("c", "a_b", data=df) + ax.legend() + ax.text(0, 0, "foo_bar", usetex=True) + plt.draw() + + +@pytest.mark.flaky(reruns=3) # Tends to hit a TeX cache lock on AppVeyor. +@pytest.mark.parametrize("fmt", ["pdf", "svg"]) +def test_missing_psfont(fmt, monkeypatch): + """An error is raised if a TeX font lacks a Type-1 equivalent""" + monkeypatch.setattr( + dviread.PsfontsMap, '__getitem__', + lambda self, k: dviread.PsFont( + texname=b'texfont', psname=b'Some Font', + effects=None, encoding=None, filename=None)) + mpl.rcParams['text.usetex'] = True + fig, ax = plt.subplots() + ax.text(0.5, 0.5, 'hello') + with TemporaryFile() as tmpfile, pytest.raises(ValueError): + fig.savefig(tmpfile, format=fmt) + + +try: + _old_gs_version = mpl._get_executable_info('gs').version < parse_version('9.55') +except mpl.ExecutableNotFoundError: + _old_gs_version = True + + +@image_comparison(baseline_images=['rotation'], extensions=['eps', 'pdf', 'png', 'svg'], + style='mpl20', tol=3.91 if _old_gs_version else 0) +def test_rotation(): + mpl.rcParams['text.usetex'] = True + + fig = plt.figure() + ax = fig.add_axes([0, 0, 1, 1]) + ax.set(xlim=[-0.5, 5], xticks=[], ylim=[-0.5, 3], yticks=[], frame_on=False) + + text = {val: val[0] for val in ['top', 'center', 'bottom', 'left', 'right']} + text['baseline'] = 'B' + text['center_baseline'] = 'C' + + for i, va in enumerate(['top', 'center', 'bottom', 'baseline', 'center_baseline']): + for j, ha in enumerate(['left', 'center', 'right']): + for k, angle in enumerate([0, 90, 180, 270]): + k //= 2 + x = i + k / 2 + y = j + k / 2 + ax.plot(x, y, '+', c=f'C{k}', markersize=20, markeredgewidth=0.5) + # 'My' checks full height letters plus descenders. + ax.text(x, y, f"$\\mathrm{{My {text[ha]}{text[va]} {angle}}}$", + rotation=angle, horizontalalignment=ha, verticalalignment=va) diff --git a/parrot/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..0f2cc411dbdfcebaba2f2837785ecbf06afe6d03 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/matplotlib/tests/test_widgets.py @@ -0,0 +1,1773 @@ +import functools +import io +from unittest import mock + +import matplotlib as mpl +from matplotlib.backend_bases import MouseEvent +import matplotlib.colors as mcolors +import matplotlib.widgets as widgets +import matplotlib.pyplot as plt +from matplotlib.testing.decorators import check_figures_equal, image_comparison +from matplotlib.testing.widgets import (click_and_drag, do_event, get_ax, + mock_event, noop) + +import numpy as np +from numpy.testing import assert_allclose + +import pytest + + +@pytest.fixture +def ax(): + return get_ax() + + +def test_save_blitted_widget_as_pdf(): + from matplotlib.widgets import CheckButtons, RadioButtons + from matplotlib.cbook import _get_running_interactive_framework + if _get_running_interactive_framework() not in ['headless', None]: + pytest.xfail("Callback exceptions are not raised otherwise.") + + fig, ax = plt.subplots( + nrows=2, ncols=2, figsize=(5, 2), width_ratios=[1, 2] + ) + default_rb = RadioButtons(ax[0, 0], ['Apples', 'Oranges']) + styled_rb = RadioButtons( + ax[0, 1], ['Apples', 'Oranges'], + label_props={'color': ['red', 'orange'], + 'fontsize': [16, 20]}, + radio_props={'edgecolor': ['red', 'orange'], + 'facecolor': ['mistyrose', 'peachpuff']} + ) + + default_cb = CheckButtons(ax[1, 0], ['Apples', 'Oranges'], + actives=[True, True]) + styled_cb = CheckButtons( + ax[1, 1], ['Apples', 'Oranges'], + actives=[True, True], + label_props={'color': ['red', 'orange'], + 'fontsize': [16, 20]}, + frame_props={'edgecolor': ['red', 'orange'], + 'facecolor': ['mistyrose', 'peachpuff']}, + check_props={'color': ['darkred', 'darkorange']} + ) + + ax[0, 0].set_title('Default') + ax[0, 1].set_title('Stylized') + # force an Agg render + fig.canvas.draw() + # force a pdf save + with io.BytesIO() as result_after: + fig.savefig(result_after, format='pdf') + + +@pytest.mark.parametrize('kwargs', [ + dict(), + dict(useblit=True, button=1), + dict(minspanx=10, minspany=10, spancoords='pixels'), + dict(props=dict(fill=True)), +]) +def test_rectangle_selector(ax, kwargs): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.RectangleSelector(ax, onselect, **kwargs) + do_event(tool, 'press', xdata=100, ydata=100, button=1) + do_event(tool, 'onmove', xdata=199, ydata=199, button=1) + + # purposely drag outside of axis for release + do_event(tool, 'release', xdata=250, ydata=250, button=1) + + if kwargs.get('drawtype', None) not in ['line', 'none']: + assert_allclose(tool.geometry, + [[100., 100, 199, 199, 100], + [100, 199, 199, 100, 100]], + err_msg=tool.geometry) + + onselect.assert_called_once() + (epress, erelease), kwargs = onselect.call_args + assert epress.xdata == 100 + assert epress.ydata == 100 + assert erelease.xdata == 199 + assert erelease.ydata == 199 + assert kwargs == {} + + +@pytest.mark.parametrize('spancoords', ['data', 'pixels']) +@pytest.mark.parametrize('minspanx, x1', [[0, 10], [1, 10.5], [1, 11]]) +@pytest.mark.parametrize('minspany, y1', [[0, 10], [1, 10.5], [1, 11]]) +def test_rectangle_minspan(ax, spancoords, minspanx, x1, minspany, y1): + + onselect = mock.Mock(spec=noop, return_value=None) + + x0, y0 = (10, 10) + if spancoords == 'pixels': + minspanx, minspany = (ax.transData.transform((x1, y1)) - + ax.transData.transform((x0, y0))) + + tool = widgets.RectangleSelector(ax, onselect, interactive=True, + spancoords=spancoords, + minspanx=minspanx, minspany=minspany) + # Too small to create a selector + click_and_drag(tool, start=(x0, x1), end=(y0, y1)) + assert not tool._selection_completed + onselect.assert_not_called() + + click_and_drag(tool, start=(20, 20), end=(30, 30)) + assert tool._selection_completed + onselect.assert_called_once() + + # Too small to create a selector. Should clear existing selector, and + # trigger onselect because there was a preexisting selector + onselect.reset_mock() + click_and_drag(tool, start=(x0, y0), end=(x1, y1)) + assert not tool._selection_completed + onselect.assert_called_once() + (epress, erelease), kwargs = onselect.call_args + assert epress.xdata == x0 + assert epress.ydata == y0 + assert erelease.xdata == x1 + assert erelease.ydata == y1 + assert kwargs == {} + + +def test_deprecation_selector_visible_attribute(ax): + tool = widgets.RectangleSelector(ax, lambda *args: None) + + assert tool.get_visible() + + with pytest.warns(mpl.MatplotlibDeprecationWarning, + match="was deprecated in Matplotlib 3.8"): + tool.visible + + +@pytest.mark.parametrize('drag_from_anywhere, new_center', + [[True, (60, 75)], + [False, (30, 20)]]) +def test_rectangle_drag(ax, drag_from_anywhere, new_center): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True, + drag_from_anywhere=drag_from_anywhere) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + assert tool.center == (50, 65) + # Drag inside rectangle, but away from centre handle + # + # If drag_from_anywhere == True, this will move the rectangle by (10, 10), + # giving it a new center of (60, 75) + # + # If drag_from_anywhere == False, this will create a new rectangle with + # center (30, 20) + click_and_drag(tool, start=(25, 15), end=(35, 25)) + assert tool.center == new_center + # Check that in both cases, dragging outside the rectangle draws a new + # rectangle + click_and_drag(tool, start=(175, 185), end=(185, 195)) + assert tool.center == (180, 190) + + +def test_rectangle_selector_set_props_handle_props(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True, + props=dict(facecolor='b', alpha=0.2), + handle_props=dict(alpha=0.5)) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + + artist = tool._selection_artist + assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2) + tool.set_props(facecolor='r', alpha=0.3) + assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3) + + for artist in tool._handles_artists: + assert artist.get_markeredgecolor() == 'black' + assert artist.get_alpha() == 0.5 + tool.set_handle_props(markeredgecolor='r', alpha=0.3) + for artist in tool._handles_artists: + assert artist.get_markeredgecolor() == 'r' + assert artist.get_alpha() == 0.3 + + +def test_rectangle_resize(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + assert tool.extents == (0.0, 100.0, 10.0, 120.0) + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdata_new, ydata_new = xdata + 10, ydata + 5 + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (extents[0], xdata_new, extents[2], ydata_new) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdata_new, ydata_new = xdata + 10, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (extents[0], xdata_new, extents[2], extents[3]) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdata_new, ydata_new = xdata + 15, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (xdata_new, extents[1], extents[2], extents[3]) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdata_new, ydata_new = xdata + 20, ydata + 25 + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert tool.extents == (xdata_new, extents[1], ydata_new, extents[3]) + + +def test_rectangle_add_state(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(125, 130)) + + with pytest.raises(ValueError): + tool.add_state('unsupported_state') + + with pytest.raises(ValueError): + tool.add_state('clear') + tool.add_state('move') + tool.add_state('square') + tool.add_state('center') + + +@pytest.mark.parametrize('add_state', [True, False]) +def test_rectangle_resize_center(ax, add_state): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(125, 130)) + assert tool.extents == (70.0, 125.0, 65.0, 130.0) + + if add_state: + tool.add_state('center') + use_key = None + else: + use_key = 'control' + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff, ydiff = 10, 5 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] - xdiff, xdata_new, + extents[2] - ydiff, ydata_new) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] - xdiff, xdata_new, + extents[2], extents[3]) + + # resize E handle negative diff + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -20 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] - xdiff, xdata_new, + extents[2], extents[3]) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 15 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1] - xdiff, + extents[2], extents[3]) + + # resize W handle negative diff + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -25 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1] - xdiff, + extents[2], extents[3]) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdiff, ydiff = 20, 25 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1] - xdiff, + ydata_new, extents[3] - ydiff) + + +@pytest.mark.parametrize('add_state', [True, False]) +def test_rectangle_resize_square(ax, add_state): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(120, 115)) + assert tool.extents == (70.0, 120.0, 65.0, 115.0) + + if add_state: + tool.add_state('square') + use_key = None + else: + use_key = 'shift' + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff, ydiff = 10, 5 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0], xdata_new, + extents[2], extents[3] + xdiff) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0], xdata_new, + extents[2], extents[3] + xdiff) + + # resize E handle negative diff + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -20 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0], xdata_new, + extents[2], extents[3] + xdiff) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 15 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1], + extents[2], extents[3] - xdiff) + + # resize W handle negative diff + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -25 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (xdata_new, extents[1], + extents[2], extents[3] - xdiff) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdiff, ydiff = 20, 25 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new), + key=use_key) + assert tool.extents == (extents[0] + ydiff, extents[1], + ydata_new, extents[3]) + + +def test_rectangle_resize_square_center(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(120, 115)) + tool.add_state('square') + tool.add_state('center') + assert_allclose(tool.extents, (70.0, 120.0, 65.0, 115.0)) + + # resize NE handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff, ydiff = 10, 5 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new, + extents[2] - xdiff, extents[3] + xdiff)) + + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new, + extents[2] - xdiff, extents[3] + xdiff)) + + # resize E handle negative diff + extents = tool.extents + xdata, ydata = extents[1], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -20 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] - xdiff, xdata_new, + extents[2] - xdiff, extents[3] + xdiff)) + + # resize W handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = 5 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff, + extents[2] + xdiff, extents[3] - xdiff)) + + # resize W handle negative diff + extents = tool.extents + xdata, ydata = extents[0], extents[2] + (extents[3] - extents[2]) / 2 + xdiff = -25 + xdata_new, ydata_new = xdata + xdiff, ydata + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (xdata_new, extents[1] - xdiff, + extents[2] + xdiff, extents[3] - xdiff)) + + # resize SW handle + extents = tool.extents + xdata, ydata = extents[0], extents[2] + xdiff, ydiff = 20, 25 + xdata_new, ydata_new = xdata + xdiff, ydata + ydiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, (extents[0] + ydiff, extents[1] - ydiff, + ydata_new, extents[3] - ydiff)) + + +@pytest.mark.parametrize('selector_class', + [widgets.RectangleSelector, widgets.EllipseSelector]) +def test_rectangle_rotate(ax, selector_class): + tool = selector_class(ax, onselect=noop, interactive=True) + # Draw rectangle + click_and_drag(tool, start=(100, 100), end=(130, 140)) + assert tool.extents == (100, 130, 100, 140) + assert len(tool._state) == 0 + + # Rotate anticlockwise using top-right corner + do_event(tool, 'on_key_press', key='r') + assert tool._state == {'rotate'} + assert len(tool._state) == 1 + click_and_drag(tool, start=(130, 140), end=(120, 145)) + do_event(tool, 'on_key_press', key='r') + assert len(tool._state) == 0 + # Extents shouldn't change (as shape of rectangle hasn't changed) + assert tool.extents == (100, 130, 100, 140) + assert_allclose(tool.rotation, 25.56, atol=0.01) + tool.rotation = 45 + assert tool.rotation == 45 + # Corners should move + assert_allclose(tool.corners, + np.array([[118.53, 139.75, 111.46, 90.25], + [95.25, 116.46, 144.75, 123.54]]), atol=0.01) + + # Scale using top-right corner + click_and_drag(tool, start=(110, 145), end=(110, 160)) + assert_allclose(tool.extents, (100, 139.75, 100, 151.82), atol=0.01) + + if selector_class == widgets.RectangleSelector: + with pytest.raises(ValueError): + tool._selection_artist.rotation_point = 'unvalid_value' + + +def test_rectangle_add_remove_set(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + # Draw rectangle + click_and_drag(tool, start=(100, 100), end=(130, 140)) + assert tool.extents == (100, 130, 100, 140) + assert len(tool._state) == 0 + for state in ['rotate', 'square', 'center']: + tool.add_state(state) + assert len(tool._state) == 1 + tool.remove_state(state) + assert len(tool._state) == 0 + + +@pytest.mark.parametrize('use_data_coordinates', [False, True]) +def test_rectangle_resize_square_center_aspect(ax, use_data_coordinates): + ax.set_aspect(0.8) + + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True, + use_data_coordinates=use_data_coordinates) + # Create rectangle + click_and_drag(tool, start=(70, 65), end=(120, 115)) + assert tool.extents == (70.0, 120.0, 65.0, 115.0) + tool.add_state('square') + tool.add_state('center') + + if use_data_coordinates: + # resize E handle + extents = tool.extents + xdata, ydata, width = extents[1], extents[3], extents[1] - extents[0] + xdiff, ycenter = 10, extents[2] + (extents[3] - extents[2]) / 2 + xdata_new, ydata_new = xdata + xdiff, ydata + ychange = width / 2 + xdiff + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new, + ycenter - ychange, ycenter + ychange]) + else: + # resize E handle + extents = tool.extents + xdata, ydata = extents[1], extents[3] + xdiff = 10 + xdata_new, ydata_new = xdata + xdiff, ydata + ychange = xdiff * 1 / tool._aspect_ratio_correction + click_and_drag(tool, start=(xdata, ydata), end=(xdata_new, ydata_new)) + assert_allclose(tool.extents, [extents[0] - xdiff, xdata_new, + 46.25, 133.75]) + + +def test_ellipse(ax): + """For ellipse, test out the key modifiers""" + tool = widgets.EllipseSelector(ax, onselect=noop, + grab_range=10, interactive=True) + tool.extents = (100, 150, 100, 150) + + # drag the rectangle + click_and_drag(tool, start=(125, 125), end=(145, 145)) + assert tool.extents == (120, 170, 120, 170) + + # create from center + click_and_drag(tool, start=(100, 100), end=(125, 125), key='control') + assert tool.extents == (75, 125, 75, 125) + + # create a square + click_and_drag(tool, start=(10, 10), end=(35, 30), key='shift') + extents = [int(e) for e in tool.extents] + assert extents == [10, 35, 10, 35] + + # create a square from center + click_and_drag(tool, start=(100, 100), end=(125, 130), key='ctrl+shift') + extents = [int(e) for e in tool.extents] + assert extents == [70, 130, 70, 130] + + assert tool.geometry.shape == (2, 73) + assert_allclose(tool.geometry[:, 0], [70., 100]) + + +def test_rectangle_handles(ax): + tool = widgets.RectangleSelector(ax, onselect=noop, + grab_range=10, + interactive=True, + handle_props={'markerfacecolor': 'r', + 'markeredgecolor': 'b'}) + tool.extents = (100, 150, 100, 150) + + assert_allclose(tool.corners, ((100, 150, 150, 100), (100, 100, 150, 150))) + assert tool.extents == (100, 150, 100, 150) + assert_allclose(tool.edge_centers, + ((100, 125.0, 150, 125.0), (125.0, 100, 125.0, 150))) + assert tool.extents == (100, 150, 100, 150) + + # grab a corner and move it + click_and_drag(tool, start=(100, 100), end=(120, 120)) + assert tool.extents == (120, 150, 120, 150) + + # grab the center and move it + click_and_drag(tool, start=(132, 132), end=(120, 120)) + assert tool.extents == (108, 138, 108, 138) + + # create a new rectangle + click_and_drag(tool, start=(10, 10), end=(100, 100)) + assert tool.extents == (10, 100, 10, 100) + + # Check that marker_props worked. + assert mcolors.same_color( + tool._corner_handles.artists[0].get_markerfacecolor(), 'r') + assert mcolors.same_color( + tool._corner_handles.artists[0].get_markeredgecolor(), 'b') + + +@pytest.mark.parametrize('interactive', [True, False]) +def test_rectangle_selector_onselect(ax, interactive): + # check when press and release events take place at the same position + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.RectangleSelector(ax, onselect, interactive=interactive) + # move outside of axis + click_and_drag(tool, start=(100, 110), end=(150, 120)) + + onselect.assert_called_once() + assert tool.extents == (100.0, 150.0, 110.0, 120.0) + + onselect.reset_mock() + click_and_drag(tool, start=(10, 100), end=(10, 100)) + onselect.assert_called_once() + + +@pytest.mark.parametrize('ignore_event_outside', [True, False]) +def test_rectangle_selector_ignore_outside(ax, ignore_event_outside): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.RectangleSelector(ax, onselect, + ignore_event_outside=ignore_event_outside) + click_and_drag(tool, start=(100, 110), end=(150, 120)) + onselect.assert_called_once() + assert tool.extents == (100.0, 150.0, 110.0, 120.0) + + onselect.reset_mock() + # Trigger event outside of span + click_and_drag(tool, start=(150, 150), end=(160, 160)) + if ignore_event_outside: + # event have been ignored and span haven't changed. + onselect.assert_not_called() + assert tool.extents == (100.0, 150.0, 110.0, 120.0) + else: + # A new shape is created + onselect.assert_called_once() + assert tool.extents == (150.0, 160.0, 150.0, 160.0) + + +@pytest.mark.parametrize('orientation, onmove_callback, kwargs', [ + ('horizontal', False, dict(minspan=10, useblit=True)), + ('vertical', True, dict(button=1)), + ('horizontal', False, dict(props=dict(fill=True))), + ('horizontal', False, dict(interactive=True)), +]) +def test_span_selector(ax, orientation, onmove_callback, kwargs): + onselect = mock.Mock(spec=noop, return_value=None) + onmove = mock.Mock(spec=noop, return_value=None) + if onmove_callback: + kwargs['onmove_callback'] = onmove + + # While at it, also test that span selectors work in the presence of twin axes on + # top of the axes that contain the selector. Note that we need to unforce the axes + # aspect here, otherwise the twin axes forces the original axes' limits (to respect + # aspect=1) which makes some of the values below go out of bounds. + ax.set_aspect("auto") + tax = ax.twinx() + + tool = widgets.SpanSelector(ax, onselect, orientation, **kwargs) + do_event(tool, 'press', xdata=100, ydata=100, button=1) + # move outside of axis + do_event(tool, 'onmove', xdata=199, ydata=199, button=1) + do_event(tool, 'release', xdata=250, ydata=250, button=1) + + onselect.assert_called_once_with(100, 199) + if onmove_callback: + onmove.assert_called_once_with(100, 199) + + +@pytest.mark.parametrize('interactive', [True, False]) +def test_span_selector_onselect(ax, interactive): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.SpanSelector(ax, onselect, 'horizontal', + interactive=interactive) + # move outside of axis + click_and_drag(tool, start=(100, 100), end=(150, 100)) + onselect.assert_called_once() + assert tool.extents == (100, 150) + + onselect.reset_mock() + click_and_drag(tool, start=(10, 100), end=(10, 100)) + onselect.assert_called_once() + + +@pytest.mark.parametrize('ignore_event_outside', [True, False]) +def test_span_selector_ignore_outside(ax, ignore_event_outside): + onselect = mock.Mock(spec=noop, return_value=None) + onmove = mock.Mock(spec=noop, return_value=None) + + tool = widgets.SpanSelector(ax, onselect, 'horizontal', + onmove_callback=onmove, + ignore_event_outside=ignore_event_outside) + click_and_drag(tool, start=(100, 100), end=(125, 125)) + onselect.assert_called_once() + onmove.assert_called_once() + assert tool.extents == (100, 125) + + onselect.reset_mock() + onmove.reset_mock() + # Trigger event outside of span + click_and_drag(tool, start=(150, 150), end=(160, 160)) + if ignore_event_outside: + # event have been ignored and span haven't changed. + onselect.assert_not_called() + onmove.assert_not_called() + assert tool.extents == (100, 125) + else: + # A new shape is created + onselect.assert_called_once() + onmove.assert_called_once() + assert tool.extents == (150, 160) + + +@pytest.mark.parametrize('drag_from_anywhere', [True, False]) +def test_span_selector_drag(ax, drag_from_anywhere): + # Create span + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True, + drag_from_anywhere=drag_from_anywhere) + click_and_drag(tool, start=(10, 10), end=(100, 120)) + assert tool.extents == (10, 100) + # Drag inside span + # + # If drag_from_anywhere == True, this will move the span by 10, + # giving new value extents = 20, 110 + # + # If drag_from_anywhere == False, this will create a new span with + # value extents = 25, 35 + click_and_drag(tool, start=(25, 15), end=(35, 25)) + if drag_from_anywhere: + assert tool.extents == (20, 110) + else: + assert tool.extents == (25, 35) + + # Check that in both cases, dragging outside the span draws a new span + click_and_drag(tool, start=(175, 185), end=(185, 195)) + assert tool.extents == (175, 185) + + +def test_span_selector_direction(ax): + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True) + assert tool.direction == 'horizontal' + assert tool._edge_handles.direction == 'horizontal' + + with pytest.raises(ValueError): + tool = widgets.SpanSelector(ax, onselect=noop, + direction='invalid_direction') + + tool.direction = 'vertical' + assert tool.direction == 'vertical' + assert tool._edge_handles.direction == 'vertical' + + with pytest.raises(ValueError): + tool.direction = 'invalid_string' + + +def test_span_selector_set_props_handle_props(ax): + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True, + props=dict(facecolor='b', alpha=0.2), + handle_props=dict(alpha=0.5)) + # Create rectangle + click_and_drag(tool, start=(0, 10), end=(100, 120)) + + artist = tool._selection_artist + assert artist.get_facecolor() == mcolors.to_rgba('b', alpha=0.2) + tool.set_props(facecolor='r', alpha=0.3) + assert artist.get_facecolor() == mcolors.to_rgba('r', alpha=0.3) + + for artist in tool._handles_artists: + assert artist.get_color() == 'b' + assert artist.get_alpha() == 0.5 + tool.set_handle_props(color='r', alpha=0.3) + for artist in tool._handles_artists: + assert artist.get_color() == 'r' + assert artist.get_alpha() == 0.3 + + +@pytest.mark.parametrize('selector', ['span', 'rectangle']) +def test_selector_clear(ax, selector): + kwargs = dict(ax=ax, onselect=noop, interactive=True) + if selector == 'span': + Selector = widgets.SpanSelector + kwargs['direction'] = 'horizontal' + else: + Selector = widgets.RectangleSelector + + tool = Selector(**kwargs) + click_and_drag(tool, start=(10, 10), end=(100, 120)) + + # press-release event outside the selector to clear the selector + click_and_drag(tool, start=(130, 130), end=(130, 130)) + assert not tool._selection_completed + + kwargs['ignore_event_outside'] = True + tool = Selector(**kwargs) + assert tool.ignore_event_outside + click_and_drag(tool, start=(10, 10), end=(100, 120)) + + # press-release event outside the selector ignored + click_and_drag(tool, start=(130, 130), end=(130, 130)) + assert tool._selection_completed + + do_event(tool, 'on_key_press', key='escape') + assert not tool._selection_completed + + +@pytest.mark.parametrize('selector', ['span', 'rectangle']) +def test_selector_clear_method(ax, selector): + if selector == 'span': + tool = widgets.SpanSelector(ax, onselect=noop, direction='horizontal', + interactive=True, + ignore_event_outside=True) + else: + tool = widgets.RectangleSelector(ax, onselect=noop, interactive=True) + click_and_drag(tool, start=(10, 10), end=(100, 120)) + assert tool._selection_completed + assert tool.get_visible() + if selector == 'span': + assert tool.extents == (10, 100) + + tool.clear() + assert not tool._selection_completed + assert not tool.get_visible() + + # Do another cycle of events to make sure we can + click_and_drag(tool, start=(10, 10), end=(50, 120)) + assert tool._selection_completed + assert tool.get_visible() + if selector == 'span': + assert tool.extents == (10, 50) + + +def test_span_selector_add_state(ax): + tool = widgets.SpanSelector(ax, noop, 'horizontal', + interactive=True) + + with pytest.raises(ValueError): + tool.add_state('unsupported_state') + with pytest.raises(ValueError): + tool.add_state('center') + with pytest.raises(ValueError): + tool.add_state('square') + + tool.add_state('move') + + +def test_tool_line_handle(ax): + positions = [20, 30, 50] + tool_line_handle = widgets.ToolLineHandles(ax, positions, 'horizontal', + useblit=False) + + for artist in tool_line_handle.artists: + assert not artist.get_animated() + assert not artist.get_visible() + + tool_line_handle.set_visible(True) + tool_line_handle.set_animated(True) + + for artist in tool_line_handle.artists: + assert artist.get_animated() + assert artist.get_visible() + + assert tool_line_handle.positions == positions + + +@pytest.mark.parametrize('direction', ("horizontal", "vertical")) +def test_span_selector_bound(direction): + fig, ax = plt.subplots(1, 1) + ax.plot([10, 20], [10, 30]) + ax.figure.canvas.draw() + x_bound = ax.get_xbound() + y_bound = ax.get_ybound() + + tool = widgets.SpanSelector(ax, print, direction, interactive=True) + assert ax.get_xbound() == x_bound + assert ax.get_ybound() == y_bound + + bound = x_bound if direction == 'horizontal' else y_bound + assert tool._edge_handles.positions == list(bound) + + press_data = (10.5, 11.5) + move_data = (11, 13) # Updating selector is done in onmove + release_data = move_data + click_and_drag(tool, start=press_data, end=move_data) + + assert ax.get_xbound() == x_bound + assert ax.get_ybound() == y_bound + + index = 0 if direction == 'horizontal' else 1 + handle_positions = [press_data[index], release_data[index]] + assert tool._edge_handles.positions == handle_positions + + +@pytest.mark.backend('QtAgg', skip_on_importerror=True) +def test_span_selector_animated_artists_callback(): + """Check that the animated artists changed in callbacks are updated.""" + x = np.linspace(0, 2 * np.pi, 100) + values = np.sin(x) + + fig, ax = plt.subplots() + ln, = ax.plot(x, values, animated=True) + ln2, = ax.plot([], animated=True) + + # spin the event loop to let the backend process any pending operations + # before drawing artists + # See blitting tutorial + plt.pause(0.1) + ax.draw_artist(ln) + fig.canvas.blit(fig.bbox) + + def mean(vmin, vmax): + # Return mean of values in x between *vmin* and *vmax* + indmin, indmax = np.searchsorted(x, (vmin, vmax)) + v = values[indmin:indmax].mean() + ln2.set_data(x, np.full_like(x, v)) + + span = widgets.SpanSelector(ax, mean, direction='horizontal', + onmove_callback=mean, + interactive=True, + drag_from_anywhere=True, + useblit=True) + + # Add span selector and check that the line is draw after it was updated + # by the callback + press_data = [1, 2] + move_data = [2, 2] + do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1) + do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1) + assert span._get_animated_artists() == (ln, ln2) + assert ln.stale is False + assert ln2.stale + assert_allclose(ln2.get_ydata(), 0.9547335049088455) + span.update() + assert ln2.stale is False + + # Change span selector and check that the line is drawn/updated after its + # value was updated by the callback + press_data = [4, 0] + move_data = [5, 2] + release_data = [5, 2] + do_event(span, 'press', xdata=press_data[0], ydata=press_data[1], button=1) + do_event(span, 'onmove', xdata=move_data[0], ydata=move_data[1], button=1) + assert ln.stale is False + assert ln2.stale + assert_allclose(ln2.get_ydata(), -0.9424150707548072) + do_event(span, 'release', xdata=release_data[0], + ydata=release_data[1], button=1) + assert ln2.stale is False + + +def test_snapping_values_span_selector(ax): + def onselect(*args): + pass + + tool = widgets.SpanSelector(ax, onselect, direction='horizontal',) + snap_function = tool._snap + + snap_values = np.linspace(0, 5, 11) + values = np.array([-0.1, 0.1, 0.2, 0.5, 0.6, 0.7, 0.9, 4.76, 5.0, 5.5]) + expect = np.array([00.0, 0.0, 0.0, 0.5, 0.5, 0.5, 1.0, 5.00, 5.0, 5.0]) + values = snap_function(values, snap_values) + assert_allclose(values, expect) + + +def test_span_selector_snap(ax): + def onselect(vmin, vmax): + ax._got_onselect = True + + snap_values = np.arange(50) * 4 + + tool = widgets.SpanSelector(ax, onselect, direction='horizontal', + snap_values=snap_values) + tool.extents = (17, 35) + assert tool.extents == (16, 36) + + tool.snap_values = None + assert tool.snap_values is None + tool.extents = (17, 35) + assert tool.extents == (17, 35) + + +def test_span_selector_extents(ax): + tool = widgets.SpanSelector( + ax, lambda a, b: None, "horizontal", ignore_event_outside=True + ) + tool.extents = (5, 10) + + assert tool.extents == (5, 10) + assert tool._selection_completed + + # Since `ignore_event_outside=True`, this event should be ignored + press_data = (12, 14) + release_data = (20, 14) + click_and_drag(tool, start=press_data, end=release_data) + + assert tool.extents == (5, 10) + + +@pytest.mark.parametrize('kwargs', [ + dict(), + dict(useblit=False, props=dict(color='red')), + dict(useblit=True, button=1), +]) +def test_lasso_selector(ax, kwargs): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.LassoSelector(ax, onselect, **kwargs) + do_event(tool, 'press', xdata=100, ydata=100, button=1) + do_event(tool, 'onmove', xdata=125, ydata=125, button=1) + do_event(tool, 'release', xdata=150, ydata=150, button=1) + + onselect.assert_called_once_with([(100, 100), (125, 125), (150, 150)]) + + +def test_lasso_selector_set_props(ax): + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.LassoSelector(ax, onselect, props=dict(color='b', alpha=0.2)) + + artist = tool._selection_artist + assert mcolors.same_color(artist.get_color(), 'b') + assert artist.get_alpha() == 0.2 + tool.set_props(color='r', alpha=0.3) + assert mcolors.same_color(artist.get_color(), 'r') + assert artist.get_alpha() == 0.3 + + +def test_lasso_set_props(ax): + onselect = mock.Mock(spec=noop, return_value=None) + tool = widgets.Lasso(ax, (100, 100), onselect) + line = tool.line + assert mcolors.same_color(line.get_color(), 'black') + assert line.get_linestyle() == '-' + assert line.get_lw() == 2 + tool = widgets.Lasso(ax, (100, 100), onselect, props=dict( + linestyle='-', color='darkblue', alpha=0.2, lw=1)) + + line = tool.line + assert mcolors.same_color(line.get_color(), 'darkblue') + assert line.get_alpha() == 0.2 + assert line.get_lw() == 1 + assert line.get_linestyle() == '-' + line.set_color('r') + line.set_alpha(0.3) + assert mcolors.same_color(line.get_color(), 'r') + assert line.get_alpha() == 0.3 + + +def test_CheckButtons(ax): + labels = ('a', 'b', 'c') + check = widgets.CheckButtons(ax, labels, (True, False, True)) + assert check.get_status() == [True, False, True] + check.set_active(0) + assert check.get_status() == [False, False, True] + assert check.get_checked_labels() == ['c'] + check.clear() + assert check.get_status() == [False, False, False] + assert check.get_checked_labels() == [] + + for invalid_index in [-1, len(labels), len(labels)+5]: + with pytest.raises(ValueError): + check.set_active(index=invalid_index) + + for invalid_value in ['invalid', -1]: + with pytest.raises(TypeError): + check.set_active(1, state=invalid_value) + + cid = check.on_clicked(lambda: None) + check.disconnect(cid) + + +@pytest.mark.parametrize("toolbar", ["none", "toolbar2", "toolmanager"]) +def test_TextBox(ax, toolbar): + # Avoid "toolmanager is provisional" warning. + plt.rcParams._set("toolbar", toolbar) + + submit_event = mock.Mock(spec=noop, return_value=None) + text_change_event = mock.Mock(spec=noop, return_value=None) + tool = widgets.TextBox(ax, '') + tool.on_submit(submit_event) + tool.on_text_change(text_change_event) + + assert tool.text == '' + + do_event(tool, '_click') + + tool.set_val('x**2') + + assert tool.text == 'x**2' + assert text_change_event.call_count == 1 + + tool.begin_typing() + tool.stop_typing() + + assert submit_event.call_count == 2 + + do_event(tool, '_click', xdata=.5, ydata=.5) # Ensure the click is in the axes. + do_event(tool, '_keypress', key='+') + do_event(tool, '_keypress', key='5') + + assert text_change_event.call_count == 3 + + +def test_RadioButtons(ax): + radio = widgets.RadioButtons(ax, ('Radio 1', 'Radio 2', 'Radio 3')) + radio.set_active(1) + assert radio.value_selected == 'Radio 2' + assert radio.index_selected == 1 + radio.clear() + assert radio.value_selected == 'Radio 1' + assert radio.index_selected == 0 + + +@image_comparison(['check_radio_buttons.png'], style='mpl20', remove_text=True) +def test_check_radio_buttons_image(): + ax = get_ax() + fig = ax.figure + fig.subplots_adjust(left=0.3) + + rax1 = fig.add_axes((0.05, 0.7, 0.2, 0.15)) + rb1 = widgets.RadioButtons(rax1, ('Radio 1', 'Radio 2', 'Radio 3')) + + rax2 = fig.add_axes((0.05, 0.5, 0.2, 0.15)) + cb1 = widgets.CheckButtons(rax2, ('Check 1', 'Check 2', 'Check 3'), + (False, True, True)) + + rax3 = fig.add_axes((0.05, 0.3, 0.2, 0.15)) + rb3 = widgets.RadioButtons( + rax3, ('Radio 1', 'Radio 2', 'Radio 3'), + label_props={'fontsize': [8, 12, 16], + 'color': ['red', 'green', 'blue']}, + radio_props={'edgecolor': ['red', 'green', 'blue'], + 'facecolor': ['mistyrose', 'palegreen', 'lightblue']}) + + rax4 = fig.add_axes((0.05, 0.1, 0.2, 0.15)) + cb4 = widgets.CheckButtons( + rax4, ('Check 1', 'Check 2', 'Check 3'), (False, True, True), + label_props={'fontsize': [8, 12, 16], + 'color': ['red', 'green', 'blue']}, + frame_props={'edgecolor': ['red', 'green', 'blue'], + 'facecolor': ['mistyrose', 'palegreen', 'lightblue']}, + check_props={'color': ['red', 'green', 'blue']}) + + +@check_figures_equal(extensions=["png"]) +def test_radio_buttons(fig_test, fig_ref): + widgets.RadioButtons(fig_test.subplots(), ["tea", "coffee"]) + ax = fig_ref.add_subplot(xticks=[], yticks=[]) + ax.scatter([.15, .15], [2/3, 1/3], transform=ax.transAxes, + s=(plt.rcParams["font.size"] / 2) ** 2, c=["C0", "none"]) + ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center") + ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center") + + +@check_figures_equal(extensions=['png']) +def test_radio_buttons_props(fig_test, fig_ref): + label_props = {'color': ['red'], 'fontsize': [24]} + radio_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2} + + widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'], + label_props=label_props, radio_props=radio_props) + + cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee']) + cb.set_label_props(label_props) + # Setting the label size automatically increases default marker size, so we + # need to do that here as well. + cb.set_radio_props({**radio_props, 's': (24 / 2)**2}) + + +def test_radio_button_active_conflict(ax): + with pytest.warns(UserWarning, + match=r'Both the \*activecolor\* parameter'): + rb = widgets.RadioButtons(ax, ['tea', 'coffee'], activecolor='red', + radio_props={'facecolor': 'green'}) + # *radio_props*' facecolor wins over *activecolor* + assert mcolors.same_color(rb._buttons.get_facecolor(), ['green', 'none']) + + +@check_figures_equal(extensions=['png']) +def test_radio_buttons_activecolor_change(fig_test, fig_ref): + widgets.RadioButtons(fig_ref.subplots(), ['tea', 'coffee'], + activecolor='green') + + # Test property setter. + cb = widgets.RadioButtons(fig_test.subplots(), ['tea', 'coffee'], + activecolor='red') + cb.activecolor = 'green' + + +@check_figures_equal(extensions=["png"]) +def test_check_buttons(fig_test, fig_ref): + widgets.CheckButtons(fig_test.subplots(), ["tea", "coffee"], [True, True]) + ax = fig_ref.add_subplot(xticks=[], yticks=[]) + ax.scatter([.15, .15], [2/3, 1/3], marker='s', transform=ax.transAxes, + s=(plt.rcParams["font.size"] / 2) ** 2, c=["none", "none"]) + ax.scatter([.15, .15], [2/3, 1/3], marker='x', transform=ax.transAxes, + s=(plt.rcParams["font.size"] / 2) ** 2, c=["k", "k"]) + ax.text(.25, 2/3, "tea", transform=ax.transAxes, va="center") + ax.text(.25, 1/3, "coffee", transform=ax.transAxes, va="center") + + +@check_figures_equal(extensions=['png']) +def test_check_button_props(fig_test, fig_ref): + label_props = {'color': ['red'], 'fontsize': [24]} + frame_props = {'facecolor': 'green', 'edgecolor': 'blue', 'linewidth': 2} + check_props = {'facecolor': 'red', 'linewidth': 2} + + widgets.CheckButtons(fig_ref.subplots(), ['tea', 'coffee'], [True, True], + label_props=label_props, frame_props=frame_props, + check_props=check_props) + + cb = widgets.CheckButtons(fig_test.subplots(), ['tea', 'coffee'], + [True, True]) + cb.set_label_props(label_props) + # Setting the label size automatically increases default marker size, so we + # need to do that here as well. + cb.set_frame_props({**frame_props, 's': (24 / 2)**2}) + # FIXME: Axes.scatter promotes facecolor to edgecolor on unfilled markers, + # but Collection.update doesn't do that (it forgot the marker already). + # This means we cannot pass facecolor to both setters directly. + check_props['edgecolor'] = check_props.pop('facecolor') + cb.set_check_props({**check_props, 's': (24 / 2)**2}) + + +def test_slider_slidermin_slidermax_invalid(): + fig, ax = plt.subplots() + # test min/max with floats + with pytest.raises(ValueError): + widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + slidermin=10.0) + with pytest.raises(ValueError): + widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + slidermax=10.0) + + +def test_slider_slidermin_slidermax(): + fig, ax = plt.subplots() + slider_ = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=5.0) + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=1.0, slidermin=slider_) + assert slider.val == slider_.val + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=10.0, slidermax=slider_) + assert slider.val == slider_.val + + +def test_slider_valmin_valmax(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=-10.0) + assert slider.val == slider.valmin + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=25.0) + assert slider.val == slider.valmax + + +def test_slider_valstep_snapping(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=11.4, valstep=1) + assert slider.val == 11 + + slider = widgets.Slider(ax=ax, label='', valmin=0.0, valmax=24.0, + valinit=11.4, valstep=[0, 1, 5.5, 19.7]) + assert slider.val == 5.5 + + +def test_slider_horizontal_vertical(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24, + valinit=12, orientation='horizontal') + slider.set_val(10) + assert slider.val == 10 + # check the dimension of the slider patch in axes units + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.bounds, [0, .25, 10/24, .5]) + + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=24, + valinit=12, orientation='vertical') + slider.set_val(10) + assert slider.val == 10 + # check the dimension of the slider patch in axes units + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.bounds, [.25, 0, .5, 10/24]) + + +def test_slider_reset(): + fig, ax = plt.subplots() + slider = widgets.Slider(ax=ax, label='', valmin=0, valmax=1, valinit=.5) + slider.set_val(0.75) + slider.reset() + assert slider.val == 0.5 + + +@pytest.mark.parametrize("orientation", ["horizontal", "vertical"]) +def test_range_slider(orientation): + if orientation == "vertical": + idx = [1, 0, 3, 2] + else: + idx = [0, 1, 2, 3] + + fig, ax = plt.subplots() + + slider = widgets.RangeSlider( + ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation, + valinit=[0.1, 0.34] + ) + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.get_points().flatten()[idx], [0.1, 0.25, 0.34, 0.75]) + + # Check initial value is set correctly + assert_allclose(slider.val, (0.1, 0.34)) + + def handle_positions(slider): + if orientation == "vertical": + return [h.get_ydata()[0] for h in slider._handles] + else: + return [h.get_xdata()[0] for h in slider._handles] + + slider.set_val((0.4, 0.6)) + assert_allclose(slider.val, (0.4, 0.6)) + assert_allclose(handle_positions(slider), (0.4, 0.6)) + + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.get_points().flatten()[idx], [0.4, .25, 0.6, .75]) + + slider.set_val((0.2, 0.1)) + assert_allclose(slider.val, (0.1, 0.2)) + assert_allclose(handle_positions(slider), (0.1, 0.2)) + + slider.set_val((-1, 10)) + assert_allclose(slider.val, (0, 1)) + assert_allclose(handle_positions(slider), (0, 1)) + + slider.reset() + assert_allclose(slider.val, (0.1, 0.34)) + assert_allclose(handle_positions(slider), (0.1, 0.34)) + + +@pytest.mark.parametrize("orientation", ["horizontal", "vertical"]) +def test_range_slider_same_init_values(orientation): + if orientation == "vertical": + idx = [1, 0, 3, 2] + else: + idx = [0, 1, 2, 3] + + fig, ax = plt.subplots() + + slider = widgets.RangeSlider( + ax=ax, label="", valmin=0.0, valmax=1.0, orientation=orientation, + valinit=[0, 0] + ) + box = slider.poly.get_extents().transformed(ax.transAxes.inverted()) + assert_allclose(box.get_points().flatten()[idx], [0, 0.25, 0, 0.75]) + + +def check_polygon_selector(event_sequence, expected_result, selections_count, + **kwargs): + """ + Helper function to test Polygon Selector. + + Parameters + ---------- + event_sequence : list of tuples (etype, dict()) + A sequence of events to perform. The sequence is a list of tuples + where the first element of the tuple is an etype (e.g., 'onmove', + 'press', etc.), and the second element of the tuple is a dictionary of + the arguments for the event (e.g., xdata=5, key='shift', etc.). + expected_result : list of vertices (xdata, ydata) + The list of vertices that are expected to result from the event + sequence. + selections_count : int + Wait for the tool to call its `onselect` function `selections_count` + times, before comparing the result to the `expected_result` + **kwargs + Keyword arguments are passed to PolygonSelector. + """ + ax = get_ax() + + onselect = mock.Mock(spec=noop, return_value=None) + + tool = widgets.PolygonSelector(ax, onselect, **kwargs) + + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + + assert onselect.call_count == selections_count + assert onselect.call_args == ((expected_result, ), {}) + + +def polygon_place_vertex(xdata, ydata): + return [('onmove', dict(xdata=xdata, ydata=ydata)), + ('press', dict(xdata=xdata, ydata=ydata)), + ('release', dict(xdata=xdata, ydata=ydata))] + + +def polygon_remove_vertex(xdata, ydata): + return [('onmove', dict(xdata=xdata, ydata=ydata)), + ('press', dict(xdata=xdata, ydata=ydata, button=3)), + ('release', dict(xdata=xdata, ydata=ydata, button=3))] + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector(draw_bounding_box): + check_selector = functools.partial( + check_polygon_selector, draw_bounding_box=draw_bounding_box) + + # Simple polygon + expected_result = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + check_selector(event_sequence, expected_result, 1) + + # Move first vertex before completing the polygon. + expected_result = [(75, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + ('on_key_press', dict(key='control')), + ('onmove', dict(xdata=50, ydata=50)), + ('press', dict(xdata=50, ydata=50)), + ('onmove', dict(xdata=75, ydata=50)), + ('release', dict(xdata=75, ydata=50)), + ('on_key_release', dict(key='control')), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(75, 50), + ] + check_selector(event_sequence, expected_result, 1) + + # Move first two vertices at once before completing the polygon. + expected_result = [(50, 75), (150, 75), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + ('on_key_press', dict(key='shift')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=100, ydata=125)), + ('release', dict(xdata=100, ydata=125)), + ('on_key_release', dict(key='shift')), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 75), + ] + check_selector(event_sequence, expected_result, 1) + + # Move first vertex after completing the polygon. + expected_result = [(75, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ('onmove', dict(xdata=50, ydata=50)), + ('press', dict(xdata=50, ydata=50)), + ('onmove', dict(xdata=75, ydata=50)), + ('release', dict(xdata=75, ydata=50)), + ] + check_selector(event_sequence, expected_result, 2) + + # Move all vertices after completing the polygon. + expected_result = [(75, 75), (175, 75), (75, 175)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ('on_key_press', dict(key='shift')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=125, ydata=125)), + ('release', dict(xdata=125, ydata=125)), + ('on_key_release', dict(key='shift')), + ] + check_selector(event_sequence, expected_result, 2) + + # Try to move a vertex and move all before placing any vertices. + expected_result = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + ('on_key_press', dict(key='control')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=125, ydata=125)), + ('release', dict(xdata=125, ydata=125)), + ('on_key_release', dict(key='control')), + ('on_key_press', dict(key='shift')), + ('onmove', dict(xdata=100, ydata=100)), + ('press', dict(xdata=100, ydata=100)), + ('onmove', dict(xdata=125, ydata=125)), + ('release', dict(xdata=125, ydata=125)), + ('on_key_release', dict(key='shift')), + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + check_selector(event_sequence, expected_result, 1) + + # Try to place vertex out-of-bounds, then reset, and start a new polygon. + expected_result = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(250, 50), + ('on_key_press', dict(key='escape')), + ('on_key_release', dict(key='escape')), + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + check_selector(event_sequence, expected_result, 1) + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_set_props_handle_props(ax, draw_bounding_box): + tool = widgets.PolygonSelector(ax, onselect=noop, + props=dict(color='b', alpha=0.2), + handle_props=dict(alpha=0.5), + draw_bounding_box=draw_bounding_box) + + event_sequence = [ + *polygon_place_vertex(50, 50), + *polygon_place_vertex(150, 50), + *polygon_place_vertex(50, 150), + *polygon_place_vertex(50, 50), + ] + + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + + artist = tool._selection_artist + assert artist.get_color() == 'b' + assert artist.get_alpha() == 0.2 + tool.set_props(color='r', alpha=0.3) + assert artist.get_color() == 'r' + assert artist.get_alpha() == 0.3 + + for artist in tool._handles_artists: + assert artist.get_color() == 'b' + assert artist.get_alpha() == 0.5 + tool.set_handle_props(color='r', alpha=0.3) + for artist in tool._handles_artists: + assert artist.get_color() == 'r' + assert artist.get_alpha() == 0.3 + + +@check_figures_equal() +def test_rect_visibility(fig_test, fig_ref): + # Check that requesting an invisible selector makes it invisible + ax_test = fig_test.subplots() + _ = fig_ref.subplots() + + tool = widgets.RectangleSelector(ax_test, onselect=noop, + props={'visible': False}) + tool.extents = (0.2, 0.8, 0.3, 0.7) + + +# Change the order that the extra point is inserted in +@pytest.mark.parametrize('idx', [1, 2, 3]) +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_remove(idx, draw_bounding_box): + verts = [(50, 50), (150, 50), (50, 150)] + event_sequence = [polygon_place_vertex(*verts[0]), + polygon_place_vertex(*verts[1]), + polygon_place_vertex(*verts[2]), + # Finish the polygon + polygon_place_vertex(*verts[0])] + # Add an extra point + event_sequence.insert(idx, polygon_place_vertex(200, 200)) + # Remove the extra point + event_sequence.append(polygon_remove_vertex(200, 200)) + # Flatten list of lists + event_sequence = sum(event_sequence, []) + check_polygon_selector(event_sequence, verts, 2, + draw_bounding_box=draw_bounding_box) + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_remove_first_point(draw_bounding_box): + verts = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[0]), + *polygon_remove_vertex(*verts[0]), + ] + check_polygon_selector(event_sequence, verts[1:], 2, + draw_bounding_box=draw_bounding_box) + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +def test_polygon_selector_redraw(ax, draw_bounding_box): + verts = [(50, 50), (150, 50), (50, 150)] + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[0]), + # Polygon completed, now remove first two verts. + *polygon_remove_vertex(*verts[1]), + *polygon_remove_vertex(*verts[2]), + # At this point the tool should be reset so we can add more vertices. + *polygon_place_vertex(*verts[1]), + ] + + tool = widgets.PolygonSelector(ax, onselect=noop, + draw_bounding_box=draw_bounding_box) + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + # After removing two verts, only one remains, and the + # selector should be automatically resete + assert tool.verts == verts[0:2] + + +@pytest.mark.parametrize('draw_bounding_box', [False, True]) +@check_figures_equal(extensions=['png']) +def test_polygon_selector_verts_setter(fig_test, fig_ref, draw_bounding_box): + verts = [(0.1, 0.4), (0.5, 0.9), (0.3, 0.2)] + ax_test = fig_test.add_subplot() + + tool_test = widgets.PolygonSelector( + ax_test, onselect=noop, draw_bounding_box=draw_bounding_box) + tool_test.verts = verts + assert tool_test.verts == verts + + ax_ref = fig_ref.add_subplot() + tool_ref = widgets.PolygonSelector( + ax_ref, onselect=noop, draw_bounding_box=draw_bounding_box) + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[0]), + ] + for (etype, event_args) in event_sequence: + do_event(tool_ref, etype, **event_args) + + +def test_polygon_selector_box(ax): + # Create a diamond (adjusting axes lims s.t. the diamond lies within axes limits). + ax.set(xlim=(-10, 50), ylim=(-10, 50)) + verts = [(20, 0), (0, 20), (20, 40), (40, 20)] + event_sequence = [ + *polygon_place_vertex(*verts[0]), + *polygon_place_vertex(*verts[1]), + *polygon_place_vertex(*verts[2]), + *polygon_place_vertex(*verts[3]), + *polygon_place_vertex(*verts[0]), + ] + + # Create selector + tool = widgets.PolygonSelector(ax, onselect=noop, draw_bounding_box=True) + for (etype, event_args) in event_sequence: + do_event(tool, etype, **event_args) + + # In order to trigger the correct callbacks, trigger events on the canvas + # instead of the individual tools + t = ax.transData + canvas = ax.figure.canvas + + # Scale to half size using the top right corner of the bounding box + MouseEvent( + "button_press_event", canvas, *t.transform((40, 40)), 1)._process() + MouseEvent( + "motion_notify_event", canvas, *t.transform((20, 20)))._process() + MouseEvent( + "button_release_event", canvas, *t.transform((20, 20)), 1)._process() + np.testing.assert_allclose( + tool.verts, [(10, 0), (0, 10), (10, 20), (20, 10)]) + + # Move using the center of the bounding box + MouseEvent( + "button_press_event", canvas, *t.transform((10, 10)), 1)._process() + MouseEvent( + "motion_notify_event", canvas, *t.transform((30, 30)))._process() + MouseEvent( + "button_release_event", canvas, *t.transform((30, 30)), 1)._process() + np.testing.assert_allclose( + tool.verts, [(30, 20), (20, 30), (30, 40), (40, 30)]) + + # Remove a point from the polygon and check that the box extents update + np.testing.assert_allclose( + tool._box.extents, (20.0, 40.0, 20.0, 40.0)) + + MouseEvent( + "button_press_event", canvas, *t.transform((30, 20)), 3)._process() + MouseEvent( + "button_release_event", canvas, *t.transform((30, 20)), 3)._process() + np.testing.assert_allclose( + tool.verts, [(20, 30), (30, 40), (40, 30)]) + np.testing.assert_allclose( + tool._box.extents, (20.0, 40.0, 30.0, 40.0)) + + +def test_polygon_selector_clear_method(ax): + onselect = mock.Mock(spec=noop, return_value=None) + tool = widgets.PolygonSelector(ax, onselect) + + for result in ([(50, 50), (150, 50), (50, 150), (50, 50)], + [(50, 50), (100, 50), (50, 150), (50, 50)]): + for x, y in result: + for etype, event_args in polygon_place_vertex(x, y): + do_event(tool, etype, **event_args) + + artist = tool._selection_artist + + assert tool._selection_completed + assert tool.get_visible() + assert artist.get_visible() + np.testing.assert_equal(artist.get_xydata(), result) + assert onselect.call_args == ((result[:-1],), {}) + + tool.clear() + assert not tool._selection_completed + np.testing.assert_equal(artist.get_xydata(), [(0, 0)]) + + +@pytest.mark.parametrize("horizOn", [False, True]) +@pytest.mark.parametrize("vertOn", [False, True]) +def test_MultiCursor(horizOn, vertOn): + (ax1, ax3) = plt.figure().subplots(2, sharex=True) + ax2 = plt.figure().subplots() + + # useblit=false to avoid having to draw the figure to cache the renderer + multi = widgets.MultiCursor( + None, (ax1, ax2), useblit=False, horizOn=horizOn, vertOn=vertOn + ) + + # Only two of the axes should have a line drawn on them. + assert len(multi.vlines) == 2 + assert len(multi.hlines) == 2 + + # mock a motion_notify_event + # Can't use `do_event` as that helper requires the widget + # to have a single .ax attribute. + event = mock_event(ax1, xdata=.5, ydata=.25) + multi.onmove(event) + # force a draw + draw event to exercise clear + ax1.figure.canvas.draw() + + # the lines in the first two ax should both move + for l in multi.vlines: + assert l.get_xdata() == (.5, .5) + for l in multi.hlines: + assert l.get_ydata() == (.25, .25) + # The relevant lines get turned on after move. + assert len([line for line in multi.vlines if line.get_visible()]) == ( + 2 if vertOn else 0) + assert len([line for line in multi.hlines if line.get_visible()]) == ( + 2 if horizOn else 0) + + # After toggling settings, the opposite lines should be visible after move. + multi.horizOn = not multi.horizOn + multi.vertOn = not multi.vertOn + event = mock_event(ax1, xdata=.5, ydata=.25) + multi.onmove(event) + assert len([line for line in multi.vlines if line.get_visible()]) == ( + 0 if vertOn else 2) + assert len([line for line in multi.hlines if line.get_visible()]) == ( + 0 if horizOn else 2) + + # test a move event in an Axes not part of the MultiCursor + # the lines in ax1 and ax2 should not have moved. + event = mock_event(ax3, xdata=.75, ydata=.75) + multi.onmove(event) + for l in multi.vlines: + assert l.get_xdata() == (.5, .5) + for l in multi.hlines: + assert l.get_ydata() == (.25, .25) diff --git a/parrot/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip b/parrot/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip new file mode 100644 index 0000000000000000000000000000000000000000..400905eecf0385de4d3b8e50b9892e1302b2b894 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/pkg_resources/tests/data/my-test-package-zip/my-test-package.zip @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:01845c437f4655e3cf9cc4fc4e49cfd607431f22675e1b611129a90239f34822 +size 1809 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..cdbb66c17630f1929f9fb74976d942be2391da42 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_argkmin.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:f5cb8a238ff1a628d203a73c22bd86656a7c88e96641c684bb28e84f53f43bc6 +size 356425 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..4fde4d4ced6ccf9cb8751ff10142491502646b01 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_base.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:cb752aa50c596be8c5714e74408a28fdf8dec0e851787da0d5e8c4a8770d794a +size 328017 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..d58d0ddb4ebb71be68f1c17350c0cb2686107a48 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_middle_term_computer.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ea1b26a667d7f6fe12da2642f78577782778547a635bf2e5cecfc25bb5093001 +size 414937 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..417fec3b02ffcd733f1febad5261376d150fd202 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_distances_reduction/_radius_neighbors.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:54046c485bd6db36bdb266721e706edaee02f9a8b1faf3e120edd3e5204955dc +size 380369 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..f66eddc74feceff21f6042339584d6716c3d11fe --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_pairwise_fast.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ba34d0b520a7fb16d787f3d4e442da31e92c822920c2711bd0bd466d77e19696 +size 270097 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9efd69035445133e04c01e70b687be5f7b623b81 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/confusion_matrix.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/confusion_matrix.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0710f54de693d0137c8e0494c8dbe68912bc0a94 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/confusion_matrix.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/det_curve.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/det_curve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b5e1f5a17f32a221c3695ef1d7464b00d8fb3fee Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/det_curve.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/precision_recall_curve.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/precision_recall_curve.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a5b5f81191c7bcc11a4e27170eb22c59bce26d34 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/precision_recall_curve.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/regression.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/regression.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..bb8620991729d9c7f08551d5e847cce73b0de71c Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/__pycache__/regression.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/__init__.cpython-310.pyc b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5de3517e1ad0f8e40b4e40116db9721cecebb324 Binary files /dev/null and b/videollama2/lib/python3.10/site-packages/sklearn/metrics/_plot/tests/__pycache__/__init__.cpython-310.pyc differ diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__init__.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py new file mode 100644 index 0000000000000000000000000000000000000000..4fe8013cd3602d92661f684713d1db75e0fd2a45 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_pairwise_distances_reduction.py @@ -0,0 +1,1228 @@ +import itertools +import re +import warnings +from collections import defaultdict + +import numpy as np +import pytest +import threadpoolctl +from math import log10, floor +from scipy.sparse import csr_matrix +from scipy.spatial.distance import cdist + +from sklearn.metrics._pairwise_distances_reduction import ( + BaseDistancesReductionDispatcher, + ArgKmin, + RadiusNeighbors, + sqeuclidean_row_norms, +) + +from sklearn.metrics import euclidean_distances +from sklearn.utils.fixes import sp_version, parse_version +from sklearn.utils._testing import ( + assert_array_equal, + assert_allclose, + create_memmap_backed_data, +) + +# Common supported metric between scipy.spatial.distance.cdist +# and BaseDistanceReductionDispatcher. +# This allows constructing tests to check consistency of results +# of concrete BaseDistanceReductionDispatcher on some metrics using APIs +# from scipy and numpy. +CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS = [ + "braycurtis", + "canberra", + "chebyshev", + "cityblock", + "euclidean", + "minkowski", + "seuclidean", +] + + +def _get_metric_params_list(metric: str, n_features: int, seed: int = 1): + """Return list of dummy DistanceMetric kwargs for tests.""" + + # Distinguishing on cases not to compute unneeded datastructures. + rng = np.random.RandomState(seed) + + if metric == "minkowski": + minkowski_kwargs = [dict(p=1.5), dict(p=2), dict(p=3), dict(p=np.inf)] + if sp_version >= parse_version("1.8.0.dev0"): + # TODO: remove the test once we no longer support scipy < 1.8.0. + # Recent scipy versions accept weights in the Minkowski metric directly: + # type: ignore + minkowski_kwargs.append(dict(p=3, w=rng.rand(n_features))) + + return minkowski_kwargs + + # TODO: remove this case for "wminkowski" once we no longer support scipy < 1.8.0. + if metric == "wminkowski": + weights = rng.random_sample(n_features) + weights /= weights.sum() + wminkowski_kwargs = [dict(p=1.5, w=weights)] + if sp_version < parse_version("1.8.0.dev0"): + # wminkowski was removed in scipy 1.8.0 but should work for previous + # versions. + wminkowski_kwargs.append(dict(p=3, w=rng.rand(n_features))) + return wminkowski_kwargs + + if metric == "seuclidean": + return [dict(V=rng.rand(n_features))] + + # Case of: "euclidean", "manhattan", "chebyshev", "haversine" or any other metric. + # In those cases, no kwargs is needed. + return [{}] + + +def assert_argkmin_results_equality(ref_dist, dist, ref_indices, indices, rtol=1e-7): + assert_array_equal( + ref_indices, + indices, + err_msg="Query vectors have different neighbors' indices", + ) + assert_allclose( + ref_dist, + dist, + err_msg="Query vectors have different neighbors' distances", + rtol=rtol, + ) + + +def relative_rounding(scalar, n_significant_digits): + """Round a scalar to a number of significant digits relatively to its value.""" + if scalar == 0: + return 0.0 + magnitude = int(floor(log10(abs(scalar)))) + 1 + return round(scalar, n_significant_digits - magnitude) + + +def test_relative_rounding(): + + assert relative_rounding(0, 1) == 0.0 + assert relative_rounding(0, 10) == 0.0 + assert relative_rounding(0, 123456) == 0.0 + + assert relative_rounding(123456789, 0) == 0 + assert relative_rounding(123456789, 2) == 120000000 + assert relative_rounding(123456789, 3) == 123000000 + assert relative_rounding(123456789, 10) == 123456789 + assert relative_rounding(123456789, 20) == 123456789 + + assert relative_rounding(1.23456789, 2) == 1.2 + assert relative_rounding(1.23456789, 3) == 1.23 + assert relative_rounding(1.23456789, 10) == 1.23456789 + + assert relative_rounding(123.456789, 3) == 123.0 + assert relative_rounding(123.456789, 9) == 123.456789 + assert relative_rounding(123.456789, 10) == 123.456789 + + +def assert_argkmin_results_quasi_equality( + ref_dist, + dist, + ref_indices, + indices, + rtol=1e-4, +): + """Assert that argkmin results are valid up to: + - relative tolerance on computed distance values + - permutations of indices for distances values that differ up to + a precision level + + To be used for testing neighbors queries on float32 datasets: we + accept neighbors rank swaps only if they are caused by small + rounding errors on the distance computations. + """ + is_sorted = lambda a: np.all(a[:-1] <= a[1:]) + + n_significant_digits = -(int(floor(log10(abs(rtol)))) + 1) + + assert ( + ref_dist.shape == dist.shape == ref_indices.shape == indices.shape + ), "Arrays of results have various shapes." + + n_queries, n_neighbors = ref_dist.shape + + # Asserting equality results one row at a time + for query_idx in range(n_queries): + ref_dist_row = ref_dist[query_idx] + dist_row = dist[query_idx] + + assert is_sorted( + ref_dist_row + ), f"Reference distances aren't sorted on row {query_idx}" + assert is_sorted(dist_row), f"Distances aren't sorted on row {query_idx}" + + assert_allclose(ref_dist_row, dist_row, rtol=rtol) + + ref_indices_row = ref_indices[query_idx] + indices_row = indices[query_idx] + + # Grouping indices by distances using sets on a rounded distances up + # to a given number of decimals of significant digits derived from rtol. + reference_neighbors_groups = defaultdict(set) + effective_neighbors_groups = defaultdict(set) + + for neighbor_rank in range(n_neighbors): + rounded_dist = relative_rounding( + ref_dist_row[neighbor_rank], + n_significant_digits=n_significant_digits, + ) + reference_neighbors_groups[rounded_dist].add(ref_indices_row[neighbor_rank]) + effective_neighbors_groups[rounded_dist].add(indices_row[neighbor_rank]) + + # Asserting equality of groups (sets) for each distance + msg = ( + f"Neighbors indices for query {query_idx} are not matching " + f"when rounding distances at {n_significant_digits} significant digits " + f"derived from rtol={rtol:.1e}" + ) + for rounded_distance in reference_neighbors_groups.keys(): + assert ( + reference_neighbors_groups[rounded_distance] + == effective_neighbors_groups[rounded_distance] + ), msg + + +def assert_radius_neighbors_results_equality( + ref_dist, dist, ref_indices, indices, radius +): + # We get arrays of arrays and we need to check for individual pairs + for i in range(ref_dist.shape[0]): + assert (ref_dist[i] <= radius).all() + assert_array_equal( + ref_indices[i], + indices[i], + err_msg=f"Query vector #{i} has different neighbors' indices", + ) + assert_allclose( + ref_dist[i], + dist[i], + err_msg=f"Query vector #{i} has different neighbors' distances", + rtol=1e-7, + ) + + +def assert_radius_neighbors_results_quasi_equality( + ref_dist, + dist, + ref_indices, + indices, + radius, + rtol=1e-4, +): + """Assert that radius neighborhood results are valid up to: + - relative tolerance on computed distance values + - permutations of indices for distances values that differ up to + a precision level + - missing or extra last elements if their distance is + close to the radius + + To be used for testing neighbors queries on float32 datasets: we + accept neighbors rank swaps only if they are caused by small + rounding errors on the distance computations. + + Input arrays must be sorted w.r.t distances. + """ + is_sorted = lambda a: np.all(a[:-1] <= a[1:]) + + n_significant_digits = -(int(floor(log10(abs(rtol)))) + 1) + + assert ( + len(ref_dist) == len(dist) == len(ref_indices) == len(indices) + ), "Arrays of results have various lengths." + + n_queries = len(ref_dist) + + # Asserting equality of results one vector at a time + for query_idx in range(n_queries): + + ref_dist_row = ref_dist[query_idx] + dist_row = dist[query_idx] + + assert is_sorted( + ref_dist_row + ), f"Reference distances aren't sorted on row {query_idx}" + assert is_sorted(dist_row), f"Distances aren't sorted on row {query_idx}" + + # Vectors' lengths might be different due to small + # numerical differences of distance w.r.t the `radius` threshold. + largest_row = ref_dist_row if len(ref_dist_row) > len(dist_row) else dist_row + + # For the longest distances vector, we check that last extra elements + # that aren't present in the other vector are all in: [radius ± rtol] + min_length = min(len(ref_dist_row), len(dist_row)) + last_extra_elements = largest_row[min_length:] + if last_extra_elements.size > 0: + assert np.all(radius - rtol <= last_extra_elements <= radius + rtol), ( + f"The last extra elements ({last_extra_elements}) aren't in [radius ±" + f" rtol]=[{radius} ± {rtol}]" + ) + + # We truncate the neighbors results list on the smallest length to + # be able to compare them, ignoring the elements checked above. + ref_dist_row = ref_dist_row[:min_length] + dist_row = dist_row[:min_length] + + assert_allclose(ref_dist_row, dist_row, rtol=rtol) + + ref_indices_row = ref_indices[query_idx] + indices_row = indices[query_idx] + + # Grouping indices by distances using sets on a rounded distances up + # to a given number of significant digits derived from rtol. + reference_neighbors_groups = defaultdict(set) + effective_neighbors_groups = defaultdict(set) + + for neighbor_rank in range(min_length): + rounded_dist = relative_rounding( + ref_dist_row[neighbor_rank], + n_significant_digits=n_significant_digits, + ) + reference_neighbors_groups[rounded_dist].add(ref_indices_row[neighbor_rank]) + effective_neighbors_groups[rounded_dist].add(indices_row[neighbor_rank]) + + # Asserting equality of groups (sets) for each distance + msg = ( + f"Neighbors indices for query {query_idx} are not matching " + f"when rounding distances at {n_significant_digits} significant digits " + f"derived from rtol={rtol:.1e}" + ) + for rounded_distance in reference_neighbors_groups.keys(): + assert ( + reference_neighbors_groups[rounded_distance] + == effective_neighbors_groups[rounded_distance] + ), msg + + +ASSERT_RESULT = { + # In the case of 64bit, we test for exact equality of the results rankings + # and standard tolerance levels for the computed distance values. + # + # XXX: Note that in the future we might be interested in using quasi equality + # checks also for float64 data (with a larger number of significant digits) + # as the tests could be unstable because of numerically tied distances on + # some datasets (e.g. uniform grids). + (ArgKmin, np.float64): assert_argkmin_results_equality, + ( + RadiusNeighbors, + np.float64, + ): assert_radius_neighbors_results_equality, + # In the case of 32bit, indices can be permuted due to small difference + # in the computations of their associated distances, hence we test equality of + # results up to valid permutations. + (ArgKmin, np.float32): assert_argkmin_results_quasi_equality, + ( + RadiusNeighbors, + np.float32, + ): assert_radius_neighbors_results_quasi_equality, +} + + +def test_assert_argkmin_results_quasi_equality(): + + rtol = 1e-7 + eps = 1e-7 + _1m = 1.0 - eps + _1p = 1.0 + eps + + _6_1m = 6.1 - eps + _6_1p = 6.1 + eps + + ref_dist = np.array( + [ + [1.2, 2.5, _6_1m, 6.1, _6_1p], + [_1m, _1m, 1, _1p, _1p], + ] + ) + ref_indices = np.array( + [ + [1, 2, 3, 4, 5], + [6, 7, 8, 9, 10], + ] + ) + + # Sanity check: compare the reference results to themselves. + assert_argkmin_results_quasi_equality( + ref_dist, ref_dist, ref_indices, ref_indices, rtol + ) + + # Apply valid permutation on indices: the last 3 points are + # all very close to one another so we accept any permutation + # on their rankings. + assert_argkmin_results_quasi_equality( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1.2, 2.5, 6.1, 6.1, 6.1]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[1, 2, 4, 5, 3]]), + rtol=rtol, + ) + # All points are have close distances so any ranking permutation + # is valid for this query result. + assert_argkmin_results_quasi_equality( + np.array([[_1m, _1m, 1, _1p, _1p]]), + np.array([[_1m, _1m, 1, _1p, _1p]]), + np.array([[6, 7, 8, 9, 10]]), + np.array([[6, 9, 7, 8, 10]]), + rtol=rtol, + ) + + # Apply invalid permutation on indices: permuting the ranks + # of the 2 nearest neighbors is invalid because the distance + # values are too different. + msg = "Neighbors indices for query 0 are not matching" + with pytest.raises(AssertionError, match=msg): + assert_argkmin_results_quasi_equality( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[2, 1, 3, 4, 5]]), + rtol=rtol, + ) + + # Indices aren't properly sorted w.r.t their distances + msg = "Neighbors indices for query 0 are not matching" + with pytest.raises(AssertionError, match=msg): + assert_argkmin_results_quasi_equality( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[2, 1, 4, 5, 3]]), + rtol=rtol, + ) + + # Distances aren't properly sorted + msg = "Distances aren't sorted on row 0" + with pytest.raises(AssertionError, match=msg): + assert_argkmin_results_quasi_equality( + np.array([[1.2, 2.5, _6_1m, 6.1, _6_1p]]), + np.array([[2.5, 1.2, _6_1m, 6.1, _6_1p]]), + np.array([[1, 2, 3, 4, 5]]), + np.array([[2, 1, 4, 5, 3]]), + rtol=rtol, + ) + + +def test_assert_radius_neighbors_results_quasi_equality(): + + rtol = 1e-7 + eps = 1e-7 + _1m = 1.0 - eps + _1p = 1.0 + eps + + _6_1m = 6.1 - eps + _6_1p = 6.1 + eps + + ref_dist = [ + np.array([1.2, 2.5, _6_1m, 6.1, _6_1p]), + np.array([_1m, 1, _1p, _1p]), + ] + + ref_indices = [ + np.array([1, 2, 3, 4, 5]), + np.array([6, 7, 8, 9]), + ] + + # Sanity check: compare the reference results to themselves. + assert_radius_neighbors_results_quasi_equality( + ref_dist, + ref_dist, + ref_indices, + ref_indices, + radius=6.1, + rtol=rtol, + ) + + # Apply valid permutation on indices + assert_radius_neighbors_results_quasi_equality( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([1, 2, 4, 5, 3])]), + radius=6.1, + rtol=rtol, + ) + assert_radius_neighbors_results_quasi_equality( + np.array([np.array([_1m, _1m, 1, _1p, _1p])]), + np.array([np.array([_1m, _1m, 1, _1p, _1p])]), + np.array([np.array([6, 7, 8, 9, 10])]), + np.array([np.array([6, 9, 7, 8, 10])]), + radius=6.1, + rtol=rtol, + ) + + # Apply invalid permutation on indices + msg = "Neighbors indices for query 0 are not matching" + with pytest.raises(AssertionError, match=msg): + assert_radius_neighbors_results_quasi_equality( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 3, 4, 5])]), + radius=6.1, + rtol=rtol, + ) + + # Having extra last elements is valid if they are in: [radius ± rtol] + assert_radius_neighbors_results_quasi_equality( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([1, 2, 3, 4])]), + radius=6.1, + rtol=rtol, + ) + + # Having extra last elements is invalid if they are lesser than radius - rtol + msg = re.escape( + "The last extra elements ([6.]) aren't in [radius ± rtol]=[6.1 ± 1e-07]" + ) + with pytest.raises(AssertionError, match=msg): + assert_radius_neighbors_results_quasi_equality( + np.array([np.array([1.2, 2.5, 6])]), + np.array([np.array([1.2, 2.5])]), + np.array([np.array([1, 2, 3])]), + np.array([np.array([1, 2])]), + radius=6.1, + rtol=rtol, + ) + + # Indices aren't properly sorted w.r.t their distances + msg = "Neighbors indices for query 0 are not matching" + with pytest.raises(AssertionError, match=msg): + assert_radius_neighbors_results_quasi_equality( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 4, 5, 3])]), + radius=6.1, + rtol=rtol, + ) + + # Distances aren't properly sorted + msg = "Distances aren't sorted on row 0" + with pytest.raises(AssertionError, match=msg): + assert_radius_neighbors_results_quasi_equality( + np.array([np.array([1.2, 2.5, _6_1m, 6.1, _6_1p])]), + np.array([np.array([2.5, 1.2, _6_1m, 6.1, _6_1p])]), + np.array([np.array([1, 2, 3, 4, 5])]), + np.array([np.array([2, 1, 4, 5, 3])]), + radius=6.1, + rtol=rtol, + ) + + +def test_pairwise_distances_reduction_is_usable_for(): + rng = np.random.RandomState(0) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + X_csr = csr_matrix(X) + Y_csr = csr_matrix(Y) + metric = "manhattan" + + # Must be usable for all possible pair of {dense, sparse} datasets + assert BaseDistancesReductionDispatcher.is_usable_for(X, Y, metric) + assert BaseDistancesReductionDispatcher.is_usable_for(X_csr, Y_csr, metric) + assert BaseDistancesReductionDispatcher.is_usable_for(X_csr, Y, metric) + assert BaseDistancesReductionDispatcher.is_usable_for(X, Y_csr, metric) + + assert BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.float64), Y.astype(np.float64), metric + ) + + assert BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.float32), Y.astype(np.float32), metric + ) + + assert not BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.int64), Y.astype(np.int64), metric + ) + + assert not BaseDistancesReductionDispatcher.is_usable_for(X, Y, metric="pyfunc") + assert not BaseDistancesReductionDispatcher.is_usable_for( + X.astype(np.float32), Y, metric + ) + assert not BaseDistancesReductionDispatcher.is_usable_for( + X, Y.astype(np.int32), metric + ) + + # F-ordered arrays are not supported + assert not BaseDistancesReductionDispatcher.is_usable_for( + np.asfortranarray(X), Y, metric + ) + + # We prefer not to use those implementations for fused sparse-dense when + # metric="(sq)euclidean" because it's not yet the most efficient one on + # all configurations of datasets. + # See: https://github.com/scikit-learn/scikit-learn/pull/23585#issuecomment-1247996669 # noqa + # TODO: implement specialisation for (sq)euclidean on fused sparse-dense + # using sparse-dense routines for matrix-vector multiplications. + assert not BaseDistancesReductionDispatcher.is_usable_for( + X_csr, Y, metric="euclidean" + ) + assert BaseDistancesReductionDispatcher.is_usable_for( + X_csr, Y_csr, metric="sqeuclidean" + ) + assert BaseDistancesReductionDispatcher.is_usable_for( + X_csr, Y_csr, metric="euclidean" + ) + + # CSR matrices without non-zeros elements aren't currently supported + # TODO: support CSR matrices without non-zeros elements + X_csr_0_nnz = csr_matrix(X * 0) + assert not BaseDistancesReductionDispatcher.is_usable_for(X_csr_0_nnz, Y, metric) + + # CSR matrices with int64 indices and indptr (e.g. large nnz, or large n_features) + # aren't supported as of now. + # See: https://github.com/scikit-learn/scikit-learn/issues/23653 + # TODO: support CSR matrices with int64 indices and indptr + X_csr_int64 = csr_matrix(X) + X_csr_int64.indices = X_csr_int64.indices.astype(np.int64) + assert not BaseDistancesReductionDispatcher.is_usable_for(X_csr_int64, Y, metric) + + +def test_argkmin_factory_method_wrong_usages(): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + k = 5 + metric = "euclidean" + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float32 and Y.dtype=float64" + ) + with pytest.raises(ValueError, match=msg): + ArgKmin.compute(X=X.astype(np.float32), Y=Y, k=k, metric=metric) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float64 and Y.dtype=int32" + ) + with pytest.raises(ValueError, match=msg): + ArgKmin.compute(X=X, Y=Y.astype(np.int32), k=k, metric=metric) + + with pytest.raises(ValueError, match="k == -1, must be >= 1."): + ArgKmin.compute(X=X, Y=Y, k=-1, metric=metric) + + with pytest.raises(ValueError, match="k == 0, must be >= 1."): + ArgKmin.compute(X=X, Y=Y, k=0, metric=metric) + + with pytest.raises(ValueError, match="Unrecognized metric"): + ArgKmin.compute(X=X, Y=Y, k=k, metric="wrong metric") + + with pytest.raises( + ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)" + ): + ArgKmin.compute(X=np.array([1.0, 2.0]), Y=Y, k=k, metric=metric) + + with pytest.raises(ValueError, match="ndarray is not C-contiguous"): + ArgKmin.compute(X=np.asfortranarray(X), Y=Y, k=k, metric=metric) + + # A UserWarning must be raised in this case. + unused_metric_kwargs = {"p": 3} + + message = r"Some metric_kwargs have been passed \({'p': 3}\) but" + + with pytest.warns(UserWarning, match=message): + ArgKmin.compute( + X=X, Y=Y, k=k, metric=metric, metric_kwargs=unused_metric_kwargs + ) + + # A UserWarning must be raised in this case. + metric_kwargs = { + "p": 3, # unused + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + + message = r"Some metric_kwargs have been passed \({'p': 3, 'Y_norm_squared'" + + with pytest.warns(UserWarning, match=message): + ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + ArgKmin.compute(X=X, Y=Y, k=k, metric=metric, metric_kwargs=metric_kwargs) + + +def test_radius_neighbors_factory_method_wrong_usages(): + rng = np.random.RandomState(1) + X = rng.rand(100, 10) + Y = rng.rand(100, 10) + radius = 5 + metric = "euclidean" + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float32 and Y.dtype=float64" + ) + with pytest.raises( + ValueError, + match=msg, + ): + RadiusNeighbors.compute( + X=X.astype(np.float32), Y=Y, radius=radius, metric=metric + ) + + msg = ( + "Only float64 or float32 datasets pairs are supported at this time, " + "got: X.dtype=float64 and Y.dtype=int32" + ) + with pytest.raises( + ValueError, + match=msg, + ): + RadiusNeighbors.compute(X=X, Y=Y.astype(np.int32), radius=radius, metric=metric) + + with pytest.raises(ValueError, match="radius == -1.0, must be >= 0."): + RadiusNeighbors.compute(X=X, Y=Y, radius=-1, metric=metric) + + with pytest.raises(ValueError, match="Unrecognized metric"): + RadiusNeighbors.compute(X=X, Y=Y, radius=radius, metric="wrong metric") + + with pytest.raises( + ValueError, match=r"Buffer has wrong number of dimensions \(expected 2, got 1\)" + ): + RadiusNeighbors.compute( + X=np.array([1.0, 2.0]), Y=Y, radius=radius, metric=metric + ) + + with pytest.raises(ValueError, match="ndarray is not C-contiguous"): + RadiusNeighbors.compute( + X=np.asfortranarray(X), Y=Y, radius=radius, metric=metric + ) + + unused_metric_kwargs = {"p": 3} + + # A UserWarning must be raised in this case. + message = r"Some metric_kwargs have been passed \({'p': 3}\) but" + + with pytest.warns(UserWarning, match=message): + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=unused_metric_kwargs + ) + + # A UserWarning must be raised in this case. + metric_kwargs = { + "p": 3, # unused + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + + message = r"Some metric_kwargs have been passed \({'p': 3, 'Y_norm_squared'" + + with pytest.warns(UserWarning, match=message): + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs + ) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + "Y_norm_squared": sqeuclidean_row_norms(Y, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs + ) + + # No user warning must be raised in this case. + metric_kwargs = { + "X_norm_squared": sqeuclidean_row_norms(X, num_threads=2), + } + with warnings.catch_warnings(): + warnings.simplefilter("error", category=UserWarning) + RadiusNeighbors.compute( + X=X, Y=Y, radius=radius, metric=metric, metric_kwargs=metric_kwargs + ) + + +@pytest.mark.parametrize( + "n_samples_X, n_samples_Y", [(100, 100), (500, 100), (100, 500)] +) +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_chunk_size_agnosticism( + global_random_seed, + Dispatcher, + n_samples_X, + n_samples_Y, + dtype, + n_features=100, +): + """Check that results do not depend on the chunk size.""" + rng = np.random.RandomState(global_random_seed) + spread = 100 + X = rng.rand(n_samples_X, n_features).astype(dtype) * spread + Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + # Scaling the radius slightly with the numbers of dimensions + radius = 10 ** np.log(n_features) + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + ref_dist, ref_indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=256, # default + metric="manhattan", + return_distance=True, + **compute_parameters, + ) + + dist, indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=41, + metric="manhattan", + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, dtype)]( + ref_dist, dist, ref_indices, indices, **check_parameters + ) + + +@pytest.mark.parametrize( + "n_samples_X, n_samples_Y", [(100, 100), (500, 100), (100, 500)] +) +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_n_threads_agnosticism( + global_random_seed, + Dispatcher, + n_samples_X, + n_samples_Y, + dtype, + n_features=100, +): + """Check that results do not depend on the number of threads.""" + rng = np.random.RandomState(global_random_seed) + spread = 100 + X = rng.rand(n_samples_X, n_features).astype(dtype) * spread + Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + # Scaling the radius slightly with the numbers of dimensions + radius = 10 ** np.log(n_features) + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + ref_dist, ref_indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=25, # make sure we use multiple threads + return_distance=True, + **compute_parameters, + ) + + with threadpoolctl.threadpool_limits(limits=1, user_api="openmp"): + dist, indices = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=25, + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, dtype)]( + ref_dist, dist, ref_indices, indices, **check_parameters + ) + + +@pytest.mark.parametrize( + "Dispatcher, dtype", + [ + (ArgKmin, np.float64), + (RadiusNeighbors, np.float32), + (ArgKmin, np.float32), + (RadiusNeighbors, np.float64), + ], +) +def test_format_agnosticism( + global_random_seed, + Dispatcher, + dtype, +): + """Check that results do not depend on the format (dense, sparse) of the input.""" + rng = np.random.RandomState(global_random_seed) + spread = 100 + n_samples, n_features = 100, 100 + + X = rng.rand(n_samples, n_features).astype(dtype) * spread + Y = rng.rand(n_samples, n_features).astype(dtype) * spread + + X_csr = csr_matrix(X) + Y_csr = csr_matrix(Y) + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + # Scaling the radius slightly with the numbers of dimensions + radius = 10 ** np.log(n_features) + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + dist_dense, indices_dense = Dispatcher.compute( + X, + Y, + parameter, + chunk_size=50, + return_distance=True, + **compute_parameters, + ) + + for _X, _Y in itertools.product((X, X_csr), (Y, Y_csr)): + if _X is X and _Y is Y: + continue + dist, indices = Dispatcher.compute( + _X, + _Y, + parameter, + chunk_size=50, + return_distance=True, + **compute_parameters, + ) + ASSERT_RESULT[(Dispatcher, dtype)]( + dist_dense, + dist, + indices_dense, + indices, + **check_parameters, + ) + + +@pytest.mark.parametrize( + "n_samples_X, n_samples_Y", [(100, 100), (100, 500), (500, 100)] +) +@pytest.mark.parametrize( + "metric", + ["euclidean", "minkowski", "manhattan", "infinity", "seuclidean", "haversine"], +) +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_strategies_consistency( + global_random_seed, + Dispatcher, + metric, + n_samples_X, + n_samples_Y, + dtype, + n_features=10, +): + """Check that the results do not depend on the strategy used.""" + rng = np.random.RandomState(global_random_seed) + spread = 100 + X = rng.rand(n_samples_X, n_features).astype(dtype) * spread + Y = rng.rand(n_samples_Y, n_features).astype(dtype) * spread + + # Haversine distance only accepts 2D data + if metric == "haversine": + X = np.ascontiguousarray(X[:, :2]) + Y = np.ascontiguousarray(Y[:, :2]) + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + # Scaling the radius slightly with the numbers of dimensions + radius = 10 ** np.log(n_features) + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + dist_par_X, indices_par_X = Dispatcher.compute( + X, + Y, + parameter, + metric=metric, + # Taking the first + metric_kwargs=_get_metric_params_list( + metric, n_features, seed=global_random_seed + )[0], + # To be sure to use parallelization + chunk_size=n_samples_X // 4, + strategy="parallel_on_X", + return_distance=True, + **compute_parameters, + ) + + dist_par_Y, indices_par_Y = Dispatcher.compute( + X, + Y, + parameter, + metric=metric, + # Taking the first + metric_kwargs=_get_metric_params_list( + metric, n_features, seed=global_random_seed + )[0], + # To be sure to use parallelization + chunk_size=n_samples_Y // 4, + strategy="parallel_on_Y", + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, dtype)]( + dist_par_X, dist_par_Y, indices_par_X, indices_par_Y, **check_parameters + ) + + +# "Concrete Dispatchers"-specific tests + +# TODO: Remove filterwarnings in 1.3 when wminkowski is removed +@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn") +@pytest.mark.parametrize("n_features", [50, 500]) +@pytest.mark.parametrize("translation", [0, 1e6]) +@pytest.mark.parametrize("metric", CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS) +@pytest.mark.parametrize("strategy", ("parallel_on_X", "parallel_on_Y")) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_pairwise_distances_argkmin( + global_random_seed, + n_features, + translation, + metric, + strategy, + dtype, + n_samples=100, + k=10, +): + # TODO: can we easily fix this discrepancy? + edge_cases = [ + (np.float32, "chebyshev", 1000000.0), + (np.float32, "cityblock", 1000000.0), + ] + if (dtype, metric, translation) in edge_cases: + pytest.xfail("Numerical differences lead to small differences in results.") + + rng = np.random.RandomState(global_random_seed) + spread = 1000 + X = translation + rng.rand(n_samples, n_features).astype(dtype) * spread + Y = translation + rng.rand(n_samples, n_features).astype(dtype) * spread + + X_csr = csr_matrix(X) + Y_csr = csr_matrix(Y) + + # Haversine distance only accepts 2D data + if metric == "haversine": + X = np.ascontiguousarray(X[:, :2]) + Y = np.ascontiguousarray(Y[:, :2]) + + metric_kwargs = _get_metric_params_list(metric, n_features)[0] + + # Reference for argkmin results + if metric == "euclidean": + # Compare to scikit-learn GEMM optimized implementation + dist_matrix = euclidean_distances(X, Y) + else: + dist_matrix = cdist(X, Y, metric=metric, **metric_kwargs) + # Taking argkmin (indices of the k smallest values) + argkmin_indices_ref = np.argsort(dist_matrix, axis=1)[:, :k] + # Getting the associated distances + argkmin_distances_ref = np.zeros(argkmin_indices_ref.shape, dtype=np.float64) + for row_idx in range(argkmin_indices_ref.shape[0]): + argkmin_distances_ref[row_idx] = dist_matrix[ + row_idx, argkmin_indices_ref[row_idx] + ] + + for _X, _Y in [(X, Y), (X_csr, Y_csr)]: + argkmin_distances, argkmin_indices = ArgKmin.compute( + _X, + _Y, + k, + metric=metric, + metric_kwargs=metric_kwargs, + return_distance=True, + # So as to have more than a chunk, forcing parallelism. + chunk_size=n_samples // 4, + strategy=strategy, + ) + + ASSERT_RESULT[(ArgKmin, dtype)]( + argkmin_distances, + argkmin_distances_ref, + argkmin_indices, + argkmin_indices_ref, + ) + + +# TODO: Remove filterwarnings in 1.3 when wminkowski is removed +@pytest.mark.filterwarnings("ignore:WMinkowskiDistance:FutureWarning:sklearn") +@pytest.mark.parametrize("n_features", [50, 500]) +@pytest.mark.parametrize("translation", [0, 1e6]) +@pytest.mark.parametrize("metric", CDIST_PAIRWISE_DISTANCES_REDUCTION_COMMON_METRICS) +@pytest.mark.parametrize("strategy", ("parallel_on_X", "parallel_on_Y")) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_pairwise_distances_radius_neighbors( + global_random_seed, + n_features, + translation, + metric, + strategy, + dtype, + n_samples=100, +): + rng = np.random.RandomState(global_random_seed) + spread = 1000 + radius = spread * np.log(n_features) + X = translation + rng.rand(n_samples, n_features).astype(dtype) * spread + Y = translation + rng.rand(n_samples, n_features).astype(dtype) * spread + + metric_kwargs = _get_metric_params_list( + metric, n_features, seed=global_random_seed + )[0] + + # Reference for argkmin results + if metric == "euclidean": + # Compare to scikit-learn GEMM optimized implementation + dist_matrix = euclidean_distances(X, Y) + else: + dist_matrix = cdist(X, Y, metric=metric, **metric_kwargs) + + # Getting the neighbors for a given radius + neigh_indices_ref = [] + neigh_distances_ref = [] + + for row in dist_matrix: + ind = np.arange(row.shape[0])[row <= radius] + dist = row[ind] + + sort = np.argsort(dist) + ind, dist = ind[sort], dist[sort] + + neigh_indices_ref.append(ind) + neigh_distances_ref.append(dist) + + neigh_distances, neigh_indices = RadiusNeighbors.compute( + X, + Y, + radius, + metric=metric, + metric_kwargs=metric_kwargs, + return_distance=True, + # So as to have more than a chunk, forcing parallelism. + chunk_size=n_samples // 4, + strategy=strategy, + sort_results=True, + ) + + ASSERT_RESULT[(RadiusNeighbors, dtype)]( + neigh_distances, neigh_distances_ref, neigh_indices, neigh_indices_ref, radius + ) + + +@pytest.mark.parametrize("Dispatcher", [ArgKmin, RadiusNeighbors]) +@pytest.mark.parametrize("metric", ["manhattan", "euclidean"]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_memmap_backed_data( + metric, + Dispatcher, + dtype, +): + """Check that the results do not depend on the datasets writability.""" + rng = np.random.RandomState(0) + spread = 100 + n_samples, n_features = 128, 10 + X = rng.rand(n_samples, n_features).astype(dtype) * spread + Y = rng.rand(n_samples, n_features).astype(dtype) * spread + + # Create read only datasets + X_mm, Y_mm = create_memmap_backed_data([X, Y]) + + if Dispatcher is ArgKmin: + parameter = 10 + check_parameters = {} + compute_parameters = {} + else: + # Scaling the radius slightly with the numbers of dimensions + radius = 10 ** np.log(n_features) + parameter = radius + check_parameters = {"radius": radius} + compute_parameters = {"sort_results": True} + + ref_dist, ref_indices = Dispatcher.compute( + X, + Y, + parameter, + metric=metric, + return_distance=True, + **compute_parameters, + ) + + dist_mm, indices_mm = Dispatcher.compute( + X_mm, + Y_mm, + parameter, + metric=metric, + return_distance=True, + **compute_parameters, + ) + + ASSERT_RESULT[(Dispatcher, dtype)]( + ref_dist, dist_mm, ref_indices, indices_mm, **check_parameters + ) + + +@pytest.mark.parametrize("n_samples", [100, 1000]) +@pytest.mark.parametrize("n_features", [5, 10, 100]) +@pytest.mark.parametrize("num_threads", [1, 2, 8]) +@pytest.mark.parametrize("dtype", [np.float64, np.float32]) +def test_sqeuclidean_row_norms( + global_random_seed, + n_samples, + n_features, + num_threads, + dtype, +): + rng = np.random.RandomState(global_random_seed) + spread = 100 + X = rng.rand(n_samples, n_features).astype(dtype) * spread + + X_csr = csr_matrix(X) + + sq_row_norm_reference = np.linalg.norm(X, axis=1) ** 2 + sq_row_norm = sqeuclidean_row_norms(X, num_threads=num_threads) + + sq_row_norm_csr = sqeuclidean_row_norms(X_csr, num_threads=num_threads) + + assert_allclose(sq_row_norm_reference, sq_row_norm) + assert_allclose(sq_row_norm_reference, sq_row_norm_csr) + + with pytest.raises(ValueError): + X = np.asfortranarray(X) + sqeuclidean_row_norms(X, num_threads=num_threads) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py new file mode 100644 index 0000000000000000000000000000000000000000..b51012d6c1f1b5a8ff849f90b8bb51b8f317a2dc --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/metrics/tests/test_regression.py @@ -0,0 +1,627 @@ +import numpy as np +from scipy import optimize +from numpy.testing import assert_allclose +from scipy.special import factorial, xlogy +from itertools import product +import pytest + +from sklearn.utils._testing import assert_almost_equal +from sklearn.utils._testing import assert_array_equal +from sklearn.utils._testing import assert_array_almost_equal +from sklearn.dummy import DummyRegressor +from sklearn.model_selection import GridSearchCV + +from sklearn.metrics import explained_variance_score +from sklearn.metrics import mean_absolute_error +from sklearn.metrics import mean_squared_error +from sklearn.metrics import mean_squared_log_error +from sklearn.metrics import median_absolute_error +from sklearn.metrics import mean_absolute_percentage_error +from sklearn.metrics import max_error +from sklearn.metrics import mean_pinball_loss +from sklearn.metrics import r2_score +from sklearn.metrics import mean_tweedie_deviance +from sklearn.metrics import d2_tweedie_score +from sklearn.metrics import d2_pinball_score +from sklearn.metrics import d2_absolute_error_score +from sklearn.metrics import make_scorer + +from sklearn.metrics._regression import _check_reg_targets + +from sklearn.exceptions import UndefinedMetricWarning + + +def test_regression_metrics(n_samples=50): + y_true = np.arange(n_samples) + y_pred = y_true + 1 + y_pred_2 = y_true - 1 + + assert_almost_equal(mean_squared_error(y_true, y_pred), 1.0) + assert_almost_equal( + mean_squared_log_error(y_true, y_pred), + mean_squared_error(np.log(1 + y_true), np.log(1 + y_pred)), + ) + assert_almost_equal(mean_absolute_error(y_true, y_pred), 1.0) + assert_almost_equal(mean_pinball_loss(y_true, y_pred), 0.5) + assert_almost_equal(mean_pinball_loss(y_true, y_pred_2), 0.5) + assert_almost_equal(mean_pinball_loss(y_true, y_pred, alpha=0.4), 0.6) + assert_almost_equal(mean_pinball_loss(y_true, y_pred_2, alpha=0.4), 0.4) + assert_almost_equal(median_absolute_error(y_true, y_pred), 1.0) + mape = mean_absolute_percentage_error(y_true, y_pred) + assert np.isfinite(mape) + assert mape > 1e6 + assert_almost_equal(max_error(y_true, y_pred), 1.0) + assert_almost_equal(r2_score(y_true, y_pred), 0.995, 2) + assert_almost_equal(r2_score(y_true, y_pred, force_finite=False), 0.995, 2) + assert_almost_equal(explained_variance_score(y_true, y_pred), 1.0) + assert_almost_equal( + explained_variance_score(y_true, y_pred, force_finite=False), 1.0 + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=0), + mean_squared_error(y_true, y_pred), + ) + assert_almost_equal( + d2_tweedie_score(y_true, y_pred, power=0), r2_score(y_true, y_pred) + ) + dev_median = np.abs(y_true - np.median(y_true)).sum() + assert_array_almost_equal( + d2_absolute_error_score(y_true, y_pred), + 1 - np.abs(y_true - y_pred).sum() / dev_median, + ) + alpha = 0.2 + pinball_loss = lambda y_true, y_pred, alpha: alpha * np.maximum( + y_true - y_pred, 0 + ) + (1 - alpha) * np.maximum(y_pred - y_true, 0) + y_quantile = np.percentile(y_true, q=alpha * 100) + assert_almost_equal( + d2_pinball_score(y_true, y_pred, alpha=alpha), + 1 + - pinball_loss(y_true, y_pred, alpha).sum() + / pinball_loss(y_true, y_quantile, alpha).sum(), + ) + assert_almost_equal( + d2_absolute_error_score(y_true, y_pred), + d2_pinball_score(y_true, y_pred, alpha=0.5), + ) + + # Tweedie deviance needs positive y_pred, except for p=0, + # p>=2 needs positive y_true + # results evaluated by sympy + y_true = np.arange(1, 1 + n_samples) + y_pred = 2 * y_true + n = n_samples + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=-1), + 5 / 12 * n * (n**2 + 2 * n + 1), + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=1), (n + 1) * (1 - np.log(2)) + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=2), 2 * np.log(2) - 1 + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=3 / 2), + ((6 * np.sqrt(2) - 8) / n) * np.sqrt(y_true).sum(), + ) + assert_almost_equal( + mean_tweedie_deviance(y_true, y_pred, power=3), np.sum(1 / y_true) / (4 * n) + ) + + dev_mean = 2 * np.mean(xlogy(y_true, 2 * y_true / (n + 1))) + assert_almost_equal( + d2_tweedie_score(y_true, y_pred, power=1), + 1 - (n + 1) * (1 - np.log(2)) / dev_mean, + ) + + dev_mean = 2 * np.log((n + 1) / 2) - 2 / n * np.log(factorial(n)) + assert_almost_equal( + d2_tweedie_score(y_true, y_pred, power=2), 1 - (2 * np.log(2) - 1) / dev_mean + ) + + +def test_mean_squared_error_multioutput_raw_value_squared(): + # non-regression test for + # https://github.com/scikit-learn/scikit-learn/pull/16323 + mse1 = mean_squared_error([[1]], [[10]], multioutput="raw_values", squared=True) + mse2 = mean_squared_error([[1]], [[10]], multioutput="raw_values", squared=False) + assert np.sqrt(mse1) == pytest.approx(mse2) + + +def test_multioutput_regression(): + y_true = np.array([[1, 0, 0, 1], [0, 1, 1, 1], [1, 1, 0, 1]]) + y_pred = np.array([[0, 0, 0, 1], [1, 0, 1, 1], [0, 0, 0, 1]]) + + error = mean_squared_error(y_true, y_pred) + assert_almost_equal(error, (1.0 / 3 + 2.0 / 3 + 2.0 / 3) / 4.0) + + error = mean_squared_error(y_true, y_pred, squared=False) + assert_almost_equal(error, 0.454, decimal=2) + + error = mean_squared_log_error(y_true, y_pred) + assert_almost_equal(error, 0.200, decimal=2) + + # mean_absolute_error and mean_squared_error are equal because + # it is a binary problem. + error = mean_absolute_error(y_true, y_pred) + assert_almost_equal(error, (1.0 + 2.0 / 3) / 4.0) + + error = mean_pinball_loss(y_true, y_pred) + assert_almost_equal(error, (1.0 + 2.0 / 3) / 8.0) + + error = np.around(mean_absolute_percentage_error(y_true, y_pred), decimals=2) + assert np.isfinite(error) + assert error > 1e6 + error = median_absolute_error(y_true, y_pred) + assert_almost_equal(error, (1.0 + 1.0) / 4.0) + + error = r2_score(y_true, y_pred, multioutput="variance_weighted") + assert_almost_equal(error, 1.0 - 5.0 / 2) + error = r2_score(y_true, y_pred, multioutput="uniform_average") + assert_almost_equal(error, -0.875) + + score = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values") + raw_expected_score = [ + 1 + - np.abs(y_true[:, i] - y_pred[:, i]).sum() + / np.abs(y_true[:, i] - np.median(y_true[:, i])).sum() + for i in range(y_true.shape[1]) + ] + # in the last case, the denominator vanishes and hence we get nan, + # but since the numerator vanishes as well the expected score is 1.0 + raw_expected_score = np.where(np.isnan(raw_expected_score), 1, raw_expected_score) + assert_array_almost_equal(score, raw_expected_score) + + score = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="uniform_average") + assert_almost_equal(score, raw_expected_score.mean()) + # constant `y_true` with force_finite=True leads to 1. or 0. + yc = [5.0, 5.0] + error = r2_score(yc, [5.0, 5.0], multioutput="variance_weighted") + assert_almost_equal(error, 1.0) + error = r2_score(yc, [5.0, 5.1], multioutput="variance_weighted") + assert_almost_equal(error, 0.0) + + # Setting force_finite=False results in the nan for 4th output propagating + error = r2_score( + y_true, y_pred, multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, np.nan) + error = r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False) + assert_almost_equal(error, np.nan) + + # Dropping the 4th output to check `force_finite=False` for nominal + y_true = y_true[:, :-1] + y_pred = y_pred[:, :-1] + error = r2_score(y_true, y_pred, multioutput="variance_weighted") + error2 = r2_score( + y_true, y_pred, multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, error2) + error = r2_score(y_true, y_pred, multioutput="uniform_average") + error2 = r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False) + assert_almost_equal(error, error2) + + # constant `y_true` with force_finite=False leads to NaN or -Inf. + error = r2_score( + yc, [5.0, 5.0], multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, np.nan) + error = r2_score( + yc, [5.0, 6.0], multioutput="variance_weighted", force_finite=False + ) + assert_almost_equal(error, -np.inf) + + +def test_regression_metrics_at_limits(): + # Single-sample case + # Note: for r2 and d2_tweedie see also test_regression_single_sample + assert_almost_equal(mean_squared_error([0.0], [0.0]), 0.0) + assert_almost_equal(mean_squared_error([0.0], [0.0], squared=False), 0.0) + assert_almost_equal(mean_squared_log_error([0.0], [0.0]), 0.0) + assert_almost_equal(mean_absolute_error([0.0], [0.0]), 0.0) + assert_almost_equal(mean_pinball_loss([0.0], [0.0]), 0.0) + assert_almost_equal(mean_absolute_percentage_error([0.0], [0.0]), 0.0) + assert_almost_equal(median_absolute_error([0.0], [0.0]), 0.0) + assert_almost_equal(max_error([0.0], [0.0]), 0.0) + assert_almost_equal(explained_variance_score([0.0], [0.0]), 1.0) + + # Perfect cases + assert_almost_equal(r2_score([0.0, 1], [0.0, 1]), 1.0) + assert_almost_equal(d2_pinball_score([0.0, 1], [0.0, 1]), 1.0) + + # Non-finite cases + # R² and explained variance have a fix by default for non-finite cases + for s in (r2_score, explained_variance_score): + assert_almost_equal(s([0, 0], [1, -1]), 0.0) + assert_almost_equal(s([0, 0], [1, -1], force_finite=False), -np.inf) + assert_almost_equal(s([1, 1], [1, 1]), 1.0) + assert_almost_equal(s([1, 1], [1, 1], force_finite=False), np.nan) + msg = ( + "Mean Squared Logarithmic Error cannot be used when targets " + "contain negative values." + ) + with pytest.raises(ValueError, match=msg): + mean_squared_log_error([-1.0], [-1.0]) + msg = ( + "Mean Squared Logarithmic Error cannot be used when targets " + "contain negative values." + ) + with pytest.raises(ValueError, match=msg): + mean_squared_log_error([1.0, 2.0, 3.0], [1.0, -2.0, 3.0]) + msg = ( + "Mean Squared Logarithmic Error cannot be used when targets " + "contain negative values." + ) + with pytest.raises(ValueError, match=msg): + mean_squared_log_error([1.0, -2.0, 3.0], [1.0, 2.0, 3.0]) + + # Tweedie deviance error + power = -1.2 + assert_allclose( + mean_tweedie_deviance([0], [1.0], power=power), 2 / (2 - power), rtol=1e-3 + ) + msg = "can only be used on strictly positive y_pred." + with pytest.raises(ValueError, match=msg): + mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + + assert_almost_equal(mean_tweedie_deviance([0.0], [0.0], power=0), 0.0, 2) + + power = 1.0 + msg = "only be used on non-negative y and strictly positive y_pred." + with pytest.raises(ValueError, match=msg): + mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + + power = 1.5 + assert_allclose(mean_tweedie_deviance([0.0], [1.0], power=power), 2 / (2 - power)) + msg = "only be used on non-negative y and strictly positive y_pred." + with pytest.raises(ValueError, match=msg): + mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + + power = 2.0 + assert_allclose(mean_tweedie_deviance([1.0], [1.0], power=power), 0.00, atol=1e-8) + msg = "can only be used on strictly positive y and y_pred." + with pytest.raises(ValueError, match=msg): + mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + + power = 3.0 + assert_allclose(mean_tweedie_deviance([1.0], [1.0], power=power), 0.00, atol=1e-8) + msg = "can only be used on strictly positive y and y_pred." + with pytest.raises(ValueError, match=msg): + mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match=msg): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + + power = 0.5 + with pytest.raises(ValueError, match="is only defined for power<=0 and power>=1"): + mean_tweedie_deviance([0.0], [0.0], power=power) + with pytest.raises(ValueError, match="is only defined for power<=0 and power>=1"): + d2_tweedie_score([0.0] * 2, [0.0] * 2, power=power) + + +def test__check_reg_targets(): + # All of length 3 + EXAMPLES = [ + ("continuous", [1, 2, 3], 1), + ("continuous", [[1], [2], [3]], 1), + ("continuous-multioutput", [[1, 1], [2, 2], [3, 1]], 2), + ("continuous-multioutput", [[5, 1], [4, 2], [3, 1]], 2), + ("continuous-multioutput", [[1, 3, 4], [2, 2, 2], [3, 1, 1]], 3), + ] + + for (type1, y1, n_out1), (type2, y2, n_out2) in product(EXAMPLES, repeat=2): + + if type1 == type2 and n_out1 == n_out2: + y_type, y_check1, y_check2, multioutput = _check_reg_targets(y1, y2, None) + assert type1 == y_type + if type1 == "continuous": + assert_array_equal(y_check1, np.reshape(y1, (-1, 1))) + assert_array_equal(y_check2, np.reshape(y2, (-1, 1))) + else: + assert_array_equal(y_check1, y1) + assert_array_equal(y_check2, y2) + else: + with pytest.raises(ValueError): + _check_reg_targets(y1, y2, None) + + +def test__check_reg_targets_exception(): + invalid_multioutput = "this_value_is_not_valid" + expected_message = ( + "Allowed 'multioutput' string values are.+You provided multioutput={!r}".format( + invalid_multioutput + ) + ) + with pytest.raises(ValueError, match=expected_message): + _check_reg_targets([1, 2, 3], [[1], [2], [3]], invalid_multioutput) + + +def test_regression_multioutput_array(): + y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]] + y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]] + + mse = mean_squared_error(y_true, y_pred, multioutput="raw_values") + mae = mean_absolute_error(y_true, y_pred, multioutput="raw_values") + err_msg = ( + "multioutput is expected to be 'raw_values' " + "or 'uniform_average' but we got 'variance_weighted' instead." + ) + with pytest.raises(ValueError, match=err_msg): + mean_pinball_loss(y_true, y_pred, multioutput="variance_weighted") + + with pytest.raises(ValueError, match=err_msg): + d2_pinball_score(y_true, y_pred, multioutput="variance_weighted") + + pbl = mean_pinball_loss(y_true, y_pred, multioutput="raw_values") + mape = mean_absolute_percentage_error(y_true, y_pred, multioutput="raw_values") + r = r2_score(y_true, y_pred, multioutput="raw_values") + evs = explained_variance_score(y_true, y_pred, multioutput="raw_values") + d2ps = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values") + evs2 = explained_variance_score( + y_true, y_pred, multioutput="raw_values", force_finite=False + ) + + assert_array_almost_equal(mse, [0.125, 0.5625], decimal=2) + assert_array_almost_equal(mae, [0.25, 0.625], decimal=2) + assert_array_almost_equal(pbl, [0.25 / 2, 0.625 / 2], decimal=2) + assert_array_almost_equal(mape, [0.0778, 0.2262], decimal=2) + assert_array_almost_equal(r, [0.95, 0.93], decimal=2) + assert_array_almost_equal(evs, [0.95, 0.93], decimal=2) + assert_array_almost_equal(d2ps, [0.833, 0.722], decimal=2) + assert_array_almost_equal(evs2, [0.95, 0.93], decimal=2) + + # mean_absolute_error and mean_squared_error are equal because + # it is a binary problem. + y_true = [[0, 0]] * 4 + y_pred = [[1, 1]] * 4 + mse = mean_squared_error(y_true, y_pred, multioutput="raw_values") + mae = mean_absolute_error(y_true, y_pred, multioutput="raw_values") + pbl = mean_pinball_loss(y_true, y_pred, multioutput="raw_values") + r = r2_score(y_true, y_pred, multioutput="raw_values") + d2ps = d2_pinball_score(y_true, y_pred, multioutput="raw_values") + assert_array_almost_equal(mse, [1.0, 1.0], decimal=2) + assert_array_almost_equal(mae, [1.0, 1.0], decimal=2) + assert_array_almost_equal(pbl, [0.5, 0.5], decimal=2) + assert_array_almost_equal(r, [0.0, 0.0], decimal=2) + assert_array_almost_equal(d2ps, [0.0, 0.0], decimal=2) + + r = r2_score([[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="raw_values") + assert_array_almost_equal(r, [0, -3.5], decimal=2) + assert np.mean(r) == r2_score( + [[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="uniform_average" + ) + evs = explained_variance_score( + [[0, -1], [0, 1]], [[2, 2], [1, 1]], multioutput="raw_values" + ) + assert_array_almost_equal(evs, [0, -1.25], decimal=2) + evs2 = explained_variance_score( + [[0, -1], [0, 1]], + [[2, 2], [1, 1]], + multioutput="raw_values", + force_finite=False, + ) + assert_array_almost_equal(evs2, [-np.inf, -1.25], decimal=2) + + # Checking for the condition in which both numerator and denominator is + # zero. + y_true = [[1, 3], [1, 2]] + y_pred = [[1, 4], [1, 1]] + r2 = r2_score(y_true, y_pred, multioutput="raw_values") + assert_array_almost_equal(r2, [1.0, -3.0], decimal=2) + assert np.mean(r2) == r2_score(y_true, y_pred, multioutput="uniform_average") + r22 = r2_score(y_true, y_pred, multioutput="raw_values", force_finite=False) + assert_array_almost_equal(r22, [np.nan, -3.0], decimal=2) + assert_almost_equal( + np.mean(r22), + r2_score(y_true, y_pred, multioutput="uniform_average", force_finite=False), + ) + + evs = explained_variance_score(y_true, y_pred, multioutput="raw_values") + assert_array_almost_equal(evs, [1.0, -3.0], decimal=2) + assert np.mean(evs) == explained_variance_score(y_true, y_pred) + d2ps = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput="raw_values") + assert_array_almost_equal(d2ps, [1.0, -1.0], decimal=2) + evs2 = explained_variance_score( + y_true, y_pred, multioutput="raw_values", force_finite=False + ) + assert_array_almost_equal(evs2, [np.nan, -3.0], decimal=2) + assert_almost_equal( + np.mean(evs2), explained_variance_score(y_true, y_pred, force_finite=False) + ) + + # Handling msle separately as it does not accept negative inputs. + y_true = np.array([[0.5, 1], [1, 2], [7, 6]]) + y_pred = np.array([[0.5, 2], [1, 2.5], [8, 8]]) + msle = mean_squared_log_error(y_true, y_pred, multioutput="raw_values") + msle2 = mean_squared_error( + np.log(1 + y_true), np.log(1 + y_pred), multioutput="raw_values" + ) + assert_array_almost_equal(msle, msle2, decimal=2) + + +def test_regression_custom_weights(): + y_true = [[1, 2], [2.5, -1], [4.5, 3], [5, 7]] + y_pred = [[1, 1], [2, -1], [5, 4], [5, 6.5]] + + msew = mean_squared_error(y_true, y_pred, multioutput=[0.4, 0.6]) + rmsew = mean_squared_error(y_true, y_pred, multioutput=[0.4, 0.6], squared=False) + maew = mean_absolute_error(y_true, y_pred, multioutput=[0.4, 0.6]) + mapew = mean_absolute_percentage_error(y_true, y_pred, multioutput=[0.4, 0.6]) + rw = r2_score(y_true, y_pred, multioutput=[0.4, 0.6]) + evsw = explained_variance_score(y_true, y_pred, multioutput=[0.4, 0.6]) + d2psw = d2_pinball_score(y_true, y_pred, alpha=0.5, multioutput=[0.4, 0.6]) + evsw2 = explained_variance_score( + y_true, y_pred, multioutput=[0.4, 0.6], force_finite=False + ) + + assert_almost_equal(msew, 0.39, decimal=2) + assert_almost_equal(rmsew, 0.59, decimal=2) + assert_almost_equal(maew, 0.475, decimal=3) + assert_almost_equal(mapew, 0.1668, decimal=2) + assert_almost_equal(rw, 0.94, decimal=2) + assert_almost_equal(evsw, 0.94, decimal=2) + assert_almost_equal(d2psw, 0.766, decimal=2) + assert_almost_equal(evsw2, 0.94, decimal=2) + + # Handling msle separately as it does not accept negative inputs. + y_true = np.array([[0.5, 1], [1, 2], [7, 6]]) + y_pred = np.array([[0.5, 2], [1, 2.5], [8, 8]]) + msle = mean_squared_log_error(y_true, y_pred, multioutput=[0.3, 0.7]) + msle2 = mean_squared_error( + np.log(1 + y_true), np.log(1 + y_pred), multioutput=[0.3, 0.7] + ) + assert_almost_equal(msle, msle2, decimal=2) + + +@pytest.mark.parametrize("metric", [r2_score, d2_tweedie_score, d2_pinball_score]) +def test_regression_single_sample(metric): + y_true = [0] + y_pred = [1] + warning_msg = "not well-defined with less than two samples." + + # Trigger the warning + with pytest.warns(UndefinedMetricWarning, match=warning_msg): + score = metric(y_true, y_pred) + assert np.isnan(score) + + +def test_tweedie_deviance_continuity(): + n_samples = 100 + + y_true = np.random.RandomState(0).rand(n_samples) + 0.1 + y_pred = np.random.RandomState(1).rand(n_samples) + 0.1 + + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=0 - 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=0), + ) + + # Ws we get closer to the limit, with 1e-12 difference the absolute + # tolerance to pass the below check increases. There are likely + # numerical precision issues on the edges of different definition + # regions. + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=1 + 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=1), + atol=1e-6, + ) + + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=2 - 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=2), + atol=1e-6, + ) + + assert_allclose( + mean_tweedie_deviance(y_true, y_pred, power=2 + 1e-10), + mean_tweedie_deviance(y_true, y_pred, power=2), + atol=1e-6, + ) + + +def test_mean_absolute_percentage_error(): + random_number_generator = np.random.RandomState(42) + y_true = random_number_generator.exponential(size=100) + y_pred = 1.2 * y_true + assert mean_absolute_percentage_error(y_true, y_pred) == pytest.approx(0.2) + + +@pytest.mark.parametrize( + "distribution", ["normal", "lognormal", "exponential", "uniform"] +) +@pytest.mark.parametrize("target_quantile", [0.05, 0.5, 0.75]) +def test_mean_pinball_loss_on_constant_predictions(distribution, target_quantile): + if not hasattr(np, "quantile"): + pytest.skip( + "This test requires a more recent version of numpy " + "with support for np.quantile." + ) + + # Check that the pinball loss is minimized by the empirical quantile. + n_samples = 3000 + rng = np.random.RandomState(42) + data = getattr(rng, distribution)(size=n_samples) + + # Compute the best possible pinball loss for any constant predictor: + best_pred = np.quantile(data, target_quantile) + best_constant_pred = np.full(n_samples, fill_value=best_pred) + best_pbl = mean_pinball_loss(data, best_constant_pred, alpha=target_quantile) + + # Evaluate the loss on a grid of quantiles + candidate_predictions = np.quantile(data, np.linspace(0, 1, 100)) + for pred in candidate_predictions: + # Compute the pinball loss of a constant predictor: + constant_pred = np.full(n_samples, fill_value=pred) + pbl = mean_pinball_loss(data, constant_pred, alpha=target_quantile) + + # Check that the loss of this constant predictor is greater or equal + # than the loss of using the optimal quantile (up to machine + # precision): + assert pbl >= best_pbl - np.finfo(best_pbl.dtype).eps + + # Check that the value of the pinball loss matches the analytical + # formula. + expected_pbl = (pred - data[data < pred]).sum() * (1 - target_quantile) + ( + data[data >= pred] - pred + ).sum() * target_quantile + expected_pbl /= n_samples + assert_almost_equal(expected_pbl, pbl) + + # Check that we can actually recover the target_quantile by minimizing the + # pinball loss w.r.t. the constant prediction quantile. + def objective_func(x): + constant_pred = np.full(n_samples, fill_value=x) + return mean_pinball_loss(data, constant_pred, alpha=target_quantile) + + result = optimize.minimize(objective_func, data.mean(), method="Nelder-Mead") + assert result.success + # The minimum is not unique with limited data, hence the large tolerance. + assert result.x == pytest.approx(best_pred, rel=1e-2) + assert result.fun == pytest.approx(best_pbl) + + +def test_dummy_quantile_parameter_tuning(): + # Integration test to check that it is possible to use the pinball loss to + # tune the hyperparameter of a quantile regressor. This is conceptually + # similar to the previous test but using the scikit-learn estimator and + # scoring API instead. + n_samples = 1000 + rng = np.random.RandomState(0) + X = rng.normal(size=(n_samples, 5)) # Ignored + y = rng.exponential(size=n_samples) + + all_quantiles = [0.05, 0.1, 0.25, 0.5, 0.75, 0.9, 0.95] + for alpha in all_quantiles: + neg_mean_pinball_loss = make_scorer( + mean_pinball_loss, + alpha=alpha, + greater_is_better=False, + ) + regressor = DummyRegressor(strategy="quantile", quantile=0.25) + grid_search = GridSearchCV( + regressor, + param_grid=dict(quantile=all_quantiles), + scoring=neg_mean_pinball_loss, + ).fit(X, y) + + assert grid_search.best_params_["quantile"] == pytest.approx(alpha) + + +def test_pinball_loss_relation_with_mae(): + # Test that mean_pinball loss with alpha=0.5 if half of mean absolute error + rng = np.random.RandomState(714) + n = 100 + y_true = rng.normal(size=n) + y_pred = y_true.copy() + rng.uniform(n) + assert ( + mean_absolute_error(y_true, y_pred) + == mean_pinball_loss(y_true, y_pred, alpha=0.5) * 2 + ) diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..2eba22fd3c224ce5fee316ade13a8eba488c251f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_fast_dict.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:9b4f5d29a391236bb3470e30682bbaea3a86583d5d55b51018bfe38a83cd1053 +size 271113 diff --git a/videollama2/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so b/videollama2/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..61a9d7076a93729469aa3e1ccca195b1dad398f7 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/sklearn/utils/_weight_vector.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:aa1d4bc2bc7ae83be68a224ee6288687da6dd64e1b58b3873f8d3db5486cd730 +size 204313 diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f5e98cc3184bb7d4fa6da515a8513bd71ff6552d --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_indices_copy_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor _indices_copy(const at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_mps_convolution_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_mps_convolution_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..072af280fde0361be1fce94b87365338f787f9a9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_mps_convolution_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API _mps_convolution { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const ::std::optional &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_mps_convolution") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_mps_convolution(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups); +}; + +struct TORCH_API _mps_convolution_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const ::std::optional &, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymIntArrayRef, c10::SymInt, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::_mps_convolution") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "_mps_convolution.out(Tensor self, Tensor weight, Tensor? bias, SymInt[] padding, SymInt[] stride, SymInt[] dilation, SymInt groups, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Tensor & weight, const ::std::optional & bias, c10::SymIntArrayRef padding, c10::SymIntArrayRef stride, c10::SymIntArrayRef dilation, c10::SymInt groups, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward.h new file mode 100644 index 0000000000000000000000000000000000000000..1bc8658b8542f0f4ee70e4604603fd2ebd4d74bb --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_scaled_dot_product_flash_attention_for_cpu_backward.h @@ -0,0 +1,30 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_scaled_dot_product_flash_attention_for_cpu_backward(Tensor grad_out, Tensor query, Tensor key, Tensor value, Tensor out, Tensor logsumexp, float dropout_p, bool is_causal, *, Tensor? attn_mask=None, float? scale=None) -> (Tensor grad_query, Tensor grad_key, Tensor grad_value) +inline ::std::tuple _scaled_dot_product_flash_attention_for_cpu_backward(const at::Tensor & grad_out, const at::Tensor & query, const at::Tensor & key, const at::Tensor & value, const at::Tensor & out, const at::Tensor & logsumexp, double dropout_p, bool is_causal, const ::std::optional & attn_mask={}, ::std::optional scale=::std::nullopt) { + return at::_ops::_scaled_dot_product_flash_attention_for_cpu_backward::call(grad_out, query, key, value, out, logsumexp, dropout_p, is_causal, attn_mask, scale); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..9e4ab8b7e0ab5c25d662fa5f85241b90899a04c3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_sparse_coo_tensor_with_dims_and_tensors_meta_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor _sparse_coo_tensor_with_dims_and_tensors(int64_t sparse_dim, int64_t dense_dim, at::IntArrayRef size, const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options, ::std::optional is_coalesced=::std::nullopt); +TORCH_API at::Tensor _sparse_coo_tensor_with_dims_and_tensors(int64_t sparse_dim, int64_t dense_dim, at::IntArrayRef size, const at::Tensor & indices, const at::Tensor & values, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional is_coalesced); +TORCH_API at::Tensor _sparse_coo_tensor_with_dims_and_tensors_symint(int64_t sparse_dim, int64_t dense_dim, c10::SymIntArrayRef size, const at::Tensor & indices, const at::Tensor & values, at::TensorOptions options, ::std::optional is_coalesced=::std::nullopt); +TORCH_API at::Tensor _sparse_coo_tensor_with_dims_and_tensors_symint(int64_t sparse_dim, int64_t dense_dim, c10::SymIntArrayRef size, const at::Tensor & indices, const at::Tensor & values, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional is_coalesced); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr.h new file mode 100644 index 0000000000000000000000000000000000000000..e856b14d91f21d82964311227f485314c03b5288 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_to_sparse_csr.h @@ -0,0 +1,34 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_to_sparse_csr.out(Tensor self, int? dense_dim=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _to_sparse_csr_out(at::Tensor & out, const at::Tensor & self, ::std::optional dense_dim=::std::nullopt) { + return at::_ops::_to_sparse_csr_out::call(self, dense_dim, out); +} +// aten::_to_sparse_csr.out(Tensor self, int? dense_dim=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _to_sparse_csr_outf(const at::Tensor & self, ::std::optional dense_dim, at::Tensor & out) { + return at::_ops::_to_sparse_csr_out::call(self, dense_dim, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_trilinear_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_trilinear_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..4368ffd655f67ff5ab139f2e63af036ceea94394 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_trilinear_compositeexplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor & _trilinear_out(at::Tensor & out, const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim=1); +TORCH_API at::Tensor & _trilinear_outf(const at::Tensor & i1, const at::Tensor & i2, const at::Tensor & i3, at::IntArrayRef expand1, at::IntArrayRef expand2, at::IntArrayRef expand3, at::IntArrayRef sumdim, int64_t unroll_dim, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..98c0c313e8325b3b6bd382470f5e5e39ef552606 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_bilinear2d_aa_meta_dispatch.h @@ -0,0 +1,28 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor _upsample_bilinear2d_aa(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor _upsample_bilinear2d_aa_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_outf(const at::Tensor & self, at::IntArrayRef output_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & out); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, ::std::optional scales_h=::std::nullopt, ::std::optional scales_w=::std::nullopt); +TORCH_API at::Tensor & _upsample_bilinear2d_aa_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, bool align_corners, ::std::optional scales_h, ::std::optional scales_w, at::Tensor & out); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d.h new file mode 100644 index 0000000000000000000000000000000000000000..b5690c9871cd47c6a9f140778b872615816fb897 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d.h @@ -0,0 +1,113 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::_upsample_nearest_exact1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor +inline at::Tensor _upsample_nearest_exact1d(const at::Tensor & input, at::OptionalIntArrayRef output_size, ::std::optional> scale_factors) { + return at::_ops::_upsample_nearest_exact1d_vec::call(input, output_size.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*output_size)) : ::std::nullopt, scale_factors); +} +namespace symint { + template ::value>> + at::Tensor _upsample_nearest_exact1d(const at::Tensor & input, at::OptionalIntArrayRef output_size, ::std::optional> scale_factors) { + return at::_ops::_upsample_nearest_exact1d_vec::call(input, output_size.has_value() ? ::std::make_optional(c10::fromIntArrayRefSlow(*output_size)) : ::std::nullopt, scale_factors); + } +} + +// aten::_upsample_nearest_exact1d.vec(Tensor input, SymInt[]? output_size, float[]? scale_factors) -> Tensor +inline at::Tensor _upsample_nearest_exact1d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, ::std::optional> scale_factors) { + return at::_ops::_upsample_nearest_exact1d_vec::call(input, output_size, scale_factors); +} +namespace symint { + template ::value>> + at::Tensor _upsample_nearest_exact1d(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, ::std::optional> scale_factors) { + return at::_ops::_upsample_nearest_exact1d_vec::call(input, output_size, scale_factors); + } +} + +// aten::_upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _upsample_nearest_exact1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, c10::fromIntArrayRefSlow(output_size), scales, out); +} +namespace symint { + template ::value>> + at::Tensor & _upsample_nearest_exact1d_out(at::Tensor & out, const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, c10::fromIntArrayRefSlow(output_size), scales, out); + } +} + +// aten::_upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _upsample_nearest_exact1d_outf(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales, at::Tensor & out) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, c10::fromIntArrayRefSlow(output_size), scales, out); +} +namespace symint { + template ::value>> + at::Tensor & _upsample_nearest_exact1d_outf(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales, at::Tensor & out) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, c10::fromIntArrayRefSlow(output_size), scales, out); + } +} + +// aten::_upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _upsample_nearest_exact1d_symint_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, output_size, scales, out); +} +namespace symint { + template ::value>> + at::Tensor & _upsample_nearest_exact1d_out(at::Tensor & out, const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, output_size, scales, out); + } +} + +// aten::_upsample_nearest_exact1d.out(Tensor self, SymInt[1] output_size, float? scales=None, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & _upsample_nearest_exact1d_symint_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales, at::Tensor & out) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, output_size, scales, out); +} +namespace symint { + template ::value>> + at::Tensor & _upsample_nearest_exact1d_outf(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales, at::Tensor & out) { + return at::_ops::_upsample_nearest_exact1d_out::call(self, output_size, scales, out); + } +} + +// aten::_upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor +inline at::Tensor _upsample_nearest_exact1d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d::call(self, c10::fromIntArrayRefSlow(output_size), scales); +} +namespace symint { + template ::value>> + at::Tensor _upsample_nearest_exact1d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d::call(self, c10::fromIntArrayRefSlow(output_size), scales); + } +} + +// aten::_upsample_nearest_exact1d(Tensor self, SymInt[1] output_size, float? scales=None) -> Tensor +inline at::Tensor _upsample_nearest_exact1d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d::call(self, output_size, scales); +} +namespace symint { + template ::value>> + at::Tensor _upsample_nearest_exact1d(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales=::std::nullopt) { + return at::_ops::_upsample_nearest_exact1d::call(self, output_size, scales); + } +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..433d069ede44ebd4964c7379c08cf5e4d27955b3 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/_upsample_nearest_exact1d_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor _upsample_nearest_exact1d(const at::Tensor & self, at::IntArrayRef output_size, ::std::optional scales=::std::nullopt); +TORCH_API at::Tensor _upsample_nearest_exact1d_symint(const at::Tensor & self, c10::SymIntArrayRef output_size, ::std::optional scales=::std::nullopt); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool3d_backward_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool3d_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b8a54daf60841981383e559fdfbd50d8c49ef71a --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/adaptive_max_pool3d_backward_cpu_dispatch.h @@ -0,0 +1,25 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor adaptive_max_pool3d_backward(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices); +TORCH_API at::Tensor & adaptive_max_pool3d_backward_out(at::Tensor & grad_input, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices); +TORCH_API at::Tensor & adaptive_max_pool3d_backward_outf(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & indices, at::Tensor & grad_input); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_right_shift_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_right_shift_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f14e8031a4df14ba78dc10750c241defa62fdd42 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/bitwise_right_shift_cuda_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor bitwise_right_shift(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_right_shift_out(at::Tensor & out, const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & bitwise_right_shift_outf(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +TORCH_API at::Tensor & bitwise_right_shift_(at::Tensor & self, const at::Tensor & other); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_dense_backward_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_dense_backward_native.h new file mode 100644 index 0000000000000000000000000000000000000000..006d55e1c83b386b0901635cdd103063595eef60 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/embedding_dense_backward_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor & embedding_dense_backward_out_symint(const at::Tensor & grad_output, const at::Tensor & indices, c10::SymInt num_weights, c10::SymInt padding_idx, bool scale_grad_by_freq, at::Tensor & out); +TORCH_API at::Tensor embedding_dense_backward_cpu(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +TORCH_API at::Tensor embedding_dense_backward_cuda(const at::Tensor & grad_output, const at::Tensor & indices, int64_t num_weights, int64_t padding_idx, bool scale_grad_by_freq); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expm1_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expm1_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b87e13d9c52089e2d2bd780bcb35cf733ceb6be1 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/expm1_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor expm1(const at::Tensor & self); +TORCH_API at::Tensor & expm1_(at::Tensor & self); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_backward_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_backward_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..933b0f3b741b2d6ed9f3159b2b2ab2ff64921a6b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/fake_quantize_per_tensor_affine_cachemask_backward_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor fake_quantize_per_tensor_affine_cachemask_backward(const at::Tensor & grad, const at::Tensor & mask); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/i0_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/i0_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..9b3666463c2b8eb1353408e8564576b924e80204 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/i0_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API i0 { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::i0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "i0(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API i0_ { + using schema = at::Tensor & (at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::i0_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "i0_(Tensor(a!) self) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self); +}; + +struct TORCH_API i0_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::i0") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "i0.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_native.h new file mode 100644 index 0000000000000000000000000000000000000000..4a077f5f85d1536ec5453799882069821fb6cdbf --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/is_neg_native.h @@ -0,0 +1,21 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API bool is_neg(const at::Tensor & self); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linear_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linear_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..b89506d8e1fce5f99e4079c2a1e08c54d10d2887 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/linear_compositeimplicitautograd_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor linear(const at::Tensor & input, const at::Tensor & weight, const ::std::optional & bias={}); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/logical_xor_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/logical_xor_native.h new file mode 100644 index 0000000000000000000000000000000000000000..784c8a544d31b65c2c38c2f9c2a1565536416688 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/logical_xor_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor logical_xor(const at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_xor_(at::Tensor & self, const at::Tensor & other); +TORCH_API at::Tensor & logical_xor_out(const at::Tensor & self, const at::Tensor & other, at::Tensor & out); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lu_unpack_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lu_unpack_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..87e98c03f6048f6e24c9378434ad3c4243273d37 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/lu_unpack_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API lu_unpack { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::lu_unpack") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lu_unpack(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True) -> (Tensor P, Tensor L, Tensor U)") + static ::std::tuple call(const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots); +}; + +struct TORCH_API lu_unpack_out { + using schema = ::std::tuple (const at::Tensor &, const at::Tensor &, bool, bool, at::Tensor &, at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::lu_unpack") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "lu_unpack.out(Tensor LU_data, Tensor LU_pivots, bool unpack_data=True, bool unpack_pivots=True, *, Tensor(a!) P, Tensor(b!) L, Tensor(c!) U) -> (Tensor(a!) P, Tensor(b!) L, Tensor(c!) U)") + static ::std::tuple call(const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots, at::Tensor & P, at::Tensor & L, at::Tensor & U); + static ::std::tuple redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & LU_data, const at::Tensor & LU_pivots, bool unpack_data, bool unpack_pivots, at::Tensor & P, at::Tensor & L, at::Tensor & U); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mish_meta.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mish_meta.h new file mode 100644 index 0000000000000000000000000000000000000000..230f95e026c213d55b4bed911a9079d6c9dddaa2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mish_meta.h @@ -0,0 +1,27 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeMetaFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace at { +namespace meta { + +struct TORCH_API structured_mish : public TensorIteratorBase { + + + void meta(const at::Tensor & self); +}; + +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_rnn_layer_backward_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_rnn_layer_backward_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..0539500a4d657edf5341dc80955fffaec6dbedc4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/mkldnn_rnn_layer_backward_cpu_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API ::std::tuple mkldnn_rnn_layer_backward(const at::Tensor & input, const at::Tensor & weight1, const at::Tensor & weight2, const at::Tensor & weight3, const at::Tensor & weight4, const at::Tensor & hx_, const at::Tensor & cx_tmp, const at::Tensor & output, const at::Tensor & hy_, const at::Tensor & cy_, const ::std::optional & grad_output, const ::std::optional & grad_hy, const ::std::optional & grad_cy, bool reverse, int64_t mode, int64_t hidden_size, int64_t num_layers, bool has_biases, bool train, bool bidirectional, at::IntArrayRef batch_sizes, bool batch_first, const at::Tensor & workspace); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_group_norm_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_group_norm_native.h new file mode 100644 index 0000000000000000000000000000000000000000..f76ab00bd5220a8b05eaedf3b4eb5c184460ef51 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/native_group_norm_native.h @@ -0,0 +1,23 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API ::std::tuple math_group_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, int64_t N, int64_t C, int64_t HxW, int64_t group, double eps); +TORCH_API ::std::tuple native_group_norm_out_symint(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, c10::SymInt N, c10::SymInt C, c10::SymInt HxW, int64_t group, double eps, at::Tensor & out0, at::Tensor & out1, at::Tensor & out2); +TORCH_API ::std::tuple native_group_norm(const at::Tensor & input, const ::std::optional & weight, const ::std::optional & bias, int64_t N, int64_t C, int64_t HxW, int64_t group, double eps); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/q_per_channel_zero_points_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/q_per_channel_zero_points_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..02e538c13e5a0bb044320787665a1f180159c13b --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/q_per_channel_zero_points_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API q_per_channel_zero_points { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::q_per_channel_zero_points") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "q_per_channel_zero_points(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API q_per_channel_zero_points_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::q_per_channel_zero_points") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "q_per_channel_zero_points.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..f5a4b6fa7cfe4b79767c5c603841799abd572ac8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/renorm_ops.h @@ -0,0 +1,50 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API renorm_out { + using schema = at::Tensor & (const at::Tensor &, const at::Scalar &, int64_t, const at::Scalar &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::renorm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "renorm.out(Tensor self, Scalar p, int dim, Scalar maxnorm, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm, at::Tensor & out); +}; + +struct TORCH_API renorm { + using schema = at::Tensor (const at::Tensor &, const at::Scalar &, int64_t, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::renorm") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "renorm(Tensor self, Scalar p, int dim, Scalar maxnorm) -> Tensor") + static at::Tensor call(const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm); +}; + +struct TORCH_API renorm_ { + using schema = at::Tensor & (at::Tensor &, const at::Scalar &, int64_t, const at::Scalar &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::renorm_") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "renorm_(Tensor(a!) self, Scalar p, int dim, Scalar maxnorm) -> Tensor(a!)") + static at::Tensor & call(at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, at::Tensor & self, const at::Scalar & p, int64_t dim, const at::Scalar & maxnorm); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_interleave_cuda_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_interleave_cuda_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..851c4b87c6080476f1385eb04e63fe7575eaea43 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/repeat_interleave_cuda_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cuda { + +TORCH_API at::Tensor repeat_interleave(const at::Tensor & repeats, ::std::optional output_size=::std::nullopt); +TORCH_API at::Tensor repeat_interleave_symint(const at::Tensor & repeats, ::std::optional output_size=::std::nullopt); + +} // namespace cuda +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rrelu_with_noise_backward_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rrelu_with_noise_backward_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..85e7d49f2645149f38b6ebe18b1db6c1da1d16ee --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/rrelu_with_noise_backward_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API rrelu_with_noise_backward { + using schema = at::Tensor (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, bool, bool); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rrelu_with_noise_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rrelu_with_noise_backward(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result) -> Tensor") + static at::Tensor call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower, const at::Scalar & upper, bool training, bool self_is_result); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower, const at::Scalar & upper, bool training, bool self_is_result); +}; + +struct TORCH_API rrelu_with_noise_backward_out { + using schema = at::Tensor & (const at::Tensor &, const at::Tensor &, const at::Tensor &, const at::Scalar &, const at::Scalar &, bool, bool, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::rrelu_with_noise_backward") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "rrelu_with_noise_backward.out(Tensor grad_output, Tensor self, Tensor noise, Scalar lower, Scalar upper, bool training, bool self_is_result, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower, const at::Scalar & upper, bool training, bool self_is_result, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & grad_output, const at::Tensor & self, const at::Tensor & noise, const at::Scalar & lower, const at::Scalar & upper, bool training, bool self_is_result, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/set_meta_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/set_meta_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..f58ebc53bc74b0ce6739cf925d4c4ffe578d32dd --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/set_meta_dispatch.h @@ -0,0 +1,27 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace meta { + +TORCH_API at::Tensor & set_(at::Tensor & self, at::Storage source); +TORCH_API at::Tensor & set_(at::Tensor & self, at::Storage source, int64_t storage_offset, at::IntArrayRef size, at::IntArrayRef stride={}); +TORCH_API at::Tensor & set__symint(at::Tensor & self, at::Storage source, c10::SymInt storage_offset, c10::SymIntArrayRef size, c10::SymIntArrayRef stride={}); +TORCH_API at::Tensor & set_(at::Tensor & self, const at::Tensor & source); +TORCH_API at::Tensor & set_(at::Tensor & self); + +} // namespace meta +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slow_conv_dilated3d_cpu_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slow_conv_dilated3d_cpu_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..8881d16c239adc9dfe354024d6d1466a3f030150 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/slow_conv_dilated3d_cpu_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace cpu { + +TORCH_API at::Tensor slow_conv_dilated3d(const at::Tensor & self, const at::Tensor & weight, at::IntArrayRef kernel_size, const ::std::optional & bias={}, at::IntArrayRef stride=1, at::IntArrayRef padding=0, at::IntArrayRef dilation=1); +TORCH_API at::Tensor slow_conv_dilated3d_symint(const at::Tensor & self, const at::Tensor & weight, c10::SymIntArrayRef kernel_size, const ::std::optional & bias={}, c10::SymIntArrayRef stride=c10::SymInt(1), c10::SymIntArrayRef padding=c10::SymInt(0), c10::SymIntArrayRef dilation=c10::SymInt(1)); + +} // namespace cpu +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_sinc.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_sinc.h new file mode 100644 index 0000000000000000000000000000000000000000..4438b14c18c8cf819504c3ec202ce2cf763a9b42 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_sinc.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Function.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + + +#include + +namespace at { + + +// aten::special_sinc(Tensor self) -> Tensor +inline at::Tensor special_sinc(const at::Tensor & self) { + return at::_ops::special_sinc::call(self); +} + +// aten::special_sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_sinc_out(at::Tensor & out, const at::Tensor & self) { + return at::_ops::special_sinc_out::call(self, out); +} +// aten::special_sinc.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!) +inline at::Tensor & special_sinc_outf(const at::Tensor & self, at::Tensor & out) { + return at::_ops::special_sinc_out::call(self, out); +} + +} diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_xlog1py_compositeexplicitautogradnonfunctional_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_xlog1py_compositeexplicitautogradnonfunctional_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..496e84b27a3095bbe1431706adb08800465eaa30 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/special_xlog1py_compositeexplicitautogradnonfunctional_dispatch.h @@ -0,0 +1,23 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautogradnonfunctional { + +TORCH_API at::Tensor special_xlog1py(const at::Tensor & self, const at::Tensor & other); + +} // namespace compositeexplicitautogradnonfunctional +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sum_to_size_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sum_to_size_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..fe1a50bad0646c1b36a54ce2e4f630b32ab5deb9 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/sum_to_size_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor sum_to_size(const at::Tensor & self, at::IntArrayRef size); +TORCH_API at::Tensor sum_to_size_symint(const at::Tensor & self, c10::SymIntArrayRef size); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/swapdims_native.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/swapdims_native.h new file mode 100644 index 0000000000000000000000000000000000000000..facf4c218af9a0f7f73d1e688f1c497fd9df43d2 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/swapdims_native.h @@ -0,0 +1,22 @@ +#pragma once + +// @generated by torchgen/gen.py from NativeFunction.h + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +namespace at { +namespace native { +TORCH_API at::Tensor swapdims(const at::Tensor & self, int64_t dim0, int64_t dim1); +TORCH_API at::Tensor & swapdims_(at::Tensor & self, int64_t dim0, int64_t dim1); +} // namespace native +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_bilinear2d_compositeimplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_bilinear2d_compositeimplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..c554723846bfe5e9321d68bc3e16297445a291f8 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/upsample_bilinear2d_compositeimplicitautograd_dispatch.h @@ -0,0 +1,24 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeimplicitautograd { + +TORCH_API at::Tensor upsample_bilinear2d(const at::Tensor & input, at::OptionalIntArrayRef output_size, bool align_corners, ::std::optional> scale_factors); +TORCH_API at::Tensor upsample_bilinear2d_symint(const at::Tensor & input, at::OptionalSymIntArrayRef output_size, bool align_corners, ::std::optional> scale_factors); + +} // namespace compositeimplicitautograd +} // namespace at diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/view_as_complex_copy_ops.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/view_as_complex_copy_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..088221e2616642108d76586756bd716f68bb1c86 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/view_as_complex_copy_ops.h @@ -0,0 +1,39 @@ +#pragma once + +// @generated by torchgen/gen.py from Operator.h + +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { +namespace _ops { + + +struct TORCH_API view_as_complex_copy { + using schema = at::Tensor (const at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::view_as_complex_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "view_as_complex_copy(Tensor self) -> Tensor") + static at::Tensor call(const at::Tensor & self); + static at::Tensor redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self); +}; + +struct TORCH_API view_as_complex_copy_out { + using schema = at::Tensor & (const at::Tensor &, at::Tensor &); + using ptr_schema = schema*; + // See Note [static constexpr char* members for windows NVCC] + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(name, "aten::view_as_complex_copy") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(overload_name, "out") + STATIC_CONSTEXPR_STR_INL_EXCEPT_WIN_CUDA(schema_str, "view_as_complex_copy.out(Tensor self, *, Tensor(a!) out) -> Tensor(a!)") + static at::Tensor & call(const at::Tensor & self, at::Tensor & out); + static at::Tensor & redispatch(c10::DispatchKeySet dispatchKeySet, const at::Tensor & self, at::Tensor & out); +}; + +}} // namespace at::_ops diff --git a/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/zeros_like_compositeexplicitautograd_dispatch.h b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/zeros_like_compositeexplicitautograd_dispatch.h new file mode 100644 index 0000000000000000000000000000000000000000..446a2ffd34ba4c7fbf956ff09dfccbfa4e589b34 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/torch/include/ATen/ops/zeros_like_compositeexplicitautograd_dispatch.h @@ -0,0 +1,26 @@ +#pragma once +// @generated by torchgen/gen.py from DispatchKeyFunction.h + +// NB: The implementing C++ file is RegisterDispatchKey.cpp + +// The only #includes we need are for custom classes that have defaults in the C++ API +#include +#include +#include + +// Forward declarations of any types needed in the operator signatures. +// We can't directly include these classes because it will cause circular include dependencies. +// This file is included by TensorBody.h, which defines the Tensor class. +#include + +namespace at { + +namespace compositeexplicitautograd { + +TORCH_API at::Tensor zeros_like(const at::Tensor & self, at::TensorOptions options={}, ::std::optional memory_format=::std::nullopt); +TORCH_API at::Tensor zeros_like(const at::Tensor & self, ::std::optional dtype, ::std::optional layout, ::std::optional device, ::std::optional pin_memory, ::std::optional memory_format); +TORCH_API at::Tensor & zeros_like_out(at::Tensor & out, const at::Tensor & self, ::std::optional memory_format=::std::nullopt); +TORCH_API at::Tensor & zeros_like_outf(const at::Tensor & self, ::std::optional memory_format, at::Tensor & out); + +} // namespace compositeexplicitautograd +} // namespace at