Skip to main content

lib_jsl_interpolation/nd/
cubic_basis.rs

1//! Cardinal cubic basis interpolation on an N-dimensional grid.
2
3use super::{InterpolationND, check_point, validate_grid_nd};
4use crate::two_d::{find_cell, hermite_basis};
5use lib_jsl_core::*;
6use ndarray::ArrayD;
7
8/// Tensor-product cardinal (Catmull-Rom family) cubic in N dimensions: along the last axis the 1D
9/// cardinal interpolant is evaluated at the 4 neighbouring lines of the next axis, and so on
10/// recursively, touching a `4^N` neighbourhood. C¹, exact for multi-affine data; `tension` in
11/// `[0, 1]` scales node slopes by `1 - tension` (0 is Catmull-Rom).
12#[derive(Debug, Clone)]
13pub struct CubicBasisND {
14    axes: Vec<Vec<f64>>,
15    values: ArrayD<f64>,
16    tension: f64,
17}
18
19impl CubicBasisND {
20    pub fn new(axes: &[&[f64]], values: &ArrayD<f64>, tension: f64) -> Result<Self, ErrorsJSL> {
21        Ok(CubicBasisND { axes: validate_grid_nd(axes, values, 2)?, values: values.clone(), tension })
22    }
23
24    /// Value of the interpolant restricted to the line/plane/... fixed by `prefix` (indices of the
25    /// leading axes), evaluated over the remaining axes at `point`.
26    fn eval(&self, prefix: &mut Vec<usize>, cells: &[(usize, f64)]) -> f64 {
27        let d = prefix.len();
28        if d == self.axes.len() {
29            return self.values[&prefix[..]];
30        }
31        let axis = &self.axes[d];
32        let (i, t) = cells[d];
33        let c = 1.0 - self.tension;
34        let mut at = |k: usize, this: &Self| {
35            prefix.push(k);
36            let v = this.eval(prefix, cells);
37            prefix.pop();
38            v
39        };
40        let slope = |lo_v: f64, hi_v: f64, lo: usize, hi: usize| c * (hi_v - lo_v) / (axis[hi] - axis[lo]);
41        let n = axis.len();
42        let (a, b) = (i, i + 1);
43        let (va, vb) = (at(a, self), at(b, self));
44        let (alo, bhi) = (a.saturating_sub(1), (b + 1).min(n - 1));
45        let vlo = if alo == a { va } else { at(alo, self) };
46        let vhi = if bhi == b { vb } else { at(bhi, self) };
47        // Node a is bracketed by (alo, b); node b by (a, bhi).
48        let ma = slope(vlo, vb, alo, b);
49        let mb = slope(va, vhi, a, bhi);
50        let h = axis[b] - axis[a];
51        let w = hermite_basis(t);
52        w[0] * va + w[1] * h * ma + w[2] * vb + w[3] * h * mb
53    }
54}
55
56impl InterpolationND for CubicBasisND {
57    fn interpolate_at(&self, point: &[f64]) -> Result<f64, ErrorsJSL> {
58        check_point(self.axes.len(), point)?;
59        let cells: Vec<(usize, f64)> = self
60            .axes
61            .iter()
62            .zip(point)
63            .map(|(axis, &p)| {
64                let i = find_cell(axis, p);
65                (i, (p - axis[i]) / (axis[i + 1] - axis[i]))
66            })
67            .collect();
68        Ok(self.eval(&mut Vec::new(), &cells))
69    }
70}
71
72#[cfg(test)]
73mod tests {
74    use super::*;
75    use ndarray::IxDyn;
76
77    #[test]
78    fn matches_the_2d_implementation_and_is_exact_for_affine_data() {
79        let x = [0.0, 0.5, 1.5, 2.0, 3.0];
80        let y = [0.0, 1.0, 1.5, 3.0];
81        let f = |a: f64, b: f64| 1.0 + a - 2.0 * b + 0.25 * a * b + (a * 0.7).sin() * b;
82        let v = ArrayD::from_shape_fn(IxDyn(&[5, 4]), |i| f(x[i[0]], y[i[1]]));
83        let nd = CubicBasisND::new(&[&x, &y], &v, 0.0).unwrap();
84        let two = crate::two_d::cubic_basis::CubicBasis2D::new(
85            ndarray::arr1(&x).view(),
86            ndarray::arr1(&y).view(),
87            v.view().into_dimensionality::<ndarray::Ix2>().unwrap(),
88            0.0,
89        )
90        .unwrap();
91        use crate::two_d::Interpolation2D;
92        for &(a, b) in &[(0.2, 0.3), (1.7, 1.2), (2.9, 2.8), (0.0, 3.0)] {
93            assert!((nd.interpolate_at(&[a, b]).unwrap() - two.interpolate_at(a, b).unwrap()).abs() < 1e-12);
94        }
95        let g = |p: &[f64]| 2.0 - p[0] + 3.0 * p[1] + 0.5 * p[2] + p[0] * p[2];
96        let ax = [0.0, 1.0, 2.0, 3.5];
97        let w = ArrayD::from_shape_fn(IxDyn(&[4, 4, 4]), |i| g(&[ax[i[0]], ax[i[1]], ax[i[2]]]));
98        let c3 = CubicBasisND::new(&[&ax, &ax, &ax], &w, 0.0).unwrap();
99        assert!((c3.interpolate_at(&[1.3, 2.2, 0.7]).unwrap() - g(&[1.3, 2.2, 0.7])).abs() < 1e-11);
100    }
101}