delaunay 0.7.2

A d-dimensional Delaunay triangulation library with float coordinate support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
//! Semantic classification and telemetry for triangulation operations.
//!
//! This module is intentionally **not** about implementation mechanics. It defines:
//! - What operation occurred (taxonomy)
//! - What the outcome was
//! - Lightweight telemetry/flags describing suspicious paths
//!
//! The actual algorithms live under `core::algorithms`.

#![forbid(unsafe_code)]

use crate::core::algorithms::incremental_insertion::InsertionError;
use crate::core::delaunay_triangulation::{DelaunayCheckPolicy, DelaunayRepairPolicy};
use crate::core::triangulation::TopologyGuarantee;
use crate::core::triangulation_data_structure::CellKey;

/// Semantic classification of topological modifications to a triangulation.
///
/// These correspond to bistellar (Pachner) move classes, but are not required
/// to be implemented as single atomic flips.
///
/// # Examples
///
/// ```rust
/// use delaunay::core::operations::TopologicalOperation;
/// use delaunay::core::triangulation::TopologyGuarantee;
///
/// let op = TopologicalOperation::FacetFlip;
/// assert!(op.is_admissible_under(TopologyGuarantee::Pseudomanifold));
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq)]
pub enum TopologicalOperation {
    /// k = 1 forward: vertex insertion (1 → d+1).
    InsertVertex,
    /// k = 1 inverse: vertex deletion (d+1 → 1).
    DeleteVertex,
    /// k = 2: facet bistellar flip.
    FacetFlip,
    /// k ≥ 3: higher-order cavity flip (typically in higher dimensions).
    CavityFlip,
}

/// Decision outcome for a flip-based Delaunay repair attempt.
///
/// # Examples
///
/// ```rust
/// use delaunay::core::operations::{RepairDecision, RepairSkipReason, TopologicalOperation};
/// use delaunay::core::triangulation::TopologyGuarantee;
///
/// let decision = RepairDecision::Skip {
///     reason: RepairSkipReason::Inadmissible {
///         operation: TopologicalOperation::CavityFlip,
///         required: TopologyGuarantee::PLManifold,
///         found: TopologyGuarantee::Pseudomanifold,
///     },
/// };
/// assert!(matches!(decision, RepairDecision::Skip { .. }));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepairDecision {
    /// Proceed with flip-based repair.
    Proceed,
    /// Skip repair, with a structured reason.
    Skip {
        /// Reason the repair was skipped.
        reason: RepairSkipReason,
    },
}

/// Reason why flip-based repair was skipped.
///
/// # Examples
///
/// ```rust
/// use delaunay::core::operations::RepairSkipReason;
///
/// let reason = RepairSkipReason::PolicyDisabled;
/// assert!(matches!(reason, RepairSkipReason::PolicyDisabled));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RepairSkipReason {
    /// Repair policy is disabled for this insertion count.
    PolicyDisabled,
    /// The requested operation is inadmissible under the current topology guarantee.
    Inadmissible {
        /// The operation that was attempted.
        operation: TopologicalOperation,
        /// Required topology guarantee for this operation.
        required: TopologyGuarantee,
        /// Actual topology guarantee.
        found: TopologyGuarantee,
    },
}

impl DelaunayRepairPolicy {
    /// Decide whether a flip-based repair should run, given topology and operation constraints.
    #[must_use]
    pub const fn decide(
        self,
        insertion_count: usize,
        topology: TopologyGuarantee,
        operation: TopologicalOperation,
    ) -> RepairDecision {
        if !self.should_repair(insertion_count) {
            return RepairDecision::Skip {
                reason: RepairSkipReason::PolicyDisabled,
            };
        }

        if !operation.is_admissible_under(topology) {
            return RepairDecision::Skip {
                reason: RepairSkipReason::Inadmissible {
                    operation,
                    required: operation.required_topology(),
                    found: topology,
                },
            };
        }

        RepairDecision::Proceed
    }
}

impl TopologicalOperation {
    /// Returns `true` if this operation requires a PL-manifold topology guarantee.
    #[must_use]
    pub const fn requires_pl_manifold(self) -> bool {
        // Higher-order cavity flips rely on stronger local topology guarantees.
        //
        // Note: k=2/k=3 flips used for Delaunay repair are admissible under the weaker
        // pseudomanifold invariants (facet degree + closed boundary). Callers that need
        // strict PL-manifold guarantees should select `TopologyGuarantee::PLManifold`.
        matches!(self, Self::CavityFlip)
    }

    /// Returns `true` if this operation is admissible under the given topology guarantee.
    #[must_use]
    pub const fn is_admissible_under(self, topology: TopologyGuarantee) -> bool {
        match topology {
            TopologyGuarantee::PLManifold | TopologyGuarantee::PLManifoldStrict => true,
            TopologyGuarantee::Pseudomanifold => !self.requires_pl_manifold(),
        }
    }

