FAST/Bio/Tree/Tree.pm untested

filter: Statementstmt 0.0% 0 / 137 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 49 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 21 Podpod 0.0% 0 / 19 totaltotal 0.0% 0 / 266 SCAR 61.4
CC
21
Cov
0%
new
72.0
get_nodes
12.0
set_root_node
12.0
CRAP 462.0
1 #
2 # BioPerl module for FAST::Bio::Tree::Tree
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::Tree::Tree - An Implementation of TreeI interface.
17  
18 =head1 SYNOPSIS
19  
20 # like from a TreeIO
21 my $treeio = FAST::Bio::TreeIO->new(-format => 'newick', -file => 'treefile.dnd');
22 my $tree = $treeio->next_tree;
23 my @nodes = $tree->get_nodes;
24 my $root = $tree->get_root_node;
25  
26  
27 =head1 DESCRIPTION
28  
29 This object holds handles to Nodes which make up a tree.
30  
31 =head1 IMPLEMENTATION NOTE
32  
33 This implementation of FAST::Bio::Tree::Tree contains FAST::Bio::Tree:::NodeI; mainly linked
34 via the root node. As NodeI can potentially contain circular references (as
35 nodes will need to refer to both parent and child nodes), FAST::Bio::Tree::Tree will
36 remove those circular references when the object is garbage-collected. This has
37 some side effects; primarily, one must keep the Tree in scope or have at least
38 one reference to it if working with nodes. The fix is to count the references to
39 the nodes and if it is greater than expected retain all of them, but it requires
40 an additional prereq and thus may not be worth the effort. This only shows up
41 in minor edge cases, though (see Bug #2869).
42  
43 Example of issue:
44  
45 # tree is not assigned to a variable, so passes from memory after
46 # root node is passed
47 my $root = FAST::Bio::TreeIO->new(-format => 'newick', -file => 'foo.txt')->next_tree
48 ->get_root_node;
49
50 # gets nothing, as all Node links are broken when Tree is garbage-collected above
51 my @descendents = $root->get_all_Descendents;
52  
53 =head1 FEEDBACK
54  
55 =head2 Mailing Lists
56  
57 User feedback is an integral part of the evolution of this and other
58 Bioperl modules. Send your comments and suggestions preferably to
59 the Bioperl mailing list. Your participation is much appreciated.
60  
61 bioperl-l@bioperl.org - General discussion
62 http://bioperl.org/wiki/Mailing_lists - About the mailing lists
63  
64 =head2 Support
65  
66 Please direct usage questions or support issues to the mailing list:
67  
68 I<bioperl-l@bioperl.org>
69  
70 rather than to the module maintainer directly. Many experienced and
71 reponsive experts will be able look at the problem and quickly
72 address it. Please include a thorough description of the problem
73 with code and data examples if at all possible.
74  
75 =head2 Reporting Bugs
76  
77 Report bugs to the Bioperl bug tracking system to help us keep track
78 of the bugs and their resolution. Bug reports can be submitted via
79 the web:
80  
81 https://redmine.open-bio.org/projects/bioperl/
82  
83 =head1 AUTHOR - Jason Stajich
84  
85 Email jason@bioperl.org
86  
87 =head1 CONTRIBUTORS
88  
89 Aaron Mackey amackey@virginia.edu
90 Sendu Bala bix@sendu.me.uk
91 Mark A. Jensen maj@fortinbras.us
92  
93 =head1 APPENDIX
94  
95 The rest of the documentation details each of the object methods.
96 Internal methods are usually preceded with a _
97  
98 =cut
99  
100  
101 # Let the code begin...
102  
103  
104 package FAST::Bio::Tree::Tree;
105 use strict;
106  
107 # Object preamble - inherits from FAST::Bio::Root::Root
108  
109  
110 use base qw(FAST::Bio::Root::Root FAST::Bio::Tree::TreeI FAST::Bio::Tree::TreeFunctionsI);
111  
112 =head2 new
113  
114 Title : new
115 Usage : my $obj = FAST::Bio::Tree::Tree->new();
116 Function: Builds a new FAST::Bio::Tree::Tree object
117 Returns : FAST::Bio::Tree::Tree
118 Args : -root => L<FAST::Bio::Tree::NodeI> object which is the root
119 OR
120 -node => L<FAST::Bio::Tree::NodeI> object from which the root will be
121 determined
122  
123 -nodelete => boolean, whether or not to try and cleanup all
124 the nodes when this this tree goes out
125 of scope.
126 -id => optional tree ID
127 -score => optional tree score value
128  
129 =cut
130  
131 sub new {
132 my($class,@args) = @_;
133
134 my $self = $class->SUPER::new(@args);
135 $self->{'_rootnode'} = undef;
136 $self->{'_maxbranchlen'} = 0;
137 $self->_register_for_cleanup(\&cleanup_tree);
138 my ($root,$node,$nodel,$id,$score)= $self->_rearrange([qw(ROOT NODE NODELETE
139 ID SCORE)], @args);
140
141 if ($node && ! $root) {
142 $self->throw("Must supply a FAST::Bio::Tree::NodeI") unless ref($node) && $node->isa('FAST::Bio::Tree::NodeI');
143 my @lineage = $self->get_lineage_nodes($node);
144 $root = shift(@lineage) || $node;
145
146 # to stop us pulling in entire database of a FAST::Bio::Taxon when we later do
147 # get_nodes() or similar, specifically set ancestor() for each node
148 if ($node->isa('FAST::Bio::Taxon')) {
149 push(@lineage, $node) unless $node eq $root;
150 my $ancestor = $root;
151 foreach my $lineage_node (@lineage) {
152 $lineage_node->ancestor($ancestor);
153 } continue { $ancestor = $lineage_node; }
154 }
155 }
156 if ($root) {
157 $self->set_root_node($root);
158 }
159
160 $self->nodelete($nodel || 0);
161 $self->id($id) if defined $id;
162 $self->score($score) if defined $score;
163 return $self;
164 }
165  
166  
167 =head2 nodelete
168  
169 Title : nodelete
170 Usage : $obj->nodelete($newval)
171 Function: Get/Set Boolean whether or not to delete the underlying
172 nodes when it goes out of scope. By default this is false
173 meaning trees are cleaned up.
174 Returns : boolean
175 Args : on set, new boolean value
176  
177 =cut
178  
179 sub nodelete{
180 my $self = shift;
181 return $self->{'nodelete'} = shift if @_;
182 return $self->{'nodelete'};
183 }
184  
185 =head2 get_nodes
186  
187 Title : get_nodes
188 Usage : my @nodes = $tree->get_nodes()
189 Function: Return list of FAST::Bio::Tree::NodeI objects
190 Returns : array of FAST::Bio::Tree::NodeI objects
191 Args : (named values) hash with one value
192 order => 'b|breadth' first order or 'd|depth' first order
193  
194 =cut
195  
196 sub get_nodes{
197 my ($self, @args) = @_;
198
199 my ($order, $sortby) = $self->_rearrange([qw(ORDER SORTBY)],@args);
200 $order ||= 'depth';
201 $sortby ||= 'none';
202 my $node = $self->get_root_node || return;
203 if ($order =~ m/^b|(breadth)$/oi) {
204 my @children = ($node);
205 for (@children) {
206 push @children, $_->each_Descendent($sortby);
207 }
208 return @children;
209 }
210  
211 if ($order =~ m/^d|(depth)$/oi) {
212 # this is depth-first search I believe
213 my @children = ($node,$node->get_all_Descendents($sortby));
214 return @children;
215 }
216 }
217  
218 =head2 get_root_node
219  
220 Title : get_root_node
221 Usage : my $node = $tree->get_root_node();
222 Function: Get the Top Node in the tree, in this implementation
223 Trees only have one top node.
224 Returns : FAST::Bio::Tree::NodeI object
225 Args : none
226  
227 =cut
228  
229  
230 sub get_root_node{
231 my ($self) = @_;
232 return $self->{'_rootnode'};
233 }
234  
235 =head2 set_root_node
236  
237 Title : set_root_node
238 Usage : $tree->set_root_node($node)
239 Function: Set the Root Node for the Tree
240 Returns : FAST::Bio::Tree::NodeI
241 Args : FAST::Bio::Tree::NodeI
242  
243 =cut
244  
245 sub set_root_node{
246 my $self = shift;
247 if( @_ ) {
248 my $value = shift;
249 if( defined $value &&
250 ! $value->isa('FAST::Bio::Tree::NodeI') ) {
251 $self->warn("Trying to set the root node to $value which is not a FAST::Bio::Tree::NodeI");
252 return $self->get_root_node;
253 }
254 $self->{'_rootnode'} = $value;
255 }
256 return $self->get_root_node;
257 }
258  
259 =head2 total_branch_length
260  
261 Title : total_branch_length
262 Usage : my $size = $tree->total_branch_length
263 Function: Returns the sum of the length of all branches
264 Returns : real
265 Args : none
266  
267 =cut
268  
269 sub total_branch_length { shift->subtree_length }
270  
271 =head2 subtree_length
272  
273 Title : subtree_length
274 Usage : my $subtree_size = $tree->subtree_length($internal_node)
275 Function: Returns the sum of the length of all branches in a subtree
276 under the node. Calculates the size of the whole tree
277 without an argument (but only if root node is defined)
278 Returns : real or undef
279 Args : FAST::Bio::Tree::NodeI object, defaults to the root node
280  
281 =cut
282  
283 sub subtree_length {
284 my $tree = shift;
285 my $node = shift || $tree->get_root_node;
286 return unless $node;
287 my $sum = 0;
288 for ( $node->get_all_Descendents ) {
289 $sum += $_->branch_length || 0;
290 }
291 return $sum;
292 }
293  
294  
295 =head2 id
296  
297 Title : id
298 Usage : my $id = $tree->id();
299 Function: An id value for the tree
300 Returns : scalar
301 Args : [optional] new value to set
302  
303  
304 =cut
305  
306 sub id{
307 my ($self,$val) = @_;
308 if( defined $val ) {
309 $self->{'_treeid'} = $val;
310 }
311 return $self->{'_treeid'};
312 }
313  
314 =head2 score
315  
316 Title : score
317 Usage : $obj->score($newval)
318 Function: Sets the associated score with this tree
319 This is a generic slot which is probably best used
320 for log likelihood or other overall tree score
321 Returns : value of score
322 Args : newvalue (optional)
323  
324  
325 =cut
326  
327 sub score{
328 my ($self,$val) = @_;
329 if( defined $val ) {
330 $self->{'_score'} = $val;
331 }
332 return $self->{'_score'};
333 }
334  
335  
336 # decorated interface TreeI Implements this
337  
338 =head2 height
339  
340 Title : height
341 Usage : my $height = $tree->height
342 Function: Gets the height of tree - this LOG_2($number_nodes)
343 WARNING: this is only true for strict binary trees. The TreeIO
344 system is capable of building non-binary trees, for which this
345 method will currently return an incorrect value!!
346 Returns : integer
347 Args : none
348  
349 =head2 number_nodes
350  
351 Title : number_nodes
352 Usage : my $size = $tree->number_nodes
353 Function: Returns the number of nodes in the tree
354 Returns : integer
355 Args : none
356  
357  
358 =cut
359  
360 =head2 as_text
361  
362 Title : as_text
363 Usage : my $tree_as_string = $tree->as_text($format)
364 Function: Returns the tree as a string representation in the
365 desired format (currently 'newick', 'nhx', or
366 'tabtree')
367 Returns : scalar string
368 Args : format type as specified by FAST::Bio::TreeIO
369 Note : This method loads the FAST::Bio::TreeIO::$format module
370 on the fly, and commandeers the _write_tree_Helper
371 routine therein to create the tree string.
372  
373 =cut
374  
375 sub as_text {
376 my $self = shift;
377 my $format = shift;
378 my $params_input = shift || {};
379  
380 my $iomod = "FAST::Bio::TreeIO::$format";
381 $self->_load_module($iomod);
382  
383 my $string = '';
384 open(my $fh,">",\$string) or die ("Couldn't open $string as file: $!\n");
385 my $test = $iomod->new(-format=>$format,-fh=>$fh);
386  
387 # Get the default params for the given IO module.
388 $test->set_params($params_input);
389  
390 $test->write_tree($self);
391 close($fh);
392 return $string;
393 }
394  
395 =head2 Methods for associating Tag/Values with a Tree
396  
397 These methods associate tag/value pairs with a Tree
398  
399 =head2 set_tag_value
400  
401 Title : set_tag_value
402 Usage : $tree->set_tag_value($tag,$value)
403 $tree->set_tag_value($tag,@values)
404 Function: Sets a tag value(s) to a tree. Replaces old values.
405 Returns : number of values stored for this tag
406 Args : $tag - tag name
407 $value - value to store for the tag
408  
409 =cut
410  
411 sub set_tag_value{
412 my ($self,$tag,@values) = @_;
413 if( ! defined $tag || ! scalar @values ) {
414 $self->warn("cannot call set_tag_value with an undefined value");
415 }
416 $self->remove_tag ($tag);
417 map { push @{$self->{'_tags'}->{$tag}}, $_ } @values;
418 return scalar @{$self->{'_tags'}->{$tag}};
419 }
420  
421 =head2 add_tag_value
422  
423 Title : add_tag_value
424 Usage : $tree->add_tag_value($tag,$value)
425 Function: Adds a tag value to a tree
426 Returns : number of values stored for this tag
427 Args : $tag - tag name
428 $value - value to store for the tag
429  
430 =cut
431  
432 sub add_tag_value{
433 my ($self,$tag,$value) = @_;
434 if( ! defined $tag || ! defined $value ) {
435 $self->warn("cannot call add_tag_value with an undefined value");
436 }
437 push @{$self->{'_tags'}->{$tag}}, $value;
438 return scalar @{$self->{'_tags'}->{$tag}};
439 }
440  
441 =head2 remove_tag
442  
443 Title : remove_tag
444 Usage : $tree->remove_tag($tag)
445 Function: Remove the tag and all values for this tag
446 Returns : boolean representing success (0 if tag does not exist)
447 Args : $tag - tagname to remove
448  
449  
450 =cut
451  
452 sub remove_tag {
453 my ($self,$tag) = @_;
454 if( exists $self->{'_tags'}->{$tag} ) {
455 $self->{'_tags'}->{$tag} = undef;
456 delete $self->{'_tags'}->{$tag};
457 return 1;
458 }
459 return 0;
460 }
461  
462 =head2 remove_all_tags
463  
464 Title : remove_all_tags
465 Usage : $tree->remove_all_tags()
466 Function: Removes all tags
467 Returns : None
468 Args : None
469  
470 =cut
471  
472 sub remove_all_tags{
473 my ($self) = @_;
474 $self->{'_tags'} = {};
475 return;
476 }
477  
478 =head2 get_all_tags
479  
480 Title : get_all_tags
481 Usage : my @tags = $tree->get_all_tags()
482 Function: Gets all the tag names for this Tree
483 Returns : Array of tagnames
484 Args : None
485  
486 =cut
487  
488 sub get_all_tags{
489 my ($self) = @_;
490 my @tags = sort keys %{$self->{'_tags'} || {}};
491 return @tags;
492 }
493  
494 =head2 get_tag_values
495  
496 Title : get_tag_values
497 Usage : my @values = $tree->get_tag_values($tag)
498 Function: Gets the values for given tag ($tag)
499 Returns : Array of values or empty list if tag does not exist
500 Args : $tag - tag name
501  
502 =cut
503  
504 sub get_tag_values{
505 my ($self,$tag) = @_;
506 return wantarray ? @{$self->{'_tags'}->{$tag} || []} :
507 (@{$self->{'_tags'}->{$tag} || []})[0];
508 }
509  
510 =head2 has_tag
511  
512 Title : has_tag
513 Usage : $tree->has_tag($tag)
514 Function: Boolean test if tag exists in the Tree
515 Returns : Boolean
516 Args : $tag - tagname
517  
518 =cut
519  
520 sub has_tag {
521 my ($self,$tag) = @_;
522 return exists $self->{'_tags'}->{$tag};
523 }
524  
525 # safe tree clone that doesn't seg fault
526  
527 =head2 clone()
528  
529 Title : clone
530 Alias : _clone
531 Usage : $tree_copy = $tree->clone();
532 $subtree_copy = $tree->clone($internal_node);
533 Function: Safe tree clone that doesn't segfault
534 (of Sendu)
535 Returns : FAST::Bio::Tree::Tree object
536 Args : [optional] $start_node, FAST::Bio::Tree::Node object
537  
538 =cut
539  
540 sub clone {
541 my ($self, $parent, $parent_clone) = @_;
542 $parent ||= $self->get_root_node;
543 $parent_clone ||= $self->_clone_node($parent);
544  
545 foreach my $node ($parent->each_Descendent()) {
546 my $child = $self->_clone_node($node);
547 $child->ancestor($parent_clone);
548 $self->_clone($node, $child);
549 }
550 $parent->ancestor && return;
551  
552 my $tree = $self->new(-root => $parent_clone);
553 return $tree;
554 }
555  
556 # -- private internal methods --
557  
558 sub cleanup_tree {
559 my $self = shift;
560 unless( $self->nodelete ) {
561 for my $node ($self->get_nodes(-order => 'b', -sortby => 'none')) {
562 $node->node_cleanup;
563 }
564 }
565 $self->{'_rootnode'} = undef;
566 }
567  
568 1;