fitpack.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722
  1. from __future__ import print_function, division, absolute_import
  2. __all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
  3. 'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
  4. import warnings
  5. import numpy as np
  6. from ._fitpack_impl import bisplrep, bisplev, dblint
  7. from . import _fitpack_impl as _impl
  8. from ._bsplines import BSpline
  9. def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
  10. full_output=0, nest=None, per=0, quiet=1):
  11. """
  12. Find the B-spline representation of an N-dimensional curve.
  13. Given a list of N rank-1 arrays, `x`, which represent a curve in
  14. N-dimensional space parametrized by `u`, find a smooth approximating
  15. spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK.
  16. Parameters
  17. ----------
  18. x : array_like
  19. A list of sample vector arrays representing the curve.
  20. w : array_like, optional
  21. Strictly positive rank-1 array of weights the same length as `x[0]`.
  22. The weights are used in computing the weighted least-squares spline
  23. fit. If the errors in the `x` values have standard-deviation given by
  24. the vector d, then `w` should be 1/d. Default is ``ones(len(x[0]))``.
  25. u : array_like, optional
  26. An array of parameter values. If not given, these values are
  27. calculated automatically as ``M = len(x[0])``, where
  28. v[0] = 0
  29. v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`)
  30. u[i] = v[i] / v[M-1]
  31. ub, ue : int, optional
  32. The end-points of the parameters interval. Defaults to
  33. u[0] and u[-1].
  34. k : int, optional
  35. Degree of the spline. Cubic splines are recommended.
  36. Even values of `k` should be avoided especially with a small s-value.
  37. ``1 <= k <= 5``, default is 3.
  38. task : int, optional
  39. If task==0 (default), find t and c for a given smoothing factor, s.
  40. If task==1, find t and c for another value of the smoothing factor, s.
  41. There must have been a previous call with task=0 or task=1
  42. for the same set of data.
  43. If task=-1 find the weighted least square spline for a given set of
  44. knots, t.
  45. s : float, optional
  46. A smoothing condition. The amount of smoothness is determined by
  47. satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s``,
  48. where g(x) is the smoothed interpolation of (x,y). The user can
  49. use `s` to control the trade-off between closeness and smoothness
  50. of fit. Larger `s` means more smoothing while smaller values of `s`
  51. indicate less smoothing. Recommended values of `s` depend on the
  52. weights, w. If the weights represent the inverse of the
  53. standard-deviation of y, then a good `s` value should be found in
  54. the range ``(m-sqrt(2*m),m+sqrt(2*m))``, where m is the number of
  55. data points in x, y, and w.
  56. t : int, optional
  57. The knots needed for task=-1.
  58. full_output : int, optional
  59. If non-zero, then return optional outputs.
  60. nest : int, optional
  61. An over-estimate of the total number of knots of the spline to
  62. help in determining the storage space. By default nest=m/2.
  63. Always large enough is nest=m+k+1.
  64. per : int, optional
  65. If non-zero, data points are considered periodic with period
  66. ``x[m-1] - x[0]`` and a smooth periodic spline approximation is
  67. returned. Values of ``y[m-1]`` and ``w[m-1]`` are not used.
  68. quiet : int, optional
  69. Non-zero to suppress messages.
  70. This parameter is deprecated; use standard Python warning filters
  71. instead.
  72. Returns
  73. -------
  74. tck : tuple
  75. (t,c,k) a tuple containing the vector of knots, the B-spline
  76. coefficients, and the degree of the spline.
  77. u : array
  78. An array of the values of the parameter.
  79. fp : float
  80. The weighted sum of squared residuals of the spline approximation.
  81. ier : int
  82. An integer flag about splrep success. Success is indicated
  83. if ier<=0. If ier in [1,2,3] an error occurred but was not raised.
  84. Otherwise an error is raised.
  85. msg : str
  86. A message corresponding to the integer flag, ier.
  87. See Also
  88. --------
  89. splrep, splev, sproot, spalde, splint,
  90. bisplrep, bisplev
  91. UnivariateSpline, BivariateSpline
  92. BSpline
  93. make_interp_spline
  94. Notes
  95. -----
  96. See `splev` for evaluation of the spline and its derivatives.
  97. The number of dimensions N must be smaller than 11.
  98. The number of coefficients in the `c` array is ``k+1`` less then the number
  99. of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads
  100. the array of coefficients to have the same length as the array of knots.
  101. These additional coefficients are ignored by evaluation routines, `splev`
  102. and `BSpline`.
  103. References
  104. ----------
  105. .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
  106. parametric splines, Computer Graphics and Image Processing",
  107. 20 (1982) 171-184.
  108. .. [2] P. Dierckx, "Algorithms for smoothing data with periodic and
  109. parametric splines", report tw55, Dept. Computer Science,
  110. K.U.Leuven, 1981.
  111. .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on
  112. Numerical Analysis, Oxford University Press, 1993.
  113. Examples
  114. --------
  115. Generate a discretization of a limacon curve in the polar coordinates:
  116. >>> phi = np.linspace(0, 2.*np.pi, 40)
  117. >>> r = 0.5 + np.cos(phi) # polar coords
  118. >>> x, y = r * np.cos(phi), r * np.sin(phi) # convert to cartesian
  119. And interpolate:
  120. >>> from scipy.interpolate import splprep, splev
  121. >>> tck, u = splprep([x, y], s=0)
  122. >>> new_points = splev(u, tck)
  123. Notice that (i) we force interpolation by using `s=0`,
  124. (ii) the parameterization, ``u``, is generated automatically.
  125. Now plot the result:
  126. >>> import matplotlib.pyplot as plt
  127. >>> fig, ax = plt.subplots()
  128. >>> ax.plot(x, y, 'ro')
  129. >>> ax.plot(new_points[0], new_points[1], 'r-')
  130. >>> plt.show()
  131. """
  132. res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per,
  133. quiet)
  134. return res
  135. def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
  136. full_output=0, per=0, quiet=1):
  137. """
  138. Find the B-spline representation of 1-D curve.
  139. Given the set of data points ``(x[i], y[i])`` determine a smooth spline
  140. approximation of degree k on the interval ``xb <= x <= xe``.
  141. Parameters
  142. ----------
  143. x, y : array_like
  144. The data points defining a curve y = f(x).
  145. w : array_like, optional
  146. Strictly positive rank-1 array of weights the same length as x and y.
  147. The weights are used in computing the weighted least-squares spline
  148. fit. If the errors in the y values have standard-deviation given by the
  149. vector d, then w should be 1/d. Default is ones(len(x)).
  150. xb, xe : float, optional
  151. The interval to fit. If None, these default to x[0] and x[-1]
  152. respectively.
  153. k : int, optional
  154. The degree of the spline fit. It is recommended to use cubic splines.
  155. Even values of k should be avoided especially with small s values.
  156. 1 <= k <= 5
  157. task : {1, 0, -1}, optional
  158. If task==0 find t and c for a given smoothing factor, s.
  159. If task==1 find t and c for another value of the smoothing factor, s.
  160. There must have been a previous call with task=0 or task=1 for the same
  161. set of data (t will be stored an used internally)
  162. If task=-1 find the weighted least square spline for a given set of
  163. knots, t. These should be interior knots as knots on the ends will be
  164. added automatically.
  165. s : float, optional
  166. A smoothing condition. The amount of smoothness is determined by
  167. satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x)
  168. is the smoothed interpolation of (x,y). The user can use s to control
  169. the tradeoff between closeness and smoothness of fit. Larger s means
  170. more smoothing while smaller values of s indicate less smoothing.
  171. Recommended values of s depend on the weights, w. If the weights
  172. represent the inverse of the standard-deviation of y, then a good s
  173. value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is
  174. the number of datapoints in x, y, and w. default : s=m-sqrt(2*m) if
  175. weights are supplied. s = 0.0 (interpolating) if no weights are
  176. supplied.
  177. t : array_like, optional
  178. The knots needed for task=-1. If given then task is automatically set
  179. to -1.
  180. full_output : bool, optional
  181. If non-zero, then return optional outputs.
  182. per : bool, optional
  183. If non-zero, data points are considered periodic with period x[m-1] -
  184. x[0] and a smooth periodic spline approximation is returned. Values of
  185. y[m-1] and w[m-1] are not used.
  186. quiet : bool, optional
  187. Non-zero to suppress messages.
  188. This parameter is deprecated; use standard Python warning filters
  189. instead.
  190. Returns
  191. -------
  192. tck : tuple
  193. A tuple (t,c,k) containing the vector of knots, the B-spline
  194. coefficients, and the degree of the spline.
  195. fp : array, optional
  196. The weighted sum of squared residuals of the spline approximation.
  197. ier : int, optional
  198. An integer flag about splrep success. Success is indicated if ier<=0.
  199. If ier in [1,2,3] an error occurred but was not raised. Otherwise an
  200. error is raised.
  201. msg : str, optional
  202. A message corresponding to the integer flag, ier.
  203. See Also
  204. --------
  205. UnivariateSpline, BivariateSpline
  206. splprep, splev, sproot, spalde, splint
  207. bisplrep, bisplev
  208. BSpline
  209. make_interp_spline
  210. Notes
  211. -----
  212. See `splev` for evaluation of the spline and its derivatives. Uses the
  213. FORTRAN routine ``curfit`` from FITPACK.
  214. The user is responsible for assuring that the values of `x` are unique.
  215. Otherwise, `splrep` will not return sensible results.
  216. If provided, knots `t` must satisfy the Schoenberg-Whitney conditions,
  217. i.e., there must be a subset of data points ``x[j]`` such that
  218. ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
  219. This routine zero-pads the coefficients array ``c`` to have the same length
  220. as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored
  221. by the evaluation routines, `splev` and `BSpline`.) This is in contrast with
  222. `splprep`, which does not zero-pad the coefficients.
  223. References
  224. ----------
  225. Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
  226. .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
  227. integration of experimental data using spline functions",
  228. J.Comp.Appl.Maths 1 (1975) 165-184.
  229. .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
  230. grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
  231. 1286-1304.
  232. .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
  233. functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
  234. .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
  235. Numerical Analysis, Oxford University Press, 1993.
  236. Examples
  237. --------
  238. >>> import matplotlib.pyplot as plt
  239. >>> from scipy.interpolate import splev, splrep
  240. >>> x = np.linspace(0, 10, 10)
  241. >>> y = np.sin(x)
  242. >>> spl = splrep(x, y)
  243. >>> x2 = np.linspace(0, 10, 200)
  244. >>> y2 = splev(x2, spl)
  245. >>> plt.plot(x, y, 'o', x2, y2)
  246. >>> plt.show()
  247. """
  248. res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)
  249. return res
  250. def splev(x, tck, der=0, ext=0):
  251. """
  252. Evaluate a B-spline or its derivatives.
  253. Given the knots and coefficients of a B-spline representation, evaluate
  254. the value of the smoothing polynomial and its derivatives. This is a
  255. wrapper around the FORTRAN routines splev and splder of FITPACK.
  256. Parameters
  257. ----------
  258. x : array_like
  259. An array of points at which to return the value of the smoothed
  260. spline or its derivatives. If `tck` was returned from `splprep`,
  261. then the parameter values, u should be given.
  262. tck : 3-tuple or a BSpline object
  263. If a tuple, then it should be a sequence of length 3 returned by
  264. `splrep` or `splprep` containing the knots, coefficients, and degree
  265. of the spline. (Also see Notes.)
  266. der : int, optional
  267. The order of derivative of the spline to compute (must be less than
  268. or equal to k).
  269. ext : int, optional
  270. Controls the value returned for elements of ``x`` not in the
  271. interval defined by the knot sequence.
  272. * if ext=0, return the extrapolated value.
  273. * if ext=1, return 0
  274. * if ext=2, raise a ValueError
  275. * if ext=3, return the boundary value.
  276. The default value is 0.
  277. Returns
  278. -------
  279. y : ndarray or list of ndarrays
  280. An array of values representing the spline function evaluated at
  281. the points in `x`. If `tck` was returned from `splprep`, then this
  282. is a list of arrays representing the curve in N-dimensional space.
  283. Notes
  284. -----
  285. Manipulating the tck-tuples directly is not recommended. In new code,
  286. prefer using `BSpline` objects.
  287. See Also
  288. --------
  289. splprep, splrep, sproot, spalde, splint
  290. bisplrep, bisplev
  291. BSpline
  292. References
  293. ----------
  294. .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
  295. Theory, 6, p.50-62, 1972.
  296. .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
  297. Applics, 10, p.134-149, 1972.
  298. .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
  299. on Numerical Analysis, Oxford University Press, 1993.
  300. """
  301. if isinstance(tck, BSpline):
  302. if tck.c.ndim > 1:
  303. mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is "
  304. "not recommended. Use BSpline.__call__(x) instead.")
  305. warnings.warn(mesg, DeprecationWarning)
  306. # remap the out-of-bounds behavior
  307. try:
  308. extrapolate = {0: True, }[ext]
  309. except KeyError:
  310. raise ValueError("Extrapolation mode %s is not supported "
  311. "by BSpline." % ext)
  312. return tck(x, der, extrapolate=extrapolate)
  313. else:
  314. return _impl.splev(x, tck, der, ext)
  315. def splint(a, b, tck, full_output=0):
  316. """
  317. Evaluate the definite integral of a B-spline between two given points.
  318. Parameters
  319. ----------
  320. a, b : float
  321. The end-points of the integration interval.
  322. tck : tuple or a BSpline instance
  323. If a tuple, then it should be a sequence of length 3, containing the
  324. vector of knots, the B-spline coefficients, and the degree of the
  325. spline (see `splev`).
  326. full_output : int, optional
  327. Non-zero to return optional output.
  328. Returns
  329. -------
  330. integral : float
  331. The resulting integral.
  332. wrk : ndarray
  333. An array containing the integrals of the normalized B-splines
  334. defined on the set of knots.
  335. (Only returned if `full_output` is non-zero)
  336. Notes
  337. -----
  338. `splint` silently assumes that the spline function is zero outside the data
  339. interval (`a`, `b`).
  340. Manipulating the tck-tuples directly is not recommended. In new code,
  341. prefer using the `BSpline` objects.
  342. See Also
  343. --------
  344. splprep, splrep, sproot, spalde, splev
  345. bisplrep, bisplev
  346. BSpline
  347. References
  348. ----------
  349. .. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines",
  350. J. Inst. Maths Applics, 17, p.37-41, 1976.
  351. .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs
  352. on Numerical Analysis, Oxford University Press, 1993.
  353. """
  354. if isinstance(tck, BSpline):
  355. if tck.c.ndim > 1:
  356. mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is "
  357. "not recommended. Use BSpline.integrate() instead.")
  358. warnings.warn(mesg, DeprecationWarning)
  359. if full_output != 0:
  360. mesg = ("full_output = %s is not supported. Proceeding as if "
  361. "full_output = 0" % full_output)
  362. return tck.integrate(a, b, extrapolate=False)
  363. else:
  364. return _impl.splint(a, b, tck, full_output)
  365. def sproot(tck, mest=10):
  366. """
  367. Find the roots of a cubic B-spline.
  368. Given the knots (>=8) and coefficients of a cubic B-spline return the
  369. roots of the spline.
  370. Parameters
  371. ----------
  372. tck : tuple or a BSpline object
  373. If a tuple, then it should be a sequence of length 3, containing the
  374. vector of knots, the B-spline coefficients, and the degree of the
  375. spline.
  376. The number of knots must be >= 8, and the degree must be 3.
  377. The knots must be a montonically increasing sequence.
  378. mest : int, optional
  379. An estimate of the number of zeros (Default is 10).
  380. Returns
  381. -------
  382. zeros : ndarray
  383. An array giving the roots of the spline.
  384. Notes
  385. -----
  386. Manipulating the tck-tuples directly is not recommended. In new code,
  387. prefer using the `BSpline` objects.
  388. See also
  389. --------
  390. splprep, splrep, splint, spalde, splev
  391. bisplrep, bisplev
  392. BSpline
  393. References
  394. ----------
  395. .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
  396. Theory, 6, p.50-62, 1972.
  397. .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
  398. Applics, 10, p.134-149, 1972.
  399. .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
  400. on Numerical Analysis, Oxford University Press, 1993.
  401. """
  402. if isinstance(tck, BSpline):
  403. if tck.c.ndim > 1:
  404. mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is "
  405. "not recommended.")
  406. warnings.warn(mesg, DeprecationWarning)
  407. t, c, k = tck.tck
  408. # _impl.sproot expects the interpolation axis to be last, so roll it.
  409. # NB: This transpose is a no-op if c is 1D.
  410. sh = tuple(range(c.ndim))
  411. c = c.transpose(sh[1:] + (0,))
  412. return _impl.sproot((t, c, k), mest)
  413. else:
  414. return _impl.sproot(tck, mest)
  415. def spalde(x, tck):
  416. """
  417. Evaluate all derivatives of a B-spline.
  418. Given the knots and coefficients of a cubic B-spline compute all
  419. derivatives up to order k at a point (or set of points).
  420. Parameters
  421. ----------
  422. x : array_like
  423. A point or a set of points at which to evaluate the derivatives.
  424. Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`.
  425. tck : tuple
  426. A tuple ``(t, c, k)``, containing the vector of knots, the B-spline
  427. coefficients, and the degree of the spline (see `splev`).
  428. Returns
  429. -------
  430. results : {ndarray, list of ndarrays}
  431. An array (or a list of arrays) containing all derivatives
  432. up to order k inclusive for each point `x`.
  433. See Also
  434. --------
  435. splprep, splrep, splint, sproot, splev, bisplrep, bisplev,
  436. BSpline
  437. References
  438. ----------
  439. .. [1] C. de Boor: On calculating with b-splines, J. Approximation Theory
  440. 6 (1972) 50-62.
  441. .. [2] M. G. Cox : The numerical evaluation of b-splines, J. Inst. Maths
  442. applics 10 (1972) 134-149.
  443. .. [3] P. Dierckx : Curve and surface fitting with splines, Monographs on
  444. Numerical Analysis, Oxford University Press, 1993.
  445. """
  446. if isinstance(tck, BSpline):
  447. raise TypeError("spalde does not accept BSpline instances.")
  448. else:
  449. return _impl.spalde(x, tck)
  450. def insert(x, tck, m=1, per=0):
  451. """
  452. Insert knots into a B-spline.
  453. Given the knots and coefficients of a B-spline representation, create a
  454. new B-spline with a knot inserted `m` times at point `x`.
  455. This is a wrapper around the FORTRAN routine insert of FITPACK.
  456. Parameters
  457. ----------
  458. x (u) : array_like
  459. A 1-D point at which to insert a new knot(s). If `tck` was returned
  460. from ``splprep``, then the parameter values, u should be given.
  461. tck : a `BSpline` instance or a tuple
  462. If tuple, then it is expected to be a tuple (t,c,k) containing
  463. the vector of knots, the B-spline coefficients, and the degree of
  464. the spline.
  465. m : int, optional
  466. The number of times to insert the given knot (its multiplicity).
  467. Default is 1.
  468. per : int, optional
  469. If non-zero, the input spline is considered periodic.
  470. Returns
  471. -------
  472. BSpline instance or a tuple
  473. A new B-spline with knots t, coefficients c, and degree k.
  474. ``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline.
  475. In case of a periodic spline (``per != 0``) there must be
  476. either at least k interior knots t(j) satisfying ``t(k+1)<t(j)<=x``
  477. or at least k interior knots t(j) satisfying ``x<=t(j)<t(n-k)``.
  478. A tuple is returned iff the input argument `tck` is a tuple, otherwise
  479. a BSpline object is constructed and returned.
  480. Notes
  481. -----
  482. Based on algorithms from [1]_ and [2]_.
  483. Manipulating the tck-tuples directly is not recommended. In new code,
  484. prefer using the `BSpline` objects.
  485. References
  486. ----------
  487. .. [1] W. Boehm, "Inserting new knots into b-spline curves.",
  488. Computer Aided Design, 12, p.199-201, 1980.
  489. .. [2] P. Dierckx, "Curve and surface fitting with splines, Monographs on
  490. Numerical Analysis", Oxford University Press, 1993.
  491. """
  492. if isinstance(tck, BSpline):
  493. t, c, k = tck.tck
  494. # FITPACK expects the interpolation axis to be last, so roll it over
  495. # NB: if c array is 1D, transposes are no-ops
  496. sh = tuple(range(c.ndim))
  497. c = c.transpose(sh[1:] + (0,))
  498. t_, c_, k_ = _impl.insert(x, (t, c, k), m, per)
  499. # and roll the last axis back
  500. c_ = np.asarray(c_)
  501. c_ = c_.transpose((sh[-1],) + sh[:-1])
  502. return BSpline(t_, c_, k_)
  503. else:
  504. return _impl.insert(x, tck, m, per)
  505. def splder(tck, n=1):
  506. """
  507. Compute the spline representation of the derivative of a given spline
  508. Parameters
  509. ----------
  510. tck : BSpline instance or a tuple of (t, c, k)
  511. Spline whose derivative to compute
  512. n : int, optional
  513. Order of derivative to evaluate. Default: 1
  514. Returns
  515. -------
  516. `BSpline` instance or tuple
  517. Spline of order k2=k-n representing the derivative
  518. of the input spline.
  519. A tuple is returned iff the input argument `tck` is a tuple, otherwise
  520. a BSpline object is constructed and returned.
  521. Notes
  522. -----
  523. .. versionadded:: 0.13.0
  524. See Also
  525. --------
  526. splantider, splev, spalde
  527. BSpline
  528. Examples
  529. --------
  530. This can be used for finding maxima of a curve:
  531. >>> from scipy.interpolate import splrep, splder, sproot
  532. >>> x = np.linspace(0, 10, 70)
  533. >>> y = np.sin(x)
  534. >>> spl = splrep(x, y, k=4)
  535. Now, differentiate the spline and find the zeros of the
  536. derivative. (NB: `sproot` only works for order 3 splines, so we
  537. fit an order 4 spline):
  538. >>> dspl = splder(spl)
  539. >>> sproot(dspl) / np.pi
  540. array([ 0.50000001, 1.5 , 2.49999998])
  541. This agrees well with roots :math:`\\pi/2 + n\\pi` of
  542. :math:`\\cos(x) = \\sin'(x)`.
  543. """
  544. if isinstance(tck, BSpline):
  545. return tck.derivative(n)
  546. else:
  547. return _impl.splder(tck, n)
  548. def splantider(tck, n=1):
  549. """
  550. Compute the spline for the antiderivative (integral) of a given spline.
  551. Parameters
  552. ----------
  553. tck : BSpline instance or a tuple of (t, c, k)
  554. Spline whose antiderivative to compute
  555. n : int, optional
  556. Order of antiderivative to evaluate. Default: 1
  557. Returns
  558. -------
  559. BSpline instance or a tuple of (t2, c2, k2)
  560. Spline of order k2=k+n representing the antiderivative of the input
  561. spline.
  562. A tuple is returned iff the input argument `tck` is a tuple, otherwise
  563. a BSpline object is constructed and returned.
  564. See Also
  565. --------
  566. splder, splev, spalde
  567. BSpline
  568. Notes
  569. -----
  570. The `splder` function is the inverse operation of this function.
  571. Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo
  572. rounding error.
  573. .. versionadded:: 0.13.0
  574. Examples
  575. --------
  576. >>> from scipy.interpolate import splrep, splder, splantider, splev
  577. >>> x = np.linspace(0, np.pi/2, 70)
  578. >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
  579. >>> spl = splrep(x, y)
  580. The derivative is the inverse operation of the antiderivative,
  581. although some floating point error accumulates:
  582. >>> splev(1.7, spl), splev(1.7, splder(splantider(spl)))
  583. (array(2.1565429877197317), array(2.1565429877201865))
  584. Antiderivative can be used to evaluate definite integrals:
  585. >>> ispl = splantider(spl)
  586. >>> splev(np.pi/2, ispl) - splev(0, ispl)
  587. 2.2572053588768486
  588. This is indeed an approximation to the complete elliptic integral
  589. :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
  590. >>> from scipy.special import ellipk
  591. >>> ellipk(0.8)
  592. 2.2572053268208538
  593. """
  594. if isinstance(tck, BSpline):
  595. return tck.antiderivative(n)
  596. else:
  597. return _impl.splantider(tck, n)