    /// Returns the minimum topology guarantee required for this operation.
    #[must_use]
    pub const fn required_topology(self) -> TopologyGuarantee {
        if self.requires_pl_manifold() {
            TopologyGuarantee::PLManifold
        } else {
            TopologyGuarantee::Pseudomanifold
        }
    }
}

/// Result of an insertion attempt.
///
/// # Examples
///
/// ```rust
/// use delaunay::core::operations::InsertionResult;
///
/// let result = InsertionResult::default();
/// assert_eq!(result, InsertionResult::Inserted);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum InsertionResult {
    /// The vertex was successfully inserted.
    #[default]
    Inserted,
    /// The vertex was skipped due to duplicate coordinates.
    SkippedDuplicate,
    /// The vertex was skipped due to geometric degeneracy after retries.
    SkippedDegeneracy,
}

/// Statistics about a vertex insertion operation.
///
/// # Examples
///
/// ```rust
/// use delaunay::core::operations::{InsertionResult, InsertionStatistics};
///
/// let stats = InsertionStatistics {
///     attempts: 2,
///     cells_removed_during_repair: 1,
///     result: InsertionResult::Inserted,
/// };
/// assert!(stats.used_perturbation());
/// assert!(stats.success());
/// assert!(!stats.skipped());
/// ```
#[derive(Debug, Clone, Copy, Default)]
pub struct InsertionStatistics {
    /// Number of insertion attempts (1 = success on first try, >1 = needed perturbation)
    pub attempts: usize,
    /// Number of cells removed during repair
    pub cells_removed_during_repair: usize,
    /// Result of the insertion attempt
    pub result: InsertionResult,
}

impl InsertionStatistics {
    /// Returns true if perturbation was applied (attempts > 1).
    #[must_use]
    pub const fn used_perturbation(&self) -> bool {
        self.attempts > 1
    }

    /// Returns true if the insertion succeeded.
    #[must_use]
    pub const fn success(&self) -> bool {
        matches!(self.result, InsertionResult::Inserted)
    }

    /// Returns true if the vertex was skipped (any reason).
    #[must_use]
    pub const fn skipped(&self) -> bool {
        matches!(
            self.result,
            InsertionResult::SkippedDuplicate | InsertionResult::SkippedDegeneracy
        )
    }

    /// Returns true if the vertex was skipped due to duplicate coordinates.
    #[must_use]
    pub const fn skipped_duplicate(&self) -> bool {
        matches!(self.result, InsertionResult::SkippedDuplicate)
    }
}

/// Ephemeral insertion state used by Delaunay triangulations.
#[derive(Clone, Copy, Debug)]
pub(crate) struct DelaunayInsertionState {
    /// Hint for the next `locate()` call (last inserted cell).
    pub last_inserted_cell: Option<CellKey>,
    /// Policy controlling automatic Delaunay repair (flip-based).
    pub delaunay_repair_policy: DelaunayRepairPolicy,
    /// Policy controlling automatic global Delaunay validation (Level 4).
    pub delaunay_check_policy: DelaunayCheckPolicy,
    /// Count of successful insertions (used to schedule repairs/checks).
    pub delaunay_repair_insertion_count: usize,
    /// When `true` (default), D<4 per-insertion repair falls back to global
    /// `repair_delaunay_with_flips_k2_k3` when the bounded local pass cycles.
    /// Set to `false` for constructions where global repair could disrupt
    /// the triangulation topology (e.g. periodic image-point builds).
    pub use_global_repair_fallback: bool,
}

impl DelaunayInsertionState {
    /// Create a fresh insertion state with default repair policy.
    #[must_use]
    pub const fn new() -> Self {
        Self {
            last_inserted_cell: None,
            delaunay_repair_policy: DelaunayRepairPolicy::EveryInsertion,
            delaunay_check_policy: DelaunayCheckPolicy::EndOnly,
            delaunay_repair_insertion_count: 0,
            use_global_repair_fallback: true,
        }
    }
}

