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

Piecewise polynomials, Hermite data and scattered interpolation

ProblemRepresent piecewise polynomials and differentiate, integrate and solve them; interpolate values together with derivatives; interpolate on a rectangular grid with tensor-product splines; interpolate data scattered in the plane or in any dimension
Devised byCharles Hermite (1878), interpolation with derivatives; Fred Krogh (1970), the stable Newton form for it; Hiroshi Akima (1970) and Cosmin Ionita (2019, makima); Carl de Boor (1962), tensor-product splines; Boris Delaunay (1934); Ray Clough and James Tocher (1965), the split-triangle cubic element; Gregory Nielson (1983), global gradient estimation; Rolland Hardy (1971) and Jean Duchon (1976), radial basis functions and thin-plate splines
AccuracyAgrees with SciPy to relative or better in every case
CostPPoly evaluation: a binary search and Horner’s rule; roots: a eigenproblem per piece. RectBivariateSpline: banded solves. Triangulation: ; Clough-Tocher gradients: a few hundred sweeps of ; RBF: an dense solve
Read firstPiecewise and spline interpolation, B-splines and smoothing splines, Scattered data interpolation
APIPPoly, KroghInterpolator, makima, RectBivariateSpline, LinearNDInterpolator, CloughTocher2DInterpolator, NearestNDInterpolator, griddata, RbfInterpolator

Overview

This entry completes the interpolation chapter’s coverage of scipy.interpolate:

  • PPoly, a piecewise polynomial in the power basis, with derivatives, antiderivatives, definite integrals and real roots. Every piecewise-cubic interpolant in the library (PCHIP, Akima, cubic Hermite, B-splines) converts to one.
  • Hermite data: PPoly::cubic_hermite (SciPy’s CubicHermiteSpline) for given slopes, and KroghInterpolator for one polynomial through values and derivatives of any order.
  • makima, the modified Akima interpolant, which overshoots less than Akima’s original.
  • RectBivariateSpline, interpolating tensor-product splines on a grid, with partial derivatives and integrals over rectangles.
  • Scattered data in the plane: piecewise linear (LinearNDInterpolator) and C¹ Clough-Tocher (CloughTocher2DInterpolator) interpolation on a Delaunay triangulation, nearest neighbour in any dimension, and the griddata front end.
  • RbfInterpolator: radial basis functions in any number of dimensions, with SciPy’s kernels, polynomial tails and smoothing.

Where it is used

Piecewise polynomials are the flexible container for everything spline-like.

  • Derivatives and integrals of data. Fit once, then differentiate, integrate or find roots of the fitted curve (when does a sensor signal cross a threshold?).
  • Hermite data. Values together with slopes: motion planning with prescribed velocities, shape-preserving interpolation of monotone data.
  • Scattered points. Interpolating terrain heights or measurements taken at irregular places.

History

Charles Hermite (1878) generalised Lagrange interpolation to data that include derivatives. Fred Krogh (1970) showed how to compute it stably in Newton form, with repeated nodes standing for derivatives. Hiroshi Akima (1970) designed a local cubic that avoids the wiggles of global splines. MATLAB’s makima (Cosmin Ionita, 2019) modified its weights to suppress the overshoot that remains.

Tensor-product splines go back to Carl de Boor (1962). Paul Dierckx’s FITPACK (1980s), which SciPy wraps, fits them to gridded and scattered data. For irregular points in the plane, Boris Delaunay’s (1934) triangulation gives the natural mesh. The engineers Ray Clough and James Tocher (1965) split each triangle into three cubic patches to obtain a C¹ finite element, and Gregory Nielson (1983) showed how to estimate the vertex gradients it needs from the data alone. Rolland Hardy (1971) introduced multiquadric radial basis functions for topography, and Jean Duchon (1976) derived the thin-plate spline as the minimiser of bending energy.

The idea

Piecewise polynomials

On interval , a PPoly is . Row 0 of the coefficient matrix holds the highest power, as in SciPy. Evaluation finds the interval by binary search and applies Horner’s rule. Derivatives scale the coefficients by falling factorials.

