Skip to main content

spatialrust_search/
uniform_grid.rs

1use std::collections::HashMap;
2
3use spatialrust_core::{SpatialError, SpatialResult};
4
5/// Upper bound on dense grid cells; callers should fall back when exceeded.
6pub const MAX_UNIFORM_GRID_CELLS: u64 = 64_000_000;
7
8/// Returns grid origin (min corner) and cell counts for `cell_size`.
9///
10/// Axes must have equal lengths and finite coordinates. The cell size must be
11/// positive with a finite reciprocal; positive infinity yields a single cell.
12/// Nonfinite spans and grids exceeding [`MAX_UNIFORM_GRID_CELLS`] return errors.
13/// Empty axes retain the infinite origin and unit dimensions.
14pub fn grid_bounds(
15    x: &[f32],
16    y: &[f32],
17    z: &[f32],
18    cell_size: f32,
19) -> SpatialResult<([f32; 3], [u32; 3])> {
20    if x.len() != y.len() || x.len() != z.len() {
21        return Err(SpatialError::InvalidArgument("xyz arrays must have equal length".to_owned()));
22    }
23    if cell_size <= 0.0 || cell_size.is_nan() {
24        return Err(SpatialError::InvalidArgument("cell_size must be positive".to_owned()));
25    }
26    let inv_cell = 1.0 / cell_size;
27    if !inv_cell.is_finite() {
28        return Err(SpatialError::InvalidArgument(
29            "cell_size reciprocal must be finite".to_owned(),
30        ));
31    }
32    let mut min = [f32::INFINITY; 3];
33    let mut max = [f32::NEG_INFINITY; 3];
34    for index in 0..x.len() {
35        for (axis, value) in [x[index], y[index], z[index]].into_iter().enumerate() {
36            if !value.is_finite() {
37                return Err(SpatialError::InvalidArgument(
38                    "grid coordinates must be finite".to_owned(),
39                ));
40            }
41            min[axis] = min[axis].min(value);
42            max[axis] = max[axis].max(value);
43        }
44    }
45    if x.is_empty() || inv_cell == 0.0 {
46        return Ok((min, [1; 3]));
47    }
48    let mut dims = [1u32; 3];
49    let mut cells = 1u64;
50    for axis in 0..3 {
51        // Preserve the existing f32 mapping; validate before integer narrowing.
52        let span = ((max[axis] - min[axis]) * inv_cell).floor();
53        if !span.is_finite() {
54            return Err(SpatialError::InvalidArgument("grid span must be finite".to_owned()));
55        }
56        let dim = (span as u64)
57            .checked_add(1)
58            .ok_or_else(|| SpatialError::InvalidArgument("grid dimension overflows".to_owned()))?;
59        cells = cells
60            .checked_mul(dim)
61            .ok_or_else(|| SpatialError::InvalidArgument("grid cell count overflows".to_owned()))?;
62        if cells > MAX_UNIFORM_GRID_CELLS {
63            return Err(SpatialError::InvalidArgument(format!(
64                "grid would need {cells} cells (cap {MAX_UNIFORM_GRID_CELLS}); use a larger radius or the CPU path"
65            )));
66        }
67        dims[axis] = u32::try_from(dim).map_err(|_| {
68            SpatialError::InvalidArgument("grid dimension does not fit u32".to_owned())
69        })?;
70    }
71    Ok((min, dims))
72}
73
74/// Returns whether valid axes and cell size form a grid within the cell cap.
75///
76/// Invalid lengths, coordinates, scales and unrepresentable spans return false.
77pub fn uniform_grid_fits(x: &[f32], y: &[f32], z: &[f32], cell_size: f32) -> bool {
78    grid_bounds(x, y, z, cell_size).is_ok()
79}
80
81/// Stable counting-sort into grid cells, returning sorted indices and CSR offsets.
82///
83/// Reverse scattering reuses cumulative cell ends as the final start offsets,
84/// without an additional cell-sized cursor allocation.
85pub fn build_grid(
86    x: &[f32],
87    y: &[f32],
88    z: &[f32],
89    origin: [f32; 3],
90    dims: [u32; 3],
91    cell_size: f32,
92) -> (Vec<u32>, Vec<u32>) {
93    let inv_cell = 1.0 / cell_size;
94    let n = x.len();
95    let num_cells = dims[0] as usize * dims[1] as usize * dims[2] as usize;
96
97    let cell_of = |index: usize| -> usize {
98        let cx = (((x[index] - origin[0]) * inv_cell).floor() as i64).clamp(0, dims[0] as i64 - 1)
99            as usize;
100        let cy = (((y[index] - origin[1]) * inv_cell).floor() as i64).clamp(0, dims[1] as i64 - 1)
101            as usize;
102        let cz = (((z[index] - origin[2]) * inv_cell).floor() as i64).clamp(0, dims[2] as i64 - 1)
103            as usize;
104        (cz * dims[1] as usize + cy) * dims[0] as usize + cx
105    };
106
107    let mut counts = vec![0u32; num_cells + 1];
108    for index in 0..n {
109        counts[cell_of(index)] += 1;
110    }
111    inclusive_grid_prefix(&mut counts, n);
112
113    let mut sorted = vec![0u32; n];
114    // Descending input indices preserve ascending order within each cell.
115    // Decrementing each cumulative end exactly its count leaves its start.
116    for index in (0..n).rev() {
117        let cell = cell_of(index);
118        counts[cell] -= 1;
119        sorted[counts[cell] as usize] = index as u32;
120    }
121    (sorted, counts)
122}
123
124/// Connected-component roots via uniform-grid union-find (minimum index per component).
125pub fn euclidean_cluster_roots(
126    x: &[f32],
127    y: &[f32],
128    z: &[f32],
129    cluster_tolerance: f32,
130) -> SpatialResult<Vec<u32>> {
131    if x.len() != y.len() || x.len() != z.len() {
132        return Err(SpatialError::InvalidArgument("xyz arrays must have equal length".to_owned()));
133    }
134    let point_count = x.len();
135    if point_count == 0 {
136        return Ok(Vec::new());
137    }
138    if cluster_tolerance <= 0.0 || cluster_tolerance.is_nan() {
139        return Err(SpatialError::InvalidArgument("cluster_tolerance must be positive".to_owned()));
140    }
141
142    let (origin, dims) = grid_bounds(x, y, z, cluster_tolerance)?;
143    let (sorted, cell_start) = build_grid(x, y, z, origin, dims, cluster_tolerance);
144    let radius_sq = cluster_tolerance * cluster_tolerance;
145
146    #[cfg(all(feature = "parallel", not(target_arch = "wasm32")))]
147    if point_count >= PARALLEL_CLUSTER_MIN_POINTS {
148        return Ok(cluster_roots_parallel(
149            point_count,
150            x,
151            y,
152            z,
153            origin,
154            dims,
155            cluster_tolerance,
156            radius_sq,
157            &sorted,
158            &cell_start,
159        ));
160    }
161
162    Ok(cluster_roots_sequential(
163        point_count,
164        x,
165        y,
166        z,
167        origin,
168        dims,
169        cluster_tolerance,
170        radius_sq,
171        &sorted,
172        &cell_start,
173    ))
174}
175
176/// Computes Euclidean component roots from pre-built sparse grid segments.
177///
178/// This is the shared component-labeling phase for GPU-backed clustering: a
179/// backend may build and sort the sparse grid on an accelerator, then pass the
180/// compact segment metadata here for deterministic host-side union-find. The
181/// distance predicate and minimum-root semantics are identical to
182/// [`euclidean_cluster_roots`].
183pub fn euclidean_cluster_roots_from_segments(
184    x: &[f32],
185    y: &[f32],
186    z: &[f32],
187    cluster_tolerance: f32,
188    keys: &[(i64, i64, i64)],
189    point_indices: &[u32],
190    cell_starts: &[u32],
191    cell_counts: &[u32],
192) -> SpatialResult<Vec<u32>> {
193    if x.len() != y.len() || x.len() != z.len() {
194        return Err(SpatialError::InvalidArgument("xyz arrays must have equal length".to_owned()));
195    }
196    if cluster_tolerance <= 0.0 || cluster_tolerance.is_nan() {
197        return Err(SpatialError::InvalidArgument("cluster_tolerance must be positive".to_owned()));
198    }
199    if keys.len() != cell_starts.len() || keys.len() != cell_counts.len() {
200        return Err(SpatialError::BufferLengthMismatch {
201            expected: keys.len(),
202            found: cell_starts.len().max(cell_counts.len()),
203        });
204    }
205    if point_indices.len() != x.len() {
206        return Err(SpatialError::BufferLengthMismatch {
207            expected: x.len(),
208            found: point_indices.len(),
209        });
210    }
211    if x.is_empty() {
212        return Ok(Vec::new());
213    }
214
215    let mut cell_by_key = HashMap::with_capacity(keys.len());
216    for (cell, &key) in keys.iter().enumerate() {
217        if cell_by_key.insert(key, cell).is_some() {
218            return Err(SpatialError::InvalidArgument(
219                "sparse grid segments contain duplicate cell keys".to_owned(),
220            ));
221        }
222    }
223
224    let mut seen = vec![false; x.len()];
225    for cell in 0..keys.len() {
226        let start = cell_starts[cell] as usize;
227        let end = start.checked_add(cell_counts[cell] as usize).ok_or_else(|| {
228            SpatialError::InvalidArgument("sparse grid segment overflow".to_owned())
229        })?;
230        if end > point_indices.len() {
231            return Err(SpatialError::InvalidArgument(
232                "sparse grid segment exceeds point index buffer".to_owned(),
233            ));
234        }
235        for &point in &point_indices[start..end] {
236            let index = point as usize;
237            if index >= x.len() || std::mem::replace(&mut seen[index], true) {
238                return Err(SpatialError::InvalidArgument(
239                    "sparse grid point indices are not a permutation".to_owned(),
240                ));
241            }
242        }
243    }
244    if seen.iter().any(|present| !present) {
245        return Err(SpatialError::InvalidArgument(
246            "sparse grid point indices do not cover the input cloud".to_owned(),
247        ));
248    }
249
250    let radius_sq = cluster_tolerance * cluster_tolerance;
251    let mut parent: Vec<u32> = (0..x.len() as u32).collect();
252    for cell in 0..keys.len() {
253        let key = keys[cell];
254        let start = cell_starts[cell] as usize;
255        let end = start + cell_counts[cell] as usize;
256        for dz in -1_i64..=1 {
257            for dy in -1_i64..=1 {
258                for dx in -1_i64..=1 {
259                    let neighbor_key = (
260                        key.0.saturating_add(dx),
261                        key.1.saturating_add(dy),
262                        key.2.saturating_add(dz),
263                    );
264                    let Some(&neighbor_cell) = cell_by_key.get(&neighbor_key) else {
265                        continue;
266                    };
267                    let neighbor_start = cell_starts[neighbor_cell] as usize;
268                    let neighbor_end = neighbor_start + cell_counts[neighbor_cell] as usize;
269                    for &a in &point_indices[start..end] {
270                        let a = a as usize;
271                        for &b in &point_indices[neighbor_start..neighbor_end] {
272                            let b = b as usize;
273                            let dx = x[b] - x[a];
274                            let dy = y[b] - y[a];
275                            let dz = z[b] - z[a];
276                            if dx * dx + dy * dy + dz * dz <= radius_sq {
277                                union_min_root(&mut parent, a as u32, b as u32);
278                            }
279                        }
280                    }
281                }
282            }
283        }
284    }
285
286    Ok(compress_roots(&mut parent, x.len()))
287}
288
289/// Minimum point count before the `parallel` feature uses threaded union-find.
290#[cfg(all(feature = "parallel", not(target_arch = "wasm32")))]
291const PARALLEL_CLUSTER_MIN_POINTS: usize = 4_096;
292
293#[allow(clippy::too_many_arguments)]
294fn cluster_roots_sequential(
295    point_count: usize,
296    x: &[f32],
297    y: &[f32],
298    z: &[f32],
299    origin: [f32; 3],
300    dims: [u32; 3],
301    cluster_tolerance: f32,
302    radius_sq: f32,
303    sorted: &[u32],
304    cell_start: &[u32],
305) -> Vec<u32> {
306    let mut parent: Vec<u32> = (0..point_count as u32).collect();
307
308    for index in 0..point_count {
309        for neighbor in grid_radius_neighbors(
310            index,
311            x,
312            y,
313            z,
314            origin,
315            dims,
316            cluster_tolerance,
317            radius_sq,
318            sorted,
319            cell_start,
320        ) {
321            union_min_root(&mut parent, index as u32, neighbor as u32);
322        }
323    }
324
325    compress_roots(&mut parent, point_count)
326}
327
328#[cfg(all(feature = "parallel", not(target_arch = "wasm32")))]
329#[allow(clippy::too_many_arguments)]
330fn cluster_roots_parallel(
331    point_count: usize,
332    x: &[f32],
333    y: &[f32],
334    z: &[f32],
335    origin: [f32; 3],
336    dims: [u32; 3],
337    cluster_tolerance: f32,
338    radius_sq: f32,
339    sorted: &[u32],
340    cell_start: &[u32],
341) -> Vec<u32> {
342    use std::sync::atomic::{AtomicU32, Ordering};
343    use std::sync::Arc;
344
345    let parent: Arc<[AtomicU32]> =
346        (0..point_count as u32).map(AtomicU32::new).collect::<Vec<_>>().into();
347
348    let thread_count =
349        std::thread::available_parallelism().map_or(1, |count| count.get()).min(point_count).max(1);
350    let chunk = point_count.div_ceil(thread_count);
351
352    std::thread::scope(|scope| {
353        for thread in 0..thread_count {
354            let start = thread * chunk;
355            if start >= point_count {
356                break;
357            }
358            let end = (start + chunk).min(point_count);
359            let parent = Arc::clone(&parent);
360            scope.spawn(move || {
361                for index in start..end {
362                    for neighbor in grid_radius_neighbors(
363                        index,
364                        x,
365                        y,
366                        z,
367                        origin,
368                        dims,
369                        cluster_tolerance,
370                        radius_sq,
371                        sorted,
372                        cell_start,
373                    ) {
374                        atomic_union_min_root(&parent, index as u32, neighbor as u32);
375                    }
376                }
377            });
378        }
379    });
380
381    let mut parent_vec: Vec<u32> = parent.iter().map(|slot| slot.load(Ordering::Relaxed)).collect();
382    compress_roots(&mut parent_vec, point_count)
383}
384
385#[cfg(all(feature = "parallel", not(target_arch = "wasm32")))]
386fn atomic_union_min_root(parent: &[std::sync::atomic::AtomicU32], a: u32, b: u32) {
387    use std::sync::atomic::Ordering;
388
389    let mut ra = atomic_find_root(parent, a);
390    let mut rb = atomic_find_root(parent, b);
391    while ra != rb {
392        let (min_root, max_root) = if ra < rb { (ra, rb) } else { (rb, ra) };
393        match parent[max_root as usize].compare_exchange(
394            max_root,
395            min_root,
396            Ordering::Relaxed,
397            Ordering::Relaxed,
398        ) {
399            Ok(_) => return,
400            Err(current) => {
401                if current == min_root {
402                    return;
403                }
404                ra = atomic_find_root(parent, a);
405                rb = atomic_find_root(parent, b);
406            }
407        }
408    }
409}
410
411#[cfg(all(feature = "parallel", not(target_arch = "wasm32")))]
412fn atomic_find_root(parent: &[std::sync::atomic::AtomicU32], mut index: u32) -> u32 {
413    use std::sync::atomic::Ordering;
414
415    loop {
416        let parent_index = parent[index as usize].load(Ordering::Relaxed);
417        if parent_index == index {
418            return index;
419        }
420        index = parent_index;
421    }
422}
423
424fn compress_roots(parent: &mut [u32], point_count: usize) -> Vec<u32> {
425    let mut roots = vec![0u32; point_count];
426    for (index, root) in roots.iter_mut().enumerate() {
427        *root = find_root(parent, index as u32);
428    }
429    roots
430}
431
432fn find_root(parent: &mut [u32], mut index: u32) -> u32 {
433    let mut root = index;
434    while parent[root as usize] != root {
435        root = parent[root as usize];
436    }
437    while parent[index as usize] != root {
438        let next = parent[index as usize];
439        parent[index as usize] = root;
440        index = next;
441    }
442    root
443}
444
445fn union_min_root(parent: &mut [u32], a: u32, b: u32) {
446    let ra = find_root_readonly(parent, a);
447    let rb = find_root_readonly(parent, b);
448    if ra == rb {
449        return;
450    }
451    let (min_root, max_root) = if ra < rb { (ra, rb) } else { (rb, ra) };
452    parent[max_root as usize] = min_root;
453}
454
455fn find_root_readonly(parent: &[u32], mut index: u32) -> u32 {
456    while parent[index as usize] != index {
457        index = parent[index as usize];
458    }
459    index
460}
461
462#[allow(clippy::too_many_arguments)]
463fn grid_radius_neighbors<'a>(
464    index: usize,
465    x: &'a [f32],
466    y: &'a [f32],
467    z: &'a [f32],
468    origin: [f32; 3],
469    dims: [u32; 3],
470    tolerance: f32,
471    radius_sq: f32,
472    sorted: &'a [u32],
473    cell_start: &'a [u32],
474) -> GridRadiusNeighbors<'a> {
475    let cx = cell_coord(x[index], origin[0], 1.0 / tolerance, dims[0]);
476    let cy = cell_coord(y[index], origin[1], 1.0 / tolerance, dims[1]);
477    let cz = cell_coord(z[index], origin[2], 1.0 / tolerance, dims[2]);
478    GridRadiusNeighbors {
479        index,
480        x,
481        y,
482        z,
483        dims,
484        radius_sq,
485        sorted,
486        cell_start,
487        slot: 0,
488        end: 0,
489        ny: (cy - 1).max(0) as usize,
490        nz: (cz - 1).max(0) as usize,
491        first_y: (cy - 1).max(0) as usize,
492        after_y: (cy + 1).min(dims[1] as i32 - 1) as usize + 1,
493        after_z: (cz + 1).min(dims[2] as i32 - 1) as usize + 1,
494        first_x: (cx - 1).max(0) as usize,
495        after_x: (cx + 1).min(dims[0] as i32 - 1) as usize + 1,
496    }
497}
498
499struct GridRadiusNeighbors<'a> {
500    index: usize,
501    x: &'a [f32],
502    y: &'a [f32],
503    z: &'a [f32],
504    dims: [u32; 3],
505    radius_sq: f32,
506    sorted: &'a [u32],
507    cell_start: &'a [u32],
508    slot: u32,
509    end: u32,
510    ny: usize,
511    nz: usize,
512    first_y: usize,
513    after_y: usize,
514    after_z: usize,
515    first_x: usize,
516    after_x: usize,
517}
518
519impl Iterator for GridRadiusNeighbors<'_> {
520    type Item = usize;
521
522    fn next(&mut self) -> Option<Self::Item> {
523        loop {
524            if self.slot >= self.end {
525                if !self.advance_row() {
526                    return None;
527                }
528            } else {
529                let neighbor = self.sorted[self.slot as usize] as usize;
530                self.slot += 1;
531                if neighbor == self.index {
532                    continue;
533                }
534                let dx = self.x[neighbor] - self.x[self.index];
535                let dy = self.y[neighbor] - self.y[self.index];
536                let dz = self.z[neighbor] - self.z[self.index];
537                if dx * dx + dy * dy + dz * dz <= self.radius_sq {
538                    return Some(neighbor);
539                }
540            }
541        }
542    }
543}
544
545impl GridRadiusNeighbors<'_> {
546    fn advance_row(&mut self) -> bool {
547        if self.nz >= self.after_z {
548            return false;
549        }
550        // X cells are consecutive in both the grid and stable CSR order.
551        let row = (self.nz * self.dims[1] as usize + self.ny) * self.dims[0] as usize;
552        self.slot = self.cell_start[row + self.first_x];
553        self.end = self.cell_start[row + self.after_x];
554        self.ny += 1;
555        if self.ny >= self.after_y {
556            self.ny = self.first_y;
557            self.nz += 1;
558        }
559        true
560    }
561}
562
563fn cell_coord(value: f32, origin: f32, inv_cell: f32, dim: u32) -> i32 {
564    let cell = ((value - origin) * inv_cell).floor() as i32;
565    cell.clamp(0, dim as i32 - 1)
566}
567
568#[cfg(test)]
569mod tests {
570    use super::{euclidean_cluster_roots, euclidean_cluster_roots_from_segments};
571
572    #[test]
573    fn long_chain_is_one_component() {
574        let len = 300;
575        let spacing = 1.0;
576        let mut x = Vec::with_capacity(len);
577        for index in 0..len {
578            x.push(index as f32 * spacing);
579        }
580        let y = vec![0.0_f32; len];
581        let z = vec![0.0_f32; len];
582        let roots = euclidean_cluster_roots(&x, &y, &z, 1.5).unwrap();
583        assert!(roots.iter().all(|&root| root == 0));
584    }
585
586    #[test]
587    fn prebuilt_sparse_segments_match_direct_grid_roots() {
588        let x = [0.0_f32, 0.5, 2.0];
589        let y = [0.0_f32; 3];
590        let z = [0.0_f32; 3];
591        let expected = euclidean_cluster_roots(&x, &y, &z, 1.0).unwrap();
592        let actual = euclidean_cluster_roots_from_segments(
593            &x,
594            &y,
595            &z,
596            1.0,
597            &[(0, 0, 0), (2, 0, 0)],
598            &[0, 1, 2],
599            &[0, 2],
600            &[2, 1],
601        )
602        .unwrap();
603
604        assert_eq!(actual, expected);
605    }
606}
607
608#[cfg(test)]
609#[path = "uniform_grid_rows_tests.rs"]
610mod row_tests;
611
612#[cfg(test)]
613#[path = "uniform_grid_rows_benchmark.rs"]
614mod row_benchmark;
615
616#[cfg(test)]
617#[path = "uniform_grid_build_tests.rs"]
618mod build_tests;
619
620#[cfg(test)]
621#[path = "uniform_grid_build_benchmark.rs"]
622mod build_benchmark;
623
624#[cfg(test)]
625#[path = "uniform_grid_bounds_tests.rs"]
626mod bounds_tests;
627
628#[path = "grid_prefix.rs"]
629mod grid_prefix;
630use grid_prefix::inclusive_grid_prefix;