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

Diff of /FigKernelPackages/gjonewicklib.pm

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

revision 1.5, Tue Dec 19 17:32:48 2006 UTC revision 1.12, Mon Jun 22 19:14:50 2009 UTC
# Line 1  Line 1 
1  #  #
2  # Copyright (c) 2003-2006 University of Chicago and Fellowship  # Copyright (c) 2003-2007 University of Chicago and Fellowship
3  # for Interpretations of Genomes. All Rights Reserved.  # for Interpretations of Genomes. All Rights Reserved.
4  #  #
5  # This file is part of the SEED Toolkit.  # This file is part of the SEED Toolkit.
# Line 44  Line 44 
44  #  #
45  #     $tree = \@rootnode;  #     $tree = \@rootnode;
46  #  #
47  #     @node = ( \@desc,  #  reference to list of descendants  #     $node = [ \@desc,  #  reference to list of descendants
48  #                $label, #  node label  #                $label, #  node label
49  #                $x,     #  branch length  #                $x,     #  branch length
50  #               \@c1,    #  reference to comment list 1  #               \@c1,    #  reference to comment list 1
# Line 52  Line 52 
52  #               \@c3,    #  reference to comment list 3  #               \@c3,    #  reference to comment list 3
53  #               \@c4,    #  reference to comment list 4  #               \@c4,    #  reference to comment list 4
54  #               \@c5     #  reference to comment list 5  #               \@c5     #  reference to comment list 5
55  #             )  #             ]
56  #  #
57  #  At present, no routine tests or enforces the length of the list (a single  #  At present, no routine tests or enforces the length of the list (a single
58  #  element list could be a valid internal node).  #  element list could be a valid internal node).
# Line 63  Line 63 
63  #  time, but is different from the prolog representation.  #  time, but is different from the prolog representation.
64  #  #
65  #  #
66    #  Ross Overbeek has a different tree node structure:
67    #
68    #     $node = [ Label,
69    #               DistanceToParent,
70    #               [ ParentPointer, ChildPointer1, ... ],
71    #               [ Name1\tVal1, Name2\tVal2, ... ]
72    #             ]
73    #
74    #  So:
75    #
76    #===============================================================================
77    #  Tree format interconversion:
78    #===============================================================================
79    #
80    #  $bool      = is_overbeek_tree( $tree )
81    #  $bool      = is_gjonewick_tree( $tree )
82    #
83    #  $gjonewick = overbeek_to_gjonewick( $overbeek )
84    #  $overbeek  = gjonewick_to_overbeek( $gjonewick )
85    #
86  #===============================================================================  #===============================================================================
87  #  Tree data extraction:  #  Tree data extraction:
88  #===============================================================================  #===============================================================================
# Line 90  Line 110 
110  #  set_newick_c4( $noderef, $listref )  #  set_newick_c4( $noderef, $listref )
111  #  set_newick_c5( $noderef, $listref )  #  set_newick_c5( $noderef, $listref )
112  #  set_newick_desc_list( $noderef, @desclist )  #  set_newick_desc_list( $noderef, @desclist )
113  #  set_newick_desc_i( $noderef1, $i, $noderef2)  #  set_newick_desc_i( $noderef1, $i, $noderef2 )  # 1-based numbering
114    #
115    #  $bool    = newick_is_valid( $noderef )       # verify that tree is valid
116  #  #
117  #  $bool    = newick_is_rooted( $noderef )      # 2 branches from root  #  $bool    = newick_is_rooted( $noderef )      # 2 branches from root
118  #  $bool    = newick_is_unrooted( $noderef )    # 3 or more branches from root  #  $bool    = newick_is_unrooted( $noderef )    # 3 or more branches from root
# Line 99  Line 121 
121  #  #
122  #  $n       = newick_tip_count( $noderef )  #  $n       = newick_tip_count( $noderef )
123  #  @tiprefs = newick_tip_ref_list( $noderef )  #  @tiprefs = newick_tip_ref_list( $noderef )
124    # \@tiprefs = newick_tip_ref_list( $noderef )
125  #  @tips    = newick_tip_list( $noderef )  #  @tips    = newick_tip_list( $noderef )
126    # \@tips    = newick_tip_list( $noderef )
127    #
128  #  $tipref  = newick_first_tip_ref( $noderef )  #  $tipref  = newick_first_tip_ref( $noderef )
129  #  $tip     = newick_first_tip( $noderef )  #  $tip     = newick_first_tip( $noderef )
130    #
131  #  @tips    = newick_duplicated_tips( $noderef )  #  @tips    = newick_duplicated_tips( $noderef )
132    # \@tips    = newick_duplicated_tips( $noderef )
133    #
134  #  $bool    = newick_tip_in_tree( $noderef, $tipname )  #  $bool    = newick_tip_in_tree( $noderef, $tipname )
135    #
136  #  @tips    = newick_shared_tips( $tree1, $tree2 )  #  @tips    = newick_shared_tips( $tree1, $tree2 )
137    # \@tips    = newick_shared_tips( $tree1, $tree2 )
138  #  #
139  #  $length  = newick_tree_length( $noderef )  #  $length  = newick_tree_length( $noderef )
140    #
141    #  %tip_distances = newick_tip_distances( $noderef )
142    # \%tip_distances = newick_tip_distances( $noderef )
143    #
144  #  $xmax    = newick_max_X( $noderef )  #  $xmax    = newick_max_X( $noderef )
145  #  ( $tipref,  $xmax ) = newick_most_distant_tip_ref( $noderef )  #  ( $tipref,  $xmax ) = newick_most_distant_tip_ref( $noderef )
146  #  ( $tipname, $xmax ) = newick_most_distant_tip( $noderef )  #  ( $tipname, $xmax ) = newick_most_distant_tip_name( $noderef )
147    #
148    #  Tree tip insertion point (tip is on branch of length x that
149    #  is inserted into branch connecting node1 and node2, a distance
150    #  x1 from node1 and x2 from node2):
151    #
152    #  [ $node1, $x1, $node2, $x2, $x ] = newick_tip_insertion_point( $tree, $tip )
153    #
154    #  Standardized label for a node in terms of intersection of 3 lowest sorting
155    #  tips (sort is lower case):
156    #
157    #  @TipOrTips = std_node_name( $tree, $node )
158  #  #
159  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
160  #  Paths from root of tree:  #  Paths from root of tree:
# Line 140  Line 185 
185  #  $treecopy = copy_newick_tree( $tree )  #  $treecopy = copy_newick_tree( $tree )
186  #  #
187  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
188  #  The following modify the existing tree, and passibly any components of that  #  The following modify the existing tree, and possibly any components of that
189  #  tree that are reached by reference.  If the old version is still needed, copy  #  tree that are reached by reference.  If the old version is still needed, copy
190  #  before modifying.  #  before modifying.
191  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
# Line 157  Line 202 
202  #  $n_changed = newick_set_undefined_branches( $node, $x )  #  $n_changed = newick_set_undefined_branches( $node, $x )
203  #  $n_changed = newick_set_all_branches( $node, $x )  #  $n_changed = newick_set_all_branches( $node, $x )
204  #  $n_changed = newick_fix_negative_branches( $tree )  #  $n_changed = newick_fix_negative_branches( $tree )
205    #  $node      = newick_rescale_branches( $node, $factor )
206    #
207    #  Modify comments:
208    #
209    #  $node = newick_strip_comments( $node )
210  #  #
211  #  Modify rooting and/or order:  #  Modify rooting and/or order:
212  #  #
# Line 170  Line 220 
220  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )  #  $newtree = reroot_newick_next_to_tip( $tree, $tip )
221  #  $newtree = reroot_newick_to_node( $tree, @node )  #  $newtree = reroot_newick_to_node( $tree, @node )
222  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )
223  #  $newtree = reroot_newick_to_node_ref( $tree, $noderef )  #  $newtree = reroot_newick_between_nodes( $tree, $node1, $node2, $fraction )
224    #  $newtree = reroot_newick_to_midpoint( $tree )           # unweighted
225    #  $newtree = reroot_newick_to_midpoint_w( $tree )         # weight by tips
226  #  $newtree = reroot_newick_to_approx_midpoint( $tree )    # unweighted  #  $newtree = reroot_newick_to_approx_midpoint( $tree )    # unweighted
227  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  # weight by tips  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  # weight by tips
228  #  $newtree = uproot_tip_rooted_newick( $tree )  #  $newtree = uproot_tip_rooted_newick( $tree )
229  #  $newtree = uproot_newick( $tree )  #  $newtree = uproot_newick( $tree )
230  #  #
231  #  $newtree = prune_from_newick( $tree, $tip )  #  $newtree = prune_from_newick( $tree, $tip )
232    #  $newtree = rooted_newick_subtree( $tree,  @tips )
233    #  $newtree = rooted_newick_subtree( $tree, \@tips )
234  #  $newtree = newick_subtree( $tree,  @tips )  #  $newtree = newick_subtree( $tree,  @tips )
235  #  $newtree = newick_subtree( $tree, \@tips )  #  $newtree = newick_subtree( $tree, \@tips )
236    #  $newtree = newick_covering_subtree( $tree,  @tips )
237    #  $newtree = newick_covering_subtree( $tree, \@tips )
238  #  #
239  #  $newtree = collapse_zero_length_branches( $tree )  #  $newtree = collapse_zero_length_branches( $tree )
240  #  #
241    #  $node = newick_insert_at_node( $node, $subtree )
242    #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )
243    #
244    #===============================================================================
245    #  Tree neighborhood: subtree of n tips to represent a larger tree.
246    #===============================================================================
247    #
248    #  Focus around root:
249    #
250    #  $subtree = root_neighborhood_representative_tree( $tree, $n, \%tip_priority )
251    #  $subtree = root_neighborhood_representative_tree( $tree, $n )
252    #  @tips    = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
253    #  @tips    = root_neighborhood_representative_tips( $tree, $n )
254    # \@tips    = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
255    # \@tips    = root_neighborhood_representative_tips( $tree, $n )
256    #
257    #  Focus around a tip insertion point (the tip is not in the subtree):
258    #
259    #  $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n, \%tip_priority )
260    #  $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n )
261    #  @tips    = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
262    #  @tips    = tip_neighborhood_representative_tips( $tree, $tip, $n )
263    # \@tips    = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
264    # \@tips    = tip_neighborhood_representative_tips( $tree, $tip, $n )
265    #
266  #===============================================================================  #===============================================================================
267  #  Tree reading and writing:  #  Tree reading and writing:
268  #===============================================================================  #===============================================================================
269    #  Write machine-readable trees:
270  #  #
271  #   writeNewickTree( $tree )  #   writeNewickTree( $tree )
272  #   writeNewickTree( $tree, $file )  #   writeNewickTree( $tree, $file )
273  #   writePrettyTree( $tree, $file )  #   writeNewickTree( $tree, \*FH )
274  #  fwriteNewickTree( $file, $tree )  #  fwriteNewickTree( $file, $tree )  # Matches the C arg list for f... I/O
275  #  $treestring = swriteNewickTree( $tree )  #  $treestring = swriteNewickTree( $tree )
276  #  $treestring = formatNewickTree( $tree )  #  $treestring = formatNewickTree( $tree )
277    #
278    #  Write human-readable trees:
279    #
280  #  @textlines  = text_plot_newick( $node, $width, $min_dx, $dy )  #  @textlines  = text_plot_newick( $node, $width, $min_dx, $dy )
281  #   printer_plot_newick( $node, $file, $width, $min_dx, $dy )  #   printer_plot_newick( $node, $file, $width, $min_dx, $dy )
282  #  #
283    #  Read trees:
284    #
285    #  $tree  = read_newick_tree( $file )  # reads to a semicolon
286    #  @trees = read_newick_trees( $file ) # reads to end of file
287  #  $tree = parse_newick_tree_str( $string )  #  $tree = parse_newick_tree_str( $string )
288  #  #
289  #===============================================================================  #===============================================================================
290    
291    
292    use Carp;
293    use Data::Dumper;
294    use strict;
295    
296  require Exporter;  require Exporter;
297    
298  our @ISA = qw(Exporter);  our @ISA = qw(Exporter);
299  our @EXPORT = qw(  our @EXPORT = qw(
300            is_overbeek_tree
301            is_gjonewick_tree
302            overbeek_to_gjonewick
303            gjonewick_to_overbeek
304            newick_is_valid
305          newick_is_rooted          newick_is_rooted
306          newick_is_unrooted          newick_is_unrooted
307          tree_rooted_on_tip          tree_rooted_on_tip
308          newick_is_bifurcating          newick_is_bifurcating
309          newick_tip_count          newick_tip_count
310            newick_tip_ref_list
311          newick_tip_list          newick_tip_list
312    
313          newick_first_tip          newick_first_tip
314          newick_duplicated_tips          newick_duplicated_tips
315          newick_tip_in_tree          newick_tip_in_tree
316          newick_shared_tips          newick_shared_tips
317    
318          newick_tree_length          newick_tree_length
319            newick_tip_distances
320          newick_max_X          newick_max_X
321          newick_most_distant_tip_ref          newick_most_distant_tip_ref
322          newick_most_distant_tip_name          newick_most_distant_tip_name
323    
324            newick_tip_insertion_point
325    
326          std_newick_name          std_newick_name
327    
328          path_to_tip          path_to_tip
# Line 241  Line 344 
344          newick_set_undefined_branches          newick_set_undefined_branches
345          newick_set_all_branches          newick_set_all_branches
346          newick_fix_negative_branches          newick_fix_negative_branches
347            newick_rescale_branches
348    
349            newick_strip_comments
350    
351          normalize_newick_tree          normalize_newick_tree
352          reverse_newick_tree          reverse_newick_tree
# Line 254  Line 360 
360          reroot_newick_next_to_tip          reroot_newick_next_to_tip
361          reroot_newick_to_node          reroot_newick_to_node
362          reroot_newick_to_node_ref          reroot_newick_to_node_ref
363            reroot_newick_between_nodes
364            reroot_newick_to_midpoint
365            reroot_newick_to_midpoint_w
366          reroot_newick_to_approx_midpoint          reroot_newick_to_approx_midpoint
367          reroot_newick_to_approx_midpoint_w          reroot_newick_to_approx_midpoint_w
368          uproot_tip_rooted_newick          uproot_tip_rooted_newick
369          uproot_newick          uproot_newick
370    
371          prune_from_newick          prune_from_newick
372            rooted_newick_subtree
373          newick_subtree          newick_subtree
374            newick_covering_subtree
375          collapse_zero_length_branches          collapse_zero_length_branches
376    
377            newick_insert_at_node
378            newick_insert_between_nodes
379    
380            root_neighborhood_representative_tree
381            root_neighborhood_representative_tips
382            tip_neighborhood_representative_tree
383            tip_neighborhood_representative_tips
384    
385          writeNewickTree          writeNewickTree
386          fwriteNewickTree          fwriteNewickTree
387          strNewickTree          strNewickTree
388          formatNewickTree          formatNewickTree
389    
390            read_newick_tree
391            read_newick_trees
392          parse_newick_tree_str          parse_newick_tree_str
393    
394          printer_plot_newick          printer_plot_newick
# Line 305  Line 427 
427          );          );
428    
429    
 use gjolists qw(  
         common_prefix  
         common_and_unique  
         unique_suffixes  
   
         unique_set  
         duplicates  
         random_order  
   
         union  
         intersection  
         set_difference  
         );  
   
   
 use strict;  
   
   
