Skip to main content

lib_jsl_interpolation/two_d/
bicubic.rs

1//! Bicubic (C¹) interpolation on a rectilinear grid.
2
3use super::{Interpolation2D, find_cell, hermite_basis, validate_grid};
4use lib_jsl_core::*;
5
6/// A piecewise bicubic Hermite surface. Each node carries `f`, `∂f/∂x`, `∂f/∂y` and `∂²f/∂x∂y`,
7/// estimated by (non-uniform) central differences with one-sided differences at the boundary, and
8/// the surface in each cell is the tensor-product cubic Hermite patch. Exact for bilinear data and
9/// continuous in value and first derivatives across cells.
10#[derive(Debug, Clone)]
11pub struct Bicubic {
12    x: R1D,
13    y: R1D,
14    z: R2D,
15    zx: R2D,
16    zy: R2D,
17    zxy: R2D,
18}
19
20/// Derivative of `v` along an axis by clamped central differences.
21fn diff(axis: &R1D, n: usize, i: usize, value: impl Fn(usize) -> f64) -> f64 {
22    let (lo, hi) = (i.saturating_sub(1), (i + 1).min(n - 1));
23    (value(hi) - value(lo)) / (axis[hi] - axis[lo])
24}
25
26impl Bicubic {
27    pub fn new(x: VR1D, y: VR1D, z: VR2D) -> Result<Self, ErrorsJSL> {
28        validate_grid(x, y, z, 2)?;
29        let (x, y, z) = (x.to_owned(), y.to_owned(), z.to_owned());
30        let (nx, ny) = z.dim();
31        let zx = R2D::from_shape_fn((nx, ny), |(i, j)| diff(&x, nx, i, |k| z[[k, j]]));
32        let zy = R2D::from_shape_fn((nx, ny), |(i, j)| diff(&y, ny, j, |k| z[[i, k]]));
33        let zxy = R2D::from_shape_fn((nx, ny), |(i, j)| diff(&y, ny, j, |k| zx[[i, k]]));
34        Ok(Bicubic { x, y, z, zx, zy, zxy })
35    }
36}
37
38impl Interpolation2D for Bicubic {
39    fn interpolate_at(&self, x: f64, y: f64) -> Result<f64, ErrorsJSL> {
40        let (xs, ys) = (self.x.as_slice().expect("contiguous"), self.y.as_slice().expect("contiguous"));
41        let (i, j) = (find_cell(xs, x), find_cell(ys, y));
42        let (hx, hy) = (xs[i + 1] - xs[i], ys[j + 1] - ys[j]);
43        let bx = hermite_basis((x - xs[i]) / hx);
44        let by = hermite_basis((y - ys[j]) / hy);
45        // Basis order is (value at 0, slope at 0, value at 1, slope at 1); slopes scale by cell size.
46        let sx = [1.0, hx, 1.0, hx];
47        let sy = [1.0, hy, 1.0, hy];
48        let mut total = 0.0;
49        for (a, (di, kind_x)) in [(0, 0), (0, 1), (1, 0), (1, 1)].into_iter().enumerate() {
50            for (b, (dj, kind_y)) in [(0, 0), (0, 1), (1, 0), (1, 1)].into_iter().enumerate() {
51                let node = [i + di, j + dj];
52                let value = match (kind_x, kind_y) {
53                    (0, 0) => self.z[node],
54                    (1, 0) => self.zx[node],
55                    (0, 1) => self.zy[node],
56                    _ => self.zxy[node],
57                };
58                total += value * bx[a] * sx[a] * by[b] * sy[b];
59            }
60        }
61        Ok(total)
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn exact_at_nodes_and_for_bilinear_data() {
71        let x = R1D::from_vec(vec![0.0, 0.7, 1.5, 3.0, 3.5]);
72        let y = R1D::from_vec(vec![-1.0, 0.0, 2.0, 2.5]);
73        let f = |a: f64, b: f64| 2.0 - a + 4.0 * b + 0.3 * a * b;
74        let z = R2D::from_shape_fn((5, 4), |(i, j)| f(x[i], y[j]));
75        let s = Bicubic::new(x.view(), y.view(), z.view()).unwrap();
76        for &(px, py) in &[(0.3, -0.5), (1.1, 1.0), (2.9, 2.2), (3.4, 0.3)] {
77            assert!((s.interpolate_at(px, py).unwrap() - f(px, py)).abs() < 1e-12, "{px},{py}");
78        }
79        let zz = R2D::from_shape_fn((5, 4), |(i, j)| (x[i] * y[j]).sin());
80        let t = Bicubic::new(x.view(), y.view(), zz.view()).unwrap();
81        for i in 0..5 {
82            for j in 0..4 {
83                assert!((t.interpolate_at(x[i], y[j]).unwrap() - zz[[i, j]]).abs() < 1e-14);
84            }
85        }
86    }
87
88    #[test]
89    fn smooth_function_is_accurate_on_a_fine_grid() {
90        let n = 41;
91        let ax = R1D::from_iter((0..n).map(|k| k as f64 * 0.05));
92        let f = |a: f64, b: f64| (a * 1.3).sin() * (b + 0.4).cos();
93        let z = R2D::from_shape_fn((n, n), |(i, j)| f(ax[i], ax[j]));
94        let s = Bicubic::new(ax.view(), ax.view(), z.view()).unwrap();
95        let mut worst: f64 = 0.0;
96        for p in 0..30 {
97            for q in 0..30 {
98                let (px, py) = (0.03 + p as f64 * 0.0657, 0.04 + q as f64 * 0.0651);
99                worst = worst.max((s.interpolate_at(px, py).unwrap() - f(px, py)).abs());
100            }
101        }
102        assert!(worst < 2e-4, "worst {worst}");
103    }
104}