[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.8, Sun Feb 11 18:25:48 2007 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-2007 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 77  Line 77 
77  #  Tree format interconversion:  #  Tree format interconversion:
78  #===============================================================================  #===============================================================================
79  #  #
80    #  $bool      = is_overbeek_tree( $tree )
81    #  $bool      = is_gjonewick_tree( $tree )
82    #
83  #  $gjonewick = overbeek_to_gjonewick( $overbeek )  #  $gjonewick = overbeek_to_gjonewick( $overbeek )
84  #  $overbeek  = gjonewick_to_overbeek( $gjonewick )  #  $overbeek  = gjonewick_to_overbeek( $gjonewick )
85  #  #
# Line 96  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 107  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  #  $bool    = newick_is_valid( $noderef )       # verify that tree is valid
120  #  #
# Line 118  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  #  Tree tip insertion point (tip is on branch of length x that
157  #  is inserted into branch connecting node1 and node2, a distance  #  is inserted into branch connecting node1 and node2, a distance
158  #  x1 from node1 and x2 from node2):  #  x1 from node1 and x2 from node2):
159  #  #
160  #  [ $node1, $x1, $node2, $x2, $x ]  #  [ $node1, $x1, $node2, $x2, $x ] = newick_tip_insertion_point( $tree, $tip )
 #           = newick_tip_insertion_point( $tree, $tip )  
161  #  #
162  #  Standardized label for a node in terms of intersection of 3 lowest sorting  #  Standardized label for a node in terms of intersection of 3 lowest sorting
163  #  tips (sort is lower case):  #  tips (sort is lower case):
164  #  #
165  #  @TipOrTips = std_node_name( $Tree, $Node )  #  @TipOrTips = std_node_name( $tree, $node )
166  #  #
167  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
168  #  Paths from root of tree:  #  Paths from root of tree:
# Line 151  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 189  Line 215 
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 )  #  $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:  #  Modify comments:
223  #  #
# Line 201  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  #  #
# Line 222  Line 259 
259  #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )  #  $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 )
# Line 231  Line 305 
305  #  fwriteNewickTree( $file, $tree )  # Matches the C arg list for f... I/O  #  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  #  $tree  = read_newick_tree( $file )  # reads to a semicolon
317  #  @trees = read_newick_trees( $file ) # reads to end of file  #  @trees = read_newick_trees( $file ) # reads to end of file
318  #  $tree  = parse_newick_tree_str( $string )  #  $tree  = parse_newick_tree_str( $string )
# Line 243  Line 322 
322    
323  use Carp;  use Carp;
324  use Data::Dumper;  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          overbeek_to_gjonewick
334          gjonewick_to_overbeek          gjonewick_to_overbeek
   
335          newick_is_valid          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 290  Line 376 
376          newick_set_all_branches          newick_set_all_branches
377          newick_fix_negative_branches          newick_fix_negative_branches
378          newick_rescale_branches          newick_rescale_branches
379            newick_random_branch_lengths
380            newick_modify_branches
381    
382          newick_strip_comments          newick_strip_comments
383    
# Line 300  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          newick_insert_at_node
413          newick_insert_between_nodes          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
# Line 342  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 362  Line 468 
468          );          );
469    
470    
 use gjolists qw(  
         common_prefix  
         unique_suffixes  
   
         duplicates  
         random_order  
   
         intersection  
         set_difference  
         );  
   
   
 use strict;  
   
   
471  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
472  #  Internally used definitions  #  Internally used definitions
473  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
474    
475  sub array_ref { ref( $_[0] ) eq "ARRAY" }  sub array_ref { $_[0] && ref( $_[0] ) eq 'ARRAY' }
476  sub hash_ref  { ref( $_[0] ) eq "HASH"  }  sub hash_ref  { $_[0] && ref( $_[0] ) eq 'HASH'  }
477    
478    sub max       { $_[0] >= $_[1] ? $_[0] : $_[1] }
479    sub min       { $_[0] <= $_[1] ? $_[0] : $_[1] }
480    
481    
482  #===============================================================================  #===============================================================================
483  #  Interconvert Overbeek and gjonewick trees:  #  Interconvert overbeek and gjonewick trees:
484  #===============================================================================  #===============================================================================
485    
486    sub is_overbeek_tree  { array_ref( $_[0] ) && array_ref( $_[0]->[2] ) }
487    
488    sub is_gjonewick_tree { array_ref( $_[0] ) && array_ref( $_[0]->[0] ) }
489    
490  sub overbeek_to_gjonewick  sub overbeek_to_gjonewick
491  {  {
492      return () unless ref( $_[0] ) eq 'ARRAY';      return () unless ref( $_[0] ) eq 'ARRAY';
# Line 408  Line 506 
506      return $node;      return $node;
507  }  }
508    
509    
510  #===============================================================================  #===============================================================================
511  #  Extract tree structure values:  #  Extract tree structure values:
512  #===============================================================================  #===============================================================================
# Line 423  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      { ref($_[0]) ? $_[0]->[1] : Carp::confess() }  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 486  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 560  Line 666 
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 573  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 586  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 601  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 622  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 641  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 652  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 666  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 677  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 694  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 707  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      gjolists::duplicates( newick_tip_list( $_[0] ) );  {
832        my @tips = &duplicates( newick_tip_list( $_[0] ) );
833        wantarray ? @tips : \@tips;
834  }  }
835    
836    
# Line 718  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 740  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      gjolists::intersection( \@Tips1, \@Tips2 );      my $tips2 = newick_tip_list( $tree2 );
875        my @tips = &intersection( $tips1, $tips2 );
876        wantarray ? @tips : \@tips;
877  }  }
878    
879    
# Line 754  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 767  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 790  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 812  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 834  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  }  }
# Line 910  Line 1080 
1080    
1081      else      else
1082      {      {
1083          my ( $n1, $x1 ) = describe_desc( $dl->[0] );          my ( $n1, $x1 ) = describe_descendant( $dl->[0] );
1084          my ( $n2, $x2 ) = describe_desc( $dl->[1] );          my ( $n2, $x2 ) = describe_descendant( $dl->[1] );
1085    
1086          if ( @$n1 == 2 ) { push @$n1, $n2->[0] }          if ( @$n1 == 2 ) { push @$n1, $n2->[0] }
1087          if ( @$n2 == 2 )          if ( @$n2 == 2 )
# Line 926  Line 1096 
1096  }  }
1097    
1098    
1099  sub describe_desc  sub describe_descendant
1100  {  {
1101      my $node = shift;      my $node = shift;
1102    
# Line 942  Line 1112 
1112    
1113      #  Is it a tip?  Return list of one tip;      #  Is it a tip?  Return list of one tip;
1114    
1115      if ( ( ! $dl ) || @$dl == 0 )      if ( ( ! $dl ) || ! @$dl ) { return ( [ newick_lbl( $node ) ], $x ) }
     {  
         return ( [ newick_lbl( $node ) ], $x );  
     }  
1116    
1117      #  Get tips of each descendent, keeping lowest sorting from each.      #  Get tips of each descendent, keeping lowest sorting from each.
1118      #  Return the two lowest of those (the third will come from the      #  Return the two lowest of those (the third will come from the
1119      #  other side of the original node).      #  other side of the original node).
1120    
     else  
     {  
1121          my @rep_tips = sort { lc $a cmp lc $b }          my @rep_tips = sort { lc $a cmp lc $b }
1122                         map  { ( sort { lc $a cmp lc $b } newick_tip_list( $_ ) )[0] }                         map  { ( sort { lc $a cmp lc $b } newick_tip_list( $_ ) )[0] }
1123                         @$dl;                         @$dl;
1124          return ( [ @rep_tips[0,1] ], $x );          return ( [ @rep_tips[0,1] ], $x );
1125      }      }
 }  
