Debian Codegraph @

lib/Bio/DB/HTS/Alignment.pm

raw
1
2 =head1 LICENSE
3
4 Copyright [2015-2024] EMBL-European Bioinformatics Institute
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17
18 =head1 NAME
19
20 Bio::DB::HTS::Alignment -- The HTS alignment object
21
22 =head1 SYNOPSIS
23
24 use Bio::DB::HTS;
25
26 my $sam = Bio::DB::HTS->new(-fasta=>"data/ex1.fa",
27 -bam =>"data/ex1.bam");
28
29 my @alignments = $sam->get_features_by_location(-seq_id => 'seq2',
30 -start => 500,
31 -end => 800);
32 for my $a (@alignments) {
33 my $seqid = $a->seq_id;
34 my $start = $a->start;
35 my $end = $a->end;
36 my $strand = $a->strand;
37 my $ref_dna= $a->dna;
38
39 my $query_start = $a->query->start;
40 my $query_end = $a->query->end;
41 my $query_strand = $a->query->strand;
42 my $query_dna = $a->query->dna;
43
44 my $cigar = $a->cigar_str;
45 my @scores = $a->qscore; # per-base quality scores
46 my $score = $a->qstring; # TAM-style quality string
47 my $match_qual= $a->qual; # quality of the match
48
49 my $paired = $a->get_tag_values('PAIRED');
50 }
51
52 =head1 DESCRIPTION
53
54 The Bio::DB::HTS::Alignment and Bio::DB::HTS::AlignWrapper classes
55 together represent an alignment between a sequence read (the "query")
56 and a reference sequence (the "target"). Bio::DB::HTS::Alignment
57 adheres strictly to the C-level BAM library's definition of a bam1_t*
58 and is used in the Bio::DB::HTS low-level API The latter adds
59 convenience methods that make it similar to a BioPerl Bio::SeqFeatureI
60 object. This manual page describes both.
61
62 =head1 High-level Bio::DB::HTS::Alignment methods
63
64 These methods are provided by Bio::DB::HTS::Alignment, and are
65 intended to be compatible with the Bio::SeqFeatureI interfaces. Note
66 that these objects are B<not> compatible with Bio::Align::AlignI, as
67 the BAM API is fundamentally incompatible with the BioPerl API for
68 alignments (the first deals with the alignment of a single read
69 against the reference sequence, while the second deals with a multiple
70 alignment).
71
72 Note that the high-level API return Bio::DB::HTS::AlignWrapper objects
73 B<except> in the case of the callback to the fast_pileup() method. In
74 this case only, the object returned by calling $pileup->b() is a
75 Bio::DB::HTS::Alignment object for performance reasons.
76
77 =over 4
78
79 =item $seq_id = $align->seq_id
80
81 Return the seq_id of the reference (target) sequence. This method is only
82 available in the Bio::DB::HTS::AlignWrapper extension.
83
84 =item $start = $align->start
85
86 Return the start of the alignment in 1-based reference sequence
87 coordinates.
88
89 =item $end = $align->end
90
91 Return the end of the alignment in 1-based reference sequence
92 coordinates.
93
94 =item $len = $align->length
95
96 Return the length of the alignment on the reference sequence.
97
98 =item $mseqid = $align->mate_seq_id
99
100 Return the seq_id of the mate's reference (target) sequence. This method
101 is only available in the Bio::DB::AlignWrapper extension.
102
103 =item $mstart = $align->mate_start
104
105 For paired reads, return the start of the mate's alignment in
106 1-based reference sequence coordinates.
107
108 =item $mend = $align->mate_end
109
110 For paired reads, return the end position of the mate's alignment in
111 1-based reference sequence coordinates.
112
113 =item $mlen = $align->mate_len
114
115 For mate-pairs, retrieve the length of the mate's alignment on the
116 reference sequence.
117
118 =item $strand = $align->strand
119
120 Return the strand of the alignment as -1 for reversed, +1 for
121 forward.
122
123 =item $mstrand = $align->mstrand
124
125 If the read has a mate pair, return the strand of the mate in the
126 format -1 or +1.
127
128 =item $ref_dna = $align->dna
129
130 Returns the B<reference> sequence's DNA across the aligned region. If
131 an MD tag is present in the alignment, it will be used preferentially
132 to reconstruct the reference sequence. Otherwise the reference DNA
133 access object passed to Bio::DB::HTS->new() will be used.
134
135 =item $ref_dna = $align->seq
136
137 The B<reference> sequence's DNA as a Bio::PrimarySeqI object (useful
138 for passing to BioPerl functions and for calculating subsequences and
139 reverse complements).
140
141 =item $query = $align->query
142
143 This method returns a Bio::DB::Alignment::Query object that can be
144 used to retrieve information about the query sequence. The next few
145 entries show how to use this object.
146
147 =item $read_name = $align->query->name
148
149 The name of the read.
150
151 =item $q_start = $align->query->start
152
153 This returns the start position of the query (read) sequence in
154 1-based coordinates. It acts via a transient Bio::DB::HTS::Query
155 object that is provided for Bio::Graphics compatibility (see
156 L<Bio::Graphics>).
157
158 =item $q_end = $align->query->end
159
160 This returns the end position of the query sequence in 1-based
161 coordinates.
162
163 =item $q_len = $align->query->length
164
165 Return the length of the alignment on the read.
166
167 =item $scores = $align->query->score
168
169 Return an array reference containing the unpacked quality scores for
170 each base of the query sequence. The length of this array reference
171 will be equal to the length of the read.
172
173 =item $read_dna = $align->query->dna
174
175 The read's DNA string.
176
177 =item $read_seq = $align->query->seq
178
179 The read's DNA as a Bio::PrimarySeqI object.
180
181 =item $target = $align->target;
182
183 The target() method is similar to query(), except that it follows
184 Bio::AlignIO conventions for how to represent minus strand
185 alignments. The object returned has start(), end(), qscore(), dna()
186 and seq() methods, but for minus strand alignments the sequence will
187 be represented as it appears on the reverse strand, rather than on the
188 forward strand. This has the advantage of giving you the read as it
189 came off the machine, before being reverse complemented for use in the
190 SAM file.
191
192 =item $query = $align->hit
193
194 The hit() method is identical to target() and returns information
195 about the read. It is present for compatibility with some of the
196 Bio::Graphics glyphs, which use hit() to represent the non-reference
197 sequence in aligned sequences.
198
199 =item $primary_id = $align->primary_id
200
201 This method synthesizes a unique ID for the alignment which can be
202 passed to $sam->get_feature_by_id() to retrieve the alignment at a
203 later date.
204
205 =item @tags = $align->get_all_tags
206
207 Return all tag names known to this alignment. This includes SAM flags
208 such as M_UNMAPPED, as well as auxiliary flags such as H0. The
209 behavior of this method depends on the value of -expand_flags when the
210 SAM object was created. If false (the default), then the standard SAM
211 flags will be concatenated together into a single string and stored in
212 a tag named 'FLAGS'. The format of this tag value is the list of one
213 or more flag constants separated by the "|" character, as in:
214 "PAIRED|MAP_PAIR|REVERSED|SECOND_MATE". If -expand_flags was true,
215 then each flag becomes its own named tag, such as "MAP_PAIR".
216
217 =item @values = $align->get_tag_values($tag)
218
219 Given a tag name, such as 'PAIRED' or 'H0', return its
220 value(s). -expand_flags must be true in order to use the standard SAM
221 flag constants as tags. Otherwise, they can be fetched by asking for
222 the "FLAGS" tag, or by using the low-level methods described below.
223
224 =item $is_true = $align->has_tag($tag)
225
226 Return true if the alignment has the indicated tag.
227
228 =item $string = $align->cigar_str
229
230 Return the CIGAR string for this alignment in conventional human
231 readable format (e.g. "M34D1M1").
232
233 =item $arrayref = $align->cigar_array
234
235 Return a reference to an array representing the CIGAR string. This is
236 an array of arrays, in which each subarray consists of a CIGAR
237 operation and a count. Example:
238
239 [ ['M',34], ['D',1], ['M',1] ]
240
241 =item ($ref,$matches,$query) = $align->padded_alignment
242
243 Return three strings that show the alignment between the reference
244 sequence (the target) and the query. It will look like this:
245
246 $ref AGTGCCTTTGTTCA-----ACCCCCTTGCAACAACC
247 $matches |||||||||||||| |||||||||||||||||
248 $query AGTGCCTTTGTTCACATAGACCCCCTTGCAACAACC
249
250 =item $str = $align->aux
251
252 Returns the text version of the SAM tags, e.g.
253 "XT:A:M NM:i:2 SM:i:37 AM:i:37 XM:i:1 XO:i:1 XG:i:1 MD:Z:6^C0A47"
254
255 =item $str = $align->tam_line
256
257 Returns the TAM (text) representation of the alignment (available in
258 the high-level "AlignWrapper" interface only).
259
260 =item $tag = $align->primary_tag
261
262 This is provided for Bio::SeqFeatureI compatibility. Return the string
263 "match".
264
265 =item $tag = $align->source_tag
266
267 This is provided for Bio::SeqFeatureI compatibility. Return the string
268 "sam/bam".
269
270 =item @parts = $align->get_SeqFeatures
271
272 Return subfeatures of this alignment. If you have fetched a
273 "read_pair" feature, this will be the two mate pair objects (both of
274 type Bio::DB::HTS::AlignWrapper). If you have -split_splices set to
275 true in the Bio::DB::HTS database, calling get_SeqFeatures() will
276 return the components of split alignments. See
277 L<Bio::DB::HTS/Bio::DB::HTS Constructor and basic accessors> for an
278 example of how to use this.
279
280 =back
281
282 =head1 Low-level Bio::DB::HTS::Alignment methods
283
284 These methods are available to objects of type Bio::DB::HTS::Alignment
285 as well as Bio::DB::HTS::AlignWrapper and closely mirror the native C
286 API.
287
288 =over 4
289
290 =item $align = Bio::DB::HTS::Alignment->new
291
292 Create a new, empty alignment object. This is usually needed when
293 iterating through a HTS file using Bio::DB::HTS->read1().
294
295 =item $tid = $align->tid( [$new_tid] )
296
297 Return the target ID of the alignment. Optionally you may change the
298 tid by providing it as an argument (currently this is the only field
299 that you can change; the functionality was implemented as a proof of
300 principle).
301
302 =item $read_name = $align->qname
303
304 Returns the name of the read.
305
306 =item $pos = $align->pos
307
308 0-based leftmost coordinate of the aligned sequence on the reference
309 sequence.
310
311 =item $end = $align->calend
312
313 The 0-based rightmost coordinate of the aligned sequence on the
314 reference sequence after taking alignment gaps into account.
315
316 =item $len = $align->cigar2qlen
317
318 The length of the query sequence calculated from the CIGAR string.
319
320 =item $quality = $align->qual
321
322 The quality score for the alignment as a whole.
323
324 =item $flag = $align->flag
325
326 The bitwise flag field (see the SAM documentation).
327
328 =item $mtid = $align->mtid
329
330 For paired reads, the target ID of the mate's alignemnt.
331
332 =item $mpos = $align->mpos
333
334 For paired reads, the 0-based leftmost coordinate of the mate's
335 alignment on the reference sequence.
336
337 =item $n_cigar = $align->n_cigar
338
339 Number of CIGAR operations in this alignment.
340
341 =item $length = $align->l_qseq
342
343 The length of the query sequence (the read).
344
345 =item $dna = $align->qseq
346
347 The actual DNA sequence of the query. As in the SAM file, reads that
348 are aligned to the minus strand of the reference are returned in
349 reverse complemented form.
350
351 =item $score_str = $align->_qscore
352
353 A packed binary string containing the quality scores for each base of
354 the read. It will be the same length as the DNA. You may unpack it
355 using unpack('C*',$score_str), or use the high-level qscore() method.
356
357 =item $score_arry = $align->qscore
358
359 =item @score_arry = $align->qscore
360
361 In a scalar context return an array reference containing the unpacked
362 quality scores for each base of the query sequence. In a list context
363 return a list of the scores. This array is in the same orientation as
364 the reference sequence.
365
366 =item $score_str = $align->qstring
367
368 Returns the quality string in the same format used in the SAM (TAM)
369 file.
370
371 =item $length = $align->isize
372
373 The calculated insert size for mapped paired reads.
374
375 =item $length = $align->l_aux
376
377 The length of the align "auxiliary" data.
378
379 =item $value = $align->aux_get("tag")
380
381 Given an auxiliary tag, such as "H0", return its value.
382
383 =item @keys = $align->aux_keys
384
385 Return the list of auxiliary tags known to this alignment.
386
387 =item $data = $align->data
388
389 Return a packed string containing the alignment data (sequence,
390 quality scores and cigar string).
391
392 =item $length = $align->data_len
393
394 Return the current length of the alignment data.
395
396 =item $length = $align->m_data
397
398 Return the maximum length of the alignment data.
399
400 =item $is_paired = $align->paired
401
402 Return true if the aligned read is part of a mate/read pair
403 (regardless of whether the mate mapped).
404
405 =item $is_proper = $align->proper_pair
406
407 Return true if the aligned read is part of a mate/read pair and both
408 partners mapped to the reference sequence.
409
410 =item $is_unmapped = $align->unmapped
411
412 Return true if the read failed to align.
413
414 =item $mate_is_unmapped = $align->munmapped
415
416 Return true if the read's mate failed to align.
417
418 =item $reversed = $align->reversed
419
420 Return true if the aligned read was reverse complemented prior to
421 aligning.
422
423 =item $mate_reversed = $align->mreversed
424
425 Return true if the aligned read's mate was reverse complemented prior
426 to aligning.
427
428 =item $isize = $align->isize
429
430 For mate-pairs, return the computed insert size.
431
432 =item $arrayref = $align->cigar
433
434 This returns the CIGAR data in its native BAM format. You will receive
435 an arrayref in which each operation and count are packed together into
436 an 8-bit structure. To decode each element you must use the following
437 operations:
438
439 use Bio::DB::HTS::Constants;
440 my $c = $align->cigar;
441 my $op = $c->[0] & BAM_CIGAR_MASK;
442 my $len = $c->[0] >> BAM_CIGAR_SHIFT;
443
444 =back
445
446 =head1 AUTHOR
447
448 Rishi Nag E<lt>[email protected]<gt>
449
450 =cut
451
452 package Bio::DB::HTS::Alignment;
453 $Bio::DB::HTS::Alignment::VERSION = '3.02';
454
455 use strict;
456 use warnings;
457 use Bio::DB::HTS::Query;
458 use Bio::DB::HTS::Target;
459 use Bio::DB::HTS::Constants;
460
461 sub each_tag_value { shift->get_tag_values(@_) }
462
463 sub get_tag_values {
464 my $self = shift;
465 my $tag = shift;
466 defined $tag or return;
467 if ( my $mask = RFLAGS->{ uc $tag } ) { # special tag
468 # to avoid warnings when making numeric comps
469 return ( $self->flag & $mask ) == 0 ? 0 : 1;
470 }
471 elsif ( $tag eq 'FLAGS' ) {
472 $self->flag_str;
473 }
474 else {
475 $self->aux_get($tag);
476 }
477 }
478
479 sub has_tag {
480 my $self = shift;
481 my $tag = shift;
482 defined $tag or return;
483 if ( my $mask = RFLAGS->{ uc $tag } ) { # special tag
484 return 1;
485 }
486 elsif ( $tag eq 'FLAGS' ) {
487 return 1;
488 }
489 else {
490 my %keys = map { $_ => 1 } $self->aux_keys;
491 return exists $keys{ uc $tag };
492 }
493 }
494
495 sub get_all_tags {
496 my $self = shift;
497 my @aux_tags = $self->aux_keys;
498 my @flag_tags = keys %{ RFLAGS() };
499 return ( @aux_tags, @flag_tags );
500 }
501
502 sub start {
503 my $self = shift;
504 return if $self->pos < 0 || $self->unmapped;
505 return $self->pos + 1;
506 }
507
508 sub end {
509 my $self = shift;
510 return if $self->unmapped;
511 return $self->calend;
512 }
513
514 sub stop { shift->end }
515
516 # in SAM format, alignment is always to the forward strand
517 sub strand {
518 return shift->reversed ? -1 : 1;
519 }
520
521 sub abs_strand { shift->strand }
522
523 sub mstrand {
524 my $self = shift;
525 return $self->mreversed ? -1 : 1;
526 }
527
528 sub display_name {
529 return shift->qname;
530 }
531
532 sub qscore {
533 my $self = shift;
534 my $scores = $self->_qscore;
535 my @scores = unpack( 'C*', $scores );
536 return wantarray ? @scores : \@scores;
537 }
538
539 sub qstring {
540 return join( '', map { chr( $_ + 33 ) } shift->qscore );
541 }
542
543 sub primary_id {
544 my $self = shift;
545 return join ';',
546 map { s/;/%3B/g; $_ } ( $self->display_name, $self->tid, $self->start,
547 $self->end, $self->strand );
548 }
549
550 sub cigar_str {
551 my $self = shift;
552 my $cigar = $self->cigar;
553 my $result = '';
554 for my $c (@$cigar) {
555 my $op = $c & BAM_CIGAR_MASK;
556 my $l = $c >> BAM_CIGAR_SHIFT();
557 my $symbol = CIGAR_SYMBOLS()->[$op];
558 $result .= "${l}${symbol}";
559 }
560 return $result;
561 }
562
563 sub cigar_array {
564 my $self = shift;
565 my $cigar = $self->cigar;
566 my @result;
567 for my $c (@$cigar) {
568 my $op = $c & BAM_CIGAR_MASK();
569 my $l = $c >> BAM_CIGAR_SHIFT();
570 my $symbol = CIGAR_SYMBOLS()->[$op];
571 push @result, [ $symbol, $l ];
572 }
573 return \@result;
574
575 }
576
577 sub flag_str {
578 my $self = shift;
579 my $flag = $self->flag;
580 my $flags = FLAGS;
581 return join '|',
582 map { $flags->{$_} }
583 grep { $flag & $_ } sort { $a <=> $b } keys %{$flags};
584 }
585
586 sub length {
587 my $self = shift;
588 my $end = $self->end || 0;
589 my $start = $self->start || 0;
590 return $end - $start + 1;
591 }
592
593 sub mate_start {
594 my $self = shift;
595 return if $self->mpos < 0 || $self->munmapped;
596 return $self->mpos + 1;
597 }
598
599 sub mate_len {
600 my $self = shift;
601 my $ins_len = $self->isize or return;
602 my $len = $self->length;
603
604 my $adjust = 0;
605 my @cigar = $self->cigar_array;
606 for my $event (@cigar) {
607 my ( $op, $len ) = @$event;
608 $adjust += $len if $op eq 'I';
609 $adjust -= $len if $op eq 'D';
610 }
611
612 return $adjust + $ins_len + ( $self->start - $self->mate_start )
613 if $ins_len > 0;
614 return $adjust + $self->mate_start - ( $self->start + $ins_len )
615 if $ins_len < 0;
616 }
617
618 sub mate_end {
619 my $self = shift;
620 return unless $self->mate_len;
621 return $self->mate_start + $self->mate_len - 1;
622 }
623
624 sub query {
625 my $self = shift;
626 return Bio::DB::HTS::Query->new($self);
627 }
628
629 sub get_SeqFeatures { return; }
630
631 # Target is the same as Query, but with meaning of start() and end() reversed
632 # for compatibility with Bio::DB::GFF and its ilk. Please use Query if you can!
633 sub target {
634 my $self = shift;
635 return Bio::DB::HTS::Target->new($self);
636 }
637
638 sub primary_tag { 'match' }
639 sub source_tag { 'sam/bam' }
640
641 sub hit { shift->target(@_); }
642
643 1;
644
645 =head1 SEE ALSO
646
647 L<Bio::Perl>, L<Bio::DB::HTS>, L<Bio::DB::HTS::Constants>
648
649 =cut