430  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
431  #  Internally used definitions  #  Internally used definitions
432  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
# Line 332  Line 436 
436    
437    
438  #===============================================================================  #===============================================================================
439    #  Interconvert overbeek and gjonewick trees:
440    #===============================================================================
441    
442    sub is_overbeek_tree { array_ref( $_[0] ) && array_ref( $_[0]->[2] ) }
443    
444    sub is_gjonewick_tree { array_ref( $_[0] ) && array_ref( $_[0]->[0] ) }
445    
446    sub overbeek_to_gjonewick
447    {
448        return () unless ref( $_[0] ) eq 'ARRAY';
449        my ( $lbl, $x, $desc ) = @{ $_[0] };
450        my ( undef, @desc ) = ( $desc && ref( $desc ) eq 'ARRAY' ) ? @$desc : ();
451        [ [ map { overbeek_to_gjonewick( $_ ) } @desc ], $lbl, $x ]
452    }
453    
454    sub gjonewick_to_overbeek
455    {
456        return () unless ref( $_[0] ) eq 'ARRAY';
457        my ( $desc, $lbl, $x ) = @{ $_[0] };
458        my @desc = ( $desc && ref( $desc ) eq 'ARRAY' ) ? @$desc : ();
459        my $parent = $_[1];
460        my $node = [ $lbl, $x, undef, [] ];
461        $node->[2] = [ $parent, map { gjonewick_to_overbeek( $_, $node ) } @desc ];
462        return $node;
463    }
464    
465    
466    #===============================================================================
467  #  Extract tree structure values:  #  Extract tree structure values:
468  #===============================================================================  #===============================================================================
469  #  #
# Line 351  Line 483 
483  #  #
484  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
485    
486  sub newick_desc_ref { $_[0]->[0] }  # = ${$_[0]}[0]  sub newick_desc_ref { ref($_[0]) ? $_[0]->[0] : Carp::confess() }  # = ${$_[0]}[0]
487  sub newick_lbl      { $_[0]->[1] }  sub newick_lbl      { ref($_[0]) ? $_[0]->[1] : Carp::confess() }
488  sub newick_x        { $_[0]->[2] }  sub newick_x        { ref($_[0]) ? $_[0]->[2] : Carp::confess() }
489  sub newick_c1       { $_[0]->[3] }  sub newick_c1       { ref($_[0]) ? $_[0]->[3] : Carp::confess() }
490  sub newick_c2       { $_[0]->[4] }  sub newick_c2       { ref($_[0]) ? $_[0]->[4] : Carp::confess() }
491  sub newick_c3       { $_[0]->[5] }  sub newick_c3       { ref($_[0]) ? $_[0]->[5] : Carp::confess() }
492  sub newick_c4       { $_[0]->[6] }  sub newick_c4       { ref($_[0]) ? $_[0]->[6] : Carp::confess() }
493  sub newick_c5       { $_[0]->[7] }  sub newick_c5       { ref($_[0]) ? $_[0]->[7] : Carp::confess() }
494    
495  sub newick_desc_list {  sub newick_desc_list {
496      my $node = $_[0];      my $node = $_[0];
# Line 427  Line 559 
559  #===============================================================================  #===============================================================================
560  #  Some tree property tests:  #  Some tree property tests:
561  #===============================================================================  #===============================================================================
562    #  Tree is valid?
563    #
564    #  $bool = newick_is_valid( $node, $verbose )
565    #-------------------------------------------------------------------------------
566    sub newick_is_valid
567    {
568        my $node = shift;
569    
570        if ( ! array_ref( $node ) )
571        {
572            print STDERR "Node is not array reference\n" if $_[0];
573            return 0;
574        }
575    
576        my @node = @$node;
577        if ( ! @node )
578        {
579            print STDERR "Node is empty array reference\n" if $_[0];
580            return 0;
581        }
582    
583        # Must have descendant or label:
584    
585        if ( ! ( array_ref( $node[0] ) && @{ $node[0] } ) && ! $node[2] )
586        {
587            print STDERR "Node has neither descendant nor label\n" if $_[0];
588            return 0;
589        }
590    
591        #  If comments are present, they must be array references
592    
593        foreach ( ( @node > 3 ) ? @node[ 3 .. $#node ] : () )
594        {
595            if ( defined( $_ ) && ! array_ref( $_ ) )
596            {
597                print STDERR "Node has neither descendant or label\n" if $_[0];
598                return 0;
599            }
600        }
601    
602        #  Inspect the descendants:
603    
604        foreach ( array_ref( $node[0] ) ? @{ $node[0] } : () )
605        {
606            newick_is_valid( $_, @_ ) || return 0
607        }
608    
609        return 1;
610    }
611    
612    
613    #-------------------------------------------------------------------------------
614  #  Tree is rooted (2 branches at root node)?  #  Tree is rooted (2 branches at root node)?
615  #  #
616  #  $bool = newick_is_rooted( $node )  #  $bool = newick_is_rooted( $node )
# Line 512  Line 696 
696  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
697  #  List of tip nodes:  #  List of tip nodes:
698  #  #
699  #  @tips = newick_tip_ref_list( $node )  #  @tips = newick_tip_ref_list( $noderef )
700    # \@tips = newick_tip_ref_list( $noderef )
701  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
702  sub newick_tip_ref_list {  sub newick_tip_ref_list {
703      my ( $node, $not_root ) = @_;      my ( $node, $not_root ) = @_;
# Line 529  Line 714 
714          push @list, newick_tip_ref_list( $_, 1 );          push @list, newick_tip_ref_list( $_, 1 );
715      }      }
716    
717      @list;      wantarray ? @list : \@list;
718  }  }
719    
720    
# Line 537  Line 722 
722  #  List of tips:  #  List of tips:
723  #  #
724  #  @tips = newick_tip_list( $node )  #  @tips = newick_tip_list( $node )
725    # \@tips = newick_tip_list( $node )
726  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
727  sub newick_tip_list {  sub newick_tip_list {
728      map { newick_lbl( $_ ) } newick_tip_ref_list( $_[0] );      my @tips = map { newick_lbl( $_ ) } newick_tip_ref_list( $_[0] );
729        wantarray ? @tips : \@tips;
730  }  }
731    
732    
# Line 578  Line 765 
765  #  List of duplicated tip labels.  #  List of duplicated tip labels.
766  #  #
767  #  @tips = newick_duplicated_tips( $node )  #  @tips = newick_duplicated_tips( $node )
768    # \@tips = newick_duplicated_tips( $node )
769  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
770  sub newick_duplicated_tips {  sub newick_duplicated_tips {
771      duplicates( newick_tip_list( $_[0] ) );      my @tips = &duplicates( newick_tip_list( $_[0] ) );
772        wantarray ? @tips : \@tips;
773  }  }
774    
775    
# Line 611  Line 800 
800  #  Tips shared between 2 trees.  #  Tips shared between 2 trees.
801  #  #
802  #  @tips = newick_shared_tips( $tree1, $tree2 )  #  @tips = newick_shared_tips( $tree1, $tree2 )
803    # \@tips = newick_shared_tips( $tree1, $tree2 )
804  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
805  sub newick_shared_tips {  sub newick_shared_tips {
806      my ( $Tree1, $Tree2 ) = @_;      my ( $tree1, $tree2 ) = @_;
807      my ( @Tips1 ) = newick_tip_list( $Tree1 );      my $tips1 = newick_tip_list( $tree1 );
808      my ( @Tips2 ) = newick_tip_list( $Tree2 );      my $tips2 = newick_tip_list( $tree2 );
809      intersection( \@Tips1, \@Tips2 );      my @tips = &intersection( $tips1, $tips2 );
810        wantarray ? @tips : \@tips;
811  }  }
812    
813    
# Line 638  Line 829 
829    
830    
831  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
832    #  Hash of tip nodes and corresponding distances from root:
833    #
834    #   %tip_distances = newick_tip_distances( $node )
835    #  \%tip_distances = newick_tip_distances( $node )
836    #-------------------------------------------------------------------------------
837    sub newick_tip_distances
838    {
839        my ( $node, $x, $hash ) = @_;
840        my $root = ! $hash;
841        ref( $hash ) eq 'HASH' or $hash = {};
842    
843        $x ||= 0;
844        $x  += newick_x( $node ) || 0;
845    
846        #  Is it a tip?
847    
848        my $n_desc = newick_n_desc( $node );
849        if ( ! $n_desc )
850        {
851            $hash->{ newick_lbl( $node ) } = $x;
852            return $hash;
853        }
854    
855        #  Tree rooted on tip?
856    
857        if ( ( $n_desc == 1 ) && $root && ( newick_lbl( $node ) ) )
858        {
859            $hash->{ newick_lbl( $node ) } = 0;  # Distance to root is zero
860        }
861    
862        foreach ( newick_desc_list( $node ) )
863        {
864            newick_tip_distances( $_, $x, $hash );
865        }
866    
867        wantarray ? %$hash : $hash;
868    }
869    
870    
871    #-------------------------------------------------------------------------------
872  #  Tree max X.  #  Tree max X.
873  #  #
874  #  $xmax = newick_max_X( $node )  #  $xmax = newick_max_X( $node )
# Line 712  Line 943 
943    
944    
945  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
946    #  Tree tip insertion point (with standard node labels):
947    #
948    #  [ $node1, $x1, $node2, $x2, $x ]
949    #           = newick_tip_insertion_point( $tree, $tip )
950    #
951    #  Which means: tip is on a branch of length x that is inserted into the branch
952    #  connecting node1 and node2, at distance x1 from node1 and x2 from node2.
953    #
954    #                x1    +------ n1a (lowest sorting tip of this subtree)
955    #            +--------n1
956    #            |         +------n1b (lowest sorting tip of this subtree)
957    #  tip-------n
958    #        x   |       +------------- n2a (lowest sorting tip of this subtree)
959    #            +------n2
960    #               x2   +-------- n2b (lowest sorting tip of this subtree)
961    #
962    #  The designations of 1 vs 2, and a vs b are chosen such that:
963    #     n1a < n1b, and n2a < n2b, and n1a < n2a
964    #
965    #  Then the statandard description becomes:
966    #
967    #  [ [ $n1a, min(n1b,n2a), max(n1b,n2a) ], x1,
968    #    [ $n2a, min(n2b,n1a), max(n2b,n1a) ], x2,
969    #    x
970    #  ]
971    #
972    #-------------------------------------------------------------------------------
973    sub newick_tip_insertion_point
974    {
975        my ( $tree, $tip ) = @_;
976        $tree && $tip && ref( $tree ) eq 'ARRAY'    or return undef;
977        $tree = copy_newick_tree( $tree )           or return undef;
978        $tree = reroot_newick_to_tip( $tree, $tip ) or return undef;
979        my $node = $tree;
980    
981        my $x  = 0;                        # Distance to node
982        my $dl = newick_desc_ref( $node ); # Descendent list of tip node;
983        $node  = $dl->[0];                 # Node adjacent to tip
984        $dl    = newick_desc_ref( $node );
985        while ( $dl && ( @$dl == 1 ) )     # Traverse unbranched nodes
986        {
987            $node = $dl->[0];
988            $x   += newick_x( $node );
989            $dl   = newick_desc_ref( $node );
990        }
991        $x += newick_x( $node );
992    
993        #  We are now at the node that is the insertion point.
994        #  Is it a tip?
995    
996        my @description;
997    
998        if ( ( ! $dl ) || @$dl == 0 )
999        {
1000            @description = ( [ newick_lbl( $node ) ], 0, undef, 0, $x );
1001        }
1002    
1003        #  Is it a trifurcation or greater, in which case it does not go
1004        #  away with tip deletion?
1005    
1006        elsif ( @$dl > 2 )
1007        {
1008            @description = ( [ std_node_name( $node, $node ) ], 0, undef, 0, $x );
1009        }
1010    
1011        #  The node is bifurcating.  We need to describe it.
1012    
1013        else
1014        {
1015            my ( $n1, $x1 ) = describe_descendant( $dl->[0] );
1016            my ( $n2, $x2 ) = describe_descendant( $dl->[1] );
1017    
1018            if ( @$n1 == 2 ) { push @$n1, $n2->[0] }
1019            if ( @$n2 == 2 )
1020            {
1021                @$n2 = sort { lc $a cmp lc $b } ( @$n2, $n1->[0] );
1022            }
1023            if ( @$n1 == 3 ) { @$n2 = sort { lc $a cmp lc $b } @$n2 }
1024            @description = ( $n1, $x1, $n2, $x2, $x );
1025        }
1026    
1027        return wantarray ? @description : \@description;
1028    }
1029    
1030    
1031    sub describe_descendant
1032    {
1033        my $node = shift;
1034    
1035        my $x  = 0;                        # Distance to node
1036        my $dl = newick_desc_ref( $node ); # Descendent list of tip node;
1037        while ( $dl && ( @$dl == 1 ) )     # Traverse unbranched nodes
1038        {
1039            $node = $dl->[0];
1040            $x   += newick_x( $node );
1041            $dl   = newick_desc_ref( $node );
1042        }
1043        $x += newick_x( $node );
1044    
1045        #  Is it a tip?  Return list of one tip;
1046    
1047        if ( ( ! $dl ) || @$dl == 0 )
1048        {
1049            return ( [ newick_lbl( $node ) ], $x );
1050        }
1051    
1052        #  Get tips of each descendent, keeping lowest sorting from each.
1053        #  Return the two lowest of those (the third will come from the
1054        #  other side of the original node).
1055    
1056        my @rep_tips = sort { lc $a cmp lc $b }
1057                       map  { ( sort { lc $a cmp lc $b } newick_tip_list( $_ ) )[0] }
1058                       @$dl;
1059        return ( [ @rep_tips[0,1] ], $x );
1060    }
1061    
1062    
1063    #-------------------------------------------------------------------------------
1064  #  Standard node name:  #  Standard node name:
1065  #     Tip label if at a tip  #     Tip label if at a tip
1066  #     Three sorted tip labels intersecting at node, each being smallest  #     Three sorted tip labels intersecting at node, each being smallest
1067  #           of all the tips of their subtrees  #           of all the tips of their subtrees
1068  #  #
1069  #  @TipOrTips = std_node_name( $Tree, $Node )  #  @TipOrTips = std_node_name( $tree, $node )
1070  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1071  sub std_node_name {  sub std_node_name {
1072      my $tree = $_[0];      my $tree = $_[0];
# Line 734  Line 1083 
1083      #  Work through lists of tips in descendant subtrees, removing them from      #  Work through lists of tips in descendant subtrees, removing them from
1084      #  @rest, and keeping the best tip for each subtree.      #  @rest, and keeping the best tip for each subtree.
1085    
1086      my @rest = tips_in_newick( $tree );      my @rest = newick_tip_list( $tree );
1087      my @best = map {      my @best = map
1088              my @tips = sort { lc $a cmp lc $b } tips_in_newick( $_ );            {
1089              @rest = set_difference( \@rest, \@tips );              my @tips = sort { lc $a cmp lc $b } newick_tip_list( $_ );
1090                @rest = &set_difference( \@rest, \@tips );
1091              $tips[0];              $tips[0];
1092          } newick_desc_list( $noderef );          } newick_desc_list( $noderef );
1093    
# Line 825  Line 1175 
1175      my $imax = newick_n_desc( $node );      my $imax = newick_n_desc( $node );
1176      for ( my $i = 1; $i <= $imax; $i++ ) {      for ( my $i = 1; $i <= $imax; $i++ ) {
1177         @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 ) );
1178         if ( @path ) { return @path }          return @path if @path;
1179      }      }
1180    
1181      ();  #  Not found      ();  #  Not found
# Line 856  Line 1206 
1206      @p2 && @p3 || return ();                             #  Were they found?      @p2 && @p3 || return ();                             #  Were they found?
1207    
1208      # Find the common prefix for each pair of paths      # Find the common prefix for each pair of paths
1209      my @p12 = common_prefix( \@p1, \@p2 );      my @p12 = &common_prefix( \@p1, \@p2 );
1210      my @p13 = common_prefix( \@p1, \@p3 );      my @p13 = &common_prefix( \@p1, \@p3 );
1211      my @p23 = common_prefix( \@p2, \@p3 );      my @p23 = &common_prefix( \@p2, \@p3 );
1212    
1213      # Return the longest common prefix of any two paths      # Return the longest common prefix of any two paths
1214      ( @p12 >= @p13 && @p12 >= @p23 ) ? @p12 :      ( @p12 >= @p13 && @p12 >= @p23 ) ? @p12 :
# Line 909  Line 1259 
1259      @p1 && @p2 || return undef;                          # Were they found?      @p1 && @p2 || return undef;                          # Were they found?
1260    
1261      # Find the unique suffixes of the two paths      # Find the unique suffixes of the two paths
1262      my ( $suf1, $suf2 ) = unique_suffixes( \@p1, \@p2 ); # Common node is lost      my ( $suf1, $suf2 ) = &unique_suffixes( \@p1, \@p2 ); # Common node is lost
1263      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;
1264      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;
1265    
# Line 930  Line 1280 
1280    
1281      array_ref( $node ) && defined( $node1 )      array_ref( $node ) && defined( $node1 )
1282                         && defined( $node2 ) || return undef;                         && defined( $node2 ) || return undef;
1283      my @p1 = path_to_node( $node, $node1 );      my @p1 = path_to_node( $node, $node1 ) or return undef;
1284      my @p2 = path_to_node( $node, $node2 );      my @p2 = path_to_node( $node, $node2 ) or return undef;
     @p1 && @p2 || return undef;                          # Were they found?  
1285    
1286      # Find the unique suffixes of the two paths      # Find the unique suffixes of the two paths
1287      my ( $suf1, $suf2 ) = unique_suffixes( \@p1, \@p2 ); # Common node is lost      my ( $suf1, $suf2 ) = &unique_suffixes( \@p1, \@p2 ); # Common node is lost
1288      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;      my $d1 = @$suf1 ? distance_along_path_2( @$suf1 ) : 0;
1289      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;      my $d2 = @$suf2 ? distance_along_path_2( @$suf2 ) : 0;
1290    
# Line 1150  Line 1499 
1499      my ( $node, $x, $not_root ) = @_;      my ( $node, $x, $not_root ) = @_;
1500    
1501      my $n = 0;      my $n = 0;
1502      if ( $not_root ) {      if ( $not_root )
1503        {
1504          set_newick_x( $node, $x );          set_newick_x( $node, $x );
1505          $n++;          $n++;
1506      }      }
1507    
1508      foreach ( newick_desc_list( $node ) ) {      foreach ( newick_desc_list( $node ) )
1509        {
1510          $n += newick_set_all_branches( $_, $x, 1 );          $n += newick_set_all_branches( $_, $x, 1 );
1511      }      }
1512    
# Line 1164  Line 1515 
1515    
1516    
1517  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1518    #  Rescale all branch lenghts by factor.
1519    #
1520    #  $node = newick_rescale_branches( $node, $factor )
1521    #-------------------------------------------------------------------------------
1522    sub newick_rescale_branches {
1523        my ( $node, $factor ) = @_;
1524    
1525        my $x = newick_x( $node );
1526        set_newick_x( $node, $factor * $x ) if $x;
1527    
1528        foreach ( newick_desc_list( $node ) )
1529        {
1530            newick_rescale_branches( $_, $factor );
1531        }
1532    
1533        $node;
1534    }
1535    
1536    
1537    #-------------------------------------------------------------------------------
1538  #  Set negative branches to zero.  The original tree is modfied.  #  Set negative branches to zero.  The original tree is modfied.
1539  #  #
1540  #  $n_changed = newick_fix_negative_branches( $tree )  #  $n_changed = newick_fix_negative_branches( $tree )
# Line 1189  Line 1560 
1560    
1561    
1562  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1563    #  Remove comments from a newick tree (e.g., before writing for phylip).
1564    #
1565    #  $node = newick_strip_comments( $node )
1566    #-------------------------------------------------------------------------------
1567    sub newick_strip_comments {
1568        my ( $node ) = @_;
1569    
1570        @$node = @$node[ 0 .. 2 ];
1571        foreach ( newick_desc_list( $node ) ) { newick_strip_comments( $_ ) }
1572        $node;
1573    }
1574    
1575    
1576    #-------------------------------------------------------------------------------
1577  #  Normalize tree order (in place).  #  Normalize tree order (in place).
1578  #  #
1579  #  ( $tree, $label1 ) = normalize_newick_tree( $tree )  #  ( $tree, $label1 ) = normalize_newick_tree( $tree )
# Line 1336  Line 1721 
1721  #  #
1722  #  $tree = unaesthetic_newick_tree( $treeref, $dir )  #  $tree = unaesthetic_newick_tree( $treeref, $dir )
1723  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1724  sub unaesthetic_newick_tree {  sub unaesthetic_newick_tree
1725    {
1726      my ( $tree, $dir ) = @_;      my ( $tree, $dir ) = @_;
1727      my %cnt;      my %cnt;
1728    
# Line 1356  Line 1742 
1742  #           = 0 for no change, and  #           = 0 for no change, and
1743  #           > 0 for downward branch (small group first).  #           > 0 for downward branch (small group first).
1744  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -  #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
1745  sub reorder_against_tip_count {  sub reorder_against_tip_count
1746    {
1747      my ( $node, $cntref, $dir ) = @_;      my ( $node, $cntref, $dir ) = @_;
1748    
1749      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
# Line 1395  Line 1782 
1782  #  #
1783  #  $tree = random_order_newick_tree( $tree )  #  $tree = random_order_newick_tree( $tree )
1784  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1785  sub random_order_newick_tree {  sub random_order_newick_tree
1786    {
1787      my ( $node ) = @_;      my ( $node ) = @_;
1788    
1789      my $nd = newick_n_desc( $node );      my $nd = newick_n_desc( $node );
# Line 1404  Line 1792 
1792      #  Reorder this subtree:      #  Reorder this subtree:
1793    
1794      my $dl_ref = newick_desc_ref( $node );      my $dl_ref = newick_desc_ref( $node );
1795      @$dl_ref = random_order( @$dl_ref );      @$dl_ref = &random_order( @$dl_ref );
1796    
1797      #  Reorder descendants:      #  Reorder descendants:
1798    
# Line 1419  Line 1807 
1807  #  #
1808  #  $newtree = reroot_newick_by_path( @path )  #  $newtree = reroot_newick_by_path( @path )
1809  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1810  sub reroot_newick_by_path {  sub reroot_newick_by_path
1811    {
1812      my ( $node1, $path1, @rest ) = @_;      my ( $node1, $path1, @rest ) = @_;
1813      array_ref( $node1 ) || return undef;      #  Always expect a node      array_ref( $node1 ) || return undef;      #  Always expect a node
1814    
# Line 1432  Line 1821 
1821      #      #
1822      #      splice( @$dl1, $path1-1, 1 );      #      splice( @$dl1, $path1-1, 1 );
1823      #      #
1824      #  But this maintains the cyclic order of the nodes:      #  But the following maintains the cyclic order of the nodes:
1825    
1826      my $dl1 = newick_desc_ref( $node1 );      my $dl1 = newick_desc_ref( $node1 );
1827      my $nd1 = @$dl1;      my $nd1 = @$dl1;
# Line 1447  Line 1836 
1836    
1837      my $dl2 = newick_desc_ref( $node2 );      my $dl2 = newick_desc_ref( $node2 );
1838      if ( array_ref( $dl2 ) ) { push @$dl2, $node1 }      if ( array_ref( $dl2 ) ) { push @$dl2, $node1 }
1839      else                     { set_newick_desc_list( $node2, [ $node1 ] ) }      else                     { set_newick_desc_list( $node2, $node1 ) }
1840    
1841      #  Move c1 comments from node 1 to node 2:      #  Move c1 comments from node 1 to node 2:
1842    
# Line 1527  Line 1916 
1916    
1917    
1918  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1919  #  Move root of tree to an approximate midpoint.  #  Reroot a newick tree along the path between 2 nodes:
1920  #  #
1921  #  $newtree = reroot_newick_to_approx_midpoint( $tree )  #  $tree = reroot_newick_between_nodes( $tree, $node1, $node2, $fraction )
1922  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
1923  sub reroot_newick_to_approx_midpoint {  sub reroot_newick_between_nodes
1924      my ( $tree ) = @_;  {
1925        my ( $tree, $node1, $node2, $fraction ) = @_;
1926      #  Compile average tip to node distances assending      array_ref( $tree ) or return undef;
1927        $fraction >= 0 && $fraction <= 1 or return undef;
     my $dists1 = average_to_tips_1( $tree );  
   
     #  Compile average tip to node distances descending, returning midpoint node  
1928    
1929      my $node = average_to_tips_2( $dists1, undef, undef );      #  Find the paths to the nodes:
1930    
1931      #  Reroot      my @path1 = path_to_node( $tree, $node1 ) or return undef;
1932        my @path2 = path_to_node( $tree, $node2 ) or return undef;
1933    
1934      $node ? reroot_newick_to_node_ref( $tree, $node ) : $tree      reroot_newick_between_nodes_by_path( $tree, \@path1, \@path2, $fraction )
1935  }  }
1936    
1937    
1938  sub average_to_tips_1 {  #-------------------------------------------------------------------------------
1939      my ( $node ) = @_;  #  Reroot a newick tree along the path between 2 nodes:
1940    #
1941      my @desc_dists = map { average_to_tips_1( $_ ) } newick_desc_list( $node );  #  $tree = reroot_newick_between_node_refs( $tree, $node1, $node2, $fraction )
1942      my $x_below = 0;  #-------------------------------------------------------------------------------
1943      if ( @desc_dists )  sub reroot_newick_between_node_refs
1944      {      {
1945          foreach ( @desc_dists ) { $x_below += $_->[0] }      my ( $tree, $node1, $node2, $fraction ) = @_;
1946          $x_below /= @desc_dists;      array_ref( $tree ) or return undef;
     }  
     my $x = newick_x( $node ) || 0;  
     my $x_net = $x_below + $x;  
1947    
1948      [ $x_net, $x, $x_below, [ @desc_dists ], $node ]      #  Find the paths to the nodes:
1949    
1950        my @path1 = path_to_node_ref( $tree, $node1 ) or return undef;
1951        my @path2 = path_to_node_ref( $tree, $node2 ) or return undef;;
1952    
1953        reroot_newick_between_nodes_by_path( $tree, \@path1, \@path2, $fraction )
1954  }  }
1955    
1956    
1957  sub average_to_tips_2 {  #-------------------------------------------------------------------------------
1958      my ( $dists1, $x_above, $anc_node ) = @_;  #  Reroot a newick tree along the path between 2 nodes defined by paths:
1959      my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;  #
1960    #  $tree = reroot_newick_between_nodes_by_path( $tree, $path1, $path2, $fraction )
1961    #-------------------------------------------------------------------------------
1962    sub reroot_newick_between_nodes_by_path
1963    {
1964        my ( $tree, $path1, $path2, $fraction ) = @_;
1965        array_ref( $tree ) and array_ref( $path1 ) and  array_ref( $path2 )
1966           or return undef;
1967        $fraction >= 0 && $fraction <= 1 or return undef;
1968    
1969      #  Are we done?  Root is in this node's branch, or "above"?      my @path1 = @$path1;
1970        my @path2 = @$path2;
1971    
1972      # defined( $x_above ) and print STDERR "x_above = $x_above\n";      #  Trim the common prefix, saving it:
     # print STDERR "x       = $x\n";  
     # print STDERR "x_below = $x_below\n";  
     # print STDERR "n_desc  = ", scalar @$desc_list, "\n\n";  
1973    
1974      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )      my @prefix = ();
1975        while ( $path1[1] == $path2[1] )
1976      {      {
1977          #  At this point the root can only be in this node's branch,          push @prefix, splice( @path1, 0, 2 );
1978          #  or "above" it in the current rooting of the tree (which          splice( @path2, 0, 2 );
1979          #  would mean that the midpoint is actually down a different      }
         #  path from the root of the current tree).  
         #  
         #  Is the root in the current branch?  
1980    
1981          if ( ( $x_below + $x ) >= $x_above )      my ( @path, $dist );
1982        if    ( @path1 < 3 )
1983          {          {
1984              return ( $x_above >= $x_below ) ? $anc_node : $node;          @path2 >= 3 or return undef;              # node1 = node2
1985            $dist = $fraction * newick_path_length( @path2 );
1986            @path = @path2;
1987          }          }
1988          else      elsif ( @path2 < 3 )
1989          {          {
1990              return undef;          $dist = ( 1 - $fraction ) * newick_path_length( @path1 );
1991            @path = @path1;
1992          }          }
1993        else
1994        {
1995            my $dist1 = newick_path_length( @path1 );
1996            my $dist2 = newick_path_length( @path2 );
1997            $dist = $fraction * ( $dist1 + $dist2 ) - $dist1;
1998            @path = ( $dist <= 0 ) ? @path1 : @path2;
1999            $dist = abs( $dist );
2000      }      }
2001    
2002      #  The root must be somewhere below this node:      #  Descend tree until we reach the insertion branch:
   
     my $n_1      =   @$desc_list - ( $anc_node ? 0 : 1 );  
     my $ttl_dist = ( @$desc_list * $x_below ) + ( defined( $x_above ) ? ( $x_above + $x ) : 0 );  
2003    
2004      foreach ( @$desc_list )      my $x;
2005        while ( ( $dist > ( $x = newick_x( $path[2] ) ) ) && ( @path > 3 ) )
2006      {      {
2007          #  If input tree is tip_rooted, $n-1 can be 0, so:          $dist -= $x;
2008            push @prefix, splice( @path, 0, 2 );
         my $above2 = $n_1 ? ( ( $ttl_dist - $_->[0] ) / $n_1 ) : 0;  
         my $root = average_to_tips_2( $_, $above2, $node );  
         if ( $root ) { return $root }  
2009      }      }
2010    
2011      #  Was not anywhere below this node (oh-oh):      #  Insert the new node:
2012    
2013      return undef;      my $newnode = [ [ $path[2] ], undef, $dist ];
2014        set_newick_desc_i( $path[0], $path[1], $newnode );
2015        set_newick_x( $path[2], ( ( $x > $dist ) ? ( $x - $dist ) : 0 ) );
2016    
2017        #  We can now build the path from root to the new node
2018    
2019        reroot_newick_by_path( @prefix, @path[0,1], $newnode );
2020  }  }
2021    
2022    
2023  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2024  #  Move root of tree to an approximate midpoint.  Weight by tips.  #  Move root of tree to an approximate midpoint.
2025  #  #
2026  #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )  #  $newtree = reroot_newick_to_approx_midpoint( $tree )
2027  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2028  sub reroot_newick_to_approx_midpoint_w {  sub reroot_newick_to_approx_midpoint {
2029        my ( $tree ) = @_;
2030    
2031        #  Compile average tip to node distances assending
2032    
2033        my $dists1 = average_to_tips_1( $tree );
2034    
2035        #  Compile average tip to node distances descending, returning midpoint
2036        #  cadidates as a list of [ $node1, $node2, $fraction ]
2037    
2038        my @mids = average_to_tips_2( $dists1, undef, undef );
2039    
2040        #  Reroot to first midpoint candidate
2041    
2042        return $tree if ! @mids;
2043        my ( $node1, $node2, $fraction ) = @{ $mids[0] };
2044        reroot_newick_to_node_ref( $tree, $fraction >= 0.5 ? $node2 : $node1 );
2045    }
2046    
2047    
2048    #-------------------------------------------------------------------------------
2049    #  Move root of tree to a midpoint.
2050    #
2051    #  $newtree = reroot_newick_to_midpoint( $tree )
2052    #-------------------------------------------------------------------------------
2053    sub reroot_newick_to_midpoint {
2054        my ( $tree ) = @_;
2055    
2056        #  Compile average tip to node distances assending
2057    
2058        my $dists1 = average_to_tips_1( $tree );
2059    
2060        #  Compile average tip to node distances descending, returning midpoint
2061        #  [ $node1, $node2, $fraction ]
2062    
2063        my @mids = average_to_tips_2( $dists1, undef, undef );
2064    
2065        @mids ? reroot_newick_between_node_refs( $tree, @{ $mids[0] } ) : $tree;
2066    }
2067    
2068    
2069    #-------------------------------------------------------------------------------
2070    #  Compile average tip to node distances assending
2071    #-------------------------------------------------------------------------------
2072    sub average_to_tips_1 {
2073        my ( $node ) = @_;
2074    
2075        my @desc_dists = map { average_to_tips_1( $_ ) } newick_desc_list( $node );
2076        my $x_below = 0;
2077        if ( @desc_dists )
2078        {
2079            foreach ( @desc_dists ) { $x_below += $_->[0] }
2080            $x_below /= @desc_dists;
2081        }
2082    
2083        my $x = newick_x( $node ) || 0;
2084        my $x_net = $x_below + $x;
2085    
2086        [ $x_net, $x, $x_below, [ @desc_dists ], $node ]
2087    }
2088    
2089    
2090    #-------------------------------------------------------------------------------
2091    #  Compile average tip to node distances descending, returning midpoint as
2092    #  [ $node1, $node2, $fraction_of_dist_between ]
2093    #-------------------------------------------------------------------------------
2094    sub average_to_tips_2 {
2095        my ( $dists1, $x_above, $anc_node ) = @_;
2096        my ( undef, $x, $x_below, $desc_list, $node ) = @$dists1;
2097    
2098        #  Are we done?  Root is in this node's branch, or "above"?
2099    
2100        my @mids = ();
2101        if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )
2102        {
2103            #  At this point the root can only be in this node's branch,
2104            #  or "above" it in the current rooting of the tree (which
2105            #  would mean that the midpoint is actually down a different
2106            #  path from the root of the current tree).
2107            #
2108            #  Is the root in the current branch?
2109    
2110            if ( ( $x_below + $x ) >= $x_above )
2111            {
2112                #  We will need to make a new node for the root, $fract of
2113                #  the way from $node to $anc_node:
2114                my $fract = ( $x > 0 ) ? 0.5 * ( ( $x_above - $x_below ) / $x + 1 )
2115                                       : 0.5;
2116                push @mids, [ $node, $anc_node, $fract ];
2117            }
2118        }
2119    
2120        #  The root might be somewhere below this node:
2121    
2122        my $n_1      =   @$desc_list - ( $anc_node ? 0 : 1 );
2123        my $ttl_dist = ( @$desc_list * $x_below ) + ( defined( $x_above ) ? ( $x_above + $x ) : 0 );
2124    
2125        foreach ( @$desc_list )
2126        {
2127            #  If input tree is tip_rooted, $n-1 can be 0, so:
2128    
2129            my $above2 = $n_1 ? ( ( $ttl_dist - $_->[0] ) / $n_1 ) : 0;
2130            push @mids, average_to_tips_2( $_, $above2, $node );
2131        }
2132    
2133        return @mids;
2134    }
2135    
2136    
2137    #-------------------------------------------------------------------------------
2138    #  Move root of tree to an approximate midpoint.  Weight by tips.
2139    #
2140    #  $newtree = reroot_newick_to_approx_midpoint_w( $tree )
2141    #-------------------------------------------------------------------------------
2142    sub reroot_newick_to_approx_midpoint_w {
2143        my ( $tree ) = @_;
2144    
2145        #  Compile average tip to node distances assending from tips
2146    
2147        my $dists1 = average_to_tips_1_w( $tree );
2148    
2149        #  Compile average tip to node distances descending, returning midpoints
2150    
2151        my @mids = average_to_tips_2_w( $dists1, undef, undef, undef );
2152    
2153        #  Reroot to first midpoint candidate
2154    
2155        return $tree if ! @mids;
2156        my ( $node1, $node2, $fraction ) = @{ $mids[0] };
2157        reroot_newick_to_node_ref( $tree, $fraction >= 0.5 ? $node2 : $node1 );
2158    }
2159    
2160    
2161    #-------------------------------------------------------------------------------
2162    #  Move root of tree to an approximate midpoint.  Weight by tips.
2163    #
2164    #  $newtree = reroot_newick_to_midpoint_w( $tree )
2165    #-------------------------------------------------------------------------------
2166    sub reroot_newick_to_midpoint_w {
2167      my ( $tree ) = @_;      my ( $tree ) = @_;
2168    
2169      #  Compile average tip to node distances assending      #  Compile average tip to node distances assending
# Line 1629  Line 2172 
2172    
2173      #  Compile average tip to node distances descending, returning midpoint node      #  Compile average tip to node distances descending, returning midpoint node
2174    
2175      my $node = average_to_tips_2_w( $dists1, undef, undef, undef );      my @mids = average_to_tips_2_w( $dists1, undef, undef, undef );
2176    
2177      #  Reroot      #  Reroot at first candidate midpoint
2178    
2179      $node ? reroot_newick_to_node_ref( $tree, $node ) : $tree      @mids ? reroot_newick_between_node_refs( $tree, @{ $mids[0] } ) : $tree;
2180  }  }
2181    
2182    
# Line 1654  Line 2197 
2197          }          }
2198          $x_below /= $n_below;          $x_below /= $n_below;
2199      }      }
2200    
2201      my $x = newick_x( $node ) || 0;      my $x = newick_x( $node ) || 0;
2202      my $x_net = $x_below + $x;      my $x_net = $x_below + $x;
2203    
# Line 1667  Line 2211 
2211    
2212      #  Are we done?  Root is in this node's branch, or "above"?      #  Are we done?  Root is in this node's branch, or "above"?
2213    
2214      # 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";  
   
2215      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )      if ( defined( $x_above ) && ( ( $x_above + $x ) >= $x_below ) )
2216      {      {
2217          #  At this point the root can only be in this node's branch,          #  At this point the root can only be in this node's branch,
# Line 1679  Line 2219 
2219          #  would mean that the midpoint is actually down a different          #  would mean that the midpoint is actually down a different
2220          #  path from the root of the current tree).          #  path from the root of the current tree).
2221          #          #
2222          #  Is the root in the current branch?          #  Is their a root in the current branch?
2223    
2224          if ( ( $x_below + $x ) >= $x_above )          if ( ( $x_below + $x ) >= $x_above )
2225          {          {
2226              return ( $x_above >= $x_below ) ? $anc_node : $node;              #  We will need to make a new node for the root, $fract of
2227          }              #  the way from $node to $anc_node:
2228          else              my $fract = ( $x > 0 ) ? 0.5 * ( ( $x_above - $x_below ) / $x + 1 )
2229          {                                     : 0.5;
2230              return undef;              push @mids, [ $node, $anc_node, $fract ];
2231          }          }
2232      }      }
2233    
# Line 1707  Line 2247 
2247    
2248          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 )
2249                                   : 0;                                   : 0;
2250          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 }  
2251      }      }
2252    
2253      #  Was not anywhere below this node (oh-oh):      return @mids;
   
     return undef;  
