1use std::ops::Range;
9
10use spatialrust_core::SpatialTensor;
11
12use crate::chunked::{ChunkedNearestNeighborIndex, ChunkedRadiusSearchIndex};
13use crate::Neighbor;
14
15pub const PARALLEL_CHUNK_QUERY_MIN_POINTS: usize = 4_096;
17
18pub fn radius_search_spatial_tensor_parallel<I: ChunkedRadiusSearchIndex + Sync>(
20 index: &I,
21 x: &[f32],
22 y: &[f32],
23 z: &[f32],
24 tensor: &SpatialTensor<'_>,
25 radius: f32,
26) -> Vec<(usize, Neighbor)> {
27 let mut out = Vec::new();
28 radius_search_spatial_tensor_parallel_into(index, x, y, z, tensor, radius, &mut out);
29 out
30}
31
32pub fn radius_search_spatial_tensor_parallel_into<I: ChunkedRadiusSearchIndex + Sync>(
38 index: &I,
39 x: &[f32],
40 y: &[f32],
41 z: &[f32],
42 tensor: &SpatialTensor<'_>,
43 radius: f32,
44 out: &mut Vec<(usize, Neighbor)>,
45) {
46 dispatch_chunks(tensor, available_workers(), out, |range, local| {
47 index.radius_search_chunk_into(x, y, z, range, radius, local);
48 });
49}
50
51pub fn nearest_k_spatial_tensor_parallel<I: ChunkedNearestNeighborIndex + Sync>(
53 index: &I,
54 x: &[f32],
55 y: &[f32],
56 z: &[f32],
57 tensor: &SpatialTensor<'_>,
58 k: usize,
59) -> Vec<(usize, Neighbor)> {
60 let mut out = Vec::new();
61 nearest_k_spatial_tensor_parallel_into(index, x, y, z, tensor, k, &mut out);
62 out
63}
64
65pub fn nearest_k_spatial_tensor_parallel_into<I: ChunkedNearestNeighborIndex + Sync>(
71 index: &I,
72 x: &[f32],
73 y: &[f32],
74 z: &[f32],
75 tensor: &SpatialTensor<'_>,
76 k: usize,
77 out: &mut Vec<(usize, Neighbor)>,
78) {
79 if tensor.is_empty() || k == 0 {
80 return;
81 }
82 dispatch_chunks(tensor, available_workers(), out, |range, local| {
83 index.nearest_k_chunk_into(x, y, z, range, k, local);
84 });
85}
86
87pub(crate) fn available_workers() -> usize {
88 std::thread::available_parallelism().map_or(1, |count| count.get())
89}
90
91fn chunk_worker_count(point_count: usize, chunk_size: usize, available: usize) -> usize {
92 if point_count < PARALLEL_CHUNK_QUERY_MIN_POINTS {
93 return 1;
94 }
95 available.max(1).min(point_count.div_ceil(chunk_size))
96}
97
98pub(crate) fn dispatch_chunks<T: Send, Q>(
99 tensor: &SpatialTensor<'_>,
100 available: usize,
101 out: &mut Vec<T>,
102 query: Q,
103) where
104 Q: Fn(Range<usize>, &mut Vec<T>) + Sync,
105{
106 let point_count = tensor.len();
107 if point_count == 0 {
108 return;
109 }
110 let chunk_size = tensor.chunk_size();
111 let chunk_count = point_count.div_ceil(chunk_size);
112 let workers = chunk_worker_count(point_count, chunk_size, available);
113 let query_band = |chunks: Range<usize>, local: &mut Vec<T>| {
116 for chunk in chunks {
117 let start = chunk * chunk_size; let end = start + chunk_size.min(point_count - start);
119 query(start..end, local);
120 }
121 };
122 if workers == 1 {
123 query_band(0..chunk_count, out);
124 return;
125 }
126
127 let chunks_per_worker = chunk_count / workers;
128 let extra_chunks = chunk_count % workers;
129 std::thread::scope(|scope| {
130 let mut handles = Vec::with_capacity(workers);
131 for worker in 0..workers {
132 let start = worker * chunks_per_worker + worker.min(extra_chunks);
133 let end = start + chunks_per_worker + usize::from(worker < extra_chunks);
134 let query_band = &query_band;
135 handles.push(scope.spawn(move || {
136 let mut local = Vec::new();
137 query_band(start..end, &mut local);
138 local
139 }));
140 }
141
142 for handle in handles {
143 out.extend(handle.join().expect("bounded chunk query worker panicked"));
144 }
145 });
146}
147
148#[cfg(test)]
149mod tests {
150 use super::*;
151 use crate::{NearestNeighborIndex, RadiusSearchIndex, SpatialIndex};
152 use spatialrust_core::{PointCloud, PointCloudBuilder};
153 use std::{collections::HashSet, sync::Mutex, thread::ThreadId};
154
155 fn cloud(point_count: usize) -> PointCloud {
156 if point_count == 0 {
157 return PointCloud::xyz();
158 }
159 let mut builder = PointCloudBuilder::xyz();
160 for index in 0..point_count {
161 builder.push_point([index as f32, 0.0, 0.0]).unwrap();
162 }
163 builder.build().unwrap()
164 }
165
166 #[derive(Default)]
167 struct RecordingIndex {
168 calls: Mutex<Vec<(ThreadId, Range<usize>)>>,
169 }
170
171 impl RecordingIndex {
172 fn record(&self, range: Range<usize>, out: &mut Vec<(usize, Neighbor)>) {
173 self.calls.lock().unwrap().push((std::thread::current().id(), range.clone()));
174 for query in range.clone() {
177 for index in [range.end, range.start] {
178 out.push((query, Neighbor { index, distance_squared: query as f32 }));
179 }
180 }
181 }
182 }
183
184 impl SpatialIndex for RecordingIndex {
185 fn len(&self) -> usize {
186 0
187 }
188 }
189 impl RadiusSearchIndex for RecordingIndex {
190 fn radius_search(&self, _: f32, _: f32, _: f32, _: f32) -> Vec<Neighbor> {
191 unreachable!("dispatch must use original chunk callbacks")
192 }
193 }
194 impl NearestNeighborIndex for RecordingIndex {
195 fn nearest_one(&self, _: f32, _: f32, _: f32) -> Option<Neighbor> {
196 unreachable!()
197 }
198 fn nearest_k(&self, _: f32, _: f32, _: f32, _: usize) -> Vec<Neighbor> {
199 unreachable!()
200 }
201 }
202 impl ChunkedRadiusSearchIndex for RecordingIndex {
203 fn radius_search_chunk_into(
204 &self,
205 _: &[f32],
206 _: &[f32],
207 _: &[f32],
208 chunk: Range<usize>,
209 _: f32,
210 out: &mut Vec<(usize, Neighbor)>,
211 ) {
212 self.record(chunk, out);
213 }
214 }
215 impl ChunkedNearestNeighborIndex for RecordingIndex {
216 fn nearest_k_chunk_into(
217 &self,
218 _: &[f32],
219 _: &[f32],
220 _: &[f32],
221 chunk: Range<usize>,
222 _: usize,
223 out: &mut Vec<(usize, Neighbor)>,
224 ) {
225 self.record(chunk, out);
226 }
227 }
228
229 fn prefix() -> Vec<(usize, Neighbor)> {
230 vec![(usize::MAX, Neighbor { index: usize::MAX, distance_squared: -1.0 })]
231 }
232
233 #[test]
234 fn worker_policy_bounds_threads_including_tiny_and_partial_chunks() {
235 for available in [0, 1, 2, 6, usize::MAX] {
236 let cap = available.max(1);
237 assert_eq!(chunk_worker_count(0, 1, available), 1);
238 assert_eq!(chunk_worker_count(4095, 1, available), 1);
239 assert_eq!(chunk_worker_count(4096, 1, available), cap.min(4096));
240 assert_eq!(chunk_worker_count(4097, 4096, available), cap.min(2));
241 assert_eq!(chunk_worker_count(4096, usize::MAX, available), 1);
242 assert_eq!(chunk_worker_count(usize::MAX, usize::MAX, available), 1);
243 assert_eq!(
244 chunk_worker_count(usize::MAX, 2, available),
245 cap.min(usize::MAX.div_ceil(2))
246 );
247 }
248 }
249
250 #[test]
251 fn bounded_dispatch_preserves_callbacks_order_and_append_prefix() {
252 let cloud = cloud(4103);
253 for chunk_size in [1, 7, 512, 4103, usize::MAX] {
254 let tensor = cloud.spatial_tensor_chunks(chunk_size).unwrap();
255 for available in [1, 2, 6] {
256 let index = RecordingIndex::default();
257 let mut actual = prefix();
258 dispatch_chunks(&tensor, available, &mut actual, |range, out| {
259 index.record(range, out)
260 });
261 let mut expected = prefix();
262 let mut expected_ranges = Vec::new();
263 for start in (0..cloud.len()).step_by(chunk_size) {
264 let range = start..start + chunk_size.min(cloud.len() - start);
265 expected_ranges.push(range.clone());
266 RecordingIndex::default().record(range, &mut expected);
267 }
268 assert_eq!(actual, expected, "chunk={chunk_size}, workers={available}");
269 let calls = index.calls.lock().unwrap();
270 let mut ranges: Vec<_> = calls.iter().map(|(_, range)| range.clone()).collect();
271 ranges.sort_by_key(|range| range.start);
272 assert_eq!(ranges, expected_ranges);
273 let threads: HashSet<_> = calls.iter().map(|(id, _)| *id).collect();
274 let workers = chunk_worker_count(cloud.len(), chunk_size, available);
275 assert_eq!(threads.len(), workers);
276 let counts: Vec<_> = threads
277 .iter()
278 .map(|id| {
279 let ranges: Vec<_> = calls
280 .iter()
281 .filter(|(thread, _)| thread == id)
282 .map(|(_, range)| range)
283 .collect();
284 for pair in ranges.windows(2) {
285 assert_eq!(pair[0].end, pair[1].start);
286 }
287 ranges.len()
288 })
289 .collect();
290 assert!(counts.iter().max().unwrap() - counts.iter().min().unwrap() <= 1);
291 if workers == 1 {
292 assert!(threads.contains(&std::thread::current().id()));
293 } else {
294 assert!(!threads.contains(&std::thread::current().id()));
295 }
296 }
297 }
298 }
299
300 #[test]
301 fn public_radius_and_knn_append_unsorted_results_for_generic_backend() {
302 let cloud = cloud(4103);
303 let tensor = cloud.spatial_tensor_chunks(1).unwrap();
304 let expected_index = RecordingIndex::default();
305 let mut expected = prefix();
306 crate::radius_search_spatial_tensor(
307 &expected_index,
308 &[],
309 &[],
310 &[],
311 &tensor,
312 2.0,
313 &mut expected,
314 );
315 let index = RecordingIndex::default();
316 let mut radius = prefix();
317 radius_search_spatial_tensor_parallel_into(
318 &index,
319 &[],
320 &[],
321 &[],
322 &tensor,
323 2.0,
324 &mut radius,
325 );
326 assert_eq!(radius, expected);
327 let mut knn = prefix();
328 nearest_k_spatial_tensor_parallel_into(&index, &[], &[], &[], &tensor, 2, &mut knn);
329 assert_eq!(knn, expected);
330 assert_eq!(
331 radius_search_spatial_tensor_parallel(&index, &[], &[], &[], &tensor, 2.0),
332 expected[1..]
333 );
334 assert_eq!(
335 nearest_k_spatial_tensor_parallel(&index, &[], &[], &[], &tensor, 2),
336 expected[1..]
337 );
338 let calls = index.calls.lock().unwrap();
339 let threads: HashSet<_> = calls.iter().map(|(id, _)| *id).collect();
340 assert!(threads.len() <= 4 * available_workers().min(tensor.len()));
342 }
343
344 #[test]
345 fn small_single_chunk_empty_and_zero_k_keep_caller_or_noop_behavior() {
346 for (point_count, chunk_size) in [(0, 1), (4095, 1), (4096, 4096)] {
347 let cloud = cloud(point_count);
348 let tensor = cloud.spatial_tensor_chunks(chunk_size).unwrap();
349 let index = RecordingIndex::default();
350 let mut out = prefix();
351 radius_search_spatial_tensor_parallel_into(
352 &index,
353 &[],
354 &[],
355 &[],
356 &tensor,
357 1.0,
358 &mut out,
359 );
360 nearest_k_spatial_tensor_parallel_into(&index, &[], &[], &[], &tensor, 1, &mut out);
361 let calls = index.calls.lock().unwrap();
362 assert!(calls.iter().all(|(id, _)| *id == std::thread::current().id()));
363 if point_count == 0 {
364 assert_eq!(out, prefix());
365 }
366 }
367 let cloud = cloud(4103);
368 let tensor = cloud.spatial_tensor_chunks(1).unwrap();
369 let index = RecordingIndex::default();
370 let mut out = prefix();
371 nearest_k_spatial_tensor_parallel_into(&index, &[], &[], &[], &tensor, 0, &mut out);
372 assert_eq!(out, prefix());
373 assert!(index.calls.lock().unwrap().is_empty());
374 }
375
376 #[cfg(feature = "search-kdtree")]
377 #[test]
378 fn kdtree_radius_and_knn_match_sequential_without_sorting() {
379 let mut builder = PointCloudBuilder::xyz();
380 for i in 0..4103 {
381 builder
383 .push_point([(i % 67) as f32 - 33.0, ((i / 67) % 61) as f32 - 30.0, 0.0])
384 .unwrap();
385 }
386 let cloud = builder.build().unwrap();
387 let x = cloud.field("x").unwrap().as_f32().unwrap();
388 let y = cloud.field("y").unwrap().as_f32().unwrap();
389 let z = cloud.field("z").unwrap().as_f32().unwrap();
390 let tree = crate::KdTree::from_slices(x, y, z);
391 for chunk_size in [1, 7, 512, 4103] {
392 let tensor = cloud.spatial_tensor_chunks(chunk_size).unwrap();
393 let mut radius = prefix();
394 crate::radius_search_spatial_tensor(&tree, x, y, z, &tensor, 1.5, &mut radius);
395 let mut knn = prefix();
396 crate::nearest_k_spatial_tensor(&tree, x, y, z, &tensor, 8, &mut knn);
397 for workers in [1, 2, 6] {
398 let mut actual = prefix();
399 dispatch_chunks(&tensor, workers, &mut actual, |range, out| {
400 tree.radius_search_chunk_into(x, y, z, range, 1.5, out);
401 });
402 assert_eq!(actual, radius);
403 let mut actual = prefix();
404 dispatch_chunks(&tensor, workers, &mut actual, |range, out| {
405 tree.nearest_k_chunk_into(x, y, z, range, 8, out);
406 });
407 assert_eq!(actual, knn);
408 }
409 let mut actual = prefix();
410 radius_search_spatial_tensor_parallel_into(&tree, x, y, z, &tensor, 1.5, &mut actual);
411 assert_eq!(actual, radius);
412 let mut actual = prefix();
413 nearest_k_spatial_tensor_parallel_into(&tree, x, y, z, &tensor, 8, &mut actual);
414 assert_eq!(actual, knn);
415 }
416 }
417}