test_path.py 19 KB

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