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
//! General Euclidean edits on a proof-bearing Levels 1–4 owner.
//!
//! These operations accept non-Delaunay input and never certify Level 5.
//! For toroidal edits in a selected lifted chart, compose the transactional
//! [`PachnerMoves`](crate::pachner::PachnerMoves) proposal API instead.
use crate::core::algorithms::insertion::InsertionError;
use crate::core::tds::VertexKey;
use crate::core::traits::data_type::DataType;
use crate::core::vertex::Vertex;
use crate::geometry::kernel::Kernel;
use crate::topology::traits::topological_space::TopologyKind;
use crate::triangulation::Triangulation;
pub use crate::triangulation::repair::VertexRemovalError;
use thiserror::Error;
/// Structured rejection of a general Levels 1–4 vertex edit.
#[derive(Clone, Debug, Error, PartialEq)]
#[non_exhaustive]
pub enum TriangulationEditError {
/// General cavity editing requires Euclidean coordinates.
#[error(
"general vertex editing is unsupported for {topology:?}; use a chart-bound Pachner proposal"
)]
UnsupportedTopology {
/// The owner's selected geometry.
topology: TopologyKind,
},
/// Insertion or its cumulative postcondition failed.
#[error("Level 4 insertion failed: {source}")]
Insertion {
/// The original insertion diagnostic.
#[source]
source: Box<InsertionError>,
},
/// Cavity deletion or its cumulative postcondition failed.
#[error("Level 4 deletion failed: {source}")]
Deletion {
/// The original removal diagnostic.
#[source]
source: VertexRemovalError,
},
}
impl<K, U, V, const D: usize> Triangulation<K, U, V, D>
where
K: Kernel<D, Scalar = f64>,
U: DataType,
V: DataType,
{
/// Inserts an exact-coordinate vertex while preserving Levels 1–4.
///
/// Interior insertion subdivides the containing simplex; exterior insertion
/// extends the hull. Existing non-Delaunay state is accepted. The operation
/// never perturbs the input coordinates or performs Level 5 repair. New
/// simplices have no payload; surviving vertices and simplices retain theirs.
/// A successful edit passes cumulative realization validation regardless of
/// the configured validation cadence. Failure restores the complete owner,
/// including generational keys and construction evidence.
///
/// # Errors
///
/// Returns [`TriangulationEditError`] for duplicates, unsupported degenerate
/// locations, an empty owner requiring bootstrap construction, a non-Euclidean
/// topology, or a failed geometric/topological postcondition. Toroidal callers
/// can select a lifted simplex using [`PachnerMove::K1Insert`](crate::pachner::PachnerMove::K1Insert)
/// and execute its checked proposal through [`PachnerMoves`](crate::pachner::PachnerMoves).
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::construction::{DelaunayTriangulationBuilder, vertex};
/// # #[derive(Debug, thiserror::Error)]
/// # enum ExampleError {
/// # #[error(transparent)] Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
/// # #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
/// # #[error(transparent)] Edit(#[from] delaunay::TriangulationEditError),
/// # #[error(transparent)] Realization(#[from] delaunay::TriangulationRealizationValidationError),
/// # }
/// # fn main() -> Result<(), ExampleError> {
/// let vertices = [vertex![0.0, 0.0]?, vertex![1.0, 0.0]?, vertex![0.0, 1.0]?];
/// let mut tri = DelaunayTriangulationBuilder::new(&vertices).build_triangulation()?;
/// let key = tri.insert_vertex(vertex![0.2, 0.3]?)?;
/// assert!(tri.vertex(key).is_some());
/// tri.validate_realization()?;
/// # Ok(())
/// # }
/// ```
pub fn insert_vertex(
&mut self,
vertex: Vertex<U, D>,
) -> Result<VertexKey, TriangulationEditError> {
self.require_euclidean_edit()?;
self.insert_vertex_preserving_realization(vertex)
.map_err(|source| TriangulationEditError::Insertion {
source: Box::new(source),
})
}
/// Deletes a vertex by hull clipping or cavity retriangulation, preserving Levels 1–4.
///
/// Returns the number of removed simplices, or zero for a missing key.
/// A supporting Euclidean hull corner needs no replacement simplices; exact
/// predicates certify the exposed facets before its star is removed.
/// Fan filling need not produce a Delaunay triangulation. New simplices have
/// no payload, and surviving entities retain UUIDs and payloads. Failure
/// restores the complete owner and retains the typed operation or invariant
/// diagnostic. In high dimensions an arbitrary fan may lack a PL-link proof
/// and is rejected; inverse stellar deletion is available through
/// [`PachnerMoves`](crate::pachner::PachnerMoves).
///
/// # Errors
///
/// Returns [`TriangulationEditError`] when the topology is non-Euclidean,
/// the cavity cannot be filled, or Levels 1–4 reject the candidate.
///
/// # Examples
///
/// ```rust
/// use delaunay::prelude::construction::{DelaunayTriangulationBuilder, vertex};
/// # #[derive(Debug, thiserror::Error)]
/// # enum ExampleError {
/// # #[error(transparent)] Coordinate(#[from] delaunay::prelude::geometry::CoordinateConversionError),
/// # #[error(transparent)] Construction(#[from] delaunay::DelaunayTriangulationConstructionError),
/// # #[error(transparent)] Edit(#[from] delaunay::TriangulationEditError),
/// # #[error(transparent)] Realization(#[from] delaunay::TriangulationRealizationValidationError),
/// # }
/// # fn main() -> Result<(), ExampleError> {
/// let vertices = [vertex![0.0, 0.0]?, vertex![1.0, 0.0]?, vertex![0.0, 1.0]?];
/// let mut tri = DelaunayTriangulationBuilder::new(&vertices).build_triangulation()?;
/// let key = tri.insert_vertex(vertex![0.2, 0.3]?)?;
/// assert_eq!(tri.delete_vertex(key)?, 3);
/// assert!(tri.vertex(key).is_none());
/// tri.validate_realization()?;
/// # Ok(())
/// # }
/// ```
pub fn delete_vertex(
&mut self,
vertex_key: VertexKey,
) -> Result<usize, TriangulationEditError> {
self.require_euclidean_edit()?;
self.remove_vertex_preserving_realization(vertex_key)
.map_err(|source| TriangulationEditError::Deletion { source })
}
/// Prevents Euclidean cavity routines from interpreting periodic quotient coordinates.
const fn require_euclidean_edit(&self) -> Result<(), TriangulationEditError> {
match self.topology_kind() {
TopologyKind::Euclidean => Ok(()),
topology => Err(TriangulationEditError::UnsupportedTopology { topology }),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::DelaunayRefinementBuilder;
use crate::core::tds::{EntityKind, Tds, TdsBuilder, TopologyOwner};
use crate::geometry::kernel::RobustKernel;
use crate::triangulation::builder::TriangulationBuilder;
use crate::triangulation::validation::ValidationPolicy;
use crate::{DelaunayTriangulationBuilder, vertex};
/// Supplies a convex quadrilateral with the strictly non-Delaunay diagonal.
fn non_delaunay_quad() -> Triangulation<RobustKernel<f64>, u32, u32, 2> {
let vertices = [
vertex!([0.0, 0.0]; data = 10).unwrap(),
vertex!([2.0, 0.0]; data = 20).unwrap(),
vertex!([2.0, 1.0]; data = 30).unwrap(),
vertex!([0.0, 2.0]; data = 40).unwrap(),
];
let tds = TdsBuilder::new(&vertices, &[vec![0, 1, 3], vec![1, 2, 3]])
.simplex_data_type::<u32>()
.build()
.unwrap();
TriangulationBuilder::new(tds, RobustKernel::new())
.build()
.unwrap()
}
/// Exercises exact-coordinate insertion and inverse cavity deletion in each dimension.
fn round_trip<const D: usize>() {
let mut vertices = vec![vertex!([0.0; D]; data = 7_u32).unwrap()];
for axis in 0..D {
let mut coordinates = [0.0; D];
coordinates[axis] = 1.0;
vertices.push(vertex!(coordinates; data = 9).unwrap());
}
let simplices = [(0..=D).collect::<Vec<_>>()];
let tds = TdsBuilder::new(&vertices, &simplices)
.simplex_data_type::<u32>()
.build()
.unwrap();
let mut tri = TriangulationBuilder::new(tds, RobustKernel::new())
.canonicalizing()
.build()
.unwrap();
let original_vertices = tri
.vertices()
.map(|(key, vertex)| (key, vertex.uuid(), *vertex.data().unwrap()))
.collect::<Vec<_>>();
let inserted = vertex!([0.1; D]; data = 99).unwrap();
let inserted_uuid = inserted.uuid();
let key = tri.insert_vertex(inserted).unwrap();
let actual = tri.vertex(key).unwrap();
assert_eq!(actual.uuid(), inserted_uuid);
assert_eq!(
actual.point().coords().map(f64::to_bits),
[0.1_f64.to_bits(); D]
);
assert_eq!(actual.data(), Some(&99));
assert_eq!(tri.number_of_simplices(), D + 1);
tri.validate_realization().unwrap();
assert_eq!(tri.delete_vertex(key).unwrap(), D + 1);
assert_eq!(tri.number_of_simplices(), 1);
assert_eq!(tri.delete_vertex(key).unwrap(), 0);
assert_eq!(
tri.vertices()
.map(|(key, vertex)| (key, vertex.uuid(), *vertex.data().unwrap()))
.collect::<Vec<_>>(),
original_vertices
);
tri.validate_realization().unwrap();
}
macro_rules! dimension_tests {
($($dimension:literal),+) => { $(pastey::paste! {
#[test]
fn [<insertion_deletion_round_trip_ $dimension d>]() {
round_trip::<$dimension>();
}
})+ };
}
dimension_tests!(2, 3, 4, 5);
#[test]
fn non_delaunay_input_supports_interior_and_exterior_insertion() {
let mut tri = non_delaunay_quad();
assert!(DelaunayRefinementBuilder::new(tri.clone()).build().is_err());
let key = tri
.insert_vertex(vertex!([0.2, 0.3]; data = 50).unwrap())
.unwrap();
tri.validate_realization().unwrap();
tri.delete_vertex(key).unwrap();
tri.insert_vertex(vertex!([3.0, 3.0]; data = 60).unwrap())
.unwrap();
tri.validate_realization().unwrap();
}
#[test]
fn failed_insertion_restores_owner_keys_generation_payloads_and_evidence() {
let mut tri = non_delaunay_quad();
tri.try_set_validation_policy(ValidationPolicy::ExplicitOnly)
.unwrap();
let original = tri.tds.clone_for_rollback();
let serialized = serde_json::to_value(&tri.tds).unwrap();
let handles = tri
.vertices()
.map(|(key, vertex)| (key, vertex.incident_simplex()))
.collect::<Vec<_>>();
let identity = tri.topology_owner_id();
let generation = tri.topology_generation();
let evidence = tri.topology_construction_provenance;
// This point lies exactly on the existing interior diagonal. A stellar
// subdivision cannot realize it without a degenerate simplex.
assert!(matches!(
tri.insert_vertex(vertex!([1.0, 1.0]; data = 99).unwrap()),
Err(TriangulationEditError::Insertion { .. })
));
assert_eq!(tri.tds, original);
assert_eq!(serde_json::to_value(&tri.tds).unwrap(), serialized);
assert_eq!(
tri.vertices()
.map(|(key, vertex)| (key, vertex.incident_simplex()))
.collect::<Vec<_>>(),
handles
);
assert_eq!(tri.topology_owner_id(), identity);
assert_eq!(tri.topology_generation(), generation);
assert_eq!(tri.topology_construction_provenance, evidence);
assert_eq!(tri.validation_policy(), ValidationPolicy::ExplicitOnly);
tri.validate_realization().unwrap();
}
#[test]
fn failed_deletion_restores_complete_owner_and_typed_error() {
let vertices = [
vertex![0.0, 0.0].unwrap(),
vertex![1.0, 0.0].unwrap(),
vertex![0.0, 1.0].unwrap(),
];
let mut tri = DelaunayTriangulationBuilder::new(&vertices)
.build_triangulation()
.unwrap();
let key = tri.vertices().next().unwrap().0;
let original = tri.tds.clone_for_rollback();
let serialized = serde_json::to_value(&tri.tds).unwrap();
let identity = tri.topology_owner_id();
let generation = tri.topology_generation();
assert!(matches!(
tri.delete_vertex(key),
Err(TriangulationEditError::Deletion { .. })
));
assert_eq!(tri.tds, original);
assert_eq!(serde_json::to_value(&tri.tds).unwrap(), serialized);
assert_eq!(tri.topology_owner_id(), identity);
assert_eq!(tri.topology_generation(), generation);
tri.validate_realization().unwrap();
}
#[test]
fn empty_owner_and_duplicate_insertion_fail_without_mutation() {
let mut empty = TriangulationBuilder::new(Tds::<(), (), 2>::empty(), RobustKernel::new())
.build()
.unwrap();
assert!(matches!(empty.insert_vertex(vertex![0.0, 0.0].unwrap()),
Err(TriangulationEditError::Insertion { source })
if matches!(*source, InsertionError::PublishedOwnerBootstrapRequiresBuilder { dimension: 2 })));
assert_eq!(empty.number_of_vertices(), 0);
let mut tri = non_delaunay_quad();
let before = serde_json::to_value(&tri.tds).unwrap();
assert!(
matches!(tri.insert_vertex(vertex!([0.0, 0.0]; data = 99).unwrap()),
Err(TriangulationEditError::Insertion { source })
if matches!(*source, InsertionError::DuplicateCoordinates { .. }))
);
assert_eq!(serde_json::to_value(&tri.tds).unwrap(), before);
}
#[test]
fn duplicate_uuid_at_distinct_coordinates_preserves_the_owner() {
let mut tri = non_delaunay_quad();
tri.validate_realization().unwrap();
let uuid = tri.vertices().next().unwrap().1.uuid();
let candidate = vertex!([0.2, 0.3]; data = 99).unwrap();
let duplicate = Vertex::try_new_with_uuid(*candidate.point(), uuid, Some(99)).unwrap();
let storage = tri.tds.clone_for_rollback();
let serialized = serde_json::to_value(&tri.tds).unwrap();
let hints = tri
.vertices()
.map(|(key, vertex)| (key, vertex.incident_simplex()))
.collect::<Vec<_>>();
let identity = tri.topology_owner_id();
let generation = tri.topology_generation();
let evidence = tri.topology_construction_provenance;
let policy = tri.validation_policy();
assert_eq!(
tri.insert_vertex(duplicate),
Err(TriangulationEditError::Insertion {
source: Box::new(InsertionError::DuplicateUuid {
entity: EntityKind::Vertex,
uuid
}),
})
);
assert_eq!(tri.tds, storage);
assert_eq!(serde_json::to_value(&tri.tds).unwrap(), serialized);
assert_eq!(
tri.vertices()
.map(|(key, vertex)| (key, vertex.incident_simplex()))
.collect::<Vec<_>>(),
hints
);
assert_eq!(tri.topology_owner_id(), identity);
assert_eq!(tri.topology_generation(), generation);
assert_eq!(tri.topology_construction_provenance, evidence);
assert_eq!(tri.validation_policy(), policy);
tri.validate_realization().unwrap();
}
}