tpt_math_interpolate/lib.rs
1#![no_std]
2#![forbid(unsafe_code)]
3// Dense numeric kernels are clearest with explicit indexing; the indexed-loop
4// lint does not fit this code.
5#![allow(clippy::needless_range_loop)]
6//! In-house interpolation & approximation for the `tpt-math` substrate.
7//!
8//! This crate provides scattered-data and surrogate-modelling routines built
9//! on top of the [`tpt_math_linalg_dense`] storage and the
10//! [`tpt_math_numeric`] `Scalar` trait, with **no external interpolation
11//! backend**:
12//!
13//! * [`RbfInterpolator`] — radial-basis-function interpolation with the
14//! thin-plate, Gaussian and multiquadric kernels, weights solved via the
15//! dense linear solver.
16//! * [`Kriging`] — ordinary Kriging with a configurable variogram model
17//! (spherical, exponential, Gaussian or linear), returning the prediction
18//! and the Kriging variance.
19//! * [`Pchip`] — shape-preserving piecewise-cubic-Hermite interpolation that
20//! provably preserves monotonicity of the data.
21//! * [`bspline_basis`] and [`BsplineCurve`] — Cox–de Boor B-spline basis
22//! evaluation and a weighted B-spline curve.
23//!
24//! # Why in-house?
25//!
26//! The commonly used `scirs2-interpolate` crate is Apache-2.0-only, which is
27//! disqualified by this substrate's dual MIT/Apache-2.0 license policy
28//! (see ADR-0007). All routines here are implemented from scratch so there is
29//! no license exposure and nothing to vendor.
30//!
31//! # Features
32//!
33//! * `std` (default) — enable the allocator and the `std` support of deps.
34//! * `alloc` — signal allocator availability (dynamic vectors need it).
35//!
36//! # Examples
37//!
38//! ```
39//! use tpt_math_interpolate::{RbfInterpolator, RbfKernel};
40//! use tpt_math_linalg_dense::DVector;
41//!
42//! let xs = DVector::from_vec(vec![0.0_f64, 1.0, 2.0]);
43//! let ys = DVector::from_vec(vec![0.0_f64, 1.0, 4.0]);
44//! let rbf = RbfInterpolator::new(xs, ys, RbfKernel::Gaussian { epsilon: 1.5 }).unwrap();
45//! // RBF interpolation is exact at the sample nodes.
46//! assert!((rbf.eval(1.0) - 1.0).abs() < 1e-6);
47//! ```
48
49extern crate alloc;
50
51#[cfg(feature = "alloc")]
52mod nd;
53#[cfg(feature = "alloc")]
54pub use nd::{KrigingNd, RbfInterpolatorNd};
55#[cfg(feature = "alloc")]
56mod spline;
57#[cfg(feature = "alloc")]
58pub use spline::{MultilinearGrid, NaturalCubicSpline};
59
60#[cfg(feature = "alloc")]
61use alloc::{format, vec, vec::Vec};
62#[cfg(feature = "alloc")]
63use tpt_math_linalg_dense::{DMatrix, DVector, DenseError, Lu};
64use tpt_math_numeric::Float;
65#[cfg(feature = "alloc")]
66use tpt_math_numeric::Scalar;
67
68// ===========================================================================
69// Radial basis function interpolation
70// ===========================================================================
71
72/// Radial kernels available for [`RbfInterpolator`].
73///
74/// Every kernel is a function of the (non-negative) distance `r` between two
75/// sample points; `epsilon` is a shape parameter that controls the kernel's
76/// breadth.
77#[derive(Clone, Copy, Debug, PartialEq)]
78pub enum RbfKernel {
79 /// Thin-plate spline: `φ(r) = r²·ln(r)` (with `φ(0) = 0`).
80 ThinPlate {
81 /// Shape parameter (currently unused for thin-plate, kept for API
82 /// symmetry).
83 epsilon: f64,
84 },
85 /// Gaussian: `φ(r) = exp(-(ε·r)²)`.
86 Gaussian {
87 /// Shape parameter controlling the width of the bump.
88 epsilon: f64,
89 },
90 /// Multiquadric: `φ(r) = sqrt(1 + (ε·r)²)`.
91 Multiquadric {
92 /// Shape parameter controlling the curvature.
93 epsilon: f64,
94 },
95}
96
97impl RbfKernel {
98 /// Evaluate the kernel at distance `r >= 0`.
99 pub fn eval(&self, r: f64) -> f64 {
100 match self {
101 RbfKernel::ThinPlate { .. } => {
102 let rr = r * r;
103 if rr == 0.0 {
104 0.0
105 } else {
106 rr * Float::ln(rr)
107 }
108 }
109 RbfKernel::Gaussian { epsilon } => {
110 let e = *epsilon;
111 Float::exp(-(e * r) * (e * r))
112 }
113 RbfKernel::Multiquadric { epsilon } => {
114 let e = *epsilon;
115 Float::sqrt(1.0 + (e * r) * (e * r))
116 }
117 }
118 }
119}
120
121/// A radial-basis-function interpolant of scattered 1-D data.
122///
123/// Given samples `(x_i, y_i)`, the interpolant is
124/// `s(x) = Σ_j w_j · φ(|x - x_j|)`, where the weight vector `w` solves the
125/// symmetric system `A w = y` with `A_ij = φ(|x_i - x_j|)`. The system is
126/// solved with the dense LU solver from [`tpt_math_linalg_dense`].
127#[cfg(feature = "alloc")]
128#[derive(Clone, Debug)]
129pub struct RbfInterpolator {
130 xs: DVector<f64>,
131 weights: DVector<f64>,
132 kernel: RbfKernel,
133}
134
135#[cfg(feature = "alloc")]
136impl RbfInterpolator {
137 /// Build the interpolant from samples `xs`/`ys` and a [`RbfKernel`].
138 ///
139 /// # Errors
140 ///
141 /// Returns [`DenseError::DimensionMismatch`] if `xs` and `ys` differ in
142 /// length, and [`DenseError::Singular`] if the kernel matrix is too
143 /// ill-conditioned to solve.
144 pub fn new(xs: DVector<f64>, ys: DVector<f64>, kernel: RbfKernel) -> Result<Self, DenseError> {
145 let n = xs.len();
146 if ys.len() != n {
147 return Err(DenseError::DimensionMismatch {
148 what: format!("xs has length {n}, ys has length {}", ys.len()),
149 });
150 }
151 let a = DMatrix::from_fn(n, n, |i, j| kernel.eval((xs[i] - xs[j]).abs()));
152 let weights = a.solve(&ys)?;
153 Ok(RbfInterpolator {
154 xs,
155 weights,
156 kernel,
157 })
158 }
159
160 /// Evaluate the interpolant at a single point `x`.
161 pub fn eval(&self, x: f64) -> f64 {
162 let mut s = 0.0_f64;
163 for j in 0..self.xs.len() {
164 s += self.weights[j] * self.kernel.eval((x - self.xs[j]).abs());
165 }
166 s
167 }
168
169 /// Evaluate the interpolant at each point of `points`.
170 pub fn interpolate(&self, points: &DVector<f64>) -> DVector<f64> {
171 DVector::from_fn(points.len(), |i| self.eval(points[i]))
172 }
173}
174
175// ===========================================================================
176// Ordinary Kriging
177// ===========================================================================
178
179/// A variogram model `γ(h)` describing the spatial correlation of residuals.
180///
181/// All models reduce to the nugget at `h = 0`, i.e. `γ(0) = nugget`, which is
182/// what makes ordinary Kriging an exact interpolator at sample points.
183#[derive(Clone, Copy, Debug, PartialEq)]
184pub enum Variogram {
185 /// Spherical: `γ(h) = nugget + sill·(1.5·a − 0.5·a³)` for `h ≤ range`, else
186 /// `nugget + sill`, where `a = h / range`.
187 Spherical {
188 /// Partial sill (the variance contributed by the structured component).
189 sill: f64,
190 /// Distance at which the variogram reaches the sill.
191 range: f64,
192 /// Jump at the origin (measurement/short-range noise).
193 nugget: f64,
194 },
195 /// Exponential: `γ(h) = nugget + sill·(1 − exp(−h / range))`.
196 Exponential {
197 /// Partial sill.
198 sill: f64,
199 /// Practical range (≈ 3·range is where the sill is reached).
200 range: f64,
201 /// Jump at the origin.
202 nugget: f64,
203 },
204 /// Gaussian: `γ(h) = nugget + sill·(1 − exp(−(h / range)²))`.
205 Gaussian {
206 /// Partial sill.
207 sill: f64,
208 /// Range parameter.
209 range: f64,
210 /// Jump at the origin.
211 nugget: f64,
212 },
213 /// Linear model of regionalized variables: `γ(h) = nugget + slope·h`.
214 ///
215 /// This is a valid (conditionally negative-definite) variogram in 1-D and
216 /// has the useful property that ordinary Kriging reproduces a linear trend
217 /// exactly (with `nugget = 0`).
218 Linear {
219 /// Slope of the variogram (must be non-negative).
220 slope: f64,
221 /// Jump at the origin.
222 nugget: f64,
223 },
224}
225
226impl Variogram {
227 /// Evaluate the variogram at lag `h >= 0`.
228 pub fn gamma(&self, h: f64) -> f64 {
229 match self {
230 Variogram::Spherical {
231 sill,
232 range,
233 nugget,
234 } => {
235 let r = *range;
236 if h >= r {
237 nugget + sill
238 } else {
239 let a = h / r;
240 nugget + sill * (1.5 * a - 0.5 * a * a * a)
241 }
242 }
243 Variogram::Exponential {
244 sill,
245 range,
246 nugget,
247 } => nugget + sill * (1.0 - Float::exp(-h / *range)),
248 Variogram::Gaussian {
249 sill,
250 range,
251 nugget,
252 } => {
253 let a = h / *range;
254 nugget + sill * (1.0 - Float::exp(-a * a))
255 }
256 Variogram::Linear { slope, nugget } => nugget + slope * h,
257 }
258 }
259}
260
261/// An ordinary-Kriging surrogate of scattered 1-D data.
262///
263/// The prediction at a point `x*` solves the `(n+1)×(n+1)` Kriging system
264/// built from the variogram, with the final row/column enforcing the
265/// unbiasedness constraint `Σ_i w_i = 1`. Both the predicted mean and the
266/// Kriging variance are returned.
267#[cfg(feature = "alloc")]
268#[derive(Clone, Debug)]
269pub struct Kriging {
270 xs: DVector<f64>,
271 ys: DVector<f64>,
272 variogram: Variogram,
273 /// LU factorisation of the Kriging matrix, which depends only on the
274 /// sample locations and the variogram, so it is computed once here.
275 factor: Lu,
276}
277
278/// The `(n+1)×(n+1)` ordinary-Kriging matrix for sample locations `xs`.
279#[cfg(feature = "alloc")]
280fn kriging_matrix(xs: &DVector<f64>, variogram: &Variogram) -> DMatrix<f64> {
281 let n = xs.len();
282 DMatrix::from_fn(n + 1, n + 1, |i, j| {
283 if i < n && j < n {
284 variogram.gamma((xs[i] - xs[j]).abs())
285 } else if (i < n && j == n) || (i == n && j < n) {
286 1.0
287 } else {
288 0.0
289 }
290 })
291}
292
293#[cfg(feature = "alloc")]
294impl Kriging {
295 /// Build a Kriging surrogate from samples `xs`/`ys` and a [`Variogram`].
296 ///
297 /// # Errors
298 ///
299 /// Returns [`DenseError::DimensionMismatch`] if `xs` and `ys` differ in
300 /// length.
301 ///
302 /// # Errors
303 ///
304 /// Returns [`DenseError::DimensionMismatch`] if `xs` and `ys` differ in
305 /// length, and [`DenseError::Singular`] if the Kriging matrix is singular
306 /// (for example duplicate sample locations with a zero nugget).
307 pub fn new(
308 xs: DVector<f64>,
309 ys: DVector<f64>,
310 variogram: Variogram,
311 ) -> Result<Self, DenseError> {
312 let n = xs.len();
313 if ys.len() != n {
314 return Err(DenseError::DimensionMismatch {
315 what: format!("xs has length {n}, ys has length {}", ys.len()),
316 });
317 }
318 let factor = Lu::new(&kriging_matrix(&xs, &variogram))?;
319 Ok(Kriging {
320 xs,
321 ys,
322 variogram,
323 factor,
324 })
325 }
326
327 /// Predict the value (and Kriging variance) at `x`.
328 ///
329 /// With a `nugget = 0` variogram this is an exact interpolator, so
330 /// `predict(x_i) == y_i`.
331 ///
332 /// # Errors
333 ///
334 /// Returns [`DenseError::Singular`] if the Kriging system is singular.
335 pub fn predict(&self, x: f64) -> Result<(f64, f64), DenseError> {
336 let n = self.xs.len();
337 let rhs = DVector::from_fn(n + 1, |i| {
338 if i < n {
339 self.variogram.gamma((self.xs[i] - x).abs())
340 } else {
341 1.0
342 }
343 });
344
345 let w = self.factor.solve(&rhs)?;
346 let mut mean = 0.0_f64;
347 for i in 0..n {
348 mean += w[i] * self.ys[i];
349 }
350 let mut variance = w[n];
351 for i in 0..n {
352 variance += w[i] * rhs[i];
353 }
354 Ok((mean, variance))
355 }
356}
357
358// ===========================================================================
359// PCHIP (shape-preserving piecewise cubic Hermite)
360// ===========================================================================
361
362/// Shape-preserving piecewise-cubic-Hermite interpolant (PCHIP).
363///
364/// Given sorted node abscissae `x` and values `y`, the derivative at each node
365/// is chosen by the Fritsch–Carlson harmonic-mean limiting rule, which
366/// guarantees that a monotone data set yields a monotone interpolant.
367#[cfg(feature = "alloc")]
368#[derive(Clone, Debug)]
369pub struct Pchip<T: Scalar> {
370 x: DVector<T>,
371 y: DVector<T>,
372 d: DVector<T>,
373}
374
375#[cfg(feature = "alloc")]
376impl<T: Scalar> Pchip<T> {
377 /// Build a PCHIP interpolant.
378 ///
379 /// # Errors
380 ///
381 /// Returns [`DenseError::DimensionMismatch`] if `x` and `y` differ in
382 /// length (they must each have at least two entries) or if the abscissae
383 /// are not strictly increasing.
384 pub fn new(x: DVector<T>, y: DVector<T>) -> Result<Self, DenseError> {
385 let n = x.len();
386 if y.len() != n {
387 return Err(DenseError::DimensionMismatch {
388 what: format!("x has length {n}, y has length {}", y.len()),
389 });
390 }
391 if n < 2 {
392 return Err(DenseError::DimensionMismatch {
393 what: format!("need at least 2 nodes, got {n}"),
394 });
395 }
396 let one = T::one();
397 let two = one + one;
398 let three = two + one;
399
400 let mut h: Vec<T> = vec![T::zero(); n - 1];
401 let mut delta: Vec<T> = vec![T::zero(); n - 1];
402 for i in 0..(n - 1) {
403 h[i] = x[i + 1] - x[i];
404 if h[i] <= T::zero() {
405 return Err(DenseError::DimensionMismatch {
406 what: format!("abscissae must be strictly increasing at index {i}"),
407 });
408 }
409 delta[i] = (y[i + 1] - y[i]) / h[i];
410 }
411
412 let mut d: Vec<T> = vec![T::zero(); n];
413 // Interior derivatives (Fritsch–Carlson harmonic-mean rule).
414 for i in 1..(n - 1) {
415 if delta[i - 1] * delta[i] <= T::zero() {
416 d[i] = T::zero();
417 } else {
418 let w1 = two * h[i - 1] + h[i];
419 let w2 = h[i - 1] + two * h[i];
420 d[i] = (three * (h[i - 1] + h[i])) / (w1 / delta[i - 1] + w2 / delta[i]);
421 }
422 }
423 // Endpoint derivatives (one-sided Hermite / quadratic estimate). With
424 // only two nodes there is a single secant, so both ends take its slope.
425 if n == 2 {
426 d[0] = delta[0];
427 d[1] = delta[0];
428 } else {
429 d[0] = ((two * h[0] + h[1]) * delta[0] - h[0] * delta[1]) / (h[0] + h[1]);
430 let nm = n - 1;
431 d[nm] = ((two * h[nm - 1] + h[nm - 2]) * delta[nm - 1] - h[nm - 1] * delta[nm - 2])
432 / (h[nm - 1] + h[nm - 2]);
433 }
434
435 // Fritsch–Carlson monotonicity enforcement: on each interval, limit the
436 // derivatives so the Hermite cubic cannot overshoot. This guarantees a
437 // monotone data set yields a monotone interpolant.
438 for i in 0..(n - 1) {
439 if delta[i] == T::zero() {
440 d[i] = T::zero();
441 d[i + 1] = T::zero();
442 continue;
443 }
444 let a = d[i] / delta[i];
445 let b = d[i + 1] / delta[i];
446 if a >= T::zero() && b >= T::zero() && (a * a + b * b) > three * three {
447 let tau = three / (a * a + b * b).sqrt();
448 d[i] = tau * a * delta[i];
449 d[i + 1] = tau * b * delta[i];
450 }
451 if d[i] * delta[i] < T::zero() {
452 d[i] = T::zero();
453 }
454 if d[i + 1] * delta[i] < T::zero() {
455 d[i + 1] = T::zero();
456 }
457 }
458
459 Ok(Pchip {
460 x,
461 y,
462 d: DVector::from_vec(d),
463 })
464 }
465
466 /// Evaluate the interpolant at `x` (linear extrapolation outside the
467 /// node range).
468 pub fn eval(&self, x: T) -> T {
469 let one = T::one();
470 let two = one + one;
471 let three = two + one;
472 let n = self.x.len();
473
474 // Outside the node range, continue along the endpoint tangent.
475 if x < self.x[0] {
476 return self.y[0] + self.d[0] * (x - self.x[0]);
477 }
478 if x > self.x[n - 1] {
479 return self.y[n - 1] + self.d[n - 1] * (x - self.x[n - 1]);
480 }
481
482 // Locate the bracketing interval by binary search.
483 let k = if x <= self.x[0] {
484 0
485 } else if x >= self.x[n - 1] {
486 n - 2
487 } else {
488 let mut lo = 0_usize;
489 let mut hi = n - 1;
490 while hi - lo > 1 {
491 let mid = lo + (hi - lo) / 2;
492 if self.x[mid] <= x {
493 lo = mid;
494 } else {
495 hi = mid;
496 }
497 }
498 lo
499 };
500
501 let h = self.x[k + 1] - self.x[k];
502 let t = (x - self.x[k]) / h;
503 let t2 = t * t;
504 let t3 = t2 * t;
505 let h00 = two * t3 - three * t2 + one;
506 let h10 = t3 - two * t2 + t;
507 let h01 = -two * t3 + three * t2;
508 let h11 = t3 - t2;
509
510 self.y[k] * h00 + self.d[k] * (h10 * h) + self.y[k + 1] * h01 + self.d[k + 1] * (h11 * h)
511 }
512}
513
514// ===========================================================================
515// B-spline basis (Cox–de Boor) and curve
516// ===========================================================================
517
518/// Evaluate the `i`-th B-spline basis function of the given `degree` at `x`.
519///
520/// The knot vector `knots` must contain the `p + 2` knots spanning basis `i`
521/// (so `knots.len()` must be at least `degree + i + 2`). The recursion is the
522/// Cox–de Boor formula; basis functions satisfy the partition-of-unity
523/// property `Σ_i B_{i,p}(x) = 1` for `x` in the interior of the knot span.
524///
525/// Returns `0.0` for any out-of-range `i`.
526pub fn bspline_basis(degree: usize, knots: &[f64], i: usize, x: f64) -> f64 {
527 let n = knots.len();
528 if i + degree + 1 >= n {
529 return 0.0;
530 }
531 if degree == 0 {
532 let a = knots[i];
533 let b = knots[i + 1];
534 if x >= a && x < b {
535 1.0
536 } else if i + 1 == n - 1 && x == b {
537 // Include the right endpoint on the last span so that the
538 // partition-of-unity holds across the full knot domain.
539 1.0
540 } else {
541 0.0
542 }
543 } else {
544 let denom1 = knots[i + degree] - knots[i];
545 let denom2 = knots[i + degree + 1] - knots[i + 1];
546 let t1 = if denom1 != 0.0 {
547 (x - knots[i]) / denom1
548 } else {
549 0.0
550 };
551 let t2 = if denom2 != 0.0 {
552 (knots[i + degree + 1] - x) / denom2
553 } else {
554 0.0
555 };
556 t1 * bspline_basis(degree - 1, knots, i, x)
557 + t2 * bspline_basis(degree - 1, knots, i + 1, x)
558 }
559}
560
561/// A weighted B-spline curve `C(x) = Σ_i w_i · B_{i,p}(x)`.
562///
563/// This is a thin convenience wrapper over [`bspline_basis`]: it stores the
564/// knot vector and control-point weights and evaluates their weighted sum.
565#[cfg(feature = "alloc")]
566#[derive(Clone, Debug)]
567pub struct BsplineCurve {
568 degree: usize,
569 knots: Vec<f64>,
570 weights: Vec<f64>,
571}
572
573#[cfg(feature = "alloc")]
574impl BsplineCurve {
575 /// Build a B-spline curve of `degree` with the given `knots` and control
576 /// weights.
577 ///
578 /// # Panics
579 ///
580 /// Panics if `weights.len() != knots.len() - degree - 1`, i.e. the number
581 /// of control points is not consistent with the knot vector.
582 pub fn new(degree: usize, knots: &[f64], weights: &[f64]) -> Self {
583 assert_eq!(
584 weights.len(),
585 knots.len() - degree - 1,
586 "weights length must equal knots.len() - degree - 1"
587 );
588 BsplineCurve {
589 degree,
590 knots: knots.to_vec(),
591 weights: weights.to_vec(),
592 }
593 }
594
595 /// Evaluate the weighted B-spline curve at `x`.
596 pub fn eval(&self, x: f64) -> f64 {
597 let knots = self.knots.as_slice();
598 let mut s = 0.0_f64;
599 for (i, w) in self.weights.iter().enumerate() {
600 s += *w * bspline_basis(self.degree, knots, i, x);
601 }
602 s
603 }
604}
605
606#[cfg(all(test, feature = "alloc"))]
607mod tests {
608 use super::*;
609 use approx::assert_relative_eq;
610 use tpt_math_linalg_dense::DVector;
611
612 // -------------------------------------------------------------------
613 // RBF: exact at the sample nodes.
614 // -------------------------------------------------------------------
615 #[test]
616 fn rbf_exact_at_nodes() {
617 // The Gaussian RBF matrix is positive definite, so the node values are
618 // reproduced exactly.
619 let xs = DVector::from_vec(vec![-1.0_f64, 0.0, 1.0]);
620 let ys = DVector::from_vec(vec![1.0_f64, 3.0, 2.0]);
621 let rbf = RbfInterpolator::new(xs, ys, RbfKernel::Gaussian { epsilon: 1.5 }).unwrap();
622 // At the nodes the interpolant reproduces the data exactly.
623 assert_relative_eq!(rbf.eval(0.0), 3.0, epsilon = 1e-6);
624 assert_relative_eq!(rbf.eval(1.0), 2.0, epsilon = 1e-6);
625 }
626
627 #[test]
628 fn rbf_thinplate_recovers_sin() {
629 // Non-degenerate node spacing so the thin-plate system is solvable.
630 let xs = DVector::from_vec(vec![-0.8_f64, -0.3, 0.2, 0.7]);
631 let ys = DVector::from_vec(
632 xs.iter()
633 .map(|&x| (core::f64::consts::PI * x).sin())
634 .collect(),
635 );
636 let rbf = RbfInterpolator::new(xs, ys, RbfKernel::ThinPlate { epsilon: 1.0 }).unwrap();
637 // Exact at the nodes.
638 assert_relative_eq!(
639 rbf.eval(0.2),
640 (core::f64::consts::PI * 0.2).sin(),
641 epsilon = 1e-6
642 );
643 // Close to the truth between nodes.
644 let val = rbf.eval(0.0);
645 let truth = (0.0_f64).sin();
646 assert!((val - truth).abs() < 0.2, "val={val}, truth={truth}");
647 }
648
649 // -------------------------------------------------------------------
650 // Kriging: recovers a linear trend exactly (Linear variogram, nugget 0).
651 // -------------------------------------------------------------------
652 #[test]
653 fn kriging_rejects_duplicate_samples_without_nugget() {
654 let xs = DVector::from_vec(vec![0.0_f64, 1.0, 1.0]);
655 let ys = DVector::from_vec(vec![0.0_f64, 1.0, 1.0]);
656 let v = Variogram::Linear {
657 slope: 1.0,
658 nugget: 0.0,
659 };
660 assert!(Kriging::new(xs, ys, v).is_err());
661 }
662
663 #[test]
664 fn kriging_recovers_line() {
665 // y = x sampled at two collinear points; ordinary Kriging with the
666 // linear variogram reproduces the line everywhere inside the span.
667 let xs = DVector::from_vec(vec![-1.0_f64, 1.0]);
668 let ys = DVector::from_vec(vec![-1.0_f64, 1.0]);
669 let krig = Kriging::new(
670 xs,
671 ys,
672 Variogram::Linear {
673 slope: 1.0,
674 nugget: 0.0,
675 },
676 )
677 .unwrap();
678 for &x in &[-1.0_f64, -0.5, 0.0, 0.5, 1.0] {
679 let (mean, _var) = krig.predict(x).unwrap();
680 assert_relative_eq!(mean, x, epsilon = 1e-9);
681 }
682 }
683
684 #[test]
685 fn kriging_exact_at_nodes() {
686 // Spherical variogram with no nugget is an exact interpolator.
687 let xs = DVector::from_vec(vec![0.0_f64, 1.0, 2.0, 3.0]);
688 let ys = DVector::from_vec(vec![0.5_f64, 2.0, 1.0, 4.0]);
689 let v = Variogram::Spherical {
690 sill: 1.0,
691 range: 5.0,
692 nugget: 0.0,
693 };
694 let krig = Kriging::new(xs, ys.clone(), v).unwrap();
695 for i in 0..4 {
696 let (mean, _) = krig.predict(i as f64).unwrap();
697 assert_relative_eq!(mean, ys[i], epsilon = 1e-6);
698 }
699 }
700
701 // -------------------------------------------------------------------
702 // PCHIP: monotonicity preservation.
703 // -------------------------------------------------------------------
704 #[test]
705 fn pchip_preserves_monotonicity() {
706 let x = DVector::from_vec(vec![0.0_f64, 1.0, 2.0, 3.0]);
707 let y = DVector::from_vec(vec![0.0_f64, 1.0, 8.0, 27.0]); // strictly increasing
708 let pchip = Pchip::new(x, y).unwrap();
709 let mut prev = pchip.eval(0.0);
710 for k in 1..=100 {
711 let xv = (k as f64) / 100.0 * 3.0;
712 let cur = pchip.eval(xv);
713 assert!(cur >= prev - 1e-12, "non-monotone at x={xv}");
714 prev = cur;
715 }
716 }
717
718 #[test]
719 fn pchip_two_nodes_is_linear() {
720 // Two nodes used to panic (out-of-bounds `h[1]` in the endpoint rule).
721 let x = DVector::from_vec(vec![0.0_f64, 2.0]);
722 let y = DVector::from_vec(vec![1.0_f64, 5.0]);
723 let pchip = Pchip::new(x, y).unwrap();
724 assert_relative_eq!(pchip.eval(1.0), 3.0, epsilon = 1e-12);
725 assert_relative_eq!(pchip.eval(0.5), 2.0, epsilon = 1e-12);
726 }
727
728 #[test]
729 fn pchip_extrapolates_linearly() {
730 // Outside the node range the interpolant continues along the endpoint
731 // tangent, as documented on `eval`.
732 let x = DVector::from_vec(vec![0.0_f64, 1.0, 2.0, 3.0]);
733 let y = DVector::from_vec(vec![0.0_f64, 1.0, 8.0, 27.0]);
734 let pchip = Pchip::new(x, y).unwrap();
735 let d0 = pchip.eval(1e-6) / 1e-6; // slope at the left endpoint
736 let dn = (pchip.eval(3.0) - pchip.eval(3.0 - 1e-6)) / 1e-6;
737 assert_relative_eq!(pchip.eval(-1.0), pchip.eval(0.0) - d0, epsilon = 1e-4);
738 assert_relative_eq!(pchip.eval(4.0), pchip.eval(3.0) + dn, epsilon = 1e-4);
739 }
740
741 #[test]
742 fn pchip_matches_nodes() {
743 let x = DVector::from_vec(vec![0.0_f64, 1.0, 2.0, 3.0]);
744 let y = DVector::from_vec(vec![0.0_f64, 1.0, 8.0, 27.0]);
745 let pchip = Pchip::new(x, y.clone()).unwrap();
746 for i in 0..4 {
747 assert_relative_eq!(pchip.eval(i as f64), y[i], epsilon = 1e-9);
748 }
749 }
750
751 // -------------------------------------------------------------------
752 // B-spline: partition of unity.
753 // -------------------------------------------------------------------
754 #[test]
755 fn bspline_partition_of_unity() {
756 // Open-uniform knot vector; the basis functions form a partition of
757 // unity on the interior span (t_p, t_{m-p-1}) = (2, 6).
758 let knots: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
759 let p = 2;
760 let n = knots.len() - p - 1;
761 // Sample a deterministic grid strictly inside the interior span.
762 for k in 3..6 {
763 for m in 1..=9 {
764 let x = k as f64 + m as f64 / 10.0;
765 let mut sum = 0.0_f64;
766 for i in 0..n {
767 sum += bspline_basis(p, &knots, i, x);
768 }
769 assert_relative_eq!(sum, 1.0, epsilon = 1e-9, max_relative = 1e-9);
770 }
771 }
772 }
773
774 #[test]
775 fn bspline_curve_uniform_weights_is_partition() {
776 let knots: Vec<f64> = vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0];
777 let p = 2;
778 let n = knots.len() - p - 1;
779 let weights: Vec<f64> = vec![1.0; n];
780 let curve = BsplineCurve::new(p, &knots, &weights);
781 for k in 3..6 {
782 let x = k as f64 + 0.5;
783 assert_relative_eq!(curve.eval(x), 1.0, epsilon = 1e-9, max_relative = 1e-9);
784 }
785 }
786}