Antiderivatives divide by rising factorials, which leaves the new low-order coefficients free. They are set so that the antiderivative is zero at and continuous, with as many continuous derivatives as were added. Interval by interval, each new coefficient is the previous piece’s derivative at the shared breakpoint divided by a factorial. A definite integral is then a difference of two antiderivative values.

Roots. On each piece, the roots of the polynomial are the eigenvalues of its companion matrix. Real ones (to a small tolerance) inside the piece are kept and polished by a Newton step. The first and last pieces extend to when extrapolating. A breakpoint where the function jumps across the target value is reported too, as in SciPy’s solve(…, discontinuity=True).

Hermite data

Given values and slopes , each interval’s cubic is fixed by its four end conditions. With the interval length and the secant slope,

Krogh’s interpolant is a single polynomial through all the conditions. In Newton form, , the coefficients are divided differences. When a node is repeated, the divided difference of equal nodes becomes . Krogh’s recurrence uses exactly that, and its derivatives come from a second recurrence on the products .

Akima and makima

Akima’s slope at is a weighted average of the neighbouring secants and . The weights are the differences of the next secants out, and , so a slope follows the side where the data are changing least. On a flat stretch both weights vanish and SciPy falls back to an average. makima adds half the secants’ sizes to the weights, , which damps overshoot next to flat stretches. On the data of Figure 3.13 the not-a-knot spline overshoots by 0.22 and ripples by 0.23 across the plateau. Akima overshoots by 0.17 and makima by 0.14, both with a flat plateau, and PCHIP never overshoots.

Figure 3.13. Four cubic interpolants through data with flat stretches. The global spline rings across the plateau. Akima and makima keep it flat and overshoot less at the peak; PCHIP preserves monotonicity at the cost of a sharper shape.

Tensor-product splines

On a grid with values , the spline interpolates when , with and the one-dimensional collocation matrices. The system separates: interpolate each column of along , then each row of the result along . With smoothing , FITPACK places the interior knots at the data points except at each end. For odd degree that is the not-a-knot spline of make_interp_spline, so RectBivariateSpline uses it directly. Even degrees, where FITPACK uses other knots, are not supported. Partial derivatives differentiate the one-dimensional bases. Integrals over a rectangle are , with and the integrals of the basis functions.

Scattered data on a triangulation

The Delaunay triangulation of the data sites tiles their convex hull with triangles whose circumcircles contain no other site. Inside a triangle, linear interpolation uses the barycentric coordinates of the query point: . The result is continuous, with kinks along the edges.

Clough-Tocher builds a C¹ surface. Each triangle is split at its centroid into three sub-triangles, each carrying a cubic in Bézier form. Its 19 Bézier ordinates are fixed by three things:

  • the values and gradients at the three vertices;
  • C¹ continuity across the interior edges;
  • the requirement that the derivative across each outer edge be linear along it, so that neighbouring triangles agree.

SciPy takes that cross-edge direction towards the neighbouring triangle’s centroid rather than along the normal. Barycentric coordinates make this choice affine-invariant, so long thin triangles do not cause oscillations.

The gradients are not given, so they are estimated (Nielson, 1983). The Clough-Tocher interpolant restricted to an edge is a cubic in the end values and the end directional derivatives. The integral of its squared second derivative is then a quadratic form in the gradients. Each vertex’s gradient minimises the sum over its edges, with the neighbours’ gradients held fixed: a 2 × 2 system. Sweeping over the vertices (Gauss-Seidel) until the largest change is below gives the estimates. The sweep order is the point order, as in SciPy, so the library reproduces SciPy’s iterates, not just its limit.

Radial basis functions in any dimension

A radial basis function interpolant is

with a polynomial tail up to the degree that makes the kernel’s system solvable. The thin-plate spline and the cubic need degree 1, the quintic needs degree 2, and the linear and multiquadric need degree 0. The Gaussian and the inverse kernels need none. The coefficients solve

