63c6215253b89bc58f5ef013d91167a220504bbf
[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         if ( gene_tree.getRoot().getNumberOfDescendants() == 3 ) {
63             gene_tree.reRoot( gene_tree.getRoot().getChildNode( 2 ) );
64         }
65         final NodesLinkingResult nodes_linking_result = linkNodesOfG( gene_tree,
66                                                                       species_tree,
67                                                                       strip_gene_tree,
68                                                                       strip_species_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();
81     }
82
83     public int getDuplicationsSum() {
84         return _duplications_sum;
85     }
86
87     @Override
88     public Set<PhylogenyNode> getMappedExternalSpeciesTreeNodes() {
89         return _mapped_species_tree_nodes;
90     }
91
92     @Override
93     public final SortedSet<String> getReMappedScientificNamesFromGeneTree() {
94         return _scientific_names_mapped_to_reduced_specificity;
95     }
96
97     public final int getSpeciationOrDuplicationEventsSum() {
98         return _speciation_or_duplication_events_sum;
99     }
100
101     @Override
102     public final int getSpeciationsSum() {
103         return _speciations_sum;
104     }
105
106     @Override
107     public List<PhylogenyNode> getStrippedExternalGeneTreeNodes() {
108         return _stripped_gene_tree_nodes;
109     }
110
111     @Override
112     public List<PhylogenyNode> getStrippedSpeciesTreeNodes() {
113         return _stripped_species_tree_nodes;
114     }
115
116     @Override
117     public TaxonomyComparisonBase getTaxCompBase() {
118         return _tax_comp_base;
119     }
120
121     @Override
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() );
133         }
134         return sb.toString();
135     }
136
137     /**
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.
141      * <p>
142      * Preconditions: Mapping M for external nodes must have been calculated and
143      * the species tree must be labeled in preorder.
144      * <p>
145      * @return 
146      * @throws SDIException 
147      * 
148      */
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()
158                             + " descendents" );
159                 }
160                 PhylogenyNode s1 = g.getChildNode1().getLink();
161                 PhylogenyNode s2 = g.getChildNode2().getLink();
162                 while ( s1 != s2 ) {
163                     if ( s1.getId() > s2.getId() ) {
164                         s1 = s1.getParent();
165                     }
166                     else {
167                         s2 = s2.getParent();
168                     }
169                 }
170                 g.setLink( s1 );
171                 determineEvent( s1, g, most_parsimonious_duplication_model, res );
172             }
173         }
174         return res;
175     }
176
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)" );
184         }
185         return linkNodesOfG( gene_tree, species_tree, tax_comp_base, strip_gene_tree, strip_species_tree );
186     }
187
188     /**
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 
193      * 
194      */
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" );
202         }
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)" );
217                     }
218                     species_to_node_map.put( tax_str, s );
219                 }
220             }
221         }
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 );
228                 }
229                 else {
230                     throw new SDIException( "gene tree node \"" + g + "\" has no taxonomic data" );
231                 }
232             }
233             else {
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 );
238                     }
239                     else {
240                         throw new SDIException( "gene tree node \"" + g + "\" has no appropriate taxonomic data" );
241                     }
242                 }
243                 else {
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,
248                                                                 tax_str,
249                                                                 res.getScientificNamesMappedToReducedSpecificity() );
250                     }
251                     if ( s == null ) {
252                         if ( strip_gene_tree ) {
253                             res.getStrippedGeneTreeNodes().add( g );
254                         }
255                         else {
256                             throw new SDIException( "taxonomy \"" + g.getNodeData().getTaxonomy()
257                                     + "\" not present in species tree" );
258                         }
259                     }
260                     else {
261                         g.setLink( s );
262                         res.getMappedSpeciesTreeNodes().add( s );
263                     }
264                 }
265             }
266         } // for loop
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() + ")" );
272             }
273         }
274         if ( strip_species_tree ) {
275             stripSpeciesTree( species_tree, species_tree_ext_nodes, res );
276         }
277         return res;
278     }
279
280     private final static void addScientificNamesMappedToReducedSpecificity( final String s1,
281                                                                             final String s2,
282                                                                             final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
283         scientific_names_mapped_to_reduced_specificity.add( s1 + " -> " + s2 );
284     }
285
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 ) ) {
292             oyako = true;
293         }
294         if ( g.getLink().getNumberOfDescendants() == 2 ) {
295             if ( oyako ) {
296                 g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
297                 res.increaseDuplicationsSum();
298             }
299             else {
300                 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
301                 res.increaseSpeciationsSum();
302             }
303         }
304         else {
305             if ( oyako ) {
306                 final Set<PhylogenyNode> set = new HashSet<PhylogenyNode>();
307                 for( PhylogenyNode n : g.getChildNode1().getAllExternalDescendants() ) {
308                     n = n.getLink();
309                     while ( n.getParent() != s ) {
310                         n = n.getParent();
311                         if ( n.isRoot() ) {
312                             break;
313                         }
314                     }
315                     set.add( n );
316                 }
317                 boolean multiple = false;
318                 for( PhylogenyNode n : g.getChildNode2().getAllExternalDescendants() ) {
319                     n = n.getLink();
320                     while ( n.getParent() != s ) {
321                         n = n.getParent();
322                         if ( n.isRoot() ) {
323                             break;
324                         }
325                     }
326                     if ( set.contains( n ) ) {
327                         multiple = true;
328                         break;
329                     }
330                 }
331                 if ( multiple ) {
332                     g.getNodeData().setEvent( Event.createSingleDuplicationEvent() );
333                     res.increaseDuplicationsSum();
334                 }
335                 else {
336                     if ( most_parsimonious_duplication_model ) {
337                         g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
338                         res.increaseSpeciationsSum();
339                     }
340                     else {
341                         g.getNodeData().setEvent( Event.createSingleSpeciationOrDuplicationEvent() );
342                         res.increaseSpeciationOrDuplicationEventsSum();
343                     }
344                 }
345             }
346             else {
347                 g.getNodeData().setEvent( Event.createSingleSpeciationEvent() );
348                 res.increaseSpeciationsSum();
349             }
350         }
351     }
352
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 );
360             }
361         }
362         species_tree.clearHashIdToNodeMap();
363         species_tree.externalNodesHaveChanged();
364     }
365
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 );
369         }
370         phy.clearHashIdToNodeMap();
371         phy.externalNodesHaveChanged();
372     }
373
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,
378                                                               tax_str,
379                                                               " (",
380                                                               scientific_names_mapped_to_reduced_specificity );
381         if ( s == null ) {
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 );
385                 if ( s != null ) {
386                     addScientificNamesMappedToReducedSpecificity( tax_str,
387                                                                   new_tax_str,
388                                                                   scientific_names_mapped_to_reduced_specificity );
389                 }
390             }
391         }
392         if ( s == null ) {
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,
396                                                         tax_str,
397                                                         t,
398                                                         scientific_names_mapped_to_reduced_specificity );
399                 if ( s != null ) {
400                     break;
401                 }
402             }
403         }
404         return s;
405     }
406
407     private final static PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
408                                                                            final String tax_str,
409                                                                            final String term,
410                                                                            final SortedSet<String> scientific_names_mapped_to_reduced_specificity ) {
411         final int i = tax_str.indexOf( term );
412         if ( i > 4 ) {
413             final String new_tax_str = tax_str.substring( 0, i ).trim();
414             final PhylogenyNode s = species_to_node_map.get( new_tax_str );
415             if ( s != null ) {
416                 addScientificNamesMappedToReducedSpecificity( tax_str,
417                                                               new_tax_str,
418                                                               scientific_names_mapped_to_reduced_specificity );
419             }
420             return s;
421         }
422         return null;
423     }
424 }