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
//! Reusable scratch state for repeated point-to-point Dijkstra queries on the
//! **same** volume.

use crate::connectivity_graph::ConnectivityGraph;
use crate::dijkstra::{checked_int_distance_bound, Dist, IntQueue};
use crate::neighborhood::{neighborhood_masks, neighborhood_offsets, DIRECTIONS_26};
use crate::queue::binary_heap::BinaryHeapQueue;
use crate::queue::bucket::BucketQueue;
use crate::voxel::{ToU64Fast, VolumeShape};
use crate::{Connectivity, Dijkstra3dError, Result};

/// Largest edge-weight range that still fits the bucket (Dial) queue. Mirrors
/// the threshold in `dijkstra_unidirectional_slice_int`.
const MAX_BUCKET_RANGE: u64 = 65_536;

/// The persistent priority queue, selected once from the field's weight range.
enum WsQueue {
    /// Small integer weight range: `O(1)` bucket (Dial) queue.
    Bucket(BucketQueue),
    /// Large weight range: binary heap keyed on `u64` distances.
    Heap(BinaryHeapQueue<u64, u32>),
}

enum WsDist {
    /// `dist_bound <= u32::MAX` (covers all u8/u16 fields and most u32).
    U32(Vec<u32>),
    /// Larger bounds.
    U64(Vec<u64>),
}

/// Reusable Dijkstra scratch for repeated queries on a fixed volume.
pub struct DijkstraWorkspace {
    shape: VolumeShape,

    distances: WsDist,

    parents: Vec<u32>,

    gen: Vec<u32>,

    generation: u32,

    max_weight: u64,

    queue: WsQueue,
}

impl DijkstraWorkspace {
    /// Allocate a workspace for a volume of `shape` whose maximum edge weight is
    /// `max_weight`.
    pub fn with_capacity(shape: VolumeShape, max_weight: u64) -> Result<Self> {
        let total = shape.total();
        if total > u32::MAX as u64 {
            return Err(Dijkstra3dError::InvalidInput(format!(
                "DijkstraWorkspace: volume {total} exceeds u32::MAX voxels; \
                 use the u64/f32 path"
            )));
        }
        let dist_bound = checked_int_distance_bound(shape, max_weight)?;
        let total = total as usize;
        let queue = if max_weight < MAX_BUCKET_RANGE {
            WsQueue::Bucket(BucketQueue::with_capacity(max_weight as u32))
        } else {
            WsQueue::Heap(BinaryHeapQueue::<u64, u32>::new())
        };

        let distances = if dist_bound <= u32::MAX as u64 {
            WsDist::U32(vec![u32::MAX; total])
        } else {
            WsDist::U64(vec![u64::MAX; total])
        };
        Ok(Self {
            shape,
            distances,
            parents: vec![0u32; total],
            gen: vec![0u32; total],
            generation: 0,
            max_weight,
            queue,
        })
    }

    /// Build a workspace pinned to `field`, scanning its maximum weight once.
    pub fn for_field<T: ToU64Fast>(field: &[T], shape: VolumeShape) -> Result<Self> {
        let total = shape.total();
        if field.len() as u64 != total {
            return Err(Dijkstra3dError::InvalidInput(format!(
                "DijkstraWorkspace::for_field: slice length {} != shape.total() {}",
                field.len(),
                total
            )));
        }
        let max_weight = field.iter().map(|&v| v.to_u64_fast()).max().unwrap_or(0);
        Self::with_capacity(shape, max_weight)
    }

    /// The volume shape this workspace serves.
    #[inline]
    pub fn shape(&self) -> VolumeShape {
        self.shape
    }

    /// The maximum edge weight the workspace was sized for.
    #[inline]
    pub fn max_weight(&self) -> u64 {
        self.max_weight
    }

    /// Advance to a fresh query generation and reset the queue. `O(1)` except
    /// on the ~once-per-2^32-queries generation wrap (then `O(total)`).
    #[inline]
    fn begin_query(&mut self) {
        self.generation = self.generation.wrapping_add(1);
        if self.generation == 0 {
            // Wrapped: no old stamp may alias the new generation. Clear stamps
            // and restart at 1. Rare enough (every 2^32 queries) to be free.
            for g in self.gen.iter_mut() {
                *g = 0;
            }
            self.generation = 1;
        }
        match &mut self.queue {
            WsQueue::Bucket(q) => q.reset(),
            WsQueue::Heap(q) => q.clear(),
        }
    }

