honeycomb-core 0.11.0

Core structure implementation for combinatorial maps
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
//! Basic operations implementation
//!
//! This module contains code used to implement basic operations of combinatorial maps, such as
//! (but not limited to):
//!
//! - Dart addition / insertion / removal
//! - Beta function interfaces
//! - i-cell computations

use std::cell::RefCell;
use std::collections::VecDeque;

use rayon::prelude::*;
use rustc_hash::FxHashSet as HashSet;

use crate::cmap::{
    CMap3, DartIdType, EdgeIdType, FaceIdType, NULL_DART_ID, VertexIdType, VolumeIdType,
};
use crate::geometry::CoordsFloat;
use crate::stm::{StmClosureResult, StmError, Transaction, atomically};

// use thread local hashset and queue for orbit traversal of ID comp.
// not applied to orbit currently bc they are lazily onsumed, and therefore require dedicated
// instances to be robust
thread_local! {
    static AUXILIARIES: RefCell<(VecDeque<DartIdType>, HashSet<DartIdType>)> = RefCell::new(
        (
            VecDeque::with_capacity(10),
            HashSet::default(),
        )
    );
}

/// **Beta-related methods**
impl<T: CoordsFloat> CMap3<T> {
    // --- read

    /// Return β<sub>`I`</sub>(`dart_id`).
    ///
    /// # Errors
    ///
    /// This method is meant to be called in a context where the returned `Result` is used to
    /// validate the transaction passed as argument. Errors should not be processed manually,
    /// only processed via the `?` operator.
    ///
    /// # Panics
    ///
    /// The method will panic if `I` is not 0, 1, 2, or 3.
    pub fn beta_tx<const I: u8>(
        &self,
        t: &mut Transaction,
        dart_id: DartIdType,
    ) -> StmClosureResult<DartIdType> {
        assert!(I < 4);
        self.betas[(I, dart_id)].read(t)
    }

    /// Return β<sub>`i`</sub>(`dart_id`).
    ///
    /// # Errors
    ///
    /// This method is meant to be called in a context where the returned `Result` is used to
    /// validate the transaction passed as argument. Errors should not be processed manually,
    /// only processed via the `?` operator.
    ///
    /// # Panics
    ///
    /// The method will panic if `i` is not 0, 1, 2, or 3.
    pub fn beta_rt_tx(
        &self,
        t: &mut Transaction,
        i: u8,
        dart_id: DartIdType,
    ) -> StmClosureResult<DartIdType> {
        assert!(i < 4);
        match i {
            0 => self.beta_tx::<0>(t, dart_id),
            1 => self.beta_tx::<1>(t, dart_id),
            2 => self.beta_tx::<2>(t, dart_id),
            3 => self.beta_tx::<3>(t, dart_id),
            _ => unreachable!(),
        }
    }

    /// Return β<sub>`I`</sub>(`dart_id`).
    ///
    /// # Panics
    ///
    /// The method will panic if `I` is not 0, 1, 2, or 3.
    #[must_use = "unused return value"]
    pub fn beta<const I: u8>(&self, dart_id: DartIdType) -> DartIdType {
        assert!(I < 4);
        atomically(|t| self.betas[(I, dart_id)].read(t))
    }

    /// Return β<sub>`i`</sub>(`dart_id`).
    ///
    /// # Panics
    ///
    /// The method will panic if `i` is not 0, 1, 2, or 3.
    #[must_use = "unused return value"]
    pub fn beta_rt(&self, i: u8, dart_id: DartIdType) -> DartIdType {
        assert!(i < 4);
        match i {
            0 => self.beta::<0>(dart_id),
            1 => self.beta::<1>(dart_id),
            2 => self.beta::<2>(dart_id),
            3 => self.beta::<3>(dart_id),
            _ => unreachable!(),
        }
    }

    /// Check if a given dart is `I`-free.
    ///
    /// # Return
    ///
    /// The method returns:
    /// - `true` if β<sub>`I`</sub>(`dart_id`) = `NULL_DART_ID`,
    /// - `false` otherwise.
    ///
    /// # Panics
    ///
    /// The function will panic if *I* is not 0, 1, 2, or 3.
    #[must_use = "unused return value"]
    pub fn is_i_free<const I: u8>(&self, dart_id: DartIdType) -> bool {
        self.beta::<I>(dart_id) == NULL_DART_ID
    }

