Skip to content

Commit 4fe925d

Browse files
authored
Return 0.0 for degenerate input in simplex_volume_in_embedding (#15)
The reference implementation treats a Cayley-Menger squared volume within rounding noise of zero (> -1e-15) as a degenerate input with volume 0.0 and only raises below that; this implementation raised for anything <= 0. adaptive's curvature losses feed collinear/coplanar vertices whenever the sampled function is locally flat, so with adaptive >= 1.5 auto-selecting this backend, LearnerND runs with curvature_loss_function crashed where the pure-Python backend returned a zero loss (7 known test failures noted in adaptive#493). - the general Cayley-Menger path now returns 0.0 in the reference's (-EMBEDDED_VOLUME_SQ_EPS, 0] band and raises only below it - 3 vertices in a >2D embedding use the Cayley-Menger form expanded in squared distances instead of root-based Heron, so rounding near zero behaves like the reference's numeric determinant and the same band applies; in 2D the reference's Heron path (which raises on any negative product) is mirrored unchanged - 2 coincident vertices in a >2D embedding are a zero-length segment, like the reference's Cayley-Menger path (2D keeps raising, as the reference does for any 2-vertex input) With this fix the full adaptive 1.5.0 test suite passes with the Rust backend active (283 passed; previously 7 curvature-loss failures plus test_learnernd_with_neighbor_aware_loss_runs in this repo), clearing the way for adaptive to bump _MIN_RUST_VERSION and add a Rust-backend CI job.
1 parent a8a02a4 commit 4fe925d

3 files changed

Lines changed: 138 additions & 13 deletions

File tree

‎src/geometry.rs‎

Lines changed: 86 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
use nalgebra::{DMatrix, DVector};
99
use thiserror::Error;
1010

11-
use crate::tolerances::ORIENTATION_LOG_DET_CUTOFF;
11+
use crate::tolerances::{EMBEDDED_VOLUME_SQ_EPS, ORIENTATION_LOG_DET_CUTOFF};
1212

1313
/// Errors produced by the geometric primitives.
1414
#[derive(Debug, Error)]
@@ -622,24 +622,55 @@ pub fn simplex_volume_in_embedding(vertices: &[Vec<f64>]) -> Result<f64, Geometr
622622
));
623623
}
624624