where and smooths. The polynomial is built on coordinates shifted and scaled into per dimension, which keeps well conditioned; that shift and scale are SciPy’s. The library’s existing 2-D RadialBasisInterpolator remains; RbfInterpolator adds any dimension, all eight kernels, polynomial tails and smoothing.

Algorithm

estimate_gradients_2d_global: set every gradient to zero; repeat up to 400 times: for each vertex , accumulate over its neighbours , with and , and ; set ; stop when the largest change, relative to the gradient when it exceeds 1, is below .

PPoly::solve(y): for each piece, subtract from the constant coefficient, drop leading zeros, take the eigenvalues of the companion matrix, keep those within of the real axis and inside the piece (or beyond it, for the end pieces when extrapolating), polish each by up to three Newton steps, then sort and merge duplicates.

Implementation

    /// The antiderivative of order `nu`, zero at `x₀` and continuous with its first `nu − 1`
    /// derivatives (SciPy's `antiderivative`): the coefficients are divided by rising factorials,
    /// and the new low-order coefficients of each piece are set from the previous piece's values
    /// at the shared breakpoint.
    pub fn antiderivative(&self, nu: usize) -> PPoly {
        let k = self.degree();
        let m = self.c.ncols();
        let rows = k + 1 + nu;
        let mut c = Array2::zeros((rows, m));
        for i in 0..=k {
            let factor: f64 = (1..=nu).map(|r| (k - i + r) as f64).product();
            for j in 0..m {
                c[(i, j)] = self.c[(i, j)] / factor;
            }
        }
        let mut out = PPoly { c, x: self.x.clone(), extrapolate: self.extrapolate };
        for j in 1..m {
            let h = out.x[j] - out.x[j - 1];
            for dx in (0..nu).rev() {
                let value = out.eval_piece(j - 1, h, dx) / (1..=dx).map(|r| r as f64).product::<f64>();
                out.c[(rows - 1 - dx, j)] = value;
            }
        }
        out
    }
    /// Builds the interpolant. `xi` lists the nodes with each repeated node consecutive; `yi[k]`
    /// is the value at `xi[k]` if it is the first copy, else the derivative whose order is the
    /// number of earlier copies. Divided differences with repeated nodes become derivatives
    /// divided by factorials, which is how `Vk[0] = yᵢ/s!` enters.
    pub fn new(xi: &[f64], yi: &[f64]) -> Result<KroghInterpolator, ErrorsJSL> {
        let n = xi.len();
        if n == 0 || yi.len() != n {
            return Err(ErrorsJSL::InvalidInputRange("need one value per node"));
        }
        let mut c = vec![0.0; n];
        c[0] = yi[0];
        let mut vk = vec![0.0; n];
        for k in 1..n {
            let mut s = 0;
            while s <= k && xi[k - s] == xi[k] {
                s += 1;
            }
            s -= 1;
            vk[0] = yi[k] / factorial(s);
            for i in 0..k - s {
                if xi[i] == xi[k] {
                    return Err(ErrorsJSL::InvalidInputRange("copies of a node must be consecutive"));
                }
                vk[i + 1] = if s == 0 { (c[i] - vk[i]) / (xi[i] - xi[k]) } else { (vk[i + 1] - vk[i]) / (xi[i] - xi[k]) };
            }
            c[k] = vk[k - s];
        }
        Ok(KroghInterpolator { xi: xi.to_vec(), c })
    }
