test_transforms.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  1. import numpy as np
  2. from numpy.testing import (assert_allclose, assert_almost_equal,
  3. assert_array_equal, assert_array_almost_equal)
  4. import pytest
  5. import matplotlib.pyplot as plt
  6. import matplotlib.patches as mpatches
  7. import matplotlib.transforms as mtransforms
  8. from matplotlib.path import Path
  9. from matplotlib.scale import LogScale
  10. from matplotlib.testing.decorators import image_comparison
  11. def test_non_affine_caching():
  12. class AssertingNonAffineTransform(mtransforms.Transform):
  13. """
  14. This transform raises an assertion error when called when it
  15. shouldn't be and self.raise_on_transform is True.
  16. """
  17. input_dims = output_dims = 2
  18. is_affine = False
  19. def __init__(self, *args, **kwargs):
  20. mtransforms.Transform.__init__(self, *args, **kwargs)
  21. self.raise_on_transform = False
  22. self.underlying_transform = mtransforms.Affine2D().scale(10, 10)
  23. def transform_path_non_affine(self, path):
  24. assert not self.raise_on_transform, \
  25. 'Invalidated affine part of transform unnecessarily.'
  26. return self.underlying_transform.transform_path(path)
  27. transform_path = transform_path_non_affine
  28. def transform_non_affine(self, path):
  29. assert not self.raise_on_transform, \
  30. 'Invalidated affine part of transform unnecessarily.'
  31. return self.underlying_transform.transform(path)
  32. transform = transform_non_affine
  33. my_trans = AssertingNonAffineTransform()
  34. ax = plt.axes()
  35. plt.plot(np.arange(10), transform=my_trans + ax.transData)
  36. plt.draw()
  37. # enable the transform to raise an exception if it's non-affine transform
  38. # method is triggered again.
  39. my_trans.raise_on_transform = True
  40. ax.transAxes.invalidate()
  41. plt.draw()
  42. def test_external_transform_api():
  43. class ScaledBy:
  44. def __init__(self, scale_factor):
  45. self._scale_factor = scale_factor
  46. def _as_mpl_transform(self, axes):
  47. return (mtransforms.Affine2D().scale(self._scale_factor)
  48. + axes.transData)
  49. ax = plt.axes()
  50. line, = plt.plot(np.arange(10), transform=ScaledBy(10))
  51. ax.set_xlim(0, 100)
  52. ax.set_ylim(0, 100)
  53. # assert that the top transform of the line is the scale transform.
  54. assert_allclose(line.get_transform()._a.get_matrix(),
  55. mtransforms.Affine2D().scale(10).get_matrix())
  56. @image_comparison(['pre_transform_data'],
  57. tol=0.08, remove_text=True, style='mpl20')
  58. def test_pre_transform_plotting():
  59. # a catch-all for as many as possible plot layouts which handle
  60. # pre-transforming the data NOTE: The axis range is important in this
  61. # plot. It should be x10 what the data suggests it should be
  62. ax = plt.axes()
  63. times10 = mtransforms.Affine2D().scale(10)
  64. ax.contourf(np.arange(48).reshape(6, 8), transform=times10 + ax.transData)
  65. ax.pcolormesh(np.linspace(0, 4, 7),
  66. np.linspace(5.5, 8, 9),
  67. np.arange(48).reshape(8, 6),
  68. transform=times10 + ax.transData)
  69. ax.scatter(np.linspace(0, 10), np.linspace(10, 0),
  70. transform=times10 + ax.transData)
  71. x = np.linspace(8, 10, 20)
  72. y = np.linspace(1, 5, 20)
  73. u = 2*np.sin(x) + np.cos(y[:, np.newaxis])
  74. v = np.sin(x) - np.cos(y[:, np.newaxis])
  75. df = 25. / 30. # Compatibility factor for old test image
  76. ax.streamplot(x, y, u, v, transform=times10 + ax.transData,
  77. density=(df, df), linewidth=u**2 + v**2)
  78. # reduce the vector data down a bit for barb and quiver plotting
  79. x, y = x[::3], y[::3]
  80. u, v = u[::3, ::3], v[::3, ::3]
  81. ax.quiver(x, y + 5, u, v, transform=times10 + ax.transData)
  82. ax.barbs(x - 3, y + 5, u**2, v**2, transform=times10 + ax.transData)
  83. def test_contour_pre_transform_limits():
  84. ax = plt.axes()
  85. xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))
  86. ax.contourf(xs, ys, np.log(xs * ys),
  87. transform=mtransforms.Affine2D().scale(0.1) + ax.transData)
  88. expected = np.array([[1.5, 1.24],
  89. [2., 1.25]])
  90. assert_almost_equal(expected, ax.dataLim.get_points())
  91. def test_pcolor_pre_transform_limits():
  92. # Based on test_contour_pre_transform_limits()
  93. ax = plt.axes()
  94. xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))
  95. ax.pcolor(xs, ys, np.log(xs * ys),
  96. transform=mtransforms.Affine2D().scale(0.1) + ax.transData)
  97. expected = np.array([[1.5, 1.24],
  98. [2., 1.25]])
  99. assert_almost_equal(expected, ax.dataLim.get_points())
  100. def test_pcolormesh_pre_transform_limits():
  101. # Based on test_contour_pre_transform_limits()
  102. ax = plt.axes()
  103. xs, ys = np.meshgrid(np.linspace(15, 20, 15), np.linspace(12.4, 12.5, 20))
  104. ax.pcolormesh(xs, ys, np.log(xs * ys),
  105. transform=mtransforms.Affine2D().scale(0.1) + ax.transData)
  106. expected = np.array([[1.5, 1.24],
  107. [2., 1.25]])
  108. assert_almost_equal(expected, ax.dataLim.get_points())
  109. def test_Affine2D_from_values():
  110. points = np.array([[0, 0],
  111. [10, 20],
  112. [-1, 0],
  113. ])
  114. t = mtransforms.Affine2D.from_values(1, 0, 0, 0, 0, 0)
  115. actual = t.transform(points)
  116. expected = np.array([[0, 0], [10, 0], [-1, 0]])
  117. assert_almost_equal(actual, expected)
  118. t = mtransforms.Affine2D.from_values(0, 2, 0, 0, 0, 0)
  119. actual = t.transform(points)
  120. expected = np.array([[0, 0], [0, 20], [0, -2]])
  121. assert_almost_equal(actual, expected)
  122. t = mtransforms.Affine2D.from_values(0, 0, 3, 0, 0, 0)
  123. actual = t.transform(points)
  124. expected = np.array([[0, 0], [60, 0], [0, 0]])
  125. assert_almost_equal(actual, expected)
  126. t = mtransforms.Affine2D.from_values(0, 0, 0, 4, 0, 0)
  127. actual = t.transform(points)
  128. expected = np.array([[0, 0], [0, 80], [0, 0]])
  129. assert_almost_equal(actual, expected)
  130. t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 5, 0)
  131. actual = t.transform(points)
  132. expected = np.array([[5, 0], [5, 0], [5, 0]])
  133. assert_almost_equal(actual, expected)
  134. t = mtransforms.Affine2D.from_values(0, 0, 0, 0, 0, 6)
  135. actual = t.transform(points)
  136. expected = np.array([[0, 6], [0, 6], [0, 6]])
  137. assert_almost_equal(actual, expected)
  138. def test_affine_inverted_invalidated():
  139. # Ensure that the an affine transform is not declared valid on access
  140. point = [1.0, 1.0]
  141. t = mtransforms.Affine2D()
  142. assert_almost_equal(point, t.transform(t.inverted().transform(point)))
  143. # Change and access the transform
  144. t.translate(1.0, 1.0).get_matrix()
  145. assert_almost_equal(point, t.transform(t.inverted().transform(point)))
  146. def test_clipping_of_log():
  147. # issue 804
  148. M, L, C = Path.MOVETO, Path.LINETO, Path.CLOSEPOLY
  149. points = [(0.2, -99), (0.4, -99), (0.4, 20), (0.2, 20), (0.2, -99)]
  150. codes = [M, L, L, L, C]
  151. path = Path(points, codes)
  152. # something like this happens in plotting logarithmic histograms
  153. trans = mtransforms.BlendedGenericTransform(
  154. mtransforms.Affine2D(), LogScale.LogTransform(10, 'clip'))
  155. tpath = trans.transform_path_non_affine(path)
  156. result = tpath.iter_segments(trans.get_affine(),
  157. clip=(0, 0, 100, 100),
  158. simplify=False)
  159. tpoints, tcodes = zip(*result)
  160. assert_allclose(tcodes, [M, L, L, L, C])
  161. class NonAffineForTest(mtransforms.Transform):
  162. """
  163. A class which looks like a non affine transform, but does whatever
  164. the given transform does (even if it is affine). This is very useful
  165. for testing NonAffine behaviour with a simple Affine transform.
  166. """
  167. is_affine = False
  168. output_dims = 2
  169. input_dims = 2
  170. def __init__(self, real_trans, *args, **kwargs):
  171. self.real_trans = real_trans
  172. mtransforms.Transform.__init__(self, *args, **kwargs)
  173. def transform_non_affine(self, values):
  174. return self.real_trans.transform(values)
  175. def transform_path_non_affine(self, path):
  176. return self.real_trans.transform_path(path)
  177. class TestBasicTransform:
  178. def setup_method(self):
  179. self.ta1 = mtransforms.Affine2D(shorthand_name='ta1').rotate(np.pi / 2)
  180. self.ta2 = mtransforms.Affine2D(shorthand_name='ta2').translate(10, 0)
  181. self.ta3 = mtransforms.Affine2D(shorthand_name='ta3').scale(1, 2)
  182. self.tn1 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),
  183. shorthand_name='tn1')
  184. self.tn2 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),
  185. shorthand_name='tn2')
  186. self.tn3 = NonAffineForTest(mtransforms.Affine2D().translate(1, 2),
  187. shorthand_name='tn3')
  188. # creates a transform stack which looks like ((A, (N, A)), A)
  189. self.stack1 = (self.ta1 + (self.tn1 + self.ta2)) + self.ta3
  190. # creates a transform stack which looks like (((A, N), A), A)
  191. self.stack2 = self.ta1 + self.tn1 + self.ta2 + self.ta3
  192. # creates a transform stack which is a subset of stack2
  193. self.stack2_subset = self.tn1 + self.ta2 + self.ta3
  194. # when in debug, the transform stacks can produce dot images:
  195. # self.stack1.write_graphviz(file('stack1.dot', 'w'))
  196. # self.stack2.write_graphviz(file('stack2.dot', 'w'))
  197. # self.stack2_subset.write_graphviz(file('stack2_subset.dot', 'w'))
  198. def test_transform_depth(self):
  199. assert self.stack1.depth == 4
  200. assert self.stack2.depth == 4
  201. assert self.stack2_subset.depth == 3
  202. def test_left_to_right_iteration(self):
  203. stack3 = (self.ta1 + (self.tn1 + (self.ta2 + self.tn2))) + self.ta3
  204. # stack3.write_graphviz(file('stack3.dot', 'w'))
  205. target_transforms = [stack3,
  206. (self.tn1 + (self.ta2 + self.tn2)) + self.ta3,
  207. (self.ta2 + self.tn2) + self.ta3,
  208. self.tn2 + self.ta3,
  209. self.ta3,
  210. ]
  211. r = [rh for _, rh in stack3._iter_break_from_left_to_right()]
  212. assert len(r) == len(target_transforms)
  213. for target_stack, stack in zip(target_transforms, r):
  214. assert target_stack == stack
  215. def test_transform_shortcuts(self):
  216. assert self.stack1 - self.stack2_subset == self.ta1
  217. assert self.stack2 - self.stack2_subset == self.ta1
  218. assert self.stack2_subset - self.stack2 == self.ta1.inverted()
  219. assert (self.stack2_subset - self.stack2).depth == 1
  220. with pytest.raises(ValueError):
  221. self.stack1 - self.stack2
  222. aff1 = self.ta1 + (self.ta2 + self.ta3)
  223. aff2 = self.ta2 + self.ta3
  224. assert aff1 - aff2 == self.ta1
  225. assert aff1 - self.ta2 == aff1 + self.ta2.inverted()
  226. assert self.stack1 - self.ta3 == self.ta1 + (self.tn1 + self.ta2)
  227. assert self.stack2 - self.ta3 == self.ta1 + self.tn1 + self.ta2
  228. assert ((self.ta2 + self.ta3) - self.ta3 + self.ta3 ==
  229. self.ta2 + self.ta3)
  230. def test_contains_branch(self):
  231. r1 = (self.ta2 + self.ta1)
  232. r2 = (self.ta2 + self.ta1)
  233. assert r1 == r2
  234. assert r1 != self.ta1
  235. assert r1.contains_branch(r2)
  236. assert r1.contains_branch(self.ta1)
  237. assert not r1.contains_branch(self.ta2)
  238. assert not r1.contains_branch(self.ta2 + self.ta2)
  239. assert r1 == r2
  240. assert self.stack1.contains_branch(self.ta3)
  241. assert self.stack2.contains_branch(self.ta3)
  242. assert self.stack1.contains_branch(self.stack2_subset)
  243. assert self.stack2.contains_branch(self.stack2_subset)
  244. assert not self.stack2_subset.contains_branch(self.stack1)
  245. assert not self.stack2_subset.contains_branch(self.stack2)
  246. assert self.stack1.contains_branch(self.ta2 + self.ta3)
  247. assert self.stack2.contains_branch(self.ta2 + self.ta3)
  248. assert not self.stack1.contains_branch(self.tn1 + self.ta2)
  249. def test_affine_simplification(self):
  250. # tests that a transform stack only calls as much is absolutely
  251. # necessary "non-affine" allowing the best possible optimization with
  252. # complex transformation stacks.
  253. points = np.array([[0, 0], [10, 20], [np.nan, 1], [-1, 0]],
  254. dtype=np.float64)
  255. na_pts = self.stack1.transform_non_affine(points)
  256. all_pts = self.stack1.transform(points)
  257. na_expected = np.array([[1., 2.], [-19., 12.],
  258. [np.nan, np.nan], [1., 1.]], dtype=np.float64)
  259. all_expected = np.array([[11., 4.], [-9., 24.],
  260. [np.nan, np.nan], [11., 2.]],
  261. dtype=np.float64)
  262. # check we have the expected results from doing the affine part only
  263. assert_array_almost_equal(na_pts, na_expected)
  264. # check we have the expected results from a full transformation
  265. assert_array_almost_equal(all_pts, all_expected)
  266. # check we have the expected results from doing the transformation in
  267. # two steps
  268. assert_array_almost_equal(self.stack1.transform_affine(na_pts),
  269. all_expected)
  270. # check that getting the affine transformation first, then fully
  271. # transforming using that yields the same result as before.
  272. assert_array_almost_equal(self.stack1.get_affine().transform(na_pts),
  273. all_expected)
  274. # check that the affine part of stack1 & stack2 are equivalent
  275. # (i.e. the optimization is working)
  276. expected_result = (self.ta2 + self.ta3).get_matrix()
  277. result = self.stack1.get_affine().get_matrix()
  278. assert_array_equal(expected_result, result)
  279. result = self.stack2.get_affine().get_matrix()
  280. assert_array_equal(expected_result, result)
  281. class TestTransformPlotInterface:
  282. def test_line_extent_axes_coords(self):
  283. # a simple line in axes coordinates
  284. ax = plt.axes()
  285. ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transAxes)
  286. assert_array_equal(ax.dataLim.get_points(),
  287. np.array([[np.inf, np.inf],
  288. [-np.inf, -np.inf]]))
  289. def test_line_extent_data_coords(self):
  290. # a simple line in data coordinates
  291. ax = plt.axes()
  292. ax.plot([0.1, 1.2, 0.8], [0.9, 0.5, 0.8], transform=ax.transData)
  293. assert_array_equal(ax.dataLim.get_points(),
  294. np.array([[0.1, 0.5], [1.2, 0.9]]))
  295. def test_line_extent_compound_coords1(self):
  296. # a simple line in data coordinates in the y component, and in axes
  297. # coordinates in the x
  298. ax = plt.axes()
  299. trans = mtransforms.blended_transform_factory(ax.transAxes,
  300. ax.transData)
  301. ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)
  302. assert_array_equal(ax.dataLim.get_points(),
  303. np.array([[np.inf, -5.],
  304. [-np.inf, 35.]]))
  305. def test_line_extent_predata_transform_coords(self):
  306. # a simple line in (offset + data) coordinates
  307. ax = plt.axes()
  308. trans = mtransforms.Affine2D().scale(10) + ax.transData
  309. ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)
  310. assert_array_equal(ax.dataLim.get_points(),
  311. np.array([[1., -50.], [12., 350.]]))
  312. def test_line_extent_compound_coords2(self):
  313. # a simple line in (offset + data) coordinates in the y component, and
  314. # in axes coordinates in the x
  315. ax = plt.axes()
  316. trans = mtransforms.blended_transform_factory(ax.transAxes,
  317. mtransforms.Affine2D().scale(10) + ax.transData)
  318. ax.plot([0.1, 1.2, 0.8], [35, -5, 18], transform=trans)
  319. assert_array_equal(ax.dataLim.get_points(),
  320. np.array([[np.inf, -50.], [-np.inf, 350.]]))
  321. def test_line_extents_affine(self):
  322. ax = plt.axes()
  323. offset = mtransforms.Affine2D().translate(10, 10)
  324. plt.plot(np.arange(10), transform=offset + ax.transData)
  325. expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 10
  326. assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
  327. def test_line_extents_non_affine(self):
  328. ax = plt.axes()
  329. offset = mtransforms.Affine2D().translate(10, 10)
  330. na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
  331. plt.plot(np.arange(10), transform=offset + na_offset + ax.transData)
  332. expected_data_lim = np.array([[0., 0.], [9., 9.]]) + 20
  333. assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
  334. def test_pathc_extents_non_affine(self):
  335. ax = plt.axes()
  336. offset = mtransforms.Affine2D().translate(10, 10)
  337. na_offset = NonAffineForTest(mtransforms.Affine2D().translate(10, 10))
  338. pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
  339. patch = mpatches.PathPatch(pth,
  340. transform=offset + na_offset + ax.transData)
  341. ax.add_patch(patch)
  342. expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 20
  343. assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
  344. def test_pathc_extents_affine(self):
  345. ax = plt.axes()
  346. offset = mtransforms.Affine2D().translate(10, 10)
  347. pth = Path(np.array([[0, 0], [0, 10], [10, 10], [10, 0]]))
  348. patch = mpatches.PathPatch(pth, transform=offset + ax.transData)
  349. ax.add_patch(patch)
  350. expected_data_lim = np.array([[0., 0.], [10., 10.]]) + 10
  351. assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
  352. def test_line_extents_for_non_affine_transData(self):
  353. ax = plt.axes(projection='polar')
  354. # add 10 to the radius of the data
  355. offset = mtransforms.Affine2D().translate(0, 10)
  356. plt.plot(np.arange(10), transform=offset + ax.transData)
  357. # the data lim of a polar plot is stored in coordinates
  358. # before a transData transformation, hence the data limits
  359. # are not what is being shown on the actual plot.
  360. expected_data_lim = np.array([[0., 0.], [9., 9.]]) + [0, 10]
  361. assert_array_almost_equal(ax.dataLim.get_points(), expected_data_lim)
  362. def assert_bbox_eq(bbox1, bbox2):
  363. assert_array_equal(bbox1.bounds, bbox2.bounds)
  364. def test_bbox_intersection():
  365. bbox_from_ext = mtransforms.Bbox.from_extents
  366. inter = mtransforms.Bbox.intersection
  367. r1 = bbox_from_ext(0, 0, 1, 1)
  368. r2 = bbox_from_ext(0.5, 0.5, 1.5, 1.5)
  369. r3 = bbox_from_ext(0.5, 0, 0.75, 0.75)
  370. r4 = bbox_from_ext(0.5, 1.5, 1, 2.5)
  371. r5 = bbox_from_ext(1, 1, 2, 2)
  372. # self intersection -> no change
  373. assert_bbox_eq(inter(r1, r1), r1)
  374. # simple intersection
  375. assert_bbox_eq(inter(r1, r2), bbox_from_ext(0.5, 0.5, 1, 1))
  376. # r3 contains r2
  377. assert_bbox_eq(inter(r1, r3), r3)
  378. # no intersection
  379. assert inter(r1, r4) is None
  380. # single point
  381. assert_bbox_eq(inter(r1, r5), bbox_from_ext(1, 1, 1, 1))
  382. def test_bbox_as_strings():
  383. b = mtransforms.Bbox([[.5, 0], [.75, .75]])
  384. assert_bbox_eq(b, eval(repr(b), {'Bbox': mtransforms.Bbox}))
  385. asdict = eval(str(b), {'Bbox': dict})
  386. for k, v in asdict.items():
  387. assert getattr(b, k) == v
  388. fmt = '.1f'
  389. asdict = eval(format(b, fmt), {'Bbox': dict})
  390. for k, v in asdict.items():
  391. assert eval(format(getattr(b, k), fmt)) == v
  392. def test_transform_single_point():
  393. t = mtransforms.Affine2D()
  394. r = t.transform_affine((1, 1))
  395. assert r.shape == (2,)
  396. def test_log_transform():
  397. # Tests that the last line runs without exception (previously the
  398. # transform would fail if one of the axes was logarithmic).
  399. fig, ax = plt.subplots()
  400. ax.set_yscale('log')
  401. ax.transData.transform((1, 1))
  402. def test_nan_overlap():
  403. a = mtransforms.Bbox([[0, 0], [1, 1]])
  404. b = mtransforms.Bbox([[0, 0], [1, np.nan]])
  405. assert not a.overlaps(b)
  406. def test_transform_angles():
  407. t = mtransforms.Affine2D() # Identity transform
  408. angles = np.array([20, 45, 60])
  409. points = np.array([[0, 0], [1, 1], [2, 2]])
  410. # Identity transform does not change angles
  411. new_angles = t.transform_angles(angles, points)
  412. assert_array_almost_equal(angles, new_angles)
  413. # points missing a 2nd dimension
  414. with pytest.raises(ValueError):
  415. t.transform_angles(angles, points[0:2, 0:1])
  416. # Number of angles != Number of points
  417. with pytest.raises(ValueError):
  418. t.transform_angles(angles, points[0:2, :])
  419. def test_nonsingular():
  420. # test for zero-expansion type cases; other cases may be added later
  421. zero_expansion = np.array([-0.001, 0.001])
  422. cases = [(0, np.nan), (0, 0), (0, 7.9e-317)]
  423. for args in cases:
  424. out = np.array(mtransforms.nonsingular(*args))
  425. assert_array_equal(out, zero_expansion)
  426. def test_invalid_arguments():
  427. t = mtransforms.Affine2D()
  428. # There are two different exceptions, since the wrong number of
  429. # dimensions is caught when constructing an array_view, and that
  430. # raises a ValueError, and a wrong shape with a possible number
  431. # of dimensions is caught by our CALL_CPP macro, which always
  432. # raises the less precise RuntimeError.
  433. with pytest.raises(ValueError):
  434. t.transform(1)
  435. with pytest.raises(ValueError):
  436. t.transform([[[1]]])
  437. with pytest.raises(RuntimeError):
  438. t.transform([])
  439. with pytest.raises(RuntimeError):
  440. t.transform([1])
  441. with pytest.raises(RuntimeError):
  442. t.transform([[1]])
  443. with pytest.raises(RuntimeError):
  444. t.transform([[1, 2, 3]])
  445. def test_transformed_path():
  446. points = [(0, 0), (1, 0), (1, 1), (0, 1)]
  447. codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY]
  448. path = Path(points, codes)
  449. trans = mtransforms.Affine2D()
  450. trans_path = mtransforms.TransformedPath(path, trans)
  451. assert_allclose(trans_path.get_fully_transformed_path().vertices, points)
  452. # Changing the transform should change the result.
  453. r2 = 1 / np.sqrt(2)
  454. trans.rotate(np.pi / 4)
  455. assert_allclose(trans_path.get_fully_transformed_path().vertices,
  456. [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],
  457. atol=1e-15)
  458. # Changing the path does not change the result (it's cached).
  459. path.points = [(0, 0)] * 4
  460. assert_allclose(trans_path.get_fully_transformed_path().vertices,
  461. [(0, 0), (r2, r2), (0, 2 * r2), (-r2, r2)],
  462. atol=1e-15)
  463. def test_transformed_patch_path():
  464. trans = mtransforms.Affine2D()
  465. patch = mpatches.Wedge((0, 0), 1, 45, 135, transform=trans)
  466. tpatch = mtransforms.TransformedPatchPath(patch)
  467. points = tpatch.get_fully_transformed_path().vertices
  468. # Changing the transform should change the result.
  469. trans.scale(2)
  470. assert_allclose(tpatch.get_fully_transformed_path().vertices, points * 2)
  471. # Changing the path should change the result (and cancel out the scaling
  472. # from the transform).
  473. patch.set_radius(0.5)
  474. assert_allclose(tpatch.get_fully_transformed_path().vertices, points)
  475. @pytest.mark.parametrize('locked_element', ['x0', 'y0', 'x1', 'y1'])
  476. def test_lockable_bbox(locked_element):
  477. other_elements = ['x0', 'y0', 'x1', 'y1']
  478. other_elements.remove(locked_element)
  479. orig = mtransforms.Bbox.unit()
  480. locked = mtransforms.LockableBbox(orig, **{locked_element: 2})
  481. # LockableBbox should keep its locked element as specified in __init__.
  482. assert getattr(locked, locked_element) == 2
  483. assert getattr(locked, 'locked_' + locked_element) == 2
  484. for elem in other_elements:
  485. assert getattr(locked, elem) == getattr(orig, elem)
  486. # Changing underlying Bbox should update everything but locked element.
  487. orig.set_points(orig.get_points() + 10)
  488. assert getattr(locked, locked_element) == 2
  489. assert getattr(locked, 'locked_' + locked_element) == 2
  490. for elem in other_elements:
  491. assert getattr(locked, elem) == getattr(orig, elem)
  492. # Unlocking element should revert values back to the underlying Bbox.
  493. setattr(locked, 'locked_' + locked_element, None)
  494. assert getattr(locked, 'locked_' + locked_element) is None
  495. assert np.all(orig.get_points() == locked.get_points())
  496. # Relocking an element should change its value, but not others.
  497. setattr(locked, 'locked_' + locked_element, 3)
  498. assert getattr(locked, locked_element) == 3
  499. assert getattr(locked, 'locked_' + locked_element) == 3
  500. for elem in other_elements:
  501. assert getattr(locked, elem) == getattr(orig, elem)