Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Smoothing splines with automatic knots

ProblemFit a smooth spline to noisy data with a chosen bound on the weighted sum of squared residuals, placing the knots automatically; do the same for a parametric curve; and represent piecewise polynomials in the Bernstein basis, built from derivatives at the breakpoints
Devised byPaul Dierckx (1975, 1982), FITPACK’s curfit and parcur; Sergei Bernstein (1912) and Pierre Bézier (1960s), the Bernstein basis and Bézier curves; Paul de Casteljau (1959), its evaluation
AccuracyThe residual within of , as FITPACK; the same knots as SciPy’s make_splrep and coefficients to
CostEach least-squares fit is a banded QR by Givens rotations, for points; the knot search tries to knot sets for knots, and the smoothing parameter takes up to 20 more banded solves
Read firstB-splines and smoothing splines, Piecewise polynomials, Hermite data and scattered interpolation
APIfitpack (make_splrep, make_splprep, generate_knots, SplrepOptions, make_splrep_periodic); bisplrep, bisplrep_lsq, SmoothBivariateSpline; BPoly

Overview

B-splines and smoothing splines fits splines whose knots are given (make_lsq_spline) or are all the data points (make_smoothing_spline). FITPACK, Paul Dierckx’s Fortran library, chooses the knots itself. Given a smoothing factor , make_splrep returns the smoothest spline whose weighted residual is at most : where “smoothest” means that the jumps of at the interior knots are as small as possible. The spline has only as many knots as the data need: few where the data are smooth, more where they change quickly.

  • interpolates.
  • A large gives the least-squares polynomial of degree .
  • With weights , the expected residual of the true curve is , and Dierckx recommends in .

This is SciPy’s splrep(x, y, s=...) and UnivariateSpline, in the form of SciPy’s newer make_splrep, a reimplementation of the Fortran algorithm. make_splprep (SciPy’s splprep) fits a curve through points in any number of dimensions with shared knots.

The entry also adds BPoly, piecewise polynomials in the Bernstein basis . Its coefficients are the control points of Bézier curves. BPoly.from_derivatives builds the piecewise polynomial matching any number of derivatives at each breakpoint, a generalisation of cubic Hermite interpolation.

Where it is used

Noisy data need a smooth curve whose complexity matches the data.

  • Calibration and trend estimation. Fitting a sensor’s response curve, or a growth curve, with the smoothness chosen by a noise level .
  • Parametric curves. Smoothing a noisy trajectory of a vehicle or a moving point.
  • Surfaces from scattered data. Terrain, temperature fields and calibration surfaces from measurements at irregular points.
  • Reference implementation. This is the FITPACK algorithm underlying SciPy’s splrep and bisplrep.

History

Paul Dierckx (1975) gave the algorithm for smoothing with automatic knots, and FITPACK (1982–1993), collected in his book Curve and Surface Fitting with Splines, extended it to periodic and parametric curves and to surfaces. SciPy wrapped FITPACK from its beginning in 2001. In 2024 (SciPy 1.15) Evgeni Burovski reimplemented the curve-fitting drivers in Python and C++ as make_splrep, make_splprep and generate_knots; this library follows that reimplementation.

Sergei Bernstein (1912) introduced his polynomials for a constructive proof of the Weierstrass approximation theorem. Paul de Casteljau at Citroën (1959) and Pierre Bézier at Renault (1960s) independently used them for car-body design, and de Casteljau’s algorithm is still how Bézier curves are drawn.

The idea

Placing the knots

FITPACK starts with no interior knots (the least-squares polynomial) and repeats:

  1. Fit the least-squares spline on the current knots and compute its residual .
  2. If , stop.
  3. Otherwise add knots. Split the residuals into the knot intervals, counting a point on an interior knot half to each side. In the interval with the largest sum that holds more than one data point, insert a knot at the data point in its middle.

One knot is added at the first step. After that, the number added grows from the rate at which the residual fell, per knot: about more knots should reach . That estimate is clamped between half and twice the previous number. If the knots reach , they are replaced by those of the interpolating spline.

The smoothing parameter