/// The node slopes of Akima's method (`modified = false`) or of `makima` (`modified = true`).
pub fn akima_slopes(x: VR1D, y: VR1D, modified: bool) -> Result<Vec<f64>, ErrorsJSL> {
    let d = secants(x, y)?;
    let n = x.len();
    if n < 2 {
        return Err(ErrorsJSL::IncompatibleArraySizes((n, 2)));
    }
    if n == 2 {
        return Ok(vec![d[0]; 2]);
    }
    // Extended secants: m[k+2] = d[k], with two extrapolated values at each end.
    let mut m = vec![0.0; n + 3];
    m[2..n + 1].copy_from_slice(&d);
    m[1] = 2.0 * m[2] - m[3];
    m[0] = 2.0 * m[1] - m[2];
    m[n + 1] = 2.0 * m[n] - m[n - 1];
    m[n + 2] = 2.0 * m[n + 1] - m[n];
    let weight = |a: f64, b: f64| (a - b).abs() + if modified { 0.5 * (a + b).abs() } else { 0.0 };
    let f1: Vec<f64> = (0..n).map(|i| weight(m[i + 3], m[i + 2])).collect();
    let f2: Vec<f64> = (0..n).map(|i| weight(m[i + 1], m[i])).collect();
    let f12: Vec<f64> = f1.iter().zip(&f2).map(|(a, b)| a + b).collect();
    let cutoff = 1e-9 * f12.iter().copied().fold(f64::NEG_INFINITY, f64::max);
    Ok((0..n)
        .map(|i| if f12[i] > cutoff { m[i + 1] + f2[i] / f12[i] * (m[i + 2] - m[i + 1]) } else { 0.5 * (m[i + 3] + m[i]) })
        .collect())
}
/// Gradient estimates at the vertices that minimise the integrated squared second derivative of
/// the Clough-Tocher interpolant along every edge (Nielson's global method, SciPy's
/// `estimate_gradients_2d_global`). Each vertex's 2 × 2 local problem is solved in turn with the
/// current estimates at its neighbours (Gauss-Seidel), until the largest change is below `tol`
/// (relative to the gradient, or absolute when it is below 1) or after `max_iterations` sweeps.
pub fn estimate_gradients_2d_global(tri: &TriangulationIndex, values: &[f64], tol: f64, max_iterations: usize) -> Vec<[f64; 2]> {
    let nbrs = tri.vertex_neighbors();
    let mut y = vec![[0.0; 2]; tri.points.len()];
    for _ in 0..max_iterations {
        let mut err = 0.0f64;
        for ip in 0..tri.points.len() {
            let (mut q0, mut q1, mut q3, mut s0, mut s1) = (0.0, 0.0, 0.0, 0.0, 0.0);
            for &jp in &nbrs[ip] {
                let ex = tri.points[jp][0] - tri.points[ip][0];
                let ey = tri.points[jp][1] - tri.points[ip][1];
                let l = ex.hypot(ey);
                let l3 = l * l * l;
                let (f1, f2) = (values[ip], values[jp]);
                let df2 = -ex * y[jp][0] - ey * y[jp][1];
                q0 += 4.0 * ex * ex / l3;
                q1 += 4.0 * ex * ey / l3;
                q3 += 4.0 * ey * ey / l3;
                s0 += (6.0 * (f1 - f2) - 2.0 * df2) * ex / l3;
                s1 += (6.0 * (f1 - f2) - 2.0 * df2) * ey / l3;
            }
            let det = q0 * q3 - q1 * q1;
            let r0 = (q3 * s0 - q1 * s1) / det;
            let r1 = (-q1 * s0 + q0 * s1) / det;
            let change = (y[ip][0] + r0).abs().max((y[ip][1] + r1).abs()) / r0.abs().max(r1.abs()).max(1.0);
            y[ip] = [-r0, -r1];
            err = err.max(change);
        }
        if err < tol {
            break;
        }
    }
    y
}
    /// Fits the interpolant to values `d` at points `y` (rows). `epsilon` defaults to 1 for the
    /// scale-invariant kernels and is required otherwise; `degree` defaults to the kernel's
    /// minimum (at least 0); `smoothing` (≥ 0) relaxes interpolation to a least-squares fit. The
    /// system `[K + λI, P; Pᵀ, 0] [a; b] = [d; 0]` is solved by LU, with the polynomial built on
    /// coordinates shifted and scaled into `[−1, 1]`.
    pub fn new(y: &[Vec<f64>], d: &[f64], kernel: RbfKernel, epsilon: Option<f64>, degree: Option<i32>, smoothing: f64) -> Result<RbfInterpolator, ErrorsJSL> {
        let p = y.len();
        if p == 0 || d.len() != p {
            return Err(ErrorsJSL::InvalidInputRange("need one value per point"));
        }
        let ndim = y[0].len();
        if y.iter().any(|r| r.len() != ndim) {
            return Err(ErrorsJSL::InvalidInputRange("all points must have the same dimension"));
        }
        let epsilon = match epsilon {
            Some(e) => e,
            None if kernel.scale_invariant() => 1.0,
            None => return Err(ErrorsJSL::InvalidInputRange("this kernel needs a shape parameter epsilon")),
        };
        let degree = degree.unwrap_or(kernel.min_degree().max(0));
        let powers = monomial_powers(ndim, degree);
        let r = powers.len();
        let mut shift = vec![0.0; ndim];
        let mut scale = vec![1.0; ndim];
        for k in 0..ndim {
            let lo = y.iter().map(|v| v[k]).fold(f64::INFINITY, f64::min);
            let hi = y.iter().map(|v| v[k]).fold(f64::NEG_INFINITY, f64::max);
            shift[k] = (hi + lo) / 2.0;
            scale[k] = if hi == lo { 1.0 } else { (hi - lo) / 2.0 };
        }
        let mut lhs = Array2::zeros((p + r, p + r));
        for i in 0..p {
            for j in 0..p {
                let dist = y[i].iter().zip(&y[j]).map(|(a, b)| (a * epsilon - b * epsilon).powi(2)).sum::<f64>().sqrt();
                lhs[(i, j)] = kernel.eval(dist);
            }
            lhs[(i, i)] += smoothing;
            for (m, pw) in powers.iter().enumerate() {
                let v: f64 = (0..ndim).map(|k| ((y[i][k] - shift[k]) / scale[k]).powi(pw[k] as i32)).product();
                lhs[(i, p + m)] = v;
                lhs[(p + m, i)] = v;
            }
        }
        let mut rhs = Array1::zeros(p + r);
        for i in 0..p {
            rhs[i] = d[i];
        }
        let coeffs = lhs.solve(&rhs).map_err(|_| ErrorsJSL::RuntimeError("singular RBF system: too few points for the polynomial degree?"))?;
        Ok(RbfInterpolator { y: y.to_vec(), kernel, epsilon, powers, shift, scale, coeffs })
    }
  • PiecewiseHermite::to_ppoly turns PCHIP, Akima and makima interpolants into PPolys, and PPoly::from_spline does the same for B-splines. from_spline keeps only the distinct knots as breakpoints; SciPy also keeps zero-length intervals at repeated knots.
  • akima now uses SciPy’s exact weights, cutoff and fill value, so the two agree to rounding.
  • Points outside a RectBivariateSpline’s grid are clamped to its edge, as in FITPACK.
  • Point location uses a bucket grid over the triangles. Points on an edge are accepted with a slack of in the barycentric coordinates, as in Qhull.
  • Linear and Clough-Tocher interpolation are 2-D only. SciPy’s LinearNDInterpolator also handles 3-D and higher through Qhull.

