dijkstra3d-core 0.1.0

Voxel-grid Dijkstra and rolling-ball invalidation, ported from seung-lab/dijkstra3d and seung-lab/kimimaro
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
//! Atomic distance primitives for parallel SSSP/Dijkstra-style algorithms.

use std::sync::atomic::{AtomicU32, AtomicU64, Ordering};

/// Atomic `f32` distance stored through its `u32` bit representation.
#[derive(Debug)]
pub struct AtomicDist {
    bits: AtomicU32,
}

impl AtomicDist {
    /// Construct at `+INFINITY`. Use this for the initial state of every
    /// non-source voxel before Dijkstra starts.
    #[inline]
    pub fn infinity() -> Self {
        Self {
            bits: AtomicU32::new(f32::INFINITY.to_bits()),
        }
    }

    /// Construct at exactly `value`. Use this for source voxels (typically
    /// `0.0`).
    #[inline]
    pub fn new(value: f32) -> Self {
        debug_assert!(
            value >= 0.0 && !value.is_nan(),
            "AtomicDist requires non-negative non-NaN values; got {}",
            value
        );
        Self {
            bits: AtomicU32::new(value.to_bits()),
        }
    }

    /// Unconditionally store 0.0.
    #[inline]
    pub fn store_zero(&self) {
        self.bits.store(0u32, Ordering::Relaxed);
    }

    /// Read the current distance.
    #[inline]
    pub fn load(&self) -> f32 {
        f32::from_bits(self.bits.load(Ordering::Relaxed))
    }

    /// Relax: atomically write `new_dist` if and only if it is strictly less
    /// than the current value. Returns `true` if the write happened.
    #[inline]
    pub fn relax(&self, new_dist: f32) -> bool {
        debug_assert!(
            new_dist >= 0.0 && !new_dist.is_nan(),
            "AtomicDist::relax requires non-negative non-NaN; got {}",
            new_dist
        );
        let new_bits = new_dist.to_bits();
        let mut current_bits = self.bits.load(Ordering::Relaxed);
        loop {
            // Bitwise comparison works because new_dist and current value are
            // both non-negative finite (or +INFINITY)
            if new_bits >= current_bits {
                return false;
            }
            match self.bits.compare_exchange_weak(
                current_bits,
                new_bits,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return true,
                Err(observed) => current_bits = observed,
            }
        }
    }
}

/// Parent and distance packed into one atomic word.
#[derive(Debug)]
pub struct AtomicDistParent {
    packed: AtomicU64,
}

/// Pack `(parent_plus_one, dist)` into a u64.
///
/// Layout: `(parent_plus_one as u64) << 32 | (dist.to_bits() as u64)`.
#[inline]
fn pack(parent_plus_one: u32, dist_bits: u32) -> u64 {
    ((parent_plus_one as u64) << 32) | (dist_bits as u64)
}

#[inline]
fn unpack_parent(packed: u64) -> u32 {
    (packed >> 32) as u32
}

#[inline]
fn unpack_dist_bits(packed: u64) -> u32 {
    (packed & 0xFFFF_FFFF) as u32
}

impl AtomicDistParent {
    /// Construct at `(parent=0, dist=+INFINITY)` — the standard
    /// "unreached voxel" state.
    #[inline]
    pub fn infinity() -> Self {
        Self {
            packed: AtomicU64::new(pack(0, f32::INFINITY.to_bits())),
        }
    }

    /// Construct at `(parent=0, dist=0.0)` — the standard "source voxel" state.
    /// Sources have no parent; the path-reconstruction code stops at
    /// `parent_plus_one == 0`.
    #[inline]
    pub fn source() -> Self {
        Self {
            packed: AtomicU64::new(pack(0, 0.0_f32.to_bits())),
        }
    }

    /// Construct at `(parent=0, dist=u32::MAX)`, the unreached state for the
    /// integer parallel kernel.
    #[inline]
    pub fn int_infinity() -> Self {
        Self {
            packed: AtomicU64::new(pack(0, u32::MAX)),
        }
    }