With the knots fixed, the least-squares spline has , usually well below it, and the polynomial has . Between them lies a one-parameter family: minimise For this is the least-squares spline, for the polynomial, and the residual decreases monotonically in between. The jumps are linear in the coefficients, so for each the minimiser solves a least-squares problem. That problem is the observation matrix with the scaled jump rows appended.

FITPACK finds the with by fitting a rational function through three values and taking its zero. It keeps a bracket with on one side and on the other, and stops when .

Banded QR by Givens rotations

Each row of the observation matrix has non-zero entries, the B-splines that are non-zero at , so the triangular factor is banded. FITPACK rotates the rows into the triangle one at a time with Givens rotations, in operations per row. A jump row has entries, and rotating it in fills the band to width all the way down. The row being rotated therefore travels along the band, one column per rotation, to the end of the matrix. The triangle of the data rows is computed once and reused for every .

The Bernstein basis

On with , , and:

  • , , and the curve lies in the convex hull of the coefficients.
  • De Casteljau’s algorithm evaluates by rounds of convex combinations . It is numerically stable because every step is an average.
  • Derivatives are again in the Bernstein basis: .
  • Matching derivatives at the ends. The -th derivative at the left end involves only , and at the right end only . Prescribed derivatives at both ends therefore determine the coefficients one at a time from each end.

Algorithm

Knot placement (generate_knots), with acc :

  1. = copies of each end; .
  2. Repeat:
    1. Fit the least-squares spline; if acc, stop.
    2. Unless this is the first fit, set , with ; if acc, use for the first argument.
    3. Add knots, refitting between additions. Stop with the interpolating knots if there are , or at nest.

Smoothing (make_splrep):

  1. Starting values: with the triangular factor; the bracket , .
  2. Repeat up to 20 times:
    1. Rotate the rows into a copy of , back-substitute, and evaluate ; stop if it is below acc.
    2. If the bracket is not yet confirmed, move by a factor of 25 (or towards the other end).
    3. Otherwise take the zero of the rational interpolant through the bracket and the new point, and replace the bracket end of the same sign.

Implementation

