Skip to main content

lib_jsl_interpolation/three_d/
cubic_lagrangian.rs

1//! Tricubic Lagrange interpolation on a 3D rectilinear grid.
2
3use super::{Interpolation3D, validate_grid_3d};
4use lib_jsl_core::*;
5use ndarray::Array3;
6
7/// Separable 4-point (cubic) Lagrange interpolation: the 4×4×4 block of nodes nearest the query
8/// (two on each side, shifted at the boundary) is interpolated exactly by tricubic polynomials, so
9/// any polynomial of degree ≤ 3 in each coordinate is reproduced. Non-uniform axes are supported;
10/// the result is continuous but not C¹ across cells.
11#[derive(Debug, Clone)]
12pub struct CubicLagrangian3D {
13    axes: [R1D; 3],
14    v: Array3<f64>,
15}
16
17/// First node of the 4-point stencil around `p` and its Lagrange weights.
18fn stencil(axis: &R1D, p: f64) -> (usize, [f64; 4]) {
19    let ax = axis.as_slice().expect("contiguous");
20    let cell = crate::two_d::find_cell(ax, p);
21    let start = cell.saturating_sub(1).min(ax.len() - 4);
22    let mut w = [1.0; 4];
23    for (a, wa) in w.iter_mut().enumerate() {
24        for b in 0..4 {
25            if a != b {
26                *wa *= (p - ax[start + b]) / (ax[start + a] - ax[start + b]);
27            }
28        }
29    }
30    (start, w)
31}
32
33impl CubicLagrangian3D {
34    pub fn new(x: VR1D, y: VR1D, z: VR1D, v: &Array3<f64>) -> Result<Self, ErrorsJSL> {
35        validate_grid_3d([x, y, z], v, 4)?;
36        Ok(CubicLagrangian3D { axes: [x.to_owned(), y.to_owned(), z.to_owned()], v: v.clone() })
37    }
38}
39
40impl Interpolation3D for CubicLagrangian3D {
41    fn interpolate_at(&self, x: f64, y: f64, z: f64) -> Result<f64, ErrorsJSL> {
42        let (i0, wx) = stencil(&self.axes[0], x);
43        let (j0, wy) = stencil(&self.axes[1], y);
44        let (k0, wz) = stencil(&self.axes[2], z);
45        let mut sum = 0.0;
46        for (a, wa) in wx.iter().enumerate() {
47            for (b, wb) in wy.iter().enumerate() {
48                for (c, wc) in wz.iter().enumerate() {
49                    sum += wa * wb * wc * self.v[[i0 + a, j0 + b, k0 + c]];
50                }
51            }
52        }
53        Ok(sum)
54    }
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60
61    #[test]
62    fn reproduces_tricubic_polynomials_on_nonuniform_axes() {
63        let x = R1D::from_vec(vec![0.0, 0.4, 1.1, 1.5, 2.6, 3.0]);
64        let y = R1D::from_vec(vec![-1.0, 0.0, 0.7, 1.9, 2.2]);
65        let z = R1D::from_vec(vec![0.0, 1.0, 1.4, 2.5, 4.0]);
66        let f = |a: f64, b: f64, c: f64| a.powi(3) - 2.0 * a * b * b + b.powi(3) * c - c.powi(3) + 0.5 * a * b * c + 1.0;
67        let v = Array3::from_shape_fn((6, 5, 5), |(i, j, k)| f(x[i], y[j], z[k]));
68        let l = CubicLagrangian3D::new(x.view(), y.view(), z.view(), &v).unwrap();
69        for &(a, b, c) in &[(0.2, -0.5, 0.3), (1.3, 1.0, 2.0), (2.9, 2.1, 3.9), (0.0, 2.2, 4.0)] {
70            assert!((l.interpolate_at(a, b, c).unwrap() - f(a, b, c)).abs() < 1e-9, "{a},{b},{c}");
71        }
72        assert!(CubicLagrangian3D::new(x.view(), y.view(), R1D::zeros(3).view(), &Array3::zeros((6, 5, 3))).is_err());
73    }
74}