BaseAlignFeature.pm 28 KB
Newer Older
1 2 3 4 5 6
# EnsEMBL module for storing dna-protein pairwise alignments
#
# Cared for by Michele Clamp <michele@sanger.ac.uk>
#
# You may distribute this module under the same terms as perl itself
#
7
=pod
8 9 10 11 12 13 14 15

=head1 NAME

  Bio::EnsEMBL::DnaPepAlignFeature - Ensembl specific dna-protein pairwise alignment feature

=head1 SYNOPSIS

  my $feat = new Bio::EnsEMBL::DnaPepAlignFeature(-seqname => 'myseq',
16 17 18 19 20 21
                                                  -start   => 100,
                                                  -end     => 120,
                                                  -strand  => 1,
                                                  -hstart  => 200,
                                                  -hend    => 220,
                                                  -analysis    => $analysis,
Laura Clarke's avatar
 
Laura Clarke committed
22
                                                  -cigar_string => '');
23

24
  Alternatively if you have an array of ungapped features
25 26 27

      my $feat = new Bio::EnsEMBL::DnaPepAlignFeature(-features => \@features);

28
  Where @features is an array of Bio::EnsEMBL::FeaturePair
29

30
  There is a method to manipulate the cigar_string into ungapped features
31 32 33

      my @ungapped_features = $feat->ungapped_features;

34
  This converts the cigar string into an array of Bio::EnsEMBL::FeaturePair
35

36
  $analysis is a Bio::EnsEMBL::Analysis object
37
  
38 39
  Bio::EnsEMBL::SeqFeature methods can be used
  Bio::EnsEMBL::FeaturePair methods can be used
40

41 42 43 44 45
  The cigar_string contains the ungapped pieces that make up the gapped alignment
  
  It looks like: n Matches [ x Deletes or Inserts m Matches ]*
  but a bit more condensed like "23M4I12M2D1M"
  and evenmore condensed as you can ommit 1s "23M4I12M2DM"
46 47


48
  To make things clearer this is how a blast HSP would be parsed
49

50 51
  >AK014066
         Length = 146
52

53
    Minus Strand HSPs:
54

55 56
    Score = 76 (26.8 bits), Expect = 1.4, P = 0.74
    Identities = 20/71 (28%), Positives = 29/71 (40%), Frame = -1
57

58 59 60
  Query:   479 GLQAPPPTPQGCRLIPPPPLGLQAPLPTLRAVGSSHHHP*GRQGSSLSSFRSSLASKASA 300
               G  APPP PQG R   P P G + P   L             + + ++  R  +A   +
  Sbjct:     7 GALAPPPAPQG-RWAFPRPTG-KRPATPLHGTARQDRQVRRSEAAKVTGCRGRVAPHVAP 64
61

62 63 64
  Query:   299 SSPHNPSPLPS 267
                  H P+P P+
  Sbjct:    65 PLTHTPTPTPT 75
65

66 67
  The alignment goes from 267 to 479 in sequence 1 and 7 to 75 in sequence 2 and the
  strand is -1.
68

69
  The alignment is made up of the following ungapped pieces :
70

71 72 73
  sequence 1 start 447 , sequence 2 start 7  , match length 33 , strand -1
  sequence 1 start 417 , sequence 2 start 18 , match length 27 , strand -1
  sequence 1 start 267 , sequence 2 start 27 , match length 137 , strand -1
74

75 76 77 78
  These ungapped pieces are made up into the following string (called a cigar string)
  "33M3I27M3I137M" with start 267 end 479 strand -1 hstart 7 hend 75 hstrand 1 and
  feature type would be DnaPepAlignFeature
  
79 80 81

=cut 

82

83 84 85 86 87 88 89 90
package Bio::EnsEMBL::BaseAlignFeature;

use Bio::EnsEMBL::FeaturePair;
use Bio::EnsEMBL::SeqFeature;

use vars qw(@ISA);
use strict;

91
@ISA = qw(Bio::EnsEMBL::FeaturePair);
92 93 94 95 96

sub new {
    my ($class,@args) = @_;

    my $self = $class->SUPER::new(@args);
Laura Clarke's avatar
 
Laura Clarke committed
97
    #print "calling new with @args\n";
98 99
    my ($cigar_string,$features) 
      = $self->_rearrange([qw(CIGAR_STRING FEATURES)], @args);
Laura Clarke's avatar
 
Laura Clarke committed
100

101 102 103 104 105 106
    if (defined($cigar_string) && defined($features)) {
      $self->throw("Can't input cigar_string and an array of features.");
    } elsif (defined($features)) {
      $self->_parse_features($features);
    } elsif (!defined($cigar_string)) {
      $self->throw("Must have a cigar string defining the alignment");
107
    } 
108
    
109
    $self->cigar_string($cigar_string);
110
    
111 112 113 114
    return $self;
}


Arne Stabenau's avatar
Arne Stabenau committed
115
=head2 cigar_string
116

Arne Stabenau's avatar
Arne Stabenau committed
117
  Arg [1]    : string $cigar_string
118
  Example    : ( "12MI3M" )
