')
+
+
+def test_multivariate_repr_png():
+ cmap = mpl.multivar_colormaps['3VarAddA']
+ png = cmap._repr_png_()
+ assert len(png) > 0
+ img = Image.open(BytesIO(png))
+ assert img.width > 0
+ assert img.height > 0
+ assert 'Title' in img.text
+ assert 'Description' in img.text
+ assert 'Author' in img.text
+ assert 'Software' in img.text
+
+
+def test_multivariate_repr_html():
+ cmap = mpl.multivar_colormaps['3VarAddA']
+ html = cmap._repr_html_()
+ assert len(html) > 0
+ for c in cmap:
+ png = c._repr_png_()
+ assert base64.b64encode(png).decode('ascii') in html
+ assert cmap.name in html
+ assert html.startswith('
')
+
+
+def test_bivar_eq():
+ """
+ Tests equality between multivariate colormaps
+ """
+ cmap_0 = mpl.bivar_colormaps['BiPeak']
+
+ cmap_1 = mpl.bivar_colormaps['BiPeak']
+ assert (cmap_0 == cmap_1) is True
+
+ cmap_1 = mpl.multivar_colormaps['2VarAddA']
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.bivar_colormaps['BiCone']
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.bivar_colormaps['BiPeak']
+ cmap_1 = cmap_1.with_extremes(bad='k')
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.bivar_colormaps['BiPeak']
+ cmap_1 = cmap_1.with_extremes(outside='k')
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.bivar_colormaps['BiPeak']
+ cmap_1._init()
+ cmap_1._lut *= 0.5
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.bivar_colormaps['BiPeak']
+ cmap_1 = cmap_1.with_extremes(shape='ignore')
+ assert (cmap_0 == cmap_1) is False
+
+
+def test_multivar_eq():
+ """
+ Tests equality between multivariate colormaps
+ """
+ cmap_0 = mpl.multivar_colormaps['2VarAddA']
+
+ cmap_1 = mpl.multivar_colormaps['2VarAddA']
+ assert (cmap_0 == cmap_1) is True
+
+ cmap_1 = mpl.bivar_colormaps['BiPeak']
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.colors.MultivarColormap([cmap_0[0]]*2,
+ 'sRGB_add')
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.multivar_colormaps['3VarAddA']
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.multivar_colormaps['2VarAddA']
+ cmap_1 = cmap_1.with_extremes(bad='k')
+ assert (cmap_0 == cmap_1) is False
+
+ cmap_1 = mpl.multivar_colormaps['2VarAddA']
+ cmap_1 = mpl.colors.MultivarColormap(cmap_1[:], 'sRGB_sub')
+ assert (cmap_0 == cmap_1) is False
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_offsetbox.py b/lib/python3.12/site-packages/matplotlib/tests/test_offsetbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..b23a8da7dc052157f4ba9e4f6f08d5fa41ab8c41
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_offsetbox.py
@@ -0,0 +1,462 @@
+from collections import namedtuple
+import io
+
+import numpy as np
+from numpy.testing import assert_allclose
+import pytest
+
+from matplotlib.testing.decorators import check_figures_equal, image_comparison
+import matplotlib.pyplot as plt
+import matplotlib.patches as mpatches
+import matplotlib.lines as mlines
+from matplotlib.backend_bases import MouseButton, MouseEvent
+
+from matplotlib.offsetbox import (
+ AnchoredOffsetbox, AnnotationBbox, AnchoredText, DrawingArea, HPacker,
+ OffsetBox, OffsetImage, PaddedBox, TextArea, VPacker, _get_packed_offsets)
+
+
+@image_comparison(['offsetbox_clipping'], remove_text=True)
+def test_offsetbox_clipping():
+ # - create a plot
+ # - put an AnchoredOffsetbox with a child DrawingArea
+ # at the center of the axes
+ # - give the DrawingArea a gray background
+ # - put a black line across the bounds of the DrawingArea
+ # - see that the black line is clipped to the edges of
+ # the DrawingArea.
+ fig, ax = plt.subplots()
+ size = 100
+ da = DrawingArea(size, size, clip=True)
+ assert da.clip_children
+ bg = mpatches.Rectangle((0, 0), size, size,
+ facecolor='#CCCCCC',
+ edgecolor='None',
+ linewidth=0)
+ line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2],
+ color='black',
+ linewidth=10)
+ anchored_box = AnchoredOffsetbox(
+ loc='center',
+ child=da,
+ pad=0.,
+ frameon=False,
+ bbox_to_anchor=(.5, .5),
+ bbox_transform=ax.transAxes,
+ borderpad=0.)
+
+ da.add_artist(bg)
+ da.add_artist(line)
+ ax.add_artist(anchored_box)
+ ax.set_xlim((0, 1))
+ ax.set_ylim((0, 1))
+
+
+def test_offsetbox_clip_children():
+ # - create a plot
+ # - put an AnchoredOffsetbox with a child DrawingArea
+ # at the center of the axes
+ # - give the DrawingArea a gray background
+ # - put a black line across the bounds of the DrawingArea
+ # - see that the black line is clipped to the edges of
+ # the DrawingArea.
+ fig, ax = plt.subplots()
+ size = 100
+ da = DrawingArea(size, size, clip=True)
+ bg = mpatches.Rectangle((0, 0), size, size,
+ facecolor='#CCCCCC',
+ edgecolor='None',
+ linewidth=0)
+ line = mlines.Line2D([-size*.5, size*1.5], [size/2, size/2],
+ color='black',
+ linewidth=10)
+ anchored_box = AnchoredOffsetbox(
+ loc='center',
+ child=da,
+ pad=0.,
+ frameon=False,
+ bbox_to_anchor=(.5, .5),
+ bbox_transform=ax.transAxes,
+ borderpad=0.)
+
+ da.add_artist(bg)
+ da.add_artist(line)
+ ax.add_artist(anchored_box)
+
+ fig.canvas.draw()
+ assert not fig.stale
+ da.clip_children = True
+ assert fig.stale
+
+
+def test_offsetbox_loc_codes():
+ # Check that valid string location codes all work with an AnchoredOffsetbox
+ codes = {'upper right': 1,
+ 'upper left': 2,
+ 'lower left': 3,
+ 'lower right': 4,
+ 'right': 5,
+ 'center left': 6,
+ 'center right': 7,
+ 'lower center': 8,
+ 'upper center': 9,
+ 'center': 10,
+ }
+ fig, ax = plt.subplots()
+ da = DrawingArea(100, 100)
+ for code in codes:
+ anchored_box = AnchoredOffsetbox(loc=code, child=da)
+ ax.add_artist(anchored_box)
+ fig.canvas.draw()
+
+
+def test_expand_with_tight_layout():
+ # Check issue reported in #10476, and updated due to #10784
+ fig, ax = plt.subplots()
+
+ d1 = [1, 2]
+ d2 = [2, 1]
+ ax.plot(d1, label='series 1')
+ ax.plot(d2, label='series 2')
+ ax.legend(ncols=2, mode='expand')
+
+ fig.tight_layout() # where the crash used to happen
+
+
+@pytest.mark.parametrize('widths',
+ ([150], [150, 150, 150], [0.1], [0.1, 0.1]))
+@pytest.mark.parametrize('total', (250, 100, 0, -1, None))
+@pytest.mark.parametrize('sep', (250, 1, 0, -1))
+@pytest.mark.parametrize('mode', ("expand", "fixed", "equal"))
+def test_get_packed_offsets(widths, total, sep, mode):
+ # Check a (rather arbitrary) set of parameters due to successive similar
+ # issue tickets (at least #10476 and #10784) related to corner cases
+ # triggered inside this function when calling higher-level functions
+ # (e.g. `Axes.legend`).
+ # These are just some additional smoke tests. The output is untested.
+ _get_packed_offsets(widths, total, sep, mode=mode)
+
+
+_Params = namedtuple('_Params', 'wd_list, total, sep, expected')
+
+
+@pytest.mark.parametrize('widths, total, sep, expected', [
+ _Params( # total=None
+ [3, 1, 2], total=None, sep=1, expected=(8, [0, 4, 6])),
+ _Params( # total larger than required
+ [3, 1, 2], total=10, sep=1, expected=(10, [0, 4, 6])),
+ _Params( # total smaller than required
+ [3, 1, 2], total=5, sep=1, expected=(5, [0, 4, 6])),
+])
+def test_get_packed_offsets_fixed(widths, total, sep, expected):
+ result = _get_packed_offsets(widths, total, sep, mode='fixed')
+ assert result[0] == expected[0]
+ assert_allclose(result[1], expected[1])
+
+
+@pytest.mark.parametrize('widths, total, sep, expected', [
+ _Params( # total=None (implicit 1)
+ [.1, .1, .1], total=None, sep=None, expected=(1, [0, .45, .9])),
+ _Params( # total larger than sum of widths
+ [3, 1, 2], total=10, sep=1, expected=(10, [0, 5, 8])),
+ _Params( # total smaller sum of widths: overlapping boxes
+ [3, 1, 2], total=5, sep=1, expected=(5, [0, 2.5, 3])),
+])
+def test_get_packed_offsets_expand(widths, total, sep, expected):
+ result = _get_packed_offsets(widths, total, sep, mode='expand')
+ assert result[0] == expected[0]
+ assert_allclose(result[1], expected[1])
+
+
+@pytest.mark.parametrize('widths, total, sep, expected', [
+ _Params( # total larger than required
+ [3, 2, 1], total=6, sep=None, expected=(6, [0, 2, 4])),
+ _Params( # total smaller sum of widths: overlapping boxes
+ [3, 2, 1, .5], total=2, sep=None, expected=(2, [0, 0.5, 1, 1.5])),
+ _Params( # total larger than required
+ [.5, 1, .2], total=None, sep=1, expected=(6, [0, 2, 4])),
+ # the case total=None, sep=None is tested separately below
+])
+def test_get_packed_offsets_equal(widths, total, sep, expected):
+ result = _get_packed_offsets(widths, total, sep, mode='equal')
+ assert result[0] == expected[0]
+ assert_allclose(result[1], expected[1])
+
+
+def test_get_packed_offsets_equal_total_none_sep_none():
+ with pytest.raises(ValueError):
+ _get_packed_offsets([1, 1, 1], total=None, sep=None, mode='equal')
+
+
+@pytest.mark.parametrize('child_type', ['draw', 'image', 'text'])
+@pytest.mark.parametrize('boxcoords',
+ ['axes fraction', 'axes pixels', 'axes points',
+ 'data'])
+def test_picking(child_type, boxcoords):
+ # These all take up approximately the same area.
+ if child_type == 'draw':
+ picking_child = DrawingArea(5, 5)
+ picking_child.add_artist(mpatches.Rectangle((0, 0), 5, 5, linewidth=0))
+ elif child_type == 'image':
+ im = np.ones((5, 5))
+ im[2, 2] = 0
+ picking_child = OffsetImage(im)
+ elif child_type == 'text':
+ picking_child = TextArea('\N{Black Square}', textprops={'fontsize': 5})
+ else:
+ assert False, f'Unknown picking child type {child_type}'
+
+ fig, ax = plt.subplots()
+ ab = AnnotationBbox(picking_child, (0.5, 0.5), boxcoords=boxcoords)
+ ab.set_picker(True)
+ ax.add_artist(ab)
+
+ calls = []
+ fig.canvas.mpl_connect('pick_event', lambda event: calls.append(event))
+
+ # Annotation should be picked by an event occurring at its center.
+ if boxcoords == 'axes points':
+ x, y = ax.transAxes.transform_point((0, 0))
+ x += 0.5 * fig.dpi / 72
+ y += 0.5 * fig.dpi / 72
+ elif boxcoords == 'axes pixels':
+ x, y = ax.transAxes.transform_point((0, 0))
+ x += 0.5
+ y += 0.5
+ else:
+ x, y = ax.transAxes.transform_point((0.5, 0.5))
+ fig.canvas.draw()
+ calls.clear()
+ MouseEvent(
+ "button_press_event", fig.canvas, x, y, MouseButton.LEFT)._process()
+ assert len(calls) == 1 and calls[0].artist == ab
+
+ # Annotation should *not* be picked by an event at its original center
+ # point when the limits have changed enough to hide the *xy* point.
+ ax.set_xlim(-1, 0)
+ ax.set_ylim(-1, 0)
+ fig.canvas.draw()
+ calls.clear()
+ MouseEvent(
+ "button_press_event", fig.canvas, x, y, MouseButton.LEFT)._process()
+ assert len(calls) == 0
+
+
+@image_comparison(['anchoredtext_align.png'], remove_text=True, style='mpl20')
+def test_anchoredtext_horizontal_alignment():
+ fig, ax = plt.subplots()
+
+ text0 = AnchoredText("test\ntest long text", loc="center left",
+ pad=0.2, prop={"ha": "left"})
+ ax.add_artist(text0)
+ text1 = AnchoredText("test\ntest long text", loc="center",
+ pad=0.2, prop={"ha": "center"})
+ ax.add_artist(text1)
+ text2 = AnchoredText("test\ntest long text", loc="center right",
+ pad=0.2, prop={"ha": "right"})
+ ax.add_artist(text2)
+
+
+@pytest.mark.parametrize("extent_kind", ["window_extent", "tightbbox"])
+def test_annotationbbox_extents(extent_kind):
+ plt.rcParams.update(plt.rcParamsDefault)
+ fig, ax = plt.subplots(figsize=(4, 3), dpi=100)
+
+ ax.axis([0, 1, 0, 1])
+
+ an1 = ax.annotate("Annotation", xy=(.9, .9), xytext=(1.1, 1.1),
+ arrowprops=dict(arrowstyle="->"), clip_on=False,
+ va="baseline", ha="left")
+
+ da = DrawingArea(20, 20, 0, 0, clip=True)
+ p = mpatches.Circle((-10, 30), 32)
+ da.add_artist(p)
+
+ ab3 = AnnotationBbox(da, [.5, .5], xybox=(-0.2, 0.5), xycoords='data',
+ boxcoords="axes fraction", box_alignment=(0., .5),
+ arrowprops=dict(arrowstyle="->"))
+ ax.add_artist(ab3)
+
+ im = OffsetImage(np.random.rand(10, 10), zoom=3)
+ im.image.axes = ax
+ ab6 = AnnotationBbox(im, (0.5, -.3), xybox=(0, 75),
+ xycoords='axes fraction',
+ boxcoords="offset points", pad=0.3,
+ arrowprops=dict(arrowstyle="->"))
+ ax.add_artist(ab6)
+
+ # Test Annotation
+ bb1 = getattr(an1, f"get_{extent_kind}")()
+
+ target1 = [332.9, 242.8, 467.0, 298.9]
+ assert_allclose(bb1.extents, target1, atol=2)
+
+ # Test AnnotationBbox
+ bb3 = getattr(ab3, f"get_{extent_kind}")()
+
+ target3 = [-17.6, 129.0, 200.7, 167.9]
+ assert_allclose(bb3.extents, target3, atol=2)
+
+ bb6 = getattr(ab6, f"get_{extent_kind}")()
+
+ target6 = [180.0, -32.0, 230.0, 92.9]
+ assert_allclose(bb6.extents, target6, atol=2)
+
+ # Test bbox_inches='tight'
+ buf = io.BytesIO()
+ fig.savefig(buf, bbox_inches='tight')
+ buf.seek(0)
+ shape = plt.imread(buf).shape
+ targetshape = (350, 504, 4)
+ assert_allclose(shape, targetshape, atol=2)
+
+ # Simple smoke test for tight_layout, to make sure it does not error out.
+ fig.canvas.draw()
+ fig.tight_layout()
+ fig.canvas.draw()
+
+
+def test_zorder():
+ assert OffsetBox(zorder=42).zorder == 42
+
+
+def test_arrowprops_copied():
+ da = DrawingArea(20, 20, 0, 0, clip=True)
+ arrowprops = {"arrowstyle": "->", "relpos": (.3, .7)}
+ ab = AnnotationBbox(da, [.5, .5], xybox=(-0.2, 0.5), xycoords='data',
+ boxcoords="axes fraction", box_alignment=(0., .5),
+ arrowprops=arrowprops)
+ assert ab.arrowprops is not ab
+ assert arrowprops["relpos"] == (.3, .7)
+
+
+@pytest.mark.parametrize("align", ["baseline", "bottom", "top",
+ "left", "right", "center"])
+def test_packers(align):
+ # set the DPI to match points to make the math easier below
+ fig = plt.figure(dpi=72)
+ renderer = fig.canvas.get_renderer()
+
+ x1, y1 = 10, 30
+ x2, y2 = 20, 60
+ r1 = DrawingArea(x1, y1)
+ r2 = DrawingArea(x2, y2)
+
+ # HPacker
+ hpacker = HPacker(children=[r1, r2], align=align)
+ hpacker.draw(renderer)
+ bbox = hpacker.get_bbox(renderer)
+ px, py = hpacker.get_offset(bbox, renderer)
+ # width, height, xdescent, ydescent
+ assert_allclose(bbox.bounds, (0, 0, x1 + x2, max(y1, y2)))
+ # internal element placement
+ if align in ("baseline", "left", "bottom"):
+ y_height = 0
+ elif align in ("right", "top"):
+ y_height = y2 - y1
+ elif align == "center":
+ y_height = (y2 - y1) / 2
+ # x-offsets, y-offsets
+ assert_allclose([child.get_offset() for child in hpacker.get_children()],
+ [(px, py + y_height), (px + x1, py)])
+
+ # VPacker
+ vpacker = VPacker(children=[r1, r2], align=align)
+ vpacker.draw(renderer)
+ bbox = vpacker.get_bbox(renderer)
+ px, py = vpacker.get_offset(bbox, renderer)
+ # width, height, xdescent, ydescent
+ assert_allclose(bbox.bounds, (0, -max(y1, y2), max(x1, x2), y1 + y2))
+ # internal element placement
+ if align in ("baseline", "left", "bottom"):
+ x_height = 0
+ elif align in ("right", "top"):
+ x_height = x2 - x1
+ elif align == "center":
+ x_height = (x2 - x1) / 2
+ # x-offsets, y-offsets
+ assert_allclose([child.get_offset() for child in vpacker.get_children()],
+ [(px + x_height, py), (px, py - y2)])
+
+
+def test_paddedbox_default_values():
+ # smoke test paddedbox for correct default value
+ fig, ax = plt.subplots()
+ at = AnchoredText("foo", 'upper left')
+ pb = PaddedBox(at, patch_attrs={'facecolor': 'r'}, draw_frame=True)
+ ax.add_artist(pb)
+ fig.draw_without_rendering()
+
+
+def test_annotationbbox_properties():
+ ab = AnnotationBbox(DrawingArea(20, 20, 0, 0, clip=True), (0.5, 0.5),
+ xycoords='data')
+ assert ab.xyann == (0.5, 0.5) # xy if xybox not given
+ assert ab.anncoords == 'data' # xycoords if boxcoords not given
+
+ ab = AnnotationBbox(DrawingArea(20, 20, 0, 0, clip=True), (0.5, 0.5),
+ xybox=(-0.2, 0.4), xycoords='data',
+ boxcoords='axes fraction')
+ assert ab.xyann == (-0.2, 0.4) # xybox if given
+ assert ab.anncoords == 'axes fraction' # boxcoords if given
+
+
+def test_textarea_properties():
+ ta = TextArea('Foo')
+ assert ta.get_text() == 'Foo'
+ assert not ta.get_multilinebaseline()
+
+ ta.set_text('Bar')
+ ta.set_multilinebaseline(True)
+ assert ta.get_text() == 'Bar'
+ assert ta.get_multilinebaseline()
+
+
+@check_figures_equal(extensions=['png'])
+def test_textarea_set_text(fig_test, fig_ref):
+ ax_ref = fig_ref.add_subplot()
+ text0 = AnchoredText("Foo", "upper left")
+ ax_ref.add_artist(text0)
+
+ ax_test = fig_test.add_subplot()
+ text1 = AnchoredText("Bar", "upper left")
+ ax_test.add_artist(text1)
+ text1.txt.set_text("Foo")
+
+
+@image_comparison(['paddedbox.png'], remove_text=True, style='mpl20')
+def test_paddedbox():
+ fig, ax = plt.subplots()
+
+ ta = TextArea("foo")
+ pb = PaddedBox(ta, pad=5, patch_attrs={'facecolor': 'r'}, draw_frame=True)
+ ab = AnchoredOffsetbox('upper left', child=pb)
+ ax.add_artist(ab)
+
+ ta = TextArea("bar")
+ pb = PaddedBox(ta, pad=10, patch_attrs={'facecolor': 'b'})
+ ab = AnchoredOffsetbox('upper right', child=pb)
+ ax.add_artist(ab)
+
+ ta = TextArea("foobar")
+ pb = PaddedBox(ta, pad=15, draw_frame=True)
+ ab = AnchoredOffsetbox('lower right', child=pb)
+ ax.add_artist(ab)
+
+
+def test_remove_draggable():
+ fig, ax = plt.subplots()
+ an = ax.annotate("foo", (.5, .5))
+ an.draggable(True)
+ an.remove()
+ MouseEvent("button_release_event", fig.canvas, 1, 1)._process()
+
+
+def test_draggable_in_subfigure():
+ fig = plt.figure()
+ # Put annotation at lower left corner to make it easily pickable below.
+ ann = fig.subfigures().add_axes([0, 0, 1, 1]).annotate("foo", (0, 0))
+ ann.draggable(True)
+ fig.canvas.draw() # Texts are non-pickable until the first draw.
+ MouseEvent("button_press_event", fig.canvas, 1, 1)._process()
+ assert ann._draggable.got_artist
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_path.py b/lib/python3.12/site-packages/matplotlib/tests/test_path.py
new file mode 100644
index 0000000000000000000000000000000000000000..21f4c33794af64371c6b026f81411daf8f8bec98
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_path.py
@@ -0,0 +1,624 @@
+import platform
+import re
+
+import numpy as np
+
+from numpy.testing import assert_array_equal
+import pytest
+
+from matplotlib import patches
+from matplotlib.path import Path
+from matplotlib.patches import Polygon
+from matplotlib.testing.decorators import image_comparison
+import matplotlib.pyplot as plt
+from matplotlib import transforms
+from matplotlib.backend_bases import MouseEvent
+
+
+def test_empty_closed_path():
+ path = Path(np.zeros((0, 2)), closed=True)
+ assert path.vertices.shape == (0, 2)
+ assert path.codes is None
+ assert_array_equal(path.get_extents().extents,
+ transforms.Bbox.null().extents)
+
+
+def test_readonly_path():
+ path = Path.unit_circle()
+
+ def modify_vertices():
+ path.vertices = path.vertices * 2.0
+
+ with pytest.raises(AttributeError):
+ modify_vertices()
+
+
+def test_path_exceptions():
+ bad_verts1 = np.arange(12).reshape(4, 3)
+ with pytest.raises(ValueError,
+ match=re.escape(f'has shape {bad_verts1.shape}')):
+ Path(bad_verts1)
+
+ bad_verts2 = np.arange(12).reshape(2, 3, 2)
+ with pytest.raises(ValueError,
+ match=re.escape(f'has shape {bad_verts2.shape}')):
+ Path(bad_verts2)
+
+ good_verts = np.arange(12).reshape(6, 2)
+ bad_codes = np.arange(2)
+ msg = re.escape(f"Your vertices have shape {good_verts.shape} "
+ f"but your codes have shape {bad_codes.shape}")
+ with pytest.raises(ValueError, match=msg):
+ Path(good_verts, bad_codes)
+
+
+def test_point_in_path():
+ # Test #1787
+ path = Path._create_closed([(0, 0), (0, 1), (1, 1), (1, 0)])
+ points = [(0.5, 0.5), (1.5, 0.5)]
+ ret = path.contains_points(points)
+ assert ret.dtype == 'bool'
+ np.testing.assert_equal(ret, [True, False])
+
+
+@pytest.mark.parametrize(
+ "other_path, inside, inverted_inside",
+ [(Path([(0.25, 0.25), (0.25, 0.75), (0.75, 0.75), (0.75, 0.25), (0.25, 0.25)],
+ closed=True), True, False),
+ (Path([(-0.25, -0.25), (-0.25, 1.75), (1.75, 1.75), (1.75, -0.25), (-0.25, -0.25)],
+ closed=True), False, True),
+ (Path([(-0.25, -0.25), (-0.25, 1.75), (0.5, 0.5),
+ (1.75, 1.75), (1.75, -0.25), (-0.25, -0.25)],
+ closed=True), False, False),
+ (Path([(0.25, 0.25), (0.25, 1.25), (1.25, 1.25), (1.25, 0.25), (0.25, 0.25)],
+ closed=True), False, False),
+ (Path([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)], closed=True), False, False),
+ (Path([(2, 2), (2, 3), (3, 3), (3, 2), (2, 2)], closed=True), False, False)])
+def test_contains_path(other_path, inside, inverted_inside):
+ path = Path([(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)], closed=True)
+ assert path.contains_path(other_path) is inside
+ assert other_path.contains_path(path) is inverted_inside
+
+
+def test_contains_points_negative_radius():
+ path = Path.unit_circle()
+
+ points = [(0.0, 0.0), (1.25, 0.0), (0.9, 0.9)]
+ result = path.contains_points(points, radius=-0.5)
+ np.testing.assert_equal(result, [True, False, False])
+
+
+_test_paths = [
+ # interior extrema determine extents and degenerate derivative
+ Path([[0, 0], [1, 0], [1, 1], [0, 1]],
+ [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]),
+ # a quadratic curve
+ Path([[0, 0], [0, 1], [1, 0]], [Path.MOVETO, Path.CURVE3, Path.CURVE3]),
+ # a linear curve, degenerate vertically
+ Path([[0, 1], [1, 1]], [Path.MOVETO, Path.LINETO]),
+ # a point
+ Path([[1, 2]], [Path.MOVETO]),
+]
+
+
+_test_path_extents = [(0., 0., 0.75, 1.), (0., 0., 1., 0.5), (0., 1., 1., 1.),
+ (1., 2., 1., 2.)]
+
+
+@pytest.mark.parametrize('path, extents', zip(_test_paths, _test_path_extents))
+def test_exact_extents(path, extents):
+ # notice that if we just looked at the control points to get the bounding
+ # box of each curve, we would get the wrong answers. For example, for
+ # hard_curve = Path([[0, 0], [1, 0], [1, 1], [0, 1]],
+ # [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4])
+ # we would get that the extents area (0, 0, 1, 1). This code takes into
+ # account the curved part of the path, which does not typically extend all
+ # the way out to the control points.
+ # Note that counterintuitively, path.get_extents() returns a Bbox, so we
+ # have to get that Bbox's `.extents`.
+ assert np.all(path.get_extents().extents == extents)
+
+
+@pytest.mark.parametrize('ignored_code', [Path.CLOSEPOLY, Path.STOP])
+def test_extents_with_ignored_codes(ignored_code):
+ # Check that STOP and CLOSEPOLY points are ignored when calculating extents
+ # of a path with only straight lines
+ path = Path([[0, 0],
+ [1, 1],
+ [2, 2]], [Path.MOVETO, Path.MOVETO, ignored_code])
+ assert np.all(path.get_extents().extents == (0., 0., 1., 1.))
+
+
+def test_point_in_path_nan():
+ box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
+ p = Path(box)
+ test = np.array([[np.nan, 0.5]])
+ contains = p.contains_points(test)
+ assert len(contains) == 1
+ assert not contains[0]
+
+
+def test_nonlinear_containment():
+ fig, ax = plt.subplots()
+ ax.set(xscale="log", ylim=(0, 1))
+ polygon = ax.axvspan(1, 10)
+ assert polygon.get_path().contains_point(
+ ax.transData.transform((5, .5)), polygon.get_transform())
+ assert not polygon.get_path().contains_point(
+ ax.transData.transform((.5, .5)), polygon.get_transform())
+ assert not polygon.get_path().contains_point(
+ ax.transData.transform((50, .5)), polygon.get_transform())
+
+
+@image_comparison(['arrow_contains_point.png'], remove_text=True, style='mpl20',
+ tol=0 if platform.machine() == 'x86_64' else 0.027)
+def test_arrow_contains_point():
+ # fix bug (#8384)
+ fig, ax = plt.subplots()
+ ax.set_xlim((0, 2))
+ ax.set_ylim((0, 2))
+
+ # create an arrow with Curve style
+ arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75),
+ arrowstyle='->',
+ mutation_scale=40)
+ ax.add_patch(arrow)
+ # create an arrow with Bracket style
+ arrow1 = patches.FancyArrowPatch((0.5, 1), (1.5, 1.25),
+ arrowstyle=']-[',
+ mutation_scale=40)
+ ax.add_patch(arrow1)
+ # create an arrow with other arrow style
+ arrow2 = patches.FancyArrowPatch((0.5, 1.5), (1.5, 1.75),
+ arrowstyle='fancy',
+ fill=False,
+ mutation_scale=40)
+ ax.add_patch(arrow2)
+ patches_list = [arrow, arrow1, arrow2]
+
+ # generate some points
+ X, Y = np.meshgrid(np.arange(0, 2, 0.1),
+ np.arange(0, 2, 0.1))
+ for k, (x, y) in enumerate(zip(X.ravel(), Y.ravel())):
+ xdisp, ydisp = ax.transData.transform([x, y])
+ event = MouseEvent('button_press_event', fig.canvas, xdisp, ydisp)
+ for m, patch in enumerate(patches_list):
+ # set the points to red only if the arrow contains the point
+ inside, res = patch.contains(event)
+ if inside:
+ ax.scatter(x, y, s=5, c="r")
+
+
+@image_comparison(['path_clipping.svg'], remove_text=True)
+def test_path_clipping():
+ fig = plt.figure(figsize=(6.0, 6.2))
+
+ for i, xy in enumerate([
+ [(200, 200), (200, 350), (400, 350), (400, 200)],
+ [(200, 200), (200, 350), (400, 350), (400, 100)],
+ [(200, 100), (200, 350), (400, 350), (400, 100)],
+ [(200, 100), (200, 415), (400, 350), (400, 100)],
+ [(200, 100), (200, 415), (400, 415), (400, 100)],
+ [(200, 415), (400, 415), (400, 100), (200, 100)],
+ [(400, 415), (400, 100), (200, 100), (200, 415)]]):
+ ax = fig.add_subplot(4, 2, i+1)
+ bbox = [0, 140, 640, 260]
+ ax.set_xlim(bbox[0], bbox[0] + bbox[2])
+ ax.set_ylim(bbox[1], bbox[1] + bbox[3])
+ ax.add_patch(Polygon(
+ xy, facecolor='none', edgecolor='red', closed=True))
+
+
+@image_comparison(['semi_log_with_zero.png'], style='mpl20')
+def test_log_transform_with_zero():
+ x = np.arange(-10, 10)
+ y = (1.0 - 1.0/(x**2+1))**20
+
+ fig, ax = plt.subplots()
+ ax.semilogy(x, y, "-o", lw=15, markeredgecolor='k')
+ ax.set_ylim(1e-7, 1)
+ ax.grid(True)
+
+
+def test_make_compound_path_empty():
+ # We should be able to make a compound path with no arguments.
+ # This makes it easier to write generic path based code.
+ empty = Path.make_compound_path()
+ assert empty.vertices.shape == (0, 2)
+ r2 = Path.make_compound_path(empty, empty)
+ assert r2.vertices.shape == (0, 2)
+ assert r2.codes.shape == (0,)
+ r3 = Path.make_compound_path(Path([(0, 0)]), empty)
+ assert r3.vertices.shape == (1, 2)
+ assert r3.codes.shape == (1,)
+
+
+def test_make_compound_path_stops():
+ zero = [0, 0]
+ paths = 3*[Path([zero, zero], [Path.MOVETO, Path.STOP])]
+ compound_path = Path.make_compound_path(*paths)
+ # the choice to not preserve the terminal STOP is arbitrary, but
+ # documented, so we test that it is in fact respected here
+ assert np.sum(compound_path.codes == Path.STOP) == 0
+
+
+@image_comparison(['xkcd.png'], remove_text=True)
+def test_xkcd():
+ np.random.seed(0)
+
+ x = np.linspace(0, 2 * np.pi, 100)
+ y = np.sin(x)
+
+ with plt.xkcd():
+ fig, ax = plt.subplots()
+ ax.plot(x, y)
+
+
+@image_comparison(['xkcd_marker.png'], remove_text=True)
+def test_xkcd_marker():
+ np.random.seed(0)
+
+ x = np.linspace(0, 5, 8)
+ y1 = x
+ y2 = 5 - x
+ y3 = 2.5 * np.ones(8)
+
+ with plt.xkcd():
+ fig, ax = plt.subplots()
+ ax.plot(x, y1, '+', ms=10)
+ ax.plot(x, y2, 'o', ms=10)
+ ax.plot(x, y3, '^', ms=10)
+
+
+@image_comparison(['marker_paths.pdf'], remove_text=True)
+def test_marker_paths_pdf():
+ N = 7
+
+ plt.errorbar(np.arange(N),
+ np.ones(N) + 4,
+ np.ones(N))
+ plt.xlim(-1, N)
+ plt.ylim(-1, 7)
+
+
+@image_comparison(['nan_path'], style='default', remove_text=True,
+ extensions=['pdf', 'svg', 'eps', 'png'],
+ tol=0 if platform.machine() == 'x86_64' else 0.009)
+def test_nan_isolated_points():
+
+ y0 = [0, np.nan, 2, np.nan, 4, 5, 6]
+ y1 = [np.nan, 7, np.nan, 9, 10, np.nan, 12]
+
+ fig, ax = plt.subplots()
+
+ ax.plot(y0, '-o')
+ ax.plot(y1, '-o')
+
+
+def test_path_no_doubled_point_in_to_polygon():
+ hand = np.array(
+ [[1.64516129, 1.16145833],
+ [1.64516129, 1.59375],
+ [1.35080645, 1.921875],
+ [1.375, 2.18229167],
+ [1.68548387, 1.9375],
+ [1.60887097, 2.55208333],
+ [1.68548387, 2.69791667],
+ [1.76209677, 2.56770833],
+ [1.83064516, 1.97395833],
+ [1.89516129, 2.75],
+ [1.9516129, 2.84895833],
+ [2.01209677, 2.76041667],
+ [1.99193548, 1.99479167],
+ [2.11290323, 2.63020833],
+ [2.2016129, 2.734375],
+ [2.25403226, 2.60416667],
+ [2.14919355, 1.953125],
+ [2.30645161, 2.36979167],
+ [2.39112903, 2.36979167],
+ [2.41532258, 2.1875],
+ [2.1733871, 1.703125],
+ [2.07782258, 1.16666667]])
+
+ (r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5)
+
+ poly = Path(np.vstack((hand[:, 1], hand[:, 0])).T, closed=True)
+ clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
+ poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]
+
+ assert np.all(poly_clipped[-2] != poly_clipped[-1])
+ assert np.all(poly_clipped[-1] == poly_clipped[0])
+
+
+def test_path_to_polygons():
+ data = [[10, 10], [20, 20]]
+ p = Path(data)
+
+ assert_array_equal(p.to_polygons(width=40, height=40), [])
+ assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),
+ [data])
+ assert_array_equal(p.to_polygons(), [])
+ assert_array_equal(p.to_polygons(closed_only=False), [data])
+
+ data = [[10, 10], [20, 20], [30, 30]]
+ closed_data = [[10, 10], [20, 20], [30, 30], [10, 10]]
+ p = Path(data)
+
+ assert_array_equal(p.to_polygons(width=40, height=40), [closed_data])
+ assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),
+ [data])
+ assert_array_equal(p.to_polygons(), [closed_data])
+ assert_array_equal(p.to_polygons(closed_only=False), [data])
+
+
+def test_path_deepcopy():
+ # Should not raise any error
+ verts = [[0, 0], [1, 1]]
+ codes = [Path.MOVETO, Path.LINETO]
+ path1 = Path(verts)
+ path2 = Path(verts, codes)
+ path1_copy = path1.deepcopy()
+ path2_copy = path2.deepcopy()
+ assert path1 is not path1_copy
+ assert path1.vertices is not path1_copy.vertices
+ assert path2 is not path2_copy
+ assert path2.vertices is not path2_copy.vertices
+ assert path2.codes is not path2_copy.codes
+
+
+def test_path_shallowcopy():
+ # Should not raise any error
+ verts = [[0, 0], [1, 1]]
+ codes = [Path.MOVETO, Path.LINETO]
+ path1 = Path(verts)
+ path2 = Path(verts, codes)
+ path1_copy = path1.copy()
+ path2_copy = path2.copy()
+ assert path1 is not path1_copy
+ assert path1.vertices is path1_copy.vertices
+ assert path2 is not path2_copy
+ assert path2.vertices is path2_copy.vertices
+ assert path2.codes is path2_copy.codes
+
+
+@pytest.mark.parametrize('phi', np.concatenate([
+ np.array([0, 15, 30, 45, 60, 75, 90, 105, 120, 135]) + delta
+ for delta in [-1, 0, 1]]))
+def test_path_intersect_path(phi):
+ # test for the range of intersection angles
+ eps_array = [1e-5, 1e-8, 1e-10, 1e-12]
+
+ transform = transforms.Affine2D().rotate(np.deg2rad(phi))
+
+ # a and b intersect at angle phi
+ a = Path([(-2, 0), (2, 0)])
+ b = transform.transform_path(a)
+ assert a.intersects_path(b) and b.intersects_path(a)
+
+ # a and b touch at angle phi at (0, 0)
+ a = Path([(0, 0), (2, 0)])
+ b = transform.transform_path(a)
+ assert a.intersects_path(b) and b.intersects_path(a)
+
+ # a and b are orthogonal and intersect at (0, 3)
+ a = transform.transform_path(Path([(0, 1), (0, 3)]))
+ b = transform.transform_path(Path([(1, 3), (0, 3)]))
+ assert a.intersects_path(b) and b.intersects_path(a)
+
+ # a and b are collinear and intersect at (0, 3)
+ a = transform.transform_path(Path([(0, 1), (0, 3)]))
+ b = transform.transform_path(Path([(0, 5), (0, 3)]))
+ assert a.intersects_path(b) and b.intersects_path(a)
+
+ # self-intersect
+ assert a.intersects_path(a)
+
+ # a contains b
+ a = transform.transform_path(Path([(0, 0), (5, 5)]))
+ b = transform.transform_path(Path([(1, 1), (3, 3)]))
+ assert a.intersects_path(b) and b.intersects_path(a)
+
+ # a and b are collinear but do not intersect
+ a = transform.transform_path(Path([(0, 1), (0, 5)]))
+ b = transform.transform_path(Path([(3, 0), (3, 3)]))
+ assert not a.intersects_path(b) and not b.intersects_path(a)
+
+ # a and b are on the same line but do not intersect
+ a = transform.transform_path(Path([(0, 1), (0, 5)]))
+ b = transform.transform_path(Path([(0, 6), (0, 7)]))
+ assert not a.intersects_path(b) and not b.intersects_path(a)
+
+ # Note: 1e-13 is the absolute tolerance error used for
+ # `isclose` function from src/_path.h
+
+ # a and b are parallel but do not touch
+ for eps in eps_array:
+ a = transform.transform_path(Path([(0, 1), (0, 5)]))
+ b = transform.transform_path(Path([(0 + eps, 1), (0 + eps, 5)]))
+ assert not a.intersects_path(b) and not b.intersects_path(a)
+
+ # a and b are on the same line but do not intersect (really close)
+ for eps in eps_array:
+ a = transform.transform_path(Path([(0, 1), (0, 5)]))
+ b = transform.transform_path(Path([(0, 5 + eps), (0, 7)]))
+ assert not a.intersects_path(b) and not b.intersects_path(a)
+
+ # a and b are on the same line and intersect (really close)
+ for eps in eps_array:
+ a = transform.transform_path(Path([(0, 1), (0, 5)]))
+ b = transform.transform_path(Path([(0, 5 - eps), (0, 7)]))
+ assert a.intersects_path(b) and b.intersects_path(a)
+
+ # b is the same as a but with an extra point
+ a = transform.transform_path(Path([(0, 1), (0, 5)]))
+ b = transform.transform_path(Path([(0, 1), (0, 2), (0, 5)]))
+ assert a.intersects_path(b) and b.intersects_path(a)
+
+ # a and b are collinear but do not intersect
+ a = transform.transform_path(Path([(1, -1), (0, -1)]))
+ b = transform.transform_path(Path([(0, 1), (0.9, 1)]))
+ assert not a.intersects_path(b) and not b.intersects_path(a)
+
+ # a and b are collinear but do not intersect
+ a = transform.transform_path(Path([(0., -5.), (1., -5.)]))
+ b = transform.transform_path(Path([(1., 5.), (0., 5.)]))
+ assert not a.intersects_path(b) and not b.intersects_path(a)
+
+
+@pytest.mark.parametrize('offset', range(-720, 361, 45))
+def test_full_arc(offset):
+ low = offset
+ high = 360 + offset
+
+ path = Path.arc(low, high)
+ mins = np.min(path.vertices, axis=0)
+ maxs = np.max(path.vertices, axis=0)
+ np.testing.assert_allclose(mins, -1)
+ np.testing.assert_allclose(maxs, 1)
+
+
+def test_disjoint_zero_length_segment():
+ this_path = Path(
+ np.array([
+ [824.85064295, 2056.26489203],
+ [861.69033931, 2041.00539016],
+ [868.57864109, 2057.63522175],
+ [831.73894473, 2072.89472361],
+ [824.85064295, 2056.26489203]]),
+ np.array([1, 2, 2, 2, 79], dtype=Path.code_type))
+
+ outline_path = Path(
+ np.array([
+ [859.91051028, 2165.38461538],
+ [859.06772495, 2149.30331334],
+ [859.06772495, 2181.46591743],
+ [859.91051028, 2165.38461538],
+ [859.91051028, 2165.38461538]]),
+ np.array([1, 2, 2, 2, 2],
+ dtype=Path.code_type))
+
+ assert not outline_path.intersects_path(this_path)
+ assert not this_path.intersects_path(outline_path)
+
+
+def test_intersect_zero_length_segment():
+ this_path = Path(
+ np.array([
+ [0, 0],
+ [1, 1],
+ ]))
+
+ outline_path = Path(
+ np.array([
+ [1, 0],
+ [.5, .5],
+ [.5, .5],
+ [0, 1],
+ ]))
+
+ assert outline_path.intersects_path(this_path)
+ assert this_path.intersects_path(outline_path)
+
+
+def test_cleanup_closepoly():
+ # if the first connected component of a Path ends in a CLOSEPOLY, but that
+ # component contains a NaN, then Path.cleaned should ignore not just the
+ # control points but also the CLOSEPOLY, since it has nowhere valid to
+ # point.
+ paths = [
+ Path([[np.nan, np.nan], [np.nan, np.nan]],
+ [Path.MOVETO, Path.CLOSEPOLY]),
+ # we trigger a different path in the C++ code if we don't pass any
+ # codes explicitly, so we must also make sure that this works
+ Path([[np.nan, np.nan], [np.nan, np.nan]]),
+ # we should also make sure that this cleanup works if there's some
+ # multi-vertex curves
+ Path([[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan],
+ [np.nan, np.nan]],
+ [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY])
+ ]
+ for p in paths:
+ cleaned = p.cleaned(remove_nans=True)
+ assert len(cleaned) == 1
+ assert cleaned.codes[0] == Path.STOP
+
+
+def test_interpolated_moveto():
+ # Initial path has two subpaths with two LINETOs each
+ vertices = np.array([[0, 0],
+ [0, 1],
+ [1, 2],
+ [4, 4],
+ [4, 5],
+ [5, 5]])
+ codes = [Path.MOVETO, Path.LINETO, Path.LINETO] * 2
+
+ path = Path(vertices, codes)
+ result = path.interpolated(3)
+
+ # Result should have two subpaths with six LINETOs each
+ expected_subpath_codes = [Path.MOVETO] + [Path.LINETO] * 6
+ np.testing.assert_array_equal(result.codes, expected_subpath_codes * 2)
+
+
+def test_interpolated_closepoly():
+ codes = [Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]
+ vertices = [(4, 3), (5, 4), (5, 3), (0, 0)]
+
+ path = Path(vertices, codes)
+ result = path.interpolated(2)
+
+ expected_vertices = np.array([[4, 3],
+ [4.5, 3.5],
+ [5, 4],
+ [5, 3.5],
+ [5, 3],
+ [4.5, 3],
+ [4, 3]])
+ expected_codes = [Path.MOVETO] + [Path.LINETO]*5 + [Path.CLOSEPOLY]
+
+ np.testing.assert_allclose(result.vertices, expected_vertices)
+ np.testing.assert_array_equal(result.codes, expected_codes)
+
+ # Usually closepoly is the last vertex but does not have to be.
+ codes += [Path.LINETO]
+ vertices += [(2, 1)]
+
+ path = Path(vertices, codes)
+ result = path.interpolated(2)
+
+ extra_expected_vertices = np.array([[3, 2],
+ [2, 1]])
+ expected_vertices = np.concatenate([expected_vertices, extra_expected_vertices])
+
+ expected_codes += [Path.LINETO] * 2
+
+ np.testing.assert_allclose(result.vertices, expected_vertices)
+ np.testing.assert_array_equal(result.codes, expected_codes)
+
+
+def test_interpolated_moveto_closepoly():
+ # Initial path has two closed subpaths
+ codes = ([Path.MOVETO] + [Path.LINETO]*2 + [Path.CLOSEPOLY]) * 2
+ vertices = [(4, 3), (5, 4), (5, 3), (0, 0), (8, 6), (10, 8), (10, 6), (0, 0)]
+
+ path = Path(vertices, codes)
+ result = path.interpolated(2)
+
+ expected_vertices1 = np.array([[4, 3],
+ [4.5, 3.5],
+ [5, 4],
+ [5, 3.5],
+ [5, 3],
+ [4.5, 3],
+ [4, 3]])
+ expected_vertices = np.concatenate([expected_vertices1, expected_vertices1 * 2])
+ expected_codes = ([Path.MOVETO] + [Path.LINETO]*5 + [Path.CLOSEPOLY]) * 2
+
+ np.testing.assert_allclose(result.vertices, expected_vertices)
+ np.testing.assert_array_equal(result.codes, expected_codes)
+
+
+def test_interpolated_empty_path():
+ path = Path(np.zeros((0, 2)))
+ assert path.interpolated(42) is path
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_patheffects.py b/lib/python3.12/site-packages/matplotlib/tests/test_patheffects.py
new file mode 100644
index 0000000000000000000000000000000000000000..6c89d1c531e0c7e7504b30fefbd587b971ca0436
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_patheffects.py
@@ -0,0 +1,217 @@
+import platform
+
+import numpy as np
+
+from matplotlib.testing.decorators import image_comparison
+import matplotlib.pyplot as plt
+import matplotlib.patheffects as path_effects
+from matplotlib.path import Path
+import matplotlib.patches as patches
+from matplotlib.backend_bases import RendererBase
+from matplotlib.patheffects import PathEffectRenderer
+
+
+@image_comparison(['patheffect1'], remove_text=True)
+def test_patheffect1():
+ ax1 = plt.subplot()
+ ax1.imshow([[1, 2], [2, 3]])
+ txt = ax1.annotate("test", (1., 1.), (0., 0),
+ arrowprops=dict(arrowstyle="->",
+ connectionstyle="angle3", lw=2),
+ size=20, ha="center",
+ path_effects=[path_effects.withStroke(linewidth=3,
+ foreground="w")])
+ txt.arrow_patch.set_path_effects([path_effects.Stroke(linewidth=5,
+ foreground="w"),
+ path_effects.Normal()])
+
+ pe = [path_effects.withStroke(linewidth=3, foreground="w")]
+ ax1.grid(True, linestyle="-", path_effects=pe)
+
+
+@image_comparison(['patheffect2'], remove_text=True, style='mpl20',
+ tol=0 if platform.machine() == 'x86_64' else 0.06)
+def test_patheffect2():
+
+ ax2 = plt.subplot()
+ arr = np.arange(25).reshape((5, 5))
+ ax2.imshow(arr, interpolation='nearest')
+ cntr = ax2.contour(arr, colors="k")
+ cntr.set(path_effects=[path_effects.withStroke(linewidth=3, foreground="w")])
+
+ clbls = ax2.clabel(cntr, fmt="%2.0f", use_clabeltext=True)
+ plt.setp(clbls,
+ path_effects=[path_effects.withStroke(linewidth=3,
+ foreground="w")])
+
+
+@image_comparison(['patheffect3'],
+ tol=0 if platform.machine() == 'x86_64' else 0.019)
+def test_patheffect3():
+ p1, = plt.plot([1, 3, 5, 4, 3], 'o-b', lw=4)
+ p1.set_path_effects([path_effects.SimpleLineShadow(),
+ path_effects.Normal()])
+ plt.title(
+ r'testing$^{123}$',
+ path_effects=[path_effects.withStroke(linewidth=1, foreground="r")])
+ leg = plt.legend([p1], [r'Line 1$^2$'], fancybox=True, loc='upper left')
+ leg.legendPatch.set_path_effects([path_effects.withSimplePatchShadow()])
+
+ text = plt.text(2, 3, 'Drop test', color='white',
+ bbox={'boxstyle': 'circle,pad=0.1', 'color': 'red'})
+ pe = [path_effects.Stroke(linewidth=3.75, foreground='k'),
+ path_effects.withSimplePatchShadow((6, -3), shadow_rgbFace='blue')]
+ text.set_path_effects(pe)
+ text.get_bbox_patch().set_path_effects(pe)
+
+ pe = [path_effects.PathPatchEffect(offset=(4, -4), hatch='xxxx',
+ facecolor='gray'),
+ path_effects.PathPatchEffect(edgecolor='white', facecolor='black',
+ lw=1.1)]
+
+ t = plt.gcf().text(0.02, 0.1, 'Hatch shadow', fontsize=75, weight=1000,
+ va='center')
+ t.set_path_effects(pe)
+
+
+@image_comparison(['stroked_text.png'])
+def test_patheffects_stroked_text():
+ text_chunks = [
+ 'A B C D E F G H I J K L',
+ 'M N O P Q R S T U V W',
+ 'X Y Z a b c d e f g h i j',
+ 'k l m n o p q r s t u v',
+ 'w x y z 0123456789',
+ r"!@#$%^&*()-=_+[]\;'",
+ ',./{}|:"<>?'
+ ]
+ font_size = 50
+
+ ax = plt.axes((0, 0, 1, 1))
+ for i, chunk in enumerate(text_chunks):
+ text = ax.text(x=0.01, y=(0.9 - i * 0.13), s=chunk,
+ fontdict={'ha': 'left', 'va': 'center',
+ 'size': font_size, 'color': 'white'})
+
+ text.set_path_effects([path_effects.Stroke(linewidth=font_size / 10,
+ foreground='black'),
+ path_effects.Normal()])
+
+ ax.set_xlim(0, 1)
+ ax.set_ylim(0, 1)
+ ax.axis('off')
+
+
+def test_PathEffect_points_to_pixels():
+ fig = plt.figure(dpi=150)
+ p1, = plt.plot(range(10))
+ p1.set_path_effects([path_effects.SimpleLineShadow(),
+ path_effects.Normal()])
+ renderer = fig.canvas.get_renderer()
+ pe_renderer = path_effects.PathEffectRenderer(
+ p1.get_path_effects(), renderer)
+ # Confirm that using a path effects renderer maintains point sizes
+ # appropriately. Otherwise rendered font would be the wrong size.
+ assert renderer.points_to_pixels(15) == pe_renderer.points_to_pixels(15)
+
+
+def test_SimplePatchShadow_offset():
+ pe = path_effects.SimplePatchShadow(offset=(4, 5))
+ assert pe._offset == (4, 5)
+
+
+@image_comparison(['collection'], tol=0.03, style='mpl20')
+def test_collection():
+ x, y = np.meshgrid(np.linspace(0, 10, 150), np.linspace(-5, 5, 100))
+ data = np.sin(x) + np.cos(y)
+ cs = plt.contour(data)
+ cs.set(path_effects=[
+ path_effects.PathPatchEffect(edgecolor='black', facecolor='none', linewidth=12),
+ path_effects.Stroke(linewidth=5)])
+ for text in plt.clabel(cs, colors='white'):
+ text.set_path_effects([path_effects.withStroke(foreground='k',
+ linewidth=3)])
+ text.set_bbox({'boxstyle': 'sawtooth', 'facecolor': 'none',
+ 'edgecolor': 'blue'})
+
+
+@image_comparison(['tickedstroke'], remove_text=True, extensions=['png'],
+ tol=0.22) # Increased tolerance due to fixed clipping.
+def test_tickedstroke():
+ fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(12, 4))
+ path = Path.unit_circle()
+ patch = patches.PathPatch(path, facecolor='none', lw=2, path_effects=[
+ path_effects.withTickedStroke(angle=-90, spacing=10,
+ length=1)])
+
+ ax1.add_patch(patch)
+ ax1.axis('equal')
+ ax1.set_xlim(-2, 2)
+ ax1.set_ylim(-2, 2)
+
+ ax2.plot([0, 1], [0, 1], label=' ',
+ path_effects=[path_effects.withTickedStroke(spacing=7,
+ angle=135)])
+ nx = 101
+ x = np.linspace(0.0, 1.0, nx)
+ y = 0.3 * np.sin(x * 8) + 0.4
+ ax2.plot(x, y, label=' ', path_effects=[path_effects.withTickedStroke()])
+
+ ax2.legend()
+
+ nx = 101
+ ny = 105
+
+ # Set up survey vectors
+ xvec = np.linspace(0.001, 4.0, nx)
+ yvec = np.linspace(0.001, 4.0, ny)
+
+ # Set up survey matrices. Design disk loading and gear ratio.
+ x1, x2 = np.meshgrid(xvec, yvec)
+
+ # Evaluate some stuff to plot
+ g1 = -(3 * x1 + x2 - 5.5)
+ g2 = -(x1 + 2 * x2 - 4)
+ g3 = .8 + x1 ** -3 - x2
+
+ cg1 = ax3.contour(x1, x2, g1, [0], colors=('k',))
+ cg1.set(path_effects=[path_effects.withTickedStroke(angle=135)])
+
+ cg2 = ax3.contour(x1, x2, g2, [0], colors=('r',))
+ cg2.set(path_effects=[path_effects.withTickedStroke(angle=60, length=2)])
+
+ cg3 = ax3.contour(x1, x2, g3, [0], colors=('b',))
+ cg3.set(path_effects=[path_effects.withTickedStroke(spacing=7)])
+
+ ax3.set_xlim(0, 4)
+ ax3.set_ylim(0, 4)
+
+
+@image_comparison(['spaces_and_newlines.png'], remove_text=True)
+def test_patheffects_spaces_and_newlines():
+ ax = plt.subplot()
+ s1 = " "
+ s2 = "\nNewline also causes problems"
+ text1 = ax.text(0.5, 0.75, s1, ha='center', va='center', size=20,
+ bbox={'color': 'salmon'})
+ text2 = ax.text(0.5, 0.25, s2, ha='center', va='center', size=20,
+ bbox={'color': 'thistle'})
+ text1.set_path_effects([path_effects.Normal()])
+ text2.set_path_effects([path_effects.Normal()])
+
+
+def test_patheffects_overridden_methods_open_close_group():
+ class CustomRenderer(RendererBase):
+ def __init__(self):
+ super().__init__()
+
+ def open_group(self, s, gid=None):
+ return "open_group overridden"
+
+ def close_group(self, s):
+ return "close_group overridden"
+
+ renderer = PathEffectRenderer([path_effects.Normal()], CustomRenderer())
+
+ assert renderer.open_group('s') == "open_group overridden"
+ assert renderer.close_group('s') == "close_group overridden"
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_pickle.py b/lib/python3.12/site-packages/matplotlib/tests/test_pickle.py
new file mode 100644
index 0000000000000000000000000000000000000000..eb47b26681018c922b92dc7364d6da1a4d54ed05
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_pickle.py
@@ -0,0 +1,339 @@
+from io import BytesIO
+import ast
+import os
+import sys
+import pickle
+import pickletools
+
+import numpy as np
+import pytest
+
+import matplotlib as mpl
+from matplotlib import cm
+from matplotlib.testing import subprocess_run_helper, is_ci_environment
+from matplotlib.testing.decorators import check_figures_equal
+from matplotlib.dates import rrulewrapper
+from matplotlib.lines import VertexSelector
+import matplotlib.pyplot as plt
+import matplotlib.transforms as mtransforms
+import matplotlib.figure as mfigure
+from mpl_toolkits.axes_grid1 import axes_divider, parasite_axes # type: ignore[import]
+
+
+def test_simple():
+ fig = plt.figure()
+ pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
+
+ ax = plt.subplot(121)
+ pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)
+
+ ax = plt.axes(projection='polar')
+ plt.plot(np.arange(10), label='foobar')
+ plt.legend()
+
+ pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)
+
+# ax = plt.subplot(121, projection='hammer')
+# pickle.dump(ax, BytesIO(), pickle.HIGHEST_PROTOCOL)
+
+ plt.figure()
+ plt.bar(x=np.arange(10), height=np.arange(10))
+ pickle.dump(plt.gca(), BytesIO(), pickle.HIGHEST_PROTOCOL)
+
+ fig = plt.figure()
+ ax = plt.axes()
+ plt.plot(np.arange(10))
+ ax.set_yscale('log')
+ pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
+
+
+def _generate_complete_test_figure(fig_ref):
+ fig_ref.set_size_inches((10, 6))
+ plt.figure(fig_ref)
+
+ plt.suptitle('Can you fit any more in a figure?')
+
+ # make some arbitrary data
+ x, y = np.arange(8), np.arange(10)
+ data = u = v = np.linspace(0, 10, 80).reshape(10, 8)
+ v = np.sin(v * -0.6)
+
+ # Ensure lists also pickle correctly.
+ plt.subplot(3, 3, 1)
+ plt.plot(list(range(10)))
+ plt.ylabel("hello")
+
+ plt.subplot(3, 3, 2)
+ plt.contourf(data, hatches=['//', 'ooo'])
+ plt.colorbar()
+
+ plt.subplot(3, 3, 3)
+ plt.pcolormesh(data)
+
+ plt.subplot(3, 3, 4)
+ plt.imshow(data)
+ plt.ylabel("hello\nworld!")
+
+ plt.subplot(3, 3, 5)
+ plt.pcolor(data)
+
+ ax = plt.subplot(3, 3, 6)
+ ax.set_xlim(0, 7)
+ ax.set_ylim(0, 9)
+ plt.streamplot(x, y, u, v)
+
+ ax = plt.subplot(3, 3, 7)
+ ax.set_xlim(0, 7)
+ ax.set_ylim(0, 9)
+ plt.quiver(x, y, u, v)
+
+ plt.subplot(3, 3, 8)
+ plt.scatter(x, x ** 2, label='$x^2$')
+ plt.legend(loc='upper left')
+
+ plt.subplot(3, 3, 9)
+ plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4, label='$-.5 x$')
+ plt.legend(draggable=True)
+
+ # Ensure subfigure parenting works.
+ subfigs = fig_ref.subfigures(2)
+ subfigs[0].subplots(1, 2)
+ subfigs[1].subplots(1, 2)
+
+ fig_ref.align_ylabels() # Test handling of _align_label_groups Groupers.
+
+
+@mpl.style.context("default")
+@check_figures_equal(extensions=["png"])
+def test_complete(fig_test, fig_ref):
+ _generate_complete_test_figure(fig_ref)
+ # plotting is done, now test its pickle-ability
+ pkl = pickle.dumps(fig_ref, pickle.HIGHEST_PROTOCOL)
+ # FigureCanvasAgg is picklable and GUI canvases are generally not, but there should
+ # be no reference to the canvas in the pickle stream in either case. In order to
+ # keep the test independent of GUI toolkits, run it with Agg and check that there's
+ # no reference to FigureCanvasAgg in the pickle stream.
+ assert "FigureCanvasAgg" not in [arg for op, arg, pos in pickletools.genops(pkl)]
+ loaded = pickle.loads(pkl)
+ loaded.canvas.draw()
+
+ fig_test.set_size_inches(loaded.get_size_inches())
+ fig_test.figimage(loaded.canvas.renderer.buffer_rgba())
+
+ plt.close(loaded)
+
+
+def _pickle_load_subprocess():
+ import os
+ import pickle
+
+ path = os.environ['PICKLE_FILE_PATH']
+
+ with open(path, 'rb') as blob:
+ fig = pickle.load(blob)
+
+ print(str(pickle.dumps(fig)))
+
+
+@mpl.style.context("default")
+@check_figures_equal(extensions=['png'])
+def test_pickle_load_from_subprocess(fig_test, fig_ref, tmp_path):
+ _generate_complete_test_figure(fig_ref)
+
+ fp = tmp_path / 'sinus.pickle'
+ assert not fp.exists()
+
+ with fp.open('wb') as file:
+ pickle.dump(fig_ref, file, pickle.HIGHEST_PROTOCOL)
+ assert fp.exists()
+
+ proc = subprocess_run_helper(
+ _pickle_load_subprocess,
+ timeout=60,
+ extra_env={
+ "PICKLE_FILE_PATH": str(fp),
+ "MPLBACKEND": "Agg",
+ # subprocess_run_helper will set SOURCE_DATE_EPOCH=0, so for a dirty tree,
+ # the version will have the date 19700101. As we aren't trying to test the
+ # version compatibility warning, force setuptools-scm to use the same
+ # version as us.
+ "SETUPTOOLS_SCM_PRETEND_VERSION_FOR_MATPLOTLIB": mpl.__version__,
+ },
+ )
+
+ loaded_fig = pickle.loads(ast.literal_eval(proc.stdout))
+
+ loaded_fig.canvas.draw()
+
+ fig_test.set_size_inches(loaded_fig.get_size_inches())
+ fig_test.figimage(loaded_fig.canvas.renderer.buffer_rgba())
+
+ plt.close(loaded_fig)
+
+
+def test_gcf():
+ fig = plt.figure("a label")
+ buf = BytesIO()
+ pickle.dump(fig, buf, pickle.HIGHEST_PROTOCOL)
+ plt.close("all")
+ assert plt._pylab_helpers.Gcf.figs == {} # No figures must be left.
+ fig = pickle.loads(buf.getbuffer())
+ assert plt._pylab_helpers.Gcf.figs != {} # A manager is there again.
+ assert fig.get_label() == "a label"
+
+
+def test_no_pyplot():
+ # tests pickle-ability of a figure not created with pyplot
+ from matplotlib.backends.backend_pdf import FigureCanvasPdf
+ fig = mfigure.Figure()
+ _ = FigureCanvasPdf(fig)
+ ax = fig.add_subplot(1, 1, 1)
+ ax.plot([1, 2, 3], [1, 2, 3])
+ pickle.dump(fig, BytesIO(), pickle.HIGHEST_PROTOCOL)
+
+
+def test_renderer():
+ from matplotlib.backends.backend_agg import RendererAgg
+ renderer = RendererAgg(10, 20, 30)
+ pickle.dump(renderer, BytesIO())
+
+
+def test_image():
+ # Prior to v1.4.0 the Image would cache data which was not picklable
+ # once it had been drawn.
+ from matplotlib.backends.backend_agg import new_figure_manager
+ manager = new_figure_manager(1000)
+ fig = manager.canvas.figure
+ ax = fig.add_subplot(1, 1, 1)
+ ax.imshow(np.arange(12).reshape(3, 4))
+ manager.canvas.draw()
+ pickle.dump(fig, BytesIO())
+
+
+def test_polar():
+ plt.subplot(polar=True)
+ fig = plt.gcf()
+ pf = pickle.dumps(fig)
+ pickle.loads(pf)
+ plt.draw()
+
+
+class TransformBlob:
+ def __init__(self):
+ self.identity = mtransforms.IdentityTransform()
+ self.identity2 = mtransforms.IdentityTransform()
+ # Force use of the more complex composition.
+ self.composite = mtransforms.CompositeGenericTransform(
+ self.identity,
+ self.identity2)
+ # Check parent -> child links of TransformWrapper.
+ self.wrapper = mtransforms.TransformWrapper(self.composite)
+ # Check child -> parent links of TransformWrapper.
+ self.composite2 = mtransforms.CompositeGenericTransform(
+ self.wrapper,
+ self.identity)
+
+
+def test_transform():
+ obj = TransformBlob()
+ pf = pickle.dumps(obj)
+ del obj
+
+ obj = pickle.loads(pf)
+ # Check parent -> child links of TransformWrapper.
+ assert obj.wrapper._child == obj.composite
+ # Check child -> parent links of TransformWrapper.
+ assert [v() for v in obj.wrapper._parents.values()] == [obj.composite2]
+ # Check input and output dimensions are set as expected.
+ assert obj.wrapper.input_dims == obj.composite.input_dims
+ assert obj.wrapper.output_dims == obj.composite.output_dims
+
+
+def test_rrulewrapper():
+ r = rrulewrapper(2)
+ try:
+ pickle.loads(pickle.dumps(r))
+ except RecursionError:
+ print('rrulewrapper pickling test failed')
+ raise
+
+
+def test_shared():
+ fig, axs = plt.subplots(2, sharex=True)
+ fig = pickle.loads(pickle.dumps(fig))
+ fig.axes[0].set_xlim(10, 20)
+ assert fig.axes[1].get_xlim() == (10, 20)
+
+
+def test_inset_and_secondary():
+ fig, ax = plt.subplots()
+ ax.inset_axes([.1, .1, .3, .3])
+ ax.secondary_xaxis("top", functions=(np.square, np.sqrt))
+ pickle.loads(pickle.dumps(fig))
+
+
+@pytest.mark.parametrize("cmap", cm._colormaps.values())
+def test_cmap(cmap):
+ pickle.dumps(cmap)
+
+
+def test_unpickle_canvas():
+ fig = mfigure.Figure()
+ assert fig.canvas is not None
+ out = BytesIO()
+ pickle.dump(fig, out)
+ out.seek(0)
+ fig2 = pickle.load(out)
+ assert fig2.canvas is not None
+
+
+def test_mpl_toolkits():
+ ax = parasite_axes.host_axes([0, 0, 1, 1])
+ axes_divider.make_axes_area_auto_adjustable(ax)
+ assert type(pickle.loads(pickle.dumps(ax))) == parasite_axes.HostAxes
+
+
+def test_standard_norm():
+ assert type(pickle.loads(pickle.dumps(mpl.colors.LogNorm()))) \
+ == mpl.colors.LogNorm
+
+
+def test_dynamic_norm():
+ logit_norm_instance = mpl.colors.make_norm_from_scale(
+ mpl.scale.LogitScale, mpl.colors.Normalize)()
+ assert type(pickle.loads(pickle.dumps(logit_norm_instance))) \
+ == type(logit_norm_instance)
+
+
+def test_vertexselector():
+ line, = plt.plot([0, 1], picker=True)
+ pickle.loads(pickle.dumps(VertexSelector(line)))
+
+
+def test_cycler():
+ ax = plt.figure().add_subplot()
+ ax.set_prop_cycle(c=["c", "m", "y", "k"])
+ ax.plot([1, 2])
+ ax = pickle.loads(pickle.dumps(ax))
+ l, = ax.plot([3, 4])
+ assert l.get_color() == "m"
+
+
+# Run under an interactive backend to test that we don't try to pickle the
+# (interactive and non-picklable) canvas.
+def _test_axeswidget_interactive():
+ ax = plt.figure().add_subplot()
+ pickle.dumps(mpl.widgets.Button(ax, "button"))
+
+
+@pytest.mark.xfail( # https://github.com/actions/setup-python/issues/649
+ ('TF_BUILD' in os.environ or 'GITHUB_ACTION' in os.environ) and
+ sys.platform == 'darwin' and sys.version_info[:2] < (3, 11),
+ reason='Tk version mismatch on Azure macOS CI'
+ )
+def test_axeswidget_interactive():
+ subprocess_run_helper(
+ _test_axeswidget_interactive,
+ timeout=120 if is_ci_environment() else 20,
+ extra_env={'MPLBACKEND': 'tkagg'}
+ )
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_png.py b/lib/python3.12/site-packages/matplotlib/tests/test_png.py
new file mode 100644
index 0000000000000000000000000000000000000000..9208c31df2bf7181ab003ee860543ebbf2975b52
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_png.py
@@ -0,0 +1,53 @@
+from io import BytesIO
+from pathlib import Path
+
+import pytest
+
+from matplotlib.testing.decorators import image_comparison
+from matplotlib import cm, pyplot as plt
+
+
+@image_comparison(['pngsuite.png'], tol=0.04)
+def test_pngsuite():
+ files = sorted(
+ (Path(__file__).parent / "baseline_images/pngsuite").glob("basn*.png"))
+
+ plt.figure(figsize=(len(files), 2))
+
+ for i, fname in enumerate(files):
+ data = plt.imread(fname)
+ cmap = None # use default colormap
+ if data.ndim == 2:
+ # keep grayscale images gray
+ cmap = cm.gray
+ # Using the old default data interpolation stage lets us
+ # continue to use the existing reference image
+ plt.imshow(data, extent=(i, i + 1, 0, 1), cmap=cmap,
+ interpolation_stage='data')
+
+ plt.gca().patch.set_facecolor("#ddffff")
+ plt.gca().set_xlim(0, len(files))
+
+
+def test_truncated_file(tmp_path):
+ path = tmp_path / 'test.png'
+ path_t = tmp_path / 'test_truncated.png'
+ plt.savefig(path)
+ with open(path, 'rb') as fin:
+ buf = fin.read()
+ with open(path_t, 'wb') as fout:
+ fout.write(buf[:20])
+
+ with pytest.raises(Exception):
+ plt.imread(path_t)
+
+
+def test_truncated_buffer():
+ b = BytesIO()
+ plt.savefig(b)
+ b.seek(0)
+ b2 = BytesIO(b.read(20))
+ b2.seek(0)
+
+ with pytest.raises(Exception):
+ plt.imread(b2)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_preprocess_data.py b/lib/python3.12/site-packages/matplotlib/tests/test_preprocess_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..0684f0dbb9aef3a7ee195a4e6de723e1e271478d
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_preprocess_data.py
@@ -0,0 +1,288 @@
+import re
+import sys
+
+import numpy as np
+import pytest
+
+from matplotlib import _preprocess_data
+from matplotlib.axes import Axes
+from matplotlib.testing import subprocess_run_for_testing
+from matplotlib.testing.decorators import check_figures_equal
+
+# Notes on testing the plotting functions itself
+# * the individual decorated plotting functions are tested in 'test_axes.py'
+# * that pyplot functions accept a data kwarg is only tested in
+# test_axes.test_pie_linewidth_0
+
+
+# this gets used in multiple tests, so define it here
+@_preprocess_data(replace_names=["x", "y"], label_namer="y")
+def plot_func(ax, x, y, ls="x", label=None, w="xyz"):
+ return f"x: {list(x)}, y: {list(y)}, ls: {ls}, w: {w}, label: {label}"
+
+
+all_funcs = [plot_func]
+all_func_ids = ['plot_func']
+
+
+def test_compiletime_checks():
+ """Test decorator invocations -> no replacements."""
+
+ def func(ax, x, y): pass
+ def func_args(ax, x, y, *args): pass
+ def func_kwargs(ax, x, y, **kwargs): pass
+ def func_no_ax_args(*args, **kwargs): pass
+
+ # this is ok
+ _preprocess_data(replace_names=["x", "y"])(func)
+ _preprocess_data(replace_names=["x", "y"])(func_kwargs)
+ # this has "enough" information to do all the replaces
+ _preprocess_data(replace_names=["x", "y"])(func_args)
+
+ # no positional_parameter_names but needed due to replaces
+ with pytest.raises(AssertionError):
+ # z is unknown
+ _preprocess_data(replace_names=["x", "y", "z"])(func_args)
+
+ # no replacements at all -> all ok...
+ _preprocess_data(replace_names=[], label_namer=None)(func)
+ _preprocess_data(replace_names=[], label_namer=None)(func_args)
+ _preprocess_data(replace_names=[], label_namer=None)(func_kwargs)
+ _preprocess_data(replace_names=[], label_namer=None)(func_no_ax_args)
+
+ # label namer is unknown
+ with pytest.raises(AssertionError):
+ _preprocess_data(label_namer="z")(func)
+
+ with pytest.raises(AssertionError):
+ _preprocess_data(label_namer="z")(func_args)
+
+
+@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)
+def test_function_call_without_data(func):
+ """Test without data -> no replacements."""
+ assert (func(None, "x", "y") ==
+ "x: ['x'], y: ['y'], ls: x, w: xyz, label: None")
+ assert (func(None, x="x", y="y") ==
+ "x: ['x'], y: ['y'], ls: x, w: xyz, label: None")
+ assert (func(None, "x", "y", label="") ==
+ "x: ['x'], y: ['y'], ls: x, w: xyz, label: ")
+ assert (func(None, "x", "y", label="text") ==
+ "x: ['x'], y: ['y'], ls: x, w: xyz, label: text")
+ assert (func(None, x="x", y="y", label="") ==
+ "x: ['x'], y: ['y'], ls: x, w: xyz, label: ")
+ assert (func(None, x="x", y="y", label="text") ==
+ "x: ['x'], y: ['y'], ls: x, w: xyz, label: text")
+
+
+@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)
+def test_function_call_with_dict_input(func):
+ """Tests with dict input, unpacking via preprocess_pipeline"""
+ data = {'a': 1, 'b': 2}
+ assert (func(None, data.keys(), data.values()) ==
+ "x: ['a', 'b'], y: [1, 2], ls: x, w: xyz, label: None")
+
+
+@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)
+def test_function_call_with_dict_data(func):
+ """Test with dict data -> label comes from the value of 'x' parameter."""
+ data = {"a": [1, 2], "b": [8, 9], "w": "NOT"}
+ assert (func(None, "a", "b", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")
+ assert (func(None, x="a", y="b", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")
+ assert (func(None, "a", "b", label="", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")
+ assert (func(None, "a", "b", label="text", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")
+ assert (func(None, x="a", y="b", label="", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")
+ assert (func(None, x="a", y="b", label="text", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")
+
+
+@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)
+def test_function_call_with_dict_data_not_in_data(func):
+ """Test the case that one var is not in data -> half replaces, half kept"""
+ data = {"a": [1, 2], "w": "NOT"}
+ assert (func(None, "a", "b", data=data) ==
+ "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b")
+ assert (func(None, x="a", y="b", data=data) ==
+ "x: [1, 2], y: ['b'], ls: x, w: xyz, label: b")
+ assert (func(None, "a", "b", label="", data=data) ==
+ "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ")
+ assert (func(None, "a", "b", label="text", data=data) ==
+ "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text")
+ assert (func(None, x="a", y="b", label="", data=data) ==
+ "x: [1, 2], y: ['b'], ls: x, w: xyz, label: ")
+ assert (func(None, x="a", y="b", label="text", data=data) ==
+ "x: [1, 2], y: ['b'], ls: x, w: xyz, label: text")
+
+
+@pytest.mark.parametrize('func', all_funcs, ids=all_func_ids)
+def test_function_call_with_pandas_data(func, pd):
+ """Test with pandas dataframe -> label comes from ``data["col"].name``."""
+ data = pd.DataFrame({"a": np.array([1, 2], dtype=np.int32),
+ "b": np.array([8, 9], dtype=np.int32),
+ "w": ["NOT", "NOT"]})
+
+ assert (func(None, "a", "b", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")
+ assert (func(None, x="a", y="b", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")
+ assert (func(None, "a", "b", label="", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")
+ assert (func(None, "a", "b", label="text", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")
+ assert (func(None, x="a", y="b", label="", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")
+ assert (func(None, x="a", y="b", label="text", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")
+
+
+def test_function_call_replace_all():
+ """Test without a "replace_names" argument, all vars should be replaced."""
+ data = {"a": [1, 2], "b": [8, 9], "x": "xyz"}
+
+ @_preprocess_data(label_namer="y")
+ def func_replace_all(ax, x, y, ls="x", label=None, w="NOT"):
+ return f"x: {list(x)}, y: {list(y)}, ls: {ls}, w: {w}, label: {label}"
+
+ assert (func_replace_all(None, "a", "b", w="x", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")
+ assert (func_replace_all(None, x="a", y="b", w="x", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: b")
+ assert (func_replace_all(None, "a", "b", w="x", label="", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")
+ assert (
+ func_replace_all(None, "a", "b", w="x", label="text", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")
+ assert (
+ func_replace_all(None, x="a", y="b", w="x", label="", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")
+ assert (
+ func_replace_all(None, x="a", y="b", w="x", label="text", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")
+
+
+def test_no_label_replacements():
+ """Test with "label_namer=None" -> no label replacement at all."""
+
+ @_preprocess_data(replace_names=["x", "y"], label_namer=None)
+ def func_no_label(ax, x, y, ls="x", label=None, w="xyz"):
+ return f"x: {list(x)}, y: {list(y)}, ls: {ls}, w: {w}, label: {label}"
+
+ data = {"a": [1, 2], "b": [8, 9], "w": "NOT"}
+ assert (func_no_label(None, "a", "b", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None")
+ assert (func_no_label(None, x="a", y="b", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: None")
+ assert (func_no_label(None, "a", "b", label="", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: ")
+ assert (func_no_label(None, "a", "b", label="text", data=data) ==
+ "x: [1, 2], y: [8, 9], ls: x, w: xyz, label: text")
+
+
+def test_more_args_than_pos_parameter():
+ @_preprocess_data(replace_names=["x", "y"], label_namer="y")
+ def func(ax, x, y, z=1):
+ pass
+
+ data = {"a": [1, 2], "b": [8, 9], "w": "NOT"}
+ with pytest.raises(TypeError):
+ func(None, "a", "b", "z", "z", data=data)
+
+
+def test_docstring_addition():
+ @_preprocess_data()
+ def funcy(ax, *args, **kwargs):
+ """
+ Parameters
+ ----------
+ data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+ """
+
+ assert re.search(r"all parameters also accept a string", funcy.__doc__)
+ assert not re.search(r"the following parameters", funcy.__doc__)
+
+ @_preprocess_data(replace_names=[])
+ def funcy(ax, x, y, z, bar=None):
+ """
+ Parameters
+ ----------
+ data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+ """
+
+ assert not re.search(r"all parameters also accept a string", funcy.__doc__)
+ assert not re.search(r"the following parameters", funcy.__doc__)
+
+ @_preprocess_data(replace_names=["bar"])
+ def funcy(ax, x, y, z, bar=None):
+ """
+ Parameters
+ ----------
+ data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+ """
+
+ assert not re.search(r"all parameters also accept a string", funcy.__doc__)
+ assert not re.search(r"the following parameters .*: \*bar\*\.",
+ funcy.__doc__)
+
+ @_preprocess_data(replace_names=["x", "t"])
+ def funcy(ax, x, y, z, t=None):
+ """
+ Parameters
+ ----------
+ data : indexable object, optional
+ DATA_PARAMETER_PLACEHOLDER
+ """
+
+ assert not re.search(r"all parameters also accept a string", funcy.__doc__)
+ assert not re.search(r"the following parameters .*: \*x\*, \*t\*\.",
+ funcy.__doc__)
+
+
+def test_data_parameter_replacement():
+ """
+ Test that the docstring contains the correct *data* parameter stub
+ for all methods that we run _preprocess_data() on.
+ """
+ program = (
+ "import logging; "
+ "logging.basicConfig(level=logging.DEBUG); "
+ "import matplotlib.pyplot as plt"
+ )
+ cmd = [sys.executable, "-c", program]
+ completed_proc = subprocess_run_for_testing(
+ cmd, text=True, capture_output=True
+ )
+ assert 'data parameter docstring error' not in completed_proc.stderr
+
+
+class TestPlotTypes:
+
+ plotters = [Axes.scatter, Axes.bar, Axes.plot]
+
+ @pytest.mark.parametrize('plotter', plotters)
+ @check_figures_equal(extensions=['png'])
+ def test_dict_unpack(self, plotter, fig_test, fig_ref):
+ x = [1, 2, 3]
+ y = [4, 5, 6]
+ ddict = dict(zip(x, y))
+
+ plotter(fig_test.subplots(),
+ ddict.keys(), ddict.values())
+ plotter(fig_ref.subplots(), x, y)
+
+ @pytest.mark.parametrize('plotter', plotters)
+ @check_figures_equal(extensions=['png'])
+ def test_data_kwarg(self, plotter, fig_test, fig_ref):
+ x = [1, 2, 3]
+ y = [4, 5, 6]
+
+ plotter(fig_test.subplots(), 'xval', 'yval',
+ data={'xval': x, 'yval': y})
+ plotter(fig_ref.subplots(), x, y)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_quiver.py b/lib/python3.12/site-packages/matplotlib/tests/test_quiver.py
new file mode 100644
index 0000000000000000000000000000000000000000..9cbe1639dadcfce03819e4c8853842091a0be2b2
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_quiver.py
@@ -0,0 +1,387 @@
+import platform
+import sys
+
+import numpy as np
+import pytest
+
+from matplotlib import pyplot as plt
+from matplotlib.testing.decorators import image_comparison
+from matplotlib.testing.decorators import check_figures_equal
+
+
+def draw_quiver(ax, **kwargs):
+ X, Y = np.meshgrid(np.arange(0, 2 * np.pi, 1),
+ np.arange(0, 2 * np.pi, 1))
+ U = np.cos(X)
+ V = np.sin(Y)
+
+ Q = ax.quiver(U, V, **kwargs)
+ return Q
+
+
+@pytest.mark.skipif(platform.python_implementation() != 'CPython',
+ reason='Requires CPython')
+def test_quiver_memory_leak():
+ fig, ax = plt.subplots()
+
+ Q = draw_quiver(ax)
+ ttX = Q.X
+ orig_refcount = sys.getrefcount(ttX)
+ Q.remove()
+
+ del Q
+
+ assert sys.getrefcount(ttX) < orig_refcount
+
+
+@pytest.mark.skipif(platform.python_implementation() != 'CPython',
+ reason='Requires CPython')
+def test_quiver_key_memory_leak():
+ fig, ax = plt.subplots()
+
+ Q = draw_quiver(ax)
+
+ qk = ax.quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$',
+ labelpos='W',
+ fontproperties={'weight': 'bold'})
+ orig_refcount = sys.getrefcount(qk)
+ qk.remove()
+ assert sys.getrefcount(qk) < orig_refcount
+
+
+def test_quiver_number_of_args():
+ X = [1, 2]
+ with pytest.raises(
+ TypeError,
+ match='takes from 2 to 5 positional arguments but 1 were given'):
+ plt.quiver(X)
+ with pytest.raises(
+ TypeError,
+ match='takes from 2 to 5 positional arguments but 6 were given'):
+ plt.quiver(X, X, X, X, X, X)
+
+
+def test_quiver_arg_sizes():
+ X2 = [1, 2]
+ X3 = [1, 2, 3]
+ with pytest.raises(
+ ValueError, match=('X and Y must be the same size, but '
+ 'X.size is 2 and Y.size is 3.')):
+ plt.quiver(X2, X3, X2, X2)
+ with pytest.raises(
+ ValueError, match=('Argument U has a size 3 which does not match '
+ '2, the number of arrow positions')):
+ plt.quiver(X2, X2, X3, X2)
+ with pytest.raises(
+ ValueError, match=('Argument V has a size 3 which does not match '
+ '2, the number of arrow positions')):
+ plt.quiver(X2, X2, X2, X3)
+ with pytest.raises(
+ ValueError, match=('Argument C has a size 3 which does not match '
+ '2, the number of arrow positions')):
+ plt.quiver(X2, X2, X2, X2, X3)
+
+
+def test_no_warnings():
+ fig, ax = plt.subplots()
+ X, Y = np.meshgrid(np.arange(15), np.arange(10))
+ U = V = np.ones_like(X)
+ phi = (np.random.rand(15, 10) - .5) * 150
+ ax.quiver(X, Y, U, V, angles=phi)
+ fig.canvas.draw() # Check that no warning is emitted.
+
+
+def test_zero_headlength():
+ # Based on report by Doug McNeil:
+ # https://discourse.matplotlib.org/t/quiver-warnings/16722
+ fig, ax = plt.subplots()
+ X, Y = np.meshgrid(np.arange(10), np.arange(10))
+ U, V = np.cos(X), np.sin(Y)
+ ax.quiver(U, V, headlength=0, headaxislength=0)
+ fig.canvas.draw() # Check that no warning is emitted.
+
+
+@image_comparison(['quiver_animated_test_image.png'])
+def test_quiver_animate():
+ # Tests fix for #2616
+ fig, ax = plt.subplots()
+ Q = draw_quiver(ax, animated=True)
+ ax.quiverkey(Q, 0.5, 0.92, 2, r'$2 \frac{m}{s}$',
+ labelpos='W', fontproperties={'weight': 'bold'})
+
+
+@image_comparison(['quiver_with_key_test_image.png'])
+def test_quiver_with_key():
+ fig, ax = plt.subplots()
+ ax.margins(0.1)
+ Q = draw_quiver(ax)
+ ax.quiverkey(Q, 0.5, 0.95, 2,
+ r'$2\, \mathrm{m}\, \mathrm{s}^{-1}$',
+ angle=-10,
+ coordinates='figure',
+ labelpos='W',
+ fontproperties={'weight': 'bold', 'size': 'large'})
+
+
+@image_comparison(['quiver_single_test_image.png'], remove_text=True)
+def test_quiver_single():
+ fig, ax = plt.subplots()
+ ax.margins(0.1)
+ ax.quiver([1], [1], [2], [2])
+
+
+def test_quiver_copy():
+ fig, ax = plt.subplots()
+ uv = dict(u=np.array([1.1]), v=np.array([2.0]))
+ q0 = ax.quiver([1], [1], uv['u'], uv['v'])
+ uv['v'][0] = 0
+ assert q0.V[0] == 2.0
+
+
+@image_comparison(['quiver_key_pivot.png'], remove_text=True)
+def test_quiver_key_pivot():
+ fig, ax = plt.subplots()
+
+ u, v = np.mgrid[0:2*np.pi:10j, 0:2*np.pi:10j]
+
+ q = ax.quiver(np.sin(u), np.cos(v))
+ ax.set_xlim(-2, 11)
+ ax.set_ylim(-2, 11)
+ ax.quiverkey(q, 0.5, 1, 1, 'N', labelpos='N')
+ ax.quiverkey(q, 1, 0.5, 1, 'E', labelpos='E')
+ ax.quiverkey(q, 0.5, 0, 1, 'S', labelpos='S')
+ ax.quiverkey(q, 0, 0.5, 1, 'W', labelpos='W')
+
+
+@image_comparison(['quiver_key_xy.png'], remove_text=True)
+def test_quiver_key_xy():
+ # With scale_units='xy', ensure quiverkey still matches its quiver.
+ # Note that the quiver and quiverkey lengths depend on the axes aspect
+ # ratio, and that with angles='xy' their angles also depend on the axes
+ # aspect ratio.
+ X = np.arange(8)
+ Y = np.zeros(8)
+ angles = X * (np.pi / 4)
+ uv = np.exp(1j * angles)
+ U = uv.real
+ V = uv.imag
+ fig, axs = plt.subplots(2)
+ for ax, angle_str in zip(axs, ('uv', 'xy')):
+ ax.set_xlim(-1, 8)
+ ax.set_ylim(-0.2, 0.2)
+ q = ax.quiver(X, Y, U, V, pivot='middle',
+ units='xy', width=0.05,
+ scale=2, scale_units='xy',
+ angles=angle_str)
+ for x, angle in zip((0.2, 0.5, 0.8), (0, 45, 90)):
+ ax.quiverkey(q, X=x, Y=0.8, U=1, angle=angle, label='', color='b')
+
+
+@image_comparison(['barbs_test_image.png'], remove_text=True)
+def test_barbs():
+ x = np.linspace(-5, 5, 5)
+ X, Y = np.meshgrid(x, x)
+ U, V = 12*X, 12*Y
+ fig, ax = plt.subplots()
+ ax.barbs(X, Y, U, V, np.hypot(U, V), fill_empty=True, rounding=False,
+ sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3),
+ cmap='viridis')
+
+
+@image_comparison(['barbs_pivot_test_image.png'], remove_text=True)
+def test_barbs_pivot():
+ x = np.linspace(-5, 5, 5)
+ X, Y = np.meshgrid(x, x)
+ U, V = 12*X, 12*Y
+ fig, ax = plt.subplots()
+ ax.barbs(X, Y, U, V, fill_empty=True, rounding=False, pivot=1.7,
+ sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3))
+ ax.scatter(X, Y, s=49, c='black')
+
+
+@image_comparison(['barbs_test_flip.png'], remove_text=True)
+def test_barbs_flip():
+ """Test barbs with an array for flip_barb."""
+ x = np.linspace(-5, 5, 5)
+ X, Y = np.meshgrid(x, x)
+ U, V = 12*X, 12*Y
+ fig, ax = plt.subplots()
+ ax.barbs(X, Y, U, V, fill_empty=True, rounding=False, pivot=1.7,
+ sizes=dict(emptybarb=0.25, spacing=0.2, height=0.3),
+ flip_barb=Y < 0)
+
+
+def test_barb_copy():
+ fig, ax = plt.subplots()
+ u = np.array([1.1])
+ v = np.array([2.2])
+ b0 = ax.barbs([1], [1], u, v)
+ u[0] = 0
+ assert b0.u[0] == 1.1
+ v[0] = 0
+ assert b0.v[0] == 2.2
+
+
+def test_bad_masked_sizes():
+ """Test error handling when given differing sized masked arrays."""
+ x = np.arange(3)
+ y = np.arange(3)
+ u = np.ma.array(15. * np.ones((4,)))
+ v = np.ma.array(15. * np.ones_like(u))
+ u[1] = np.ma.masked
+ v[1] = np.ma.masked
+ fig, ax = plt.subplots()
+ with pytest.raises(ValueError):
+ ax.barbs(x, y, u, v)
+
+
+def test_angles_and_scale():
+ # angles array + scale_units kwarg
+ fig, ax = plt.subplots()
+ X, Y = np.meshgrid(np.arange(15), np.arange(10))
+ U = V = np.ones_like(X)
+ phi = (np.random.rand(15, 10) - .5) * 150
+ ax.quiver(X, Y, U, V, angles=phi, scale_units='xy')
+
+
+@image_comparison(['quiver_xy.png'], remove_text=True)
+def test_quiver_xy():
+ # simple arrow pointing from SW to NE
+ fig, ax = plt.subplots(subplot_kw=dict(aspect='equal'))
+ ax.quiver(0, 0, 1, 1, angles='xy', scale_units='xy', scale=1)
+ ax.set_xlim(0, 1.1)
+ ax.set_ylim(0, 1.1)
+ ax.grid()
+
+
+def test_quiverkey_angles():
+ # Check that only a single arrow is plotted for a quiverkey when an array
+ # of angles is given to the original quiver plot
+ fig, ax = plt.subplots()
+
+ X, Y = np.meshgrid(np.arange(2), np.arange(2))
+ U = V = angles = np.ones_like(X)
+
+ q = ax.quiver(X, Y, U, V, angles=angles)
+ qk = ax.quiverkey(q, 1, 1, 2, 'Label')
+ # The arrows are only created when the key is drawn
+ fig.canvas.draw()
+ assert len(qk.verts) == 1
+
+
+def test_quiverkey_angles_xy_aitoff():
+ # GH 26316 and GH 26748
+ # Test that only one arrow will be plotted with non-cartesian
+ # when angles='xy' and/or scale_units='xy'
+
+ # only for test purpose
+ # scale_units='xy' may not be a valid use case for non-cartesian
+ kwargs_list = [
+ {'angles': 'xy'},
+ {'angles': 'xy', 'scale_units': 'xy'},
+ {'scale_units': 'xy'}
+ ]
+
+ for kwargs_dict in kwargs_list:
+
+ x = np.linspace(-np.pi, np.pi, 11)
+ y = np.ones_like(x) * np.pi / 6
+ vx = np.zeros_like(x)
+ vy = np.ones_like(x)
+
+ fig = plt.figure()
+ ax = fig.add_subplot(projection='aitoff')
+ q = ax.quiver(x, y, vx, vy, **kwargs_dict)
+ qk = ax.quiverkey(q, 0, 0, 1, '1 units')
+
+ fig.canvas.draw()
+ assert len(qk.verts) == 1
+
+
+def test_quiverkey_angles_scale_units_cartesian():
+ # GH 26316
+ # Test that only one arrow will be plotted with normal cartesian
+ # when angles='xy' and/or scale_units='xy'
+
+ kwargs_list = [
+ {'angles': 'xy'},
+ {'angles': 'xy', 'scale_units': 'xy'},
+ {'scale_units': 'xy'}
+ ]
+
+ for kwargs_dict in kwargs_list:
+ X = [0, -1, 0]
+ Y = [0, -1, 0]
+ U = [1, -1, 1]
+ V = [1, -1, 0]
+
+ fig, ax = plt.subplots()
+ q = ax.quiver(X, Y, U, V, **kwargs_dict)
+ ax.quiverkey(q, X=0.3, Y=1.1, U=1,
+ label='Quiver key, length = 1', labelpos='E')
+ qk = ax.quiverkey(q, 0, 0, 1, '1 units')
+
+ fig.canvas.draw()
+ assert len(qk.verts) == 1
+
+
+def test_quiver_setuvc_numbers():
+ """Check that it is possible to set all arrow UVC to the same numbers"""
+
+ fig, ax = plt.subplots()
+
+ X, Y = np.meshgrid(np.arange(2), np.arange(2))
+ U = V = np.ones_like(X)
+
+ q = ax.quiver(X, Y, U, V)
+ q.set_UVC(0, 1)
+
+
+def draw_quiverkey_zorder_argument(fig, zorder=None):
+ """Draw Quiver and QuiverKey using zorder argument"""
+ x = np.arange(1, 6, 1)
+ y = np.arange(1, 6, 1)
+ X, Y = np.meshgrid(x, y)
+ U, V = 2, 2
+
+ ax = fig.subplots()
+ q = ax.quiver(X, Y, U, V, pivot='middle')
+ ax.set_xlim(0.5, 5.5)
+ ax.set_ylim(0.5, 5.5)
+ if zorder is None:
+ ax.quiverkey(q, 4, 4, 25, coordinates='data',
+ label='U', color='blue')
+ ax.quiverkey(q, 5.5, 2, 20, coordinates='data',
+ label='V', color='blue', angle=90)
+ else:
+ ax.quiverkey(q, 4, 4, 25, coordinates='data',
+ label='U', color='blue', zorder=zorder)
+ ax.quiverkey(q, 5.5, 2, 20, coordinates='data',
+ label='V', color='blue', angle=90, zorder=zorder)
+
+
+def draw_quiverkey_setzorder(fig, zorder=None):
+ """Draw Quiver and QuiverKey using set_zorder"""
+ x = np.arange(1, 6, 1)
+ y = np.arange(1, 6, 1)
+ X, Y = np.meshgrid(x, y)
+ U, V = 2, 2
+
+ ax = fig.subplots()
+ q = ax.quiver(X, Y, U, V, pivot='middle')
+ ax.set_xlim(0.5, 5.5)
+ ax.set_ylim(0.5, 5.5)
+ qk1 = ax.quiverkey(q, 4, 4, 25, coordinates='data',
+ label='U', color='blue')
+ qk2 = ax.quiverkey(q, 5.5, 2, 20, coordinates='data',
+ label='V', color='blue', angle=90)
+ if zorder is not None:
+ qk1.set_zorder(zorder)
+ qk2.set_zorder(zorder)
+
+
+@pytest.mark.parametrize('zorder', [0, 2, 5, None])
+@check_figures_equal(extensions=['png'])
+def test_quiverkey_zorder(fig_test, fig_ref, zorder):
+ draw_quiverkey_zorder_argument(fig_test, zorder=zorder)
+ draw_quiverkey_setzorder(fig_ref, zorder=zorder)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_rcparams.py b/lib/python3.12/site-packages/matplotlib/tests/test_rcparams.py
new file mode 100644
index 0000000000000000000000000000000000000000..bea5e90ea4e54cb1ea480b2b20c7eb72e087bdcb
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_rcparams.py
@@ -0,0 +1,682 @@
+import copy
+import os
+import subprocess
+import sys
+from unittest import mock
+
+from cycler import cycler, Cycler
+from packaging.version import parse as parse_version
+import pytest
+
+import matplotlib as mpl
+from matplotlib import _api, _c_internal_utils
+import matplotlib.pyplot as plt
+import matplotlib.colors as mcolors
+import numpy as np
+from matplotlib.rcsetup import (
+ validate_bool,
+ validate_color,
+ validate_colorlist,
+ _validate_color_or_linecolor,
+ validate_cycler,
+ validate_float,
+ validate_fontstretch,
+ validate_fontweight,
+ validate_hatch,
+ validate_hist_bins,
+ validate_int,
+ validate_markevery,
+ validate_stringlist,
+ validate_sketch,
+ _validate_linestyle,
+ _listify_validator)
+from matplotlib.testing import subprocess_run_for_testing
+
+
+def test_rcparams(tmp_path):
+ mpl.rc('text', usetex=False)
+ mpl.rc('lines', linewidth=22)
+
+ usetex = mpl.rcParams['text.usetex']
+ linewidth = mpl.rcParams['lines.linewidth']
+
+ rcpath = tmp_path / 'test_rcparams.rc'
+ rcpath.write_text('lines.linewidth: 33', encoding='utf-8')
+
+ # test context given dictionary
+ with mpl.rc_context(rc={'text.usetex': not usetex}):
+ assert mpl.rcParams['text.usetex'] == (not usetex)
+ assert mpl.rcParams['text.usetex'] == usetex
+
+ # test context given filename (mpl.rc sets linewidth to 33)
+ with mpl.rc_context(fname=rcpath):
+ assert mpl.rcParams['lines.linewidth'] == 33
+ assert mpl.rcParams['lines.linewidth'] == linewidth
+
+ # test context given filename and dictionary
+ with mpl.rc_context(fname=rcpath, rc={'lines.linewidth': 44}):
+ assert mpl.rcParams['lines.linewidth'] == 44
+ assert mpl.rcParams['lines.linewidth'] == linewidth
+
+ # test context as decorator (and test reusability, by calling func twice)
+ @mpl.rc_context({'lines.linewidth': 44})
+ def func():
+ assert mpl.rcParams['lines.linewidth'] == 44
+
+ func()
+ func()
+
+ # test rc_file
+ mpl.rc_file(rcpath)
+ assert mpl.rcParams['lines.linewidth'] == 33
+
+
+def test_RcParams_class():
+ rc = mpl.RcParams({'font.cursive': ['Apple Chancery',
+ 'Textile',
+ 'Zapf Chancery',
+ 'cursive'],
+ 'font.family': 'sans-serif',
+ 'font.weight': 'normal',
+ 'font.size': 12})
+
+ expected_repr = """
+RcParams({'font.cursive': ['Apple Chancery',
+ 'Textile',
+ 'Zapf Chancery',
+ 'cursive'],
+ 'font.family': ['sans-serif'],
+ 'font.size': 12.0,
+ 'font.weight': 'normal'})""".lstrip()
+
+ assert expected_repr == repr(rc)
+
+ expected_str = """
+font.cursive: ['Apple Chancery', 'Textile', 'Zapf Chancery', 'cursive']
+font.family: ['sans-serif']
+font.size: 12.0
+font.weight: normal""".lstrip()
+
+ assert expected_str == str(rc)
+
+ # test the find_all functionality
+ assert ['font.cursive', 'font.size'] == sorted(rc.find_all('i[vz]'))
+ assert ['font.family'] == list(rc.find_all('family'))
+
+
+def test_rcparams_update():
+ rc = mpl.RcParams({'figure.figsize': (3.5, 42)})
+ bad_dict = {'figure.figsize': (3.5, 42, 1)}
+ # make sure validation happens on input
+ with pytest.raises(ValueError):
+ rc.update(bad_dict)
+
+
+def test_rcparams_init():
+ with pytest.raises(ValueError):
+ mpl.RcParams({'figure.figsize': (3.5, 42, 1)})
+
+
+def test_nargs_cycler():
+ from matplotlib.rcsetup import cycler as ccl
+ with pytest.raises(TypeError, match='3 were given'):
+ # cycler() takes 0-2 arguments.
+ ccl(ccl(color=list('rgb')), 2, 3)
+
+
+def test_Bug_2543():
+ # Test that it possible to add all values to itself / deepcopy
+ # https://github.com/matplotlib/matplotlib/issues/2543
+ # We filter warnings at this stage since a number of them are raised
+ # for deprecated rcparams as they should. We don't want these in the
+ # printed in the test suite.
+ with _api.suppress_matplotlib_deprecation_warning():
+ with mpl.rc_context():
+ _copy = mpl.rcParams.copy()
+ for key in _copy:
+ mpl.rcParams[key] = _copy[key]
+ with mpl.rc_context():
+ copy.deepcopy(mpl.rcParams)
+ with pytest.raises(ValueError):
+ validate_bool(None)
+ with pytest.raises(ValueError):
+ with mpl.rc_context():
+ mpl.rcParams['svg.fonttype'] = True
+
+
+legend_color_tests = [
+ ('face', {'color': 'r'}, mcolors.to_rgba('r')),
+ ('face', {'color': 'inherit', 'axes.facecolor': 'r'},
+ mcolors.to_rgba('r')),
+ ('face', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g')),
+ ('edge', {'color': 'r'}, mcolors.to_rgba('r')),
+ ('edge', {'color': 'inherit', 'axes.edgecolor': 'r'},
+ mcolors.to_rgba('r')),
+ ('edge', {'color': 'g', 'axes.facecolor': 'r'}, mcolors.to_rgba('g'))
+]
+legend_color_test_ids = [
+ 'same facecolor',
+ 'inherited facecolor',
+ 'different facecolor',
+ 'same edgecolor',
+ 'inherited edgecolor',
+ 'different facecolor',
+]
+
+
+@pytest.mark.parametrize('color_type, param_dict, target', legend_color_tests,
+ ids=legend_color_test_ids)
+def test_legend_colors(color_type, param_dict, target):
+ param_dict[f'legend.{color_type}color'] = param_dict.pop('color')
+ get_func = f'get_{color_type}color'
+
+ with mpl.rc_context(param_dict):
+ _, ax = plt.subplots()
+ ax.plot(range(3), label='test')
+ leg = ax.legend()
+ assert getattr(leg.legendPatch, get_func)() == target
+
+
+def test_mfc_rcparams():
+ mpl.rcParams['lines.markerfacecolor'] = 'r'
+ ln = mpl.lines.Line2D([1, 2], [1, 2])
+ assert ln.get_markerfacecolor() == 'r'
+
+
+def test_mec_rcparams():
+ mpl.rcParams['lines.markeredgecolor'] = 'r'
+ ln = mpl.lines.Line2D([1, 2], [1, 2])
+ assert ln.get_markeredgecolor() == 'r'
+
+
+def test_axes_titlecolor_rcparams():
+ mpl.rcParams['axes.titlecolor'] = 'r'
+ _, ax = plt.subplots()
+ title = ax.set_title("Title")
+ assert title.get_color() == 'r'
+
+
+def test_Issue_1713(tmp_path):
+ rcpath = tmp_path / 'test_rcparams.rc'
+ rcpath.write_text('timezone: UTC', encoding='utf-8')
+ with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'):
+ rc = mpl.rc_params_from_file(rcpath, True, False)
+ assert rc.get('timezone') == 'UTC'
+
+
+def test_animation_frame_formats():
+ # Animation frame_format should allow any of the following
+ # if any of these are not allowed, an exception will be raised
+ # test for gh issue #17908
+ for fmt in ['png', 'jpeg', 'tiff', 'raw', 'rgba', 'ppm',
+ 'sgi', 'bmp', 'pbm', 'svg']:
+ mpl.rcParams['animation.frame_format'] = fmt
+
+
+def generate_validator_testcases(valid):
+ validation_tests = (
+ {'validator': validate_bool,
+ 'success': (*((_, True) for _ in
+ ('t', 'y', 'yes', 'on', 'true', '1', 1, True)),
+ *((_, False) for _ in
+ ('f', 'n', 'no', 'off', 'false', '0', 0, False))),
+ 'fail': ((_, ValueError)
+ for _ in ('aardvark', 2, -1, [], ))
+ },
+ {'validator': validate_stringlist,
+ 'success': (('', []),
+ ('a,b', ['a', 'b']),
+ ('aardvark', ['aardvark']),
+ ('aardvark, ', ['aardvark']),
+ ('aardvark, ,', ['aardvark']),
+ (['a', 'b'], ['a', 'b']),
+ (('a', 'b'), ['a', 'b']),
+ (iter(['a', 'b']), ['a', 'b']),
+ (np.array(['a', 'b']), ['a', 'b']),
+ ),
+ 'fail': ((set(), ValueError),
+ (1, ValueError),
+ )
+ },
+ {'validator': _listify_validator(validate_int, n=2),
+ 'success': ((_, [1, 2])
+ for _ in ('1, 2', [1.5, 2.5], [1, 2],
+ (1, 2), np.array((1, 2)))),
+ 'fail': ((_, ValueError)
+ for _ in ('aardvark', ('a', 1),
+ (1, 2, 3)
+ ))
+ },
+ {'validator': _listify_validator(validate_float, n=2),
+ 'success': ((_, [1.5, 2.5])
+ for _ in ('1.5, 2.5', [1.5, 2.5], [1.5, 2.5],
+ (1.5, 2.5), np.array((1.5, 2.5)))),
+ 'fail': ((_, ValueError)
+ for _ in ('aardvark', ('a', 1), (1, 2, 3), (None, ), None))
+ },
+ {'validator': validate_cycler,
+ 'success': (('cycler("color", "rgb")',
+ cycler("color", 'rgb')),
+ (cycler('linestyle', ['-', '--']),
+ cycler('linestyle', ['-', '--'])),
+ ("""(cycler("color", ["r", "g", "b"]) +
+ cycler("mew", [2, 3, 5]))""",
+ (cycler("color", 'rgb') +
+ cycler("markeredgewidth", [2, 3, 5]))),
+ ("cycler(c='rgb', lw=[1, 2, 3])",
+ cycler('color', 'rgb') + cycler('linewidth', [1, 2, 3])),
+ ("cycler('c', 'rgb') * cycler('linestyle', ['-', '--'])",
+ (cycler('color', 'rgb') *
+ cycler('linestyle', ['-', '--']))),
+ (cycler('ls', ['-', '--']),
+ cycler('linestyle', ['-', '--'])),
+ (cycler(mew=[2, 5]),
+ cycler('markeredgewidth', [2, 5])),
+ ),
+ # This is *so* incredibly important: validate_cycler() eval's
+ # an arbitrary string! I think I have it locked down enough,
+ # and that is what this is testing.
+ # TODO: Note that these tests are actually insufficient, as it may
+ # be that they raised errors, but still did an action prior to
+ # raising the exception. We should devise some additional tests
+ # for that...
+ 'fail': ((4, ValueError), # Gotta be a string or Cycler object
+ ('cycler("bleh, [])', ValueError), # syntax error
+ ('Cycler("linewidth", [1, 2, 3])',
+ ValueError), # only 'cycler()' function is allowed
+ # do not allow dunder in string literals
+ ("cycler('c', [j.__class__(j) for j in ['r', 'b']])",
+ ValueError),
+ ("cycler('c', [j. __class__(j) for j in ['r', 'b']])",
+ ValueError),
+ ("cycler('c', [j.\t__class__(j) for j in ['r', 'b']])",
+ ValueError),
+ ("cycler('c', [j.\u000c__class__(j) for j in ['r', 'b']])",
+ ValueError),
+ ("cycler('c', [j.__class__(j).lower() for j in ['r', 'b']])",
+ ValueError),
+ ('1 + 2', ValueError), # doesn't produce a Cycler object
+ ('os.system("echo Gotcha")', ValueError), # os not available
+ ('import os', ValueError), # should not be able to import
+ ('def badjuju(a): return a; badjuju(cycler("color", "rgb"))',
+ ValueError), # Should not be able to define anything
+ # even if it does return a cycler
+ ('cycler("waka", [1, 2, 3])', ValueError), # not a property
+ ('cycler(c=[1, 2, 3])', ValueError), # invalid values
+ ("cycler(lw=['a', 'b', 'c'])", ValueError), # invalid values
+ (cycler('waka', [1, 3, 5]), ValueError), # not a property
+ (cycler('color', ['C1', 'r', 'g']), ValueError) # no CN
+ )
+ },
+ {'validator': validate_hatch,
+ 'success': (('--|', '--|'), ('\\oO', '\\oO'),
+ ('/+*/.x', '/+*/.x'), ('', '')),
+ 'fail': (('--_', ValueError),
+ (8, ValueError),
+ ('X', ValueError)),
+ },
+ {'validator': validate_colorlist,
+ 'success': (('r,g,b', ['r', 'g', 'b']),
+ (['r', 'g', 'b'], ['r', 'g', 'b']),
+ ('r, ,', ['r']),
+ (['', 'g', 'blue'], ['g', 'blue']),
+ ([np.array([1, 0, 0]), np.array([0, 1, 0])],
+ np.array([[1, 0, 0], [0, 1, 0]])),
+ (np.array([[1, 0, 0], [0, 1, 0]]),
+ np.array([[1, 0, 0], [0, 1, 0]])),
+ ),
+ 'fail': (('fish', ValueError),
+ ),
+ },
+ {'validator': validate_color,
+ 'success': (('None', 'none'),
+ ('none', 'none'),
+ ('AABBCC', '#AABBCC'), # RGB hex code
+ ('AABBCC00', '#AABBCC00'), # RGBA hex code
+ ('tab:blue', 'tab:blue'), # named color
+ ('C12', 'C12'), # color from cycle
+ ('(0, 1, 0)', (0.0, 1.0, 0.0)), # RGB tuple
+ ((0, 1, 0), (0, 1, 0)), # non-string version
+ ('(0, 1, 0, 1)', (0.0, 1.0, 0.0, 1.0)), # RGBA tuple
+ ((0, 1, 0, 1), (0, 1, 0, 1)), # non-string version
+ ),
+ 'fail': (('tab:veryblue', ValueError), # invalid name
+ ('(0, 1)', ValueError), # tuple with length < 3
+ ('(0, 1, 0, 1, 0)', ValueError), # tuple with length > 4
+ ('(0, 1, none)', ValueError), # cannot cast none to float
+ ('(0, 1, "0.5")', ValueError), # last one not a float
+ ),
+ },
+ {'validator': _validate_color_or_linecolor,
+ 'success': (('linecolor', 'linecolor'),
+ ('markerfacecolor', 'markerfacecolor'),
+ ('mfc', 'markerfacecolor'),
+ ('markeredgecolor', 'markeredgecolor'),
+ ('mec', 'markeredgecolor')
+ ),
+ 'fail': (('line', ValueError),
+ ('marker', ValueError)
+ )
+ },
+ {'validator': validate_hist_bins,
+ 'success': (('auto', 'auto'),
+ ('fd', 'fd'),
+ ('10', 10),
+ ('1, 2, 3', [1, 2, 3]),
+ ([1, 2, 3], [1, 2, 3]),
+ (np.arange(15), np.arange(15))
+ ),
+ 'fail': (('aardvark', ValueError),
+ )
+ },
+ {'validator': validate_markevery,
+ 'success': ((None, None),
+ (1, 1),
+ (0.1, 0.1),
+ ((1, 1), (1, 1)),
+ ((0.1, 0.1), (0.1, 0.1)),
+ ([1, 2, 3], [1, 2, 3]),
+ (slice(2), slice(None, 2, None)),
+ (slice(1, 2, 3), slice(1, 2, 3))
+ ),
+ 'fail': (((1, 2, 3), TypeError),
+ ([1, 2, 0.3], TypeError),
+ (['a', 2, 3], TypeError),
+ ([1, 2, 'a'], TypeError),
+ ((0.1, 0.2, 0.3), TypeError),
+ ((0.1, 2, 3), TypeError),
+ ((1, 0.2, 0.3), TypeError),
+ ((1, 0.1), TypeError),
+ ((0.1, 1), TypeError),
+ (('abc'), TypeError),
+ ((1, 'a'), TypeError),
+ ((0.1, 'b'), TypeError),
+ (('a', 1), TypeError),
+ (('a', 0.1), TypeError),
+ ('abc', TypeError),
+ ('a', TypeError),
+ (object(), TypeError)
+ )
+ },
+ {'validator': _validate_linestyle,
+ 'success': (('-', '-'), ('solid', 'solid'),
+ ('--', '--'), ('dashed', 'dashed'),
+ ('-.', '-.'), ('dashdot', 'dashdot'),
+ (':', ':'), ('dotted', 'dotted'),
+ ('', ''), (' ', ' '),
+ ('None', 'none'), ('none', 'none'),
+ ('DoTtEd', 'dotted'), # case-insensitive
+ ('1, 3', (0, (1, 3))),
+ ([1.23, 456], (0, [1.23, 456.0])),
+ ([1, 2, 3, 4], (0, [1.0, 2.0, 3.0, 4.0])),
+ ((0, [1, 2]), (0, [1, 2])),
+ ((-1, [1, 2]), (-1, [1, 2])),
+ ),
+ 'fail': (('aardvark', ValueError), # not a valid string
+ (b'dotted', ValueError),
+ ('dotted'.encode('utf-16'), ValueError),
+ ([1, 2, 3], ValueError), # sequence with odd length
+ (1.23, ValueError), # not a sequence
+ (("a", [1, 2]), ValueError), # wrong explicit offset
+ ((None, [1, 2]), ValueError), # wrong explicit offset
+ ((1, [1, 2, 3]), ValueError), # odd length sequence
+ (([1, 2], 1), ValueError), # inverted offset/onoff
+ )
+ },
+ )
+
+ for validator_dict in validation_tests:
+ validator = validator_dict['validator']
+ if valid:
+ for arg, target in validator_dict['success']:
+ yield validator, arg, target
+ else:
+ for arg, error_type in validator_dict['fail']:
+ yield validator, arg, error_type
+
+
+@pytest.mark.parametrize('validator, arg, target',
+ generate_validator_testcases(True))
+def test_validator_valid(validator, arg, target):
+ res = validator(arg)
+ if isinstance(target, np.ndarray):
+ np.testing.assert_equal(res, target)
+ elif not isinstance(target, Cycler):
+ assert res == target
+ else:
+ # Cyclers can't simply be asserted equal. They don't implement __eq__
+ assert list(res) == list(target)
+
+
+@pytest.mark.parametrize('validator, arg, exception_type',
+ generate_validator_testcases(False))
+def test_validator_invalid(validator, arg, exception_type):
+ with pytest.raises(exception_type):
+ validator(arg)
+
+
+@pytest.mark.parametrize('weight, parsed_weight', [
+ ('bold', 'bold'),
+ ('BOLD', ValueError), # weight is case-sensitive
+ (100, 100),
+ ('100', 100),
+ (np.array(100), 100),
+ # fractional fontweights are not defined. This should actually raise a
+ # ValueError, but historically did not.
+ (20.6, 20),
+ ('20.6', ValueError),
+ ([100], ValueError),
+])
+def test_validate_fontweight(weight, parsed_weight):
+ if parsed_weight is ValueError:
+ with pytest.raises(ValueError):
+ validate_fontweight(weight)
+ else:
+ assert validate_fontweight(weight) == parsed_weight
+
+
+@pytest.mark.parametrize('stretch, parsed_stretch', [
+ ('expanded', 'expanded'),
+ ('EXPANDED', ValueError), # stretch is case-sensitive
+ (100, 100),
+ ('100', 100),
+ (np.array(100), 100),
+ # fractional fontweights are not defined. This should actually raise a
+ # ValueError, but historically did not.
+ (20.6, 20),
+ ('20.6', ValueError),
+ ([100], ValueError),
+])
+def test_validate_fontstretch(stretch, parsed_stretch):
+ if parsed_stretch is ValueError:
+ with pytest.raises(ValueError):
+ validate_fontstretch(stretch)
+ else:
+ assert validate_fontstretch(stretch) == parsed_stretch
+
+
+def test_keymaps():
+ key_list = [k for k in mpl.rcParams if 'keymap' in k]
+ for k in key_list:
+ assert isinstance(mpl.rcParams[k], list)
+
+
+def test_no_backend_reset_rccontext():
+ assert mpl.rcParams['backend'] != 'module://aardvark'
+ with mpl.rc_context():
+ mpl.rcParams['backend'] = 'module://aardvark'
+ assert mpl.rcParams['backend'] == 'module://aardvark'
+
+
+def test_rcparams_reset_after_fail():
+ # There was previously a bug that meant that if rc_context failed and
+ # raised an exception due to issues in the supplied rc parameters, the
+ # global rc parameters were left in a modified state.
+ with mpl.rc_context(rc={'text.usetex': False}):
+ assert mpl.rcParams['text.usetex'] is False
+ with pytest.raises(KeyError):
+ with mpl.rc_context(rc={'text.usetex': True, 'test.blah': True}):
+ pass
+ assert mpl.rcParams['text.usetex'] is False
+
+
+@pytest.mark.skipif(sys.platform != "linux", reason="Linux only")
+def test_backend_fallback_headless_invalid_backend(tmp_path):
+ env = {**os.environ,
+ "DISPLAY": "", "WAYLAND_DISPLAY": "",
+ "MPLBACKEND": "", "MPLCONFIGDIR": str(tmp_path)}
+ # plotting should fail with the tkagg backend selected in a headless environment
+ with pytest.raises(subprocess.CalledProcessError):
+ subprocess_run_for_testing(
+ [sys.executable, "-c",
+ "import matplotlib;"
+ "matplotlib.use('tkagg');"
+ "import matplotlib.pyplot;"
+ "matplotlib.pyplot.plot(42);"
+ ],
+ env=env, check=True, stderr=subprocess.DEVNULL)
+
+
+@pytest.mark.skipif(sys.platform != "linux", reason="Linux only")
+def test_backend_fallback_headless_auto_backend(tmp_path):
+ # specify a headless mpl environment, but request a graphical (tk) backend
+ env = {**os.environ,
+ "DISPLAY": "", "WAYLAND_DISPLAY": "",
+ "MPLBACKEND": "TkAgg", "MPLCONFIGDIR": str(tmp_path)}
+
+ # allow fallback to an available interactive backend explicitly in configuration
+ rc_path = tmp_path / "matplotlibrc"
+ rc_path.write_text("backend_fallback: true")
+
+ # plotting should succeed, by falling back to use the generic agg backend
+ backend = subprocess_run_for_testing(
+ [sys.executable, "-c",
+ "import matplotlib.pyplot;"
+ "matplotlib.pyplot.plot(42);"
+ "print(matplotlib.get_backend());"
+ ],
+ env=env, text=True, check=True, capture_output=True).stdout
+ assert backend.strip().lower() == "agg"
+
+
+@pytest.mark.skipif(
+ sys.platform == "linux" and not _c_internal_utils.xdisplay_is_valid(),
+ reason="headless")
+def test_backend_fallback_headful(tmp_path):
+ if parse_version(pytest.__version__) >= parse_version('8.2.0'):
+ pytest_kwargs = dict(exc_type=ImportError)
+ else:
+ pytest_kwargs = {}
+
+ pytest.importorskip("tkinter", **pytest_kwargs)
+ env = {**os.environ, "MPLBACKEND": "", "MPLCONFIGDIR": str(tmp_path)}
+ backend = subprocess_run_for_testing(
+ [sys.executable, "-c",
+ "import matplotlib as mpl; "
+ "sentinel = mpl.rcsetup._auto_backend_sentinel; "
+ # Check that access on another instance does not resolve the sentinel.
+ "assert mpl.RcParams({'backend': sentinel})['backend'] == sentinel; "
+ "assert mpl.rcParams._get('backend') == sentinel; "
+ "assert mpl.get_backend(auto_select=False) is None; "
+ "import matplotlib.pyplot; "
+ "print(matplotlib.get_backend())"],
+ env=env, text=True, check=True, capture_output=True).stdout
+ # The actual backend will depend on what's installed, but at least tkagg is
+ # present.
+ assert backend.strip().lower() != "agg"
+
+
+def test_deprecation(monkeypatch):
+ monkeypatch.setitem(
+ mpl._deprecated_map, "patch.linewidth",
+ ("0.0", "axes.linewidth", lambda old: 2 * old, lambda new: new / 2))
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
+ assert mpl.rcParams["patch.linewidth"] \
+ == mpl.rcParams["axes.linewidth"] / 2
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
+ mpl.rcParams["patch.linewidth"] = 1
+ assert mpl.rcParams["axes.linewidth"] == 2
+
+ monkeypatch.setitem(
+ mpl._deprecated_ignore_map, "patch.edgecolor",
+ ("0.0", "axes.edgecolor"))
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
+ assert mpl.rcParams["patch.edgecolor"] \
+ == mpl.rcParams["axes.edgecolor"]
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
+ mpl.rcParams["patch.edgecolor"] = "#abcd"
+ assert mpl.rcParams["axes.edgecolor"] != "#abcd"
+
+ monkeypatch.setitem(
+ mpl._deprecated_ignore_map, "patch.force_edgecolor",
+ ("0.0", None))
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
+ assert mpl.rcParams["patch.force_edgecolor"] is None
+
+ monkeypatch.setitem(
+ mpl._deprecated_remain_as_none, "svg.hashsalt",
+ ("0.0",))
+ with pytest.warns(mpl.MatplotlibDeprecationWarning):
+ mpl.rcParams["svg.hashsalt"] = "foobar"
+ assert mpl.rcParams["svg.hashsalt"] == "foobar" # Doesn't warn.
+ mpl.rcParams["svg.hashsalt"] = None # Doesn't warn.
+
+ mpl.rcParams.update(mpl.rcParams.copy()) # Doesn't warn.
+ # Note that the warning suppression actually arises from the
+ # iteration over the updater rcParams being protected by
+ # suppress_matplotlib_deprecation_warning, rather than any explicit check.
+
+
+@pytest.mark.parametrize("value", [
+ "best",
+ 1,
+ "1",
+ (0.9, .7),
+ (-0.9, .7),
+ "(0.9, .7)"
+])
+def test_rcparams_legend_loc(value):
+ # rcParams['legend.loc'] should allow any of the following formats.
+ # if any of these are not allowed, an exception will be raised
+ # test for gh issue #22338
+ mpl.rcParams["legend.loc"] = value
+
+
+@pytest.mark.parametrize("value", [
+ "best",
+ 1,
+ (0.9, .7),
+ (-0.9, .7),
+])
+def test_rcparams_legend_loc_from_file(tmp_path, value):
+ # rcParams['legend.loc'] should be settable from matplotlibrc.
+ # if any of these are not allowed, an exception will be raised.
+ # test for gh issue #22338
+ rc_path = tmp_path / "matplotlibrc"
+ rc_path.write_text(f"legend.loc: {value}")
+
+ with mpl.rc_context(fname=rc_path):
+ assert mpl.rcParams["legend.loc"] == value
+
+
+@pytest.mark.parametrize("value", [(1, 2, 3), '1, 2, 3', '(1, 2, 3)'])
+def test_validate_sketch(value):
+ mpl.rcParams["path.sketch"] = value
+ assert mpl.rcParams["path.sketch"] == (1, 2, 3)
+ assert validate_sketch(value) == (1, 2, 3)
+
+
+@pytest.mark.parametrize("value", [1, '1', '1 2 3'])
+def test_validate_sketch_error(value):
+ with pytest.raises(ValueError, match="scale, length, randomness"):
+ validate_sketch(value)
+ with pytest.raises(ValueError, match="scale, length, randomness"):
+ mpl.rcParams["path.sketch"] = value
+
+
+@pytest.mark.parametrize("value", ['1, 2, 3', '(1,2,3)'])
+def test_rcparams_path_sketch_from_file(tmp_path, value):
+ rc_path = tmp_path / "matplotlibrc"
+ rc_path.write_text(f"path.sketch: {value}")
+ with mpl.rc_context(fname=rc_path):
+ assert mpl.rcParams["path.sketch"] == (1, 2, 3)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_skew.py b/lib/python3.12/site-packages/matplotlib/tests/test_skew.py
new file mode 100644
index 0000000000000000000000000000000000000000..8527e474fa21d751584fb8ffca47408f0dffeb0e
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_skew.py
@@ -0,0 +1,170 @@
+"""
+Testing that skewed Axes properly work.
+"""
+
+from contextlib import ExitStack
+import itertools
+import platform
+
+import matplotlib.pyplot as plt
+from matplotlib.testing.decorators import image_comparison
+
+from matplotlib.axes import Axes
+import matplotlib.transforms as transforms
+import matplotlib.axis as maxis
+import matplotlib.spines as mspines
+import matplotlib.patches as mpatch
+from matplotlib.projections import register_projection
+
+
+# The sole purpose of this class is to look at the upper, lower, or total
+# interval as appropriate and see what parts of the tick to draw, if any.
+class SkewXTick(maxis.XTick):
+ def draw(self, renderer):
+ with ExitStack() as stack:
+ for artist in [self.gridline, self.tick1line, self.tick2line,
+ self.label1, self.label2]:
+ stack.callback(artist.set_visible, artist.get_visible())
+ needs_lower = transforms.interval_contains(
+ self.axes.lower_xlim, self.get_loc())
+ needs_upper = transforms.interval_contains(
+ self.axes.upper_xlim, self.get_loc())
+ self.tick1line.set_visible(
+ self.tick1line.get_visible() and needs_lower)
+ self.label1.set_visible(
+ self.label1.get_visible() and needs_lower)
+ self.tick2line.set_visible(
+ self.tick2line.get_visible() and needs_upper)
+ self.label2.set_visible(
+ self.label2.get_visible() and needs_upper)
+ super().draw(renderer)
+
+ def get_view_interval(self):
+ return self.axes.xaxis.get_view_interval()
+
+
+# This class exists to provide two separate sets of intervals to the tick,
+# as well as create instances of the custom tick
+class SkewXAxis(maxis.XAxis):
+ def _get_tick(self, major):
+ return SkewXTick(self.axes, None, major=major)
+
+ def get_view_interval(self):
+ return self.axes.upper_xlim[0], self.axes.lower_xlim[1]
+
+
+# This class exists to calculate the separate data range of the
+# upper X-axis and draw the spine there. It also provides this range
+# to the X-axis artist for ticking and gridlines
+class SkewSpine(mspines.Spine):
+ def _adjust_location(self):
+ pts = self._path.vertices
+ if self.spine_type == 'top':
+ pts[:, 0] = self.axes.upper_xlim
+ else:
+ pts[:, 0] = self.axes.lower_xlim
+
+
+# This class handles registration of the skew-xaxes as a projection as well
+# as setting up the appropriate transformations. It also overrides standard
+# spines and axes instances as appropriate.
+class SkewXAxes(Axes):
+ # The projection must specify a name. This will be used be the
+ # user to select the projection, i.e. ``subplot(projection='skewx')``.
+ name = 'skewx'
+
+ def _init_axis(self):
+ # Taken from Axes and modified to use our modified X-axis
+ self.xaxis = SkewXAxis(self)
+ self.spines.top.register_axis(self.xaxis)
+ self.spines.bottom.register_axis(self.xaxis)
+ self.yaxis = maxis.YAxis(self)
+ self.spines.left.register_axis(self.yaxis)
+ self.spines.right.register_axis(self.yaxis)
+
+ def _gen_axes_spines(self):
+ spines = {'top': SkewSpine.linear_spine(self, 'top'),
+ 'bottom': mspines.Spine.linear_spine(self, 'bottom'),
+ 'left': mspines.Spine.linear_spine(self, 'left'),
+ 'right': mspines.Spine.linear_spine(self, 'right')}
+ return spines
+
+ def _set_lim_and_transforms(self):
+ """
+ This is called once when the plot is created to set up all the
+ transforms for the data, text and grids.
+ """
+ rot = 30
+
+ # Get the standard transform setup from the Axes base class
+ super()._set_lim_and_transforms()
+
+ # Need to put the skew in the middle, after the scale and limits,
+ # but before the transAxes. This way, the skew is done in Axes
+ # coordinates thus performing the transform around the proper origin
+ # We keep the pre-transAxes transform around for other users, like the
+ # spines for finding bounds
+ self.transDataToAxes = (self.transScale +
+ (self.transLimits +
+ transforms.Affine2D().skew_deg(rot, 0)))
+
+ # Create the full transform from Data to Pixels
+ self.transData = self.transDataToAxes + self.transAxes
+
+ # Blended transforms like this need to have the skewing applied using
+ # both axes, in axes coords like before.
+ self._xaxis_transform = (transforms.blended_transform_factory(
+ self.transScale + self.transLimits,
+ transforms.IdentityTransform()) +
+ transforms.Affine2D().skew_deg(rot, 0)) + self.transAxes
+
+ @property
+ def lower_xlim(self):
+ return self.axes.viewLim.intervalx
+
+ @property
+ def upper_xlim(self):
+ pts = [[0., 1.], [1., 1.]]
+ return self.transDataToAxes.inverted().transform(pts)[:, 0]
+
+
+# Now register the projection with matplotlib so the user can select
+# it.
+register_projection(SkewXAxes)
+
+
+@image_comparison(['skew_axes.png'], remove_text=True)
+def test_set_line_coll_dash_image():
+ fig = plt.figure()
+ ax = fig.add_subplot(1, 1, 1, projection='skewx')
+ ax.set_xlim(-50, 50)
+ ax.set_ylim(50, -50)
+ ax.grid(True)
+
+ # An example of a slanted line at constant X
+ ax.axvline(0, color='b')
+
+
+@image_comparison(['skew_rects.png'], remove_text=True,
+ tol=0 if platform.machine() == 'x86_64' else 0.009)
+def test_skew_rectangle():
+
+ fix, axes = plt.subplots(5, 5, sharex=True, sharey=True, figsize=(8, 8))
+ axes = axes.flat
+
+ rotations = list(itertools.product([-3, -1, 0, 1, 3], repeat=2))
+
+ axes[0].set_xlim([-3, 3])
+ axes[0].set_ylim([-3, 3])
+ axes[0].set_aspect('equal', share=True)
+
+ for ax, (xrots, yrots) in zip(axes, rotations):
+ xdeg, ydeg = 45 * xrots, 45 * yrots
+ t = transforms.Affine2D().skew_deg(xdeg, ydeg)
+
+ ax.set_title(f'Skew of {xdeg} in X and {ydeg} in Y')
+ ax.add_patch(mpatch.Rectangle([-1, -1], 2, 2,
+ transform=t + ax.transData,
+ alpha=0.5, facecolor='coral'))
+
+ plt.subplots_adjust(wspace=0, left=0.01, right=0.99, bottom=0.01, top=0.99)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_sphinxext.py b/lib/python3.12/site-packages/matplotlib/tests/test_sphinxext.py
new file mode 100644
index 0000000000000000000000000000000000000000..1aaa6baca47c5f8e5a7dd6dbae608487a401590f
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_sphinxext.py
@@ -0,0 +1,227 @@
+"""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='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_text(encoding='utf-8')
+
+ assert '# 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 'This is the caption for plot 15.' in html_contents
+ # check if figure caption using :caption: made it into html file (because this plot
+ # doesn't use srcset, the caption preserves newlines in the output.)
+ assert 'Plot 17 uses the caption option,\nwith multi-line input.' in html_contents
+ # check if figure alt text using :alt: made it into html file
+ assert 'Plot 17 uses the alt option, with multi-line input.' in html_contents
+ # check if figure caption made it into html file
+ assert 'This is the caption for plot 18.' in html_contents
+ # check if the custom classes made it into the html file
+ assert 'plot-directive my-class my-other-class' in html_contents
+ # check that the multi-image caption is applied twice
+ assert html_contents.count('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/lib/python3.12/site-packages/matplotlib/tests/test_spines.py b/lib/python3.12/site-packages/matplotlib/tests/test_spines.py
new file mode 100644
index 0000000000000000000000000000000000000000..29b4ecf6f33033a8d46f281a7fba92b6cc7d46ce
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_spines.py
@@ -0,0 +1,156 @@
+import numpy as np
+import pytest
+
+import matplotlib.pyplot as plt
+from matplotlib.spines import Spines
+from matplotlib.testing.decorators import check_figures_equal, image_comparison
+
+
+def test_spine_class():
+ """Test Spines and SpinesProxy in isolation."""
+ class SpineMock:
+ def __init__(self):
+ self.val = None
+
+ def set(self, **kwargs):
+ vars(self).update(kwargs)
+
+ def set_val(self, val):
+ self.val = val
+
+ spines_dict = {
+ 'left': SpineMock(),
+ 'right': SpineMock(),
+ 'top': SpineMock(),
+ 'bottom': SpineMock(),
+ }
+ spines = Spines(**spines_dict)
+
+ assert spines['left'] is spines_dict['left']
+ assert spines.left is spines_dict['left']
+
+ spines[['left', 'right']].set_val('x')
+ assert spines.left.val == 'x'
+ assert spines.right.val == 'x'
+ assert spines.top.val is None
+ assert spines.bottom.val is None
+
+ spines[:].set_val('y')
+ assert all(spine.val == 'y' for spine in spines.values())
+
+ spines[:].set(foo='bar')
+ assert all(spine.foo == 'bar' for spine in spines.values())
+
+ with pytest.raises(AttributeError, match='foo'):
+ spines.foo
+ with pytest.raises(KeyError, match='foo'):
+ spines['foo']
+ with pytest.raises(KeyError, match='foo, bar'):
+ spines[['left', 'foo', 'right', 'bar']]
+ with pytest.raises(ValueError, match='single list'):
+ spines['left', 'right']
+ with pytest.raises(ValueError, match='Spines does not support slicing'):
+ spines['left':'right']
+ with pytest.raises(ValueError, match='Spines does not support slicing'):
+ spines['top':]
+
+
+@image_comparison(['spines_axes_positions.png'])
+def test_spines_axes_positions():
+ # SF bug 2852168
+ fig = plt.figure()
+ x = np.linspace(0, 2*np.pi, 100)
+ y = 2*np.sin(x)
+ ax = fig.add_subplot(1, 1, 1)
+ ax.set_title('centered spines')
+ ax.plot(x, y)
+ ax.spines.right.set_position(('axes', 0.1))
+ ax.yaxis.set_ticks_position('right')
+ ax.spines.top.set_position(('axes', 0.25))
+ ax.xaxis.set_ticks_position('top')
+ ax.spines.left.set_color('none')
+ ax.spines.bottom.set_color('none')
+
+
+@image_comparison(['spines_data_positions.png'])
+def test_spines_data_positions():
+ fig, ax = plt.subplots()
+ ax.spines.left.set_position(('data', -1.5))
+ ax.spines.top.set_position(('data', 0.5))
+ ax.spines.right.set_position(('data', -0.5))
+ ax.spines.bottom.set_position('zero')
+ ax.set_xlim([-2, 2])
+ ax.set_ylim([-2, 2])
+
+
+@check_figures_equal(extensions=["png"])
+def test_spine_nonlinear_data_positions(fig_test, fig_ref):
+ plt.style.use("default")
+
+ ax = fig_test.add_subplot()
+ ax.set(xscale="log", xlim=(.1, 1))
+ # Use position="data" to visually swap the left and right spines, using
+ # linewidth to distinguish them. The calls to tick_params removes labels
+ # (for image comparison purposes) and harmonizes tick positions with the
+ # reference).
+ ax.spines.left.set_position(("data", 1))
+ ax.spines.left.set_linewidth(2)
+ ax.spines.right.set_position(("data", .1))
+ ax.tick_params(axis="y", labelleft=False, direction="in")
+
+ ax = fig_ref.add_subplot()
+ ax.set(xscale="log", xlim=(.1, 1))
+ ax.spines.right.set_linewidth(2)
+ ax.tick_params(axis="y", labelleft=False, left=False, right=True)
+
+
+@image_comparison(['spines_capstyle.png'])
+def test_spines_capstyle():
+ # issue 2542
+ plt.rc('axes', linewidth=20)
+ fig, ax = plt.subplots()
+ ax.set_xticks([])
+ ax.set_yticks([])
+
+
+def test_label_without_ticks():
+ fig, ax = plt.subplots()
+ plt.subplots_adjust(left=0.3, bottom=0.3)
+ ax.plot(np.arange(10))
+ ax.yaxis.set_ticks_position('left')
+ ax.spines.left.set_position(('outward', 30))
+ ax.spines.right.set_visible(False)
+ ax.set_ylabel('y label')
+ ax.xaxis.set_ticks_position('bottom')
+ ax.spines.bottom.set_position(('outward', 30))
+ ax.spines.top.set_visible(False)
+ ax.set_xlabel('x label')
+ ax.xaxis.set_ticks([])
+ ax.yaxis.set_ticks([])
+ plt.draw()
+
+ spine = ax.spines.left
+ spinebbox = spine.get_transform().transform_path(
+ spine.get_path()).get_extents()
+ assert ax.yaxis.label.get_position()[0] < spinebbox.xmin, \
+ "Y-Axis label not left of the spine"
+
+ spine = ax.spines.bottom
+ spinebbox = spine.get_transform().transform_path(
+ spine.get_path()).get_extents()
+ assert ax.xaxis.label.get_position()[1] < spinebbox.ymin, \
+ "X-Axis label not below the spine"
+
+
+@image_comparison(['black_axes.png'])
+def test_spines_black_axes():
+ # GitHub #18804
+ plt.rcParams["savefig.pad_inches"] = 0
+ plt.rcParams["savefig.bbox"] = 'tight'
+ fig = plt.figure(0, figsize=(4, 4))
+ ax = fig.add_axes((0, 0, 1, 1))
+ ax.set_xticklabels([])
+ ax.set_yticklabels([])
+ ax.set_xticks([])
+ ax.set_yticks([])
+ ax.set_facecolor((0, 0, 0))
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_streamplot.py b/lib/python3.12/site-packages/matplotlib/tests/test_streamplot.py
new file mode 100644
index 0000000000000000000000000000000000000000..92e72c5baeca1d8f6212310d9f0b5b98beb39f82
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_streamplot.py
@@ -0,0 +1,169 @@
+import numpy as np
+from numpy.testing import assert_array_almost_equal
+import pytest
+import matplotlib.pyplot as plt
+from matplotlib.testing.decorators import image_comparison
+import matplotlib.transforms as mtransforms
+
+
+def velocity_field():
+ Y, X = np.mgrid[-3:3:100j, -3:3:200j]
+ U = -1 - X**2 + Y
+ V = 1 + X - Y**2
+ return X, Y, U, V
+
+
+def swirl_velocity_field():
+ x = np.linspace(-3., 3., 200)
+ y = np.linspace(-3., 3., 100)
+ X, Y = np.meshgrid(x, y)
+ a = 0.1
+ U = np.cos(a) * (-Y) - np.sin(a) * X
+ V = np.sin(a) * (-Y) + np.cos(a) * X
+ return x, y, U, V
+
+
+@image_comparison(['streamplot_startpoints'], remove_text=True, style='mpl20',
+ extensions=['png'])
+def test_startpoints():
+ X, Y, U, V = velocity_field()
+ start_x, start_y = np.meshgrid(np.linspace(X.min(), X.max(), 5),
+ np.linspace(Y.min(), Y.max(), 5))
+ start_points = np.column_stack([start_x.ravel(), start_y.ravel()])
+ plt.streamplot(X, Y, U, V, start_points=start_points)
+ plt.plot(start_x, start_y, 'ok')
+
+
+@image_comparison(['streamplot_colormap.png'], remove_text=True, style='mpl20',
+ tol=0.022)
+def test_colormap():
+ X, Y, U, V = velocity_field()
+ plt.streamplot(X, Y, U, V, color=U, density=0.6, linewidth=2,
+ cmap=plt.cm.autumn)
+ plt.colorbar()
+
+
+@image_comparison(['streamplot_linewidth'], remove_text=True, style='mpl20',
+ tol=0.004)
+def test_linewidth():
+ X, Y, U, V = velocity_field()
+ speed = np.hypot(U, V)
+ lw = 5 * speed / speed.max()
+ ax = plt.figure().subplots()
+ ax.streamplot(X, Y, U, V, density=[0.5, 1], color='k', linewidth=lw)
+
+
+@image_comparison(['streamplot_masks_and_nans.png'],
+ remove_text=True, style='mpl20')
+def test_masks_and_nans():
+ X, Y, U, V = velocity_field()
+ mask = np.zeros(U.shape, dtype=bool)
+ mask[40:60, 80:120] = 1
+ U[:20, :40] = np.nan
+ U = np.ma.array(U, mask=mask)
+ ax = plt.figure().subplots()
+ with np.errstate(invalid='ignore'):
+ ax.streamplot(X, Y, U, V, color=U, cmap=plt.cm.Blues)
+
+
+@image_comparison(['streamplot_maxlength.png'],
+ remove_text=True, style='mpl20', tol=0.302)
+def test_maxlength():
+ x, y, U, V = swirl_velocity_field()
+ ax = plt.figure().subplots()
+ ax.streamplot(x, y, U, V, maxlength=10., start_points=[[0., 1.5]],
+ linewidth=2, density=2)
+ assert ax.get_xlim()[-1] == ax.get_ylim()[-1] == 3
+ # Compatibility for old test image
+ ax.set(xlim=(None, 3.2555988021882305), ylim=(None, 3.078326760195413))
+
+
+@image_comparison(['streamplot_maxlength_no_broken.png'],
+ remove_text=True, style='mpl20', tol=0.302)
+def test_maxlength_no_broken():
+ x, y, U, V = swirl_velocity_field()
+ ax = plt.figure().subplots()
+ ax.streamplot(x, y, U, V, maxlength=10., start_points=[[0., 1.5]],
+ linewidth=2, density=2, broken_streamlines=False)
+ assert ax.get_xlim()[-1] == ax.get_ylim()[-1] == 3
+ # Compatibility for old test image
+ ax.set(xlim=(None, 3.2555988021882305), ylim=(None, 3.078326760195413))
+
+
+@image_comparison(['streamplot_direction.png'],
+ remove_text=True, style='mpl20', tol=0.073)
+def test_direction():
+ x, y, U, V = swirl_velocity_field()
+ plt.streamplot(x, y, U, V, integration_direction='backward',
+ maxlength=1.5, start_points=[[1.5, 0.]],
+ linewidth=2, density=2)
+
+
+def test_streamplot_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)
+
+
+def test_streamplot_grid():
+ u = np.ones((2, 2))
+ v = np.zeros((2, 2))
+
+ # Test for same rows and columns
+ x = np.array([[10, 20], [10, 30]])
+ y = np.array([[10, 10], [20, 20]])
+
+ with pytest.raises(ValueError, match="The rows of 'x' must be equal"):
+ plt.streamplot(x, y, u, v)
+
+ x = np.array([[10, 20], [10, 20]])
+ y = np.array([[10, 10], [20, 30]])
+
+ with pytest.raises(ValueError, match="The columns of 'y' must be equal"):
+ plt.streamplot(x, y, u, v)
+
+ x = np.array([[10, 20], [10, 20]])
+ y = np.array([[10, 10], [20, 20]])
+ plt.streamplot(x, y, u, v)
+
+ # Test for maximum dimensions
+ x = np.array([0, 10])
+ y = np.array([[[0, 10]]])
+
+ with pytest.raises(ValueError, match="'y' can have at maximum "
+ "2 dimensions"):
+ plt.streamplot(x, y, u, v)
+
+ # Test for equal spacing
+ u = np.ones((3, 3))
+ v = np.zeros((3, 3))
+ x = np.array([0, 10, 20])
+ y = np.array([0, 10, 30])
+
+ with pytest.raises(ValueError, match="'y' values must be equally spaced"):
+ plt.streamplot(x, y, u, v)
+
+ # Test for strictly increasing
+ x = np.array([0, 20, 40])
+ y = np.array([0, 20, 10])
+
+ with pytest.raises(ValueError, match="'y' must be strictly increasing"):
+ plt.streamplot(x, y, u, v)
+
+
+def test_streamplot_inputs(): # test no exception occurs.
+ # fully-masked
+ plt.streamplot(np.arange(3), np.arange(3),
+ np.full((3, 3), np.nan), np.full((3, 3), np.nan),
+ color=np.random.rand(3, 3))
+ # array-likes
+ plt.streamplot(range(3), range(3),
+ np.random.rand(3, 3), np.random.rand(3, 3))
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_style.py b/lib/python3.12/site-packages/matplotlib/tests/test_style.py
new file mode 100644
index 0000000000000000000000000000000000000000..be038965e33da3a0646b5a330a7247e51488fb16
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_style.py
@@ -0,0 +1,197 @@
+from contextlib import contextmanager
+from pathlib import Path
+from tempfile import TemporaryDirectory
+import sys
+
+import numpy as np
+import pytest
+
+import matplotlib as mpl
+from matplotlib import pyplot as plt, style
+from matplotlib.style.core import USER_LIBRARY_PATHS, STYLE_EXTENSION
+
+
+PARAM = 'image.cmap'
+VALUE = 'pink'
+DUMMY_SETTINGS = {PARAM: VALUE}
+
+
+@contextmanager
+def temp_style(style_name, settings=None):
+ """Context manager to create a style sheet in a temporary directory."""
+ if not settings:
+ settings = DUMMY_SETTINGS
+ temp_file = f'{style_name}.{STYLE_EXTENSION}'
+ try:
+ with TemporaryDirectory() as tmpdir:
+ # Write style settings to file in the tmpdir.
+ Path(tmpdir, temp_file).write_text(
+ "\n".join(f"{k}: {v}" for k, v in settings.items()),
+ encoding="utf-8")
+ # Add tmpdir to style path and reload so we can access this style.
+ USER_LIBRARY_PATHS.append(tmpdir)
+ style.reload_library()
+ yield
+ finally:
+ style.reload_library()
+
+
+def test_invalid_rc_warning_includes_filename(caplog):
+ SETTINGS = {'foo': 'bar'}
+ basename = 'basename'
+ with temp_style(basename, SETTINGS):
+ # style.reload_library() in temp_style() triggers the warning
+ pass
+ assert (len(caplog.records) == 1
+ and basename in caplog.records[0].getMessage())
+
+
+def test_available():
+ with temp_style('_test_', DUMMY_SETTINGS):
+ assert '_test_' in style.available
+
+
+def test_use():
+ mpl.rcParams[PARAM] = 'gray'
+ with temp_style('test', DUMMY_SETTINGS):
+ with style.context('test'):
+ assert mpl.rcParams[PARAM] == VALUE
+
+
+def test_use_url(tmp_path):
+ path = tmp_path / 'file'
+ path.write_text('axes.facecolor: adeade', encoding='utf-8')
+ with temp_style('test', DUMMY_SETTINGS):
+ url = ('file:'
+ + ('///' if sys.platform == 'win32' else '')
+ + path.resolve().as_posix())
+ with style.context(url):
+ assert mpl.rcParams['axes.facecolor'] == "#adeade"
+
+
+def test_single_path(tmp_path):
+ mpl.rcParams[PARAM] = 'gray'
+ path = tmp_path / f'text.{STYLE_EXTENSION}'
+ path.write_text(f'{PARAM} : {VALUE}', encoding='utf-8')
+ with style.context(path):
+ assert mpl.rcParams[PARAM] == VALUE
+ assert mpl.rcParams[PARAM] == 'gray'
+
+
+def test_context():
+ mpl.rcParams[PARAM] = 'gray'
+ with temp_style('test', DUMMY_SETTINGS):
+ with style.context('test'):
+ assert mpl.rcParams[PARAM] == VALUE
+ # Check that this value is reset after the exiting the context.
+ assert mpl.rcParams[PARAM] == 'gray'
+
+
+def test_context_with_dict():
+ original_value = 'gray'
+ other_value = 'blue'
+ mpl.rcParams[PARAM] = original_value
+ with style.context({PARAM: other_value}):
+ assert mpl.rcParams[PARAM] == other_value
+ assert mpl.rcParams[PARAM] == original_value
+
+
+def test_context_with_dict_after_namedstyle():
+ # Test dict after style name where dict modifies the same parameter.
+ original_value = 'gray'
+ other_value = 'blue'
+ mpl.rcParams[PARAM] = original_value
+ with temp_style('test', DUMMY_SETTINGS):
+ with style.context(['test', {PARAM: other_value}]):
+ assert mpl.rcParams[PARAM] == other_value
+ assert mpl.rcParams[PARAM] == original_value
+
+
+def test_context_with_dict_before_namedstyle():
+ # Test dict before style name where dict modifies the same parameter.
+ original_value = 'gray'
+ other_value = 'blue'
+ mpl.rcParams[PARAM] = original_value
+ with temp_style('test', DUMMY_SETTINGS):
+ with style.context([{PARAM: other_value}, 'test']):
+ assert mpl.rcParams[PARAM] == VALUE
+ assert mpl.rcParams[PARAM] == original_value
+
+
+def test_context_with_union_of_dict_and_namedstyle():
+ # Test dict after style name where dict modifies the a different parameter.
+ original_value = 'gray'
+ other_param = 'text.usetex'
+ other_value = True
+ d = {other_param: other_value}
+ mpl.rcParams[PARAM] = original_value
+ mpl.rcParams[other_param] = (not other_value)
+ with temp_style('test', DUMMY_SETTINGS):
+ with style.context(['test', d]):
+ assert mpl.rcParams[PARAM] == VALUE
+ assert mpl.rcParams[other_param] == other_value
+ assert mpl.rcParams[PARAM] == original_value
+ assert mpl.rcParams[other_param] == (not other_value)
+
+
+def test_context_with_badparam():
+ original_value = 'gray'
+ other_value = 'blue'
+ with style.context({PARAM: other_value}):
+ assert mpl.rcParams[PARAM] == other_value
+ x = style.context({PARAM: original_value, 'badparam': None})
+ with pytest.raises(KeyError):
+ with x:
+ pass
+ assert mpl.rcParams[PARAM] == other_value
+
+
+@pytest.mark.parametrize('equiv_styles',
+ [('mpl20', 'default'),
+ ('mpl15', 'classic')],
+ ids=['mpl20', 'mpl15'])
+def test_alias(equiv_styles):
+ rc_dicts = []
+ for sty in equiv_styles:
+ with style.context(sty):
+ rc_dicts.append(mpl.rcParams.copy())
+
+ rc_base = rc_dicts[0]
+ for nm, rc in zip(equiv_styles[1:], rc_dicts[1:]):
+ assert rc_base == rc
+
+
+def test_xkcd_no_cm():
+ assert mpl.rcParams["path.sketch"] is None
+ plt.xkcd()
+ assert mpl.rcParams["path.sketch"] == (1, 100, 2)
+ np.testing.break_cycles()
+ assert mpl.rcParams["path.sketch"] == (1, 100, 2)
+
+
+def test_xkcd_cm():
+ assert mpl.rcParams["path.sketch"] is None
+ with plt.xkcd():
+ assert mpl.rcParams["path.sketch"] == (1, 100, 2)
+ assert mpl.rcParams["path.sketch"] is None
+
+
+def test_up_to_date_blacklist():
+ assert mpl.style.core.STYLE_BLACKLIST <= {*mpl.rcsetup._validators}
+
+
+def test_style_from_module(tmp_path, monkeypatch):
+ monkeypatch.syspath_prepend(tmp_path)
+ monkeypatch.chdir(tmp_path)
+ pkg_path = tmp_path / "mpl_test_style_pkg"
+ pkg_path.mkdir()
+ (pkg_path / "test_style.mplstyle").write_text(
+ "lines.linewidth: 42", encoding="utf-8")
+ pkg_path.with_suffix(".mplstyle").write_text(
+ "lines.linewidth: 84", encoding="utf-8")
+ mpl.style.use("mpl_test_style_pkg.test_style")
+ assert mpl.rcParams["lines.linewidth"] == 42
+ mpl.style.use("mpl_test_style_pkg.mplstyle")
+ assert mpl.rcParams["lines.linewidth"] == 84
+ mpl.style.use("./mpl_test_style_pkg.mplstyle")
+ assert mpl.rcParams["lines.linewidth"] == 84
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_subplots.py b/lib/python3.12/site-packages/matplotlib/tests/test_subplots.py
new file mode 100644
index 0000000000000000000000000000000000000000..704ff6e1bd3f0f87a7374be7cd3b6c55e7a0ca27
--- /dev/null
+++ b/lib/python3.12/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.png'],
+ tol=0 if platform.machine() == 'x86_64' else 0.028)
+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/lib/python3.12/site-packages/matplotlib/tests/test_table.py b/lib/python3.12/site-packages/matplotlib/tests/test_table.py
new file mode 100644
index 0000000000000000000000000000000000000000..29d1944323fc3e6141b0cc2bac229ae4a82bec35
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_table.py
@@ -0,0 +1,283 @@
+import datetime
+from unittest.mock import Mock
+
+import numpy as np
+
+import matplotlib.pyplot as plt
+from matplotlib.path import Path
+from matplotlib.table import CustomCell, Table
+from matplotlib.testing.decorators import image_comparison, check_figures_equal
+from matplotlib.transforms import Bbox
+import matplotlib.units as munits
+
+
+def test_non_square():
+ # Check that creating a non-square table works
+ cellcolors = ['b', 'r']
+ plt.table(cellColours=cellcolors)
+
+
+@image_comparison(['table_zorder.png'], remove_text=True)
+def test_zorder():
+ data = [[66386, 174296],
+ [58230, 381139]]
+
+ colLabels = ('Freeze', 'Wind')
+ rowLabels = ['%d year' % x for x in (100, 50)]
+
+ cellText = []
+ yoff = np.zeros(len(colLabels))
+ for row in reversed(data):
+ yoff += row
+ cellText.append(['%1.1f' % (x/1000.0) for x in yoff])
+
+ t = np.linspace(0, 2*np.pi, 100)
+ plt.plot(t, np.cos(t), lw=4, zorder=2)
+
+ plt.table(cellText=cellText,
+ rowLabels=rowLabels,
+ colLabels=colLabels,
+ loc='center',
+ zorder=-2,
+ )
+
+ plt.table(cellText=cellText,
+ rowLabels=rowLabels,
+ colLabels=colLabels,
+ loc='upper center',
+ zorder=4,
+ )
+ plt.yticks([])
+
+
+@image_comparison(['table_labels.png'])
+def test_label_colours():
+ dim = 3
+
+ c = np.linspace(0, 1, dim)
+ colours = plt.cm.RdYlGn(c)
+ cellText = [['1'] * dim] * dim
+
+ fig = plt.figure()
+
+ ax1 = fig.add_subplot(4, 1, 1)
+ ax1.axis('off')
+ ax1.table(cellText=cellText,
+ rowColours=colours,
+ loc='best')
+
+ ax2 = fig.add_subplot(4, 1, 2)
+ ax2.axis('off')
+ ax2.table(cellText=cellText,
+ rowColours=colours,
+ rowLabels=['Header'] * dim,
+ loc='best')
+
+ ax3 = fig.add_subplot(4, 1, 3)
+ ax3.axis('off')
+ ax3.table(cellText=cellText,
+ colColours=colours,
+ loc='best')
+
+ ax4 = fig.add_subplot(4, 1, 4)
+ ax4.axis('off')
+ ax4.table(cellText=cellText,
+ colColours=colours,
+ colLabels=['Header'] * dim,
+ loc='best')
+
+
+@image_comparison(['table_cell_manipulation.png'], style='mpl20')
+def test_diff_cell_table(text_placeholders):
+ cells = ('horizontal', 'vertical', 'open', 'closed', 'T', 'R', 'B', 'L')
+ cellText = [['1'] * len(cells)] * 2
+ colWidths = [0.1] * len(cells)
+
+ _, axs = plt.subplots(nrows=len(cells), figsize=(4, len(cells)+1), layout='tight')
+ for ax, cell in zip(axs, cells):
+ ax.table(
+ colWidths=colWidths,
+ cellText=cellText,
+ loc='center',
+ edges=cell,
+ )
+ ax.axis('off')
+
+
+def test_customcell():
+ types = ('horizontal', 'vertical', 'open', 'closed', 'T', 'R', 'B', 'L')
+ codes = (
+ (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO, Path.MOVETO),
+ (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.LINETO),
+ (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO),
+ (Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY),
+ (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO),
+ (Path.MOVETO, Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO),
+ (Path.MOVETO, Path.LINETO, Path.MOVETO, Path.MOVETO, Path.MOVETO),
+ (Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.MOVETO, Path.LINETO),
+ )
+
+ for t, c in zip(types, codes):
+ cell = CustomCell((0, 0), visible_edges=t, width=1, height=1)
+ code = tuple(s for _, s in cell.get_path().iter_segments())
+ assert c == code
+
+
+@image_comparison(['table_auto_column.png'])
+def test_auto_column():
+ fig, (ax1, ax2, ax3, ax4) = plt.subplots(4, 1)
+
+ # iterable list input
+ ax1.axis('off')
+ tb1 = ax1.table(
+ cellText=[['Fit Text', 2],
+ ['very long long text, Longer text than default', 1]],
+ rowLabels=["A", "B"],
+ colLabels=["Col1", "Col2"],
+ loc="center")
+ tb1.auto_set_font_size(False)
+ tb1.set_fontsize(12)
+ tb1.auto_set_column_width([-1, 0, 1])
+
+ # iterable tuple input
+ ax2.axis('off')
+ tb2 = ax2.table(
+ cellText=[['Fit Text', 2],
+ ['very long long text, Longer text than default', 1]],
+ rowLabels=["A", "B"],
+ colLabels=["Col1", "Col2"],
+ loc="center")
+ tb2.auto_set_font_size(False)
+ tb2.set_fontsize(12)
+ tb2.auto_set_column_width((-1, 0, 1))
+
+ # 3 single inputs
+ ax3.axis('off')
+ tb3 = ax3.table(
+ cellText=[['Fit Text', 2],
+ ['very long long text, Longer text than default', 1]],
+ rowLabels=["A", "B"],
+ colLabels=["Col1", "Col2"],
+ loc="center")
+ tb3.auto_set_font_size(False)
+ tb3.set_fontsize(12)
+ tb3.auto_set_column_width(-1)
+ tb3.auto_set_column_width(0)
+ tb3.auto_set_column_width(1)
+
+ # 4 this used to test non-integer iterable input, which did nothing, but only
+ # remains to avoid re-generating the test image.
+ ax4.axis('off')
+ tb4 = ax4.table(
+ cellText=[['Fit Text', 2],
+ ['very long long text, Longer text than default', 1]],
+ rowLabels=["A", "B"],
+ colLabels=["Col1", "Col2"],
+ loc="center")
+ tb4.auto_set_font_size(False)
+ tb4.set_fontsize(12)
+
+
+def test_table_cells():
+ fig, ax = plt.subplots()
+ table = Table(ax)
+
+ cell = table.add_cell(1, 2, 1, 1)
+ assert isinstance(cell, CustomCell)
+ assert cell is table[1, 2]
+
+ cell2 = CustomCell((0, 0), 1, 2, visible_edges=None)
+ table[2, 1] = cell2
+ assert table[2, 1] is cell2
+
+ # make sure getitem support has not broken
+ # properties and setp
+ table.properties()
+ plt.setp(table)
+
+
+@check_figures_equal(extensions=["png"])
+def test_table_bbox(fig_test, fig_ref):
+ data = [[2, 3],
+ [4, 5]]
+
+ col_labels = ('Foo', 'Bar')
+ row_labels = ('Ada', 'Bob')
+
+ cell_text = [[f"{x}" for x in row] for row in data]
+
+ ax_list = fig_test.subplots()
+ ax_list.table(cellText=cell_text,
+ rowLabels=row_labels,
+ colLabels=col_labels,
+ loc='center',
+ bbox=[0.1, 0.2, 0.8, 0.6]
+ )
+
+ ax_bbox = fig_ref.subplots()
+ ax_bbox.table(cellText=cell_text,
+ rowLabels=row_labels,
+ colLabels=col_labels,
+ loc='center',
+ bbox=Bbox.from_extents(0.1, 0.2, 0.9, 0.8)
+ )
+
+
+@check_figures_equal(extensions=['png'])
+def test_table_unit(fig_test, fig_ref):
+ # test that table doesn't participate in unit machinery, instead uses repr/str
+
+ class FakeUnit:
+ def __init__(self, thing):
+ pass
+ def __repr__(self):
+ return "Hello"
+
+ fake_convertor = munits.ConversionInterface()
+ # v, u, a = value, unit, axis
+ fake_convertor.convert = Mock(side_effect=lambda v, u, a: 0)
+ # not used, here for completeness
+ fake_convertor.default_units = Mock(side_effect=lambda v, a: None)
+ fake_convertor.axisinfo = Mock(side_effect=lambda u, a: munits.AxisInfo())
+
+ munits.registry[FakeUnit] = fake_convertor
+
+ data = [[FakeUnit("yellow"), FakeUnit(42)],
+ [FakeUnit(datetime.datetime(1968, 8, 1)), FakeUnit(True)]]
+
+ fig_test.subplots().table(data)
+ fig_ref.subplots().table([["Hello", "Hello"], ["Hello", "Hello"]])
+ fig_test.canvas.draw()
+ fake_convertor.convert.assert_not_called()
+
+ munits.registry.pop(FakeUnit)
+ assert not munits.registry.get_converter(FakeUnit)
+
+
+def test_table_dataframe(pd):
+ # Test if Pandas Data Frame can be passed in cellText
+
+ data = {
+ 'Letter': ['A', 'B', 'C'],
+ 'Number': [100, 200, 300]
+ }
+
+ df = pd.DataFrame(data)
+ fig, ax = plt.subplots()
+ table = ax.table(df, loc='center')
+
+ for r, (index, row) in enumerate(df.iterrows()):
+ for c, col in enumerate(df.columns if r == 0 else row.values):
+ assert table[r if r == 0 else r+1, c].get_text().get_text() == str(col)
+
+
+def test_table_fontsize():
+ # Test that the passed fontsize propagates to cells
+ tableData = [['a', 1], ['b', 2]]
+ fig, ax = plt.subplots()
+ test_fontsize = 20
+ t = ax.table(cellText=tableData, loc='top', fontsize=test_fontsize)
+ cell_fontsize = t[(0, 0)].get_fontsize()
+ assert cell_fontsize == test_fontsize, f"Actual:{test_fontsize},got:{cell_fontsize}"
+ cell_fontsize = t[(1, 1)].get_fontsize()
+ assert cell_fontsize == test_fontsize, f"Actual:{test_fontsize},got:{cell_fontsize}"
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_testing.py b/lib/python3.12/site-packages/matplotlib/tests/test_testing.py
new file mode 100644
index 0000000000000000000000000000000000000000..f13839d6b3b68a6ce7e2f7d21e7ba68088e05f95
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_testing.py
@@ -0,0 +1,41 @@
+import warnings
+
+import pytest
+
+import matplotlib.pyplot as plt
+from matplotlib.testing.decorators import check_figures_equal
+
+
+@pytest.mark.xfail(
+ strict=True, reason="testing that warnings fail tests"
+)
+def test_warn_to_fail():
+ warnings.warn("This should fail the test")
+
+
+@pytest.mark.parametrize("a", [1])
+@check_figures_equal(extensions=["png"])
+@pytest.mark.parametrize("b", [1])
+def test_parametrize_with_check_figure_equal(a, fig_ref, b, fig_test):
+ assert a == b
+
+
+def test_wrap_failure():
+ with pytest.raises(ValueError, match="^The decorated function"):
+ @check_figures_equal()
+ def should_fail(test, ref):
+ pass
+
+
+@pytest.mark.xfail(raises=RuntimeError, strict=True,
+ reason='Test for check_figures_equal test creating '
+ 'new figures')
+@check_figures_equal()
+def test_check_figures_equal_extra_fig(fig_test, fig_ref):
+ plt.figure()
+
+
+@check_figures_equal()
+def test_check_figures_equal_closed_fig(fig_test, fig_ref):
+ fig = plt.figure()
+ plt.close(fig)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_texmanager.py b/lib/python3.12/site-packages/matplotlib/tests/test_texmanager.py
new file mode 100644
index 0000000000000000000000000000000000000000..64dcbf46456de679c6c29f104a7e86e6afcd9ac2
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_texmanager.py
@@ -0,0 +1,75 @@
+import os
+from pathlib import Path
+import re
+import sys
+
+import pytest
+
+import matplotlib.pyplot as plt
+from matplotlib.testing import subprocess_run_for_testing
+from matplotlib.testing._markers import needs_usetex
+from matplotlib.texmanager import TexManager
+
+
+def test_fontconfig_preamble():
+ """Test that the preamble is included in the source."""
+ plt.rcParams['text.usetex'] = True
+
+ src1 = TexManager()._get_tex_source("", fontsize=12)
+ plt.rcParams['text.latex.preamble'] = '\\usepackage{txfonts}'
+ src2 = TexManager()._get_tex_source("", fontsize=12)
+
+ assert src1 != src2
+
+
+@pytest.mark.parametrize(
+ "rc, preamble, family", [
+ ({"font.family": "sans-serif", "font.sans-serif": "helvetica"},
+ r"\usepackage{helvet}", r"\sffamily"),
+ ({"font.family": "serif", "font.serif": "palatino"},
+ r"\usepackage{mathpazo}", r"\rmfamily"),
+ ({"font.family": "cursive", "font.cursive": "zapf chancery"},
+ r"\usepackage{chancery}", r"\rmfamily"),
+ ({"font.family": "monospace", "font.monospace": "courier"},
+ r"\usepackage{courier}", r"\ttfamily"),
+ ({"font.family": "helvetica"}, r"\usepackage{helvet}", r"\sffamily"),
+ ({"font.family": "palatino"}, r"\usepackage{mathpazo}", r"\rmfamily"),
+ ({"font.family": "zapf chancery"},
+ r"\usepackage{chancery}", r"\rmfamily"),
+ ({"font.family": "courier"}, r"\usepackage{courier}", r"\ttfamily")
+ ])
+def test_font_selection(rc, preamble, family):
+ plt.rcParams.update(rc)
+ tm = TexManager()
+ src = Path(tm.make_tex("hello, world", fontsize=12)).read_text()
+ assert preamble in src
+ assert [*re.findall(r"\\\w+family", src)] == [family]
+
+
+@needs_usetex
+def test_unicode_characters():
+ # Smoke test to see that Unicode characters does not cause issues
+ # See #23019
+ plt.rcParams['text.usetex'] = True
+ fig, ax = plt.subplots()
+ ax.set_ylabel('\\textit{Velocity (\N{DEGREE SIGN}/sec)}')
+ ax.set_xlabel('\N{VULGAR FRACTION ONE QUARTER}Öøæ')
+ fig.canvas.draw()
+
+ # But not all characters.
+ # Should raise RuntimeError, not UnicodeDecodeError
+ with pytest.raises(RuntimeError):
+ ax.set_title('\N{SNOWMAN}')
+ fig.canvas.draw()
+
+
+@needs_usetex
+def test_openin_any_paranoid():
+ completed = subprocess_run_for_testing(
+ [sys.executable, "-c",
+ 'import matplotlib.pyplot as plt;'
+ 'plt.rcParams.update({"text.usetex": True});'
+ 'plt.title("paranoid");'
+ 'plt.show(block=False);'],
+ env={**os.environ, 'openin_any': 'p'}, check=True, capture_output=True)
+ assert completed.stderr == ""
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_text.py b/lib/python3.12/site-packages/matplotlib/tests/test_text.py
new file mode 100644
index 0000000000000000000000000000000000000000..19262202e5c160c32fe1ebda3d4feabb54233616
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_text.py
@@ -0,0 +1,1137 @@
+from datetime import datetime
+import io
+import warnings
+
+import numpy as np
+from numpy.testing import assert_almost_equal
+from packaging.version import parse as parse_version
+import pyparsing
+import pytest
+
+import matplotlib as mpl
+from matplotlib.backend_bases import MouseEvent
+from matplotlib.backends.backend_agg import RendererAgg
+from matplotlib.figure import Figure
+from matplotlib.font_manager import FontProperties
+import matplotlib.patches as mpatches
+import matplotlib.pyplot as plt
+from matplotlib.gridspec import GridSpec
+import matplotlib.transforms as mtransforms
+from matplotlib.testing.decorators import check_figures_equal, image_comparison
+from matplotlib.testing._markers import needs_usetex
+from matplotlib.text import Text, Annotation, OffsetFrom
+
+pyparsing_version = parse_version(pyparsing.__version__)
+
+
+@image_comparison(['font_styles'])
+def test_font_styles():
+
+ def find_matplotlib_font(**kw):
+ prop = FontProperties(**kw)
+ path = findfont(prop, directory=mpl.get_data_path())
+ return FontProperties(fname=path)
+
+ from matplotlib.font_manager import FontProperties, findfont
+ warnings.filterwarnings(
+ 'ignore',
+ r"findfont: Font family \[u?'Foo'\] not found. Falling back to .",
+ UserWarning,
+ module='matplotlib.font_manager')
+
+ fig, ax = plt.subplots()
+
+ normal_font = find_matplotlib_font(
+ family="sans-serif",
+ style="normal",
+ variant="normal",
+ size=14)
+ a = ax.annotate(
+ "Normal Font",
+ (0.1, 0.1),
+ xycoords='axes fraction',
+ fontproperties=normal_font)
+ assert a.get_fontname() == 'DejaVu Sans'
+ assert a.get_fontstyle() == 'normal'
+ assert a.get_fontvariant() == 'normal'
+ assert a.get_weight() == 'normal'
+ assert a.get_stretch() == 'normal'
+
+ bold_font = find_matplotlib_font(
+ family="Foo",
+ style="normal",
+ variant="normal",
+ weight="bold",
+ stretch=500,
+ size=14)
+ ax.annotate(
+ "Bold Font",
+ (0.1, 0.2),
+ xycoords='axes fraction',
+ fontproperties=bold_font)
+
+ bold_italic_font = find_matplotlib_font(
+ family="sans serif",
+ style="italic",
+ variant="normal",
+ weight=750,
+ stretch=500,
+ size=14)
+ ax.annotate(
+ "Bold Italic Font",
+ (0.1, 0.3),
+ xycoords='axes fraction',
+ fontproperties=bold_italic_font)
+
+ light_font = find_matplotlib_font(
+ family="sans-serif",
+ style="normal",
+ variant="normal",
+ weight=200,
+ stretch=500,
+ size=14)
+ ax.annotate(
+ "Light Font",
+ (0.1, 0.4),
+ xycoords='axes fraction',
+ fontproperties=light_font)
+
+ condensed_font = find_matplotlib_font(
+ family="sans-serif",
+ style="normal",
+ variant="normal",
+ weight=500,
+ stretch=100,
+ size=14)
+ ax.annotate(
+ "Condensed Font",
+ (0.1, 0.5),
+ xycoords='axes fraction',
+ fontproperties=condensed_font)
+
+ ax.set_xticks([])
+ ax.set_yticks([])
+
+
+@image_comparison(['multiline'])
+def test_multiline():
+ plt.figure()
+ ax = plt.subplot(1, 1, 1)
+ ax.set_title("multiline\ntext alignment")
+
+ plt.text(
+ 0.2, 0.5, "TpTpTp\n$M$\nTpTpTp", size=20, ha="center", va="top")
+
+ plt.text(
+ 0.5, 0.5, "TpTpTp\n$M^{M^{M^{M}}}$\nTpTpTp", size=20,
+ ha="center", va="top")
+
+ plt.text(
+ 0.8, 0.5, "TpTpTp\n$M_{q_{q_{q}}}$\nTpTpTp", size=20,
+ ha="center", va="top")
+
+ plt.xlim(0, 1)
+ plt.ylim(0, 0.8)
+
+ ax.set_xticks([])
+ ax.set_yticks([])
+
+
+@image_comparison(['multiline2'], style='mpl20')
+def test_multiline2():
+ # Remove this line when this test image is regenerated.
+ plt.rcParams['text.kerning_factor'] = 6
+
+ fig, ax = plt.subplots()
+
+ ax.set_xlim([0, 1.4])
+ ax.set_ylim([0, 2])
+ ax.axhline(0.5, color='C2', linewidth=0.3)
+ sts = ['Line', '2 Lineg\n 2 Lg', '$\\sum_i x $', 'hi $\\sum_i x $\ntest',
+ 'test\n $\\sum_i x $', '$\\sum_i x $\n $\\sum_i x $']
+ renderer = fig.canvas.get_renderer()
+
+ def draw_box(ax, tt):
+ r = mpatches.Rectangle((0, 0), 1, 1, clip_on=False,
+ transform=ax.transAxes)
+ r.set_bounds(
+ tt.get_window_extent(renderer)
+ .transformed(ax.transAxes.inverted())
+ .bounds)
+ ax.add_patch(r)
+
+ horal = 'left'
+ for nn, st in enumerate(sts):
+ tt = ax.text(0.2 * nn + 0.1, 0.5, st, horizontalalignment=horal,
+ verticalalignment='bottom')
+ draw_box(ax, tt)
+ ax.text(1.2, 0.5, 'Bottom align', color='C2')
+
+ ax.axhline(1.3, color='C2', linewidth=0.3)
+ for nn, st in enumerate(sts):
+ tt = ax.text(0.2 * nn + 0.1, 1.3, st, horizontalalignment=horal,
+ verticalalignment='top')
+ draw_box(ax, tt)
+ ax.text(1.2, 1.3, 'Top align', color='C2')
+
+ ax.axhline(1.8, color='C2', linewidth=0.3)
+ for nn, st in enumerate(sts):
+ tt = ax.text(0.2 * nn + 0.1, 1.8, st, horizontalalignment=horal,
+ verticalalignment='baseline')
+ draw_box(ax, tt)
+ ax.text(1.2, 1.8, 'Baseline align', color='C2')
+
+ ax.axhline(0.1, color='C2', linewidth=0.3)
+ for nn, st in enumerate(sts):
+ tt = ax.text(0.2 * nn + 0.1, 0.1, st, horizontalalignment=horal,
+ verticalalignment='bottom', rotation=20)
+ draw_box(ax, tt)
+ ax.text(1.2, 0.1, 'Bot align, rot20', color='C2')
+
+
+@image_comparison(['antialiased.png'], style='mpl20')
+def test_antialiasing():
+ mpl.rcParams['text.antialiased'] = False # Passed arguments should override.
+
+ fig = plt.figure(figsize=(5.25, 0.75))
+ fig.text(0.3, 0.75, "antialiased", horizontalalignment='center',
+ verticalalignment='center', antialiased=True)
+ fig.text(0.3, 0.25, r"$\sqrt{x}$", horizontalalignment='center',
+ verticalalignment='center', antialiased=True)
+
+ mpl.rcParams['text.antialiased'] = True # Passed arguments should override.
+ fig.text(0.7, 0.75, "not antialiased", horizontalalignment='center',
+ verticalalignment='center', antialiased=False)
+ fig.text(0.7, 0.25, r"$\sqrt{x}$", horizontalalignment='center',
+ verticalalignment='center', antialiased=False)
+
+ mpl.rcParams['text.antialiased'] = False # Should not affect existing text.
+
+
+def test_afm_kerning():
+ fn = mpl.font_manager.findfont("Helvetica", fontext="afm")
+ with open(fn, 'rb') as fh:
+ afm = mpl._afm.AFM(fh)
+ assert afm.string_width_height('VAVAVAVAVAVA') == (7174.0, 718)
+
+
+@image_comparison(['text_contains.png'])
+def test_contains():
+ fig = plt.figure()
+ ax = plt.axes()
+
+ mevent = MouseEvent('button_press_event', fig.canvas, 0.5, 0.5, 1, None)
+
+ xs = np.linspace(0.25, 0.75, 30)
+ ys = np.linspace(0.25, 0.75, 30)
+ xs, ys = np.meshgrid(xs, ys)
+
+ txt = plt.text(
+ 0.5, 0.4, 'hello world', ha='center', fontsize=30, rotation=30)
+ # uncomment to draw the text's bounding box
+ # txt.set_bbox(dict(edgecolor='black', facecolor='none'))
+
+ # draw the text. This is important, as the contains method can only work
+ # when a renderer exists.
+ fig.canvas.draw()
+
+ for x, y in zip(xs.flat, ys.flat):
+ mevent.x, mevent.y = plt.gca().transAxes.transform([x, y])
+ contains, _ = txt.contains(mevent)
+ color = 'yellow' if contains else 'red'
+
+ # capture the viewLim, plot a point, and reset the viewLim
+ vl = ax.viewLim.frozen()
+ ax.plot(x, y, 'o', color=color)
+ ax.viewLim.set(vl)
+
+
+def test_annotation_contains():
+ # Check that Annotation.contains looks at the bboxes of the text and the
+ # arrow separately, not at the joint bbox.
+ fig, ax = plt.subplots()
+ ann = ax.annotate(
+ "hello", xy=(.4, .4), xytext=(.6, .6), arrowprops={"arrowstyle": "->"})
+ fig.canvas.draw() # Needed for the same reason as in test_contains.
+ event = MouseEvent(
+ "button_press_event", fig.canvas, *ax.transData.transform((.5, .6)))
+ assert ann.contains(event) == (False, {})
+
+
+@pytest.mark.parametrize('err, xycoords, match', (
+ (TypeError, print, "xycoords callable must return a BboxBase or Transform, not a"),
+ (TypeError, [0, 0], r"'xycoords' must be an instance of str, tuple"),
+ (ValueError, "foo", "'foo' is not a valid coordinate"),
+ (ValueError, "foo bar", "'foo bar' is not a valid coordinate"),
+ (ValueError, "offset foo", "xycoords cannot be an offset coordinate"),
+ (ValueError, "axes foo", "'foo' is not a recognized unit"),
+))
+def test_annotate_errors(err, xycoords, match):
+ fig, ax = plt.subplots()
+ with pytest.raises(err, match=match):
+ ax.annotate('xy', (0, 0), xytext=(0.5, 0.5), xycoords=xycoords)
+ fig.canvas.draw()
+
+
+@image_comparison(['titles'])
+def test_titles():
+ # left and right side titles
+ plt.figure()
+ ax = plt.subplot(1, 1, 1)
+ ax.set_title("left title", loc="left")
+ ax.set_title("right title", loc="right")
+ ax.set_xticks([])
+ ax.set_yticks([])
+
+
+@image_comparison(['text_alignment'], style='mpl20')
+def test_alignment():
+ plt.figure()
+ ax = plt.subplot(1, 1, 1)
+
+ x = 0.1
+ for rotation in (0, 30):
+ for alignment in ('top', 'bottom', 'baseline', 'center'):
+ ax.text(
+ x, 0.5, alignment + " Tj", va=alignment, rotation=rotation,
+ bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.5))
+ ax.text(
+ x, 1.0, r'$\sum_{i=0}^{j}$', va=alignment, rotation=rotation)
+ x += 0.1
+
+ ax.plot([0, 1], [0.5, 0.5])
+ ax.plot([0, 1], [1.0, 1.0])
+
+ ax.set_xlim(0, 1)
+ ax.set_ylim(0, 1.5)
+ ax.set_xticks([])
+ ax.set_yticks([])
+
+
+@image_comparison(['axes_titles.png'])
+def test_axes_titles():
+ # Related to issue #3327
+ plt.figure()
+ ax = plt.subplot(1, 1, 1)
+ ax.set_title('center', loc='center', fontsize=20, fontweight=700)
+ ax.set_title('left', loc='left', fontsize=12, fontweight=400)
+ ax.set_title('right', loc='right', fontsize=12, fontweight=400)
+
+
+def test_set_position():
+ fig, ax = plt.subplots()
+
+ # test set_position
+ ann = ax.annotate(
+ 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
+ fig.canvas.draw()
+
+ init_pos = ann.get_window_extent(fig.canvas.renderer)
+ shift_val = 15
+ ann.set_position((shift_val, shift_val))
+ fig.canvas.draw()
+ post_pos = ann.get_window_extent(fig.canvas.renderer)
+
+ for a, b in zip(init_pos.min, post_pos.min):
+ assert a + shift_val == b
+
+ # test xyann
+ ann = ax.annotate(
+ 'test', (0, 0), xytext=(0, 0), textcoords='figure pixels')
+ fig.canvas.draw()
+
+ init_pos = ann.get_window_extent(fig.canvas.renderer)
+ shift_val = 15
+ ann.xyann = (shift_val, shift_val)
+ fig.canvas.draw()
+ post_pos = ann.get_window_extent(fig.canvas.renderer)
+
+ for a, b in zip(init_pos.min, post_pos.min):
+ assert a + shift_val == b
+
+
+def test_char_index_at():
+ fig = plt.figure()
+ text = fig.text(0.1, 0.9, "")
+
+ text.set_text("i")
+ bbox = text.get_window_extent()
+ size_i = bbox.x1 - bbox.x0
+
+ text.set_text("m")
+ bbox = text.get_window_extent()
+ size_m = bbox.x1 - bbox.x0
+
+ text.set_text("iiiimmmm")
+ bbox = text.get_window_extent()
+ origin = bbox.x0
+
+ assert text._char_index_at(origin - size_i) == 0 # left of first char
+ assert text._char_index_at(origin) == 0
+ assert text._char_index_at(origin + 0.499*size_i) == 0
+ assert text._char_index_at(origin + 0.501*size_i) == 1
+ assert text._char_index_at(origin + size_i*3) == 3
+ assert text._char_index_at(origin + size_i*4 + size_m*3) == 7
+ assert text._char_index_at(origin + size_i*4 + size_m*4) == 8
+ assert text._char_index_at(origin + size_i*4 + size_m*10) == 8
+
+
+@pytest.mark.parametrize('text', ['', 'O'], ids=['empty', 'non-empty'])
+def test_non_default_dpi(text):
+ fig, ax = plt.subplots()
+
+ t1 = ax.text(0.5, 0.5, text, ha='left', va='bottom')
+ fig.canvas.draw()
+ dpi = fig.dpi
+
+ bbox1 = t1.get_window_extent()
+ bbox2 = t1.get_window_extent(dpi=dpi * 10)
+ np.testing.assert_allclose(bbox2.get_points(), bbox1.get_points() * 10,
+ rtol=5e-2)
+ # Text.get_window_extent should not permanently change dpi.
+ assert fig.dpi == dpi
+
+
+def test_get_rotation_string():
+ assert Text(rotation='horizontal').get_rotation() == 0.
+ assert Text(rotation='vertical').get_rotation() == 90.
+
+
+def test_get_rotation_float():
+ for i in [15., 16.70, 77.4]:
+ assert Text(rotation=i).get_rotation() == i
+
+
+def test_get_rotation_int():
+ for i in [67, 16, 41]:
+ assert Text(rotation=i).get_rotation() == float(i)
+
+
+def test_get_rotation_raises():
+ with pytest.raises(ValueError):
+ Text(rotation='hozirontal')
+
+
+def test_get_rotation_none():
+ assert Text(rotation=None).get_rotation() == 0.0
+
+
+def test_get_rotation_mod360():
+ for i, j in zip([360., 377., 720+177.2], [0., 17., 177.2]):
+ assert_almost_equal(Text(rotation=i).get_rotation(), j)
+
+
+@pytest.mark.parametrize("ha", ["center", "right", "left"])
+@pytest.mark.parametrize("va", ["center", "top", "bottom",
+ "baseline", "center_baseline"])
+def test_null_rotation_with_rotation_mode(ha, va):
+ fig, ax = plt.subplots()
+ kw = dict(rotation=0, va=va, ha=ha)
+ t0 = ax.text(.5, .5, 'test', rotation_mode='anchor', **kw)
+ t1 = ax.text(.5, .5, 'test', rotation_mode='default', **kw)
+ fig.canvas.draw()
+ assert_almost_equal(t0.get_window_extent(fig.canvas.renderer).get_points(),
+ t1.get_window_extent(fig.canvas.renderer).get_points())
+
+
+@image_comparison(['text_bboxclip'])
+def test_bbox_clipping():
+ plt.text(0.9, 0.2, 'Is bbox clipped?', backgroundcolor='r', clip_on=True)
+ t = plt.text(0.9, 0.5, 'Is fancy bbox clipped?', clip_on=True)
+ t.set_bbox({"boxstyle": "round, pad=0.1"})
+
+
+@image_comparison(['annotation_negative_ax_coords.png'])
+def test_annotation_negative_ax_coords():
+ fig, ax = plt.subplots()
+
+ ax.annotate('+ pts',
+ xytext=[30, 20], textcoords='axes points',
+ xy=[30, 20], xycoords='axes points', fontsize=32)
+ ax.annotate('- pts',
+ xytext=[30, -20], textcoords='axes points',
+ xy=[30, -20], xycoords='axes points', fontsize=32,
+ va='top')
+ ax.annotate('+ frac',
+ xytext=[0.75, 0.05], textcoords='axes fraction',
+ xy=[0.75, 0.05], xycoords='axes fraction', fontsize=32)
+ ax.annotate('- frac',
+ xytext=[0.75, -0.05], textcoords='axes fraction',
+ xy=[0.75, -0.05], xycoords='axes fraction', fontsize=32,
+ va='top')
+
+ ax.annotate('+ pixels',
+ xytext=[160, 25], textcoords='axes pixels',
+ xy=[160, 25], xycoords='axes pixels', fontsize=32)
+ ax.annotate('- pixels',
+ xytext=[160, -25], textcoords='axes pixels',
+ xy=[160, -25], xycoords='axes pixels', fontsize=32,
+ va='top')
+
+
+@image_comparison(['annotation_negative_fig_coords.png'])
+def test_annotation_negative_fig_coords():
+ fig, ax = plt.subplots()
+
+ ax.annotate('+ pts',
+ xytext=[10, 120], textcoords='figure points',
+ xy=[10, 120], xycoords='figure points', fontsize=32)
+ ax.annotate('- pts',
+ xytext=[-10, 180], textcoords='figure points',
+ xy=[-10, 180], xycoords='figure points', fontsize=32,
+ va='top')
+ ax.annotate('+ frac',
+ xytext=[0.05, 0.55], textcoords='figure fraction',
+ xy=[0.05, 0.55], xycoords='figure fraction', fontsize=32)
+ ax.annotate('- frac',
+ xytext=[-0.05, 0.5], textcoords='figure fraction',
+ xy=[-0.05, 0.5], xycoords='figure fraction', fontsize=32,
+ va='top')
+
+ ax.annotate('+ pixels',
+ xytext=[50, 50], textcoords='figure pixels',
+ xy=[50, 50], xycoords='figure pixels', fontsize=32)
+ ax.annotate('- pixels',
+ xytext=[-50, 100], textcoords='figure pixels',
+ xy=[-50, 100], xycoords='figure pixels', fontsize=32,
+ va='top')
+
+
+def test_text_stale():
+ fig, (ax1, ax2) = plt.subplots(1, 2)
+ plt.draw_all()
+ assert not ax1.stale
+ assert not ax2.stale
+ assert not fig.stale
+
+ txt1 = ax1.text(.5, .5, 'aardvark')
+ assert ax1.stale
+ assert txt1.stale
+ assert fig.stale
+
+ ann1 = ax2.annotate('aardvark', xy=[.5, .5])
+ assert ax2.stale
+ assert ann1.stale
+ assert fig.stale
+
+ plt.draw_all()
+ assert not ax1.stale
+ assert not ax2.stale
+ assert not fig.stale
+
+
+@image_comparison(['agg_text_clip.png'])
+def test_agg_text_clip():
+ np.random.seed(1)
+ fig, (ax1, ax2) = plt.subplots(2)
+ for x, y in np.random.rand(10, 2):
+ ax1.text(x, y, "foo", clip_on=True)
+ ax2.text(x, y, "foo")
+
+
+def test_text_size_binding():
+ mpl.rcParams['font.size'] = 10
+ fp = mpl.font_manager.FontProperties(size='large')
+ sz1 = fp.get_size_in_points()
+ mpl.rcParams['font.size'] = 100
+
+ assert sz1 == fp.get_size_in_points()
+
+
+@image_comparison(['font_scaling.pdf'])
+def test_font_scaling():
+ mpl.rcParams['pdf.fonttype'] = 42
+ fig, ax = plt.subplots(figsize=(6.4, 12.4))
+ ax.xaxis.set_major_locator(plt.NullLocator())
+ ax.yaxis.set_major_locator(plt.NullLocator())
+ ax.set_ylim(-10, 600)
+
+ for i, fs in enumerate(range(4, 43, 2)):
+ ax.text(0.1, i*30, f"{fs} pt font size", fontsize=fs)
+
+
+@pytest.mark.parametrize('spacing1, spacing2', [(0.4, 2), (2, 0.4), (2, 2)])
+def test_two_2line_texts(spacing1, spacing2):
+ text_string = 'line1\nline2'
+ fig = plt.figure()
+ renderer = fig.canvas.get_renderer()
+
+ text1 = fig.text(0.25, 0.5, text_string, linespacing=spacing1)
+ text2 = fig.text(0.25, 0.5, text_string, linespacing=spacing2)
+ fig.canvas.draw()
+
+ box1 = text1.get_window_extent(renderer=renderer)
+ box2 = text2.get_window_extent(renderer=renderer)
+
+ # line spacing only affects height
+ assert box1.width == box2.width
+ if spacing1 == spacing2:
+ assert box1.height == box2.height
+ else:
+ assert box1.height != box2.height
+
+
+def test_validate_linespacing():
+ with pytest.raises(TypeError):
+ plt.text(.25, .5, "foo", linespacing="abc")
+
+
+def test_nonfinite_pos():
+ fig, ax = plt.subplots()
+ ax.text(0, np.nan, 'nan')
+ ax.text(np.inf, 0, 'inf')
+ fig.canvas.draw()
+
+
+def test_hinting_factor_backends():
+ plt.rcParams['text.hinting_factor'] = 1
+ fig = plt.figure()
+ t = fig.text(0.5, 0.5, 'some text')
+
+ fig.savefig(io.BytesIO(), format='svg')
+ expected = t.get_window_extent().intervalx
+
+ fig.savefig(io.BytesIO(), format='png')
+ # Backends should apply hinting_factor consistently (within 10%).
+ np.testing.assert_allclose(t.get_window_extent().intervalx, expected,
+ rtol=0.1)
+
+
+@needs_usetex
+def test_usetex_is_copied():
+ # Indirectly tests that update_from (which is used to copy tick label
+ # properties) copies usetex state.
+ fig = plt.figure()
+ plt.rcParams["text.usetex"] = False
+ ax1 = fig.add_subplot(121)
+ plt.rcParams["text.usetex"] = True
+ ax2 = fig.add_subplot(122)
+ fig.canvas.draw()
+ for ax, usetex in [(ax1, False), (ax2, True)]:
+ for t in ax.xaxis.majorTicks:
+ assert t.label1.get_usetex() == usetex
+
+
+@needs_usetex
+def test_single_artist_usetex():
+ # Check that a single artist marked with usetex does not get passed through
+ # the mathtext parser at all (for the Agg backend) (the mathtext parser
+ # currently fails to parse \frac12, requiring \frac{1}{2} instead).
+ fig = plt.figure()
+ fig.text(.5, .5, r"$\frac12$", usetex=True)
+ fig.canvas.draw()
+
+
+@pytest.mark.parametrize("fmt", ["png", "pdf", "svg"])
+def test_single_artist_usenotex(fmt):
+ # Check that a single artist can be marked as not-usetex even though the
+ # rcParam is on ("2_2_2" fails if passed to TeX). This currently skips
+ # postscript output as the ps renderer doesn't support mixing usetex and
+ # non-usetex.
+ plt.rcParams["text.usetex"] = True
+ fig = plt.figure()
+ fig.text(.5, .5, "2_2_2", usetex=False)
+ fig.savefig(io.BytesIO(), format=fmt)
+
+
+@image_comparison(['text_as_path_opacity.svg'])
+def test_text_as_path_opacity():
+ plt.figure()
+ plt.gca().set_axis_off()
+ plt.text(0.25, 0.25, 'c', color=(0, 0, 0, 0.5))
+ plt.text(0.25, 0.5, 'a', alpha=0.5)
+ plt.text(0.25, 0.75, 'x', alpha=0.5, color=(0, 0, 0, 1))
+
+
+@image_comparison(['text_as_text_opacity.svg'])
+def test_text_as_text_opacity():
+ mpl.rcParams['svg.fonttype'] = 'none'
+ plt.figure()
+ plt.gca().set_axis_off()
+ plt.text(0.25, 0.25, '50% using `color`', color=(0, 0, 0, 0.5))
+ plt.text(0.25, 0.5, '50% using `alpha`', alpha=0.5)
+ plt.text(0.25, 0.75, '50% using `alpha` and 100% `color`', alpha=0.5,
+ color=(0, 0, 0, 1))
+
+
+def test_text_repr():
+ # smoketest to make sure text repr doesn't error for category
+ plt.plot(['A', 'B'], [1, 2])
+ repr(plt.text(['A'], 0.5, 'Boo'))
+
+
+def test_annotation_update():
+ fig, ax = plt.subplots(1, 1)
+ an = ax.annotate('annotation', xy=(0.5, 0.5))
+ extent1 = an.get_window_extent(fig.canvas.get_renderer())
+ fig.tight_layout()
+ extent2 = an.get_window_extent(fig.canvas.get_renderer())
+
+ assert not np.allclose(extent1.get_points(), extent2.get_points(),
+ rtol=1e-6)
+
+
+@check_figures_equal(extensions=["png"])
+def test_annotation_units(fig_test, fig_ref):
+ ax = fig_test.add_subplot()
+ ax.plot(datetime.now(), 1, "o") # Implicitly set axes extents.
+ ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"),
+ # This used to crash before.
+ xytext=(0, 0), textcoords="offset points")
+ ax = fig_ref.add_subplot()
+ ax.plot(datetime.now(), 1, "o")
+ ax.annotate("x", (datetime.now(), 0.5), xycoords=("data", "axes fraction"))
+
+
+@image_comparison(['large_subscript_title.png'], style='mpl20')
+def test_large_subscript_title():
+ # Remove this line when this test image is regenerated.
+ plt.rcParams['text.kerning_factor'] = 6
+ plt.rcParams['axes.titley'] = None
+
+ fig, axs = plt.subplots(1, 2, figsize=(9, 2.5), constrained_layout=True)
+ ax = axs[0]
+ ax.set_title(r'$\sum_{i} x_i$')
+ ax.set_title('New way', loc='left')
+ ax.set_xticklabels([])
+
+ ax = axs[1]
+ ax.set_title(r'$\sum_{i} x_i$', y=1.01)
+ ax.set_title('Old Way', loc='left')
+ ax.set_xticklabels([])
+
+
+@pytest.mark.parametrize(
+ "x, rotation, halign",
+ [(0.7, 0, 'left'),
+ (0.5, 95, 'left'),
+ (0.3, 0, 'right'),
+ (0.3, 185, 'left')])
+def test_wrap(x, rotation, halign):
+ fig = plt.figure(figsize=(18, 18))
+ gs = GridSpec(nrows=3, ncols=3, figure=fig)
+ subfig = fig.add_subfigure(gs[1, 1])
+ # we only use the central subfigure, which does not align with any
+ # figure boundary, to ensure only subfigure boundaries are relevant
+ s = 'This is a very long text that should be wrapped multiple times.'
+ text = subfig.text(x, 0.7, s, wrap=True, rotation=rotation, ha=halign)
+ fig.canvas.draw()
+ assert text._get_wrapped_text() == ('This is a very long\n'
+ 'text that should be\n'
+ 'wrapped multiple\n'
+ 'times.')
+
+
+def test_mathwrap():
+ fig = plt.figure(figsize=(6, 4))
+ s = r'This is a very $\overline{\mathrm{long}}$ line of Mathtext.'
+ text = fig.text(0, 0.5, s, size=40, wrap=True)
+ fig.canvas.draw()
+ assert text._get_wrapped_text() == ('This is a very $\\overline{\\mathrm{long}}$\n'
+ 'line of Mathtext.')
+
+
+def test_get_window_extent_wrapped():
+ # Test that a long title that wraps to two lines has the same vertical
+ # extent as an explicit two line title.
+
+ fig1 = plt.figure(figsize=(3, 3))
+ fig1.suptitle("suptitle that is clearly too long in this case", wrap=True)
+ window_extent_test = fig1._suptitle.get_window_extent()
+
+ fig2 = plt.figure(figsize=(3, 3))
+ fig2.suptitle("suptitle that is clearly\ntoo long in this case")
+ window_extent_ref = fig2._suptitle.get_window_extent()
+
+ assert window_extent_test.y0 == window_extent_ref.y0
+ assert window_extent_test.y1 == window_extent_ref.y1
+
+
+def test_long_word_wrap():
+ fig = plt.figure(figsize=(6, 4))
+ text = fig.text(9.5, 8, 'Alonglineoftexttowrap', wrap=True)
+ fig.canvas.draw()
+ assert text._get_wrapped_text() == 'Alonglineoftexttowrap'
+
+
+def test_wrap_no_wrap():
+ fig = plt.figure(figsize=(6, 4))
+ text = fig.text(0, 0, 'non wrapped text', wrap=True)
+ fig.canvas.draw()
+ assert text._get_wrapped_text() == 'non wrapped text'
+
+
+@check_figures_equal(extensions=["png"])
+def test_buffer_size(fig_test, fig_ref):
+ # On old versions of the Agg renderer, large non-ascii single-character
+ # strings (here, "€") would be rendered clipped because the rendering
+ # buffer would be set by the physical size of the smaller "a" character.
+ ax = fig_test.add_subplot()
+ ax.set_yticks([0, 1])
+ ax.set_yticklabels(["€", "a"])
+ ax.yaxis.majorTicks[1].label1.set_color("w")
+ ax = fig_ref.add_subplot()
+ ax.set_yticks([0, 1])
+ ax.set_yticklabels(["€", ""])
+
+
+def test_fontproperties_kwarg_precedence():
+ """Test that kwargs take precedence over fontproperties defaults."""
+ plt.figure()
+ text1 = plt.xlabel("value", fontproperties='Times New Roman', size=40.0)
+ text2 = plt.ylabel("counts", size=40.0, fontproperties='Times New Roman')
+ assert text1.get_size() == 40.0
+ assert text2.get_size() == 40.0
+
+
+def test_transform_rotates_text():
+ ax = plt.gca()
+ transform = mtransforms.Affine2D().rotate_deg(30)
+ text = ax.text(0, 0, 'test', transform=transform,
+ transform_rotates_text=True)
+ result = text.get_rotation()
+ assert_almost_equal(result, 30)
+
+
+def test_update_mutate_input():
+ inp = dict(fontproperties=FontProperties(weight="bold"),
+ bbox=None)
+ cache = dict(inp)
+ t = Text()
+ t.update(inp)
+ assert inp['fontproperties'] == cache['fontproperties']
+ assert inp['bbox'] == cache['bbox']
+
+
+@pytest.mark.parametrize('rotation', ['invalid string', [90]])
+def test_invalid_rotation_values(rotation):
+ with pytest.raises(
+ ValueError,
+ match=("rotation must be 'vertical', 'horizontal' or a number")):
+ Text(0, 0, 'foo', rotation=rotation)
+
+
+def test_invalid_color():
+ with pytest.raises(ValueError):
+ plt.figtext(.5, .5, "foo", c="foobar")
+
+
+@image_comparison(['text_pdf_kerning.pdf'], style='mpl20')
+def test_pdf_kerning():
+ plt.figure()
+ plt.figtext(0.1, 0.5, "ATATATATATATATATATA", size=30)
+
+
+def test_unsupported_script(recwarn):
+ fig = plt.figure()
+ t = fig.text(.5, .5, "\N{BENGALI DIGIT ZERO}")
+ fig.canvas.draw()
+ assert all(isinstance(warn.message, UserWarning) for warn in recwarn)
+ assert (
+ [warn.message.args for warn in recwarn] ==
+ [(r"Glyph 2534 (\N{BENGALI DIGIT ZERO}) missing from font(s) "
+ + f"{t.get_fontname()}.",),
+ (r"Matplotlib currently does not support Bengali natively.",)])
+
+
+# See gh-26152 for more information on this xfail
+@pytest.mark.xfail(pyparsing_version.release == (3, 1, 0),
+ reason="Error messages are incorrect with pyparsing 3.1.0")
+def test_parse_math():
+ fig, ax = plt.subplots()
+ ax.text(0, 0, r"$ \wrong{math} $", parse_math=False)
+ fig.canvas.draw()
+
+ ax.text(0, 0, r"$ \wrong{math} $", parse_math=True)
+ with pytest.raises(ValueError, match='Unknown symbol'):
+ fig.canvas.draw()
+
+
+# See gh-26152 for more information on this xfail
+@pytest.mark.xfail(pyparsing_version.release == (3, 1, 0),
+ reason="Error messages are incorrect with pyparsing 3.1.0")
+def test_parse_math_rcparams():
+ # Default is True
+ fig, ax = plt.subplots()
+ ax.text(0, 0, r"$ \wrong{math} $")
+ with pytest.raises(ValueError, match='Unknown symbol'):
+ fig.canvas.draw()
+
+ # Setting rcParams to False
+ with mpl.rc_context({'text.parse_math': False}):
+ fig, ax = plt.subplots()
+ ax.text(0, 0, r"$ \wrong{math} $")
+ fig.canvas.draw()
+
+
+@image_comparison(['text_pdf_font42_kerning.pdf'], style='mpl20')
+def test_pdf_font42_kerning():
+ plt.rcParams['pdf.fonttype'] = 42
+ plt.figure()
+ plt.figtext(0.1, 0.5, "ATAVATAVATAVATAVATA", size=30)
+
+
+@image_comparison(['text_pdf_chars_beyond_bmp.pdf'], style='mpl20')
+def test_pdf_chars_beyond_bmp():
+ plt.rcParams['pdf.fonttype'] = 42
+ plt.rcParams['mathtext.fontset'] = 'stixsans'
+ plt.figure()
+ plt.figtext(0.1, 0.5, "Mass $m$ \U00010308", size=30)
+
+
+@needs_usetex
+def test_metrics_cache():
+ mpl.text._get_text_metrics_with_cache_impl.cache_clear()
+
+ fig = plt.figure()
+ fig.text(.3, .5, "foo\nbar")
+ fig.text(.3, .5, "foo\nbar", usetex=True)
+ fig.text(.5, .5, "foo\nbar", usetex=True)
+ fig.canvas.draw()
+ renderer = fig._get_renderer()
+ ys = {} # mapping of strings to where they were drawn in y with draw_tex.
+
+ def call(*args, **kwargs):
+ renderer, x, y, s, *_ = args
+ ys.setdefault(s, set()).add(y)
+
+ renderer.draw_tex = call
+ fig.canvas.draw()
+ assert [*ys] == ["foo", "bar"]
+ # Check that both TeX strings were drawn with the same y-position for both
+ # single-line substrings. Previously, there used to be an incorrect cache
+ # collision with the non-TeX string (drawn first here) whose metrics would
+ # get incorrectly reused by the first TeX string.
+ assert len(ys["foo"]) == len(ys["bar"]) == 1
+
+ info = mpl.text._get_text_metrics_with_cache_impl.cache_info()
+ # Every string gets a miss for the first layouting (extents), then a hit
+ # when drawing, but "foo\nbar" gets two hits as it's drawn twice.
+ assert info.hits > info.misses
+
+
+def test_annotate_offset_fontsize():
+ # Test that offset_fontsize parameter works and uses accurate values
+ fig, ax = plt.subplots()
+ text_coords = ['offset points', 'offset fontsize']
+ # 10 points should be equal to 1 fontsize unit at fontsize=10
+ xy_text = [(10, 10), (1, 1)]
+ anns = [ax.annotate('test', xy=(0.5, 0.5),
+ xytext=xy_text[i],
+ fontsize='10',
+ xycoords='data',
+ textcoords=text_coords[i]) for i in range(2)]
+ points_coords, fontsize_coords = (ann.get_window_extent() for ann in anns)
+ fig.canvas.draw()
+ assert str(points_coords) == str(fontsize_coords)
+
+
+def test_get_set_antialiased():
+ txt = Text(.5, .5, "foo\nbar")
+ assert txt._antialiased == mpl.rcParams['text.antialiased']
+ assert txt.get_antialiased() == mpl.rcParams['text.antialiased']
+
+ txt.set_antialiased(True)
+ assert txt._antialiased is True
+ assert txt.get_antialiased() == txt._antialiased
+
+ txt.set_antialiased(False)
+ assert txt._antialiased is False
+ assert txt.get_antialiased() == txt._antialiased
+
+
+def test_annotation_antialiased():
+ annot = Annotation("foo\nbar", (.5, .5), antialiased=True)
+ assert annot._antialiased is True
+ assert annot.get_antialiased() == annot._antialiased
+
+ annot2 = Annotation("foo\nbar", (.5, .5), antialiased=False)
+ assert annot2._antialiased is False
+ assert annot2.get_antialiased() == annot2._antialiased
+
+ annot3 = Annotation("foo\nbar", (.5, .5), antialiased=False)
+ annot3.set_antialiased(True)
+ assert annot3.get_antialiased() is True
+ assert annot3._antialiased is True
+
+ annot4 = Annotation("foo\nbar", (.5, .5))
+ assert annot4._antialiased == mpl.rcParams['text.antialiased']
+
+
+@check_figures_equal(extensions=["png"])
+def test_annotate_and_offsetfrom_copy_input(fig_test, fig_ref):
+ # Both approaches place the text (10, 0) pixels away from the center of the line.
+ ax = fig_test.add_subplot()
+ l, = ax.plot([0, 2], [0, 2])
+ of_xy = np.array([.5, .5])
+ ax.annotate("foo", textcoords=OffsetFrom(l, of_xy), xytext=(10, 0),
+ xy=(0, 0)) # xy is unused.
+ of_xy[:] = 1
+ ax = fig_ref.add_subplot()
+ l, = ax.plot([0, 2], [0, 2])
+ an_xy = np.array([.5, .5])
+ ax.annotate("foo", xy=an_xy, xycoords=l, xytext=(10, 0), textcoords="offset points")
+ an_xy[:] = 2
+
+
+@check_figures_equal()
+def test_text_antialiased_off_default_vs_manual(fig_test, fig_ref):
+ fig_test.text(0.5, 0.5, '6 inches x 2 inches',
+ antialiased=False)
+
+ mpl.rcParams['text.antialiased'] = False
+ fig_ref.text(0.5, 0.5, '6 inches x 2 inches')
+
+
+@check_figures_equal()
+def test_text_antialiased_on_default_vs_manual(fig_test, fig_ref):
+ fig_test.text(0.5, 0.5, '6 inches x 2 inches', antialiased=True)
+
+ mpl.rcParams['text.antialiased'] = True
+ fig_ref.text(0.5, 0.5, '6 inches x 2 inches')
+
+
+def test_text_annotation_get_window_extent():
+ figure = Figure(dpi=100)
+ renderer = RendererAgg(200, 200, 100)
+
+ # Only text annotation
+ annotation = Annotation('test', xy=(0, 0), xycoords='figure pixels')
+ annotation.set_figure(figure)
+
+ text = Text(text='test', x=0, y=0)
+ text.set_figure(figure)
+
+ bbox = annotation.get_window_extent(renderer=renderer)
+
+ text_bbox = text.get_window_extent(renderer=renderer)
+ assert bbox.width == text_bbox.width
+ assert bbox.height == text_bbox.height
+
+ _, _, d = renderer.get_text_width_height_descent(
+ 'text', annotation._fontproperties, ismath=False)
+ _, _, lp_d = renderer.get_text_width_height_descent(
+ 'lp', annotation._fontproperties, ismath=False)
+ below_line = max(d, lp_d)
+
+ # These numbers are specific to the current implementation of Text
+ points = bbox.get_points()
+ assert points[0, 0] == 0.0
+ assert points[1, 0] == text_bbox.width
+ assert points[0, 1] == -below_line
+ assert points[1, 1] == text_bbox.height - below_line
+
+
+def test_text_with_arrow_annotation_get_window_extent():
+ headwidth = 21
+ fig, ax = plt.subplots(dpi=100)
+ txt = ax.text(s='test', x=0, y=0)
+ ann = ax.annotate(
+ 'test',
+ xy=(0.0, 50.0),
+ xytext=(50.0, 50.0), xycoords='figure pixels',
+ arrowprops={
+ 'facecolor': 'black', 'width': 2,
+ 'headwidth': headwidth, 'shrink': 0.0})
+
+ plt.draw()
+ renderer = fig.canvas.renderer
+ # bounding box of text
+ text_bbox = txt.get_window_extent(renderer=renderer)
+ # bounding box of annotation (text + arrow)
+ bbox = ann.get_window_extent(renderer=renderer)
+ # bounding box of arrow
+ arrow_bbox = ann.arrow_patch.get_window_extent(renderer)
+ # bounding box of annotation text
+ ann_txt_bbox = Text.get_window_extent(ann)
+
+ # make sure annotation width is 50 px wider than
+ # just the text
+ assert bbox.width == text_bbox.width + 50.0
+ # make sure the annotation text bounding box is same size
+ # as the bounding box of the same string as a Text object
+ assert ann_txt_bbox.height == text_bbox.height
+ assert ann_txt_bbox.width == text_bbox.width
+ # compute the expected bounding box of arrow + text
+ expected_bbox = mtransforms.Bbox.union([ann_txt_bbox, arrow_bbox])
+ assert_almost_equal(bbox.height, expected_bbox.height)
+
+
+def test_arrow_annotation_get_window_extent():
+ dpi = 100
+ dots_per_point = dpi / 72
+ figure = Figure(dpi=dpi)
+ figure.set_figwidth(2.0)
+ figure.set_figheight(2.0)
+ renderer = RendererAgg(200, 200, 100)
+
+ # Text annotation with arrow; arrow dimensions are in points
+ annotation = Annotation(
+ '', xy=(0.0, 50.0), xytext=(50.0, 50.0), xycoords='figure pixels',
+ arrowprops={
+ 'facecolor': 'black', 'width': 8, 'headwidth': 10, 'shrink': 0.0})
+ annotation.set_figure(figure)
+ annotation.draw(renderer)
+
+ bbox = annotation.get_window_extent()
+ points = bbox.get_points()
+
+ assert bbox.width == 50.0
+ assert_almost_equal(bbox.height, 10.0 * dots_per_point)
+ assert points[0, 0] == 0.0
+ assert points[0, 1] == 50.0 - 5 * dots_per_point
+
+
+def test_empty_annotation_get_window_extent():
+ figure = Figure(dpi=100)
+ figure.set_figwidth(2.0)
+ figure.set_figheight(2.0)
+ renderer = RendererAgg(200, 200, 100)
+
+ # Text annotation with arrow
+ annotation = Annotation(
+ '', xy=(0.0, 50.0), xytext=(0.0, 50.0), xycoords='figure pixels')
+ annotation.set_figure(figure)
+ annotation.draw(renderer)
+
+ bbox = annotation.get_window_extent()
+ points = bbox.get_points()
+
+ assert points[0, 0] == 0.0
+ assert points[1, 0] == 0.0
+ assert points[1, 1] == 50.0
+ assert points[0, 1] == 50.0
+
+
+@image_comparison(baseline_images=['basictext_wrap'],
+ extensions=['png'])
+def test_basic_wrap():
+ fig = plt.figure()
+ plt.axis([0, 10, 0, 10])
+ t = "This is a really long string that I'd rather have wrapped so that" \
+ " it doesn't go outside of the figure, but if it's long enough it" \
+ " will go off the top or bottom!"
+ plt.text(4, 1, t, ha='left', rotation=15, wrap=True)
+ plt.text(6, 5, t, ha='left', rotation=15, wrap=True)
+ plt.text(5, 5, t, ha='right', rotation=-15, wrap=True)
+ plt.text(5, 10, t, fontsize=18, style='oblique', ha='center',
+ va='top', wrap=True)
+ plt.text(3, 4, t, family='serif', style='italic', ha='right', wrap=True)
+ plt.text(-1, 0, t, ha='left', rotation=-15, wrap=True)
+
+
+@image_comparison(baseline_images=['fonttext_wrap'],
+ extensions=['png'])
+def test_font_wrap():
+ fig = plt.figure()
+ plt.axis([0, 10, 0, 10])
+ t = "This is a really long string that I'd rather have wrapped so that" \
+ " it doesn't go outside of the figure, but if it's long enough it" \
+ " will go off the top or bottom!"
+ plt.text(4, -1, t, fontsize=18, family='serif', ha='left', rotation=15,
+ wrap=True)
+ plt.text(6, 5, t, family='sans serif', ha='left', rotation=15, wrap=True)
+ plt.text(5, 10, t, weight='heavy', ha='center', va='top', wrap=True)
+ plt.text(3, 4, t, family='monospace', ha='right', wrap=True)
+ plt.text(-1, 0, t, fontsize=14, style='italic', ha='left', rotation=-15,
+ wrap=True)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_textpath.py b/lib/python3.12/site-packages/matplotlib/tests/test_textpath.py
new file mode 100644
index 0000000000000000000000000000000000000000..e421d2623cadac7931f1f21148bdc0a603c290b1
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_textpath.py
@@ -0,0 +1,10 @@
+import copy
+
+from matplotlib.textpath import TextPath
+
+
+def test_copy():
+ tp = TextPath((0, 0), ".")
+ assert copy.deepcopy(tp).vertices is not tp.vertices
+ assert (copy.deepcopy(tp).vertices == tp.vertices).all()
+ assert copy.copy(tp).vertices is tp.vertices
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_ticker.py b/lib/python3.12/site-packages/matplotlib/tests/test_ticker.py
new file mode 100644
index 0000000000000000000000000000000000000000..77c0e917df8a1fd2c7deb450e3dd8b917391f3b8
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_ticker.py
@@ -0,0 +1,1939 @@
+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],
+ numticks=15 and change it to something else.
+ See if change was successful. Should not raise exception.
+ """
+ loc = mticker.LogLocator()
+ loc.set_params(numticks=7, subs=[2.0], base=4)
+ assert loc.numticks == 7
+ 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_array_equal(sym(), [-20, -40, -2, -4, 0, 2, 4, 20, 40])
+
+ 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']
+
+
+@pytest.mark.parametrize(
+ 'data_offset, noise, oom_center_desired, oom_noise_desired', [
+ (271_490_000_000.0, 10, 9, 0),
+ (27_149_000_000_000.0, 10_000_000, 12, 6),
+ (27.149, 0.01, 0, -3),
+ (2_714.9, 0.01, 3, -3),
+ (271_490.0, 0.001, 3, -3),
+ (271.49, 0.001, 0, -3),
+ # The following sets of parameters demonstrates that when
+ # oom(data_offset)-1 and oom(noise)-2 equal a standard 3*N oom, we get
+ # that oom_noise_desired < oom(noise)
+ (27_149_000_000.0, 100, 9, +3),
+ (27.149, 1e-07, 0, -6),
+ (271.49, 0.0001, 0, -3),
+ (27.149, 0.0001, 0, -3),
+ # Tests where oom(data_offset) <= oom(noise), those are probably
+ # covered by the part where formatter.offset != 0
+ (27_149.0, 10_000, 0, 3),
+ (27.149, 10_000, 0, 3),
+ (27.149, 1_000, 0, 3),
+ (27.149, 100, 0, 0),
+ (27.149, 10, 0, 0),
+ ]
+)
+def test_engformatter_offset_oom(
+ data_offset,
+ noise,
+ oom_center_desired,
+ oom_noise_desired
+):
+ UNIT = "eV"
+ fig, ax = plt.subplots()
+ ydata = data_offset + np.arange(-5, 7, dtype=float)*noise
+ ax.plot(ydata)
+ formatter = mticker.EngFormatter(useOffset=True, unit=UNIT)
+ # So that offset strings will always have the same size
+ formatter.ENG_PREFIXES[0] = "_"
+ ax.yaxis.set_major_formatter(formatter)
+ fig.canvas.draw()
+ offset_got = formatter.get_offset()
+ ticks_got = [labl.get_text() for labl in ax.get_yticklabels()]
+ # Predicting whether offset should be 0 or not is essentially testing
+ # ScalarFormatter._compute_offset . This function is pretty complex and it
+ # would be nice to test it, but this is out of scope for this test which
+ # only makes sure that offset text and the ticks gets the correct unit
+ # prefixes and the ticks.
+ if formatter.offset:
+ prefix_noise_got = offset_got[2]
+ prefix_noise_desired = formatter.ENG_PREFIXES[oom_noise_desired]
+ prefix_center_got = offset_got[-1-len(UNIT)]
+ prefix_center_desired = formatter.ENG_PREFIXES[oom_center_desired]
+ assert prefix_noise_desired == prefix_noise_got
+ assert prefix_center_desired == prefix_center_got
+ # Make sure the ticks didn't get the UNIT
+ for tick in ticks_got:
+ assert UNIT not in tick
+ else:
+ assert oom_center_desired == 0
+ assert offset_got == ""
+ # Make sure the ticks contain now the prefixes
+ for tick in ticks_got:
+ # 0 is zero on all orders of magnitudes, no matter what is
+ # oom_noise_desired
+ prefix_idx = 0 if tick[0] == "0" else oom_noise_desired
+ assert tick.endswith(formatter.ENG_PREFIXES[prefix_idx] + UNIT)
+
+
+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/lib/python3.12/site-packages/matplotlib/tests/test_tightlayout.py b/lib/python3.12/site-packages/matplotlib/tests/test_tightlayout.py
new file mode 100644
index 0000000000000000000000000000000000000000..f6b6d8f644cc50537a7466fa7548a97833033e48
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_tightlayout.py
@@ -0,0 +1,430 @@
+import warnings
+
+import numpy as np
+from numpy.testing import assert_array_equal
+import pytest
+
+import matplotlib as mpl
+from matplotlib.testing.decorators import image_comparison
+import matplotlib.pyplot as plt
+from matplotlib.offsetbox import AnchoredOffsetbox, DrawingArea
+from matplotlib.patches import Rectangle
+
+
+pytestmark = [
+ pytest.mark.usefixtures('text_placeholders')
+]
+
+
+def example_plot(ax, fontsize=12):
+ ax.plot([1, 2])
+ ax.locator_params(nbins=3)
+ ax.set_xlabel('x-label', fontsize=fontsize)
+ ax.set_ylabel('y-label', fontsize=fontsize)
+ ax.set_title('Title', fontsize=fontsize)
+
+
+@image_comparison(['tight_layout1'], style='mpl20')
+def test_tight_layout1():
+ """Test tight_layout for a single subplot."""
+ fig, ax = plt.subplots()
+ example_plot(ax, fontsize=24)
+ plt.tight_layout()
+
+
+@image_comparison(['tight_layout2'], style='mpl20')
+def test_tight_layout2():
+ """Test tight_layout for multiple subplots."""
+ fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)
+ example_plot(ax1)
+ example_plot(ax2)
+ example_plot(ax3)
+ example_plot(ax4)
+ plt.tight_layout()
+
+
+@image_comparison(['tight_layout3'], style='mpl20')
+def test_tight_layout3():
+ """Test tight_layout for multiple subplots."""
+ ax1 = plt.subplot(221)
+ ax2 = plt.subplot(223)
+ ax3 = plt.subplot(122)
+ example_plot(ax1)
+ example_plot(ax2)
+ example_plot(ax3)
+ plt.tight_layout()
+
+
+@image_comparison(['tight_layout4'], style='mpl20')
+def test_tight_layout4():
+ """Test tight_layout for subplot2grid."""
+ ax1 = plt.subplot2grid((3, 3), (0, 0))
+ ax2 = plt.subplot2grid((3, 3), (0, 1), colspan=2)
+ ax3 = plt.subplot2grid((3, 3), (1, 0), colspan=2, rowspan=2)
+ ax4 = plt.subplot2grid((3, 3), (1, 2), rowspan=2)
+ example_plot(ax1)
+ example_plot(ax2)
+ example_plot(ax3)
+ example_plot(ax4)
+ plt.tight_layout()
+
+
+@image_comparison(['tight_layout5'], style='mpl20')
+def test_tight_layout5():
+ """Test tight_layout for image."""
+ ax = plt.subplot()
+ arr = np.arange(100).reshape((10, 10))
+ ax.imshow(arr, interpolation="none")
+ plt.tight_layout()
+
+
+@image_comparison(['tight_layout6'], style='mpl20')
+def test_tight_layout6():
+ """Test tight_layout for gridspec."""
+
+ # This raises warnings since tight layout cannot
+ # do this fully automatically. But the test is
+ # correct since the layout is manually edited
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ fig = plt.figure()
+
+ gs1 = mpl.gridspec.GridSpec(2, 1)
+ ax1 = fig.add_subplot(gs1[0])
+ ax2 = fig.add_subplot(gs1[1])
+
+ example_plot(ax1)
+ example_plot(ax2)
+
+ gs1.tight_layout(fig, rect=[0, 0, 0.5, 1])
+
+ gs2 = mpl.gridspec.GridSpec(3, 1)
+
+ for ss in gs2:
+ ax = fig.add_subplot(ss)
+ example_plot(ax)
+ ax.set_title("")
+ ax.set_xlabel("")
+
+ ax.set_xlabel("x-label", fontsize=12)
+
+ gs2.tight_layout(fig, rect=[0.5, 0, 1, 1], h_pad=0.45)
+
+ top = min(gs1.top, gs2.top)
+ bottom = max(gs1.bottom, gs2.bottom)
+
+ gs1.tight_layout(fig, rect=[None, 0 + (bottom-gs1.bottom),
+ 0.5, 1 - (gs1.top-top)])
+ gs2.tight_layout(fig, rect=[0.5, 0 + (bottom-gs2.bottom),
+ None, 1 - (gs2.top-top)],
+ h_pad=0.45)
+
+
+@image_comparison(['tight_layout7'], style='mpl20')
+def test_tight_layout7():
+ # tight layout with left and right titles
+ fontsize = 24
+ fig, ax = plt.subplots()
+ ax.plot([1, 2])
+ ax.locator_params(nbins=3)
+ ax.set_xlabel('x-label', fontsize=fontsize)
+ ax.set_ylabel('y-label', fontsize=fontsize)
+ ax.set_title('Left Title', loc='left', fontsize=fontsize)
+ ax.set_title('Right Title', loc='right', fontsize=fontsize)
+ plt.tight_layout()
+
+
+@image_comparison(['tight_layout8'], style='mpl20', tol=0.005)
+def test_tight_layout8():
+ """Test automatic use of tight_layout."""
+ fig = plt.figure()
+ fig.set_layout_engine(layout='tight', pad=0.1)
+ ax = fig.add_subplot()
+ example_plot(ax, fontsize=24)
+ fig.draw_without_rendering()
+
+
+@image_comparison(['tight_layout9'], style='mpl20')
+def test_tight_layout9():
+ # Test tight_layout for non-visible subplots
+ # GH 8244
+ f, axarr = plt.subplots(2, 2)
+ axarr[1][1].set_visible(False)
+ plt.tight_layout()
+
+
+def test_outward_ticks():
+ """Test automatic use of tight_layout."""
+ fig = plt.figure()
+ ax = fig.add_subplot(221)
+ ax.xaxis.set_tick_params(tickdir='out', length=16, width=3)
+ ax.yaxis.set_tick_params(tickdir='out', length=16, width=3)
+ ax.xaxis.set_tick_params(
+ tickdir='out', length=32, width=3, tick1On=True, which='minor')
+ ax.yaxis.set_tick_params(
+ tickdir='out', length=32, width=3, tick1On=True, which='minor')
+ ax.xaxis.set_ticks([0], minor=True)
+ ax.yaxis.set_ticks([0], minor=True)
+ ax = fig.add_subplot(222)
+ ax.xaxis.set_tick_params(tickdir='in', length=32, width=3)
+ ax.yaxis.set_tick_params(tickdir='in', length=32, width=3)
+ ax = fig.add_subplot(223)
+ ax.xaxis.set_tick_params(tickdir='inout', length=32, width=3)
+ ax.yaxis.set_tick_params(tickdir='inout', length=32, width=3)
+ ax = fig.add_subplot(224)
+ ax.xaxis.set_tick_params(tickdir='out', length=32, width=3)
+ ax.yaxis.set_tick_params(tickdir='out', length=32, width=3)
+ plt.tight_layout()
+ # These values were obtained after visual checking that they correspond
+ # to a tight layouting that did take the ticks into account.
+ expected = [
+ [[0.092, 0.605], [0.433, 0.933]],
+ [[0.581, 0.605], [0.922, 0.933]],
+ [[0.092, 0.138], [0.433, 0.466]],
+ [[0.581, 0.138], [0.922, 0.466]],
+ ]
+ for nn, ax in enumerate(fig.axes):
+ assert_array_equal(np.round(ax.get_position().get_points(), 3),
+ expected[nn])
+
+
+def add_offsetboxes(ax, size=10, margin=.1, color='black'):
+ """
+ Surround ax with OffsetBoxes
+ """
+ m, mp = margin, 1+margin
+ anchor_points = [(-m, -m), (-m, .5), (-m, mp),
+ (.5, mp), (mp, mp), (mp, .5),
+ (mp, -m), (.5, -m)]
+ for point in anchor_points:
+ da = DrawingArea(size, size)
+ background = Rectangle((0, 0), width=size,
+ height=size,
+ facecolor=color,
+ edgecolor='None',
+ linewidth=0,
+ antialiased=False)
+ da.add_artist(background)
+
+ anchored_box = AnchoredOffsetbox(
+ loc='center',
+ child=da,
+ pad=0.,
+ frameon=False,
+ bbox_to_anchor=point,
+ bbox_transform=ax.transAxes,
+ borderpad=0.)
+ ax.add_artist(anchored_box)
+
+
+def test_tight_layout_offsetboxes():
+ # 0.
+ # - Create 4 subplots
+ # - Plot a diagonal line on them
+ # - Use tight_layout
+ #
+ # 1.
+ # - Same 4 subplots
+ # - Surround each plot with 7 boxes
+ # - Use tight_layout
+ # - See that the squares are included in the tight_layout and that the squares do
+ # not overlap
+ #
+ # 2.
+ # - Make the squares around the Axes invisible
+ # - See that the invisible squares do not affect the tight_layout
+ rows = cols = 2
+ colors = ['red', 'blue', 'green', 'yellow']
+ x = y = [0, 1]
+
+ def _subplots(with_boxes):
+ fig, axs = plt.subplots(rows, cols)
+ for ax, color in zip(axs.flat, colors):
+ ax.plot(x, y, color=color)
+ if with_boxes:
+ add_offsetboxes(ax, 20, color=color)
+ return fig, axs
+
+ # 0.
+ fig0, axs0 = _subplots(False)
+ fig0.tight_layout()
+
+ # 1.
+ fig1, axs1 = _subplots(True)
+ fig1.tight_layout()
+
+ # The AnchoredOffsetbox should be added to the bounding of the Axes, causing them to
+ # be smaller than the plain figure.
+ for ax0, ax1 in zip(axs0.flat, axs1.flat):
+ bbox0 = ax0.get_position()
+ bbox1 = ax1.get_position()
+ assert bbox1.x0 > bbox0.x0
+ assert bbox1.x1 < bbox0.x1
+ assert bbox1.y0 > bbox0.y0
+ assert bbox1.y1 < bbox0.y1
+
+ # No AnchoredOffsetbox should overlap with another.
+ bboxes = []
+ for ax1 in axs1.flat:
+ for child in ax1.get_children():
+ if not isinstance(child, AnchoredOffsetbox):
+ continue
+ bbox = child.get_window_extent()
+ for other_bbox in bboxes:
+ assert not bbox.overlaps(other_bbox)
+ bboxes.append(bbox)
+
+ # 2.
+ fig2, axs2 = _subplots(True)
+ for ax in axs2.flat:
+ for child in ax.get_children():
+ if isinstance(child, AnchoredOffsetbox):
+ child.set_visible(False)
+ fig2.tight_layout()
+ # The invisible AnchoredOffsetbox should not count for tight layout, so it should
+ # look the same as when they were never added.
+ for ax0, ax2 in zip(axs0.flat, axs2.flat):
+ bbox0 = ax0.get_position()
+ bbox2 = ax2.get_position()
+ assert_array_equal(bbox2.get_points(), bbox0.get_points())
+
+
+def test_empty_layout():
+ """Test that tight layout doesn't cause an error when there are no Axes."""
+ fig = plt.gcf()
+ fig.tight_layout()
+
+
+@pytest.mark.parametrize("label", ["xlabel", "ylabel"])
+def test_verybig_decorators(label):
+ """Test that no warning emitted when xlabel/ylabel too big."""
+ fig, ax = plt.subplots(figsize=(3, 2))
+ ax.set(**{label: 'a' * 100})
+
+
+def test_big_decorators_horizontal():
+ """Test that doesn't warn when xlabel too big."""
+ fig, axs = plt.subplots(1, 2, figsize=(3, 2))
+ axs[0].set_xlabel('a' * 30)
+ axs[1].set_xlabel('b' * 30)
+
+
+def test_big_decorators_vertical():
+ """Test that doesn't warn when ylabel too big."""
+ fig, axs = plt.subplots(2, 1, figsize=(3, 2))
+ axs[0].set_ylabel('a' * 20)
+ axs[1].set_ylabel('b' * 20)
+
+
+def test_badsubplotgrid():
+ # test that we get warning for mismatched subplot grids, not than an error
+ plt.subplot2grid((4, 5), (0, 0))
+ # this is the bad entry:
+ plt.subplot2grid((5, 5), (0, 3), colspan=3, rowspan=5)
+ with pytest.warns(UserWarning):
+ plt.tight_layout()
+
+
+def test_collapsed():
+ # test that if the amount of space required to make all the axes
+ # decorations fit would mean that the actual Axes would end up with size
+ # zero (i.e. margins add up to more than the available width) that a call
+ # to tight_layout will not get applied:
+ fig, ax = plt.subplots(tight_layout=True)
+ ax.set_xlim([0, 1])
+ ax.set_ylim([0, 1])
+
+ ax.annotate('BIG LONG STRING', xy=(1.25, 2), xytext=(10.5, 1.75),
+ annotation_clip=False)
+ p1 = ax.get_position()
+ with pytest.warns(UserWarning):
+ plt.tight_layout()
+ p2 = ax.get_position()
+ assert p1.width == p2.width
+ # test that passing a rect doesn't crash...
+ with pytest.warns(UserWarning):
+ plt.tight_layout(rect=[0, 0, 0.8, 0.8])
+
+
+def test_suptitle():
+ fig, ax = plt.subplots(tight_layout=True)
+ st = fig.suptitle("foo")
+ t = ax.set_title("bar")
+ fig.canvas.draw()
+ assert st.get_window_extent().y0 > t.get_window_extent().y1
+
+
+@pytest.mark.backend("pdf")
+def test_non_agg_renderer(monkeypatch, recwarn):
+ unpatched_init = mpl.backend_bases.RendererBase.__init__
+
+ def __init__(self, *args, **kwargs):
+ # Check that we don't instantiate any other renderer than a pdf
+ # renderer to perform pdf tight layout.
+ assert isinstance(self, mpl.backends.backend_pdf.RendererPdf)
+ unpatched_init(self, *args, **kwargs)
+
+ monkeypatch.setattr(mpl.backend_bases.RendererBase, "__init__", __init__)
+ fig, ax = plt.subplots()
+ fig.tight_layout()
+
+
+def test_manual_colorbar():
+ # This should warn, but not raise
+ fig, axes = plt.subplots(1, 2)
+ pts = axes[1].scatter([0, 1], [0, 1], c=[1, 5])
+ ax_rect = axes[1].get_position()
+ cax = fig.add_axes(
+ [ax_rect.x1 + 0.005, ax_rect.y0, 0.015, ax_rect.height]
+ )
+ fig.colorbar(pts, cax=cax)
+ with pytest.warns(UserWarning, match="This figure includes Axes"):
+ fig.tight_layout()
+
+
+def test_clipped_to_axes():
+ # Ensure that _fully_clipped_to_axes() returns True under default
+ # conditions for all projection types. Axes.get_tightbbox()
+ # uses this to skip artists in layout calculations.
+ arr = np.arange(100).reshape((10, 10))
+ fig = plt.figure(figsize=(6, 2))
+ ax1 = fig.add_subplot(131, projection='rectilinear')
+ ax2 = fig.add_subplot(132, projection='mollweide')
+ ax3 = fig.add_subplot(133, projection='polar')
+ for ax in (ax1, ax2, ax3):
+ # Default conditions (clipped by ax.bbox or ax.patch)
+ ax.grid(False)
+ h, = ax.plot(arr[:, 0])
+ m = ax.pcolor(arr)
+ assert h._fully_clipped_to_axes()
+ assert m._fully_clipped_to_axes()
+ # Non-default conditions (not clipped by ax.patch)
+ rect = Rectangle((0, 0), 0.5, 0.5, transform=ax.transAxes)
+ h.set_clip_path(rect)
+ m.set_clip_path(rect.get_path(), rect.get_transform())
+ assert not h._fully_clipped_to_axes()
+ assert not m._fully_clipped_to_axes()
+
+
+def test_tight_pads():
+ fig, ax = plt.subplots()
+ with pytest.warns(PendingDeprecationWarning,
+ match='will be deprecated'):
+ fig.set_tight_layout({'pad': 0.15})
+ fig.draw_without_rendering()
+
+
+def test_tight_kwargs():
+ fig, ax = plt.subplots(tight_layout={'pad': 0.15})
+ fig.draw_without_rendering()
+
+
+def test_tight_toggle():
+ fig, ax = plt.subplots()
+ with pytest.warns(PendingDeprecationWarning):
+ fig.set_tight_layout(True)
+ assert fig.get_tight_layout()
+ fig.set_tight_layout(False)
+ assert not fig.get_tight_layout()
+ fig.set_tight_layout(True)
+ assert fig.get_tight_layout()
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_transforms.py b/lib/python3.12/site-packages/matplotlib/tests/test_transforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..96e78b6828f8d061ef61826678a7d5c91df8d884
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_transforms.py
@@ -0,0 +1,1131 @@
+import copy
+
+import numpy as np
+from numpy.testing import (assert_allclose, assert_almost_equal,
+ assert_array_equal, assert_array_almost_equal)
+import pytest
+
+from matplotlib import scale
+import matplotlib.pyplot as plt
+import matplotlib.patches as mpatches
+import matplotlib.transforms as mtransforms
+from matplotlib.transforms import Affine2D, Bbox, TransformedBbox, _ScaledRotation
+from matplotlib.path import Path
+from matplotlib.testing.decorators import image_comparison, check_figures_equal
+from unittest.mock import MagicMock
+
+
+class TestAffine2D:
+ single_point = [1.0, 1.0]
+ multiple_points = [[0.0, 2.0], [3.0, 3.0], [4.0, 0.0]]
+ pivot = single_point
+
+ def test_init(self):
+ Affine2D([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ Affine2D(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], int))
+ Affine2D(np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]], float))
+
+ def test_values(self):
+ np.random.seed(19680801)
+ values = np.random.random(6)
+ assert_array_equal(Affine2D.from_values(*values).to_values(), values)
+
+ def test_modify_inplace(self):
+ # Some polar transforms require modifying the matrix in place.
+ trans = Affine2D()
+ mtx = trans.get_matrix()
+ mtx[0, 0] = 42
+ assert_array_equal(trans.get_matrix(), [[42, 0, 0], [0, 1, 0], [0, 0, 1]])
+
+ def test_clear(self):
+ a = Affine2D(np.random.rand(3, 3) + 5) # Anything non-identity.
+ a.clear()
+ assert_array_equal(a.get_matrix(), [[1, 0, 0], [0, 1, 0], [0, 0, 1]])
+
+ def test_rotate(self):
+ r_pi_2 = Affine2D().rotate(np.pi / 2)
+ r90 = Affine2D().rotate_deg(90)
+ assert_array_equal(r_pi_2.get_matrix(), r90.get_matrix())
+ assert_array_almost_equal(r90.transform(self.single_point), [-1, 1])
+ assert_array_almost_equal(r90.transform(self.multiple_points),
+ [[-2, 0], [-3, 3], [0, 4]])
+
+ r_pi = Affine2D().rotate(np.pi)
+ r180 = Affine2D().rotate_deg(180)
+ assert_array_equal(r_pi.get_matrix(), r180.get_matrix())
+ assert_array_almost_equal(r180.transform(self.single_point), [-1, -1])
+ assert_array_almost_equal(r180.transform(self.multiple_points),
+ [[0, -2], [-3, -3], [-4, 0]])
+
+ r_pi_3_2 = Affine2D().rotate(3 * np.pi / 2)
+ r270 = Affine2D().rotate_deg(270)
+ assert_array_equal(r_pi_3_2.get_matrix(), r270.get_matrix())
+ assert_array_almost_equal(r270.transform(self.single_point), [1, -1])
+ assert_array_almost_equal(r270.transform(self.multiple_points),
+ [[2, 0], [3, -3], [0, -4]])
+
+ assert_array_equal((r90 + r90).get_matrix(), r180.get_matrix())
+ assert_array_equal((r90 + r180).get_matrix(), r270.get_matrix())
+
+ def test_rotate_around(self):
+ r_pi_2 = Affine2D().rotate_around(*self.pivot, np.pi / 2)
+ r90 = Affine2D().rotate_deg_around(*self.pivot, 90)
+ assert_array_equal(r_pi_2.get_matrix(), r90.get_matrix())
+ assert_array_almost_equal(r90.transform(self.single_point), [1, 1])
+ assert_array_almost_equal(r90.transform(self.multiple_points),
+ [[0, 0], [-1, 3], [2, 4]])
+
+ r_pi = Affine2D().rotate_around(*self.pivot, np.pi)
+ r180 = Affine2D().rotate_deg_around(*self.pivot, 180)
+ assert_array_equal(r_pi.get_matrix(), r180.get_matrix())
+ assert_array_almost_equal(r180.transform(self.single_point), [1, 1])
+ assert_array_almost_equal(r180.transform(self.multiple_points),
+ [[2, 0], [-1, -1], [-2, 2]])
+
+ r_pi_3_2 = Affine2D().rotate_around(*self.pivot, 3 * np.pi / 2)
+ r270 = Affine2D().rotate_deg_around(*self.pivot, 270)
+ assert_array_equal(r_pi_3_2.get_matrix(), r270.get_matrix())
+ assert_array_almost_equal(r270.transform(self.single_point), [1, 1])
+ assert_array_almost_equal(r270.transform(self.multiple_points),
+ [[2, 2], [3, -1], [0, -2]])
+
+ assert_array_almost_equal((r90 + r90).get_matrix(), r180.get_matrix())
+ assert_array_almost_equal((r90 + r180).get_matrix(), r270.get_matrix())
+
+ def test_scale(self):
+ sx = Affine2D().scale(3, 1)
+ sy = Affine2D().scale(1, -2)
+ trans = Affine2D().scale(3, -2)
+ assert_array_equal((sx + sy).get_matrix(), trans.get_matrix())
+ assert_array_equal(trans.transform(self.single_point), [3, -2])
+ assert_array_equal(trans.transform(self.multiple_points),
+ [[0, -4], [9, -6], [12, 0]])
+
+ def test_skew(self):
+ trans_rad = Affine2D().skew(np.pi / 8, np.pi / 12)
+ trans_deg = Affine2D().skew_deg(22.5, 15)
+ assert_array_equal(trans_rad.get_matrix(), trans_deg.get_matrix())
+ # Using ~atan(0.5), ~atan(0.25) produces roundish numbers on output.
+ trans = Affine2D().skew_deg(26.5650512, 14.0362435)
+ assert_array_almost_equal(trans.transform(self.single_point), [1.5, 1.25])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[1, 2], [4.5, 3.75], [4, 1]])
+
+ def test_translate(self):
+ tx = Affine2D().translate(23, 0)
+ ty = Affine2D().translate(0, 42)
+ trans = Affine2D().translate(23, 42)
+ assert_array_equal((tx + ty).get_matrix(), trans.get_matrix())
+ assert_array_equal(trans.transform(self.single_point), [24, 43])
+ assert_array_equal(trans.transform(self.multiple_points),
+ [[23, 44], [26, 45], [27, 42]])
+
+ def test_rotate_plus_other(self):
+ trans = Affine2D().rotate_deg(90).rotate_deg_around(*self.pivot, 180)
+ trans_added = (Affine2D().rotate_deg(90) +
+ Affine2D().rotate_deg_around(*self.pivot, 180))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [3, 1])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[4, 2], [5, -1], [2, -2]])
+
+ trans = Affine2D().rotate_deg(90).scale(3, -2)
+ trans_added = Affine2D().rotate_deg(90) + Affine2D().scale(3, -2)
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [-3, -2])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[-6, -0], [-9, -6], [0, -8]])
+
+ trans = (Affine2D().rotate_deg(90)
+ .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)
+ trans_added = (Affine2D().rotate_deg(90) +
+ Affine2D().skew_deg(26.5650512, 14.0362435))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [-0.5, 0.75])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[-2, -0.5], [-1.5, 2.25], [2, 4]])
+
+ trans = Affine2D().rotate_deg(90).translate(23, 42)
+ trans_added = Affine2D().rotate_deg(90) + Affine2D().translate(23, 42)
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [22, 43])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[21, 42], [20, 45], [23, 46]])
+
+ def test_rotate_around_plus_other(self):
+ trans = Affine2D().rotate_deg_around(*self.pivot, 90).rotate_deg(180)
+ trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +
+ Affine2D().rotate_deg(180))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [-1, -1])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[0, 0], [1, -3], [-2, -4]])
+
+ trans = Affine2D().rotate_deg_around(*self.pivot, 90).scale(3, -2)
+ trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +
+ Affine2D().scale(3, -2))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [3, -2])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[0, 0], [-3, -6], [6, -8]])
+
+ trans = (Affine2D().rotate_deg_around(*self.pivot, 90)
+ .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)
+ trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +
+ Affine2D().skew_deg(26.5650512, 14.0362435))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [1.5, 1.25])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[0, 0], [0.5, 2.75], [4, 4.5]])
+
+ trans = Affine2D().rotate_deg_around(*self.pivot, 90).translate(23, 42)
+ trans_added = (Affine2D().rotate_deg_around(*self.pivot, 90) +
+ Affine2D().translate(23, 42))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [24, 43])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[23, 42], [22, 45], [25, 46]])
+
+ def test_scale_plus_other(self):
+ trans = Affine2D().scale(3, -2).rotate_deg(90)
+ trans_added = Affine2D().scale(3, -2) + Affine2D().rotate_deg(90)
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_equal(trans.transform(self.single_point), [2, 3])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[4, 0], [6, 9], [0, 12]])
+
+ trans = Affine2D().scale(3, -2).rotate_deg_around(*self.pivot, 90)
+ trans_added = (Affine2D().scale(3, -2) +
+ Affine2D().rotate_deg_around(*self.pivot, 90))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_equal(trans.transform(self.single_point), [4, 3])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[6, 0], [8, 9], [2, 12]])
+
+ trans = (Affine2D().scale(3, -2)
+ .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)
+ trans_added = (Affine2D().scale(3, -2) +
+ Affine2D().skew_deg(26.5650512, 14.0362435))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [2, -1.25])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[-2, -4], [6, -3.75], [12, 3]])
+
+ trans = Affine2D().scale(3, -2).translate(23, 42)
+ trans_added = Affine2D().scale(3, -2) + Affine2D().translate(23, 42)
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_equal(trans.transform(self.single_point), [26, 40])
+ assert_array_equal(trans.transform(self.multiple_points),
+ [[23, 38], [32, 36], [35, 42]])
+
+ def test_skew_plus_other(self):
+ # Using ~atan(0.5), ~atan(0.25) produces roundish numbers on output.
+ trans = Affine2D().skew_deg(26.5650512, 14.0362435).rotate_deg(90)
+ trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +
+ Affine2D().rotate_deg(90))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [-1.25, 1.5])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[-2, 1], [-3.75, 4.5], [-1, 4]])
+
+ trans = (Affine2D().skew_deg(26.5650512, 14.0362435)
+ .rotate_deg_around(*self.pivot, 90))
+ trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +
+ Affine2D().rotate_deg_around(*self.pivot, 90))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [0.75, 1.5])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[0, 1], [-1.75, 4.5], [1, 4]])
+
+ trans = Affine2D().skew_deg(26.5650512, 14.0362435).scale(3, -2)
+ trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +
+ Affine2D().scale(3, -2))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [4.5, -2.5])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[3, -4], [13.5, -7.5], [12, -2]])
+
+ trans = Affine2D().skew_deg(26.5650512, 14.0362435).translate(23, 42)
+ trans_added = (Affine2D().skew_deg(26.5650512, 14.0362435) +
+ Affine2D().translate(23, 42))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [24.5, 43.25])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[24, 44], [27.5, 45.75], [27, 43]])
+
+ def test_translate_plus_other(self):
+ trans = Affine2D().translate(23, 42).rotate_deg(90)
+ trans_added = Affine2D().translate(23, 42) + Affine2D().rotate_deg(90)
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [-43, 24])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[-44, 23], [-45, 26], [-42, 27]])
+
+ trans = Affine2D().translate(23, 42).rotate_deg_around(*self.pivot, 90)
+ trans_added = (Affine2D().translate(23, 42) +
+ Affine2D().rotate_deg_around(*self.pivot, 90))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [-41, 24])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[-42, 23], [-43, 26], [-40, 27]])
+
+ trans = Affine2D().translate(23, 42).scale(3, -2)
+ trans_added = Affine2D().translate(23, 42) + Affine2D().scale(3, -2)
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [72, -86])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[69, -88], [78, -90], [81, -84]])
+
+ trans = (Affine2D().translate(23, 42)
+ .skew_deg(26.5650512, 14.0362435)) # ~atan(0.5), ~atan(0.25)
+ trans_added = (Affine2D().translate(23, 42) +
+ Affine2D().skew_deg(26.5650512, 14.0362435))
+ assert_array_equal(trans.get_matrix(), trans_added.get_matrix())
+ assert_array_almost_equal(trans.transform(self.single_point), [45.5, 49])
+ assert_array_almost_equal(trans.transform(self.multiple_points),
+ [[45, 49.75], [48.5, 51.5], [48, 48.75]])
+
+ def test_invalid_transform(self):
+ t = mtransforms.Affine2D()
+ # There are two different exceptions, since the wrong number of
+ # dimensions is caught when constructing an array_view, and that
+ # raises a ValueError, and a wrong shape with a possible number
+ # of dimensions is caught by our CALL_CPP macro, which always
+ # raises the less precise RuntimeError.
+ with pytest.raises(ValueError):
+ t.transform(1)
+ with pytest.raises(ValueError):
+ t.transform([[[1]]])
+ with pytest.raises(RuntimeError):
+ t.transform([])
+ with pytest.raises(RuntimeError):
+ t.transform([1])
+ with pytest.raises(ValueError):
+ t.transform([[1]])
+ with pytest.raises(ValueError):
+ t.transform([[1, 2, 3]])
+
+ def test_copy(self):
+ a = mtransforms.Affine2D()
+ b = mtransforms.Affine2D()
+ s = a + b
+ # Updating a dependee should invalidate a copy of the dependent.
+ s.get_matrix() # resolve it.
+ s1 = copy.copy(s)
+ assert not s._invalid and not s1._invalid
+ a.translate(1, 2)
+ assert s._invalid and s1._invalid
+ assert (s1.get_matrix() == a.get_matrix()).all()
+ # Updating a copy of a dependee shouldn't invalidate a dependent.
+ s.get_matrix() # resolve it.
+ b1 = copy.copy(b)
+ b1.translate(3, 4)
+ assert not s._invalid
+ assert_array_equal(s.get_matrix(), a.get_matrix())
+
+ def test_deepcopy(self):
+ a = mtransforms.Affine2D()
+ b = mtransforms.Affine2D()
+ s = a + b
+ # Updating a dependee shouldn't invalidate a deepcopy of the dependent.
+ s.get_matrix() # resolve it.
+ s1 = copy.deepcopy(s)
+ assert not s._invalid and not s1._invalid
+ a.translate(1, 2)
+ assert s._invalid and not s1._invalid
+ assert_array_equal(s1.get_matrix(), mtransforms.Affine2D().get_matrix())
+ # Updating a deepcopy of a dependee shouldn't invalidate a dependent.
+ s.get_matrix() # resolve it.
+ b1 = copy.deepcopy(b)
+ b1.translate(3, 4)
+ assert not s._invalid
+ assert_array_equal(s.get_matrix(), a.get_matrix())
+
+
+class TestAffineDeltaTransform:
+ def test_invalidate(self):
+ before = np.array([[1.0, 4.0, 0.0],
+ [5.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0]])
+ after = np.array([[1.0, 3.0, 0.0],
+ [5.0, 1.0, 0.0],
+ [0.0, 0.0, 1.0]])
+
+ # Translation and skew present
+ base = mtransforms.Affine2D.from_values(1, 5, 4, 1, 2, 3)
+ t = mtransforms.AffineDeltaTransform(base)
+ assert_array_equal(t.get_matrix(), before)
+
+ # Mess with the internal structure of `base` without invalidating
+ # This should not affect this transform because it's a passthrough:
+ # it's always invalid
+ base.get_matrix()[0, 1:] = 3
+ assert_array_equal(t.get_matrix(), after)
+
+ # Invalidate the base
+ base.invalidate()
+ assert_array_equal(t.get_matrix(), after)
+
+
+def test_non_affine_caching():
+ class AssertingNonAffineTransform(mtransforms.Transform):
+ """
+ This transform raises an assertion error when called when it
+ shouldn't be and ``self.raise_on_transform`` is True.
+
+ """
+ input_dims = output_dims = 2
+ is_affine = False
+
+ def __init__(self, *args, **kwargs):
+ super().__init__(*args, **kwargs)
+ self.raise_on_transform = False
+ self.underlying_transform = mtransforms.Affine2D().scale(10, 10)
+
+ def transform_path_non_affine(self, path):
+ assert not self.raise_on_transform, \
+ 'Invalidated affine part of transform unnecessarily.'
+ return self.underlying_transform.transform_path(path)
+ transform_path = transform_path_non_affine
+
+ def transform_non_affine(self, path):
+ assert not self.raise_on_transform, \
+ 'Invalidated affine part of transform unnecessarily.'
+ return self.underlying_transform.transform(path)
+ transform = transform_non_affine
+
+ my_trans = AssertingNonAffineTransform()
+ ax = plt.axes()
+ plt.plot(np.arange(10), transform=my_trans + ax.transData)
+ plt.draw()
+ # enable the transform to raise an exception if it's non-affine transform
+ # method is triggered again.
+ my_trans.raise_on_transform = True
+ ax.transAxes.invalidate()
+ plt.draw()
+
+
+def test_external_transform_api():
+ class ScaledBy:
+ def __init__(self, scale_factor):
+ self._scale_factor = scale_factor
+
+ def _as_mpl_transform(self, axes):
+ return (mtransforms.Affine2D().scale(self._scale_factor)
+ + axes.transData)
+
+ ax = plt.axes()
+ line, = plt.plot(np.arange(10), transform=ScaledBy(10))
+ ax.set_xlim(0, 100)
+ ax.set_ylim(0, 100)
+ # assert that the top transform of the line is the scale transform.
+ assert_allclose(line.get_transform()._a.get_matrix(),
+ mtransforms.Affine2D().scale(10).get_matrix())
+
+
+@image_comparison(['pre_transform_data'], remove_text=True, style='mpl20',
+ tol=0.05)
+def test_pre_transform_plotting():
+ # a catch-all for as many as possible plot layouts which handle
+ # pre-transforming the data NOTE: The axis range is important in this
+ # plot. It should be x10 what the data suggests it should be
+
+ ax = plt.axes()
+ times10 = mtransforms.Affine2D().scale(10)
+
+ ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData)
+
+ ax.pcolormesh(np.linspace(0, 4, 7),
+ np.linspace(5.5, 8, 9),
+ np.arange(48).reshape(8, 6),
+ transform=times10 + ax.transData)
+
+ ax.scatter(np.linspace(0, 10), np.linspace(10, 0),
+ transform=times10 + ax.transData)
+
+ x = np.linspace(8, 10, 20)
+ y = np.linspace(1, 5, 20)
+ u = 2*np.sin(x) + np.cos(y[:, np.newaxis])
+ v = np.sin(x) - np.cos(y[:, np.newaxis])
+
+ ax.streamplot(x, y, u, v, transform=times10 + ax.transData,
+ linewidth=np.hypot(u, v))
+
+ # reduce the vector data down a bit for barb and quiver plotting
+ x, y = x[::3], y[::3]
+ u, v = u[::3, ::3], v[::3, ::3]
+
+ ax.quiver(x, y + 5, u, v, transform=times10 + ax.transData)
+
+ ax.barbs(x - 3, y + 5, u**2, v**2, transform=times10 + ax.transData)
+
+
+def test_contour_pre_transform_limits():
+ ax = plt.axes()
+ xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))
+ ax.contourf(xs, ys, np.log(xs * ys),
+ transform=mtransforms.Affine2D().scale(0.1) + ax.transData)
+
+ expected = np.array([[1.5, 1.24],
+ [2., 1.25]])
+ assert_almost_equal(expected, ax.dataLim.get_points())
+
+
+def test_pcolor_pre_transform_limits():
+ # Based on test_contour_pre_transform_limits()
+ ax = plt.axes()
+ xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))
+ ax.pcolor(xs, ys, np.log(xs * ys)[:-1, :-1],
+ transform=mtransforms.Affine2D().scale(0.1) + ax.transData)
+
+ expected = np.array([[1.5, 1.24],
+ [2., 1.25]])
+ assert_almost_equal(expected, ax.dataLim.get_points())
+
+
+def test_pcolormesh_pre_transform_limits():
+ # Based on test_contour_pre_transform_limits()
+ ax = plt.axes()
+ xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))
+ ax.pcolormesh(xs, ys, np.log(xs * ys)[:-1, :-1],
+ transform=mtransforms.Affine2D().scale(0.1) + ax.transData)
+
+ expected = np.array([[1.5, 1.24],
+ [2., 1.25]])
+ assert_almost_equal(expected, ax.dataLim.get_points())
+
+
+def test_pcolormesh_gouraud_nans():
+ np.random.seed(19680801)
+
+ values = np.linspace(0, 180, 3)
+ radii = np.linspace(100, 1000, 10)
+ z, y = np.meshgrid(values, radii)
+ x = np.radians(np.random.rand(*z.shape) * 100)
+
+ fig = plt.figure()
+ ax = fig.add_subplot(111, projection="polar")
+ # Setting the limit to cause clipping of the r values causes NaN to be
+ # introduced; these should not crash but be ignored as in other path
+ # operations.
+ ax.set_rlim(101, 1000)
+ ax.pcolormesh(x, y, z, shading="gouraud")
+
+ fig.canvas.draw()
+
+
+def test_Affine2D_from_values():
+ points = np.array([[0, 0],
+ [10, 20],
+ [-1, 0],
+ ])
+
+ t = mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, 0)
+ actual = t.transform(points)
+ expected = np.array([[0, 0], [10, 0], [-1, 0]])
+ assert_almost_equal(actual, expected)
+
+ t = mtransforms.Affine2D.from_values(0, 2, 0, 0, 0, 0)
+ actual = t.transform(points)
+ expected = np.array([[0, 0], [0, 20], [0, -2]])
+ assert_almost_equal(actual, expected)
+
+ t = mtransforms.Affine2D.from_values(0, 0, 3, 0, 0, 0)
+ actual = t.transform(points)
+ expected = np.array([[0, 0], [60, 0], [0, 0]])
+ assert_almost_equal(actual, expected)
+
+ t = mtransforms.Affine2D.from_values(0, 0, 0, 4, 0, 0)
+ actual = t.transform(points)
+ expected = np.array([[0, 0], [0, 80], [0, 0]])
+ assert_almost_equal(actual, expected)
+
+ t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 5, 0)
+ actual = t.transform(points)
+ expected = np.array([[5, 0], [5, 0], [5, 0]])
+ assert_almost_equal(actual, expected)
+
+ t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 0, 6)
+ actual = t.transform(points)
+ expected = np.array([[0, 6], [0, 6], [0, 6]])
+ assert_almost_equal(actual, expected)
+
+
+def test_affine_inverted_invalidated():
+ # Ensure that the an affine transform is not declared valid on access
+ point = [1.0, 1.0]
+ t = mtransforms.Affine2D()
+
+ assert_almost_equal(point, t.transform(t.inverted().transform(point)))
+ # Change and access the transform
+ t.translate(1.0, 1.0).get_matrix()
+ assert_almost_equal(point, t.transform(t.inverted().transform(point)))
+
+
+def test_clipping_of_log():
+ # issue 804
+ path = Path._create_closed([(0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20)])
+ # something like this happens in plotting logarithmic histograms
+ trans = mtransforms.BlendedGenericTransform(
+ mtransforms.Affine2D(), scale.LogTransform(10, 'clip'))
+ tpath = trans.transform_path_non_affine(path)
+ result = tpath.iter_segments(trans.get_affine(),
+ clip=(0, 0, 100, 100),
+ simplify=False)
+ tpoints, tcodes = zip(*result)
+ assert_allclose(tcodes, path.codes[:-1]) # No longer closed.
+
+
+class NonAffineForTest(mtransforms.Transform):
+ """
+ A class which looks like a non affine transform, but does whatever
+ the given transform does (even if it is affine). This is very useful
+ for testing NonAffine behaviour with a simple Affine transform.
+
+ """
+ is_affine = False
+ output_dims = 2
+ input_dims = 2
+
+ def __init__(self, real_trans, *args, **kwargs):
+ self.real_trans = real_trans
+ super().__init__(*args, **kwargs)
+
+ def transform_non_affine(self, values):
+ return self.real_trans.transform(values)
+
+ def transform_path_non_affine(self, path):
+ return self.real_trans.transform_path(path)
+
+
+class TestBasicTransform:
+ def setup_method(self):
+
+ self.ta1 = mtransforms.Affine2D(shorthand_name='ta1').rotate(np.pi / 2)
+ self.ta2 = mtransforms.Affine2D(shorthand_name='ta2').translate(10, 0)
+ self.ta3 = mtransforms.Affine2D(shorthand_name='ta3').scale(1, 2)
+
+ self.tn1 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),
+ shorthand_name='tn1')
+ self.tn2 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),
+ shorthand_name='tn2')
+ self.tn3 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),
+ shorthand_name='tn3')
+
+ # creates a transform stack which looks like ((A, (N, A)), A)
+ self.stack1 = (self.ta1 + (self.tn1 + self.ta2)) + self.ta3
+ # creates a transform stack which looks like (((A, N), A), A)
+ self.stack2 = self.ta1 + self.tn1 + self.ta2 + self.ta3
+ # creates a transform stack which is a subset of stack2
+ self.stack2_subset = self.tn1 + self.ta2 + self.ta3
+
+ # when in debug, the transform stacks can produce dot images:
+# self.stack1.write_graphviz(file('stack1.dot', 'w'))
+# self.stack2.write_graphviz(file('stack2.dot', 'w'))
+# self.stack2_subset.write_graphviz(file('stack2_subset.dot', 'w'))
+
+ def test_transform_depth(self):
+ assert self.stack1.depth == 4
+ assert self.stack2.depth == 4
+ assert self.stack2_subset.depth == 3
+
+ def test_left_to_right_iteration(self):
+ stack3 = (self.ta1 + (self.tn1 + (self.ta2 + self.tn2))) + self.ta3
+# stack3.write_graphviz(file('stack3.dot', 'w'))
+
+ target_transforms = [stack3,
+ (self.tn1 + (self.ta2 + self.tn2)) + self.ta3,
+ (self.ta2 + self.tn2) + self.ta3,
+ self.tn2 + self.ta3,
+ self.ta3,
+ ]
+ r = [rh for _, rh in stack3._iter_break_from_left_to_right()]
+ assert len(r) == len(target_transforms)
+
+ for target_stack, stack in zip(target_transforms, r):
+ assert target_stack == stack
+
+ def test_transform_shortcuts(self):
+ assert self.stack1 - self.stack2_subset == self.ta1
+ assert self.stack2 - self.stack2_subset == self.ta1
+
+ assert self.stack2_subset - self.stack2 == self.ta1.inverted()
+ assert (self.stack2_subset - self.stack2).depth == 1
+
+ with pytest.raises(ValueError):
+ self.stack1 - self.stack2
+
+ aff1 = self.ta1 + (self.ta2 + self.ta3)
+ aff2 = self.ta2 + self.ta3
+
+ assert aff1 - aff2 == self.ta1
+ assert aff1 - self.ta2 == aff1 + self.ta2.inverted()
+
+ assert self.stack1 - self.ta3 == self.ta1 + (self.tn1 + self.ta2)
+ assert self.stack2 - self.ta3 == self.ta1 + self.tn1 + self.ta2
+
+ assert ((self.ta2 + self.ta3) - self.ta3 + self.ta3 ==
+ self.ta2 + self.ta3)
+
+ def test_contains_branch(self):
+ r1 = (self.ta2 + self.ta1)
+ r2 = (self.ta2 + self.ta1)
+ assert r1 == r2
+ assert r1 != self.ta1
+ assert r1.contains_branch(r2)
+ assert r1.contains_branch(self.ta1)
+ assert not r1.contains_branch(self.ta2)
+ assert not r1.contains_branch(self.ta2 + self.ta2)
+
+ assert r1 == r2
+
+ assert self.stack1.contains_branch(self.ta3)
+ assert self.stack2.contains_branch(self.ta3)
+
+ assert self.stack1.contains_branch(self.stack2_subset)
+ assert self.stack2.contains_branch(self.stack2_subset)
+
+ assert not self.stack2_subset.contains_branch(self.stack1)
+ assert not self.stack2_subset.contains_branch(self.stack2)
+
+ assert self.stack1.contains_branch(self.ta2 + self.ta3)
+ assert self.stack2.contains_branch(self.ta2 + self.ta3)
+
+ assert not self.stack1.contains_branch(self.tn1 + self.ta2)
+
+ blend = mtransforms.BlendedGenericTransform(self.tn2, self.stack2)
+ x, y = blend.contains_branch_seperately(self.stack2_subset)
+ stack_blend = self.tn3 + blend
+ sx, sy = stack_blend.contains_branch_seperately(self.stack2_subset)
+ assert x is sx is False
+ assert y is sy is True
+
+ def test_affine_simplification(self):
+ # tests that a transform stack only calls as much is absolutely
+ # necessary "non-affine" allowing the best possible optimization with
+ # complex transformation stacks.
+ points = np.array([[0, 0], [10, 20], [np.nan, 1], [-1, 0]],
+ dtype=np.float64)
+ na_pts = self.stack1.transform_non_affine(points)
+ all_pts = self.stack1.transform(points)
+
+ na_expected = np.array([[1., 2.], [-19., 12.],
+ [np.nan, np.nan], [1., 1.]], dtype=np.float64)
+ all_expected = np.array([[11., 4.], [-9., 24.],
+ [np.nan, np.nan], [11., 2.]],
+ dtype=np.float64)
+
+ # check we have the expected results from doing the affine part only
+ assert_array_almost_equal(na_pts, na_expected)
+ # check we have the expected results from a full transformation
+ assert_array_almost_equal(all_pts, all_expected)
+ # check we have the expected results from doing the transformation in
+ # two steps
+ assert_array_almost_equal(self.stack1.transform_affine(na_pts),
+ all_expected)
+ # check that getting the affine transformation first, then fully
+ # transforming using that yields the same result as before.
+ assert_array_almost_equal(self.stack1.get_affine().transform(na_pts),
+ all_expected)
+
+ # check that the affine part of stack1 & stack2 are equivalent
+ # (i.e. the optimization is working)
+ expected_result = (self.ta2 + self.ta3).get_matrix()
+ result = self.stack1.get_affine().get_matrix()
+ assert_array_equal(expected_result, result)
+
+ result = self.stack2.get_affine().get_matrix()
+ assert_array_equal(expected_result, result)
+
+
+class TestTransformPlotInterface:
+ def test_line_extent_axes_coords(self):
+ # a simple line in axes coordinates
+ ax = plt.axes()
+ ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transAxes)
+ assert_array_equal(ax.dataLim.get_points(),
+ np.array([[np.inf, np.inf],
+ [-np.inf, -np.inf]]))
+
+ def test_line_extent_data_coords(self):
+ # a simple line in data coordinates
+ ax = plt.axes()
+ ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transData)
+ assert_array_equal(ax.dataLim.get_points(),
+ np.array([[0.1, 0.5], [1.2, 0.9]]))
+
+ def test_line_extent_compound_coords1(self):
+ # a simple line in data coordinates in the y component, and in axes
+ # coordinates in the x
+ ax = plt.axes()
+ trans = mtransforms.blended_transform_factory(ax.transAxes,
+ ax.transData)
+ ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)
+ assert_array_equal(ax.dataLim.get_points(),
+ np.array([[np.inf, -5.],
+ [-np.inf, 35.]]))
+
+ def test_line_extent_predata_transform_coords(self):
+ # a simple line in (offset + data) coordinates
+ ax = plt.axes()
+ trans = mtransforms.Affine2D().scale(10) + ax.transData
+ ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)
+ assert_array_equal(ax.dataLim.get_points(),
+ np.array([[1., -50.], [12., 350.]]))
+
+ def test_line_extent_compound_coords2(self):
+ # a simple line in (offset + data) coordinates in the y component, and
+ # in axes coordinates in the x
+ ax = plt.axes()
+ trans = mtransforms.blended_transform_factory(
+ ax.transAxes, mtransforms.Affine2D().scale(10) + ax.transData)
+ ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)
+ assert_array_equal(ax.dataLim.get_points(),
+ np.array([[np.inf, -50.], [-np.inf, 350.]]))
+
+ def test_line_extents_affine(self):
+ ax = plt.axes()
+ offset = mtransforms.Affine2D().translate(10, 10)
+ plt.plot(np.arange(10), transform=offset + ax.transData)
+ expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 10
+ assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
+
+ def test_line_extents_non_affine(self):
+ ax = plt.axes()
+ offset = mtransforms.Affine2D().translate(10, 10)
+ na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
+ plt.plot(np.arange(10), transform=offset + na_offset + ax.transData)
+ expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 20
+ assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
+
+ def test_pathc_extents_non_affine(self):
+ ax = plt.axes()
+ offset = mtransforms.Affine2D().translate(10, 10)
+ na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
+ pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])
+ patch = mpatches.PathPatch(pth,
+ transform=offset + na_offset + ax.transData)
+ ax.add_patch(patch)
+ expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 20
+ assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
+
+ def test_pathc_extents_affine(self):
+ ax = plt.axes()
+ offset = mtransforms.Affine2D().translate(10, 10)
+ pth = Path([[0, 0], [0, 10], [10, 10], [10, 0]])
+ patch = mpatches.PathPatch(pth, transform=offset + ax.transData)
+ ax.add_patch(patch)
+ expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 10
+ assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
+
+ def test_line_extents_for_non_affine_transData(self):
+ ax = plt.axes(projection='polar')
+ # add 10 to the radius of the data
+ offset = mtransforms.Affine2D().translate(0, 10)
+
+ plt.plot(np.arange(10), transform=offset + ax.transData)
+ # the data lim of a polar plot is stored in coordinates
+ # before a transData transformation, hence the data limits
+ # are not what is being shown on the actual plot.
+ expected_data_lim = np.array([[0., 0.], [9., 9.]]) + [0, 10]
+ assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
+
+
+def assert_bbox_eq(bbox1, bbox2):
+ assert_array_equal(bbox1.bounds, bbox2.bounds)
+
+
+def test_bbox_frozen_copies_minpos():
+ bbox = mtransforms.Bbox.from_extents(0.0, 0.0, 1.0, 1.0, minpos=1.0)
+ frozen = bbox.frozen()
+ assert_array_equal(frozen.minpos, bbox.minpos)
+
+
+def test_bbox_intersection():
+ bbox_from_ext = mtransforms.Bbox.from_extents
+ inter = mtransforms.Bbox.intersection
+
+ r1 = bbox_from_ext(0, 0, 1, 1)
+ r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5)
+ r3 = bbox_from_ext(0.5, 0, 0.75, 0.75)
+ r4 = bbox_from_ext(0.5, 1.5, 1, 2.5)
+ r5 = bbox_from_ext(1, 1, 2, 2)
+
+ # self intersection -> no change
+ assert_bbox_eq(inter(r1, r1), r1)
+ # simple intersection
+ assert_bbox_eq(inter(r1, r2), bbox_from_ext(0.5, 0.5, 1, 1))
+ # r3 contains r2
+ assert_bbox_eq(inter(r1, r3), r3)
+ # no intersection
+ assert inter(r1, r4) is None
+ # single point
+ assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1))
+
+
+def test_bbox_as_strings():
+ b = mtransforms.Bbox([[.5, 0], [.75, .75]])
+ assert_bbox_eq(b, eval(repr(b), {'Bbox': mtransforms.Bbox}))
+ asdict = eval(str(b), {'Bbox': dict})
+ for k, v in asdict.items():
+ assert getattr(b, k) == v
+ fmt = '.1f'
+ asdict = eval(format(b, fmt), {'Bbox': dict})
+ for k, v in asdict.items():
+ assert eval(format(getattr(b, k), fmt)) == v
+
+
+def test_str_transform():
+ # The str here should not be considered as "absolutely stable", and may be
+ # reformatted later; this is just a smoketest for __str__.
+ assert str(plt.subplot(projection="polar").transData) == """\
+CompositeGenericTransform(
+ CompositeGenericTransform(
+ CompositeGenericTransform(
+ TransformWrapper(
+ BlendedAffine2D(
+ IdentityTransform(),
+ IdentityTransform())),
+ CompositeAffine2D(
+ Affine2D().scale(1.0),
+ Affine2D().scale(1.0))),
+ PolarTransform(
+ PolarAxes(0.125,0.1;0.775x0.8),
+ use_rmin=True,
+ apply_theta_transforms=False)),
+ CompositeGenericTransform(
+ CompositeGenericTransform(
+ PolarAffine(
+ TransformWrapper(
+ BlendedAffine2D(
+ IdentityTransform(),
+ IdentityTransform())),
+ LockableBbox(
+ Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0),
+ [[-- --]
+ [-- --]])),
+ BboxTransformFrom(
+ _WedgeBbox(
+ (0.5, 0.5),
+ TransformedBbox(
+ Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0),
+ CompositeAffine2D(
+ Affine2D().scale(1.0),
+ Affine2D().scale(1.0))),
+ LockableBbox(
+ Bbox(x0=0.0, y0=0.0, x1=6.283185307179586, y1=1.0),
+ [[-- --]
+ [-- --]])))),
+ BboxTransformTo(
+ TransformedBbox(
+ Bbox(x0=0.125, y0=0.09999999999999998, x1=0.9, y1=0.9),
+ BboxTransformTo(
+ TransformedBbox(
+ Bbox(x0=0.0, y0=0.0, x1=8.0, y1=6.0),
+ Affine2D().scale(80.0)))))))"""
+
+
+def test_transform_single_point():
+ t = mtransforms.Affine2D()
+ r = t.transform_affine((1, 1))
+ assert r.shape == (2,)
+
+
+def test_log_transform():
+ # Tests that the last line runs without exception (previously the
+ # transform would fail if one of the axes was logarithmic).
+ fig, ax = plt.subplots()
+ ax.set_yscale('log')
+ ax.transData.transform((1, 1))
+
+
+def test_nan_overlap():
+ a = mtransforms.Bbox([[0, 0], [1, 1]])
+ b = mtransforms.Bbox([[0, 0], [1, np.nan]])
+ assert not a.overlaps(b)
+
+
+def test_transform_angles():
+ t = mtransforms.Affine2D() # Identity transform
+ angles = np.array([20, 45, 60])
+ points = np.array([[0, 0], [1, 1], [2, 2]])
+
+ # Identity transform does not change angles
+ new_angles = t.transform_angles(angles, points)
+ assert_array_almost_equal(angles, new_angles)
+
+ # points missing a 2nd dimension
+ with pytest.raises(ValueError):
+ t.transform_angles(angles, points[0:2, 0:1])
+
+ # Number of angles != Number of points
+ with pytest.raises(ValueError):
+ t.transform_angles(angles, points[0:2, :])
+
+
+def test_nonsingular():
+ # test for zero-expansion type cases; other cases may be added later
+ zero_expansion = np.array([-0.001, 0.001])
+ cases = [(0, np.nan), (0, 0), (0, 7.9e-317)]
+ for args in cases:
+ out = np.array(mtransforms.nonsingular(*args))
+ assert_array_equal(out, zero_expansion)
+
+
+def test_transformed_path():
+ points = [(0, 0), (1, 0), (1, 1), (0, 1)]
+ path = Path(points, closed=True)
+
+ trans = mtransforms.Affine2D()
+ trans_path = mtransforms.TransformedPath(path, trans)
+ assert_allclose(trans_path.get_fully_transformed_path().vertices, points)
+
+ # Changing the transform should change the result.
+ r2 = 1 / np.sqrt(2)
+ trans.rotate(np.pi / 4)
+ assert_allclose(trans_path.get_fully_transformed_path().vertices,
+ [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],
+ atol=1e-15)
+
+ # Changing the path does not change the result (it's cached).
+ path.points = [(0, 0)] * 4
+ assert_allclose(trans_path.get_fully_transformed_path().vertices,
+ [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],
+ atol=1e-15)
+
+
+def test_transformed_patch_path():
+ trans = mtransforms.Affine2D()
+ patch = mpatches.Wedge((0, 0), 1, 45, 135, transform=trans)
+
+ tpatch = mtransforms.TransformedPatchPath(patch)
+ points = tpatch.get_fully_transformed_path().vertices
+
+ # Changing the transform should change the result.
+ trans.scale(2)
+ assert_allclose(tpatch.get_fully_transformed_path().vertices, points * 2)
+
+ # Changing the path should change the result (and cancel out the scaling
+ # from the transform).
+ patch.set_radius(0.5)
+ assert_allclose(tpatch.get_fully_transformed_path().vertices, points)
+
+
+@pytest.mark.parametrize('locked_element', ['x0', 'y0', 'x1', 'y1'])
+def test_lockable_bbox(locked_element):
+ other_elements = ['x0', 'y0', 'x1', 'y1']
+ other_elements.remove(locked_element)
+
+ orig = mtransforms.Bbox.unit()
+ locked = mtransforms.LockableBbox(orig, **{locked_element: 2})
+
+ # LockableBbox should keep its locked element as specified in __init__.
+ assert getattr(locked, locked_element) == 2
+ assert getattr(locked, 'locked_' + locked_element) == 2
+ for elem in other_elements:
+ assert getattr(locked, elem) == getattr(orig, elem)
+
+ # Changing underlying Bbox should update everything but locked element.
+ orig.set_points(orig.get_points() + 10)
+ assert getattr(locked, locked_element) == 2
+ assert getattr(locked, 'locked_' + locked_element) == 2
+ for elem in other_elements:
+ assert getattr(locked, elem) == getattr(orig, elem)
+
+ # Unlocking element should revert values back to the underlying Bbox.
+ setattr(locked, 'locked_' + locked_element, None)
+ assert getattr(locked, 'locked_' + locked_element) is None
+ assert np.all(orig.get_points() == locked.get_points())
+
+ # Relocking an element should change its value, but not others.
+ setattr(locked, 'locked_' + locked_element, 3)
+ assert getattr(locked, locked_element) == 3
+ assert getattr(locked, 'locked_' + locked_element) == 3
+ for elem in other_elements:
+ assert getattr(locked, elem) == getattr(orig, elem)
+
+
+def test_transformwrapper():
+ t = mtransforms.TransformWrapper(mtransforms.Affine2D())
+ with pytest.raises(ValueError, match=(
+ r"The input and output dims of the new child \(1, 1\) "
+ r"do not match those of current child \(2, 2\)")):
+ t.set(scale.LogTransform(10))
+
+
+@check_figures_equal(extensions=["png"])
+def test_scale_swapping(fig_test, fig_ref):
+ np.random.seed(19680801)
+ samples = np.random.normal(size=10)
+ x = np.linspace(-5, 5, 10)
+
+ for fig, log_state in zip([fig_test, fig_ref], [True, False]):
+ ax = fig.subplots()
+ ax.hist(samples, log=log_state, density=True)
+ ax.plot(x, np.exp(-(x**2) / 2) / np.sqrt(2 * np.pi))
+ fig.canvas.draw()
+ ax.set_yscale('linear')
+
+
+def test_offset_copy_errors():
+ with pytest.raises(ValueError,
+ match="'fontsize' is not a valid value for units;"
+ " supported values are 'dots', 'points', 'inches'"):
+ mtransforms.offset_copy(None, units='fontsize')
+
+ with pytest.raises(ValueError,
+ match='For units of inches or points a fig kwarg is needed'):
+ mtransforms.offset_copy(None, units='inches')
+
+
+def test_transformedbbox_contains():
+ bb = TransformedBbox(Bbox.unit(), Affine2D().rotate_deg(30))
+ assert bb.contains(.8, .5)
+ assert bb.contains(-.4, .85)
+ assert not bb.contains(.9, .5)
+ bb = TransformedBbox(Bbox.unit(), Affine2D().translate(.25, .5))
+ assert bb.contains(1.25, 1.5)
+ assert not bb.fully_contains(1.25, 1.5)
+ assert not bb.fully_contains(.1, .1)
+
+
+def test_interval_contains():
+ assert mtransforms.interval_contains((0, 1), 0.5)
+ assert mtransforms.interval_contains((0, 1), 0)
+ assert mtransforms.interval_contains((0, 1), 1)
+ assert not mtransforms.interval_contains((0, 1), -1)
+ assert not mtransforms.interval_contains((0, 1), 2)
+ assert mtransforms.interval_contains((1, 0), 0.5)
+
+
+def test_interval_contains_open():
+ assert mtransforms.interval_contains_open((0, 1), 0.5)
+ assert not mtransforms.interval_contains_open((0, 1), 0)
+ assert not mtransforms.interval_contains_open((0, 1), 1)
+ assert not mtransforms.interval_contains_open((0, 1), -1)
+ assert not mtransforms.interval_contains_open((0, 1), 2)
+ assert mtransforms.interval_contains_open((1, 0), 0.5)
+
+
+def test_scaledrotation_initialization():
+ """Test that the ScaledRotation object is initialized correctly."""
+ theta = 1.0 # Arbitrary theta value for testing
+ trans_shift = MagicMock() # Mock the trans_shift transformation
+ scaled_rot = _ScaledRotation(theta, trans_shift)
+ assert scaled_rot._theta == theta
+ assert scaled_rot._trans_shift == trans_shift
+ assert scaled_rot._mtx is None
+
+
+def test_scaledrotation_get_matrix_invalid():
+ """Test get_matrix when the matrix is invalid and needs recalculation."""
+ theta = np.pi / 2
+ trans_shift = MagicMock(transform=MagicMock(return_value=[[theta, 0]]))
+ scaled_rot = _ScaledRotation(theta, trans_shift)
+ scaled_rot._invalid = True
+ matrix = scaled_rot.get_matrix()
+ trans_shift.transform.assert_called_once_with([[theta, 0]])
+ expected_rotation = np.array([[0, -1],
+ [1, 0]])
+ assert matrix is not None
+ assert_allclose(matrix[:2, :2], expected_rotation, atol=1e-15)
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_triangulation.py b/lib/python3.12/site-packages/matplotlib/tests/test_triangulation.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd91144f240cefa592a0c73387974c7fcd977ba9
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_triangulation.py
@@ -0,0 +1,1403 @@
+import numpy as np
+from numpy.testing import (
+ assert_array_equal, assert_array_almost_equal, assert_array_less)
+import numpy.ma.testutils as matest
+import pytest
+
+import matplotlib as mpl
+import matplotlib.pyplot as plt
+import matplotlib.tri as mtri
+from matplotlib.path import Path
+from matplotlib.testing.decorators import image_comparison, check_figures_equal
+
+
+class TestTriangulationParams:
+ x = [-1, 0, 1, 0]
+ y = [0, -1, 0, 1]
+ triangles = [[0, 1, 2], [0, 2, 3]]
+ mask = [False, True]
+
+ @pytest.mark.parametrize('args, kwargs, expected', [
+ ([x, y], {}, [x, y, None, None]),
+ ([x, y, triangles], {}, [x, y, triangles, None]),
+ ([x, y], dict(triangles=triangles), [x, y, triangles, None]),
+ ([x, y], dict(mask=mask), [x, y, None, mask]),
+ ([x, y, triangles], dict(mask=mask), [x, y, triangles, mask]),
+ ([x, y], dict(triangles=triangles, mask=mask), [x, y, triangles, mask])
+ ])
+ def test_extract_triangulation_params(self, args, kwargs, expected):
+ other_args = [1, 2]
+ other_kwargs = {'a': 3, 'b': '4'}
+ x_, y_, triangles_, mask_, args_, kwargs_ = \
+ mtri.Triangulation._extract_triangulation_params(
+ args + other_args, {**kwargs, **other_kwargs})
+ x, y, triangles, mask = expected
+ assert x_ is x
+ assert y_ is y
+ assert_array_equal(triangles_, triangles)
+ assert mask_ is mask
+ assert args_ == other_args
+ assert kwargs_ == other_kwargs
+
+
+def test_extract_triangulation_positional_mask():
+ # mask cannot be passed positionally
+ mask = [True]
+ args = [[0, 2, 1], [0, 0, 1], [[0, 1, 2]], mask]
+ x_, y_, triangles_, mask_, args_, kwargs_ = \
+ mtri.Triangulation._extract_triangulation_params(args, {})
+ assert mask_ is None
+ assert args_ == [mask]
+ # the positional mask must be caught downstream because this must pass
+ # unknown args through
+
+
+def test_triangulation_init():
+ x = [-1, 0, 1, 0]
+ y = [0, -1, 0, 1]
+ with pytest.raises(ValueError, match="x and y must be equal-length"):
+ mtri.Triangulation(x, [1, 2])
+ with pytest.raises(
+ ValueError,
+ match=r"triangles must be a \(N, 3\) int array, but found shape "
+ r"\(3,\)"):
+ mtri.Triangulation(x, y, [0, 1, 2])
+ with pytest.raises(
+ ValueError,
+ match=r"triangles must be a \(N, 3\) int array, not 'other'"):
+ mtri.Triangulation(x, y, 'other')
+ with pytest.raises(ValueError, match="found value 99"):
+ mtri.Triangulation(x, y, [[0, 1, 99]])
+ with pytest.raises(ValueError, match="found value -1"):
+ mtri.Triangulation(x, y, [[0, 1, -1]])
+
+
+def test_triangulation_set_mask():
+ x = [-1, 0, 1, 0]
+ y = [0, -1, 0, 1]
+ triangles = [[0, 1, 2], [2, 3, 0]]
+ triang = mtri.Triangulation(x, y, triangles)
+
+ # Check neighbors, which forces creation of C++ triangulation
+ assert_array_equal(triang.neighbors, [[-1, -1, 1], [-1, -1, 0]])
+
+ # Set mask
+ triang.set_mask([False, True])
+ assert_array_equal(triang.mask, [False, True])
+
+ # Reset mask
+ triang.set_mask(None)
+ assert triang.mask is None
+
+ msg = r"mask array must have same length as triangles array"
+ for mask in ([False, True, False], [False], [True], False, True):
+ with pytest.raises(ValueError, match=msg):
+ triang.set_mask(mask)
+
+
+def test_delaunay():
+ # No duplicate points, regular grid.
+ nx = 5
+ ny = 4
+ x, y = np.meshgrid(np.linspace(0.0, 1.0, nx), np.linspace(0.0, 1.0, ny))
+ x = x.ravel()
+ y = y.ravel()
+ npoints = nx*ny
+ ntriangles = 2 * (nx-1) * (ny-1)
+ nedges = 3*nx*ny - 2*nx - 2*ny + 1
+
+ # Create delaunay triangulation.
+ triang = mtri.Triangulation(x, y)
+
+ # The tests in the remainder of this function should be passed by any
+ # triangulation that does not contain duplicate points.
+
+ # Points - floating point.
+ assert_array_almost_equal(triang.x, x)
+ assert_array_almost_equal(triang.y, y)
+
+ # Triangles - integers.
+ assert len(triang.triangles) == ntriangles
+ assert np.min(triang.triangles) == 0
+ assert np.max(triang.triangles) == npoints-1
+
+ # Edges - integers.
+ assert len(triang.edges) == nedges
+ assert np.min(triang.edges) == 0
+ assert np.max(triang.edges) == npoints-1
+
+ # Neighbors - integers.
+ # Check that neighbors calculated by C++ triangulation class are the same
+ # as those returned from delaunay routine.
+ neighbors = triang.neighbors
+ triang._neighbors = None
+ assert_array_equal(triang.neighbors, neighbors)
+
+ # Is each point used in at least one triangle?
+ assert_array_equal(np.unique(triang.triangles), np.arange(npoints))
+
+
+def test_delaunay_duplicate_points():
+ npoints = 10
+ duplicate = 7
+ duplicate_of = 3
+
+ np.random.seed(23)
+ x = np.random.random(npoints)
+ y = np.random.random(npoints)
+ x[duplicate] = x[duplicate_of]
+ y[duplicate] = y[duplicate_of]
+
+ # Create delaunay triangulation.
+ triang = mtri.Triangulation(x, y)
+
+ # Duplicate points should be ignored, so the index of the duplicate points
+ # should not appear in any triangle.
+ assert_array_equal(np.unique(triang.triangles),
+ np.delete(np.arange(npoints), duplicate))
+
+
+def test_delaunay_points_in_line():
+ # Cannot triangulate points that are all in a straight line, but check
+ # that delaunay code fails gracefully.
+ x = np.linspace(0.0, 10.0, 11)
+ y = np.linspace(0.0, 10.0, 11)
+ with pytest.raises(RuntimeError):
+ mtri.Triangulation(x, y)
+
+ # Add an extra point not on the line and the triangulation is OK.
+ x = np.append(x, 2.0)
+ y = np.append(y, 8.0)
+ mtri.Triangulation(x, y)
+
+
+@pytest.mark.parametrize('x, y', [
+ # Triangulation should raise a ValueError if passed less than 3 points.
+ ([], []),
+ ([1], [5]),
+ ([1, 2], [5, 6]),
+ # Triangulation should also raise a ValueError if passed duplicate points
+ # such that there are less than 3 unique points.
+ ([1, 2, 1], [5, 6, 5]),
+ ([1, 2, 2], [5, 6, 6]),
+ ([1, 1, 1, 2, 1, 2], [5, 5, 5, 6, 5, 6]),
+])
+def test_delaunay_insufficient_points(x, y):
+ with pytest.raises(ValueError):
+ mtri.Triangulation(x, y)
+
+
+def test_delaunay_robust():
+ # Fails when mtri.Triangulation uses matplotlib.delaunay, works when using
+ # qhull.
+ tri_points = np.array([
+ [0.8660254037844384, -0.5000000000000004],
+ [0.7577722283113836, -0.5000000000000004],
+ [0.6495190528383288, -0.5000000000000003],
+ [0.5412658773652739, -0.5000000000000003],
+ [0.811898816047911, -0.40625000000000044],
+ [0.7036456405748561, -0.4062500000000004],
+ [0.5953924651018013, -0.40625000000000033]])
+ test_points = np.asarray([
+ [0.58, -0.46],
+ [0.65, -0.46],
+ [0.65, -0.42],
+ [0.7, -0.48],
+ [0.7, -0.44],
+ [0.75, -0.44],
+ [0.8, -0.48]])
+
+ # Utility function that indicates if a triangle defined by 3 points
+ # (xtri, ytri) contains the test point xy. Avoid calling with a point that
+ # lies on or very near to an edge of the triangle.
+ def tri_contains_point(xtri, ytri, xy):
+ tri_points = np.vstack((xtri, ytri)).T
+ return Path(tri_points).contains_point(xy)
+
+ # Utility function that returns how many triangles of the specified
+ # triangulation contain the test point xy. Avoid calling with a point that
+ # lies on or very near to an edge of any triangle in the triangulation.
+ def tris_contain_point(triang, xy):
+ return sum(tri_contains_point(triang.x[tri], triang.y[tri], xy)
+ for tri in triang.triangles)
+
+ # Using matplotlib.delaunay, an invalid triangulation is created with
+ # overlapping triangles; qhull is OK.
+ triang = mtri.Triangulation(tri_points[:, 0], tri_points[:, 1])
+ for test_point in test_points:
+ assert tris_contain_point(triang, test_point) == 1
+
+ # If ignore the first point of tri_points, matplotlib.delaunay throws a
+ # KeyError when calculating the convex hull; qhull is OK.
+ triang = mtri.Triangulation(tri_points[1:, 0], tri_points[1:, 1])
+
+
+@image_comparison(['tripcolor1.png'])
+def test_tripcolor():
+ x = np.asarray([0, 0.5, 1, 0, 0.5, 1, 0, 0.5, 1, 0.75])
+ y = np.asarray([0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1, 0.75])
+ triangles = np.asarray([
+ [0, 1, 3], [1, 4, 3],
+ [1, 2, 4], [2, 5, 4],
+ [3, 4, 6], [4, 7, 6],
+ [4, 5, 9], [7, 4, 9], [8, 7, 9], [5, 8, 9]])
+
+ # Triangulation with same number of points and triangles.
+ triang = mtri.Triangulation(x, y, triangles)
+
+ Cpoints = x + 0.5*y
+
+ xmid = x[triang.triangles].mean(axis=1)
+ ymid = y[triang.triangles].mean(axis=1)
+ Cfaces = 0.5*xmid + ymid
+
+ plt.subplot(121)
+ plt.tripcolor(triang, Cpoints, edgecolors='k')
+ plt.title('point colors')
+
+ plt.subplot(122)
+ plt.tripcolor(triang, facecolors=Cfaces, edgecolors='k')
+ plt.title('facecolors')
+
+
+def test_tripcolor_color():
+ x = [-1, 0, 1, 0]
+ y = [0, -1, 0, 1]
+ fig, ax = plt.subplots()
+ with pytest.raises(TypeError, match=r"tripcolor\(\) missing 1 required "):
+ ax.tripcolor(x, y)
+ with pytest.raises(ValueError, match="The length of c must match either"):
+ ax.tripcolor(x, y, [1, 2, 3])
+ with pytest.raises(ValueError,
+ match="length of facecolors must match .* triangles"):
+ ax.tripcolor(x, y, facecolors=[1, 2, 3, 4])
+ with pytest.raises(ValueError,
+ match="'gouraud' .* at the points.* not at the faces"):
+ ax.tripcolor(x, y, facecolors=[1, 2], shading='gouraud')
+ with pytest.raises(ValueError,
+ match="'gouraud' .* at the points.* not at the faces"):
+ ax.tripcolor(x, y, [1, 2], shading='gouraud') # faces
+ with pytest.raises(TypeError,
+ match="positional.*'c'.*keyword-only.*'facecolors'"):
+ ax.tripcolor(x, y, C=[1, 2, 3, 4])
+ with pytest.raises(TypeError, match="Unexpected positional parameter"):
+ ax.tripcolor(x, y, [1, 2], 'unused_positional')
+
+ # smoke test for valid color specifications (via C or facecolors)
+ ax.tripcolor(x, y, [1, 2, 3, 4]) # edges
+ ax.tripcolor(x, y, [1, 2, 3, 4], shading='gouraud') # edges
+ ax.tripcolor(x, y, [1, 2]) # faces
+ ax.tripcolor(x, y, facecolors=[1, 2]) # faces
+
+
+def test_tripcolor_clim():
+ np.random.seed(19680801)
+ a, b, c = np.random.rand(10), np.random.rand(10), np.random.rand(10)
+
+ ax = plt.figure().add_subplot()
+ clim = (0.25, 0.75)
+ norm = ax.tripcolor(a, b, c, clim=clim).norm
+ assert (norm.vmin, norm.vmax) == clim
+
+
+def test_tripcolor_warnings():
+ x = [-1, 0, 1, 0]
+ y = [0, -1, 0, 1]
+ c = [0.4, 0.5]
+ fig, ax = plt.subplots()
+ # facecolors takes precedence over c
+ with pytest.warns(UserWarning, match="Positional parameter c .*no effect"):
+ ax.tripcolor(x, y, c, facecolors=c)
+ with pytest.warns(UserWarning, match="Positional parameter c .*no effect"):
+ ax.tripcolor(x, y, 'interpreted as c', facecolors=c)
+
+
+def test_no_modify():
+ # Test that Triangulation does not modify triangles array passed to it.
+ triangles = np.array([[3, 2, 0], [3, 1, 0]], dtype=np.int32)
+ points = np.array([(0, 0), (0, 1.1), (1, 0), (1, 1)])
+
+ old_triangles = triangles.copy()
+ mtri.Triangulation(points[:, 0], points[:, 1], triangles).edges
+ assert_array_equal(old_triangles, triangles)
+
+
+def test_trifinder():
+ # Test points within triangles of masked triangulation.
+ x, y = np.meshgrid(np.arange(4), np.arange(4))
+ x = x.ravel()
+ y = y.ravel()
+ triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6],
+ [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9],
+ [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13],
+ [10, 14, 13], [10, 11, 14], [11, 15, 14]]
+ mask = np.zeros(len(triangles))
+ mask[8:10] = 1
+ triang = mtri.Triangulation(x, y, triangles, mask)
+ trifinder = triang.get_trifinder()
+
+ xs = [0.25, 1.25, 2.25, 3.25]
+ ys = [0.25, 1.25, 2.25, 3.25]
+ xs, ys = np.meshgrid(xs, ys)
+ xs = xs.ravel()
+ ys = ys.ravel()
+ tris = trifinder(xs, ys)
+ assert_array_equal(tris, [0, 2, 4, -1, 6, -1, 10, -1,
+ 12, 14, 16, -1, -1, -1, -1, -1])
+ tris = trifinder(xs-0.5, ys-0.5)
+ assert_array_equal(tris, [-1, -1, -1, -1, -1, 1, 3, 5,
+ -1, 7, -1, 11, -1, 13, 15, 17])
+
+ # Test points exactly on boundary edges of masked triangulation.
+ xs = [0.5, 1.5, 2.5, 0.5, 1.5, 2.5, 1.5, 1.5, 0.0, 1.0, 2.0, 3.0]
+ ys = [0.0, 0.0, 0.0, 3.0, 3.0, 3.0, 1.0, 2.0, 1.5, 1.5, 1.5, 1.5]
+ tris = trifinder(xs, ys)
+ assert_array_equal(tris, [0, 2, 4, 13, 15, 17, 3, 14, 6, 7, 10, 11])
+
+ # Test points exactly on boundary corners of masked triangulation.
+ xs = [0.0, 3.0]
+ ys = [0.0, 3.0]
+ tris = trifinder(xs, ys)
+ assert_array_equal(tris, [0, 17])
+
+ #
+ # Test triangles with horizontal colinear points. These are not valid
+ # triangulations, but we try to deal with the simplest violations.
+ #
+
+ # If +ve, triangulation is OK, if -ve triangulation invalid,
+ # if zero have colinear points but should pass tests anyway.
+ delta = 0.0
+
+ x = [1.5, 0, 1, 2, 3, 1.5, 1.5]
+ y = [-1, 0, 0, 0, 0, delta, 1]
+ triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5],
+ [3, 4, 5], [1, 5, 6], [4, 6, 5]]
+ triang = mtri.Triangulation(x, y, triangles)
+ trifinder = triang.get_trifinder()
+
+ xs = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9]
+ ys = [-0.1, 0.1]
+ xs, ys = np.meshgrid(xs, ys)
+ tris = trifinder(xs, ys)
+ assert_array_equal(tris, [[-1, 0, 0, 1, 1, 2, -1],
+ [-1, 6, 6, 6, 7, 7, -1]])
+
+ #
+ # Test triangles with vertical colinear points. These are not valid
+ # triangulations, but we try to deal with the simplest violations.
+ #
+
+ # If +ve, triangulation is OK, if -ve triangulation invalid,
+ # if zero have colinear points but should pass tests anyway.
+ delta = 0.0
+
+ x = [-1, -delta, 0, 0, 0, 0, 1]
+ y = [1.5, 1.5, 0, 1, 2, 3, 1.5]
+ triangles = [[0, 1, 2], [0, 1, 5], [1, 2, 3], [1, 3, 4], [1, 4, 5],
+ [2, 6, 3], [3, 6, 4], [4, 6, 5]]
+ triang = mtri.Triangulation(x, y, triangles)
+ trifinder = triang.get_trifinder()
+
+ xs = [-0.1, 0.1]
+ ys = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9]
+ xs, ys = np.meshgrid(xs, ys)
+ tris = trifinder(xs, ys)
+ assert_array_equal(tris, [[-1, -1], [0, 5], [0, 5], [0, 6], [1, 6], [1, 7],
+ [-1, -1]])
+
+ # Test that changing triangulation by setting a mask causes the trifinder
+ # to be reinitialised.
+ x = [0, 1, 0, 1]
+ y = [0, 0, 1, 1]
+ triangles = [[0, 1, 2], [1, 3, 2]]
+ triang = mtri.Triangulation(x, y, triangles)
+ trifinder = triang.get_trifinder()
+
+ xs = [-0.2, 0.2, 0.8, 1.2]
+ ys = [0.5, 0.5, 0.5, 0.5]
+ tris = trifinder(xs, ys)
+ assert_array_equal(tris, [-1, 0, 1, -1])
+
+ triang.set_mask([1, 0])
+ assert trifinder == triang.get_trifinder()
+ tris = trifinder(xs, ys)
+ assert_array_equal(tris, [-1, -1, 1, -1])
+
+
+def test_triinterp():
+ # Test points within triangles of masked triangulation.
+ x, y = np.meshgrid(np.arange(4), np.arange(4))
+ x = x.ravel()
+ y = y.ravel()
+ z = 1.23*x - 4.79*y
+ triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6],
+ [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9],
+ [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13],
+ [10, 14, 13], [10, 11, 14], [11, 15, 14]]
+ mask = np.zeros(len(triangles))
+ mask[8:10] = 1
+ triang = mtri.Triangulation(x, y, triangles, mask)
+ linear_interp = mtri.LinearTriInterpolator(triang, z)
+ cubic_min_E = mtri.CubicTriInterpolator(triang, z)
+ cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
+
+ xs = np.linspace(0.25, 2.75, 6)
+ ys = [0.25, 0.75, 2.25, 2.75]
+ xs, ys = np.meshgrid(xs, ys) # Testing arrays with array.ndim = 2
+ for interp in (linear_interp, cubic_min_E, cubic_geom):
+ zs = interp(xs, ys)
+ assert_array_almost_equal(zs, (1.23*xs - 4.79*ys))
+
+ # Test points outside triangulation.
+ xs = [-0.25, 1.25, 1.75, 3.25]
+ ys = xs
+ xs, ys = np.meshgrid(xs, ys)
+ for interp in (linear_interp, cubic_min_E, cubic_geom):
+ zs = linear_interp(xs, ys)
+ assert_array_equal(zs.mask, [[True]*4]*4)
+
+ # Test mixed configuration (outside / inside).
+ xs = np.linspace(0.25, 1.75, 6)
+ ys = [0.25, 0.75, 1.25, 1.75]
+ xs, ys = np.meshgrid(xs, ys)
+ for interp in (linear_interp, cubic_min_E, cubic_geom):
+ zs = interp(xs, ys)
+ matest.assert_array_almost_equal(zs, (1.23*xs - 4.79*ys))
+ mask = (xs >= 1) * (xs <= 2) * (ys >= 1) * (ys <= 2)
+ assert_array_equal(zs.mask, mask)
+
+ # 2nd order patch test: on a grid with an 'arbitrary shaped' triangle,
+ # patch test shall be exact for quadratic functions and cubic
+ # interpolator if *kind* = user
+ (a, b, c) = (1.23, -4.79, 0.6)
+
+ def quad(x, y):
+ return a*(x-0.5)**2 + b*(y-0.5)**2 + c*x*y
+
+ def gradient_quad(x, y):
+ return (2*a*(x-0.5) + c*y, 2*b*(y-0.5) + c*x)
+
+ x = np.array([0.2, 0.33367, 0.669, 0., 1., 1., 0.])
+ y = np.array([0.3, 0.80755, 0.4335, 0., 0., 1., 1.])
+ triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5],
+ [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]])
+ triang = mtri.Triangulation(x, y, triangles)
+ z = quad(x, y)
+ dz = gradient_quad(x, y)
+ # test points for 2nd order patch test
+ xs = np.linspace(0., 1., 5)
+ ys = np.linspace(0., 1., 5)
+ xs, ys = np.meshgrid(xs, ys)
+ cubic_user = mtri.CubicTriInterpolator(triang, z, kind='user', dz=dz)
+ interp_zs = cubic_user(xs, ys)
+ assert_array_almost_equal(interp_zs, quad(xs, ys))
+ (interp_dzsdx, interp_dzsdy) = cubic_user.gradient(x, y)
+ (dzsdx, dzsdy) = gradient_quad(x, y)
+ assert_array_almost_equal(interp_dzsdx, dzsdx)
+ assert_array_almost_equal(interp_dzsdy, dzsdy)
+
+ # Cubic improvement: cubic interpolation shall perform better than linear
+ # on a sufficiently dense mesh for a quadratic function.
+ n = 11
+ x, y = np.meshgrid(np.linspace(0., 1., n+1), np.linspace(0., 1., n+1))
+ x = x.ravel()
+ y = y.ravel()
+ z = quad(x, y)
+ triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1))
+ xs, ys = np.meshgrid(np.linspace(0.1, 0.9, 5), np.linspace(0.1, 0.9, 5))
+ xs = xs.ravel()
+ ys = ys.ravel()
+ linear_interp = mtri.LinearTriInterpolator(triang, z)
+ cubic_min_E = mtri.CubicTriInterpolator(triang, z)
+ cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
+ zs = quad(xs, ys)
+ diff_lin = np.abs(linear_interp(xs, ys) - zs)
+ for interp in (cubic_min_E, cubic_geom):
+ diff_cubic = np.abs(interp(xs, ys) - zs)
+ assert np.max(diff_lin) >= 10 * np.max(diff_cubic)
+ assert (np.dot(diff_lin, diff_lin) >=
+ 100 * np.dot(diff_cubic, diff_cubic))
+
+
+def test_triinterpcubic_C1_continuity():
+ # Below the 4 tests which demonstrate C1 continuity of the
+ # TriCubicInterpolator (testing the cubic shape functions on arbitrary
+ # triangle):
+ #
+ # 1) Testing continuity of function & derivatives at corner for all 9
+ # shape functions. Testing also function values at same location.
+ # 2) Testing C1 continuity along each edge (as gradient is polynomial of
+ # 2nd order, it is sufficient to test at the middle).
+ # 3) Testing C1 continuity at triangle barycenter (where the 3 subtriangles
+ # meet)
+ # 4) Testing C1 continuity at median 1/3 points (midside between 2
+ # subtriangles)
+
+ # Utility test function check_continuity
+ def check_continuity(interpolator, loc, values=None):
+ """
+ Checks the continuity of interpolator (and its derivatives) near
+ location loc. Can check the value at loc itself if *values* is
+ provided.
+
+ *interpolator* TriInterpolator
+ *loc* location to test (x0, y0)
+ *values* (optional) array [z0, dzx0, dzy0] to check the value at *loc*
+ """
+ n_star = 24 # Number of continuity points in a boundary of loc
+ epsilon = 1.e-10 # Distance for loc boundary
+ k = 100. # Continuity coefficient
+ (loc_x, loc_y) = loc
+ star_x = loc_x + epsilon*np.cos(np.linspace(0., 2*np.pi, n_star))
+ star_y = loc_y + epsilon*np.sin(np.linspace(0., 2*np.pi, n_star))
+ z = interpolator([loc_x], [loc_y])[0]
+ (dzx, dzy) = interpolator.gradient([loc_x], [loc_y])
+ if values is not None:
+ assert_array_almost_equal(z, values[0])
+ assert_array_almost_equal(dzx[0], values[1])
+ assert_array_almost_equal(dzy[0], values[2])
+ diff_z = interpolator(star_x, star_y) - z
+ (tab_dzx, tab_dzy) = interpolator.gradient(star_x, star_y)
+ diff_dzx = tab_dzx - dzx
+ diff_dzy = tab_dzy - dzy
+ assert_array_less(diff_z, epsilon*k)
+ assert_array_less(diff_dzx, epsilon*k)
+ assert_array_less(diff_dzy, epsilon*k)
+
+ # Drawing arbitrary triangle (a, b, c) inside a unit square.
+ (ax, ay) = (0.2, 0.3)
+ (bx, by) = (0.33367, 0.80755)
+ (cx, cy) = (0.669, 0.4335)
+ x = np.array([ax, bx, cx, 0., 1., 1., 0.])
+ y = np.array([ay, by, cy, 0., 0., 1., 1.])
+ triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5],
+ [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]])
+ triang = mtri.Triangulation(x, y, triangles)
+
+ for idof in range(9):
+ z = np.zeros(7, dtype=np.float64)
+ dzx = np.zeros(7, dtype=np.float64)
+ dzy = np.zeros(7, dtype=np.float64)
+ values = np.zeros([3, 3], dtype=np.float64)
+ case = idof//3
+ values[case, idof % 3] = 1.0
+ if case == 0:
+ z[idof] = 1.0
+ elif case == 1:
+ dzx[idof % 3] = 1.0
+ elif case == 2:
+ dzy[idof % 3] = 1.0
+ interp = mtri.CubicTriInterpolator(triang, z, kind='user',
+ dz=(dzx, dzy))
+ # Test 1) Checking values and continuity at nodes
+ check_continuity(interp, (ax, ay), values[:, 0])
+ check_continuity(interp, (bx, by), values[:, 1])
+ check_continuity(interp, (cx, cy), values[:, 2])
+ # Test 2) Checking continuity at midside nodes
+ check_continuity(interp, ((ax+bx)*0.5, (ay+by)*0.5))
+ check_continuity(interp, ((ax+cx)*0.5, (ay+cy)*0.5))
+ check_continuity(interp, ((cx+bx)*0.5, (cy+by)*0.5))
+ # Test 3) Checking continuity at barycenter
+ check_continuity(interp, ((ax+bx+cx)/3., (ay+by+cy)/3.))
+ # Test 4) Checking continuity at median 1/3-point
+ check_continuity(interp, ((4.*ax+bx+cx)/6., (4.*ay+by+cy)/6.))
+ check_continuity(interp, ((ax+4.*bx+cx)/6., (ay+4.*by+cy)/6.))
+ check_continuity(interp, ((ax+bx+4.*cx)/6., (ay+by+4.*cy)/6.))
+
+
+def test_triinterpcubic_cg_solver():
+ # Now 3 basic tests of the Sparse CG solver, used for
+ # TriCubicInterpolator with *kind* = 'min_E'
+ # 1) A commonly used test involves a 2d Poisson matrix.
+ def poisson_sparse_matrix(n, m):
+ """
+ Return the sparse, (n*m, n*m) matrix in coo format resulting from the
+ discretisation of the 2-dimensional Poisson equation according to a
+ finite difference numerical scheme on a uniform (n, m) grid.
+ """
+ l = m*n
+ rows = np.concatenate([
+ np.arange(l, dtype=np.int32),
+ np.arange(l-1, dtype=np.int32), np.arange(1, l, dtype=np.int32),
+ np.arange(l-n, dtype=np.int32), np.arange(n, l, dtype=np.int32)])
+ cols = np.concatenate([
+ np.arange(l, dtype=np.int32),
+ np.arange(1, l, dtype=np.int32), np.arange(l-1, dtype=np.int32),
+ np.arange(n, l, dtype=np.int32), np.arange(l-n, dtype=np.int32)])
+ vals = np.concatenate([
+ 4*np.ones(l, dtype=np.float64),
+ -np.ones(l-1, dtype=np.float64), -np.ones(l-1, dtype=np.float64),
+ -np.ones(l-n, dtype=np.float64), -np.ones(l-n, dtype=np.float64)])
+ # In fact +1 and -1 diags have some zeros
+ vals[l:2*l-1][m-1::m] = 0.
+ vals[2*l-1:3*l-2][m-1::m] = 0.
+ return vals, rows, cols, (n*m, n*m)
+
+ # Instantiating a sparse Poisson matrix of size 48 x 48:
+ (n, m) = (12, 4)
+ mat = mtri._triinterpolate._Sparse_Matrix_coo(*poisson_sparse_matrix(n, m))
+ mat.compress_csc()
+ mat_dense = mat.to_dense()
+ # Testing a sparse solve for all 48 basis vector
+ for itest in range(n*m):
+ b = np.zeros(n*m, dtype=np.float64)
+ b[itest] = 1.
+ x, _ = mtri._triinterpolate._cg(A=mat, b=b, x0=np.zeros(n*m),
+ tol=1.e-10)
+ assert_array_almost_equal(np.dot(mat_dense, x), b)
+
+ # 2) Same matrix with inserting 2 rows - cols with null diag terms
+ # (but still linked with the rest of the matrix by extra-diag terms)
+ (i_zero, j_zero) = (12, 49)
+ vals, rows, cols, _ = poisson_sparse_matrix(n, m)
+ rows = rows + 1*(rows >= i_zero) + 1*(rows >= j_zero)
+ cols = cols + 1*(cols >= i_zero) + 1*(cols >= j_zero)
+ # adding extra-diag terms
+ rows = np.concatenate([rows, [i_zero, i_zero-1, j_zero, j_zero-1]])
+ cols = np.concatenate([cols, [i_zero-1, i_zero, j_zero-1, j_zero]])
+ vals = np.concatenate([vals, [1., 1., 1., 1.]])
+ mat = mtri._triinterpolate._Sparse_Matrix_coo(vals, rows, cols,
+ (n*m + 2, n*m + 2))
+ mat.compress_csc()
+ mat_dense = mat.to_dense()
+ # Testing a sparse solve for all 50 basis vec
+ for itest in range(n*m + 2):
+ b = np.zeros(n*m + 2, dtype=np.float64)
+ b[itest] = 1.
+ x, _ = mtri._triinterpolate._cg(A=mat, b=b, x0=np.ones(n * m + 2),
+ tol=1.e-10)
+ assert_array_almost_equal(np.dot(mat_dense, x), b)
+
+ # 3) Now a simple test that summation of duplicate (i.e. with same rows,
+ # same cols) entries occurs when compressed.
+ vals = np.ones(17, dtype=np.float64)
+ rows = np.array([0, 1, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1],
+ dtype=np.int32)
+ cols = np.array([0, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
+ dtype=np.int32)
+ dim = (3, 3)
+ mat = mtri._triinterpolate._Sparse_Matrix_coo(vals, rows, cols, dim)
+ mat.compress_csc()
+ mat_dense = mat.to_dense()
+ assert_array_almost_equal(mat_dense, np.array([
+ [1., 2., 0.], [2., 1., 5.], [0., 5., 1.]], dtype=np.float64))
+
+
+def test_triinterpcubic_geom_weights():
+ # Tests to check computation of weights for _DOF_estimator_geom:
+ # The weight sum per triangle can be 1. (in case all angles < 90 degrees)
+ # or (2*w_i) where w_i = 1-alpha_i/np.pi is the weight of apex i; alpha_i
+ # is the apex angle > 90 degrees.
+ (ax, ay) = (0., 1.687)
+ x = np.array([ax, 0.5*ax, 0., 1.])
+ y = np.array([ay, -ay, 0., 0.])
+ z = np.zeros(4, dtype=np.float64)
+ triangles = [[0, 2, 3], [1, 3, 2]]
+ sum_w = np.zeros([4, 2]) # 4 possibilities; 2 triangles
+ for theta in np.linspace(0., 2*np.pi, 14): # rotating the figure...
+ x_rot = np.cos(theta)*x + np.sin(theta)*y
+ y_rot = -np.sin(theta)*x + np.cos(theta)*y
+ triang = mtri.Triangulation(x_rot, y_rot, triangles)
+ cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
+ dof_estimator = mtri._triinterpolate._DOF_estimator_geom(cubic_geom)
+ weights = dof_estimator.compute_geom_weights()
+ # Testing for the 4 possibilities...
+ sum_w[0, :] = np.sum(weights, 1) - 1
+ for itri in range(3):
+ sum_w[itri+1, :] = np.sum(weights, 1) - 2*weights[:, itri]
+ assert_array_almost_equal(np.min(np.abs(sum_w), axis=0),
+ np.array([0., 0.], dtype=np.float64))
+
+
+def test_triinterp_colinear():
+ # Tests interpolating inside a triangulation with horizontal colinear
+ # points (refer also to the tests :func:`test_trifinder` ).
+ #
+ # These are not valid triangulations, but we try to deal with the
+ # simplest violations (i. e. those handled by default TriFinder).
+ #
+ # Note that the LinearTriInterpolator and the CubicTriInterpolator with
+ # kind='min_E' or 'geom' still pass a linear patch test.
+ # We also test interpolation inside a flat triangle, by forcing
+ # *tri_index* in a call to :meth:`_interpolate_multikeys`.
+
+ # If +ve, triangulation is OK, if -ve triangulation invalid,
+ # if zero have colinear points but should pass tests anyway.
+ delta = 0.
+
+ x0 = np.array([1.5, 0, 1, 2, 3, 1.5, 1.5])
+ y0 = np.array([-1, 0, 0, 0, 0, delta, 1])
+
+ # We test different affine transformations of the initial figure; to
+ # avoid issues related to round-off errors we only use integer
+ # coefficients (otherwise the Triangulation might become invalid even with
+ # delta == 0).
+ transformations = [[1, 0], [0, 1], [1, 1], [1, 2], [-2, -1], [-2, 1]]
+ for transformation in transformations:
+ x_rot = transformation[0]*x0 + transformation[1]*y0
+ y_rot = -transformation[1]*x0 + transformation[0]*y0
+ (x, y) = (x_rot, y_rot)
+ z = 1.23*x - 4.79*y
+ triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5],
+ [3, 4, 5], [1, 5, 6], [4, 6, 5]]
+ triang = mtri.Triangulation(x, y, triangles)
+ xs = np.linspace(np.min(triang.x), np.max(triang.x), 20)
+ ys = np.linspace(np.min(triang.y), np.max(triang.y), 20)
+ xs, ys = np.meshgrid(xs, ys)
+ xs = xs.ravel()
+ ys = ys.ravel()
+ mask_out = (triang.get_trifinder()(xs, ys) == -1)
+ zs_target = np.ma.array(1.23*xs - 4.79*ys, mask=mask_out)
+
+ linear_interp = mtri.LinearTriInterpolator(triang, z)
+ cubic_min_E = mtri.CubicTriInterpolator(triang, z)
+ cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
+
+ for interp in (linear_interp, cubic_min_E, cubic_geom):
+ zs = interp(xs, ys)
+ assert_array_almost_equal(zs_target, zs)
+
+ # Testing interpolation inside the flat triangle number 4: [2, 3, 5]
+ # by imposing *tri_index* in a call to :meth:`_interpolate_multikeys`
+ itri = 4
+ pt1 = triang.triangles[itri, 0]
+ pt2 = triang.triangles[itri, 1]
+ xs = np.linspace(triang.x[pt1], triang.x[pt2], 10)
+ ys = np.linspace(triang.y[pt1], triang.y[pt2], 10)
+ zs_target = 1.23*xs - 4.79*ys
+ for interp in (linear_interp, cubic_min_E, cubic_geom):
+ zs, = interp._interpolate_multikeys(
+ xs, ys, tri_index=itri*np.ones(10, dtype=np.int32))
+ assert_array_almost_equal(zs_target, zs)
+
+
+def test_triinterp_transformations():
+ # 1) Testing that the interpolation scheme is invariant by rotation of the
+ # whole figure.
+ # Note: This test is non-trivial for a CubicTriInterpolator with
+ # kind='min_E'. It does fail for a non-isotropic stiffness matrix E of
+ # :class:`_ReducedHCT_Element` (tested with E=np.diag([1., 1., 1.])), and
+ # provides a good test for :meth:`get_Kff_and_Ff`of the same class.
+ #
+ # 2) Also testing that the interpolation scheme is invariant by expansion
+ # of the whole figure along one axis.
+ n_angles = 20
+ n_radii = 10
+ min_radius = 0.15
+
+ def z(x, y):
+ r1 = np.hypot(0.5 - x, 0.5 - y)
+ theta1 = np.arctan2(0.5 - x, 0.5 - y)
+ r2 = np.hypot(-x - 0.2, -y - 0.2)
+ theta2 = np.arctan2(-x - 0.2, -y - 0.2)
+ z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
+ (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
+ 0.7*(x**2 + y**2))
+ return (np.max(z)-z)/(np.max(z)-np.min(z))
+
+ # First create the x and y coordinates of the points.
+ radii = np.linspace(min_radius, 0.95, n_radii)
+ angles = np.linspace(0 + n_angles, 2*np.pi + n_angles,
+ n_angles, endpoint=False)
+ angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
+ angles[:, 1::2] += np.pi/n_angles
+ x0 = (radii*np.cos(angles)).flatten()
+ y0 = (radii*np.sin(angles)).flatten()
+ triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation
+ z0 = z(x0, y0)
+
+ # Then create the test points
+ xs0 = np.linspace(-1., 1., 23)
+ ys0 = np.linspace(-1., 1., 23)
+ xs0, ys0 = np.meshgrid(xs0, ys0)
+ xs0 = xs0.ravel()
+ ys0 = ys0.ravel()
+
+ interp_z0 = {}
+ for i_angle in range(2):
+ # Rotating everything
+ theta = 2*np.pi / n_angles * i_angle
+ x = np.cos(theta)*x0 + np.sin(theta)*y0
+ y = -np.sin(theta)*x0 + np.cos(theta)*y0
+ xs = np.cos(theta)*xs0 + np.sin(theta)*ys0
+ ys = -np.sin(theta)*xs0 + np.cos(theta)*ys0
+ triang = mtri.Triangulation(x, y, triang0.triangles)
+ linear_interp = mtri.LinearTriInterpolator(triang, z0)
+ cubic_min_E = mtri.CubicTriInterpolator(triang, z0)
+ cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom')
+ dic_interp = {'lin': linear_interp,
+ 'min_E': cubic_min_E,
+ 'geom': cubic_geom}
+ # Testing that the interpolation is invariant by rotation...
+ for interp_key in ['lin', 'min_E', 'geom']:
+ interp = dic_interp[interp_key]
+ if i_angle == 0:
+ interp_z0[interp_key] = interp(xs0, ys0) # storage
+ else:
+ interpz = interp(xs, ys)
+ matest.assert_array_almost_equal(interpz,
+ interp_z0[interp_key])
+
+ scale_factor = 987654.3210
+ for scaled_axis in ('x', 'y'):
+ # Scaling everything (expansion along scaled_axis)
+ if scaled_axis == 'x':
+ x = scale_factor * x0
+ y = y0
+ xs = scale_factor * xs0
+ ys = ys0
+ else:
+ x = x0
+ y = scale_factor * y0
+ xs = xs0
+ ys = scale_factor * ys0
+ triang = mtri.Triangulation(x, y, triang0.triangles)
+ linear_interp = mtri.LinearTriInterpolator(triang, z0)
+ cubic_min_E = mtri.CubicTriInterpolator(triang, z0)
+ cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom')
+ dic_interp = {'lin': linear_interp,
+ 'min_E': cubic_min_E,
+ 'geom': cubic_geom}
+ # Test that the interpolation is invariant by expansion along 1 axis...
+ for interp_key in ['lin', 'min_E', 'geom']:
+ interpz = dic_interp[interp_key](xs, ys)
+ matest.assert_array_almost_equal(interpz, interp_z0[interp_key])
+
+
+@image_comparison(['tri_smooth_contouring.png'], remove_text=True, tol=0.072)
+def test_tri_smooth_contouring():
+ # Image comparison based on example tricontour_smooth_user.
+ n_angles = 20
+ n_radii = 10
+ min_radius = 0.15
+
+ def z(x, y):
+ r1 = np.hypot(0.5 - x, 0.5 - y)
+ theta1 = np.arctan2(0.5 - x, 0.5 - y)
+ r2 = np.hypot(-x - 0.2, -y - 0.2)
+ theta2 = np.arctan2(-x - 0.2, -y - 0.2)
+ z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
+ (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
+ 0.7*(x**2 + y**2))
+ return (np.max(z)-z)/(np.max(z)-np.min(z))
+
+ # First create the x and y coordinates of the points.
+ radii = np.linspace(min_radius, 0.95, n_radii)
+ angles = np.linspace(0 + n_angles, 2*np.pi + n_angles,
+ n_angles, endpoint=False)
+ angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
+ angles[:, 1::2] += np.pi/n_angles
+ x0 = (radii*np.cos(angles)).flatten()
+ y0 = (radii*np.sin(angles)).flatten()
+ triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation
+ z0 = z(x0, y0)
+ triang0.set_mask(np.hypot(x0[triang0.triangles].mean(axis=1),
+ y0[triang0.triangles].mean(axis=1))
+ < min_radius)
+
+ # Then the plot
+ refiner = mtri.UniformTriRefiner(triang0)
+ tri_refi, z_test_refi = refiner.refine_field(z0, subdiv=4)
+ levels = np.arange(0., 1., 0.025)
+ plt.triplot(triang0, lw=0.5, color='0.5')
+ plt.tricontour(tri_refi, z_test_refi, levels=levels, colors="black")
+
+
+@image_comparison(['tri_smooth_gradient.png'], remove_text=True, tol=0.092)
+def test_tri_smooth_gradient():
+ # Image comparison based on example trigradient_demo.
+
+ def dipole_potential(x, y):
+ """An electric dipole potential V."""
+ r_sq = x**2 + y**2
+ theta = np.arctan2(y, x)
+ z = np.cos(theta)/r_sq
+ return (np.max(z)-z) / (np.max(z)-np.min(z))
+
+ # Creating a Triangulation
+ n_angles = 30
+ n_radii = 10
+ min_radius = 0.2
+ radii = np.linspace(min_radius, 0.95, n_radii)
+ angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
+ angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
+ angles[:, 1::2] += np.pi/n_angles
+ x = (radii*np.cos(angles)).flatten()
+ y = (radii*np.sin(angles)).flatten()
+ V = dipole_potential(x, y)
+ triang = mtri.Triangulation(x, y)
+ triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
+ y[triang.triangles].mean(axis=1))
+ < min_radius)
+
+ # Refine data - interpolates the electrical potential V
+ refiner = mtri.UniformTriRefiner(triang)
+ tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)
+
+ # Computes the electrical field (Ex, Ey) as gradient of -V
+ tci = mtri.CubicTriInterpolator(triang, -V)
+ Ex, Ey = tci.gradient(triang.x, triang.y)
+ E_norm = np.hypot(Ex, Ey)
+
+ # Plot the triangulation, the potential iso-contours and the vector field
+ plt.figure()
+ plt.gca().set_aspect('equal')
+ plt.triplot(triang, color='0.8')
+
+ levels = np.arange(0., 1., 0.01)
+ cmap = mpl.colormaps['hot']
+ plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
+ linewidths=[2.0, 1.0, 1.0, 1.0])
+ # Plots direction of the electrical vector field
+ plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
+ units='xy', scale=10., zorder=3, color='blue',
+ width=0.007, headwidth=3., headlength=4.)
+ # We are leaving ax.use_sticky_margins as True, so the
+ # view limits are the contour data limits.
+
+
+def test_tritools():
+ # Tests TriAnalyzer.scale_factors on masked triangulation
+ # Tests circle_ratios on equilateral and right-angled triangle.
+ x = np.array([0., 1., 0.5, 0., 2.])
+ y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.])
+ triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32)
+ mask = np.array([False, False, True], dtype=bool)
+ triang = mtri.Triangulation(x, y, triangles, mask=mask)
+ analyser = mtri.TriAnalyzer(triang)
+ assert_array_almost_equal(analyser.scale_factors, [1, 1/(1+3**.5/2)])
+ assert_array_almost_equal(
+ analyser.circle_ratios(rescale=False),
+ np.ma.masked_array([0.5, 1./(1.+np.sqrt(2.)), np.nan], mask))
+
+ # Tests circle ratio of a flat triangle
+ x = np.array([0., 1., 2.])
+ y = np.array([1., 1.+3., 1.+6.])
+ triangles = np.array([[0, 1, 2]], dtype=np.int32)
+ triang = mtri.Triangulation(x, y, triangles)
+ analyser = mtri.TriAnalyzer(triang)
+ assert_array_almost_equal(analyser.circle_ratios(), np.array([0.]))
+
+ # Tests TriAnalyzer.get_flat_tri_mask
+ # Creates a triangulation of [-1, 1] x [-1, 1] with contiguous groups of
+ # 'flat' triangles at the 4 corners and at the center. Checks that only
+ # those at the borders are eliminated by TriAnalyzer.get_flat_tri_mask
+ n = 9
+
+ def power(x, a):
+ return np.abs(x)**a*np.sign(x)
+
+ x = np.linspace(-1., 1., n+1)
+ x, y = np.meshgrid(power(x, 2.), power(x, 0.25))
+ x = x.ravel()
+ y = y.ravel()
+
+ triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1))
+ analyser = mtri.TriAnalyzer(triang)
+ mask_flat = analyser.get_flat_tri_mask(0.2)
+ verif_mask = np.zeros(162, dtype=bool)
+ corners_index = [0, 1, 2, 3, 14, 15, 16, 17, 18, 19, 34, 35, 126, 127,
+ 142, 143, 144, 145, 146, 147, 158, 159, 160, 161]
+ verif_mask[corners_index] = True
+ assert_array_equal(mask_flat, verif_mask)
+
+ # Now including a hole (masked triangle) at the center. The center also
+ # shall be eliminated by get_flat_tri_mask.
+ mask = np.zeros(162, dtype=bool)
+ mask[80] = True
+ triang.set_mask(mask)
+ mask_flat = analyser.get_flat_tri_mask(0.2)
+ center_index = [44, 45, 62, 63, 78, 79, 80, 81, 82, 83, 98, 99, 116, 117]
+ verif_mask[center_index] = True
+ assert_array_equal(mask_flat, verif_mask)
+
+
+def test_trirefine():
+ # Testing subdiv=2 refinement
+ n = 3
+ subdiv = 2
+ x = np.linspace(-1., 1., n+1)
+ x, y = np.meshgrid(x, x)
+ x = x.ravel()
+ y = y.ravel()
+ mask = np.zeros(2*n**2, dtype=bool)
+ mask[n**2:] = True
+ triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1),
+ mask=mask)
+ refiner = mtri.UniformTriRefiner(triang)
+ refi_triang = refiner.refine_triangulation(subdiv=subdiv)
+ x_refi = refi_triang.x
+ y_refi = refi_triang.y
+
+ n_refi = n * subdiv**2
+ x_verif = np.linspace(-1., 1., n_refi+1)
+ x_verif, y_verif = np.meshgrid(x_verif, x_verif)
+ x_verif = x_verif.ravel()
+ y_verif = y_verif.ravel()
+ ind1d = np.isin(np.around(x_verif*(2.5+y_verif), 8),
+ np.around(x_refi*(2.5+y_refi), 8))
+ assert_array_equal(ind1d, True)
+
+ # Testing the mask of the refined triangulation
+ refi_mask = refi_triang.mask
+ refi_tri_barycenter_x = np.sum(refi_triang.x[refi_triang.triangles],
+ axis=1) / 3.
+ refi_tri_barycenter_y = np.sum(refi_triang.y[refi_triang.triangles],
+ axis=1) / 3.
+ tri_finder = triang.get_trifinder()
+ refi_tri_indices = tri_finder(refi_tri_barycenter_x,
+ refi_tri_barycenter_y)
+ refi_tri_mask = triang.mask[refi_tri_indices]
+ assert_array_equal(refi_mask, refi_tri_mask)
+
+ # Testing that the numbering of triangles does not change the
+ # interpolation result.
+ x = np.asarray([0.0, 1.0, 0.0, 1.0])
+ y = np.asarray([0.0, 0.0, 1.0, 1.0])
+ triang = [mtri.Triangulation(x, y, [[0, 1, 3], [3, 2, 0]]),
+ mtri.Triangulation(x, y, [[0, 1, 3], [2, 0, 3]])]
+ z = np.hypot(x - 0.3, y - 0.4)
+ # Refining the 2 triangulations and reordering the points
+ xyz_data = []
+ for i in range(2):
+ refiner = mtri.UniformTriRefiner(triang[i])
+ refined_triang, refined_z = refiner.refine_field(z, subdiv=1)
+ xyz = np.dstack((refined_triang.x, refined_triang.y, refined_z))[0]
+ xyz = xyz[np.lexsort((xyz[:, 1], xyz[:, 0]))]
+ xyz_data += [xyz]
+ assert_array_almost_equal(xyz_data[0], xyz_data[1])
+
+
+@pytest.mark.parametrize('interpolator',
+ [mtri.LinearTriInterpolator,
+ mtri.CubicTriInterpolator],
+ ids=['linear', 'cubic'])
+def test_trirefine_masked(interpolator):
+ # Repeated points means we will have fewer triangles than points, and thus
+ # get masking.
+ x, y = np.mgrid[:2, :2]
+ x = np.repeat(x.flatten(), 2)
+ y = np.repeat(y.flatten(), 2)
+
+ z = np.zeros_like(x)
+ tri = mtri.Triangulation(x, y)
+ refiner = mtri.UniformTriRefiner(tri)
+ interp = interpolator(tri, z)
+ refiner.refine_field(z, triinterpolator=interp, subdiv=2)
+
+
+def meshgrid_triangles(n):
+ """
+ Return (2*(N-1)**2, 3) array of triangles to mesh (N, N)-point np.meshgrid.
+ """
+ tri = []
+ for i in range(n-1):
+ for j in range(n-1):
+ a = i + j*n
+ b = (i+1) + j*n
+ c = i + (j+1)*n
+ d = (i+1) + (j+1)*n
+ tri += [[a, b, d], [a, d, c]]
+ return np.array(tri, dtype=np.int32)
+
+
+def test_triplot_return():
+ # Check that triplot returns the artists it adds
+ ax = plt.figure().add_subplot()
+ triang = mtri.Triangulation(
+ [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0],
+ triangles=[[0, 1, 3], [3, 2, 0]])
+ assert ax.triplot(triang, "b-") is not None, \
+ 'triplot should return the artist it adds'
+
+
+def test_trirefiner_fortran_contiguous_triangles():
+ # github issue 4180. Test requires two arrays of triangles that are
+ # identical except that one is C-contiguous and one is fortran-contiguous.
+ triangles1 = np.array([[2, 0, 3], [2, 1, 0]])
+ assert not np.isfortran(triangles1)
+
+ triangles2 = np.array(triangles1, copy=True, order='F')
+ assert np.isfortran(triangles2)
+
+ x = np.array([0.39, 0.59, 0.43, 0.32])
+ y = np.array([33.99, 34.01, 34.19, 34.18])
+ triang1 = mtri.Triangulation(x, y, triangles1)
+ triang2 = mtri.Triangulation(x, y, triangles2)
+
+ refiner1 = mtri.UniformTriRefiner(triang1)
+ refiner2 = mtri.UniformTriRefiner(triang2)
+
+ fine_triang1 = refiner1.refine_triangulation(subdiv=1)
+ fine_triang2 = refiner2.refine_triangulation(subdiv=1)
+
+ assert_array_equal(fine_triang1.triangles, fine_triang2.triangles)
+
+
+def test_qhull_triangle_orientation():
+ # github issue 4437.
+ xi = np.linspace(-2, 2, 100)
+ x, y = map(np.ravel, np.meshgrid(xi, xi))
+ w = (x > y - 1) & (x < -1.95) & (y > -1.2)
+ x, y = x[w], y[w]
+ theta = np.radians(25)
+ x1 = x*np.cos(theta) - y*np.sin(theta)
+ y1 = x*np.sin(theta) + y*np.cos(theta)
+
+ # Calculate Delaunay triangulation using Qhull.
+ triang = mtri.Triangulation(x1, y1)
+
+ # Neighbors returned by Qhull.
+ qhull_neighbors = triang.neighbors
+
+ # Obtain neighbors using own C++ calculation.
+ triang._neighbors = None
+ own_neighbors = triang.neighbors
+
+ assert_array_equal(qhull_neighbors, own_neighbors)
+
+
+def test_trianalyzer_mismatched_indices():
+ # github issue 4999.
+ x = np.array([0., 1., 0.5, 0., 2.])
+ y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.])
+ triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32)
+ mask = np.array([False, False, True], dtype=bool)
+ triang = mtri.Triangulation(x, y, triangles, mask=mask)
+ analyser = mtri.TriAnalyzer(triang)
+ # numpy >= 1.10 raises a VisibleDeprecationWarning in the following line
+ # prior to the fix.
+ analyser._get_compressed_triangulation()
+
+
+def test_tricontourf_decreasing_levels():
+ # github issue 5477.
+ x = [0.0, 1.0, 1.0]
+ y = [0.0, 0.0, 1.0]
+ z = [0.2, 0.4, 0.6]
+ plt.figure()
+ with pytest.raises(ValueError):
+ plt.tricontourf(x, y, z, [1.0, 0.0])
+
+
+def test_internal_cpp_api() -> None:
+ # Following github issue 8197.
+ from matplotlib import _tri # noqa: F401, ensure lazy-loaded module *is* loaded.
+
+ # C++ Triangulation.
+ with pytest.raises(
+ TypeError,
+ match=r'__init__\(\): incompatible constructor arguments.'):
+ mpl._tri.Triangulation() # type: ignore[call-arg]
+
+ with pytest.raises(
+ ValueError, match=r'x and y must be 1D arrays of the same length'):
+ mpl._tri.Triangulation(np.array([]), np.array([1]), np.array([[]]), (), (), (),
+ False)
+
+ x = np.array([0, 1, 1], dtype=np.float64)
+ y = np.array([0, 0, 1], dtype=np.float64)
+ with pytest.raises(
+ ValueError,
+ match=r'triangles must be a 2D array of shape \(\?,3\)'):
+ mpl._tri.Triangulation(x, y, np.array([[0, 1]]), (), (), (), False)
+
+ tris = np.array([[0, 1, 2]], dtype=np.int_)
+ with pytest.raises(
+ ValueError,
+ match=r'mask must be a 1D array with the same length as the '
+ r'triangles array'):
+ mpl._tri.Triangulation(x, y, tris, np.array([0, 1]), (), (), False)
+
+ with pytest.raises(
+ ValueError, match=r'edges must be a 2D array with shape \(\?,2\)'):
+ mpl._tri.Triangulation(x, y, tris, (), np.array([[1]]), (), False)
+
+ with pytest.raises(
+ ValueError,
+ match=r'neighbors must be a 2D array with the same shape as the '
+ r'triangles array'):
+ mpl._tri.Triangulation(x, y, tris, (), (), np.array([[-1]]), False)
+
+ triang = mpl._tri.Triangulation(x, y, tris, (), (), (), False)
+
+ with pytest.raises(
+ ValueError,
+ match=r'z must be a 1D array with the same length as the '
+ r'triangulation x and y arrays'):
+ triang.calculate_plane_coefficients([])
+
+ for mask in ([0, 1], None):
+ with pytest.raises(
+ ValueError,
+ match=r'mask must be a 1D array with the same length as the '
+ r'triangles array'):
+ triang.set_mask(mask) # type: ignore[arg-type]
+
+ triang.set_mask(np.array([True]))
+ assert_array_equal(triang.get_edges(), np.empty((0, 2)))
+
+ triang.set_mask(()) # Equivalent to Python Triangulation mask=None
+ assert_array_equal(triang.get_edges(), [[1, 0], [2, 0], [2, 1]])
+
+ # C++ TriContourGenerator.
+ with pytest.raises(
+ TypeError,
+ match=r'__init__\(\): incompatible constructor arguments.'):
+ mpl._tri.TriContourGenerator() # type: ignore[call-arg]
+
+ with pytest.raises(
+ ValueError,
+ match=r'z must be a 1D array with the same length as the x and y arrays'):
+ mpl._tri.TriContourGenerator(triang, np.array([1]))
+
+ z = np.array([0, 1, 2])
+ tcg = mpl._tri.TriContourGenerator(triang, z)
+
+ with pytest.raises(
+ ValueError, match=r'filled contour levels must be increasing'):
+ tcg.create_filled_contour(1, 0)
+
+ # C++ TrapezoidMapTriFinder.
+ with pytest.raises(
+ TypeError,
+ match=r'__init__\(\): incompatible constructor arguments.'):
+ mpl._tri.TrapezoidMapTriFinder() # type: ignore[call-arg]
+
+ trifinder = mpl._tri.TrapezoidMapTriFinder(triang)
+
+ with pytest.raises(
+ ValueError, match=r'x and y must be array-like with same shape'):
+ trifinder.find_many(np.array([0]), np.array([0, 1]))
+
+
+def test_qhull_large_offset():
+ # github issue 8682.
+ x = np.asarray([0, 1, 0, 1, 0.5])
+ y = np.asarray([0, 0, 1, 1, 0.5])
+
+ offset = 1e10
+ triang = mtri.Triangulation(x, y)
+ triang_offset = mtri.Triangulation(x + offset, y + offset)
+ assert len(triang.triangles) == len(triang_offset.triangles)
+
+
+def test_tricontour_non_finite_z():
+ # github issue 10167.
+ x = [0, 1, 0, 1]
+ y = [0, 0, 1, 1]
+ triang = mtri.Triangulation(x, y)
+ plt.figure()
+
+ with pytest.raises(ValueError, match='z array must not contain non-finite '
+ 'values within the triangulation'):
+ plt.tricontourf(triang, [0, 1, 2, np.inf])
+
+ with pytest.raises(ValueError, match='z array must not contain non-finite '
+ 'values within the triangulation'):
+ plt.tricontourf(triang, [0, 1, 2, -np.inf])
+
+ with pytest.raises(ValueError, match='z array must not contain non-finite '
+ 'values within the triangulation'):
+ plt.tricontourf(triang, [0, 1, 2, np.nan])
+
+ with pytest.raises(ValueError, match='z must not contain masked points '
+ 'within the triangulation'):
+ plt.tricontourf(triang, np.ma.array([0, 1, 2, 3], mask=[1, 0, 0, 0]))
+
+
+def test_tricontourset_reuse():
+ # If TriContourSet returned from one tricontour(f) call is passed as first
+ # argument to another the underlying C++ contour generator will be reused.
+ x = [0.0, 0.5, 1.0]
+ y = [0.0, 1.0, 0.0]
+ z = [1.0, 2.0, 3.0]
+ fig, ax = plt.subplots()
+ tcs1 = ax.tricontourf(x, y, z)
+ tcs2 = ax.tricontour(x, y, z)
+ assert tcs2._contour_generator != tcs1._contour_generator
+ tcs3 = ax.tricontour(tcs1, z)
+ assert tcs3._contour_generator == tcs1._contour_generator
+
+
+@check_figures_equal(extensions=['png'])
+def test_triplot_with_ls(fig_test, fig_ref):
+ x = [0, 2, 1]
+ y = [0, 0, 1]
+ data = [[0, 1, 2]]
+ fig_test.subplots().triplot(x, y, data, ls='--')
+ fig_ref.subplots().triplot(x, y, data, linestyle='--')
+
+
+def test_triplot_label():
+ x = [0, 2, 1]
+ y = [0, 0, 1]
+ data = [[0, 1, 2]]
+ fig, ax = plt.subplots()
+ lines, markers = ax.triplot(x, y, data, label='label')
+ handles, labels = ax.get_legend_handles_labels()
+ assert labels == ['label']
+ assert len(handles) == 1
+ assert handles[0] is lines
+
+
+def test_tricontour_path():
+ x = [0, 4, 4, 0, 2]
+ y = [0, 0, 4, 4, 2]
+ triang = mtri.Triangulation(x, y)
+ _, ax = plt.subplots()
+
+ # Line strip from boundary to boundary
+ cs = ax.tricontour(triang, [1, 0, 0, 0, 0], levels=[0.5])
+ paths = cs.get_paths()
+ assert len(paths) == 1
+ expected_vertices = [[2, 0], [1, 1], [0, 2]]
+ assert_array_almost_equal(paths[0].vertices, expected_vertices)
+ assert_array_equal(paths[0].codes, [1, 2, 2])
+ assert_array_almost_equal(
+ paths[0].to_polygons(closed_only=False), [expected_vertices])
+
+ # Closed line loop inside domain
+ cs = ax.tricontour(triang, [0, 0, 0, 0, 1], levels=[0.5])
+ paths = cs.get_paths()
+ assert len(paths) == 1
+ expected_vertices = [[3, 1], [3, 3], [1, 3], [1, 1], [3, 1]]
+ assert_array_almost_equal(paths[0].vertices, expected_vertices)
+ assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])
+ assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])
+
+
+def test_tricontourf_path():
+ x = [0, 4, 4, 0, 2]
+ y = [0, 0, 4, 4, 2]
+ triang = mtri.Triangulation(x, y)
+ _, ax = plt.subplots()
+
+ # Polygon inside domain
+ cs = ax.tricontourf(triang, [0, 0, 0, 0, 1], levels=[0.5, 1.5])
+ paths = cs.get_paths()
+ assert len(paths) == 1
+ expected_vertices = [[3, 1], [3, 3], [1, 3], [1, 1], [3, 1]]
+ assert_array_almost_equal(paths[0].vertices, expected_vertices)
+ assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])
+ assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])
+
+ # Polygon following boundary and inside domain
+ cs = ax.tricontourf(triang, [1, 0, 0, 0, 0], levels=[0.5, 1.5])
+ paths = cs.get_paths()
+ assert len(paths) == 1
+ expected_vertices = [[2, 0], [1, 1], [0, 2], [0, 0], [2, 0]]
+ assert_array_almost_equal(paths[0].vertices, expected_vertices)
+ assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])
+ assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])
+
+ # Polygon is outer boundary with hole
+ cs = ax.tricontourf(triang, [0, 0, 0, 0, 1], levels=[-0.5, 0.5])
+ paths = cs.get_paths()
+ assert len(paths) == 1
+ expected_vertices = [[0, 0], [4, 0], [4, 4], [0, 4], [0, 0],
+ [1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]
+ assert_array_almost_equal(paths[0].vertices, expected_vertices)
+ assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79, 1, 2, 2, 2, 79])
+ assert_array_almost_equal(paths[0].to_polygons(), np.split(expected_vertices, [5]))
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_type1font.py b/lib/python3.12/site-packages/matplotlib/tests/test_type1font.py
new file mode 100644
index 0000000000000000000000000000000000000000..9b8a2d1f07c6fd7124a4bc8349766c01c3a58435
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_type1font.py
@@ -0,0 +1,160 @@
+import matplotlib._type1font as t1f
+import os.path
+import difflib
+import pytest
+
+
+def test_Type1Font():
+ filename = os.path.join(os.path.dirname(__file__), 'cmr10.pfb')
+ font = t1f.Type1Font(filename)
+ slanted = font.transform({'slant': 1})
+ condensed = font.transform({'extend': 0.5})
+ with open(filename, 'rb') as fd:
+ rawdata = fd.read()
+ assert font.parts[0] == rawdata[0x0006:0x10c5]
+ assert font.parts[1] == rawdata[0x10cb:0x897f]
+ assert font.parts[2] == rawdata[0x8985:0x8ba6]
+ assert font.decrypted.startswith(b'dup\n/Private 18 dict dup begin')
+ assert font.decrypted.endswith(b'mark currentfile closefile\n')
+ assert slanted.decrypted.startswith(b'dup\n/Private 18 dict dup begin')
+ assert slanted.decrypted.endswith(b'mark currentfile closefile\n')
+ assert b'UniqueID 5000793' in font.parts[0]
+ assert b'UniqueID 5000793' in font.decrypted
+ assert font._pos['UniqueID'] == [(797, 818), (4483, 4504)]
+
+ len0 = len(font.parts[0])
+ for key in font._pos.keys():
+ for pos0, pos1 in font._pos[key]:
+ if pos0 < len0:
+ data = font.parts[0][pos0:pos1]
+ else:
+ data = font.decrypted[pos0-len0:pos1-len0]
+ assert data.startswith(f'/{key}'.encode('ascii'))
+ assert {'FontType', 'FontMatrix', 'PaintType', 'ItalicAngle', 'RD'
+ } < set(font._pos.keys())
+
+ assert b'UniqueID 5000793' not in slanted.parts[0]
+ assert b'UniqueID 5000793' not in slanted.decrypted
+ assert 'UniqueID' not in slanted._pos
+ assert font.prop['Weight'] == 'Medium'
+ assert not font.prop['isFixedPitch']
+ assert font.prop['ItalicAngle'] == 0
+ assert slanted.prop['ItalicAngle'] == -45
+ assert font.prop['Encoding'][5] == 'Pi'
+ assert isinstance(font.prop['CharStrings']['Pi'], bytes)
+ assert font._abbr['ND'] == 'ND'
+
+ differ = difflib.Differ()
+ diff = list(differ.compare(
+ font.parts[0].decode('latin-1').splitlines(),
+ slanted.parts[0].decode('latin-1').splitlines()))
+ for line in (
+ # Removes UniqueID
+ '- /UniqueID 5000793 def',
+ # Changes the font name
+ '- /FontName /CMR10 def',
+ '+ /FontName/CMR10_Slant_1000 def',
+ # Alters FontMatrix
+ '- /FontMatrix [0.001 0 0 0.001 0 0 ]readonly def',
+ '+ /FontMatrix [0.001 0 0.001 0.001 0 0] readonly def',
+ # Alters ItalicAngle
+ '- /ItalicAngle 0 def',
+ '+ /ItalicAngle -45.0 def'):
+ assert line in diff, 'diff to slanted font must contain %s' % line
+
+ diff = list(differ.compare(
+ font.parts[0].decode('latin-1').splitlines(),
+ condensed.parts[0].decode('latin-1').splitlines()))
+ for line in (
+ # Removes UniqueID
+ '- /UniqueID 5000793 def',
+ # Changes the font name
+ '- /FontName /CMR10 def',
+ '+ /FontName/CMR10_Extend_500 def',
+ # Alters FontMatrix
+ '- /FontMatrix [0.001 0 0 0.001 0 0 ]readonly def',
+ '+ /FontMatrix [0.0005 0 0 0.001 0 0] readonly def'):
+ assert line in diff, 'diff to condensed font must contain %s' % line
+
+
+def test_Type1Font_2():
+ filename = os.path.join(os.path.dirname(__file__),
+ 'Courier10PitchBT-Bold.pfb')
+ font = t1f.Type1Font(filename)
+ assert font.prop['Weight'] == 'Bold'
+ assert font.prop['isFixedPitch']
+ assert font.prop['Encoding'][65] == 'A' # the font uses StandardEncoding
+ (pos0, pos1), = font._pos['Encoding']
+ assert font.parts[0][pos0:pos1] == b'/Encoding StandardEncoding'
+ assert font._abbr['ND'] == '|-'
+
+
+def test_tokenize():
+ data = (b'1234/abc false -9.81 Foo <<[0 1 2]<0 1ef a\t>>>\n'
+ b'(string with(nested\t\\) par)ens\\\\)')
+ # 1 2 x 2 xx1
+ # 1 and 2 are matching parens, x means escaped character
+ n, w, num, kw, d = 'name', 'whitespace', 'number', 'keyword', 'delimiter'
+ b, s = 'boolean', 'string'
+ correct = [
+ (num, 1234), (n, 'abc'), (w, ' '), (b, False), (w, ' '), (num, -9.81),
+ (w, ' '), (kw, 'Foo'), (w, ' '), (d, '<<'), (d, '['), (num, 0),
+ (w, ' '), (num, 1), (w, ' '), (num, 2), (d, ']'), (s, b'\x01\xef\xa0'),
+ (d, '>>'), (w, '\n'), (s, 'string with(nested\t) par)ens\\')
+ ]
+ correct_no_ws = [x for x in correct if x[0] != w]
+
+ def convert(tokens):
+ return [(t.kind, t.value()) for t in tokens]
+
+ assert convert(t1f._tokenize(data, False)) == correct
+ assert convert(t1f._tokenize(data, True)) == correct_no_ws
+
+ def bin_after(n):
+ tokens = t1f._tokenize(data, True)
+ result = []
+ for _ in range(n):
+ result.append(next(tokens))
+ result.append(tokens.send(10))
+ return convert(result)
+
+ for n in range(1, len(correct_no_ws)):
+ result = bin_after(n)
+ assert result[:-1] == correct_no_ws[:n]
+ assert result[-1][0] == 'binary'
+ assert isinstance(result[-1][1], bytes)
+
+
+def test_tokenize_errors():
+ with pytest.raises(ValueError):
+ list(t1f._tokenize(b'1234 (this (string) is unterminated\\)', True))
+ with pytest.raises(ValueError):
+ list(t1f._tokenize(b'/Foo<01234', True))
+ with pytest.raises(ValueError):
+ list(t1f._tokenize(b'/Foo<01234abcg>/Bar', True))
+
+
+def test_overprecision():
+ # We used to output too many digits in FontMatrix entries and
+ # ItalicAngle, which could make Type-1 parsers unhappy.
+ filename = os.path.join(os.path.dirname(__file__), 'cmr10.pfb')
+ font = t1f.Type1Font(filename)
+ slanted = font.transform({'slant': .167})
+ lines = slanted.parts[0].decode('ascii').splitlines()
+ matrix, = (line[line.index('[')+1:line.index(']')]
+ for line in lines if '/FontMatrix' in line)
+ angle, = (word
+ for line in lines if '/ItalicAngle' in line
+ for word in line.split() if word[0] in '-0123456789')
+ # the following used to include 0.00016700000000000002
+ assert matrix == '0.001 0 0.000167 0.001 0 0'
+ # and here we had -9.48090361795083
+ assert angle == '-9.4809'
+
+
+def test_encrypt_decrypt_roundtrip():
+ data = b'this is my plaintext \0\1\2\3'
+ encrypted = t1f.Type1Font._encrypt(data, 'eexec')
+ decrypted = t1f.Type1Font._decrypt(encrypted, 'eexec')
+ assert encrypted != decrypted
+ assert data == decrypted
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_units.py b/lib/python3.12/site-packages/matplotlib/tests/test_units.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc71f685857e2e6da4677969837bd66c828cc17c
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/tests/test_units.py
@@ -0,0 +1,353 @@
+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.patches as mpatches
+import matplotlib.units as munits
+from matplotlib.category import StrCategoryConverter, UnitData
+from matplotlib.dates import DateConverter
+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_explicit_converter():
+ d1 = {"a": 1, "b": 2}
+ str_cat_converter = StrCategoryConverter()
+ str_cat_converter_2 = StrCategoryConverter()
+ date_converter = DateConverter()
+
+ # Explicit is set
+ fig1, ax1 = plt.subplots()
+ ax1.xaxis.set_converter(str_cat_converter)
+ assert ax1.xaxis.get_converter() == str_cat_converter
+ # Explicit not overridden by implicit
+ ax1.plot(d1.keys(), d1.values())
+ assert ax1.xaxis.get_converter() == str_cat_converter
+ # No error when called twice with equivalent input
+ ax1.xaxis.set_converter(str_cat_converter)
+ # Error when explicit called twice
+ with pytest.raises(RuntimeError):
+ ax1.xaxis.set_converter(str_cat_converter_2)
+
+ fig2, ax2 = plt.subplots()
+ ax2.plot(d1.keys(), d1.values())
+
+ # No error when equivalent type is used
+ ax2.xaxis.set_converter(str_cat_converter)
+
+ fig3, ax3 = plt.subplots()
+ ax3.plot(d1.keys(), d1.values())
+
+ # Warn when implicit overridden
+ with pytest.warns():
+ ax3.xaxis.set_converter(date_converter)
+
+
+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)
+
+
+def test_connection_patch_units(pd):
+ # tests that this doesn't raise an error
+ fig, (ax1, ax2) = plt.subplots(nrows=2, figsize=(10, 5))
+ x = pd.Timestamp('2017-01-01T12')
+ ax1.axvline(x)
+ y = "test test"
+ ax2.axhline(y)
+ arr = mpatches.ConnectionPatch((x, 0), (0, y),
+ coordsA='data', coordsB='data',
+ axesA=ax1, axesB=ax2)
+ fig.add_artist(arr)
+ fig.draw_without_rendering()
diff --git a/lib/python3.12/site-packages/matplotlib/tests/test_usetex.py b/lib/python3.12/site-packages/matplotlib/tests/test_usetex.py
new file mode 100644
index 0000000000000000000000000000000000000000..342face4504fbc444c530fa08335cf19b3c98e6f
--- /dev/null
+++ b/lib/python3.12/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/lib/python3.12/site-packages/matplotlib/textpath.pyi b/lib/python3.12/site-packages/matplotlib/textpath.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..34d4e92ac47ef45c70ab906bc3b8d1fa2bac07dd
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/textpath.pyi
@@ -0,0 +1,74 @@
+from matplotlib.font_manager import FontProperties
+from matplotlib.ft2font import FT2Font
+from matplotlib.mathtext import MathTextParser, VectorParse
+from matplotlib.path import Path
+
+import numpy as np
+
+from typing import Literal
+
+class TextToPath:
+ FONT_SCALE: float
+ DPI: float
+ mathtext_parser: MathTextParser[VectorParse]
+ def __init__(self) -> None: ...
+ def get_text_width_height_descent(
+ self, s: str, prop: FontProperties, ismath: bool | Literal["TeX"]
+ ) -> tuple[float, float, float]: ...
+ def get_text_path(
+ self, prop: FontProperties, s: str, ismath: bool | Literal["TeX"] = ...
+ ) -> list[np.ndarray]: ...
+ def get_glyphs_with_font(
+ self,
+ font: FT2Font,
+ s: str,
+ glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ...,
+ return_new_glyphs_only: bool = ...,
+ ) -> tuple[
+ list[tuple[str, float, float, float]],
+ dict[str, tuple[np.ndarray, np.ndarray]],
+ list[tuple[list[tuple[float, float]], list[int]]],
+ ]: ...
+ def get_glyphs_mathtext(
+ self,
+ prop: FontProperties,
+ s: str,
+ glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ...,
+ return_new_glyphs_only: bool = ...,
+ ) -> tuple[
+ list[tuple[str, float, float, float]],
+ dict[str, tuple[np.ndarray, np.ndarray]],
+ list[tuple[list[tuple[float, float]], list[int]]],
+ ]: ...
+ def get_glyphs_tex(
+ self,
+ prop: FontProperties,
+ s: str,
+ glyph_map: dict[str, tuple[np.ndarray, np.ndarray]] | None = ...,
+ return_new_glyphs_only: bool = ...,
+ ) -> tuple[
+ list[tuple[str, float, float, float]],
+ dict[str, tuple[np.ndarray, np.ndarray]],
+ list[tuple[list[tuple[float, float]], list[int]]],
+ ]: ...
+
+text_to_path: TextToPath
+
+class TextPath(Path):
+ def __init__(
+ self,
+ xy: tuple[float, float],
+ s: str,
+ size: float | None = ...,
+ prop: FontProperties | None = ...,
+ _interpolation_steps: int = ...,
+ usetex: bool = ...,
+ ) -> None: ...
+ def set_size(self, size: float | None) -> None: ...
+ def get_size(self) -> float | None: ...
+
+ # These are read only... there actually are protections in the base class, so probably can be deleted...
+ @property # type: ignore[misc]
+ def vertices(self) -> np.ndarray: ... # type: ignore[override]
+ @property # type: ignore[misc]
+ def codes(self) -> np.ndarray: ... # type: ignore[override]
diff --git a/lib/python3.12/site-packages/matplotlib/transforms.pyi b/lib/python3.12/site-packages/matplotlib/transforms.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..551487a11c6015ba392d32fa1a86b5c7b61090e5
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/transforms.pyi
@@ -0,0 +1,341 @@
+from .path import Path
+from .patches import Patch
+from .figure import Figure
+import numpy as np
+from numpy.typing import ArrayLike
+from collections.abc import Iterable, Sequence
+from typing import Literal
+
+DEBUG: bool
+
+class TransformNode:
+ INVALID_NON_AFFINE: int
+ INVALID_AFFINE: int
+ INVALID: int
+ is_bbox: bool
+ # Implemented as a standard attr in base class, but functionally readonly and some subclasses implement as such
+ @property
+ def is_affine(self) -> bool: ...
+ pass_through: bool
+ def __init__(self, shorthand_name: str | None = ...) -> None: ...
+ def __copy__(self) -> TransformNode: ...
+ def invalidate(self) -> None: ...
+ def set_children(self, *children: TransformNode) -> None: ...
+ def frozen(self) -> TransformNode: ...
+
+class BboxBase(TransformNode):
+ is_bbox: bool
+ is_affine: bool
+ def frozen(self) -> Bbox: ...
+ def __array__(self, *args, **kwargs): ...
+ @property
+ def x0(self) -> float: ...
+ @property
+ def y0(self) -> float: ...
+ @property
+ def x1(self) -> float: ...
+ @property
+ def y1(self) -> float: ...
+ @property
+ def p0(self) -> tuple[float, float]: ...
+ @property
+ def p1(self) -> tuple[float, float]: ...
+ @property
+ def xmin(self) -> float: ...
+ @property
+ def ymin(self) -> float: ...
+ @property
+ def xmax(self) -> float: ...
+ @property
+ def ymax(self) -> float: ...
+ @property
+ def min(self) -> tuple[float, float]: ...
+ @property
+ def max(self) -> tuple[float, float]: ...
+ @property
+ def intervalx(self) -> tuple[float, float]: ...
+ @property
+ def intervaly(self) -> tuple[float, float]: ...
+ @property
+ def width(self) -> float: ...
+ @property
+ def height(self) -> float: ...
+ @property
+ def size(self) -> tuple[float, float]: ...
+ @property
+ def bounds(self) -> tuple[float, float, float, float]: ...
+ @property
+ def extents(self) -> tuple[float, float, float, float]: ...
+ def get_points(self) -> np.ndarray: ...
+ def containsx(self, x: float) -> bool: ...
+ def containsy(self, y: float) -> bool: ...
+ def contains(self, x: float, y: float) -> bool: ...
+ def overlaps(self, other: BboxBase) -> bool: ...
+ def fully_containsx(self, x: float) -> bool: ...
+ def fully_containsy(self, y: float) -> bool: ...
+ def fully_contains(self, x: float, y: float) -> bool: ...
+ def fully_overlaps(self, other: BboxBase) -> bool: ...
+ def transformed(self, transform: Transform) -> Bbox: ...
+ coefs: dict[str, tuple[float, float]]
+ def anchored(
+ self,
+ c: tuple[float, float] | Literal['C', 'SW', 'S', 'SE', 'E', 'NE', 'N', 'NW', 'W'],
+ container: BboxBase,
+ ) -> Bbox: ...
+ def shrunk(self, mx: float, my: float) -> Bbox: ...
+ def shrunk_to_aspect(
+ self,
+ box_aspect: float,
+ container: BboxBase | None = ...,
+ fig_aspect: float = ...,
+ ) -> Bbox: ...
+ def splitx(self, *args: float) -> list[Bbox]: ...
+ def splity(self, *args: float) -> list[Bbox]: ...
+ def count_contains(self, vertices: ArrayLike) -> int: ...
+ def count_overlaps(self, bboxes: Iterable[BboxBase]) -> int: ...
+ def expanded(self, sw: float, sh: float) -> Bbox: ...
+ def padded(self, w_pad: float, h_pad: float | None = ...) -> Bbox: ...
+ def translated(self, tx: float, ty: float) -> Bbox: ...
+ def corners(self) -> np.ndarray: ...
+ def rotated(self, radians: float) -> Bbox: ...
+ @staticmethod
+ def union(bboxes: Sequence[BboxBase]) -> Bbox: ...
+ @staticmethod
+ def intersection(bbox1: BboxBase, bbox2: BboxBase) -> Bbox | None: ...
+
+class Bbox(BboxBase):
+ def __init__(self, points: ArrayLike, **kwargs) -> None: ...
+ @staticmethod
+ def unit() -> Bbox: ...
+ @staticmethod
+ def null() -> Bbox: ...
+ @staticmethod
+ def from_bounds(x0: float, y0: float, width: float, height: float) -> Bbox: ...
+ @staticmethod
+ def from_extents(*args: float, minpos: float | None = ...) -> Bbox: ...
+ def __format__(self, fmt: str) -> str: ...
+ def ignore(self, value: bool) -> None: ...
+ def update_from_path(
+ self,
+ path: Path,
+ ignore: bool | None = ...,
+ updatex: bool = ...,
+ updatey: bool = ...,
+ ) -> None: ...
+ def update_from_data_x(self, x: ArrayLike, ignore: bool | None = ...) -> None: ...
+ def update_from_data_y(self, y: ArrayLike, ignore: bool | None = ...) -> None: ...
+ def update_from_data_xy(
+ self,
+ xy: ArrayLike,
+ ignore: bool | None = ...,
+ updatex: bool = ...,
+ updatey: bool = ...,
+ ) -> None: ...
+ @property
+ def minpos(self) -> float: ...
+ @property
+ def minposx(self) -> float: ...
+ @property
+ def minposy(self) -> float: ...
+ def get_points(self) -> np.ndarray: ...
+ def set_points(self, points: ArrayLike) -> None: ...
+ def set(self, other: Bbox) -> None: ...
+ def mutated(self) -> bool: ...
+ def mutatedx(self) -> bool: ...
+ def mutatedy(self) -> bool: ...
+
+class TransformedBbox(BboxBase):
+ def __init__(self, bbox: Bbox, transform: Transform, **kwargs) -> None: ...
+ def get_points(self) -> np.ndarray: ...
+
+class LockableBbox(BboxBase):
+ def __init__(
+ self,
+ bbox: BboxBase,
+ x0: float | None = ...,
+ y0: float | None = ...,
+ x1: float | None = ...,
+ y1: float | None = ...,
+ **kwargs
+ ) -> None: ...
+ @property
+ def locked_x0(self) -> float | None: ...
+ @locked_x0.setter
+ def locked_x0(self, x0: float | None) -> None: ...
+ @property
+ def locked_y0(self) -> float | None: ...
+ @locked_y0.setter
+ def locked_y0(self, y0: float | None) -> None: ...
+ @property
+ def locked_x1(self) -> float | None: ...
+ @locked_x1.setter
+ def locked_x1(self, x1: float | None) -> None: ...
+ @property
+ def locked_y1(self) -> float | None: ...
+ @locked_y1.setter
+ def locked_y1(self, y1: float | None) -> None: ...
+
+class Transform(TransformNode):
+
+ # Implemented as a standard attrs in base class, but functionally readonly and some subclasses implement as such
+ @property
+ def input_dims(self) -> int | None: ...
+ @property
+ def output_dims(self) -> int | None: ...
+ @property
+ def is_separable(self) -> bool: ...
+ @property
+ def has_inverse(self) -> bool: ...
+
+ def __add__(self, other: Transform) -> Transform: ...
+ @property
+ def depth(self) -> int: ...
+ def contains_branch(self, other: Transform) -> bool: ...
+ def contains_branch_seperately(
+ self, other_transform: Transform
+ ) -> Sequence[bool]: ...
+ def __sub__(self, other: Transform) -> Transform: ...
+ def __array__(self, *args, **kwargs) -> np.ndarray: ...
+ def transform(self, values: ArrayLike) -> np.ndarray: ...
+ def transform_affine(self, values: ArrayLike) -> np.ndarray: ...
+ def transform_non_affine(self, values: ArrayLike) -> ArrayLike: ...
+ def transform_bbox(self, bbox: BboxBase) -> Bbox: ...
+ def get_affine(self) -> Transform: ...
+ def get_matrix(self) -> np.ndarray: ...
+ def transform_point(self, point: ArrayLike) -> np.ndarray: ...
+ def transform_path(self, path: Path) -> Path: ...
+ def transform_path_affine(self, path: Path) -> Path: ...
+ def transform_path_non_affine(self, path: Path) -> Path: ...
+ def transform_angles(
+ self,
+ angles: ArrayLike,
+ pts: ArrayLike,
+ radians: bool = ...,
+ pushoff: float = ...,
+ ) -> np.ndarray: ...
+ def inverted(self) -> Transform: ...
+
+class TransformWrapper(Transform):
+ pass_through: bool
+ def __init__(self, child: Transform) -> None: ...
+ def __eq__(self, other: object) -> bool: ...
+ def frozen(self) -> Transform: ...
+ def set(self, child: Transform) -> None: ...
+
+class AffineBase(Transform):
+ is_affine: Literal[True]
+ def __init__(self, *args, **kwargs) -> None: ...
+ def __eq__(self, other: object) -> bool: ...
+
+class Affine2DBase(AffineBase):
+ input_dims: Literal[2]
+ output_dims: Literal[2]
+ def frozen(self) -> Affine2D: ...
+ def to_values(self) -> tuple[float, float, float, float, float, float]: ...
+
+class Affine2D(Affine2DBase):
+ def __init__(self, matrix: ArrayLike | None = ..., **kwargs) -> None: ...
+ @staticmethod
+ def from_values(
+ a: float, b: float, c: float, d: float, e: float, f: float
+ ) -> Affine2D: ...
+ def set_matrix(self, mtx: ArrayLike) -> None: ...
+ def clear(self) -> Affine2D: ...
+ def rotate(self, theta: float) -> Affine2D: ...
+ def rotate_deg(self, degrees: float) -> Affine2D: ...
+ def rotate_around(self, x: float, y: float, theta: float) -> Affine2D: ...
+ def rotate_deg_around(self, x: float, y: float, degrees: float) -> Affine2D: ...
+ def translate(self, tx: float, ty: float) -> Affine2D: ...
+ def scale(self, sx: float, sy: float | None = ...) -> Affine2D: ...
+ def skew(self, xShear: float, yShear: float) -> Affine2D: ...
+ def skew_deg(self, xShear: float, yShear: float) -> Affine2D: ...
+
+class IdentityTransform(Affine2DBase): ...
+
+class _BlendedMixin:
+ def __eq__(self, other: object) -> bool: ...
+ def contains_branch_seperately(self, transform: Transform) -> Sequence[bool]: ...
+
+class BlendedGenericTransform(_BlendedMixin, Transform):
+ input_dims: Literal[2]
+ output_dims: Literal[2]
+ pass_through: bool
+ def __init__(
+ self, x_transform: Transform, y_transform: Transform, **kwargs
+ ) -> None: ...
+ @property
+ def depth(self) -> int: ...
+ def contains_branch(self, other: Transform) -> Literal[False]: ...
+ @property
+ def is_affine(self) -> bool: ...
+
+class BlendedAffine2D(_BlendedMixin, Affine2DBase):
+ def __init__(
+ self, x_transform: Transform, y_transform: Transform, **kwargs
+ ) -> None: ...
+
+def blended_transform_factory(
+ x_transform: Transform, y_transform: Transform
+) -> BlendedGenericTransform | BlendedAffine2D: ...
+
+class CompositeGenericTransform(Transform):
+ pass_through: bool
+ def __init__(self, a: Transform, b: Transform, **kwargs) -> None: ...
+
+class CompositeAffine2D(Affine2DBase):
+ def __init__(self, a: Affine2DBase, b: Affine2DBase, **kwargs) -> None: ...
+ @property
+ def depth(self) -> int: ...
+
+def composite_transform_factory(a: Transform, b: Transform) -> Transform: ...
+
+class BboxTransform(Affine2DBase):
+ def __init__(self, boxin: BboxBase, boxout: BboxBase, **kwargs) -> None: ...
+
+class BboxTransformTo(Affine2DBase):
+ def __init__(self, boxout: BboxBase, **kwargs) -> None: ...
+
+class BboxTransformToMaxOnly(BboxTransformTo): ...
+
+class BboxTransformFrom(Affine2DBase):
+ def __init__(self, boxin: BboxBase, **kwargs) -> None: ...
+
+class ScaledTranslation(Affine2DBase):
+ def __init__(
+ self, xt: float, yt: float, scale_trans: Affine2DBase, **kwargs
+ ) -> None: ...
+
+class AffineDeltaTransform(Affine2DBase):
+ def __init__(self, transform: Affine2DBase, **kwargs) -> None: ...
+
+class TransformedPath(TransformNode):
+ def __init__(self, path: Path, transform: Transform) -> None: ...
+ def get_transformed_points_and_affine(self) -> tuple[Path, Transform]: ...
+ def get_transformed_path_and_affine(self) -> tuple[Path, Transform]: ...
+ def get_fully_transformed_path(self) -> Path: ...
+ def get_affine(self) -> Transform: ...
+
+class TransformedPatchPath(TransformedPath):
+ def __init__(self, patch: Patch) -> None: ...
+
+def nonsingular(
+ vmin: float,
+ vmax: float,
+ expander: float = ...,
+ tiny: float = ...,
+ increasing: bool = ...,
+) -> tuple[float, float]: ...
+def interval_contains(interval: tuple[float, float], val: float) -> bool: ...
+def interval_contains_open(interval: tuple[float, float], val: float) -> bool: ...
+def offset_copy(
+ trans: Transform,
+ fig: Figure | None = ...,
+ x: float = ...,
+ y: float = ...,
+ units: Literal["inches", "points", "dots"] = ...,
+) -> Transform: ...
+
+
+class _ScaledRotation(Affine2DBase):
+ def __init__(self, theta: float, trans_shift: Transform) -> None: ...
+ def get_matrix(self) -> np.ndarray: ...
diff --git a/lib/python3.12/site-packages/matplotlib/units.py b/lib/python3.12/site-packages/matplotlib/units.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3480f228bb45cff45ed0566ceabdb1f3dcd53e1
--- /dev/null
+++ b/lib/python3.12/site-packages/matplotlib/units.py
@@ -0,0 +1,195 @@
+"""
+The classes here provide support for using custom classes with
+Matplotlib, e.g., those that do not expose the array interface but know
+how to convert themselves to arrays. It also supports classes with
+units and units conversion. Use cases include converters for custom
+objects, e.g., a list of datetime objects, as well as for objects that
+are unit aware. We don't assume any particular units implementation;
+rather a units implementation must register with the Registry converter
+dictionary and provide a `ConversionInterface`. For example,
+here is a complete implementation which supports plotting with native
+datetime objects::
+
+ import matplotlib.units as units
+ import matplotlib.dates as dates
+ import matplotlib.ticker as ticker
+ import datetime
+
+ class DateConverter(units.ConversionInterface):
+
+ @staticmethod
+ def convert(value, unit, axis):
+ "Convert a datetime value to a scalar or array."
+ return dates.date2num(value)
+
+ @staticmethod
+ def axisinfo(unit, axis):
+ "Return major and minor tick locators and formatters."
+ if unit != 'date':
+ return None
+ majloc = dates.AutoDateLocator()
+ majfmt = dates.AutoDateFormatter(majloc)
+ return units.AxisInfo(majloc=majloc, majfmt=majfmt, label='date')
+
+ @staticmethod
+ def default_units(x, axis):
+ "Return the default unit for x or None."
+ return 'date'
+
+ # Finally we register our object type with the Matplotlib units registry.
+ units.registry[datetime.date] = DateConverter()
+"""
+
+from decimal import Decimal
+from numbers import Number
+
+import numpy as np
+from numpy import ma
+
+from matplotlib import cbook
+
+
+class ConversionError(TypeError):
+ pass
+
+
+def _is_natively_supported(x):
+ """
+ Return whether *x* is of a type that Matplotlib natively supports or an
+ array of objects of such types.
+ """
+ # Matplotlib natively supports all number types except Decimal.
+ if np.iterable(x):
+ # Assume lists are homogeneous as other functions in unit system.
+ for thisx in x:
+ if thisx is ma.masked:
+ continue
+ return isinstance(thisx, Number) and not isinstance(thisx, Decimal)
+ else:
+ return isinstance(x, Number) and not isinstance(x, Decimal)
+
+
+class AxisInfo:
+ """
+ Information to support default axis labeling, tick labeling, and limits.
+
+ An instance of this class must be returned by
+ `ConversionInterface.axisinfo`.
+ """
+ def __init__(self, majloc=None, minloc=None,
+ majfmt=None, minfmt=None, label=None,
+ default_limits=None):
+ """
+ Parameters
+ ----------
+ majloc, minloc : Locator, optional
+ Tick locators for the major and minor ticks.
+ majfmt, minfmt : Formatter, optional
+ Tick formatters for the major and minor ticks.
+ label : str, optional
+ The default axis label.
+ default_limits : optional
+ The default min and max limits of the axis if no data has
+ been plotted.
+
+ Notes
+ -----
+ If any of the above are ``None``, the axis will simply use the
+ default value.
+ """
+ self.majloc = majloc
+ self.minloc = minloc
+ self.majfmt = majfmt
+ self.minfmt = minfmt
+ self.label = label
+ self.default_limits = default_limits
+
+
+class ConversionInterface:
+ """
+ The minimal interface for a converter to take custom data types (or
+ sequences) and convert them to values Matplotlib can use.
+ """
+
+ @staticmethod
+ def axisinfo(unit, axis):
+ """Return an `.AxisInfo` for the axis with the specified units."""
+ return None
+
+ @staticmethod
+ def default_units(x, axis):
+ """Return the default unit for *x* or ``None`` for the given axis."""
+ return None
+
+ @staticmethod
+ def convert(obj, unit, axis):
+ """
+ Convert *obj* using *unit* for the specified *axis*.
+
+ If *obj* is a sequence, return the converted sequence. The output must
+ be a sequence of scalars that can be used by the numpy array layer.
+ """
+ return obj
+
+
+class DecimalConverter(ConversionInterface):
+ """Converter for decimal.Decimal data to float."""
+
+ @staticmethod
+ def convert(value, unit, axis):
+ """
+ Convert Decimals to floats.
+
+ The *unit* and *axis* arguments are not used.
+
+ Parameters
+ ----------
+ value : decimal.Decimal or iterable
+ Decimal or list of Decimal need to be converted
+ """
+ if isinstance(value, Decimal):
+ return float(value)
+ # value is Iterable[Decimal]
+ elif isinstance(value, ma.MaskedArray):
+ return ma.asarray(value, dtype=float)
+ else:
+ return np.asarray(value, dtype=float)
+
+ # axisinfo and default_units can be inherited as Decimals are Numbers.
+
+
+class Registry(dict):
+ """Register types with conversion interface."""
+
+ def get_converter(self, x):
+ """Get the converter interface instance for *x*, or None."""
+ # Unpack in case of e.g. Pandas or xarray object
+ x = cbook._unpack_to_numpy(x)
+
+ if isinstance(x, np.ndarray):
+ # In case x in a masked array, access the underlying data (only its
+ # type matters). If x is a regular ndarray, getdata() just returns
+ # the array itself.
+ x = np.ma.getdata(x).ravel()
+ # If there are no elements in x, infer the units from its dtype
+ if not x.size:
+ return self.get_converter(np.array([0], dtype=x.dtype))
+ for cls in type(x).__mro__: # Look up in the cache.
+ try:
+ return self[cls]
+ except KeyError:
+ pass
+ try: # If cache lookup fails, look up based on first element...
+ first = cbook._safe_first_finite(x)
+ except (TypeError, StopIteration):
+ pass
+ else:
+ # ... and avoid infinite recursion for pathological iterables for
+ # which indexing returns instances of the same iterable class.
+ if type(first) is not type(x):
+ return self.get_converter(first)
+ return None
+
+
+registry = Registry()
+registry[Decimal] = DecimalConverter()