Skip to main content

lib_jsl_interpolation/two_d/
scattered.rs

1//! Interpolation of scattered 2-D data on a Delaunay triangulation, following
2//! `scipy.interpolate`: piecewise linear (`LinearNDInterpolator`), the C¹ Clough-Tocher scheme
3//! with globally estimated gradients (`CloughTocher2DInterpolator`), nearest neighbour
4//! (`NearestNDInterpolator`, any dimension) and the `griddata` front end.
5//!
6//! See the book entry [Piecewise polynomials, Hermite data and scattered interpolation](https://jwkunz.github.io/lib_jsl/book/interpolation/piecewise-scattered.html#scattered-data-on-a-triangulation).
7
8use lib_jsl_core::ErrorsJSL;
9use lib_jsl_geometry::algorithms::delaunay_triangulation;
10use std::collections::HashMap;
11
12/// A Delaunay triangulation with neighbour links and a bucket grid for point location.
13#[derive(Clone, Debug)]
14pub struct TriangulationIndex {
15    pub points: Vec<[f64; 2]>,
16    /// Triangles, counter-clockwise.
17    pub triangles: Vec<[usize; 3]>,
18    /// `neighbors[t][k]`: the triangle across the edge opposite vertex `k` (Qhull's convention).
19    pub neighbors: Vec<[Option<usize>; 3]>,
20    origin: [f64; 2],
21    cell: [f64; 2],
22    dims: [usize; 2],
23    buckets: Vec<Vec<usize>>,
24}
25
26impl TriangulationIndex {
27    /// Triangulates the points (at least three, not all collinear).
28    pub fn new(points: &[[f64; 2]]) -> Result<TriangulationIndex, ErrorsJSL> {
29        let tri = delaunay_triangulation(points).ok_or(ErrorsJSL::InvalidInputRange("need three or more points, not all collinear"))?;
30        let triangles = tri.triangles;
31        let mut edge_owner: HashMap<(usize, usize), Vec<(usize, usize)>> = HashMap::new();
32        for (t, tr) in triangles.iter().enumerate() {
33            for k in 0..3 {
34                let (a, b) = (tr[(k + 1) % 3], tr[(k + 2) % 3]);
35                edge_owner.entry((a.min(b), a.max(b))).or_default().push((t, k));
36            }
37        }
38        let mut neighbors = vec![[None; 3]; triangles.len()];
39        for owners in edge_owner.values() {
40            if let [(t1, k1), (t2, k2)] = owners[..] {
41                neighbors[t1][k1] = Some(t2);
42                neighbors[t2][k2] = Some(t1);
43            }
44        }
45        // Bucket grid of about one triangle per cell.
46        let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
47        for p in points {
48            for d in 0..2 {
49                lo[d] = lo[d].min(p[d]);
50                hi[d] = hi[d].max(p[d]);
51            }
52        }
53        let side = (triangles.len() as f64).sqrt().ceil().max(1.0) as usize;
54        let dims = [side, side];
55        let cell = [((hi[0] - lo[0]) / side as f64).max(f64::MIN_POSITIVE), ((hi[1] - lo[1]) / side as f64).max(f64::MIN_POSITIVE)];
56        let mut buckets = vec![Vec::new(); side * side];
57        let to_cell = |v: f64, d: usize| (((v - lo[d]) / cell[d]).floor().max(0.0) as usize).min(dims[d] - 1);
58        for (t, tr) in triangles.iter().enumerate() {
59            let xs = tr.map(|i| points[i][0]);
60            let ys = tr.map(|i| points[i][1]);
61            let (cx0, cx1) = (to_cell(xs.iter().copied().fold(f64::INFINITY, f64::min), 0), to_cell(xs.iter().copied().fold(f64::NEG_INFINITY, f64::max), 0));
62            let (cy0, cy1) = (to_cell(ys.iter().copied().fold(f64::INFINITY, f64::min), 1), to_cell(ys.iter().copied().fold(f64::NEG_INFINITY, f64::max), 1));
63            for cx in cx0..=cx1 {
64                for cy in cy0..=cy1 {
65                    buckets[cx * side + cy].push(t);
66                }
67            }
68        }
69        Ok(TriangulationIndex { points: points.to_vec(), triangles, neighbors, origin: lo, cell, dims, buckets })
70    }
71
72    /// The barycentric coordinates of `p` in triangle `t`.
73    pub fn barycentric(&self, t: usize, p: [f64; 2]) -> [f64; 3] {
74        let [a, b, c] = self.triangles[t].map(|i| self.points[i]);
75        let det = (b[1] - c[1]) * (a[0] - c[0]) + (c[0] - b[0]) * (a[1] - c[1]);
76        let l1 = ((b[1] - c[1]) * (p[0] - c[0]) + (c[0] - b[0]) * (p[1] - c[1])) / det;
77        let l2 = ((c[1] - a[1]) * (p[0] - c[0]) + (a[0] - c[0]) * (p[1] - c[1])) / det;
78        [l1, l2, 1.0 - l1 - l2]
79    }
80
81    /// A triangle containing `p` and its barycentric coordinates, allowing a relative slack of
82    /// `100 ε` on the coordinates (as Qhull's `find_simplex`); `None` outside the convex hull.
83    pub fn find(&self, p: [f64; 2]) -> Option<(usize, [f64; 3])> {
84        if !p.iter().all(|v| v.is_finite()) {
85            return None;
86        }
87        let cx = (p[0] - self.origin[0]) / self.cell[0];
88        let cy = (p[1] - self.origin[1]) / self.cell[1];
89        let eps = 100.0 * f64::EPSILON;
90        if cx < -eps || cy < -eps || cx > self.dims[0] as f64 + eps || cy > self.dims[1] as f64 + eps {
91            return None;
92        }
93        let (ix, iy) = ((cx.floor().max(0.0) as usize).min(self.dims[0] - 1), (cy.floor().max(0.0) as usize).min(self.dims[1] - 1));
94        self.buckets[ix * self.dims[1] + iy].iter().find_map(|&t| {
95            let b = self.barycentric(t, p);
96            b.iter().all(|&v| v >= -eps).then_some((t, b))
97        })
98    }
99
100    /// The neighbours of each vertex (sorted, without duplicates).
101    pub fn vertex_neighbors(&self) -> Vec<Vec<usize>> {
102        let mut out = vec![Vec::new(); self.points.len()];
103        for tr in &self.triangles {
104            for k in 0..3 {
105                out[tr[k]].push(tr[(k + 1) % 3]);
106                out[tr[k]].push(tr[(k + 2) % 3]);
107            }
108        }
109        for v in out.iter_mut() {
110            v.sort_unstable();
111            v.dedup();
112        }
113        out
114    }
115}
116
117/// Piecewise-linear interpolation on the Delaunay triangulation (SciPy's
118/// `LinearNDInterpolator` in 2-D): barycentric weights of the containing triangle.
119#[derive(Clone, Debug)]
120pub struct LinearNDInterpolator {
121    tri: TriangulationIndex,
122    values: Vec<f64>,
123    pub fill_value: f64,
124}
125
126impl LinearNDInterpolator {
127    pub fn new(points: &[[f64; 2]], values: &[f64]) -> Result<LinearNDInterpolator, ErrorsJSL> {
128        if points.len() != values.len() {
129            return Err(ErrorsJSL::InvalidInputRange("one value per point"));
130        }
131        Ok(LinearNDInterpolator { tri: TriangulationIndex::new(points)?, values: values.to_vec(), fill_value: f64::NAN })
132    }
133
134    /// The interpolated value, or `fill_value` (`NaN` by default) outside the convex hull.
135    pub fn evaluate(&self, p: [f64; 2]) -> f64 {
136        match self.tri.find(p) {
137            Some((t, b)) => (0..3).map(|k| b[k] * self.values[self.tri.triangles[t][k]]).sum(),
138            None => self.fill_value,
139        }
140    }
141}
142
143// ANCHOR: gradients
144/// Gradient estimates at the vertices that minimise the integrated squared second derivative of
145/// the Clough-Tocher interpolant along every edge (Nielson's global method, SciPy's
146/// `estimate_gradients_2d_global`). Each vertex's 2 × 2 local problem is solved in turn with the
147/// current estimates at its neighbours (Gauss-Seidel), until the largest change is below `tol`
148/// (relative to the gradient, or absolute when it is below 1) or after `max_iterations` sweeps.
149pub fn estimate_gradients_2d_global(tri: &TriangulationIndex, values: &[f64], tol: f64, max_iterations: usize) -> Vec<[f64; 2]> {
150    let nbrs = tri.vertex_neighbors();
151    let mut y = vec![[0.0; 2]; tri.points.len()];
152    for _ in 0..max_iterations {
153        let mut err = 0.0f64;
154        for ip in 0..tri.points.len() {
155            let (mut q0, mut q1, mut q3, mut s0, mut s1) = (0.0, 0.0, 0.0, 0.0, 0.0);
156            for &jp in &nbrs[ip] {
157                let ex = tri.points[jp][0] - tri.points[ip][0];
158                let ey = tri.points[jp][1] - tri.points[ip][1];
159                let l = ex.hypot(ey);
160                let l3 = l * l * l;
161                let (f1, f2) = (values[ip], values[jp]);
162                let df2 = -ex * y[jp][0] - ey * y[jp][1];
163                q0 += 4.0 * ex * ex / l3;
164                q1 += 4.0 * ex * ey / l3;
165                q3 += 4.0 * ey * ey / l3;
166                s0 += (6.0 * (f1 - f2) - 2.0 * df2) * ex / l3;
167                s1 += (6.0 * (f1 - f2) - 2.0 * df2) * ey / l3;
168            }
169            let det = q0 * q3 - q1 * q1;
170            let r0 = (q3 * s0 - q1 * s1) / det;
171            let r1 = (-q1 * s0 + q0 * s1) / det;
172            let change = (y[ip][0] + r0).abs().max((y[ip][1] + r1).abs()) / r0.abs().max(r1.abs()).max(1.0);
173            y[ip] = [-r0, -r1];
174            err = err.max(change);
175        }
176        if err < tol {
177            break;
178        }
179    }
180    y
181}
182// ANCHOR_END: gradients
183
184/// The C¹ piecewise-cubic Clough-Tocher interpolant (SciPy's `CloughTocher2DInterpolator`): each
185/// triangle is split at its centroid into three cubic Bézier patches, fixed by the values and
186/// gradients at the vertices and by requiring the cross-boundary derivative to be linear along
187/// each edge.
188#[derive(Clone, Debug)]
189pub struct CloughTocher2DInterpolator {
190    tri: TriangulationIndex,
191    values: Vec<f64>,
192    gradients: Vec<[f64; 2]>,
193    pub fill_value: f64,
194}
195
196impl CloughTocher2DInterpolator {
197    /// Triangulates, estimates the gradients (tolerance `1e-6`, at most 400 sweeps, as SciPy).
198    pub fn new(points: &[[f64; 2]], values: &[f64]) -> Result<CloughTocher2DInterpolator, ErrorsJSL> {
199        if points.len() != values.len() {
200            return Err(ErrorsJSL::InvalidInputRange("one value per point"));
201        }
202        let tri = TriangulationIndex::new(points)?;
203        let gradients = estimate_gradients_2d_global(&tri, values, 1e-6, 400);
204        Ok(CloughTocher2DInterpolator { tri, values: values.to_vec(), gradients, fill_value: f64::NAN })
205    }
206
207    /// The estimated gradients at the data points.
208    pub fn gradients(&self) -> &[[f64; 2]] {
209        &self.gradients
210    }
211
212    /// The interpolated value, or `fill_value` outside the convex hull.
213    pub fn evaluate(&self, p: [f64; 2]) -> f64 {
214        match self.tri.find(p) {
215            Some((t, b)) => self.single(t, b),
216            None => self.fill_value,
217        }
218    }
219
220    // ANCHOR: clough_tocher
221    /// SciPy's `_clough_tocher_2d_single`: the Bézier ordinates of the three sub-triangles from
222    /// the vertex data, the cross-derivative direction taken towards the neighbouring triangle's
223    /// centroid (which makes the scheme affine invariant), and evaluation in extended barycentric
224    /// coordinates.
225    fn single(&self, t: usize, b: [f64; 3]) -> f64 {
226        let tr = self.tri.triangles[t];
227        let p = |k: usize| self.tri.points[tr[k]];
228        let (e12x, e12y) = (p(1)[0] - p(0)[0], p(1)[1] - p(0)[1]);
229        let (e23x, e23y) = (p(2)[0] - p(1)[0], p(2)[1] - p(1)[1]);
230        let (e31x, e31y) = (p(0)[0] - p(2)[0], p(0)[1] - p(2)[1]);
231        let f = |k: usize| self.values[tr[k]];
232        let g = |k: usize| self.gradients[tr[k]];
233        let (f1, f2, f3) = (f(0), f(1), f(2));
234        let df12 = g(0)[0] * e12x + g(0)[1] * e12y;
235        let df21 = -(g(1)[0] * e12x + g(1)[1] * e12y);
236        let df23 = g(1)[0] * e23x + g(1)[1] * e23y;
237        let df32 = -(g(2)[0] * e23x + g(2)[1] * e23y);
238        let df31 = g(2)[0] * e31x + g(2)[1] * e31y;
239        let df13 = -(g(0)[0] * e31x + g(0)[1] * e31y);
240        let c3000 = f1;
241        let c2100 = (df12 + 3.0 * c3000) / 3.0;
242        let c2010 = (df13 + 3.0 * c3000) / 3.0;
243        let c0300 = f2;
244        let c1200 = (df21 + 3.0 * c0300) / 3.0;
245        let c0210 = (df23 + 3.0 * c0300) / 3.0;
246        let c0030 = f3;
247        let c1020 = (df31 + 3.0 * c0030) / 3.0;
248        let c0120 = (df32 + 3.0 * c0030) / 3.0;
249        let c2001 = (c2100 + c2010 + c3000) / 3.0;
250        let c0201 = (c1200 + c0300 + c0210) / 3.0;
251        let c0021 = (c1020 + c0120 + c0030) / 3.0;
252        let mut gk = [0.0; 3];
253        for (k, gv) in gk.iter_mut().enumerate() {
254            let Some(nt) = self.tri.neighbors[t][k] else {
255                *gv = -0.5;
256                continue;
257            };
258            let ntr = self.tri.triangles[nt];
259            let cen = [(0..3).map(|i| self.tri.points[ntr[i]][0]).sum::<f64>() / 3.0, (0..3).map(|i| self.tri.points[ntr[i]][1]).sum::<f64>() / 3.0];
260            let c = self.tri.barycentric(t, cen);
261            *gv = match k {
262                0 => (2.0 * c[2] + c[1] - 1.0) / (2.0 - 3.0 * c[2] - 3.0 * c[1]),
263                1 => (2.0 * c[0] + c[2] - 1.0) / (2.0 - 3.0 * c[0] - 3.0 * c[2]),
264                _ => (2.0 * c[1] + c[0] - 1.0) / (2.0 - 3.0 * c[1] - 3.0 * c[0]),
265            };
266        }
267        let c0111 = (gk[0] * (-c0300 + 3.0 * c0210 - 3.0 * c0120 + c0030) + (-c0300 + 2.0 * c0210 - c0120 + c0021 + c0201)) / 2.0;
268        let c1011 = (gk[1] * (-c0030 + 3.0 * c1020 - 3.0 * c2010 + c3000) + (-c0030 + 2.0 * c1020 - c2010 + c2001 + c0021)) / 2.0;
269        let c1101 = (gk[2] * (-c3000 + 3.0 * c2100 - 3.0 * c1200 + c0300) + (-c3000 + 2.0 * c2100 - c1200 + c2001 + c0201)) / 2.0;
270        let c1002 = (c1101 + c1011 + c2001) / 3.0;
271        let c0102 = (c1101 + c0111 + c0201) / 3.0;
272        let c0012 = (c1011 + c0111 + c0021) / 3.0;
273        let c0003 = (c1002 + c0102 + c0012) / 3.0;
274        let minval = b[0].min(b[1]).min(b[2]);
275        let (b1, b2, b3, b4) = (b[0] - minval, b[1] - minval, b[2] - minval, 3.0 * minval);
276        b1.powi(3) * c3000 + 3.0 * b1 * b1 * b2 * c2100 + 3.0 * b1 * b1 * b3 * c2010 + 3.0 * b1 * b1 * b4 * c2001 + 3.0 * b1 * b2 * b2 * c1200
277            + 6.0 * b1 * b2 * b4 * c1101 + 3.0 * b1 * b3 * b3 * c1020 + 6.0 * b1 * b3 * b4 * c1011 + 3.0 * b1 * b4 * b4 * c1002
278            + b2.powi(3) * c0300 + 3.0 * b2 * b2 * b3 * c0210 + 3.0 * b2 * b2 * b4 * c0201 + 3.0 * b2 * b3 * b3 * c0120
279            + 6.0 * b2 * b3 * b4 * c0111 + 3.0 * b2 * b4 * b4 * c0102 + b3.powi(3) * c0030 + 3.0 * b3 * b3 * b4 * c0021
280            + 3.0 * b3 * b4 * b4 * c0012 + b4.powi(3) * c0003
281    }
282    // ANCHOR_END: clough_tocher
283}
284
285/// Nearest-neighbour interpolation in any dimension (SciPy's `NearestNDInterpolator`); ties go
286/// to the first point.
287#[derive(Clone, Debug)]
288pub struct NearestNDInterpolator {
289    points: Vec<Vec<f64>>,
290    values: Vec<f64>,
291}
292
293impl NearestNDInterpolator {
294    pub fn new(points: &[Vec<f64>], values: &[f64]) -> Result<NearestNDInterpolator, ErrorsJSL> {
295        if points.is_empty() || points.len() != values.len() {
296            return Err(ErrorsJSL::InvalidInputRange("need one value per point"));
297        }
298        let d = points[0].len();
299        if points.iter().any(|p| p.len() != d) {
300            return Err(ErrorsJSL::InvalidInputRange("all points must have the same dimension"));
301        }
302        Ok(NearestNDInterpolator { points: points.to_vec(), values: values.to_vec() })
303    }
304
305    pub fn evaluate(&self, p: &[f64]) -> f64 {
306        let dist = |q: &Vec<f64>| q.iter().zip(p).map(|(a, b)| (a - b) * (a - b)).sum::<f64>();
307        let mut best = (0, f64::INFINITY);
308        for (i, q) in self.points.iter().enumerate() {
309            let d = dist(q);
310            if d < best.1 {
311                best = (i, d);
312            }
313        }
314        self.values[best.0]
315    }
316}
317
318/// The method of [`griddata`].
319#[derive(Clone, Copy, Debug, PartialEq, Eq)]
320pub enum GriddataMethod {
321    Nearest,
322    Linear,
323    Cubic,
324}
325
326/// Interpolates scattered 2-D data at the query points (SciPy's `griddata`): nearest neighbour,
327/// piecewise linear or Clough-Tocher; outside the convex hull the linear and cubic methods return
328/// `NaN`.
329pub fn griddata(points: &[[f64; 2]], values: &[f64], queries: &[[f64; 2]], method: GriddataMethod) -> Result<Vec<f64>, ErrorsJSL> {
330    Ok(match method {
331        GriddataMethod::Nearest => {
332            let n = NearestNDInterpolator::new(&points.iter().map(|p| p.to_vec()).collect::<Vec<_>>(), values)?;
333            queries.iter().map(|q| n.evaluate(q)).collect()
334        }
335        GriddataMethod::Linear => {
336            let l = LinearNDInterpolator::new(points, values)?;
337            queries.iter().map(|&q| l.evaluate(q)).collect()
338        }
339        GriddataMethod::Cubic => {
340            let c = CloughTocher2DInterpolator::new(points, values)?;
341            queries.iter().map(|&q| c.evaluate(q)).collect()
342        }
343    })
344}
345
346#[cfg(test)]
347mod tests {
348    use super::*;
349
350    fn points() -> Vec<[f64; 2]> {
351        let mut s: u64 = 12345;
352        let mut next = || {
353            s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
354            (s >> 11) as f64 / (1u64 << 53) as f64
355        };
356        let mut p: Vec<[f64; 2]> = (0..80).map(|_| [next(), next()]).collect();
357        p.extend([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]]);
358        p
359    }
360
361    #[test]
362    fn linear_reproduces_planes_and_cubic_reproduces_quadratics_approximately() {
363        let p = points();
364        let plane: Vec<f64> = p.iter().map(|q| 2.0 * q[0] - q[1] + 0.5).collect();
365        let l = LinearNDInterpolator::new(&p, &plane).unwrap();
366        for q in [[0.3, 0.7], [0.91, 0.05], [0.5, 0.5]] {
367            assert!((l.evaluate(q) - (2.0 * q[0] - q[1] + 0.5)).abs() < 1e-12);
368        }
369        assert!(l.evaluate([1.5, 0.5]).is_nan());
370        let ct = CloughTocher2DInterpolator::new(&p, &plane).unwrap();
371        for q in [[0.3, 0.7], [0.91, 0.05], [0.5, 0.5]] {
372            assert!((ct.evaluate(q) - (2.0 * q[0] - q[1] + 0.5)).abs() < 1e-6);
373        }
374        let quad: Vec<f64> = p.iter().map(|q| q[0] * q[0] + q[0] * q[1]).collect();
375        let ct = CloughTocher2DInterpolator::new(&p, &quad).unwrap();
376        let ln = LinearNDInterpolator::new(&p, &quad).unwrap();
377        let (mut e_ct, mut e_l) = (0.0f64, 0.0f64);
378        for i in 1..20 {
379            for j in 1..20 {
380                let q = [i as f64 / 20.0, j as f64 / 20.0];
381                let exact = q[0] * q[0] + q[0] * q[1];
382                e_ct = e_ct.max((ct.evaluate(q) - exact).abs());
383                e_l = e_l.max((ln.evaluate(q) - exact).abs());
384            }
385        }
386        assert!(e_ct < e_l / 3.0, "Clough-Tocher {e_ct} vs linear {e_l}");
387        let nn = griddata(&p, &quad, &[p[7]], GriddataMethod::Nearest).unwrap();
388        assert_eq!(nn[0], quad[7]);
389    }
390}