FAST/Bio/SearchIO/blastxml.pm untested

filter: Statementstmt 0.0% 0 / 156 Branchbran 0.0% 0 / 60 Conditioncond 0.0% 0 / 19 MC/DCmcdc 0.0% 0 / 12 Subroutinesub 0.0% 0 / 16 Podpod 0.0% 0 / 8 totaltotal 0.0% 0 / 271 CC 31 SCAR 42.8
CC
31
Cov
0%
_chunk_normalblast
156.0
next_result
110.0
blasttype
42.0
CRAP 72.3
1 #
2 # BioPerl module for FAST::Bio::SearchIO::blastxml
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::SearchIO::blastxml - A SearchIO implementation of NCBI Blast XML parsing.
17  
18 =head1 SYNOPSIS
19  
20 use FAST::Bio::SearchIO;
21 my $searchin = FAST::Bio::SearchIO->new(-format => 'blastxml',
22 -file => 't/data/plague_yeast.bls.xml');
23
24 while( my $result = $searchin->next_result ) {
25 ....
26 }
27  
28 # one can also request that the parser NOT keep the XML data in memory
29 # by using the tempfile initialization flag.
30
31 $searchin = FAST::Bio::SearchIO->new(-tempfile => 1,
32 -format => 'blastxml',
33 -file => 't/data/plague_yeast.bls.xml');
34
35 while( my $result = $searchin->next_result ) {
36 ....
37 }
38
39 # PSI-BLAST parsing (default is normal BLAST)
40 $searchin = FAST::Bio::SearchIO->new(
41 -format => 'blastxml',
42 -blasttype => 'psiblast',
43 -file => 't/data/plague_yeast.bls.xml');
44
45 while( my $result = $searchin->next_result ) {
46 ....
47 }
48  
49 =head1 DESCRIPTION
50  
51 This object implements a NCBI Blast XML parser. It requires XML::SAX; it is
52 also recommended (for faster parsing) that XML::SAX::ExpatXS or XML::LibXML
53 be installed. Either 'XML::SAX::ExpatXS' or 'XML::LibXML::SAX::Parser' should
54 be set as the default parser in ParserDetails.ini. This file is located in the
55 SAX subdirectory of XML in your local perl library (normally in the 'site'
56 directory).
57  
58 Two different XML handlers currently exist to deal with logical differences
59 between how normal BLAST reports and PSI-BLAST reports are logically parsed into
60 BioPerl objects; this is explicitly settable using the B<-blasttype> parameter.
61 The default is for parsing a normal BLAST report ('blast'), but if one is
62 expecting PSI-BLAST report parsing, -blasttype B<must> be set explicitly to
63 'psiblast'. This is due to a lack of any information in the XML output which
64 tells the parser the report is derived from a PSI-BLAST run vs. a normal BLAST
65 run.
66  
67 There is one additional initialization flag from the SearchIO defaults. That is
68 the B<-tempfile> flag. If specified as true, then the parser will write out each
69 report to a temporary filehandle rather than holding the entire report as a
70 string in memory. The reason this is done in the first place is NCBI reports
71 have an uncessary E<lt>?xml version="1.0"?E<gt> at the beginning of each report
72 and RPS-BLAST reports have an additional unnecessary RPS-BLAST tag at the top of
73 each report. So we currently have implemented the work around by preparsing the
74 file (yes it makes the process slower, but it works). We are open to suggestions
75 on how to optimize this in the future.
76  
77 =head1 DEPENDENCIES
78  
79 In addition to parts of the FAST::Bio:: hierarchy, this module uses:
80  
81 XML::SAX
82  
83 It is also recommended that XML::SAX::ExpatXS be installed and made the default
84 XML::SAX parser using , along with the Expat library () for faster parsing.
85 XML::SAX::Expat is not recommended; XML::SAX::ExpatXS is considered the current
86 replacement for XML::SAX:Expat and is actively being considered to replace
87 XML::SAX::Expat. XML::SAX::Expat will work, but only if you have local copies of
88 the NCBI BLAST DTDs. This is due to issues with NCBI's BLAST XML format. The
89 DTDs and the web address to obtain them are:
90  
91 NCBI_BlastOutput.dtd
92 NCBI_BlastOutput.mod.dtd
93  
94 http://www.ncbi.nlm.nih.gov/data_specs/dtd/
95  
96 =head1 FEEDBACK
97  
98 =head2 Mailing Lists
99  
100 User feedback is an integral part of the evolution of this and other
101 Bioperl modules. Send your comments and suggestions preferably to
102 the Bioperl mailing list. Your participation is much appreciated.
103  
104 bioperl-l@bioperl.org - General discussion
105 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
106  
107 =head2 Support
108  
109 Please direct usage questions or support issues to the mailing list:
110  
111 I<bioperl-l@bioperl.org>
112  
113 rather than to the module maintainer directly. Many experienced and
114 reponsive experts will be able look at the problem and quickly
115 address it. Please include a thorough description of the problem
116 with code and data examples if at all possible.
117  
118 =head2 Reporting Bugs
119  
120 Report bugs to the Bioperl bug tracking system to help us keep track
121 of the bugs and their resolution. Bug reports can be submitted via the
122 web:
123  
124 https://redmine.open-bio.org/projects/bioperl/
125  
126 =head1 AUTHOR - Jason Stajich
127  
128 Email jason-at-bioperl.org
129  
130 =head1 APPENDIX
131  
132 The rest of the documentation details each of the object methods.
133 Internal methods are usually preceded with a _
134  
135 =cut
136  
137 # Let the code begin...
138  
139 package FAST::Bio::SearchIO::blastxml;
140 use strict;
141 # Object preamble - inherits from FAST::Bio::Root::Root
142  
143 use base qw(FAST::Bio::SearchIO);
144 use FAST::Bio::Root::Root;
145 use XML::SAX;
146 use IO::File;
147 use FAST::Bio::SearchIO::XML::BlastHandler;
148 use FAST::Bio::SearchIO::IteratedSearchResultEventBuilder;
149  
150 our $DEBUG;
151  
152 my %VALID_TYPE = (
153 'BLAST' => 'FAST::Bio::SearchIO::XML::BlastHandler',
154 'PSIBLAST' => 'FAST::Bio::SearchIO::XML::PsiBlastHandler',
155 'PSI-BLAST' => 'FAST::Bio::SearchIO::XML::PsiBlastHandler'
156 );
157  
158 # mapping of NCBI Blast terms to Bioperl hash keys
159  
160 =head2 new
161  
162 Title : new
163 Usage : my $searchio = FAST::Bio::SearchIO->new(-format => 'blastxml',
164 -file => 'filename',
165 -tempfile => 1);
166 Function: Initializes the object - this is chained through new in SearchIO
167 Returns : FAST::Bio::SearchIO::blastxml object
168 Args : One additional argument from the format and file/fh parameters.
169 -tempfile => boolean. Defaults to false. Write out XML data
170 to a temporary filehandle to send to PerlSAX parser.
171  
172 =cut
173  
174 =head2 _initialize
175  
176 Title : _initialize
177 Usage : private
178 Function: Initializes the object - this is chained through new in SearchIO
179  
180 =cut
181  
182 sub _initialize{
183 my ($self,@args) = @_;
184 $self->SUPER::_initialize(@args);
185 my ($usetempfile, $blasttype,$xmlcompact) = $self->_rearrange([qw(
186 TEMPFILE
187 BLASTTYPE
188 XMLCOMPACT)],@args);
189 $blasttype ||= 'BLAST';
190 $self->{_xml_compact} = $xmlcompact || 0;
191 $self->blasttype(uc $blasttype);
192 defined $usetempfile && $self->use_tempfile($usetempfile);
193 $self->{_result_count} = 0;
194 eval { require Time::HiRes };
195 if( $@ ) { $DEBUG = 0; }
196 $DEBUG = 1 if( ! defined $DEBUG && ($self->verbose > 0));
197 }
198  
199 =head2 next_result
200  
201 Title : next_result
202 Usage : my $hit = $searchio->next_result;
203 Function: Returns the next Result from a search
204 Returns : FAST::Bio::Search::Result::ResultI object
205 Args : none
206  
207 =cut
208  
209 sub next_result {
210 my ($self) = @_;
211
212 my $result;
213  
214 my ($tfh);
215
216 # XMLCOMPACT
217 # WU-BLAST has an XML_COMPACT option which needs to be preprocessed before
218 # passing on to the parser.
219 if ($self->{_xml_compact}) {
220 $self->debug("XMLCOMPACT mode\n");
221 my ($tfh2, $filename) = IO::File->new_tmpfile or $self->throw("Unable to open temp file: $!");
222 $tfh2->autoflush(1);
223 my $fh = $self->_fh;
224 while (my $line = <$fh>) {
225 $line =~ s/></>\n</g;
226 print $tfh2 $line;
227 }
228 seek($tfh2,0,0);
229 close $fh;
230 # redirect self's IO to use new tempfile
231 $self->_fh($tfh2);
232 }
233
234 if( $self->use_tempfile ) {
235 $tfh = IO::File->new_tmpfile or $self->throw("Unable to open temp file: $!");
236 $tfh->autoflush(1);
237 }
238
239 my $okaytoprocess = ($self->blasttype =~ /PSI/) ? $self->_chunk_psiblast($tfh) :
240 $self->_chunk_normalblast($tfh);
241
242 return unless( $okaytoprocess);
243
244 my %parser_args;
245 if( defined $tfh ) {
246 seek($tfh,0,0);
247 %parser_args = ('Source' => { 'ByteStream' => $tfh });
248 } else {
249 %parser_args = ('Source' => { 'String' => $self->{'_blastdata'} });
250 }
251  
252 my $starttime;
253 if( $DEBUG ) { $starttime = [ Time::HiRes::gettimeofday() ]; }
254
255 eval {
256 $result = $self->{'_xmlparser'}->parse(%parser_args);
257 };
258
259 if( $@ ) {
260 $self->warn("error in parsing a report:\n $@");
261 $result = undef;
262 }
263 if( $DEBUG ) {
264 $self->debug( sprintf("parsing took %f seconds\n", Time::HiRes::tv_interval($starttime)));
265 }
266 # parsing magic here - but we call event handlers rather than
267 # instantiating things
268 if (defined $result) {
269 # result count is handled here, as the BLASTXML reports are
270 # broken up into smaller easier to digest bits
271 $self->{_result_count}++;
272 return $result;
273 } else {
274 return;
275 }
276 }
277  
278 =head2 result_count
279  
280 Title : result_count
281 Usage : $num = $stream->result_count;
282 Function: Gets the number of Blast results that have been successfully parsed
283 at the point of the method call. This is not the total # of results
284 in the file.
285 Returns : integer
286 Args : none
287 Throws : none
288  
289 =cut
290  
291 sub result_count {
292 my $self = shift;
293 return $self->{_result_count};
294 }
295  
296 =head2 use_tempfile
297  
298 Title : use_tempfile
299 Usage : $obj->use_tempfile($newval)
300 Function: Get/Set boolean flag on whether or not use a tempfile
301 Example :
302 Returns : value of use_tempfile
303 Args : newvalue (optional)
304  
305 =cut
306  
307 sub use_tempfile{
308 my ($self,$value) = @_;
309 if( defined $value) {
310 $self->{'_use_tempfile'} = $value;
311 }
312 return $self->{'_use_tempfile'};
313 }
314  
315 =head2 blasttype
316  
317 Title : blasttype
318 Usage : $obj->blasttype($newtype)
319 Function: Get/Set BLAST report type.
320 Returns : BLAST report type
321 Args : case-insensitive string of types BLAST or PSIBLAST (default: BLAST)
322 Note : this is used to determine how reports are 'chunked' (in cases
323 where multiple queries are submitted) and which XML handler
324 to use when parsing the report(s)
325  
326 =cut
327  
328 sub blasttype{
329 my ($self,$value) = @_;
330 if ($value) {
331 $self->throw("$value is not a supported BLAST type") unless exists $VALID_TYPE{$value};
332 my $ok;
333 eval {
334 $ok = $self->_load_module($VALID_TYPE{$value});
335 };
336 if ($@) {
337 print STDERR <<END;
338 $self: data module $VALID_TYPE{$value} cannot be found
339 Exception $@
340 For more information about the FAST::Bio::SearchIO::blastxml system please see the FAST::Bio::SearchIO::blastxml.
341 END
342 return unless $ok;
343 }
344 # BlastHandler does the heavy lifting
345 my $xmlhandler = $VALID_TYPE{$value}->new(-verbose => $self->verbose);
346
347 # The XML handler does the heavy work, passes data to object handler
348 if ($value =~ /^PSI/) {
349 my $handler = FAST::Bio::SearchIO::IteratedSearchResultEventBuilder->new();
350 $self->{'_handler'} = $handler; # cache
351 }
352 $xmlhandler->eventHandler($self->_eventHandler());
353  
354 # start up the parser factory
355 my $parserfactory = XML::SAX::ParserFactory->parser(
356 Handler => $xmlhandler);
357 $self->{'_xmlparser'} = $parserfactory;
358 $self->saxparser(ref($parserfactory));
359
360 $self->{'_blasttype'} = $value;
361 }
362 return $self->{'_blasttype'};
363 }
364  
365 sub saxparser {
366 my $self = shift;
367 return ref($self->{'_xmlparser'});
368 }
369  
370 sub _chunk_normalblast {
371 my ($self, $tfh) = @_;
372
373 local $/ = "\n";
374 local $_;
375 $self->{'_blastdata'} = '';
376
377 my ($sawxmlheader, $okaytoprocess);
378
379 my $mode = 'header';
380  
381 my $tail = << 'XML_END';
382 </BlastOutput_iterations>
383 </BlastOutput>
384 XML_END
385  
386 # no buffering needed (famous last words...)
387 my $fh = $self->_fh;
388
389 #chop up XML into edible bits for the parser
390 while( defined( my $line = <$fh>) ) {
391 next if $line =~ m{^\s*</BlastOutput_iterations>}xmso || $line =~ m{^</BlastOutput>}xmso;
392 if( $line =~ m{^RPS-BLAST}i ) {
393 $self->{'_type'} = 'RPS-BLAST';
394 next;
395 } elsif ($line =~ m{^<\?xml\sversion="1.0"}xms) {# <?xml version="1.0"?> & <?xml version="1.0" encoding="UTF-8"?>
396 delete $self->{'_header'} if exists $self->{'_header'};
397 $sawxmlheader++;
398 $mode = 'header';
399 } elsif ($line =~ m{^\s*<Iteration>}xmso) {
400 if (!$sawxmlheader) {
401 if (defined $tfh) {
402 print $tfh $self->{'_header'}
403 } else {
404 $self->{'_blastdata'} .= $self->{'_header'};
405 }
406 }
407 $mode = 'iteration';
408 } elsif ($line =~ m{^\s*</Iteration>}xmso) {
409 if (defined $tfh) {
410 print $tfh $line.$tail;
411 } else {
412 $self->{'_blastdata'} .= $line.$tail;
413 }
414 $okaytoprocess++;
415 last;
416 }
417 if (defined $tfh) {
418 print $tfh $line;
419 } else {
420 $self->{'_blastdata'} .= $line;
421 }
422 $self->{"_$mode"} .= $line if $mode eq 'header';
423 }
424 return $okaytoprocess;
425 }
426  
427 sub _chunk_psiblast {
428 my ($self, $tfh) = @_;
429
430 local $/ = "\n";
431 local $_;
432 $self->{'_blastdata'} = '';
433
434 my ($sawxmlheader, $okaytoprocess);
435  
436 # no buffering needed (famous last words...)
437 my $fh = $self->_fh;
438
439 #chop up XML into edible bits for the parser
440 while( defined( my $line = <$fh>) ) {
441 if (defined $tfh) {
442 print $tfh $line;
443 } else {
444 $self->{'_blastdata'} .= $line;
445 }
446 #$self->{"_$mode"} .= $line;
447 if ($line =~ m{^</BlastOutput>}xmso) {
448 $okaytoprocess++;
449 last;
450 }
451 }
452 #$self->debug($self->{'_blastdata'}."\n");
453 return $okaytoprocess;
454 }
455  
456 1;