Skip to main content

lib_jsl_geometry/algorithms/
hull_nd.rs

1//! Convex hulls, Delaunay triangulations and Voronoi diagrams in any dimension, half-space
2//! intersections and Voronoi diagrams on the sphere, following `scipy.spatial` (which wraps
3//! Qhull): [`ConvexHullNd`], [`DelaunayNd`], [`VoronoiNd`], [`HalfspaceIntersection`] and
4//! [`SphericalVoronoi`].
5//!
6//! Everything rests on one n-dimensional Quickhull (Barber, Dobkin and Huhdanpaa, 1996), the
7//! algorithm inside Qhull: start from a simplex, and repeatedly take the point farthest outside
8//! some facet, delete the facets it can see, and join it to the horizon. Delaunay triangulations
9//! are lower hulls of the points lifted to the paraboloid `x_{d+1} = ‖x‖²`, Voronoi diagrams
10//! their duals, and half-space intersections hulls of the dual points.
11//!
12//! See the book entry [Geometry in any dimension](https://jwkunz.github.io/lib_jsl/book/geometry/hulls-nd.html).
13
14#![allow(clippy::needless_range_loop)]
15
16use lib_jsl_core::ErrorsJSL;
17use std::collections::HashMap;
18
19fn dot(a: &[f64], b: &[f64]) -> f64 {
20    a.iter().zip(b).map(|(x, y)| x * y).sum()
21}
22
23fn sub(a: &[f64], b: &[f64]) -> Vec<f64> {
24    a.iter().zip(b).map(|(x, y)| x - y).collect()
25}
26
27/// The determinant of a square matrix by Gaussian elimination with partial pivoting.
28fn det(mut m: Vec<Vec<f64>>) -> f64 {
29    let n = m.len();
30    let mut d = 1.0;
31    for k in 0..n {
32        let p = (k..n).max_by(|&i, &j| m[i][k].abs().total_cmp(&m[j][k].abs())).unwrap();
33        if m[p][k] == 0.0 {
34            return 0.0;
35        }
36        if p != k {
37            m.swap(p, k);
38            d = -d;
39        }
40        d *= m[k][k];
41        for i in k + 1..n {
42            let f = m[i][k] / m[k][k];
43            for j in k..n {
44                m[i][j] -= f * m[k][j];
45            }
46        }
47    }
48    d
49}
50
51/// A unit vector orthogonal to the `d − 1` rows of `rows` (each of length `d`): the last column
52/// of the Householder QR factor of `rowsᵀ`.
53fn normal_of(rows: &[Vec<f64>], d: usize) -> Vec<f64> {
54    let k = rows.len();
55    // Columns of A = rowsᵀ (d × k); accumulate Householder reflectors H_j = I − 2 v vᵀ.
56    let mut a: Vec<Vec<f64>> = rows.to_vec(); // a[j] is column j
57    let mut vs: Vec<Vec<f64>> = Vec::new();
58    for j in 0..k {
59        let mut x = a[j].clone();
60        for v in &vs {
61            let c = 2.0 * dot(v, &x);
62            x.iter_mut().zip(v).for_each(|(xi, vi)| *xi -= c * vi);
63        }
64        let tail_norm = x[j..].iter().map(|t| t * t).sum::<f64>().sqrt();
65        let mut v = vec![0.0; d];
66        if tail_norm > 0.0 {
67            let alpha = if x[j] > 0.0 { -tail_norm } else { tail_norm };
68            v[j..].copy_from_slice(&x[j..]);
69            v[j] -= alpha;
70            let vn = v.iter().map(|t| t * t).sum::<f64>().sqrt();
71            if vn > 0.0 {
72                v.iter_mut().for_each(|t| *t /= vn);
73            }
74        }
75        vs.push(v);
76        a[j] = x;
77    }
78    // Q e_d = H_0 H_1 … H_{k−1} e_d.
79    let mut e = vec![0.0; d];
80    e[d - 1] = 1.0;
81    for v in vs.iter().rev() {
82        let c = 2.0 * dot(v, &e);
83        e.iter_mut().zip(v).for_each(|(ei, vi)| *ei -= c * vi);
84    }
85    e
86}
87
88/// One hull facet: `d` vertices, the outward unit normal `n` and offset `b` with
89/// `n·x + b = 0` on the facet and `< 0` inside; `neighbors[i]` is the facet across the ridge
90/// opposite `vertices[i]`.
91#[derive(Clone, Debug)]
92struct Facet {
93    vertices: Vec<usize>,
94    normal: Vec<f64>,
95    offset: f64,
96    neighbors: Vec<usize>,
97    outside: Vec<usize>,
98    alive: bool,
99}
100
101/// The raw Quickhull result: facets as vertex lists with their hyperplanes and neighbours, and the
102/// interior point that orients them (a point that stays inside as the hull grows).
103#[derive(Clone, Debug)]
104struct Hull {
105    facets: Vec<Facet>,
106    interior: Vec<f64>,
107}
108
109fn make_facet(points: &[Vec<f64>], vertices: Vec<usize>, interior: &[f64]) -> Facet {
110    let d = interior.len();
111    let p0 = &points[vertices[0]];
112    let rows: Vec<Vec<f64>> = vertices[1..].iter().map(|&v| sub(&points[v], p0)).collect();
113    let mut normal = normal_of(&rows, d);
114    let mut offset = -dot(&normal, p0);
115    if dot(&normal, interior) + offset > 0.0 {
116        normal.iter_mut().for_each(|t| *t = -*t);
117        offset = -offset;
118    }
119    Facet { vertices, normal, offset, neighbors: Vec::new(), outside: Vec::new(), alive: true }
120}
121
122// ANCHOR: quickhull
123/// Quickhull in `d ≥ 2` dimensions. `eps` is the distance below which a point counts as on a
124/// facet; such points are not added (Qhull's default "coplanar points are inside").
125fn quickhull(points: &[Vec<f64>], eps: f64) -> Result<Hull, ErrorsJSL> {
126    let n = points.len();
127    let d = points.first().map_or(0, |p| p.len());
128    if d < 2 || n < d + 1 {
129        return Err(ErrorsJSL::InvalidInputRange("Quickhull needs d ≥ 2 and at least d + 1 points"));
130    }
131    // Initial simplex: the extreme pair along the first coordinate, then repeatedly the point
132    // farthest from the affine hull of those chosen (Gram-Schmidt on the differences).
133    let lo = (0..n).min_by(|&a, &b| points[a][0].total_cmp(&points[b][0])).unwrap();
134    let hi = (0..n).max_by(|&a, &b| points[a][0].total_cmp(&points[b][0])).unwrap();
135    let mut simplex = vec![lo];
136    let mut basis: Vec<Vec<f64>> = Vec::new();
137    let mut candidate = Some(hi);
138    while simplex.len() < d + 1 {
139        let next = match candidate.take() {
140            Some(c) if c != simplex[0] => c,
141            _ => (0..n)
142                .max_by(|&a, &b| {
143                    let r = |i: usize| {
144                        let mut v = sub(&points[i], &points[simplex[0]]);
145                        for q in &basis {
146                            let c = dot(q, &v);
147                            v.iter_mut().zip(q).for_each(|(x, y)| *x -= c * y);
148                        }
149                        dot(&v, &v)
150                    };
151                    r(a).total_cmp(&r(b))
152                })
153                .unwrap(),
154        };
155        let mut v = sub(&points[next], &points[simplex[0]]);
156        for q in &basis {
157            let c = dot(q, &v);
158            v.iter_mut().zip(q).for_each(|(x, y)| *x -= c * y);
159        }
160        let vn = dot(&v, &v).sqrt();
161        if vn <= eps.max(f64::MIN_POSITIVE) {
162            return Err(ErrorsJSL::InvalidInputRange("the points lie in a lower-dimensional subspace (the initial simplex is flat)"));
163        }
164        basis.push(v.iter().map(|t| t / vn).collect());
165        simplex.push(next);
166    }
167    let interior: Vec<f64> = (0..d).map(|k| simplex.iter().map(|&i| points[i][k]).sum::<f64>() / (d + 1) as f64).collect();
168    let mut facets: Vec<Facet> = (0..=d)
169        .map(|skip| make_facet(points, simplex.iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, &v)| v).collect(), &interior))
170        .collect();
171    // Facet i omits simplex vertex i; the facet across the ridge opposite vertex v of facet i is
172    // the facet that omits v.
173    for i in 0..=d {
174        let verts = facets[i].vertices.clone();
175        facets[i].neighbors = verts.iter().map(|v| simplex.iter().position(|s| s == v).unwrap()).collect();
176    }
177    let in_simplex: Vec<bool> = (0..n).map(|i| simplex.contains(&i)).collect();
178    for p in 0..n {
179        if in_simplex[p] {
180            continue;
181        }
182        if let Some((f, _)) = facets.iter().enumerate().map(|(f, fa)| (f, dot(&fa.normal, &points[p]) + fa.offset)).filter(|(_, dist)| *dist > eps).max_by(|a, b| a.1.total_cmp(&b.1)) {
183            facets[f].outside.push(p);
184        }
185    }
186    let mut hull = Hull { facets, interior };
187    expand(points, &mut hull, eps);
188    Ok(hull)
189}
190
191/// Adds the points that lie outside facets (already assigned to their facet's `outside` list) to the
192/// hull one at a time, the farthest of a facet first, until no facet has an outside point.
193fn expand(points: &[Vec<f64>], hull: &mut Hull, eps: f64) {
194    let d = hull.interior.len();
195    let interior = hull.interior.clone();
196    let facets = &mut hull.facets;
197    while let Some(start) = facets.iter().position(|f| f.alive && !f.outside.is_empty()) {
198        let fs = &facets[start];
199        let apex = *fs.outside.iter().max_by(|&&a, &&b| (dot(&fs.normal, &points[a]) + fs.offset).total_cmp(&(dot(&fs.normal, &points[b]) + fs.offset))).unwrap();
200        // Visible facets by a search over neighbours. A facet within `eps` of the apex's plane is not
201        // visible, but facets that are nearly coplanar can leave a horizon that does not close up (a
202        // sub-face of the horizon shared by one ridge or three). When that happens the facets a little
203        // below the threshold are taken as visible too, in growing steps, until the horizon is closed.
204        let mut visible = Vec::new();
205        let mut seen: HashMap<usize, bool> = HashMap::new();
206        for band in [0.0, 1.0, 10.0, 100.0, 1e3, 1e4, 1e5] {
207            let threshold = eps * (1.0 - band);
208            visible = vec![start];
209            seen = HashMap::from([(start, true)]);
210            let mut k = 0;
211            while k < visible.len() {
212                let f = visible[k];
213                k += 1;
214                for &g in &facets[f].neighbors.clone() {
215                    if g == usize::MAX || seen.contains_key(&g) {
216                        continue;
217                    }
218                    let vis = dot(&facets[g].normal, &points[apex]) + facets[g].offset > threshold;
219                    seen.insert(g, vis);
220                    if vis {
221                        visible.push(g);
222                    }
223                }
224            }
225            // The horizon closes up if every (d − 3)-face of it lies on exactly two horizon ridges.
226            let mut count: HashMap<Vec<usize>, usize> = HashMap::new();
227            for &f in &visible {
228                for i in 0..d {
229                    if seen.get(&facets[f].neighbors[i]).copied().unwrap_or(false) {
230                        continue;
231                    }
232                    let verts: Vec<usize> = facets[f].vertices.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect();
233                    for skip in 0..verts.len() {
234                        let mut key: Vec<usize> = verts.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &v)| v).collect();
235                        key.sort_unstable();
236                        *count.entry(key).or_insert(0) += 1;
237                    }
238                }
239            }
240            if count.values().all(|&c| c == 2) {
241                break;
242            }
243        }
244        // Horizon ridges: (visible facet, index of the opposite vertex) with an invisible neighbour.
245        let mut new_ids = Vec::new();
246        let mut ridge_map: HashMap<Vec<usize>, (usize, usize)> = HashMap::new();
247        for &f in &visible {
248            for i in 0..d {
249                let g = facets[f].neighbors[i];
250                if seen.get(&g).copied().unwrap_or(false) {
251                    continue;
252                }
253                let mut verts: Vec<usize> = facets[f].vertices.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect();
254                verts.push(apex);
255                let mut nf = make_facet(points, verts, &interior);
256                let id = facets.len();
257                // Neighbour opposite the apex (the last vertex) is g; repoint g's link from f.
258                nf.neighbors = vec![usize::MAX; d];
259                nf.neighbors[d - 1] = g;
260                if let Some(slot) = facets[g].neighbors.iter().position(|&h| h == f) {
261                    facets[g].neighbors[slot] = id;
262                }
263                // Ridges through the apex, keyed by the sorted vertex set without one vertex.
264                for j in 0..d - 1 {
265                    let mut key: Vec<usize> = nf.vertices.iter().enumerate().filter(|(m, _)| *m != j).map(|(_, &v)| v).collect();
266                    key.sort_unstable();
267                    if let Some(&(other, oj)) = ridge_map.get(&key) {
268                        nf.neighbors[j] = other;
269                        facets[other].neighbors[oj] = id;
270                    } else {
271                        ridge_map.insert(key, (id, j));
272                    }
273                }
274                facets.push(nf);
275                new_ids.push(id);
276            }
277        }
278        // Reassign the outside points of the deleted facets.
279        let mut orphans = Vec::new();
280        for &f in &visible {
281            facets[f].alive = false;
282            orphans.append(&mut facets[f].outside);
283        }
284        for p in orphans {
285            if p == apex {
286                continue;
287            }
288            if let Some((f, _)) = new_ids.iter().map(|&f| (f, dot(&facets[f].normal, &points[p]) + facets[f].offset)).filter(|(_, dist)| *dist > eps).max_by(|a, b| a.1.total_cmp(&b.1)) {
289                facets[f].outside.push(p);
290            }
291        }
292    }
293}
294// ANCHOR_END: quickhull
295
296/// Drops the hull vertices that are not extreme. A point on an edge or in the relative interior of a
297/// face of the hull can become a vertex of the simplicial facets (it was outside the hull while it was
298/// still growing); Qhull's facet merging removes it. A vertex is extreme exactly when the normals of
299/// the facets that meet there span `ℝᵈ` (otherwise they lie in the subspace orthogonal to the face the
300/// point is inside). When some are not, the hull is built again on the extreme points alone.
301fn drop_non_extreme(points: &[Vec<f64>], hull: Hull, eps: f64) -> Hull {
302    let d = hull.interior.len();
303    let n = points.len();
304    let spread = (0..d).map(|k| points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max) - points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min)).fold(0.0f64, f64::max);
305    let tol = (5.0 * eps / spread.max(f64::MIN_POSITIVE)).max(1e-14);
306    let mut incident: Vec<Vec<usize>> = vec![Vec::new(); n];
307    for (i, f) in hull.facets.iter().enumerate().filter(|(_, f)| f.alive) {
308        for &v in &f.vertices {
309            incident[v].push(i);
310        }
311    }
312    let mut keep = vec![false; n];
313    let mut all = true;
314    for v in 0..n {
315        if incident[v].is_empty() {
316            continue;
317        }
318        let mut basis: Vec<Vec<f64>> = Vec::new();
319        for &fi in &incident[v] {
320            let mut x = hull.facets[fi].normal.clone();
321            for q in &basis {
322                let c = dot(q, &x);
323                x.iter_mut().zip(q).for_each(|(a, b)| *a -= c * b);
324            }
325            let nn = dot(&x, &x).sqrt();
326            if nn > tol {
327                basis.push(x.iter().map(|t| t / nn).collect());
328                if basis.len() == d {
329                    break;
330                }
331            }
332        }
333        keep[v] = basis.len() == d;
334        all &= keep[v];
335    }
336    if all || keep.iter().filter(|&&k| k).count() <= d {
337        return hull;
338    }
339    let ids: Vec<usize> = (0..n).filter(|&v| keep[v]).collect();
340    let sub_points: Vec<Vec<f64>> = ids.iter().map(|&v| points[v].clone()).collect();
341    match quickhull(&sub_points, eps) {
342        Ok(mut h) => {
343            for f in h.facets.iter_mut() {
344                f.vertices.iter_mut().for_each(|v| *v = ids[*v]);
345            }
346            h
347        }
348        Err(_) => hull,
349    }
350}
351
352/// A tolerance for "on the facet" from the size of the coordinates (Qhull's is similar).
353fn default_eps(points: &[Vec<f64>]) -> f64 {
354    let d = points.first().map_or(1, |p| p.len());
355    let m = points.iter().flat_map(|p| p.iter()).fold(0.0f64, |m, v| m.max(v.abs())).max(1e-300);
356    let spread = (0..d).map(|k| points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max) - points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min)).fold(0.0f64, f64::max);
357    10.0 * (d as f64) * f64::EPSILON * m.max(spread)
358}
359
360fn factorial(k: usize) -> f64 {
361    (1..=k).map(|i| i as f64).product()
362}
363
364/// The `(d − 1)`-volume of a simplex with `d` vertices in `ℝ^d`, from the Gram determinant.
365fn facet_area(points: &[Vec<f64>], verts: &[usize]) -> f64 {
366    let p0 = &points[verts[0]];
367    let e: Vec<Vec<f64>> = verts[1..].iter().map(|&v| sub(&points[v], p0)).collect();
368    let g: Vec<Vec<f64>> = e.iter().map(|a| e.iter().map(|b| dot(a, b)).collect()).collect();
369    det(g).max(0.0).sqrt() / factorial(e.len())
370}
371
372/// Options in the spirit of Qhull's `qhull_options` string (SciPy's `qhull_options` argument),
373/// for the subset that this implementation can honour. [`QhullOptions::parse`] reads a string:
374///
375/// - `Qt` (triangulated output), `Qbb` (scale the lifted coordinate), `Qz` (a point at infinity),
376///   `Qc` and `Pp` are always on or without effect here, and are accepted;
377/// - `QJ` or `QJn` joggles the input: every coordinate is moved by a deterministic pseudo-random
378///   amount of up to `n` times the extent of the point set (default 3e-12), which makes
379///   degenerate input (cospherical points, coplanar facets) simplicial at the price of a result
380///   for the moved points;
381/// - `En` sets the distance below which a point counts as on a facet (absolute, as Qhull's
382///   `E` roundoff error), replacing the default derived from the coordinates.
383///
384/// Any other option is an error, so that nothing is silently ignored.
385#[derive(Clone, Debug, PartialEq, Default)]
386#[non_exhaustive]
387pub struct QhullOptions {
388    /// Joggle size relative to the extent of the points (`QJ`).
389    pub joggle: Option<f64>,
390    /// The coplanarity tolerance (`E`).
391    pub tolerance: Option<f64>,
392}
393
394impl QhullOptions {
395    /// Parses a Qhull option string such as `"Qt QJ1e-9 E1e-12"` (whitespace-separated; the empty
396    /// string gives the defaults).
397    pub fn parse(options: &str) -> Result<QhullOptions, ErrorsJSL> {
398        let mut out = QhullOptions::default();
399        for token in options.split_whitespace() {
400            match token {
401                "Qt" | "Qbb" | "Qz" | "Qc" | "Pp" | "Qx" => {}
402                "QJ" => out.joggle = Some(3e-12),
403                t if t.starts_with("QJ") => out.joggle = Some(t[2..].parse().map_err(|_| ErrorsJSL::InvalidInputRange("QJ needs a number, as in QJ1e-9"))?),
404                t if t.starts_with('E') && t.len() > 1 => out.tolerance = Some(t[1..].parse().map_err(|_| ErrorsJSL::InvalidInputRange("E needs a number, as in E1e-12"))?),
405                _ => return Err(ErrorsJSL::InvalidInputRange("unsupported Qhull option (supported: Qt, Qbb, Qz, Qc, Pp, Qx, QJ[n], E<n>)")),
406            }
407        }
408        Ok(out)
409    }
410
411    /// The points moved by the joggle, if there is one.
412    fn joggled(&self, points: &[Vec<f64>]) -> Vec<Vec<f64>> {
413        let Some(size) = self.joggle else { return points.to_vec() };
414        let d = points.first().map_or(0, |p| p.len());
415        let extent = (0..d).map(|k| points.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max) - points.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min)).fold(0.0f64, f64::max).max(f64::MIN_POSITIVE);
416        let mut state = 0xD1B5_4A32_D192_ED03u64;
417        points
418            .iter()
419            .map(|p| {
420                p.iter()
421                    .map(|&x| {
422                        state ^= state << 13;
423                        state ^= state >> 7;
424                        state ^= state << 17;
425                        x + ((state >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * 2.0 * size * extent
426                    })
427                    .collect()
428            })
429            .collect()
430    }
431}
432
433// ANCHOR: convex_hull_nd
434/// The convex hull of points in any dimension `d ≥ 2` (SciPy's `ConvexHull`), with simplicial
435/// facets. Points within a small tolerance of a facet are treated as inside.
436#[derive(Clone, Debug)]
437#[non_exhaustive]
438pub struct ConvexHullNd {
439    pub points: Vec<Vec<f64>>,
440    /// Each facet as `d` point indices (SciPy's `simplices`).
441    pub simplices: Vec<Vec<usize>>,
442    /// Each facet's hyperplane `[n, b]` with outward unit normal `n` and `n·x + b ≤ 0` inside
443    /// (SciPy's `equations`).
444    pub equations: Vec<Vec<f64>>,
445    /// For each facet, the facets across the ridges opposite each of its vertices.
446    pub neighbors: Vec<Vec<usize>>,
447    /// The hull's vertices, sorted (SciPy's `vertices` is in counter-clockwise order in 2-D).
448    pub vertices: Vec<usize>,
449    /// The hull's facets as Qhull sees them after merging: for each facet of the polytope (all the
450    /// coplanar pieces of a cube's face, say), the indices into `simplices` of the simplices that
451    /// triangulate it. A facet that is already a simplex has one entry.
452    pub facet_groups: Vec<Vec<usize>>,
453    /// The `d`-volume enclosed and the `(d − 1)`-volume of the boundary.
454    pub volume: f64,
455    pub area: f64,
456    /// The Quickhull state, kept so that points can be added without starting over.
457    hull: Hull,
458    eps: f64,
459    /// The points the hull was computed from (the joggled ones, with `QJ`).
460    work: Vec<Vec<f64>>,
461    options: QhullOptions,
462}
463
464impl ConvexHullNd {
465    pub fn new(points: &[Vec<f64>]) -> Result<ConvexHullNd, ErrorsJSL> {
466        Self::with_options(points, &QhullOptions::default())
467    }
468
469    /// As [`ConvexHullNd::new`] with Qhull-style options (see [`QhullOptions`]).
470    pub fn with_options(points: &[Vec<f64>], options: &QhullOptions) -> Result<ConvexHullNd, ErrorsJSL> {
471        let d = points.first().map_or(0, |p| p.len());
472        if points.iter().any(|p| p.len() != d || p.iter().any(|v| !v.is_finite())) {
473            return Err(ErrorsJSL::InvalidInputRange("points must be finite and of one dimension"));
474        }
475        let work = options.joggled(points);
476        let eps = options.tolerance.unwrap_or_else(|| default_eps(&work));
477        let hull = drop_non_extreme(&work, quickhull(&work, eps)?, eps);
478        Ok(Self::from_hull(points.to_vec(), work, hull, eps, options.clone()))
479    }
480
481    fn from_hull(points: Vec<Vec<f64>>, work: Vec<Vec<f64>>, hull: Hull, eps: f64, options: QhullOptions) -> ConvexHullNd {
482        let d = hull.interior.len();
483        let alive: Vec<usize> = (0..hull.facets.len()).filter(|&i| hull.facets[i].alive).collect();
484        let index: HashMap<usize, usize> = alive.iter().enumerate().map(|(k, &i)| (i, k)).collect();
485        // Facets that lie in one hyperplane (the pieces of a cube's face, a lattice's cell) are one facet of the
486        // polytope: group them, and triangulate each group by a rule that depends only on its vertices.
487        let mut parent: Vec<usize> = (0..alive.len()).collect();
488        fn find(parent: &mut [usize], mut i: usize) -> usize {
489            while parent[i] != i {
490                parent[i] = parent[parent[i]];
491                i = parent[i];
492            }
493            i
494        }
495        for (k, &i) in alive.iter().enumerate() {
496            for &g in &hull.facets[i].neighbors {
497                let kg = index[&g];
498                if kg > k {
499                    let mut union: Vec<usize> = hull.facets[i].vertices.iter().chain(&hull.facets[g].vertices).copied().collect();
500                    union.sort_unstable();
501                    union.dedup();
502                    if affine_rank(&work, &union, eps) < d {
503                        let (a, b) = (find(&mut parent, k), find(&mut parent, kg));
504                        parent[a] = b;
505                    }
506                }
507            }
508        }
509        let mut members: HashMap<usize, Vec<usize>> = HashMap::new();
510        for k in 0..alive.len() {
511            let r = find(&mut parent, k);
512            members.entry(r).or_default().push(k);
513        }
514        let mut roots: Vec<usize> = members.keys().copied().collect();
515        roots.sort_unstable();
516        let mut simplices: Vec<Vec<usize>> = Vec::new();
517        let mut equations: Vec<Vec<f64>> = Vec::new();
518        let mut facet_groups: Vec<Vec<usize>> = Vec::new();
519        let equation = |i: usize| -> Vec<f64> {
520            let mut e = hull.facets[i].normal.clone();
521            e.push(hull.facets[i].offset);
522            e
523        };
524        for r in roots {
525            let group = &members[&r];
526            let first = group[0];
527            if group.len() == 1 {
528                facet_groups.push(vec![simplices.len()]);
529                simplices.push(hull.facets[alive[first]].vertices.clone());
530                equations.push(equation(alive[first]));
531                continue;
532            }
533            // The boundary of the merged facet: the ridges that belong to one piece only.
534            let mut count: HashMap<Vec<usize>, (usize, Vec<usize>)> = HashMap::new();
535            for &k in group {
536                let v = &hull.facets[alive[k]].vertices;
537                for skip in 0..d {
538                    let ridge: Vec<usize> = v.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &x)| x).collect();
539                    let mut key = ridge.clone();
540                    key.sort_unstable();
541                    count.entry(key).or_insert((0, ridge)).0 += 1;
542                }
543            }
544            let mut rim: Vec<Vec<usize>> = count.into_values().filter(|(c, _)| *c == 1).map(|(_, f)| f).collect();
545            rim.sort_unstable();
546            let mut tri = pulling_triangulation(&work, rim, eps);
547            if tri.is_empty() || tri.iter().any(|t| t.len() != d) {
548                // Numerical trouble: keep the pieces as the hull built them.
549                tri = group.iter().map(|&k| hull.facets[alive[k]].vertices.clone()).collect();
550            }
551            for t in tri.iter_mut() {
552                t.sort_unstable();
553            }
554            tri.sort_unstable();
555            let eq = equation(alive[first]);
556            let mut ids = Vec::new();
557            for t in tri {
558                ids.push(simplices.len());
559                simplices.push(t);
560                equations.push(eq.clone());
561            }
562            facet_groups.push(ids);
563        }
564        // Neighbours across ridges, from the simplices themselves.
565        let mut by_ridge: HashMap<Vec<usize>, Vec<(usize, usize)>> = HashMap::new();
566        for (si, sv) in simplices.iter().enumerate() {
567            for skip in 0..d {
568                let mut key: Vec<usize> = sv.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &x)| x).collect();
569                key.sort_unstable();
570                by_ridge.entry(key).or_default().push((si, skip));
571            }
572        }
573        let mut neighbors: Vec<Vec<usize>> = vec![vec![usize::MAX; d]; simplices.len()];
574        for sharing in by_ridge.values() {
575            if let [(a, ja), (b, jb)] = sharing[..] {
576                neighbors[a][ja] = b;
577                neighbors[b][jb] = a;
578            }
579        }
580        let mut vertices: Vec<usize> = simplices.iter().flatten().copied().collect();
581        vertices.sort_unstable();
582        vertices.dedup();
583        // Volume from a cone over each facet with apex at the vertex centroid.
584        let c: Vec<f64> = (0..d).map(|k| vertices.iter().map(|&v| work[v][k]).sum::<f64>() / vertices.len() as f64).collect();
585        let mut volume = 0.0;
586        let mut area = 0.0;
587        for (s, e) in simplices.iter().zip(&equations) {
588            let a = facet_area(&work, s);
589            area += a;
590            volume += a * (-(dot(&e[..d], &c) + e[d])) / d as f64;
591        }
592        ConvexHullNd { points, simplices, equations, neighbors, vertices, facet_groups, volume, area, hull, eps, work, options }
593    }
594
595    /// Adds points (SciPy's `add_points`): the new points get the next indices. The hull is grown
596    /// from its current state, as Quickhull does: only the new points that lie outside it are
597    /// added, each replacing the facets it sees, and nothing is recomputed for the rest. The hull
598    /// is that of the union (the order of the simplices may differ from a fresh computation).
599    pub fn add_points(&mut self, new: &[Vec<f64>]) -> Result<(), ErrorsJSL> {
600        let d = self.hull.interior.len();
601        if new.iter().any(|p| p.len() != d || p.iter().any(|v| !v.is_finite())) {
602            return Err(ErrorsJSL::InvalidInputRange("points must be finite and of the hull's dimension"));
603        }
604        if new.is_empty() {
605            return Ok(());
606        }
607        let first = self.points.len();
608        let mut points = std::mem::take(&mut self.points);
609        points.extend_from_slice(new);
610        // The joggle of the old points is kept; the new points are joggled the same way.
611        let mut work = std::mem::take(&mut self.work);
612        let moved = if self.options.joggle.is_some() { self.options.joggled(&points)[first..].to_vec() } else { new.to_vec() };
613        work.extend(moved);
614        let eps = self.eps.max(if self.options.tolerance.is_some() { 0.0 } else { default_eps(&work) });
615        let mut hull = std::mem::replace(&mut self.hull, Hull { facets: Vec::new(), interior: Vec::new() });
616        for p in first..work.len() {
617            let best = hull
618                .facets
619                .iter()
620                .enumerate()
621                .filter(|(_, f)| f.alive)
622                .map(|(i, f)| (i, dot(&f.normal, &work[p]) + f.offset))
623                .filter(|(_, dist)| *dist > eps)
624                .max_by(|a, b| a.1.total_cmp(&b.1));
625            if let Some((f, _)) = best {
626                hull.facets[f].outside.push(p);
627            }
628        }
629        expand(&work, &mut hull, eps);
630        let hull = drop_non_extreme(&work, hull, eps);
631        *self = Self::from_hull(points, work, hull, eps, self.options.clone());
632        Ok(())
633    }
634}
635// ANCHOR_END: convex_hull_nd
636
637// ANCHOR: delaunay_nd
638/// The Delaunay triangulation of points in any dimension `d ≥ 2` (SciPy's `Delaunay`): the
639/// lower facets of the hull of the points lifted to `(x, ‖x‖²)`. Degenerate (cospherical) sets,
640/// such as grids, are triangulated by a tiny deterministic perturbation of the lifted
641/// coordinate, which picks one of their valid triangulations (Qhull's "joggle").
642#[derive(Clone, Debug)]
643#[non_exhaustive]
644pub struct DelaunayNd {
645    pub points: Vec<Vec<f64>>,
646    /// Each simplex as `d + 1` point indices.
647    pub simplices: Vec<Vec<usize>>,
648    /// `neighbors[s][i]`: the simplex opposite vertex `i` of simplex `s`, or `None` on the hull.
649    pub neighbors: Vec<Vec<Option<usize>>>,
650    /// For each simplex, the barycentric transform: rows `0..d` hold `T⁻¹` and row `d` the
651    /// vertex `r = x_{v_d}`, so that `c = T⁻¹ (x − r)` gives the first `d` barycentric
652    /// coordinates (SciPy's `transform`).
653    pub transform: Vec<Vec<Vec<f64>>>,
654    /// Whether this is the furthest-site triangulation.
655    pub furthest_site: bool,
656    /// The lifted hull, kept so that points can be added without starting over.
657    state: DelState,
658}
659
660/// The lifted hull behind a [`DelaunayNd`]: the points in the frame fixed at construction (lifted
661/// to the paraboloid, then the point at infinity, then any added points), the Quickhull state,
662/// and what is needed to lift the points that are added later in the same way.
663#[derive(Clone, Debug)]
664struct DelState {
665    /// The lifted points; index `top` is the point at infinity.
666    lifted: Vec<Vec<f64>>,
667    top: usize,
668    hull: Hull,
669    lo: Vec<f64>,
670    scale: f64,
671    /// The state of the generator of the lifting joggle.
672    jog: u64,
673    eps: f64,
674    options: QhullOptions,
675}
676
677fn invert(m: &[Vec<f64>]) -> Option<Vec<Vec<f64>>> {
678    let n = m.len();
679    let mut a: Vec<Vec<f64>> = m.iter().enumerate().map(|(i, r)| {
680        let mut r = r.clone();
681        r.extend((0..n).map(|j| if i == j { 1.0 } else { 0.0 }));
682        r
683    }).collect();
684    for k in 0..n {
685        let p = (k..n).max_by(|&i, &j| a[i][k].abs().total_cmp(&a[j][k].abs()))?;
686        if a[p][k].abs() < 1e-300 {
687            return None;
688        }
689        a.swap(k, p);
690        let piv = a[k][k];
691        a[k].iter_mut().for_each(|v| *v /= piv);
692        for i in 0..n {
693            if i != k {
694                let f = a[i][k];
695                if f != 0.0 {
696                    let rk = a[k].clone();
697                    a[i].iter_mut().zip(&rk).for_each(|(x, y)| *x -= f * y);
698                }
699            }
700        }
701    }
702    Some(a.into_iter().map(|r| r[n..].to_vec()).collect())
703}
704
705/// The rank of the vectors `p − p₀` for `p` in `vs` (the affine dimension of the points), to tolerance `tol`.
706fn affine_rank(points: &[Vec<f64>], vs: &[usize], tol: f64) -> usize {
707    let p0 = &points[vs[0]];
708    let mut basis: Vec<Vec<f64>> = Vec::new();
709    for &v in &vs[1..] {
710        let mut x = sub(&points[v], p0);
711        for q in &basis {
712            let c = dot(q, &x);
713            x.iter_mut().zip(q).for_each(|(a, b)| *a -= c * b);
714        }
715        let n = dot(&x, &x).sqrt();
716        if n > tol {
717            basis.push(x.iter().map(|t| t / n).collect());
718        }
719    }
720    basis.len()
721}
722
723/// The pulling triangulation of a convex polytope given by the simplices of its boundary: every facet
724/// of the polytope that does not contain the polytope's lexicographically smallest vertex (the apex) is
725/// itself triangulated the same way (from its own boundary) and coned to the apex. The result depends
726/// only on the vertices, not on how the boundary was triangulated. `boundary` holds `k` vertices per
727/// simplex; the triangulation has `k + 1`.
728fn pulling_triangulation(points: &[Vec<f64>], boundary: Vec<Vec<usize>>, tol: f64) -> Vec<Vec<usize>> {
729    let Some(first) = boundary.first() else { return Vec::new() };
730    let k = first.len();
731    let m = boundary.len();
732    // Facets of the polytope: boundary simplices that share a ridge and lie in one flat of dimension k − 1.
733    let mut parent: Vec<usize> = (0..m).collect();
734    fn find(parent: &mut [usize], mut i: usize) -> usize {
735        while parent[i] != i {
736            parent[i] = parent[parent[i]];
737            i = parent[i];
738        }
739        i
740    }
741    let mut by_ridge: HashMap<Vec<usize>, Vec<usize>> = HashMap::new();
742    for (si, s) in boundary.iter().enumerate() {
743        for skip in 0..k {
744            let mut key: Vec<usize> = s.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &v)| v).collect();
745            key.sort_unstable();
746            by_ridge.entry(key).or_default().push(si);
747        }
748    }
749    for sharing in by_ridge.values() {
750        if let [a, b] = sharing[..] {
751            let mut union: Vec<usize> = boundary[a].iter().chain(&boundary[b]).copied().collect();
752            union.sort_unstable();
753            union.dedup();
754            if affine_rank(points, &union, tol) < k {
755                let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
756                parent[ra] = rb;
757            }
758        }
759    }
760    let mut facets: HashMap<usize, Vec<usize>> = HashMap::new();
761    for si in 0..m {
762        let r = find(&mut parent, si);
763        facets.entry(r).or_default().push(si);
764    }
765    let mut all: Vec<usize> = boundary.iter().flatten().copied().collect();
766    all.sort_unstable();
767    all.dedup();
768    let apex = *all.iter().min_by(|&&a, &&b| points[a].iter().zip(&points[b]).map(|(x, y)| x.total_cmp(y)).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b))).expect("a polytope has vertices");
769    let mut roots: Vec<usize> = facets.keys().copied().collect();
770    roots.sort_unstable();
771    let mut out = Vec::new();
772    for r in roots {
773        let simplices: Vec<&Vec<usize>> = facets[&r].iter().map(|&i| &boundary[i]).collect();
774        if simplices.iter().any(|s| s.contains(&apex)) {
775            continue;
776        }
777        // The facet's own triangulation: a single simplex stays, a merged facet is pulled from its boundary.
778        let triangulation: Vec<Vec<usize>> = if simplices.len() == 1 || k < 3 {
779            simplices.iter().map(|s| (*s).clone()).collect()
780        } else {
781            let mut count: HashMap<Vec<usize>, (usize, Vec<usize>)> = HashMap::new();
782            for s in &simplices {
783                for skip in 0..k {
784                    let face: Vec<usize> = s.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &v)| v).collect();
785                    let mut key = face.clone();
786                    key.sort_unstable();
787                    let e = count.entry(key).or_insert((0, face));
788                    e.0 += 1;
789                }
790            }
791            let mut rim: Vec<Vec<usize>> = count.into_values().filter(|(c, _)| *c == 1).map(|(_, f)| f).collect();
792            rim.sort_unstable();
793            pulling_triangulation(points, rim, tol)
794        };
795        out.extend(triangulation.into_iter().map(|mut t| {
796            t.push(apex);
797            t
798        }));
799    }
800    out
801}
802
803/// The triangulation with its ties resolved by a rule that depends only on the points: facets of the
804/// (joggled) lifted hull that lie in one hyperplane of the *unjoggled* lifted points (four or more
805/// cospherical points: a grid cell, a regular polytope) are merged into one cell, and the cell is
806/// triangulated by a fan from its lexicographically smallest vertex (Qhull's `Qt` fans from an apex
807/// too, but chooses it by internal numbering). The result does not depend on the order of the points or
808/// on the joggle, so a triangulation grown by `add_points` equals a fresh one on degenerate sets. A cell
809/// whose fan does not tile it (numerical trouble) keeps the joggled triangulation.
810fn canonical_ties(points: &[Vec<f64>], lo: &[f64], scale: f64, vertices: Vec<Vec<usize>>, neighbors: Vec<Vec<Option<usize>>>) -> (Vec<Vec<usize>>, Vec<Vec<Option<usize>>>) {
811    let d = lo.len();
812    let n = vertices.len();
813    if n == 0 {
814        return (vertices, neighbors);
815    }
816    // Distances are compared with this fraction of the extent of the points.
817    let tol = 1e-9 * scale;
818    let lift = |v: usize| -> Vec<f64> {
819        let mut q: Vec<f64> = points[v].iter().zip(lo).map(|(x, l)| (x - l) / scale).collect();
820        let r2: f64 = q.iter().map(|t| t * t).sum();
821        q.push(r2);
822        q
823    };
824    // The unjoggled hyperplane of every facet.
825    let planes: Vec<(Vec<f64>, f64)> = vertices
826        .iter()
827        .map(|vs| {
828            let p0 = lift(vs[0]);
829            let rows: Vec<Vec<f64>> = vs[1..].iter().map(|&v| sub(&lift(v), &p0)).collect();
830            let normal = normal_of(&rows, d + 1);
831            let offset = -dot(&normal, &p0);
832            (normal, offset)
833        })
834        .collect();
835    let volume = |vs: &[usize]| -> f64 { det((1..=d).map(|k| sub(&points[vs[k]], &points[vs[0]])).collect()).abs() / factorial(d) };
836    // A facet of the joggled hull can be flat in the plane of the points (its vertices dependent); its lifted
837    // hyperplane is then arbitrary, so it is joined to its neighbours by the plane of the other one.
838    let vols: Vec<f64> = vertices.iter().map(|vs| volume(vs)).collect();
839    let vmax = vols.iter().cloned().fold(0.0f64, f64::max);
840    let flat: Vec<bool> = vols.iter().map(|&v| v <= 1e-12 * vmax).collect();
841    // Union-find over neighbouring facets whose opposite vertices lie on the plane.
842    let mut parent: Vec<usize> = (0..n).collect();
843    fn find(parent: &mut [usize], mut i: usize) -> usize {
844        while parent[i] != i {
845            parent[i] = parent[parent[i]];
846            i = parent[i];
847        }
848        i
849    }
850    for f in 0..n {
851        for (i, g) in neighbors[f].iter().enumerate() {
852            let Some(g) = *g else { continue };
853            // The vertex of g that is not on the ridge shared with f (the ridge omits f's vertex i).
854            let opposite = vertices[g].iter().find(|v| !vertices[f].iter().enumerate().any(|(j, w)| j != i && w == *v)).copied();
855            let Some(o) = opposite else { continue };
856            let on_plane = if !flat[f] {
857                (dot(&planes[f].0, &lift(o)) + planes[f].1).abs() < 1e-9
858            } else if !flat[g] {
859                (dot(&planes[g].0, &lift(vertices[f][i])) + planes[g].1).abs() < 1e-9
860            } else {
861                // Two flat facets: they share a cell if the plane of either one's other neighbours is
862                // unknowable here; join them (a flat pair never separates two cells).
863                true
864            };
865            if on_plane {
866                let (a, b) = (find(&mut parent, f), find(&mut parent, g));
867                parent[a] = b;
868            }
869        }
870    }
871    let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
872    for f in 0..n {
873        let r = find(&mut parent, f);
874        groups.entry(r).or_default().push(f);
875    }
876    let mut out: Vec<Vec<usize>> = Vec::with_capacity(n);
877    let mut roots: Vec<usize> = groups.keys().copied().collect();
878    roots.sort_unstable();
879    for r in roots {
880        let members = &groups[&r];
881        if members.len() == 1 {
882            // A flat facet with no neighbour at all is an artefact of the joggle: it covers no volume and nothing
883            // can be reached through it.
884            if !(flat[members[0]] && neighbors[members[0]].iter().all(|g| g.is_none())) {
885                out.push(vertices[members[0]].clone());
886            }
887            continue;
888        }
889        let in_group: std::collections::HashSet<usize> = members.iter().copied().collect();
890        let mut cell: Vec<usize> = members.iter().flat_map(|&f| vertices[f].iter().copied()).collect();
891        cell.sort_unstable();
892        cell.dedup();
893        let apex = *cell.iter().min_by(|&&a, &&b| points[a].iter().zip(&points[b]).map(|(x, y)| x.total_cmp(y)).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal).then(a.cmp(&b))).expect("a cell has vertices");
894        // The cell's boundary: the ridges of its facets that no other facet of the cell shares.
895        let mut boundary: Vec<Vec<usize>> = Vec::new();
896        for &f in members {
897            for (i, g) in neighbors[f].iter().enumerate() {
898                if g.is_some_and(|g| in_group.contains(&g)) {
899                    continue;
900                }
901                boundary.push(vertices[f].iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect());
902            }
903        }
904        let _ = apex;
905        // The joggled triangulation of the cell's boundary can contain flat simplices (four corners of a
906        // square as a "tetrahedron"), which the pulling rule cannot place: a cell of cospherical points is
907        // the convex hull of its vertices, so take its boundary from the hull, which merges and
908        // triangulates the coplanar pieces itself.
909        if let Ok(hull) = ConvexHullNd::new(&cell.iter().map(|&v| points[v].clone()).collect::<Vec<_>>()) {
910            boundary = hull.simplices.iter().map(|s| s.iter().map(|&i| cell[i]).collect()).collect();
911        }
912        let fan = pulling_triangulation(points, boundary, tol);
913        let want: f64 = members.iter().map(|&f| volume(&vertices[f])).sum();
914        let got: f64 = fan.iter().map(|s| volume(s)).sum();
915        if (got - want).abs() <= 1e-9 * want.max(f64::MIN_POSITIVE) {
916            // The fan's flat simplices (ridges in a face through the apex) carry no volume: drop them.
917            out.extend(fan.into_iter().filter(|s| volume(s) > 1e-12 * want / members.len() as f64));
918        } else {
919            out.extend(members.iter().map(|&f| vertices[f].clone()));
920        }
921    }
922    // Neighbours from the shared ridges.
923    let mut ridges: HashMap<Vec<usize>, Vec<(usize, usize)>> = HashMap::new();
924    for (s, vs) in out.iter().enumerate() {
925        for i in 0..vs.len() {
926            let mut key: Vec<usize> = vs.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect();
927            key.sort_unstable();
928            ridges.entry(key).or_default().push((s, i));
929        }
930    }
931    let mut nb: Vec<Vec<Option<usize>>> = out.iter().map(|vs| vec![None; vs.len()]).collect();
932    for shared in ridges.values() {
933        if let [(a, i), (b, j)] = shared[..] {
934            nb[a][i] = Some(b);
935            nb[b][j] = Some(a);
936        }
937    }
938    (out, nb)
939}
940
941/// A point in the frame of the triangulation (the unit box of the construction), lifted to the
942/// paraboloid with the tiny joggle of the lifted coordinate.
943fn lift_point(p: &[f64], lo: &[f64], scale: f64, jog: &mut u64) -> Vec<f64> {
944    let mut q: Vec<f64> = p.iter().zip(lo).map(|(x, l)| (x - l) / scale).collect();
945    *jog ^= *jog << 13;
946    *jog ^= *jog >> 7;
947    *jog ^= *jog << 17;
948    let j = ((*jog >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * 1e-11;
949    let r2: f64 = q.iter().map(|v| v * v).sum();
950    q.push(r2 + j);
951    q
952}
953
954impl DelaunayNd {
955    pub fn new(points: &[Vec<f64>]) -> Result<DelaunayNd, ErrorsJSL> {
956        Self::build(points, false, &QhullOptions::default())
957    }
958
959    /// As [`DelaunayNd::new`] with Qhull-style options (see [`QhullOptions`]): `QJ` moves the
960    /// points by a larger amount than the built-in tiny joggle, and `E` sets the tolerance of the
961    /// lifted hull.
962    pub fn with_options(points: &[Vec<f64>], options: &QhullOptions) -> Result<DelaunayNd, ErrorsJSL> {
963        Self::build(points, false, options)
964    }
965
966    /// The furthest-site Delaunay triangulation (SciPy's `Delaunay(furthest_site=True)`): the
967    /// simplices whose circumscribed sphere contains *all* the points, from the upper facets of
968    /// the lifted hull. It triangulates the convex hull of the points, using only the points that
969    /// are vertices of the hull; the others appear in no simplex.
970    pub fn new_furthest_site(points: &[Vec<f64>]) -> Result<DelaunayNd, ErrorsJSL> {
971        Self::build(points, true, &QhullOptions::default())
972    }
973
974    /// The furthest-site triangulation with Qhull-style options.
975    pub fn new_furthest_site_with_options(points: &[Vec<f64>], options: &QhullOptions) -> Result<DelaunayNd, ErrorsJSL> {
976        Self::build(points, true, options)
977    }
978
979    /// Adds points (SciPy's `add_points`): the new points get the next indices. They are lifted in
980    /// the frame (the box and the joggle sequence) fixed when the triangulation was made and added to
981    /// the lifted hull as Quickhull does, so the old points are not touched: only the facets that a
982    /// new point sees are replaced. In general position the result is the triangulation of a fresh
983    /// computation; for cospherical sets it is one of the valid ones, which may differ from a fresh
984    /// computation's, since the joggle depends on the order in which the points arrive.
985    pub fn add_points(&mut self, new: &[Vec<f64>]) -> Result<(), ErrorsJSL> {
986        let d = self.state.lo.len();
987        if new.iter().any(|p| p.len() != d || p.iter().any(|v| !v.is_finite())) {
988            return Err(ErrorsJSL::InvalidInputRange("points must be finite and of the triangulation's dimension"));
989        }
990        if new.is_empty() {
991            return Ok(());
992        }
993        let first = self.points.len();
994        let mut points = std::mem::take(&mut self.points);
995        points.extend_from_slice(new);
996        let mut state = std::mem::replace(&mut self.state, DelState { lifted: Vec::new(), top: 0, hull: Hull { facets: Vec::new(), interior: Vec::new() }, lo: Vec::new(), scale: 1.0, jog: 0, eps: 0.0, options: QhullOptions::default() });
997        let moved: Vec<Vec<f64>> = if state.options.joggle.is_some() { state.options.joggled(&points)[first..].to_vec() } else { new.to_vec() };
998        let first_new = state.lifted.len();
999        for p in &moved {
1000            let q = lift_point(p, &state.lo, state.scale, &mut state.jog);
1001            state.lifted.push(q);
1002        }
1003        for h in first_new..state.lifted.len() {
1004            let best = state
1005                .hull
1006                .facets
1007                .iter()
1008                .enumerate()
1009                .filter(|(_, f)| f.alive)
1010                .map(|(i, f)| (i, dot(&f.normal, &state.lifted[h]) + f.offset))
1011                .filter(|(_, dist)| *dist > state.eps)
1012                .max_by(|a, b| a.1.total_cmp(&b.1));
1013            if let Some((f, _)) = best {
1014                state.hull.facets[f].outside.push(h);
1015            }
1016        }
1017        expand(&state.lifted, &mut state.hull, state.eps);
1018        *self = Self::from_state(points, self.furthest_site, state);
1019        Ok(())
1020    }
1021
1022    fn build(points: &[Vec<f64>], furthest_site: bool, options: &QhullOptions) -> Result<DelaunayNd, ErrorsJSL> {
1023        let d = points.first().map_or(0, |p| p.len());
1024        if d < 1 || points.iter().any(|p| p.len() != d || p.iter().any(|v| !v.is_finite())) {
1025            return Err(ErrorsJSL::InvalidInputRange("points must be finite and of one dimension"));
1026        }
1027        // Scale to a unit box (Qhull's Qbb) and lift, with a tiny deterministic joggle (and the
1028        // larger one that `QJ` asks for).
1029        let moved = options.joggled(points);
1030        let lo: Vec<f64> = (0..d).map(|k| moved.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min)).collect();
1031        let hi: Vec<f64> = (0..d).map(|k| moved.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max)).collect();
1032        let scale = (0..d).map(|k| hi[k] - lo[k]).fold(0.0f64, f64::max).max(f64::MIN_POSITIVE);
1033        let mut jog = 0x9E3779B97F4A7C15u64;
1034        let mut lifted: Vec<Vec<f64>> = moved.iter().map(|p| lift_point(p, &lo, scale, &mut jog)).collect();
1035        // A point far above the paraboloid closes the hull (Qhull's Qz) and keeps upper facets
1036        // separate from lower ones; for the furthest-site triangulation it is a point far below,
1037        // and the upper facets are the ones kept.
1038        let top = lifted.len();
1039        let mut far: Vec<f64> = vec![0.5; d];
1040        far.push(if furthest_site { -1e3 * (d as f64 + 1.0) } else { 1e3 * (d as f64 + 1.0) });
1041        lifted.push(far);
1042        let eps = options.tolerance.unwrap_or(1e2 * (d as f64 + 1.0) * f64::EPSILON * 4.0);
1043        let hull = quickhull(&lifted, eps)?;
1044        Ok(Self::from_state(points.to_vec(), furthest_site, DelState { lifted, top, hull, lo, scale, jog, eps, options: options.clone() }))
1045    }
1046
1047    /// The triangulation from the lifted hull: its lower (or, furthest-site, upper) facets that do not
1048    /// touch the point at infinity, with the hull's point indices translated to the input's.
1049    fn from_state(points: Vec<Vec<f64>>, furthest_site: bool, state: DelState) -> DelaunayNd {
1050        let d = state.lo.len();
1051        let top = state.top;
1052        let hull = &state.hull;
1053        let wanted = |nz: f64| if furthest_site { nz > 1e-6 } else { nz < -1e-6 };
1054        let alive: Vec<usize> = (0..hull.facets.len()).filter(|&i| hull.facets[i].alive && wanted(hull.facets[i].normal[d]) && !hull.facets[i].vertices.contains(&top)).collect();
1055        let index: HashMap<usize, usize> = alive.iter().enumerate().map(|(k, &i)| (i, k)).collect();
1056        // Hull indices above the point at infinity are the added points, one place later than the input's.
1057        let input = |h: usize| if h > top { h - 1 } else { h };
1058        let facet_vertices: Vec<Vec<usize>> = alive.iter().map(|&i| hull.facets[i].vertices.iter().map(|&h| input(h)).collect()).collect();
1059        let facet_neighbors: Vec<Vec<Option<usize>>> = alive.iter().map(|&i| hull.facets[i].neighbors.iter().map(|g| index.get(g).copied()).collect()).collect();
1060        let (simplices, neighbors) = canonical_ties(&points, &state.lo, state.scale, facet_vertices, facet_neighbors);
1061        let transform = simplices
1062            .iter()
1063            .map(|s| {
1064                let r = &points[s[d]];
1065                let t: Vec<Vec<f64>> = (0..d).map(|row| (0..d).map(|col| points[s[col]][row] - r[row]).collect()).collect();
1066                let mut out = invert(&t).unwrap_or_else(|| vec![vec![f64::NAN; d]; d]);
1067                out.push(r.clone());
1068                out
1069            })
1070            .collect();
1071        DelaunayNd { points, simplices, neighbors, transform, furthest_site, state }
1072    }
1073
1074    /// The barycentric coordinates of `x` in simplex `s` (`d + 1` values summing to 1).
1075    pub fn barycentric(&self, s: usize, x: &[f64]) -> Vec<f64> {
1076        let t = &self.transform[s];
1077        let d = x.len();
1078        let dx = sub(x, &t[d]);
1079        let mut c: Vec<f64> = (0..d).map(|i| dot(&t[i], &dx)).collect();
1080        let last = 1.0 - c.iter().sum::<f64>();
1081        c.push(last);
1082        c
1083    }
1084
1085    /// The simplex containing `x`, or `None` outside the triangulation (SciPy's `find_simplex`),
1086    /// by a walk from simplex 0 towards `x`, falling back to a full search.
1087    pub fn find_simplex(&self, x: &[f64]) -> Option<usize> {
1088        let tol = 1e2 * f64::EPSILON;
1089        if self.simplices.is_empty() {
1090            return None;
1091        }
1092        let mut s = 0;
1093        for _ in 0..4 * self.simplices.len() + 10 {
1094            let c = self.barycentric(s, x);
1095            let (i, m) = c.iter().enumerate().min_by(|a, b| a.1.total_cmp(b.1)).map(|(i, m)| (i, *m)).unwrap();
1096            if m >= -tol {
1097                return Some(s);
1098            }
1099            match self.neighbors[s][i] {
1100                Some(t) => s = t,
1101                None => break,
1102            }
1103        }
1104        (0..self.simplices.len()).find(|&s| self.barycentric(s, x).iter().all(|&c| c >= -tol))
1105    }
1106}
1107// ANCHOR_END: delaunay_nd
1108
1109/// The circumcentre of a simplex with `d + 1` vertices in `ℝ^d`.
1110fn circumcenter(pts: &[&Vec<f64>]) -> Option<Vec<f64>> {
1111    let d = pts[0].len();
1112    let p0 = pts[0];
1113    let a: Vec<Vec<f64>> = pts[1..].iter().map(|p| sub(p, p0).iter().map(|v| 2.0 * v).collect()).collect();
1114    let b: Vec<f64> = pts[1..].iter().map(|p| dot(p, p) - dot(p0, p0)).collect();
1115    let inv = invert(&a)?;
1116    Some((0..d).map(|i| dot(&inv[i], &b)).collect())
1117}
1118
1119// ANCHOR: voronoi_nd
1120/// The Voronoi diagram of points in any dimension (SciPy's `Voronoi`), as the dual of the
1121/// Delaunay triangulation: one Voronoi vertex per Delaunay simplex (its circumcentre), one
1122/// region per input point, and one ridge per Delaunay edge (pair of neighbouring points).
1123#[derive(Clone, Debug)]
1124#[non_exhaustive]
1125pub struct VoronoiNd {
1126    pub points: Vec<Vec<f64>>,
1127    pub vertices: Vec<Vec<f64>>,
1128    /// The pairs of input points that each ridge separates.
1129    pub ridge_points: Vec<[usize; 2]>,
1130    /// The Voronoi vertices of each ridge, with `None` for a vertex at infinity (SciPy's −1).
1131    pub ridge_vertices: Vec<Vec<Option<usize>>>,
1132    /// For each input point, the vertices of its region (unordered), with `None` if unbounded.
1133    pub regions: Vec<Vec<Option<usize>>>,
1134    /// Whether this is the furthest-site diagram.
1135    pub furthest_site: bool,
1136}
1137
1138impl VoronoiNd {
1139    pub fn new(points: &[Vec<f64>]) -> Result<VoronoiNd, ErrorsJSL> {
1140        Self::build(points, false, &QhullOptions::default())
1141    }
1142
1143    /// The furthest-site Voronoi diagram (SciPy's `Voronoi(furthest_site=True)`): the dual of the
1144    /// furthest-site Delaunay triangulation, whose cells are the points of the plane (or space) for
1145    /// which a given input point is the *farthest*. Only the vertices of the convex hull have a
1146    /// region, and every region is unbounded; the other points get empty regions.
1147    pub fn new_furthest_site(points: &[Vec<f64>]) -> Result<VoronoiNd, ErrorsJSL> {
1148        Self::build(points, true, &QhullOptions::default())
1149    }
1150
1151    /// As [`VoronoiNd::new`] or [`VoronoiNd::new_furthest_site`] with Qhull-style options.
1152    pub fn with_options(points: &[Vec<f64>], furthest_site: bool, options: &QhullOptions) -> Result<VoronoiNd, ErrorsJSL> {
1153        Self::build(points, furthest_site, options)
1154    }
1155
1156    fn build(points: &[Vec<f64>], furthest_site: bool, options: &QhullOptions) -> Result<VoronoiNd, ErrorsJSL> {
1157        let tri = if furthest_site { DelaunayNd::new_furthest_site_with_options(points, options)? } else { DelaunayNd::with_options(points, options)? };
1158        let vertices: Vec<Vec<f64>> = tri.simplices.iter().map(|s| circumcenter(&s.iter().map(|&i| &points[i]).collect::<Vec<_>>()).unwrap_or_else(|| vec![f64::NAN; points[0].len()])).collect();
1159        // Ridges: point pairs sharing a Delaunay edge, with the simplices around that edge.
1160        let mut ridges: HashMap<[usize; 2], Vec<usize>> = HashMap::new();
1161        let mut on_hull: HashMap<[usize; 2], bool> = HashMap::new();
1162        for (si, s) in tri.simplices.iter().enumerate() {
1163            for a in 0..s.len() {
1164                for b in a + 1..s.len() {
1165                    let key = [s[a].min(s[b]), s[a].max(s[b])];
1166                    ridges.entry(key).or_default().push(si);
1167                    // The edge is on the hull if some facet opposite another vertex is.
1168                    let hull_edge = (0..s.len()).any(|k| k != a && k != b && tri.neighbors[si][k].is_none());
1169                    *on_hull.entry(key).or_insert(false) |= hull_edge;
1170                }
1171            }
1172        }
1173        let mut keys: Vec<[usize; 2]> = ridges.keys().copied().collect();
1174        keys.sort_unstable();
1175        let mut ridge_points = Vec::new();
1176        let mut ridge_vertices = Vec::new();
1177        let mut regions: Vec<Vec<Option<usize>>> = vec![Vec::new(); points.len()];
1178        for key in keys {
1179            // In 3-D and above an edge in a single simplex gives a degenerate ridge with one
1180            // finite vertex, which Qhull (and so SciPy) leaves out.
1181            if points[0].len() >= 3 && ridges[&key].len() < 2 {
1182                continue;
1183            }
1184            let mut vs: Vec<Option<usize>> = ridges[&key].iter().map(|&s| Some(s)).collect();
1185            if on_hull[&key] {
1186                vs.insert(0, None);
1187            }
1188            for &p in &key {
1189                for v in &vs {
1190                    if !regions[p].contains(v) {
1191                        regions[p].push(*v);
1192                    }
1193                }
1194            }
1195            ridge_points.push(key);
1196            ridge_vertices.push(vs);
1197        }
1198        Ok(VoronoiNd { points: points.to_vec(), vertices, ridge_points, ridge_vertices, regions, furthest_site })
1199    }
1200}
1201// ANCHOR_END: voronoi_nd
1202
1203// ANCHOR: halfspace
1204/// The intersection of half-spaces `A x + b ≤ 0` (SciPy's `HalfspaceIntersection`), given a
1205/// point strictly inside all of them: each half-space maps to the dual point
1206/// `aᵢ / −(aᵢ·c + bᵢ)` (relative to the interior point `c`), each facet of the dual points'
1207/// convex hull to a vertex of the intersection.
1208#[derive(Clone, Debug)]
1209#[non_exhaustive]
1210pub struct HalfspaceIntersection {
1211    /// The vertices of the intersection, one per dual facet (SciPy's `intersections`).
1212    pub intersections: Vec<Vec<f64>>,
1213    /// For each vertex, the half-spaces whose boundaries meet there (SciPy's `dual_facets`).
1214    pub dual_facets: Vec<Vec<usize>>,
1215    /// The dual points' hull vertices: the half-spaces that are not redundant.
1216    pub dual_vertices: Vec<usize>,
1217}
1218
1219impl HalfspaceIntersection {
1220    /// `halfspaces` rows are `[a, b]` (length `d + 1`).
1221    pub fn new(halfspaces: &[Vec<f64>], interior_point: &[f64]) -> Result<HalfspaceIntersection, ErrorsJSL> {
1222        let d = interior_point.len();
1223        if halfspaces.iter().any(|h| h.len() != d + 1) {
1224            return Err(ErrorsJSL::InvalidInputRange("each half-space is [a, b] with a of the point's dimension"));
1225        }
1226        let duals: Vec<Vec<f64>> = halfspaces
1227            .iter()
1228            .map(|h| {
1229                let s = -(dot(&h[..d], interior_point) + h[d]);
1230                h[..d].iter().map(|a| a / s).collect()
1231            })
1232            .collect();
1233        if halfspaces.iter().any(|h| dot(&h[..d], interior_point) + h[d] >= 0.0) {
1234            return Err(ErrorsJSL::InvalidInputRange("the interior point must lie strictly inside every half-space"));
1235        }
1236        let hull = ConvexHullNd::new(&duals)?;
1237        let intersections = hull.equations.iter().map(|e| (0..d).map(|k| -e[k] / e[d] + interior_point[k]).collect()).collect();
1238        Ok(HalfspaceIntersection { intersections, dual_facets: hull.simplices.clone(), dual_vertices: hull.vertices })
1239    }
1240}
1241// ANCHOR_END: halfspace
1242
1243// ANCHOR: spherical_voronoi
1244/// The Voronoi diagram of points on a sphere in `ℝ³` (SciPy's `SphericalVoronoi`): the convex
1245/// hull of the points is their Delaunay triangulation on the sphere, and each triangle's
1246/// circumcentre projected onto the sphere (its outward normal times the radius) is a Voronoi
1247/// vertex. Regions are sorted counter-clockwise seen from outside.
1248#[derive(Clone, Debug)]
1249#[non_exhaustive]
1250pub struct SphericalVoronoi {
1251    pub vertices: Vec<[f64; 3]>,
1252    pub regions: Vec<Vec<usize>>,
1253    pub radius: f64,
1254    pub center: [f64; 3],
1255}
1256
1257impl SphericalVoronoi {
1258    pub fn new(points: &[[f64; 3]], radius: f64, center: [f64; 3]) -> Result<SphericalVoronoi, ErrorsJSL> {
1259        if points.len() < 4 || radius.is_nan() || radius <= 0.0 {
1260            return Err(ErrorsJSL::InvalidInputRange("need at least 4 points and a positive radius"));
1261        }
1262        let rel: Vec<Vec<f64>> = points.iter().map(|p| (0..3).map(|k| p[k] - center[k]).collect()).collect();
1263        if rel.iter().any(|p| ((dot(p, p)).sqrt() - radius).abs() > 1e-8 * radius.max(1.0)) {
1264            return Err(ErrorsJSL::InvalidInputRange("the points must lie on the sphere"));
1265        }
1266        let hull = ConvexHullNd::new(&rel)?;
1267        if hull.vertices.len() != points.len() {
1268            return Err(ErrorsJSL::InvalidInputRange("duplicate points"));
1269        }
1270        let vertices: Vec<[f64; 3]> = hull.equations.iter().map(|e| [e[0] * radius + center[0], e[1] * radius + center[1], e[2] * radius + center[2]]).collect();
1271        let mut regions: Vec<Vec<usize>> = vec![Vec::new(); points.len()];
1272        for (f, s) in hull.simplices.iter().enumerate() {
1273            for &p in s {
1274                regions[p].push(f);
1275            }
1276        }
1277        // Sort each region's vertices by angle around the generator.
1278        for (p, reg) in regions.iter_mut().enumerate() {
1279            let n: Vec<f64> = rel[p].iter().map(|v| v / radius).collect();
1280            let helper = if n[0].abs() < 0.9 { [1.0, 0.0, 0.0] } else { [0.0, 1.0, 0.0] };
1281            let u = {
1282                let c = dot(&helper, &n);
1283                let u: Vec<f64> = (0..3).map(|k| helper[k] - c * n[k]).collect();
1284                let un = dot(&u, &u).sqrt();
1285                u.iter().map(|x| x / un).collect::<Vec<_>>()
1286            };
1287            let w = [n[1] * u[2] - n[2] * u[1], n[2] * u[0] - n[0] * u[2], n[0] * u[1] - n[1] * u[0]];
1288            reg.sort_by(|&a, &b| {
1289                let ang = |v: usize| {
1290                    let q: Vec<f64> = (0..3).map(|k| vertices[v][k] - center[k]).collect();
1291                    dot(&q, &w).atan2(dot(&q, &u))
1292                };
1293                ang(a).total_cmp(&ang(b))
1294            });
1295        }
1296        Ok(SphericalVoronoi { vertices, regions, radius, center })
1297    }
1298
1299    /// The area of each region on the sphere (SciPy's `calculate_areas`), from the spherical
1300    /// excess of the triangles fanned from the generator.
1301    pub fn calculate_areas(&self, points: &[[f64; 3]]) -> Vec<f64> {
1302        let r = self.radius;
1303        self.regions
1304            .iter()
1305            .zip(points)
1306            .map(|(reg, p)| {
1307                let unit = |q: &[f64; 3]| {
1308                    let v: Vec<f64> = (0..3).map(|k| q[k] - self.center[k]).collect();
1309                    let n = dot(&v, &v).sqrt();
1310                    v.iter().map(|x| x / n).collect::<Vec<f64>>()
1311                };
1312                let g = unit(p);
1313                let k = reg.len();
1314                (0..k)
1315                    .map(|i| {
1316                        let a = unit(&self.vertices[reg[i]]);
1317                        let b = unit(&self.vertices[reg[(i + 1) % k]]);
1318                        // Van Oosterom and Strackee: tan(E/2) = |g·(a×b)| / (1 + g·a + a·b + b·g).
1319                        let cross = [a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0]];
1320                        let num = dot(&g, &cross).abs();
1321                        let den = 1.0 + dot(&g, &a) + dot(&a, &b) + dot(&b, &g);
1322                        2.0 * num.atan2(den)
1323                    })
1324                    .sum::<f64>()
1325                    * r
1326                    * r
1327            })
1328            .collect()
1329    }
1330}
1331// ANCHOR_END: spherical_voronoi
1332
1333#[cfg(test)]
1334mod tests {
1335    use super::*;
1336
1337    fn lcg(n: usize, d: usize, seed: u64) -> Vec<Vec<f64>> {
1338        let mut s = seed;
1339        (0..n)
1340            .map(|_| {
1341                (0..d)
1342                    .map(|_| {
1343                        s = s.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1344                        (s >> 11) as f64 / (1u64 << 53) as f64
1345                    })
1346                    .collect()
1347            })
1348            .collect()
1349    }
1350
1351    #[test]
1352    fn hull_of_a_cube_and_random_points() {
1353        // The unit cube with interior points: 8 vertices, 12 triangles, volume 1, area 6.
1354        let mut pts: Vec<Vec<f64>> = (0..8).map(|i| vec![(i & 1) as f64, (i >> 1 & 1) as f64, (i >> 2 & 1) as f64]).collect();
1355        pts.extend(lcg(50, 3, 1).into_iter().map(|p| p.iter().map(|v| 0.1 + 0.8 * v).collect()));
1356        let h = ConvexHullNd::new(&pts).unwrap();
1357        assert_eq!(h.vertices, (0..8).collect::<Vec<_>>());
1358        assert!((h.volume - 1.0).abs() < 1e-12 && (h.area - 6.0).abs() < 1e-12, "{} {}", h.volume, h.area);
1359        // 4-D: every random point is inside or on the hull, and Euler's relation for the
1360        // simplicial boundary (each ridge in two facets).
1361        let pts = lcg(60, 4, 2);
1362        let h = ConvexHullNd::new(&pts).unwrap();
1363        assert!(pts.iter().all(|p| h.equations.iter().all(|e| dot(&e[..4], p) + e[4] <= 1e-10)));
1364        assert!(h.neighbors.iter().enumerate().all(|(f, ns)| ns.iter().all(|&g| h.neighbors[g].contains(&f))));
1365    }
1366
1367    #[test]
1368    fn delaunay_is_empty_sphere_and_covers_the_hull() {
1369        for d in [2usize, 3] {
1370            let pts = lcg(40, d, 3 + d as u64);
1371            let t = DelaunayNd::new(&pts).unwrap();
1372            // Empty circumspheres.
1373            for s in &t.simplices {
1374                let c = circumcenter(&s.iter().map(|&i| &pts[i]).collect::<Vec<_>>()).unwrap();
1375                let r2 = dot(&sub(&pts[s[0]], &c), &sub(&pts[s[0]], &c));
1376                assert!(pts.iter().all(|p| dot(&sub(p, &c), &sub(p, &c)) >= r2 * (1.0 - 1e-9)));
1377            }
1378            // Volumes add up to the hull's.
1379            let vol: f64 = t.simplices.iter().map(|s| det((1..=d).map(|k| sub(&pts[s[k]], &pts[s[0]])).collect()).abs() / factorial(d)).sum();
1380            assert!((vol - ConvexHullNd::new(&pts).unwrap().volume).abs() < 1e-12, "{d}");
1381            let x: Vec<f64> = vec![0.5; d];
1382            let s = t.find_simplex(&x).unwrap();
1383            assert!(t.barycentric(s, &x).iter().all(|c| *c >= -1e-12));
1384        }
1385        // A grid (cospherical quadruples) still triangulates.
1386        let grid: Vec<Vec<f64>> = (0..16).map(|i| vec![(i % 4) as f64, (i / 4) as f64]).collect();
1387        let t = DelaunayNd::new(&grid).unwrap();
1388        assert_eq!(t.simplices.len(), 18);
1389    }
1390
1391    #[test]
1392    fn furthest_site_spheres_contain_every_point_and_cover_the_hull() {
1393        for d in [2usize, 3] {
1394            let pts = lcg(30, d, 11 + d as u64);
1395            let t = DelaunayNd::new_furthest_site(&pts).unwrap();
1396            assert!(t.furthest_site && !t.simplices.is_empty());
1397            let hull = ConvexHullNd::new(&pts).unwrap();
1398            for s in &t.simplices {
1399                // Only hull vertices take part, and every point lies inside the circumsphere.
1400                assert!(s.iter().all(|v| hull.vertices.contains(v)));
1401                let c = circumcenter(&s.iter().map(|&i| &pts[i]).collect::<Vec<_>>()).unwrap();
1402                let r2 = dot(&sub(&pts[s[0]], &c), &sub(&pts[s[0]], &c));
1403                assert!(pts.iter().all(|p| dot(&sub(p, &c), &sub(p, &c)) <= r2 * (1.0 + 1e-9)), "d = {d}");
1404            }
1405            // The simplices tile the convex hull of the points.
1406            let vol: f64 = t.simplices.iter().map(|s| det((1..=d).map(|k| sub(&pts[s[k]], &pts[s[0]])).collect()).abs() / factorial(d)).sum();
1407            assert!((vol - hull.volume).abs() < 1e-10, "{d}: {vol} against {}", hull.volume);
1408        }
1409    }
1410
1411    #[test]
1412    fn add_points_equals_a_fresh_computation() {
1413        let pts = lcg(30, 3, 5);
1414        let more = lcg(10, 3, 6);
1415        let mut h = ConvexHullNd::new(&pts).unwrap();
1416        h.add_points(&more).unwrap();
1417        let all: Vec<Vec<f64>> = pts.iter().chain(&more).cloned().collect();
1418        let fresh = ConvexHullNd::new(&all).unwrap();
1419        assert_eq!((h.vertices.clone(), h.simplices.len()), (fresh.vertices.clone(), fresh.simplices.len()));
1420        assert!((h.volume - fresh.volume).abs() < 1e-14);
1421        let mut t = DelaunayNd::new_furthest_site(&pts).unwrap();
1422        t.add_points(&more).unwrap();
1423        assert!(t.furthest_site && t.points.len() == 40);
1424        assert_eq!(t.simplices.len(), DelaunayNd::new_furthest_site(&all).unwrap().simplices.len());
1425    }
1426
1427    #[test]
1428    fn halfspaces_of_a_square_and_a_spherical_voronoi() {
1429        // |x| ≤ 1, |y| ≤ 1 plus a redundant x + y ≤ 5.
1430        let hs = vec![vec![1.0, 0.0, -1.0], vec![-1.0, 0.0, -1.0], vec![0.0, 1.0, -1.0], vec![0.0, -1.0, -1.0], vec![1.0, 1.0, -5.0]];
1431        let h = HalfspaceIntersection::new(&hs, &[0.1, -0.2]).unwrap();
1432        let mut v: Vec<(i64, i64)> = h.intersections.iter().map(|p| ((p[0] * 1e9).round() as i64, (p[1] * 1e9).round() as i64)).collect();
1433        v.sort_unstable();
1434        assert_eq!(v, vec![(-1_000_000_000, -1_000_000_000), (-1_000_000_000, 1_000_000_000), (1_000_000_000, -1_000_000_000), (1_000_000_000, 1_000_000_000)]);
1435        assert_eq!(h.dual_vertices, vec![0, 1, 2, 3]);
1436        // The octahedron's vertices on the unit sphere: the Voronoi regions are the 8 octants'
1437        // cube corners, each region of area 4π/6.
1438        let pts = [[1.0, 0.0, 0.0], [-1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, -1.0, 0.0], [0.0, 0.0, 1.0], [0.0, 0.0, -1.0]];
1439        let sv = SphericalVoronoi::new(&pts, 1.0, [0.0; 3]).unwrap();
1440        assert_eq!(sv.vertices.len(), 8);
1441        let s3 = 1.0 / 3f64.sqrt();
1442        assert!(sv.vertices.iter().all(|v| v.iter().all(|c| (c.abs() - s3).abs() < 1e-12)));
1443        assert!(sv.calculate_areas(&pts).iter().all(|a| (a - 4.0 * std::f64::consts::PI / 6.0).abs() < 1e-12));
1444    }
1445
1446    #[test]
1447    fn furthest_site_voronoi_matches_scipy() {
1448        // SciPy 1.17: Voronoi(default_rng(3).random((9, 2)), furthest_site=True).
1449        let pts: Vec<Vec<f64>> = [
1450            [0.08564916714362436, 0.2368105065960997],
1451            [0.8012744652063969, 0.5821620360643678],
1452            [0.09412864224039919, 0.4331269402364738],
1453            [0.479051298140834, 0.15973891463707857],
1454            [0.7345771514092145, 0.11367201992140341],
1455            [0.39122819049566204, 0.5167401826213637],
1456            [0.4306280204141778, 0.5867985714381407],
1457            [0.7378377872921602, 0.9562672548360985],
1458            [0.28420116374879145, 0.648547207079825],
1459        ]
1460        .iter()
1461        .map(|p| p.to_vec())
1462        .collect();
1463        let v = VoronoiNd::new_furthest_site(&pts).unwrap();
1464        assert!(v.furthest_site);
1465        let mut verts: Vec<(i64, i64)> = v.vertices.iter().map(|p| ((p[0] * 1e8).round() as i64, (p[1] * 1e8).round() as i64)).collect();
1466        verts.sort_unstable();
1467        let want: [(f64, f64); 5] = [(-0.5817794072, 0.5400699217), (0.4785632495, 0.535966657), (0.7308321403, 0.3072845296), (1.4327916019, -0.5564564445), (4.489001782, 21.6705920953)];
1468        let mut want: Vec<(i64, i64)> = want.iter().map(|p| ((p.0 * 1e8).round() as i64, (p.1 * 1e8).round() as i64)).collect();
1469        want.sort_unstable();
1470        assert_eq!(verts.len(), 5);
1471        for (a, b) in verts.iter().zip(&want) {
1472            assert!((a.0 - b.0).abs() < 200 && (a.1 - b.1).abs() < 2000, "{a:?} {b:?}");
1473        }
1474        let mut rp: Vec<[usize; 2]> = v.ridge_points.clone();
1475        rp.sort_unstable();
1476        assert_eq!(rp, vec![[0, 2], [0, 3], [0, 4], [0, 7], [1, 4], [1, 7], [2, 7], [2, 8], [3, 4], [4, 7], [7, 8]]);
1477        // Only the hull vertices have regions, and all of them are unbounded.
1478        let with_region: Vec<usize> = (0..pts.len()).filter(|&i| !v.regions[i].is_empty()).collect();
1479        assert_eq!(with_region, vec![0, 1, 2, 3, 4, 7, 8]);
1480        assert!(with_region.iter().all(|&i| v.regions[i].contains(&None)));
1481    }
1482
1483    #[test]
1484    fn adding_points_grows_the_hull_in_place() {
1485        for d in [2usize, 3, 4] {
1486            let all = lcg(60, d, 21 + d as u64);
1487            let mut h = ConvexHullNd::new(&all[..20]).unwrap();
1488            // One batch, then single points; each state equals a fresh hull of the same points.
1489            h.add_points(&all[20..35]).unwrap();
1490            let fresh = ConvexHullNd::new(&all[..35]).unwrap();
1491            assert_eq!(h.vertices, fresh.vertices, "d = {d}");
1492            assert!((h.volume - fresh.volume).abs() < 1e-12 * (1.0 + fresh.volume) && (h.area - fresh.area).abs() < 1e-12 * (1.0 + fresh.area));
1493            for k in 35..60 {
1494                h.add_points(&all[k..k + 1]).unwrap();
1495            }
1496            let fresh = ConvexHullNd::new(&all).unwrap();
1497            assert_eq!(h.vertices, fresh.vertices);
1498            assert_eq!(h.simplices.len(), fresh.simplices.len());
1499            assert!((h.volume - fresh.volume).abs() < 1e-12 * (1.0 + fresh.volume));
1500            // Interior points change nothing.
1501            let centre: Vec<f64> = (0..d).map(|k| all.iter().map(|p| p[k]).sum::<f64>() / all.len() as f64).collect();
1502            let before = h.simplices.len();
1503            h.add_points(&[centre]).unwrap();
1504            assert_eq!(h.simplices.len(), before);
1505            assert_eq!(h.points.len(), 61);
1506        }
1507    }
1508
1509    #[test]
1510    fn qhull_options_are_parsed_and_joggle_makes_flat_input_valid() {
1511        let o = QhullOptions::parse("Qt Qbb Qc QJ1e-9 E1e-12").unwrap();
1512        assert_eq!((o.joggle, o.tolerance), (Some(1e-9), Some(1e-12)));
1513        assert_eq!(QhullOptions::parse("QJ").unwrap().joggle, Some(3e-12));
1514        assert_eq!(QhullOptions::parse("").unwrap(), QhullOptions::default());
1515        assert!(QhullOptions::parse("Qs").is_err() && QhullOptions::parse("QJx").is_err());
1516        // Points on a line: no hull without a joggle, a sliver with one (as in Qhull).
1517        let line: Vec<Vec<f64>> = (0..6).map(|i| vec![i as f64, 2.0 * i as f64]).collect();
1518        assert!(ConvexHullNd::new(&line).is_err());
1519        let h = ConvexHullNd::with_options(&line, &QhullOptions::parse("QJ1e-6").unwrap()).unwrap();
1520        assert!(h.volume > 0.0 && h.volume < 1e-3, "{}", h.volume);
1521        assert_eq!(h.points, line);
1522        // A grid is cospherical: a joggled Delaunay is a valid triangulation of the square.
1523        let grid: Vec<Vec<f64>> = (0..4).flat_map(|i| (0..4).map(move |j| vec![i as f64, j as f64])).collect();
1524        let t = DelaunayNd::with_options(&grid, &QhullOptions::parse("QJ1e-8").unwrap()).unwrap();
1525        let area: f64 = t.simplices.iter().map(|s| det((1..=2).map(|k| sub(&grid[s[k]], &grid[s[0]])).collect()).abs() / 2.0).sum();
1526        assert!((area - 9.0).abs() < 1e-6, "{area}");
1527    }
1528
1529    fn simplex_set(t: &DelaunayNd) -> Vec<Vec<usize>> {
1530        let mut v: Vec<Vec<usize>> = t.simplices.iter().map(|s| { let mut s = s.clone(); s.sort_unstable(); s }).collect();
1531        v.sort_unstable();
1532        v
1533    }
1534
1535    #[test]
1536    fn delaunay_add_points_is_incremental_and_equals_a_fresh_triangulation() {
1537        for d in [2usize, 3, 4] {
1538            let all = lcg(50, d, 31 + d as u64);
1539            let mut t = DelaunayNd::new(&all[..18]).unwrap();
1540            t.add_points(&all[18..30]).unwrap();
1541            // Points in general position: the same simplices as a fresh triangulation of those points.
1542            assert_eq!(simplex_set(&t), simplex_set(&DelaunayNd::new(&all[..30]).unwrap()), "d = {d}");
1543            for k in 30..50 {
1544                t.add_points(&all[k..k + 1]).unwrap();
1545            }
1546            let fresh = DelaunayNd::new(&all).unwrap();
1547            assert_eq!(simplex_set(&t), simplex_set(&fresh), "d = {d}");
1548            assert_eq!(t.points.len(), 50);
1549            // The empty-sphere property and the neighbour structure hold for every simplex.
1550            for s in &t.simplices {
1551                let c = circumcenter(&s.iter().map(|&i| &all[i]).collect::<Vec<_>>()).unwrap();
1552                let r2 = dot(&sub(&all[s[0]], &c), &sub(&all[s[0]], &c));
1553                assert!(all.iter().all(|p| dot(&sub(p, &c), &sub(p, &c)) >= r2 * (1.0 - 1e-9)));
1554            }
1555            assert_eq!(t.neighbors.len(), t.simplices.len());
1556            // find_simplex works on the grown triangulation.
1557            let centre: Vec<f64> = (0..d).map(|k| all.iter().map(|p| p[k]).sum::<f64>() / 50.0).collect();
1558            assert!(t.find_simplex(&centre).is_some());
1559        }
1560        // A grid in two halves: a valid triangulation of the whole square (it may differ from a fresh one).
1561        let grid: Vec<Vec<f64>> = (0..5).flat_map(|i| (0..5).map(move |j| vec![i as f64, j as f64])).collect();
1562        let mut t = DelaunayNd::new(&grid[..13]).unwrap();
1563        t.add_points(&grid[13..]).unwrap();
1564        let area: f64 = t.simplices.iter().map(|s| det((1..=2).map(|k| sub(&grid[s[k]], &grid[s[0]])).collect()).abs() / 2.0).sum();
1565        assert!((area - 16.0).abs() < 1e-6, "{area}");
1566        // The furthest-site triangulation grows too, and a point outside the old box is fine.
1567        let pts = lcg(25, 2, 77);
1568        let mut f = DelaunayNd::new_furthest_site(&pts[..15]).unwrap();
1569        f.add_points(&pts[15..]).unwrap();
1570        assert_eq!(simplex_set(&f), simplex_set(&DelaunayNd::new_furthest_site(&pts).unwrap()));
1571        let mut g = DelaunayNd::new(&pts).unwrap();
1572        g.add_points(&[vec![5.0, 5.0], vec![-4.0, 3.0]]).unwrap();
1573        assert!(g.find_simplex(&[0.0, 3.0]).is_some() && g.find_simplex(&[0.0, 4.5]).is_none() && g.points.len() == 27);
1574    }
1575
1576    /// The simplices of a triangulation as sets of coordinates (so that two orderings of the same
1577    /// points can be compared).
1578    fn geometric_simplices(t: &DelaunayNd) -> Vec<Vec<Vec<i64>>> {
1579        let mut v: Vec<Vec<Vec<i64>>> = t
1580            .simplices
1581            .iter()
1582            .map(|s| {
1583                let mut c: Vec<Vec<i64>> = s.iter().map(|&i| t.points[i].iter().map(|x| (x * 1e6).round() as i64).collect()).collect();
1584                c.sort();
1585                c
1586            })
1587            .collect();
1588        v.sort();
1589        v
1590    }
1591
1592    #[test]
1593    fn cospherical_ties_are_resolved_by_a_rule_that_depends_only_on_the_points() {
1594        // A 5 × 5 grid in any order, and built in two steps, gives one triangulation: fans from the
1595        // lowest corner of every cell, so all the diagonals run the same way.
1596        let grid: Vec<Vec<f64>> = (0..5).flat_map(|i| (0..5).map(move |j| vec![i as f64, j as f64])).collect();
1597        let fresh = DelaunayNd::new(&grid).unwrap();
1598        assert_eq!(fresh.simplices.len(), 32);
1599        let area: f64 = fresh.simplices.iter().map(|s| det((1..=2).map(|k| sub(&grid[s[k]], &grid[s[0]])).collect()).abs() / 2.0).sum();
1600        assert!((area - 16.0).abs() < 1e-9);
1601        let mut shuffled = grid.clone();
1602        let mut state = 7u64;
1603        for k in (1..shuffled.len()).rev() {
1604            state = state.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
1605            shuffled.swap(k, (state >> 33) as usize % (k + 1));
1606        }
1607        assert_eq!(geometric_simplices(&DelaunayNd::new(&shuffled).unwrap()), geometric_simplices(&fresh));
1608        let mut grown = DelaunayNd::new(&grid[..9]).unwrap();
1609        grown.add_points(&grid[9..]).unwrap();
1610        assert_eq!(geometric_simplices(&grown), geometric_simplices(&fresh));
1611        // Neighbours are consistent: a shared ridge is listed on both sides.
1612        for (s, nb) in fresh.neighbors.iter().enumerate() {
1613            for (i, g) in nb.iter().enumerate() {
1614                if let Some(g) = g {
1615                    let shared: Vec<usize> = fresh.simplices[s].iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect();
1616                    assert!(shared.iter().all(|v| fresh.simplices[*g].contains(v)) && fresh.neighbors[*g].contains(&Some(s)));
1617                }
1618            }
1619        }
1620        // The cube: eight cospherical points, one cell, still a tiling of volume 1 in any order.
1621        let cube: Vec<Vec<f64>> = (0..8).map(|m| (0..3).map(|k| ((m >> k) & 1) as f64).collect()).collect();
1622        let t = DelaunayNd::new(&cube).unwrap();
1623        let vol: f64 = t.simplices.iter().map(|s| det((1..=3).map(|k| sub(&cube[s[k]], &cube[s[0]])).collect()).abs() / 6.0).sum();
1624        assert!((vol - 1.0).abs() < 1e-9, "{vol}");
1625        let reversed: Vec<Vec<f64>> = cube.iter().rev().cloned().collect();
1626        assert_eq!(geometric_simplices(&DelaunayNd::new(&reversed).unwrap()), geometric_simplices(&t));
1627        // A 4 × 4 × 4 grid in 3-D tiles the cube.
1628        let g3: Vec<Vec<f64>> = (0..4).flat_map(|i| (0..4).flat_map(move |j| (0..4).map(move |k| vec![i as f64, j as f64, k as f64]))).collect();
1629        let t3 = DelaunayNd::new(&g3).unwrap();
1630        let vol3: f64 = t3.simplices.iter().map(|s| det((1..=3).map(|k| sub(&g3[s[k]], &g3[s[0]])).collect()).abs() / 6.0).sum();
1631        assert!((vol3 - 27.0).abs() < 1e-8, "{vol3}");
1632    }
1633}