Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/scipy/interpolate/_fitpack_py.py: 22%

63 statements  

« prev     ^ index     » next       coverage.py v7.3.2, created at 2023-12-12 06:31 +0000

1__all__ = ['splrep', 'splprep', 'splev', 'splint', 'sproot', 'spalde', 

2 'bisplrep', 'bisplev', 'insert', 'splder', 'splantider'] 

3 

4 

5import numpy as np 

6 

7# These are in the API for fitpack even if not used in fitpack.py itself. 

8from ._fitpack_impl import bisplrep, bisplev, dblint 

9from . import _fitpack_impl as _impl 

10from ._bsplines import BSpline 

11 

12 

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. 

17 

18 Given a list of N rank-1 arrays, `x`, which represent a curve in 

19 N-D space parametrized by `u`, find a smooth approximating 

20 spline curve g(`u`). Uses the FORTRAN routine parcur from FITPACK. 

21 

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 

34 

35 v[0] = 0 

36 

37 v[i] = v[i-1] + distance(`x[i]`, `x[i-1]`) 

38 

39 u[i] = v[i] / v[M-1] 

40 

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 : int, optional 

67 The knots needed for task=-1. 

68 full_output : int, optional 

69 If non-zero, then return optional outputs. 

70 nest : int, optional 

71 An over-estimate of the total number of knots of the spline to 

72 help in determining the storage space. By default nest=m/2. 

73 Always large enough is nest=m+k+1. 

74 per : int, optional 

75 If non-zero, data points are considered periodic with period 

76 ``x[m-1] - x[0]`` and a smooth periodic spline approximation is 

77 returned. Values of ``y[m-1]`` and ``w[m-1]`` are not used. 

78 quiet : int, optional 

79 Non-zero to suppress messages. 

80 

81 Returns 

82 ------- 

83 tck : tuple 

84 (t,c,k) a tuple containing the vector of knots, the B-spline 

85 coefficients, and the degree of the spline. 

86 u : array 

87 An array of the values of the parameter. 

88 fp : float 

89 The weighted sum of squared residuals of the spline approximation. 

90 ier : int 

91 An integer flag about splrep success. Success is indicated 

92 if ier<=0. If ier in [1,2,3] an error occurred but was not raised. 

93 Otherwise an error is raised. 

94 msg : str 

95 A message corresponding to the integer flag, ier. 

96 

97 See Also 

98 -------- 

99 splrep, splev, sproot, spalde, splint, 

100 bisplrep, bisplev 

101 UnivariateSpline, BivariateSpline 

102 BSpline 

103 make_interp_spline 

104 

105 Notes 

106 ----- 

107 See `splev` for evaluation of the spline and its derivatives. 

108 The number of dimensions N must be smaller than 11. 

109 

110 The number of coefficients in the `c` array is ``k+1`` less than the number 

111 of knots, ``len(t)``. This is in contrast with `splrep`, which zero-pads 

112 the array of coefficients to have the same length as the array of knots. 

113 These additional coefficients are ignored by evaluation routines, `splev` 

114 and `BSpline`. 

115 

116 References 

117 ---------- 

118 .. [1] P. Dierckx, "Algorithms for smoothing data with periodic and 

119 parametric splines, Computer Graphics and Image Processing", 

120 20 (1982) 171-184. 

121 .. [2] P. Dierckx, "Algorithms for smoothing data with periodic and 

122 parametric splines", report tw55, Dept. Computer Science, 

123 K.U.Leuven, 1981. 

124 .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs on 

125 Numerical Analysis, Oxford University Press, 1993. 

126 

127 Examples 

128 -------- 

129 Generate a discretization of a limacon curve in the polar coordinates: 

130 

131 >>> import numpy as np 

132 >>> phi = np.linspace(0, 2.*np.pi, 40) 

133 >>> r = 0.5 + np.cos(phi) # polar coords 

134 >>> x, y = r * np.cos(phi), r * np.sin(phi) # convert to cartesian 

135 

136 And interpolate: 

137 

138 >>> from scipy.interpolate import splprep, splev 

139 >>> tck, u = splprep([x, y], s=0) 

140 >>> new_points = splev(u, tck) 

141 

142 Notice that (i) we force interpolation by using `s=0`, 