/// Outcome of a single-vertex insertion attempt.
///
/// This distinguishes between:
/// - A successful insertion (`Inserted`)
/// - An intentionally skipped insertion (`Skipped`) where the triangulation is left unchanged
///   for this vertex (transactional rollback). This can happen for example when:
///   - The input vertex is a duplicate/near-duplicate (skipped immediately)
///   - A retryable geometric degeneracy exhausts all perturbation attempts
///
/// Other non-recoverable structural failures are returned as `Err(InsertionError)` instead
/// (e.g. duplicate UUID).
///
/// # Examples
///
/// ```rust
/// use delaunay::core::algorithms::incremental_insertion::InsertionError;
/// use delaunay::core::operations::InsertionOutcome;
///
/// let outcome = InsertionOutcome::Skipped {
///     error: InsertionError::DuplicateCoordinates {
///         coordinates: "[0.0, 0.0, 0.0]".to_string(),
///     },
/// };
/// assert!(matches!(outcome, InsertionOutcome::Skipped { .. }));
/// ```
#[derive(Debug, Clone)]
pub enum InsertionOutcome {
    /// The vertex was inserted successfully.
    Inserted {
        /// Key of the inserted vertex.
        vertex_key: crate::core::triangulation_data_structure::VertexKey,
        /// Optional cell key that can be used as a hint for subsequent insertions.
        hint: Option<crate::core::triangulation_data_structure::CellKey>,
    },
    /// The vertex was intentionally not inserted.
    ///
    /// This covers both immediate skips (e.g. duplicate/near-duplicate coordinates) and skips
    /// after exhausting retry attempts for geometric degeneracies.
    ///
    /// The triangulation is left unchanged for this vertex (transactional rollback).
    Skipped {
        /// The reason the vertex was skipped.
        ///
        /// This may be non-retryable (e.g. [`InsertionError::DuplicateCoordinates`]) or, for
        /// retry-based skips, the last error encountered.
        error: InsertionError,
    },
}

/// Adaptive error-checking on suspicious operations.
///
/// # Examples
///
/// ```rust
/// use delaunay::core::operations::SuspicionFlags;
///
/// let flags = SuspicionFlags {
///     perturbation_used: true,
///     neighbor_pointers_rebuilt: true,
///     ..SuspicionFlags::default()
/// };
/// assert!(flags.perturbation_used);
/// assert!(flags.neighbor_pointers_rebuilt);
/// ```
#[derive(Clone, Copy, Debug, Default)]
#[expect(
    clippy::struct_excessive_bools,
    reason = "A small set of boolean flags is clearer here than bitflags or an enum"
)]
pub struct SuspicionFlags {
    /// A perturbation retry was required to resolve a geometric degeneracy.
    pub perturbation_used: bool,

    /// A conflict-region computation returned an empty set for an interior point.
    pub empty_conflict_region: bool,

    /// The insertion fell back to splitting the containing cell (star-split) to avoid
    /// creating a dangling vertex.
    pub fallback_star_split: bool,

    /// The non-manifold repair loop was entered after insertion/hull extension.
    pub repair_loop_entered: bool,

    /// One or more cells were removed during non-manifold repair.
    pub cells_removed: bool,

    /// Neighbor pointers were rebuilt (facet-matched) after topology repair.
    pub neighbor_pointers_rebuilt: bool,
}

impl SuspicionFlags {
    /// Returns `true` if any suspicious condition was observed.
    #[inline]
    #[must_use]
    pub const fn is_suspicious(&self) -> bool {
        self.perturbation_used
            || self.empty_conflict_region
            || self.fallback_star_split
            || self.repair_loop_entered
            || self.cells_removed
            || self.neighbor_pointers_rebuilt
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_topological_operation_admissibility() {
        assert!(!TopologicalOperation::FacetFlip.requires_pl_manifold());
        assert!(TopologicalOperation::CavityFlip.requires_pl_manifold());
        assert!(!TopologicalOperation::InsertVertex.requires_pl_manifold());
        assert!(!TopologicalOperation::DeleteVertex.requires_pl_manifold());

        assert!(TopologicalOperation::FacetFlip.is_admissible_under(TopologyGuarantee::PLManifold));
        assert!(
            TopologicalOperation::FacetFlip
                .is_admissible_under(TopologyGuarantee::PLManifoldStrict)
        );
        assert!(
            TopologicalOperation::FacetFlip.is_admissible_under(TopologyGuarantee::Pseudomanifold)
        );

        assert!(
            TopologicalOperation::InsertVertex
                .is_admissible_under(TopologyGuarantee::Pseudomanifold)
        );
    }

    #[test]
    fn test_repair_policy_decide_respects_policy_and_topology() {
        let op = TopologicalOperation::FacetFlip;

        let decision =
            DelaunayRepairPolicy::EveryInsertion.decide(1, TopologyGuarantee::PLManifold, op);
        assert!(matches!(decision, RepairDecision::Proceed));

        let decision =
            DelaunayRepairPolicy::EveryInsertion.decide(1, TopologyGuarantee::Pseudomanifold, op);
        assert!(matches!(decision, RepairDecision::Proceed));

        let decision = DelaunayRepairPolicy::Never.decide(1, TopologyGuarantee::PLManifold, op);
        assert!(matches!(
            decision,
            RepairDecision::Skip {
                reason: RepairSkipReason::PolicyDisabled
            }
        ));
    }
}