forked from Lucaweihs/range-tree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRangeTree.h
More file actions
1291 lines (1183 loc) · 52 KB
/
RangeTree.h
File metadata and controls
1291 lines (1183 loc) · 52 KB
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
/*
* MIT License
*
* Copyright (c) 2016 Luca Weihs
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
* Implements the RangeTree datastructure.
*
* See the documentation of the class RangeTree for more details regarding the purpose
* of RangeTree's.
*
* This file contains two main abstractions meant for use:
* 1. The RangeTree class.
* 2. A Point class which captures the idea of a d-dimensional euclidean point.
*/
#ifndef RANGETREE_H
#define RANGETREE_H
#include <vector>
#include <iostream>
#include <sstream>
#include <numeric>
#include <type_traits>
#include <deque>
#include <cmath>
#include <algorithm>
namespace RangeTree {
/**
* A point in euclidean space.
*
* A class that represents a multi-dimensional euclidean point
* with some associated value. We allow for each point to have an
* associated value so that some more information can be stored with
* each point. Points can also have a multiplicity/count, this corresponds
* to having several duplicates of the same point.
*/
template<typename T, class S>
class Point {
static_assert(std::is_arithmetic<T>::value, "Type T must be numeric");
private:
std::vector<T> vec;
S val;
int multiplicity;
public:
/**
* Constructs an empty point.
*
* Creates a point in 0 dimensional euclidean space. This constructor
* is provided only to make certain edge cases easier to handle.
*/
Point() : multiplicity(0) {}
/**
* Constructs a point.
*
* Creates a point with its position in euclidean space defined by vec,
* value defined by val, and a multiplicity/count of 1.
*
* @param vec the position in euclidean space.
* @param val the value associated with the point.
*/
Point(const std::vector<T>& vec, const S& val): val(val), vec(vec), multiplicity(1) {}
/**
* Constructs a point.
*
* Copies a point.
*
* @param vec the position in euclidean space.
* @param val the value associated with the point.
*/
Point(const Point<T,S>& p): val(p.val), vec(p.vec), multiplicity(p.count()) {}
/**
* Euclidean position of the point.
*
* @return the euclidean position of the point as a std::vector.
*/
const std::vector<T>& asVector() const {
return vec;
}
/**
* The point's ambient dimension.
*
* @return the dimension of the space in which the point lives. I.e. a point of the
* form (1,2,3) lives in dimension 3.
*/
unsigned long dim() const {
return vec.size();
}
/**
* The point's count/multiplicity.
*
* @return returns the count/multiplicity.
*/
int count() const {
return multiplicity;
}
/**
* Increase the point's count/multiplicity.
*
* @param n amount to increase by.
*/
void increaseCountBy(int n) {
if (n < 0) {
throw std::logic_error("Can't increase by a negative amount");
}
multiplicity += n;
}
/**
* The point's value.
*
* @return the value stored in the point.
*/
S value() const {
return val;
}
/**
* Index a point.
*
* Get the ith coordinate value of the point. I.e. if a point is of the form (4,5,6),
* then its 0th coordinate value is 4 while its 2nd is 6.
*
* @param index the coordinate to index.
* @return the coordinate value.
*/
T operator[](int index) const {
if(index < 0 || index >= dim()) {
throw std::out_of_range("[] access index for point is out of range.");
}
return vec[index];
}
/**
* Check for equality.
*
* Two points are considered equal if they are in the same spot, have the same
* multiplicity/count, and store the same value.
*
* @param p some other point
* @return true if \p equals the current point, otherwise false.
*/
bool operator==(const Point<T,S>& p) const {
return vec == p.vec && multiplicity == p.multiplicity && val == p.val;
}
/**
* Check for inequality.
*
* The opposite of ==.
*
* @param p some other point.
* @return false if \p equals the current point, otherwise true.
*/
bool operator!=(const Point<T,S>& p) const {
return !((*this) == p);
}
/**
* Prints the point to standard out.
*
* As an example, a point with euclidean location (3,4,5) and with a
* multiplicity/count of 4 will be printed as
*
* (3, 4, 5) : 4
*
* @param withCount whether or not to display the points count/multiplicity.
*/
void print(bool withCount=true) const {
std::cout << "(";
for (int i = 0; i < dim() - 1; i++) {
std::cout << (*this)[i] << ", ";
}
if (withCount) {
std::cout << (*this)[dim() - 1] << ") : " << count() << std::endl;
} else {
std::cout << (*this)[dim() - 1] << ") : " << std::endl;
}
}
};
/**
* A class that totally orders Point<T,S>'s in euclidean space.
*
* A total order of Points is required in the RangeTree. This is an implementation
* detail that can be ignored. Given a start index \compareStartIndex, this class
* orders points so that, for two points p_1 = (p_{11}, p_{12},...,p_{1n}) and
* p_2 = (p_{21}, p_{22},...,p_{2n}) we have that p_1 < p_2 if and only if
*
* (p_{1\compareStartInd},...,p_{1n}) < (p_{2\compareStartInd},...,p_{2n})
*
* using the usual lexicographic order, or
*
* (p_{1\compareStartInd},...,p_{1n}) == (p_{2\compareStartInd},...,p_{2n}) and
* (p_{11},...,p_{1(\compareStartInd-1)}) < (p_{21},...,p_{2(\compareStartInd-1)})
*
* again using the usual lexicographic order.
*/
template <typename T, class S>
class PointOrdering {
static_assert(std::is_arithmetic<T>::value, "Type T must be numeric");
private:
int compareStartIndex;
public:
PointOrdering(int compareStartIndex): compareStartIndex(compareStartIndex) {
if (compareStartIndex < 0) {
throw new std::logic_error("Cannot have comparison start index <0.");
}
}
static bool equals(const Point<T,S>& p1, const Point<T,S>& p2) {
return p1.asVector() == p2.asVector();
}
int getCompareStartIndex() const {
return compareStartIndex;
}
bool less(const Point<T,S>& p1, const Point<T,S>& p2) const {
if (p1.dim() != p2.dim()) {
throw std::logic_error("Points are incomparable (differing dims).");
}
if (compareStartIndex >= p1.dim()) {
throw std::logic_error("Cannot compare points, compare start index >= point dimension.");
}
for (int i = compareStartIndex; i < p1.dim(); i++) {
if (p1[i] < p2[i]) {
return true;
} else if (p1[i] > p2[i]) {
return false;
}
}
for (int i = 0; i < compareStartIndex; i++) {
if (p1[i] < p2[i]) {
return true;
} else if (p1[i] > p2[i]) {
return false;
}
}
return false;
}
bool lessOrEq(const Point<T,S>& p1, const Point<T,S>& p2) const {
return less(p1, p2) || equals(p1, p2);
}
bool greater(const Point<T,S>& p1, const Point<T,S>& p2) const {
return less(p2, p1);
}
bool greaterOrEq(const Point<T,S>& p1, const Point<T,S>& p2) const {
return greater(p1, p2) || equals(p1,p2);
}
bool operator()(const Point<T,S>& p1, const Point<T,S>& p2) const {
return this->less(p1, p2);
}
};
/**
* A matrix that keeps a collection of points sorted on each coordinate
*/
template<typename T, class S>
class SortedPointMatrix {
static_assert(std::is_arithmetic<T>::value, "Type T must be numeric");
private:
std::vector<Point<T,S>* > pointsSortedByCurrentDim;
std::deque<std::vector<int> > redirectionTable;
int currentDim;
int dim;
static const int MAX_POINTS_BEFORE_SWITCH = 1000;
std::vector<int> sortOrder(const std::vector<Point<T,S>* >& points, int onDim) {
std::vector<int> order(points.size());
for (int i = 0; i < points.size(); i++) { order[i] = i; }
PointOrdering<T,S> pointOrdering(onDim);
std::sort(order.begin(), order.end(),
[pointOrdering, points](int i, int j) {
return pointOrdering.less(*(points[i]), *(points[j]));
});
return order;
}
void sort(std::vector<Point<T,S>* >& points, int onDim) {
PointOrdering<T,S> pointOrdering(onDim);
std::sort(points.begin(), points.end(),
[pointOrdering](Point<T,S>* pt0, Point<T,S>* pt1) {
return pointOrdering.less(*(pt0), *(pt1));
});
}
void rearrangeGivenOrder(std::vector<Point<T,S>* >& points,
const std::vector<int>& order) {
std::vector<Point<T,S>* > tmp = points;
for (int i = 0; i < points.size(); i++) {
points[i] = tmp[order[i]];
}
}
SortedPointMatrix(const std::vector<Point<T,S>* >& pointsSortedByCurrentDim,
const std::deque<std::vector<int> >& redirectionTable,
int currentDim, int dim) : pointsSortedByCurrentDim(pointsSortedByCurrentDim), redirectionTable(redirectionTable),
currentDim(currentDim), dim(dim) {}
public:
/**
* Constructs a sorted point matrix
*/
SortedPointMatrix(std::vector<Point<T,S>* >& points): currentDim(0) {
if (points.size() == 0) {
throw std::range_error("Cannot construct a SortedPointMatrix with 0 points.");
} else {
dim = points[0]->dim();
for (int i = 1; i < points.size(); i++) {
if (points[i]->dim() != dim) {
throw std::logic_error("Input points to SortedPointMatrix must all"
" have the same dimension.");
}
}
int sortDimension = (points.size() > MAX_POINTS_BEFORE_SWITCH) ? dim - 1 : 0;
PointOrdering<T,S> pointOrdering(sortDimension);
std::sort(points.begin(), points.end(),
[pointOrdering](Point<T,S>* p1, Point<T,S>* p2) {
return pointOrdering.less(*p1, *p2);
});
pointsSortedByCurrentDim.push_back(points[0]);
int k = 0;
for (int i = 1; i < points.size(); i++) {
if (pointOrdering.equals(*(pointsSortedByCurrentDim[k]), *points[i])) {
if (pointsSortedByCurrentDim[k]->value() != points[i]->value()) {
throw std::logic_error("Input points have same position but different values");
}
pointsSortedByCurrentDim[k]->increaseCountBy(points[i]->count());
} else {
pointsSortedByCurrentDim.push_back(points[i]);
k++;
}
}
if (pointsSortedByCurrentDim.size() > MAX_POINTS_BEFORE_SWITCH) {
for (int i = dim - 2; i >= currentDim; i--) {
std::vector<int> order = sortOrder(pointsSortedByCurrentDim, i);
redirectionTable.push_front(order);
rearrangeGivenOrder(pointsSortedByCurrentDim, order);
}
}
}
}
void moveToNextDimension() {
if (currentDim == dim - 1) {
throw std::logic_error("Already at max dimension, cannot move to next.");
}
currentDim++;
if (pointsSortedByCurrentDim.size() > MAX_POINTS_BEFORE_SWITCH) {
std::vector<Point<T,S>* > tmp = pointsSortedByCurrentDim;
for (int i = 0; i < pointsSortedByCurrentDim.size(); i++) {
pointsSortedByCurrentDim[redirectionTable[0][i]] = tmp[i];
}
redirectionTable.pop_front();
} else {
sort(pointsSortedByCurrentDim, currentDim);
}
}
Point<T,S>* getMidPoint() {
int mid = (numUniquePoints() - 1) / 2;
return pointsSortedByCurrentDim[mid];
}
int numUniquePoints() {
return pointsSortedByCurrentDim.size();
}
int getCurrentDim() {
return currentDim;
}
std::vector<Point<T,S>* > getSortedPointsAtCurrentDim() {
return pointsSortedByCurrentDim;
}
/**
* Constructs two sorted point matrices after splitting on the current midpoint
*/
std::pair<SortedPointMatrix, SortedPointMatrix> splitOnMid() {
int n = numUniquePoints();
if (n == 1) {
throw std::logic_error("Cannot split on mid when there is only one point.");
}
int mid = (n - 1) / 2;
std::vector<Point<T, S> *> sortedPointsLeft(mid + 1), sortedPointsRight(n - mid - 1);
for (int i = 0; i < mid + 1; i++) {
sortedPointsLeft[i] = pointsSortedByCurrentDim[i];
}
for (int i = mid + 1; i < n; i++) {
sortedPointsRight[i - mid - 1] = pointsSortedByCurrentDim[i];
}
if (n <= MAX_POINTS_BEFORE_SWITCH) {
std::deque<std::vector<int> > redirectionTableLeft, redirectionTableRight;
return std::make_pair(
SortedPointMatrix(sortedPointsLeft, redirectionTableLeft, currentDim, dim),
SortedPointMatrix(sortedPointsRight, redirectionTableRight, currentDim, dim));
} else {
std::vector<bool> onLeft(n);
for (int i = 0; i < n; i++) {
onLeft[i] = i <= mid;
}
std::deque<std::vector<int> > redirectionTableLeft(redirectionTable.size(),
std::vector<int>(mid + 1));
std::deque<std::vector<int> > redirectionTableRight(redirectionTable.size(),
std::vector<int>(n - mid - 1));
for (int i = 0; i < redirectionTable.size(); i++) {
std::vector<bool> lastOnLeft = onLeft;
for (int j = 0; j < numUniquePoints(); j++) {
onLeft[redirectionTable[i][j]] = lastOnLeft[j];
}
std::vector<int> newRedirect(numUniquePoints());
int kLeft = 0, kRight = 0;
for (int j = 0; j < numUniquePoints(); j++) {
if (onLeft[j]) {
newRedirect[j] = kLeft;
kLeft++;
} else {
newRedirect[j] = kRight;
kRight++;
}
}
kLeft = 0, kRight = 0;
for (int j = 0; j < numUniquePoints(); j++) {
if (lastOnLeft[j]) {
redirectionTableLeft[i][kLeft] = newRedirect[redirectionTable[i][j]];
kLeft++;
} else {
redirectionTableRight[i][kRight] = newRedirect[redirectionTable[i][j]];
kRight++;
}
}
}
return std::make_pair(
SortedPointMatrix(sortedPointsLeft, redirectionTableLeft, currentDim, dim),
SortedPointMatrix(sortedPointsRight, redirectionTableRight, currentDim, dim));
}
}
};
/**
* A class representing a single node in a RangeTree. These should not be
* constructed directly, instead use the RangeTree class.
*/
template <typename T, class S>
class RangeTreeNode {
static_assert(std::is_arithmetic<T>::value, "Type T must be numeric");
private:
std::shared_ptr<RangeTreeNode<T,S> > left; /**< Contains points <= the comparison point **/
std::shared_ptr<RangeTreeNode<T,S> > right; /**< Contains points > the comparison point **/
std::shared_ptr<RangeTreeNode<T,S> > treeOnNextDim; /**< Tree on the next dimension **/
Point<T,S>* point; /**< The comparison point **/
bool isLeaf; /**< Whether or not the point is a leaf **/
int pointCountSum; /**< Total number of points, counting multiplicities, at leaves of the tree **/
PointOrdering<T,S> pointOrdering; /**< Helper to totally order input points **/
// For fractional cascading
std::vector<T> pointsLastDimSorted;
std::vector<Point<T,S>* > allPointsSorted;
std::vector<int> pointerToGeqLeft;
std::vector<int> pointerToLeqLeft;
std::vector<int> pointerToGeqRight;
std::vector<int> pointerToLeqRight;
std::vector<int> cumuCountPoints;
public:
/**
* Construct a range tree structure from points.
*
* Creates a range tree structure on the input collection \allPoints using the lexicographic order
* starting at \compareStartInd.
*
* @param uniquePoints a collection of points.
* @return a range tree structure
*/
RangeTreeNode(SortedPointMatrix<T,S>& spm,
bool onLeftEdge = true,
bool onRightEdge = true): pointOrdering(spm.getCurrentDim()) {
point = spm.getMidPoint();
if (spm.numUniquePoints() == 1) {
isLeaf = true;
pointCountSum = point->count();
pointsLastDimSorted.push_back((*point)[point->dim() - 1]);
if (spm.getCurrentDim() == point->dim() - 2) {
spm.moveToNextDimension();
}
} else {
auto spmPair = spm.splitOnMid();
left = std::shared_ptr<RangeTreeNode<T,S> >(
new RangeTreeNode<T,S>(spmPair.first, onLeftEdge, false));
right = std::shared_ptr<RangeTreeNode<T,S> >(
new RangeTreeNode<T,S>(spmPair.second, false, onRightEdge));
pointCountSum = left->totalPoints() + right->totalPoints();
int dim = point->dim();
if (spm.getCurrentDim() + 2 == dim) {
spm.moveToNextDimension();
allPointsSorted = spm.getSortedPointsAtCurrentDim();
cumuCountPoints.push_back(0);
for (int i = 0; i < allPointsSorted.size(); i++) {
pointsLastDimSorted.push_back((*allPointsSorted[i])[dim - 1]);
cumuCountPoints.push_back(cumuCountPoints.back() + allPointsSorted[i]->count());
}
const auto& leftSorted = left->pointsLastDimSorted;
const auto& rightSorted = right->pointsLastDimSorted;
pointerToGeqLeft = createGeqPointers(pointsLastDimSorted, leftSorted);
pointerToGeqRight = createGeqPointers(pointsLastDimSorted, rightSorted);
pointerToLeqLeft = createLeqPointers(pointsLastDimSorted, leftSorted);
pointerToLeqRight = createLeqPointers(pointsLastDimSorted, rightSorted);
} else if (!onLeftEdge && !onRightEdge && spm.getCurrentDim() + 1 != point->dim()) {
spm.moveToNextDimension();
treeOnNextDim = std::shared_ptr<RangeTreeNode>(new RangeTreeNode(spm));
}
isLeaf = false;
}
}
std::vector<int> createGeqPointers(const std::vector<T>& vec,
const std::vector<T>& subVec) {
std::vector<int> grePointers(vec.size());
int k = 0;
for (int i = 0; i < vec.size(); i++) {
while (k < subVec.size() && subVec[k] < vec[i]) {
k++;
}
grePointers[i] = k;
}
return grePointers;
}
std::vector<int> createLeqPointers(const std::vector<T>& vec,
const std::vector<T>& subVec) {
std::vector<int> leqPointers(vec.size());
int k = subVec.size() - 1;
for (int i = vec.size() - 1; i >= 0; i--) {
while (k >= 0 && subVec[k] > vec[i]) {
k--;
}
leqPointers[i] = k;
}
return leqPointers;
}
int binarySearchFirstGeq(T needle, int left, int right) const {
if (left == right) {
if (needle <= pointsLastDimSorted[left]) {
return left;
} else {
return left + 1;
}
}
int mid = (left + right) / 2;
if (needle <= pointsLastDimSorted[mid]) {
return binarySearchFirstGeq(needle, left, mid);
} else {
return binarySearchFirstGeq(needle, mid + 1, right);
}
}
int binarySearchFirstLeq(T needle, int left, int right) const {
if (left == right) {
if (needle >= pointsLastDimSorted[left]) {
return left;
} else {
return left - 1;
}
}
int mid = (left + right + 1) / 2;
if (needle >= pointsLastDimSorted[mid]) {
return binarySearchFirstLeq(needle, mid, right);
} else {
return binarySearchFirstLeq(needle, left, mid - 1);
}
}
/**
* Construct a RangeTreeNode representing a leaf.
*
* @param pointAtLeaf the point to use at the leaf.
* @param compareStartInd the index defining the lexicographic ordering.
* @return
*/
RangeTreeNode(Point<T,S>* pointAtLeaf, int compareStartInd) :
point(pointAtLeaf), isLeaf(true), pointCountSum(pointAtLeaf->count()), pointOrdering(compareStartInd) {}
/**
* Total count of points at the leaves of the range tree rooted at this node.
*
* The total count returned INCLUDES the multiplicities/count of the points at the leaves.
*
* @return the total count.
*/
int totalPoints() const {
return pointCountSum;
}
/**
* Return all points at the leaves of the range tree rooted at this node.
* @return all the points.
*/
std::vector<Point<T,S> > getAllPoints() const {
if (isLeaf) {
std::vector<Point<T,S> > vec;
vec.push_back(*point);
return vec;
}
auto allPointsLeft = left->getAllPoints();
auto allPointsRight = right->getAllPoints();
allPointsLeft.insert(allPointsLeft.end(), allPointsRight.begin(), allPointsRight.end());
return allPointsLeft;
}
/**
* Check if point is in a euclidean box.
*
* Determines whether or not a point is in a euclidean box. That is, if p_1 = (p_{11},...,p_{1n}) is an
* n-dimensional point. Then this function returns true if, for all 1 <= i <= n we have
*
* lower[i] <= p_{1i} <= upper[i] if withLower[i] == true and withUpper[i] == true, or
* lower[i] < p_{1i} <= upper[i] if withLower[i] == false and withUpper[i] == true, or
* lower[i] <= p_{1i} < upper[i] if withLower[i] == true and withUpper[i] == false, or
* lower[i] < p_{1i} < upper[i] if withLower[i] == false and withUpper[i] == false.
*
* @param point the point to check.
* @param lower the lower points of the rectangle.
* @param upper the upper bounds of the rectangle.
* @param withLower whether to use strict (<) or not strict (<=) inequalities at certain coordiantes of p_1
* for the lower bounds.
* @param withUpper as for \withLower but for the upper bounds.
* @return true if the point is in the rectangle, false otherwise.
*/
bool pointInRange(const Point<T,S>& point,
const std::vector<T>& lower,
const std::vector<T>& upper) const {
for (int i = 0; i < point.dim(); i++) {
if (point[i] < lower[i]) {
return false;
}
if (point[i] > upper[i]) {
return false;
}
}
return true;
}
/**
* Count the number of points at leaves of tree rooted at the current node that are within the given bounds.
*
* @param lower see the pointInRange(...) function.
* @param upper
* @return the count.
*/
int countInRange(const std::vector<T>& lower,
const std::vector<T>& upper) const {
if (isLeaf) {
if (pointInRange(*point, lower, upper)) {
return totalPoints();
} else {
return 0;
}
}
int compareInd = pointOrdering.getCompareStartIndex();
if ((*point)[compareInd] > upper[compareInd]) {
return left->countInRange(lower, upper);
}
if ((*point)[compareInd] < lower[compareInd]) {
return right->countInRange(lower, upper);
}
int dim = point->dim();
if (compareInd + 2 == dim) {
int n = pointsLastDimSorted.size();
int geqInd = binarySearchFirstGeq(lower.back(), 0, n - 1);
int leqInd = binarySearchFirstLeq(upper.back(), 0, n - 1);
if (geqInd > leqInd) {
return 0;
}
std::vector<RangeTreeNode<T, S>* > nodes;
std::vector<std::pair<int,int> > inds;
left->leftFractionalCascade(lower,
pointerToGeqLeft[geqInd],
pointerToLeqLeft[leqInd],
nodes,
inds);
right->rightFractionalCascade(upper,
pointerToGeqRight[geqInd],
pointerToLeqRight[leqInd],
nodes,
inds);
int sum = 0;
for (int i = 0; i < nodes.size(); i++) {
if (nodes[i]->isLeaf) {
sum += nodes[i]->totalPoints();
} else {
sum += nodes[i]->cumuCountPoints[inds[i].second + 1] -
nodes[i]->cumuCountPoints[inds[i].first];
}
}
return sum;
} else {
std::vector<std::shared_ptr<RangeTreeNode<T, S> > > canonicalNodes;
if (left->isLeaf) {
canonicalNodes.push_back(left);
} else {
left->leftCanonicalNodes(lower, canonicalNodes);
}
if (right->isLeaf) {
canonicalNodes.push_back(right);
} else {
right->rightCanonicalNodes(upper, canonicalNodes);
}
int numPointsInRange = 0;
for (int i = 0; i < canonicalNodes.size(); i++) {
std::shared_ptr<RangeTreeNode<T, S> > node = canonicalNodes[i];
if (node->isLeaf) {
if (pointInRange(*(node->point), lower, upper)) {
numPointsInRange += node->totalPoints();
}
} else if (compareInd + 1 == point->dim()) {
numPointsInRange += node->totalPoints();
} else {
numPointsInRange += node->treeOnNextDim->countInRange(lower, upper);
}
}
return numPointsInRange;
}
}
/**
* Return the points at leaves of tree rooted at the current node that are within the given bounds.
*
* @param lower see the pointInRange(...) function.
* @param upper
* @return a std::vector of the Points.
*/
std::vector<Point<T,S> > pointsInRange(const std::vector<T>& lower,
const std::vector<T>& upper) const {
std::vector<Point<T,S> > pointsToReturn = {};
if (isLeaf) {
if (pointInRange(*point, lower, upper)) {
pointsToReturn.push_back(*point);
}
return pointsToReturn;
}
int compareInd = pointOrdering.getCompareStartIndex();
if ((*point)[compareInd] > upper[compareInd]) {
return left->pointsInRange(lower, upper);
}
if ((*point)[compareInd] < lower[compareInd]) {
return right->pointsInRange(lower, upper);
}
int dim = point->dim();
if (compareInd + 2 == dim) {
int n = pointsLastDimSorted.size();
int geqInd = binarySearchFirstGeq(lower.back(), 0, n - 1);
int leqInd = binarySearchFirstLeq(upper.back(), 0, n - 1);
if (geqInd > leqInd) {
return pointsToReturn;
}
std::vector<RangeTreeNode<T, S>* > nodes;
std::vector<std::pair<int,int> > inds;
left->leftFractionalCascade(lower,
pointerToGeqLeft[geqInd],
pointerToLeqLeft[leqInd],
nodes,
inds);
right->rightFractionalCascade(upper,
pointerToGeqRight[geqInd],
pointerToLeqRight[leqInd],
nodes,
inds);
for (int i = 0; i < nodes.size(); i++) {
if (nodes[i]->isLeaf) {
pointsToReturn.push_back(*(nodes[i]->point));
} else {
for (int j = inds[i].first; j <= inds[i].second; j++) {
pointsToReturn.push_back(*(nodes[i]->allPointsSorted[j]));
}
}
}
return pointsToReturn;
} else {
std::vector<std::shared_ptr<RangeTreeNode<T, S> > > canonicalNodes = {};
if (left->isLeaf) {
canonicalNodes.push_back(left);
} else {
left->leftCanonicalNodes(lower, canonicalNodes);
}
if (right->isLeaf) {
canonicalNodes.push_back(right);
} else {
right->rightCanonicalNodes(upper, canonicalNodes);
}
for (int i = 0; i < canonicalNodes.size(); i++) {
std::shared_ptr<RangeTreeNode<T, S> > node = canonicalNodes[i];
if (node->isLeaf) {
if (pointInRange(*(node->point), lower, upper)) {
pointsToReturn.push_back(*(node->point));
}
} else if (compareInd + 1 == point->dim()) {
auto allPointsAtNode = node->getAllPoints();
pointsToReturn.insert(pointsToReturn.end(), allPointsAtNode.begin(), allPointsAtNode.end());
} else {
auto allPointsAtNode = node->treeOnNextDim->pointsInRange(lower, upper);
pointsToReturn.insert(pointsToReturn.end(), allPointsAtNode.begin(), allPointsAtNode.end());
}
}
return pointsToReturn;
}
}
void leftFractionalCascade(const std::vector<T>& lower,
int geqInd,
int leqInd,
std::vector<RangeTreeNode<T,S>* >& nodes,
std::vector<std::pair<int,int> >& inds) {
if (leqInd < geqInd) {
return;
}
int compareInd = point->dim() - 2;
if (lower[compareInd] <= (*point)[compareInd]) {
if (isLeaf) {
nodes.push_back(this);
inds.push_back(std::pair<int,int>(0,0));
return;
}
int geqIndRight = pointerToGeqRight[geqInd];
int leqIndRight = pointerToLeqRight[leqInd];
if (leqIndRight >= geqIndRight) {
nodes.push_back(right.get());
if (right->isLeaf) {
inds.push_back(std::pair<int,int>(0,0));
} else {
inds.push_back(std::pair<int,int>(geqIndRight,leqIndRight));
}
}
left->leftFractionalCascade(lower,
pointerToGeqLeft[geqInd],
pointerToLeqLeft[leqInd],
nodes,
inds);
} else {
if (isLeaf) {
return;
}
right->leftFractionalCascade(lower,
pointerToGeqRight[geqInd],
pointerToLeqRight[leqInd],
nodes,
inds);
}
}
void rightFractionalCascade(const std::vector<T>& upper,
int geqInd,
int leqInd,
std::vector<RangeTreeNode<T,S>* >& nodes,
std::vector<std::pair<int,int> >& inds) {
if (leqInd < geqInd) {
return;
}
int compareInd = point->dim() - 2;
if ((*point)[compareInd] <= upper[compareInd]) {
if (isLeaf) {
nodes.push_back(this);
inds.push_back(std::pair<int,int>(0,0));
return;
}
int geqIndLeft = pointerToGeqLeft[geqInd];
int leqIndLeft = pointerToLeqLeft[leqInd];
if (leqIndLeft >= geqIndLeft) {
nodes.push_back(left.get());
if (left->isLeaf) {
inds.push_back(std::pair<int,int>(0,0));
} else {
inds.push_back(std::pair<int,int>(geqIndLeft,leqIndLeft));
}
}
right->rightFractionalCascade(upper,
pointerToGeqRight[geqInd],
pointerToLeqRight[leqInd],
nodes,
inds);
} else {
if (isLeaf) {
return;
}
left->rightFractionalCascade(upper,
pointerToGeqLeft[geqInd],
pointerToLeqLeft[leqInd],
nodes,
inds);
}
}
/**
* Helper function for countInRange(...).
* @param lower
* @param withLower
* @param nodes
*/
void leftCanonicalNodes(const std::vector<T>& lower,
std::vector<std::shared_ptr<RangeTreeNode<T,S> > >& nodes) {
if (isLeaf) {
throw std::logic_error("Should never have a leaf deciding if its canonical.");
}
int compareInd = pointOrdering.getCompareStartIndex();
int totalPoints = 0;
if (lower[compareInd] <= (*point)[compareInd]) {
nodes.push_back(right);
if (left->isLeaf) {
nodes.push_back(left);
} else {
left->leftCanonicalNodes(lower, nodes);
}
} else {
if (right->isLeaf) {
nodes.push_back(right);
} else {
right->leftCanonicalNodes(lower, nodes);
}
}
}
/**
* Helper function for countInRange(...).
* @param upper
* @param nodes
*/
void rightCanonicalNodes(const std::vector<T>& upper,
std::vector<std::shared_ptr<RangeTreeNode<T,S> > >& nodes) {
if (isLeaf) {
throw std::logic_error("Should never have a leaf deciding if its canonical.");
}