interpolate
On this page
- Modules
- Re-exports
- Structs
Barycentric1RegularGrid5Linear2Step1- Enums
- Functions
Interpolation, splines, smoothing and integration of data on core's
Array.
Modules
bsplineB-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).curveThe interface of every 1-d interpolant, and what it does outside its data.diffNumerical 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.integrateIntegration: rules for sampled data, adaptive Gauss-Kronrod, Romberg and Gauss-Legendre for functions, and nested double and triple integrals.opsNotation for calculus on interpolants (featureops, 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'sops.polyPolynomials: power series and Chebyshev series.ppolyPiecewise polynomials: the form every cubic interpolant (spline, PCHIP, Akima, Hermite) is evaluated, differentiated, integrated and solved in.scatterScattered data in any dimension: a k-d tree, robust predicates, the 2-d Delaunay triangulation, and interpolants on top of them.smoothSmoothing 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}BSplineA spline of degreek,s(x) = sum_i c[i] B[i, k](x), on the knotst(n + k + 1 of them, non-decreasing) withncoefficients.splevbat every element ofx(itsder-th derivative whender > 0), FITPACK'ssplev.splintThe integral ofboverr, FITPACK'ssplint.sprootThe roots ofbin its base interval, FITPACK'ssproot.
curve::{Curve, Extrapolate}Source
pub use curve::{Curve, Extrapolate}CurveA function of one variable built from data.ExtrapolateWhat 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}EstimateAn estimate and its error, fromderivative.derivativeThe derivative of ordern(1 or 2) offatxby Ridders' method: central differences on steps falling fromh(by default 0.1 max(1, |x|)) by 1.4, extrapolated in a Neville table, stopping when the error grows.differentiateThederiv-th derivative of uniform samplesywith stepdx, with error O(dx^accuracy) (accuracyeven, 2 by default): central stencils of2 floor((deriv + 1) / 2) - 1 + accuracypoints inside, one-sided stencils ofderiv + accuracypoints near the ends, all fromfd_weights.fd_weightsThe weightswwithsum_i w[i] f(stencil[i]) ~ f^(m)(x0), by Fornberg's recursion (Math.gradientThe derivative of samplesyat positionsx(a vector of the same length) or with a uniform stepdx(default 1), as NumPy'sgradient: second-order central differences inside (the three-point formula for uneven steps), one-sided differences of orderedge_order(1 or 2) at the ends.gradient_ndThe gradient of an array of any rank: one array per axis, each the derivative along that axis asgradientcomputes 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}QuadThe 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_trapezoidThe running trapezoid integral: elementiis the integral fromx[0]tox[i + 1](n - 1 values), or withinitialgiven, fromx[0]tox[i]plusinitial(n values, the firstinitial).dblquadThe integral off(x, y)over the rectanglerxxry(ends may be infinite),xouter:quadoverxofquadovery.dblquad_overThe integral off(x, y)overxinrxandyinry(x), inner limits as a function ofx.fixed_quadThe integral offover the finite rangerby the n-point Gauss-Legendre rule (default 5): exact for polynomials of degree up to 2n - 1, n evaluations, no error estimate.gauss_legendreThe nodes and weights of the n-point Gauss-Legendre rule on [-1, 1], nodes rising.quadThe integral offoverrby adaptive Gauss-Kronrod quadrature with extrapolation (QUADPACK's QAGS; QAGI when an end is infinite,f64::INFINITY/f64::NEG_INFINITY).rombRomberg integration of2^k + 1uniform samples with stepdx: trapezoid sums on the nested grids, extrapolated by Richardson's table to O(h^(2k + 2)).rombergThe integral offover the finite rangerby Romberg's method: trapezoid sums with 2^k intervals, k up todivmax, and Richardson extrapolation to O(h^(2k + 2)).simpsonComposite Simpson's rule for samplesyat positionsxor with a uniform stepdx(default 1).tplquadThe integral off(x, y, z)over the boxrxxryxrz, nested asdblquad.tplquad_overThe integral off(x, y, z)overxinrx,yinry(x)andzinrz(x, y).trapezoidThe trapezoid rule for samplesyat positionsx(a vector of the same length, any order: a fallingxgives the negative), or a uniform stepdx(default 1).
poly::chebyshev::ChebyshevSource
pub use poly::chebyshev::ChebyshevChebyshevA Chebyshev series on[a, b].
poly::polynomial::PolynomialSource
pub use poly::polynomial::PolynomialPolynomialA polynomial with real coefficients, lowest power first.
ppoly::PPolySource
pub use ppoly::PPolyPPolyA piecewise polynomial of degreekon 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}DelaunayA Delaunay triangulation of points in the plane: no point lies strictly inside the circumcircle of any triangle.KdTreeA k-d tree over the rows of an n x d matrix.KernelThe radial functionphi(r)of anRbf, applied toeps * r.LinearNDPiecewise-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).NearestNDNearest-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.NeighborsTheknearest neighbors of a point: their row indices into the tree's points and their Euclidean distances, nearest first.RbfA radial basis function interpolant of scattered data in any dimension.griddataThe datavaluesatpoints(n x d) interpolated at the rows ofxi(m x d), in one call:LinearND(NaN outside the hull) orNearestND.
smooth::lowess::lowessSource
pub use smooth::lowess::lowesslowessThe LOWESS fit ofyonxat everyx, in input order (xneed not be sorted).
smooth::savgol::{Edge, savgol_coeffs, savgol_filter}Source
pub use smooth::savgol::{Edge, savgol_coeffs, savgol_filter}EdgeHowsavgol_filtertreats the first and lastwindow / 2samples.savgol_coeffsThe correlation weights of a Savitzky-Golay filter: outputiissum_j c[j] y[i + j - window / 2], thederiv-th derivative of the degree-polyorderleast-squares fit over the window, for samplesdeltaapart.savgol_filteryfiltered by a Savitzky-Golay filter (seesavgol_coeffs), the ends handled bymode.
smooth::spline::make_smoothing_splineSource
pub use smooth::spline::make_smoothing_splinemake_smoothing_splineThe cubic smoothing spline of(x, y)with weightsw(default all 1) and penaltylamonintegral g''^2, a natural cubicPPolywith breakpoints atx.
Structs
BarycentricSource
pub struct BarycentricThe 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).
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);
The weights,
1 / prod_{k != j} c (x[j] - x[k])with the capacity scalec.nabilet 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.
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);
Sourcepub fn extrapolate(§self, mode: Extrapolate) -> RegularGrid<N> This interpolant with extrapolation
mode, applied per axis.nabiuse 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());
Sourcepub fn method(§self) -> GridMethod The method.
The value at
p.nabiuse 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
Sourcepub fn eval(§self, points: Matrix<f64>) throws (InterpError) -> Vector<f64> The values at the points in the rows of
points(m x N).nabiuse 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]));The values on the mesh of
axes: an array of shape[axes[0].len(), ...](the outer product of the coordinates).nabiuse 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 LinearThe 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.
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);
Sourcepub fn extrapolate(§self, mode: Extrapolate) -> Linear This interpolant with extrapolation
mode.nabiuse interpolate::{Curve, Extrapolate}; let f = try interpolate::linear([0, 1], [0, 1]); assert(f.extrapolate(Extrapolate::Fill(7.0)).at(2.0) == 7.0);The same function as a degree-1
PPoly, for derivatives, integrals and roots.nabilet p = try interpolate::linear([0, 1, 2], [0, 1, 0]).ppoly(); assert(p.integrate(0.0..2.0) == 1.0);
Trait implementations 1
impl Curve for Linear
StepSource
pub struct StepA piecewise-constant interpolant (nearest, previous, next).
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);
Sourcepub fn extrapolate(§self, mode: Extrapolate) -> Step This interpolant with extrapolation
mode.nabiuse 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
impl Curve for Step
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)).
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
Sourcepub fn fit(§axes: [Vector<f64>; N], values: Array<f64, N>, k: usize = 3) throws (InterpError) -> TensorSpline<N> The interpolating spline of degree
k(lower along an axis with fewer than k + 1 points) throughvalueson the gridaxes.nabiuse 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);
Sourcepub fn extrapolate(§self, mode: Extrapolate) -> TensorSpline<N> This spline with extrapolation
mode, applied per axis.nabiuse 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);The degree along each axis.
The knots of axis
d.nabiuse 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);The coefficients, an array with one axis per dimension.
The value at
p.nabiuse 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);
Sourcepub fn eval(§self, points: Matrix<f64>) throws (InterpError) -> Vector<f64> The values at the points in the rows of
points(m x N).nabiuse 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);The partial derivative of order
nualongaxis, a tensor spline of degreek - nuthere.nabiuse 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 yThe integral over the box
r[0] x r[1] x ..., each range in or beyond the base interval (the end pieces continue).nabiuse 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 BoundaryThe end conditions of a cubic spline.
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);
The first two and last two pieces are one cubic (third derivative continuous at
x[1]andx[n - 2]); the default. Exact for cubics.Zero second derivative at both ends.
Zero slope at both ends.
The given first derivatives at the start and the end.
The given second derivatives at the start and the end.
Periodic: value, slope and curvature match at both ends; needs
y[0] == y[n - 1].
InterpErrorSource
pub enum InterpErrorWhat went wrong building or evaluating an interpolant, a fit or an integral.
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"));
The method needs at least
needpoints and gotgot.The sample positions must rise strictly;
atis the first index that does not.Two inputs that must agree in length or shape do not;
whatnames both.An input holds NaN or an infinity;
whatnames it.An argument is out of its range;
whatsays which and what fits.A linear system of the method is singular (repeated points, or a degenerate configuration);
whatnames it.An iteration stopped after
iterationssteps short of the tolerance;valueanderrorare the best estimate so far.
Trait implementations 2
impl Display for InterpErrorimpl Error for InterpError
GridMethodSource
pub enum GridMethodHow RegularGrid interpolates between grid points.
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.
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 StepKindWhich sample a step interpolant takes.
use interpolate::{Curve, StepKind};
let f = try interpolate::step([0, 1, 2], [5, 6, 7], StepKind::Next);
assert(f.at(0.2) == 6.0);
The closest sample; the lower one at a midpoint.
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.
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).
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).
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.
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.
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).
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.
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.
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.
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.
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.
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.
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.
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).
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).
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).
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.
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).
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);