File Coverage

blib/lib/Bio/Phylo/IO.pm
Criterion Covered Total %
statement 55 80 68.7
branch 20 30 66.6
condition 10 14 71.4
subroutine 11 14 78.5
pod 6 6 100.0
total 102 144 70.8


line stmt bran cond sub pod time code
1             package Bio::Phylo::IO;
2 55     55   1914904 use strict;
  55         340  
  55         1411  
3 55     55   258 use warnings;
  55         95  
  55         1333  
4 55     55   248 use base 'Exporter';
  55         86  
  55         5869  
5 55     55   10383 use Bio::Phylo;
  55         119  
  55         1015  
6 55     55   285 use Bio::Phylo::Util::CONSTANT qw'/looks_like/ :objecttypes';
  55         82  
  55         12487  
7 55     55   341 use Bio::Phylo::Util::Exceptions 'throw';
  55         85  
  55         1972  
8 55     55   15140 use IO::File;
  55         329510  
  55         40240  
9             our @EXPORT_OK = qw'parse unparse parse_matrix parse_tree';
10              
11             =head1 NAME
12              
13             Bio::Phylo::IO - Front end for parsers and serializers
14              
15             =head1 SYNOPSIS
16              
17             use Bio::Phylo::IO qw(parse unparse);
18              
19             # returns an unblessed array reference of block objects,
20             # i.e. taxa, matrix or forest objects
21             my $blocks = parse(
22             '-file' => $file,
23             '-format' => 'nexus',
24             '-encoding' => ':encoding(UTF-8)', # optional, default is system-dependent
25             );
26            
27             for my $block ( @{ $blocks } ) {
28             if ( $block->isa('Bio::Phylo::Taxa') ) {
29             my $taxa = $block;
30             # do something with the taxa
31             }
32             }
33            
34             # returns a Bio::Phylo::Project object
35             my $project = parse(
36             '-file' => $file,
37             '-format' => 'nexus',
38             '-as_project' => 1
39             )
40             my ($taxa) = @{ $project->get_taxa };
41              
42             # parsing a tree from a newick string
43             my $tree_string = '(((A,B),C),D);';
44             my $tree = Bio::Phylo::IO->parse(
45             '-string' => $tree_string,
46             '-format' => 'newick',
47             )->first;
48              
49             # note: newick parsers return
50             # 'Bio::Phylo::Forest'! Call
51             # ->first to retrieve the first
52             # tree of the forest.
53              
54             # prints 'Bio::Phylo::Forest::Tree'
55             print ref $tree, "\n";
56              
57             # if the tree is very large and you need only some terminal nodes from it
58             $simplified_tree = Bio::Phylo::IO->parse(
59             '-string' => $tree_string,
60             '-format' => 'newick',
61             '-keep' => ['A', 'D'], # nodes to keep
62             '-ignore_comments' => 1, # treats [] symbols as part of taxon name
63             )->first;
64              
65             # parsing a table
66             my $table_string = qq(A,1,2|B,1,2|C,2,2|D,2,1);
67             my $matrix = Bio::Phylo::IO->parse(
68             '-string' => $table_string,
69             '-format' => 'table',
70              
71             # Data type, see Bio::Phylo::Parsers::Table
72             '-type' => 'STANDARD',
73              
74             # field separator
75             '-fieldsep' => ',',
76              
77             # line separator
78             '-linesep' => '|'
79             );
80              
81             # prints 'Bio::Phylo::Matrices::Matrix'
82             print ref $matrix, "\n";
83              
84             # parsing a list of taxa
85             my $taxa_string = 'A:B:C:D';
86             my $taxa = Bio::Phylo::IO->parse(
87             '-string' => $taxa_string,
88             '-format' => 'taxlist',
89             '-fieldsep' => ':'
90             );
91              
92             # prints 'Bio::Phylo::Taxa'
93             print ref $taxa, "\n";
94              
95             # matches taxon names in tree to $taxa object
96             $tree->cross_reference($taxa);
97              
98             # likewise for matrix
99             $matrix->cross_reference($taxa);
100              
101             print unparse(
102              
103             # pass the tree object,
104             # crossreferenced to taxa, which
105             # are crossreferenced to the matrix
106             '-phylo' => $tree,
107             '-format' => 'pagel'
108             );
109              
110             # prints a pagel data file:
111             #4 2
112             #A,n1,0.000000,1,2
113             #B,n1,0.000000,1,2
114             #n1,n2,0.000000
115             #C,n2,0.000000,2,2
116             #n2,n3,0.000000
117             #D,n3,0.000000,2,1
118              
119             =head1 DESCRIPTION
120              
121             The IO module is the front end for parsing and serializing phylogenetic
122             data objects. It is a non-OO module that optionally exports the 'parse' and
123             'unparse' subroutines into the caller's namespace, using the
124             C<< use Bio::Phylo::IO qw(parse unparse); >> directive. Alternatively, you can
125             call the subroutines as class methods. The C<< parse >> and
126             C<< unparse >> subroutines load and dispatch the appropriate sub-modules at
127             runtime, depending on the '-format' argument.
128              
129             =head2 CLASS METHODS
130              
131             =over
132              
133             =item parse()
134              
135             Parses a file or string.
136              
137             Type : Class method
138             Title : parse
139             Usage : my $obj = Bio::Phylo::IO->parse(%options);
140             Function: Creates (file) handle,
141             instantiates appropriate parser.
142             Returns : A Bio::Phylo::* object
143             Args : -file => (path),
144             or
145             -string => (scalar),
146             or
147             -handle => (IO::Handle object)
148             or
149             -url => (url string)
150             -format => (description format),
151             -(other) => (parser specific options)
152             Comments: The parse method makes assumptions about
153             the capabilities of Bio::Phylo::Parsers::*
154             modules: i) their names match those of the
155             -format => (blah) arguments, insofar that
156             ucfirst(blah) . '.pm' is an existing module;
157             ii) the modules implement a _from_handle,
158             or a _from_string method. Exceptions are
159             thrown if either assumption is violated.
160            
161             If @ARGV contains even key/value pairs such
162             as "format newick file <filename>" (note: no
163             dashes) these will be prepended to @_, for
164             one-liners.
165              
166             =cut
167              
168             sub parse {
169              
170             # first argument could be the package name or an object reference
171             # if called as Bio::Phylo::IO->parse or as $io->parse, respectively
172 118 100 100 118 1 6834 shift if $_[0] and $_[0] eq __PACKAGE__ or ref $_[0] eq __PACKAGE__;
      66        
173              
174             # arguments were provided on the command line, in @ARGV
175 118 50       402 if (@ARGV) {
176 0         0 my $i = 0;
177 0         0 while ( $i < @ARGV ) {
178 0         0 my ( $key, $value ) = ( $ARGV[$i], $ARGV[ $i + 1 ] );
179              
180             # shell words have no -dash prefix, so we
181             # add it here
182 0 0       0 $key = "-$key" if $key !~ /^-/;
183              
184             # we put @ARGV key/value pairs at the
185             # front of the @_ array
186 0         0 unshift @_, $key, $value;
187 0         0 $i += 2;
188             }
189             }
190              
191             # turn merged @ARGV and @_ arguments into a hash
192 118         542 my %opts = looks_like_hash @_;
193              
194             # there must be at least one of these args as a data source
195 117         438 my @sources = qw(-file -string -handle -url);
196 117         496 my ($source) = grep { defined $_ } @opts{@sources};
  468         897  
197              
198             # check provided arguments
199 117 100       365 throw 'OddHash' => 'Odd number of elements in hash assignment' if !@_;
200 116 100       317 throw 'BadArgs' => 'No parseable data source specified' unless $source;
201              
202             # instantiate parser subclass and process data
203 115 100       586 my $class = $opts{'-format'} ? ucfirst $opts{'-format'} : 'Abstract';
204 115         316 my $lib = 'Bio::Phylo::Parsers::' . $class;
205 115         416 return looks_like_class($lib)->_new(@_)->_process;
206             }
207              
208             =item parse_matrix()
209              
210             Parses a file or string.
211              
212             Type : Class method
213             Title : parse_matrix
214             Usage : my $matrix = Bio::Phylo::IO->parse_matrix(%options);
215             Function: Creates (file) handle,
216             instantiates appropriate parser.
217             Returns : A Bio::Phylo::Matrices::Matrix object
218             Args : Same as parse()
219             Comments: This method is syntactical sugar to get the first matrix
220             out of a file/handle/string
221              
222             =cut
223              
224             sub parse_matrix {
225             my ($matrix) = @{
226 0     0 1 0 parse(
  0         0  
227             @_,
228             '-as_project' => 1,
229             )->get_items(_MATRIX_)
230             };
231 0         0 return $matrix;
232             }
233              
234             =item parse_tree()
235              
236             Parses a file or string.
237              
238             Type : Class method
239             Title : parse_tree
240             Usage : my $tree = Bio::Phylo::IO->parse_tree(%options);
241             Function: Creates (file) handle,
242             instantiates appropriate parser.
243             Returns : A Bio::Phylo::Forest::Tree object
244             Args : Same as parse()
245             Comments: This method is syntactical sugar to get the first tree
246             out of a file/handle/string
247              
248             =cut
249              
250             sub parse_tree {
251             my ($tree) = @{
252 11     11 1 669 parse(
  11         49  
253             @_,
254             '-as_project' => 1,
255             )->get_items(_TREE_)
256             };
257 11         53 return $tree;
258             }
259              
260             =item unparse()
261              
262             Unparses object(s) to a string.
263              
264             Type : Class method
265             Title : unparse
266             Usage : my $string = Bio::Phylo::IO->unparse(
267             %options
268             );
269             Function: Turns Bio::Phylo object into a
270             string according to specified format. If an
271             optional -file or -handle argument is provided
272             the string is also written to that.
273             Returns : SCALAR
274             Args : -phylo => (Bio::Phylo object),
275             -format => (description format),
276             -(other) => (parser specific options)
277             -file => (optional: a file path to open and write to)
278             or
279             -handle => (optional: a handle to write to)
280              
281             =cut
282              
283             sub unparse {
284 41 50 66 41 1 884 if ( $_[0] and $_[0] eq __PACKAGE__ or ref $_[0] eq __PACKAGE__ ) {
      33        
285 0         0 shift;
286             }
287 41         88 my %opts;
288 41 100 100     239 if ( !@_ || scalar @_ % 2 ) {
289 2         6 throw 'OddHash' => 'Odd number of elements in hash assignment';
290             }
291 39         187 %opts = looks_like_hash @_;
292 39 100       161 if ( !$opts{-format} ) {
293 1         3 throw 'BadFormat' => 'no format specified.';
294             }
295 38 50       138 if ( !$opts{-phylo} ) {
296 0         0 throw 'BadArgs' => 'no object to unparse specified.';
297             }
298 38         164 my $lib = 'Bio::Phylo::Unparsers::' . ucfirst $opts{-format};
299 38         149 my $unparser = looks_like_class($lib)->_new(%opts);
300 37 50       264 if ( $unparser->can('_to_string') ) {
301 37         142 my $string = $unparser->_to_string;
302            
303             # as per @fangly's request, make it possible to provide a -file
304             # or -handle argument
305 37 50       152 if ( $opts{'-file'} ) {
306 0 0       0 open my $fh, '>', $opts{'-file'} or throw 'FileError' => $!;
307 0         0 print $fh $string;
308             }
309 37 100       129 if ( $opts{'-handle'} ) {
310 1         1 my $fh = $opts{'-handle'};
311 1         2 eval { $fh->print($string) };
  1         10  
312 1 50       40 if ( $@ ) {
313 0         0 throw 'BadArgs' => "No valid, open handle provided: $@";
314             }
315             }
316 37         244 return $string;
317             }
318             else {
319 0         0 throw 'ObjectMismatch' => 'the unparser can\'t convert to strings.';
320             }
321             }
322              
323             =item can_read()
324              
325             Tests whether L<Bio::Phylo::IO> can read provided syntax format.
326              
327             Type : Class method
328             Title : can_read
329             Usage : &do_something if Bio::Phylo::IO->can_read('foo');
330             Function: Tests whether Bio::Phylo::IO can read provided syntax format.
331             Returns : Boolean
332             Args : A syntax format name, like "nexml"
333              
334             =cut
335              
336             sub can_read {
337 0     0 1 0 my ( $self, $format ) = @_;
338 0         0 my $package = 'Bio::Phylo::Parsers::' . ucfirst($format);
339 0         0 eval { looks_like_class $package };
  0         0  
340 0         0 return ! $@;
341             }
342              
343             =item can_write()
344              
345             Tests whether L<Bio::Phylo::IO> can write provided syntax format.
346              
347             Type : Class method
348             Title : can_write
349             Usage : &do_something if Bio::Phylo::IO->can_write('foo');
350             Function: Tests whether Bio::Phylo::IO can write provided syntax format.
351             Returns : Boolean
352             Args : A syntax format name, like "nexml"
353              
354             =cut
355              
356             sub can_write {
357 0     0 1 0 my ( $self, $format ) = @_;
358 0         0 my $package = 'Bio::Phylo::Unparsers::' . ucfirst($format);
359 0         0 eval { looks_like_class $package };
  0         0  
360 0         0 return ! $@;
361             }
362              
363             # this just to prevent from calling __PACKAGE__->SUPER::DESTROY
364             sub DESTROY {
365 150     150   3039 return 1;
366             }
367              
368             =back
369              
370             =head1 SEE ALSO
371              
372             There is a mailing list at L<https://groups.google.com/forum/#!forum/bio-phylo>
373             for any user or developer questions and discussions.
374              
375             =over
376              
377             =item L<Bio::Phylo::Parsers::Fasta>
378              
379             =item L<Bio::Phylo::Parsers::Newick>
380              
381             =item L<Bio::Phylo::Parsers::Nexml>
382              
383             =item L<Bio::Phylo::Parsers::Nexus>
384              
385             =item L<Bio::Phylo::Parsers::Phylip>
386              
387             =item L<Bio::Phylo::Parsers::Phyloxml>
388              
389             =item L<Bio::Phylo::Parsers::Table>
390              
391             =item L<Bio::Phylo::Parsers::Taxlist>
392              
393             =item L<Bio::Phylo::Parsers::Tolweb>
394              
395             =item L<Bio::Phylo::Unparsers::Mrp>
396              
397             =item L<Bio::Phylo::Unparsers::Newick>
398              
399             =item L<Bio::Phylo::Unparsers::Nexml>
400              
401             =item L<Bio::Phylo::Unparsers::Nexus>
402              
403             =item L<Bio::Phylo::Unparsers::Pagel>
404              
405             =item L<Bio::Phylo::Unparsers::Phylip>
406              
407             =item L<Bio::Phylo::Unparsers::Phyloxml>
408              
409             =item L<Bio::Phylo::Manual>
410              
411             Also see the manual: L<Bio::Phylo::Manual> and L<http://rutgervos.blogspot.com>
412              
413             =back
414              
415             =head1 CITATION
416              
417             If you use Bio::Phylo in published research, please cite it:
418              
419             B<Rutger A Vos>, B<Jason Caravas>, B<Klaas Hartmann>, B<Mark A Jensen>
420             and B<Chase Miller>, 2011. Bio::Phylo - phyloinformatic analysis using Perl.
421             I<BMC Bioinformatics> B<12>:63.
422             L<http://dx.doi.org/10.1186/1471-2105-12-63>
423              
424             =cut
425              
426             1;