forked from DaehwanKimLab/centrifuge
-
Notifications
You must be signed in to change notification settings - Fork 0
/
aln_sink.h
2488 lines (2261 loc) · 79.5 KB
/
aln_sink.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 ALN_SINK_H_
#define ALN_SINK_H_
#include <limits>
#include <utility>
#include <map>
#include "read.h"
#include "ds.h"
#include "simple_func.h"
#include "outq.h"
#include "aligner_result.h"
#include "hyperloglogplus.h"
#include "timer.h"
#include "taxonomy.h"
// Forward decl
template <typename index_t>
class SeedResults;
enum {
OUTPUT_SAM = 1
};
struct ReadCounts {
uint32_t n_reads;
uint32_t sum_score;
double summed_hit_len;
double weighted_reads;
uint32_t n_unique_reads;
};
/**
* Metrics summarizing the species level information we have
*/
struct SpeciesMetrics {
//
struct IDs {
EList<uint64_t, 5> ids;
bool operator<(const IDs& o) const {
if(ids.size() != o.ids.size()) return ids.size() < o.ids.size();
for(size_t i = 0; i < ids.size(); i++) {
assert_lt(i, o.ids.size());
if(ids[i] != o.ids[i]) return ids[i] < o.ids[i];
}
return false;
}
IDs& operator=(const IDs& other) {
if(this == &other)
return *this;
ids = other.ids;
return *this;
}
};
SpeciesMetrics():mutex_m() {
reset();
}
void reset() {
species_counts.clear();
//for(map<uint32_t, HyperLogLogPlusMinus<uint64_t> >::iterator it = this->species_kmers.begin(); it != this->species_kmers.end(); ++it) {
// it->second.reset();
//} //TODO: is this required?
species_kmers.clear();
num_non_leaves = 0;
}
void init(
const map<uint64_t, ReadCounts>& species_counts_,
const map<uint64_t, HyperLogLogPlusMinus<uint64_t> >& species_kmers_,
const map<IDs, uint64_t>& observed_)
{
species_counts = species_counts_;
species_kmers = species_kmers_;
observed = observed_;
num_non_leaves = 0;
}
/**
* Merge (add) the counters in the given ReportingMetrics object
* into this object. This is the only safe way to update a
* ReportingMetrics shared by multiple threads.
*/
void merge(const SpeciesMetrics& met, bool getLock = false) {
ThreadSafe ts(&mutex_m, getLock);
// update species read count
for(map<uint64_t, ReadCounts>::const_iterator it = met.species_counts.begin(); it != met.species_counts.end(); ++it) {
if (species_counts.find(it->first) == species_counts.end()) {
species_counts[it->first] = it->second;
} else {
species_counts[it->first].n_reads += it->second.n_reads;
species_counts[it->first].sum_score += it->second.sum_score;
species_counts[it->first].summed_hit_len += it->second.summed_hit_len;
species_counts[it->first].weighted_reads += it->second.weighted_reads;
species_counts[it->first].n_unique_reads += it->second.n_unique_reads;
}
}
// update species k-mers
for(map<uint64_t, HyperLogLogPlusMinus<uint64_t> >::const_iterator it = met.species_kmers.begin(); it != met.species_kmers.end(); ++it) {
species_kmers[it->first].merge(&(it->second));
}
for(map<IDs, uint64_t>::const_iterator itr = met.observed.begin(); itr != met.observed.end(); itr++) {
const IDs& ids = itr->first;
uint64_t count = itr->second;
if(observed.find(ids) == observed.end()) {
observed[ids] = count;
} else {
observed[ids] += count;
}
}
}
void addSpeciesCounts(
uint64_t taxID,
int64_t score,
int64_t max_score,
double summed_hit_len,
double weighted_read,
uint32_t nresult)
{
species_counts[taxID].n_reads += 1;
species_counts[taxID].sum_score += 1;
species_counts[taxID].weighted_reads += weighted_read;
species_counts[taxID].summed_hit_len += summed_hit_len;
if(nresult == 1) {
species_counts[taxID].n_unique_reads += 1;
}
// Only consider good hits for abundance analysis
// DK - for debugging purposes
if(score >= max_score) {
cur_ids.ids.push_back(taxID);
if(cur_ids.ids.size() == nresult) {
cur_ids.ids.sort();
if(observed.find(cur_ids) == observed.end()) {
observed[cur_ids] = 1;
} else {
observed[cur_ids] += 1;
}
cur_ids.ids.clear();
}
}
}
void addAllKmers(
uint64_t taxID,
const BTDnaString &btdna,
size_t begin,
size_t len) {
#ifdef FLORIAN_DEBUG
cerr << "add all kmers for " << taxID << " from " << begin << " for " << len << ": " << string(btdna.toZBuf()).substr(begin,len) << endl;
#endif
uint64_t kmer = btdna.int_kmer<uint64_t>(begin,begin+len);
species_kmers[taxID].add(kmer);
size_t i = begin;
while (i+32 < len) {
kmer = btdna.next_kmer(kmer,i);
species_kmers[taxID].add(kmer);
++i;
}
}
size_t nDistinctKmers(uint64_t taxID) {
return(species_kmers[taxID].cardinality());
}
static void EM(
const map<IDs, uint64_t>& observed,
const map<uint64_t, EList<uint64_t> >& ancestors,
const map<uint64_t, uint64_t>& tid_to_num,
const EList<double>& p,
EList<double>& p_next,
const EList<size_t>& len)
{
assert_eq(p.size(), len.size());
// E step
p_next.fill(0.0);
// for each assigned read set
for(map<IDs, uint64_t>::const_iterator itr = observed.begin(); itr != observed.end(); itr++) {
const EList<uint64_t, 5>& ids = itr->first.ids; // all ids assigned to the read set
uint64_t count = itr->second; // number of reads in the read set
double psum = 0.0;
for(size_t i = 0; i < ids.size(); i++) {
uint64_t tid = ids[i];
// Leaves?
map<uint64_t, uint64_t>::const_iterator id_itr = tid_to_num.find(tid);
if(id_itr != tid_to_num.end()) {
uint64_t num = id_itr->second;
assert_lt(num, p.size());
psum += p[num];
} else { // Ancestors
map<uint64_t, EList<uint64_t> >::const_iterator a_itr = ancestors.find(tid);
if(a_itr == ancestors.end())
continue;
const EList<uint64_t>& children = a_itr->second;
for(size_t c = 0; c < children.size(); c++) {
uint64_t c_tid = children[c];
map<uint64_t, uint64_t>::const_iterator id_itr = tid_to_num.find(c_tid);
if(id_itr == tid_to_num.end())
continue;
uint64_t c_num = id_itr->second;
psum += p[c_num];
}
}
}
if(psum == 0.0) continue;
for(size_t i = 0; i < ids.size(); i++) {
uint64_t tid = ids[i];
// Leaves?
map<uint64_t, uint64_t>::const_iterator id_itr = tid_to_num.find(tid);
if(id_itr != tid_to_num.end()) {
uint64_t num = id_itr->second;
assert_leq(p[num], psum);
p_next[num] += (count * (p[num] / psum));
} else {
map<uint64_t, EList<uint64_t> >::const_iterator a_itr = ancestors.find(tid);
if(a_itr == ancestors.end())
continue;
const EList<uint64_t>& children = a_itr->second;
for(size_t c = 0; c < children.size(); c++) {
uint64_t c_tid = children[c];
map<uint64_t, uint64_t>::const_iterator id_itr = tid_to_num.find(c_tid);
if(id_itr == tid_to_num.end())
continue;
uint64_t c_num = id_itr->second;
p_next[c_num] += (count * (p[c_num] / psum));
}
}
}
}
// M step
double sum = 0.0;
for(size_t i = 0; i < p_next.size(); i++) {
sum += (p_next[i] / len[i]);
}
for(size_t i = 0; i < p_next.size(); i++) {
p_next[i] = p_next[i] / len[i] / sum;
}
}
void calculateAbundance(const Ebwt<uint64_t>& ebwt, uint8_t rank)
{
const map<uint64_t, TaxonomyNode>& tree = ebwt.tree();
// Find leaves
set<uint64_t> leaves;
for(map<IDs, uint64_t>::iterator itr = observed.begin(); itr != observed.end(); itr++) {
const IDs& ids = itr->first;
for(size_t i = 0; i < ids.ids.size(); i++) {
uint64_t tid = ids.ids[i];
map<uint64_t, TaxonomyNode>::const_iterator tree_itr = tree.find(tid);
if(tree_itr == tree.end())
continue;
const TaxonomyNode& node = tree_itr->second;
if(!node.leaf) {
//if(tax_rank_num[node.rank] > tax_rank_num[rank]) {
continue;
//}
}
leaves.insert(tree_itr->first);
}
}
#ifdef DAEHWAN_DEBUG
cerr << "\t\tnumber of leaves: " << leaves.size() << endl;
#endif
// Find all descendants coming from the same ancestor
map<uint64_t, EList<uint64_t> > ancestors;
for(map<IDs, uint64_t>::iterator itr = observed.begin(); itr != observed.end(); itr++) {
const IDs& ids = itr->first;
for(size_t i = 0; i < ids.ids.size(); i++) {
uint64_t tid = ids.ids[i];
if(leaves.find(tid) != leaves.end())
continue;
if(ancestors.find(tid) != ancestors.end())
continue;
ancestors[tid].clear();
for(set<uint64_t> ::const_iterator leaf_itr = leaves.begin(); leaf_itr != leaves.end(); leaf_itr++) {
uint64_t tid2 = *leaf_itr;
assert(tree.find(tid2) != tree.end());
assert(tree.find(tid2)->second.leaf);
uint64_t temp_tid2 = tid2;
while(true) {
map<uint64_t, TaxonomyNode>::const_iterator tree_itr = tree.find(temp_tid2);
if(tree_itr == tree.end())
break;
const TaxonomyNode& node = tree_itr->second;
if(tid == node.parent_tid) {
ancestors[tid].push_back(tid2);
}
if(temp_tid2 == node.parent_tid)
break;
temp_tid2 = node.parent_tid;
}
}
ancestors[tid].sort();
}
}
#ifdef DAEHWAN_DEBUG
cerr << "\t\tnumber of ancestors: " << ancestors.size() << endl;
for(map<uint64_t, EList<uint64_t> >::const_iterator itr = ancestors.begin(); itr != ancestors.end(); itr++) {
uint64_t tid = itr->first;
const EList<uint64_t>& children = itr->second;
if(children.size() <= 0)
continue;
map<uint64_t, TaxonomyNode>::const_iterator tree_itr = tree.find(tid);
if(tree_itr == tree.end())
continue;
const TaxonomyNode& node = tree_itr->second;
cerr << "\t\t\t" << tid << ": " << children.size() << "\t" << get_tax_rank(node.rank) << endl;
cerr << "\t\t\t\t";
for(size_t i = 0; i < children.size(); i++) {
cerr << children[i];
if(i + 1 < children.size())
cerr << ",";
if(i > 10) {
cerr << " ...";
break;
}
}
cerr << endl;
}
uint64_t test_tid = 0, test_tid2 = 0;
#endif
// Lengths of genomes (or contigs)
const map<uint64_t, uint64_t>& size_table = ebwt.size();
// Initialize probabilities
map<uint64_t, uint64_t> tid_to_num; // taxonomic ID to corresponding element of a list
EList<double> p;
EList<size_t> len; // genome lengths
for(map<IDs, uint64_t>::iterator itr = observed.begin(); itr != observed.end(); itr++) {
const IDs& ids = itr->first;
uint64_t count = itr->second;
for(size_t i = 0; i < ids.ids.size(); i++) {
uint64_t tid = ids.ids[i];
if(leaves.find(tid) == leaves.end())
continue;
#ifdef DAEHWAN_DEBUG
if((tid == test_tid || tid == test_tid2) &&
count >= 100) {
cerr << tid << ": " << count << "\t";
for(size_t j = 0; j < ids.ids.size(); j++) {
cerr << ids.ids[j];
if(j + 1 < ids.ids.size())
cerr << ",";
}
cerr << endl;
}
#endif
if(tid_to_num.find(tid) == tid_to_num.end()) {
tid_to_num[tid] = p.size();
p.push_back(1.0 / ids.ids.size() * count);
map<uint64_t, uint64_t>::const_iterator size_itr = size_table.find(tid);
if(size_itr != size_table.end()) {
len.push_back(size_itr->second);
} else {
len.push_back(std::numeric_limits<size_t>::max());
}
} else {
uint64_t num = tid_to_num[tid];
assert_lt(num, p.size());
p[num] += (1.0 / ids.ids.size() * count);
}
}
}
assert_eq(p.size(), len.size());
{
double sum = 0.0;
for(size_t i = 0; i < p.size(); i++) {
sum += (p[i] / len[i]);
}
for(size_t i = 0; i < p.size(); i++) {
p[i] = (p[i] / len[i]) / sum;
}
}
EList<double> p_next; p_next.resizeExact(p.size());
EList<double> p_next2; p_next2.resizeExact(p.size());
EList<double> p_r; p_r.resizeExact(p.size());
EList<double> p_v; p_v.resizeExact(p.size());
size_t num_iteration = 0;
double diff = 0.0;
while(true) {
#ifdef DAEHWAN_DEBUG
if(num_iteration % 50 == 0) {
if(test_tid != 0 || test_tid2 != 0)
cerr << "iter " << num_iteration << endl;
if(test_tid != 0)
cerr << "\t" << test_tid << ": " << p[tid_to_num[test_tid]] << endl;
if(test_tid2 != 0)
cerr << "\t" << test_tid2 << ": " << p[tid_to_num[test_tid2]] << endl;
}
#endif
// Accelerated version of EM - SQUAREM iteration
// Varadhan, R. & Roland, C. Scand. J. Stat. 35, 335–353 (2008).
// Also, this algorithm is used in Sailfish - http://www.nature.com/nbt/journal/v32/n5/full/nbt.2862.html
#if 1
EM(observed, ancestors, tid_to_num, p, p_next, len);
EM(observed, ancestors, tid_to_num, p_next, p_next2, len);
double sum_squared_r = 0.0, sum_squared_v = 0.0;
for(size_t i = 0; i < p.size(); i++) {
p_r[i] = p_next[i] - p[i];
sum_squared_r += (p_r[i] * p_r[i]);
p_v[i] = p_next2[i] - p_next[i] - p_r[i];
sum_squared_v += (p_v[i] * p_v[i]);
}
if(sum_squared_v > 0.0) {
double gamma = -sqrt(sum_squared_r / sum_squared_v);
for(size_t i = 0; i < p.size(); i++) {
p_next2[i] = max(0.0, p[i] - 2 * gamma * p_r[i] + gamma * gamma * p_v[i]);
}
EM(observed, ancestors, tid_to_num, p_next2, p_next, len);
}
#else
EM(observed, ancestors, tid_to_num, p, p_next, len);
#endif
diff = 0.0;
for(size_t i = 0; i < p.size(); i++) {
diff += (p[i] > p_next[i] ? p[i] - p_next[i] : p_next[i] - p[i]);
}
if(diff < 0.0000000001) break;
if(++num_iteration >= 10000) break;
p = p_next;
}
cerr << "Number of iterations in EM algorithm: " << num_iteration << endl;
cerr << "Probability diff. (P - P_prev) in the last iteration: " << diff << endl;
{
// Calculate abundance normalized by genome size
abundance_len.clear();
double sum = 0.0;
for(map<uint64_t, uint64_t>::iterator itr = tid_to_num.begin(); itr != tid_to_num.end(); itr++) {
uint64_t tid = itr->first;
uint64_t num = itr->second;
assert_lt(num, p.size());
abundance_len[tid] = p[num];
sum += (p[num] * len[num]);
}
// Calculate abundance without genome size taken into account
abundance.clear();
for(map<uint64_t, uint64_t>::iterator itr = tid_to_num.begin(); itr != tid_to_num.end(); itr++) {
uint64_t tid = itr->first;
uint64_t num = itr->second;
assert_lt(num, p.size());
abundance[tid] = (p[num] * len[num]) / sum;
}
}
}
map<uint64_t, ReadCounts> species_counts; // read count per species
map<uint64_t, HyperLogLogPlusMinus<uint64_t> > species_kmers; // unique k-mer count per species
map<IDs, uint64_t> observed;
IDs cur_ids;
uint32_t num_non_leaves;
map<uint64_t, double> abundance; // abundance without genome size taken into consideration
map<uint64_t, double> abundance_len; // abundance normalized by genome size
MUTEX_T mutex_m;
};
/**
* Metrics summarizing the work done by the reporter and summarizing
* the number of reads that align, that fail to align, and that align
* non-uniquely.
*/
struct ReportingMetrics {
ReportingMetrics():mutex_m() {
reset();
}
void reset() {
init(0, 0, 0, 0);
}
void init(
uint64_t nread_,
uint64_t npaired_,
uint64_t nunpaired_,
uint64_t nconcord_uni_)
{
nread = nread_;
npaired = npaired_;
nunpaired = nunpaired_;
nconcord_uni = nconcord_uni_;
}
/**
* Merge (add) the counters in the given ReportingMetrics object
* into this object. This is the only safe way to update a
* ReportingMetrics shared by multiple threads.
*/
void merge(const ReportingMetrics& met, bool getLock = false) {
ThreadSafe ts(&mutex_m, getLock);
nread += met.nread;
npaired += met.npaired;
nunpaired += met.nunpaired;
nconcord_uni += met.nconcord_uni;
}
uint64_t nread; // # reads
uint64_t npaired; // # pairs
uint64_t nunpaired; // # unpaired reads
// Paired
// Concordant
uint64_t nconcord_uni; // # pairs with unique concordant alns
MUTEX_T mutex_m;
};
// Type for expression numbers of hits
typedef int64_t THitInt;
/**
* Parameters affecting reporting of alignments, specifically -k & -a,
* -m & -M.
*/
struct ReportingParams {
explicit ReportingParams(THitInt khits_, bool compressed_)
{
init(khits_, compressed_);
}
void init(THitInt khits_, bool compressed_)
{
khits = khits_; // -k (or high if -a)
if(compressed_) {
ihits = max<THitInt>(khits, 5) * 4;
} else {
ihits = max<THitInt>(khits, 5) * 40;
}
}
#ifndef NDEBUG
/**
* Check that reporting parameters are internally consistent.
*/
bool repOk() const {
assert_geq(khits, 1);
return true;
}
#endif
inline THitInt mult() const {
return khits;
}
// Number of assignments to report
THitInt khits;
// Number of internal assignments
THitInt ihits;
};
/**
* A state machine keeping track of the number and type of alignments found so
* far. Its purpose is to inform the caller as to what stage the alignment is
* in and what categories of alignment are still of interest. This information
* should allow the caller to short-circuit some alignment work. Another
* purpose is to tell the AlnSinkWrap how many and what type of alignment to
* report.
*
* TODO: This class does not keep accurate information about what
* short-circuiting took place. If a read is identical to a previous read,
* there should be a way to query this object to determine what work, if any,
* has to be re-done for the new read.
*/
class ReportingState {
public:
enum {
NO_READ = 1, // haven't got a read yet
CONCORDANT_PAIRS, // looking for concordant pairs
DONE // finished looking
};
// Flags for different ways we can finish out a category of potential
// alignments.
enum {
EXIT_DID_NOT_EXIT = 1, // haven't finished
EXIT_DID_NOT_ENTER, // never tried search
EXIT_SHORT_CIRCUIT_k, // -k exceeded
EXIT_NO_ALIGNMENTS, // none found
EXIT_WITH_ALIGNMENTS // some found
};
ReportingState(const ReportingParams& p) : p_(p) { reset(); }
/**
* Set all state to uninitialized defaults.
*/
void reset() {
state_ = ReportingState::NO_READ;
paired_ = false;
nconcord_ = 0;
doneConcord_ = false;
exitConcord_ = ReportingState::EXIT_DID_NOT_ENTER;
done_ = false;
}
/**
* Return true iff this ReportingState has been initialized with a call to
* nextRead() since the last time reset() was called.
*/
bool inited() const { return state_ != ReportingState::NO_READ; }
/**
* Initialize state machine with a new read. The state we start in depends
* on whether it's paired-end or unpaired.
*/
void nextRead(bool paired);
/**
* Caller uses this member function to indicate that one additional
* concordant alignment has been found.
*/
bool foundConcordant();
/**
* Caller uses this member function to indicate that one additional
* discordant alignment has been found.
*/
bool foundUnpaired(bool mate1);
/**
* Called to indicate that the aligner has finished searching for
* alignments. This gives us a chance to finalize our state.
*
* TODO: Keep track of short-circuiting information.
*/
void finish();
/**
* Populate given counters with the number of various kinds of alignments
* to report for this read. Concordant alignments are preferable to (and
* mutually exclusive with) discordant alignments, and paired-end
* alignments are preferable to unpaired alignments.
*
* The caller also needs some additional information for the case where a
* pair or unpaired read aligns repetitively. If the read is paired-end
* and the paired-end has repetitive concordant alignments, that should be
* reported, and 'pairMax' is set to true to indicate this. If the read is
* paired-end, does not have any conordant alignments, but does have
* repetitive alignments for one or both mates, then that should be
* reported, and 'unpair1Max' and 'unpair2Max' are set accordingly.
*
* Note that it's possible in the case of a paired-end read for the read to
* have repetitive concordant alignments, but for one mate to have a unique
* unpaired alignment.
*/
void getReport(uint64_t& nconcordAln) const; // # concordant alignments to report
/**
* Return an integer representing the alignment state we're in.
*/
inline int state() const { return state_; }
/**
* If false, there's no need to solve any more dynamic programming problems
* for finding opposite mates.
*/
inline bool doneConcordant() const { return doneConcord_; }
/**
* Return true iff all alignment stages have been exited.
*/
inline bool done() const { return done_; }
inline uint64_t numConcordant() const { return nconcord_; }
inline int exitConcordant() const { return exitConcord_; }
/**
* Return ReportingParams object governing this ReportingState.
*/
const ReportingParams& params() const {
return p_;
}
protected:
const ReportingParams& p_; // reporting parameters
int state_; // state we're currently in
bool paired_; // true iff read we're currently handling is paired
uint64_t nconcord_; // # concordants found so far
bool doneConcord_; // true iff we're no longner interested in concordants
int exitConcord_; // flag indicating how we exited concordant state
bool done_; // done with all alignments
};
/**
* Global hit sink for hits from the MultiSeed aligner. Encapsulates
* all aspects of the MultiSeed aligner hitsink that are global to all
* threads. This includes aspects relating to:
*
* (a) synchronized access to the output stream
* (b) the policy to be enforced by the per-thread wrapper
*
* TODO: Implement splitting up of alignments into separate files
* according to genomic coordinate.
*/
template <typename index_t>
class AlnSink {
typedef EList<std::string> StrList;
public:
explicit AlnSink(
OutputQueue& oq,
const StrList& refnames,
const EList<uint32_t>& tab_fmt_cols,
bool quiet) :
oq_(oq),
refnames_(refnames),
tab_fmt_cols_(tab_fmt_cols),
quiet_(quiet)
{
}
/**
* Destroy HitSinkobject;
*/
virtual ~AlnSink() { }
/**
* Called when the AlnSink is wrapped by a new AlnSinkWrap. This helps us
* keep track of whether the main lock or any of the per-stream locks will
* be contended by multiple threads.
*/
void addWrapper() { numWrappers_++; }
/**
* Append a single hit to the given output stream. If
* synchronization is required, append() assumes the caller has
* already grabbed the appropriate lock.
*/
virtual void append(
BTString& o,
size_t threadId,
const Read *rd1,
const Read *rd2,
const TReadId rdid,
AlnRes *rs1,
AlnRes *rs2,
const AlnSetSumm& summ,
const PerReadMetrics& prm,
SpeciesMetrics& sm,
bool report2,
size_t n_results) = 0;
/**
* Report a given batch of hits for the given read or read pair.
* Should be called just once per read pair. Assumes all the
* alignments are paired, split between rs1 and rs2.
*
* The caller hasn't decided which alignments get reported as primary
* or secondary; that's up to the routine. Because the caller might
* want to know this, we use the pri1 and pri2 out arguments to
* convey this.
*/
virtual void reportHits(
BTString& o, // write to this buffer
size_t threadId, // which thread am I?
const Read *rd1, // mate #1
const Read *rd2, // mate #2
const TReadId rdid, // read ID
const EList<size_t>& select1, // random subset of rd1s
const EList<size_t>* select2, // random subset of rd2s
EList<AlnRes> *rs1, // alignments for mate #1
EList<AlnRes> *rs2, // alignments for mate #2
bool maxed, // true iff -m/-M exceeded
const AlnSetSumm& summ, // summary
const PerReadMetrics& prm, // per-read metrics
SpeciesMetrics& sm, // species metrics
bool getLock = true) // true iff lock held by caller
{
assert(rd1 != NULL || rd2 != NULL);
assert(rs1 != NULL || rs2 != NULL);
for(size_t i = 0; i < select1.size(); i++) {
AlnRes* r1 = ((rs1 != NULL) ? &rs1->get(select1[i]) : NULL);
AlnRes* r2 = ((rs2 != NULL) ? &rs2->get(select1[i]) : NULL);
append(o, threadId, rd1, rd2, rdid, r1, r2, summ, prm, sm, true, select1.size());
}
}
/**
* Report an unaligned read. Typically we do nothing, but we might
* want to print a placeholder when output is chained.
*/
virtual void reportUnaligned(
BTString& o, // write to this string
size_t threadId, // which thread am I?
const Read *rd1, // mate #1
const Read *rd2, // mate #2
const TReadId rdid, // read ID
const AlnSetSumm& summ, // summary
const PerReadMetrics& prm, // per-read metrics
bool report2, // report alns for both mates?
bool getLock = true) // true iff lock held by caller
{
// FIXME: reportUnaligned does nothing
//append(o, threadId, rd1, rd2, rdid, NULL, NULL, summ, prm, NULL,report2);
}
/**
* Print summary of how many reads aligned, failed to align and aligned
* repetitively. Write it to stderr. Optionally write Hadoop counter
* updates.
*/
void printAlSumm(
const ReportingMetrics& met,
size_t repThresh, // threshold for uniqueness, or max if no thresh
bool discord, // looked for discordant alignments
bool mixed, // looked for unpaired alignments where paired failed?
bool hadoopOut); // output Hadoop counters?
/**
* Called when all alignments are complete. It is assumed that no
* synchronization is necessary.
*/
void finish(
size_t repThresh,
bool discord,
bool mixed,
bool hadoopOut)
{
// Close output streams
if(!quiet_) {
printAlSumm(
met_,
repThresh,
discord,
mixed,
hadoopOut);
}
}
#ifndef NDEBUG
/**
* Check that hit sink is internally consistent.
*/
bool repOk() const { return true; }
#endif
//
// Related to reporting seed hits
//
/**
* Given a Read and associated, filled-in SeedResults objects,
* print a record summarizing the seed hits.
*/
void reportSeedSummary(
BTString& o,
const Read& rd,
TReadId rdid,
size_t threadId,
const SeedResults<index_t>& rs,
bool getLock = true);
/**
* Given a Read, print an empty record (all 0s).
*/
void reportEmptySeedSummary(
BTString& o,
const Read& rd,
TReadId rdid,
size_t threadId,
bool getLock = true);
/**
* Append a batch of unresolved seed alignment results (i.e. seed
* alignments where all we know is the reference sequence aligned
* to and its SA range, not where it falls in the reference
* sequence) to the given output stream in Bowtie's seed-alignment
* verbose-mode format.
*/
virtual void appendSeedSummary(
BTString& o,
const Read& rd,
const TReadId rdid,
size_t seedsTried,
size_t nonzero,
size_t ranges,
size_t elts,
size_t seedsTriedFw,
size_t nonzeroFw,
size_t rangesFw,
size_t eltsFw,
size_t seedsTriedRc,
size_t nonzeroRc,
size_t rangesRc,
size_t eltsRc);
/**
* Merge given metrics in with ours by summing all individual metrics.
*/
void mergeMetrics(const ReportingMetrics& met, bool getLock = true) {
met_.merge(met, getLock);
}
/**
* Return mutable reference to the shared OutputQueue.
*/
OutputQueue& outq() {
return oq_;
}
protected:
OutputQueue& oq_; // output queue
int numWrappers_; // # threads owning a wrapper for this HitSink
const StrList& refnames_; // reference names
const EList<uint32_t>& tab_fmt_cols_; // Columns that are printed in tabular format
bool quiet_; // true -> don't print alignment stats at the end
ReportingMetrics met_; // global repository of reporting metrics
};
/**
* Per-thread hit sink "wrapper" for the MultiSeed aligner. Encapsulates
* aspects of the MultiSeed aligner hit sink that are per-thread. This
* includes aspects relating to:
*
* (a) Enforcement of the reporting policy
* (b) Tallying of results
* (c) Storing of results for the previous read in case this allows us to
* short-circuit some work for the next read (i.e. if it's identical)
*
* PHASED ALIGNMENT ASSUMPTION
*
* We make some assumptions about how alignment proceeds when we try to
* short-circuit work for identical reads. Specifically, we assume that for
* each read the aligner proceeds in a series of stages (or perhaps just one
* stage). In each stage, the aligner either:
*
* (a) Finds no alignments, or
* (b) Finds some alignments and short circuits out of the stage with some
* random reporting involved (e.g. in -k and/or -M modes), or
* (c) Finds all of the alignments in the stage
*
* In the event of (a), the aligner proceeds to the next stage and keeps