test_interpnd.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import os
  2. import numpy as np
  3. from numpy.testing import (assert_equal, assert_allclose, assert_almost_equal,
  4. suppress_warnings)
  5. from pytest import raises as assert_raises
  6. import pytest
  7. import scipy.interpolate.interpnd as interpnd
  8. import scipy.spatial._qhull as qhull
  9. import pickle
  10. def data_file(basename):
  11. return os.path.join(os.path.abspath(os.path.dirname(__file__)),
  12. 'data', basename)
  13. class TestLinearNDInterpolation:
  14. def test_smoketest(self):
  15. # Test at single points
  16. x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
  17. dtype=np.double)
  18. y = np.arange(x.shape[0], dtype=np.double)
  19. yi = interpnd.LinearNDInterpolator(x, y)(x)
  20. assert_almost_equal(y, yi)
  21. def test_smoketest_alternate(self):
  22. # Test at single points, alternate calling convention
  23. x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
  24. dtype=np.double)
  25. y = np.arange(x.shape[0], dtype=np.double)
  26. yi = interpnd.LinearNDInterpolator((x[:,0], x[:,1]), y)(x[:,0], x[:,1])
  27. assert_almost_equal(y, yi)
  28. def test_complex_smoketest(self):
  29. # Test at single points
  30. x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
  31. dtype=np.double)
  32. y = np.arange(x.shape[0], dtype=np.double)
  33. y = y - 3j*y
  34. yi = interpnd.LinearNDInterpolator(x, y)(x)
  35. assert_almost_equal(y, yi)
  36. def test_tri_input(self):
  37. # Test at single points
  38. x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
  39. dtype=np.double)
  40. y = np.arange(x.shape[0], dtype=np.double)
  41. y = y - 3j*y
  42. tri = qhull.Delaunay(x)
  43. yi = interpnd.LinearNDInterpolator(tri, y)(x)
  44. assert_almost_equal(y, yi)
  45. def test_square(self):
  46. # Test barycentric interpolation on a square against a manual
  47. # implementation
  48. points = np.array([(0,0), (0,1), (1,1), (1,0)], dtype=np.double)
  49. values = np.array([1., 2., -3., 5.], dtype=np.double)
  50. # NB: assume triangles (0, 1, 3) and (1, 2, 3)
  51. #
  52. # 1----2
  53. # | \ |
  54. # | \ |
  55. # 0----3
  56. def ip(x, y):
  57. t1 = (x + y <= 1)
  58. t2 = ~t1
  59. x1 = x[t1]
  60. y1 = y[t1]
  61. x2 = x[t2]
  62. y2 = y[t2]
  63. z = 0*x
  64. z[t1] = (values[0]*(1 - x1 - y1)
  65. + values[1]*y1
  66. + values[3]*x1)
  67. z[t2] = (values[2]*(x2 + y2 - 1)
  68. + values[1]*(1 - x2)
  69. + values[3]*(1 - y2))
  70. return z
  71. xx, yy = np.broadcast_arrays(np.linspace(0, 1, 14)[:,None],
  72. np.linspace(0, 1, 14)[None,:])
  73. xx = xx.ravel()
  74. yy = yy.ravel()
  75. xi = np.array([xx, yy]).T.copy()
  76. zi = interpnd.LinearNDInterpolator(points, values)(xi)
  77. assert_almost_equal(zi, ip(xx, yy))
  78. def test_smoketest_rescale(self):
  79. # Test at single points
  80. x = np.array([(0, 0), (-5, -5), (-5, 5), (5, 5), (2.5, 3)],
  81. dtype=np.double)
  82. y = np.arange(x.shape[0], dtype=np.double)
  83. yi = interpnd.LinearNDInterpolator(x, y, rescale=True)(x)
  84. assert_almost_equal(y, yi)
  85. def test_square_rescale(self):
  86. # Test barycentric interpolation on a rectangle with rescaling
  87. # agaings the same implementation without rescaling
  88. points = np.array([(0,0), (0,100), (10,100), (10,0)], dtype=np.double)
  89. values = np.array([1., 2., -3., 5.], dtype=np.double)
  90. xx, yy = np.broadcast_arrays(np.linspace(0, 10, 14)[:,None],
  91. np.linspace(0, 100, 14)[None,:])
  92. xx = xx.ravel()
  93. yy = yy.ravel()
  94. xi = np.array([xx, yy]).T.copy()
  95. zi = interpnd.LinearNDInterpolator(points, values)(xi)
  96. zi_rescaled = interpnd.LinearNDInterpolator(points, values,
  97. rescale=True)(xi)
  98. assert_almost_equal(zi, zi_rescaled)
  99. def test_tripoints_input_rescale(self):
  100. # Test at single points
  101. x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
  102. dtype=np.double)
  103. y = np.arange(x.shape[0], dtype=np.double)
  104. y = y - 3j*y
  105. tri = qhull.Delaunay(x)
  106. yi = interpnd.LinearNDInterpolator(tri.points, y)(x)
  107. yi_rescale = interpnd.LinearNDInterpolator(tri.points, y,
  108. rescale=True)(x)
  109. assert_almost_equal(yi, yi_rescale)
  110. def test_tri_input_rescale(self):
  111. # Test at single points
  112. x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
  113. dtype=np.double)
  114. y = np.arange(x.shape[0], dtype=np.double)
  115. y = y - 3j*y
  116. tri = qhull.Delaunay(x)
  117. match = ("Rescaling is not supported when passing a "
  118. "Delaunay triangulation as ``points``.")
  119. with pytest.raises(ValueError, match=match):
  120. interpnd.LinearNDInterpolator(tri, y, rescale=True)(x)
  121. def test_pickle(self):
  122. # Test at single points
  123. np.random.seed(1234)
  124. x = np.random.rand(30, 2)
  125. y = np.random.rand(30) + 1j*np.random.rand(30)
  126. ip = interpnd.LinearNDInterpolator(x, y)
  127. ip2 = pickle.loads(pickle.dumps(ip))
  128. assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5))
  129. class TestEstimateGradients2DGlobal:
  130. def test_smoketest(self):
  131. x = np.array([(0, 0), (0, 2),
  132. (1, 0), (1, 2), (0.25, 0.75), (0.6, 0.8)], dtype=float)
  133. tri = qhull.Delaunay(x)
  134. # Should be exact for linear functions, independent of triangulation
  135. funcs = [
  136. (lambda x, y: 0*x + 1, (0, 0)),
  137. (lambda x, y: 0 + x, (1, 0)),
  138. (lambda x, y: -2 + y, (0, 1)),
  139. (lambda x, y: 3 + 3*x + 14.15*y, (3, 14.15))
  140. ]
  141. for j, (func, grad) in enumerate(funcs):
  142. z = func(x[:,0], x[:,1])
  143. dz = interpnd.estimate_gradients_2d_global(tri, z, tol=1e-6)
  144. assert_equal(dz.shape, (6, 2))
  145. assert_allclose(dz, np.array(grad)[None,:] + 0*dz,
  146. rtol=1e-5, atol=1e-5, err_msg="item %d" % j)
  147. def test_regression_2359(self):
  148. # Check regression --- for certain point sets, gradient
  149. # estimation could end up in an infinite loop
  150. points = np.load(data_file('estimate_gradients_hang.npy'))
  151. values = np.random.rand(points.shape[0])
  152. tri = qhull.Delaunay(points)
  153. # This should not hang
  154. with suppress_warnings() as sup:
  155. sup.filter(interpnd.GradientEstimationWarning,
  156. "Gradient estimation did not converge")
  157. interpnd.estimate_gradients_2d_global(tri, values, maxiter=1)
  158. class TestCloughTocher2DInterpolator:
  159. def _check_accuracy(self, func, x=None, tol=1e-6, alternate=False, rescale=False, **kw):
  160. np.random.seed(1234)
  161. if x is None:
  162. x = np.array([(0, 0), (0, 1),
  163. (1, 0), (1, 1), (0.25, 0.75), (0.6, 0.8),
  164. (0.5, 0.2)],
  165. dtype=float)
  166. if not alternate:
  167. ip = interpnd.CloughTocher2DInterpolator(x, func(x[:,0], x[:,1]),
  168. tol=1e-6, rescale=rescale)
  169. else:
  170. ip = interpnd.CloughTocher2DInterpolator((x[:,0], x[:,1]),
  171. func(x[:,0], x[:,1]),
  172. tol=1e-6, rescale=rescale)
  173. p = np.random.rand(50, 2)
  174. if not alternate:
  175. a = ip(p)
  176. else:
  177. a = ip(p[:,0], p[:,1])
  178. b = func(p[:,0], p[:,1])
  179. try:
  180. assert_allclose(a, b, **kw)
  181. except AssertionError:
  182. print("_check_accuracy: abs(a-b):", abs(a - b))
  183. print("ip.grad:", ip.grad)
  184. raise
  185. def test_linear_smoketest(self):
  186. # Should be exact for linear functions, independent of triangulation
  187. funcs = [
  188. lambda x, y: 0*x + 1,
  189. lambda x, y: 0 + x,
  190. lambda x, y: -2 + y,
  191. lambda x, y: 3 + 3*x + 14.15*y,
  192. ]
  193. for j, func in enumerate(funcs):
  194. self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
  195. err_msg="Function %d" % j)
  196. self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
  197. alternate=True,
  198. err_msg="Function (alternate) %d" % j)
  199. # check rescaling
  200. self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
  201. err_msg="Function (rescaled) %d" % j, rescale=True)
  202. self._check_accuracy(func, tol=1e-13, atol=1e-7, rtol=1e-7,
  203. alternate=True, rescale=True,
  204. err_msg="Function (alternate, rescaled) %d" % j)
  205. def test_quadratic_smoketest(self):
  206. # Should be reasonably accurate for quadratic functions
  207. funcs = [
  208. lambda x, y: x**2,
  209. lambda x, y: y**2,
  210. lambda x, y: x**2 - y**2,
  211. lambda x, y: x*y,
  212. ]
  213. for j, func in enumerate(funcs):
  214. self._check_accuracy(func, tol=1e-9, atol=0.22, rtol=0,
  215. err_msg="Function %d" % j)
  216. self._check_accuracy(func, tol=1e-9, atol=0.22, rtol=0,
  217. err_msg="Function %d" % j, rescale=True)
  218. def test_tri_input(self):
  219. # Test at single points
  220. x = np.array([(0,0), (-0.5,-0.5), (-0.5,0.5), (0.5, 0.5), (0.25, 0.3)],
  221. dtype=np.double)
  222. y = np.arange(x.shape[0], dtype=np.double)
  223. y = y - 3j*y
  224. tri = qhull.Delaunay(x)
  225. yi = interpnd.CloughTocher2DInterpolator(tri, y)(x)
  226. assert_almost_equal(y, yi)
  227. def test_tri_input_rescale(self):
  228. # Test at single points
  229. x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
  230. dtype=np.double)
  231. y = np.arange(x.shape[0], dtype=np.double)
  232. y = y - 3j*y
  233. tri = qhull.Delaunay(x)
  234. match = ("Rescaling is not supported when passing a "
  235. "Delaunay triangulation as ``points``.")
  236. with pytest.raises(ValueError, match=match):
  237. interpnd.CloughTocher2DInterpolator(tri, y, rescale=True)(x)
  238. def test_tripoints_input_rescale(self):
  239. # Test at single points
  240. x = np.array([(0,0), (-5,-5), (-5,5), (5, 5), (2.5, 3)],
  241. dtype=np.double)
  242. y = np.arange(x.shape[0], dtype=np.double)
  243. y = y - 3j*y
  244. tri = qhull.Delaunay(x)
  245. yi = interpnd.CloughTocher2DInterpolator(tri.points, y)(x)
  246. yi_rescale = interpnd.CloughTocher2DInterpolator(tri.points, y, rescale=True)(x)
  247. assert_almost_equal(yi, yi_rescale)
  248. def test_dense(self):
  249. # Should be more accurate for dense meshes
  250. funcs = [
  251. lambda x, y: x**2,
  252. lambda x, y: y**2,
  253. lambda x, y: x**2 - y**2,
  254. lambda x, y: x*y,
  255. lambda x, y: np.cos(2*np.pi*x)*np.sin(2*np.pi*y)
  256. ]
  257. np.random.seed(4321) # use a different seed than the check!
  258. grid = np.r_[np.array([(0,0), (0,1), (1,0), (1,1)], dtype=float),
  259. np.random.rand(30*30, 2)]
  260. for j, func in enumerate(funcs):
  261. self._check_accuracy(func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2,
  262. err_msg="Function %d" % j)
  263. self._check_accuracy(func, x=grid, tol=1e-9, atol=5e-3, rtol=1e-2,
  264. err_msg="Function %d" % j, rescale=True)
  265. def test_wrong_ndim(self):
  266. x = np.random.randn(30, 3)
  267. y = np.random.randn(30)
  268. assert_raises(ValueError, interpnd.CloughTocher2DInterpolator, x, y)
  269. def test_pickle(self):
  270. # Test at single points
  271. np.random.seed(1234)
  272. x = np.random.rand(30, 2)
  273. y = np.random.rand(30) + 1j*np.random.rand(30)
  274. ip = interpnd.CloughTocher2DInterpolator(x, y)
  275. ip2 = pickle.loads(pickle.dumps(ip))
  276. assert_almost_equal(ip(0.5, 0.5), ip2(0.5, 0.5))
  277. def test_boundary_tri_symmetry(self):
  278. # Interpolation at neighbourless triangles should retain
  279. # symmetry with mirroring the triangle.
  280. # Equilateral triangle
  281. points = np.array([(0, 0), (1, 0), (0.5, np.sqrt(3)/2)])
  282. values = np.array([1, 0, 0])
  283. ip = interpnd.CloughTocher2DInterpolator(points, values)
  284. # Set gradient to zero at vertices
  285. ip.grad[...] = 0
  286. # Interpolation should be symmetric vs. bisector
  287. alpha = 0.3
  288. p1 = np.array([0.5 * np.cos(alpha), 0.5 * np.sin(alpha)])
  289. p2 = np.array([0.5 * np.cos(np.pi/3 - alpha), 0.5 * np.sin(np.pi/3 - alpha)])
  290. v1 = ip(p1)
  291. v2 = ip(p2)
  292. assert_allclose(v1, v2)
  293. # ... and affine invariant
  294. np.random.seed(1)
  295. A = np.random.randn(2, 2)
  296. b = np.random.randn(2)
  297. points = A.dot(points.T).T + b[None,:]
  298. p1 = A.dot(p1) + b
  299. p2 = A.dot(p2) + b
  300. ip = interpnd.CloughTocher2DInterpolator(points, values)
  301. ip.grad[...] = 0
  302. w1 = ip(p1)
  303. w2 = ip(p2)
  304. assert_allclose(w1, v1)
  305. assert_allclose(w2, v2)