    /// Compute the shortest path from `source` to `target` through `field`,
    /// reusing the pinned scratch.
    pub fn shortest_path<T: ToU64Fast>(
        &mut self,
        field: &[T],
        source: u64,
        target: u64,
        connectivity: Connectivity,
        graph: Option<ConnectivityGraph<'_>>,
    ) -> Result<Vec<u64>> {
        let total = self.shape.total();
        if field.len() as u64 != total {
            return Err(Dijkstra3dError::InvalidInput(format!(
                "DijkstraWorkspace::shortest_path: slice length {} != shape.total() {}",
                field.len(),
                total
            )));
        }
        if source >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: source,
                volume_size: total,
            });
        }
        if target >= total {
            return Err(Dijkstra3dError::OutOfBounds {
                idx: target,
                volume_size: total,
            });
        }
        if source == target {
            return Ok(vec![source]);
        }

        self.begin_query();

        let generation = self.generation;
        let shape = self.shape;
        // Split the disjoint field borrows so the search can hold `queue` and
        // the buffers mutably at once, then monomorphize over (distance width,
        // queue).
        let Self {
            distances,
            parents,
            gen,
            queue,
            ..
        } = self;
        macro_rules! dispatch {
            ($dist:expr) => {
                match queue {
                    WsQueue::Bucket(q) => generation_search(
                        field,
                        shape,
                        source,
                        target,
                        connectivity,
                        graph,
                        $dist,
                        parents,
                        gen,
                        generation,
                        q,
                    ),
                    WsQueue::Heap(q) => generation_search(
                        field,
                        shape,
                        source,
                        target,
                        connectivity,
                        graph,
                        $dist,
                        parents,
                        gen,
                        generation,
                        q,
                    ),
                }
            };
        }
        match distances {
            WsDist::U32(d) => dispatch!(d.as_mut_slice()),
            WsDist::U64(d) => dispatch!(d.as_mut_slice()),
        }
    }
}

/// Reconstruct `source -> target` from the `+1`-sentinel parent array. All path
/// cells were stamped in the current generation, so their parents are live.
fn reconstruct(parents: &[u32], source: u64, target: u64) -> Vec<u64> {
    let mut path = vec![target];
    let mut current = target;
    while current != source {
        let parent = parents[current as usize];
        if parent == 0 {
            break;
        }
        current = (parent - 1) as u64;
        path.push(current);
    }
    path.reverse();
    path
}

