Skip to main content

lib_jsl_interpolation/nd/
linear_nd.rs

1//! Piecewise-linear interpolation of scattered data in any dimension (SciPy's
2//! `LinearNDInterpolator` in 3-D and higher), on the Delaunay triangulation of the data.
3//!
4//! See the book entry [Geometry in any dimension](https://jwkunz.github.io/lib_jsl/book/geometry/hulls-nd.html#implementation).
5
6use crate::nd::InterpolationND;
7use lib_jsl_core::ErrorsJSL;
8use lib_jsl_geometry::algorithms::hull_nd::DelaunayNd;
9
10// ANCHOR: linear_nd
11/// Linear interpolation on the Delaunay triangulation of scattered points in `d ≥ 2`
12/// dimensions: the value at `x` is the barycentric average of the values at the vertices of
13/// the simplex containing `x`, and `fill_value` (NaN by default, as SciPy) outside the convex
14/// hull.
15#[derive(Clone, Debug)]
16pub struct LinearNdInterpolator {
17    tri: DelaunayNd,
18    values: Vec<f64>,
19    fill_value: f64,
20}
21
22impl LinearNdInterpolator {
23    pub fn new(points: &[Vec<f64>], values: &[f64]) -> Result<LinearNdInterpolator, ErrorsJSL> {
24        if points.len() != values.len() {
25            return Err(ErrorsJSL::IncompatibleArraySizes((points.len(), values.len())));
26        }
27        Ok(LinearNdInterpolator { tri: DelaunayNd::new(points)?, values: values.to_vec(), fill_value: f64::NAN })
28    }
29
30    /// The value returned outside the convex hull of the data.
31    pub fn with_fill_value(mut self, fill_value: f64) -> Self {
32        self.fill_value = fill_value;
33        self
34    }
35
36    /// The triangulation used.
37    pub fn triangulation(&self) -> &DelaunayNd {
38        &self.tri
39    }
40
41    pub fn evaluate(&self, x: &[f64]) -> f64 {
42        match self.tri.find_simplex(x) {
43            None => self.fill_value,
44            Some(s) => self.tri.barycentric(s, x).iter().zip(&self.tri.simplices[s]).map(|(c, &i)| c * self.values[i]).sum(),
45        }
46    }
47}
48// ANCHOR_END: linear_nd
49
50impl InterpolationND for LinearNdInterpolator {
51    fn interpolate_at(&self, point: &[f64]) -> Result<f64, ErrorsJSL> {
52        Ok(self.evaluate(point))
53    }
54}
55
56#[cfg(test)]
57mod tests {
58    use super::*;
59
60    #[test]
61    fn reproduces_linear_functions_in_three_and_four_dimensions() {
62        for d in [3usize, 4] {
63            let mut s = 7u64 + d as u64;
64            let mut next = || {
65                s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
66                (s >> 11) as f64 / (1u64 << 53) as f64
67            };
68            let pts: Vec<Vec<f64>> = (0..80).map(|_| (0..d).map(|_| next()).collect()).collect();
69            let f = |p: &[f64]| 1.0 + p.iter().enumerate().map(|(k, v)| (k as f64 + 1.0) * v).sum::<f64>();
70            let vals: Vec<f64> = pts.iter().map(|p| f(p)).collect();
71            let it = LinearNdInterpolator::new(&pts, &vals).unwrap();
72            let x: Vec<f64> = vec![0.5; d];
73            assert!((it.evaluate(&x) - f(&x)).abs() < 1e-12);
74            assert!(it.evaluate(&vec![2.0; d]).is_nan());
75            assert_eq!(it.clone().with_fill_value(-1.0).evaluate(&vec![2.0; d]), -1.0);
76        }
77    }
78}