    /// Check if a given dart is free for all `i`.
    ///
    /// # Return
    ///
    /// Returns `true` if the dart is 0-free, 1-free, 2-free, **and** 3-free.
    #[must_use = "unused return value"]
    pub fn is_free(&self, dart_id: DartIdType) -> bool {
        atomically(|t| self.is_free_tx(t, dart_id))
    }

    /// Check if a given dart is `i`-free, for all `i`.
    ///
    /// # Return
    ///
    /// Return a boolean indicating if the dart is 0-free, 1-free **and** 2-free.
    ///
    /// # Errors
    ///
    /// This method is meant to be called in a context where the returned `Result` is used to
    /// validate the transaction passed as argument. Errors should not be processed manually,
    /// only processed via the `?` operator.
    #[must_use = "unused return value"]
    pub fn is_free_tx(&self, t: &mut Transaction, dart_id: DartIdType) -> StmClosureResult<bool> {
        Ok(self.beta_tx::<0>(t, dart_id)? == NULL_DART_ID
            && self.beta_tx::<1>(t, dart_id)? == NULL_DART_ID
            && self.beta_tx::<2>(t, dart_id)? == NULL_DART_ID
            && self.beta_tx::<3>(t, dart_id)? == NULL_DART_ID)
    }
}

/// **I-cell-related methods**
impl<T: CoordsFloat> CMap3<T> {
    /// Compute the ID of the vertex a given dart is part of.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 0-cell orbit.
    #[must_use = "unused return value"]
    pub fn vertex_id(&self, dart_id: DartIdType) -> VertexIdType {
        atomically(|t| self.vertex_id_tx(t, dart_id))
    }

    /// Compute the ID of the vertex a given dart is part of, transactionally.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 0-cell orbit.
    ///
    /// # Errors
    ///
    /// This method is meant to be called in a context where the returned `Result` is used to
    /// validate the transaction passed as argument. Errors should not be processed manually,
    /// only processed via the `?` operator.
    pub fn vertex_id_tx(
        &self,
        t: &mut Transaction,
        dart_id: DartIdType,
    ) -> Result<VertexIdType, StmError> {
        AUXILIARIES.with(|cell| {
            let (pending, marked) = &mut *cell.borrow_mut();
            // clear from previous computations
            pending.clear();
            marked.clear();
            // initialize
            pending.push_front(dart_id);
            marked.insert(NULL_DART_ID); // we don't want to include the null dart in the orbit

            let mut min = dart_id;

            while let Some(d) = pending.pop_front() {
                if marked.insert(d) {
                    min = min.min(d);
                    let (b0, b2, b3) = (
                        self.beta_tx::<0>(t, d)?, // ?
                        self.beta_tx::<2>(t, d)?,
                        self.beta_tx::<3>(t, d)?,
                    );
                    // B1oB2, B2oB0, B1oB3, B3oB0, B2oB3, B3oB2
                    pending.push_back(self.beta_tx::<1>(t, b2)?); // B1oB2
                    pending.push_back(self.beta_tx::<1>(t, b3)?); // B1oB3
                    pending.push_back(self.beta_tx::<2>(t, b3)?); // B2oB3
                    pending.push_back(self.beta_tx::<2>(t, b0)?); // B2oB0
                    pending.push_back(self.beta_tx::<3>(t, b0)?); // B3oB0
                    pending.push_back(self.beta_tx::<3>(t, b2)?); // B3oB2
                }
            }

            Ok(min)
        })
    }

    /// Compute the ID of the edge a given dart is part of.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 1-cell orbit.
    #[must_use = "unused return value"]
    pub fn edge_id(&self, dart_id: DartIdType) -> EdgeIdType {
        atomically(|t| self.edge_id_tx(t, dart_id))
    }