/// FITPACK's `fpknot`: split the residuals into the knot intervals (a point on an interior knot
/// counts half to each side), pick the interval with the largest sum among those holding more
/// than one point, and insert a knot at the data point in its middle.
fn add_knot(x: &[f64], t: &[f64], k: usize, res: &[f64]) -> Result<Vec<f64>, ErrorsJSL> {
    let m = x.len();
    let bounds = &t[k..t.len() - k];
    let mut ix: Vec<usize> = bounds.iter().map(|&b| x.partition_point(|&v| v < b)).collect();
    let last = ix.len() - 1;
    ix[last] = m - 1;
    let mut parts: Vec<f64> = ix.windows(2).map(|w| res[w[0]..w[1]].iter().sum()).collect();
    for i in 1..last {
        let carry = res[ix[i]] / 2.0;
        parts[i - 1] += carry;
        parts[i] -= carry;
    }
    parts[last - 1] += res[m - 1];
    let mut best: Option<usize> = None;
    for i in 0..parts.len() {
        if ix[i + 1] - ix[i] > 1 && best.is_none_or(|b| parts[i] > parts[b]) {
            best = Some(i);
        }
    }
    let b = best.ok_or(ErrorsJSL::RuntimeError("generate_knots: no knot interval has room for another knot"))?;
    let knot = x[(ix[b] + ix[b + 1]).div_ceil(2)];
    let pos = t.partition_point(|&v| v < knot);
    let mut out = t.to_vec();
    out.insert(pos, knot);
    Ok(out)
}
fn fit_smoothing(data: &Data, t: Option<&[f64]>, nest: Option<usize>) -> Result<Fit, ErrorsJSL> {
    let (k, s) = (data.k, data.s);
    let acc = s * TOL;
    let t: Vec<f64> = match t {
        Some(t) => t.to_vec(),
        None => knot_sequence(data, nest)?.pop().expect("at least one knot vector"),
    };
    let base = lsq(data, &t);
    if t.len() == 2 * (k + 1) {
        return Ok(Fit { t, c: base.c, fp: base.fp, converged: true });
    }
    // f(p) = fp(p) − s decreases from the polynomial fit (p = 0) to the least-squares spline
    // (p = ∞); bracket the root and refine it by rational interpolation.
    let nc = t.len() - k - 1;
    let mut p = nc as f64 / base.qr.r.iter().map(|r| r[0]).sum::<f64>();
    let poly: Vec<f64> = std::iter::repeat_n(data.xb, k + 1).chain(std::iter::repeat_n(data.xe, k + 1)).collect();
    let (mut p1, mut f1) = (0.0, lsq(data, &poly).fp - s);
    let (mut p3, mut f3) = (f64::INFINITY, base.fp - s);
    let jumps = discontinuity_jumps(&t, k);
    let (con1, con4, con9) = (0.1, 0.04, 0.9);
    let (mut ich1, mut ich3) = (false, false);
    let mut last = (base.c.clone(), base.fp);
    for _ in 0..MAXIT {
        let (c, f2) = smoothing_for_p(data, &t, &base.qr, &jumps, p);
        let p2 = p;
        last = (c, f2 + s);
        if f2.abs() < acc {
            return Ok(Fit { t, c: last.0, fp: last.1, converged: true });
        }
        if !ich3 {
            if f2 - f3 <= acc {
                // p is too large.
                (p3, f3) = (p2, f2);
                p *= con4;
                if p <= p1 {
                    p = p1 * con9 + p2 * con1;
                }
                continue;
            }
            if f2 < 0.0 {
                ich3 = true;
            }
        }
        if !ich1 {
            if f1 - f2 <= acc {
                // p is too small.
                (p1, f1) = (p2, f2);
                p /= con4;
                if p3.is_finite() && p <= p3 {
                    p = p2 * con1 + p3 * con9;
                }
                continue;
            }
            if f2 > 0.0 {
                ich1 = true;
            }
        }
        if f1 <= f2 || f2 <= f3 {
            // f is not decreasing: s is too small for the arithmetic.
            break;
        }
        p = fprati(p1, f1, p2, f2, p3, f3);
        if f2 < 0.0 {
            (p3, f3) = (p2, f2);
        } else {
            (p1, f1) = (p2, f2);
        }
    }
    Ok(Fit { t, c: last.0, fp: last.1, converged: false })
}
    /// The piecewise polynomial matching given derivatives at the breakpoints (SciPy's
    /// `BPoly.from_derivatives`): `yi[i]` lists `f(xᵢ), f'(xᵢ), …`. On each interval the
    /// Bernstein coefficients follow from the end values one at a time, since the `q`-th
    /// derivative at the left end involves only the first `q + 1` coefficients (and at the right
    /// end only the last). With `orders`, interval `i` matches only enough derivatives for a
    /// polynomial of that degree, split between the ends. All pieces are raised to the degree of
    /// the interval with the most derivatives given, as in SciPy.
    pub fn from_derivatives(xi: &[f64], yi: &[Vec<f64>], orders: Option<&[usize]>) -> Result<BPoly, ErrorsJSL> {
        let m = xi.len().saturating_sub(1);
        if m == 0 || yi.len() != xi.len() || yi.iter().any(|y| y.is_empty()) {
            return Err(ErrorsJSL::InvalidInputRange("from_derivatives: need two or more breakpoints, each with at least a value"));
        }
        if xi.windows(2).any(|w| !(w[1] > w[0])) {
            return Err(ErrorsJSL::InvalidInputRange("from_derivatives: breakpoints must be increasing"));
        }
        if let Some(o) = orders
            && o.len() != 1
            && o.len() != m
        {
            return Err(ErrorsJSL::IncompatibleArraySizes((o.len(), m)));
        }
        if orders.is_some_and(|o| o.contains(&0)) {
            return Err(ErrorsJSL::InvalidInputRange("from_derivatives: orders must be positive"));
        }
        let mut pieces = Vec::with_capacity(m);
        for i in 0..m {
            let (la, lb) = (yi[i].len(), yi[i + 1].len());
            let (n1, n2) = match orders {
                None => (la, lb),
                Some(o) => {
                    let n = o[if o.len() == 1 { 0 } else { i }] + 1;
                    let n1 = (n / 2).min(la);
                    let n2 = (n - n1).min(lb);
                    let n1 = (n - n2).min(la);
                    if n1 + n2 != n {
                        return Err(ErrorsJSL::InvalidInputRange("from_derivatives: not enough derivatives for the requested order"));
                    }
                    (n1, n2)
                }
            };
            pieces.push(construct_from_derivatives(xi[i], xi[i + 1], &yi[i][..n1], &yi[i + 1][..n2]));
        }
        // SciPy's common size: the most derivatives given at the ends of any interval, or the
        // largest order if that is more.
        let given = (0..m).map(|i| yi[i].len() + yi[i + 1].len()).max().unwrap_or(1);
        let k1 = given.max(orders.and_then(|o| o.iter().copied().max()).unwrap_or(0));
        let mut c = Array2::zeros((k1, m));
        for (j, p) in pieces.iter().enumerate() {
            let col = Array2::from_shape_vec((p.len(), 1), p.clone()).expect("shape");
            let raised = raise_degree(&col, k1 - p.len());
            for a in 0..k1 {
                c[(a, j)] = raised[(a, 0)];
            }
        }
        Ok(BPoly { c, x: xi.to_vec(), extrapolate: true })
    }
  • make_splrep returns the spline and a SplrepInfo with and whether the tolerance was met. SciPy warns instead.
  • Periodic smoothing splines and smoothing surfaces were added in 2.19.0; see the section below.
  • BPoly covers one-dimensional values. extend and BPoly with vector values are not implemented.

