[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.21, Sat Aug 21 17:12:51 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 77  Line 79 
79  #  Tree format interconversion:  #  Tree format interconversion:
80  #===============================================================================  #===============================================================================
81  #  #
82    #  $bool      = is_overbeek_tree( $tree )
83    #  $bool      = is_gjonewick_tree( $tree )
84    #
85  #  $gjonewick = overbeek_to_gjonewick( $overbeek )  #  $gjonewick = overbeek_to_gjonewick( $overbeek )
86  #  $overbeek  = gjonewick_to_overbeek( $gjonewick )  #  $overbeek  = gjonewick_to_overbeek( $gjonewick )
87  #  #
# Line 107  Line 112 
112  #  set_newick_c4( $noderef, $listref )  #  set_newick_c4( $noderef, $listref )
113  #  set_newick_c5( $noderef, $listref )  #  set_newick_c5( $noderef, $listref )
114  #  set_newick_desc_list( $noderef, @desclist )  #  set_newick_desc_list( $noderef, @desclist )
115  #  set_newick_desc_i( $noderef1, $i, $noderef2 )  #  set_newick_desc_i( $noderef1, $i, $noderef2 )  # 1-based numbering
116  #  #
117  #  $bool    = newick_is_valid( $noderef )       # verify that tree is valid  #  $bool    = newick_is_valid( $noderef )       # verify that tree is valid
118  #  #
# Line 118  Line 123 
123  #  #
124  #  $n       = newick_tip_count( $noderef )  #  $n       = newick_tip_count( $noderef )
125  #  @tiprefs = newick_tip_ref_list( $noderef )  #  @tiprefs = newick_tip_ref_list( $noderef )
126    # \@tiprefs = newick_tip_ref_list( $noderef )
127  #  @tips    = newick_tip_list( $noderef )  #  @tips    = newick_tip_list( $noderef )
128    # \@tips    = newick_tip_list( $noderef )
129    #
130  #  $tipref  = newick_first_tip_ref( $noderef )  #  $tipref  = newick_first_tip_ref( $noderef )
131  #  $tip     = newick_first_tip( $noderef )  #  $tip     = newick_first_tip( $noderef )
132    #
133  #  @tips    = newick_duplicated_tips( $noderef )  #  @tips    = newick_duplicated_tips( $noderef )
134    # \@tips    = newick_duplicated_tips( $noderef )
135    #
136  #  $bool    = newick_tip_in_tree( $noderef, $tipname )  #  $bool    = newick_tip_in_tree( $noderef, $tipname )
137    #
138  #  @tips    = newick_shared_tips( $tree1, $tree2 )  #  @tips    = newick_shared_tips( $tree1, $tree2 )
139    # \@tips    = newick_shared_tips( $tree1, $tree2 )
140  #  #
141  #  $length  = newick_tree_length( $noderef )  #  $length  = newick_tree_length( $noderef )
142    #
143    #  %tip_distances = newick_tip_distances( $noderef )
144    # \%tip_distances = newick_tip_distances( $noderef )
145    #
146  #  $xmax    = newick_max_X( $noderef )  #  $xmax    = newick_max_X( $noderef )
147  #  ( $tipref,  $xmax ) = newick_most_distant_tip_ref( $noderef )  #  ( $tipref,  $xmax ) = newick_most_distant_tip_ref( $noderef )
148  #  ( $tipname, $xmax ) = newick_most_distant_tip( $noderef )  #  ( $tipname, $xmax ) = newick_most_distant_tip_name( $noderef )
149    #
150    #  Provide a standard name by which two trees can be compared for same topology
151    #
152    #  $stdname = std_tree_name( $tree )
153  #  #
154  #  Tree tip insertion point (tip is on branch of length x that  #  Tree tip insertion point (tip is on branch of length x that
155  #  is inserted into branch connecting node1 and node2, a distance  #  is inserted into branch connecting node1 and node2, a distance
156  #  x1 from node1 and x2 from node2):  #  x1 from node1 and x2 from node2):
157  #  #
158  #  [ $node1, $x1, $node2, $x2, $x ]  #  [ $node1, $x1, $node2, $x2, $x ] = newick_tip_insertion_point( $tree, $tip )
 #           = newick_tip_insertion_point( $tree, $tip )  
159  #  #
160  #  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
161  #  tips (sort is lower case):  #  tips (sort is lower case):
162  #  #
163  #  @TipOrTips = std_node_name( $Tree, $Node )  #  @TipOrTips = std_node_name( $tree, $node )
164  #  #
165  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
166  #  Paths from root of tree:  #  Paths from root of tree:
# Line 189  Line 209 
209  #  $n_changed = newick_set_all_branches( $node, $x )  #  $n_changed = newick_set_all_branches( $node, $x )
210  #  $n_changed = newick_fix_negative_branches( $tree )  #  $n_changed = newick_fix_negative_branches( $tree )
211  #  $node      = newick_rescale_branches( $node, $factor )  #  $node      = newick_rescale_branches( $node, $factor )
212    #  $node      = newick_modify_branches( $node, \&function )
213    #  $node      = newick_modify_branches( $node, \&function, \@func_parms )
214  #  #
215  #  Modify comments:  #  Modify comments:
216  #  #
# Line 206  Line 228 
228  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )
229  #  $newtree = reroot_newick_to_node( $tree, @node )  #  $newtree = reroot_newick_to_node( $tree, @node )
230  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )
231  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )  #  $newtree = reroot_newick_between_nodes( $tree, $node1, $node2, $fraction )
232    #  $newtree = reroot_newick_to_midpoint( $tree )           # unweighted
233    #  $newtree = reroot_newick_to_midpoint_w( $tree )         # weight by tips
234  #  $newtree = reroot_newick_to_approx_midpoint( $tree )    # unweighted  #  $newtree = reroot_newick_to_approx_midpoint( $tree )    # unweighted
235  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  # weight by tips  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  # weight by tips
236  #  $newtree = uproot_tip_rooted_newick( $tree )  #  $newtree = uproot_tip_rooted_newick( $tree )
237  #  $newtree = uproot_newick( $tree )  #  $newtree = uproot_newick( $tree )
238  #  #
239  #  $newtree = prune_from_newick( $tree, $tip )  #  $newtree = prune_from_newick( $tree, $tip )
240    #  $newtree = rooted_newick_subtree( $tree,  @tips )
241    #  $newtree = rooted_newick_subtree( $tree, \@tips )
242  #  $newtree = newick_subtree( $tree,  @tips )  #  $newtree = newick_subtree( $tree,  @tips )
243  #  $newtree = newick_subtree( $tree, \@tips )  #  $newtree = newick_subtree( $tree, \@tips )
244    #  $newtree = newick_covering_subtree( $tree,  @tips )
245    #  $newtree = newick_covering_subtree( $tree, \@tips )
246  #  #
247  #  $newtree = collapse_zero_length_branches( $tree )  #  $newtree = collapse_zero_length_branches( $tree )
248  #  #
# Line 222  Line 250 
250  #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )  #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )
251  #  #
252  #===============================================================================  #===============================================================================
253    #  Tree neighborhood: subtree of n tips to represent a larger tree.
254    #===============================================================================
255    #
256    #  Focus around root:
257    #
258    #  $subtree = root_neighborhood_representative_tree( $tree, $n, \%tip_priority )
259    #  $subtree = root_neighborhood_representative_tree( $tree, $n )
260    #  @tips    = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
261    #  @tips    = root_neighborhood_representative_tips( $tree, $n )
262    # \@tips    = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
263    # \@tips    = root_neighborhood_representative_tips( $tree, $n )
264    #
265    #  Focus around a tip insertion point (the tip is not in the subtree):
266    #
267    #  $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n, \%tip_priority )
268    #  $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n )
269    #  @tips    = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
270    #  @tips    = tip_neighborhood_representative_tips( $tree, $tip, $n )
271    # \@tips    = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
272    # \@tips    = tip_neighborhood_representative_tips( $tree, $tip, $n )
273    #
274    #===============================================================================
275  #  Tree reading and writing:  #  Tree reading and writing:
276  #===============================================================================  #===============================================================================
277    #  Write machine-readable trees:
278  #  #
279  #   writeNewickTree( $tree )  #   writeNewickTree( $tree )
280  #   writeNewickTree( $tree, $file )  #   writeNewickTree( $tree, $file )
# Line 231  Line 282 
282  #  fwriteNewickTree( $file, $tree )  # Matches the C arg list for f... I/O  #  fwriteNewickTree( $file, $tree )  # Matches the C arg list for f... I/O
283  #  $treestring = swriteNewickTree( $tree )  #  $treestring = swriteNewickTree( $tree )
284  #  $treestring = formatNewickTree( $tree )  #  $treestring = formatNewickTree( $tree )
285    #
286    #  Write human-readable trees:
287    #
288  #  @textlines  = text_plot_newick( $node, $width, $min_dx, $dy )  #  @textlines  = text_plot_newick( $node, $width, $min_dx, $dy )
289  #   printer_plot_newick( $node, $file, $width, $min_dx, $dy )  #   printer_plot_newick( $node, $file, $width, $min_dx, $dy )
290  #  #
291    #  Read trees:
292    #
293  #  $tree  = read_newick_tree( $file )  # reads to a semicolon  #  $tree  = read_newick_tree( $file )  # reads to a semicolon
294  #  @trees = read_newick_trees( $file ) # reads to end of file  #  @trees = read_newick_trees( $file ) # reads to end of file
295  #  $tree  = parse_newick_tree_str( $string )  #  $tree  = parse_newick_tree_str( $string )
# Line 243  Line 299 
299    
300  use Carp;  use Carp;
301  use Data::Dumper;  use Data::Dumper;
302    use strict;
303    
304  require Exporter;  require Exporter;
305    
306  our @ISA = qw(Exporter);  our @ISA = qw(Exporter);
307  our @EXPORT = qw(  our @EXPORT = qw(
308            is_overbeek_tree
309            is_gjonewick_tree
310          overbeek_to_gjonewick          overbeek_to_gjonewick
311          gjonewick_to_overbeek          gjonewick_to_overbeek
   
312          newick_is_valid          newick_is_valid
313          newick_is_rooted          newick_is_rooted
314          newick_is_unrooted          newick_is_unrooted
315          tree_rooted_on_tip          tree_rooted_on_tip
316          newick_is_bifurcating          newick_is_bifurcating
317          newick_tip_count          newick_tip_count
318            newick_tip_ref_list
319          newick_tip_list          newick_tip_list
320    
321          newick_first_tip          newick_first_tip
322          newick_duplicated_tips          newick_duplicated_tips
323          newick_tip_in_tree          newick_tip_in_tree
324          newick_shared_tips          newick_shared_tips
325    
326          newick_tree_length          newick_tree_length
327            newick_tip_distances
328          newick_max_X          newick_max_X
329          newick_most_distant_tip_ref          newick_most_distant_tip_ref
330          newick_most_distant_tip_name          newick_most_distant_tip_name
331    
332          std_newick_name          newick_tip_insertion_point
333    
334            std_tree_name
335    
336          path_to_tip          path_to_tip
337          path_to_named_node          path_to_named_node
# Line 290  Line 353 
353          newick_set_all_branches          newick_set_all_branches
354          newick_fix_negative_branches          newick_fix_negative_branches
355          newick_rescale_branches          newick_rescale_branches
356            newick_modify_branches
357    
358          newick_strip_comments          newick_strip_comments
359    
# Line 305  Line 369 
369          reroot_newick_next_to_tip          reroot_newick_next_to_tip
370          reroot_newick_to_node          reroot_newick_to_node
371          reroot_newick_to_node_ref          reroot_newick_to_node_ref
372            reroot_newick_between_nodes
373            reroot_newick_to_midpoint
374            reroot_newick_to_midpoint_w
375          reroot_newick_to_approx_midpoint          reroot_newick_to_approx_midpoint
376          reroot_newick_to_approx_midpoint_w          reroot_newick_to_approx_midpoint_w
377          uproot_tip_rooted_newick          uproot_tip_rooted_newick
378          uproot_newick          uproot_newick
379    
380          prune_from_newick          prune_from_newick
381            rooted_newick_subtree
382          newick_subtree          newick_subtree
383            newick_covering_subtree
384          collapse_zero_length_branches          collapse_zero_length_branches
385    
386          newick_insert_at_node          newick_insert_at_node
387          newick_insert_between_nodes          newick_insert_between_nodes
388    
389            root_neighborhood_representative_tree
390            root_neighborhood_representative_tips
391            tip_neighborhood_representative_tree
392            tip_neighborhood_representative_tips
393    
394          writeNewickTree          writeNewickTree
395          fwriteNewickTree          fwriteNewickTree
396          strNewickTree          strNewickTree
# Line 362  Line 436 
436          );          );
437    
438    
 use gjolists qw(  
         common_prefix  
         unique_suffixes  
   
         duplicates  
         random_order  
   
         intersection  
         set_difference  
         );  
   
   
 use strict;  
   
   
