2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
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.
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.
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
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
26 package org.forester.sdi;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
35 import org.forester.phylogeny.Phylogeny;
36 import org.forester.phylogeny.PhylogenyNode;
37 import org.forester.phylogeny.data.Event;
38 import org.forester.phylogeny.data.Taxonomy;
39 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
40 import org.forester.util.ForesterUtil;
43 * Implements our algorithm for speciation - duplication inference (SDI). <p>
44 * The initialization is accomplished by: </p> <ul> <li>method
45 * "linkExtNodesOfG()" of class SDI: setting the links for the external nodes of
46 * the gene tree <li>"preorderReID(int)" from class Phylogeny: numbering of
47 * nodes of the species tree in preorder <li>the optional stripping of the
48 * species tree is accomplished by method "stripTree(Phylogeny,Phylogeny)" of
49 * class Phylogeny </ul> <p> The recursion part is accomplished by this class'
50 * method "geneTreePostOrderTraversal(PhylogenyNode)". <p> Requires JDK 1.5 or
53 * @see SDI#linkNodesOfG()
55 * @see Phylogeny#preorderReID(int)
58 * PhylogenyMethods#taxonomyBasedDeletionOfExternalNodes(Phylogeny,Phylogeny)
60 * @see #geneTreePostOrderTraversal(PhylogenyNode)
62 * @author Christian M. Zmasek
64 public final class GSDI extends SDI {
66 private final HashMap<PhylogenyNode, Integer> _transversal_counts;
67 private final boolean _most_parsimonious_duplication_model;
68 private final boolean _strip_gene_tree;
69 private final boolean _strip_species_tree;
70 private int _speciation_or_duplication_events_sum;
71 private int _speciations_sum;
72 private final List<PhylogenyNode> _stripped_gene_tree_nodes;
73 private final List<PhylogenyNode> _stripped_species_tree_nodes;
74 private final Set<PhylogenyNode> _mapped_species_tree_nodes;
77 * Constructor which sets the gene tree and the species tree to be compared.
78 * species_tree is the species tree to which the gene tree gene_tree will be
79 * compared to - with method "infer(boolean)". Both Trees must be completely
80 * binary and rooted. The actual inference is accomplished with method
81 * "infer(boolean)". The mapping cost L can then be calculated with method
82 * "computeMappingCost()".
85 * @see #infer(boolean)
86 * @see SDI#computeMappingCostL()
88 * reference to a rooted gene tree to which assign duplication vs
89 * speciation, must have species names in the species name fields
90 * for all external nodes
92 * reference to a rooted binary species tree which might get
93 * stripped in the process, must have species names in the
94 * species name fields for all external nodes
96 * @param most_parsimonious_duplication_model
97 * set to true to assign nodes as speciations which would
98 * otherwise be assiged as unknown because of polytomies in the
100 * @throws SdiException
103 public GSDI( final Phylogeny gene_tree,
104 final Phylogeny species_tree,
105 final boolean most_parsimonious_duplication_model,
106 final boolean strip_gene_tree,
107 final boolean strip_species_tree ) throws SdiException {
108 super( gene_tree, species_tree );
109 _speciation_or_duplication_events_sum = 0;
110 _speciations_sum = 0;
111 _most_parsimonious_duplication_model = most_parsimonious_duplication_model;
112 _transversal_counts = new HashMap<PhylogenyNode, Integer>();
113 _duplications_sum = 0;
114 _strip_gene_tree = strip_gene_tree;
115 _strip_species_tree = strip_species_tree;
116 _stripped_gene_tree_nodes = new ArrayList<PhylogenyNode>();
117 _stripped_species_tree_nodes = new ArrayList<PhylogenyNode>();
118 _mapped_species_tree_nodes = new HashSet<PhylogenyNode>();
119 getSpeciesTree().preOrderReId();
121 geneTreePostOrderTraversal( getGeneTree().getRoot() );
124 GSDI( final Phylogeny gene_tree, final Phylogeny species_tree, final boolean most_parsimonious_duplication_model )
125 throws SdiException {
126 this( gene_tree, species_tree, most_parsimonious_duplication_model, false, false );
129 private final Event createDuplicationEvent() {
130 final Event event = Event.createSingleDuplicationEvent();
135 private final Event createSingleSpeciationOrDuplicationEvent() {
136 final Event event = Event.createSingleSpeciationOrDuplicationEvent();
137 ++_speciation_or_duplication_events_sum;
141 private final Event createSpeciationEvent() {
142 final Event event = Event.createSingleSpeciationEvent();
147 // s is the node on the species tree g maps to.
148 private final void determineEvent( final PhylogenyNode s, final PhylogenyNode g ) {
150 // Determine how many children map to same node as parent.
151 int sum_g_childs_mapping_to_s = 0;
152 for( int i = 0; i < g.getNumberOfDescendants(); ++i ) {
153 final PhylogenyNode c = g.getChildNode( i );
154 if ( c.getLink() == s ) {
155 ++sum_g_childs_mapping_to_s;
158 // Determine the sum of traversals.
159 int traversals_sum = 0;
160 int max_traversals = 0;
161 PhylogenyNode max_traversals_node = null;
162 if ( !s.isExternal() ) {
163 for( int i = 0; i < s.getNumberOfDescendants(); ++i ) {
164 final PhylogenyNode current_node = s.getChildNode( i );
165 final int traversals = getTraversalCount( current_node );
166 traversals_sum += traversals;
167 if ( traversals > max_traversals ) {
168 max_traversals = traversals;
169 max_traversals_node = current_node;
173 // System.out.println( " sum=" + traversals_sum );
174 // System.out.println( " max=" + max_traversals );
175 // System.out.println( " m=" + sum_g_childs_mapping_to_s );
176 if ( sum_g_childs_mapping_to_s > 0 ) {
177 if ( traversals_sum == 2 ) {
178 event = createDuplicationEvent();
179 System.out.print( g.toString() );
180 System.out.println( " : ==2" );
181 // _transversal_counts.clear();
183 else if ( traversals_sum > 2 ) {
184 if ( max_traversals <= 1 ) {
185 if ( _most_parsimonious_duplication_model ) {
186 event = createSpeciationEvent();
189 event = createSingleSpeciationOrDuplicationEvent();
193 event = createDuplicationEvent();
194 //System.out.println( g.toString() );
195 _transversal_counts.put( max_traversals_node, 1 );
196 // _transversal_counts.clear();
200 event = createDuplicationEvent();
201 // _transversal_counts.clear();
205 event = createSpeciationEvent();
207 g.getNodeData().setEvent( event );
211 * Traverses the subtree of PhylogenyNode g in postorder, calculating the
212 * mapping function M, and determines which nodes represent speciation
213 * events and which ones duplication events.
215 * Preconditions: Mapping M for external nodes must have been calculated and
216 * the species tree must be labeled in preorder.
220 * starting node of a gene tree - normally the root
222 final void geneTreePostOrderTraversal( final PhylogenyNode g ) {
223 if ( !g.isExternal() ) {
224 boolean all_ext = true;
225 for( int i = 0; i < g.getNumberOfDescendants(); ++i ) {
226 if ( g.getChildNode( i ).isInternal() ) {
232 _transversal_counts.clear();
234 for( int i = 0; i < g.getNumberOfDescendants(); ++i ) {
235 geneTreePostOrderTraversal( g.getChildNode( i ) );
237 final PhylogenyNode[] linked_nodes = new PhylogenyNode[ g.getNumberOfDescendants() ];
238 for( int i = 0; i < linked_nodes.length; ++i ) {
239 if ( g.getChildNode( i ).getLink() == null ) {
240 System.out.println( "link is null for " + g.getChildNode( i ) );
243 linked_nodes[ i ] = g.getChildNode( i ).getLink();
245 final int[] min_max = obtainMinMaxIdIndices( linked_nodes );
246 int min_i = min_max[ 0 ];
247 int max_i = min_max[ 1 ];
248 // initTransversalCounts();
249 while ( linked_nodes[ min_i ] != linked_nodes[ max_i ] ) {
250 increaseTraversalCount( linked_nodes[ max_i ] );
251 linked_nodes[ max_i ] = linked_nodes[ max_i ].getParent();
252 final int[] min_max_ = obtainMinMaxIdIndices( linked_nodes );
253 min_i = min_max_[ 0 ];
254 max_i = min_max_[ 1 ];
256 final PhylogenyNode s = linked_nodes[ max_i ];
258 // Determines whether dup. or spec.
259 determineEvent( s, g );
263 public final int getSpeciationOrDuplicationEventsSum() {
264 return _speciation_or_duplication_events_sum;
267 public final int getSpeciationsSum() {
268 return _speciations_sum;
271 private final int getTraversalCount( final PhylogenyNode node ) {
272 if ( _transversal_counts.containsKey( node ) ) {
273 return _transversal_counts.get( node );
278 private final void increaseTraversalCount( final PhylogenyNode node ) {
279 if ( _transversal_counts.containsKey( node ) ) {
280 _transversal_counts.put( node, _transversal_counts.get( node ) + 1 );
283 _transversal_counts.put( node, 1 );
285 // System.out.println( "count for node " + node.getID() + " is now "
286 // + getTraversalCount( node ) );
290 * This allows for linking of internal nodes of the species tree (as opposed
291 * to just external nodes, as in the method it overrides.
292 * @throws SdiException
296 // final void linkNodesOfG() {
297 // final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes = createTaxonomyToNodeMap();
298 // if ( _strip_gene_tree ) {
299 // stripGeneTree( speciestree_ext_nodes );
300 // if ( ( _gene_tree == null ) || ( _gene_tree.getNumberOfExternalNodes() < 2 ) ) {
301 // throw new IllegalArgumentException( "species tree does not contain any"
302 // + " nodes matching species in the gene tree" );
305 // // Retrieve the reference to the PhylogenyNode with a matching species.
306 // for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
307 // final PhylogenyNode g = iter.next();
308 // if ( !g.getNodeData().isHasTaxonomy() ) {
309 // throw new IllegalArgumentException( "gene tree node " + g + " has no taxonomic data" );
311 // final PhylogenyNode s = speciestree_ext_nodes.get( g.getNodeData().getTaxonomy() );
312 // if ( s == null ) {
313 // throw new IllegalArgumentException( "species " + g.getNodeData().getTaxonomy()
314 // + " not present in species tree" );
319 final void linkNodesOfG() throws SdiException {
320 final Map<String, PhylogenyNode> species_to_node_map = new HashMap<String, PhylogenyNode>();
321 final List<PhylogenyNode> species_tree_ext_nodes = new ArrayList<PhylogenyNode>();
322 final TaxonomyComparisonBase tax_comp_base = determineTaxonomyComparisonBase( _gene_tree );
323 // System.out.println( "comp base is: " + tax_comp_base );
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 species_tree_ext_nodes.add( s );
328 final String tax_str = taxonomyToString( s, tax_comp_base );
329 if ( !ForesterUtil.isEmpty( tax_str ) ) {
330 if ( species_to_node_map.containsKey( tax_str ) ) {
331 throw new SdiException( "taxonomy \"" + s + "\" is not unique in species tree" );
333 species_to_node_map.put( tax_str, s );
336 // Retrieve the reference to the node with a matching stringyfied taxonomy.
337 for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
338 final PhylogenyNode g = iter.next();
339 if ( !g.getNodeData().isHasTaxonomy() ) {
340 if ( _strip_gene_tree ) {
341 _stripped_gene_tree_nodes.add( g );
344 throw new SdiException( "gene tree node \"" + g + "\" has no taxonomic data" );
348 final String tax_str = taxonomyToString( g, tax_comp_base );
349 if ( ForesterUtil.isEmpty( tax_str ) ) {
350 if ( _strip_gene_tree ) {
351 _stripped_gene_tree_nodes.add( g );
354 throw new SdiException( "gene tree node \"" + g + "\" has no appropriate taxonomic data" );
358 final PhylogenyNode s = species_to_node_map.get( tax_str );
360 if ( _strip_gene_tree ) {
361 _stripped_gene_tree_nodes.add( g );
364 throw new SdiException( "taxonomy \"" + g.getNodeData().getTaxonomy()
365 + "\" not present in species tree" );
370 _mapped_species_tree_nodes.add( s );
371 // System.out.println( "setting link of " + g + " to " + s );
376 if ( _strip_gene_tree ) {
377 for( final PhylogenyNode g : _stripped_gene_tree_nodes ) {
378 _gene_tree.deleteSubtree( g, true );
381 if ( _strip_species_tree ) {
382 for( final PhylogenyNode s : species_tree_ext_nodes ) {
383 if ( !_mapped_species_tree_nodes.contains( s ) ) {
384 _species_tree.deleteSubtree( s, true );
390 public Set<PhylogenyNode> getMappedExternalSpeciesTreeNodes() {
391 return _mapped_species_tree_nodes;
394 // final private HashMap<Taxonomy, PhylogenyNode> createTaxonomyToNodeMap() {
395 // final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes = new HashMap<Taxonomy, PhylogenyNode>();
396 // for( final PhylogenyNodeIterator iter = _species_tree.iteratorLevelOrder(); iter.hasNext(); ) {
397 // final PhylogenyNode n = iter.next();
398 // if ( n.getNodeData().isHasTaxonomy() ) {
399 // if ( speciestree_ext_nodes.containsKey( n.getNodeData().getTaxonomy() ) ) {
400 // throw new IllegalArgumentException( "taxonomy [" + n.getNodeData().getTaxonomy()
401 // + "] is not unique in species phylogeny" );
403 // speciestree_ext_nodes.put( n.getNodeData().getTaxonomy(), n );
406 // return speciestree_ext_nodes;
408 // private final void stripGeneTree( final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes ) {
409 // // final Set<PhylogenyNode> to_delete = new HashSet<PhylogenyNode>();
410 // for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
411 // final PhylogenyNode g = iter.next();
412 // if ( !g.getNodeData().isHasTaxonomy() ) {
413 // throw new IllegalArgumentException( "gene tree node " + g + " has no taxonomic data" );
415 // if ( !speciestree_ext_nodes.containsKey( g.getNodeData().getTaxonomy() ) ) {
416 // _stripped_gene_tree_nodes.add( g );
419 // for( final PhylogenyNode n : _stripped_gene_tree_nodes ) {
420 // _gene_tree.deleteSubtree( n, true );
423 // private final void stripGeneTree2( final HashMap<Taxonomy, PhylogenyNode> speciestree_ext_nodes ) {
424 // // final Set<PhylogenyNode> to_delete = new HashSet<PhylogenyNode>();
425 // for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
426 // final PhylogenyNode g = iter.next();
427 // if ( !g.getNodeData().isHasTaxonomy() ) {
428 // _stripped_gene_tree_nodes.add( g );
431 // if ( !speciestree_ext_nodes.containsKey( g.getNodeData().getTaxonomy() ) ) {
432 // _stripped_gene_tree_nodes.add( g );
436 // for( final PhylogenyNode n : _stripped_gene_tree_nodes ) {
437 // _gene_tree.deleteSubtree( n, true );
440 public static TaxonomyComparisonBase determineTaxonomyComparisonBase( final Phylogeny gene_tree ) {
441 int with_id_count = 0;
442 int with_code_count = 0;
443 int with_sn_count = 0;
445 for( final PhylogenyNodeIterator iter = gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
446 final PhylogenyNode g = iter.next();
447 if ( g.getNodeData().isHasTaxonomy() ) {
448 final Taxonomy tax = g.getNodeData().getTaxonomy();
449 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) {
450 if ( ++with_id_count > max ) {
454 if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
455 if ( ++with_code_count > max ) {
456 max = with_code_count;
459 if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
460 if ( ++with_sn_count > max ) {
467 throw new IllegalArgumentException( "gene tree has no taxonomic data" );
469 else if ( max == 1 ) {
470 throw new IllegalArgumentException( "gene tree has only one node with taxonomic data" );
472 else if ( max == with_sn_count ) {
473 return SDI.TaxonomyComparisonBase.SCIENTIFIC_NAME;
475 else if ( max == with_id_count ) {
476 return SDI.TaxonomyComparisonBase.ID;
479 return SDI.TaxonomyComparisonBase.CODE;
483 public List<PhylogenyNode> getStrippedExternalGeneTreeNodes() {
484 return _stripped_gene_tree_nodes;
488 public final String toString() {
489 final StringBuffer sb = new StringBuffer();
490 sb.append( "Most parsimonious duplication model: " + _most_parsimonious_duplication_model );
491 sb.append( ForesterUtil.getLineSeparator() );
492 sb.append( "Speciations sum : " + getSpeciationsSum() );
493 sb.append( ForesterUtil.getLineSeparator() );
494 sb.append( "Duplications sum : " + getDuplicationsSum() );
495 sb.append( ForesterUtil.getLineSeparator() );
496 if ( !_most_parsimonious_duplication_model ) {
497 sb.append( "Speciation or duplications sum : " + getSpeciationOrDuplicationEventsSum() );
498 sb.append( ForesterUtil.getLineSeparator() );
500 sb.append( "mapping cost L : " + computeMappingCostL() );
501 return sb.toString();
504 static final int[] obtainMinMaxIdIndices( final PhylogenyNode[] linked_nodes ) {
507 int max_i_id = -Integer.MAX_VALUE;
508 int min_i_id = Integer.MAX_VALUE;
509 for( int i = 0; i < linked_nodes.length; ++i ) {
510 final int id_i = linked_nodes[ i ].getId();
511 if ( id_i > max_i_id ) {
513 max_i_id = linked_nodes[ max_i ].getId();
515 if ( id_i < min_i_id ) {
517 min_i_id = linked_nodes[ min_i ].getId();
520 return new int[] { min_i, max_i };
523 * Updates the mapping function M after the root of the gene tree has been
524 * moved by one branch. It calculates M for the root of the gene tree and
525 * one of its two children.
527 * To be used ONLY by method "SDIunrooted.fastInfer(Phylogeny,Phylogeny)".
531 * @param prev_root_was_dup
532 * true if the previous root was a duplication, false otherwise
533 * @param prev_root_c1
534 * child 1 of the previous root
535 * @param prev_root_c2
536 * child 2 of the previous root
537 * @return number of duplications which have been assigned in gene tree
539 // int updateM( final boolean prev_root_was_dup,
540 // final PhylogenyNode prev_root_c1, final PhylogenyNode prev_root_c2 ) {
541 // final PhylogenyNode root = getGeneTree().getRoot();
542 // if ( ( root.getChildNode1() == prev_root_c1 )
543 // || ( root.getChildNode2() == prev_root_c1 ) ) {
544 // calculateMforNode( prev_root_c1 );
547 // calculateMforNode( prev_root_c2 );
549 // Event event = null;
550 // if ( prev_root_was_dup ) {
551 // event = Event.createSingleDuplicationEvent();
554 // event = Event.createSingleSpeciationEvent();
556 // root.getPhylogenyNodeData().setEvent( event );
557 // calculateMforNode( root );
558 // return getDuplications();
559 // } // updateM( boolean, PhylogenyNode, PhylogenyNode )
560 // Helper method for updateM( boolean, PhylogenyNode, PhylogenyNode )
561 // Calculates M for PhylogenyNode n, given that M for the two children
562 // of n has been calculated.
563 // (Last modified: 10/02/01)
564 // private void calculateMforNode( final PhylogenyNode n ) {
565 // if ( !n.isExternal() ) {
566 // boolean was_duplication = n.isDuplication();
567 // PhylogenyNode a = n.getChildNode1().getLink(), b = n
568 // .getChildNode2().getLink();
569 // while ( a != b ) {
570 // if ( a.getID() > b.getID() ) {
571 // a = a.getParent();
574 // b = b.getParent();
578 // Event event = null;
579 // if ( ( a == n.getChildNode1().getLink() )
580 // || ( a == n.getChildNode2().getLink() ) ) {
581 // event = Event.createSingleDuplicationEvent();
582 // if ( !was_duplication ) {
583 // increaseDuplications();
587 // event = Event.createSingleSpeciationEvent();
588 // if ( was_duplication ) {
589 // decreaseDuplications();
592 // n.getPhylogenyNodeData().setEvent( event );
594 // } // calculateMforNode( PhylogenyNode )