In practice

The references are from SciPy 1.17.1, written by book/generator/data/make_fitpack_refs.py. The data are 80 noisy samples of with noise of standard deviation 0.15:

Table 3.13. Smoothing splines against SciPy's `make_splrep`, `make_splprep` and `generate_knots`, and against FITPACK's Fortran `splrep`.

Case (80 points)KnotsKnots vs make_splrepCoefficientsfp: library / SciPyFITPACK’s splrep
cubic s=0.561identical2e-150.5000 / 0.500060 knots
cubic s=218identical1e-151.9996 / 1.999621 knots
cubic s=810identical1e-158.0000 / 8.0000same knots; 3e-16
linear s=135identical1e-151.0001 / 1.000143 knots
quadratic s=151identical3e-151.0005 / 1.000548 knots
quartic s=149identical4e-151.0009 / 1.000949 knots
quintic s=158identical1e-141.0009 / 1.000958 knots
weighted s=8034identical2e-1580.0082 / 80.008236 knots
interval [-1, 11]18identical6e-152.0000 / 2.000021 knots
nest=1414identical2e-157.8403 / 7.8403(no nest in splrep)
s huge8identical2e-1535.7924 / 35.7924same knots; 0
make_splprep, 3-D curve, s=0.0518identical8e-16 (u: 0)0.0500same knots
generate_knots, s=0.58, 9, 10, 12, 16, 19, 25, 37, 61identical

The library places the same knots as SciPy’s make_splrep in every case. Its coefficients agree to rounding, and so do its residuals.

FITPACK’s Fortran splrep often places different knots. In the cubic case with it uses 21 knots against 18, of which 10 interior knots are shared. Both meet the criterion, with and . SciPy’s reimplementation, which the library follows, differs from the Fortran code in details of knot placement; for and the polynomial, where they coincide, the coefficients agree to .

Figure 3.15. Smoothing splines for three values of . The noise variance gives an expected residual of . With the spline follows the signal with 10 interior knots. With it chases the noise with 53, and with it is too stiff to follow the oscillation near .

Figure 3.16. The residual of the least-squares spline on each knot vector FITPACK tries. The dashed lines mark . The three runs share their first steps, and the number of knots added per step grows until the residual approaches .

Table 3.14. `BPoly` against SciPy, on four breakpoints with two or three derivatives each, evaluated at 23 points including extrapolation.