439  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
440  #  Internally used definitions  #  Internally used definitions
441  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
442    
443  sub array_ref { ref( $_[0] ) eq "ARRAY" }  sub array_ref { $_[0] && ref( $_[0] ) eq 'ARRAY' }
444  sub hash_ref  { ref( $_[0] ) eq "HASH"  }  sub hash_ref  { $_[0] && ref( $_[0] ) eq 'HASH'  }
445    
446    
447  #===============================================================================  #===============================================================================
448  #  Interconvert Overbeek and gjonewick trees:  #  Interconvert overbeek and gjonewick trees:
449  #===============================================================================  #===============================================================================
450    
451    sub is_overbeek_tree { array_ref( $_[0] ) && array_ref( $_[0]->[2] ) }
452    
453    sub is_gjonewick_tree { array_ref( $_[0] ) && array_ref( $_[0]->[0] ) }
454    
455  sub overbeek_to_gjonewick  sub overbeek_to_gjonewick
456  {  {
457      return () unless ref( $_[0] ) eq 'ARRAY';      return () unless ref( $_[0] ) eq 'ARRAY';
# Line 408  Line 471 
471      return $node;      return $node;
472  }  }
473    
474    
475  #===============================================================================  #===============================================================================
476  #  Extract tree structure values:  #  Extract tree structure values:
477  #===============================================================================  #===============================================================================
# Line 428  Line 492 
492  #  #
493  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
494    
495  sub newick_desc_ref { $_[0]->[0] }  # = ${$_[0]}[0]  sub newick_desc_ref { ref($_[0]) ? $_[0]->[0] : Carp::confess() }  # = ${$_[0]}[0]
496  sub newick_lbl      { ref($_[0]) ? $_[0]->[1] : Carp::confess() }  sub newick_lbl      { ref($_[0]) ? $_[0]->[1] : Carp::confess() }
497  sub newick_x        { $_[0]->[2] }  sub newick_x        { ref($_[0]) ? $_[0]->[2] : Carp::confess() }
498  sub newick_c1       { $_[0]->[3] }  sub newick_c1       { ref($_[0]) ? $_[0]->[3] : Carp::confess() }
499  sub newick_c2       { $_[0]->[4] }  sub newick_c2       { ref($_[0]) ? $_[0]->[4] : Carp::confess() }
500  sub newick_c3       { $_[0]->[5] }  sub newick_c3       { ref($_[0]) ? $_[0]->[5] : Carp::confess() }
501  sub newick_c4       { $_[0]->[6] }  sub newick_c4       { ref($_[0]) ? $_[0]->[6] : Carp::confess() }
502  sub newick_c5       { $_[0]->[7] }  sub newick_c5       { ref($_[0]) ? $_[0]->[7] : Carp::confess() }
503    
504  sub newick_desc_list {  sub newick_desc_list {
505      my $node = $_[0];      my $node = $_[0];
506      ! array_ref( $node      ) ? undef           :      array_ref( $node ) && array_ref( $node->[0] ) ? @{ $node->[0] } : ();
       array_ref( $node->[0] ) ? @{ $node->[0] } :  
                                 ()              ;  
507  }  }
508    
509  sub newick_n_desc {  sub newick_n_desc {
510      my $node = $_[0];      my $node = $_[0];
511      ! array_ref( $node      ) ? undef                  :      array_ref( $node ) && array_ref( $node->[0] ) ? scalar @{ $node->[0] } : 0;
       array_ref( $node->[0] ) ? scalar @{ $node->[0] } :  
                                 0                      ;  
512  }  }
513    
514  sub newick_desc_i {  sub newick_desc_i {
515      my ( $node, $i ) = @_;      my ( $node, $i ) = @_;
516      ! array_ref( $node      ) ? undef              :      array_ref( $node ) && $i && array_ref( $node->[0] ) ? $node->[0]->[$i-1] : undef;
       array_ref( $node->[0] ) ? $node->[0]->[$i-1] :  
                                 undef              ;  
517  }  }
518    
519  sub node_is_tip {  sub node_is_tip {
# Line 641  Line 699 
699  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
700  #  List of tip nodes:  #  List of tip nodes:
701  #  #
702  #  @tips = newick_tip_ref_list( $node )  #  @tips = newick_tip_ref_list( $noderef )
703    # \@tips = newick_tip_ref_list( $noderef )
704  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
705  sub newick_tip_ref_list {  sub newick_tip_ref_list {
706      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
# Line 658  Line 717 
717          push @list, newick_tip_ref_list( $_, 1 );          push @list, newick_tip_ref_list( $_, 1 );
718      }      }
719    
720      @list;      wantarray ? @list : \@list;
721  }  }
722    
723    
# Line 666  Line 725 
725  #  List of tips:  #  List of tips:
726  #  #
727  #  @tips = newick_tip_list( $node )  #  @tips = newick_tip_list( $node )
728    # \@tips = newick_tip_list( $node )
729  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
730  sub newick_tip_list {  sub newick_tip_list {
731      map { newick_lbl( $_ ) } newick_tip_ref_list( $_[0] );      my @tips = map { newick_lbl( $_ ) } newick_tip_ref_list( $_[0] );
732        wantarray ? @tips : \@tips;
733  }  }
734    
735    
# Line 707  Line 768 
768  #  List of duplicated tip labels.  #  List of duplicated tip labels.
769  #  #
770  #  @tips = newick_duplicated_tips( $node )  #  @tips = newick_duplicated_tips( $node )
771    # \@tips = newick_duplicated_tips( $node )
772  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
773  sub newick_duplicated_tips {  sub newick_duplicated_tips {
774      gjolists::duplicates( newick_tip_list( $_[0] ) );      my @tips = &duplicates( newick_tip_list( $_[0] ) );
775        wantarray ? @tips : \@tips;
776  }  }
777    
778    
# Line 740  Line 803 
803  #  Tips shared between 2 trees.  #  Tips shared between 2 trees.
804  #  #
805  #  @tips = newick_shared_tips( $tree1, $tree2 )  #  @tips = newick_shared_tips( $tree1, $tree2 )
806    # \@tips = newick_shared_tips( $tree1, $tree2 )
807  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
808  sub newick_shared_tips {  sub newick_shared_tips {
809      my ( $Tree1, $Tree2 ) = @_;      my ( $tree1, $tree2 ) = @_;
810      my ( @Tips1 ) = newick_tip_list( $Tree1 );      my $tips1 = newick_tip_list( $tree1 );
811      my ( @Tips2 ) = newick_tip_list( $Tree2 );      my $tips2 = newick_tip_list( $tree2 );
812      gjolists::intersection( \@Tips1, \@Tips2 );      my @tips = &intersection( $tips1, $tips2 );
813        wantarray ? @tips : \@tips;
814  }  }
815    
816    
# Line 767  Line 832 
832    
833    
834  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
835    #  Hash of tip nodes and corresponding distances from root:
836    #
837    #   %tip_distances = newick_tip_distances( $node )
838    #  \%tip_distances = newick_tip_distances( $node )
839    #-------------------------------------------------------------------------------
840    sub newick_tip_distances
841    {
842        my ( $node, $x, $hash ) = @_;
843        my $root = ! $hash;
844        ref( $hash ) eq 'HASH' or $hash = {};
845    
846        $x ||= 0;
847        $x  += newick_x( $node ) || 0;
848    
849        #  Is it a tip?
850    
851        my $n_desc = newick_n_desc( $node );
852        if ( ! $n_desc )
853        {
854            $hash->{ newick_lbl( $node ) } = $x;
855            return $hash;
856        }
857    
858        #  Tree rooted on tip?
859    
860        if ( ( $n_desc == 1 ) && $root && ( newick_lbl( $node ) ) )
861        {
862            $hash->{ newick_lbl( $node ) } = 0;  # Distance to root is zero
863        }
864    
865        foreach ( newick_desc_list( $node ) )
866        {
867            newick_tip_distances( $_, $x, $hash );
868        }
869    
870        wantarray ? %$hash : $hash;
871    }
872    
873    
874    #-------------------------------------------------------------------------------
875  #  Tree max X.  #  Tree max X.
876  #  #
877  #  $xmax = newick_max_X( $node )  #  $xmax = newick_max_X( $node )
# Line 910  Line 1015 
1015    
1016      else      else
1017      {      {
1018          my ( $n1, $x1 ) = describe_desc( $dl->[0] );          my ( $n1, $x1 ) = describe_descendant( $dl->[0] );
1019          my ( $n2, $x2 ) = describe_desc( $dl->[1] );          my ( $n2, $x2 ) = describe_descendant( $dl->[1] );
1020    
1021          if ( @$n1 == 2 ) { push @$n1, $n2->[0] }          if ( @$n1 == 2 ) { push @$n1, $n2->[0] }
1022          if ( @$n2 == 2 )          if ( @$n2 == 2 )
# Line 926  Line 1031 
1031  }  }
1032    
1033    
1034  sub describe_desc  sub describe_descendant
1035  {  {
1036      my $node = shift;      my $node = shift;
1037    
# Line 951  Line 1056 
1056      #  Return the two lowest of those (the third will come from the      #  Return the two lowest of those (the third will come from the
1057      #  other side of the original node).      #  other side of the original node).
1058    
     else  
     {  
1059          my @rep_tips = sort { lc $a cmp lc $b }          my @rep_tips = sort { lc $a cmp lc $b }
1060                         map  { ( sort { lc $a cmp lc $b } newick_tip_list( $_ ) )[0] }                         map  { ( sort { lc $a cmp lc $b } newick_tip_list( $_ ) )[0] }
1061                         @$dl;                         @$dl;
1062          return ( [ @rep_tips[0,1] ], $x );          return ( [ @rep_tips[0,1] ], $x );
1063      }      }
 }  
