[Bio] / FigKernelPackages / gjonewicklib.pm Repository:
ViewVC logotype

Diff of /FigKernelPackages/gjonewicklib.pm

Parent Directory Parent Directory | Revision Log Revision Log | View Patch Patch

revision 1.5, Tue Dec 19 17:32:48 2006 UTC revision 1.24, Sat Oct 2 00:01:10 2010 UTC
# Line 1  Line 1 
1    # This is a SAS component.
2    
3  #  #
4  # Copyright (c) 2003-2006 University of Chicago and Fellowship  # Copyright (c) 2003-2010 University of Chicago and Fellowship
5  # for Interpretations of Genomes. All Rights Reserved.  # for Interpretations of Genomes. All Rights Reserved.
6  #  #
7  # This file is part of the SEED Toolkit.  # This file is part of the SEED Toolkit.
# Line 20  Line 22 
22  #===============================================================================  #===============================================================================
23  #  perl functions for dealing with trees  #  perl functions for dealing with trees
24  #  #
25  #  Usage:  #  Usage:  use gjonewicklib
 #      use gjonewicklib  
 #  
26  #  #
27  #===============================================================================  #===============================================================================
28  #  Tree data structures:  #  Tree data structures:
# Line 44  Line 44 
44  #  #
45  #     $tree = \@rootnode;  #     $tree = \@rootnode;
46  #  #
47  #     @node = ( \@desc,  #  reference to list of descendants  #     $node = [ \@desc,  #  reference to list of descendants
48  #                $label, #  node label  #                $label, #  node label
49  #                $x,     #  branch length  #                $x,     #  branch length
50  #               \@c1,    #  reference to comment list 1  #               \@c1,    #  reference to comment list 1
# Line 52  Line 52 
52  #               \@c3,    #  reference to comment list 3  #               \@c3,    #  reference to comment list 3
53  #               \@c4,    #  reference to comment list 4  #               \@c4,    #  reference to comment list 4
54  #               \@c5     #  reference to comment list 5  #               \@c5     #  reference to comment list 5
55  #             )  #             ]
56  #  #
57  #  At present, no routine tests or enforces the length of the list (a single  #  At present, no routine tests or enforces the length of the list (a single
58  #  element list could be a valid internal node).  #  element list could be a valid internal node).
# Line 63  Line 63 
63  #  time, but is different from the prolog representation.  #  time, but is different from the prolog representation.
64  #  #
65  #  #
66    #  Ross Overbeek has a different tree node structure:
67    #
68    #     $node = [ Label,
69    #               DistanceToParent,
70    #               [ ParentPointer, ChildPointer1, ... ],
71    #               [ Name1\tVal1, Name2\tVal2, ... ]
72    #             ]
73    #
74    #  So:
75    #
76    #===============================================================================
77    #  Tree format interconversion:
78    #===============================================================================
79    #
80    #  $bool      = is_overbeek_tree( $tree )
81    #  $bool      = is_gjonewick_tree( $tree )
82    #
83    #  $gjonewick = overbeek_to_gjonewick( $overbeek )
84    #  $overbeek  = gjonewick_to_overbeek( $gjonewick )
85    #
86  #===============================================================================  #===============================================================================
87  #  Tree data extraction:  #  Tree data extraction:
88  #===============================================================================  #===============================================================================
# Line 79  Line 99 
99  #  @desclist = newick_desc_list( $noderef )  #  @desclist = newick_desc_list( $noderef )
100  #  $n        = newick_n_desc( $noderef )  #  $n        = newick_n_desc( $noderef )
101  #  $descref  = newick_desc_i( $noderef, $i )    # 1-based numbering  #  $descref  = newick_desc_i( $noderef, $i )    # 1-based numbering
102  #  $bool     = newick_is_tip( $noderef )  #
103    #  $bool     = node_is_tip( $noderef )
104    #  $bool     = node_is_valid( $noderef )
105    #  $bool     = node_has_lbl( $noderef )
106    #  $bool     = node_lbl_is( $noderef, $label )
107  #  #
108  #  set_newick_desc_ref( $noderef, $listref )  #  set_newick_desc_ref( $noderef, $listref )
109  #  set_newick_lbl( $noderef, $label )  #  set_newick_lbl( $noderef, $label )
# Line 90  Line 114 
114  #  set_newick_c4( $noderef, $listref )  #  set_newick_c4( $noderef, $listref )
115  #  set_newick_c5( $noderef, $listref )  #  set_newick_c5( $noderef, $listref )
116  #  set_newick_desc_list( $noderef, @desclist )  #  set_newick_desc_list( $noderef, @desclist )
117  #  set_newick_desc_i( $noderef1, $i, $noderef2)  #  set_newick_desc_i( $noderef1, $i, $noderef2 )  # 1-based numbering
118    #
119    #  $bool    = newick_is_valid( $noderef )       # verify that tree is valid
120  #  #
121  #  $bool    = newick_is_rooted( $noderef )      # 2 branches from root  #  $bool    = newick_is_rooted( $noderef )      # 2 branches from root
122  #  $bool    = newick_is_unrooted( $noderef )    # 3 or more branches from root  #  $bool    = newick_is_unrooted( $noderef )    # 3 or more branches from root
# Line 99  Line 125 
125  #  #
126  #  $n       = newick_tip_count( $noderef )  #  $n       = newick_tip_count( $noderef )
127  #  @tiprefs = newick_tip_ref_list( $noderef )  #  @tiprefs = newick_tip_ref_list( $noderef )
128    # \@tiprefs = newick_tip_ref_list( $noderef )
129  #  @tips    = newick_tip_list( $noderef )  #  @tips    = newick_tip_list( $noderef )
130    # \@tips    = newick_tip_list( $noderef )
131    #
132  #  $tipref  = newick_first_tip_ref( $noderef )  #  $tipref  = newick_first_tip_ref( $noderef )
133  #  $tip     = newick_first_tip( $noderef )  #  $tip     = newick_first_tip( $noderef )
134    #
135  #  @tips    = newick_duplicated_tips( $noderef )  #  @tips    = newick_duplicated_tips( $noderef )
136    # \@tips    = newick_duplicated_tips( $noderef )
137    #
138  #  $bool    = newick_tip_in_tree( $noderef, $tipname )  #  $bool    = newick_tip_in_tree( $noderef, $tipname )
139    #
140  #  @tips    = newick_shared_tips( $tree1, $tree2 )  #  @tips    = newick_shared_tips( $tree1, $tree2 )
141    # \@tips    = newick_shared_tips( $tree1, $tree2 )
142  #  #
143  #  $length  = newick_tree_length( $noderef )  #  $length  = newick_tree_length( $noderef )
144    #
145    #  %tip_distances = newick_tip_distances( $noderef )
146    # \%tip_distances = newick_tip_distances( $noderef )
147    #
148  #  $xmax    = newick_max_X( $noderef )  #  $xmax    = newick_max_X( $noderef )
149  #  ( $tipref,  $xmax ) = newick_most_distant_tip_ref( $noderef )  #  ( $tipref,  $xmax ) = newick_most_distant_tip_ref( $noderef )
150  #  ( $tipname, $xmax ) = newick_most_distant_tip( $noderef )  #  ( $tipname, $xmax ) = newick_most_distant_tip_name( $noderef )
151    #
152    #  Provide a standard name by which two trees can be compared for same topology
153    #
154    #  $stdname = std_tree_name( $tree )
155    #
156    #  Tree tip insertion point (tip is on branch of length x that
157    #  is inserted into branch connecting node1 and node2, a distance
158    #  x1 from node1 and x2 from node2):
159    #
160    #  [ $node1, $x1, $node2, $x2, $x ] = newick_tip_insertion_point( $tree, $tip )
161    #
162    #  Standardized label for a node in terms of intersection of 3 lowest sorting
163    #  tips (sort is lower case):
164    #
165    #  @TipOrTips = std_node_name( $tree, $node )
166  #  #
167  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
168  #  Paths from root of tree:  #  Paths from root of tree:
# Line 120  Line 173 
173  #      () is returned upon failure  #      () is returned upon failure
174  #  #
175  #  @path = path_to_tip( $treenode, $tipname )  #  @path = path_to_tip( $treenode, $tipname )
176    # \%paths = paths_to_tips( $treenode, \@%tips )
177  #  @path = path_to_named_node( $treenode, $nodename )  #  @path = path_to_named_node( $treenode, $nodename )
178    # \%paths = paths_to_named_nodes( $treenode, \@names )
179  #  @path = path_to_node_ref( $treenode, $noderef )  #  @path = path_to_node_ref( $treenode, $noderef )
180  #  #
181  #  @path = path_to_node( $node,   $tip1, $tip2, $tip3   )  #  3 tip names  #  @path  = path_to_node( $node,   $name1, $name2, $name3   )  #  3 node names
182  #  @path = path_to_node( $node, [ $tip1, $tip2, $tip3 ] )  #  Array of tips  #  @path  = path_to_node( $node, [ $name1, $name2, $name3 ] )  #  Array of names
183  #  @path = path_to_node( $node,   $tip1                 )  #  Use path_to_tip  #  @path  = path_to_node( $node,   $name1, $name2   )          #  2 node names
184  #  @path = path_to_node( $node, [ $tip1 ]               )  #  Use path_to_tip  #  @path  = path_to_node( $node, [ $name1, $name2 ] )          #  Array of names
185    #  @path  = path_to_node( $node,   $name1   )                  #  1 node name
186    #  @path  = path_to_node( $node, [ $name1 ] )                  #  Array with name
187  #  #
188  #  $distance = newick_path_length( @path )  #  $distance = newick_path_length( @path )
189  #  $distance = tip_to_tip_distance( $tree, $tip1, $tip2 )  #  $distance = tip_to_tip_distance( $tree, $tip1, $tip2 )
# Line 140  Line 197 
197  #  $treecopy = copy_newick_tree( $tree )  #  $treecopy = copy_newick_tree( $tree )
198  #  #
199  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
200  #  The following modify the existing tree, and passibly any components of that  #  The following modify the existing tree, and possibly any components of that
201  #  tree that are reached by reference.  If the old version is still needed, copy  #  tree that are reached by reference.  If the old version is still needed, copy
202  #  before modifying.  #  before modifying.
203  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
# Line 157  Line 214 
214  #  $n_changed = newick_set_undefined_branches( $node, $x )  #  $n_changed = newick_set_undefined_branches( $node, $x )
215  #  $n_changed = newick_set_all_branches( $node, $x )  #  $n_changed = newick_set_all_branches( $node, $x )
216  #  $n_changed = newick_fix_negative_branches( $tree )  #  $n_changed = newick_fix_negative_branches( $tree )
217    #  $node      = newick_rescale_branches( $node, $factor )
218    #  $node      = newick_random_branch_lengths( $node, $x1, $x2 )
219    #  $node      = newick_modify_branches( $node, \&function )
220    #  $node      = newick_modify_branches( $node, \&function, \@func_parms )
221    #
222    #  Modify comments:
223    #
224    #  $node = newick_strip_comments( $node )
225  #  #
226  #  Modify rooting and/or order:  #  Modify rooting and/or order:
227  #  #
# Line 165  Line 230 
230  #  $stdtree = std_unrooted_newick( $tree )  #  $stdtree = std_unrooted_newick( $tree )
231  #  $newtree = aesthetic_newick_tree( $tree, $direction )  #  $newtree = aesthetic_newick_tree( $tree, $direction )
232  #  $rndtree = random_order_newick_tree( $tree )  #  $rndtree = random_order_newick_tree( $tree )
233    #  $newtree - reroot_tree( $tree, \%options )
234  #  $newtree = reroot_newick_by_path( @path )  #  $newtree = reroot_newick_by_path( @path )
235  #  $newtree = reroot_newick_to_tip( $tree, $tip )  #  $newtree = reroot_newick_to_tip( $tree, $tip )
236  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )
237  #  $newtree = reroot_newick_to_node( $tree, @node )  #  $newtree = reroot_newick_to_node( $tree, @node )
238  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )
239  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )  #  $newtree = reroot_newick_between_nodes( $tree, $node1, $node2, $fraction )
240    #  $newtree = reroot_newick_at_dist_between_nodes( $tree, $node1, $node2, $distance )
241    #  $newtree = reroot_newick_to_midpoint( $tree )           # unweighted
242    #  $newtree = reroot_newick_to_midpoint_w( $tree )         # weight by tips
243  #  $newtree = reroot_newick_to_approx_midpoint( $tree )    # unweighted  #  $newtree = reroot_newick_to_approx_midpoint( $tree )    # unweighted
244  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  # weight by tips  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  # weight by tips
245  #  $newtree = uproot_tip_rooted_newick( $tree )  #  $newtree = uproot_tip_rooted_newick( $tree )
246  #  $newtree = uproot_newick( $tree )  #  $newtree = uproot_newick( $tree )
247  #  #
248  #  $newtree = prune_from_newick( $tree, $tip )  #  $newtree = prune_from_newick( $tree, $tip )
249    #  $newtree = rooted_newick_subtree( $tree,  @tips )
250    #  $newtree = rooted_newick_subtree( $tree, \@tips )
251  #  $newtree = newick_subtree( $tree,  @tips )  #  $newtree = newick_subtree( $tree,  @tips )
252  #  $newtree = newick_subtree( $tree, \@tips )  #  $newtree = newick_subtree( $tree, \@tips )
253    #  $newtree = newick_covering_subtree( $tree,  @tips )
254    #  $newtree = newick_covering_subtree( $tree, \@tips )
255  #  #
256  #  $newtree = collapse_zero_length_branches( $tree )  #  $newtree = collapse_zero_length_branches( $tree )
257  #  #
258    #  $node = newick_insert_at_node( $node, $subtree )
259    #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )
260    #
261    #===============================================================================
262    #  Tree neighborhood: subtree of n tips to represent a larger tree.
263    #===============================================================================
264    #
265    #  Focus around root:
266    #
267    #  $subtree = root_neighborhood_representative_tree( $tree, $n, \%tip_priority )
268    #  $subtree = root_neighborhood_representative_tree( $tree, $n )
269    #  @tips    = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
270    #  @tips    = root_neighborhood_representative_tips( $tree, $n )
271    # \@tips    = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
272    # \@tips    = root_neighborhood_representative_tips( $tree, $n )
273    #
274    #  Focus around a tip insertion point (the tip is not in the subtree):
275    #
276    #  $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n, \%tip_priority )
277    #  $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n )
278    #  @tips    = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
279    #  @tips    = tip_neighborhood_representative_tips( $tree, $tip, $n )
280    # \@tips    = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
281    # \@tips    = tip_neighborhood_representative_tips( $tree, $tip, $n )
282    #
283    #===============================================================================
284    #  Random trees
285    #===============================================================================
286    #
287    #   $tree = random_equibranch_tree(  @tips, \%options )
288    #   $tree = random_equibranch_tree( \@tips, \%options )
289    #   $tree = random_equibranch_tree(  @tips )
290    #   $tree = random_equibranch_tree( \@tips )
291    #
292    #   $tree = random_ultrametric_tree(  @tips, \%options )
293    #   $tree = random_ultrametric_tree( \@tips, \%options )
294    #   $tree = random_ultrametric_tree(  @tips )
295    #   $tree = random_ultrametric_tree( \@tips )
296    #
297  #===============================================================================  #===============================================================================
298  #  Tree reading and writing:  #  Tree reading and writing:
299  #===============================================================================  #===============================================================================
300    #  Write machine-readable trees:
301  #  #
302  #   writeNewickTree( $tree )  #   writeNewickTree( $tree )
303  #   writeNewickTree( $tree, $file )  #   writeNewickTree( $tree, $file )
304  #   writePrettyTree( $tree, $file )  #   writeNewickTree( $tree, \*FH )
305  #  fwriteNewickTree( $file, $tree )  #  fwriteNewickTree( $file, $tree )  # Matches the C arg list for f... I/O
306  #  $treestring = swriteNewickTree( $tree )  #  $treestring = swriteNewickTree( $tree )
307  #  $treestring = formatNewickTree( $tree )  #  $treestring = formatNewickTree( $tree )
308    #
309    #  Write human-readable trees:
310    #
311  #  @textlines  = text_plot_newick( $node, $width, $min_dx, $dy )  #  @textlines  = text_plot_newick( $node, $width, $min_dx, $dy )
312  #   printer_plot_newick( $node, $file, $width, $min_dx, $dy )  #   printer_plot_newick( $node, $file, $width, $min_dx, $dy )
313  #  #
314    #  Read trees:
315    #
316    #  $tree  = read_newick_tree( $file )  # reads to a semicolon
317    #  @trees = read_newick_trees( $file ) # reads to end of file
318  #  $tree = parse_newick_tree_str( $string )  #  $tree = parse_newick_tree_str( $string )
319  #  #
320  #===============================================================================  #===============================================================================
321    
322    
323    use Carp;
324    use Data::Dumper;
325    use strict;
326    
327  require Exporter;  require Exporter;
328    
329  our @ISA = qw(Exporter);  our @ISA = qw(Exporter);
330  our @EXPORT = qw(  our @EXPORT = qw(
331            is_overbeek_tree
332            is_gjonewick_tree
333            overbeek_to_gjonewick
334            gjonewick_to_overbeek
335            newick_is_valid
336          newick_is_rooted          newick_is_rooted
337          newick_is_unrooted          newick_is_unrooted
338          tree_rooted_on_tip          tree_rooted_on_tip
339          newick_is_bifurcating          newick_is_bifurcating
340          newick_tip_count          newick_tip_count
341            newick_tip_ref_list
342          newick_tip_list          newick_tip_list
343    
344          newick_first_tip          newick_first_tip
345          newick_duplicated_tips          newick_duplicated_tips
346          newick_tip_in_tree          newick_tip_in_tree
347          newick_shared_tips          newick_shared_tips
348    
349          newick_tree_length          newick_tree_length
350            newick_tip_distances
351          newick_max_X          newick_max_X
352          newick_most_distant_tip_ref          newick_most_distant_tip_ref
353          newick_most_distant_tip_name          newick_most_distant_tip_name
354    
355          std_newick_name          newick_tip_insertion_point
356    
357            std_tree_name
358    
359          path_to_tip          path_to_tip
360          path_to_named_node          path_to_named_node
# Line 241  Line 375 
375          newick_set_undefined_branches          newick_set_undefined_branches
376          newick_set_all_branches          newick_set_all_branches
377          newick_fix_negative_branches          newick_fix_negative_branches
378            newick_rescale_branches
379            newick_random_branch_lengths
380            newick_modify_branches
381    
382            newick_strip_comments
383    
384          normalize_newick_tree          normalize_newick_tree
385          reverse_newick_tree          reverse_newick_tree
# Line 249  Line 388 
388          unaesthetic_newick_tree          unaesthetic_newick_tree
389          random_order_newick_tree          random_order_newick_tree
390    
391            reroot_tree
392          reroot_newick_by_path          reroot_newick_by_path
393          reroot_newick_to_tip          reroot_newick_to_tip
394          reroot_newick_next_to_tip          reroot_newick_next_to_tip
395          reroot_newick_to_node          reroot_newick_to_node
396          reroot_newick_to_node_ref          reroot_newick_to_node_ref
397            reroot_newick_between_nodes
398            reroot_newick_at_dist_between_nodes
399            reroot_newick_to_midpoint
400            reroot_newick_to_midpoint_w
401          reroot_newick_to_approx_midpoint          reroot_newick_to_approx_midpoint
402          reroot_newick_to_approx_midpoint_w          reroot_newick_to_approx_midpoint_w
403          uproot_tip_rooted_newick          uproot_tip_rooted_newick
404          uproot_newick          uproot_newick
405    
406          prune_from_newick          prune_from_newick
407            rooted_newick_subtree
408          newick_subtree          newick_subtree
409            newick_covering_subtree
410          collapse_zero_length_branches          collapse_zero_length_branches
411    
412            newick_insert_at_node
413            newick_insert_between_nodes
414    
415            root_neighborhood_representative_tree
416            root_neighborhood_representative_tips
417            tip_neighborhood_representative_tree
418            tip_neighborhood_representative_tips
419    
420            random_equibranch_tree
421            random_ultrametric_tree
422    
423          writeNewickTree          writeNewickTree
424          fwriteNewickTree          fwriteNewickTree
425          strNewickTree          strNewickTree
426          formatNewickTree          formatNewickTree
427    
428            read_newick_tree
429            read_newick_trees
430          parse_newick_tree_str          parse_newick_tree_str
431    
432          printer_plot_newick          printer_plot_newick
# Line 285  Line 445 
445          newick_desc_list          newick_desc_list
446          newick_n_desc          newick_n_desc
447          newick_desc_i          newick_desc_i
448          newick_is_tip  
449          newick_is_valid          node_is_tip
450            node_is_valid
451            node_has_lbl
452            node_lbl_is
453    
454          set_newick_desc_ref          set_newick_desc_ref
455          set_newick_lbl          set_newick_lbl
# Line 305  Line 468 
468          );          );
469    
470    
471  use gjolists qw(  #-------------------------------------------------------------------------------
472          common_prefix  #  Internally used definitions
473          common_and_unique  #-------------------------------------------------------------------------------
         unique_suffixes  
   
         unique_set  
         duplicates  
         random_order  
   
         union  
         intersection  
         set_difference  
         );  
