blib/lib/Bio/BPWrapper/TreeManipulations.pm untested

filter: Statementstmt 0.0% 0 / 440 Branchbran 0.0% 0 / 170 Conditioncond 0.0% 0 / 18 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 44 Podpod 0.0% 0 / 34 totaltotal 0.0% 0 / 706 CC 85 SCAR 50.6
CC
85
Cov
0%
write_out
702.0
print_tree_shape
56.0
subset
42.0
CRAP 157.1
1 =encoding utf8
2  
3 =head1 NAME
4  
5 Bio::BPWrapper::TreeManipulations - Functions for biotree
6  
7 =head1 SYNOPSIS
8  
9 use Bio::BPWrapper::TreeManipulations;
10 # Set options hash ...
11 initialize(\%opts);
12 write_out(\%opts);
13  
14 =cut
15  
16 # Package global variables
17 my ($in, $out, $aln, %opts, $file, $in_format, $out_format, @nodes,
18 $tree, $print_tree, $rootnode);
19  
20 ###################### subroutine ######################
21  
22 package Bio::BPWrapper::TreeManipulations;
23  
24 use strict;
25 use warnings;
26 use v5.10;
27 use Bio::BPWrapper;
28 use Bio::TreeIO;
29 use Bio::Tree::Tree;
30 use Bio::Tree::Node;
31 use Data::Dumper;
32  
33 if ($ENV{'DEBUG'}) { use Data::Dumper }
34  
35 use vars qw(@ISA @EXPORT @EXPORT_OK);
36  
37 @ISA = qw(Exporter);
38  
39 @EXPORT = qw(print_tree_shape edge_length_abundance swap_otus getdistance
40 sister_pairs countOTU reroot clean_tree delete_otus initialize
41 write_out);
42  
43 =head1 SUBROUTINES
44  
45 =head2 initialize()
46  
47 Sets up most of the actions to be performed on an alignment.
48  
49 Call this right after setting up an options hash.
50  
51 Sets package variables: C<$in_format>, C<@nodes>, C<$tree>, C<$out_format>, and C<$out>.
52  
53  
54 =cut
55  
56 sub initialize {
57 my $opts_ref = shift;
58 Bio::BPWrapper::common_opts($opts_ref);
59 %opts = %{$opts_ref};
60  
61 $in_format = $opts{"input"} // 'newick'; # This doesn't work...or does it?
62 $out_format = $opts{"output"} // "newick";
63 $print_tree = 0; # Trigger printing the tree.
64 my $file = shift || "STDIN";
65  
66 $in = Bio::TreeIO->new(-format => $in_format, ($file eq "STDIN") ? (-fh => \*STDIN) : (-file => $file));
67 $tree = $in->next_tree(); # get the first tree (and ignore the rest)
68  
69 $out = Bio::TreeIO->new(-format => $out_format);
70 @nodes = $tree->get_nodes;
71 $rootnode = $tree->get_root_node;
72 }
73  
74  
75 sub print_tree_shape {
76 my @matrix;
77 my (%leaf, %inode);
78 my $ct_leaf = 0;
79 my $ct_inode = 0;
80 for my $nd (@nodes) {
81 if ($nd->is_Leaf()) {
82 $leaf{$nd->id} = ++$ct_leaf;
83 } else {
84 $inode{$nd->internal_id} = ++$ct_inode;
85 }
86 }
87  
88 for my $nd (@nodes) {
89 next if $nd->is_Leaf();
90 my @dscs = $nd->each_Descendent;
91 die unless @dscs == 2;
92 my $id1 = $dscs[0]->is_Leaf
93 ? -1 * $leaf{$dscs[0]->id} : $inode{$dscs[0]->internal_id};
94 my $id2 = $dscs[1]->is_Leaf
95 ? -1 * $leaf{$dscs[1]->id} : $inode{$dscs[1]->internal_id};
96 if ($nd eq $rootnode) { # root at first
97 unshift @matrix, [ ($id1, $id2) ];
98 } else {
99 push @matrix, [ ($id1, $id2) ]
100 }
101 }
102 for (my $i = $#matrix; $i >=0; $i--) {
103 print $matrix[$i]->[0], "\t", $matrix[$i]->[1], "\n";
104 };
105 # print Dumper(\%leaf, \%inode);
106 }
107  
108 sub edge_length_abundance {
109 my @inodes;
110 my @brs;
111 push (@inodes, $_) for _walk_up($rootnode);
112  
113 for my $nd (@inodes) {
114 next if $nd eq $rootnode;
115 my $id = $nd->internal_id;
116 my $ct_otus = 0;
117 if ($nd->is_Leaf) {
118 $ct_otus = 1;
119 } else {
120 foreach (&_each_leaf($nd)) {
121 $ct_otus++;
122 }
123 }
124 push @brs, { 'id' => $id, 'num_tips' => $ct_otus, 'br_len' => $nd->branch_length() }
125 }
126  
127 my $ct_tips = 0;
128 foreach my $nd (@nodes) {
129 $ct_tips ++ if $nd->is_Leaf();
130 }
131  
132 for (my $k=1; $k<=$ct_tips; $k++) {
133 my $total = 0;
134 my @nds = grep { $_->{num_tips} == $k } @brs;
135 if (@nds) { $total += $_->{br_len} for @nds }
136 printf "%d\t%.6f\n", $k, $total/$tree->total_branch_length();
137 }
138 }
139  
140 sub swap_otus {
141 my @otus;
142 my $otu_ct = 0;
143 foreach (@nodes) {
144 next unless $_->is_Leaf();
145 push @otus, $_;
146 $otu_ct++;
147 }
148 @otus = sort {$a->id() cmp $b->id() } @otus;
149 my $ref_otu;
150 if ($opts{'swap-otus'}) {
151 $ref_otu = $tree->find_node($opts{'swap-otus'}) || die "node not found\n";
152 } else {
153 $ref_otu = $otus[0];
154 }
155  
156 foreach my $nd (@otus) {
157 next if $nd eq $ref_otu;
158 my $nd_id = $nd->id();
159 my $ref_id = $ref_otu->id();
160 $nd->id("new_".$ref_id);
161 $ref_otu->id("new_".$nd_id);
162 say $tree->as_text($out_format);
163 $nd->id($nd_id);
164 $ref_otu->id($ref_id);
165 }
166 }
167  
168 # Get the distance between nodes
169 sub getdistance {
170 my @dnodes = _name2node($opts{'distance'});
171 if (scalar(@dnodes) != 2) { say "Error: Provide exactly two nodes/leaves to use with --distance" }
172 else { say $tree->distance(-nodes => \@dnodes) }
173 }
174  
175 sub sister_pairs {
176 my @otus;
177 my $otu_ct = 0;
178 foreach (@nodes) {
179 next unless $_->is_Leaf();
180 push @otus, $_;
181 $otu_ct++;
182 }
183  
184 @otus = sort {$a->id() cmp $b->id() } @otus;
185 for (my $i = 0; $i < $otu_ct; $i++) {
186 my $pa_i = $otus[$i]->ancestor();
187 for (my $j = $i+1; $j < $otu_ct; $j++) {
188 my $pa_j = $otus[$j]->ancestor();
189 print $otus[$i]->id, "\t", $otus[$j]->id, "\t";
190 print $pa_i eq $pa_j ? 1 : 0;
191 print "\n";
192 }
193 }
194 }
195  
196 =head2 countOTU()
197  
198 Print total number of OTUs (leaves).
199  
200 =cut
201  
202 sub countOTU {
203 my $otu_ct = 0;
204 foreach (@nodes) { $otu_ct++ if $_->is_Leaf() }
205 say $otu_ct
206 }
207  
208 =head2 reroot()
209  
210 Reroot tree to node in C<$opts{'reroot'}> by creating new branch.
211  
212 =cut
213  
214 sub reroot {
215 my $outgroup_id = $opts{'reroot'};
216 my $outgroup = $tree->find_node($outgroup_id);
217 my $newroot = $outgroup->create_node_on_branch(-FRACTION => 0.5, -ANNOT => {id => 'newroot'});
218 $tree->reroot($newroot);
219 $print_tree = 1;
220 }
221  
222 sub clean_tree {
223 foreach my $nd (@nodes) {
224 $nd->branch_length(0) if $opts{'cleanbr'};
225 if ($opts{'cleanboot'}) {
226 $nd->bootstrap(0);
227 $nd->id('') unless $nd->is_Leaf;
228 }
229 }
230 $print_tree = 1;
231 }
232  
233 sub delete_otus {
234 my $ref_otus = &_get_otus();
235 my @otus_to_retain = &_remove_otus($ref_otus, $opts{'delete-otus'});
236 # print Dumper(\@otus_to_retain);
237 $opts{'subset'} = join ",", @otus_to_retain;
238 &subset();
239 }
240  
241 sub _get_otus {
242 my @list;
243 foreach my $nd (@nodes) { push @list, $nd if $nd->is_Leaf }
244 return \@list;
245 }
246  
247 sub _remove_otus {
248 my $ref = shift;
249 my $str = shift;
250 my @list;
251 my @otus_to_remove = split /\s*,\s*/, $str;
252  
253 foreach my $nd (@$ref) {
254 foreach my $otu (@otus_to_remove) {
255 push @list, $nd->id() unless $otu eq $nd->id();
256 }
257 }
258 return @list;
259 }
260  
261 sub multi2bi {
262 foreach my $nd (@nodes) {
263 # next if $nd eq $rootnode;
264 &_add_node($nd);
265 }
266 $print_tree = 1;
267 }
268  
269 sub _add_node {
270 my $node = shift;
271 # warn "processing\t", $node->internal_id, "\n";
272 my @desc = $node->each_Descendent;
273 return if scalar(@desc) <= 2;
274 # warn "multifurcating node:\t", $node->internal_id, " ... add a new node\n";
275 shift @desc; # retain the first descent
276 # my $new_node = $node->create_node_on_branch(-FRACTION => 0.5, -FORCE => 1, -ANNOT=>{ -id => "new_id" });
277 my $new_node = Bio::Tree::Node->new(-id => "new", -branch_length => 0);
278 $node->add_Descendent($new_node);
279 # warn "\ta new node created:\t", $new_node->id, "\n";
280 foreach (@desc) {
281 $node->remove_Descendent($_); # remove from grand-parent
282 # warn "\t\tremove descendant:\t", $_->internal_id, "\n";
283 $new_node->add_Descendent($_); # re-attarch to parent
284 # warn "\t\tadd descendant to the new node:\t", $_->internal_id, "\n";
285 }
286 &_add_node($new_node);
287 }
288  
289 # Subset a tree
290 sub subset {
291 # Collect the subset of nodes from STDIN or from $_
292 my @keep_nodes;
293 if ($opts{'subset'}) { @keep_nodes = _name2node($opts{'subset'}) }
294 else { my $ar = $_[0]; @keep_nodes = @$ar }
295  
296 # Collect list of descendents
297 my @descendents;
298 for my $nd (@keep_nodes) { push @descendents, $_ for $nd->get_all_Descendents }
299  
300 # Collect list of ancestors
301 my @ancestors;
302 my $tmp;
303 for (@keep_nodes) {
304 $tmp = $_;
305 while ($tmp->ancestor) {
306 push @ancestors, $tmp->ancestor;
307 $tmp = $tmp->ancestor
308 }
309 }
310  
311 # Make a hash of nodes to keep
312 my %keep = map { $_->internal_id => $_ } @keep_nodes;
313 $keep{$_->internal_id} = $_ for @descendents;
314 $keep{$_->internal_id} = $_ for @ancestors;
315  
316 # Remove all nodes but those in %keep
317 for (@nodes) { $tree->remove_Node($_) unless exists($keep{$_->internal_id}) }
318  
319 # Clean up internal single-descendent nodes
320 my @desc;
321 my $nd_len;
322 my $desc_len;
323 for my $nd ($tree->get_nodes) {
324 next if $nd == $rootnode;
325 @desc = $nd->each_Descendent;
326 next unless scalar(@desc) == 1;
327 $nd_len = $nd->branch_length() || 0;
328 $desc_len = $desc[0]->branch_length() || 0;
329 $desc[0]->branch_length($nd_len + $desc_len);
330 $nd->ancestor->add_Descendent($desc[0]);
331 $tree->remove_Node($nd)
332 }
333  
334 # Take care of the a single-descendent root node
335 @desc = $rootnode->each_Descendent;
336 if (scalar(@desc) == 1) {
337 $rootnode->add_Descendent($_) for $desc[0]->each_Descendent;
338 $tree->remove_Node($desc[0])
339 }
340 $print_tree = 1
341 }
342  
343 # Print OTU names and lengths
344 sub print_leaves_lengths {
345 foreach (@nodes) { say $_->id(), "\t", $_->branch_length() if $_->is_Leaf() }
346 }
347  
348 # Get LCA
349 sub getlca {
350 my @lca_nodes;
351 if (_name2node($opts{'lca'})) { @lca_nodes = _name2node($opts{'lca'}) }
352 else { my $ar = $_[0]; @lca_nodes = @$ar }
353 my @nd_pair;
354 my $lca;
355  
356 $nd_pair[0] = $lca_nodes[0];
357 if (@lca_nodes > 1) {
358 for (my $index = 1; $index < @lca_nodes; $index++) {
359 $nd_pair[1] = $lca_nodes[$index];
360 $lca = $tree->get_lca(-nodes => \@nd_pair);
361 $nd_pair[0] = $lca
362 }
363 if (_name2node($opts{'lca'})) { say $lca->internal_id } else { return $lca }
364 } elsif (@lca_nodes == 1) {
365 if (_name2node($opts{'lca'})) { say $lca_nodes[0]->ancestor->internal_id }
366 else { return $lca_nodes[0]->ancestor->internal_id }
367 }
368 }
369  
370 # Label nodes with their internal ID's
371 sub label_nodes {
372 for (@nodes) {
373 next if $_ == $rootnode;
374 my $suffix = defined($_->id) ? "_" . $_->id : "";
375 $_->id($_->internal_id . $suffix)
376 }
377 $print_tree = 1
378 }
379  
380 # Print half-tree id distances between all pairs of nodes
381 sub listdistance {
382 my (@leaves, @sortedleaf_names, @leafnames);
383 foreach (@nodes) { push(@leaves, $_) if $_->is_Leaf() }
384  
385 # Make an alphabetical list of OTU names
386 push @sortedleaf_names, $_->id foreach sort {lc($a->id) cmp lc($b->id)} @leaves;
387  
388 @leaves = ();
389  
390 #Rebuld leaf array with new alphabetical order
391 push @leaves, $tree->find_node(-id => $_) foreach @sortedleaf_names;
392  
393 # Prints a half-matrix of distance values
394 my $i = 1;
395 for my $firstleaf (@leaves) {
396 my @dnodes;
397 for (my $x = $i; $x < scalar(@leaves); $x++) {
398 @dnodes = ($firstleaf, $leaves[$x]);
399 say join "\t", ($firstleaf->id(), $leaves[$x]->id(), $tree->distance(-nodes => \@dnodes))
400 }
401 $i++
402 }
403 }
404  
405 =head2 bin()
406  
407 Divides tree into number of specified segments and counts branches up
408 to height the segment. Prints: bin_number, branch_count, bin_floor,
409 bin_ceiling.
410  
411 =cut
412  
413 sub bin {
414 my $treeheight = _treeheight(\$tree);
415 my $bincount = $opts{'ltt'};
416 my $binsize = $treeheight/$bincount;
417 my @bins;
418 while ($treeheight > 0) {
419 unshift @bins, $treeheight;
420 $treeheight -= $binsize
421 }
422 # Handle imperfect division. When approaching 0, if a tiny number is found, such as 2e-17, assign it as 0 and ignore negatives that may follow.
423 for (@bins) { shift @bins if $_ < 1e-10 }
424 unshift @bins, 0;
425  
426 for (my $i=0; $i+1<@bins; $i++) {
427 my $branchcount = 1; # branch from root
428 # Starting from the root, add a branch for each found descendent
429 $branchcount += _binrecursive(\$rootnode, $bins[$i+1]);
430 printf "%3d\t%3d\t%.4f\t%.4f\n", $i+1, $branchcount, $bins[$i], $bins[$i+1];
431 }
432 }
433  
434 sub print_all_lengths{
435 for (@nodes) {
436 next if $_ == $rootnode;
437 my $p_node = $_->ancestor();
438 my $p_id = $p_node->id ? $p_node->id : $p_node->internal_id;
439 my $c_id = $_->id ? $_->id() : $_->internal_id;
440 say $p_id, "\t", $c_id, "\t", $_->branch_length;
441 }
442 }
443  
444 sub random_tree{
445 my @otus = _each_leaf($rootnode);
446 my @sample;
447 my $sample_size = $opts{"random"} == 0 ? int(scalar(@otus) / 2) : $opts{"random"};
448  
449 die "Error: sample size ($sample_size) exceeds number of OTUs (", scalar(@otus), ")" if $sample_size > scalar(@otus);
450  
451 # Use Reservoir Sampling to pick random otus.
452 my @sampled = (1 .. $sample_size);
453 for ($sample_size + 1 .. scalar(@otus)) {
454 $sampled[rand(@sampled)] = $_ if rand() < $sample_size/$_
455 }
456 push @sample, $otus[--$_] for @sampled;
457 &subset(\@sample)
458 }
459  
460 # Depth to the root for a node
461 sub depth_to_root {
462 say $_->depth for _name2node($opts{'depth'})
463 }
464  
465 # Remove Branch Lenghts
466 sub remove_brlengths {
467 foreach (@nodes) { $_->branch_length(0) if defined $_->branch_length }
468 $print_tree = 1
469 }
470  
471 sub alldesc {
472 my @inodes;
473 my $inode_id = $opts{'allchildOTU'};
474  
475 if ($inode_id eq 'all') { push (@inodes, $_) for _walk_up($rootnode) }
476 else { push @inodes, $tree->find_node(-internal_id => $inode_id) }
477  
478 for my $nd (@inodes) {
479 print $nd->internal_id, " ";
480 if ($nd->is_Leaf) { print $nd->id } else { print $_->id, " " for _each_leaf($nd) }
481 print "\n"
482 }
483 }
484  
485 # Walks from starting OTU
486 sub walk {
487 my $startleaf = $tree->find_node($opts{'walk'});
488 my $curnode = $startleaf->ancestor;
489 my $last_curnode = $startleaf;
490 my @decs;
491 my %visited;
492 my $totlen = 0;
493 my @dpair;
494 my $vcount = 0;
495  
496 $visited{$startleaf} = 1;
497  
498 while ($curnode) {
499 $visited{$curnode} = 1;
500 @dpair = ($last_curnode, $curnode);
501 $totlen += $tree->distance(-nodes => \@dpair);
502 _desclen($curnode, \%visited, \$totlen, \$vcount);
503 $last_curnode = $curnode;
504 $curnode = $curnode->ancestor
505 }
506 }
507  
508  
509 =head2 write_out()
510  
511 Performs the bulk of the actions actions set via
512 L<C<initialize(\%opts)>|/initialize>.
513  
514 Call this after calling C<#initialize(\%opts)>.
515  
516 =cut
517 sub write_out {
518 my $opts = shift;
519 getdistance() if $opts->{'distance'};
520 say $tree->total_branch_length() if $opts->{'length'};
521 countOTU() if $opts->{'numOTU'};
522 $print_tree = 1 if defined($opts->{'output'});
523 reroot() if $opts->{'reroot'};
524 subset() if $opts->{'subset'};
525 print_leaves_lengths() if $opts->{'otu'};
526 getlca() if $opts->{'lca'};
527  
528 label_nodes() if $opts->{'labelnodes'};
529 listdistance() if $opts->{'distanceall'};
530 bin() if $opts->{'ltt'};
531 print_all_lengths() if $opts->{'lengthall'};
532 random_tree() if defined($opts->{'random'});
533 depth_to_root() if $opts->{'depth'};
534 remove_brlengths() if $opts->{'rmbl'};
535 alldesc() if $opts->{'allchildOTU'};
536 walk() if $opts->{'walk'};
537 multi2bi() if $opts->{'multi2bi'};
538 clean_tree() if $opts->{'cleanbr'} || $opts->{'cleanboot'};
539 delete_otus() if $opts->{'delete-otus'};
540 sister_pairs() if $opts->{'sis-pairs'};
541 swap_otus() if $opts->{'swap-otus'};
542 edge_length_abundance() if $opts->{'ead'};
543 print_tree_shape() if $opts->{'tree-shape'};
544 say $tree->as_text($out_format) if $print_tree;
545 }
546  
547 ################# internal subroutines ##############
548  
549 sub _name2node {
550 my $str = shift;
551 my @node_names = split /,/, $str;
552 my $nd;
553 my @node_objects;
554 for my $node_name (@node_names) {
555 $nd = $tree->find_node(-id => $node_name) || $tree->find_node(-internal_id => $node_name);
556 if ($nd) { push @node_objects, $nd } else { say "Node/leaf '$node_name' not found. Ignoring..." }
557 }
558 return @node_objects
559 }
560  
561 # _each_leaf ($node): returns a list of all OTU's descended from this node, if any
562 sub _each_leaf {
563 my @leaves;
564 for ($_[0]->get_all_Descendents) { push (@leaves, $_) if $_->is_Leaf }
565 return @leaves
566 }
567  
568 # main routine to walk up from root
569 sub _wu {
570 my (@lf, @nd);
571 my $curnode = $_[0];
572 my @decs = $_[0]->each_Descendent;
573 my $visitref = $_[1];
574 my %visited = %$visitref;
575 my $node_list_ref = $_[2];
576 # my $ref_ct_otu = $_[3];
577 # my $ref_tatal_br_len = $_[4];
578  
579 for (@decs) {
580 # $ref_total_br_len += $_->branch_length;
581 if ($_->is_Leaf) {
582 push @lf, $_;
583 # $$ref_ct_otu++;
584 } else {
585 push @nd, $_
586 }
587 }
588  
589 for (@lf) { if (!exists($visited{$_})) { $visited{$_} = 1; push @$node_list_ref, $_ } }
590 for (@nd) {
591 next if exists($visited{$_});
592 $visited{$_} = 1;
593 push @$node_list_ref, $_;
594 _wu($_, \%visited, $node_list_ref)
595 }
596 }
597  
598 # Walk Up: "Walks" up from a given node and returned an order array representing the order that each node descended from the given node was visited.
599 sub _walk_up {
600 my %visited;
601 my @node_list = $_[0];
602 _wu($_[0], \%visited, \@node_list);
603 return @node_list
604 }
605  
606 sub _treeheight {
607 my $height = 0;
608 my $tree = $_[0];
609 for ($$tree->get_nodes) { $height = $_->depth if $_->depth > $height }
610 return $height
611 }
612  
613 sub _binrecursive {
614  
615 my $branchcount = 0;
616 my $noderef = $_[0];
617 my $upper = $_[1];
618 my @desc = $$noderef->each_Descendent;
619 $branchcount-- unless $$noderef->is_Leaf;
620  
621 for (@desc) {
622 $branchcount++;
623 $branchcount += _binrecursive(\$_, $upper) if $_->depth <= $upper
624 }
625 return $branchcount
626 }
627  
628 # Starting at a node that has 2 descendents, print the distance from start to desc if it's a leaf or call itself passing the internal-node descendent
629 # Input: basenode, internal node
630 sub _desclen {
631 # startlear, curnode
632 my (@dpair, @lf, @nd);
633 my $curnode = $_[0];
634 my @decs = $_[0]->each_Descendent;
635 my $visitref = $_[1];
636 my $totlen = $_[2];
637 my $vcountref = $_[3];
638 my %visited = %$visitref;
639 my $dist;
640  
641 for (@decs) { if ($_->is_Leaf) { push @lf, $_ } else { push @nd, $_ } }
642 for (@lf) {
643 next if exists($visited{$_});
644 $visited{$_} = 1;
645 $dpair[0] = $curnode;
646 $dpair[1] = $_;
647 $dist = $tree->distance(-nodes => \@dpair);
648 $$totlen += $dist;
649 $$vcountref++;
650 say $_->id, "\t$$totlen\t$$vcountref"
651 }
652  
653 for (@nd) {
654 next if exists($visited{$_});
655 $visited{$_} = 1;
656 $dpair[0] = $curnode;
657 $dpair[1] = $_;
658 $dist = $tree->distance(-nodes => \@dpair);
659 $$totlen += $dist;
660 _desclen($_, \%visited, $totlen, $vcountref)
661 }
662 }
663  
664 1;