1064    
1065    
1066  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
# Line 967  Line 1069 
1069  #     Three sorted tip labels intersecting at node, each being smallest  #     Three sorted tip labels intersecting at node, each being smallest
1070  #           of all the tips of their subtrees  #           of all the tips of their subtrees
1071  #  #
1072  #  @TipOrTips = std_node_name( $Tree, $Node )  #  @TipOrTips = std_node_name( $tree, $node )
1073  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1074  sub std_node_name {  sub std_node_name {
1075      my $tree = $_[0];      my $tree = $_[0];
# Line 985  Line 1087 
1087      #  @rest, and keeping the best tip for each subtree.      #  @rest, and keeping the best tip for each subtree.
1088    
1089      my @rest = newick_tip_list( $tree );      my @rest = newick_tip_list( $tree );
1090      my @best = map {      my @best = map
1091              {
1092              my @tips = sort { lc $a cmp lc $b } newick_tip_list( $_ );              my @tips = sort { lc $a cmp lc $b } newick_tip_list( $_ );
1093              @rest = gjolists::set_difference( \@rest, \@tips );              @rest = &set_difference( \@rest, \@tips );
1094              $tips[0];              $tips[0];
1095          } newick_desc_list( $noderef );          } newick_desc_list( $noderef );
1096    
# Line 1075  Line 1178 
1178      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
1179      for ( my $i = 1; $i <= $imax; $i++ ) {      for ( my $i = 1; $i <= $imax; $i++ ) {
1180         @path = path_to_node_ref( newick_desc_i( $node, $i ), $noderef, ( @path0, $i ) );         @path = path_to_node_ref( newick_desc_i( $node, $i ), $noderef, ( @path0, $i ) );
1181         if ( @path ) { return @path }          return @path if @path;
1182      }      }
1183    
1184      ();  #  Not found      ();  #  Not found
# Line 1106  Line 1209 
1209      @p2 && @p3 || return ();                             #  Were they found?      @p2 && @p3 || return ();                             #  Were they found?
1210    
1211      # Find the common prefix for each pair of paths      # Find the common prefix for each pair of paths
1212      my @p12 = gjolists::common_prefix( \@p1, \@p2 );      my @p12 = &common_prefix( \@p1, \@p2 );
1213      my @p13 = gjolists::common_prefix( \@p1, \@p3 );      my @p13 = &common_prefix( \@p1, \@p3 );
1214      my @p23 = gjolists::common_prefix( \@p2, \@p3 );      my @p23 = &common_prefix( \@p2, \@p3 );
1215    
1216      # Return the longest common prefix of any two paths      # Return the longest common prefix of any two paths
1217      ( @p12 >= @p13 && @p12 >= @p23 ) ? @p12 :      ( @p12 >= @p13 && @p12 >= @p23 ) ? @p12 :
# Line 1159  Line 1262 
1262      @p1 && @p2 || return undef;                          # Were they found?      @p1 && @p2 || return undef;                          # Were they found?
1263    
1264      # Find the unique suffixes of the two paths      # Find the unique suffixes of the two paths
1265      my ( $suf1, $suf2 ) = gjolists::unique_suffixes( \@p1, \@p2 ); # Common node is lost      my ( $suf1, $suf2 ) = &unique_suffixes( \@p1, \@p2 ); # Common node is lost
1266      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;
1267      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;
1268    
# Line 1184  Line 1287 
1287      my @p2 = path_to_node( $node, $node2 ) or return undef;      my @p2 = path_to_node( $node, $node2 ) or return undef;
1288    
1289      # Find the unique suffixes of the two paths      # Find the unique suffixes of the two paths
1290      my ( $suf1, $suf2 ) = gjolists::unique_suffixes( \@p1, \@p2 ); # Common node is lost      my ( $suf1, $suf2 ) = &unique_suffixes( \@p1, \@p2 ); # Common node is lost
1291      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;
1292      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;
1293    
# Line 1435  Line 1538 
1538    
1539    
1540  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1541    #  Modify all branch lengths by a function.
1542    #
1543    #     $node = newick_modify_branches( $node, \&function )
1544    #     $node = newick_modify_branches( $node, \&function, \@func_parms )
1545    #
1546    #  Function must have form
1547    #
1548    #     $x2 = &$function( $x1 )
1549    #     $x2 = &$function( $x1, @$func_parms )
1550    #
1551    #-------------------------------------------------------------------------------
1552    sub newick_modify_branches {
1553        my ( $node, $func, $parm ) = @_;
1554    
1555        set_newick_x( $node, &$func( newick_x( $node ), ( $parm ? @$parm : () ) ) );
1556        foreach ( newick_desc_list( $node ) )
1557        {
1558            newick_modify_branches( $_, $func, $parm )
1559        }
1560    
1561        $node;
1562    }
1563    
1564    
1565    #-------------------------------------------------------------------------------
1566  #  Set negative branches to zero.  The original tree is modfied.  #  Set negative branches to zero.  The original tree is modfied.
1567  #  #
1568  #  $n_changed = newick_fix_negative_branches( $tree )  #  $n_changed = newick_fix_negative_branches( $tree )
# Line 1523  Line 1651 
1651    
1652    
1653  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1654    #  Standard name for a Newick tree topology
1655    #
1656    #    $stdname = std_tree_name( $tree )
1657    #
1658    #-------------------------------------------------------------------------------
1659    sub std_tree_name
1660    {
1661        my ( $tree ) = @_;
1662        my ( $mintip ) = sort { lc $a cmp lc $b } newick_tip_list( $tree );
1663        ( std_tree_name_2( reroot_newick_next_to_tip( copy_newick_tree( $tree ), $mintip ) ) )[0];
1664    }
1665    
1666    
1667    #
1668    #  ( $name, $mintip ) = std_tree_name_2( $node )
1669    #
1670    sub std_tree_name_2
1671    {
1672        my ( $node ) = @_;
1673    
1674        my @descends = newick_desc_list( $node );
1675        if ( @descends == 0 )
1676        {
1677            my $lbl = newick_lbl( $node );
1678            return ( $lbl, $lbl );
1679        }
1680    
1681        my @list = sort { lc $a->[1] cmp lc $b->[1] || $a->[1] cmp $b->[1] }
1682                   map  { [ std_tree_name_2( $_ ) ] }
1683                   @descends;
1684        my $mintip = $list[0]->[1];
1685        my $name   = '(' . join( "\t", map { $_->[0] } @list ) . ')';
1686    
1687        return ( $name, $mintip );
1688    }
1689    
1690    
1691    #-------------------------------------------------------------------------------
1692  #  Move largest groups to periphery of tree (in place).  #  Move largest groups to periphery of tree (in place).
1693  #  #
1694  #      dir  <= -2 for up-sweeping tree (big groups always first),  #      dir  <= -2 for up-sweeping tree (big groups always first),
# Line 1582  Line 1748 
1748      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
1749      if ( $nd <  1 ) { return $node }       #  Do nothing to a tip      if ( $nd <  1 ) { return $node }       #  Do nothing to a tip
1750    
     #  Reorder this subtree:  
   
1751      my $dl_ref = newick_desc_ref( $node );      my $dl_ref = newick_desc_ref( $node );
1752      if    ( $dir < 0 ) {                   #  Big group first  
1753          @$dl_ref = sort { $cntref->{$b} <=> $cntref->{$a} } @$dl_ref;      #  Reorder this subtree (biggest subtrees to outside)
1754    
1755        if ( $dir )
1756        {
1757            #  Big group first
1758            my @dl = sort { $cntref->{$b} <=> $cntref->{$a} } @$dl_ref;
1759    
1760            my ( @dl1, @dl2 );
1761            for ( my $i = 0; $i < $nd; $i++ ) {
1762                if ( $i & 1 ) { push @dl2, $dl[$i] } else { push @dl1, $dl[$i] }
1763      }      }
1764      elsif ( $dir > 0 ) {                   #  Small group first  
1765          @$dl_ref = sort { $cntref->{$a} <=> $cntref->{$b} } @$dl_ref;          @$dl_ref = ( $dir < 0 ) ? ( @dl1, reverse @dl2 )
1766                                    : ( @dl2, reverse @dl1 );
1767      }      }
1768    
1769      #  Reorder within descendant subtrees:      #  Reorder within descendant subtrees:
# Line 1621  Line 1795 
1795  #  #
1796  #  $tree = unaesthetic_newick_tree( $treeref, $dir )  #  $tree = unaesthetic_newick_tree( $treeref, $dir )
1797  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1798  sub unaesthetic_newick_tree {  sub unaesthetic_newick_tree
1799    {
1800      my ( $tree, $dir ) = @_;      my ( $tree, $dir ) = @_;
1801      my %cnt;      my %cnt;
1802    
# Line 1641  Line 1816 
1816  #           = 0 for no change, and  #           = 0 for no change, and
1817  #           > 0 for downward branch (small group first).  #           > 0 for downward branch (small group first).
1818  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1819  sub reorder_against_tip_count {  sub reorder_against_tip_count
1820    {
1821      my ( $node, $cntref, $dir ) = @_;      my ( $node, $cntref, $dir ) = @_;
1822    
1823      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
# Line 1680  Line 1856 
1856  #  #
1857  #  $tree = random_order_newick_tree( $tree )  #  $tree = random_order_newick_tree( $tree )
1858  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1859  sub random_order_newick_tree {  sub random_order_newick_tree
1860    {
1861      my ( $node ) = @_;      my ( $node ) = @_;
1862    
1863      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
# Line 1689  Line 1866 
1866      #  Reorder this subtree:      #  Reorder this subtree:
1867    
1868      my $dl_ref = newick_desc_ref( $node );      my $dl_ref = newick_desc_ref( $node );
1869      @$dl_ref = gjolists::random_order( @$dl_ref );      @$dl_ref = &random_order( @$dl_ref );
1870    
1871      #  Reorder descendants:      #  Reorder descendants:
1872    
# Line 1704  Line 1881 
1881  #  #
1882  #  $newtree = reroot_newick_by_path( @path )  #  $newtree = reroot_newick_by_path( @path )
1883  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1884  sub reroot_newick_by_path {  sub reroot_newick_by_path
1885    {
1886      my ( $node1, $path1, @rest ) = @_;      my ( $node1, $path1, @rest ) = @_;
1887      array_ref( $node1 ) || return undef;      #  Always expect a node      array_ref( $node1 ) || return undef;      #  Always expect a node
1888    
# Line 1812  Line 1990 
1990    
1991    
1992  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1993    #  Reroot a newick tree along the path between 2 nodes:
1994    #
1995    #  $tree = reroot_newick_between_nodes( $tree, $node1, $node2, $fraction )
1996    #-------------------------------------------------------------------------------
1997    sub reroot_newick_between_nodes
1998    {
1999        my ( $tree, $node1, $node2, $fraction ) = @_;
2000        array_ref( $tree ) or return undef;
2001        $fraction >= 0 && $fraction <= 1 or return undef;
2002    
2003        #  Find the paths to the nodes:
2004    
2005        my @path1 = path_to_node( $tree, $node1 ) or return undef;
2006        my @path2 = path_to_node( $tree, $node2 ) or return undef;
2007    
2008        reroot_newick_between_nodes_by_path( $tree, \@path1, \@path2, $fraction )
2009    }
2010    
2011    
2012    #-------------------------------------------------------------------------------
2013    #  Reroot a newick tree along the path between 2 nodes:
2014    #
2015    #  $tree = reroot_newick_between_node_refs( $tree, $node1, $node2, $fraction )
2016    #-------------------------------------------------------------------------------
2017    sub reroot_newick_between_node_refs
2018    {
2019        my ( $tree, $node1, $node2, $fraction ) = @_;
2020        array_ref( $tree ) or return undef;
2021    
2022        #  Find the paths to the nodes:
2023    
2024        my @path1 = path_to_node_ref( $tree, $node1 ) or return undef;
2025        my @path2 = path_to_node_ref( $tree, $node2 ) or return undef;;
2026    
2027        reroot_newick_between_nodes_by_path( $tree, \@path1, \@path2, $fraction )
2028    }
2029    
2030    
2031    #-------------------------------------------------------------------------------
2032    #  Reroot a newick tree along the path between 2 nodes defined by paths:
2033    #
2034    #  $tree = reroot_newick_between_nodes_by_path( $tree, $path1, $path2, $fraction )
2035    #-------------------------------------------------------------------------------
2036    sub reroot_newick_between_nodes_by_path
2037    {
2038        my ( $tree, $path1, $path2, $fraction ) = @_;
2039        array_ref( $tree ) and array_ref( $path1 ) and  array_ref( $path2 )
2040           or return undef;
2041        $fraction >= 0 && $fraction <= 1 or return undef;
2042    
2043        my @path1 = @$path1;
2044        my @path2 = @$path2;
2045    
2046        #  Trim the common prefix, saving it:
2047    
2048        my @prefix = ();
2049        while ( defined( $path1[1] ) && defined( $path2[1] ) && ( $path1[1] == $path2[1] ) )
2050        {
2051            push @prefix, splice( @path1, 0, 2 );
2052            splice( @path2, 0, 2 );
2053        }
2054    
2055        my ( @path, $dist );
2056        if    ( @path1 < 3 )
2057        {
2058            @path2 >= 3 or return undef;              # node1 = node2
2059            $dist = $fraction * newick_path_length( @path2 );
2060            @path = @path2;
2061        }
2062        elsif ( @path2 < 3 )
2063        {
2064            $dist = ( 1 - $fraction ) * newick_path_length( @path1 );
2065            @path = @path1;
2066        }
2067        else
2068        {
2069            my $dist1 = newick_path_length( @path1 );
2070            my $dist2 = newick_path_length( @path2 );
2071            $dist = $fraction * ( $dist1 + $dist2 ) - $dist1;
2072            @path = ( $dist <= 0 ) ? @path1 : @path2;
2073            $dist = abs( $dist );
2074        }
2075    
2076        #  Descend tree until we reach the insertion branch:
2077    
2078        my $x;
2079        while ( ( $dist > ( $x = newick_x( $path[2] ) ) ) && ( @path > 3 ) )
2080        {
2081            $dist -= $x;
2082            push @prefix, splice( @path, 0, 2 );
2083        }
2084    
2085        #  Insert the new node:
2086    
2087        my $newnode = [ [ $path[2] ], undef, $dist ];
2088        set_newick_desc_i( $path[0], $path[1], $newnode );
2089        set_newick_x( $path[2], ( ( $x > $dist ) ? ( $x - $dist ) : 0 ) );
2090    
2091        #  We can now build the path from root to the new node
2092    
2093        reroot_newick_by_path( @prefix, @path[0,1], $newnode );
2094    }
2095    
2096    
2097    #-------------------------------------------------------------------------------
2098  #  Move root of tree to an approximate midpoint.  #  Move root of tree to an approximate midpoint.
2099  #  #
2100  #  $newtree = reroot_newick_to_approx_midpoint( $tree )  #  $newtree = reroot_newick_to_approx_midpoint( $tree )
# Line 1823  Line 2106 
2106    
2107      my $dists1 = average_to_tips_1( $tree );      my $dists1 = average_to_tips_1( $tree );
2108    
2109      #  Compile average tip to node distances descending, returning midpoint node      #  Compile average tip to node distances descending, returning midpoint
2110        #  cadidates as a list of [ $node1, $node2, $fraction ]
2111    
2112        my @mids = average_to_tips_2( $dists1, undef, undef );
2113    
2114        #  Reroot to first midpoint candidate
2115    
2116        return $tree if ! @mids;
2117        my ( $node1, $node2, $fraction ) = @{ $mids[0] };
2118        reroot_newick_to_node_ref( $tree, $fraction >= 0.5 ? $node2 : $node1 );
2119    }
2120    
2121    
2122    #-------------------------------------------------------------------------------
2123    #  Move root of tree to a midpoint.
2124    #
2125    #  $newtree = reroot_newick_to_midpoint( $tree )
2126    #-------------------------------------------------------------------------------
2127    sub reroot_newick_to_midpoint {
2128        my ( $tree ) = @_;
2129    
2130        #  Compile average tip to node distances assending
2131    
2132        my $dists1 = average_to_tips_1( $tree );
2133    
2134      my $node = average_to_tips_2( $dists1, undef, undef );      #  Compile average tip to node distances descending, returning midpoint
2135        #  [ $node1, $node2, $fraction ]
2136    
2137      #  Reroot      my @mids = average_to_tips_2( $dists1, undef, undef );
2138    
2139      $node ? reroot_newick_to_node_ref( $tree, $node ) : $tree      @mids ? reroot_newick_between_node_refs( $tree, @{ $mids[0] } ) : $tree;
2140  }  }
2141    
2142    
2143    #-------------------------------------------------------------------------------
2144    #  Compile average tip to node distances assending
2145    #-------------------------------------------------------------------------------
2146  sub average_to_tips_1 {  sub average_to_tips_1 {
2147      my ( $node ) = @_;      my ( $node ) = @_;
2148    
# Line 1843  Line 2153 
2153          foreach ( @desc_dists ) { $x_below += $_->[0] }          foreach ( @desc_dists ) { $x_below += $_->[0] }
2154          $x_below /= @desc_dists;          $x_below /= @desc_dists;
2155      }      }
2156    
2157      my $x = newick_x( $node ) || 0;      my $x = newick_x( $node ) || 0;
2158      my $x_net = $x_below + $x;      my $x_net = $x_below + $x;
2159    
# Line 1850  Line 2161 
2161  }  }
2162    
2163    
2164    #-------------------------------------------------------------------------------
2165    #  Compile average tip to node distances descending, returning midpoint as
2166    #  [ $node1, $node2, $fraction_of_dist_between ]
2167    #-------------------------------------------------------------------------------
2168  sub average_to_tips_2 {  sub average_to_tips_2 {
2169      my ( $dists1, $x_above, $anc_node ) = @_;      my ( $dists1, $x_above, $anc_node ) = @_;
2170      my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;      my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;
2171    
2172      #  Are we done?  Root is in this node's branch, or "above"?      #  Are we done?  Root is in this node's branch, or "above"?
2173    
2174      # 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";  
   
2175      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )
2176      {      {
2177          #  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 2183 
2183    
2184          if ( ( $x_below + $x ) >= $x_above )          if ( ( $x_below + $x ) >= $x_above )
2185          {          {
2186              return ( $x_above >= $x_below ) ? $anc_node : $node;              #  We will need to make a new node for the root, $fract of
2187          }              #  the way from $node to $anc_node:
2188          else              my $fract = ( $x > 0 ) ? 0.5 * ( ( $x_above - $x_below ) / $x + 1 )
2189          {                                     : 0.5;
2190              return undef;              push @mids, [ $node, $anc_node, $fract ];
2191          }          }
2192      }      }
2193    
2194      #  The root must be somewhere below this node:      #  The root might be somewhere below this node:
2195    
2196      my $n_1      =   @$desc_list - ( $anc_node ? 0 : 1 );      my $n_1      =   @$desc_list - ( $anc_node ? 0 : 1 );
2197      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 2201 
2201          #  If input tree is tip_rooted, $n-1 can be 0, so:          #  If input tree is tip_rooted, $n-1 can be 0, so:
2202    
2203          my $above2 = $n_1 ? ( ( $ttl_dist - $_->[0] ) / $n_1 ) : 0;          my $above2 = $n_1 ? ( ( $ttl_dist - $_->[0] ) / $n_1 ) : 0;
2204          my $root = average_to_tips_2( $_, $above2, $node );          push @mids, average_to_tips_2( $_, $above2, $node );
         if ( $root ) { return $root }  
2205      }      }
2206    
2207      #  Was not anywhere below this node (oh-oh):      return @mids;
   
     return undef;  
2208  }  }
2209    
2210    
# Line 1907  Line 2215 
2215  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2216  sub reroot_newick_to_approx_midpoint_w {  sub reroot_newick_to_approx_midpoint_w {
2217      my ( $tree ) = @_;      my ( $tree ) = @_;
2218        array_ref( $tree ) or return undef;
2219    
2220        #  Compile average tip to node distances assending from tips
2221    
2222        my $dists1 = average_to_tips_1_w( $tree );
2223    
2224        #  Compile average tip to node distances descending, returning midpoints
2225    
2226        my @mids = average_to_tips_2_w( $dists1, undef, undef, undef );
2227    
2228        #  Reroot to first midpoint candidate
2229    
2230        return $tree if ! @mids;
2231        my ( $node1, $node2, $fraction ) = @{ $mids[0] };
2232        reroot_newick_to_node_ref( $tree, $fraction >= 0.5 ? $node2 : $node1 );
2233    }
2234    
2235    
2236    #-------------------------------------------------------------------------------
2237    #  Move root of tree to an approximate midpoint.  Weight by tips.
2238    #
2239    #  $newtree = reroot_newick_to_midpoint_w( $tree )
2240    #-------------------------------------------------------------------------------
2241    sub reroot_newick_to_midpoint_w {
2242        my ( $tree ) = @_;
2243        array_ref( $tree ) or return ();
2244    
2245      #  Compile average tip to node distances assending      #  Compile average tip to node distances assending
2246    
# Line 1914  Line 2248 
2248    
2249      #  Compile average tip to node distances descending, returning midpoint node      #  Compile average tip to node distances descending, returning midpoint node
2250    
2251      my $node = average_to_tips_2_w( $dists1, undef, undef, undef );      my @mids = average_to_tips_2_w( $dists1, undef, undef, undef );
2252    
2253      #  Reroot      #  Reroot at first candidate midpoint
2254    
2255      $node ? reroot_newick_to_node_ref( $tree, $node ) : $tree      @mids ? reroot_newick_between_node_refs( $tree, @{ $mids[0] } ) : $tree;
2256  }  }
2257    
2258    
2259    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2260  sub average_to_tips_1_w {  sub average_to_tips_1_w {
2261      my ( $node ) = @_;      my ( $node ) = @_;
2262    
# Line 1939  Line 2274 
2274          }          }
2275          $x_below /= $n_below;          $x_below /= $n_below;
2276      }      }
2277    
2278      my $x = newick_x( $node ) || 0;      my $x = newick_x( $node ) || 0;
2279      my $x_net = $x_below + $x;      my $x_net = $x_below + $x;
2280    
# Line 1946  Line 2282 
2282  }  }
2283    
2284    
2285    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2286  sub average_to_tips_2_w {  sub average_to_tips_2_w {
2287      my ( $dists1, $x_above, $n_above, $anc_node ) = @_;      my ( $dists1, $x_above, $n_above, $anc_node ) = @_;
2288      my ( undef, $n_below, $x, $x_below, $desc_list, $node ) = @$dists1;      my ( undef, $n_below, $x, $x_below, $desc_list, $node ) = @$dists1;
2289    
2290      #  Are we done?  Root is in this node's branch, or "above"?      #  Are we done?  Root is in this node's branch, or "above"?
2291    
2292      # 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";  
   
2293      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )
2294      {      {
2295          #  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 2297 
2297          #  would mean that the midpoint is actually down a different          #  would mean that the midpoint is actually down a different
2298          #  path from the root of the current tree).          #  path from the root of the current tree).
2299          #          #
2300          #  Is the root in the current branch?          #  Is their a root in the current branch?
2301    
2302          if ( ( $x_below + $x ) >= $x_above )          if ( ( $x_below + $x ) >= $x_above )
2303          {          {
2304              return ( $x_above >= $x_below ) ? $anc_node : $node;              #  We will need to make a new node for the root, $fract of
2305          }              #  the way from $node to $anc_node:
2306          else              my $fract = ( $x > 0 ) ? 0.5 * ( ( $x_above - $x_below ) / $x + 1 )
2307          {                                     : 0.5;
2308              return undef;              push @mids, [ $node, $anc_node, $fract ];
2309          }          }
2310      }      }
2311    
# Line 1992  Line 2325 
2325    
2326          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 )
2327                                   : 0;                                   : 0;
2328          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 }  
2329      }      }
2330    
2331      #  Was not anywhere below this node (oh-oh):      return @mids;
   
     return undef;  
