test_path.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  1. import copy
  2. import re
  3. import numpy as np
  4. from numpy.testing import assert_array_equal
  5. import pytest
  6. from matplotlib import patches
  7. from matplotlib.path import Path
  8. from matplotlib.patches import Polygon
  9. from matplotlib.testing.decorators import image_comparison
  10. import matplotlib.pyplot as plt
  11. from matplotlib import transforms
  12. from matplotlib.backend_bases import MouseEvent
  13. def test_empty_closed_path():
  14. path = Path(np.zeros((0, 2)), closed=True)
  15. assert path.vertices.shape == (0, 2)
  16. assert path.codes is None
  17. assert_array_equal(path.get_extents().extents,
  18. transforms.Bbox.null().extents)
  19. def test_readonly_path():
  20. path = Path.unit_circle()
  21. def modify_vertices():
  22. path.vertices = path.vertices * 2.0
  23. with pytest.raises(AttributeError):
  24. modify_vertices()
  25. def test_path_exceptions():
  26. bad_verts1 = np.arange(12).reshape(4, 3)
  27. with pytest.raises(ValueError,
  28. match=re.escape(f'has shape {bad_verts1.shape}')):
  29. Path(bad_verts1)
  30. bad_verts2 = np.arange(12).reshape(2, 3, 2)
  31. with pytest.raises(ValueError,
  32. match=re.escape(f'has shape {bad_verts2.shape}')):
  33. Path(bad_verts2)
  34. good_verts = np.arange(12).reshape(6, 2)
  35. bad_codes = np.arange(2)
  36. msg = re.escape(f"Your vertices have shape {good_verts.shape} "
  37. f"but your codes have shape {bad_codes.shape}")
  38. with pytest.raises(ValueError, match=msg):
  39. Path(good_verts, bad_codes)
  40. def test_point_in_path():
  41. # Test #1787
  42. verts2 = [(0, 0), (0, 1), (1, 1), (1, 0), (0, 0)]
  43. path = Path(verts2, closed=True)
  44. points = [(0.5, 0.5), (1.5, 0.5)]
  45. ret = path.contains_points(points)
  46. assert ret.dtype == 'bool'
  47. np.testing.assert_equal(ret, [True, False])
  48. def test_contains_points_negative_radius():
  49. path = Path.unit_circle()
  50. points = [(0.0, 0.0), (1.25, 0.0), (0.9, 0.9)]
  51. result = path.contains_points(points, radius=-0.5)
  52. np.testing.assert_equal(result, [True, False, False])
  53. _test_paths = [
  54. # interior extrema determine extents and degenerate derivative
  55. Path([[0, 0], [1, 0], [1, 1], [0, 1]],
  56. [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4]),
  57. # a quadratic curve
  58. Path([[0, 0], [0, 1], [1, 0]], [Path.MOVETO, Path.CURVE3, Path.CURVE3]),
  59. # a linear curve, degenerate vertically
  60. Path([[0, 1], [1, 1]], [Path.MOVETO, Path.LINETO]),
  61. # a point
  62. Path([[1, 2]], [Path.MOVETO]),
  63. ]
  64. _test_path_extents = [(0., 0., 0.75, 1.), (0., 0., 1., 0.5), (0., 1., 1., 1.),
  65. (1., 2., 1., 2.)]
  66. @pytest.mark.parametrize('path, extents', zip(_test_paths, _test_path_extents))
  67. def test_exact_extents(path, extents):
  68. # notice that if we just looked at the control points to get the bounding
  69. # box of each curve, we would get the wrong answers. For example, for
  70. # hard_curve = Path([[0, 0], [1, 0], [1, 1], [0, 1]],
  71. # [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4])
  72. # we would get that the extents area (0, 0, 1, 1). This code takes into
  73. # account the curved part of the path, which does not typically extend all
  74. # the way out to the control points.
  75. # Note that counterintuitively, path.get_extents() returns a Bbox, so we
  76. # have to get that Bbox's `.extents`.
  77. assert np.all(path.get_extents().extents == extents)
  78. def test_point_in_path_nan():
  79. box = np.array([[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]])
  80. p = Path(box)
  81. test = np.array([[np.nan, 0.5]])
  82. contains = p.contains_points(test)
  83. assert len(contains) == 1
  84. assert not contains[0]
  85. def test_nonlinear_containment():
  86. fig, ax = plt.subplots()
  87. ax.set(xscale="log", ylim=(0, 1))
  88. polygon = ax.axvspan(1, 10)
  89. assert polygon.get_path().contains_point(
  90. ax.transData.transform((5, .5)), ax.transData)
  91. assert not polygon.get_path().contains_point(
  92. ax.transData.transform((.5, .5)), ax.transData)
  93. assert not polygon.get_path().contains_point(
  94. ax.transData.transform((50, .5)), ax.transData)
  95. @image_comparison(['arrow_contains_point.png'],
  96. remove_text=True, style='mpl20')
  97. def test_arrow_contains_point():
  98. # fix bug (#8384)
  99. fig, ax = plt.subplots()
  100. ax.set_xlim((0, 2))
  101. ax.set_ylim((0, 2))
  102. # create an arrow with Curve style
  103. arrow = patches.FancyArrowPatch((0.5, 0.25), (1.5, 0.75),
  104. arrowstyle='->',
  105. mutation_scale=40)
  106. ax.add_patch(arrow)
  107. # create an arrow with Bracket style
  108. arrow1 = patches.FancyArrowPatch((0.5, 1), (1.5, 1.25),
  109. arrowstyle=']-[',
  110. mutation_scale=40)
  111. ax.add_patch(arrow1)
  112. # create an arrow with other arrow style
  113. arrow2 = patches.FancyArrowPatch((0.5, 1.5), (1.5, 1.75),
  114. arrowstyle='fancy',
  115. fill=False,
  116. mutation_scale=40)
  117. ax.add_patch(arrow2)
  118. patches_list = [arrow, arrow1, arrow2]
  119. # generate some points
  120. X, Y = np.meshgrid(np.arange(0, 2, 0.1),
  121. np.arange(0, 2, 0.1))
  122. for k, (x, y) in enumerate(zip(X.ravel(), Y.ravel())):
  123. xdisp, ydisp = ax.transData.transform([x, y])
  124. event = MouseEvent('button_press_event', fig.canvas, xdisp, ydisp)
  125. for m, patch in enumerate(patches_list):
  126. # set the points to red only if the arrow contains the point
  127. inside, res = patch.contains(event)
  128. if inside:
  129. ax.scatter(x, y, s=5, c="r")
  130. @image_comparison(['path_clipping.svg'], remove_text=True)
  131. def test_path_clipping():
  132. fig = plt.figure(figsize=(6.0, 6.2))
  133. for i, xy in enumerate([
  134. [(200, 200), (200, 350), (400, 350), (400, 200)],
  135. [(200, 200), (200, 350), (400, 350), (400, 100)],
  136. [(200, 100), (200, 350), (400, 350), (400, 100)],
  137. [(200, 100), (200, 415), (400, 350), (400, 100)],
  138. [(200, 100), (200, 415), (400, 415), (400, 100)],
  139. [(200, 415), (400, 415), (400, 100), (200, 100)],
  140. [(400, 415), (400, 100), (200, 100), (200, 415)]]):
  141. ax = fig.add_subplot(4, 2, i+1)
  142. bbox = [0, 140, 640, 260]
  143. ax.set_xlim(bbox[0], bbox[0] + bbox[2])
  144. ax.set_ylim(bbox[1], bbox[1] + bbox[3])
  145. ax.add_patch(Polygon(
  146. xy, facecolor='none', edgecolor='red', closed=True))
  147. @image_comparison(['semi_log_with_zero.png'], style='mpl20')
  148. def test_log_transform_with_zero():
  149. x = np.arange(-10, 10)
  150. y = (1.0 - 1.0/(x**2+1))**20
  151. fig, ax = plt.subplots()
  152. ax.semilogy(x, y, "-o", lw=15, markeredgecolor='k')
  153. ax.set_ylim(1e-7, 1)
  154. ax.grid(True)
  155. def test_make_compound_path_empty():
  156. # We should be able to make a compound path with no arguments.
  157. # This makes it easier to write generic path based code.
  158. r = Path.make_compound_path()
  159. assert r.vertices.shape == (0, 2)
  160. def test_make_compound_path_stops():
  161. zero = [0, 0]
  162. paths = 3*[Path([zero, zero], [Path.MOVETO, Path.STOP])]
  163. compound_path = Path.make_compound_path(*paths)
  164. # the choice to not preserve the terminal STOP is arbitrary, but
  165. # documented, so we test that it is in fact respected here
  166. assert np.sum(compound_path.codes == Path.STOP) == 0
  167. @image_comparison(['xkcd.png'], remove_text=True)
  168. def test_xkcd():
  169. np.random.seed(0)
  170. x = np.linspace(0, 2 * np.pi, 100)
  171. y = np.sin(x)
  172. with plt.xkcd():
  173. fig, ax = plt.subplots()
  174. ax.plot(x, y)
  175. @image_comparison(['xkcd_marker.png'], remove_text=True)
  176. def test_xkcd_marker():
  177. np.random.seed(0)
  178. x = np.linspace(0, 5, 8)
  179. y1 = x
  180. y2 = 5 - x
  181. y3 = 2.5 * np.ones(8)
  182. with plt.xkcd():
  183. fig, ax = plt.subplots()
  184. ax.plot(x, y1, '+', ms=10)
  185. ax.plot(x, y2, 'o', ms=10)
  186. ax.plot(x, y3, '^', ms=10)
  187. @image_comparison(['marker_paths.pdf'], remove_text=True)
  188. def test_marker_paths_pdf():
  189. N = 7
  190. plt.errorbar(np.arange(N),
  191. np.ones(N) + 4,
  192. np.ones(N))
  193. plt.xlim(-1, N)
  194. plt.ylim(-1, 7)
  195. @image_comparison(['nan_path'], style='default', remove_text=True,
  196. extensions=['pdf', 'svg', 'eps', 'png'])
  197. def test_nan_isolated_points():
  198. y0 = [0, np.nan, 2, np.nan, 4, 5, 6]
  199. y1 = [np.nan, 7, np.nan, 9, 10, np.nan, 12]
  200. fig, ax = plt.subplots()
  201. ax.plot(y0, '-o')
  202. ax.plot(y1, '-o')
  203. def test_path_no_doubled_point_in_to_polygon():
  204. hand = np.array(
  205. [[1.64516129, 1.16145833],
  206. [1.64516129, 1.59375],
  207. [1.35080645, 1.921875],
  208. [1.375, 2.18229167],
  209. [1.68548387, 1.9375],
  210. [1.60887097, 2.55208333],
  211. [1.68548387, 2.69791667],
  212. [1.76209677, 2.56770833],
  213. [1.83064516, 1.97395833],
  214. [1.89516129, 2.75],
  215. [1.9516129, 2.84895833],
  216. [2.01209677, 2.76041667],
  217. [1.99193548, 1.99479167],
  218. [2.11290323, 2.63020833],
  219. [2.2016129, 2.734375],
  220. [2.25403226, 2.60416667],
  221. [2.14919355, 1.953125],
  222. [2.30645161, 2.36979167],
  223. [2.39112903, 2.36979167],
  224. [2.41532258, 2.1875],
  225. [2.1733871, 1.703125],
  226. [2.07782258, 1.16666667]])
  227. (r0, c0, r1, c1) = (1.0, 1.5, 2.1, 2.5)
  228. poly = Path(np.vstack((hand[:, 1], hand[:, 0])).T, closed=True)
  229. clip_rect = transforms.Bbox([[r0, c0], [r1, c1]])
  230. poly_clipped = poly.clip_to_bbox(clip_rect).to_polygons()[0]
  231. assert np.all(poly_clipped[-2] != poly_clipped[-1])
  232. assert np.all(poly_clipped[-1] == poly_clipped[0])
  233. def test_path_to_polygons():
  234. data = [[10, 10], [20, 20]]
  235. p = Path(data)
  236. assert_array_equal(p.to_polygons(width=40, height=40), [])
  237. assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),
  238. [data])
  239. assert_array_equal(p.to_polygons(), [])
  240. assert_array_equal(p.to_polygons(closed_only=False), [data])
  241. data = [[10, 10], [20, 20], [30, 30]]
  242. closed_data = [[10, 10], [20, 20], [30, 30], [10, 10]]
  243. p = Path(data)
  244. assert_array_equal(p.to_polygons(width=40, height=40), [closed_data])
  245. assert_array_equal(p.to_polygons(width=40, height=40, closed_only=False),
  246. [data])
  247. assert_array_equal(p.to_polygons(), [closed_data])
  248. assert_array_equal(p.to_polygons(closed_only=False), [data])
  249. def test_path_deepcopy():
  250. # Should not raise any error
  251. verts = [[0, 0], [1, 1]]
  252. codes = [Path.MOVETO, Path.LINETO]
  253. path1 = Path(verts)
  254. path2 = Path(verts, codes)
  255. copy.deepcopy(path1)
  256. copy.deepcopy(path2)
  257. @pytest.mark.parametrize('phi', np.concatenate([
  258. np.array([0, 15, 30, 45, 60, 75, 90, 105, 120, 135]) + delta
  259. for delta in [-1, 0, 1]]))
  260. def test_path_intersect_path(phi):
  261. # test for the range of intersection angles
  262. eps_array = [1e-5, 1e-8, 1e-10, 1e-12]
  263. transform = transforms.Affine2D().rotate(np.deg2rad(phi))
  264. # a and b intersect at angle phi
  265. a = Path([(-2, 0), (2, 0)])
  266. b = transform.transform_path(a)
  267. assert a.intersects_path(b) and b.intersects_path(a)
  268. # a and b touch at angle phi at (0, 0)
  269. a = Path([(0, 0), (2, 0)])
  270. b = transform.transform_path(a)
  271. assert a.intersects_path(b) and b.intersects_path(a)
  272. # a and b are orthogonal and intersect at (0, 3)
  273. a = transform.transform_path(Path([(0, 1), (0, 3)]))
  274. b = transform.transform_path(Path([(1, 3), (0, 3)]))
  275. assert a.intersects_path(b) and b.intersects_path(a)
  276. # a and b are collinear and intersect at (0, 3)
  277. a = transform.transform_path(Path([(0, 1), (0, 3)]))
  278. b = transform.transform_path(Path([(0, 5), (0, 3)]))
  279. assert a.intersects_path(b) and b.intersects_path(a)
  280. # self-intersect
  281. assert a.intersects_path(a)
  282. # a contains b
  283. a = transform.transform_path(Path([(0, 0), (5, 5)]))
  284. b = transform.transform_path(Path([(1, 1), (3, 3)]))
  285. assert a.intersects_path(b) and b.intersects_path(a)
  286. # a and b are collinear but do not intersect
  287. a = transform.transform_path(Path([(0, 1), (0, 5)]))
  288. b = transform.transform_path(Path([(3, 0), (3, 3)]))
  289. assert not a.intersects_path(b) and not b.intersects_path(a)
  290. # a and b are on the same line but do not intersect
  291. a = transform.transform_path(Path([(0, 1), (0, 5)]))
  292. b = transform.transform_path(Path([(0, 6), (0, 7)]))
  293. assert not a.intersects_path(b) and not b.intersects_path(a)
  294. # Note: 1e-13 is the absolute tolerance error used for
  295. # `isclose` function from src/_path.h
  296. # a and b are parallel but do not touch
  297. for eps in eps_array:
  298. a = transform.transform_path(Path([(0, 1), (0, 5)]))
  299. b = transform.transform_path(Path([(0 + eps, 1), (0 + eps, 5)]))
  300. assert not a.intersects_path(b) and not b.intersects_path(a)
  301. # a and b are on the same line but do not intersect (really close)
  302. for eps in eps_array:
  303. a = transform.transform_path(Path([(0, 1), (0, 5)]))
  304. b = transform.transform_path(Path([(0, 5 + eps), (0, 7)]))
  305. assert not a.intersects_path(b) and not b.intersects_path(a)
  306. # a and b are on the same line and intersect (really close)
  307. for eps in eps_array:
  308. a = transform.transform_path(Path([(0, 1), (0, 5)]))
  309. b = transform.transform_path(Path([(0, 5 - eps), (0, 7)]))
  310. assert a.intersects_path(b) and b.intersects_path(a)
  311. # b is the same as a but with an extra point
  312. a = transform.transform_path(Path([(0, 1), (0, 5)]))
  313. b = transform.transform_path(Path([(0, 1), (0, 2), (0, 5)]))
  314. assert a.intersects_path(b) and b.intersects_path(a)
  315. @pytest.mark.parametrize('offset', range(-720, 361, 45))
  316. def test_full_arc(offset):
  317. low = offset
  318. high = 360 + offset
  319. path = Path.arc(low, high)
  320. mins = np.min(path.vertices, axis=0)
  321. maxs = np.max(path.vertices, axis=0)
  322. np.testing.assert_allclose(mins, -1)
  323. np.testing.assert_allclose(maxs, 1)
  324. def test_disjoint_zero_length_segment():
  325. this_path = Path(
  326. np.array([
  327. [824.85064295, 2056.26489203],
  328. [861.69033931, 2041.00539016],
  329. [868.57864109, 2057.63522175],
  330. [831.73894473, 2072.89472361],
  331. [824.85064295, 2056.26489203]]),
  332. np.array([1, 2, 2, 2, 79], dtype=Path.code_type))
  333. outline_path = Path(
  334. np.array([
  335. [859.91051028, 2165.38461538],
  336. [859.06772495, 2149.30331334],
  337. [859.06772495, 2181.46591743],
  338. [859.91051028, 2165.38461538],
  339. [859.91051028, 2165.38461538]]),
  340. np.array([1, 2, 2, 2, 2],
  341. dtype=Path.code_type))
  342. assert not outline_path.intersects_path(this_path)
  343. assert not this_path.intersects_path(outline_path)
  344. def test_intersect_zero_length_segment():
  345. this_path = Path(
  346. np.array([
  347. [0, 0],
  348. [1, 1],
  349. ]))
  350. outline_path = Path(
  351. np.array([
  352. [1, 0],
  353. [.5, .5],
  354. [.5, .5],
  355. [0, 1],
  356. ]))
  357. assert outline_path.intersects_path(this_path)
  358. assert this_path.intersects_path(outline_path)
  359. def test_cleanup_closepoly():
  360. # if the first connected component of a Path ends in a CLOSEPOLY, but that
  361. # component contains a NaN, then Path.cleaned should ignore not just the
  362. # control points but also the CLOSEPOLY, since it has nowhere valid to
  363. # point.
  364. paths = [
  365. Path([[np.nan, np.nan], [np.nan, np.nan]],
  366. [Path.MOVETO, Path.CLOSEPOLY]),
  367. # we trigger a different path in the C++ code if we don't pass any
  368. # codes explicitly, so we must also make sure that this works
  369. Path([[np.nan, np.nan], [np.nan, np.nan]]),
  370. # we should also make sure that this cleanup works if there's some
  371. # multi-vertex curves
  372. Path([[np.nan, np.nan], [np.nan, np.nan], [np.nan, np.nan],
  373. [np.nan, np.nan]],
  374. [Path.MOVETO, Path.CURVE3, Path.CURVE3, Path.CLOSEPOLY])
  375. ]
  376. for p in paths:
  377. cleaned = p.cleaned(remove_nans=True)
  378. assert len(cleaned) == 1
  379. assert cleaned.codes[0] == Path.STOP