In practice

Every function is compared with SciPy 1.17.1 (references from book/generator/data/make_piecewise_refs.py). The scattered data are 60 random points in the unit square plus its corners, with , and the RBF data are 50 random points in :

Table 3.12. Piecewise polynomials, Hermite data, tensor-product splines and scattered interpolation against SciPy.

computation (SciPy reference)largest difference (relative to the largest value)
PPoly.from_spline: values, first and second derivatives (with extrapolation)4e-15
integrate on [0.3, 3.7] and [−0.5, 4.5]; second antiderivative8e-16
roots (4, two by extrapolation) and solve(0.5)4e-15
CubicHermiteSpline: values and slopes1e-15
CubicHermiteSpline: integral, roots and solve(0.25)4e-16
Akima1DInterpolator, Akima’s data and data with flat stretches1e-15
Akima1DInterpolator(method="makima"), the same data1e-15
KroghInterpolator with derivative data: values and derivatives 0–36e-15
RectBivariateSpline, degrees (3, 3): values, ∂x and ∂x∂y, integral2e-15
RectBivariateSpline, degrees (1, 1): values, integral5e-16
RectBivariateSpline, degrees (5, 3): values, ∂x and ∂x∂y, integral4e-15
LinearNDInterpolator, 64 scattered points, 169 queries3e-16
estimate_gradients_2d_global (Nielson’s method, tolerance 10⁻⁶)6e-16
CloughTocher2DInterpolator7e-16
NearestNDInterpolator0
griddata outside the hull: NaN and NaN (SciPy: NaN)0
RBFInterpolator in 3-D: 8 kernels, smoothing, degree 2 (largest: quintic)1e-14