2332  }  }
2333    
2334    
# Line 2313  Line 2643 
2643    
2644    
2645  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2646  #  Produce a subtree with the desired tips:  #  Produce a potentially rooted subtree with the desired tips:
2647  #  #
2648  #     Except for (some) tip nodes, the tree produced is a copy.  #     Except for (some) tip nodes, the tree produced is a copy.
2649  #     There is no check that requested tips exist.  #     There is no check that requested tips exist.
2650  #  #
2651  #  $newtree = newick_subtree( $tree,  @tips )  #  $newtree = rooted_newick_subtree( $tree,  @tips )
2652  #  $newtree = newick_subtree( $tree, \@tips )  #  $newtree = rooted_newick_subtree( $tree, \@tips )
2653  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2654  sub newick_subtree {  sub rooted_newick_subtree {
2655      my ( $tr, @tips ) = @_;      my ( $tr, @tips ) = @_;
2656      if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }      if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }
2657    
2658      if ( @tips < 2 ) { return undef }      if ( @tips < 2 ) { return undef }
     my $was_rooted = newick_is_rooted( $tr );  
2659      my $keephash = { map { ( $_, 1 ) } @tips };      my $keephash = { map { ( $_, 1 ) } @tips };
2660      my $tr2 = subtree1( $tr, $keephash );      my $tr2 = subtree1( $tr, $keephash );
     $tr2 = uproot_newick( $tr2 ) if ! $was_rooted && newick_is_rooted( $tr2 );  
