_fitpack2.py 80 KB

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