Coverage for /usr/lib/python3/dist-packages/scipy/interpolate/_fitpack_py.py: 22%
63 statements
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
« prev ^ index » next coverage.py v7.9.1, created at 2025-06-14 15:55 +0200
1__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde',
2 'bisplrep', 'bisplev', 'insert', 'splder', 'splantider']
5import numpy as np
7# These are in the API for fitpack even if not used in fitpack.py itself.
8from ._fitpack_impl import bisplrep, bisplev, dblint # noqa: F401
9from . import _fitpack_impl as _impl
10from ._bsplines import BSpline
13def splprep(x, w=None, u=None, ub=None, ue=None, k=3, task=0, s=None, t=None,
14 full_output=0, nest=None, per=0, quiet=1):
15 """
16 Find the B-spline representation of an N-D curve.
18 Given a list of N rank-1 arrays, `x`, which represent a curve in
19 N-dimensional space parametrized by `u`, find a smooth approximating
20 spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK.
22 Parameters
23 ----------
24 x : array_like
25 A list of sample vector arrays representing the curve.
26 w : array_like, optional
27 Strictly positive rank-1 array of weights the same length as `x[0]`.
28 The weights are used in computing the weighted least-squares spline
29 fit. If the errors in the `x` values have standard-deviation given by
30 the vector d, then `w` should be 1/d. Default is ``ones(len(x[0]))``.
31 u : array_like, optional
32 An array of parameter values. If not given, these values are
33 calculated automatically as ``M = len(x[0])``, where
35 v[0] = 0
37 v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`)
39 u[i] = v[i] / v[M-1]
41 ub, ue : int, optional
42 The end-points of the parameters interval. Defaults to
43 u[0] and u[-1].
44 k : int, optional
45 Degree of the spline. Cubic splines are recommended.
46 Even values of `k` should be avoided especially with a small s-value.
47 ``1 <= k <= 5``, default is 3.
48 task : int, optional
49 If task==0 (default), find t and c for a given smoothing factor, s.
50 If task==1, find t and c for another value of the smoothing factor, s.
51 There must have been a previous call with task=0 or task=1
52 for the same set of data.
53 If task=-1 find the weighted least square spline for a given set of
54 knots, t.
55 s : float, optional
56 A smoothing condition. The amount of smoothness is determined by
57 satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s``,
58 where g(x) is the smoothed interpolation of (x,y). The user can
59 use `s` to control the trade-off between closeness and smoothness
60 of fit. Larger `s` means more smoothing while smaller values of `s`
61 indicate less smoothing. Recommended values of `s` depend on the
62 weights, w. If the weights represent the inverse of the
63 standard-deviation of y, then a good `s` value should be found in
64 the range ``(m-sqrt(2*m),m+sqrt(2*m))``, where m is the number of
65 data points in x, y, and w.
66 t : array, optional
67 The knots needed for ``task=-1``.
68 There must be at least ``2*k+2`` knots.
69 full_output : int, optional
70 If non-zero, then return optional outputs.
71 nest : int, optional
72 An over-estimate of the total number of knots of the spline to
73 help in determining the storage space. By default nest=m/2.
74 Always large enough is nest=m+k+1.
75 per : int, optional
76 If non-zero, data points are considered periodic with period
77 ``x[m-1] - x[0]`` and a smooth periodic spline approximation is
78 returned. Values of ``y[m-1]`` and ``w[m-1]`` are not used.
79 quiet : int, optional
80 Non-zero to suppress messages.
82 Returns
83 -------
84 tck : tuple
85 A tuple, ``(t,c,k)`` containing the vector of knots, the B-spline
86 coefficients, and the degree of the spline.
87 u : array
88 An array of the values of the parameter.
89 fp : float
90 The weighted sum of squared residuals of the spline approximation.
91 ier : int
92 An integer flag about splrep success. Success is indicated
93 if ier<=0. If ier in [1,2,3] an error occurred but was not raised.
94 Otherwise an error is raised.
95 msg : str
96 A message corresponding to the integer flag, ier.
98 See Also
99 --------
100 splrep, splev, sproot, spalde, splint,
101 bisplrep, bisplev
102 UnivariateSpline, BivariateSpline
103 BSpline
104 make_interp_spline
106 Notes
107 -----
108 See `splev` for evaluation of the spline and its derivatives.
109 The number of dimensions N must be smaller than 11.
111 The number of coefficients in the `c` array is ``k+1`` less than the number
112 of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads
113 the array of coefficients to have the same length as the array of knots.
114 These additional coefficients are ignored by evaluation routines, `splev`
115 and `BSpline`.
117 References
118 ----------
119 .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and
120 parametric splines, Computer Graphics and Image Processing",
121 20 (1982) 171-184.
122 .. [2] P. Dierckx, "Algorithms for smoothing data with periodic and
123 parametric splines", report tw55, Dept. Computer Science,
124 K.U.Leuven, 1981.
125 .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on
126 Numerical Analysis, Oxford University Press, 1993.
128 Examples
129 --------
130 Generate a discretization of a limacon curve in the polar coordinates:
132 >>> import numpy as np
133 >>> phi = np.linspace(0, 2.*np.pi, 40)
134 >>> r = 0.5 + np.cos(phi) # polar coords
135 >>> x, y = r * np.cos(phi), r * np.sin(phi) # convert to cartesian
137 And interpolate:
139 >>> from scipy.interpolate import splprep, splev
140 >>> tck, u = splprep([x, y], s=0)
141 >>> new_points = splev(u, tck)
143 Notice that (i) we force interpolation by using `s=0`,
144 (ii) the parameterization, ``u``, is generated automatically.
145 Now plot the result:
147 >>> import matplotlib.pyplot as plt
148 >>> fig, ax = plt.subplots()
149 >>> ax.plot(x, y, 'ro')
150 >>> ax.plot(new_points[0], new_points[1], 'r-')
151 >>> plt.show()
153 """
155 res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per,
156 quiet)
157 return res
160def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None,
161 full_output=0, per=0, quiet=1):
162 """
163 Find the B-spline representation of a 1-D curve.
165 Given the set of data points ``(x[i], y[i])`` determine a smooth spline
166 approximation of degree k on the interval ``xb <= x <= xe``.
168 Parameters
169 ----------
170 x, y : array_like
171 The data points defining a curve y = f(x).
172 w : array_like, optional
173 Strictly positive rank-1 array of weights the same length as x and y.
174 The weights are used in computing the weighted least-squares spline
175 fit. If the errors in the y values have standard-deviation given by the
176 vector d, then w should be 1/d. Default is ones(len(x)).
177 xb, xe : float, optional
178 The interval to fit. If None, these default to x[0] and x[-1]
179 respectively.
180 k : int, optional
181 The degree of the spline fit. It is recommended to use cubic splines.
182 Even values of k should be avoided especially with small s values.
183 1 <= k <= 5
184 task : {1, 0, -1}, optional
185 If task==0 find t and c for a given smoothing factor, s.
187 If task==1 find t and c for another value of the smoothing factor, s.
188 There must have been a previous call with task=0 or task=1 for the same
189 set of data (t will be stored an used internally)
191 If task=-1 find the weighted least square spline for a given set of
192 knots, t. These should be interior knots as knots on the ends will be
193 added automatically.
194 s : float, optional
195 A smoothing condition. The amount of smoothness is determined by
196 satisfying the conditions: ``sum((w * (y - g))**2,axis=0) <= s`` where g(x)
197 is the smoothed interpolation of (x,y). The user can use s to control
198 the tradeoff between closeness and smoothness of fit. Larger s means
199 more smoothing while smaller values of s indicate less smoothing.
200 Recommended values of s depend on the weights, w. If the weights
201 represent the inverse of the standard-deviation of y, then a good s
202 value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is
203 the number of datapoints in x, y, and w. default : s=m-sqrt(2*m) if
204 weights are supplied. s = 0.0 (interpolating) if no weights are
205 supplied.
206 t : array_like, optional
207 The knots needed for task=-1. If given then task is automatically set
208 to -1.
209 full_output : bool, optional
210 If non-zero, then return optional outputs.
211 per : bool, optional
212 If non-zero, data points are considered periodic with period x[m-1] -
213 x[0] and a smooth periodic spline approximation is returned. Values of
214 y[m-1] and w[m-1] are not used.
215 quiet : bool, optional
216 Non-zero to suppress messages.
218 Returns
219 -------
220 tck : tuple
221 A tuple (t,c,k) containing the vector of knots, the B-spline
222 coefficients, and the degree of the spline.
223 fp : array, optional
224 The weighted sum of squared residuals of the spline approximation.
225 ier : int, optional
226 An integer flag about splrep success. Success is indicated if ier<=0.
227 If ier in [1,2,3] an error occurred but was not raised. Otherwise an
228 error is raised.
229 msg : str, optional
230 A message corresponding to the integer flag, ier.
232 See Also
233 --------
234 UnivariateSpline, BivariateSpline
235 splprep, splev, sproot, spalde, splint
236 bisplrep, bisplev
237 BSpline
238 make_interp_spline
240 Notes
241 -----
242 See `splev` for evaluation of the spline and its derivatives. Uses the
243 FORTRAN routine ``curfit`` from FITPACK.
245 The user is responsible for assuring that the values of `x` are unique.
246 Otherwise, `splrep` will not return sensible results.
248 If provided, knots `t` must satisfy the Schoenberg-Whitney conditions,
249 i.e., there must be a subset of data points ``x[j]`` such that
250 ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``.
252 This routine zero-pads the coefficients array ``c`` to have the same length
253 as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored
254 by the evaluation routines, `splev` and `BSpline`.) This is in contrast with
255 `splprep`, which does not zero-pad the coefficients.
257 References
258 ----------
259 Based on algorithms described in [1]_, [2]_, [3]_, and [4]_:
261 .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and
262 integration of experimental data using spline functions",
263 J.Comp.Appl.Maths 1 (1975) 165-184.
264 .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular
265 grid while using spline functions", SIAM J.Numer.Anal. 19 (1982)
266 1286-1304.
267 .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline
268 functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981.
269 .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on
270 Numerical Analysis, Oxford University Press, 1993.
272 Examples
273 --------
274 You can interpolate 1-D points with a B-spline curve.
275 Further examples are given in
276 :ref:`in the tutorial <tutorial-interpolate_splXXX>`.
278 >>> import numpy as np
279 >>> import matplotlib.pyplot as plt
280 >>> from scipy.interpolate import splev, splrep
281 >>> x = np.linspace(0, 10, 10)
282 >>> y = np.sin(x)
283 >>> spl = splrep(x, y)
284 >>> x2 = np.linspace(0, 10, 200)
285 >>> y2 = splev(x2, spl)
286 >>> plt.plot(x, y, 'o', x2, y2)
287 >>> plt.show()
289 """
290 res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet)
291 return res
294def splev(x, tck, der=0, ext=0):
295 """
296 Evaluate a B-spline or its derivatives.
298 Given the knots and coefficients of a B-spline representation, evaluate
299 the value of the smoothing polynomial and its derivatives. This is a
300 wrapper around the FORTRAN routines splev and splder of FITPACK.
302 Parameters
303 ----------
304 x : array_like
305 An array of points at which to return the value of the smoothed
306 spline or its derivatives. If `tck` was returned from `splprep`,
307 then the parameter values, u should be given.
308 tck : 3-tuple or a BSpline object
309 If a tuple, then it should be a sequence of length 3 returned by
310 `splrep` or `splprep` containing the knots, coefficients, and degree
311 of the spline. (Also see Notes.)
312 der : int, optional
313 The order of derivative of the spline to compute (must be less than
314 or equal to k, the degree of the spline).
315 ext : int, optional
316 Controls the value returned for elements of ``x`` not in the
317 interval defined by the knot sequence.
319 * if ext=0, return the extrapolated value.
320 * if ext=1, return 0
321 * if ext=2, raise a ValueError
322 * if ext=3, return the boundary value.
324 The default value is 0.
326 Returns
327 -------
328 y : ndarray or list of ndarrays
329 An array of values representing the spline function evaluated at
330 the points in `x`. If `tck` was returned from `splprep`, then this
331 is a list of arrays representing the curve in an N-D space.
333 See Also
334 --------
335 splprep, splrep, sproot, spalde, splint
336 bisplrep, bisplev
337 BSpline
339 Notes
340 -----
341 Manipulating the tck-tuples directly is not recommended. In new code,
342 prefer using `BSpline` objects.
344 References
345 ----------
346 .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
347 Theory, 6, p.50-62, 1972.
348 .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
349 Applics, 10, p.134-149, 1972.
350 .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
351 on Numerical Analysis, Oxford University Press, 1993.
353 Examples
354 --------
355 Examples are given :ref:`in the tutorial <tutorial-interpolate_splXXX>`.
357 """
358 if isinstance(tck, BSpline):
359 if tck.c.ndim > 1:
360 mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is "
361 "not allowed. Use BSpline.__call__(x) instead.")
362 raise ValueError(mesg)
364 # remap the out-of-bounds behavior
365 try:
366 extrapolate = {0: True, }[ext]
367 except KeyError as e:
368 raise ValueError("Extrapolation mode %s is not supported "
369 "by BSpline." % ext) from e
371 return tck(x, der, extrapolate=extrapolate)
372 else:
373 return _impl.splev(x, tck, der, ext)
376def splint(a, b, tck, full_output=0):
377 """
378 Evaluate the definite integral of a B-spline between two given points.
380 Parameters
381 ----------
382 a, b : float
383 The end-points of the integration interval.
384 tck : tuple or a BSpline instance
385 If a tuple, then it should be a sequence of length 3, containing the
386 vector of knots, the B-spline coefficients, and the degree of the
387 spline (see `splev`).
388 full_output : int, optional
389 Non-zero to return optional output.
391 Returns
392 -------
393 integral : float
394 The resulting integral.
395 wrk : ndarray
396 An array containing the integrals of the normalized B-splines
397 defined on the set of knots.
398 (Only returned if `full_output` is non-zero)
400 See Also
401 --------
402 splprep, splrep, sproot, spalde, splev
403 bisplrep, bisplev
404 BSpline
406 Notes
407 -----
408 `splint` silently assumes that the spline function is zero outside the data
409 interval (`a`, `b`).
411 Manipulating the tck-tuples directly is not recommended. In new code,
412 prefer using the `BSpline` objects.
414 References
415 ----------
416 .. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines",
417 J. Inst. Maths Applics, 17, p.37-41, 1976.
418 .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs
419 on Numerical Analysis, Oxford University Press, 1993.
421 Examples
422 --------
423 Examples are given :ref:`in the tutorial <tutorial-interpolate_splXXX>`.
425 """
426 if isinstance(tck, BSpline):
427 if tck.c.ndim > 1:
428 mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is "
429 "not allowed. Use BSpline.integrate() instead.")
430 raise ValueError(mesg)
432 if full_output != 0:
433 mesg = ("full_output = %s is not supported. Proceeding as if "
434 "full_output = 0" % full_output)
436 return tck.integrate(a, b, extrapolate=False)
437 else:
438 return _impl.splint(a, b, tck, full_output)
441def sproot(tck, mest=10):
442 """
443 Find the roots of a cubic B-spline.
445 Given the knots (>=8) and coefficients of a cubic B-spline return the
446 roots of the spline.
448 Parameters
449 ----------
450 tck : tuple or a BSpline object
451 If a tuple, then it should be a sequence of length 3, containing the
452 vector of knots, the B-spline coefficients, and the degree of the
453 spline.
454 The number of knots must be >= 8, and the degree must be 3.
455 The knots must be a montonically increasing sequence.
456 mest : int, optional
457 An estimate of the number of zeros (Default is 10).
459 Returns
460 -------
461 zeros : ndarray
462 An array giving the roots of the spline.
464 See Also
465 --------
466 splprep, splrep, splint, spalde, splev
467 bisplrep, bisplev
468 BSpline
470 Notes
471 -----
472 Manipulating the tck-tuples directly is not recommended. In new code,
473 prefer using the `BSpline` objects.
475 References
476 ----------
477 .. [1] C. de Boor, "On calculating with b-splines", J. Approximation
478 Theory, 6, p.50-62, 1972.
479 .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths
480 Applics, 10, p.134-149, 1972.
481 .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs
482 on Numerical Analysis, Oxford University Press, 1993.
484 Examples
485 --------
487 For some data, this method may miss a root. This happens when one of
488 the spline knots (which FITPACK places automatically) happens to
489 coincide with the true root. A workaround is to convert to `PPoly`,
490 which uses a different root-finding algorithm.
492 For example,
494 >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05]
495 >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03,
496 ... 4.440892e-16, 1.616930e-03, 3.243000e-03, 4.877670e-03,
497 ... 6.520430e-03, 8.170770e-03]
498 >>> from scipy.interpolate import splrep, sproot, PPoly
499 >>> tck = splrep(x, y, s=0)
500 >>> sproot(tck)
501 array([], dtype=float64)
503 Converting to a PPoly object does find the roots at `x=2`:
505 >>> ppoly = PPoly.from_spline(tck)
506 >>> ppoly.roots(extrapolate=False)
507 array([2.])
510 Further examples are given :ref:`in the tutorial
511 <tutorial-interpolate_splXXX>`.
513 """
514 if isinstance(tck, BSpline):
515 if tck.c.ndim > 1:
516 mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is "
517 "not allowed.")
518 raise ValueError(mesg)
520 t, c, k = tck.tck
522 # _impl.sproot expects the interpolation axis to be last, so roll it.
523 # NB: This transpose is a no-op if c is 1D.
524 sh = tuple(range(c.ndim))
525 c = c.transpose(sh[1:] + (0,))
526 return _impl.sproot((t, c, k), mest)
527 else:
528 return _impl.sproot(tck, mest)
531def spalde(x, tck):
532 """
533 Evaluate all derivatives of a B-spline.
535 Given the knots and coefficients of a cubic B-spline compute all
536 derivatives up to order k at a point (or set of points).
538 Parameters
539 ----------
540 x : array_like
541 A point or a set of points at which to evaluate the derivatives.
542 Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`.
543 tck : tuple
544 A tuple (t,c,k) containing the vector of knots,
545 the B-spline coefficients, and the degree of the spline.
547 Returns
548 -------
549 results : {ndarray, list of ndarrays}
550 An array (or a list of arrays) containing all derivatives
551 up to order k inclusive for each point `x`.
553 See Also
554 --------
555 splprep, splrep, splint, sproot, splev, bisplrep, bisplev,
556 UnivariateSpline, BivariateSpline
558 References
559 ----------
560 .. [1] de Boor C : On calculating with b-splines, J. Approximation Theory
561 6 (1972) 50-62.
562 .. [2] Cox M.G. : The numerical evaluation of b-splines, J. Inst. Maths
563 applics 10 (1972) 134-149.
564 .. [3] Dierckx P. : Curve and surface fitting with splines, Monographs on
565 Numerical Analysis, Oxford University Press, 1993.
567 """
568 if isinstance(tck, BSpline):
569 raise TypeError("spalde does not accept BSpline instances.")
570 else:
571 return _impl.spalde(x, tck)
574def insert(x, tck, m=1, per=0):
575 """
576 Insert knots into a B-spline.
578 Given the knots and coefficients of a B-spline representation, create a
579 new B-spline with a knot inserted `m` times at point `x`.
580 This is a wrapper around the FORTRAN routine insert of FITPACK.
582 Parameters
583 ----------
584 x (u) : array_like
585 A 1-D point at which to insert a new knot(s). If `tck` was returned
586 from ``splprep``, then the parameter values, u should be given.
587 tck : a `BSpline` instance or a tuple
588 If tuple, then it is expected to be a tuple (t,c,k) containing
589 the vector of knots, the B-spline coefficients, and the degree of
590 the spline.
591 m : int, optional
592 The number of times to insert the given knot (its multiplicity).
593 Default is 1.
594 per : int, optional
595 If non-zero, the input spline is considered periodic.
597 Returns
598 -------
599 BSpline instance or a tuple
600 A new B-spline with knots t, coefficients c, and degree k.
601 ``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline.
602 In case of a periodic spline (``per != 0``) there must be
603 either at least k interior knots t(j) satisfying ``t(k+1)<t(j)<=x``
604 or at least k interior knots t(j) satisfying ``x<=t(j)<t(n-k)``.
605 A tuple is returned iff the input argument `tck` is a tuple, otherwise
606 a BSpline object is constructed and returned.
608 Notes
609 -----
610 Based on algorithms from [1]_ and [2]_.
612 Manipulating the tck-tuples directly is not recommended. In new code,
613 prefer using the `BSpline` objects.
615 References
616 ----------
617 .. [1] W. Boehm, "Inserting new knots into b-spline curves.",
618 Computer Aided Design, 12, p.199-201, 1980.
619 .. [2] P. Dierckx, "Curve and surface fitting with splines, Monographs on
620 Numerical Analysis", Oxford University Press, 1993.
622 Examples
623 --------
624 You can insert knots into a B-spline.
626 >>> from scipy.interpolate import splrep, insert
627 >>> import numpy as np
628 >>> x = np.linspace(0, 10, 5)
629 >>> y = np.sin(x)
630 >>> tck = splrep(x, y)
631 >>> tck[0]
632 array([ 0., 0., 0., 0., 5., 10., 10., 10., 10.])
634 A knot is inserted:
636 >>> tck_inserted = insert(3, tck)
637 >>> tck_inserted[0]
638 array([ 0., 0., 0., 0., 3., 5., 10., 10., 10., 10.])
640 Some knots are inserted:
642 >>> tck_inserted2 = insert(8, tck, m=3)
643 >>> tck_inserted2[0]
644 array([ 0., 0., 0., 0., 5., 8., 8., 8., 10., 10., 10., 10.])
646 """
647 if isinstance(tck, BSpline):
649 t, c, k = tck.tck
651 # FITPACK expects the interpolation axis to be last, so roll it over
652 # NB: if c array is 1D, transposes are no-ops
653 sh = tuple(range(c.ndim))
654 c = c.transpose(sh[1:] + (0,))
655 t_, c_, k_ = _impl.insert(x, (t, c, k), m, per)
657 # and roll the last axis back
658 c_ = np.asarray(c_)
659 c_ = c_.transpose((sh[-1],) + sh[:-1])
660 return BSpline(t_, c_, k_)
661 else:
662 return _impl.insert(x, tck, m, per)
665def splder(tck, n=1):
666 """
667 Compute the spline representation of the derivative of a given spline
669 Parameters
670 ----------
671 tck : BSpline instance or a tuple of (t, c, k)
672 Spline whose derivative to compute
673 n : int, optional
674 Order of derivative to evaluate. Default: 1
676 Returns
677 -------
678 `BSpline` instance or tuple
679 Spline of order k2=k-n representing the derivative
680 of the input spline.
681 A tuple is returned iff the input argument `tck` is a tuple, otherwise
682 a BSpline object is constructed and returned.
684 See Also
685 --------
686 splantider, splev, spalde
687 BSpline
689 Notes
690 -----
692 .. versionadded:: 0.13.0
694 Examples
695 --------
696 This can be used for finding maxima of a curve:
698 >>> from scipy.interpolate import splrep, splder, sproot
699 >>> import numpy as np
700 >>> x = np.linspace(0, 10, 70)
701 >>> y = np.sin(x)
702 >>> spl = splrep(x, y, k=4)
704 Now, differentiate the spline and find the zeros of the
705 derivative. (NB: `sproot` only works for order 3 splines, so we
706 fit an order 4 spline):
708 >>> dspl = splder(spl)
709 >>> sproot(dspl) / np.pi
710 array([ 0.50000001, 1.5 , 2.49999998])
712 This agrees well with roots :math:`\\pi/2 + n\\pi` of
713 :math:`\\cos(x) = \\sin'(x)`.
715 """
716 if isinstance(tck, BSpline):
717 return tck.derivative(n)
718 else:
719 return _impl.splder(tck, n)
722def splantider(tck, n=1):
723 """
724 Compute the spline for the antiderivative (integral) of a given spline.
726 Parameters
727 ----------
728 tck : BSpline instance or a tuple of (t, c, k)
729 Spline whose antiderivative to compute
730 n : int, optional
731 Order of antiderivative to evaluate. Default: 1
733 Returns
734 -------
735 BSpline instance or a tuple of (t2, c2, k2)
736 Spline of order k2=k+n representing the antiderivative of the input
737 spline.
738 A tuple is returned iff the input argument `tck` is a tuple, otherwise
739 a BSpline object is constructed and returned.
741 See Also
742 --------
743 splder, splev, spalde
744 BSpline
746 Notes
747 -----
748 The `splder` function is the inverse operation of this function.
749 Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo
750 rounding error.
752 .. versionadded:: 0.13.0
754 Examples
755 --------
756 >>> from scipy.interpolate import splrep, splder, splantider, splev
757 >>> import numpy as np
758 >>> x = np.linspace(0, np.pi/2, 70)
759 >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2)
760 >>> spl = splrep(x, y)
762 The derivative is the inverse operation of the antiderivative,
763 although some floating point error accumulates:
765 >>> splev(1.7, spl), splev(1.7, splder(splantider(spl)))
766 (array(2.1565429877197317), array(2.1565429877201865))
768 Antiderivative can be used to evaluate definite integrals:
770 >>> ispl = splantider(spl)
771 >>> splev(np.pi/2, ispl) - splev(0, ispl)
772 2.2572053588768486
774 This is indeed an approximation to the complete elliptic integral
775 :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`:
777 >>> from scipy.special import ellipk
778 >>> ellipk(0.8)
779 2.2572053268208538
781 """
782 if isinstance(tck, BSpline):
783 return tck.antiderivative(n)
784 else:
785 return _impl.splantider(tck, n)