forked from BenLangmead/bowtie
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hit.h
1705 lines (1563 loc) · 47.9 KB
/
hit.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
#ifndef HIT_H_
#define HIT_H_
#include <vector>
#include <stdint.h>
#include <iostream>
#include <sstream>
#include <fstream>
#include <string>
#include <stdexcept>
#include <seqan/sequence.h>
#include "alphabet.h"
#include "assert_helpers.h"
#include "threading.h"
#include "bitset.h"
#include "tokenize.h"
#include "pat.h"
#include "formats.h"
#include "filebuf.h"
#include "edit.h"
#include "refmap.h"
#include "annot.h"
/**
* Classes for dealing with reporting alignments.
*/
using namespace std;
using namespace seqan;
/// Constants for the various output modes
enum output_types {
OUTPUT_FULL = 1,
OUTPUT_CONCISE,
OUTPUT_BINARY,
OUTPUT_CHAIN,
OUTPUT_SAM,
OUTPUT_NONE
};
/// Names of the various output modes
static const std::string output_type_names[] = {
"Invalid!",
"Full",
"Concise",
"Binary",
"None"
};
typedef pair<TIndexOffU,TIndexOffU> UPair;
/**
* Encapsulates a hit, including a text-id/text-offset pair, a pattern
* id, and a boolean indicating whether it matched as its forward or
* reverse-complement version.
*/
class Hit {
public:
Hit() : stratum(-1) { }
UPair h; /// reference index & offset
UPair mh; /// reference index & offset for mate
uint32_t patId; /// read index
String<char> patName; /// read name
String<Dna5> patSeq; /// read sequence
String<Dna5> colSeq; /// original color sequence, not decoded
String<char> quals; /// read qualities
String<char> colQuals;/// original color qualities, not decoded
FixedBitset<1024> mms; /// nucleotide mismatch mask
FixedBitset<1024> cmms; /// color mismatch mask (if relevant)
vector<char> refcs; /// reference characters for mms
vector<char> crefcs; /// reference characters for cmms
uint32_t oms; /// # of other possible mappings; 0 -> this is unique
bool fw; /// orientation of read in alignment
bool mfw; /// orientation of mate in alignment
uint16_t mlen; /// length of mate
int8_t stratum; /// stratum of hit (= mismatches in seed)
uint32_t cost; /// total cost, factoring in stratum and quality penalty
uint8_t mate; /// matedness; 0 = not a mate
/// 1 = upstream mate
/// 2 = downstream mate
bool color; /// read is in colorspace?
char primer; /// primer base, for csfasta files
char trimc; /// trimmed color, for csfasta files
uint32_t seed; /// pseudo-random seed for aligned read
/**
* Return true if this Hit is internally consistent. Otherwise,
* throw an assertion.
*/
bool repOk() const {
assert_geq(cost, (uint32_t)(stratum << 14));
return true;
}
size_t length() const { return seqan::length(patSeq); }
Hit& operator = (const Hit &other) {
this->h = other.h;
this->mh = other.mh;
this->patId = other.patId;
this->patName = other.patName;
this->patSeq = other.patSeq;
this->colSeq = other.colSeq;
this->quals = other.quals;
this->colQuals= other.colQuals;
this->mms = other.mms;
this->cmms = other.cmms;
this->refcs = other.refcs;
this->crefcs = other.crefcs;
this->oms = other.oms;
this->fw = other.fw;
this->mfw = other.mfw;
this->mlen = other.mlen;
this->stratum = other.stratum;
this->cost = other.cost;
this->mate = other.mate;
this->color = other.color;
this->cmms = other.cmms;
this->seed = other.seed;
return *this;
}
};
/**
* Compare hits a and b; a < b if its cost is less than B's. If
* there's a tie, break on position and orientation.
*/
class HitCostCompare {
public:
bool operator() (const Hit& a, const Hit& b) {
if(a.cost < b.cost) return true;
if(a.cost > b.cost) return false;
if(a.h < b.h) return true;
if(a.h > b.h) return false;
if(a.fw < b.fw) return true;
if(a.fw > b.fw) return false;
return false;
}
};
/// Sort by text-id then by text-offset
bool operator< (const Hit& a, const Hit& b);
/**
* Table for holding recalibration counts, along the lines of the table
* presented in the SOAPsnp paper in Genome Res. Each element maps a
* read allele (o), quality score (q), cycle (c), and reference allele
* (H), to a count of how many times that combination is observed in a
* reported alignment.
*
* RecalTable is not synchronized, so it's assumed that threads are
* incrementing the counters from within critical sections.
*/
class RecalTable {
public:
RecalTable(int maxCycle,
int maxQual,
int qualShift) : maxCycle_(maxCycle),
maxQual_(maxQual),
qualShift_(qualShift),
shift1_(6 - qualShift_),
shift2_(shift1_ + 2),
shift3_(shift2_ + 2),
ents_(NULL), len_(0)
{
if(maxCycle == 0) {
cerr << "Warning: maximum cycle for recalibration table is 0" << endl;
} else if(maxQual >> qualShift == 0) {
cerr << "Warning: maximum quality value " << maxQual << ", when shifted, is 0" << endl;
} else if(qualShift > 5) {
cerr << "Warning: quality shift value " << qualShift << " exceeds ceiling of 5" << endl;
} else {
try {
len_ = maxCycle_ * 4 /* subj alleles*/ * 4 /* ref alleles */ * 64 /* quals */;
ents_ = new uint32_t[len_];
if(ents_ == NULL) {
throw std::bad_alloc();
}
memset(ents_, 0, len_ << 2);
} catch(std::bad_alloc& e) {
cerr << "Error allocating recalibration table with " << len_ << " entries" << endl;
throw 1;
}
}
}
~RecalTable() {
if(ents_ != NULL) delete[] ents_;
}
/**
* Factor a new alignment into the recalibration table.
*/
void commitHit(const Hit& h) {
// Iterate through the pattern from 5' to 3', calculate the
// shifted quality value, obtain the reference character, and
// increment the appropriate counter
assert(h.repOk());
for(int i = 0; i < (int)h.length(); i++) {
int ii = i;
if(!h.fw) {
ii = (int)(h.length() - ii - 1);
}
int qc = (int)h.patSeq[ii];
int rc = qc;
if(h.mms.test(i)) {
rc = charToDna5[(int)h.refcs[i]];
assert_neq(rc, qc);
}
int q = (int)h.quals[ii]-33;
assert_lt(q, 64);
q >>= qualShift_;
ents_[calcIdx(i, qc, rc, q)]++;
}
}
/**
* Print the contents of the recalibration table.
*/
void print (std::ostream& out) const {
if(ents_ == NULL) return;
const int lim = maxCycle_;
for(int i = 0; i < lim; i++) {
out << "t" << i << "\t";
// Iterate over subject alleles
for(int j = 0; j < 4; j++) {
// Iterate over reference alleles
for(int k = 0; k < 4; k++) {
// Iterate over qualities
int lim2 = maxQual_ >> qualShift_;
for(int l = 0; l < lim2; l++) {
out << ents_[calcIdx(i, j, k, l)] << '\t';
}
}
}
out << endl;
}
}
protected:
/**
* Calculate index into the ents_ array given cycle, subject
* allele, reference allele, and (shifted) quality.
*/
int calcIdx(int cyc, int sa, int ra, int q) const {
int ret = q | (ra << shift1_) | (sa << shift2_) | (cyc << shift3_);
assert_lt(ret, len_);
return ret;
}
const int maxCycle_;
const int maxQual_;
const int qualShift_;
const int shift1_;
const int shift2_;
const int shift3_;
uint32_t *ents_;
int len_;
};
#define DECL_HIT_DUMPS \
const std::string& dumpAl, \
const std::string& dumpUnal, \
const std::string& dumpMax
#define INIT_HIT_DUMPS \
dumpAlBase_(dumpAl), \
dumpUnalBase_(dumpUnal), \
dumpMaxBase_(dumpMax)
#define DECL_HIT_DUMPS2 \
DECL_HIT_DUMPS, \
bool onePairFile, \
bool sampleMax, \
RecalTable *recalTable, \
std::vector<std::string>* refnames
#define PASS_HIT_DUMPS \
dumpAl, \
dumpUnal, \
dumpMax
#define PASS_HIT_DUMPS2 \
PASS_HIT_DUMPS, \
onePairFile, \
sampleMax, \
recalTable, \
refnames
/**
* Encapsulates an object that accepts hits, optionally retains them in
* a vector, and does something else with them according to
* descendent's implementation of pure virtual member reportHitImpl().
*/
class HitSink {
public:
explicit HitSink(OutFileBuf* out,
DECL_HIT_DUMPS,
bool onePairFile,
bool sampleMax,
RecalTable *table,
vector<string>* refnames = NULL) :
_outs(),
_deleteOuts(false),
recalTable_(table),
_refnames(refnames),
_numWrappers(0),
_locks(),
INIT_HIT_DUMPS,
onePairFile_(onePairFile),
sampleMax_(sampleMax),
first_(true),
numAligned_(0llu),
numUnaligned_(0llu),
numMaxed_(0llu),
numReported_(0llu),
numReportedPaired_(0llu),
quiet_(false),
ssmode_(ios_base::out)
{
_outs.push_back(out);
vector<MUTEX_T*>::iterator it;
_locks.push_back(new MUTEX_T);
initDumps();
}
/**
* Open a number of output streams; usually one per reference
* sequence. For now, we give then names refXXXXX.map where XXXXX
* is the 0-padded reference index. Someday we may want to include
* the name of the reference sequence in the filename somehow.
*/
explicit HitSink(size_t numOuts,
DECL_HIT_DUMPS,
bool onePairFile,
bool sampleMax,
RecalTable *table,
vector<string>* refnames = NULL) :
_outs(),
_deleteOuts(true),
recalTable_(table),
_refnames(refnames),
_locks(),
INIT_HIT_DUMPS,
onePairFile_(onePairFile),
sampleMax_(sampleMax),
quiet_(false),
ssmode_(ios_base::out)
{
// Open all files for writing and initialize all locks
for(size_t i = 0; i < numOuts; i++) {
_outs.push_back(NULL); // we open output streams lazily
_locks.push_back(new MUTEX_T);
}
initDumps();
}
/**
* Destroy HitSinkobject;
*/
virtual ~HitSink() {
closeOuts();
if(_deleteOuts) {
// Delete all non-NULL output streams
for(size_t i = 0; i < _outs.size(); i++) {
if(_outs[i] != NULL) {
delete _outs[i];
_outs[i] = NULL;
}
}
}
destroyDumps();
}
/**
* Call this whenever this HitSink is wrapped by a new
* HitSinkPerThread. This helps us keep track of whether the main
* lock or any of the per-stream locks will be contended.
*/
void addWrapper() {
numWrapper_mutex_m.lock();
_numWrappers++;
numWrapper_mutex_m.unlock();
}
/**
* Called by concrete subclasses to figure out which elements of
* the _outs/_locks array to use when outputting the alignment.
*/
size_t refIdxToStreamIdx(size_t refIdx) {
if(refIdx >= _outs.size()) return 0;
return refIdx;
}
/**
* Append a single hit to the given output stream.
*/
virtual void append(ostream& o, const Hit& h) = 0;
/**
* Report a batch of hits; all in the given vector.
*/
virtual void reportHits(vector<Hit>& hs) {
reportHits(hs, 0, hs.size());
}
/**
* Report a batch of hits from a vector, perhaps subsetting it.
*/
virtual void reportHits(vector<Hit>& hs, size_t start, size_t end) {
assert_geq(end, start);
if(end-start == 0) return;
bool paired = hs[start].mate > 0;
// Sort reads so that those against the same reference sequence
// are consecutive.
if(_outs.size() > 1 && end-start > 2) {
sort(hs.begin() + start, hs.begin() + end);
}
char buf[4096];
for(size_t i = start; i < end; i++) {
const Hit& h = hs[i];
assert(h.repOk());
bool diff = false;
if(i > start) {
diff = (refIdxToStreamIdx(h.h.first) != refIdxToStreamIdx(hs[i-1].h.first));
if(diff) unlock(hs[i-1].h.first);
}
ostringstream ss(ssmode_);
ss.rdbuf()->pubsetbuf(buf, 4096);
append(ss, h);
if(i == start || diff) {
lock(h.h.first);
}
out(h.h.first).writeChars(buf, ss.tellp());
}
unlock(hs[end-1].h.first);
tthread::lock_guard<MUTEX_T> guard(main_mutex_m);
commitHits(hs);
first_ = false;
numAligned_++;
if(paired) numReportedPaired_ += (end-start);
else numReported_ += (end-start);
}
void commitHit(const Hit& hit) {
if(recalTable_ != NULL) {
recalTable_->commitHit(hit);
}
}
void commitHits(const std::vector<Hit>& hits) {
if(recalTable_ != NULL) {
const size_t sz = hits.size();
for(size_t i = 0; i < sz; i++) {
commitHit(hits[i]);
}
}
}
/**
* Called when all alignments are complete. It is assumed that no
* synchronization is necessary.
*/
void finish(bool hadoopOut) {
// Close output streams
closeOuts();
if(!quiet_) {
// Print information about how many unpaired and/or paired
// reads were aligned.
uint64_t tot = numAligned_ + numUnaligned_ + numMaxed_;
double alPct = 0.0, unalPct = 0.0, maxPct = 0.0;
if(tot > 0) {
alPct = 100.0 * (double)numAligned_ / (double)tot;
unalPct = 100.0 * (double)numUnaligned_ / (double)tot;
maxPct = 100.0 * (double)numMaxed_ / (double)tot;
}
cerr << "# reads processed: " << tot << endl;
cerr << "# reads with at least one reported alignment: "
<< numAligned_ << " (" << fixed << setprecision(2)
<< alPct << "%)" << endl;
cerr << "# reads that failed to align: "
<< numUnaligned_ << " (" << fixed << setprecision(2)
<< unalPct << "%)" << endl;
if(numMaxed_ > 0) {
if(sampleMax_) {
cerr << "# reads with alignments sampled due to -M: "
<< numMaxed_ << " (" << fixed << setprecision(2)
<< maxPct << "%)" << endl;
} else {
cerr << "# reads with alignments suppressed due to -m: "
<< numMaxed_ << " (" << fixed << setprecision(2)
<< maxPct << "%)" << endl;
}
}
if(first_) {
assert_eq(0llu, numReported_);
cerr << "No alignments" << endl;
}
else if(numReportedPaired_ > 0 && numReported_ == 0) {
cerr << "Reported " << (numReportedPaired_ >> 1)
<< " paired-end alignments to " << _outs.size()
<< " output stream(s)" << endl;
}
else if(numReported_ > 0 && numReportedPaired_ == 0) {
cerr << "Reported " << numReported_
<< " alignments to " << _outs.size()
<< " output stream(s)" << endl;
}
else {
assert_gt(numReported_, 0);
assert_gt(numReportedPaired_, 0);
cerr << "Reported " << (numReportedPaired_ >> 1)
<< " paired-end alignments and " << numReported_
<< " singleton alignments to " << _outs.size()
<< " output stream(s)" << endl;
}
if(hadoopOut) {
cerr << "reporter:counter:Bowtie,Reads with reported alignments," << numAligned_ << endl;
cerr << "reporter:counter:Bowtie,Reads with no alignments," << numUnaligned_ << endl;
cerr << "reporter:counter:Bowtie,Reads exceeding -m limit," << numMaxed_ << endl;
cerr << "reporter:counter:Bowtie,Unpaired alignments reported," << numReported_ << endl;
cerr << "reporter:counter:Bowtie,Paired alignments reported," << numReportedPaired_ << endl;
}
}
// Print the recalibration table.
if(recalTable_ != NULL) {
recalTable_->print(cout);
}
}
/// Returns the alignment output stream; if the stream needs to be
/// created, create it
OutFileBuf& out(size_t refIdx) {
size_t strIdx = refIdxToStreamIdx(refIdx);
if(_outs[strIdx] == NULL) {
assert(_deleteOuts);
ostringstream oss;
oss << "ref";
if (strIdx < 10) oss << "0000";
else if(strIdx < 100) oss << "000";
else if(strIdx < 1000) oss << "00";
else if(strIdx < 10000) oss << "0";
oss << strIdx << ".map";
_outs[strIdx] = new OutFileBuf(oss.str().c_str(), ssmode_ == ios_base::binary);
}
assert(_outs[strIdx] != NULL);
return *(_outs[strIdx]);
}
/**
* Lock the monolithic lock for this HitSink. This is useful when,
* for example, outputting a read to an unaligned-read file.
*/
void mainlock() {
main_mutex_m.lock();
}
/**
* Unlock the monolithic lock for this HitSink. This is useful
* when, for example, outputting a read to an unaligned-read file.
*/
void mainunlock() {
main_mutex_m.unlock();
}
/**
* Return true iff this HitSink dumps aligned reads to an output
* stream (i.e., iff --alfa or --alfq are specified).
*/
bool dumpsAlignedReads() {
return dumpAlignFlag_;
}
/**
* Return true iff this HitSink dumps unaligned reads to an output
* stream (i.e., iff --unfa or --unfq are specified).
*/
bool dumpsUnalignedReads() {
return dumpUnalignFlag_;
}
/**
* Return true iff this HitSink dumps maxed-out reads to an output
* stream (i.e., iff --maxfa or --maxfq are specified).
*/
bool dumpsMaxedReads() {
return dumpMaxedFlag_ || dumpUnalignFlag_;
}
/**
* Return true iff this HitSink dumps either unaligned or maxed-
* out reads to an output stream (i.e., iff --unfa, --maxfa,
* --unfq, or --maxfq are specified).
*/
bool dumpsReads() {
return dumpAlignFlag_ || dumpUnalignFlag_ || dumpMaxedFlag_;
}
/**
* Dump an aligned read to all of the appropriate output streams.
* Be careful to synchronize correctly - there may be multiple
* simultaneous writers.
*/
void dumpAlign(PatternSourcePerThread& p) {
if(!dumpAlignFlag_) return;
if(!p.paired() || onePairFile_) {
// Dump unpaired read to an aligned-read file of the same format
if(!dumpAlBase_.empty()) {
tthread::lock_guard<MUTEX_T> guard(dumpAlignLock_);
if(dumpAl_ == NULL) {
assert(dumpAlQv_ == NULL);
dumpAl_ = openOf(dumpAlBase_, 0, "");
assert(dumpAl_ != NULL);
if(p.bufa().qualOrigBufLen > 0) {
dumpAlQv_ = openOf(dumpAlBase_ + ".qual", 0, "");
assert(dumpAlQv_ != NULL);
}
}
dumpAl_->write(p.bufa().readOrigBuf, p.bufa().readOrigBufLen);
if(dumpAlQv_ != NULL) {
dumpAlQv_->write(p.bufa().qualOrigBuf, p.bufa().qualOrigBufLen);
}
}
} else {
// Dump paired-end read to an aligned-read file (or pair of
// files) of the same format
if(!dumpAlBase_.empty()) {
tthread::lock_guard<MUTEX_T> guard(dumpAlignLockPE_);
if(dumpAl_1_ == NULL) {
assert(dumpAlQv_1_ == NULL);
assert(dumpAlQv_2_ == NULL);
dumpAl_1_ = openOf(dumpAlBase_, 1, "");
dumpAl_2_ = openOf(dumpAlBase_, 2, "");
assert(dumpAl_1_ != NULL);
assert(dumpAl_2_ != NULL);
if(p.bufa().qualOrigBufLen > 0) {
dumpAlQv_1_ = openOf(dumpAlBase_ + ".qual", 1, "");
dumpAlQv_2_ = openOf(dumpAlBase_ + ".qual", 2, "");
assert(dumpAlQv_1_ != NULL);
assert(dumpAlQv_2_ != NULL);
}
}
dumpAl_1_->write(p.bufa().readOrigBuf, p.bufa().readOrigBufLen);
dumpAl_2_->write(p.bufb().readOrigBuf, p.bufb().readOrigBufLen);
if(dumpAlQv_1_ != NULL) {
dumpAlQv_1_->write(p.bufa().qualOrigBuf, p.bufa().qualOrigBufLen);
dumpAlQv_2_->write(p.bufb().qualOrigBuf, p.bufb().qualOrigBufLen);
}
}
}
}
/**
* Dump an unaligned read to all of the appropriate output streams.
* Be careful to synchronize correctly - there may be multiple
* simultaneous writers.
*/
void dumpUnal(PatternSourcePerThread& p) {
if(!dumpUnalignFlag_) return;
if(!p.paired() || onePairFile_) {
// Dump unpaired read to an unaligned-read file of the same format
if(!dumpUnalBase_.empty()) {
tthread::lock_guard<MUTEX_T> guard(dumpUnalLock_);
if(dumpUnal_ == NULL) {
assert(dumpUnalQv_ == NULL);
dumpUnal_ = openOf(dumpUnalBase_, 0, "");
assert(dumpUnal_ != NULL);
if(p.bufa().qualOrigBufLen > 0) {
dumpUnalQv_ = openOf(dumpUnalBase_ + ".qual", 0, "");
assert(dumpUnalQv_ != NULL);
}
}
dumpUnal_->write(p.bufa().readOrigBuf, p.bufa().readOrigBufLen);
if(dumpUnalQv_ != NULL) {
dumpUnalQv_->write(p.bufa().qualOrigBuf, p.bufa().qualOrigBufLen);
}
}
} else {
// Dump paired-end read to an unaligned-read file (or pair
// of files) of the same format
if(!dumpUnalBase_.empty()) {
tthread::lock_guard<MUTEX_T> guard(dumpUnalLockPE_);
if(dumpUnal_1_ == NULL) {
assert(dumpUnal_1_ == NULL);
assert(dumpUnal_2_ == NULL);
dumpUnal_1_ = openOf(dumpUnalBase_, 1, "");
dumpUnal_2_ = openOf(dumpUnalBase_, 2, "");
assert(dumpUnal_1_ != NULL);
assert(dumpUnal_2_ != NULL);
if(p.bufa().qualOrigBufLen > 0) {
dumpUnalQv_1_ = openOf(dumpUnalBase_ + ".qual", 1, "");
dumpUnalQv_2_ = openOf(dumpUnalBase_ + ".qual", 2, "");
}
}
dumpUnal_1_->write(p.bufa().readOrigBuf, p.bufa().readOrigBufLen);
dumpUnal_2_->write(p.bufb().readOrigBuf, p.bufb().readOrigBufLen);
if(dumpUnalQv_1_ != NULL) {
dumpUnalQv_1_->write(p.bufa().qualOrigBuf, p.bufa().qualOrigBufLen);
dumpUnalQv_2_->write(p.bufb().qualOrigBuf, p.bufb().qualOrigBufLen);
}
}
}
}
/**
* Dump a maxed-out read to all of the appropriate output streams.
* Be careful to synchronize correctly - there may be multiple
* simultaneous writers.
*/
void dumpMaxed(PatternSourcePerThread& p) {
if(!dumpMaxedFlag_) {
if(dumpUnalignFlag_) dumpUnal(p);
return;
}
if(!p.paired() || onePairFile_) {
// Dump unpaired read to an maxed-out-read file of the same format
if(!dumpMaxBase_.empty()) {
tthread::lock_guard<MUTEX_T> guard(dumpMaxLock_);
if(dumpMax_ == NULL) {
dumpMax_ = openOf(dumpMaxBase_, 0, "");
assert(dumpMax_ != NULL);
if(p.bufa().qualOrigBufLen > 0) {
dumpMaxQv_ = openOf(dumpMaxBase_ + ".qual", 0, "");
}
}
dumpMax_->write(p.bufa().readOrigBuf, p.bufa().readOrigBufLen);
if(dumpMaxQv_ != NULL) {
dumpMaxQv_->write(p.bufa().qualOrigBuf, p.bufa().qualOrigBufLen);
}
}
} else {
// Dump paired-end read to a maxed-out-read file (or pair
// of files) of the same format
if(!dumpMaxBase_.empty()) {
tthread::lock_guard<MUTEX_T> guard(dumpMaxLockPE_);
if(dumpMax_1_ == NULL) {
assert(dumpMaxQv_1_ == NULL);
assert(dumpMaxQv_2_ == NULL);
dumpMax_1_ = openOf(dumpMaxBase_, 1, "");
dumpMax_2_ = openOf(dumpMaxBase_, 2, "");
assert(dumpMax_1_ != NULL);
assert(dumpMax_2_ != NULL);
if(p.bufa().qualOrigBufLen > 0) {
dumpMaxQv_1_ = openOf(dumpMaxBase_ + ".qual", 1, "");
dumpMaxQv_2_ = openOf(dumpMaxBase_ + ".qual", 2, "");
}
}
dumpMax_1_->write(p.bufa().readOrigBuf, p.bufa().readOrigBufLen);
dumpMax_2_->write(p.bufb().readOrigBuf, p.bufb().readOrigBufLen);
if(dumpMaxQv_1_ != NULL) {
dumpMaxQv_1_->write(p.bufa().qualOrigBuf, p.bufa().qualOrigBufLen);
dumpMaxQv_2_->write(p.bufb().qualOrigBuf, p.bufb().qualOrigBufLen);
}
}
}
}
/**
* Report a maxed-out read. Typically we do nothing, but we might
* want to print a placeholder when output is chained.
*/
virtual void reportMaxed(vector<Hit>& hs, PatternSourcePerThread& p) {
tthread::lock_guard<MUTEX_T> guard(main_mutex_m);
numMaxed_++;
}
/**
* Report an unaligned read. Typically we do nothing, but we might
* want to print a placeholder when output is chained.
*/
virtual void reportUnaligned(PatternSourcePerThread& p) {
tthread::lock_guard<MUTEX_T> guard(main_mutex_m);
numUnaligned_++;
}
protected:
/// Implementation of hit-report
virtual void reportHit(const Hit& h) {
assert(h.repOk());
tthread::lock_guard<MUTEX_T> guard(main_mutex_m);
commitHit(h);
first_ = false;
if(h.mate > 0) numReportedPaired_++;
else numReported_++;
numAligned_++;
}
/**
* Close (and flush) all OutFileBufs.
*/
void closeOuts() {
// Flush and close all non-NULL output streams
for(size_t i = 0; i < _outs.size(); i++) {
if(_outs[i] != NULL && !_outs[i]->closed()) {
_outs[i]->close();
}
}
}
/**
* Lock the output buffer for the output stream for reference with
* index 'refIdx'. By default, hits for all references are
* directed to the same output stream, but if --refout is
* specified, each reference has its own reference stream.
*/
void lock(size_t refIdx) {
size_t strIdx = refIdxToStreamIdx(refIdx);
_locks[strIdx]->lock();
}
/**
* Lock the output buffer for the output stream for reference with
* index 'refIdx'. By default, hits for all references are
* directed to the same output stream, but if --refout is
* specified, each reference has its own reference stream.
*/
void unlock(size_t refIdx) {
size_t strIdx = refIdxToStreamIdx(refIdx);
_locks[strIdx]->unlock();
}
vector<OutFileBuf*> _outs; /// the alignment output stream(s)
bool _deleteOuts; /// Whether to delete elements of _outs upon exit
RecalTable *recalTable_; /// recalibration table
vector<string>* _refnames; /// map from reference indexes to names
int _numWrappers; /// # threads owning a wrapper for this HitSink
vector<MUTEX_T*> _locks; /// pthreads mutexes for per-file critical sections
MUTEX_T main_mutex_m; /// pthreads mutexes for fields of this object
MUTEX_T numWrapper_mutex_m;
// Output filenames for dumping
std::string dumpAlBase_;
std::string dumpUnalBase_;
std::string dumpMaxBase_;
bool onePairFile_;
bool sampleMax_;
// Output streams for dumping sequences
std::ofstream *dumpAl_; // for single-ended reads
std::ofstream *dumpAl_1_; // for first mates
std::ofstream *dumpAl_2_; // for second mates
std::ofstream *dumpUnal_; // for single-ended reads
std::ofstream *dumpUnal_1_; // for first mates
std::ofstream *dumpUnal_2_; // for second mates
std::ofstream *dumpMax_; // for single-ended reads
std::ofstream *dumpMax_1_; // for first mates
std::ofstream *dumpMax_2_; // for second mates
// Output streams for dumping qualities
std::ofstream *dumpAlQv_; // for single-ended reads
std::ofstream *dumpAlQv_1_; // for first mates
std::ofstream *dumpAlQv_2_; // for second mates
std::ofstream *dumpUnalQv_; // for single-ended reads
std::ofstream *dumpUnalQv_1_; // for first mates
std::ofstream *dumpUnalQv_2_; // for second mates
std::ofstream *dumpMaxQv_; // for single-ended reads
std::ofstream *dumpMaxQv_1_; // for first mates
std::ofstream *dumpMaxQv_2_; // for second mates
/**
* Open an ofstream with given name; output error message and quit
* if it fails.
*/
std::ofstream* openOf(const std::string& name,
int mateType,
const std::string& suffix)
{
std::string s = name;
size_t dotoff = name.find_last_of(".");
if(mateType == 1) {
if(dotoff == string::npos) {
s += "_1"; s += suffix;
} else {
s = name.substr(0, dotoff) + "_1" + s.substr(dotoff);
}
} else if(mateType == 2) {
if(dotoff == string::npos) {
s += "_2"; s += suffix;
} else {
s = name.substr(0, dotoff) + "_2" + s.substr(dotoff);
}
} else if(mateType != 0) {
cerr << "Bad mate type " << mateType << endl; throw 1;
}
std::ofstream* tmp = new ofstream(s.c_str(), ios::out);
if(tmp->fail()) {
if(mateType == 0) {
cerr << "Could not open single-ended aligned/unaligned-read file for writing: " << name << endl;
} else {
cerr << "Could not open paired-end aligned/unaligned-read file for writing: " << name << endl;
}
throw 1;
}
return tmp;
}
/**
* Initialize all the locks for dumping.
*/
void initDumps() {
dumpAl_ = dumpAl_1_ = dumpAl_2_ = NULL;
dumpUnal_ = dumpUnal_1_ = dumpUnal_2_ = NULL;
dumpMax_ = dumpMax_1_ = dumpMax_2_ = NULL;
dumpAlQv_ = dumpAlQv_1_ = dumpAlQv_2_ = NULL;
dumpUnalQv_ = dumpUnalQv_1_ = dumpUnalQv_2_ = NULL;
dumpMaxQv_ = dumpMaxQv_1_ = dumpMaxQv_2_ = NULL;
dumpAlignFlag_ = !dumpAlBase_.empty();
dumpUnalignFlag_ = !dumpUnalBase_.empty();
dumpMaxedFlag_ = !dumpMaxBase_.empty();
}
void destroyDumps() {
if(dumpAl_ != NULL) { dumpAl_->close(); delete dumpAl_; }
if(dumpAl_1_ != NULL) { dumpAl_1_->close(); delete dumpAl_1_; }
if(dumpAl_2_ != NULL) { dumpAl_2_->close(); delete dumpAl_2_; }
if(dumpUnal_ != NULL) { dumpUnal_->close(); delete dumpUnal_; }
if(dumpUnal_1_ != NULL) { dumpUnal_1_->close(); delete dumpUnal_1_; }
if(dumpUnal_2_ != NULL) { dumpUnal_2_->close(); delete dumpUnal_2_; }
if(dumpMax_ != NULL) { dumpMax_->close(); delete dumpMax_; }
if(dumpMax_1_ != NULL) { dumpMax_1_->close(); delete dumpMax_1_; }
if(dumpMax_2_ != NULL) { dumpMax_2_->close(); delete dumpMax_2_; }
if(dumpAlQv_ != NULL) { dumpAlQv_->close(); delete dumpAlQv_; }
if(dumpAlQv_1_ != NULL) { dumpAlQv_1_->close(); delete dumpAlQv_1_; }
if(dumpAlQv_2_ != NULL) { dumpAlQv_2_->close(); delete dumpAlQv_2_; }
if(dumpUnalQv_ != NULL) { dumpUnalQv_->close(); delete dumpUnalQv_; }
if(dumpUnalQv_1_ != NULL) { dumpUnalQv_1_->close(); delete dumpUnalQv_1_; }
if(dumpUnalQv_2_ != NULL) { dumpUnalQv_2_->close(); delete dumpUnalQv_2_; }
if(dumpMaxQv_ != NULL) { dumpMaxQv_->close(); delete dumpMaxQv_; }
if(dumpMaxQv_1_ != NULL) { dumpMaxQv_1_->close(); delete dumpMaxQv_1_; }
if(dumpMaxQv_2_ != NULL) { dumpMaxQv_2_->close(); delete dumpMaxQv_2_; }
}
// Locks for dumping
MUTEX_T dumpAlignLock_;
MUTEX_T dumpAlignLockPE_; // _1 and _2
MUTEX_T dumpUnalLock_;
MUTEX_T dumpUnalLockPE_; // _1 and _2
MUTEX_T dumpMaxLock_;
MUTEX_T dumpMaxLockPE_; // _1 and _2
// false -> no dumping
bool dumpAlignFlag_;
bool dumpUnalignFlag_;
bool dumpMaxedFlag_;
volatile bool first_; /// true -> first hit hasn't yet been reported
volatile uint64_t numAligned_; /// # reads with >= 1 alignment
volatile uint64_t numUnaligned_;/// # reads with no alignments
volatile uint64_t numMaxed_; /// # reads with # alignments exceeding -m ceiling
volatile uint64_t numReported_; /// # single-ended alignments reported
volatile uint64_t numReportedPaired_; /// # paired-end alignments reported
bool quiet_; /// true -> don't print alignment stats at the end
ios_base::openmode ssmode_; /// output mode for stringstreams
};
/**
* A per-thread wrapper for a HitSink. Incorporates state that a
* single search thread cares about.
*/
class HitSinkPerThread {
public:
HitSinkPerThread(HitSink& sink, uint32_t max, uint32_t n) :
_sink(sink),
_bestRemainingStratum(0),
_numValidHits(0llu),
_hits(),
_bufferedHits(),
hitsForThisRead_(),
_max(max),
_n(n)
{
_sink.addWrapper();
assert_gt(_n, 0);
}
virtual ~HitSinkPerThread() { }
/// Return the vector of retained hits
vector<Hit>& retainedHits() { return _hits; }
/// Finalize current read
virtual uint32_t finishRead(PatternSourcePerThread& p, bool report, bool dump) {
uint32_t ret = finishReadImpl();
_bestRemainingStratum = 0;
if(!report) {
_bufferedHits.clear();
return 0;
}
bool maxed = (ret > _max);
bool unal = (ret == 0);
if(dump && (unal || maxed)) {
// Either no reportable hits were found or the number of
// reportable hits exceeded the -m limit specified by the
// user
assert(ret == 0 || ret > _max);