EnsEMBL/BaseAlignFeature.pm untested

filter: Statementstmt 0.0% 0 / 433 Branchbran 0.0% 0 / 196 Conditioncond 0.0% 0 / 77 Subroutinesub 0.0% 0 / 26 Podpod 0.0% 0 / 21 totaltotal 0.0% 0 / 753 CC 99 SCAR 63.7
CC
99
Cov
0%
_parse_ensembl_features
1640.0
_parse_ensembl_cigar
272.0
_mdz_alignment_string
156.0
CRAP 585.9
1 =head1 LICENSE
2  
3 See the NOTICE file distributed with this work for additional information
4 regarding copyright ownership.
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 =cut
19  
20  
21 =head1 CONTACT
22  
23 Please email comments or questions to the public Ensembl
24 developers list at <http://lists.ensembl.org/mailman/listinfo/dev>.
25  
26 Questions may also be sent to the Ensembl help desk at
27 <http://www.ensembl.org/Help/Contact>.
28  
29 =cut
30  
31 =head1 NAME
32  
33 Bio::EnsEMBL::BaseAlignFeature - Baseclass providing a common abstract
34 implmentation for alignment features
35  
36 =head1 SYNOPSIS
37  
38 my $feat = new Bio::EnsEMBL::DnaPepAlignFeature(
39 -slice => $slice,
40 -start => 100,
41 -end => 120,
42 -strand => 1,
43 -hseqname => 'SP:RF1231',
44 -hstart => 200,
45 -hend => 220,
46 -analysis => $analysis,
47 -cigar_string => '10M3D5M2I',
48 -align_type => 'ensembl'
49 );
50  
51 where $analysis is a Bio::EnsEMBL::Analysis object.
52  
53 Alternatively if you have an array of ungapped features:
54  
55 my $feat =
56 new Bio::EnsEMBL::DnaPepAlignFeature( -features => \@features );
57  
58 where @features is an array of Bio::EnsEMBL::FeaturePair objects.
59  
60 There is a method to (re)create ungapped features from the cigar_string:
61  
62 my @ungapped_features = $feat->ungapped_features();
63  
64 where @ungapped_features is an array of Bio::EnsEMBL::FeaturePair's.
65  
66 Bio::EnsEMBL::BaseAlignFeature inherits from:
67 Bio::EnsEMBL::FeaturePair, which in turn inherits from:
68 Bio::EnsEMBL::Feature,
69 thus methods from both parent classes are available.
70  
71  
72 The cigar_string is a condensed representation of the matches and gaps
73 which make up the gapped alignment (where CIGAR stands for
74 Concise Idiosyncratic Gapped Alignment Report).
75  
76 CIGAR format is: n <matches> [ x <deletes or inserts> m <matches> ]*
77 where M = match, D = delete, I = insert; n, m are match lengths;
78 x is delete or insert length.
79  
80 Spaces are omitted, thus: "23M4I12M2D1M"
81 as are counts for any lengths of 1, thus 1M becomes M: "23M4I12M2DM"
82  
83  
84 To make things clearer this is how a blast HSP would be parsed:
85  
86 >AK014066
87 Length = 146
88  
89 Minus Strand HSPs:
90  
91 Score = 76 (26.8 bits), Expect = 1.4, P = 0.74
92 Identities = 20/71 (28%), Positives = 29/71 (40%), Frame = -1
93  
94 Query: 479 GLQAPPPTPQGCRLIPPPPLGLQAPLPTLRAVGSSHHHP*GRQGSSLSSFRSSLASKASA 300
95 G APPP PQG R P P G + P L + + ++ R +A +
96 Sbjct: 7 GALAPPPAPQG-RWAFPRPTG-KRPATPLHGTARQDRQVRRSEAAKVTGCRGRVAPHVAP 64
97  
98 Query: 299 SSPHNPSPLPS 267
99 H P+P P+
100 Sbjct: 65 PLTHTPTPTPT 75
101  
102 The alignment goes from 479 down to 267 in the query sequence on the reverse
103 strand, and from 7 to 75 in the subject sequence.
104  
105 The alignment is made up of the following ungapped pieces:
106  
107 query_seq start 447 , sbjct_seq hstart 7 , match length 33 , strand -1
108 query_seq start 417 , sbjct_seq hstart 18 , match length 27 , strand -1
109 query_seq start 267 , sbjct_seq hstart 27 , match length 147 , strand -1
110  
111 When assembled into a DnaPepAlignFeature where:
112 (seqname, start, end, strand) refer to the query sequence,
113 (hseqname, hstart, hend, hstrand) refer to the subject sequence,
114 these ungapped pieces are represented by the cigar string:
115 33M3I27M3I147M
116 with start 267, end 479, strand -1, and hstart 7, hend 75, hstrand 1.
117  
118 =head1 CAVEATS
119  
120 AlignFeature cigar strings have the opposite 'sense'
121 ('D' and 'I' swapped) compared with Exonerate cigar strings.
122  
123 Exonerate modules in Bio::EnsEMBL::Analysis use this convention:
124  
125 The longer genomic sequence specified by:
126 exonerate: target
127 AlignFeature: (sequence, start, end, strand)
128  
129 A shorter sequence (such as EST or protein) specified by:
130 exonerate: query
131 AlignFeature: (hsequence, hstart, hend, hstrand)
132  
133 The resulting AlignFeature cigar strings have 'D' and 'I'
134 swapped compared with the Exonerate output, i.e.:
135  
136 exonerate: M 123 D 1 M 11 I 1 M 39
137 AlignFeature: 123MI11MD39M
138  
139 =head1 METHODS
140  
141 =cut
142  
143  
144 package Bio::EnsEMBL::BaseAlignFeature;
145 $Bio::EnsEMBL::BaseAlignFeature::VERSION = '114.0.0_50'; # TRIAL
146 $Bio::EnsEMBL::BaseAlignFeature::VERSION = '114.0.050';
147 use Bio::EnsEMBL::FeaturePair;
148 use Bio::EnsEMBL::Utils::Argument qw(rearrange);
149 use Bio::EnsEMBL::Utils::Exception qw(throw warning);
150  
151 use vars qw(@ISA);
152 use strict;
153  
154 @ISA = qw(Bio::EnsEMBL::FeaturePair);
155  
156  
157 =head2 new
158  
159 Arg [..] : List of named arguments. (-cigar_string , -features, -align_type) defined
160 in this constructor, others defined in FeaturePair and
161 SeqFeature superclasses. Either cigar_string or a list
162 of ungapped features should be provided - not both.
163 Example : $baf = new BaseAlignFeatureSubclass(-cigar_string => '3M3I12M', -align_type => 'ensembl');
164 Description: Creates a new BaseAlignFeature using either a cigar string or
165 a list of ungapped features. BaseAlignFeature is an abstract
166 baseclass and should not actually be instantiated - rather its
167 subclasses should be.
168 Returntype : Bio::EnsEMBL::BaseAlignFeature
169 Exceptions : thrown if both feature and cigar string args are provided
170 thrown if neither feature nor cigar string args are provided
171 warn if cigar string is provided without cigar type
172 Caller : general
173 Status : Stable
174  
175 =cut
176  
177 sub new {
178
179 my $caller = shift;
180  
181 my $class = ref($caller) || $caller;
182  
183 my $self = $class->SUPER::new(@_);
184  
185 my ($cigar_string,$align_type,$features) = rearrange([qw(CIGAR_STRING ALIGN_TYPE FEATURES)], @_);
186  
187 if (defined($align_type)) {
188 $self->{'align_type'} = $align_type;
189 } else {
190 warning("No align_type provided, using ensembl as default");
191 $self->{'align_type'} = 'ensembl';
192 }
193  
194 if (defined($cigar_string) && defined($features)) {
195 throw("CIGAR_STRING or FEATURES argument is required - not both.");
196 } elsif (defined($features)) {
197 $self->_parse_features($features);
198
199 } elsif (defined($cigar_string)) {
200 $self->{'cigar_string'} = $cigar_string;
201 } else {
202 throw("CIGAR_STRING or FEATURES argument is required");
203 }
204  
205 return $self;
206 }
207  
208  
209 =head2 cigar_string
210  
211 Arg [1] : string $cigar_string
212 Example : $feature->cigar_string( "12MI3M" );
213 Description: get/set for attribute cigar_string.
214 cigar_string describes the alignment:
215 "xM" stands for x matches (or mismatches),
216 "xI" for x inserts into the query sequence,
217 "xD" for x deletions from the query sequence
218 where the query sequence is specified by (seqname, start, ...)
219 and the subject sequence by (hseqname, hstart, ...).
220 An "x" that is 1 can be omitted.
221 See the SYNOPSIS for an example.
222 Returntype : string
223 Exceptions : none
224 Caller : general
225 Status : Stable
226  
227 =cut
228  
229 sub cigar_string {
230 my $self = shift;
231 $self->{'cigar_string'} = shift if(@_);
232 return $self->{'cigar_string'};
233 }
234  
235  
236 =head2 align_type
237  
238 Arg [1] : type $align_type
239 Example : $feature->align_type( "ensembl" );
240 Description: get/set for attribute align_type.
241 align_type specifies which cigar string
242 is used to describe the alignment:
243 The default is 'ensembl'
244 Returntype : string
245 Exceptions : none
246 Caller : general
247 Status : Stable
248  
249 =cut
250  
251 sub align_type {
252 my $self = shift;
253 $self->{'align_type'} = shift if(@_);
254 return $self->{'align_type'};
255 }
256  
257  
258 =head2 alignment_length
259  
260 Arg [1] : None
261 Description: return the alignment length (including indels) based on the alignment_type ('ensembl', 'mdtag')
262 Returntype : int
263 Exceptions :
264 Caller :
265 Status : Stable
266  
267 =cut
268  
269 sub alignment_length {
270 my $self = shift;
271
272 # ensembl: Internal CIGAR format
273 if ($self->{'align_type'} eq 'ensembl') {
274 return $self->_ensembl_cigar_alignment_length();
275 # mdtag: MD Z String for mismatching positions. Regex : [0-9]+(([A-Z]|\^[A-Z]+)[0-9]+)* (Refer: SAM/BAM specification)
276 } elsif ($self->{'align_type'} eq 'mdtag') {
277 return $self->_mdtag_alignment_length();
278 } else {
279 throw("No alignment_length method available for " . $self->{'align_type'});
280 }
281  
282 }
283  
284  
285 =head2 _ensembl_cigar_alignment_length
286  
287 Arg [1] : None
288 Description: return the alignment length (including indels) based on the cigar_string
289 Returntype : int
290 Exceptions :
291 Caller :
292 Status : Stable
293  
294 =cut
295  
296 sub _ensembl_cigar_alignment_length {
297 my $self = shift;
298  
299 if (! defined $self->{'_alignment_length'} && defined $self->cigar_string) {
300  
301 my @pieces = ( $self->cigar_string =~ /(\d*[MDI])/g );
302 unless (@pieces) {
303 print STDERR "Error parsing cigar_string\n";
304 }
305 my $alignment_length = 0;
306 foreach my $piece (@pieces) {
307 my ($length) = ( $piece =~ /^(\d*)/ );
308 if (! defined $length || $length eq "") {
309 $length = 1;
310 }
311 $alignment_length += $length;
312 }
313 $self->{'_alignment_length'} = $alignment_length;
314 }
315 return $self->{'_alignment_length'};
316 }
317  
318 =head2 ungapped_features
319  
320 Args : none
321 Example : @ungapped_features = $align_feature->get_feature
322 Description: converts the internal cigar_string into an array of
323 ungapped feature pairs
324 Returntype : list of Bio::EnsEMBL::FeaturePair
325 Exceptions : cigar_string not set internally
326 Caller : general
327 Status : Stable
328  
329 =cut
330  
331 sub ungapped_features {
332 my ($self) = @_;
333  
334 if (!defined($self->{'cigar_string'})) {
335 throw("No cigar_string defined. Can't return ungapped features");
336 }
337  
338 return @{$self->_parse_cigar()};
339 }
340  
341 =head2 strands_reversed
342
343 Arg [1] : int $strands_reversed
344 Description: get/set for attribute strands_reversed
345 0 means that strand and hstrand are the original strands obtained
346 from the alignment program used
347 1 means that strand and hstrand have been flipped as compared to
348 the original result provided by the alignment program used.
349 You may want to use the reverse_complement method to restore the
350 original strandness.
351 Returntype : int
352 Exceptions : none
353 Caller : general
354 Status : Stable
355
356 =cut
357  
358 sub strands_reversed {
359 my ($self, $arg) = @_;
360
361 if ( defined $arg ) {
362 $self->{'strands_reversed'} = $arg ;
363 }
364  
365 $self->{'strands_reversed'} = 0 unless (defined $self->{'strands_reversed'});
366  
367 return $self->{'strands_reversed'};
368 }
369  
370  
371 =head2 reverse_complement
372  
373 Args : none
374 Description: reverse complement the FeaturePair based on the cigar type
375 modifing strand, hstrand and cigar_string in consequence
376 Returntype : none
377 Exceptions : none
378 Caller : general
379 Status : Stable
380  
381 =cut
382  
383  
384 sub reverse_complement {
385 my ($self) = @_;
386  
387 if ($self->{'align_type'} eq 'ensembl') {
388 return $self->_ensembl_reverse_complement();
389 } else {
390 throw("no reverse_complement method implemented for " . $self->{'align_type'});
391 }
392 }
393  
394 =head2 _ensembl_reverse_complement
395  
396 Args : none
397 Description: reverse complement the FeaturePair for ensembl cigar string,
398 modifing strand, hstrand and cigar_string in consequence
399 Returntype : none
400 Exceptions : none
401 Caller : general
402 Status : Stable
403  
404 =cut
405  
406 sub _ensembl_reverse_complement {
407 my ($self) = @_;
408  
409 # reverse strand in both sequences
410 $self->strand($self->strand * -1);
411 $self->hstrand($self->hstrand * -1);
412  
413 # reverse cigar_string as consequence
414 my $cigar_string = $self->cigar_string;
415 $cigar_string =~ s/(D|I|M)/$1 /g;
416 my @cigar_pieces = split / /,$cigar_string;
417 $cigar_string = "";
418 while (my $piece = pop @cigar_pieces) {
419 $cigar_string .= $piece;
420 }
421
422 $self->{'strands_reversed'} = 0 unless (defined $self->{'strands_reversed'});
423  
424 if ($self->strands_reversed) {
425 $self->strands_reversed(0)
426 } else {
427 $self->strands_reversed(1);
428 }
429  
430 $self->cigar_string($cigar_string);
431 }
432  
433  
434  
435 =head2 transform
436  
437 Arg 1 : String $coordinate_system_name
438 Arg [2] : String $coordinate_system_version
439 Example : $feature = $feature->transform('contig');
440 $feature = $feature->transform('chromosome', 'NCBI33');
441 Description: Moves this AlignFeature to the given coordinate system.
442 If the feature cannot be transformed to the destination
443 coordinate system undef is returned instead.
444 Returntype : Bio::EnsEMBL::BaseAlignFeature;
445 Exceptions : wrong parameters
446 Caller : general
447 Status : Medium Risk
448  
449 =cut
450  
451 sub transform {
452 my $self = shift;
453  
454 my $new_feature = $self->SUPER::transform(@_);
455 if ( !defined($new_feature)
456 || $new_feature->length() != $self->length() )
457 {
458 my @segments = @{ $self->project(@_) };
459  
460 if ( !@segments ) {
461 return undef;
462 }
463  
464 my @ungapped;
465 foreach my $f ( $self->ungapped_features() ) {
466 $f = $f->transform(@_);
467 if ( defined($f) ) {
468 push( @ungapped, $f );
469 } else {
470 warning( "Failed to transform alignment feature; "
471 . "ungapped component could not be transformed" );
472 return undef;
473 }
474 }
475  
476 eval { $new_feature = $self->new( -features => \@ungapped ); };
477  
478 if ($@) {
479 warning($@);
480 return undef;
481 }
482 } ## end if ( !defined($new_feature...))
483  
484 return $new_feature;
485 }
486  
487  
488 =head2 _parse_ensembl_cigar
489  
490 Args : none
491 Description: PRIVATE (internal) method - creates ungapped features from
492 internally stored cigar line in ensembl format
493 Returntype : list of Bio::EnsEMBL::FeaturePair
494 Exceptions : none
495 Caller : ungapped_features
496 Status : Stable
497  
498 =cut
499  
500 sub _parse_ensembl_cigar {
501 my ( $self ) = @_;
502  
503 my $query_unit = $self->_query_unit();
504 my $hit_unit = $self->_hit_unit();
505  
506 my $string = $self->{'cigar_string'};
507  
508 throw("No cigar string defined in object") if(!defined($string));
509  
510 my @pieces = ( $string =~ /(\d*[MDI])/g );
511  
512 my @features;
513 my $strand1 = $self->{'strand'} || 1;
514 my $strand2 = $self->{'hstrand'}|| 1;
515  
516 my ( $start1, $start2 );
517  
518 if( $strand1 == 1 ) {
519 $start1 = $self->{'start'};
520 } else {
521 $start1 = $self->{'end'};
522 }
523  
524 if( $strand2 == 1 ) {
525 $start2 = $self->{'hstart'};
526 } else {
527 $start2 = $self->{'hend'};
528 }
529  
530 #
531 # Construct ungapped blocks as FeaturePairs objects for each MATCH
532 #
533 foreach my $piece (@pieces) {
534  
535 my ($length) = ( $piece =~ /^(\d*)/ );
536 if( $length eq "" ) { $length = 1 }
537 my $mapped_length;
538  
539 # explicit if statements to avoid rounding problems
540 # and make sure we have sane coordinate systems
541 if( $query_unit == 1 && $hit_unit == 3 ) {
542 $mapped_length = $length*3;
543 } elsif( $query_unit == 3 && $hit_unit == 1 ) {
544 $mapped_length = $length / 3;
545 } elsif ( $query_unit == 1 && $hit_unit == 1 ) {
546 $mapped_length = $length;
547 } else {
548 throw("Internal error $query_unit $hit_unit, currently only " .
549 "allowing 1 or 3 ");
550 }
551  
552 if( int($mapped_length) != $mapped_length and
553 ($piece =~ /M$/ or $piece =~ /D$/)) {
554 throw("Internal error with mismapped length of hit, query " .
555 "$query_unit, hit $hit_unit, length $length");
556 }
557  
558 if( $piece =~ /M$/ ) {
559 #
560 # MATCH
561 #
562 my ( $qstart, $qend);
563 if( $strand1 == 1 ) {
564 $qstart = $start1;
565 $qend = $start1 + $length - 1;
566 $start1 = $qend + 1;
567 } else {
568 $qend = $start1;
569 $qstart = $start1 - $length + 1;
570 $start1 = $qstart - 1;
571 }
572  
573 my ($hstart, $hend);
574 if( $strand2 == 1 ) {
575 $hstart = $start2;
576 $hend = $start2 + $mapped_length - 1;
577 $start2 = $hend + 1;
578 } else {
579 $hend = $start2;
580 $hstart = $start2 - $mapped_length + 1;
581 $start2 = $hstart - 1;
582 }
583  
584  
585 push @features, Bio::EnsEMBL::FeaturePair->new
586 (-SLICE => $self->{'slice'},
587 -SEQNAME => $self->{'seqname'},
588 -START => $qstart,
589 -END => $qend,
590 -STRAND => $strand1,
591 -HSLICE => $self->{'hslice'},
592 -HSEQNAME => $self->{'hseqname'},
593 -HSTART => $hstart,
594 -HEND => $hend,
595 -HSTRAND => $strand2,
596 -SCORE => $self->{'score'},
597 -PERCENT_ID => $self->{'percent_id'},
598 -ANALYSIS => $self->{'analysis'},
599 -P_VALUE => $self->{'p_value'},
600 -EXTERNAL_DB_ID => $self->{'external_db_id'},
601 -HCOVERAGE => $self->{'hcoverage'},
602 -GROUP_ID => $self->{'group_id'},
603 -LEVEL_ID => $self->{'level_id'});
604
605  
606 # end M cigar bits
607 } elsif( $piece =~ /I$/ ) {
608 #
609 # INSERT
610 #
611 if( $strand1 == 1 ) {
612 $start1 += $length;
613 } else {
614 $start1 -= $length;
615 }
616 } elsif( $piece =~ /D$/ ) {
617 #
618 # DELETION
619 #
620 if( $strand2 == 1 ) {
621 $start2 += $mapped_length;
622 } else {
623 $start2 -= $mapped_length;
624 }
625 } else {
626 throw( "Illegal cigar line $string!" );
627 }
628 }
629  
630 return \@features;
631 }
632  
633  
634 sub _parse_cigar {
635 my $self = shift;
636  
637 if ($self->{'align_type'} eq 'ensembl') {
638 return $self->_parse_ensembl_cigar();
639 }
640 else {
641 throw("No parsing method implemented for " . $self->{'align_type'});
642 }
643 }
644  
645  
646 =head2 _parse_features
647  
648 Arg [1] : listref Bio::EnsEMBL::FeaturePair $ungapped_features
649 Description: creates internal cigar_string and start,end hstart,hend
650 entries.
651 Returntype : none, fills in values of self
652 Exceptions : argument list undergoes many sanity checks - throws under many
653 invalid conditions
654 Caller : new
655 Status : Stable
656  
657 =cut
658  
659 sub _parse_features {
660 my ($self, $features) = @_;
661 if ($self->{'align_type'} eq 'ensembl') {
662 $self->_parse_ensembl_features($features);
663 } else {
664 throw("No _parse_features method implemented for " . $self->{'align_type'});
665 }
666 }
667  
668 my $message_only_once = 1;
669  
670 sub _parse_ensembl_features {
671 my ($self,$features ) = @_;
672  
673 if (ref($features) ne "ARRAY") {
674 throw("features must be an array reference not a [".ref($features)."]");
675 } elsif (scalar(@$features) == 0) {
676 throw("features array must not be empty");
677 }
678  
679 my $query_unit = $self->_query_unit();
680 my $hit_unit = $self->_hit_unit();
681  
682 my $strand = $features->[0]->strand;
683  
684 throw ('FeaturePair needs to have strand == 1 or strand == -1') if(!$strand);
685  
686 my @f;
687  
688 #
689 # Sort the features on their start position
690 # Ascending order on positive strand, descending on negative strand
691 #
692 if( $strand == 1 ) {
693 @f = sort {$a->start <=> $b->start} @$features;
694 } else {
695 @f = sort { $b->start <=> $a->start} @$features;
696 }
697  
698 my $hstrand = $f[0]->hstrand;
699 my $slice = $f[0]->slice();
700 my $hslice = $f[0]->hslice();
701 my $name = $slice ? $slice->name() : undef;
702 my $hname = $f[0]->hseqname;
703 my $score = $f[0]->score;
704 my $percent = $f[0]->percent_id;
705 my $analysis = $f[0]->analysis;
706 my $pvalue = $f[0]->p_value();
707 my $external_db_id = $f[0]->external_db_id;
708 my $hcoverage = $f[0]->hcoverage;
709 my $group_id = $f[0]->group_id;
710 my $level_id = $f[0]->level_id;
711  
712 my $seqname = $f[0]->seqname;
713 # implicit strand 1 for peptide sequences
714 $strand ||= 1;
715 $hstrand ||= 1;
716 my $ori = $strand * $hstrand;
717  
718 throw("No features in the array to parse") if(scalar(@f) == 0);
719  
720 my $prev1; # where last feature q part ended
721 my $prev2; # where last feature s part ended
722  
723 my $string;
724  
725 # Use strandedness info of query and hit to make sure both sets of
726 # start and end coordinates are oriented the right way around.
727 my $f1start;
728 my $f1end;
729 my $f2end;
730 my $f2start;
731  
732 if ($strand == 1) {
733 $f1start = $f[0]->start;
734 $f1end = $f[-1]->end;
735 } else {
736 $f1start = $f[-1]->start;
737 $f1end = $f[0]->end;
738 }
739  
740 if ($hstrand == 1) {
741 $f2start = $f[0]->hstart;
742 $f2end = $f[-1]->hend;
743 } else {
744 $f2start = $f[-1]->hstart;
745 $f2end = $f[0]->hend;
746 }
747  
748 #
749 # Loop through each portion of alignment and construct cigar string
750 #
751  
752 foreach my $f (@f) {
753 #
754 # Sanity checks
755 #
756  
757 if (!$f->isa("Bio::EnsEMBL::FeaturePair")) {
758 throw("Array element [$f] is not a Bio::EnsEMBL::FeaturePair");
759 }
760 if( defined($f->hstrand()) && $f->hstrand() != $hstrand ) {
761 throw("Inconsistent hstrands in feature array");
762 }
763 if( defined($f->strand()) && ($f->strand != $strand)) {
764 throw("Inconsistent strands in feature array");
765 }
766 if ( defined($name) && $name ne $f->slice->name()) {
767 throw("Inconsistent names in feature array [$name - ".
768 $f->slice->name()."]");
769 }
770 if ( defined($hname) && $hname ne $f->hseqname) {
771 throw("Inconsistent hit names in feature array [$hname - ".
772 $f->hseqname . "]");
773 }
774 if ( defined($score) && $score ne $f->score) {
775 throw("Inconsisent scores in feature array [$score - " .
776 $f->score . "]");
777 }
778 if (defined($f->percent_id) && $percent ne $f->percent_id) {
779 throw("Inconsistent pids in feature array [$percent - " .
780 $f->percent_id . "]");
781 }
782 if(defined($pvalue) && $pvalue != $f->p_value()) {
783 throw("Inconsistant p_values in feature arraw [$pvalue " .
784 $f->p_value() . "]");
785 }
786 if($seqname && $seqname ne $f->seqname){
787 throw("Inconsistent seqname in feature array [$seqname - ".
788 $f->seqname . "]");
789 }
790 my $start1 = $f->start; #source sequence alignment start
791 my $start2 = $f->hstart(); #hit sequence alignment start
792  
793 #
794 # More sanity checking
795 #
796 if (defined($prev1)) {
797 if ( $strand == 1 ) {
798 if ($f->start < $prev1) {
799 throw("Inconsistent coords in feature array (forward strand).\n" .
800 "Start [".$f->start()."] in current feature should be greater " .
801 "than previous feature end [$prev1].");
802 }
803 } else {
804 if ($f->end > $prev1) {
805 throw("Inconsistent coords in feature array (reverse strand).\n" .
806 "End [".$f->end() ."] should be less than previous feature " .
807 "start [$prev1].");
808 }
809 }
810 }
811  
812 my $length = ($f->end - $f->start + 1); #length of source seq alignment
813 my $hlength = ($f->hend - $f->hstart + 1); #length of hit seq alignment
814  
815 # using multiplication to avoid rounding errors, hence the
816 # switch from query to hit for the ratios
817  
818 #
819 # Yet more sanity checking
820 #
821 if($query_unit > $hit_unit){
822 # I am going to make the assumption here that this situation will
823 # only occur with DnaPepAlignFeatures, this may not be true
824 my $query_p_length = sprintf "%.0f", ($length/$query_unit);
825 my $hit_p_length = sprintf "%.0f", ($hlength * $hit_unit);
826 if( $query_p_length != $hit_p_length) {
827 throw( "Feature lengths not comparable Lengths:" .$length .
828 " " . $hlength . " Ratios:" . $query_unit . " " .
829 $hit_unit );
830 }
831 } else{
832 my $query_d_length = sprintf "%.0f", ($length*$hit_unit);
833 my $hit_d_length = sprintf "%.0f", ($hlength * $query_unit);
834 if( $length * $hit_unit != $hlength * $query_unit ) {
835 throw( "Feature lengths not comparable Lengths:" . $length .
836 " " . $hlength . " Ratios:" . $query_unit . " " .
837 $hit_unit );
838 }
839 }
840  
841 my $hlengthfactor = ($query_unit/$hit_unit);
842  
843 #
844 # Check to see if there is an I type (insertion) gap:
845 # If there is a space between the end of the last source sequence
846 # alignment and the start of this one, then this is an insertion
847 #
848  
849 my $insertion_flag = 0;
850 if( $strand == 1 ) {
851 if( ( defined $prev1 ) && ( $f->start > $prev1 + 1 )) {
852  
853 #there is an insertion
854 $insertion_flag = 1;
855 my $gap = $f->start - $prev1 - 1;
856 if( $gap == 1 ) {
857 $gap = ""; # no need for a number if gap length is 1
858 }
859 $string .= "$gap"."I";
860  
861 }
862  
863 #shift our position in the source seq alignment
864 $prev1 = $f->end();
865 } else {
866  
867 if(( defined $prev1 ) && ($f->end + 1 < $prev1 )) {
868  
869 #there is an insertion
870 $insertion_flag = 1;
871 my $gap = $prev1 - $f->end() - 1;
872 if( $gap == 1 ) {
873 $gap = ""; # no need for a number if gap length is 1
874 }
875 $string .= "$gap"."I";
876 }
877  
878 #shift our position in the source seq alignment
879 $prev1 = $f->start();
880 }
881  
882 #
883 # Check to see if there is a D type (deletion) gap
884 # There is a deletion gap if there is a space between the end of the
885 # last portion of the hit sequence alignment and this one
886 #
887 if( $hstrand == 1 ) {
888 if(( defined $prev2 ) && ( $f->hstart() > $prev2 + 1 )) {
889  
890 #there is a deletion
891 my $gap = $f->hstart - $prev2 - 1;
892 my $gap2 = int( $gap * $hlengthfactor + 0.5 );
893
894 if( $gap2 == 1 ) {
895 $gap2 = ""; # no need for a number if gap length is 1
896 }
897 $string .= "$gap2"."D";
898  
899 #sanity check, Should not be an insertion and deletion
900 if($insertion_flag) {
901 if ($message_only_once) {
902 warning("Should not be an deletion and insertion on the " .
903 "same alignment region. cigar_line=$string\n");
904 $message_only_once = 0;
905 }
906 }
907 }
908 #shift our position in the hit seq alignment
909 $prev2 = $f->hend();
910  
911 } else {
912 if( ( defined $prev2 ) && ( $f->hend() + 1 < $prev2 )) {
913  
914 #there is a deletion
915 my $gap = $prev2 - $f->hend - 1;
916 my $gap2 = int( $gap * $hlengthfactor + 0.5 );
917
918 if( $gap2 == 1 ) {
919 $gap2 = ""; # no need for a number if gap length is 1
920 }
921 $string .= "$gap2"."D";
922  
923 #sanity check, Should not be an insertion and deletion
924 if($insertion_flag) {
925 if ($message_only_once) {
926 warning("Should not be an deletion and insertion on the " .
927 "same alignment region. prev2 = $prev2; f->hend() = " .
928 $f->hend() . "; cigar_line = $string;\n");
929 $message_only_once = 0;
930 }
931 }
932 }
933 #shift our position in the hit seq alignment
934 $prev2 = $f->hstart();
935 }
936  
937 my $matchlength = $f->end() - $f->start() + 1;
938 if( $matchlength == 1 ) {
939 $matchlength = "";
940 }
941 $string .= $matchlength."M";
942 }
943  
944 $self->{'start'} = $f1start;
945 $self->{'end'} = $f1end;
946 $self->{'seqname'} = $seqname;
947 $self->{'strand'} = $strand;
948 $self->{'score'} = $score;
949 $self->{'percent_id'} = $percent;
950 $self->{'analysis'} = $analysis;
951 $self->{'slice'} = $slice;
952 $self->{'hslice'} = $hslice;
953 $self->{'hstart'} = $f2start;
954 $self->{'hend'} = $f2end;
955 $self->{'hstrand'} = $hstrand;
956 $self->{'hseqname'} = $hname;
957 $self->{'cigar_string'} = $string;
958 $self->{'p_value'} = $pvalue;
959 $self->{'external_db_id'} = $external_db_id;
960 $self->{'hcoverage'} = $hcoverage;
961 $self->{'group_id'} = $group_id;
962 $self->{'level_id'} = $level_id;
963 }
964  
965  
966  
967  
968  
969  
970 =head2 _hit_unit
971  
972 Args : none
973 Description: abstract method, overwrite with something that returns
974 one or three
975 Returntype : int 1,3
976 Exceptions : none
977 Caller : internal
978 Status : Stable
979  
980 =cut
981  
982 sub _hit_unit {
983 my $self = shift;
984 throw( "Abstract method call!" );
985 }
986  
987  
988  
989 =head2 _query_unit
990  
991 Args : none
992 Description: abstract method, overwrite with something that returns
993 one or three
994 Returntype : int 1,3
995 Exceptions : none
996 Caller : internal
997 Status : Stable
998  
999 =cut
1000  
1001 sub _query_unit {
1002 my $self = shift;
1003 throw( "Abstract method call!" );
1004 }
1005  
1006 =head2 _mdtag_alignment_length
1007  
1008 Arg [1] : None
1009 Description: return the alignment length (including indels) based on the mdtag (mdz) string
1010 Returntype : int
1011 Exceptions : none
1012 Caller : internal
1013 Status : Stable
1014  
1015 =cut
1016  
1017 sub _mdtag_alignment_length {
1018 my $self = shift;
1019  
1020 if (! defined $self->{'_alignment_length'} && defined $self->cigar_string) {
1021 my $mdz_string = $self->cigar_string;
1022 my $chunks = $self->_get_mdz_chunks($mdz_string);
1023 my $alignment_length = 0;
1024 $alignment_length = $self->_get_mdz_alignment_length($chunks);
1025 $self->{'_alignment_length'} = $alignment_length;
1026 }
1027 return $self->{'_alignment_length'};
1028 }
1029  
1030 =head2 _get_mdz_chunks
1031  
1032 Arg [1] : mdtag string - MD Z String for mismatching positions. Regex : [0-9]+(([A-Z]|\^[A-Z]+)[0-9]+)* (Refer: SAM/BAM specification)
1033 Description: parses the mdtag string and group it according the type
1034 eg: MD:Z:35^VIVALE31^GRPLIQPRRKKAYQLEHTFQGLLGKRSLFTE10 returns ['35', '^', 'VIVALE', '31', '^', 'GRPLIQPRRKKAYQLEHTFQGLLGKRSLFTE', '10']
1035 Returntype : array of strings
1036 Exceptions : none
1037 Caller : internal
1038 Status : Stable
1039  
1040 =cut
1041 sub _get_mdz_chunks {
1042 my $self = shift;
1043  
1044 my $mdz_string = shift;
1045 my $alignment_length = 0;
1046 my @chunks;
1047 if ( $mdz_string =~ /^MD:Z:(.+)/ ){
1048 my $mdtag = $1;
1049  
1050 #if start to end is a number then all match return as it is
1051 if($mdtag =~/^\d+$/){
1052 return [$mdtag];
1053 } else{
1054 my @char_arr = split('',$mdtag);
1055 # Set up for the first loop, this also will handle
1056 # if the array is size one, as we'll have a character
1057 # in the current_chunk to push on the pile at the end.
1058 my $prev_type = $self->_get_mdz_chunk_type( $char_arr[0]);
1059 my $current_chunk = $char_arr[0];
1060 for(my $i = 1; $i <= $#char_arr; $i++) {
1061 my $cur_type = $self->_get_mdz_chunk_type( $char_arr[$i] );
1062 if($cur_type ne $prev_type) {
1063 # We've found a new character class, push the
1064 # current chunk on to the list
1065 push @chunks, $current_chunk;
1066 # Restart the current pile
1067 $current_chunk = $char_arr[$i];
1068 } else {
1069 # Same character class, put it on the current pile
1070 $current_chunk .= $char_arr[$i];
1071 }
1072 # Shift current type in to the prior slot
1073 $prev_type = $cur_type;
1074 }
1075  
1076 # Post loop cleanup of the last piece
1077 # This also handles an array of size one where
1078 # we never entered the loop, that one element
1079 # now gets pushed on the pile.
1080 push @chunks, $current_chunk;
1081 }
1082 }
1083 return \@chunks;
1084 }
1085  
1086 =head2 _get_mdz_alignment_length
1087  
1088 Arg [1] : array of strings
1089 Description: calculate the alignment length from the given chunks
1090 Returntype : array of strings
1091 Exceptions : none
1092 Caller : internal
1093 Status : Stable
1094  
1095 =cut
1096  
1097 sub _get_mdz_alignment_length{
1098 my $self = shift;
1099  
1100 my $chunks = shift;
1101 my $length = 0;
1102 for(my $i=0; $i< scalar(@$chunks); $i++){
1103 my $chunk = $chunks->[$i];
1104 my $type = $self->_get_mdz_chunk_type($chunk);
1105  
1106 if($type eq 'num'){
1107 $length = $length + $chunk;
1108 }elsif($type eq 'alpha'){
1109 $length = $length + length($chunk);
1110 }elsif($type eq 'del'){
1111 #skip next chunk
1112 $i++;
1113 }
1114  
1115 }
1116 return $length;
1117 }
1118  
1119 =head2 _get_mdz_chunk_type
1120  
1121 Arg [1] : char
1122 Description: get the chunk type
1123 Returntype : string
1124 Exceptions : none
1125 Caller : internal
1126 Status : Stable
1127  
1128 =cut
1129  
1130 sub _get_mdz_chunk_type{
1131 my $self = shift;
1132 my $char = shift;
1133  
1134 my $type;
1135 if($char eq '^'){
1136 $type = "del";
1137 } elsif($char =~ /\d+/){
1138 $type = 'num';
1139 } elsif($char =~ /\w+/){
1140 $type = 'alpha';
1141 }
1142 return $type;
1143 }
1144  
1145  
1146 =head2 _mdz_alignment_string
1147  
1148 Arg [1] : input sequence
1149 Arg [2] : MD Z String for mismatching positions. Regex : [0-9]+(([A-Z]|\^[A-Z]+)[0-9]+)* (Refer: SAM/BAM specification)
1150 eg: MD:Z:96^RHKTDSFVGLMGKRALNS0V14
1151 Example : $pf->alignment_strings
1152 Description: Allows to rebuild the alignment string of both the seq and hseq sequence
1153 Returntype : array reference containing 2 strings
1154 the first corresponds to seq
1155 the second corresponds to hseq
1156 Exceptions : none
1157 Caller : general
1158 Status : Stable
1159  
1160 =cut
1161  
1162 # Try to get the sequence from translation object
1163 # mdz_string from current object
1164 sub _mdz_alignment_string {
1165 my ($self, $input_seq, $mdz_string) = @_;
1166  
1167 my $chunks = $self->_get_mdz_chunks($mdz_string);
1168  
1169 my $target_seq = "";
1170 my $query_seq = "";
1171  
1172 #Handle first chunk, which is always a num
1173 my $first_chunk = $chunks->[0];
1174 my $first_chunk_type = $self->_get_mdz_chunk_type($first_chunk);
1175  
1176 my $offset = 0;
1177 if($first_chunk_type eq 'num'){
1178 if($first_chunk > 0){
1179 $target_seq = substr($input_seq, $offset, $first_chunk);
1180  
1181 #query and target are same at this point
1182 $query_seq = $target_seq;
1183 $offset = length($target_seq);
1184 }
1185 }else{
1186 die "First chunk should always be a num...something wrong\n";
1187 }
1188  
1189 for(my $i=1; $i < scalar(@$chunks); $i++){
1190  
1191 my $chunk = $chunks->[$i];
1192 my $chunk_type = $self->_get_mdz_chunk_type($chunk);
1193  
1194 if($chunk_type eq 'num'){
1195 #if 0, what follows next is a INSERT
1196 if($chunk == 0){
1197 my $insert_chunk = $chunks->[++$i];
1198 my $insert_chunk_type = $self->_get_mdz_chunk_type($insert_chunk);
1199  
1200 #insert_chunk_type is always alpha
1201 die if $insert_chunk_type eq "num";
1202 if($insert_chunk_type eq 'del'){
1203 $i--;
1204 next;
1205 }
1206 $target_seq = $target_seq . substr($input_seq, $offset, length($insert_chunk));
1207 $query_seq = $query_seq . $insert_chunk;
1208  
1209 $offset = $offset + length($insert_chunk);
1210  
1211 }else{
1212 #if non-0, then it is a match
1213 my $match_chunk = $chunks->[$i];
1214 my $match_chunk_type = $self->_get_mdz_chunk_type($match_chunk);
1215  
1216 #$match_chunk_type is always num
1217 die if $match_chunk_type ne "num";
1218  
1219 my $match_target_string = substr($input_seq, $offset, $match_chunk);
1220  
1221 $target_seq = $target_seq . $match_target_string;
1222 $query_seq = $query_seq . $match_target_string;
1223  
1224 $offset = $offset + $match_chunk;
1225 }
1226  
1227 }elsif($chunk_type eq 'alpha'){
1228 my $insert_chunk = $chunk;
1229 my $insert_chunk_type = $self->_get_mdz_chunk_type($insert_chunk);
1230 die if $insert_chunk_type ne "alpha";
1231  
1232 $target_seq = $target_seq . substr($input_seq, $offset, length($insert_chunk));
1233 $query_seq = $query_seq . $insert_chunk;
1234  
1235 $offset = $offset + length($insert_chunk);
1236  
1237 }elsif($chunk_type eq 'del'){
1238 #get next chunk which contains the deleted sequence
1239 my $del_chunk = $chunks->[++$i];
1240 my $del_chunk_type = $self->_get_mdz_chunk_type($del_chunk);
1241  
1242 #del_chunk_type is always alpha
1243 die if $del_chunk_type ne 'alpha';
1244  
1245 $target_seq = $target_seq . "-" x length($del_chunk);
1246 $query_seq = $query_seq . $del_chunk;
1247  
1248 #no change in offset
1249 $offset = $offset;
1250  
1251  
1252 }
1253  
1254 }
1255  
1256 return [$target_seq, $query_seq];
1257  
1258 }
1259  
1260  
1261 1;