Skip to main content

lib_jsl_geometry/algorithms/
region_tree.rs

1//! A point region tree: the shared engine behind quad trees (`D = 2`) and oct trees (`D = 3`).
2//!
3//! See the book entry [Spatial trees](https://jwkunz.github.io/lib_jsl/book/geometry/spatial-trees.html#quadtrees-and-octrees).
4
5use std::cmp::Ordering;
6use std::collections::BinaryHeap;
7
8#[derive(Debug, Clone)]
9
10struct Node<const D: usize> {
11    min: [f64; D],
12    max: [f64; D],
13    entries: Vec<(usize, [f64; D])>,
14    children: Vec<Node<D>>,
15}
16
17#[derive(PartialEq)]
18
19struct Candidate {
20    dist2: f64,
21    id: usize,
22}
23impl Eq for Candidate {}
24impl PartialOrd for Candidate {
25    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
26        Some(self.cmp(other))
27    }
28}
29impl Ord for Candidate {
30    fn cmp(&self, other: &Self) -> Ordering {
31        self.dist2.total_cmp(&other.dist2).then(self.id.cmp(&other.id))
32    }
33}
34
35fn point_dist2<const D: usize>(a: &[f64; D], b: &[f64; D]) -> f64 {
36    (0..D).map(|k| (a[k] - b[k]) * (a[k] - b[k])).sum()
37}
38
39impl<const D: usize> Node<D> {
40    fn new(min: [f64; D], max: [f64; D]) -> Self {
41        Node { min, max, entries: Vec::new(), children: Vec::new() }
42    }
43
44    fn centre(&self) -> [f64; D] {
45        std::array::from_fn(|k| 0.5 * (self.min[k] + self.max[k]))
46    }
47
48    fn child_index(&self, p: &[f64; D]) -> usize {
49        let c = self.centre();
50        (0..D).fold(0, |acc, k| acc | (usize::from(p[k] >= c[k]) << k))
51    }
52
53    /// Squared distance from `q` to the closest point of this node's box.
54    fn box_dist2(&self, q: &[f64; D]) -> f64 {
55        (0..D)
56            .map(|k| {
57                let d = (self.min[k] - q[k]).max(q[k] - self.max[k]).max(0.0);
58                d * d
59            })
60            .sum()
61    }
62
63    fn split(&mut self) {
64        let c = self.centre();
65        self.children = (0..1usize << D)
66            .map(|i| {
67                let min = std::array::from_fn(|k| if i >> k & 1 == 1 { c[k] } else { self.min[k] });
68                let max = std::array::from_fn(|k| if i >> k & 1 == 1 { self.max[k] } else { c[k] });
69                Node::new(min, max)
70            })
71            .collect();
72        for (id, p) in std::mem::take(&mut self.entries) {
73            let ci = self.child_index(&p);
74            self.children[ci].entries.push((id, p));
75        }
76    }
77
78    fn insert(&mut self, id: usize, p: [f64; D], capacity: usize, depth: usize, max_depth: usize) {
79        if self.children.is_empty() {
80            self.entries.push((id, p));
81            if self.entries.len() > capacity && depth < max_depth {
82                self.split();
83                // Redistribution may overfill a child (clustered points); split those further.
84                for child in &mut self.children {
85                    child.resplit(capacity, depth + 1, max_depth);
86                }
87            }
88        } else {
89            let ci = self.child_index(&p);
90            self.children[ci].insert(id, p, capacity, depth + 1, max_depth);
91        }
92    }
93
94    fn resplit(&mut self, capacity: usize, depth: usize, max_depth: usize) {
95        if self.entries.len() > capacity && depth < max_depth {
96            self.split();
97            for child in &mut self.children {
98                child.resplit(capacity, depth + 1, max_depth);
99            }
100        }
101    }
102
103    fn remove(&mut self, id: usize, p: &[f64; D]) -> bool {
104        if self.children.is_empty() {
105            if let Some(pos) = self.entries.iter().position(|(i, q)| *i == id && q == p) {
106                self.entries.swap_remove(pos);
107                return true;
108            }
109            return false;
110        }
111        let ci = self.child_index(p);
112        let removed = self.children[ci].remove(id, p);
113        // Collapse if the whole subtree has become small enough to be one leaf again.
114        if removed && self.children.iter().all(|c| c.children.is_empty()) && self.children.iter().map(|c| c.entries.len()).sum::<usize>() == 0 {
115            self.children.clear();
116        }
117        removed
118    }
119
120    fn query_box(&self, min: &[f64; D], max: &[f64; D], out: &mut Vec<usize>) {
121        if (0..D).any(|k| self.max[k] < min[k] || self.min[k] > max[k]) {
122            return;
123        }
124        out.extend(self.entries.iter().filter(|(_, p)| (0..D).all(|k| p[k] >= min[k] && p[k] <= max[k])).map(|(id, _)| *id));
125        self.children.iter().for_each(|c| c.query_box(min, max, out));
126    }
127
128    fn query_radius(&self, q: &[f64; D], r2: f64, out: &mut Vec<usize>) {
129        if self.box_dist2(q) > r2 {
130            return;
131        }
132        out.extend(self.entries.iter().filter(|(_, p)| point_dist2(p, q) <= r2).map(|(id, _)| *id));
133        self.children.iter().for_each(|c| c.query_radius(q, r2, out));
134    }
135
136    fn k_nearest(&self, q: &[f64; D], k: usize, heap: &mut BinaryHeap<Candidate>) {
137        if heap.len() >= k && heap.peek().is_some_and(|w| self.box_dist2(q) > w.dist2) {
138            return;
139        }
140        for (id, p) in &self.entries {
141            let cand = Candidate { dist2: point_dist2(p, q), id: *id };
142            if heap.len() < k {
143                heap.push(cand);
144            } else if heap.peek().is_some_and(|w| cand < *w) {
145                heap.pop();
146                heap.push(cand);
147            }
148        }
149        // Visit children nearest-first so pruning kicks in early.
150        let mut order: Vec<&Node<D>> = self.children.iter().collect();
151        order.sort_by(|a, b| a.box_dist2(q).total_cmp(&b.box_dist2(q)));
152        for child in order {
153            child.k_nearest(q, k, heap);
154        }
155    }
156}
157
158/// A point tree over an axis-aligned region of `D`-space. Each leaf holds up to `capacity` points
159/// before splitting into `2^D` equal sub-boxes (down to `max_depth` levels, so coincident points
160/// cannot cause unbounded splitting). Entries are `(id, point)` pairs; ids are chosen by the caller.
161///
162/// See [`QuadTree`](super::quad_trees::QuadTree) (`D = 2`) and [`OctTree`](super::oct_trees::OctTree)
163/// (`D = 3`).
164#[derive(Debug, Clone)]
165
166pub struct RegionTree<const D: usize> {
167    root: Node<D>,
168    capacity: usize,
169    max_depth: usize,
170    count: usize,
171}
172
173impl<const D: usize> RegionTree<D> {
174    /// An empty tree covering `[min, max]` with leaf capacity 8 and depth limit 20.
175    pub fn new(min: [f64; D], max: [f64; D]) -> Self {
176        Self::with_limits(min, max, 8, 20)
177    }
178
179    pub fn with_limits(min: [f64; D], max: [f64; D], capacity: usize, max_depth: usize) -> Self {
180        RegionTree { root: Node::new(min, max), capacity: capacity.max(1), max_depth, count: 0 }
181    }
182
183    /// Builds a tree sized to the bounding box of `points`, using each point's index as its id.
184    pub fn from_points(points: &[[f64; D]]) -> Self {
185        let (mut lo, mut hi) = ([f64::INFINITY; D], [f64::NEG_INFINITY; D]);
186        for p in points.iter().filter(|p| p.iter().all(|v| v.is_finite())) {
187            for k in 0..D {
188                lo[k] = lo[k].min(p[k]);
189                hi[k] = hi[k].max(p[k]);
190            }
191        }
192        if lo[0] > hi[0] {
193            (lo, hi) = ([0.0; D], [1.0; D]);
194        }
195        let mut tree = Self::new(lo, hi);
196        for (i, &p) in points.iter().enumerate() {
197            tree.insert(i, p);
198        }
199        tree
200    }
201
202    /// Adds a point; returns `false` (and stores nothing) if it is non-finite or outside the region.
203    pub fn insert(&mut self, id: usize, point: [f64; D]) -> bool {
204        let r = &self.root;
205        if !(0..D).all(|k| point[k].is_finite() && point[k] >= r.min[k] && point[k] <= r.max[k]) {
206            return false;
207        }
208        self.root.insert(id, point, self.capacity, 0, self.max_depth);
209        self.count += 1;
210        true
211    }
212
213    /// Removes the entry with this `id` and `point`; returns whether it was present.
214    pub fn remove(&mut self, id: usize, point: [f64; D]) -> bool {
215        let removed = self.root.remove(id, &point);
216        if removed {
217            self.count -= 1;
218        }
219        removed
220    }
221
222    pub fn len(&self) -> usize {
223        self.count
224    }
225
226    pub fn is_empty(&self) -> bool {
227        self.count == 0
228    }
229
230    /// Ids of all points in the box `[min, max]` (inclusive).
231    pub fn query_box(&self, min: [f64; D], max: [f64; D]) -> Vec<usize> {
232        let mut out = Vec::new();
233        self.root.query_box(&min, &max, &mut out);
234        out
235    }
236
237    /// Ids of all points within `radius` of `centre` (inclusive).
238    pub fn query_radius(&self, centre: [f64; D], radius: f64) -> Vec<usize> {
239        let mut out = Vec::new();
240        if radius >= 0.0 {
241            self.root.query_radius(&centre, radius * radius, &mut out);
242        }
243        out
244    }
245
246    /// The `k` nearest points as `(id, distance)`, nearest first (ties by id).
247    pub fn k_nearest(&self, query: [f64; D], k: usize) -> Vec<(usize, f64)> {
248        if k == 0 || self.is_empty() || query.iter().any(|v| !v.is_finite()) {
249            return Vec::new();
250        }
251        let mut heap = BinaryHeap::with_capacity(k + 1);
252        self.root.k_nearest(&query, k, &mut heap);
253        let mut v = heap.into_vec();
254        v.sort();
255        v.into_iter().map(|c| (c.id, c.dist2.sqrt())).collect()
256    }
257
258    pub fn nearest(&self, query: [f64; D]) -> Option<(usize, f64)> {
259        self.k_nearest(query, 1).into_iter().next()
260    }
261
262    /// Deepest level reached by any leaf (0 for a single leaf), for diagnostics.
263    pub fn depth(&self) -> usize {
264        fn go<const D: usize>(n: &Node<D>) -> usize {
265            n.children.iter().map(|c| 1 + go(c)).max().unwrap_or(0)
266        }
267        go(&self.root)
268    }
269}