5939037a8087cd910f55fedcbe428e85132a10c4
[jalview.git] / forester / java / src / org / forester / sdi / GSDI.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 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.sdi;
27
28 import java.util.HashMap;
29 import java.util.HashSet;
30 import java.util.Map;
31 import java.util.Set;
32
33 import org.forester.phylogeny.Phylogeny;
34 import org.forester.phylogeny.PhylogenyNode;
35 import org.forester.phylogeny.data.Event;
36 import org.forester.phylogeny.data.Taxonomy;
37 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
38 import org.forester.util.ForesterUtil;
39
40 /*
41  * Implements our algorithm for speciation - duplication inference (SDI). <p>
42  * The initialization is accomplished by: </p> <ul> <li>method
43  * "linkExtNodesOfG()" of class SDI: setting the links for the external nodes of
44  * the gene tree <li>"preorderReID(int)" from class Phylogeny: numbering of
45  * nodes of the species tree in preorder <li>the optional stripping of the
46  * species tree is accomplished by method "stripTree(Phylogeny,Phylogeny)" of
47  * class Phylogeny </ul> <p> The recursion part is accomplished by this class'
48  * method "geneTreePostOrderTraversal(PhylogenyNode)". <p> Requires JDK 1.5 or
49  * greater.
50  * 
51  * @see SDI#linkNodesOfG()
52  * 
53  * @see Phylogeny#preorderReID(int)
54  * 
55  * @see
56  * PhylogenyMethods#taxonomyBasedDeletionOfExternalNodes(Phylogeny,Phylogeny)
57  * 
58  * @see #geneTreePostOrderTraversal(PhylogenyNode)
59  * 
60  * @author Christian M. Zmasek
61  */
62 public final class GSDI extends SDI {
63
64     private final HashMap<PhylogenyNode, Integer> _transversal_counts;
65     private final boolean                         _most_parsimonious_duplication_model;
66     private final boolean                         _strip_gene_tree;
67     private int                                   _speciation_or_duplication_events_sum;
68     private int                                   _speciations_sum;
69     private final Set<PhylogenyNode>              _stripped_gene_tree_nodes;
70
71     /**
72      * Constructor which sets the gene tree and the species tree to be compared.
73      * species_tree is the species tree to which the gene tree gene_tree will be
74      * compared to - with method "infer(boolean)". Both Trees must be completely
75      * binary and rooted. The actual inference is accomplished with method
76      * "infer(boolean)". The mapping cost L can then be calculated with method
77      * "computeMappingCost()".
78      * <p>
79      * 
80      * @see #infer(boolean)
81      * @see SDI#computeMappingCostL()
82      * @param gene_tree
83      *            reference to a rooted gene tree to which assign duplication vs
84      *            speciation, must have species names in the species name fields
85      *            for all external nodes
86      * @param species_tree
87      *            reference to a rooted binary species tree which might get
88      *            stripped in the process, must have species names in the
89      *            species name fields for all external nodes
90      * 
91      * @param most_parsimonious_duplication_model
92      *            set to true to assign nodes as speciations which would
93      *            otherwise be assiged as unknown because of polytomies in the
94      *            species tree.
95      * 
96      */
97     public GSDI( final Phylogeny gene_tree,
98                  final Phylogeny species_tree,
99                  final boolean most_parsimonious_duplication_model,
100                  final boolean strip_gene_tree ) {
101         super( gene_tree, species_tree );
102         _speciation_or_duplication_events_sum = 0;
103         _speciations_sum = 0;
104         _most_parsimonious_duplication_model = most_parsimonious_duplication_model;
105         _transversal_counts = new HashMap<PhylogenyNode, Integer>();
106         _duplications_sum = 0;
107         _strip_gene_tree = strip_gene_tree;
108         _stripped_gene_tree_nodes = new HashSet<PhylogenyNode>();
109         getSpeciesTree().preOrderReId();
110         linkNodesOfG();
111         geneTreePostOrderTraversal( getGeneTree().getRoot() );
112     }
113
114     public GSDI( final Phylogeny gene_tree,
115                  final Phylogeny species_tree,
116                  final boolean most_parsimonious_duplication_model ) {
117         this( gene_tree, species_tree, most_parsimonious_duplication_model, false );
118     }
119
120     private final Event createDuplicationEvent() {
121         final Event event = Event.createSingleDuplicationEvent();
122         ++_duplications_sum;
123         return event;
124     }
125
126     private final Event createSingleSpeciationOrDuplicationEvent() {
127         final Event event = Event.createSingleSpeciationOrDuplicationEvent();
128         ++_speciation_or_duplication_events_sum;
129         return event;
130     }
131
132     private final Event createSpeciationEvent() {
133         final Event event = Event.createSingleSpeciationEvent();
134         ++_speciations_sum;
135         return event;
136     }
137
138     // s is the node on the species tree g maps to.
139     private final void determineEvent( final PhylogenyNode s, final PhylogenyNode g ) {
140         Event event = null;
141         // Determine how many children map to same node as parent.
142         int sum_g_childs_mapping_to_s = 0;
143         for( final PhylogenyNodeIterator iter = g.iterateChildNodesForward(); iter.hasNext(); ) {
144             if ( iter.next().getLink() == s ) {
145                 ++sum_g_childs_mapping_to_s;
146             }
147         }
148         // Determine the sum of traversals.
149         int traversals_sum = 0;
150         int max_traversals = 0;
151         PhylogenyNode max_traversals_node = null;
152         if ( !s.isExternal() ) {
153             for( final PhylogenyNodeIterator iter = s.iterateChildNodesForward(); iter.hasNext(); ) {
154                 final PhylogenyNode current_node = iter.next();
155                 final int traversals = getTraversalCount( current_node );
156                 traversals_sum += traversals;
157                 if ( traversals > max_traversals ) {
158                     max_traversals = traversals;
159                     max_traversals_node = current_node;
160                 }
161             }
162         }
163         // System.out.println( " sum=" + traversals_sum );
164         // System.out.println( " max=" + max_traversals );
165         // System.out.println( " m=" + sum_g_childs_mapping_to_s );
166         if ( sum_g_childs_mapping_to_s > 0 ) {
167             if ( traversals_sum == 2 ) {
168                 event = createDuplicationEvent();
169             }
170             else if ( traversals_sum > 2 ) {
171                 if ( max_traversals <= 1 ) {
172                     if ( _most_parsimonious_duplication_model ) {
173                         event = createSpeciationEvent();
174                     }
175                     else {
176                         event = createSingleSpeciationOrDuplicationEvent();
177                     }
178                 }
179                 else {
180                     event = createDuplicationEvent();
181                     _transversal_counts.put( max_traversals_node, 1 );
182                 }
183             }
184             else {
185                 event = createDuplicationEvent();
186             }
187         }
188         else {
189             event = createSpeciationEvent();
190         }
191         g.getNodeData().setEvent( event );
192     }
193
194     /**
195      * Traverses the subtree of PhylogenyNode g in postorder, calculating the
196      * mapping function M, and determines which nodes represent speciation
197      * events and which ones duplication events.
198      * <p>
199      * Preconditions: Mapping M for external nodes must have been calculated and
200      * the species tree must be labeled in preorder.
201      * <p>
202      * (Last modified: )
203      * 
204      * @param g
205      *            starting node of a gene tree - normally the root
206      */
207     final void geneTreePostOrderTraversal( final PhylogenyNode g ) {
208         if ( !g.isExternal() ) {
209             for( final PhylogenyNodeIterator iter = g.iterateChildNodesForward(); iter.hasNext(); ) {
210                 geneTreePostOrderTraversal( iter.next() );
211             }
212             final PhylogenyNode[] linked_nodes = new PhylogenyNode[ g.getNumberOfDescendants() ];
213             for( int i = 0; i < linked_nodes.length; ++i ) {
214                 linked_nodes[ i ] = g.getChildNode( i ).getLink();
215             }
216             final int[] min_max = obtainMinMaxIdIndices( linked_nodes );
217             int min_i = min_max[ 0 ];
218             int max_i = min_max[ 1 ];
219             // initTransversalCounts();
220             while ( linked_nodes[ min_i ] != linked_nodes[ max_i ] ) {
221                 increaseTraversalCount( linked_nodes[ max_i ] );
222                 linked_nodes[ max_i ] = linked_nodes[ max_i ].getParent();
223                 final int[] min_max_ = obtainMinMaxIdIndices( linked_nodes );
224                 min_i = min_max_[ 0 ];
225                 max_i = min_max_[ 1 ];
226             }
227             final PhylogenyNode s = linked_nodes[ max_i ];
228             g.setLink( s );
229             // Determines whether dup. or spec.
230             determineEvent( s, g );
231             // _transversal_counts.clear();
232         }
233     }
234
235     public final int getSpeciationOrDuplicationEventsSum() {
236         return _speciation_or_duplication_events_sum;
237     }
238
239     public final int getSpeciationsSum() {
240         return _speciations_sum;
241     }
242
243     private final int getTraversalCount( final PhylogenyNode node ) {
244         if ( _transversal_counts.containsKey( node ) ) {
245             return _transversal_counts.get( node );
246         }
247         return 0;
248     }
249
250     private final void increaseTraversalCount( final PhylogenyNode node ) {
251         if ( _transversal_counts.containsKey( node ) ) {
252             _transversal_counts.put( node, _transversal_counts.get( node ) + 1 );
253         }
254         else {
255             _transversal_counts.put( node, 1 );
256         }
257         // System.out.println( "count for node " + node.getID() + " is now "
258         // + getTraversalCount( node ) );
259     }
260
261     /**
262      * This allows for linking of internal nodes of the species tree (as opposed
263      * to just external nodes, as in the method it overrides.
264      * 
265      */
266     @Override
267     final void linkNodesOfG() {
268         final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes = createTaxonomyToNodeMap();
269         if ( _strip_gene_tree ) {
270             stripGeneTree( speciestree_ext_nodes );
271             if ( ( _gene_tree == null ) || ( _gene_tree.getNumberOfExternalNodes() < 2 ) ) {
272                 throw new IllegalArgumentException( "species tree does not contain any"
273                         + " nodes matching species in the gene tree" );
274             }
275         }
276         // Retrieve the reference to the PhylogenyNode with a matching species.
277         for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
278             final PhylogenyNode g = iter.next();
279             if ( !g.getNodeData().isHasTaxonomy() ) {
280                 throw new IllegalArgumentException( "gene tree node " + g + " has no taxonomic data" );
281             }
282             final PhylogenyNode s = speciestree_ext_nodes.get( g.getNodeData().getTaxonomy() );
283             if ( s == null ) {
284                 throw new IllegalArgumentException( "species " + g.getNodeData().getTaxonomy()
285                         + " not present in species tree" );
286             }
287             g.setLink( s );
288         }
289     }
290
291     final void linkNodesOfG2() {
292         final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes = createTaxonomyToNodeMap();
293         if ( _strip_gene_tree ) {
294             stripGeneTree( speciestree_ext_nodes );
295             if ( ( _gene_tree == null ) || ( _gene_tree.getNumberOfExternalNodes() < 2 ) ) {
296                 throw new IllegalArgumentException( "species tree does not contain any"
297                         + " nodes matching species in the gene tree" );
298             }
299         }
300         // Retrieve the reference to the PhylogenyNode with a matching species.
301         for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
302             final PhylogenyNode g = iter.next();
303             if ( !g.getNodeData().isHasTaxonomy() ) {
304                 throw new IllegalArgumentException( "gene tree node " + g + " has no taxonomic data" );
305             }
306             final PhylogenyNode s = speciestree_ext_nodes.get( g.getNodeData().getTaxonomy() );
307             if ( s == null ) {
308                 throw new IllegalArgumentException( "species " + g.getNodeData().getTaxonomy()
309                         + " not present in species tree" );
310             }
311             g.setLink( s );
312         }
313         //////
314         final Map<String, PhylogenyNode> speciestree_ext_nodes = new HashMap<String, PhylogenyNode>();
315         final TaxonomyComparisonBase tax_comp_base = determineTaxonomyComparisonBase( _gene_tree );
316         if ( _strip_gene_tree ) {
317             stripGeneTree( speciestree_ext_nodes );
318             if ( ( _gene_tree == null ) || ( _gene_tree.getNumberOfExternalNodes() < 2 ) ) {
319                 throw new IllegalArgumentException( "species tree does not contain any"
320                         + " nodes matching species in the gene tree" );
321             }
322         }
323         // Put references to all external nodes of the species tree into a map.
324         // Stringyfied taxonomy is the key, node is the value.
325         for( final PhylogenyNodeIterator iter = _species_tree.iteratorExternalForward(); iter.hasNext(); ) {
326             final PhylogenyNode s = iter.next();
327             final String tax_str = taxonomyToString( s, tax_comp_base );
328             if ( speciestree_ext_nodes.containsKey( tax_str ) ) {
329                 throw new IllegalArgumentException( "taxonomy [" + s + "] is not unique in species phylogeny" );
330             }
331             speciestree_ext_nodes.put( tax_str, s );
332         }
333         // Retrieve the reference to the node with a matching stringyfied taxonomy.
334         for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
335             final PhylogenyNode g = iter.next();
336             final String tax_str = taxonomyToString( g, tax_comp_base );
337             final PhylogenyNode s = speciestree_ext_nodes.get( tax_str );
338             if ( s == null ) {
339                 throw new IllegalArgumentException( "taxonomy [" + g.getNodeData().getTaxonomy()
340                         + "] not present in species tree" );
341             }
342             g.setLink( s );
343         }
344     }
345
346     final private HashMap<Taxonomy, PhylogenyNode> createTaxonomyToNodeMap() {
347         final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes = new HashMap<Taxonomy, PhylogenyNode>();
348         for( final PhylogenyNodeIterator iter = _species_tree.iteratorLevelOrder(); iter.hasNext(); ) {
349             final PhylogenyNode n = iter.next();
350             if ( n.getNodeData().isHasTaxonomy() ) {
351                 if ( speciestree_ext_nodes.containsKey( n.getNodeData().getTaxonomy() ) ) {
352                     throw new IllegalArgumentException( "taxonomy [" + n.getNodeData().getTaxonomy()
353                             + "] is not unique in species phylogeny" );
354                 }
355                 speciestree_ext_nodes.put( n.getNodeData().getTaxonomy(), n );
356             }
357         }
358         return speciestree_ext_nodes;
359     }
360
361     private final void stripGeneTree( final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes ) {
362         //  final Set<PhylogenyNode> to_delete = new HashSet<PhylogenyNode>();
363         for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
364             final PhylogenyNode g = iter.next();
365             if ( !g.getNodeData().isHasTaxonomy() ) {
366                 throw new IllegalArgumentException( "gene tree node " + g + " has no taxonomic data" );
367             }
368             if ( !speciestree_ext_nodes.containsKey( g.getNodeData().getTaxonomy() ) ) {
369                 _stripped_gene_tree_nodes.add( g );
370             }
371         }
372         for( final PhylogenyNode n : _stripped_gene_tree_nodes ) {
373             _gene_tree.deleteSubtree( n, true );
374         }
375     }
376
377     public static TaxonomyComparisonBase determineTaxonomyComparisonBase( final Phylogeny gene_tree ) {
378         int with_id_count = 0;
379         int with_code_count = 0;
380         int with_sn_count = 0;
381         int max = 0;
382         for( final PhylogenyNodeIterator iter = gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
383             final PhylogenyNode g = iter.next();
384             if ( g.getNodeData().isHasTaxonomy() ) {
385                 final Taxonomy tax = g.getNodeData().getTaxonomy();
386                 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) {
387                     if ( ++with_id_count > max ) {
388                         max = with_id_count;
389                     }
390                 }
391                 if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
392                     if ( ++with_code_count > max ) {
393                         max = with_code_count;
394                     }
395                 }
396                 if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
397                     if ( ++with_sn_count > max ) {
398                         max = with_sn_count;
399                     }
400                 }
401             }
402         }
403         if ( max == 0 ) {
404             throw new IllegalArgumentException( "gene tree has no taxonomic data" );
405         }
406         else if ( max == 1 ) {
407             throw new IllegalArgumentException( "gene tree has only one node with taxonomic data" );
408         }
409         else if ( max == with_sn_count ) {
410             return SDI.TaxonomyComparisonBase.SCIENTIFIC_NAME;
411         }
412         else if ( max == with_id_count ) {
413             return SDI.TaxonomyComparisonBase.ID;
414         }
415         else {
416             return SDI.TaxonomyComparisonBase.CODE;
417         }
418     }
419
420     public Set<PhylogenyNode> getStrippedExternalGeneTreeNodes() {
421         return _stripped_gene_tree_nodes;
422     }
423
424     @Override
425     public final String toString() {
426         final StringBuffer sb = new StringBuffer();
427         sb.append( "Most parsimonious duplication model: " + _most_parsimonious_duplication_model );
428         sb.append( ForesterUtil.getLineSeparator() );
429         sb.append( "Speciations sum                    : " + getSpeciationsSum() );
430         sb.append( ForesterUtil.getLineSeparator() );
431         sb.append( "Duplications sum                   : " + getDuplicationsSum() );
432         sb.append( ForesterUtil.getLineSeparator() );
433         if ( !_most_parsimonious_duplication_model ) {
434             sb.append( "Speciation or duplications sum     : " + getSpeciationOrDuplicationEventsSum() );
435             sb.append( ForesterUtil.getLineSeparator() );
436         }
437         sb.append( "mapping cost L                     : " + computeMappingCostL() );
438         return sb.toString();
439     }
440
441     static final int[] obtainMinMaxIdIndices( final PhylogenyNode[] linked_nodes ) {
442         int max_i = 0;
443         int min_i = 0;
444         int max_i_id = -Integer.MAX_VALUE;
445         int min_i_id = Integer.MAX_VALUE;
446         for( int i = 0; i < linked_nodes.length; ++i ) {
447             final int id_i = linked_nodes[ i ].getId();
448             if ( id_i > max_i_id ) {
449                 max_i = i;
450                 max_i_id = linked_nodes[ max_i ].getId();
451             }
452             if ( id_i < min_i_id ) {
453                 min_i = i;
454                 min_i_id = linked_nodes[ min_i ].getId();
455             }
456         }
457         return new int[] { min_i, max_i };
458     }
459     /**
460      * Updates the mapping function M after the root of the gene tree has been
461      * moved by one branch. It calculates M for the root of the gene tree and
462      * one of its two children.
463      * <p>
464      * To be used ONLY by method "SDIunrooted.fastInfer(Phylogeny,Phylogeny)".
465      * <p>
466      * (Last modfied: )
467      * 
468      * @param prev_root_was_dup
469      *            true if the previous root was a duplication, false otherwise
470      * @param prev_root_c1
471      *            child 1 of the previous root
472      * @param prev_root_c2
473      *            child 2 of the previous root
474      * @return number of duplications which have been assigned in gene tree
475      */
476     // int updateM( final boolean prev_root_was_dup,
477     // final PhylogenyNode prev_root_c1, final PhylogenyNode prev_root_c2 ) {
478     // final PhylogenyNode root = getGeneTree().getRoot();
479     // if ( ( root.getChildNode1() == prev_root_c1 )
480     // || ( root.getChildNode2() == prev_root_c1 ) ) {
481     // calculateMforNode( prev_root_c1 );
482     // }
483     // else {
484     // calculateMforNode( prev_root_c2 );
485     // }
486     // Event event = null;
487     // if ( prev_root_was_dup ) {
488     // event = Event.createSingleDuplicationEvent();
489     // }
490     // else {
491     // event = Event.createSingleSpeciationEvent();
492     // }
493     // root.getPhylogenyNodeData().setEvent( event );
494     // calculateMforNode( root );
495     // return getDuplications();
496     // } // updateM( boolean, PhylogenyNode, PhylogenyNode )
497     // Helper method for updateM( boolean, PhylogenyNode, PhylogenyNode )
498     // Calculates M for PhylogenyNode n, given that M for the two children
499     // of n has been calculated.
500     // (Last modified: 10/02/01)
501     // private void calculateMforNode( final PhylogenyNode n ) {
502     // if ( !n.isExternal() ) {
503     // boolean was_duplication = n.isDuplication();
504     // PhylogenyNode a = n.getChildNode1().getLink(), b = n
505     // .getChildNode2().getLink();
506     // while ( a != b ) {
507     // if ( a.getID() > b.getID() ) {
508     // a = a.getParent();
509     // }
510     // else {
511     // b = b.getParent();
512     // }
513     // }
514     // n.setLink( a );
515     // Event event = null;
516     // if ( ( a == n.getChildNode1().getLink() )
517     // || ( a == n.getChildNode2().getLink() ) ) {
518     // event = Event.createSingleDuplicationEvent();
519     // if ( !was_duplication ) {
520     // increaseDuplications();
521     // }
522     // }
523     // else {
524     // event = Event.createSingleSpeciationEvent();
525     // if ( was_duplication ) {
526     // decreaseDuplications();
527     // }
528     // }
529     // n.getPhylogenyNodeData().setEvent( event );
530     // }
531     // } // calculateMforNode( PhylogenyNode )
532 }