Geometry in any dimension: hulls, Delaunay, Voronoi and half-spaces
| Problem | Compute convex hulls, Delaunay triangulations and Voronoi diagrams of points in any number of dimensions; intersect half-spaces; build Voronoi diagrams on a sphere; and interpolate scattered data linearly in three or more dimensions |
| Devised by | Bradford Barber, David Dobkin and Hannu Huhdanpaa (1996), Quickhull and Qhull; Kenneth Brown (1979) and Herbert Edelsbrunner and Raimund Seidel (1986), Delaunay triangulations as lifted hulls; Boris Delaunay (1934); Georgy Voronoi (1908); Robert Renka (1997), spherical Delaunay and Voronoi |
| Accuracy | Combinatorially identical to SciPy’s (Qhull’s) results on points in general position; volumes, areas and vertices to rounding |
| Cost | Hulls: about for and in the worst case, as Qhull; Delaunay in dimensions: a hull in |
| Read first | Convex hulls and polygon booleans, Delaunay triangulations and Voronoi diagrams |
| API | ConvexHullNd, DelaunayNd (find_simplex, barycentric), VoronoiNd, HalfspaceIntersection, SphericalVoronoi (calculate_areas); LinearNdInterpolator |
Overview
The library’s earlier geometry routines are specialised to the plane and to space. scipy.spatial wraps Qhull, which works in any dimension, and this entry brings the same reach to the library:
ConvexHullNd: hulls of points in for any , with facet hyperplanes, neighbours, volume and boundary area.DelaunayNd: Delaunay triangulations into simplices, with point location (find_simplex) and barycentric coordinates.VoronoiNd: Voronoi diagrams as duals of the triangulations.HalfspaceIntersection: the polytope where a set of linear inequalities holds, its vertices and its non-redundant constraints.SphericalVoronoi: Voronoi diagrams of points on a sphere, with region areas.LinearNdInterpolator: SciPy’sLinearNDInterpolatorin three and more dimensions.
Where it is used
Hulls, triangulations and Voronoi diagrams in many dimensions appear wherever data have more than three coordinates.
- Interpolation of scattered data. Delaunay triangulation of points in 2-D, 3-D or higher gives piecewise-linear interpolation of measurements taken at irregular locations (sensor networks, engine test maps).
- Optimisation and economics. Half-space intersection is linear programming’s feasible region; the convex hull of attainable outcomes is the set of Pareto-optimal trade-offs.
- Spherical Voronoi diagrams. Partitions of the globe by nearest station (weather stations, satellites) use the spherical version.
- Computational physics. Phase diagrams and Wulff shapes are convex hulls in composition or energy space.
History
Quickhull grew out of the planar “quicksort-like” hull algorithms of the 1970s. Barber, Dobkin and Huhdanpaa (1996) generalised it to any dimension, made it robust to rounding by merging nearly coplanar facets, and released it as Qhull, which MATLAB, R, Octave and SciPy all use. Brown (1979) observed that projecting points onto a paraboloid turns circles into planes, so that Delaunay triangulations are lower convex hulls one dimension up; Edelsbrunner and Seidel (1986) made that the standard construction. The duality between half-spaces and points, used to intersect half-spaces by computing a hull, is classical projective geometry.
The idea
Quickhull
Start from a simplex of points, and give every remaining point to a facet it lies outside of. Then repeat:
- Take a facet with outside points and its farthest point .
- Find all facets can see (those with on their outer side) by a search over facet neighbours.
- The boundary of the visible region is the horizon: a set of ridges (faces of dimension ). Delete the visible facets and join to each horizon ridge, making a cone of new facets.
- Give the outside points of the deleted facets to the new facets.
When no facet has outside points, the facets form the hull. Each new facet’s hyperplane comes from the null space of its edge vectors, and its orientation from a point inside the first simplex. Points within a small tolerance of a facet count as inside, which is Qhull’s default behaviour for coplanar points.
Delaunay triangulations by lifting
Lift each point to . A sphere becomes the hyperplane . So a simplex has an empty circumsphere exactly when its lifted vertices span a lower facet of the lifted hull, a facet with no lifted point beneath it. The Delaunay triangulation is the projection of the lower hull.
Furthest-site triangulations use the other side of the lifted hull. A lifted point beneath the upper hull has its sphere inside out: a simplex whose lifted vertices span an upper facet has a circumsphere that contains all the points, not none. DelaunayNd::new_furthest_site keeps those facets (closing the hull from below with a far point where the ordinary one closes it from above). The simplices triangulate the convex hull of the points, using only points that are hull vertices, and are the dual of the farthest-point Voronoi diagram, whose regions are the cells where each point is the farthest one. The smallest circle that contains a point set is found among their circumcentres.
Grids and other sets with four or more cospherical points have many valid triangulations. The lifted hull is computed with a perturbation of the lifted coordinate of order in a unit box (Qhull’s “joggle”), and then the ties are resolved by a rule that depends only on the points: facets that lie in one hyperplane of the unjoggled lifted points are merged into a cell (Qhull’s merged facet), and the cell is triangulated by pulling: the cell’s lexicographically smallest vertex is the apex, each facet of the cell that does not contain it is triangulated the same way from its own boundary, and the pieces are coned to the apex. A grid therefore has all its diagonals running the same way, and the result is the same for any order of the points and for a triangulation grown by add_points. It is not Qhull’s choice: Qhull fans from an apex fixed by its internal vertex numbering, which gives a checkerboard of diagonals on a grid from Delaunay and an irregular pattern when the points are shuffled, and cannot be reproduced without emulating its steps.
Voronoi diagrams and point location
The Voronoi vertex of each Delaunay simplex is its circumcentre. Each Delaunay edge between two points is a Voronoi ridge between their regions, whose vertices are the circumcentres of the simplices around the edge; a ridge reaches infinity when the edge lies on the hull. find_simplex walks from simplex to simplex towards the query point, always crossing the face opposite the most negative barycentric coordinate.
Half-spaces and spheres
Given half-spaces and an interior point , the dual point of each half-space is . A facet of the dual points’ hull with hyperplane corresponds to the vertex of the intersection. Half-spaces whose dual points are not hull vertices are redundant.
On a sphere, the convex hull of the points is their Delaunay triangulation on the sphere, because every hull facet’s plane cuts the sphere in a circle with no point beyond it. Each facet’s outward normal, scaled by the radius, is the Voronoi vertex. Region areas follow from the spherical excess of the triangles fanned from each generator.
Implementation
/// Quickhull in `d ≥ 2` dimensions. `eps` is the distance below which a point counts as on a
/// facet; such points are not added (Qhull's default "coplanar points are inside").
fn quickhull(points: &[Vec<f64>], eps: f64) -> Result<Hull, ErrorsJSL> {
let n = points.len();
let d = points.first().map_or(0, |p| p.len());
if d < 2 || n < d + 1 {
return Err(ErrorsJSL::InvalidInputRange("Quickhull needs d ≥ 2 and at least d + 1 points"));
}
// Initial simplex: the extreme pair along the first coordinate, then repeatedly the point
// farthest from the affine hull of those chosen (Gram-Schmidt on the differences).
let lo = (0..n).min_by(|&a, &b| points[a][0].total_cmp(&points[b][0])).unwrap();
let hi = (0..n).max_by(|&a, &b| points[a][0].total_cmp(&points[b][0])).unwrap();
let mut simplex = vec![lo];
let mut basis: Vec<Vec<f64>> = Vec::new();
let mut candidate = Some(hi);
while simplex.len() < d + 1 {
let next = match candidate.take() {
Some(c) if c != simplex[0] => c,
_ => (0..n)
.max_by(|&a, &b| {
let r = |i: usize| {
let mut v = sub(&points[i], &points[simplex[0]]);
for q in &basis {
let c = dot(q, &v);
v.iter_mut().zip(q).for_each(|(x, y)| *x -= c * y);
}
dot(&v, &v)
};
r(a).total_cmp(&r(b))
})
.unwrap(),
};
let mut v = sub(&points[next], &points[simplex[0]]);
for q in &basis {
let c = dot(q, &v);
v.iter_mut().zip(q).for_each(|(x, y)| *x -= c * y);
}
let vn = dot(&v, &v).sqrt();
if vn <= eps.max(f64::MIN_POSITIVE) {
return Err(ErrorsJSL::InvalidInputRange("the points lie in a lower-dimensional subspace (the initial simplex is flat)"));
}
basis.push(v.iter().map(|t| t / vn).collect());
simplex.push(next);
}
let interior: Vec<f64> = (0..d).map(|k| simplex.iter().map(|&i| points[i][k]).sum::<f64>() / (d + 1) as f64).collect();
let mut facets: Vec<Facet> = (0..=d)
.map(|skip| make_facet(points, simplex.iter().enumerate().filter(|(i, _)| *i != skip).map(|(_, &v)| v).collect(), &interior))
.collect();
// Facet i omits simplex vertex i; the facet across the ridge opposite vertex v of facet i is
// the facet that omits v.
for i in 0..=d {
let verts = facets[i].vertices.clone();
facets[i].neighbors = verts.iter().map(|v| simplex.iter().position(|s| s == v).unwrap()).collect();
}
let in_simplex: Vec<bool> = (0..n).map(|i| simplex.contains(&i)).collect();
for p in 0..n {
if in_simplex[p] {
continue;
}
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)) {
facets[f].outside.push(p);
}
}
let mut hull = Hull { facets, interior };
expand(points, &mut hull, eps);
Ok(hull)
}
/// Adds the points that lie outside facets (already assigned to their facet's `outside` list) to the
/// hull one at a time, the farthest of a facet first, until no facet has an outside point.
fn expand(points: &[Vec<f64>], hull: &mut Hull, eps: f64) {
let d = hull.interior.len();
let interior = hull.interior.clone();
let facets = &mut hull.facets;
while let Some(start) = facets.iter().position(|f| f.alive && !f.outside.is_empty()) {
let fs = &facets[start];
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();
// Visible facets by a search over neighbours. A facet within `eps` of the apex's plane is not
// visible, but facets that are nearly coplanar can leave a horizon that does not close up (a
// sub-face of the horizon shared by one ridge or three). When that happens the facets a little
// below the threshold are taken as visible too, in growing steps, until the horizon is closed.
let mut visible = Vec::new();
let mut seen: HashMap<usize, bool> = HashMap::new();
for band in [0.0, 1.0, 10.0, 100.0, 1e3, 1e4, 1e5] {
let threshold = eps * (1.0 - band);
visible = vec![start];
seen = HashMap::from([(start, true)]);
let mut k = 0;
while k < visible.len() {
let f = visible[k];
k += 1;
for &g in &facets[f].neighbors.clone() {
if g == usize::MAX || seen.contains_key(&g) {
continue;
}
let vis = dot(&facets[g].normal, &points[apex]) + facets[g].offset > threshold;
seen.insert(g, vis);
if vis {
visible.push(g);
}
}
}
// The horizon closes up if every (d − 3)-face of it lies on exactly two horizon ridges.
let mut count: HashMap<Vec<usize>, usize> = HashMap::new();
for &f in &visible {
for i in 0..d {
if seen.get(&facets[f].neighbors[i]).copied().unwrap_or(false) {
continue;
}
let verts: Vec<usize> = facets[f].vertices.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect();
for skip in 0..verts.len() {
let mut key: Vec<usize> = verts.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &v)| v).collect();
key.sort_unstable();
*count.entry(key).or_insert(0) += 1;
}
}
}
if count.values().all(|&c| c == 2) {
break;
}
}
// Horizon ridges: (visible facet, index of the opposite vertex) with an invisible neighbour.
let mut new_ids = Vec::new();
let mut ridge_map: HashMap<Vec<usize>, (usize, usize)> = HashMap::new();
for &f in &visible {
for i in 0..d {
let g = facets[f].neighbors[i];
if seen.get(&g).copied().unwrap_or(false) {
continue;
}
let mut verts: Vec<usize> = facets[f].vertices.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect();
verts.push(apex);
let mut nf = make_facet(points, verts, &interior);
let id = facets.len();
// Neighbour opposite the apex (the last vertex) is g; repoint g's link from f.
nf.neighbors = vec![usize::MAX; d];
nf.neighbors[d - 1] = g;
if let Some(slot) = facets[g].neighbors.iter().position(|&h| h == f) {
facets[g].neighbors[slot] = id;
}
// Ridges through the apex, keyed by the sorted vertex set without one vertex.
for j in 0..d - 1 {
let mut key: Vec<usize> = nf.vertices.iter().enumerate().filter(|(m, _)| *m != j).map(|(_, &v)| v).collect();
key.sort_unstable();
if let Some(&(other, oj)) = ridge_map.get(&key) {
nf.neighbors[j] = other;
facets[other].neighbors[oj] = id;
} else {
ridge_map.insert(key, (id, j));
}
}
facets.push(nf);
new_ids.push(id);
}
}
// Reassign the outside points of the deleted facets.
let mut orphans = Vec::new();
for &f in &visible {
facets[f].alive = false;
orphans.append(&mut facets[f].outside);
}
for p in orphans {
if p == apex {
continue;
}
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)) {
facets[f].outside.push(p);
}
}
}
}
/// The Delaunay triangulation of points in any dimension `d ≥ 2` (SciPy's `Delaunay`): the
/// lower facets of the hull of the points lifted to `(x, ‖x‖²)`. Degenerate (cospherical) sets,
/// such as grids, are triangulated by a tiny deterministic perturbation of the lifted
/// coordinate, which picks one of their valid triangulations (Qhull's "joggle").
#[derive(Clone, Debug)]
#[non_exhaustive]
pub struct DelaunayNd {
pub points: Vec<Vec<f64>>,
/// Each simplex as `d + 1` point indices.
pub simplices: Vec<Vec<usize>>,
/// `neighbors[s][i]`: the simplex opposite vertex `i` of simplex `s`, or `None` on the hull.
pub neighbors: Vec<Vec<Option<usize>>>,
/// For each simplex, the barycentric transform: rows `0..d` hold `T⁻¹` and row `d` the
/// vertex `r = x_{v_d}`, so that `c = T⁻¹ (x − r)` gives the first `d` barycentric
/// coordinates (SciPy's `transform`).
pub transform: Vec<Vec<Vec<f64>>>,
/// Whether this is the furthest-site triangulation.
pub furthest_site: bool,
/// The lifted hull, kept so that points can be added without starting over.
state: DelState,
}
/// The lifted hull behind a [`DelaunayNd`]: the points in the frame fixed at construction (lifted
/// to the paraboloid, then the point at infinity, then any added points), the Quickhull state,
/// and what is needed to lift the points that are added later in the same way.
#[derive(Clone, Debug)]
struct DelState {
/// The lifted points; index `top` is the point at infinity.
lifted: Vec<Vec<f64>>,
top: usize,
hull: Hull,
lo: Vec<f64>,
scale: f64,
/// The state of the generator of the lifting joggle.
jog: u64,
eps: f64,
options: QhullOptions,
}
fn invert(m: &[Vec<f64>]) -> Option<Vec<Vec<f64>>> {
let n = m.len();
let mut a: Vec<Vec<f64>> = m.iter().enumerate().map(|(i, r)| {
let mut r = r.clone();
r.extend((0..n).map(|j| if i == j { 1.0 } else { 0.0 }));
r
}).collect();
for k in 0..n {
let p = (k..n).max_by(|&i, &j| a[i][k].abs().total_cmp(&a[j][k].abs()))?;
if a[p][k].abs() < 1e-300 {
return None;
}
a.swap(k, p);
let piv = a[k][k];
a[k].iter_mut().for_each(|v| *v /= piv);
for i in 0..n {
if i != k {
let f = a[i][k];
if f != 0.0 {
let rk = a[k].clone();
a[i].iter_mut().zip(&rk).for_each(|(x, y)| *x -= f * y);
}
}
}
}
Some(a.into_iter().map(|r| r[n..].to_vec()).collect())
}
/// The rank of the vectors `p − p₀` for `p` in `vs` (the affine dimension of the points), to tolerance `tol`.
fn affine_rank(points: &[Vec<f64>], vs: &[usize], tol: f64) -> usize {
let p0 = &points[vs[0]];
let mut basis: Vec<Vec<f64>> = Vec::new();
for &v in &vs[1..] {
let mut x = sub(&points[v], p0);
for q in &basis {
let c = dot(q, &x);
x.iter_mut().zip(q).for_each(|(a, b)| *a -= c * b);
}
let n = dot(&x, &x).sqrt();
if n > tol {
basis.push(x.iter().map(|t| t / n).collect());
}
}
basis.len()
}
/// The pulling triangulation of a convex polytope given by the simplices of its boundary: every facet
/// of the polytope that does not contain the polytope's lexicographically smallest vertex (the apex) is
/// itself triangulated the same way (from its own boundary) and coned to the apex. The result depends
/// only on the vertices, not on how the boundary was triangulated. `boundary` holds `k` vertices per
/// simplex; the triangulation has `k + 1`.
fn pulling_triangulation(points: &[Vec<f64>], boundary: Vec<Vec<usize>>, tol: f64) -> Vec<Vec<usize>> {
let Some(first) = boundary.first() else { return Vec::new() };
let k = first.len();
let m = boundary.len();
// Facets of the polytope: boundary simplices that share a ridge and lie in one flat of dimension k − 1.
let mut parent: Vec<usize> = (0..m).collect();
fn find(parent: &mut [usize], mut i: usize) -> usize {
while parent[i] != i {
parent[i] = parent[parent[i]];
i = parent[i];
}
i
}
let mut by_ridge: HashMap<Vec<usize>, Vec<usize>> = HashMap::new();
for (si, s) in boundary.iter().enumerate() {
for skip in 0..k {
let mut key: Vec<usize> = s.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &v)| v).collect();
key.sort_unstable();
by_ridge.entry(key).or_default().push(si);
}
}
for sharing in by_ridge.values() {
if let [a, b] = sharing[..] {
let mut union: Vec<usize> = boundary[a].iter().chain(&boundary[b]).copied().collect();
union.sort_unstable();
union.dedup();
if affine_rank(points, &union, tol) < k {
let (ra, rb) = (find(&mut parent, a), find(&mut parent, b));
parent[ra] = rb;
}
}
}
let mut facets: HashMap<usize, Vec<usize>> = HashMap::new();
for si in 0..m {
let r = find(&mut parent, si);
facets.entry(r).or_default().push(si);
}
let mut all: Vec<usize> = boundary.iter().flatten().copied().collect();
all.sort_unstable();
all.dedup();
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");
let mut roots: Vec<usize> = facets.keys().copied().collect();
roots.sort_unstable();
let mut out = Vec::new();
for r in roots {
let simplices: Vec<&Vec<usize>> = facets[&r].iter().map(|&i| &boundary[i]).collect();
if simplices.iter().any(|s| s.contains(&apex)) {
continue;
}
// The facet's own triangulation: a single simplex stays, a merged facet is pulled from its boundary.
let triangulation: Vec<Vec<usize>> = if simplices.len() == 1 || k < 3 {
simplices.iter().map(|s| (*s).clone()).collect()
} else {
let mut count: HashMap<Vec<usize>, (usize, Vec<usize>)> = HashMap::new();
for s in &simplices {
for skip in 0..k {
let face: Vec<usize> = s.iter().enumerate().filter(|(j, _)| *j != skip).map(|(_, &v)| v).collect();
let mut key = face.clone();
key.sort_unstable();
let e = count.entry(key).or_insert((0, face));
e.0 += 1;
}
}
let mut rim: Vec<Vec<usize>> = count.into_values().filter(|(c, _)| *c == 1).map(|(_, f)| f).collect();
rim.sort_unstable();
pulling_triangulation(points, rim, tol)
};
out.extend(triangulation.into_iter().map(|mut t| {
t.push(apex);
t
}));
}
out
}
/// The triangulation with its ties resolved by a rule that depends only on the points: facets of the
/// (joggled) lifted hull that lie in one hyperplane of the *unjoggled* lifted points (four or more
/// cospherical points: a grid cell, a regular polytope) are merged into one cell, and the cell is
/// triangulated by a fan from its lexicographically smallest vertex (Qhull's `Qt` fans from an apex
/// too, but chooses it by internal numbering). The result does not depend on the order of the points or
/// on the joggle, so a triangulation grown by `add_points` equals a fresh one on degenerate sets. A cell
/// whose fan does not tile it (numerical trouble) keeps the joggled triangulation.
fn 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>>>) {
let d = lo.len();
let n = vertices.len();
if n == 0 {
return (vertices, neighbors);
}
// Distances are compared with this fraction of the extent of the points.
let tol = 1e-9 * scale;
let lift = |v: usize| -> Vec<f64> {
let mut q: Vec<f64> = points[v].iter().zip(lo).map(|(x, l)| (x - l) / scale).collect();
let r2: f64 = q.iter().map(|t| t * t).sum();
q.push(r2);
q
};
// The unjoggled hyperplane of every facet.
let planes: Vec<(Vec<f64>, f64)> = vertices
.iter()
.map(|vs| {
let p0 = lift(vs[0]);
let rows: Vec<Vec<f64>> = vs[1..].iter().map(|&v| sub(&lift(v), &p0)).collect();
let normal = normal_of(&rows, d + 1);
let offset = -dot(&normal, &p0);
(normal, offset)
})
.collect();
let volume = |vs: &[usize]| -> f64 { det((1..=d).map(|k| sub(&points[vs[k]], &points[vs[0]])).collect()).abs() / factorial(d) };
// A facet of the joggled hull can be flat in the plane of the points (its vertices dependent); its lifted
// hyperplane is then arbitrary, so it is joined to its neighbours by the plane of the other one.
let vols: Vec<f64> = vertices.iter().map(|vs| volume(vs)).collect();
let vmax = vols.iter().cloned().fold(0.0f64, f64::max);
let flat: Vec<bool> = vols.iter().map(|&v| v <= 1e-12 * vmax).collect();
// Union-find over neighbouring facets whose opposite vertices lie on the plane.
let mut parent: Vec<usize> = (0..n).collect();
fn find(parent: &mut [usize], mut i: usize) -> usize {
while parent[i] != i {
parent[i] = parent[parent[i]];
i = parent[i];
}
i
}
for f in 0..n {
for (i, g) in neighbors[f].iter().enumerate() {
let Some(g) = *g else { continue };
// The vertex of g that is not on the ridge shared with f (the ridge omits f's vertex i).
let opposite = vertices[g].iter().find(|v| !vertices[f].iter().enumerate().any(|(j, w)| j != i && w == *v)).copied();
let Some(o) = opposite else { continue };
let on_plane = if !flat[f] {
(dot(&planes[f].0, &lift(o)) + planes[f].1).abs() < 1e-9
} else if !flat[g] {
(dot(&planes[g].0, &lift(vertices[f][i])) + planes[g].1).abs() < 1e-9
} else {
// Two flat facets: they share a cell if the plane of either one's other neighbours is
// unknowable here; join them (a flat pair never separates two cells).
true
};
if on_plane {
let (a, b) = (find(&mut parent, f), find(&mut parent, g));
parent[a] = b;
}
}
}
let mut groups: HashMap<usize, Vec<usize>> = HashMap::new();
for f in 0..n {
let r = find(&mut parent, f);
groups.entry(r).or_default().push(f);
}
let mut out: Vec<Vec<usize>> = Vec::with_capacity(n);
let mut roots: Vec<usize> = groups.keys().copied().collect();
roots.sort_unstable();
for r in roots {
let members = &groups[&r];
if members.len() == 1 {
// A flat facet with no neighbour at all is an artefact of the joggle: it covers no volume and nothing
// can be reached through it.
if !(flat[members[0]] && neighbors[members[0]].iter().all(|g| g.is_none())) {
out.push(vertices[members[0]].clone());
}
continue;
}
let in_group: std::collections::HashSet<usize> = members.iter().copied().collect();
let mut cell: Vec<usize> = members.iter().flat_map(|&f| vertices[f].iter().copied()).collect();
cell.sort_unstable();
cell.dedup();
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");
// The cell's boundary: the ridges of its facets that no other facet of the cell shares.
let mut boundary: Vec<Vec<usize>> = Vec::new();
for &f in members {
for (i, g) in neighbors[f].iter().enumerate() {
if g.is_some_and(|g| in_group.contains(&g)) {
continue;
}
boundary.push(vertices[f].iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect());
}
}
let _ = apex;
// The joggled triangulation of the cell's boundary can contain flat simplices (four corners of a
// square as a "tetrahedron"), which the pulling rule cannot place: a cell of cospherical points is
// the convex hull of its vertices, so take its boundary from the hull, which merges and
// triangulates the coplanar pieces itself.
if let Ok(hull) = ConvexHullNd::new(&cell.iter().map(|&v| points[v].clone()).collect::<Vec<_>>()) {
boundary = hull.simplices.iter().map(|s| s.iter().map(|&i| cell[i]).collect()).collect();
}
let fan = pulling_triangulation(points, boundary, tol);
let want: f64 = members.iter().map(|&f| volume(&vertices[f])).sum();
let got: f64 = fan.iter().map(|s| volume(s)).sum();
if (got - want).abs() <= 1e-9 * want.max(f64::MIN_POSITIVE) {
// The fan's flat simplices (ridges in a face through the apex) carry no volume: drop them.
out.extend(fan.into_iter().filter(|s| volume(s) > 1e-12 * want / members.len() as f64));
} else {
out.extend(members.iter().map(|&f| vertices[f].clone()));
}
}
// Neighbours from the shared ridges.
let mut ridges: HashMap<Vec<usize>, Vec<(usize, usize)>> = HashMap::new();
for (s, vs) in out.iter().enumerate() {
for i in 0..vs.len() {
let mut key: Vec<usize> = vs.iter().enumerate().filter(|(j, _)| *j != i).map(|(_, &v)| v).collect();
key.sort_unstable();
ridges.entry(key).or_default().push((s, i));
}
}
let mut nb: Vec<Vec<Option<usize>>> = out.iter().map(|vs| vec![None; vs.len()]).collect();
for shared in ridges.values() {
if let [(a, i), (b, j)] = shared[..] {
nb[a][i] = Some(b);
nb[b][j] = Some(a);
}
}
(out, nb)
}
/// A point in the frame of the triangulation (the unit box of the construction), lifted to the
/// paraboloid with the tiny joggle of the lifted coordinate.
fn lift_point(p: &[f64], lo: &[f64], scale: f64, jog: &mut u64) -> Vec<f64> {
let mut q: Vec<f64> = p.iter().zip(lo).map(|(x, l)| (x - l) / scale).collect();
*jog ^= *jog << 13;
*jog ^= *jog >> 7;
*jog ^= *jog << 17;
let j = ((*jog >> 11) as f64 / (1u64 << 53) as f64 - 0.5) * 1e-11;
let r2: f64 = q.iter().map(|v| v * v).sum();
q.push(r2 + j);
q
}
impl DelaunayNd {
pub fn new(points: &[Vec<f64>]) -> Result<DelaunayNd, ErrorsJSL> {
Self::build(points, false, &QhullOptions::default())
}
/// As [`DelaunayNd::new`] with Qhull-style options (see [`QhullOptions`]): `QJ` moves the
/// points by a larger amount than the built-in tiny joggle, and `E` sets the tolerance of the
/// lifted hull.
pub fn with_options(points: &[Vec<f64>], options: &QhullOptions) -> Result<DelaunayNd, ErrorsJSL> {
Self::build(points, false, options)
}
/// The furthest-site Delaunay triangulation (SciPy's `Delaunay(furthest_site=True)`): the
/// simplices whose circumscribed sphere contains *all* the points, from the upper facets of
/// the lifted hull. It triangulates the convex hull of the points, using only the points that
/// are vertices of the hull; the others appear in no simplex.
pub fn new_furthest_site(points: &[Vec<f64>]) -> Result<DelaunayNd, ErrorsJSL> {
Self::build(points, true, &QhullOptions::default())
}
/// The furthest-site triangulation with Qhull-style options.
pub fn new_furthest_site_with_options(points: &[Vec<f64>], options: &QhullOptions) -> Result<DelaunayNd, ErrorsJSL> {
Self::build(points, true, options)
}
/// Adds points (SciPy's `add_points`): the new points get the next indices. They are lifted in
/// the frame (the box and the joggle sequence) fixed when the triangulation was made and added to
/// the lifted hull as Quickhull does, so the old points are not touched: only the facets that a
/// new point sees are replaced. In general position the result is the triangulation of a fresh
/// computation; for cospherical sets it is one of the valid ones, which may differ from a fresh
/// computation's, since the joggle depends on the order in which the points arrive.
pub fn add_points(&mut self, new: &[Vec<f64>]) -> Result<(), ErrorsJSL> {
let d = self.state.lo.len();
if new.iter().any(|p| p.len() != d || p.iter().any(|v| !v.is_finite())) {
return Err(ErrorsJSL::InvalidInputRange("points must be finite and of the triangulation's dimension"));
}
if new.is_empty() {
return Ok(());
}
let first = self.points.len();
let mut points = std::mem::take(&mut self.points);
points.extend_from_slice(new);
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() });
let moved: Vec<Vec<f64>> = if state.options.joggle.is_some() { state.options.joggled(&points)[first..].to_vec() } else { new.to_vec() };
let first_new = state.lifted.len();
for p in &moved {
let q = lift_point(p, &state.lo, state.scale, &mut state.jog);
state.lifted.push(q);
}
for h in first_new..state.lifted.len() {
let best = state
.hull
.facets
.iter()
.enumerate()
.filter(|(_, f)| f.alive)
.map(|(i, f)| (i, dot(&f.normal, &state.lifted[h]) + f.offset))
.filter(|(_, dist)| *dist > state.eps)
.max_by(|a, b| a.1.total_cmp(&b.1));
if let Some((f, _)) = best {
state.hull.facets[f].outside.push(h);
}
}
expand(&state.lifted, &mut state.hull, state.eps);
*self = Self::from_state(points, self.furthest_site, state);
Ok(())
}
fn build(points: &[Vec<f64>], furthest_site: bool, options: &QhullOptions) -> Result<DelaunayNd, ErrorsJSL> {
let d = points.first().map_or(0, |p| p.len());
if d < 1 || points.iter().any(|p| p.len() != d || p.iter().any(|v| !v.is_finite())) {
return Err(ErrorsJSL::InvalidInputRange("points must be finite and of one dimension"));
}
// Scale to a unit box (Qhull's Qbb) and lift, with a tiny deterministic joggle (and the
// larger one that `QJ` asks for).
let moved = options.joggled(points);
let lo: Vec<f64> = (0..d).map(|k| moved.iter().map(|p| p[k]).fold(f64::INFINITY, f64::min)).collect();
let hi: Vec<f64> = (0..d).map(|k| moved.iter().map(|p| p[k]).fold(f64::NEG_INFINITY, f64::max)).collect();
let scale = (0..d).map(|k| hi[k] - lo[k]).fold(0.0f64, f64::max).max(f64::MIN_POSITIVE);
let mut jog = 0x9E3779B97F4A7C15u64;
let mut lifted: Vec<Vec<f64>> = moved.iter().map(|p| lift_point(p, &lo, scale, &mut jog)).collect();
// A point far above the paraboloid closes the hull (Qhull's Qz) and keeps upper facets
// separate from lower ones; for the furthest-site triangulation it is a point far below,
// and the upper facets are the ones kept.
let top = lifted.len();
let mut far: Vec<f64> = vec![0.5; d];
far.push(if furthest_site { -1e3 * (d as f64 + 1.0) } else { 1e3 * (d as f64 + 1.0) });
lifted.push(far);
let eps = options.tolerance.unwrap_or(1e2 * (d as f64 + 1.0) * f64::EPSILON * 4.0);
let hull = quickhull(&lifted, eps)?;
Ok(Self::from_state(points.to_vec(), furthest_site, DelState { lifted, top, hull, lo, scale, jog, eps, options: options.clone() }))
}
/// The triangulation from the lifted hull: its lower (or, furthest-site, upper) facets that do not
/// touch the point at infinity, with the hull's point indices translated to the input's.
fn from_state(points: Vec<Vec<f64>>, furthest_site: bool, state: DelState) -> DelaunayNd {
let d = state.lo.len();
let top = state.top;
let hull = &state.hull;
let wanted = |nz: f64| if furthest_site { nz > 1e-6 } else { nz < -1e-6 };
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();
let index: HashMap<usize, usize> = alive.iter().enumerate().map(|(k, &i)| (i, k)).collect();
// Hull indices above the point at infinity are the added points, one place later than the input's.
let input = |h: usize| if h > top { h - 1 } else { h };
let facet_vertices: Vec<Vec<usize>> = alive.iter().map(|&i| hull.facets[i].vertices.iter().map(|&h| input(h)).collect()).collect();
let facet_neighbors: Vec<Vec<Option<usize>>> = alive.iter().map(|&i| hull.facets[i].neighbors.iter().map(|g| index.get(g).copied()).collect()).collect();
let (simplices, neighbors) = canonical_ties(&points, &state.lo, state.scale, facet_vertices, facet_neighbors);
let transform = simplices
.iter()
.map(|s| {
let r = &points[s[d]];
let t: Vec<Vec<f64>> = (0..d).map(|row| (0..d).map(|col| points[s[col]][row] - r[row]).collect()).collect();
let mut out = invert(&t).unwrap_or_else(|| vec![vec![f64::NAN; d]; d]);
out.push(r.clone());
out
})
.collect();
DelaunayNd { points, simplices, neighbors, transform, furthest_site, state }
}
/// The barycentric coordinates of `x` in simplex `s` (`d + 1` values summing to 1).
pub fn barycentric(&self, s: usize, x: &[f64]) -> Vec<f64> {
let t = &self.transform[s];
let d = x.len();
let dx = sub(x, &t[d]);
let mut c: Vec<f64> = (0..d).map(|i| dot(&t[i], &dx)).collect();
let last = 1.0 - c.iter().sum::<f64>();
c.push(last);
c
}
/// The simplex containing `x`, or `None` outside the triangulation (SciPy's `find_simplex`),
/// by a walk from simplex 0 towards `x`, falling back to a full search.
pub fn find_simplex(&self, x: &[f64]) -> Option<usize> {
let tol = 1e2 * f64::EPSILON;
if self.simplices.is_empty() {
return None;
}
let mut s = 0;
for _ in 0..4 * self.simplices.len() + 10 {
let c = self.barycentric(s, x);
let (i, m) = c.iter().enumerate().min_by(|a, b| a.1.total_cmp(b.1)).map(|(i, m)| (i, *m)).unwrap();
if m >= -tol {
return Some(s);
}
match self.neighbors[s][i] {
Some(t) => s = t,
None => break,
}
}
(0..self.simplices.len()).find(|&s| self.barycentric(s, x).iter().all(|&c| c >= -tol))
}
}
/// Linear interpolation on the Delaunay triangulation of scattered points in `d ≥ 2`
/// dimensions: the value at `x` is the barycentric average of the values at the vertices of
/// the simplex containing `x`, and `fill_value` (NaN by default, as SciPy) outside the convex
/// hull.
#[derive(Clone, Debug)]
pub struct LinearNdInterpolator {
tri: DelaunayNd,
values: Vec<f64>,
fill_value: f64,
}
impl LinearNdInterpolator {
pub fn new(points: &[Vec<f64>], values: &[f64]) -> Result<LinearNdInterpolator, ErrorsJSL> {
if points.len() != values.len() {
return Err(ErrorsJSL::IncompatibleArraySizes((points.len(), values.len())));
}
Ok(LinearNdInterpolator { tri: DelaunayNd::new(points)?, values: values.to_vec(), fill_value: f64::NAN })
}
/// The value returned outside the convex hull of the data.
pub fn with_fill_value(mut self, fill_value: f64) -> Self {
self.fill_value = fill_value;
self
}
/// The triangulation used.
pub fn triangulation(&self) -> &DelaunayNd {
&self.tri
}
pub fn evaluate(&self, x: &[f64]) -> f64 {
match self.tri.find_simplex(x) {
None => self.fill_value,
Some(s) => self.tri.barycentric(s, x).iter().zip(&self.tri.simplices[s]).map(|(c, &i)| c * self.values[i]).sum(),
}
}
}
- Facets of the output are simplices (SciPy’s
Qtconvention), but the facets of the polytope are known: coplanar pieces are merged into one facet group (ConvexHullNd::facet_groups, the indices of the simplices that triangulate each polytope facet; a cube’s face is one group of two triangles), and each group is triangulated by the same pulling rule as the Delaunay cells, from the facet’s boundary. The triangulation therefore depends only on the points: not on their order, nor on whether the hull was grown byadd_points, and none of its simplices is flat. The number of facets (distinct hyperplanes) is SciPy’s: 6, 8, 10 and 12 for the cubes of dimension 3 to 6, and for lattices and a cube’s surface and edges. The number of simplices is SciPy’s wherever the triangulation of a facet is forced, which is in 3-D and for sets in general position. A hull’s vertices that are not extreme (points on an edge or face) are dropped, after which the hull is rebuilt on the extreme points. - Qhull’s own triangulation of a merged facet in four or more dimensions cannot be reproduced. Its output has flat simplices (zero volume) and depends on its internal vertex numbering: the eight cubic cells of the 4-cube come out as 9, 9, 8, 8, 6, 6, 6, 6 tetrahedra, of which 3, 3, 2, 2, 0, 0, 0, 0 have zero volume (58 simplices in all, against 48 here), and the whole 5-cube has 316 against 240. The same holds for Delaunay cells: the 4-cube is 22 simplices in SciPy (some cubic cells in 5 tetrahedra, some in 6) and 24 here, and the diagonals of a grid alternate in SciPy in a pattern that depends on the grid’s size (the cell at the corner has the opposite diagonal on a 3 × 3 grid and on a 4 × 4 grid). Both triangulations are valid and cover the same polytope.
VoronoiNd::new_furthest_siteis the dual of the furthest-site triangulation: its vertices are the circumcentres of the furthest-site simplices, only the vertices of the convex hull have regions, and every region is unbounded (checked againstVoronoi(furthest_site=True): the same vertices, ridges and non-empty regions).QhullOptions::parse("QJ1e-9 E1e-12")takes the part of Qhull’s option string that this implementation can honour:QJ[n]joggles the input by up to times its extent, which makes degenerate input simplicial (a flat point set gives a sliver hull, not an error), andE<n>sets the tolerance for points on a facet.Qt,Qbb,Qz,Qc,PpandQxare accepted because they are always on or without effect here; anything else is an error, so that no option is silently ignored.ConvexHullNd::with_options,DelaunayNd::with_optionsandVoronoiNd::with_optionstake them.ConvexHullNd::verticesis sorted; SciPy’s is sorted in 3-D and above and counter-clockwise in 2-D.- In three or more dimensions
VoronoiNdleaves out ridges from Delaunay edges that belong to a single simplex. Such a ridge has one finite vertex, and Qhull omits it. - The routines are written for clarity in dense arithmetic; Qhull is faster on large sets.
In practice
The references are from SciPy 1.17.1 (Qhull 2020.2), written by book/generator/data/make_geo217_refs.py:
Table 24.10. Hulls, triangulations, Voronoi diagrams, half-space intersections and scattered-data interpolation against SciPy.
| Function and data | Library against SciPy (Qhull) |
|---|---|
ConvexHullNd, 200 normal points in 2-D | volume 2e-16, area 2e-16; 11 facets vs 11; vertices identical |
ConvexHullNd, 200 normal points in 3-D | volume 0, area 0; 38 facets vs 38; vertices identical |
ConvexHullNd, 150 normal points in 4-D | volume 4e-16, area 4e-16; 194 facets vs 194; vertices identical |
ConvexHullNd, 120 normal points in 5-D | volume 5e-16, area 2e-15; 786 facets vs 786; vertices identical |
ConvexHullNd, 80 normal points in 6-D | volume 8e-16, area 4e-16; 2257 facets vs 2257; vertices identical |
DelaunayNd, 60 uniform points in 2-D | 108 simplices vs 108, identical; find_simplex agrees for 20 of 20 points |
DelaunayNd, 50 uniform points in 3-D | 216 simplices vs 216, identical; find_simplex agrees for 20 of 20 points |
DelaunayNd, 40 uniform points in 4-D | 403 simplices vs 403, identical; find_simplex agrees for 20 of 20 points |
VoronoiNd, 40 uniform points in 2-D | 70 vertices vs 70, matched to 4e-15; ridges identical |
VoronoiNd, 30 uniform points in 3-D | 105 vertices vs 105, matched to 2e-13; ridges identical |
HalfspaceIntersection, 30 tangent planes of the unit sphere and 5 redundant ones (3-D) | 56 vertices vs 56, matched to 2e-15; non-redundant half-spaces identical |
SphericalVoronoi, 60 random points on the unit sphere | 116 vertices vs 116, matched to 8e-16; region areas 3e-15 |
LinearNdInterpolator, 80 points in 3-D, 100 queries | 4e-16; outside the hull (NaN) at the same queries |
LinearNdInterpolator, 80 points in 4-D, 100 queries | 4e-16; outside the hull (NaN) at the same queries |
Every combinatorial result agrees with Qhull’s: hull facets in two to six dimensions, Delaunay simplices, Voronoi ridges and non-redundant half-spaces. Every computed coordinate agrees to rounding.
The furthest-site triangulation, against Delaunay(furthest_site=True) on random points:
Table 24.11. Columns: Points, Simplices, library / SciPy, Sets of simplices.
| Points | Simplices, library / SciPy | Sets of simplices |
|---|---|---|
| 25 random points in 2-D | 10 / 10 | identical |
| 18 random points in 3-D | 19 / 19 | identical |
The properties that define it hold as well: every circumsphere contains all the points, and the simplices tile the hull (checked for 2-D and 3-D random sets in the library’s tests).
Figure 24.16. Twelve random half-planes around the origin and their intersection. Six of them bound the polygon, and the other six are redundant: their dual points fall inside the dual hull.
Strengths
- One algorithm serves hulls, triangulations, Voronoi diagrams and half-spaces in any dimension.
- The same combinatorial results as Qhull on points in general position, and a valid triangulation of degenerate sets.
- Point location and barycentric coordinates make the triangulation directly usable for interpolation.
Weaknesses
- The size of hulls and triangulations grows like in the worst case, which limits practical use to about eight dimensions.
- Floating-point predicates with a tolerance, not exact arithmetic: points that are nearly but not exactly on a face are judged by the tolerance, and at the noise level (1e-13 for unit coordinates) the vertex set may differ by a point from Qhull’s.
ConvexHullNd::add_pointsgrows the hull in place, as Quickhull does (only the new points outside the hull are added, each replacing the facets it sees);DelaunayNd::add_pointsdoes the same on the lifted hull: the new points are lifted in the frame fixed at construction (the box and the joggle sequence), so the old lifted points do not move, and only the facets a new point sees are replaced. In general position the simplices are those of a fresh triangulation (tested in 2, 3 and 4 dimensions, also for single points and for the furthest-site variant); for cospherical sets the result is one of the valid triangulations, which may differ from a fresh one’s. Adding 50 points to 4000 in the plane took 19 ms against 106 ms for a fresh triangulation, and 30 ms against 149 ms for 50 to 1500 points in 3-D; what remains is rebuilding the simplex lists and barycentric transforms from the live facets.
Exercises
- Show that a point lies inside the circumsphere of a simplex exactly when its lift lies below the hyperplane through the simplex’s lifted vertices.
- Why does the dual of a redundant half-space fall inside the convex hull of the other dual points?
- A Delaunay triangulation of points in the plane with of them on the hull has how many triangles?
- Why is the convex hull of points on a sphere their spherical Delaunay triangulation?
Hints and answers
- Subtract the hyperplane’s equation from : the difference is .
- Its constraint is implied by the others, so moving its dual point onto their hull would not change the polytope; it can only be strictly inside.
- , from Euler’s formula.
- A facet’s plane cuts the sphere in a small circle, and all other points lie on the far side of the plane, which is outside the circle on the sphere.
Further reading
- C. B. Barber, D. P. Dobkin and H. Huhdanpaa, “The Quickhull algorithm for convex hulls”, ACM Transactions on Mathematical Software 22 (1996) 469–483.
- K. Q. Brown, “Voronoi diagrams from convex hulls”, Information Processing Letters 9 (1979) 223–228.
- H. Edelsbrunner and R. Seidel, “Voronoi diagrams and arrangements”, Discrete & Computational Geometry 1 (1986) 25–44.
- R. J. Renka, “Algorithm 772: STRIPACK: Delaunay triangulation and Voronoi diagram on the surface of a sphere”, ACM Transactions on Mathematical Software 23 (1997) 416–434.
- M. de Berg, O. Cheong, M. van Kreveld and M. Overmars, Computational Geometry: Algorithms and Applications, 3rd ed., Springer, 2008.