B-splines and smoothing splines
| Problem | Represent piecewise polynomials of any degree stably; interpolate data with a chosen end condition (not-a-knot, natural, clamped, periodic or given derivatives); fit splines to noisy data by least squares on given knots, or by a smoothing spline whose roughness is chosen by cross-validation |
| Devised by | Isaac Schoenberg (1946), splines and B-splines; Haskell Curry and Schoenberg (1947); Maurice Cox (1972) and Carl de Boor (1972), the recurrence; Schoenberg (1964) and Christian Reinsch (1967), smoothing splines; Peter Craven and Grace Wahba (1979), generalised cross-validation; Michael Hutchinson and Frank de Hoog (1985), the banded trace |
| Accuracy | A spline of degree with good end conditions: . Agrees with scipy.interpolate to or better, and the GCV choice of to |
| Cost | Interpolation: one banded solve, . Evaluation: a binary search and . Smoothing spline: per value of , including the GCV score |
| Read first | Piecewise and spline interpolation |
| API | BSpline, make_interp_spline, BoundaryCondition, make_lsq_spline, make_interp_curve, make_smoothing_spline |
Overview
The previous entry built the natural cubic spline from its values and second derivatives at the data. That approach does not generalise well: other degrees, other end conditions, smoothing and least-squares fitting each need their own derivation. B-splines give one representation for all of them. Every spline of degree on a knot sequence is a combination
of B-splines: non-negative bumps, each a piecewise polynomial of degree that is non-zero on only knot intervals. Fitting
a spline becomes a small banded linear system for the coefficients , and derivatives, integrals and evaluation follow from
simple recurrences. The library follows scipy.interpolate’s design: a BSpline type, and constructors for interpolating,
least-squares and smoothing splines.
Where it is used
B-splines are the standard way to describe smooth curves and surfaces.
- Computer-aided design. Car bodies, ship hulls and fonts are B-spline curves and surfaces.
- Computer graphics and animation. Smooth camera paths and character motion.
- Signal and image processing. Smoothing noisy data, resampling images, and representing trajectories.
- Data smoothing. Smoothing splines trade fidelity to noisy measurements against curvature, as in estimating a trend or a calibration curve.
History
Isaac Schoenberg introduced splines in 1946, naming them after the draughtsman’s flexible strip, and with Haskell Curry
described the B-spline basis in 1947. B-splines became practical with the stable recurrence found independently by Maurice
Cox and Carl de Boor in 1972. De Boor’s A Practical Guide to Splines (1978) and its Fortran codes, and Paul Dierckx’s FITPACK
(1975–1993), became the foundations of spline software; SciPy’s interpolate module grew from FITPACK and, since 2016, from
de Boor’s algorithms in Python. The smoothing spline goes back to Edmund Whittaker (1923) for discrete data. Schoenberg (1964)
showed that its continuous form is a natural cubic spline, and Christian Reinsch (1967) gave the banded algorithm. Grace Wahba
and Peter Craven (1979) proposed choosing its parameter by generalised cross-validation. Michael Hutchinson and Frank de Hoog
(1985) showed how to compute the GCV score in linear time.
The idea
The B-spline basis
Given knots , the B-splines are defined by the Cox-de Boor recurrence. Degree 0 is the indicator of a knot interval, on and 0 elsewhere. Each higher degree blends two neighbours of the degree below with weights that rise and fall linearly:
is non-zero only on , is non-negative, and the B-splines sum to one on the base interval . A spline is therefore a moving weighted average of its coefficients, and evaluating it involves only the functions that are non-zero at . Repeating a knot lowers the continuity there: with copies at each end, as in the figure, the spline starts and ends at its first and last coefficient.
Figure 3.5. Cubic B-splines.
The derivative of a spline is a spline of one degree less on the same knots, with coefficients
and the antiderivative is a spline of one degree more, with coefficients that are partial sums . Integrals are differences of the antiderivative.
Interpolation and end conditions
A spline of degree through points has interpolation conditions . With knots at the data, there are coefficients, so conditions are still free: one at each end for a cubic. The choice matters most near the ends:
- Not-a-knot (the default) removes knots instead of adding conditions. For a cubic, the knots at and are dropped, so the first two and the last two intervals are each one cubic. It needs no information beyond the data.
- Natural sets at both ends. This is the spline of the previous entry, and the smoothest interpolant in the sense of .
- Clamped sets at both ends (SciPy’s meaning). The general form, given derivatives, sets any derivatives at the ends to known values.
- Periodic matches all derivatives up to order across the ends, for periodic data.
The conditions form a banded linear system with bandwidth , solved with partial pivoting in operations. The end condition decides the rate of convergence for a smooth function sampled with spacing :
Table 3.3. Largest error interpolating sin 2x + e^(x/3) on [0, 3] with n equally spaced points.
| spline | n = 8 | n = 16 | n = 32 | n = 64 | n = 128 | order |
|---|---|---|---|---|---|---|
| linear | 9.6e-2 | 2.1e-2 | 5.0e-3 | 1.2e-3 | 3.0e-4 | 2.0 |
| cubic, zero end slopes (clamped) | 2.1e-1 | 9.6e-2 | 4.7e-2 | 2.3e-2 | 1.1e-2 | 1.0 |
| cubic, natural | 1.5e-2 | 2.8e-3 | 6.6e-4 | 1.6e-4 | 3.9e-5 | 2.0 |
| cubic, not-a-knot | 1.4e-2 | 4.6e-4 | 1.8e-5 | 8.6e-7 | 4.6e-8 | 4.2 |
| cubic, exact end slopes | 1.8e-3 | 6.9e-5 | 3.7e-6 | 2.1e-7 | 1.3e-8 | 4.1 |
| quintic, not-a-knot | 4.8e-3 | 4.7e-5 | 4.3e-7 | 4.5e-9 | 5.5e-11 | 6.4 |
Not-a-knot and exact end slopes give the full of a cubic. The natural condition imposes where is not zero, and the error near the ends falls only as . Clamping to zero slope is worse still, , unless the function really has zero slope there. Wrong end conditions are a common cause of poor spline accuracy.
Least-squares splines
With fewer knots than data, a spline cannot interpolate, but it can be fitted by least squares. make_lsq_spline minimises
on a given knot sequence. The design matrix has at most non-zeros per row, and
the problem is solved with a QR factorisation. The solution is unique when each B-spline is non-zero at some data point in the
right order (the Schoenberg-Whitney conditions).
Smoothing splines
The smoothing spline balances fidelity against roughness: it minimises
over all twice-differentiable functions . The minimiser is a natural cubic spline with knots at the data (Schoenberg’s theorem), so it is found exactly in a finite basis. In the cubic B-spline basis, the coefficients solve
with both matrices banded with half-bandwidth 3. Large gives the least-squares straight line, and the interpolating natural spline. The fitted values are , and the trace of the influence matrix counts the effective number of parameters, from 2 to .
Generalised cross-validation chooses to minimise
an estimate of the prediction error that needs no knowledge of the noise level. The trace needs only the entries of inside the band, and the recurrence of Hutchinson and de Hoog computes those from the factors in . The library minimises GCV over with the same bounded Brent search as SciPy, so the two choose the same :
Figure 3.6. Smoothing splines.
Table 3.4. Smoothing splines of the data in the figure.
| λ | degrees of freedom tr A | RMS residual | RMS error against the true function |
|---|---|---|---|
| 1.00e-5 | 52.0 | 0.127 | 0.214 |
| 4.63e-2 | 7.5 | 0.275 | 0.095 |
| 1.00e1 | 2.7 | 0.548 | 0.497 |
The nearly interpolating spline follows the noise and has the smallest residual but a large error. The oversmoothed one misses the signal. GCV picks about 7.5 effective parameters, and its error is less than half that of either extreme.
Algorithm
Evaluation, s(x): find the interval by binary search (clamped to the first or last interval when extrapolating);
compute the non-zero B-splines by the recurrence, raising the degree one step at a time (de Boor’s bsplvb); return
. Derivatives use the derivative recurrence on the lower-degree values.
Interpolation, make_interp_spline(x, y, k, bc):
- Choose the knots: for not-a-knot, the data points with removed at each end for odd (midpoints between data points for even ), and copies of each end; with derivative conditions, the data points with extra copies of each end.
- One row per condition: the non-zero B-splines (or their derivatives) at the point.
- Solve the banded system with partial pivoting. Periodic splines use free coefficients with the last repeating the first, and solve the resulting cyclic system densely.
Smoothing spline, make_smoothing_spline(x, y, w, λ): form , and (by two-point Gauss quadrature on each interval,
exact because is linear there); eliminate the two end coefficients with the natural conditions ; and
solve by a banded factorisation. Without , minimise the GCV score, computing each trace from the band of the inverse.
Implementation
/// The `k + 1` B-splines of degree `k` that are non-zero on the knot interval
/// `t[l] ≤ x < t[l + 1]`, namely `B_{l−k}, …, B_l`, by the Cox-de Boor recurrence (de Boor's
/// `bsplvb`). Each degree is built from the previous one; the values are non-negative and sum
/// to one.
pub fn nonzero_basis(t: &[f64], k: usize, l: usize, x: f64) -> Vec<f64> {
let mut b = vec![0.0; k + 1];
let (mut left, mut right) = (vec![0.0; k + 1], vec![0.0; k + 1]);
b[0] = 1.0;
for j in 1..=k {
left[j] = x - t[l + 1 - j];
right[j] = t[l + j] - x;
let mut saved = 0.0;
for r in 0..j {
let temp = b[r] / (right[r + 1] + left[j - r]);
b[r] = saved + right[r + 1] * temp;
saved = left[j - r] * temp;
}
b[j] = saved;
}
b
}
/// The interpolating spline of degree `k` through `(x, y)` (SciPy's `make_interp_spline`).
///
/// For `k = 0` and `k = 1` the spline is piecewise constant or linear. Otherwise the knots are
/// chosen from the data (not-a-knot, or the data points with `k` copies of each end when
/// derivatives are given), and the `n` interpolation conditions `s(xᵢ) = yᵢ` together with the
/// end conditions form a banded linear system for the coefficients. Periodic splines solve a
/// cyclic system for `n − 1` free coefficients.
pub fn make_interp_spline(x: &[f64], y: &[f64], k: usize, bc: &BoundaryCondition) -> Result<BSpline, ErrorsJSL> {
check_data(x, y)?;
let n = x.len();
if n < k + 1 {
return Err(ErrorsJSL::InvalidInputRange("need at least k + 1 data points"));
}
let derivatives = match bc {
BoundaryCondition::NotAKnot => None,
BoundaryCondition::Natural => Some((vec![(2, 0.0)], vec![(2, 0.0)])),
BoundaryCondition::Clamped => Some((vec![(1, 0.0)], vec![(1, 0.0)])),
BoundaryCondition::Derivatives { left, right } => Some((left.clone(), right.clone())),
BoundaryCondition::Periodic => return periodic_spline(x, y, k),
};
if k == 0 || k == 1 {
if derivatives.is_some() {
return Err(ErrorsJSL::InvalidInputRange("degrees 0 and 1 take no end conditions"));
}
let mut t = x.to_vec();
if k == 0 {
t.push(x[n - 1]);
} else {
t.insert(0, x[0]);
t.push(x[n - 1]);
}
let mut s = BSpline::new(t, y.to_vec(), k)?;
s.extrapolate = Extrapolate::Yes;
return Ok(s);
}
let (left, right) = derivatives.unwrap_or_default();
let t = if left.is_empty() && right.is_empty() {
not_a_knot_knots(x, k)
} else {
let mut t = vec![x[0]; k];
t.extend_from_slice(x);
t.extend(std::iter::repeat_n(x[n - 1], k));
t
};
let nt = t.len() - k - 1;
if nt != n + left.len() + right.len() {
return Err(ErrorsJSL::InvalidInputRange("the number of end conditions must be k − 1 (one at each end for a cubic)"));
}
if left.iter().chain(&right).any(|&(nu, _)| nu == 0 || nu > k) {
return Err(ErrorsJSL::InvalidInputRange("end-condition derivative orders must lie in 1..=k"));
}
let probe = BSpline::new(t.clone(), vec![0.0; nt], k)?;
let mut rows = Vec::with_capacity(nt);
let mut rhs = Vec::with_capacity(nt);
let (l0, _) = probe.interval(x[0]).expect("finite");
for &(nu, v) in &left {
rows.push((l0 - k, nonzero_basis_derivatives(&t, k, l0, x[0], nu)));
rhs.push(v);
}
for (&xi, &yi) in x.iter().zip(y) {
let (l, _) = probe.interval(xi).expect("finite");
rows.push((l - k, nonzero_basis(&t, k, l, xi)));
rhs.push(yi);
}
let (ln, _) = probe.interval(x[n - 1]).expect("finite");
for &(nu, v) in &right {
rows.push((ln - k, nonzero_basis_derivatives(&t, k, ln, x[n - 1], nu)));
rhs.push(v);
}
let c = solve_banded(nt, &rows, &rhs)?;
BSpline::new(t, c, k)
}
/// The entries of `M⁻¹` within the band, from `M = L D Lᵀ`, by the recurrence of Hutchinson and
/// de Hoog (1985): `Z = D⁻¹ L⁻¹ + (I − Lᵀ) Z`, run from the last row upwards, needs only entries of
/// `Z` that are themselves in the band.
fn band_of_inverse(l: &[[f64; 3]], d: &[f64]) -> Band4 {
let n = d.len();
let mut z = Band4::zeros(n);
for i in (0..n).rev() {
let reach = (i + 4).min(n);
for j in (i..reach).rev() {
let mut s = if i == j { 1.0 / d[i] } else { 0.0 };
for k in i + 1..reach {
s -= l[i][k - i - 1] * z.get(k, j);
}
z.d[i][j - i] = s;
}
}
z
}
BSplineholds knots, coefficients and degree, as SciPy’s does. Itsextrapolatefield continues the end polynomials (the default), returns NaN, or wraps periodically.make_lsq_splineuses SciPy’s convention that the weights multiply the residuals;make_smoothing_splineweights the squared residuals.make_interp_curveinterpolates a parametric curve through points in any dimension, with the chord-length parameter thatsplprepuses.
In practice
Every constructor is compared with scipy.interpolate from SciPy 1.17.1 (references from
book/generator/data/make_bspline_refs.py), on 15 irregular points and 141 evaluation points that include extrapolation
beyond both ends:
Table 3.5. B-splines against SciPy.
| computation (SciPy reference) | values | first derivative | integrals, antiderivative |
|---|---|---|---|
cubic not-a-knot (make_interp_spline) | 7e-15 | 2e-14 | 2e-15 |
quadratic not-a-knot (make_interp_spline) | 6e-16 | 1e-15 | 4e-16 |
quartic not-a-knot (make_interp_spline) | 4e-14 | 1e-13 | 8e-15 |
quintic not-a-knot (make_interp_spline) | 4e-14 | 1e-13 | 4e-15 |
cubic natural (make_interp_spline) | 3e-16 | 2e-15 | 1e-15 |
cubic clamped (make_interp_spline) | 4e-16 | 7e-16 | 7e-16 |
cubic given slopes (make_interp_spline) | 2e-16 | 3e-16 | 2e-16 |
quintic given derivatives (make_interp_spline) | 3e-15 | 1e-14 | 1e-15 |
linear (make_interp_spline) | 6e-17 | 0 | 4e-17 |
| periodic, degree 3 | 9e-16 | 1e-15 | |
| periodic, degree 4 | 2e-15 | 2e-16 | |
weighted least squares, 5 interior knots (make_lsq_spline) | 1e-14 | ||
weighted smoothing spline, λ = 0.05 (make_smoothing_spline) | 5e-12 | ||
weighted smoothing spline, λ = 2 (make_smoothing_spline) | 1e-10 | ||
| smoothing spline, λ by GCV (here 0.0856) | 2e-8 | ||
parametric cubic curve (splprep, s = 0; parameters differ by 0) | 1e-15 |
The smoothing splines agree to , the conditioning of the penalised system. The GCV choice agrees to : both run the same search on the same function, but floating-point differences in the GCV score move its stopping point slightly.
Strengths
- One representation for every degree and end condition, with exact derivatives, antiderivatives and integrals.
- Banded systems: interpolation and smoothing cost for fixed degree.
- The smoothing spline needs no knot placement, and GCV chooses its parameter automatically.
Weaknesses
- Periodic interpolation solves a dense system; a cyclic banded solver would make it .
- No automatic knot selection for a given smoothing tolerance (FITPACK’s
splrepwiths > 0); usemake_smoothing_splineormake_lsq_splinewith chosen knots instead. - Splines are one-dimensional here; tensor products for grids are in Interpolation on grids.
Exercises
- Show from the recurrence that on the base interval.
- Show that the derivative formula for follows from differentiating the recurrence, and check it on .
- Count the coefficients and conditions of a cubic interpolating spline with knots at the data, and explain why not-a-knot needs no extra conditions.
- Explain why the natural spline converges only as near the ends, and estimate the size of its error at .
- Show that as the smoothing spline tends to the weighted least-squares straight line, and that .
Hints and answers
- By induction on : substituting the recurrence and collecting the terms that multiply each gives the weights .
- Differentiate using and shift the index in the second sum. For the hat function has slopes , as the formula gives.
- With knots at the data points and 4 copies of each end, there are coefficients and conditions. Not-a-knot removes 2 knots, leaving coefficients for conditions.
- at the end is wrong by . The resulting error decays away from the end like a damped correction, of order in the first intervals.
- Dividing by , the objective tends to , whose minimisers are straight lines. Among them the fit term picks the least-squares line. becomes the projection onto lines, whose trace is 2.
Further reading
- C. de Boor, A Practical Guide to Splines, revised ed., Springer, 2001.
- P. Dierckx, Curve and Surface Fitting with Splines, Oxford University Press, 1993.
- C. H. Reinsch, “Smoothing by spline functions”, Numerische Mathematik 10 (1967) 177–183.
- P. Craven and G. Wahba, “Smoothing noisy data with spline functions”, Numerische Mathematik 31 (1979) 377–403.
- M. F. Hutchinson and F. R. de Hoog, “Smoothing noisy data with spline functions”, Numerische Mathematik 47 (1985) 99–106.
- T. Lyche and K. Mørken, Spline Methods (lecture notes), University of Oslo, 2008.