Skip to main content

yggdrasil/
pos.rs

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
11/// Bucket size of the position index: the maximum number of points a single leaf of the
12/// kd-tree holds before it is split.
13///
14/// This is a deliberate memory-versus-latency choice made by this crate, not a tuning knob
15/// the tree is free to change on its own: leaves are fixed-size arrays, so every leaf costs
16/// this many slots regardless of how many are occupied. Position indexing is opt-in
17/// precisely so that a caller can decide to pay for it.
18pub(crate) const POS_INDEX_BUCKET_SIZE: usize = 128;
19
20/// The kd-tree configuration backing every position index in this crate.
21///
22/// `EytzingerAdaptive` is the breadth-first stem layout, splitting on the widest axis, and `VecOfArrays` is the mutable leaf
23/// strategy, which is what makes incremental `add`/`remove` available — the position
24/// indexes are maintained point by point as the graph changes, never rebuilt in bulk.
25pub(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/// Specifies the number of nodes to return in position-based queries.
35#[derive(Debug, Clone, Copy)]
36pub enum PosQueryCount {
37    /// Return All matching nodes.
38    All,
39    /// Return a specific Count of matching nodes.
40    Count(usize),
41}
42
43impl PosQueryCount {
44    /// Convert to usize, capping at the provided maximum value.
45    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    /// Retrieve at most `count` nearest nodes to the given position.
55    /// The list is sorted by distance from nearest to farthest.
56    fn nearest_nodes(&self, pos: &super::Coordinate, count: PosQueryCount) -> Vec<(NodeId, f32)>;
57
58    /// Retrieve at most `count` nodes within a specified radius to the given position.
59    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    /// Retrieve at most `count` nearest nodes to the given position.
69    /// The list is sorted by distance from nearest to farthest.
70    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    /// Retrieve at most `count` nodes within a specified radius to the given position.
106    /// If this function is called frequently, consider creating the Layer with indexing enabled.
107    fn nodes_within(
108        &self,
109        pos: &super::Coordinate,
110        radius: f32,
111        count: PosQueryCount,
112    ) -> Vec<(NodeId, f32)> {
113        // Distance is SquaredEuclidean<f32>, so we need to square the radius for the query.
114        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    /// Retrieve at most `count` nearest nodes to the given position.
140    /// The list is sorted by distance from nearest to farthest.
141    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        // .collect();
147        // distances.sort_by(|a, b| a.1.partial_cmp(&b.1).unwrap());
148        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::Count(c) if (c as f32) < ((distances.len()) as f32).log2() => {
159                PosQueryCount::All => distances,
160                PosQueryCount::Count(c) => distances.into_iter().take(c).collect(),
161            }
162        }
163    }
164
165    /// Retrieve at most `count` nodes within a specified radius to the given position.
166    /// If this function is called frequently, consider creating the Layer with indexing enabled.
167    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    /// Retrieve at most `count` nearest nodes to the given position.
192    /// The list is sorted by distance from nearest to farthest.
193    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    /// Retrieve at most `count` nodes within a specified radius to the given position.
215    /// If this function is called frequently, consider creating the Layer with indexing enabled.
216    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/// Tests for coplanar and lattice-quantised geometry — the input that upstream kiddo cannot
236/// insert at all.
237///
238/// The kd-tree picks the axis it splits a full leaf on. Upstream derives it from tree depth, so a
239/// leaf that fills with points sharing one value on the cycled axis has no plane to cut at and the
240/// insert is refused. That is not an exotic input for this crate: reconstructed indoor geometry
241/// snapped to a voxel lattice puts thousands of points on a single floor, wall or ceiling plane,
242/// far past a 128-point bucket. `spatial-index` chooses the axis by widest spread instead, and
243/// records it in the split value so queries agree.
244///
245/// These began as characterization tests asserting the refusal, and were rewritten when the
246/// adaptive split landed. What they now pin is that the geometry inserts *and* that queries over
247/// it match a brute-force scan — the failure mode a mis-recorded axis would produce is silently
248/// wrong neighbours, not an error.
249#[cfg(test)]
250mod coplanar_geometry {
251    use super::*;
252    use crate::layer::Layer;
253    use crate::node::AnonNode;
254
255    /// Insert every point into a fresh index, reporting the first refusal.
256    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    /// The `count` nearest points to `query` by exhaustive scan, as `(index, distance)`.
270    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    /// Every query must agree with brute force on distances. Ids are compared only where the
285    /// distance is unambiguous, since ties may be broken either way.
286    #[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    /// 500 points spread over x and y but sharing one z: a single ceiling plane. Upstream refuses
308    /// insert #348 of these, on the shared axis.
309    #[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    /// The realistic shape: a room on a 0.05 m lattice, floor plus two walls, each surface one
327    /// plane holding thousands of points. Upstream stops 208 points into 12,800.
328    #[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    /// Removal over coplanar data: removed points must stop being returned, and the tree must stay
356    /// queryable afterwards. Exercises the paths that locate a leaf by descent, which is where a
357    /// mis-recorded split axis would send the walk down the wrong subtree.
358    #[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        // No removed id may come back, at any radius.
379        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        // And the tree still answers correctly over what is left.
390        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    /// An indexed layer holds the same geometry through the public API.
401    #[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        // Nearest to the corner is the corner itself.
415        assert!(found[0].1 <= 1e-6);
416    }
417
418    /// The one case a better axis choice cannot fix: points identical on *every* axis have no
419    /// separating plane at all, so the bucket is refused once full. Storing them needs an overflow
420    /// representation rather than a different split — deliberately still outstanding, and pinned
421    /// here so that work has a failing test to turn green.
422    #[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    /// The unindexed backends handle the same geometry, as they always did.
434    #[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    /// The bucket size is a deliberate memory-versus-latency choice by this crate, not something
449    /// the tree may adjust for itself. Degenerate data must not change it — increasing it is the
450    /// fix upstream suggests for the coplanar refusal, and the one this crate does not take.
451    #[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        // Whatever the tree did with that input, its configuration is a compile-time constant and
460        // its live count can never exceed what it accepted.
461        assert_eq!(POS_INDEX_BUCKET_SIZE, 128);
462        assert!(tree.size() <= 400);
463    }
464}
465
466/// Scale test for the position index, at the size real scenes reach.
467///
468/// Nothing else in this crate builds an index this large: `parse/concept_graph.rs` puts its point
469/// cloud in an *unindexed* layer and `examples/demo.rs` uses 100 points, which is why the coplanar
470/// defect went unnoticed for so long. This is the test that would have caught it.
471#[cfg(test)]
472mod scale {
473    use super::*;
474    use crate::layer::Layer;
475    use crate::node::AnonNode;
476
477    /// Points on a 0.05 m lattice filling a room-sized volume, emitted in a scattered order.
478    ///
479    /// The order matters and is not incidental. Lattice points in scan order arrive spatially
480    /// clustered, which drives tree depth rather than breadth — and stems are addressed by
481    /// breadth-first position, so that costs `2^depth` slots and exhausts memory well before
482    /// 350,000 points. That is a separate, unfixed defect (see `bench/BASELINE.md`), so this test
483    /// deliberately interleaves the points instead of pretending it does not exist.
484    fn scattered_lattice(count: usize) -> Vec<Coordinate> {
485        // A stride coprime with the span walks every cell exactly once in a scattered order,
486        // which is deterministic without needing a PRNG.
487        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    /// Build an indexed layer of ~350,000 lattice points and query it.
504    ///
505    /// Slow in a debug build, so it is ignored by default:
506    /// `cargo test -p yggdrasil-3d --release -- --ignored`
507    #[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        // A query at a lattice site must find that site at distance zero, and return neighbours in
521        // nondecreasing order of distance.
522        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        // And a radius query must agree with the same radius measured by brute force.
531        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    /// Node ids are all placed on layer 0; only the index within the layer varies.
547    fn nid(i: usize) -> NodeId {
548        NodeId::new(i as u32, 0)
549    }
550
551    /// A point on the +X axis, so its distance from the origin is exactly `x`.
552    fn pt(x: f32) -> Coordinate {
553        Coordinate::new(x, 0.0, 0.0)
554    }
555
556    /// Converts 1D points into Vec<Node> with generated ids
557    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    /// Converts 1D points into Vec<(Coordinate, NodeId)> with generated ids
565    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    /// Convert 1D points into a [`PosIndex`] with generated ids
573    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    /// The invariant the benchmark suite rests on: all three backends must be
652    /// interchangeable. The kd-tree is the reference, since indexing must not change
653    /// what a query answers — only how fast it answers it.
654    #[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    /// Same invariant for radius search, swept across radii on both sides of 1.0 so the
683    /// squared-versus-unsquared comparison cannot pass by coincidence.
684    #[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}