Skip to content

Commit 1f77f1b

Browse files
committed
fix: scale-aware degeneracy filter and orphan-free insertion in 2D+
Two deliberate behavior divergences from the Python reference, in regimes where the reference corrupts its own state. Cross-validation on well-conditioned inputs is unaffected (all parity tests still pass). - simplex_is_numerically_degenerate: drop a Bowyer-Watson candidate only when its volume is negligible BOTH absolutely (the reference's criterion, which keeps volume conservation safe) AND as scale-invariant flatness. The absolute test alone silently emptied finely refined or small-coordinate meshes (inserting into a [0, 1e-4]^2 mesh deleted every simplex and orphaned all vertices); the flatness test alone (briefly used here for 1D) deletes large-but-flat simplices the cavity needs. The conjunction also subsumes the previous 1D special case. - bowyer_watson now collects the cavity without mutating, and rejects the insertion as 'Point already in triangulation.' when it would strand a cavity vertex (a point within the circumcircle slack of every simplex around an existing vertex - previously this silently orphaned the vertex). add_point rolls back the pushed vertex/hull extension on these pre-mutation rejections. - New regression tests for both, plus a parametrized 2D/3D off-origin small-scale insertion sweep (the class of test whose absence hid the PR #3 bugs). Known limitation, now documented in tolerances.rs: point sets mixing widely separated coordinate scales in one triangulation create ~1e7 aspect-ratio slivers whose circumsphere tests are unreliable; the volume conservation assertion catches this loudly. The Python reference fails the same stress more often (41/50 runs vs 33/50 here); a real fix needs exact geometric predicates.
1 parent eea84c6 commit 1f77f1b

3 files changed

Lines changed: 212 additions & 27 deletions

File tree

‎src/tolerances.rs‎

Lines changed: 31 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,21 @@
1111
//! (silently assumes coordinates of order 1). Mixing the two up is how small
1212
//! simplices far from the origin get misclassified — see the regression tests
1313
//! added for exactly that failure in PR #3.
14+
//!
15+
//! # Known limitation
16+
//!
17+
//! Point sets that mix widely separated coordinate scales in one
18+
//! triangulation (e.g. a unit-sized cloud plus a 1e-5-sized cluster 100
19+
//! away) force sliver simplices with aspect ratios around 1e7 into the mesh.
20+
//! Floating-point circumsphere tests on such slivers are unreliable, and the
21+
//! Bowyer-Watson cascade can then assemble an inconsistent cavity; this is
22+
//! caught loudly by the volume-conservation assertion rather than corrupting
23+
//! state silently. The Python reference fails the same way (more often, in
24+
//! fact). Fixing it would require exact geometric predicates, i.e.
25+
//! adaptive-precision orientation/insphere tests, which is out of scope for
26+
//! a tolerance constant. Homogeneous-scale inputs — at any magnitude and any
27+
//! offset from the origin — are unaffected; see
28+
//! `test_random_insertions_small_scale_far_from_origin`.
1429
1530
/// Relative slack on barycentric coordinates when deciding whether a point
1631
/// lies inside a simplex, on one of its faces, or coincides with a vertex.
@@ -27,17 +42,25 @@ pub const BARYCENTRIC_EPS: f64 = 1e-8;
2742
/// Scale-invariant, but note it is *proportional to the neighbouring
2843
/// simplex's size*, not the inserted point's distance to it — a point can be
2944
/// within this slack of a large neighbour while being a meaningful fraction
30-
/// of a small simplex away from it. This is why 1D insertion skips the
31-
/// circumcircle cascade entirely (see `Triangulation::bowyer_watson`).
45+
/// of a small simplex away from it. Two guards in
46+
/// `Triangulation::bowyer_watson` keep that asymmetry from corrupting the
47+
/// triangulation: 1D insertion skips the circumcircle cascade entirely, and
48+
/// in higher dimensions an insertion that would strand a cavity vertex is
49+
/// rejected as a duplicate before anything is mutated.
3250
pub const CIRCUMCIRCLE_RTOL: f64 = 1e-8;
3351

34-
/// Absolute volume below which a candidate simplex is discarded as
35-
/// degenerate during Bowyer-Watson re-triangulation (dim >= 2).
52+
/// Threshold below which a candidate simplex is discarded as numerically
53+
/// degenerate during Bowyer-Watson re-triangulation. A candidate is dropped
54+
/// only when BOTH its raw volume (absolute; guarantees the omission cannot
55+
/// leave a material hole) and its normalized volume (volume divided by
56+
/// characteristic length to the dim-th power, i.e. scale-invariant
57+
/// *flatness*) fall below this constant.
3658
///
37-
/// NOT scale-invariant: this assumes coordinates of order 1, matching the
38-
/// Python reference. In 1D, where adaptive sampling routinely produces
39-
/// intervals far below this threshold, a normalized (scale-invariant) volume
40-
/// is used instead — see `Triangulation::simplex_is_numerically_degenerate`.
59+
/// The flatness condition is a deliberate divergence from the Python
60+
/// reference, which uses the absolute test alone and therefore silently
61+
/// deletes well-shaped simplices once a mesh is refined below ~1e-8 volume
62+
/// (in 2D that is edge lengths of ~1e-4) — emptying whole regions of the
63+
/// triangulation. See `Triangulation::simplex_is_numerically_degenerate`.
4164
pub const DEGENERATE_VOLUME_EPS: f64 = 1e-8;
4265

4366
/// Absolute and relative tolerances of the volume-conservation check after

‎src/triangulation.rs‎

Lines changed: 117 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -968,6 +968,8 @@ impl Triangulation {
968968
/// circumsphere contains it (cascading through facet neighbours, except
969969
/// in 1D) and fill the resulting hole with simplices through the vertex.
970970
/// Returns `(deleted, created)` and verifies total volume is conserved.
971+
/// Errors without mutating anything when the insertion would strand a
972+
/// cavity vertex, i.e. the point is numerically a duplicate of it.
971973
pub fn bowyer_watson(
972974
&mut self,
973975
pt_index: usize,
@@ -980,10 +982,12 @@ impl Triangulation {
980982
self.validate_simplex_indices(simplex)?;
981983
}
982984

985+
// Collect the cavity (every simplex whose circumsphere contains the
986+
// point, cascading through facet neighbours) without mutating, so
987+
// that pathological insertions can still be rejected cleanly below.
983988
let mut queue = VecDeque::new();
984989
let mut queued = FxHashSet::default();
985-
let mut done_simplices = FxHashSet::default();
986-
let mut bad_triangles = FxHashSet::default();
990+
let mut bad_triangles: FxHashSet<Simplex> = FxHashSet::default();
987991

988992
if let Some(simplex) = containing_simplex {
989993
queued.insert(simplex.clone());
@@ -997,23 +1001,16 @@ impl Triangulation {
9971001
}
9981002

9991003
while let Some(simplex) = queue.pop_front() {
1000-
if !done_simplices.insert(simplex.clone()) {
1001-
continue;
1002-
}
10031004
if !self.simplices.contains(&simplex) {
10041005
continue;
10051006
}
10061007

10071008
if self.point_in_circumcircle(pt_index, &simplex, transform)? {
1008-
self.delete_simplex(&simplex)?;
10091009
bad_triangles.insert(simplex.clone());
10101010

10111011
if self.dim == 1 {
10121012
// Inserting a point into an interval never invalidates
10131013
// neighbouring intervals, so there is no cascade in 1D.
1014-
// Cascading on the (1 + eps) circumcircle tolerance can
1015-
// delete a neighbour the point is strictly outside of,
1016-
// orphaning the shared vertex.
10171014
continue;
10181015
}
10191016

@@ -1024,9 +1021,6 @@ impl Triangulation {
10241021
}
10251022

10261023
for neighbour in neighbours {
1027-
if done_simplices.contains(&neighbour) {
1028-
continue;
1029-
}
10301024
let shared = neighbour
10311025
.iter()
10321026
.filter(|vertex| simplex_vertices.contains(vertex))
@@ -1044,6 +1038,7 @@ impl Triangulation {
10441038
.filter_map(|(face, count)| (count == 1).then_some(face))
10451039
.collect();
10461040

1041+
let mut candidates: Vec<Simplex> = Vec::new();
10471042
for face in hole_faces {
10481043
if face.contains(&pt_index) {
10491044
continue;
@@ -1055,6 +1050,33 @@ impl Triangulation {
10551050
if self.simplex_is_numerically_degenerate(&simplex)? {
10561051
continue;
10571052
}
1053+
candidates.push(simplex);
1054+
}
1055+
1056+
// A cavity vertex that would lose all of its simplices without
1057+
// being reconnected means the point is numerically indistinguishable
1058+
// from that vertex (it sits within the circumcircle slack of every
1059+
// simplex around it). Reject the insertion before mutating anything
1060+
// rather than orphaning the vertex and corrupting the triangulation.
1061+
let candidate_vertices: FxHashSet<usize> = candidates.iter().flatten().copied().collect();
1062+
for &vertex in bad_triangles.iter().flatten() {
1063+
if vertex == pt_index || candidate_vertices.contains(&vertex) {
1064+
continue;
1065+
}
1066+
if self.vertex_to_simplices[vertex]
1067+
.iter()
1068+
.all(|simplex| bad_triangles.contains(simplex))
1069+
{
1070+
return Err(TriangulationError::Value(
1071+
"Point already in triangulation.".to_string(),
1072+
));
1073+
}
1074+
}
1075+
1076+
for simplex in &bad_triangles {
1077+
self.delete_simplex(simplex)?;
1078+
}
1079+
for simplex in candidates {
10581080
self.add_simplex(simplex)?;
10591081
}
10601082

@@ -1171,7 +1193,20 @@ impl Triangulation {
11711193
}
11721194
};
11731195
let (deleted_simplices, added_simplices) =
1174-
self.bowyer_watson(pt_index, None, &transform)?;
1196+
match self.bowyer_watson(pt_index, None, &transform) {
1197+
Ok(result) => result,
1198+
// Value errors are raised before bowyer_watson mutates,
1199+
// so only the hull extension needs rolling back.
1200+
Err(err @ TriangulationError::Value(_)) => {
1201+
for simplex in self.vertex_to_simplices[pt_index].clone() {
1202+
self.delete_simplex(&simplex)?;
1203+
}
1204+
self.vertex_to_simplices.pop();
1205+
self.vertices.pop();
1206+
return Err(err);
1207+
}
1208+
Err(err) => return Err(err),
1209+
};
11751210

11761211
let deleted: FxHashSet<Simplex> = deleted_simplices
11771212
.difference(&temporary_simplices)
@@ -1202,7 +1237,16 @@ impl Triangulation {
12021237

12031238
let pt_index = self.vertices.len();
12041239
self.vertices.push(point);
1205-
self.bowyer_watson(pt_index, Some(actual_simplex), &transform)
1240+
match self.bowyer_watson(pt_index, Some(actual_simplex), &transform) {
1241+
// Value errors are raised before bowyer_watson mutates, so only
1242+
// the freshly pushed vertex needs rolling back.
1243+
Err(err @ TriangulationError::Value(_)) => {
1244+
self.vertex_to_simplices.pop();
1245+
self.vertices.pop();
1246+
Err(err)
1247+
}
1248+
other => other,
1249+
}
12061250
}
12071251

12081252
/// Volume of the simplex with the given vertex indices.
@@ -1237,11 +1281,16 @@ impl Triangulation {
12371281
&self,
12381282
simplex: &[usize],
12391283
) -> Result<bool, TriangulationError> {
1240-
if self.dim == 1 {
1241-
// In 1D we only want to reject coincident endpoints, not tiny but valid intervals.
1242-
return Ok(self.normalized_volume(simplex)? < DEGENERATE_VOLUME_EPS);
1243-
}
1244-
Ok(self.volume(simplex)? < DEGENERATE_VOLUME_EPS)
1284+
// Drop a candidate only when its volume is negligible in BOTH
1285+
// senses: absolutely tiny, so removing it cannot leave a material
1286+
// hole (this is the Python reference's criterion), AND flat relative
1287+
// to its own extent. Either test alone is wrong in some regime: the
1288+
// absolute cutoff alone empties finely refined or small-coordinate
1289+
// meshes whose well-shaped simplices all sit below it, while the
1290+
// flatness cutoff alone deletes large-but-flat simplices whose
1291+
// volume the cavity genuinely needs (breaking volume conservation).
1292+
Ok(self.volume(simplex)? < DEGENERATE_VOLUME_EPS
1293+
&& self.normalized_volume(simplex)? < DEGENERATE_VOLUME_EPS)
12451294
}
12461295

12471296
/// Whether the (order-insensitive) simplex is present.
@@ -1948,6 +1997,55 @@ mod tests {
19481997
assert_eq!(added, FxHashSet::from_iter([vec![1, 2]]));
19491998
}
19501999

2000+
#[test]
2001+
fn two_dimensional_small_scale_insertion_keeps_mesh() {
2002+
// Regression: the absolute degenerate-volume cutoff dropped every
2003+
// candidate simplex below 1e-8 volume, emptying the mesh.
2004+
let mut tri = Triangulation::from_simplices(
2005+
vec![
2006+
vec![0.0, 0.0],
2007+
vec![1e-4, 0.0],
2008+
vec![0.0, 1e-4],
2009+
vec![1e-4, 1e-4],
2010+
],
2011+
vec![vec![0, 1, 3], vec![0, 2, 3]],
2012+
)
2013+
.unwrap();
2014+
2015+
let (deleted, added) = tri.add_point(vec![5e-5, 6e-5], None, None).unwrap();
2016+
2017+
assert_eq!(deleted.len(), 2);
2018+
assert_eq!(added.len(), 4);
2019+
assert_eq!(tri.simplices.len(), 4);
2020+
assert!((0..tri.vertices.len()).all(|v| !tri.vertex_to_simplices[v].is_empty()));
2021+
}
2022+
2023+
#[test]
2024+
fn two_dimensional_near_duplicate_insertion_is_rejected_without_mutation() {
2025+
// Regression: a point within the circumcircle slack of every simplex
2026+
// around an existing vertex orphaned that vertex.
2027+
let mut tri = Triangulation::new(vec![
2028+
vec![0.0, 0.0],
2029+
vec![1.0, 0.0],
2030+
vec![0.5, 1.0],
2031+
vec![0.5, 0.5],
2032+
vec![0.5 + 1e-6, 0.5],
2033+
vec![0.5, 0.5 + 1e-6],
2034+
])
2035+
.unwrap();
2036+
let simplices_before = tri.simplices.clone();
2037+
let n_vertices_before = tri.vertices.len();
2038+
2039+
let err = tri
2040+
.add_point(vec![0.5 + 2e-10, 0.5 + 2e-10], None, None)
2041+
.unwrap_err();
2042+
2043+
assert!(matches!(err, TriangulationError::Value(_)));
2044+
assert_eq!(tri.simplices, simplices_before);
2045+
assert_eq!(tri.vertices.len(), n_vertices_before);
2046+
assert!(tri.reference_invariant());
2047+
}
2048+
19512049
#[test]
19522050
fn one_dimensional_insertion_near_shared_vertex_keeps_vertex_connected() {
19532051
// Regression: the circumcircle cascade deleted the long neighbouring

‎tests/test_triangulation.py‎

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,70 @@ def test_add_point_in_tiny_interval_far_from_origin_1d():
277277
assert_1d_triangulation_state(tri)
278278

279279

280+
def all_vertices_connected(tri) -> bool:
281+
return all(len(tri.vertex_to_simplices[i]) > 0 for i in range(len(tri.vertices)))
282+
283+
284+
def test_add_point_in_small_scale_mesh_2d_keeps_all_simplices():
285+
# Regression: the absolute degenerate-volume cutoff (matching the Python
286+
# reference) deleted every candidate simplex below 1e-8 volume, silently
287+
# emptying the mesh on insertion into a finely refined region.
288+
tri = rust_tri.Triangulation([[0, 0], [1e-4, 0], [0, 1e-4], [1e-4, 1e-4]])
289+
290+
deleted, added = tri.add_point([5e-5, 6e-5])
291+
292+
assert len(deleted) == 2
293+
assert len(added) == 4
294+
assert len(tri.simplices) == 4
295+
assert all_vertices_connected(tri)
296+
assert tri.reference_invariant()
297+
298+
299+
def test_near_duplicate_insertion_2d_is_rejected_not_orphaned():
300+
# Regression: a point within the circumcircle slack of every simplex
301+
# around an existing vertex deleted them all and orphaned that vertex.
302+
# It must instead be rejected as a duplicate, leaving the state intact.
303+
pts = [
304+
[0.0, 0.0],
305+
[1.0, 0.0],
306+
[0.5, 1.0],
307+
[0.5, 0.5],
308+
[0.5 + 1e-6, 0.5],
309+
[0.5, 0.5 + 1e-6],
310+
]
311+
tri = rust_tri.Triangulation(pts)
312+
before = as_simplex_set(tri.simplices)
313+
314+
with pytest.raises(ValueError, match="Point already in triangulation"):
315+
tri.add_point([0.5 + 2e-10, 0.5 + 2e-10])
316+
317+
assert as_simplex_set(tri.simplices) == before
318+
assert len(tri.vertices) == len(pts)
319+
assert all_vertices_connected(tri)
320+
assert tri.reference_invariant()
321+
322+
323+
@pytest.mark.parametrize("dim", [2, 3])
324+
@pytest.mark.parametrize(
325+
("offset", "scale"),
326+
[(100.0, 1e-5), (-1e6, 1e-2), (0.5, 1e-6)],
327+
ids=["near-100", "near-minus-1e6", "near-half"],
328+
)
329+
def test_random_insertions_small_scale_far_from_origin(dim, offset, scale):
330+
rng = np.random.default_rng(7)
331+
pts = offset + scale * rng.random((30, dim))
332+
tri = rust_tri.Triangulation(pts[: dim + 2].tolist())
333+
334+
for p in pts[dim + 2 :]:
335+
tri.add_point(p.tolist())
336+
337+
assert all_vertices_connected(tri)
338+
assert tri.reference_invariant()
339+
assert all(v > 0 for v in tri.volumes())
340+
interior = pts.mean(axis=0)
341+
assert len(tri.locate_point(interior.tolist())) == dim + 1
342+
343+
280344
def test_add_point_near_shared_vertex_keeps_vertex_connected_1d():
281345
# Regression: the circumcircle cascade also deleted the long neighbouring
282346
# interval the point is strictly outside of, orphaning the shared vertex.

0 commit comments

Comments
 (0)