-
Notifications
You must be signed in to change notification settings - Fork 3
/
sorting_bytecode.cpp
1867 lines (1628 loc) · 69.8 KB
/
sorting_bytecode.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
#include "sorting_bytecode.h"
#include "sorting_network.h"
#include <algorithm>
#include <assert.h>
#include <map>
#include <numeric>
#include <set>
#include <stdio.h>
using std::pair;
using std::set;
using std::vector;
struct Program {
vector<Op> ops;
void copy(const Seq &src, const Seq &dst, const char *reason) {
assert(src.len == dst.len);
ops.emplace_back();
auto &op = ops.back();
op.op = Copy;
op.s1 = src;
op.s2 = dst;
op.min_idx = 0;
op.max_idx = src.len - 1;
op.reason = reason;
}
void sort_in_place(const Seq &s, const char *reason) {
sort_in_place(s, 0, s.len - 1, reason);
}
void sort_in_place(const Seq &s, int min_idx, int max_idx, const char *reason) {
assert(min_idx >= 0 && min_idx < s.len);
assert(max_idx >= 0 && max_idx < s.len);
assert(min_idx <= max_idx);
ops.emplace_back();
auto &op = ops.back();
op.op = Sort;
op.s1 = s;
op.min_idx = min_idx;
op.max_idx = max_idx;
op.reason = reason;
}
void merge_in_place(const Seq &s1, const Seq &s2, const char *reason) {
merge_in_place(s1, s2, 0, s1.len + s2.len - 1, reason);
}
void merge_in_place(const Seq &s1, const Seq &s2, int min_idx, int max_idx, const char *reason) {
ops.emplace_back();
auto &op = ops.back();
op.op = Merge;
op.s1 = s1;
op.s2 = s2;
op.min_idx = min_idx;
op.max_idx = max_idx;
op.reason = reason;
}
void print(const Seq &s, const char *reason) {
ops.emplace_back();
auto &op = ops.back();
op.op = Print;
op.s1 = s;
op.min_idx = 0;
op.max_idx = op.s1.len - 1;
op.reason = reason;
}
void assert_sorted(const Seq &s, const char *reason) {
assert_sorted(s, 0, s.len - 1, reason);
}
void assert_sorted(const Seq &s, int min_idx, int max_idx, const char *reason) {
assert(min_idx >= 0 && min_idx < s.len);
assert(max_idx >= 0 && max_idx < s.len);
assert(min_idx <= max_idx);
ops.emplace_back();
auto &op = ops.back();
op.op = AssertSorted;
op.s1 = s;
op.min_idx = min_idx;
op.max_idx = max_idx;
op.reason = reason;
}
};
void Op::print() const {
if (op == Sort) {
printf("sort(reason = %s\n"
" min_idx = %d, max_idx = %d, x = %d, dx = %d, len = %d)\n",
reason, min_idx, max_idx, s1.x, s1.dx, s1.len);
} else if (op == AssertSorted) {
printf("assert_sorted(reason = %s\n"
" min_idx = %d, max_idx = %d, x = %d, dx = %d, len = %d)\n",
reason, min_idx, max_idx, s1.x, s1.dx, s1.len);
} else if (op == Print) {
printf("print(reason = %s\n"
" min_idx = %d, max_idx = %d, x = %d, dx = %d, len = %d)\n",
reason, min_idx, max_idx, s1.x, s1.dx, s1.len);
} else if (op == Merge) {
printf("merge(reason = %s\n"
" min_idx = %d, max_idx = %d, \n"
" s1.x = %d, s1.dx = %d, s1.len = %d, \n"
" s2.x = %d, s2.dx = %d, s2.len = %d)\n",
reason,
min_idx, max_idx,
s1.x, s1.dx, s1.len,
s2.x, s2.dx, s2.len);
} else if (op == Copy) {
printf("copy(reason = %s\n"
" min_idx = %d, max_idx = %d, \n"
" s1.x = %d, s1.dx = %d, s1.len = %d, \n"
" s2.x = %d, s2.dx = %d, s2.len = %d)\n",
reason,
min_idx, max_idx,
s1.x, s1.dx, s1.len,
s2.x, s2.dx, s2.len);
} else {
assert(false && "Bad op");
}
}
vector<Op> sort_2d_naive(int w, int h, int min_idx, int max_idx) {
// Just sort each row, then merge the rows using a Batcher
// even-odd merge sort across y, where each link is interpreted as
// a batcher merge of two rows.
Program result;
for (int y = 0; y < h; y++) {
result.sort_in_place(Seq{y * w, 1, w}, "Sort row");
}
for (const auto &p : pairwise_sort(h)) {
result.merge_in_place(Seq{p.first * w, 1, w},
Seq{p.second * w, 1, w},
"Merge rows");
}
return result.ops;
}
vector<Op> sort_1d(int w, int min_idx, int max_idx) {
Program result;
result.sort_in_place(Seq{0, 1, w}, min_idx, max_idx, "Sort");
return result.ops;
}
vector<Op> sort_pair(int w) {
Program result;
Seq a{0, 1, w}, b{w, 1, w}, c{2 * w, 1, w}, d{3 * w, 1, w};
result.sort_in_place(a, "sort_pair: Sort first half");
result.copy(a, c, "sort_pair: Copying first half");
result.sort_in_place(b, "sort_pair: Sort second half");
result.copy(b, d, "sort_pair: Copying second half");
result.merge_in_place(c, d, "sort_pair: Merge sorted halves");
return result.ops;
}
vector<Op> tiled_median_2d(int w, int h, int tw, int th, bool col_major_core) {
// The size of the intersection of the supports. We call this the
// "core".
int core_w = w - tw + 1;
int core_h = h - th + 1;
// Each output is going to use some number of values from outside
// the core unique(ish) to that output.
int values_inside_core = core_w * core_h;
int values_outside_core = w * h - values_inside_core;
// To compute the median, we'll sort the values outside the core
// unique to this output, then sort the values inside the core
// (this work is shared). Then we merge those two lists and return
// the median. The final merge is between values_outside_core and
// values_inside_core.
// When taking a median of two sorted lists of size n and m, where
// n < m, you only need the middle-most n + 1 values from the list
// of size m. Everything outside of that is too small or too large
// to possibly be the median of the sorted combination.
// For example: If we have n == 5 and m == 20, then the combined
// list is of size 25, so the median of the combined list is
// greater than 12 things, less than 12 things, and equal to one
// thing. Anything in the list of size m that's already greater
// than 13 things can be excluded from consideration. This lops
// off the last 7 elements (indices 13, 14, 15, 16, 17, 18, 19). A
// similar argument lops off the first 7 elements, leaving us with
// 6 elements remaining (7, 8, 9, 10, 11, 12).
int min_core_idx = 0;
int max_core_idx = core_w * core_h - 1;
while (max_core_idx - min_core_idx > values_outside_core) {
min_core_idx++;
max_core_idx--;
}
max_core_idx = std::min(max_core_idx, values_inside_core - 1);
min_core_idx = std::max(min_core_idx, 0);
assert(min_core_idx <= max_core_idx);
int total_w = w + (tw - 1);
int total_h = h + (th - 1);
int output_start = total_w * total_h;
// First do the shared work of sorting the values inside the
// core.
// In theory if there are more values outside the core than
// inside, we should just do a conventional mergesort. However, in
// that case the total amount of work to do inside the core is
// negligible compared to total runtime, so it doesn't matter.
Program result;
if (!col_major_core) {
//printf("Calling merge_cols_2d(%d, %d, %d, %d, %d)\n",
//core_w, core_h, min_core_idx, max_core_idx, output_start);
result.ops = merge_cols_2d(core_w, core_h, min_core_idx, max_core_idx, output_start);
} else {
//printf("Calling merge_rows_2d(%d, %d, %d, %d)\n",
//core_h, core_w, min_core_idx, max_core_idx);
result.ops = merge_rows_2d(core_h, core_w, min_core_idx, max_core_idx);
}
// int peak_while_sorting_core = compute_working_memory(result.ops);
// printf("Peak memory while sorting core: %d\n", peak_while_sorting_core);
Seq sorted_core;
sorted_core.x = 0;
sorted_core.dx = 1;
sorted_core.len = max_core_idx - min_core_idx + 1;
result.print(sorted_core, "Sorted core");
if (tw == 1 && th == 1) {
// Untiled.
// Copy the median to the expected output location
result.copy(Seq{sorted_core.x, 1, 1},
Seq{output_start, 1, 1},
"Copying the result to the expected location");
return result.ops;
}
// Unpack the rest of the memory layout (see the comment in the header file)
int extra_cols_start = core_w * core_h;
int num_extra_cols = 2 * (tw - 1);
int extra_rows_start = extra_cols_start + core_h * num_extra_cols;
int num_extra_rows = 2 * (th - 1);
int corners_start = extra_rows_start + core_w * num_extra_rows;
assert(corners_start + num_extra_cols * num_extra_rows == output_start);
// Sort all the extra rows in-place
for (int r = 0; r < num_extra_rows; r++) {
Seq row;
row.x = extra_rows_start + r * core_w;
row.dx = 1;
row.len = core_w;
result.sort_in_place(row, "Sorting extra row");
}
// TODO: We could find the optimal order in which to merge things
// using a directed Steiner tree algorithm.
int row_groups_start = output_start + tw * th;
int row_group_size = (th - 1) * core_w;
int num_row_groups = th;
auto merge_rows_net = pairwise_sort(th - 1);
auto merge_cols_net = pairwise_sort(tw - 1);
// Gather and merge each window of th - 1 consecutive sorted rows
if (th > 1) {
for (int y = 0; y < th; y++) {
// TODO: the windows overlap, so there's shared work here we
// can still exploit (e.g. consider aligned pairs starting at
// idx 1).
// This is an im2col-like operation where we just gather
// the values under the stencil footprint.
Seq row_group{row_groups_start + y * row_group_size, 1, row_group_size};
result.copy(Seq{extra_rows_start + y * core_w, 1, row_group_size},
row_group,
"Copy group of extra rows");
// Now use a sorting network of size th - 1 to drive a series
// of merge operations to sort the row group.
for (const auto &p : merge_rows_net) {
int x1 = row_groups_start + y * row_group_size + p.first * core_w;
int x2 = row_groups_start + y * row_group_size + p.second * core_w;
result.merge_in_place(Seq{x1, 1, core_w},
Seq{x2, 1, core_w},
"Merge extra row group");
}
// Assert sorted. Not just for debugging - it also lets the op limiter knows this is now sorted
result.assert_sorted(row_group, "Assert row group sorted");
result.print(row_group, "Sorted row group");
if (tw == 1) {
// merge the in sorted core and finish
Seq sorted_core_copy{row_group.x + row_group.len, 1, sorted_core.len};
result.copy(sorted_core, sorted_core_copy,
"Copy sorted core");
int median_idx = (row_group.len + sorted_core.len) / 2;
result.merge_in_place(row_group, sorted_core_copy,
median_idx, median_idx,
"Merge row group with sorted core");
row_group.len += sorted_core.len;
result.print(row_group, "Median taken with sorted core");
// Copy the median back to the expected output location
result.copy(Seq{row_group.x + median_idx, 1, 1},
Seq{output_start + y, 1, 1},
"Copying the result to the expected location");
}
}
}
if (tw == 1) {
return result.ops;
}
int col_groups_start = row_groups_start + num_row_groups * row_group_size;
int col_group_size = (tw - 1) * core_h;
/*
printf("sorted core ends at %d\n"
"extra_cols_start: %d\n"
"extra_rows_start: %d\n"
"corners_start: %d\n"
"row_groups_start: %d\n"
"col_groups_start %d\n",
sorted_core.len,
extra_cols_start,
extra_rows_start,
corners_start,
row_groups_start,
col_groups_start);
*/
result.print(Seq{row_groups_start, 1, num_row_groups * row_group_size},
"All row groups before sorting col groups");
col_group_size += sorted_core.len;
// When taking a median by merging a bunch of sorted lists, at
// each merge step you can ignore everything except for the
// middle-most n + 1, where n is all the number of elements
// still left to handle after this merge.
// The elements not yet merged here are the missing rows/corners
int elements_remaining_after_merge = w * (h - core_h);
int elements_to_discard_after_this_merge = col_group_size - (elements_remaining_after_merge + 1);
int col_merge_min_idx = elements_to_discard_after_this_merge / 2;
int col_merge_max_idx = col_group_size - 1 - col_merge_min_idx;
int scratch_start = col_groups_start + col_merge_max_idx + 1;
//printf("Scratch start: %d\n", scratch_start);
// Then we enter the loop over the tile
for (int x = 0; x < tw; x++) {
// Merge the sorted core with the appropriate additional columns for this x coord within the tile
{
// This is an im2col-like operation where we just gather
// the values under the stencil footprint.
int cols_only_size = (tw - 1) * core_h;
Seq col_group{col_groups_start, 1, cols_only_size};
result.copy(Seq{extra_cols_start + x * core_h, 1, cols_only_size},
col_group,
"Copy group of extra cols");
// Now use a sorting network of size th - 1 to drive a series
// of merge operations to sort the col group.
for (const auto &p : merge_cols_net) {
int x1 = col_groups_start + p.first * core_h;
int x2 = col_groups_start + p.second * core_h;
result.merge_in_place(Seq{x1, 1, core_h},
Seq{x2, 1, core_h},
"Merge extra col group");
}
// Merge in the sorted core too
Seq sorted_core_dst{col_groups_start + (tw - 1) * core_h, 1, sorted_core.len};
result.copy(sorted_core, sorted_core_dst,
"Copying sorted core onto the end of the sorted col group");
result.merge_in_place(col_group, sorted_core_dst,
col_merge_min_idx, col_merge_max_idx,
"Merging col group with sorted core");
assert(col_group.x + col_group.len == sorted_core_dst.x);
col_group.len += sorted_core.len;
if (th == 1) {
// We're actually done with this x
assert(col_merge_min_idx == col_merge_max_idx);
// Copy the median back to the expected output location
result.copy(Seq{col_group.x + col_merge_min_idx, 1, 1},
Seq{output_start + x, 1, 1},
"Copying the result to the expected location");
} else {
// Make sure the op limiter knows this is now sorted
result.assert_sorted(col_group, col_merge_min_idx, col_merge_max_idx,
"Assert col group sorted");
result.print(col_group, "Sorted col group");
}
}
if (tw == 1) {
continue;
}
for (int y = 0; y < th; y++) {
Seq extra_cols, extra_rows;
vector<Seq> corners;
extra_rows.x = row_groups_start + y * row_group_size;
extra_rows.dx = 1;
extra_rows.len = row_group_size;
// Grab the sorted columns we need for this tile element
// (TODO: there is shared work here to exploit, at the
// cost of more memory).
extra_cols.x = col_groups_start + col_merge_min_idx;
extra_cols.dx = 1;
extra_cols.len = col_merge_max_idx - col_merge_min_idx + 1;
for (int r = y; r < y + th - 1; r++) {
// Also grab the corner sequences. They form a little
// square num_extra_cols wide and num_extra_rows
// high. We want a (tw - 1) x (th - 1) crop from inside of it
// starting at position x, y.
Seq corner{corners_start + r * num_extra_cols + x, 1, tw - 1};
corners.push_back(corner);
result.print(corner, "Row of corners");
}
// We can't mutate these things in-place, because
// different pixels in the tile need different subsets of
// them. The scratch space is currently entirely free
// though, so we can start by copying stuff over there.
// TODO: for y == th - 1 we can clobber the
// extra_rows. For x == tw - 1 we can clobber the extra
// cols.
vector<Seq *> to_copy;
if (y < th - 1) {
// For the final value of y we can just clobber the
// extra_cols in place, as this is their last use.
to_copy.push_back(&extra_cols);
}
to_copy.push_back(&extra_rows);
for (auto &c : corners) {
to_copy.push_back(&c);
}
int idx = scratch_start;
for (Seq *s : to_copy) {
Seq dst{idx, 1, s->len};
result.copy(*s, dst,
"Assembling pieces unique to this output in scratch space");
*s = dst;
idx += s->len;
}
{
// Consider a graph where the nodes are all the
// different intersections of subsets of the
// input. There are edges that go from an
// intersection of many things to an intersection
// of a subset of them. These edges can be
// traversed by sorting in the newly-included
// elements. Ultimately we want to reach the nodes
// with one thing in the intersection. We start at
// the intersection of everything. We want a
// spanning tree rooted at the intersection of
// everything that hits all our leaves. This is
// the "Directed Steiner Tree Problem". It's
// NP-hard. We can probably take the minimum
// spanning tree and delete the less useful nodes,
// and repeat? Or we could iterate over all
// possible spanning trees? Or maybe a structure
// will jump out at us.
// Sort the corners
Seq all_corners = corners[0];
all_corners.len = idx - all_corners.x;
assert(all_corners.len == (tw - 1) * (th - 1));
if (all_corners.len > 1) {
result.sort_in_place(all_corners, "Sorting the corner pieces unique to this output");
result.print(all_corners, "Sorted corners");
}
// We now have three groups of things to take the
// median of. Surprisingly, it's best to merge in
// the smallest thing (for us, probably the
// corners) last.
// First ensure no one thing is larger than the
// other two combined. If that's the case it
// should have been pruned down when it was created.
/*
printf("extra_rows.x = %d, extra_cols.x = %d, all_corners.x = %d\n",
extra_rows.x, extra_cols.x, all_corners.x);
*/
assert(all_corners.len <= extra_rows.len + extra_cols.len + 1);
assert(extra_rows.len <= all_corners.len + extra_cols.len + 1);
assert(extra_cols.len <= all_corners.len + extra_rows.len + 1);
// Merge rows with cols
int rows_and_cols_min_idx = 0;
int rows_and_cols_max_idx = extra_rows.len + extra_cols.len - 1;
// Prune it down to the middle all_corners.len + 1 values
while (rows_and_cols_max_idx - rows_and_cols_min_idx + 1 > all_corners.len + 1) {
rows_and_cols_min_idx++;
rows_and_cols_max_idx--;
}
result.merge_in_place(extra_cols, extra_rows,
rows_and_cols_min_idx,
rows_and_cols_max_idx,
"Merging the sorted rows into the sorted cols and core");
// Grow the extra_cols seq to include the merged-in rows
assert(extra_cols.x + extra_cols.len == extra_rows.x);
extra_cols.x += rows_and_cols_min_idx;
extra_cols.len = all_corners.len + 1;
// Now take the median with the corners, if there are any.
result.merge_in_place(extra_cols, all_corners,
all_corners.len, all_corners.len,
"Merging the sorted corners into the sorted extra rows");
// Copy the median back to the expected output location
result.copy(Seq{extra_cols.x + all_corners.len, 1, 1},
Seq{output_start + y * tw + x, 1, 1},
"Copying the result to the expected location");
}
}
}
return result.ops;
}
vector<Op> merge_rows_2d(int w, int h, int min_idx, int max_idx) {
Program result;
// Which rows of the output do we want?
int min_row_idx = min_idx / w;
int max_row_idx = max_idx / w;
auto merge_network = pairwise_sort(h, min_row_idx, max_row_idx, false);
if (w % 2 == 0) {
int hw = w / 2;
assert(merge_network.size() <= pairwise_sort(2 * h, min_idx / hw, max_idx / hw, true).size() &&
"Should have used a pairwise network on half-rows");
}
for (auto p : merge_network) {
result.merge_in_place(Seq{p.first * w, 1, w},
Seq{p.second * w, 1, w},
"Merge rows");
}
if (min_idx != 0) {
result.copy(Seq{min_idx, 1, max_idx - min_idx + 1},
Seq{0, 1, max_idx - min_idx + 1},
"Copying merge_rows_2d output to expected location");
}
return result.ops;
}
vector<Op> merge_cols_2d(int w, int h, int min_idx, int max_idx, int scratch_start) {
assert(min_idx <= max_idx);
Program result;
// After sorting horizontally, a bunch of values are no longer
// going to be in min_idx / max_idx and so may as well be negative
// or positive infinity. We'll maintain a mask that specifies the
// state of each site.
enum State {
Valid = 0,
NegInf = 1,
PosInf = 2,
};
// We'll also compute two thresholds for detecting when a value
// falls into one of these states.
// In the final list, the value stored at max_idx is greater than
// or equal to max_idx + 1 total values in the list (including
// itself). Therefore, if something is greater than or equal to
// more than that many total values in the input, it may as well
// be positive infinity, because it's going to land in the final
// last after max_idx.
// If something is >= more than this many values, it may as well
// be positive infinity.
int max_threshold = max_idx + 1;
// If a value is <= more than this many other values, it may as
// well be negative infinity.
int min_threshold = w * h - min_idx;
// Initially everything is valid (we assume the vertical sort
// alone isn't enough to render anything +/- infinity).
vector<State> state(w * h, Valid);
// Sort the rows. Note that after doing this, the square is still
// sorted along the columns!
for (int y = 0; y < h; y++) {
int num_pos_inf = 0, num_neg_inf = 0;
for (int x = 0; x < w; x++) {
// After sorting, how many values in the square is this
// value definitely greater than or equal to (including itself).
// Answer: Everything above and to the left.
int gt = (x + 1) * (y + 1);
if (gt > max_threshold) {
state[x + y * w] = PosInf;
num_pos_inf++;
}
// We're less than everything below and to the right.
int lt = (w - x) * (h - y);
if (lt > min_threshold) {
state[x + y * w] = NegInf;
num_neg_inf++;
}
}
result.sort_in_place(Seq{y * w, 1, w},
num_neg_inf,
w - 1 - num_pos_inf,
"Sort along rows");
}
if (0) {
printf("State after horizontal sort:\n");
int valids = 0;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
switch (state[y * w + x]) {
case Valid:
valids++;
printf(".");
break;
case PosInf:
printf("^");
break;
case NegInf:
printf("_");
break;
}
}
printf("\n");
}
printf("%d valid sites\n", valids);
}
// Sort diagonally up and to the right. It will still be sorted
// horizontally and vertically after doing this, though the proof
// only works if the square is taller than it is wide.
bool transposed = h < w;
int x_stride = 1, y_stride = w;
if (transposed) {
std::swap(w, h);
std::swap(x_stride, y_stride);
}
struct Diagonal {
// Current location in memory
Seq seq;
// Whether or not it's currently sorted
bool sorted = false;
// The 2d coordinates it represents
vector<pair<int, int>> sites;
};
vector<Diagonal> diagonals;
vector<State> state_after = state;
int scratch_cursor = scratch_start;
int num_diagonals = 0, num_sorted_diagonals = 0;
int neg_infs_in_final_sort = 0, pos_infs_in_final_sort = 0;
// Figure out the order in which to visit the x coordinates
vector<int> x_coords;
for (int x = -h + 1; x < w; x++) {
x_coords.emplace_back(x);
}
std::sort(x_coords.begin(), x_coords.end(), [=](int x1, int x2) {
int y1_start = std::min(x1, 0) + h - 1;
int y1_end = std::max(x1 + h - w, 0);
int len1 = y1_start - y1_end;
int y2_start = std::min(x2, 0) + h - 1;
int y2_end = std::max(x2 + h - w, 0);
int len2 = y2_start - y2_end;
return (len1 > len2);
});
for (int x_start : x_coords) {
//for (int x_start = -h + 1; x_start < w; x_start++) {
int y_start = std::min(x_start, 0) + h - 1;
int y_end = std::max(x_start + h - w, 0);
assert(y_end <= y_start);
int idx = 0;
int min_input_idx = std::max(w, h);
int max_input_idx = -1;
int min_output_idx = std::max(w, h);
int max_output_idx = -1;
for (int y = y_start; y >= y_end; y--) {
int x = x_start + (h - 1 - y);
assert(x >= 0 && x < w && y >= 0 && y < h);
// Track the min and max valid index along this diagonal
// to see what we'll need to sort.
if (state[x * x_stride + y * y_stride] == Valid) {
min_input_idx = std::min(min_input_idx, idx);
max_input_idx = std::max(max_input_idx, idx);
}
// After sorting, this value may be out-of-range. It's
// less than everything in a wide fan to the right, and
// greater than everything in a wide fan to the left. For
// for the center value in a 7x7 grid the relations look
// like:
// >>>>..<
// >>>>.<<
// >>>><<<
// >>>=<<<
// >>><<<<
// >>.<<<<
// >..<<<<
int ge = 0, le = 0;
for (int y2 = 0; y2 < h; y2++) {
for (int x2 = 0; x2 < w; x2++) {
if (x <= x2 && x + y <= x2 + y2) {
le++;
}
if (x2 <= x && x2 + y2 <= x + y) {
ge++;
}
// Not an else-if because there's a single value where both are true (x == x2, y == y2)
}
}
if (le > min_threshold) {
state_after[x * x_stride + y * y_stride] = NegInf;
} else if (ge > max_threshold) {
state_after[x * x_stride + y * y_stride] = PosInf;
} else {
min_output_idx = std::min(min_output_idx, idx);
max_output_idx = std::max(max_output_idx, idx);
}
idx++;
}
if (min_input_idx <= max_input_idx) {
int x = x_start + (h - 1 - y_start);
diagonals.emplace_back();
auto &diag = diagonals.back();
diag.seq.x = (x + min_input_idx) * x_stride + (y_start - min_input_idx) * y_stride;
diag.seq.dx = x_stride - y_stride;
diag.seq.len = max_input_idx - min_input_idx + 1;
for (int i = min_input_idx; i <= max_input_idx; i++) {
diag.sites.emplace_back(x + i, y_start - i);
}
// Output indices are relative to the starting input index
min_output_idx -= min_input_idx;
max_output_idx -= min_input_idx;
// Because of the hyperbolic slice we've cut out of the
// valid region, some diagonals have a segment of pos_inf
// or neg_inf in the middle that we can excise before
// copying.
int neg_inf_start = diag.seq.len;
int neg_inf_end = -1;
int pos_inf_start = diag.seq.len;
int pos_inf_end = -1;
assert(state[diag.seq.x] == Valid);
assert(state[diag.seq.x + (diag.seq.len - 1) * diag.seq.dx] == Valid);
for (int i = 0; i < diag.seq.len; i++) {
auto v = state[diag.seq.x + i * diag.seq.dx];
if (v == NegInf) {
neg_inf_start = std::min(neg_inf_start, i);
neg_inf_end = std::max(neg_inf_end, i);
}
if (v == PosInf) {
pos_inf_start = std::min(pos_inf_start, i);
pos_inf_end = std::max(pos_inf_end, i);
}
}
// Copy the diagonal into scratch space
if (pos_inf_start > pos_inf_end && neg_inf_start > neg_inf_end) {
// One long diagonal
Seq diag_dst{scratch_cursor, 1, diag.seq.len};
result.copy(diag.seq, diag_dst, "Copying diagonal to scratch space");
diag.seq = diag_dst;
num_diagonals++;
} else if (pos_inf_start <= pos_inf_end ||
neg_inf_start <= neg_inf_end) {
int inf_start, inf_end;
if (pos_inf_start <= pos_inf_end) {
inf_start = pos_inf_start;
inf_end = pos_inf_end;
} else {
inf_start = neg_inf_start;
inf_end = neg_inf_end;
// If we only wanted some region of this diagonal,
// we should adjust it according to the negative
// infinities we just discarded on the left.
int num_neg_inf = neg_inf_end - neg_inf_start + 1;
min_output_idx -= num_neg_inf;
max_output_idx -= num_neg_inf;
}
// There's a blob of positive or negative infinities
// in the middle. Copy the regions around it.
Seq diag1_src = diag.seq;
Seq diag2_src = diag.seq;
diag1_src.len = inf_start;
diag2_src.x += (inf_end + 1) * diag2_src.dx;
diag2_src.len = diag.seq.len - inf_end - 1;
Seq diag1_dst{scratch_cursor, 1, diag1_src.len};
Seq diag2_dst{scratch_cursor + inf_start, 1, diag2_src.len};
result.copy(diag1_src, diag1_dst, "Copying start of diagonal to scratch space");
result.copy(diag2_src, diag2_dst, "Copying end of diagonal to scratch space");
// Update diag to refer to its new location
diag.seq = diag1_dst;
diag.seq.len = diag1_dst.len + diag2_dst.len;
vector<pair<int, int>> new_coords;
for (int i = 0; i < diag1_dst.len; i++) {
new_coords.push_back(diag.sites[i]);
}
for (int i = 0; i < diag2_dst.len; i++) {
new_coords.push_back(diag.sites[inf_end + 1 + i]);
}
diag.sites.swap(new_coords);
num_diagonals++;
}
// 2) Sort it in-place. There's no point doing this if we
// don't get pruning from it, because we're just going to
// re-sort the whole thing anyway.
int pruned_len = max_output_idx - min_output_idx + 1;
if (pruned_len < diag.seq.len) {
result.sort_in_place(diag.seq, min_output_idx, max_output_idx, "Sorting diagonal");
num_sorted_diagonals++;
// Copy the unpruned region leftwards if necessary
diag.seq.len = pruned_len;
if (min_output_idx) {
result.copy(Seq{diag.seq.x + min_output_idx, 1, pruned_len},
diag.seq,
"Compacting sorted diagonal");
}
diag.sorted = true;
} else {
// We may have willingly included things that are
// known to not be the median in order to do fewer
// sorting ops total.
neg_infs_in_final_sort += min_output_idx;
pos_infs_in_final_sort += diag.seq.len - 1 - max_output_idx;
diag.sorted = false;
}
scratch_cursor += diag.seq.len;
}
}
if (0) {
printf("State after diagonal sort:\n");
int valids = 0;
for (int y = 0; y < h; y++) {
for (int x = 0; x < w; x++) {
switch (state_after[y * w + x]) {
case Valid:
valids++;
printf(".");
break;
case PosInf:
printf("^");
break;
case NegInf:
printf("_");
break;
}
}
printf("\n");
}
printf("%d valid sites\n", valids);
}
// Count how many Infs vs Valids we ended up with, and assert that
// every value is accounted for
int num_pos_inf = 0, num_neg_inf = 0, num_valid = 0;
for (auto s : state_after) {
if (s == PosInf) {
num_pos_inf++;
} else if (s == NegInf) {
num_neg_inf++;
} else if (s == Valid) {
num_valid++;
} else {
assert(false && "bad state");
}
}
assert(scratch_cursor - scratch_start == neg_infs_in_final_sort + pos_infs_in_final_sort + num_valid);
if ((num_diagonals > 1 || // There are multiple diagonals to merge
num_sorted_diagonals == 0) && // There's only one diagonal, but it's not sorted
scratch_cursor > scratch_start + 1) { // We have more than one value to worry about
for (auto &d : diagonals) {
if (d.sorted) {
// Make sure the limiter knows this span is already sorted
result.assert_sorted(d.seq, "Assert diagonal sub-component is already sorted");
// TODO: This final sort is somewhat wasteful because
// there are already large sorted sequences within
// it. Try a merge sort instead?
}
}
int final_min_idx = min_idx - num_neg_inf + neg_infs_in_final_sort;
int final_max_idx = max_idx - num_neg_inf + neg_infs_in_final_sort;
// Ignore the fact that (some of) the diagonals are already
// sorted, and just do a full sort of their concatenation
Seq merged{scratch_start, 1, scratch_cursor - scratch_start};
result.sort_in_place(merged,
final_min_idx,
final_max_idx,
"Final sort of concatenated diagonals");
/*
// First sort every contiguous span of unsorted ones
Seq pending{0, 1, 0};
vector<Seq> sorted_diagonals;
for (size_t i = 0; i < diagonals.size(); i++) {
if (diagonals[i].sorted && diagonals[i].seq.len > 8) {
if (pending.len) {
// TODO: min_idx / max_idx
result.sort_in_place(pending, "Sorting section of diagonals");
sorted_diagonals.push_back(pending);
pending.len = 0;
}
sorted_diagonals.push_back(diagonals[i].seq);
} else {
if (!pending.len) {
pending.x = diagonals[i].seq.x;
}
pending.len += diagonals[i].seq.len;
}
}
if (pending.len) {
result.sort_in_place(pending, "Sorting section of diagonals");
sorted_diagonals.push_back(pending);
pending.len = 0;
}
// Then iteratively merge the smallest pair
while (sorted_diagonals.size() > 1) {
if (sorted_diagonals.size() == 2) {
result.merge_in_place(sorted_diagonals[0],
sorted_diagonals[1],
final_min_idx, final_max_idx,
"Merging two sorted diagonals");
break;
} else {