474    
475    sub array_ref { $_[0] && ref( $_[0] ) eq 'ARRAY' }
476    sub hash_ref  { $_[0] && ref( $_[0] ) eq 'HASH'  }
477    
478  use strict;  sub max       { $_[0] >= $_[1] ? $_[0] : $_[1] }
479    sub min       { $_[0] <= $_[1] ? $_[0] : $_[1] }
480    
481    
482  #-------------------------------------------------------------------------------  #===============================================================================
483  #  Internally used definitions  #  Interconvert overbeek and gjonewick trees:
484  #-------------------------------------------------------------------------------  #===============================================================================
485    
486  sub array_ref { ref( $_[0] ) eq "ARRAY" }  sub is_overbeek_tree  { array_ref( $_[0] ) && array_ref( $_[0]->[2] ) }
487  sub hash_ref  { ref( $_[0] ) eq "HASH"  }  
488    sub is_gjonewick_tree { array_ref( $_[0] ) && array_ref( $_[0]->[0] ) }
489    
490    sub overbeek_to_gjonewick
491    {
492        return () unless ref( $_[0] ) eq 'ARRAY';
493        my ( $lbl, $x, $desc ) = @{ $_[0] };
494        my ( undef, @desc ) = ( $desc && ref( $desc ) eq 'ARRAY' ) ? @$desc : ();
495        [ [ map { overbeek_to_gjonewick( $_ ) } @desc ], $lbl, $x ]
496    }
497    
498    sub gjonewick_to_overbeek
499    {
500        return () unless ref( $_[0] ) eq 'ARRAY';
501        my ( $desc, $lbl, $x ) = @{ $_[0] };
502        my @desc   = ( $desc && ref( $desc ) eq 'ARRAY' ) ? @$desc : ();
503        my $parent = $_[1];
504        my $node   = [ $lbl, $x, undef, [] ];
505        $node->[2] = [ $parent, map { gjonewick_to_overbeek( $_, $node ) } @desc ];
506        return $node;
507    }
508    
509    
510  #===============================================================================  #===============================================================================
# Line 346  Line 522 
522  #     @list    = newick_desc_list( $noderef )  #     @list    = newick_desc_list( $noderef )
523  #     $int     = newick_n_desc( $noderef )  #     $int     = newick_n_desc( $noderef )
524  #     $listref = newick_desc_i( $noderef )  #     $listref = newick_desc_i( $noderef )
525    #
526  #     $bool    = node_is_tip( $noderef )  #     $bool    = node_is_tip( $noderef )
527  #     $bool    = node_is_valid( $noderef )  #     $bool    = node_is_valid( $noderef )
528    #     $bool    = node_has_lbl( $noderef )
529    #     $bool    = node_lbl_is( $noderef, $label )
530  #  #
531  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
532    
533  sub newick_desc_ref { $_[0]->[0] }  # = ${$_[0]}[0]  sub newick_desc_ref { ref($_[0]) ? $_[0]->[0] : Carp::confess() }
534  sub newick_lbl      { $_[0]->[1] }  sub newick_lbl      { ref($_[0]) ? $_[0]->[1] : Carp::confess() }
535  sub newick_x        { $_[0]->[2] }  sub newick_x        { ref($_[0]) ? $_[0]->[2] : Carp::confess() }
536  sub newick_c1       { $_[0]->[3] }  sub newick_c1       { ref($_[0]) ? $_[0]->[3] : Carp::confess() }
537  sub newick_c2       { $_[0]->[4] }  sub newick_c2       { ref($_[0]) ? $_[0]->[4] : Carp::confess() }
538  sub newick_c3       { $_[0]->[5] }  sub newick_c3       { ref($_[0]) ? $_[0]->[5] : Carp::confess() }
539  sub newick_c4       { $_[0]->[6] }  sub newick_c4       { ref($_[0]) ? $_[0]->[6] : Carp::confess() }
540  sub newick_c5       { $_[0]->[7] }  sub newick_c5       { ref($_[0]) ? $_[0]->[7] : Carp::confess() }
541    
542  sub newick_desc_list {  sub newick_desc_list
543      my $node = $_[0];  {
544      ! array_ref( $node      ) ? undef           :      local $_ = $_[0];
545        array_ref( $node->[0] ) ? @{ $node->[0] } :      array_ref( $_ ) && array_ref( $_->[0] ) ? @{ $_->[0] } : ();
546                                  ()              ;  }
547  }  
548    sub newick_n_desc
549  sub newick_n_desc {  {
550      my $node = $_[0];      local $_ = $_[0];
551      ! array_ref( $node      ) ? undef                  :      array_ref( $_ ) && array_ref( $_->[0] ) ? scalar @{ $_->[0] } : 0;
552        array_ref( $node->[0] ) ? scalar @{ $node->[0] } :  }
553                                  0                      ;  
554  }  sub newick_desc_i
555    {
556  sub newick_desc_i {      local $_ = $_[0];
557      my ( $node, $i ) = @_;      my    $i = $_[1];
558      ! array_ref( $node      ) ? undef              :      array_ref( $_ ) && $i && array_ref( $_->[0] ) ? $_->[0]->[$i-1] : undef;
559        array_ref( $node->[0] ) ? $node->[0]->[$i-1] :  }
560                                  undef              ;  
561  }  sub node_is_tip
562    {
563  sub node_is_tip {      local $_ = $_[0];
564      my $node = $_[0];      ! array_ref( $_ )      ? undef             :  # Not a node ref
565      ! array_ref( $node      ) ? undef                :  # Not a node ref        array_ref( $_->[0] ) ? @{ $_->[0] } == 0 :  # Empty descend list?
       array_ref( $node->[0] ) ? @{ $node->[0] } == 0 :  # Empty descend list?  
566                                  1                    ;  # No descend list                                  1                    ;  # No descend list
567  }  }
568    
569  sub node_is_valid {      #  An array ref with nonempty descend list or a label  sub node_is_valid      #  An array ref with nonempty descend list or a label
570      my $node = $_[0];  {
571      array_ref( $node ) && (  array_ref( $node->[0] ) && @{ $node->[0] }      local $_ = $_[0];
572                            || defined( $node->[1] )      array_ref( $_ ) && ( array_ref( $_->[0] ) && @{ $_->[0] } || defined( $_->[1] ) )
                           )  
573  }  }
574    
575    sub node_has_lbl { local $_ = $_[0]->[1]; defined( $_ ) && ( $_ ne '' ) }
576    
577    sub node_lbl_is { local $_ = $_[0]->[1]; defined( $_ ) && ( $_ eq $_[1] ) }
578    
579    
580  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
581  #  Set tree structure values  #  Set tree structure values
# Line 409  Line 590 
590  sub set_newick_c4       { $_[0]->[6] = $_[1] }  sub set_newick_c4       { $_[0]->[6] = $_[1] }
591  sub set_newick_c5       { $_[0]->[7] = $_[1] }  sub set_newick_c5       { $_[0]->[7] = $_[1] }
592    
593  sub set_newick_desc_list {  sub set_newick_desc_list
594      my $node = shift;  {
595      array_ref( $node ) || return;      local $_ = shift;
596      if ( array_ref( $node->[0] ) ) { @{ $node->[0] } =   @_   }      array_ref( $_ ) || return;
597      else                           {    $node->[0]   = [ @_ ] }      if ( array_ref( $_->[0] ) ) { @{ $_->[0] } =   @_   }
598        else                        {    $_->[0]   = [ @_ ] }
599  }  }
600    
601  sub set_newick_desc_i {  sub set_newick_desc_i
602    {
603      my ( $node1, $i, $node2 ) = @_;      my ( $node1, $i, $node2 ) = @_;
604      array_ref( $node1 ) && array_ref( $node2 ) || return;      array_ref( $node1 ) && array_ref( $node2 ) || return;
605      if ( array_ref( $node1->[0] ) ) { $node1->[0]->[$i-1] =   $node2   }      if ( array_ref( $node1->[0] ) ) { $node1->[0]->[$i-1] =   $node2   }
# Line 427  Line 610 
610  #===============================================================================  #===============================================================================
611  #  Some tree property tests:  #  Some tree property tests:
612  #===============================================================================  #===============================================================================
613    #  Tree is valid?
614    #
615    #  $bool = newick_is_valid( $node, $verbose )
616    #-------------------------------------------------------------------------------
617    sub newick_is_valid
618    {
619        my $node = shift;
620    
621        if ( ! array_ref( $node ) )
622        {
623            print STDERR "Node is not array reference\n" if $_[0];
624            return 0;
625        }
626    
627        my @node = @$node;
628        if ( ! @node )
629        {
630            print STDERR "Node is empty array reference\n" if $_[0];
631            return 0;
632        }
633    
634        # Must have descendant or label:
635    
636        if ( ! ( array_ref( $node[0] ) && @{ $node[0] } ) && ! $node[2] )
637        {
638            print STDERR "Node has neither descendant nor label\n" if $_[0];
639            return 0;
640        }
641    
642        #  If comments are present, they must be array references
643    
644        foreach ( ( @node > 3 ) ? @node[ 3 .. $#node ] : () )
645        {
646            if ( defined( $_ ) && ! array_ref( $_ ) )
647            {
648                print STDERR "Node has neither descendant or label\n" if $_[0];
649                return 0;
650            }
651        }
652    
653        #  Inspect the descendants:
654    
655        foreach ( array_ref( $node[0] ) ? @{ $node[0] } : () )
656        {
657            newick_is_valid( $_, @_ ) || return 0
658        }
659    
660        return 1;
661    }
662    
663    
664    #-------------------------------------------------------------------------------
665  #  Tree is rooted (2 branches at root node)?  #  Tree is rooted (2 branches at root node)?
666  #  #
667  #  $bool = newick_is_rooted( $node )  #  $bool = newick_is_rooted( $node )
668  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
669  sub newick_is_rooted {  sub newick_is_rooted
670      my $node = $_[0];  {
671      ! array_ref( $node      ) ? undef                :  # Not a node ref      local $_ = $_[0];
672        array_ref( $node->[0] ) ? @{ $node->[0] } == 2 :  # 2 branches      ! array_ref( $_      ) ? undef             :  # Not a node ref
673          array_ref( $_->[0] ) ? @{ $_->[0] } == 2 :  # 2 branches
674                                  0                    ;  # No descend list                                  0                    ;  # No descend list
675  }  }
676    
# Line 444  Line 680 
680  #  #
681  #  $bool = newick_is_unrooted( $node )  #  $bool = newick_is_unrooted( $node )
682  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
683  sub newick_is_unrooted {  sub newick_is_unrooted
684      my $node = $_[0];  {
685      ! array_ref( $node      ) ? undef                :  # Not a node ref      local $_ = $_[0];
686        array_ref( $node->[0] ) ? @{ $node->[0] } >= 3 :  # Over 2 branches      ! array_ref( $_      ) ? undef             :  # Not a node ref
687          array_ref( $_->[0] ) ? @{ $_->[0] } >= 3 :  # Over 2 branches
688                                  0                    ;  # No descend list                                  0                    ;  # No descend list
689  }  }
690    
# Line 457  Line 694 
694  #  #
695  #  $bool = newick_is_tip_rooted( $node )  #  $bool = newick_is_tip_rooted( $node )
696  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
697  sub newick_is_tip_rooted {  sub newick_is_tip_rooted
698      my $node = $_[0];  {
699      ! array_ref( $node      ) ? undef                :  # Not a node ref      local $_ = $_[0];
700        array_ref( $node->[0] ) ? @{ $node->[0] } == 1 :  # 1 branch      ! array_ref( $_      ) ? undef             :  # Not a node ref
701          array_ref( $_->[0] ) ? @{ $_->[0] } == 1 :  # 1 branch
702                                  0                    ;  # No descend list                                  0                    ;  # No descend list
703  }  }
704    
# Line 472  Line 710 
710  #  #
711  #  $n_desc = newick_is_bifurcating( $node )  #  $n_desc = newick_is_bifurcating( $node )
712  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
713  sub newick_is_bifurcating {  sub newick_is_bifurcating
714    {
715      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
716      if ( ! array_ref( $node ) ) { return undef }    #  Bad arg      if ( ! array_ref( $node ) ) { return undef }    #  Bad arg
717    
# Line 493  Line 732 
732  #  #
733  #  $n = newick_tip_count( $node )  #  $n = newick_tip_count( $node )
734  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
735  sub newick_tip_count {  sub newick_tip_count
736    {
737      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
738    
739      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
# Line 512  Line 752 
752  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
753  #  List of tip nodes:  #  List of tip nodes:
754  #  #
755  #  @tips = newick_tip_ref_list( $node )  #  @tips = newick_tip_ref_list( $noderef )
756    # \@tips = newick_tip_ref_list( $noderef )
757  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
758  sub newick_tip_ref_list {  sub newick_tip_ref_list
759    {
760      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
761    
762      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
# Line 523  Line 765 
765      my @list = ();      my @list = ();
766    
767      #  Tree rooted on tip?      #  Tree rooted on tip?
768      if ( $imax == 1 && ! $not_root && newick_lbl( $node ) ) { push @list, $node }      if ( ! $not_root && ( $imax == 1 ) && node_has_lbl( $node ) ) { push @list, $node }
769    
770      foreach ( newick_desc_list( $node ) ) {      foreach ( newick_desc_list( $node ) ) {
771          push @list, newick_tip_ref_list( $_, 1 );          push @list, newick_tip_ref_list( $_, 1 );
772      }      }
773    
774      @list;      wantarray ? @list : \@list;
775  }  }
776    
777    
# Line 537  Line 779 
779  #  List of tips:  #  List of tips:
780  #  #
781  #  @tips = newick_tip_list( $node )  #  @tips = newick_tip_list( $node )
782    # \@tips = newick_tip_list( $node )
783  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
784  sub newick_tip_list {  sub newick_tip_list
785      map { newick_lbl( $_ ) } newick_tip_ref_list( $_[0] );  {
786        my @tips = map { newick_lbl( $_ ) } newick_tip_ref_list( $_[0] );
787        wantarray ? @tips : \@tips;
788  }  }
789    
790    
# Line 548  Line 793 
793  #  #
794  #  $tipref = newick_first_tip_ref( $node )  #  $tipref = newick_first_tip_ref( $node )
795  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
796  sub newick_first_tip_ref {  sub newick_first_tip_ref
797    {
798      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
799      valid_node( $node ) || return  undef;      valid_node( $node ) || return  undef;
800    
# Line 565  Line 811 
811  #  #
812  #  $tip = newick_first_tip( $node )  #  $tip = newick_first_tip( $node )
813  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
814  sub newick_first_tip {  sub newick_first_tip
815    {
816      my ( $noderef ) = @_;      my ( $noderef ) = @_;
817    
818      my $tipref;      my $tipref;
# Line 578  Line 825 
825  #  List of duplicated tip labels.  #  List of duplicated tip labels.
826  #  #
827  #  @tips = newick_duplicated_tips( $node )  #  @tips = newick_duplicated_tips( $node )
828    # \@tips = newick_duplicated_tips( $node )
829  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
830  sub newick_duplicated_tips {  sub newick_duplicated_tips
831      duplicates( newick_tip_list( $_[0] ) );  {
832        my @tips = &duplicates( newick_tip_list( $_[0] ) );
833        wantarray ? @tips : \@tips;
834  }  }
835    
836    
# Line 589  Line 839 
839  #  #
840  #  $bool = newick_tip_in_tree( $node, $tipname )  #  $bool = newick_tip_in_tree( $node, $tipname )
841  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
842  sub newick_tip_in_tree {  sub newick_tip_in_tree
843    {
844      my ( $node, $tip, $not_root ) = @_;      my ( $node, $tip, $not_root ) = @_;
845    
846      my $n = newick_n_desc( $node );      my $n = newick_n_desc( $node );
847      if ( $n < 1 ) { return ( newick_lbl( $node ) eq $tip) ? 1 : 0 }      if ( $n < 1 ) { return node_lbl_is( $node, $tip ) ? 1 : 0 }
848    
849      #  Special case for tree rooted on tip      #  Special case for tree rooted on tip
850    
851      if ( $n == 1 && ( ! $not_root ) && newick_lbl( $node ) eq $tip ) { return 1 }      if ( ( $n == 1 ) && ( ! $not_root ) && node_lbl_is( $node, $tip ) )
852        {
853            return 1
854        }
855    
856      foreach ( newick_desc_list( $node ) ) {      foreach ( newick_desc_list( $node ) ) {
857          if ( newick_tip_in_tree( $_, $tip, 1 ) ) { return 1 }          if ( newick_tip_in_tree( $_, $tip, 1 ) ) { return 1 }
# Line 611  Line 865 
865  #  Tips shared between 2 trees.  #  Tips shared between 2 trees.
866  #  #
867  #  @tips = newick_shared_tips( $tree1, $tree2 )  #  @tips = newick_shared_tips( $tree1, $tree2 )
868    # \@tips = newick_shared_tips( $tree1, $tree2 )
869  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
870  sub newick_shared_tips {  sub newick_shared_tips
871      my ( $Tree1, $Tree2 ) = @_;  {
872      my ( @Tips1 ) = newick_tip_list( $Tree1 );      my ( $tree1, $tree2 ) = @_;
873      my ( @Tips2 ) = newick_tip_list( $Tree2 );      my $tips1 = newick_tip_list( $tree1 );
874      intersection( \@Tips1, \@Tips2 );      my $tips2 = newick_tip_list( $tree2 );
875        my @tips = &intersection( $tips1, $tips2 );
876        wantarray ? @tips : \@tips;
877  }  }
878    
879    
# Line 625  Line 882 
882  #  #
883  #  $length = newick_tree_length( $node )  #  $length = newick_tree_length( $node )
884  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
885  sub newick_tree_length {  sub newick_tree_length
886    {
887      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
888    
889      my $x = $not_root ? newick_x( $node ) : 0;      my $x = $not_root ? newick_x( $node ) : 0;
# Line 638  Line 896 
896    
897    
898  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
899    #  Hash of tip nodes and corresponding distances from root:
900    #
901    #   %tip_distances = newick_tip_distances( $node )
902    #  \%tip_distances = newick_tip_distances( $node )
903    #-------------------------------------------------------------------------------
904    sub newick_tip_distances
905    {
906        my ( $node, $x, $hash ) = @_;
907        my $root = ! $hash;
908        ref( $hash ) eq 'HASH' or $hash = {};
909    
910        $x ||= 0;
911        $x  += newick_x( $node ) || 0;
912    
913        #  Is it a tip?
914    
915        my $n_desc = newick_n_desc( $node );
916        if ( ! $n_desc )
917        {
918            $hash->{ newick_lbl( $node ) } = $x;
919            return $hash;
920        }
921    
922        #  Tree rooted on tip?
923    
924        if ( $root && ( $n_desc == 1 ) && node_has_lbl( $node ) )
925        {
926            $hash->{ newick_lbl( $node ) } = 0;  # Distance to root is zero
927        }
928    
929        foreach ( newick_desc_list( $node ) ) { newick_tip_distances( $_, $x, $hash ) }
930    
931        wantarray ? %$hash : $hash;
932    }
933    
934    
935    #-------------------------------------------------------------------------------
936  #  Tree max X.  #  Tree max X.
937  #  #
938  #  $xmax = newick_max_X( $node )  #  $xmax = newick_max_X( $node )
939  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
940  sub newick_max_X {  sub newick_max_X
941    {
942      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
943    
944      my $xmax = 0;      my $xmax = 0;
# Line 661  Line 957 
957  #  #
958  #  ( $xmax, @path ) = newick_most_distant_tip_path( $tree )  #  ( $xmax, @path ) = newick_most_distant_tip_path( $tree )
959  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
960  sub newick_most_distant_tip_path {  sub newick_most_distant_tip_path
961    {
962      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
963    
964      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
# Line 683  Line 980 
980  #  #
981  #  ( $tipref, $xmax ) = newick_most_distant_tip_ref( $tree )  #  ( $tipref, $xmax ) = newick_most_distant_tip_ref( $tree )
982  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
983  sub newick_most_distant_tip_ref {  sub newick_most_distant_tip_ref
984    {
985      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
986    
987      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
# Line 705  Line 1003 
1003  #  #
1004  #  ( $tipname, $xmax ) = newick_most_distant_tip_name( $tree )  #  ( $tipname, $xmax ) = newick_most_distant_tip_name( $tree )
1005  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1006  sub newick_most_distant_tip_name {  sub newick_most_distant_tip_name
1007    {
1008      my ( $tipref, $xmax ) = newick_most_distant_tip_ref( $_[0] );      my ( $tipref, $xmax ) = newick_most_distant_tip_ref( $_[0] );
1009      ( newick_lbl( $tipref ), $xmax )      ( newick_lbl( $tipref ), $xmax )
1010  }  }
1011    
1012    
1013  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1014    #  Tree tip insertion point (with standard node labels):
1015    #
1016    #  [ $node1, $x1, $node2, $x2, $x ]
1017    #           = newick_tip_insertion_point( $tree, $tip )
1018    #
1019    #  Which means: tip is on a branch of length x that is inserted into the branch
1020    #  connecting node1 and node2, at distance x1 from node1 and x2 from node2.
1021    #
1022    #                x1    +------ n1a (lowest sorting tip of this subtree)
1023    #            +--------n1
1024    #            |         +------n1b (lowest sorting tip of this subtree)
1025    #  tip-------n
1026    #        x   |       +------------- n2a (lowest sorting tip of this subtree)
1027    #            +------n2
1028    #               x2   +-------- n2b (lowest sorting tip of this subtree)
1029    #
1030    #  The designations of 1 vs 2, and a vs b are chosen such that:
1031    #     n1a < n1b, and n2a < n2b, and n1a < n2a
1032    #
1033    #  Then the statandard description becomes:
1034    #
1035    #  [ [ $n1a, min(n1b,n2a), max(n1b,n2a) ], x1,
1036    #    [ $n2a, min(n2b,n1a), max(n2b,n1a) ], x2,
1037    #    x
1038    #  ]
1039    #
1040    #-------------------------------------------------------------------------------
1041    sub newick_tip_insertion_point
1042    {
1043        my ( $tree, $tip ) = @_;
1044        $tree && $tip && ref( $tree ) eq 'ARRAY'    or return undef;
1045        $tree = copy_newick_tree( $tree )           or return undef;
1046        $tree = reroot_newick_to_tip( $tree, $tip ) or return undef;
1047        my $node = $tree;
1048    
1049        my $x  = 0;                        # Distance to node
1050        my $dl = newick_desc_ref( $node ); # Descendent list of tip node;
1051        $node  = $dl->[0];                 # Node adjacent to tip
1052        $dl    = newick_desc_ref( $node );
1053        while ( $dl && ( @$dl == 1 ) )     # Traverse unbranched nodes
1054        {
1055            $node = $dl->[0];
1056            $x   += newick_x( $node );
1057            $dl   = newick_desc_ref( $node );
1058        }
1059        $x += newick_x( $node );
1060    
1061        #  We are now at the node that is the insertion point.
1062        #  Is it a tip?
1063    
1064        my @description;
1065    
1066        if ( ( ! $dl ) || @$dl == 0 )
1067        {
1068            @description = ( [ newick_lbl( $node ) ], 0, undef, 0, $x );
1069        }
1070    
1071        #  Is it a trifurcation or greater, in which case it does not go
1072        #  away with tip deletion?
1073    
1074        elsif ( @$dl > 2 )
1075        {
1076            @description = ( [ std_node_name( $node, $node ) ], 0, undef, 0, $x );
1077        }
1078    
1079        #  The node is bifurcating.  We need to describe it.
1080    
1081        else
1082        {
1083            my ( $n1, $x1 ) = describe_descendant( $dl->[0] );
1084            my ( $n2, $x2 ) = describe_descendant( $dl->[1] );
1085    
1086            if ( @$n1 == 2 ) { push @$n1, $n2->[0] }
1087            if ( @$n2 == 2 )
1088            {
1089                @$n2 = sort { lc $a cmp lc $b } ( @$n2, $n1->[0] );
1090            }
1091            if ( @$n1 == 3 ) { @$n2 = sort { lc $a cmp lc $b } @$n2 }
1092            @description = ( $n1, $x1, $n2, $x2, $x );
1093        }
1094    
1095        return wantarray ? @description : \@description;
1096    }
1097    
1098    
1099    sub describe_descendant
1100    {
1101        my $node = shift;
1102    
1103        my $x  = 0;                        # Distance to node
1104        my $dl = newick_desc_ref( $node ); # Descendent list of tip node;
1105        while ( $dl && ( @$dl == 1 ) )     # Traverse unbranched nodes
1106        {
1107            $node = $dl->[0];
1108            $x   += newick_x( $node );
1109            $dl   = newick_desc_ref( $node );
1110        }
1111        $x += newick_x( $node );
1112    
1113        #  Is it a tip?  Return list of one tip;
1114    
1115        if ( ( ! $dl ) || ! @$dl ) { return ( [ newick_lbl( $node ) ], $x ) }
1116    
1117        #  Get tips of each descendent, keeping lowest sorting from each.
1118        #  Return the two lowest of those (the third will come from the
1119        #  other side of the original node).
1120    
1121        my @rep_tips = sort { lc $a cmp lc $b }
1122                       map  { ( sort { lc $a cmp lc $b } newick_tip_list( $_ ) )[0] }
1123                       @$dl;
1124        return ( [ @rep_tips[0,1] ], $x );
1125    }
1126    
1127    
1128    #-------------------------------------------------------------------------------
1129  #  Standard node name:  #  Standard node name:
1130  #     Tip label if at a tip  #     Tip label if at a tip
1131  #     Three sorted tip labels intersecting at node, each being smallest  #     Three sorted tip labels intersecting at node, each being smallest
1132  #           of all the tips of their subtrees  #           of all the tips of their subtrees
1133  #  #
1134  #  @TipOrTips = std_node_name( $Tree, $Node )  #  @TipOrTips = std_node_name( $tree, $node )
1135  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1136  sub std_node_name {  sub std_node_name
1137    {
1138      my $tree = $_[0];      my $tree = $_[0];
1139    
1140      #  Node reference is last element of path to node      #  Node reference is last element of path to node
# Line 727  Line 1142 
1142      my $noderef = ( path_to_node( @_ ) )[-1];      my $noderef = ( path_to_node( @_ ) )[-1];
1143      defined( $noderef ) || return ();      defined( $noderef ) || return ();
1144    
1145      if ( node_is_tip( $noderef ) || $noderef eq $tree ) {  # Is it a tip?      if ( node_is_tip( $noderef ) || ( $noderef eq $tree ) ) {  # Is it a tip?
1146          return newick_lbl( $noderef );          return newick_lbl( $noderef );
1147      }      }
1148    
1149      #  Work through lists of tips in descendant subtrees, removing them from      #  Work through lists of tips in descendant subtrees, removing them from
1150      #  @rest, and keeping the best tip for each subtree.      #  @rest, and keeping the best tip for each subtree.
1151    
1152      my @rest = tips_in_newick( $tree );      my @rest = newick_tip_list( $tree );
1153      my @best = map {      my @best = map
1154              my @tips = sort { lc $a cmp lc $b } tips_in_newick( $_ );            {
1155              @rest = set_difference( \@rest, \@tips );              my @tips = sort { lc $a cmp lc $b } newick_tip_list( $_ );
1156                @rest = &set_difference( \@rest, \@tips );
1157              $tips[0];              $tips[0];
1158          } newick_desc_list( $noderef );          } newick_desc_list( $noderef );
1159    
# Line 763  Line 1179 
1179  #  #
1180  #  @path = path_to_tip( $treenode, $tipname )  #  @path = path_to_tip( $treenode, $tipname )
1181  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1182  sub path_to_tip {  sub path_to_tip
1183      my ( $node, $tip, @path0 ) = @_;  {
1184        my ( $node, $tip ) = @_;
1185    
     push @path0, $node;  
1186      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
     if ( $imax < 1 ) { return ( newick_lbl( $node ) eq $tip ) ? @path0 : () }  
1187    
1188      #  Special case for tree rooted on tip      #  Tip (including root tip):
1189    
1190      if ( ( $imax  == 1 )                  #  One descendant      return ( $node ) if ( $imax < 2 ) && node_lbl_is( $node, $tip );
       && ( @path0 == 1 )                  #  First step in path  
       && ( newick_lbl( $node ) eq $tip )  #  Label matches  
        ) { return @path0 }  
1191    
     my @path;  
1192      for (my $i = 1; $i <= $imax; $i++ ) {      for (my $i = 1; $i <= $imax; $i++ ) {
1193         @path = path_to_tip( newick_desc_i( $node, $i ), $tip, ( @path0, $i ) );         my @suf = path_to_tip( newick_desc_i( $node, $i ), $tip );
1194         if ( @path ) { return @path }         return ( $node, $i, @suf ) if @suf;
1195      }      }
1196    
1197      ();  #  Not found      ();  #  Not found
# Line 788  Line 1199 
1199    
1200    
1201  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1202  #  Path to named node.  #  Paths to tips:
1203  #  Like path to tip, but will find named internal nodes as well.  #
1204    #  \%paths = paths_to_tips( $treenode, \@tips )
1205    #  \%paths = paths_to_tips( $treenode, \%tips )
1206  #  #
 #  @path = path_to_named_node( $treenode, $name )  
1207  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1208  sub path_to_named_node {  sub paths_to_tips
1209      my ( $node, $name, @path0 ) = @_;  {
1210        my ( $node, $tips ) = @_;
1211        return {} if ! ( $tips && ref( $tips ) );
1212    
1213        #  Replace request for list with request by hash
1214    
1215      push @path0, $node;      if ( ref( $tips ) eq 'ARRAY' ) { $tips = { map { $_ => 1 } @$tips } }
     if ( newick_lbl( $node ) eq $name ) { return @path0 }  
1216    
1217      my @path;      my $paths = {};
1218      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
1219      for ( my $i = 1; $i <= $imax; $i++ ) {      if ( $imax < 2 )
1220         @path = path_to_named_node( newick_desc_i( $node, $i ), $name, ( @path0, $i ) );      {
1221         if ( @path ) { return @path }          my $lbl;
1222            if ( node_has_lbl( $node ) && defined( $lbl = newick_lbl( $node ) ) && $tips->{ $lbl } )
1223            {
1224                delete $tips->{ $lbl };
1225                $paths->{ $lbl } = [ $node ];
1226            }
1227            return $paths if ! $imax;  # tip (no more to do it tested below)
1228      }      }
1229    
1230      ();  #  Not found      for ( my $i = 1; $i <= $imax && keys %$tips; $i++ )
1231        {
1232           my $new = paths_to_tips( newick_desc_i( $node, $i ), $tips );
1233           foreach ( keys %$new )
1234           {
1235               splice @{ $new->{ $_ } }, 0, 0, ( $node, $i );
1236               $paths->{ $_ } = $new->{ $_ };
1237           }
1238        }
1239    
1240        return $paths;
1241  }  }
1242    
1243    
1244  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1245  #  Path to node reference.  #  Path to named node.  Like path to tip, but also finds named internal nodes.
1246    #
1247    #  @path = path_to_named_node( $treenode, $name )
1248  #  #
 #  @path = path_to_node_ref( $treenode, $noderef )  
1249  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1250  sub path_to_node_ref {  sub path_to_named_node
1251      my ( $node, $noderef, @path0 ) = @_;  {
1252        my ( $node, $name ) = @_;
1253    
1254      push @path0, $node;      return ( $node ) if node_lbl_is( $node, $name );
     if ( $node eq $noderef ) { return @path0 }  
1255    
     my @path;  
1256      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
1257      for ( my $i = 1; $i <= $imax; $i++ ) {      for ( my $i = 1; $i <= $imax; $i++ ) {
1258         @path = path_to_node_ref( newick_desc_i( $node, $i ), $noderef, ( @path0, $i ) );         my @suf = path_to_named_node( newick_desc_i( $node, $i ), $name );
1259         if ( @path ) { return @path }         return ( $node, $i, @suf ) if @suf;
1260      }      }
1261    
1262      ();  #  Not found      ();  #  Not found
# Line 833  Line 1264 
1264    
1265    
1266  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1267  #  Path to node, as defined by 1 or 3 tips.  #  Paths to named nodes in tree (need not be tips):
1268    #
1269    #  \%paths = paths_to_named_nodes( $treenode, \@names )
1270    #  \%paths = paths_to_named_nodes( $treenode, \%names )
1271  #  #
1272  #  @path = path_to_node( $node,   $tip1, $tip2, $tip3   )  #  3 tip names  #-------------------------------------------------------------------------------
1273  #  @path = path_to_node( $node, [ $tip1, $tip2, $tip3 ] )  #  Allow array ref  sub paths_to_named_nodes
1274  #  @path = path_to_node( $node,   $tip1                 )  #  Use path_to_tip  {
1275  #  @path = path_to_node( $node, [ $tip1 ]               )  #  Use path_to_tip      my ( $node, $names ) = @_;
1276  #-------------------------------------------------------------------------------      return {} if ! ( $names && ref( $names ) );
 sub path_to_node {  
     my ( $node, $tip1, $tip2, $tip3 ) = @_;  
     array_ref( $node ) && defined( $tip1 ) || return ();  
1277    
1278      # Allow arg 2 to be an array reference      #  Replace request for list with request by hash
     if ( array_ref( $tip1 ) ) { ( $tip1, $tip2, $tip3 ) = @$tip1 }  
1279    
1280      my @p1 = path_to_tip( $node, $tip1 );                #  Path to first tip      if ( ref( $names ) eq 'ARRAY' ) { $names = { map { $_ => 1 } @$names } }
     @p1 || return ();                                    #  Was the tip found?  
     defined( $tip2 ) && defined( $tip3 ) || return @p1;  #  Two more defined?  
1281    
1282      my @p2 = path_to_tip( $node, $tip2 );      my $paths = {};
1283      my @p3 = path_to_tip( $node, $tip3 );      my $imax = newick_n_desc( $node );
1284      @p2 && @p3 || return ();                             #  Were they found?  
1285        my $lbl;
1286        if ( node_has_lbl( $node ) && defined( $lbl = newick_lbl( $node ) ) && $names->{ $lbl } )
1287        {
1288            delete $names->{ $lbl };
1289            $paths->{ $lbl } = [ $node ];
1290        }
1291        return $paths if ! $imax;  # tip (no more to do it tested below)
1292    
1293      # Find the common prefix for each pair of paths      for ( my $i = 1; $i <= $imax && keys %$names; $i++ )
1294      my @p12 = common_prefix( \@p1, \@p2 );      {
1295      my @p13 = common_prefix( \@p1, \@p3 );         my $new = paths_to_named_nodes( newick_desc_i( $node, $i ), $names );
1296      my @p23 = common_prefix( \@p2, \@p3 );         foreach ( keys %$new )
1297           {
1298               splice @{ $new->{ $_ } }, 0, 0, ( $node, $i );
1299               $paths->{ $_ } = $new->{ $_ };
1300           }
1301        }
1302    
1303      # Return the longest common prefix of any two paths      return $paths;
     ( @p12 >= @p13 && @p12 >= @p23 ) ? @p12 :  
     ( @p13 >= @p23 )                 ? @p13 :  
                                        @p23 ;  
1304  }  }
1305    
1306    
1307  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1308  #  Distance along path.  #  Path to node reference.
1309    #
1310    #  @path = path_to_node_ref( $treenode, $noderef )
1311  #  #
 #  $distance = newick_path_length( @path )  
1312  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1313  sub newick_path_length {  sub path_to_node_ref
1314      my $node = shift;      #  Discard the first node  {
1315      array_ref( $node ) || return undef;      my ( $node, $noderef ) = @_;
1316      @_ ? distance_along_path_2( @_ ) : 0;  
1317        return ( $node ) if ( $node eq $noderef );
1318    
1319        my $imax = newick_n_desc( $node );
1320        for ( my $i = 1; $i <= $imax; $i++ ) {
1321            my @suf = path_to_node_ref( newick_desc_i( $node, $i ), $noderef );
1322            return ( $node, $i, @suf ) if @suf;
1323  }  }
1324    
1325        ();  #  Not found
1326    }
1327    
1328  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
1329  #  This expects to get path minus root node:  #-------------------------------------------------------------------------------
1330    #  Path to node, as defined by 1, 2 or 3 node names (usually tips).
1331    #
1332    #  @path = path_to_node( $tree,   $name1, $name2, $name3   )  #  3 tip names
1333    #  @path = path_to_node( $tree, [ $name1, $name2, $name3 ] )  #  Allow array ref
1334    #  @path = path_to_node( $tree,   $name1, $name2   )          #  2 tip names
1335    #  @path = path_to_node( $tree, [ $name1, $name2 ] )          #  Allow array ref
1336    #  @path = path_to_node( $tree,   $name1   )                  #  Path to tip or named node
1337    #  @path = path_to_node( $tree, [ $name1 ] )                  #  Allow array ref
1338    #
1339    #-------------------------------------------------------------------------------
1340    sub path_to_node
1341    {
1342        my ( $tree, @names ) = @_;
1343        array_ref( $tree ) && defined( $names[0] ) || return ();
1344    
1345        # Allow arg 2 to be an array reference
1346    
1347        @names = @{ $names[0] }  if array_ref( $names[0] );
1348    
1349        return () if @names < 1 || @names > 3;
1350    
1351        #  Just one name:
1352    
1353        return path_to_named_node( $tree, $names[0] ) if ( @names == 1 );
1354    
1355        my @paths = values %{ paths_to_named_nodes( $tree, \@names ) };
1356    
1357        #  Were all node names found?
1358    
1359        return () if @paths != @names;
1360    
1361        my @path12 = &common_prefix( @paths[0,1] );
1362        return () if ! @path12;
1363        return @path12 if @paths == 2;
1364    
1365        my @path13 = &common_prefix( @paths[0,2] );
1366        my @path23 = &common_prefix( @paths[1,2] );
1367    
1368        # Return the longest common prefix of any two paths
1369    
1370        ( @path12 >= @path13 && @path12 >= @path23 ) ? @path12 :
1371        ( @path13 >= @path23 )                       ? @path13 :
1372                                                       @path23 ;
1373    }
1374    
1375    
1376    #-------------------------------------------------------------------------------
1377    #  Distance along path.
1378    #
1379    #  $distance = newick_path_length( @path )
1380    #
1381    #-------------------------------------------------------------------------------
1382    sub newick_path_length
1383    {
1384        my $node = shift;      #  Discard the first node
1385        array_ref( $node ) || return undef;
1386        @_ ? distance_along_path_2( @_ ) : 0;
1387    }
1388    
1389    
1390    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1391    #  This expects to get path minus root node:
1392  #  #
1393  #  $distance = distance_along_path_2( @path )  #  $distance = distance_along_path_2( @path )
1394    #
1395  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1396  sub distance_along_path_2 {  sub distance_along_path_2
1397    {
1398      shift;                 #  Discard descendant number      shift;                 #  Discard descendant number
1399      my $node = shift;      my $node = shift;
1400      array_ref( $node ) || return undef;      array_ref( $node ) || return undef;
# Line 898  Line 1408 
1408  #  Tip-to-tip distance.  #  Tip-to-tip distance.
1409  #  #
1410  #  $distance = tip_to_tip_distance( $tree, $tip1, $tip2 )  #  $distance = tip_to_tip_distance( $tree, $tip1, $tip2 )
1411    #
1412  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1413  sub tip_to_tip_distance {  sub tip_to_tip_distance
1414    {
1415      my ( $node, $tip1, $tip2 ) = @_;      my ( $node, $tip1, $tip2 ) = @_;
1416    
1417      array_ref( $node ) && defined( $tip1 )      array_ref( $node ) && defined( $tip1 )
# Line 909  Line 1421 
1421      @p1 && @p2 || return undef;                          # Were they found?      @p1 && @p2 || return undef;                          # Were they found?
1422    
1423      # Find the unique suffixes of the two paths      # Find the unique suffixes of the two paths
1424      my ( $suf1, $suf2 ) = unique_suffixes( \@p1, \@p2 ); # Common node is lost      my ( $suf1, $suf2 ) = &unique_suffixes( \@p1, \@p2 ); # Common node is lost
1425      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;
1426      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;
1427    
# Line 924  Line 1436 
1436  #                [ $tipname1, $tipname2, $tipname3 ]  #                [ $tipname1, $tipname2, $tipname3 ]
1437  #  #
1438  #  $distance = node_to_node_distance( $tree, $node1, $node2 )  #  $distance = node_to_node_distance( $tree, $node1, $node2 )
1439    #
1440  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1441  sub node_to_node_distance {  sub node_to_node_distance
1442    {
1443      my ( $node, $node1, $node2 ) = @_;      my ( $node, $node1, $node2 ) = @_;
1444    
1445      array_ref( $node ) && defined( $node1 )      array_ref( $node ) && defined( $node1 )
1446                         && defined( $node2 ) || return undef;                         && defined( $node2 ) || return undef;
1447      my @p1 = path_to_node( $node, $node1 );      my @p1 = path_to_node( $node, $node1 ) or return undef;
1448      my @p2 = path_to_node( $node, $node2 );      my @p2 = path_to_node( $node, $node2 ) or return undef;
     @p1 && @p2 || return undef;                          # Were they found?  
1449    
1450      # Find the unique suffixes of the two paths      # Find the unique suffixes of the two paths
1451      my ( $suf1, $suf2 ) = unique_suffixes( \@p1, \@p2 ); # Common node is lost      my ( $suf1, $suf2 ) = &unique_suffixes( \@p1, \@p2 ); # Common node is lost
1452      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;
1453      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;
1454    
# Line 951  Line 1464 
1464  #  Only defined fields are added, so tree list may be shorter than 8 fields.  #  Only defined fields are added, so tree list may be shorter than 8 fields.
1465  #  #
1466  #  $treecopy = copy_newick_tree( $tree )  #  $treecopy = copy_newick_tree( $tree )
1467    #
1468  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1469  sub copy_newick_tree {  sub copy_newick_tree
1470    {
1471      my ( $node ) = @_;      my ( $node ) = @_;
1472      array_ref( $node ) || return undef;      array_ref( $node ) || return undef;
1473    
# Line 985  Line 1500 
1500  #  Use a hash to relabel the nodes in a newick tree.  #  Use a hash to relabel the nodes in a newick tree.
1501  #  #
1502  #  $newtree = newick_relabel_nodes( $node, \%new_name )  #  $newtree = newick_relabel_nodes( $node, \%new_name )
1503    #
1504  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1505  sub newick_relabel_nodes {  sub newick_relabel_nodes
1506    {
1507      my ( $node, $new_name ) = @_;      my ( $node, $new_name ) = @_;
1508    
1509      my ( $lbl, $new );      my ( $new );
1510      if ( defined( $lbl = newick_lbl( $node ) )      if ( node_has_lbl( $node ) && defined( $new = $new_name->{ newick_lbl( $node ) } ) ) {
       && ( $lbl ne "" )  
       && defined( $new = $new_name->{ $lbl } )  
        ) {  
1511          set_newick_lbl( $node, $new );          set_newick_lbl( $node, $new );
1512      }      }
1513    
# Line 1009  Line 1523 
1523  #  Use a hash to relabel the nodes in a newick tree (case insensitive).  #  Use a hash to relabel the nodes in a newick tree (case insensitive).
1524  #  #
1525  #  $newtree = newick_relabel_nodes_i( $node, \%new_name )  #  $newtree = newick_relabel_nodes_i( $node, \%new_name )
1526    #
1527  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1528  sub newick_relabel_nodes_i {  sub newick_relabel_nodes_i
1529    {
1530      my ( $node, $new_name ) = @_;      my ( $node, $new_name ) = @_;
1531    
1532      #  Add any necessary lowercase keys to the hash:      #  Add any necessary lowercase keys to the hash:
# Line 1028  Line 1544 
1544  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1545  #  Do the actual relabeling  #  Do the actual relabeling
1546  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1547  sub newick_relabel_nodes_i2 {  sub newick_relabel_nodes_i2
1548    {
1549      my ( $node, $new_name ) = @_;      my ( $node, $new_name ) = @_;
1550    
1551      my ( $lbl, $new );      my ( $new );
1552      if ( defined( $lbl = newick_lbl( $node ) )      if ( node_has_lbl( $node ) && defined( $new = $new_name->{ lc newick_lbl( $node ) } ) ) {
       && ( $lbl ne "" )  
       && defined( $new = $new_name->{ lc $lbl } )  
        ) {  
1553          set_newick_lbl( $node, $new );          set_newick_lbl( $node, $new );
1554      }      }
1555    
# Line 1051  Line 1565 
1565  #  Use a hash to relabel the tips in a newick tree.  #  Use a hash to relabel the tips in a newick tree.
1566  #  #
1567  #  $newtree = newick_relabel_tips( $node, \%new_name )  #  $newtree = newick_relabel_tips( $node, \%new_name )
1568    #
1569  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1570  sub newick_relabel_tips {  sub newick_relabel_tips
1571    {
1572      my ( $node, $new_name ) = @_;      my ( $node, $new_name ) = @_;
1573    
1574      my @desc = newick_desc_list( $node );      my @desc = newick_desc_list( $node );
# Line 1061  Line 1577 
1577          foreach ( @desc ) { newick_relabel_tips( $_, $new_name ) }          foreach ( @desc ) { newick_relabel_tips( $_, $new_name ) }
1578      }      }
1579      else {      else {
1580          my ( $lbl, $new );          my ( $new );
1581          if ( defined( $lbl = newick_lbl( $node ) )          if ( node_has_lbl( $node ) && defined( $new = $new_name->{ newick_lbl( $node ) } ) ) {
           && ( $lbl ne "" )  
           && defined( $new = $new_name->{ $lbl } )  
            ) {  
1582              set_newick_lbl( $node, $new );              set_newick_lbl( $node, $new );
1583          }          }
1584      }      }
# Line 1078  Line 1591 
1591  #  Use a hash to relabel the tips in a newick tree (case insensitive).  #  Use a hash to relabel the tips in a newick tree (case insensitive).
1592  #  #
1593  #  $newtree = newick_relabel_tips_i( $node, \%new_name )  #  $newtree = newick_relabel_tips_i( $node, \%new_name )
1594    #
1595  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1596  sub newick_relabel_tips_i {  sub newick_relabel_tips_i
1597    {
1598      my ( $node, $new_name ) = @_;      my ( $node, $new_name ) = @_;
1599    
1600      #  Add any necessary lowercase keys to the hash:      #  Add any necessary lowercase keys to the hash:
# Line 1097  Line 1612 
1612  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1613  #  Do the actual relabeling  #  Do the actual relabeling
1614  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1615  sub newick_relabel_tips_i2 {  sub newick_relabel_tips_i2
1616    {
1617      my ( $node, $new_name ) = @_;      my ( $node, $new_name ) = @_;
1618    
1619      my @desc = newick_desc_list( $node );      my @desc = newick_desc_list( $node );
# Line 1106  Line 1622 
1622          foreach ( @desc ) { newick_relabel_tips_i2( $_, $new_name ) }          foreach ( @desc ) { newick_relabel_tips_i2( $_, $new_name ) }
1623      }      }
1624      else {      else {
1625          my ( $lbl, $new );          my ( $new );
1626          if ( defined( $lbl = newick_lbl( $node ) )          if ( node_has_lbl( $node ) && defined( $new = $new_name->{ lc newick_lbl( $node ) } ) ) {
           && ( $lbl ne "" )  
           && defined( $new = $new_name->{ lc $lbl } )  
            ) {  
1627              set_newick_lbl( $node, $new );              set_newick_lbl( $node, $new );
1628          }          }
1629      }      }
# Line 1123  Line 1636 
1636  #  Set undefined branch lenghts (except root) to length x.  #  Set undefined branch lenghts (except root) to length x.
1637  #  #
1638  #  $n_changed = newick_set_undefined_branches( $node, $x )  #  $n_changed = newick_set_undefined_branches( $node, $x )
1639    #
1640  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1641  sub newick_set_undefined_branches {  sub newick_set_undefined_branches
1642    {
1643      my ( $node, $x, $not_root ) = @_;      my ( $node, $x, $not_root ) = @_;
1644    
1645      my $n = 0;      my $n = 0;
# Line 1145  Line 1660 
1660  #  Set all branch lenghts (except root) to length x.  #  Set all branch lenghts (except root) to length x.
1661  #  #
1662  #  $n_changed = newick_set_all_branches( $node, $x )  #  $n_changed = newick_set_all_branches( $node, $x )
1663    #
1664  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1665  sub newick_set_all_branches {  sub newick_set_all_branches
1666    {
1667      my ( $node, $x, $not_root ) = @_;      my ( $node, $x, $not_root ) = @_;
1668    
1669      my $n = 0;      my $n = 0;
1670      if ( $not_root ) {      if ( $not_root )
1671        {
1672          set_newick_x( $node, $x );          set_newick_x( $node, $x );
1673          $n++;          $n++;
1674      }      }
1675    
1676      foreach ( newick_desc_list( $node ) ) {      foreach ( newick_desc_list( $node ) )
1677        {
1678          $n += newick_set_all_branches( $_, $x, 1 );          $n += newick_set_all_branches( $_, $x, 1 );
1679      }      }
1680    
# Line 1164  Line 1683 
1683    
1684    
1685  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1686    #  Rescale all branch lenghts by factor.
1687    #
1688    #  $node = newick_rescale_branches( $node, $factor )
1689    #
1690    #-------------------------------------------------------------------------------
1691    sub newick_rescale_branches
1692    {
1693        my ( $node, $factor ) = @_;
1694    
1695        my $x = newick_x( $node );
1696        set_newick_x( $node, $factor * $x ) if $x;
1697    
1698        foreach ( newick_desc_list( $node ) )
1699        {
1700            newick_rescale_branches( $_, $factor );
1701        }
1702    
1703        $node;
1704    }
1705    
1706    
1707    #-------------------------------------------------------------------------------
1708    #  Set all branch lenghts (except root) to random number between x1 and x2.
1709    #
1710    #  $node = newick_random_branch_lengths( $node, $x1, $x2 )
1711    #
1712    #-------------------------------------------------------------------------------
1713    sub newick_random_branch_lengths
1714    {
1715        my ( $node, $x1, $x2 ) = @_;
1716        return undef if ! array_ref( $node );
1717        $x1 = 0        if ! defined( $x1 ) || $x1 < 0;
1718        $x2 = $x1 + 1  if ! defined( $x2 ) || $x2 < $x1;
1719        newick_random_branch_lengths_0( $node, $x1, $x2, 0 );
1720    }
1721    
1722    
1723    sub newick_random_branch_lengths_0
1724    {
1725        my ( $node, $x1, $x2, $not_root ) = @_;
1726    
1727        set_newick_x( $node, rand($x2-$x1) + $x1 ) if ( $not_root );
1728        foreach ( newick_desc_list( $node ) ) { newick_random_branch_lengths_0( $_, $x1, $x2, 1 ) }
1729    
1730        $node;
1731    }
1732    
1733    
1734    #-------------------------------------------------------------------------------
1735    #  Modify all branch lengths by a function.
1736    #
1737    #     $node = newick_modify_branches( $node, \&function )
1738    #     $node = newick_modify_branches( $node, \&function, \@func_parms )
1739    #
1740    #  Function must have form
1741    #
1742    #     $x2 = &$function( $x1 )
1743    #     $x2 = &$function( $x1, @$func_parms )
1744    #
1745    #-------------------------------------------------------------------------------
1746    sub newick_modify_branches
1747    {
1748        my ( $node, $func, $parm ) = @_;
1749    
1750        set_newick_x( $node, &$func( newick_x( $node ), ( $parm ? @$parm : () ) ) );
1751        foreach ( newick_desc_list( $node ) )
1752        {
1753            newick_modify_branches( $_, $func, $parm )
1754        }
1755    
1756        $node;
1757    }
1758    
1759    
1760    #-------------------------------------------------------------------------------
1761  #  Set negative branches to zero.  The original tree is modfied.  #  Set negative branches to zero.  The original tree is modfied.
1762  #  #
1763  #  $n_changed = newick_fix_negative_branches( $tree )  #  $n_changed = newick_fix_negative_branches( $tree )
1764    #
1765  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1766  sub newick_fix_negative_branches {  sub newick_fix_negative_branches
1767    {
1768      my ( $tree ) = @_;      my ( $tree ) = @_;
1769      array_ref( $tree ) or return undef;      array_ref( $tree ) or return undef;
1770      my $n_changed = 0;      my $n_changed = 0;
# Line 1189  Line 1785 
1785    
1786    
1787  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1788    #  Remove comments from a newick tree (e.g., before writing for phylip).
1789    #
1790    #  $node = newick_strip_comments( $node )
1791    #
1792    #-------------------------------------------------------------------------------
1793    sub newick_strip_comments
1794    {
1795        my ( $node ) = @_;
1796    
1797        @$node = @$node[ 0 .. 2 ];
1798        foreach ( newick_desc_list( $node ) ) { newick_strip_comments( $_ ) }
1799        $node;
1800    }
1801    
1802    
1803    #-------------------------------------------------------------------------------
1804  #  Normalize tree order (in place).  #  Normalize tree order (in place).
1805  #  #
1806  #  ( $tree, $label1 ) = normalize_newick_tree( $tree )  #  ( $tree, $label1 ) = normalize_newick_tree( $tree )
1807    #
1808  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1809  sub normalize_newick_tree {  sub normalize_newick_tree
1810    {
1811      my ( $node ) = @_;      my ( $node ) = @_;
1812    
1813      my @descends = newick_desc_list( $node );      my @descends = newick_desc_list( $node );
# Line 1211  Line 1825 
1825  #  Reverse tree order (in place).  #  Reverse tree order (in place).
1826  #  #
1827  #  $tree = reverse_newick_tree( $tree )  #  $tree = reverse_newick_tree( $tree )
1828    #
1829  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1830  sub reverse_newick_tree {  sub reverse_newick_tree
1831    {
1832      my ( $node ) = @_;      my ( $node ) = @_;
1833    
1834      my @descends = newick_desc_list( $node );      my @descends = newick_desc_list( $node );
# Line 1228  Line 1844 
1844  #  Standard unrooted tree (in place).  #  Standard unrooted tree (in place).
1845  #  #
1846  #  $stdtree = std_unrooted_newick( $tree )  #  $stdtree = std_unrooted_newick( $tree )
1847    #
1848  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1849  sub std_unrooted_newick {  sub std_unrooted_newick
1850    {
1851      my ( $tree ) = @_;      my ( $tree ) = @_;
1852    
1853      my ( $mintip ) = sort { lc $a cmp lc $b } newick_tip_list( $tree );      my ( $mintip ) = sort { lc $a cmp lc $b } newick_tip_list( $tree );
# Line 1238  Line 1856 
1856    
1857    
1858  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1859    #  Standard name for a Newick tree topology
1860    #
1861    #    $stdname = std_tree_name( $tree )
1862    #
1863    #-------------------------------------------------------------------------------
1864    sub std_tree_name
1865    {
1866        my ( $tree ) = @_;
1867        my ( $mintip ) = sort { lc $a cmp lc $b } newick_tip_list( $tree );
1868        ( std_tree_name_2( reroot_newick_next_to_tip( copy_newick_tree( $tree ), $mintip ) ) )[0];
1869    }
1870    
1871    
1872    #
1873    #  ( $name, $mintip ) = std_tree_name_2( $node )
1874    #
1875    sub std_tree_name_2
1876    {
1877        my ( $node ) = @_;
1878    
1879        my @descends = newick_desc_list( $node );
1880        if ( @descends == 0 )
1881        {
1882            my $lbl = newick_lbl( $node );
1883            return ( $lbl, $lbl );
1884        }
1885    
1886        my @list = sort { lc $a->[1] cmp lc $b->[1] || $a->[1] cmp $b->[1] }
1887                   map  { [ std_tree_name_2( $_ ) ] }
1888                   @descends;
1889        my $mintip = $list[0]->[1];
1890        my $name   = '(' . join( "\t", map { $_->[0] } @list ) . ')';
1891    
1892        return ( $name, $mintip );
1893    }
1894    
1895    
1896    #-------------------------------------------------------------------------------
1897  #  Move largest groups to periphery of tree (in place).  #  Move largest groups to periphery of tree (in place).
1898  #  #
1899    #  $tree = aesthetic_newick_tree( $treeref, $dir )
1900    #
1901  #      dir  <= -2 for up-sweeping tree (big groups always first),  #      dir  <= -2 for up-sweeping tree (big groups always first),
1902  #            = -1 for big group first, balanced tree,  #            = -1 for big group first, balanced tree,
1903  #            =  0 for balanced tree,  #            =  0 for balanced tree,
1904  #            =  1 for small group first, balanced tree, and  #            =  1 for small group first, balanced tree, and
1905  #           >=  2 for down-sweeping tree (small groups always top)  #           >=  2 for down-sweeping tree (small groups always top)
1906  #  #
 #  $tree = aesthetic_newick_tree( $treeref, $dir )  
1907  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1908  sub aesthetic_newick_tree {  sub aesthetic_newick_tree
1909    {
1910      my ( $tree, $dir ) = @_;      my ( $tree, $dir ) = @_;
1911      my %cnt;      my %cnt;
1912    
# Line 1267  Line 1925 
1925  #  Access count with $cntref->{$noderef}  #  Access count with $cntref->{$noderef}
1926  #  #
1927  #  $count = build_tip_count_hash( $node, $cnt_hash_ref )  #  $count = build_tip_count_hash( $node, $cnt_hash_ref )
1928    #
1929  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1930  sub build_tip_count_hash {  sub build_tip_count_hash
1931    {
1932      my ( $node, $cntref ) = @_;      my ( $node, $cntref ) = @_;
1933      my ( $i, $cnt );      my ( $i, $cnt );
1934    
# Line 1291  Line 1951 
1951  #           = 0 for no change, and  #           = 0 for no change, and
1952  #           > 0 for downward branch (small group first).  #           > 0 for downward branch (small group first).
1953  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1954  sub reorder_by_tip_count {  sub reorder_by_tip_count
1955    {
1956      my ( $node, $cntref, $dir ) = @_;      my ( $node, $cntref, $dir ) = @_;
1957    
1958      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
1959      if ( $nd <  1 ) { return $node }       #  Do nothing to a tip      if ( $nd <  1 ) { return $node }       #  Do nothing to a tip
1960    
     #  Reorder this subtree:  
   
1961      my $dl_ref = newick_desc_ref( $node );      my $dl_ref = newick_desc_ref( $node );
1962      if    ( $dir < 0 ) {                   #  Big group first  
1963          @$dl_ref = sort { $cntref->{$b} <=> $cntref->{$a} } @$dl_ref;      #  Reorder this subtree (biggest subtrees to outside)
1964    
1965        if ( $dir )
1966        {
1967            #  Big group first
1968            my @dl = sort { $cntref->{$b} <=> $cntref->{$a} } @$dl_ref;
1969    
1970            my ( @dl1, @dl2 );
1971            for ( my $i = 0; $i < $nd; $i++ ) {
1972                if ( $i & 1 ) { push @dl2, $dl[$i] } else { push @dl1, $dl[$i] }
1973      }      }
1974      elsif ( $dir > 0 ) {                   #  Small group first  
1975          @$dl_ref = sort { $cntref->{$a} <=> $cntref->{$b} } @$dl_ref;          @$dl_ref = ( $dir < 0 ) ? ( @dl1, reverse @dl2 )
1976                                    : ( @dl2, reverse @dl1 );
1977      }      }
1978    
1979      #  Reorder within descendant subtrees:      #  Reorder within descendant subtrees:
# Line 1328  Line 1997 
1997  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1998  #  Move smallest groups to periphery of tree (in place).  #  Move smallest groups to periphery of tree (in place).
1999  #  #
2000    #  $tree = unaesthetic_newick_tree( $treeref, $dir )
2001    #
2002  #      dir  <= -2 for up-sweeping tree (big groups always first),  #      dir  <= -2 for up-sweeping tree (big groups always first),
2003  #            = -1 for big group first, balanced tree,  #            = -1 for big group first, balanced tree,
2004  #            =  0 for balanced tree,  #            =  0 for balanced tree,
2005  #            =  1 for small group first, balanced tree, and  #            =  1 for small group first, balanced tree, and
2006  #           >=  2 for down-sweeping tree (small groups always top)  #           >=  2 for down-sweeping tree (small groups always top)
2007  #  #
 #  $tree = unaesthetic_newick_tree( $treeref, $dir )  
2008  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2009  sub unaesthetic_newick_tree {  sub unaesthetic_newick_tree
2010    {
2011      my ( $tree, $dir ) = @_;      my ( $tree, $dir ) = @_;
2012      my %cnt;      my %cnt;
2013    
# Line 1356  Line 2027 
2027  #           = 0 for no change, and  #           = 0 for no change, and
2028  #           > 0 for downward branch (small group first).  #           > 0 for downward branch (small group first).
2029  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2030  sub reorder_against_tip_count {  sub reorder_against_tip_count
2031    {
2032      my ( $node, $cntref, $dir ) = @_;      my ( $node, $cntref, $dir ) = @_;
2033    
2034      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
# Line 1394  Line 2066 
2066  #  Randomize descendant order at each node (in place).  #  Randomize descendant order at each node (in place).
2067  #  #
2068  #  $tree = random_order_newick_tree( $tree )  #  $tree = random_order_newick_tree( $tree )
2069    #
2070  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2071  sub random_order_newick_tree {  sub random_order_newick_tree
2072    {
2073      my ( $node ) = @_;      my ( $node ) = @_;
2074    
2075      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
# Line 1404  Line 2078 
2078      #  Reorder this subtree:      #  Reorder this subtree:
2079    
2080      my $dl_ref = newick_desc_ref( $node );      my $dl_ref = newick_desc_ref( $node );
2081      @$dl_ref = random_order( @$dl_ref );      @$dl_ref = &random_order( @$dl_ref );
2082    
2083      #  Reorder descendants:      #  Reorder descendants:
2084    
# Line 1415  Line 2089 
2089    
2090    
2091  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2092    #  Reroot a tree using method specified by options.
2093    #
2094    #     $newtree = reroot_tree( $tree, \%options )
2095    #
2096    #  Options
2097    #
2098    #     adjacent_to_tip =>  $tip         # root next to named tip (no nodes)
2099    #     adjacent_to_tip =>  $bool        # root next to tip defined by nodes
2100    #     distance        =>  $distance    # distance on path from node1 to node2
2101    #     fraction        =>  $fraction    # fraction of path from node1 to node2
2102    #     midpoint        =>  $bool        # midpoint root tree (no nodes)
2103    #     node            =>  $node_spec   # just one node spec
2104    #     nodes           => \@node_specs  # 0, 1 or 2 node specifiers
2105    #     tip             =>  $tip         # short way to get tip root
2106    #
2107    #  node_spec can be 1, 2 or 3 node labels:
2108    #
2109    #     With 1 label, it is the node with that name (tip or internal)
2110    #     With 2 labels, it is the most recent common ancestor of the 2 named nodes
2111    #     With 3 labels, it is the intersection point of the paths to the 3 nodes
2112    #
2113    #-------------------------------------------------------------------------------
2114    sub reroot_tree
2115    {
2116        my ( $tree, $opts ) = @_;
2117        return undef if ! array_ref( $tree );
2118        $opts ||= {};
2119    
2120        return reroot_newick_to_midpoint_w( $tree ) if $opts->{ midpoint };
2121    
2122        #  All other options require 1 or 2 node specifiers
2123    
2124        my @nodes = array_ref( $opts->{ nodes } ) ? @{ $opts->{ nodes } } : ();
2125        push @nodes, $opts->{ node } if array_ref( $opts->{ node } );
2126    
2127        foreach ( @nodes )
2128        {
2129            next if ( array_ref( $_ ) && ( @$_ > 0 ) && ( @$_ <= 3 ) );
2130            print STDERR "Bad node specifier passed to gjonewicklib::reroot_tree().\n";
2131            return $tree;
2132        }
2133    
2134        my $adj_to_tip = $opts->{ adjacent_to_tip };
2135        my $distance   = $opts->{ distance };
2136        my $fraction   = $opts->{ fraction };
2137        my $tip        = $opts->{ tip };
2138    
2139        if ( defined( $distance ) )
2140        {
2141            return $tree if @nodes != 2;
2142            $distance = 0 if $distance < 0;
2143            $tree = reroot_newick_at_dist_between_nodes( $tree, @nodes, $distance )
2144        }
2145        elsif ( @nodes == 2 )
2146        {
2147            $fraction = 0.5 if ! defined( $fraction );
2148            $fraction = 0   if $fraction < 0;
2149            $fraction = 1   if $fraction > 1;
2150            $tree = reroot_newick_between_nodes( $tree, @nodes, $fraction )
2151        }
2152        elsif ( $adj_to_tip )
2153        {
2154            $adj_to_tip = $nodes[0]->[0] if @nodes == 1 && @{$nodes[0]} == 1;
2155            $tree = reroot_newick_next_to_tip( $tree, $adj_to_tip );
2156        }
2157        elsif ( @nodes == 1 )
2158        {
2159            #  Root at node:
2160            $tree = reroot_newick_to_node( $tree, $nodes[0] );
2161        }
2162        elsif ( defined( $tip ) && $tip ne '' )
2163        {
2164            #  Root at tip:
2165            $tree = reroot_newick_to_tip( $tree, $tip );
2166        }
2167    
2168        return $tree;
2169    }
2170    
2171    
2172    #-------------------------------------------------------------------------------
2173  #  Reroot a tree to the node that lies at the end of a path.  #  Reroot a tree to the node that lies at the end of a path.
2174  #  #
2175  #  $newtree = reroot_newick_by_path( @path )  #  $newtree = reroot_newick_by_path( @path )
2176    #
2177  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2178  sub reroot_newick_by_path {  sub reroot_newick_by_path
2179    {
2180      my ( $node1, $path1, @rest ) = @_;      my ( $node1, $path1, @rest ) = @_;
2181      array_ref( $node1 ) || return undef;      #  Always expect a node      array_ref( $node1 ) || return undef;      #  Always expect a node
2182    
# Line 1432  Line 2189 
2189      #      #
2190      #      splice( @$dl1, $path1-1, 1 );      #      splice( @$dl1, $path1-1, 1 );
2191      #      #
2192      #  But this maintains the cyclic order of the nodes:      #  But the following maintains the cyclic order of the nodes:
2193    
2194      my $dl1 = newick_desc_ref( $node1 );      my $dl1 = newick_desc_ref( $node1 );
2195      my $nd1 = @$dl1;      my $nd1 = @$dl1;
# Line 1447  Line 2204 
2204    
2205      my $dl2 = newick_desc_ref( $node2 );      my $dl2 = newick_desc_ref( $node2 );
2206      if ( array_ref( $dl2 ) ) { push @$dl2, $node1 }      if ( array_ref( $dl2 ) ) { push @$dl2, $node1 }
2207      else                     { set_newick_desc_list( $node2, [ $node1 ] ) }      else                     { set_newick_desc_list( $node2, $node1 ) }
2208    
2209      #  Move c1 comments from node 1 to node 2:      #  Move c1 comments from node 1 to node 2:
2210    
# Line 1484  Line 2241 
2241  #  Move root of tree to named tip.  #  Move root of tree to named tip.
2242  #  #
2243  #  $newtree = reroot_newick_to_tip( $tree, $tip )  #  $newtree = reroot_newick_to_tip( $tree, $tip )
2244    #
2245  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2246  sub reroot_newick_to_tip {  sub reroot_newick_to_tip
2247    {
2248      my ( $tree, $tipname ) = @_;      my ( $tree, $tipname ) = @_;
2249      reroot_newick_by_path( path_to_tip( $tree, $tipname ) );      reroot_newick_by_path( path_to_tip( $tree, $tipname ) );
2250  }  }
# Line 1495  Line 2254 
2254  #  Move root of tree to be node adjacent to a named tip.  #  Move root of tree to be node adjacent to a named tip.
2255  #  #
2256  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )
2257    #
2258  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2259  sub reroot_newick_next_to_tip {  sub reroot_newick_next_to_tip
2260    {
2261      my ( $tree, $tipname ) = @_;      my ( $tree, $tipname ) = @_;
2262      my @path = path_to_tip( $tree, $tipname );      my @path = path_to_tip( $tree, $tipname );
2263      @path || return undef;      @path || return undef;
# Line 1509  Line 2270 
2270  #  Move root of tree to a node, defined by 1 or 3 tip names.  #  Move root of tree to a node, defined by 1 or 3 tip names.
2271  #  #
2272  #  $newtree = reroot_newick_to_node( $tree, @node )  #  $newtree = reroot_newick_to_node( $tree, @node )
2273    #
2274  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2275  sub reroot_newick_to_node {  sub reroot_newick_to_node
2276    {
2277      reroot_newick_by_path( path_to_node( @_ ) );      reroot_newick_by_path( path_to_node( @_ ) );
2278  }  }
2279    
# Line 1519  Line 2282 
2282  #  Move root of tree to a node, defined by reference.  #  Move root of tree to a node, defined by reference.
2283  #  #
2284  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )
2285    #
2286  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2287  sub reroot_newick_to_node_ref {  sub reroot_newick_to_node_ref
2288    {
2289      my ( $tree, $node ) = @_;      my ( $tree, $node ) = @_;
2290      reroot_newick_by_path( path_to_node_ref( $tree, $node ) );      reroot_newick_by_path( path_to_node_ref( $tree, $node ) );
2291  }  }
2292    
2293    
2294  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2295  #  Move root of tree to an approximate midpoint.  #  Reroot a newick tree along the path between 2 nodes:
2296    #
2297    #  $tree = reroot_newick_between_nodes( $tree, $node1, $node2, $fraction )
2298  #  #
 #  $newtree = reroot_newick_to_approx_midpoint( $tree )  
2299  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2300  sub reroot_newick_to_approx_midpoint {  sub reroot_newick_between_nodes
2301      my ( $tree ) = @_;  {
2302        my ( $tree, $node1, $node2, $fraction ) = @_;
2303        array_ref( $tree ) or return undef;
2304    
2305      #  Compile average tip to node distances assending      #  Find the paths to the nodes:
2306    
2307      my $dists1 = average_to_tips_1( $tree );      my @path1 = path_to_node( $tree, $node1 ) or return $tree;
2308        my @path2 = path_to_node( $tree, $node2 ) or return $tree;
2309    
2310      #  Compile average tip to node distances descending, returning midpoint node      reroot_newick_between_nodes_by_path( \@path1, \@path2, $fraction )
2311    }
2312    
     my $node = average_to_tips_2( $dists1, undef, undef );  
2313    
2314      #  Reroot  #-------------------------------------------------------------------------------
2315    #  Reroot a newick tree along the path between 2 nodes:
2316    #
2317    #  $tree = reroot_newick_between_node_refs( $tree, $node1, $node2, $fraction )
2318    #
2319    #-------------------------------------------------------------------------------
2320    sub reroot_newick_between_node_refs
2321    {
2322        my ( $tree, $node1, $node2, $fraction ) = @_;
2323        array_ref( $tree ) or return undef;
2324    
2325      $node ? reroot_newick_to_node_ref( $tree, $node ) : $tree      #  Find the paths to the nodes:
 }  
2326    
2327        my @path1 = path_to_node_ref( $tree, $node1 ) or return $tree;
2328        my @path2 = path_to_node_ref( $tree, $node2 ) or return $tree;
2329    
2330  sub average_to_tips_1 {      reroot_newick_between_nodes_by_path( \@path1, \@path2, $fraction )
2331      my ( $node ) = @_;  }
2332    
2333      my @desc_dists = map { average_to_tips_1( $_ ) } newick_desc_list( $node );  
2334      my $x_below = 0;  #-------------------------------------------------------------------------------
2335      if ( @desc_dists )  #  Reroot a newick tree along the path between 2 nodes defined by paths:
2336    #
2337    #  $tree = reroot_newick_between_nodes_by_path( $path1, $path2, $fraction )
2338    #
2339    #-------------------------------------------------------------------------------
2340    sub reroot_newick_between_nodes_by_path
2341      {      {
2342          foreach ( @desc_dists ) { $x_below += $_->[0] }      my ( $path1, $path2, $fraction ) = @_;
2343          $x_below /= @desc_dists;      array_ref( $path1 ) && array_ref( $path2 ) or return undef;
     }  
     my $x = newick_x( $node ) || 0;  
     my $x_net = $x_below + $x;  
2344    
2345      [ $x_net, $x, $x_below, [ @desc_dists ], $node ]      $fraction = 0 if ( ! defined( $fraction ) ) || ( $fraction < 0 );
2346  }      $fraction = 1 if ( $fraction > 1 );
2347    
2348        my $prefix;
2349        ( $prefix, $path1, $path2 ) = common_and_unique_paths( $path1, $path2 );
2350    
2351  sub average_to_tips_2 {      my $dist1 = ( @$path1 >= 3 ) ? newick_path_length( @$path1 ) : 0;
2352      my ( $dists1, $x_above, $anc_node ) = @_;      my $dist2 = ( @$path2 >= 3 ) ? newick_path_length( @$path2 ) : 0;
     my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;  
2353    
2354      #  Are we done?  Root is in this node's branch, or "above"?      #  Case where there is no length (possibly same node):
2355    
2356      # defined( $x_above ) and print STDERR "x_above = $x_above\n";      return reroot_newick_by_path( @$prefix, $path1->[0] ) if $dist1 + $dist2 <= 0;
     # print STDERR "x       = $x\n";  
     # print STDERR "x_below = $x_below\n";  
     # print STDERR "n_desc  = ", scalar @$desc_list, "\n\n";  
2357    
2358      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )      my $dist = $fraction * ( $dist1 + $dist2 ) - $dist1;
2359      {      my $path = ( $dist <= 0 ) ? $path1 : $path2;
2360          #  At this point the root can only be in this node's branch,      $dist = abs( $dist );
2361          #  or "above" it in the current rooting of the tree (which  
2362        #  Descend tree until we reach the insertion branch:
2363    
2364        reroot_newick_at_dist_along_path( $prefix, $path, $dist );
2365    }
2366    
2367    
2368    #-------------------------------------------------------------------------------
2369    #  Reroot a newick tree along the path between 2 nodes:
2370    #
2371    #  $tree = reroot_newick_at_dist_between_nodes( $tree, $node1, $node2, $distance )
2372    #
2373    #-------------------------------------------------------------------------------
2374    sub reroot_newick_at_dist_between_nodes
2375    {
2376        my ( $tree, $node1, $node2, $distance ) = @_;
2377        array_ref( $tree ) or return undef;
2378    
2379        #  Find the paths to the nodes:
2380    
2381        my @path1 = path_to_node( $tree, $node1 ) or return $tree;
2382        my @path2 = path_to_node( $tree, $node2 ) or return $tree;
2383    
2384        reroot_newick_at_dist_between_nodes_by_path( \@path1, \@path2, $distance );
2385    }
2386    
2387    
2388    #-------------------------------------------------------------------------------
2389    #  Reroot a newick tree along the path between 2 nodes identified by ref:
2390    #
2391    #  $tree = reroot_newick_at_dist_between_node_refs( $tree, $node1, $node2, $distance )
2392    #
2393    #-------------------------------------------------------------------------------
2394    sub reroot_newick_at_dist_between_node_refs
2395    {
2396        my ( $tree, $node1, $node2, $distance ) = @_;
2397        array_ref( $tree ) or return undef;
2398    
2399        #  Find the paths to the nodes:
2400    
2401        my @path1 = path_to_node_ref( $tree, $node1 ) or return $tree;
2402        my @path2 = path_to_node_ref( $tree, $node2 ) or return $tree;
2403    
2404        reroot_newick_at_dist_between_nodes_by_path( \@path1, \@path2, $distance );
2405    }
2406    
2407    
2408    #-------------------------------------------------------------------------------
2409    #  Reroot a newick tree along the path between 2 nodes defined by paths:
2410    #
2411    #  $tree = reroot_newick_at_dist_between_nodes_by_path( $path1, $path2, $distance )
2412    #
2413    #-------------------------------------------------------------------------------
2414    sub reroot_newick_at_dist_between_nodes_by_path
2415    {
2416        my ( $path1, $path2, $distance ) = @_;
2417        array_ref( $path1 ) && array_ref( $path2 ) or return undef;
2418        $distance = 0 if ( ! defined( $distance ) ) || ( $distance < 0 );
2419    
2420        my $prefix;
2421        ( $prefix, $path1, $path2 ) = common_and_unique_paths( $path1, $path2 );
2422    
2423        my $dist1 = ( @$path1 >= 3 ) ? newick_path_length( @$path1 ) : 0;
2424        my $dist2 = ( @$path2 >= 3 ) ? newick_path_length( @$path2 ) : 0;
2425    
2426        #  Case where there is no length (possibly same node):
2427    
2428        return reroot_newick_by_path( @$prefix, $path1->[0] ) if $dist1 + $dist2 <= 0;
2429    
2430        my ( $path, $dist );
2431        if ( $distance < $dist1 )
2432        {
2433            $path = $path1;
2434            $dist = $dist1 - $distance;
2435        }
2436        else
2437        {
2438            $path = $path2;
2439            $dist = $distance - $dist1;
2440        }
2441    
2442        #  Descend tree until we reach the insertion branch:
2443    
2444        reroot_newick_at_dist_along_path( $prefix, $path, $dist );
2445    }
2446    
2447    
2448    #-------------------------------------------------------------------------------
2449    #  Reroot a newick tree along the path between 2 nodes defined by paths:
2450    #
2451    #  ( \@common, \@unique1, \@unique2 ) = common_and_unique_paths( \@path1, \@path2 )
2452    #
2453    #-------------------------------------------------------------------------------
2454    sub common_and_unique_paths
2455    {
2456        my ( $path1, $path2 ) = @_;
2457    
2458        my @path1 = @$path1;
2459        my @path2 = @$path2;
2460    
2461        #  Trim the common prefix, saving it:
2462    
2463        my $i = 1;
2464        my $imax = min( scalar @path1, scalar @path2 );
2465        while ( ( $i < $imax ) && ( $path1[$i] == $path2[$i] ) ) { $i += 2 }
2466    
2467        my @prefix = ();
2468        if ( $i > 1 ) { @prefix = splice( @path1, 0, $i-1 ); splice( @path2, 0, $i-1 ) }
2469    
2470        ( \@prefix, \@path1, \@path2 );
2471    }
2472    
2473    
2474    #-------------------------------------------------------------------------------
2475    #  Reroot a newick tree at a distance from the most ancestral node along a path:
2476    #
2477    #  $tree = reroot_newick_at_dist_along_path( \@prefix, \@path, $distance )
2478    #
2479    #     -   n1              n1
2480    #     |  /  \            /  \
2481    #     |      \ x2            \ x2
2482    #     |       \               \
2483    #     | dist   n2              n2
2484    #     |       /  \            /  \ x23 = dist - x2
2485    #     |           \               \
2486    #     -----------  \ x3  --------  n23
2487    #                   \             /  \ x3' = x3 - x23
2488    #                    n3               n3
2489    #                   /  \             /  \
2490    #
2491    #-------------------------------------------------------------------------------
2492    sub reroot_newick_at_dist_along_path
2493    {
2494        my ( $prefix, $path, $dist ) = @_;
2495        array_ref( $prefix ) or return undef;
2496        array_ref( $path )   or return $prefix->[0];
2497        defined( $dist )     or $dist = 0;
2498    
2499        my @prefix = @$prefix;
2500        my @path   = @$path;
2501    
2502        #  Descend tree until we reach the insertion branch:
2503    
2504        my $x = ( @path > 2 ) ? newick_x( $path[2] ) : 0;
2505        while ( ( @path > 4 ) && ( $dist > $x ) )
2506        {
2507            $dist -= $x;
2508            push @prefix, splice( @path, 0, 2 );
2509            $x = newick_x( $path[2] );
2510        }
2511        $dist = $x if ( $dist > $x );
2512    
2513        #  Insert the new node:
2514    
2515        my $newnode = [ [ $path[2] ], undef, $dist ];
2516        set_newick_desc_i( $path[0], $path[1], $newnode );
2517        set_newick_x( $path[2], $x - $dist );
2518    
2519        #  We can now build the path from root to the new node
2520    
2521        reroot_newick_by_path( @prefix, @path[0,1], $newnode );
2522    }
2523    
2524    
2525    #-------------------------------------------------------------------------------
2526    #  Move root of tree to an approximate midpoint.
2527    #
2528    #  $newtree = reroot_newick_to_approx_midpoint( $tree )
2529    #
2530    #-------------------------------------------------------------------------------
2531    sub reroot_newick_to_approx_midpoint
2532    {
2533        my ( $tree ) = @_;
2534    
2535        #  Compile average tip to node distances assending
2536    
2537        my $dists1 = average_to_tips_1( $tree );
2538    
2539        #  Compile average tip to node distances descending, returning midpoint
2540        #  cadidates as a list of [ $node1, $node2, $fraction ]
2541    
2542        my @mids = average_to_tips_2( $dists1, undef, undef );
2543    
2544        #  Reroot to first midpoint candidate
2545    
2546        return $tree if ! @mids;
2547        my ( $node1, $node2, $fraction ) = @{ $mids[0] };
2548        reroot_newick_to_node_ref( $tree, $fraction >= 0.5 ? $node2 : $node1 );
2549    }
2550    
2551    
2552    #-------------------------------------------------------------------------------
2553    #  Move root of tree to a midpoint.
2554    #
2555    #  $newtree = reroot_newick_to_midpoint( $tree )
2556    #
2557    #-------------------------------------------------------------------------------
2558    sub reroot_newick_to_midpoint
2559    {
2560        my ( $tree ) = @_;
2561    
2562        #  Compile average tip to node distances assending
2563    
2564        my $dists1 = average_to_tips_1( $tree );
2565    
2566        #  Compile average tip to node distances descending, returning midpoint
2567        #  [ $node1, $node2, $fraction ]
2568    
2569        my @mids = average_to_tips_2( $dists1, undef, undef );
2570    
2571        @mids ? reroot_newick_between_node_refs( $tree, @{ $mids[0] } ) : $tree;
2572    }
2573    
2574    
2575    #-------------------------------------------------------------------------------
2576    #  Compile average tip to node distances assending
2577    #-------------------------------------------------------------------------------
2578    sub average_to_tips_1
2579    {
2580        my ( $node ) = @_;
2581    
2582        my @desc_dists = map { average_to_tips_1( $_ ) } newick_desc_list( $node );
2583        my $x_below = 0;
2584        if ( @desc_dists )
2585        {
2586            foreach ( @desc_dists ) { $x_below += $_->[0] }
2587            $x_below /= @desc_dists;
2588        }
2589    
2590        my $x = newick_x( $node ) || 0;
2591        my $x_net = $x_below + $x;
2592    
2593        [ $x_net, $x, $x_below, [ @desc_dists ], $node ]
2594    }
2595    
2596    
2597    #-------------------------------------------------------------------------------
2598    #  Compile average tip to node distances descending, returning midpoint as
2599    #  [ $node1, $node2, $fraction_of_dist_between ]
2600    #-------------------------------------------------------------------------------
2601    sub average_to_tips_2
2602    {
2603        my ( $dists1, $x_above, $anc_node ) = @_;
2604        my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;
2605    
2606        #  Are we done?  Root is in this node's branch, or "above"?
2607    
2608        my @mids = ();
2609        if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )
2610        {
2611            #  At this point the root can only be in this node's branch,
2612            #  or "above" it in the current rooting of the tree (which
2613          #  would mean that the midpoint is actually down a different          #  would mean that the midpoint is actually down a different
2614          #  path from the root of the current tree).          #  path from the root of the current tree).
2615          #          #
# Line 1587  Line 2617 
2617    
2618          if ( ( $x_below + $x ) >= $x_above )          if ( ( $x_below + $x ) >= $x_above )
2619          {          {
2620              return ( $x_above >= $x_below ) ? $anc_node : $node;              #  We will need to make a new node for the root, $fract of
2621          }              #  the way from $node to $anc_node:
2622          else              my $fract = ( $x > 0 ) ? 0.5 * ( ( $x_above - $x_below ) / $x + 1 )
2623          {                                     : 0.5;
2624              return undef;              push @mids, [ $node, $anc_node, $fract ];
2625          }          }
2626      }      }
2627    
2628      #  The root must be somewhere below this node:      #  The root might be somewhere below this node:
2629    
2630      my $n_1      =   @$desc_list - ( $anc_node ? 0 : 1 );      my $n_1      =   @$desc_list - ( $anc_node ? 0 : 1 );
2631      my $ttl_dist = ( @$desc_list * $x_below ) + ( defined( $x_above ) ? ( $x_above + $x ) : 0 );      my $ttl_dist = ( @$desc_list * $x_below ) + ( defined( $x_above ) ? ( $x_above + $x ) : 0 );
# Line 1605  Line 2635 
2635          #  If input tree is tip_rooted, $n-1 can be 0, so:          #  If input tree is tip_rooted, $n-1 can be 0, so:
2636    
2637          my $above2 = $n_1 ? ( ( $ttl_dist - $_->[0] ) / $n_1 ) : 0;          my $above2 = $n_1 ? ( ( $ttl_dist - $_->[0] ) / $n_1 ) : 0;
2638          my $root = average_to_tips_2( $_, $above2, $node );          push @mids, average_to_tips_2( $_, $above2, $node );
         if ( $root ) { return $root }  
2639      }      }
2640    
2641      #  Was not anywhere below this node (oh-oh):      return @mids;
   
     return undef;  
2642  }  }
2643    
2644    
# Line 1619  Line 2646 
2646  #  Move root of tree to an approximate midpoint.  Weight by tips.  #  Move root of tree to an approximate midpoint.  Weight by tips.
2647  #  #
2648  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )
2649    #
2650    #-------------------------------------------------------------------------------
2651    sub reroot_newick_to_approx_midpoint_w
2652    {
2653        my ( $tree ) = @_;
2654        array_ref( $tree ) or return undef;
2655    
2656        #  Compile average tip to node distances assending from tips
2657    
2658        my $dists1 = average_to_tips_1_w( $tree );
2659    
2660        #  Compile average tip to node distances descending, returning midpoints
2661    
2662        my @mids = average_to_tips_2_w( $dists1, undef, undef, undef );
2663    
2664        #  Reroot to first midpoint candidate
2665    
2666        return $tree if ! @mids;
2667        my ( $node1, $node2, $fraction ) = @{ $mids[0] };
2668        reroot_newick_to_node_ref( $tree, $fraction >= 0.5 ? $node2 : $node1 );
2669    }
2670    
2671    
2672    #-------------------------------------------------------------------------------
2673    #  Move root of tree to an approximate midpoint.  Weight by tips.
2674    #
2675    #  $newtree = reroot_newick_to_midpoint_w( $tree )
2676    #
2677  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2678  sub reroot_newick_to_approx_midpoint_w {  sub reroot_newick_to_midpoint_w
2679    {
2680      my ( $tree ) = @_;      my ( $tree ) = @_;
2681        array_ref( $tree ) or return ();
2682    
2683      #  Compile average tip to node distances assending      #  Compile average tip to node distances assending
2684    
# Line 1629  Line 2686 
2686    
2687      #  Compile average tip to node distances descending, returning midpoint node      #  Compile average tip to node distances descending, returning midpoint node
2688    
2689      my $node = average_to_tips_2_w( $dists1, undef, undef, undef );      my @mids = average_to_tips_2_w( $dists1, undef, undef, undef );
2690    
2691      #  Reroot      #  Reroot at first candidate midpoint
2692    
2693      $node ? reroot_newick_to_node_ref( $tree, $node ) : $tree      @mids ? reroot_newick_between_node_refs( $tree, @{ $mids[0] } ) : $tree;
2694  }  }
2695    
2696    
2697  sub average_to_tips_1_w {  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2698    sub average_to_tips_1_w
2699    {
2700      my ( $node ) = @_;      my ( $node ) = @_;
2701    
2702      my @desc_dists = map { average_to_tips_1_w( $_ ) } newick_desc_list( $node );      my @desc_dists = map { average_to_tips_1_w( $_ ) } newick_desc_list( $node );
# Line 1654  Line 2713 
2713          }          }
2714          $x_below /= $n_below;          $x_below /= $n_below;
2715      }      }
2716    
2717      my $x = newick_x( $node ) || 0;      my $x = newick_x( $node ) || 0;
2718      my $x_net = $x_below + $x;      my $x_net = $x_below + $x;
2719    
# Line 1661  Line 2721 
2721  }  }
2722    
2723    
2724  sub average_to_tips_2_w {  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2725    sub average_to_tips_2_w
2726    {
2727      my ( $dists1, $x_above, $n_above, $anc_node ) = @_;      my ( $dists1, $x_above, $n_above, $anc_node ) = @_;
2728      my ( undef, $n_below, $x, $x_below, $desc_list, $node ) = @$dists1;      my ( undef, $n_below, $x, $x_below, $desc_list, $node ) = @$dists1;
2729    
2730      #  Are we done?  Root is in this node's branch, or "above"?      #  Are we done?  Root is in this node's branch, or "above"?
2731    
2732      # defined( $x_above ) and print STDERR "x_above = $x_above\n";      my @mids = ();
     # print STDERR "x       = $x\n";  
     # print STDERR "x_below = $x_below\n";  
     # print STDERR "n_desc  = ", scalar @$desc_list, "\n\n";  
   
2733      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )
2734      {      {
2735          #  At this point the root can only be in this node's branch,          #  At this point the root can only be in this node's branch,
# Line 1679  Line 2737 
2737          #  would mean that the midpoint is actually down a different          #  would mean that the midpoint is actually down a different
2738          #  path from the root of the current tree).          #  path from the root of the current tree).
2739          #          #
2740          #  Is the root in the current branch?          #  Is their a root in the current branch?
2741    
2742          if ( ( $x_below + $x ) >= $x_above )          if ( ( $x_below + $x ) >= $x_above )
2743          {          {
2744              return ( $x_above >= $x_below ) ? $anc_node : $node;              #  We will need to make a new node for the root, $fract of
2745          }              #  the way from $node to $anc_node:
2746          else              my $fract = ( $x > 0 ) ? 0.5 * ( ( $x_above - $x_below ) / $x + 1 )
2747          {                                     : 0.5;
2748              return undef;              push @mids, [ $node, $anc_node, $fract ];
2749          }          }
2750      }      }
2751    
# Line 1707  Line 2765 
2765    
2766          my $x_above2 = $n_above2 ? ( ( $ttl_w_dist - $n_2 * $_->[0] ) / $n_above2 )          my $x_above2 = $n_above2 ? ( ( $ttl_w_dist - $n_2 * $_->[0] ) / $n_above2 )
2767                                   : 0;                                   : 0;
2768          my $root = average_to_tips_2_w( $_, $x_above2, $n_above2 || 1, $node );          push @mids, average_to_tips_2_w( $_, $x_above2, $n_above2 || 1, $node );
         if ( $root ) { return $root }  
2769      }      }
2770    
2771      #  Was not anywhere below this node (oh-oh):      return @mids;
   
     return undef;  
2772  }  }
2773    
2774    
# Line 1721  Line 2776 
2776  #  Move root of tree from tip to adjacent node.  #  Move root of tree from tip to adjacent node.
2777  #  #
2778  #  $newtree = uproot_tip_rooted_newick( $tree )  #  $newtree = uproot_tip_rooted_newick( $tree )
2779    #
2780  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2781  sub uproot_tip_rooted_newick {  sub uproot_tip_rooted_newick
2782    {
2783      my ( $node ) = @_;      my ( $node ) = @_;
2784      newick_is_tip_rooted( $node ) || return $node;      newick_is_tip_rooted( $node ) || return $node;
2785    
# Line 1738  Line 2795 
2795  #  Root node label, label comment and descendant list comment are discarded.  #  Root node label, label comment and descendant list comment are discarded.
2796  #  #
2797  #  $newtree = uproot_newick( $tree )  #  $newtree = uproot_newick( $tree )
2798    #
2799  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2800  sub uproot_newick {  sub uproot_newick
2801    {
2802      my ( $node0 ) = @_;      my ( $node0 ) = @_;
2803      newick_is_rooted( $node0 ) || return $node0;      newick_is_rooted( $node0 ) || return $node0;
2804    
# Line 1786  Line 2845 
2845  #  Prefix branch of node2 to that of node1:  #  Prefix branch of node2 to that of node1:
2846  #  #
2847  #  $node1 = add_to_newick_branch( $node1, $node2 )  #  $node1 = add_to_newick_branch( $node1, $node2 )
2848    #
2849  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2850  sub add_to_newick_branch {  sub add_to_newick_branch
2851    {
2852      my ( $node1, $node2 ) = @_;      my ( $node1, $node2 ) = @_;
2853      array_ref( $node1 ) || die "add_to_newick_branch: arg 1 not array ref\n";      array_ref( $node1 ) || die "add_to_newick_branch: arg 1 not array ref\n";
2854      array_ref( $node2 ) || die "add_to_newick_branch: arg 2 not array ref\n";      array_ref( $node2 ) || die "add_to_newick_branch: arg 2 not array ref\n";
# Line 1825  Line 2886 
2886  #  #
2887  #  $tree = collapse_zero_length_branches( $tree )  #  $tree = collapse_zero_length_branches( $tree )
2888  #  $tree = collapse_zero_length_branches( $tree, $not_root )  #  $tree = collapse_zero_length_branches( $tree, $not_root )
2889    #
2890  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2891  sub collapse_zero_length_branches {  sub collapse_zero_length_branches
2892    {
2893      my ( $tree, $not_root ) = @_;      my ( $tree, $not_root ) = @_;
2894      array_ref( $tree ) || return undef;      array_ref( $tree ) || return undef;
2895    
# Line 1859  Line 2922 
2922      ( $tree, ( $collapse ? @new_desc : () ) );      ( $tree, ( $collapse ? @new_desc : () ) );
2923  }  }
2924    
2925    #-------------------------------------------------------------------------------
2926    #  Add a subtree to a newick tree node:
2927    #
2928    #  $node = newick_insert_at_node( $node, $subtree )
2929    #
2930    #-------------------------------------------------------------------------------
2931    sub newick_insert_at_node
2932    {
2933        my ( $node, $subtree ) = @_;
2934        array_ref( $node ) && array_ref( $subtree ) or return undef;
2935    
2936        #  We could check validity of trees, but ....
2937    
2938        my $dl = newick_desc_ref( $node );
2939        if ( array_ref( $dl ) )
2940        {
2941            push @$dl, $subtree;
2942        }
2943        else
2944        {
2945            set_newick_desc_ref( $node, [ $subtree ] );
2946        }
2947        return $node;
2948    }
2949    
2950    
2951    #-------------------------------------------------------------------------------
2952    #  Insert a subtree into a newick tree along the path between 2 nodes:
2953    #
2954    #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )
2955    #
2956    #-------------------------------------------------------------------------------
2957    sub newick_insert_between_nodes
2958    {
2959        my ( $tree, $subtree, $node1, $node2, $fraction ) = @_;
2960        array_ref( $tree ) && array_ref( $subtree ) or return undef;
2961        $fraction >= 0 && $fraction <= 1 or return undef;
2962    
2963        #  Find the paths to the nodes:
2964    
2965        my @path1 = path_to_node( $tree, $node1 ) or return undef;
2966        my @path2 = path_to_node( $tree, $node2 ) or return undef;
2967    
2968        #  Trim the common prefix:
2969    
2970        while ( $path1[1] == $path2[1] )
2971        {
2972            splice( @path1, 0, 2 );
2973            splice( @path2, 0, 2 );
2974        }
2975    
2976        my ( @path, $dist );
2977        if    ( @path1 < 3 )
2978        {
2979            @path2 >= 3 or return undef;              # node1 = node2
2980            $dist = $fraction * newick_path_length( @path2 );
2981            @path = @path2;
2982        }
2983        elsif ( @path2 < 3 )
2984        {
2985            $dist = ( 1 - $fraction ) * newick_path_length( @path1 );
2986            @path = @path1;
2987        }
2988        else
2989        {
2990            my $dist1 = newick_path_length( @path1 );
2991            my $dist2 = newick_path_length( @path2 );
2992            $dist = $fraction * ( $dist1 + $dist2 ) - $dist1;
2993            @path = ( $dist <= 0 ) ? @path1 : @path2;
2994            $dist = abs( $dist );
2995        }
2996    
2997        #  Descend tree until we reach the insertion branch:
2998    
2999        my $x;
3000        while ( ( $dist > ( $x = newick_x( $path[2] ) ) ) && ( @path > 3 ) )
3001        {
3002            $dist -= $x;
3003            splice( @path, 0, 2 );
3004        }
3005    
3006        #  Insert the new node:
3007    
3008        set_newick_desc_i( $path[0], $path[1], [ [ $path[2], $subtree ], undef, $dist ] );
3009        set_newick_x( $path[2], ( ( $x > $dist ) ? ( $x - $dist ) : 0 ) );
3010    
3011        return $tree;
3012    }
3013    
3014    
3015  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3016  #  Prune one or more tips from a tree:  #  Prune one or more tips from a tree:
# Line 1869  Line 3021 
3021  #  $newtree = prune_from_newick( $tree,  $tip  )  #  $newtree = prune_from_newick( $tree,  $tip  )
3022  #  $newtree = prune_from_newick( $tree,  @tips )  #  $newtree = prune_from_newick( $tree,  @tips )
3023  #  $newtree = prune_from_newick( $tree, \@tips )  #  $newtree = prune_from_newick( $tree, \@tips )
3024    #
3025  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3026  sub prune_from_newick {  sub prune_from_newick
3027    {
3028      my ( $tr, @tips ) = @_;      my ( $tr, @tips ) = @_;
3029      if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }      if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }
3030    
# Line 1887  Line 3041 
3041  #  Prune a tip from a tree:  #  Prune a tip from a tree:
3042  #  #
3043  #  $newtree = prune_1_from_newick( $tree, $tip )  #  $newtree = prune_1_from_newick( $tree, $tip )
3044    #
3045  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3046  sub prune_1_from_newick {  sub prune_1_from_newick
3047    {
3048      my ( $tr, $tip ) = @_;      my ( $tr, $tip ) = @_;
3049      my @path = path_to_tip( $tr, $tip );      my @path = path_to_tip( $tr, $tip );
3050      if ( @path < 3 ) { return $tr }      if ( @path < 3 ) { return $tr }
# Line 1941  Line 3097 
3097    
3098    
3099  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3100    #  Produce a potentially rooted subtree with the desired tips:
3101    #
3102    #     Except for (some) tip nodes, the tree produced is a copy.
3103    #     There is no check that requested tips exist.
3104    #
3105    #  $newtree = rooted_newick_subtree( $tree,  @tips )
3106    #  $newtree = rooted_newick_subtree( $tree, \@tips )
3107    #
3108    #-------------------------------------------------------------------------------
3109    sub rooted_newick_subtree
3110    {
3111        my ( $tr, @tips ) = @_;
3112        if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }
3113    
3114        if ( @tips < 2 ) { return undef }
3115        my $keephash = { map { ( $_, 1 ) } @tips };
3116        my $tr2 = subtree1( $tr, $keephash );
3117        $tr2->[2] = undef if $tr2;                   # undef root branch length
3118        $tr2;
3119    }
3120    
3121    
3122    #-------------------------------------------------------------------------------
3123  #  Produce a subtree with the desired tips:  #  Produce a subtree with the desired tips:
3124  #  #
3125  #     Except for (some) tip nodes, the tree produced is a copy.  #     Except for (some) tip nodes, the tree produced is a copy.
# Line 1948  Line 3127 
3127  #  #
3128  #  $newtree = newick_subtree( $tree,  @tips )  #  $newtree = newick_subtree( $tree,  @tips )
3129  #  $newtree = newick_subtree( $tree, \@tips )  #  $newtree = newick_subtree( $tree, \@tips )
3130    #
3131  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3132  sub newick_subtree {  sub newick_subtree
3133    {
3134      my ( $tr, @tips ) = @_;      my ( $tr, @tips ) = @_;
3135      if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }      if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }
3136    
3137      if ( @tips < 2 ) { return undef }      if ( @tips < 2 ) { return undef }
3138      my $was_rooted = newick_is_rooted( $tr );      my $was_rooted = newick_is_rooted( $tr );
3139      my $keephash = { map { ( $_, 1 ) } @tips };      my $keephash = { map { ( $_, 1 ) } @tips };
3140      my $tr2 = subtree1( $tr, $keephash );      my $tr2 = subtree1( $tr, $keephash );
3141      $tr2 = uproot_newick( $tr2 ) if ! $was_rooted && newick_is_rooted( $tr2 );      $tr2 = uproot_newick( $tr2 ) if ! $was_rooted && newick_is_rooted( $tr2 );
3142      $tr2->[2] = undef if $tr2;                   # undef root branch length      $tr2->[2] = undef if $tr2;                   # undef root branch length
3143      $tr2;      $tr2;
3144  }  }
3145    
3146    
3147    sub subtree1
3148    {
3149        my ( $tr, $keep ) = @_;
3150        my @desc1 = newick_desc_list( $tr );
3151    
3152        #  Is this a tip, and is it in the keep list?
3153    
3154        if ( @desc1 < 1 ) {
3155            return ( $keep->{ newick_lbl( $tr ) } ) ? $tr : undef;
3156        }
3157    
3158        #  Internal node: analyze the descendants:
3159    
3160        my @desc2 = ();
3161        foreach ( @desc1 ) {
3162            my $desc = subtree1( $_, $keep );
3163            if ( $desc && @$desc ) { push @desc2, $desc }
3164        }
3165    
3166        if ( @desc2 == 0 ) { return undef }
3167        if ( @desc2 >  1 ) { return [ \@desc2, @$tr[ 1 .. @$tr - 1 ] ] }
3168    
3169        #  Exactly 1 descendant
3170    
3171        my $desc = $desc2[ 0 ];
3172        my @nn = ( $desc->[0],
3173                   $desc->[1] ? $desc->[1] : $tr->[1],
3174                   defined( $tr->[2] ) ? $desc->[2] + $tr->[2] : undef
3175                 );
3176    
3177        #  Merge comments (only recreating the ones that existed):
3178    
3179        if ( $tr->[3] && @{$tr->[3]} || $desc->[3] && @{$desc->[3]} ) {
3180            $nn[3] = [ $tr->[3] ? @{$tr->[3]} : (), $desc->[3] ? @{$desc->[3]} : () ];
3181        }
3182        if ( $tr->[4] && @{$tr->[4]} || $desc->[4] && @{$desc->[4]} ) {
3183            $nn[4] = [ $tr->[4] ? @{$tr->[4]} : (), $desc->[4] ? @{$desc->[4]} : () ];
3184        }
3185        if ( $tr->[5] && @{$tr->[5]} || $desc->[5] && @{$desc->[5]} ) {
3186            $nn[5] = [ $tr->[5] ? @{$tr->[5]} : (), $desc->[5] ? @{$desc->[5]} : () ];
3187        }
3188        if ( $tr->[6] && @{$tr->[6]} || $desc->[6] && @{$desc->[6]} ) {
3189            $nn[6] = [ $tr->[6] ? @{$tr->[6]} : (), $desc->[6] ? @{$desc->[6]} : () ];
3190        }
3191        if ( $tr->[7] && @{$tr->[7]} || $desc->[7] && @{$desc->[7]} ) {
3192            $nn[7] = [ $tr->[7] ? @{$tr->[7]} : (), $desc->[7] ? @{$desc->[7]} : () ];
3193        }
3194    
3195        return \@nn;
3196    }
3197    
3198    
3199    #-------------------------------------------------------------------------------
3200    #  The smallest subtree of rooted tree that includes @tips:
3201    #
3202    #    $node = newick_covering_subtree( $tree,  @tips )
3203    #    $node = newick_covering_subtree( $tree, \@tips )
3204    #
3205    #-------------------------------------------------------------------------------
3206    
3207    sub newick_covering_subtree
3208    {
3209        my $tree = shift;
3210        my %tips = map { $_ => 1 } ( ( ref( $_[0] ) eq 'ARRAY' ) ? @{ $_[0] } : @_ );
3211    
3212        #  Return smallest covering node, if any:
3213    
3214        ( newick_covering_subtree( $tree, \%tips ) )[ 0 ];
3215    }
3216    
3217    
3218    sub newick_covering_subtree_1
3219    {
3220        my ( $node, $tips ) = @_;
3221        my $n_cover = 0;
3222        my @desc = newick_desc_list( $node );
3223        if ( @desc )
3224        {
3225            foreach ( @desc )
3226            {
3227                my ( $subtree, $n ) = newick_covering_subtree_1( $_, $tips );
3228                return ( $subtree, $n ) if $subtree;
3229                $n_cover += $n;
3230            }
3231        }
3232        elsif ( $tips->{ newick_lbl( $node ) } )
3233        {
3234            $n_cover++;
3235        }
3236    
3237        #  If all tips are covered, return node
3238    
3239        ( $n_cover == keys %$tips ) ? ( $node, $n_cover ) : ( undef, $n_cover );
3240    }
3241    
3242    
3243    #===============================================================================
3244    #
3245    #  Representative subtrees
3246    #
3247    #===============================================================================
3248    #  Find subtree of size n representating vicinity of the root:
3249    #
3250    #   $subtree = root_neighborhood_representative_tree( $tree, $n, \%tip_priority )
3251    #   $subtree = root_neighborhood_representative_tree( $tree, $n )
3252    #
3253    #  Note that if $tree is rooted, then the subtree will also be.  This can have
3254    #  consequences on downstream programs.
3255    #-------------------------------------------------------------------------------
3256    sub root_neighborhood_representative_tree
3257    {
3258        my ( $tree, $n, $tip_priority ) = @_;
3259        array_ref( $tree ) && ( $n >= 2 ) or return undef;
3260        if ( newick_tip_count( $tree ) <= $n ) { return $tree }
3261    
3262        $tip_priority ||= default_tip_priority( $tree );
3263        my @tips = map { representative_tip_of_newick_node( $_, $tip_priority ) }
3264                   root_proximal_newick_subtrees( $tree, $n );
3265    
3266        newick_subtree( copy_newick_tree( $tree ), \@tips );
3267    }
3268    
3269    
3270    #-------------------------------------------------------------------------------
3271    #  Find n tips to represent tree lineages in vicinity of another tip.
3272    #  Default tip priority is short total branch length.
3273    #
3274    #  \@tips = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
3275    #   @tips = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
3276    #  \@tips = root_neighborhood_representative_tips( $tree, $n )
3277    #   @tips = root_neighborhood_representative_tips( $tree, $n )
3278    #
3279    #-------------------------------------------------------------------------------
3280    sub root_neighborhood_representative_tips
3281    {
3282        my ( $tree, $n, $tip_priority ) = @_;
3283        array_ref( $tree ) && ( $n >= 2 ) or return undef;
3284    
3285        my @tips;
3286        if ( newick_tip_count( $tree ) <= $n )
3287        {
3288            @tips = newick_tip_list( $tree );
3289        }
3290        else
3291        {
3292            $tip_priority ||= default_tip_priority( $tree );
3293            @tips = map { representative_tip_of_newick_node( $_, $tip_priority ) }
3294                    root_proximal_newick_subtrees( $tree, $n );
3295        }
3296    
3297        wantarray ? @tips : \@tips;
3298    }
3299    
3300    
3301    #-------------------------------------------------------------------------------
3302    #  Find subtree of size n representating vicinity of a tip:
3303    #
3304    #   $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n, \%tip_priority )
3305    #   $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n )
3306    #
3307    #-------------------------------------------------------------------------------
3308    sub tip_neighborhood_representative_tree
3309    {
3310        my ( $tree, $tip, $n, $tip_priority ) = @_;
3311        array_ref( $tree ) && $tip && ( $n >= 2 ) or return undef;
3312        newick_tip_in_tree( $tree, $tip ) or return undef;
3313    
3314        my $tree1 = copy_newick_tree( $tree );
3315        if ( newick_tip_count( $tree1 ) - 1 <= $n )
3316        {
3317            return prune_from_newick( $tree1, $tip )
3318        }
3319    
3320        $tree1 = reroot_newick_to_tip( $tree1, $tip );
3321        $tree1 = newick_desc_i( $tree1, 1 );        # Node immediately below tip
3322        my @tips = root_neighborhood_representative_tips( $tree1, $n, $tip_priority );
3323        newick_subtree( copy_newick_tree( $tree ), \@tips );
3324    }
3325    
3326    
3327    #-------------------------------------------------------------------------------
3328    #  Find n tips to represent tree lineages in vicinity of another tip.
3329    #  Default tip priority is short total branch length.
3330    #
3331    #  \@tips = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
3332    #   @tips = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
3333    #  \@tips = tip_neighborhood_representative_tips( $tree, $tip, $n )
3334    #   @tips = tip_neighborhood_representative_tips( $tree, $tip, $n )
3335    #
3336    #-------------------------------------------------------------------------------
3337    sub tip_neighborhood_representative_tips
3338    {
3339        my ( $tree, $tip, $n, $tip_priority ) = @_;
3340        array_ref( $tree ) && $tip && ( $n >= 2 ) or return undef;
3341        newick_tip_in_tree( $tree, $tip ) or return undef;
3342    
3343        my @tips = newick_tip_list( $tree );
3344        if ( newick_tip_count( $tree ) - 1 <= $n )
3345        {
3346            @tips = grep { $_ ne $tip } @tips;
3347        }
3348        else
3349        {
3350            my $tree1 = copy_newick_tree( $tree );
3351            $tree1 = reroot_newick_to_tip( $tree1, $tip );
3352            $tree1 = newick_desc_i( $tree1, 1 );        # Node immediately below tip
3353            @tips = root_neighborhood_representative_tips( $tree1, $n, $tip_priority );
3354        }
3355    
3356        wantarray ? @tips : \@tips;
3357    }
3358    
3359    
3360    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3361    #  Anonymous hash of the negative distance from root to each tip:
3362    #
3363    #   \%tip_priority = default_tip_priority( $tree )
3364    #
3365    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3366    sub default_tip_priority
3367    {
3368        my ( $tree ) = @_;
3369        my $tip_distances = newick_tip_distances( $tree ) || {};
3370        return { map { $_ => -$tip_distances->{$_} } keys %$tip_distances };
3371    }
3372    
3373    
3374    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3375    #  Select a tip from a subtree base on a priority value:
3376    #
3377    #    $tip = representative_tip_of_newick_node( $node, \%tip_priority )
3378    #
3379    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3380    sub representative_tip_of_newick_node
3381    {
3382        my ( $node, $tip_priority ) = @_;
3383        my ( $tip ) = sort { $b->[1] <=> $a->[1] }   # The best
3384                      map  { [ $_, $tip_priority->{ $_ } ] }
3385                      newick_tip_list( $node );
3386        $tip->[0];                                   # Label from label-priority pair
3387    }
3388    
3389    
3390    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3391    #  Find n subtrees focused around the root of a tree.  Typically each will
3392    #  then be reduced to a single tip to make a representative tree:
3393    #
3394    #   @subtrees = root_proximal_newick_subtrees( $tree, $n )
3395    #
3396    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3397    sub root_proximal_newick_subtrees
3398    {
3399        my ( $tree, $n ) = @_;
3400        my $node_start_end = newick_branch_intervals( $tree );
3401        n_representative_branches( $n, $node_start_end );
3402    }
3403    
3404    
3405    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3406    #   @node_start_end = newick_branch_intervals( $tree )
3407    #  \@node_start_end = newick_branch_intervals( $tree )
3408    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3409    sub newick_branch_intervals
3410    {
3411        my ( $node, $parent_x ) = @_;
3412        $parent_x ||= 0;
3413        my ( $desc, undef, $dx ) = @$node;
3414        my $x = $parent_x + $dx;
3415        my $interval = [ $node, $parent_x, $desc && @$desc ? $x : 1e100 ];
3416        my @intervals = ( $interval,
3417                          map { &newick_branch_intervals( $_, $x ) } @$desc
3418                        );
3419        return wantarray ? @intervals : \@intervals;
3420    }
3421    
3422    
3423    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3424    #   @ids = n_representative_branches( $n,  @id_start_end )
3425    #   @ids = n_representative_branches( $n, \@id_start_end )
3426    #  \@ids = n_representative_branches( $n,  @id_start_end )
3427    #  \@ids = n_representative_branches( $n, \@id_start_end )
3428    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3429    sub n_representative_branches
3430    {
3431        my $n = shift;
3432        #  Sort intervals by start point:
3433        my @unprocessed = sort { $a->[1] <=> $b->[1] }
3434                          ( @_ == 1 ) ? @{ $_[0] } : @_;
3435        my @active = ();
3436        my ( $interval, $current_point );
3437        foreach $interval ( @unprocessed )
3438        {
3439            $current_point = $interval->[1];
3440            #  Filter out intervals that have ended.  This is N**2 in the number
3441            #  of representatives.  Fixing this would require maintaining a sorted
3442            #  active list.
3443            @active = grep { $_->[2] > $current_point } @active;
3444            push @active, $interval;
3445            last if ( @active >= $n );
3446        }
3447    
3448        my @ids = map { $_->[0] } @active;
3449        return wantarray() ? @ids : \@ids;
3450    }
3451    
3452    
3453    #===============================================================================
3454    #  Random trees
3455    #===============================================================================
3456    #
3457    #   $tree = random_equibranch_tree(  @tips, \%options )
3458    #   $tree = random_equibranch_tree( \@tips, \%options )
3459    #   $tree = random_equibranch_tree(  @tips )
3460    #   $tree = random_equibranch_tree( \@tips )
3461    #
3462    #  Options:
3463    #
3464    #     length => $branch_length   # D = 1
3465    #
3466    #-------------------------------------------------------------------------------
3467    sub random_equibranch_tree
3468    {
3469        my $opts = $_[ 0] && ref $_[ 0] eq 'HASH' ? shift
3470                 : $_[-1] && ref $_[-1] eq 'HASH' ? pop
3471                 :                                  {};
3472        return undef if ! defined $_[0];
3473    
3474        my @tips = ref $_[0] ? @{ $_[0] } : @_;
3475        return undef if @tips < 2;
3476    
3477        my $len = $opts->{ length } ||= 1;
3478    
3479        if ( @tips == 2 )
3480        {
3481            return [ [ map { [ [], $_, $len ] } @tips ], undef, 0 ];
3482        }
3483    
3484        my $tree = [ [ ], undef, 0 ];
3485    
3486        my @links;  # \$anc_dl[i], i.e. a reference to an element in a descendent list
3487    
3488        my $anc_dl = $tree->[0];
3489        foreach my $tip ( splice( @tips, 0, 3 ) )
3490        {
3491            my $node = [ [], $tip, $len ];
3492            push @$anc_dl, $node;
3493            push @links, \$anc_dl->[-1];  #  Ref to the just added descendent list entry
3494        }
3495    
3496        foreach my $tip ( @tips )
3497        {
3498            my $link    = $links[ int( rand( scalar @links ) ) ];
3499            my $newtip  = [ [], $tip, $len ];
3500            my $new_dl  = [ $$link, $newtip ];
3501            my $newnode = [ $new_dl, undef, $len ];
3502            $$link = $newnode;
3503            push @links, \$new_dl->[0], \$new_dl->[1]
3504        }
3505    
3506        return $tree;
3507    }
3508    
3509    
3510    #-------------------------------------------------------------------------------
3511    #
3512    #   $tree = random_ultrametric_tree(  @tips, \%options )
3513    #   $tree = random_ultrametric_tree( \@tips, \%options )
3514    #   $tree = random_ultrametric_tree(  @tips )
3515    #   $tree = random_ultrametric_tree( \@tips )
3516    #
3517    #  Options:
3518    #
3519    #     depth => $root_to_tip_dist   # D = 1
3520    #
3521    #-------------------------------------------------------------------------------
3522    sub random_ultrametric_tree
3523    {
3524        my $opts = $_[ 0] && ref $_[ 0] eq 'HASH' ? shift
3525                 : $_[-1] && ref $_[-1] eq 'HASH' ? pop
3526                 :                                  {};
3527        return undef if ! defined $_[0];
3528    
3529        my @tips = ref $_[0] ? @{ $_[0] } : @_;
3530        return undef if @tips < 2;
3531    
3532        my $d2tip = $opts->{ depth } ||= 1;
3533    
3534        #  Random tip addition order (for rooted tree it matters):
3535    
3536        @tips = sort { rand() <=> 0.5 } @tips;
3537        my $tree = [ [ ], undef, 0 ];
3538    
3539  sub subtree1 {      my $subtree_size = { $tree => 0 };  # total branch length of each subtree
     my ( $tr, $keep ) = @_;  
     my @desc1 = newick_desc_list( $tr );  
3540    
3541      #  Is this a tip, and is it in the keep list?      #  We start with root bifurcation:
3542    
3543      if ( @desc1 < 1 ) {      foreach my $tip ( splice( @tips, 0, 2 ) )
3544          return ( $keep->{ newick_lbl( $tr ) } ) ? $tr : undef;      {
3545            my $node = [ [], $tip, $d2tip ];
3546            push @{ $tree->[0] }, $node;
3547            $subtree_size->{ $node }  = $d2tip;
3548            $subtree_size->{ $tree } += $d2tip;
3549      }      }
3550    
3551      #  Internal node: analyze the descendants:      #  Add each remaining tip at $pos, measured along the contour length
3552        #  of the tree (with no retracing along branches).
3553    
3554      my @desc2 = ();      foreach my $tip ( @tips )
3555      foreach ( @desc1 ) {      {
3556          my $desc = subtree1( $_, $keep );          my $pos = rand( $subtree_size->{ $tree } );
3557          if ( $desc && @$desc ) { push @desc2, $desc }          random_add_to_ultrametric_tree( $tree, $tip, $subtree_size, $pos, $d2tip );
3558      }      }
3559    
3560      if ( @desc2 == 0 ) { return undef }      return $tree;
3561      if ( @desc2 >  1 ) { return [ \@desc2, @$tr[ 1 .. @$tr - 1 ] ] }  }
3562    
     #  Exactly 1 descendant  
3563    
3564      my $desc = $desc2[ 0 ];  sub random_add_to_ultrametric_tree
3565      my @nn = ( $desc->[0],  {
3566                 $desc->[1] ? $desc->[1] : $tr->[1],      my ( $node, $tip, $subtree_size, $pos, $d2tip ) = @_;
3567                 defined( $tr->[2] ) ? $desc->[2] + $tr->[2] : undef      $node && $node->[0] && ref $node->[0] eq 'ARRAY' or die "Bad tree node passed to random_add_to_ultrametric_tree().\n";
              );  
3568    
3569      #  Merge comments (only recreating the ones that existed):      # Find the descendent line that it goes in:
3570    
3571      if ( $tr->[3] && @{$tr->[3]} || $desc->[3] && @{$desc->[3]} ) {      my $i;
3572          $nn[3] = [ $tr->[3] ? @{$tr->[3]} : (), $desc->[3] ? @{$desc->[3]} : () ];      my $dl = $node->[0];
3573      }      my $size0 = $subtree_size->{ $dl->[0] };
3574      if ( $tr->[4] && @{$tr->[4]} || $desc->[4] && @{$desc->[4]} ) {      if ( $size0 > $pos ) { $i = 0 } else { $i = 1; $pos -= $size0 }
3575          $nn[4] = [ $tr->[4] ? @{$tr->[4]} : (), $desc->[4] ? @{$desc->[4]} : () ];      my $desc = $dl->[$i];
3576      }  
3577      if ( $tr->[5] && @{$tr->[5]} || $desc->[5] && @{$desc->[5]} ) {      # Does it go within the subtree, or the branch to the subtree?
3578          $nn[5] = [ $tr->[5] ? @{$tr->[5]} : (), $desc->[5] ? @{$desc->[5]} : () ];  
3579      }      my $len;
3580      if ( $tr->[6] && @{$tr->[6]} || $desc->[6] && @{$desc->[6]} ) {      my $added;
3581          $nn[6] = [ $tr->[6] ? @{$tr->[6]} : (), $desc->[6] ? @{$desc->[6]} : () ];      if ( ( $len = $desc->[2] ) <= $pos )
3582        {
3583            $added = random_add_to_ultrametric_tree( $desc, $tip, $subtree_size, $pos - $len, $d2tip - $len );
3584      }      }
3585      if ( $tr->[7] && @{$tr->[7]} || $desc->[7] && @{$desc->[7]} ) {      else
3586          $nn[7] = [ $tr->[7] ? @{$tr->[7]} : (), $desc->[7] ? @{$desc->[7]} : () ];      {
3587            # If not in subtree, then it goes in the branch to the descendent node
3588            #
3589            #     ----- node  ------------       node
3590            #       ^   /  \       ^             /  \
3591            #       |       \      | pos             \l1
3592            #       |        \     v                  \
3593            #       |      len\ ----------         newnode
3594            #       |          \                     /  \ l2
3595            # d2tip |           \                   /    \
3596            #       |           desc               /     desc
3597            #       |           /  \            l3/      /  \
3598            #       |          .    .            /      .    .
3599            #       v         .      .          /      .      .
3600            #     -----      .        .     newtip    .        .
3601    
3602            my $l1      = $pos;
3603            my $l2      = $len   - $pos;
3604            my $l3      = $d2tip - $pos;
3605            my $newtip  = [ [], $tip, $l3 ];
3606            my $newnode = [ [ $desc, $newtip ], undef, $l1 ];
3607            $dl->[$i]   = $newnode;
3608            $subtree_size->{ $newtip  } = $l3;
3609            $subtree_size->{ $newnode } = $subtree_size->{ $desc } + $l3;
3610            $desc->[2] = $l2;
3611            $subtree_size->{ $desc } -= $l1;
3612            $added = $l3;
3613      }      }
3614    
3615      return \@nn;      #  New branch was inserted below this point:
3616    
3617        $subtree_size->{ $node } += $added;
3618        return $added;
3619  }  }
3620    
3621    
3622    
3623  #===============================================================================  #===============================================================================
3624  #  #
3625  #  Tree writing and reading  #  Tree writing and reading
3626  #  #
3627  #===============================================================================  #===============================================================================
3628  #  writeNewickTree( $tree [, $file ] )  #
3629    #  writeNewickTree( $tree )
3630    #  writeNewickTree( $tree, $file )
3631    #  writeNewickTree( $tree, \*FH )
3632    #
3633  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3634  sub writeNewickTree {  sub writeNewickTree
3635    {
3636      my ( $tree, $file ) = @_;      my ( $tree, $file ) = @_;
3637      $file || ( $file = \*STDOUT );      my ( $fh, $close ) = open_output( $file );
3638      print  $file  ( strNewickTree( $tree ), "\n" );      $fh or return;
3639        print  $fh  ( strNewickTree( $tree ), "\n" );
3640        close $fh if $close;
3641  }  }
3642    
3643    
# Line 2037  Line 3650 
3650  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3651  #  $treestring = strNewickTree( $tree )  #  $treestring = strNewickTree( $tree )
3652  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3653  sub strNewickTree {  sub strNewickTree
3654    {
3655      my $node = shift @_;      my $node = shift @_;
3656      strNewickSubtree( $node, "" ) . ";";      strNewickSubtree( $node, "" ) . ";";
3657  }  }
# Line 2046  Line 3660 
3660  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3661  #  $string = strNewickSubtree( $node, $prefix )  #  $string = strNewickSubtree( $node, $prefix )
3662  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3663  sub strNewickSubtree {  sub strNewickSubtree
3664    {
3665      my ( $node, $prefix ) = @_;      my ( $node, $prefix ) = @_;
3666      my  $s;      my  $s;
3667    
# Line 2064  Line 3679 
3679          $prefix = " ";          $prefix = " ";
3680      }      }
3681    
3682      if ( defined( newick_lbl( $node ) ) && newick_lbl( $node ) ) {      if ( node_has_lbl( $node ) ) {
3683          $s .= $prefix          $s .= $prefix
3684             .  q_newick_lbl( $node )             .  q_newick_lbl( $node )
3685             .  strNewickComments( newick_c3( $node ), " " );             .  strNewickComments( newick_c3( $node ), " " );
# Line 2084  Line 3699 
3699  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3700  #  $string = strNewickComments( $clist, $prefix )  #  $string = strNewickComments( $clist, $prefix )
3701  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3702  sub strNewickComments {  sub strNewickComments
3703    {
3704      my ( $clist, $prefix ) = @_;      my ( $clist, $prefix ) = @_;
3705      array_ref( $clist ) && ( @$clist > 0 ) || return  "";      array_ref( $clist ) && ( @$clist > 0 ) || return  "";
3706      $prefix . "[" . join( "] [", @$clist ) . "]";      $prefix . "[" . join( "] [", @$clist ) . "]";
# Line 2094  Line 3710 
3710  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3711  #  $quoted_label = q_newick_lbl( $label )  #  $quoted_label = q_newick_lbl( $label )
3712  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3713  sub q_newick_lbl {  sub q_newick_lbl
3714      my $lbl = newick_lbl( $_[0] );  {
3715      defined( $lbl ) && ( $lbl ne "" ) || return undef;      node_has_lbl( $_[0] ) || return undef;
3716    
3717        my $lbl = newick_lbl( $_[0] );
3718      if ( $lbl =~ m/^[^][()_:;,]+$/        #  Anything but []()_:;,      if ( $lbl =~ m/^[^][()_:;,]+$/        #  Anything but []()_:;,
3719        && $lbl !~ m/^'/  ) {               #     and does not start with '        && $lbl !~ m/^'/  ) {               #     and does not start with '
3720          $lbl =~ s/ /_/g;                  #  Recode blanks as _          $lbl =~ s/ /_/g;                  #  Recode blanks as _
# Line 2112  Line 3729 
3729    
3730    
3731  #===============================================================================  #===============================================================================
3732    #
3733  #  $treestring = formatNewickTree( $tree )  #  $treestring = formatNewickTree( $tree )
3734    #
3735  #===============================================================================  #===============================================================================
3736  sub formatNewickTree {  sub formatNewickTree
3737    {
3738      formatNewickSubtree( $_[0], "", "" ) . ";";      formatNewickSubtree( $_[0], "", "" ) . ";";
3739  }  }
3740    
# Line 2122  Line 3742 
3742  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3743  #  $string = formatNewickSubtree( $node, $prefix, $indent )  #  $string = formatNewickSubtree( $node, $prefix, $indent )
3744  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3745  sub formatNewickSubtree {  sub formatNewickSubtree
3746    {
3747      my ( $node, $prefix, $indent ) = @_;      my ( $node, $prefix, $indent ) = @_;
3748      my  $s;      my  $s;
3749    
# Line 2139  Line 3760 
3760          $prefix = " ";          $prefix = " ";
3761      }      }
3762    
3763      if ( defined( newick_lbl( $node ) ) && newick_lbl( $node ) ) {      if ( node_has_lbl( $node ) ) {
3764          $s .= $prefix          $s .= $prefix
3765             .  q_newick_lbl( $node )             .  q_newick_lbl( $node )
3766             .  formatNewickComments( newick_c3( $node ), " ", $indent );             .  formatNewickComments( newick_c3( $node ), " ", $indent );
# Line 2159  Line 3780 
3780  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3781  #  $string = formatNewickComments( $clist, $prefix, $indent )  #  $string = formatNewickComments( $clist, $prefix, $indent )
3782  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3783  sub formatNewickComments {  sub formatNewickComments
3784    {
3785      my ( $clist, $prefix, $indent ) = @_;      my ( $clist, $prefix, $indent ) = @_;
3786      array_ref( $clist ) && @$clist || return  "";      array_ref( $clist ) && @$clist || return  "";
3787      $prefix . "[" . join( "] [", @$clist ) . "]";      $prefix . "[" . join( "] [", @$clist ) . "]";
# Line 2167  Line 3789 
3789    
3790    
3791  #===============================================================================  #===============================================================================
3792    #
3793    #  $tree  = read_newick_tree( $file )  # reads to a semicolon
3794    #  @trees = read_newick_trees( $file ) # reads to end of file
3795    #
3796    #===============================================================================
3797    
3798    sub read_newick_tree
3799    {
3800        my $file = shift;
3801        my ( $fh, $close ) = open_input( $file );
3802        my $tree;
3803        my @lines = ();
3804        foreach ( <$fh> )
3805        {
3806            chomp;
3807            push @lines, $_;
3808            if ( /;/ )
3809            {
3810                $tree = parse_newick_tree_str( join( ' ', @lines ) );
3811                last;
3812            }
3813        }
3814        close $fh if $close;
3815    
3816        $tree;
3817    }
3818    
3819    
3820    sub read_newick_trees
3821    {
3822        my $file = shift;
3823        my ( $fh, $close ) = open_input( $file );
3824        my @trees = ();
3825        my @lines = ();
3826        foreach ( <$fh> )
3827        {
3828            chomp;
3829            push @lines, $_;
3830            if ( /;/ )
3831            {
3832                push @trees, parse_newick_tree_str( join( ' ', @lines ) );
3833                @lines = ()
3834            }
3835        }
3836        close $fh if $close;
3837    
3838        @trees;
3839    }
3840    
3841    
3842    #===============================================================================
3843  #  Tree reader adapted from the C language reader in fastDNAml  #  Tree reader adapted from the C language reader in fastDNAml
3844  #  #
3845  #  $tree = parse_newick_tree_str( $string )  #  $tree = parse_newick_tree_str( $string )
3846    #
3847  #===============================================================================  #===============================================================================
3848  sub parse_newick_tree_str {  sub parse_newick_tree_str
3849    {
3850      my $s = shift @_;      my $s = shift @_;
3851    
3852      my ( $ind, $rootnode ) = parse_newick_subtree( $s, 0 );      my ( $ind, $rootnode ) = parse_newick_subtree( $s, 0 );
# Line 2183  Line 3858 
3858  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3859  #  Read a subtrees recursively (everything of tree but a semicolon)  #  Read a subtrees recursively (everything of tree but a semicolon)
3860  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3861  sub parse_newick_subtree {  sub parse_newick_subtree
3862    {
3863      my ( $s, $ind ) = @_;      my ( $s, $ind ) = @_;
3864    
3865      my $newnode = [];      my $newnode = [];
# Line 2237  Line 3913 
3913  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3914  #  Read a Newick tree label  #  Read a Newick tree label
3915  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3916  sub parseTreeNodeLabel {  #  Empty string is permitted  sub parseTreeNodeLabel
3917    {  #  Empty string is permitted
3918      my ( $s, $ind ) = @_;      my ( $s, $ind ) = @_;
3919      my ( $lbl, $c );      my ( $lbl, $c );
3920    
# Line 2272  Line 3949 
3949  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3950  #  Read a Newick tree branch length  #  Read a Newick tree branch length
3951  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3952  sub parseBranchLength {  sub parseBranchLength
3953    {
3954      my ( $s, $ind ) = @_;      my ( $s, $ind ) = @_;
3955    
3956      my $c = substr( $s, $ind, 1 );      my $c = substr( $s, $ind, 1 );
# Line 2326  Line 4004 
4004  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4005  #  ( $index, /@commentlist ) = getNextTreeChar( $string, $index )  #  ( $index, /@commentlist ) = getNextTreeChar( $string, $index )
4006  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4007  sub getNextTreeChar {       #  Move to next nonblank, noncomment character  sub getNextTreeChar
4008    {       #  Move to next nonblank, noncomment character
4009      my ( $s, $ind ) = @_;      my ( $s, $ind ) = @_;
4010    
4011      my @clist = ();      my @clist = ();
# Line 2337  Line 4016 
4016      #  Loop while it is a comment:      #  Loop while it is a comment:
4017      while ( substr( $s, $ind, 1 ) eq "[" ) {      while ( substr( $s, $ind, 1 ) eq "[" ) {
4018          $ind++;          $ind++;
4019            my $depth = 1;
4020            my $ind2  = $ind;
4021    
4022          #  Find end          #  Find end
4023          if ( substr( $s, $ind ) !~ /^([^]]*)\]/ ) {          while ( $depth > 0 )
4024            {
4025                if ( substr( $s, $ind2 ) =~ /^([^][]*\[)/ )     # nested [ ... ]
4026                {
4027                    $ind2 += length( $1 );  #  Points at char just past [
4028                    $depth++;               #  If nested comments are allowed
4029                }
4030                elsif ( substr( $s, $ind2 ) =~ /^([^][]*\])/ )  # close bracket
4031                {
4032                    $ind2 += length( $1 );  #  Points at char just past ]
4033                    $depth--;
4034                }
4035                else
4036                {
4037              treeParseError( "comment missing closing bracket '["              treeParseError( "comment missing closing bracket '["
4038                             . substr( $s, $ind ) . "'" )                             . substr( $s, $ind ) . "'" )
4039          }          }
4040          my $comment = $1;          }
4041    
4042          #  Save if it includes any "text"          my $comment = substr( $s, $ind, $ind2-$ind-1 );
4043          if ( $comment =~ m/\S/ ) { push @clist, $comment }          if ( $comment =~ m/\S/ ) { push @clist, $comment }
4044    
4045          $ind += length( $comment ) + 1;     #  Comment plus closing bracket          $ind = $ind2;
4046    
4047          #  Skip white space          #  Skip white space
4048          if ( substr( $s, $ind ) =~ /^(\s+)/ ) { $ind += length( $1 ) }          if ( substr( $s, $ind ) =~ /^(\s+)/ ) { $ind += length( $1 ) }
# Line 2367  Line 4061 
4061  #===============================================================================  #===============================================================================
4062  #  Make a printer plot of a tree:  #  Make a printer plot of a tree:
4063  #  #
4064  #     $node   newick tree root node  #  printer_plot_newick( $node, $file, $width, $min_dx, $dy )
4065  #     $file   undef (= \*STDOUT), \*STDOUT, \*STDERR, or a file name.  #  printer_plot_newick( $node, $file, \%options )
4066  #     $width  the approximate characters for the tree without labels  #
4067  #     $min_dx the minimum horizontal branch length  #     $node   # newick tree root node
4068  #     $dy     the vertical space per taxon  #     $file   # undef = \*STDOUT, \*FH, or a file name.
4069  #  #     $width  # the approximate characters for the tree without labels (D = 68)
4070  #  printer_plot_newick( $node, $file (D=\*STDOUT), $width (D=68), $min_dx (D=2), $dy (D=1) )  #     $min_dx # the minimum horizontal branch length (D = 2)
4071  #===============================================================================  #     $dy     # the vertical space per taxon (D = 1, most compressed)
4072  sub printer_plot_newick {  #
4073      my ( $node, $file, $width, $min_dx, $dy ) = @_;  #  Options:
4074    #
4075      my ( $fh, $close );  #    dy     => nat_number    # the vertical space per taxon
4076      if ( ! defined( $file ) ) {  #    chars  => key           # line drawing character set:
4077          $fh = \*STDOUT;  #                            #     html_unicode
4078      }  #                            #     text (default)
4079      elsif ( $file =~ /^\*/ ) {  #    min_dx => whole_number  # the minimum horizontal branch length
4080          $fh = $file;  #    width  => whole_number  # approximate tree width without labels
4081      }  #
4082      else {  #===============================================================================
4083          open $fh, ">$file" or die "Could not open $file for writing printer_plot_newick\n";  sub printer_plot_newick
4084          $close = 1;  {
4085      }      my ( $node, $file, @opts ) = @_;
4086    
4087        my ( $fh, $close ) = open_output( $file );
4088        $fh or return;
4089    
4090        my $html = $opts[0] && ref($opts[0]) eq 'HASH'
4091                            && $opts[0]->{ chars }
4092                            && $opts[0]->{ chars } =~ /html/;
4093        print $fh '<PRE>' if $html;
4094        print $fh join( "\n", text_plot_newick( $node, @opts ) ), "\n";
4095        print $fh "</PRE>\n" if $html;
4096    
     print $fh join( "\n", text_plot_newick( $node, $width, $min_dx, $dy ) ), "\n";  
4097      if ( $close ) { close $fh }      if ( $close ) { close $fh }
4098  }  }
4099    
4100    
4101  #===============================================================================  #===============================================================================
4102    #  Character sets for printer plot trees:
4103    #-------------------------------------------------------------------------------
4104    
4105    my %char_set =
4106      ( text1     => { space  => ' ',
4107                       horiz  => '-',
4108                       vert   => '|',
4109                       el_d_r => '/',
4110                       el_u_r => '\\',
4111                       el_d_l => '\\',
4112                       el_u_l => '/',
4113                       tee_l  => '+',
4114                       tee_r  => '+',
4115                       tee_u  => '+',
4116                       tee_d  => '+',
4117                       half_l => '-',
4118                       half_r => '-',
4119                       half_u => '|',
4120                       half_d => '|',
4121                       cross  => '+',
4122                     },
4123        text2     => { space  => ' ',
4124                       horiz  => '-',
4125                       vert   => '|',
4126                       el_d_r => '+',
4127                       el_u_r => '+',
4128                       el_d_l => '+',
4129                       el_u_l => '+',
4130                       tee_l  => '+',
4131                       tee_r  => '+',
4132                       tee_u  => '+',
4133                       tee_d  => '+',
4134                       half_l => '-',
4135                       half_r => '-',
4136                       half_u => '|',
4137                       half_d => '|',
4138                       cross  => '+',
4139                     },
4140        html_box  => { space  => '&nbsp;',
4141                       horiz  => '&#9472;',
4142                       vert   => '&#9474;',
4143                       el_d_r => '&#9484;',
4144                       el_u_r => '&#9492;',
4145                       el_d_l => '&#9488;',
4146                       el_u_l => '&#9496;',
4147                       tee_l  => '&#9508;',
4148                       tee_r  => '&#9500;',
4149                       tee_u  => '&#9524;',
4150                       tee_d  => '&#9516;',
4151                       half_l => '&#9588;',
4152                       half_r => '&#9590;',
4153                       half_u => '&#9589;',
4154                       half_d => '&#9591;',
4155                       cross  => '&#9532;',
4156                     },
4157        utf8_box  => { space  => ' ',
4158                       horiz  => chr(226) . chr(148) . chr(128),
4159                       vert   => chr(226) . chr(148) . chr(130),
4160                       el_d_r => chr(226) . chr(148) . chr(140),
4161                       el_u_r => chr(226) . chr(148) . chr(148),
4162                       el_d_l => chr(226) . chr(148) . chr(144),
4163                       el_u_l => chr(226) . chr(148) . chr(152),
4164                       tee_l  => chr(226) . chr(148) . chr(164),
4165                       tee_r  => chr(226) . chr(148) . chr(156),
4166                       tee_u  => chr(226) . chr(148) . chr(180),
4167                       tee_d  => chr(226) . chr(148) . chr(172),
4168                       half_l => chr(226) . chr(149) . chr(180),
4169                       half_r => chr(226) . chr(149) . chr(182),
4170                       half_u => chr(226) . chr(149) . chr(181),
4171                       half_d => chr(226) . chr(149) . chr(183),
4172                       cross  => chr(226) . chr(148) . chr(188),
4173                     },
4174      );
4175    
4176    %{ $char_set{ html1 } } = %{ $char_set{ text1 } };
4177    $char_set{ html1 }->{ space } = '&nbsp;';
4178    
4179    %{ $char_set{ html2 } } = %{ $char_set{ text2 } };
4180    $char_set{ html2 }->{ space } = '&nbsp;';
4181    
4182    #  Define some synonyms
4183    
4184    $char_set{ html } = $char_set{ html_box };
4185    $char_set{ line } = $char_set{ utf8_box };
4186    $char_set{ symb } = $char_set{ utf8_box };
4187    $char_set{ text } = $char_set{ text1 };
4188    $char_set{ utf8 } = $char_set{ utf8_box };
4189    
4190    #  Define tree formats and synonyms
4191    
4192    my %tree_format =
4193        ( text         => 'text',
4194          tree_tab_lbl => 'tree_tab_lbl',
4195          tree_lbl     => 'tree_lbl',
4196          chrlist_lbl  => 'chrlist_lbl',
4197          raw          => 'chrlist_lbl',
4198        );
4199    
4200    #===============================================================================
4201  #  Make a text plot of a tree:  #  Make a text plot of a tree:
4202  #  #
4203  #     $node   newick tree root node  #  @lines = text_plot_newick( $node, $width, $min_dx, $dy )
4204  #     $width  the approximate characters for the tree without labels  #  @lines = text_plot_newick( $node, \%options )
4205  #     $min_dx the minimum horizontal branch length  #
4206  #     $dy     the vertical space per taxon  #     $node   # newick tree root node
4207    #     $width  # the approximate characters for the tree without labels (D = 68)
4208    #     $min_dx # the minimum horizontal branch length (D = 2)
4209    #     $dy     # the vertical space per taxon (D = 1, most compressed)
4210    #
4211    #  Options:
4212    #
4213    #    chars  => keyword       # the output character set for the tree
4214    #    dy     => nat_number    # the vertical space per taxon
4215    #    format => keyword       # output format of each line
4216    #    min_dx => whole_number  # the minimum horizontal branch length
4217    #    width  => whole_number  # approximate tree width without labels
4218    #
4219    #  Character sets:
4220    #
4221    #    html       #  synonym of html1
4222    #    html_box   #  html encoding of unicode box drawing characters
4223    #    html1      #  text1 with nonbreaking spaces
4224    #    html2      #  text2 with nonbreaking spaces
4225    #    line       #  synonym of utf8_box
4226    #    raw        #  pass out the internal representation
4227    #    symb       #  synonym of utf8_box
4228    #    text       #  synonym of text1 (Default)
4229    #    text1      #  ascii characters: - + | / \ and space
4230    #    text2      #  ascii characters: - + | + + and space
4231    #    utf8       #  synonym of utf8_box
4232    #    utf8_box   #  utf8 encoding of unicode box drawing characters
4233    #
4234    #  Formats for row lines:
4235    #
4236    #    text           #    $textstring              # Default
4237    #    tree_tab_lbl   #    $treestr \t $labelstr
4238    #    tree_lbl       # [  $treestr,  $labelstr ]
4239    #    chrlist_lbl    # [ \@treechar, $labelstr ]   # Forced with raw chars
4240    #    raw            #  synonym of chrlist_lbl
4241  #  #
 #  @textlines = text_plot_newick( $node, $width (D=68), $min_dx (D=2), $dy (D=1) )  
4242  #===============================================================================  #===============================================================================
4243  sub text_plot_newick {  sub text_plot_newick
4244      my ( $node, $width, $min_dx, $dy ) = @_;  {
4245        my $node = shift @_;
4246      array_ref( $node ) || die "Bad node passed to text_plot_newick\n";      array_ref( $node ) || die "Bad node passed to text_plot_newick\n";
4247      defined( $min_dx ) and ( $min_dx >=  0 ) or $min_dx =  2;  
4248      defined(     $dy ) and (     $dy >=  1 ) or     $dy =  1;      my ( $opts, $width, $min_dx, $dy, $chars, $fmt );
4249      defined( $width  )                       or  $width = 68;      if ( $_[0] && ref $_[0] eq 'HASH' )
4250        {
4251            $opts = shift;
4252        }
4253        else
4254        {
4255            ( $width, $min_dx, $dy ) = @_;
4256            $opts = {};
4257        }
4258    
4259        $chars = $opts->{ chars } || '';
4260        my $charH;
4261        $charH = $char_set{ $chars } || $char_set{ 'text1' } if ( $chars ne 'raw' );
4262        my $is_box = $charH eq $char_set{ html_box }
4263                  || $charH eq $char_set{ utf8_box }
4264                  || $chars eq 'raw';
4265    
4266        $fmt = ( $chars eq 'raw' ) ? 'chrlist_lbl' : $opts->{ format };
4267        $fmt = $tree_format{ $fmt || '' } || 'text';
4268    
4269        $dy    ||= $opts->{ dy     } ||  1;
4270        $width ||= $opts->{ width  } || 68;
4271        $min_dx  = $opts->{ min_dx } if ( ! defined $min_dx || $min_dx < 0 );
4272        $min_dx  = $is_box ? 1 : 2   if ( ! defined $min_dx || $min_dx < 0 );
4273    
4274        #  Layout the tree:
4275    
4276      $min_dx = int( $min_dx );      $min_dx = int( $min_dx );
4277      $dy     = int( $dy );      $dy     = int( $dy );
# Line 2419  Line 4280 
4280      my $hash = {};      my $hash = {};
4281      layout_printer_plot( $node, $hash, 0, -0.5 * $dy, $x_scale, $min_dx, $dy );      layout_printer_plot( $node, $hash, 0, -0.5 * $dy, $x_scale, $min_dx, $dy );
4282    
4283      # dump_tree_hash( $node, $hash ); exit;      #  Generate the lines of the tree-one by-one:
   
     #  Generate the lines of the tree one by one:  
4284    
4285      my ( $y1, $y2 ) = @{ $hash->{ $node } };      my ( $y1, $y2 ) = @{ $hash->{ $node } };
4286      map { text_tree_row( $node, $hash, $_, "", "+" ) } ( $y1 .. $y2 );      my @lines;
4287        foreach ( ( $y1 .. $y2 ) )
4288        {
4289            my $line = text_tree_row( $node, $hash, $_, [], 'tee_l', $dy >= 2 );
4290            my $lbl  = '';
4291            if ( @$line )
4292            {
4293                if ( $line->[-1] eq '' ) { pop @$line; $lbl = pop @$line }
4294                #  Translate tree characters
4295                @$line = map { $charH->{ $_ } } @$line if $chars ne 'raw';
4296            }
4297    
4298            # Convert to requested output format:
4299    
4300            push @lines, $fmt eq 'text'         ? join( '', @$line, ( $lbl ? " $lbl" : () ) )
4301                       : $fmt eq 'text_tab_lbl' ? join( '', @$line, "\t", $lbl )
4302                       : $fmt eq 'tree_lbl'     ? [ join( '', @$line ), $lbl ]
4303                       : $fmt eq 'chrlist_lbl'  ? [ $line, $lbl ]
4304                       :                          ();
4305        }
4306    
4307        # if ( $cells )
4308        # {
4309        #     my $nmax = 0;
4310        #     foreach ( @lines ) { $nmax = @$_ if @$_ > $nmax }
4311        #     foreach ( @lines )
4312        #     {
4313        #         @$_ = map { "<TD>$_</TD>" } @$_;
4314        #         my $span = $nmax - @$_ + 1;
4315        #         $_->[-1] =~ s/^<TD>/<TD NoWrap ColSpan=$span>/;
4316        #     }
4317        # }
4318        # elsif ( $tables )
4319        # {
4320        #     my $nmax = 0;
4321        #     foreach ( @lines ) { $nmax = @$_ if @$_ > $nmax }
4322        #     foreach ( @lines )
4323        #     {
4324        #         @$_ = map { "<TD>$_</TD>" } @$_;
4325        #         my $span = $nmax - @$_ + 1;
4326        #         $_->[-1] =~ s/^<TD>/<TD NoWrap ColSpan=$span>/;
4327        #     }
4328        # }
4329    
4330        wantarray ? @lines : \@lines;
4331  }  }
4332    
4333    
4334  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4335  #  ( $xmax, $ymax, $root_y ) = layout_printer_plot( $node, $hash, $x0, $y0, $x_scale, $min_dx, $dy )  #  ( $xmax, $ymax, $root_y ) = layout_printer_plot( $node, $hash, $x0, $y0, $x_scale, $min_dx, $dy, $yrnd )
4336  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4337  sub layout_printer_plot {  sub layout_printer_plot
4338      my ( $node, $hash, $x0, $y0, $x_scale, $min_dx, $dy ) = @_;  {
4339        my ( $node, $hash, $x0, $y0, $x_scale, $min_dx, $dy, $yrnd ) = @_;
4340      array_ref( $node ) || die "Bad node ref passed to layout_printer_plot\n";      array_ref( $node ) || die "Bad node ref passed to layout_printer_plot\n";
4341      hash_ref(  $hash ) || die "Bad hash ref passed to layout_printer_plot\n";      hash_ref(  $hash ) || die "Bad hash ref passed to layout_printer_plot\