2661      $tr2->[2] = undef if $tr2;                   # undef root branch length      $tr2->[2] = undef if $tr2;                   # undef root branch length
2662      $tr2;      $tr2;
2663  }  }
2664    
2665    
2666  sub subtree1 {  #-------------------------------------------------------------------------------
2667    #  Produce a subtree with the desired tips:
2668    #
2669    #     Except for (some) tip nodes, the tree produced is a copy.
2670    #     There is no check that requested tips exist.
2671    #
2672    #  $newtree = newick_subtree( $tree,  @tips )
2673    #  $newtree = newick_subtree( $tree, \@tips )
2674    #-------------------------------------------------------------------------------
2675    sub newick_subtree {
2676        my ( $tr, @tips ) = @_;
2677        if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }
2678    
2679        if ( @tips < 2 ) { return undef }
2680        my $was_rooted = newick_is_rooted( $tr );
2681        my $keephash = { map { ( $_, 1 ) } @tips };
2682        my $tr2 = subtree1( $tr, $keephash );
2683        $tr2 = uproot_newick( $tr2 ) if ! $was_rooted && newick_is_rooted( $tr2 );
2684        $tr2->[2] = undef if $tr2;                   # undef root branch length
2685        $tr2;
2686    }
2687    
2688    
2689    sub subtree1 {
2690      my ( $tr, $keep ) = @_;      my ( $tr, $keep ) = @_;
2691      my @desc1 = newick_desc_list( $tr );      my @desc1 = newick_desc_list( $tr );
2692    
# Line 2386  Line 2737 
2737  }  }
2738    
2739    
2740    #-------------------------------------------------------------------------------
2741    #  The smallest subtree of rooted tree that includes @tips:
2742    #
2743    #    $node = newick_covering_subtree( $tree,  @tips )
2744    #    $node = newick_covering_subtree( $tree, \@tips )
2745    #-------------------------------------------------------------------------------
2746    
2747    sub newick_covering_subtree {
2748        my $tree = shift;
2749        my %tips = map { $_ => 1 } ( ( ref( $_[0] ) eq 'ARRAY' ) ? @{ $_[0] } : @_ );
2750    
2751        #  Return smallest covering node, if any:
2752    
2753        ( newick_covering_subtree( $tree, \%tips ) )[ 0 ];
2754    }
2755    
2756    
2757    sub newick_covering_subtree_1 {
2758        my ( $node, $tips ) = @_;
2759        my $n_cover = 0;
2760        my @desc = newick_desc_list( $node );
2761        if ( @desc )
2762        {
2763            foreach ( @desc )
2764            {
2765                my ( $subtree, $n ) = newick_covering_subtree_1( $_, $tips );
2766                return ( $subtree, $n ) if $subtree;
2767                $n_cover += $n;
2768            }
2769        }
2770        elsif ( $tips->{ newick_lbl( $node ) } )
2771        {
2772            $n_cover++;
2773        }
2774    
2775        #  If all tips are covered, return node
2776    
2777        ( $n_cover == keys %$tips ) ? ( $node, $n_cover ) : ( undef, $n_cover );
2778    }
2779    
2780    
2781    #===============================================================================
2782    #
2783    #  Representative subtrees
2784    #
2785    #===============================================================================
2786    #  Find subtree of size n representating vicinity of the root:
2787    #
2788    #   $subtree = root_neighborhood_representative_tree( $tree, $n, \%tip_priority )
2789    #   $subtree = root_neighborhood_representative_tree( $tree, $n )
2790    #
2791    #  Note that if $tree is rooted, then the subtree will also be.  This can have
2792    #  consequences on downstream programs.
2793    #-------------------------------------------------------------------------------
2794    sub root_neighborhood_representative_tree
2795    {
2796        my ( $tree, $n, $tip_priority ) = @_;
2797        array_ref( $tree ) && ( $n >= 2 ) or return undef;
2798        if ( newick_tip_count( $tree ) <= $n ) { return $tree }
2799    
2800        $tip_priority ||= default_tip_priority( $tree );
2801        my @tips = map { representative_tip_of_newick_node( $_, $tip_priority ) }
2802                   root_proximal_newick_subtrees( $tree, $n );
2803    
2804        newick_subtree( copy_newick_tree( $tree ), \@tips );
2805    }
2806    
2807    
2808    #-------------------------------------------------------------------------------
2809    #  Find n tips to represent tree lineages in vicinity of another tip.
2810    #  Default tip priority is short total branch length.
2811    #
2812    #  \@tips = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
2813    #   @tips = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
2814    #  \@tips = root_neighborhood_representative_tips( $tree, $n )
2815    #   @tips = root_neighborhood_representative_tips( $tree, $n )
2816    #-------------------------------------------------------------------------------
2817    sub root_neighborhood_representative_tips
2818    {
2819        my ( $tree, $n, $tip_priority ) = @_;
2820        array_ref( $tree ) && ( $n >= 2 ) or return undef;
2821    
2822        my @tips;
2823        if ( newick_tip_count( $tree ) <= $n )
2824        {
2825            @tips = newick_tip_list( $tree );
2826        }
2827        else
2828        {
2829            $tip_priority ||= default_tip_priority( $tree );
2830            @tips = map { representative_tip_of_newick_node( $_, $tip_priority ) }
2831                    root_proximal_newick_subtrees( $tree, $n );
2832        }
2833    
2834        wantarray ? @tips : \@tips;
2835    }
2836    
2837    
2838    #-------------------------------------------------------------------------------
2839    #  Find subtree of size n representating vicinity of a tip:
2840    #
2841    #   $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n, \%tip_priority )
2842    #   $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n )
2843    #-------------------------------------------------------------------------------
2844    sub tip_neighborhood_representative_tree
2845    {
2846        my ( $tree, $tip, $n, $tip_priority ) = @_;
2847        array_ref( $tree ) && $tip && ( $n >= 2 ) or return undef;
2848        newick_tip_in_tree( $tree, $tip ) or return undef;
2849    
2850        my $tree1 = copy_newick_tree( $tree );
2851        if ( newick_tip_count( $tree1 ) - 1 <= $n )
2852        {
2853            return prune_from_newick( $tree1, $tip )
2854        }
2855    
2856        $tree1 = reroot_newick_to_tip( $tree1, $tip );
2857        $tree1 = newick_desc_i( $tree1, 1 );        # Node immediately below tip
2858        my @tips = root_neighborhood_representative_tips( $tree1, $n, $tip_priority );
2859        newick_subtree( copy_newick_tree( $tree ), \@tips );
2860    }
2861    
2862    
2863    #-------------------------------------------------------------------------------
2864    #  Find n tips to represent tree lineages in vicinity of another tip.
2865    #  Default tip priority is short total branch length.
2866    #
2867    #  \@tips = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
2868    #   @tips = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
2869    #  \@tips = tip_neighborhood_representative_tips( $tree, $tip, $n )
2870    #   @tips = tip_neighborhood_representative_tips( $tree, $tip, $n )
2871    #-------------------------------------------------------------------------------
2872    sub tip_neighborhood_representative_tips
2873    {
2874        my ( $tree, $tip, $n, $tip_priority ) = @_;
2875        array_ref( $tree ) && $tip && ( $n >= 2 ) or return undef;
2876        newick_tip_in_tree( $tree, $tip ) or return undef;
2877    
2878        my @tips = newick_tip_list( $tree );
2879        if ( newick_tip_count( $tree ) - 1 <= $n )
2880        {
2881            @tips = grep { $_ ne $tip } @tips;
2882        }
2883        else
2884        {
2885            my $tree1 = copy_newick_tree( $tree );
2886            $tree1 = reroot_newick_to_tip( $tree1, $tip );
2887            $tree1 = newick_desc_i( $tree1, 1 );        # Node immediately below tip
2888            @tips = root_neighborhood_representative_tips( $tree1, $n, $tip_priority );
2889        }
2890    
2891        wantarray ? @tips : \@tips;
2892    }
2893    
2894    
2895    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2896    #  Anonymous hash of the negative distance from root to each tip:
2897    #
2898    #   \%tip_priority = default_tip_priority( $tree )
2899    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2900    sub default_tip_priority
2901    {
2902        my ( $tree ) = @_;
2903        my $tip_distances = newick_tip_distances( $tree ) || {};
2904        return { map { $_ => -$tip_distances->{$_} } keys %$tip_distances };
2905    }
2906    
2907    
2908    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2909    #  Select a tip from a subtree base on a priority value:
2910    #
2911    #    $tip = representative_tip_of_newick_node( $node, \%tip_priority )
2912    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2913    sub representative_tip_of_newick_node
2914    {
2915        my ( $node, $tip_priority ) = @_;
2916        my ( $tip ) = sort { $b->[1] <=> $a->[1] }   # The best
2917                      map  { [ $_, $tip_priority->{ $_ } ] }
2918                      newick_tip_list( $node );
2919        $tip->[0];                                   # Label from label-priority pair
2920    }
2921    
2922    
2923    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2924    #  Find n subtrees focused around the root of a tree.  Typically each will
2925    #  then be reduced to a single tip to make a representative tree:
2926    #
2927    #   @subtrees = root_proximal_newick_subtrees( $tree, $n )
2928    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2929    sub root_proximal_newick_subtrees
2930    {
2931        my ( $tree, $n ) = @_;
2932        my $node_start_end = newick_branch_intervals( $tree );
2933        n_representative_branches( $n, $node_start_end );
2934    }
2935    
2936    
2937    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2938    #   @node_start_end = newick_branch_intervals( $tree )
2939    #  \@node_start_end = newick_branch_intervals( $tree )
2940    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2941    sub newick_branch_intervals
2942    {
2943        my ( $node, $parent_x ) = @_;
2944        $parent_x ||= 0;
2945        my ( $desc, undef, $dx ) = @$node;
2946        my $x = $parent_x + $dx;
2947        my $interval = [ $node, $parent_x, $desc && @$desc ? $x : 1e100 ];
2948        my @intervals = ( $interval,
2949                          map { &newick_branch_intervals( $_, $x ) } @$desc
2950                        );
2951        return wantarray ? @intervals : \@intervals;
2952    }
2953    
2954    
2955    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2956    #   @ids = n_representative_branches( $n,  @id_start_end )
2957    #   @ids = n_representative_branches( $n, \@id_start_end )
2958    #  \@ids = n_representative_branches( $n,  @id_start_end )
2959    #  \@ids = n_representative_branches( $n, \@id_start_end )
2960    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2961    sub n_representative_branches
2962    {
2963        my $n = shift;
2964        #  Sort intervals by start point:
2965        my @unprocessed = sort { $a->[1] <=> $b->[1] }
2966                          ( @_ == 1 ) ? @{ $_[0] } : @_;
2967        my @active = ();
2968        my ( $interval, $current_point );
2969        foreach $interval ( @unprocessed )
2970        {
2971            $current_point = $interval->[1];
2972            #  Filter out intervals that have ended.  This is N**2 in the number
2973            #  of representatives.  Fixing this would require maintaining a sorted
2974            #  active list.
2975            @active = grep { $_->[2] > $current_point } @active;
2976            push @active, $interval;
2977            last if ( @active >= $n );
2978        }
2979    
2980        my @ids = map { $_->[0] } @active;
2981        return wantarray() ? @ids : \@ids;
2982    }
2983    
2984    
2985  #===============================================================================  #===============================================================================
2986  #  #
2987  #  Tree writing and reading  #  Tree writing and reading
# Line 2553  Line 3149 
3149      my ( $fh, $close ) = open_input( $file );      my ( $fh, $close ) = open_input( $file );
3150      my $tree;      my $tree;
3151      my @lines = ();      my @lines = ();
3152      while ( defined( $_ = <$fh> ) )      foreach ( <$fh> )
3153      {      {
3154          chomp;          chomp;
3155          push @lines, $_;          push @lines, $_;
# Line 2575  Line 3171 
3171      my ( $fh, $close ) = open_input( $file );      my ( $fh, $close ) = open_input( $file );
3172      my @trees = ();      my @trees = ();
3173      my @lines = ();      my @lines = ();
3174      while ( defined( $_ = <$fh> ) )      foreach ( <$fh> )
3175      {      {
3176          chomp;          chomp;
3177          push @lines, $_;          push @lines, $_;
# Line 2762  Line 3358 
3358      #  Loop while it is a comment:      #  Loop while it is a comment:
3359      while ( substr( $s, $ind, 1 ) eq "[" ) {      while ( substr( $s, $ind, 1 ) eq "[" ) {
3360          $ind++;          $ind++;
3361            my $depth = 1;
3362            my $ind2  = $ind;
3363    
3364          #  Find end          #  Find end
3365          if ( substr( $s, $ind ) !~ /^([^]]*)\]/ ) {          while ( $depth > 0 )
3366            {
3367                if ( substr( $s, $ind2 ) =~ /^([^][]*\[)/ )     # nested [ ... ]
3368                {
3369                    $ind2 += length( $1 );  #  Points at char just past [
3370                    $depth++;               #  If nested comments are allowed
3371                }
3372                elsif ( substr( $s, $ind2 ) =~ /^([^][]*\])/ )  # close bracket
3373                {
3374                    $ind2 += length( $1 );  #  Points at char just past ]
3375                    $depth--;
3376                }
3377                else
3378                {
3379              treeParseError( "comment missing closing bracket '["              treeParseError( "comment missing closing bracket '["
3380                             . substr( $s, $ind ) . "'" )                             . substr( $s, $ind ) . "'" )
3381          }          }
3382          my $comment = $1;          }
3383    
3384          #  Save if it includes any "text"          my $comment = substr( $s, $ind, $ind2-$ind-1 );
3385          if ( $comment =~ m/\S/ ) { push @clist, $comment }          if ( $comment =~ m/\S/ ) { push @clist, $comment }
3386    
3387          $ind += length( $comment ) + 1;     #  Comment plus closing bracket          $ind = $ind2;
3388    
3389          #  Skip white space          #  Skip white space
3390          if ( substr( $s, $ind ) =~ /^(\s+)/ ) { $ind += length( $1 ) }          if ( substr( $s, $ind ) =~ /^(\s+)/ ) { $ind += length( $1 ) }
# Line 2792  Line 3403 
3403  #===============================================================================  #===============================================================================
3404  #  Make a printer plot of a tree:  #  Make a printer plot of a tree:
3405  #  #
3406  #     $node   newick tree root node  #  printer_plot_newick( $node, $file, $width, $min_dx, $dy )
3407  #     $file   undef (= \*STDOUT), \*STDOUT, \*STDERR, or a file name.  #  printer_plot_newick( $node, $file, \%options )
3408  #     $width  the approximate characters for the tree without labels  #
3409  #     $min_dx the minimum horizontal branch length  #     $node   # newick tree root node
3410  #     $dy     the vertical space per taxon  #     $file   # undef = \*STDOUT, \*FH, or a file name.
3411    #     $width  # the approximate characters for the tree without labels (D = 68)
3412    #     $min_dx # the minimum horizontal branch length (D = 2)
3413    #     $dy     # the vertical space per taxon (D = 1, most compressed)
3414    #
3415    #  Options:
3416    #
3417    #    dy     => nat_number    # the vertical space per taxon
3418    #    chars  => key           # line drawing character set:
3419    #                            #     html_unicode
3420    #                            #     text (default)
3421    #    min_dx => whole_number  # the minimum horizontal branch length
3422    #    width  => whole_number  # approximate tree width without labels
3423  #  #
 #  printer_plot_newick( $node, $file (D=\*STDOUT), $width (D=68), $min_dx (D=2), $dy (D=1) )  
3424  #===============================================================================  #===============================================================================
3425  sub printer_plot_newick {  sub printer_plot_newick
3426      my ( $node, $file, $width, $min_dx, $dy ) = @_;  {
3427        my ( $node, $file, @opts ) = @_;
3428    
3429      my ( $fh, $close ) = open_output( $file );      my ( $fh, $close ) = open_output( $file );
3430      $fh or return;      $fh or return;
3431    
3432      print $fh join( "\n", text_plot_newick( $node, $width, $min_dx, $dy ) ), "\n";      my $html = $opts[0] && ref($opts[0]) eq 'HASH'
3433                            && $opts[0]->{ chars }
3434                            && $opts[0]->{ chars } =~ /html/;
3435        print $fh '<PRE>' if $html;
3436        print $fh join( "\n", text_plot_newick( $node, @opts ) ), "\n";
3437        print $fh "</PRE>\n" if $html;
3438    
3439      if ( $close ) { close $fh }      if ( $close ) { close $fh }
3440  }  }
3441    
3442    
3443  #===============================================================================  #===============================================================================
3444    #  Character sets for printer plot trees:
3445    #-------------------------------------------------------------------------------
3446    
3447    my %char_set =
3448      ( text1     => { space  => ' ',
3449                       horiz  => '-',
3450                       vert   => '|',
3451                       el_d_r => '/',
3452                       el_u_r => '\\',
3453                       el_d_l => '\\',
3454                       el_u_l => '/',
3455                       tee_l  => '+',
3456                       tee_r  => '+',
3457                       tee_u  => '+',
3458                       tee_d  => '+',
3459                       half_l => '-',
3460                       half_r => '-',
3461                       half_u => '|',
3462                       half_d => '|',
3463                       cross  => '+',
3464                     },
3465        text2     => { space  => ' ',
3466                       horiz  => '-',
3467                       vert   => '|',
3468                       el_d_r => '+',
3469                       el_u_r => '+',
3470                       el_d_l => '+',
3471                       el_u_l => '+',
3472                       tee_l  => '+',
3473                       tee_r  => '+',
3474                       tee_u  => '+',
3475                       tee_d  => '+',
3476                       half_l => '-',
3477                       half_r => '-',
3478                       half_u => '|',
3479                       half_d => '|',
3480                       cross  => '+',
3481                     },
3482        html_box  => { space  => '&nbsp;',
3483                       horiz  => '&#9472;',
3484                       vert   => '&#9474;',
3485                       el_d_r => '&#9484;',
3486                       el_u_r => '&#9492;',
3487                       el_d_l => '&#9488;',
3488                       el_u_l => '&#9496;',
3489                       tee_l  => '&#9508;',
3490                       tee_r  => '&#9500;',
3491                       tee_u  => '&#9524;',
3492                       tee_d  => '&#9516;',
3493                       half_l => '&#9588;',
3494                       half_r => '&#9590;',
3495                       half_u => '&#9589;',
3496                       half_d => '&#9591;',
3497                       cross  => '&#9532;',
3498                     },
3499        utf8_box  => { space  => ' ',
3500                       horiz  => chr(226) . chr(148) . chr(128),
3501                       vert   => chr(226) . chr(148) . chr(130),
3502                       el_d_r => chr(226) . chr(148) . chr(140),
3503                       el_u_r => chr(226) . chr(148) . chr(148),
3504                       el_d_l => chr(226) . chr(148) . chr(144),
3505                       el_u_l => chr(226) . chr(148) . chr(152),
3506                       tee_l  => chr(226) . chr(148) . chr(164),
3507                       tee_r  => chr(226) . chr(148) . chr(156),
3508                       tee_u  => chr(226) . chr(148) . chr(180),
3509                       tee_d  => chr(226) . chr(148) . chr(172),
3510                       half_l => chr(226) . chr(149) . chr(180),
3511                       half_r => chr(226) . chr(149) . chr(182),
3512                       half_u => chr(226) . chr(149) . chr(181),
3513                       half_d => chr(226) . chr(149) . chr(183),
3514                       cross  => chr(226) . chr(148) . chr(188),
3515                     },
3516      );
3517    
3518    %{ $char_set{ html1 } } = %{ $char_set{ text1 } };
3519    $char_set{ html1 }->{ space } = '&nbsp;';
3520    
3521    %{ $char_set{ html2 } } = %{ $char_set{ text2 } };
3522    $char_set{ html2 }->{ space } = '&nbsp;';
3523    
3524    #  Define some synonyms
3525    
3526    $char_set{ html } = $char_set{ html_box };
3527    $char_set{ line } = $char_set{ utf8_box };
3528    $char_set{ symb } = $char_set{ utf8_box };
3529    $char_set{ text } = $char_set{ text1 };
3530    $char_set{ utf8 } = $char_set{ utf8_box };
3531    
3532    #  Define tree formats and synonyms
3533    
3534    my %tree_format =
3535        ( text         => 'text',
3536          tree_tab_lbl => 'tree_tab_lbl',
3537          tree_lbl     => 'tree_lbl',
3538          chrlist_lbl  => 'chrlist_lbl',
3539          raw          => 'chrlist_lbl',
3540        );
3541    
3542    #===============================================================================
3543  #  Make a text plot of a tree:  #  Make a text plot of a tree:
3544  #  #
3545  #     $node   newick tree root node  #  @lines = text_plot_newick( $node, $width, $min_dx, $dy )
3546  #     $width  the approximate characters for the tree without labels  #  @lines = text_plot_newick( $node, \%options )
3547  #     $min_dx the minimum horizontal branch length  #
3548  #     $dy     the vertical space per taxon  #     $node   # newick tree root node
3549    #     $width  # the approximate characters for the tree without labels (D = 68)
3550    #     $min_dx # the minimum horizontal branch length (D = 2)
3551    #     $dy     # the vertical space per taxon (D = 1, most compressed)
3552    #
3553    #  Options:
3554    #
3555    #    chars  => keyword       # the output character set for the tree
3556    #    dy     => nat_number    # the vertical space per taxon
3557    #    format => keyword       # output format of each line
3558    #    min_dx => whole_number  # the minimum horizontal branch length
3559    #    width  => whole_number  # approximate tree width without labels
3560    #
3561    #  Character sets:
3562    #
3563    #    html       #  synonym of html1
3564    #    html_box   #  html encoding of unicode box drawing characters
3565    #    html1      #  text1 with nonbreaking spaces
3566    #    html2      #  text2 with nonbreaking spaces
3567    #    line       #  synonym of utf8_box
3568    #    raw        #  pass out the internal representation
3569    #    symb       #  synonym of utf8_box
3570    #    text       #  synonym of text1 (Default)
3571    #    text1      #  ascii characters: - + | / \ and space
3572    #    text2      #  ascii characters: - + | + + and space
3573    #    utf8       #  synonym of utf8_box
3574    #    utf8_box   #  utf8 encoding of unicode box drawing characters
3575    #
3576    #  Formats for row lines:
3577    #
3578    #    text           #    $textstring              # Default
3579    #    tree_tab_lbl   #    $treestr \t $labelstr
3580    #    tree_lbl       # [  $treestr,  $labelstr ]
3581    #    chrlist_lbl    # [ \@treechar, $labelstr ]   # Forced with raw chars
3582    #    raw            #  synonym of chrlist_lbl
3583  #  #
 #  @textlines = text_plot_newick( $node, $width (D=68), $min_dx (D=2), $dy (D=1) )  
3584  #===============================================================================  #===============================================================================
3585  sub text_plot_newick {  sub text_plot_newick
3586      my ( $node, $width, $min_dx, $dy ) = @_;  {
3587        my $node = shift @_;
3588      array_ref( $node ) || die "Bad node passed to text_plot_newick\n";      array_ref( $node ) || die "Bad node passed to text_plot_newick\n";
3589      defined( $min_dx ) and ( $min_dx >=  0 ) or $min_dx =  2;  
3590      defined(     $dy ) and (     $dy >=  1 ) or     $dy =  1;      my ( $opts, $width, $min_dx, $dy, $chars, $fmt );
3591      defined( $width  )                       or  $width = 68;      if ( $_[0] && ref $_[0] eq 'HASH' )
3592        {
3593            $opts = shift;
3594        }
3595        else
3596        {
3597            ( $width, $min_dx, $dy ) = @_;
3598            $opts = {};
3599        }
3600    
3601        $chars = $opts->{ chars } || '';
3602        my $charH;
3603        $charH = $char_set{ $chars } || $char_set{ 'text1' } if ( $chars ne 'raw' );
3604        my $is_box = $charH eq $char_set{ html_box }
3605                  || $charH eq $char_set{ utf8_box }
3606                  || $chars eq 'raw';
3607    
3608        $fmt = ( $chars eq 'raw' ) ? 'chrlist_lbl' : $opts->{ format };
3609        $fmt = $tree_format{ $fmt || '' } || 'text';
3610    
3611        $dy    ||= $opts->{ dy     } ||  1;
3612        $width ||= $opts->{ width  } || 68;
3613        $min_dx  = $opts->{ min_dx } if ( ! defined $min_dx || $min_dx < 0 );
3614        $min_dx  = $is_box ? 1 : 2   if ( ! defined $min_dx || $min_dx < 0 );
3615    
3616        #  Layout the tree:
3617    
3618      $min_dx = int( $min_dx );      $min_dx = int( $min_dx );
3619      $dy     = int( $dy );      $dy     = int( $dy );
# Line 2835  Line 3622 
3622      my $hash = {};      my $hash = {};
3623      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 );
3624    
3625      # dump_tree_hash( $node, $hash ); exit;      #  Generate the lines of the tree-one by-one:
   
     #  Generate the lines of the tree one by one:  
3626    
3627      my ( $y1, $y2 ) = @{ $hash->{ $node } };      my ( $y1, $y2 ) = @{ $hash->{ $node } };
3628      map { text_tree_row( $node, $hash, $_, "", "+" ) } ( $y1 .. $y2 );      my @lines;
3629        foreach ( ( $y1 .. $y2 ) )
3630        {
3631            my $line = text_tree_row( $node, $hash, $_, [], 'tee_l', $dy >= 2 );
3632            my $lbl  = '';
3633            if ( @$line )
3634            {
3635                if ( $line->[-1] eq '' ) { pop @$line; $lbl = pop @$line }
3636                #  Translate tree characters
3637                @$line = map { $charH->{ $_ } } @$line if $chars ne 'raw';
3638            }
3639    
3640            # Convert to requested output format:
3641    
3642            push @lines, $fmt eq 'text'         ? join( '', @$line, ( $lbl ? " $lbl" : () ) )
3643                       : $fmt eq 'text_tab_lbl' ? join( '', @$line, "\t", $lbl )
3644                       : $fmt eq 'tree_lbl'     ? [ join( '', @$line ), $lbl ]
3645                       : $fmt eq 'chrlist_lbl'  ? [ $line, $lbl ]
3646                       :                          ();
3647        }
3648    
3649        # if ( $cells )
3650        # {
3651        #     my $nmax = 0;
3652        #     foreach ( @lines ) { $nmax = @$_ if @$_ > $nmax }
3653        #     foreach ( @lines )
3654        #     {
3655        #         @$_ = map { "<TD>$_</TD>" } @$_;
3656        #         my $span = $nmax - @$_ + 1;
3657        #         $_->[-1] =~ s/^<TD>/<TD NoWrap ColSpan=$span>/;
3658        #     }
3659        # }
3660        # elsif ( $tables )
3661        # {
3662        #     my $nmax = 0;
3663        #     foreach ( @lines ) { $nmax = @$_ if @$_ > $nmax }
3664        #     foreach ( @lines )
3665        #     {
3666        #         @$_ = map { "<TD>$_</TD>" } @$_;
3667        #         my $span = $nmax - @$_ + 1;
3668        #         $_->[-1] =~ s/^<TD>/<TD NoWrap ColSpan=$span>/;
3669        #     }
3670        # }
3671    
3672        wantarray ? @lines : \@lines;
3673  }  }
3674    
3675    
3676  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3677  #  ( $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 )
3678  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3679  sub layout_printer_plot {  sub layout_printer_plot
3680      my ( $node, $hash, $x0, $y0, $x_scale, $min_dx, $dy ) = @_;  {
3681        my ( $node, $hash, $x0, $y0, $x_scale, $min_dx, $dy, $yrnd ) = @_;
3682      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";
3683      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";
3684    
3685      my $dx = newick_x( $node );      my $dx = newick_x( $node );
3686      if ( defined( $dx ) ) {      if ( defined( $dx ) ) {
3687          $dx *= $x_scale;          $dx *= $x_scale;
3688          $dx >= $min_dx or $dx = $min_dx;          $dx = $min_dx if $dx < $min_dx;
3689      }      }
3690      else {      else {
3691          $dx = ( $x0 > 0 ) ? $min_dx : 0;          $dx = ( $x0 > 0 ) ? $min_dx : 0;
# Line 2881  Line 3712 
3712          $ymax = $y0;          $ymax = $y0;
3713    
3714          foreach ( @dl ) {          foreach ( @dl ) {
3715              ( $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,
3716                                                              ( 2*@ylist < @dl ? 0.5001 : 0.4999 )
3717                                                            );
3718              push @ylist, $yi;              push @ylist, $yi;
3719              if ( $xmaxi > $xmax ) { $xmax = $xmaxi }              if ( $xmaxi > $xmax ) { $xmax = $xmaxi }
3720          }          }
# Line 2891  Line 3724 
3724    
3725          $yn1 = $ylist[ 0];          $yn1 = $ylist[ 0];
3726          $yn2 = $ylist[-1];          $yn2 = $ylist[-1];
3727          $y = int( 0.5 * ( $yn1 + $yn2 ) + 0.4999 );          $y   = int( 0.5 * ( $yn1 + $yn2 ) + ( $yrnd || 0.4999 ) );
3728    
3729            #  Handle special case of internal node label. Put it between subtrees.
3730    
3731            if ( ( $dy >= 2 ) && newick_lbl( $node ) && ( @dl > 1 ) ) {
3732                #  Find the descendents $i1 and $i2 to put the branch between
3733                my $i2 = 1;
3734                while ( ( $i2+1 < @ylist ) && ( $ylist[$i2] < $y ) ) { $i2++ }
3735                my $i1 = $i2 - 1;
3736                #  Get bottom of subtree1 and top of subtree2:
3737                my $ymax1 = $hash->{ $dl[ $i1 ] }->[ 1 ];
3738                my $ymin2 = $hash->{ $dl[ $i2 ] }->[ 0 ];
3739                #  Midway between bottom of subtree1 and top of subtree2, with
3740                #  preferred rounding direction
3741                $y = int( 0.5 * ( $ymax1 + $ymin2 ) + ( $yrnd || 0.4999 ) );
3742            }
3743      }      }
3744    
3745      $y2 = int( $ymax - 0.5 * $dy + 0.4999 );      $y2 = int( $ymax - 0.5 * $dy + 0.4999 );
# Line 2901  Line 3749 
3749  }  }
3750    
3751    
3752  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #  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 . "  " ) }  
 }  
3753    
3754    my %with_left_line = ( space  => 'half_l',
3755                           horiz  => 'horiz',
3756                           vert   => 'tee_l',
3757                           el_d_r => 'tee_d',
3758                           el_u_r => 'tee_u',
3759                           el_d_l => 'el_d_l',
3760                           el_u_l => 'el_u_l',
3761                           tee_l  => 'tee_l',
3762                           tee_r  => 'cross',
3763                           tee_u  => 'tee_u',
3764                           tee_d  => 'tee_d',
3765                           half_l => 'half_l',
3766                           half_r => 'horiz',
3767                           half_u => 'el_u_l',
3768                           half_d => 'el_d_l',
3769                           cross  => 'cross',
3770                         );
3771    
3772  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3773  #  $line = text_tree_row( $node, $hash, $row, $line, $symb )  #  Produce a description of one line of a printer plot tree.
3774    #
3775    #  \@line = text_tree_row( $node, $hash, $row, \@line, $symb, $ilbl )
3776    #
3777    #     \@line is the character descriptions accumulated so far, one per array
3778    #          element, except for a label, which can be any number of characters.
3779    #          Labels are followed by an empty string, so if $line->[-1] eq '',
3780    #          then $line->[-2] is a label. The calling program translates the
3781    #          symbol names to output characters.
3782    #
3783    #     \@node is a newick tree node
3784    #     \%hash contains tree layout information
3785    #      $row  is the row number (y value) that we are building
3786    #      $symb is the plot symbol proposed for the current x and y position
3787    #      $ilbl is true if internal node labels are allowed
3788    #
3789  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3790  sub text_tree_row {  sub text_tree_row
3791      my ( $node, $hash, $row, $line, $symb ) = @_;  {
3792        my ( $node, $hash, $row, $line, $symb, $ilbl ) = @_;
3793    
3794      my ( $y1, $y2, $x0, $x, $y, $yn1, $yn2 ) = @{ $hash->{ $node } };      my ( $y1, $y2, $x0, $x, $y, $yn1, $yn2 ) = @{ $hash->{ $node } };
3795      if ( $row < $y1 || $row > $y2 ) { return $line }      if ( $row < $y1 || $row > $y2 ) { return $line }
3796    
3797      if ( length( $line ) < $x0 ) { $line .= " " x ( $x0 - length( $line ) ) }      if ( @$line < $x0 ) { push @$line, ('space') x ( $x0 - @$line ) }
3798    
3799      if ( $row == $y ) {      if ( $row == $y ) {
3800          $line = substr( $line, 0, $x0 ) . $symb . (( $x > $x0 ) ? "-" x ($x - $x0) : "");          while ( @$line > $x0 ) { pop @$line }  # Actually 0-1 times
3801            push @$line, $symb,
3802                         ( ( $x > $x0 ) ? ('horiz') x ($x - $x0) : () );
3803      }      }
3804    
3805      elsif ( $row > $yn1 && $row < $yn2 ) {      elsif ( $row > $yn1 && $row < $yn2 ) {
3806          if ( length( $line ) < $x ) { $line .= " " x ( $x - length( $line ) ) . "|" }          if ( @$line < $x ) { push @$line, ('space') x ( $x - @$line ), 'vert' }
3807          else { substr( $line, $x ) = "|" }          else               { $line->[$x] = 'vert' }
3808      }      }
3809    
3810      my @dl = newick_desc_list( $node );      my @dl = newick_desc_list( $node );
3811    
3812      if ( @dl < 1 ) {      if ( @dl < 1 ) { push @$line, ( newick_lbl( $node ) || '' ), '' }
         $line .= " " . $node->[1];  
     }  
3813    
3814      else {      else {
3815          my @list = map { [ $_, "+" ] } @dl;  #  Print symbol for line          my @list = map { [ $_, 'tee_r' ] } @dl;  # Line to the right
3816          $list[ 0]->[1] = "/";          if ( @list > 1 ) { #  Fix top and bottom sympbols
3817          $list[-1]->[1] = "\\";              $list[ 0]->[1] = 'el_d_r';
3818                $list[-1]->[1] = 'el_u_r';
3819            }
3820            elsif ( @list ) {  # Only one descendent
3821                $list[ 0]->[1] = 'half_r';
3822            }
3823          foreach ( @list ) {          foreach ( @list ) {
3824              my ( $n, $s ) = @$_;              my ( $n, $s ) = @$_;
3825              if ( $row >= $hash->{ $n }->[0] && $row <= $hash->{ $n }->[1] ) {              if ( $row >= $hash->{ $n }->[0] && $row <= $hash->{ $n }->[1] ) {
3826                  $line = text_tree_row( $n, $hash, $row, $line, $s );                  $line = text_tree_row( $n, $hash, $row, $line, $s, $ilbl );
3827              }              }
3828           }           }
3829    
3830          if ( $row == $y ) { substr( $line, $x, 1 ) = "+" }          if ( $row == $y ) {
3831                $line->[$x] = ( $line->[$x] eq 'horiz' ) ? 'tee_l'
3832                                                         : $with_left_line{ $line->[$x] };
3833                push( @$line, newick_lbl( $node ), '' ) if $ilbl && newick_lbl( $node );
3834            }
3835      }      }
3836    
3837      return $line;      return $line;
3838  }  }
3839    
3840    
3841    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3842    #  Debug routine
3843    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3844    sub dump_tree {
3845        my ( $node, $prefix ) = @_;
3846        defined( $prefix ) or $prefix = "";
3847        print STDERR $prefix, join(", ", @$node), "\n";
3848        my @dl = $node->[0] ? @{$node->[0]} : ();
3849        foreach ( @dl ) { dump_tree( $_, $prefix . "  " ) }
3850        $prefix or print STDERR "\n";
3851    }
3852    
3853    
3854    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3855    #  Debug routine
3856    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
3857    sub dump_tree_hash {
3858        my ( $node, $hash, $prefix ) = @_;
3859        defined( $prefix ) or print STDERR "node; [ y1, y2, x0, x, y, yn1, yn2 ]\n" and $prefix = "";
3860        print STDERR $prefix, join(", ", @$node), "; ", join(", ", @{ $hash->{ $node } } ), "\n";
3861        my @dl = $node->[0] ? @{$node->[0]} : ();
3862        foreach (@dl) { dump_tree_hash( $_, $hash, $prefix . "  " ) }
3863    }
3864    
3865    
3866  #===============================================================================  #===============================================================================
3867  #  Open an input file stream:  #  Open an input file stream:
3868  #  #
# Line 2983  Line 3875 
3875  {  {
3876      my $file = shift;      my $file = shift;
3877      my $fh;      my $fh;
3878      if    ( ! defined( $file ) )     { return ( \*STDIN ) }      if    ( ! defined $file || $file eq '' ) { return ( \*STDIN ) }
3879      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file   ) }      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file   ) }
3880      elsif ( open( $fh, "<$file" ) )  { return ( $fh, 1  ) } # Need to close      elsif ( open( $fh, "<$file" ) )  { return ( $fh, 1  ) } # Need to close
3881    
# Line 3004  Line 3896 
3896  {  {
3897      my $file = shift;      my $file = shift;
3898      my $fh;      my $fh;
3899      if    ( ! defined( $file ) )     { return ( \*STDOUT ) }      if    ( ! defined $file || $file eq '' ) { return ( \*STDOUT ) }
3900      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file    ) }      elsif ( ref( $file ) eq 'GLOB' ) { return ( $file    ) }
3901      elsif ( ( open $fh, ">$file" ) ) { return ( $fh, 1   ) } # Need to close      elsif ( ( open $fh, ">$file" ) ) { return ( $fh, 1   ) } # Need to close
3902    
# Line 3012  Line 3904 
3904      return undef;      return undef;
3905  }  }
3906    
3907    
3908    #===============================================================================
3909    #  Some subroutines copied from gjolists
3910    #===============================================================================
3911    #  Return the common prefix of two lists:
3912    #
3913    #  @common = common_prefix( \@list1, \@list2 )
3914    #-----------------------------------------------------------------------------
3915    sub common_prefix
3916    {
3917        my ($l1, $l2) = @_;
3918        ref($l1) eq "ARRAY" || die "common_prefix: arg 1 is not an array ref\n";
3919        ref($l2) eq "ARRAY" || die "common_prefix: arg 2 is not an array ref\n";
3920    
3921        my $i = 0;
3922        my $l1_i;
3923        while ( defined( $l1_i = $l1->[$i] ) && $l1_i eq $l2->[$i] ) { $i++ }
3924    
3925        return @$l1[ 0 .. ($i-1) ];  # perl handles negative range
3926    }
3927    
3928    
3929    #-----------------------------------------------------------------------------
3930    #  Return the unique suffixes of each of two lists:
3931    #
3932    #  ( \@suffix1, \@suffix2 ) = unique_suffixes( \@list1, \@list2 )
3933    #-----------------------------------------------------------------------------
3934    sub unique_suffixes
3935    {
3936        my ($l1, $l2) = @_;
3937        ref($l1) eq "ARRAY" || die "common_prefix: arg 1 is not an array ref\n";
3938        ref($l2) eq "ARRAY" || die "common_prefix: arg 2 is not an array ref\n";
3939    
3940        my $i = 0;
3941        my @l1 = @$l1;
3942        my @l2 = @$l2;
3943        my $l1_i;
3944        while ( defined( $l1_i = $l1[$i] ) && $l1_i eq $l2[$i] ) { $i++ }
3945    
3946        splice @l1, 0, $i;
3947        splice @l2, 0, $i;
3948        return ( \@l1, \@l2 );
3949    }
3950    
3951    
3952    #-------------------------------------------------------------------------------
3953    #  List of values duplicated in a list (stable in order by second occurance):
3954    #
3955    #  @dups = duplicates( @list )
3956    #-------------------------------------------------------------------------------
3957    sub duplicates
3958    {
3959        my %cnt = ();
3960        grep { ++$cnt{$_} == 2 } @_;
3961    }
3962    
3963    
3964    #-------------------------------------------------------------------------------
3965    #  Randomize the order of a list:
3966    #
3967    #  @random = random_order( @list )
3968    #-------------------------------------------------------------------------------
3969    sub random_order
3970    {
3971        my ( $i, $j );
3972        for ( $i = @_ - 1; $i > 0; $i-- )
3973        {
3974            $j = int( ($i+1) * rand() );
3975            ( $_[$i], $_[$j] ) = ( $_[$j], $_[$i] ); # Interchange i and j
3976        }
3977    
3978       @_;
3979    }
3980    
3981    
3982    #-----------------------------------------------------------------------------
3983    #  Intersection of two or more sets:
3984    #
3985    #  @intersection = intersection( \@set1, \@set2, ... )
3986    #-----------------------------------------------------------------------------
3987    sub intersection
3988    {
3989        my $set = shift;
3990        my @intersection = @$set;
3991    
3992        foreach $set ( @_ )
3993        {
3994            my %set = map { $_ => 1 } @$set;
3995            @intersection = grep { exists $set{ $_ } } @intersection;
3996        }
3997    
3998        @intersection;
3999    }
4000    
4001    
4002    #-----------------------------------------------------------------------------
4003    #  Elements in set 1, but not set 2:
4004    #
4005    #  @difference = set_difference( \@set1, \@set2 )
4006    #-----------------------------------------------------------------------------
4007    sub set_difference
4008    {
4009        my ($set1, $set2) = @_;
4010        my %set2 = map { $_ => 1 } @$set2;
4011        grep { ! ( exists $set2{$_} ) } @$set1;
4012    }
4013    
4014    
4015  1;  1;

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

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3