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