-
Notifications
You must be signed in to change notification settings - Fork 123
/
rtree.go
861 lines (741 loc) · 22.2 KB
/
rtree.go
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
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
// Copyright 2012 Daniel Connelly. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package rtreego is a library for efficiently storing and querying spatial data.
package rtreego
import (
"fmt"
"math"
"sort"
)
// Comparator compares two spatials and returns whether they are equal.
type Comparator func(obj1, obj2 Spatial) (equal bool)
func defaultComparator(obj1, obj2 Spatial) bool {
return obj1 == obj2
}
// Rtree represents an R-tree, a balanced search tree for storing and querying
// spatial objects. Dim specifies the number of spatial dimensions and
// MinChildren/MaxChildren specify the minimum/maximum branching factors.
type Rtree struct {
Dim int
MinChildren int
MaxChildren int
root *node
size int
height int
// deleted is a temporary buffer to avoid memory allocations in Delete.
// It is just an optimization and not part of the data structure.
deleted []*node
// FloatingPointTolerance is the tolerance to guard against floating point rounding errors during minMaxDist calculations.
FloatingPointTolerance float64
}
// NewTree returns an Rtree. If the number of objects given on initialization
// is larger than max, the Rtree will be initialized using the Overlap
// Minimizing Top-down bulk-loading algorithm.
func NewTree(dim, min, max int, objs ...Spatial) *Rtree {
rt := &Rtree{
Dim: dim,
MinChildren: min,
MaxChildren: max,
height: 1,
FloatingPointTolerance: 1e-6,
root: &node{
entries: []entry{},
leaf: true,
level: 1,
},
}
if len(objs) <= rt.MaxChildren {
for _, obj := range objs {
rt.Insert(obj)
}
} else {
rt.bulkLoad(objs)
}
return rt
}
// Size returns the number of objects currently stored in tree.
func (tree *Rtree) Size() int {
return tree.size
}
func (tree *Rtree) String() string {
return "foo"
}
// Depth returns the maximum depth of tree.
func (tree *Rtree) Depth() int {
return tree.height
}
type dimSorter struct {
dim int
objs []entry
}
func (s *dimSorter) Len() int {
return len(s.objs)
}
func (s *dimSorter) Swap(i, j int) {
s.objs[i], s.objs[j] = s.objs[j], s.objs[i]
}
func (s *dimSorter) Less(i, j int) bool {
return s.objs[i].bb.p[s.dim] < s.objs[j].bb.p[s.dim]
}
// walkPartitions splits objs into slices of maximum k elements and
// iterates over these partitions.
func walkPartitions(k int, objs []entry, iter func(parts []entry)) {
n := (len(objs) + k - 1) / k // ceil(len(objs) / k)
for i := 1; i < n; i++ {
iter(objs[(i-1)*k : i*k])
}
iter(objs[(n-1)*k:])
}
func sortByDim(dim int, objs []entry) {
sort.Sort(&dimSorter{dim, objs})
}
// bulkLoad bulk loads the Rtree using OMT algorithm. bulkLoad contains special
// handling for the root node.
func (tree *Rtree) bulkLoad(objs []Spatial) {
n := len(objs)
// create entries for all the objects
entries := make([]entry, n)
for i := range objs {
entries[i] = entry{
bb: objs[i].Bounds(),
obj: objs[i],
}
}
// following equations are defined in the paper describing OMT
var (
N = float64(n)
M = float64(tree.MaxChildren)
)
// Eq1: height of the tree
// use log2 instead of log due to rounding errors with log,
// eg, math.Log(9) / math.Log(3) > 2
h := math.Ceil(math.Log2(N) / math.Log2(M))
// Eq2: size of subtrees at the root
nsub := math.Pow(M, h-1)
// Inner Eq3: number of subtrees at the root
s := math.Ceil(N / nsub)
// Eq3: number of slices
S := math.Floor(math.Sqrt(s))
// sort all entries by first dimension
sortByDim(0, entries)
tree.height = int(h)
tree.size = n
tree.root = tree.omt(int(h), int(S), entries, int(s))
}
// omt is the recursive part of the Overlap Minimizing Top-loading bulk-
// load approach. Returns the root node of a subtree.
func (tree *Rtree) omt(level, nSlices int, objs []entry, m int) *node {
// if number of objects is less than or equal than max children per leaf,
// we need to create a leaf node
if len(objs) <= m {
// as long as the recursion is not at the leaf, call it again
if level > 1 {
child := tree.omt(level-1, nSlices, objs, m)
n := &node{
level: level,
entries: []entry{{
bb: child.computeBoundingBox(),
child: child,
}},
}
child.parent = n
return n
}
entries := make([]entry, len(objs))
copy(entries, objs)
return &node{
leaf: true,
entries: entries,
level: level,
}
}
n := &node{
level: level,
entries: make([]entry, 0, m),
}
// maximum node size given at most M nodes at this level
k := (len(objs) + m - 1) / m // = ceil(N / M)
// In the root level, split objs in nSlices. In all other levels,
// we use a single slice.
vertSize := len(objs)
if nSlices > 1 {
vertSize = nSlices * k
}
// create sub trees
walkPartitions(vertSize, objs, func(vert []entry) {
// sort vertical slice by a different dimension on every level
sortByDim((tree.height-level+1)%tree.Dim, vert)
// split slice into groups of size k
walkPartitions(k, vert, func(part []entry) {
child := tree.omt(level-1, 1, part, tree.MaxChildren)
child.parent = n
n.entries = append(n.entries, entry{
bb: child.computeBoundingBox(),
child: child,
})
})
})
return n
}
// node represents a tree node of an Rtree.
type node struct {
parent *node
entries []entry
level int // node depth in the Rtree
leaf bool
}
func (n *node) String() string {
return fmt.Sprintf("node{leaf: %v, entries: %v}", n.leaf, n.entries)
}
// entry represents a spatial index record stored in a tree node.
type entry struct {
bb Rect // bounding-box of all children of this entry
child *node
obj Spatial
}
func (e entry) String() string {
if e.child != nil {
return fmt.Sprintf("entry{bb: %v, child: %v}", e.bb, e.child)
}
return fmt.Sprintf("entry{bb: %v, obj: %v}", e.bb, e.obj)
}
// Spatial is an interface for objects that can be stored in an Rtree and queried.
type Spatial interface {
Bounds() Rect
}
// Insertion
// Insert inserts a spatial object into the tree. If insertion
// causes a leaf node to overflow, the tree is rebalanced automatically.
//
// Implemented per Section 3.2 of "R-trees: A Dynamic Index Structure for
// Spatial Searching" by A. Guttman, Proceedings of ACM SIGMOD, p. 47-57, 1984.
func (tree *Rtree) Insert(obj Spatial) {
e := entry{obj.Bounds(), nil, obj}
tree.insert(e, 1)
tree.size++
}
// insert adds the specified entry to the tree at the specified level.
func (tree *Rtree) insert(e entry, level int) {
leaf := tree.chooseNode(tree.root, e, level)
leaf.entries = append(leaf.entries, e)
// update parent pointer if necessary
if e.child != nil {
e.child.parent = leaf
}
// split leaf if overflows
var split *node
if len(leaf.entries) > tree.MaxChildren {
leaf, split = leaf.split(tree.MinChildren)
}
root, splitRoot := tree.adjustTree(leaf, split)
if splitRoot != nil {
oldRoot := root
tree.height++
tree.root = &node{
parent: nil,
level: tree.height,
entries: []entry{
{bb: oldRoot.computeBoundingBox(), child: oldRoot},
{bb: splitRoot.computeBoundingBox(), child: splitRoot},
},
}
oldRoot.parent = tree.root
splitRoot.parent = tree.root
}
}
// chooseNode finds the node at the specified level to which e should be added.
func (tree *Rtree) chooseNode(n *node, e entry, level int) *node {
if n.leaf || n.level == level {
return n
}
// find the entry whose bb needs least enlargement to include obj
diff := math.MaxFloat64
var chosen entry
for _, en := range n.entries {
bb := boundingBox(en.bb, e.bb)
d := bb.Size() - en.bb.Size()
if d < diff || (d == diff && en.bb.Size() < chosen.bb.Size()) {
diff = d
chosen = en
}
}
return tree.chooseNode(chosen.child, e, level)
}
// adjustTree splits overflowing nodes and propagates the changes upwards.
func (tree *Rtree) adjustTree(n, nn *node) (*node, *node) {
// Let the caller handle root adjustments.
if n == tree.root {
return n, nn
}
// Re-size the bounding box of n to account for lower-level changes.
en := n.getEntry()
prevBox := en.bb
en.bb = n.computeBoundingBox()
// If nn is nil, then we're just propagating changes upwards.
if nn == nil {
// Optimize for the case where nothing is changed
// to avoid computeBoundingBox which is expensive.
if en.bb.Equal(prevBox) {
return tree.root, nil
}
return tree.adjustTree(n.parent, nil)
}
// Otherwise, these are two nodes resulting from a split.
// n was reused as the "left" node, but we need to add nn to n.parent.
enn := entry{nn.computeBoundingBox(), nn, nil}
n.parent.entries = append(n.parent.entries, enn)
// If the new entry overflows the parent, split the parent and propagate.
if len(n.parent.entries) > tree.MaxChildren {
return tree.adjustTree(n.parent.split(tree.MinChildren))
}
// Otherwise keep propagating changes upwards.
return tree.adjustTree(n.parent, nil)
}
// getEntry returns a pointer to the entry for the node n from n's parent.
func (n *node) getEntry() *entry {
var e *entry
for i := range n.parent.entries {
if n.parent.entries[i].child == n {
e = &n.parent.entries[i]
break
}
}
return e
}
// computeBoundingBox finds the MBR of the children of n.
func (n *node) computeBoundingBox() (bb Rect) {
if len(n.entries) == 1 {
bb = n.entries[0].bb
return
}
bb = boundingBox(n.entries[0].bb, n.entries[1].bb)
for _, e := range n.entries[2:] {
bb = boundingBox(bb, e.bb)
}
return
}
// split splits a node into two groups while attempting to minimize the
// bounding-box area of the resulting groups.
func (n *node) split(minGroupSize int) (left, right *node) {
// find the initial split
l, r := n.pickSeeds()
leftSeed, rightSeed := n.entries[l], n.entries[r]
// get the entries to be divided between left and right
remaining := append(n.entries[:l], n.entries[l+1:r]...)
remaining = append(remaining, n.entries[r+1:]...)
// setup the new split nodes, but re-use n as the left node
left = n
left.entries = []entry{leftSeed}
right = &node{
parent: n.parent,
leaf: n.leaf,
level: n.level,
entries: []entry{rightSeed},
}
// TODO
if rightSeed.child != nil {
rightSeed.child.parent = right
}
if leftSeed.child != nil {
leftSeed.child.parent = left
}
// distribute all of n's old entries into left and right.
for len(remaining) > 0 {
next := pickNext(left, right, remaining)
e := remaining[next]
if len(remaining)+len(left.entries) <= minGroupSize {
assign(e, left)
} else if len(remaining)+len(right.entries) <= minGroupSize {
assign(e, right)
} else {
assignGroup(e, left, right)
}
remaining = append(remaining[:next], remaining[next+1:]...)
}
return
}
// getAllBoundingBoxes traverses tree populating slice of bounding boxes of non-leaf nodes.
func (n *node) getAllBoundingBoxes() []Rect {
var rects []Rect
if n.leaf {
return rects
}
for _, e := range n.entries {
if e.child == nil {
return rects
}
rectsInter := append(e.child.getAllBoundingBoxes(), e.bb)
rects = append(rects, rectsInter...)
}
return rects
}
func assign(e entry, group *node) {
if e.child != nil {
e.child.parent = group
}
group.entries = append(group.entries, e)
}
// assignGroup chooses one of two groups to which a node should be added.
func assignGroup(e entry, left, right *node) {
leftBB := left.computeBoundingBox()
rightBB := right.computeBoundingBox()
leftEnlarged := boundingBox(leftBB, e.bb)
rightEnlarged := boundingBox(rightBB, e.bb)
// first, choose the group that needs the least enlargement
leftDiff := leftEnlarged.Size() - leftBB.Size()
rightDiff := rightEnlarged.Size() - rightBB.Size()
if diff := leftDiff - rightDiff; diff < 0 {
assign(e, left)
return
} else if diff > 0 {
assign(e, right)
return
}
// next, choose the group that has smaller area
if diff := leftBB.Size() - rightBB.Size(); diff < 0 {
assign(e, left)
return
} else if diff > 0 {
assign(e, right)
return
}
// next, choose the group with fewer entries
if diff := len(left.entries) - len(right.entries); diff <= 0 {
assign(e, left)
return
}
assign(e, right)
}
// pickSeeds chooses two child entries of n to start a split.
func (n *node) pickSeeds() (int, int) {
left, right := 0, 1
maxWastedSpace := -1.0
for i, e1 := range n.entries {
for j, e2 := range n.entries[i+1:] {
d := boundingBox(e1.bb, e2.bb).Size() - e1.bb.Size() - e2.bb.Size()
if d > maxWastedSpace {
maxWastedSpace = d
left, right = i, j+i+1
}
}
}
return left, right
}
// pickNext chooses an entry to be added to an entry group.
func pickNext(left, right *node, entries []entry) (next int) {
maxDiff := -1.0
leftBB := left.computeBoundingBox()
rightBB := right.computeBoundingBox()
for i, e := range entries {
d1 := boundingBox(leftBB, e.bb).Size() - leftBB.Size()
d2 := boundingBox(rightBB, e.bb).Size() - rightBB.Size()
d := math.Abs(d1 - d2)
if d > maxDiff {
maxDiff = d
next = i
}
}
return
}
// Deletion
// Delete removes an object from the tree. If the object is not found, returns
// false, otherwise returns true. Uses the default comparator when checking
// equality.
//
// Implemented per Section 3.3 of "R-trees: A Dynamic Index Structure for
// Spatial Searching" by A. Guttman, Proceedings of ACM SIGMOD, p. 47-57, 1984.
func (tree *Rtree) Delete(obj Spatial) bool {
return tree.DeleteWithComparator(obj, defaultComparator)
}
// DeleteWithComparator removes an object from the tree using a custom
// comparator for evaluating equalness. This is useful when you want to remove
// an object from a tree but don't have a pointer to the original object
// anymore.
func (tree *Rtree) DeleteWithComparator(obj Spatial, cmp Comparator) bool {
n := tree.findLeaf(tree.root, obj, cmp)
if n == nil {
return false
}
ind := -1
for i, e := range n.entries {
if cmp(e.obj, obj) {
ind = i
}
}
if ind < 0 {
return false
}
n.entries = append(n.entries[:ind], n.entries[ind+1:]...)
tree.condenseTree(n)
tree.size--
if !tree.root.leaf && len(tree.root.entries) == 1 {
tree.root = tree.root.entries[0].child
}
tree.height = tree.root.level
return true
}
// findLeaf finds the leaf node containing obj.
func (tree *Rtree) findLeaf(n *node, obj Spatial, cmp Comparator) *node {
if n.leaf {
return n
}
// if not leaf, search all candidate subtrees
for _, e := range n.entries {
if e.bb.containsRect(obj.Bounds()) {
leaf := tree.findLeaf(e.child, obj, cmp)
if leaf == nil {
continue
}
// check if the leaf actually contains the object
for _, leafEntry := range leaf.entries {
if cmp(leafEntry.obj, obj) {
return leaf
}
}
}
}
return nil
}
// condenseTree deletes underflowing nodes and propagates the changes upwards.
func (tree *Rtree) condenseTree(n *node) {
// reset the deleted buffer
tree.deleted = tree.deleted[:0]
for n != tree.root {
if len(n.entries) < tree.MinChildren {
// find n and delete it by swapping the last entry into its place
idx := -1
for i, e := range n.parent.entries {
if e.child == n {
idx = i
break
}
}
if idx == -1 {
panic(fmt.Errorf("Failed to remove entry from parent"))
}
l := len(n.parent.entries)
n.parent.entries[idx] = n.parent.entries[l-1]
n.parent.entries = n.parent.entries[:l-1]
// only add n to deleted if it still has children
if len(n.entries) > 0 {
tree.deleted = append(tree.deleted, n)
}
} else {
// just a child entry deletion, no underflow
en := n.getEntry()
prevBox := en.bb
en.bb = n.computeBoundingBox()
if en.bb.Equal(prevBox) {
// Optimize for the case where nothing is changed
// to avoid computeBoundingBox which is expensive.
break
}
}
n = n.parent
}
for i := len(tree.deleted) - 1; i >= 0; i-- {
n := tree.deleted[i]
// reinsert entry so that it will remain at the same level as before
e := entry{n.computeBoundingBox(), n, nil}
tree.insert(e, n.level+1)
}
}
// Searching
// SearchIntersect returns all objects that intersect the specified rectangle.
// Implemented per Section 3.1 of "R-trees: A Dynamic Index Structure for
// Spatial Searching" by A. Guttman, Proceedings of ACM SIGMOD, p. 47-57, 1984.
func (tree *Rtree) SearchIntersect(bb Rect, filters ...Filter) []Spatial {
return tree.searchIntersect([]Spatial{}, tree.root, bb, filters)
}
// SearchIntersectWithLimit is similar to SearchIntersect, but returns
// immediately when the first k results are found. A negative k behaves exactly
// like SearchIntersect and returns all the results.
//
// Kept for backwards compatibility, please use SearchIntersect with a
// LimitFilter.
func (tree *Rtree) SearchIntersectWithLimit(k int, bb Rect) []Spatial {
// backwards compatibility, previous implementation didn't limit results if
// k was negative.
if k < 0 {
return tree.SearchIntersect(bb)
}
return tree.SearchIntersect(bb, LimitFilter(k))
}
func (tree *Rtree) searchIntersect(results []Spatial, n *node, bb Rect, filters []Filter) []Spatial {
for _, e := range n.entries {
if !intersect(e.bb, bb) {
continue
}
if !n.leaf {
results = tree.searchIntersect(results, e.child, bb, filters)
continue
}
refuse, abort := applyFilters(results, e.obj, filters)
if !refuse {
results = append(results, e.obj)
}
if abort {
break
}
}
return results
}
// NearestNeighbor returns the closest object to the specified point.
// Implemented per "Nearest Neighbor Queries" by Roussopoulos et al
func (tree *Rtree) NearestNeighbor(p Point) Spatial {
obj, _ := tree.nearestNeighbor(p, tree.root, math.MaxFloat64, nil)
return obj
}
// GetAllBoundingBoxes returning slice of bounding boxes by traversing tree. Slice
// includes bounding boxes from all non-leaf nodes.
func (tree *Rtree) GetAllBoundingBoxes() []Rect {
var rects []Rect
if tree.root != nil {
rects = tree.root.getAllBoundingBoxes()
}
return rects
}
// utilities for sorting slices of entries
type entrySlice struct {
entries []entry
dists []float64
}
func (s entrySlice) Len() int { return len(s.entries) }
func (s entrySlice) Swap(i, j int) {
s.entries[i], s.entries[j] = s.entries[j], s.entries[i]
s.dists[i], s.dists[j] = s.dists[j], s.dists[i]
}
func (s entrySlice) Less(i, j int) bool {
return s.dists[i] < s.dists[j]
}
func sortEntries(p Point, entries []entry) ([]entry, []float64) {
sorted := make([]entry, len(entries))
dists := make([]float64, len(entries))
return sortPreallocEntries(p, entries, sorted, dists)
}
func sortPreallocEntries(p Point, entries, sorted []entry, dists []float64) ([]entry, []float64) {
// use preallocated slices
sorted = sorted[:len(entries)]
dists = dists[:len(entries)]
for i := 0; i < len(entries); i++ {
sorted[i] = entries[i]
dists[i] = p.minDist(entries[i].bb)
}
sort.Sort(entrySlice{sorted, dists})
return sorted, dists
}
func pruneEntriesMinDist(d float64, entries []entry, minDists []float64) []entry {
var i int
for ; i < len(entries); i++ {
if minDists[i] > d {
break
}
}
return entries[:i]
}
func (tree *Rtree) nearestNeighbor(p Point, n *node, d float64, nearest Spatial) (Spatial, float64) {
if n.leaf {
for _, e := range n.entries {
dist := math.Sqrt(p.minDist(e.bb))
if dist < d {
d = dist
nearest = e.obj
}
}
} else {
// Search only through entries with minDist <= minMinMaxDist,
// where minDist is the distance between a point and a rectangle,
// and minMaxDist is the smallest value among the maximum distance across all axes.
//
// Entries with minDist > minMinMaxDist are guaranteed to be farther away than some other entry.
//
// For more details, please consult
// N. Roussopoulos, S. Kelley and F. Vincent, ACM SIGMOD, pages 71-79, 1995.
minMinMaxDist := math.MaxFloat64
for _, e := range n.entries {
minMaxDist := p.minMaxDist(e.bb)
if minMaxDist < minMinMaxDist {
minMinMaxDist = minMaxDist
}
}
for _, e := range n.entries {
minDist := p.minDist(e.bb)
// Add a bit of tolerance to guard against floating point rounding errors.
if minDist > minMinMaxDist+tree.FloatingPointTolerance {
continue
}
subNearest, dist := tree.nearestNeighbor(p, e.child, d, nearest)
if dist < d {
d = dist
nearest = subNearest
}
}
}
return nearest, d
}
// NearestNeighbors gets the closest Spatials to the Point.
func (tree *Rtree) NearestNeighbors(k int, p Point, filters ...Filter) []Spatial {
// preallocate the buffers for sortings the branches. At each level of the
// tree, we slide the buffer by the number of entries in the node.
maxBufSize := tree.MaxChildren * tree.Depth()
branches := make([]entry, maxBufSize)
branchDists := make([]float64, maxBufSize)
// allocate the buffers for the results
dists := make([]float64, 0, k)
objs := make([]Spatial, 0, k)
objs, _, _ = tree.nearestNeighbors(k, p, tree.root, dists, objs, filters, branches, branchDists)
return objs
}
// insert obj into nearest and return the first k elements in increasing order.
func insertNearest(k int, dists []float64, nearest []Spatial, dist float64, obj Spatial, filters []Filter) ([]float64, []Spatial, bool) {
i := sort.SearchFloat64s(dists, dist)
for i < len(nearest) && dist >= dists[i] {
i++
}
if i >= k {
return dists, nearest, false
}
if refuse, abort := applyFilters(nearest, obj, filters); refuse || abort {
return dists, nearest, abort
}
// no resize since cap = k
if len(nearest) < k {
dists = append(dists, 0)
nearest = append(nearest, nil)
}
left, right := dists[:i], dists[i:len(dists)-1]
copy(dists, left)
copy(dists[i+1:], right)
dists[i] = dist
leftObjs, rightObjs := nearest[:i], nearest[i:len(nearest)-1]
copy(nearest, leftObjs)
copy(nearest[i+1:], rightObjs)
nearest[i] = obj
return dists, nearest, false
}
func (tree *Rtree) nearestNeighbors(k int, p Point, n *node, dists []float64, nearest []Spatial, filters []Filter, b []entry, bd []float64) ([]Spatial, []float64, bool) {
var abort bool
if n.leaf {
for _, e := range n.entries {
dist := p.minDist(e.bb)
dists, nearest, abort = insertNearest(k, dists, nearest, dist, e.obj, filters)
if abort {
break
}
}
} else {
branches, branchDists := sortPreallocEntries(p, n.entries, b, bd)
// only prune if buffer has k elements
if l := len(dists); l >= k {
branches = pruneEntriesMinDist(dists[l-1], branches, branchDists)
}
for _, e := range branches {
nearest, dists, abort = tree.nearestNeighbors(k, p, e.child, dists, nearest, filters, b[len(n.entries):], bd[len(n.entries):])
if abort {
break
}
}
}
return nearest, dists, abort
}