-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathsuffix_array.hpp
More file actions
1513 lines (1279 loc) · 55.7 KB
/
suffix_array.hpp
File metadata and controls
1513 lines (1279 loc) · 55.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2015 Georgia Institute of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef SUFFIX_ARRAY_HPP
#define SUFFIX_ARRAY_HPP
#include <vector>
#include <iostream>
#include "alphabet.hpp"
#include "kmer.hpp"
#include "par_rmq.hpp"
#include "shifting.hpp"
#include "bucketing.hpp"
#include "stringset.hpp"
#include "bulk_permute.hpp"
#include "bulk_rma.hpp"
#include "idxsort.hpp"
#include <mxx/datatypes.hpp>
#include <mxx/shift.hpp>
#include <mxx/partition.hpp>
#include <mxx/sort.hpp>
#include <mxx/collective.hpp>
#include <mxx/timer.hpp>
#include <mxx/file.hpp>
#include <prettyprint.hpp>
/*********************************************************************
* Macros for timing sections in the code *
*********************************************************************/
// TODO: use a proper logging engine!
#define INFO(msg) {std::cerr << msg << std::endl;}
//#define INFO(msg) {}
#define SAC_ENABLE_TIMER 1
#if SAC_ENABLE_TIMER
#define SAC_TIMER_START() mxx::section_timer timer(std::cerr, this->comm);
#define SAC_TIMER_END_SECTION(str) timer.end_section(str);
#define SAC_TIMER_LOOP_START() mxx::section_timer looptimer(std::cerr, this->comm);
#define SAC_TIMER_END_LOOP_SECTION(iter, str) looptimer.end_section(str);
#else
#define SAC_TIMER_START()
#define SAC_TIMER_END_SECTION(str)
#define SAC_TIMER_LOOP_START()
#define SAC_TIMER_END_LOOP_SECTION(iter, str)
#endif
template <typename T>
struct TwoBSA {
T B1;
T B2;
T SA;
inline bool operator<(const TwoBSA& other) const
{
// tuple comparison of (B1, B2) with precedence to B1
return (this->B1 < other.B1)
|| (this->B1 == other.B1 && this->B2 < other.B2);
}
};
template <typename T>
std::ostream& operator<<(std::ostream& os, const TwoBSA<T>& t){
return os << "{" << t.SA << "," << t.B1 << "," << t.B2 << "}";
}
// specialize MPI datatype (mxx)
namespace mxx {
template <typename T>
class datatype_builder<TwoBSA<T> > : public datatype_contiguous<T, 3> {};
}
// pair of two same element
template <typename T>
struct mypair
{
T first;
T second;
};
// partial template specialization for mypair
namespace mxx {
template <typename T>
class datatype_builder<mypair<T> > : public datatype_contiguous<T, 2> {};
}
// TODO: template by char_type and alphabet type, sa index type, LCP index type
// and build multiple subclasses based on common underlying templated
// implementation?
// appends .uintXX or .intXX based on size of the type
// e.g. basename.uint32, basename.int16 etc
template <typename T>
std::string get_int_ext() {
static_assert(std::is_integral<T>::value && !std::is_same<T,bool>::value, "This function works only for integral types excluding bool");
std::string ext = "";
if (std::is_unsigned<T>::value) {
ext += "u";
}
ext += "int";
ext += std::to_string(sizeof(T)*8);
return ext;
}
template <typename T>
void write_dist_int_array(const std::string& basename, const std::vector<T>& vec, const mxx::comm& comm) {
static_assert(std::is_integral<T>::value && !std::is_same<T,bool>::value, "This function works only for integral types excluding bool");
//std::string type_ext = get_int_ext<T>();
mxx::coll_file f(basename, comm);
f.open(MPI_MODE_WRONLY | MPI_MODE_CREATE);
f.write_ordered(vec.data(), vec.size());
}
// how to distinguish between types?
template <typename T>
std::vector<T> read_dist_int_array(const std::string& filename, const mxx::comm& comm) {
static_assert(std::is_integral<T>::value && !std::is_same<T,bool>::value, "This function works only for integral types excluding bool");
std::ifstream f(filename, std::ios::binary | std::ios::ate);
size_t n = f.tellg() / sizeof(T);
mxx::blk_dist d(n, comm);
// Use C++ fileIO if local size is larger than INT_MAX
// because some MPI implementations will silently fail to load the input
// file otherwise
std::vector<T> data(d.local_size());
if ((n + comm.size())*sizeof(T) / comm.size() >= std::numeric_limits<int>::max()) {
if (comm.rank() == 0) {
std::cerr << "[WARNING] local size is larger than INT_MAX, using C++ file IO instead of MPI IO" << std::endl;
}
f.seekg(d.eprefix_size(), std::ios::beg);
f.read((char*)data.data(), d.local_size()*sizeof(T));
} else {
// use MPI File IO
f.close();
mxx::coll_file f2(filename, comm);
f2.open(MPI_MODE_RDONLY);
f2.read_ordered(d.local_size(), data.data());
}
return data;
}
// distributed suffix array
template <typename char_t, typename index_t = std::size_t, bool _CONSTRUCT_LCP = false, bool _CONSTRUCT_LC = false>
class suffix_array {
private:
public:
suffix_array(const mxx::comm& _comm) : comm(_comm.copy()) {
}
virtual ~suffix_array() {}
public:
/// The global size of the input string and suffix array
std::size_t n;
/// The local size of the input string and suffix array
/// is either floor(n/p) or ceil(n/p) and based on a equal block
/// distribution
std::size_t local_size;
/// The MPI communicator to use for the parallel suffix array construction
mxx::comm comm;
/// number of processes = size of the communicator
int p;
// The block decomposition for the suffix array
mxx::blk_dist part;
//using char_type = typename std::iterator_traits<InputIterator>::value_type;
using char_type = char_t;
//using alphabet_type = alphabet<char_type>;
using alphabet_type = typename alphabet_helper<char_type>::alphabet_type;
/// alphabet of underlying text
alphabet_type alpha;
/// The local suffix array
std::vector<index_t> local_SA;
/// The local inverse suffix array
std::vector<index_t> local_B;
/// The local LCP array (remains empty if no LCP is constructed)
std::vector<index_t> local_LCP;
// left-branching character (remains empty if `_CONSTRUCT_LC = false`)
std::vector<char_t> local_Lc;
public:
void init_size(size_t lsize) {
local_size = lsize;
n = mxx::allreduce(local_size, this->comm);
// get distribution
part = mxx::blk_dist(n, comm.size(), comm.rank());
p = comm.size();
// assert a block decomposition
if (part.local_size() != local_size)
throw std::runtime_error("The input string must be equally block decomposed accross all MPI processes.");
}
// store to file using parallel IO
void write(const std::string& basename) {
write_dist_int_array(basename + ".sa", local_SA, comm);
if (_CONSTRUCT_LCP) {
write_dist_int_array(basename + ".lcp", local_LCP, comm);
}
if (_CONSTRUCT_LC) {
write_dist_int_array(basename + ".lc", local_Lc, comm);
}
alpha.write(basename + ".alpha", comm);
}
// load from file using parallel IO
void read(const std::string& basename) {
local_SA = read_dist_int_array<index_t>(basename + ".sa", comm);
// TODO: read different datatype for LCP?
if (_CONSTRUCT_LCP) {
local_LCP = read_dist_int_array<index_t>(basename + ".lcp", comm);
if (local_SA.size() != local_LCP.size()) {
throw std::runtime_error("SA and LCP have to have same size");
}
}
if (_CONSTRUCT_LC) {
local_Lc = read_dist_int_array<char_t>(basename + ".lc", comm);
if (local_SA.size() != local_Lc.size()) {
throw std::runtime_error("SA and Lc have to have same size");
}
}
alpha.read(basename + ".alpha", comm);
// initialize the rest
init_size(local_SA.size());
}
//template <typename StringSet> TODO template later
void construct_ss(simple_dstringset& ss, const alphabet_type& alpha) {
SAC_TIMER_START();
/***********************
* Initial bucketing *
***********************/
unsigned int k = get_optimal_k<index_t>(alpha, ss.sum_sizes, comm);
if(comm.rank() == 0) {
INFO("Alphabet: " << alpha);
}
SAC_TIMER_END_SECTION("alphabet detection");
// create distributed sequences helper structure for the distributed stringset
dist_seqs ds = dist_seqs::from_dss(ss, comm);
// create all kmers
local_B = kmer_gen_stringset<index_t>(ss, k, alpha, comm);
// equally distribute kmers
mxx::stable_distribute_inplace(local_B, comm);
init_size(local_B.size());
SAC_TIMER_END_SECTION("kmer generation");
size_t shift_by;
std::vector<index_t> local_B_SA;
size_t unfinished_buckets, unfinished_elements;
for (shift_by = k; shift_by < n; shift_by <<= 1) {
SAC_TIMER_LOOP_START();
// 1) doubling by shifting into tuples (2BSA kind of structure)
std::vector<index_t> B2 = shift_buckets_ds(ds, local_B, shift_by, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "shift-buckets-ds");
// 2) sort by (B1, B2)
local_SA = idxsort_vectors<index_t, index_t, true>(local_B, B2, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA2ISA-idxsort");
// 4) rebucket (B1, B2) -> B1 and LCP contruction
if (shift_by == k) {
if (_CONSTRUCT_LCP) {
initial_kmer_lcp_gsa(k, alpha.bits_per_char(), B2);
SAC_TIMER_END_LOOP_SECTION(shift_by, "init-lcp");
}
std::tie(unfinished_buckets, unfinished_elements) = rebucket_gsa_kmers(local_B, B2, true, comm, alpha.bits_per_char());
} else {
if (_CONSTRUCT_LCP) {
resolve_next_lcp(shift_by, B2);
SAC_TIMER_END_LOOP_SECTION(shift_by, "resove-lcp");
}
std::tie(unfinished_buckets, unfinished_elements) = rebucket_gsa(local_B, B2, true, comm);
}
if (comm.rank() == 0) {
INFO("iteration " << shift_by << ": unfinished buckets = " << unfinished_buckets << ", unfinished elements = " << unfinished_elements);
}
// 5) reverse order to SA order
if ((shift_by << 1) >= n || unfinished_buckets == 0) {
// if last iteration, use copy of local_SA for reorder and keep
// original SA
std::vector<index_t> cpy_SA(local_SA);
bulk_permute_inplace(local_B, cpy_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA2ISA-bulk-permute");
//} else if (unfinished_elements < n/10) {
} else if (true) {
// switch to A2: bucket chaising
// prepare for bucket chaising (needs SA, and bucket arrays in both
// SA and ISA order)
std::vector<index_t> cpy_SA(local_SA);
local_B_SA = local_B; // copy
bulk_permute_inplace(local_B, cpy_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA2ISA-bulk-permute");
break;
} else {
bulk_permute_inplace(local_B, local_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA2ISA-bulk-permute");
//SAC_TIMER_END_LOOP_SECTION(shift_by, "SA-to-ISA");
}
// end iteratior
SAC_TIMER_END_SECTION("sac-iteration");
if (unfinished_buckets == 0)
break;
}
if (unfinished_buckets > 0) {
if (comm.rank() == 0)
INFO("Starting Bucket chasing algorithm");
construct_msgs_gsa(ds, local_B_SA, local_B, 2*shift_by);
}
SAC_TIMER_END_SECTION("construct-msgs");
for (std::size_t i = 0; i < local_B.size(); ++i) {
// the buffer indeces are `1` based indeces, but the ISA should be
// `0` based indeces
local_B[i] -= 1;
}
}
template <typename Iterator>
void construct(Iterator begin, Iterator end, bool fast_resolval, const alphabet_type& alpha, unsigned int k) {
SAC_TIMER_START();
// create initial k-mers and use these as the initial bucket numbers
// for each character position
local_B = kmer_generation<index_t>(begin, end, k, alpha, comm);
SAC_TIMER_END_SECTION("kmer-gen");
std::vector<index_t> local_B_SA;
std::size_t unfinished_buckets = 1<<k;
std::size_t unfinished_elements = n;
std::size_t shift_by;
/*******************************
* Prefix Doubling main loop *
*******************************/
for (shift_by = k; shift_by < n; shift_by <<= 1) {
SAC_TIMER_LOOP_START();
/**************************************************
* Pairing buckets by shifting `shift_by` = 2^i *
**************************************************/
// shift the B1 buckets by 2^i to the left => equals B2
std::vector<index_t> local_B2 = shift_vector(local_B, part, shift_by, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "shift-buckets");
/*************
* ISA->SA *
*************/
// by using sample sort on tuples (B1,B2)
local_SA = idxsort_vectors<index_t, index_t>(local_B, local_B2, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "ISA-to-SA");
/****************
* Update LCP *
****************/
// if this is the first iteration: create LCP, otherwise update
if (_CONSTRUCT_LCP) {
if (shift_by == k) {
initial_kmer_lcp(k, alpha.bits_per_char(), local_B2);
SAC_TIMER_END_LOOP_SECTION(shift_by, "init-lcp");
} else {
resolve_next_lcp(shift_by, local_B2);
SAC_TIMER_END_LOOP_SECTION(shift_by, "update-lcp");
}
}
/*******************************
* Assign new bucket numbers *
*******************************/
std::tie(unfinished_buckets, unfinished_elements) = rebucket(local_B, local_B2, true, comm);
if (comm.rank() == 0) {
INFO("iteration " << shift_by << ": unfinished buckets = " << unfinished_buckets << ", unfinished elements = " << unfinished_elements);
}
SAC_TIMER_END_LOOP_SECTION(shift_by, "rebucket");
/*************
* SA->ISA *
*************/
// by bucketing to correct target processor using the `SA` array
if (fast_resolval && unfinished_elements < n/10) {
// prepare for bucket chaising (needs SA, and bucket arrays in both
// SA and ISA order)
std::vector<index_t> cpy_SA(local_SA);
local_B_SA = local_B; // copy
bulk_permute_inplace(local_B, cpy_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA-to-ISA");
SAC_TIMER_END_SECTION("sac-iteration");
break;
} else if ((shift_by << 1) >= n || unfinished_buckets == 0) {
// if last iteration, use copy of local_SA for reorder and keep
// original SA
std::vector<index_t> cpy_SA(local_SA);
bulk_permute_inplace(local_B, cpy_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA-to-ISA");
} else {
bulk_permute_inplace(local_B, local_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA-to-ISA");
}
// end iteratior
SAC_TIMER_END_SECTION("sac-iteration");
// check for termination condition
if (unfinished_buckets == 0)
break;
}
if (unfinished_buckets > 0) {
if (comm.rank() == 0)
INFO("Starting Bucket chasing algorithm");
construct_msgs(local_B_SA, local_B, 2*shift_by);
}
SAC_TIMER_END_SECTION("construct-msgs");
// now local_SA is actual block decomposed SA and local_B is actual ISA with an offset of one
for (std::size_t i = 0; i < local_B.size(); ++i) {
// the buffer indeces are `1` based indeces, but the ISA should be
// `0` based indeces
local_B[i] -= 1;
}
SAC_TIMER_END_SECTION("fix-isa");
}
template <typename Iterator>
void construct(Iterator begin, Iterator end, bool fast_resolval = true, unsigned int k = 0) {
SAC_TIMER_START();
// the local size of the input
init_size(std::distance(begin, end));
// detect alphabet and get encoding
alpha = alphabet_type::from_sequence(begin, end, comm);
k = get_optimal_k<index_t>(alpha, local_size, comm, k);
if(comm.rank() == 0) {
INFO("Alphabet: " << alpha);
}
SAC_TIMER_END_SECTION("get alphabet");
construct(begin, end, fast_resolval, alpha, k);
}
// generalized to more than "doubling" (e.g. prefix-trippling with L=3)
// NOTE: this implementation doesn't support building the LCP (SA + ISA only)
template <std::size_t L, typename Iterator>
void construct_arr(Iterator begin, Iterator end, bool fast_resolval = true) {
SAC_TIMER_START();
init_size(std::distance(begin, end));
/***********************
* Initial bucketing *
***********************/
// detect alphabet and get encoding
alpha = alphabet_type::from_sequence(begin, end, comm);
unsigned int k = get_optimal_k<index_t>(alpha, local_size, comm);
if(comm.rank() == 0) {
INFO("Alphabet: " << alpha.unique_chars());
INFO("Detecting sigma=" << alpha.sigma() << " => l=" << alpha.bits_per_char() << ", k=" << k);
}
// create initial k-mers and use these as the initial bucket numbers
// for each character position
local_B = kmer_generation<index_t>(begin, end, k, alpha, comm);
SAC_TIMER_END_SECTION("initial-bucketing");
std::vector<index_t> local_B_SA;
std::size_t unfinished_buckets = 1<<k;
std::size_t unfinished_elements = n;
std::size_t shift_by;
/*******************************
* Prefix Doubling main loop *
*******************************/
for (shift_by = k; shift_by < n; shift_by*=L) {
SAC_TIMER_LOOP_START();
/*****************
* fill tuples *
*****************/
std::vector<std::array<index_t, L+1> > tuples(local_size);
std::size_t offset = part.eprefix_size();
for (std::size_t i = 0; i < local_size; ++i) {
tuples[i][0] = i + offset;
tuples[i][1] = local_B[i];
}
SAC_TIMER_END_LOOP_SECTION(shift_by, "arr-tupelize");
/**************************************************
* Pairing buckets by shifting `shift_by` = 2^k *
**************************************************/
// shift the B1 buckets by 2^k to the left => equals B2
multi_shift_inplace<index_t, L>(tuples, part, shift_by, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "shift-buckets");
/*************
* ISA->SA *
*************/
// by using sample sort on tuples (B1,B2)
sort_array_tuples<L>(tuples);
SAC_TIMER_END_LOOP_SECTION(shift_by, "ISA-to-SA");
/****************
* Update LCP *
****************/
// if this is the first iteration: create LCP, otherwise update
// TODO: LCP construciton is not (yet) implemented for std::array based construction
/*
if (_CONSTRUCT_LCP)
{
if (shift_by == k) {
initial_kmer_lcp(k, bits_per_char, local_B2);
SAC_TIMER_END_LOOP_SECTION(shift_by, "init-lcp");
} else {
resolve_next_lcp(shift_by, local_B2);
SAC_TIMER_END_LOOP_SECTION(shift_by, "update-lcp");
}
}
*/
/*******************************
* Assign new bucket numbers *
*******************************/
std::tie(unfinished_buckets,unfinished_elements) = rebucket_arr<L>(tuples, local_B, true, comm);
if (comm.rank() == 0) {
INFO("iteration " << shift_by << ": unfinished buckets = " << unfinished_buckets << ", unfinished elements = " << unfinished_elements);
}
SAC_TIMER_END_LOOP_SECTION(shift_by, "rebucket");
/**************************************
* Reset local_SA array from tuples *
**************************************/
// init local_SA
local_SA.resize(local_size);
for (std::size_t i = 0; i < local_size; ++i) {
local_SA[i] = tuples[i][0];
}
// deallocate all memory
tuples.clear();
tuples.shrink_to_fit();
SAC_TIMER_END_LOOP_SECTION(shift_by, "arr-untupelize");
/*************
* SA->ISA *
*************/
// by bucketing to correct target processor using the `SA` array
if (fast_resolval && unfinished_elements < n/10) {
// prepare for bucket chaising (needs SA, and bucket arrays in both
// SA and ISA order)
std::vector<index_t> cpy_SA(local_SA);
local_B_SA = local_B; // copy
bulk_permute_inplace(local_B, cpy_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA-to-ISA");
break;
} else if ((shift_by * L) >= n || unfinished_buckets == 0) {
// if last iteration, use copy of local_SA for reorder and keep
// original SA
std::vector<index_t> cpy_SA(local_SA);
bulk_permute_inplace(local_B, cpy_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA-to-ISA");
} else {
bulk_permute_inplace(local_B, local_SA, part, comm);
SAC_TIMER_END_LOOP_SECTION(shift_by, "SA-to-ISA");
}
// end iteratior
SAC_TIMER_END_SECTION("sac-iteration");
// check for termination condition
if (unfinished_buckets == 0)
break;
}
if (unfinished_buckets > 0) {
if (comm.rank() == 0)
INFO("Starting Bucket chasing algorithm");
construct_msgs(local_B_SA, local_B, L*shift_by);
}
SAC_TIMER_END_SECTION("construct-msgs");
// now local_SA is actual block decomposed SA and local_B is actual ISA with an offset of one
for (std::size_t i = 0; i < local_B.size(); ++i) {
// the buffer indeces are `1` based indeces, but the ISA should be
// `0` based indeces
local_B[i] -= 1;
}
SAC_TIMER_END_SECTION("fix-isa");
}
private:
#if 0
void construct_fast() {
SAC_TIMER_START();
/***********************
* Initial bucketing *
***********************/
// detect alphabet and get encoding
alpha = alphabet_type::from_sequence(input_begin, input_end, comm);
unsigned int bits_per_char = alpha.bits_per_char();
unsigned int k = get_optimal_k<index_t>(alpha, local_size, comm);
if(comm.rank() == 0) {
INFO("Alphabet: " << alpha.unique_chars());
INFO("Detecting sigma=" << alpha.sigma() << " => l=" << bits_per_char << ", k=" << k);
}
// create initial k-mers and use these as the initial bucket numbers
// for each character position
local_B = kmer_generation<index_t>(input_begin, input_end, k, alpha, comm);
SAC_TIMER_END_SECTION("initial-bucketing");
// init local_SA
if (local_SA.size() != local_B.size()) {
local_SA.resize(local_B.size());
}
kmer_sorting();
SAC_TIMER_END_SECTION("kmer-sorting");
if (_CONSTRUCT_LCP) {
initial_kmer_lcp(k, bits_per_char);
SAC_TIMER_END_SECTION("initial-kmer-lcp");
}
rebucket_kmer();
SAC_TIMER_END_SECTION("rebucket-kmer");
std::vector<index_t> cpy_SA(local_SA);
std::vector<index_t> local_B_SA(local_B); // copy
bulk_permute_inplace(local_B, cpy_SA, part, comm);
SAC_TIMER_END_SECTION("sa2isa");
cpy_SA.clear();
cpy_SA.shrink_to_fit();
if (comm.rank() == 0)
INFO("Starting Bucket chasing algorithm");
construct_msgs(local_B_SA, local_B, k);
SAC_TIMER_END_SECTION("construct-msgs");
// now local_SA is actual block decomposed SA and local_B is actual ISA with an offset of one
for (std::size_t i = 0; i < local_B.size(); ++i) {
// the buffer indeces are `1` based indeces, but the ISA should be
// `0` based indeces
local_B[i] -= 1;
}
SAC_TIMER_END_SECTION("fix-isa");
}
#endif
private:
/*********************************************************************
* ISA -> SA (sort buckets) *
*********************************************************************/
template <std::size_t L>
void sort_array_tuples(std::vector<std::array<index_t, L+1> >& tuples) {
assert(tuples.size() == local_size);
SAC_TIMER_START();
// parallel, distributed sample-sorting of tuples (B1, B2, SA)
mxx::sort(tuples.begin(), tuples.end(),
[] (const std::array<index_t, L+1>& x, const std::array<index_t, L+1>& y) {
for (unsigned int i = 1; i < L+1; ++i) {
if (x[i] != y[i])
return x[i] < y[i];
}
return false;
}, comm);
SAC_TIMER_END_SECTION("isa2sa_samplesort");
}
void kmer_sorting() {
SAC_TIMER_START();
// initialize tuple array
std::vector<mypair<index_t> > tuple_vec(local_size);
// get global index offset
std::size_t str_offset = part.eprefix_size();
// fill tuple vector
for (std::size_t i = 0; i < local_size; ++i) {
tuple_vec[i].first = local_B[i];
assert(str_offset + i < std::numeric_limits<index_t>::max());
tuple_vec[i].second = str_offset + i;
}
// release memory of input (to remain at the minimum 6x words memory usage)
local_B.clear(); local_B.shrink_to_fit();
local_SA.clear(); local_SA.shrink_to_fit();
SAC_TIMER_END_SECTION("isa2sa_pairize");
// parallel, distributed sample-sorting of tuples (B1, B2, SA)
mxx::sort(tuple_vec.begin(), tuple_vec.end(),
[](const mypair<index_t>& x, const mypair<index_t>& y) {
return x.first < y.first;
}, comm);
SAC_TIMER_END_SECTION("isa2sa_samplesort_pairs");
// reallocate output
local_B.resize(local_size);
local_SA.resize(local_size);
// read back into input vectors
for (std::size_t i = 0; i < local_size; ++i) {
local_B[i] = tuple_vec[i].first;
local_SA[i] = tuple_vec[i].second;
}
SAC_TIMER_END_SECTION("isa2sa_unpairize");
}
/*********************************************************************
* Rebucket tuples into new bucket numbers *
*********************************************************************/
// assumed sorted order (globally) by local_B
// this reassigns new, unique bucket numbers in {1,...,n} globally
void rebucket_kmer() {
/*
* NOTE: buckets are indexed by the global index of the first element in
* the bucket with a ONE-BASED-INDEX (since bucket number `0` is
* reserved for out-of-bounds)
*/
// get my global starting index
size_t prefix = part.eprefix_size();
size_t local_max = 0;
/*
* assign local zero or one, depending on whether the bucket is the same
* as the previous one
*/
foreach_pair(local_B.begin(), local_B.end(), [&](index_t prev, index_t& cur, size_t i) {
if (prev == cur) {
cur = prefix + i + 1;
local_max = cur;
} else {
cur = 0;
}
}, comm);
if (comm.rank() == 0) {
local_B[0] = 1;
if (local_max == 0)
local_max = 1;
}
/*
* Global prefix MAX:
* - such that for every item we have it's bucket number, where the
* bucket number is equal to the first index in the bucket
* this way buckets who are finished, will never receive a new
* number.
*/
// 2.) distributed scan with max() to get starting max for each sequence
size_t pre_max = mxx::exscan(local_max, mxx::max<size_t>(), comm);
// 3.) linear scan and assign bucket numbers
for (std::size_t i = 0; i < local_B.size(); ++i) {
if (local_B[i] == 0)
local_B[i] = pre_max;
else
pre_max = local_B[i];
assert(local_B[i] <= i+prefix+1);
// first element of bucket has id of it's own global index:
assert(i == 0 || (local_B[i-1] == local_B[i] || local_B[i] == i+prefix+1));
}
}
// same function as before, but this one assumes tuples instead of
// two arrays
// This is used in the bucket chaising construction. The MPI_Comm will most
// of the time be a subcommunicator (so do not use the member `comm`)
template <typename EqualFunc>
void rebucket_bucket(std::vector<TwoBSA<index_t> >& bucket, const mxx::comm& comm, std::size_t bucket_offset, std::vector<std::pair<index_t, index_t> >& minqueries, std::vector<index_t>& minq_idx, size_t shift_by, EqualFunc eq) {
/*
* NOTE: buckets are indexed by the global index of the first element in
* the bucket with a ONE-BASED-INDEX (since bucket number `0` is
* reserved for out-of-bounds)
*/
// inputs can be of different size, since buckets can span bucket boundaries
std::size_t local_size = bucket.size();
std::size_t prefix = mxx::exscan(local_size, std::plus<size_t>(), comm);
size_t local_max = 0;
prefix += bucket_offset;
// iterate through all pairs of elements (spanning across processors)
foreach_pair(bucket.begin(), bucket.end(), [&](const TwoBSA<index_t>& prev, TwoBSA<index_t>& cur, size_t i){
// if this is a new bucket boundary: set current to prefix+index and update LCP
if (!eq(prev, cur)) {
cur.B1 = prefix+i+1;
local_max = cur.B1;
} else {
cur.B1 = 0;
}
if (_CONSTRUCT_LCP) {
if (prev.B2 == 0 || cur.B2 == 0) {
if (local_LCP[i+prefix - part.eprefix_size()] == n)
local_LCP[i+prefix - part.eprefix_size()] = shift_by;
} else if (prev.B2 != cur.B2) {
index_t left_b = std::min(prev.B2, cur.B2);
index_t right_b = std::max(prev.B2, cur.B2);
assert(0 < left_b && left_b < n);
assert(0 < right_b && right_b <= n);
minqueries.emplace_back(left_b, right_b);
minq_idx.emplace_back(i + prefix);
}
}
}, comm);
// specially handle first element of first process
if (comm.rank() == 0) {
bucket[0].B1 = prefix + 1;
if (local_max == 0)
local_max = prefix + 1;
}
/*
* Global prefix MAX:
* - such that for every item we have it's bucket number, where the
* bucket number is equal to the first index in the bucket
* this way buckets who are finished, will never receive a new
* number.
*/
// 2.) distributed scan with max() to get starting max for each sequence
std::size_t pre_max = mxx::exscan(local_max, mxx::max<size_t>(), comm);
if (comm.rank() == 0)
pre_max = 0;
// 3.) linear scan and assign bucket numbers
for (std::size_t i = 0; i < local_size; ++i) {
if (bucket[i].B1 == 0)
bucket[i].B1 = pre_max;
else
pre_max = bucket[i].B1;
assert(bucket[i].B1 <= i+prefix+1);
// first element of bucket has id of it's own global index:
assert(i == 0 || (bucket[i-1].B1 == bucket[i].B1 || bucket[i].B1 == i+prefix+1));
}
}
void rebucket_bucket(std::vector<TwoBSA<index_t> >& bucket, const mxx::comm& comm, std::size_t gl_offset, std::vector<std::pair<index_t, index_t> >& minqueries, std::vector<index_t>& minq_idx, size_t shift_by) {
rebucket_bucket(bucket, comm, gl_offset, minqueries, minq_idx, shift_by, [](const TwoBSA<index_t>& x, const TwoBSA<index_t>& y){
return x.B1 == y.B1 && x.B2 == y.B2;
});
}
void rebucket_bucket_gsa(std::vector<TwoBSA<index_t> >& bucket, const mxx::comm& comm, std::size_t gl_offset, std::vector<std::pair<index_t, index_t> >& minqueries, std::vector<index_t>& minq_idx, size_t shift_by) {
rebucket_bucket(bucket, comm, gl_offset, minqueries, minq_idx, shift_by, [](const TwoBSA<index_t>& x, const TwoBSA<index_t>& y){
return x.B1 == y.B1 && x.B2 == y.B2 && x.B2 != 0;
});
}
/*********************************************************************
* Faster construction for fewer remaining buckets *
*********************************************************************/
std::vector<index_t> get_active(const std::vector<index_t>& B, const std::vector<index_t>& active, const mxx::comm& comm, bool print_stats = false) {
// get next element from right
index_t right_B = mxx::left_shift(B[0], comm);
// get global offset
size_t prefix = part.eprefix_size();
size_t unresolved_els = 0;
size_t unfinished_b = 0;
std::vector<index_t> active_elements;
bool use_b = active.empty();
size_t loopn = use_b ? B.size() : active.size();
for (index_t g = 0; g < loopn; ++g) {
size_t j = use_b ? g : active[g];
// get global index for each local index
size_t i = prefix + j;
// check if this is a unresolved bucket
// relying on the property that for resolved buckets:
// B[i] == i+1 and B[i+1] == i+2
// (where `i' is the global index)
if (B[j] != i+1) {
// save local active indexes
active_elements.push_back(j);
unresolved_els++;
} else if (B[j] == i+1 && ((j < local_size-1 && B[j+1] == i+1)
|| (j == local_size-1 && comm.rank() < p-1 && right_B == i+1))) {
active_elements.push_back(j);
unresolved_els++;
unfinished_b++;
}
}
if (print_stats) {
size_t gl_unresolved = mxx::allreduce(unresolved_els, comm);
size_t gl_unfinished = mxx::allreduce(unfinished_b, comm);
if (comm.rank() == 0) {
INFO("unresolved = " << gl_unresolved << ", unfinished = " << gl_unfinished);
}
}
return active_elements;
}
std::vector<index_t> get_active(const std::vector<index_t>& B, const mxx::comm& comm, bool print_stats = false) {
std::vector<index_t> empty;
return get_active(B, empty, comm, print_stats);
}
std::vector<index_t> sparse_get_b2(const std::vector<index_t>& active, const std::vector<index_t>& B, const std::vector<index_t>& SA, size_t shift_by, const mxx::comm& comm) {
std::vector<size_t> rma_reqs;
std::vector<index_t> b2(active.size());
for (size_t ai = 0; ai < active.size(); ++ai) {
size_t j = active[ai];
if (SA[j] + shift_by < n) {
rma_reqs.push_back(SA[j]+shift_by);
}
}
// use bulk RMA to request the values of B at doubled (+shift_by) location for
// each active suffix
std::vector<index_t> rma_b2 = bulk_rma(B.begin(), B.end(), rma_reqs, comm);
auto b2in = rma_b2.begin();
for (size_t i = 0; i < active.size(); ++i) {
size_t j = active[i];
if (SA[j] + shift_by < n) {
b2[i] = *b2in;
++b2in;
}
}
return b2;
}
std::vector<index_t> sparse_get_b2(const dist_seqs& ds, const std::vector<index_t>& active, const std::vector<index_t>& B, const std::vector<index_t>& SA, size_t shift_by, const mxx::comm& comm) {
// create RMA requests for the doubled positions
std::vector<size_t> rma_reqs;