ConstructionCoefficientsValuesFirst derivativeSecond antiderivativeIntegral
from_derivatives, all given derivatives (degree 4)05e-168e-161e-152e-16
from_derivatives, orders = 307e-161e-158e-161e-16
from_derivatives, orders = 106e-162e-164e-160
from_power_basis, to_power_basis (cubic spline)5e-161e-16

Periodic splines and smoothing surfaces

Periodic splines. make_splrep_periodic is SciPy’s make_splrep(bc_type='periodic'), FITPACK’s percur, for data that repeat with the period :

  • the last point stands for the first one shifted by a period;
  • the boundary knots repeat the interior spacing across the ends;
  • the last coefficients repeat the first , which makes the spline and its first derivatives continuous around the circle.

Knot placement and the iteration on are those of the non-periodic fit. Because the wrapped coefficients break the band structure, the library solves the small least-squares problems densely rather than with FITPACK’s two-part Givens factorisation.

/// The periodic smoothing spline with automatically placed knots (SciPy's
/// `make_splrep(..., bc_type='periodic')`, FITPACK's `percur`): the spline and its first `k − 1`
/// derivatives match at `xb` and `xe = xb + period`, the last data point stands for the first
/// one shifted by a period, and otherwise the criterion is [`make_splrep`]'s. The free
/// coefficients are the first `n − 2k − 1`; the last `k` repeat them.
pub fn make_splrep_periodic(x: &[f64], y: &[f64], t: Option<&[f64]>, options: &SplrepOptions) -> Result<(BSpline, SplrepInfo), ErrorsJSL> {
    let data = validate(x, y.iter().map(|&v| vec![v]).collect(), options)?;
    let (k, s) = (data.k, data.s);
    if x.len() < 2 * k.max(2) {
        return Err(ErrorsJSL::InvalidInputRange("make_splrep_periodic: too few points for the degree"));
    }
    if s == 0.0 && t.is_none() {
        let t = periodic_interp_knots(x, k);
        let (c, _, fp, _) = periodic_fit(&data, &t, None);
        return Ok((BSpline::new(t, periodic_full(&c, k), k)?, SplrepInfo { fp, converged: true }));
    }
    let acc = s * TOL;
    let t: Vec<f64> = match t {
        Some(t) => t.to_vec(),
        None => periodic_knot_sequence(&data, options.nest)?.pop().expect("at least one knot vector"),
    };
    let (c0, diag, fpinf, _) = periodic_fit(&data, &t, None);
    if t.len() == 2 * (k + 1) || fpinf - s >= -acc {
        return Ok((BSpline::new(t.clone(), periodic_full(&c0, k), k)?, SplrepInfo { fp: fpinf, converged: fpinf <= s + acc }));
    }
    let n7 = t.len() - 2 * k - 1;
    let per = data.xe - data.xb;
    let m = data.m();
    let tc: Vec<f64> = (0..=k).map(|i| x[0] - (k - i) as f64 * per).chain((0..=k).map(|i| x[m - 1] + i as f64 * per)).collect();
    let (mut p1, mut f1) = (0.0, periodic_fit(&data, &tc, None).2 - s);
    let (mut p3, mut f3) = (f64::INFINITY, fpinf - s);
    let mut p = n7 as f64 / diag.iter().sum::<f64>();
    let (con1, con4, con9) = (0.1, 0.04, 0.9);
    let (mut ich1, mut ich3) = (false, false);
    let mut last = (c0, fpinf);
    let mut converged = false;
    for _ in 0..MAXIT {
        let (c, _, fp, _) = periodic_fit(&data, &t, Some(p));
        let (p2, f2) = (p, fp - s);
        last = (c, fp);
        if f2.abs() < acc {
            converged = true;
            break;
        }
        if !ich3 {
            if f2 - f3 <= acc {
                (p3, f3) = (p2, f2);
                p *= con4;
                if p <= p1 {
                    p = p1 * con9 + p2 * con1;
                }
                continue;
            }
            if f2 < 0.0 {
                ich3 = true;
            }
        }
        if !ich1 {
            if f1 - f2 <= acc {
                (p1, f1) = (p2, f2);
                p /= con4;
                if p3.is_finite() && p <= p3 {
                    p = p2 * con1 + p3 * con9;
                }
                continue;
            }
            if f2 > 0.0 {
                ich1 = true;
            }
        }
        if f1 <= f2 || f2 <= f3 {
            break;
        }
        p = fprati(p1, f1, p2, f2, p3, f3);
        if f2 < 0.0 {
            (p3, f3) = (p2, f2);
        } else {
            (p1, f1) = (p2, f2);
        }
    }
    Ok((BSpline::new(t, periodic_full(&last.0, k), k)?, SplrepInfo { fp: last.1, converged }))
}

