bug 2549; fixed small bug in Bio::Taxon which doesn't catch -common_name
[bioperl-live.git] / Bio / SearchIO / sim4.pm
blobec83018f7807a8f359a9c891a479005b60504b74
1 # $Id$
3 # BioPerl module for Bio::SearchIO::sim4
5 # Cared for by Jason Stajich <jason-at-bioperl-dot-org>
7 # Copyright Jason Stajich
9 # You may distribute this module under the same terms as perl itself
11 # POD documentation - main docs before the code
13 =head1 NAME
15 Bio::SearchIO::sim4 - parser for Sim4 alignments
17 =head1 SYNOPSIS
19 # do not use this module directly, it is a driver for SearchIO
20 use Bio::SearchIO;
21 my $searchio = Bio::SearchIO->new(-file => 'results.sim4',
22 -format => 'sim4');
24 while ( my $result = $searchio->next_result ) {
25 while ( my $hit = $result->next_hit ) {
26 while ( my $hsp = $hit->next_hsp ) {
27 # ...
32 =head1 DESCRIPTION
34 This is a driver for the SearchIO system for parsing Sim4.
35 http://globin.cse.psu.edu/html/docs/sim4.html
37 Cannot parse LAV or 'exon file' formats (A=2 or A=5)
39 =head1 FEEDBACK
41 =head2 Mailing Lists
43 User feedback is an integral part of the evolution of this and other
44 Bioperl modules. Send your comments and suggestions preferably to
45 the Bioperl mailing list. Your participation is much appreciated.
47 bioperl-l@bioperl.org - General discussion
48 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
50 =head2 Reporting Bugs
52 Report bugs to the Bioperl bug tracking system to help us keep track
53 of the bugs and their resolution. Bug reports can be submitted via the
54 web:
56 http://bugzilla.open-bio.org/
58 =head1 AUTHOR - Jason Stajich
60 Email jason-at-bioperl-dot-org
62 =head1 CONTRIBUTORS
64 Luc Gauthier (lgauthie@hotmail.com)
66 =head1 APPENDIX
68 The rest of the documentation details each of the object methods.
69 Internal methods are usually preceded with a _
71 =cut
74 # Let the code begin...
77 package Bio::SearchIO::sim4;
79 use strict;
80 use vars qw($DEFAULTFORMAT %ALIGN_TYPES
81 %MAPPING %MODEMAP $DEFAULT_WRITER_CLASS);
83 use POSIX;
84 use Bio::SearchIO::SearchResultEventBuilder;
86 use base qw(Bio::SearchIO);
88 $DEFAULTFORMAT = 'SIM4';
89 $DEFAULT_WRITER_CLASS = 'Bio::Search::Writer::HitTableWriter';
91 %ALIGN_TYPES = (
92 0 => 'Ruler',
93 1 => 'Query',
94 2 => 'Mid',
95 3 => 'Sbjct'
98 %MODEMAP = (
99 'Sim4Output' => 'result',
100 'Hit' => 'hit',
101 'Hsp' => 'hsp'
104 %MAPPING = (
105 'Hsp_query-from'=> 'HSP-query_start',
106 'Hsp_query-to' => 'HSP-query_end',
107 'Hsp_qseq' => 'HSP-query_seq',
108 'Hsp_qlength' => 'HSP-query_length',
109 'Hsp_querygaps' => 'HSP-query_gaps',
110 'Hsp_hit-from' => 'HSP-hit_start',
111 'Hsp_hit-to' => 'HSP-hit_end',
112 'Hsp_hseq' => 'HSP-hit_seq',
113 'Hsp_hlength' => 'HSP-hit_length',
114 'Hsp_hitgaps' => 'HSP-hit_gaps',
115 'Hsp_midline' => 'HSP-homology_seq',
116 'Hsp_score' => 'HSP-score',
117 'Hsp_align-len' => 'HSP-hsp_length',
118 'Hsp_identity' => 'HSP-identical',
120 'Hit_id' => 'HIT-name',
121 'Hit_desc' => 'HIT-description',
122 'Hit_len' => 'HIT-length',
124 'Sim4Output_program' => 'RESULT-algorithm_name',
125 'Sim4Output_query-def' => 'RESULT-query_name',
126 'Sim4Output_query-desc'=> 'RESULT-query_description',
127 'Sim4Output_query-len' => 'RESULT-query_length',
132 =head2 new
134 Title : new
135 Usage : my $obj = Bio::SearchIO::sim4->new();
136 Function: Builds a new Bio::SearchIO::sim4 object
137 Returns : an instance of Bio::SearchIO::sim4
138 Args :
141 =cut
144 =head2 next_result
146 Title : next_result
147 Usage : my $result = $searchio->next_result;
148 Function: Returns the next Result from a search
149 Returns : Bio::Search::Result::ResultI object
150 Args : none
152 =cut
154 sub next_result {
155 my ($self) = @_;
156 local $/ = "\n";
157 local $_;
159 # Declare/adjust needed variables
160 $self->{'_last_data'} = '';
161 my ($seentop, $qfull, @hsps, %alignment, $format);
162 my $hit_direction = 1;
164 # Start document and main element
165 $self->start_document();
166 $self->start_element({'Name' => 'Sim4Output'});
167 my $lastquery = '';
168 # Read output report until EOF
169 while( defined($_ = $self->_readline) ) {
170 # Skip empty lines, chomp filled ones
171 next if( /^\s+$/); chomp;
173 # Make sure sim4 output format is not 2 or 5
174 if (!$seentop) {
175 if ( /^\#:lav/ ) { $format = 2; }
176 elsif ( /^<|>/ ) { $format = 5; }
177 $self->throw("Bio::SearchIO::sim4 module cannot parse 'type $format' outputs.") if $format;
180 # This line indicates the start of a new hit
181 if( /^seq1\s*=\s*(\S+),\s+(\d+)/ ) {
182 my ($nm,$desc) = ($1,$2);
183 # First hit? Adjust some parameters if so
184 if ( ! $seentop ) {
185 $self->element( {'Name' => 'Sim4Output_query-def',
186 'Data' => $nm} );
187 $self->element( {'Name' => 'Sim4Output_query-len',
188 'Data' => $desc} );
189 $seentop = 1;
190 } elsif( $nm ne $lastquery ) {
191 $self->_pushback($_);
192 last;
194 $lastquery = $nm;
195 # A previous HSP may need to be ended
196 $self->end_element({'Name' => 'Hsp'}) if ( $self->in_element('hsp') );
197 # A previous hit exists? End it and reset needed variables
198 if ( $self->in_element('hit') ) {
199 foreach (@hsps) {
200 $self->start_element({'Name' => 'Hsp'});
201 while (my ($name, $data) = each %$_) {
202 $self->{'_currentHSP'}{$name} = $data;
204 $self->end_element({'Name' => 'Hsp'});
205 $self->{'_currentHSP'} = {};
207 $format = 0 if @hsps;
208 @hsps = ();
209 %alignment = ();
210 $qfull = 0;
211 $hit_direction = 1;
212 $self->end_element({'Name' => 'Hit'});
215 # This line describes the current hit... so let's start it
216 } elsif( /^seq2\s*=\s*(\S+)\s+\(>?(\S+)\s*\),\s*(\d+)/ ) {
217 $self->start_element({'Name' => 'Hit'});
218 $self->element( {'Name' => 'Hit_id', 'Data' => $2} );
219 $self->element( {'Name' => 'Hit_desc', 'Data' => $1} );
220 $self->element( {'Name' => 'Hit_len', 'Data' => $3} );
222 # This line may give additional details about query or subject
223 } elsif( /^>(\S+)\s*(.*)?/ ) {
224 # Previous line was query details... this time subject details
225 if( $qfull ) {
226 $format = 4 if !$format;
227 $self->element({'Name' => 'Hit_desc', 'Data' => $2});
228 # First line of this type is always query details for a given hit
229 } else {
230 $self->element({'Name' => 'Sim4Output_query-desc', 'Data' => $2});
231 $qfull = 1;
234 # This line indicates that subject is on reverse strand
235 } elsif( /^\(complement\)/ ) {
236 $hit_direction = -1;
238 # This line describes the current HSP... so add it to @hsps array
239 } elsif( /^\(?(\d+)\-(\d+)\)?\s+\(?(\d+)\-(\d+)\)?\s+(\d+)/ ) {
240 my ($qs,$qe,$hs,$he,$pid) = ($1,$2,$3,$4,$5);
241 push @hsps, {
242 'Hsp_query-from' => $qs,
243 'Hsp_query-to' => $qe,
244 'Hsp_hit-from' => $hit_direction >= 0 ? $hs : $he,
245 'Hsp_hit-to' => $hit_direction >= 0 ? $he : $hs,
246 'Hsp_identity' => 0, #can't determine correctly from raw pct
247 'Hsp_qlength' => abs($qe - $qs) + 1,
248 'Hsp_hlength' => abs($he - $hs) + 1,
249 'Hsp_align-len' => abs($qe - $qs) + 1,
252 # This line indicates the start of an alignment block
253 } elsif( /^\s+(\d+)\s/ ) {
254 # Store the current alignment block in a hash
255 for( my $i = 0; defined($_) && $i < 4; $i++ ) {
256 my ($start, $string) = /^\s+(\d*)\s(.*)/;
257 $alignment{$ALIGN_TYPES{$i}} = { start => $start, string => $i != 2
258 ? $string
259 : (' ' x (length($alignment{$ALIGN_TYPES{$i-1}}{string}) - length($string))) . $string
261 $_ = $self->_readline();
264 # 'Ruler' line indicates the start of a new HSP
265 if ($alignment{Ruler}{start} == 0) {
266 $format = @hsps ? 3 : 1 if !$format;
267 # A previous HSP may need to be ended
268 $self->end_element({'Name' => 'Hsp'}) if ( $self->in_element('hsp') );
269 # Start the new HSP and fill the '_currentHSP' property with available details
270 $self->start_element({'Name' => 'Hsp'});
271 $self->{'_currentHSP'} = @hsps ? shift @hsps : {
272 'Hsp_query-from' => $alignment{Query}{start},
273 'Hsp_hit-from' => $alignment{Sbjct}{start},
277 # Midline indicates a boundary between two HSPs
278 if ( $alignment{Mid}{string} =~ /<|>/g ) {
279 my ($hsp_start, $hsp_end);
280 # Are we currently in an open HSP?
281 if ( $self->in_element('hsp') ) {
282 # Find end pos, adjust 'gaps', 'seq' and 'midline' properties... then close HSP
283 $hsp_end = (pos $alignment{Mid}{string}) - 1;
284 $self->{'_currentHSP'}{'Hsp_querygaps'} +=
285 ($self->{'_currentHSP'}{'Hsp_qseq'} .= substr($alignment{Query}{string}, 0, $hsp_end)) =~ s/ /-/g;
286 $self->{'_currentHSP'}{'Hsp_hitgaps'} +=
287 ($self->{'_currentHSP'}{'Hsp_hseq'} .= substr($alignment{Sbjct}{string}, 0, $hsp_end)) =~ s/ /-/g;
288 ($self->{'_currentHSP'}{'Hsp_midline'} .= substr($alignment{Mid}{string}, 0, $hsp_end)) =~ s/-/ /g;
289 $self->end_element({'Name' => 'Hsp'});
291 # Does a new HSP start in the current alignment block?
292 if ( $alignment{Mid}{string} =~ /\|/g ) {
293 # Find start pos, start new HSP and fill it with available details
294 $hsp_start = (pos $alignment{Mid}{string}) - 1;
295 $self->start_element({'Name' => 'Hsp'});
296 $self->{'_currentHSP'} = @hsps ? shift @hsps : {};
297 $self->{'_currentHSP'}{'Hsp_querygaps'} +=
298 ($self->{'_currentHSP'}{'Hsp_qseq'} = substr($alignment{Query}{string}, $hsp_start)) =~ s/ /-/g;
299 $self->{'_currentHSP'}{'Hsp_hitgaps'} +=
300 ($self->{'_currentHSP'}{'Hsp_hseq'} = substr($alignment{Sbjct}{string}, $hsp_start)) =~ s/ /-/g;
301 ($self->{'_currentHSP'}{'Hsp_midline'} = substr($alignment{Mid}{string}, $hsp_start)) =~ s/-/ /g;
304 # No HSP is currently open...
305 else {
306 # Find start pos, start new HSP and fill it with available
307 # details then skip to next alignment block
308 $hsp_start = index($alignment{Mid}{string}, '|');
309 $self->start_element({'Name' => 'Hsp'});
310 $self->{'_currentHSP'} = @hsps ? shift @hsps : {
311 'Hsp_query-from' => $alignment{Query}{start},
313 $self->{'_currentHSP'}{'Hsp_querygaps'} +=
314 ($self->{'_currentHSP'}{'Hsp_qseq'} = substr($alignment{Query}{string}, $hsp_start)) =~ s/ /-/g;
315 $self->{'_currentHSP'}{'Hsp_hitgaps'} +=
316 ($self->{'_currentHSP'}{'Hsp_hseq'} = substr($alignment{Sbjct}{string}, $hsp_start)) =~ s/ /-/g;
317 ($self->{'_currentHSP'}{'Hsp_midline'} = substr($alignment{Mid}{string}, $hsp_start)) =~ s/-/ /g;
318 next;
321 # Current alignment block does not contain HSPs boundary
322 else {
323 # Start a new HSP if none is currently open
324 # (Happens if last boundary finished at the very end of previous block)
325 if ( !$self->in_element('hsp') ) {
326 $self->start_element({'Name' => 'Hsp'});
327 $self->{'_currentHSP'} = @hsps ? shift @hsps : {
328 'Hsp_query-from' => $alignment{Query}{start},
329 'Hsp_hit-from' => $alignment{Sbjct}{start},
332 # Adjust details of the current HSP
333 $self->{'_currentHSP'}{'Hsp_query-from'} ||=
334 $alignment{Query}{start} -
335 length($self->{'_currentHSP'}{'Hsp_qseq'} || '');
336 $self->{'_currentHSP'}{'Hsp_hit-from'} ||=
337 $alignment{Sbjct}{start} -
338 length($self->{'_currentHSP'}{'Hsp_hseq'} || '');
339 $self->{'_currentHSP'}{'Hsp_querygaps'} +=
340 ($self->{'_currentHSP'}{'Hsp_qseq'} .=
341 $alignment{Query}{string}) =~ s/ /-/g;
342 $self->{'_currentHSP'}{'Hsp_hitgaps'} +=
343 ($self->{'_currentHSP'}{'Hsp_hseq'} .=
344 $alignment{Sbjct}{string}) =~ s/ /-/g;
345 ($self->{'_currentHSP'}{'Hsp_midline'} .=
346 $alignment{Mid}{string}) =~ s/-/ /g;
351 # We are done reading the sim4 report, end everything and return
352 if( $seentop ) {
353 # end HSP if needed
354 $self->end_element({'Name' => 'Hsp'}) if ( $self->in_element('hsp') );
355 # end Hit if needed
356 if ( $self->in_element('hit') ) {
357 foreach (@hsps) {
358 $self->start_element({'Name' => 'Hsp'});
359 while (my ($name, $data) = each %$_) {
360 $self->{'_currentHSP'}{$name} = $data;
362 $self->end_element({'Name' => 'Hsp'});
364 $self->end_element({'Name' => 'Hit'});
366 # adjust result's algorithm name, end output and return
367 $self->element({'Name' => 'Sim4Output_program',
368 'Data' => $DEFAULTFORMAT . ' (A=' . (defined $format ? $format : '?') . ')'});
369 $self->end_element({'Name' => 'Sim4Output'});
370 return $self->end_document();
372 return;
375 =head2 start_element
377 Title : start_element
378 Usage : $eventgenerator->start_element
379 Function: Handles a start element event
380 Returns : none
381 Args : hashref with at least 2 keys 'Data' and 'Name'
384 =cut
386 sub start_element{
387 my ($self,$data) = @_;
388 # we currently don't care about attributes
389 my $nm = $data->{'Name'};
390 my $type = $MODEMAP{$nm};
392 if( $type ) {
393 if( $self->_will_handle($type) ) {
394 my $func = sprintf("start_%s",lc $type);
395 $self->_eventHandler->$func($data->{'Attributes'});
397 unshift @{$self->{'_elements'}}, $type;
399 if($type eq 'result') {
400 $self->{'_values'} = {};
401 $self->{'_result'}= undef;
407 =head2 end_element
409 Title : start_element
410 Usage : $eventgenerator->end_element
411 Function: Handles an end element event
412 Returns : none
413 Args : hashref with at least 2 keys 'Data' and 'Name'
416 =cut
418 sub end_element {
419 my ($self,$data) = @_;
420 my $nm = $data->{'Name'};
421 my $type = $MODEMAP{$nm};
422 my $rc;
424 if( $nm eq 'Hsp' ) {
425 $self->{'_currentHSP'}{'Hsp_midline'} ||= '';
426 $self->{'_currentHSP'}{'Hsp_query-to'} ||=
427 $self->{'_currentHSP'}{'Hsp_query-from'} + length($self->{'_currentHSP'}{'Hsp_qseq'}) - 1 - $self->{'_currentHSP'}{'Hsp_querygaps'};
428 $self->{'_currentHSP'}{'Hsp_hit-to'} ||=
429 $self->{'_currentHSP'}{'Hsp_hit-from'} + length($self->{'_currentHSP'}{'Hsp_hseq'}) - 1 - $self->{'_currentHSP'}{'Hsp_hitgaps'};
430 $self->{'_currentHSP'}{'Hsp_identity'} ||=
431 ($self->{'_currentHSP'}{'Hsp_midline'} =~ tr/\|//);
432 $self->{'_currentHSP'}{'Hsp_qlength'} ||= abs($self->{'_currentHSP'}{'Hsp_query-to'} - $self->{'_currentHSP'}{'Hsp_query-from'}) + 1;
433 $self->{'_currentHSP'}{'Hsp_hlength'} ||= abs($self->{'_currentHSP'}{'Hsp_hit-to'} - $self->{'_currentHSP'}{'Hsp_hit-from'}) + 1;
434 $self->{'_currentHSP'}{'Hsp_align-len'} ||= abs($self->{'_currentHSP'}{'Hsp_query-to'} - $self->{'_currentHSP'}{'Hsp_query-from'}) + 1;
435 $self->{'_currentHSP'}{'Hsp_score'} ||= int(100 * ($self->{'_currentHSP'}{'Hsp_identity'} / $self->{'_currentHSP'}{'Hsp_align-len'}));
436 foreach (keys %{$self->{'_currentHSP'}}) {
437 $self->element({'Name' => $_, 'Data' => delete ${$self->{'_currentHSP'}}{$_}});
441 if( $type = $MODEMAP{$nm} ) {
442 if( $self->_will_handle($type) ) {
443 my $func = sprintf("end_%s",lc $type);
444 $rc = $self->_eventHandler->$func($self->{'_reporttype'},
445 $self->{'_values'});
447 shift @{$self->{'_elements'}};
449 } elsif( $MAPPING{$nm} ) {
451 if ( ref($MAPPING{$nm}) =~ /hash/i ) {
452 my $key = (keys %{$MAPPING{$nm}})[0];
453 $self->{'_values'}->{$key}->{$MAPPING{$nm}->{$key}} = $self->{'_last_data'};
454 } else {
455 $self->{'_values'}->{$MAPPING{$nm}} = $self->{'_last_data'};
457 } else {
458 $self->debug( "unknown nm $nm, ignoring\n");
460 $self->{'_last_data'} = ''; # remove read data if we are at
461 # end of an element
462 $self->{'_result'} = $rc if( defined $type && $type eq 'result' );
463 return $rc;
466 =head2 element
468 Title : element
469 Usage : $eventhandler->element({'Name' => $name, 'Data' => $str});
470 Function: Convience method that calls start_element, characters, end_element
471 Returns : none
472 Args : Hash ref with the keys 'Name' and 'Data'
475 =cut
477 sub element{
478 my ($self,$data) = @_;
479 $self->start_element($data);
480 $self->characters($data);
481 $self->end_element($data);
484 =head2 characters
486 Title : characters
487 Usage : $eventgenerator->characters($str)
488 Function: Send a character events
489 Returns : none
490 Args : string
493 =cut
495 sub characters{
496 my ($self,$data) = @_;
497 return unless ( defined $data->{'Data'} && $data->{'Data'} !~ /^\s+$/ );
499 if( $self->in_element('hsp') &&
500 $data->{'Name'} =~ /Hsp\_(qseq|hseq|midline)/ ) {
501 $self->{'_last_hspdata'}->{$data->{'Name'}} .= $data->{'Data'};
504 $self->{'_last_data'} = $data->{'Data'};
507 =head2 within_element
509 Title : within_element
510 Usage : if( $eventgenerator->within_element($element) ) {}
511 Function: Test if we are within a particular element
512 This is different than 'in' because within can be tested
513 for a whole block.
514 Returns : boolean
515 Args : string element name
518 =cut
520 sub within_element{
521 my ($self,$name) = @_;
522 return 0 if ( ! defined $name &&
523 ! defined $self->{'_elements'} ||
524 scalar @{$self->{'_elements'}} == 0) ;
525 foreach ( @{$self->{'_elements'}} ) {
526 if( $_ eq $name ) {
527 return 1;
530 return 0;
534 =head2 in_element
536 Title : in_element
537 Usage : if( $eventgenerator->in_element($element) ) {}
538 Function: Test if we are in a particular element
539 This is different than 'in' because within can be tested
540 for a whole block.
541 Returns : boolean
542 Args : string element name
545 =cut
547 sub in_element{
548 my ($self,$name) = @_;
549 return 0 if ! defined $self->{'_elements'}->[0];
550 return ( $self->{'_elements'}->[0] eq $name)
553 =head2 start_document
555 Title : start_document
556 Usage : $eventgenerator->start_document
557 Function: Handle a start document event
558 Returns : none
559 Args : none
562 =cut
564 sub start_document{
565 my ($self) = @_;
566 $self->{'_lasttype'} = '';
567 $self->{'_values'} = {};
568 $self->{'_result'}= undef;
569 $self->{'_elements'} = [];
570 $self->{'_reporttype'} = $DEFAULTFORMAT;
574 =head2 end_document
576 Title : end_document
577 Usage : $eventgenerator->end_document
578 Function: Handles an end document event
579 Returns : Bio::Search::Result::ResultI object
580 Args : none
583 =cut
585 sub end_document{
586 my ($self,@args) = @_;
587 return $self->{'_result'};
591 sub write_result {
592 my ($self, $blast, @args) = @_;
594 if( not defined($self->writer) ) {
595 $self->warn("Writer not defined. Using a $DEFAULT_WRITER_CLASS");
596 $self->writer( $DEFAULT_WRITER_CLASS->new() );
598 $self->SUPER::write_result( $blast, @args );
601 sub result_count {
602 return 1; # can a sim4 report contain more than one result?
605 sub report_count { shift->result_count }
607 =head2 _will_handle
609 Title : _will_handle
610 Usage : Private method. For internal use only.
611 if( $self->_will_handle($type) ) { ... }
612 Function: Provides an optimized way to check whether or not an element of a
613 given type is to be handled.
614 Returns : Reference to EventHandler object if the element type is to be handled.
615 undef if the element type is not to be handled.
616 Args : string containing type of element.
618 Optimizations:
620 1. Using the cached pointer to the EventHandler to minimize repeated lookups.
621 2. Caching the will_handle status for each type that is encountered
622 so that it only need be checked by calling handler->will_handle($type) once.
624 This does not lead to a major savings by itself (only 5-10%).
625 In combination with other optimizations, or for large parse jobs, the
626 savings good be significant.
628 To test against the unoptimized version, remove the parentheses from
629 around the third term in the ternary " ? : " operator and add two
630 calls to $self-E<gt>_eventHandler().
632 =cut
634 sub _will_handle {
635 my ($self,$type) = @_;
636 my $handler = $self->{'_handler_cache'} ||= $self->_eventHandler;
638 my $will_handle = defined($self->{'_will_handle_cache'}->{$type})
639 ? $self->{'_will_handle_cache'}->{$type}
640 : ($self->{'_will_handle_cache'}->{$type} =
641 $handler->will_handle($type));
643 return $will_handle ? $handler : undef;