test_triangulation.py 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403
  1. import numpy as np
  2. from numpy.testing import (
  3. assert_array_equal, assert_array_almost_equal, assert_array_less)
  4. import numpy.ma.testutils as matest
  5. import pytest
  6. import matplotlib as mpl
  7. import matplotlib.pyplot as plt
  8. import matplotlib.tri as mtri
  9. from matplotlib.path import Path
  10. from matplotlib.testing.decorators import image_comparison, check_figures_equal
  11. class TestTriangulationParams:
  12. x = [-1, 0, 1, 0]
  13. y = [0, -1, 0, 1]
  14. triangles = [[0, 1, 2], [0, 2, 3]]
  15. mask = [False, True]
  16. @pytest.mark.parametrize('args, kwargs, expected', [
  17. ([x, y], {}, [x, y, None, None]),
  18. ([x, y, triangles], {}, [x, y, triangles, None]),
  19. ([x, y], dict(triangles=triangles), [x, y, triangles, None]),
  20. ([x, y], dict(mask=mask), [x, y, None, mask]),
  21. ([x, y, triangles], dict(mask=mask), [x, y, triangles, mask]),
  22. ([x, y], dict(triangles=triangles, mask=mask), [x, y, triangles, mask])
  23. ])
  24. def test_extract_triangulation_params(self, args, kwargs, expected):
  25. other_args = [1, 2]
  26. other_kwargs = {'a': 3, 'b': '4'}
  27. x_, y_, triangles_, mask_, args_, kwargs_ = \
  28. mtri.Triangulation._extract_triangulation_params(
  29. args + other_args, {**kwargs, **other_kwargs})
  30. x, y, triangles, mask = expected
  31. assert x_ is x
  32. assert y_ is y
  33. assert_array_equal(triangles_, triangles)
  34. assert mask_ is mask
  35. assert args_ == other_args
  36. assert kwargs_ == other_kwargs
  37. def test_extract_triangulation_positional_mask():
  38. # mask cannot be passed positionally
  39. mask = [True]
  40. args = [[0, 2, 1], [0, 0, 1], [[0, 1, 2]], mask]
  41. x_, y_, triangles_, mask_, args_, kwargs_ = \
  42. mtri.Triangulation._extract_triangulation_params(args, {})
  43. assert mask_ is None
  44. assert args_ == [mask]
  45. # the positional mask must be caught downstream because this must pass
  46. # unknown args through
  47. def test_triangulation_init():
  48. x = [-1, 0, 1, 0]
  49. y = [0, -1, 0, 1]
  50. with pytest.raises(ValueError, match="x and y must be equal-length"):
  51. mtri.Triangulation(x, [1, 2])
  52. with pytest.raises(
  53. ValueError,
  54. match=r"triangles must be a \(N, 3\) int array, but found shape "
  55. r"\(3,\)"):
  56. mtri.Triangulation(x, y, [0, 1, 2])
  57. with pytest.raises(
  58. ValueError,
  59. match=r"triangles must be a \(N, 3\) int array, not 'other'"):
  60. mtri.Triangulation(x, y, 'other')
  61. with pytest.raises(ValueError, match="found value 99"):
  62. mtri.Triangulation(x, y, [[0, 1, 99]])
  63. with pytest.raises(ValueError, match="found value -1"):
  64. mtri.Triangulation(x, y, [[0, 1, -1]])
  65. def test_triangulation_set_mask():
  66. x = [-1, 0, 1, 0]
  67. y = [0, -1, 0, 1]
  68. triangles = [[0, 1, 2], [2, 3, 0]]
  69. triang = mtri.Triangulation(x, y, triangles)
  70. # Check neighbors, which forces creation of C++ triangulation
  71. assert_array_equal(triang.neighbors, [[-1, -1, 1], [-1, -1, 0]])
  72. # Set mask
  73. triang.set_mask([False, True])
  74. assert_array_equal(triang.mask, [False, True])
  75. # Reset mask
  76. triang.set_mask(None)
  77. assert triang.mask is None
  78. msg = r"mask array must have same length as triangles array"
  79. for mask in ([False, True, False], [False], [True], False, True):
  80. with pytest.raises(ValueError, match=msg):
  81. triang.set_mask(mask)
  82. def test_delaunay():
  83. # No duplicate points, regular grid.
  84. nx = 5
  85. ny = 4
  86. x, y = np.meshgrid(np.linspace(0.0, 1.0, nx), np.linspace(0.0, 1.0, ny))
  87. x = x.ravel()
  88. y = y.ravel()
  89. npoints = nx*ny
  90. ntriangles = 2 * (nx-1) * (ny-1)
  91. nedges = 3*nx*ny - 2*nx - 2*ny + 1
  92. # Create delaunay triangulation.
  93. triang = mtri.Triangulation(x, y)
  94. # The tests in the remainder of this function should be passed by any
  95. # triangulation that does not contain duplicate points.
  96. # Points - floating point.
  97. assert_array_almost_equal(triang.x, x)
  98. assert_array_almost_equal(triang.y, y)
  99. # Triangles - integers.
  100. assert len(triang.triangles) == ntriangles
  101. assert np.min(triang.triangles) == 0
  102. assert np.max(triang.triangles) == npoints-1
  103. # Edges - integers.
  104. assert len(triang.edges) == nedges
  105. assert np.min(triang.edges) == 0
  106. assert np.max(triang.edges) == npoints-1
  107. # Neighbors - integers.
  108. # Check that neighbors calculated by C++ triangulation class are the same
  109. # as those returned from delaunay routine.
  110. neighbors = triang.neighbors
  111. triang._neighbors = None
  112. assert_array_equal(triang.neighbors, neighbors)
  113. # Is each point used in at least one triangle?
  114. assert_array_equal(np.unique(triang.triangles), np.arange(npoints))
  115. def test_delaunay_duplicate_points():
  116. npoints = 10
  117. duplicate = 7
  118. duplicate_of = 3
  119. np.random.seed(23)
  120. x = np.random.random(npoints)
  121. y = np.random.random(npoints)
  122. x[duplicate] = x[duplicate_of]
  123. y[duplicate] = y[duplicate_of]
  124. # Create delaunay triangulation.
  125. triang = mtri.Triangulation(x, y)
  126. # Duplicate points should be ignored, so the index of the duplicate points
  127. # should not appear in any triangle.
  128. assert_array_equal(np.unique(triang.triangles),
  129. np.delete(np.arange(npoints), duplicate))
  130. def test_delaunay_points_in_line():
  131. # Cannot triangulate points that are all in a straight line, but check
  132. # that delaunay code fails gracefully.
  133. x = np.linspace(0.0, 10.0, 11)
  134. y = np.linspace(0.0, 10.0, 11)
  135. with pytest.raises(RuntimeError):
  136. mtri.Triangulation(x, y)
  137. # Add an extra point not on the line and the triangulation is OK.
  138. x = np.append(x, 2.0)
  139. y = np.append(y, 8.0)
  140. mtri.Triangulation(x, y)
  141. @pytest.mark.parametrize('x, y', [
  142. # Triangulation should raise a ValueError if passed less than 3 points.
  143. ([], []),
  144. ([1], [5]),
  145. ([1, 2], [5, 6]),
  146. # Triangulation should also raise a ValueError if passed duplicate points
  147. # such that there are less than 3 unique points.
  148. ([1, 2, 1], [5, 6, 5]),
  149. ([1, 2, 2], [5, 6, 6]),
  150. ([1, 1, 1, 2, 1, 2], [5, 5, 5, 6, 5, 6]),
  151. ])
  152. def test_delaunay_insufficient_points(x, y):
  153. with pytest.raises(ValueError):
  154. mtri.Triangulation(x, y)
  155. def test_delaunay_robust():
  156. # Fails when mtri.Triangulation uses matplotlib.delaunay, works when using
  157. # qhull.
  158. tri_points = np.array([
  159. [0.8660254037844384, -0.5000000000000004],
  160. [0.7577722283113836, -0.5000000000000004],
  161. [0.6495190528383288, -0.5000000000000003],
  162. [0.5412658773652739, -0.5000000000000003],
  163. [0.811898816047911, -0.40625000000000044],
  164. [0.7036456405748561, -0.4062500000000004],
  165. [0.5953924651018013, -0.40625000000000033]])
  166. test_points = np.asarray([
  167. [0.58, -0.46],
  168. [0.65, -0.46],
  169. [0.65, -0.42],
  170. [0.7, -0.48],
  171. [0.7, -0.44],
  172. [0.75, -0.44],
  173. [0.8, -0.48]])
  174. # Utility function that indicates if a triangle defined by 3 points
  175. # (xtri, ytri) contains the test point xy. Avoid calling with a point that
  176. # lies on or very near to an edge of the triangle.
  177. def tri_contains_point(xtri, ytri, xy):
  178. tri_points = np.vstack((xtri, ytri)).T
  179. return Path(tri_points).contains_point(xy)
  180. # Utility function that returns how many triangles of the specified
  181. # triangulation contain the test point xy. Avoid calling with a point that
  182. # lies on or very near to an edge of any triangle in the triangulation.
  183. def tris_contain_point(triang, xy):
  184. return sum(tri_contains_point(triang.x[tri], triang.y[tri], xy)
  185. for tri in triang.triangles)
  186. # Using matplotlib.delaunay, an invalid triangulation is created with
  187. # overlapping triangles; qhull is OK.
  188. triang = mtri.Triangulation(tri_points[:, 0], tri_points[:, 1])
  189. for test_point in test_points:
  190. assert tris_contain_point(triang, test_point) == 1
  191. # If ignore the first point of tri_points, matplotlib.delaunay throws a
  192. # KeyError when calculating the convex hull; qhull is OK.
  193. triang = mtri.Triangulation(tri_points[1:, 0], tri_points[1:, 1])
  194. @image_comparison(['tripcolor1.png'])
  195. def test_tripcolor():
  196. x = np.asarray([0, 0.5, 1, 0, 0.5, 1, 0, 0.5, 1, 0.75])
  197. y = np.asarray([0, 0, 0, 0.5, 0.5, 0.5, 1, 1, 1, 0.75])
  198. triangles = np.asarray([
  199. [0, 1, 3], [1, 4, 3],
  200. [1, 2, 4], [2, 5, 4],
  201. [3, 4, 6], [4, 7, 6],
  202. [4, 5, 9], [7, 4, 9], [8, 7, 9], [5, 8, 9]])
  203. # Triangulation with same number of points and triangles.
  204. triang = mtri.Triangulation(x, y, triangles)
  205. Cpoints = x + 0.5*y
  206. xmid = x[triang.triangles].mean(axis=1)
  207. ymid = y[triang.triangles].mean(axis=1)
  208. Cfaces = 0.5*xmid + ymid
  209. plt.subplot(121)
  210. plt.tripcolor(triang, Cpoints, edgecolors='k')
  211. plt.title('point colors')
  212. plt.subplot(122)
  213. plt.tripcolor(triang, facecolors=Cfaces, edgecolors='k')
  214. plt.title('facecolors')
  215. def test_tripcolor_color():
  216. x = [-1, 0, 1, 0]
  217. y = [0, -1, 0, 1]
  218. fig, ax = plt.subplots()
  219. with pytest.raises(TypeError, match=r"tripcolor\(\) missing 1 required "):
  220. ax.tripcolor(x, y)
  221. with pytest.raises(ValueError, match="The length of c must match either"):
  222. ax.tripcolor(x, y, [1, 2, 3])
  223. with pytest.raises(ValueError,
  224. match="length of facecolors must match .* triangles"):
  225. ax.tripcolor(x, y, facecolors=[1, 2, 3, 4])
  226. with pytest.raises(ValueError,
  227. match="'gouraud' .* at the points.* not at the faces"):
  228. ax.tripcolor(x, y, facecolors=[1, 2], shading='gouraud')
  229. with pytest.raises(ValueError,
  230. match="'gouraud' .* at the points.* not at the faces"):
  231. ax.tripcolor(x, y, [1, 2], shading='gouraud') # faces
  232. with pytest.raises(TypeError,
  233. match="positional.*'c'.*keyword-only.*'facecolors'"):
  234. ax.tripcolor(x, y, C=[1, 2, 3, 4])
  235. with pytest.raises(TypeError, match="Unexpected positional parameter"):
  236. ax.tripcolor(x, y, [1, 2], 'unused_positional')
  237. # smoke test for valid color specifications (via C or facecolors)
  238. ax.tripcolor(x, y, [1, 2, 3, 4]) # edges
  239. ax.tripcolor(x, y, [1, 2, 3, 4], shading='gouraud') # edges
  240. ax.tripcolor(x, y, [1, 2]) # faces
  241. ax.tripcolor(x, y, facecolors=[1, 2]) # faces
  242. def test_tripcolor_clim():
  243. np.random.seed(19680801)
  244. a, b, c = np.random.rand(10), np.random.rand(10), np.random.rand(10)
  245. ax = plt.figure().add_subplot()
  246. clim = (0.25, 0.75)
  247. norm = ax.tripcolor(a, b, c, clim=clim).norm
  248. assert (norm.vmin, norm.vmax) == clim
  249. def test_tripcolor_warnings():
  250. x = [-1, 0, 1, 0]
  251. y = [0, -1, 0, 1]
  252. c = [0.4, 0.5]
  253. fig, ax = plt.subplots()
  254. # facecolors takes precedence over c
  255. with pytest.warns(UserWarning, match="Positional parameter c .*no effect"):
  256. ax.tripcolor(x, y, c, facecolors=c)
  257. with pytest.warns(UserWarning, match="Positional parameter c .*no effect"):
  258. ax.tripcolor(x, y, 'interpreted as c', facecolors=c)
  259. def test_no_modify():
  260. # Test that Triangulation does not modify triangles array passed to it.
  261. triangles = np.array([[3, 2, 0], [3, 1, 0]], dtype=np.int32)
  262. points = np.array([(0, 0), (0, 1.1), (1, 0), (1, 1)])
  263. old_triangles = triangles.copy()
  264. mtri.Triangulation(points[:, 0], points[:, 1], triangles).edges
  265. assert_array_equal(old_triangles, triangles)
  266. def test_trifinder():
  267. # Test points within triangles of masked triangulation.
  268. x, y = np.meshgrid(np.arange(4), np.arange(4))
  269. x = x.ravel()
  270. y = y.ravel()
  271. triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6],
  272. [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9],
  273. [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13],
  274. [10, 14, 13], [10, 11, 14], [11, 15, 14]]
  275. mask = np.zeros(len(triangles))
  276. mask[8:10] = 1
  277. triang = mtri.Triangulation(x, y, triangles, mask)
  278. trifinder = triang.get_trifinder()
  279. xs = [0.25, 1.25, 2.25, 3.25]
  280. ys = [0.25, 1.25, 2.25, 3.25]
  281. xs, ys = np.meshgrid(xs, ys)
  282. xs = xs.ravel()
  283. ys = ys.ravel()
  284. tris = trifinder(xs, ys)
  285. assert_array_equal(tris, [0, 2, 4, -1, 6, -1, 10, -1,
  286. 12, 14, 16, -1, -1, -1, -1, -1])
  287. tris = trifinder(xs-0.5, ys-0.5)
  288. assert_array_equal(tris, [-1, -1, -1, -1, -1, 1, 3, 5,
  289. -1, 7, -1, 11, -1, 13, 15, 17])
  290. # Test points exactly on boundary edges of masked triangulation.
  291. 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]
  292. 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]
  293. tris = trifinder(xs, ys)
  294. assert_array_equal(tris, [0, 2, 4, 13, 15, 17, 3, 14, 6, 7, 10, 11])
  295. # Test points exactly on boundary corners of masked triangulation.
  296. xs = [0.0, 3.0]
  297. ys = [0.0, 3.0]
  298. tris = trifinder(xs, ys)
  299. assert_array_equal(tris, [0, 17])
  300. #
  301. # Test triangles with horizontal colinear points. These are not valid
  302. # triangulations, but we try to deal with the simplest violations.
  303. #
  304. # If +ve, triangulation is OK, if -ve triangulation invalid,
  305. # if zero have colinear points but should pass tests anyway.
  306. delta = 0.0
  307. x = [1.5, 0, 1, 2, 3, 1.5, 1.5]
  308. y = [-1, 0, 0, 0, 0, delta, 1]
  309. triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5],
  310. [3, 4, 5], [1, 5, 6], [4, 6, 5]]
  311. triang = mtri.Triangulation(x, y, triangles)
  312. trifinder = triang.get_trifinder()
  313. xs = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9]
  314. ys = [-0.1, 0.1]
  315. xs, ys = np.meshgrid(xs, ys)
  316. tris = trifinder(xs, ys)
  317. assert_array_equal(tris, [[-1, 0, 0, 1, 1, 2, -1],
  318. [-1, 6, 6, 6, 7, 7, -1]])
  319. #
  320. # Test triangles with vertical colinear points. These are not valid
  321. # triangulations, but we try to deal with the simplest violations.
  322. #
  323. # If +ve, triangulation is OK, if -ve triangulation invalid,
  324. # if zero have colinear points but should pass tests anyway.
  325. delta = 0.0
  326. x = [-1, -delta, 0, 0, 0, 0, 1]
  327. y = [1.5, 1.5, 0, 1, 2, 3, 1.5]
  328. triangles = [[0, 1, 2], [0, 1, 5], [1, 2, 3], [1, 3, 4], [1, 4, 5],
  329. [2, 6, 3], [3, 6, 4], [4, 6, 5]]
  330. triang = mtri.Triangulation(x, y, triangles)
  331. trifinder = triang.get_trifinder()
  332. xs = [-0.1, 0.1]
  333. ys = [-0.1, 0.4, 0.9, 1.4, 1.9, 2.4, 2.9]
  334. xs, ys = np.meshgrid(xs, ys)
  335. tris = trifinder(xs, ys)
  336. assert_array_equal(tris, [[-1, -1], [0, 5], [0, 5], [0, 6], [1, 6], [1, 7],
  337. [-1, -1]])
  338. # Test that changing triangulation by setting a mask causes the trifinder
  339. # to be reinitialised.
  340. x = [0, 1, 0, 1]
  341. y = [0, 0, 1, 1]
  342. triangles = [[0, 1, 2], [1, 3, 2]]
  343. triang = mtri.Triangulation(x, y, triangles)
  344. trifinder = triang.get_trifinder()
  345. xs = [-0.2, 0.2, 0.8, 1.2]
  346. ys = [0.5, 0.5, 0.5, 0.5]
  347. tris = trifinder(xs, ys)
  348. assert_array_equal(tris, [-1, 0, 1, -1])
  349. triang.set_mask([1, 0])
  350. assert trifinder == triang.get_trifinder()
  351. tris = trifinder(xs, ys)
  352. assert_array_equal(tris, [-1, -1, 1, -1])
  353. def test_triinterp():
  354. # Test points within triangles of masked triangulation.
  355. x, y = np.meshgrid(np.arange(4), np.arange(4))
  356. x = x.ravel()
  357. y = y.ravel()
  358. z = 1.23*x - 4.79*y
  359. triangles = [[0, 1, 4], [1, 5, 4], [1, 2, 5], [2, 6, 5], [2, 3, 6],
  360. [3, 7, 6], [4, 5, 8], [5, 9, 8], [5, 6, 9], [6, 10, 9],
  361. [6, 7, 10], [7, 11, 10], [8, 9, 12], [9, 13, 12], [9, 10, 13],
  362. [10, 14, 13], [10, 11, 14], [11, 15, 14]]
  363. mask = np.zeros(len(triangles))
  364. mask[8:10] = 1
  365. triang = mtri.Triangulation(x, y, triangles, mask)
  366. linear_interp = mtri.LinearTriInterpolator(triang, z)
  367. cubic_min_E = mtri.CubicTriInterpolator(triang, z)
  368. cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
  369. xs = np.linspace(0.25, 2.75, 6)
  370. ys = [0.25, 0.75, 2.25, 2.75]
  371. xs, ys = np.meshgrid(xs, ys) # Testing arrays with array.ndim = 2
  372. for interp in (linear_interp, cubic_min_E, cubic_geom):
  373. zs = interp(xs, ys)
  374. assert_array_almost_equal(zs, (1.23*xs - 4.79*ys))
  375. # Test points outside triangulation.
  376. xs = [-0.25, 1.25, 1.75, 3.25]
  377. ys = xs
  378. xs, ys = np.meshgrid(xs, ys)
  379. for interp in (linear_interp, cubic_min_E, cubic_geom):
  380. zs = linear_interp(xs, ys)
  381. assert_array_equal(zs.mask, [[True]*4]*4)
  382. # Test mixed configuration (outside / inside).
  383. xs = np.linspace(0.25, 1.75, 6)
  384. ys = [0.25, 0.75, 1.25, 1.75]
  385. xs, ys = np.meshgrid(xs, ys)
  386. for interp in (linear_interp, cubic_min_E, cubic_geom):
  387. zs = interp(xs, ys)
  388. matest.assert_array_almost_equal(zs, (1.23*xs - 4.79*ys))
  389. mask = (xs >= 1) * (xs <= 2) * (ys >= 1) * (ys <= 2)
  390. assert_array_equal(zs.mask, mask)
  391. # 2nd order patch test: on a grid with an 'arbitrary shaped' triangle,
  392. # patch test shall be exact for quadratic functions and cubic
  393. # interpolator if *kind* = user
  394. (a, b, c) = (1.23, -4.79, 0.6)
  395. def quad(x, y):
  396. return a*(x-0.5)**2 + b*(y-0.5)**2 + c*x*y
  397. def gradient_quad(x, y):
  398. return (2*a*(x-0.5) + c*y, 2*b*(y-0.5) + c*x)
  399. x = np.array([0.2, 0.33367, 0.669, 0., 1., 1., 0.])
  400. y = np.array([0.3, 0.80755, 0.4335, 0., 0., 1., 1.])
  401. triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5],
  402. [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]])
  403. triang = mtri.Triangulation(x, y, triangles)
  404. z = quad(x, y)
  405. dz = gradient_quad(x, y)
  406. # test points for 2nd order patch test
  407. xs = np.linspace(0., 1., 5)
  408. ys = np.linspace(0., 1., 5)
  409. xs, ys = np.meshgrid(xs, ys)
  410. cubic_user = mtri.CubicTriInterpolator(triang, z, kind='user', dz=dz)
  411. interp_zs = cubic_user(xs, ys)
  412. assert_array_almost_equal(interp_zs, quad(xs, ys))
  413. (interp_dzsdx, interp_dzsdy) = cubic_user.gradient(x, y)
  414. (dzsdx, dzsdy) = gradient_quad(x, y)
  415. assert_array_almost_equal(interp_dzsdx, dzsdx)
  416. assert_array_almost_equal(interp_dzsdy, dzsdy)
  417. # Cubic improvement: cubic interpolation shall perform better than linear
  418. # on a sufficiently dense mesh for a quadratic function.
  419. n = 11
  420. x, y = np.meshgrid(np.linspace(0., 1., n+1), np.linspace(0., 1., n+1))
  421. x = x.ravel()
  422. y = y.ravel()
  423. z = quad(x, y)
  424. triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1))
  425. xs, ys = np.meshgrid(np.linspace(0.1, 0.9, 5), np.linspace(0.1, 0.9, 5))
  426. xs = xs.ravel()
  427. ys = ys.ravel()
  428. linear_interp = mtri.LinearTriInterpolator(triang, z)
  429. cubic_min_E = mtri.CubicTriInterpolator(triang, z)
  430. cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
  431. zs = quad(xs, ys)
  432. diff_lin = np.abs(linear_interp(xs, ys) - zs)
  433. for interp in (cubic_min_E, cubic_geom):
  434. diff_cubic = np.abs(interp(xs, ys) - zs)
  435. assert np.max(diff_lin) >= 10 * np.max(diff_cubic)
  436. assert (np.dot(diff_lin, diff_lin) >=
  437. 100 * np.dot(diff_cubic, diff_cubic))
  438. def test_triinterpcubic_C1_continuity():
  439. # Below the 4 tests which demonstrate C1 continuity of the
  440. # TriCubicInterpolator (testing the cubic shape functions on arbitrary
  441. # triangle):
  442. #
  443. # 1) Testing continuity of function & derivatives at corner for all 9
  444. # shape functions. Testing also function values at same location.
  445. # 2) Testing C1 continuity along each edge (as gradient is polynomial of
  446. # 2nd order, it is sufficient to test at the middle).
  447. # 3) Testing C1 continuity at triangle barycenter (where the 3 subtriangles
  448. # meet)
  449. # 4) Testing C1 continuity at median 1/3 points (midside between 2
  450. # subtriangles)
  451. # Utility test function check_continuity
  452. def check_continuity(interpolator, loc, values=None):
  453. """
  454. Checks the continuity of interpolator (and its derivatives) near
  455. location loc. Can check the value at loc itself if *values* is
  456. provided.
  457. *interpolator* TriInterpolator
  458. *loc* location to test (x0, y0)
  459. *values* (optional) array [z0, dzx0, dzy0] to check the value at *loc*
  460. """
  461. n_star = 24 # Number of continuity points in a boundary of loc
  462. epsilon = 1.e-10 # Distance for loc boundary
  463. k = 100. # Continuity coefficient
  464. (loc_x, loc_y) = loc
  465. star_x = loc_x + epsilon*np.cos(np.linspace(0., 2*np.pi, n_star))
  466. star_y = loc_y + epsilon*np.sin(np.linspace(0., 2*np.pi, n_star))
  467. z = interpolator([loc_x], [loc_y])[0]
  468. (dzx, dzy) = interpolator.gradient([loc_x], [loc_y])
  469. if values is not None:
  470. assert_array_almost_equal(z, values[0])
  471. assert_array_almost_equal(dzx[0], values[1])
  472. assert_array_almost_equal(dzy[0], values[2])
  473. diff_z = interpolator(star_x, star_y) - z
  474. (tab_dzx, tab_dzy) = interpolator.gradient(star_x, star_y)
  475. diff_dzx = tab_dzx - dzx
  476. diff_dzy = tab_dzy - dzy
  477. assert_array_less(diff_z, epsilon*k)
  478. assert_array_less(diff_dzx, epsilon*k)
  479. assert_array_less(diff_dzy, epsilon*k)
  480. # Drawing arbitrary triangle (a, b, c) inside a unit square.
  481. (ax, ay) = (0.2, 0.3)
  482. (bx, by) = (0.33367, 0.80755)
  483. (cx, cy) = (0.669, 0.4335)
  484. x = np.array([ax, bx, cx, 0., 1., 1., 0.])
  485. y = np.array([ay, by, cy, 0., 0., 1., 1.])
  486. triangles = np.array([[0, 1, 2], [3, 0, 4], [4, 0, 2], [4, 2, 5],
  487. [1, 5, 2], [6, 5, 1], [6, 1, 0], [6, 0, 3]])
  488. triang = mtri.Triangulation(x, y, triangles)
  489. for idof in range(9):
  490. z = np.zeros(7, dtype=np.float64)
  491. dzx = np.zeros(7, dtype=np.float64)
  492. dzy = np.zeros(7, dtype=np.float64)
  493. values = np.zeros([3, 3], dtype=np.float64)
  494. case = idof//3
  495. values[case, idof % 3] = 1.0
  496. if case == 0:
  497. z[idof] = 1.0
  498. elif case == 1:
  499. dzx[idof % 3] = 1.0
  500. elif case == 2:
  501. dzy[idof % 3] = 1.0
  502. interp = mtri.CubicTriInterpolator(triang, z, kind='user',
  503. dz=(dzx, dzy))
  504. # Test 1) Checking values and continuity at nodes
  505. check_continuity(interp, (ax, ay), values[:, 0])
  506. check_continuity(interp, (bx, by), values[:, 1])
  507. check_continuity(interp, (cx, cy), values[:, 2])
  508. # Test 2) Checking continuity at midside nodes
  509. check_continuity(interp, ((ax+bx)*0.5, (ay+by)*0.5))
  510. check_continuity(interp, ((ax+cx)*0.5, (ay+cy)*0.5))
  511. check_continuity(interp, ((cx+bx)*0.5, (cy+by)*0.5))
  512. # Test 3) Checking continuity at barycenter
  513. check_continuity(interp, ((ax+bx+cx)/3., (ay+by+cy)/3.))
  514. # Test 4) Checking continuity at median 1/3-point
  515. check_continuity(interp, ((4.*ax+bx+cx)/6., (4.*ay+by+cy)/6.))
  516. check_continuity(interp, ((ax+4.*bx+cx)/6., (ay+4.*by+cy)/6.))
  517. check_continuity(interp, ((ax+bx+4.*cx)/6., (ay+by+4.*cy)/6.))
  518. def test_triinterpcubic_cg_solver():
  519. # Now 3 basic tests of the Sparse CG solver, used for
  520. # TriCubicInterpolator with *kind* = 'min_E'
  521. # 1) A commonly used test involves a 2d Poisson matrix.
  522. def poisson_sparse_matrix(n, m):
  523. """
  524. Return the sparse, (n*m, n*m) matrix in coo format resulting from the
  525. discretisation of the 2-dimensional Poisson equation according to a
  526. finite difference numerical scheme on a uniform (n, m) grid.
  527. """
  528. l = m*n
  529. rows = np.concatenate([
  530. np.arange(l, dtype=np.int32),
  531. np.arange(l-1, dtype=np.int32), np.arange(1, l, dtype=np.int32),
  532. np.arange(l-n, dtype=np.int32), np.arange(n, l, dtype=np.int32)])
  533. cols = np.concatenate([
  534. np.arange(l, dtype=np.int32),
  535. np.arange(1, l, dtype=np.int32), np.arange(l-1, dtype=np.int32),
  536. np.arange(n, l, dtype=np.int32), np.arange(l-n, dtype=np.int32)])
  537. vals = np.concatenate([
  538. 4*np.ones(l, dtype=np.float64),
  539. -np.ones(l-1, dtype=np.float64), -np.ones(l-1, dtype=np.float64),
  540. -np.ones(l-n, dtype=np.float64), -np.ones(l-n, dtype=np.float64)])
  541. # In fact +1 and -1 diags have some zeros
  542. vals[l:2*l-1][m-1::m] = 0.
  543. vals[2*l-1:3*l-2][m-1::m] = 0.
  544. return vals, rows, cols, (n*m, n*m)
  545. # Instantiating a sparse Poisson matrix of size 48 x 48:
  546. (n, m) = (12, 4)
  547. mat = mtri._triinterpolate._Sparse_Matrix_coo(*poisson_sparse_matrix(n, m))
  548. mat.compress_csc()
  549. mat_dense = mat.to_dense()
  550. # Testing a sparse solve for all 48 basis vector
  551. for itest in range(n*m):
  552. b = np.zeros(n*m, dtype=np.float64)
  553. b[itest] = 1.
  554. x, _ = mtri._triinterpolate._cg(A=mat, b=b, x0=np.zeros(n*m),
  555. tol=1.e-10)
  556. assert_array_almost_equal(np.dot(mat_dense, x), b)
  557. # 2) Same matrix with inserting 2 rows - cols with null diag terms
  558. # (but still linked with the rest of the matrix by extra-diag terms)
  559. (i_zero, j_zero) = (12, 49)
  560. vals, rows, cols, _ = poisson_sparse_matrix(n, m)
  561. rows = rows + 1*(rows >= i_zero) + 1*(rows >= j_zero)
  562. cols = cols + 1*(cols >= i_zero) + 1*(cols >= j_zero)
  563. # adding extra-diag terms
  564. rows = np.concatenate([rows, [i_zero, i_zero-1, j_zero, j_zero-1]])
  565. cols = np.concatenate([cols, [i_zero-1, i_zero, j_zero-1, j_zero]])
  566. vals = np.concatenate([vals, [1., 1., 1., 1.]])
  567. mat = mtri._triinterpolate._Sparse_Matrix_coo(vals, rows, cols,
  568. (n*m + 2, n*m + 2))
  569. mat.compress_csc()
  570. mat_dense = mat.to_dense()
  571. # Testing a sparse solve for all 50 basis vec
  572. for itest in range(n*m + 2):
  573. b = np.zeros(n*m + 2, dtype=np.float64)
  574. b[itest] = 1.
  575. x, _ = mtri._triinterpolate._cg(A=mat, b=b, x0=np.ones(n * m + 2),
  576. tol=1.e-10)
  577. assert_array_almost_equal(np.dot(mat_dense, x), b)
  578. # 3) Now a simple test that summation of duplicate (i.e. with same rows,
  579. # same cols) entries occurs when compressed.
  580. vals = np.ones(17, dtype=np.float64)
  581. rows = np.array([0, 1, 2, 0, 0, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1],
  582. dtype=np.int32)
  583. cols = np.array([0, 1, 2, 1, 1, 0, 0, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2],
  584. dtype=np.int32)
  585. dim = (3, 3)
  586. mat = mtri._triinterpolate._Sparse_Matrix_coo(vals, rows, cols, dim)
  587. mat.compress_csc()
  588. mat_dense = mat.to_dense()
  589. assert_array_almost_equal(mat_dense, np.array([
  590. [1., 2., 0.], [2., 1., 5.], [0., 5., 1.]], dtype=np.float64))
  591. def test_triinterpcubic_geom_weights():
  592. # Tests to check computation of weights for _DOF_estimator_geom:
  593. # The weight sum per triangle can be 1. (in case all angles < 90 degrees)
  594. # or (2*w_i) where w_i = 1-alpha_i/np.pi is the weight of apex i; alpha_i
  595. # is the apex angle > 90 degrees.
  596. (ax, ay) = (0., 1.687)
  597. x = np.array([ax, 0.5*ax, 0., 1.])
  598. y = np.array([ay, -ay, 0., 0.])
  599. z = np.zeros(4, dtype=np.float64)
  600. triangles = [[0, 2, 3], [1, 3, 2]]
  601. sum_w = np.zeros([4, 2]) # 4 possibilities; 2 triangles
  602. for theta in np.linspace(0., 2*np.pi, 14): # rotating the figure...
  603. x_rot = np.cos(theta)*x + np.sin(theta)*y
  604. y_rot = -np.sin(theta)*x + np.cos(theta)*y
  605. triang = mtri.Triangulation(x_rot, y_rot, triangles)
  606. cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
  607. dof_estimator = mtri._triinterpolate._DOF_estimator_geom(cubic_geom)
  608. weights = dof_estimator.compute_geom_weights()
  609. # Testing for the 4 possibilities...
  610. sum_w[0, :] = np.sum(weights, 1) - 1
  611. for itri in range(3):
  612. sum_w[itri+1, :] = np.sum(weights, 1) - 2*weights[:, itri]
  613. assert_array_almost_equal(np.min(np.abs(sum_w), axis=0),
  614. np.array([0., 0.], dtype=np.float64))
  615. def test_triinterp_colinear():
  616. # Tests interpolating inside a triangulation with horizontal colinear
  617. # points (refer also to the tests :func:`test_trifinder` ).
  618. #
  619. # These are not valid triangulations, but we try to deal with the
  620. # simplest violations (i. e. those handled by default TriFinder).
  621. #
  622. # Note that the LinearTriInterpolator and the CubicTriInterpolator with
  623. # kind='min_E' or 'geom' still pass a linear patch test.
  624. # We also test interpolation inside a flat triangle, by forcing
  625. # *tri_index* in a call to :meth:`_interpolate_multikeys`.
  626. # If +ve, triangulation is OK, if -ve triangulation invalid,
  627. # if zero have colinear points but should pass tests anyway.
  628. delta = 0.
  629. x0 = np.array([1.5, 0, 1, 2, 3, 1.5, 1.5])
  630. y0 = np.array([-1, 0, 0, 0, 0, delta, 1])
  631. # We test different affine transformations of the initial figure; to
  632. # avoid issues related to round-off errors we only use integer
  633. # coefficients (otherwise the Triangulation might become invalid even with
  634. # delta == 0).
  635. transformations = [[1, 0], [0, 1], [1, 1], [1, 2], [-2, -1], [-2, 1]]
  636. for transformation in transformations:
  637. x_rot = transformation[0]*x0 + transformation[1]*y0
  638. y_rot = -transformation[1]*x0 + transformation[0]*y0
  639. (x, y) = (x_rot, y_rot)
  640. z = 1.23*x - 4.79*y
  641. triangles = [[0, 2, 1], [0, 3, 2], [0, 4, 3], [1, 2, 5], [2, 3, 5],
  642. [3, 4, 5], [1, 5, 6], [4, 6, 5]]
  643. triang = mtri.Triangulation(x, y, triangles)
  644. xs = np.linspace(np.min(triang.x), np.max(triang.x), 20)
  645. ys = np.linspace(np.min(triang.y), np.max(triang.y), 20)
  646. xs, ys = np.meshgrid(xs, ys)
  647. xs = xs.ravel()
  648. ys = ys.ravel()
  649. mask_out = (triang.get_trifinder()(xs, ys) == -1)
  650. zs_target = np.ma.array(1.23*xs - 4.79*ys, mask=mask_out)
  651. linear_interp = mtri.LinearTriInterpolator(triang, z)
  652. cubic_min_E = mtri.CubicTriInterpolator(triang, z)
  653. cubic_geom = mtri.CubicTriInterpolator(triang, z, kind='geom')
  654. for interp in (linear_interp, cubic_min_E, cubic_geom):
  655. zs = interp(xs, ys)
  656. assert_array_almost_equal(zs_target, zs)
  657. # Testing interpolation inside the flat triangle number 4: [2, 3, 5]
  658. # by imposing *tri_index* in a call to :meth:`_interpolate_multikeys`
  659. itri = 4
  660. pt1 = triang.triangles[itri, 0]
  661. pt2 = triang.triangles[itri, 1]
  662. xs = np.linspace(triang.x[pt1], triang.x[pt2], 10)
  663. ys = np.linspace(triang.y[pt1], triang.y[pt2], 10)
  664. zs_target = 1.23*xs - 4.79*ys
  665. for interp in (linear_interp, cubic_min_E, cubic_geom):
  666. zs, = interp._interpolate_multikeys(
  667. xs, ys, tri_index=itri*np.ones(10, dtype=np.int32))
  668. assert_array_almost_equal(zs_target, zs)
  669. def test_triinterp_transformations():
  670. # 1) Testing that the interpolation scheme is invariant by rotation of the
  671. # whole figure.
  672. # Note: This test is non-trivial for a CubicTriInterpolator with
  673. # kind='min_E'. It does fail for a non-isotropic stiffness matrix E of
  674. # :class:`_ReducedHCT_Element` (tested with E=np.diag([1., 1., 1.])), and
  675. # provides a good test for :meth:`get_Kff_and_Ff`of the same class.
  676. #
  677. # 2) Also testing that the interpolation scheme is invariant by expansion
  678. # of the whole figure along one axis.
  679. n_angles = 20
  680. n_radii = 10
  681. min_radius = 0.15
  682. def z(x, y):
  683. r1 = np.hypot(0.5 - x, 0.5 - y)
  684. theta1 = np.arctan2(0.5 - x, 0.5 - y)
  685. r2 = np.hypot(-x - 0.2, -y - 0.2)
  686. theta2 = np.arctan2(-x - 0.2, -y - 0.2)
  687. z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
  688. (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
  689. 0.7*(x**2 + y**2))
  690. return (np.max(z)-z)/(np.max(z)-np.min(z))
  691. # First create the x and y coordinates of the points.
  692. radii = np.linspace(min_radius, 0.95, n_radii)
  693. angles = np.linspace(0 + n_angles, 2*np.pi + n_angles,
  694. n_angles, endpoint=False)
  695. angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
  696. angles[:, 1::2] += np.pi/n_angles
  697. x0 = (radii*np.cos(angles)).flatten()
  698. y0 = (radii*np.sin(angles)).flatten()
  699. triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation
  700. z0 = z(x0, y0)
  701. # Then create the test points
  702. xs0 = np.linspace(-1., 1., 23)
  703. ys0 = np.linspace(-1., 1., 23)
  704. xs0, ys0 = np.meshgrid(xs0, ys0)
  705. xs0 = xs0.ravel()
  706. ys0 = ys0.ravel()
  707. interp_z0 = {}
  708. for i_angle in range(2):
  709. # Rotating everything
  710. theta = 2*np.pi / n_angles * i_angle
  711. x = np.cos(theta)*x0 + np.sin(theta)*y0
  712. y = -np.sin(theta)*x0 + np.cos(theta)*y0
  713. xs = np.cos(theta)*xs0 + np.sin(theta)*ys0
  714. ys = -np.sin(theta)*xs0 + np.cos(theta)*ys0
  715. triang = mtri.Triangulation(x, y, triang0.triangles)
  716. linear_interp = mtri.LinearTriInterpolator(triang, z0)
  717. cubic_min_E = mtri.CubicTriInterpolator(triang, z0)
  718. cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom')
  719. dic_interp = {'lin': linear_interp,
  720. 'min_E': cubic_min_E,
  721. 'geom': cubic_geom}
  722. # Testing that the interpolation is invariant by rotation...
  723. for interp_key in ['lin', 'min_E', 'geom']:
  724. interp = dic_interp[interp_key]
  725. if i_angle == 0:
  726. interp_z0[interp_key] = interp(xs0, ys0) # storage
  727. else:
  728. interpz = interp(xs, ys)
  729. matest.assert_array_almost_equal(interpz,
  730. interp_z0[interp_key])
  731. scale_factor = 987654.3210
  732. for scaled_axis in ('x', 'y'):
  733. # Scaling everything (expansion along scaled_axis)
  734. if scaled_axis == 'x':
  735. x = scale_factor * x0
  736. y = y0
  737. xs = scale_factor * xs0
  738. ys = ys0
  739. else:
  740. x = x0
  741. y = scale_factor * y0
  742. xs = xs0
  743. ys = scale_factor * ys0
  744. triang = mtri.Triangulation(x, y, triang0.triangles)
  745. linear_interp = mtri.LinearTriInterpolator(triang, z0)
  746. cubic_min_E = mtri.CubicTriInterpolator(triang, z0)
  747. cubic_geom = mtri.CubicTriInterpolator(triang, z0, kind='geom')
  748. dic_interp = {'lin': linear_interp,
  749. 'min_E': cubic_min_E,
  750. 'geom': cubic_geom}
  751. # Test that the interpolation is invariant by expansion along 1 axis...
  752. for interp_key in ['lin', 'min_E', 'geom']:
  753. interpz = dic_interp[interp_key](xs, ys)
  754. matest.assert_array_almost_equal(interpz, interp_z0[interp_key])
  755. @image_comparison(['tri_smooth_contouring.png'], remove_text=True, tol=0.072)
  756. def test_tri_smooth_contouring():
  757. # Image comparison based on example tricontour_smooth_user.
  758. n_angles = 20
  759. n_radii = 10
  760. min_radius = 0.15
  761. def z(x, y):
  762. r1 = np.hypot(0.5 - x, 0.5 - y)
  763. theta1 = np.arctan2(0.5 - x, 0.5 - y)
  764. r2 = np.hypot(-x - 0.2, -y - 0.2)
  765. theta2 = np.arctan2(-x - 0.2, -y - 0.2)
  766. z = -(2*(np.exp((r1/10)**2)-1)*30. * np.cos(7.*theta1) +
  767. (np.exp((r2/10)**2)-1)*30. * np.cos(11.*theta2) +
  768. 0.7*(x**2 + y**2))
  769. return (np.max(z)-z)/(np.max(z)-np.min(z))
  770. # First create the x and y coordinates of the points.
  771. radii = np.linspace(min_radius, 0.95, n_radii)
  772. angles = np.linspace(0 + n_angles, 2*np.pi + n_angles,
  773. n_angles, endpoint=False)
  774. angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
  775. angles[:, 1::2] += np.pi/n_angles
  776. x0 = (radii*np.cos(angles)).flatten()
  777. y0 = (radii*np.sin(angles)).flatten()
  778. triang0 = mtri.Triangulation(x0, y0) # Delaunay triangulation
  779. z0 = z(x0, y0)
  780. triang0.set_mask(np.hypot(x0[triang0.triangles].mean(axis=1),
  781. y0[triang0.triangles].mean(axis=1))
  782. < min_radius)
  783. # Then the plot
  784. refiner = mtri.UniformTriRefiner(triang0)
  785. tri_refi, z_test_refi = refiner.refine_field(z0, subdiv=4)
  786. levels = np.arange(0., 1., 0.025)
  787. plt.triplot(triang0, lw=0.5, color='0.5')
  788. plt.tricontour(tri_refi, z_test_refi, levels=levels, colors="black")
  789. @image_comparison(['tri_smooth_gradient.png'], remove_text=True, tol=0.092)
  790. def test_tri_smooth_gradient():
  791. # Image comparison based on example trigradient_demo.
  792. def dipole_potential(x, y):
  793. """An electric dipole potential V."""
  794. r_sq = x**2 + y**2
  795. theta = np.arctan2(y, x)
  796. z = np.cos(theta)/r_sq
  797. return (np.max(z)-z) / (np.max(z)-np.min(z))
  798. # Creating a Triangulation
  799. n_angles = 30
  800. n_radii = 10
  801. min_radius = 0.2
  802. radii = np.linspace(min_radius, 0.95, n_radii)
  803. angles = np.linspace(0, 2*np.pi, n_angles, endpoint=False)
  804. angles = np.repeat(angles[..., np.newaxis], n_radii, axis=1)
  805. angles[:, 1::2] += np.pi/n_angles
  806. x = (radii*np.cos(angles)).flatten()
  807. y = (radii*np.sin(angles)).flatten()
  808. V = dipole_potential(x, y)
  809. triang = mtri.Triangulation(x, y)
  810. triang.set_mask(np.hypot(x[triang.triangles].mean(axis=1),
  811. y[triang.triangles].mean(axis=1))
  812. < min_radius)
  813. # Refine data - interpolates the electrical potential V
  814. refiner = mtri.UniformTriRefiner(triang)
  815. tri_refi, z_test_refi = refiner.refine_field(V, subdiv=3)
  816. # Computes the electrical field (Ex, Ey) as gradient of -V
  817. tci = mtri.CubicTriInterpolator(triang, -V)
  818. Ex, Ey = tci.gradient(triang.x, triang.y)
  819. E_norm = np.hypot(Ex, Ey)
  820. # Plot the triangulation, the potential iso-contours and the vector field
  821. plt.figure()
  822. plt.gca().set_aspect('equal')
  823. plt.triplot(triang, color='0.8')
  824. levels = np.arange(0., 1., 0.01)
  825. cmap = mpl.colormaps['hot']
  826. plt.tricontour(tri_refi, z_test_refi, levels=levels, cmap=cmap,
  827. linewidths=[2.0, 1.0, 1.0, 1.0])
  828. # Plots direction of the electrical vector field
  829. plt.quiver(triang.x, triang.y, Ex/E_norm, Ey/E_norm,
  830. units='xy', scale=10., zorder=3, color='blue',
  831. width=0.007, headwidth=3., headlength=4.)
  832. # We are leaving ax.use_sticky_margins as True, so the
  833. # view limits are the contour data limits.
  834. def test_tritools():
  835. # Tests TriAnalyzer.scale_factors on masked triangulation
  836. # Tests circle_ratios on equilateral and right-angled triangle.
  837. x = np.array([0., 1., 0.5, 0., 2.])
  838. y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.])
  839. triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32)
  840. mask = np.array([False, False, True], dtype=bool)
  841. triang = mtri.Triangulation(x, y, triangles, mask=mask)
  842. analyser = mtri.TriAnalyzer(triang)
  843. assert_array_almost_equal(analyser.scale_factors, [1, 1/(1+3**.5/2)])
  844. assert_array_almost_equal(
  845. analyser.circle_ratios(rescale=False),
  846. np.ma.masked_array([0.5, 1./(1.+np.sqrt(2.)), np.nan], mask))
  847. # Tests circle ratio of a flat triangle
  848. x = np.array([0., 1., 2.])
  849. y = np.array([1., 1.+3., 1.+6.])
  850. triangles = np.array([[0, 1, 2]], dtype=np.int32)
  851. triang = mtri.Triangulation(x, y, triangles)
  852. analyser = mtri.TriAnalyzer(triang)
  853. assert_array_almost_equal(analyser.circle_ratios(), np.array([0.]))
  854. # Tests TriAnalyzer.get_flat_tri_mask
  855. # Creates a triangulation of [-1, 1] x [-1, 1] with contiguous groups of
  856. # 'flat' triangles at the 4 corners and at the center. Checks that only
  857. # those at the borders are eliminated by TriAnalyzer.get_flat_tri_mask
  858. n = 9
  859. def power(x, a):
  860. return np.abs(x)**a*np.sign(x)
  861. x = np.linspace(-1., 1., n+1)
  862. x, y = np.meshgrid(power(x, 2.), power(x, 0.25))
  863. x = x.ravel()
  864. y = y.ravel()
  865. triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1))
  866. analyser = mtri.TriAnalyzer(triang)
  867. mask_flat = analyser.get_flat_tri_mask(0.2)
  868. verif_mask = np.zeros(162, dtype=bool)
  869. corners_index = [0, 1, 2, 3, 14, 15, 16, 17, 18, 19, 34, 35, 126, 127,
  870. 142, 143, 144, 145, 146, 147, 158, 159, 160, 161]
  871. verif_mask[corners_index] = True
  872. assert_array_equal(mask_flat, verif_mask)
  873. # Now including a hole (masked triangle) at the center. The center also
  874. # shall be eliminated by get_flat_tri_mask.
  875. mask = np.zeros(162, dtype=bool)
  876. mask[80] = True
  877. triang.set_mask(mask)
  878. mask_flat = analyser.get_flat_tri_mask(0.2)
  879. center_index = [44, 45, 62, 63, 78, 79, 80, 81, 82, 83, 98, 99, 116, 117]
  880. verif_mask[center_index] = True
  881. assert_array_equal(mask_flat, verif_mask)
  882. def test_trirefine():
  883. # Testing subdiv=2 refinement
  884. n = 3
  885. subdiv = 2
  886. x = np.linspace(-1., 1., n+1)
  887. x, y = np.meshgrid(x, x)
  888. x = x.ravel()
  889. y = y.ravel()
  890. mask = np.zeros(2*n**2, dtype=bool)
  891. mask[n**2:] = True
  892. triang = mtri.Triangulation(x, y, triangles=meshgrid_triangles(n+1),
  893. mask=mask)
  894. refiner = mtri.UniformTriRefiner(triang)
  895. refi_triang = refiner.refine_triangulation(subdiv=subdiv)
  896. x_refi = refi_triang.x
  897. y_refi = refi_triang.y
  898. n_refi = n * subdiv**2
  899. x_verif = np.linspace(-1., 1., n_refi+1)
  900. x_verif, y_verif = np.meshgrid(x_verif, x_verif)
  901. x_verif = x_verif.ravel()
  902. y_verif = y_verif.ravel()
  903. ind1d = np.isin(np.around(x_verif*(2.5+y_verif), 8),
  904. np.around(x_refi*(2.5+y_refi), 8))
  905. assert_array_equal(ind1d, True)
  906. # Testing the mask of the refined triangulation
  907. refi_mask = refi_triang.mask
  908. refi_tri_barycenter_x = np.sum(refi_triang.x[refi_triang.triangles],
  909. axis=1) / 3.
  910. refi_tri_barycenter_y = np.sum(refi_triang.y[refi_triang.triangles],
  911. axis=1) / 3.
  912. tri_finder = triang.get_trifinder()
  913. refi_tri_indices = tri_finder(refi_tri_barycenter_x,
  914. refi_tri_barycenter_y)
  915. refi_tri_mask = triang.mask[refi_tri_indices]
  916. assert_array_equal(refi_mask, refi_tri_mask)
  917. # Testing that the numbering of triangles does not change the
  918. # interpolation result.
  919. x = np.asarray([0.0, 1.0, 0.0, 1.0])
  920. y = np.asarray([0.0, 0.0, 1.0, 1.0])
  921. triang = [mtri.Triangulation(x, y, [[0, 1, 3], [3, 2, 0]]),
  922. mtri.Triangulation(x, y, [[0, 1, 3], [2, 0, 3]])]
  923. z = np.hypot(x - 0.3, y - 0.4)
  924. # Refining the 2 triangulations and reordering the points
  925. xyz_data = []
  926. for i in range(2):
  927. refiner = mtri.UniformTriRefiner(triang[i])
  928. refined_triang, refined_z = refiner.refine_field(z, subdiv=1)
  929. xyz = np.dstack((refined_triang.x, refined_triang.y, refined_z))[0]
  930. xyz = xyz[np.lexsort((xyz[:, 1], xyz[:, 0]))]
  931. xyz_data += [xyz]
  932. assert_array_almost_equal(xyz_data[0], xyz_data[1])
  933. @pytest.mark.parametrize('interpolator',
  934. [mtri.LinearTriInterpolator,
  935. mtri.CubicTriInterpolator],
  936. ids=['linear', 'cubic'])
  937. def test_trirefine_masked(interpolator):
  938. # Repeated points means we will have fewer triangles than points, and thus
  939. # get masking.
  940. x, y = np.mgrid[:2, :2]
  941. x = np.repeat(x.flatten(), 2)
  942. y = np.repeat(y.flatten(), 2)
  943. z = np.zeros_like(x)
  944. tri = mtri.Triangulation(x, y)
  945. refiner = mtri.UniformTriRefiner(tri)
  946. interp = interpolator(tri, z)
  947. refiner.refine_field(z, triinterpolator=interp, subdiv=2)
  948. def meshgrid_triangles(n):
  949. """
  950. Return (2*(N-1)**2, 3) array of triangles to mesh (N, N)-point np.meshgrid.
  951. """
  952. tri = []
  953. for i in range(n-1):
  954. for j in range(n-1):
  955. a = i + j*n
  956. b = (i+1) + j*n
  957. c = i + (j+1)*n
  958. d = (i+1) + (j+1)*n
  959. tri += [[a, b, d], [a, d, c]]
  960. return np.array(tri, dtype=np.int32)
  961. def test_triplot_return():
  962. # Check that triplot returns the artists it adds
  963. ax = plt.figure().add_subplot()
  964. triang = mtri.Triangulation(
  965. [0.0, 1.0, 0.0, 1.0], [0.0, 0.0, 1.0, 1.0],
  966. triangles=[[0, 1, 3], [3, 2, 0]])
  967. assert ax.triplot(triang, "b-") is not None, \
  968. 'triplot should return the artist it adds'
  969. def test_trirefiner_fortran_contiguous_triangles():
  970. # github issue 4180. Test requires two arrays of triangles that are
  971. # identical except that one is C-contiguous and one is fortran-contiguous.
  972. triangles1 = np.array([[2, 0, 3], [2, 1, 0]])
  973. assert not np.isfortran(triangles1)
  974. triangles2 = np.array(triangles1, copy=True, order='F')
  975. assert np.isfortran(triangles2)
  976. x = np.array([0.39, 0.59, 0.43, 0.32])
  977. y = np.array([33.99, 34.01, 34.19, 34.18])
  978. triang1 = mtri.Triangulation(x, y, triangles1)
  979. triang2 = mtri.Triangulation(x, y, triangles2)
  980. refiner1 = mtri.UniformTriRefiner(triang1)
  981. refiner2 = mtri.UniformTriRefiner(triang2)
  982. fine_triang1 = refiner1.refine_triangulation(subdiv=1)
  983. fine_triang2 = refiner2.refine_triangulation(subdiv=1)
  984. assert_array_equal(fine_triang1.triangles, fine_triang2.triangles)
  985. def test_qhull_triangle_orientation():
  986. # github issue 4437.
  987. xi = np.linspace(-2, 2, 100)
  988. x, y = map(np.ravel, np.meshgrid(xi, xi))
  989. w = (x > y - 1) & (x < -1.95) & (y > -1.2)
  990. x, y = x[w], y[w]
  991. theta = np.radians(25)
  992. x1 = x*np.cos(theta) - y*np.sin(theta)
  993. y1 = x*np.sin(theta) + y*np.cos(theta)
  994. # Calculate Delaunay triangulation using Qhull.
  995. triang = mtri.Triangulation(x1, y1)
  996. # Neighbors returned by Qhull.
  997. qhull_neighbors = triang.neighbors
  998. # Obtain neighbors using own C++ calculation.
  999. triang._neighbors = None
  1000. own_neighbors = triang.neighbors
  1001. assert_array_equal(qhull_neighbors, own_neighbors)
  1002. def test_trianalyzer_mismatched_indices():
  1003. # github issue 4999.
  1004. x = np.array([0., 1., 0.5, 0., 2.])
  1005. y = np.array([0., 0., 0.5*np.sqrt(3.), -1., 1.])
  1006. triangles = np.array([[0, 1, 2], [0, 1, 3], [1, 2, 4]], dtype=np.int32)
  1007. mask = np.array([False, False, True], dtype=bool)
  1008. triang = mtri.Triangulation(x, y, triangles, mask=mask)
  1009. analyser = mtri.TriAnalyzer(triang)
  1010. # numpy >= 1.10 raises a VisibleDeprecationWarning in the following line
  1011. # prior to the fix.
  1012. analyser._get_compressed_triangulation()
  1013. def test_tricontourf_decreasing_levels():
  1014. # github issue 5477.
  1015. x = [0.0, 1.0, 1.0]
  1016. y = [0.0, 0.0, 1.0]
  1017. z = [0.2, 0.4, 0.6]
  1018. plt.figure()
  1019. with pytest.raises(ValueError):
  1020. plt.tricontourf(x, y, z, [1.0, 0.0])
  1021. def test_internal_cpp_api():
  1022. # Following github issue 8197.
  1023. from matplotlib import _tri # noqa: ensure lazy-loaded module *is* loaded.
  1024. # C++ Triangulation.
  1025. with pytest.raises(
  1026. TypeError,
  1027. match=r'__init__\(\): incompatible constructor arguments.'):
  1028. mpl._tri.Triangulation()
  1029. with pytest.raises(
  1030. ValueError, match=r'x and y must be 1D arrays of the same length'):
  1031. mpl._tri.Triangulation([], [1], [[]], (), (), (), False)
  1032. x = [0, 1, 1]
  1033. y = [0, 0, 1]
  1034. with pytest.raises(
  1035. ValueError,
  1036. match=r'triangles must be a 2D array of shape \(\?,3\)'):
  1037. mpl._tri.Triangulation(x, y, [[0, 1]], (), (), (), False)
  1038. tris = [[0, 1, 2]]
  1039. with pytest.raises(
  1040. ValueError,
  1041. match=r'mask must be a 1D array with the same length as the '
  1042. r'triangles array'):
  1043. mpl._tri.Triangulation(x, y, tris, [0, 1], (), (), False)
  1044. with pytest.raises(
  1045. ValueError, match=r'edges must be a 2D array with shape \(\?,2\)'):
  1046. mpl._tri.Triangulation(x, y, tris, (), [[1]], (), False)
  1047. with pytest.raises(
  1048. ValueError,
  1049. match=r'neighbors must be a 2D array with the same shape as the '
  1050. r'triangles array'):
  1051. mpl._tri.Triangulation(x, y, tris, (), (), [[-1]], False)
  1052. triang = mpl._tri.Triangulation(x, y, tris, (), (), (), False)
  1053. with pytest.raises(
  1054. ValueError,
  1055. match=r'z must be a 1D array with the same length as the '
  1056. r'triangulation x and y arrays'):
  1057. triang.calculate_plane_coefficients([])
  1058. for mask in ([0, 1], None):
  1059. with pytest.raises(
  1060. ValueError,
  1061. match=r'mask must be a 1D array with the same length as the '
  1062. r'triangles array'):
  1063. triang.set_mask(mask)
  1064. triang.set_mask([True])
  1065. assert_array_equal(triang.get_edges(), np.empty((0, 2)))
  1066. triang.set_mask(()) # Equivalent to Python Triangulation mask=None
  1067. assert_array_equal(triang.get_edges(), [[1, 0], [2, 0], [2, 1]])
  1068. # C++ TriContourGenerator.
  1069. with pytest.raises(
  1070. TypeError,
  1071. match=r'__init__\(\): incompatible constructor arguments.'):
  1072. mpl._tri.TriContourGenerator()
  1073. with pytest.raises(
  1074. ValueError,
  1075. match=r'z must be a 1D array with the same length as the x and y '
  1076. r'arrays'):
  1077. mpl._tri.TriContourGenerator(triang, [1])
  1078. z = [0, 1, 2]
  1079. tcg = mpl._tri.TriContourGenerator(triang, z)
  1080. with pytest.raises(
  1081. ValueError, match=r'filled contour levels must be increasing'):
  1082. tcg.create_filled_contour(1, 0)
  1083. # C++ TrapezoidMapTriFinder.
  1084. with pytest.raises(
  1085. TypeError,
  1086. match=r'__init__\(\): incompatible constructor arguments.'):
  1087. mpl._tri.TrapezoidMapTriFinder()
  1088. trifinder = mpl._tri.TrapezoidMapTriFinder(triang)
  1089. with pytest.raises(
  1090. ValueError, match=r'x and y must be array-like with same shape'):
  1091. trifinder.find_many([0], [0, 1])
  1092. def test_qhull_large_offset():
  1093. # github issue 8682.
  1094. x = np.asarray([0, 1, 0, 1, 0.5])
  1095. y = np.asarray([0, 0, 1, 1, 0.5])
  1096. offset = 1e10
  1097. triang = mtri.Triangulation(x, y)
  1098. triang_offset = mtri.Triangulation(x + offset, y + offset)
  1099. assert len(triang.triangles) == len(triang_offset.triangles)
  1100. def test_tricontour_non_finite_z():
  1101. # github issue 10167.
  1102. x = [0, 1, 0, 1]
  1103. y = [0, 0, 1, 1]
  1104. triang = mtri.Triangulation(x, y)
  1105. plt.figure()
  1106. with pytest.raises(ValueError, match='z array must not contain non-finite '
  1107. 'values within the triangulation'):
  1108. plt.tricontourf(triang, [0, 1, 2, np.inf])
  1109. with pytest.raises(ValueError, match='z array must not contain non-finite '
  1110. 'values within the triangulation'):
  1111. plt.tricontourf(triang, [0, 1, 2, -np.inf])
  1112. with pytest.raises(ValueError, match='z array must not contain non-finite '
  1113. 'values within the triangulation'):
  1114. plt.tricontourf(triang, [0, 1, 2, np.nan])
  1115. with pytest.raises(ValueError, match='z must not contain masked points '
  1116. 'within the triangulation'):
  1117. plt.tricontourf(triang, np.ma.array([0, 1, 2, 3], mask=[1, 0, 0, 0]))
  1118. def test_tricontourset_reuse():
  1119. # If TriContourSet returned from one tricontour(f) call is passed as first
  1120. # argument to another the underlying C++ contour generator will be reused.
  1121. x = [0.0, 0.5, 1.0]
  1122. y = [0.0, 1.0, 0.0]
  1123. z = [1.0, 2.0, 3.0]
  1124. fig, ax = plt.subplots()
  1125. tcs1 = ax.tricontourf(x, y, z)
  1126. tcs2 = ax.tricontour(x, y, z)
  1127. assert tcs2._contour_generator != tcs1._contour_generator
  1128. tcs3 = ax.tricontour(tcs1, z)
  1129. assert tcs3._contour_generator == tcs1._contour_generator
  1130. @check_figures_equal()
  1131. def test_triplot_with_ls(fig_test, fig_ref):
  1132. x = [0, 2, 1]
  1133. y = [0, 0, 1]
  1134. data = [[0, 1, 2]]
  1135. fig_test.subplots().triplot(x, y, data, ls='--')
  1136. fig_ref.subplots().triplot(x, y, data, linestyle='--')
  1137. def test_triplot_label():
  1138. x = [0, 2, 1]
  1139. y = [0, 0, 1]
  1140. data = [[0, 1, 2]]
  1141. fig, ax = plt.subplots()
  1142. lines, markers = ax.triplot(x, y, data, label='label')
  1143. handles, labels = ax.get_legend_handles_labels()
  1144. assert labels == ['label']
  1145. assert len(handles) == 1
  1146. assert handles[0] is lines
  1147. def test_tricontour_path():
  1148. x = [0, 4, 4, 0, 2]
  1149. y = [0, 0, 4, 4, 2]
  1150. triang = mtri.Triangulation(x, y)
  1151. _, ax = plt.subplots()
  1152. # Line strip from boundary to boundary
  1153. cs = ax.tricontour(triang, [1, 0, 0, 0, 0], levels=[0.5])
  1154. paths = cs.get_paths()
  1155. assert len(paths) == 1
  1156. expected_vertices = [[2, 0], [1, 1], [0, 2]]
  1157. assert_array_almost_equal(paths[0].vertices, expected_vertices)
  1158. assert_array_equal(paths[0].codes, [1, 2, 2])
  1159. assert_array_almost_equal(
  1160. paths[0].to_polygons(closed_only=False), [expected_vertices])
  1161. # Closed line loop inside domain
  1162. cs = ax.tricontour(triang, [0, 0, 0, 0, 1], levels=[0.5])
  1163. paths = cs.get_paths()
  1164. assert len(paths) == 1
  1165. expected_vertices = [[3, 1], [3, 3], [1, 3], [1, 1], [3, 1]]
  1166. assert_array_almost_equal(paths[0].vertices, expected_vertices)
  1167. assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])
  1168. assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])
  1169. def test_tricontourf_path():
  1170. x = [0, 4, 4, 0, 2]
  1171. y = [0, 0, 4, 4, 2]
  1172. triang = mtri.Triangulation(x, y)
  1173. _, ax = plt.subplots()
  1174. # Polygon inside domain
  1175. cs = ax.tricontourf(triang, [0, 0, 0, 0, 1], levels=[0.5, 1.5])
  1176. paths = cs.get_paths()
  1177. assert len(paths) == 1
  1178. expected_vertices = [[3, 1], [3, 3], [1, 3], [1, 1], [3, 1]]
  1179. assert_array_almost_equal(paths[0].vertices, expected_vertices)
  1180. assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])
  1181. assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])
  1182. # Polygon following boundary and inside domain
  1183. cs = ax.tricontourf(triang, [1, 0, 0, 0, 0], levels=[0.5, 1.5])
  1184. paths = cs.get_paths()
  1185. assert len(paths) == 1
  1186. expected_vertices = [[2, 0], [1, 1], [0, 2], [0, 0], [2, 0]]
  1187. assert_array_almost_equal(paths[0].vertices, expected_vertices)
  1188. assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79])
  1189. assert_array_almost_equal(paths[0].to_polygons(), [expected_vertices])
  1190. # Polygon is outer boundary with hole
  1191. cs = ax.tricontourf(triang, [0, 0, 0, 0, 1], levels=[-0.5, 0.5])
  1192. paths = cs.get_paths()
  1193. assert len(paths) == 1
  1194. expected_vertices = [[0, 0], [4, 0], [4, 4], [0, 4], [0, 0],
  1195. [1, 1], [1, 3], [3, 3], [3, 1], [1, 1]]
  1196. assert_array_almost_equal(paths[0].vertices, expected_vertices)
  1197. assert_array_equal(paths[0].codes, [1, 2, 2, 2, 79, 1, 2, 2, 2, 79])
  1198. assert_array_almost_equal(paths[0].to_polygons(), np.split(expected_vertices, [5]))