fd6497002ae453c38f42eac84d29599fcc880977
[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.ArrayList;
29 import java.util.HashMap;
30 import java.util.HashSet;
31 import java.util.List;
32 import java.util.Map;
33 import java.util.Set;
34 import java.util.SortedSet;
35
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;
43
44 public final class GSDI implements GSDII  {
45
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;
55
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,
63                                                                       species_tree,
64                                                                       null,
65                                                                       strip_gene_tree,
66                                                                       strip_species_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();
79     }
80
81     public int getDuplicationsSum() {
82         return _duplications_sum;
83     }
84
85     public Set<PhylogenyNode> getMappedExternalSpeciesTreeNodes() {
86         return _mapped_species_tree_nodes;
87     }
88
89     public final SortedSet<String> getReMappedScientificNamesFromGeneTree() {
90         return _scientific_names_mapped_to_reduced_specificity;
91     }
92
93     public final int getSpeciationOrDuplicationEventsSum() {
94         return _speciation_or_duplication_events_sum;
95     }
96
97     public final int getSpeciationsSum() {
98         return _speciations_sum;
99     }
100
101     public List<PhylogenyNode> getStrippedExternalGeneTreeNodes() {
102         return _stripped_gene_tree_nodes;
103     }
104
105     public List<PhylogenyNode> getStrippedSpeciesTreeNodes() {
106         return _stripped_species_tree_nodes;
107     }
108
109     public TaxonomyComparisonBase getTaxCompBase() {
110         return _tax_comp_base;
111     }
112
113     @Override
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() );
125         }
126         return sb.toString();
127     }
128
129     /**
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.
133      * <p>
134      * Preconditions: Mapping M for external nodes must have been calculated and
135      * the species tree must be labeled in preorder.
136      * <p>
137      * @return 
138      * 
139      */
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();
148                 while ( s1 != s2 ) {
149                     if ( s1.getId() > s2.getId() ) {
150                         s1 = s1.getParent();
151                     }
152                     else {
153                         s2 = s2.getParent();
154                     }
155                 }
156                 g.setLink( s1 );
157                 determineEvent( s1, g, most_parsimonious_duplication_model, res );
158             }
159         }
160         return res;
161     }
162
163     /**
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 
168      * 
169      */
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 ) );
180         }
181         else {
182             res.setTaxCompBase( tax_comp_base );
183         }
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" );
193                     }
194                     species_to_node_map.put( tax_str, s );
195                 }
196             }
197         }
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 );
204                 }
205                 else {
206                     throw new SDIException( "gene tree node \"" + g + "\" has no taxonomic data" );
207                 }
208             }
209             else {
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 );
214                     }
215                     else {
216                         throw new SDIException( "gene tree node \"" + g + "\" has no appropriate taxonomic data" );
217                     }
218                 }
219                 else {
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,
224                                                                 tax_str,
225                                                                 res.getScientificNamesMappedToReducedSpecificity() );
226                     }
227                     if ( s == null ) {
228                         if ( strip_gene_tree ) {
229                             res.getStrippedGeneTreeNodes().add( g );
230                         }
231                         else {
232                             throw new SDIException( "taxonomy \"" + g.getNodeData().getTaxonomy()
233                                     + "\" not present in species tree" );
234                         }
235                     }
236                     else {
237                         g.setLink( s );
238                         res.getMappedSpeciesTreeNodes().add( s );
239                     }
240                 }
241             }
242         } // for loop
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" );
247             }
248         }
249         if ( strip_species_tree ) {
250             stripSpeciesTree( species_tree, species_tree_ext_nodes, res );
251         }
252         return res;
253     }
254
255     private final static void addScientificNamesMappedToReducedSpecificity( final String s1,
256                                                                             final String s2,
257                                                                             final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
258         scientific_names_mapped_to_reduced_specificity.add( s1 + " -> " + s2 );
259     }
260
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 ) ) {
267             oyako = true;
268         }
269         if ( g.getLink().getNumberOfDescendants() == 2 ) {
270             if ( oyako ) {
271                 g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
272                 res.increaseDuplicationsSum();
273             }
274             else {
275                 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
276                 res.increaseSpeciationsSum();
277             }
278         }
279         else {
280             if ( oyako ) {
281                 final Set<PhylogenyNode> set = new HashSet<PhylogenyNode>();
282                 for( PhylogenyNode n : g.getChildNode1().getAllExternalDescendants() ) {
283                     n = n.getLink();
284                     while ( n.getParent() != s ) {
285                         n = n.getParent();
286                         if ( n.isRoot() ) {
287                             break;
288                         }
289                     }
290                     set.add( n );
291                 }
292                 boolean multiple = false;
293                 for( PhylogenyNode n : g.getChildNode2().getAllExternalDescendants() ) {
294                     n = n.getLink();
295                     while ( n.getParent() != s ) {
296                         n = n.getParent();
297                         if ( n.isRoot() ) {
298                             break;
299                         }
300                     }
301                     if ( set.contains( n ) ) {
302                         multiple = true;
303                         break;
304                     }
305                 }
306                 if ( multiple ) {
307                     g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
308                     res.increaseDuplicationsSum();
309                 }
310                 else {
311                     if ( most_parsimonious_duplication_model ) {
312                         g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
313                         res.increaseSpeciationsSum();
314                     }
315                     else {
316                         g.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
317                         res.increaseSpeciationOrDuplicationEventsSum();
318                     }
319                 }
320             }
321             else {
322                 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
323                 res.increaseSpeciationsSum();
324             }
325         }
326     }
327
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 );
335             }
336         }
337         species_tree.clearHashIdToNodeMap();
338         species_tree.externalNodesHaveChanged();
339     }
340
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 );
344         }
345         phy.clearHashIdToNodeMap();
346         phy.externalNodesHaveChanged();
347     }
348
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,
353                                                               tax_str,
354                                                               " (",
355                                                               scientific_names_mapped_to_reduced_specificity );
356         if ( s == null ) {
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 );
360                 if ( s != null ) {
361                     addScientificNamesMappedToReducedSpecificity( tax_str,
362                                                                   new_tax_str,
363                                                                   scientific_names_mapped_to_reduced_specificity );
364                 }
365             }
366         }
367         if ( s == null ) {
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,
371                                                         tax_str,
372                                                         t,
373                                                         scientific_names_mapped_to_reduced_specificity );
374                 if ( s != null ) {
375                     break;
376                 }
377             }
378         }
379         return s;
380     }
381
382     private final static PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
383                                                                            final String tax_str,
384                                                                            final String term,
385                                                                            final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
386         final int i = tax_str.indexOf( term );
387         if ( i > 4 ) {
388             final String new_tax_str = tax_str.substring( 0, i ).trim();
389             final PhylogenyNode s = species_to_node_map.get( new_tax_str );
390             if ( s != null ) {
391                 addScientificNamesMappedToReducedSpecificity( tax_str,
392                                                               new_tax_str,
393                                                               scientific_names_mapped_to_reduced_specificity );
394             }
395             return s;
396         }
397         return null;
398     }
399 }