143 (ii) the parameterization, ``u``, is generated automatically. 

144 Now plot the result: 

145 

146 >>> import matplotlib.pyplot as plt 

147 >>> fig, ax = plt.subplots() 

148 >>> ax.plot(x, y, 'ro') 

149 >>> ax.plot(new_points[0], new_points[1], 'r-') 

150 >>> plt.show() 

151 

152 """ 

153 res = _impl.splprep(x, w, u, ub, ue, k, task, s, t, full_output, nest, per, 

154 quiet) 

155 return res 

156 

157 

158def splrep(x, y, w=None, xb=None, xe=None, k=3, task=0, s=None, t=None, 

159 full_output=0, per=0, quiet=1): 

160 """ 

161 Find the B-spline representation of a 1-D curve. 

162 

163 Given the set of data points ``(x[i], y[i])`` determine a smooth spline 

164 approximation of degree k on the interval ``xb <= x <= xe``. 

165 

166 Parameters 

167 ---------- 

168 x, y : array_like 

169 The data points defining a curve y = f(x). 

170 w : array_like, optional 

171 Strictly positive rank-1 array of weights the same length as x and y. 

172 The weights are used in computing the weighted least-squares spline 

173 fit. If the errors in the y values have standard-deviation given by the 

174 vector d, then w should be 1/d. Default is ones(len(x)). 

175 xb, xe : float, optional 

176 The interval to fit. If None, these default to x[0] and x[-1] 

177 respectively. 

178 k : int, optional 

179 The degree of the spline fit. It is recommended to use cubic splines. 

180 Even values of k should be avoided especially with small s values. 

181 1 <= k <= 5 

182 task : {1, 0, -1}, optional 

183 If task==0 find t and c for a given smoothing factor, s. 

184 

185 If task==1 find t and c for another value of the smoothing factor, s. 

186 There must have been a previous call with task=0 or task=1 for the same 

187 set of data (t will be stored an used internally) 

188 

189 If task=-1 find the weighted least square spline for a given set of 

190 knots, t. These should be interior knots as knots on the ends will be 

191 added automatically. 

192 s : float, optional 

193 A smoothing condition. The amount of smoothness is determined by 

194 satisfying the conditions: sum((w * (y - g))**2,axis=0) <= s where g(x) 

195 is the smoothed interpolation of (x,y). The user can use s to control 

196 the tradeoff between closeness and smoothness of fit. Larger s means 

197 more smoothing while smaller values of s indicate less smoothing. 

198 Recommended values of s depend on the weights, w. If the weights 

199 represent the inverse of the standard-deviation of y, then a good s 

200 value should be found in the range (m-sqrt(2*m),m+sqrt(2*m)) where m is 

201 the number of datapoints in x, y, and w. default : s=m-sqrt(2*m) if 

202 weights are supplied. s = 0.0 (interpolating) if no weights are 

203 supplied. 

204 t : array_like, optional 

205 The knots needed for task=-1. If given then task is automatically set 

206 to -1. 

207 full_output : bool, optional 

208 If non-zero, then return optional outputs. 

209 per : bool, optional 

210 If non-zero, data points are considered periodic with period x[m-1] - 

211 x[0] and a smooth periodic spline approximation is returned. Values of 

212 y[m-1] and w[m-1] are not used. 

213 quiet : bool, optional 

214 Non-zero to suppress messages. 

215 

216 Returns 

217 ------- 

218 tck : tuple 

219 A tuple (t,c,k) containing the vector of knots, the B-spline 

220 coefficients, and the degree of the spline. 

221 fp : array, optional 

222 The weighted sum of squared residuals of the spline approximation. 

223 ier : int, optional 

224 An integer flag about splrep success. Success is indicated if ier<=0. 

225 If ier in [1,2,3] an error occurred but was not raised. Otherwise an 

226 error is raised. 

227 msg : str, optional 

228 A message corresponding to the integer flag, ier. 

229 

230 See Also 

231 -------- 

232 UnivariateSpline, BivariateSpline 

233 splprep, splev, sproot, spalde, splint 

234 bisplrep, bisplev 

235 BSpline 

236 make_interp_spline 

237 

238 Notes 

239 ----- 

240 See `splev` for evaluation of the spline and its derivatives. Uses the 

