-
Notifications
You must be signed in to change notification settings - Fork 73
/
hier_idx.h
1877 lines (1778 loc) · 67.5 KB
/
hier_idx.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2013, Daehwan Kim <[email protected]>
*
* This file is part of Beast. Beast is based on Bowtie 2.
*
* Beast is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Beast is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Beast. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HIEREBWT_H_
#define HIEREBWT_H_
#include "hier_idx_common.h"
#include "bt2_idx.h"
#include "bt2_io.h"
#include "bt2_util.h"
/**
* Extended Burrows-Wheeler transform data.
* LocalEbwt is a specialized Ebwt index that represents ~64K bps
* and therefore uses two bytes as offsets within 64K bps.
* This class has only two additional member variables to denote the genomic sequenuce it represents:
* (1) the contig index and (2) the offset within the contig.
*
*/
template <typename index_t = uint16_t, typename full_index_t = uint32_t>
class LocalEbwt : public Ebwt<index_t> {
typedef Ebwt<index_t> PARENT_CLASS;
public:
/// Construct an Ebwt from the given input file
LocalEbwt(const string& in,
FILE *in5,
FILE *in6,
char *mmFile5,
char *mmFile6,
full_index_t& tidx,
full_index_t& localOffset,
bool switchEndian,
size_t& bytesRead,
int color,
int needEntireReverse,
bool fw,
int32_t overrideOffRate, // = -1,
int32_t offRatePlus, // = -1,
uint32_t lineRate,
uint32_t offRate,
uint32_t ftabChars,
bool useMm, // = false,
bool useShmem, // = false,
bool mmSweep, // = false,
bool loadNames, // = false,
bool loadSASamp, // = true,
bool loadFtab, // = true,
bool loadRstarts, // = true,
bool verbose, // = false,
bool startVerbose, // = false,
bool passMemExc, // = false,
bool sanityCheck) : // = false) :
Ebwt<index_t>(in,
color,
needEntireReverse,
fw,
overrideOffRate,
offRatePlus,
useMm,
useShmem,
mmSweep,
loadNames,
loadSASamp,
loadFtab,
loadRstarts,
verbose,
startVerbose,
passMemExc,
sanityCheck,
true)
{
this->_in1Str = in + ".5." + gEbwt_ext;
this->_in2Str = in + ".5." + gEbwt_ext;
readIntoMemory(
in5,
in6,
mmFile5,
mmFile6,
tidx,
localOffset,
switchEndian,
bytesRead,
color,
needEntireReverse,
loadSASamp,
loadFtab,
loadRstarts,
false, //justHeader
lineRate,
offRate,
ftabChars,
mmSweep,
loadNames,
startVerbose);
_tidx = tidx;
_localOffset = localOffset;
// If the offRate has been overridden, reflect that in the
// _eh._offRate field
if(offRatePlus > 0 && this->_overrideOffRate == -1) {
this->_overrideOffRate = this->_eh._offRate + offRatePlus;
}
if(this->_overrideOffRate > this->_eh._offRate) {
this->_eh.setOffRate(this->_overrideOffRate);
assert_eq(this->_overrideOffRate, this->_eh._offRate);
}
assert(this->repOk());
}
/// Construct an Ebwt from the given header parameters and string
/// vector, optionally using a blockwise suffix sorter with the
/// given 'bmax' and 'dcv' parameters. The string vector is
/// ultimately joined and the joined string is passed to buildToDisk().
template<typename TStr>
LocalEbwt(
TStr& s,
full_index_t tidx,
full_index_t local_offset,
index_t local_size,
bool packed,
int color,
int needEntireReverse,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
const string& file, // base filename for EBWT files
bool fw,
int dcv,
EList<RefRecord>& szs,
index_t sztot,
const RefReadInParams& refparams,
uint32_t seed,
ostream& out5,
ostream& out6,
int32_t overrideOffRate = -1,
bool verbose = false,
bool passMemExc = false,
bool sanityCheck = false) :
Ebwt<index_t>(packed,
color,
needEntireReverse,
lineRate,
offRate,
ftabChars,
file,
fw,
dcv,
szs,
sztot,
refparams,
seed,
overrideOffRate,
verbose,
passMemExc,
sanityCheck)
{
const EbwtParams<index_t>& eh = this->_eh;
assert(eh.repOk());
uint32_t be = this->toBe();
assert(out5.good());
assert(out6.good());
writeIndex<full_index_t>(out5, tidx, be);
writeIndex<full_index_t>(out5, local_offset, be);
writeU32(out5, eh._len, be); // length of string (and bwt and suffix array)
if(eh._len > 0) {
assert_gt(szs.size(), 0);
assert_gt(sztot, 0);
// Not every fragment represents a distinct sequence - many
// fragments may correspond to a single sequence. Count the
// number of sequences here by counting the number of "first"
// fragments.
this->_nPat = 0;
this->_nFrag = 0;
for(size_t i = 0; i < szs.size(); i++) {
if(szs[i].len > 0) this->_nFrag++;
if(szs[i].first && szs[i].len > 0) this->_nPat++;
}
assert_eq(this->_nPat, 1);
assert_geq(this->_nFrag, this->_nPat);
this->_rstarts.reset();
writeIndex(out5, this->_nPat, be);
assert_eq(this->_nPat, 1);
this->_plen.init(new index_t[this->_nPat], this->_nPat);
// For each pattern, set plen
int npat = -1;
for(size_t i = 0; i < szs.size(); i++) {
if(szs[i].first && szs[i].len > 0) {
if(npat >= 0) {
writeIndex(out5, this->plen()[npat], be);
}
npat++;
this->plen()[npat] = (szs[i].len + szs[i].off);
} else {
this->plen()[npat] += (szs[i].len + szs[i].off);
}
}
assert_eq((index_t)npat, this->_nPat-1);
writeIndex(out5, this->plen()[npat], be);
// Write the number of fragments
writeIndex(out5, this->_nFrag, be);
if(refparams.reverse == REF_READ_REVERSE) {
EList<RefRecord> tmp(EBWT_CAT);
reverseRefRecords(szs, tmp, false, verbose);
this->szsToDisk(tmp, out5, refparams.reverse);
} else {
this->szsToDisk(szs, out5, refparams.reverse);
}
VMSG_NL("Constructing suffix-array element generator");
KarkkainenBlockwiseSA<TStr> bsa(s, s.length()+1, dcv, seed, this->_sanity, this->_passMemExc, this->_verbose);
assert(bsa.suffixItrIsReset());
assert_eq(bsa.size(), s.length()+1);
VMSG_NL("Converting suffix-array elements to index image");
buildToDisk(bsa, s, out5, out6);
}
out5.flush(); out6.flush();
if(out5.fail() || out6.fail()) {
cerr << "An error occurred writing the index to disk. Please check if the disk is full." << endl;
throw 1;
}
}
template <typename TStr> void buildToDisk(
InorderBlockwiseSA<TStr>& sa,
const TStr& s,
ostream& out1,
ostream& out2);
// I/O
void readIntoMemory(
FILE *in5,
FILE *in6,
char *mmFile5,
char *mmFile6,
full_index_t& tidx,
full_index_t& localOffset,
bool switchEndian,
size_t bytesRead,
int color,
int needEntireRev,
bool loadSASamp,
bool loadFtab,
bool loadRstarts,
bool justHeader,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
bool mmSweep,
bool loadNames,
bool startVerbose);
/**
* Sanity-check various pieces of the Ebwt
*/
void sanityCheckAll(int reverse) const {
if(this->_eh._len > 0) {
PARENT_CLASS::sanityCheckAll(reverse);
}
}
bool empty() const { return this->_eh._len == 0; }
public:
full_index_t _tidx;
full_index_t _localOffset;
};
/**
* Build an Ebwt from a string 's' and its suffix array 'sa' (which
* might actually be a suffix array *builder* that builds blocks of the
* array on demand). The bulk of the Ebwt, i.e. the ebwt and offs
* arrays, is written directly to disk. This is by design: keeping
* those arrays in memory needlessly increases the footprint of the
* building process. Instead, we prefer to build the Ebwt directly
* "to disk" and then read it back into memory later as necessary.
*
* It is assumed that the header values and join-related values (nPat,
* plen) have already been written to 'out1' before this function
* is called. When this function is finished, it will have
* additionally written ebwt, zOff, fchr, ftab and eftab to the primary
* file and offs to the secondary file.
*
* Assume DNA/RNA/any alphabet with 4 or fewer elements.
* Assume occ array entries are 32 bits each.
*
* @param sa the suffix array to convert to a Ebwt
* @param s the original string
* @param out
*/
template <typename index_t, typename full_index_t>
template <typename TStr>
void LocalEbwt<index_t, full_index_t>::buildToDisk(
InorderBlockwiseSA<TStr>& sa,
const TStr& s,
ostream& out5,
ostream& out6)
{
assert_leq(s.length(), std::numeric_limits<index_t>::max());
const EbwtParams<index_t>& eh = this->_eh;
assert(eh.repOk());
assert_eq(s.length()+1, sa.size());
assert_eq(s.length(), eh._len);
assert_gt(eh._lineRate, 3);
assert(sa.suffixItrIsReset());
index_t len = eh._len;
index_t ftabLen = eh._ftabLen;
index_t sideSz = eh._sideSz;
index_t ebwtTotSz = eh._ebwtTotSz;
index_t fchr[] = {0, 0, 0, 0, 0};
EList<index_t> ftab(EBWT_CAT);
index_t zOff = (index_t)OFF_MASK;
// Save # of occurrences of each character as we walk along the bwt
index_t occ[4] = {0, 0, 0, 0};
index_t occSave[4] = {0, 0, 0, 0};
// Record rows that should "absorb" adjacent rows in the ftab.
// The absorbed rows represent suffixes shorter than the ftabChars
// cutoff.
uint8_t absorbCnt = 0;
EList<uint8_t> absorbFtab(EBWT_CAT);
try {
VMSG_NL("Allocating ftab, absorbFtab");
ftab.resize(ftabLen);
ftab.fillZero();
absorbFtab.resize(ftabLen);
absorbFtab.fillZero();
} catch(bad_alloc &e) {
cerr << "Out of memory allocating ftab[] or absorbFtab[] "
<< "in Ebwt::buildToDisk() at " << __FILE__ << ":"
<< __LINE__ << endl;
throw e;
}
// Allocate the side buffer; holds a single side as its being
// constructed and then written to disk. Reused across all sides.
#ifdef SIXTY4_FORMAT
EList<uint64_t> ebwtSide(EBWT_CAT);
#else
EList<uint8_t> ebwtSide(EBWT_CAT);
#endif
try {
#ifdef SIXTY4_FORMAT
ebwtSide.resize(sideSz >> 3);
#else
ebwtSide.resize(sideSz);
#endif
} catch(bad_alloc &e) {
cerr << "Out of memory allocating ebwtSide[] in "
<< "Ebwt::buildToDisk() at " << __FILE__ << ":"
<< __LINE__ << endl;
throw e;
}
// Points to the base offset within ebwt for the side currently
// being written
index_t side = 0;
// Whether we're assembling a forward or a reverse bucket
bool fw;
int sideCur = 0;
fw = true;
// Have we skipped the '$' in the last column yet?
ASSERT_ONLY(bool dollarSkipped = false);
index_t si = 0; // string offset (chars)
ASSERT_ONLY(uint32_t lastSufInt = 0);
ASSERT_ONLY(bool inSA = true); // true iff saI still points inside suffix
// array (as opposed to the padding at the
// end)
// Iterate over packed bwt bytes
VMSG_NL("Entering Ebwt loop");
ASSERT_ONLY(uint32_t beforeEbwtOff = (uint32_t)out5.tellp());
while(side < ebwtTotSz) {
// Sanity-check our cursor into the side buffer
assert_geq(sideCur, 0);
assert_lt(sideCur, (int)eh._sideBwtSz);
assert_eq(0, side % sideSz); // 'side' must be on side boundary
ebwtSide[sideCur] = 0; // clear
assert_lt(side + sideCur, ebwtTotSz);
// Iterate over bit-pairs in the si'th character of the BWT
#ifdef SIXTY4_FORMAT
for(int bpi = 0; bpi < 32; bpi++, si++) {
#else
for(int bpi = 0; bpi < 4; bpi++, si++) {
#endif
int bwtChar;
bool count = true;
if(si <= len) {
// Still in the SA; extract the bwtChar
index_t saElt = (index_t)sa.nextSuffix();
// (that might have triggered sa to calc next suf block)
if(saElt == 0) {
// Don't add the '$' in the last column to the BWT
// transform; we can't encode a $ (only A C T or G)
// and counting it as, say, an A, will mess up the
// LR mapping
bwtChar = 0; count = false;
ASSERT_ONLY(dollarSkipped = true);
zOff = si; // remember the SA row that
// corresponds to the 0th suffix
} else {
bwtChar = (int)(s[saElt-1]);
assert_lt(bwtChar, 4);
// Update the fchr
fchr[bwtChar]++;
}
// Update ftab
if((len-saElt) >= (index_t)eh._ftabChars) {
// Turn the first ftabChars characters of the
// suffix into an integer index into ftab. The
// leftmost (lowest index) character of the suffix
// goes in the most significant bit pair if the
// integer.
uint32_t sufInt = 0;
for(int i = 0; i < eh._ftabChars; i++) {
sufInt <<= 2;
assert_lt((index_t)i, len-saElt);
sufInt |= (unsigned char)(s[saElt+i]);
}
// Assert that this prefix-of-suffix is greater
// than or equal to the last one (true b/c the
// suffix array is sorted)
#ifndef NDEBUG
if(lastSufInt > 0) assert_geq(sufInt, lastSufInt);
lastSufInt = sufInt;
#endif
// Update ftab
assert_lt(sufInt+1, ftabLen);
ftab[sufInt+1]++;
if(absorbCnt > 0) {
// Absorb all short suffixes since the last
// transition into this transition
absorbFtab[sufInt] = absorbCnt;
absorbCnt = 0;
}
} else {
// Otherwise if suffix is fewer than ftabChars
// characters long, then add it to the 'absorbCnt';
// it will be absorbed into the next transition
assert_lt(absorbCnt, 255);
absorbCnt++;
}
// Suffix array offset boundary? - update offset array
if((si & eh._offMask) == si) {
assert_lt((si >> eh._offRate), eh._offsLen);
// Write offsets directly to the secondary output
// stream, thereby avoiding keeping them in memory
writeIndex(out6, saElt, this->toBe());
}
} else {
// Strayed off the end of the SA, now we're just
// padding out a bucket
#ifndef NDEBUG
if(inSA) {
// Assert that we wrote all the characters in the
// string before now
assert_eq(si, len+1);
inSA = false;
}
#endif
// 'A' used for padding; important that padding be
// counted in the occ[] array
bwtChar = 0;
}
if(count) occ[bwtChar]++;
// Append BWT char to bwt section of current side
if(fw) {
// Forward bucket: fill from least to most
#ifdef SIXTY4_FORMAT
ebwtSide[sideCur] |= ((uint64_t)bwtChar << (bpi << 1));
if(bwtChar > 0) assert_gt(ebwtSide[sideCur], 0);
#else
pack_2b_in_8b(bwtChar, ebwtSide[sideCur], bpi);
assert_eq((ebwtSide[sideCur] >> (bpi*2)) & 3, bwtChar);
#endif
} else {
// Backward bucket: fill from most to least
#ifdef SIXTY4_FORMAT
ebwtSide[sideCur] |= ((uint64_t)bwtChar << ((31 - bpi) << 1));
if(bwtChar > 0) assert_gt(ebwtSide[sideCur], 0);
#else
pack_2b_in_8b(bwtChar, ebwtSide[sideCur], 3-bpi);
assert_eq((ebwtSide[sideCur] >> ((3-bpi)*2)) & 3, bwtChar);
#endif
}
} // end loop over bit-pairs
assert_eq(dollarSkipped ? 3 : 0, (occ[0] + occ[1] + occ[2] + occ[3]) & 3);
#ifdef SIXTY4_FORMAT
assert_eq(0, si & 31);
#else
assert_eq(0, si & 3);
#endif
sideCur++;
if(sideCur == (int)eh._sideBwtSz) {
sideCur = 0;
index_t *uside = reinterpret_cast<index_t*>(ebwtSide.ptr());
// Write 'A', 'C', 'G' and 'T' tallies
side += sideSz;
assert_leq(side, eh._ebwtTotSz);
uside[(sideSz / sizeof(index_t))-4] = endianizeIndex(occSave[0], this->toBe());
uside[(sideSz / sizeof(index_t))-3] = endianizeIndex(occSave[1], this->toBe());
uside[(sideSz / sizeof(index_t))-2] = endianizeIndex(occSave[2], this->toBe());
uside[(sideSz / sizeof(index_t))-1] = endianizeIndex(occSave[3], this->toBe());
occSave[0] = occ[0];
occSave[1] = occ[1];
occSave[2] = occ[2];
occSave[3] = occ[3];
// Write backward side to primary file
out5.write((const char *)ebwtSide.ptr(), sideSz);
}
}
VMSG_NL("Exited Ebwt loop");
assert_neq(zOff, (index_t)OFF_MASK);
if(absorbCnt > 0) {
// Absorb any trailing, as-yet-unabsorbed short suffixes into
// the last element of ftab
absorbFtab[ftabLen-1] = absorbCnt;
}
// Assert that our loop counter got incremented right to the end
assert_eq(side, eh._ebwtTotSz);
// Assert that we wrote the expected amount to out1
assert_eq(((uint32_t)out5.tellp() - beforeEbwtOff), eh._ebwtTotSz);
// assert that the last thing we did was write a forward bucket
//
// Write zOff to primary stream
//
writeIndex(out5, zOff, this->toBe());
//
// Finish building fchr
//
// Exclusive prefix sum on fchr
for(int i = 1; i < 4; i++) {
fchr[i] += fchr[i-1];
}
assert_eq(fchr[3], len);
// Shift everybody up by one
for(int i = 4; i >= 1; i--) {
fchr[i] = fchr[i-1];
}
fchr[0] = 0;
if(this->_verbose) {
for(int i = 0; i < 5; i++)
cout << "fchr[" << "ACGT$"[i] << "]: " << fchr[i] << endl;
}
// Write fchr to primary file
for(int i = 0; i < 5; i++) {
writeIndex(out5, fchr[i], this->toBe());
}
//
// Finish building ftab and build eftab
//
// Prefix sum on ftable
index_t eftabLen = 0;
assert_eq(0, absorbFtab[0]);
for(index_t i = 1; i < ftabLen; i++) {
if(absorbFtab[i] > 0) eftabLen += 2;
}
assert_leq(eftabLen, (index_t)eh._ftabChars*2);
eftabLen = eh._ftabChars*2;
EList<index_t> eftab(EBWT_CAT);
try {
eftab.resize(eftabLen);
eftab.fillZero();
} catch(bad_alloc &e) {
cerr << "Out of memory allocating eftab[] "
<< "in Ebwt::buildToDisk() at " << __FILE__ << ":"
<< __LINE__ << endl;
throw e;
}
index_t eftabCur = 0;
for(index_t i = 1; i < ftabLen; i++) {
index_t lo = ftab[i] + Ebwt<index_t>::ftabHi(ftab.ptr(), eftab.ptr(), len, ftabLen, eftabLen, i-1);
if(absorbFtab[i] > 0) {
// Skip a number of short pattern indicated by absorbFtab[i]
index_t hi = lo + absorbFtab[i];
assert_lt(eftabCur*2+1, eftabLen);
eftab[eftabCur*2] = lo;
eftab[eftabCur*2+1] = hi;
ftab[i] = (eftabCur++) ^ (index_t)OFF_MASK; // insert pointer into eftab
assert_eq(lo, Ebwt<index_t>::ftabLo(ftab.ptr(), eftab.ptr(), len, ftabLen, eftabLen, i));
assert_eq(hi, Ebwt<index_t>::ftabHi(ftab.ptr(), eftab.ptr(), len, ftabLen, eftabLen, i));
} else {
ftab[i] = lo;
}
}
assert_eq(Ebwt<index_t>::ftabHi(ftab.ptr(), eftab.ptr(), len, ftabLen, eftabLen, ftabLen-1), len+1);
// Write ftab to primary file
for(index_t i = 0; i < ftabLen; i++) {
writeIndex(out5, ftab[i], this->toBe());
}
// Write eftab to primary file
for(index_t i = 0; i < eftabLen; i++) {
writeIndex(out5, eftab[i], this->toBe());
}
// Note: if you'd like to sanity-check the Ebwt, you'll have to
// read it back into memory first!
assert(!this->isInMemory());
VMSG_NL("Exiting Ebwt::buildToDisk()");
}
/**
* Read an Ebwt from file with given filename.
*/
template <typename index_t, typename full_index_t>
void LocalEbwt<index_t, full_index_t>::readIntoMemory(
FILE *in5,
FILE *in6,
char *mmFile5,
char *mmFile6,
full_index_t& tidx,
full_index_t& localOffset,
bool switchEndian,
size_t bytesRead,
int color,
int entireRev,
bool loadSASamp,
bool loadFtab,
bool loadRstarts,
bool justHeader,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
bool mmSweep,
bool loadNames,
bool startVerbose)
{
#ifdef BOWTIE_MM
char *mmFile[] = { mmFile5, mmFile6 };
#endif
// Reads header entries one by one from primary stream
tidx = readIndex<full_index_t>(in5, switchEndian); bytesRead += sizeof(full_index_t);
localOffset = readIndex<full_index_t>(in5, switchEndian); bytesRead += sizeof(full_index_t);
uint32_t len = readU32(in5, switchEndian); bytesRead += 4;
// Create a new EbwtParams from the entries read from primary stream
this->_eh.init(len, lineRate, offRate, ftabChars, color, entireRev);
if(len <= 0) {
return;
}
// Set up overridden suffix-array-sample parameters
uint32_t offsLen = this->_eh._offsLen;
uint32_t offRateDiff = 0;
uint32_t offsLenSampled = offsLen;
if(this->_overrideOffRate > offRate) {
offRateDiff = this->_overrideOffRate - offRate;
}
if(offRateDiff > 0) {
offsLenSampled >>= offRateDiff;
if((offsLen & ~((index_t)OFF_MASK << offRateDiff)) != 0) {
offsLenSampled++;
}
}
// Can't override the offrate or isarate and use memory-mapped
// files; ultimately, all processes need to copy the sparser sample
// into their own memory spaces.
if(this->_useMm && (offRateDiff)) {
cerr << "Error: Can't use memory-mapped files when the offrate is overridden" << endl;
throw 1;
}
// Read nPat from primary stream
this->_nPat = readIndex<index_t>(in5, switchEndian);
assert_eq(this->_nPat, 1);
bytesRead += sizeof(index_t);
this->_plen.reset();
// Read plen from primary stream
if(this->_useMm) {
#ifdef BOWTIE_MM
this->_plen.init((index_t*)(mmFile[0] + bytesRead), this->_nPat, false);
bytesRead += this->_nPat*sizeof(index_t);
fseek(in5, this->_nPat*sizeof(index_t), SEEK_CUR);
#endif
} else {
try {
if(this->_verbose || startVerbose) {
cerr << "Reading plen (" << this->_nPat << "): ";
logTime(cerr);
}
this->_plen.init(new index_t[this->_nPat], this->_nPat, true);
if(switchEndian) {
for(index_t i = 0; i < this->_nPat; i++) {
this->plen()[i] = readIndex<index_t>(in5, switchEndian);
}
} else {
size_t r = MM_READ(in5, (void*)(this->plen()), this->_nPat*sizeof(index_t));
if(r != (size_t)(this->_nPat*sizeof(index_t))) {
cerr << "Error reading _plen[] array: " << r << ", " << this->_nPat*sizeof(index_t) << endl;
throw 1;
}
}
} catch(bad_alloc& e) {
cerr << "Out of memory allocating plen[] in Ebwt::read()"
<< " at " << __FILE__ << ":" << __LINE__ << endl;
throw e;
}
}
bool shmemLeader;
// TODO: I'm not consistent on what "header" means. Here I'm using
// "header" to mean everything that would exist in memory if we
// started to build the Ebwt but stopped short of the build*() step
// (i.e. everything up to and including join()).
if(justHeader) return;
this->_nFrag = readIndex<index_t>(in5, switchEndian);
bytesRead += sizeof(index_t);
if(this->_verbose || startVerbose) {
cerr << "Reading rstarts (" << this->_nFrag*3 << "): ";
logTime(cerr);
}
assert_geq(this->_nFrag, this->_nPat);
this->_rstarts.reset();
if(loadRstarts) {
if(this->_useMm) {
#ifdef BOWTIE_MM
this->_rstarts.init((index_t*)(mmFile[0] + bytesRead), this->_nFrag*3, false);
bytesRead += this->_nFrag*sizeof(index_t)*3;
fseek(in5, this->_nFrag*sizeof(index_t)*3, SEEK_CUR);
#endif
} else {
this->_rstarts.init(new index_t[this->_nFrag*3], this->_nFrag*3, true);
if(switchEndian) {
for(index_t i = 0; i < this->_nFrag*3; i += 3) {
// fragment starting position in joined reference
// string, text id, and fragment offset within text
this->rstarts()[i] = readIndex<index_t>(in5, switchEndian);
this->rstarts()[i+1] = readIndex<index_t>(in5, switchEndian);
this->rstarts()[i+2] = readIndex<index_t>(in5, switchEndian);
}
} else {
size_t r = MM_READ(in5, (void *)this->rstarts(), this->_nFrag*sizeof(index_t)*3);
if(r != (size_t)(this->_nFrag*sizeof(index_t)*3)) {
cerr << "Error reading _rstarts[] array: " << r << ", " << (this->_nFrag*sizeof(index_t)*3) << endl;
throw 1;
}
}
}
} else {
// Skip em
assert(this->rstarts() == NULL);
bytesRead += this->_nFrag*sizeof(index_t)*3;
fseek(in5, this->_nFrag*sizeof(index_t)*3, SEEK_CUR);
}
this->_ebwt.reset();
if(this->_useMm) {
#ifdef BOWTIE_MM
this->_ebwt.init((uint8_t*)(mmFile[0] + bytesRead), this->_eh._ebwtTotLen, false);
bytesRead += this->_eh._ebwtTotLen;
fseek(in5, this->_eh._ebwtTotLen, SEEK_CUR);
#endif
} else {
// Allocate ebwt (big allocation)
if(this->_verbose || startVerbose) {
cerr << "Reading ebwt (" << this->_eh._ebwtTotLen << "): ";
logTime(cerr);
}
bool shmemLeader = true;
if(this->useShmem_) {
uint8_t *tmp = NULL;
shmemLeader = ALLOC_SHARED_U8(
(this->_in1Str + "[ebwt]"), this->_eh._ebwtTotLen, &tmp,
"ebwt[]", (this->_verbose || startVerbose));
assert(tmp != NULL);
this->_ebwt.init(tmp, this->_eh._ebwtTotLen, false);
if(this->_verbose || startVerbose) {
cerr << " shared-mem " << (shmemLeader ? "leader" : "follower") << endl;
}
} else {
try {
this->_ebwt.init(new uint8_t[this->_eh._ebwtTotLen], this->_eh._ebwtTotLen, true);
} catch(bad_alloc& e) {
cerr << "Out of memory allocating the ebwt[] array for the Bowtie index. Please try" << endl
<< "again on a computer with more memory." << endl;
throw 1;
}
}
if(shmemLeader) {
// Read ebwt from primary stream
uint64_t bytesLeft = this->_eh._ebwtTotLen;
char *pebwt = (char*)this->ebwt();
while (bytesLeft>0){
size_t r = MM_READ(in5, (void *)pebwt, bytesLeft);
if(MM_IS_IO_ERR(in5, r, bytesLeft)) {
cerr << "Error reading _ebwt[] array: " << r << ", "
<< bytesLeft << endl;
throw 1;
}
pebwt += r;
bytesLeft -= r;
}
if(switchEndian) {
uint8_t *side = this->ebwt();
for(size_t i = 0; i < this->_eh._numSides; i++) {
index_t *cums = reinterpret_cast<index_t*>(side + this->_eh._sideSz - sizeof(index_t)*2);
cums[0] = endianSwapIndex(cums[0]);
cums[1] = endianSwapIndex(cums[1]);
side += this->_eh._sideSz;
}
}
#ifdef BOWTIE_SHARED_MEM
if(useShmem_) NOTIFY_SHARED(this->ebwt(), this->_eh._ebwtTotLen);
#endif
} else {
// Seek past the data and wait until master is finished
fseek(in5, this->_eh._ebwtTotLen, SEEK_CUR);
#ifdef BOWTIE_SHARED_MEM
if(useShmem_) WAIT_SHARED(this->ebwt(), this->_eh._ebwtTotLen);
#endif
}
}
// Read zOff from primary stream
this->_zOff = readIndex<index_t>(in5, switchEndian);
bytesRead += sizeof(index_t);
assert_lt(this->_zOff, len);
try {
// Read fchr from primary stream
if(this->_verbose || startVerbose) cerr << "Reading fchr (5)" << endl;
this->_fchr.reset();
if(this->_useMm) {
#ifdef BOWTIE_MM
this->_fchr.init((index_t*)(mmFile[0] + bytesRead), 5, false);
bytesRead += 5*sizeof(index_t);
fseek(in5, 5*sizeof(index_t), SEEK_CUR);
#endif
} else {
this->_fchr.init(new index_t[5], 5, true);
for(index_t i = 0; i < 5; i++) {
this->fchr()[i] = readIndex<index_t>(in5, switchEndian);
assert_leq(this->fchr()[i], len);
assert(i <= 0 || this->fchr()[i] >= this->fchr()[i-1]);
}
}
assert_gt(this->fchr()[4], this->fchr()[0]);
// Read ftab from primary stream
if(this->_verbose || startVerbose) {
if(loadFtab) {
cerr << "Reading ftab (" << this->_eh._ftabLen << "): ";
logTime(cerr);
} else {
cerr << "Skipping ftab (" << this->_eh._ftabLen << "): ";
}
}
this->_ftab.reset();
if(loadFtab) {
if(this->_useMm) {
#ifdef BOWTIE_MM
this->_ftab.init((index_t*)(mmFile[0] + bytesRead), this->_eh._ftabLen, false);
bytesRead += this->_eh._ftabLen*sizeof(index_t);
fseek(in5, this->_eh._ftabLen*sizeof(index_t), SEEK_CUR);
#endif
} else {
this->_ftab.init(new index_t[this->_eh._ftabLen], this->_eh._ftabLen, true);
if(switchEndian) {
for(uint32_t i = 0; i < this->_eh._ftabLen; i++)
this->ftab()[i] = readIndex<index_t>(in5, switchEndian);
} else {
size_t r = MM_READ(in5, (void *)this->ftab(), this->_eh._ftabLen*sizeof(index_t));
if(r != (size_t)(this->_eh._ftabLen*sizeof(index_t))) {
cerr << "Error reading _ftab[] array: " << r << ", " << (this->_eh._ftabLen*sizeof(index_t)) << endl;
throw 1;
}
}
}
// Read etab from primary stream
if(this->_verbose || startVerbose) {
if(loadFtab) {
cerr << "Reading eftab (" << this->_eh._eftabLen << "): ";
logTime(cerr);
} else {
cerr << "Skipping eftab (" << this->_eh._eftabLen << "): ";
}
}
this->_eftab.reset();
if(this->_useMm) {
#ifdef BOWTIE_MM
this->_eftab.init((index_t*)(mmFile[0] + bytesRead), this->_eh._eftabLen, false);
bytesRead += this->_eh._eftabLen*sizeof(index_t);
fseek(in5, this->_eh._eftabLen*sizeof(index_t), SEEK_CUR);
#endif
} else {
this->_eftab.init(new index_t[this->_eh._eftabLen], this->_eh._eftabLen, true);
if(switchEndian) {
for(uint32_t i = 0; i < this->_eh._eftabLen; i++)
this->eftab()[i] = readIndex<index_t>(in5, switchEndian);
} else {
size_t r = MM_READ(in5, (void *)this->eftab(), this->_eh._eftabLen*sizeof(index_t));
if(r != (size_t)(this->_eh._eftabLen*sizeof(index_t))) {
cerr << "Error reading _eftab[] array: " << r << ", " << (this->_eh._eftabLen*sizeof(index_t)) << endl;
throw 1;
}
}
}
for(uint32_t i = 0; i < this->_eh._eftabLen; i++) {
if(i > 0 && this->eftab()[i] > 0) {
assert_geq(this->eftab()[i], this->eftab()[i-1]);
} else if(i > 0 && this->eftab()[i-1] == 0) {
assert_eq(0, this->eftab()[i]);
}
}
} else {
assert(this->ftab() == NULL);
assert(this->eftab() == NULL);
// Skip ftab
bytesRead += this->_eh._ftabLen*sizeof(index_t);
fseek(in5, this->_eh._ftabLen*sizeof(index_t), SEEK_CUR);
// Skip eftab
bytesRead += this->_eh._eftabLen*sizeof(index_t);
fseek(in5, this->_eh._eftabLen*sizeof(index_t), SEEK_CUR);
}
} catch(bad_alloc& e) {
cerr << "Out of memory allocating fchr[], ftab[] or eftab[] arrays for the Bowtie index." << endl
<< "Please try again on a computer with more memory." << endl;
throw 1;
}
this->_offs.reset();
if(loadSASamp) {
bytesRead = 4; // reset for secondary index file (already read 1-sentinel)
shmemLeader = true;
if(this->_verbose || startVerbose) {
cerr << "Reading offs (" << offsLenSampled << " " << std::setw(2) << sizeof(index_t)*8 << "-bit words): ";
logTime(cerr);
}
if(!this->_useMm) {
if(!this->useShmem_) {
// Allocate offs_
try {
this->_offs.init(new index_t[offsLenSampled], offsLenSampled, true);
} catch(bad_alloc& e) {
cerr << "Out of memory allocating the offs[] array for the Bowtie index." << endl
<< "Please try again on a computer with more memory." << endl;
throw 1;
}
} else {
index_t *tmp = NULL;
shmemLeader = ALLOC_SHARED_U32(
(this->_in2Str + "[offs]"), offsLenSampled*2, &tmp,
"offs", (this->_verbose || startVerbose));
this->_offs.init((index_t*)tmp, offsLenSampled, false);
}
}
if(this->_overrideOffRate < 32) {
if(shmemLeader) {
// Allocate offs (big allocation)
if(switchEndian || offRateDiff > 0) {
assert(!this->_useMm);
const uint32_t blockMaxSz = (2 * 1024 * 1024); // 2 MB block size
const uint32_t blockMaxSzUIndex = (blockMaxSz / sizeof(index_t)); // # UIndexs per block
char *buf;
try {
buf = new char[blockMaxSz];
} catch(std::bad_alloc& e) {
cerr << "Error: Out of memory allocating part of _offs array: '" << e.what() << "'" << endl;
throw e;
}
for(index_t i = 0; i < offsLen; i += blockMaxSzUIndex) {
index_t block = min<index_t>((index_t)blockMaxSzUIndex, (index_t)(offsLen - i));
size_t r = MM_READ(in6, (void *)buf, block * sizeof(index_t));