-
Notifications
You must be signed in to change notification settings - Fork 1
/
kdTreeMapNlogn.cpp
3652 lines (3271 loc) · 152 KB
/
kdTreeMapNlogn.cpp
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 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(n log n) time by finding the
* median of the data at each level of the tree via the "median of medians" algorithm
* described by Manuel Blum, et al. in "Time Bounds for Selection", Journal of Computer
* and System Sciences, 7: 448-461, 1973.
*
* Gnu g++ compilation options are: -lm -O3 -std=c++11 -pthread -D TEST_KD_TREE -W
*
* Optional compilation options are:
*
* -D INSERTION_SORT_CUTOFF=n - A cutoff for switching from merge sort to insertion sort
* in the KdNode::mergeSort* functions (default 15)
* -D MEDIAN_OF_MEDIANS_CUTOFF=n - A cutoff for switching from median of medians to insertion sort
* in KdNode::partition (default 15)
* -D MEDIAN_CUTOFF=n - A cutoff for switching from to 2 threads to calculate the median
* in KdNode::partition (default 16384)
* -D INDEX_CUTOFF=n - A cutoff for switching from to 2 threads to find the index of
* the calculated median in KdNode::partition (default 512)
* -D NO_SUPER_KEY - Do not compare super-keys in the KdNode::regionSearch function.
* -D DUAL_THREAD_MEDIAN - Calculate the medians with two threads.
* -D DUAL_THREAD_INDEX - Find the index of the median of medians with two threads.
* -D BIDIRECTIONAL_PARTITION - Partition an array about the median of medians proceeding
* from both ends of the array instead of only the beginning.
* -D MACH - Use a Mach equivalent to the clock_gettime(CLOCK_REALTIME, &time) function
* but this option appears to no longer be necessary.
*
* Usage:
*
* kdTreeMapNlogn [-n N] [-m M] [-x X] [-d D] [-t T] [-s S] [-p P] [-b] [-c] [-r]
*
* where the command-line options are interpreted as follows.
*
* -n The number N of randomly generated points used to build the k-d tree
*
* -m The maximum number M of nearest neighbors added to a priority queue
* when searching the k-d tree for nearest neighbors
*
* -x The number X of duplicate points added to test removal of duplicate points
*
* -t The number of threads T used to build and search the k-d tree
*
* -s The search distance S used for region search
*
* -p The maximum number P of nodes to report when reporting region search results
*
* -b Compare k-d tree nearest neighbors search to exhaustive search
*
* -c Compare k-d tree region search to exhaustive search
*
* -r Construct nearest-neighbors and reverse-nearest-neighbors maps
*/
#include <exception>
#include <forward_list>
#include <future>
#include <iomanip>
#include <iostream>
#include <limits>
#include <list>
#include <math.h>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <vector>
using std::async;
using std::cout;
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::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::string;
using std::vector;
/* A cutoff for switching from merge sort to insertion sort in the KdNode::mergeSort* functions */
#ifndef INSERTION_SORT_CUTOFF
#define INSERTION_SORT_CUTOFF 15
#endif
/* A cutoff for switching from median of medians to insertion sort in KdNode::partition */
#ifndef MEDIAN_OF_MEDIANS_CUTOFF
#define MEDIAN_OF_MEDIANS_CUTOFF 15
#endif
/* A cutoff for switching from 1 to 2 threads to calculate the median in KdNode::partition */
#ifndef MEDIAN_CUTOFF
#define MEDIAN_CUTOFF 16384
#endif
/* A cutoff for switching from 1 to 2 threads to find the index of the calculated median in KdNode::partition */
#ifndef INDEX_CUTOFF
#define INDEX_CUTOFF = 512
#endif
/*
* This type is the signed equivalent of size_t and might be equivalent to intmax_t
*/
typedef streamsize signed_size_t;
/*
* These are the types used for the test. Change the intrisic types in
* these typedefs to test the k-d tree with different intrisic types.
*/
typedef int64_t kdKey_t;
typedef string kdValue_t;
/*
* Create an alternate to clock_gettime(CLOCK_REALTIME, &time) for Mach. See
* http://stackoverflow.com/questions/5167269/clock-gettime-alternative-in-mac-os-x
* However, it appears that later versions of Mac OS X support clock_gettime(),
* so this alternative may no longer be necessary for Mac OS X.
*/
#ifdef MACH
#include <mach/mach_time.h>
#define MACH_NANO (+1.0E-9)
#define MACH_GIGA UINT64_C(1000000000)
static double mach_timebase = 0.0;
static uint64_t mach_timestart = 0;
struct timespec getTime(void) {
// be more careful in a multithreaded environement
if (!mach_timestart) {
mach_timebase_info_data_t tb = { 0, 1 }; // Initialize tb.numer and tb.denom
mach_timebase_info(&tb);
mach_timebase = tb.numer;
mach_timebase /= tb.denom;
mach_timestart = mach_absolute_time();
}
struct timespec t;
double diff = (mach_absolute_time() - mach_timestart) * mach_timebase;
t.tv_sec = diff * MACH_NANO;
t.tv_nsec = diff - (t.tv_sec * MACH_GIGA);
return t;
}
#else
#if defined(_WIN32) || defined(_WIN64)
//see https://stackoverflow.com/questions/5404277/porting-clock-gettime-to-windows/5404467#5404467
#define NOMINMAX // Prevent Windows from getting confused about std::min vs. min, etc.
#include <windows.h>
int clock_gettime(int, struct timespec* tv)
{
static int initialized = 0;
static LARGE_INTEGER freq, startCount;
static struct timespec tv_start;
LARGE_INTEGER curCount;
time_t sec_part;
long nsec_part;
if (!initialized) {
QueryPerformanceFrequency(&freq);
QueryPerformanceCounter(&startCount);
timespec_get(&tv_start, TIME_UTC);
initialized = 1;
}
QueryPerformanceCounter(&curCount);
curCount.QuadPart -= startCount.QuadPart;
sec_part = curCount.QuadPart / freq.QuadPart;
nsec_part = (long)((curCount.QuadPart - (sec_part * freq.QuadPart))
* 1000000000UL / freq.QuadPart);
tv->tv_sec = tv_start.tv_sec + sec_part;
tv->tv_nsec = tv_start.tv_nsec + nsec_part;
if (tv->tv_nsec >= 1000000000UL) {
tv->tv_sec += 1;
tv->tv_nsec -= 1000000000UL;
}
return 0;
}
#define CLOCK_REALTIME 0
#endif
struct timespec getTime(void) {
struct timespec time;
clock_gettime(CLOCK_REALTIME, &time);
return time;
}
#endif
/* A forward reference to NearestNeighborHeap */
template <typename, typename>
class NearestNeighborHeap;
/* One node of a k-d tree where K is key type and V is value type */
template <typename K, typename V>
class KdNode {
public:
K* tuple;
private:
KdNode<K,V>* ltChild;
KdNode<K,V>* gtChild;
KdNode<K,V>* duplicates;
V value;
size_t index;
public:
KdNode(signed_size_t const dim,
V const& value,
size_t const index) {
this->tuple = new K[dim];
this->value = value;
this->index = index;
this->ltChild = this->gtChild = this->duplicates = nullptr; // redundant
}
public:
~KdNode() {
delete[] tuple;
// Delete each KdNode from the duplicates list.
auto nextPtr = this->duplicates;
while (nextPtr != nullptr) {
auto tempPtr = nextPtr;
nextPtr = nextPtr->duplicates;
tempPtr->duplicates = nullptr; // Prevent recursive deletion.
delete tempPtr;
}
}
public:
K const* getTuple() {
return this->tuple;
}
/*
* The superKeyCompare function compares two K arrays in all k dimensions,
* and uses the sorting or partition coordinate as the most significant dimension.
*
* Calling parameters:
*
* a - a K*
* b - a K*
* p - the most significant dimension
* dim - the number of dimensions
*
* returns a K result of comparing two K arrays
*/
private:
inline
static K superKeyCompare(K const* a,
K const* b,
signed_size_t const p,
signed_size_t const dim) {
// Typically, this first calculation of diff will be non-zero and bypass the 'for' loop.
K diff = a[p] - b[p];
for (signed_size_t i = 1; diff == 0 && i < dim; i++) {
signed_size_t r = i + p;
// A fast alternative to the modulus operator for (i + p) < 2 * dim.
r = (r < dim) ? r : r - dim;
diff = a[r] - b[r];
}
return diff;
}
/*
* The following four merge sort functions are adapted from the mergesort function that is shown
* on p. 166 of Robert Sedgewick's "Algorithms in C++", Addison-Wesley, Reading, MA, 1992.
* That elegant implementation of the merge sort algorithm eliminates the requirement to test
* whether the upper and lower halves of an auxiliary array have become exhausted during the
* merge operation that copies from the auxiliary array to a result array. This elimination is
* made possible by inverting the order of the upper half of the auxiliary array and by accessing
* elements of the upper half of the auxiliary array from highest address to lowest address while
* accessing elements of the lower half of the auxiliary array from lowest address to highest
* address.
*
* The following four merge sort functions also implement two suggestions from p. 275 of Robert
* Sedgewick's and Kevin Wayne's "Algorithms 4th Edition", Addison-Wesley, New York, 2011. The
* first suggestion is to replace merge sort with insertion sort when the size of the array to
* sort falls below a threshold. The second suggestion is to avoid unnecessary copying to the
* auxiliary array prior to the merge step of the algorithm by implementing two versions of
* merge sort and by applying some "recursive trickery" to arrange that the required result is
* returned in an auxiliary array by one version and in a result array by the other version.
* The following four merge sort methods build upon this suggestion and return their result in
* either ascending or descending order, as discussed on pp. 173-174 of Robert Sedgewick's
* "Algorithms in C++", Addison-Wesley, Reading, MA, 1992.
*
* During multi-threaded execution, the upper and lower halves of the result array may be filled
* from the auxiliary array (or vice versa) simultaneously by two threads. The lower half of the
* result array is filled by accessing elements of the upper half of the auxiliary array from highest
* address to lowest address while accessing elements of the lower half of the auxiliary array from
* lowest address to highest address, as explained above for elimination of the test for exhaustion.
* The upper half of the result array is filled by addressing elements from the upper half of the
* auxiliary array from lowest address to highest address while accessing the elements from the lower
* half of the auxiliary array from highest address to lowest address. Note: for the upper half
* of the result array, there is no requirement to test for exhaustion provided that the upper half
* of the result array never comprises more elements than the lower half of the result array. This
* provision is satisfied by computing the median address of the result array as shown below for
* all four merge sort methods.
*
*
* The mergeSortReferenceAscending function recursively subdivides the reference array then
* merges the elements in ascending order and leaves the result in the reference array.
*
* Calling parameters:
*
* reference - a KdNode** array to sort via its (x, y, z, w...) tuples array
* temporary - a KdNode** temporary array from which to copy sorted results;
* this array must be as large as the reference array
* low - the start index of the region of the reference array to sort
* high - the end index of the region of the reference array to sort
* p - the sorting partition (x, y, z, w...)
* dim - the number of dimensions
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* depth - the tree depth
*/
private:
static void mergeSortReferenceAscending(KdNode<K,V>** const reference,
KdNode<K,V>** const temporary,
signed_size_t const low,
signed_size_t const high,
signed_size_t const p,
signed_size_t const dim,
signed_size_t const maximumSubmitDepth,
signed_size_t const depth) {
if (high - low > INSERTION_SORT_CUTOFF) {
// Avoid overflow when calculating the median.
signed_size_t const mid = low + ((high - low) >> 1);
// Subdivide the lower half of the reference array with a child thread at as many levels of subdivision as possible.
// Create the child threads as high in the subdivision hierarchy as possible for greater utilization.
// Is a child thread available to subdivide the lower half of the reference array?
if (maximumSubmitDepth < 0 || depth > maximumSubmitDepth) {
// No, recursively subdivide the lower half of the reference array with the current
// thread and return the result in the temporary array in ascending order.
mergeSortTemporaryAscending(reference, temporary, low, mid, p, dim, maximumSubmitDepth, depth + 1);
// Then recursively subdivide the upper half of the reference array with the current
// thread and return the result in the temporary array in descending order.
mergeSortTemporaryDescending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Compare the results in the temporary array in ascending order and merge them into
// the reference array in ascending order.
for (signed_size_t i = low, j = high, k = low; k <= high; ++k) {
reference[k] =
(superKeyCompare(temporary[i]->tuple, temporary[j]->tuple, p, dim) < 0) ? temporary[i++] : temporary[j--];
}
}
else {
// Yes, a child thread is available, so recursively subdivide the lower half of the reference
// array with a child thread and return the result in the temporary array in ascending order.
auto sortFuture = async(launch::async, mergeSortTemporaryAscending, reference, temporary,
low, mid, p, dim, maximumSubmitDepth, depth + 1);
// And simultaneously, recursively subdivide the upper half of the reference array with
// the current thread and return the result in the temporary array in descending order.
mergeSortTemporaryDescending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Wait for the child thread to finish execution.
try {
sortFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for sort future in mergeSortReferenceAscending\n");
}
// Compare the results in the temporary array in ascending order with a child thread
// and merge them into the lower half of the reference array in ascending order.
auto mergeFuture =
async(launch::async, [&] {
for (signed_size_t i = low, j = high, k = low; k <= mid; ++k) {
reference[k] =
(superKeyCompare(temporary[i]->tuple, temporary[j]->tuple, p, dim) <= 0)
? temporary[i++] : temporary[j--];
}
});
// And simultaneously compare the results in the temporary array in descending order with the
// current thread and merge them into the upper half of the reference array in ascending order.
for (signed_size_t i = mid, j = mid + 1, k = high; k > mid; --k) {
reference[k] =
(superKeyCompare(temporary[i]->tuple, temporary[j]->tuple, p, dim) > 0) ? temporary[i--] : temporary[j++];
}
// Wait for the child thread to finish execution.
try {
mergeFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for merge future in mergeSortReferenceAscending\n");
}
}
}
else {
// Here is Jon Benley's implementation of insertion sort from "Programming Pearls", pp. 115-116,
// Addison-Wesley, 1999, that sorts in ascending order and leaves the result in the reference array.
for (signed_size_t i = low + 1; i <= high; ++i) {
auto const tmp = reference[i];
signed_size_t j;
for (j = i; j > low && superKeyCompare(reference[j - 1]->tuple, tmp->tuple, p, dim) > 0; --j) {
reference[j] = reference[j - 1];
}
reference[j] = tmp;
}
}
}
/*
* The mergeSortReferenceDescending function recursively subdivides the reference array then
* merges the elements in descending order and leaves the result in the reference array.
*
* Calling parameters:
*
* reference - a KdNode** array to sort via its (x, y, z, w...) tuples array
* temporary - a KdNode** temporary array from which to copy sorted results;
* this array must be as large as the reference array
* low - the start index of the region of the reference array to sort
* high - the end index of the region of the reference array to sort
* p - the sorting partition (x, y, z, w...)
* dim - the number of dimensions
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* depth - the tree depth
*/
private:
static void mergeSortReferenceDescending(KdNode<K,V>** const reference,
KdNode<K,V>** const temporary,
signed_size_t const low,
signed_size_t const high,
signed_size_t const p,
signed_size_t const dim,
signed_size_t const maximumSubmitDepth,
signed_size_t const depth) {
if (high - low > INSERTION_SORT_CUTOFF) {
// Avoid overflow when calculating the median.
signed_size_t const mid = low + ((high - low) >> 1);
// Subdivide the lower half of the reference array with a child thread at as many levels of subdivision as possible.
// Create the child threads as high in the subdivision hierarchy as possible for greater utilization.
// Is a child thread available to subdivide the lower half of the reference array?
if (maximumSubmitDepth < 0 || depth > maximumSubmitDepth) {
// No, recursively subdivide the lower half of the reference array with the current
// thread and return the result in the temporary array in descending order.
mergeSortTemporaryDescending(reference, temporary, low, mid, p, dim, maximumSubmitDepth, depth + 1);
// Then recursively subdivide the upper half of the reference array with the current
// thread and return the result in the temporary array in ascending order.
mergeSortTemporaryAscending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Compare the results in the temporary array in ascending order and merge them into
// the reference array in descending order.
for (signed_size_t i = low, j = high, k = low; k <= high; ++k) {
reference[k] =
(superKeyCompare(temporary[i]->tuple, temporary[j]->tuple, p, dim) > 0) ? temporary[i++] : temporary[j--];
}
}
else {
// Yes, a child thread is available, so recursively subdivide the lower half of the reference
// array with a child thread and return the result in the temporary array in descending order.
auto sortFuture = async(launch::async, mergeSortTemporaryDescending, reference, temporary,
low, mid, p, dim, maximumSubmitDepth, depth + 1);
// And simultaneously, recursively subdivide the upper half of the reference array with
// the current thread and return the result in the temporary array in ascending order.
mergeSortTemporaryAscending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Wait for the child thread to finish execution.
try {
sortFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for sort future in mergeSortReferenceDescending\n");
}
// Compare the results in the temporary array in ascending order with a child thread
// and merge them into the lower half of the reference array in descending order.
auto mergeFuture =
async(launch::async, [&] {
for (signed_size_t i = low, j = high, k = low; k <= mid; ++k) {
reference[k] =
(superKeyCompare(temporary[i]->tuple, temporary[j]->tuple, p, dim) >= 0)
? temporary[i++] : temporary[j--];
}
});
// And simultaneously compare the results in the temporary array in descending order with the
// current thread and merge them into the upper half of the reference array in descending order.
for (signed_size_t i = mid, j = mid + 1, k = high; k > mid; --k) {
reference[k] =
(superKeyCompare(temporary[i]->tuple, temporary[j]->tuple, p, dim) < 0) ? temporary[i--] : temporary[j++];
}
// Wait for the child thread to finish execution.
try {
mergeFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for merge future in mergeSortReferenceDescending\n");
}
}
}
else {
// Here is Jon Benley's implementation of insertion sort from "Programming Pearls", pp. 115-116,
// Addison-Wesley, 1999, that sorts in descending order and leaves the result in the reference array.
for (signed_size_t i = low + 1; i <= high; ++i) {
auto const tmp = reference[i];
signed_size_t j;
for (j = i; j > low && superKeyCompare(reference[j - 1]->tuple, tmp->tuple, p, dim) < 0; --j) {
reference[j] = reference[j - 1];
}
reference[j] = tmp;
}
}
}
/*
* The mergeSortTemporaryAscending function recursively subdivides the reference array then
* merges the elements in ascending order and leaves the result in the temporary array.
*
* Calling parameters:
*
* reference - a KdNode** array to sort via its (x, y, z, w...) tuples array
* temporary - a KdNode** temporary array from which to copy sorted results;
* this array must be as large as the reference array
* low - the start index of the region of the reference array to sort
* high - the end index of the region of the reference array to sort
* p - the sorting partition (x, y, z, w...)
* dim - the number of dimensions
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* depth - the tree depth
*/
private:
static void mergeSortTemporaryAscending(KdNode<K,V>** const reference,
KdNode<K,V>** const temporary,
signed_size_t const low,
signed_size_t const high,
signed_size_t const p,
signed_size_t const dim,
signed_size_t const maximumSubmitDepth,
signed_size_t const depth) {
if (high - low > INSERTION_SORT_CUTOFF) {
// Avoid overflow when calculating the median.
signed_size_t const mid = low + ((high - low) >> 1);
// Subdivide the lower half of the reference array with a child thread at as many levels of subdivision as possible.
// Create the child threads as high in the subdivision hierarchy as possible for greater utilization.
// Is a child thread available to subdivide the lower half of the reference array?
if (maximumSubmitDepth < 0 || depth > maximumSubmitDepth) {
// No, recursively subdivide the lower half of the reference array with the current
// thread and return the result in the reference array in ascending order.
mergeSortReferenceAscending(reference, temporary, low, mid, p, dim, maximumSubmitDepth, depth + 1);
// Then recursively subdivide the upper half of the reference array with the current
// thread and return the result in the reference array in descending order.
mergeSortReferenceDescending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Compare the results in the reference array in ascending order and merge them into
// the temporary array in ascending order.
for (signed_size_t i = low, j = high, k = low; k <= high; ++k) {
temporary[k] =
(superKeyCompare(reference[i]->tuple, reference[j]->tuple, p, dim) < 0) ? reference[i++] : reference[j--];
}
}
else {
// Yes, a child thread is available, so recursively subdivide the lower half of the reference
// array with a child thread and return the result in the reference array in ascending order.
auto sortFuture = async(launch::async, mergeSortReferenceAscending, reference, temporary,
low, mid, p, dim, maximumSubmitDepth, depth + 1);
// And simultaneously, recursively subdivide the upper half of the reference array with
// the current thread and return the result in the reference array in descending order.
mergeSortReferenceDescending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Wait for the child thread to finish execution.
try {
sortFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for sort future in mergeSortTemporaryAscending\n");
}
// Compare the results in the reference array in ascending order with a child thread
// and merge them into the lower half of the temporary array in ascending order.
auto mergeFuture =
async(launch::async, [&] {
for (signed_size_t i = low, j = high, k = low; k <= mid; ++k) {
temporary[k] =
(superKeyCompare(reference[i]->tuple, reference[j]->tuple, p, dim) <= 0)
? reference[i++] : reference[j--];
}
});
// And simultaneously compare the results in the reference array in descending order with the
// current thread and merge them into the upper half of the temporary array in ascending order.
for (signed_size_t i = mid, j = mid + 1, k = high; k > mid; --k) {
temporary[k] =
(superKeyCompare(reference[i]->tuple, reference[j]->tuple, p, dim) > 0) ? reference[i--] : reference[j++];
}
// Wait for the child thread to finish execution.
try {
mergeFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for merge future in mergeSortTemporaryAscending\n");
}
}
}
else {
// Here is John Robinson's implementation of insertion sort that sorts in ascending order
// and leaves the result in the temporary array.
temporary[high] = reference[high];
signed_size_t i;
signed_size_t j; // MUST be signed because it can decrement to -1
for (j = high - 1; j >= low; --j) {
for (i = j; i < high; ++i) {
if (superKeyCompare(reference[j]->tuple, temporary[i + 1]->tuple, p, dim) > 0) {
temporary[i] = temporary[i + 1];
}
else {
break;
}
}
temporary[i] = reference[j];
}
}
}
/*
* The mergeSortTemporaryDescending function recursively subdivides the reference array
* then merges the elements in descending order and leaves the result in the reference array.
*
* Calling parameters:
*
* reference - a KdNode** array to sort via its (x, y, z, w...) tuples array
* temporary - a KdNode** temporary array from which to copy sorted results;
* this array must be as large as the reference array
* low - the start index of the region of the reference array to sort
* high - the end index of the region of the reference array to sort
* p - the sorting partition (x, y, z, w...)
* dim - the number of dimensions
* maximumSubmitDepth - the maximum tree depth at which a child task may be launched
* depth - the tree depth
*/
private:
static void mergeSortTemporaryDescending(KdNode<K,V>** const reference,
KdNode<K,V>** const temporary,
signed_size_t const low,
signed_size_t const high,
signed_size_t const p,
signed_size_t const dim,
signed_size_t const maximumSubmitDepth,
signed_size_t const depth) {
if (high - low > INSERTION_SORT_CUTOFF) {
// Avoid overflow when calculating the median.
signed_size_t const mid = low + ((high - low) >> 1);
// Subdivide the lower half of the reference array with a child thread at as many levels of subdivision as possible.
// Create the child threads as high in the subdivision hierarchy as possible for greater utilization.
// Is a child thread available to subdivide the lower half of the reference array?
if (maximumSubmitDepth < 0 || depth > maximumSubmitDepth) {
// No, recursively subdivide the lower half of the reference array with the current
// thread and return the result in the reference array in descending order.
mergeSortReferenceDescending(reference, temporary, low, mid, p, dim, maximumSubmitDepth, depth + 1);
// Then recursively subdivide the upper half of the reference array with the current
// thread and return the result in the reference array in ascending order.
mergeSortReferenceAscending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Compare the results in the reference array in ascending order and merge them into
// the temporary array in descending order.
for (signed_size_t i = low, j = high, k = low; k <= high; ++k) {
temporary[k] =
(superKeyCompare(reference[i]->tuple, reference[j]->tuple, p, dim) > 0) ? reference[i++] : reference[j--];
}
}
else {
// Yes, a child thread is available, so recursively subdivide the lower half of the reference
// array with a child thread and return the result in the reference array in descending order.
auto sortFuture = async(launch::async, mergeSortReferenceDescending, reference, temporary,
low, mid, p, dim, maximumSubmitDepth, depth + 1);
// And simultaneously, recursively subdivide the upper half of the reference array with
// the current thread and return the result in the reference array in ascending order.
mergeSortReferenceAscending(reference, temporary, mid + 1, high, p, dim, maximumSubmitDepth, depth + 1);
// Wait for the child thread to finish execution.
try {
sortFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for sort future in mergeSortTemporaryDescending\n");
}
// Compare the results in the reference array in ascending order with a child thread
// and merge them into the lower half of the temporary array in descending order.
auto mergeFuture =
async(launch::async, [&] {
for (signed_size_t i = low, j = high, k = low; k <= mid; ++k) {
temporary[k] =
(superKeyCompare(reference[i]->tuple, reference[j]->tuple, p, dim) >= 0)
? reference[i++] : reference[j--];
}
});
// And simultaneously compare the results in the reference array in descending order with the
// current thread and merge them into the upper half of the temporary array in descending order.
for (signed_size_t i = mid, j = mid + 1, k = high; k > mid; --k) {
temporary[k] =
(superKeyCompare(reference[i]->tuple, reference[j]->tuple, p, dim) < 0) ? reference[i--] : reference[j++];
}
// Wait for the child thread to finish execution.
try {
mergeFuture.get();
}
catch (exception const& e) {
throw runtime_error("\n\ncaught exception for merge future in mergeSortTemporaryDescending\n");
}
}
}
else {
// Here is John Robinson's implementation of insertion sort that sorts in descending order
// and leaves the result in the temporary array.
temporary[high] = reference[high];
signed_size_t i;
signed_size_t j; // MUST be signed because it can decrement to -1
for (j = high - 1; j >= low; --j) {
for (i = j; i < high; ++i) {
if (superKeyCompare(reference[j]->tuple, temporary[i + 1]->tuple, p, dim) < 0) {
temporary[i] = temporary[i + 1];
}
else {
break;
}
}
temporary[i] = reference[j];
}
}
}
/*
* The removeDuplicates function checks the validity of the merge sort and
* removes duplicates from the kdNodes array.
*
* Calling parameters:
*
* kdNodes - a KdNode** array that has been sorted via merge sort according to (x,y,z,w...) tuples
* 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(KdNode<K,V>** const kdNodes,
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) {
K const compare = superKeyCompare(kdNodes[j]->tuple, kdNodes[j - 1]->tuple, 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 kdNodes array.
kdNodes[++end] = kdNodes[j];
} else {
// Discard the jth element of the kdNodes array and prepend it to the duplicates list.
kdNodes[j]->duplicates = kdNodes[end]->duplicates;
kdNodes[end]->duplicates = kdNodes[j];
}
}
return end;
}
/*
* The swap function swaps two array elements.
*
* Calling parameters:
*
* a - KdNode** array wherein each element contains a (x,y,z,w...) tuple
* i - the index of the first element
* j - the index of the second element
*/
private:
inline
static void swap(KdNode<K,V>** const a,
signed_size_t const i,
signed_size_t const j) {
auto const t = a[i];
a[i] = a[j];
a[j] = t;
}
/*
* The following select_j_k functions select the jth of k items. Adapted
* from Chapter 4, "Linear Orderings", of Alexander Stepanov's and
* Paul McJones' "Elements of Programming", Addison-Wesley, New York, 2009.
*
* Calling parameters:
*
* a through e - KdNode* pointers to include in the selection
* p - the sorting partition (x, y, z, w...)
* dim - the number of dimensions
*
* returns a KdNode* that represents the selected KdNode
*/
private:
inline
static KdNode<K,V>* select_0_2(KdNode<K,V>* const a,
KdNode<K,V>* const b,
signed_size_t const p,
signed_size_t const dim) {
if (superKeyCompare(a->tuple, b->tuple, p, dim) < 0) {
// a < b
return a;
}
else {
// b < a
return b;
}
}
private:
inline
static KdNode<K,V>* select_1_2(KdNode<K,V>* const a,
KdNode<K,V>* const b,
signed_size_t const p,
signed_size_t const dim) {
if (superKeyCompare(a->tuple, b->tuple, p, dim) < 0) {
// a < b
return b;
}
else {
// b < a
return a;
}
}
private:
inline
static KdNode<K,V>* select_1_3_ab(KdNode<K,V>* const a,
KdNode<K,V>* const b,
KdNode<K,V>* const c,
signed_size_t const p,
signed_size_t const dim) {
if (superKeyCompare(b->tuple, c->tuple, p, dim) < 0) {
// a < b < c
return b;
}
else {
// a ? c < b
return select_1_2(a, c, p, dim);
}
}
private:
inline
static KdNode<K,V>* select_1_3(KdNode<K,V>* const a,
KdNode<K,V>* const b,
KdNode<K,V>* const c,
signed_size_t const p,
signed_size_t const dim) {
if (superKeyCompare(a->tuple, b->tuple, p, dim) < 0) {
// a < b
return select_1_3_ab(a, b, c, p, dim);
}
else {
// b < a
return select_1_3_ab(b, a, c, p, dim);
}
}
private:
inline
static KdNode<K,V>* select_1_4_ab_cd(KdNode<K,V>* const a,
KdNode<K,V>* const b,
KdNode<K,V>* const c,
KdNode<K,V>* const d,
signed_size_t const p,
signed_size_t const dim) {
if (superKeyCompare(c->tuple, a->tuple, p, dim) < 0) {
// c < a < b && a ? d so c is eliminated and a ? d
return select_0_2(a, d, p, dim);
}
else {
// a < b ? c < d so a is eliminated and b ? c
return select_0_2(b, c, p, dim);
}
}
private:
inline
static KdNode<K,V>* select_1_4_ab(KdNode<K,V>* const a,
KdNode<K,V>* const b,
KdNode<K,V>* const c,
KdNode<K,V>* const d,
signed_size_t const p,
signed_size_t const dim) {
if (superKeyCompare(c->tuple, d->tuple, p, dim) < 0) {
// a < b && c < d
return select_1_4_ab_cd(a, b, c, d, p, dim);
}
else {
// a < b && d < c
return select_1_4_ab_cd(a, b, d, c, p, dim);
}
}
private:
inline