[bug 2663]
[bioperl-live.git] / Bio / AlignIO.pm
blobc7875103f80f8cbf5b64118a0591e04730d9e60d
1 # $Id$
3 # BioPerl module for Bio::AlignIO
5 # based on the Bio::SeqIO module
6 # by Ewan Birney <birney@ebi.ac.uk>
7 # and Lincoln Stein <lstein@cshl.org>
9 # Copyright Peter Schattner
11 # You may distribute this module under the same terms as perl itself
13 # History
14 # September, 2000 AlignIO written by Peter Schattner
16 # POD documentation - main docs before the code
18 =head1 NAME
20 Bio::AlignIO - Handler for AlignIO Formats
22 =head1 SYNOPSIS
24 use Bio::AlignIO;
26 $inputfilename = "testaln.fasta";
27 $in = Bio::AlignIO->new(-file => $inputfilename ,
28 -format => 'fasta');
29 $out = Bio::AlignIO->new(-file => ">out.aln.pfam" ,
30 -format => 'pfam');
32 while ( my $aln = $in->next_aln() ) {
33 $out->write_aln($aln);
36 # OR
38 use Bio::AlignIO;
40 open MYIN,"testaln.fasta";
41 $in = Bio::AlignIO->newFh(-fh => \*MYIN,
42 -format => 'fasta');
43 open my $MYOUT, '>', 'testaln.pfam';
44 $out = Bio::AlignIO->newFh(-fh => $MYOUT,
45 -format => 'pfam');
47 # World's smallest Fasta<->pfam format converter:
48 print $out $_ while <$in>;
50 =head1 DESCRIPTION
52 L<Bio::AlignIO> is a handler module for the formats in the AlignIO set,
53 for example, L<Bio::AlignIO::fasta>. It is the officially sanctioned way
54 of getting at the alignment objects. The resulting alignment is a
55 L<Bio::Align::AlignI>-compliant object.
57 The idea is that you request an object for a particular format.
58 All the objects have a notion of an internal file that is read
59 from or written to. A particular AlignIO object instance is configured
60 for either input or output, you can think of it as a stream object.
62 Each object has functions:
64 $stream->next_aln();
66 And:
68 $stream->write_aln($aln);
70 Also:
72 $stream->type() # returns 'INPUT' or 'OUTPUT'
74 As an added bonus, you can recover a filehandle that is tied to the
75 AlignIO object, allowing you to use the standard E<lt>E<gt> and print
76 operations to read and write alignment objects:
78 use Bio::AlignIO;
80 # read from standard input
81 $stream = Bio::AlignIO->newFh(-format => 'Fasta');
83 while ( $aln = <$stream> ) {
84 # do something with $aln
87 And:
89 print $stream $aln; # when stream is in output mode
91 L<Bio::AlignIO> is patterned on the L<Bio::SeqIO> module and shares
92 most of its features. One significant difference is that
93 L<Bio::AlignIO> usually handles IO for only a single alignment at a time,
94 whereas L<Bio::SeqIO> handles IO for multiple sequences in a single stream.
95 The principal reason for this is that whereas simultaneously handling
96 multiple sequences is a common requirement, simultaneous handling of
97 multiple alignments is not. The only current exception is format
98 C<bl2seq> which parses results of the BLAST C<bl2seq> program and which
99 may produce several alignment pairs. This set of alignment pairs can
100 be read using multiple calls to L<next_aln>.
102 =head1 CONSTRUCTORS
104 =head2 Bio::AlignIO-E<gt>new()
106 $seqIO = Bio::AlignIO->new(-file => 'filename', -format=>$format);
107 $seqIO = Bio::AlignIO->new(-fh => \*FILEHANDLE, -format=>$format);
108 $seqIO = Bio::AlignIO->new(-format => $format);
109 $seqIO = Bio::AlignIO->new(-fh => \*STDOUT, -format => $format);
111 The L<new> class method constructs a new L<Bio::AlignIO> object.
112 The returned object can be used to retrieve or print alignment
113 objects. L<new> accepts the following parameters:
115 =over 4
117 =item -file
119 A file path to be opened for reading or writing. The usual Perl
120 conventions apply:
122 'file' # open file for reading
123 '>file' # open file for writing
124 '>>file' # open file for appending
125 '+<file' # open file read/write
126 'command |' # open a pipe from the command
127 '| command' # open a pipe to the command
129 =item -fh
131 You may provide new() with a previously-opened filehandle. For
132 example, to read from STDIN:
134 $seqIO = Bio::AlignIO->new(-fh => \*STDIN);
136 Note that you must pass filehandles as references to globs.
138 If neither a filehandle nor a filename is specified, then the module
139 will read from the @ARGV array or STDIN, using the familiar E<lt>E<gt>
140 semantics.
142 =item -format
144 Specify the format of the file. Supported formats include:
146 bl2seq Bl2seq Blast output
147 clustalw clustalw (.aln) format
148 emboss EMBOSS water and needle format
149 fasta FASTA format
150 maf Multiple Alignment Format
151 mase mase (seaview) format
152 mega MEGA format
153 meme MEME format
154 msf msf (GCG) format
155 nexus Swofford et al NEXUS format
156 pfam Pfam sequence alignment format
157 phylip Felsenstein PHYLIP format
158 prodom prodom (protein domain) format
159 psi PSI-BLAST format
160 selex selex (hmmer) format
161 stockholm stockholm format
163 Currently only those formats which were implemented in L<Bio::SimpleAlign>
164 have been incorporated into L<Bio::AlignIO>. Specifically, C<mase>, C<stockholm>
165 and C<prodom> have only been implemented for input. See the specific module
166 (e.g. L<Bio::AlignIO::prodom>) for notes on supported versions.
168 If no format is specified and a filename is given, then the module
169 will attempt to deduce it from the filename suffix. If this is unsuccessful,
170 C<fasta> format is assumed.
172 The format name is case insensitive; C<FASTA>, C<Fasta> and C<fasta> are
173 all treated equivalently.
175 =back
177 =head2 Bio::AlignIO-E<gt>newFh()
179 $fh = Bio::AlignIO->newFh(-fh => \*FILEHANDLE, -format=>$format);
180 # read from STDIN or use @ARGV:
181 $fh = Bio::AlignIO->newFh(-format => $format);
183 This constructor behaves like L<new>, but returns a tied filehandle
184 rather than a L<Bio::AlignIO> object. You can read sequences from this
185 object using the familiar E<lt>E<gt> operator, and write to it using
186 L<print>. The usual array and $_ semantics work. For example, you can
187 read all sequence objects into an array like this:
189 @sequences = <$fh>;
191 Other operations, such as read(), sysread(), write(), close(), and printf()
192 are not supported.
194 =over 1
196 =item -flush
198 By default, all files (or filehandles) opened for writing alignments
199 will be flushed after each write_aln() making the file immediately
200 usable. If you do not need this facility and would like to marginally
201 improve the efficiency of writing multiple sequences to the same file
202 (or filehandle), pass the -flush option '0' or any other value that
203 evaluates as defined but false:
205 my $clustal = Bio::AlignIO->new( -file => "<prot.aln",
206 -format => "clustalw" );
207 my $msf = Bio::AlignIO->new(-file => ">prot.msf",
208 -format => "msf",
209 -flush => 0 ); # go as fast as we can!
210 while($seq = $clustal->next_aln) { $msf->write_aln($seq) }
212 =back
214 =head1 OBJECT METHODS
216 See below for more detailed summaries. The main methods are:
218 =head2 $alignment = $AlignIO-E<gt>next_aln()
220 Fetch an alignment from a formatted file.
222 =head2 $AlignIO-E<gt>write_aln($aln)
224 Write the specified alignment to a file..
226 =head2 TIEHANDLE(), READLINE(), PRINT()
228 These provide the tie interface. See L<perltie> for more details.
230 =head1 FEEDBACK
232 =head2 Mailing Lists
234 User feedback is an integral part of the evolution of this and other
235 Bioperl modules. Send your comments and suggestions preferably to one
236 of the Bioperl mailing lists. Your participation is much appreciated.
238 bioperl-l@bioperl.org - General discussion
239 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
241 =head2 Reporting Bugs
243 Report bugs to the Bioperl bug tracking system to help us keep track
244 the bugs and their resolution. Bug reports can be submitted via the
245 web:
247 http://bugzilla.open-bio.org/
249 =head1 AUTHOR - Peter Schattner
251 Email: schattner@alum.mit.edu
253 =head1 CONTRIBUTORS
255 Jason Stajich, jason@bioperl.org
257 =head1 APPENDIX
259 The rest of the documentation details each of the object
260 methods. Internal methods are usually preceded with a _
262 =cut
264 # 'Let the code begin...
266 package Bio::AlignIO;
268 use strict;
270 use Bio::Seq;
271 use Bio::LocatableSeq;
272 use Bio::SimpleAlign;
273 use Bio::Tools::GuessSeqFormat;
274 use base qw(Bio::Root::Root Bio::Root::IO);
276 =head2 new
278 Title : new
279 Usage : $stream = Bio::AlignIO->new(-file => $filename,
280 -format => 'Format')
281 Function: Returns a new seqstream
282 Returns : A Bio::AlignIO::Handler initialised with
283 the appropriate format
284 Args : -file => $filename
285 -format => format
286 -fh => filehandle to attach to
287 -displayname_flat => 1 [optional]
288 to force the displayname to not show start/end
289 information
291 =cut
293 sub new {
294 my ($caller,@args) = @_;
295 my $class = ref($caller) || $caller;
297 # or do we want to call SUPER on an object if $caller is an
298 # object?
299 if( $class =~ /Bio::AlignIO::(\S+)/ ) {
300 my ($self) = $class->SUPER::new(@args);
301 $self->_initialize(@args);
302 return $self;
303 } else {
305 my %param = @args;
306 @param{ map { lc $_ } keys %param } = values %param; # lowercase keys
307 my $format = $param{'-format'} ||
308 $class->_guess_format( $param{-file} || $ARGV[0] );
309 unless ($format) {
310 if ($param{-file}) {
311 $format = Bio::Tools::GuessSeqFormat->new(-file => $param{-file}||$ARGV[0] )->guess;
313 elsif ($param{-fh}) {
314 $format = Bio::Tools::GuessSeqFormat->new(-fh => $param{-fh}||$ARGV[0] )->guess;
317 $format = "\L$format"; # normalize capitalization to lower case
318 $class->throw("Unknown format given or could not determine it [$format]")
319 unless $format;
321 return unless( $class->_load_format_module($format) );
322 return "Bio::AlignIO::$format"->new(@args);
327 =head2 newFh
329 Title : newFh
330 Usage : $fh = Bio::AlignIO->newFh(-file=>$filename,-format=>'Format')
331 Function: does a new() followed by an fh()
332 Example : $fh = Bio::AlignIO->newFh(-file=>$filename,-format=>'Format')
333 $sequence = <$fh>; # read a sequence object
334 print $fh $sequence; # write a sequence object
335 Returns : filehandle tied to the Bio::AlignIO::Fh class
336 Args :
338 =cut
340 sub newFh {
341 my $class = shift;
342 return unless my $self = $class->new(@_);
343 return $self->fh;
346 =head2 fh
348 Title : fh
349 Usage : $obj->fh
350 Function:
351 Example : $fh = $obj->fh; # make a tied filehandle
352 $sequence = <$fh>; # read a sequence object
353 print $fh $sequence; # write a sequence object
354 Returns : filehandle tied to the Bio::AlignIO::Fh class
355 Args :
357 =cut
360 sub fh {
361 my $self = shift;
362 my $class = ref($self) || $self;
363 my $s = Symbol::gensym;
364 tie $$s,$class,$self;
365 return $s;
368 # _initialize is where the heavy stuff will happen when new is called
370 sub _initialize {
371 my($self,@args) = @_;
372 my ($flat) = $self->_rearrange([qw(DISPLAYNAME_FLAT)],
373 @args);
374 $self->force_displayname_flat($flat) if defined $flat;
375 $self->_initialize_io(@args);
379 =head2 _load_format_module
381 Title : _load_format_module
382 Usage : *INTERNAL AlignIO stuff*
383 Function: Loads up (like use) a module at run time on demand
384 Example :
385 Returns :
386 Args :
388 =cut
390 sub _load_format_module {
391 my ($self,$format) = @_;
392 my $module = "Bio::AlignIO::" . $format;
393 my $ok;
395 eval {
396 $ok = $self->_load_module($module);
398 if ( $@ ) {
399 print STDERR <<END;
400 $self: $format cannot be found
401 Exception $@
402 For more information about the AlignIO system please see the AlignIO docs.
403 This includes ways of checking for formats at compile time, not run time
406 return;
408 return 1;
411 =head2 next_aln
413 Title : next_aln
414 Usage : $aln = stream->next_aln
415 Function: reads the next $aln object from the stream
416 Returns : a Bio::Align::AlignI compliant object
417 Args :
419 =cut
421 sub next_aln {
422 my ($self,$aln) = @_;
423 $self->throw("Sorry, you cannot read from a generic Bio::AlignIO object.");
426 =head2 write_aln
428 Title : write_aln
429 Usage : $stream->write_aln($aln)
430 Function: writes the $aln object into the stream
431 Returns : 1 for success and 0 for error
432 Args : Bio::Seq object
434 =cut
436 sub write_aln {
437 my ($self,$aln) = @_;
438 $self->throw("Sorry, you cannot write to a generic Bio::AlignIO object.");
441 =head2 _guess_format
443 Title : _guess_format
444 Usage : $obj->_guess_format($filename)
445 Function:
446 Example :
447 Returns : guessed format of filename (lower case)
448 Args :
450 =cut
452 sub _guess_format {
453 my $class = shift;
454 return unless $_ = shift;
455 return 'clustalw' if /\.aln$/i;
456 return 'emboss' if /\.(water|needle)$/i;
457 return 'metafasta' if /\.metafasta$/;
458 return 'fasta' if /\.(fasta|fast|seq|fa|fsa|nt|aa)$/i;
459 return 'maf' if /\.maf/i;
460 return 'mega' if /\.(meg|mega)$/i;
461 return 'meme' if /\.meme$/i;
462 return 'msf' if /\.(msf|pileup|gcg)$/i;
463 return 'nexus' if /\.(nexus|nex)$/i;
464 return 'pfam' if /\.(pfam|pfm)$/i;
465 return 'phylip' if /\.(phylip|phlp|phyl|phy|ph)$/i;
466 return 'psi' if /\.psi$/i;
467 return 'stockholm' if /\.stk$/i;
468 return 'selex' if /\.(selex|slx|selx|slex|sx)$/i;
469 return 'xmfa' if /\.xmfa$/i;
472 sub DESTROY {
473 my $self = shift;
474 $self->close();
477 sub TIEHANDLE {
478 my $class = shift;
479 return bless {'alignio' => shift},$class;
482 sub READLINE {
483 my $self = shift;
484 return $self->{'alignio'}->next_aln() unless wantarray;
485 my (@list,$obj);
486 push @list,$obj while $obj = $self->{'alignio'}->next_aln();
487 return @list;
490 sub PRINT {
491 my $self = shift;
492 $self->{'alignio'}->write_aln(@_);
496 =head2 force_displayname_flat
498 Title : force_displayname_flat
499 Usage : $obj->force_displayname_flat($newval)
500 Function:
501 Example :
502 Returns : value of force_displayname_flat (a scalar)
503 Args : on set, new value (a scalar or undef, optional)
506 =cut
508 sub force_displayname_flat{
509 my $self = shift;
510 return $self->{'_force_displayname_flat'} = shift if @_;
511 return $self->{'_force_displayname_flat'} || 0;