geo-index 0.3.3

Fast, immutable, ABI-stable spatial indexes.
Documentation
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
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
//! Utilities to traverse the RTree structure.

use geo_traits::{
    GeometryTrait, RectTrait, UnimplementedGeometryCollection, UnimplementedLine,
    UnimplementedLineString, UnimplementedMultiLineString, UnimplementedMultiPoint,
    UnimplementedMultiPolygon, UnimplementedPoint, UnimplementedPolygon, UnimplementedTriangle,
};

use crate::r#type::{Coord, IndexableNum};
use crate::rtree::util::upper_bound;
use crate::rtree::RTreeIndex;
use core::mem::take;
use std::marker::PhantomData;

/// An internal node in the RTree.
#[derive(Debug, Clone)]
pub struct Node<'a, N: IndexableNum, T: RTreeIndex<N>> {
    /// The tree that this node is a reference onto
    tree: &'a T,

    /// This points to the position in the full `boxes` slice of the **first** coordinate of
    /// this node. So
    /// ```notest
    /// self.tree.boxes()[self.pos]
    /// ```
    /// accesses the `min_x` coordinate of this node.
    ///
    /// This also relates to the children and the insertion index. When this is `<
    /// self.tree.num_items() * 4`, it means it's a leaf node at the bottom of the tree. In this
    /// case, calling `>> 2` on this finds the original insertion index.
    ///
    /// When this is `>= self.tree.num_items() * 4`, it means it's _not_ a leaf node, and calling
    /// `>> 2` retrieves the `pos` of the first of its children.
    pos: usize,

    phantom: PhantomData<N>,
}

impl<'a, N: IndexableNum, T: RTreeIndex<N>> Node<'a, N, T> {
    fn new(tree: &'a T, pos: usize) -> Self {
        Self {
            tree,
            pos,
            phantom: PhantomData,
        }
    }

    pub(crate) fn from_root(tree: &'a T) -> Self {
        let root_index = tree.boxes().len() - 4;
        Self {
            tree,
            pos: root_index,
            phantom: PhantomData,
        }
    }

    /// Get the minimum `x` value of this node.
    #[inline]
    pub fn min_x(&self) -> N {
        self.tree.boxes()[self.pos]
    }

    /// Get the minimum `y` value of this node.
    #[inline]
    pub fn min_y(&self) -> N {
        self.tree.boxes()[self.pos + 1]
    }

    /// Get the maximum `x` value of this node.
    #[inline]
    pub fn max_x(&self) -> N {
        self.tree.boxes()[self.pos + 2]
    }

    /// Get the maximum `y` value of this node.
    #[inline]
    pub fn max_y(&self) -> N {
        self.tree.boxes()[self.pos + 3]
    }

    /// Returns `true` if this is a leaf node without children.
    #[inline]
    pub fn is_leaf(&self) -> bool {
        self.pos < self.tree.num_items() as usize * 4
    }

    /// Returns `true` if this is an intermediate node with children.
    #[inline]
    pub fn is_parent(&self) -> bool {
        !self.is_leaf()
    }

    /// Returns `true` if this node intersects another node.
    #[inline]
    pub fn intersects<T2: RTreeIndex<N>>(&self, other: &Node<N, T2>) -> bool {
        if self.max_x() < other.min_x() {
            return false;
        }

        if self.max_y() < other.min_y() {
            return false;
        }

        if self.min_x() > other.max_x() {
            return false;
        }

        if self.min_y() > other.max_y() {
            return false;
        }

        true
    }

    /// Returns an iterator over the child nodes of this node.
    ///
    /// Returns `None` if [`Self::is_parent`] is `false`.
    pub fn children(&self) -> Option<impl Iterator<Item = Node<'_, N, T>>> {
        if self.is_parent() {
            Some(self.children_unchecked())
        } else {
            None
        }
    }

    /// Returns an iterator over the child nodes of this node. This is only valid when
    /// [`Self::is_parent`] is `true`.
    pub fn children_unchecked(&self) -> impl Iterator<Item = Node<'_, N, T>> {
        debug_assert!(self.is_parent());

        // find the start and end indexes of the children of this node
        let start_child_pos = self.tree.indices().get(self.pos >> 2);
        let end_children_pos = (start_child_pos + self.tree.node_size() as usize * 4)
            .min(upper_bound(start_child_pos, self.tree.level_bounds()));

        (start_child_pos..end_children_pos)
            .step_by(4)
            .map(|pos| Node::new(self.tree, pos))
    }

    /// The original insertion index. This is only valid when this is a leaf node, which you can
    /// check with `Self::is_leaf`.
    ///
    /// Returns `None` if [`Self::is_leaf`] is `false`.
    #[inline]
    pub fn insertion_index(&self) -> Option<u32> {
        if self.is_leaf() {
            Some(self.insertion_index_unchecked())
        } else {
            None
        }
    }

    /// The original insertion index. This is only valid when this is a leaf node, which you can
    /// check with `Self::is_leaf`.
    #[inline]
    pub fn insertion_index_unchecked(&self) -> u32 {
        debug_assert!(self.is_leaf());
        self.tree.indices().get(self.pos >> 2) as u32
    }
}