Table 3.15. Periodic smoothing splines against SciPy's.

Periodic smoothing splineKnots (library vs SciPy)Values on 101 pointsfp (library)
k = 3, s = 066 vs 66, identical2e-140.0000
k = 3, s = 0.333 vs 33, identical1e-150.2999
k = 3, s = 0.618 vs 18, identical2e-150.6000
k = 3, s = 214 vs 14, identical1e-151.9998
k = 2, s = 064 vs 64, identical6e-140.0000
k = 2, s = 0.333 vs 33, identical9e-150.3000
k = 2, s = 0.616 vs 16, identical9e-160.5994
k = 2, s = 214 vs 14, identical2e-152.0007

The knots are SciPy’s, and so are the values to .

Figure 3.17. The periodic smoothing spline of noisy samples of a periodic function, drawn over two periods: it joins itself smoothly at .

Smoothing surfaces. bisplrep fits scattered data with a tensor-product spline. Of the surfaces with , it returns the one whose -th -derivatives and -th -derivatives jump least across the knots.

  • Knots are added one at a time, by FITPACK’s rule as SciPy applies it. After each least-squares fit on the current knots, the squared residuals are summed over every -interval and every -interval (a point on a knot belongs to the interval on its right). The direction whose largest interval sum is the larger gets the knot ( on a tie; the other direction once one has reached nxest, which is ), and the knot goes to the residual-weighted mean coordinate of the points in that interval. It is not a data point, nor a midpoint.
  • The penalty weight is found by the same rational iteration as for curves, starting from FITPACK’s first weight: the number of coefficients over the sum of the diagonal of the triangular factor of the least-squares problem.

bisplrep_lsq is the least-squares surface on given knots: SciPy’s bisplrep(task=-1) and LSQBivariateSpline. As in FITPACK, the boundary knots are moved to the data’s range and points outside it are clamped.

