clean up
[jalview.git] / forester / java / src / org / forester / sdi / SDIR.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // Copyright (C) 2000-2001 Washington University School of Medicine
8 // and Howard Hughes Medical Institute
9 // All rights reserved
10 //
11 // This library is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU Lesser General Public
13 // License as published by the Free Software Foundation; either
14 // version 2.1 of the License, or (at your option) any later version.
15 //
16 // This library is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 // Lesser General Public License for more details.
20 //
21 // You should have received a copy of the GNU Lesser General Public
22 // License along with this library; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 //
25 // Contact: phylosoft @ gmail . com
26 // WWW: www.phylosoft.org/forester
27
28 package org.forester.sdi;
29
30 import java.util.ArrayList;
31 import java.util.HashSet;
32 import java.util.List;
33 import java.util.Set;
34
35 import org.forester.phylogeny.Phylogeny;
36 import org.forester.phylogeny.PhylogenyBranch;
37 import org.forester.phylogeny.PhylogenyNode;
38 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
39
40 /*
41  * Allows to infer duplications - speciations on a unrooted gene tree. It
42  * reroots the gene trees on each of its branches and performs SDIse on each of
43  * the resulting trees. Trees which minimize a certain criterion are returned as
44  * the "correctly" rooted ones. The criterions are: <ul> <li>Sum of duplications
45  * <li>Mapping cost L <li>Phylogeny height - which is the largest distance from
46  * root to external node (minimizing of which is the same as "midpoint rooting")
47  * </ul>
48  * 
49  * @see SDIse
50  * 
51  * @see SDI
52  * 
53  * @author Christian M. Zmasek
54  */
55 public class SDIR {
56
57     private final static double ZERO_DIFF = 1.0E-6; // Due to inaccurate
58     // calculations on
59     // Java's side, not
60     // everything that should
61     // be 0.0 is 0.0.
62     private int                 _count;
63     private int                 _min_dup;
64     private int                 _min_cost;
65     private double              _min_height;
66     private double              _min_diff;
67     private long                _time_sdi;
68
69     /**
70      * Default contructor which creates an "empty" object..
71      */
72     public SDIR() {
73         init();
74     }
75
76     /**
77      * Returns the number of differently rooted trees which minimize the
78      * (rooting) "criterion" - as determined by method "infer".
79      * 
80      * @see #infer(Phylogeny,Phylogeny,boolean,boolean,boolean,boolean,int,boolean)
81      * @return number of differently rooted trees which minimized the criterion
82      */
83     public int getCount() {
84         return _count;
85     }
86
87     /**
88      * Returns the (absolue value of the) minimal difference in tree heights of
89      * the two subtrees at the root (of the (re)rooted gene tree) - as
90      * determined by method "infer" - if minimize_height is set to true.
91      * <p>
92      * If a tree is midpoint rooted this number is zero.
93      * <p>
94      * <B>IMPORTANT </B>: If minimize_mapping_cost or minimize_sum_of_dup are
95      * also set to true, then this returns the minimal difference in tree
96      * heights of the trees which minimize the first criterion, and is therefore
97      * not necessarily zero.
98      * <p>
99      * (Last modified: 01/22/00)
100      * 
101      * @see #infer(Phylogeny,Phylogeny,boolean,boolean,boolean,boolean,int,boolean)
102      * @return the minimal difference in tree heights -- IF calculated by
103      *         "infer"
104      */
105     public double getMinimalDiffInSubTreeHeights() {
106         return _min_diff;
107     }
108
109     /**
110      * Returns the minimal number of duplications - as determined by method
111      * "infer".
112      * <p>
113      * <B>IMPORTANT </B>: If the tree is not rooted by minimizing the sum of
114      * duplications or the mapping cost L, then this number is NOT NECESSARILY
115      * the MINIMAL number of duplications.
116      * 
117      * @see #infer(Phylogeny,Phylogeny,boolean,boolean,boolean,boolean,int,boolean)
118      * @return (minimal) number of duplications
119      */
120     public int getMinimalDuplications() {
121         return _min_dup;
122     }
123
124     /**
125      * Returns the minimal mapping cost L - as determined by method "infer" - if
126      * minimize_mapping_cost is set to true.
127      * <p>
128      * (Last modified: 11/07/00)
129      * 
130      * @see #infer(Phylogeny,Phylogeny,boolean,boolean,boolean,boolean,int,boolean)
131      * @return the minimal mapping cost "L" -- IF calculated by "infer"
132      */
133     public int getMinimalMappingCost() {
134         return _min_cost;
135     }
136
137     /**
138      * Returns the minimal tree height - as determined by method "infer" - if
139      * minimize_height is set to true. <B>IMPORTANT </B>: If
140      * minimize_mapping_cost or minimize_sum_of_dup are also set to true, then
141      * this returns the minimal tree height of the trees which minimize the
142      * first criterion.
143      * <p>
144      * (Last modified: 01/12/00)
145      * 
146      * @see #infer(Phylogeny,Phylogeny,boolean,boolean,boolean,boolean,int,boolean)
147      * @return the minimal tree height -- IF calculated by "infer"
148      */
149     public double getMinimalTreeHeight() {
150         return _min_height;
151     }
152
153     /**
154      * Returns the sum of times (in ms) needed to run method infer of class SDI.
155      * Final variable TIME needs to be set to true.
156      * 
157      * @return sum of times (in ms) needed to run method infer of class SDI
158      */
159     public long getTimeSumSDI() {
160         return _time_sdi;
161     }
162
163     /**
164      * Infers gene duplications on a possibly unrooted gene Phylogeny gene_tree.
165      * The tree is rooted be minimizing either the sum of duplications, the
166      * mapping cost L, or the tree height (or combinations thereof). If
167      * return_trees is set to true, it returns an array of possibly more than
168      * one differently rooted Trees. <br>
169      * The maximal number of returned trees is set with max_trees_to_return.
170      * <br>
171      * Phylogeny species_tree is a species Phylogeny to which the gene Phylogeny
172      * gene_tree is compared to. <br>
173      * If both minimize_sum_of_dup and minimize_mapping_cost are true, the tree
174      * is rooted by minimizing the mapping cost L.<br>
175      * If minimize_sum_of_dup, minimize_mapping_cost, and minimize_height are
176      * false tree gene_tree is assumed to be alreadty rooted and no attempts at
177      * rooting are made, and only one tree is returned. <br>
178      * <p>
179      * Conditions:
180      * </p>
181      * <ul>
182      * <li>Both Trees must be completely binary (except deepest node of gene
183      * tree)
184      * <li>The species Phylogeny must be rooted
185      * <li>Both Trees must have species names in the species name fields of
186      * their nodes
187      * <li>Both Trees must not have any collapses nodes
188      * </ul>
189      * <p>
190      * (Last modified: 10/01/01)
191      * 
192      * @param gene_tree
193      *            a binary (except deepest node) gene Phylogeny
194      * @param species_tree
195      *            a rooted binary species Phylogeny
196      * @param minimize_mapping_cost
197      *            set to true to root by minimizing the mapping cost L (and also
198      *            the sum of duplications)
199      * @param minimize_sum_of_dup
200      *            set to true to root by minimizing the sum of duplications
201      * @param minimize_height
202      *            set to true to root by minimizing the tree height - if
203      *            minimize_mapping_cost is set to true or minimize_sum_of_dup is
204      *            set to true, then out of the resulting trees with minimal
205      *            mapping cost or minimal number of duplications the tree with
206      *            the minimal height is chosen
207      * @param return_trees
208      *            set to true to return Array of Trees, otherwise null is
209      *            returned
210      * @param max_trees_to_return
211      *            maximal number of Trees to return (=maximal size of returned
212      *            Array) must be no lower than 1
213      * @return array of rooted Trees with duplication vs. speciation assigned if
214      *         return_trees is set to true, null otherwise
215      */
216     public Phylogeny[] infer( final Phylogeny gene_tree,
217                               final Phylogeny species_tree,
218                               final boolean minimize_mapping_cost,
219                               boolean minimize_sum_of_dup,
220                               final boolean minimize_height,
221                               final boolean return_trees,
222                               int max_trees_to_return ) {
223         init();
224         SDIse sdise = null;
225         final ArrayList<Phylogeny> trees = new ArrayList<Phylogeny>();
226         Phylogeny[] tree_array = null;
227         List<PhylogenyBranch> branches = null;
228         Phylogeny g = null;
229         PhylogenyNode prev_root = null;
230         PhylogenyNode prev_root_c1 = null;
231         PhylogenyNode prev_root_c2 = null;
232         int duplications = 0;
233         int cost = 0;
234         int counter = 0;
235         int min_duplications = Integer.MAX_VALUE;
236         int min_cost = Integer.MAX_VALUE;
237         int j = 0;
238         double height = 0.0;
239         double diff = 0.0;
240         double min_height = Double.MAX_VALUE;
241         double min_diff = 0.0;
242         double[] height__diff = new double[ 2 ];
243         boolean smaller = false;
244         boolean equal = false;
245         boolean prev_root_was_dup = false;
246         if ( max_trees_to_return < 1 ) {
247             max_trees_to_return = 1;
248         }
249         if ( minimize_mapping_cost && minimize_sum_of_dup ) {
250             minimize_sum_of_dup = false;
251         }
252         if ( !minimize_mapping_cost && !minimize_sum_of_dup && !minimize_height ) {
253             throw new IllegalArgumentException( "parameter to minimize not given for rooting of phylogeny" );
254         }
255         g = gene_tree.copy();
256         if ( g.getNumberOfExternalNodes() <= 1 ) {
257             g.setRooted( true );
258             setMinimalDuplications( 0 );
259             setMinimalTreeHeight( 0.0 );
260             tree_array = new Phylogeny[ 1 ];
261             tree_array[ 0 ] = g;
262             return tree_array;
263         }
264         for( final PhylogenyNodeIterator iter = g.iteratorPostorder(); iter.hasNext(); ) {
265             final PhylogenyNode n = iter.next();
266             if ( n.isRoot() ) {
267                 if ( ( n.getNumberOfDescendants() != 2 ) && ( n.getNumberOfDescendants() != 3 ) ) {
268                     throw new IllegalArgumentException( "attempt to run SDI on gene tree with "
269                             + n.getNumberOfDescendants() + " child nodes at its root" );
270                 }
271             }
272             else if ( !n.isExternal() && ( n.getNumberOfDescendants() != 2 ) ) {
273                 throw new IllegalArgumentException( "attempt to run SDI on gene tree which is not completely binary [found node with "
274                         + n.getNumberOfDescendants() + " child nodes]" );
275             }
276         }
277         for( final PhylogenyNodeIterator iter = species_tree.iteratorPostorder(); iter.hasNext(); ) {
278             final PhylogenyNode n = iter.next();
279             if ( !n.isExternal() && ( n.getNumberOfDescendants() != 2 ) ) {
280                 throw new IllegalArgumentException( "attempt to run SDI with a species tree which is not completely binary (after stripping) [found node with "
281                         + n.getNumberOfDescendants() + " child nodes]" );
282             }
283         }
284         g.reRoot( g.getFirstExternalNode() );
285         branches = SDIR.getBranchesInPreorder( g );
286         if ( minimize_mapping_cost || minimize_sum_of_dup ) {
287             sdise = new SDIse( g, species_tree );
288             duplications = sdise.getDuplicationsSum();
289         }
290         final Set<PhylogenyBranch> used_root_placements = new HashSet<PhylogenyBranch>();
291         F: for( j = 0; j < branches.size(); ++j ) {
292             prev_root = g.getRoot();
293             prev_root_c1 = prev_root.getChildNode1();
294             prev_root_c2 = prev_root.getChildNode2();
295             prev_root_was_dup = prev_root.isDuplication();
296             final PhylogenyBranch current_branch = branches.get( j );
297             g.reRoot( current_branch );
298             if ( minimize_mapping_cost || minimize_sum_of_dup ) {
299                 duplications = sdise.updateM( prev_root_was_dup, prev_root_c1, prev_root_c2 );
300             }
301             if ( !used_root_placements.contains( current_branch ) ) {
302                 if ( minimize_mapping_cost ) {
303                     cost = sdise.computeMappingCostL();
304                     if ( minimize_height && ( cost <= min_cost ) ) {
305                         height__diff = SDIR.moveRootOnBranchToMinHeight( g );
306                         height = height__diff[ 0 ];
307                         diff = height__diff[ 1 ];
308                     }
309                     if ( cost == min_cost ) {
310                         if ( minimize_height ) {
311                             smaller = equal = false;
312                             if ( height < min_height ) {
313                                 min_height = height;
314                                 counter = 1;
315                                 smaller = true;
316                             }
317                             else if ( height == min_height ) {
318                                 counter++;
319                                 equal = true;
320                             }
321                             if ( Math.abs( diff ) < min_diff ) {
322                                 min_diff = Math.abs( diff );
323                             }
324                         }
325                         if ( return_trees ) {
326                             if ( minimize_height ) {
327                                 if ( smaller ) {
328                                     trees.clear();
329                                     trees.add( g.copy() );
330                                 }
331                                 else if ( equal && ( trees.size() < max_trees_to_return ) ) {
332                                     trees.add( g.copy() );
333                                 }
334                             }
335                             else {
336                                 counter++;
337                                 if ( trees.size() < max_trees_to_return ) {
338                                     trees.add( g.copy() );
339                                 }
340                             }
341                         }
342                         else if ( !minimize_height ) {
343                             counter++;
344                         }
345                     }
346                     else if ( cost < min_cost ) {
347                         if ( minimize_height ) {
348                             min_height = height;
349                             min_diff = Math.abs( diff );
350                         }
351                         if ( return_trees ) {
352                             trees.clear();
353                             trees.add( g.copy() );
354                         }
355                         counter = 1;
356                         min_cost = cost;
357                     }
358                     if ( duplications < min_duplications ) {
359                         min_duplications = duplications;
360                     }
361                 }
362                 else if ( minimize_sum_of_dup ) {
363                     if ( minimize_height && ( duplications <= min_duplications ) ) {
364                         height__diff = SDIR.moveRootOnBranchToMinHeight( g );
365                         height = height__diff[ 0 ];
366                         diff = height__diff[ 1 ];
367                     }
368                     if ( duplications == min_duplications ) {
369                         if ( minimize_height ) {
370                             smaller = equal = false;
371                             if ( height < min_height ) {
372                                 min_height = height;
373                                 counter = 1;
374                                 smaller = true;
375                             }
376                             else if ( height == min_height ) {
377                                 counter++;
378                                 equal = true;
379                             }
380                             if ( Math.abs( diff ) < min_diff ) {
381                                 min_diff = Math.abs( diff );
382                             }
383                         }
384                         if ( return_trees ) {
385                             if ( minimize_height ) {
386                                 if ( smaller ) {
387                                     trees.clear();
388                                     trees.add( g.copy() );
389                                 }
390                                 else if ( equal && ( trees.size() < max_trees_to_return ) ) {
391                                     trees.add( g.copy() );
392                                 }
393                             }
394                             else {
395                                 counter++;
396                                 if ( trees.size() < max_trees_to_return ) {
397                                     trees.add( g.copy() );
398                                 }
399                             }
400                         }
401                         else if ( !minimize_height ) {
402                             counter++;
403                         }
404                     }
405                     else if ( duplications < min_duplications ) {
406                         if ( minimize_height ) {
407                             min_height = height;
408                             min_diff = Math.abs( diff );
409                         }
410                         if ( return_trees ) {
411                             trees.clear();
412                             trees.add( g.copy() );
413                         }
414                         counter = 1;
415                         min_duplications = duplications;
416                     }
417                 }
418                 else if ( minimize_height ) {
419                     height__diff = SDIR.moveRootOnBranchToMinHeight( g );
420                     height = height__diff[ 0 ];
421                     diff = height__diff[ 1 ];
422                     if ( Math.abs( diff ) < SDIR.ZERO_DIFF ) {
423                         sdise = new SDIse( g, species_tree );
424                         min_duplications = sdise.getDuplicationsSum();
425                         min_height = height;
426                         min_diff = Math.abs( diff );
427                         counter = 1;
428                         if ( return_trees ) {
429                             trees.add( g.copy() );
430                         }
431                         break F;
432                     }
433                 }
434             } // if ( used_root_placements.containsKey( current_branch ) )
435             used_root_placements.add( current_branch );
436         } // End of huge for loop "F".
437         if ( return_trees ) {
438             trees.trimToSize();
439             tree_array = new Phylogeny[ trees.size() ];
440             for( int i = 0; i < trees.size(); ++i ) {
441                 tree_array[ i ] = trees.get( i );
442                 tree_array[ i ].recalculateNumberOfExternalDescendants( false );
443             }
444         }
445         setCount( counter );
446         setMinimalDuplications( min_duplications );
447         setMinimalMappingCost( min_cost );
448         setMinimalTreeHeight( min_height );
449         setMinimalDiffInSubTreeHeights( Math.abs( min_diff ) );
450         return tree_array;
451     }
452
453     private void init() {
454         _count = -1;
455         _min_dup = Integer.MAX_VALUE;
456         _min_cost = Integer.MAX_VALUE;
457         _min_height = Double.MAX_VALUE;
458         _min_diff = Double.MAX_VALUE;
459         _time_sdi = -1;
460     }
461
462     private void setCount( final int i ) {
463         _count = i;
464     }
465
466     private void setMinimalDiffInSubTreeHeights( final double d ) {
467         _min_diff = d;
468     }
469
470     private void setMinimalDuplications( final int i ) {
471         _min_dup = i;
472     }
473
474     private void setMinimalMappingCost( final int i ) {
475         _min_cost = i;
476     }
477
478     private void setMinimalTreeHeight( final double d ) {
479         _min_height = d;
480     }
481
482     // This was totally changed on 2006/10/03.
483     // Places references to all Branches of Phylogeny t into a List.
484     // The order is preorder.
485     // Trees are treated as if they were unrooted (i.e. child 1 and
486     // child 2 of the root are treated as if they were connected
487     // directly).
488     // The resulting List allows to visit all branches without ever
489     // traversing more than one node at a time.
490     public static List<PhylogenyBranch> getBranchesInPreorder( final Phylogeny t ) {
491         final ArrayList<PhylogenyBranch> branches = new ArrayList<PhylogenyBranch>();
492         if ( t.isEmpty() || ( t.getNumberOfExternalNodes() <= 1 ) ) {
493             return branches;
494         }
495         if ( t.getNumberOfExternalNodes() == 2 ) {
496             branches.add( new PhylogenyBranch( t.getRoot().getChildNode1(), t.getRoot().getChildNode2() ) );
497             return branches;
498         }
499         final Set<Integer> one = new HashSet<Integer>();
500         final Set<Integer> two = new HashSet<Integer>();
501         PhylogenyNode node = t.getRoot();
502         while ( !node.isRoot() || !two.contains( node.getId() ) ) {
503             if ( !node.isExternal() && !two.contains( node.getId() ) ) {
504                 if ( !one.contains( node.getId() ) && !two.contains( node.getId() ) ) {
505                     one.add( node.getId() );
506                     node = node.getChildNode1();
507                 }
508                 else {
509                     two.add( node.getId() );
510                     node = node.getChildNode2();
511                 }
512                 if ( !node.getParent().isRoot() ) {
513                     branches.add( new PhylogenyBranch( node, node.getParent() ) );
514                 }
515                 else if ( !node.isExternal() ) {
516                     branches.add( new PhylogenyBranch( t.getRoot().getChildNode1(), t.getRoot().getChildNode2() ) );
517                 }
518             }
519             else {
520                 if ( !node.getParent().isRoot() && !node.isExternal() ) {
521                     branches.add( new PhylogenyBranch( node, node.getParent() ) );
522                 }
523                 node = node.getParent();
524             }
525         }
526         return branches;
527     }
528
529     // This places the root of t on its branch in such a way that it
530     // minimizes the tree height as good as possible.
531     // Returns the height and the difference in heights of the resulting
532     // modified Phylogeny t.
533     private static double[] moveRootOnBranchToMinHeight( final Phylogeny t ) {
534         final PhylogenyNode root = t.getRoot();
535         if ( root.getNumberOfDescendants() != 2 ) {
536             throw new IllegalArgumentException( "attempt to move root to minimize height on root where number of child nodes does not equal two" );
537         }
538         final PhylogenyNode child0 = root.getChildNode( 0 );
539         final PhylogenyNode child1 = root.getChildNode( 1 );
540         final double newdist = 0.5 * ( ( child0.getDistanceToParent() > 0 ? child0.getDistanceToParent() : 0 ) + ( child1
541                 .getDistanceToParent() > 0 ? child1.getDistanceToParent() : 0 ) );
542         child0.setDistanceToParent( newdist );
543         child1.setDistanceToParent( newdist );
544         final double d = child0.getDistanceToParent();
545         double diff = 0.0;
546         double height = 0.0;
547         final double[] height_diff = new double[ 2 ];
548         final double l0 = t.calculateSubtreeHeight( t.getRoot().getChildNode( 0 ) );
549         final double l1 = t.calculateSubtreeHeight( t.getRoot().getChildNode( 1 ) );
550         diff = l0 - l1;
551         height = t.getHeight();
552         if ( d > 0.0 ) {
553             if ( ( 2 * d ) > Math.abs( diff ) ) {
554                 child0.setDistanceToParent( d - ( diff / 2.0 ) );
555                 child1.setDistanceToParent( d + ( diff / 2.0 ) );
556                 height_diff[ 0 ] = height - Math.abs( diff / 2 );
557                 height_diff[ 1 ] = 0.0;
558             }
559             else {
560                 if ( diff > 0 ) {
561                     child0.setDistanceToParent( 0.0 );
562                     child1.setDistanceToParent( 2 * d );
563                     height_diff[ 1 ] = diff - ( 2 * d );
564                 }
565                 else {
566                     child0.setDistanceToParent( 2 * d );
567                     child1.setDistanceToParent( 0.0 );
568                     height_diff[ 1 ] = diff + ( 2 * d );
569                 }
570                 height_diff[ 0 ] = height - d;
571             }
572         }
573         else {
574             height_diff[ 0 ] = height;
575             height_diff[ 1 ] = diff;
576         }
577         return height_diff;
578     }
579 }