This repository has been archived by the owner on Dec 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathpileup.d
1008 lines (863 loc) · 34.5 KB
/
pileup.d
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
/*
This file is part of BioD.
Copyright (C) 2012-2016 Artem Tarasov <lomereiter@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the "Software"),
to deal in the Software without restriction, including without limitation
the rights to use, copy, modify, merge, publish, distribute, sublicense,
and/or sell copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
DEALINGS IN THE SOFTWARE.
*/
/// $(P This module is used for iterating over columns of alignment.)
/// $(P The function makePileup is called on
/// a range of coordinate-sorted reads mapped to the same reference.
/// It returns an input range of columns.)
/// $(P This returned range can then be iterated with $(D foreach).
/// First column is located at the same position on the reference,
/// as the first base of the first read.
/// $(BR)
/// Each $(D popFront) operation advances current position on the
/// reference. The default behaviour is to exclude sites with zero coverage
/// from the iteration.)
/// $(P Each column keeps set of reads that overlap corresponding position
/// on the reference.
/// If reads contain MD tags, and makePileup was asked
/// to use them, reference base at the column is also available.)
/// $(BR)
/// Each read preserves all standard read properties
/// but also keeps column-related information, namely
/// <ul>
/// $(LI number of bases consumed from the read sequence so far)
/// $(LI current CIGAR operation and offset in it)
/// $(LI all CIGAR operations before and after current one)</ul>
/// $(BR)
/// It is clear from the above that current CIGAR operation cannot be an insertion.
/// The following are suggested ways to check for them:
/// <ul>
/// $(LI $(D cigar_after.length > 0 &&
/// cigar_operation_offset == cigar_operation.length - 1 &&
/// cigar_after[0].type == 'I'))
/// $(LI $(D cigar_before.length > 0 &&
/// cigar_operation_offset == 0 &&
/// cigar_before[$ - 1].type == 'I'))</ul>
/// $(BR)
/// Example:
/// ---------------------------------------------------------
/// import bio.bam.reader, bio.bam.pileup, std.stdio, std.algorithm : count;
/// void main() {
/// auto bam = new BamReader("file.bam"); // assume single reference and MD tags
/// auto pileup = bam.reads().makePileup(useMD);
/// foreach (column; pileup) {
/// auto matches = column.bases.count(column.reference_base);
/// if (matches < column.coverage * 2 / 3)
/// writeln(column.position); // print positions of possible mismatches
/// }
/// }
/// ---------------------------------------------------------
module bio.bam.pileup;
import bio.bam.read;
import bio.bam.md.reconstruct;
import bio.bam.splitter;
import std.algorithm;
import std.range;
import std.random;
import std.traits;
import std.conv;
import std.array;
import std.exception;
/// Represents a read aligned to a column
struct PileupRead(Read=bio.bam.read.EagerBamRead) {
Read read; ///
alias read this;
private alias read _read;
/// Current CIGAR operation. One of 'M', '=', 'X', 'D', 'N.
/// Use $(D cigar_after)/$(D cigar_before) to determine insertions.
bio.bam.read.CigarOperation cigar_operation() @property const {
return _cur_op;
}
/// Number of bases consumed from the current CIGAR operation.
uint cigar_operation_offset() @property const {
return _cur_op_offset;
}
/// CIGAR operations after the current operation
const(bio.bam.read.CigarOperation)[] cigar_after() @property const {
return _read.cigar[_cur_op_index + 1 .. $];
}
/// CIGAR operations before the current operation
const(bio.bam.read.CigarOperation)[] cigar_before() @property const {
return _read.cigar[0 .. _cur_op_index];
}
/// If current CIGAR operation is one of 'M', '=', or 'X', returns read base
/// at the current column. Otherwise, returns '-'.
char current_base() @property const {
assert(_query_offset <= _read.sequence_length);
if (_cur_op.is_query_consuming && _cur_op.is_reference_consuming) {
return _read.sequence[_query_offset];
} else {
return '-';
}
}
/// If current CIGAR operation is one of 'M', '=', or 'X', returns
/// Phred-scaled read base quality at the current column.
/// Otherwise, returns 255.
ubyte current_base_quality() @property const {
assert(_query_offset <= _read.sequence_length);
if (_cur_op.is_query_consuming && _cur_op.is_reference_consuming) {
return _read.base_qualities[_query_offset];
} else {
return 255;
}
}
/// Returns number of bases consumed from the read sequence.
/// $(BR)
/// More concisely,
/// $(UL
/// $(LI if current CIGAR operation is 'M', '=', or 'X',
/// index of current read base in the read sequence)
/// $(LI if current CIGAR operation is 'D' or 'N',
/// index of read base after the deletion)
/// )
/// (in both cases indices are 0-based)
int query_offset() @property const {
assert(_query_offset <= _read.sequence_length);
return _query_offset;
}
/// Returns duplicate
PileupRead dup() @property {
PileupRead r = void;
r._read = _read; // logically const, thus no .dup here
r._cur_op_index = _cur_op_index;
r._cur_op = _cur_op;
r._cur_op_offset = _cur_op_offset;
r._query_offset = _query_offset;
return r;
}
private {
// index of current CIGAR operation in _read.cigar
uint _cur_op_index;
// current CIGAR operation
CigarOperation _cur_op;
// number of bases consumed from the current CIGAR operation
uint _cur_op_offset;
// number of bases consumed from the read sequence
uint _query_offset;
this(Read read) {
_read = read;
// find first M/=/X/D operation
auto cigar = _read.cigar;
for (_cur_op_index = 0; _cur_op_index < cigar.length; ++_cur_op_index) {
_cur_op = cigar[_cur_op_index];
if (_cur_op.is_reference_consuming) {
if (_cur_op.type != 'N') {
break;
}
} else if (_cur_op.is_query_consuming) {
_query_offset += _cur_op.length; // skip S and I operations
}
}
assertCigarIndexIsValid();
}
// move one base to the right on the reference
void incrementPosition() {
++_cur_op_offset;
// if current CIGAR operation is D or N, query offset is untouched
if (_cur_op.is_query_consuming) {
++_query_offset;
}
if (_cur_op_offset >= _cur_op.length) {
_cur_op_offset = 0; // reset CIGAR operation offset
auto cigar = _read.cigar;
// get next reference-consuming CIGAR operation (M/=/X/D/N)
for (++_cur_op_index; _cur_op_index < cigar.length; ++_cur_op_index) {
_cur_op = cigar[_cur_op_index];
if (_cur_op.is_reference_consuming) {
break;
}
if (_cur_op.is_query_consuming) {
_query_offset += _cur_op.length;
}
}
assertCigarIndexIsValid();
}
}
void assertCigarIndexIsValid() {
assert(_cur_op_index < _read.cigar.length, "Invalid read " ~ _read.name
~ " - CIGAR " ~ _read.cigarString()
~ ", sequence " ~ to!string(_read.sequence));
}
}
}
static assert(isBamRead!(PileupRead!BamRead));
//static assert(isBamRead!(PileupRead!(EagerBamRead!BamRead)));
/// Represents a single pileup column
struct PileupColumn(R) {
private {
ulong _position;
int _ref_id = -1;
R _reads;
size_t _n_starting_here;
}
/// Reference base. 'N' if not available.
char reference_base() @property const {
return _reference_base;
}
private char _reference_base = 'N';
/// Coverage at this position (equals to number of reads)
size_t coverage() const @property {
return _reads.length;
}
/// Returns reference ID (-1 if unmapped)
int ref_id() const @property {
return _ref_id;
}
/// Position on the reference
ulong position() const @property {
return _position;
}
/// Reads overlapping the position, sorted by coordinate
auto reads() @property {
return assumeSorted!compareCoordinates(_reads[]);
}
/// Reads that have leftmost mapped position at this column
auto reads_starting_here() @property {
return _reads[$ - _n_starting_here .. $];
}
/// Shortcut for map!(read => read.current_base)(reads)
auto bases() @property {
return map!"a.current_base"(reads);
}
/// Shortcut for map!(read => read.current_base_quality)(reads)
auto base_qualities() @property {
return map!"a.current_base_quality"(reads);
}
/// Shortcut for map!(read => read.mapping_quality)(reads)
auto read_qualities() @property {
return map!"a.mapping_quality"(reads);
}
}
/**
* The class for iterating reference bases together with reads overlapping them.
*/
class PileupRange(R, alias TColumn=PileupColumn) {
alias Unqual!(ElementType!R) Raw;
alias EagerBamRead!Raw Eager;
alias PileupRead!Eager Read;
alias Read[] ReadArray;
alias TColumn!ReadArray Column;
private {
R _reads;
Column _column;
Appender!ReadArray _read_buf;
bool _skip_zero_coverage;
}
protected {
// This is extracted into a method not only to reduce duplication
// (not so much of it), but to allow to override it!
// For that reason it is not marked as final. Overhead of virtual
// function is negligible compared to computations in EagerBamRead
// constructor together with inserting new element into appender.
void add(ref Raw read) {
_read_buf.put(PileupRead!Eager(Eager(read)));
}
}
/**
* Create new pileup iterator from a range of reads.
*/
this(R reads, bool skip_zero_coverage) {
_reads = reads;
_read_buf = appender!ReadArray();
_skip_zero_coverage = skip_zero_coverage;
if (!_reads.empty) {
initNewReference(); // C++ programmers, don't worry! Virtual tables in D
// are populated before constructor body is executed.
}
}
/// Returns PileupColumn struct corresponding to the current position.
ref Column front() @property {
return _column;
}
/// Whether all reads have been processed.
bool empty() @property {
return _reads.empty && _read_buf.data.empty;
}
/// Move to next position on the reference.
void popFront() {
auto pos = ++_column._position;
size_t survived = 0;
auto data = _read_buf.data;
for (size_t i = 0; i < data.length; ++i) {
if (data[i].end_position > pos) {
if (survived < i)
{
data[survived] = data[i];
}
++survived;
}
}
for (size_t i = 0; i < survived; ++i) {
data[i].incrementPosition();
}
// unless range is empty, this value is
_read_buf.shrinkTo(survived);
_column._n_starting_here = 0; // updated either in initNewReference()
// or in the loop below
if (!_reads.empty) {
if (_reads.front.ref_id != _column._ref_id &&
survived == 0) // processed all reads aligned to the previous reference
{
initNewReference();
} else {
size_t n = 0;
while (!_reads.empty &&
_reads.front.position == pos &&
_reads.front.ref_id == _column._ref_id)
{
auto read = _reads.front;
add(read);
_reads.popFront();
++n;
}
_column._n_starting_here = n;
// handle option of skipping sites with zero coverage
if (survived == 0 && n == 0 && _skip_zero_coverage) {
// the name might be misleading but it does the trick
initNewReference();
}
}
}
_column._reads = _read_buf.data;
}
protected void initNewReference() {
auto read = _reads.front;
_column._position = read.position;
_column._ref_id = read.ref_id;
uint n = 1;
add(read);
_reads.popFront();
while (!_reads.empty) {
read = _reads.front;
if (read.ref_id == _column.ref_id &&
read.position == _column._position)
{
add(read);
++n;
_reads.popFront();
} else {
break;
}
}
_column._n_starting_here = n;
_column._reads = _read_buf.data;
}
}
/// Abstract pileup structure. S is type of column range.
struct AbstractPileup(R, S) {
private R reads_;
R reads() @property {
return reads_;
}
S columns;
/// Pileup columns
alias columns this;
private {
ulong _start_position;
ulong _end_position;
int _ref_id;
}
/// $(D start_from) parameter provided to a pileup function
ulong start_position() @property const {
return _start_position;
}
/// $(D end_at) parameter provided to a pileup function
ulong end_position() @property const {
return _end_position;
}
/// Reference ID of all reads in this pileup.
int ref_id() @property const {
return _ref_id;
}
}
struct TakeUntil(alias pred, Range, Sentinel) if (isInputRange!Range)
{
private Range _input;
private Sentinel _sentinel;
bool _done;
this(Range input, Sentinel sentinel) {
_input = input; _sentinel = sentinel; _done = _input.empty || predSatisfied();
}
@property bool empty() { return _done; }
@property auto ref front() { return _input.front; }
private bool predSatisfied() { return startsWith!pred(_input, _sentinel); }
void popFront() { _input.popFront(); _done = _input.empty || predSatisfied(); }
}
auto takeUntil(alias pred, Range, Sentinel)(Range range, Sentinel sentinel) {
return TakeUntil!(pred, Range, Sentinel)(range, sentinel);
}
auto pileupInstance(alias P, R)(R reads, ulong start_from, ulong end_at, bool skip_zero_coverage) {
auto rs = filter!"a.basesCovered() > 0"(reads);
while (!rs.empty) {
auto r = rs.front;
if (r.position + r.basesCovered() < start_from) {
rs.popFront();
} else {
break;
}
}
int ref_id = -1;
if (!rs.empty) {
ref_id = rs.front.ref_id;
}
auto sameref_rs = takeUntil!"a.ref_id != b"(rs, ref_id);
alias typeof(sameref_rs) ReadRange;
PileupRange!ReadRange columns = new P!ReadRange(sameref_rs, skip_zero_coverage);
while (!columns.empty) {
auto c = columns.front;
if (c.position < start_from) {
columns.popFront();
} else {
break;
}
}
auto chopped = takeUntil!"a.position >= b"(columns, end_at);
return AbstractPileup!(R, typeof(chopped))(reads, chopped, start_from, end_at, ref_id);
}
auto pileupColumns(R)(R reads, bool use_md_tag=false, bool skip_zero_coverage=true) {
auto rs = filter!"a.basesCovered() > 0"(reads);
alias typeof(rs) ReadRange;
PileupRange!ReadRange columns;
if (use_md_tag) {
columns = new PileupRangeUsingMdTag!ReadRange(rs, skip_zero_coverage);
} else {
columns = new PileupRange!ReadRange(rs, skip_zero_coverage);
}
return columns;
}
/// Tracks current reference base
final static class PileupRangeUsingMdTag(R) :
PileupRange!(R, PileupColumn)
{
// The code is similar to that in reconstruct.d but here we can't make
// an assumption about any particular read having non-zero length on reference.
// current chunk of reference
private alias typeof(_column._reads[].front) Read;
private ReturnType!(dna!Read) _chunk;
// end position of the current chunk on reference (assuming half-open interval)
private uint _chunk_end_position;
// next read from which we will extract reference chunk
//
// More precisely,
// _next_chunk_provider = argmax (read => read.end_position)
// {reads overlapping current column}
private Read _next_chunk_provider;
private bool _has_next_chunk_provider = false;
// coverage at the previous location
private ulong _prev_coverage;
// we also track current reference ID
private int _curr_ref_id = -1;
///
this(R reads, bool skip_zero_coverage) {
super(reads, skip_zero_coverage);
}
alias Unqual!(ElementType!R) Raw;
// Checks length of the newly added read and tracks the read which
// end position on the reference is the largest.
//
// When reconstructed reference chunk will become empty, next one will be
// constructed from that read. This algorithm allows to minimize the number
// of reads for which MD tag will be decoded.
protected override void add(ref Raw read) {
// the behaviour depends on whether a new contig starts here or not
bool had_zero_coverage = _prev_coverage == 0;
super.add(read);
// get wrapped read
auto _read = _read_buf.data.back;
// if we've just moved to another reference sequence, do the setup
if (_read.ref_id != _curr_ref_id) {
_curr_ref_id = _read.ref_id;
_has_next_chunk_provider = true;
_next_chunk_provider = _read;
return;
}
// two subsequent next_chunk_providers must overlap
// unless (!) there was a region with zero coverage in-between
if (_read.position > _chunk_end_position && !had_zero_coverage) {
return;
}
// compare with previous candidate and replace if this one is better
if (_read.end_position > _chunk_end_position) {
if (!_has_next_chunk_provider) {
_has_next_chunk_provider = true;
_next_chunk_provider = _read;
} else if (_read.end_position > _next_chunk_provider.end_position) {
_next_chunk_provider = _read;
}
}
}
protected override void initNewReference() {
_prev_coverage = 0;
super.initNewReference();
if (_has_next_chunk_provider) {
// prepare first chunk
_chunk = dna(_next_chunk_provider);
_chunk_end_position = _next_chunk_provider.end_position;
_has_next_chunk_provider = false;
_column._reference_base = _chunk.front;
_chunk.popFront();
} else {
_column._reference_base = 'N';
}
}
///
override void popFront() {
if (!_chunk.empty) {
// update current reference base
_column._reference_base = _chunk.front;
_chunk.popFront();
} else {
_column._reference_base = 'N';
}
// update _prev_coverage
_prev_coverage = _column.coverage;
// the order is important - maybe we will obtain new next_chunk_provider
// during this call to popFront()
super.popFront();
// If we have consumed the whole current chunk,
// we need to obtain the next one if it's possible.
if (_chunk.empty && _has_next_chunk_provider) {
_chunk = dna(_next_chunk_provider);
debug {
/* import std.stdio;
writeln();
writeln("position: ", _next_chunk_provider.position);
writeln("next chunk: ", to!string(_chunk));
*/
}
_chunk_end_position = _next_chunk_provider.end_position;
_has_next_chunk_provider = false;
_chunk.popFrontN(cast(size_t)(_column.position - _next_chunk_provider.position));
_column._reference_base = _chunk.front;
_chunk.popFront();
}
}
}
/// Creates a pileup range from a range of reads.
/// Note that all reads must be aligned to the same reference.
///
/// See $(D PileupColumn) documentation for description of range elements.
/// Note also that you can't use $(D std.array.array()) function on pileup
/// because it won't make deep copies of underlying data structure.
/// (One might argue that in this case it would be better to use opApply,
/// but typically one would use $(D std.algorithm.map) on pileup columns
/// to obtain some numeric characteristics.)
///
/// Params:
/// use_md_tag = if true, use MD tag together with CIGAR
/// to recover reference bases
///
/// start_from = position from which to start
///
/// end_at = position before which to stop
///
/// $(BR)
/// That is, the range of positions is half-open interval
/// $(BR)
/// [max(start_from, first mapped read start position),
/// $(BR)
/// min(end_at, last mapped end position among all reads))
///
/// skip_zero_coverage = if true, skip sites with zero coverage
///
auto makePileup(R)(R reads,
bool use_md_tag=false,
ulong start_from=0,
ulong end_at=ulong.max,
bool skip_zero_coverage=true)
{
if (use_md_tag) {
return pileupInstance!PileupRangeUsingMdTag(reads, start_from, end_at, skip_zero_coverage);
} else {
return pileupInstance!PileupRange(reads, start_from, end_at, skip_zero_coverage);
}
}
/// Allows to express the intention clearer.
enum useMD = true;
unittest {
import std.algorithm;
import std.range;
import std.array;
// the set of reads below was taken from 1000 Genomes BAM file
// NA20828.mapped.ILLUMINA.bwa.TSI.low_coverage.20101123.bam
// (region 20:1127810-1127819)
auto readnames = array(iota(10).map!(i => "r" ~ to!string(i))());
auto sequences = ["ATTATGGACATTGTTTCCGTTATCATCATCATCATCATCATCATCATTATCATC",
"GACATTGTTTCCGTTATCATCATCATCATCATCATCATCATCATCATCATCATC",
"ATTGTTTCCGTTATCATCATCATCATCATCATCATCATCATCATCATCATCACC",
"TGTTTCCGTTATCATCATCATCATCATCATCATCATCATCATCATCATCACCAC",
"TCCGTTATCATCATCATCATCATCATCATCATCATCATCATCATCACCACCACC",
"GTTATCATCATCATCATCATCATCATCATCATCATCATCATCATCGTCACCCTG",
"TCATCATCATCATAATCATCATCATCATCATCATCATCGTCACCCTGTGTTGAG",
"TCATCATCATCGTCACCCTGTGTTGAGGACAGAAGTAATTTCCCTTTCTTGGCT",
"TCATCATCATCATCACCACCACCACCCTGTGTTGAGGACAGAAGTAATATCCCT",
"CACCACCACCCTGTGTTGAGGACAGAAGTAATTTCCCTTTCTTGGCTGGTCACC"];
// multiple sequence alignment:
// ***
// ATTATGGACATTGTTTCCGTTATCATCATCATCATCATCATCATCATTATCATC
// GACATTGTTTCCGTTATCATCATCATCATCATCATCATCATCATCATCATCAT---C
// ATTGTTTCCGTTATCATCATCATCATCATCATCATCATCATCATCATCATCACC
// TGTTTCCGTTATCATCATCATCATCATCATCATCATCATCATCATCAT---CACCAC
// TCCGTTATCATCATCATCATCATCATCATCATCATCATCATCAT---CACCACCACC
// GTTATCATCATCATCATCATCATCATCATCATCATCATCAT---CATCGTCACCCTG
// ATCATCATCATAATCATCATCATCATCATCAT---CATCGTCACCCTGTGTTGAG
// TCATCATCATCGTCAC------------------CCTGTGTTGAGGACAGAAGTAATTTCCCTTTCTTGGCT
// TCATCATCATCATCACCACCACCACCCTGTGTTGAGGACAGAAGTAATATCCCT
// ---CACCACCACCCTGTGTTGAGGACAGAAGTAATTTCCCTTTCTTGGCTGGTCACC
// * * * * * * * * * *
// 760 770 780 790 800 810 820 830 840 850
auto cigars = [[CigarOperation(54, 'M')],
[CigarOperation(54, 'M')],
[CigarOperation(50, 'M'), CigarOperation(3, 'I'), CigarOperation(1, 'M')],
[CigarOperation(54, 'M')],
[CigarOperation(54, 'M')],
[CigarOperation(54, 'M')],
[CigarOperation(2, 'S'), CigarOperation(52, 'M')],
[CigarOperation(16, 'M'), CigarOperation(15, 'D'), CigarOperation(38, 'M')],
[CigarOperation(13, 'M'), CigarOperation(3, 'I'), CigarOperation(38, 'M')],
[CigarOperation(54, 'M')]];
auto positions = [758, 764, 767, 769, 773, 776, 785, 795, 804, 817];
auto md_tags = ["47C6", "54", "51", "50T3", "46T7", "45A0C7", "11C24A0C14",
"11A3T0^CATCATCATCACCAC38", "15T29T5", "2T45T5"];
BamRead[] reads = new BamRead[10];
foreach (i; iota(10)) {
reads[i] = BamRead(readnames[i], sequences[i], cigars[i]);
reads[i].position = positions[i];
reads[i].ref_id = 0;
reads[i]["MD"] = md_tags[i];
}
auto first_read_position = reads.front.position;
auto reference = to!string(dna(reads));
import std.stdio;
writeln("Testing pileup (low-level aspects)...");
auto pileup = makePileup(reads, true, 796, 849, false);
auto pileup2 = makePileup(reads, true, 0, ulong.max, false);
assert(pileup.front.position == 796);
assert(pileup.start_position == 796);
assert(pileup.end_position == 849);
while (pileup2.front.position != 796) {
pileup2.popFront();
}
while (!pileup.empty) {
auto column = pileup.front;
auto column2 = pileup2.front;
assert(column.coverage == column2.coverage);
pileup2.popFront();
// check that DNA is built correctly from MD tags and CIGAR
assert(column.reference_base == reference[cast(size_t)(column.position - first_read_position)]);
switch (column.position) {
case 796:
assert(equal(column.bases, "CCCCCCAC"));
pileup.popFront();
break;
case 805:
assert(equal(column.bases, "TCCCCCCCC"));
pileup.popFront();
break;
case 806:
assert(equal(column.bases, "AAAAAAAGA"));
pileup.popFront();
break;
case 810:
// last read is not yet fetched by pileup engine
assert(column.reads[column.coverage - 2].cigar_after.front.type == 'D');
pileup.popFront();
break;
case 817:
assert(column.reads[column.coverage - 2].cigar_before.back.type == 'I');
pileup.popFront();
break;
case 821:
assert(column.reads[column.coverage - 3].cigar_operation.type == 'D');
assert(equal(column.bases, "AAGG-AA"));
pileup.popFront();
break;
case 826:
assert(equal(column.bases, "CCCCCC"));
pileup.popFront();
break;
case 849:
assert(equal(column.bases, "TAT"));
pileup.popFront();
assert(pileup.empty);
break;
default:
pileup.popFront();
break;
}
}
// another set of reads, the same file, region 20:12360032-12360050
// test the case when reference has some places with zero coverage
reads = [BamRead("r1", "CCCACATAGAAAGCTTGCTGTTTCTCTGTGGGAAGTTTTAACTTAGGTCAGCTT",
[CigarOperation(54, 'M')]),
BamRead("r2", "TAGAAAGCTTGCTGTTTCTCTGTGGGAAGTTTTAACTTAGGTTAGCTTCATCTA",
[CigarOperation(54, 'M')]),
BamRead("r3", "TTTTTCTTTCTTTCTTTGAAGAAGGCAGATTCCTGGTCCTGCCACTCAAATTTT",
[CigarOperation(54, 'M')]),
BamRead("r4", "TTTCTTTCTTTCTTTGAAGAAGGCAGATTCCTGGTCCTGCCACTCAAATTTTCA",
[CigarOperation(54, 'M')])];
reads[0].position = 979;
reads[0]["MD"] = "54";
reads[0].ref_id = 0;
reads[1].position = 985;
reads[1]["MD"] = "42C7C3";
reads[1].ref_id = 0;
reads[2].position = 1046;
reads[2]["MD"] = "54";
reads[2].ref_id = 0;
reads[3].position = 1048;
reads[3]["MD"] = "54";
reads[3].ref_id = 0;
assert(equal(dna(reads),
map!(c => c.reference_base)(makePileup(reads, true, 0, ulong.max, false))));
}
struct PileupChunkRange(C) {
private C _chunks;
private ElementType!C _prev_chunk;
private ElementType!C _current_chunk;
private bool _empty;
private ulong _beg = 0;
private bool _use_md_tag;
private ulong _start_from;
private ulong _end_at;
this(C chunks, bool use_md_tag, ulong start_from, ulong end_at) {
_chunks = chunks;
_use_md_tag = use_md_tag;
_start_from = start_from;
_end_at = end_at;
while (true) {
if (_chunks.empty) {
_empty = true;
} else {
_current_chunk = _chunks.front;
_chunks.popFront();
if (_current_chunk[0].ref_id < 0) continue;
_beg = _current_chunk[0].position;
if (_beg >= end_at) {
_empty = true;
break;
}
auto last_read = _current_chunk[$-1];
if (last_read.position + last_read.basesCovered() > start_from) {
break;
}
}
}
}
bool empty() @property {
return _empty;
}
auto front() @property {
auto end_pos = _current_chunk[$-1].position;
if (_chunks.empty || _chunks.front[0].ref_id != _current_chunk[$-1].ref_id)
end_pos += _current_chunk[$-1].basesCovered();
return makePileup(chain(_prev_chunk, _current_chunk),
_use_md_tag,
max(_beg, _start_from), min(end_pos, _end_at));
}
void popFront() {
_prev_chunk = _current_chunk;
while (true) {
if (_chunks.empty) {
_empty = true;
return;
}
_current_chunk = _chunks.front;
_chunks.popFront();
if (_current_chunk[0].ref_id >= 0) break;
}
// if we changed reference, nullify prev_chunk
if (_prev_chunk.length > 0 &&
_prev_chunk[$ - 1].ref_id == _current_chunk[0].ref_id)
{
_beg = _prev_chunk[$-1].position;
} else {
_beg = _current_chunk[0].position;
_prev_chunk.length = 0;
}
// keep only those reads in _prev_chunk that have overlap with the last one
// 1) estimate read length
enum sampleSize = 15;
int[sampleSize] buf = void;
int read_length = void;
if (_prev_chunk.length <= sampleSize) {
for (size_t k = 0; k < _prev_chunk.length; ++k) {
buf[k] = _prev_chunk[k].sequence_length;
}
topN(buf[0.._prev_chunk.length], _prev_chunk.length / 2);
read_length = buf[_prev_chunk.length / 2];
} else {
size_t i = 0;
foreach (read; randomSample(_prev_chunk, sampleSize))
buf[i++] = read.sequence_length;
topN(buf[], sampleSize / 2);
read_length = buf[sampleSize / 2];
debug {
import std.stdio;
stderr.writeln("[pileupChunks] read_length=", read_length);
}
}
// 2) do binary search for those reads that start from (_beg - 2 * read_length)
// (it's an experimental fact that almost none of reads consumes that much
// on a reference sequence)
auto pos = _beg - 2 * read_length;
long i = 0;
long j = _prev_chunk.length - 1;
// positions of _prev_chunk[0 .. i] are less than pos,
// positions of _prev_chunk[j + 1 .. $] are more or equal to pos.
while (i <= j) {
auto m = cast(size_t)(i + j) / 2;
assert(m < _prev_chunk.length);
auto p = _prev_chunk[m].position;
if (p >= pos) {
j = m - 1;
} else {
i = m + 1;
}
}
_prev_chunk = _prev_chunk[cast(size_t)i .. $];
}
}
/// This function constructs range of non-overlapping consecutive pileups from a range of reads
/// so that these pileups can be processed in parallel.
///
/// It's allowed to pass ranges of sorted reads with different ref. IDs,
/// they won't get mixed in any chunk.
///
/// Params:
/// use_md_tag = recover reference bases from MD tag and CIGAR
///
/// block_size = approximate amount of memory that each pileup will consume,
/// given in bytes. (Usually consumption will be a bit higher.)
///
/// start_from = position of the first column of the first chunk
///
/// end_at = position after the last column of the last chunk
///
/// $(BR)
/// WARNING: block size should be big enough so that every block will share
/// some reads only with adjacent blocks.