test_bsplines.py 150 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330
  1. import os
  2. import operator
  3. import itertools
  4. import math
  5. import cmath
  6. import threading
  7. import copy
  8. import warnings
  9. import sys
  10. import numpy as np
  11. from scipy._lib._array_api import (
  12. xp_assert_equal, xp_assert_close, xp_default_dtype, concat_1d, make_xp_test_case,
  13. xp_ravel
  14. )
  15. import scipy._lib.array_api_extra as xpx
  16. from pytest import raises as assert_raises
  17. import pytest
  18. from scipy.interpolate import (
  19. BSpline, BPoly, PPoly, make_interp_spline, make_lsq_spline,
  20. splev, splrep, splprep, splder, splantider, sproot, splint, insert,
  21. CubicSpline, NdBSpline, make_smoothing_spline, RegularGridInterpolator,
  22. )
  23. import scipy.linalg as sl
  24. import scipy.sparse.linalg as ssl
  25. from scipy.interpolate._bsplines import (_not_a_knot, _augknt,
  26. _woodbury_algorithm, _periodic_knots,
  27. _make_interp_per_full_matr)
  28. from scipy.interpolate._fitpack_repro import Fperiodic, root_rati
  29. from scipy.interpolate import generate_knots, make_splrep, make_splprep
  30. import scipy.interpolate._fitpack_impl as _impl
  31. from scipy._lib._util import AxisError
  32. from scipy._lib._testutils import _run_concurrent_barrier
  33. # XXX: move to the interpolate namespace
  34. from scipy.interpolate._ndbspline import make_ndbspl
  35. from scipy.interpolate import _dfitpack as dfitpack
  36. from scipy.interpolate import _bsplines as _b
  37. from scipy.interpolate import _dierckx
  38. skip_xp_backends = pytest.mark.skip_xp_backends
  39. @make_xp_test_case(BSpline)
  40. class TestBSpline:
  41. def test_ctor(self, xp):
  42. # knots should be an ordered 1-D array of finite real numbers
  43. assert_raises((TypeError, ValueError), BSpline,
  44. **dict(t=[1, 1.j], c=[1.], k=0))
  45. with np.errstate(invalid='ignore'):
  46. assert_raises(ValueError, BSpline, **dict(t=[1, np.nan], c=[1.], k=0))
  47. assert_raises(ValueError, BSpline, **dict(t=[1, np.inf], c=[1.], k=0))
  48. assert_raises(ValueError, BSpline, **dict(t=[1, -1], c=[1.], k=0))
  49. assert_raises(ValueError, BSpline, **dict(t=[[1], [1]], c=[1.], k=0))
  50. # for n+k+1 knots and degree k need at least n coefficients
  51. assert_raises(ValueError, BSpline, **dict(t=[0, 1, 2], c=[1], k=0))
  52. assert_raises(ValueError, BSpline,
  53. **dict(t=[0, 1, 2, 3, 4], c=[1., 1.], k=2))
  54. # non-integer orders
  55. assert_raises(TypeError, BSpline,
  56. **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k="cubic"))
  57. assert_raises(TypeError, BSpline,
  58. **dict(t=[0., 0., 1., 2., 3., 4.], c=[1., 1., 1.], k=2.5))
  59. # basic interval cannot have measure zero (here: [1..1])
  60. assert_raises(ValueError, BSpline,
  61. **dict(t=[0., 0, 1, 1, 2, 3], c=[1., 1, 1], k=2))
  62. # tck vs self.tck
  63. n, k = 11, 3
  64. t = xp.arange(n+k+1, dtype=xp.float64)
  65. c = xp.asarray(np.random.random(n))
  66. b = BSpline(t, c, k)
  67. xp_assert_close(t, b.t)
  68. xp_assert_close(c, b.c)
  69. assert k == b.k
  70. def test_tck(self):
  71. b = _make_random_spline()
  72. tck = b.tck
  73. xp_assert_close(b.t, tck[0], atol=1e-15, rtol=1e-15)
  74. xp_assert_close(b.c, tck[1], atol=1e-15, rtol=1e-15)
  75. assert b.k == tck[2]
  76. # b.tck is read-only
  77. with pytest.raises(AttributeError):
  78. b.tck = 'foo'
  79. def test_call_namespace(self, xp):
  80. # similar to test_degree_0 below, only parametrized with xp
  81. # (test_degree_0 tests array-like inputs, which resolve to numpy)
  82. b = BSpline(t=xp.asarray([0, 1., 2]), c=xp.asarray([3., 4]), k=0)
  83. xx = xp.linspace(0, 2, 10)
  84. expected = xp.where(xx < 1., xp.asarray(3., dtype=xp.float64), 4.0)
  85. xp_assert_close(b(xx), expected)
  86. def test_degree_0(self):
  87. xx = np.linspace(0, 1, 10)
  88. b = BSpline(t=[0, 1], c=[3.], k=0)
  89. xp_assert_close(b(xx), np.ones_like(xx) * 3.0)
  90. b = BSpline(t=[0, 0.35, 1], c=[3, 4], k=0)
  91. xp_assert_close(b(xx), np.where(xx < 0.35, 3.0, 4.0))
  92. def test_degree_1(self, xp):
  93. t = xp.asarray([0, 1, 2, 3, 4])
  94. c = xp.asarray([1.0, 2, 3])
  95. k = 1
  96. b = BSpline(t, c, k)
  97. x = xp.linspace(1.0, 3.0, 50, dtype=xp.float64)
  98. xp_assert_close(
  99. b(x),
  100. c[0]*B_012(x, xp=xp) + c[1]*B_012(x-1, xp=xp) + c[2]*B_012(x-2, xp=xp),
  101. atol=1e-14
  102. )
  103. x_np, t_np, c_np = map(np.asarray, (x, t, c))
  104. splev_result = splev(x_np, (t_np, c_np, k))
  105. xp_assert_close(b(x), xp.asarray(splev_result), atol=1e-14)
  106. def test_bernstein(self, xp):
  107. # a special knot vector: Bernstein polynomials
  108. k = 3
  109. t = xp.asarray([0]*(k+1) + [1]*(k+1))
  110. c = xp.asarray([1., 2., 3., 4.])
  111. bp = BPoly(xp.reshape(c, (-1, 1)), xp.asarray([0, 1]))
  112. bspl = BSpline(t, c, k)
  113. xx = xp.linspace(-1., 2., 10)
  114. xp_assert_close(bp(xx, extrapolate=True),
  115. bspl(xx, extrapolate=True), atol=1e-14)
  116. @skip_xp_backends("dask.array", reason="_naive_eval is not dask-compatible")
  117. @skip_xp_backends("jax.numpy", reason="too slow; XXX a slow-if marker?")
  118. @skip_xp_backends("torch", reason="OOB on CI")
  119. def test_rndm_naive_eval(self, xp):
  120. # test random coefficient spline *on the base interval*,
  121. # t[k] <= x < t[-k-1]
  122. b = _make_random_spline(xp=xp)
  123. t, c, k = b.tck
  124. xx = xp.linspace(t[k], t[-k-1], 50)
  125. y_b = b(xx)
  126. y_n = xp.stack([_naive_eval(x, t, c, k, xp=xp) for x in xx])
  127. xp_assert_close(y_b, y_n, atol=1e-14)
  128. y_n2 = xp.stack([_naive_eval_2(x, t, c, k, xp=xp) for x in xx])
  129. xp_assert_close(y_b, y_n2, atol=1e-14)
  130. def test_rndm_splev(self):
  131. b = _make_random_spline()
  132. t, c, k = b.tck
  133. xx = np.linspace(t[k], t[-k-1], 50)
  134. xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14)
  135. def test_rndm_splrep(self):
  136. rng = np.random.RandomState(1234)
  137. x = np.sort(rng.random(20))
  138. y = rng.random(20)
  139. tck = splrep(x, y)
  140. b = BSpline(*tck)
  141. t, k = b.t, b.k
  142. xx = np.linspace(t[k], t[-k-1], 80)
  143. xp_assert_close(b(xx), splev(xx, tck), atol=1e-14)
  144. def test_rndm_unity(self, xp):
  145. b = _make_random_spline(xp=xp)
  146. b.c = xp.ones_like(b.c)
  147. xx = xp.linspace(b.t[b.k], b.t[-b.k-1], 100, dtype=xp.float64)
  148. xp_assert_close(b(xx), xp.ones_like(xx))
  149. def test_vectorization(self, xp):
  150. rng = np.random.RandomState(1234)
  151. n, k = 22, 3
  152. t = np.sort(rng.random(n))
  153. c = rng.random(size=(n, 6, 7))
  154. t, c = map(xp.asarray, (t, c))
  155. b = BSpline(t, c, k)
  156. tm, tp = t[k], t[-k-1]
  157. xx = tm + (tp - tm) * xp.asarray(rng.random((3, 4, 5)))
  158. assert b(xx).shape == (3, 4, 5, 6, 7)
  159. def test_len_c(self):
  160. # for n+k+1 knots, only first n coefs are used.
  161. # and BTW this is consistent with FITPACK
  162. rng = np.random.RandomState(1234)
  163. n, k = 33, 3
  164. t = np.sort(rng.random(n+k+1))
  165. c = rng.random(n)
  166. # pad coefficients with random garbage
  167. c_pad = np.r_[c, rng.random(k+1)]
  168. b, b_pad = BSpline(t, c, k), BSpline(t, c_pad, k)
  169. dt = t[-1] - t[0]
  170. xx = np.linspace(t[0] - dt, t[-1] + dt, 50)
  171. xp_assert_close(b(xx), b_pad(xx), atol=1e-14)
  172. xp_assert_close(b(xx), splev(xx, (t, c, k)), atol=1e-14)
  173. xp_assert_close(b(xx), splev(xx, (t, c_pad, k)), atol=1e-14)
  174. def test_endpoints(self, num_parallel_threads):
  175. # base interval is closed
  176. b = _make_random_spline()
  177. t, _, k = b.tck
  178. tm, tp = t[k], t[-k-1]
  179. # atol = 1e-9 if num_parallel_threads == 1 else 1e-7
  180. for extrap in (True, False):
  181. xp_assert_close(b([tm, tp], extrap),
  182. b([tm + 1e-10, tp - 1e-10], extrap), atol=1e-9, rtol=1e-7)
  183. def test_continuity(self, num_parallel_threads):
  184. # assert continuity at internal knots
  185. b = _make_random_spline()
  186. t, _, k = b.tck
  187. xp_assert_close(b(t[k+1:-k-1] - 1e-10), b(t[k+1:-k-1] + 1e-10),
  188. atol=1e-9)
  189. def test_extrap(self, xp):
  190. b = _make_random_spline(xp=xp)
  191. t, c, k = b.tck
  192. dt = t[-1] - t[0]
  193. xx = xp.linspace(t[k] - dt, t[-k-1] + dt, 50)
  194. mask = (t[k] < xx) & (xx < t[-k-1])
  195. # extrap has no effect within the base interval
  196. xp_assert_close(b(xx[mask], extrapolate=True),
  197. b(xx[mask], extrapolate=False))
  198. # extrapolated values agree with FITPACK
  199. xx_np, t_np, c_np = map(np.asarray, (xx, t, c))
  200. splev_result = xp.asarray(splev(xx_np, (t_np, c_np, k), ext=0))
  201. xp_assert_close(b(xx, extrapolate=True), splev_result)
  202. def test_default_extrap(self):
  203. # BSpline defaults to extrapolate=True
  204. b = _make_random_spline()
  205. t, _, k = b.tck
  206. xx = [t[0] - 1, t[-1] + 1]
  207. yy = b(xx)
  208. assert not np.all(np.isnan(yy))
  209. def test_periodic_extrap(self, xp):
  210. rng = np.random.RandomState(1234)
  211. t = np.sort(rng.random(8))
  212. c = rng.random(4)
  213. t, c = map(xp.asarray, (t, c))
  214. k = 3
  215. b = BSpline(t, c, k, extrapolate='periodic')
  216. n = t.shape[0] - (k + 1)
  217. dt = t[-1] - t[0]
  218. xx = xp.linspace(t[k] - dt, t[n] + dt, 50)
  219. xy = t[k] + (xx - t[k]) % (t[n] - t[k])
  220. xy_np, t_np, c_np = map(np.asarray, (xy, t, c))
  221. atol = 1e-12 if xp_default_dtype(xp) == xp.float64 else 2e-7
  222. xp_assert_close(
  223. b(xx), xp.asarray(splev(xy_np, (t_np, c_np, k))), atol=atol
  224. )
  225. # Direct check
  226. xx = xp.asarray([-1, 0, 0.5, 1])
  227. xy = t[k] + (xx - t[k]) % (t[n] - t[k])
  228. xp_assert_close(
  229. b(xx, extrapolate='periodic'),
  230. b(xy, extrapolate=True),
  231. atol=1e-14 if xp_default_dtype(xp) == xp.float64 else 5e-7
  232. )
  233. def test_ppoly(self):
  234. b = _make_random_spline()
  235. t, c, k = b.tck
  236. pp = PPoly.from_spline((t, c, k))
  237. xx = np.linspace(t[k], t[-k], 100)
  238. xp_assert_close(b(xx), pp(xx), atol=1e-14, rtol=1e-14)
  239. def test_derivative_rndm(self):
  240. b = _make_random_spline()
  241. t, c, k = b.tck
  242. xx = np.linspace(t[0], t[-1], 50)
  243. xx = np.r_[xx, t]
  244. for der in range(1, k+1):
  245. yd = splev(xx, (t, c, k), der=der)
  246. xp_assert_close(yd, b(xx, nu=der), atol=1e-14)
  247. # higher derivatives all vanish
  248. xp_assert_close(b(xx, nu=k+1), np.zeros_like(xx), atol=1e-14)
  249. def test_derivative_jumps(self):
  250. # example from de Boor, Chap IX, example (24)
  251. # NB: knots augmented & corresp coefs are zeroed out
  252. # in agreement with the convention (29)
  253. k = 2
  254. t = [-1, -1, 0, 1, 1, 3, 4, 6, 6, 6, 7, 7]
  255. rng = np.random.RandomState(1234)
  256. c = np.r_[0, 0, rng.random(5), 0, 0]
  257. b = BSpline(t, c, k)
  258. # b is continuous at x != 6 (triple knot)
  259. x = np.asarray([1, 3, 4, 6])
  260. xp_assert_close(b(x[x != 6] - 1e-10),
  261. b(x[x != 6] + 1e-10))
  262. assert not np.allclose(b(6.-1e-10), b(6+1e-10))
  263. # 1st derivative jumps at double knots, 1 & 6:
  264. x0 = np.asarray([3, 4])
  265. xp_assert_close(b(x0 - 1e-10, nu=1),
  266. b(x0 + 1e-10, nu=1))
  267. x1 = np.asarray([1, 6])
  268. assert not np.allclose(b(x1 - 1e-10, nu=1), b(x1 + 1e-10, nu=1))
  269. # 2nd derivative is not guaranteed to be continuous either
  270. assert not np.allclose(b(x - 1e-10, nu=2), b(x + 1e-10, nu=2))
  271. def test_basis_element_quadratic(self, xp):
  272. xx = xp.linspace(-1, 4, 20)
  273. b = BSpline.basis_element(t=xp.asarray([0, 1, 2, 3]))
  274. xx_np, t_np, c_np = map(np.asarray, (xx, b.t, b.c))
  275. splev_result = xp.asarray(splev(xx_np, (t_np, c_np, b.k)))
  276. xp_assert_close(b(xx), splev_result, atol=1e-14)
  277. atol=1e-14 if xp_default_dtype(xp) == xp.float64 else 1e-7
  278. xp_assert_close(b(xx), xp.asarray(B_0123(xx), dtype=xp.float64), atol=atol)
  279. b = BSpline.basis_element(t=xp.asarray([0, 1, 1, 2]))
  280. xx = xp.linspace(0, 2, 10, dtype=xp.float64)
  281. xp_assert_close(b(xx),
  282. xp.where(xx < 1, xx*xx, (2.-xx)**2), atol=1e-14)
  283. def test_basis_element_rndm(self):
  284. b = _make_random_spline()
  285. t, c, k = b.tck
  286. xx = np.linspace(t[k], t[-k-1], 20)
  287. xp_assert_close(b(xx), _sum_basis_elements(xx, t, c, k), atol=1e-14)
  288. def test_cmplx(self):
  289. b = _make_random_spline()
  290. t, c, k = b.tck
  291. cc = c * (1. + 3.j)
  292. b = BSpline(t, cc, k)
  293. b_re = BSpline(t, b.c.real, k)
  294. b_im = BSpline(t, b.c.imag, k)
  295. xx = np.linspace(t[k], t[-k-1], 20)
  296. xp_assert_close(b(xx).real, b_re(xx), atol=1e-14)
  297. xp_assert_close(b(xx).imag, b_im(xx), atol=1e-14)
  298. def test_nan(self, xp):
  299. # nan in, nan out.
  300. b = BSpline.basis_element(xp.asarray([0, 1, 1, 2]))
  301. assert xp.isnan(b(xp.nan))
  302. def test_derivative_method(self, xp):
  303. b = _make_random_spline(k=5, xp=xp)
  304. t, c, k = b.tck
  305. b0 = BSpline(t, c, k)
  306. xx = xp.linspace(t[k], t[-k-1], 20)
  307. for j in range(1, k):
  308. b = b.derivative()
  309. xp_assert_close(b0(xx, j), b(xx), atol=1e-12, rtol=1e-12)
  310. def test_antiderivative_method(self, xp):
  311. b = _make_random_spline(xp=xp)
  312. t, c, k = b.tck
  313. xx = xp.linspace(t[k], t[-k-1], 20)
  314. xp_assert_close(b.antiderivative().derivative()(xx),
  315. b(xx), atol=1e-14, rtol=1e-14)
  316. # repeat with N-D array for c
  317. c = xp.stack((c, c, c), axis=1)
  318. c = xp.stack((c, c), axis=2)
  319. b = BSpline(t, c, k)
  320. xp_assert_close(b.antiderivative().derivative()(xx),
  321. b(xx), atol=1e-14, rtol=1e-14)
  322. def test_integral(self, xp):
  323. b = BSpline.basis_element(xp.asarray([0, 1, 2])) # x for x < 1 else 2 - x
  324. assert math.isclose(b.integrate(0, 1), 0.5, abs_tol=1e-14)
  325. assert math.isclose(b.integrate(1, 0), -1 * 0.5, abs_tol=1e-14)
  326. assert math.isclose(b.integrate(1, 0), -0.5, abs_tol=1e-14)
  327. assert math.isclose(b.integrate(0, 1), 0.5, abs_tol=1e-14)
  328. assert math.isclose(b.integrate(1, 0), -1 * 0.5, abs_tol=1e-14)
  329. assert math.isclose(b.integrate(1, 0), -0.5, abs_tol=1e-14)
  330. # extrapolate or zeros outside of [0, 2]; default is yes
  331. assert math.isclose(b.integrate(-1, 1), 0.0, abs_tol=1e-14)
  332. assert math.isclose(b.integrate(-1, 1, extrapolate=True), 0.0, abs_tol=1e-14)
  333. assert math.isclose(b.integrate(-1, 1, extrapolate=False), 0.5, abs_tol=1e-14)
  334. assert math.isclose(b.integrate(1, -1, extrapolate=False), -0.5, abs_tol=1e-14)
  335. # Test ``_fitpack._splint()``
  336. assert math.isclose(b.integrate(1, -1, extrapolate=False),
  337. _impl.splint(1, -1, b.tck), abs_tol=1e-14)
  338. # Test ``extrapolate='periodic'``.
  339. b.extrapolate = 'periodic'
  340. i = b.antiderivative()
  341. period_int = xp.asarray(i(2) - i(0), dtype=xp.float64)
  342. assert math.isclose(b.integrate(0, 2), period_int)
  343. assert math.isclose(b.integrate(2, 0), -1 * period_int)
  344. assert math.isclose(b.integrate(-9, -7), period_int)
  345. assert math.isclose(b.integrate(-8, -4), 2 * period_int)
  346. xp_assert_close(b.integrate(0.5, 1.5),
  347. xp.asarray(i(1.5) - i(0.5)))
  348. xp_assert_close(b.integrate(1.5, 3),
  349. xp.asarray(i(1) - i(0) + i(2) - i(1.5)))
  350. xp_assert_close(b.integrate(1.5 + 12, 3 + 12),
  351. xp.asarray(i(1) - i(0) + i(2) - i(1.5)))
  352. xp_assert_close(b.integrate(1.5, 3 + 12),
  353. xp.asarray(i(1) - i(0) + i(2) - i(1.5) + 6 * period_int))
  354. xp_assert_close(b.integrate(0, -1), xp.asarray(i(0) - i(1)))
  355. xp_assert_close(b.integrate(-9, -10), xp.asarray(i(0) - i(1)))
  356. xp_assert_close(b.integrate(0, -9),
  357. xp.asarray(i(1) - i(2) - 4 * period_int))
  358. def test_integrate_ppoly(self):
  359. # test .integrate method to be consistent with PPoly.integrate
  360. x = [0, 1, 2, 3, 4]
  361. b = make_interp_spline(x, x)
  362. b.extrapolate = 'periodic'
  363. p = PPoly.from_spline(b)
  364. for x0, x1 in [(-5, 0.5), (0.5, 5), (-4, 13)]:
  365. xp_assert_close(b.integrate(x0, x1),
  366. p.integrate(x0, x1))
  367. def test_integrate_0D_always(self):
  368. # make sure the result is always a 0D array (not a python scalar)
  369. b = BSpline.basis_element([0, 1, 2])
  370. for extrapolate in (True, False):
  371. res = b.integrate(0, 1, extrapolate=extrapolate)
  372. assert isinstance(res, np.ndarray)
  373. assert res.ndim == 0
  374. def test_subclassing(self):
  375. # classmethods should not decay to the base class
  376. class B(BSpline):
  377. pass
  378. b = B.basis_element([0, 1, 2, 2])
  379. assert b.__class__ == B
  380. assert b.derivative().__class__ == B
  381. assert b.antiderivative().__class__ == B
  382. @pytest.mark.parametrize('axis', range(-4, 4))
  383. def test_axis(self, axis, xp):
  384. n, k = 22, 3
  385. t = xp.linspace(0, 1, n + k + 1)
  386. sh = [6, 7, 8]
  387. # We need the positive axis for some of the indexing and slices used
  388. # in this test.
  389. pos_axis = axis % 4
  390. sh.insert(pos_axis, n) # [22, 6, 7, 8] etc
  391. sh = tuple(sh)
  392. rng = np.random.RandomState(1234)
  393. c = xp.asarray(rng.random(size=sh))
  394. b = BSpline(t, c, k, axis=axis)
  395. assert b.c.shape == (sh[pos_axis],) + sh[:pos_axis] + sh[pos_axis+1:]
  396. xp = rng.random((3, 4, 5))
  397. assert b(xp).shape == sh[:pos_axis] + xp.shape + sh[pos_axis+1:]
  398. # -c.ndim <= axis < c.ndim
  399. for ax in [-c.ndim - 1, c.ndim]:
  400. assert_raises(AxisError, BSpline,
  401. **dict(t=t, c=c, k=k, axis=ax))
  402. # derivative, antiderivative keeps the axis
  403. for b1 in [BSpline(t, c, k, axis=axis).derivative(),
  404. BSpline(t, c, k, axis=axis).derivative(2),
  405. BSpline(t, c, k, axis=axis).antiderivative(),
  406. BSpline(t, c, k, axis=axis).antiderivative(2)]:
  407. assert b1.axis == b.axis
  408. def test_neg_axis(self, xp):
  409. k = 2
  410. t = xp.asarray([0, 1, 2, 3, 4, 5, 6])
  411. c = xp.asarray([[-1, 2, 0, -1], [2, 0, -3, 1]])
  412. spl = BSpline(t, c, k, axis=-1)
  413. spl0 = BSpline(t, c[0, :], k)
  414. spl1 = BSpline(t, c[1, :], k)
  415. xp_assert_equal(spl(2.5), xp.stack([spl0(2.5), spl1(2.5)]))
  416. def test_design_matrix_bc_types(self):
  417. '''
  418. Splines with different boundary conditions are built on different
  419. types of vectors of knots. As far as design matrix depends only on
  420. vector of knots, `k` and `x` it is useful to make tests for different
  421. boundary conditions (and as following different vectors of knots).
  422. '''
  423. def run_design_matrix_tests(n, k, bc_type):
  424. '''
  425. To avoid repetition of code the following function is provided.
  426. '''
  427. rng = np.random.RandomState(1234)
  428. x = np.sort(rng.random_sample(n) * 40 - 20)
  429. y = rng.random_sample(n) * 40 - 20
  430. if bc_type == "periodic":
  431. y[0] = y[-1]
  432. bspl = make_interp_spline(x, y, k=k, bc_type=bc_type)
  433. c = np.eye(len(bspl.t) - k - 1)
  434. des_matr_def = BSpline(bspl.t, c, k)(x)
  435. des_matr_csr = BSpline.design_matrix(x,
  436. bspl.t,
  437. k).toarray()
  438. xp_assert_close(des_matr_csr @ bspl.c, y, atol=1e-14)
  439. xp_assert_close(des_matr_def, des_matr_csr, atol=1e-14)
  440. # "clamped" and "natural" work only with `k = 3`
  441. n = 11
  442. k = 3
  443. for bc in ["clamped", "natural"]:
  444. run_design_matrix_tests(n, k, bc)
  445. # "not-a-knot" works with odd `k`
  446. for k in range(3, 8, 2):
  447. run_design_matrix_tests(n, k, "not-a-knot")
  448. # "periodic" works with any `k` (even more than `n`)
  449. n = 5 # smaller `n` to test `k > n` case
  450. for k in range(2, 7):
  451. run_design_matrix_tests(n, k, "periodic")
  452. @pytest.mark.parametrize('extrapolate', [False, True, 'periodic'])
  453. @pytest.mark.parametrize('degree', range(5))
  454. def test_design_matrix_same_as_BSpline_call(self, extrapolate, degree):
  455. """Test that design_matrix(x) is equivalent to BSpline(..)(x)."""
  456. rng = np.random.RandomState(1234)
  457. x = rng.random_sample(10 * (degree + 1))
  458. xmin, xmax = np.amin(x), np.amax(x)
  459. k = degree
  460. t = np.r_[np.linspace(xmin - 2, xmin - 1, degree),
  461. np.linspace(xmin, xmax, 2 * (degree + 1)),
  462. np.linspace(xmax + 1, xmax + 2, degree)]
  463. c = np.eye(len(t) - k - 1)
  464. bspline = BSpline(t, c, k, extrapolate)
  465. xp_assert_close(
  466. bspline(x), BSpline.design_matrix(x, t, k, extrapolate).toarray()
  467. )
  468. # extrapolation regime
  469. x = np.array([xmin - 10, xmin - 1, xmax + 1.5, xmax + 10])
  470. if not extrapolate:
  471. with pytest.raises(ValueError):
  472. BSpline.design_matrix(x, t, k, extrapolate)
  473. else:
  474. xp_assert_close(
  475. bspline(x),
  476. BSpline.design_matrix(x, t, k, extrapolate).toarray()
  477. )
  478. def test_design_matrix_x_shapes(self):
  479. # test for different `x` shapes
  480. rng = np.random.RandomState(1234)
  481. n = 10
  482. k = 3
  483. x = np.sort(rng.random_sample(n) * 40 - 20)
  484. y = rng.random_sample(n) * 40 - 20
  485. bspl = make_interp_spline(x, y, k=k)
  486. for i in range(1, 4):
  487. xc = x[:i]
  488. yc = y[:i]
  489. des_matr_csr = BSpline.design_matrix(xc,
  490. bspl.t,
  491. k).toarray()
  492. xp_assert_close(des_matr_csr @ bspl.c, yc, atol=1e-14)
  493. def test_design_matrix_t_shapes(self):
  494. # test for minimal possible `t` shape
  495. t = [1., 1., 1., 2., 3., 4., 4., 4.]
  496. des_matr = BSpline.design_matrix(2., t, 3).toarray()
  497. xp_assert_close(des_matr,
  498. [[0.25, 0.58333333, 0.16666667, 0.]],
  499. atol=1e-14)
  500. def test_design_matrix_asserts(self):
  501. rng = np.random.RandomState(1234)
  502. n = 10
  503. k = 3
  504. x = np.sort(rng.random_sample(n) * 40 - 20)
  505. y = rng.random_sample(n) * 40 - 20
  506. bspl = make_interp_spline(x, y, k=k)
  507. # invalid vector of knots (should be a 1D non-descending array)
  508. # here the actual vector of knots is reversed, so it is invalid
  509. with assert_raises(ValueError):
  510. BSpline.design_matrix(x, bspl.t[::-1], k)
  511. k = 2
  512. t = [0., 1., 2., 3., 4., 5.]
  513. x = [1., 2., 3., 4.]
  514. # out of bounds
  515. with assert_raises(ValueError):
  516. BSpline.design_matrix(x, t, k)
  517. @pytest.mark.parametrize('bc_type', ['natural', 'clamped',
  518. 'periodic', 'not-a-knot'])
  519. def test_from_power_basis(self, bc_type):
  520. # TODO: convert CubicSpline
  521. rng = np.random.RandomState(1234)
  522. x = np.sort(rng.random(20))
  523. y = rng.random(20)
  524. if bc_type == 'periodic':
  525. y[-1] = y[0]
  526. cb = CubicSpline(x, y, bc_type=bc_type)
  527. bspl = BSpline.from_power_basis(cb, bc_type=bc_type)
  528. xx = np.linspace(0, 1, 20)
  529. xp_assert_close(cb(xx), bspl(xx), atol=1e-15)
  530. bspl_new = make_interp_spline(x, y, bc_type=bc_type)
  531. xp_assert_close(bspl.c, bspl_new.c, atol=1e-15)
  532. @pytest.mark.parametrize('bc_type', ['natural', 'clamped',
  533. 'periodic', 'not-a-knot'])
  534. def test_from_power_basis_complex(self, bc_type):
  535. # TODO: convert CubicSpline
  536. rng = np.random.RandomState(1234)
  537. x = np.sort(rng.random(20))
  538. y = rng.random(20) + rng.random(20) * 1j
  539. if bc_type == 'periodic':
  540. y[-1] = y[0]
  541. cb = CubicSpline(x, y, bc_type=bc_type)
  542. bspl = BSpline.from_power_basis(cb, bc_type=bc_type)
  543. bspl_new_real = make_interp_spline(x, y.real, bc_type=bc_type)
  544. bspl_new_imag = make_interp_spline(x, y.imag, bc_type=bc_type)
  545. xp_assert_close(bspl.c, bspl_new_real.c + 1j * bspl_new_imag.c, atol=1e-15)
  546. def test_from_power_basis_exmp(self):
  547. '''
  548. For x = [0, 1, 2, 3, 4] and y = [1, 1, 1, 1, 1]
  549. the coefficients of Cubic Spline in the power basis:
  550. $[[0, 0, 0, 0, 0],\\$
  551. $[0, 0, 0, 0, 0],\\$
  552. $[0, 0, 0, 0, 0],\\$
  553. $[1, 1, 1, 1, 1]]$
  554. It could be shown explicitly that coefficients of the interpolating
  555. function in B-spline basis are c = [1, 1, 1, 1, 1, 1, 1]
  556. '''
  557. x = np.array([0, 1, 2, 3, 4])
  558. y = np.array([1, 1, 1, 1, 1])
  559. bspl = BSpline.from_power_basis(CubicSpline(x, y, bc_type='natural'),
  560. bc_type='natural')
  561. xp_assert_close(bspl.c, [1.0, 1, 1, 1, 1, 1, 1], atol=1e-15)
  562. def test_read_only(self):
  563. # BSpline must work on read-only knots and coefficients.
  564. t = np.array([0, 1])
  565. c = np.array([3.0])
  566. t.setflags(write=False)
  567. c.setflags(write=False)
  568. xx = np.linspace(0, 1, 10)
  569. xx.setflags(write=False)
  570. b = BSpline(t=t, c=c, k=0)
  571. xp_assert_close(b(xx), np.ones_like(xx) * 3.0)
  572. def test_concurrency(self, xp):
  573. # Check that no segfaults appear with concurrent access to BSpline
  574. b = _make_random_spline(xp=xp)
  575. def worker_fn(_, b):
  576. t, _, k = b.tck
  577. xx = xp.linspace(t[k], t[-k-1], 10000)
  578. b(xx)
  579. _run_concurrent_barrier(10, worker_fn, b)
  580. @pytest.mark.xfail(
  581. sys.platform == "cygwin",
  582. reason="threading.get_native_id not implemented",
  583. raises=AttributeError
  584. )
  585. def test_memmap(self, tmpdir):
  586. # Make sure that memmaps can be used as t and c atrributes after the
  587. # spline has been constructed. This is similar to what happens in a
  588. # scikit-learn context, where joblib can create read-only memmap to
  589. # share objects between workers. For more details, see
  590. # https://github.com/scipy/scipy/issues/22143
  591. b = _make_random_spline()
  592. xx = np.linspace(0, 1, 10)
  593. expected = b(xx)
  594. tid = threading.get_native_id()
  595. t_mm = np.memmap(str(tmpdir.join(f't{tid}.dat')), mode='w+',
  596. dtype=b.t.dtype, shape=b.t.shape)
  597. t_mm[:] = b.t
  598. c_mm = np.memmap(str(tmpdir.join(f'c{tid}.dat')), mode='w+',
  599. dtype=b.c.dtype, shape=b.c.shape)
  600. c_mm[:] = b.c
  601. b.t = t_mm
  602. b.c = c_mm
  603. xp_assert_close(b(xx), expected)
  604. @make_xp_test_case(BSpline)
  605. class TestInsert:
  606. @pytest.mark.parametrize('xval', [0.0, 1.0, 2.5, 4, 6.5, 7.0])
  607. def test_insert(self, xval, xp):
  608. # insert a knot, incl edges (0.0, 7.0) and exactly at an existing knot (4.0)
  609. x = xp.arange(8, dtype=xp.float64)
  610. y = xp.sin(x)**3
  611. spl = make_interp_spline(x, y, k=3)
  612. tck = (spl._t, spl._c, spl.k)
  613. spl_1f = BSpline(*insert(xval, tck)) # FITPACK
  614. spl_1 = spl.insert_knot(xval)
  615. xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15)
  616. xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15)
  617. # knot insertion preserves values, unless multiplicity >= k+1
  618. xx = x if xval != x[-1] else x[:-1]
  619. xx = xp.concat((xx, 0.5*(x[1:] + x[:-1])))
  620. xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
  621. # ... repeat with ndim > 1
  622. y1 = xp.cos(x)**3
  623. spl_y1 = make_interp_spline(x, y1, k=3)
  624. spl_yy = make_interp_spline(x, xp.stack((y, y1), axis=1), k=3)
  625. spl_yy1 = spl_yy.insert_knot(xval)
  626. xp_assert_close(spl_yy1.t, spl_1.t, atol=1e-15)
  627. xp_assert_close(
  628. spl_yy1.c,
  629. xp.stack((spl.insert_knot(xval).c, spl_y1.insert_knot(xval).c), axis=1),
  630. atol=1e-15
  631. )
  632. xx = x if xval != x[-1] else x[:-1]
  633. xx = xp.concat((xx, 0.5*(x[1:] + x[:-1])))
  634. xp_assert_close(spl_yy(xx), spl_yy1(xx), atol=1e-15)
  635. @pytest.mark.parametrize(
  636. 'xval, m', [(0.0, 2), (1.0, 3), (1.5, 5), (4, 2), (7.0, 2)]
  637. )
  638. def test_insert_multi(self, xval, m, xp):
  639. x = xp.arange(8, dtype=xp.float64)
  640. y = xp.sin(x)**3
  641. spl = make_interp_spline(x, y, k=3)
  642. spl_1f = BSpline(*insert(xval, (spl._t, spl._c, spl.k), m=m))
  643. spl_1 = spl.insert_knot(xval, m)
  644. xp_assert_close(spl_1.t, xp.asarray(spl_1f.t), atol=1e-15)
  645. xp_assert_close(spl_1.c, xp.asarray(spl_1f.c[:-spl.k-1]), atol=1e-15)
  646. xx = x if xval != x[-1] else x[:-1]
  647. xx = xp.concat((xx, 0.5*(x[1:] + x[:-1])))
  648. xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
  649. def test_insert_random(self, xp):
  650. rng = np.random.default_rng(12345)
  651. n, k = 11, 3
  652. t = xp.asarray(np.sort(rng.uniform(size=n+k+1)))
  653. c = xp.asarray(rng.uniform(size=(n, 3, 2)))
  654. spl = BSpline(t, c, k)
  655. xv = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1]))
  656. spl_1 = spl.insert_knot(xv)
  657. xx = xp.asarray(rng.uniform(low=t[k+1], high=t[-k-1], size=33))
  658. xp_assert_close(spl(xx), spl_1(xx), atol=1e-15)
  659. @pytest.mark.parametrize('xv', [0, 0.1, 2.0, 4.0, 4.5, # l.h. edge
  660. 5.5, 6.0, 6.1, 7.0] # r.h. edge
  661. )
  662. def test_insert_periodic(self, xv, xp):
  663. x = xp.arange(8, dtype=xp.float64)
  664. y = xp.sin(x)**3
  665. t, c, k = splrep(x, y, k=3)
  666. t, c = map(xp.asarray, (t, c))
  667. spl = BSpline(t, c, k, extrapolate="periodic")
  668. spl_1 = spl.insert_knot(xv)
  669. tf, cf, k = insert(xv, spl.tck, per=True)
  670. xp_assert_close(spl_1.t, xp.asarray(tf), atol=1e-15)
  671. xp_assert_close(spl_1.c[:-k-1], xp.asarray(cf[:-k-1]), atol=1e-15)
  672. xx_np = np.random.default_rng(1234).uniform(low=0, high=7, size=41)
  673. xx = xp.asarray(xx_np)
  674. xp_assert_close(spl_1(xx), xp.asarray(splev(xx_np, (tf, cf, k))), atol=1e-15)
  675. @pytest.mark.parametrize('extrapolate', [None, 'periodic'])
  676. def test_complex(self, extrapolate, xp):
  677. x = xp.arange(8, dtype=xp.float64) * 2 * np.pi
  678. y_re, y_im = xp.sin(x), xp.cos(x)
  679. spl = make_interp_spline(x, y_re + 1j*y_im, k=3)
  680. spl.extrapolate = extrapolate
  681. spl_re = make_interp_spline(x, y_re, k=3)
  682. spl_re.extrapolate = extrapolate
  683. spl_im = make_interp_spline(x, y_im, k=3)
  684. spl_im.extrapolate = extrapolate
  685. xv = 3.5
  686. spl_1 = spl.insert_knot(xv)
  687. spl_1re = spl_re.insert_knot(xv)
  688. spl_1im = spl_im.insert_knot(xv)
  689. xp_assert_close(spl_1.t, spl_1re.t, atol=1e-15)
  690. xp_assert_close(spl_1.t, spl_1im.t, atol=1e-15)
  691. xp_assert_close(spl_1.c, spl_1re.c + 1j*spl_1im.c, atol=1e-15)
  692. def test_insert_periodic_too_few_internal_knots(self):
  693. # both FITPACK and spl.insert_knot raise when there's not enough
  694. # internal knots to make a periodic extension.
  695. # Below the internal knots are 2, 3, , 4, 5
  696. # ^
  697. # 2, 3, 3.5, 4, 5
  698. # so two knots from each side from the new one, while need at least
  699. # from either left or right.
  700. xv = 3.5
  701. k = 3
  702. t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1))
  703. c = np.ones(len(t) - k - 1)
  704. spl = BSpline(t, c, k, extrapolate="periodic")
  705. with assert_raises(ValueError):
  706. insert(xv, (t, c, k), per=True)
  707. with assert_raises(ValueError):
  708. spl.insert_knot(xv)
  709. def test_insert_no_extrap(self):
  710. k = 3
  711. t = np.array([0]*(k+1) + [2, 3, 4, 5] + [7]*(k+1))
  712. c = np.ones(len(t) - k - 1)
  713. spl = BSpline(t, c, k)
  714. with assert_raises(ValueError):
  715. spl.insert_knot(-1)
  716. with assert_raises(ValueError):
  717. spl.insert_knot(8)
  718. with assert_raises(ValueError):
  719. spl.insert_knot(3, m=0)
  720. def test_knots_multiplicity():
  721. # Take a spline w/ random coefficients, throw in knots of varying
  722. # multiplicity.
  723. def check_splev(b, j, der=0, atol=1e-14, rtol=1e-14):
  724. # check evaluations against FITPACK, incl extrapolations
  725. t, c, k = b.tck
  726. x = np.unique(t)
  727. x = np.r_[t[0]-0.1, 0.5*(x[1:] + x[:1]), t[-1]+0.1]
  728. xp_assert_close(splev(x, (t, c, k), der), b(x, der),
  729. atol=atol, rtol=rtol, err_msg=f'der = {der} k = {b.k}')
  730. # test loop itself
  731. # [the index `j` is for interpreting the traceback in case of a failure]
  732. for k in [1, 2, 3, 4, 5]:
  733. b = _make_random_spline(k=k)
  734. for j, b1 in enumerate(_make_multiples(b)):
  735. check_splev(b1, j)
  736. for der in range(1, k+1):
  737. check_splev(b1, j, der, 1e-12, 1e-12)
  738. def _naive_B(x, k, i, t):
  739. """
  740. Naive way to compute B-spline basis functions. Useful only for testing!
  741. computes B(x; t[i],..., t[i+k+1])
  742. """
  743. if k == 0:
  744. return 1.0 if t[i] <= x < t[i+1] else 0.0
  745. if t[i+k] == t[i]:
  746. c1 = 0.0
  747. else:
  748. c1 = (x - t[i])/(t[i+k] - t[i]) * _naive_B(x, k-1, i, t)
  749. if t[i+k+1] == t[i+1]:
  750. c2 = 0.0
  751. else:
  752. c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * _naive_B(x, k-1, i+1, t)
  753. return (c1 + c2)
  754. def _naive_eval(x, t, c, k, *, xp):
  755. """
  756. Naive B-spline evaluation. Useful only for testing!
  757. """
  758. if x == t[k]:
  759. i = k
  760. else:
  761. i = xp.searchsorted(t, x) - 1
  762. assert t[i] <= x <= t[i+1]
  763. assert i >= k and i < t.shape[0] - k
  764. return sum(c[i-j] * _naive_B(x, k, i-j, t) for j in range(0, k+1))
  765. def _naive_eval_2(x, t, c, k, *, xp):
  766. """Naive B-spline evaluation, another way."""
  767. n = t.shape[0] - (k+1)
  768. assert n >= k+1
  769. assert c.shape[0] >= n
  770. assert t[k] <= x <= t[n]
  771. return sum(c[i] * _naive_B(x, k, i, t) for i in range(n))
  772. def _sum_basis_elements(x, t, c, k):
  773. n = len(t) - (k+1)
  774. assert n >= k+1
  775. assert c.shape[0] >= n
  776. s = 0.
  777. for i in range(n):
  778. b = BSpline.basis_element(t[i:i+k+2], extrapolate=False)(x)
  779. s += c[i] * np.nan_to_num(b) # zero out out-of-bounds elements
  780. return s
  781. def B_012(x, xp=np):
  782. """ A linear B-spline function B(x | 0, 1, 2)."""
  783. x = np.atleast_1d(x)
  784. result = np.piecewise(x, [(x < 0) | (x > 2),
  785. (x >= 0) & (x < 1),
  786. (x >= 1) & (x <= 2)],
  787. [lambda x: 0., lambda x: x, lambda x: 2.-x])
  788. return xp.asarray(result)
  789. def B_0123(x, der=0):
  790. """A quadratic B-spline function B(x | 0, 1, 2, 3)."""
  791. x = np.atleast_1d(x)
  792. conds = [x < 1, (x > 1) & (x < 2), x > 2]
  793. if der == 0:
  794. funcs = [lambda x: x*x/2.,
  795. lambda x: 3./4 - (x-3./2)**2,
  796. lambda x: (3.-x)**2 / 2]
  797. elif der == 2:
  798. funcs = [lambda x: 1.,
  799. lambda x: -2.,
  800. lambda x: 1.]
  801. else:
  802. raise ValueError(f'never be here: der={der}')
  803. pieces = np.piecewise(x, conds, funcs)
  804. return pieces
  805. def _make_random_spline(n=35, k=3, xp=np):
  806. rng = np.random.RandomState(123)
  807. t = np.sort(rng.random(n+k+1))
  808. c = rng.random(n)
  809. t, c = xp.asarray(t), xp.asarray(c)
  810. return BSpline.construct_fast(t, c, k)
  811. def _make_multiples(b):
  812. """Increase knot multiplicity."""
  813. c, k = b.c, b.k
  814. t1 = b.t.copy()
  815. t1[17:19] = t1[17]
  816. t1[22] = t1[21]
  817. yield BSpline(t1, c, k)
  818. t1 = b.t.copy()
  819. t1[:k+1] = t1[0]
  820. yield BSpline(t1, c, k)
  821. t1 = b.t.copy()
  822. t1[-k-1:] = t1[-1]
  823. yield BSpline(t1, c, k)
  824. class TestInterop:
  825. #
  826. # Test that FITPACK-based spl* functions can deal with BSpline objects
  827. #
  828. def setup_method(self):
  829. xx = np.linspace(0, 4.*np.pi, 41)
  830. yy = np.cos(xx)
  831. b = make_interp_spline(xx, yy)
  832. self.tck = (b.t, b.c, b.k)
  833. self.xx, self.yy, self.b = xx, yy, b
  834. self.xnew = np.linspace(0, 4.*np.pi, 21)
  835. c2 = np.c_[b.c, b.c, b.c]
  836. self.c2 = np.dstack((c2, c2))
  837. self.b2 = BSpline(b.t, self.c2, b.k)
  838. def test_splev(self):
  839. xnew, b, b2 = self.xnew, self.b, self.b2
  840. # check that splev works with 1-D array of coefficients
  841. # for array and scalar `x`
  842. xp_assert_close(splev(xnew, b),
  843. b(xnew), atol=1e-15, rtol=1e-15)
  844. xp_assert_close(splev(xnew, b.tck),
  845. b(xnew), atol=1e-15, rtol=1e-15)
  846. xp_assert_close(np.asarray([splev(x, b) for x in xnew]),
  847. b(xnew), atol=1e-15, rtol=1e-15)
  848. # With N-D coefficients, there's a quirck:
  849. # splev(x, BSpline) is equivalent to BSpline(x)
  850. with assert_raises(ValueError, match="Calling splev.. with BSpline"):
  851. splev(xnew, b2)
  852. # However, splev(x, BSpline.tck) needs some transposes. This is because
  853. # BSpline interpolates along the first axis, while the legacy FITPACK
  854. # wrapper does list(map(...)) which effectively interpolates along the
  855. # last axis. Like so:
  856. sh = tuple(range(1, b2.c.ndim)) + (0,) # sh = (1, 2, 0)
  857. cc = b2.c.transpose(sh)
  858. tck = (b2.t, cc, b2.k)
  859. xp_assert_close(np.asarray(splev(xnew, tck)),
  860. b2(xnew).transpose(sh), atol=1e-15, rtol=1e-15)
  861. def test_splrep(self):
  862. x, y = self.xx, self.yy
  863. # test that "new" splrep is equivalent to _impl.splrep
  864. tck = splrep(x, y)
  865. t, c, k = _impl.splrep(x, y)
  866. xp_assert_close(tck[0], t, atol=1e-15)
  867. xp_assert_close(tck[1], c, atol=1e-15)
  868. assert tck[2] == k
  869. # also cover the `full_output=True` branch
  870. tck_f, _, _, _ = splrep(x, y, full_output=True)
  871. xp_assert_close(tck_f[0], t, atol=1e-15)
  872. xp_assert_close(tck_f[1], c, atol=1e-15)
  873. assert tck_f[2] == k
  874. # test that the result of splrep roundtrips with splev:
  875. # evaluate the spline on the original `x` points
  876. yy = splev(x, tck)
  877. xp_assert_close(y, yy, atol=1e-15)
  878. # ... and also it roundtrips if wrapped in a BSpline
  879. b = BSpline(*tck)
  880. xp_assert_close(y, b(x), atol=1e-15)
  881. def test_splrep_errors(self):
  882. # test that both "old" and "new" splrep raise for an N-D ``y`` array
  883. # with n > 1
  884. x, y = self.xx, self.yy
  885. y2 = np.c_[y, y]
  886. with assert_raises(ValueError):
  887. splrep(x, y2)
  888. with assert_raises(ValueError):
  889. _impl.splrep(x, y2)
  890. # input below minimum size
  891. with assert_raises(TypeError, match="m > k must hold"):
  892. splrep(x[:3], y[:3])
  893. with assert_raises(TypeError, match="m > k must hold"):
  894. _impl.splrep(x[:3], y[:3])
  895. def test_splprep(self):
  896. x = np.arange(15, dtype=np.float64).reshape((3, 5))
  897. b, u = splprep(x)
  898. tck, u1 = _impl.splprep(x)
  899. # test the roundtrip with splev for both "old" and "new" output
  900. xp_assert_close(u, u1, atol=1e-15)
  901. xp_assert_close(np.asarray(splev(u, b)), x, atol=1e-15)
  902. xp_assert_close(np.asarray(splev(u, tck)), x, atol=1e-15)
  903. # cover the ``full_output=True`` branch
  904. (b_f, u_f), _, _, _ = splprep(x, s=0, full_output=True)
  905. xp_assert_close(u, u_f, atol=1e-15)
  906. xp_assert_close(np.asarray(splev(u_f, b_f)), x, atol=1e-15)
  907. def test_splprep_errors(self):
  908. # test that both "old" and "new" code paths raise for x.ndim > 2
  909. x = np.arange(3*4*5).reshape((3, 4, 5))
  910. with assert_raises(ValueError, match="too many values to unpack"):
  911. splprep(x)
  912. with assert_raises(ValueError, match="too many values to unpack"):
  913. _impl.splprep(x)
  914. # input below minimum size
  915. x = np.linspace(0, 40, num=3)
  916. with assert_raises(TypeError, match="m > k must hold"):
  917. splprep([x])
  918. with assert_raises(TypeError, match="m > k must hold"):
  919. _impl.splprep([x])
  920. # automatically calculated parameters are non-increasing
  921. # see gh-7589
  922. x = [-50.49072266, -50.49072266, -54.49072266, -54.49072266]
  923. with assert_raises(ValueError, match="Invalid inputs"):
  924. splprep([x])
  925. with assert_raises(ValueError, match="Invalid inputs"):
  926. _impl.splprep([x])
  927. # given non-increasing parameter values u
  928. x = [1, 3, 2, 4]
  929. u = [0, 0.3, 0.2, 1]
  930. with assert_raises(ValueError, match="Invalid inputs"):
  931. splprep(*[[x], None, u])
  932. def test_sproot(self):
  933. b, b2 = self.b, self.b2
  934. roots = np.array([0.5, 1.5, 2.5, 3.5])*np.pi
  935. # sproot accepts a BSpline obj w/ 1-D coef array
  936. xp_assert_close(sproot(b), roots, atol=1e-7, rtol=1e-7)
  937. xp_assert_close(sproot((b.t, b.c, b.k)), roots, atol=1e-7, rtol=1e-7)
  938. # ... and deals with trailing dimensions if coef array is N-D
  939. with assert_raises(ValueError, match="Calling sproot.. with BSpline"):
  940. sproot(b2, mest=50)
  941. # and legacy behavior is preserved for a tck tuple w/ N-D coef
  942. c2r = b2.c.transpose(1, 2, 0)
  943. rr = np.asarray(sproot((b2.t, c2r, b2.k), mest=50))
  944. assert rr.shape == (3, 2, 4)
  945. xp_assert_close(rr - roots, np.zeros_like(rr), atol=1e-12)
  946. def test_splint(self):
  947. # test that splint accepts BSpline objects
  948. b, b2 = self.b, self.b2
  949. xp_assert_close(splint(0, 1, b),
  950. splint(0, 1, b.tck), atol=1e-14, check_0d=False)
  951. xp_assert_close(splint(0, 1, b),
  952. b.integrate(0, 1), atol=1e-14, check_0d=False)
  953. # ... and deals with N-D arrays of coefficients
  954. with assert_raises(ValueError, match="Calling splint.. with BSpline"):
  955. splint(0, 1, b2)
  956. # and the legacy behavior is preserved for a tck tuple w/ N-D coef
  957. c2r = b2.c.transpose(1, 2, 0)
  958. integr = np.asarray(splint(0, 1, (b2.t, c2r, b2.k)))
  959. assert integr.shape == (3, 2)
  960. xp_assert_close(integr,
  961. splint(0, 1, b), atol=1e-14, check_shape=False)
  962. def test_splder(self):
  963. for b in [self.b, self.b2]:
  964. # pad the c array (FITPACK convention)
  965. ct = len(b.t) - len(b.c)
  966. b_c = b.c.copy()
  967. if ct > 0:
  968. b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])]
  969. for n in [1, 2, 3]:
  970. bd = splder(b)
  971. tck_d = _impl.splder((b.t.copy(), b_c, b.k))
  972. xp_assert_close(bd.t, tck_d[0], atol=1e-15)
  973. xp_assert_close(bd.c, tck_d[1], atol=1e-15)
  974. assert bd.k == tck_d[2]
  975. assert isinstance(bd, BSpline)
  976. assert isinstance(tck_d, tuple) # back-compat: tck in and out
  977. def test_splantider(self):
  978. for b in [self.b, self.b2]:
  979. # pad the c array (FITPACK convention)
  980. ct = len(b.t) - len(b.c)
  981. b_c = b.c.copy()
  982. if ct > 0:
  983. b_c = np.r_[b_c, np.zeros((ct,) + b_c.shape[1:])]
  984. for n in [1, 2, 3]:
  985. bd = splantider(b)
  986. tck_d = _impl.splantider((b.t.copy(), b_c, b.k))
  987. xp_assert_close(bd.t, tck_d[0], atol=1e-15)
  988. xp_assert_close(bd.c, tck_d[1], atol=1e-15)
  989. assert bd.k == tck_d[2]
  990. assert isinstance(bd, BSpline)
  991. assert isinstance(tck_d, tuple) # back-compat: tck in and out
  992. def test_insert(self):
  993. b, b2, xx = self.b, self.b2, self.xx
  994. j = b.t.size // 2
  995. tn = 0.5*(b.t[j] + b.t[j+1])
  996. bn, tck_n = insert(tn, b), insert(tn, (b.t, b.c, b.k))
  997. xp_assert_close(splev(xx, bn),
  998. splev(xx, tck_n), atol=1e-15)
  999. assert isinstance(bn, BSpline)
  1000. assert isinstance(tck_n, tuple) # back-compat: tck in, tck out
  1001. # for N-D array of coefficients, BSpline.c needs to be transposed
  1002. # after that, the results are equivalent.
  1003. sh = tuple(range(b2.c.ndim))
  1004. c_ = b2.c.transpose(sh[1:] + (0,))
  1005. tck_n2 = insert(tn, (b2.t, c_, b2.k))
  1006. bn2 = insert(tn, b2)
  1007. # need a transpose for comparing the results, cf test_splev
  1008. xp_assert_close(np.asarray(splev(xx, tck_n2)).transpose(2, 0, 1),
  1009. bn2(xx), atol=1e-15)
  1010. assert isinstance(bn2, BSpline)
  1011. assert isinstance(tck_n2, tuple) # back-compat: tck in, tck out
  1012. @make_xp_test_case(make_interp_spline)
  1013. class TestInterp:
  1014. #
  1015. # Test basic ways of constructing interpolating splines.
  1016. #
  1017. xx = np.linspace(0., 2.*np.pi)
  1018. yy = np.sin(xx)
  1019. def _get_xy(self, xp):
  1020. return xp.asarray(self.xx), xp.asarray(self.yy)
  1021. def test_non_int_order(self):
  1022. with assert_raises(TypeError):
  1023. make_interp_spline(self.xx, self.yy, k=2.5)
  1024. def test_order_0(self, xp):
  1025. xx, yy = self._get_xy(xp)
  1026. b = make_interp_spline(xx, yy, k=0)
  1027. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1028. b = make_interp_spline(xx, yy, k=0, axis=-1)
  1029. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1030. def test_linear(self, xp):
  1031. xx, yy = self._get_xy(xp)
  1032. b = make_interp_spline(xx, yy, k=1)
  1033. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1034. b = make_interp_spline(xx, yy, k=1, axis=-1)
  1035. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1036. @pytest.mark.parametrize('k', [0, 1, 2, 3])
  1037. def test_incompatible_x_y(self, k):
  1038. x = [0, 1, 2, 3, 4, 5]
  1039. y = [0, 1, 2, 3, 4, 5, 6, 7]
  1040. with assert_raises(ValueError, match="Shapes of x"):
  1041. make_interp_spline(x, y, k=k)
  1042. @pytest.mark.parametrize('k', [0, 1, 2, 3])
  1043. def test_broken_x(self, k):
  1044. x = [0, 1, 1, 2, 3, 4] # duplicates
  1045. y = [0, 1, 2, 3, 4, 5]
  1046. with assert_raises(ValueError, match="x to not have duplicates"):
  1047. make_interp_spline(x, y, k=k)
  1048. x = [0, 2, 1, 3, 4, 5] # unsorted
  1049. with assert_raises(ValueError, match="Expect x to be a 1D strictly"):
  1050. make_interp_spline(x, y, k=k)
  1051. x = [0, 1, 2, 3, 4, 5]
  1052. x = np.asarray(x).reshape((1, -1)) # 1D
  1053. with assert_raises(ValueError, match="Expect x to be a 1D strictly"):
  1054. make_interp_spline(x, y, k=k)
  1055. def test_not_a_knot(self, xp):
  1056. xx, yy = self._get_xy(xp)
  1057. for k in [2, 3, 4, 5, 6, 7]:
  1058. b = make_interp_spline(xx, yy, k)
  1059. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1060. def test_periodic(self, xp):
  1061. xx, yy = self._get_xy(xp)
  1062. # k = 5 here for more derivatives
  1063. b = make_interp_spline(xx, yy, k=5, bc_type='periodic')
  1064. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1065. # in periodic case it is expected equality of k-1 first
  1066. # derivatives at the boundaries
  1067. for i in range(1, 5):
  1068. xp_assert_close(b(xx[0], nu=i), b(xx[-1], nu=i), atol=1e-11)
  1069. # tests for axis=-1
  1070. b = make_interp_spline(xx, yy, k=5, bc_type='periodic', axis=-1)
  1071. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1072. for i in range(1, 5):
  1073. xp_assert_close(b(xx[0], nu=i), b(xx[-1], nu=i), atol=1e-11)
  1074. @pytest.mark.parametrize('k', [2, 3, 4, 5, 6, 7])
  1075. def test_periodic_random(self, k, xp):
  1076. # tests for both cases (k > n and k <= n)
  1077. n = 5
  1078. rng = np.random.RandomState(1234)
  1079. x = np.sort(rng.random_sample(n) * 10)
  1080. y = rng.random_sample(n) * 100
  1081. y[0] = y[-1]
  1082. x, y = xp.asarray(x), xp.asarray(y)
  1083. b = make_interp_spline(x, y, k=k, bc_type='periodic')
  1084. xp_assert_close(b(x), y, atol=1e-14)
  1085. def test_periodic_axis(self, xp):
  1086. n = self.xx.shape[0]
  1087. rng = np.random.RandomState(1234)
  1088. x = rng.random_sample(n) * 2 * np.pi
  1089. x = np.sort(x)
  1090. x[0] = 0.
  1091. x[-1] = 2 * np.pi
  1092. y = np.zeros((2, n))
  1093. y[0] = np.sin(x)
  1094. y[1] = np.cos(x)
  1095. x, y = xp.asarray(x), xp.asarray(y)
  1096. b = make_interp_spline(x, y, k=5, bc_type='periodic', axis=1)
  1097. for i in range(n):
  1098. xp_assert_close(b(x[i]), y[:, i], atol=1e-14)
  1099. xp_assert_close(b(x[0]), b(x[-1]), atol=1e-14)
  1100. def test_periodic_points_exception(self):
  1101. # first and last points should match when periodic case expected
  1102. rng = np.random.RandomState(1234)
  1103. k = 5
  1104. n = 8
  1105. x = np.sort(rng.random_sample(n))
  1106. y = rng.random_sample(n)
  1107. y[0] = y[-1] - 1 # to be sure that they are not equal
  1108. with assert_raises(ValueError):
  1109. make_interp_spline(x, y, k=k, bc_type='periodic')
  1110. def test_periodic_knots_exception(self):
  1111. # `periodic` case does not work with passed vector of knots
  1112. rng = np.random.RandomState(1234)
  1113. k = 3
  1114. n = 7
  1115. x = np.sort(rng.random_sample(n))
  1116. y = rng.random_sample(n)
  1117. t = np.zeros(n + 2 * k)
  1118. with assert_raises(ValueError):
  1119. make_interp_spline(x, y, k, t, 'periodic')
  1120. @pytest.mark.parametrize('k', [2, 3, 4, 5])
  1121. def test_periodic_splev(self, k):
  1122. # comparison values of periodic b-spline with splev
  1123. b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic')
  1124. tck = splrep(self.xx, self.yy, per=True, k=k)
  1125. spl = splev(self.xx, tck)
  1126. xp_assert_close(spl, b(self.xx), atol=1e-14)
  1127. # comparison derivatives of periodic b-spline with splev
  1128. for i in range(1, k):
  1129. spl = splev(self.xx, tck, der=i)
  1130. xp_assert_close(spl, b(self.xx, nu=i), atol=1e-10)
  1131. def test_periodic_cubic(self):
  1132. # comparison values of cubic periodic b-spline with CubicSpline
  1133. b = make_interp_spline(self.xx, self.yy, k=3, bc_type='periodic')
  1134. cub = CubicSpline(self.xx, self.yy, bc_type='periodic')
  1135. xp_assert_close(b(self.xx), cub(self.xx), atol=1e-14)
  1136. # edge case: Cubic interpolation on 3 points
  1137. rng = np.random.RandomState(1234)
  1138. n = 3
  1139. x = np.sort(rng.random_sample(n) * 10)
  1140. y = rng.random_sample(n) * 100
  1141. y[0] = y[-1]
  1142. b = make_interp_spline(x, y, k=3, bc_type='periodic')
  1143. cub = CubicSpline(x, y, bc_type='periodic')
  1144. xp_assert_close(b(x), cub(x), atol=1e-14)
  1145. def test_periodic_full_matrix(self):
  1146. # comparison values of cubic periodic b-spline with
  1147. # solution of the system with full matrix
  1148. k = 3
  1149. b = make_interp_spline(self.xx, self.yy, k=k, bc_type='periodic')
  1150. t = _periodic_knots(self.xx, k)
  1151. c = _make_interp_per_full_matr(self.xx, self.yy, t, k)
  1152. b1 = np.vectorize(lambda x: _naive_eval(x, t, c, k, xp=np))
  1153. xp_assert_close(b(self.xx), b1(self.xx), atol=1e-14)
  1154. def test_quadratic_deriv(self, xp):
  1155. xx, yy = self._get_xy(xp)
  1156. der = [(1, 8.)] # order, value: f'(x) = 8.
  1157. # derivative at right-hand edge
  1158. b = make_interp_spline(xx, yy, k=2, bc_type=(None, der))
  1159. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1160. xp_assert_close(
  1161. b(xx[-1], 1),
  1162. xp.asarray(der[0][1], dtype=xp.float64),
  1163. atol=1e-14, rtol=1e-14, check_0d=False
  1164. )
  1165. # derivative at left-hand edge
  1166. b = make_interp_spline(xx, yy, k=2, bc_type=(der, None))
  1167. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1168. xp_assert_close(
  1169. b(xx[0], 1),
  1170. xp.asarray(der[0][1], dtype=xp.float64),
  1171. atol=1e-14, rtol=1e-14, check_0d=False
  1172. )
  1173. def test_cubic_deriv(self, xp):
  1174. xx, yy = self._get_xy(xp)
  1175. k = 3
  1176. # first derivatives at left & right edges:
  1177. der_l, der_r = [(1, 3.)], [(1, 4.)]
  1178. b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
  1179. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1180. xp_assert_close(
  1181. b(xx[0], 1),
  1182. xp.asarray(der_l[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
  1183. )
  1184. xp_assert_close(
  1185. b(xx[-1], 1),
  1186. xp.asarray(der_r[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
  1187. )
  1188. # 'natural' cubic spline, zero out 2nd derivatives at the boundaries
  1189. der_l, der_r = [(2, 0)], [(2, 0)]
  1190. b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
  1191. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1192. def test_quintic_derivs(self, xp):
  1193. k, n = 5, 7
  1194. x = xp.arange(n, dtype=xp.float64)
  1195. y = xp.sin(x)
  1196. der_l = [(1, -12.), (2, 1)]
  1197. der_r = [(1, 8.), (2, 3.)]
  1198. b = make_interp_spline(x, y, k=k, bc_type=(der_l, der_r))
  1199. xp_assert_close(b(x), y, atol=1e-14, rtol=1e-14)
  1200. xp_assert_close(xp.stack([b(x[0], 1), b(x[0], 2)]),
  1201. xp.asarray([val for (nu, val) in der_l], dtype=xp.float64))
  1202. xp_assert_close(xp.stack([b(x[-1], 1), b(x[-1], 2)]),
  1203. xp.asarray([val for (nu, val) in der_r], dtype=xp.float64))
  1204. @pytest.mark.xfail(reason='unstable')
  1205. def test_cubic_deriv_unstable(self):
  1206. # 1st and 2nd derivative at x[0], no derivative information at x[-1]
  1207. # The problem is not that it fails [who would use this anyway],
  1208. # the problem is that it fails *silently*, and I've no idea
  1209. # how to detect this sort of instability.
  1210. # In this particular case: it's OK for len(t) < 20, goes haywire
  1211. # at larger `len(t)`.
  1212. k = 3
  1213. t = _augknt(self.xx, k)
  1214. der_l = [(1, 3.), (2, 4.)]
  1215. b = make_interp_spline(self.xx, self.yy, k, t, bc_type=(der_l, None))
  1216. xp_assert_close(b(self.xx), self.yy, atol=1e-14, rtol=1e-14)
  1217. def test_knots_not_data_sites(self, xp):
  1218. # Knots need not coincide with the data sites.
  1219. # use a quadratic spline, knots are at data averages,
  1220. # two additional constraints are zero 2nd derivatives at edges
  1221. k = 2
  1222. xx, yy = self._get_xy(xp)
  1223. t = concat_1d(xp,
  1224. xp.ones(k+1) * xx[0],
  1225. (xx[1:] + xx[:-1]) / 2.,
  1226. xp.ones(k+1) * xx[-1]
  1227. )
  1228. b = make_interp_spline(xx, yy, k, t,
  1229. bc_type=([(2, 0)], [(2, 0)]))
  1230. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1231. assert math.isclose(b(xx[0], 2), 0.0, abs_tol=1e-14)
  1232. assert math.isclose(b(xx[-1], 2), 0.0, abs_tol=1e-14)
  1233. def test_minimum_points_and_deriv(self, xp):
  1234. # interpolation of f(x) = x**3 between 0 and 1. f'(x) = 3 * xx**2 and
  1235. # f'(0) = 0, f'(1) = 3.
  1236. k = 3
  1237. x = xp.asarray([0., 1.])
  1238. y = xp.asarray([0., 1.])
  1239. b = make_interp_spline(x, y, k, bc_type=([(1, 0.)], [(1, 3.)]))
  1240. xx = xp.linspace(0., 1., 21, dtype=xp.float64)
  1241. yy = xx**3
  1242. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1243. def test_deriv_spec(self):
  1244. # If one of the derivatives is omitted, the spline definition is
  1245. # incomplete.
  1246. x = y = [1.0, 2, 3, 4, 5, 6]
  1247. with assert_raises(ValueError):
  1248. make_interp_spline(x, y, bc_type=([(1, 0.)], None))
  1249. with assert_raises(ValueError):
  1250. make_interp_spline(x, y, bc_type=(1, 0.))
  1251. with assert_raises(ValueError):
  1252. make_interp_spline(x, y, bc_type=[(1, 0.)])
  1253. with assert_raises(ValueError):
  1254. make_interp_spline(x, y, bc_type=42)
  1255. # CubicSpline expects`bc_type=(left_pair, right_pair)`, while
  1256. # here we expect `bc_type=(iterable, iterable)`.
  1257. l, r = (1, 0.0), (1, 0.0)
  1258. with assert_raises(ValueError):
  1259. make_interp_spline(x, y, bc_type=(l, r))
  1260. def test_deriv_order_too_large(self, xp):
  1261. x = xp.arange(7)
  1262. y = x**2
  1263. l, r = [(6, 0)], [(1, 0)] # 6th derivative = 0 at x[0] for k=3
  1264. with assert_raises(ValueError, match="Bad boundary conditions at 0."):
  1265. # cannot fix 6th derivative at x[0]: does not segfault
  1266. make_interp_spline(x, y, bc_type=(l, r))
  1267. l, r = [(1, 0)], [(-6, 0)] # derivative order < 0 at x[-1]
  1268. with assert_raises(ValueError, match="Bad boundary conditions at 6."):
  1269. # does not segfault
  1270. make_interp_spline(x, y, bc_type=(l, r))
  1271. def test_complex(self, xp):
  1272. k = 3
  1273. xx, yy = self._get_xy(xp)
  1274. yy = yy + 1.j*yy
  1275. # first derivatives at left & right edges:
  1276. der_l, der_r = [(1, 3.j)], [(1, 4.+2.j)]
  1277. b = make_interp_spline(xx, yy, k, bc_type=(der_l, der_r))
  1278. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1279. assert cmath.isclose(b(xx[0], 1), der_l[0][1], abs_tol=1e-14)
  1280. assert cmath.isclose(b(xx[-1], 1), der_r[0][1], abs_tol=1e-14)
  1281. # also test zero and first order
  1282. for k in (0, 1):
  1283. b = make_interp_spline(xx, yy, k=k)
  1284. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1285. def test_int_xy(self, xp):
  1286. x = xp.arange(10, dtype=xp.int32)
  1287. y = xp.arange(10, dtype=xp.int32)
  1288. # Cython chokes on "buffer type mismatch" (construction) or
  1289. # "no matching signature found" (evaluation)
  1290. for k in (0, 1, 2, 3):
  1291. b = make_interp_spline(x, y, k=k)
  1292. b(x)
  1293. def test_sliced_input(self, xp):
  1294. # Cython code chokes on non C contiguous arrays
  1295. xx = xp.linspace(-1, 1, 100)
  1296. x = xx[::5]
  1297. y = xx[::5]
  1298. for k in (0, 1, 2, 3):
  1299. make_interp_spline(x, y, k=k)
  1300. def test_check_finite(self, xp):
  1301. # check_finite defaults to True; nans and such trigger a ValueError
  1302. x = xp.arange(10, dtype=xp.float64)
  1303. y = x**2
  1304. for z in [xp.nan, xp.inf, -xp.inf]:
  1305. y = xpx.at(y, -1).set(z)
  1306. assert_raises(ValueError, make_interp_spline, x, y)
  1307. @pytest.mark.parametrize('k', [1, 2, 3, 5])
  1308. def test_list_input(self, k):
  1309. # regression test for gh-8714: TypeError for x, y being lists and k=2
  1310. x = list(range(10))
  1311. y = [a**2 for a in x]
  1312. make_interp_spline(x, y, k=k)
  1313. def test_multiple_rhs(self, xp):
  1314. xx, yy = self._get_xy(xp)
  1315. yy = xp.stack((xx, yy), axis=1)
  1316. der_l = [(1, [1., 2.])]
  1317. der_r = [(1, [3., 4.])]
  1318. b = make_interp_spline(xx, yy, k=3, bc_type=(der_l, der_r))
  1319. xp_assert_close(b(xx), yy, atol=1e-14, rtol=1e-14)
  1320. xp_assert_close(
  1321. b(xx[0], 1),
  1322. xp.asarray(der_l[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
  1323. )
  1324. xp_assert_close(
  1325. b(xx[-1], 1),
  1326. xp.asarray(der_r[0][1], dtype=xp.float64), atol=1e-14, rtol=1e-14
  1327. )
  1328. def test_shapes(self):
  1329. rng = np.random.RandomState(1234)
  1330. k, n = 3, 22
  1331. x = np.sort(rng.random(size=n))
  1332. y = rng.random(size=(n, 5, 6, 7))
  1333. b = make_interp_spline(x, y, k)
  1334. assert b.c.shape == (n, 5, 6, 7)
  1335. # now throw in some derivatives
  1336. d_l = [(1, rng.random((5, 6, 7)))]
  1337. d_r = [(1, rng.random((5, 6, 7)))]
  1338. b = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
  1339. assert b.c.shape == (n + k - 1, 5, 6, 7)
  1340. def test_string_aliases(self, xp):
  1341. xx, yy = self._get_xy(xp)
  1342. yy = xp.sin(xx)
  1343. # a single string is duplicated
  1344. b1 = make_interp_spline(xx, yy, k=3, bc_type='natural')
  1345. b2 = make_interp_spline(xx, yy, k=3, bc_type=([(2, 0)], [(2, 0)]))
  1346. xp_assert_close(b1.c, b2.c, atol=1e-15)
  1347. # two strings are handled
  1348. b1 = make_interp_spline(xx, yy, k=3,
  1349. bc_type=('natural', 'clamped'))
  1350. b2 = make_interp_spline(xx, yy, k=3,
  1351. bc_type=([(2, 0)], [(1, 0)]))
  1352. xp_assert_close(b1.c, b2.c, atol=1e-15)
  1353. # one-sided BCs are OK
  1354. b1 = make_interp_spline(xx, yy, k=2, bc_type=(None, 'clamped'))
  1355. b2 = make_interp_spline(xx, yy, k=2, bc_type=(None, [(1, 0.0)]))
  1356. xp_assert_close(b1.c, b2.c, atol=1e-15)
  1357. # 'not-a-knot' is equivalent to None
  1358. b1 = make_interp_spline(xx, yy, k=3, bc_type='not-a-knot')
  1359. b2 = make_interp_spline(xx, yy, k=3, bc_type=None)
  1360. xp_assert_close(b1.c, b2.c, atol=1e-15)
  1361. # unknown strings do not pass
  1362. with assert_raises(ValueError):
  1363. make_interp_spline(xx, yy, k=3, bc_type='typo')
  1364. # string aliases are handled for 2D values
  1365. yy = xp.stack((xp.sin(xx), xp.cos(xx)), axis=1)
  1366. der_l = [(1, [0., 0.])]
  1367. der_r = [(2, [0., 0.])]
  1368. b2 = make_interp_spline(xx, yy, k=3, bc_type=(der_l, der_r))
  1369. b1 = make_interp_spline(xx, yy, k=3,
  1370. bc_type=('clamped', 'natural'))
  1371. xp_assert_close(b1.c, b2.c, atol=1e-15)
  1372. # ... and for N-D values:
  1373. rng = np.random.RandomState(1234)
  1374. k, n = 3, 22
  1375. x = np.sort(rng.random(size=n))
  1376. y = rng.random(size=(n, 5, 6, 7))
  1377. x, y = xp.asarray(x), xp.asarray(y)
  1378. # now throw in some derivatives
  1379. d_l = [(1, xp.zeros((5, 6, 7)))]
  1380. d_r = [(1, xp.zeros((5, 6, 7)))]
  1381. b1 = make_interp_spline(x, y, k, bc_type=(d_l, d_r))
  1382. b2 = make_interp_spline(x, y, k, bc_type='clamped')
  1383. xp_assert_close(b1.c, b2.c, atol=1e-15)
  1384. def test_full_matrix(self, xp):
  1385. rng = np.random.RandomState(1234)
  1386. k, n = 3, 7
  1387. x_np = np.sort(rng.random(size=n))
  1388. y_np = rng.random(size=n)
  1389. t_np = _not_a_knot(x_np, k)
  1390. cf = make_interp_full_matr(x_np, y_np, t_np, k)
  1391. cf = xp.asarray(cf)
  1392. x, y, t = map(xp.asarray, (x_np, y_np, t_np))
  1393. b = make_interp_spline(x, y, k, t)
  1394. xp_assert_close(b.c, cf, atol=1e-14, rtol=1e-14)
  1395. def test_woodbury(self):
  1396. '''
  1397. Random elements in diagonal matrix with blocks in the
  1398. left lower and right upper corners checking the
  1399. implementation of Woodbury algorithm.
  1400. '''
  1401. rng = np.random.RandomState(1234)
  1402. n = 201
  1403. for k in range(3, 32, 2):
  1404. offset = int((k - 1) / 2)
  1405. a = np.diagflat(rng.random((1, n)))
  1406. for i in range(1, offset + 1):
  1407. a[:-i, i:] += np.diagflat(rng.random((1, n - i)))
  1408. a[i:, :-i] += np.diagflat(rng.random((1, n - i)))
  1409. ur = rng.random((offset, offset))
  1410. a[:offset, -offset:] = ur
  1411. ll = rng.random((offset, offset))
  1412. a[-offset:, :offset] = ll
  1413. d = np.zeros((k, n))
  1414. for i, j in enumerate(range(offset, -offset - 1, -1)):
  1415. if j < 0:
  1416. d[i, :j] = np.diagonal(a, offset=j)
  1417. else:
  1418. d[i, j:] = np.diagonal(a, offset=j)
  1419. b = rng.random(n)
  1420. xp_assert_close(_woodbury_algorithm(d, ur, ll, b, k),
  1421. np.linalg.solve(a, b), atol=1e-14)
  1422. def make_interp_full_matr(x, y, t, k):
  1423. """Assemble an spline order k with knots t to interpolate
  1424. y(x) using full matrices.
  1425. Not-a-knot BC only.
  1426. This routine is here for testing only (even though it's functional).
  1427. """
  1428. assert x.size == y.size
  1429. assert t.size == x.size + k + 1
  1430. n = x.size
  1431. A = np.zeros((n, n), dtype=np.float64)
  1432. for j in range(n):
  1433. xval = x[j]
  1434. if xval == t[k]:
  1435. left = k
  1436. else:
  1437. left = np.searchsorted(t, xval) - 1
  1438. # fill a row
  1439. bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
  1440. A[j, left-k:left+1] = bb
  1441. c = sl.solve(A, y)
  1442. return c
  1443. def make_lsq_full_matrix(x, y, t, k=3):
  1444. """Make the least-square spline, full matrices."""
  1445. x, y, t = map(np.asarray, (x, y, t))
  1446. m = x.size
  1447. n = t.size - k - 1
  1448. A = np.zeros((m, n), dtype=np.float64)
  1449. for j in range(m):
  1450. xval = x[j]
  1451. # find interval
  1452. if xval == t[k]:
  1453. left = k
  1454. else:
  1455. left = np.searchsorted(t, xval) - 1
  1456. # fill a row
  1457. bb = _dierckx.evaluate_all_bspl(t, k, xval, left)
  1458. A[j, left-k:left+1] = bb
  1459. # have observation matrix, can solve the LSQ problem
  1460. B = np.dot(A.T, A)
  1461. Y = np.dot(A.T, y)
  1462. c = sl.solve(B, Y)
  1463. return c, (A, Y)
  1464. parametrize_lsq_methods = pytest.mark.parametrize("method", ["norm-eq", "qr"])
  1465. @make_xp_test_case(make_lsq_spline)
  1466. class TestLSQ:
  1467. #
  1468. # Test make_lsq_spline
  1469. #
  1470. rng = np.random.RandomState(1234)
  1471. n, k = 13, 3
  1472. x = np.sort(rng.random(n))
  1473. y = rng.random(n)
  1474. t = _augknt(np.linspace(x[0], x[-1], 7), k)
  1475. @parametrize_lsq_methods
  1476. def test_lstsq(self, method):
  1477. # check LSQ construction vs a full matrix version
  1478. x, y, t, k = self.x, self.y, self.t, self.k
  1479. c0, AY = make_lsq_full_matrix(x, y, t, k)
  1480. b = make_lsq_spline(x, y, t, k, method=method)
  1481. xp_assert_close(b.c, c0)
  1482. assert b.c.shape == (t.size - k - 1,)
  1483. # also check against numpy.lstsq
  1484. aa, yy = AY
  1485. c1, _, _, _ = np.linalg.lstsq(aa, y, rcond=-1)
  1486. xp_assert_close(b.c, c1)
  1487. @parametrize_lsq_methods
  1488. def test_weights(self, method, xp):
  1489. # weights = 1 is same as None
  1490. x, y, t, k = *map(xp.asarray, (self.x, self.y, self.t)), self.k
  1491. w = xp.ones_like(x)
  1492. b = make_lsq_spline(x, y, t, k, method=method)
  1493. b_w = make_lsq_spline(x, y, t, k, w=w, method=method)
  1494. xp_assert_close(b.t, b_w.t, atol=1e-14)
  1495. xp_assert_close(b.c, b_w.c, atol=1e-14)
  1496. assert b.k == b_w.k
  1497. def test_weights_same(self, xp):
  1498. # both methods treat weights
  1499. x, y, t, k = *map(xp.asarray, (self.x, self.y, self.t)), self.k
  1500. w = np.random.default_rng(1234).uniform(size=x.shape[0])
  1501. w = xp.asarray(w)
  1502. b_ne = make_lsq_spline(x, y, t, k, w=w, method="norm-eq")
  1503. b_qr = make_lsq_spline(x, y, t, k, w=w, method="qr")
  1504. b_no_w = make_lsq_spline(x, y, t, k, method="qr")
  1505. xp_assert_close(b_ne.c, b_qr.c, atol=1e-14)
  1506. assert not xp.all(xp.abs(b_no_w.c - b_qr.c) < 1e-14)
  1507. @parametrize_lsq_methods
  1508. def test_multiple_rhs(self, method, xp):
  1509. x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n
  1510. rng = np.random.RandomState(1234)
  1511. y = rng.random(size=(n, 5, 6, 7))
  1512. y = xp.asarray(y)
  1513. b = make_lsq_spline(x, y, t, k, method=method)
  1514. assert b.c.shape == (t.shape[0] - k - 1, 5, 6, 7)
  1515. @parametrize_lsq_methods
  1516. def test_multiple_rhs_2(self, method, xp):
  1517. x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n
  1518. nrhs = 3
  1519. rng = np.random.RandomState(1234)
  1520. y = rng.random(size=(n, nrhs))
  1521. y = xp.asarray(y)
  1522. b = make_lsq_spline(x, y, t, k, method=method)
  1523. bb = [make_lsq_spline(x, y[:, i], t, k, method=method)
  1524. for i in range(nrhs)]
  1525. coefs = xp.stack([bb[i].c for i in range(nrhs)]).T
  1526. xp_assert_close(coefs, b.c, atol=1e-15)
  1527. def test_multiple_rhs_3(self, xp):
  1528. x, t, k, n = *map(xp.asarray, (self.x, self.t)), self.k, self.n
  1529. nrhs = 3
  1530. y = np.random.random(size=(n, nrhs))
  1531. y = xp.asarray(y)
  1532. b_qr = make_lsq_spline(x, y, t, k, method="qr")
  1533. b_neq = make_lsq_spline(x, y, t, k, method="norm-eq")
  1534. xp_assert_close(b_qr.c, b_neq.c, atol=1e-15)
  1535. @parametrize_lsq_methods
  1536. def test_complex(self, method, xp):
  1537. # cmplx-valued `y`
  1538. x, t, k = *map(xp.asarray, (self.x, self.t)), self.k
  1539. yc = xp.asarray(self.y * (1. + 2.j))
  1540. b = make_lsq_spline(x, yc, t, k, method=method)
  1541. b_re = make_lsq_spline(x, xp.real(yc), t, k, method=method)
  1542. b_im = make_lsq_spline(x, xp.imag(yc), t, k, method=method)
  1543. xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)
  1544. def test_complex_2(self, xp):
  1545. # test complex-valued y with y.ndim > 1
  1546. x, t, k = *map(xp.asarray, (self.x, self.t)), self.k
  1547. yc = xp.asarray(self.y * (1. + 2.j))
  1548. yc = xp.stack((yc, yc), axis=1)
  1549. b = make_lsq_spline(x, yc, t, k)
  1550. b_re = make_lsq_spline(x, xp.real(yc), t, k)
  1551. b_im = make_lsq_spline(x, xp.imag(yc), t, k)
  1552. xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)
  1553. # repeat with num_trailing_dims > 1 : yc.shape[1:] = (2, 2)
  1554. yc = xp.stack((yc, yc), axis=1)
  1555. b = make_lsq_spline(x, yc, t, k)
  1556. b_re = make_lsq_spline(x, xp.real(yc), t, k)
  1557. b_im = make_lsq_spline(x, xp.imag(yc), t, k)
  1558. xp_assert_close(b(x), b_re(x) + 1.j*b_im(x), atol=1e-15, rtol=1e-15)
  1559. @parametrize_lsq_methods
  1560. def test_int_xy(self, method):
  1561. x = np.arange(10).astype(int)
  1562. y = np.arange(10).astype(int)
  1563. t = _augknt(x, k=1)
  1564. # Cython chokes on "buffer type mismatch"
  1565. make_lsq_spline(x, y, t, k=1, method=method)
  1566. @parametrize_lsq_methods
  1567. def test_f32_xy(self, method):
  1568. x = np.arange(10, dtype=np.float32)
  1569. y = np.arange(10, dtype=np.float32)
  1570. t = _augknt(x, k=1)
  1571. spl_f32 = make_lsq_spline(x, y, t, k=1, method=method)
  1572. spl_f64 = make_lsq_spline(
  1573. x.astype(float), y.astype(float), t.astype(float), k=1, method=method
  1574. )
  1575. x2 = (x[1:] + x[:-1]) / 2.0
  1576. xp_assert_close(spl_f32(x2), spl_f64(x2), atol=1e-15)
  1577. @parametrize_lsq_methods
  1578. def test_sliced_input(self, method):
  1579. # Cython code chokes on non C contiguous arrays
  1580. xx = np.linspace(-1, 1, 100)
  1581. x = xx[::3]
  1582. y = xx[::3]
  1583. t = _augknt(x, 1)
  1584. make_lsq_spline(x, y, t, k=1, method=method)
  1585. @parametrize_lsq_methods
  1586. def test_checkfinite(self, method):
  1587. # check_finite defaults to True; nans and such trigger a ValueError
  1588. x = np.arange(12).astype(float)
  1589. y = x**2
  1590. t = _augknt(x, 3)
  1591. for z in [np.nan, np.inf, -np.inf]:
  1592. y[-1] = z
  1593. assert_raises(ValueError, make_lsq_spline, x, y, t, method=method)
  1594. @parametrize_lsq_methods
  1595. def test_read_only(self, method):
  1596. # Check that make_lsq_spline works with read only arrays
  1597. x, y, t = self.x, self.y, self.t
  1598. x.setflags(write=False)
  1599. y.setflags(write=False)
  1600. t.setflags(write=False)
  1601. make_lsq_spline(x=x, y=y, t=t, method=method)
  1602. @pytest.mark.parametrize('k', list(range(1, 7)))
  1603. def test_qr_vs_norm_eq(self, k):
  1604. # check that QR and normal eq solutions match
  1605. x, y = self.x, self.y
  1606. t = _augknt(np.linspace(x[0], x[-1], 7), k)
  1607. spl_norm_eq = make_lsq_spline(x, y, t, k=k, method='norm-eq')
  1608. spl_qr = make_lsq_spline(x, y, t, k=k, method='qr')
  1609. xx = (x[1:] + x[:-1]) / 2.0
  1610. xp_assert_close(spl_norm_eq(xx), spl_qr(xx), atol=1e-15)
  1611. def test_duplicates(self):
  1612. # method="qr" can handle duplicated data points
  1613. x = np.repeat(self.x, 2)
  1614. y = np.repeat(self.y, 2)
  1615. spl_1 = make_lsq_spline(self.x, self.y, self.t, k=3, method='qr')
  1616. spl_2 = make_lsq_spline(x, y, self.t, k=3, method='qr')
  1617. xx = (x[1:] + x[:-1]) / 2.0
  1618. xp_assert_close(spl_1(xx), spl_2(xx), atol=1e-15)
  1619. class PackedMatrix:
  1620. """A simplified CSR format for when non-zeros in each row are consecutive.
  1621. Assuming that each row of an `(m, nc)` matrix 1) only has `nz` non-zeros, and
  1622. 2) these non-zeros are consecutive, we only store an `(m, nz)` matrix of
  1623. non-zeros and a 1D array of row offsets. This way, a row `i` of the original
  1624. matrix A is ``A[i, offset[i]: offset[i] + nz]``.
  1625. """
  1626. def __init__(self, a, offset, nc):
  1627. self.a = a
  1628. self.offset = offset
  1629. self.nc = nc
  1630. assert a.ndim == 2
  1631. assert offset.ndim == 1
  1632. assert a.shape[0] == offset.shape[0]
  1633. @property
  1634. def shape(self):
  1635. return self.a.shape[0], self.nc
  1636. def todense(self):
  1637. out = np.zeros(self.shape)
  1638. nelem = self.a.shape[1]
  1639. for i in range(out.shape[0]):
  1640. nel = min(self.nc - self.offset[i], nelem)
  1641. out[i, self.offset[i]:self.offset[i] + nel] = self.a[i, :nel]
  1642. return out
  1643. def _qr_reduce_py(a_p, y, startrow=1):
  1644. """This is a python counterpart of the `_qr_reduce` routine,
  1645. declared in interpolate/src/__fitpack.h
  1646. """
  1647. from scipy.linalg.lapack import dlartg
  1648. # unpack the packed format
  1649. a = a_p.a
  1650. offset = a_p.offset
  1651. nc = a_p.nc
  1652. m, nz = a.shape
  1653. assert y.shape[0] == m
  1654. R = a.copy()
  1655. y1 = y.copy()
  1656. for i in range(startrow, m):
  1657. oi = offset[i]
  1658. for j in range(oi, nc):
  1659. # rotate only the lower diagonal
  1660. if j >= min(i, nc):
  1661. break
  1662. # In dense format: diag a1[j, j] vs a1[i, j]
  1663. c, s, r = dlartg(R[j, 0], R[i, 0])
  1664. # rotate l.h.s.
  1665. R[j, 0] = r
  1666. for l in range(1, nz):
  1667. R[j, l], R[i, l-1] = fprota(c, s, R[j, l], R[i, l])
  1668. R[i, -1] = 0.0
  1669. # rotate r.h.s.
  1670. for l in range(y1.shape[1]):
  1671. y1[j, l], y1[i, l] = fprota(c, s, y1[j, l], y1[i, l])
  1672. # convert to packed
  1673. offs = list(range(R.shape[0]))
  1674. R_p = PackedMatrix(R, np.array(offs, dtype=np.int64), nc)
  1675. return R_p, y1
  1676. def fprota(c, s, a, b):
  1677. """Givens rotate [a, b].
  1678. [aa] = [ c s] @ [a]
  1679. [bb] [-s c] [b]
  1680. """
  1681. aa = c*a + s*b
  1682. bb = -s*a + c*b
  1683. return aa, bb
  1684. def fpback(R_p, y):
  1685. """Backsubsitution solve upper triangular banded `R @ c = y.`
  1686. `R` is in the "packed" format: `R[i, :]` is `a[i, i:i+k+1]`
  1687. """
  1688. R = R_p.a
  1689. _, nz = R.shape
  1690. nc = R_p.nc
  1691. assert y.shape[0] == R.shape[0]
  1692. c = np.zeros_like(y[:nc])
  1693. c[nc-1, ...] = y[nc-1] / R[nc-1, 0]
  1694. for i in range(nc-2, -1, -1):
  1695. nel = min(nz, nc-i)
  1696. # NB: broadcast R across trailing dimensions of `c`.
  1697. summ = (R[i, 1:nel, None] * c[i+1:i+nel, ...]).sum(axis=0)
  1698. c[i, ...] = ( y[i] - summ ) / R[i, 0]
  1699. return c
  1700. class TestGivensQR:
  1701. # Test row-by-row QR factorization, used for the LSQ spline construction.
  1702. # This is implementation detail; still test it separately.
  1703. def _get_xyt(self, n):
  1704. k = 3
  1705. x = np.arange(n, dtype=float)
  1706. y = x**3 + 1/(1+x)
  1707. t = _not_a_knot(x, k)
  1708. return x, y, t, k
  1709. def test_vs_full(self):
  1710. n = 10
  1711. x, y, t, k = self._get_xyt(n)
  1712. # design matrix
  1713. a_csr = BSpline.design_matrix(x, t, k)
  1714. # dense QR
  1715. q, r = sl.qr(a_csr.todense())
  1716. qTy = q.T @ y
  1717. # prepare the PackedMatrix to factorize
  1718. # convert to "packed" format
  1719. m, nc = a_csr.shape
  1720. assert nc == t.shape[0] - k - 1
  1721. offset = a_csr.indices[::(k+1)]
  1722. offset = np.ascontiguousarray(offset, dtype=np.int64)
  1723. A = a_csr.data.reshape(m, k+1)
  1724. R = PackedMatrix(A, offset, nc)
  1725. y_ = y[:, None] # _qr_reduce requires `y` a 2D array
  1726. _dierckx.qr_reduce(A, offset, nc, y_) # modifies arguments in-place
  1727. # signs may differ
  1728. xp_assert_close(np.minimum(R.todense() + r,
  1729. R.todense() - r), np.zeros_like(r), atol=1e-15)
  1730. xp_assert_close(np.minimum(abs(qTy - y_[:, 0]),
  1731. abs(qTy + y_[:, 0])), np.zeros_like(qTy), atol=2e-13)
  1732. # sign changes are consistent between Q and R:
  1733. c_full = sl.solve(r, qTy)
  1734. c_banded, _, _ = _dierckx.fpback(R.a, R.nc, x, y_, t, k, np.ones_like(y), y_)
  1735. xp_assert_close(c_full, c_banded[:, 0], atol=5e-13)
  1736. def test_py_vs_compiled(self):
  1737. # test _qr_reduce vs a python implementation
  1738. n = 10
  1739. x, y, t, k = self._get_xyt(n)
  1740. # design matrix
  1741. a_csr = BSpline.design_matrix(x, t, k)
  1742. m, nc = a_csr.shape
  1743. assert nc == t.shape[0] - k - 1
  1744. offset = a_csr.indices[::(k+1)]
  1745. offset = np.ascontiguousarray(offset, dtype=np.int64)
  1746. A = a_csr.data.reshape(m, k+1)
  1747. R = PackedMatrix(A, offset, nc)
  1748. y_ = y[:, None]
  1749. RR, yy = _qr_reduce_py(R, y_)
  1750. _dierckx.qr_reduce(A, offset, nc , y_) # in-place
  1751. xp_assert_close(RR.a, R.a, atol=1e-15)
  1752. xp_assert_equal(RR.offset, R.offset, check_dtype=False)
  1753. assert RR.nc == R.nc
  1754. xp_assert_close(yy, y_, atol=1e-15)
  1755. # Test C-level construction of the design matrix
  1756. def test_data_matrix(self):
  1757. n = 10
  1758. x, y, t, k = self._get_xyt(n)
  1759. w = np.arange(1, n+1, dtype=float)
  1760. A, offset, nc = _dierckx.data_matrix(x, t, k, w)
  1761. m = x.shape[0]
  1762. a_csr = BSpline.design_matrix(x, t, k)
  1763. a_w = (a_csr * w[:, None]).tocsr()
  1764. A_ = a_w.data.reshape((m, k+1))
  1765. offset_ = a_w.indices[::(k+1)].astype(np.int64)
  1766. xp_assert_close(A, A_, atol=1e-15)
  1767. xp_assert_equal(offset, offset_)
  1768. assert nc == t.shape[0] - k - 1
  1769. def test_fpback(self):
  1770. n = 10
  1771. x, y, t, k = self._get_xyt(n)
  1772. y = np.c_[y, y**2]
  1773. A, offset, nc = _dierckx.data_matrix(x, t, k, np.ones_like(x))
  1774. R = PackedMatrix(A, offset, nc)
  1775. _dierckx.qr_reduce(A, offset, nc, y)
  1776. c = fpback(R, y)
  1777. cc, _, _ = _dierckx.fpback(A, nc, x, y, t, k, np.ones_like(x), y)
  1778. xp_assert_close(cc, c, atol=1e-14)
  1779. def test_evaluate_all_bspl(self):
  1780. n = 10
  1781. x, _, t, k = self._get_xyt(n)
  1782. zero_array = np.zeros((k + 1,), dtype=float)
  1783. for xval in x:
  1784. xp_assert_equal(
  1785. _dierckx.evaluate_all_bspl(t, k, xval, n, k + 2), zero_array)
  1786. xp_assert_equal(
  1787. _dierckx.evaluate_all_bspl(t, k, xval, n, 2*k), zero_array)
  1788. def data_file(basename):
  1789. return os.path.join(os.path.abspath(os.path.dirname(__file__)),
  1790. 'data', basename)
  1791. @make_xp_test_case(make_smoothing_spline)
  1792. class TestSmoothingSpline:
  1793. #
  1794. # test make_smoothing_spline
  1795. #
  1796. def test_invalid_input(self):
  1797. rng = np.random.RandomState(1234)
  1798. n = 100
  1799. x = np.sort(rng.random_sample(n) * 4 - 2)
  1800. y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n)
  1801. # ``x`` and ``y`` should have same shapes (1-D array)
  1802. with assert_raises(ValueError):
  1803. make_smoothing_spline(x, y[1:])
  1804. with assert_raises(ValueError):
  1805. make_smoothing_spline(x[1:], y)
  1806. with assert_raises(ValueError):
  1807. make_smoothing_spline(x.reshape(1, n), y)
  1808. # ``x`` should be an ascending array
  1809. with assert_raises(ValueError):
  1810. make_smoothing_spline(x[::-1], y)
  1811. x_dupl = np.copy(x)
  1812. x_dupl[0] = x_dupl[1]
  1813. with assert_raises(ValueError):
  1814. make_smoothing_spline(x_dupl, y)
  1815. # x and y length must be >= 5
  1816. x = np.arange(4)
  1817. y = np.ones(4)
  1818. exception_message = "``x`` and ``y`` length must be at least 5"
  1819. with pytest.raises(ValueError, match=exception_message):
  1820. make_smoothing_spline(x, y)
  1821. def test_compare_with_GCVSPL(self):
  1822. """
  1823. Data is generated in the following way:
  1824. >>> np.random.seed(1234)
  1825. >>> n = 100
  1826. >>> x = np.sort(np.random.random_sample(n) * 4 - 2)
  1827. >>> y = np.sin(x) + np.random.normal(scale=.5, size=n)
  1828. >>> np.savetxt('x.csv', x)
  1829. >>> np.savetxt('y.csv', y)
  1830. We obtain the result of performing the GCV smoothing splines
  1831. package (by Woltring, gcvspl) on the sample data points
  1832. using its version for Octave (https://github.com/srkuberski/gcvspl).
  1833. In order to use this implementation, one should clone the repository
  1834. and open the folder in Octave.
  1835. In Octave, we load up ``x`` and ``y`` (generated from Python code
  1836. above):
  1837. >>> x = csvread('x.csv');
  1838. >>> y = csvread('y.csv');
  1839. Then, in order to access the implementation, we compile gcvspl files in
  1840. Octave:
  1841. >>> mex gcvsplmex.c gcvspl.c
  1842. >>> mex spldermex.c gcvspl.c
  1843. The first function computes the vector of unknowns from the dataset
  1844. (x, y) while the second one evaluates the spline in certain points
  1845. with known vector of coefficients.
  1846. >>> c = gcvsplmex( x, y, 2 );
  1847. >>> y0 = spldermex( x, c, 2, x, 0 );
  1848. If we want to compare the results of the gcvspl code, we can save
  1849. ``y0`` in csv file:
  1850. >>> csvwrite('y0.csv', y0);
  1851. """
  1852. # load the data sample
  1853. with np.load(data_file('gcvspl.npz')) as data:
  1854. # data points
  1855. x = data['x']
  1856. y = data['y']
  1857. y_GCVSPL = data['y_GCVSPL']
  1858. y_compr = make_smoothing_spline(x, y)(x)
  1859. # such tolerance is explained by the fact that the spline is built
  1860. # using an iterative algorithm for minimizing the GCV criteria. These
  1861. # algorithms may vary, so the tolerance should be rather low.
  1862. # Not checking dtypes as gcvspl.npz stores little endian arrays, which
  1863. # result in conflicting dtypes on big endian systems.
  1864. xp_assert_close(y_compr, y_GCVSPL, atol=1e-4, rtol=1e-4, check_dtype=False)
  1865. def test_non_regularized_case(self, xp):
  1866. """
  1867. In case the regularization parameter is 0, the resulting spline
  1868. is an interpolation spline with natural boundary conditions.
  1869. """
  1870. # create data sample
  1871. rng = np.random.RandomState(1234)
  1872. n = 100
  1873. x = np.sort(rng.random_sample(n) * 4 - 2)
  1874. y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n)
  1875. x, y = xp.asarray(x), xp.asarray(y)
  1876. spline_GCV = make_smoothing_spline(x, y, lam=0.)
  1877. spline_interp = make_interp_spline(x, y, 3, bc_type='natural')
  1878. grid = xp.linspace(x[0], x[-1], 2 * n)
  1879. xp_assert_close(spline_GCV(grid),
  1880. spline_interp(grid),
  1881. atol=1e-15)
  1882. @pytest.mark.fail_slow(2)
  1883. def test_weighted_smoothing_spline(self, xp):
  1884. # create data sample
  1885. rng = np.random.RandomState(1234)
  1886. n = 100
  1887. x = np.sort(rng.random_sample(n) * 4 - 2)
  1888. y = x**2 * np.sin(4 * x) + x**3 + rng.normal(0., 1.5, n)
  1889. x, y = map(xp.asarray, (x, y))
  1890. spl = make_smoothing_spline(x, y)
  1891. # in order not to iterate over all of the indices, we select 10 of
  1892. # them randomly
  1893. for ind in rng.choice(range(100), size=10):
  1894. w = xp.ones(n)
  1895. xpx.at(w, int(ind)).set(30.) # w[int(ind)] = 30.
  1896. spl_w = make_smoothing_spline(x, y, w)
  1897. # check that spline with weight in a certain point is closer to the
  1898. # original point than the one without weights
  1899. orig = abs(spl(x[ind]) - y[ind])
  1900. weighted = abs(spl_w(x[ind]) - y[ind])
  1901. if orig < weighted:
  1902. raise ValueError(f'Spline with weights should be closer to the'
  1903. f' points than the original one: {orig:.4} < '
  1904. f'{weighted:.4}')
  1905. ################################
  1906. # NdBSpline tests
  1907. def bspline2(xy, t, c, k):
  1908. """A naive 2D tensort product spline evaluation."""
  1909. x, y = xy
  1910. tx, ty = t
  1911. nx = len(tx) - k - 1
  1912. assert (nx >= k+1)
  1913. ny = len(ty) - k - 1
  1914. assert (ny >= k+1)
  1915. res = sum(c[ix, iy] * B(x, k, ix, tx) * B(y, k, iy, ty)
  1916. for ix in range(nx) for iy in range(ny))
  1917. return np.asarray(res)
  1918. def B(x, k, i, t):
  1919. if k == 0:
  1920. return 1.0 if t[i] <= x < t[i+1] else 0.0
  1921. if t[i+k] == t[i]:
  1922. c1 = 0.0
  1923. else:
  1924. c1 = (x - t[i])/(t[i+k] - t[i]) * B(x, k-1, i, t)
  1925. if t[i+k+1] == t[i+1]:
  1926. c2 = 0.0
  1927. else:
  1928. c2 = (t[i+k+1] - x)/(t[i+k+1] - t[i+1]) * B(x, k-1, i+1, t)
  1929. return c1 + c2
  1930. def bspline(x, t, c, k):
  1931. n = len(t) - k - 1
  1932. assert (n >= k+1) and (len(c) >= n)
  1933. return sum(c[i] * B(x, k, i, t) for i in range(n))
  1934. class NdBSpline0:
  1935. def __init__(self, t, c, k=3):
  1936. """Tensor product spline object.
  1937. c[i1, i2, ..., id] * B(x1, i1) * B(x2, i2) * ... * B(xd, id)
  1938. Parameters
  1939. ----------
  1940. c : ndarray, shape (n1, n2, ..., nd, ...)
  1941. b-spline coefficients
  1942. t : tuple of 1D ndarrays
  1943. knot vectors in directions 1, 2, ... d
  1944. ``len(t[i]) == n[i] + k + 1``
  1945. k : int or length-d tuple of integers
  1946. spline degrees.
  1947. """
  1948. ndim = len(t)
  1949. assert ndim <= len(c.shape)
  1950. try:
  1951. len(k)
  1952. except TypeError:
  1953. # make k a tuple
  1954. k = (k,)*ndim
  1955. self.k = tuple(operator.index(ki) for ki in k)
  1956. self.t = tuple(np.asarray(ti, dtype=float) for ti in t)
  1957. self.c = c
  1958. def __call__(self, x):
  1959. ndim = len(self.t)
  1960. # a single evaluation point: `x` is a 1D array_like, shape (ndim,)
  1961. assert len(x) == ndim
  1962. # get the indices in an ndim-dimensional vector
  1963. i = ['none', ]*ndim
  1964. for d in range(ndim):
  1965. td, xd = self.t[d], x[d]
  1966. k = self.k[d]
  1967. # find the index for x[d]
  1968. if xd == td[k]:
  1969. i[d] = k
  1970. else:
  1971. i[d] = np.searchsorted(td, xd) - 1
  1972. assert td[i[d]] <= xd <= td[i[d]+1]
  1973. assert i[d] >= k and i[d] < len(td) - k
  1974. i = tuple(i)
  1975. # iterate over the dimensions, form linear combinations of
  1976. # products B(x_1) * B(x_2) * ... B(x_N) of (k+1)**N b-splines
  1977. # which are non-zero at `i = (i_1, i_2, ..., i_N)`.
  1978. result = 0
  1979. iters = [range(i[d] - self.k[d], i[d] + 1) for d in range(ndim)]
  1980. for idx in itertools.product(*iters):
  1981. term = self.c[idx] * np.prod([B(x[d], self.k[d], idx[d], self.t[d])
  1982. for d in range(ndim)])
  1983. result += term
  1984. return np.asarray(result)
  1985. @make_xp_test_case(NdBSpline)
  1986. class TestNdBSpline:
  1987. def test_1D(self, xp):
  1988. # test ndim=1 agrees with BSpline
  1989. rng = np.random.default_rng(12345)
  1990. n, k = 11, 3
  1991. n_tr = 7
  1992. t = np.sort(rng.uniform(size=n + k + 1))
  1993. c = rng.uniform(size=(n, n_tr))
  1994. t = xp.asarray(t)
  1995. c = xp.asarray(c)
  1996. b = BSpline(t, c, k)
  1997. nb = NdBSpline((t,), c, k)
  1998. xi = rng.uniform(size=21)
  1999. xi = xp.asarray(xi)
  2000. # NdBSpline expects xi.shape=(npts, ndim)
  2001. xp_assert_close(nb(xi[:, None]),
  2002. b(xi), atol=1e-14)
  2003. assert nb(xi[:, None]).shape == (xi.shape[0], c.shape[1])
  2004. def make_2d_case(self, xp=np):
  2005. # make a 2D separable spline
  2006. x = xp.arange(6)
  2007. y = x**3
  2008. spl = make_interp_spline(x, y, k=3)
  2009. y_1 = x**3 + 2*x
  2010. spl_1 = make_interp_spline(x, y_1, k=3)
  2011. t2 = (spl.t, spl_1.t)
  2012. c2 = spl.c[:, None] * spl_1.c[None, :]
  2013. return t2, c2, 3
  2014. def make_2d_mixed(self, xp=np):
  2015. # make a 2D separable spline w/ kx=3, ky=2
  2016. x = xp.arange(6)
  2017. y = x**3
  2018. spl = make_interp_spline(x, y, k=3)
  2019. x = xp.arange(5, dtype=xp.float64) + 1.5
  2020. y_1 = x**2 + 2*x
  2021. spl_1 = make_interp_spline(x, y_1, k=2)
  2022. t2 = (spl.t, spl_1.t)
  2023. c2 = spl.c[:, None] * spl_1.c[None, :]
  2024. return t2, c2, spl.k, spl_1.k
  2025. def test_2D_separable(self, xp):
  2026. xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)]
  2027. t2, c2, k = self.make_2d_case(xp=xp)
  2028. target = [x**3 * (y**3 + 2*y) for (x, y) in xi]
  2029. # sanity check: bspline2 gives the product as constructed
  2030. b2 = [bspline2(
  2031. xy,
  2032. [np.asarray(_) for _ in t2],
  2033. np.asarray(c2),
  2034. k
  2035. ) for xy in xi
  2036. ]
  2037. b2 = np.asarray(b2, dtype=np.float64)
  2038. xp_assert_close(xp.asarray(b2),
  2039. xp.asarray(target, dtype=xp.float64),
  2040. check_shape=False,
  2041. atol=1e-14)
  2042. # check evaluation on a 2D array: the 1D array of 2D points
  2043. bspl2 = NdBSpline(t2, c2, k=3)
  2044. assert bspl2(xi).shape == (len(xi), )
  2045. xp_assert_close(bspl2(xi),
  2046. xp.asarray(target, dtype=xp.float64), atol=1e-14)
  2047. # test that a nan in -> nan out
  2048. xi = np.asarray(xi)
  2049. xi[0, 1] = np.nan
  2050. xi = xp.asarray(xi)
  2051. xp_assert_equal(xp.isnan(bspl2(xi)), xp.asarray([True, False, False]))
  2052. # now check on a multidim xi
  2053. rng = np.random.default_rng(12345)
  2054. xi = rng.uniform(size=(4, 3, 2)) * 5
  2055. xi = xp.asarray(xi)
  2056. result = bspl2(xi)
  2057. assert result.shape == (4, 3)
  2058. # also check the values
  2059. rrr = xp.reshape(xi, (-1, 2)).T
  2060. x, y = rrr[0, ...], rrr[1, ...]
  2061. xp_assert_close(xp_ravel(result, xp=xp),
  2062. x**3 * (y**3 + 2*y), atol=1e-14)
  2063. def test_2D_separable_2(self, xp):
  2064. # test `c` with trailing dimensions, i.e. c.ndim > ndim
  2065. ndim = 2
  2066. xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)]
  2067. target = [x**3 * (y**3 + 2*y) for (x, y) in xi]
  2068. t2, c2, k = self.make_2d_case(xp=xp)
  2069. c2_4 = xp.stack((c2, c2, c2, c2), axis=2) # c22.shape = (6, 6, 4)
  2070. xy = (1.5, 2.5)
  2071. bspl2_4 = NdBSpline(t2, c2_4, k=3)
  2072. result = bspl2_4(xy)
  2073. val_single = NdBSpline(t2, c2, k)(xy)
  2074. assert result.shape == (4,)
  2075. xp_assert_close(result,
  2076. xp.stack([val_single, ]*4), atol=1e-14)
  2077. # now try the array xi : the output.shape is (3, 4) where 3
  2078. # is the number of points in xi and 4 is the trailing dimension of c
  2079. assert bspl2_4(xi).shape == np.shape(xi)[:-1] + bspl2_4.c.shape[ndim:]
  2080. xp_assert_close(bspl2_4(xi),
  2081. xp.asarray(target, dtype=xp.float64)[:, None],
  2082. check_shape=False,
  2083. atol=5e-14)
  2084. # two trailing dimensions
  2085. c2_22 = xp.reshape(c2_4, (6, 6, 2, 2))
  2086. bspl2_22 = NdBSpline(t2, c2_22, k=3)
  2087. result = bspl2_22(xy)
  2088. assert result.shape == (2, 2)
  2089. target2_22 = xp.ones((2, 2), dtype=xp.float64)*val_single
  2090. xp_assert_close(result, target2_22, atol=1e-14)
  2091. # now try the array xi : the output shape is (3, 2, 2)
  2092. # for 3 points in xi and c trailing dimensions being (2, 2)
  2093. assert (bspl2_22(xi).shape ==
  2094. np.shape(xi)[:-1] + bspl2_22.c.shape[ndim:])
  2095. xp_assert_close(bspl2_22(xi),
  2096. xp.asarray(target, dtype=xp.float64)[:, None, None],
  2097. check_shape=False,
  2098. atol=5e-14)
  2099. def test_2D_separable_2_complex(self, xp):
  2100. # test `c` with c.dtype == complex, with and w/o trailing dims
  2101. xi = [(1.5, 2.5), (2.5, 1), (0.5, 1.5)]
  2102. target = [x**3 * (y**3 + 2*y) for (x, y) in xi]
  2103. target = [t + 2j*t for t in target]
  2104. t2, c2, k = self.make_2d_case(xp=xp)
  2105. c2 = c2 * (1 + 2j)
  2106. c2_4 = xp.stack((c2, c2, c2, c2), axis=2) # c2_4.shape = (6, 6, 4)
  2107. xy = (1.5, 2.5)
  2108. bspl2_4 = NdBSpline(t2, c2_4, k=3)
  2109. result = bspl2_4(xy)
  2110. val_single = NdBSpline(t2, c2, k)(xy)
  2111. assert result.shape == (4,)
  2112. xp_assert_close(result,
  2113. xp.stack([val_single]*4), atol=1e-14)
  2114. def test_2D_random(self):
  2115. rng = np.random.default_rng(12345)
  2116. k = 3
  2117. tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
  2118. ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2119. c = rng.uniform(size=(tx.size-k-1, ty.size-k-1))
  2120. spl = NdBSpline((tx, ty), c, k=k)
  2121. xi = (1., 1.)
  2122. xp_assert_close(spl(xi),
  2123. bspline2(xi, (tx, ty), c, k), atol=1e-14)
  2124. xi = np.c_[[1, 1.5, 2],
  2125. [1.1, 1.6, 2.1]]
  2126. xp_assert_close(spl(xi),
  2127. [bspline2(xy, (tx, ty), c, k) for xy in xi],
  2128. atol=1e-14)
  2129. def test_2D_mixed(self):
  2130. t2, c2, kx, ky = self.make_2d_mixed()
  2131. xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)]
  2132. target = [x**3 * (y**2 + 2*y) for (x, y) in xi]
  2133. bspl2 = NdBSpline(t2, c2, k=(kx, ky))
  2134. assert bspl2(xi).shape == (len(xi), )
  2135. xp_assert_close(bspl2(xi),
  2136. target, atol=1e-14)
  2137. def test_2D_derivative(self, xp):
  2138. t2, c2, kx, ky = self.make_2d_mixed(xp=xp)
  2139. xi = [(1.4, 4.5), (2.5, 2.4), (4.5, 3.5)]
  2140. bspl2 = NdBSpline(t2, c2, k=(kx, ky))
  2141. # Derivative orders and expected functions
  2142. test_cases = {
  2143. (1, 0): lambda x, y: 3 * x**2 * (y**2 + 2*y),
  2144. (1, 1): lambda x, y: 3 * x**2 * (2*y + 2),
  2145. (0, 0): lambda x, y: x**3 * (y**2 + 2*y),
  2146. (2*kx, 1): lambda x, y: 0,
  2147. (2*kx, 0): lambda x, y: 0,
  2148. (1, 3*ky): lambda x, y: 0,
  2149. (0, 3*ky): lambda x, y: 0,
  2150. (3*kx, 2*ky): lambda x, y: 0,
  2151. }
  2152. for nu, expected_fn in test_cases.items():
  2153. expected_vals = xp.asarray(
  2154. [expected_fn(x, y) for x, y in xi], dtype=xp.float64
  2155. )
  2156. # Evaluate via nu argument
  2157. direct = bspl2(xi, nu=nu)
  2158. xp_assert_close(direct, expected_vals, atol=1e-14)
  2159. # Evaluate via .derivative() call
  2160. via_method = bspl2.derivative(nu)(xi)
  2161. xp_assert_close(via_method, expected_vals, atol=1e-14)
  2162. # Error cases
  2163. for bad_nu in [(-1, 0), # all(nu >= 0)
  2164. (-1, 0, 1)]: # len(nu) == ndim
  2165. with assert_raises(ValueError):
  2166. bspl2(xi, nu=bad_nu)
  2167. with assert_raises(ValueError):
  2168. bspl2.derivative(bad_nu)
  2169. def test_2D_mixed_random(self):
  2170. rng = np.random.default_rng(12345)
  2171. kx, ky = 2, 3
  2172. tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
  2173. ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2174. c = rng.uniform(size=(tx.size - kx - 1, ty.size - ky - 1))
  2175. xi = np.c_[[1, 1.5, 2],
  2176. [1.1, 1.6, 2.1]]
  2177. bspl2 = NdBSpline((tx, ty), c, k=(kx, ky))
  2178. bspl2_0 = NdBSpline0((tx, ty), c, k=(kx, ky))
  2179. xp_assert_close(bspl2(xi),
  2180. [bspl2_0(xp) for xp in xi], atol=1e-14)
  2181. def test_tx_neq_ty(self):
  2182. # 2D separable spline w/ len(tx) != len(ty)
  2183. x = np.arange(6)
  2184. y = np.arange(7) + 1.5
  2185. spl_x = make_interp_spline(x, x**3, k=3)
  2186. spl_y = make_interp_spline(y, y**2 + 2*y, k=3)
  2187. cc = spl_x.c[:, None] * spl_y.c[None, :]
  2188. bspl = NdBSpline((spl_x.t, spl_y.t), cc, (spl_x.k, spl_y.k))
  2189. values = (x**3)[:, None] * (y**2 + 2*y)[None, :]
  2190. rgi = RegularGridInterpolator((x, y), values)
  2191. xi = [(a, b) for a, b in itertools.product(x, y)]
  2192. bxi = bspl(xi)
  2193. assert not np.isnan(bxi).any()
  2194. xp_assert_close(bxi, rgi(xi), atol=1e-14)
  2195. xp_assert_close(bxi.reshape(values.shape), values, atol=1e-14)
  2196. def make_3d_case(self, xp=np):
  2197. # make a 3D separable spline
  2198. x = xp.arange(6)
  2199. y = x**3
  2200. spl = make_interp_spline(x, y, k=3)
  2201. y_1 = x**3 + 2*x
  2202. spl_1 = make_interp_spline(x, y_1, k=3)
  2203. y_2 = x**3 + 3*x + 1
  2204. spl_2 = make_interp_spline(x, y_2, k=3)
  2205. t2 = (spl.t, spl_1.t, spl_2.t)
  2206. c2 = (spl.c[:, None, None] *
  2207. spl_1.c[None, :, None] *
  2208. spl_2.c[None, None, :])
  2209. return t2, c2, 3
  2210. def test_3D_separable(self):
  2211. rng = np.random.default_rng(12345)
  2212. x, y, z = rng.uniform(size=(3, 11)) * 5
  2213. target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
  2214. t3, c3, k = self.make_3d_case()
  2215. bspl3 = NdBSpline(t3, c3, k=3)
  2216. xi = [_ for _ in zip(x, y, z)]
  2217. result = bspl3(xi)
  2218. assert result.shape == (11,)
  2219. xp_assert_close(result, target, atol=1e-14)
  2220. def test_3D_derivative(self, xp):
  2221. t3, c3, k = self.make_3d_case(xp=xp)
  2222. bspl3 = NdBSpline(t3, c3, k=3)
  2223. rng = np.random.default_rng(12345)
  2224. x, y, z = rng.uniform(size=(3, 11)) * 5
  2225. xi_np = [_ for _ in zip(x, y, z)]
  2226. xi = xp.asarray(xi_np)
  2227. # Derivative orders and their expected expressions
  2228. test_cases = {
  2229. (1, 0, 0): lambda x, y, z: 3 * x**2 * (y**3 + 2*y) * (z**3 + 3*z + 1),
  2230. (2, 0, 0): lambda x, y, z: 6 * x * (y**3 + 2*y) * (z**3 + 3*z + 1),
  2231. (2, 1, 0): lambda x, y, z: 6 * x * (3*y**2 + 2) * (z**3 + 3*z + 1),
  2232. (2, 1, 3): lambda x, y, z: 6 * x * (3*y**2 + 2) * 6,
  2233. (2, 1, 4): lambda x, y, z: 0.0,
  2234. }
  2235. for nu, expected_fn in test_cases.items():
  2236. expected_vals = [expected_fn(xi_, yi_, zi_) for xi_, yi_, zi_ in xi_np]
  2237. expected_vals = xp.asarray(expected_vals, dtype=xp.float64)
  2238. xp_assert_close(bspl3(xi, nu=nu), expected_vals, atol=1e-14)
  2239. xp_assert_close(bspl3.derivative(nu)(xi), expected_vals, atol=1e-14)
  2240. def test_3D_random(self):
  2241. rng = np.random.default_rng(12345)
  2242. k = 3
  2243. tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
  2244. ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2245. tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2246. c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))
  2247. spl = NdBSpline((tx, ty, tz), c, k=k)
  2248. spl_0 = NdBSpline0((tx, ty, tz), c, k=k)
  2249. xi = (1., 1., 1)
  2250. xp_assert_close(spl(xi), spl_0(xi), atol=1e-14)
  2251. xi = np.c_[[1, 1.5, 2],
  2252. [1.1, 1.6, 2.1],
  2253. [0.9, 1.4, 1.9]]
  2254. xp_assert_close(spl(xi), [spl_0(xp) for xp in xi], atol=1e-14)
  2255. def test_3D_random_complex(self):
  2256. rng = np.random.default_rng(12345)
  2257. k = 3
  2258. tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
  2259. ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2260. tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2261. c = (rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1)) +
  2262. rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))*1j)
  2263. spl = NdBSpline((tx, ty, tz), c, k=k)
  2264. spl_re = NdBSpline((tx, ty, tz), c.real, k=k)
  2265. spl_im = NdBSpline((tx, ty, tz), c.imag, k=k)
  2266. xi = np.c_[[1, 1.5, 2],
  2267. [1.1, 1.6, 2.1],
  2268. [0.9, 1.4, 1.9]]
  2269. xp_assert_close(spl(xi),
  2270. spl_re(xi) + 1j*spl_im(xi), atol=1e-14)
  2271. @pytest.mark.parametrize('cls_extrap', [None, True])
  2272. @pytest.mark.parametrize('call_extrap', [None, True])
  2273. def test_extrapolate_3D_separable(self, cls_extrap, call_extrap):
  2274. # test that extrapolate=True does extrapolate
  2275. t3, c3, k = self.make_3d_case()
  2276. bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap)
  2277. # evaluate out of bounds
  2278. x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5]
  2279. x, y, z = map(np.asarray, (x, y, z))
  2280. xi = [_ for _ in zip(x, y, z)]
  2281. target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
  2282. result = bspl3(xi, extrapolate=call_extrap)
  2283. xp_assert_close(result, target, atol=1e-14)
  2284. @pytest.mark.parametrize('extrap', [(False, True), (True, None)])
  2285. def test_extrapolate_3D_separable_2(self, extrap):
  2286. # test that call(..., extrapolate=None) defers to self.extrapolate,
  2287. # otherwise supersedes self.extrapolate
  2288. t3, c3, k = self.make_3d_case()
  2289. cls_extrap, call_extrap = extrap
  2290. bspl3 = NdBSpline(t3, c3, k=3, extrapolate=cls_extrap)
  2291. # evaluate out of bounds
  2292. x, y, z = [-2, -1, 7], [-3, -0.5, 6.5], [-1, -1.5, 7.5]
  2293. x, y, z = map(np.asarray, (x, y, z))
  2294. xi = [_ for _ in zip(x, y, z)]
  2295. target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
  2296. result = bspl3(xi, extrapolate=call_extrap)
  2297. xp_assert_close(result, target, atol=1e-14)
  2298. def test_extrapolate_false_3D_separable(self):
  2299. # test that extrapolate=False produces nans for out-of-bounds values
  2300. t3, c3, k = self.make_3d_case()
  2301. bspl3 = NdBSpline(t3, c3, k=3)
  2302. # evaluate out of bounds and inside
  2303. x, y, z = [-2, 1, 7], [-3, 0.5, 6.5], [-1, 1.5, 7.5]
  2304. x, y, z = map(np.asarray, (x, y, z))
  2305. xi = [_ for _ in zip(x, y, z)]
  2306. target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
  2307. result = bspl3(xi, extrapolate=False)
  2308. assert np.isnan(result[0])
  2309. assert np.isnan(result[-1])
  2310. xp_assert_close(result[1:-1], target[1:-1], atol=1e-14)
  2311. def test_x_nan_3D(self):
  2312. # test that spline(nan) is nan
  2313. t3, c3, k = self.make_3d_case()
  2314. bspl3 = NdBSpline(t3, c3, k=3)
  2315. # evaluate out of bounds and inside
  2316. x = np.asarray([-2, 3, np.nan, 1, 2, 7, np.nan])
  2317. y = np.asarray([-3, 3.5, 1, np.nan, 3, 6.5, 6.5])
  2318. z = np.asarray([-1, 3.5, 2, 3, np.nan, 7.5, 7.5])
  2319. xi = [_ for _ in zip(x, y, z)]
  2320. target = x**3 * (y**3 + 2*y) * (z**3 + 3*z + 1)
  2321. mask = np.isnan(x) | np.isnan(y) | np.isnan(z)
  2322. target[mask] = np.nan
  2323. result = bspl3(xi)
  2324. assert np.isnan(result[mask]).all()
  2325. xp_assert_close(result, target, atol=1e-14)
  2326. def test_non_c_contiguous(self):
  2327. # check that non C-contiguous inputs are OK
  2328. rng = np.random.default_rng(12345)
  2329. kx, ky = 3, 3
  2330. tx = np.sort(rng.uniform(low=0, high=4, size=16))
  2331. tx = np.r_[(tx[0],)*kx, tx, (tx[-1],)*kx]
  2332. ty = np.sort(rng.uniform(low=0, high=4, size=16))
  2333. ty = np.r_[(ty[0],)*ky, ty, (ty[-1],)*ky]
  2334. assert not tx[::2].flags.c_contiguous
  2335. assert not ty[::2].flags.c_contiguous
  2336. c = rng.uniform(size=(tx.size//2 - kx - 1, ty.size//2 - ky - 1))
  2337. c = c.T
  2338. assert not c.flags.c_contiguous
  2339. xi = np.c_[[1, 1.5, 2],
  2340. [1.1, 1.6, 2.1]]
  2341. bspl2 = NdBSpline((tx[::2], ty[::2]), c, k=(kx, ky))
  2342. bspl2_0 = NdBSpline0((tx[::2], ty[::2]), c, k=(kx, ky))
  2343. xp_assert_close(bspl2(xi),
  2344. [bspl2_0(xp) for xp in xi], atol=1e-14)
  2345. def test_readonly(self):
  2346. t3, c3, k = self.make_3d_case()
  2347. bspl3 = NdBSpline(t3, c3, k=3)
  2348. for i in range(3):
  2349. t3[i].flags.writeable = False
  2350. c3.flags.writeable = False
  2351. bspl3_ = NdBSpline(t3, c3, k=3)
  2352. assert bspl3((1, 2, 3)) == bspl3_((1, 2, 3))
  2353. def test_design_matrix(self):
  2354. t3, c3, k = self.make_3d_case()
  2355. xi = np.asarray([[1, 2, 3], [4, 5, 6]])
  2356. dm = NdBSpline(t3, c3, k).design_matrix(xi, t3, k)
  2357. dm1 = NdBSpline.design_matrix(xi, t3, [k, k, k])
  2358. assert dm.shape[0] == xi.shape[0]
  2359. xp_assert_close(dm.todense(), dm1.todense(), atol=1e-16)
  2360. with assert_raises(ValueError):
  2361. NdBSpline.design_matrix([1, 2, 3], t3, [k]*3)
  2362. with assert_raises(ValueError, match="Data and knots*"):
  2363. NdBSpline.design_matrix([[1, 2]], t3, [k]*3)
  2364. def test_concurrency(self):
  2365. rng = np.random.default_rng(12345)
  2366. k = 3
  2367. tx = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7)) * 3, 3, 3, 3, 3]
  2368. ty = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2369. tz = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=8)) * 4, 4, 4, 4, 4]
  2370. c = rng.uniform(size=(tx.size-k-1, ty.size-k-1, tz.size-k-1))
  2371. spl = NdBSpline((tx, ty, tz), c, k=k)
  2372. def worker_fn(_, spl):
  2373. xi = np.c_[[1, 1.5, 2],
  2374. [1.1, 1.6, 2.1],
  2375. [0.9, 1.4, 1.9]]
  2376. spl(xi)
  2377. _run_concurrent_barrier(10, worker_fn, spl)
  2378. class TestMakeND:
  2379. def test_2D_separable_simple(self):
  2380. x = np.arange(6)
  2381. y = np.arange(6) + 0.5
  2382. values = x[:, None]**3 * (y**3 + 2*y)[None, :]
  2383. xi = [(a, b) for a, b in itertools.product(x, y)]
  2384. bspl = make_ndbspl((x, y), values, k=1)
  2385. xp_assert_close(bspl(xi), values.ravel(), atol=1e-15)
  2386. # test the coefficients vs outer product of 1D coefficients
  2387. spl_x = make_interp_spline(x, x**3, k=1)
  2388. spl_y = make_interp_spline(y, y**3 + 2*y, k=1)
  2389. cc = spl_x.c[:, None] * spl_y.c[None, :]
  2390. xp_assert_close(cc, bspl.c, atol=1e-11, rtol=0)
  2391. # test against RGI
  2392. from scipy.interpolate import RegularGridInterpolator as RGI
  2393. rgi = RGI((x, y), values, method='linear')
  2394. xp_assert_close(rgi(xi), bspl(xi), atol=1e-14)
  2395. def test_2D_separable_trailing_dims(self):
  2396. # test `c` with trailing dimensions, i.e. c.ndim > ndim
  2397. x = np.arange(6)
  2398. y = np.arange(6)
  2399. xi = [(a, b) for a, b in itertools.product(x, y)]
  2400. # make values4.shape = (6, 6, 4)
  2401. values = x[:, None]**3 * (y**3 + 2*y)[None, :]
  2402. values4 = np.dstack((values, values, values, values))
  2403. bspl = make_ndbspl((x, y), values4, k=3, solver=ssl.spsolve)
  2404. result = bspl(xi)
  2405. target = np.dstack((values, values, values, values)).astype(float)
  2406. assert result.shape == (36, 4)
  2407. xp_assert_close(result.reshape(6, 6, 4),
  2408. target, atol=1e-14)
  2409. # now two trailing dimensions
  2410. values22 = values4.reshape((6, 6, 2, 2))
  2411. bspl = make_ndbspl((x, y), values22, k=3, solver=ssl.spsolve)
  2412. result = bspl(xi)
  2413. assert result.shape == (36, 2, 2)
  2414. xp_assert_close(result.reshape(6, 6, 2, 2),
  2415. target.reshape((6, 6, 2, 2)), atol=1e-14)
  2416. @pytest.mark.parametrize('k', [(3, 3), (1, 1), (3, 1), (1, 3), (3, 5)])
  2417. def test_2D_mixed(self, k):
  2418. # make a 2D separable spline w/ len(tx) != len(ty)
  2419. x = np.arange(6)
  2420. y = np.arange(7) + 1.5
  2421. xi = [(a, b) for a, b in itertools.product(x, y)]
  2422. values = (x**3)[:, None] * (y**2 + 2*y)[None, :]
  2423. bspl = make_ndbspl((x, y), values, k=k, solver=ssl.spsolve)
  2424. xp_assert_close(bspl(xi), values.ravel(), atol=1e-15)
  2425. def test_2D_nans(self):
  2426. x = np.arange(6)
  2427. y = np.arange(6) + 0.5
  2428. y[-1] = np.nan
  2429. values = x[:, None]**3 * (y**3 + 2*y)[None, :]
  2430. with assert_raises(ValueError):
  2431. make_ndbspl((x, y), values, k=1)
  2432. def _get_sample_2d_data(self):
  2433. # from test_rgi.py::TestIntepN
  2434. x = np.array([.5, 2., 3., 4., 5.5, 6.])
  2435. y = np.array([.5, 2., 3., 4., 5.5, 6.])
  2436. z = np.array(
  2437. [
  2438. [1, 2, 1, 2, 1, 1],
  2439. [1, 2, 1, 2, 1, 1],
  2440. [1, 2, 3, 2, 1, 1],
  2441. [1, 2, 2, 2, 1, 1],
  2442. [1, 2, 1, 2, 1, 1],
  2443. [1, 2, 2, 2, 1, 1],
  2444. ]
  2445. )
  2446. return x, y, z
  2447. def test_2D_vs_RGI_linear(self):
  2448. x, y, z = self._get_sample_2d_data()
  2449. bspl = make_ndbspl((x, y), z, k=1)
  2450. rgi = RegularGridInterpolator((x, y), z, method='linear')
  2451. xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
  2452. [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
  2453. xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
  2454. def test_2D_vs_RGI_cubic(self):
  2455. x, y, z = self._get_sample_2d_data()
  2456. bspl = make_ndbspl((x, y), z, k=3, solver=ssl.spsolve)
  2457. rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy')
  2458. xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
  2459. [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
  2460. xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
  2461. @pytest.mark.parametrize('solver', [ssl.gmres, ssl.gcrotmk])
  2462. def test_2D_vs_RGI_cubic_iterative(self, solver):
  2463. # same as `test_2D_vs_RGI_cubic`, only with an iterative solver.
  2464. # Note the need to add an explicit `rtol` solver_arg to achieve the
  2465. # target accuracy of 1e-14. (the relation between solver atol/rtol
  2466. # and the accuracy of the final result is not direct and needs experimenting)
  2467. x, y, z = self._get_sample_2d_data()
  2468. bspl = make_ndbspl((x, y), z, k=3, solver=solver, rtol=1e-6)
  2469. rgi = RegularGridInterpolator((x, y), z, method='cubic_legacy')
  2470. xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
  2471. [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
  2472. xp_assert_close(bspl(xi), rgi(xi), atol=1e-14, rtol=1e-7)
  2473. def test_2D_vs_RGI_quintic(self):
  2474. x, y, z = self._get_sample_2d_data()
  2475. bspl = make_ndbspl((x, y), z, k=5, solver=ssl.spsolve)
  2476. rgi = RegularGridInterpolator((x, y), z, method='quintic_legacy')
  2477. xi = np.array([[1, 2.3, 5.3, 0.5, 3.3, 1.2, 3],
  2478. [1, 3.3, 1.2, 4.0, 5.0, 1.0, 3]]).T
  2479. xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
  2480. @pytest.mark.parametrize(
  2481. 'k, meth', [(1, 'linear'), (3, 'cubic_legacy'), (5, 'quintic_legacy')]
  2482. )
  2483. def test_3D_random_vs_RGI(self, k, meth):
  2484. rndm = np.random.default_rng(123456)
  2485. x = np.cumsum(rndm.uniform(size=6))
  2486. y = np.cumsum(rndm.uniform(size=7))
  2487. z = np.cumsum(rndm.uniform(size=8))
  2488. values = rndm.uniform(size=(6, 7, 8))
  2489. bspl = make_ndbspl((x, y, z), values, k=k, solver=ssl.spsolve)
  2490. rgi = RegularGridInterpolator((x, y, z), values, method=meth)
  2491. xi = np.random.uniform(low=0.7, high=2.1, size=(11, 3))
  2492. xp_assert_close(bspl(xi), rgi(xi), atol=1e-14)
  2493. def test_solver_err_not_converged(self):
  2494. x, y, z = self._get_sample_2d_data()
  2495. solver_args = {'maxiter': 1}
  2496. with assert_raises(ValueError, match='solver'):
  2497. make_ndbspl((x, y), z, k=3, **solver_args)
  2498. with assert_raises(ValueError, match='solver'):
  2499. make_ndbspl((x, y), np.dstack((z, z)), k=3, **solver_args)
  2500. class TestFpchec:
  2501. # https://github.com/scipy/scipy/blob/main/scipy/interpolate/fitpack/fpchec.f
  2502. def test_1D_x_t(self):
  2503. k = 1
  2504. t = np.arange(12).reshape(2, 6)
  2505. x = np.arange(12)
  2506. with pytest.raises(ValueError, match="1D sequence"):
  2507. _b.fpcheck(x, t, k)
  2508. with pytest.raises(ValueError, match="1D sequence"):
  2509. _b.fpcheck(t, x, k)
  2510. def test_condition_1(self):
  2511. # c 1) k+1 <= n-k-1 <= m
  2512. k = 3
  2513. n = 2*(k + 1) - 1 # not OK
  2514. m = n + 11 # OK
  2515. t = np.arange(n)
  2516. x = np.arange(m)
  2517. assert dfitpack.fpchec(x, t, k) == 10
  2518. with pytest.raises(ValueError, match="Need k+1*"):
  2519. _b.fpcheck(x, t, k)
  2520. n = 2*(k+1) + 1 # OK
  2521. m = n - k - 2 # not OK
  2522. t = np.arange(n)
  2523. x = np.arange(m)
  2524. assert dfitpack.fpchec(x, t, k) == 10
  2525. with pytest.raises(ValueError, match="Need k+1*"):
  2526. _b.fpcheck(x, t, k)
  2527. def test_condition_2(self):
  2528. # c 2) t(1) <= t(2) <= ... <= t(k+1)
  2529. # c t(n-k) <= t(n-k+1) <= ... <= t(n)
  2530. k = 3
  2531. t = [0]*(k+1) + [2] + [5]*(k+1) # this is OK
  2532. x = [1, 2, 3, 4, 4.5]
  2533. assert dfitpack.fpchec(x, t, k) == 0
  2534. assert _b.fpcheck(x, t, k) is None # does not raise
  2535. tt = t.copy()
  2536. tt[-1] = tt[0] # not OK
  2537. assert dfitpack.fpchec(x, tt, k) == 20
  2538. with pytest.raises(ValueError, match="Last k knots*"):
  2539. _b.fpcheck(x, tt, k)
  2540. tt = t.copy()
  2541. tt[0] = tt[-1] # not OK
  2542. assert dfitpack.fpchec(x, tt, k) == 20
  2543. with pytest.raises(ValueError, match="First k knots*"):
  2544. _b.fpcheck(x, tt, k)
  2545. def test_condition_3(self):
  2546. # c 3) t(k+1) < t(k+2) < ... < t(n-k)
  2547. k = 3
  2548. t = [0]*(k+1) + [2, 3] + [5]*(k+1) # this is OK
  2549. x = [1, 2, 3, 3.5, 4, 4.5]
  2550. assert dfitpack.fpchec(x, t, k) == 0
  2551. assert _b.fpcheck(x, t, k) is None
  2552. t = [0]*(k+1) + [2, 2] + [5]*(k+1) # this is not OK
  2553. assert dfitpack.fpchec(x, t, k) == 30
  2554. with pytest.raises(ValueError, match="Internal knots*"):
  2555. _b.fpcheck(x, t, k)
  2556. def test_condition_4(self):
  2557. # c 4) t(k+1) <= x(i) <= t(n-k)
  2558. # NB: FITPACK's fpchec only checks x[0] & x[-1], so we follow.
  2559. k = 3
  2560. t = [0]*(k+1) + [5]*(k+1)
  2561. x = [1, 2, 3, 3.5, 4, 4.5] # this is OK
  2562. assert dfitpack.fpchec(x, t, k) == 0
  2563. assert _b.fpcheck(x, t, k) is None
  2564. xx = x.copy()
  2565. xx[0] = t[0] # still OK
  2566. assert dfitpack.fpchec(xx, t, k) == 0
  2567. assert _b.fpcheck(x, t, k) is None
  2568. xx = x.copy()
  2569. xx[0] = t[0] - 1 # not OK
  2570. assert dfitpack.fpchec(xx, t, k) == 40
  2571. with pytest.raises(ValueError, match="Out of bounds*"):
  2572. _b.fpcheck(xx, t, k)
  2573. xx = x.copy()
  2574. xx[-1] = t[-1] + 1 # not OK
  2575. assert dfitpack.fpchec(xx, t, k) == 40
  2576. with pytest.raises(ValueError, match="Out of bounds*"):
  2577. _b.fpcheck(xx, t, k)
  2578. # ### Test the S-W condition (no 5)
  2579. # c 5) the conditions specified by schoenberg and whitney must hold
  2580. # c for at least one subset of data points, i.e. there must be a
  2581. # c subset of data points y(j) such that
  2582. # c t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
  2583. def test_condition_5_x1xm(self):
  2584. # x(1).ge.t(k2) .or. x(m).le.t(nk1)
  2585. k = 1
  2586. t = [0, 0, 1, 2, 2]
  2587. x = [1.1, 1.1, 1.1]
  2588. assert dfitpack.fpchec(x, t, k) == 50
  2589. with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
  2590. _b.fpcheck(x, t, k)
  2591. x = [0.5, 0.5, 0.5]
  2592. assert dfitpack.fpchec(x, t, k) == 50
  2593. with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
  2594. _b.fpcheck(x, t, k)
  2595. def test_condition_5_k1(self):
  2596. # special case nk3 (== n - k - 2) < 2
  2597. k = 1
  2598. t = [0, 0, 1, 1]
  2599. x = [0.5, 0.6]
  2600. assert dfitpack.fpchec(x, t, k) == 0
  2601. assert _b.fpcheck(x, t, k) is None
  2602. def test_condition_5_1(self):
  2603. # basically, there can't be an interval of t[j]..t[j+k+1] with no x
  2604. k = 3
  2605. t = [0]*(k+1) + [2] + [5]*(k+1)
  2606. x = [3]*5
  2607. assert dfitpack.fpchec(x, t, k) == 50
  2608. with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
  2609. _b.fpcheck(x, t, k)
  2610. t = [0]*(k+1) + [2] + [5]*(k+1)
  2611. x = [1]*5
  2612. assert dfitpack.fpchec(x, t, k) == 50
  2613. with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
  2614. _b.fpcheck(x, t, k)
  2615. def test_condition_5_2(self):
  2616. # same as _5_1, only the empty interval is in the middle
  2617. k = 3
  2618. t = [0]*(k+1) + [2, 3] + [5]*(k+1)
  2619. x = [1.1]*5 + [4]
  2620. assert dfitpack.fpchec(x, t, k) == 50
  2621. with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
  2622. _b.fpcheck(x, t, k)
  2623. # and this one is OK
  2624. x = [1.1]*4 + [4, 4]
  2625. assert dfitpack.fpchec(x, t, k) == 0
  2626. assert _b.fpcheck(x, t, k) is None
  2627. def test_condition_5_3(self):
  2628. # similar to _5_2, covers a different failure branch
  2629. k = 1
  2630. t = [0, 0, 2, 3, 4, 5, 6, 7, 7]
  2631. x = [1, 1, 1, 5.2, 5.2, 5.2, 6.5]
  2632. assert dfitpack.fpchec(x, t, k) == 50
  2633. with pytest.raises(ValueError, match="Schoenberg-Whitney*"):
  2634. _b.fpcheck(x, t, k)
  2635. # ### python replicas of generate_knots(...) implementation details, for testing.
  2636. # ### see TestGenerateKnots::test_split_and_add_knot
  2637. def _split(x, t, k, residuals):
  2638. """Split the knot interval into "runs".
  2639. """
  2640. ix = np.searchsorted(x, t[k:-k])
  2641. # sum half-open intervals
  2642. fparts = [residuals[ix[i]:ix[i+1]].sum() for i in range(len(ix)-1)]
  2643. carries = residuals[ix[1:-1]]
  2644. for i in range(len(carries)): # split residuals at internal knots
  2645. carry = carries[i] / 2
  2646. fparts[i] += carry
  2647. fparts[i+1] -= carry
  2648. fparts[-1] += residuals[-1] # add the contribution of the last knot
  2649. xp_assert_close(sum(fparts), sum(residuals), atol=1e-15)
  2650. return fparts, ix
  2651. def _add_knot(x, t, k, residuals):
  2652. """Insert a new knot given reduals."""
  2653. fparts, ix = _split(x, t, k, residuals)
  2654. # find the interval with max fparts and non-zero number of x values inside
  2655. idx_max = -101
  2656. fpart_max = -1e100
  2657. for i in range(len(fparts)):
  2658. if ix[i+1] - ix[i] > 1 and fparts[i] > fpart_max:
  2659. idx_max = i
  2660. fpart_max = fparts[i]
  2661. if idx_max == -101:
  2662. raise ValueError("Internal error, please report it to SciPy developers.")
  2663. # round up, like Dierckx does? This is really arbitrary though.
  2664. idx_newknot = (ix[idx_max] + ix[idx_max+1] + 1) // 2
  2665. new_knot = x[idx_newknot]
  2666. idx_t = np.searchsorted(t, new_knot)
  2667. t_new = np.r_[t[:idx_t], new_knot, t[idx_t:]]
  2668. return t_new
  2669. @make_xp_test_case(generate_knots)
  2670. class TestGenerateKnots:
  2671. def test_split_add_knot(self):
  2672. # smoke test implementation details: insert a new knot given residuals
  2673. x = np.arange(8, dtype=float)
  2674. y = x**3 + 1./(1 + x)
  2675. k = 3
  2676. t = np.array([0.]*(k+1) + [7.]*(k+1))
  2677. spl = make_lsq_spline(x, y, k=k, t=t)
  2678. residuals = (spl(x) - y)**2
  2679. from scipy.interpolate import _fitpack_repro as _fr
  2680. new_t = _fr.add_knot(x, t, k, residuals)
  2681. new_t_py = _add_knot(x, t, k, residuals)
  2682. xp_assert_close(new_t, new_t_py, atol=1e-15)
  2683. # redo with new knots
  2684. spl2 = make_lsq_spline(x, y, k=k, t=new_t)
  2685. residuals2 = (spl2(x) - y)**2
  2686. new_t2 = _fr.add_knot(x, new_t, k, residuals2)
  2687. new_t2_py = _add_knot(x, new_t, k, residuals2)
  2688. xp_assert_close(new_t2, new_t2_py, atol=1e-15)
  2689. @pytest.mark.parametrize('k', [1, 2, 3, 4, 5])
  2690. def test_s0(self, k, xp):
  2691. x = xp.arange(8, dtype=xp.float64)
  2692. y = xp.sin(x*xp.pi/8)
  2693. t = list(generate_knots(x, y, k=k, s=0))[-1]
  2694. tt = splrep(x, y, k=k, s=0)[0]
  2695. tt = xp.asarray(tt, dtype=xp.float64)
  2696. xp_assert_close(t, tt, atol=1e-15)
  2697. def test_s0_1(self, xp):
  2698. # with these data, naive algorithm tries to insert >= nmax knots
  2699. n = 10
  2700. x = xp.arange(n, dtype=xp.float64)
  2701. y = x**3
  2702. knots = list(generate_knots(x, y, k=3, s=0)) # does not error out
  2703. expected = xp.asarray(_not_a_knot(np.asarray(x), 3))
  2704. xp_assert_close(knots[-1], expected, atol=1e-15)
  2705. def test_s0_n20(self, xp):
  2706. n = 20
  2707. x = xp.arange(n)
  2708. y = x**3
  2709. knots = list(generate_knots(x, y, k=3, s=0))
  2710. expected = xp.asarray(_not_a_knot(np.asarray(x), 3))
  2711. xp_assert_close(knots[-1], expected, atol=1e-15)
  2712. def test_s0_nest(self):
  2713. # s=0 and non-default nest: not implemented, errors out
  2714. x = np.arange(10)
  2715. y = x**3
  2716. with assert_raises(ValueError):
  2717. list(generate_knots(x, y, k=3, s=0, nest=10))
  2718. def test_s_switch(self, xp):
  2719. # test the process switching to interpolating knots when len(t) == m + k + 1
  2720. """
  2721. To generate the `wanted` list below apply the following diff and rerun
  2722. the test. The stdout will contain successive iterations of the `t`
  2723. array.
  2724. $ git diff scipy/interpolate/fitpack/fpcurf.f
  2725. diff --git a/scipy/interpolate/fitpack/fpcurf.f b/scipy/interpolate/fitpack/fpcurf.f
  2726. index 1afb1900f1..d817e51ad8 100644
  2727. --- a/scipy/interpolate/fitpack/fpcurf.f
  2728. +++ b/scipy/interpolate/fitpack/fpcurf.f
  2729. @@ -216,6 +216,9 @@ c t(j+k) <= x(i) <= t(j+k+1) and store it in fpint(j),j=1,2,...nrint.
  2730. do 190 l=1,nplus
  2731. c add a new knot.
  2732. call fpknot(x,m,t,n,fpint,nrdata,nrint,nest,1)
  2733. + print*, l, nest, ': ', t
  2734. + print*, "n, nmax = ", n, nmax
  2735. +
  2736. c if n=nmax we locate the knots as for interpolation.
  2737. if(n.eq.nmax) go to 10
  2738. c test whether we cannot further increase the number of knots.
  2739. """ # NOQA: E501
  2740. x = xp.arange(8, dtype=xp.float64)
  2741. y = xp.sin(x*np.pi/8)
  2742. k = 3
  2743. knots = list(generate_knots(x, y, k=k, s=1e-7))
  2744. wanted = [[0., 0., 0., 0., 7., 7., 7., 7.],
  2745. [0., 0., 0., 0., 4., 7., 7., 7., 7.],
  2746. [0., 0., 0., 0., 2., 4., 7., 7., 7., 7.],
  2747. [0., 0., 0., 0., 2., 4., 6., 7., 7., 7., 7.],
  2748. [0., 0., 0., 0., 2., 3., 4., 5., 7, 7., 7., 7.]
  2749. ]
  2750. wanted = [xp.asarray(want, dtype=xp.float64) for want in wanted]
  2751. assert len(knots) == len(wanted)
  2752. for t, tt in zip(knots, wanted):
  2753. xp_assert_close(t, tt, atol=1e-15)
  2754. # also check that the last knot vector matches FITPACK
  2755. t, _, _ = splrep(x, y, k=k, s=1e-7)
  2756. xp_assert_close(knots[-1], xp.asarray(t), atol=1e-15)
  2757. def test_list_input(self):
  2758. # test that list inputs are accepted
  2759. x = list(range(8))
  2760. gen = generate_knots(x, x, s=0.1, k=1)
  2761. next(gen)
  2762. def test_nest(self, xp):
  2763. # test that nest < nmax stops the process early (and we get 10 knots not 12)
  2764. x = xp.arange(8, dtype=xp.float64)
  2765. y = xp.sin(x*xp.pi/8)
  2766. s = 1e-7
  2767. knots = list(generate_knots(x, y, k=3, s=s, nest=10))
  2768. xp_assert_close(
  2769. knots[-1],
  2770. xp.asarray([0., 0., 0., 0., 2., 4., 7., 7., 7., 7.], dtype=xp.float64),
  2771. atol=1e-15
  2772. )
  2773. with assert_raises(ValueError):
  2774. # nest < 2*(k+1)
  2775. list(generate_knots(x, y, k=3, nest=4))
  2776. def test_weights(self):
  2777. x = np.arange(8)
  2778. y = np.sin(x*np.pi/8)
  2779. with assert_raises(ValueError):
  2780. list(generate_knots(x, y, w=np.arange(11))) # len(w) != len(x)
  2781. with assert_raises(ValueError):
  2782. list(generate_knots(x, y, w=-np.ones(8))) # w < 0
  2783. @pytest.mark.parametrize("npts", [30, 50, 100])
  2784. @pytest.mark.parametrize("s", [0.1, 1e-2, 0])
  2785. def test_vs_splrep(self, s, npts):
  2786. # XXX this test is brittle: differences start apearing for k=3 and s=1e-6,
  2787. # also for k != 3. Might be worth investigating at some point.
  2788. # I think we do not really guarantee exact agreement with splrep. Instead,
  2789. # we guarantee it is the same *in most cases*; otherwise slight differences
  2790. # are allowed. There is no theorem, it is al heuristics by P. Dierckx.
  2791. # The best we can do it to best-effort reproduce it.
  2792. rndm = np.random.RandomState(12345)
  2793. x = 10*np.sort(rndm.uniform(size=npts))
  2794. y = np.sin(x*np.pi/10) + np.exp(-(x-6)**2)
  2795. k = 3
  2796. t = splrep(x, y, k=k, s=s)[0]
  2797. tt = list(generate_knots(x, y, k=k, s=s))[-1]
  2798. xp_assert_close(tt, t, atol=1e-15)
  2799. def test_s_too_small(self):
  2800. n = 14
  2801. x = np.arange(n)
  2802. y = x**3
  2803. # XXX splrep warns that "s too small": ier=2
  2804. knots = list(generate_knots(x, y, k=3, s=1e-50))
  2805. with pytest.warns(RuntimeWarning) as r:
  2806. tck = splrep(x, y, k=3, s=1e-50)
  2807. assert len(r) == 1
  2808. xp_assert_equal(knots[-1], tck[0])
  2809. def test_zero_weights(self):
  2810. # regression test for https://github.com/scipy/scipy/issues/23542
  2811. gen = generate_knots([0.,1.,2.,3.], [4.,5.,6.,7.], w=[0.,0.,0.,0.], s=1)
  2812. with pytest.raises(ValueError, match="weights are zero"):
  2813. list(gen)
  2814. def disc_naive(t, k):
  2815. """Straitforward way to compute the discontinuity matrix. For testing ONLY.
  2816. This routine returns a dense matrix, while `_fitpack_repro.disc` returns
  2817. a packed one.
  2818. """
  2819. n = t.shape[0]
  2820. delta = t[n - k - 1] - t[k]
  2821. nrint = n - 2*k - 1
  2822. ti = t[k+1:n-k-1] # internal knots
  2823. tii = np.repeat(ti, 2)
  2824. tii[::2] += 1e-10
  2825. tii[1::2] -= 1e-10
  2826. m = BSpline(t, np.eye(n - k - 1), k)(tii, nu=k)
  2827. matr = np.empty((nrint-1, m.shape[1]), dtype=float)
  2828. for i in range(0, m.shape[0], 2):
  2829. matr[i//2, :] = m[i, :] - m[i+1, :]
  2830. matr *= (delta/nrint)**k / math.factorial(k)
  2831. return matr
  2832. class F_dense:
  2833. """ The r.h.s. of ``f(p) = s``, an analog of _fitpack_repro.F
  2834. Uses full matrices, so is for tests only.
  2835. """
  2836. def __init__(self, x, y, t, k, s, w=None, extrapolate=True):
  2837. self.x = x
  2838. self.y = y
  2839. self.t = t
  2840. self.k = k
  2841. self.w = np.ones_like(x, dtype=float) if w is None else w
  2842. self.extrapolate = extrapolate
  2843. assert self.w.ndim == 1
  2844. # lhs
  2845. a_dense = BSpline(t, np.eye(t.shape[0] - k - 1), k, extrapolate=extrapolate)(x)
  2846. self.a_dense = a_dense * self.w[:, None]
  2847. from scipy.interpolate import _fitpack_repro as _fr
  2848. self.b_dense = PackedMatrix(*_fr.disc(t, k)).todense()
  2849. # rhs
  2850. assert y.ndim == 1
  2851. yy = y * self.w
  2852. self.yy = np.r_[yy, np.zeros(self.b_dense.shape[0])]
  2853. self.s = s
  2854. def __call__(self, p):
  2855. ab = np.vstack((self.a_dense, self.b_dense / p))
  2856. # LSQ solution of ab @ c = yy
  2857. from scipy.linalg import qr, solve
  2858. q, r = qr(ab, mode='economic')
  2859. qy = q.T @ self.yy
  2860. nc = r.shape[1]
  2861. c = solve(r[:nc, :nc], qy[:nc])
  2862. spl = BSpline(self.t, c, self.k, extrapolate=self.extrapolate)
  2863. fp = np.sum(self.w**2 * (spl(self.x) - self.y)**2)
  2864. self.spl = spl # store it
  2865. return fp - self.s
  2866. class _TestMakeSplrepBase:
  2867. bc_type = None
  2868. def _get_xykt(self, xp=np):
  2869. if self.bc_type == 'periodic':
  2870. x = xp.linspace(0, 2*np.pi, 10) # nodes
  2871. y = xp.sin(x)
  2872. s = 1.7e-4
  2873. return x, y, s
  2874. else:
  2875. x = xp.linspace(0, 5, 11)
  2876. y = xp.sin(x*3.14 / 5)**2
  2877. s = 1.7e-4
  2878. return x, y, s
  2879. def test_input_errors(self):
  2880. x = np.linspace(0, 10, 11)
  2881. y = np.linspace(0, 10, 12)
  2882. with assert_raises(ValueError):
  2883. # len(x) != len(y)
  2884. make_splrep(x, y, bc_type=self.bc_type)
  2885. with assert_raises(ValueError):
  2886. # 0D inputs
  2887. make_splrep(1, 2, s=0.1, bc_type=self.bc_type)
  2888. with assert_raises(ValueError):
  2889. # y.ndim > 2
  2890. y = np.ones((x.size, 2, 2, 2))
  2891. make_splrep(x, y, s=0.1, bc_type=self.bc_type)
  2892. w = np.ones(12)
  2893. with assert_raises(ValueError):
  2894. # len(weights) != len(x)
  2895. make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type)
  2896. w = -np.ones(12)
  2897. with assert_raises(ValueError):
  2898. # w < 0
  2899. make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type)
  2900. w = np.ones((x.shape[0], 2))
  2901. with assert_raises(ValueError):
  2902. # w.ndim != 1
  2903. make_splrep(x, x**3, w=w, s=0.1, bc_type=self.bc_type)
  2904. with assert_raises(ValueError):
  2905. # x not ordered
  2906. make_splrep(x[::-1], x**3, s=0.1, bc_type=self.bc_type)
  2907. with assert_raises(TypeError):
  2908. # k != int(k)
  2909. make_splrep(x, x**3, k=2.5, s=0.1, bc_type=self.bc_type)
  2910. with assert_raises(ValueError):
  2911. # s < 0
  2912. make_splrep(x, x**3, s=-1, bc_type=self.bc_type)
  2913. with assert_raises(ValueError):
  2914. # nest < 2*k + 2
  2915. make_splrep(x, x**3, k=3, nest=2, s=0.1, bc_type=self.bc_type)
  2916. with assert_raises(ValueError):
  2917. # nest not None and s==0
  2918. make_splrep(x, x**3, s=0, nest=11, bc_type=self.bc_type)
  2919. with assert_raises(ValueError):
  2920. # len(x) != len(y)
  2921. make_splrep(np.arange(8), np.arange(9), s=0.1, bc_type=self.bc_type)
  2922. def _test_with_knots(self, x, y, k, s):
  2923. t = list(generate_knots(x, y, k=k, s=s, bc_type=self.bc_type))[-1]
  2924. spl_auto = make_splrep(x, y, k=k, s=s, bc_type=self.bc_type)
  2925. spl_t = make_splrep(x, y, t=t, k=k, s=s, bc_type=self.bc_type)
  2926. xp_assert_close(spl_auto.t, spl_t.t, atol=1e-15)
  2927. xp_assert_close(spl_auto.c, spl_t.c, atol=1e-15)
  2928. assert spl_auto.k == spl_t.k
  2929. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
  2930. def test_with_knots(self, k):
  2931. x, y, s = self._get_xykt()
  2932. self._test_with_knots(x, y, k, s)
  2933. def _test_default_s(self, x, y, k):
  2934. spl = make_splrep(x, y, k=k, bc_type=self.bc_type)
  2935. spl_i = make_interp_spline(x, y, k=k, bc_type=self.bc_type)
  2936. t = list(generate_knots(x, y, k=k, bc_type=self.bc_type))[-1]
  2937. xp_assert_close(spl.c, spl_i.c, atol=1e-15)
  2938. xp_assert_close(spl.t, t, atol=1e-15)
  2939. xp_assert_close(spl_i.t, t, atol=1e-15)
  2940. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
  2941. def test_default_s(self, k):
  2942. x, y, _ = self._get_xykt()
  2943. self._test_default_s(x, y, k)
  2944. @pytest.mark.thread_unsafe
  2945. def test_s_too_small(self):
  2946. # both splrep and make_splrep warn that "s too small": ier=2
  2947. s = 1e-30
  2948. if self.bc_type == 'periodic':
  2949. x = np.linspace(0, 2*np.pi, 14)
  2950. y = np.sin(x)
  2951. else:
  2952. x = np.arange(14)
  2953. y = x**3
  2954. with warnings.catch_warnings():
  2955. warnings.simplefilter(
  2956. "ignore",
  2957. RuntimeWarning
  2958. )
  2959. tck = splrep(x, y, k=3, s=s, per=(self.bc_type == 'periodic'))
  2960. with warnings.catch_warnings():
  2961. warnings.simplefilter(
  2962. "ignore",
  2963. RuntimeWarning
  2964. )
  2965. spl = make_splrep(x, y, k=3, s=s, bc_type=self.bc_type)
  2966. xp_assert_close(spl.t, tck[0])
  2967. xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
  2968. tck[1], atol=5e-13)
  2969. @pytest.mark.parametrize("k", [1, 2, 3])
  2970. def test_shape(self, k):
  2971. # make sure coefficients have the right shape (not extra dims)
  2972. n = 10
  2973. if self.bc_type == 'periodic':
  2974. x = np.linspace(0, 2*np.pi, n)
  2975. y = np.cos(x)
  2976. else:
  2977. x = np.arange(n)
  2978. y = x**3
  2979. spl = make_splrep(x, y, k=k, bc_type=self.bc_type)
  2980. spl_1 = make_splrep(x, y, k=k, s=1e-5, bc_type=self.bc_type)
  2981. assert spl.c.ndim == 1
  2982. assert spl_1.c.ndim == 1
  2983. # force the general code path, not shortcuts
  2984. spl_2 = make_splrep(x, y + 1/(1+y), k=k, s=1e-5, bc_type=self.bc_type)
  2985. assert spl_2.c.ndim == 1
  2986. def test_error_on_invalid_bc_type(self):
  2987. N = 10
  2988. a, b = 0, 2*np.pi
  2989. x = np.linspace(a, b, N + 1) # nodes
  2990. y = np.exp(x)
  2991. with assert_raises(ValueError):
  2992. make_splrep(x, y, s=1e-8, bc_type="nonsense")
  2993. @pytest.mark.parametrize("bc_type", ["periodic", None])
  2994. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5])
  2995. def test_make_splrep_with_unequal_weights(self, bc_type, k):
  2996. # Sample data
  2997. x = np.linspace(0, 2*np.pi, 10)
  2998. y = np.sin(x)
  2999. w = np.linspace(1, 5, len(x))
  3000. tck = splrep(x, y, w=w, k=k, s=1e-8, per=(bc_type == 'periodic'))
  3001. spl = make_splrep(x, y, w=w, s=1e-8, k=k, bc_type=bc_type)
  3002. xp_assert_close(spl.t, tck[0])
  3003. xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
  3004. tck[1], atol=1e-8)
  3005. @pytest.mark.parametrize("bc_type", ["periodic", None])
  3006. def test_make_splrep_with_non_c_contiguous_input(self, bc_type):
  3007. # regression test for https://github.com/scipy/scipy/issues/23371
  3008. def check(spl, tck):
  3009. xp_assert_close(spl.t, tck[0])
  3010. xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
  3011. tck[1], atol=1e-8)
  3012. # Sample data
  3013. x = np.linspace(0, 2*np.pi, 10)
  3014. y = np.sin(x)
  3015. x1, y1 = np.c_[x, y].T
  3016. # Safety check to make sure inputs
  3017. # are actually not C contiguous
  3018. assert x1.flags.c_contiguous is False
  3019. assert y1.flags.c_contiguous is False
  3020. w = np.linspace(1, 5, len(x))
  3021. w1, _ = np.c_[w, w].T
  3022. # Safety check to make sure inputs
  3023. # are actually not C contiguous
  3024. assert w1.flags.c_contiguous is False
  3025. tck = splrep(x, y, w=w, k=3, s=1e-8, per=(bc_type == 'periodic'))
  3026. # only x.flags.c_contiguous is False
  3027. spl = make_splrep(x1, y, w=w, s=1e-8, k=3, bc_type=bc_type)
  3028. check(spl, tck)
  3029. # only x.flags.c_contiguous is False
  3030. spl = make_splrep(x, y1, w=w, s=1e-8, k=3, bc_type=bc_type)
  3031. check(spl, tck)
  3032. # only w.flags.c_contiguous is False
  3033. spl = make_splrep(x, y, w=w1, s=1e-8, k=3, bc_type=bc_type)
  3034. check(spl, tck)
  3035. # x, y, z all have c_contiguous False
  3036. spl = make_splrep(x1, y1, w=w1, s=1e-8, k=3,
  3037. bc_type=bc_type)
  3038. check(spl, tck)
  3039. @pytest.mark.parametrize("bc_type", ["periodic", None])
  3040. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5])
  3041. def test_make_splrep_impl_no_optimization(self, bc_type, k):
  3042. # Sample data
  3043. x = np.linspace(0, 1, 10)
  3044. y = np.sin(2 * np.pi * x)
  3045. xb, xe = x[0], x[-1]
  3046. k = 3 # Cubic spline
  3047. s = 1e-8 # No smoothing
  3048. # Provide t with only boundary knots -> length = 2*(k+1)
  3049. t = np.array([xb] * (k + 1) + [xe] * (k + 1))
  3050. # Should skip optimization
  3051. spl = make_splrep(x, y, xb=xb, xe=xe, k=k,
  3052. s=s, t=t, nest=None, bc_type=bc_type)
  3053. assert isinstance(spl, BSpline)
  3054. assert spl.t.shape[0] == 2 * (k + 1)
  3055. assert spl.k == k
  3056. xp_assert_close(spl.t[:k+1], np.asarray([xb] * (k + 1)))
  3057. xp_assert_close(spl.t[-(k+1):], np.asarray([xe] * (k + 1)))
  3058. @pytest.mark.parametrize("n", [100, 51, 15, 11])
  3059. @pytest.mark.parametrize("s", [10, 8, 5, 1, 1e-2])
  3060. def test_make_splrep_matches_splrep_periodic(self, n, s):
  3061. rng = np.random.default_rng(123)
  3062. x = np.r_[0, np.sort(rng.uniform(0, 2 * np.pi, size=n - 2)), 2 * np.pi]
  3063. y = np.sin(x) + np.cos(x)
  3064. t, c, k = splrep(x, y, s=s, per=(self.bc_type == "periodic"))
  3065. spl = make_splrep(x, y, s=s, bc_type=self.bc_type)
  3066. if not (n == 11 and s == 1 and self.bc_type == "periodic"):
  3067. xp_assert_close(spl.t, t, atol=1e-15)
  3068. xp_assert_close(spl.c, c[:-k - 1], atol=1e-15)
  3069. @pytest.mark.parametrize("n", [100, 51, 15, 11])
  3070. @pytest.mark.parametrize("s", [10, 8, 5, 1, 1e-2])
  3071. def test_make_splrep_with_splrep_knots(self, n, s):
  3072. rng = np.random.default_rng(123)
  3073. x = np.r_[0, np.sort(rng.uniform(0, 2 * np.pi, size=n - 2)), 2 * np.pi]
  3074. y = np.sin(x) + np.cos(x)
  3075. t, c, k = splrep(x, y, s=s, per=(self.bc_type == "periodic"))
  3076. spl = make_splrep(x, y, s=s, bc_type=self.bc_type, t=t)
  3077. xp_assert_close(spl.c, c[:-k - 1], atol=1e-15)
  3078. @make_xp_test_case(make_splrep)
  3079. class TestMakeSplrep(_TestMakeSplrepBase):
  3080. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
  3081. def test_fitpack_F(self, k):
  3082. # test an implementation detail: banded/packed linalg vs full matrices
  3083. from scipy.interpolate._fitpack_repro import F
  3084. x, y, s = self._get_xykt()
  3085. t = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
  3086. f = F(x, y[:, None], t, k, s) # F expects y to be 2D
  3087. f_d = F_dense(x, y, t, k, s)
  3088. for p in [1, 10, 100]:
  3089. xp_assert_close(f(p), f_d(p), atol=1e-15)
  3090. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
  3091. def test_fitpack_F_with_weights(self, k):
  3092. # repeat test_fitpack_F, with weights
  3093. from scipy.interpolate._fitpack_repro import F
  3094. x, y, s = self._get_xykt()
  3095. t = np.array([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
  3096. w = np.arange(x.shape[0], dtype=float)
  3097. fw = F(x, y[:, None], t, k, s, w=w) # F expects y to be 2D
  3098. fw_d = F_dense(x, y, t, k, s, w=w)
  3099. f_d = F_dense(x, y, t, k, s) # no weights
  3100. for p in [1, 10, 100]:
  3101. xp_assert_close(fw(p), fw_d(p), atol=1e-15)
  3102. assert not np.allclose(f_d(p), fw_d(p), atol=1e-15)
  3103. def test_disc_matrix(self):
  3104. # test an implementation detail: discontinuity matrix
  3105. # (jumps of k-th derivative at knots)
  3106. import scipy.interpolate._fitpack_repro as _fr
  3107. rng = np.random.default_rng(12345)
  3108. t = np.r_[0, 0, 0, 0, np.sort(rng.uniform(size=7))*5, 5, 5, 5, 5]
  3109. n, k = len(t), 3
  3110. D = PackedMatrix(*_fr.disc(t, k)).todense()
  3111. D_dense = disc_naive(t, k)
  3112. assert D.shape[0] == n - 2*k - 2 # number of internal knots
  3113. xp_assert_close(D, D_dense, atol=1e-15)
  3114. def test_simple_vs_splrep(self, xp):
  3115. # XX: Non-periodic splines do not work for all supported degrees
  3116. k = 3
  3117. x, y, s = self._get_xykt(xp)
  3118. tt = xp.asarray([0]*(k+1) + [2.5, 4.0] + [5]*(k+1))
  3119. t, c, k = splrep(x, y, k=k, s=s)
  3120. t, c = xp.asarray(t), xp.asarray(c)
  3121. assert all(t == tt)
  3122. spl = make_splrep(x, y, k=k, s=s)
  3123. xp_assert_close(c[:spl.c.shape[0]], spl.c, atol=1e-15)
  3124. def test_with_knots(self):
  3125. k = 3
  3126. x, y, s = self._get_xykt()
  3127. t = list(generate_knots(x, y, k=k, s=s))[-1]
  3128. spl_auto = make_splrep(x, y, k=k, s=s)
  3129. spl_t = make_splrep(x, y, t=t, k=k, s=s)
  3130. xp_assert_close(spl_auto.t, spl_t.t, atol=1e-15)
  3131. xp_assert_close(spl_auto.c, spl_t.c, atol=1e-15)
  3132. assert spl_auto.k == spl_t.k
  3133. def test_no_internal_knots(self, xp):
  3134. # should not fail if there are no internal knots
  3135. n = 10
  3136. x = xp.arange(n, dtype=xp.float64)
  3137. y = x**3
  3138. k = 3
  3139. spl = make_splrep(x, y, k=k, s=1)
  3140. assert spl.t.shape[0] == 2*(k+1)
  3141. def test_default_s(self, xp):
  3142. n = 10
  3143. x = xp.arange(n, dtype=xp.float64)
  3144. y = x**3
  3145. spl = make_splrep(x, y, k=3)
  3146. spl_i = make_interp_spline(x, y, k=3)
  3147. xp_assert_close(spl.c, spl_i.c, atol=1e-15)
  3148. def test_s_too_small(self):
  3149. # both splrep and make_splrep warn that "s too small": ier=2
  3150. n = 14
  3151. x = np.arange(n)
  3152. y = x**3
  3153. with pytest.warns(RuntimeWarning) as r:
  3154. tck = splrep(x, y, k=3, s=1e-50)
  3155. spl = make_splrep(x, y, k=3, s=1e-50)
  3156. xp_assert_equal(spl.t, tck[0])
  3157. xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
  3158. tck[1], atol=5e-13)
  3159. assert len(r) == 2
  3160. def test_issue_22704(self):
  3161. # Reference - https://github.com/scipy/scipy/issues/22704
  3162. x = np.asarray([20.00, 153.81, 175.57, 202.47, 237.11,
  3163. 253.61, 258.56, 273.40, 284.54, 293.61,
  3164. 298.56, 301.86, 305.57, 307.22, 308.45,
  3165. 310.10, 310.10, 310.50], dtype=np.float64)
  3166. y = np.asarray([53.00, 49.50, 48.60, 46.80, 43.20,
  3167. 40.32, 39.60, 36.00, 32.40, 28.80,
  3168. 25.20, 21.60, 18.00, 14.40, 10.80,
  3169. 7.20, 3.60, 0.0], dtype=np.float64)
  3170. w = np.asarray([1.38723] * y.shape[0], dtype=np.float64)
  3171. with assert_raises(ValueError):
  3172. make_splrep(x, y, w=w, k=2, s=12)
  3173. def test_shape(self, xp):
  3174. # make sure coefficients have the right shape (not extra dims)
  3175. n, k = 10, 3
  3176. x = xp.arange(n, dtype=xp.float64)
  3177. y = x**3
  3178. spl = make_splrep(x, y, k=k)
  3179. spl_1 = make_splrep(x, y, k=k, s=1e-5)
  3180. assert spl.c.ndim == 1
  3181. assert spl_1.c.ndim == 1
  3182. # force the general code path, not shortcuts
  3183. spl_2 = make_splrep(x, y + 1/(1+y), k=k, s=1e-5)
  3184. assert spl_2.c.ndim == 1
  3185. def test_s0_vs_not(self, xp):
  3186. # check that the shapes are consistent
  3187. n, k = 10, 3
  3188. x = xp.arange(n, dtype=xp.float64)
  3189. y = x**3
  3190. spl_0 = make_splrep(x, y, k=3, s=0)
  3191. spl_1 = make_splrep(x, y, k=3, s=1)
  3192. assert spl_0.c.ndim == 1
  3193. assert spl_1.c.ndim == 1
  3194. assert spl_0.t.shape[0] == n + k + 1
  3195. assert spl_1.t.shape[0] == 2 * (k + 1)
  3196. @make_xp_test_case(make_splrep)
  3197. class TestMakeSplrepPeriodic(_TestMakeSplrepBase):
  3198. bc_type = 'periodic'
  3199. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
  3200. def test_no_internal_knots(self, k, xp):
  3201. # should not fail if there are no internal knots
  3202. x = xp.linspace(0, 10, 11) # nodes
  3203. y = xp.ones((11,))
  3204. spl = make_splrep(x, y, k=k, s=1, bc_type=self.bc_type)
  3205. assert spl.t.shape[0] == 2*(k+1)
  3206. @pytest.mark.parametrize("k", [1, 2, 3, 4, 5, 6])
  3207. def test_s0_vs_not(self, k):
  3208. # check that the shapes are consistent
  3209. n = 10
  3210. x = np.linspace(0, 2*np.pi, n)
  3211. y = np.sin(x) + np.cos(x)
  3212. spl_0 = make_splrep(x, y, k=k, s=0, bc_type=self.bc_type)
  3213. spl_1 = make_splrep(x, y, k=k, s=1, bc_type=self.bc_type)
  3214. assert spl_0.c.ndim == 1
  3215. assert spl_1.c.ndim == 1
  3216. assert spl_0.t.shape[0] == n + 2 * k
  3217. def test_periodic_with_periodic_data(self, xp):
  3218. N = 10
  3219. a, b = 0, 2*xp.pi
  3220. x = xp.linspace(a, b, N + 1, dtype=xp.float64) # nodes
  3221. y = xp.cos(x)
  3222. spl = make_splrep(x, y, s=1e-8, bc_type=self.bc_type)
  3223. xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-4)
  3224. y = xp.sin(x) + xp.cos(x)
  3225. spl = make_splrep(x, y, s=1e-12, bc_type=self.bc_type)
  3226. xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-6)
  3227. y = 5*xp.sin(x) + xp.cos(x)*3
  3228. spl = make_splrep(x, y, s=1e-8, bc_type=self.bc_type)
  3229. xp_assert_close(splev(x, spl), y, atol=1e-5, rtol=1e-4)
  3230. def test_periodic_with_non_periodic_data(self):
  3231. N = 10
  3232. a, b = 0, 2*np.pi
  3233. x = np.linspace(a, b, N + 1) # nodes
  3234. y = np.exp(x)
  3235. with assert_raises(ValueError):
  3236. make_splrep(x, y, s=1e-8, bc_type=self.bc_type)
  3237. @pytest.mark.parametrize("s", [0, 1e-50])
  3238. def test_make_splrep_periodic_m_eq_2_k_eq_1(self, s):
  3239. # Two data points (m = 2)
  3240. x = np.array([0.0, 1.0])
  3241. y = np.array([5.0, 5.0]) # constant function
  3242. w = np.array([1.0, 1.0]) if s > 0 else None
  3243. # Degree 1 periodic spline
  3244. spl = make_splrep(x, y, w=w, k=1, bc_type="periodic", s=s)
  3245. tck = splrep(x, y, w=w, k=1, per=1, s=s)
  3246. if s > 0:
  3247. xp_assert_close(spl.t, tck[0])
  3248. xp_assert_close(np.r_[spl.c, [0]*(spl.k+1)],
  3249. tck[1])
  3250. @pytest.mark.parametrize("k_fp", [(1, -0.0001), (2, -0.0001), (3, -8.62e-05)])
  3251. @pytest.mark.parametrize("s", [1e-4])
  3252. def test_fperiodic_basic_fit(self, k_fp, s):
  3253. n = 10
  3254. x = np.linspace(0, 1, n)
  3255. y = np.sin(2 * np.pi * x)
  3256. k, fp = k_fp
  3257. tck = splrep(x, y, k=k, s=s, per=1)
  3258. fp0 = 4.5
  3259. spline = Fperiodic(x, y[:, None], tck[0], k=k, s=s)
  3260. with warnings.catch_warnings():
  3261. warnings.simplefilter("ignore", RuntimeWarning)
  3262. _ = root_rati(spline, 2.0, ((0, fp0 - s), (np.inf, fp - s)), s * 0.001)
  3263. # Check the returned spline is periodic at endpoints
  3264. bs = spline.spl
  3265. x_check = np.array([0.0, 1.0])
  3266. y_check = bs(x_check)
  3267. xp_assert_close(y_check[0], y_check[1])
  3268. @make_xp_test_case(make_splprep)
  3269. class TestMakeSplprep:
  3270. def _get_xyk(self, m=10, k=3, xp=np):
  3271. x = xp.arange(m, dtype=xp.float64) * xp.pi / m
  3272. y = [xp.sin(x), xp.cos(x)]
  3273. return x, y, k
  3274. @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5])
  3275. def test_simple_vs_splprep(self, s):
  3276. # Check/document the interface vs splPrep
  3277. # The four values of `s` are to probe all code paths and shortcuts
  3278. m, k = 10, 3
  3279. x = np.arange(m) * np.pi / m
  3280. y = [np.sin(x), np.cos(x)]
  3281. # the number of knots depends on `s` (this is by construction)
  3282. num_knots = {0: 14, 0.1: 8, 1e-3: 8 + 1, 1e-5: 8 + 2}
  3283. # construct the splines
  3284. (t, c, k), u_ = splprep(y, s=s)
  3285. spl, u = make_splprep(y, s=s)
  3286. # parameters
  3287. xp_assert_close(u, u_, atol=1e-15)
  3288. # knots
  3289. xp_assert_close(spl.t, t, atol=1e-15)
  3290. assert len(t) == num_knots[s]
  3291. # coefficients: note the transpose
  3292. cc = np.asarray(c).T
  3293. xp_assert_close(spl.c, cc, atol=1e-15)
  3294. # values: note axis=1
  3295. xp_assert_close(spl(u),
  3296. BSpline(t, c, k, axis=1)(u), atol=1e-15)
  3297. @pytest.mark.parametrize('s', [0, 0.1, 1e-3, 1e-5])
  3298. def test_array_not_list(self, s):
  3299. # the argument of splPrep is either a list of arrays or a 2D array (sigh)
  3300. _, y, _ = self._get_xyk()
  3301. assert isinstance(y, list)
  3302. assert np.shape(y)[0] == 2
  3303. # assert the behavior of FITPACK's splrep
  3304. tck, u = splprep(y, s=s)
  3305. tck_a, u_a = splprep(np.asarray(y), s=s)
  3306. xp_assert_close(u, u_a, atol=s)
  3307. xp_assert_close(tck[0], tck_a[0], atol=1e-15)
  3308. assert len(tck[1]) == len(tck_a[1])
  3309. xp_assert_close(tck[1], tck_a[1], atol=1e-15)
  3310. assert tck[2] == tck_a[2]
  3311. assert np.shape(splev(u, tck)) == np.shape(y)
  3312. spl, u = make_splprep(y, s=s)
  3313. xp_assert_close(u, u_a, atol=1e-15)
  3314. xp_assert_close(spl.t, tck_a[0], atol=1e-15)
  3315. xp_assert_close(spl.c.T, tck_a[1], atol=1e-15)
  3316. assert spl.k == tck_a[2]
  3317. assert spl(u).shape == np.shape(y)
  3318. spl, u = make_splprep(np.asarray(y), s=s)
  3319. xp_assert_close(u, u_a, atol=1e-15)
  3320. xp_assert_close(spl.t, tck_a[0], atol=1e-15)
  3321. xp_assert_close(spl.c.T, tck_a[1], atol=1e-15)
  3322. assert spl.k == tck_a[2]
  3323. assert spl(u).shape == np.shape(y)
  3324. with assert_raises(ValueError):
  3325. make_splprep(np.asarray(y).T, s=s)
  3326. def test_default_s_is_zero(self, xp):
  3327. x, y, k = self._get_xyk(m=10, xp=xp)
  3328. spl, u = make_splprep(y)
  3329. xp_assert_close(spl(u), xp.stack(y), atol=1e-15)
  3330. def test_s_zero_vs_near_zero(self, xp):
  3331. # s=0 and s \approx 0 are consistent
  3332. x, y, k = self._get_xyk(m=10, xp=xp)
  3333. spl_i, u_i = make_splprep(y, s=0)
  3334. spl_n, u_n = make_splprep(y, s=1e-15)
  3335. xp_assert_close(u_i, u_n, atol=1e-15)
  3336. xp_assert_close(spl_i(u_i), xp.stack(y), atol=1e-15)
  3337. xp_assert_close(spl_n(u_n), xp.stack(y), atol=1e-7)
  3338. assert spl_i.axis == spl_n.axis
  3339. assert spl_i.c.shape == spl_n.c.shape
  3340. def test_1D(self):
  3341. x = np.arange(8, dtype=float)
  3342. with assert_raises(ValueError):
  3343. splprep(x)
  3344. with assert_raises(ValueError):
  3345. make_splprep(x, s=0)
  3346. with assert_raises(ValueError):
  3347. make_splprep(x, s=0.1)
  3348. tck, u_ = splprep([x], s=1e-5)
  3349. spl, u = make_splprep([x], s=1e-5)
  3350. assert spl(u).shape == (1, 8)
  3351. xp_assert_close(spl(u), [x], atol=1e-15)
  3352. @make_xp_test_case(make_splprep)
  3353. class TestMakeSplprepPeriodic:
  3354. def _get_xyk(self, n=10, k=3, xp=np):
  3355. x = xp.linspace(0, 2*xp.pi, n, dtype=xp.float64)
  3356. y = [xp.sin(x), xp.cos(x)]
  3357. return x, y, k
  3358. @pytest.mark.parametrize('s', [0, 1e-4, 1e-5, 1e-6])
  3359. def test_simple_vs_splprep(self, s):
  3360. # Check/document the interface vs splPrep
  3361. # The four values of `s` are to probe all code paths and shortcuts
  3362. n = 10
  3363. x = np.linspace(0, 2*np.pi, n)
  3364. y = [np.sin(x), np.cos(x)]
  3365. # the number of knots depends on `s` (this is by construction)
  3366. num_knots = {0: 14, 1e-4: 16, 1e-5: 16, 1e-6: 16}
  3367. # construct the splines
  3368. (t, c, k), u_ = splprep(y, s=s, per=1)
  3369. spl, u = make_splprep(y, s=s, bc_type="periodic")
  3370. # parameters
  3371. xp_assert_close(u, u_, atol=1e-15)
  3372. # knots
  3373. assert len(spl.t) == num_knots[s]
  3374. # values: note axis=1
  3375. xp_assert_close(spl(u), BSpline(t, c, k, axis=1)(u),
  3376. atol=1e-06, rtol=1e-06)
  3377. @pytest.mark.parametrize('s', [0, 1e-4, 1e-5, 1e-6])
  3378. def test_array_not_list(self, s):
  3379. # the argument of splPrep is either a list of arrays or a 2D array (sigh)
  3380. _, y, _ = self._get_xyk()
  3381. assert isinstance(y, list)
  3382. assert np.shape(y)[0] == 2
  3383. # assert the behavior of FITPACK's splrep
  3384. tck, u = splprep(y, s=s, per=1)
  3385. tck_a, u_a = splprep(np.asarray(y), s=s, per=1)
  3386. xp_assert_close(u, u_a, atol=s)
  3387. xp_assert_close(tck[0], tck_a[0], atol=1e-15)
  3388. assert len(tck[1]) == len(tck_a[1])
  3389. for c1, c2 in zip(tck[1], tck_a[1]):
  3390. xp_assert_close(c1, c2, atol=1e-15)
  3391. assert tck[2] == tck_a[2]
  3392. assert np.shape(splev(u, tck)) == np.shape(y)
  3393. spl, u = make_splprep(y, s=s, bc_type="periodic")
  3394. xp_assert_close(u, u_a, atol=1e-15)
  3395. assert spl.k == tck_a[2]
  3396. assert spl(u).shape == np.shape(y)
  3397. spl, u = make_splprep(np.asarray(y), s=s, bc_type="periodic")
  3398. xp_assert_close(u, u_a, atol=1e-15)
  3399. assert spl.k == tck_a[2]
  3400. assert spl(u).shape == np.shape(y)
  3401. with assert_raises(ValueError):
  3402. make_splprep(np.asarray(y).T, s=s, bc_type="periodic")
  3403. def test_default_s_is_zero(self, xp):
  3404. x, y, k = self._get_xyk(n=10, xp=xp)
  3405. spl, u = make_splprep(y, bc_type="periodic")
  3406. xp_assert_close(spl(u), xp.stack(y), atol=1e-15)
  3407. def test_s_zero_vs_near_zero(self, xp):
  3408. # s=0 and s \approx 0 are consistent
  3409. x, y, k = self._get_xyk(n=10, xp=xp)
  3410. spl_i, u_i = make_splprep(y, s=0, bc_type="periodic")
  3411. spl_n, u_n = make_splprep(y, s=1e-12, bc_type="periodic")
  3412. xp_assert_close(u_i, u_n, atol=1e-15)
  3413. y_arr = xp.stack(y) # xp_assert_close chokes on the list `y`
  3414. xp_assert_close(spl_i(u_i), y_arr, atol=1e-15)
  3415. xp_assert_close(spl_n(u_n), y_arr, atol=1e-7, rtol=1e-6)
  3416. assert spl_i.axis == spl_n.axis
  3417. def test_1D(self):
  3418. x = np.linspace(0, 2*np.pi, 8)
  3419. x = np.sin(x)
  3420. with assert_raises(ValueError):
  3421. splprep(x, per=1)
  3422. with assert_raises(ValueError):
  3423. make_splprep(x, s=0, bc_type="periodic")
  3424. with assert_raises(ValueError):
  3425. make_splprep(x, s=0.1, bc_type="periodic")
  3426. spl, u = make_splprep([x], s=1e-15, bc_type="periodic")
  3427. assert spl(u).shape == (1, 8)
  3428. xp_assert_close(spl(u), [x], atol=1e-15)
  3429. class BatchSpline:
  3430. # BSpline-line class with reference batch behavior
  3431. def __init__(self, x, y, axis, *, spline, **kwargs):
  3432. y = np.moveaxis(y, axis, -1)
  3433. self._batch_shape = y.shape[:-1]
  3434. self._splines = [spline(x, yi, **kwargs) for yi in y.reshape(-1, y.shape[-1])]
  3435. self._axis = axis
  3436. def __call__(self, x):
  3437. y = [spline(x) for spline in self._splines]
  3438. y = np.reshape(y, self._batch_shape + x.shape)
  3439. return np.moveaxis(y, -1, self._axis) if x.shape else y
  3440. def integrate(self, a, b, extrapolate=None):
  3441. y = [spline.integrate(a, b, extrapolate) for spline in self._splines]
  3442. return np.reshape(y, self._batch_shape)
  3443. def derivative(self, nu):
  3444. res = copy.deepcopy(self)
  3445. res._splines = [spline.derivative(nu) for spline in res._splines]
  3446. return res
  3447. def antiderivative(self, nu):
  3448. res = copy.deepcopy(self)
  3449. res._splines = [spline.antiderivative(nu) for spline in res._splines]
  3450. return res
  3451. class TestBatch:
  3452. @pytest.mark.parametrize('make_spline, kwargs',
  3453. [(make_interp_spline, {}),
  3454. (make_smoothing_spline, {}),
  3455. (make_smoothing_spline, {'lam': 1.0}),
  3456. (make_lsq_spline, {'method': "norm-eq"}),
  3457. (make_lsq_spline, {'method': "qr"}),
  3458. ])
  3459. @pytest.mark.parametrize('eval_shape', [(), (1,), (3,)])
  3460. @pytest.mark.parametrize('axis', [-1, 0, 1])
  3461. def test_batch(self, make_spline, kwargs, axis, eval_shape):
  3462. rng = np.random.default_rng(4329872134985134)
  3463. n = 10
  3464. shape = (2, 3, 4, n)
  3465. domain = (0, 10)
  3466. x = np.linspace(*domain, n)
  3467. y = np.moveaxis(rng.random(shape), -1, axis)
  3468. if make_spline == make_lsq_spline:
  3469. k = 3 # spline degree, if needed
  3470. t = (x[0],) * (k + 1) + (x[-1],) * (k + 1) # valid knots, if needed
  3471. kwargs = kwargs | dict(t=t, k=k)
  3472. res = make_spline(x, y, axis=axis, **kwargs)
  3473. ref = BatchSpline(x, y, axis=axis, spline=make_spline, **kwargs)
  3474. x = rng.uniform(*domain, size=eval_shape)
  3475. np.testing.assert_allclose(res(x), ref(x))
  3476. res, ref = res.antiderivative(1), ref.antiderivative(1)
  3477. np.testing.assert_allclose(res(x), ref(x))
  3478. res, ref = res.derivative(2), ref.derivative(2)
  3479. np.testing.assert_allclose(res(x), ref(x))
  3480. np.testing.assert_allclose(res.integrate(*domain), ref.integrate(*domain))