test_triangulation.py 44 KB

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