-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathkdTreeNode.h
1577 lines (1427 loc) · 64.9 KB
/
kdTreeNode.h
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
/*
* Copyright (c) 2015, 2021, 2023, 2024, 2025 Russell A. Brown
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors
* may be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/*
* The k-d tree was described by Jon Bentley in "Multidimensional Binary Search Trees
* Used for Associative Searching", CACM 18(9): 509-517, 1975. For k dimensions and
* n elements of data, a balanced k-d tree is built in O(kn log n) + O((k-1)n log n)
* time by first sorting the data in each of k dimensions, then building the k-d tree
* in a manner that preserves the order of the k sorts while recursively partitioning
* the data at each level of the k-d tree. No further sorting is necessary.
*/
#ifndef KD_TREE_NODE_H
#define KD_TREE_NODE_H
#include <algorithm>
#include <chrono>
#include <climits>
#include <exception>
#include <forward_list>
#include <future>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <map>
#include <math.h>
#include <mutex>
#include <random>
#include <sstream>
#include <stdexcept>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <utility>
#include <vector>
using std::async;
using std::cout;
using std::chrono::duration_cast;
using std::chrono::steady_clock;
using std::endl;
using std::distance;
using std::exception;
using std::fixed;
using std::forward_list;
using std::future;
using std::launch;
using std::list;
using std::map;
using std::lock_guard;
using std::make_pair;
using std::min;
using std::mutex;
using std::numeric_limits;
using std::ostringstream;
using std::pair;
using std::ref;
using std::runtime_error;
using std::scientific;
using std::setprecision;
using std::streamsize;
using std::vector;
/* Convert microseconds to seconds for use with std::chrono */
static const double MICROSECONDS_TO_SECONDS = 1000000.;
/* This type is the signed equivalent of size_t and might be equivalent to intmax_t */
typedef streamsize signed_size_t;
#include "kdTreeMergeSort.h"
#include "kdTreeHeapSort.h"
/* A forward reference to the friend class KdTree */
template <typename>
class KdTree;
/* One node of a k-d tree where T is key type */
template <typename K>
class KdNode {
private:
K* tuple;
KdNode<K>* ltChild;
KdNode<K>* gtChild;
#ifdef REVERSE_NEAREST_NEIGHBORS
size_t index;
#endif
// If PREALLOCATE is defined, the default ~KdNode destructor
// is used, which implies that no KdNode member field can be
// a pointer because a pointer would require explicit delete.
#ifndef PREALLOCATE
public:
~KdNode() {
// Because tuple is not contained by the KdTree::tuples
// vector, delete it.
delete[] tuple;
// Delete the child nodes, which performs recursive deletion.
delete ltChild;
delete gtChild;
}
#endif
private:
K* getTuple() {
return this->tuple;
}
/*
* The removeDuplicates function checks the validity of the merge sort and
* removes duplicates from a reference array.
*
* Calling parameters:
*
* reference - a K** that represents one of the reference arrays
* i - the leading dimension for the super key
* dim - the number of dimensions
*
* returns: the end index of the reference array following removal of duplicate elements
*/
private:
inline
static signed_size_t removeDuplicates(K** const reference,
signed_size_t const i,
signed_size_t const dim,
signed_size_t const size) {
signed_size_t end = 0;
for (signed_size_t j = 1; j < size; ++j) {
auto const compare = MergeSort<K>::superKeyCompare(reference[j], reference[end], i, dim);
if (compare < 0) {
ostringstream buffer;
buffer << "\n\nmerge sort failure: superKeyCompare(ref[" << j << "], ref["
<< end << "], " << i << ") = " << compare << " in removeDuplicates\n";
throw runtime_error(buffer.str());
}
else if (compare > 0) {
// Keep the jth element of the reference array.
reference[++end] = reference[j];
} else {
// If PREALLOCATE is undefined, skip over the jth element of the
// references array and delete the tuple. A pointer to any tuple
// not skipped will subsequently be copied from the references array
// to the kdNodes vector; hence, this tuple will be deleted by the
// ~KdNode destructor. So there will be no need to delete tuples via
// their pointers in this or any other references array.
//
// If PREALLOCATE is defined, skip over the jth element of the
// references array but do not delete the tuple because all tuples
// will be deleted en masse by the ~KdTree destructor.
#ifndef PREALLOCATE
delete[] reference[j];
#endif
}
}
return end;
}
/*
* The getKdNode function gets a KdNode from the kdNodes vector and assigns the tuple field.
* It also assigns to the index field the index of the KdNode within the kdNodes array.
*
* Calling parameters:
*
* reference - a K** that represents one of the reference arrays
* kdNodes - a vector<KdNode<K>>* if PREALLOCATE is defined
* - a vector<KdNode<K>*> if PREALLOCATE is undefined
* k - the index into both the reference and the kdNodes arrays
*
* returns: a KdNode pointer to the KdNode to which the tuple has been assigned
*/
private:
#ifndef PREALLOCATE
inline
static KdNode<K>* getKdNode(K** const reference,
vector<KdNode<K>*> const& kdNodes,
signed_size_t const k) {
kdNodes[k]->tuple = reference[k];
#ifdef REVERSE_NEAREST_NEIGHBORS
kdNodes[k]->index = k;
#endif
return kdNodes[k];
}
#else
inline
static KdNode<K>* getKdNode(K** const reference,
vector<KdNode<K>>* const kdNodes,
signed_size_t const k) {
(*kdNodes)[k].tuple = reference[k];
#ifdef REVERSE_NEAREST_NEIGHBORS
(*kdNodes)[k].index = k;
#endif
return &(*kdNodes)[k];
}
#endif
/*
* Create a permutation vector.
*
* Calling parameters:
*
* permutation - the permutation vector that is passed by reference and modified
* numDimensions - the number of dimensions
* numCoordinates - the number of points in the coordinates vector
*/
private:
static
void createPermutation(vector<signed_size_t>& permutation,
signed_size_t const numDimensions,
signed_size_t const numCoordinates) {
// Determine the maximum depth of the k-d tree, which is log2(numCoordinates).
signed_size_t size = numCoordinates;
signed_size_t maxDepth = 1;
while (size > 0) {
++maxDepth;
size >>= 1;
}
// Because the partition coordinate permutes in the order 0, 1, 2, 3, 0, 1, 2, 3, etc.
// (for e.g. 4-dimensional data), the leading key of the super key will be 0 at the
// first level of the nascent tree, consistent with having sorted the reference array
// using 0 as the leading key of the super key.
permutation.resize(maxDepth);
for (size_t i = 0; i < permutation.size(); ++i) {
permutation[i] = i % numDimensions;
}
}
/*
* The verifyKdTree function walks the k-d tree and checks that the
* children of a node are in the correct branch of that node.
*
* Calling parameters:
*
* permutation - the permutation vector
* dim - the number of dimensions
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* depth - the depth in the k-d tree
*
* returns: a count of the number of kdNodes in the k-d tree
*/
private:
signed_size_t verifyKdTree(vector<signed_size_t> const& permutation,
signed_size_t const dim,
signed_size_t const maximumSubmitDepth,
signed_size_t const depth) const {
signed_size_t count = 1;
if (tuple == nullptr) {
throw runtime_error("\n\npoint is null in verifyKdTree\n");
}
// The partition cycles as x, y, z, w...
signed_size_t const p = permutation[depth];
if (ltChild != nullptr) {
if (ltChild->tuple[p] > tuple[p]) {
throw runtime_error("\n\nchild is > node in verifyKdTree\n");
}
if (MergeSort<K>::superKeyCompare(ltChild->tuple, tuple, p, dim) >= 0) {
throw runtime_error("\n\nchild is >= node in verifyKdTree\n");
}
}
if (gtChild != nullptr) {
if (gtChild->tuple[p] < tuple[p]) {
throw runtime_error("\n\nchild is < node in verifyKdTree\n");
}
if (MergeSort<K>::superKeyCompare(gtChild->tuple, tuple, p, dim) <= 0) {
throw runtime_error("\n\nchild is <= node in verifyKdTree\n");
}
}
// Verify the < branch with a child thread at as many levels of the tree as possible.
// Create the child thread as high in the tree as possible for greater utilization.
// Is a child thread available to verify the < branch?
if (maximumSubmitDepth < 0 || depth > maximumSubmitDepth) {
// No, so verify the < branch with the current thread.
if (ltChild != nullptr) {
count += ltChild->verifyKdTree(permutation, dim, maximumSubmitDepth, depth + 1);
}
// Then verify the > branch with the current thread.
if (gtChild != nullptr) {
count += gtChild->verifyKdTree(permutation, dim, maximumSubmitDepth, depth + 1);
}
}
else {
// Yes, so verify the < branch with a child thread. Note that a lambda
// is required because this verifyKdTree function is not static. The use
// of std::ref may be unnecessary in view of the [&] lambda argument specification.
future<signed_size_t> verifyFuture;
if (ltChild != nullptr) {
verifyFuture =
async(launch::async, [&] {
return ltChild->verifyKdTree(ref(permutation),
dim,
maximumSubmitDepth,
depth + 1);
});
}
// And simultaneously verify the > branch with the current thread.
signed_size_t gtCount = 0;
if (gtChild != nullptr) {
gtCount = gtChild->verifyKdTree(permutation, dim, maximumSubmitDepth, depth + 1);
}
// Wait for the child thread to finish execution.
signed_size_t ltCount = 0;
if (ltChild != nullptr) {
try {
ltCount = verifyFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for verify future in verifyKdTree\n");
}
}
// Sum the counts returned by the child and current threads.
count += ltCount + gtCount;
}
return count;
}
/*
* The insideBounds function determines whether KdNode::tuple lies inside the
* hyper-rectangle defined by the query lower and upper bound vectors.
*
* Calling parameters:
*
* queryLower - the query lower bound vector
* queryUpper - the query upper bound vector
* enable - a vector that specifies the dimensions on which to test for insidedness
*
* return true if inside, false if outside
*/
private:
bool insideBounds(vector<K> const& queryLower,
vector<K> const& queryUpper,
vector<bool> const& enable) const {
bool inside = true;
for (size_t i = 0; i < queryLower.size(); ++i) {
if (enable[i] && (queryLower[i] > tuple[i] || queryUpper[i] < tuple[i])) {
inside = false;
break;
}
}
return inside;
}
/*
* The regionSearch function searches the k-d tree recursively to find the KdNodes that
* lie within a hyper-rectangle defined by the query lower and upper bounds.
*
* Calling parameters:
*
* result - a list<KdNode<K>*> that is passed by reference and modified
* queryLower - the query lower bound vector
* queryUpper - the query upper bound vector
* permutation - vector that specifies permutation of the partition coordinate
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* depth - the depth in the k-d tree
* enable - a vector that specifies the dimensions on which to prune the region search
*/
private:
void regionSearch(list<KdNode<K>*>& result,
vector<K> const& queryLower,
vector<K> const& queryUpper,
vector<signed_size_t> const& permutation,
signed_size_t const maximumSubmitDepth,
signed_size_t const depth,
vector<bool> const& enable) {
// The partition cycles as x, y, z, w...
signed_size_t const p = permutation[depth];
// If the KdNode is within the query hyper-rectangle for each of the k dimensions,
// add the KdNode to the list of KdNodes that lie inside the hyper-cube. The
// following loop is equivalent to the IN_REGION pseudo-Algol code proposed
// by Jon Bentley in his CACM article.
if (insideBounds(queryLower, queryUpper, enable)) {
result.push_front(this);
}
// Determine whether to search the < and > branches of the k-d tree. Although
// the superKeyCompare function can produce a different result for the == case
// than does comparing only the leading keys of the super-keys, that result
// will avoid unnecessary searching of a sub-tree (at the expense of a more
// precise super-key comparison) but the unnecessary search appears not to
// change the outcome of this recursive regionSearch function.
//
// Note that if the partition dimension is not enabled, both branches are searched.
#ifdef NO_SUPER_KEY
bool const searchLT = ltChild != nullptr && (tuple[p] >= queryLower[p] || !enable[p]);
bool const searchGT = gtChild != nullptr && (tuple[p] <= queryUpper[p] || !enable[p]);;
#else
bool const searchLT = ltChild != nullptr && (MergeSort<K>::superKeyCompare(tuple, queryLower.data(),
p, queryLower.size()) >= 0
|| !enable[p]);
bool const searchGT = gtChild != nullptr && (MergeSort<K>::superKeyCompare(tuple, queryUpper.data(),
p, queryLower.size()) <= 0
|| !enable[p]);
#endif
// Do both branches require searching and is a child thread available?
if (searchLT && searchGT && maximumSubmitDepth >= 0 && depth <= maximumSubmitDepth) {
// Yes, both branches of the tree require searching and a child thread is available,
// so prepare to search the < branch with a child thread.
future<void> searchFuture;
// Search the < branch?
if (searchLT) {
// Yes, search the < branch asynchronously with a child thread.
// A lamba is required because this regionSearch function is not
// static. The use of std::ref may be unnecessary in view of the
// [&] lambda argument specification.
list<KdNode<K>*> ltResult;
searchFuture = async(launch::async, [&] {
ltChild->regionSearch(ref(ltResult),
ref(queryLower),
ref(queryUpper),
ref(permutation),
maximumSubmitDepth,
depth + 1,
ref(enable));
});
// Search the > branch?
list<KdNode<K>*> gtResult;
if (searchGT) {
// Yes, search the > branch with the master thread.
gtChild->regionSearch(gtResult, queryLower, queryUpper, permutation, maximumSubmitDepth, depth + 1, enable);
}
// Get the result of searching the < branch with the child thread.
try {
searchFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for search future in regionSearch\n");
}
// Append the results of searching the < and > branches to the result (if any) for this KdNode.
result.splice(result.end(), ltResult);
result.splice(result.end(), gtResult);
} else {
// No, don't search the < branch. Search the > branch?
list<KdNode<K>*> gtResult;
if (searchGT) {
// Yes, search the > branch with the master thread.
gtChild->regionSearch(gtResult, queryLower, queryUpper, permutation, maximumSubmitDepth, depth + 1, enable);
}
// Append the result of searching the > branch to the result (if any) for this KdNode.
result.splice(result.end(), gtResult);
}
} else {
// No, both branches do not require searching. Search the < branch with the master thread?
if (searchLT) {
list<KdNode<K>*> ltResult;
ltChild->regionSearch(ltResult, queryLower, queryUpper, permutation, maximumSubmitDepth, depth + 1, enable);
result.splice(result.end(), ltResult);
}
// Search the > branch with the master thread?
if (searchGT) {
list<KdNode<K>*> gtResult;
gtChild->regionSearch(gtResult, queryLower, queryUpper, permutation, maximumSubmitDepth, depth + 1, enable);
result.splice(result.end(), gtResult);
}
}
}
/*
* The searchRegion function searches the k-d tree to find the KdNodes that
* lie within a hyper-rectangle defined by the query lower and upper bounds.
*
* Calling parameters:
*
* result - a list<KdNode<K>*> that is passed by reference and modified
* queryLower - the query lower bound vector that is passed by reference and modified
* queryUpper - the query upper bound vector that is passed by reference and modified
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* size - the number of points in the coordinates vector
*
* return a list of KdNodes that lie within the query hyper-rectangle
*/
private:
void searchRegion(list<KdNode<K>*>& result,
vector<K>& queryLower,
vector<K>& queryUpper,
signed_size_t const maximumSubmitDepth,
signed_size_t const size) {
// It is unnecessary to compute the partition coordinate upon each recursive call
// of the regionSearch function because that coordinate depends only on the depth
// of recursion, so it may be pre-computed and stored in the 'permutation' vector.
vector<signed_size_t> permutation;
createPermutation(permutation, queryLower.size(), size);
// Ensure that each query lower bound <= the corresponding query upper bound.
for (size_t i = 0; i < queryLower.size(); ++i) {
if (queryLower[i] > queryUpper[i]) {
auto const tmp = queryLower[i];
queryLower[i] = queryUpper[i];
queryUpper[i] = tmp;
}
}
// Search the tree over all dimensions to obtain the resulting list of KdNodes.
vector<bool> enable(queryLower.size(), true);
regionSearch(result, queryLower, queryUpper, permutation, maximumSubmitDepth, 0, enable);
}
/*
* The searchRegion function searches the k-d tree to find the KdNodes that
* lie within a hyper-rectangle defined by the query lower and upper bounds.
*
* Calling parameters:
*
* result - a list of KdNode pointers that is passed by reference and modified
* queryLower - the query lower bound vector that is passed by reference and modified
* queryUpper - the query upper bound vector that is passed by reference and modified
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* size - the number of points in the coordinates vector
* enable - a vector that specifies the dimensions on which to test for insidedness
* and prune the region search
*
* return a list of KdNodes that lie within the query hyper-rectangle
*/
private:
void searchRegion(list<KdNode<K>*>& result,
vector<K>& queryLower,
vector<K>& queryUpper,
signed_size_t const maximumSubmitDepth,
signed_size_t const size,
vector<bool> const& enable) {
// It is unnecessary to compute the partition coordinate upon each recursive call
// of the regionSearch function because that coordinate depends only on the depth
// of recursion, so it may be pre-computed and stored in the 'permutation' vector.
vector<signed_size_t> permutation;
createPermutation(permutation, queryLower.size(), size);
// Ensure that each query lower bound <= the corresponding query upper bound.
for (size_t i = 0; i < queryLower.size(); ++i) {
if (queryLower[i] > queryUpper[i]) {
auto const tmp = queryLower[i];
queryLower[i] = queryUpper[i];
queryUpper[i] = tmp;
}
}
// Search the tree over the enabled dimensions to obtain the resulting list of KdNodes.
regionSearch(result, queryLower, queryUpper, permutation, maximumSubmitDepth, 0, enable);
}
/*
* Walk the k-d tree recursively and append to a list each KdNode that lies inside
* the hyper-rectangle defined by the query lower and upper bounds.
*
* Calling parameters:
*
* result - a list of KdNode pointers that is passed by reference and modified
* queryLower - the query lower bound vector
* queryUpper - the query upper bound vector
* enable - a vector that specifies the dimensions on which to test for insidedness
* and prune the search
*
* return a list of pointers to KdNodes that lie within the query hyper-rectangle.
*/
private:
void regionBrute(list<KdNode<K>*>& result,
vector<K> const& queryLower,
vector<K> const& queryUpper,
vector<bool> const& enable) {
// Append the KdNode to the list if it lies inside the query bounds.
if (insideBounds(queryLower, queryUpper, enable)) {
result.push_front(this);
}
// Visit the < sub-tree.
if (ltChild != nullptr) {
list<KdNode<K>*> ltResult;
ltChild->regionBrute(ltResult, queryLower, queryUpper, enable);
result.splice(result.end(), ltResult);
}
// Visit the > sub-tree.
if (gtChild != nullptr) {
list<KdNode<K>*> gtResult;
gtChild->regionBrute(gtResult, queryLower, queryUpper, enable);
result.splice(result.end(), gtResult);
}
}
/*
* Walk the k-d tree and append to a list each KdNode that lies inside
* the hyper-rectangle defined by the query lower and upper bounds.
*
* Calling parameters:
*
* result - a list of KdNode pointers that is passed by reference and modified
* queryLower - the query lower bound vector
* queryUpper - the query upper bound vector
*
* return a list of pointers to KdNodes that lie within the query hyper-rectangle.
*/
private:
void bruteRegion(list<KdNode<K>*>& result,
vector<K>& queryLower,
vector<K>& queryUpper) {
// Search over all dimensions.
vector<bool> enable(queryLower.size(), true);
// Ensure that each query lower bound <= the corresponding query upper bound.
for (size_t i = 0; i < queryLower.size(); ++i) {
if (queryLower[i] > queryUpper[i]) {
auto const tmp = queryLower[i];
queryLower[i] = queryUpper[i];
queryUpper[i] = tmp;
}
}
// Walk the k-d tree recursively.
regionBrute(result, queryLower, queryUpper, enable);
}
/*
* Search the k-d tree recursively for up to M nearest geometric neighbors to a query point
* by adding them to the NearestNeighborHeap that stores up to M neighbors. Exclude from the
* search any branch of the tree wherein it is guaranteed that all nodes in that branch are
* farther away than the current farthest node stored in the heap. Details of the search
* algorithm are described by Friedman et al. in "An Algorithm for Finding Best Matches in
* Logarithmic Expected Time", ACM Transactions on Mathematical Software, 3: 209-226, 1977.
*
* Calling parameters:
*
* heap - an instance of NearestNeighborHeap that is built relative to a query point
* permutation - vector that specifies permutation of the partition coordinate
* depth - depth in the k-d tree
*/
private:
void nearestNeighbors(NearestNeighborHeap<K>& heap,
vector<signed_size_t> const& permutation,
signed_size_t const depth) {
// The partition permutes as x, y, z, w...
signed_size_t p = permutation[depth];
// If query[p] < tuple[p], descend the < branch to the bottom of the tree before adding a point to the
// heap, which increases the probability that closer nodes to the query point will get added earlier,
// thus reducing the likelihood of adding more distant points that get kicked out of the heap later.
if (heap.query[p] < tuple[p]) {
if (ltChild != nullptr) { // If not at the bottom of the tree, descend the < branch unconditionally.
ltChild->nearestNeighbors(heap, permutation, depth + 1);
}
// If the current node is closer to the query point than the farthest item in the heap, or if this
// component of the array is not part of the nearest neighbor search, or if the heap is not full,
// descend the > branch and then attempt to add the node to the heap.
double const tup = static_cast<double>(tuple[p]); // May result in loss of precision
double const que = static_cast<double>(heap.query[p]); // May result in loss of precision
double const dist = tup - que;
if (dist * dist <= heap.curMaxDist() || !heap.enable[p] || !heap.heapFull()) {
if (gtChild != nullptr) { // If not at the bottom of the tree, descend the > branch
gtChild->nearestNeighbors(heap, permutation, depth + 1);
}
heap.add(this); // Attempt to add the current KdNode to the heap.
}
}
// If query[p] > tuple[p], descend the > branch to the bottom of the tree before adding a point to the
// heap, which increases the probability that closer nodes to the query point will get added earlier,
// thus reducing the likelihood of adding more distant points that get kicked out of the heap later.
else if (heap.query[p] > tuple[p]) {
if (gtChild != nullptr) { // If not at the bottom of the tree, descend the > branch unconditionally.
gtChild->nearestNeighbors(heap, permutation, depth + 1);
}
// If the current node is closer to the query point than the farthest item in the heap, or if this
// component of the array is not part of the nearest neighbor search, or if the heap is not full,
// descend the < branch and then attempt to add the node to the heap.
double const tup = static_cast<double>(tuple[p]); // May result in loss of precision
double const que = static_cast<double>(heap.query[p]); // May result in loss of precision
double const dist = tup - que;
if (dist * dist <= heap.curMaxDist() || !heap.enable[p] || !heap.heapFull()) {
if (ltChild != nullptr) {
ltChild->nearestNeighbors(heap, permutation, depth + 1);
}
heap.add(this); // Attempt to add the current node to the heap.
}
}
// Because query[p] == tuple[p], the probability of finding nearest neighbors is equal for both branches
// of the tree, so descend both branches and then attempt to add the current node to the heap.
else {
if (ltChild != nullptr) {
ltChild->nearestNeighbors(heap, permutation, depth + 1);
}
if (gtChild != nullptr) {
gtChild->nearestNeighbors(heap, permutation, depth + 1);
}
heap.add(this); // Attempt to add the current node to the heap.
}
}
/*
* Find up to M nearest neighbors to the query vector and return them as a list ordered by increasing distance.
*
* Calling parameters:
*
* neighbors - the nearest neighbors list that is passed by reference and modified.
* query - the query vector
* numNeighbors - the number M of nearest neighbors to attempt to find
* size - the number of points in the coordinates vector
*/
private:
void findNearestNeighbors(forward_list< pair<double, KdNode<K>*> >& neighbors,
vector<K> const& query,
signed_size_t const numNeighbors,
signed_size_t const size) {
// It is unnecessary to compute the partition coordinate upon each recursive call
// of the nearestNeighbors function because that coordinate depends only on the depth
// of recursion, so it may be pre-computed and stored in the 'permutation' vector.
vector<signed_size_t> permutation;
createPermutation(permutation, query.size(), size);
// Create the heap and search the k-d tree for nearest neighbors.
NearestNeighborHeap<K> heap(query, numNeighbors);
nearestNeighbors(heap, permutation, 0);
// Empty the heap by successively removing the top of the heap and prepending it to a list.
// Remove only the number of heap entries present.
signed_size_t const heapDepth = heap.heapDepth();
for (signed_size_t i = 0; i < heapDepth; ++i) {
neighbors.push_front(heap.removeTop());
}
}
/*
* Find up to M nearest neighbors to the query vector and return them as a list ordered by increasing distance.
*
* Calling parameters:
*
* neighbors - the nearest neighbors list that is passed by reference and modified.
* query - the query vector
* numNeighbors - the number M of nearest neighbors to attempt to find
* size - the number of points in the coordinates vector
* enable - a vector that specifies the dimensions for which to test distance
*/
private:
void findNearestNeighbors(forward_list< pair<double, KdNode<K>*> >& neighbors,
vector<K> const& query,
signed_size_t const numNeighbors,
signed_size_t const size,
vector<bool> const& enable) {
// It is unnecessary to compute the partition coordinate upon each recursive call
// of the nearestNeighbors function because that coordinate depends only on the depth
// of recursion, so it may be pre-computed and stored in the 'permutation' vector.
vector<signed_size_t> permutation;
createPermutation(permutation, query.size(), size);
// Create the heap and search the k-d tree for nearest neighbors.
NearestNeighborHeap<K> heap(query, numNeighbors, enable);
nearestNeighbors(heap, permutation, 0);
// Empty the heap by successively removing the top of the heap and prepending it to a list.
// Remove only the number of heap entries present.
signed_size_t const heapDepth = heap.heapDepth();;
for (signed_size_t i = 0; i < heapDepth; ++i) {
neighbors.push_front(heap.removeTop());
}
}
/*
* Find up to M nearest neighbors to the query vector and return them as a list ordered by increasing distance.
*
* Calling parameters:
*
* neighbors - the nearest neighbors list that is passed by reference and modified
* query - the query vector
* permutation - vector that specifies permutation of the partition coordinate
* numNeighbors - the number M of nearest neighbors to attempt to find
*/
private:
void findNearestNeighbors(forward_list< pair<double, KdNode<K>*> >& neighbors,
vector<K> const& query,
vector<signed_size_t> const& permutation,
signed_size_t const numNeighbors) {
// Create the heap and search the k-d tree for nearest neighbors.
NearestNeighborHeap<K> heap(query, numNeighbors);
nearestNeighbors(heap, permutation, 0);
// Empty the heap by successively removing the top of the heap and prepending it to a list.
// Remove only the number of heap entries present.
signed_size_t const heapDepth = heap.heapDepth();;
for (signed_size_t i = 0; i < heapDepth; ++i) {
neighbors.push_front(heap.removeTop());
}
}
/*
* Find up to M nearest neighbors to the query vector and return them as a list ordered by increasing distance.
*
* Calling parameters:
*
* neighbors - the nearest neighbors list that is passed by reference and modified
* query - the query vector
* permutation - vector that specifies permutation of the partition coordinate
* numNeighbors - the number M of nearest neighbors to attempt to find
* enable - a vector that specifies the dimensions for which to test distance
*/
private:
void findNearestNeighbors(forward_list< pair<double, KdNode<K>*> >& neighbors,
vector<K> const& query,
vector<signed_size_t> const& permutation,
signed_size_t const numNeighbors,
vector<bool> const& enable) {
// Create the heap and search the k-d tree for nearest neighbors.
NearestNeighborHeap<K> heap(query, numNeighbors, enable);
nearestNeighbors(heap, permutation, 0);
// Empty the heap by successively removing the top of the heap and prepending it to a list.
// Remove only the number of heap entries present.
signed_size_t const heapDepth = heap.heapDepth();;
for (signed_size_t i = 0; i < heapDepth; ++i) {
neighbors.push_front(heap.removeTop());
}
}
/*
* Verify the consistency between the nearest neighbors lists found
* by k-d tree search and by brute force.
*
* Calling parameters:
*
* neighborsFast - a list of nearest neighbors found by k-d tree search
* neighborsSlow - a list of nearest neighbors found by brute force.
*
* Although this function does not directly access the k-d tree, it requires the persistence
* of the k-d tree for access to the KdNodes via the lists. Hence, this function is not static.
*/
private:
void verifyNearestNeighbors(forward_list< pair<double, KdNode<K>*> >& neighborsFast,
forward_list< pair<double, KdNode<K>*> >& neighborsSlow) const {
auto itf1 = neighborsFast.begin();
auto its1 = neighborsSlow.begin();
// Compare the first k-d tree (fast) distance to the first brute-force (slow) distance.
if (itf1->first != its1->first) {
ostringstream buffer;
buffer << "\n\nfast distance[0] = " << itf1->first << " != slow distance[0] = " << its1->first << endl;
throw runtime_error(buffer.str());
}
// Compare the first k-d tree KdNode pointer to the first brute-force KdNode pointer.
if (itf1->second != its1->second) {
throw runtime_error("\n\nfast KdNode*[0] != slow KdNode*[0]\n");
}
// Compare the remaining distances and KdNode*
auto itf2 = itf1;
auto its2 = its1;
++itf2;
++its2;
signed_size_t i = 1;
for ( ; itf2 != neighborsFast.end(); ++itf1, ++its1, ++itf2, ++its2, ++i) {
// Ensure that the fast distances increase monotonically.
if (itf1->first > itf2->first) {
ostringstream buffer;
buffer << "\n\nfast distance[" << (i-1) << "] = " << itf1->first << " > fast distance[" << i << "] = " << itf2->first << endl;
throw runtime_error(buffer.str());
}
// Ensure that the slow distances increase monotonically.
if (its1->first > its2->first) {
ostringstream buffer;
buffer << "\n\nslow distance[" << (i-1) << "] = " << its1->first << " > slow distance[" << i << "] = " << its2->first << endl;
throw runtime_error(buffer.str());
}
// Compare the ith k-d tree distance to the ith brute-force distance.
if (itf2->first != its2->first) {
ostringstream buffer;
buffer << "\n\nfast distance[" << i << "] = " << itf2->first << " != slow distance[" << i << "] = " << its2->first << endl;
throw runtime_error(buffer.str());
}
// Compare the ith k-d tree KdNode pointer to the ith brute-force KdNode pointer.
if (itf2->second != its2->second) {
ostringstream buffer;
buffer << "\n\nfast KdNode*[" << i << "] != slow KdNode*[" << i << "]\n";
throw runtime_error(buffer.str());
}
}
}
/*
* Sort a list of KdNode instances by increasing distance from the query point.
*
* Calling parameters:
*
* kdList - the list of KdNode instances
* query - a vector that contains the query point coordinates
* maxNodes - the maximum number of nodes to maintain on the heap
*
* returns: a sorted forward list of (distance, KdNode*) pairs
*
* Because this function does not access the k-d tree, it could be static.
* However, calling it as a static function requires speicification of a
* type, so calling it as a non-static function is less cumbersome.
*/
private:
forward_list<pair<double, KdNode<K>*>> sortByDistance(list<KdNode<K>*> const& kdList,
vector<K> const& query,
signed_size_t const& maxNodes) {
// Create a heap and add each KdNode on the list to the heap
// if that KdNode's distance to the query point is less than
// the distance of the currently farthest KdNode on the heap.
NearestNeighborHeap<K> heap(query, maxNodes);
for (auto it = kdList.begin(); it != kdList.end(); ++it) {
double dist2 = 0;
for (size_t j = 0; j < query.size(); ++j) {
double tup = (*it)->tuple[j]; // May result in loss of precision
double que = query[j] ; // May result in loss of precision
double dist = tup - que;
dist2 += dist * dist;
}
if (dist2 <= heap.curMaxDist() || !heap.heapFull()) {
heap.add(*it);
}
}
// Empty the heap and prepend each entry to a sorted list.
forward_list<pair<double, KdNode<K>*>> sortedList;
signed_size_t const heapDepth = heap.heapDepth();
for (signed_size_t i = 0; i < heapDepth; ++i) {
sortedList.push_front(heap.removeTop());
}
return sortedList;
}
#ifdef REVERSE_NEAREST_NEIGHBORS
/*
* Walk the k-d tree, find up to M nearest neighbors to each point in the k-d tree,
* and add those nearest neighbors to nearest neighbors and reverse nearest neighbors