Skip to main content

spatialrust_search/
chunked.rs

1//! Chunk-oriented query extensions for [`SpatialIndex`](crate::SpatialIndex) backends.
2//!
3//! These traits align query batching with [`SpatialTensor`](spatialrust_core::SpatialTensor)
4//! chunk iteration for parallel CPU/GPU algorithms.
5
6use std::ops::Range;
7
8use spatialrust_core::SpatialTensor;
9
10use crate::{Neighbor, RadiusSearchIndex};
11
12/// Range of query point indices (matches [`SpatialTensor::chunks`] ranges).
13pub type ChunkQueryRange = Range<usize>;
14
15/// Radius search over contiguous query index ranges.
16pub trait ChunkedRadiusSearchIndex: RadiusSearchIndex {
17    /// Appends `(query_index, neighbor)` for each point index in `chunk`.
18    fn radius_search_chunk_into(
19        &self,
20        x: &[f32],
21        y: &[f32],
22        z: &[f32],
23        chunk: ChunkQueryRange,
24        radius: f32,
25        out: &mut Vec<(usize, Neighbor)>,
26    );
27
28    /// Radius search for a single indexed query point.
29    fn radius_search_at(
30        &self,
31        x: &[f32],
32        y: &[f32],
33        z: &[f32],
34        index: usize,
35        radius: f32,
36    ) -> Vec<Neighbor> {
37        self.radius_search(x[index], y[index], z[index], radius)
38    }
39}
40
41/// k-NN search over contiguous query index ranges.
42pub trait ChunkedNearestNeighborIndex: crate::NearestNeighborIndex {
43    /// Appends `(query_index, neighbor)` for each point index in `chunk`.
44    fn nearest_k_chunk_into(
45        &self,
46        x: &[f32],
47        y: &[f32],
48        z: &[f32],
49        chunk: ChunkQueryRange,
50        k: usize,
51        out: &mut Vec<(usize, Neighbor)>,
52    );
53}
54
55/// Runs radius search for every chunk in a [`SpatialTensor`], appending tagged neighbors.
56pub fn radius_search_spatial_tensor<I: ChunkedRadiusSearchIndex>(
57    index: &I,
58    x: &[f32],
59    y: &[f32],
60    z: &[f32],
61    tensor: &SpatialTensor<'_>,
62    radius: f32,
63    out: &mut Vec<(usize, Neighbor)>,
64) {
65    for chunk in tensor.chunks() {
66        index.radius_search_chunk_into(x, y, z, chunk.range(), radius, out);
67    }
68}
69
70/// Runs k-NN search for every chunk in a [`SpatialTensor`], appending tagged neighbors.
71pub fn nearest_k_spatial_tensor<I: ChunkedNearestNeighborIndex>(
72    index: &I,
73    x: &[f32],
74    y: &[f32],
75    z: &[f32],
76    tensor: &SpatialTensor<'_>,
77    k: usize,
78    out: &mut Vec<(usize, Neighbor)>,
79) {
80    for chunk in tensor.chunks() {
81        index.nearest_k_chunk_into(x, y, z, chunk.range(), k, out);
82    }
83}
84
85#[cfg(test)]
86mod tests {
87    use super::{
88        nearest_k_spatial_tensor, radius_search_spatial_tensor, ChunkedNearestNeighborIndex,
89        ChunkedRadiusSearchIndex,
90    };
91    #[cfg(feature = "search-kdtree")]
92    use crate::kdtree::KdTree;
93    use crate::{brute::BruteForceIndex, RadiusSearchIndex};
94    use spatialrust_core::{PointCloudBuilder, StandardSchemas};
95
96    fn sample_cloud() -> (Vec<f32>, Vec<f32>, Vec<f32>) {
97        (
98            vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
99            vec![0.0, 0.0, 0.0, 1.0, 2.0, 0.0],
100            vec![0.0, 0.0, 0.0, 0.0, 0.0, 5.0],
101        )
102    }
103
104    fn chunked_matches_per_index<I>(index: &I, radius: f32)
105    where
106        I: ChunkedRadiusSearchIndex + RadiusSearchIndex,
107    {
108        let (x, y, z) = sample_cloud();
109        let mut chunked = Vec::new();
110        index.radius_search_chunk_into(&x, &y, &z, 1..4, radius, &mut chunked);
111
112        let mut expected = Vec::new();
113        for query in 1..4 {
114            for neighbor in index.radius_search_at(&x, &y, &z, query, radius) {
115                expected.push((query, neighbor));
116            }
117        }
118
119        chunked.sort_by_key(|a| (a.0, a.1.index));
120        expected.sort_by_key(|a| (a.0, a.1.index));
121        assert_eq!(chunked, expected);
122    }
123
124    #[cfg(feature = "search-kdtree")]
125    #[test]
126    fn kdtree_chunked_radius_matches_per_index() {
127        let (x, y, z) = sample_cloud();
128        let tree = KdTree::from_slices(&x, &y, &z);
129        chunked_matches_per_index(&tree, 1.5);
130    }
131
132    #[test]
133    fn brute_chunked_radius_matches_per_index() {
134        let (x, y, z) = sample_cloud();
135        let index = BruteForceIndex::from_slices(&x, &y, &z);
136        chunked_matches_per_index(&index, 1.5);
137    }
138
139    #[test]
140    fn spatial_tensor_radius_matches_full_scan() {
141        let (x, y, z) = sample_cloud();
142        let index = BruteForceIndex::from_slices(&x, &y, &z);
143
144        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
145        for index in 0..x.len() {
146            builder.push_point([x[index], y[index], z[index]]).unwrap();
147        }
148        let cloud = builder.build().unwrap();
149        let tensor = cloud.spatial_tensor_chunks(2).unwrap();
150
151        let mut tensor_out = Vec::new();
152        radius_search_spatial_tensor(&index, &x, &y, &z, &tensor, 1.5, &mut tensor_out);
153
154        let mut full_out = Vec::new();
155        index.radius_search_chunk_into(&x, &y, &z, 0..x.len(), 1.5, &mut full_out);
156
157        tensor_out.sort_by_key(|a| (a.0, a.1.index));
158        full_out.sort_by_key(|a| (a.0, a.1.index));
159        assert_eq!(tensor_out, full_out);
160    }
161
162    #[test]
163    fn spatial_tensor_nearest_k_matches_full_scan() {
164        let (x, y, z) = sample_cloud();
165        let index = BruteForceIndex::from_slices(&x, &y, &z);
166
167        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
168        for index in 0..x.len() {
169            builder.push_point([x[index], y[index], z[index]]).unwrap();
170        }
171        let cloud = builder.build().unwrap();
172        let tensor = cloud.spatial_tensor_chunks(2).unwrap();
173
174        let mut tensor_out = Vec::new();
175        nearest_k_spatial_tensor(&index, &x, &y, &z, &tensor, 2, &mut tensor_out);
176
177        let mut full_out = Vec::new();
178        index.nearest_k_chunk_into(&x, &y, &z, 0..x.len(), 2, &mut full_out);
179
180        tensor_out.sort_by(|a, b| {
181            a.0.cmp(&b.0)
182                .then(
183                    a.1.distance_squared
184                        .partial_cmp(&b.1.distance_squared)
185                        .unwrap_or(std::cmp::Ordering::Equal),
186                )
187                .then(a.1.index.cmp(&b.1.index))
188        });
189        full_out.sort_by(|a, b| {
190            a.0.cmp(&b.0)
191                .then(
192                    a.1.distance_squared
193                        .partial_cmp(&b.1.distance_squared)
194                        .unwrap_or(std::cmp::Ordering::Equal),
195                )
196                .then(a.1.index.cmp(&b.1.index))
197        });
198        assert_eq!(tensor_out, full_out);
199    }
200}