    /// Compute the ID of the edge a given dart is part of.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 1-cell orbit.
    ///
    /// # Errors
    ///
    /// This method is meant to be called in a context where the returned `Result` is used to
    /// validate the transaction passed as argument. Errors should not be processed manually,
    /// only processed via the `?` operator.
    pub fn edge_id_tx(
        &self,
        t: &mut Transaction,
        dart_id: DartIdType,
    ) -> Result<EdgeIdType, StmError> {
        AUXILIARIES.with(|cell| {
            let (pending, marked) = &mut *cell.borrow_mut();
            // clear from previous computations
            pending.clear();
            marked.clear();
            // initialize
            pending.push_back(dart_id);
            marked.insert(NULL_DART_ID);

            let mut min = dart_id;

            while let Some(d) = pending.pop_front() {
                if marked.insert(d) {
                    min = min.min(d);
                    for im in [self.beta_tx::<2>(t, d)?, self.beta_tx::<3>(t, d)?] {
                        pending.push_back(im);
                    }
                }
            }

            Ok(min)
        })
    }

    /// Compute the ID of the face a given dart is part of.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 2-cell orbit.
    #[must_use = "unused return value"]
    pub fn face_id(&self, dart_id: DartIdType) -> FaceIdType {
        atomically(|t| self.face_id_tx(t, dart_id))
    }

    /// Compute the ID of the face a given dart is part of.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 2-cell orbit.
    ///
    /// # Errors
    ///
    /// This method is meant to be called in a context where the returned `Result` is used to
    /// validate the transaction passed as argument. Errors should not be processed manually,
    /// only processed via the `?` operator.
    pub fn face_id_tx(
        &self,
        t: &mut Transaction,
        dart_id: DartIdType,
    ) -> Result<FaceIdType, StmError> {
        AUXILIARIES.with(|cell| {
            let (_pending, marked) = &mut *cell.borrow_mut();
            // clear from previous computations
            marked.clear();
            // initialize
            marked.insert(NULL_DART_ID); // we don't want to include the null dart in the orbit

            let b3_dart_id = self.beta_tx::<3>(t, dart_id)?;
            let (mut lb, mut rb) = (dart_id, b3_dart_id);
            let mut min = if rb == NULL_DART_ID { lb } else { lb.min(rb) };

            while marked.insert(lb) || marked.insert(rb) {
                (lb, rb) = (self.beta_tx::<1>(t, lb)?, self.beta_tx::<0>(t, rb)?);
                if lb != NULL_DART_ID {
                    min = min.min(lb);
                }
                if rb != NULL_DART_ID {
                    min = min.min(rb);
                }
            }
            // face is open, we need to iterate in the other direction
            if lb == NULL_DART_ID || rb == NULL_DART_ID {
                (lb, rb) = (
                    self.beta_tx::<0>(t, dart_id)?,
                    self.beta_tx::<1>(t, b3_dart_id)?,
                );
                while marked.insert(lb) || marked.insert(rb) {
                    (lb, rb) = (self.beta_tx::<0>(t, lb)?, self.beta_tx::<1>(t, rb)?);
                    if lb != NULL_DART_ID {
                        min = min.min(lb);
                    }
                    if rb != NULL_DART_ID {
                        min = min.min(rb);
                    }
                }
            }

            Ok(min)
        })
    }

    /// Compute the ID of the volume a given dart is part of.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 3-cell orbit.
    #[must_use = "unused return value"]
    pub fn volume_id(&self, dart_id: DartIdType) -> VolumeIdType {
        atomically(|t| self.volume_id_tx(t, dart_id))
    }

    /// Compute the ID of the volume a given dart is part of.
    ///
    /// This corresponds to the minimum dart ID among darts composing the 3-cell orbit.
    ///
    /// # Errors
    ///
    /// This method is meant to be called in a context where the returned `Result` is used to
    /// validate the transaction passed as argument. Errors should not be processed manually,
    /// only processed via the `?` operator.
    pub fn volume_id_tx(
        &self,
        t: &mut Transaction,
        dart_id: DartIdType,
    ) -> Result<VolumeIdType, StmError> {
        AUXILIARIES.with(|cell| {
            let (pending, marked) = &mut *cell.borrow_mut();
            // clear from previous computations
            pending.clear();
            marked.clear();
            // initialize
            pending.push_front(dart_id);
            marked.insert(NULL_DART_ID); // we don't want to include the null dart in the orbit

            let mut min = dart_id;

            while let Some(d) = pending.pop_front() {
                if marked.insert(d) {
                    min = min.min(d);
                    pending.push_back(self.beta_tx::<1>(t, d)?);
                    pending.push_back(self.beta_tx::<0>(t, d)?); // ?
                    pending.push_back(self.beta_tx::<2>(t, d)?);
                }
            }

            Ok(min)
        })
    }