241 FORTRAN routine ``curfit`` from FITPACK. 

242 

243 The user is responsible for assuring that the values of `x` are unique. 

244 Otherwise, `splrep` will not return sensible results. 

245 

246 If provided, knots `t` must satisfy the Schoenberg-Whitney conditions, 

247 i.e., there must be a subset of data points ``x[j]`` such that 

248 ``t[j] < x[j] < t[j+k+1]``, for ``j=0, 1,...,n-k-2``. 

249 

250 This routine zero-pads the coefficients array ``c`` to have the same length 

251 as the array of knots ``t`` (the trailing ``k + 1`` coefficients are ignored 

252 by the evaluation routines, `splev` and `BSpline`.) This is in contrast with 

253 `splprep`, which does not zero-pad the coefficients. 

254 

255 References 

256 ---------- 

257 Based on algorithms described in [1]_, [2]_, [3]_, and [4]_: 

258 

259 .. [1] P. Dierckx, "An algorithm for smoothing, differentiation and 

260 integration of experimental data using spline functions", 

261 J.Comp.Appl.Maths 1 (1975) 165-184. 

262 .. [2] P. Dierckx, "A fast algorithm for smoothing data on a rectangular 

263 grid while using spline functions", SIAM J.Numer.Anal. 19 (1982) 

264 1286-1304. 

265 .. [3] P. Dierckx, "An improved algorithm for curve fitting with spline 

266 functions", report tw54, Dept. Computer Science,K.U. Leuven, 1981. 

267 .. [4] P. Dierckx, "Curve and surface fitting with splines", Monographs on 

268 Numerical Analysis, Oxford University Press, 1993. 

269 

270 Examples 

271 -------- 

272 You can interpolate 1-D points with a B-spline curve. 

273 Further examples are given in 

274 :ref:`in the tutorial <tutorial-interpolate_splXXX>`. 

275 

276 >>> import numpy as np 

277 >>> import matplotlib.pyplot as plt 

278 >>> from scipy.interpolate import splev, splrep 

279 >>> x = np.linspace(0, 10, 10) 

280 >>> y = np.sin(x) 

281 >>> spl = splrep(x, y) 

282 >>> x2 = np.linspace(0, 10, 200) 

283 >>> y2 = splev(x2, spl) 

284 >>> plt.plot(x, y, 'o', x2, y2) 

285 >>> plt.show() 

286 

287 """ 

288 res = _impl.splrep(x, y, w, xb, xe, k, task, s, t, full_output, per, quiet) 

289 return res 

290 

291 

292def splev(x, tck, der=0, ext=0): 

293 """ 

294 Evaluate a B-spline or its derivatives. 

295 

296 Given the knots and coefficients of a B-spline representation, evaluate 

297 the value of the smoothing polynomial and its derivatives. This is a 

298 wrapper around the FORTRAN routines splev and splder of FITPACK. 

299 

300 Parameters 

301 ---------- 

302 x : array_like 

303 An array of points at which to return the value of the smoothed 

304 spline or its derivatives. If `tck` was returned from `splprep`, 

305 then the parameter values, u should be given. 

306 tck : 3-tuple or a BSpline object 

307 If a tuple, then it should be a sequence of length 3 returned by 

308 `splrep` or `splprep` containing the knots, coefficients, and degree 

309 of the spline. (Also see Notes.) 

310 der : int, optional 

311 The order of derivative of the spline to compute (must be less than 

312 or equal to k, the degree of the spline). 

313 ext : int, optional 

314 Controls the value returned for elements of ``x`` not in the 

315 interval defined by the knot sequence. 

316 

317 * if ext=0, return the extrapolated value. 

318 * if ext=1, return 0 

319 * if ext=2, raise a ValueError 

320 * if ext=3, return the boundary value. 

321 

322 The default value is 0. 

323 

324 Returns 

325 ------- 

326 y : ndarray or list of ndarrays 

327 An array of values representing the spline function evaluated at 

328 the points in `x`. If `tck` was returned from `splprep`, then this 

329 is a list of arrays representing the curve in an N-D space. 

330 

331 Notes 

332 ----- 

333 Manipulating the tck-tuples directly is not recommended. In new code, 

334 prefer using `BSpline` objects. 

335 

336 See Also 