625+
// Degenerate inputs (collinear/coplanar/coincident vertices) have volume
626+
// 0.0, like the reference: adaptive's loss functions feed those routinely
627+
// (e.g. curvature losses on a locally flat function) and expect a zero
628+
// loss back. Only inputs whose squared volume is more negative than
629+
// rounding noise (`EMBEDDED_VOLUME_SQ_EPS`) are an error, plus the cases
630+
// where the reference's 2D Heron path raises.
631+
let dim = vertices[0].len();
632+
625633
if vertices.len() == 2 {
626634
let length_sq = squared_distance(&vertices[0], &vertices[1]);
627-
if length_sq == 0.0 {
635+
if length_sq == 0.0 && dim == 2 {
636+
// The reference's 2D path raises for anything but 3 vertices; in
637+
// higher embeddings its Cayley-Menger path returns 0.0.
628638
return Err(GeometryError::DegenerateSimplex);
629639
}
630640
return Ok(length_sq.sqrt());
631641
}
632642

633643
if vertices.len() == 3 {
634-
let a = squared_distance(&vertices[0], &vertices[1]).sqrt();
635-
let b = squared_distance(&vertices[1], &vertices[2]).sqrt();
636-
let c = squared_distance(&vertices[2], &vertices[0]).sqrt();
637-
let s = 0.5 * (a + b + c);
638-
let area_sq = s * (s - a) * (s - b) * (s - c);
639-
if area_sq <= 0.0 {
644+
let d01 = squared_distance(&vertices[0], &vertices[1]);
645+
let d12 = squared_distance(&vertices[1], &vertices[2]);
646+
let d02 = squared_distance(&vertices[2], &vertices[0]);
647+
648+
if dim == 2 {
649+
// The reference uses Heron's formula with explicit square roots
650+
// in 2D; its sqrt raises for any negative product
651+
// (`math domain error`), so no tolerance band here.
652+
let (a, b, c) = (d01.sqrt(), d12.sqrt(), d02.sqrt());
653+
let s = 0.5 * (a + b + c);
654+
let area_sq = s * (s - a) * (s - b) * (s - c);
655+
if area_sq >= 0.0 {
656+
return Ok(area_sq.sqrt());
657+
}
640658
return Err(GeometryError::DegenerateSimplex);
641659
}
642-
return Ok(area_sq.sqrt());
660+
661+
// Cayley-Menger determinant for three vertices, expanded in squared
662+
// distances (16·area² = 2(d01·d12 + d12·d02 + d02·d01) − d01² − d12²
663+
// − d02²), so its rounding near zero behaves like the reference's
664+
// numeric determinant and the same tolerance band applies.
665+
let area_sq =
666+
(2.0 * (d01 * d12 + d12 * d02 + d02 * d01) - d01 * d01 - d12 * d12 - d02 * d02) / 16.0;
667+
if area_sq >= 0.0 {
668+
return Ok(area_sq.sqrt());
669+
}
670+
if area_sq > -EMBEDDED_VOLUME_SQ_EPS {
671+
return Ok(0.0);
672+
}
673+
return Err(GeometryError::DegenerateSimplex);
643674
}
644675

645676
let n = vertices.len();
@@ -660,10 +691,13 @@ pub fn simplex_volume_in_embedding(vertices: &[Vec<f64>]) -> Result<f64, Geometr
660691

661692
let coeff = -(-2.0f64).powi((n - 1) as i32) * factorial(n - 1).powi(2);
662693
let vol_square = determinant(&matrix)? / coeff;
663-
if vol_square <= 0.0 {
664-
return Err(GeometryError::DegenerateSimplex);
694+
if vol_square >= 0.0 {
695+
return Ok(vol_square.sqrt());
696+
}
697+
if vol_square > -EMBEDDED_VOLUME_SQ_EPS {
698+
return Ok(0.0);
665699
}
666-
Ok(vol_square.sqrt())
700+
Err(GeometryError::DegenerateSimplex)
667701
}
668702

669703
/// The loss adaptive's `LearnerND` assigns to a simplex by default: the
@@ -691,11 +725,50 @@ mod tests {
691725
}
692726

693727
#[test]
694-
fn simplex_volume_in_embedding_rejects_identical_endpoints() {
728+
fn simplex_volume_in_embedding_rejects_identical_endpoints_in_2d() {
695729
let err = simplex_volume_in_embedding(&[vec![1.0, 2.0], vec![1.0, 2.0]]).unwrap_err();
696730
assert!(matches!(err, GeometryError::DegenerateSimplex));
697731
}
698732

733+
#[test]
734+
fn simplex_volume_in_embedding_identical_endpoints_in_3d_is_zero() {
735+
let volume =
736+
simplex_volume_in_embedding(&[vec![1.0, 2.0, 3.0], vec![1.0, 2.0, 3.0]]).unwrap();
737+
assert_eq!(volume, 0.0);
738+
}
739+
740+
#[test]
741+
fn simplex_volume_in_embedding_collinear_triangle_in_3d_is_zero() {
742+
let volume = simplex_volume_in_embedding(&[
743+
vec![0.0, 0.0, 0.0],
744+
vec![1.0, 1.0, 1.0],
745+
vec![2.0, 2.0, 2.0],
746+
])
747+
.unwrap();
748+
assert_eq!(volume, 0.0);
749+
}
750+
751+
#[test]
752+
fn simplex_volume_in_embedding_collinear_triangle_in_2d_is_zero() {
753+
// Heron's formula gives exactly 0 here (s - c == 0), like the
754+
// reference's sqrt(0); only negative products are an error in 2D.
755+
let volume =
756+
simplex_volume_in_embedding(&[vec![0.0, 0.0], vec![1.0, 1.0], vec![2.0, 2.0]]).unwrap();
757+
assert_eq!(volume, 0.0);
758+
}
759+
760+
#[test]
761+
fn simplex_volume_in_embedding_coplanar_tetrahedron_is_zero() {
762+
let volume = simplex_volume_in_embedding(&[
763+
vec![0.0, 0.0, 0.0],
764+
vec![1.0, 0.0, 0.0],
765+
vec![0.0, 1.0, 0.0],
766+
vec![1.0, 1.0, 0.0],
767+
])
768+
.unwrap();
769+
assert_eq!(volume, 0.0);
770+
}
771+
699772
#[test]
700773
fn circumsphere_supports_one_dimensional_segment() {
701774
let (center, radius) = circumsphere(&[vec![0.0], vec![2.0]]).unwrap();

‎src/tolerances.rs‎

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -95,3 +95,16 @@ pub const VOLUME_CONSERVATION_RTOL: f64 = 1e-5;
9595
/// face's edge lengths, so faces with edges below ~`exp(-50/dim)` are always
9696
/// reported as degenerate. Matches the Python reference.
9797
pub const ORIENTATION_LOG_DET_CUTOFF: f64 = -50.0;
98+
99+
/// Band of negative squared volumes that `simplex_volume_in_embedding`
100+
/// reports as exactly zero instead of an error: a squared volume in
101+
/// `(-EMBEDDED_VOLUME_SQ_EPS, 0.0)` is rounding noise from a degenerate
102+
/// (collinear/coplanar/coincident) input, which adaptive's loss functions
103+
/// feed it routinely and expect a 0.0 loss for. Anything more negative is
104+
/// a genuinely malformed input and stays an error.
105+
///
106+
/// NOT scale-invariant: the squared volume scales with the `2(n-1)`-th
107+
/// power of the edge lengths. Matches the Python reference, which returns
108+
/// 0.0 in exactly this band of its Cayley-Menger determinant and raises
109+
/// below it.
110+
pub const EMBEDDED_VOLUME_SQ_EPS: f64 = 1e-15;

‎tests/test_triangulation.py‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -777,6 +777,45 @@ def test_simplex_volume_in_embedding_returns_length_for_two_vertices():
777777
) == pytest.approx(1.0)
778778

779779

780+
def test_simplex_volume_in_embedding_degenerate_input_is_zero():
781+
# Degenerate inputs are zero-volume simplices, not errors, like the
782+
# reference Cayley-Menger path: adaptive's curvature losses feed
783+
# collinear/coplanar vertices whenever the function is locally flat.
784+
collinear_3d = [[0.0, 0.0, 0.0], [1.0, 1.0, 1.0], [2.0, 2.0, 2.0]]
785+
coplanar = [[0.0, 0.0, 0.0], [1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [1.0, 1.0, 0.0]]
786+
coincident_3d = [[1.0, 2.0, 3.0], [1.0, 2.0, 3.0]]
787+
collinear_2d = [[0.0, 0.0], [1.0, 1.0], [2.0, 2.0]]
788+
for vertices in (collinear_3d, coplanar, coincident_3d, collinear_2d):
789+
assert rust_tri.simplex_volume_in_embedding(vertices) == 0.0
790+
# The reference lands within determinant rounding of zero (it may
791+
# return sqrt of a tiny positive det rather than exactly 0.0).
792+
if vertices is not coincident_3d: # ref raises for 2 vertices
793+
ref = reference_module.simplex_volume_in_embedding(vertices)
794+
assert ref == pytest.approx(0.0, abs=1e-7)
795+
796+
797+
def test_simplex_volume_in_embedding_near_degenerate_matches_reference():
798+
# Random nearly-collinear triangles in a 3D embedding (what a curvature
799+
# loss produces near a flat region): both implementations must agree on
800+
# value-or-exception, with values equal to rounding noise.
801+
rng = np.random.default_rng(13)
802+
for _ in range(50):
803+
base = rng.random(3)
804+
direction = rng.random(3)
805+
ts = rng.random(3)
806+
wiggle = rng.normal(0.0, 1e-12, (3, 3))
807+
vertices = base + np.outer(ts, direction) + wiggle
808+
try:
809+
expected = reference_module.simplex_volume_in_embedding(vertices)
810+
except ValueError:
811+
with pytest.raises(ValueError, match="do not form a simplex"):
812+
rust_tri.simplex_volume_in_embedding(vertices)
813+
else:
814+
assert rust_tri.simplex_volume_in_embedding(vertices) == pytest.approx(
815+
expected, abs=1e-7
816+
)
817+
818+
780819
def test_orientation_matches_reference_at_large_scale():
781820
face = [
782821
[-1.41794610203929e-141, 7.406648259110687e188, -5.742753819358816e155],

0 commit comments

Comments
 (0)