test_bsplines.py 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639
  1. import numpy as np
  2. from numpy.testing import assert_equal, assert_allclose, assert_
  3. from pytest import raises as assert_raises
  4. import pytest
  5. from scipy.interpolate import (BSpline, BPoly, PPoly, make_interp_spline,
  6. make_lsq_spline, _bspl, splev, splrep, splprep,
  7. splder, splantider, sproot, splint, insert,
  8. CubicSpline, make_smoothing_spline)
  9. import scipy.linalg as sl
  10. from scipy.interpolate._bsplines import (_not_a_knot, _augknt,
  11. _woodbury_algorithm, _periodic_knots,
  12. _make_interp_per_full_matr)
  13. import scipy.interpolate._fitpack_impl as _impl
  14. import os
  15. class TestBSpline:
  16. def test_ctor(self):
  17. # knots should be an ordered 1-D array of finite real numbers
  18. assert_raises((TypeError, ValueError), BSpline,
  19. **dict(t=[1, 1.j], c=[1.], k=0))
  20. with np.errstate(invalid='ignore'):
  21. assert_raises(ValueError, BSpline, **dict(t=[1, np.nan], c=[1.], k=0))
  22. assert_raises(ValueError, BSpline, **dict(t=[1, np.inf], c=[1.], k=0))
  23. assert_raises(ValueError, BSpline, **dict(t=[1, -1], c=[1.], k=0))
  24. assert_raises(ValueError, BSpline, **dict(t=[[1], [1]], c=[1.], k=0))
  25. # for n+k+1 knots and degree k need at least n coefficients
  26. assert_raises(ValueError, BSpline, **dict(t=[0, 1, 2], c=[1], k=0))
  27. assert_raises(ValueError, BSpline,
  28. **dict(t=[0, 1, 2, 3, 4], c=[1., 1.], k=2))
  29. # non-integer orders
  30. assert_raises(TypeError, BSpline,
  31. **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k="cubic"))
  32. assert_raises(TypeError, BSpline,
  33. **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k=2.5))
  34. # basic interval cannot have measure zero (here: [1..1])
  35. assert_raises(ValueError, BSpline,
  36. **dict(t=[0., 0, 1, 1, 2, 3], c=[1., 1, 1], k=2))
  37. # tck vs self.tck
  38. n, k = 11, 3
  39. t = np.arange(n+k+1)
  40. c = np.random.random(n)
  41. b = BSpline(t, c, k)
  42. assert_allclose(t, b.t)
  43. assert_allclose(c, b.c)
  44. assert_equal(k, b.k)
  45. def test_tck(self):
  46. b = _make_random_spline()
  47. tck = b.tck
  48. assert_allclose(b.t, tck[0], atol=1e-15, rtol=1e-15)
  49. assert_allclose(b.c, tck[1], atol=1e-15, rtol=1e-15)
  50. assert_equal(b.k, tck[2])
  51. # b.tck is read-only
  52. with pytest.raises(AttributeError):
  53. b.tck = 'foo'
  54. def test_degree_0(self):
  55. xx = np.linspace(0, 1, 10)
  56. b = BSpline(t=[0, 1], c=[3.], k=0)
  57. assert_allclose(b(xx), 3)
  58. b = BSpline(t=[0, 0.35, 1], c=[3, 4], k=0)
  59. assert_allclose(b(xx), np.where(xx < 0.35, 3, 4))
  60. def test_degree_1(self):
  61. t = [0, 1, 2, 3, 4]
  62. c = [1, 2, 3]
  63. k = 1
  64. b = BSpline(t, c, k)
  65. x = np.linspace(1, 3, 50)
  66. assert_allclose(c[0]*B_012(x) + c[1]*B_012(x-1) + c[2]*B_012(x-2),
  67. b(x), atol=1e-14)
  68. assert_allclose(splev(x, (t, c, k)), b(x), atol=1e-14)
  69. def test_bernstein(self):
  70. # a special knot vector: Bernstein polynomials
  71. k = 3
  72. t = np.asarray([0]*(k+1) + [1]*(k+1))
  73. c = np.asarray([1., 2., 3., 4.])
  74. bp = BPoly(c.reshape(-1, 1), [0, 1])
  75. bspl = BSpline(t, c, k)
  76. xx = np.linspace(-1., 2., 10)
  77. assert_allclose(bp(xx, extrapolate=True),
  78. bspl(xx, extrapolate=True), atol=1e-14)
  79. assert_allclose(splev(xx, (t, c, k)),
  80. bspl(xx), atol=1e-14)
  81. def test_rndm_naive_eval(self):
  82. # test random coefficient spline *on the base interval*,
  83. # t[k] <= x < t[-k-1]
  84. b = _make_random_spline()
  85. t, c, k = b.tck
  86. xx = np.linspace(t[k], t[-k-1], 50)
  87. y_b = b(xx)
  88. y_n = [_naive_eval(x, t, c, k) for x in xx]
  89. assert_allclose(y_b, y_n, atol=1e-14)
  90. y_n2 = [_naive_eval_2(x, t, c, k) for x in xx]
  91. assert_allclose(y_b, y_n2, atol=1e-14)
  92. def test_rndm_splev(self):
  93. b = _make_random_spline()
  94. t, c, k = b.tck
  95. xx = np.linspace(t[k], t[-k-1], 50)
  96. assert_allclose(b(xx), splev(xx, (t, c, k)), atol=1e-14)
  97. def test_rndm_splrep(self):
  98. np.random.seed(1234)
  99. x = np.sort(np.random.random(20))
  100. y = np.random.random(20)
  101. tck = splrep(x, y)
  102. b = BSpline(*tck)
  103. t, k = b.t, b.k
  104. xx = np.linspace(t[k], t[-k-1], 80)
  105. assert_allclose(b(xx), splev(xx, tck), atol=1e-14)
  106. def test_rndm_unity(self):
  107. b = _make_random_spline()
  108. b.c = np.ones_like(b.c)
  109. xx = np.linspace(b.t[b.k], b.t[-b.k-1], 100)
  110. assert_allclose(b(xx), 1.)
  111. def test_vectorization(self):
  112. n, k = 22, 3
  113. t = np.sort(np.random.random(n))
  114. c = np.random.random(size=(n, 6, 7))
  115. b = BSpline(t, c, k)
  116. tm, tp = t[k], t[-k-1]
  117. xx = tm + (tp - tm) * np.random.random((3, 4, 5))
  118. assert_equal(b(xx).shape, (3, 4, 5, 6, 7))
  119. def test_len_c(self):
  120. # for n+k+1 knots, only first n coefs are used.
  121. # and BTW this is consistent with FITPACK
  122. n, k = 33, 3
  123. t = np.sort(np.random.random(n+k+1))
  124. c = np.random.random(n)
  125. # pad coefficients with random garbage
  126. c_pad = np.r_[c, np.random.random(k+1)]
  127. b, b_pad = BSpline(t, c, k), BSpline(t, c_pad, k)
  128. dt = t[-1] - t[0]
  129. xx = np.linspace(t[0] - dt, t[-1] + dt, 50)
  130. assert_allclose(b(xx), b_pad(xx), atol=1e-14)
  131. assert_allclose(b(xx), splev(xx, (t, c, k)), atol=1e-14)
  132. assert_allclose(b(xx), splev(xx, (t, c_pad, k)), atol=1e-14)
  133. def test_endpoints(self):
  134. # base interval is closed
  135. b = _make_random_spline()
  136. t, _, k = b.tck
  137. tm, tp = t[k], t[-k-1]
  138. for extrap in (True, False):
  139. assert_allclose(b([tm, tp], extrap),
  140. b([tm + 1e-10, tp - 1e-10], extrap), atol=1e-9)
  141. def test_continuity(self):
  142. # assert continuity at internal knots
  143. b = _make_random_spline()
  144. t, _, k = b.tck
  145. assert_allclose(b(t[k+1:-k-1] - 1e-10), b(t[k+1:-k-1] + 1e-10),
  146. atol=1e-9)
  147. def test_extrap(self):
  148. b = _make_random_spline()
  149. t, c, k = b.tck
  150. dt = t[-1] - t[0]
  151. xx = np.linspace(t[k] - dt, t[-k-1] + dt, 50)
  152. mask = (t[k] < xx) & (xx < t[-k-1])
  153. # extrap has no effect within the base interval
  154. assert_allclose(b(xx[mask], extrapolate=True),
  155. b(xx[mask], extrapolate=False))
  156. # extrapolated values agree with FITPACK
  157. assert_allclose(b(xx, extrapolate=True),
  158. splev(xx, (t, c, k), ext=0))
  159. def test_default_extrap(self):
  160. # BSpline defaults to extrapolate=True
  161. b = _make_random_spline()
  162. t, _, k = b.tck
  163. xx = [t[0] - 1, t[-1] + 1]
  164. yy = b(xx)
  165. assert_(not np.all(np.isnan(yy)))
  166. def test_periodic_extrap(self):
  167. np.random.seed(1234)
  168. t = np.sort(np.random.random(8))
  169. c = np.random.random(4)
  170. k = 3
  171. b = BSpline(t, c, k, extrapolate='periodic')
  172. n = t.size - (k + 1)
  173. dt = t[-1] - t[0]
  174. xx = np.linspace(t[k] - dt, t[n] + dt, 50)
  175. xy = t[k] + (xx - t[k]) % (t[n] - t[k])
  176. assert_allclose(b(xx), splev(xy, (t, c, k)))
  177. # Direct check
  178. xx = [-1, 0, 0.5, 1]
  179. xy = t[k] + (xx - t[k]) % (t[n] - t[k])
  180. assert_equal(b(xx, extrapolate='periodic'), b(xy, extrapolate=True))
  181. def test_ppoly(self):
  182. b = _make_random_spline()
  183. t, c, k = b.tck
  184. pp = PPoly.from_spline((t, c, k))
  185. xx = np.linspace(t[k], t[-k], 100)
  186. assert_allclose(b(xx), pp(xx), atol=1e-14, rtol=1e-14)
  187. def test_derivative_rndm(self):
  188. b = _make_random_spline()
  189. t, c, k = b.tck
  190. xx = np.linspace(t[0], t[-1], 50)
  191. xx = np.r_[xx, t]
  192. for der in range(1, k+1):
  193. yd = splev(xx, (t, c, k), der=der)
  194. assert_allclose(yd, b(xx, nu=der), atol=1e-14)
  195. # higher derivatives all vanish
  196. assert_allclose(b(xx, nu=k+1), 0, atol=1e-14)
  197. def test_derivative_jumps(self):
  198. # example from de Boor, Chap IX, example (24)
  199. # NB: knots augmented & corresp coefs are zeroed out
  200. # in agreement with the convention (29)
  201. k = 2
  202. t = [-1, -1, 0, 1, 1, 3, 4, 6, 6, 6, 7, 7]
  203. np.random.seed(1234)
  204. c = np.r_[0, 0, np.random.random(5), 0, 0]
  205. b = BSpline(t, c, k)
  206. # b is continuous at x != 6 (triple knot)
  207. x = np.asarray([1, 3, 4, 6])
  208. assert_allclose(b(x[x != 6] - 1e-10),
  209. b(x[x != 6] + 1e-10))
  210. assert_(not np.allclose(b(6.-1e-10), b(6+1e-10)))
  211. # 1st derivative jumps at double knots, 1 & 6:
  212. x0 = np.asarray([3, 4])
  213. assert_allclose(b(x0 - 1e-10, nu=1),
  214. b(x0 + 1e-10, nu=1))
  215. x1 = np.asarray([1, 6])
  216. assert_(not np.all(np.allclose(b(x1 - 1e-10, nu=1),
  217. b(x1 + 1e-10, nu=1))))
  218. # 2nd derivative is not guaranteed to be continuous either
  219. assert_(not np.all(np.allclose(b(x - 1e-10, nu=2),
  220. b(x + 1e-10, nu=2))))
  221. def test_basis_element_quadratic(self):
  222. xx = np.linspace(-1, 4, 20)
  223. b = BSpline.basis_element(t=[0, 1, 2, 3])
  224. assert_allclose(b(xx),
  225. splev(xx, (b.t, b.c, b.k)), atol=1e-14)
  226. assert_allclose(b(xx),
  227. B_0123(xx), atol=1e-14)
  228. b = BSpline.basis_element(t=[0, 1, 1, 2])
  229. xx = np.linspace(0, 2, 10)
  230. assert_allclose(b(xx),
  231. np.where(xx < 1, xx*xx, (2.-xx)**2), atol=1e-14)
  232. def test_basis_element_rndm(self):
  233. b = _make_random_spline()
  234. t, c, k = b.tck
  235. xx = np.linspace(t[k], t[-k-1], 20)
  236. assert_allclose(b(xx), _sum_basis_elements(xx, t, c, k), atol=1e-14)
  237. def test_cmplx(self):
  238. b = _make_random_spline()
  239. t, c, k = b.tck
  240. cc = c * (1. + 3.j)
  241. b = BSpline(t, cc, k)
  242. b_re = BSpline(t, b.c.real, k)
  243. b_im = BSpline(t, b.c.imag, k)
  244. xx = np.linspace(t[k], t[-k-1], 20)
  245. assert_allclose(b(xx).real, b_re(xx), atol=1e-14)
  246. assert_allclose(b(xx).imag, b_im(xx), atol=1e-14)
  247. def test_nan(self):
  248. # nan in, nan out.
  249. b = BSpline.basis_element([0, 1, 1, 2])
  250. assert_(np.isnan(b(np.nan)))
  251. def test_derivative_method(self):
  252. b = _make_random_spline(k=5)
  253. t, c, k = b.tck
  254. b0 = BSpline(t, c, k)
  255. xx = np.linspace(t[k], t[-k-1], 20)
  256. for j in range(1, k):
  257. b = b.derivative()
  258. assert_allclose(b0(xx, j), b(xx), atol=1e-12, rtol=1e-12)
  259. def test_antiderivative_method(self):
  260. b = _make_random_spline()
  261. t, c, k = b.tck
  262. xx = np.linspace(t[k], t[-k-1], 20)
  263. assert_allclose(b.antiderivative().derivative()(xx),
  264. b(xx), atol=1e-14, rtol=1e-14)
  265. # repeat with N-D array for c
  266. c = np.c_[c, c, c]
  267. c = np.dstack((c, c))
  268. b = BSpline(t, c, k)
  269. assert_allclose(b.antiderivative().derivative()(xx),
  270. b(xx), atol=1e-14, rtol=1e-14)
  271. def test_integral(self):
  272. b = BSpline.basis_element([0, 1, 2]) # x for x < 1 else 2 - x
  273. assert_allclose(b.integrate(0, 1), 0.5)
  274. assert_allclose(b.integrate(1, 0), -1 * 0.5)
  275. assert_allclose(b.integrate(1, 0), -0.5)
  276. # extrapolate or zeros outside of [0, 2]; default is yes
  277. assert_allclose(b.integrate(-1, 1), 0)
  278. assert_allclose(b.integrate(-1, 1, extrapolate=True), 0)
  279. assert_allclose(b.integrate(-1, 1, extrapolate=False), 0.5)
  280. assert_allclose(b.integrate(1, -1, extrapolate=False), -1 * 0.5)
  281. # Test ``_fitpack._splint()``
  282. assert_allclose(b.integrate(1, -1, extrapolate=False),
  283. _impl.splint(1, -1, b.tck))
  284. # Test ``extrapolate='periodic'``.
  285. b.extrapolate = 'periodic'
  286. i = b.antiderivative()
  287. period_int = i(2) - i(0)
  288. assert_allclose(b.integrate(0, 2), period_int)
  289. assert_allclose(b.integrate(2, 0), -1 * period_int)
  290. assert_allclose(b.integrate(-9, -7), period_int)
  291. assert_allclose(b.integrate(-8, -4), 2 * period_int)
  292. assert_allclose(b.integrate(0.5, 1.5), i(1.5) - i(0.5))
  293. assert_allclose(b.integrate(1.5, 3), i(1) - i(0) + i(2) - i(1.5))
  294. assert_allclose(b.integrate(1.5 + 12, 3 + 12),
  295. i(1) - i(0) + i(2) - i(1.5))
  296. assert_allclose(b.integrate(1.5, 3 + 12),
  297. i(1) - i(0) + i(2) - i(1.5) + 6 * period_int)
  298. assert_allclose(b.integrate(0, -1), i(0) - i(1))
  299. assert_allclose(b.integrate(-9, -10), i(0) - i(1))
  300. assert_allclose(b.integrate(0, -9), i(1) - i(2) - 4 * period_int)
  301. def test_integrate_ppoly(self):
  302. # test .integrate method to be consistent with PPoly.integrate
  303. x = [0, 1, 2, 3, 4]
  304. b = make_interp_spline(x, x)
  305. b.extrapolate = 'periodic'
  306. p = PPoly.from_spline(b)
  307. for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]:
  308. assert_allclose(b.integrate(x0, x1),
  309. p.integrate(x0, x1))
  310. def test_subclassing(self):
  311. # classmethods should not decay to the base class
  312. class B(BSpline):
  313. pass
  314. b = B.basis_element([0, 1, 2, 2])
  315. assert_equal(b.__class__, B)
  316. assert_equal(b.derivative().__class__, B)
  317. assert_equal(b.antiderivative().__class__, B)
  318. @pytest.mark.parametrize('axis', range(-4, 4))
  319. def test_axis(self, axis):
  320. n, k = 22, 3
  321. t = np.linspace(0, 1, n + k + 1)
  322. sh = [6, 7, 8]
  323. # We need the positive axis for some of the indexing and slices used
  324. # in this test.
  325. pos_axis = axis % 4
  326. sh.insert(pos_axis, n) # [22, 6, 7, 8] etc
  327. c = np.random.random(size=sh)
  328. b = BSpline(t, c, k, axis=axis)
  329. assert_equal(b.c.shape,
  330. [sh[pos_axis],] + sh[:pos_axis] + sh[pos_axis+1:])
  331. xp = np.random.random((3, 4, 5))
  332. assert_equal(b(xp).shape,
  333. sh[:pos_axis] + list(xp.shape) + sh[pos_axis+1:])
  334. # -c.ndim <= axis < c.ndim
  335. for ax in [-c.ndim - 1, c.ndim]:
  336. assert_raises(np.AxisError, BSpline,
  337. **dict(t=t, c=c, k=k, axis=ax))
  338. # derivative, antiderivative keeps the axis
  339. for b1 in [BSpline(t, c, k, axis=axis).derivative(),
  340. BSpline(t, c, k, axis=axis).derivative(2),
  341. BSpline(t, c, k, axis=axis).antiderivative(),
  342. BSpline(t, c, k, axis=axis).antiderivative(2)]:
  343. assert_equal(b1.axis, b.axis)
  344. def test_neg_axis(self):
  345. k = 2
  346. t = [0, 1, 2, 3, 4, 5, 6]
  347. c = np.array([[-1, 2, 0, -1], [2, 0, -3, 1]])
  348. spl = BSpline(t, c, k, axis=-1)
  349. spl0 = BSpline(t, c[0], k)
  350. spl1 = BSpline(t, c[1], k)
  351. assert_equal(spl(2.5), [spl0(2.5), spl1(2.5)])
  352. def test_design_matrix_bc_types(self):
  353. '''
  354. Splines with different boundary conditions are built on different
  355. types of vectors of knots. As far as design matrix depends only on
  356. vector of knots, `k` and `x` it is useful to make tests for different
  357. boundary conditions (and as following different vectors of knots).
  358. '''
  359. def run_design_matrix_tests(n, k, bc_type):
  360. '''
  361. To avoid repetition of code the following function is provided.
  362. '''
  363. np.random.seed(1234)
  364. x = np.sort(np.random.random_sample(n) * 40 - 20)
  365. y = np.random.random_sample(n) * 40 - 20
  366. if bc_type == "periodic":
  367. y[0] = y[-1]
  368. bspl = make_interp_spline(x, y, k=k, bc_type=bc_type)
  369. c = np.eye(len(bspl.t) - k - 1)
  370. des_matr_def = BSpline(bspl.t, c, k)(x)
  371. des_matr_csr = BSpline.design_matrix(x,
  372. bspl.t,
  373. k).toarray()
  374. assert_allclose(des_matr_csr @ bspl.c, y, atol=1e-14)
  375. assert_allclose(des_matr_def, des_matr_csr, atol=1e-14)
  376. # "clamped" and "natural" work only with `k = 3`
  377. n = 11
  378. k = 3
  379. for bc in ["clamped", "natural"]:
  380. run_design_matrix_tests(n, k, bc)
  381. # "not-a-knot" works with odd `k`
  382. for k in range(3, 8, 2):
  383. run_design_matrix_tests(n, k, "not-a-knot")
  384. # "periodic" works with any `k` (even more than `n`)
  385. n = 5 # smaller `n` to test `k > n` case
  386. for k in range(2, 7):
  387. run_design_matrix_tests(n, k, "periodic")
  388. @pytest.mark.parametrize('extrapolate', [False, True, 'periodic'])
  389. @pytest.mark.parametrize('degree', range(5))
  390. def test_design_matrix_same_as_BSpline_call(self, extrapolate, degree):
  391. """Test that design_matrix(x) is equivalent to BSpline(..)(x)."""
  392. np.random.seed(1234)
  393. x = np.random.random_sample(10 * (degree + 1))
  394. xmin, xmax = np.amin(x), np.amax(x)
  395. k = degree
  396. t = np.r_[np.linspace(xmin - 2, xmin - 1, degree),
  397. np.linspace(xmin, xmax, 2 * (degree + 1)),
  398. np.linspace(xmax + 1, xmax + 2, degree)]
  399. c = np.eye(len(t) - k - 1)
  400. bspline = BSpline(t, c, k, extrapolate)
  401. assert_allclose(
  402. bspline(x), BSpline.design_matrix(x, t, k, extrapolate).toarray()
  403. )
  404. # extrapolation regime
  405. x = np.array([xmin - 10, xmin - 1, xmax + 1.5, xmax + 10])
  406. if not extrapolate:
  407. with pytest.raises(ValueError):
  408. BSpline.design_matrix(x, t, k, extrapolate)
  409. else:
  410. assert_allclose(
  411. bspline(x),
  412. BSpline.design_matrix(x, t, k, extrapolate).toarray()
  413. )
  414. def test_design_matrix_x_shapes(self):
  415. # test for different `x` shapes
  416. np.random.seed(1234)
  417. n = 10
  418. k = 3
  419. x = np.sort(np.random.random_sample(n) * 40 - 20)
  420. y = np.random.random_sample(n) * 40 - 20
  421. bspl = make_interp_spline(x, y, k=k)
  422. for i in range(1, 4):
  423. xc = x[:i]
  424. yc = y[:i]
  425. des_matr_csr = BSpline.design_matrix(xc,
  426. bspl.t,
  427. k).toarray()
  428. assert_allclose(des_matr_csr @ bspl.c, yc, atol=1e-14)
  429. def test_design_matrix_t_shapes(self):
  430. # test for minimal possible `t` shape
  431. t = [1., 1., 1., 2., 3., 4., 4., 4.]
  432. des_matr = BSpline.design_matrix(2., t, 3).toarray()
  433. assert_allclose(des_matr,
  434. [[0.25, 0.58333333, 0.16666667, 0.]],
  435. atol=1e-14)
  436. def test_design_matrix_asserts(self):
  437. np.random.seed(1234)
  438. n = 10
  439. k = 3
  440. x = np.sort(np.random.random_sample(n) * 40 - 20)
  441. y = np.random.random_sample(n) * 40 - 20
  442. bspl = make_interp_spline(x, y, k=k)
  443. # invalid vector of knots (should be a 1D non-descending array)
  444. # here the actual vector of knots is reversed, so it is invalid
  445. with assert_raises(ValueError):
  446. BSpline.design_matrix(x, bspl.t[::-1], k)
  447. k = 2
  448. t = [0., 1., 2., 3., 4., 5.]
  449. x = [1., 2., 3., 4.]
  450. # out of bounds
  451. with assert_raises(ValueError):
  452. BSpline.design_matrix(x, t, k)
  453. @pytest.mark.parametrize('bc_type', ['natural', 'clamped',
  454. 'periodic', 'not-a-knot'])
  455. def test_from_power_basis(self, bc_type):
  456. np.random.seed(1234)
  457. x = np.sort(np.random.random(20))
  458. y = np.random.random(20)
  459. if bc_type == 'periodic':
  460. y[-1] = y[0]
  461. cb = CubicSpline(x, y, bc_type=bc_type)
  462. bspl = BSpline.from_power_basis(cb, bc_type=bc_type)
  463. xx = np.linspace(0, 1, 20)
  464. assert_allclose(cb(xx), bspl(xx), atol=1e-15)
  465. bspl_new = make_interp_spline(x, y, bc_type=bc_type)
  466. assert_allclose(bspl.c, bspl_new.c, atol=1e-15)
  467. @pytest.mark.parametrize('bc_type', ['natural', 'clamped',
  468. 'periodic', 'not-a-knot'])
  469. def test_from_power_basis_complex(self, bc_type):
  470. np.random.seed(1234)
  471. x = np.sort(np.random.random(20))
  472. y = np.random.random(20) + np.random.random(20) * 1j
  473. if bc_type == 'periodic':
  474. y[-1] = y[0]
  475. cb = CubicSpline(x, y, bc_type=bc_type)
  476. bspl = BSpline.from_power_basis(cb, bc_type=bc_type)
  477. bspl_new_real = make_interp_spline(x, y.real, bc_type=bc_type)
  478. bspl_new_imag = make_interp_spline(x, y.imag, bc_type=bc_type)
  479. assert_equal(bspl.c.dtype, (bspl_new_real.c
  480. + 1j * bspl_new_imag.c).dtype)
  481. assert_allclose(bspl.c, bspl_new_real.c
  482. + 1j * bspl_new_imag.c, atol=1e-15)
  483. def test_from_power_basis_exmp(self):
  484. '''
  485. For x = [0, 1, 2, 3, 4] and y = [1, 1, 1, 1, 1]
  486. the coefficients of Cubic Spline in the power basis:
  487. $[[0, 0, 0, 0, 0],\\$
  488. $[0, 0, 0, 0, 0],\\$
  489. $[0, 0, 0, 0, 0],\\$
  490. $[1, 1, 1, 1, 1]]$
  491. It could be shown explicitly that coefficients of the interpolating
  492. function in B-spline basis are c = [1, 1, 1, 1, 1, 1, 1]
  493. '''
  494. x = np.array([0, 1, 2, 3, 4])
  495. y = np.array([1, 1, 1, 1, 1])
  496. bspl = BSpline.from_power_basis(CubicSpline(x, y, bc_type='natural'),
  497. bc_type='natural')
  498. assert_allclose(bspl.c, [1, 1, 1, 1, 1, 1, 1], atol=1e-15)
  499. def test_knots_multiplicity():
  500. # Take a spline w/ random coefficients, throw in knots of varying
  501. # multiplicity.
  502. def check_splev(b, j, der=0, atol=1e-14, rtol=1e-14):
  503. # check evaluations against FITPACK, incl extrapolations
  504. t, c, k = b.tck
  505. x = np.unique(t)
  506. x = np.r_[t[0]-0.1, 0.5*(x[1:] + x[:1]), t[-1]+0.1]
  507. assert_allclose(splev(x, (t, c, k), der), b(x, der),
  508. atol=atol, rtol=rtol, err_msg='der = %s k = %s' % (der, b.k))
  509. # test loop itself
  510. # [the index `j` is for interpreting the traceback in case of a failure]
  511. for k in [1, 2, 3, 4, 5]:
  512. b = _make_random_spline(k=k)
  513. for j, b1 in enumerate(_make_multiples(b)):
  514. check_splev(b1, j)
  515. for der in range(1, k+1):
  516. check_splev(b1, j, der, 1e-12, 1e-12)
  517. ### stolen from @pv, verbatim
  518. def _naive_B(x, k, i, t):
  519. """
  520. Naive way to compute B-spline basis functions. Useful only for testing!
  521. computes B(x; t[i],..., t[i+k+1])
  522. """
  523. if k == 0:
  524. return 1.0 if t[i] <= x < t[i+1] else 0.0
  525. if t[i+k] == t[i]:
  526. c1 = 0.0
  527. else:
  528. c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t)
  529. if t[i+k+1] == t[i+1]:
  530. c2 = 0.0
  531. else:
  532. c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t)
  533. return (c1 + c2)
  534. ### stolen from @pv, verbatim
  535. def _naive_eval(x, t, c, k):
  536. """
  537. Naive B-spline evaluation. Useful only for testing!
  538. """
  539. if x == t[k]:
  540. i = k
  541. else:
  542. i = np.searchsorted(t, x) - 1
  543. assert t[i] <= x <= t[i+1]
  544. assert i >= k and i < len(t) - k
  545. return sum(c[i-j] * _naive_B(x, k, i-j, t) for j in range(0, k+1))
  546. def _naive_eval_2(x, t, c, k):
  547. """Naive B-spline evaluation, another way."""
  548. n = len(t) - (k+1)
  549. assert n >= k+1
  550. assert len(c) >= n
  551. assert t[k] <= x <= t[n]
  552. return sum(c[i] * _naive_B(x, k, i, t) for i in range(n))
  553. def _sum_basis_elements(x, t, c, k):
  554. n = len(t) - (k+1)
  555. assert n >= k+1
  556. assert len(c) >= n
  557. s = 0.
  558. for i in range(n):
  559. b = BSpline.basis_element(t[i:i+k+2], extrapolate=False)(x)
  560. s += c[i] * np.nan_to_num(b) # zero out out-of-bounds elements
  561. return s
  562. def B_012(x):
  563. """ A linear B-spline function B(x | 0, 1, 2)."""
  564. x = np.atleast_1d(x)
  565. return np.piecewise(x, [(x < 0) | (x > 2),
  566. (x >= 0) & (x < 1),
  567. (x >= 1) & (x <= 2)],
  568. [lambda x: 0., lambda x: x, lambda x: 2.-x])
  569. def B_0123(x, der=0):
  570. """A quadratic B-spline function B(x | 0, 1, 2, 3)."""
  571. x = np.atleast_1d(x)
  572. conds = [x < 1, (x > 1) & (x < 2), x > 2]
  573. if der == 0:
  574. funcs = [lambda x: x*x/2.,
  575. lambda x: 3./4 - (x-3./2)**2,
  576. lambda x: (3.-x)**2 / 2]
  577. elif der == 2:
  578. funcs = [lambda x: 1.,
  579. lambda x: -2.,
  580. lambda x: 1.]
  581. else:
  582. raise ValueError('never be here: der=%s' % der)
  583. pieces = np.piecewise(x, conds, funcs)
  584. return pieces
  585. def _make_random_spline(n=35, k=3):
  586. np.random.seed(123)
  587. t = np.sort(np.random.random(n+k+1))
  588. c = np.random.random(n)
  589. return BSpline.construct_fast(t, c, k)
  590. def _make_multiples(b):
  591. """Increase knot multiplicity."""
  592. c, k = b.c, b.k
  593. t1 = b.t.copy()
  594. t1[17:19] = t1[17]
  595. t1[22] = t1[21]
  596. yield BSpline(t1, c, k)
  597. t1 = b.t.copy()
  598. t1[:k+1] = t1[0]
  599. yield BSpline(t1, c, k)
  600. t1 = b.t.copy()
  601. t1[-k-1:] = t1[-1]
  602. yield BSpline(t1, c, k)
  603. class TestInterop:
  604. #
  605. # Test that FITPACK-based spl* functions can deal with BSpline objects
  606. #
  607. def setup_method(self):
  608. xx = np.linspace(0, 4.*np.pi, 41)
  609. yy = np.cos(xx)
  610. b = make_interp_spline(xx, yy)
  611. self.tck = (b.t, b.c, b.k)
  612. self.xx, self.yy, self.b = xx, yy, b
  613. self.xnew = np.linspace(0, 4.*np.pi, 21)
  614. c2 = np.c_[b.c, b.c, b.c]
  615. self.c2 = np.dstack((c2, c2))
  616. self.b2 = BSpline(b.t, self.c2, b.k)
  617. def test_splev(self):
  618. xnew, b, b2 = self.xnew, self.b, self.b2
  619. # check that splev works with 1-D array of coefficients
  620. # for array and scalar `x`
  621. assert_allclose(splev(xnew, b),
  622. b(xnew), atol=1e-15, rtol=1e-15)
  623. assert_allclose(splev(xnew, b.tck),
  624. b(xnew), atol=1e-15, rtol=1e-15)
  625. assert_allclose([splev(x, b) for x in xnew],
  626. b(xnew), atol=1e-15, rtol=1e-15)
  627. # With N-D coefficients, there's a quirck:
  628. # splev(x, BSpline) is equivalent to BSpline(x)
  629. with assert_raises(ValueError, match="Calling splev.. with BSpline"):
  630. splev(xnew, b2)
  631. # However, splev(x, BSpline.tck) needs some transposes. This is because
  632. # BSpline interpolates along the first axis, while the legacy FITPACK
  633. # wrapper does list(map(...)) which effectively interpolates along the
  634. # last axis. Like so:
  635. sh = tuple(range(1, b2.c.ndim)) + (0,) # sh = (1, 2, 0)
  636. cc = b2.c.transpose(sh)
  637. tck = (b2.t, cc, b2.k)
  638. assert_allclose(splev(xnew, tck),
  639. b2(xnew).transpose(sh), atol=1e-15, rtol=1e-15)
  640. def test_splrep(self):
  641. x, y = self.xx, self.yy
  642. # test that "new" splrep is equivalent to _impl.splrep
  643. tck = splrep(x, y)
  644. t, c, k = _impl.splrep(x, y)
  645. assert_allclose(tck[0], t, atol=1e-15)
  646. assert_allclose(tck[1], c, atol=1e-15)
  647. assert_equal(tck[2], k)
  648. # also cover the `full_output=True` branch
  649. tck_f, _, _, _ = splrep(x, y, full_output=True)
  650. assert_allclose(tck_f[0], t, atol=1e-15)
  651. assert_allclose(tck_f[1], c, atol=1e-15)
  652. assert_equal(tck_f[2], k)
  653. # test that the result of splrep roundtrips with splev:
  654. # evaluate the spline on the original `x` points
  655. yy = splev(x, tck)
  656. assert_allclose(y, yy, atol=1e-15)
  657. # ... and also it roundtrips if wrapped in a BSpline
  658. b = BSpline(*tck)
  659. assert_allclose(y, b(x), atol=1e-15)
  660. def test_splrep_errors(self):
  661. # test that both "old" and "new" splrep raise for an N-D ``y`` array
  662. # with n > 1
  663. x, y = self.xx, self.yy
  664. y2 = np.c_[y, y]
  665. with assert_raises(ValueError):
  666. splrep(x, y2)
  667. with assert_raises(ValueError):
  668. _impl.splrep(x, y2)
  669. # input below minimum size
  670. with assert_raises(TypeError, match="m > k must hold"):
  671. splrep(x[:3], y[:3])
  672. with assert_raises(TypeError, match="m > k must hold"):
  673. _impl.splrep(x[:3], y[:3])
  674. def test_splprep(self):
  675. x = np.arange(15).reshape((3, 5))
  676. b, u = splprep(x)
  677. tck, u1 = _impl.splprep(x)
  678. # test the roundtrip with splev for both "old" and "new" output
  679. assert_allclose(u, u1, atol=1e-15)
  680. assert_allclose(splev(u, b), x, atol=1e-15)
  681. assert_allclose(splev(u, tck), x, atol=1e-15)
  682. # cover the ``full_output=True`` branch
  683. (b_f, u_f), _, _, _ = splprep(x, s=0, full_output=True)
  684. assert_allclose(u, u_f, atol=1e-15)
  685. assert_allclose(splev(u_f, b_f), x, atol=1e-15)
  686. def test_splprep_errors(self):
  687. # test that both "old" and "new" code paths raise for x.ndim > 2
  688. x = np.arange(3*4*5).reshape((3, 4, 5))
  689. with assert_raises(ValueError, match="too many values to unpack"):
  690. splprep(x)
  691. with assert_raises(ValueError, match="too many values to unpack"):
  692. _impl.splprep(x)
  693. # input below minimum size
  694. x = np.linspace(0, 40, num=3)
  695. with assert_raises(TypeError, match="m > k must hold"):
  696. splprep([x])
  697. with assert_raises(TypeError, match="m > k must hold"):
  698. _impl.splprep([x])
  699. # automatically calculated parameters are non-increasing
  700. # see gh-7589
  701. x = [-50.49072266, -50.49072266, -54.49072266, -54.49072266]
  702. with assert_raises(ValueError, match="Invalid inputs"):
  703. splprep([x])
  704. with assert_raises(ValueError, match="Invalid inputs"):
  705. _impl.splprep([x])
  706. # given non-increasing parameter values u
  707. x = [1, 3, 2, 4]
  708. u = [0, 0.3, 0.2, 1]
  709. with assert_raises(ValueError, match="Invalid inputs"):
  710. splprep(*[[x], None, u])
  711. def test_sproot(self):
  712. b, b2 = self.b, self.b2
  713. roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi
  714. # sproot accepts a BSpline obj w/ 1-D coef array
  715. assert_allclose(sproot(b), roots, atol=1e-7, rtol=1e-7)
  716. assert_allclose(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7)
  717. # ... and deals with trailing dimensions if coef array is N-D
  718. with assert_raises(ValueError, match="Calling sproot.. with BSpline"):
  719. sproot(b2, mest=50)
  720. # and legacy behavior is preserved for a tck tuple w/ N-D coef
  721. c2r = b2.c.transpose(1, 2, 0)
  722. rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50))
  723. assert_equal(rr.shape, (3, 2, 4))
  724. assert_allclose(rr - roots, 0, atol=1e-12)
  725. def test_splint(self):
  726. # test that splint accepts BSpline objects
  727. b, b2 = self.b, self.b2
  728. assert_allclose(splint(0, 1, b),
  729. splint(0, 1, b.tck), atol=1e-14)
  730. assert_allclose(splint(0, 1, b),
  731. b.integrate(0, 1), atol=1e-14)
  732. # ... and deals with N-D arrays of coefficients
  733. with assert_raises(ValueError, match="Calling splint.. with BSpline"):
  734. splint(0, 1, b2)
  735. # and the legacy behavior is preserved for a tck tuple w/ N-D coef
  736. c2r = b2.c.transpose(1, 2, 0)
  737. integr = np.asarray(splint(0, 1, (b2.t, c2r, b2.k)))
  738. assert_equal(integr.shape, (3, 2))
  739. assert_allclose(integr,
  740. splint(0, 1, b), atol=1e-14)
  741. def test_splder(self):
  742. for b in [self.b, self.b2]:
  743. # pad the c array (FITPACK convention)
  744. ct = len(b.t) - len(b.c)
  745. if ct > 0:
  746. b.c = np.r_[b.c, np.zeros((ct,) + b.c.shape[1:])]
  747. for n in [1, 2, 3]:
  748. bd = splder(b)
  749. tck_d = _impl.splder((b.t, b.c, b.k))
  750. assert_allclose(bd.t, tck_d[0], atol=1e-15)
  751. assert_allclose(bd.c, tck_d[1], atol=1e-15)
  752. assert_equal(bd.k, tck_d[2])
  753. assert_(isinstance(bd, BSpline))
  754. assert_(isinstance(tck_d, tuple)) # back-compat: tck in and out
  755. def test_splantider(self):
  756. for b in [self.b, self.b2]:
  757. # pad the c array (FITPACK convention)
  758. ct = len(b.t) - len(b.c)
  759. if ct > 0:
  760. b.c = np.r_[b.c, np.zeros((ct,) + b.c.shape[1:])]
  761. for n in [1, 2, 3]:
  762. bd = splantider(b)
  763. tck_d = _impl.splantider((b.t, b.c, b.k))
  764. assert_allclose(bd.t, tck_d[0], atol=1e-15)
  765. assert_allclose(bd.c, tck_d[1], atol=1e-15)
  766. assert_equal(bd.k, tck_d[2])
  767. assert_(isinstance(bd, BSpline))
  768. assert_(isinstance(tck_d, tuple)) # back-compat: tck in and out
  769. def test_insert(self):
  770. b, b2, xx = self.b, self.b2, self.xx
  771. j = b.t.size // 2
  772. tn = 0.5*(b.t[j] + b.t[j+1])
  773. bn, tck_n = insert(tn, b), insert(tn, (b.t, b.c, b.k))
  774. assert_allclose(splev(xx, bn),
  775. splev(xx, tck_n), atol=1e-15)
  776. assert_(isinstance(bn, BSpline))
  777. assert_(isinstance(tck_n, tuple)) # back-compat: tck in, tck out
  778. # for N-D array of coefficients, BSpline.c needs to be transposed
  779. # after that, the results are equivalent.
  780. sh = tuple(range(b2.c.ndim))
  781. c_ = b2.c.transpose(sh[1:] + (0,))
  782. tck_n2 = insert(tn, (b2.t, c_, b2.k))
  783. bn2 = insert(tn, b2)
  784. # need a transpose for comparing the results, cf test_splev
  785. assert_allclose(np.asarray(splev(xx, tck_n2)).transpose(2, 0, 1),
  786. bn2(xx), atol=1e-15)
  787. assert_(isinstance(bn2, BSpline))
  788. assert_(isinstance(tck_n2, tuple)) # back-compat: tck in, tck out
  789. class TestInterp:
  790. #
  791. # Test basic ways of constructing interpolating splines.
  792. #
  793. xx = np.linspace(0., 2.*np.pi)
  794. yy = np.sin(xx)
  795. def test_non_int_order(self):
  796. with assert_raises(TypeError):
  797. make_interp_spline(self.xx, self.yy, k=2.5)
  798. def test_order_0(self):
  799. b = make_interp_spline(self.xx, self.yy, k=0)
  800. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  801. b = make_interp_spline(self.xx, self.yy, k=0, axis=-1)
  802. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  803. def test_linear(self):
  804. b = make_interp_spline(self.xx, self.yy, k=1)
  805. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  806. b = make_interp_spline(self.xx, self.yy, k=1, axis=-1)
  807. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  808. @pytest.mark.parametrize('k', [0, 1, 2, 3])
  809. def test_incompatible_x_y(self, k):
  810. x = [0, 1, 2, 3, 4, 5]
  811. y = [0, 1, 2, 3, 4, 5, 6, 7]
  812. with assert_raises(ValueError, match="Shapes of x"):
  813. make_interp_spline(x, y, k=k)
  814. @pytest.mark.parametrize('k', [0, 1, 2, 3])
  815. def test_broken_x(self, k):
  816. x = [0, 1, 1, 2, 3, 4] # duplicates
  817. y = [0, 1, 2, 3, 4, 5]
  818. with assert_raises(ValueError, match="x to not have duplicates"):
  819. make_interp_spline(x, y, k=k)
  820. x = [0, 2, 1, 3, 4, 5] # unsorted
  821. with assert_raises(ValueError, match="Expect x to be a 1D strictly"):
  822. make_interp_spline(x, y, k=k)
  823. x = [0, 1, 2, 3, 4, 5]
  824. x = np.asarray(x).reshape((1, -1)) # 1D
  825. with assert_raises(ValueError, match="Expect x to be a 1D strictly"):
  826. make_interp_spline(x, y, k=k)
  827. def test_not_a_knot(self):
  828. for k in [3, 5]:
  829. b = make_interp_spline(self.xx, self.yy, k)
  830. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  831. def test_periodic(self):
  832. # k = 5 here for more derivatives
  833. b = make_interp_spline(self.xx, self.yy, k=5, bc_type='periodic')
  834. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  835. # in periodic case it is expected equality of k-1 first
  836. # derivatives at the boundaries
  837. for i in range(1, 5):
  838. assert_allclose(b(self.xx[0], nu=i), b(self.xx[-1], nu=i), atol=1e-11)
  839. # tests for axis=-1
  840. b = make_interp_spline(self.xx, self.yy, k=5, bc_type='periodic', axis=-1)
  841. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  842. for i in range(1, 5):
  843. assert_allclose(b(self.xx[0], nu=i), b(self.xx[-1], nu=i), atol=1e-11)
  844. @pytest.mark.parametrize('k', [2, 3, 4, 5, 6, 7])
  845. def test_periodic_random(self, k):
  846. # tests for both cases (k > n and k <= n)
  847. n = 5
  848. np.random.seed(1234)
  849. x = np.sort(np.random.random_sample(n) * 10)
  850. y = np.random.random_sample(n) * 100
  851. y[0] = y[-1]
  852. b = make_interp_spline(x, y, k=k, bc_type='periodic')
  853. assert_allclose(b(x), y, atol=1e-14)
  854. def test_periodic_axis(self):
  855. n = self.xx.shape[0]
  856. np.random.seed(1234)
  857. x = np.random.random_sample(n) * 2 * np.pi
  858. x = np.sort(x)
  859. x[0] = 0.
  860. x[-1] = 2 * np.pi
  861. y = np.zeros((2, n))
  862. y[0] = np.sin(x)
  863. y[1] = np.cos(x)
  864. b = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
  865. for i in range(n):
  866. assert_allclose(b(x[i]), y[:, i], atol=1e-14)
  867. assert_allclose(b(x[0]), b(x[-1]), atol=1e-14)
  868. def test_periodic_points_exception(self):
  869. # first and last points should match when periodic case expected
  870. np.random.seed(1234)
  871. k = 5
  872. n = 8
  873. x = np.sort(np.random.random_sample(n))
  874. y = np.random.random_sample(n)
  875. y[0] = y[-1] - 1 # to be sure that they are not equal
  876. with assert_raises(ValueError):
  877. make_interp_spline(x, y, k=k, bc_type='periodic')
  878. def test_periodic_knots_exception(self):
  879. # `periodic` case does not work with passed vector of knots
  880. np.random.seed(1234)
  881. k = 3
  882. n = 7
  883. x = np.sort(np.random.random_sample(n))
  884. y = np.random.random_sample(n)
  885. t = np.zeros(n + 2 * k)
  886. with assert_raises(ValueError):
  887. make_interp_spline(x, y, k, t, 'periodic')
  888. @pytest.mark.parametrize('k', [2, 3, 4, 5])
  889. def test_periodic_splev(self, k):
  890. # comparision values of periodic b-spline with splev
  891. b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic')
  892. tck = splrep(self.xx, self.yy, per=True, k=k)
  893. spl = splev(self.xx, tck)
  894. assert_allclose(spl, b(self.xx), atol=1e-14)
  895. # comparison derivatives of periodic b-spline with splev
  896. for i in range(1, k):
  897. spl = splev(self.xx, tck, der=i)
  898. assert_allclose(spl, b(self.xx, nu=i), atol=1e-10)
  899. def test_periodic_cubic(self):
  900. # comparison values of cubic periodic b-spline with CubicSpline
  901. b = make_interp_spline(self.xx, self.yy, k=3, bc_type='periodic')
  902. cub = CubicSpline(self.xx, self.yy, bc_type='periodic')
  903. assert_allclose(b(self.xx), cub(self.xx), atol=1e-14)
  904. # edge case: Cubic interpolation on 3 points
  905. n = 3
  906. x = np.sort(np.random.random_sample(n) * 10)
  907. y = np.random.random_sample(n) * 100
  908. y[0] = y[-1]
  909. b = make_interp_spline(x, y, k=3, bc_type='periodic')
  910. cub = CubicSpline(x, y, bc_type='periodic')
  911. assert_allclose(b(x), cub(x), atol=1e-14)
  912. def test_periodic_full_matrix(self):
  913. # comparison values of cubic periodic b-spline with
  914. # solution of the system with full matrix
  915. k = 3
  916. b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic')
  917. t = _periodic_knots(self.xx, k)
  918. c = _make_interp_per_full_matr(self.xx, self.yy, t, k)
  919. b1 = np.vectorize(lambda x: _naive_eval(x, t, c, k))
  920. assert_allclose(b(self.xx), b1(self.xx), atol=1e-14)
  921. def test_quadratic_deriv(self):
  922. der = [(1, 8.)] # order, value: f'(x) = 8.
  923. # derivative at right-hand edge
  924. b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(None, der))
  925. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  926. assert_allclose(b(self.xx[-1], 1), der[0][1], atol=1e-14, rtol=1e-14)
  927. # derivative at left-hand edge
  928. b = make_interp_spline(self.xx, self.yy, k=2, bc_type=(der, None))
  929. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  930. assert_allclose(b(self.xx[0], 1), der[0][1], atol=1e-14, rtol=1e-14)
  931. def test_cubic_deriv(self):
  932. k = 3
  933. # first derivatives at left & right edges:
  934. der_l, der_r = [(1, 3.)], [(1, 4.)]
  935. b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r))
  936. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  937. assert_allclose([b(self.xx[0], 1), b(self.xx[-1], 1)],
  938. [der_l[0][1], der_r[0][1]], atol=1e-14, rtol=1e-14)
  939. # 'natural' cubic spline, zero out 2nd derivatives at the boundaries
  940. der_l, der_r = [(2, 0)], [(2, 0)]
  941. b = make_interp_spline(self.xx, self.yy, k, bc_type=(der_l, der_r))
  942. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  943. def test_quintic_derivs(self):
  944. k, n = 5, 7
  945. x = np.arange(n).astype(np.float_)
  946. y = np.sin(x)
  947. der_l = [(1, -12.), (2, 1)]
  948. der_r = [(1, 8.), (2, 3.)]
  949. b = make_interp_spline(x, y, k=k, bc_type=(der_l, der_r))
  950. assert_allclose(b(x), y, atol=1e-14, rtol=1e-14)
  951. assert_allclose([b(x[0], 1), b(x[0], 2)],
  952. [val for (nu, val) in der_l])
  953. assert_allclose([b(x[-1], 1), b(x[-1], 2)],
  954. [val for (nu, val) in der_r])
  955. @pytest.mark.xfail(reason='unstable')
  956. def test_cubic_deriv_unstable(self):
  957. # 1st and 2nd derivative at x[0], no derivative information at x[-1]
  958. # The problem is not that it fails [who would use this anyway],
  959. # the problem is that it fails *silently*, and I've no idea
  960. # how to detect this sort of instability.
  961. # In this particular case: it's OK for len(t) < 20, goes haywire
  962. # at larger `len(t)`.
  963. k = 3
  964. t = _augknt(self.xx, k)
  965. der_l = [(1, 3.), (2, 4.)]
  966. b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None))
  967. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  968. def test_knots_not_data_sites(self):
  969. # Knots need not coincide with the data sites.
  970. # use a quadratic spline, knots are at data averages,
  971. # two additional constraints are zero 2nd derivatives at edges
  972. k = 2
  973. t = np.r_[(self.xx[0],)*(k+1),
  974. (self.xx[1:] + self.xx[:-1]) / 2.,
  975. (self.xx[-1],)*(k+1)]
  976. b = make_interp_spline(self.xx, self.yy, k, t,
  977. bc_type=([(2, 0)], [(2, 0)]))
  978. assert_allclose(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  979. assert_allclose([b(self.xx[0], 2), b(self.xx[-1], 2)], [0., 0.],
  980. atol=1e-14)
  981. def test_minimum_points_and_deriv(self):
  982. # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and
  983. # f'(0) = 0, f'(1) = 3.
  984. k = 3
  985. x = [0., 1.]
  986. y = [0., 1.]
  987. b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))
  988. xx = np.linspace(0., 1.)
  989. yy = xx**3
  990. assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)
  991. def test_deriv_spec(self):
  992. # If one of the derivatives is omitted, the spline definition is
  993. # incomplete.
  994. x = y = [1.0, 2, 3, 4, 5, 6]
  995. with assert_raises(ValueError):
  996. make_interp_spline(x, y, bc_type=([(1, 0.)], None))
  997. with assert_raises(ValueError):
  998. make_interp_spline(x, y, bc_type=(1, 0.))
  999. with assert_raises(ValueError):
  1000. make_interp_spline(x, y, bc_type=[(1, 0.)])
  1001. with assert_raises(ValueError):
  1002. make_interp_spline(x, y, bc_type=42)
  1003. # CubicSpline expects`bc_type=(left_pair, right_pair)`, while
  1004. # here we expect `bc_type=(iterable, iterable)`.
  1005. l, r = (1, 0.0), (1, 0.0)
  1006. with assert_raises(ValueError):
  1007. make_interp_spline(x, y, bc_type=(l, r))
  1008. def test_complex(self):
  1009. k = 3
  1010. xx = self.xx
  1011. yy = self.yy + 1.j*self.yy
  1012. # first derivatives at left & right edges:
  1013. der_l, der_r = [(1, 3.j)], [(1, 4.+2.j)]
  1014. b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
  1015. assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)
  1016. assert_allclose([b(xx[0], 1), b(xx[-1], 1)],
  1017. [der_l[0][1], der_r[0][1]], atol=1e-14, rtol=1e-14)
  1018. # also test zero and first order
  1019. for k in (0, 1):
  1020. b = make_interp_spline(xx, yy, k=k)
  1021. assert_allclose(b(xx), yy, atol=1e-14, rtol=1e-14)
  1022. def test_int_xy(self):
  1023. x = np.arange(10).astype(np.int_)
  1024. y = np.arange(10).astype(np.int_)
  1025. # Cython chokes on "buffer type mismatch" (construction) or
  1026. # "no matching signature found" (evaluation)
  1027. for k in (0, 1, 2, 3):
  1028. b = make_interp_spline(x, y, k=k)
  1029. b(x)
  1030. def test_sliced_input(self):
  1031. # Cython code chokes on non C contiguous arrays
  1032. xx = np.linspace(-1, 1, 100)
  1033. x = xx[::5]
  1034. y = xx[::5]
  1035. for k in (0, 1, 2, 3):
  1036. make_interp_spline(x, y, k=k)
  1037. def test_check_finite(self):
  1038. # check_finite defaults to True; nans and such trigger a ValueError
  1039. x = np.arange(10).astype(float)
  1040. y = x**2
  1041. for z in [np.nan, np.inf, -np.inf]:
  1042. y[-1] = z
  1043. assert_raises(ValueError, make_interp_spline, x, y)
  1044. @pytest.mark.parametrize('k', [1, 2, 3, 5])
  1045. def test_list_input(self, k):
  1046. # regression test for gh-8714: TypeError for x, y being lists and k=2
  1047. x = list(range(10))
  1048. y = [a**2 for a in x]
  1049. make_interp_spline(x, y, k=k)
  1050. def test_multiple_rhs(self):
  1051. yy = np.c_[np.sin(self.xx), np.cos(self.xx)]
  1052. der_l = [(1, [1., 2.])]
  1053. der_r = [(1, [3., 4.])]
  1054. b = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))
  1055. assert_allclose(b(self.xx), yy, atol=1e-14, rtol=1e-14)
  1056. assert_allclose(b(self.xx[0], 1), der_l[0][1], atol=1e-14, rtol=1e-14)
  1057. assert_allclose(b(self.xx[-1], 1), der_r[0][1], atol=1e-14, rtol=1e-14)
  1058. def test_shapes(self):
  1059. np.random.seed(1234)
  1060. k, n = 3, 22
  1061. x = np.sort(np.random.random(size=n))
  1062. y = np.random.random(size=(n, 5, 6, 7))
  1063. b = make_interp_spline(x, y, k)
  1064. assert_equal(b.c.shape, (n, 5, 6, 7))
  1065. # now throw in some derivatives
  1066. d_l = [(1, np.random.random((5, 6, 7)))]
  1067. d_r = [(1, np.random.random((5, 6, 7)))]
  1068. b = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
  1069. assert_equal(b.c.shape, (n + k - 1, 5, 6, 7))
  1070. def test_string_aliases(self):
  1071. yy = np.sin(self.xx)
  1072. # a single string is duplicated
  1073. b1 = make_interp_spline(self.xx, yy, k=3, bc_type='natural')
  1074. b2 = make_interp_spline(self.xx, yy, k=3, bc_type=([(2, 0)], [(2, 0)]))
  1075. assert_allclose(b1.c, b2.c, atol=1e-15)
  1076. # two strings are handled
  1077. b1 = make_interp_spline(self.xx, yy, k=3,
  1078. bc_type=('natural', 'clamped'))
  1079. b2 = make_interp_spline(self.xx, yy, k=3,
  1080. bc_type=([(2, 0)], [(1, 0)]))
  1081. assert_allclose(b1.c, b2.c, atol=1e-15)
  1082. # one-sided BCs are OK
  1083. b1 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, 'clamped'))
  1084. b2 = make_interp_spline(self.xx, yy, k=2, bc_type=(None, [(1, 0.0)]))
  1085. assert_allclose(b1.c, b2.c, atol=1e-15)
  1086. # 'not-a-knot' is equivalent to None
  1087. b1 = make_interp_spline(self.xx, yy, k=3, bc_type='not-a-knot')
  1088. b2 = make_interp_spline(self.xx, yy, k=3, bc_type=None)
  1089. assert_allclose(b1.c, b2.c, atol=1e-15)
  1090. # unknown strings do not pass
  1091. with assert_raises(ValueError):
  1092. make_interp_spline(self.xx, yy, k=3, bc_type='typo')
  1093. # string aliases are handled for 2D values
  1094. yy = np.c_[np.sin(self.xx), np.cos(self.xx)]
  1095. der_l = [(1, [0., 0.])]
  1096. der_r = [(2, [0., 0.])]
  1097. b2 = make_interp_spline(self.xx, yy, k=3, bc_type=(der_l, der_r))
  1098. b1 = make_interp_spline(self.xx, yy, k=3,
  1099. bc_type=('clamped', 'natural'))
  1100. assert_allclose(b1.c, b2.c, atol=1e-15)
  1101. # ... and for N-D values:
  1102. np.random.seed(1234)
  1103. k, n = 3, 22
  1104. x = np.sort(np.random.random(size=n))
  1105. y = np.random.random(size=(n, 5, 6, 7))
  1106. # now throw in some derivatives
  1107. d_l = [(1, np.zeros((5, 6, 7)))]
  1108. d_r = [(1, np.zeros((5, 6, 7)))]
  1109. b1 = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
  1110. b2 = make_interp_spline(x, y, k, bc_type='clamped')
  1111. assert_allclose(b1.c, b2.c, atol=1e-15)
  1112. def test_full_matrix(self):
  1113. np.random.seed(1234)
  1114. k, n = 3, 7
  1115. x = np.sort(np.random.random(size=n))
  1116. y = np.random.random(size=n)
  1117. t = _not_a_knot(x, k)
  1118. b = make_interp_spline(x, y, k, t)
  1119. cf = make_interp_full_matr(x, y, t, k)
  1120. assert_allclose(b.c, cf, atol=1e-14, rtol=1e-14)
  1121. def test_woodbury(self):
  1122. '''
  1123. Random elements in diagonal matrix with blocks in the
  1124. left lower and right upper corners checking the
  1125. implementation of Woodbury algorithm.
  1126. '''
  1127. np.random.seed(1234)
  1128. n = 201
  1129. for k in range(3, 32, 2):
  1130. offset = int((k - 1) / 2)
  1131. a = np.diagflat(np.random.random((1, n)))
  1132. for i in range(1, offset + 1):
  1133. a[:-i, i:] += np.diagflat(np.random.random((1, n - i)))
  1134. a[i:, :-i] += np.diagflat(np.random.random((1, n - i)))
  1135. ur = np.random.random((offset, offset))
  1136. a[:offset, -offset:] = ur
  1137. ll = np.random.random((offset, offset))
  1138. a[-offset:, :offset] = ll
  1139. d = np.zeros((k, n))
  1140. for i, j in enumerate(range(offset, -offset - 1, -1)):
  1141. if j < 0:
  1142. d[i, :j] = np.diagonal(a, offset=j)
  1143. else:
  1144. d[i, j:] = np.diagonal(a, offset=j)
  1145. b = np.random.random(n)
  1146. assert_allclose(_woodbury_algorithm(d, ur, ll, b, k),
  1147. np.linalg.solve(a, b), atol=1e-14)
  1148. def make_interp_full_matr(x, y, t, k):
  1149. """Assemble an spline order k with knots t to interpolate
  1150. y(x) using full matrices.
  1151. Not-a-knot BC only.
  1152. This routine is here for testing only (even though it's functional).
  1153. """
  1154. assert x.size == y.size
  1155. assert t.size == x.size + k + 1
  1156. n = x.size
  1157. A = np.zeros((n, n), dtype=np.float_)
  1158. for j in range(n):
  1159. xval = x[j]
  1160. if xval == t[k]:
  1161. left = k
  1162. else:
  1163. left = np.searchsorted(t, xval) - 1
  1164. # fill a row
  1165. bb = _bspl.evaluate_all_bspl(t, k, xval, left)
  1166. A[j, left-k:left+1] = bb
  1167. c = sl.solve(A, y)
  1168. return c
  1169. def make_lsq_full_matrix(x, y, t, k=3):
  1170. """Make the least-square spline, full matrices."""
  1171. x, y, t = map(np.asarray, (x, y, t))
  1172. m = x.size
  1173. n = t.size - k - 1
  1174. A = np.zeros((m, n), dtype=np.float_)
  1175. for j in range(m):
  1176. xval = x[j]
  1177. # find interval
  1178. if xval == t[k]:
  1179. left = k
  1180. else:
  1181. left = np.searchsorted(t, xval) - 1
  1182. # fill a row
  1183. bb = _bspl.evaluate_all_bspl(t, k, xval, left)
  1184. A[j, left-k:left+1] = bb
  1185. # have observation matrix, can solve the LSQ problem
  1186. B = np.dot(A.T, A)
  1187. Y = np.dot(A.T, y)
  1188. c = sl.solve(B, Y)
  1189. return c, (A, Y)
  1190. class TestLSQ:
  1191. #
  1192. # Test make_lsq_spline
  1193. #
  1194. np.random.seed(1234)
  1195. n, k = 13, 3
  1196. x = np.sort(np.random.random(n))
  1197. y = np.random.random(n)
  1198. t = _augknt(np.linspace(x[0], x[-1], 7), k)
  1199. def test_lstsq(self):
  1200. # check LSQ construction vs a full matrix version
  1201. x, y, t, k = self.x, self.y, self.t, self.k
  1202. c0, AY = make_lsq_full_matrix(x, y, t, k)
  1203. b = make_lsq_spline(x, y, t, k)
  1204. assert_allclose(b.c, c0)
  1205. assert_equal(b.c.shape, (t.size - k - 1,))
  1206. # also check against numpy.lstsq
  1207. aa, yy = AY
  1208. c1, _, _, _ = np.linalg.lstsq(aa, y, rcond=-1)
  1209. assert_allclose(b.c, c1)
  1210. def test_weights(self):
  1211. # weights = 1 is same as None
  1212. x, y, t, k = self.x, self.y, self.t, self.k
  1213. w = np.ones_like(x)
  1214. b = make_lsq_spline(x, y, t, k)
  1215. b_w = make_lsq_spline(x, y, t, k, w=w)
  1216. assert_allclose(b.t, b_w.t, atol=1e-14)
  1217. assert_allclose(b.c, b_w.c, atol=1e-14)
  1218. assert_equal(b.k, b_w.k)
  1219. def test_multiple_rhs(self):
  1220. x, t, k, n = self.x, self.t, self.k, self.n
  1221. y = np.random.random(size=(n, 5, 6, 7))
  1222. b = make_lsq_spline(x, y, t, k)
  1223. assert_equal(b.c.shape, (t.size-k-1, 5, 6, 7))
  1224. def test_complex(self):
  1225. # cmplx-valued `y`
  1226. x, t, k = self.x, self.t, self.k
  1227. yc = self.y * (1. + 2.j)
  1228. b = make_lsq_spline(x, yc, t, k)
  1229. b_re = make_lsq_spline(x, yc.real, t, k)
  1230. b_im = make_lsq_spline(x, yc.imag, t, k)
  1231. assert_allclose(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)
  1232. def test_int_xy(self):
  1233. x = np.arange(10).astype(np.int_)
  1234. y = np.arange(10).astype(np.int_)
  1235. t = _augknt(x, k=1)
  1236. # Cython chokes on "buffer type mismatch"
  1237. make_lsq_spline(x, y, t, k=1)
  1238. def test_sliced_input(self):
  1239. # Cython code chokes on non C contiguous arrays
  1240. xx = np.linspace(-1, 1, 100)
  1241. x = xx[::3]
  1242. y = xx[::3]
  1243. t = _augknt(x, 1)
  1244. make_lsq_spline(x, y, t, k=1)
  1245. def test_checkfinite(self):
  1246. # check_finite defaults to True; nans and such trigger a ValueError
  1247. x = np.arange(12).astype(float)
  1248. y = x**2
  1249. t = _augknt(x, 3)
  1250. for z in [np.nan, np.inf, -np.inf]:
  1251. y[-1] = z
  1252. assert_raises(ValueError, make_lsq_spline, x, y, t)
  1253. def data_file(basename):
  1254. return os.path.join(os.path.abspath(os.path.dirname(__file__)),
  1255. 'data', basename)
  1256. class TestSmoothingSpline:
  1257. #
  1258. # test make_smoothing_spline
  1259. #
  1260. def test_invalid_input(self):
  1261. np.random.seed(1234)
  1262. n = 100
  1263. x = np.sort(np.random.random_sample(n) * 4 - 2)
  1264. y = x**2 * np.sin(4 * x) + x**3 + np.random.normal(0., 1.5, n)
  1265. # ``x`` and ``y`` should have same shapes (1-D array)
  1266. with assert_raises(ValueError):
  1267. make_smoothing_spline(x, y[1:])
  1268. with assert_raises(ValueError):
  1269. make_smoothing_spline(x[1:], y)
  1270. with assert_raises(ValueError):
  1271. make_smoothing_spline(x.reshape(1, n), y)
  1272. # ``x`` should be an ascending array
  1273. with assert_raises(ValueError):
  1274. make_smoothing_spline(x[::-1], y)
  1275. x_dupl = np.copy(x)
  1276. x_dupl[0] = x_dupl[1]
  1277. with assert_raises(ValueError):
  1278. make_smoothing_spline(x_dupl, y)
  1279. def test_compare_with_GCVSPL(self):
  1280. """
  1281. Data is generated in the following way:
  1282. >>> np.random.seed(1234)
  1283. >>> n = 100
  1284. >>> x = np.sort(np.random.random_sample(n) * 4 - 2)
  1285. >>> y = np.sin(x) + np.random.normal(scale=.5, size=n)
  1286. >>> np.savetxt('x.csv', x)
  1287. >>> np.savetxt('y.csv', y)
  1288. We obtain the result of performing the GCV smoothing splines
  1289. package (by Woltring, gcvspl) on the sample data points
  1290. using its version for Octave (https://github.com/srkuberski/gcvspl).
  1291. In order to use this implementation, one should clone the repository
  1292. and open the folder in Octave.
  1293. In Octave, we load up ``x`` and ``y`` (generated from Python code
  1294. above):
  1295. >>> x = csvread('x.csv');
  1296. >>> y = csvread('y.csv');
  1297. Then, in order to access the implementation, we compile gcvspl files in
  1298. Octave:
  1299. >>> mex gcvsplmex.c gcvspl.c
  1300. >>> mex spldermex.c gcvspl.c
  1301. The first function computes the vector of unknowns from the dataset
  1302. (x, y) while the second one evaluates the spline in certain points
  1303. with known vector of coefficients.
  1304. >>> c = gcvsplmex( x, y, 2 );
  1305. >>> y0 = spldermex( x, c, 2, x, 0 );
  1306. If we want to compare the results of the gcvspl code, we can save
  1307. ``y0`` in csv file:
  1308. >>> csvwrite('y0.csv', y0);
  1309. """
  1310. # load the data sample
  1311. data = np.load(data_file('gcvspl.npz'))
  1312. # data points
  1313. x = data['x']
  1314. y = data['y']
  1315. y_GCVSPL = data['y_GCVSPL']
  1316. y_compr = make_smoothing_spline(x, y)(x)
  1317. # such tolerance is explained by the fact that the spline is built
  1318. # using an iterative algorithm for minimizing the GCV criteria. These
  1319. # algorithms may vary, so the tolerance should be rather low.
  1320. assert_allclose(y_compr, y_GCVSPL, atol=1e-4, rtol=1e-4)
  1321. def test_non_regularized_case(self):
  1322. """
  1323. In case the regularization parameter is 0, the resulting spline
  1324. is an interpolation spline with natural boundary conditions.
  1325. """
  1326. # create data sample
  1327. np.random.seed(1234)
  1328. n = 100
  1329. x = np.sort(np.random.random_sample(n) * 4 - 2)
  1330. y = x**2 * np.sin(4 * x) + x**3 + np.random.normal(0., 1.5, n)
  1331. spline_GCV = make_smoothing_spline(x, y, lam=0.)
  1332. spline_interp = make_interp_spline(x, y, 3, bc_type='natural')
  1333. grid = np.linspace(x[0], x[-1], 2 * n)
  1334. assert_allclose(spline_GCV(grid),
  1335. spline_interp(grid),
  1336. atol=1e-15)
  1337. def test_weighted_smoothing_spline(self):
  1338. # create data sample
  1339. np.random.seed(1234)
  1340. n = 100
  1341. x = np.sort(np.random.random_sample(n) * 4 - 2)
  1342. y = x**2 * np.sin(4 * x) + x**3 + np.random.normal(0., 1.5, n)
  1343. spl = make_smoothing_spline(x, y)
  1344. # in order not to iterate over all of the indices, we select 10 of
  1345. # them randomly
  1346. for ind in np.random.choice(range(100), size=10):
  1347. w = np.ones(n)
  1348. w[ind] = 30.
  1349. spl_w = make_smoothing_spline(x, y, w)
  1350. # check that spline with weight in a certain point is closer to the
  1351. # original point than the one without weights
  1352. orig = abs(spl(x[ind]) - y[ind])
  1353. weighted = abs(spl_w(x[ind]) - y[ind])
  1354. if orig < weighted:
  1355. raise ValueError(f'Spline with weights should be closer to the'
  1356. f' points than the original one: {orig:.4} < '
  1357. f'{weighted:.4}')