337 -------- 

338 splprep, splrep, sproot, spalde, splint 

339 bisplrep, bisplev 

340 BSpline 

341 

342 References 

343 ---------- 

344 .. [1] C. de Boor, "On calculating with b-splines", J. Approximation 

345 Theory, 6, p.50-62, 1972. 

346 .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths 

347 Applics, 10, p.134-149, 1972. 

348 .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs 

349 on Numerical Analysis, Oxford University Press, 1993. 

350 

351 Examples 

352 -------- 

353 Examples are given :ref:`in the tutorial <tutorial-interpolate_splXXX>`. 

354 

355 """ 

356 if isinstance(tck, BSpline): 

357 if tck.c.ndim > 1: 

358 mesg = ("Calling splev() with BSpline objects with c.ndim > 1 is " 

359 "not allowed. Use BSpline.__call__(x) instead.") 

360 raise ValueError(mesg) 

361 

362 # remap the out-of-bounds behavior 

363 try: 

364 extrapolate = {0: True, }[ext] 

365 except KeyError as e: 

366 raise ValueError("Extrapolation mode %s is not supported " 

367 "by BSpline." % ext) from e 

368 

369 return tck(x, der, extrapolate=extrapolate) 

370 else: 

371 return _impl.splev(x, tck, der, ext) 

372 

373 

374def splint(a, b, tck, full_output=0): 

375 """ 

376 Evaluate the definite integral of a B-spline between two given points. 

377 

378 Parameters 

379 ---------- 

380 a, b : float 

381 The end-points of the integration interval. 

382 tck : tuple or a BSpline instance 

383 If a tuple, then it should be a sequence of length 3, containing the 

384 vector of knots, the B-spline coefficients, and the degree of the 

385 spline (see `splev`). 

386 full_output : int, optional 

387 Non-zero to return optional output. 

388 

389 Returns 

390 ------- 

391 integral : float 

392 The resulting integral. 

393 wrk : ndarray 

394 An array containing the integrals of the normalized B-splines 

395 defined on the set of knots. 

396 (Only returned if `full_output` is non-zero) 

397 

398 Notes 

399 ----- 

400 `splint` silently assumes that the spline function is zero outside the data 

401 interval (`a`, `b`). 

402 

403 Manipulating the tck-tuples directly is not recommended. In new code, 

404 prefer using the `BSpline` objects. 

405 

406 See Also 

407 -------- 

408 splprep, splrep, sproot, spalde, splev 

409 bisplrep, bisplev 

410 BSpline 

411 

412 References 

413 ---------- 

414 .. [1] P.W. Gaffney, The calculation of indefinite integrals of b-splines", 

415 J. Inst. Maths Applics, 17, p.37-41, 1976. 

416 .. [2] P. Dierckx, "Curve and surface fitting with splines", Monographs 

417 on Numerical Analysis, Oxford University Press, 1993. 

418 

419 Examples 

420 -------- 

421 Examples are given :ref:`in the tutorial <tutorial-interpolate_splXXX>`. 

422 

423 """ 

424 if isinstance(tck, BSpline): 

425 if tck.c.ndim > 1: 

426 mesg = ("Calling splint() with BSpline objects with c.ndim > 1 is " 

427 "not allowed. Use BSpline.integrate() instead.") 

428 raise ValueError(mesg) 

429 

430 if full_output != 0: 

431 mesg = ("full_output = %s is not supported. Proceeding as if " 

432 "full_output = 0" % full_output) 

433 

434 return tck.integrate(a, b, extrapolate=False) 

435 else: 

436 return _impl.splint(a, b, tck, full_output) 

437 

438 

439def sproot(tck, mest=10): 

440 """ 

441 Find the roots of a cubic B-spline. 

442 

443 Given the knots (>=8) and coefficients of a cubic B-spline return the 

444 roots of the spline. 

445 

446 Parameters 

447 ---------- 

448 tck : tuple or a BSpline object 

449 If a tuple, then it should be a sequence of length 3, containing the 

450 vector of knots, the B-spline coefficients, and the degree of the 

451 spline. 

452 The number of knots must be >= 8, and the degree must be 3. 

453 The knots must be a montonically increasing sequence. 

454 mest : int, optional 