/// A smoothing spline surface through scattered data with automatically placed knots (SciPy's
/// `bisplrep` / `SmoothBivariateSpline`, after FITPACK's `surfit`): of the splines with
/// `Σ (wᵢ (zᵢ − s(xᵢ, yᵢ)))² ≤ smoothing`, the one whose `kx`-th x- and `ky`-th y-derivatives
/// jump least across the knots. `smoothing = None` gives SciPy's default `m − √(2m)`.
///
/// Starting from a single polynomial patch, one knot at a time is added in the direction (x or y)
/// whose largest interval residual sum is the larger, at the residual-weighted mean coordinate of the
/// points in that interval (FITPACK's rule, which SciPy follows to the digit), until the
/// least-squares surface reaches the smoothing target or `nxest`, `nyest` knots (SciPy's
/// defaults); then the penalty weight `p` is found by FITPACK's rational iteration so that the
/// residual sum equals the target.
#[allow(clippy::too_many_arguments)]
pub fn bisplrep(x: &[f64], y: &[f64], z: &[f64], w: Option<&[f64]>, kx: usize, ky: usize, smoothing: Option<f64>) -> Result<SmoothBivariateSpline, ErrorsJSL> {
    let d = validate(x, y, z, w, kx, ky)?;
    let m = x.len() as f64;
    let s = smoothing.unwrap_or(m - (2.0 * m).sqrt());
    let acc = 0.001 * s;
    let (xb, xe) = (x.iter().copied().fold(f64::INFINITY, f64::min), x.iter().copied().fold(f64::NEG_INFINITY, f64::max));
    let (yb, ye) = (y.iter().copied().fold(f64::INFINITY, f64::min), y.iter().copied().fold(f64::NEG_INFINITY, f64::max));
    let nxest = ((kx as f64 + (m / 2.0).sqrt()) as usize).max(2 * kx + 3);
    let nyest = ((ky as f64 + (m / 2.0).sqrt()) as usize).max(2 * ky + 3);
    let ends = |b: f64, e: f64, k: usize| -> Vec<f64> { std::iter::repeat_n(b, k + 1).chain(std::iter::repeat_n(e, k + 1)).collect() };
    let (mut tx, mut ty) = (ends(xb, xe, kx), ends(yb, ye, ky));
    let (mut spl, mut res, mut rdiag) = fit(&d, &tx, &ty, None);
    let poly_fp = spl.fp;
    while spl.fp > s + acc && (tx.len() < nxest || ty.len() < nyest) {
        // FITPACK's `fpsurf`: the sum of squared residuals in every x-interval and every y-interval
        // (a point on a knot belongs to the interval to its right); the direction whose largest
        // interval sum is the larger gets the next knot (x on a tie, and whichever has room), and the
        // knot goes to the residual-weighted mean coordinate of the points in that interval.
        let (px, py) = (tx.len() - 2 * kx - 1, ty.len() - 2 * ky - 1);
        let (mut sx, mut sy) = (vec![0.0; px], vec![0.0; py]);
        let (mut mx, mut my) = (vec![0.0; px], vec![0.0; py]);
        for i in 0..x.len() {
            let (lx, ly) = (interval(&tx, kx, x[i]) - kx, interval(&ty, ky, y[i]) - ky);
            sx[lx] += res[i];
            sy[ly] += res[i];
            mx[lx] += res[i] * x[i];
            my[ly] += res[i] * y[i];
        }
        let argmax = |v: &[f64]| (0..v.len()).fold(0, |b, i| if v[i] > v[b] { i } else { b });
        let (jx, jy) = (argmax(&sx), argmax(&sy));
        let (can_x, can_y) = (tx.len() < nxest, ty.len() < nyest);
        let in_x = match (can_x, can_y) {
            (true, true) => sx[jx] >= sy[jy],
            (true, false) => true,
            _ => false,
        };
        let (t, k, j, sums, moments) = if in_x { (&mut tx, kx, jx, &sx, &mx) } else { (&mut ty, ky, jy, &sy, &my) };
        let (lo, hi) = (t[j + k], t[j + k + 1]);
        let knot = if sums[j] > 0.0 { moments[j] / sums[j] } else { 0.5 * (lo + hi) };
        if !(knot > lo && knot < hi) {
            break;
        }
        t.insert(j + k + 1, knot);
        (spl, res, rdiag) = fit(&d, &tx, &ty, None);
    }
    // A single polynomial patch, a fit already at the target, or a least-squares surface that
    // cannot reach it: nothing to smooth.
    if (spl.fp - s).abs() < acc || (tx.len() == 2 * kx + 2 && ty.len() == 2 * ky + 2) || spl.fp > s {
        return Ok(spl);
    }
    // Rational iteration on p for fp(p) = s, between the polynomial (p = 0) and the
    // least-squares surface (p = ∞).
    let (mut p1, mut f1) = (0.0, poly_fp - s);
    let (mut p3, mut f3) = (f64::INFINITY, spl.fp - s);
    // FITPACK's first weight: the number of coefficients over the sum of the diagonal of R.
    let mut p = ((tx.len() - kx - 1) * (ty.len() - ky - 1)) as f64 / rdiag;
    let (con1, con4, con9) = (0.1, 0.04, 0.9);
    let (mut ich1, mut ich3) = (false, false);
    let mut best = spl;
    for _ in 0..40 {
        let (cand, _, _) = fit(&d, &tx, &ty, Some(p));
        let (p2, f2) = (p, cand.fp - s);
        best = cand;
        if f2.abs() < acc {
            break;
        }
        if !ich3 {
            if f2 - f3 <= acc {
                (p3, f3) = (p2, f2);
                p *= con4;
                if p <= p1 {
                    p = p1 * con9 + p2 * con1;
                }
                continue;
            }
            if f2 < 0.0 {
                ich3 = true;
            }
        }
        if !ich1 {
            if f1 - f2 <= acc {
                (p1, f1) = (p2, f2);
                p /= con4;
                if p3.is_finite() && p <= p3 {
                    p = p2 * con1 + p3 * con9;
                }
                continue;
            }
            if f2 > 0.0 {
                ich1 = true;
            }
        }
        if f1 <= f2 || f2 <= f3 {
            break;
        }
        p = fprati(p1, f1, p2, f2, p3, f3);
        if f2 < 0.0 {
            (p3, f3) = (p2, f2);
        } else {
            (p1, f1) = (p2, f2);
        }
    }
    Ok(best)
}