Arne Stabenau's avatar
Arne Stabenau committed
119 120 121 122 123 124 125 126
  Description: get/set for attribute cigar_string
               cigar_string describes the alignment. "xM" stands for 
               x matches (mismatches), "xI" for inserts into query sequence 
               (thats the ensembl sequence), "xD" for deletions (inserts in the 
               subject). an "x" that is 1 can be omitted.
  Returntype : string
  Exceptions : throws on a get without previous set
  Caller     : general
127 128 129 130 131 132 133

=cut



sub cigar_string {
  my ($self,$arg) = @_;
134
  
135
  if (defined($arg)) {
136
    
137 138 139 140 141 142 143 144 145
    # Do some checks to see whether this is valid
    my $tmp = $arg;
    
    $self->{_cigar_string} = $arg;
  }

  if (!defined($self->{_cigar_string})) {
    $self->throw("No cigar string defined - can't return one");
  }
146
  
147 148 149 150 151 152
  return $self->{_cigar_string};
}


=head2 ungapped_features

Arne Stabenau's avatar
Arne Stabenau committed
153 154 155 156 157 158 159
  Args       : none
  Example    : none
  Description: converts the internal cigar_string into an array of
               ungapped feature pairs
  Returntype : list of Bio::EnsEMBL::FeaturePair
  Exceptions : cigar_string not set internally
  Caller     : general
160

Arne Stabenau's avatar
Arne Stabenau committed
161
=cut
162 163 164 165 166 167 168 169 170 171 172 173 174 175 176



sub ungapped_features {
  my ($self) = @_;

  if (defined($self->cigar_string)) {
    my @features = $self->_parse_cigar;
    return @features;
  } else {
    $self->throw("No cigar_string defined.  Can't return ungapped features");
  }

}

177

178

179 180
=head2 transform

Arne Stabenau's avatar
Arne Stabenau committed
181 182 183 184 185 186 187 188 189 190
  Arg [1]    : Bio::EnsEMBL::Slice $slice
  Example    : none
  Description: if argument is given, transforms this feature into the slice
               coordinate system, invalidating this one.
               if no argument is given, transforms this feature into raw contig
               coordinates, invalidating this one.
               The process can produce more than one feature so we return an array. 
  Returntype : list of Bio::EnsEMBL::BaseAlignFeature
  Exceptions : none
  Caller     : general
191

Arne Stabenau's avatar
Arne Stabenau committed
192
=cut
193 194


195 196
sub transform{
  my ($self, $slice) = @_;
Laura Clarke's avatar
 
Laura Clarke committed
197
  #print "transforming ".$self." to ".$slice." coords\n";
198 199 200 201
  if( ! defined $slice ) {
    #Since slice arg is not defined -  we want raw contig coords
    if(( defined  $self->contig ) && 
       ( $self->contig->isa( "Bio::EnsEMBL::RawContig" )) ) {
Laura Clarke's avatar
 
Laura Clarke committed
202
   #   print STDERR "BaseAlignFeature::transform, you are already apparently in rawcontig coords so why try to transform to them\n";
203 204 205 206
      #we are already in rawcontig coords, nothing needs to be done
      return $self;
    } else {
      #transform to raw_contig coords from Slice coords
Laura Clarke's avatar
 
Laura Clarke committed
207 208 209 210 211 212
      my @array =  $self->_transform_to_rawcontig();
    #  print "transform to  rawcontig has returned ".@array." features\n";
    #  foreach my $a(@array){
#	print "feature is ".$a."\n";
#      }
      return @array;
213 214
    }
  }
215

216 217 218 219 220 221 222 223 224 225 226
  if( defined $self->contig ) {  
    if($self->contig->isa( "Bio::EnsEMBL::RawContig" ))  {
      #transform to slice coords from raw contig coords
      return $self->_transform_to_slice( $slice );
    } elsif($self->contig->isa( "Bio::EnsEMBL::Slice" )) {
      #transform to slice coords from other slice coords
      return $self->_transform_between_slices( $slice );
    } else {
      #Unknown contig type - throw an exception
      return $self->throw("Exon's 'contig' is of unknown type " 
		   . $self->contig() . " - cannot transform to Slice coords");
227
    }
228 229 230 231 232 233
  } else {
    #Can't convert to slice coords without a contig to work with
    return $self->throw("Exon's contig is not defined - cannot transform to " .
			"Slice coords");
  }
}
234

235
=head2 dbID
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
  Arg [1]    : int $dbID
  Example    : none
  Description: get/set for the database internal id
  Returntype : int
  Exceptions : none
  Caller     : general, set from adaptor on store

=cut


sub dbID{
  my ($self, $arg) = @_;

  if($arg){
    $self->{_database_id} = $arg;
  }

  return $self->{_database_id}; 

}

=head2 adaptor

  Arg [1]    : Bio::EnsEMBL::DBSQL::BaseAlignFeatureAdaptor $adaptor
  Example    : none
  Description: get/set for this objects Adaptor
  Returntype : Bio::EnsEMBL::DBSQL::BaseAlignFeatureAdaptor
  Exceptions : none
  Caller     : general, set from adaptor on store