impl<N: IndexableNum, T: RTreeIndex<N>> RectTrait for Node<'_, N, T> {
    type CoordType<'a>
        = Coord<N>
    where
        Self: 'a;

    fn min(&self) -> Self::CoordType<'_> {
        Coord {
            x: self.min_x(),
            y: self.min_y(),
        }
    }

    fn max(&self) -> Self::CoordType<'_> {
        Coord {
            x: self.max_x(),
            y: self.max_y(),
        }
    }
}

impl<N: IndexableNum, T: RTreeIndex<N>> GeometryTrait for Node<'_, N, T> {
    type T = N;

    type PointType<'a>
        = UnimplementedPoint<N>
    where
        Self: 'a;

    type LineStringType<'a>
        = UnimplementedLineString<N>
    where
        Self: 'a;

    type PolygonType<'a>
        = UnimplementedPolygon<N>
    where
        Self: 'a;

    type MultiPointType<'a>
        = UnimplementedMultiPoint<N>
    where
        Self: 'a;

    type MultiLineStringType<'a>
        = UnimplementedMultiLineString<N>
    where
        Self: 'a;

    type MultiPolygonType<'a>
        = UnimplementedMultiPolygon<N>
    where
        Self: 'a;

    type GeometryCollectionType<'a>
        = UnimplementedGeometryCollection<N>
    where
        Self: 'a;

    type RectType<'a>
        = Node<'a, N, T>
    where
        Self: 'a;

    type TriangleType<'a>
        = UnimplementedTriangle<N>
    where
        Self: 'a;

    type LineType<'a>
        = UnimplementedLine<N>
    where
        Self: 'a;

    fn dim(&self) -> geo_traits::Dimensions {
        geo_traits::Dimensions::Xy
    }

    fn as_type(
        &self,
    ) -> geo_traits::GeometryType<
        '_,
        Self::PointType<'_>,
        Self::LineStringType<'_>,
        Self::PolygonType<'_>,
        Self::MultiPointType<'_>,
        Self::MultiLineStringType<'_>,
        Self::MultiPolygonType<'_>,
        Self::GeometryCollectionType<'_>,
        Self::RectType<'_>,
        Self::TriangleType<'_>,
        Self::LineType<'_>,
    > {
        geo_traits::GeometryType::Rect(self)
    }
}

// This is copied from rstar under the MIT/Apache 2 license
// https://github.com/georust/rstar/blob/6c23af0f3acc0c4668ce6c368820e0fa986a65b4/rstar/src/algorithm/intersection_iterator.rs
pub(crate) struct IntersectionIterator<'a, N, T1, T2>
where
    N: IndexableNum,
    T1: RTreeIndex<N>,
    T2: RTreeIndex<N>,
{
    left: &'a T1,
    right: &'a T2,
    todo_list: Vec<(usize, usize)>,
    candidates: Vec<usize>,
    phantom: PhantomData<N>,
}

impl<'a, N, T1, T2> IntersectionIterator<'a, N, T1, T2>
where
    N: IndexableNum,
    T1: RTreeIndex<N>,
    T2: RTreeIndex<N>,
{
    pub(crate) fn from_trees(root1: &'a T1, root2: &'a T2) -> Self {
        let mut intersections = IntersectionIterator {
            left: root1,
            right: root2,
            todo_list: Vec::new(),
            candidates: Vec::new(),
            phantom: PhantomData,
        };
        intersections.add_intersecting_children(&root1.root(), &root2.root());
        intersections
    }

    #[allow(dead_code)]
    pub(crate) fn new(root1: &'a Node<N, T1>, root2: &'a Node<N, T2>) -> Self {
        let mut intersections = IntersectionIterator {
            left: root1.tree,
            right: root2.tree,
            todo_list: Vec::new(),
            candidates: Vec::new(),
            phantom: PhantomData,
        };
        intersections.add_intersecting_children(root1, root2);
        intersections
    }

    fn push_if_intersecting(&mut self, node1: &'_ Node<N, T1>, node2: &'_ Node<N, T2>) {
        if node1.intersects(node2) {
            self.todo_list.push((node1.pos, node2.pos));
        }
    }

    fn add_intersecting_children(&mut self, parent1: &'_ Node<N, T1>, parent2: &'_ Node<N, T2>) {
        if !parent1.intersects(parent2) {
            return;
        }

        let children1 = parent1
            .children_unchecked()
            .filter(|c1| c1.intersects(parent2));

        let mut children2 = take(&mut self.candidates);
        children2.extend(
            parent2
                .children_unchecked()
                .filter(|c2| c2.intersects(parent1))
                .map(|c| c.pos),
        );

        for child1 in children1 {
            for child2 in &children2 {
                self.push_if_intersecting(&child1, &Node::new(self.right, *child2));
            }
        }

        children2.clear();
        self.candidates = children2;
    }
}

