FAST/Bio/SearchIO/blasttable.pm untested

filter: Statementstmt 0.0% 0 / 235 Branchbran 0.0% 0 / 72 Conditioncond 0.0% 0 / 30 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 15 totaltotal 0.0% 0 / 373 SCAR 72.5
CC
37
Cov
0%
next_result
306.0
end_element
42.0
characters
42.0
CRAP 1406.0
1 #
2 # BioPerl module for FAST::Bio::SearchIO::blasttable
3 #
4 # Please direct questions and support issues to <bioperl-l@bioperl.org>
5 #
6 # Cared for by Jason Stajich <jason-at-bioperl-dot-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::SearchIO::blasttable - Driver module for SearchIO for parsing NCBI -m 8/9 format
17  
18 =head1 SYNOPSIS
19  
20 # do not use this module directly
21 use FAST::Bio::SearchIO;
22 my $parser = FAST::Bio::SearchIO->new(-file => $file,
23 -format => 'blasttable');
24  
25 while( my $result = $parser->next_result ) {
26 }
27  
28 =head1 DESCRIPTION
29  
30 This module will support parsing NCBI -m 8 or -m 9 tabular output
31 and WU-BLAST -mformat 2 or -mformat 3 tabular output.
32  
33 =head1 FEEDBACK
34  
35 =head2 Mailing Lists
36  
37 User feedback is an integral part of the evolution of this and other
38 Bioperl modules. Send your comments and suggestions preferably to
39 the Bioperl mailing list. Your participation is much appreciated.
40  
41 bioperl-l@bioperl.org - General discussion
42 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
43  
44 =head2 Support
45  
46 Please direct usage questions or support issues to the mailing list:
47  
48 I<bioperl-l@bioperl.org>
49  
50 rather than to the module maintainer directly. Many experienced and
51 reponsive experts will be able look at the problem and quickly
52 address it. Please include a thorough description of the problem
53 with code and data examples if at all possible.
54  
55 =head2 Reporting Bugs
56  
57 Report bugs to the Bioperl bug tracking system to help us keep track
58 of the bugs and their resolution. Bug reports can be submitted via
59 the web:
60  
61 https://redmine.open-bio.org/projects/bioperl/
62  
63 =head1 AUTHOR - Jason Stajich
64  
65 Email jason-at-bioperl-dot-org
66  
67 =head1 APPENDIX
68  
69 The rest of the documentation details each of the object methods.
70 Internal methods are usually preceded with a _
71  
72 =cut
73  
74 # Let the code begin...
75  
76  
77 package FAST::Bio::SearchIO::blasttable;
78 use vars qw(%MAPPING %MODEMAP $DEFAULT_WRITER_CLASS $DefaultProgramName);
79 use strict;
80 use FAST::Bio::Search::Result::ResultFactory;
81 use FAST::Bio::Search::Hit::HitFactory;
82 use FAST::Bio::Search::HSP::HSPFactory;
83  
84 $DefaultProgramName = 'BLASTN';
85 $DEFAULT_WRITER_CLASS = 'FAST::Bio::SearchIO::Writer::HitTableWriter';
86  
87 # mapping of terms to Bioperl hash keys
88 %MODEMAP = (
89 'Result' => 'result',
90 'Hit' => 'hit',
91 'Hsp' => 'hsp'
92 );
93  
94 %MAPPING = (
95 'Hsp_bit-score' => 'HSP-bits',
96 'Hsp_score' => 'HSP-score',
97 'Hsp_evalue' => 'HSP-evalue',
98 'Hsp_query-from' => 'HSP-query_start',
99 'Hsp_query-to' => 'HSP-query_end',
100 'Hsp_hit-from' => 'HSP-hit_start',
101 'Hsp_hit-to' => 'HSP-hit_end',
102 'Hsp_positive' => 'HSP-conserved',
103 'Hsp_identity' => 'HSP-identical',
104 'Hsp_mismatches' => 'HSP-mismatches',
105 'Hsp_qgapblocks' => 'HSP-query_gapblocks',
106 'Hsp_hgapblocks' => 'HSP-hit_gapblocks',
107 'Hsp_gaps' => 'HSP-hsp_gaps',
108 'Hsp_hitgaps' => 'HSP-hit_gaps',
109 'Hsp_querygaps' => 'HSP-query_gaps',
110 'Hsp_align-len' => 'HSP-hsp_length',
111 'Hsp_query-frame'=> 'HSP-query_frame',
112 'Hsp_hit-frame' => 'HSP-hit_frame',
113  
114 'Hit_id' => 'HIT-name',
115 'Hit_len' => 'HIT-length',
116 'Hit_accession' => 'HIT-accession',
117 'Hit_def' => 'HIT-description',
118 'Hit_signif' => 'HIT-significance',
119 'Hit_score' => 'HIT-score',
120 'Hit_bits' => 'HIT-bits',
121  
122 'Result_program' => 'RESULT-algorithm_name',
123 'Result_version' => 'RESULT-algorithm_version',
124 'Result_query-def'=> 'RESULT-query_name',
125 'Result_query-len'=> 'RESULT-query_length',
126 'Result_query-acc'=> 'RESULT-query_accession',
127 'Result_querydesc'=> 'RESULT-query_description',
128 'Result_db' => 'RESULT-database_name',
129 'Result_db-len' => 'RESULT-database_entries',
130 'Result_db-let' => 'RESULT-database_letters',
131 );
132  
133 use base qw(FAST::Bio::SearchIO);
134  
135 =head2 new
136  
137 Title : new
138 Usage : my $obj = FAST::Bio::SearchIO::blasttable->new();
139 Function: Builds a new FAST::Bio::SearchIO::blasttable object
140 Returns : an instance of FAST::Bio::SearchIO::blasttable
141 Args :
142  
143  
144 =cut
145  
146 sub _initialize {
147 my ($self,@args) = @_;
148 $self->SUPER::_initialize(@args);
149  
150 my ($pname) = $self->_rearrange([qw(PROGRAM_NAME)],
151 @args);
152 $self->program_name($pname || $DefaultProgramName);
153 $self->_eventHandler->register_factory('result', FAST::Bio::Search::Result::ResultFactory->new(-type => 'FAST::Bio::Search::Result::GenericResult'));
154 $self->_eventHandler->register_factory('hit', FAST::Bio::Search::Hit::HitFactory->new(-type => 'FAST::Bio::Search::Hit::GenericHit'));
155 $self->_eventHandler->register_factory('hsp', FAST::Bio::Search::HSP::HSPFactory->new(-type => 'FAST::Bio::Search::HSP::GenericHSP'));
156 }
157  
158  
159 =head2 next_result
160  
161 Title : next_result
162 Usage : my $result = $parser->next_result
163 Function: Parse the next result from the data stream
164 Returns : L<FAST::Bio::Search::Result::ResultI>
165 Args : none
166  
167  
168 =cut
169  
170 sub next_result{
171 my ($self) = @_;
172 my ($lastquery,$lasthit);
173 local $/ = "\n";
174 local $_;
175 my ($alg, $ver);
176 while( defined ($_ = $self->_readline) ) {
177 # WU-BLAST -mformat 3 only
178 if(m{^#\s((?:\S+?)?BLAST[NPX])\s(\d+\.\d+.+\d{4}\])}) {
179 ($alg, $ver) = ($1, $2);
180 # only one header for whole file with WU-BLAST
181 # so $alg and $ver won't get set properly for
182 # each result
183 $self->program_name($alg) if $alg;
184 $self->element({'Name' => 'Result_version',
185 'Data' => $ver}) if $ver;
186 next;
187 }
188 # -m 9 only
189 elsif(m{^#\s+((?:\S+?)?BLAST[NPX])\s+(.+)}) {
190 ($alg, $ver) = ($1, $2);
191 next;
192 }
193 next if /^#/ || /^\s*$/;
194  
195 my @fields = split;
196 next if @fields == 1;
197 my ($qname,$hname, $percent_id, $hsp_len, $mismatches,$gapsm,
198 $qstart,$qend,$hstart,$hend,$evalue,$bits);
199 # WU-BLAST-specific
200 my ($num_scores, $raw_score, $identities, $positives, $percent_pos,
201 $qgap_blocks,$qgaps, $sgap_blocks, $sgaps, $qframe,
202 $sframe);
203 # NCBI -m8 and -m9
204 if (@fields == 12) {
205 ($qname,$hname, $percent_id, $hsp_len, $mismatches,$gapsm,
206 $qstart,$qend,$hstart,$hend,$evalue,$bits) = @fields;
207 # NCBI -m8 and -m9, v 2.2.18+
208 } elsif (@fields == 13) {
209 ($qname, $hname, $percent_id, $percent_pos, $hsp_len, $mismatches, $gapsm,
210 $qstart,$qend,$hstart,$hend,$evalue,$bits) = @fields;
211 }
212 # WU-BLAST -mformat 2 and 3
213 elsif ((@fields == 22) or (@fields == 24)) {
214 ($qname,$hname,$evalue,$num_scores, $bits, $raw_score, $hsp_len,
215 $identities, $positives,$mismatches, $percent_id, $percent_pos,
216 $qgap_blocks, $qgaps, $sgap_blocks, $sgaps, $qframe, $qstart,
217 $qend, $sframe, $hstart,$hend,) = @fields;
218 # we need total gaps in the alignment
219 $gapsm=$qgaps+$sgaps;
220 }
221  
222 # Remember Jim's code is 0 based
223 if( defined $lastquery &&
224 $lastquery ne $qname ) {
225 $self->end_element({'Name' => 'Hit'});
226 $self->end_element({'Name' => 'Result'});
227 $self->_pushback($_);
228 return $self->end_document;
229 } elsif( ! defined $lastquery ) {
230 $self->{'_result_count'}++;
231 $self->start_element({'Name' => 'Result'});
232 $self->element({'Name' => 'Result_program',
233 'Data' => $alg || $self->program_name});
234 $self->element({'Name' => 'Result_version',
235 'Data' => $ver}) if $ver;
236 $self->element({'Name' => 'Result_query-def',
237 'Data' => $qname});
238 $self->start_element({'Name' => 'Hit'});
239 $self->element({'Name' => 'Hit_id',
240 'Data' => $hname});
241 # we'll store the 1st hsp bits as the hit bits
242 $self->element({'Name' => 'Hit_bits',
243 'Data' => $bits});
244 # we'll store the 1st hsp value as the hit evalue
245 $self->element({'Name' => 'Hit_signif',
246 'Data' => $evalue});
247
248 } elsif( $lasthit ne $hname ) {
249 if( $self->in_element('hit') ) {
250 $self->end_element({'Name' => 'Hit'});
251 }
252 $self->start_element({'Name' => 'Hit'});
253 $self->element({'Name' => 'Hit_id',
254 'Data' => $hname});
255 # we'll store the 1st hsp bits as the hit bits
256 $self->element({'Name' => 'Hit_bits',
257 'Data' => $bits});
258 # we'll store the 1st hsp value as the hit evalue
259 $self->element({'Name' => 'Hit_signif',
260 'Data' => $evalue});
261 }
262 my $identical = $hsp_len - $mismatches - $gapsm;
263 $self->start_element({'Name' => 'Hsp'});
264 $self->element({'Name' => 'Hsp_evalue',
265 'Data' => $evalue});
266 $self->element({'Name' => 'Hsp_bit-score',
267 'Data' => $bits});
268 $self->element({'Name' => 'Hsp_identity',
269 'Data' => $identical});
270 $self->element({'Name' => 'Hsp_positive',
271 'Data' => $positives});
272 $self->element({'Name' => 'Hsp_gaps',
273 'Data' => $gapsm});
274 $self->element({'Name' => 'Hsp_query-from',
275 'Data' => $qstart});
276 $self->element({'Name' => 'Hsp_query-to',
277 'Data' => $qend});
278  
279 $self->element({'Name' => 'Hsp_hit-from',
280 'Data' => $hstart });
281 $self->element({'Name' => 'Hsp_hit-to',
282 'Data' => $hend });
283 $self->element({'Name' => 'Hsp_align-len',
284 'Data' => $hsp_len});
285 $self->end_element({'Name' => 'Hsp'});
286 $lastquery = $qname;
287 $lasthit = $hname;
288 }
289 # fencepost
290 if( defined $lasthit && defined $lastquery ) {
291 if( $self->in_element('hit') ) {
292 $self->end_element({'Name' => 'Hit'});
293 }
294 $self->end_element({'Name' => 'Result'});
295 return $self->end_document;
296 }
297 }
298  
299 =head2 start_element
300  
301 Title : start_element
302 Usage : $eventgenerator->start_element
303 Function: Handles a start element event
304 Returns : none
305 Args : hashref with at least 2 keys 'Data' and 'Name'
306  
307  
308 =cut
309  
310 sub start_element{
311 my ($self,$data) = @_;
312 # we currently don't care about attributes
313 my $nm = $data->{'Name'};
314 if( my $type = $MODEMAP{$nm} ) {
315 $self->_mode($type);
316 if( $self->_will_handle($type) ) {
317 my $func = sprintf("start_%s",lc $type);
318 $self->_eventHandler->$func($data->{'Attributes'});
319 }
320 unshift @{$self->{'_elements'}}, $type;
321 }
322 if($nm eq 'Result') {
323 $self->{'_values'} = {};
324 $self->{'_result'}= undef;
325 $self->{'_mode'} = '';
326 }
327  
328 }
329  
330 =head2 end_element
331  
332 Title : start_element
333 Usage : $eventgenerator->end_element
334 Function: Handles an end element event
335 Returns : none
336 Args : hashref with at least 2 keys 'Data' and 'Name'
337  
338  
339 =cut
340  
341 sub end_element {
342 my ($self,$data) = @_;
343 my $nm = $data->{'Name'};
344 my $rc;
345 # Hsp are sort of weird, in that they end when another
346 # object begins so have to detect this in end_element for now
347
348 if( my $type = $MODEMAP{$nm} ) {
349 if( $self->_will_handle($type) ) {
350 my $func = sprintf("end_%s",lc $type);
351 $rc = $self->_eventHandler->$func($self->{'_reporttype'},
352 $self->{'_values'});
353 }
354 shift @{$self->{'_elements'}};
355  
356 } elsif( $MAPPING{$nm} ) {
357 if ( ref($MAPPING{$nm}) =~ /hash/i ) {
358 my $key = (keys %{$MAPPING{$nm}})[0];
359 $self->{'_values'}->{$key}->{$MAPPING{$nm}->{$key}} = $self->{'_last_data'};
360 } else {
361 $self->{'_values'}->{$MAPPING{$nm}} = $self->{'_last_data'};
362 }
363 } else {
364 $self->warn( "unknown nm $nm ignoring\n");
365 }
366 $self->{'_last_data'} = ''; # remove read data if we are at
367 # end of an element
368 $self->{'_result'} = $rc if( $nm eq 'Result' );
369 return $rc;
370  
371 }
372  
373 =head2 element
374  
375 Title : element
376 Usage : $eventhandler->element({'Name' => $name, 'Data' => $str});
377 Function: Convience method that calls start_element, characters, end_element
378 Returns : none
379 Args : Hash ref with the keys 'Name' and 'Data'
380  
381  
382 =cut
383  
384 sub element{
385 my ($self,$data) = @_;
386 $self->start_element($data);
387 $self->characters($data);
388 $self->end_element($data);
389 }
390  
391  
392 =head2 characters
393  
394 Title : characters
395 Usage : $eventgenerator->characters($str)
396 Function: Send a character events
397 Returns : none
398 Args : string
399  
400  
401 =cut
402  
403 sub characters{
404 my ($self,$data) = @_;
405  
406 # deep bug fix: set $self->{'_last_data'} to undef if $$data{Data} is
407 # a valid slot, whose value is undef --
408 # allows an undef to be propagated to object constructors and
409 # handled there as desired; in particular, when Hsp_postive => -conserved
410 # is not defined (in BLASTN, e.g.), the value of hsp's {CONSERVED} property is
411 # set to the value of {IDENTICAL}.
412 #/maj
413 # return unless ( defined $data->{'Data'} );
414 return unless ( grep /Data/, keys %$data );
415 if ( !defined $data->{'Data'} ) {
416 $self->{'_last_data'} = undef;
417 return;
418 }
419 if( $data->{'Data'} =~ /^\s+$/ ) {
420 return unless $data->{'Name'} =~ /Hsp\_(midline|qseq|hseq)/;
421 }
422  
423 if( $self->in_element('hsp') &&
424 $data->{'Name'} =~ /Hsp\_(qseq|hseq|midline)/ ) {
425
426 $self->{'_last_hspdata'}->{$data->{'Name'}} .= $data->{'Data'};
427 }
428
429 $self->{'_last_data'} = $data->{'Data'};
430 }
431  
432 =head2 _mode
433  
434 Title : _mode
435 Usage : $obj->_mode($newval)
436 Function:
437 Example :
438 Returns : value of _mode
439 Args : newvalue (optional)
440  
441  
442 =cut
443  
444 sub _mode{
445 my ($self,$value) = @_;
446 if( defined $value) {
447 $self->{'_mode'} = $value;
448 }
449 return $self->{'_mode'};
450 }
451  
452 =head2 within_element
453  
454 Title : within_element
455 Usage : if( $eventgenerator->within_element($element) ) {}
456 Function: Test if we are within a particular element
457 This is different than 'in' because within can be tested
458 for a whole block.
459 Returns : boolean
460 Args : string element name
461  
462  
463 =cut
464  
465 sub within_element{
466 my ($self,$name) = @_;
467 return 0 if ( ! defined $name &&
468 ! defined $self->{'_elements'} ||
469 scalar @{$self->{'_elements'}} == 0) ;
470 foreach ( @{$self->{'_elements'}} ) {
471 if( $_ eq $name ) {
472 return 1;
473 }
474 }
475 return 0;
476 }
477  
478 =head2 in_element
479  
480 Title : in_element
481 Usage : if( $eventgenerator->in_element($element) ) {}
482 Function: Test if we are in a particular element
483 This is different than 'in' because within can be tested
484 for a whole block.
485 Returns : boolean
486 Args : string element name
487  
488  
489 =cut
490  
491 sub in_element{
492 my ($self,$name) = @_;
493 return 0 if ! defined $self->{'_elements'}->[0];
494 return ( $self->{'_elements'}->[0] eq $name)
495 }
496  
497  
498 =head2 start_document
499  
500 Title : start_document
501 Usage : $eventgenerator->start_document
502 Function: Handles a start document event
503 Returns : none
504 Args : none
505  
506  
507 =cut
508  
509 sub start_document{
510 my ($self) = @_;
511 $self->{'_lasttype'} = '';
512 $self->{'_values'} = {};
513 $self->{'_result'}= undef;
514 $self->{'_mode'} = '';
515 $self->{'_elements'} = [];
516 }
517  
518  
519 =head2 end_document
520  
521 Title : end_document
522 Usage : $eventgenerator->end_document
523 Function: Handles an end document event
524 Returns : FAST::Bio::Search::Result::ResultI object
525 Args : none
526  
527  
528 =cut
529  
530 sub end_document{
531 my ($self,@args) = @_;
532 return $self->{'_result'};
533 }
534  
535 =head2 result_count
536  
537 Title : result_count
538 Usage : my $count = $searchio->result_count
539 Function: Returns the number of results we have processed
540 Returns : integer
541 Args : none
542  
543  
544 =cut
545  
546 sub result_count {
547 my $self = shift;
548 return $self->{'_result_count'};
549 }
550  
551 sub report_count { shift->result_count }
552  
553  
554 =head2 program_name
555  
556 Title : program_name
557 Usage : $obj->program_name($newval)
558 Function: Get/Set the program name
559 Returns : value of program_name (a scalar)
560 Args : on set, new value (a scalar or undef, optional)
561  
562  
563 =cut
564  
565 sub program_name{
566 my $self = shift;
567  
568 $self->{'program_name'} = shift if @_;
569 return $self->{'program_name'} || $DefaultProgramName;
570 }
571  
572  
573 =head2 _will_handle
574  
575 Title : _will_handle
576 Usage : Private method. For internal use only.
577 if( $self->_will_handle($type) ) { ... }
578 Function: Provides an optimized way to check whether or not an element of a
579 given type is to be handled.
580 Returns : Reference to EventHandler object if the element type is to be handled.
581 undef if the element type is not to be handled.
582 Args : string containing type of element.
583  
584 Optimizations:
585  
586 =over 2
587  
588 =item 1
589  
590 Using the cached pointer to the EventHandler to minimize repeated
591 lookups.
592  
593 =item 2
594  
595 Caching the will_handle status for each type that is encountered so
596 that it only need be checked by calling
597 handler-E<gt>will_handle($type) once.
598  
599 =back
600  
601 This does not lead to a major savings by itself (only 5-10%). In
602 combination with other optimizations, or for large parse jobs, the
603 savings good be significant.
604  
605 To test against the unoptimized version, remove the parentheses from
606 around the third term in the ternary " ? : " operator and add two
607 calls to $self-E<gt>_eventHandler().
608  
609 =cut
610  
611 sub _will_handle {
612 my ($self,$type) = @_;
613 my $handler = $self->{'_handler'};
614 my $will_handle = defined($self->{'_will_handle_cache'}->{$type})
615 ? $self->{'_will_handle_cache'}->{$type}
616 : ($self->{'_will_handle_cache'}->{$type} =
617 $handler->will_handle($type));
618  
619 return $will_handle ? $handler : undef;
620 }
621  
622 1;