Skip to main content

lib_jsl_interpolation/two_d/
bilinear.rs

1//! Bilinear interpolation on a rectilinear grid.
2
3use super::{Interpolation2D, find_cell, validate_grid};
4use lib_jsl_core::*;
5
6/// Linear in each coordinate within a cell; continuous across cells. Outside the grid the edge
7/// cells are extended linearly.
8#[derive(Debug, Clone)]
9pub struct Bilinear {
10    x: R1D,
11    y: R1D,
12    z: R2D,
13}
14
15impl Bilinear {
16    pub fn new(x: VR1D, y: VR1D, z: VR2D) -> Result<Self, ErrorsJSL> {
17        validate_grid(x, y, z, 2)?;
18        Ok(Bilinear { x: x.to_owned(), y: y.to_owned(), z: z.to_owned() })
19    }
20}
21
22impl Interpolation2D for Bilinear {
23    fn interpolate_at(&self, x: f64, y: f64) -> Result<f64, ErrorsJSL> {
24        let (xs, ys) = (self.x.as_slice().expect("contiguous"), self.y.as_slice().expect("contiguous"));
25        let (i, j) = (find_cell(xs, x), find_cell(ys, y));
26        let tx = (x - xs[i]) / (xs[i + 1] - xs[i]);
27        let ty = (y - ys[j]) / (ys[j + 1] - ys[j]);
28        let z = &self.z;
29        Ok((1.0 - tx) * ((1.0 - ty) * z[[i, j]] + ty * z[[i, j + 1]]) + tx * ((1.0 - ty) * z[[i + 1, j]] + ty * z[[i + 1, j + 1]]))
30    }
31}
32
33#[cfg(test)]
34mod tests {
35    use super::*;
36
37    #[test]
38    fn exact_for_bilinear_functions_everywhere() {
39        let x = R1D::from_vec(vec![-1.0, 0.0, 0.5, 2.0]);
40        let y = R1D::from_vec(vec![0.0, 1.0, 4.0]);
41        let f = |a: f64, b: f64| 1.0 + 2.0 * a - 3.0 * b + 0.5 * a * b;
42        let z = R2D::from_shape_fn((4, 3), |(i, j)| f(x[i], y[j]));
43        let b = Bilinear::new(x.view(), y.view(), z.view()).unwrap();
44        for &(px, py) in &[(-1.0, 0.0), (0.25, 0.5), (1.3, 3.1), (3.0, 5.0), (-2.0, -1.0)] {
45            assert!((b.interpolate_at(px, py).unwrap() - f(px, py)).abs() < 1e-12);
46        }
47    }
48
49    #[test]
50    fn validates_shapes_and_axes() {
51        let x = R1D::from_vec(vec![0.0, 1.0]);
52        let y = R1D::from_vec(vec![0.0, 0.0]);
53        let z = R2D::zeros((2, 2));
54        assert!(Bilinear::new(x.view(), y.view(), z.view()).is_err());
55        assert!(Bilinear::new(x.view(), x.view(), R2D::zeros((3, 2)).view()).is_err());
56    }
57}