1use std::num::NonZero;
2
3use spatial_index::{
4 EytzingerAdaptive, KdTree, SquaredEuclidean, VecOfArrays, dist::DistanceMetricScalar,
5};
6
7use crate::NodeId;
8
9use super::{Coordinate, Node};
10
11pub(crate) const POS_INDEX_BUCKET_SIZE: usize = 128;
19
20pub(crate) type PosIndex = KdTree<
26 f32,
27 NodeId,
28 EytzingerAdaptive,
29 VecOfArrays<f32, NodeId, 3, POS_INDEX_BUCKET_SIZE>,
30 3,
31 POS_INDEX_BUCKET_SIZE,
32>;
33
34#[derive(Debug, Clone, Copy)]
36pub enum PosQueryCount {
37 All,
39 Count(usize),
41}
42
43impl PosQueryCount {
44 pub(crate) fn capped_with(&self, cap: usize) -> usize {
46 match self {
47 PosQueryCount::All => cap,
48 PosQueryCount::Count(k) => std::cmp::min(*k, cap),
49 }
50 }
51}
52
53pub(crate) trait PositionQuery {
54 fn nearest_nodes(&self, pos: &super::Coordinate, count: PosQueryCount) -> Vec<(NodeId, f32)>;
57
58 fn nodes_within(
60 &self,
61 pos: &super::Coordinate,
62 radius: f32,
63 count: PosQueryCount,
64 ) -> Vec<(NodeId, f32)>;
65}
66
67impl PositionQuery for PosIndex {
68 fn nearest_nodes(&self, pos: &super::Coordinate, count: PosQueryCount) -> Vec<(NodeId, f32)> {
71 match count {
72 PosQueryCount::All => {
73 let query: [f32; 3] = (*pos).into();
74 let mut distances: Vec<_> = self
75 .iter()
76 .map(|(id, coords)| {
77 (
78 id,
79 <SquaredEuclidean<f32> as DistanceMetricScalar<f32>>::dist(
80 &coords, &query,
81 ),
82 )
83 })
84 .map(|(id, d)| (id, d.sqrt()))
85 .collect();
86
87 distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
88 distances
89 }
90 PosQueryCount::Count(_) => {
91 let count = match NonZero::new(count.capped_with(self.size())) {
92 Some(c) => c,
93 None => return Vec::new(),
94 };
95 self.query(&(*pos).into())
96 .nearest_n::<SquaredEuclidean<f32>>(count)
97 .execute()
98 .into_iter()
99 .map(|n| (n.item, n.distance.sqrt()))
100 .collect()
101 }
102 }
103 }
104
105 fn nodes_within(
108 &self,
109 pos: &super::Coordinate,
110 radius: f32,
111 count: PosQueryCount,
112 ) -> Vec<(NodeId, f32)> {
113 let radius_squared = radius * radius;
115 let results = match count {
116 PosQueryCount::All => self
117 .query(&(*pos).into())
118 .within::<SquaredEuclidean<f32>>(radius_squared)
119 .execute(),
120 PosQueryCount::Count(_) => {
121 let count = match NonZero::new(count.capped_with(self.size())) {
122 Some(count) => count,
123 None => return Vec::new(),
124 };
125 self.query(&(*pos).into())
126 .nearest_n::<SquaredEuclidean<f32>>(count)
127 .within(radius_squared)
128 .execute()
129 }
130 };
131 results
132 .into_iter()
133 .map(|n| (n.item, n.distance.sqrt()))
134 .collect()
135 }
136}
137
138impl PositionQuery for Vec<Node> {
139 fn nearest_nodes(&self, pos: &super::Coordinate, count: PosQueryCount) -> Vec<(NodeId, f32)> {
142 let distances = self
143 .iter()
144 .flat_map(|n| n.coordinates.iter().map(|c| (n.id, c)))
145 .map(|(id, c)| (id, c.distance_squared(*pos).sqrt()));
146 if let PosQueryCount::Count(1) = count {
149 distances
150 .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
151 .into_iter()
152 .collect()
153 } else {
154 let mut distances = distances.collect::<Vec<(NodeId, f32)>>();
155
156 distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
157 match count {
158 PosQueryCount::All => distances,
160 PosQueryCount::Count(c) => distances.into_iter().take(c).collect(),
161 }
162 }
163 }
164
165 fn nodes_within(
168 &self,
169 pos: &super::Coordinate,
170 radius: f32,
171 count: PosQueryCount,
172 ) -> Vec<(NodeId, f32)> {
173 let mut distances = self
174 .iter()
175 .flat_map(|n| n.coordinates.iter().map(|c| (n.id, c)))
176 .map(|(id, c)| (id, c.distance_squared(*pos)))
177 .filter(|(_, d)| *d <= radius * radius)
178 .map(|(id, d)| (id, d.sqrt()))
179 .collect::<Vec<(NodeId, f32)>>();
180
181 distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
182
183 match count {
184 PosQueryCount::All => distances,
185 PosQueryCount::Count(c) => distances.into_iter().take(c).collect::<Vec<_>>(),
186 }
187 }
188}
189
190impl PositionQuery for Vec<(Coordinate, NodeId)> {
191 fn nearest_nodes(&self, pos: &super::Coordinate, count: PosQueryCount) -> Vec<(NodeId, f32)> {
194 let distances = self
195 .iter()
196 .map(|(c, id)| (*id, c.distance_squared(*pos).sqrt()));
197
198 if let PosQueryCount::Count(1) = count {
199 distances
200 .min_by(|a, b| a.1.partial_cmp(&b.1).unwrap())
201 .into_iter()
202 .collect()
203 } else {
204 let mut distances = distances.collect::<Vec<(NodeId, f32)>>();
205
206 distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
207 match count {
208 PosQueryCount::All => distances,
209 PosQueryCount::Count(c) => distances.into_iter().take(c).collect(),
210 }
211 }
212 }
213
214 fn nodes_within(
217 &self,
218 pos: &super::Coordinate,
219 radius: f32,
220 count: PosQueryCount,
221 ) -> Vec<(NodeId, f32)> {
222 let mut distances = self
223 .iter()
224 .map(|(c, id)| (*id, c.distance(*pos)))
225 .filter(|(_, d)| *d <= radius)
226 .collect::<Vec<_>>();
227 distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
228 match count {
229 PosQueryCount::All => distances,
230 PosQueryCount::Count(c) => distances.into_iter().take(c).collect(),
231 }
232 }
233}
234
235#[cfg(test)]
250mod coplanar_geometry {
251 use super::*;
252 use crate::layer::Layer;
253 use crate::node::AnonNode;
254
255 fn insert_all(points: &[[f32; 3]]) -> Result<PosIndex, (usize, usize)> {
257 let mut tree = PosIndex::default();
258 for (i, p) in points.iter().enumerate() {
259 if let Err(spatial_index::kd_tree::ConstructionError::UnsplittableBucket {
260 split_dim,
261 }) = tree.add(p, NodeId::new(i as u32, 0))
262 {
263 return Err((i, split_dim));
264 }
265 }
266 Ok(tree)
267 }
268
269 fn brute_force(points: &[[f32; 3]], query: [f32; 3], count: usize) -> Vec<(u32, f32)> {
271 let mut d: Vec<(u32, f32)> = points
272 .iter()
273 .enumerate()
274 .map(|(i, p)| {
275 let s: f32 = (0..3).map(|k| (p[k] - query[k]).powi(2)).sum();
276 (i as u32, s)
277 })
278 .collect();
279 d.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap().then(a.0.cmp(&b.0)));
280 d.truncate(count);
281 d
282 }
283
284 #[track_caller]
287 fn assert_matches_brute_force(tree: &PosIndex, points: &[[f32; 3]], query: [f32; 3]) {
288 for count in [1usize, 5, 40, 200] {
289 let count = count.min(points.len());
290 let want = brute_force(points, query, count);
291 let got = tree
292 .query(&query)
293 .nearest_n::<SquaredEuclidean<f32>>(NonZero::new(count).unwrap())
294 .execute();
295 assert_eq!(got.len(), want.len(), "count {count}: wrong result length");
296 for (g, w) in got.iter().zip(want.iter()) {
297 assert!(
298 (g.distance - w.1).abs() <= 1e-6 * w.1.max(1.0),
299 "count {count}: got distance {} want {}",
300 g.distance,
301 w.1
302 );
303 }
304 }
305 }
306
307 #[test]
310 fn coplanar_plane_inserts_and_answers_queries() {
311 let plane: Vec<[f32; 3]> = (0..500)
312 .map(|i| [(i % 25) as f32 * 0.05, (i / 25) as f32 * 0.05, 3.85])
313 .collect();
314
315 let tree = match insert_all(&plane) {
316 Ok(t) => t,
317 Err((i, d)) => panic!("refused point {i} on axis {d}"),
318 };
319 assert_eq!(tree.size(), plane.len());
320
321 for query in [[0.0, 0.0, 3.85], [0.6, 0.4, 3.85], [10.0, -10.0, 0.0]] {
322 assert_matches_brute_force(&tree, &plane, query);
323 }
324 }
325
326 #[test]
329 fn quantized_lattice_room_inserts_and_answers_queries() {
330 const GRID: usize = 80;
331 let mut room: Vec<[f32; 3]> = Vec::new();
332 for i in 0..GRID {
333 for j in 0..GRID {
334 room.push([i as f32 * 0.05, 0.0, j as f32 * 0.05]);
335 }
336 }
337 for i in 0..GRID {
338 for k in 0..GRID / 2 {
339 room.push([i as f32 * 0.05, k as f32 * 0.05, 0.0]);
340 room.push([0.0, k as f32 * 0.05, i as f32 * 0.05]);
341 }
342 }
343
344 let tree = match insert_all(&room) {
345 Ok(t) => t,
346 Err((i, d)) => panic!("refused point {i} of {} on axis {d}", room.len()),
347 };
348 assert_eq!(tree.size(), room.len());
349
350 for query in [[1.0, 1.0, 1.0], [0.0, 0.0, 0.0], [2.0, 0.05, 3.9]] {
351 assert_matches_brute_force(&tree, &room, query);
352 }
353 }
354
355 #[test]
359 fn removing_coplanar_points_keeps_the_tree_queryable() {
360 let plane: Vec<[f32; 3]> = (0..500)
361 .map(|i| [(i % 25) as f32 * 0.05, (i / 25) as f32 * 0.05, 3.85])
362 .collect();
363 let mut tree = insert_all(&plane).expect("coplanar insert must succeed");
364
365 let removed: Vec<usize> = (0..plane.len()).step_by(3).collect();
366 for &i in &removed {
367 tree.remove(&plane[i], NodeId::new(i as u32, 0));
368 }
369 assert_eq!(tree.size(), plane.len() - removed.len());
370
371 let survivors: Vec<[f32; 3]> = plane
372 .iter()
373 .enumerate()
374 .filter(|(i, _)| !removed.contains(i))
375 .map(|(_, p)| *p)
376 .collect();
377
378 let gone: Vec<NodeId> = removed.iter().map(|&i| NodeId::new(i as u32, 0)).collect();
380 let found = tree
381 .query(&[0.6, 0.4, 3.85])
382 .within::<SquaredEuclidean<f32>>(100.0)
383 .execute();
384 assert_eq!(found.len(), survivors.len(), "radius query lost survivors");
385 for r in &found {
386 assert!(!gone.contains(&r.item), "removed {} came back", r.item);
387 }
388
389 let want = brute_force(&survivors, [0.6, 0.4, 3.85], 10);
391 let got = tree
392 .query(&[0.6, 0.4, 3.85])
393 .nearest_n::<SquaredEuclidean<f32>>(NonZero::new(10).unwrap())
394 .execute();
395 for (g, w) in got.iter().zip(want.iter()) {
396 assert!((g.distance - w.1).abs() <= 1e-6 * w.1.max(1.0));
397 }
398 }
399
400 #[test]
402 fn indexed_layer_accepts_coplanar_geometry() {
403 let mut layer = Layer::with_pos_index(0);
404 for i in 0..500u32 {
405 let pos = Coordinate::new((i % 25) as f32 * 0.05, (i / 25) as f32 * 0.05, 3.85);
406 layer
407 .push_node(AnonNode::new(i, Vec::new(), vec![pos], false, None))
408 .expect("an indexed layer must accept coplanar geometry");
409 }
410 assert_eq!(layer.all_nodes().len(), 500);
411
412 let found = layer.nearest_nodes(&Coordinate::new(0.0, 0.0, 3.85), PosQueryCount::Count(4));
413 assert_eq!(found.len(), 4);
414 assert!(found[0].1 <= 1e-6);
416 }
417
418 #[test]
423 fn identical_points_are_still_refused_at_bucket_capacity() {
424 match insert_all(&[[1.0, 2.0, 3.0]; 300]) {
425 Ok(_) => panic!("expected refusal: no plane separates identical points"),
426 Err((accepted, _)) => assert_eq!(
427 accepted, POS_INDEX_BUCKET_SIZE,
428 "the bucket fills, then the next insert has nowhere to go"
429 ),
430 }
431 }
432
433 #[test]
435 fn unindexed_backends_accept_the_same_geometry() {
436 let mut layer = Layer::new(0);
437 for i in 0..500u32 {
438 let pos = Coordinate::new((i % 25) as f32 * 0.05, (i / 25) as f32 * 0.05, 3.85);
439 layer
440 .push_node(AnonNode::new(i, Vec::new(), vec![pos], false, None))
441 .expect("an unindexed layer has no bucket to split");
442 }
443 assert_eq!(layer.all_nodes().len(), 500);
444 let found = layer.nearest_nodes(&Coordinate::new(0.0, 0.0, 3.85), PosQueryCount::Count(4));
445 assert_eq!(found.len(), 4);
446 }
447
448 #[test]
452 fn bucket_size_is_fixed_at_128_through_degenerate_data() {
453 assert_eq!(POS_INDEX_BUCKET_SIZE, 128);
454
455 let mut tree = PosIndex::default();
456 for i in 0..400u32 {
457 let _ = tree.add(&[0.0, 0.0, 3.85], NodeId::new(i, 0));
458 }
459 assert_eq!(POS_INDEX_BUCKET_SIZE, 128);
462 assert!(tree.size() <= 400);
463 }
464}
465
466#[cfg(test)]
472mod scale {
473 use super::*;
474 use crate::layer::Layer;
475 use crate::node::AnonNode;
476
477 fn scattered_lattice(count: usize) -> Vec<Coordinate> {
485 const SPAN: usize = 71;
488 let cells = SPAN * SPAN * SPAN;
489 let stride = 47_351usize;
490 assert!(count <= cells);
491 (0..count)
492 .map(|i| {
493 let c = (i.wrapping_mul(stride)) % cells;
494 Coordinate::new(
495 (c % SPAN) as f32 * 0.05,
496 ((c / SPAN) % SPAN) as f32 * 0.05,
497 ((c / SPAN / SPAN) % SPAN) as f32 * 0.05,
498 )
499 })
500 .collect()
501 }
502
503 #[test]
508 #[ignore = "350k inserts; run explicitly, ideally in release"]
509 fn indexed_layer_holds_350k_lattice_points() {
510 let points = scattered_lattice(350_000);
511 let mut layer = Layer::with_pos_index(0);
512
513 for (i, p) in points.iter().enumerate() {
514 layer
515 .push_node(AnonNode::new(i as u32, Vec::new(), vec![*p], false, None))
516 .unwrap_or_else(|e| panic!("insert {i} of {} refused: {e}", points.len()));
517 }
518 assert_eq!(layer.all_nodes().len(), points.len());
519
520 let probe = points[points.len() / 2];
523 let found = layer.nearest_nodes(&probe, PosQueryCount::Count(16));
524 assert_eq!(found.len(), 16);
525 assert!(found[0].1 <= 1e-6, "nearest to a lattice site is itself");
526 for w in found.windows(2) {
527 assert!(w[0].1 <= w[1].1 + 1e-6, "results not ordered by distance");
528 }
529
530 let radius = 0.12f32;
532 let within = layer.nodes_within(&probe, radius, PosQueryCount::All);
533 let expected = points
534 .iter()
535 .filter(|q| q.distance(probe) <= radius + 1e-6)
536 .count();
537 assert_eq!(within.len(), expected, "radius query lost or gained points");
538 }
539}
540
541#[cfg(test)]
542mod test {
543 use super::*;
544 use crate::Coordinate;
545
546 fn nid(i: usize) -> NodeId {
548 NodeId::new(i as u32, 0)
549 }
550
551 fn pt(x: f32) -> Coordinate {
553 Coordinate::new(x, 0.0, 0.0)
554 }
555
556 fn as_nodes(xs: &[f32]) -> Vec<Node> {
558 xs.iter()
559 .enumerate()
560 .map(|(i, x)| Node::new(nid(i), Vec::new(), vec![pt(*x)], false, None))
561 .collect()
562 }
563
564 fn as_coords(xs: &[f32]) -> Vec<(Coordinate, NodeId)> {
566 xs.iter()
567 .enumerate()
568 .map(|(i, x)| (pt(*x), nid(i)))
569 .collect()
570 }
571
572 fn as_kdtree(xs: &[f32]) -> PosIndex {
574 let mut tree = PosIndex::default();
575 for (i, x) in xs.iter().enumerate() {
576 tree.add(&[*x, 0.0, 0.0], nid(i)).unwrap();
577 }
578 tree
579 }
580
581 #[track_caller]
582 fn assert_equal(backend: &str, got: &Vec<(NodeId, f32)>, want: &Vec<(NodeId, f32)>) {
583 assert_eq!(
584 got.len(),
585 want.len(),
586 "{backend}: returned {} results, kd-tree returned {}\n got: {got:?}\n want: {want:?}",
587 got.len(),
588 want.len()
589 );
590 for ((got_id, got_d), (want_id, want_d)) in got.iter().zip(want.iter()) {
591 assert_eq!(
592 got_id, want_id,
593 "{backend}: node id mismatch\n got: {got:?}\n want: {want:?}"
594 );
595 assert!(
596 (got_d - want_d).abs() <= 1e-5,
597 "{backend}: distance for {got_id} is {got_d}, kd-tree says {want_d}"
598 );
599 }
600 }
601
602 #[test]
603 fn vec_node_nearest_returns_true_distances() {
604 let nodes = as_nodes(&[3.0, 4.0, 5.0]);
605
606 let got = nodes.nearest_nodes(&Coordinate::ZERO, PosQueryCount::Count(3));
607
608 let distances = got.iter().map(|(_, d)| *d).collect::<Vec<_>>();
609 assert_eq!(distances, vec![3.0, 4.0, 5.0]);
610
611 let got = nodes.nearest_nodes(&Coordinate::ZERO, PosQueryCount::All);
612
613 let distances = got.iter().map(|(_, d)| *d).collect::<Vec<_>>();
614 assert_eq!(distances, vec![3.0, 4.0, 5.0]);
615 }
616
617 #[test]
618 fn vec_coords_nearest_returns_true_distances() {
619 let coords = as_coords(&[3.0, 4.0, 5.0]);
620
621 let got = coords.nearest_nodes(&Coordinate::ZERO, PosQueryCount::Count(3));
622
623 let distances = got.iter().map(|(_, d)| *d).collect::<Vec<_>>();
624 assert_eq!(distances, vec![3.0, 4.0, 5.0]);
625
626 let got = coords.nearest_nodes(&Coordinate::ZERO, PosQueryCount::All);
627
628 let distances = got.iter().map(|(_, d)| *d).collect::<Vec<_>>();
629 assert_eq!(distances, vec![3.0, 4.0, 5.0]);
630 }
631
632 #[test]
633 fn vec_coords_nodes_within_respects_radius() {
634 let coords = as_coords(&[1.0, 3.0]);
635
636 let got = coords.nodes_within(&Coordinate::ZERO, 2.0, PosQueryCount::All);
637
638 assert_eq!(
639 got.len(),
640 1,
641 "radius 2.0 must exclude the point at distance 3.0, got {got:?}"
642 );
643 assert_eq!(got[0].0, nid(0));
644 assert!(
645 (got[0].1 - 1.0).abs() <= 1e-5,
646 "expected distance 1.0, got {}",
647 got[0].1
648 );
649 }
650
651 #[test]
655 fn all_backends_agree_on_nearest_nodes() {
656 let xs = [1.0, 4.0, 9.0, 16.0];
657 let query = Coordinate::new(0.5, 2.0, -3.0);
658 let nodes = as_nodes(&xs);
659 let coords = as_coords(&xs);
660 let tree = as_kdtree(&xs);
661
662 for count in [
663 PosQueryCount::Count(1),
664 PosQueryCount::Count(3),
665 PosQueryCount::Count(xs.len()),
666 PosQueryCount::All,
667 ] {
668 let reference = tree.nearest_nodes(&query, count);
669 assert_equal(
670 &format!("Vec<Node> nearest_nodes({count:?})"),
671 &nodes.nearest_nodes(&query, count),
672 &reference,
673 );
674 assert_equal(
675 &format!("Vec<(Coordinate, NodeId)> nearest_nodes({count:?})"),
676 &coords.nearest_nodes(&query, count),
677 &reference,
678 );
679 }
680 }
681
682 #[test]
685 fn all_backends_agree_on_nodes_within() {
686 let xs = [1.0, 4.0, 9.0, 16.0];
687 let query = Coordinate::ZERO;
688 let nodes = as_nodes(&xs);
689 let coords = as_coords(&xs);
690 let tree = as_kdtree(&xs);
691
692 for radius in [0.5f32, 1.0, 2.0, 5.0, 10.0, 100.0] {
693 let reference = tree.nodes_within(&query, radius, PosQueryCount::All);
694 assert_equal(
695 &format!("Vec<Node> nodes_within(radius = {radius})"),
696 &nodes.nodes_within(&query, radius, PosQueryCount::All),
697 &reference,
698 );
699 assert_equal(
700 &format!("Vec<(Coordinate, NodeId)> nodes_within(radius = {radius})"),
701 &coords.nodes_within(&query, radius, PosQueryCount::All),
702 &reference,
703 );
704 }
705 }
706}