2254  }  }
2255    
2256    
# Line 1859  Line 2396 
2396      ( $tree, ( $collapse ? @new_desc : () ) );      ( $tree, ( $collapse ? @new_desc : () ) );
2397  }  }
2398    
2399    #-------------------------------------------------------------------------------
2400    #  Add a subtree to a newick tree node:
2401    #
2402    #  $node = newick_insert_at_node( $node, $subtree )
2403    #-------------------------------------------------------------------------------
2404    sub newick_insert_at_node
2405    {
2406        my ( $node, $subtree ) = @_;
2407        array_ref( $node ) && array_ref( $subtree ) or return undef;
2408    
2409        #  We could check validity of trees, but ....
2410    
2411        my $dl = newick_desc_ref( $node );
2412        if ( array_ref( $dl ) )
2413        {
2414            push @$dl, $subtree;
2415        }
2416        else
2417        {
2418            set_newick_desc_ref( $node, [ $subtree ] );
2419        }
2420        return $node;
2421    }
2422    
2423    
2424    #-------------------------------------------------------------------------------
2425    #  Insert a subtree into a newick tree along the path between 2 nodes:
2426    #
2427    #  $tree = newick_insert_between_nodes( $tree, $subtree, $node1, $node2, $fraction )
2428    #-------------------------------------------------------------------------------
2429    sub newick_insert_between_nodes
2430    {
2431        my ( $tree, $subtree, $node1, $node2, $fraction ) = @_;
2432        array_ref( $tree ) && array_ref( $subtree ) or return undef;
2433        $fraction >= 0 && $fraction <= 1 or return undef;
2434    
2435        #  Find the paths to the nodes:
2436    
2437        my @path1 = path_to_node( $tree, $node1 ) or return undef;
2438        my @path2 = path_to_node( $tree, $node2 ) or return undef;
2439    
2440        #  Trim the common prefix:
2441    
2442        while ( $path1[1] == $path2[1] )
2443        {
2444            splice( @path1, 0, 2 );
2445            splice( @path2, 0, 2 );
2446        }
2447    
2448        my ( @path, $dist );
2449        if    ( @path1 < 3 )
2450        {
2451            @path2 >= 3 or return undef;              # node1 = node2
2452            $dist = $fraction * newick_path_length( @path2 );
2453            @path = @path2;
2454        }
2455        elsif ( @path2 < 3 )
2456        {
2457            $dist = ( 1 - $fraction ) * newick_path_length( @path1 );
2458            @path = @path1;
2459        }
2460        else
2461        {
2462            my $dist1 = newick_path_length( @path1 );
2463            my $dist2 = newick_path_length( @path2 );
2464            $dist = $fraction * ( $dist1 + $dist2 ) - $dist1;
2465            @path = ( $dist <= 0 ) ? @path1 : @path2;
2466            $dist = abs( $dist );
2467        }
2468    
2469        #  Descend tree until we reach the insertion branch:
2470    
2471        my $x;
2472        while ( ( $dist > ( $x = newick_x( $path[2] ) ) ) && ( @path > 3 ) )
2473        {
2474            $dist -= $x;
2475            splice( @path, 0, 2 );
2476        }
2477    
2478        #  Insert the new node:
2479    
2480        set_newick_desc_i( $path[0], $path[1], [ [ $path[2], $subtree ], undef, $dist ] );
2481        set_newick_x( $path[2], ( ( $x > $dist ) ? ( $x - $dist ) : 0 ) );
2482    
2483        return $tree;
2484    }
2485    
2486    
2487  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2488  #  Prune one or more tips from a tree:  #  Prune one or more tips from a tree:
# Line 1941  Line 2565 
2565    
2566    
2567  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2568    #  Produce a potentially rooted subtree with the desired tips:
2569    #
2570    #     Except for (some) tip nodes, the tree produced is a copy.
2571    #     There is no check that requested tips exist.
2572    #
2573    #  $newtree = rooted_newick_subtree( $tree,  @tips )
2574    #  $newtree = rooted_newick_subtree( $tree, \@tips )
2575    #-------------------------------------------------------------------------------
2576    sub rooted_newick_subtree {
2577        my ( $tr, @tips ) = @_;
2578        if ( @tips == 1 && ref( $tips[0] ) eq "ARRAY" ) { @tips = @{ $tips[0] } }
2579    
2580        if ( @tips < 2 ) { return undef }
2581        my $keephash = { map { ( $_, 1 ) } @tips };
2582        my $tr2 = subtree1( $tr, $keephash );
2583        $tr2->[2] = undef if $tr2;                   # undef root branch length
2584        $tr2;
2585    }
2586    
2587    
2588    #-------------------------------------------------------------------------------
2589  #  Produce a subtree with the desired tips:  #  Produce a subtree with the desired tips:
2590  #  #
2591  #     Except for (some) tip nodes, the tree produced is a copy.  #     Except for (some) tip nodes, the tree produced is a copy.
# Line 2014  Line 2659 
2659  }  }
2660    
2661    
2662    #-------------------------------------------------------------------------------
2663    #  The smallest subtree of rooted tree that includes @tips:
2664    #
2665    #    $node = newick_covering_subtree( $tree,  @tips )
2666    #    $node = newick_covering_subtree( $tree, \@tips )
2667    #-------------------------------------------------------------------------------
2668    
2669    sub newick_covering_subtree {
2670        my $tree = shift;
2671        my %tips = map { $_ => 1 } ( ( ref( $_[0] ) eq 'ARRAY' ) ? @{ $_[0] } : @_ );
2672    
2673        #  Return smallest covering node, if any:
2674    
2675        ( newick_covering_subtree( $tree, \%tips ) )[ 0 ];
2676    }
2677    
2678    
2679    sub newick_covering_subtree_1 {
2680        my ( $node, $tips ) = @_;
2681        my $n_cover = 0;
2682        my @desc = newick_desc_list( $node );
2683        if ( @desc )
2684        {
2685            foreach ( @desc )
2686            {
2687                my ( $subtree, $n ) = newick_covering_subtree_1( $_, $tips );
2688                return ( $subtree, $n ) if $subtree;
2689                $n_cover += $n;
2690            }
2691        }
2692        elsif ( $tips->{ newick_lbl( $node ) } )
2693        {
2694            $n_cover++;
2695        }
2696    
2697        #  If all tips are covered, return node
2698    
2699        ( $n_cover == keys %$tips ) ? ( $node, $n_cover ) : ( undef, $n_cover );
2700    }
2701    
2702    
2703    #===============================================================================
2704    #
2705    #  Representative subtrees
2706    #
2707    #===============================================================================
2708    #  Find subtree of size n representating vicinity of the root:
2709    #
2710    #   $subtree = root_neighborhood_representative_tree( $tree, $n, \%tip_priority )
2711    #   $subtree = root_neighborhood_representative_tree( $tree, $n )
2712    #
2713    #  Note that if $tree is rooted, then the subtree will also be.  This can have
2714    #  consequences on downstream programs.
2715    #-------------------------------------------------------------------------------
2716    sub root_neighborhood_representative_tree
2717    {
2718        my ( $tree, $n, $tip_priority ) = @_;
2719        array_ref( $tree ) && ( $n >= 2 ) or return undef;
2720        if ( newick_tip_count( $tree ) <= $n ) { return $tree }
2721    
2722        $tip_priority ||= default_tip_priority( $tree );
2723        my @tips = map { representative_tip_of_newick_node( $_, $tip_priority ) }
2724                   root_proximal_newick_subtrees( $tree, $n );
2725    
2726        newick_subtree( copy_newick_tree( $tree ), \@tips );
2727    }
2728    
2729    
2730    #-------------------------------------------------------------------------------
2731    #  Find n tips to represent tree lineages in vicinity of another tip.
2732    #  Default tip priority is short total branch length.
2733    #
2734    #  \@tips = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
2735    #   @tips = root_neighborhood_representative_tips( $tree, $n, \%tip_priority )
2736    #  \@tips = root_neighborhood_representative_tips( $tree, $n )
2737    #   @tips = root_neighborhood_representative_tips( $tree, $n )
2738    #-------------------------------------------------------------------------------
2739    sub root_neighborhood_representative_tips
2740    {
2741        my ( $tree, $n, $tip_priority ) = @_;
2742        array_ref( $tree ) && ( $n >= 2 ) or return undef;
2743    
2744        my @tips;
2745        if ( newick_tip_count( $tree ) <= $n )
2746        {
2747            @tips = newick_tip_list( $tree );
2748        }
2749        else
2750        {
2751            $tip_priority ||= default_tip_priority( $tree );
2752            @tips = map { representative_tip_of_newick_node( $_, $tip_priority ) }
2753                    root_proximal_newick_subtrees( $tree, $n );
2754        }
2755    
2756        wantarray ? @tips : \@tips;
2757    }
2758    
2759    
2760    #-------------------------------------------------------------------------------
2761    #  Find subtree of size n representating vicinity of a tip:
2762    #
2763    #   $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n, \%tip_priority )
2764    #   $subtree = tip_neighborhood_representative_tree( $tree, $tip, $n )
2765    #-------------------------------------------------------------------------------
2766    sub tip_neighborhood_representative_tree
2767    {
2768        my ( $tree, $tip, $n, $tip_priority ) = @_;
2769        array_ref( $tree ) && $tip && ( $n >= 2 ) or return undef;
2770        newick_tip_in_tree( $tree, $tip ) or return undef;
2771    
2772        my $tree1 = copy_newick_tree( $tree );
2773        if ( newick_tip_count( $tree1 ) - 1 <= $n )
2774        {
2775            return prune_from_newick( $tree1, $tip )
2776        }
2777    
2778        $tree1 = reroot_newick_to_tip( $tree1, $tip );
2779        $tree1 = newick_desc_i( $tree1, 1 );        # Node immediately below tip
2780        my @tips = root_neighborhood_representative_tips( $tree1, $n, $tip_priority );
2781        newick_subtree( copy_newick_tree( $tree ), \@tips );
2782    }
2783    
2784    
2785    #-------------------------------------------------------------------------------
2786    #  Find n tips to represent tree lineages in vicinity of another tip.
2787    #  Default tip priority is short total branch length.
2788    #
2789    #  \@tips = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
2790    #   @tips = tip_neighborhood_representative_tips( $tree, $tip, $n, \%tip_priority )
2791    #  \@tips = tip_neighborhood_representative_tips( $tree, $tip, $n )
2792    #   @tips = tip_neighborhood_representative_tips( $tree, $tip, $n )
2793    #-------------------------------------------------------------------------------
2794    sub tip_neighborhood_representative_tips
2795    {
2796        my ( $tree, $tip, $n, $tip_priority ) = @_;
2797        array_ref( $tree ) && $tip && ( $n >= 2 ) or return undef;
2798        newick_tip_in_tree( $tree, $tip ) or return undef;
2799    
2800        my @tips = newick_tip_list( $tree );
2801        if ( newick_tip_count( $tree ) - 1 <= $n )
2802        {
2803            @tips = grep { $_ ne $tip } @tips;
2804        }
2805        else
2806        {
2807            my $tree1 = copy_newick_tree( $tree );
2808            $tree1 = reroot_newick_to_tip( $tree1, $tip );
2809            $tree1 = newick_desc_i( $tree1, 1 );        # Node immediately below tip
2810            @tips = root_neighborhood_representative_tips( $tree1, $n, $tip_priority );
2811        }
2812    
2813        wantarray ? @tips : \@tips;
2814    }
2815    
2816    
2817    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2818    #  Anonymous hash of the negative distance from root to each tip:
2819    #
2820    #   \%tip_priority = default_tip_priority( $tree )
2821    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2822    sub default_tip_priority
2823    {
2824        my ( $tree ) = @_;
2825        my $tip_distances = newick_tip_distances( $tree ) || {};
2826        return { map { $_ => -$tip_distances->{$_} } keys %$tip_distances };
2827    }
2828    
2829    
2830    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2831    #  Select a tip from a subtree base on a priority value:
2832    #
2833    #    $tip = representative_tip_of_newick_node( $node, \%tip_priority )
2834    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2835    sub representative_tip_of_newick_node
2836    {
2837        my ( $node, $tip_priority ) = @_;
2838        my ( $tip ) = sort { $b->[1] <=> $a->[1] }   # The best
2839                      map  { [ $_, $tip_priority->{ $_ } ] }
2840                      newick_tip_list( $node );
2841        $tip->[0];                                   # Label from label-priority pair
2842    }
2843    
2844    
2845    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2846    #  Find n subtrees focused around the root of a tree.  Typically each will
2847    #  then be reduced to a single tip to make a representative tree:
2848    #
2849    #   @subtrees = root_proximal_newick_subtrees( $tree, $n )
2850    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2851    sub root_proximal_newick_subtrees
2852    {
2853        my ( $tree, $n ) = @_;
2854        my $node_start_end = newick_branch_intervals( $tree );
2855        n_representative_branches( $n, $node_start_end );
2856    }
2857    
2858    
2859    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2860    #   @node_start_end = newick_branch_intervals( $tree )
2861    #  \@node_start_end = newick_branch_intervals( $tree )
2862    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2863    sub newick_branch_intervals
2864    {
2865        my ( $node, $parent_x ) = @_;
2866        $parent_x ||= 0;
2867        my ( $desc, undef, $dx ) = @$node;
2868        my $x = $parent_x + $dx;
2869        my $interval = [ $node, $parent_x, $desc && @$desc ? $x : 1e100 ];
2870        my @intervals = ( $interval,
2871                          map { &newick_branch_intervals( $_, $x ) } @$desc
2872                        );
2873        return wantarray ? @intervals : \@intervals;
2874    }
2875    
2876    
2877    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2878    #   @ids = n_representative_branches( $n,  @id_start_end )
2879    #   @ids = n_representative_branches( $n, \@id_start_end )
2880    #  \@ids = n_representative_branches( $n,  @id_start_end )
2881    #  \@ids = n_representative_branches( $n, \@id_start_end )
2882    #- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
2883    sub n_representative_branches
2884    {
2885        my $n = shift;
2886        #  Sort intervals by start point:
2887        my @unprocessed = sort { $a->[1] <=> $b->[1] }
2888                          ( @_ == 1 ) ? @{ $_[0] } : @_;
2889        my @active = ();
2890        my ( $interval, $current_point );
2891        foreach $interval ( @unprocessed )
2892        {
2893            $current_point = $interval->[1];
2894            #  Filter out intervals that have ended.  This is N**2 in the number
2895            #  of representatives.  Fixing this would require maintaining a sorted
2896            #  active list.
2897            @active = grep { $_->[2] > $current_point } @active;
2898            push @active, $interval;
2899            last if ( @active >= $n );
2900        }
2901    
2902        my @ids = map { $_->[0] } @active;
2903        return wantarray() ? @ids : \@ids;
2904    }
2905    
2906    
2907  #===============================================================================  #===============================================================================
2908  #  #
2909  #  Tree writing and reading  #  Tree writing and reading
2910  #  #
2911  #===============================================================================  #===============================================================================
2912  #  writeNewickTree( $tree [, $file ] )  #  writeNewickTree( $tree )
2913    #  writeNewickTree( $tree, $file )
2914    #  writeNewickTree( $tree, \*FH )
2915  #-------------------------------------------------------------------------------  #-------------------------------------------------------------------------------
2916  sub writeNewickTree {  sub writeNewickTree {
2917      my ( $tree, $file ) = @_;      my ( $tree, $file ) = @_;
2918      $file || ( $file = \*STDOUT );      my ( $fh, $close ) = open_output( $file );
2919      print  $file  ( strNewickTree( $tree ), "\n" );      $fh or return;
2920        print  $fh  ( strNewickTree( $tree ), "\n" );
2921        close $fh if $close;
2922  }  }
2923    
2924    
# Line 2167  Line 3061 
3061    
3062    
3063  #===============================================================================  #===============================================================================
3064    #  $tree  = read_newick_tree( $file )  # reads to a semicolon
3065    #  @trees = read_newick_trees( $file ) # reads to end of file
3066    #===============================================================================
3067    
3068    sub read_newick_tree
3069    {
3070        my $file = shift;
3071        my ( $fh, $close ) = open_input( $file );
3072        my $tree;
3073        my @lines = ();
3074        foreach ( <$fh> )
3075        {
3076            chomp;
3077            push @lines, $_;
3078            if ( /;/ )
3079            {
3080                $tree = parse_newick_tree_str( join( ' ', @lines ) );
3081                last;
3082            }
3083        }
3084        close $fh if $close;
3085    
3086        $tree;
3087    }
3088    
3089    
3090    sub read_newick_trees
3091    {
3092        my $file = shift;
3093        my ( $fh, $close ) = open_input( $file );
3094        my @trees = ();
3095        my @lines = ();
3096        foreach ( <$fh> )
3097        {
3098            chomp;
3099            push @lines, $_;
3100            if ( /;/ )
3101            {
3102                push @trees, parse_newick_tree_str( join( ' ', @lines ) );
3103                @lines = ()
3104            }
3105        }
3106        close $fh if $close;
3107    
3108        @trees;
3109    }
3110    
3111    
3112    #===============================================================================
3113  #  Tree reader adapted from the C language reader in fastDNAml  #  Tree reader adapted from the C language reader in fastDNAml
3114  #  #
3115  #  $tree = parse_newick_tree_str( $string )  #  $tree = parse_newick_tree_str( $string )
# Line 2337  Line 3280 
3280      #  Loop while it is a comment:      #  Loop while it is a comment:
3281      while ( substr( $s, $ind, 1 ) eq "[" ) {      while ( substr( $s, $ind, 1 ) eq "[" ) {
3282          $ind++;          $ind++;
3283            my $depth = 1;
3284            my $ind2  = $ind;
3285    
3286          #  Find end          #  Find end
3287          if ( substr( $s, $ind ) !~ /^([^]]*)\]/ ) {          while ( $depth > 0 )
3288            {
3289                if ( substr( $s, $ind2 ) =~ /^([^][]*\[)/ )     # nested [ ... ]
3290                {
3291                    $ind2 += length( $1 );  #  Points at char just past [
3292                    $depth++;               #  If nested comments are allowed
3293                }
3294                elsif ( substr( $s, $ind2 ) =~ /^([^][]*\])/ )  # close bracket
3295                {
3296                    $ind2 += length( $1 );  #  Points at char just past ]
3297                    $depth--;
3298                }
3299                else
3300                {
3301              treeParseError( "comment missing closing bracket '["              treeParseError( "comment missing closing bracket '["
3302                             . substr( $s, $ind ) . "'" )                             . substr( $s, $ind ) . "'" )
3303          }          }
3304          my $comment = $1;          }
3305    
3306          #  Save if it includes any "text"          my $comment = substr( $s, $ind, $ind2-$ind-1 );
3307          if ( $comment =~ m/\S/ ) { push @clist, $comment }          if ( $comment =~ m/\S/ ) { push @clist, $comment }
3308    
3309          $ind += length( $comment ) + 1;     #  Comment plus closing bracket          $ind = $ind2;
3310    
3311          #  Skip white space          #  Skip white space
3312          if ( substr( $s, $ind ) =~ /^(\s+)/ ) { $ind += length( $1 ) }          if ( substr( $s, $ind ) =~ /^(\s+)/ ) { $ind += length( $1 ) }
# Line 2378  Line 3336 
3336  sub printer_plot_newick {  sub printer_plot_newick {
3337      my ( $node, $file, $width, $min_dx, $dy ) = @_;      my ( $node, $file, $width, $min_dx, $dy ) = @_;
3338    
3339      my ( $fh, $close );      my ( $fh, $close ) = open_output( $file );
3340      if ( ! defined( $file ) ) {      $fh or return;
         $fh = \*STDOUT;  
     }  
     elsif ( $file =~ /^\*/ ) {  
         $fh = $file;  
     }  
     else {  
         open $fh, ">$file" or die "Could not open $file for writing printer_plot_newick\n";  
         $close = 1;  
     }  
3341    
3342      print $fh join( "\n", text_plot_newick( $node, $width, $min_dx, $dy ) ), "\n";      print $fh join( "\n", text_plot_newick( $node, $width, $min_dx, $dy ) ), "\n";
3343      if ( $close ) { close $fh }      if ( $close ) { close $fh }
# Line 2555  Line 3504 
3504  }  }
3505    
3506    
3507    #===============================================================================
3508    #  Open an input file stream:
3509    #
3510    #     ( $handle, undef ) = open_input(       );  # \*STDIN
3511    #     ( $handle, undef ) = open_input( \*FH  );
3512    #     ( $handle, 1     ) = open_input( $file );  # need to close $handle
3513    #
3514    #===============================================================================
3515    sub open_input
3516    {
3517        my $file = shift;
3518        my $fh;
3519        if    ( ! defined( $file ) )     { return ( \*STDIN ) }
3520        elsif ( ref( $file ) eq 'GLOB' ) { return ( $file   ) }
3521        elsif ( open( $fh, "<$file" ) )  { return ( $fh, 1  ) } # Need to close
3522    
3523        print STDERR "gjonewick::open_input could not open '$file' for reading\n";
3524        return undef;
3525    }
3526    
3527    
3528    #===============================================================================
3529    #  Open an output file stream:
3530    #
3531    #     ( $handle, undef ) = open_output(      );  # \*STDOUT
3532    #     ( $handle, undef ) = open_output( \*FH );
3533    #     ( $handle, 1     ) = open_output( $file ); # need to close $handle
3534    #
3535    #===============================================================================
3536    sub open_output
3537    {
3538        my $file = shift;
3539        my $fh;
3540        if    ( ! defined( $file ) )     { return ( \*STDOUT ) }
3541        elsif ( ref( $file ) eq 'GLOB' ) { return ( $file    ) }
3542        elsif ( ( open $fh, ">$file" ) ) { return ( $fh, 1   ) } # Need to close
3543    
3544        print STDERR "gjonewick::open_output could not open '$file' for writing\n";
3545        return undef;
3546    }
3547    
3548    
3549    #===============================================================================
3550    #  Some subroutines copied from gjolists
3551    #===============================================================================
3552    #  Return the common prefix of two lists:
3553    #
3554    #  @common = common_prefix( \@list1, \@list2 )
3555    #-----------------------------------------------------------------------------
3556    sub common_prefix
3557    {
3558        my ($l1, $l2) = @_;
3559        ref($l1) eq "ARRAY" || die "common_prefix: arg 1 is not an array ref\n";
3560        ref($l2) eq "ARRAY" || die "common_prefix: arg 2 is not an array ref\n";
3561    
3562        my $i = 0;
3563        my $l1_i;
3564        while ( defined( $l1_i = $l1->[$i] ) && $l1_i eq $l2->[$i] ) { $i++ }
3565    
3566        return @$l1[ 0 .. ($i-1) ];  # perl handles negative range
3567    }
3568    
3569    
3570    #-----------------------------------------------------------------------------
3571    #  Return the unique suffixes of each of two lists:
3572    #
3573    #  ( \@suffix1, \@suffix2 ) = unique_suffixes( \@list1, \@list2 )
3574    #-----------------------------------------------------------------------------
3575    sub unique_suffixes
3576    {
3577        my ($l1, $l2) = @_;
3578        ref($l1) eq "ARRAY" || die "common_prefix: arg 1 is not an array ref\n";
3579        ref($l2) eq "ARRAY" || die "common_prefix: arg 2 is not an array ref\n";
3580    
3581        my $i = 0;
3582        my @l1 = @$l1;
3583        my @l2 = @$l2;
3584        my $l1_i;
3585        while ( defined( $l1_i = $l1[$i] ) && $l1_i eq $l2[$i] ) { $i++ }
3586    
3587        splice @l1, 0, $i;
3588        splice @l2, 0, $i;
3589        return ( \@l1, \@l2 );
3590    }
3591    
3592    
3593    #-------------------------------------------------------------------------------
3594    #  List of values duplicated in a list (stable in order by second occurance):
3595    #
3596    #  @dups = duplicates( @list )
3597    #-------------------------------------------------------------------------------
3598    sub duplicates
3599    {
3600        my %cnt = ();
3601        grep { ++$cnt{$_} == 2 } @_;
3602    }
3603    
3604    
3605    #-------------------------------------------------------------------------------
3606    #  Randomize the order of a list:
3607    #
3608    #  @random = random_order( @list )
3609    #-------------------------------------------------------------------------------
3610    sub random_order
3611    {
3612        my ( $i, $j );
3613        for ( $i = @_ - 1; $i > 0; $i-- )
3614        {
3615            $j = int( ($i+1) * rand() );
3616            ( $_[$i], $_[$j] ) = ( $_[$j], $_[$i] ); # Interchange i and j
3617        }
3618    
3619       @_;
3620    }
3621    
3622    
3623    #-----------------------------------------------------------------------------
3624    #  Intersection of two or more sets:
3625    #
3626    #  @intersection = intersection( \@set1, \@set2, ... )
3627    #-----------------------------------------------------------------------------
3628    sub intersection
3629    {
3630        my $set = shift;
3631        my @intersection = @$set;
3632    
3633        foreach $set ( @_ )
3634        {
3635            my %set = map { $_ => 1 } @$set;
3636            @intersection = grep { exists $set{ $_ } } @intersection;
3637        }
3638    
3639        @intersection;
3640    }
3641    
3642    
3643    #-----------------------------------------------------------------------------
3644    #  Elements in set 1, but not set 2:
3645    #
3646    #  @difference = set_difference( \@set1, \@set2 )
3647    #-----------------------------------------------------------------------------
3648    sub set_difference
3649    {
3650        my ($set1, $set2) = @_;
3651        my %set2 = map { $_ => 1 } @$set2;
3652        grep { ! ( exists $set2{$_} ) } @$set1;
3653    }
3654    
3655    
3656  1;  1;

Legend:
Removed from v.1.5  
changed lines
  Added in v.1.12

MCS Webmaster
ViewVC Help
Powered by ViewVC 1.0.3