Merge pull request #24 from carandraug/bp_genbank_ref_extractor
[bioperl-live.git] / Bio / FeatureIO.pm
blob062dca0c93027ade5f2ba6aa40c5f02a7a4ad326
2 # BioPerl module for Bio::FeatureIO
4 # Please direct questions and support issues to <bioperl-l@bioperl.org>
6 # Cared for by Allen Day <allenday@ucla.edu>
8 # Copyright Allen Day
10 # You may distribute this module under the same terms as perl itself
12 # POD documentation - main docs before the code
14 =head1 NAME
16 Bio::FeatureIO - Handler for FeatureIO
18 =head1 SYNOPSIS
20 use Bio::FeatureIO;
22 #read from a file
23 $in = Bio::FeatureIO->new(-file => "my.gff" , -format => 'GFF');
25 #read from a filehandle
26 $in = Bio::FeatureIO->new(-fh => \*GFF , -format => 'GFF');
28 #read features already attached to a sequence
29 my $feat = Bio::FeatureIO->new(-seq => $seq , -format => 'features');
31 #read new features for existing sequence
32 my $seq = Bio::FeatureIO->new(-seq => $seq , -format => 'Das');
34 #write out features
35 $out = Bio::FeatureIO->new(-file => ">outputfilename" ,
36 -format => 'GFF' ,
37 -version => 3);
39 while ( my $feature = $in->next_feature() ) {
40 $out->write_feature($feature);
43 =head1 DESCRIPTION
45 NOTE: This is a highly experimental I/O iterator subsystem for genomic sequence
46 features. It is not complete, and is now undergoing a significant refactoring in
47 a separate branch of BioPerl to address specific issues regarding the current
48 implementation. Use at your own risk.
50 Bio::FeatureIO is a handler module for the formats in the FeatureIO set (eg,
51 Bio::FeatureIO::GFF).
53 The Bio::FeatureIO system can be thought of like biological file handles.
54 They are attached to filehandles with smart formatting rules (eg,
55 GFF format, or BED format) and
56 can either read or write feature objects (Bio::SeqFeature objects, or
57 more correctly, Bio::FeatureHolderI implementing objects, of which
58 Bio::SeqFeature is one such object). If you want to know what to
59 do with a Bio::SeqFeatureI object, read L<Bio::SeqFeatureI>.
61 The idea is that you request a stream object for a particular format.
62 All the stream objects have a notion of an internal file that is read
63 from or written to. A particular FeatureIO object instance is configured
64 for either input or output. A specific example of a stream object is
65 the Bio::FeatureIO::gff object.
67 Each stream object has functions:
69 $stream->next_feature();
70 $stream->write_feature($feature);
72 =head1 SUPPORTED FORMATS
74 name module
75 -----------------------------------
76 BED bed.pm
77 GFF gff.pm
78 GTF gtf.pm
79 InterPro (IPRScan 4.0) interpro.pm
80 PTT (NCBI protein table) ptt.pm
83 =head1 CONSTRUCTORS
85 =head2 Bio::FeatureIO-E<gt>new()
87 $featureIO = Bio::FeatureIO->new(-file => 'filename', -format=>$format);
88 $featureIO = Bio::FeatureIO->new(-fh => \*FILEHANDLE, -format=>$format);
89 $featureIO = Bio::FeatureIO->new(-seq => $seq, -format=>$format);
91 The new() class method constructs a new Bio::FeatureIO object. The
92 returned object can be used to retrieve or print Seq objects. new()
93 accepts the following parameters:
95 =over 4
97 =item -file
99 A file path to be opened for reading or writing. The usual Perl
100 conventions apply:
102 'file' # open file for reading
103 '>file' # open file for writing
104 '>>file' # open file for appending
105 '+<file' # open file read/write
106 'command |' # open a pipe from the command
107 '| command' # open a pipe to the command
109 =item -fh
111 You may provide new() with a previously-opened filehandle. For
112 example, to read from STDIN:
114 $featio = Bio::FeatureIO->new(-fh => \*STDIN);
116 Note that you must pass filehandles as references to globs.
118 If neither a filehandle nor a filename is specified, then the module
119 will read from the @ARGV array or STDIN, using the familiar E<lt>E<gt>
120 semantics.
122 A string filehandle is handy if you want to modify the output in the
123 memory, before printing it out. The following program reads in EMBL
124 formatted entries from a file and prints them out in fasta format with
125 some HTML tags:
127 use Bio::FeatureIO;
128 use IO::String;
129 my $in = Bio::FeatureIO->new('-file' => "my.gff" ,
130 '-format' => 'EMBL');
131 while ( my $f = $in->next_feature() ) {
132 # the output handle is reset for every file
133 my $stringio = IO::String->new($string);
134 my $out = Bio::FeatureIO->new('-fh' => $stringio,
135 '-format' => 'gtf');
136 # output goes into $string
137 $out->write_feature($f);
138 # modify $string
139 $string =~ s|(>)(\w+)|$1<font color="Red">$2</font>|g;
140 # print into STDOUT
141 print $string;
144 =item -format
146 Specify the format of the file. See above for list of supported formats
148 =item -flush
150 By default, all files (or filehandles) opened for writing sequences
151 will be flushed after each write_seq() (making the file immediately
152 usable). If you don't need this facility and would like to marginally
153 improve the efficiency of writing multiple sequences to the same file
154 (or filehandle), pass the -flush option '0' or any other value that
155 evaluates as defined but false:
157 my $f1 = Bio::FeatureIO->new -file => "<a.f1",
158 -format => "f1";
159 my $f2 = Bio::FeatureIO->new -file => ">a.f2",
160 -format => "f2",
161 -flush => 0; # go as fast as we can!
163 while($feature = $f1->next_feature) { $f2->write_feature($feature) }
165 =back
167 =head2 Bio::FeatureIO-E<gt>newFh()
169 $fh = Bio::FeatureIO->newFh(-fh => \*FILEHANDLE, -format=>$format);
170 $fh = Bio::FeatureIO->newFh(-format => $format);
171 # etc.
173 This constructor behaves like new(), but returns a tied filehandle
174 rather than a Bio::FeatureIO object. You can read sequences from this
175 object using the familiar E<lt>E<gt> operator, and write to it using
176 print(). The usual array and $_ semantics work. For example, you can
177 read all sequence objects into an array like this:
179 @features = <$fh>;
181 Other operations, such as read(), sysread(), write(), close(), and printf()
182 are not supported.
184 =head1 OBJECT METHODS
186 See below for more detailed summaries. The main methods are:
188 =head2 $feature = $featureIO-E<gt>next_feature()
190 Fetch the next feature from the stream.
192 =head2 $featureIO-E<gt>write_feature($feature [,$another_feature,...])
194 Write the specified feature(s) to the stream.
196 =head2 TIEHANDLE(), READLINE(), PRINT()
198 These provide the tie interface. See L<perltie> for more details.
200 =head1 FEEDBACK
202 =head2 Mailing Lists
204 User feedback is an integral part of the evolution of this
205 and other Bioperl modules. Send your comments and suggestions preferably
206 to one of the Bioperl mailing lists.
208 Your participation is much appreciated.
210 bioperl-l@bioperl.org - General discussion
211 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
213 =head2 Support
215 Please direct usage questions or support issues to the mailing list:
217 I<bioperl-l@bioperl.org>
219 rather than to the module maintainer directly. Many experienced and
220 reponsive experts will be able look at the problem and quickly
221 address it. Please include a thorough description of the problem
222 with code and data examples if at all possible.
224 =head2 Reporting Bugs
226 Report bugs to the Bioperl bug tracking system to help us keep track
227 the bugs and their resolution. Bug reports can be submitted via the
228 web:
230 https://redmine.open-bio.org/projects/bioperl/
232 =head1 AUTHOR - Allen Day
234 Email allenday@ucla.edu
236 =head1 APPENDIX
238 The rest of the documentation details each of the object
239 methods. Internal methods are usually preceded with a _
241 =cut
243 #' Let the code begin...
245 package Bio::FeatureIO;
247 use strict;
249 use Symbol;
251 use base qw(Bio::Root::Root Bio::Root::IO);
253 =head2 new
255 Title : new
256 Usage : $stream = Bio::FeatureIO->new(-file => $filename, -format => 'Format')
257 Function: Returns a new feature stream
258 Returns : A Bio::FeatureIO stream initialised with the appropriate format
259 Args : Named parameters:
260 -file => $filename
261 -fh => filehandle to attach to
262 -format => format
264 =cut
266 my $entry = 0;
268 sub new {
269 my ($caller,@args) = @_;
270 my $class = ref($caller) || $caller;
272 # or do we want to call SUPER on an object if $caller is an
273 # object?
274 if( $class =~ /Bio::FeatureIO::(\S+)/ ) {
276 my ($self) = $class->SUPER::new(@args);
277 $self->_initialize(@args);
278 return $self;
280 } else {
282 my %param = @args;
284 @param{ map { lc $_ } keys %param } = values %param; # lowercase keys
285 my $format = $param{'-format'} ||
286 $class->_guess_format( $param{-file} || $ARGV[0] );
288 if( ! $format ) {
289 if ($param{-file}) {
290 $format = $class->_guess_format($param{-file});
291 } elsif ($param{-fh}) {
292 $format = $class->_guess_format(undef);
295 $format = "\L$format"; # normalize capitalization to lower case
296 return unless( $class->_load_format_module($format) );
297 return "Bio::FeatureIO::$format"->new(@args);
302 =head2 newFh
304 Title : newFh
305 Usage : $fh = Bio::FeatureIO->newFh(-file=>$filename,-format=>'Format')
306 Function: does a new() followed by an fh()
307 Example : $fh = Bio::FeatureIO->newFh(-file=>$filename,-format=>'Format')
308 $feature = <$fh>; # read a feature object
309 print $fh $feature; # write a feature object
310 Returns : filehandle tied to the Bio::FeatureIO::Fh class
311 Args :
313 See L<Bio::FeatureIO::Fh>
315 =cut
317 sub newFh {
318 my $class = shift;
319 return unless my $self = $class->new(@_);
320 return $self->fh;
323 =head2 fh
325 Title : fh
326 Usage : $obj->fh
327 Function:
328 Example : $fh = $obj->fh; # make a tied filehandle
329 $feature = <$fh>; # read a feature object
330 print $fh $feature; # write a feature object
331 Returns : filehandle tied to Bio::FeatureIO class
332 Args : none
334 =cut
337 sub fh {
338 my $self = shift;
339 my $class = ref($self) || $self;
340 my $s = Symbol::gensym;
341 tie $$s,$class,$self;
342 return $s;
345 =head2 format
347 Title : format
348 Usage : $format = $stream->format()
349 Function: Get the feature format
350 Returns : feature format
351 Args : none
353 =cut
355 # format() method inherited from Bio::Root::IO
358 # _initialize is chained for all FeatureIO classes
360 sub _initialize {
361 my($self, %arg) = @_;
363 # flush is initialized by the Root::IO init
365 # initialize the IO part
366 $self->seq($arg{-seq});
367 $self->_initialize_io(%arg);
370 =head2 next_feature
372 Title : next_feature
373 Usage : $feature = stream->next_feature
374 Function: Reads the next feature object from the stream and returns it.
376 Certain driver modules may encounter entries in the stream
377 that are either misformatted or that use syntax not yet
378 understood by the driver. If such an incident is
379 recoverable, e.g., by dismissing a feature of a feature
380 table or some other non-mandatory part of an entry, the
381 driver will issue a warning. In the case of a
382 non-recoverable situation an exception will be thrown. Do
383 not assume that you can resume parsing the same stream
384 after catching the exception. Note that you can always turn
385 recoverable errors into exceptions by calling
386 $stream->verbose(2).
388 Returns : a Bio::SeqFeatureI feature object
389 Args : none
391 See L<Bio::Root::RootI>, L<Bio::SeqFeatureI>
393 =cut
395 sub next_feature {
396 my ($self, $seq) = @_;
397 $self->throw("Sorry, you cannot read from a generic Bio::FeatureIO object.");
400 =head2 write_feature
402 Title : write_feature
403 Usage : $stream->write_feature($feature)
404 Function: writes the $feature object into the stream
405 Returns : 1 for success and 0 for error
406 Args : Bio::SeqFeature object
408 =cut
410 sub write_feature {
411 my ($self, $seq) = @_;
412 if(ref($self) eq __PACKAGE__){
413 $self->throw("Sorry, you cannot write to a generic Bio::FeatureIO object.");
414 } else {
415 $self->throw_not_implemented();
419 =head2 _load_format_module
421 Title : _load_format_module
422 Usage : *INTERNAL FeatureIO stuff*
423 Function: Loads up (like use) a module at run time on demand
424 Example :
425 Returns :
426 Args :
428 =cut
430 sub _load_format_module {
431 my ($self, $format) = @_;
432 my $class = ref($self) || $self;
433 my $module = $class."::$format";#"Bio::Feature::" . $format;
434 my $ok;
436 eval {
437 $ok = $self->_load_module($module);
439 if ( $@ ) {
440 print STDERR <<END;
441 $self: $format cannot be found
442 Exception $@
443 For more information about the FeatureIO system please see the FeatureIO docs.
444 This includes ways of checking for formats at compile time, not run time
448 return $ok;
451 =head2 seq
453 Title : seq
454 Usage : $obj->seq() OR $obj->seq($newSeq)
455 Example :
456 Returns : Bio::SeqI object
457 Args : newSeq (optional)
459 =cut
461 sub seq {
462 my $self = shift;
463 my $val = shift;
465 $self->{'seq'} = $val if defined($val);
466 return $self->{'seq'};
469 =head2 _filehandle
471 Title : _filehandle
472 Usage : $obj->_filehandle($newval)
473 Function: This method is deprecated. Call _fh() instead.
474 Example :
475 Returns : value of _filehandle
476 Args : newvalue (optional)
479 =cut
481 sub _filehandle {
482 my ($self,@args) = @_;
483 return $self->_fh(@args);
486 =head2 _guess_format
488 Title : _guess_format
489 Usage : $obj->_guess_format($filename)
490 Function: guess format based on file suffix
491 Example :
492 Returns : guessed format of filename (lower case)
493 Args :
494 Notes : See "SUPPORTED FORMATS"
496 =cut
498 sub _guess_format {
499 my $class = shift;
500 return unless $_ = shift;
501 return 'gff' if /\.gff3?$/i;
502 return 'gff' if /\.gtf$/i;
503 return 'bed' if /\.bed$/i;
504 return 'ptt' if /\.ptt$/i;
506 return 'gff'; #the default
509 sub DESTROY {
510 my $self = shift;
511 $self->close();
514 sub TIEHANDLE {
515 my ($class,$val) = @_;
516 return bless {'featio' => $val}, $class;
519 sub READLINE {
520 my $self = shift;
521 return $self->{'featio'}->next_feature() unless wantarray;
522 my (@list, $obj);
523 push @list, $obj while $obj = $self->{'featio'}->next_feature();
524 return @list;
527 sub PRINT {
528 my $self = shift;
529 $self->{'featio'}->write_feature(@_);