Skip to main content

lib_jsl_interpolation/three_d/
b_spline.rs

1//! Interpolating tricubic B-spline on a uniform 3D grid.
2
3use super::{Interpolation3D, validate_grid_3d};
4use crate::two_d::uniform_axis;
5use lib_jsl_core::*;
6use ndarray::{Array3, Axis};
7
8/// Cubic B-spline `s(u) = Σ c_k B₃(u - k)` through the samples, with natural end conditions
9/// (zero second derivative, equivalent to the natural cubic spline along each axis). Coefficients
10/// are found by solving a tridiagonal system along each axis; the surface is C² and each evaluation
11/// touches a 4×4×4 coefficient block.
12#[derive(Debug, Clone)]
13pub struct BSpline3D {
14    origin: [f64; 3],
15    step: [f64; 3],
16    /// Coefficients padded by one extra layer on each side (extrapolated linearly), shape (nx+2, ny+2, nz+2).
17    coeffs: Array3<f64>,
18}
19
20/// Cubic B-spline coefficients with natural ends for samples `f`; returns `n + 2` values whose
21/// index 0 and `n + 1` are the extrapolated `c_{-1}` and `c_n`.
22fn coefficients_1d(f: &[f64]) -> Vec<f64> {
23    let n = f.len();
24    let mut c = vec![0.0; n + 2];
25    c[1] = f[0];
26    c[n] = f[n - 1];
27    if n > 2 {
28        // (c[i-1] + 4 c[i] + c[i+1]) / 6 = f[i] for interior i, c[0-node] and c[n-1 node] fixed.
29        let m = n - 2;
30        let (mut diag, mut rhs) = (vec![4.0; m], vec![0.0; m]);
31        for i in 0..m {
32            rhs[i] = 6.0 * f[i + 1];
33        }
34        rhs[0] -= f[0];
35        rhs[m - 1] -= f[n - 1];
36        for i in 1..m {
37            let w = 1.0 / diag[i - 1];
38            diag[i] -= w;
39            rhs[i] -= w * rhs[i - 1];
40        }
41        let mut x = vec![0.0; m];
42        x[m - 1] = rhs[m - 1] / diag[m - 1];
43        for i in (0..m - 1).rev() {
44            x[i] = (rhs[i] - x[i + 1]) / diag[i];
45        }
46        c[2..n].copy_from_slice(&x);
47    }
48    c[0] = 2.0 * c[1] - c[2.min(n)];
49    c[n + 1] = 2.0 * c[n] - c[(n - 1).max(1)];
50    c
51}
52
53fn basis(t: f64) -> [f64; 4] {
54    // Weights of coefficients c[i-1..=i+2] for the position i + t, t in [0, 1).
55    let (t2, t3) = (t * t, t * t * t);
56    [(1.0 - t).powi(3) / 6.0, (3.0 * t3 - 6.0 * t2 + 4.0) / 6.0, (-3.0 * t3 + 3.0 * t2 + 3.0 * t + 1.0) / 6.0, t3 / 6.0]
57}
58
59impl BSpline3D {
60    /// All three axes must be uniformly spaced with at least 3 points.
61    pub fn new(x: VR1D, y: VR1D, z: VR1D, v: &Array3<f64>) -> Result<Self, ErrorsJSL> {
62        validate_grid_3d([x, y, z], v, 3)?;
63        let (ox, sx) = uniform_axis(x)?;
64        let (oy, sy) = uniform_axis(y)?;
65        let (oz, sz) = uniform_axis(z)?;
66        let (nx, ny, nz) = v.dim();
67        let mut c = v.clone();
68        // Prefilter along each axis, growing it by the two padding layers.
69        for (axis, n) in [(0usize, nx), (1, ny), (2, nz)] {
70            let mut shape = c.raw_dim();
71            shape[axis] = n + 2;
72            let mut out = Array3::<f64>::zeros(shape);
73            for (lane_in, mut lane_out) in c.lanes(Axis(axis)).into_iter().zip(out.lanes_mut(Axis(axis))) {
74                let coef = coefficients_1d(&lane_in.to_vec());
75                lane_out.iter_mut().zip(coef).for_each(|(o, k)| *o = k);
76            }
77            c = out;
78        }
79        Ok(BSpline3D { origin: [ox, oy, oz], step: [sx, sy, sz], coeffs: c })
80    }
81}
82
83impl Interpolation3D for BSpline3D {
84    fn interpolate_at(&self, x: f64, y: f64, z: f64) -> Result<f64, ErrorsJSL> {
85        let (nx, ny, nz) = self.coeffs.dim();
86        let n = [nx - 2, ny - 2, nz - 2];
87        let p = [x, y, z];
88        let mut base = [0usize; 3];
89        let mut w = [[0.0; 4]; 3];
90        for d in 0..3 {
91            let u = (p[d] - self.origin[d]) / self.step[d];
92            let cell = (u.floor().max(0.0) as usize).min(n[d] - 2);
93            base[d] = cell; // padded index of c_{cell-1} is `cell`
94            w[d] = basis(u - cell as f64);
95        }
96        let mut sum = 0.0;
97        for (a, wa) in w[0].iter().enumerate() {
98            for (b, wb) in w[1].iter().enumerate() {
99                for (c, wc) in w[2].iter().enumerate() {
100                    sum += wa * wb * wc * self.coeffs[[base[0] + a, base[1] + b, base[2] + c]];
101                }
102            }
103        }
104        Ok(sum)
105    }
106}
107
108#[cfg(test)]
109mod tests {
110    use super::*;
111
112    #[test]
113    fn interpolates_nodes_and_reproduces_linear_functions() {
114        let ax = R1D::from_iter((0..7).map(|k| 0.5 * k as f64));
115        let ay = R1D::from_iter((0..6).map(|k| -1.0 + 0.4 * k as f64));
116        let az = R1D::from_iter((0..5).map(|k| 2.0 + 0.25 * k as f64));
117        let f = |a: f64, b: f64, c: f64| 1.0 + 2.0 * a - b + 0.5 * c;
118        let v = Array3::from_shape_fn((7, 6, 5), |(i, j, k)| f(ax[i], ay[j], az[k]));
119        let s = BSpline3D::new(ax.view(), ay.view(), az.view(), &v).unwrap();
120        for &(a, b, c) in &[(0.0, -1.0, 2.0), (1.3, 0.2, 2.6), (3.0, 1.0, 3.0), (3.4, -0.7, 2.1)] {
121            assert!((s.interpolate_at(a, b, c).unwrap() - f(a, b, c)).abs() < 1e-11, "{a},{b},{c}");
122        }
123        let g = Array3::from_shape_fn((7, 6, 5), |(i, j, k)| ((i * 3 + j * 5 + k * 7) % 4) as f64);
124        let t = BSpline3D::new(ax.view(), ay.view(), az.view(), &g).unwrap();
125        for i in 0..7 {
126            for j in 0..6 {
127                for k in 0..5 {
128                    assert!((t.interpolate_at(ax[i], ay[j], az[k]).unwrap() - g[[i, j, k]]).abs() < 1e-11);
129                }
130            }
131        }
132    }
133
134    #[test]
135    fn smooth_function_accuracy_and_requirements() {
136        let n = 21;
137        let ax = R1D::from_iter((0..n).map(|k| k as f64 * 0.1));
138        let f = |a: f64, b: f64, c: f64| (a + 0.2).sin() * (b * 1.1).cos() + c * c * 0.3;
139        let v = Array3::from_shape_fn((n, n, n), |(i, j, k)| f(ax[i], ax[j], ax[k]));
140        let s = BSpline3D::new(ax.view(), ax.view(), ax.view(), &v).unwrap();
141        assert!((s.interpolate_at(0.83, 1.07, 0.55).unwrap() - f(0.83, 1.07, 0.55)).abs() < 2e-4);
142        let bad = R1D::from_vec(vec![0.0, 1.0, 3.0]);
143        assert!(BSpline3D::new(bad.view(), bad.view(), bad.view(), &Array3::zeros((3, 3, 3))).is_err());
144    }
145}