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;
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 final NodesLinkingResult nodes_linking_result = linkNodesOfG( gene_tree,
67 _stripped_gene_tree_nodes = nodes_linking_result.getStrippedGeneTreeNodes();
68 _stripped_species_tree_nodes = nodes_linking_result.getStrippedSpeciesTreeNodes();
69 _mapped_species_tree_nodes = nodes_linking_result.getMappedSpeciesTreeNodes();
70 _scientific_names_mapped_to_reduced_specificity = nodes_linking_result
71 .getScientificNamesMappedToReducedSpecificity();
72 _tax_comp_base = nodes_linking_result.getTaxCompBase();
73 PhylogenyMethods.preOrderReId( species_tree );
74 final GSDIsummaryResult gsdi_summary_result = geneTreePostOrderTraversal( gene_tree,
75 _most_parsimonious_duplication_model );
76 _speciation_or_duplication_events_sum = gsdi_summary_result.getSpeciationOrDuplicationEventsSum();
77 _speciations_sum = gsdi_summary_result.getSpeciationsSum();
78 _duplications_sum = gsdi_summary_result.getDuplicationsSum();
81 public int getDuplicationsSum() {
82 return _duplications_sum;
85 public Set<PhylogenyNode> getMappedExternalSpeciesTreeNodes() {
86 return _mapped_species_tree_nodes;
89 public final SortedSet<String> getReMappedScientificNamesFromGeneTree() {
90 return _scientific_names_mapped_to_reduced_specificity;
93 public final int getSpeciationOrDuplicationEventsSum() {
94 return _speciation_or_duplication_events_sum;
97 public final int getSpeciationsSum() {
98 return _speciations_sum;
101 public List<PhylogenyNode> getStrippedExternalGeneTreeNodes() {
102 return _stripped_gene_tree_nodes;
105 public List<PhylogenyNode> getStrippedSpeciesTreeNodes() {
106 return _stripped_species_tree_nodes;
109 public TaxonomyComparisonBase getTaxCompBase() {
110 return _tax_comp_base;
114 public final String toString() {
115 final StringBuffer sb = new StringBuffer();
116 sb.append( "Most parsimonious duplication model: " + _most_parsimonious_duplication_model );
117 sb.append( ForesterUtil.getLineSeparator() );
118 sb.append( "Speciations sum : " + getSpeciationsSum() );
119 sb.append( ForesterUtil.getLineSeparator() );
120 sb.append( "Duplications sum : " + getDuplicationsSum() );
121 sb.append( ForesterUtil.getLineSeparator() );
122 if ( !_most_parsimonious_duplication_model ) {
123 sb.append( "Speciation or duplications sum : " + getSpeciationOrDuplicationEventsSum() );
124 sb.append( ForesterUtil.getLineSeparator() );
126 return sb.toString();
130 * Traverses the subtree of PhylogenyNode g in postorder, calculating the
131 * mapping function M, and determines which nodes represent speciation
132 * events and which ones duplication events.
134 * Preconditions: Mapping M for external nodes must have been calculated and
135 * the species tree must be labeled in preorder.
140 final static GSDIsummaryResult geneTreePostOrderTraversal( final Phylogeny gene_tree,
141 final boolean most_parsimonious_duplication_model ) {
142 final GSDIsummaryResult res = new GSDIsummaryResult();
143 for( final PhylogenyNodeIterator it = gene_tree.iteratorPostorder(); it.hasNext(); ) {
144 final PhylogenyNode g = it.next();
145 if ( g.isInternal() ) {
146 PhylogenyNode s1 = g.getChildNode1().getLink();
147 PhylogenyNode s2 = g.getChildNode2().getLink();
149 if ( s1.getId() > s2.getId() ) {
157 determineEvent( s1, g, most_parsimonious_duplication_model, res );
164 * This allows for linking of internal nodes of the species tree (as opposed
165 * to just external nodes, as in the method it overrides.
166 * If TaxonomyComparisonBase is null, it will try to determine it.
167 * @throws SDIException
170 final static NodesLinkingResult linkNodesOfG( final Phylogeny gene_tree,
171 final Phylogeny species_tree,
172 final TaxonomyComparisonBase tax_comp_base,
173 final boolean strip_gene_tree,
174 final boolean strip_species_tree ) throws SDIException {
175 final Map<String, PhylogenyNode> species_to_node_map = new HashMap<String, PhylogenyNode>();
176 final List<PhylogenyNode> species_tree_ext_nodes = new ArrayList<PhylogenyNode>();
177 final NodesLinkingResult res = new NodesLinkingResult();
178 if ( tax_comp_base == null ) {
179 res.setTaxCompBase( SDIutil.determineTaxonomyComparisonBase( gene_tree ) );
182 res.setTaxCompBase( tax_comp_base );
184 // Stringyfied taxonomy is the key, node is the value.
185 for( final PhylogenyNodeIterator iter = species_tree.iteratorExternalForward(); iter.hasNext(); ) {
186 final PhylogenyNode s = iter.next();
187 species_tree_ext_nodes.add( s );
188 if ( s.getNodeData().isHasTaxonomy() ) {
189 final String tax_str = SDIutil.taxonomyToString( s, res.getTaxCompBase() );
190 if ( !ForesterUtil.isEmpty( tax_str ) ) {
191 if ( species_to_node_map.containsKey( tax_str ) ) {
192 throw new SDIException( "taxonomy \"" + s + "\" is not unique in species tree" );
194 species_to_node_map.put( tax_str, s );
198 // Retrieve the reference to the node with a matching stringyfied taxonomy.
199 for( final PhylogenyNodeIterator iter = gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
200 final PhylogenyNode g = iter.next();
201 if ( !g.getNodeData().isHasTaxonomy() ) {
202 if ( strip_gene_tree ) {
203 res.getStrippedGeneTreeNodes().add( g );
206 throw new SDIException( "gene tree node \"" + g + "\" has no taxonomic data" );
210 final String tax_str = SDIutil.taxonomyToString( g, res.getTaxCompBase() );
211 if ( ForesterUtil.isEmpty( tax_str ) ) {
212 if ( strip_gene_tree ) {
213 res.getStrippedGeneTreeNodes().add( g );
216 throw new SDIException( "gene tree node \"" + g + "\" has no appropriate taxonomic data" );
220 PhylogenyNode s = species_to_node_map.get( tax_str );
221 if ( ( res.getTaxCompBase() == TaxonomyComparisonBase.SCIENTIFIC_NAME ) && ( s == null )
222 && ( ForesterUtil.countChars( tax_str, ' ' ) > 1 ) ) {
223 s = tryMapByRemovingOverlySpecificData( species_to_node_map,
225 res.getScientificNamesMappedToReducedSpecificity() );
228 if ( strip_gene_tree ) {
229 res.getStrippedGeneTreeNodes().add( g );
232 throw new SDIException( "taxonomy \"" + g.getNodeData().getTaxonomy()
233 + "\" not present in species tree" );
238 res.getMappedSpeciesTreeNodes().add( s );
243 if ( strip_gene_tree ) {
244 stripTree( gene_tree, res.getStrippedGeneTreeNodes() );
245 if ( gene_tree.isEmpty() || ( gene_tree.getNumberOfExternalNodes() < 2 ) ) {
246 throw new SDIException( "species could not be mapped between gene tree and species tree" );
249 if ( strip_species_tree ) {
250 stripSpeciesTree( species_tree, species_tree_ext_nodes, res );
255 private final static void addScientificNamesMappedToReducedSpecificity( final String s1,
257 final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
258 scientific_names_mapped_to_reduced_specificity.add( s1 + " -> " + s2 );
261 private final static void determineEvent( final PhylogenyNode s,
262 final PhylogenyNode g,
263 final boolean most_parsimonious_duplication_model,
264 final GSDIsummaryResult res ) {
265 boolean oyako = false;
266 if ( ( g.getChildNode1().getLink() == s ) || ( g.getChildNode2().getLink() == s ) ) {
269 if ( g.getLink().getNumberOfDescendants() == 2 ) {
271 g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
272 res.increaseDuplicationsSum();
275 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
276 res.increaseSpeciationsSum();
281 final Set<PhylogenyNode> set = new HashSet<PhylogenyNode>();
282 for( PhylogenyNode n : g.getChildNode1().getAllExternalDescendants() ) {
284 while ( n.getParent() != s ) {
292 boolean multiple = false;
293 for( PhylogenyNode n : g.getChildNode2().getAllExternalDescendants() ) {
295 while ( n.getParent() != s ) {
301 if ( set.contains( n ) ) {
307 g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
308 res.increaseDuplicationsSum();
311 if ( most_parsimonious_duplication_model ) {
312 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
313 res.increaseSpeciationsSum();
316 g.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
317 res.increaseSpeciationOrDuplicationEventsSum();
322 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
323 res.increaseSpeciationsSum();
328 private final static void stripSpeciesTree( final Phylogeny species_tree,
329 final List<PhylogenyNode> species_tree_ext_nodes,
330 final NodesLinkingResult res ) {
331 for( final PhylogenyNode s : species_tree_ext_nodes ) {
332 if ( !res.getMappedSpeciesTreeNodes().contains( s ) ) {
333 species_tree.deleteSubtree( s, true );
334 res.getStrippedSpeciesTreeNodes().add( s );
337 species_tree.clearHashIdToNodeMap();
338 species_tree.externalNodesHaveChanged();
341 private final static void stripTree( final Phylogeny phy, final List<PhylogenyNode> strip_nodes ) {
342 for( final PhylogenyNode g : strip_nodes ) {
343 phy.deleteSubtree( g, true );
345 phy.clearHashIdToNodeMap();
346 phy.externalNodesHaveChanged();
349 private final static PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
350 final String tax_str,
351 final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
352 PhylogenyNode s = tryMapByRemovingOverlySpecificData( species_to_node_map,
355 scientific_names_mapped_to_reduced_specificity );
357 if ( ForesterUtil.countChars( tax_str, ' ' ) == 2 ) {
358 final String new_tax_str = tax_str.substring( 0, tax_str.lastIndexOf( ' ' ) ).trim();
359 s = species_to_node_map.get( new_tax_str );
361 addScientificNamesMappedToReducedSpecificity( tax_str,
363 scientific_names_mapped_to_reduced_specificity );
368 for( final String t : new String[] { " subspecies ", " strain ", " variety ", " varietas ", " subvariety ",
369 " form ", " subform ", " cultivar ", " section ", " subsection " } ) {
370 s = tryMapByRemovingOverlySpecificData( species_to_node_map,
373 scientific_names_mapped_to_reduced_specificity );
382 private final static PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
383 final String tax_str,
385 final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
386 final int i = tax_str.indexOf( term );
388 final String new_tax_str = tax_str.substring( 0, i ).trim();
389 final PhylogenyNode s = species_to_node_map.get( new_tax_str );
391 addScientificNamesMappedToReducedSpecificity( tax_str,
393 scientific_names_mapped_to_reduced_specificity );