=cut

sub adaptor {
   my $self = shift;
   if( @_ ) {
      my $value = shift;
      $self->{'adaptor'} = $value;
274
    }
275 276
    return $self->{'adaptor'};

277 278 279
}


280
=head2 contig
281

282 283 284 285 286 287 288 289
  Arg [1]    : Bio::EnsEMBL::Slice or
               Bio::EnsEMBL::RawContig $contig
  Example    : none
  Description: The sequnence where the coordinates make sense. Channeled to
               attach_seq/entire_seq from BioPerl
  Returntype : Slice/RawContig
  Exceptions : none
  Caller     : general
290

291
=cut
292 293


294 295 296 297 298 299 300 301 302 303 304
sub contig {
  my $self = shift;
  if( @_ ) {
    my $value = shift;
    #print "setting exons contig to ".$value." \n";
    $self->attach_seq($value);
  }
  else {
    return $self->entire_seq();
  }
}
305 306 307



308 309 310 311 312 313 314 315
=head2 _parse_cigar

  Args       : none
  Example    : none
  Description: creates ungapped features from internally stored cigar line
  Returntype : list of Bio::EnsEMBL::FeaturePair
  Exceptions : none
  Caller     : ungapped_features
316 317 318

=cut

319 320 321 322 323
sub _parse_cigar {
  my ( $self ) = @_;

  my $query_unit = $self->_query_unit();
  my $hit_unit = $self->_hit_unit();
324

325
  
326
  my $string = $self->cigar_string;
327
 
328 329 330 331 332 333
  if (!defined($string)) {
    $self->throw("No cigar string defined in object.  This should be caught by the cigar_string method and never happen");
  }

  
  my @pieces = ( $string =~ /(\d*[MDI])/g );
Laura Clarke's avatar
 
Laura Clarke committed
334 335
  #print "cigar: ",join ( ",", @pieces ),"\n";
  
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
  my @features;
  my $strand1 = $self->strand() || 1;
  my $strand2 = $self->hstrand() || 1;

  my ( $start1, $start2 );
  
  if( $strand1 == 1 ) {
    $start1 = $self->start();
  } else {
    $start1 = $self->end();
  }

  if( $strand2 == 1 ) {
    $start2 = $self->hstart();
  } else {
    $start2 = $self->hend();
  }


  foreach my $piece (@pieces) {

    my ($length) = ( $piece =~ /^(\d*)/ );
    if( $length eq "" ) { $length = 1 }
    my $mapped_length;

    # explicit if statements to avoid rounding problems
    # and make sure we have sane coordinate systems
    if( $query_unit == 1 && $hit_unit == 3 ) {
      $mapped_length = $length*3;
    } elsif( $query_unit == 3 && $hit_unit == 1 ) {
      $mapped_length = $length / 3;
    } elsif ( $query_unit == 1 && $hit_unit == 1 ) {
      $mapped_length = $length;
    } else {
      $self->throw("Internal error $query_unit $hit_unit, currently only allowing 1 or 3 ");
    }
    
    if( int($mapped_length) != $mapped_length ) {
      $self->throw("Internal error with mismapped length of hit, query $query_unit, hit $hit_unit, length $length");
    }

    if( $piece =~ /M$/ ) {
      my $feature1 = new Bio::EnsEMBL::SeqFeature();
      
      my ( $a, $b );
      if( $strand1 == 1 ) {
382 383 384
        $a = $start1;
        $b = $start1 + $length - 1;
        $start1 = $b + 1;
385
      } else {
386 387 388
        $b = $start1;
        $a = $start1 - $length + 1;
        $start1 = $a - 1;
389 390 391 392 393 394 395 396 397 398 399 400 401
      }
      
      $feature1->start($a);
      $feature1->end  ($b);
      $feature1->strand($self->strand() );
      $feature1->score($self->score);
      $feature1->seqname($self->seqname);
      $feature1->phase($self->phase);
      $feature1->p_value($self->p_value);
      $feature1->percent_id($self->percent_id);

      my $feature2 = new Bio::EnsEMBL::SeqFeature();
      if( $strand2 == 1 ) {
402 403 404
        $a = $start2;
        $b = $start2 + $mapped_length - 1;
        $start2 = $b + 1;
405
      } else {
406 407 408
        $b = $start2;
        $a = $start2 - $mapped_length + 1;
        $start2 = $a - 1;
409 410 411 412 413 414 415 416 417 418 419 420
      }

      $feature2->start($a);
      $feature2->end($b);
      $feature2->strand($self->hstrand());
      $feature2->score($self->score);
      $feature2->seqname($self->hseqname);
      $feature2->phase($self->phase);
      $feature2->p_value($self->p_value);
      $feature2->percent_id($self->percent_id);
    
      my $fp = new Bio::EnsEMBL::FeaturePair(-feature1 => $feature1,
421
                                             -feature2 => $feature2);
422 423 424 425 426 427 428 429

 
      $fp->analysis($self->analysis);

      push(@features,$fp);
      # end M cigar bits 
    } elsif( $piece =~ /I$/ ) {
      if( $strand1 == 1 ) {
430
        $start1 += $length;
431
      } else {
432
        $start1 -= $length;
433 434 435
      }
    } elsif( $piece =~ /D$/ ) {
      if( $strand2 == 1 ) {
436
        $start2 += $mapped_length;
437
      } else {
438
        $start2 -= $mapped_length;
439 440 441 442 443 444 445 446 447 448 449 450 451 452
      }
    } else {
      $self->throw( "Illegal cigar line $string!" );
    } 
      
  }
  # should the features be sorted ?
  # 
  return @features;
}




