Skip to main content

lib_jsl_interpolation/nd/
grid_data.rs

1//! Multilinear interpolation of gridded data in any number of dimensions.
2
3use super::{InterpolationND, check_point, validate_grid_nd};
4use crate::two_d::find_cell;
5use lib_jsl_core::*;
6use ndarray::ArrayD;
7
8/// Multilinear ("grid data") interpolation: linear along each axis within the enclosing cell, a
9/// weighted average of the cell's `2^N` corners. Exact for functions that are affine in each
10/// coordinate; edge cells extend linearly outside the grid.
11#[derive(Debug, Clone)]
12pub struct GridData {
13    axes: Vec<Vec<f64>>,
14    values: ArrayD<f64>,
15}
16
17impl GridData {
18    pub fn new(axes: &[&[f64]], values: &ArrayD<f64>) -> Result<Self, ErrorsJSL> {
19        Ok(GridData { axes: validate_grid_nd(axes, values, 2)?, values: values.clone() })
20    }
21}
22
23impl InterpolationND for GridData {
24    fn interpolate_at(&self, point: &[f64]) -> Result<f64, ErrorsJSL> {
25        let dims = self.axes.len();
26        check_point(dims, point)?;
27        let mut cell = Vec::with_capacity(dims);
28        let mut t = Vec::with_capacity(dims);
29        for (axis, &p) in self.axes.iter().zip(point) {
30            let i = find_cell(axis, p);
31            cell.push(i);
32            t.push((p - axis[i]) / (axis[i + 1] - axis[i]));
33        }
34        // ANCHOR: multilinear
35        let mut idx = vec![0usize; dims];
36        let mut sum = 0.0;
37        for corner in 0..(1usize << dims) {
38            let mut weight = 1.0;
39            for d in 0..dims {
40                let up = (corner >> d) & 1;
41                idx[d] = cell[d] + up;
42                weight *= if up == 1 { t[d] } else { 1.0 - t[d] };
43            }
44            if weight != 0.0 {
45                sum += weight * self.values[&idx[..]];
46            }
47        }
48        // ANCHOR_END: multilinear
49        Ok(sum)
50    }
51}
52
53#[cfg(test)]
54mod tests {
55    use super::*;
56    use ndarray::IxDyn;
57
58    #[test]
59    fn exact_for_multi_affine_functions_in_four_dimensions() {
60        let ax: [Vec<f64>; 4] = [vec![0.0, 1.0, 2.5], vec![-1.0, 0.0, 3.0, 4.0], vec![0.0, 2.0], vec![1.0, 1.5, 2.0]];
61        let f = |p: &[f64]| 1.0 + p[0] - 2.0 * p[1] + 0.5 * p[2] * p[3] + p[0] * p[1] * p[2] * p[3];
62        let v = ArrayD::from_shape_fn(IxDyn(&[3, 4, 2, 3]), |i| f(&[ax[0][i[0]], ax[1][i[1]], ax[2][i[2]], ax[3][i[3]]]));
63        let g = GridData::new(&[&ax[0], &ax[1], &ax[2], &ax[3]], &v).unwrap();
64        for p in [[0.3, 0.2, 1.1, 1.2], [2.2, 3.5, 0.4, 1.9], [3.0, 5.0, 3.0, 2.5]] {
65            assert!((g.interpolate_at(&p).unwrap() - f(&p)).abs() < 1e-10, "{p:?}");
66        }
67    }
68
69    #[test]
70    fn one_dimensional_and_validation() {
71        let g = GridData::new(&[&[0.0, 2.0]], &ArrayD::from_shape_vec(IxDyn(&[2]), vec![1.0, 5.0]).unwrap()).unwrap();
72        assert_eq!(g.interpolate_at(&[0.5]).unwrap(), 2.0);
73        assert!(GridData::new(&[&[0.0, 2.0]], &ArrayD::zeros(IxDyn(&[3]))).is_err());
74        assert!(g.interpolate_at(&[0.0, 1.0]).is_err());
75    }
76}