    /// Return an iterator over IDs of all the map's vertices.
    pub fn iter_vertices(&self) -> impl Iterator<Item = VertexIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .zip(self.unused_darts.iter().skip(1))
            .filter_map(
                |(d, unused)| {
                    if unused.read_atomic() { None } else { Some(d) }
                },
            )
            .filter_map(|d| {
                let vid = self.vertex_id(d);
                if d == vid { Some(vid) } else { None }
            })
    }

    /// Return an iterator over IDs of all the map's edges.
    pub fn iter_edges(&self) -> impl Iterator<Item = EdgeIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .zip(self.unused_darts.iter().skip(1))
            .filter_map(
                |(d, unused)| {
                    if unused.read_atomic() { None } else { Some(d) }
                },
            )
            .filter_map(|d| {
                let eid = self.edge_id(d);
                if d == eid { Some(eid) } else { None }
            })
    }

    /// Return an iterator over IDs of all the map's faces.
    pub fn iter_faces(&self) -> impl Iterator<Item = FaceIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .zip(self.unused_darts.iter().skip(1))
            .filter_map(
                |(d, unused)| {
                    if unused.read_atomic() { None } else { Some(d) }
                },
            )
            .filter_map(|d| {
                let fid = self.face_id(d);
                if d == fid { Some(fid) } else { None }
            })
    }

    /// Return an iterator over IDs of all the map's volumes.
    pub fn iter_volumes(&self) -> impl Iterator<Item = VolumeIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .zip(self.unused_darts.iter().skip(1))
            .filter_map(
                |(d, unused)| {
                    if unused.read_atomic() { None } else { Some(d) }
                },
            )
            .filter_map(|d| {
                let vid = self.volume_id(d);
                if d == vid { Some(vid) } else { None }
            })
    }

    /// Return an iterator over IDs of all the map's vertices.
    #[must_use = "iterators are lazy and do nothing unless consumed"]
    pub fn par_iter_vertices(&self) -> impl ParallelIterator<Item = VertexIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .into_par_iter()
            .filter_map(|d| {
                if atomically(|t| self.is_unused_tx(t, d)) {
                    None
                } else {
                    Some(d)
                }
            })
            .filter_map(|d| {
                let vid = self.vertex_id(d);
                if d == vid { Some(vid) } else { None }
            })
    }

    /// Return an iterator over IDs of all the map's edges.
    #[must_use = "iterators are lazy and do nothing unless consumed"]
    pub fn par_iter_edges(&self) -> impl ParallelIterator<Item = EdgeIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .into_par_iter()
            .filter_map(|d| {
                if atomically(|t| self.is_unused_tx(t, d)) {
                    None
                } else {
                    Some(d)
                }
            })
            .filter_map(|d| {
                let eid = self.edge_id(d);
                if d == eid { Some(eid) } else { None }
            })
    }

    /// Return an iterator over IDs of all the map's faces.
    #[must_use = "iterators are lazy and do nothing unless consumed"]
    pub fn par_iter_faces(&self) -> impl ParallelIterator<Item = FaceIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .into_par_iter()
            .filter_map(|d| {
                if atomically(|t| self.is_unused_tx(t, d)) {
                    None
                } else {
                    Some(d)
                }
            })
            .filter_map(|d| {
                let fid = self.face_id(d);
                if d == fid { Some(fid) } else { None }
            })
    }

    /// Return an iterator over IDs of all the map's volumes.
    #[must_use = "iterators are lazy and do nothing unless consumed"]
    pub fn par_iter_volumes(&self) -> impl ParallelIterator<Item = VolumeIdType> + '_ {
        (1..self.n_darts() as DartIdType)
            .into_par_iter()
            .filter_map(|d| {
                if atomically(|t| self.is_unused_tx(t, d)) {
                    None
                } else {
                    Some(d)
                }
            })
            .filter_map(|d| {
                let vid = self.volume_id(d);
                if d == vid { Some(vid) } else { None }
            })
    }
}