455 An estimate of the number of zeros (Default is 10). 

456 

457 Returns 

458 ------- 

459 zeros : ndarray 

460 An array giving the roots of the spline. 

461 

462 Notes 

463 ----- 

464 Manipulating the tck-tuples directly is not recommended. In new code, 

465 prefer using the `BSpline` objects. 

466 

467 See Also 

468 -------- 

469 splprep, splrep, splint, spalde, splev 

470 bisplrep, bisplev 

471 BSpline 

472 

473 

474 References 

475 ---------- 

476 .. [1] C. de Boor, "On calculating with b-splines", J. Approximation 

477 Theory, 6, p.50-62, 1972. 

478 .. [2] M. G. Cox, "The numerical evaluation of b-splines", J. Inst. Maths 

479 Applics, 10, p.134-149, 1972. 

480 .. [3] P. Dierckx, "Curve and surface fitting with splines", Monographs 

481 on Numerical Analysis, Oxford University Press, 1993. 

482 

483 Examples 

484 -------- 

485 

486 For some data, this method may miss a root. This happens when one of 

487 the spline knots (which FITPACK places automatically) happens to 

488 coincide with the true root. A workaround is to convert to `PPoly`, 

489 which uses a different root-finding algorithm. 

490 

491 For example, 

492 

493 >>> x = [1.96, 1.97, 1.98, 1.99, 2.00, 2.01, 2.02, 2.03, 2.04, 2.05] 

494 >>> y = [-6.365470e-03, -4.790580e-03, -3.204320e-03, -1.607270e-03, 

495 ... 4.440892e-16, 1.616930e-03, 3.243000e-03, 4.877670e-03, 

496 ... 6.520430e-03, 8.170770e-03] 

497 >>> from scipy.interpolate import splrep, sproot, PPoly 

498 >>> tck = splrep(x, y, s=0) 

499 >>> sproot(tck) 

500 array([], dtype=float64) 

501 

502 Converting to a PPoly object does find the roots at `x=2`: 

503 

504 >>> ppoly = PPoly.from_spline(tck) 

505 >>> ppoly.roots(extrapolate=False) 

506 array([2.]) 

507 

508 

509 Further examples are given :ref:`in the tutorial 

510 <tutorial-interpolate_splXXX>`. 

511 

512 """ 

513 if isinstance(tck, BSpline): 

514 if tck.c.ndim > 1: 

515 mesg = ("Calling sproot() with BSpline objects with c.ndim > 1 is " 

516 "not allowed.") 

517 raise ValueError(mesg) 

518 

519 t, c, k = tck.tck 

520 

521 # _impl.sproot expects the interpolation axis to be last, so roll it. 

522 # NB: This transpose is a no-op if c is 1D. 

523 sh = tuple(range(c.ndim)) 

524 c = c.transpose(sh[1:] + (0,)) 

525 return _impl.sproot((t, c, k), mest) 

526 else: 

527 return _impl.sproot(tck, mest) 

528 

529 

530def spalde(x, tck): 

531 """ 

532 Evaluate all derivatives of a B-spline. 

533 

534 Given the knots and coefficients of a cubic B-spline compute all 

535 derivatives up to order k at a point (or set of points). 

536 

537 Parameters 

538 ---------- 

539 x : array_like 

540 A point or a set of points at which to evaluate the derivatives. 

541 Note that ``t(k) <= x <= t(n-k+1)`` must hold for each `x`. 

542 tck : tuple 

543 A tuple ``(t, c, k)``, containing the vector of knots, the B-spline 

544 coefficients, and the degree of the spline (see `splev`). 

545 

546 Returns 

547 ------- 

548 results : {ndarray, list of ndarrays} 

549 An array (or a list of arrays) containing all derivatives 

550 up to order k inclusive for each point `x`. 

551 

552 See Also 

553 -------- 

554 splprep, splrep, splint, sproot, splev, bisplrep, bisplev, 

555 BSpline 

556 

557 References 

558 ---------- 

559 .. [1] C. de Boor: On calculating with b-splines, J. Approximation Theory 

560 6 (1972) 50-62. 

561 .. [2] M. G. Cox : The numerical evaluation of b-splines, J. Inst. Maths 

562 applics 10 (1972) 134-149. 