    /// Unconditionally store the "source state" (parent=0, dist=0.0).
    #[inline]
    pub fn store_source(&self) {
        self.packed
            .store(pack(0, 0.0_f32.to_bits()), Ordering::Relaxed);
    }

    /// Read the current `(parent_plus_one, dist)` pair.
    #[inline]
    pub fn load(&self) -> (u32, f32) {
        let p = self.packed.load(Ordering::Relaxed);
        (unpack_parent(p), f32::from_bits(unpack_dist_bits(p)))
    }

    /// Read the current distance.
    #[inline]
    pub fn load_dist(&self) -> f32 {
        let p = self.packed.load(Ordering::Relaxed);
        f32::from_bits(unpack_dist_bits(p))
    }

    /// Relax: atomically write `(new_parent_idx + 1, new_dist)` if and only
    /// if `new_dist` is strictly less than the current distance.
    #[inline]
    pub fn relax_with_parent(&self, new_dist: f32, new_parent_idx: u32) -> bool {
        debug_assert!(
            new_dist >= 0.0 && !new_dist.is_nan(),
            "AtomicDistParent::relax_with_parent requires non-negative non-NaN; got {}",
            new_dist
        );
        debug_assert!(
            new_parent_idx < u32::MAX,
            "parent_idx + 1 would overflow u32"
        );
        let new_bits = new_dist.to_bits();
        let new_packed = pack(new_parent_idx + 1, new_bits);

        let mut current_packed = self.packed.load(Ordering::Relaxed);
        loop {
            let current_dist_bits = unpack_dist_bits(current_packed);
            // IEEE-754 monotonicity for non-negative finite values.
            if new_bits >= current_dist_bits {
                return false;
            }
            match self.packed.compare_exchange_weak(
                current_packed,
                new_packed,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return true,
                Err(observed) => current_packed = observed,
            }
        }
    }

    /// Integer counterpart to [`relax_with_parent`](Self::relax_with_parent)
    #[inline]
    pub fn relax_with_parent_int(&self, new_dist: u32, new_parent_idx: u32) -> bool {
        debug_assert!(
            new_parent_idx < u32::MAX,
            "parent_idx + 1 would overflow u32"
        );
        let new_packed = pack(new_parent_idx + 1, new_dist);
        let mut current_packed = self.packed.load(Ordering::Relaxed);
        loop {
            let current_dist = unpack_dist_bits(current_packed);
            if new_dist >= current_dist {
                return false;
            }
            match self.packed.compare_exchange_weak(
                current_packed,
                new_packed,
                Ordering::Relaxed,
                Ordering::Relaxed,
            ) {
                Ok(_) => return true,
                Err(observed) => current_packed = observed,
            }
        }
    }

    /// Read just the raw integer distance (the low 32 bits, uninterpreted).
    /// Companion to [`relax_with_parent_int`](Self::relax_with_parent_int); the
    /// unreached sentinel is `u32::MAX`.
    #[inline]
    pub fn load_dist_int(&self) -> u32 {
        unpack_dist_bits(self.packed.load(Ordering::Relaxed))
    }
}

/// Allocate a vector of [`AtomicDist`] of length `n`, all initialized to
/// `+INFINITY`. Use this for the `dist[]` array in parallel SSSP.
pub fn atomic_dist_vec(n: usize) -> Vec<AtomicDist> {
    (0..n).map(|_| AtomicDist::infinity()).collect()
}

/// Allocate a vector of [`AtomicDistParent`] of length `n`, all initialized
/// to `(parent=0, dist=+INFINITY)`.
pub fn atomic_dist_parent_vec(n: usize) -> Vec<AtomicDistParent> {
    (0..n).map(|_| AtomicDistParent::infinity()).collect()
}

