test_triangulation.py 45 KB

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