forked from BenLangmead/bowtie2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bt2_idx.h
3084 lines (2936 loc) · 94.3 KB
/
bt2_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 2011, Ben Langmead <langmea@cs.jhu.edu>
*
* This file is part of Bowtie 2.
*
* Bowtie 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.
*
* Bowtie 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 Bowtie 2. If not, see <http://www.gnu.org/licenses/>.
*/
#ifndef EBWT_H_
#define EBWT_H_
#include <stdint.h>
#include <string.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
#include <fcntl.h>
#include <math.h>
#include <errno.h>
#include <stdexcept>
#include <sys/stat.h>
#ifdef BOWTIE_MM
#include <sys/mman.h>
#include <sys/shm.h>
#endif
#include "shmem.h"
#include "alphabet.h"
#include "assert_helpers.h"
#include "bitpack.h"
#include "blockwise_sa.h"
#include "endian_swap.h"
#include "word_io.h"
#include "random_source.h"
#include "ref_read.h"
#include "threading.h"
#include "str_util.h"
#include "mm.h"
#include "timer.h"
#include "reference.h"
#include "search_globals.h"
#include "ds.h"
#include "random_source.h"
#include "mem_ids.h"
#include "btypes.h"
#ifdef POPCNT_CAPABILITY
#include "processor_support.h"
#endif
using namespace std;
// From ccnt_lut.cpp, automatically generated by gen_lookup_tables.pl
extern uint8_t cCntLUT_4[4][4][256];
static const uint64_t c_table[4] = {
0xffffffffffffffff,
0xaaaaaaaaaaaaaaaa,
0x5555555555555555,
0x0000000000000000
};
#ifndef VMSG_NL
#define VMSG_NL(...) \
if(this->verbose()) { \
stringstream tmp; \
tmp << __VA_ARGS__ << endl; \
this->verbose(tmp.str()); \
}
#endif
#ifndef VMSG
#define VMSG(...) \
if(this->verbose()) { \
stringstream tmp; \
tmp << __VA_ARGS__; \
this->verbose(tmp.str()); \
}
#endif
/**
* Flags describing type of Ebwt.
*/
enum EBWT_FLAGS {
EBWT_COLOR = 2, // true -> Ebwt is colorspace
EBWT_ENTIRE_REV = 4 // true -> reverse Ebwt is the whole
// concatenated string reversed, rather than
// each stretch reversed
};
/**
* Extended Burrows-Wheeler transform header. This together with the
* actual data arrays and other text-specific parameters defined in
* class Ebwt constitute the entire Ebwt.
*/
class EbwtParams {
public:
EbwtParams() { }
EbwtParams(
TIndexOffU len,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
bool color,
bool entireReverse)
{
init(len, lineRate, offRate, ftabChars, color, entireReverse);
}
EbwtParams(const EbwtParams& eh) {
init(eh._len, eh._lineRate, eh._offRate,
eh._ftabChars, eh._color, eh._entireReverse);
}
void init(
TIndexOffU len,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
bool color,
bool entireReverse)
{
_color = color;
_entireReverse = entireReverse;
_len = len;
_bwtLen = _len + 1;
_sz = (len+3)/4;
_bwtSz = (len/4 + 1);
_lineRate = lineRate;
_origOffRate = offRate;
_offRate = offRate;
_offMask = OFF_MASK << _offRate;
_ftabChars = ftabChars;
_eftabLen = _ftabChars*2;
_eftabSz = _eftabLen*OFF_SIZE;
_ftabLen = (1 << (_ftabChars*2))+1;
_ftabSz = _ftabLen*OFF_SIZE;
_offsLen = (_bwtLen + (1 << _offRate) - 1) >> _offRate;
_offsSz = (uint64_t)_offsLen*OFF_SIZE;
_lineSz = 1 << _lineRate;
_sideSz = _lineSz * 1 /* lines per side */;
_sideBwtSz = _sideSz - OFF_SIZE*4;
_sideBwtLen = _sideBwtSz*4;
_numSides = (_bwtSz+(_sideBwtSz)-1)/(_sideBwtSz);
_numLines = _numSides * 1 /* lines per side */;
_ebwtTotLen = _numSides * _sideSz;
_ebwtTotSz = _ebwtTotLen;
assert(repOk());
}
TIndexOffU len() const { return _len; }
TIndexOffU lenNucs() const { return _len + (_color ? 1 : 0); }
TIndexOffU bwtLen() const { return _bwtLen; }
TIndexOffU sz() const { return _sz; }
TIndexOffU bwtSz() const { return _bwtSz; }
int32_t lineRate() const { return _lineRate; }
int32_t origOffRate() const { return _origOffRate; }
int32_t offRate() const { return _offRate; }
TIndexOffU offMask() const { return _offMask; }
int32_t ftabChars() const { return _ftabChars; }
int32_t eftabLen() const { return _eftabLen; }
int32_t eftabSz() const { return _eftabSz; }
TIndexOffU ftabLen() const { return _ftabLen; }
TIndexOffU ftabSz() const { return _ftabSz; }
TIndexOffU offsLen() const { return _offsLen; }
uint64_t offsSz() const { return _offsSz; }
int32_t lineSz() const { return _lineSz; }
int32_t sideSz() const { return _sideSz; }
int32_t sideBwtSz() const { return _sideBwtSz; }
int32_t sideBwtLen() const { return _sideBwtLen; }
TIndexOffU numSides() const { return _numSides; }
TIndexOffU numLines() const { return _numLines; }
TIndexOffU ebwtTotLen() const { return _ebwtTotLen; }
TIndexOffU ebwtTotSz() const { return _ebwtTotSz; }
bool color() const { return _color; }
bool entireReverse() const { return _entireReverse; }
/**
* Set a new suffix-array sampling rate, which involves updating
* rate, mask, sample length, and sample size.
*/
void setOffRate(int __offRate) {
_offRate = __offRate;
_offMask = OFF_MASK << _offRate;
_offsLen = (_bwtLen + (1 << _offRate) - 1) >> _offRate;
_offsSz = (uint64_t)_offsLen * OFF_SIZE;
}
#ifndef NDEBUG
/// Check that this EbwtParams is internally consistent
bool repOk() const {
assert_gt(_len, 0);
assert_gt(_lineRate, 3);
assert_geq(_offRate, 0);
assert_leq(_ftabChars, 16);
assert_geq(_ftabChars, 1);
assert_lt(_lineRate, 32);
assert_lt(_ftabChars, 32);
assert_eq(0, _ebwtTotSz % _lineSz);
return true;
}
#endif
/**
* Pretty-print the header contents to the given output stream.
*/
void print(ostream& out) const {
out << "Headers:" << endl
<< " len: " << _len << endl
<< " bwtLen: " << _bwtLen << endl
<< " sz: " << _sz << endl
<< " bwtSz: " << _bwtSz << endl
<< " lineRate: " << _lineRate << endl
<< " offRate: " << _offRate << endl
<< " offMask: 0x" << hex << _offMask << dec << endl
<< " ftabChars: " << _ftabChars << endl
<< " eftabLen: " << _eftabLen << endl
<< " eftabSz: " << _eftabSz << endl
<< " ftabLen: " << _ftabLen << endl
<< " ftabSz: " << _ftabSz << endl
<< " offsLen: " << _offsLen << endl
<< " offsSz: " << _offsSz << endl
<< " lineSz: " << _lineSz << endl
<< " sideSz: " << _sideSz << endl
<< " sideBwtSz: " << _sideBwtSz << endl
<< " sideBwtLen: " << _sideBwtLen << endl
<< " numSides: " << _numSides << endl
<< " numLines: " << _numLines << endl
<< " ebwtTotLen: " << _ebwtTotLen << endl
<< " ebwtTotSz: " << _ebwtTotSz << endl
<< " color: " << _color << endl
<< " reverse: " << _entireReverse << endl;
}
TIndexOffU _len;
TIndexOffU _bwtLen;
TIndexOffU _sz;
TIndexOffU _bwtSz;
int32_t _lineRate;
int32_t _origOffRate;
int32_t _offRate;
TIndexOffU _offMask;
int32_t _ftabChars;
uint32_t _eftabLen;
uint32_t _eftabSz;
TIndexOffU _ftabLen;
TIndexOffU _ftabSz;
TIndexOffU _offsLen;
uint64_t _offsSz;
uint32_t _lineSz;
uint32_t _sideSz;
uint32_t _sideBwtSz;
uint32_t _sideBwtLen;
TIndexOffU _numSides;
TIndexOffU _numLines;
TIndexOffU _ebwtTotLen;
TIndexOffU _ebwtTotSz;
bool _color;
bool _entireReverse;
};
/**
* Exception to throw when a file-realted error occurs.
*/
class EbwtFileOpenException : public std::runtime_error {
public:
EbwtFileOpenException(const std::string& msg = "") :
std::runtime_error(msg) { }
};
/**
* Calculate size of file with given name.
*/
static inline int64_t fileSize(const char* name) {
std::ifstream f;
f.open(name, std::ios_base::binary | std::ios_base::in);
if (!f.good() || f.eof() || !f.is_open()) { return 0; }
f.seekg(0, std::ios_base::beg);
std::ifstream::pos_type begin_pos = f.tellg();
f.seekg(0, std::ios_base::end);
return static_cast<int64_t>(f.tellg() - begin_pos);
}
/**
* Encapsulates a location in the bwt text in terms of the side it
* occurs in and its offset within the side.
*/
struct SideLocus {
SideLocus() :
_sideByteOff(0),
_sideNum(0),
_charOff(0),
_by(-1),
_bp(-1) { }
/**
* Construct from row and other relevant information about the Ebwt.
*/
SideLocus(TIndexOffU row, const EbwtParams& ep, const uint8_t* ebwt) {
initFromRow(row, ep, ebwt);
}
/**
* Init two SideLocus objects from a top/bot pair, using the result
* from one call to initFromRow to possibly avoid a second call.
*/
static void initFromTopBot(
TIndexOffU top,
TIndexOffU bot,
const EbwtParams& ep,
const uint8_t* ebwt,
SideLocus& ltop,
SideLocus& lbot)
{
const TIndexOffU sideBwtLen = ep._sideBwtLen;
assert_gt(bot, top);
ltop.initFromRow(top, ep, ebwt);
TIndexOffU spread = bot - top;
// Many cache misses on the following lines
if(ltop._charOff + spread < sideBwtLen) {
lbot._charOff = (uint32_t)(ltop._charOff + spread);
lbot._sideNum = ltop._sideNum;
lbot._sideByteOff = ltop._sideByteOff;
lbot._by = lbot._charOff >> 2;
assert_lt(lbot._by, (int)ep._sideBwtSz);
lbot._bp = lbot._charOff & 3;
} else {
lbot.initFromRow(bot, ep, ebwt);
}
}
/**
* Calculate SideLocus based on a row and other relevant
* information about the shape of the Ebwt.
*/
void initFromRow(TIndexOffU row, const EbwtParams& ep, const uint8_t* ebwt) {
const int32_t sideSz = ep._sideSz;
// Side length is hard-coded for now; this allows the compiler
// to do clever things to accelerate / and %.
_sideNum = row / (48*OFF_SIZE);
assert_lt(_sideNum, ep._numSides);
_charOff = row % (48*OFF_SIZE);
_sideByteOff = _sideNum * sideSz;
assert_leq(row, ep._len);
assert_leq(_sideByteOff + sideSz, ep._ebwtTotSz);
// Tons of cache misses on the next line
_by = _charOff >> 2; // byte within side
assert_lt(_by, (int)ep._sideBwtSz);
_bp = _charOff & 3; // bit-pair within byte
}
/**
* Transform this SideLocus to refer to the next side (i.e. the one
* corresponding to the next side downstream). Set all cursors to
* point to the beginning of the side.
*/
void nextSide(const EbwtParams& ep) {
assert(valid());
_sideByteOff += ep.sideSz();
_sideNum++;
_by = _bp = _charOff = 0;
assert(valid());
}
/**
* Return true iff this is an initialized SideLocus
*/
bool valid() const {
if(_bp != -1) {
return true;
}
return false;
}
/**
* Convert locus to BW row it corresponds to.
*/
TIndexOffU toBWRow() const {
return _sideNum * 48*OFF_SIZE + _charOff;
}
#ifndef NDEBUG
/**
* Check that SideLocus is internally consistent and consistent
* with the (provided) EbwtParams.
*/
bool repOk(const EbwtParams& ep) const {
ASSERT_ONLY(TIndexOffU row = _sideNum * 48*OFF_SIZE + _charOff);
assert_leq(row, ep._len);
assert_range(-1, 3, _bp);
assert_range(0, (int)ep._sideBwtSz, _by);
return true;
}
#endif
/// Make this look like an invalid SideLocus
void invalidate() {
_bp = -1;
}
/**
* Return a read-only pointer to the beginning of the top side.
*/
const uint8_t *side(const uint8_t* ebwt) const {
return ebwt + _sideByteOff;
}
TIndexOffU _sideByteOff; // offset of top side within ebwt[]
TIndexOffU _sideNum; // index of side
uint32_t _charOff; // character offset within side
int32_t _by; // byte within side (not adjusted for bw sides)
int32_t _bp; // bitpair within byte (not adjusted for bw sides)
};
#ifdef POPCNT_CAPABILITY // wrapping of "struct"
struct USE_POPCNT_GENERIC {
#endif
// Use this standard bit-bashing population count
inline static int pop64(uint64_t x) {
// Lots of cache misses on following lines (>10K)
x = x - ((x >> 1) & 0x5555555555555555llu);
x = (x & 0x3333333333333333llu) + ((x >> 2) & 0x3333333333333333llu);
x = (x + (x >> 4)) & 0x0F0F0F0F0F0F0F0Fllu;
x = x + (x >> 8);
x = x + (x >> 16);
x = x + (x >> 32);
return (int)(x & 0x3Fllu);
}
#ifdef POPCNT_CAPABILITY // wrapping a "struct"
};
#endif
#ifdef POPCNT_CAPABILITY
struct USE_POPCNT_INSTRUCTION {
inline static int pop64(uint64_t x) {
int64_t count;
asm ("popcnt %[x],%[count]\n": [count] "=&r" (count): [x] "r" (x));
return count;
}
};
#endif
/**
* Tricky-bit-bashing bitpair counting for given two-bit value (0-3)
* within a 64-bit argument.
*/
#ifdef POPCNT_CAPABILITY
template<typename Operation>
#endif
inline static int countInU64(int c, uint64_t dw) {
uint64_t c0 = c_table[c];
uint64_t x0 = dw ^ c0;
uint64_t x1 = (x0 >> 1);
uint64_t x2 = x1 & (0x5555555555555555);
uint64_t x3 = x0 & x2;
#ifdef POPCNT_CAPABILITY
uint64_t tmp = Operation().pop64(x3);
#else
uint64_t tmp = pop64(x3);
#endif
return (int) tmp;
}
// Forward declarations for Ebwt class
class EbwtSearchParams;
/**
* Extended Burrows-Wheeler transform data.
*
* An Ebwt may be transferred to and from RAM with calls to
* evictFromMemory() and loadIntoMemory(). By default, a newly-created
* Ebwt is not loaded into memory; if the user would like to use a
* newly-created Ebwt to answer queries, they must first call
* loadIntoMemory().
*/
class Ebwt {
public:
#define Ebwt_INITS \
_toBigEndian(currentlyBigEndian()), \
_overrideOffRate(overrideOffRate), \
_verbose(verbose), \
_passMemExc(passMemExc), \
_sanity(sanityCheck), \
fw_(fw), \
_in1(NULL), \
_in2(NULL), \
_zOff(OFF_MASK), \
_zEbwtByteOff(OFF_MASK), \
_zEbwtBpOff(-1), \
_nPat(0), \
_nFrag(0), \
_plen(EBWT_CAT), \
_rstarts(EBWT_CAT), \
_fchr(EBWT_CAT), \
_ftab(EBWT_CAT), \
_eftab(EBWT_CAT), \
_offs(EBWT_CAT), \
_ebwt(EBWT_CAT), \
_useMm(false), \
useShmem_(false), \
_refnames(EBWT_CAT), \
mmFile1_(NULL), \
mmFile2_(NULL)
/// Construct an Ebwt from the given input file
Ebwt(const string& in,
int color,
int needEntireReverse,
bool fw,
int32_t overrideOffRate, // = -1,
int32_t offRatePlus, // = -1,
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_INITS
{
assert(!useMm || !useShmem);
#ifdef POPCNT_CAPABILITY
ProcessorSupport ps;
_usePOPCNTinstruction = ps.POPCNTenabled();
#endif
packed_ = false;
_useMm = useMm;
useShmem_ = useShmem;
_in1Str = in + ".1." + gEbwt_ext;
_in2Str = in + ".2." + gEbwt_ext;
readIntoMemory(
color, // expect index to be colorspace?
fw ? -1 : needEntireReverse, // need REF_READ_REVERSE
loadSASamp, // load the SA sample portion?
loadFtab, // load the ftab & eftab?
loadRstarts, // load the rstarts array?
true, // stop after loading the header portion?
&_eh, // params
mmSweep, // mmSweep
loadNames, // loadNames
startVerbose); // startVerbose
// If the offRate has been overridden, reflect that in the
// _eh._offRate field
if(offRatePlus > 0 && _overrideOffRate == -1) {
_overrideOffRate = _eh._offRate + offRatePlus;
}
if(_overrideOffRate > _eh._offRate) {
_eh.setOffRate(_overrideOffRate);
assert_eq(_overrideOffRate, _eh._offRate);
}
assert(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>
Ebwt(
TStr exampleStr,
bool packed,
int color,
int needEntireReverse,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
int nthreads,
const string& file, // base filename for EBWT files
bool fw,
bool useBlockwise,
TIndexOffU bmax,
TIndexOffU bmaxSqrtMult,
TIndexOffU bmaxDivN,
int dcv,
EList<FileBuf*>& is,
EList<RefRecord>& szs,
TIndexOffU sztot,
const RefReadInParams& refparams,
uint32_t seed,
int32_t overrideOffRate = -1,
bool doSaFile = false,
bool doBwtFile = false,
bool verbose = false,
bool passMemExc = false,
bool sanityCheck = false) :
Ebwt_INITS,
_eh(
joinedLen(szs),
lineRate,
offRate,
ftabChars,
color,
refparams.reverse == REF_READ_REVERSE)
{
#ifdef POPCNT_CAPABILITY
ProcessorSupport ps;
_usePOPCNTinstruction = ps.POPCNTenabled();
#endif
_in1Str = file + ".1." + gEbwt_ext;
_in2Str = file + ".2." + gEbwt_ext;
packed_ = packed;
// Open output files
ofstream fout1(_in1Str.c_str(), ios::binary);
if(!fout1.good()) {
cerr << "Could not open index file for writing: \"" << _in1Str.c_str() << "\"" << endl
<< "Please make sure the directory exists and that permissions allow writing by" << endl
<< "Bowtie." << endl;
throw 1;
}
ofstream fout2(_in2Str.c_str(), ios::binary);
if(!fout2.good()) {
cerr << "Could not open index file for writing: \"" << _in2Str.c_str() << "\"" << endl
<< "Please make sure the directory exists and that permissions allow writing by" << endl
<< "Bowtie." << endl;
throw 1;
}
_inSaStr = file + ".sa";
_inBwtStr = file + ".bwt";
ofstream *saOut = NULL, *bwtOut = NULL;
if(doSaFile) {
saOut = new ofstream(_inSaStr.c_str(), ios::binary);
if(!saOut->good()) {
cerr << "Could not open suffix-array file for writing: \"" << _inSaStr.c_str() << "\"" << endl
<< "Please make sure the directory exists and that permissions allow writing by" << endl
<< "Bowtie." << endl;
throw 1;
}
}
if(doBwtFile) {
bwtOut = new ofstream(_inBwtStr.c_str(), ios::binary);
if(!bwtOut->good()) {
cerr << "Could not open suffix-array file for writing: \"" << _inBwtStr.c_str() << "\"" << endl
<< "Please make sure the directory exists and that permissions allow writing by" << endl
<< "Bowtie." << endl;
throw 1;
}
}
// Build SA(T) and BWT(T) block by block
initFromVector<TStr>(
is,
szs,
sztot,
refparams,
fout1,
fout2,
file,
saOut,
bwtOut,
nthreads,
useBlockwise,
bmax,
bmaxSqrtMult,
bmaxDivN,
dcv,
seed,
verbose);
// Close output files
fout1.flush();
int64_t tellpSz1 = (int64_t)fout1.tellp();
VMSG_NL("Wrote " << fout1.tellp() << " bytes to primary EBWT file: " << _in1Str.c_str());
fout1.close();
bool err = false;
if(tellpSz1 > fileSize(_in1Str.c_str())) {
err = true;
cerr << "Index is corrupt: File size for " << _in1Str.c_str() << " should have been " << tellpSz1
<< " but is actually " << fileSize(_in1Str.c_str()) << "." << endl;
}
fout2.flush();
int64_t tellpSz2 = (int64_t)fout2.tellp();
VMSG_NL("Wrote " << fout2.tellp() << " bytes to secondary EBWT file: " << _in2Str.c_str());
fout2.close();
if(tellpSz2 > fileSize(_in2Str.c_str())) {
err = true;
cerr << "Index is corrupt: File size for " << _in2Str.c_str() << " should have been " << tellpSz2
<< " but is actually " << fileSize(_in2Str.c_str()) << "." << endl;
}
if(saOut != NULL) {
// Check on suffix array output file size
int64_t tellpSzSa = (int64_t)saOut->tellp();
VMSG_NL("Wrote " << tellpSzSa << " bytes to suffix-array file: " << _inSaStr.c_str());
saOut->close();
if(tellpSzSa > fileSize(_inSaStr.c_str())) {
err = true;
cerr << "Index is corrupt: File size for " << _inSaStr.c_str() << " should have been " << tellpSzSa
<< " but is actually " << fileSize(_inSaStr.c_str()) << "." << endl;
}
}
if(bwtOut != NULL) {
// Check on suffix array output file size
int64_t tellpSzBwt = (int64_t)bwtOut->tellp();
VMSG_NL("Wrote " << tellpSzBwt << " bytes to BWT file: " << _inBwtStr.c_str());
bwtOut->close();
if(tellpSzBwt > fileSize(_inBwtStr.c_str())) {
err = true;
cerr << "Index is corrupt: File size for " << _inBwtStr.c_str() << " should have been " << tellpSzBwt
<< " but is actually " << fileSize(_inBwtStr.c_str()) << "." << endl;
}
}
if(err) {
cerr << "Please check if there is a problem with the disk or if disk is full." << endl;
throw 1;
}
// Reopen as input streams
VMSG_NL("Re-opening _in1 and _in2 as input streams");
if(_sanity) {
VMSG_NL("Sanity-checking Bt2");
assert(!isInMemory());
readIntoMemory(
color, // colorspace?
fw ? -1 : needEntireReverse, // 1 -> need the reverse to be reverse-of-concat
true, // load SA sample (_offs[])?
true, // load ftab (_ftab[] & _eftab[])?
true, // load r-starts (_rstarts[])?
false, // just load header?
NULL, // Params object to fill
false, // mm sweep?
true, // load names?
false); // verbose startup?
sanityCheckAll(refparams.reverse);
evictFromMemory();
assert(!isInMemory());
}
VMSG_NL("Returning from Ebwt constructor");
}
/**
* Static constructor for a pair of forward/reverse indexes for the
* given reference string.
*/
template<typename TStr>
static pair<Ebwt*, Ebwt*>
fromString(
const char* str,
bool packed,
int color,
int reverse,
bool bigEndian,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
const string& file,
bool useBlockwise,
TIndexOffU bmax,
TIndexOffU bmaxSqrtMult,
TIndexOffU bmaxDivN,
int dcv,
uint32_t seed,
bool verbose,
bool autoMem,
bool sanity)
{
EList<std::string> strs(EBWT_CAT);
strs.push_back(std::string(str));
return fromStrings<TStr>(
strs,
packed,
color,
reverse,
bigEndian,
lineRate,
offRate,
ftabChars,
file,
useBlockwise,
bmax,
bmaxSqrtMult,
bmaxDivN,
dcv,
seed,
verbose,
autoMem,
sanity);
}
/**
* Static constructor for a pair of forward/reverse indexes for the
* given list of reference strings.
*/
template<typename TStr>
static pair<Ebwt*, Ebwt*>
fromStrings(
const EList<std::string>& strs,
bool packed,
int color,
int reverse,
bool bigEndian,
int32_t lineRate,
int32_t offRate,
int32_t ftabChars,
const string& file,
bool useBlockwise,
TIndexOffU bmax,
TIndexOffU bmaxSqrtMult,
TIndexOffU bmaxDivN,
int dcv,
uint32_t seed,
bool verbose,
bool autoMem,
bool sanity)
{
assert(!strs.empty());
EList<FileBuf*> is(EBWT_CAT);
RefReadInParams refparams(color, REF_READ_FORWARD, false, false);
// Adapt sequence strings to stringstreams open for input
auto_ptr<stringstream> ss(new stringstream());
for(TIndexOffU i = 0; i < strs.size(); i++) {
(*ss) << ">" << i << endl << strs[i] << endl;
}
auto_ptr<FileBuf> fb(new FileBuf(ss.get()));
assert(!fb->eof());
assert(fb->get() == '>');
ASSERT_ONLY(fb->reset());
assert(!fb->eof());
is.push_back(fb.get());
// Vector for the ordered list of "records" comprising the input
// sequences. A record represents a stretch of unambiguous
// characters in one of the input sequences.
EList<RefRecord> szs(EBWT_CAT);
std::pair<TIndexOffU, TIndexOffU> sztot;
sztot = BitPairReference::szsFromFasta(is, file, bigEndian, refparams, szs, sanity);
// Construct Ebwt from input strings and parameters
Ebwt *ebwtFw = new Ebwt(
TStr(),
packed,
refparams.color ? 1 : 0,
-1, // fw
lineRate,
offRate, // suffix-array sampling rate
ftabChars, // number of chars in initial arrow-pair calc
file, // basename for .?.ebwt files
true, // fw?
useBlockwise, // useBlockwise
bmax, // block size for blockwise SA builder
bmaxSqrtMult, // block size as multiplier of sqrt(len)
bmaxDivN, // block size as divisor of len
dcv, // difference-cover period
is, // list of input streams
szs, // list of reference sizes
sztot.first, // total size of all unambiguous ref chars
refparams, // reference read-in parameters
seed, // pseudo-random number generator seed
-1, // override offRate
verbose, // be talkative
autoMem, // pass exceptions up to the toplevel so that we can adjust memory settings automatically
sanity); // verify results and internal consistency
refparams.reverse = reverse;
szs.clear();
sztot = BitPairReference::szsFromFasta(is, file, bigEndian, refparams, szs, sanity);
// Construct Ebwt from input strings and parameters
Ebwt *ebwtBw = new Ebwt(
TStr(),
packed,
refparams.color ? 1 : 0,
reverse == REF_READ_REVERSE,
lineRate,
offRate, // suffix-array sampling rate
ftabChars, // number of chars in initial arrow-pair calc
file + ".rev",// basename for .?.ebwt files
false, // fw?
useBlockwise, // useBlockwise
bmax, // block size for blockwise SA builder
bmaxSqrtMult, // block size as multiplier of sqrt(len)
bmaxDivN, // block size as divisor of len
dcv, // difference-cover period
is, // list of input streams
szs, // list of reference sizes
sztot.first, // total size of all unambiguous ref chars
refparams, // reference read-in parameters
seed, // pseudo-random number generator seed
-1, // override offRate
verbose, // be talkative
autoMem, // pass exceptions up to the toplevel so that we can adjust memory settings automatically
sanity); // verify results and internal consistency
return make_pair(ebwtFw, ebwtBw);
}
/// Return true iff the Ebwt is packed
bool isPacked() { return packed_; }
/**
* Write the rstarts array given the szs array for the reference.
*/
void szsToDisk(const EList<RefRecord>& szs, ostream& os, int reverse);
/**
* Helper for the constructors above. Takes a vector of text
* strings and joins them into a single string with a call to
* joinToDisk, which does a join (with padding) and writes some of
* the resulting data directly to disk rather than keep it in
* memory. It then constructs a suffix-array producer (what kind
* depends on 'useBlockwise') for the resulting sequence. The
* suffix-array producer can then be used to obtain chunks of the
* joined string's suffix array.
*/
template <typename TStr>
void initFromVector(EList<FileBuf*>& is,
EList<RefRecord>& szs,
TIndexOffU sztot,
const RefReadInParams& refparams,
ofstream& out1,
ofstream& out2,
const string& outfile,
ofstream* saOut,
ofstream* bwtOut,
int nthreads,
bool useBlockwise,
TIndexOffU bmax,
TIndexOffU bmaxSqrtMult,
TIndexOffU bmaxDivN,
int dcv,
uint32_t seed,
bool verbose)
{
// Compose text strings into single string
VMSG_NL("Calculating joined length");
TStr s; // holds the entire joined reference after call to joinToDisk
TIndexOffU jlen;
jlen = joinedLen(szs);
assert_geq(jlen, sztot);
VMSG_NL("Writing header");
writeFromMemory(true, out1, out2);
try {
VMSG_NL("Reserving space for joined string");
s.resize(jlen);
VMSG_NL("Joining reference sequences");
if(refparams.reverse == REF_READ_REVERSE) {
{
Timer timer(cout, " Time to join reference sequences: ", _verbose);
joinToDisk(is, szs, sztot, refparams, s, out1, out2);
} {
Timer timer(cout, " Time to reverse reference sequence: ", _verbose);
EList<RefRecord> tmp(EBWT_CAT);
s.reverse();
reverseRefRecords(szs, tmp, false, verbose);
szsToDisk(tmp, out1, refparams.reverse);
}
} else {
Timer timer(cout, " Time to join reference sequences: ", _verbose);
joinToDisk(is, szs, sztot, refparams, s, out1, out2);
szsToDisk(szs, out1, refparams.reverse);
}
// Joined reference sequence now in 's'
} catch(bad_alloc& e) {
// If we throw an allocation exception in the try block,
// that means that the joined version of the reference
// string itself is too larger to fit in memory. The only
// alternatives are to tell the user to give us more memory
// or to try again with a packed representation of the
// reference (if we haven't tried that already).
cerr << "Could not allocate space for a joined string of " << jlen << " elements." << endl;
if(!isPacked() && _passMemExc) {
// Pass the exception up so that we can retry using a
// packed string representation
throw e;
}
// There's no point passing this exception on. The fact
// that we couldn't allocate the joined string means that
// --bmax is irrelevant - the user should re-run with
// ebwt-build-packed
if(isPacked()) {
cerr << "Please try running bowtie-build on a computer with more memory." << endl;
} else {
cerr << "Please try running bowtie-build in packed mode (-p/--packed) or in automatic" << endl
<< "mode (-a/--auto), or try again on a computer with more memory." << endl;
}
if(sizeof(void*) == 4) {
cerr << "If this computer has more than 4 GB of memory, try using a 64-bit executable;" << endl
<< "this executable is 32-bit." << endl;
}
throw 1;
}
// Succesfully obtained joined reference string
assert_geq(s.length(), jlen);
if(bmax != OFF_MASK) {
VMSG_NL("bmax according to bmax setting: " << bmax);
}
else if(bmaxSqrtMult != OFF_MASK) {
bmax *= bmaxSqrtMult;