/// Allocate a vector of [`AtomicDistParent`] of length `n`, all initialized to
/// the **integer** unreached sentinel `(parent=0, dist=u32::MAX)`.
pub fn atomic_dist_parent_vec_int(n: usize) -> Vec<AtomicDistParent> {
    (0..n).map(|_| AtomicDistParent::int_infinity()).collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::Arc;
    use std::thread;

    #[test]
    fn atomic_dist_starts_at_infinity() {
        let d = AtomicDist::infinity();
        assert_eq!(d.load(), f32::INFINITY);
    }

    #[test]
    fn atomic_dist_relax_smaller_succeeds() {
        let d = AtomicDist::infinity();
        assert!(d.relax(3.5));
        assert_eq!(d.load(), 3.5);
    }

    #[test]
    fn atomic_dist_relax_larger_fails() {
        let d = AtomicDist::new(3.5);
        assert!(!d.relax(10.0));
        assert_eq!(d.load(), 3.5);
    }

    #[test]
    fn atomic_dist_relax_equal_fails() {
        // Strict inequality: equal distance should NOT relax.
        let d = AtomicDist::new(3.5);
        assert!(!d.relax(3.5));
    }

    #[test]
    fn atomic_dist_relax_zero_against_infinity() {
        let d = AtomicDist::infinity();
        assert!(d.relax(0.0));
        assert_eq!(d.load(), 0.0);
    }

    #[test]
    fn atomic_dist_concurrent_relax_keeps_minimum() {
        // Spawn 16 threads each trying to relax with a different value.
        // The smallest value must be retained.
        let d = Arc::new(AtomicDist::infinity());
        let values: Vec<f32> = (1..=16).map(|i| i as f32).collect();
        let handles: Vec<_> = values
            .iter()
            .map(|&v| {
                let d = Arc::clone(&d);
                thread::spawn(move || d.relax(v))
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        assert_eq!(d.load(), 1.0, "Concurrent relax must converge to minimum");
    }

    #[test]
    fn atomic_dist_parent_starts_at_infinity_no_parent() {
        let dp = AtomicDistParent::infinity();
        let (p, d) = dp.load();
        assert_eq!(p, 0);
        assert_eq!(d, f32::INFINITY);
    }

    #[test]
    fn atomic_dist_parent_source_starts_at_zero_no_parent() {
        let dp = AtomicDistParent::source();
        let (p, d) = dp.load();
        assert_eq!(p, 0);
        assert_eq!(d, 0.0);
    }

    #[test]
    fn atomic_dist_parent_relax_with_parent_smaller_succeeds() {
        let dp = AtomicDistParent::infinity();
        assert!(dp.relax_with_parent(3.5, 42));
        let (p, d) = dp.load();
        assert_eq!(p, 43, "parent stored with +1 sentinel");
        assert_eq!(d, 3.5);
    }

    #[test]
    fn atomic_dist_parent_relax_with_parent_larger_fails() {
        let dp = AtomicDistParent::infinity();
        assert!(dp.relax_with_parent(3.5, 42));
        assert!(!dp.relax_with_parent(10.0, 99));
        let (p, d) = dp.load();
        assert_eq!(p, 43, "parent unchanged after failed relax");
        assert_eq!(d, 3.5);
    }

    #[test]
    fn atomic_dist_parent_concurrent_relax_keeps_minimum_pair() {
        // Sixteen threads race to relax with (i, dist=i). The smallest distance
        // and its corresponding parent must be observed.
        let dp = Arc::new(AtomicDistParent::infinity());
        let handles: Vec<_> = (1..=16u32)
            .map(|i| {
                let dp = Arc::clone(&dp);
                thread::spawn(move || dp.relax_with_parent(i as f32, i * 100))
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        let (p, d) = dp.load();
        assert_eq!(d, 1.0);
        assert_eq!(p, 101, "parent must match the winning relax");
    }

    #[test]
    fn atomic_dist_parent_load_dist_matches_load() {
        let dp = AtomicDistParent::infinity();
        dp.relax_with_parent(7.25, 1234);
        let (_, d_full) = dp.load();
        let d_fast = dp.load_dist();
        assert_eq!(d_full, d_fast);
    }

    #[test]
    fn atomic_dist_vec_initializes_to_infinity() {
        let v = atomic_dist_vec(10);
        for d in &v {
            assert_eq!(d.load(), f32::INFINITY);
        }
    }

    #[test]
    fn atomic_dist_parent_vec_initializes_to_infinity_no_parent() {
        let v = atomic_dist_parent_vec(10);
        for dp in &v {
            assert_eq!(dp.load(), (0, f32::INFINITY));
        }
    }

    #[test]
    fn atomic_dist_parent_store_source_overrides_infinity() {
        let dp = AtomicDistParent::infinity();
        dp.store_source();
        let (p, d) = dp.load();
        assert_eq!(p, 0);
        assert_eq!(d, 0.0);
    }

    #[test]
    fn atomic_dist_store_zero_overrides_infinity() {
        let d = AtomicDist::infinity();
        d.store_zero();
        assert_eq!(d.load(), 0.0);
    }

    #[test]
    fn atomic_dist_parent_int_infinity_sentinel() {
        let dp = AtomicDistParent::int_infinity();
        assert_eq!(dp.load_dist_int(), u32::MAX);
        assert_eq!(dp.load().0, 0, "no parent at int-infinity");
    }

    #[test]
    fn atomic_dist_parent_relax_int_smaller_succeeds() {
        let dp = AtomicDistParent::int_infinity();
        assert!(dp.relax_with_parent_int(100, 42));
        assert_eq!(dp.load_dist_int(), 100);
        assert_eq!(dp.load().0, 43, "parent stored with +1 sentinel");
    }

    #[test]
    fn atomic_dist_parent_relax_int_larger_and_equal_fail() {
        let dp = AtomicDistParent::int_infinity();
        assert!(dp.relax_with_parent_int(100, 42));
        assert!(!dp.relax_with_parent_int(200, 7), "larger must not relax");
        assert!(!dp.relax_with_parent_int(100, 7), "equal must not relax");
        assert_eq!(dp.load_dist_int(), 100);
        assert_eq!(dp.load().0, 43, "parent unchanged after failed relax");
    }

    #[test]
    fn atomic_dist_parent_relax_int_concurrent_keeps_minimum() {
        // Sixteen threads race with distinct integer distances. The smallest
        // distance and its parent must be observed, as in the f32 concurrency test.
        let dp = Arc::new(AtomicDistParent::int_infinity());
        let handles: Vec<_> = (1..=16u32)
            .map(|i| {
                let dp = Arc::clone(&dp);
                thread::spawn(move || dp.relax_with_parent_int(i * 10, i * 100))
            })
            .collect();
        for h in handles {
            h.join().unwrap();
        }
        assert_eq!(dp.load_dist_int(), 10);
        assert_eq!(dp.load().0, 100 + 1, "parent must match the winning relax");
    }

    #[test]
    fn atomic_dist_parent_store_source_zeroes_int_distance() {
        // store_source is shared between f32 and integer modes: integer 0 has the
        // same bit pattern as 0.0_f32, so a source cell reads back as int dist 0.
        let dp = AtomicDistParent::int_infinity();
        dp.store_source();
        assert_eq!(dp.load_dist_int(), 0);
        assert_eq!(dp.load().0, 0);
    }

    #[test]
    fn atomic_dist_parent_vec_int_initializes_to_sentinel() {
        let v = atomic_dist_parent_vec_int(8);
        for dp in &v {
            assert_eq!(dp.load_dist_int(), u32::MAX);
            assert_eq!(dp.load().0, 0);
        }
    }

    #[test]
    fn pack_unpack_roundtrip() {
        let cases = [
            (0, 0u32),
            (1, 0u32),
            (42, 0x40000000u32), // 2.0 in f32 bits
            (u32::MAX - 1, f32::INFINITY.to_bits()),
        ];
        for &(parent, dist_bits) in &cases {
            let packed = pack(parent, dist_bits);
            assert_eq!(unpack_parent(packed), parent);
            assert_eq!(unpack_dist_bits(packed), dist_bits);
        }
    }
}