453
=head2 _parse_features
454

455 456 457 458 459 460 461
  Arg  1     : listref Bio::EnsEMBL::FeaturePair $ungapped_features
  Example    : none
  Description: creates internal cigarstring and start,end hstart,hend
               entries.
  Returntype : none, fills in values of self
  Exceptions : argument list is sanity checked
  Caller     : new
462

463
=cut
464

465 466
sub _parse_features {
  my ($self,$features ) = @_;
467

468 469
  my $query_unit = $self->_query_unit();
  my $hit_unit = $self->_hit_unit();
470 471 472 473
  my $verbose = 0;
  if($features->[0]->hseqname eq 'CE25688'){
    $verbose = 1;
  }
474
  if (ref($features) ne "ARRAY") {
475 476
    $self->throw("features must be an array reference not a [" . 
		 ref($features) . "]");
477 478
  }

479 480 481 482 483 484 485 486 487 488 489 490
  my $strand     = $features->[0]->strand;
  my @f;
  
  #
  # Sort the features on their start position
  # Ascending order on positive strand, descending on negative strand
  #
  if( $strand == 1 ) {
    @f = sort {$a->start <=> $b->start} @$features;
  } else {
    @f = sort { $b->start <=> $a->start} @$features;
  }
491
  #print STDERR $f[0]->gffstring."\n";  
492 493 494 495 496 497 498 499
  my $hstrand     = $f[0]->hstrand;
  my $name        = $f[0]->seqname;
  my $hname       = $f[0]->hseqname;
  my $score       = $f[0]->score;
  my $percent     = $f[0]->percent_id;
  my $pvalue      = $f[0]->p_value;
  my $analysis    = $f[0]->analysis;
  my $phase       = $f[0]->phase;
500
 
501 502 503 504
  # implicit strand 1 for peptide sequences
  ( defined $strand ) || ( $strand = 1 );
  ( defined $hstrand ) || ( $hstrand = 1 );
  my $ori = $strand * $hstrand;
Arne Stabenau's avatar
Arne Stabenau committed
505 506
    
    
507 508 509
  if (scalar(@f) == 0) {
    $self->throw("No features in the array to parse");
  }
510

511 512
  my $prev1; # where last feature q part ended
  my $prev2; # where last feature s part ended
Arne Stabenau's avatar
Arne Stabenau committed
513
    
514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530
  my $string;

  #determine start of the alignment on source sequence    
  my $f1start;
  my $f1end;
  if ( $strand == 1 ) {
    $f1start = $f[0]->start;
    $f1end   = $f[$#f]->end;
  } else {
    $f1end   = $f[0]->end;
    $f1start = $f[$#f]->start;
  }

  #determine start of alignment on hit sequence    
  my $f2start;
  my $f2end;
  if ( $hstrand == 1 ) {
531
   # print STDERR "hstrand forward \n" if($verbose);
532 533 534
    $f2start = $f[0]->hstart;
    $f2end   = $f[$#f]->hend;
  } else {
535
    # print STDERR "hstrand reverse \n" if($verbose);
536 537 538
    $f2end = $f[0]->hend;
    $f2start = $f[$#f]->hstart;
  }
Arne Stabenau's avatar
Arne Stabenau committed
539
    
540 541 542 543 544 545 546
  #
  # Loop through each portion of alignment and construct cigar string
  #
  foreach my $f (@f) {
    #
    # Sanity checks
    #
547
    #print STDERR "supporting feature to convert ".$f->gffstring."\n" if($verbose);
548 549
    if (!$f->isa("Bio::EnsEMBL::FeaturePair")) {
      $self->throw("Array element [$f] is not a Bio::EnsEMBL::FeaturePair");
550
    }
551 552 553 554
    if( defined $f->hstrand() ) {
      if ($f->hstrand != $hstrand) {
	$self->throw("Inconsistent hstrands in feature array");
      }
555
    }
556 557 558
    if( defined $f->strand() ) {
      if ($f->strand != $strand) {
	$self->throw("Inconsistent strands in feature array");
Arne Stabenau's avatar
Arne Stabenau committed
559
      }
560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579
    }
    if ($name ne $f->seqname) {
      $self->throw("Inconsistent names in feature array [$name - " . 
		   $f->seqname . "]");
    }
    if ($hname ne $f->hseqname) {
      $self->throw("Inconsistent names in feature array [$hname - " . 
		   $f->hseqname . "]");
    }
    if ($score ne $f->score) {
      $self->throw("Inconsisent scores in feature array [$score - " . 
		   $f->score . "]");
    }
    if ($percent ne $f->percent_id) {
      $self->throw("Inconsistent pids in feature array [$percent - " . 
		   $f->percent_id . "]");
    }
    
    my $start1 = $f->start;      #source sequence alignment start
    my $start2 = $f->hstart();   #hit sequence alignment start
580
 #   print STDERR "start1 ".$start1." start2 ".$start2."\n"  if($verbose);
581 582 583 584 585 586 587 588 589 590
    #
    # More sanity checking
    #
    if (defined($prev1)) {
      if ( $strand == 1 ) {
	if ($f->start < $prev1) {
	  $self->throw("Inconsistent coordinates feature is forward strand " .
		       "hstart in current feature should be greater than " .
		       "hend in previous feature " . $f->start . " < " .
		       $prev1."\n");
Arne Stabenau's avatar
Arne Stabenau committed
591
	}
592 593 594 595 596
      } else {
	if ($f->end > $prev1) {
	  $self->throw("Inconsistent coordinates in feature array feature " .
		       "is reverse strand hend should be less than previous " .
		       "hstart " . $f->end . " > $prev1");
Arne Stabenau's avatar
Arne Stabenau committed
597
	}
598
      }
599
    }
600

601 602
    my $length = ($f->end - $f->start + 1); #length of source seq alignment
    my $hlength = ($f->hend - $f->hstart + 1); #length of hit seq alignment
603
  #  print STDERR "length ".$length." hlength ".$hlength."\n"  if($verbose);
604 605 606 607 608 609 610 611 612 613 614 615 616
    # using multiplication to avoid rounding errors, hence the
    # switch from query to hit for the ratios
    
    #
    # Yet more sanity checking
    #
    if($query_unit > $hit_unit){
      # I am going to make the assumption here that this situation will 
      # only occur with DnaPepAlignFeatures, this may not be true
      if( int($length/$query_unit)!= $hlength * $hit_unit) {
	$self->throw( "Feature lengths not comparable Lengths:" .$length . 
		      " " . $hlength . " Ratios:" . $query_unit . " " . 
		      $hit_unit );
Arne Stabenau's avatar
Arne Stabenau committed
617
      }
618 619 620 621 622
    } else{
      if( $length * $hit_unit != $hlength * $query_unit ) {
	$self->throw( "Feature lengths not comparable Lengths:" . $length . 
		      " " . $hlength . " Ratios:" . $query_unit . " " . 
		      $hit_unit );
Arne Stabenau's avatar
Arne Stabenau committed
623
      }
624 625 626
    }

    my $hlengthfactor = ($query_unit/$hit_unit);
627
   # print STDERR "hlengthfactor ".$hlengthfactor."\n" if($verbose);
628 629 630 631 632 633
    # if( $query_unit == 1 && $hit_unit == 3 ) {
    #	$hlengthfactor = (1/3);
    #     }
    #     if( $query_unit == 3 && $hit_unit == 1 ) {
    #	$hlengthfactor = 3;
    #      }
Arne Stabenau's avatar
Arne Stabenau committed
634
      
635 636 637 638 639 640 641 642 643 644

    #
    # Check to see if there is an I type (insertion) gap:
    #   If there is a space between the end of the last source sequence 
    #   alignment and the start of this one, then this is an insertion
    #

    my $insertion_flag = 0;
    if( $strand == 1 ) {
      if( ( defined $prev1 ) && ( $f->start > $prev1 + 1  )) {
645
	#print STDERR "there is an insertion\n" if($verbose);
646 647 648 649 650
	#there is an insertion
	$insertion_flag = 1;
	my $gap = $f->start - $prev1 - 1;
	if( $gap == 1 ) {
	  $gap = ""; # no need for a number if gap length is 1
Arne Stabenau's avatar
Arne Stabenau committed
651
	}
652
	$string .= "$gap"."I";
653
	#print STDERR "cigar stands at ".$string."\n" if($verbose);
Arne Stabenau's avatar
Arne Stabenau committed
654
      }
655 656 657 658

      #shift our position in the source seq alignment
      $prev1 = $f->end();
    } else {
659
      #print STDERR "there is a insertion\n";
660 661 662 663 664 665 666
      if(( defined $prev1 ) && ($f->end + 1 < $prev1 )) {

	#there is an insertion
	$insertion_flag = 1;
	my $gap = $prev1 - $f->end() - 1;
	if( $gap == 1 ) {
	  $gap = ""; # no need for a number if gap length is 1
Laura Clarke's avatar
 
Laura Clarke committed
667
	}
668
	$string .= "$gap"."I";
669
	#print STDERR "cigar stands at ".$string."\n" if($verbose);
Arne Stabenau's avatar
Arne Stabenau committed
670
      }
671

672 673 674
      #shift our position in the source seq alignment
      $prev1 = $f->start();
    }
Laura Clarke's avatar
 
Laura Clarke committed
675
      
676 677 678 679 680 681 682
    #
    # Check to see if there is a D type (deletion) gap
    #   There is a deletion gap if there is a space between the end of the
    #   last portion of the hit sequence alignment and this one
    #
    if( $hstrand == 1 ) {
      if((  defined $prev2 ) && ( $f->hstart() > $prev2 + 1 )) {
683
	#print STDERR "there is a deletion\n" if($verbose);
684 685 686 687 688 689
	#there is a deletion
	my $gap = $f->hstart - $prev2 - 1;
	my $gap2 = int( $gap * $hlengthfactor + 0.05 );
	
	if( $gap2 == 1 ) {
	  $gap2 = "";  # no need for a number if gap length is 1
Arne Stabenau's avatar
Arne Stabenau committed
690
	}
691
	$string .= "$gap2"."D";
692
	#print STDERR "cigar stands at ".$string."\n"  if($verbose);
693 694
	#sanity check,  Should not be an insertion and deletion
	if($insertion_flag) {
695
	  $self->warn("Should not be an deletion and insertion on the " .
696
		       "same alignment region. cigar_line=$string\n");
Arne Stabenau's avatar
Arne Stabenau committed
697
	} 
698 699 700 701 702 703
      } 
      #shift our position in the hit seq alignment
      $prev2 = $f->hend();

     } else {
      if( ( defined $prev2 ) && ( $f->hend() + 1 < $prev2 )) {
704
	#print STDERR "there is a deletion\n" if($verbose);
705 706 707 708 709 710
	#there is a deletion
	my $gap = $prev2 - $f->hend - 1;
	my $gap2 = int( $gap * $hlengthfactor + 0.05 );
	
	if( $gap2 == 1 ) {
	  $gap2 = "";  # no need for a number if gap length is 1
Arne Stabenau's avatar
Arne Stabenau committed
711
	}
712
	$string .= "$gap2"."D";
713
	#print STDERR "cigar stands at ".$string."\n" if($verbose);
714 715 716 717 718 719
	#sanity check,  Should not be an insertion and deletion
	if($insertion_flag) {
	  $self->throw("Should not be an deletion and insertion on the " .
		       "same alignment region. prev2 = $prev2; f->hend() = " .
		       $f->hend() . "; cigar_line = $string;\n");
	} 
720
      }
721
      #shift our position in the hit seq alignment
722
     
723 724
      $prev2 = $f->hstart();
    }
725
      
726 727 728
    my $matchlength = $f->end() - $f->start() + 1;
    if( $matchlength == 1 ) {
      $matchlength = "";
729
    }
730
    $string .= $matchlength."M";
731 732
  #  print STDERR "cigar stands at ".$string."\n" if($verbose);
    #print STDERR "finished with this feature\n\n";
733
  }
734 735
#  print STDERR "creating align feature start ".$f1start." end ".$f1end." strand ".$strand." score ".$score." percent id ".$percent." pvalue ".$pvalue." seqname ".$name." phase ".$phase." analysis ".$analysis." hstart ".$f2start," hend ".$f2end." hstrand ".$hstrand." hid ".$hname."\n"; 
  if(!$score){
736
    #$self->warn("score is not set assume its 1");
737 738
    $score = 1;
  } 
739
  my $feature1 = new Bio::EnsEMBL::SeqFeature();
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
  $feature1->start($f1start);
  $feature1->end  ($f1end);
  $feature1->strand($strand);
  $feature1->score($score);
  $feature1->percent_id($percent);
  $feature1->p_value($pvalue);
  $feature1->seqname($name);
  $feature1->phase($phase);
  $feature1->analysis($analysis);
  #print STDERR "checking feature1 ".$feature1->gffstring."\n";
  $feature1->validate;
  
  my $feature2 = new Bio::EnsEMBL::SeqFeature();
  
  $feature2->start($f2start);
  $feature2->end  ($f2end);
  $feature2->strand($hstrand);
  $feature2->score($score);
  $feature2->seqname($hname);
  $feature2->percent_id($percent);
  $feature2->p_value($pvalue);
  $feature2->phase($phase);
  $feature2->analysis($analysis);
  $feature2->validate;
  $self->feature1($feature1);
  $self->feature2($feature2);
  $self->cigar_string($string);
768 769 770
  #print STDERR "finished ".$self->gffstring."\t ".$self->cigar_string."\n\n" if($verbose);

  #print STDERR "\n\n";
771
}
772

Laura Clarke's avatar
 
Laura Clarke committed
773

Arne Stabenau's avatar
Arne Stabenau committed
774

775 776 777 778
sub _transform_to_slice{
  my ($self, $slice ) = @_;
  $self->throw( "implented soon :-)" );
}
Arne Stabenau's avatar
Arne Stabenau committed
779 780


Laura Clarke's avatar
 
Laura Clarke committed
781

Laura Clarke's avatar
 
Laura Clarke committed
782 783
sub _transform_to_rawcontig{
  my ($self, $rc) = @_;
784
  #print STDERR "transforming to raw contig coord\n\n";
Laura Clarke's avatar
 
Laura Clarke committed
785 786 787 788 789
  if(!$self->contig){
    $self->throw("can't transform coordinates of ".$self." without some sort of contig defined");
  }
  #my $mapper = $self->contig->adaptor->db->get_AssemblyMapperAdaptor->fetch_by_type( $self->contig()->assembly_type() );
 
Laura Clarke's avatar
 
Laura Clarke committed
790
  my $rcAdaptor = $self->adaptor()->db()->get_RawContigAdaptor();
Laura Clarke's avatar
 
Laura Clarke committed
791 792
  #my $global_start = $self->contig->chr_start();
  my @out;
Laura Clarke's avatar
 
Laura Clarke committed
793

Laura Clarke's avatar
 
Laura Clarke committed
794 795 796
  my @features = $self->_parse_cigar();
  my @mapped_features;
  my %rc_features;
Laura Clarke's avatar
 
Laura Clarke committed
797

Laura Clarke's avatar
 
Laura Clarke committed
798 799 800 801
  foreach my $f(@features){
    my @new_features = $self->_transform_feature_to_rawcontig($f);
    push(@mapped_features, @new_features);
  }
Arne Stabenau's avatar
Arne Stabenau committed
802

Laura Clarke's avatar
 
Laura Clarke committed
803 804 805 806 807 808 809
  foreach my $mf(@mapped_features){
    my $contig_id = $mf->seqname;
    if(!$rc_features{$contig_id}){
      $rc_features{$contig_id} = [];
      push(@{$rc_features{$contig_id}}, $mf);
    }else{
      push(@{$rc_features{$contig_id}}, $mf);
810
    }
Laura Clarke's avatar
 
Laura Clarke committed
811
  }
Arne Stabenau's avatar
Arne Stabenau committed
812

Laura Clarke's avatar
 
Laura Clarke committed
813 814 815 816 817 818 819
  foreach my $contig_id(keys(%rc_features)){
    my $outputf = $self->new( -features => \@{$rc_features{$contig_id}} );
    $outputf->analysis( $self->analysis() );
    $outputf->score( $self->score() );
    $outputf->percent_id( $self->percent_id() );
    $outputf->p_value( $self->p_value() );
    push(@out, $outputf);
Laura Clarke's avatar
 
Laura Clarke committed
820
  }
Laura Clarke's avatar
 
Laura Clarke committed
821 822
  return @out;

823 824
}

Laura Clarke's avatar
 
Laura Clarke committed
825 826


827 828
sub _transform_between_slices {
  my ( $self, $to_slice ) = @_;
Laura Clarke's avatar
 
Laura Clarke committed
829 830 831
}


832 833 834 835 836 837



=head2 _hit_unit

  Args       : none
Arne Stabenau's avatar
Arne Stabenau committed
838
  Example    : none
839 840 841
  Description: abstract method, overwrite with something that returns
               one or three
  Returntype : int 1,3
Arne Stabenau's avatar
Arne Stabenau committed
842
  Exceptions : none
843
  Caller     : internal
Laura Clarke's avatar
 
Laura Clarke committed
844 845 846

=cut

847 848 849
sub _hit_unit {
  my $self = shift;
  $self->throw( "Abstract method call!" );
Laura Clarke's avatar
 
Laura Clarke committed
850 851
}

852
=head2 _query_unit
Laura Clarke's avatar
 
Laura Clarke committed
853

854
  Args       : none
Arne Stabenau's avatar
Arne Stabenau committed
855
  Example    : none
856 857 858
  Description: abstract method, overwrite with something that returns
               one or three
  Returntype : int 1,3
Arne Stabenau's avatar
Arne Stabenau committed
859
  Exceptions : none
860
  Caller     : internal
Laura Clarke's avatar
 
Laura Clarke committed
861 862 863

=cut

864
sub _query_unit {
Laura Clarke's avatar
 
Laura Clarke committed
865
  my $self = shift;
866
  $self->throw( "Abstract method call!" );
Laura Clarke's avatar
 
Laura Clarke committed
867 868
}

Arne Stabenau's avatar
Arne Stabenau committed
869

Laura Clarke's avatar
 
Laura Clarke committed
870 871 872
sub _transform_feature_to_rawcontig{
  my($self, $feature) =  @_;

873 874 875 876 877
  my $verbose = 0;
  #$verbose = 1 if($feature->hseqname eq 'CE25688');

  #print STDERR "transforming ".$feature->gffstring."\n" if($verbose);

Laura Clarke's avatar
 
Laura Clarke committed
878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901
  if(!$self->contig){
    $self->throw("can't transform coordinates of ".$self." without some sort of contig defined");
  }
  my $mapper = $self->contig->adaptor->db->get_AssemblyMapperAdaptor->fetch_by_type( $self->contig()->assembly_type() );
  
  my $rcAdaptor = $self->adaptor()->db()->get_RawContigAdaptor();
  my $global_start = $self->contig->chr_start();
  my @out;
  my @mapped = $mapper->map_coordinates_to_rawcontig
    (
     $self->contig()->chr_name(),
     $feature->start()+$global_start-1,
     $feature->end()+$global_start-1,
     $feature->strand()*$self->contig()->strand()
    );

  if( ! @mapped ) {
    $self->throw( "couldn't map ".$self."\n" );
    return $self;
  }
  if( scalar( @mapped ) > 1 ) {
    my $hit_start = $feature->hstart;
    #print STDERR " feature is being mapped across multiple contigs ".$feature->gffstring."\n";
  SPLIT: for( my $i=0; $i <= $#mapped; $i++ ) {
902 903 904 905 906
      if($mapped[$i]->isa("Bio::EnsEMBL::Mapper::Gap")){
	$self->warn("piece of evidence lies on gap\n");
	next SPLIT;
      }
      #print STDERR "query coords ".$mapped[$i]->end." ".$mapped[$i]->start."\n";
Laura Clarke's avatar
 
Laura Clarke committed
907
      my $query_length = ($mapped[$i]->end - $mapped[$i]->start + 1);
908
      #print STDERR " query length = ".$query_length."\n";
Laura Clarke's avatar
 
Laura Clarke committed
909 910 911 912
      my $hit_length;
      if($self->_query_unit == $self->_hit_unit){
	$hit_length = $query_length;
      }elsif($self->_query_unit > $self->_hit_unit){
913 914 915
	my $tmp =  ($query_length/$self->_query_unit);
	#print STDERR "tmp = ".$tmp."\n";
	#$hit_length = int($tmp);
916
	$hit_length = sprintf "%.0f", $tmp;
Laura Clarke's avatar
 
Laura Clarke committed
917
      }elsif($self->_hit_unit > $self->_query_unit){
918 919
	my $tmp = ($query_length*$self->_hit_unit);
	#print STDERR "tmp = ".$tmp."\n";
920
	$hit_length = sprintf "%.0f", $tmp;
Laura Clarke's avatar
 
Laura Clarke committed
921
      }
922
      #print STDERR "hit length ".$hit_length."\n";
Laura Clarke's avatar
 
Laura Clarke committed
923 924
     
      my $hit_end = ($hit_start + $hit_length) - 1;
925
      #print "hit start ".$hit_start." hit end ".$hit_end."\n";
Laura Clarke's avatar
 
Laura Clarke committed
926 927 928 929 930
      my $rawContig = $rcAdaptor->fetch_by_dbID( $mapped[$i]->id() );
      my $f1 = new Bio::EnsEMBL::SeqFeature();
      my $f2 = new Bio::EnsEMBL::SeqFeature();
      my $new_feature = Bio::EnsEMBL::FeaturePair->new(-feature1=>$f1,
						       -feature2=>$f2);
931
     
Laura Clarke's avatar
 
Laura Clarke committed
932 933 934 935 936 937 938 939 940 941 942
      $new_feature->start($mapped[$i]->start);
      $new_feature->end($mapped[$i]->end);
      $new_feature->strand($mapped[$i]->strand);
      $new_feature->seqname($mapped[$i]->id);
      $new_feature->score($feature->score);
      $new_feature->percent_id($feature->percent_id);
      $new_feature->p_value($feature->p_value);
      $new_feature->hstart($hit_start);
      $new_feature->hend($hit_end);
      $new_feature->hstrand($feature->hstrand);
      $new_feature->hseqname($feature->hseqname);
943
      #$new_feature->hscore($feature->score);
Laura Clarke's avatar
 
Laura Clarke committed
944 945 946 947
      $new_feature->analysis($feature->analysis);
      $new_feature->attach_seq($rawContig);
      #print STDERR "split feature ".$new_feature->gffstring."\n";
      push(@out, $new_feature);
948
      $hit_start = ($hit_end + 1);
Laura Clarke's avatar
 
Laura Clarke committed
949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970
    }
  }else{
    if($mapped[0]->isa("Bio::EnsEMBL::Mapper::Gap")){
      $self->warn("piece of evidence lies on gap\n");
      return;
    }
    my $rawContig = $rcAdaptor->fetch_by_dbID( $mapped[0]->id() );
    my $f1 = new Bio::EnsEMBL::SeqFeature();
    my $f2 = new Bio::EnsEMBL::SeqFeature();
    my $new_feature = Bio::EnsEMBL::FeaturePair->new(-feature1=>$f1,
						     -feature2=>$f2);
    $new_feature->start($mapped[0]->start);
    $new_feature->end($mapped[0]->end);
    $new_feature->strand($mapped[0]->strand);
    $new_feature->seqname($mapped[0]->id);
    $new_feature->score($feature->score);
    $new_feature->percent_id($feature->percent_id);
    $new_feature->p_value($feature->p_value);
    $new_feature->hstart($feature->hstart);
    $new_feature->hend($feature->hend);
    $new_feature->hstrand($feature->hstrand);
    $new_feature->hseqname($feature->hseqname);
971
    #$new_feature->hscore($feature->score);
Laura Clarke's avatar
 
Laura Clarke committed
972 973 974 975 976 977
    $new_feature->analysis($feature->analysis);
    $new_feature->attach_seq($rawContig);

    push(@out, $new_feature);
  }

978 979 980 981
  foreach my $sf(@out){
    #print STDERR "gff ".$sf->gffstring."\n";
  }

Laura Clarke's avatar
 
Laura Clarke committed
982 983 984 985 986 987 988
  return @out;

}




989

990
1;