563 .. [3] P. Dierckx : Curve and surface fitting with splines, Monographs on 

564 Numerical Analysis, Oxford University Press, 1993. 

565 

566 Examples 

567 -------- 

568 Examples are given :ref:`in the tutorial <tutorial-interpolate_splXXX>`. 

569 

570 """ 

571 if isinstance(tck, BSpline): 

572 raise TypeError("spalde does not accept BSpline instances.") 

573 else: 

574 return _impl.spalde(x, tck) 

575 

576 

577def insert(x, tck, m=1, per=0): 

578 """ 

579 Insert knots into a B-spline. 

580 

581 Given the knots and coefficients of a B-spline representation, create a 

582 new B-spline with a knot inserted `m` times at point `x`. 

583 This is a wrapper around the FORTRAN routine insert of FITPACK. 

584 

585 Parameters 

586 ---------- 

587 x (u) : array_like 

588 A 1-D point at which to insert a new knot(s). If `tck` was returned 

589 from ``splprep``, then the parameter values, u should be given. 

590 tck : a `BSpline` instance or a tuple 

591 If tuple, then it is expected to be a tuple (t,c,k) containing 

592 the vector of knots, the B-spline coefficients, and the degree of 

593 the spline. 

594 m : int, optional 

595 The number of times to insert the given knot (its multiplicity). 

596 Default is 1. 

597 per : int, optional 

598 If non-zero, the input spline is considered periodic. 

599 

600 Returns 

601 ------- 

602 BSpline instance or a tuple 

603 A new B-spline with knots t, coefficients c, and degree k. 

604 ``t(k+1) <= x <= t(n-k)``, where k is the degree of the spline. 

605 In case of a periodic spline (``per != 0``) there must be 

606 either at least k interior knots t(j) satisfying ``t(k+1)<t(j)<=x`` 

607 or at least k interior knots t(j) satisfying ``x<=t(j)<t(n-k)``. 

608 A tuple is returned iff the input argument `tck` is a tuple, otherwise 

609 a BSpline object is constructed and returned. 

610 

611 Notes 

612 ----- 

613 Based on algorithms from [1]_ and [2]_. 

614 

615 Manipulating the tck-tuples directly is not recommended. In new code, 

616 prefer using the `BSpline` objects. 

617 

618 References 

619 ---------- 

620 .. [1] W. Boehm, "Inserting new knots into b-spline curves.", 

621 Computer Aided Design, 12, p.199-201, 1980. 

622 .. [2] P. Dierckx, "Curve and surface fitting with splines, Monographs on 

623 Numerical Analysis", Oxford University Press, 1993. 

624 

625 Examples 

626 -------- 

627 You can insert knots into a B-spline. 

628 

629 >>> from scipy.interpolate import splrep, insert 

630 >>> import numpy as np 

631 >>> x = np.linspace(0, 10, 5) 

632 >>> y = np.sin(x) 

633 >>> tck = splrep(x, y) 

634 >>> tck[0] 

635 array([ 0., 0., 0., 0., 5., 10., 10., 10., 10.]) 

636 

637 A knot is inserted: 

638 

639 >>> tck_inserted = insert(3, tck) 

640 >>> tck_inserted[0] 

641 array([ 0., 0., 0., 0., 3., 5., 10., 10., 10., 10.]) 

642 

643 Some knots are inserted: 

644 

645 >>> tck_inserted2 = insert(8, tck, m=3) 

646 >>> tck_inserted2[0] 

647 array([ 0., 0., 0., 0., 5., 8., 8., 8., 10., 10., 10., 10.]) 

648 

649 """ 

650 if isinstance(tck, BSpline): 

651 

652 t, c, k = tck.tck 

653 

654 # FITPACK expects the interpolation axis to be last, so roll it over 

655 # NB: if c array is 1D, transposes are no-ops 

656 sh = tuple(range(c.ndim)) 

657 c = c.transpose(sh[1:] + (0,)) 

658 t_, c_, k_ = _impl.insert(x, (t, c, k), m, per) 

659 

660 # and roll the last axis back 

661 c_ = np.asarray(c_) 

662 c_ = c_.transpose((sh[-1],) + sh[:-1]) 

663 return BSpline(t_, c_, k_) 

664 else: 

665 return _impl.insert(x, tck, m, per) 

666 

667 

668def splder(tck, n=1): 

669 """ 

