forked from DaehwanKimLab/hisat2
-
Notifications
You must be signed in to change notification settings - Fork 6
/
aligner_result.cpp
2124 lines (2008 loc) · 55.6 KB
/
aligner_result.cpp
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 <[email protected]>
*
* 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/>.
*/
#include <iostream>
#include "reference.h"
#include "aligner_result.h"
#include "read.h"
#include "edit.h"
#include "sstring.h"
#include "ds.h"
#include "util.h"
#include "alphabet.h"
using namespace std;
/**
* Clear all contents.
*/
void AlnRes::reset() {
if(ned_ != NULL) {
assert(aed_ != NULL);
ned_->clear();
aed_->clear();
}
score_.invalidate();
refcoord_.reset();
refival_.reset();
shapeSet_ = false;
rdlen_ = 0;
rdid_ = 0;
reflen_ = 0;
rdrows_ = 0;
rdextent_ = 0;
rdexrows_ = 0;
rfextent_ = 0;
refns_ = 0;
type_ = ALN_RES_TYPE_UNPAIRED;
fraglen_ = -1;
trimSoft_ = false;
trim5p_ = 0;
trim3p_ = 0;
pretrimSoft_ = true;
pretrim5p_ = 0;
pretrim3p_ = 0;
seedmms_ = 0; // number of mismatches allowed in seed
seedlen_ = 0; // length of seed
seedival_ = 0; // interval between seeds
minsc_ = 0; // minimum score
nuc5p_ = 0;
nuc3p_ = 0;
fraglenSet_ = false;
num_spliced_ = 0;
assert(!refcoord_.inited());
assert(!refival_.inited());
}
/**
* Set the upstream-most reference offset involved in the alignment, and
* the extent of the alignment (w/r/t the reference)
*/
void AlnRes::setShape(
TRefId id, // id of reference aligned to
TRefOff off, // offset of first aligned char into ref seq
TRefOff reflen, // length of reference sequence aligned to
bool fw, // aligned to Watson strand?
size_t rdlen, // length of read after hard trimming, before soft
TReadId rdid, // read ID
bool pretrimSoft, // whether trimming prior to alignment was soft
size_t pretrim5p, // # poss trimmed form 5p end before alignment
size_t pretrim3p, // # poss trimmed form 3p end before alignment
bool trimSoft, // whether local-alignment trimming was soft
size_t trim5p, // # poss trimmed form 5p end during alignment
size_t trim3p) // # poss trimmed form 3p end during alignment
{
rdlen_ = rdlen;
rdid_ = rdid;
rdrows_ = rdlen;
refcoord_.init(id, off, fw);
pretrimSoft_ = pretrimSoft;
pretrim5p_ = pretrim5p;
pretrim3p_ = pretrim3p;
trimSoft_ = trimSoft;
trim5p_ = trim5p;
trim3p_ = trim3p;
// Propagate trimming to the edits. We assume that the pos fields of the
// edits are set w/r/t to the rows of the dynamic programming table, and
// haven't taken trimming into account yet.
//
// TODO: The division of labor between the aligner and the AlnRes is not
// clean. Perhaps the trimming and *all* of its side-effects should be
// handled by the aligner.
// daehwan - check this out - this doesn't seem to work with SAWHI
// size_t trimBeg = fw ? trim5p : trim3p;
size_t trimBeg = trim5p;
if(trimBeg > 0) {
for(size_t i = 0; i < ned_->size(); i++) {
// Shift by trim5p, since edits are w/r/t 5p end
assert_geq((*ned_)[i].pos, trimBeg);
(*ned_)[i].pos -= (uint32_t)trimBeg;
}
}
// Length after all soft trimming and any hard trimming that occurred
// during alignment
rdextent_ = rdlen;
if(pretrimSoft_) {
rdextent_ -= (pretrim5p + pretrim3p); // soft trim
}
rdextent_ -= (trim5p + trim3p); // soft or hard trim from alignment
assert_gt(rdextent_, 0);
rdexrows_ = rdextent_;
calcRefExtent();
refival_.init(id, off, fw, rfextent_);
reflen_ = reflen;
shapeSet_ = true;
}
/**
* Initialize new AlnRes.
*/
void AlnRes::init(
size_t rdlen, // # chars after hard trimming
TReadId rdid, // read ID
AlnScore score, // alignment score
const EList<Edit>* ned, // nucleotide edits
size_t ned_i, // first position to copy
size_t ned_n, // # positions to copy
const EList<Edit>* aed, // ambiguous base resolutions
size_t aed_i, // first position to copy
size_t aed_n, // # positions to copy
Coord refcoord, // leftmost ref pos of 1st al char
TRefOff reflen, // length of ref aligned to
LinkedEList<EList<Edit> >* raw_edits,
int seedmms, // # seed mms allowed
int seedlen, // seed length
int seedival, // space between seeds
int64_t minsc, // minimum score for valid aln
int nuc5p,
int nuc3p,
bool pretrimSoft,
size_t pretrim5p, // trimming prior to alignment
size_t pretrim3p, // trimming prior to alignment
bool trimSoft,
size_t trim5p, // trimming from alignment
size_t trim3p) // trimming from alignment
{
assert(raw_edits != NULL);
assert(raw_edits_ == NULL || raw_edits_ == raw_edits);
raw_edits_ = raw_edits;
if(ned_ != NULL) {
assert(aed_ != NULL);
ned_->clear();
aed_->clear();
} else if(raw_edits_ != NULL) {
assert(aed_ == NULL);
assert(ned_node_ == NULL && aed_node_ == NULL);
ned_node_ = raw_edits_->new_node();
aed_node_ = raw_edits_->new_node();
assert(ned_node_ != NULL && aed_node_ != NULL);
ned_ = &(ned_node_->payload);
aed_ = &(aed_node_->payload);
}
rdlen_ = rdlen;
rdid_ = rdid;
rdrows_ = rdlen;
score_ = score;
ned_->clear();
aed_->clear();
if(ned != NULL) {
for(size_t i = ned_i; i < ned_i + ned_n; i++) {
ned_->push_back((*ned)[i]);
}
}
if(aed != NULL) {
for(size_t i = aed_i; i < aed_i + aed_n; i++) {
aed_->push_back((*aed)[i]);
}
}
refcoord_ = refcoord;
reflen_ = reflen;
seedmms_ = seedmms;
seedlen_ = seedlen;
seedival_ = seedival;
minsc_ = minsc;
nuc5p_ = nuc5p;
nuc3p_ = nuc3p;
pretrimSoft_ = pretrimSoft;
pretrim5p_ = pretrim5p;
pretrim3p_ = pretrim3p;
trimSoft_ = trimSoft;
trim5p_ = trim5p;
trim3p_ = trim3p;
rdextent_ = rdlen; // # read characters after any hard trimming
if(pretrimSoft) {
rdextent_ -= (pretrim5p + pretrim3p);
}
if(trimSoft) {
rdextent_ -= (trim5p + trim3p);
}
rdexrows_ = rdextent_;
calcRefExtent();
setShape(
refcoord.ref(), // id of reference aligned to
refcoord.off(), // offset of first aligned char into ref seq
reflen, // length of reference sequence aligned to
refcoord.fw(), // aligned to Watson strand?
rdlen, // length of read after hard trimming, before soft
rdid, // read ID
pretrimSoft, // whether trimming prior to alignment was soft
pretrim5p, // # poss trimmed form 5p end before alignment
pretrim3p, // # poss trimmed form 3p end before alignment
trimSoft, // whether local-alignment trimming was soft
trim5p, // # poss trimmed form 5p end during alignment
trim3p); // # poss trimmed form 3p end during alignment
shapeSet_ = true;
num_spliced_ = 0;
for(size_t i = 0; i < ned_->size(); i++) {
if((*ned_)[i].type == EDIT_TYPE_SPL) {
num_spliced_++;
}
}
}
/**
* Clip given number of characters from the Watson-upstream end of the
* alignment.
*/
void AlnRes::clipLeft(size_t rd_amt, size_t rf_amt) {
assert_geq(rd_amt, 0);
assert_geq(rf_amt, 0);
assert_leq(rd_amt, rdexrows_);
assert_leq(rf_amt, rfextent_);
assert(trimSoft_);
if(fw()) {
trim5p_ += rd_amt;
Edit::clipLo(*ned_, rdexrows_, rd_amt);
Edit::clipLo(*aed_, rdexrows_, rd_amt);
} else {
trim3p_ += rd_amt;
Edit::clipHi(*ned_, rdexrows_, rd_amt);
Edit::clipHi(*aed_, rdexrows_, rd_amt);
}
rdexrows_ -= rd_amt;
rdextent_ -= rd_amt;
rfextent_ -= rf_amt;
refcoord_.adjustOff(rf_amt);
refival_.adjustOff(rf_amt);
// Adjust refns_?
}
/**
* Clip given number of characters from the Watson-downstream end of the
* alignment.
*/
void AlnRes::clipRight(size_t rd_amt, size_t rf_amt) {
assert_geq(rd_amt, 0);
assert_geq(rf_amt, 0);
assert_leq(rd_amt, rdexrows_);
assert_leq(rf_amt, rfextent_);
assert(trimSoft_);
if(fw()) {
trim3p_ += rd_amt;
Edit::clipHi(*ned_, rdexrows_, rd_amt);
Edit::clipHi(*aed_, rdexrows_, rd_amt);
} else {
trim5p_ += rd_amt;
Edit::clipLo(*ned_, rdexrows_, rd_amt);
Edit::clipLo(*aed_, rdexrows_, rd_amt);
}
rdexrows_ -= rd_amt;
rdextent_ -= rd_amt;
rfextent_ -= rf_amt;
// Adjust refns_?
}
/**
* Clip away portions of the alignment that are outside the given bounds.
* Clipping is soft if soft == true, hard otherwise. Assuming for now that
* there isn't any other clipping.
*
* Note that all clipping is expressed in terms of read positions. So if there
* are reference gaps in the overhanging portion, we must
*/
void AlnRes::clipOutside(bool soft, TRefOff refi, TRefOff reff) {
// Overhang on LHS
TRefOff left = refcoord_.off();
if(left < refi) {
size_t rf_amt = (size_t)(refi - left);
size_t rf_i = rf_amt;
size_t nedsz = ned_->size();
if(!fw()) {
Edit::invertPoss(*ned_, rdexrows_, false);
}
for(size_t i = 0; i < nedsz; i++) {
assert_lt((*ned_)[i].pos, rdexrows_);
if((*ned_)[i].pos > rf_i) break;
if((*ned_)[i].isRefGap()) rf_i++;
}
if(!fw()) {
Edit::invertPoss(*ned_, rdexrows_, false);
}
clipLeft(rf_i, rf_amt);
}
// Overhang on RHS
TRefOff right = refcoord_.off() + refNucExtent();
if(right > reff) {
size_t rf_amt = (size_t)(right - reff);
size_t rf_i = rf_amt;
size_t nedsz = ned_->size();
if(fw()) {
Edit::invertPoss(*ned_, rdexrows_, false);
}
for(size_t i = 0; i < nedsz; i++) {
assert_lt((*ned_)[i].pos, rdexrows_);
if((*ned_)[i].pos > rf_i) break;
if((*ned_)[i].isRefGap()) rf_i++;
}
if(fw()) {
Edit::invertPoss(*ned_, rdexrows_, false);
}
clipRight(rf_i, rf_amt);
}
}
/**
* Return true iff this AlnRes and the given AlnRes overlap. Two AlnRess
* overlap if they share a cell in the overall dynamic programming table:
* i.e. if there exists a read position s.t. that position in both reads
* matches up with the same reference character. E.g., the following
* alignments (drawn schematically as paths through a dynamic programming
* table) are redundant:
*
* a b a b
* \ \ \ \
* \ \ \ \
* \ \ \ \
* ---\ \ \
* \ ---\---
* ---\ \ \
* \ \ \ \
* \ \ \ \
* \ \ \ \
* a b a b
*
* We iterate over each read position that hasn't been hard-trimmed, but
* only overlaps at positions that have also not been soft-trimmed are
* considered.
*/
bool AlnRes::overlap(AlnRes& res) {
if(fw() != res.fw() || refid() != res.refid()) {
// Must be same reference and same strand in order to overlap
return false;
}
TRefOff my_left = refoff(); // my leftmost aligned char
TRefOff other_left = res.refoff(); // other leftmost aligned char
TRefOff my_right = my_left + refExtent();
TRefOff other_right = other_left + res.refExtent();
if(my_right < other_left || other_right < my_left) {
// The rectangular hulls of the two alignments don't overlap, so
// they can't overlap at any cell
return false;
}
// Reference and strand are the same and hulls overlap. Now go read
// position by read position testing if any align identically with the
// reference.
// Edits are ordered and indexed from 5' to 3' to start with. We
// reorder them to go from left to right along the Watson strand.
if(!fw()) {
invertEdits();
}
if(!res.fw()) {
res.invertEdits();
}
size_t nedidx = 0, onedidx = 0;
bool olap = false;
// For each row, going left to right along Watson reference strand...
for(size_t i = 0; i < rdexrows_; i++) {
size_t diff = 1; // amount to shift to right for next round
size_t odiff = 1; // amount to shift to right for next round
// Unless there are insertions before the next position, we say
// that there is one cell in this row involved in the alignment
my_right = my_left + 1;
other_right = other_left + 1;
while(nedidx < ned_->size() && (*ned_)[nedidx].pos == i) {
if((*ned_)[nedidx].isRefGap()) {
// Next my_left will be in same column as this round
diff = 0;
}
nedidx++;
}
while(onedidx < res.ned_->size() && (*res.ned_)[onedidx].pos == i) {
if((*res.ned_)[onedidx].isRefGap()) {
// Next my_left will be in same column as this round
odiff = 0;
}
onedidx++;
}
if(i < rdexrows_ - 1) {
// See how many inserts there are before the next read
// character
size_t nedidx_next = nedidx;
size_t onedidx_next = onedidx;
while(nedidx_next < ned_->size() &&
(*ned_)[nedidx_next].pos == i+1)
{
if((*ned_)[nedidx_next].isReadGap()) {
my_right++;
}
nedidx_next++;
}
while(onedidx_next < res.ned_->size() &&
(*res.ned_)[onedidx_next].pos == i+1)
{
if((*res.ned_)[onedidx_next].isReadGap()) {
other_right++;
}
onedidx_next++;
}
}
// Contained?
olap =
(my_left >= other_left && my_right <= other_right) ||
(other_left >= my_left && other_right <= my_right);
// Overlapping but not contained?
if(!olap) {
olap =
(my_left <= other_left && my_right > other_left) ||
(other_left <= my_left && other_right > my_left);
}
if(olap) {
break;
}
// How to do adjust my_left and my_right
my_left = my_right + diff - 1;
other_left = other_right + odiff - 1;
}
if(!fw()) {
invertEdits();
}
if(!res.fw()) {
res.invertEdits();
}
return olap;
}
#ifndef NDEBUG
/**
* Assuming this AlnRes is an alignment for 'rd', check that the alignment and
* 'rd' are compatible with the corresponding reference sequence.
*/
bool AlnRes::matchesRef(
const Read& rd,
const BitPairReference& ref,
BTDnaString& rf,
BTDnaString& rdseq,
BTString& qseq,
SStringExpandable<char>& raw_refbuf,
SStringExpandable<uint32_t>& destU32,
EList<bool>& matches,
SStringExpandable<char>& raw_refbuf2,
EList<TIndexOffU>& reflens,
EList<TIndexOffU>& refoffs)
{
assert(!empty());
assert(repOk());
assert(refcoord_.inited());
size_t rdlen = rd.length();
bool fw = refcoord_.fw();
if(!fw) {
assert_lt(trim3p_, rdlen);
Edit::invertPoss(const_cast<EList<Edit>&>(*ned_), rdlen - trim5p_ - trim3p_, false);
}
size_t refallen = 0;
reflens.clear(); refoffs.clear();
int64_t reflen = 0;
int64_t refoff = refcoord_.off();
refoffs.push_back((uint32_t)refoff);
size_t eidx = 0;
assert_lt(trim5p_ + trim3p_, rdlen);
for(size_t i = 0; i < rdlen - trim5p_ - trim3p_; i++, reflen++, refoff++) {
while(eidx < ned_->size() && (*ned_)[eidx].pos == i) {
if((*ned_)[eidx].isReadGap()) {
reflen++;
refoff++;
} else if((*ned_)[eidx].isRefGap()) {
reflen--;
refoff--;
}
if((*ned_)[eidx].isSpliced()) {
assert_gt(reflen, 0);
refallen += (uint32_t)reflen;
reflens.push_back((uint32_t)reflen);
reflen = 0;
refoff += (*ned_)[eidx].splLen;
assert_gt(refoff, 0);
refoffs.push_back((uint32_t)refoff);
}
eidx++;
}
}
assert_gt(reflen, 0);
refallen += (uint32_t)reflen;
reflens.push_back((uint32_t)reflen);
assert_gt(reflens.size(), 0);
assert_gt(refoffs.size(), 0);
assert_eq(reflens.size(), refoffs.size());
if(!fw) {
assert_lt(trim3p_, rdlen);
Edit::invertPoss(const_cast<EList<Edit>&>(*ned_), rdlen - trim5p_ - trim3p_, false);
}
// Adjust reference string length according to edits
#ifndef NDEBUG
if(reflens.size() == 1) {
assert_eq(refallen, refNucExtent());
}
#endif
assert_geq(refcoord_.ref(), 0);
int nsOnLeft = 0;
if(refcoord_.off() < 0) {
nsOnLeft = -((int)refcoord_.off());
}
raw_refbuf.resize(refallen);
raw_refbuf.clear();
raw_refbuf2.clear();
for(size_t i = 0; i < reflens.size(); i++) {
assert_gt(reflens[i], 0);
#ifndef NDEBUG
if(i > 0) {
assert_gt(refoffs[i], refoffs[i-1]);
}
#endif
raw_refbuf2.resize(reflens[i] + 16);
raw_refbuf2.clear();
int off = ref.getStretch(
reinterpret_cast<uint32_t*>(raw_refbuf2.wbuf()),
(size_t)refcoord_.ref(),
(size_t)max<TRefOff>(refoffs[i], 0),
reflens[i],
destU32);
assert_leq(off, 16);
raw_refbuf.append(raw_refbuf2.wbuf() + off, reflens[i]);
}
char *refbuf = raw_refbuf.wbuf();
size_t trim5 = 0, trim3 = 0;
if(trimSoft_) {
trim5 += trim5p_;
trim3 += trim3p_;
}
if(pretrimSoft_) {
trim5 += pretrim5p_;
trim3 += pretrim3p_;
}
rf.clear();
rdseq.clear();
rdseq = rd.patFw;
if(!fw) {
rdseq.reverseComp(false);
}
assert_eq(rdrows_, rdseq.length());
// rdseq is the nucleotide sequence from upstream to downstream on the
// Watson strand. ned_ are the nucleotide edits from upstream to
// downstream. rf contains the reference characters.
assert(Edit::repOk(*ned_, rdseq, fw, trim5, trim3));
Edit::toRef(rdseq, *ned_, rf, fw, trim5, trim3);
assert_eq(refallen, rf.length());
matches.clear();
bool matchesOverall = true;
matches.resize(refallen);
matches.fill(true);
for(size_t i = 0; i < refallen; i++) {
if((int)i < nsOnLeft) {
if((int)rf[i] != 4) {
matches[i] = false;
matchesOverall = false;
}
} else {
if((int)rf[i] != (int)refbuf[i-nsOnLeft]) {
matches[i] = false;
matchesOverall = false;
}
}
}
if(!matchesOverall) {
// Print a friendly message showing the difference between the
// reference sequence obtained with Edit::toRef and the actual
// reference sequence
cerr << endl;
Edit::printQAlignNoCheck(
cerr,
" ",
rdseq,
*ned_);
cerr << " ";
for(size_t i = 0; i < refallen; i++) {
cerr << (matches[i] ? " " : "*");
}
cerr << endl;
cerr << " ";
for(size_t i = 0; i < refallen-nsOnLeft; i++) {
cerr << "ACGTN"[(int)refbuf[i]];
}
cerr << endl;
Edit::printQAlign(
cerr,
" ",
rdseq,
*ned_);
cerr << endl;
}
return matchesOverall;
}
#endif /*ndef NDEBUG*/
#define COPY_BUF() { \
char *bufc = buf; \
while(*bufc != '\0') { \
*occ = *bufc; \
occ++; \
bufc++; \
} \
}
/**
* Initialized the stacked alignment with respect to a read string, a list of
* edits (expressed left-to-right), and integers indicating how much hard and
* soft trimming has occurred on either end of the read.
*
* s: read sequence
* ed: all relevant edits, including ambiguous nucleotides
* trimLS: # bases soft-trimmed from LHS
* trimLH: # bases hard-trimmed from LHS
* trimRS: # bases soft-trimmed from RHS
* trimRH: # bases hard-trimmed from RHS
*/
void StackedAln::init(
const BTDnaString& s,
const EList<Edit>& ed,
size_t trimLS,
size_t trimLH,
size_t trimRS,
size_t trimRH)
{
trimLS_ = trimLS;
trimLH_ = trimLH;
trimRS_ = trimRS;
trimRH_ = trimRH;
ASSERT_ONLY(size_t ln_postsoft = s.length() - trimLS - trimRS);
stackRef_.clear();
stackRel_.clear();
stackSNP_.clear();
stackRead_.clear();
size_t rdoff = trimLS;
for(size_t i = 0; i < ed.size(); i++) {
assert_lt(ed[i].pos, ln_postsoft);
size_t pos = ed[i].pos + trimLS;
while(rdoff < pos) {
int c = s[rdoff++];
assert_range(0, 4, c);
stackRef_.push_back("ACGTN"[c]);
stackRel_.push_back('=');
stackSNP_.push_back(false);
stackRead_.push_back("ACGTN"[c]);
}
if(ed[i].isMismatch()) {
int c = s[rdoff++];
assert_range(0, 4, c);
assert_eq(c, asc2dna[(int)ed[i].qchr]);
assert_neq(c, asc2dna[(int)ed[i].chr]);
stackRef_.push_back(ed[i].chr);
stackRel_.push_back('X');
stackSNP_.push_back(ed[i].snpID != (uint32_t)INDEX_MAX);
stackRead_.push_back("ACGTN"[c]);
} else if(ed[i].isRefGap()) {
int c = s[rdoff++];
assert_range(0, 4, c);
assert_eq(c, asc2dna[(int)ed[i].qchr]);
stackRef_.push_back('-');
stackRel_.push_back('I');
stackSNP_.push_back(ed[i].snpID != (uint32_t)INDEX_MAX);
stackRead_.push_back("ACGTN"[c]);
} else if(ed[i].isReadGap()) {
stackRef_.push_back(ed[i].chr);
stackRel_.push_back('D');
stackSNP_.push_back(ed[i].snpID != (uint32_t)INDEX_MAX);
stackRead_.push_back('-');
} else if(ed[i].isSpliced()) {
stackRef_.push_back('N');
stackRel_.push_back('N');
stackSNP_.push_back(false);
stackRead_.push_back('N');
assert_gt(ed[i].splLen, 0);
stackSkip_.push_back(ed[i].splLen);
}
}
while(rdoff < s.length() - trimRS) {
int c = s[rdoff++];
assert_range(0, 4, c);
stackRef_.push_back("ACGTN"[c]);
stackRel_.push_back('=');
stackSNP_.push_back(false);
stackRead_.push_back("ACGTN"[c]);
}
inited_ = true;
}
/**
* Left-align all the gaps. If this changes the alignment and the CIGAR or
* MD:Z strings have already been calculated, this renders them invalid.
*
* We left-align gaps with in the following way: for each gap, we check
* whether the character opposite the rightmost gap character is the same
* as the character opposite the character just to the left of the gap. If
* this is the case, we can slide the gap to the left and make the
* rightmost position previously covered by the gap into a non-gap.
*
* This scheme allows us to push the gap past a mismatch. BWA does seem to
* allow this. It's not clear that Bowtie 2 should, since moving the
* mismatch could cause a mismatch with one base quality to be replaced
* with a mismatch with a different base quality.
*/
void StackedAln::leftAlign(bool pastMms) {
assert(inited_);
bool changed = false;
size_t ln = stackRef_.size();
// Scan left-to-right
for(size_t i = 0; i < ln; i++) {
int rel = stackRel_[i];
if(rel != '=' && rel != 'X' && rel != 'N') {
// Neither a match nor a mismatch - must be a gap
assert(rel == 'I' || rel == 'D');
if(stackSNP_[i]) continue;
size_t glen = 1;
// Scan further right to measure length of gap
for(size_t j = i+1; j < ln; j++) {
if(rel != (int)stackRel_[j]) break;
glen++;
}
// We've identified a gap of type 'rel' (D = deletion or read
// gap, I = insertion or ref gap) with length 'glen'. Now we
// can try to slide it to the left repeatedly.
size_t l = i - 1;
size_t r = l + glen;
EList<char>& gp = ((rel == 'I') ? stackRef_ : stackRead_);
const EList<char>& ngp = ((rel == 'I') ? stackRead_ : stackRef_);
while(l > 0 && ngp[l] == ngp[r]) {
if(stackRel_[l] == 'I' || stackRel_[l] == 'D') break;
assert(stackRel_[l] == '=' || stackRel_[l] == 'X' || stackRel_[l] == 'N');
assert(stackRel_[r] == 'D' || stackRel_[r] == 'I');
if(!pastMms && (stackRel_[l] == 'X' || stackRel_[l] == 'N')) {
break;
}
swap(gp[l], gp[r]);
swap(stackRel_[l], stackRel_[r]);
assert_neq('-', gp[r]);
assert_eq('-', gp[l]);
l--; r--;
changed = true;
}
i += (glen-1);
}
}
if(changed) {
cigCalc_ = mdzCalc_ = false;
}
}
/**
* Build the CIGAR list, if it hasn't already built. Returns true iff it
* was built for the first time.
*/
bool StackedAln::buildCigar(bool xeq) {
assert(inited_);
if(cigCalc_) {
return false; // already done
}
cigOp_.clear();
cigRun_.clear();
if(trimLS_ > 0) {
cigOp_.push_back('S');
cigRun_.push_back(trimLS_);
}
size_t numSkips = 0;
size_t ln = stackRef_.size();
for(size_t i = 0; i < ln; i++) {
char op = stackRel_[i];
if(!xeq && (op == 'X' || op == '=')) {
op = 'M';
}
size_t run;
if(op != 'N') {
run = 1;
for(; i + run < ln; run++) {
char op2 = stackRel_[i + run];
if(!xeq && (op2 == 'X' || op2 == '=')) {
op2 = 'M';
}
if(op2 != op) {
break;
}
}
i += (run-1);
} else {
assert_lt(numSkips, stackSkip_.size());
run = stackSkip_[numSkips];
numSkips++;
}
cigOp_.push_back(op);
cigRun_.push_back(run);
}
if(trimRS_ > 0) {
cigOp_.push_back('S');
cigRun_.push_back(trimRS_);
}
cigCalc_ = true;
return true;
}
/**
* Build the CIGAR list, if it hasn't already built. Returns true iff it
* was built for the first time.
*/
bool StackedAln::buildMdz() {
assert(inited_);
if(mdzCalc_) {
return false; // already done
}
mdzOp_.clear();
mdzChr_.clear();
mdzRun_.clear();
size_t ln = stackRef_.size();
for(size_t i = 0; i < ln; i++) {
char op = stackRel_[i];
if(op == '=') {
size_t run = 1;
size_t ninserts = 0;
size_t nskips = 0;
// Skip over matches and insertions (ref gaps)
for(; i+run < ln; run++) {
if(stackRel_[i + run] == '=') {
// do nothing
} else if(stackRel_[i + run] == 'I') {
ninserts++;
} else if(stackRel_[i + run] == 'N') {
nskips++;
} else {
break;
}
}
i += (run - 1);
mdzOp_.push_back('='); // = X or G
mdzChr_.push_back('-');
mdzRun_.push_back(run - ninserts - nskips);
} else if(op == 'X') {
assert_neq(stackRef_[i], stackRead_[i]);
mdzOp_.push_back('X'); // = X or G
mdzChr_.push_back(stackRef_[i]);
mdzRun_.push_back(1);
} else if(op == 'D') {
assert_neq('-', stackRef_[i]);
mdzOp_.push_back('G'); // = X or G
mdzChr_.push_back(stackRef_[i]);
mdzRun_.push_back(1);
}
}
mdzCalc_ = true;
return true;
}
/**
* Write a CIGAR representation of the alignment to the given string and/or
* char buffer.
*/
void StackedAln::writeCigar(
BTString* o, // if non-NULL, string to append to
char* occ) const // if non-NULL, character string to append to
{
const EList<char>& op = cigOp_;
const EList<size_t>& run = cigRun_;
assert_eq(op.size(), run.size());
if(o != NULL || occ != NULL) {
char buf[128];
ASSERT_ONLY(bool printed = false);
for(size_t i = 0; i < op.size(); i++) {
size_t r = run[i];
if(r > 0) {
itoa10<size_t>(r, buf);
ASSERT_ONLY(printed = true);
if(o != NULL) {
o->append(buf);
o->append(op[i]);
}
if(occ != NULL) {
COPY_BUF();
*occ = op[i];
occ++;
}
}
}
assert(printed);
if(occ != NULL) {
*occ = '\0';
}
}
}
/**
* Write an MD:Z representation of the alignment to the given string and/or
* char buffer.
*/
void StackedAln::writeMdz(BTString* o, char* occ) const {
char buf[128];
bool mm_last = false;
bool rdgap_last = false;
bool first_print = true;
const EList<char>& op = mdzOp_;
const EList<char>& ch = mdzChr_;
const EList<size_t>& run = mdzRun_;
for(size_t i = 0; i < op.size(); i++) {
size_t r = run[i];
if(r > 0) {
if(op[i] == '=') {
// Write run length
itoa10<size_t>(r, buf);
if(o != NULL) { o->append(buf); }
if(occ != NULL) { COPY_BUF(); }
first_print = false;
mm_last = false;
rdgap_last = false;
} else if(op[i] == 'X') {
if(o != NULL) {
if(rdgap_last || mm_last || first_print) {
o->append('0');
}
o->append(ch[i]);
}
if(occ != NULL) {
if(rdgap_last || mm_last || first_print) {
*occ = '0';
occ++;
}
*occ = ch[i];
occ++;
}
first_print = false;
mm_last = true;
rdgap_last = false;
} else if(op[i] == 'G') {
if(o != NULL) {
if(mm_last || first_print) {
o->append('0');
}
if(!rdgap_last) {
o->append('^');
}
o->append(ch[i]);
}
if(occ != NULL) {
if(mm_last || first_print) {
*occ = '0'; occ++;
}
if(!rdgap_last) {
*occ = '^'; occ++;
}
*occ = ch[i];
occ++;
}
first_print = false;
mm_last = false;
rdgap_last = true;
}
} // if r > 0
} // for loop over ops
if(mm_last || rdgap_last) {
if(o != NULL) { o->append('0'); }
if(occ != NULL) { *occ = '0'; occ++; }
}
if(occ != NULL) { *occ = '\0'; }