Sync with main trunk
[bioperl-live.git] / Bio / PullParserI.pm
blobaf5f61b326ccd5ccfb3ce39f90ee7c18de56faf8
1 # $Id$
3 # BioPerl module for Bio::PullParserI
5 # Cared for by Sendu Bala <bix@sendu.me.uk>
7 # Copyright Sendu Bala
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::PullParserI - A base module for fast 'pull' parsing
17 =head1 SYNOPSIS
19 # do not use this class, it is intended for parser module
20 # writers only
22 =head1 DESCRIPTION
24 If you are writing a module to parse some new format, you may wish to use
25 a 'pull' approach whereby you only do work (reading file data, parsing it,
26 turning the parsed data in an object) when absolutely necessary.
28 PullParserI provides a system for doing exactly that. As a PullParser you
29 need a chunk. A chunk is just a Bio::Root::IO that contains all the raw data
30 you would want to parse. You can use the chunk() method to create a chunk from
31 a filename, existing filehandle or even a string. If you make a chunk from a
32 large file, but actually only want your chunk to be some portion of the whole
33 file, supply start and end amounts in bytes to chunk() at the same time.
34 The methods _chunk_seek() and _chunk_tell() provide seeks and tells that are
35 relative to the start and end of your chunk, not the whole file.
37 The other thing you will need to decide when making a chunk is how to handle
38 piped input. A PullParser typically needs seekable data to parse, so if your
39 data is piped in and unseekable, you must decide between creating a temp file
40 or reading the input into memory, which will be done before the chunk becomes
41 usable and you can begin any parsing. Alternatively you can choose to force
42 a sequential read, in which case you can make use of _dependencies() to define
43 the linear order of methods that would result in the file being read
44 sequentially. The return value of _sequential() is also useful here, if you
45 would need to cache some data or otherwise behave differently during a
46 sequential read.
48 The main method in the system is get_field(). This method relies on the
49 existance of a private hash reference accessible to it with the method
50 _fields(). That hash ref should have as keys all the sorts of data you will want
51 to parse (eg. 'score'), and prior to parsing the values would be undefined. A
52 user of your module can then call either $module-E<gt>get_field('score') or
53 $module-E<gt>score and get_field will either return the answer from
54 $self-E<gt>_fields-E<gt>{score} if it is defined, or call a method _discover_score()
55 first if not. So for the system to work you need to define a _discover_*()
56 method for every field in the fields hash, and ensure that the method stores an
57 answer in the fields hash.
59 How you implement your _discover_* methods is up to you, though you should never
60 call a _discover_* method directly yourself; always use get_field(), since
61 get_field() will deal with calling dependant methods for you if a forced
62 sequenctial read is in progress due to piped input. You will almost certainly
63 want to make use of the various chunk-related methods of this class (that are
64 denoted private by the leading '_'; this means you can use them as the author of
65 a parser class, but users of your parser should not).
67 Primary amongst them is _*_chunk_by_end() to which you provide text that
68 represents the end of your desired chunk and it does a readline with your
69 argument as $/. The chunk knows about its line-endings, so if you want your
70 end definition to include a new line, just always use "\n" and PullParserI will
71 do any necessary conversion for you.
73 If your input data is hierarchical (eg. report-E<gt>many results-E<gt>many hits-E<gt>many
74 hsps), and you want an object at the leaf of the hierarchy to have access to
75 information that is shared amongst all of them (is parsed in the root), you
76 don't have to copy the data to each leaf object; simply by defining parent(),
77 when you call get_field() and the requested field isn't in your leaf's fields
78 hash, the leaf's parent will be asked for the field instead, and so on till
79 root.
81 See Bio::SearchIO::hmmer_pull for an example of implementing a parser using
82 PullParserI.
84 =head1 FEEDBACK
86 =head2 Mailing Lists
88 User feedback is an integral part of the evolution of this and other
89 Bioperl modules. Send your comments and suggestions preferably to
90 the Bioperl mailing list. Your participation is much appreciated.
92 bioperl-l@bioperl.org - General discussion
93 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
95 =head2 Reporting Bugs
97 Report bugs to the Bioperl bug tracking system to help us keep track
98 of the bugs and their resolution. Bug reports can be submitted via the
99 web:
101 http://bugzilla.open-bio.org/
103 =head1 AUTHOR - Sendu Bala
105 Email bix@sendu.me.uk
107 =head1 CONTRIBUTORS
109 Inspired by a posting by Aaron J. Mackey
111 =head1 APPENDIX
113 The rest of the documentation details each of the object methods.
114 Internal methods are usually preceded with a _
116 =cut
118 # Let the code begin...
120 package Bio::PullParserI;
122 use vars qw($AUTOLOAD $FORCE_TEMP_FILE);
123 use strict;
125 use Bio::Root::IO;
127 use base qw(Bio::Root::RootI);
129 BEGIN {
130 # chunk() needs perl 5.8 feature for modes other than temp_file, so will
131 # workaround by forcing temp_file mode in <5.8. Could also rewrite using
132 # IO::String, but don't want to.
133 if ($] < 5.008) {
134 $FORCE_TEMP_FILE = 1;
138 =head2 _fields
140 Title : _fields
141 Usage : $obj->_fields( { field1 => undef } );
142 my $fields_ref = $obj->_fields;
143 Function: Get/set the hash reference containing all the fields for this parser
144 Returns : hash ref
145 Args : none to get, OR hash ref to set
147 =cut
149 sub _fields {
150 my $self = shift;
151 if (@_) {
152 $self->{_fields} = shift;
154 unless (defined $self->{_fields}) {
155 $self->{_fields} = { };
157 return $self->{_fields};
160 =head2 has_field
162 Title : has_field
163 Usage : if ($obj->has_field('field_name') {...}
164 Function: Ask if a particular object has a given field (doesn't ask ancestors)
165 Returns : boolean
166 Args : string (the field name to test)
168 =cut
170 sub has_field {
171 my ($self, $desired) = @_;
172 $desired || return;
173 return exists $self->_fields->{$desired};
176 =head2 get_field
178 Title : get_field
179 Usage : my $field_value = $obj->get_field('field_name');
180 Function: Get the value of a given field. If this $obj doesn't have the field,
181 it's parent() will be asked, and so on until there are no more
182 parents.
183 Returns : scalar, warns if a value for the field couldn't be found and returns
184 undef.
185 Args : string (the field to get)
187 =cut
189 sub get_field {
190 my $self = shift;
191 my $desired = shift || return keys %{$self->_fields};
192 if (exists $self->_fields->{$desired}) {
193 unless (defined $self->_fields->{$desired}) {
194 my $method = '_discover_'.$desired;
196 my $dependency = $self->_dependencies($desired);
197 if ($dependency && ! defined $self->_fields->{$dependency}) {
198 $self->get_field($dependency);
201 # it might exist now
202 $self->$method unless defined $self->_fields->{$desired};
204 return $self->_fields->{$desired};
207 # is it a field of our parent? (checks all ancestors)
208 if (my $parent = $self->parent) {
209 return $parent->get_field($desired);
212 $desired =~ s/_discover_//;
213 $self->warn("This report does not hold information about '$desired'");
214 return;
217 =head2 parent
219 Title : parent
220 Usage : $obj->parent($parent_obj);
221 my $parent_obj = $obj->parent;
222 Function: Get/set the parent object of this one.
223 Returns : Bio::PullParserI
224 Args : none to get, OR Bio::PullParserI to set
226 =cut
228 sub parent {
229 my $self = shift;
230 if (@_) { $self->{parent} = shift }
231 return $self->{parent} || return;
234 =head2 chunk
236 Title : chunk
237 Usage : $obj->chunk($filename);
238 my $chunk = $obj->chunk;
239 Function: Get/set the chunk of this parser.
240 Returns : Bio:Root::IO
241 Args : none to get, OR
242 First argument of a GLOB reference, filename string, string data to
243 treat as the chunk, or Bio::Root::IO.
244 Optionally, also provide:
245 -start => int : the byte position within the thing described by the
246 first arguement to consider as the start of this
247 chunk (default 0)
248 -end => int : the byte position to consider as the end (default
249 true end)
250 -piped_behaviour => 'memory'|'temp_file'|'sequential_read'
252 The last option comes into effect when the first argument is
253 something that cannot be seeked (eg. piped input filehandle).
254 'memory' means read all the piped input into a string
255 first, then set the chunk to that string.
256 'temp_file' means read all the piped input and output it to
257 a temp file, then set the chunk to that temp file.
258 'sequential_read' means that the piped input should be read
259 sequentially and your parsing code must cope with
260 not being able to seek.
261 'memory' is the fastest but uses the most memory. 'temp_file' and
262 'sequential_read' can be slow, with 'temp_file' being the most memory
263 efficient but requiring disc space. The default is 'sequential_read'.
264 Note that in versions of perl earlier than 5.8 only temp_file works
265 and will be used regardless of what value is supplied here.
267 =cut
269 sub chunk {
270 my $self = shift;
272 if (@_) {
273 my $thing = shift || $self->throw("Trying to set chunk() to an undefined value");
274 if (ref($thing) eq 'GLOB') {
275 $self->{_chunk} = Bio::Root::IO->new(-fh => $thing);
277 elsif (ref(\$thing) eq 'SCALAR') {
278 if ($thing !~ /\n/ && -e $thing) {
279 $self->{_chunk} = Bio::Root::IO->new(-file => $thing);
281 else {
282 unless ($FORCE_TEMP_FILE) {
283 # treat a string as a filehandle
284 open(my $fake_fh, "+<", \$thing); # requires perl 5.8
285 $self->{_chunk} = Bio::Root::IO->new(-fh => $fake_fh);
287 else {
288 my ($handle) = $self->{_chunk}->tempfile();
289 print $handle $thing;
290 $self->{_chunk} = Bio::Root::IO->new(-fh => $handle);
294 elsif ($thing->isa('Bio::Root::IO')) {
295 $self->{_chunk} = $thing;
297 else {
298 $self->throw("Unknown input into chunk()");
301 my ($piped_behaviour, $start, $end);
302 if (@_) {
303 ($piped_behaviour, $start, $end) =
304 $self->_rearrange([qw(PIPED_BEHAVIOUR START END)], @_);
306 $piped_behaviour ||= 'sequential_read';
307 $FORCE_TEMP_FILE && ($piped_behaviour = 'temp_file');
308 $start ||= 0;
309 $self->_chunk_true_start($start);
310 $self->_chunk_true_end($end);
312 # determine if the chunk is seekable
313 my $fh = $self->{_chunk}->_fh;
314 seek($fh, 0, 0);
315 my $first_line = <$fh>;
316 seek($fh, 0, 0);
317 my $seekable = tell($fh) == 0;
318 unless ($seekable) {
319 if ($piped_behaviour eq 'memory') {
320 my $string = $first_line;
321 while (<$fh>) {
322 $string .= $_;
324 $self->chunk($string);
326 elsif ($piped_behaviour eq 'temp_file') {
327 my ($handle) = $self->{_chunk}->tempfile();
328 print $handle $first_line;
329 while (<$fh>) {
330 print $handle $_;
332 seek($handle, 0, 0);
333 $self->chunk($handle);
335 elsif ($piped_behaviour eq 'sequential_read') {
336 $self->{_chunk}->_pushback($first_line);
337 $self->_sequential(1);
339 else {
340 $self->throw("Unknown piped behaviour type '$piped_behaviour'");
344 # determine our line ending
345 if ($first_line =~ /\r\n/) {
346 $self->_line_ending("\r\n");
348 elsif ($first_line =~ /\r/) {
349 $self->_line_ending("\r");
351 else {
352 $self->_line_ending("\n");
356 return $self->{_chunk} || return;
359 =head2 _sequential
361 Title : _sequential
362 Usage : if ($obj->_sequential) {...}
363 Function: Ask if we have to do operations such that the input is read
364 sequentially.
365 Returns : boolean
366 Args : none to get, OR boolean to set (typically, you should never set this
367 yourself)
369 =cut
371 sub _sequential {
372 my $self = shift;
373 if (@_) {
374 $self->{_sequential} = shift;
376 return $self->{_sequential} || 0;
379 =head2 _dependencies
381 Title : _dependencies
382 Usage : $obj->_dependencies( { field1 => field2 } );
383 my $dependancy = $obj->_dependencies('field_name');
384 Function: Set the fields that are dependent on each other, or get the field
385 than another is dependent upon.
386 Returns : string (a field name)
387 Args : string (a field name) to get, OR hash ref to initially set, with
388 field names as keys and values, key field being dependent upon value
389 field.
391 =cut
393 sub _dependencies {
394 my ($self, $thing) = @_;
395 $thing || return;
396 if (ref($thing) eq 'HASH') {
397 $self->{_dependencies} = $thing;
399 else {
400 return $self->{_dependencies}->{$thing};
404 =head2 _chunk_true_start
406 Title : _chunk_true_start
407 Usage : my $true_start = $obj->_chunk_true_start;
408 Function: Get/set the true start position of the chunk within the filehandle
409 it is part of.
410 Returns : int
411 Args : none to get, OR int to set (typically, you won't set this yourself)
413 =cut
415 sub _chunk_true_start {
416 my $self = shift;
417 if (@_) {
418 $self->{_chunk_start} = shift;
420 return $self->{_chunk_start} || 0;
423 =head2 _chunk_true_end
425 Title : _chunk_true_end
426 Usage : my $true_end = $obj->_chunk_true_end;
427 Function: Get/set for the true end position of the chunk within the filehandle
428 it is part of.
429 Returns : int
430 Args : none to get, OR int to set (typically, you won't set this yourself)
432 =cut
434 sub _chunk_true_end {
435 my $self = shift;
436 if (@_) {
437 $self->{_chunk_end} = shift;
439 return $self->{_chunk_end};
442 =head2 _line_ending
444 Title : _line_ending
445 Usage : my $line_ending = $obj->_line_ending;
446 Function: Get/set for the line ending for the chunk.
447 Returns : string
448 Args : none to get, OR string to set (typically, you won't set this
449 yourself)
451 =cut
453 sub _line_ending {
454 my $self = shift;
455 if (@_) {
456 $self->{_chunk_line_ending} = shift;
458 return $self->{_chunk_line_ending};
461 =head2 _chunk_seek
463 Title : _chunk_seek
464 Usage : $obj->_chunk_seek($pos);
465 Function: seek() the chunk to the provided position in bytes, relative to the
466 defined start of the chunk within its filehandle.
468 In _sequential() mode, this function does nothing.
470 Returns : n/a
471 Args : int
473 =cut
475 sub _chunk_seek {
476 my ($self, $pos) = @_;
477 return if $self->_sequential;
479 my $fh = $self->chunk->_fh;
481 # seek to the defined start
482 seek($fh, $self->_chunk_true_start, 0);
484 # now seek to desired position relative to defined start
485 seek($fh, $pos, 1);
488 =head2 _chunk_tell
490 Title : _chunk_seek
491 Usage : my $pos = $obj->_chunk_tell;
492 Function: Get the current tell() position within the chunk, relative to the
493 defined start of the chunk within its filehandle.
495 In _sequential() mode, this function does nothing.
497 Returns : int
498 Args : none
500 =cut
502 sub _chunk_tell {
503 my $self = shift;
504 return if $self->_sequential;
506 my $fh = $self->chunk->_fh;
507 return tell($fh) - $self->_chunk_true_start;
510 =head2 _get_chunk_by_nol
512 Title : _chunk_seek
513 Usage : my $string = $obj->_get_chunk_by_nol;
514 Function: Get a chunk of chunk() from the current position onward for the given
515 number of lines.
516 Returns : string
517 Args : int (number of lines you want)
519 =cut
521 sub _get_chunk_by_nol {
522 my ($self, $nol) = @_;
523 $nol > 0 || $self->throw("Can't request a chunk of fewer than 1 lines");
525 # hope that $/ is \n
527 my ($line, $count);
528 while (defined($_ = $self->chunk->_readline)) {
529 $line .= $_;
530 $count++;
531 last if $count == $nol;
534 my $current = $self->_chunk_tell;
535 my $end = ($current || 0) + $self->_chunk_true_start;
536 if (! $current || ($self->_chunk_true_end ? $end <= $self->_chunk_true_end : 1)) {
537 return $line;
539 return;
542 =head2 _get_chunk_by_end
544 Title : _get_chunk_by_end
545 Usage : my $string = $obj->_get_chunk_by_end;
546 Function: Get a chunk of chunk() from the current position onward till the end
547 of the line, as defined by the supplied argument.
548 Returns : string
549 Args : string (line ending - if you want the line ending to include a new
550 line, always use \n)
552 =cut
554 sub _get_chunk_by_end {
555 my ($self, $chunk_ending) = @_;
557 my $start = $self->_chunk_tell;
559 my $line_ending = $self->_line_ending;
560 $chunk_ending =~ s/\n/$line_ending/g;
561 local $/ = $chunk_ending || '';
562 my $line = $self->chunk->_readline;
564 my $current = $self->_chunk_tell;
565 my $end = ($current || 0) + $self->_chunk_true_start;
566 if (! $current || ($self->_chunk_true_end ? $end <= $self->_chunk_true_end : 1)) {
567 return $line;
570 $self->_chunk_seek($start);
571 return;
574 =head2 _find_chunk_by_end
576 Title : _find_chunk_by_end
577 Usage : my $string = $obj->_find_chunk_by_end;
578 Function: Get the start and end of what would be a chunk of chunk() from the
579 current position onward till the end of the line, as defined by the
580 supplied argument.
582 In _sequential() mode, this function does nothing.
584 Returns : _chunk_tell values for start and end in 2 element list
585 Args : string (line ending - if you want the line ending to include a new
586 line, always use \n)
588 =cut
590 sub _find_chunk_by_end {
591 my ($self, $chunk_ending) = @_;
592 return if $self->_sequential;
594 my $line_ending = $self->_line_ending;
595 $chunk_ending =~ s/\n/$line_ending/g;
596 local $/ = $chunk_ending || '';
598 my $start = $self->_chunk_tell;
599 $self->chunk->_readline;
600 my $end = $self->_chunk_tell;
602 my $comp_end = $end + $self->_chunk_true_start;
603 if ($self->_chunk_true_end ? $comp_end <= $self->_chunk_true_end : 1) {
604 return ($start, $end);
607 $self->_chunk_seek($start);
608 return;
611 =head2 AUTOLOAD
613 Title : AUTOLOAD
614 Usage : n/a
615 Function: Assumes that any unknown method called should be treated as
616 get_field($method_name).
617 Returns : n/a
618 Args : n/a
620 =cut
622 sub AUTOLOAD {
623 my $self = shift;
624 ref($self) || return;
626 my $name = $AUTOLOAD;
627 $name =~ s/.*://; # strip fully-qualified portion
629 # is it one of our fields?
630 return $self->get_field($name);