670 Compute the spline representation of the derivative of a given spline 

671 

672 Parameters 

673 ---------- 

674 tck : BSpline instance or a tuple of (t, c, k) 

675 Spline whose derivative to compute 

676 n : int, optional 

677 Order of derivative to evaluate. Default: 1 

678 

679 Returns 

680 ------- 

681 `BSpline` instance or tuple 

682 Spline of order k2=k-n representing the derivative 

683 of the input spline. 

684 A tuple is returned iff the input argument `tck` is a tuple, otherwise 

685 a BSpline object is constructed and returned. 

686 

687 Notes 

688 ----- 

689 

690 .. versionadded:: 0.13.0 

691 

692 See Also 

693 -------- 

694 splantider, splev, spalde 

695 BSpline 

696 

697 Examples 

698 -------- 

699 This can be used for finding maxima of a curve: 

700 

701 >>> from scipy.interpolate import splrep, splder, sproot 

702 >>> import numpy as np 

703 >>> x = np.linspace(0, 10, 70) 

704 >>> y = np.sin(x) 

705 >>> spl = splrep(x, y, k=4) 

706 

707 Now, differentiate the spline and find the zeros of the 

708 derivative. (NB: `sproot` only works for order 3 splines, so we 

709 fit an order 4 spline): 

710 

711 >>> dspl = splder(spl) 

712 >>> sproot(dspl) / np.pi 

713 array([ 0.50000001, 1.5 , 2.49999998]) 

714 

715 This agrees well with roots :math:`\\pi/2 + n\\pi` of 

716 :math:`\\cos(x) = \\sin'(x)`. 

717 

718 """ 

719 if isinstance(tck, BSpline): 

720 return tck.derivative(n) 

721 else: 

722 return _impl.splder(tck, n) 

723 

724 

725def splantider(tck, n=1): 

726 """ 

727 Compute the spline for the antiderivative (integral) of a given spline. 

728 

729 Parameters 

730 ---------- 

731 tck : BSpline instance or a tuple of (t, c, k) 

732 Spline whose antiderivative to compute 

733 n : int, optional 

734 Order of antiderivative to evaluate. Default: 1 

735 

736 Returns 

737 ------- 

738 BSpline instance or a tuple of (t2, c2, k2) 

739 Spline of order k2=k+n representing the antiderivative of the input 

740 spline. 

741 A tuple is returned iff the input argument `tck` is a tuple, otherwise 

742 a BSpline object is constructed and returned. 

743 

744 See Also 

745 -------- 

746 splder, splev, spalde 

747 BSpline 

748 

749 Notes 

750 ----- 

751 The `splder` function is the inverse operation of this function. 

752 Namely, ``splder(splantider(tck))`` is identical to `tck`, modulo 

753 rounding error. 

754 

755 .. versionadded:: 0.13.0 

756 

757 Examples 

758 -------- 

759 >>> from scipy.interpolate import splrep, splder, splantider, splev 

760 >>> import numpy as np 

761 >>> x = np.linspace(0, np.pi/2, 70) 

762 >>> y = 1 / np.sqrt(1 - 0.8*np.sin(x)**2) 

763 >>> spl = splrep(x, y) 

764 

765 The derivative is the inverse operation of the antiderivative, 

766 although some floating point error accumulates: 

767 

768 >>> splev(1.7, spl), splev(1.7, splder(splantider(spl))) 

769 (array(2.1565429877197317), array(2.1565429877201865)) 

770 

771 Antiderivative can be used to evaluate definite integrals: 

772 

773 >>> ispl = splantider(spl) 

774 >>> splev(np.pi/2, ispl) - splev(0, ispl) 

775 2.2572053588768486 

776 

777 This is indeed an approximation to the complete elliptic integral 

778 :math:`K(m) = \\int_0^{\\pi/2} [1 - m\\sin^2 x]^{-1/2} dx`: 

779 

780 >>> from scipy.special import ellipk 

781 >>> ellipk(0.8) 

782 2.2572053268208538 

783 

784 """ 

785 if isinstance(tck, BSpline): 

786 return tck.antiderivative(n) 

787 else: 

788 return _impl.splantider(tck, n)