How do the scattered-data methods compare as points are added? For Franke’s test function, the RMS error falls like for linear interpolation (error with ). For Clough-Tocher it falls like or faster once the triangles resolve the function. From about 400 points on, the thin-plate spline is another 2–3 times more accurate:

Figure 3.14. Interpolating Franke's function from random points in the unit square. With 800 points, Clough-Tocher is about 9 times and the thin-plate spline about 23 times more accurate than linear interpolation. The RBF costs an 800 × 800 dense solve; the triangulation methods cost .

Strengths

  • One piecewise-polynomial type with derivatives, integrals and roots for every piecewise interpolant.
  • Clough-Tocher and RBF interpolation that reproduce SciPy to rounding, including its gradient iteration and polynomial scaling.
  • Tensor-product splines with partial derivatives and rectangle integrals.

Weaknesses

  • Triangulation-based methods are 2-D only; RBFs cover higher dimensions but cost , and there is no neighbors option for local RBF fits.
  • RectBivariateSpline supports only odd degrees and (no smoothing).
  • No Bernstein-basis BPoly, and no PPoly.extend.

Exercises

  1. Show that the antiderivative coefficients of a piece are , and why the remaining coefficients are free.
  2. Derive the cubic Hermite coefficients from , , , .
  3. Show that the divided difference with copies equals .
  4. Why does linear interpolation on a triangulation have error , and Clough-Tocher for smooth data with exact gradients?
  5. Show that the thin-plate spline system has a unique solution when the data sites are not collinear.
Hints and answers
  1. Integrating times gives divided by the rising factorial. Polynomials of degree below have zero -th derivative, so they can be added freely: they are fixed by continuity.
  2. ; the conditions at give and ; solve for and .
  3. As the nodes coalesce, for some between them, by the mean-value theorem for divided differences; in the limit .
  4. Linear interpolation is exact for degree 1, so the error is governed by the second derivatives times . Clough-Tocher is exact for cubics, so the error is ; with estimated gradients the gradient error usually limits it to about .
  5. The kernel is conditionally positive definite of order 2: for with . Together with having full column rank (non-collinear sites), this makes the saddle-point matrix non-singular.

Further reading

  • F. T. Krogh, “Efficient algorithms for polynomial interpolation and numerical differentiation”, Mathematics of Computation 24 (1970) 185–190.
  • H. Akima, “A new method of interpolation and smooth curve fitting based on local procedures”, Journal of the ACM 17 (1970) 589–602.
  • C. de Boor, A Practical Guide to Splines, revised ed., Springer, 2001.
  • P. Dierckx, Curve and Surface Fitting with Splines, Oxford University Press, 1993.
  • R. W. Clough and J. L. Tocher, “Finite element stiffness matrices for analysis of plate bending”, Proceedings of the Conference on Matrix Methods in Structural Mechanics, Wright-Patterson Air Force Base, 1965, 515–545.
  • G. M. Nielson, “A method for interpolating scattered data based upon a minimum norm network”, Mathematics of Computation 40 (1983) 253–271.
  • G. E. Fasshauer, Meshfree Approximation Methods with MATLAB, World Scientific, 2007.
  • R. Franke, “Scattered data interpolation: tests of some methods”, Mathematics of Computation 38 (1982) 181–200.