_fitpack2.py 88 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408
  1. """
  2. fitpack --- curve and surface fitting with splines
  3. fitpack is based on a collection of Fortran routines DIERCKX
  4. by P. Dierckx (see http://www.netlib.org/dierckx/) transformed
  5. to double routines by Pearu Peterson.
  6. """
  7. # Created by Pearu Peterson, June,August 2003
  8. __all__ = [
  9. 'UnivariateSpline',
  10. 'InterpolatedUnivariateSpline',
  11. 'LSQUnivariateSpline',
  12. 'BivariateSpline',
  13. 'LSQBivariateSpline',
  14. 'SmoothBivariateSpline',
  15. 'LSQSphereBivariateSpline',
  16. 'SmoothSphereBivariateSpline',
  17. 'RectBivariateSpline',
  18. 'RectSphereBivariateSpline']
  19. import warnings
  20. from threading import Lock
  21. from numpy import zeros, concatenate, ravel, diff, array
  22. import numpy as np
  23. from . import _fitpack_impl
  24. from . import _dfitpack as dfitpack
  25. from scipy._lib._array_api import xp_capabilities
  26. dfitpack_int = dfitpack.types.intvar.dtype
  27. FITPACK_LOCK = Lock()
  28. # ############### Univariate spline ####################
  29. _curfit_messages = {1: """
  30. The required storage space exceeds the available storage space, as
  31. specified by the parameter nest: nest too small. If nest is already
  32. large (say nest > m/2), it may also indicate that s is too small.
  33. The approximation returned is the weighted least-squares spline
  34. according to the knots t[0],t[1],...,t[n-1]. (n=nest) the parameter fp
  35. gives the corresponding weighted sum of squared residuals (fp>s).
  36. """,
  37. 2: """
  38. A theoretically impossible result was found during the iteration
  39. process for finding a smoothing spline with fp = s: s too small.
  40. There is an approximation returned but the corresponding weighted sum
  41. of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
  42. 3: """
  43. The maximal number of iterations maxit (set to 20 by the program)
  44. allowed for finding a smoothing spline with fp=s has been reached: s
  45. too small.
  46. There is an approximation returned but the corresponding weighted sum
  47. of squared residuals does not satisfy the condition abs(fp-s)/s < tol.""",
  48. 10: """
  49. Error on entry, no approximation returned. The following conditions
  50. must hold:
  51. xb<=x[0]<x[1]<...<x[m-1]<=xe, w[i]>0, i=0..m-1
  52. if iopt=-1:
  53. xb<t[k+1]<t[k+2]<...<t[n-k-2]<xe"""
  54. }
  55. # UnivariateSpline, ext parameter can be an int or a string
  56. _extrap_modes = {0: 0, 'extrapolate': 0,
  57. 1: 1, 'zeros': 1,
  58. 2: 2, 'raise': 2,
  59. 3: 3, 'const': 3}
  60. @xp_capabilities(out_of_scope=True)
  61. class UnivariateSpline:
  62. """
  63. 1-D smoothing spline fit to a given set of data points.
  64. .. legacy:: class
  65. Specifically, we recommend using `make_splrep` instead.
  66. Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. `s`
  67. specifies the number of knots by specifying a smoothing condition.
  68. Parameters
  69. ----------
  70. x : (N,) array_like
  71. 1-D array of independent input data. Must be increasing;
  72. must be strictly increasing if `s` is 0.
  73. y : (N,) array_like
  74. 1-D array of dependent input data, of the same length as `x`.
  75. w : (N,) array_like, optional
  76. Weights for spline fitting. Must be positive. If `w` is None,
  77. weights are all 1. Default is None.
  78. bbox : (2,) array_like, optional
  79. 2-sequence specifying the boundary of the approximation interval. If
  80. `bbox` is None, ``bbox=[x[0], x[-1]]``. Default is None.
  81. k : int, optional
  82. Degree of the smoothing spline. Must be 1 <= `k` <= 5.
  83. ``k = 3`` is a cubic spline. Default is 3.
  84. s : float or None, optional
  85. Positive smoothing factor used to choose the number of knots. Number
  86. of knots will be increased until the smoothing condition is satisfied::
  87. sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) <= s
  88. However, because of numerical issues, the actual condition is::
  89. abs(sum((w[i] * (y[i]-spl(x[i])))**2, axis=0) - s) < 0.001 * s
  90. If `s` is None, `s` will be set as `len(w)` for a smoothing spline
  91. that uses all data points.
  92. If 0, spline will interpolate through all data points. This is
  93. equivalent to `InterpolatedUnivariateSpline`.
  94. Default is None.
  95. The user can use the `s` to control the tradeoff between closeness
  96. and smoothness of fit. Larger `s` means more smoothing while smaller
  97. values of `s` indicate less smoothing.
  98. Recommended values of `s` depend on the weights, `w`. If the weights
  99. represent the inverse of the standard-deviation of `y`, then a good
  100. `s` value should be found in the range (m-sqrt(2*m),m+sqrt(2*m))
  101. where m is the number of datapoints in `x`, `y`, and `w`. This means
  102. ``s = len(w)`` should be a good value if ``1/w[i]`` is an
  103. estimate of the standard deviation of ``y[i]``.
  104. ext : int or str, optional
  105. Controls the extrapolation mode for elements
  106. not in the interval defined by the knot sequence.
  107. * if ext=0 or 'extrapolate', return the extrapolated value.
  108. * if ext=1 or 'zeros', return 0
  109. * if ext=2 or 'raise', raise a ValueError
  110. * if ext=3 or 'const', return the boundary value.
  111. Default is 0.
  112. check_finite : bool, optional
  113. Whether to check that the input arrays contain only finite numbers.
  114. Disabling may give a performance gain, but may result in problems
  115. (crashes, non-termination or non-sensical results) if the inputs
  116. do contain infinities or NaNs.
  117. Default is False.
  118. See Also
  119. --------
  120. BivariateSpline :
  121. a base class for bivariate splines.
  122. SmoothBivariateSpline :
  123. a smoothing bivariate spline through the given points
  124. LSQBivariateSpline :
  125. a bivariate spline using weighted least-squares fitting
  126. RectSphereBivariateSpline :
  127. a bivariate spline over a rectangular mesh on a sphere
  128. SmoothSphereBivariateSpline :
  129. a smoothing bivariate spline in spherical coordinates
  130. LSQSphereBivariateSpline :
  131. a bivariate spline in spherical coordinates using weighted
  132. least-squares fitting
  133. RectBivariateSpline :
  134. a bivariate spline over a rectangular mesh
  135. InterpolatedUnivariateSpline :
  136. a interpolating univariate spline for a given set of data points.
  137. bisplrep :
  138. a function to find a bivariate B-spline representation of a surface
  139. bisplev :
  140. a function to evaluate a bivariate B-spline and its derivatives
  141. splrep :
  142. a function to find the B-spline representation of a 1-D curve
  143. splev :
  144. a function to evaluate a B-spline or its derivatives
  145. sproot :
  146. a function to find the roots of a cubic B-spline
  147. splint :
  148. a function to evaluate the definite integral of a B-spline between two
  149. given points
  150. spalde :
  151. a function to evaluate all derivatives of a B-spline
  152. Notes
  153. -----
  154. The number of data points must be larger than the spline degree `k`.
  155. **NaN handling**: If the input arrays contain ``nan`` values, the result
  156. is not useful, since the underlying spline fitting routines cannot deal
  157. with ``nan``. A workaround is to use zero weights for not-a-number
  158. data points:
  159. >>> import numpy as np
  160. >>> from scipy.interpolate import UnivariateSpline
  161. >>> x, y = np.array([1, 2, 3, 4]), np.array([1, np.nan, 3, 4])
  162. >>> w = np.isnan(y)
  163. >>> y[w] = 0.
  164. >>> spl = UnivariateSpline(x, y, w=~w)
  165. Notice the need to replace a ``nan`` by a numerical value (precise value
  166. does not matter as long as the corresponding weight is zero.)
  167. References
  168. ----------
  169. Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
  170. .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
  171. integration of experimental data using spline functions",
  172. J.Comp.Appl.Maths 1 (1975) 165-184.
  173. .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
  174. grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
  175. 1286-1304.
  176. .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
  177. functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
  178. .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
  179. Numerical Analysis, Oxford University Press, 1993.
  180. Examples
  181. --------
  182. >>> import numpy as np
  183. >>> import matplotlib.pyplot as plt
  184. >>> from scipy.interpolate import UnivariateSpline
  185. >>> rng = np.random.default_rng()
  186. >>> x = np.linspace(-3, 3, 50)
  187. >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
  188. >>> plt.plot(x, y, 'ro', ms=5)
  189. Use the default value for the smoothing parameter:
  190. >>> spl = UnivariateSpline(x, y)
  191. >>> xs = np.linspace(-3, 3, 1000)
  192. >>> plt.plot(xs, spl(xs), 'g', lw=3)
  193. Manually change the amount of smoothing:
  194. >>> spl.set_smoothing_factor(0.5)
  195. >>> plt.plot(xs, spl(xs), 'b', lw=3)
  196. >>> plt.show()
  197. """
  198. def __init__(self, x, y, w=None, bbox=[None]*2, k=3, s=None,
  199. ext=0, check_finite=False):
  200. x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, s, ext,
  201. check_finite)
  202. # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
  203. with FITPACK_LOCK:
  204. data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
  205. xe=bbox[1], s=s)
  206. if data[-1] == 1:
  207. # nest too small, setting to maximum bound
  208. data = self._reset_nest(data)
  209. self._data = data
  210. self._reset_class()
  211. @staticmethod
  212. def validate_input(x, y, w, bbox, k, s, ext, check_finite):
  213. x, y, bbox = np.asarray(x), np.asarray(y), np.asarray(bbox)
  214. if w is not None:
  215. w = np.asarray(w)
  216. if check_finite:
  217. w_finite = np.isfinite(w).all() if w is not None else True
  218. if (not np.isfinite(x).all() or not np.isfinite(y).all() or
  219. not w_finite):
  220. raise ValueError("x and y array must not contain "
  221. "NaNs or infs.")
  222. if s is None or s > 0:
  223. if not np.all(diff(x) >= 0.0):
  224. raise ValueError("x must be increasing if s > 0")
  225. else:
  226. if not np.all(diff(x) > 0.0):
  227. raise ValueError("x must be strictly increasing if s = 0")
  228. if x.size != y.size:
  229. raise ValueError("x and y should have a same length")
  230. elif w is not None and not x.size == y.size == w.size:
  231. raise ValueError("x, y, and w should have a same length")
  232. elif bbox.shape != (2,):
  233. raise ValueError("bbox shape should be (2,)")
  234. elif not (1 <= k <= 5):
  235. raise ValueError("k should be 1 <= k <= 5")
  236. elif s is not None and not s >= 0.0:
  237. raise ValueError("s should be s >= 0.0")
  238. try:
  239. ext = _extrap_modes[ext]
  240. except KeyError as e:
  241. raise ValueError(f"Unknown extrapolation mode {ext}.") from e
  242. return x, y, w, bbox, ext
  243. @classmethod
  244. def _from_tck(cls, tck, ext=0):
  245. """Construct a spline object from given tck"""
  246. self = cls.__new__(cls)
  247. t, c, k = tck
  248. self._eval_args = tck
  249. # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
  250. self._data = (None, None, None, None, None, k, None, len(t), t,
  251. c, None, None, None, None)
  252. self.ext = ext
  253. return self
  254. def _reset_class(self):
  255. data = self._data
  256. n, t, c, k, ier = data[7], data[8], data[9], data[5], data[-1]
  257. self._eval_args = t[:n], c[:n], k
  258. if ier == 0:
  259. # the spline returned has a residual sum of squares fp
  260. # such that abs(fp-s)/s <= tol with tol a relative
  261. # tolerance set to 0.001 by the program
  262. pass
  263. elif ier == -1:
  264. # the spline returned is an interpolating spline
  265. self._set_class(InterpolatedUnivariateSpline)
  266. elif ier == -2:
  267. # the spline returned is the weighted least-squares
  268. # polynomial of degree k. In this extreme case fp gives
  269. # the upper bound fp0 for the smoothing factor s.
  270. self._set_class(LSQUnivariateSpline)
  271. else:
  272. # error
  273. if ier == 1:
  274. self._set_class(LSQUnivariateSpline)
  275. message = _curfit_messages.get(ier, f'ier={ier}')
  276. warnings.warn(message, stacklevel=3)
  277. def _set_class(self, cls):
  278. self._spline_class = cls
  279. if self.__class__ in (UnivariateSpline, InterpolatedUnivariateSpline,
  280. LSQUnivariateSpline):
  281. self.__class__ = cls
  282. else:
  283. # It's an unknown subclass -- don't change class. cf. #731
  284. pass
  285. def _reset_nest(self, data, nest=None):
  286. n = data[10]
  287. if nest is None:
  288. k, m = data[5], len(data[0])
  289. nest = m+k+1 # this is the maximum bound for nest
  290. else:
  291. if not n <= nest:
  292. raise ValueError("`nest` can only be increased")
  293. t, c, fpint, nrdata = (np.resize(data[j], nest) for j in
  294. [8, 9, 11, 12])
  295. args = data[:8] + (t, c, n, fpint, nrdata, data[13])
  296. with FITPACK_LOCK:
  297. data = dfitpack.fpcurf1(*args)
  298. return data
  299. def set_smoothing_factor(self, s):
  300. """ Continue spline computation with the given smoothing
  301. factor s and with the knots found at the last call.
  302. This routine modifies the spline in place.
  303. """
  304. data = self._data
  305. if data[6] == -1:
  306. warnings.warn('smoothing factor unchanged for'
  307. 'LSQ spline with fixed knots',
  308. stacklevel=2)
  309. return
  310. args = data[:6] + (s,) + data[7:]
  311. with FITPACK_LOCK:
  312. data = dfitpack.fpcurf1(*args)
  313. if data[-1] == 1:
  314. # nest too small, setting to maximum bound
  315. data = self._reset_nest(data)
  316. self._data = data
  317. self._reset_class()
  318. def __call__(self, x, nu=0, ext=None):
  319. """
  320. Evaluate spline (or its nu-th derivative) at positions x.
  321. Parameters
  322. ----------
  323. x : array_like
  324. A 1-D array of points at which to return the value of the smoothed
  325. spline or its derivatives. Note: `x` can be unordered but the
  326. evaluation is more efficient if `x` is (partially) ordered.
  327. nu : int
  328. The order of derivative of the spline to compute.
  329. ext : int
  330. Controls the value returned for elements of `x` not in the
  331. interval defined by the knot sequence.
  332. * if ext=0 or 'extrapolate', return the extrapolated value.
  333. * if ext=1 or 'zeros', return 0
  334. * if ext=2 or 'raise', raise a ValueError
  335. * if ext=3 or 'const', return the boundary value.
  336. The default value is 0, passed from the initialization of
  337. UnivariateSpline.
  338. """
  339. x = np.asarray(x)
  340. # empty input yields empty output
  341. if x.size == 0:
  342. return array([])
  343. if ext is None:
  344. ext = self.ext
  345. else:
  346. try:
  347. ext = _extrap_modes[ext]
  348. except KeyError as e:
  349. raise ValueError(f"Unknown extrapolation mode {ext}.") from e
  350. with FITPACK_LOCK:
  351. return _fitpack_impl.splev(x, self._eval_args, der=nu, ext=ext)
  352. def get_knots(self):
  353. """ Return positions of interior knots of the spline.
  354. Internally, the knot vector contains ``2*k`` additional boundary knots.
  355. """
  356. data = self._data
  357. k, n = data[5], data[7]
  358. return data[8][k:n-k]
  359. def get_coeffs(self):
  360. """Return spline coefficients."""
  361. data = self._data
  362. k, n = data[5], data[7]
  363. return data[9][:n-k-1]
  364. def get_residual(self):
  365. """Return weighted sum of squared residuals of the spline approximation.
  366. This is equivalent to::
  367. sum((w[i] * (y[i]-spl(x[i])))**2, axis=0)
  368. """
  369. return self._data[10]
  370. def integral(self, a, b):
  371. """ Return definite integral of the spline between two given points.
  372. Parameters
  373. ----------
  374. a : float
  375. Lower limit of integration.
  376. b : float
  377. Upper limit of integration.
  378. Returns
  379. -------
  380. integral : float
  381. The value of the definite integral of the spline between limits.
  382. Examples
  383. --------
  384. >>> import numpy as np
  385. >>> from scipy.interpolate import UnivariateSpline
  386. >>> x = np.linspace(0, 3, 11)
  387. >>> y = x**2
  388. >>> spl = UnivariateSpline(x, y)
  389. >>> spl.integral(0, 3)
  390. 9.0
  391. which agrees with :math:`\\int x^2 dx = x^3 / 3` between the limits
  392. of 0 and 3.
  393. A caveat is that this routine assumes the spline to be zero outside of
  394. the data limits:
  395. >>> spl.integral(-1, 4)
  396. 9.0
  397. >>> spl.integral(-1, 0)
  398. 0.0
  399. """
  400. with FITPACK_LOCK:
  401. return _fitpack_impl.splint(a, b, self._eval_args)
  402. def derivatives(self, x):
  403. """ Return all derivatives of the spline at the point x.
  404. Parameters
  405. ----------
  406. x : float
  407. The point to evaluate the derivatives at.
  408. Returns
  409. -------
  410. der : ndarray, shape(k+1,)
  411. Derivatives of the orders 0 to k.
  412. Examples
  413. --------
  414. >>> import numpy as np
  415. >>> from scipy.interpolate import UnivariateSpline
  416. >>> x = np.linspace(0, 3, 11)
  417. >>> y = x**2
  418. >>> spl = UnivariateSpline(x, y)
  419. >>> spl.derivatives(1.5)
  420. array([2.25, 3.0, 2.0, 0])
  421. """
  422. with FITPACK_LOCK:
  423. return _fitpack_impl.spalde(x, self._eval_args)
  424. def roots(self):
  425. """ Return the zeros of the spline.
  426. Notes
  427. -----
  428. Restriction: only cubic splines are supported by FITPACK. For non-cubic
  429. splines, use `PPoly.root` (see below for an example).
  430. Examples
  431. --------
  432. For some data, this method may miss a root. This happens when one of
  433. the spline knots (which FITPACK places automatically) happens to
  434. coincide with the true root. A workaround is to convert to `PPoly`,
  435. which uses a different root-finding algorithm.
  436. For example,
  437. >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
  438. >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
  439. ... 4.440892e-16, 1.616930e-03, 3.243000e-03, 4.877670e-03,
  440. ... 6.520430e-03, 8.170770e-03]
  441. >>> from scipy.interpolate import UnivariateSpline
  442. >>> spl = UnivariateSpline(x, y, s=0)
  443. >>> spl.roots()
  444. array([], dtype=float64)
  445. Converting to a PPoly object does find the roots at `x=2`:
  446. >>> from scipy.interpolate import splrep, PPoly
  447. >>> tck = splrep(x, y, s=0)
  448. >>> ppoly = PPoly.from_spline(tck)
  449. >>> ppoly.roots(extrapolate=False)
  450. array([2.])
  451. See Also
  452. --------
  453. sproot
  454. PPoly.roots
  455. """
  456. k = self._data[5]
  457. if k == 3:
  458. t = self._eval_args[0]
  459. mest = 3 * (len(t) - 7)
  460. with FITPACK_LOCK:
  461. return _fitpack_impl.sproot(self._eval_args, mest=mest)
  462. raise NotImplementedError('finding roots unsupported for '
  463. 'non-cubic splines')
  464. def derivative(self, n=1):
  465. """
  466. Construct a new spline representing the derivative of this spline.
  467. Parameters
  468. ----------
  469. n : int, optional
  470. Order of derivative to evaluate. Default: 1
  471. Returns
  472. -------
  473. spline : UnivariateSpline
  474. Spline of order k2=k-n representing the derivative of this
  475. spline.
  476. See Also
  477. --------
  478. splder, antiderivative
  479. Notes
  480. -----
  481. .. versionadded:: 0.13.0
  482. Examples
  483. --------
  484. This can be used for finding maxima of a curve:
  485. >>> import numpy as np
  486. >>> from scipy.interpolate import UnivariateSpline
  487. >>> x = np.linspace(0, 10, 70)
  488. >>> y = np.sin(x)
  489. >>> spl = UnivariateSpline(x, y, k=4, s=0)
  490. Now, differentiate the spline and find the zeros of the
  491. derivative. (NB: `sproot` only works for order 3 splines, so we
  492. fit an order 4 spline):
  493. >>> spl.derivative().roots() / np.pi
  494. array([ 0.50000001, 1.5 , 2.49999998])
  495. This agrees well with roots :math:`\\pi/2 + n\\pi` of
  496. :math:`\\cos(x) = \\sin'(x)`.
  497. """
  498. with FITPACK_LOCK:
  499. tck = _fitpack_impl.splder(self._eval_args, n)
  500. # if self.ext is 'const', derivative.ext will be 'zeros'
  501. ext = 1 if self.ext == 3 else self.ext
  502. return UnivariateSpline._from_tck(tck, ext=ext)
  503. def antiderivative(self, n=1):
  504. """
  505. Construct a new spline representing the antiderivative of this spline.
  506. Parameters
  507. ----------
  508. n : int, optional
  509. Order of antiderivative to evaluate. Default: 1
  510. Returns
  511. -------
  512. spline : UnivariateSpline
  513. Spline of order k2=k+n representing the antiderivative of this
  514. spline.
  515. Notes
  516. -----
  517. .. versionadded:: 0.13.0
  518. See Also
  519. --------
  520. splantider, derivative
  521. Examples
  522. --------
  523. >>> import numpy as np
  524. >>> from scipy.interpolate import UnivariateSpline
  525. >>> x = np.linspace(0, np.pi/2, 70)
  526. >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
  527. >>> spl = UnivariateSpline(x, y, s=0)
  528. The derivative is the inverse operation of the antiderivative,
  529. although some floating point error accumulates:
  530. >>> spl(1.7), spl.antiderivative().derivative()(1.7)
  531. (array(2.1565429877197317), array(2.1565429877201865))
  532. Antiderivative can be used to evaluate definite integrals:
  533. >>> ispl = spl.antiderivative()
  534. >>> ispl(np.pi/2) - ispl(0)
  535. 2.2572053588768486
  536. This is indeed an approximation to the complete elliptic integral
  537. :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
  538. >>> from scipy.special import ellipk
  539. >>> ellipk(0.8)
  540. 2.2572053268208538
  541. """
  542. with FITPACK_LOCK:
  543. tck = _fitpack_impl.splantider(self._eval_args, n)
  544. return UnivariateSpline._from_tck(tck, self.ext)
  545. @xp_capabilities(out_of_scope=True)
  546. class InterpolatedUnivariateSpline(UnivariateSpline):
  547. """
  548. 1-D interpolating spline for a given set of data points.
  549. .. legacy:: class
  550. Specifically, we recommend using `make_interp_spline` instead.
  551. Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data.
  552. Spline function passes through all provided points. Equivalent to
  553. `UnivariateSpline` with `s` = 0.
  554. Parameters
  555. ----------
  556. x : (N,) array_like
  557. Input dimension of data points -- must be strictly increasing
  558. y : (N,) array_like
  559. input dimension of data points
  560. w : (N,) array_like, optional
  561. Weights for spline fitting. Must be positive. If None (default),
  562. weights are all 1.
  563. bbox : (2,) array_like, optional
  564. 2-sequence specifying the boundary of the approximation interval. If
  565. None (default), ``bbox=[x[0], x[-1]]``.
  566. k : int, optional
  567. Degree of the smoothing spline. Must be ``1 <= k <= 5``. Default is
  568. ``k = 3``, a cubic spline.
  569. ext : int or str, optional
  570. Controls the extrapolation mode for elements
  571. not in the interval defined by the knot sequence.
  572. * if ext=0 or 'extrapolate', return the extrapolated value.
  573. * if ext=1 or 'zeros', return 0
  574. * if ext=2 or 'raise', raise a ValueError
  575. * if ext=3 of 'const', return the boundary value.
  576. The default value is 0.
  577. check_finite : bool, optional
  578. Whether to check that the input arrays contain only finite numbers.
  579. Disabling may give a performance gain, but may result in problems
  580. (crashes, non-termination or non-sensical results) if the inputs
  581. do contain infinities or NaNs.
  582. Default is False.
  583. See Also
  584. --------
  585. UnivariateSpline :
  586. a smooth univariate spline to fit a given set of data points.
  587. LSQUnivariateSpline :
  588. a spline for which knots are user-selected
  589. SmoothBivariateSpline :
  590. a smoothing bivariate spline through the given points
  591. LSQBivariateSpline :
  592. a bivariate spline using weighted least-squares fitting
  593. splrep :
  594. a function to find the B-spline representation of a 1-D curve
  595. splev :
  596. a function to evaluate a B-spline or its derivatives
  597. sproot :
  598. a function to find the roots of a cubic B-spline
  599. splint :
  600. a function to evaluate the definite integral of a B-spline between two
  601. given points
  602. spalde :
  603. a function to evaluate all derivatives of a B-spline
  604. Notes
  605. -----
  606. The number of data points must be larger than the spline degree `k`.
  607. Examples
  608. --------
  609. >>> import numpy as np
  610. >>> import matplotlib.pyplot as plt
  611. >>> from scipy.interpolate import InterpolatedUnivariateSpline
  612. >>> rng = np.random.default_rng()
  613. >>> x = np.linspace(-3, 3, 50)
  614. >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
  615. >>> spl = InterpolatedUnivariateSpline(x, y)
  616. >>> plt.plot(x, y, 'ro', ms=5)
  617. >>> xs = np.linspace(-3, 3, 1000)
  618. >>> plt.plot(xs, spl(xs), 'g', lw=3, alpha=0.7)
  619. >>> plt.show()
  620. Notice that the ``spl(x)`` interpolates `y`:
  621. >>> spl.get_residual()
  622. 0.0
  623. """
  624. def __init__(self, x, y, w=None, bbox=[None]*2, k=3,
  625. ext=0, check_finite=False):
  626. x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
  627. ext, check_finite)
  628. if not np.all(diff(x) > 0.0):
  629. raise ValueError('x must be strictly increasing')
  630. # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
  631. with FITPACK_LOCK:
  632. self._data = dfitpack.fpcurf0(x, y, k, w=w, xb=bbox[0],
  633. xe=bbox[1], s=0)
  634. self._reset_class()
  635. _fpchec_error_string = """The input parameters have been rejected by fpchec. \
  636. This means that at least one of the following conditions is violated:
  637. 1) k+1 <= n-k-1 <= m
  638. 2) t(1) <= t(2) <= ... <= t(k+1)
  639. t(n-k) <= t(n-k+1) <= ... <= t(n)
  640. 3) t(k+1) < t(k+2) < ... < t(n-k)
  641. 4) t(k+1) <= x(i) <= t(n-k)
  642. 5) The conditions specified by Schoenberg and Whitney must hold
  643. for at least one subset of data points, i.e., there must be a
  644. subset of data points y(j) such that
  645. t(j) < y(j) < t(j+k+1), j=1,2,...,n-k-1
  646. """
  647. @xp_capabilities(out_of_scope=True)
  648. class LSQUnivariateSpline(UnivariateSpline):
  649. """
  650. 1-D spline with explicit internal knots.
  651. .. legacy:: class
  652. Specifically, we recommend using `make_lsq_spline` instead.
  653. Fits a spline y = spl(x) of degree `k` to the provided `x`, `y` data. `t`
  654. specifies the internal knots of the spline
  655. Parameters
  656. ----------
  657. x : (N,) array_like
  658. Input dimension of data points -- must be increasing
  659. y : (N,) array_like
  660. Input dimension of data points
  661. t : (M,) array_like
  662. interior knots of the spline. Must be in ascending order and::
  663. bbox[0] < t[0] < ... < t[-1] < bbox[-1]
  664. w : (N,) array_like, optional
  665. weights for spline fitting. Must be positive. If None (default),
  666. weights are all 1.
  667. bbox : (2,) array_like, optional
  668. 2-sequence specifying the boundary of the approximation interval. If
  669. None (default), ``bbox = [x[0], x[-1]]``.
  670. k : int, optional
  671. Degree of the smoothing spline. Must be 1 <= `k` <= 5.
  672. Default is `k` = 3, a cubic spline.
  673. ext : int or str, optional
  674. Controls the extrapolation mode for elements
  675. not in the interval defined by the knot sequence.
  676. * if ext=0 or 'extrapolate', return the extrapolated value.
  677. * if ext=1 or 'zeros', return 0
  678. * if ext=2 or 'raise', raise a ValueError
  679. * if ext=3 of 'const', return the boundary value.
  680. The default value is 0.
  681. check_finite : bool, optional
  682. Whether to check that the input arrays contain only finite numbers.
  683. Disabling may give a performance gain, but may result in problems
  684. (crashes, non-termination or non-sensical results) if the inputs
  685. do contain infinities or NaNs.
  686. Default is False.
  687. Raises
  688. ------
  689. ValueError
  690. If the interior knots do not satisfy the Schoenberg-Whitney conditions
  691. See Also
  692. --------
  693. UnivariateSpline :
  694. a smooth univariate spline to fit a given set of data points.
  695. InterpolatedUnivariateSpline :
  696. a interpolating univariate spline for a given set of data points.
  697. splrep :
  698. a function to find the B-spline representation of a 1-D curve
  699. splev :
  700. a function to evaluate a B-spline or its derivatives
  701. sproot :
  702. a function to find the roots of a cubic B-spline
  703. splint :
  704. a function to evaluate the definite integral of a B-spline between two
  705. given points
  706. spalde :
  707. a function to evaluate all derivatives of a B-spline
  708. Notes
  709. -----
  710. The number of data points must be larger than the spline degree `k`.
  711. Knots `t` must satisfy the Schoenberg-Whitney conditions,
  712. i.e., there must be a subset of data points ``x[j]`` such that
  713. ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
  714. Examples
  715. --------
  716. >>> import numpy as np
  717. >>> from scipy.interpolate import LSQUnivariateSpline, UnivariateSpline
  718. >>> import matplotlib.pyplot as plt
  719. >>> rng = np.random.default_rng()
  720. >>> x = np.linspace(-3, 3, 50)
  721. >>> y = np.exp(-x**2) + 0.1 * rng.standard_normal(50)
  722. Fit a smoothing spline with a pre-defined internal knots:
  723. >>> t = [-1, 0, 1]
  724. >>> spl = LSQUnivariateSpline(x, y, t)
  725. >>> xs = np.linspace(-3, 3, 1000)
  726. >>> plt.plot(x, y, 'ro', ms=5)
  727. >>> plt.plot(xs, spl(xs), 'g-', lw=3)
  728. >>> plt.show()
  729. Check the knot vector:
  730. >>> spl.get_knots()
  731. array([-3., -1., 0., 1., 3.])
  732. Constructing lsq spline using the knots from another spline:
  733. >>> x = np.arange(10)
  734. >>> s = UnivariateSpline(x, x, s=0)
  735. >>> s.get_knots()
  736. array([ 0., 2., 3., 4., 5., 6., 7., 9.])
  737. >>> knt = s.get_knots()
  738. >>> s1 = LSQUnivariateSpline(x, x, knt[1:-1]) # Chop 1st and last knot
  739. >>> s1.get_knots()
  740. array([ 0., 2., 3., 4., 5., 6., 7., 9.])
  741. """
  742. def __init__(self, x, y, t, w=None, bbox=[None]*2, k=3,
  743. ext=0, check_finite=False):
  744. x, y, w, bbox, self.ext = self.validate_input(x, y, w, bbox, k, None,
  745. ext, check_finite)
  746. if not np.all(diff(x) >= 0.0):
  747. raise ValueError('x must be increasing')
  748. # _data == x,y,w,xb,xe,k,s,n,t,c,fp,fpint,nrdata,ier
  749. xb = bbox[0]
  750. xe = bbox[1]
  751. if xb is None:
  752. xb = x[0]
  753. if xe is None:
  754. xe = x[-1]
  755. t = concatenate(([xb]*(k+1), t, [xe]*(k+1)))
  756. n = len(t)
  757. if not np.all(t[k+1:n-k]-t[k:n-k-1] > 0, axis=0):
  758. raise ValueError('Interior knots t must satisfy '
  759. 'Schoenberg-Whitney conditions')
  760. with FITPACK_LOCK:
  761. if not dfitpack.fpchec(x, t, k) == 0:
  762. raise ValueError(_fpchec_error_string)
  763. data = dfitpack.fpcurfm1(x, y, k, t, w=w, xb=xb, xe=xe)
  764. self._data = data[:-3] + (None, None, data[-1])
  765. self._reset_class()
  766. # ############### Bivariate spline ####################
  767. class _BivariateSplineBase:
  768. """ Base class for Bivariate spline s(x,y) interpolation on the rectangle
  769. [xb,xe] x [yb, ye] calculated from a given set of data points
  770. (x,y,z).
  771. See Also
  772. --------
  773. bisplrep :
  774. a function to find a bivariate B-spline representation of a surface
  775. bisplev :
  776. a function to evaluate a bivariate B-spline and its derivatives
  777. BivariateSpline :
  778. a base class for bivariate splines.
  779. SphereBivariateSpline :
  780. a bivariate spline on a spherical grid
  781. """
  782. @classmethod
  783. def _from_tck(cls, tck):
  784. """Construct a spline object from given tck and degree"""
  785. self = cls.__new__(cls)
  786. if len(tck) != 5:
  787. raise ValueError("tck should be a 5 element tuple of tx,"
  788. " ty, c, kx, ky")
  789. self.tck = tck[:3]
  790. self.degrees = tck[3:]
  791. return self
  792. def get_residual(self):
  793. """ Return weighted sum of squared residuals of the spline
  794. approximation: sum ((w[i]*(z[i]-s(x[i],y[i])))**2,axis=0)
  795. """
  796. return self.fp
  797. def get_knots(self):
  798. """ Return a tuple (tx,ty) where tx,ty contain knots positions
  799. of the spline with respect to x-, y-variable, respectively.
  800. The position of interior and additional knots are given as
  801. t[k+1:-k-1] and t[:k+1]=b, t[-k-1:]=e, respectively.
  802. """
  803. return self.tck[:2]
  804. def get_coeffs(self):
  805. """ Return spline coefficients."""
  806. return self.tck[2]
  807. def __call__(self, x, y, dx=0, dy=0, grid=True):
  808. """
  809. Evaluate the spline or its derivatives at given positions.
  810. Parameters
  811. ----------
  812. x, y : array_like
  813. Input coordinates.
  814. If `grid` is False, evaluate the spline at points ``(x[i],
  815. y[i]), i=0, ..., len(x)-1``. Standard Numpy broadcasting
  816. is obeyed.
  817. If `grid` is True: evaluate spline at the grid points
  818. defined by the coordinate arrays x, y. The arrays must be
  819. sorted to increasing order.
  820. The ordering of axes is consistent with
  821. ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
  822. default ordering ``np.meshgrid(..., indexing="xy")``.
  823. dx : int
  824. Order of x-derivative
  825. .. versionadded:: 0.14.0
  826. dy : int
  827. Order of y-derivative
  828. .. versionadded:: 0.14.0
  829. grid : bool
  830. Whether to evaluate the results on a grid spanned by the
  831. input arrays, or at points specified by the input arrays.
  832. .. versionadded:: 0.14.0
  833. Examples
  834. --------
  835. Suppose that we want to bilinearly interpolate an exponentially decaying
  836. function in 2 dimensions.
  837. >>> import numpy as np
  838. >>> from scipy.interpolate import RectBivariateSpline
  839. We sample the function on a coarse grid. Note that the default indexing="xy"
  840. of meshgrid would result in an unexpected (transposed) result after
  841. interpolation.
  842. >>> xarr = np.linspace(-3, 3, 100)
  843. >>> yarr = np.linspace(-3, 3, 100)
  844. >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
  845. The function to interpolate decays faster along one axis than the other.
  846. >>> zdata = np.exp(-np.sqrt((xgrid / 2) ** 2 + ygrid**2))
  847. Next we sample on a finer grid using interpolation (kx=ky=1 for bilinear).
  848. >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
  849. >>> xarr_fine = np.linspace(-3, 3, 200)
  850. >>> yarr_fine = np.linspace(-3, 3, 200)
  851. >>> xgrid_fine, ygrid_fine = np.meshgrid(xarr_fine, yarr_fine, indexing="ij")
  852. >>> zdata_interp = rbs(xgrid_fine, ygrid_fine, grid=False)
  853. And check that the result agrees with the input by plotting both.
  854. >>> import matplotlib.pyplot as plt
  855. >>> fig = plt.figure()
  856. >>> ax1 = fig.add_subplot(1, 2, 1, aspect="equal")
  857. >>> ax2 = fig.add_subplot(1, 2, 2, aspect="equal")
  858. >>> ax1.imshow(zdata)
  859. >>> ax2.imshow(zdata_interp)
  860. >>> plt.show()
  861. """
  862. x = np.asarray(x)
  863. y = np.asarray(y)
  864. tx, ty, c = self.tck[:3]
  865. kx, ky = self.degrees
  866. if grid:
  867. if x.size == 0 or y.size == 0:
  868. return np.zeros((x.size, y.size), dtype=self.tck[2].dtype)
  869. if (x.size >= 2) and (not np.all(np.diff(x) >= 0.0)):
  870. raise ValueError("x must be strictly increasing when `grid` is True")
  871. if (y.size >= 2) and (not np.all(np.diff(y) >= 0.0)):
  872. raise ValueError("y must be strictly increasing when `grid` is True")
  873. if dx or dy:
  874. with FITPACK_LOCK:
  875. z, ier = dfitpack.parder(tx, ty, c, kx, ky, dx, dy, x, y)
  876. if not ier == 0:
  877. raise ValueError(f"Error code returned by parder: {ier}")
  878. else:
  879. with FITPACK_LOCK:
  880. z, ier = dfitpack.bispev(tx, ty, c, kx, ky, x, y)
  881. if not ier == 0:
  882. raise ValueError(f"Error code returned by bispev: {ier}")
  883. else:
  884. # standard Numpy broadcasting
  885. if x.shape != y.shape:
  886. x, y = np.broadcast_arrays(x, y)
  887. shape = x.shape
  888. x = x.ravel()
  889. y = y.ravel()
  890. if x.size == 0 or y.size == 0:
  891. return np.zeros(shape, dtype=self.tck[2].dtype)
  892. if dx or dy:
  893. with FITPACK_LOCK:
  894. z, ier = dfitpack.pardeu(tx, ty, c, kx, ky, dx, dy, x, y)
  895. if not ier == 0:
  896. raise ValueError(f"Error code returned by pardeu: {ier}")
  897. else:
  898. with FITPACK_LOCK:
  899. z, ier = dfitpack.bispeu(tx, ty, c, kx, ky, x, y)
  900. if not ier == 0:
  901. raise ValueError(f"Error code returned by bispeu: {ier}")
  902. z = z.reshape(shape)
  903. return z
  904. def partial_derivative(self, dx, dy):
  905. """Construct a new spline representing a partial derivative of this
  906. spline.
  907. Parameters
  908. ----------
  909. dx, dy : int
  910. Orders of the derivative in x and y respectively. They must be
  911. non-negative integers and less than the respective degree of the
  912. original spline (self) in that direction (``kx``, ``ky``).
  913. Returns
  914. -------
  915. spline :
  916. A new spline of degrees (``kx - dx``, ``ky - dy``) representing the
  917. derivative of this spline.
  918. Notes
  919. -----
  920. .. versionadded:: 1.9.0
  921. """
  922. if dx == 0 and dy == 0:
  923. return self
  924. else:
  925. kx, ky = self.degrees
  926. if not (dx >= 0 and dy >= 0):
  927. raise ValueError("order of derivative must be positive or"
  928. " zero")
  929. if not (dx < kx and dy < ky):
  930. raise ValueError("order of derivative must be less than"
  931. " degree of spline")
  932. tx, ty, c = self.tck[:3]
  933. with FITPACK_LOCK:
  934. newc, ier = dfitpack.pardtc(tx, ty, c, kx, ky, dx, dy)
  935. if ier != 0:
  936. # This should not happen under normal conditions.
  937. raise ValueError(f"Unexpected error code returned by pardtc: {ier}")
  938. nx = len(tx)
  939. ny = len(ty)
  940. newtx = tx[dx:nx - dx]
  941. newty = ty[dy:ny - dy]
  942. newkx, newky = kx - dx, ky - dy
  943. newclen = (nx - dx - kx - 1) * (ny - dy - ky - 1)
  944. return _DerivedBivariateSpline._from_tck((newtx, newty,
  945. newc[:newclen],
  946. newkx, newky))
  947. _surfit_messages = {1: """
  948. The required storage space exceeds the available storage space: nxest
  949. or nyest too small, or s too small.
  950. The weighted least-squares spline corresponds to the current set of
  951. knots.""",
  952. 2: """
  953. A theoretically impossible result was found during the iteration
  954. process for finding a smoothing spline with fp = s: s too small or
  955. badly chosen eps.
  956. Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.""",
  957. 3: """
  958. the maximal number of iterations maxit (set to 20 by the program)
  959. allowed for finding a smoothing spline with fp=s has been reached:
  960. s too small.
  961. Weighted sum of squared residuals does not satisfy abs(fp-s)/s < tol.
  962. Try increasing maxit by passing it as a keyword argument.""",
  963. 4: """
  964. No more knots can be added because the number of b-spline coefficients
  965. (nx-kx-1)*(ny-ky-1) already exceeds the number of data points m:
  966. either s or m too small.
  967. The weighted least-squares spline corresponds to the current set of
  968. knots.""",
  969. 5: """
  970. No more knots can be added because the additional knot would (quasi)
  971. coincide with an old one: s too small or too large a weight to an
  972. inaccurate data point.
  973. The weighted least-squares spline corresponds to the current set of
  974. knots.""",
  975. 10: """
  976. Error on entry, no approximation returned. The following conditions
  977. must hold:
  978. xb<=x[i]<=xe, yb<=y[i]<=ye, w[i]>0, i=0..m-1
  979. If iopt==-1, then
  980. xb<tx[kx+1]<tx[kx+2]<...<tx[nx-kx-2]<xe
  981. yb<ty[ky+1]<ty[ky+2]<...<ty[ny-ky-2]<ye""",
  982. -3: """
  983. The coefficients of the spline returned have been computed as the
  984. minimal norm least-squares solution of a (numerically) rank deficient
  985. system (deficiency=%i). If deficiency is large, the results may be
  986. inaccurate. Deficiency may strongly depend on the value of eps."""
  987. }
  988. @xp_capabilities(out_of_scope=True)
  989. class BivariateSpline(_BivariateSplineBase):
  990. """
  991. Base class for bivariate splines.
  992. This describes a spline ``s(x, y)`` of degrees ``kx`` and ``ky`` on
  993. the rectangle ``[xb, xe] * [yb, ye]`` calculated from a given set
  994. of data points ``(x, y, z)``.
  995. This class is meant to be subclassed, not instantiated directly.
  996. To construct these splines, call either `SmoothBivariateSpline` or
  997. `LSQBivariateSpline` or `RectBivariateSpline`.
  998. See Also
  999. --------
  1000. UnivariateSpline :
  1001. a smooth univariate spline to fit a given set of data points.
  1002. SmoothBivariateSpline :
  1003. a smoothing bivariate spline through the given points
  1004. LSQBivariateSpline :
  1005. a bivariate spline using weighted least-squares fitting
  1006. RectSphereBivariateSpline :
  1007. a bivariate spline over a rectangular mesh on a sphere
  1008. SmoothSphereBivariateSpline :
  1009. a smoothing bivariate spline in spherical coordinates
  1010. LSQSphereBivariateSpline :
  1011. a bivariate spline in spherical coordinates using weighted
  1012. least-squares fitting
  1013. RectBivariateSpline :
  1014. a bivariate spline over a rectangular mesh.
  1015. bisplrep :
  1016. a function to find a bivariate B-spline representation of a surface
  1017. bisplev :
  1018. a function to evaluate a bivariate B-spline and its derivatives
  1019. """
  1020. def ev(self, xi, yi, dx=0, dy=0):
  1021. """
  1022. Evaluate the spline at points
  1023. Returns the interpolated value at ``(xi[i], yi[i]),
  1024. i=0,...,len(xi)-1``.
  1025. Parameters
  1026. ----------
  1027. xi, yi : array_like
  1028. Input coordinates. Standard Numpy broadcasting is obeyed.
  1029. The ordering of axes is consistent with
  1030. ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
  1031. default ordering ``np.meshgrid(..., indexing="xy")``.
  1032. dx : int, optional
  1033. Order of x-derivative
  1034. .. versionadded:: 0.14.0
  1035. dy : int, optional
  1036. Order of y-derivative
  1037. .. versionadded:: 0.14.0
  1038. Examples
  1039. --------
  1040. Suppose that we want to bilinearly interpolate an exponentially decaying
  1041. function in 2 dimensions.
  1042. >>> import numpy as np
  1043. >>> from scipy.interpolate import RectBivariateSpline
  1044. >>> def f(x, y):
  1045. ... return np.exp(-np.sqrt((x / 2) ** 2 + y**2))
  1046. We sample the function on a coarse grid and set up the interpolator. Note that
  1047. the default ``indexing="xy"`` of meshgrid would result in an unexpected
  1048. (transposed) result after interpolation.
  1049. >>> xarr = np.linspace(-3, 3, 21)
  1050. >>> yarr = np.linspace(-3, 3, 21)
  1051. >>> xgrid, ygrid = np.meshgrid(xarr, yarr, indexing="ij")
  1052. >>> zdata = f(xgrid, ygrid)
  1053. >>> rbs = RectBivariateSpline(xarr, yarr, zdata, kx=1, ky=1)
  1054. Next we sample the function along a diagonal slice through the coordinate space
  1055. on a finer grid using interpolation.
  1056. >>> xinterp = np.linspace(-3, 3, 201)
  1057. >>> yinterp = np.linspace(3, -3, 201)
  1058. >>> zinterp = rbs.ev(xinterp, yinterp)
  1059. And check that the interpolation passes through the function evaluations as a
  1060. function of the distance from the origin along the slice.
  1061. >>> import matplotlib.pyplot as plt
  1062. >>> fig = plt.figure()
  1063. >>> ax1 = fig.add_subplot(1, 1, 1)
  1064. >>> ax1.plot(np.sqrt(xarr**2 + yarr**2), np.diag(zdata), "or")
  1065. >>> ax1.plot(np.sqrt(xinterp**2 + yinterp**2), zinterp, "-b")
  1066. >>> plt.show()
  1067. """
  1068. return self.__call__(xi, yi, dx=dx, dy=dy, grid=False)
  1069. def integral(self, xa, xb, ya, yb):
  1070. """
  1071. Evaluate the integral of the spline over area [xa,xb] x [ya,yb].
  1072. Parameters
  1073. ----------
  1074. xa, xb : float
  1075. The end-points of the x integration interval.
  1076. ya, yb : float
  1077. The end-points of the y integration interval.
  1078. Returns
  1079. -------
  1080. integ : float
  1081. The value of the resulting integral.
  1082. """
  1083. tx, ty, c = self.tck[:3]
  1084. kx, ky = self.degrees
  1085. with FITPACK_LOCK:
  1086. return dfitpack.dblint(tx, ty, c, kx, ky, xa, xb, ya, yb)
  1087. @staticmethod
  1088. def _validate_input(x, y, z, w, kx, ky, eps):
  1089. x, y, z = np.asarray(x), np.asarray(y), np.asarray(z)
  1090. if not x.size == y.size == z.size:
  1091. raise ValueError('x, y, and z should have a same length')
  1092. if w is not None:
  1093. w = np.asarray(w)
  1094. if x.size != w.size:
  1095. raise ValueError('x, y, z, and w should have a same length')
  1096. elif not np.all(w >= 0.0):
  1097. raise ValueError('w should be positive')
  1098. if (eps is not None) and (not 0.0 < eps < 1.0):
  1099. raise ValueError('eps should be between (0, 1)')
  1100. if not x.size >= (kx + 1) * (ky + 1):
  1101. raise ValueError('The length of x, y and z should be at least'
  1102. ' (kx+1) * (ky+1)')
  1103. return x, y, z, w
  1104. class _DerivedBivariateSpline(_BivariateSplineBase):
  1105. """Bivariate spline constructed from the coefficients and knots of another
  1106. spline.
  1107. Notes
  1108. -----
  1109. The class is not meant to be instantiated directly from the data to be
  1110. interpolated or smoothed. As a result, its ``fp`` attribute and
  1111. ``get_residual`` method are inherited but overridden; ``AttributeError`` is
  1112. raised when they are accessed.
  1113. The other inherited attributes can be used as usual.
  1114. """
  1115. _invalid_why = ("is unavailable, because _DerivedBivariateSpline"
  1116. " instance is not constructed from data that are to be"
  1117. " interpolated or smoothed, but derived from the"
  1118. " underlying knots and coefficients of another spline"
  1119. " object")
  1120. @property
  1121. def fp(self):
  1122. raise AttributeError(f"attribute \"fp\" {self._invalid_why}")
  1123. def get_residual(self):
  1124. raise AttributeError(f"method \"get_residual\" {self._invalid_why}")
  1125. @xp_capabilities(out_of_scope=True)
  1126. class SmoothBivariateSpline(BivariateSpline):
  1127. """
  1128. Smooth bivariate spline approximation.
  1129. Parameters
  1130. ----------
  1131. x, y, z : array_like
  1132. 1-D sequences of data points (order is not important).
  1133. w : array_like, optional
  1134. Positive 1-D sequence of weights, of same length as `x`, `y` and `z`.
  1135. bbox : array_like, optional
  1136. Sequence of length 4 specifying the boundary of the rectangular
  1137. approximation domain. By default,
  1138. ``bbox=[min(x), max(x), min(y), max(y)]``.
  1139. kx, ky : ints, optional
  1140. Degrees of the bivariate spline. Default is 3.
  1141. s : float, optional
  1142. Positive smoothing factor defined for estimation condition:
  1143. ``sum((w[i]*(z[i]-s(x[i], y[i])))**2, axis=0) <= s``
  1144. Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
  1145. estimate of the standard deviation of ``z[i]``.
  1146. eps : float, optional
  1147. A threshold for determining the effective rank of an over-determined
  1148. linear system of equations. `eps` should have a value within the open
  1149. interval ``(0, 1)``, the default is 1e-16.
  1150. See Also
  1151. --------
  1152. BivariateSpline :
  1153. a base class for bivariate splines.
  1154. UnivariateSpline :
  1155. a smooth univariate spline to fit a given set of data points.
  1156. LSQBivariateSpline :
  1157. a bivariate spline using weighted least-squares fitting
  1158. RectSphereBivariateSpline :
  1159. a bivariate spline over a rectangular mesh on a sphere
  1160. SmoothSphereBivariateSpline :
  1161. a smoothing bivariate spline in spherical coordinates
  1162. LSQSphereBivariateSpline :
  1163. a bivariate spline in spherical coordinates using weighted
  1164. least-squares fitting
  1165. RectBivariateSpline :
  1166. a bivariate spline over a rectangular mesh
  1167. bisplrep :
  1168. a function to find a bivariate B-spline representation of a surface
  1169. bisplev :
  1170. a function to evaluate a bivariate B-spline and its derivatives
  1171. Notes
  1172. -----
  1173. The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
  1174. If the input data is such that input dimensions have incommensurate
  1175. units and differ by many orders of magnitude, the interpolant may have
  1176. numerical artifacts. Consider rescaling the data before interpolating.
  1177. This routine constructs spline knot vectors automatically via the FITPACK
  1178. algorithm. The spline knots may be placed away from the data points. For
  1179. some data sets, this routine may fail to construct an interpolating spline,
  1180. even if one is requested via ``s=0`` parameter. In such situations, it is
  1181. recommended to use `bisplrep` / `bisplev` directly instead of this routine
  1182. and, if needed, increase the values of ``nxest`` and ``nyest`` parameters
  1183. of `bisplrep`.
  1184. For linear interpolation, `LinearNDInterpolator` is preferred.
  1185. Consult the :ref:`interp-transition-guide` for discussion.
  1186. """
  1187. def __init__(self, x, y, z, w=None, bbox=[None] * 4, kx=3, ky=3, s=None,
  1188. eps=1e-16):
  1189. x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
  1190. bbox = ravel(bbox)
  1191. if not bbox.shape == (4,):
  1192. raise ValueError('bbox shape should be (4,)')
  1193. if s is not None and not s >= 0.0:
  1194. raise ValueError("s should be s >= 0.0")
  1195. xb, xe, yb, ye = bbox
  1196. with FITPACK_LOCK:
  1197. nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
  1198. x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps, lwrk2=1)
  1199. if ier > 10: # lwrk2 was to small, re-run
  1200. nx, tx, ny, ty, c, fp, wrk1, ier = dfitpack.surfit_smth(
  1201. x, y, z, w, xb, xe, yb, ye, kx, ky, s=s, eps=eps,
  1202. lwrk2=ier)
  1203. if ier in [0, -1, -2]: # normal return
  1204. pass
  1205. else:
  1206. message = _surfit_messages.get(ier, f'ier={ier}')
  1207. warnings.warn(message, stacklevel=2)
  1208. self.fp = fp
  1209. self.tck = tx[:nx], ty[:ny], c[:(nx-kx-1)*(ny-ky-1)]
  1210. self.degrees = kx, ky
  1211. @xp_capabilities(out_of_scope=True)
  1212. class LSQBivariateSpline(BivariateSpline):
  1213. """
  1214. Weighted least-squares bivariate spline approximation.
  1215. Parameters
  1216. ----------
  1217. x, y, z : array_like
  1218. 1-D sequences of data points (order is not important).
  1219. tx, ty : array_like
  1220. Strictly ordered 1-D sequences of knots coordinates.
  1221. w : array_like, optional
  1222. Positive 1-D array of weights, of the same length as `x`, `y` and `z`.
  1223. bbox : (4,) array_like, optional
  1224. Sequence of length 4 specifying the boundary of the rectangular
  1225. approximation domain. By default,
  1226. ``bbox=[min(x,tx),max(x,tx), min(y,ty),max(y,ty)]``.
  1227. kx, ky : ints, optional
  1228. Degrees of the bivariate spline. Default is 3.
  1229. eps : float, optional
  1230. A threshold for determining the effective rank of an over-determined
  1231. linear system of equations. `eps` should have a value within the open
  1232. interval ``(0, 1)``, the default is 1e-16.
  1233. See Also
  1234. --------
  1235. BivariateSpline :
  1236. a base class for bivariate splines.
  1237. UnivariateSpline :
  1238. a smooth univariate spline to fit a given set of data points.
  1239. SmoothBivariateSpline :
  1240. a smoothing bivariate spline through the given points
  1241. RectSphereBivariateSpline :
  1242. a bivariate spline over a rectangular mesh on a sphere
  1243. SmoothSphereBivariateSpline :
  1244. a smoothing bivariate spline in spherical coordinates
  1245. LSQSphereBivariateSpline :
  1246. a bivariate spline in spherical coordinates using weighted
  1247. least-squares fitting
  1248. RectBivariateSpline :
  1249. a bivariate spline over a rectangular mesh.
  1250. bisplrep :
  1251. a function to find a bivariate B-spline representation of a surface
  1252. bisplev :
  1253. a function to evaluate a bivariate B-spline and its derivatives
  1254. Notes
  1255. -----
  1256. The length of `x`, `y` and `z` should be at least ``(kx+1) * (ky+1)``.
  1257. If the input data is such that input dimensions have incommensurate
  1258. units and differ by many orders of magnitude, the interpolant may have
  1259. numerical artifacts. Consider rescaling the data before interpolating.
  1260. """
  1261. def __init__(self, x, y, z, tx, ty, w=None, bbox=[None]*4, kx=3, ky=3,
  1262. eps=None):
  1263. x, y, z, w = self._validate_input(x, y, z, w, kx, ky, eps)
  1264. bbox = ravel(bbox)
  1265. if not bbox.shape == (4,):
  1266. raise ValueError('bbox shape should be (4,)')
  1267. nx = 2*kx+2+len(tx)
  1268. ny = 2*ky+2+len(ty)
  1269. # The Fortran subroutine "surfit" (called as dfitpack.surfit_lsq)
  1270. # requires that the knot arrays passed as input should be "real
  1271. # array(s) of dimension nmax" where "nmax" refers to the greater of nx
  1272. # and ny. We pad the tx1/ty1 arrays here so that this is satisfied, and
  1273. # slice them to the desired sizes upon return.
  1274. nmax = max(nx, ny)
  1275. tx1 = zeros((nmax,), float)
  1276. ty1 = zeros((nmax,), float)
  1277. tx1[kx+1:nx-kx-1] = tx
  1278. ty1[ky+1:ny-ky-1] = ty
  1279. xb, xe, yb, ye = bbox
  1280. with FITPACK_LOCK:
  1281. tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z, nx, tx1, ny, ty1,
  1282. w, xb, xe, yb, ye,
  1283. kx, ky, eps, lwrk2=1)
  1284. if ier > 10:
  1285. tx1, ty1, c, fp, ier = dfitpack.surfit_lsq(x, y, z,
  1286. nx, tx1, ny, ty1, w,
  1287. xb, xe, yb, ye,
  1288. kx, ky, eps, lwrk2=ier)
  1289. if ier in [0, -1, -2]: # normal return
  1290. pass
  1291. else:
  1292. if ier < -2:
  1293. deficiency = (nx-kx-1)*(ny-ky-1)+ier
  1294. message = _surfit_messages.get(-3) % (deficiency)
  1295. else:
  1296. message = _surfit_messages.get(ier, f'ier={ier}')
  1297. warnings.warn(message, stacklevel=2)
  1298. self.fp = fp
  1299. self.tck = tx1[:nx], ty1[:ny], c
  1300. self.degrees = kx, ky
  1301. @xp_capabilities(out_of_scope=True)
  1302. class RectBivariateSpline(BivariateSpline):
  1303. """
  1304. Bivariate spline approximation over a rectangular mesh.
  1305. Can be used for both smoothing and interpolating data.
  1306. Parameters
  1307. ----------
  1308. x,y : array_like
  1309. 1-D arrays of coordinates in strictly ascending order.
  1310. Evaluated points outside the data range will be extrapolated.
  1311. z : array_like
  1312. 2-D array of data with shape (x.size,y.size).
  1313. bbox : array_like, optional
  1314. Sequence of length 4 specifying the boundary of the rectangular
  1315. approximation domain, which means the start and end spline knots of
  1316. each dimension are set by these values. By default,
  1317. ``bbox=[min(x), max(x), min(y), max(y)]``.
  1318. kx, ky : ints, optional
  1319. Degrees of the bivariate spline. Default is 3.
  1320. s : float, optional
  1321. Positive smoothing factor defined for estimation condition:
  1322. ``sum((z[i]-f(x[i], y[i]))**2, axis=0) <= s`` where f is a spline
  1323. function. Default is ``s=0``, which is for interpolation.
  1324. maxit : int, optional
  1325. The maximal number of iterations maxit allowed for finding a
  1326. smoothing spline with fp=s. Default is ``maxit=20``.
  1327. See Also
  1328. --------
  1329. BivariateSpline :
  1330. a base class for bivariate splines.
  1331. UnivariateSpline :
  1332. a smooth univariate spline to fit a given set of data points.
  1333. SmoothBivariateSpline :
  1334. a smoothing bivariate spline through the given points
  1335. LSQBivariateSpline :
  1336. a bivariate spline using weighted least-squares fitting
  1337. RectSphereBivariateSpline :
  1338. a bivariate spline over a rectangular mesh on a sphere
  1339. SmoothSphereBivariateSpline :
  1340. a smoothing bivariate spline in spherical coordinates
  1341. LSQSphereBivariateSpline :
  1342. a bivariate spline in spherical coordinates using weighted
  1343. least-squares fitting
  1344. bisplrep :
  1345. a function to find a bivariate B-spline representation of a surface
  1346. bisplev :
  1347. a function to evaluate a bivariate B-spline and its derivatives
  1348. Notes
  1349. -----
  1350. If the input data is such that input dimensions have incommensurate
  1351. units and differ by many orders of magnitude, the interpolant may have
  1352. numerical artifacts. Consider rescaling the data before interpolating.
  1353. """
  1354. def __init__(self, x, y, z, bbox=[None] * 4, kx=3, ky=3, s=0, maxit=20):
  1355. x, y, bbox = ravel(x), ravel(y), ravel(bbox)
  1356. z = np.asarray(z)
  1357. if not np.all(diff(x) > 0.0):
  1358. raise ValueError('x must be strictly increasing')
  1359. if not np.all(diff(y) > 0.0):
  1360. raise ValueError('y must be strictly increasing')
  1361. if not x.size == z.shape[0]:
  1362. raise ValueError('x dimension of z must have same number of '
  1363. 'elements as x')
  1364. if not y.size == z.shape[1]:
  1365. raise ValueError('y dimension of z must have same number of '
  1366. 'elements as y')
  1367. if not bbox.shape == (4,):
  1368. raise ValueError('bbox shape should be (4,)')
  1369. if s is not None and not s >= 0.0:
  1370. raise ValueError("s should be s >= 0.0")
  1371. z = ravel(z)
  1372. xb, xe, yb, ye = bbox
  1373. with FITPACK_LOCK:
  1374. nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth(x, y, z, xb, xe, yb,
  1375. ye, kx, ky, s, maxit)
  1376. if ier not in [0, -1, -2]:
  1377. msg = _surfit_messages.get(ier, f'ier={ier}')
  1378. raise ValueError(msg)
  1379. self.fp = fp
  1380. self.tck = tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)]
  1381. self.degrees = kx, ky
  1382. _spherefit_messages = _surfit_messages.copy()
  1383. _spherefit_messages[10] = """
  1384. ERROR. On entry, the input data are controlled on validity. The following
  1385. restrictions must be satisfied:
  1386. -1<=iopt<=1, m>=2, ntest>=8 ,npest >=8, 0<eps<1,
  1387. 0<=teta(i)<=pi, 0<=phi(i)<=2*pi, w(i)>0, i=1,...,m
  1388. lwrk1 >= 185+52*v+10*u+14*u*v+8*(u-1)*v**2+8*m
  1389. kwrk >= m+(ntest-7)*(npest-7)
  1390. if iopt=-1: 8<=nt<=ntest , 9<=np<=npest
  1391. 0<tt(5)<tt(6)<...<tt(nt-4)<pi
  1392. 0<tp(5)<tp(6)<...<tp(np-4)<2*pi
  1393. if iopt>=0: s>=0
  1394. if one of these conditions is found to be violated,control
  1395. is immediately repassed to the calling program. in that
  1396. case there is no approximation returned."""
  1397. _spherefit_messages[-3] = """
  1398. WARNING. The coefficients of the spline returned have been computed as the
  1399. minimal norm least-squares solution of a (numerically) rank
  1400. deficient system (deficiency=%i, rank=%i). Especially if the rank
  1401. deficiency, which is computed by 6+(nt-8)*(np-7)+ier, is large,
  1402. the results may be inaccurate. They could also seriously depend on
  1403. the value of eps."""
  1404. @xp_capabilities(out_of_scope=True)
  1405. class SphereBivariateSpline(_BivariateSplineBase):
  1406. """
  1407. Bivariate spline s(x,y) of degrees 3 on a sphere, calculated from a
  1408. given set of data points (theta,phi,r).
  1409. .. versionadded:: 0.11.0
  1410. See Also
  1411. --------
  1412. bisplrep :
  1413. a function to find a bivariate B-spline representation of a surface
  1414. bisplev :
  1415. a function to evaluate a bivariate B-spline and its derivatives
  1416. UnivariateSpline :
  1417. a smooth univariate spline to fit a given set of data points.
  1418. SmoothBivariateSpline :
  1419. a smoothing bivariate spline through the given points
  1420. LSQUnivariateSpline :
  1421. a univariate spline using weighted least-squares fitting
  1422. """
  1423. def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
  1424. """
  1425. Evaluate the spline or its derivatives at given positions.
  1426. Parameters
  1427. ----------
  1428. theta, phi : array_like
  1429. Input coordinates.
  1430. If `grid` is False, evaluate the spline at points
  1431. ``(theta[i], phi[i]), i=0, ..., len(x)-1``. Standard
  1432. Numpy broadcasting is obeyed.
  1433. If `grid` is True: evaluate spline at the grid points
  1434. defined by the coordinate arrays theta, phi. The arrays
  1435. must be sorted to increasing order.
  1436. The ordering of axes is consistent with
  1437. ``np.meshgrid(..., indexing="ij")`` and inconsistent with the
  1438. default ordering ``np.meshgrid(..., indexing="xy")``.
  1439. dtheta : int, optional
  1440. Order of theta-derivative
  1441. .. versionadded:: 0.14.0
  1442. dphi : int
  1443. Order of phi-derivative
  1444. .. versionadded:: 0.14.0
  1445. grid : bool
  1446. Whether to evaluate the results on a grid spanned by the
  1447. input arrays, or at points specified by the input arrays.
  1448. .. versionadded:: 0.14.0
  1449. Examples
  1450. --------
  1451. Suppose that we want to use splines to interpolate a bivariate function on a
  1452. sphere. The value of the function is known on a grid of longitudes and
  1453. colatitudes.
  1454. >>> import numpy as np
  1455. >>> from scipy.interpolate import RectSphereBivariateSpline
  1456. >>> def f(theta, phi):
  1457. ... return np.sin(theta) * np.cos(phi)
  1458. We evaluate the function on the grid. Note that the default indexing="xy"
  1459. of meshgrid would result in an unexpected (transposed) result after
  1460. interpolation.
  1461. >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
  1462. >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
  1463. >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
  1464. >>> zdata = f(thetagrid, phigrid)
  1465. We next set up the interpolator and use it to evaluate the function
  1466. on a finer grid.
  1467. >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
  1468. >>> thetaarr_fine = np.linspace(0, np.pi, 200)
  1469. >>> phiarr_fine = np.linspace(0, 2 * np.pi, 200)
  1470. >>> zdata_fine = rsbs(thetaarr_fine, phiarr_fine)
  1471. Finally we plot the coarsly-sampled input data alongside the
  1472. finely-sampled interpolated data to check that they agree.
  1473. >>> import matplotlib.pyplot as plt
  1474. >>> fig = plt.figure()
  1475. >>> ax1 = fig.add_subplot(1, 2, 1)
  1476. >>> ax2 = fig.add_subplot(1, 2, 2)
  1477. >>> ax1.imshow(zdata)
  1478. >>> ax2.imshow(zdata_fine)
  1479. >>> plt.show()
  1480. """
  1481. theta = np.asarray(theta)
  1482. phi = np.asarray(phi)
  1483. if theta.size > 0 and (theta.min() < 0. or theta.max() > np.pi):
  1484. raise ValueError("requested theta out of bounds.")
  1485. return _BivariateSplineBase.__call__(self, theta, phi,
  1486. dx=dtheta, dy=dphi, grid=grid)
  1487. def ev(self, theta, phi, dtheta=0, dphi=0):
  1488. """
  1489. Evaluate the spline at points
  1490. Returns the interpolated value at ``(theta[i], phi[i]),
  1491. i=0,...,len(theta)-1``.
  1492. Parameters
  1493. ----------
  1494. theta, phi : array_like
  1495. Input coordinates. Standard Numpy broadcasting is obeyed.
  1496. The ordering of axes is consistent with
  1497. np.meshgrid(..., indexing="ij") and inconsistent with the
  1498. default ordering np.meshgrid(..., indexing="xy").
  1499. dtheta : int, optional
  1500. Order of theta-derivative
  1501. .. versionadded:: 0.14.0
  1502. dphi : int, optional
  1503. Order of phi-derivative
  1504. .. versionadded:: 0.14.0
  1505. Examples
  1506. --------
  1507. Suppose that we want to use splines to interpolate a bivariate function on a
  1508. sphere. The value of the function is known on a grid of longitudes and
  1509. colatitudes.
  1510. >>> import numpy as np
  1511. >>> from scipy.interpolate import RectSphereBivariateSpline
  1512. >>> def f(theta, phi):
  1513. ... return np.sin(theta) * np.cos(phi)
  1514. We evaluate the function on the grid. Note that the default indexing="xy"
  1515. of meshgrid would result in an unexpected (transposed) result after
  1516. interpolation.
  1517. >>> thetaarr = np.linspace(0, np.pi, 22)[1:-1]
  1518. >>> phiarr = np.linspace(0, 2 * np.pi, 21)[:-1]
  1519. >>> thetagrid, phigrid = np.meshgrid(thetaarr, phiarr, indexing="ij")
  1520. >>> zdata = f(thetagrid, phigrid)
  1521. We next set up the interpolator and use it to evaluate the function
  1522. at points not on the original grid.
  1523. >>> rsbs = RectSphereBivariateSpline(thetaarr, phiarr, zdata)
  1524. >>> thetainterp = np.linspace(thetaarr[0], thetaarr[-1], 200)
  1525. >>> phiinterp = np.linspace(phiarr[0], phiarr[-1], 200)
  1526. >>> zinterp = rsbs.ev(thetainterp, phiinterp)
  1527. Finally we plot the original data for a diagonal slice through the
  1528. initial grid, and the spline approximation along the same slice.
  1529. >>> import matplotlib.pyplot as plt
  1530. >>> fig = plt.figure()
  1531. >>> ax1 = fig.add_subplot(1, 1, 1)
  1532. >>> ax1.plot(np.sin(thetaarr) * np.sin(phiarr), np.diag(zdata), "or")
  1533. >>> ax1.plot(np.sin(thetainterp) * np.sin(phiinterp), zinterp, "-b")
  1534. >>> plt.show()
  1535. """
  1536. return self.__call__(theta, phi, dtheta=dtheta, dphi=dphi, grid=False)
  1537. @xp_capabilities(out_of_scope=True)
  1538. class SmoothSphereBivariateSpline(SphereBivariateSpline):
  1539. """
  1540. Smooth bivariate spline approximation in spherical coordinates.
  1541. .. versionadded:: 0.11.0
  1542. Parameters
  1543. ----------
  1544. theta, phi, r : array_like
  1545. 1-D sequences of data points (order is not important). Coordinates
  1546. must be given in radians. Theta must lie within the interval
  1547. ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
  1548. w : array_like, optional
  1549. Positive 1-D sequence of weights.
  1550. s : float, optional
  1551. Positive smoothing factor defined for estimation condition:
  1552. ``sum((w(i)*(r(i) - s(theta(i), phi(i))))**2, axis=0) <= s``
  1553. Default ``s=len(w)`` which should be a good value if ``1/w[i]`` is an
  1554. estimate of the standard deviation of ``r[i]``.
  1555. eps : float, optional
  1556. A threshold for determining the effective rank of an over-determined
  1557. linear system of equations. `eps` should have a value within the open
  1558. interval ``(0, 1)``, the default is 1e-16.
  1559. See Also
  1560. --------
  1561. BivariateSpline :
  1562. a base class for bivariate splines.
  1563. UnivariateSpline :
  1564. a smooth univariate spline to fit a given set of data points.
  1565. SmoothBivariateSpline :
  1566. a smoothing bivariate spline through the given points
  1567. LSQBivariateSpline :
  1568. a bivariate spline using weighted least-squares fitting
  1569. RectSphereBivariateSpline :
  1570. a bivariate spline over a rectangular mesh on a sphere
  1571. LSQSphereBivariateSpline :
  1572. a bivariate spline in spherical coordinates using weighted
  1573. least-squares fitting
  1574. RectBivariateSpline :
  1575. a bivariate spline over a rectangular mesh.
  1576. bisplrep :
  1577. a function to find a bivariate B-spline representation of a surface
  1578. bisplev :
  1579. a function to evaluate a bivariate B-spline and its derivatives
  1580. Notes
  1581. -----
  1582. For more information, see the FITPACK_ site about this function.
  1583. .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
  1584. Examples
  1585. --------
  1586. Suppose we have global data on a coarse grid (the input data does not
  1587. have to be on a grid):
  1588. >>> import numpy as np
  1589. >>> theta = np.linspace(0., np.pi, 7)
  1590. >>> phi = np.linspace(0., 2*np.pi, 9)
  1591. >>> data = np.empty((theta.shape[0], phi.shape[0]))
  1592. >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
  1593. >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
  1594. >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
  1595. >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
  1596. >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
  1597. >>> data[3,3:-2] = 3.
  1598. >>> data = np.roll(data, 4, 1)
  1599. We need to set up the interpolator object
  1600. >>> lats, lons = np.meshgrid(theta, phi)
  1601. >>> from scipy.interpolate import SmoothSphereBivariateSpline
  1602. >>> lut = SmoothSphereBivariateSpline(lats.ravel(), lons.ravel(),
  1603. ... data.T.ravel(), s=3.5)
  1604. As a first test, we'll see what the algorithm returns when run on the
  1605. input coordinates
  1606. >>> data_orig = lut(theta, phi)
  1607. Finally we interpolate the data to a finer grid
  1608. >>> fine_lats = np.linspace(0., np.pi, 70)
  1609. >>> fine_lons = np.linspace(0., 2 * np.pi, 90)
  1610. >>> data_smth = lut(fine_lats, fine_lons)
  1611. >>> import matplotlib.pyplot as plt
  1612. >>> fig = plt.figure()
  1613. >>> ax1 = fig.add_subplot(131)
  1614. >>> ax1.imshow(data, interpolation='nearest')
  1615. >>> ax2 = fig.add_subplot(132)
  1616. >>> ax2.imshow(data_orig, interpolation='nearest')
  1617. >>> ax3 = fig.add_subplot(133)
  1618. >>> ax3.imshow(data_smth, interpolation='nearest')
  1619. >>> plt.show()
  1620. """
  1621. def __init__(self, theta, phi, r, w=None, s=0., eps=1E-16):
  1622. theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
  1623. # input validation
  1624. if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
  1625. raise ValueError('theta should be between [0, pi]')
  1626. if not ((0.0 <= phi).all() and (phi <= 2.0 * np.pi).all()):
  1627. raise ValueError('phi should be between [0, 2pi]')
  1628. if w is not None:
  1629. w = np.asarray(w)
  1630. if not (w >= 0.0).all():
  1631. raise ValueError('w should be positive')
  1632. if not s >= 0.0:
  1633. raise ValueError('s should be positive')
  1634. if not 0.0 < eps < 1.0:
  1635. raise ValueError('eps should be between (0, 1)')
  1636. with FITPACK_LOCK:
  1637. nt_, tt_, np_, tp_, c, fp, ier = dfitpack.spherfit_smth(theta, phi,
  1638. r, w=w, s=s,
  1639. eps=eps)
  1640. if ier not in [0, -1, -2]:
  1641. message = _spherefit_messages.get(ier, f'ier={ier}')
  1642. raise ValueError(message)
  1643. self.fp = fp
  1644. self.tck = tt_[:nt_], tp_[:np_], c[:(nt_ - 4) * (np_ - 4)]
  1645. self.degrees = (3, 3)
  1646. def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
  1647. theta = np.asarray(theta)
  1648. phi = np.asarray(phi)
  1649. if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
  1650. raise ValueError("requested phi out of bounds.")
  1651. return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
  1652. dphi=dphi, grid=grid)
  1653. @xp_capabilities(out_of_scope=True)
  1654. class LSQSphereBivariateSpline(SphereBivariateSpline):
  1655. """
  1656. Weighted least-squares bivariate spline approximation in spherical
  1657. coordinates.
  1658. Determines a smoothing bicubic spline according to a given
  1659. set of knots in the `theta` and `phi` directions.
  1660. .. versionadded:: 0.11.0
  1661. Parameters
  1662. ----------
  1663. theta, phi, r : array_like
  1664. 1-D sequences of data points (order is not important). Coordinates
  1665. must be given in radians. Theta must lie within the interval
  1666. ``[0, pi]``, and phi must lie within the interval ``[0, 2pi]``.
  1667. tt, tp : array_like
  1668. Strictly ordered 1-D sequences of knots coordinates.
  1669. Coordinates must satisfy ``0 < tt[i] < pi``, ``0 < tp[i] < 2*pi``.
  1670. w : array_like, optional
  1671. Positive 1-D sequence of weights, of the same length as `theta`, `phi`
  1672. and `r`.
  1673. eps : float, optional
  1674. A threshold for determining the effective rank of an over-determined
  1675. linear system of equations. `eps` should have a value within the
  1676. open interval ``(0, 1)``, the default is 1e-16.
  1677. See Also
  1678. --------
  1679. BivariateSpline :
  1680. a base class for bivariate splines.
  1681. UnivariateSpline :
  1682. a smooth univariate spline to fit a given set of data points.
  1683. SmoothBivariateSpline :
  1684. a smoothing bivariate spline through the given points
  1685. LSQBivariateSpline :
  1686. a bivariate spline using weighted least-squares fitting
  1687. RectSphereBivariateSpline :
  1688. a bivariate spline over a rectangular mesh on a sphere
  1689. SmoothSphereBivariateSpline :
  1690. a smoothing bivariate spline in spherical coordinates
  1691. RectBivariateSpline :
  1692. a bivariate spline over a rectangular mesh.
  1693. bisplrep :
  1694. a function to find a bivariate B-spline representation of a surface
  1695. bisplev :
  1696. a function to evaluate a bivariate B-spline and its derivatives
  1697. Notes
  1698. -----
  1699. For more information, see the FITPACK_ site about this function.
  1700. .. _FITPACK: http://www.netlib.org/dierckx/sphere.f
  1701. Examples
  1702. --------
  1703. Suppose we have global data on a coarse grid (the input data does not
  1704. have to be on a grid):
  1705. >>> from scipy.interpolate import LSQSphereBivariateSpline
  1706. >>> import numpy as np
  1707. >>> import matplotlib.pyplot as plt
  1708. >>> theta = np.linspace(0, np.pi, num=7)
  1709. >>> phi = np.linspace(0, 2*np.pi, num=9)
  1710. >>> data = np.empty((theta.shape[0], phi.shape[0]))
  1711. >>> data[:,0], data[0,:], data[-1,:] = 0., 0., 0.
  1712. >>> data[1:-1,1], data[1:-1,-1] = 1., 1.
  1713. >>> data[1,1:-1], data[-2,1:-1] = 1., 1.
  1714. >>> data[2:-2,2], data[2:-2,-2] = 2., 2.
  1715. >>> data[2,2:-2], data[-3,2:-2] = 2., 2.
  1716. >>> data[3,3:-2] = 3.
  1717. >>> data = np.roll(data, 4, 1)
  1718. We need to set up the interpolator object. Here, we must also specify the
  1719. coordinates of the knots to use.
  1720. >>> lats, lons = np.meshgrid(theta, phi)
  1721. >>> knotst, knotsp = theta.copy(), phi.copy()
  1722. >>> knotst[0] += .0001
  1723. >>> knotst[-1] -= .0001
  1724. >>> knotsp[0] += .0001
  1725. >>> knotsp[-1] -= .0001
  1726. >>> lut = LSQSphereBivariateSpline(lats.ravel(), lons.ravel(),
  1727. ... data.T.ravel(), knotst, knotsp)
  1728. As a first test, we'll see what the algorithm returns when run on the
  1729. input coordinates
  1730. >>> data_orig = lut(theta, phi)
  1731. Finally we interpolate the data to a finer grid
  1732. >>> fine_lats = np.linspace(0., np.pi, 70)
  1733. >>> fine_lons = np.linspace(0., 2*np.pi, 90)
  1734. >>> data_lsq = lut(fine_lats, fine_lons)
  1735. >>> fig = plt.figure()
  1736. >>> ax1 = fig.add_subplot(131)
  1737. >>> ax1.imshow(data, interpolation='nearest')
  1738. >>> ax2 = fig.add_subplot(132)
  1739. >>> ax2.imshow(data_orig, interpolation='nearest')
  1740. >>> ax3 = fig.add_subplot(133)
  1741. >>> ax3.imshow(data_lsq, interpolation='nearest')
  1742. >>> plt.show()
  1743. """
  1744. def __init__(self, theta, phi, r, tt, tp, w=None, eps=1E-16):
  1745. theta, phi, r = np.asarray(theta), np.asarray(phi), np.asarray(r)
  1746. tt, tp = np.asarray(tt), np.asarray(tp)
  1747. if not ((0.0 <= theta).all() and (theta <= np.pi).all()):
  1748. raise ValueError('theta should be between [0, pi]')
  1749. if not ((0.0 <= phi).all() and (phi <= 2*np.pi).all()):
  1750. raise ValueError('phi should be between [0, 2pi]')
  1751. if not ((0.0 < tt).all() and (tt < np.pi).all()):
  1752. raise ValueError('tt should be between (0, pi)')
  1753. if not ((0.0 < tp).all() and (tp < 2*np.pi).all()):
  1754. raise ValueError('tp should be between (0, 2pi)')
  1755. if w is not None:
  1756. w = np.asarray(w)
  1757. if not (w >= 0.0).all():
  1758. raise ValueError('w should be positive')
  1759. if not 0.0 < eps < 1.0:
  1760. raise ValueError('eps should be between (0, 1)')
  1761. nt_, np_ = 8 + len(tt), 8 + len(tp)
  1762. tt_, tp_ = zeros((nt_,), float), zeros((np_,), float)
  1763. tt_[4:-4], tp_[4:-4] = tt, tp
  1764. tt_[-4:], tp_[-4:] = np.pi, 2. * np.pi
  1765. with FITPACK_LOCK:
  1766. tt_, tp_, c, fp, ier = dfitpack.spherfit_lsq(theta, phi, r, tt_, tp_,
  1767. w=w, eps=eps)
  1768. if ier > 0:
  1769. message = _spherefit_messages.get(ier, f'ier={ier}')
  1770. raise ValueError(message)
  1771. self.fp = fp
  1772. self.tck = tt_, tp_, c
  1773. self.degrees = (3, 3)
  1774. def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
  1775. theta = np.asarray(theta)
  1776. phi = np.asarray(phi)
  1777. if phi.size > 0 and (phi.min() < 0. or phi.max() > 2. * np.pi):
  1778. raise ValueError("requested phi out of bounds.")
  1779. return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
  1780. dphi=dphi, grid=grid)
  1781. _spfit_messages = _surfit_messages.copy()
  1782. _spfit_messages[10] = """
  1783. ERROR: on entry, the input data are controlled on validity
  1784. the following restrictions must be satisfied.
  1785. -1<=iopt(1)<=1, 0<=iopt(2)<=1, 0<=iopt(3)<=1,
  1786. -1<=ider(1)<=1, 0<=ider(2)<=1, ider(2)=0 if iopt(2)=0.
  1787. -1<=ider(3)<=1, 0<=ider(4)<=1, ider(4)=0 if iopt(3)=0.
  1788. mu >= mumin (see above), mv >= 4, nuest >=8, nvest >= 8,
  1789. kwrk>=5+mu+mv+nuest+nvest,
  1790. lwrk >= 12+nuest*(mv+nvest+3)+nvest*24+4*mu+8*mv+max(nuest,mv+nvest)
  1791. 0< u(i-1)<u(i)< pi,i=2,..,mu,
  1792. -pi<=v(1)< pi, v(1)<v(i-1)<v(i)<v(1)+2*pi, i=3,...,mv
  1793. if iopt(1)=-1: 8<=nu<=min(nuest,mu+6+iopt(2)+iopt(3))
  1794. 0<tu(5)<tu(6)<...<tu(nu-4)< pi
  1795. 8<=nv<=min(nvest,mv+7)
  1796. v(1)<tv(5)<tv(6)<...<tv(nv-4)<v(1)+2*pi
  1797. the schoenberg-whitney conditions, i.e. there must be
  1798. subset of grid coordinates uu(p) and vv(q) such that
  1799. tu(p) < uu(p) < tu(p+4) ,p=1,...,nu-4
  1800. (iopt(2)=1 and iopt(3)=1 also count for a uu-value
  1801. tv(q) < vv(q) < tv(q+4) ,q=1,...,nv-4
  1802. (vv(q) is either a value v(j) or v(j)+2*pi)
  1803. if iopt(1)>=0: s>=0
  1804. if s=0: nuest>=mu+6+iopt(2)+iopt(3), nvest>=mv+7
  1805. if one of these conditions is found to be violated,control is
  1806. immediately repassed to the calling program. in that case there is no
  1807. approximation returned."""
  1808. @xp_capabilities(out_of_scope=True)
  1809. class RectSphereBivariateSpline(SphereBivariateSpline):
  1810. """
  1811. Bivariate spline approximation over a rectangular mesh on a sphere.
  1812. Can be used for smoothing data.
  1813. .. versionadded:: 0.11.0
  1814. Parameters
  1815. ----------
  1816. u : array_like
  1817. 1-D array of colatitude coordinates in strictly ascending order.
  1818. Coordinates must be given in radians and lie within the open interval
  1819. ``(0, pi)``.
  1820. v : array_like
  1821. 1-D array of longitude coordinates in strictly ascending order.
  1822. Coordinates must be given in radians. First element (``v[0]``) must lie
  1823. within the interval ``[-pi, pi)``. Last element (``v[-1]``) must satisfy
  1824. ``v[-1] <= v[0] + 2*pi``.
  1825. r : array_like
  1826. 2-D array of data with shape ``(u.size, v.size)``.
  1827. s : float, optional
  1828. Positive smoothing factor defined for estimation condition
  1829. (``s=0`` is for interpolation).
  1830. pole_continuity : bool or (bool, bool), optional
  1831. Order of continuity at the poles ``u=0`` (``pole_continuity[0]``) and
  1832. ``u=pi`` (``pole_continuity[1]``). The order of continuity at the pole
  1833. will be 1 or 0 when this is True or False, respectively.
  1834. Defaults to False.
  1835. pole_values : float or (float, float), optional
  1836. Data values at the poles ``u=0`` and ``u=pi``. Either the whole
  1837. parameter or each individual element can be None. Defaults to None.
  1838. pole_exact : bool or (bool, bool), optional
  1839. Data value exactness at the poles ``u=0`` and ``u=pi``. If True, the
  1840. value is considered to be the right function value, and it will be
  1841. fitted exactly. If False, the value will be considered to be a data
  1842. value just like the other data values. Defaults to False.
  1843. pole_flat : bool or (bool, bool), optional
  1844. For the poles at ``u=0`` and ``u=pi``, specify whether or not the
  1845. approximation has vanishing derivatives. Defaults to False.
  1846. See Also
  1847. --------
  1848. BivariateSpline :
  1849. a base class for bivariate splines.
  1850. UnivariateSpline :
  1851. a smooth univariate spline to fit a given set of data points.
  1852. SmoothBivariateSpline :
  1853. a smoothing bivariate spline through the given points
  1854. LSQBivariateSpline :
  1855. a bivariate spline using weighted least-squares fitting
  1856. SmoothSphereBivariateSpline :
  1857. a smoothing bivariate spline in spherical coordinates
  1858. LSQSphereBivariateSpline :
  1859. a bivariate spline in spherical coordinates using weighted
  1860. least-squares fitting
  1861. RectBivariateSpline :
  1862. a bivariate spline over a rectangular mesh.
  1863. bisplrep :
  1864. a function to find a bivariate B-spline representation of a surface
  1865. bisplev :
  1866. a function to evaluate a bivariate B-spline and its derivatives
  1867. Notes
  1868. -----
  1869. Currently, only the smoothing spline approximation (``iopt[0] = 0`` and
  1870. ``iopt[0] = 1`` in the FITPACK routine) is supported. The exact
  1871. least-squares spline approximation is not implemented yet.
  1872. When actually performing the interpolation, the requested `v` values must
  1873. lie within the same length 2pi interval that the original `v` values were
  1874. chosen from.
  1875. For more information, see the FITPACK_ site about this function.
  1876. .. _FITPACK: http://www.netlib.org/dierckx/spgrid.f
  1877. Examples
  1878. --------
  1879. Suppose we have global data on a coarse grid
  1880. >>> import numpy as np
  1881. >>> lats = np.linspace(10, 170, 9) * np.pi / 180.
  1882. >>> lons = np.linspace(0, 350, 18) * np.pi / 180.
  1883. >>> data = np.dot(np.atleast_2d(90. - np.linspace(-80., 80., 18)).T,
  1884. ... np.atleast_2d(180. - np.abs(np.linspace(0., 350., 9)))).T
  1885. We want to interpolate it to a global one-degree grid
  1886. >>> new_lats = np.linspace(1, 180, 180) * np.pi / 180
  1887. >>> new_lons = np.linspace(1, 360, 360) * np.pi / 180
  1888. >>> new_lats, new_lons = np.meshgrid(new_lats, new_lons)
  1889. We need to set up the interpolator object
  1890. >>> from scipy.interpolate import RectSphereBivariateSpline
  1891. >>> lut = RectSphereBivariateSpline(lats, lons, data)
  1892. Finally we interpolate the data. The `RectSphereBivariateSpline` object
  1893. only takes 1-D arrays as input, therefore we need to do some reshaping.
  1894. >>> data_interp = lut.ev(new_lats.ravel(),
  1895. ... new_lons.ravel()).reshape((360, 180)).T
  1896. Looking at the original and the interpolated data, one can see that the
  1897. interpolant reproduces the original data very well:
  1898. >>> import matplotlib.pyplot as plt
  1899. >>> fig = plt.figure()
  1900. >>> ax1 = fig.add_subplot(211)
  1901. >>> ax1.imshow(data, interpolation='nearest')
  1902. >>> ax2 = fig.add_subplot(212)
  1903. >>> ax2.imshow(data_interp, interpolation='nearest')
  1904. >>> plt.show()
  1905. Choosing the optimal value of ``s`` can be a delicate task. Recommended
  1906. values for ``s`` depend on the accuracy of the data values. If the user
  1907. has an idea of the statistical errors on the data, she can also find a
  1908. proper estimate for ``s``. By assuming that, if she specifies the
  1909. right ``s``, the interpolator will use a spline ``f(u,v)`` which exactly
  1910. reproduces the function underlying the data, she can evaluate
  1911. ``sum((r(i,j)-s(u(i),v(j)))**2)`` to find a good estimate for this ``s``.
  1912. For example, if she knows that the statistical errors on her
  1913. ``r(i,j)``-values are not greater than 0.1, she may expect that a good
  1914. ``s`` should have a value not larger than ``u.size * v.size * (0.1)**2``.
  1915. If nothing is known about the statistical error in ``r(i,j)``, ``s`` must
  1916. be determined by trial and error. The best is then to start with a very
  1917. large value of ``s`` (to determine the least-squares polynomial and the
  1918. corresponding upper bound ``fp0`` for ``s``) and then to progressively
  1919. decrease the value of ``s`` (say by a factor 10 in the beginning, i.e.
  1920. ``s = fp0 / 10, fp0 / 100, ...`` and more carefully as the approximation
  1921. shows more detail) to obtain closer fits.
  1922. The interpolation results for different values of ``s`` give some insight
  1923. into this process:
  1924. >>> fig2 = plt.figure()
  1925. >>> s = [3e9, 2e9, 1e9, 1e8]
  1926. >>> for idx, sval in enumerate(s, 1):
  1927. ... lut = RectSphereBivariateSpline(lats, lons, data, s=sval)
  1928. ... data_interp = lut.ev(new_lats.ravel(),
  1929. ... new_lons.ravel()).reshape((360, 180)).T
  1930. ... ax = fig2.add_subplot(2, 2, idx)
  1931. ... ax.imshow(data_interp, interpolation='nearest')
  1932. ... ax.set_title(f"s = {sval:g}")
  1933. >>> plt.show()
  1934. """
  1935. def __init__(self, u, v, r, s=0., pole_continuity=False, pole_values=None,
  1936. pole_exact=False, pole_flat=False):
  1937. iopt = np.array([0, 0, 0], dtype=dfitpack_int)
  1938. ider = np.array([-1, 0, -1, 0], dtype=dfitpack_int)
  1939. if pole_values is None:
  1940. pole_values = (None, None)
  1941. elif isinstance(pole_values, float | np.float32 | np.float64):
  1942. pole_values = (pole_values, pole_values)
  1943. if isinstance(pole_continuity, bool):
  1944. pole_continuity = (pole_continuity, pole_continuity)
  1945. if isinstance(pole_exact, bool):
  1946. pole_exact = (pole_exact, pole_exact)
  1947. if isinstance(pole_flat, bool):
  1948. pole_flat = (pole_flat, pole_flat)
  1949. r0, r1 = pole_values
  1950. iopt[1:] = pole_continuity
  1951. if r0 is None:
  1952. ider[0] = -1
  1953. else:
  1954. ider[0] = pole_exact[0]
  1955. if r1 is None:
  1956. ider[2] = -1
  1957. else:
  1958. ider[2] = pole_exact[1]
  1959. ider[1], ider[3] = pole_flat
  1960. u, v = np.ravel(u), np.ravel(v)
  1961. r = np.asarray(r)
  1962. if not (0.0 < u[0] and u[-1] < np.pi):
  1963. raise ValueError('u should be between (0, pi)')
  1964. if not -np.pi <= v[0] < np.pi:
  1965. raise ValueError('v[0] should be between [-pi, pi)')
  1966. if not v[-1] <= v[0] + 2*np.pi:
  1967. raise ValueError('v[-1] should be v[0] + 2pi or less ')
  1968. if not np.all(np.diff(u) > 0.0):
  1969. raise ValueError('u must be strictly increasing')
  1970. if not np.all(np.diff(v) > 0.0):
  1971. raise ValueError('v must be strictly increasing')
  1972. if not u.size == r.shape[0]:
  1973. raise ValueError('u dimension of r must have same number of '
  1974. 'elements as u')
  1975. if not v.size == r.shape[1]:
  1976. raise ValueError('v dimension of r must have same number of '
  1977. 'elements as v')
  1978. if pole_continuity[1] is False and pole_flat[1] is True:
  1979. raise ValueError('if pole_continuity is False, so must be '
  1980. 'pole_flat')
  1981. if pole_continuity[0] is False and pole_flat[0] is True:
  1982. raise ValueError('if pole_continuity is False, so must be '
  1983. 'pole_flat')
  1984. if not s >= 0.0:
  1985. raise ValueError('s should be positive')
  1986. r = np.ravel(r)
  1987. with FITPACK_LOCK:
  1988. nu, tu, nv, tv, c, fp, ier = dfitpack.regrid_smth_spher(iopt, ider,
  1989. u.copy(),
  1990. v.copy(),
  1991. r.copy(),
  1992. r0, r1, s)
  1993. if ier not in [0, -1, -2]:
  1994. msg = _spfit_messages.get(ier, f'ier={ier}')
  1995. raise ValueError(msg)
  1996. self.fp = fp
  1997. self.tck = tu[:nu], tv[:nv], c[:(nu - 4) * (nv-4)]
  1998. self.degrees = (3, 3)
  1999. self.v0 = v[0]
  2000. def __call__(self, theta, phi, dtheta=0, dphi=0, grid=True):
  2001. theta = np.asarray(theta)
  2002. phi = np.asarray(phi)
  2003. return SphereBivariateSpline.__call__(self, theta, phi, dtheta=dtheta,
  2004. dphi=dphi, grid=grid)