Skip to main content

spatialrust_search/
kdtree.rs

1use std::cmp::Ordering;
2
3use spatialrust_core::{HasPositions3, PointCloud, SpatialResult};
4
5use crate::{
6    chunked::{ChunkQueryRange, ChunkedNearestNeighborIndex, ChunkedRadiusSearchIndex},
7    NearestNeighborIndex, Neighbor, RadiusSearchIndex, SpatialIndex,
8};
9
10const LEAF_SIZE: usize = 16;
11const SEARCH_STACK_SIZE: usize = 64;
12const AXIS_LEAF: u8 = u8::MAX;
13const INVALID_NODE: u32 = u32::MAX;
14
15#[cfg(feature = "parallel")]
16#[path = "kdtree_build.rs"]
17mod parallel_build;
18
19#[cfg(feature = "parallel")]
20pub use parallel_build::PARALLEL_KDTREE_BUILD_MIN_POINTS;
21
22/// Cache-friendly KD-tree for 3D point clouds.
23#[derive(Clone, Debug)]
24pub struct KdTree {
25    x: Vec<f32>,
26    y: Vec<f32>,
27    z: Vec<f32>,
28    points_order: Vec<u32>,
29    nodes: Vec<KdNode>,
30    root: u32,
31}
32
33#[derive(Clone, Copy, Debug)]
34struct KdNode {
35    split: f32,
36    left: u32,
37    right: u32,
38    start: u32,
39    end: u32,
40    axis: u8,
41}
42
43/// A backend-neutral node in a borrowed KD-tree layout.
44#[derive(Clone, Copy, Debug, PartialEq)]
45pub enum KdTreeNode {
46    /// Leaf range in the layout's point order (end exclusive).
47    Leaf {
48        /// First ordered point.
49        start: u32,
50        /// End of the ordered point range.
51        end: u32,
52    },
53    /// Near-first split; children are indices into the node iterator.
54    Branch {
55        /// Coordinate axis (0, 1 or 2).
56        axis: u8,
57        /// Split coordinate.
58        split: f32,
59        /// Child visited first when the query coordinate is <= split.
60        left: u32,
61        /// Other child.
62        right: u32,
63    },
64}
65
66/// Read-only layout for explicit backend staging, retaining CPU traversal ties.
67/// The tree owns all storage; borrowing this view performs no copies.
68pub struct KdTreeLayout<'a> {
69    tree: &'a KdTree,
70}
71
72impl<'a> KdTreeLayout<'a> {
73    /// Coordinates in original point order.
74    #[must_use]
75    pub fn positions(&self) -> (&'a [f32], &'a [f32], &'a [f32]) {
76        (&self.tree.x, &self.tree.y, &self.tree.z)
77    }
78
79    /// Original point indices in leaf traversal order.
80    #[must_use]
81    pub fn point_order(&self) -> &'a [u32] {
82        &self.tree.points_order
83    }
84
85    /// Root node index, or None for an empty tree.
86    #[must_use]
87    pub fn root(&self) -> Option<u32> {
88        (self.tree.root != INVALID_NODE).then_some(self.tree.root)
89    }
90
91    /// Nodes in index order. The balanced tree has at most 32 levels for u32 points.
92    pub fn nodes(&self) -> impl ExactSizeIterator<Item = KdTreeNode> + '_ {
93        self.tree.nodes.iter().map(|n| {
94            if n.axis == AXIS_LEAF {
95                KdTreeNode::Leaf { start: n.start, end: n.end }
96            } else {
97                KdTreeNode::Branch { axis: n.axis, split: n.split, left: n.left, right: n.right }
98            }
99        })
100    }
101}
102
103impl KdTree {
104    /// Borrows the tree's backend-neutral layout without changing query behavior.
105    #[must_use]
106    pub fn layout(&self) -> KdTreeLayout<'_> {
107        KdTreeLayout { tree: self }
108    }
109
110    /// Finds the nearest point inside an inclusive squared-distance bound.
111    ///
112    /// Uses the same traversal and first-encountered tie policy as `nearest_one`,
113    /// without allocating a result vector. Negative/NaN bounds and nonfinite
114    /// query coordinates return `None`; positive infinity is an unbounded query.
115    #[must_use]
116    pub fn nearest_one_within(
117        &self,
118        x: f32,
119        y: f32,
120        z: f32,
121        max_distance_squared: f32,
122    ) -> Option<Neighbor> {
123        if max_distance_squared.is_nan()
124            || max_distance_squared < 0.0
125            || !x.is_finite()
126            || !y.is_finite()
127            || !z.is_finite()
128        {
129            return None;
130        }
131        let mut best = None;
132        self.nearest_one_within_recursive(self.root, [x, y, z], max_distance_squared, &mut best);
133        best
134    }
135
136    fn nearest_one_within_recursive(
137        &self,
138        node: u32,
139        query: [f32; 3],
140        bound: f32,
141        best: &mut Option<Neighbor>,
142    ) {
143        if node == INVALID_NODE {
144            return;
145        }
146        let data = self.nodes[node as usize];
147        if data.axis == AXIS_LEAF {
148            for order in data.start..data.end {
149                let (index, x, y, z) = self.ordered_point(order);
150                let distance = squared_distance(x, y, z, query[0], query[1], query[2]);
151                if distance <= bound
152                    && best.as_ref().map_or(true, |n| distance < n.distance_squared)
153                {
154                    *best = Some(Neighbor { index: index as usize, distance_squared: distance });
155                }
156            }
157            return;
158        }
159        let diff = query[data.axis as usize] - data.split;
160        let (near, far) =
161            if diff <= 0.0 { (data.left, data.right) } else { (data.right, data.left) };
162        self.nearest_one_within_recursive(near, query, bound, best);
163        // Before finding a point, equality must be visited to include the gate
164        // boundary. Once found, retain the original strict pruning/tie policy.
165        let visit_far =
166            best.as_ref().map_or(diff * diff <= bound, |n| diff * diff < n.distance_squared);
167        if visit_far {
168            self.nearest_one_within_recursive(far, query, bound, best);
169        }
170    }
171
172    /// Builds a KD-tree from coordinate slices.
173    #[must_use]
174    pub fn from_slices(x: &[f32], y: &[f32], z: &[f32]) -> Self {
175        assert_eq!(x.len(), y.len());
176        assert_eq!(x.len(), z.len());
177
178        let len = x.len();
179        let mut points_order: Vec<u32> = (0..len as u32).collect();
180        let mut nodes = Vec::with_capacity(if len == 0 { 0 } else { len.div_ceil(LEAF_SIZE) * 2 });
181
182        let root = if len == 0 {
183            INVALID_NODE
184        } else {
185            build_node(x, y, z, &mut points_order, 0, len, &mut nodes)
186        };
187
188        Self { x: x.to_vec(), y: y.to_vec(), z: z.to_vec(), points_order, nodes, root }
189    }
190
191    /// Builds a KD-tree from any point cloud with XYZ positions.
192    pub fn from_point_cloud(cloud: &PointCloud) -> SpatialResult<Self> {
193        let (x, y, z) = cloud.positions3()?;
194        Ok(Self::from_slices(x, y, z))
195    }
196
197    fn point(&self, point_index: u32) -> (f32, f32, f32) {
198        let idx = point_index as usize;
199        (self.x[idx], self.y[idx], self.z[idx])
200    }
201
202    fn ordered_point(&self, order_index: u32) -> (u32, f32, f32, f32) {
203        let point_index = self.points_order[order_index as usize];
204        let (x, y, z) = self.point(point_index);
205        (point_index, x, y, z)
206    }
207
208    fn nearest_one_recursive(
209        &self,
210        node: u32,
211        qx: f32,
212        qy: f32,
213        qz: f32,
214        best: &mut Option<Neighbor>,
215    ) {
216        if node == INVALID_NODE {
217            return;
218        }
219
220        let node_data = self.nodes[node as usize];
221        if node_data.axis == AXIS_LEAF {
222            for order_index in node_data.start..node_data.end {
223                let (index, px, py, pz) = self.ordered_point(order_index);
224                let distance_squared = squared_distance(px, py, pz, qx, qy, qz);
225                if let Some(neighbor) = best {
226                    // Retain the k=1 accumulator's rejection comparison:
227                    // NaN candidates or incumbents must still be replaced.
228                    if distance_squared >= neighbor.distance_squared {
229                        continue;
230                    }
231                }
232                *best = Some(Neighbor { index: index as usize, distance_squared });
233            }
234            return;
235        }
236
237        let diff = match node_data.axis {
238            0 => qx - node_data.split,
239            1 => qy - node_data.split,
240            _ => qz - node_data.split,
241        };
242        let (near, far) = if diff <= 0.0 {
243            (node_data.left, node_data.right)
244        } else {
245            (node_data.right, node_data.left)
246        };
247
248        self.nearest_one_recursive(near, qx, qy, qz, best);
249        if best.as_ref().map_or(true, |neighbor| diff * diff < neighbor.distance_squared) {
250            self.nearest_one_recursive(far, qx, qy, qz, best);
251        }
252    }
253
254    fn nearest_k_recursive(
255        &self,
256        node: u32,
257        qx: f32,
258        qy: f32,
259        qz: f32,
260        k: usize,
261        best: &mut KnnAccumulator,
262    ) {
263        if node == INVALID_NODE {
264            return;
265        }
266
267        let node_data = self.nodes[node as usize];
268        if node_data.axis == AXIS_LEAF {
269            let start = node_data.start as usize;
270            let end = node_data.end as usize;
271            for order_index in start..end {
272                let (index, px, py, pz) = self.ordered_point(order_index as u32);
273                best.insert(
274                    k,
275                    Neighbor {
276                        index: index as usize,
277                        distance_squared: squared_distance(px, py, pz, qx, qy, qz),
278                    },
279                );
280            }
281            return;
282        }
283
284        let diff = match node_data.axis {
285            0 => qx - node_data.split,
286            1 => qy - node_data.split,
287            _ => qz - node_data.split,
288        };
289
290        let (near, far) = if diff <= 0.0 {
291            (node_data.left, node_data.right)
292        } else {
293            (node_data.right, node_data.left)
294        };
295
296        self.nearest_k_recursive(near, qx, qy, qz, k, best);
297
298        let worst = best.prune_distance(k);
299        if diff * diff < worst || best.len() < k {
300            self.nearest_k_recursive(far, qx, qy, qz, k, best);
301        }
302    }
303
304    fn radius_recursive(
305        &self,
306        node: u32,
307        qx: f32,
308        qy: f32,
309        qz: f32,
310        radius_sq: f32,
311        out: &mut Vec<Neighbor>,
312    ) {
313        if node == INVALID_NODE {
314            return;
315        }
316
317        let node_data = self.nodes[node as usize];
318        if node_data.axis == AXIS_LEAF {
319            let start = node_data.start as usize;
320            let end = node_data.end as usize;
321            for order_index in start..end {
322                let (index, px, py, pz) = self.ordered_point(order_index as u32);
323                let distance_squared = squared_distance(px, py, pz, qx, qy, qz);
324                if distance_squared <= radius_sq {
325                    out.push(Neighbor { index: index as usize, distance_squared });
326                }
327            }
328            return;
329        }
330
331        let diff = match node_data.axis {
332            0 => qx - node_data.split,
333            1 => qy - node_data.split,
334            _ => qz - node_data.split,
335        };
336
337        let (near, far) = if diff <= 0.0 {
338            (node_data.left, node_data.right)
339        } else {
340            (node_data.right, node_data.left)
341        };
342
343        self.radius_recursive(near, qx, qy, qz, radius_sq, out);
344        if diff * diff <= radius_sq {
345            self.radius_recursive(far, qx, qy, qz, radius_sq, out);
346        }
347    }
348
349    /// Returns whether at least `target` points lie within `radius` of the
350    /// query, stopping as soon as the threshold is reached. Unlike
351    /// [`radius_search`](RadiusSearchIndex::radius_search) this allocates nothing
352    /// and early-exits, which is much faster for density tests (outlier removal).
353    #[must_use]
354    pub fn radius_reaches(&self, x: f32, y: f32, z: f32, radius: f32, target: usize) -> bool {
355        if target == 0 {
356            return true;
357        }
358        if self.is_empty() || radius < 0.0 {
359            return false;
360        }
361        self.radius_count_iterative(x, y, z, radius * radius, target)
362    }
363
364    fn radius_count_iterative(
365        &self,
366        qx: f32,
367        qy: f32,
368        qz: f32,
369        radius_sq: f32,
370        target: usize,
371    ) -> bool {
372        let mut count = 0usize;
373        let mut stack = [INVALID_NODE; SEARCH_STACK_SIZE];
374        let mut stack_len = 0usize;
375        let mut node = self.root;
376
377        loop {
378            while node != INVALID_NODE {
379                let node_data = self.nodes[node as usize];
380                if node_data.axis == AXIS_LEAF {
381                    let start = node_data.start as usize;
382                    let end = node_data.end as usize;
383                    for order_index in start..end {
384                        let (_, px, py, pz) = self.ordered_point(order_index as u32);
385                        if squared_distance(px, py, pz, qx, qy, qz) <= radius_sq {
386                            count += 1;
387                            if count >= target {
388                                return true;
389                            }
390                        }
391                    }
392                    break;
393                }
394
395                let diff = match node_data.axis {
396                    0 => qx - node_data.split,
397                    1 => qy - node_data.split,
398                    _ => qz - node_data.split,
399                };
400                let (near, far) = if diff <= 0.0 {
401                    (node_data.left, node_data.right)
402                } else {
403                    (node_data.right, node_data.left)
404                };
405
406                if diff * diff <= radius_sq {
407                    if stack_len < stack.len() {
408                        stack[stack_len] = far;
409                        stack_len += 1;
410                    } else if self
411                        .radius_count_recursive(far, qx, qy, qz, radius_sq, target, &mut count)
412                    {
413                        return true;
414                    }
415                }
416                node = near;
417            }
418
419            if stack_len == 0 {
420                return false;
421            }
422            stack_len -= 1;
423            node = stack[stack_len];
424        }
425    }
426
427    /// Accumulates points within `radius_sq` into `count`; returns `true` as soon
428    /// as `count` reaches `target` so the search can short-circuit.
429    fn radius_count_recursive(
430        &self,
431        node: u32,
432        qx: f32,
433        qy: f32,
434        qz: f32,
435        radius_sq: f32,
436        target: usize,
437        count: &mut usize,
438    ) -> bool {
439        if node == INVALID_NODE {
440            return false;
441        }
442
443        let node_data = self.nodes[node as usize];
444        if node_data.axis == AXIS_LEAF {
445            let start = node_data.start as usize;
446            let end = node_data.end as usize;
447            for order_index in start..end {
448                let (_, px, py, pz) = self.ordered_point(order_index as u32);
449                if squared_distance(px, py, pz, qx, qy, qz) <= radius_sq {
450                    *count += 1;
451                    if *count >= target {
452                        return true;
453                    }
454                }
455            }
456            return false;
457        }
458
459        let diff = match node_data.axis {
460            0 => qx - node_data.split,
461            1 => qy - node_data.split,
462            _ => qz - node_data.split,
463        };
464        let (near, far) = if diff <= 0.0 {
465            (node_data.left, node_data.right)
466        } else {
467            (node_data.right, node_data.left)
468        };
469
470        if self.radius_count_recursive(near, qx, qy, qz, radius_sq, target, count) {
471            return true;
472        }
473        if diff * diff <= radius_sq {
474            return self.radius_count_recursive(far, qx, qy, qz, radius_sq, target, count);
475        }
476        false
477    }
478}
479
480impl SpatialIndex for KdTree {
481    fn len(&self) -> usize {
482        self.x.len()
483    }
484}
485
486impl NearestNeighborIndex for KdTree {
487    fn nearest_one(&self, x: f32, y: f32, z: f32) -> Option<Neighbor> {
488        let mut best = None;
489        self.nearest_one_recursive(self.root, x, y, z, &mut best);
490        best
491    }
492
493    fn nearest_k(&self, x: f32, y: f32, z: f32, k: usize) -> Vec<Neighbor> {
494        let mut best = Vec::with_capacity(k.min(self.len()));
495        self.nearest_k_into(x, y, z, k, &mut best);
496        best
497    }
498}
499
500impl KdTree {
501    /// Finds up to `k` nearest neighbors sorted by ascending distance, reusing
502    /// the caller-provided output buffer.
503    pub fn nearest_k_into(&self, x: f32, y: f32, z: f32, k: usize, out: &mut Vec<Neighbor>) {
504        self.nearest_k_unsorted_into(x, y, z, k, out);
505        out.sort_by(|a, b| {
506            a.distance_squared.partial_cmp(&b.distance_squared).unwrap_or(Ordering::Equal)
507        });
508    }
509
510    /// Finds up to `k` nearest neighbors without sorting the result, reusing the
511    /// caller-provided output buffer. This is faster for callers that only need
512    /// the neighbor set, such as covariance and mean-distance calculations.
513    pub fn nearest_k_unsorted_into(
514        &self,
515        x: f32,
516        y: f32,
517        z: f32,
518        k: usize,
519        out: &mut Vec<Neighbor>,
520    ) {
521        out.clear();
522        if self.is_empty() || k == 0 {
523            return;
524        }
525
526        out.reserve(k.min(self.len()));
527        let mut best = KnnAccumulator::new(out);
528        self.nearest_k_recursive(self.root, x, y, z, k, &mut best);
529    }
530}
531
532impl RadiusSearchIndex for KdTree {
533    fn radius_search(&self, x: f32, y: f32, z: f32, radius: f32) -> Vec<Neighbor> {
534        if self.is_empty() || radius < 0.0 {
535            return Vec::new();
536        }
537
538        let radius_sq = radius * radius;
539        let mut out = Vec::new();
540        self.radius_recursive(self.root, x, y, z, radius_sq, &mut out);
541        // Intentionally unsorted: callers count or iterate neighbors, and
542        // sorting every query dominates radius search on dense clouds.
543        out
544    }
545}
546
547impl ChunkedRadiusSearchIndex for KdTree {
548    fn radius_search_chunk_into(
549        &self,
550        x: &[f32],
551        y: &[f32],
552        z: &[f32],
553        chunk: ChunkQueryRange,
554        radius: f32,
555        out: &mut Vec<(usize, Neighbor)>,
556    ) {
557        if self.is_empty() || radius < 0.0 || chunk.is_empty() {
558            return;
559        }
560
561        let radius_sq = radius * radius;
562        let mut scratch = Vec::new();
563        for index in chunk {
564            scratch.clear();
565            self.radius_recursive(self.root, x[index], y[index], z[index], radius_sq, &mut scratch);
566            for neighbor in scratch.drain(..) {
567                out.push((index, neighbor));
568            }
569        }
570    }
571}
572
573impl ChunkedNearestNeighborIndex for KdTree {
574    fn nearest_k_chunk_into(
575        &self,
576        x: &[f32],
577        y: &[f32],
578        z: &[f32],
579        chunk: ChunkQueryRange,
580        k: usize,
581        out: &mut Vec<(usize, Neighbor)>,
582    ) {
583        if chunk.is_empty() || k == 0 {
584            return;
585        }
586
587        let mut scratch = Vec::new();
588        for index in chunk {
589            scratch.clear();
590            self.nearest_k_unsorted_into(x[index], y[index], z[index], k, &mut scratch);
591            for neighbor in scratch.drain(..) {
592                out.push((index, neighbor));
593            }
594        }
595    }
596}
597
598#[allow(clippy::too_many_arguments)]
599fn build_node(
600    x: &[f32],
601    y: &[f32],
602    z: &[f32],
603    points_order: &mut [u32],
604    start: usize,
605    end: usize,
606    nodes: &mut Vec<KdNode>,
607) -> u32 {
608    let node_index = nodes.len() as u32;
609    nodes.push(KdNode {
610        split: 0.0,
611        left: INVALID_NODE,
612        right: INVALID_NODE,
613        start: start as u32,
614        end: end as u32,
615        axis: 0,
616    });
617
618    let count = end - start;
619    if count <= LEAF_SIZE {
620        nodes[node_index as usize].axis = AXIS_LEAF;
621        return node_index;
622    }
623
624    let (axis, minimum) = select_axis(x, y, z, points_order, start, end);
625    let mid = start + count / 2;
626    select_nth_by_axis(x, y, z, points_order, start, end, (axis, minimum), mid);
627
628    let split_point = points_order[mid];
629    let split_value = coordinate(x, y, z, split_point, axis);
630    nodes[node_index as usize].axis = axis;
631    nodes[node_index as usize].split = split_value;
632
633    let left = build_node(x, y, z, points_order, start, mid, nodes);
634    let right = build_node(x, y, z, points_order, mid, end, nodes);
635
636    nodes[node_index as usize].left = left;
637    nodes[node_index as usize].right = right;
638    node_index
639}
640
641fn select_axis(
642    x: &[f32],
643    y: &[f32],
644    z: &[f32],
645    points_order: &[u32],
646    start: usize,
647    end: usize,
648) -> (u8, f32) {
649    let mut min = [f32::INFINITY; 3];
650    let mut max = [f32::NEG_INFINITY; 3];
651    for &point_index in &points_order[start..end] {
652        min[0] = min[0].min(x[point_index as usize]);
653        min[1] = min[1].min(y[point_index as usize]);
654        min[2] = min[2].min(z[point_index as usize]);
655        max[0] = max[0].max(x[point_index as usize]);
656        max[1] = max[1].max(y[point_index as usize]);
657        max[2] = max[2].max(z[point_index as usize]);
658    }
659
660    let mut best_axis = 0_u8;
661    let mut best_extent = max[0] - min[0];
662    for axis in 1_u8..3 {
663        let extent = max[axis as usize] - min[axis as usize];
664        if extent > best_extent {
665            best_extent = extent;
666            best_axis = axis;
667        }
668    }
669    (best_axis, min[best_axis as usize])
670}
671
672fn select_nth_by_axis(
673    x: &[f32],
674    y: &[f32],
675    z: &[f32],
676    points_order: &mut [u32],
677    start: usize,
678    end: usize,
679    axis_and_minimum: (u8, f32),
680    nth: usize,
681) {
682    let (axis, mut lower_bound) = axis_and_minimum;
683    let mut left = start;
684    let mut right = end;
685    while left < right {
686        let pivot_index = (left + right) / 2;
687        let pivot_value = coordinate(x, y, z, points_order[pivot_index], axis);
688        let pivot = if pivot_value == lower_bound || pivot_value.is_nan() {
689            // Nothing compares below the known lower bound, or below NaN.
690            // The original partition then performs only this pivot swap.
691            // Retain that exact permutation, including equal-distance ties.
692            points_order.swap(left, pivot_index);
693            left
694        } else {
695            partition_by_axis(x, y, z, points_order, left, right, axis)
696        };
697        match nth.cmp(&pivot) {
698            Ordering::Less => right = pivot,
699            Ordering::Greater => {
700                left = pivot + 1;
701                // The retained finite values did not compare below this
702                // pivot. NaN partitions provide no new numeric lower bound.
703                if !pivot_value.is_nan() {
704                    lower_bound = pivot_value;
705                }
706            }
707            Ordering::Equal => break,
708        }
709    }
710}
711
712#[cfg(all(test, not(target_arch = "wasm32")))]
713#[path = "../tests/fixtures/kdtree_serial.rs"]
714#[allow(dead_code)]
715mod previous;
716
717#[cfg(all(test, not(target_arch = "wasm32")))]
718#[path = "kdtree_partition_tests.rs"]
719mod partition_tests;
720
721#[cfg(all(test, not(target_arch = "wasm32")))]
722#[path = "kdtree_partition_benchmark.rs"]
723mod partition_benchmark;
724
725#[cfg(all(test, not(target_arch = "wasm32")))]
726#[path = "kdtree_nearest_tests.rs"]
727mod nearest_tests;
728
729#[cfg(all(test, not(target_arch = "wasm32")))]
730#[path = "kdtree_nearest_benchmark.rs"]
731mod nearest_benchmark;
732
733#[cfg(all(test, feature = "parallel", not(target_arch = "wasm32")))]
734#[path = "kdtree_build_benchmark.rs"]
735mod build_benchmark;
736
737fn partition_by_axis(
738    x: &[f32],
739    y: &[f32],
740    z: &[f32],
741    points_order: &mut [u32],
742    start: usize,
743    end: usize,
744    axis: u8,
745) -> usize {
746    let pivot_index = (start + end) / 2;
747    points_order.swap(start, pivot_index);
748    let pivot_point = points_order[start];
749    let pivot_value = coordinate(x, y, z, pivot_point, axis);
750
751    let mut store = start + 1;
752    for i in (start + 1)..end {
753        if coordinate(x, y, z, points_order[i], axis) < pivot_value {
754            points_order.swap(i, store);
755            store += 1;
756        }
757    }
758    points_order.swap(start, store - 1);
759    store - 1
760}
761
762fn coordinate(x: &[f32], y: &[f32], z: &[f32], point_index: u32, axis: u8) -> f32 {
763    match axis {
764        0 => x[point_index as usize],
765        1 => y[point_index as usize],
766        _ => z[point_index as usize],
767    }
768}
769
770fn squared_distance(px: f32, py: f32, pz: f32, qx: f32, qy: f32, qz: f32) -> f32 {
771    let dx = px - qx;
772    let dy = py - qy;
773    let dz = pz - qz;
774    dx * dx + dy * dy + dz * dz
775}
776
777#[derive(Debug)]
778struct KnnAccumulator<'a> {
779    neighbors: &'a mut Vec<Neighbor>,
780    worst_index: usize,
781    worst_distance_squared: f32,
782}
783
784impl<'a> KnnAccumulator<'a> {
785    fn new(neighbors: &'a mut Vec<Neighbor>) -> Self {
786        Self { neighbors, worst_index: 0, worst_distance_squared: 0.0 }
787    }
788
789    fn len(&self) -> usize {
790        self.neighbors.len()
791    }
792
793    fn prune_distance(&self, k: usize) -> f32 {
794        if self.neighbors.len() < k {
795            f32::INFINITY
796        } else {
797            self.worst_distance_squared
798        }
799    }
800
801    fn insert(&mut self, k: usize, candidate: Neighbor) {
802        if k == 0 {
803            return;
804        }
805
806        if self.neighbors.len() < k {
807            let distance_squared = candidate.distance_squared;
808            self.neighbors.push(candidate);
809            if self.neighbors.len() == 1 || distance_squared > self.worst_distance_squared {
810                self.worst_index = self.neighbors.len() - 1;
811                self.worst_distance_squared = distance_squared;
812            }
813            return;
814        }
815
816        if candidate.distance_squared >= self.worst_distance_squared {
817            return;
818        }
819
820        self.neighbors[self.worst_index] = candidate;
821        self.refresh_worst();
822    }
823
824    fn refresh_worst(&mut self) {
825        let mut worst_index = 0usize;
826        let mut worst_distance_squared = self.neighbors[0].distance_squared;
827        for (index, neighbor) in self.neighbors.iter().enumerate().skip(1) {
828            if neighbor.distance_squared > worst_distance_squared {
829                worst_index = index;
830                worst_distance_squared = neighbor.distance_squared;
831            }
832        }
833        self.worst_index = worst_index;
834        self.worst_distance_squared = worst_distance_squared;
835    }
836}
837
838#[cfg(test)]
839mod tests {
840    use super::KdTree;
841    use crate::{
842        brute::{brute_force_knn, brute_force_radius, BruteForceIndex},
843        NearestNeighborIndex, RadiusSearchIndex,
844    };
845    use spatialrust_core::{PointCloudBuilder, StandardSchemas};
846
847    use crate::SpatialIndex;
848
849    fn sample_cloud() -> (Vec<f32>, Vec<f32>, Vec<f32>) {
850        (
851            vec![0.0, 1.0, 2.0, 3.0, 4.0, 5.0],
852            vec![0.0, 0.0, 0.0, 1.0, 2.0, 0.0],
853            vec![0.0, 0.0, 0.0, 0.0, 0.0, 5.0],
854        )
855    }
856
857    #[test]
858    fn bounded_nearest_matches_unbounded_then_gate() {
859        let x: Vec<f32> = (0..257).map(|i| ((i * 37) % 101) as f32 / 13.0).collect();
860        let y: Vec<f32> = (0..257).map(|i| ((i * 53) % 97) as f32 / 17.0).collect();
861        let z: Vec<f32> = (0..257).map(|i| ((i * 19) % 89) as f32 / 11.0).collect();
862        let tree = KdTree::from_slices(&x, &y, &z);
863        for i in 0..1000 {
864            let query = [
865                ((i * 43) % 139) as f32 / 9.0 - 4.0,
866                ((i * 61) % 131) as f32 / 13.0 - 3.0,
867                ((i * 29) % 127) as f32 / 7.0 - 5.0,
868            ];
869            for bound in [0.0, 0.0025, 0.16, 4.0, f32::INFINITY] {
870                let expected = tree
871                    .nearest_one(query[0], query[1], query[2])
872                    .filter(|n| n.distance_squared <= bound);
873                assert_eq!(tree.nearest_one_within(query[0], query[1], query[2], bound), expected);
874            }
875        }
876    }
877
878    #[test]
879    fn bounded_nearest_handles_boundary_ties_and_invalid_queries() {
880        let x: Vec<f32> = (0..64).map(|i| if i % 2 == 0 { -1.0 } else { 1.0 }).collect();
881        let zero = vec![0.0; x.len()];
882        let tree = KdTree::from_slices(&x, &zero, &zero);
883        assert_eq!(tree.nearest_one_within(0.0, 0.0, 0.0, 1.0), tree.nearest_one(0.0, 0.0, 0.0));
884        assert!(tree.nearest_one_within(0.0, 0.0, 0.0, 0.99).is_none());
885        assert_eq!(tree.nearest_one_within(1.0, 0.0, 0.0, 0.0), tree.nearest_one(1.0, 0.0, 0.0));
886        assert!(tree.nearest_one_within(0.0, 0.0, 0.0, -1.0).is_none());
887        assert!(tree.nearest_one_within(0.0, 0.0, 0.0, f32::NAN).is_none());
888        assert!(tree.nearest_one_within(f32::NAN, 0.0, 0.0, 1.0).is_none());
889        assert!(KdTree::from_slices(&[], &[], &[])
890            .nearest_one_within(0.0, 0.0, 0.0, 1.0)
891            .is_none());
892    }
893
894    #[test]
895    fn nearest_one_matches_brute_force() {
896        let (x, y, z) = sample_cloud();
897        let tree = KdTree::from_slices(&x, &y, &z);
898        let brute = BruteForceIndex::from_slices(&x, &y, &z);
899
900        let query = (2.1_f32, 0.0, 0.0);
901        assert_eq!(
902            tree.nearest_one(query.0, query.1, query.2),
903            brute.nearest_one(query.0, query.1, query.2)
904        );
905    }
906
907    #[test]
908    fn nearest_k_matches_brute_force() {
909        let (x, y, z) = sample_cloud();
910        let tree = KdTree::from_slices(&x, &y, &z);
911        let expected = brute_force_knn(&x, &y, &z, 1.0, 0.0, 0.0, 3);
912        let actual = tree.nearest_k(1.0, 0.0, 0.0, 3);
913        assert_eq!(actual, expected);
914    }
915
916    #[test]
917    fn radius_search_matches_brute_force() {
918        let (x, y, z) = sample_cloud();
919        let tree = KdTree::from_slices(&x, &y, &z);
920        let mut expected = brute_force_radius(&x, &y, &z, 2.0, 0.0, 0.0, 1.5);
921        let mut actual = tree.radius_search(2.0, 0.0, 0.0, 1.5);
922        // `radius_search` is unsorted, so compare as sets ordered by index.
923        expected.sort_by_key(|n| n.index);
924        actual.sort_by_key(|n| n.index);
925        assert_eq!(actual, expected);
926    }
927
928    #[test]
929    fn radius_reaches_matches_radius_search_count() {
930        let (x, y, z) = sample_cloud();
931        let tree = KdTree::from_slices(&x, &y, &z);
932        let count = tree.radius_search(2.0, 0.0, 0.0, 1.5).len();
933        // True for any target up to the real count, false beyond it.
934        assert!(tree.radius_reaches(2.0, 0.0, 0.0, 1.5, count));
935        assert!(!tree.radius_reaches(2.0, 0.0, 0.0, 1.5, count + 1));
936        assert!(tree.radius_reaches(2.0, 0.0, 0.0, 1.5, 0));
937    }
938
939    #[test]
940    fn radius_reaches_matches_brute_force_on_many_queries() {
941        let mut state = 0x8765_4321_u32;
942        let mut next = || {
943            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
944            (state as f32 / u32::MAX as f32) * 20.0 - 10.0
945        };
946
947        let mut x = Vec::new();
948        let mut y = Vec::new();
949        let mut z = Vec::new();
950        for _ in 0..257 {
951            x.push(next());
952            y.push(next());
953            z.push(next());
954        }
955
956        let tree = KdTree::from_slices(&x, &y, &z);
957        for radius in [0.5_f32, 2.0, 5.0] {
958            for _ in 0..32 {
959                let qx = next();
960                let qy = next();
961                let qz = next();
962                let count = brute_force_radius(&x, &y, &z, qx, qy, qz, radius).len();
963                assert!(tree.radius_reaches(qx, qy, qz, radius, 0));
964                if count > 0 {
965                    assert!(tree.radius_reaches(qx, qy, qz, radius, count));
966                }
967                assert!(!tree.radius_reaches(qx, qy, qz, radius, count + 1));
968            }
969        }
970    }
971
972    #[test]
973    fn nearest_k_matches_brute_force_on_many_queries() {
974        let mut state = 0x1234_5678_u32;
975        let mut next = || {
976            state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
977            (state as f32 / u32::MAX as f32) * 20.0 - 10.0
978        };
979
980        let mut x = Vec::new();
981        let mut y = Vec::new();
982        let mut z = Vec::new();
983        for _ in 0..257 {
984            x.push(next());
985            y.push(next());
986            z.push(next());
987        }
988
989        let tree = KdTree::from_slices(&x, &y, &z);
990        for k in [1_usize, 2, 5, 10, 33] {
991            for _ in 0..64 {
992                let qx = next();
993                let qy = next();
994                let qz = next();
995                let actual = tree.nearest_k(qx, qy, qz, k);
996                let expected = brute_force_knn(&x, &y, &z, qx, qy, qz, k);
997                assert_eq!(actual, expected, "k={k}, query=({qx}, {qy}, {qz})");
998            }
999        }
1000    }
1001
1002    #[test]
1003    fn builds_from_point_cloud() {
1004        let mut builder = PointCloudBuilder::new(StandardSchemas::point_xyz());
1005        builder.push_point([0.0, 0.0, 0.0]).unwrap();
1006        builder.push_point([1.0, 0.0, 0.0]).unwrap();
1007        let cloud = builder.build().unwrap();
1008        let tree = KdTree::from_point_cloud(&cloud).unwrap();
1009        assert_eq!(tree.len(), 2);
1010        let nearest = tree.nearest_one(0.9, 0.0, 0.0).unwrap();
1011        assert_eq!(nearest.index, 1);
1012    }
1013
1014    #[test]
1015    fn degenerate_points_return_valid_neighbor() {
1016        let x = vec![1.0, 1.0, 1.0];
1017        let y = vec![2.0, 2.0, 2.0];
1018        let z = vec![3.0, 3.0, 3.0];
1019        let tree = KdTree::from_slices(&x, &y, &z);
1020        let neighbor = tree.nearest_one(1.0, 2.0, 2.0).unwrap();
1021        assert_eq!(neighbor.distance_squared, 1.0);
1022    }
1023}