packages

interpolate

On this page

Interpolation, splines, smoothing and integration of data on core's Array.

Modules

  • bspline B-splines: a spline of degree k as coefficients on a knot vector, evaluated by de Boor's algorithm, with derivatives, antiderivatives, integrals and roots; built by interpolation (make_interp_spline), least squares (make_lsq_spline) or smoothing (splrep).
  • curve The interface of every 1-d interpolant, and what it does outside its data.
  • diff Numerical differentiation: gradients of samples on 1-d and N-d grids, finite-difference weights for any stencil (Fornberg 1988), smooth derivatives of uniform samples to a chosen order of accuracy, and derivatives of functions by Ridders' extrapolation.
  • integrate Integration: rules for sampled data, adaptive Gauss-Kronrod, Romberg and Gauss-Legendre for functions, and nested double and triple integrals.
  • ops Notation for calculus on interpolants (feature ops, on by default): ∂(s), ∂(s, n) derivative of a spline or polynomial, as a spline or polynomial (autodiff's ∂, also for functions) ∇(a) gradient of samples on a unit grid, as samples (autodiff's ∇, also for functions) ∫(f, a..b) definite integral of a function (adaptive quadrature) a ≈ b approximately equal, for floats and arrays (==) s ⊗ t tensor product of two 1-d splines (linalg's ⊗) ∂ and ∇ are autodiff's, re-exported: they give the derivative in the form of what they are given, never a value at a point (∂(s)(x) is the value), and this module only adds the interpolants to them, so it imports together with optimize's ops.
  • poly Polynomials: power series and Chebyshev series.
  • ppoly Piecewise polynomials: the form every cubic interpolant (spline, PCHIP, Akima, Hermite) is evaluated, differentiated, integrated and solved in.
  • scatter Scattered data in any dimension: a k-d tree, robust predicates, the 2-d Delaunay triangulation, and interpolants on top of them.
  • smooth Smoothing noisy samples: penalized cubic splines, Savitzky-Golay filters and LOWESS.

Re-exports

bspline::{BSpline, splev, splint, sproot}Source

pub use bspline::{BSpline, splev, splint, sproot}
  • BSpline A spline of degree k, s(x) = sum_i c[i] B[i, k](x), on the knots t (n + k + 1 of them, non-decreasing) with n coefficients.
  • splev b at every element of x (its der-th derivative when der > 0), FITPACK's splev.
  • splint The integral of b over r, FITPACK's splint.
  • sproot The roots of b in its base interval, FITPACK's sproot.

curve::{Curve, Extrapolate}Source

pub use curve::{Curve, Extrapolate}
  • Curve A function of one variable built from data.
  • Extrapolate What an interpolant gives outside [x[0], x[n - 1]].

diff::{Estimate, derivative, differentiate, fd_weights, gradient, gradient_nd}Source

pub use diff::{Estimate, derivative, differentiate, fd_weights, gradient, gradient_nd}
  • Estimate An estimate and its error, from derivative.
  • derivative The derivative of order n (1 or 2) of f at x by Ridders' method: central differences on steps falling from h (by default 0.1 max(1, |x|)) by 1.4, extrapolated in a Neville table, stopping when the error grows.
  • differentiate The deriv-th derivative of uniform samples y with step dx, with error O(dx^accuracy) (accuracy even, 2 by default): central stencils of 2 floor((deriv + 1) / 2) - 1 + accuracy points inside, one-sided stencils of deriv + accuracy points near the ends, all from fd_weights.
  • fd_weights The weights w with sum_i w[i] f(stencil[i]) ~ f^(m)(x0), by Fornberg's recursion (Math.
  • gradient The derivative of samples y at positions x (a vector of the same length) or with a uniform step dx (default 1), as NumPy's gradient: second-order central differences inside (the three-point formula for uneven steps), one-sided differences of order edge_order (1 or 2) at the ends.
  • gradient_nd The gradient of an array of any rank: one array per axis, each the derivative along that axis as gradient computes it.

integrate::{Quad, cumulative_trapezoid, dblquad, dblquad_over, fixed_quad, gauss_legendre, quad, romb, romberg, simpson, tplquad, tplquad_over, trapezoid}Source

pub use integrate::{Quad, cumulative_trapezoid, dblquad, dblquad_over, fixed_quad, gauss_legendre, quad, romb, romberg, simpson, tplquad, tplquad_over, trapezoid}
  • Quad The result of an adaptive integration: the estimate, an estimate of its absolute error, the integrand evaluations it took and the subintervals it ended with.
  • cumulative_trapezoid The running trapezoid integral: element i is the integral from x[0] to x[i + 1] (n - 1 values), or with initial given, from x[0] to x[i] plus initial (n values, the first initial).
  • dblquad The integral of f(x, y) over the rectangle rx x ry (ends may be infinite), x outer: quad over x of quad over y.
  • dblquad_over The integral of f(x, y) over x in rx and y in ry(x), inner limits as a function of x.
  • fixed_quad The integral of f over the finite range r by the n-point Gauss-Legendre rule (default 5): exact for polynomials of degree up to 2n - 1, n evaluations, no error estimate.
  • gauss_legendre The nodes and weights of the n-point Gauss-Legendre rule on [-1, 1], nodes rising.
  • quad The integral of f over r by adaptive Gauss-Kronrod quadrature with extrapolation (QUADPACK's QAGS; QAGI when an end is infinite, f64::INFINITY / f64::NEG_INFINITY).
  • romb Romberg integration of 2^k + 1 uniform samples with step dx: trapezoid sums on the nested grids, extrapolated by Richardson's table to O(h^(2k + 2)).
  • romberg The integral of f over the finite range r by Romberg's method: trapezoid sums with 2^k intervals, k up to divmax, and Richardson extrapolation to O(h^(2k + 2)).
  • simpson Composite Simpson's rule for samples y at positions x or with a uniform step dx (default 1).
  • tplquad The integral of f(x, y, z) over the box rx x ry x rz, nested as dblquad.
  • tplquad_over The integral of f(x, y, z) over x in rx, y in ry(x) and z in rz(x, y).
  • trapezoid The trapezoid rule for samples y at positions x (a vector of the same length, any order: a falling x gives the negative), or a uniform step dx (default 1).

poly::chebyshev::ChebyshevSource

pub use poly::chebyshev::Chebyshev

poly::polynomial::PolynomialSource

pub use poly::polynomial::Polynomial
  • Polynomial A polynomial with real coefficients, lowest power first.

ppoly::PPolySource

pub use ppoly::PPoly
  • PPoly A piecewise polynomial of degree k on rising breakpoints `b[0] < ...

scatter::{Delaunay, KdTree, Kernel, LinearND, NearestND, Neighbors, Rbf, griddata}Source

pub use scatter::{Delaunay, KdTree, Kernel, LinearND, NearestND, Neighbors, Rbf, griddata}
  • Delaunay A Delaunay triangulation of points in the plane: no point lies strictly inside the circumcircle of any triangle.
  • KdTree A k-d tree over the rows of an n x d matrix.
  • Kernel The radial function phi(r) of an Rbf, applied to eps * r.
  • LinearND Piecewise-linear interpolation of 2-d scattered data: inside each Delaunay triangle the plane through its three values (barycentric weights), so linear functions come back exactly (to rounding).
  • NearestND Nearest-neighbor interpolation in any dimension: the value of the closest data point (the lowest row among equally close ones), found with a k-d tree.
  • Neighbors The k nearest neighbors of a point: their row indices into the tree's points and their Euclidean distances, nearest first.
  • Rbf A radial basis function interpolant of scattered data in any dimension.
  • griddata The data values at points (n x d) interpolated at the rows of xi (m x d), in one call: LinearND (NaN outside the hull) or NearestND.

smooth::lowess::lowessSource

pub use smooth::lowess::lowess
  • lowess The LOWESS fit of y on x at every x, in input order (x need not be sorted).

smooth::savgol::{Edge, savgol_coeffs, savgol_filter}Source

pub use smooth::savgol::{Edge, savgol_coeffs, savgol_filter}
  • Edge How savgol_filter treats the first and last window / 2 samples.
  • savgol_coeffs The correlation weights of a Savitzky-Golay filter: output i is sum_j c[j] y[i + j - window / 2], the deriv-th derivative of the degree-polyorder least-squares fit over the window, for samples delta apart.
  • savgol_filter y filtered by a Savitzky-Golay filter (see savgol_coeffs), the ends handled by mode.

smooth::spline::make_smoothing_splineSource

pub use smooth::spline::make_smoothing_spline
  • make_smoothing_spline The cubic smoothing spline of (x, y) with weights w (default all 1) and penalty lam on integral g''^2, a natural cubic PPoly with breakpoints at x.

Structs

BarycentricSource

pub struct Barycentric

The polynomial of degree n - 1 through n samples, in barycentric form. Exact (to rounding) for polynomials of degree < n; on equispaced nodes it suffers Runge's phenomenon, so prefer Chebyshev nodes or a spline for many points. Outside the nodes it is the same polynomial (no extrapolation modes).

nabi
use interpolate::Curve;

let p = try interpolate::barycentric([0, 1, 2, 3], [1, 2, 5, 10]);    // x^2 + 1
assert((p.at(1.5) - 3.25).abs() < 1e-14 && (p.at(4.0) - 17.0).abs() < 1e-12);
  • pub fn weights(self) -> Vector<f64>§

    Source

    The weights, 1 / prod_{k != j} c (x[j] - x[k]) with the capacity scale c.

    nabi
    let p = try interpolate::barycentric([0, 1, 2], [0, 0, 0]);
    let w = p.weights();
    assert(w[0] == w[2] && w[1] == -2.0 * w[0]);
    
Trait implementations 1
  • impl Curve for Barycentric

RegularGridSource

pub struct RegularGrid<const N: usize>

An interpolant of values on a rectilinear grid of rank N: axis d has rising coordinates axes[d], and values has their lengths as its shape. Call it at a point, g([x, y]) (or g.at(..)). Linear and nearest cost O(N log n + 2^N) per point, cubic O(N log n + 4^N) after an O(n_total) fit.

nabi
use core::array::{Matrix, Vector};

let x: Vector<f64> = [0, 1, 2];
let y: Vector<f64> = [0, 10];
let z: Matrix<f64> = [[0, 10], [1, 11], [2, 12]];      // z = x + y
let g = try interpolate::bilinear(x, y, z);
assert(g([1.5, 2.5]) == 4.0);
  • pub fn extrapolate(self, mode: Extrapolate) -> RegularGrid<N>§

    Source

    This interpolant with extrapolation mode, applied per axis.

    nabi
    use interpolate::Extrapolate;
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1];
    let z: Matrix<f64> = [[0, 1], [1, 2]];
    let g = try interpolate::bilinear(x, x, z);
    assert(g.at([2.0, 0.0]) == 2.0);
    assert(g.extrapolate(Extrapolate::Clamp).at([2.0, 0.0]) == 1.0);
    assert(g.extrapolate(Extrapolate::Fill(f64::NAN)).at([2.0, 0.0]).is_nan());
    
  • pub fn method(self) -> GridMethod§

    Source

    The method.

  • pub fn at(self, p: [f64; N]) -> f64§

    Source

    The value at p.

    nabi
    use interpolate::GridMethod;
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1, 2, 3];
    let z = Matrix::<f64>::from_fn([4, 4], |i: [usize; 2]| -> f64 { (i[0] * i[0] * i[1]) as f64 });
    let g = try interpolate::grid([x, x], z, GridMethod::Cubic);
    assert((g.at([1.5, 2.5]) - 5.625).abs() < 1e-12);            // x^2 y, exactly
    
  • pub fn eval(self, points: Matrix<f64>) throws (InterpError) -> Vector<f64>§

    Source

    The values at the points in the rows of points (m x N).

    nabi
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1];
    let z: Matrix<f64> = [[0, 1], [1, 2]];
    let g = try interpolate::bilinear(x, x, z);
    let p: Matrix<f64> = [[0.5, 0.5], [1, 0.25]];
    assert(try g.eval(p) == Vector::<f64>::from([1.0, 1.25]));
    
  • pub fn mesh(self, axes: [Vector<f64>; N]) -> Array<f64, N>§

    Source

    The values on the mesh of axes: an array of shape [axes[0].len(), ...] (the outer product of the coordinates).

    nabi
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1];
    let z: Matrix<f64> = [[0, 1], [1, 2]];
    let fine: Vector<f64> = [0, 0.5, 1];
    let m = (try interpolate::bilinear(x, x, z)).mesh([fine, fine]);
    assert(m.shape() == [3, 3] && m[1, 1] == 1.0);
    
Trait implementations 1
  • impl<const N: usize> ops::Call<[f64; N]> for RegularGrid<N>

LinearSource

pub struct Linear

The piecewise-linear interpolant of samples: exact for lines, error h^2 max|f''| / 8 for smooth f and spacing h. O(log n) per point, O(1) per point in a sorted eval.

nabi
use interpolate::Curve;

let f = try interpolate::linear([0, 1, 3], [0, 10, 30]);
assert(f.at(2.0) == 20.0 && f.at(-1.0) == -10.0);
  • pub fn extrapolate(self, mode: Extrapolate) -> Linear§

    Source

    This interpolant with extrapolation mode.

    nabi
    use interpolate::{Curve, Extrapolate};
    
    let f = try interpolate::linear([0, 1], [0, 1]);
    assert(f.extrapolate(Extrapolate::Fill(7.0)).at(2.0) == 7.0);
    
  • pub fn ppoly(self) -> PPoly§

    Source

    The same function as a degree-1 PPoly, for derivatives, integrals and roots.

    nabi
    let p = try interpolate::linear([0, 1, 2], [0, 1, 0]).ppoly();
    assert(p.integrate(0.0..2.0) == 1.0);
    
Trait implementations 1

StepSource

pub struct Step

A piecewise-constant interpolant (nearest, previous, next).

nabi
use interpolate::Curve;

let f = try interpolate::nearest([0, 1, 2], [5, 6, 7]);
assert(f.at(1.4) == 6.0 && f.at(1.5) == 6.0 && f.at(1.6) == 7.0);
  • pub fn extrapolate(self, mode: Extrapolate) -> Step§

    Source

    This interpolant with extrapolation mode.

    nabi
    use interpolate::{Curve, Extrapolate};
    
    let f = try interpolate::nearest([0, 1], [3, 4]);
    assert(f.extrapolate(Extrapolate::Fill(0.0)).at(5.0) == 0.0);
    
Trait implementations 1

TensorSplineSource

pub struct TensorSpline<const N: usize>

A tensor-product spline of rank N: knots and a degree per axis and a coefficient array; call it at a point, s([x, y]). Evaluation is O(N log n + prod (k_d + 1)).

nabi
use core::array::{Matrix, Vector};

let x: Vector<f64> = [0, 1, 2, 3, 4];
let z = Matrix::<f64>::from_fn([5, 5], |i: [usize; 2]| -> f64 { (i[0] * i[1] * i[1]) as f64 });
let s = try interpolate::bicubic(x, x, z);
assert((s([2.5, 1.5]) - 5.625).abs() < 1e-12);             // x y^2
  • pub fn fit(axes: [Vector<f64>; N], values: Array<f64, N>, k: usize = 3) throws (InterpError) -> TensorSpline<N>§

    Source

    The interpolating spline of degree k (lower along an axis with fewer than k + 1 points) through values on the grid axes.

    nabi
    use interpolate::TensorSpline;
    use core::array::{Array, Vector};
    
    let x: Vector<f64> = [0, 1, 2, 3];
    let v = Array::from_fn([4, 4, 4], |i: [usize; 3]| -> f64 { (i[0] * i[1] * i[2]) as f64 });
    let s = try TensorSpline::fit([x, x, x], v, 3);
    assert((s.at([0.5, 1.5, 2.5]) - 1.875).abs() < 1e-12);
    
  • pub fn extrapolate(self, mode: Extrapolate) -> TensorSpline<N>§

    Source

    This spline with extrapolation mode, applied per axis.

    nabi
    use interpolate::Extrapolate;
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1, 2, 3];
    let z = Matrix::<f64>::from_fn([4, 4], |i: [usize; 2]| -> f64 { i[0] as f64 });
    let s = (try interpolate::bicubic(x, x, z)).extrapolate(Extrapolate::Clamp);
    assert((s.at([5.0, 1.0]) - 3.0).abs() < 1e-14);
    
  • pub fn degrees(self) -> [usize; N]§

    Source

    The degree along each axis.

  • pub fn knots(self, d: usize) -> Vector<f64>§

    Source

    The knots of axis d.

    nabi
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1, 2, 3];
    let s = try interpolate::bicubic(x, x, Matrix::<f64>::zeros([4, 4]));
    assert(s.knots(1).len() == 8);
    
  • pub fn coefficients(self) -> Array<f64, N>§

    Source

    The coefficients, an array with one axis per dimension.

  • pub fn at(self, p: [f64; N]) -> f64§

    Source

    The value at p.

    nabi
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1, 2];
    let z: Matrix<f64> = [[0, 1, 4], [1, 2, 5], [4, 5, 8]];   // x^2 + y^2
    let s = try interpolate::bicubic(x, x, z);
    assert((s.at([0.5, 1.5]) - 2.5).abs() < 1e-13);
    
  • pub fn eval(self, points: Matrix<f64>) throws (InterpError) -> Vector<f64>§

    Source

    The values at the points in the rows of points (m x N).

    nabi
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1, 2, 3];
    let z = Matrix::<f64>::from_fn([4, 4], |i: [usize; 2]| -> f64 { (i[0] * i[1]) as f64 });
    let s = try interpolate::bicubic(x, x, z);
    let p: Matrix<f64> = [[0.5, 2], [3, 3]];
    let v = try s.eval(p);
    assert((v[0] - 1.0).abs() < 1e-13 && (v[1] - 9.0).abs() < 1e-12);
    
  • pub fn partial(self, axis: usize, nu: usize = 1) -> TensorSpline<N>§

    Source

    The partial derivative of order nu along axis, a tensor spline of degree k - nu there.

    nabi
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1, 2, 3];
    let z = Matrix::<f64>::from_fn([4, 4], |i: [usize; 2]| -> f64 { (i[0] * i[0] * i[1]) as f64 });
    let s = try interpolate::bicubic(x, x, z);
    assert((s.partial(0, 1).at([1.5, 2.0]) - 6.0).abs() < 1e-12);  // d/dx x^2 y = 2 x y
    
  • pub fn integrate(self, r: [Range<f64>; N]) -> f64§

    Source

    The integral over the box r[0] x r[1] x ..., each range in or beyond the base interval (the end pieces continue).

    nabi
    use core::array::{Matrix, Vector};
    
    let x: Vector<f64> = [0, 1, 2, 3];
    let z = Matrix::<f64>::from_fn([4, 4], |i: [usize; 2]| -> f64 { (i[0] * i[1]) as f64 });
    let s = try interpolate::bicubic(x, x, z);
    assert((s.integrate([0.0..2.0, 0.0..3.0]) - 9.0).abs() < 1e-12);
    
Trait implementations 1
  • impl<const N: usize> ops::Call<[f64; N]> for TensorSpline<N>

Enums

BoundarySource

pub enum Boundary

The end conditions of a cubic spline.

nabi
use interpolate::{Boundary, Curve};

let s = try interpolate::cubic_spline_with([0, 1, 2], [0, 1, 0], Boundary::Natural);
assert(s.derivative(2).at(0.0).abs() < 1e-14);
  • NotAKnot§

    Source

    The first two and last two pieces are one cubic (third derivative continuous at x[1] and x[n - 2]); the default. Exact for cubics.

  • Natural§

    Source

    Zero second derivative at both ends.

  • Clamped§

    Source

    Zero slope at both ends.

  • Slopes(f64, f64)§

    Source

    The given first derivatives at the start and the end.

  • Curvatures(f64, f64)§

    Source

    The given second derivatives at the start and the end.

  • Periodic§

    Source

    Periodic: value, slope and curvature match at both ends; needs y[0] == y[n - 1].

InterpErrorSource

pub enum InterpError

What went wrong building or evaluating an interpolant, a fit or an integral.

nabi
use interpolate::InterpError;
use core::array::Vector;

let x: Vector<f64> = [0, 2, 1];
let y: Vector<f64> = [0, 1, 2];
let e = try {
    _ = try interpolate::linear(x, y);
    InterpError::NotFinite { what: "" }
} catch e: InterpError { e };
assert(e == InterpError::NotSorted { at: 2 });
assert(f"{e}".contains("sort"));
  • TooFewPoints§

    Source

    The method needs at least need points and got got.

  • NotSorted§

    Source

    The sample positions must rise strictly; at is the first index that does not.

  • LengthMismatch§

    Source

    Two inputs that must agree in length or shape do not; what names both.

  • NotFinite§

    Source

    An input holds NaN or an infinity; what names it.

  • BadArgument§

    Source

    An argument is out of its range; what says which and what fits.

  • Singular§

    Source

    A linear system of the method is singular (repeated points, or a degenerate configuration); what names it.

  • NoConvergence§

    Source

    An iteration stopped after iterations steps short of the tolerance; value and error are the best estimate so far.

Trait implementations 2
  • impl Display for InterpError
  • impl Error for InterpError

GridMethodSource

pub enum GridMethod

How RegularGrid interpolates between grid points.

nabi
use interpolate::GridMethod;
use core::array::{Matrix, Vector};

let x: Vector<f64> = [0, 1];
let z: Matrix<f64> = [[0, 1], [2, 3]];
let g = try interpolate::grid([x, x], z, GridMethod::Nearest);
assert(g.at([0.4, 0.6]) == 1.0);
  • Multilinear (bilinear in 2-d): exact for functions linear in each coordinate; C0.

  • Nearest§

    Source

    The value at the closest grid point (the lower one at a tie).

  • A tensor-product not-a-knot cubic spline (lower degree along an axis of fewer than 4 points); C2, exact for cubics in each coordinate.

StepKindSource

pub enum StepKind

Which sample a step interpolant takes.

nabi
use interpolate::{Curve, StepKind};

let f = try interpolate::step([0, 1, 2], [5, 6, 7], StepKind::Next);
assert(f.at(0.2) == 6.0);
  • Nearest§

    Source

    The closest sample; the lower one at a midpoint.

  • Previous§

    Source

    The last sample at or before x.

  • The first sample at or after x.

Functions

barycentricSource

pub fn barycentric<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> Barycentric

The barycentric interpolant through (x[i], y[i]) (at least 1 point, x rising strictly). The weights are scaled by the capacity 4 / (x[n - 1] - x[0]) per factor so they neither overflow nor underflow for large n.

nabi
use interpolate::Curve;
use core::array::Vector;

// 21 Chebyshev points of the second kind on [-1, 1].
let x = Vector::<f64>::from_fn([21], |i: [usize; 1]| -> f64 { -(f64::PI * (i[0] as f64) / 20.0).cos() });
let y = f64::exp.(x);
let p = try interpolate::barycentric(x, y);
assert((p.at(0.3) - 0.3.exp()).abs() < 1e-15);

make_interp_splineSource

pub fn make_interp_spline<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y, k: usize = 3, bc: Boundary = Boundary::NotAKnot) throws (InterpError) -> BSpline

The interpolating B-spline of degree k (default 3) through the samples, scipy's make_interp_spline. Knots: k = 0 steps at the data, k = 1 the data, odd k not-a-knot (interior knots at the data with the (k - 1) / 2 nearest each end left out), even k the midpoints between samples, likewise trimmed. bc other than NotAKnot needs k = 3 (the data as knots and one derivative condition at each end); Periodic is cubic_spline_with's job. O(n k^2).

nabi
use interpolate::{Boundary, Curve};

let b = try interpolate::make_interp_spline([0, 1, 2, 3, 4], [0, 1, 16, 81, 256], 4);
assert((b.at(2.5) - 39.0625).abs() < 1e-11);              // x^4, degree 4
let n = try interpolate::make_interp_spline([0, 1, 2], [0, 1, 0], 3, Boundary::Natural);
assert(n.derivative(2).at(0.0).abs() < 1e-14);

make_lsq_splineSource

pub fn make_lsq_spline<X: AsVector<f64>, Y: AsVector<f64>, T: AsVector<f64>>(x: X, y: Y, t: T, k: usize = 3, w: Vector<f64> | none = none) throws (InterpError) -> BSpline

The weighted least-squares spline of degree k on the knots t (scipy's make_lsq_spline): minimizes sum (w[i] (y[i] - s(x[i])))^2. The data must meet the Schoenberg-Whitney conditions (each basis function has a sample where it is nonzero, in order), else the normal equations are singular. Banded Cholesky, O(m k^2).

nabi
use interpolate::Curve;
use core::array::Vector;

let x: Vector<f64> = [0, 1, 2, 3, 4, 5, 6];
let y = x .* x;                                   // a parabola, exactly
let t: Vector<f64> = [0, 0, 0, 0, 3, 6, 6, 6, 6];
let s = try interpolate::make_lsq_spline(x, y, t);
assert((s.at(2.5) - 6.25).abs() < 1e-12);

splrepSource

pub fn splrep<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y, k: usize = 3, s: f64 = 0.0, w: Vector<f64> | none = none) throws (InterpError) -> BSpline

A smoothing spline of degree k (1 to 5, default 3), FITPACK's splrep: the spline with the fewest knots and the least roughness whose weighted residual sum sum (w[i] (y[i] - s(x[i])))^2 is at most s. s = 0 (the default) interpolates; with weights 1 / sigma[i] a good s is in m - sqrt(2 m) ..= m + sqrt(2 m) for m samples. Larger s gives a smoother curve; past the residual of the least-squares polynomial of degree k the answer is that polynomial. Knots are data points, so the fit always exists; O(m k^2) per trial fit, a few dozen trials.

nabi
use interpolate::Curve;
use core::array::Vector;

let x = Vector::<f64>::from(num::linspace(0.0, 6.0, 61));
let y = f64::sin.(x) .+ 0.1 .* f64::cos.(x .* 37.0);       // a wiggle on a sine
let s = try interpolate::splrep(x, y, s: 0.3);
assert(s.knots().len() < 20);
assert((s.at(1.5) - 1.5.sin()).abs() < 0.05);

cubic_splineSource

pub fn cubic_spline<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> PPoly

The not-a-knot cubic spline through the samples (at least 2; 2 points give the line, 3 the parabola). Error 5 h^4 max|f''''| / 384 for smooth f; exact for cubics.

nabi
use interpolate::Curve;

let s = try interpolate::cubic_spline([0, 1, 2, 3, 4], [0, 1, 8, 27, 64]);
assert((s.at(2.5) - 15.625).abs() < 1e-12);

cubic_spline_withSource

pub fn cubic_spline_with<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y, bc: Boundary) throws (InterpError) -> PPoly

The cubic spline with end conditions bc (see Boundary).

nabi
use interpolate::{Boundary, Curve, Extrapolate};
use core::array::Vector;

let x: Vector<f64> = [0, 1, 2, 3];
let s = try interpolate::cubic_spline_with(x, [0, 1, 0, 0], Boundary::Periodic);
let p = s.extrapolate(Extrapolate::Periodic);
assert((p.at(3.5) - p.at(0.5)).abs() < 1e-15);
assert((s.derivative(1).at(0.0) - s.derivative(1).at(3.0)).abs() < 1e-14);

bilinearSource

pub fn bilinear<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y, z: Matrix<f64>) throws (InterpError) -> RegularGrid<2>

The bilinear interpolant of z (shape [x.len(), y.len()]) on the grid x by y.

nabi
use core::array::{Matrix, Vector};

let x: Vector<f64> = [0, 1];
let z: Matrix<f64> = [[0, 0], [0, 1]];              // z = x y
assert((try interpolate::bilinear(x, x, z)).at([0.5, 0.5]) == 0.25);

gridSource

pub fn grid<const N: usize>(axes: [Vector<f64>; N], values: Array<f64, N>, method: GridMethod = GridMethod::Linear) throws (InterpError) -> RegularGrid<N>

The interpolant of values on the grid with coordinates axes (each rising strictly, with at least 2 points; 1 point for Nearest). Outside the grid it extends the edge cells (Extrapolate::Extend); set another mode with extrapolate.

nabi
use interpolate::GridMethod;
use core::array::{Array, Vector};

let x: Vector<f64> = [0, 1, 2, 3];
let v = Array::from_fn([4, 4, 4], |i: [usize; 3]| -> f64 { (i[0] * i[1] + i[2]) as f64 });
let g = try interpolate::grid([x, x, x], v, GridMethod::Linear);
assert(g.at([1.5, 2.0, 0.5]) == 3.5);

akimaSource

pub fn akima<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> PPoly

Akima's (1970) interpolant: slopes from the four nearest secants, weighted by how much they change, so an outlier moves only the pieces next to it. C1; exact for lines. Two extra secants at each end are extrapolated linearly, as Akima does.

nabi
use interpolate::Curve;

let a = try interpolate::akima([0, 1, 2, 3, 4, 5], [0, 0, 0, 1, 1, 1]);
assert(a.at(0.5) == 0.0 && a.at(4.5) == 1.0);

cubic_hermiteSource

pub fn cubic_hermite<X: AsVector<f64>, Y: AsVector<f64>, D: AsVector<f64>>(x: X, y: Y, dydx: D) throws (InterpError) -> PPoly

The cubic Hermite interpolant with values y and slopes dydx at x: C1, exact for cubics when the slopes are exact.

nabi
use interpolate::Curve;

// x^3 with exact slopes 3x^2.
let p = try interpolate::cubic_hermite([0, 1, 2], [0, 1, 8], [0, 3, 12]);
assert((p.at(1.5) - 3.375).abs() < 1e-15);

makimaSource

pub fn makima<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> PPoly

The modified Akima interpolant (MATLAB's makima): Akima's weights plus the mean of each pair of secants, which removes the overshoot of plain Akima where the data are flat on one side.

nabi
use interpolate::Curve;

let a = try interpolate::makima([0, 1, 2, 3, 4], [0, 0, 1, 1, 1]);
assert(a.at(3.5) == 1.0);

pchipSource

pub fn pchip<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> PPoly

PCHIP, the piecewise cubic Hermite interpolating polynomial of Fritsch and Carlson (1980) with the slopes of Fritsch and Butland (1984): a weighted harmonic mean of the neighbouring secants, zero where they change sign, and a shape-preserving three-point formula at the ends. The result is C1 and monotone wherever the data are, with no overshoot at a step. Exact for lines.

nabi
use interpolate::Curve;

let p = try interpolate::pchip([0, 1, 2, 3], [0, 0, 1, 1]);
assert(p.at(0.5) == 0.0 && p.at(2.5) == 1.0);   // flat stays flat
assert(p.at(1.5) == 0.5);

linearSource

pub fn linear<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> Linear

Linear interpolation through (x[i], y[i]), x rising strictly, at least 2 points. Outside the data it continues the end segments; set another mode with extrapolate.

nabi
use interpolate::{Curve, Extrapolate};
use core::array::Vector;

let f = try interpolate::linear([1, 2, 4], [1, 4, 16]);
let xs: Vector<f64> = [1.5, 3.0];
assert(f.eval(xs) == Vector::<f64>::from([2.5, 10.0]));
assert(f.extrapolate(Extrapolate::Clamp).at(9.0) == 16.0);

nearestSource

pub fn nearest<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> Step

step(x, y, StepKind::Nearest).

nabi
use interpolate::Curve;

assert((try interpolate::nearest([0, 2], [1, 3])).at(0.9) == 1.0);

nextSource

pub fn next<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> Step

step(x, y, StepKind::Next).

nabi
use interpolate::Curve;

assert((try interpolate::next([0, 2], [1, 3])).at(0.1) == 3.0);

previousSource

pub fn previous<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y) throws (InterpError) -> Step

step(x, y, StepKind::Previous).

nabi
use interpolate::Curve;

assert((try interpolate::previous([0, 2], [1, 3])).at(1.9) == 1.0);

stepSource

pub fn step<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y, kind: StepKind) throws (InterpError) -> Step

A step interpolant of kind through the samples (at least 1). Outside the data Extend holds the end values, as Clamp does; previous before the first sample and next after the last take the end value too.

nabi
use interpolate::{Curve, StepKind};

let f = try interpolate::step([0, 10], [1, 2], StepKind::Previous);
assert(f.at(9.9) == 1.0 && f.at(10.0) == 2.0);

bicubicSource

pub fn bicubic<X: AsVector<f64>, Y: AsVector<f64>>(x: X, y: Y, z: Matrix<f64>) throws (InterpError) -> TensorSpline<2>

The tensor-product cubic spline interpolating z (shape [x.len(), y.len()]) on the grid x by y, not-a-knot along both axes (scipy's RectBivariateSpline with s = 0).

nabi
use core::array::{Matrix, Vector};

let x: Vector<f64> = [0, 1, 2, 3];
let z = Matrix::<f64>::from_fn([4, 4], |i: [usize; 2]| -> f64 { (i[0] + i[1]) as f64 });
assert(((try interpolate::bicubic(x, x, z)).at([0.5, 0.25]) - 0.75).abs() < 1e-14);