Skip to main content

lib_jsl_interpolation/nd/
nearest.rs

1//! Nearest-neighbour interpolation on an N-dimensional grid.
2
3use super::{InterpolationND, check_point, validate_grid_nd};
4use lib_jsl_core::*;
5use ndarray::ArrayD;
6
7/// Returns the value of the closest grid node (ties go to the lower index).
8#[derive(Debug, Clone)]
9pub struct NearestND {
10    axes: Vec<Vec<f64>>,
11    values: ArrayD<f64>,
12}
13
14impl NearestND {
15    pub fn new(axes: &[&[f64]], values: &ArrayD<f64>) -> Result<Self, ErrorsJSL> {
16        Ok(NearestND { axes: validate_grid_nd(axes, values, 1)?, values: values.clone() })
17    }
18}
19
20impl InterpolationND for NearestND {
21    fn interpolate_at(&self, point: &[f64]) -> Result<f64, ErrorsJSL> {
22        check_point(self.axes.len(), point)?;
23        let idx: Vec<usize> = self
24            .axes
25            .iter()
26            .zip(point)
27            .map(|(axis, &p)| {
28                let i = axis.partition_point(|&a| a < p);
29                if i == 0 {
30                    0
31                } else if i == axis.len() || p - axis[i - 1] <= axis[i] - p {
32                    i - 1
33                } else {
34                    i
35                }
36            })
37            .collect();
38        Ok(self.values[&idx[..]])
39    }
40}
41
42#[cfg(test)]
43mod tests {
44    use super::*;
45    use ndarray::IxDyn;
46
47    #[test]
48    fn four_dimensional_nearest() {
49        let a = [0.0, 1.0, 2.0];
50        let v = ArrayD::from_shape_fn(IxDyn(&[3, 3, 3, 3]), |i| (i[0] * 1000 + i[1] * 100 + i[2] * 10 + i[3]) as f64);
51        let n = NearestND::new(&[&a, &a, &a, &a], &v).unwrap();
52        assert_eq!(n.interpolate_at(&[0.4, 1.6, 1.4, 2.9]).unwrap(), 212.0);
53        assert!(n.interpolate_at(&[0.0, 0.0]).is_err());
54    }
55}