This repository has been archived by the owner on Jan 27, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RTree.cs
1102 lines (946 loc) · 40.5 KB
/
RTree.cs
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
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// RTree.java
// Java Spatial Index Library
// Copyright (C) 2002 Infomatiq Limited
// Copyright (C) 2008 Aled Morris [email protected]
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
// Ported to C# By Dror Gluska, April 9th, 2009
using System.Collections.Generic;
using System;
using System.Collections;
namespace SolucionAlumno
{
/// <summary>
/// This is a lightweight RTree implementation, specifically designed
/// for the following features (in order of importance):
///
/// Fast intersection query performance. To achieve this, the RTree
/// uses only main memory to store entries. Obviously this will only improve
/// performance if there is enough physical memory to avoid paging.
/// Low memory requirements.
/// Fast add performance.
///
///
/// The main reason for the high speed of this RTree implementation is the
/// avoidance of the creation of unnecessary objects, mainly achieved by using
/// primitive collections from the trove4j library.
/// author [email protected]
/// version 1.0b2p1
/// Ported to C# By Dror Gluska, April 9th, 2009
/// </summary>
/// <typeparam name="T"></typeparam>
public class RTree<T>
{
private const string version = "1.0b2p1";
// parameters of the tree
private const int DEFAULT_MAX_NODE_ENTRIES = 10;
internal int maxNodeEntries;
int minNodeEntries;
// map of nodeId -> Node<T> object
// [x] TODO eliminate this map - it should not be needed. Nodes
// can be found by traversing the tree.
//private TIntObjectHashMap nodeMap = new TIntObjectHashMap();
private Dictionary<int, RNode<T>> nodeMap = new Dictionary<int, RNode<T>>();
// internal consistency checking - set to true if debugging tree corruption
private const bool INTERNAL_CONSISTENCY_CHECKING = false;
// used to mark the status of entries during a Node<T> split
private const int ENTRY_STATUS_ASSIGNED = 0;
private const int ENTRY_STATUS_UNASSIGNED = 1;
private byte[] entryStatus = null;
private byte[] initialEntryStatus = null;
// stacks used to store nodeId and entry index of each Node<T>
// from the root down to the leaf. Enables fast lookup
// of nodes when a split is propagated up the tree.
//private TIntStack parents = new TIntStack();
private Stack<int> parents = new Stack<int>();
//private TIntStack parentsEntry = new TIntStack();
private Stack<int> parentsEntry = new Stack<int>();
// initialisation
private int treeHeight = 1; // leaves are always level 1
private int rootNodeId = 0;
private int msize = 0;
// Enables creation of new nodes
//private int highestUsedNodeId = rootNodeId;
private int highestUsedNodeId = 0;
// Deleted Node<T> objects are retained in the nodeMap,
// so that they can be reused. Store the IDs of nodes
// which can be reused.
//private TIntStack deletedNodeIds = new TIntStack();
private Stack<int> deletedNodeIds = new Stack<int>();
// List of nearest rectangles. Use a member variable to
// avoid recreating the object each time nearest() is called.
//private TIntArrayList nearestIds = new TIntArrayList();
List<int> nearestIds = new List<int>();
//Added dictionaries to support generic objects..
//possibility to change the code to support objects without dictionaries.
private Dictionary<int, T> IdsToItems = new Dictionary<int,T>();
private Dictionary<T,int> ItemsToIds = new Dictionary<T,int>();
private volatile int idcounter = int.MinValue;
//the recursion methods require a delegate to retrieve data
private delegate void intproc(int x);
/// <summary>
/// Initialize implementation dependent properties of the RTree.
/// </summary>
public RTree()
{
init();
}
/// <summary>
/// Initialize implementation dependent properties of the RTree.
/// </summary>
/// <param name="MaxNodeEntries">his specifies the maximum number of entries
///in a node. The default value is 10, which is used if the property is
///not specified, or is less than 2.</param>
/// <param name="MinNodeEntries">This specifies the minimum number of entries
///in a node. The default value is half of the MaxNodeEntries value (rounded
///down), which is used if the property is not specified or is less than 1.
///</param>
public RTree(int MaxNodeEntries, int MinNodeEntries)
{
minNodeEntries = MinNodeEntries;
maxNodeEntries = MaxNodeEntries;
init();
}
private void init()
{
// Obviously a Node<T> with less than 2 entries cannot be split.
// The Node<T> splitting algorithm will work with only 2 entries
// per node, but will be inefficient.
if (maxNodeEntries < 2)
{
// log.Warn("Invalid MaxNodeEntries = " + maxNodeEntries + " Resetting to default value of " + DEFAULT_MAX_NODE_ENTRIES);
maxNodeEntries = DEFAULT_MAX_NODE_ENTRIES;
}
// The MinNodeEntries must be less than or equal to (int) (MaxNodeEntries / 2)
if (minNodeEntries < 1 || minNodeEntries > maxNodeEntries / 2)
{
// log.Warn("MinNodeEntries must be between 1 and MaxNodeEntries / 2");
minNodeEntries = maxNodeEntries / 2;
}
entryStatus = new byte[maxNodeEntries];
initialEntryStatus = new byte[maxNodeEntries];
for (int i = 0; i < maxNodeEntries; i++)
{
initialEntryStatus[i] = ENTRY_STATUS_UNASSIGNED;
}
RNode<T> root = new RNode<T>(rootNodeId, 1, maxNodeEntries);
nodeMap.Add(rootNodeId, root);
// log.Info("init() " + " MaxNodeEntries = " + maxNodeEntries + ", MinNodeEntries = " + minNodeEntries);
}
/// <summary>
/// Adds an item to the spatial index
/// </summary>
/// <param name="r"></param>
/// <param name="item"></param>
public void Add(RRectangle r, T item)
{
idcounter++;
int id = idcounter;
IdsToItems.Add(id, item);
ItemsToIds.Add(item, id);
add(r, id);
}
private void add(RRectangle r, int id)
{
add(r.copy(), id, 1);
msize++;
}
/// <summary>
/// Adds a new entry at a specified level in the tree
/// </summary>
/// <param name="r"></param>
/// <param name="id"></param>
/// <param name="level"></param>
private void add(RRectangle r, int id, int level)
{
// I1 [Find position for new record] Invoke ChooseLeaf to select a
// leaf Node<T> L in which to place r
RNode<T> n = chooseNode(r, level);
RNode<T> newLeaf = null;
// I2 [Add record to leaf node] If L has room for another entry,
// install E. Otherwise invoke SplitNode to obtain L and LL containing
// E and all the old entries of L
if (n.entryCount < maxNodeEntries)
{
n.addEntryNoCopy(r, id);
}
else
{
newLeaf = splitNode(n, r, id);
}
// I3 [Propagate changes upwards] Invoke AdjustTree on L, also passing LL
// if a split was performed
RNode<T> newNode = adjustTree(n, newLeaf);
// I4 [Grow tree taller] If Node<T> split propagation caused the root to
// split, create a new root whose children are the two resulting nodes.
if (newNode != null)
{
int oldRootNodeId = rootNodeId;
RNode<T> oldRoot = getNode(oldRootNodeId);
rootNodeId = getNextNodeId();
treeHeight++;
RNode<T> root = new RNode<T>(rootNodeId, treeHeight, maxNodeEntries);
root.addEntry(newNode.mbr, newNode.nodeId);
root.addEntry(oldRoot.mbr, oldRoot.nodeId);
nodeMap.Add(rootNodeId, root);
}
/*
if (INTERNAL_CONSISTENCY_CHECKING)
{
checkConsistency(rootNodeId, treeHeight, null);
}*/
}
/// <summary>
/// Deletes an item from the spatial index
/// </summary>
/// <param name="r"></param>
/// <param name="item"></param>
/// <returns></returns>
public bool Delete(RRectangle r, T item)
{
int id = ItemsToIds[item];
bool success = delete(r, id);
if (success == true)
{
IdsToItems.Remove(id);
ItemsToIds.Remove(item);
}
return success;
}
private bool delete(RRectangle r, int id)
{
// FindLeaf algorithm inlined here. Note the "official" algorithm
// searches all overlapping entries. This seems inefficient to me,
// as an entry is only worth searching if it contains (NOT overlaps)
// the rectangle we are searching for.
//
// Also the algorithm has been changed so that it is not recursive.
// FL1 [Search subtrees] If root is not a leaf, check each entry
// to determine if it contains r. For each entry found, invoke
// findLeaf on the Node<T> pointed to by the entry, until r is found or
// all entries have been checked.
parents.Clear();
parents.Push(rootNodeId);
parentsEntry.Clear();
parentsEntry.Push(-1);
RNode<T> n = null;
int foundIndex = -1; // index of entry to be deleted in leaf
while (foundIndex == -1 && parents.Count > 0)
{
n = getNode(parents.Peek());
int startIndex = parentsEntry.Peek() + 1;
if (!n.isLeaf())
{
bool contains = false;
for (int i = startIndex; i < n.entryCount; i++)
{
if (n.entries[i].contains(r))
{
parents.Push(n.ids[i]);
parentsEntry.Pop();
parentsEntry.Push(i); // this becomes the start index when the child has been searched
parentsEntry.Push(-1);
contains = true;
break; // ie go to next iteration of while()
}
}
if (contains)
{
continue;
}
}
else
{
foundIndex = n.findEntry(r, id);
}
parents.Pop();
parentsEntry.Pop();
} // while not found
if (foundIndex != -1)
{
n.deleteEntry(foundIndex, minNodeEntries);
condenseTree(n);
msize--;
}
// shrink the tree if possible (i.e. if root Node<T%gt; has exactly one entry,and that
// entry is not a leaf node, delete the root (it's entry becomes the new root)
RNode<T> root = getNode(rootNodeId);
while (root.entryCount == 1 && treeHeight > 1)
{
root.entryCount = 0;
rootNodeId = root.ids[0];
treeHeight--;
root = getNode(rootNodeId);
}
return (foundIndex != -1);
}
/// <summary>
/// Retrieve nearest items to a point in radius furthestDistance
/// </summary>
/// <param name="p">Point of origin</param>
/// <param name="furthestDistance">maximum distance</param>
/// <returns>List of items</returns>
public List<T> Nearest(RPoint p, int furthestDistance)
{
List<T> retval = new List<T>();
nearest(p, delegate(int id)
{
retval.Add(IdsToItems[id]);
}, furthestDistance);
return retval;
}
private void nearest(RPoint p, intproc v, int furthestDistance)
{
RNode<T> rootNode = getNode(rootNodeId);
nearest(p, rootNode, furthestDistance);
foreach (int id in nearestIds)
v(id);
nearestIds.Clear();
}
/// <summary>
/// Retrieve items which intersect with Rectangle r
/// </summary>
/// <param name="r"></param>
/// <returns></returns>
public List<T> Intersects(RRectangle r)
{
List<T> retval = new List<T>();
intersects(r, delegate(int id)
{
retval.Add(IdsToItems[id]);
});
return retval;
}
private void intersects(RRectangle r, intproc v)
{
RNode<T> rootNode = getNode(rootNodeId);
intersects(r, v, rootNode);
}
/// <summary>
/// find all rectangles in the tree that are contained by the passed rectangle
/// written to be non-recursive (should model other searches on this?)</summary>
/// <param name="r"></param>
/// <returns></returns>
public List<T> Contains(RRectangle r)
{
List<T> retval = new List<T>();
contains(r, delegate(int id)
{
retval.Add(IdsToItems[id]);
});
return retval;
}
private void contains(RRectangle r, intproc v)
{
// find all rectangles in the tree that are contained by the passed rectangle
// written to be non-recursive (should model other searches on this?)
parents.Clear();
parents.Push(rootNodeId);
parentsEntry.Clear();
parentsEntry.Push(-1);
// TODO: possible shortcut here - could test for intersection with the
// MBR of the root node. If no intersection, return immediately.
while (parents.Count > 0)
{
RNode<T> n = getNode(parents.Peek());
int startIndex = parentsEntry.Peek() + 1;
if (!n.isLeaf())
{
// go through every entry in the index Node<T> to check
// if it intersects the passed rectangle. If so, it
// could contain entries that are contained.
bool intersects = false;
for (int i = startIndex; i < n.entryCount; i++)
{
if (r.intersects(n.entries[i]))
{
parents.Push(n.ids[i]);
parentsEntry.Pop();
parentsEntry.Push(i); // this becomes the start index when the child has been searched
parentsEntry.Push(-1);
intersects = true;
break; // ie go to next iteration of while()
}
}
if (intersects)
{
continue;
}
}
else
{
// go through every entry in the leaf to check if
// it is contained by the passed rectangle
for (int i = 0; i < n.entryCount; i++)
{
if (r.contains(n.entries[i]))
{
v(n.ids[i]);
}
}
}
parents.Pop();
parentsEntry.Pop();
}
}
/**
* @see com.infomatiq.jsi.SpatialIndex#getBounds()
*/
public RRectangle getBounds()
{
RRectangle bounds = null;
RNode<T> n = getNode(getRootNodeId());
if (n != null && n.getMBR() != null)
{
bounds = n.getMBR().copy();
}
return bounds;
}
/**
* @see com.infomatiq.jsi.SpatialIndex#getVersion()
*/
public string getVersion()
{
return "RTree-" + version;
}
//-------------------------------------------------------------------------
// end of SpatialIndex methods
//-------------------------------------------------------------------------
/**
* Get the next available Node<T> ID. Reuse deleted Node<T> IDs if
* possible
*/
private int getNextNodeId()
{
int nextNodeId = 0;
if (deletedNodeIds.Count > 0)
{
nextNodeId = deletedNodeIds.Pop();
}
else
{
nextNodeId = 1 + highestUsedNodeId++;
}
return nextNodeId;
}
/// <summary>
/// Get a Node<T> object, given the ID of the node.
/// </summary>
/// <param name="index"></param>
/// <returns></returns>
private RNode<T> getNode(int index)
{
return (RNode<T>)nodeMap[index];
}
/// <summary>
/// Get the highest used Node<T> ID
/// </summary>
/// <returns></returns>
private int getHighestUsedNodeId()
{
return highestUsedNodeId;
}
/// <summary>
/// Get the root Node<T> ID
/// </summary>
/// <returns></returns>
public int getRootNodeId()
{
return rootNodeId;
}
/// <summary>
/// Split a node. Algorithm is taken pretty much verbatim from
/// Guttman's original paper.
/// </summary>
/// <param name="n"></param>
/// <param name="newRect"></param>
/// <param name="newId"></param>
/// <returns>return new Node<T> object.</returns>
private RNode<T> splitNode(RNode<T> n, RRectangle newRect, int newId)
{
// [Pick first entry for each group] Apply algorithm pickSeeds to
// choose two entries to be the first elements of the groups. Assign
// each to a group.
// debug code
// int initialArea = 0;
System.Array.Copy(initialEntryStatus, 0, entryStatus, 0, maxNodeEntries);
RNode<T> newNode = null;
newNode = new RNode<T>(getNextNodeId(), n.level, maxNodeEntries);
nodeMap.Add(newNode.nodeId, newNode);
pickSeeds(n, newRect, newId, newNode); // this also sets the entryCount to 1
// [Check if done] If all entries have been assigned, stop. If one
// group has so few entries that all the rest must be assigned to it in
// order for it to have the minimum number m, assign them and stop.
while (n.entryCount + newNode.entryCount < maxNodeEntries + 1)
{
if (maxNodeEntries + 1 - newNode.entryCount == minNodeEntries)
{
// assign all remaining entries to original node
for (int i = 0; i < maxNodeEntries; i++)
{
if (entryStatus[i] == ENTRY_STATUS_UNASSIGNED)
{
entryStatus[i] = ENTRY_STATUS_ASSIGNED;
n.mbr.add(n.entries[i]);
n.entryCount++;
}
}
break;
}
if (maxNodeEntries + 1 - n.entryCount == minNodeEntries)
{
// assign all remaining entries to new node
for (int i = 0; i < maxNodeEntries; i++)
{
if (entryStatus[i] == ENTRY_STATUS_UNASSIGNED)
{
entryStatus[i] = ENTRY_STATUS_ASSIGNED;
newNode.addEntryNoCopy(n.entries[i], n.ids[i]);
n.entries[i] = null;
}
}
break;
}
// [Select entry to assign] Invoke algorithm pickNext to choose the
// next entry to assign. Add it to the group whose covering rectangle
// will have to be enlarged least to accommodate it. Resolve ties
// by adding the entry to the group with smaller area, then to the
// the one with fewer entries, then to either. Repeat from S2
pickNext(n, newNode);
}
n.reorganize(this);
/*
// check that the MBR stored for each Node<T> is correct.
if (INTERNAL_CONSISTENCY_CHECKING)
{
if (!n.mbr.Equals(calculateMBR(n)))
{
// log.Error("Error: splitNode old Node<T> MBR wrong");
}
if (!newNode.mbr.Equals(calculateMBR(newNode)))
{
// log.Error("Error: splitNode new Node<T> MBR wrong");
}
}
// debug code
*/
return newNode;
}
/// <summary>
/// Pick the seeds used to split a node.
/// Select two entries to be the first elements of the groups
/// </summary>
/// <param name="n"></param>
/// <param name="newRect"></param>
/// <param name="newId"></param>
/// <param name="newNode"></param>
private void pickSeeds(RNode<T> n, RRectangle newRect, int newId, RNode<T> newNode)
{
// Find extreme rectangles along all dimension. Along each dimension,
// find the entry whose rectangle has the highest low side, and the one
// with the lowest high side. Record the separation.
int maxNormalizedSeparation = 0;
int highestLowIndex = 0;
int lowestHighIndex = 0;
// for the purposes of picking seeds, take the MBR of the Node<T> to include
// the new rectangle aswell.
n.mbr.add(newRect);
for (int d = 0; d < RRectangle.DIMENSIONS; d++)
{
int tempHighestLow = newRect.min[d];
int tempHighestLowIndex = -1; // -1 indicates the new rectangle is the seed
int tempLowestHigh = newRect.max[d];
int tempLowestHighIndex = -1;
for (int i = 0; i < n.entryCount; i++)
{
int tempLow = n.entries[i].min[d];
if (tempLow >= tempHighestLow)
{
tempHighestLow = tempLow;
tempHighestLowIndex = i;
}
else
{ // ensure that the same index cannot be both lowestHigh and highestLow
int tempHigh = n.entries[i].max[d];
if (tempHigh <= tempLowestHigh)
{
tempLowestHigh = tempHigh;
tempLowestHighIndex = i;
}
}
// PS2 [Adjust for shape of the rectangle cluster] Normalize the separations
// by dividing by the widths of the entire set along the corresponding
// dimension
int normalizedSeparation = (tempHighestLow - tempLowestHigh) / (n.mbr.max[d] - n.mbr.min[d]);
// PS3 [Select the most extreme pair] Choose the pair with the greatest
// normalized separation along any dimension.
if (normalizedSeparation > maxNormalizedSeparation)
{
maxNormalizedSeparation = normalizedSeparation;
highestLowIndex = tempHighestLowIndex;
lowestHighIndex = tempLowestHighIndex;
}
}
}
// highestLowIndex is the seed for the new node.
if (highestLowIndex == -1)
{
newNode.addEntry(newRect, newId);
}
else
{
newNode.addEntryNoCopy(n.entries[highestLowIndex], n.ids[highestLowIndex]);
n.entries[highestLowIndex] = null;
// move the new rectangle into the space vacated by the seed for the new node
n.entries[highestLowIndex] = newRect;
n.ids[highestLowIndex] = newId;
}
// lowestHighIndex is the seed for the original node.
if (lowestHighIndex == -1)
{
lowestHighIndex = highestLowIndex;
}
entryStatus[lowestHighIndex] = ENTRY_STATUS_ASSIGNED;
n.entryCount = 1;
n.mbr.set(n.entries[lowestHighIndex].min, n.entries[lowestHighIndex].max);
}
/// <summary>
/// Pick the next entry to be assigned to a group during a Node<T> split.
/// [Determine cost of putting each entry in each group] For each
/// entry not yet in a group, calculate the area increase required
/// in the covering rectangles of each group
/// </summary>
/// <param name="n"></param>
/// <param name="newNode"></param>
/// <returns></returns>
private int pickNext(RNode<T> n, RNode<T> newNode)
{
int maxDifference = int.MinValue;
int next = 0;
int nextGroup = 0;
maxDifference = int.MinValue;
for (int i = 0; i < maxNodeEntries; i++)
{
if (entryStatus[i] == ENTRY_STATUS_UNASSIGNED)
{
int nIncrease = n.mbr.enlargement(n.entries[i]);
int newNodeIncrease = newNode.mbr.enlargement(n.entries[i]);
int difference = Math.Abs(nIncrease - newNodeIncrease);
if (difference > maxDifference)
{
next = i;
if (nIncrease < newNodeIncrease)
{
nextGroup = 0;
}
else if (newNodeIncrease < nIncrease)
{
nextGroup = 1;
}
else if (n.mbr.area() < newNode.mbr.area())
{
nextGroup = 0;
}
else if (newNode.mbr.area() < n.mbr.area())
{
nextGroup = 1;
}
else if (newNode.entryCount < maxNodeEntries / 2)
{
nextGroup = 0;
}
else
{
nextGroup = 1;
}
maxDifference = difference;
}
}
}
entryStatus[next] = ENTRY_STATUS_ASSIGNED;
if (nextGroup == 0)
{
n.mbr.add(n.entries[next]);
n.entryCount++;
}
else
{
// move to new node.
newNode.addEntryNoCopy(n.entries[next], n.ids[next]);
n.entries[next] = null;
}
return next;
}
/// <summary>
/// Recursively searches the tree for the nearest entry. Other queries
/// call execute() on an IntProcedure when a matching entry is found;
/// however nearest() must store the entry Ids as it searches the tree,
/// in case a nearer entry is found.
/// Uses the member variable nearestIds to store the nearest
/// entry IDs.
/// </summary>
/// <remarks>TODO rewrite this to be non-recursive?</remarks>
/// <param name="p"></param>
/// <param name="n"></param>
/// <param name="nearestDistance"></param>
/// <returns></returns>
private int nearest(RPoint p, RNode<T> n, int nearestDistance)
{
for (int i = 0; i < n.entryCount; i++)
{
int tempDistance = n.entries[i].distance(p);
if (n.isLeaf())
{ // for leaves, the distance is an actual nearest distance
if (tempDistance < nearestDistance)
{
nearestDistance = tempDistance;
nearestIds.Clear();
}
if (tempDistance <= nearestDistance)
{
nearestIds.Add(n.ids[i]);
}
}
else
{ // for index nodes, only go into them if they potentially could have
// a rectangle nearer than actualNearest
if (tempDistance <= nearestDistance)
{
// search the child node
nearestDistance = nearest(p, getNode(n.ids[i]), nearestDistance);
}
}
}
return nearestDistance;
}
/// <summary>
/// Recursively searches the tree for all intersecting entries.
/// Immediately calls execute() on the passed IntProcedure when
/// a matching entry is found.
/// [x] TODO rewrite this to be non-recursive? Make sure it
/// doesn't slow it down.
/// </summary>
/// <param name="r"></param>
/// <param name="v"></param>
/// <param name="n"></param>
private void intersects(RRectangle r, intproc v, RNode<T> n)
{
for (int i = 0; i < n.entryCount; i++)
{
if (r.intersects(n.entries[i]))
{
if (n.isLeaf())
{
v(n.ids[i]);
}
else
{
RNode<T> childNode = getNode(n.ids[i]);
intersects(r, v, childNode);
}
}
}
}
/**
* Used by delete(). Ensures that all nodes from the passed node
* up to the root have the minimum number of entries.
*
* Note that the parent and parentEntry stacks are expected to
* contain the nodeIds of all parents up to the root.
*/
private RRectangle oldRectangle = new RRectangle(0, 0, 0, 0);
private void condenseTree(RNode<T> l)
{
// CT1 [Initialize] Set n=l. Set the list of eliminated
// nodes to be empty.
RNode<T> n = l;
RNode<T> parent = null;
int parentEntry = 0;
//TIntStack eliminatedNodeIds = new TIntStack();
Stack<int> eliminatedNodeIds = new Stack<int>();
// CT2 [Find parent entry] If N is the root, go to CT6. Otherwise
// let P be the parent of N, and let En be N's entry in P
while (n.level != treeHeight)
{
parent = getNode(parents.Pop());
parentEntry = parentsEntry.Pop();
// CT3 [Eliminiate under-full node] If N has too few entries,
// delete En from P and add N to the list of eliminated nodes
if (n.entryCount < minNodeEntries)
{
parent.deleteEntry(parentEntry, minNodeEntries);
eliminatedNodeIds.Push(n.nodeId);
}
else
{
// CT4 [Adjust covering rectangle] If N has not been eliminated,
// adjust EnI to tightly contain all entries in N
if (!n.mbr.Equals(parent.entries[parentEntry]))
{
oldRectangle.set(parent.entries[parentEntry].min, parent.entries[parentEntry].max);
parent.entries[parentEntry].set(n.mbr.min, n.mbr.max);
parent.recalculateMBR(oldRectangle);
}
}
// CT5 [Move up one level in tree] Set N=P and repeat from CT2
n = parent;
}
// CT6 [Reinsert orphaned entries] Reinsert all entries of nodes in set Q.
// Entries from eliminated leaf nodes are reinserted in tree leaves as in
// Insert(), but entries from higher level nodes must be placed higher in
// the tree, so that leaves of their dependent subtrees will be on the same
// level as leaves of the main tree
while (eliminatedNodeIds.Count > 0)
{
RNode<T> e = getNode(eliminatedNodeIds.Pop());
for (int j = 0; j < e.entryCount; j++)
{
add(e.entries[j], e.ids[j], e.level);
e.entries[j] = null;
}
e.entryCount = 0;
deletedNodeIds.Push(e.nodeId);
}
}
/**
* Used by add(). Chooses a leaf to add the rectangle to.
*/
private RNode<T> chooseNode(RRectangle r, int level)
{
// CL1 [Initialize] Set N to be the root node
RNode<T> n = getNode(rootNodeId);
parents.Clear();
parentsEntry.Clear();
// CL2 [Leaf check] If N is a leaf, return N
while (true)
{
if (n.level == level)
{
return n;
}
// CL3 [Choose subtree] If N is not at the desired level, let F be the entry in N
// whose rectangle FI needs least enlargement to include EI. Resolve
// ties by choosing the entry with the rectangle of smaller area.
int leastEnlargement = n.getEntry(0).enlargement(r);
int index = 0; // index of rectangle in subtree
for (int i = 1; i < n.entryCount; i++)
{
RRectangle tempRectangle = n.getEntry(i);
int tempEnlargement = tempRectangle.enlargement(r);
if ((tempEnlargement < leastEnlargement) ||
((tempEnlargement == leastEnlargement) &&
(tempRectangle.area() < n.getEntry(index).area())))
{
index = i;
leastEnlargement = tempEnlargement;
}
}
parents.Push(n.nodeId);
parentsEntry.Push(index);
// CL4 [Descend until a leaf is reached] Set N to be the child Node<T>
// pointed to by Fp and repeat from CL2
n = getNode(n.ids[index]);
}
}
/**
* Ascend from a leaf Node<T> L to the root, adjusting covering rectangles and
* propagating Node<T> splits as necessary.
*/
private RNode<T> adjustTree(RNode<T> n, RNode<T> nn)
{
// AT1 [Initialize] Set N=L. If L was split previously, set NN to be
// the resulting second node.
// AT2 [Check if done] If N is the root, stop
while (n.level != treeHeight)
{