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: https://sites.google.com/site/cmzmasek/home/software/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;
34 import java.util.SortedSet;
36 import org.forester.phylogeny.Phylogeny;
37 import org.forester.phylogeny.PhylogenyMethods;
38 import org.forester.phylogeny.PhylogenyNode;
39 import org.forester.phylogeny.data.Event;
40 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
41 import org.forester.sdi.SDIutil.TaxonomyComparisonBase;
42 import org.forester.util.ForesterUtil;
44 public final class GSDI implements GSDII {
46 private final boolean _most_parsimonious_duplication_model;
47 private final int _speciation_or_duplication_events_sum;
48 private final int _speciations_sum;
49 private final int _duplications_sum;
50 private final List<PhylogenyNode> _stripped_gene_tree_nodes;
51 private final List<PhylogenyNode> _stripped_species_tree_nodes;
52 private final Set<PhylogenyNode> _mapped_species_tree_nodes;
53 private final TaxonomyComparisonBase _tax_comp_base;
54 private final SortedSet<String> _scientific_names_mapped_to_reduced_specificity;
56 public GSDI( final Phylogeny gene_tree,
57 final Phylogeny species_tree,
58 final boolean most_parsimonious_duplication_model,
59 final boolean strip_gene_tree,
60 final boolean strip_species_tree ) throws SDIException {
61 _most_parsimonious_duplication_model = most_parsimonious_duplication_model;
62 if ( gene_tree.getRoot().getNumberOfDescendants() == 3 ) {
63 gene_tree.reRoot( gene_tree.getRoot().getChildNode( 2 ) );
65 final NodesLinkingResult nodes_linking_result = linkNodesOfG( gene_tree,
69 _stripped_gene_tree_nodes = nodes_linking_result.getStrippedGeneTreeNodes();
70 _stripped_species_tree_nodes = nodes_linking_result.getStrippedSpeciesTreeNodes();
71 _mapped_species_tree_nodes = nodes_linking_result.getMappedSpeciesTreeNodes();
72 _scientific_names_mapped_to_reduced_specificity = nodes_linking_result
73 .getScientificNamesMappedToReducedSpecificity();
74 _tax_comp_base = nodes_linking_result.getTaxCompBase();
75 PhylogenyMethods.preOrderReId( species_tree );
76 final GSDIsummaryResult gsdi_summary_result = geneTreePostOrderTraversal( gene_tree,
77 _most_parsimonious_duplication_model );
78 _speciation_or_duplication_events_sum = gsdi_summary_result.getSpeciationOrDuplicationEventsSum();
79 _speciations_sum = gsdi_summary_result.getSpeciationsSum();
80 _duplications_sum = gsdi_summary_result.getDuplicationsSum();
83 public int getDuplicationsSum() {
84 return _duplications_sum;
88 public Set<PhylogenyNode> getMappedExternalSpeciesTreeNodes() {
89 return _mapped_species_tree_nodes;
93 public final SortedSet<String> getReMappedScientificNamesFromGeneTree() {
94 return _scientific_names_mapped_to_reduced_specificity;
97 public final int getSpeciationOrDuplicationEventsSum() {
98 return _speciation_or_duplication_events_sum;
102 public final int getSpeciationsSum() {
103 return _speciations_sum;
107 public List<PhylogenyNode> getStrippedExternalGeneTreeNodes() {
108 return _stripped_gene_tree_nodes;
112 public List<PhylogenyNode> getStrippedSpeciesTreeNodes() {
113 return _stripped_species_tree_nodes;
117 public TaxonomyComparisonBase getTaxCompBase() {
118 return _tax_comp_base;
122 public final String toString() {
123 final StringBuffer sb = new StringBuffer();
124 sb.append( "Most parsimonious duplication model: " + _most_parsimonious_duplication_model );
125 sb.append( ForesterUtil.getLineSeparator() );
126 sb.append( "Speciations sum : " + getSpeciationsSum() );
127 sb.append( ForesterUtil.getLineSeparator() );
128 sb.append( "Duplications sum : " + getDuplicationsSum() );
129 sb.append( ForesterUtil.getLineSeparator() );
130 if ( !_most_parsimonious_duplication_model ) {
131 sb.append( "Speciation or duplications sum : " + getSpeciationOrDuplicationEventsSum() );
132 sb.append( ForesterUtil.getLineSeparator() );
134 return sb.toString();
138 * Traverses the subtree of PhylogenyNode g in postorder, calculating the
139 * mapping function M, and determines which nodes represent speciation
140 * events and which ones duplication events.
142 * Preconditions: Mapping M for external nodes must have been calculated and
143 * the species tree must be labeled in preorder.
146 * @throws SDIException
149 final static GSDIsummaryResult geneTreePostOrderTraversal( final Phylogeny gene_tree,
150 final boolean most_parsimonious_duplication_model )
151 throws SDIException {
152 final GSDIsummaryResult res = new GSDIsummaryResult();
153 for( final PhylogenyNodeIterator it = gene_tree.iteratorPostorder(); it.hasNext(); ) {
154 final PhylogenyNode g = it.next();
155 if ( g.isInternal() ) {
156 if ( g.getNumberOfDescendants() != 2 ) {
157 throw new SDIException( "gene tree contains internal node with " + g.getNumberOfDescendants()
160 PhylogenyNode s1 = g.getChildNode1().getLink();
161 PhylogenyNode s2 = g.getChildNode2().getLink();
163 if ( s1.getId() > s2.getId() ) {
171 determineEvent( s1, g, most_parsimonious_duplication_model, res );
177 final static NodesLinkingResult linkNodesOfG( final Phylogeny gene_tree,
178 final Phylogeny species_tree,
179 final boolean strip_gene_tree,
180 final boolean strip_species_tree ) throws SDIException {
181 final TaxonomyComparisonBase tax_comp_base = SDIutil.determineTaxonomyComparisonBase( gene_tree );
182 if ( tax_comp_base == null ) {
183 throw new RuntimeException( "failed to establish taxonomy linking base (taxonomy linking base is null)" );
185 return linkNodesOfG( gene_tree, species_tree, tax_comp_base, strip_gene_tree, strip_species_tree );
189 * This allows for linking of internal nodes of the species tree (as opposed
190 * to just external nodes, as in the method it overrides.
191 * If TaxonomyComparisonBase is null, it will try to determine it.
192 * @throws SDIException
195 final static NodesLinkingResult linkNodesOfG( final Phylogeny gene_tree,
196 final Phylogeny species_tree,
197 final TaxonomyComparisonBase tax_comp_base,
198 final boolean strip_gene_tree,
199 final boolean strip_species_tree ) throws SDIException {
200 if ( tax_comp_base == null ) {
201 throw new IllegalArgumentException( "taxonomy linking base is null" );
203 final Map<String, PhylogenyNode> species_to_node_map = new HashMap<String, PhylogenyNode>();
204 final List<PhylogenyNode> species_tree_ext_nodes = new ArrayList<PhylogenyNode>();
205 final NodesLinkingResult res = new NodesLinkingResult();
206 res.setTaxCompBase( tax_comp_base );
207 // Stringyfied taxonomy is the key, node is the value.
208 for( final PhylogenyNodeIterator iter = species_tree.iteratorExternalForward(); iter.hasNext(); ) {
209 final PhylogenyNode s = iter.next();
210 species_tree_ext_nodes.add( s );
211 if ( s.getNodeData().isHasTaxonomy() ) {
212 final String tax_str = SDIutil.taxonomyToString( s, res.getTaxCompBase() );
213 if ( !ForesterUtil.isEmpty( tax_str ) ) {
214 if ( species_to_node_map.containsKey( tax_str ) ) {
215 throw new SDIException( "taxonomy \"" + tax_str + "\" is not unique in species tree (using "
216 + res.getTaxCompBase() + " for linking to gene tree)" );
218 species_to_node_map.put( tax_str, s );
222 // Retrieve the reference to the node with a matching stringyfied taxonomy.
223 for( final PhylogenyNodeIterator iter = gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
224 final PhylogenyNode g = iter.next();
225 if ( !g.getNodeData().isHasTaxonomy() ) {
226 if ( strip_gene_tree ) {
227 res.getStrippedGeneTreeNodes().add( g );
230 throw new SDIException( "gene tree node \"" + g + "\" has no taxonomic data" );
234 final String tax_str = SDIutil.taxonomyToString( g, res.getTaxCompBase() );
235 if ( ForesterUtil.isEmpty( tax_str ) ) {
236 if ( strip_gene_tree ) {
237 res.getStrippedGeneTreeNodes().add( g );
240 throw new SDIException( "gene tree node \"" + g + "\" has no appropriate taxonomic data" );
244 PhylogenyNode s = species_to_node_map.get( tax_str );
245 if ( ( res.getTaxCompBase() == TaxonomyComparisonBase.SCIENTIFIC_NAME ) && ( s == null )
246 && ( ForesterUtil.countChars( tax_str, ' ' ) > 1 ) ) {
247 s = tryMapByRemovingOverlySpecificData( species_to_node_map,
249 res.getScientificNamesMappedToReducedSpecificity() );
252 if ( strip_gene_tree ) {
253 res.getStrippedGeneTreeNodes().add( g );
256 throw new SDIException( "taxonomy \"" + g.getNodeData().getTaxonomy()
257 + "\" not present in species tree" );
262 res.getMappedSpeciesTreeNodes().add( s );
267 if ( strip_gene_tree ) {
268 stripTree( gene_tree, res.getStrippedGeneTreeNodes() );
269 if ( gene_tree.isEmpty() || ( gene_tree.getNumberOfExternalNodes() < 2 ) ) {
270 throw new SDIException( "species could not be mapped between gene tree and species tree (based on "
271 + res.getTaxCompBase() + ")" );
274 if ( strip_species_tree ) {
275 stripSpeciesTree( species_tree, species_tree_ext_nodes, res );
280 private final static void addScientificNamesMappedToReducedSpecificity( final String s1,
282 final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
283 scientific_names_mapped_to_reduced_specificity.add( s1 + " -> " + s2 );
286 private final static void determineEvent( final PhylogenyNode s,
287 final PhylogenyNode g,
288 final boolean most_parsimonious_duplication_model,
289 final GSDIsummaryResult res ) {
290 boolean oyako = false;
291 if ( ( g.getChildNode1().getLink() == s ) || ( g.getChildNode2().getLink() == s ) ) {
294 if ( g.getLink().getNumberOfDescendants() == 2 ) {
296 g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
297 res.increaseDuplicationsSum();
300 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
301 res.increaseSpeciationsSum();
306 final Set<PhylogenyNode> set = new HashSet<PhylogenyNode>();
307 for( PhylogenyNode n : g.getChildNode1().getAllExternalDescendants() ) {
309 while ( n.getParent() != s ) {
317 boolean multiple = false;
318 for( PhylogenyNode n : g.getChildNode2().getAllExternalDescendants() ) {
320 while ( n.getParent() != s ) {
326 if ( set.contains( n ) ) {
332 g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
333 res.increaseDuplicationsSum();
336 if ( most_parsimonious_duplication_model ) {
337 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
338 res.increaseSpeciationsSum();
341 g.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
342 res.increaseSpeciationOrDuplicationEventsSum();
347 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
348 res.increaseSpeciationsSum();
353 private final static void stripSpeciesTree( final Phylogeny species_tree,
354 final List<PhylogenyNode> species_tree_ext_nodes,
355 final NodesLinkingResult res ) {
356 for( final PhylogenyNode s : species_tree_ext_nodes ) {
357 if ( !res.getMappedSpeciesTreeNodes().contains( s ) ) {
358 species_tree.deleteSubtree( s, true );
359 res.getStrippedSpeciesTreeNodes().add( s );
362 species_tree.clearHashIdToNodeMap();
363 species_tree.externalNodesHaveChanged();
366 private final static void stripTree( final Phylogeny phy, final List<PhylogenyNode> strip_nodes ) {
367 for( final PhylogenyNode g : strip_nodes ) {
368 phy.deleteSubtree( g, true );
370 phy.clearHashIdToNodeMap();
371 phy.externalNodesHaveChanged();
374 private final static PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
375 final String tax_str,
376 final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
377 PhylogenyNode s = tryMapByRemovingOverlySpecificData( species_to_node_map,
380 scientific_names_mapped_to_reduced_specificity );
382 if ( ForesterUtil.countChars( tax_str, ' ' ) == 2 ) {
383 final String new_tax_str = tax_str.substring( 0, tax_str.lastIndexOf( ' ' ) ).trim();
384 s = species_to_node_map.get( new_tax_str );
386 addScientificNamesMappedToReducedSpecificity( tax_str,
388 scientific_names_mapped_to_reduced_specificity );
393 for( final String t : new String[] { " subspecies ", " strain ", " variety ", " varietas ", " subvariety ",
394 " form ", " subform ", " cultivar ", " section ", " subsection " } ) {
395 s = tryMapByRemovingOverlySpecificData( species_to_node_map,
398 scientific_names_mapped_to_reduced_specificity );
407 private final static PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
408 final String tax_str,
410 final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
411 final int i = tax_str.indexOf( term );
413 final String new_tax_str = tax_str.substring( 0, i ).trim();
414 final PhylogenyNode s = species_to_node_map.get( new_tax_str );
416 addScientificNamesMappedToReducedSpecificity( tax_str,
418 scientific_names_mapped_to_reduced_specificity );