/// Generation-stamped integer Dijkstra, monomorphized over the queue `Q` and
/// the distance-accumulator width `D` (`u32`/`u64`, via [`Dist`]).
#[allow(clippy::too_many_arguments)]
fn generation_search<T: ToU64Fast, Q: IntQueue, D: Dist>(
    field: &[T],
    shape: VolumeShape,
    source: u64,
    target: u64,
    connectivity: Connectivity,
    graph: Option<ConnectivityGraph<'_>>,
    distances: &mut [D],
    parents: &mut [u32],
    gen: &mut [u32],
    generation: u32,
    queue: &mut Q,
) -> Result<Vec<u64>> {
    let source_us = source as usize;
    distances[source_us] = D::ZERO;
    parents[source_us] = 0;
    gen[source_us] = generation;
    queue.push_i(0, source as u32);

    let sx_i = shape.sx as i64;
    let sxy_i = (shape.sx * shape.sy) as i64;
    let offsets = neighborhood_offsets(sx_i, sxy_i);
    let masks = neighborhood_masks();
    let neighbor_count = connectivity.count();

    let sx_u = shape.sx as i64;
    let sy_u = shape.sy as i64;
    let sz_u = shape.sz as i64;

    while let Some((dist, loc)) = queue.pop_i() {
        let loc_us = loc as usize;
        // A popped loc was stamped `generation` when pushed, so `distances`
        // is live: lazy-delete stale queue entries.
        if dist > distances[loc_us].to_priority() {
            continue;
        }
        if loc as u64 == target {
            return Ok(reconstruct(parents, source, target));
        }

        let current_dist = distances[loc_us];
        let (lx, ly, lz) = shape.coords(loc as u64);

        for i in 0..neighbor_count {
            let (dx, dy, dz) = DIRECTIONS_26[i];

            let nx = lx as i64 + dx as i64;
            let ny = ly as i64 + dy as i64;
            let nz = lz as i64 + dz as i64;
            if nx < 0 || nx >= sx_u || ny < 0 || ny >= sy_u || nz < 0 || nz >= sz_u {
                continue;
            }

            let neighbor = (loc as i64 + offsets[i]) as u64;
            let neighbor_us = neighbor as usize;

            if let Some(ref g) = graph {
                if !g.allows(loc as u64, masks[i]) {
                    continue;
                }
            }

            let neighbor_cost = field[neighbor_us].to_u64_fast();
            let new_dist = current_dist.add_cost(neighbor_cost);

            // Effective best-known distance at neighbor: the sentinel unless
            // touched by this query.
            let nb_best = if gen[neighbor_us] == generation {
                distances[neighbor_us]
            } else {
                D::MAX
            };

            if new_dist < nb_best {
                distances[neighbor_us] = new_dist;
                parents[neighbor_us] = loc + 1; // +1 sentinel encoding
                gen[neighbor_us] = generation;
                queue.push_i(new_dist.to_priority(), neighbor as u32);
            }
        }
    }

    Err(Dijkstra3dError::Unreachable)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::dijkstra::dijkstra_unidirectional_slice_int;
    use rand::rngs::StdRng;
    use rand::{Rng, SeedableRng};

    #[test]
    fn workspace_matches_oneshot_repeated() {
        let conns = [
            Connectivity::Six,
            Connectivity::Eighteen,
            Connectivity::TwentySix,
        ];
        let mut rng = StdRng::seed_from_u64(0x5EED_0071);

        for trial in 0..200u64 {
            let a = rng.random_range(2u64..=14);
            let b = rng.random_range(2u64..=14);
            let c = rng.random_range(2u64..=14);
            let shape = VolumeShape::new(a, b, c);
            let total = shape.total() as usize;

            let field: Vec<u32> = match trial % 3 {
                0 => (0..total).map(|_| rng.random_range(1..=8u32)).collect(),
                1 => (0..total).map(|_| rng.random_range(1..=5000u32)).collect(),
                _ => {
                    let mut f: Vec<u32> =
                        (0..total).map(|_| rng.random_range(1..=100u32)).collect();
                    // A single huge weight forces the binary-heap branch.
                    f[total / 2] = 5_000_000;
                    f
                }
            };

            let mut ws = DijkstraWorkspace::for_field(&field, shape).unwrap();

            // Several queries on the same workspace exercise reset and reuse.
            for _ in 0..6 {
                let src = rng.random_range(0..total as u64);
                let mut tgt = rng.random_range(0..total as u64);
                if tgt == src {
                    tgt = (tgt + 1) % total as u64;
                }
                let conn = conns[rng.random_range(0..3)];

                let ws_path = ws.shortest_path(&field, src, tgt, conn, None);
                let one = dijkstra_unidirectional_slice_int(&field, shape, src, tgt, conn, None);
                match (ws_path, one) {
                    (Ok(p), Ok(q)) => assert_eq!(
                        p, q,
                        "path mismatch trial={trial} src={src} tgt={tgt} conn={conn:?}"
                    ),
                    (Err(_), Err(_)) => {}
                    (a, b) => panic!("Ok/Err disagreement: {a:?} vs {b:?}"),
                }
            }
        }
    }

    /// source == target returns the singleton path (parity with the engine).
    #[test]
    fn workspace_source_equals_target() {
        let shape = VolumeShape::new(4, 4, 4);
        let field = vec![3u32; shape.total() as usize];
        let mut ws = DijkstraWorkspace::for_field(&field, shape).unwrap();
        let s = shape.linear(1, 1, 1);
        assert_eq!(
            ws.shortest_path(&field, s, s, Connectivity::Six, None)
                .unwrap(),
            vec![s]
        );
    }

    #[test]
    fn workspace_generation_wrap_is_correct() {
        let shape = VolumeShape::new(6, 6, 6);
        let total = shape.total() as usize;
        let mut rng = StdRng::seed_from_u64(0xC0FFEE);
        let field: Vec<u16> = (0..total).map(|_| rng.random_range(1..=20u16)).collect();
        let mut ws = DijkstraWorkspace::for_field(&field, shape).unwrap();

        // Drive the generation counter to just below wrap, then across it, so
        // begin_query hits the `generation == 0` reset branch on a live buffer.
        ws.generation = u32::MAX - 1;

        let src = shape.linear(0, 0, 0);
        let tgt = shape.linear(5, 5, 5);
        for _ in 0..4 {
            let ws_path = ws
                .shortest_path(&field, src, tgt, Connectivity::TwentySix, None)
                .unwrap();
            let one = dijkstra_unidirectional_slice_int(
                &field,
                shape,
                src,
                tgt,
                Connectivity::TwentySix,
                None,
            )
            .unwrap();
            assert_eq!(ws_path, one, "mismatch around generation wrap");
        }
        // Confirm the wrap actually happened (generation restarted small).
        assert!(
            ws.generation < 8,
            "generation should have wrapped, got {}",
            ws.generation
        );
    }

    /// Length-mismatch / out-of-bounds errors mirror the one-shot engine.
    #[test]
    fn workspace_input_validation() {
        let shape = VolumeShape::new(4, 4, 4);
        let field = vec![1u8; shape.total() as usize];
        let mut ws = DijkstraWorkspace::for_field(&field, shape).unwrap();
        let total = shape.total();
        // Out-of-bounds source/target.
        assert!(matches!(
            ws.shortest_path(&field, total, 0, Connectivity::Six, None),
            Err(Dijkstra3dError::OutOfBounds { .. })
        ));
        assert!(matches!(
            ws.shortest_path(&field, 0, total, Connectivity::Six, None),
            Err(Dijkstra3dError::OutOfBounds { .. })
        ));
        // Wrong field length.
        let short = vec![1u8; 3];
        assert!(matches!(
            ws.shortest_path(&short, 0, 1, Connectivity::Six, None),
            Err(Dijkstra3dError::InvalidInput(_))
        ));
    }

    #[test]
    fn workspace_rejects_unrepresentable_distance_bound() {
        let shape = VolumeShape::new(2, 2, 2);

        assert!(matches!(
            DijkstraWorkspace::with_capacity(shape, u64::MAX),
            Err(Dijkstra3dError::InvalidInput(_))
        ));
    }
}