blib/lib/Bio/Gonzales/Phylo/Util.pm untested

filter: Statementstmt 0.0% 0 / 54 Branchbran 0.0% 0 / 6 Conditioncond 0.0% 0 / 9 MC/DCmcdc n/a Subroutinesub 0.0% 0 / 8 Podpod 0.0% 0 / 2 totaltotal 0.0% 0 / 79 CC 4 SCAR 21.5
CC
4
Cov
0%
leaf_mapper
20.0
consensus
2.0
BEGIN
2.0
CRAP 8.5
1 package Bio::Gonzales::Phylo::Util;
2  
3 use warnings;
4 use strict;
5 use Carp;
6  
7 use 5.010;
8  
9 use Bio::Phylo::IO qw/parse unparse/;
10  
11 use base 'Exporter';
12 our ( @EXPORT, @EXPORT_OK, %EXPORT_TAGS );
13 our $VERSION = '0.058'; # VERSION
14  
15 @EXPORT = qw();
16 %EXPORT_TAGS = ();
17 @EXPORT_OK = qw(leaf_mapper consensus);
18  
19 sub leaf_mapper {
20 my ($pattern) = @_;
21 $pattern //= 's%09d';
22  
23 my $handler;
24 if ( ref $pattern eq 'CODE' ) {
25 $handler = $pattern;
26 } elsif ( ref $pattern eq 'HASH' ) {
27 my $i = 1;
28 $handler = sub {
29 my ($id) = @_;
30
31 return $pattern->{$id} // $id . '.NA';
32 };
33 } else {
34 $handler = sub {
35 my ($id, $i) = @_;
36 return sprintf $pattern, $i;
37 };
38 }
39  
40 return sub {
41 my ($tree) = @_;
42 return unless ($tree);
43  
44 my $leaves = $tree->get_terminals;
45 my $i = 0;
46  
47 my %map;
48 for my $l (@$leaves) {
49 my $orig_id = $l->get_name;
50 my $id = $handler->($orig_id, $i++);
51 $l->set_name($id);
52 $map{$id} = $orig_id;
53 }
54 return \%map;
55 };
56 }
57  
58 sub consensus {
59 my ( $infile, $outfile, $cutoff ) = @_;
60  
61 my $forest = parse(
62 -format => 'newick',
63 -file => $infile,
64 );
65  
66 #Bio::Phylo::Forest
67 my $consensus = $forest->make_consensus( -branches => 'average', -fraction => $cutoff // 0.5);
68 #Bio::Phylo::Forest::Tree
69 open my $outfh, '>', $outfile or die $!;
70 print $outfh $consensus->to_newick( -nodelabels => 1 );
71 $outfh->close;
72  
73 }
74  
75 1;
76  
77 __END__
78  
79 =head1 NAME
80  
81 Bio::Gonzales::Phylo::Util - utility functions for phylogenetic analysis
82  
83 =head1 SYNOPSIS
84  
85 use Bio::Gonzales::Phylo::Util qw(leaf_mapper consensus_tree);
86  
87 =head1 DESCRIPTION
88  
89 =head1 SUBROUTINES
90  
91 =over 4
92  
93 =item B<< $map_iterator = leaf_mapper($code_ref // $pattern_or_map // '%s09d') >>
94  
95 Example for a code reference:
96  
97 my $map;
98 my $handler = sub {
99 my ($id) = @_;
100
101 return $map->{$id} // $id . '.NA';
102 };
103  
104 my $map_iterator = leaf_mapper($handler);
105  
106 my $mapped_tree = $map_iterator->($tree);
107  
108 The iterator takes a Bio::Phylo::Forest::Tree object and remaps it. The
109 mapping takes place directly on the tree, thus alters it.
110  
111 =item B<< consensus_tree($input_trees_file, $consensus_tree_file) >>
112  
113 Parses the C<$input_tree_file>, builds a consensus tree and writes it to
114 C<$consensus_tree_file>.
115  
116 =back
117  
118 =head1 SEE ALSO
119  
120 =head1 AUTHOR
121  
122 jw bargsten, C<< <joachim.bargsten at wur.nl> >>
123  
124 =cut