Table 3.16. Smoothing surfaces against SciPy's bisplrep.

Surface, 400 noisy samples of sin 6x cos 4y (σ = 0.05)Library against SciPyLibrary error on a 21 × 21 gridSciPy error
bisplrep_lsq, knots 0, ¼, ½, ¾, 1 in each direction (SciPy’s task=-1)coefficients 3e-14, values 1e-140.5010.501
bisplrep, weights 1/σ, default s = m − √(2m) = 371.7fp 371.82 vs 371.82; 11 × 11 knots vs 11 × 11; surfaces differ by 9e-70.1250.125

The least-squares surface is SciPy’s to rounding. The smoothing surface has SciPy’s knots (checked in the tests to , in 1 to 5 interior knots per direction, and on this 400-point example: knots in both), the same to the printed digits, and a surface that differs from SciPy’s by , which is the tolerance of the iteration for the penalty weight. Before 2.44 the knots were placed at the middle of the worst panel and the surfaces differed by .

Strengths

  • The knots follow the data, so a smooth fit needs far fewer coefficients than an interpolating or penalised spline on all the data points.
  • One parameter, , has a statistical meaning: the residual one expects from the noise.
  • The same knots as SciPy’s make_splrep, so results transfer between the two.
  • The Bernstein basis gives stable evaluation and a direct handle on derivatives at the breakpoints.

Weaknesses

  • Knots are restricted to data points, and the greedy placement is not optimal. Free-knot splines can do better with fewer knots at much greater cost.
  • A small with even degree can make the search for fail; converged then reports it.
  • Knots of smoothing surfaces are placed by the greedy rule above; like the curve’s, it is a heuristic that does not search for the best knots.

Exercises

  1. Why does the least-squares spline on a knot vector have a smaller residual than any spline on fewer of the same knots?
  2. Show that for the minimiser tends to a polynomial of degree on the whole interval. (Hint: what does zero jump of at every interior knot mean?)
  3. Show that de Casteljau’s algorithm with evaluates .
  4. From , show that .
  5. With weights and , what range of does Dierckx recommend?
Hints and answers
  1. The splines on fewer knots are a subspace of those on more, and the least-squares fit minimises over the larger space.
  2. Then the penalty dominates, forcing every jump to zero, so is constant across all knots and is a single polynomial; among those, the data term picks the least-squares one.
  3. One round gives and ; the second combines them into the stated expression.
  4. Only and have non-zero derivatives at , and , and .
  5. , about 67 to 93.

Further reading

  • P. Dierckx, “An algorithm for smoothing, differentiation and integration of experimental data using spline functions”, Journal of Computational and Applied Mathematics 1 (1975) 165–184.
  • P. Dierckx, “Algorithms for smoothing data with periodic and parametric splines”, Computer Graphics and Image Processing 20 (1982) 171–184.
  • P. Dierckx, Curve and Surface Fitting with Splines, Oxford University Press (1993).
  • G. Farin, Curves and Surfaces for CAGD: A Practical Guide, 5th ed., Morgan Kaufmann (2002).
  • R. T. Farouki, “The Bernstein polynomial basis: a centennial retrospective”, Computer Aided Geometric Design 29 (2012) 379–419.