"rio" work
[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 import java.util.TreeSet;
36
37 import org.forester.phylogeny.Phylogeny;
38 import org.forester.phylogeny.PhylogenyMethods;
39 import org.forester.phylogeny.PhylogenyNode;
40 import org.forester.phylogeny.data.Event;
41 import org.forester.phylogeny.data.Taxonomy;
42 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
43 import org.forester.util.ForesterUtil;
44
45 /*
46  * Implements our algorithm for speciation - duplication inference (SDI). <p>
47  * The initialization is accomplished by: </p> <ul> <li>method
48  * "linkExtNodesOfG()" of class SDI: setting the links for the external nodes of
49  * the gene tree <li>"preorderReID(int)" from class Phylogeny: numbering of
50  * nodes of the species tree in preorder <li>the optional stripping of the
51  * species tree is accomplished by method "stripTree(Phylogeny,Phylogeny)" of
52  * class Phylogeny </ul> <p> The recursion part is accomplished by this class'
53  * method "geneTreePostOrderTraversal(PhylogenyNode)". <p> Requires JDK 1.5 or
54  * greater.
55  * 
56  * @see SDI#linkNodesOfG()
57  * 
58  * @see Phylogeny#preorderReID(int)
59  * 
60  * @see
61  * PhylogenyMethods#taxonomyBasedDeletionOfExternalNodes(Phylogeny,Phylogeny)
62  * 
63  * @see #geneTreePostOrderTraversal(PhylogenyNode)
64  * 
65  * @author Christian M. Zmasek
66  */
67 public final class GSDI extends SDI {
68
69     private final boolean             _most_parsimonious_duplication_model;
70     private final boolean             _strip_gene_tree;
71     private final boolean             _strip_species_tree;
72     private int                       _speciation_or_duplication_events_sum;
73     private int                       _speciations_sum;
74     private final List<PhylogenyNode> _stripped_gene_tree_nodes;
75     private final List<PhylogenyNode> _stripped_species_tree_nodes;
76     private final Set<PhylogenyNode>  _mapped_species_tree_nodes;
77     private TaxonomyComparisonBase    _tax_comp_base;
78     private final SortedSet<String>   _scientific_names_mapped_to_reduced_specificity;
79
80     public GSDI( final Phylogeny gene_tree,
81                  final Phylogeny species_tree,
82                  final boolean most_parsimonious_duplication_model,
83                  final boolean strip_gene_tree,
84                  final boolean strip_species_tree ) throws SDIException {
85         super( gene_tree, species_tree );
86         _speciation_or_duplication_events_sum = 0;
87         _speciations_sum = 0;
88         _most_parsimonious_duplication_model = most_parsimonious_duplication_model;
89         _duplications_sum = 0;
90         _strip_gene_tree = strip_gene_tree;
91         _strip_species_tree = strip_species_tree;
92         _stripped_gene_tree_nodes = new ArrayList<PhylogenyNode>();
93         _stripped_species_tree_nodes = new ArrayList<PhylogenyNode>();
94         _mapped_species_tree_nodes = new HashSet<PhylogenyNode>();
95         _scientific_names_mapped_to_reduced_specificity = new TreeSet<String>();
96         linkNodesOfG();
97         PhylogenyMethods.preOrderReId( getSpeciesTree() );
98         geneTreePostOrderTraversal();
99     }
100
101     GSDI( final Phylogeny gene_tree, final Phylogeny species_tree, final boolean most_parsimonious_duplication_model )
102             throws SDIException {
103         this( gene_tree, species_tree, most_parsimonious_duplication_model, false, false );
104     }
105
106     // s is the node on the species tree g maps to.
107     private final void determineEvent( final PhylogenyNode s, final PhylogenyNode g ) {
108         boolean oyako = false;
109         if ( ( g.getChildNode1().getLink() == s ) || ( g.getChildNode2().getLink() == s ) ) {
110             oyako = true;
111         }
112         if ( g.getLink().getNumberOfDescendants() == 2 ) {
113             if ( oyako ) {
114                 g.getNodeData().setEvent( createDuplicationEvent() );
115             }
116             else {
117                 g.getNodeData().setEvent( createSpeciationEvent() );
118             }
119         }
120         else {
121             if ( oyako ) {
122                 final Set<PhylogenyNode> set = new HashSet<PhylogenyNode>();
123                 for( PhylogenyNode n : g.getChildNode1().getAllExternalDescendants() ) {
124                     n = n.getLink();
125                     while ( n.getParent() != s ) {
126                         n = n.getParent();
127                         if ( n.isRoot() ) {
128                             break;
129                         }
130                     }
131                     set.add( n );
132                 }
133                 boolean multiple = false;
134                 for( PhylogenyNode n : g.getChildNode2().getAllExternalDescendants() ) {
135                     n = n.getLink();
136                     while ( n.getParent() != s ) {
137                         n = n.getParent();
138                         if ( n.isRoot() ) {
139                             break;
140                         }
141                     }
142                     if ( set.contains( n ) ) {
143                         multiple = true;
144                         break;
145                     }
146                 }
147                 if ( multiple ) {
148                     g.getNodeData().setEvent( createDuplicationEvent() );
149                 }
150                 else {
151                     if ( _most_parsimonious_duplication_model ) {
152                         g.getNodeData().setEvent( createSpeciationEvent() );
153                     }
154                     else {
155                         g.getNodeData().setEvent( createSingleSpeciationOrDuplicationEvent() );
156                     }
157                 }
158             }
159             else {
160                 g.getNodeData().setEvent( createSpeciationEvent() );
161             }
162         }
163     }
164
165     /**
166      * Traverses the subtree of PhylogenyNode g in postorder, calculating the
167      * mapping function M, and determines which nodes represent speciation
168      * events and which ones duplication events.
169      * <p>
170      * Preconditions: Mapping M for external nodes must have been calculated and
171      * the species tree must be labeled in preorder.
172      * <p>
173      * 
174      */
175     final void geneTreePostOrderTraversal() {
176         for( final PhylogenyNodeIterator it = getGeneTree().iteratorPostorder(); it.hasNext(); ) {
177             final PhylogenyNode g = it.next();
178             if ( g.isInternal() ) {
179                 PhylogenyNode s1 = g.getChildNode1().getLink();
180                 PhylogenyNode s2 = g.getChildNode2().getLink();
181                 while ( s1 != s2 ) {
182                     if ( s1.getId() > s2.getId() ) {
183                         s1 = s1.getParent();
184                     }
185                     else {
186                         s2 = s2.getParent();
187                     }
188                 }
189                 g.setLink( s1 );
190                 determineEvent( s1, g );
191             }
192         }
193     }
194
195     private final Event createDuplicationEvent() {
196         final Event event = Event.createSingleDuplicationEvent();
197         ++_duplications_sum;
198         return event;
199     }
200
201     private final Event createSingleSpeciationOrDuplicationEvent() {
202         final Event event = Event.createSingleSpeciationOrDuplicationEvent();
203         ++_speciation_or_duplication_events_sum;
204         return event;
205     }
206
207     private final Event createSpeciationEvent() {
208         final Event event = Event.createSingleSpeciationEvent();
209         ++_speciations_sum;
210         return event;
211     }
212
213     public final int getSpeciationOrDuplicationEventsSum() {
214         return _speciation_or_duplication_events_sum;
215     }
216
217     public final int getSpeciationsSum() {
218         return _speciations_sum;
219     }
220
221     /**
222      * This allows for linking of internal nodes of the species tree (as opposed
223      * to just external nodes, as in the method it overrides.
224      * @throws SDIException 
225      * 
226      */
227     @Override
228     final void linkNodesOfG() throws SDIException {
229         final Map<String, PhylogenyNode> species_to_node_map = new HashMap<String, PhylogenyNode>();
230         final List<PhylogenyNode> species_tree_ext_nodes = new ArrayList<PhylogenyNode>();
231         _tax_comp_base = determineTaxonomyComparisonBase( _gene_tree );
232         // Stringyfied taxonomy is the key, node is the value.
233         for( final PhylogenyNodeIterator iter = _species_tree.iteratorExternalForward(); iter.hasNext(); ) {
234             final PhylogenyNode s = iter.next();
235             species_tree_ext_nodes.add( s );
236             if ( s.getNodeData().isHasTaxonomy() ) {
237                 final String tax_str = taxonomyToString( s, _tax_comp_base );
238                 if ( !ForesterUtil.isEmpty( tax_str ) ) {
239                     if ( species_to_node_map.containsKey( tax_str ) ) {
240                         throw new SDIException( "taxonomy \"" + s + "\" is not unique in species tree" );
241                     }
242                     species_to_node_map.put( tax_str, s );
243                 }
244             }
245         }
246         // Retrieve the reference to the node with a matching stringyfied taxonomy.
247         for( final PhylogenyNodeIterator iter = _gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
248             final PhylogenyNode g = iter.next();
249             if ( !g.getNodeData().isHasTaxonomy() ) {
250                 if ( _strip_gene_tree ) {
251                     _stripped_gene_tree_nodes.add( g );
252                 }
253                 else {
254                     throw new SDIException( "gene tree node \"" + g + "\" has no taxonomic data" );
255                 }
256             }
257             else {
258                 final String tax_str = taxonomyToString( g, _tax_comp_base );
259                 if ( ForesterUtil.isEmpty( tax_str ) ) {
260                     if ( _strip_gene_tree ) {
261                         _stripped_gene_tree_nodes.add( g );
262                     }
263                     else {
264                         throw new SDIException( "gene tree node \"" + g + "\" has no appropriate taxonomic data" );
265                     }
266                 }
267                 else {
268                     PhylogenyNode s = species_to_node_map.get( tax_str );
269                     if ( ( _tax_comp_base == TaxonomyComparisonBase.SCIENTIFIC_NAME ) && ( s == null )
270                             && ( ForesterUtil.countChars( tax_str, ' ' ) > 1 ) ) {
271                         s = tryMapByRemovingOverlySpecificData( species_to_node_map, tax_str );
272                     }
273                     if ( s == null ) {
274                         if ( _strip_gene_tree ) {
275                             _stripped_gene_tree_nodes.add( g );
276                         }
277                         else {
278                             throw new SDIException( "taxonomy \"" + g.getNodeData().getTaxonomy()
279                                     + "\" not present in species tree" );
280                         }
281                     }
282                     else {
283                         g.setLink( s );
284                         _mapped_species_tree_nodes.add( s );
285                     }
286                 }
287             }
288         } // for loop
289         if ( _strip_gene_tree ) {
290             stripGeneTree();
291             if ( getGeneTree().isEmpty() || ( getGeneTree().getNumberOfExternalNodes() < 2 ) ) {
292                 throw new SDIException( "species could not be mapped between gene tree and species tree" );
293             }
294         }
295         if ( _strip_species_tree ) {
296             stripSpeciesTree( species_tree_ext_nodes );
297         }
298     }
299
300     private final PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
301                                                                     final String tax_str ) {
302         PhylogenyNode s = tryMapByRemovingOverlySpecificData( species_to_node_map, tax_str, " (" );
303         if ( s == null ) {
304             if ( ForesterUtil.countChars( tax_str, ' ' ) == 2 ) {
305                 final String new_tax_str = tax_str.substring( 0, tax_str.lastIndexOf( ' ' ) ).trim();
306                 s = species_to_node_map.get( new_tax_str );
307                 if ( s != null ) {
308                     addScientificNamesMappedToReducedSpecificity( tax_str, new_tax_str );
309                 }
310             }
311         }
312         if ( s == null ) {
313             for( final String t : new String[] { " subspecies ", " strain ", " variety ", " varietas ", " subvariety ",
314                     " form ", " subform ", " cultivar ", " section ", " subsection " } ) {
315                 s = tryMapByRemovingOverlySpecificData( species_to_node_map, tax_str, t );
316                 if ( s != null ) {
317                     break;
318                 }
319             }
320         }
321         return s;
322     }
323
324     private final PhylogenyNode tryMapByRemovingOverlySpecificData( final Map<String, PhylogenyNode> species_to_node_map,
325                                                                     final String tax_str,
326                                                                     final String term ) {
327         final int i = tax_str.indexOf( term );
328         if ( i > 4 ) {
329             final String new_tax_str = tax_str.substring( 0, i ).trim();
330             final PhylogenyNode s = species_to_node_map.get( new_tax_str );
331             if ( s != null ) {
332                 addScientificNamesMappedToReducedSpecificity( tax_str, new_tax_str );
333             }
334             return s;
335         }
336         return null;
337     }
338
339     private final void addScientificNamesMappedToReducedSpecificity( final String s1, final String s2 ) {
340         _scientific_names_mapped_to_reduced_specificity.add( s1 + " -> " + s2 );
341     }
342
343     public final SortedSet<String> getReMappedScientificNamesFromGeneTree() {
344         return _scientific_names_mapped_to_reduced_specificity;
345     }
346
347     public TaxonomyComparisonBase getTaxCompBase() {
348         return _tax_comp_base;
349     }
350
351     private void stripSpeciesTree( final List<PhylogenyNode> species_tree_ext_nodes ) {
352         for( final PhylogenyNode s : species_tree_ext_nodes ) {
353             if ( !_mapped_species_tree_nodes.contains( s ) ) {
354                 _species_tree.deleteSubtree( s, true );
355                 _stripped_species_tree_nodes.add( s );
356             }
357         }
358         _species_tree.clearHashIdToNodeMap();
359         _species_tree.externalNodesHaveChanged();
360     }
361
362     public List<PhylogenyNode> getStrippedSpeciesTreeNodes() {
363         return _stripped_species_tree_nodes;
364     }
365
366     private void stripGeneTree() {
367         for( final PhylogenyNode g : _stripped_gene_tree_nodes ) {
368             _gene_tree.deleteSubtree( g, true );
369         }
370         _gene_tree.clearHashIdToNodeMap();
371         _gene_tree.externalNodesHaveChanged();
372     }
373
374     public Set<PhylogenyNode> getMappedExternalSpeciesTreeNodes() {
375         return _mapped_species_tree_nodes;
376     }
377
378     public static TaxonomyComparisonBase determineTaxonomyComparisonBase( final Phylogeny gene_tree ) {
379         int with_id_count = 0;
380         int with_code_count = 0;
381         int with_sn_count = 0;
382         int max = 0;
383         for( final PhylogenyNodeIterator iter = gene_tree.iteratorExternalForward(); iter.hasNext(); ) {
384             final PhylogenyNode g = iter.next();
385             if ( g.getNodeData().isHasTaxonomy() ) {
386                 final Taxonomy tax = g.getNodeData().getTaxonomy();
387                 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) {
388                     if ( ++with_id_count > max ) {
389                         max = with_id_count;
390                     }
391                 }
392                 if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
393                     if ( ++with_code_count > max ) {
394                         max = with_code_count;
395                     }
396                 }
397                 if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
398                     if ( ++with_sn_count > max ) {
399                         max = with_sn_count;
400                     }
401                 }
402             }
403         }
404         if ( max == 0 ) {
405             throw new IllegalArgumentException( "gene tree has no taxonomic data" );
406         }
407         else if ( max == 1 ) {
408             throw new IllegalArgumentException( "gene tree has only one node with taxonomic data" );
409         }
410         else if ( max == with_id_count ) {
411             return SDI.TaxonomyComparisonBase.ID;
412         }
413         else if ( max == with_sn_count ) {
414             return SDI.TaxonomyComparisonBase.SCIENTIFIC_NAME;
415         }
416         else {
417             return SDI.TaxonomyComparisonBase.CODE;
418         }
419     }
420
421     public List<PhylogenyNode> getStrippedExternalGeneTreeNodes() {
422         return _stripped_gene_tree_nodes;
423     }
424
425     @Override
426     public final String toString() {
427         final StringBuffer sb = new StringBuffer();
428         sb.append( "Most parsimonious duplication model: " + _most_parsimonious_duplication_model );
429         sb.append( ForesterUtil.getLineSeparator() );
430         sb.append( "Speciations sum                    : " + getSpeciationsSum() );
431         sb.append( ForesterUtil.getLineSeparator() );
432         sb.append( "Duplications sum                   : " + getDuplicationsSum() );
433         sb.append( ForesterUtil.getLineSeparator() );
434         if ( !_most_parsimonious_duplication_model ) {
435             sb.append( "Speciation or duplications sum     : " + getSpeciationOrDuplicationEventsSum() );
436             sb.append( ForesterUtil.getLineSeparator() );
437         }
438         sb.append( "mapping cost L                     : " + computeMappingCostL() );
439         return sb.toString();
440     }
441 }