FAST/Bio/Search/HSP/GenericHSP.pm untested

filter: Statementstmt 0.0% 0 / 558 Branchbran 0.0% 0 / 336 Conditioncond 0.0% 0 / 184 MC/DCmcdc 0.0% 0 / 111 Subroutinesub 0.0% 0 / 50 Podpod 0.0% 0 / 43 totaltotal 0.0% 0 / 1282 CC 169 SCAR 48.7
CC
169
Cov
0%
_calculate_seq_positions
650.0
seq_inds
240.0
_query_seq_feature
156.0
CRAP 130.2
1 #
2 # BioPerl module for FAST::Bio::Search::HSP::GenericHSP
3 #
4 # Please direct questions and support issues to <bioperl-l@bioperl.org>
5 #
6 # Cared for by Jason Stajich <jason@bioperl.org>
7 #
8 # Copyright Jason Stajich
9 #
10 # You may distribute this module under the same terms as perl itself
11  
12 # POD documentation - main docs before the code
13  
14 =head1 NAME
15  
16 FAST::Bio::Search::HSP::GenericHSP - A "Generic" implementation of a High Scoring Pair
17  
18 =head1 SYNOPSIS
19  
20 my $hsp = FAST::Bio::Search::HSP::GenericHSP->new( -algorithm => 'blastp',
21 -evalue => '1e-30',
22 );
23  
24 $r_type = $hsp->algorithm;
25  
26 $pvalue = $hsp->p();
27  
28 $evalue = $hsp->evalue();
29  
30 $frac_id = $hsp->frac_identical( ['query'|'hit'|'total'] );
31  
32 $frac_cons = $hsp->frac_conserved( ['query'|'hit'|'total'] );
33  
34 $gaps = $hsp->gaps( ['query'|'hit'|'total'] );
35  
36 $qseq = $hsp->query_string;
37  
38 $hseq = $hsp->hit_string;
39  
40 $homo_string = $hsp->homology_string;
41  
42 $len = $hsp->length( ['query'|'hit'|'total'] );
43  
44 $len = $hsp->length( ['query'|'hit'|'total'] );
45  
46 $rank = $hsp->rank;
47  
48 # TODO: Describe how to configure a SearchIO stream so that it generates
49 # GenericHSP objects.
50  
51 =head1 DESCRIPTION
52  
53 This implementation is "Generic", meaning it is is suitable for
54 holding information about High Scoring pairs from most Search reports
55 such as BLAST and FastA. Specialized objects can be derived from
56 this.
57  
58 Unless you're writing a parser, you won't ever need to create a
59 GenericHSP or any other HSPI-implementing object. If you use
60 the SearchIO system, HSPI objects are created automatically from
61 a SearchIO stream which returns FAST::Bio::Search::Result::ResultI objects
62 and you get the HSPI objects via the ResultI API.
63  
64 For documentation on what you can do with GenericHSP (and other HSPI
65 objects), please see the API documentation in
66 L<FAST::Bio::Search::HSP::HSPI|FAST::Bio::Search::HSP::HSPI>.
67  
68 =head1 FEEDBACK
69  
70 =head2 Mailing Lists
71  
72 User feedback is an integral part of the evolution of this and other
73 Bioperl modules. Send your comments and suggestions preferably to
74 the Bioperl mailing list. Your participation is much appreciated.
75  
76 bioperl-l@bioperl.org - General discussion
77 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
78  
79 =head2 Support
80  
81 Please direct usage questions or support issues to the mailing list:
82  
83 I<bioperl-l@bioperl.org>
84  
85 rather than to the module maintainer directly. Many experienced and
86 reponsive experts will be able look at the problem and quickly
87 address it. Please include a thorough description of the problem
88 with code and data examples if at all possible.
89  
90 =head2 Reporting Bugs
91  
92 Report bugs to the Bioperl bug tracking system to help us keep track
93 of the bugs and their resolution. Bug reports can be submitted via the
94 web:
95  
96 https://redmine.open-bio.org/projects/bioperl/
97  
98 =head1 AUTHOR - Jason Stajich and Steve Chervitz
99  
100 Email jason-at-bioperl.org
101 Email sac-at-bioperl.org
102  
103 =head1 CONTRIBUTORS
104  
105 Sendu Bala, bix@sendu.me.uk
106  
107 =head1 APPENDIX
108  
109 The rest of the documentation details each of the object methods.
110 Internal methods are usually preceded with a _
111  
112 =cut
113  
114 # Let the code begin...
115  
116 package FAST::Bio::Search::HSP::GenericHSP;
117 use strict;
118  
119 use FAST::Bio::Root::Root;
120 use FAST::Bio::SeqFeature::Similarity;
121  
122 use base qw(FAST::Bio::Search::HSP::HSPI);
123  
124 =head2 new
125  
126 Title : new
127 Usage : my $obj = FAST::Bio::Search::HSP::GenericHSP->new();
128 Function: Builds a new FAST::Bio::Search::HSP::GenericHSP object
129 Returns : FAST::Bio::Search::HSP::GenericHSP
130 Args : -algorithm => algorithm used (BLASTP, TBLASTX, FASTX, etc)
131 -evalue => evalue
132 -pvalue => pvalue
133 -bits => bit value for HSP
134 -score => score value for HSP (typically z-score but depends on
135 analysis)
136 -hsp_length=> Length of the HSP (including gaps)
137 -identical => # of residues that that matched identically
138 -percent_identity => (optional) percent identity
139 -conserved => # of residues that matched conservatively
140 (only protein comparisions;
141 conserved == identical in nucleotide comparisons)
142 -hsp_gaps => # of gaps in the HSP
143 -query_gaps => # of gaps in the query in the alignment
144 -hit_gaps => # of gaps in the subject in the alignment
145 -query_name => HSP Query sequence name (if available)
146 -query_start => HSP Query start (in original query sequence coords)
147 -query_end => HSP Query end (in original query sequence coords)
148 -query_length=> total length of the query sequence
149 -query_seq => query sequence portion of the HSP
150 -query_desc => textual description of the query
151 -hit_name => HSP Hit sequence name (if available)
152 -hit_start => HSP Hit start (in original hit sequence coords)
153 -hit_end => HSP Hit end (in original hit sequence coords)
154 -hit_length => total length of the hit sequence
155 -hit_seq => hit sequence portion of the HSP
156 -hit_desc => textual description of the hit
157 -homology_seq=> homology sequence for the HSP
158 -hit_frame => hit frame (only if hit is translated protein)
159 -query_frame => query frame (only if query is translated protein)
160 -rank => HSP rank
161 -links => HSP links information (WU-BLAST only)
162 -hsp_group => HSP Group informat (WU-BLAST only)
163 -gap_symbol => symbol representing a gap (default = '-')
164 -hit_features=> string of features found in or near HSP hit
165 region (reported in some BLAST text output,
166 v. 2.2.13 and up)
167 -stranded => If the algorithm isn't known (i.e. defaults to
168 'generic'), setting this will indicate start/end
169 coordinates are to be used to determine the strand
170 for 'query', 'subject', 'hit', 'both', or 'none'
171 (default = 'none')
172  
173 =cut
174  
175 sub new {
176 my($class,%args) = @_;
177  
178 # don't pass anything to SUPER; complex hierarchy results in lots of work
179 # for nothing
180
181 my $self = $class->SUPER::new();
182  
183 # for speed, don't use _rearrange and just store all input data directly
184 # with no method calls and no work done. work can be carried
185 # out just-in-time later if desired
186 while (my ($arg, $value) = each %args) {
187 $arg =~ tr/a-z\055/A-Z/d;
188 $self->{$arg} = $value;
189 }
190 my $bits = $self->{BITS};
191  
192 defined $self->{VERBOSE} && $self->verbose($self->{VERBOSE});
193 if (exists $self->{GAP_SYMBOL}) {
194 # not checking anything else but the length (must be 1 as only one gap
195 # symbol allowed currently); can add in support for symbol checks or
196 # multiple symbols later if needed
197 $self->throw("Gap symbol must be of length 1") if
198 CORE::length($self->{GAP_SYMBOL}) != 1;
199 } else {
200 # dafault
201 $self->{GAP_SYMBOL} = '-';
202 }
203 $self->{ALGORITHM} ||= 'GENERIC';
204 $self->{STRANDED} ||= 'NONE';
205
206 if (! defined $self->{QUERY_LENGTH} || ! defined $self->{HIT_LENGTH}) {
207 $self->throw("Must define hit and query length");
208 }
209  
210 $self->{'_sequenceschanged'} = 1;
211
212 $self->{_finished_new} = 1;
213 return $self;
214 }
215  
216 sub _logical_length {
217 my ($self, $type) = @_;
218 if (!defined($self->{_sbjct_offset}) || !defined($self->{_query_offset})) {
219 $self->_calculate_seq_offsets();
220 }
221 my $key = $type =~ /sbjct|hit|tot/i ? 'sbjct' : 'query';
222
223 my $offset = $self->{"_${key}_offset"};
224 return $self->length($type) / $offset ;
225 }
226  
227 =head2 L<FAST::Bio::Search::HSP::HSPI> methods
228  
229 Implementation of L<FAST::Bio::Search::HSP::HSPI> methods follow
230  
231 =head2 algorithm
232  
233 Title : algorithm
234 Usage : my $r_type = $hsp->algorithm
235 Function: Obtain the name of the algorithm used to obtain the HSP
236 Returns : string (e.g., BLASTP)
237 Args : [optional] scalar string to set value
238  
239 =cut
240  
241 sub algorithm{
242 my ($self,$value) = @_;
243 my $previous = $self->{'ALGORITHM'};
244 if( defined $value || ! defined $previous ) {
245 $value = $previous = '' unless defined $value;
246 $self->{'ALGORITHM'} = $value;
247 }
248  
249 return $previous;
250 }
251  
252 =head2 pvalue
253  
254 Title : pvalue
255 Usage : my $pvalue = $hsp->pvalue();
256 Function: Returns the P-value for this HSP or undef
257 Returns : float or exponential (2e-10)
258 P-value is not defined with NCBI Blast2 reports.
259 Args : [optional] numeric to set value
260  
261 =cut
262  
263 sub pvalue {
264 my ($self,$value) = @_;
265 my $previous = $self->{'PVALUE'};
266 if( defined $value ) {
267 $self->{'PVALUE'} = $value;
268 }
269 return $previous;
270 }
271  
272 =head2 evalue
273  
274 Title : evalue
275 Usage : my $evalue = $hsp->evalue();
276 Function: Returns the e-value for this HSP
277 Returns : float or exponential (2e-10)
278 Args : [optional] numeric to set value
279  
280 =cut
281  
282 sub evalue {
283 my ($self,$value) = @_;
284 my $previous = $self->{'EVALUE'};
285 if( defined $value ) {
286 $self->{'EVALUE'} = $value;
287 }
288 return $previous;
289 }
290  
291 =head2 frac_identical
292  
293 Title : frac_identical
294 Usage : my $frac_id = $hsp->frac_identical( ['query'|'hit'|'total'] );
295 Function: Returns the fraction of identitical positions for this HSP
296 Returns : Float in range 0.0 -> 1.0
297 Args : arg 1: 'query' = num identical / length of query seq (without gaps)
298 'hit' = num identical / length of hit seq (without gaps)
299 synonyms: 'sbjct', 'subject'
300 'total' = num identical / length of alignment (with gaps)
301 synonyms: 'hsp'
302 default = 'total'
303 arg 2: [optional] frac identical value to set for the type requested
304 Note : for translated sequences, this adjusts the length accordingly
305  
306 =cut
307  
308 sub frac_identical {
309 my ($self, $type,$value) = @_;
310  
311 unless ($self->{_did_prefrac}) {
312 $self->_pre_frac;
313 }
314  
315 $type = lc $type if defined $type;
316 $type = 'hit' if( defined $type &&
317 $type =~ /subject|sbjct/);
318 $type = 'total' if( ! defined $type || $type eq 'hsp' ||
319 $type !~ /query|hit|subject|sbjct|total/);
320 my $previous = $self->{'_frac_identical'}->{$type};
321 if( defined $value || ! defined $previous ) {
322 $value = $previous = '' unless defined $value;
323 if( $type eq 'hit' || $type eq 'query' ) {
324 $self->$type()->frac_identical( $value);
325 }
326 $self->{'_frac_identical'}->{$type} = $value;
327 }
328 return $previous;
329  
330 }
331  
332 =head2 frac_conserved
333  
334 Title : frac_conserved
335 Usage : my $frac_cons = $hsp->frac_conserved( ['query'|'hit'|'total'] );
336 Function : Returns the fraction of conserved positions for this HSP.
337 This is the fraction of symbols in the alignment with a
338 positive score.
339 Returns : Float in range 0.0 -> 1.0
340 Args : arg 1: 'query' = num conserved / length of query seq (without gaps)
341 'hit' = num conserved / length of hit seq (without gaps)
342 synonyms: 'sbjct', 'subject'
343 'total' = num conserved / length of alignment (with gaps)
344 synonyms: 'hsp'
345 default = 'total'
346 arg 2: [optional] frac conserved value to set for the type requested
347  
348 =cut
349  
350 sub frac_conserved {
351 my ($self, $type,$value) = @_;
352  
353 unless ($self->{_did_prefrac}) {
354 $self->_pre_frac;
355 }
356  
357 $type = lc $type if defined $type;
358 $type = 'hit' if( defined $type && $type =~ /subject|sbjct/);
359 $type = 'total' if( ! defined $type || $type eq 'hsp' ||
360 $type !~ /query|hit|subject|sbjct|total/);
361 my $previous = $self->{'_frac_conserved'}->{$type};
362 if( defined $value || ! defined $previous ) {
363 $value = $previous = '' unless defined $value;
364 $self->{'_frac_conserved'}->{$type} = $value;
365 }
366 return $previous;
367 }
368  
369 =head2 gaps
370  
371 Title : gaps
372 Usage : my $gaps = $hsp->gaps( ['query'|'hit'|'total'] );
373 Function : Get the number of gap characters in the query, hit, or total alignment.
374 Returns : Integer, number of gaps or 0 if none
375 Args : arg 1: 'query' = num gap characters in query seq
376 'hit' = num gap characters in hit seq; synonyms: 'sbjct', 'subject'
377 'total' = num gap characters in whole alignment; synonyms: 'hsp'
378 default = 'total'
379 arg 2: [optional] integer gap value to set for the type requested
380  
381 =cut
382  
383 sub gaps {
384 my ($self, $type, $value) = @_;
385  
386 unless ($self->{_did_pregaps}) {
387 $self->_pre_gaps;
388 }
389  
390 $type = lc $type if defined $type;
391 $type = 'total' if( ! defined $type || $type eq 'hsp' ||
392 $type !~ /query|hit|subject|sbjct|total/);
393 $type = 'hit' if $type =~ /sbjct|subject/;
394 my $previous = $self->{'_gaps'}->{$type};
395 if( defined $value || ! defined $previous ) {
396 $value = $previous = '' unless defined $value;
397 $self->{'_gaps'}->{$type} = $value;
398 }
399 return $previous || 0;
400 }
401  
402 =head2 query_string
403  
404 Title : query_string
405 Usage : my $qseq = $hsp->query_string;
406 Function: Retrieves the query sequence of this HSP as a string
407 Returns : string
408 Args : [optional] string to set for query sequence
409  
410  
411 =cut
412  
413 sub query_string{
414 my ($self,$value) = @_;
415 my $previous = $self->{QUERY_SEQ};
416 if( defined $value || ! defined $previous ) {
417 $value = $previous = '' unless defined $value;
418 $self->{QUERY_SEQ} = $value;
419 # do some housekeeping so we know when to
420 # re-run _calculate_seq_positions
421 $self->{'_sequenceschanged'} = 1;
422 }
423 return $previous;
424 }
425  
426 =head2 hit_string
427  
428 Title : hit_string
429 Usage : my $hseq = $hsp->hit_string;
430 Function: Retrieves the hit sequence of this HSP as a string
431 Returns : string
432 Args : [optional] string to set for hit sequence
433  
434  
435 =cut
436  
437 sub hit_string{
438 my ($self,$value) = @_;
439 my $previous = $self->{HIT_SEQ};
440 if( defined $value || ! defined $previous ) {
441 $value = $previous = '' unless defined $value;
442 $self->{HIT_SEQ} = $value;
443 # do some housekeeping so we know when to
444 # re-run _calculate_seq_positions
445 $self->{'_sequenceschanged'} = 1;
446 }
447 return $previous;
448 }
449  
450 =head2 homology_string
451  
452 Title : homology_string
453 Usage : my $homo_string = $hsp->homology_string;
454 Function: Retrieves the homology sequence for this HSP as a string.
455 : The homology sequence is the string of symbols in between the
456 : query and hit sequences in the alignment indicating the degree
457 : of conservation (e.g., identical, similar, not similar).
458 Returns : string
459 Args : [optional] string to set for homology sequence
460  
461 =cut
462  
463 sub homology_string{
464 my ($self,$value) = @_;
465 my $previous = $self->{HOMOLOGY_SEQ};
466 if( defined $value || ! defined $previous ) {
467 $value = $previous = '' unless defined $value;
468 $self->{HOMOLOGY_SEQ} = $value;
469 # do some housekeeping so we know when to
470 # re-run _calculate_seq_positions
471 $self->{'_sequenceschanged'} = 1;
472 }
473 return $previous;
474 }
475  
476 =head2 length
477  
478 Title : length
479 Usage : my $len = $hsp->length( ['query'|'hit'|'total'] );
480 Function : Returns the length of the query or hit in the alignment
481 (without gaps)
482 or the aggregate length of the HSP (including gaps;
483 this may be greater than either hit or query )
484 Returns : integer
485 Args : arg 1: 'query' = length of query seq (without gaps)
486 'hit' = length of hit seq (without gaps) (synonyms: sbjct, subject)
487 'total' = length of alignment (with gaps)
488 default = 'total'
489 arg 2: [optional] integer length value to set for specific type
490  
491 =cut
492  
493 sub length {
494  
495 my $self = shift;
496 my $type = shift;
497  
498 $type = 'total' unless defined $type;
499 $type = lc $type;
500  
501 if( $type =~ /^q/i ) {
502 return $self->query()->length(shift);
503 } elsif( $type =~ /^(hit|subject|sbjct)/ ) {
504 return $self->hit()->length(shift);
505 } else {
506 my $v = shift;
507 if( defined $v ) {
508 $self->{HSP_LENGTH} = $v;
509 }
510 return $self->{HSP_LENGTH};
511 }
512 return 0; # should never get here
513 }
514  
515 =head2 hsp_length
516  
517 Title : hsp_length
518 Usage : my $len = $hsp->hsp_length()
519 Function: shortcut length('hsp')
520 Returns : floating point between 0 and 100
521 Args : none
522  
523 =cut
524  
525 sub hsp_length { return shift->length('hsp', shift); }
526  
527 =head2 percent_identity
528  
529 Title : percent_identity
530 Usage : my $percentid = $hsp->percent_identity()
531 Function: Returns the calculated percent identity for an HSP
532 Returns : floating point between 0 and 100
533 Args : none
534  
535  
536 =cut
537  
538 sub percent_identity {
539 my $self = shift;
540  
541 unless ($self->{_did_prepi}) {
542 $self->_pre_pi;
543 }
544  
545 return $self->SUPER::percent_identity(@_);
546 }
547  
548 =head2 frame
549  
550 Title : frame
551 Usage : my ($qframe, $hframe) = $hsp->frame('list',$queryframe,$subjectframe)
552 Function: Set the Frame for both query and subject and insure that
553 they agree.
554 This overrides the frame() method implementation in
555 FeaturePair.
556 Returns : array of query and subject frame if return type wants an array
557 or query frame if defined or subject frame if not defined
558 Args : 'hit' or 'subject' or 'sbjct' to retrieve the frame of the subject (default)
559 'query' to retrieve the query frame
560 'list' or 'array' to retrieve both query and hit frames together
561 Note : Frames are stored in the GFF way (0-2) not 1-3
562 as they are in BLAST (negative frames are deduced by checking
563 the strand of the query or hit)
564  
565 =cut
566  
567 # Note: changed 4/19/08 - bug 2485
568 #
569 # frame() is supposed to be a getter/setter (as is implied by the Function desc
570 # above; this is also consistent with FAST::Bio::SeqFeature::SimilarityPair). Also,
571 # the API is not consistent with the other HSP/SimilarityPair methods such as
572 # strand(), start(), end(), etc.
573 #
574 # In order to make this consistent with other methods all work is now done
575 # when the features are instantiated and not delayed. We compromise by
576 # defaulting back 'to hit' w/o passed args. Setting is now allowed.
577  
578 sub frame {
579 my $self = shift;
580 my $val = shift;
581 if (!defined $val) {
582 # unfortunately, w/o args we need to warn about API changes
583 $self->warn("API for frame() has changed.\n".
584 "Please refer to documentation for FAST::Bio::Search::HSP::GenericHSP;\n".
585 "returning query frame");
586 $val = 'query';
587 }
588 $val =~ s/^\s+//;
589  
590 if( $val =~ /^q/i ) {
591 return $self->query->frame(@_);
592 } elsif( $val =~ /^hi|^s/i ) {
593 return $self->hit->frame(@_);
594 } elsif ( $val =~ /^list|array/i ) {
595 return ($self->query->frame($_[0]),
596 $self->hit->frame($_[1]) );
597 } elsif ( $val =~ /^\d+$/) {
598 # old API i.e. frame($query_frame, $hit_frame). This catches all but one
599 # case, where no arg is passed (so the hit is wanted).
600 $self->warn("API for frame() has changed.\n".
601 "Please refer to documentation for FAST::Bio::Search::HSP::GenericHSP");
602 wantarray ?
603 return ($self->query->frame($val),
604 $self->hit->frame(@_) ) :
605 return $self->hit->frame($val,@_);
606 } else {
607 $self->warn("unrecognized component '$val' requested\n");
608 }
609 return 0;
610 }
611  
612 =head2 get_aln
613  
614 Title : get_aln
615 Usage : my $aln = $hsp->gel_aln
616 Function: Returns a L<FAST::Bio::SimpleAlign> object representing the HSP alignment
617 Returns : L<FAST::Bio::SimpleAlign>
618 Args : none
619  
620 =cut
621  
622 sub get_aln {
623 my ($self) = @_;
624 require FAST::Bio::LocatableSeq;
625 require FAST::Bio::SimpleAlign;
626 my $aln = FAST::Bio::SimpleAlign->new();
627 my $hs = $self->hit_string();
628 my $qs = $self->query_string();
629 # FASTA specific stuff moved to the FastaHSP object
630 my $seqonly = $qs;
631 $seqonly =~ s/[\-\s]//g;
632 my ($q_nm,$s_nm) = ($self->query->seq_id(),
633 $self->hit->seq_id());
634 # Should we silently change the name of the query or hit if it isn't
635 # defined? May need revisiting... cjfields 2008-12-3 (commented out below)
636
637 #unless( defined $q_nm && CORE::length ($q_nm) ) {
638 # $q_nm = 'query';
639 #}
640 #unless( defined $s_nm && CORE::length ($s_nm) ) {
641 # $s_nm = 'hit';
642 #}
643
644 # mapping: 1 residues for every x coordinate positions
645 my $query = FAST::Bio::LocatableSeq->new('-seq' => $qs,
646 '-id' => $q_nm,
647 '-start' => $self->query->start,
648 '-end' => $self->query->end,
649 '-strand' => $self->query->strand,
650 '-force_nse' => $q_nm ? 0 : 1,
651 '-mapping' => [1, $self->{_query_mapping}]
652 );
653 $seqonly = $hs;
654 $seqonly =~ s/[\-\s]//g;
655 my $hit = FAST::Bio::LocatableSeq->new('-seq' => $hs,
656 '-id' => $s_nm,
657 '-start' => $self->hit->start,
658 '-end' => $self->hit->end,
659 '-strand' => $self->hit->strand,
660 '-force_nse' => $s_nm ? 0 : 1,
661 '-mapping' => [1, $self->{_hit_mapping}]
662 );
663 $aln->add_seq($query);
664 $aln->add_seq($hit);
665 return $aln;
666 }
667  
668 =head2 num_conserved
669  
670 Title : num_conserved
671 Usage : $obj->num_conserved($newval)
672 Function: returns the number of conserved residues in the alignment
673 Returns : integer
674 Args : integer (optional)
675  
676  
677 =cut
678  
679 sub num_conserved{
680 my ($self,$value) = @_;
681  
682 unless ($self->{_did_presimilar}) {
683 $self->_pre_similar_stats;
684 }
685  
686 if (defined $value) {
687 $self->{CONSERVED} = $value;
688 }
689 return $self->{CONSERVED};
690 }
691  
692 =head2 num_identical
693  
694 Title : num_identical
695 Usage : $obj->num_identical($newval)
696 Function: returns the number of identical residues in the alignment
697 Returns : integer
698 Args : integer (optional)
699  
700  
701 =cut
702  
703 sub num_identical{
704 my ($self,$value) = @_;
705  
706 unless ($self->{_did_presimilar}) {
707 $self->_pre_similar_stats;
708 }
709  
710 if( defined $value) {
711 $self->{IDENTICAL} = $value;
712 }
713 return $self->{IDENTICAL};
714 }
715  
716 =head2 rank
717  
718 Usage : $hsp->rank( [string] );
719 Purpose : Get the rank of the HSP within a given Blast hit.
720 Example : $rank = $hsp->rank;
721 Returns : Integer (1..n) corresponding to the order in which the HSP
722 appears in the BLAST report.
723  
724 =cut
725  
726 sub rank {
727 my ($self,$value) = @_;
728 if( defined $value) {
729 $self->{RANK} = $value;
730 }
731 return $self->{RANK};
732 }
733  
734 =head2 seq_inds
735  
736 Title : seq_inds
737 Purpose : Get a list of residue positions (indices) for all identical
738 : or conserved residues in the query or sbjct sequence.
739 Example : @s_ind = $hsp->seq_inds('query', 'identical');
740 : @h_ind = $hsp->seq_inds('hit', 'conserved');
741 : @h_ind = $hsp->seq_inds('hit', 'conserved-not-identical');
742 : @h_ind = $hsp->seq_inds('hit', 'conserved', 1);
743 Returns : List of integers
744 : May include ranges if collapse is true.
745 Argument : seq_type = 'query' or 'hit' or 'sbjct' (default = query)
746 : ('sbjct' is synonymous with 'hit')
747 : class = 'identical' - identical positions
748 : 'conserved' - conserved positions
749 : 'nomatch' - mismatched residue or gap positions
750 : 'mismatch' - mismatched residue positions (no gaps)
751 : 'gap' - gap positions only
752 : 'frameshift'- frameshift positions only
753 : 'conserved-not-identical' - conserved positions w/o
754 : identical residues
755 : The name can be shortened to 'id' or 'cons' unless
756 : the name is . The default value is
757 : 'identical'
758 :
759 : collapse = boolean, if true, consecutive positions are merged
760 : using a range notation, e.g., "1 2 3 4 5 7 9 10 11"
761 : collapses to "1-5 7 9-11". This is useful for
762 : consolidating long lists. Default = no collapse.
763 :
764 Throws : n/a.
765 Comments : For HSPs partially or completely derived from translated sequences
766 : (TBLASTN, BLASTX, TBLASTX, or similar), some positional data
767 : cannot easily be attributed to a single position (i.e. the
768 : positional data is ambiguous). In these cases all three codon
769 : positions are reported. Under these conditions you can check
770 : ambiguous_seq_inds() to determine whether the query, subject,
771 : or both are ambiguous.
772 :
773 See Also : L<FAST::Bio::Search::SearchUtils::collapse_nums()|FAST::Bio::Search::SearchUtils>,
774 L<FAST::Bio::Search::Hit::HitI::seq_inds()|FAST::Bio::Search::Hit::HitI>
775  
776 =cut
777  
778 sub seq_inds{
779 my ($self, $seqType, $class, $collapse) = @_;
780  
781 # prepare the internal structures - this is cached so
782 # if the strings have not changed we're okay
783 $self->_calculate_seq_positions();
784  
785 $seqType ||= 'query';
786 $class ||= 'identical';
787 $collapse ||= 0;
788 $seqType = 'sbjct' if $seqType eq 'hit';
789 my $t = lc(substr($seqType,0,1));
790 if( $t eq 'q' ) {
791 $seqType = 'query';
792 } elsif ( $t eq 's' || $t eq 'h' ) {
793 $seqType = 'sbjct';
794 } else {
795 $self->warn("unknown seqtype $seqType using 'query'");
796 $seqType = 'query';
797 }
798
799 $t = lc(substr($class,0,1));
800  
801 if( $t eq 'c' ) {
802 if( $class =~ /conserved\-not\-identical/ ) {
803 $class = 'conserved';
804 } else {
805 $class = 'conservedall';
806 }
807 } elsif( $t eq 'i' ) {
808 $class = 'identical';
809 } elsif( $t eq 'n' ) {
810 $class = 'nomatch';
811 } elsif( $t eq 'm' ) {
812 $class = 'mismatch';
813 } elsif( $t eq 'g' ) {
814 $class = 'gap';
815 } elsif( $t eq 'f' ) {
816 $class = 'frameshift';
817 } else {
818 $self->warn("unknown sequence class $class using 'identical'");
819 $class = 'identical';
820 }
821  
822 ## Sensitive to member name changes.
823 $seqType = "_\L$seqType\E";
824 $class = "_\L$class\E";
825 my @ary;
826  
827 if( $class eq '_gap' ) {
828 # this means that we are remapping the gap length that is stored
829 # in the hash (for example $self->{'_gapRes_query'} )
830 # so we'll return an array which has the values of the position of the
831 # of the gap (the key in the hash) + the gap length (value in the
832 # hash for this key - 1.
833
834 # changing this; since the index is the position prior to the insertion,
835 # repeat the position based on the number of gaps inserted
836 @ary = map { my @tmp;
837 # position holds number of gaps inserted
838 for my $g (1..$self->{seqinds}{"${class}Res$seqType"}->{$_}) {
839 push @tmp, $_ ;
840 }
841 @tmp}
842 sort { $a <=> $b } keys %{ $self->{seqinds}{"${class}Res$seqType"}};
843 } elsif( $class eq '_conservedall' ) {
844 @ary = sort { $a <=> $b }
845 keys %{ $self->{seqinds}{"_conservedRes$seqType"}},
846 keys %{ $self->{seqinds}{"_identicalRes$seqType"}},
847 } else {
848 @ary = sort { $a <=> $b } keys %{ $self->{seqinds}{"${class}Res$seqType"}};
849 }
850 require FAST::Bio::Search::BlastUtils if $collapse;
851  
852 return $collapse ? &FAST::Bio::Search::SearchUtils::collapse_nums(@ary) : @ary;
853 }
854  
855 =head2 ambiguous_seq_inds
856  
857 Title : ambiguous_seq_inds
858 Purpose : returns a string denoting whether sequence indices for query,
859 : subject, or both are ambiguous
860 Returns : String; 'query', 'subject', 'query/subject', or empty string ''
861 Argument : none
862 Comments : For HSPs partially or completely derived from translated sequences
863 : (TBLASTN, BLASTX, TBLASTX, or similar), some positional data
864 : cannot easily be attributed to a single position (i.e. the
865 : positional data is ambiguous). In these cases all three codon
866 : positions are reported when using seq_inds(). Under these
867 : conditions you can check ambiguous_seq_inds() to determine whether
868 : the query, subject, or both are ambiguous.
869 See Also : L<FAST::Bio::Search::Hit::HSPI::seq_inds()>
870  
871 =cut
872  
873 sub ambiguous_seq_inds {
874 my $self = shift;
875 $self->_calculate_seq_positions();
876 my $type = ($self->{_query_offset} == 3 && $self->{_sbjct_offset} == 3) ?
877 'query/subject' :
878 ($self->{_query_offset} == 3) ? 'query' :
879 ($self->{_sbjct_offset} == 3) ? 'subject' : '';
880 return $type;
881 }
882  
883 =head2 Inherited from L<FAST::Bio::SeqFeature::SimilarityPair>
884  
885 These methods come from L<FAST::Bio::SeqFeature::SimilarityPair>
886  
887 =head2 query
888  
889 Title : query
890 Usage : my $query = $hsp->query
891 Function: Returns a SeqFeature representing the query in the HSP
892 Returns : L<FAST::Bio::SeqFeature::Similarity>
893 Args : [optional] new value to set
894  
895 =cut
896  
897 sub query {
898 my $self = shift;
899 unless ($self->{_created_qff}) {
900 $self->_query_seq_feature;
901 }
902 return $self->SUPER::query(@_);
903 }
904  
905 sub feature1 {
906 my $self = shift;
907 if (! $self->{_finished_new} || $self->{_making_qff}) {
908 return $self->{_sim1} if $self->{_sim1};
909 $self->{_sim1} = FAST::Bio::SeqFeature::Similarity->new();
910 return $self->{_sim1};
911 }
912 unless ($self->{_created_qff}) {
913 $self->_query_seq_feature;
914 }
915 return $self->SUPER::feature1(@_);
916 }
917  
918 =head2 hit
919  
920 Title : hit
921 Usage : my $hit = $hsp->hit
922 Function: Returns a SeqFeature representing the hit in the HSP
923 Returns : L<FAST::Bio::SeqFeature::Similarity>
924 Args : [optional] new value to set
925  
926 =cut
927  
928 sub hit {
929 my $self = shift;
930 unless ($self->{_created_sff}) {
931 $self->_subject_seq_feature;
932 }
933 return $self->SUPER::hit(@_);
934 }
935  
936 sub feature2 {
937 my $self = shift;
938 if (! $self->{_finished_new} || $self->{_making_sff}) {
939 return $self->{_sim2} if $self->{_sim2};
940 $self->{_sim2} = FAST::Bio::SeqFeature::Similarity->new();
941 return $self->{_sim2};
942 }
943 unless ($self->{_created_sff}) {
944 $self->_subject_seq_feature;
945 }
946 return $self->SUPER::feature2(@_);
947 }
948  
949 =head2 significance
950  
951 Title : significance
952 Usage : $evalue = $obj->significance();
953 $obj->significance($evalue);
954 Function: Get/Set the significance value
955 Returns : numeric
956 Args : [optional] new value to set
957  
958 =cut
959  
960 # Override significance to return the e-value or, if this is
961 # not defined (WU-BLAST), return the p-value.
962 sub significance {
963 my ($self, $val) = @_;
964 if (!defined $self->{SIGNIFICANCE} || defined $val) {
965 $self->{SIGNIFICANCE} = defined $val ? $val :
966 defined $self->evalue ? $self->evalue :
967 defined $self->pvalue ? $$self->pvalue :
968 undef;
969 $self->query->significance($self->{SIGNIFICANCE});
970 }
971 return $self->{SIGNIFICANCE};
972 }
973  
974 =head2 score
975  
976 Title : score
977 Usage : $score = $obj->score();
978 $obj->score($value);
979 Function: Get/Set the score value
980 Returns : numeric
981 Args : [optional] new value to set
982  
983  
984 =head2 bits
985  
986 Title : bits
987 Usage : $bits = $obj->bits();
988 $obj->bits($value);
989 Function: Get/Set the bits value
990 Returns : numeric
991 Args : [optional] new value to set
992  
993  
994 =head2 strand
995  
996 Title : strand
997 Usage : $hsp->strand('query')
998 Function: Retrieves the strand for the HSP component requested
999 Returns : +1 or -1 (0 if unknown)
1000 Args : 'hit' or 'subject' or 'sbjct' to retrieve the strand of the subject
1001 'query' to retrieve the query strand (default)
1002  
1003 =cut
1004  
1005 =head1 Private methods
1006  
1007 =cut
1008  
1009 =head2 _calculate_seq_positions
1010  
1011 Title : _calculate_seq_positions
1012 Usage : $self->_calculate_seq_positions
1013 Function: Internal function
1014 Returns :
1015 Args :
1016  
1017  
1018 =cut
1019  
1020 sub _calculate_seq_positions {
1021 my ($self,@args) = @_;
1022 return unless ( $self->{'_sequenceschanged'} );
1023 $self->{'_sequenceschanged'} = 0;
1024 my ($seqString, $qseq,$sseq) = ( $self->homology_string(),
1025 $self->query_string(),
1026 $self->hit_string() );
1027 my ($mlen, $qlen, $slen) = (CORE::length($seqString), CORE::length($qseq), CORE::length($sseq));
1028 my $qdir = $self->query->strand || 1;
1029 my $sdir = $self->hit->strand || 1;
1030 my ($resCount_query, $endpoint_query) = ($qdir <=0) ? ($self->query->end, $self->query->start)
1031 : ($self->query->start, $self->query->end);
1032 my ($resCount_sbjct, $endpoint_sbjct) = ($sdir <=0) ? ($self->hit->end, $self->hit->start)
1033 : ($self->hit->start, $self->hit->end);
1034
1035 my $prog = $self->algorithm;
1036
1037 if( $prog =~ /FAST|SSEARCH|SMITH-WATERMAN/i ) {
1038
1039 # we infer the end of the regional sequence where the first and last
1040 # non spaces are in the homology string
1041 # then we use the HSP->length to tell us how far to read
1042 # to cut off the end of the sequence
1043
1044 my ($start, $rest) = (0,0);
1045 if( $seqString =~ /^(\s+)?(.*?)\s*$/ ) {
1046 ($start, $rest) = ($1 ? CORE::length($1) : 0, CORE::length($2));
1047 }
1048
1049 $seqString = substr($seqString, $start, $rest);
1050 $qseq = substr($qseq, $start, $rest);
1051 $sseq = substr($sseq, $start, $rest);
1052  
1053 # commented out 10/29/08
1054 # removing frameshift symbols doesn't take into account the following:
1055 # 1) does not remove the same point in the homology string (get
1056 # positional errors)
1057 # 2) adjustments to the overall position in the string due to the
1058 # frameshift must be taken into consideration (get balancing errors)
1059 #
1060 # Frameshifts will be handled directly in the main loop.
1061 # --chris
1062
1063 # fasta reports some extra 'regional' sequence information
1064 # we need to clear out first
1065 # this seemed a bit insane to me at first, but it appears to
1066 # work --jason
1067
1068 #$qseq =~ s![\\\/]!!g;
1069 #$sseq =~ s![\\\/]!!g;
1070 }
1071  
1072 if (!defined($self->{_sbjct_offset}) || !defined($self->{_query_offset})) {
1073 $self->_calculate_seq_offsets();
1074 }
1075
1076 my ($qfs, $sfs) = (0,0);
1077 CHAR_LOOP:
1078 for my $pos (0..CORE::length($seqString)-1) {
1079 my @qrange = (0 - $qfs)..($self->{_query_offset} - 1);
1080 my @srange = (0 - $sfs)..($self->{_sbjct_offset} - 1);
1081 # $self->debug("QRange:@qrange SRange:@srange\n") if ($qfs || $sfs);
1082 ($qfs, $sfs) = (0,0);
1083 my ($mchar, $qchar, $schar) = (
1084 unpack("x$pos A1",$seqString) || ' ',
1085 $pos < CORE::length($qseq) ? unpack("x$pos A1",$qseq) : '-',
1086 $pos < CORE::length($sseq) ? unpack("x$pos A1",$sseq) : '-'
1087 );
1088 my $matchtype = '';
1089 my ($qgap, $sgap) = (0,0);
1090 if( $mchar eq '+' || $mchar eq '.') { # conserved
1091 $self->{seqinds}{_conservedRes_query}{ $resCount_query + ($_ * $qdir) } = 1 for @qrange;
1092 $self->{seqinds}{_conservedRes_sbjct}{ $resCount_sbjct + ($_ * $sdir) } = 1 for @srange;
1093 $matchtype = 'conserved';
1094 } elsif( $mchar eq ':' || $mchar ne ' ' ) { # identical
1095 $self->{seqinds}{_identicalRes_query}{ $resCount_query + ($_ * $qdir) } = 1 for @qrange;
1096 $self->{seqinds}{_identicalRes_sbjct}{ $resCount_sbjct + ($_ * $sdir) } = 1 for @srange;
1097 $matchtype = 'identical';
1098 } elsif( $mchar eq ' ' ) { # possible mismatch/nomatch/frameshift
1099 $qfs = $qchar eq '/' ? -1 : # base inserted to match frame
1100 $qchar eq '\\' ? 1 : # base deleted to match frame
1101 0;
1102 $sfs = $schar eq '/' ? -1 :
1103 $schar eq '\\' ? 1 :
1104 0;
1105 if ($qfs) {
1106 # Frameshifts are tricky.
1107
1108 # '/' indicates that the next residue is shifted back one
1109 # (-1) frame position and is a deletion of one base (so to
1110 # correctly align, a base is inserted). That residue should only
1111 # occupy two sequence positions instead of three.
1112
1113 # '\' indicates that the next residue is shifted forward
1114 # one (+1) frame position and is an insertion of one base (so to
1115 # correctly align, a base is removed). That residue should
1116 # occupy four sequence positions instead of three.
1117
1118 # Note that gaps are not counted across from frameshifts.
1119 # Frameshift indices are a range of positions starting in the
1120 # previous sequence position in which the frameshift occurs;
1121 # they are ambiguous by nature.
1122 $self->{seqinds}{_frameshiftRes_query}{ $resCount_query - ($_ * $qdir * $qfs) } = $qfs for @qrange;
1123 $matchtype = "$qfs frameshift-query";
1124 $sgap = $qgap = 1;
1125 }
1126 elsif ($sfs) {
1127 $self->{seqinds}{_frameshiftRes_sbjct}{ $resCount_sbjct - ($_ * $sdir * $sfs) } = $sfs for @srange;
1128 $matchtype = "$sfs frameshift-sbcjt";
1129 $sgap = $qgap = 1;
1130 }
1131 elsif ($qchar eq $self->{GAP_SYMBOL}) {
1132 # gap are counted as being in the immediately preceeding residue
1133 # position; for translated sequences this is not the start of
1134 # the previous codon, but the third codon position
1135 $self->{seqinds}{_gapRes_query}{ $resCount_query - $qdir }++ for @qrange;
1136 $matchtype = 'gap-query';
1137 $qgap++;
1138 }
1139 elsif ($schar eq $self->{GAP_SYMBOL}) {
1140 $self->{seqinds}{_gapRes_sbjct}{ $resCount_sbjct - $sdir }++ for @srange;
1141 $matchtype = 'gap-sbjct';
1142 $sgap++;
1143 }
1144 else {
1145 # if not a gap or frameshift in either seq, must be mismatch
1146 $self->{seqinds}{_mismatchRes_query}{ $resCount_query + ($_ * $qdir) } = 1 for @qrange;
1147 $self->{seqinds}{_mismatchRes_sbjct}{ $resCount_sbjct + ($_ * $sdir) } = 1 for @srange;
1148 $matchtype = 'mismatch';
1149 }
1150 # always add a nomatch unless the current position in the seq is a gap
1151 if (!$sgap) {
1152 $self->{seqinds}{_nomatchRes_sbjct}{ $resCount_sbjct + ($_ * $sdir) } = 1 for @srange;
1153 }
1154 if (!$qgap) {
1155 $self->{seqinds}{_nomatchRes_query}{ $resCount_query + ($_ * $qdir) } = 1 for @qrange;
1156 }
1157 } else {
1158 $self->warn("Unknown midline character: [$mchar]");
1159 }
1160 # leave in and uncomment for future debugging
1161 #$self->debug(sprintf("%7d %1s[%1s]%1s %-7d Type: %-20s QOff:%-2d SOff:%-2d\n",
1162 # $resCount_query,
1163 # $qchar,
1164 # $mchar,
1165 # $schar,
1166 # $resCount_sbjct,
1167 # $matchtype,
1168 # ($self->{_query_offset} * $qdir),
1169 # ($self->{_sbjct_offset} * $sdir)));
1170 $resCount_query += ($qdir * (scalar(@qrange) + $qfs)) if !$qgap;
1171 $resCount_sbjct += ($sdir * (scalar(@srange) + $sfs)) if !$sgap;
1172 }
1173 return 1;
1174 }
1175  
1176 sub _calculate_seq_offsets {
1177 my $self = shift;
1178 my $prog = $self->algorithm;
1179 ($self->{_sbjct_offset}, $self->{_query_offset}) = (1,1);
1180 if($prog =~ /^(?:PSI)?T(BLAST|FAST)(N|X|Y)/oi ) {
1181 $self->{_sbjct_offset} = 3;
1182 if ($1 eq 'BLAST' && $2 eq 'X') { #TBLASTX
1183 $self->{_query_offset} = 3;
1184 }
1185 } elsif($prog =~ /^(BLAST|FAST)(X|Y|XY)/oi ) {
1186 $self->{_query_offset} = 3;
1187 }
1188 1;
1189 }
1190  
1191 =head2 n
1192  
1193 See documentation in L<FAST::Bio::Search::HSP::HSPI::n()|FAST::Bio::Search::HSP::HSPI>
1194  
1195 =cut
1196  
1197 sub n {
1198 my $self = shift;
1199 if(@_) { $self->{'N'} = shift; }
1200 # note that returning 1 is completely an assumption
1201 defined $self->{'N'} ? $self->{'N'} : 1;
1202 }
1203  
1204 =head2 range
1205  
1206 See documentation in L<FAST::Bio::Search::HSP::HSPI::range()|FAST::Bio::Search::HSP::HSPI>
1207  
1208 =cut
1209  
1210 sub range {
1211 my ($self, $seqType) = @_;
1212  
1213 $seqType ||= 'query';
1214 $seqType = 'sbjct' if $seqType eq 'hit';
1215  
1216 my ($start, $end);
1217 if( $seqType eq 'query' ) {
1218 $start = $self->query->start;
1219 $end = $self->query->end;
1220 }
1221 else {
1222 $start = $self->hit->start;
1223 $end = $self->hit->end;
1224 }
1225 return ($start, $end);
1226 }
1227  
1228  
1229 =head2 links
1230  
1231 Title : links
1232 Usage : $obj->links($newval)
1233 Function: Get/Set the Links value (from WU-BLAST)
1234 Indicates the placement of the alignment in the group of HSPs
1235 Returns : Value of links
1236 Args : On set, new value (a scalar or undef, optional)
1237  
1238  
1239 =cut
1240  
1241 sub links{
1242 my $self = shift;
1243  
1244 return $self->{LINKS} = shift if @_;
1245 return $self->{LINKS};
1246 }
1247  
1248 =head2 hsp_group
1249  
1250 Title : hsp_group
1251 Usage : $obj->hsp_group($newval)
1252 Function: Get/Set the Group value (from WU-BLAST)
1253 Indicates a grouping of HSPs
1254 Returns : Value of group
1255 Args : On set, new value (a scalar or undef, optional)
1256  
1257  
1258 =cut
1259  
1260 sub hsp_group {
1261 my $self = shift;
1262  
1263 return $self->{HSP_GROUP} = shift if @_;
1264 return $self->{HSP_GROUP};
1265 }
1266  
1267 =head2 hit_features
1268  
1269 Title : hit_features
1270 Usage : $obj->hit_features($newval)
1271 Function: Get/Set the HSP hit feature string (from some BLAST 2.2.13 text
1272 output), which is a string of overlapping or nearby features in HSP
1273 hit
1274 Returns : Value of hit features, if present
1275 Args : On set, new value (a scalar or undef, optional)
1276  
1277  
1278 =cut
1279  
1280 sub hit_features {
1281 my $self = shift;
1282  
1283 return $self->{HIT_FEATURES} = shift if @_;
1284 return $self->{HIT_FEATURES};
1285 }
1286  
1287 # The cigar string code is written by Juguang Xiao <juguang@fugu-sg.org>
1288  
1289 =head1 Brief introduction on cigar string
1290  
1291 NOTE: the concept is originally from EnsEMBL docs at
1292 http://may2005.archive.ensembl.org/Docs/wiki/html/EnsemblDocs/CigarFormat.html
1293 Please append to these docs if you have a better definition.
1294  
1295 Sequence alignment hits can be stored in a database as ungapped alignments.
1296 This imposes 2 major constraints on alignments:
1297  
1298 a) alignments for a single hit record require multiple rows in the database,
1299 and
1300 b) it is not possible to accurately retrieve the exact original alignment.
1301  
1302 Alternatively, sequence alignments can be stored as gapped alignments using
1303 the CIGAR line format (where CIGAR stands for Concise Idiosyncratic Gapped
1304 Alignment Report).
1305  
1306 In the cigar line format alignments are stored as follows:
1307  
1308 M: Match
1309 D: Deletion
1310 I: Insertion
1311  
1312 An example of an alignment for a hypthetical protein match is shown below:
1313  
1314  
1315 Query: 42 PGPAGLP----GSVGLQGPRGLRGPLP-GPLGPPL...
1316  
1317 PG P G GP R PLGP
1318  
1319 Sbjct: 1672 PGTP*TPLVPLGPWVPLGPSSPR--LPSGPLGPTD...
1320  
1321  
1322 protein_align_feature table as the following cigar line:
1323  
1324 7M4D12M2I2MD7M
1325  
1326 =head2 cigar_string
1327  
1328 Name: cigar_string
1329 Usage: $cigar_string = $hsp->cigar_string
1330 Function: Generate and return cigar string for this HSP alignment
1331 Args: No input needed
1332 Return: a cigar string
1333  
1334 =cut
1335  
1336  
1337 sub cigar_string {
1338 my ($self, $arg) = @_;
1339 $self->warn("this is not a setter") if(defined $arg);
1340  
1341 unless(defined $self->{_cigar_string}){ # generate cigar string
1342 my $cigar_string = $self->generate_cigar_string($self->query_string, $self->hit_string);
1343 $self->{_cigar_string} = $cigar_string;
1344 } # end of unless
1345  
1346 return $self->{_cigar_string};
1347 }
1348  
1349 =head2 generate_cigar_string
1350  
1351 Name: generate_cigar_string
1352 Usage: my $cigar_string = FAST::Bio::Search::HSP::GenericHSP::generate_cigar_string ($qstr, $hstr);
1353 Function: generate cigar string from a simple sequence of alignment.
1354 Args: the string of query and subject
1355 Return: cigar string
1356  
1357 =cut
1358  
1359 sub generate_cigar_string {
1360 my ($self, $qstr, $hstr) = @_;
1361 my @qchars = split //, $qstr;
1362 my @hchars = split //, $hstr;
1363  
1364 unless(scalar(@qchars) == scalar(@hchars)){
1365 $self->throw("two sequences are not equal in lengths");
1366 }
1367  
1368 $self->{_count_for_cigar_string} = 0;
1369 $self->{_state_for_cigar_string} = 'M';
1370  
1371 my $cigar_string = '';
1372 for(my $i=0; $i <= $#qchars; $i++){
1373 my $qchar = $qchars[$i];
1374 my $hchar = $hchars[$i];
1375 if($qchar ne $self->{GAP_SYMBOL} && $hchar ne $self->{GAP_SYMBOL}){ # Match
1376 $cigar_string .= $self->_sub_cigar_string('M');
1377 }elsif($qchar eq $self->{GAP_SYMBOL}){ # Deletion
1378 $cigar_string .= $self->_sub_cigar_string('D');
1379 }elsif($hchar eq $self->{GAP_SYMBOL}){ # Insertion
1380 $cigar_string .= $self->_sub_cigar_string('I');
1381 }else{
1382 $self->throw("Impossible state that 2 gaps on each seq aligned");
1383 }
1384 }
1385 $cigar_string .= $self->_sub_cigar_string('X'); # not forget the tail.
1386 return $cigar_string;
1387 }
1388  
1389 # an internal method to help generate cigar string
1390  
1391 sub _sub_cigar_string {
1392 my ($self, $new_state) = @_;
1393  
1394 my $sub_cigar_string = '';
1395 if($self->{_state_for_cigar_string} eq $new_state){
1396 $self->{_count_for_cigar_string} += 1; # Remain the state and increase the counter
1397 }else{
1398 $sub_cigar_string .= $self->{_count_for_cigar_string}
1399 unless $self->{_count_for_cigar_string} == 1;
1400 $sub_cigar_string .= $self->{_state_for_cigar_string};
1401 $self->{_count_for_cigar_string} = 1;
1402 $self->{_state_for_cigar_string} = $new_state;
1403 }
1404 return $sub_cigar_string;
1405 }
1406  
1407 # needed before seqfeatures can be made
1408 sub _pre_seq_feature {
1409 my $self = shift;
1410 my $algo = $self->{ALGORITHM};
1411  
1412 my ($queryfactor, $hitfactor) = (0,0);
1413 my ($hitmap, $querymap) = (1,1);
1414 if( $algo =~ /^(?:PSI)?T(?:BLAST|FAST|SW)[NY]/oi ) {
1415 $hitfactor = 1;
1416 $hitmap = 3;
1417 }
1418 elsif ($algo =~ /^(?:FAST|BLAST)(?:X|Y|XY)/oi || $algo =~ /^P?GENEWISE/oi ) {
1419 $queryfactor = 1;
1420 $querymap = 3;
1421 }
1422 elsif ($algo =~ /^T(BLAST|FAST|SW)(X|Y|XY)/oi || $algo =~ /^(BLAST|FAST|SW)N/oi || $algo =~ /^WABA|AXT|BLAT|BLASTZ|PSL|MEGABLAST|EXONERATE|SW|SSEARCH|SMITH\-WATERMAN|SIM4$/){
1423 if ($2) {
1424 $hitmap = $querymap = 3;
1425 }
1426 $hitfactor = 1;
1427 $queryfactor = 1;
1428 }
1429 elsif ($algo =~ /^RPS-BLAST/) {
1430 if ($algo =~ /^RPS-BLAST\(BLASTX\)/) {
1431 $queryfactor = 1;
1432 $querymap = 3;
1433 }
1434 $hitfactor = 0;
1435 }
1436 else {
1437 my $stranded = lc substr($self->{STRANDED}, 0,1);
1438 $queryfactor = ($stranded eq 'q' || $stranded eq 'b') ? 1 : 0;
1439 $hitfactor = ($stranded eq 'h' || $stranded eq 's' || $stranded eq 'b') ? 1 : 0;
1440 }
1441 $self->{_query_factor} = $queryfactor;
1442 $self->{_hit_factor} = $hitfactor;
1443 $self->{_hit_mapping} = $hitmap;
1444 $self->{_query_mapping} = $querymap;
1445 }
1446  
1447 # make query seq feature
1448 sub _query_seq_feature {
1449 my $self = shift;
1450 $self->{_making_qff} = 1;
1451 my $qs = $self->{QUERY_START};
1452 my $qe = $self->{QUERY_END};
1453 unless (defined $self->{_query_factor}) {
1454 $self->_pre_seq_feature;
1455 }
1456 my $queryfactor = $self->{_query_factor};
1457  
1458 unless( defined $qe && defined $qs ) { $self->throw("Did not specify a Query End or Query Begin"); }
1459  
1460 my $strand;
1461 if ($qe > $qs) { # normal query: start < end
1462 if ($queryfactor) {
1463 $strand = 1;
1464 }
1465 else {
1466 $strand = undef;
1467 }
1468 }
1469 else {
1470 if ($queryfactor) {
1471 $strand = -1;
1472 }
1473 else {
1474 $strand = undef;
1475 }
1476 ($qs,$qe) = ($qe,$qs);
1477 }
1478  
1479 # Note: many of these data are not query- and hit-specific.
1480 # Only start, end, name, length are.
1481 # We could be more efficient by only storing this info once.
1482 # steve chervitz --- Sat Apr 5 00:55:07 2003
1483  
1484 my $sim1 = $self->{_sim1} || FAST::Bio::SeqFeature::Similarity->new();
1485 $sim1->start($qs);
1486 $sim1->end($qe);
1487 $sim1->significance($self->{EVALUE});
1488 $sim1->bits($self->{BITS});
1489 $sim1->score($self->{SCORE});
1490 $sim1->strand($strand);
1491 $sim1->seq_id($self->{QUERY_NAME});
1492 $sim1->seqlength($self->{QUERY_LENGTH});
1493 $sim1->source_tag($self->{ALGORITHM});
1494 $sim1->seqdesc($self->{QUERY_DESC});
1495 $sim1->add_tag_value('meta', $self->{META}) if $self->can('meta');
1496 # to determine frame from something like FASTXY which doesn't
1497 # report the frame
1498 my $qframe = $self->{QUERY_FRAME};
1499
1500 if (defined $strand && !defined $qframe && $queryfactor) {
1501 $qframe = ( $qs % 3 ) * $strand;
1502 }
1503 elsif (!defined $strand) {
1504 $qframe = 0;
1505 }
1506
1507 if( $qframe =~ /^([+-])?([0-3])/ ) {
1508 my $dir = $1 || '+';
1509 if($qframe && (($dir eq '-' && $strand >= 0) || ($dir eq '+' && $strand <= 0)) ) {
1510 $self->warn("Query frame ($qframe) did not match strand of query ($strand)");
1511 }
1512 $qframe = $2 != 0 ? $2 - 1 : $2;
1513 } else {
1514 $self->warn("Unknown query frame ($qframe)");
1515 $qframe = 0;
1516 }
1517
1518 $sim1->frame($qframe);
1519 $self->SUPER::feature1($sim1);
1520  
1521 $self->{_created_qff} = 1;
1522 $self->{_making_qff} = 0;
1523 }
1524  
1525 # make subject seq feature
1526 sub _subject_seq_feature {
1527 my $self = shift;
1528 $self->{_making_sff} = 1;
1529 my $hs = $self->{HIT_START};
1530 my $he = $self->{HIT_END};
1531 unless (defined $self->{_hit_factor}) {
1532 $self->_pre_seq_feature;
1533 }
1534 my $hitfactor = $self->{_hit_factor};
1535  
1536 unless( defined $he && defined $hs ) { $self->throw("Did not specify a Hit End or Hit Begin"); }
1537  
1538 my $strand;
1539 if ($he > $hs) { # normal subject
1540 if ($hitfactor) {
1541 $strand = 1;
1542 }
1543 else {
1544 $strand = undef;
1545 }
1546 }
1547 else {
1548 if ($hitfactor) {
1549 $strand = -1;
1550 }
1551 else {
1552 $strand = undef;
1553 }
1554 ($hs,$he) = ( $he,$hs); # reverse subject: start bigger than end
1555 }
1556  
1557 my $sim2 = $self->{_sim2} || FAST::Bio::SeqFeature::Similarity->new();
1558 $sim2->start($hs);
1559 $sim2->end($he);
1560 $sim2->significance($self->{EVALUE});
1561 $sim2->bits($self->{BITS});
1562 $sim2->score($self->{SCORE});
1563 $sim2->strand($strand);
1564 $sim2->seq_id($self->{HIT_NAME});
1565 $sim2->seqlength($self->{HIT_LENGTH});
1566 $sim2->source_tag($self->{ALGORITHM});
1567 $sim2->seqdesc($self->{HIT_DESC});
1568 $sim2->add_tag_value('meta', $self->{META}) if $self->can('meta');
1569 my $hframe = $self->{HIT_FRAME};
1570
1571 if (defined $strand && !defined $hframe && $hitfactor) {
1572 $hframe = ( $hs % 3 ) * $strand;
1573 }
1574 elsif (!defined $strand) {
1575 $hframe = 0;
1576 }
1577
1578 if( $hframe =~ /^([+-])?([0-3])/ ) {
1579 my $dir = $1 || '+';
1580 if($hframe && (($dir eq '-' && $strand >= 0) || ($dir eq '+' && $strand <= 0)) ) {
1581 $self->warn("Subject frame ($hframe) did not match strand of subject ($strand)");
1582 }
1583 $hframe = $2 != 0 ? $2 - 1 : $2;
1584 } else {
1585 $self->warn("Unknown subject frame ($hframe)");
1586 $hframe = 0;
1587 }
1588
1589 $sim2->frame($hframe);
1590 $self->SUPER::feature2($sim2);
1591  
1592 $self->{_created_sff} = 1;
1593 $self->{_making_sff} = 0;
1594 }
1595  
1596 # before calling the num_* methods
1597 sub _pre_similar_stats {
1598 my $self = shift;
1599 my $identical = $self->{IDENTICAL};
1600 my $conserved = $self->{CONSERVED};
1601 my $percent_id = $self->{PERCENT_IDENTITY};
1602  
1603 if (! defined $identical) {
1604 if (! defined $percent_id) {
1605 $self->warn("Did not defined the number of identical matches or overall percent identity in the HSP; assuming 0");
1606 $identical = 0;
1607 }
1608 else {
1609 $identical = sprintf("%.0f",$percent_id * $self->{HSP_LENGTH});
1610 }
1611 }
1612  
1613 if (! defined $conserved) {
1614 $self->warn("Did not define the number of conserved matches in the HSP; assuming conserved == identical ($identical)")
1615 if( $self->{ALGORITHM} !~ /^((FAST|BLAST)N)|EXONERATE|SIM4|AXT|PSL|BLAT|BLASTZ|WABA/oi);
1616 $conserved = $identical;
1617 }
1618 $self->{IDENTICAL} = $identical;
1619 $self->{CONSERVED} = $conserved;
1620 $self->{_did_presimilar} = 1;
1621 }
1622  
1623 # before calling the frac_* methods
1624  
1625 sub _pre_frac {
1626 my $self = shift;
1627
1628 my $hsp_len = $self->{HSP_LENGTH};
1629 my $hit_len = $self->{HIT_LENGTH};
1630 my $query_len = $self->{QUERY_LENGTH};
1631  
1632 my $identical = $self->num_identical;
1633 my $conserved = $self->num_conserved;
1634  
1635 $self->{_did_prefrac} = 1;
1636 my $logical;
1637 if( $hsp_len ) {
1638 $self->length('total', $hsp_len);
1639 $logical = $self->_logical_length('total');
1640 $self->frac_identical( 'total', $identical / $hsp_len);
1641 $self->frac_conserved( 'total', $conserved / $hsp_len);
1642 }
1643 if( $hit_len ) {
1644 $logical = $self->_logical_length('hit');
1645 $self->frac_identical( 'hit', $identical / $logical);
1646 $self->frac_conserved( 'hit', $conserved / $logical);
1647 }
1648 if( $query_len ) {
1649 $logical = $self->_logical_length('query');
1650 $self->frac_identical( 'query', $identical / $logical) ;
1651 $self->frac_conserved( 'query', $conserved / $logical);
1652 }
1653 }
1654  
1655 # before calling gaps()
1656 # This relies first on passed parameters (parser-dependent), then on gaps
1657 # calculated by seq_inds() (if set), then falls back to directly checking
1658 # for '-' as a last resort
1659  
1660 sub _pre_gaps {
1661 my $self = shift;
1662 my $query_gaps = $self->{QUERY_GAPS};
1663 my $query_seq = $self->{QUERY_SEQ};
1664 my $hit_gaps = $self->{HIT_GAPS};
1665 my $hit_seq = $self->{HIT_SEQ};
1666 my $gaps = $self->{HSP_GAPS};
1667  
1668 $self->{_did_pregaps} = 1; # well, we're in the process; avoid recursion
1669 if( defined $query_gaps ) {
1670 $self->gaps('query', $query_gaps);
1671 } elsif( defined $query_seq ) {
1672 my $qg = (defined $self->{'_query_offset'}) ? $self->seq_inds('query','gaps') : scalar( $query_seq =~ tr/\-//);
1673 my $offset = $self->{'_query_offset'} || 1;
1674 $self->gaps('query', $qg/$offset);
1675 }
1676 if( defined $hit_gaps ) {
1677 $self->gaps('hit', $hit_gaps);
1678 } elsif( defined $hit_seq ) {
1679 my $hg = (defined $self->{'_sbjct_offset'}) ? $self->seq_inds('hit','gaps') : scalar( $hit_seq =~ tr/\-//);
1680 my $offset = $self->{'_sbjct_offset'} || 1;
1681 $self->gaps('hit', $hg/$offset);
1682 }
1683 if( ! defined $gaps ) {
1684 $gaps = $self->gaps("query") + $self->gaps("hit");
1685 }
1686 $self->gaps('total', $gaps);
1687 }
1688  
1689 # before percent_identity
1690 sub _pre_pi {
1691 my $self = shift;
1692 $self->{_did_prepi} = 1;
1693 $self->percent_identity($self->{PERCENT_IDENTITY} || $self->frac_identical('total')*100) if( $self->{HSP_LENGTH} > 0 );
1694 }
1695  
1696 1;