impl<N, T1, T2> Iterator for IntersectionIterator<'_, N, T1, T2>
where
    N: IndexableNum,
    T1: RTreeIndex<N>,
    T2: RTreeIndex<N>,
{
    type Item = (u32, u32);

    fn next(&mut self) -> Option<Self::Item> {
        while let Some((left_index, right_index)) = self.todo_list.pop() {
            let left = Node::new(self.left, left_index);
            let right = Node::new(self.right, right_index);
            match (left.is_leaf(), right.is_leaf()) {
                (true, true) => {
                    return Some((
                        left.insertion_index_unchecked(),
                        right.insertion_index_unchecked(),
                    ))
                }
                (true, false) => right
                    .children_unchecked()
                    .for_each(|c| self.push_if_intersecting(&left, &c)),
                (false, true) => left
                    .children_unchecked()
                    .for_each(|c| self.push_if_intersecting(&c, &right)),
                (false, false) => self.add_intersecting_children(&left, &right),
            }
        }
        None
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::test::flatbush_js_test_index;

    #[test]
    fn test_node() {
        let tree = flatbush_js_test_index();

        let top_box = tree.boxes_at_level(2).unwrap();

        // Should only be one box
        assert_eq!(top_box.len(), 4);

        // Root node should match that one box in the top level
        let root_node = tree.root();
        assert_eq!(root_node.min_x(), top_box[0]);
        assert_eq!(root_node.min_y(), top_box[1]);
        assert_eq!(root_node.max_x(), top_box[2]);
        assert_eq!(root_node.max_y(), top_box[3]);

        assert!(root_node.is_parent());

        let level_1_boxes = tree.boxes_at_level(1).unwrap();
        let level_1 = root_node.children_unchecked().collect::<Vec<_>>();
        assert_eq!(level_1.len(), level_1_boxes.len() / 4);
    }
}

#[cfg(test)]
mod test_issue_42 {
    use std::collections::HashSet;

    use crate::rtree::sort::HilbertSort;
    use crate::rtree::{RTreeBuilder, RTreeIndex};
    use geo_0_31::Polygon;
    use geo_0_31::{BoundingRect, Geometry};
    use geozero::geo_types::GeoWriter;
    use geozero::geojson::read_geojson_fc;
    use rstar::primitives::GeomWithData;
    use rstar::{primitives::Rectangle, AABB};
    use zip::ZipArchive;

    // Find tree self-intersection canddiates using rstar
    fn geo_contiguity(geom: &[Polygon]) -> HashSet<(usize, usize)> {
        let to_insert = geom
            .iter()
            .enumerate()
            .map(|(i, gi)| {
                let rect = gi.bounding_rect().unwrap();
                let aabb =
                    AABB::from_corners([rect.min().x, rect.min().y], [rect.max().x, rect.max().y]);

                GeomWithData::new(Rectangle::from_aabb(aabb), i)
            })
            .collect::<Vec<_>>();

        let tree = rstar::RTree::bulk_load(to_insert);
        let candidates = tree
            .intersection_candidates_with_other_tree(&tree)
            .map(|(left_candidate, right_candidate)| (left_candidate.data, right_candidate.data));

        HashSet::from_iter(candidates)
    }

    // Find tree self-intersection canddiates using geo-index
    fn geo_index_contiguity(geoms: &Vec<Polygon>, node_size: u16) -> HashSet<(usize, usize)> {
        let mut tree_builder = RTreeBuilder::new_with_node_size(geoms.len() as _, node_size);
        for geom in geoms {
            tree_builder.add_rect(&geom.bounding_rect().unwrap());
        }
        let tree = tree_builder.finish::<HilbertSort>();

        let candidates = tree
            .intersection_candidates_with_other_tree(&tree)
            .map(|(l, r)| (l as usize, r as usize));

        HashSet::from_iter(candidates)
    }

    #[test]
    fn test_repro_issue_42() {
        let file = std::fs::File::open("fixtures/issue_42.geojson.zip").unwrap();
        let mut zip_archive = ZipArchive::new(file).unwrap();
        let zipped_file = zip_archive.by_name("guerry.geojson").unwrap();
        let reader = std::io::BufReader::new(zipped_file);

        let mut geo_writer = GeoWriter::new();
        read_geojson_fc(reader, &mut geo_writer).unwrap();

        let geoms = match geo_writer.take_geometry().unwrap() {
            Geometry::GeometryCollection(gc) => gc.0,
            _ => panic!(),
        };

        let mut polys = vec![];
        for geom in geoms {
            let poly = match geom {
                Geometry::Polygon(poly) => poly,
                _ => panic!(),
            };
            polys.push(poly);
        }

        let geo_index_self_intersection = geo_index_contiguity(&polys, 10);
        let geo_self_intersection = geo_contiguity(&polys);

        assert_eq!(
            geo_index_self_intersection, geo_self_intersection,
            "The two intersections should match!"
        );
    }
}