1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
use std::cmp::Reverse;
use std::collections::BinaryHeap;
use geo_traits::{CoordTrait, RectTrait};
use crate::error::Result;
use crate::indices::Indices;
use crate::r#type::IndexableNum;
use crate::rtree::index::{RTree, RTreeRef};
use crate::rtree::traversal::{IntersectionIterator, Node};
use crate::rtree::util::upper_bound;
use crate::rtree::RTreeMetadata;
use crate::GeoIndexError;
/// A trait for searching and accessing data out of an RTree.
pub trait RTreeIndex<N: IndexableNum>: Sized {
/// A slice representing all the bounding boxes of all elements contained within this tree,
/// including the bounding boxes of each internal node.
fn boxes(&self) -> &[N];
/// A slice representing the indices within the `boxes` slice, including internal nodes.
fn indices(&self) -> Indices;
/// Access the metadata describing this RTree
fn metadata(&self) -> &RTreeMetadata<N>;
/// The total number of items contained in this RTree.
fn num_items(&self) -> u32 {
self.metadata().num_items()
}
/// The total number of nodes in this RTree, including both leaf and intermediate nodes.
fn num_nodes(&self) -> usize {
self.metadata().num_nodes()
}
/// The maximum number of elements in each node.
fn node_size(&self) -> u16 {
self.metadata().node_size()
}
/// The offsets into [RTreeIndex::boxes] where each level's boxes starts and ends. The tree is
/// laid out bottom-up, and there's an implicit initial 0. So the boxes of the lowest level of
/// the tree are located from `boxes[0..self.level_bounds()[0]]`.
fn level_bounds(&self) -> &[usize] {
self.metadata().level_bounds()
}
/// The number of levels (height) of the tree.
fn num_levels(&self) -> usize {
self.level_bounds().len()
}
/// The tree is laid out from bottom to top. Level 0 is the _base_ of the tree. Each integer
/// higher is one level higher of the tree.
fn boxes_at_level(&self, level: usize) -> Result<&[N]> {
let level_bounds = self.level_bounds();
if level >= level_bounds.len() {
return Err(GeoIndexError::General("Level out of bounds".to_string()));
}
let result = if level == 0 {
&self.boxes()[0..level_bounds[0]]
} else if level == level_bounds.len() {
&self.boxes()[level_bounds[level]..]
} else {
&self.boxes()[level_bounds[level - 1]..level_bounds[level]]
};
Ok(result)
}
/// Search an RTree given the provided bounding box.
///
/// Results are the indexes of the inserted objects in insertion order.
fn search(&self, min_x: N, min_y: N, max_x: N, max_y: N) -> Vec<u32> {
let boxes = self.boxes();
let indices = self.indices();
let mut outer_node_index = Some(boxes.len() - 4);
let mut queue = vec![];
let mut results = vec![];
while let Some(node_index) = outer_node_index {
// find the end index of the node
let end = (node_index + self.node_size() as usize * 4)
.min(upper_bound(node_index, self.level_bounds()));
// search through child nodes
for pos in (node_index..end).step_by(4) {
// check if node bbox intersects with query bbox
if max_x < boxes[pos] {
continue; // maxX < nodeMinX
}
if max_y < boxes[pos + 1] {
continue; // maxY < nodeMinY
}
if min_x > boxes[pos + 2] {
continue; // minX > nodeMaxX
}
if min_y > boxes[pos + 3] {
continue; // minY > nodeMaxY
}
let index = indices.get(pos >> 2);
if node_index >= self.num_items() as usize * 4 {
queue.push(index); // node; add it to the search queue
} else {
// Since the max items of the index is u32, we can coerce to u32
results.push(index.try_into().unwrap()); // leaf item
}
}
outer_node_index = queue.pop();
}
results
}
/// Search an RTree given the provided bounding box.
///
/// Results are the indexes of the inserted objects in insertion order.
fn search_rect(&self, rect: &impl RectTrait<T = N>) -> Vec<u32> {
self.search(
rect.min().x(),
rect.min().y(),
rect.max().x(),
rect.max().y(),
)
}
/// Search items in order of distance from the given point.
///
/// ```
/// use geo_index::rtree::{RTreeBuilder, RTreeIndex, RTreeRef};
/// use geo_index::rtree::sort::HilbertSort;
///
/// // Create an RTree
/// let mut builder = RTreeBuilder::<f64>::new(3);
/// builder.add(0., 0., 2., 2.);
/// builder.add(1., 1., 3., 3.);
/// builder.add(2., 2., 4., 4.);
/// let tree = builder.finish::<HilbertSort>();
///
/// let results = tree.neighbors(5., 5., None, None);
/// assert_eq!(results, vec![2, 1, 0]);
/// ```
fn neighbors(
&self,
x: N,
y: N,
max_results: Option<usize>,
max_distance: Option<N>,
) -> Vec<u32> {
let boxes = self.boxes();
let indices = self.indices();
let max_distance = max_distance.unwrap_or(N::max_value());
let mut outer_node_index = Some(boxes.len() - 4);
let mut queue = BinaryHeap::new();
let mut results: Vec<u32> = vec![];
let max_dist_squared = max_distance * max_distance;
'outer: while let Some(node_index) = outer_node_index {
// find the end index of the node
let end = (node_index + self.node_size() as usize * 4)
.min(upper_bound(node_index, self.level_bounds()));
// add child nodes to the queue
for pos in (node_index..end).step_by(4) {
let index = indices.get(pos >> 2);
let dx = axis_dist(x, boxes[pos], boxes[pos + 2]);
let dy = axis_dist(y, boxes[pos + 1], boxes[pos + 3]);
let dist = dx * dx + dy * dy;
if dist > max_dist_squared {
continue;
}
if node_index >= self.num_items() as usize * 4 {
// node (use even id)
queue.push(Reverse(NeighborNode {
id: index << 1,
dist,
}));
} else {
// leaf item (use odd id)
queue.push(Reverse(NeighborNode {
id: (index << 1) + 1,
dist,
}));
}
}
// pop items from the queue
while !queue.is_empty() && queue.peek().is_some_and(|val| (val.0.id & 1) != 0) {
let dist = queue.peek().unwrap().0.dist;
if dist > max_dist_squared {
break 'outer;
}
let item = queue.pop().unwrap();
results.push((item.0.id >> 1).try_into().unwrap());
if max_results.is_some_and(|max_results| results.len() == max_results) {
break 'outer;
}
}
if let Some(item) = queue.pop() {
outer_node_index = Some(item.0.id >> 1);
} else {
outer_node_index = None;
}
}
results
}
/// Search items in order of distance from the given coordinate.
fn neighbors_coord(
&self,
coord: &impl CoordTrait<T = N>,
max_results: Option<usize>,
max_distance: Option<N>,
) -> Vec<u32> {
self.neighbors(coord.x(), coord.y(), max_results, max_distance)
}
/// Returns an iterator over the indexes of objects in this and another tree that intersect.
///
/// Each returned object is of the form `(u32, u32)`, where the first is the positional
/// index of the "left" tree and the second is the index of the "right" tree.
fn intersection_candidates_with_other_tree<'a>(
&'a self,
other: &'a impl RTreeIndex<N>,
) -> impl Iterator<Item = (u32, u32)> + 'a {
IntersectionIterator::from_trees(self, other)
}
/// Access the root node of the RTree for manual traversal.
fn root(&self) -> Node<'_, N, Self> {
Node::from_root(self)
}
}
/// A wrapper around a node and its distance for use in the priority queue.
#[derive(Debug, Clone, Copy, PartialEq)]
struct NeighborNode<N: IndexableNum> {
id: usize,
dist: N,
}
impl<N: IndexableNum> Eq for NeighborNode<N> {}
impl<N: IndexableNum> Ord for NeighborNode<N> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
// We don't allow NaN. This should only panic on NaN
self.dist.partial_cmp(&other.dist).unwrap()
}
}
impl<N: IndexableNum> PartialOrd for NeighborNode<N> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl<N: IndexableNum> RTreeIndex<N> for RTree<N> {
fn boxes(&self) -> &[N] {
self.metadata.boxes_slice(&self.buffer)
}
fn indices(&self) -> Indices {
self.metadata.indices_slice(&self.buffer)
}
fn metadata(&self) -> &RTreeMetadata<N> {
&self.metadata
}
}
impl<N: IndexableNum> RTreeIndex<N> for RTreeRef<'_, N> {
fn boxes(&self) -> &[N] {
self.boxes
}
fn indices(&self) -> Indices {
self.indices
}
fn metadata(&self) -> &RTreeMetadata<N> {
&self.metadata
}
}
/// 1D distance from a value to a range.
#[allow(dead_code)]
#[inline]
fn axis_dist<N: IndexableNum>(k: N, min: N, max: N) -> N {
if k < min {
min - k
} else if k <= max {
N::zero()
} else {
k - max
}
}
#[cfg(test)]
mod test {
// Replication of tests from flatbush js
mod js {
use crate::rtree::RTreeIndex;
use crate::test::{flatbush_js_test_data, flatbush_js_test_index};
#[test]
fn performs_bbox_search() {
let data = flatbush_js_test_data();
let index = flatbush_js_test_index();
let ids = index.search(40., 40., 60., 60.);
let mut results: Vec<usize> = vec![];
for id in ids {
results.push(data[4 * id as usize] as usize);
results.push(data[4 * id as usize + 1] as usize);
results.push(data[4 * id as usize + 2] as usize);
results.push(data[4 * id as usize + 3] as usize);
}
results.sort();
let mut expected = vec![
57, 59, 58, 59, 48, 53, 52, 56, 40, 42, 43, 43, 43, 41, 47, 43,
];
expected.sort();
assert_eq!(results, expected);
}
}
}