1126    
1127    
1128  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
# Line 967  Line 1131 
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 977  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    
# Line 985  Line 1150 
1150      #  @rest, and keeping the best tip for each subtree.      #  @rest, and keeping the best tip for each subtree.
1151    
1152      my @rest = newick_tip_list( $tree );      my @rest = newick_tip_list( $tree );
1153      my @best = map {      my @best = map
1154              {
1155              my @tips = sort { lc $a cmp lc $b } newick_tip_list( $_ );              my @tips = sort { lc $a cmp lc $b } newick_tip_list( $_ );
1156              @rest = gjolists::set_difference( \@rest, \@tips );              @rest = &set_difference( \@rest, \@tips );
1157              $tips[0];              $tips[0];
1158          } newick_desc_list( $noderef );          } newick_desc_list( $noderef );
1159    
# Line 1013  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 1038  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    #
1207    #-------------------------------------------------------------------------------
1208    sub paths_to_tips
1209    {
1210        my ( $node, $tips ) = @_;
1211        return {} if ! ( $tips && ref( $tips ) );
1212    
1213        #  Replace request for list with request by hash
1214    
1215        if ( ref( $tips ) eq 'ARRAY' ) { $tips = { map { $_ => 1 } @$tips } }
1216    
1217        my $paths = {};
1218        my $imax = newick_n_desc( $node );
1219        if ( $imax < 2 )
1220        {
1221            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        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 named node.  Like path to tip, but also finds named internal nodes.
1246  #  #
1247  #  @path = path_to_named_node( $treenode, $name )  #  @path = path_to_named_node( $treenode, $name )
1248    #
1249  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1250  sub path_to_named_node {  sub path_to_named_node
1251      my ( $node, $name, @path0 ) = @_;  {
1252        my ( $node, $name ) = @_;
1253    
1254      push @path0, $node;      return ( $node ) if node_lbl_is( $node, $name );
     if ( newick_lbl( $node ) eq $name ) { 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_named_node( newick_desc_i( $node, $i ), $name, ( @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 1061  Line 1264 
1264    
1265    
1266  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1267    #  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    #-------------------------------------------------------------------------------
1273    sub paths_to_named_nodes
1274    {
1275        my ( $node, $names ) = @_;
1276        return {} if ! ( $names && ref( $names ) );
1277    
1278        #  Replace request for list with request by hash
1279    
1280        if ( ref( $names ) eq 'ARRAY' ) { $names = { map { $_ => 1 } @$names } }
1281    
1282        my $paths = {};
1283        my $imax = newick_n_desc( $node );
1284    
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        for ( my $i = 1; $i <= $imax && keys %$names; $i++ )
1294        {
1295           my $new = paths_to_named_nodes( newick_desc_i( $node, $i ), $names );
1296           foreach ( keys %$new )
1297           {
1298               splice @{ $new->{ $_ } }, 0, 0, ( $node, $i );
1299               $paths->{ $_ } = $new->{ $_ };
1300           }
1301        }
1302    
1303        return $paths;
1304    }
1305    
1306    
1307    #-------------------------------------------------------------------------------
1308  #  Path to node reference.  #  Path to node reference.
1309  #  #
1310  #  @path = path_to_node_ref( $treenode, $noderef )  #  @path = path_to_node_ref( $treenode, $noderef )
1311    #
1312  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1313  sub path_to_node_ref {  sub path_to_node_ref
1314      my ( $node, $noderef, @path0 ) = @_;  {
1315        my ( $node, $noderef ) = @_;
1316    
1317      push @path0, $node;      return ( $node ) if ( $node eq $noderef );
     if ( $node eq $noderef ) { return @path0 }  
1318    
     my @path;  
1319      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
1320      for ( my $i = 1; $i <= $imax; $i++ ) {      for ( my $i = 1; $i <= $imax; $i++ ) {
1321         @path = path_to_node_ref( newick_desc_i( $node, $i ), $noderef, ( @path0, $i ) );          my @suf = path_to_node_ref( newick_desc_i( $node, $i ), $noderef );
1322         if ( @path ) { return @path }          return ( $node, $i, @suf ) if @suf;
1323      }      }
1324    
1325      ();  #  Not found      ();  #  Not found
# Line 1083  Line 1327 
1327    
1328    
1329  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1330  #  Path to node, as defined by 1 or 3 tips.  #  Path to node, as defined by 1, 2 or 3 node names (usually tips).
1331  #  #
1332  #  @path = path_to_node( $node,   $tip1, $tip2, $tip3   )  #  3 tip names  #  @path = path_to_node( $tree,   $name1, $name2, $name3   )  #  3 tip names
1333  #  @path = path_to_node( $node, [ $tip1, $tip2, $tip3 ] )  #  Allow array ref  #  @path = path_to_node( $tree, [ $name1, $name2, $name3 ] )  #  Allow array ref
1334  #  @path = path_to_node( $node,   $tip1                 )  #  Use path_to_tip  #  @path = path_to_node( $tree,   $name1, $name2   )          #  2 tip names
1335  #  @path = path_to_node( $node, [ $tip1 ]               )  #  Use path_to_tip  #  @path = path_to_node( $tree, [ $name1, $name2 ] )          #  Allow array ref
1336  #-------------------------------------------------------------------------------  #  @path = path_to_node( $tree,   $name1   )                  #  Path to tip or named node
1337  sub path_to_node {  #  @path = path_to_node( $tree, [ $name1 ] )                  #  Allow array ref
1338      my ( $node, $tip1, $tip2, $tip3 ) = @_;  #
1339      array_ref( $node ) && defined( $tip1 ) || return ();  #-------------------------------------------------------------------------------
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      # Allow arg 2 to be an array reference
     if ( array_ref( $tip1 ) ) { ( $tip1, $tip2, $tip3 ) = @$tip1 }  
1346    
1347      my @p1 = path_to_tip( $node, $tip1 );                #  Path to first tip      @names = @{ $names[0] }  if array_ref( $names[0] );
     @p1 || return ();                                    #  Was the tip found?  
     defined( $tip2 ) && defined( $tip3 ) || return @p1;  #  Two more defined?  
1348    
1349      my @p2 = path_to_tip( $node, $tip2 );      return () if @names < 1 || @names > 3;
     my @p3 = path_to_tip( $node, $tip3 );  
     @p2 && @p3 || return ();                             #  Were they found?  
1350    
1351      # Find the common prefix for each pair of paths      #  Just one name:
1352      my @p12 = gjolists::common_prefix( \@p1, \@p2 );  
1353      my @p13 = gjolists::common_prefix( \@p1, \@p3 );      return path_to_named_node( $tree, $names[0] ) if ( @names == 1 );
1354      my @p23 = gjolists::common_prefix( \@p2, \@p3 );  
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      # Return the longest common prefix of any two paths
1369      ( @p12 >= @p13 && @p12 >= @p23 ) ? @p12 :  
1370      ( @p13 >= @p23 )                 ? @p13 :      ( @path12 >= @path13 && @path12 >= @path23 ) ? @path12 :
1371                                         @p23 ;      ( @path13 >= @path23 )                       ? @path13 :
1372                                                       @path23 ;
1373  }  }
1374    
1375    
# Line 1121  Line 1377 
1377  #  Distance along path.  #  Distance along path.
1378  #  #
1379  #  $distance = newick_path_length( @path )  #  $distance = newick_path_length( @path )
1380    #
1381  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1382  sub newick_path_length {  sub newick_path_length
1383    {
1384      my $node = shift;      #  Discard the first node      my $node = shift;      #  Discard the first node
1385      array_ref( $node ) || return undef;      array_ref( $node ) || return undef;
1386      @_ ? distance_along_path_2( @_ ) : 0;      @_ ? distance_along_path_2( @_ ) : 0;
# Line 1133  Line 1391 
1391  #  This expects to get path minus root node:  #  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 1148  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 1159  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 ) = gjolists::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 1174  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 )
# Line 1184  Line 1448 
1448      my @p2 = path_to_node( $node, $node2 ) or return undef;      my @p2 = path_to_node( $node, $node2 ) or return undef;
1449    
1450      # Find the unique suffixes of the two paths      # Find the unique suffixes of the two paths
1451      my ( $suf1, $suf2 ) = gjolists::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 1200  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 1234  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 1258  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 1277  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 1300  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 1310  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 1327  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 1346  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 1355  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 1372  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 1394  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;
# Line 1418  Line 1686 
1686  #  Rescale all branch lenghts by factor.  #  Rescale all branch lenghts by factor.
1687  #  #
1688  #  $node = newick_rescale_branches( $node, $factor )  #  $node = newick_rescale_branches( $node, $factor )
1689    #
1690  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1691  sub newick_rescale_branches {  sub newick_rescale_branches
1692    {
1693      my ( $node, $factor ) = @_;      my ( $node, $factor ) = @_;
1694    
1695      my $x = newick_x( $node );      my $x = newick_x( $node );
# Line 1435  Line 1705 
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 1463  Line 1788 
1788  #  Remove comments from a newick tree (e.g., before writing for phylip).  #  Remove comments from a newick tree (e.g., before writing for phylip).
1789  #  #
1790  #  $node = newick_strip_comments( $node )  #  $node = newick_strip_comments( $node )
1791    #
1792  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1793  sub newick_strip_comments {  sub newick_strip_comments
1794    {
1795      my ( $node ) = @_;      my ( $node ) = @_;
1796    
1797      @$node = @$node[ 0 .. 2 ];      @$node = @$node[ 0 .. 2 ];
# Line 1477  Line 1804 
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 1496  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 1513  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 1523  Line 1856 
1856    
1857    
1858  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1859  #  Move largest groups to periphery of tree (in place).  #  Standard name for a Newick tree topology
1860  #  #
1861  #      dir  <= -2 for up-sweeping tree (big groups always first),  #    $stdname = std_tree_name( $tree )
 #            = -1 for big group first, balanced tree,  
 #            =  0 for balanced tree,  
 #            =  1 for small group first, balanced tree, and  
 #           >=  2 for down-sweeping tree (small groups always top)  
1862  #  #
 #  $tree = aesthetic_newick_tree( $treeref, $dir )  
1863  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1864  sub aesthetic_newick_tree {  sub std_tree_name
1865      my ( $tree, $dir ) = @_;  {
1866      my %cnt;      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      $dir = ! $dir       ?        0 :  #  Undefined or zero  
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).
1898    #
1899    #  $tree = aesthetic_newick_tree( $treeref, $dir )
1900    #
1901    #      dir  <= -2 for up-sweeping tree (big groups always first),
1902    #            = -1 for big group first, balanced tree,
1903    #            =  0 for balanced tree,
1904    #            =  1 for small group first, balanced tree, and
1905    #           >=  2 for down-sweeping tree (small groups always top)
1906    #
1907    #-------------------------------------------------------------------------------
1908    sub aesthetic_newick_tree
1909    {
1910        my ( $tree, $dir ) = @_;
1911        my %cnt;
1912    
1913        $dir = ! $dir       ?        0 :  #  Undefined or zero
1914               $dir <= -2 ? -1000000 :               $dir <= -2 ? -1000000 :
1915               $dir <   0 ?       -1 :               $dir <   0 ?       -1 :
1916               $dir >=  2 ?  1000000 :               $dir >=  2 ?  1000000 :
# Line 1552  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 1576  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 1613  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 1641  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 1679  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 1689  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 = gjolists::random_order( @$dl_ref );      @$dl_ref = &random_order( @$dl_ref );
2082    
2083      #  Reorder descendants:      #  Reorder descendants:
2084    
# Line 1700  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 1769  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 1780  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 1794  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 1804  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    #  Reroot a newick tree along the path between 2 nodes:
2296    #
2297    #  $tree = reroot_newick_between_nodes( $tree, $node1, $node2, $fraction )
2298    #
2299    #-------------------------------------------------------------------------------
2300    sub reroot_newick_between_nodes
2301    {
2302        my ( $tree, $node1, $node2, $fraction ) = @_;
2303        array_ref( $tree ) or return undef;
2304    
2305        #  Find the paths to the nodes:
2306    
2307        my @path1 = path_to_node( $tree, $node1 ) or return $tree;
2308        my @path2 = path_to_node( $tree, $node2 ) or return $tree;
2309    
2310        reroot_newick_between_nodes_by_path( \@path1, \@path2, $fraction )
2311    }
2312    
2313    
2314    #-------------------------------------------------------------------------------
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        #  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        reroot_newick_between_nodes_by_path( \@path1, \@path2, $fraction )
2331    }
2332    
2333    
2334    #-------------------------------------------------------------------------------
2335    #  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        my ( $path1, $path2, $fraction ) = @_;
2343        array_ref( $path1 ) && array_ref( $path2 ) or return undef;
2344    
2345        $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        my $dist1 = ( @$path1 >= 3 ) ? newick_path_length( @$path1 ) : 0;
2352        my $dist2 = ( @$path2 >= 3 ) ? newick_path_length( @$path2 ) : 0;
2353    
2354        #  Case where there is no length (possibly same node):
2355    
2356        return reroot_newick_by_path( @$prefix, $path1->[0] ) if $dist1 + $dist2 <= 0;
2357    
2358        my $dist = $fraction * ( $dist1 + $dist2 ) - $dist1;
2359        my $path = ( $dist <= 0 ) ? $path1 : $path2;
2360        $dist = abs( $dist );
2361    
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.  #  Move root of tree to an approximate midpoint.
2527  #  #
2528  #  $newtree = reroot_newick_to_approx_midpoint( $tree )  #  $newtree = reroot_newick_to_approx_midpoint( $tree )
2529    #
2530  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2531  sub reroot_newick_to_approx_midpoint {  sub reroot_newick_to_approx_midpoint
2532    {
2533      my ( $tree ) = @_;      my ( $tree ) = @_;
2534    
2535      #  Compile average tip to node distances assending      #  Compile average tip to node distances assending
2536    
2537      my $dists1 = average_to_tips_1( $tree );      my $dists1 = average_to_tips_1( $tree );
2538    
2539      #  Compile average tip to node distances descending, returning midpoint node      #  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      my $node = average_to_tips_2( $dists1, undef, undef );      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      #  Reroot      my @mids = average_to_tips_2( $dists1, undef, undef );
2570    
2571      $node ? reroot_newick_to_node_ref( $tree, $node ) : $tree      @mids ? reroot_newick_between_node_refs( $tree, @{ $mids[0] } ) : $tree;
2572  }  }
2573    
2574    
2575  sub average_to_tips_1 {  #-------------------------------------------------------------------------------
2576    #  Compile average tip to node distances assending
2577    #-------------------------------------------------------------------------------
2578    sub average_to_tips_1
2579    {
2580      my ( $node ) = @_;      my ( $node ) = @_;
2581    
2582      my @desc_dists = map { average_to_tips_1( $_ ) } newick_desc_list( $node );      my @desc_dists = map { average_to_tips_1( $_ ) } newick_desc_list( $node );
# Line 1843  Line 2586 
2586          foreach ( @desc_dists ) { $x_below += $_->[0] }          foreach ( @desc_dists ) { $x_below += $_->[0] }
2587          $x_below /= @desc_dists;          $x_below /= @desc_dists;
2588      }      }
2589    
2590      my $x = newick_x( $node ) || 0;      my $x = newick_x( $node ) || 0;
2591      my $x_net = $x_below + $x;      my $x_net = $x_below + $x;
2592    
# Line 1850  Line 2594 
2594  }  }
2595    
2596    
2597  sub average_to_tips_2 {  #-------------------------------------------------------------------------------
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 ) = @_;      my ( $dists1, $x_above, $anc_node ) = @_;
2604      my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;      my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;
2605    
2606      #  Are we done?  Root is in this node's branch, or "above"?      #  Are we done?  Root is in this node's branch, or "above"?
2607    
2608      # 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";  
   
2609      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )
2610      {      {
2611          #  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 1872  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 1890  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 1904  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 {  sub reroot_newick_to_approx_midpoint_w
2652    {
2653      my ( $tree ) = @_;      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_midpoint_w
2679    {
2680        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 1914  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 1939  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 1946  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 1964  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 1992  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 2006  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 2023  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 2071  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 2110  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 2148  Line 2926 
2926  #  Add a subtree to a newick tree node:  #  Add a subtree to a newick tree node:
2927  #  #
2928  #  $node = newick_insert_at_node( $node, $subtree )  #  $node = newick_insert_at_node( $node, $subtree )
2929    #
2930  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2931  sub newick_insert_at_node  sub newick_insert_at_node
2932  {  {
# Line 2173  Line 2952 
2952  #  Insert a subtree into a newick tree along the path between 2 nodes:  #  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 )  #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )
2955    #
2956  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2957  sub newick_insert_between_nodes  sub newick_insert_between_nodes
2958  {  {
# Line 2241  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 2259  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 2299  Line 3083 
3083          $tr = $sis;                              #    sister is new root          $tr = $sis;                              #    sister is new root
3084      }      }
3085    
3086      elsif ( $nd1 == 3 ) {                        # Tip joins trifurcating root:      elsif ( $nd1 == 3 ) {                        # Tip joins trifurcating root:
3087          splice( @{ $anc1->[0] }, $i1-1, 1 );     #    delete the descendant, and          splice( @{ $anc1->[0] }, $i1-1, 1 );     #    delete the descendant, and
3088          $tr = uproot_newick( $tr );              #    fix the rooting          $tr = uproot_newick( $tr );              #    fix the rooting
3089        }
3090    
3091        else {
3092            return undef;
3093        }
3094    
3095        return $tr;
3096    }
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:
3124    #
3125    #     Except for (some) tip nodes, the tree produced is a copy.
3126    #     There is no check that requested tips exist.
3127    #
3128    #  $newtree = newick_subtree( $tree,  @tips )
3129    #  $newtree = newick_subtree( $tree, \@tips )
3130    #
3131    #-------------------------------------------------------------------------------
3132    sub newick_subtree
3133    {
3134        my ( $tr, @tips ) = @_;
3135        if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }
3136    
3137        if ( @tips < 2 ) { return undef }
3138        my $was_rooted = newick_is_rooted( $tr );
3139        my $keephash = { map { ( $_, 1 ) } @tips };
3140        my $tr2 = subtree1( $tr, $keephash );
3141        $tr2 = uproot_newick( $tr2 ) if ! $was_rooted && newick_is_rooted( $tr2 );
3142        $tr2->[2] = undef if $tr2;                   # undef root branch length
3143        $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      else {      foreach my $tip ( @tips )
3497          return undef;      {
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 $tr;      return $tree;
3507  }  }
3508    
3509    
3510  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
 #  Produce a subtree with the desired tips:  
3511  #  #
3512  #     Except for (some) tip nodes, the tree produced is a copy.  #   $tree = random_ultrametric_tree(  @tips, \%options )
3513  #     There is no check that requested tips exist.  #   $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  #  #
 #  $newtree = newick_subtree( $tree,  @tips )  
 #  $newtree = newick_subtree( $tree, \@tips )  
3521  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3522  sub newick_subtree {  sub random_ultrametric_tree
3523      my ( $tr, @tips ) = @_;  {
3524      if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }      my $opts = $_[ 0] && ref $_[ 0] eq 'HASH' ? shift
3525                 : $_[-1] && ref $_[-1] eq 'HASH' ? pop
3526                 :                                  {};
3527        return undef if ! defined $_[0];
3528    
3529      if ( @tips < 2 ) { return undef }      my @tips = ref $_[0] ? @{ $_[0] } : @_;
3530      my $was_rooted = newick_is_rooted( $tr );      return undef if @tips < 2;
     my $keephash = { map { ( $_, 1 ) } @tips };  
     my $tr2 = subtree1( $tr, $keephash );  
     $tr2 = uproot_newick( $tr2 ) if ! $was_rooted && newick_is_rooted( $tr2 );  
     $tr2->[2] = undef if $tr2;                   # undef root branch length  
     $tr2;  
 }  
3531    
3532        my $d2tip = $opts->{ depth } ||= 1;
3533    
3534  sub subtree1 {      #  Random tip addition order (for rooted tree it matters):
     my ( $tr, $keep ) = @_;  
     my @desc1 = newick_desc_list( $tr );  
3535    
3536      #  Is this a tip, and is it in the keep list?      @tips = sort { rand() <=> 0.5 } @tips;
3537        my $tree = [ [ ], undef, 0 ];
3538    
3539      if ( @desc1 < 1 ) {      my $subtree_size = { $tree => 0 };  # total branch length of each subtree
3540          return ( $keep->{ newick_lbl( $tr ) } ) ? $tr : undef;  
3541        #  We start with root bifurcation:
3542    
3543        foreach my $tip ( splice( @tips, 0, 2 ) )
3544        {
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    #
3629  #  writeNewickTree( $tree )  #  writeNewickTree( $tree )
3630  #  writeNewickTree( $tree, $file )  #  writeNewickTree( $tree, $file )
3631  #  writeNewickTree( $tree, \*FH )  #  writeNewickTree( $tree, \*FH )
3632    #
3633  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
3634  sub writeNewickTree {  sub writeNewickTree
3635    {
3636      my ( $tree, $file ) = @_;      my ( $tree, $file ) = @_;
3637      my ( $fh, $close ) = open_output( $file );      my ( $fh, $close ) = open_output( $file );
3638      $fh or return;      $fh or return;
# Line 2413  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 2422  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 2440  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 2460  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 2470  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 2488  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 2498  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 2515  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 2535  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 2543  Line 3789 
3789    
3790    
3791  #===============================================================================  #===============================================================================
3792    #
3793  #  $tree  = read_newick_tree( $file )  # reads to a semicolon  #  $tree  = read_newick_tree( $file )  # reads to a semicolon
3794  #  @trees = read_newick_trees( $file ) # reads to end of file  #  @trees = read_newick_trees( $file ) # reads to end of file
3795    #
3796  #===============================================================================  #===============================================================================
3797    
3798  sub read_newick_tree  sub read_newick_tree
# Line 2553  Line 3801 
3801      my ( $fh, $close ) = open_input( $file );      my ( $fh, $close ) = open_input( $file );
3802      my $tree;      my $tree;
3803      my @lines = ();      my @lines = ();
3804      while ( defined( $_ = <$fh> ) )      foreach ( <$fh> )
3805      {      {
3806          chomp;          chomp;
3807          push @lines, $_;          push @lines, $_;
# Line 2575  Line 3823 
3823      my ( $fh, $close ) = open_input( $file );      my ( $fh, $close ) = open_input( $file );
3824      my @trees = ();      my @trees = ();
3825      my @lines = ();      my @lines = ();
3826      while ( defined( $_ = <$fh> ) )      foreach ( <$fh> )
3827      {      {
3828          chomp;          chomp;
3829          push @lines, $_;          push @lines, $_;
# Line 2595  Line 3843 
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 2608  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 2662  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 2697  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 2751  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 2762  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 2792  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    #     $min_dx # the minimum horizontal branch length (D = 2)
4071    #     $dy     # the vertical space per taxon (D = 1, most compressed)
4072    #
4073    #  Options:
4074    #
4075    #    dy     => nat_number    # the vertical space per taxon
4076    #    chars  => key           # line drawing character set:
4077    #                            #     html_unicode
4078    #                            #     text (default)
4079    #    min_dx => whole_number  # the minimum horizontal branch length
4080    #    width  => whole_number  # approximate tree width without labels
4081  #  #
 #  printer_plot_newick( $node, $file (D=\*STDOUT), $width (D=68), $min_dx (D=2), $dy (D=1) )  
4082  #===============================================================================  #===============================================================================
4083  sub printer_plot_newick {  sub printer_plot_newick
4084      my ( $node, $file, $width, $min_dx, $dy ) = @_;  {
4085        my ( $node, $file, @opts ) = @_;
4086    
4087      my ( $fh, $close ) = open_output( $file );      my ( $fh, $close ) = open_output( $file );
4088      $fh or return;      $fh or return;
4089    
4090      print $fh join( "\n", text_plot_newick( $node, $width, $min_dx, $dy ) ), "\n";      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    
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 2835  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\n";
4342    
4343      my $dx = newick_x( $node );      my $dx = newick_x( $node );
4344      if ( defined( $dx ) ) {      if ( defined( $dx ) ) {
4345          $dx *= $x_scale;          $dx *= $x_scale;
4346          $dx >= $min_dx or $dx = $min_dx;          $dx = $min_dx if $dx < $min_dx;
4347      }      }
4348      else {      else {
4349          $dx = ( $x0 > 0 ) ? $min_dx : 0;          $dx = ( $x0 > 0 ) ? $min_dx : 0;
# Line 2881  Line 4370 
4370          $ymax = $y0;          $ymax = $y0;
4371    
4372          foreach ( @dl ) {          foreach ( @dl ) {
4373              ( $xmaxi, $ymax, $yi ) = layout_printer_plot( $_, $hash, $x, $ymax, $x_scale, $min_dx, $dy );              ( $xmaxi, $ymax, $yi ) = layout_printer_plot( $_, $hash, $x, $ymax, $x_scale, $min_dx, $dy,
4374                                                              ( 2*@ylist < @dl ? 0.5001 : 0.4999 )
4375                                                            );
4376              push @ylist, $yi;              push @ylist, $yi;
4377              if ( $xmaxi > $xmax ) { $xmax = $xmaxi }              if ( $xmaxi > $xmax ) { $xmax = $xmaxi }
4378          }          }
# Line 2891  Line 4382 
4382    
4383          $yn1 = $ylist[ 0];          $yn1 = $ylist[ 0];
4384          $yn2 = $ylist[-1];          $yn2 = $ylist[-1];
4385          $y = int( 0.5 * ( $yn1 + $yn2 ) + 0.4999 );          $y   = int( 0.5 * ( $yn1 + $yn2 ) + ( $yrnd || 0.4999 ) );
4386    
4387            #  Handle special case of internal node label. Put it between subtrees.
4388    
4389            if ( ( $dy >= 2 ) && node_has_lbl( $node ) && ( @dl > 1 ) ) {
4390                #  Find the descendents $i1 and $i2 to put the branch between
4391                my $i2 = 1;
4392                while ( ( $i2+1 < @ylist ) && ( $ylist[$i2] < $y ) ) { $i2++ }
4393                my $i1 = $i2 - 1;
4394                #  Get bottom of subtree1 and top of subtree2:
4395                my $ymax1 = $hash->{ $dl[ $i1 ] }->[ 1 ];
4396                my $ymin2 = $hash->{ $dl[ $i2 ] }->[ 0 ];
4397                #  Midway between bottom of subtree1 and top of subtree2, with
4398                #  preferred rounding direction
4399                $y = int( 0.5 * ( $ymax1 + $ymin2 ) + ( $yrnd || 0.4999 ) );
4400            }
4401      }      }
4402    
4403      $y2 = int( $ymax - 0.5 * $dy + 0.4999 );      $y2 = int( $ymax - 0.5 * $dy + 0.4999 );
# Line 2901  Line 4407 
4407  }  }
4408    
4409    
4410  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #  What symbol do we get if we add a leftward line to some other symbol?
 #  Debug routine  
 #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
 sub dump_tree {  
     my ( $node, $prefix ) = @_;  
     defined( $prefix ) or $prefix = "";  
     print STDERR $prefix, join(", ", @$node), "\n";  
     my @dl = $node->[0] ? @{$node->[0]} : ();  
     foreach ( @dl ) { dump_tree( $_, $prefix . "  " ) }  
     $prefix or print STDERR "\n";  
 }  
   
   
 #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
 #  Debug routine  
 #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  
 sub dump_tree_hash {  
     my ( $node, $hash, $prefix ) = @_;  
     defined( $prefix ) or print STDERR "node; [ y1, y2, x0, x, y, yn1, yn2 ]\n" and $prefix = "";  
     print STDERR $prefix, join(", ", @$node), "; ", join(", ", @{ $hash->{ $node } } ), "\n";  
     my @dl = $node->[0] ? @{$node->[0]} : ();  
     foreach (@dl) { dump_tree_hash( $_, $hash, $prefix . "  " ) }  
 }  
4411    
4412    my %with_left_line = ( space  => 'half_l',
4413                           horiz  => 'horiz',
4414                           vert   => 'tee_l',
4415                           el_d_r => 'tee_d',
4416                           el_u_r => 'tee_u',
4417                           el_d_l => 'el_d_l',
4418                           el_u_l => 'el_u_l',
4419                           tee_l  => 'tee_l',
4420                           tee_r  => 'cross',
4421                           tee_u  => 'tee_u',
4422                           tee_d  => 'tee_d',
4423                           half_l => 'half_l',
4424                           half_r => 'horiz',
4425                           half_u => 'el_u_l',
4426                           half_d => 'el_d_l',
4427                           cross  => 'cross',
4428                         );
4429    
4430  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4431  #  $line = text_tree_row( $node, $hash, $row, $line, $symb )  #  Produce a description of one line of a printer plot tree.
4432    #
4433    #  \@line = text_tree_row( $node, $hash, $row, \@line, $symb, $ilbl )
4434    #
4435    #     \@line is the character descriptions accumulated so far, one per array
4436    #          element, except for a label, which can be any number of characters.
4437    #          Labels are followed by an empty string, so if $line->[-1] eq '',
4438    #          then $line->[-2] is a label. The calling program translates the
4439    #          symbol names to output characters.
4440    #
4441    #     \@node is a newick tree node
4442    #     \%hash contains tree layout information
4443    #      $row  is the row number (y value) that we are building
4444    #      $symb is the plot symbol proposed for the current x and y position
4445    #      $ilbl is true if internal node labels are allowed
4446    #
4447  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4448  sub text_tree_row {  sub text_tree_row
4449      my ( $node, $hash, $row, $line, $symb ) = @_;  {
4450        my ( $node, $hash, $row, $line, $symb, $ilbl ) = @_;
4451    
4452      my ( $y1, $y2, $x0, $x, $y, $yn1, $yn2 ) = @{ $hash->{ $node } };      my ( $y1, $y2, $x0, $x, $y, $yn1, $yn2 ) = @{ $hash->{ $node } };
4453      if ( $row < $y1 || $row > $y2 ) { return $line }      if ( $row < $y1 || $row > $y2 ) { return $line }
4454    
4455      if ( length( $line ) < $x0 ) { $line .= " " x ( $x0 - length( $line ) ) }      if ( @$line < $x0 ) { push @$line, ('space') x ( $x0 - @$line ) }
4456    
4457      if ( $row == $y ) {      if ( $row == $y ) {
4458          $line = substr( $line, 0, $x0 ) . $symb . (( $x > $x0 ) ? "-" x ($x - $x0) : "");          while ( @$line > $x0 ) { pop @$line }  # Actually 0-1 times
4459            push @$line, $symb,
4460                         ( ( $x > $x0 ) ? ('horiz') x ($x - $x0) : () );
4461      }      }
4462    
4463      elsif ( $row > $yn1 && $row < $yn2 ) {      elsif ( $row > $yn1 && $row < $yn2 ) {
4464          if ( length( $line ) < $x ) { $line .= " " x ( $x - length( $line ) ) . "|" }          if ( @$line < $x ) { push @$line, ('space') x ( $x - @$line ), 'vert' }
4465          else { substr( $line, $x ) = "|" }          else               { $line->[$x] = 'vert' }
4466      }      }
4467    
4468      my @dl = newick_desc_list( $node );      my @dl = newick_desc_list( $node );
4469    
4470      if ( @dl < 1 ) {      if ( @dl < 1 ) {
4471          $line .= " " . $node->[1];          push @$line, ( node_has_lbl( $node ) ? newick_lbl( $node ) : '' ), '';
4472      }      }
4473    
4474      else {      else {
4475          my @list = map { [ $_, "+" ] } @dl;  #  Print symbol for line          my @list = map { [ $_, 'tee_r' ] } @dl;  # Line to the right
4476          $list[ 0]->[1] = "/";          if ( @list > 1 ) { #  Fix top and bottom sympbols
4477          $list[-1]->[1] = "\\";              $list[ 0]->[1] = 'el_d_r';
4478                $list[-1]->[1] = 'el_u_r';
4479            }
4480            elsif ( @list ) {  # Only one descendent
4481                $list[ 0]->[1] = 'half_r';
4482            }
4483          foreach ( @list ) {          foreach ( @list ) {
4484              my ( $n, $s ) = @$_;              my ( $n, $s ) = @$_;
4485              if ( $row >= $hash->{ $n }->[0] && $row <= $hash->{ $n }->[1] ) {              if ( $row >= $hash->{ $n }->[0] && $row <= $hash->{ $n }->[1] ) {
4486                  $line = text_tree_row( $n, $hash, $row, $line, $s );                  $line = text_tree_row( $n, $hash, $row, $line, $s, $ilbl );
4487              }              }
4488           }           }
4489    
4490          if ( $row == $y ) { substr( $line, $x, 1 ) = "+" }          if ( $row == $y ) {
4491                $line->[$x] = ( $line->[$x] eq 'horiz' ) ? 'tee_l'
4492                                                         : $with_left_line{ $line->[$x] };
4493                push @$line, newick_lbl( $node), '' if $ilbl && node_has_lbl( $node );
4494            }
4495      }      }
4496    
4497      return $line;      return $line;
4498  }  }
4499    
4500    
4501    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4502    #  Debug routine
4503    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4504    sub dump_tree
4505    {
4506        my ( $node, $prefix ) = @_;
4507        defined( $prefix ) or $prefix = "";
4508        print STDERR $prefix, join(", ", @$node), "\n";
4509        my @dl = $node->[0] ? @{$node->[0]} : ();
4510        foreach ( @dl ) { dump_tree( $_, $prefix . "  " ) }
4511        $prefix or print STDERR "\n";
4512    }
4513    
4514    
4515    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4516    #  Debug routine
4517    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
4518    sub dump_tree_hash
4519    {
4520        my ( $node, $hash, $prefix ) = @_;
4521        defined( $prefix ) or print STDERR "node; [ y1, y2, x0, x, y, yn1, yn2 ]\n" and $prefix = "";
4522        print STDERR $prefix, join(", ", @$node), "; ", join(", ", @{ $hash->{ $node } } ), "\n";
4523        my @dl = $node->[0] ? @{$node->[0]} : ();
4524        foreach (@dl) { dump_tree_hash( $_, $hash, $prefix . "  " ) }
4525    }
4526    
4527    
4528  #===============================================================================  #===============================================================================
4529  #  Open an input file stream:  #  Open an input file stream:
4530  #  #
# Line 2983  Line 4537 
4537  {  {
4538      my $file = shift;      my $file = shift;
4539      my $fh;      my $fh;
4540      if    ( ! defined( $file ) )     { return ( \*STDIN ) }      if    ( ! defined $file || $file eq '' ) { return ( \*STDIN ) }
4541      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file   ) }      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file   ) }
4542      elsif ( open( $fh, "<$file" ) )  { return ( $fh, 1  ) } # Need to close      elsif ( open( $fh, "<$file" ) )  { return ( $fh, 1  ) } # Need to close
4543    
# Line 3004  Line 4558 
4558  {  {
4559      my $file = shift;      my $file = shift;
4560      my $fh;      my $fh;
4561      if    ( ! defined( $file ) )     { return ( \*STDOUT ) }      if    ( ! defined $file || $file eq '' ) { return ( \*STDOUT ) }
4562      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file    ) }      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file    ) }
4563      elsif ( ( open $fh, ">$file" ) ) { return ( $fh, 1   ) } # Need to close      elsif ( ( open $fh, ">$file" ) ) { return ( $fh, 1   ) } # Need to close
4564    
# Line 3012  Line 4566 
4566      return undef;      return undef;
4567  }  }
4568    
4569    
4570    #===============================================================================
4571    #  Some subroutines copied from gjolists
4572    #===============================================================================
4573    #  Return the common prefix of two lists:
4574    #
4575    #  @common = common_prefix( \@list1, \@list2 )
4576    #
4577    #-----------------------------------------------------------------------------
4578    sub common_prefix
4579    {
4580        my ($l1, $l2) = @_;
4581        ref($l1) eq "ARRAY" || die "common_prefix: arg 1 is not an array ref\n";
4582        ref($l2) eq "ARRAY" || die "common_prefix: arg 2 is not an array ref\n";
4583    
4584        my $i = 0;
4585        my $l1_i;
4586        while ( defined( $l1_i = $l1->[$i] ) && $l1_i eq $l2->[$i] ) { $i++ }
4587    
4588        return @$l1[ 0 .. ($i-1) ];  # perl handles negative range
4589    }
4590    
4591    
4592    #-----------------------------------------------------------------------------
4593    #  Return the unique suffixes of each of two lists:
4594    #
4595    #  ( \@suffix1, \@suffix2 ) = unique_suffixes( \@list1, \@list2 )
4596    #
4597    #-----------------------------------------------------------------------------
4598    sub unique_suffixes
4599    {
4600        my ($l1, $l2) = @_;
4601        ref($l1) eq "ARRAY" || die "common_prefix: arg 1 is not an array ref\n";
4602        ref($l2) eq "ARRAY" || die "common_prefix: arg 2 is not an array ref\n";
4603    
4604        my $i = 0;
4605        my @l1 = @$l1;
4606        my @l2 = @$l2;
4607        my $l1_i;
4608        while ( defined( $l1_i = $l1[$i] ) && $l1_i eq $l2[$i] ) { $i++ }
4609    
4610        splice @l1, 0, $i;
4611        splice @l2, 0, $i;
4612        return ( \@l1, \@l2 );
4613    }
4614    
4615    
4616    #-------------------------------------------------------------------------------
4617    #  List of values duplicated in a list (stable in order by second occurance):
4618    #
4619    #  @dups = duplicates( @list )
4620    #
4621    #-------------------------------------------------------------------------------
4622    sub duplicates
4623    {
4624        my %cnt = ();
4625        grep { ++$cnt{$_} == 2 } @_;
4626    }
4627    
4628    
4629    #-------------------------------------------------------------------------------
4630    #  Randomize the order of a list:
4631    #
4632    #  @random = random_order( @list )
4633    #
4634    #-------------------------------------------------------------------------------
4635    sub random_order
4636    {
4637        my ( $i, $j );
4638        for ( $i = @_ - 1; $i > 0; $i-- )
4639        {
4640            $j = int( ($i+1) * rand() );
4641            ( $_[$i], $_[$j] ) = ( $_[$j], $_[$i] ); # Interchange i and j
4642        }
4643    
4644       @_;
4645    }
4646    
4647    
4648    #-----------------------------------------------------------------------------
4649    #  Intersection of two or more sets:
4650    #
4651    #  @intersection = intersection( \@set1, \@set2, ... )
4652    #
4653    #-----------------------------------------------------------------------------
4654    sub intersection
4655    {
4656        my $set = shift;
4657        my @intersection = @$set;
4658    
4659        foreach $set ( @_ )
4660        {
4661            my %set = map { $_ => 1 } @$set;
4662            @intersection = grep { exists $set{ $_ } } @intersection;
4663        }
4664    
4665        @intersection;
4666    }
4667    
4668    
4669    #-----------------------------------------------------------------------------
4670    #  Elements in set 1, but not set 2:
4671    #
4672    #  @difference = set_difference( \@set1, \@set2 )
4673    #
4674    #-----------------------------------------------------------------------------
4675    sub set_difference
4676    {
4677        my ($set1, $set2) = @_;
4678        my %set2 = map { $_ => 1 } @$set2;
4679        grep { ! ( exists $set2{$_} ) } @$set1;
4680    }
4681    
4682    
4683  1;  1;

Legend:
Removed from v.1.8  
changed lines
  Added in v.1.24

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3