forked from DaehwanKimLab/hisat2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hgfm.h
2653 lines (2513 loc) · 102 KB
/
hgfm.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 2015, Daehwan Kim <[email protected]>
*
* This file is part of HISAT 2.
*
* HISAT 2 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.
*
* HISAT 2 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 HISAT 2. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef HGFM_H_
#define HGFM_H_
#include "hier_idx_common.h"
#include "gfm.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 LocalGFM : public GFM<index_t> {
typedef GFM<index_t> PARENT_CLASS;
public:
/// Construct an Ebwt from the given input file
LocalGFM(const string& in,
ALTDB<index_t>* altdb,
FILE *in5,
FILE *in6,
char *mmFile5,
char *mmFile6,
full_index_t& tidx,
full_index_t& localOffset,
full_index_t& joinedOffset,
bool switchEndian,
size_t& bytesRead,
size_t& bytesRead2,
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)
bool useHaplotype) : // = false
GFM<index_t>(in,
altdb,
NULL,
NULL,
needEntireReverse,
fw,
overrideOffRate,
offRatePlus,
useMm,
useShmem,
mmSweep,
loadNames,
loadSASamp,
loadFtab,
loadRstarts,
true, // load Splice Sites
verbose,
startVerbose,
passMemExc,
sanityCheck,
useHaplotype,
true)
{
this->_in1Str = in + ".5." + gfm_ext;
this->_in2Str = in + ".5." + gfm_ext;
readIntoMemory(
in5,
in6,
mmFile5,
mmFile6,
tidx,
localOffset,
joinedOffset,
switchEndian,
bytesRead,
bytesRead2,
needEntireReverse,
loadSASamp,
loadFtab,
loadRstarts,
false, //justHeader
lineRate,
offRate,
ftabChars,
mmSweep,
loadNames,
startVerbose);
_tidx = tidx;
_localOffset = localOffset;
_joinedOffset = joinedOffset;
// If the offRate has been overridden, reflect that in the
// _eh._offRate field
if(offRatePlus > 0 && this->_overrideOffRate == -1) {
this->_overrideOffRate = this->_gh._offRate + offRatePlus;
}
if(this->_overrideOffRate > this->_gh._offRate) {
this->_gh.setOffRate(this->_overrideOffRate);
assert_eq(this->_overrideOffRate, this->_gh._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>
LocalGFM(
TStr& s,
const EList<full_index_t>& sa,
PathGraph<full_index_t>* pg,
full_index_t tidx,
full_index_t localOffset,
full_index_t joinedOffset,
EList<ALT<full_index_t> >& alts,
index_t local_size,
bool packed,
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) :
GFM<index_t>(packed,
needEntireReverse,
lineRate,
offRate,
ftabChars,
file,
fw,
dcv,
szs,
sztot,
refparams,
seed,
overrideOffRate,
verbose,
passMemExc,
sanityCheck)
{
const GFMParams<index_t>& gh = this->_gh;
assert(gh.repOk());
uint32_t be = this->toBe();
assert(out5.good());
assert(out6.good());
_tidx = tidx;
_localOffset = localOffset;
_joinedOffset = joinedOffset;
writeIndex<full_index_t>(out5, tidx, be);
writeIndex<full_index_t>(out5, localOffset, be);
writeIndex<full_index_t>(out5, joinedOffset, be);
writeIndex<index_t>(out5, gh._len, be); // length of string (and bwt and suffix array)
streampos headerPos = out5.tellp();
writeIndex<index_t>(out5, 0, be); // gbwtLen
writeIndex<index_t>(out5, 0, be); // num of nodes
writeIndex<index_t>(out5, 0, be); // eftabLen
if(gh._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);
}
if(alts.empty()) {
assert(pg == NULL);
buildToDisk(sa, s, out5, out6, headerPos);
} else {
assert(pg != NULL);
// Re-initialize GFM parameters to reflect real number of edges (gbwt string)
this->_gh.init(
this->_gh.len(),
pg->getNumEdges(),
pg->getNumNodes(),
this->_gh.lineRate(),
this->_gh.offRate(),
this->_gh.ftabChars(),
0,
this->_gh.entireReverse());
buildToDisk(*pg, s, out5, out6, headerPos);
}
}
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(
PathGraph<full_index_t>& gbwt,
const TStr& s,
ostream& out1,
ostream& out2,
streampos headerPos);
template <typename TStr> void buildToDisk(
const EList<full_index_t>& sa,
const TStr& s,
ostream& out1,
ostream& out2,
streampos headerPos);
// I/O
void readIntoMemory(
FILE *in5,
FILE *in6,
char *mmFile5,
char *mmFile6,
full_index_t& tidx,
full_index_t& localOffset,
full_index_t& joinedOffset,
bool switchEndian,
size_t& bytesRead,
size_t& bytesRead2,
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->_gh._len > 0) {
PARENT_CLASS::sanityCheckAll(reverse);
}
}
bool empty() const { return this->_gh._len == 0; }
public:
full_index_t _tidx;
full_index_t _localOffset;
full_index_t _joinedOffset;
};
/**
* 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 LocalGFM<index_t, full_index_t>::buildToDisk(
PathGraph<full_index_t>& gbwt,
const TStr& s,
ostream& out5,
ostream& out6,
streampos headerPos)
{
assert_leq(s.length(), std::numeric_limits<index_t>::max());
const GFMParams<index_t>& gh = this->_gh;
assert(gh.repOk());
assert_lt(s.length(), gh.gbwtLen());
assert_eq(s.length(), gh._len);
assert_gt(gh._lineRate, 3);
index_t gbwtLen = gh._gbwtLen;
streampos out5pos = out5.tellp();
out5.seekp(headerPos);
writeIndex<index_t>(out5, gbwtLen, this->toBe());
writeIndex<index_t>(out5, gh._numNodes, this->toBe());
headerPos = out5.tellp();
out5.seekp(out5pos);
index_t ftabLen = gh._ftabLen;
index_t sideSz = gh._sideSz;
index_t gbwtTotSz = gh._gbwtTotSz;
index_t fchr[] = {0, 0, 0, 0, 0};
EList<index_t> ftab(EBWT_CAT);
EList<index_t> zOffs;
// 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};
// # of occurrences of 1 in M arrays
index_t M_occ = 0, M_occSave = 0;
// Location in F that corresponds to 1 in M
index_t F_loc = 0, F_locSave = 0;
try {
VMSG_NL("Allocating ftab, absorbFtab");
ftab.resize(ftabLen);
ftab.fillZero();
} catch(bad_alloc &e) {
cerr << "Out of memory allocating ftab[] or absorbFtab[] "
<< "in LocalGFM::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> gfmSide(EBWT_CAT);
#else
EList<uint8_t> gfmSide(EBWT_CAT);
#endif
try {
// Used to calculate ftab and eftab, but having gfm costs a lot of memory
this->_gfm.init(new uint8_t[gh._gbwtTotLen], gh._gbwtTotLen, true);
#ifdef SIXTY4_FORMAT
gfmSide.resize(sideSz >> 3);
#else
gfmSide.resize(sideSz);
#endif
} catch(bad_alloc &e) {
cerr << "Out of memory allocating ebwtSide[] in "
<< "LocalGFM::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 = true;
int sideCur = 0;
index_t si = 0; // string offset (chars)
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 LocalGFM loop");
ASSERT_ONLY(uint32_t beforeGbwtOff = (uint32_t)out5.tellp());
while(side < gbwtTotSz) {
// Sanity-check our cursor into the side buffer
assert_geq(sideCur, 0);
assert_lt(sideCur, (int)gh._sideGbwtSz);
assert_eq(0, side % sideSz); // 'side' must be on side boundary
gfmSide[sideCur] = 0; // clear
if(sideCur == 0) {
memset(gfmSide.ptr(), 0, gh._sideGbwtSz);
gfmSide[sideCur] = 0; // clear
}
assert_lt(side + sideCur, gbwtTotSz);
// 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 gbwtChar = 0;
int F = 0, M = 0;
full_index_t pos = 0;
bool count = true;
if(si < gbwtLen) {
gbwt.nextRow(gbwtChar, F, M, pos);
// (that might have triggered sa to calc next suf block)
if(gbwtChar == 'Z') {
// 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
gbwtChar = 0; count = false;
#ifndef NDEBUG
if(zOffs.size() > 0) {
assert_gt(si, zOffs.back());
}
#endif
zOffs.push_back(si); // remember GBWT row that corresponds to the 0th suffix
} else {
gbwtChar = asc2dna[gbwtChar];
assert_lt(gbwtChar, 4);
// Update the fchr
fchr[gbwtChar]++;
}
assert_lt(F, 2);
assert_lt(M, 2);
if(M == 1) {
assert_neq(F_loc, numeric_limits<index_t>::max());
F_loc = gbwt.nextFLocation();
#ifndef NDEBUG
if(F_loc > 0) {
assert_gt(F_loc, F_locSave);
}
#endif
}
// Suffix array offset boundary? - update offset array
if(M == 1 && (M_occ & gh._offMask) == M_occ) {
assert_lt((M_occ >> gh._offRate), gh._offsLen);
// Write offsets directly to the secondary output
// stream, thereby avoiding keeping them in memory
writeIndex<index_t>(out6, pos, 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, gbwtLen);
inSA = false;
}
#endif
// 'A' used for padding; important that padding be
// counted in the occ[] array
gbwtChar = 0;
F = M = 0;
}
if(count) occ[gbwtChar]++;
if(M) M_occ++;
// Append BWT char to bwt section of current side
if(fw) {
// Forward bucket: fill from least to most
#ifdef SIXTY4_FORMAT
gfmSide[sideCur] |= ((uint64_t)gbwtChar << (bpi << 1));
if(gbwtChar > 0) assert_gt(gfmSide[sideCur], 0);
assert(false);
cerr << "Not implemented" << endl;
exit(1);
#else
pack_2b_in_8b(gbwtChar, gfmSide[sideCur], bpi);
assert_eq((gfmSide[sideCur] >> (bpi*2)) & 3, gbwtChar);
int F_sideCur = (gh._sideGbwtSz + sideCur) >> 1;
int F_bpi = bpi + ((sideCur & 0x1) << 2); // Can be used as M_bpi as well
pack_1b_in_8b(F, gfmSide[F_sideCur], F_bpi);
assert_eq((gfmSide[F_sideCur] >> F_bpi) & 1, F);
int M_sideCur = F_sideCur + (gh._sideGbwtSz >> 2);
pack_1b_in_8b(M, gfmSide[M_sideCur], F_bpi);
assert_eq((gfmSide[M_sideCur] >> F_bpi) & 1, M);
#endif
} else {
// Backward bucket: fill from most to least
#ifdef SIXTY4_FORMAT
gfmSide[sideCur] |= ((uint64_t)gbwtChar << ((31 - bpi) << 1));
if(gbwtChar > 0) assert_gt(gfmSide[sideCur], 0);
// To be implemented ...
assert(false);
cerr << "Not implemented" << endl;
exit(1);
#else
pack_2b_in_8b(gbwtChar, gfmSide[sideCur], 3-bpi);
assert_eq((gfmSide[sideCur] >> ((3-bpi)*2)) & 3, gbwtChar);
// To be implemented ...
assert(false);
cerr << "Not implemented" << endl;
exit(1);
#endif
}
} // end loop over bit-pairs
assert_eq(0, (occ[0] + occ[1] + occ[2] + occ[3] + zOffs.size()) & 3);
#ifdef SIXTY4_FORMAT
assert_eq(0, si & 31);
#else
assert_eq(0, si & 3);
#endif
sideCur++;
if((sideCur << 1) == (int)gh._sideGbwtSz) {
sideCur = 0;
index_t *uside = reinterpret_cast<index_t*>(gfmSide.ptr());
// Write 'A', 'C', 'G' and 'T' tallies
side += sideSz;
assert_leq(side, gh._gbwtTotSz);
uside[(sideSz / sizeof(index_t))-6] = endianizeIndex(F_locSave, this->toBe());
uside[(sideSz / sizeof(index_t))-5] = endianizeIndex(M_occSave, this->toBe());
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());
F_locSave = F_loc;
M_occSave = M_occ;
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 *)gfmSide.ptr(), sideSz);
//
memcpy(((char*)this->_gfm.get()) + side - sideSz, (const char *)gfmSide.ptr(), sideSz);
}
}
VMSG_NL("Exited LocalGFM loop");
// Assert that our loop counter got incremented right to the end
assert_eq(side, gh._gbwtTotSz);
// Assert that we wrote the expected amount to out5
assert_eq(((uint32_t)out5.tellp() - beforeGbwtOff), gh._gbwtTotSz);
// assert that the last thing we did was write a forward bucket
//
// Write zOffs to primary stream
//
assert_gt(zOffs.size(), 0);
writeIndex<index_t>(out5, zOffs.size(), this->toBe());
for(size_t i = 0; i < zOffs.size(); i++) {
writeIndex<index_t>(out5, zOffs[i], this->toBe());
}
//
// Finish building fchr
//
// Exclusive prefix sum on fchr
for(int i = 1; i < 4; i++) {
fchr[i] += fchr[i-1];
}
assert_lt(fchr[3], gbwtLen);
// Shift everybody up by one
for(int i = 4; i >= 1; i--) {
fchr[i] = fchr[i-1];
}
fchr[0] = 0;
// Write fchr to primary file
for(int i = 0; i < 5; i++) {
writeIndex<index_t>(out5, fchr[i], this->toBe());
}
this->_fchr.init(new index_t[5], 5, true);
memcpy(this->_fchr.get(), fchr, sizeof(index_t) * 5);
// Initialize _zGbwtByteOffs and _zGbwtBpOffs
this->_zOffs = zOffs;
this->postReadInit(gh);
// Build ftab and eftab
EList<pair<index_t, index_t> > tFtab;
tFtab.resizeExact(ftabLen - 1);
for(index_t i = 0; i + 1 < ftabLen; i++) {
index_t q = i;
pair<index_t, index_t> range(0, gh._gbwtLen);
SideLocus<index_t> tloc, bloc;
SideLocus<index_t>::initFromTopBot(range.first, range.second, gh, this->gfm(), tloc, bloc);
index_t j = 0;
for(; j < gh._ftabChars; j++) {
int nt = q & 0x3; q >>= 2;
if(bloc.valid()) {
range = this->mapGLF(tloc, bloc, nt);
} else {
range = this->mapGLF1(range.first, tloc, nt);
}
if(range.first == (index_t)INDEX_MAX || range.first >= range.second) {
break;
}
if(range.first + 1 == range.second) {
tloc.initFromRow(range.first, gh, this->gfm());
bloc.invalidate();
} else {
SideLocus<index_t>::initFromTopBot(range.first, range.second, gh, this->gfm(), tloc, bloc);
}
}
if(range.first >= range.second || j < gh._ftabChars) {
if(i == 0) {
tFtab[i].first = tFtab[i].second = 0;
} else {
tFtab[i].first = tFtab[i].second = tFtab[i-1].second;
}
} else {
tFtab[i].first = range.first;
tFtab[i].second = range.second;
}
#ifndef NDEBUG
if(gbwt.ftab.size() > i) {
assert_eq(tFtab[i].first, gbwt.ftab[i].first);
assert_eq(tFtab[i].second, gbwt.ftab[i].second);
}
#endif
}
// Clear memory
this->_gfm.reset();
this->_fchr.reset();
this->_zOffs.clear();
this->_zGbwtByteOffs.clear();
this->_zGbwtBpOffs.clear();
//
// Finish building ftab and build eftab
//
// Prefix sum on ftable
index_t eftabLen = 0;
for(index_t i = 1; i + 1 < ftabLen; i++) {
if(tFtab[i-1].second != tFtab[i].first) {
eftabLen += 2;
}
}
if(gh._gbwtLen + (eftabLen >> 1) < gh._gbwtLen) {
cerr << "Too many eftab entries: "
<< gh._gbwtLen << " + " << (eftabLen >> 1)
<< " > " << (index_t)INDEX_MAX << endl;
throw 1;
}
EList<index_t> eftab(EBWT_CAT);
try {
eftab.resize(eftabLen);
eftab.fillZero();
} catch(bad_alloc &e) {
cerr << "Out of memory allocating eftab[] "
<< "in LocalGFM::buildToDisk() at " << __FILE__ << ":"
<< __LINE__ << endl;
throw e;
}
index_t eftabCur = 0;
ftab[0] = tFtab[0].first;
ftab[1] = tFtab[0].second;
for(index_t i = 1; i + 1 < ftabLen; i++) {
if(ftab[i] != tFtab[i].first) {
index_t lo = ftab[i];
index_t hi = tFtab[i].first;
assert_lt(eftabCur*2+1, eftabLen);
eftab[eftabCur*2] = lo;
eftab[eftabCur*2+1] = hi;
assert_leq(lo, hi + 4);
ftab[i] = (eftabCur++) ^ (index_t)INDEX_MAX; // insert pointer into eftab
assert_eq(lo, GFM<index_t>::ftabLo(ftab.ptr(), eftab.ptr(), gbwtLen, ftabLen, eftabLen, i));
assert_eq(hi, GFM<index_t>::ftabHi(ftab.ptr(), eftab.ptr(), gbwtLen, ftabLen, eftabLen, i));
}
ftab[i+1] = tFtab[i].second;
}
#ifndef NDEBUG
for(index_t i = 0; i + 1 < ftabLen; i++ ){
assert_eq(tFtab[i].first, GFM<index_t>::ftabHi(ftab.ptr(), eftab.ptr(), gbwtLen, ftabLen, eftabLen, i));
assert_eq(tFtab[i].second, GFM<index_t>::ftabLo(ftab.ptr(), eftab.ptr(), gbwtLen, ftabLen, eftabLen, i+1));
}
#endif
// Write ftab to primary file
for(index_t i = 0; i < ftabLen; i++) {
writeIndex<index_t>(out5, ftab[i], this->toBe());
}
// Write eftab to primary file
out5pos = out5.tellp();
out5.seekp(headerPos);
writeIndex<index_t>(out5, eftabLen, this->toBe());
out5.seekp(out5pos);
for(index_t i = 0; i < eftabLen; i++) {
writeIndex<index_t>(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 LocalGFM::buildToDisk()");
}
/**
* 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 LocalGFM<index_t, full_index_t>::buildToDisk(
const EList<full_index_t>& sa,
const TStr& s,
ostream& out5,
ostream& out6,
streampos headerPos)
{
assert_leq(s.length(), std::numeric_limits<index_t>::max());
const GFMParams<index_t>& gh = this->_gh;
assert(gh.repOk());
assert(gh.linearFM());
assert_lt(s.length(), gh.gbwtLen());
assert_eq(s.length(), gh._len);
assert_gt(gh._lineRate, 3);
index_t len = gh._len;
index_t gbwtLen = gh._gbwtLen;
assert_eq(len + 1, gbwtLen);
streampos out5pos = out5.tellp();
out5.seekp(headerPos);
writeIndex<index_t>(out5, gbwtLen, this->toBe());
writeIndex<index_t>(out5, gh._numNodes, this->toBe());
headerPos = out5.tellp();
out5.seekp(out5pos);
index_t ftabLen = gh._ftabLen;
index_t sideSz = gh._sideSz;
index_t gbwtTotSz = gh._gbwtTotSz;
index_t fchr[] = {0, 0, 0, 0, 0};
EList<index_t> ftab(EBWT_CAT);
EList<index_t> zOffs;
// 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 LocalGFM::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> gfmSide(EBWT_CAT);
#else
EList<uint8_t> gfmSide(EBWT_CAT);
#endif
try {
#ifdef SIXTY4_FORMAT
gfmSide.resize(sideSz >> 3);
#else
gfmSide.resize(sideSz);
#endif
} catch(bad_alloc &e) {
cerr << "Out of memory allocating gfmSide[] in "
<< "LocalGFM::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 = true;
int sideCur = 0;
// 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 LocalGFM loop");
ASSERT_ONLY(uint32_t beforeGbwtOff = (uint32_t)out5.tellp());
while(side < gbwtTotSz) {
// Sanity-check our cursor into the side buffer
assert_geq(sideCur, 0);
assert_lt(sideCur, (int)gh._sideGbwtSz);
assert_eq(0, side % sideSz); // 'side' must be on side boundary
gfmSide[sideCur] = 0; // clear
assert_lt(side + sideCur, gbwtTotSz);
// 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[si];
// (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);
zOffs.push_back(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)gh._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 < gh._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 & gh._offMask) == si) {
assert_lt((si >> gh._offRate), gh._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
gfmSide[sideCur] |= ((uint64_t)bwtChar << (bpi << 1));
if(bwtChar > 0) assert_gt(gfmSide[sideCur], 0);
#else
pack_2b_in_8b(bwtChar, gfmSide[sideCur], bpi);
assert_eq((gfmSide[sideCur] >> (bpi*2)) & 3, bwtChar);
#endif
} else {
// Backward bucket: fill from most to least
#ifdef SIXTY4_FORMAT
gfmSide[sideCur] |= ((uint64_t)bwtChar << ((31 - bpi) << 1));
if(bwtChar > 0) assert_gt(gfmSide[sideCur], 0);
#else
pack_2b_in_8b(bwtChar, gfmSide[sideCur], 3-bpi);
assert_eq((gfmSide[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)gh._sideGbwtSz) {
sideCur = 0;
index_t *uside = reinterpret_cast<index_t*>(gfmSide.ptr());
// Write 'A', 'C', 'G' and 'T' tallies
side += sideSz;
assert_leq(side, gh._gbwtTotSz);
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];