clean up
[jalview.git] / forester / java / src / org / forester / sdi / ORcount.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 // Copyright (C) 2000-2001 Washington University School of Medicine
8 // and Howard Hughes Medical Institute
9 // All rights reserved
10 //
11 // This library is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU Lesser General Public
13 // License as published by the Free Software Foundation; either
14 // version 2.1 of the License, or (at your option) any later version.
15 //
16 // This library is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 // Lesser General Public License for more details.
20 //
21 // You should have received a copy of the GNU Lesser General Public
22 // License along with this library; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 //
25 // Contact: phylosoft @ gmail . com
26 // WWW: www.phylosoft.org/forester
27
28 package org.forester.sdi;
29
30 import java.io.File;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34
35 import org.forester.io.parsers.PhylogenyParser;
36 import org.forester.phylogeny.Phylogeny;
37 import org.forester.phylogeny.PhylogenyMethods;
38 import org.forester.phylogeny.PhylogenyNode;
39 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
40 import org.forester.phylogeny.factories.PhylogenyFactory;
41 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
42 import org.forester.util.ForesterUtil;
43
44 /*
45  * Allows to <ul> <li> <li> <li> </ul>
46  * 
47  * @see SDIse
48  * 
49  * @see SDI
50  * 
51  * @author Christian M. Zmasek
52  * 
53  * @version 1.400 -- last modified: 10/29/2005
54  */
55 public class ORcount {
56
57     private static final String[]                     group_1              = { "ANOGA", "DROME", "CAEBR", "CAEEL" };
58     private static final String[]                     group_2              = { "CIOIN", "FUGRU", "MOUSE", "RAT",
59             "HUMAN"                                                       };
60     private static final String[]                     all_species          = { "ANOGA", "DROME", "CAEBR", "CAEEL",
61             "CIOIN", "FUGRU", "MOUSE", "RAT", "HUMAN"                     };
62     private final Phylogeny[]                         _trees;
63     private HashMap<String, HashMap<Object, Integer>> _species             = null;
64     private ArrayList<String>                         _names               = null;
65     private int                                       _group1_vs_2_counter = 0;
66
67     /**
68      * Default contructor which
69      */
70     public ORcount( final Phylogeny[] trees ) {
71         _trees = trees;
72     } // ORcount( final Phylogeny[] trees )
73
74     private void count( final PhylogenyNode node ) {
75         final List<PhylogenyNode> external_nodes = node.getAllExternalDescendants();
76         for( int i = 1; i < external_nodes.size(); ++i ) {
77             for( int j = 0; j < i; ++j ) {
78                 final PhylogenyNode node_i = external_nodes.get( i );
79                 final PhylogenyNode node_j = external_nodes.get( j );
80                 final String si = PhylogenyMethods.getSpecies( node_i );
81                 final String sj = PhylogenyMethods.getSpecies( node_j );
82                 count( si, sj, node_i.getName(), node_j.getName() );
83             }
84         }
85     } // count( PhylogenyNode )
86
87     private void count( final String a, final String b, final String seq_name_a, final String seq_name_b ) {
88         HashMap<Object, Integer> h1 = _species.get( a );
89         if ( h1 == null ) {
90             throw new RuntimeException( "Unexpected error: Species \"" + a + "\" not present in species matrix." );
91         }
92         Object h2 = h1.get( b );
93         String species_in_h1 = b;
94         // We only look at the half matrix, and we do not know/care about the
95         // order
96         // of the keys (species).
97         if ( h2 == null ) {
98             h1 = _species.get( b );
99             if ( h1 == null ) {
100                 throw new RuntimeException( "Unexpected error: Species \"" + b + "\" not present in species matrix." );
101             }
102             h2 = h1.get( a );
103             species_in_h1 = a;
104         }
105         if ( h2 == null ) {
106             throw new RuntimeException( "Unexpected error: Species \"" + a + "\" not present in species matrix." );
107         }
108         h1.put( species_in_h1, new Integer( ( ( Integer ) h2 ).intValue() + 1 ) );
109         _names.add( a + "-" + seq_name_a + " = " + b + "-" + seq_name_b );
110     } // count( String, String )
111
112     public void countSharedAncestralClades( final Phylogeny tree,
113                                             final int bootstrap_threshold,
114                                             final String[] group_1,
115                                             final String[] group_2 ) {
116         if ( ( group_1 == null ) || ( group_2 == null ) ) {
117             throw new IllegalArgumentException( "String[](s) in arguments to method \"ORcount.countSharedAncestralClades\" is (are) null." );
118         }
119         if ( !tree.isRooted() ) {
120             throw new IllegalArgumentException( "Phylogeny must be rooted in order to count shared ancestral clades." );
121         }
122         final PhylogenyNodeIterator it = tree.iteratorPostorder();
123         tree.setIndicatorsToZero();
124         while ( it.hasNext() ) {
125             final PhylogenyNode current_node = it.next();
126             if ( current_node.getNumberOfDescendants() != 2 ) {
127                 throw new IllegalArgumentException( "Phylogeny can not contain multifurcations in order to count shared ancestral clades." );
128             }
129             if ( !current_node.isExternal() ) {
130                 final PhylogenyNode child1 = current_node.getChildNode1();
131                 final PhylogenyNode child2 = current_node.getChildNode2();
132                 if ( ( child1.getIndicator() == 1 ) || ( child2.getIndicator() == 1 ) ) {
133                     current_node.setIndicator( ( byte ) 1 );
134                 }
135                 else {
136                     final List<PhylogenyNode> external_nodes = current_node.getAllExternalDescendants();
137                     final String[] external_species = new String[ external_nodes.size() ];
138                     for( int i = 0; i < external_nodes.size(); ++i ) {
139                         final PhylogenyNode n = external_nodes.get( i );
140                         external_species[ i ] = PhylogenyMethods.getSpecies( n ).trim().toUpperCase();
141                     }
142                     if ( ForesterUtil.isIntersecting( external_species, group_1 )
143                             && ForesterUtil.isIntersecting( external_species, group_2 ) ) {
144                         current_node.setIndicator( ( byte ) 1 );
145                         if ( ( group_1.length == 1 ) && ( group_2.length == 1 ) ) {
146                             count( group_1[ 0 ], group_2[ 0 ], "name a", "name b" );
147                         }
148                         else {
149                             increaseGroup1Vs2Counter();
150                         }
151                     }
152                 }
153             }
154         } // while
155     } // countSharedAncestralClades( Phylogeny, int )
156
157     public void countSharedAncestralClades( final Phylogeny[] trees, final int bootstrap_threshold ) {
158         for( int i = 1; i < ORcount.all_species.length; ++i ) {
159             for( int j = 0; j < i; ++j ) {
160                 final String all_i = ORcount.all_species[ i ].trim().toUpperCase();
161                 final String all_j = ORcount.all_species[ j ].trim().toUpperCase();
162                 final String[] a = { all_i };
163                 final String[] b = { all_j };
164                 for( int k = 0; k < trees.length; ++k ) {
165                     countSharedAncestralClades( trees[ k ], bootstrap_threshold, a, b );
166                 }
167             }
168         }
169         // print();
170         if ( ( ORcount.group_1 != null ) && ( ORcount.group_2 != null ) && ( ORcount.group_1.length > 0 )
171                 && ( ORcount.group_2.length > 0 ) ) {
172             setGroup1Vs2Counter( 0 );
173             for( int k = 0; k < trees.length; ++k ) {
174                 countSharedAncestralClades( trees[ k ], bootstrap_threshold, ORcount.group_1, ORcount.group_2 );
175             }
176             System.out.println( "\nCount [(" + ForesterUtil.stringArrayToString( ORcount.group_1 ) + ") vs ("
177                     + ForesterUtil.stringArrayToString( ORcount.group_2 ) + ")] = " + getGroup1Vs2Counter() );
178         }
179     }
180
181     public void countSuperOrthologousRelations( final int bootstrap_threshold ) {
182         reset();
183         for( int i = 0; i < _trees.length; ++i ) {
184             countSuperOrthologousRelations( _trees[ i ], bootstrap_threshold );
185         }
186     }
187
188     private void countSuperOrthologousRelations( final Phylogeny tree, final int bootstrap_threshold ) {
189         final PhylogenyNodeIterator it = tree.iteratorPostorder();
190         if ( !tree.isRooted() ) {
191             throw new IllegalArgumentException( "Phylogeny must be rooted in order to count 1:1 orthologous relationships." );
192         }
193         // The purpose of this is to find all substrees
194         // which contain only speciation events on all their nodes.
195         // All nodes in these subtrees are "painted" with 0's, wheres
196         // the rest od the nodes in painted with 1's.
197         tree.setIndicatorsToZero();
198         it.reset();
199         while ( it.hasNext() ) {
200             final PhylogenyNode current_node = it.next();
201             if ( current_node.getNumberOfDescendants() != 2 ) {
202                 throw new IllegalArgumentException( "Phylogeny can not contain multifurcations in order to count 1:1 orthologous relationships." );
203             }
204             if ( !current_node.isExternal() && !current_node.isHasAssignedEvent() ) {
205                 throw new IllegalArgumentException( "All nodes must have duplication or speciation assigned in order to count 1:1 orthologous relationships." );
206             }
207             if ( !current_node.isExternal()
208                     && ( current_node.isDuplication() || ( current_node.getChildNode1().getIndicator() == 1 ) || ( current_node
209                             .getChildNode2().getIndicator() == 1 ) ) ) {
210                 current_node.setIndicator( ( byte ) 1 );
211             }
212         }
213         // These find the largest subtrees containing only speciations
214         // and uses their largest nodes to count all possible species
215         // combinations
216         // in their extant external nodes.
217         // ~~~ this could possibly be combined with the first iteration ~~
218         // <<<<<<<<<<<~~~~~~~~~~~~~~~<<<<<<<<<<<<<<<
219         it.reset();
220         while ( it.hasNext() ) {
221             final PhylogenyNode current_node = it.next();
222             if ( !current_node.isExternal()
223                     && ( current_node.getIndicator() == 0 )
224                     && ( current_node.isRoot() || ( current_node.getParent().getIndicator() == 1 ) )
225                     && ( ( bootstrap_threshold < 1 ) || ( ( PhylogenyMethods.getConfidenceValue( current_node ) >= bootstrap_threshold )
226                             && ( PhylogenyMethods.getConfidenceValue( current_node.getChildNode1() ) >= bootstrap_threshold ) && ( PhylogenyMethods
227                             .getConfidenceValue( current_node.getChildNode2() ) >= bootstrap_threshold ) ) ) ) {
228                 count( current_node );
229             }
230         }
231     } // countOneToOneOrthologs( Phylogeny, int )
232
233     // This puts all the species found in Phylogeny array _trees into
234     // species HashMap.
235     private void getAllSpecies() {
236         if ( ( getTrees() == null ) || ( getTrees().length < 1 ) ) {
237             throw new RuntimeException( "Phylogeny array in method \"getAllSpecies( HashMap hash )\" is null or empty." );
238         }
239         setSpecies( new HashMap<String, HashMap<Object, Integer>>() );
240         for( int i = 0; i < getTrees().length; ++i ) {
241             PhylogenyNode node = getTrees()[ i ].getFirstExternalNode();
242             while ( node != null ) {
243                 getSpecies().put( PhylogenyMethods.getSpecies( node ), null );
244                 node = node.getNextExternalNode();
245             }
246         }
247     } // void getAllSpecies( HashMap hash )
248
249     private int getGroup1Vs2Counter() {
250         return _group1_vs_2_counter;
251     }
252
253     private HashMap<String, HashMap<Object, Integer>> getSpecies() {
254         return _species;
255     }
256
257     private Phylogeny[] getTrees() {
258         return _trees;
259     }
260
261     private void increaseGroup1Vs2Counter() {
262         _group1_vs_2_counter++;
263     }
264
265     private void printCount() {
266         if ( ( _species == null ) || ( _species.size() < 2 ) ) {
267             throw new RuntimeException( "Species HashMap in method \"setUpCountingMatrix()\" is null or contains less than two species." );
268         }
269         final Object[] species_array = _species.keySet().toArray();
270         final int s = species_array.length;
271         for( int i = 0; i < s - 1; ++i ) {
272             final String species = ( String ) species_array[ i ];
273             System.out.println();
274             System.out.println( species + ":" );
275             final HashMap<?, ?> h = _species.get( species );
276             // Setting up HashMaps linked to by hash (=_species)
277             // Diagonals are ignored, only half the matrix is needed.
278             for( int j = 1 + i; j < s; ++j ) {
279                 final String sp = ( String ) species_array[ j ];
280                 final int c = ( ( Integer ) h.get( sp ) ).intValue();
281                 System.out.println( species + "-" + sp + ": " + c );
282             }
283         }
284     }
285
286     private void printNames() {
287         for( int i = 0; i < _names.size(); ++i ) {
288             System.out.println( i + ": " + _names.get( i ) );
289         }
290     }
291
292     public void reset() {
293         getAllSpecies();
294         setUpCountingMatrix();
295         setGroup1Vs2Counter( 0 );
296         _names = new ArrayList<String>();
297     }
298
299     private void setGroup1Vs2Counter( final int group1_vs_2_counter ) {
300         _group1_vs_2_counter = group1_vs_2_counter;
301     }
302
303     private void setSpecies( final HashMap<String, HashMap<Object, Integer>> species ) {
304         _species = species;
305     }
306
307     private void setUpCountingMatrix() {
308         if ( ( getSpecies() == null ) || ( getSpecies().size() < 2 ) ) {
309             throw new RuntimeException( "Species HashMap in method \"setUpCountingMatrix()\" is null or contains less than two species." );
310         }
311         final Object[] species_array = getSpecies().keySet().toArray();
312         final int s = species_array.length;
313         for( int i = 0; i < s; ++i ) {
314             final String species = ( String ) species_array[ i ];
315             final HashMap<Object, Integer> h = new HashMap<Object, Integer>();
316             // Setting up HashMaps linked to by hash (=_species)
317             // Diagonals are ignored, only half the matrix is needed.
318             for( int j = 1 + i; j < s; ++j ) {
319                 h.put( species_array[ j ], new Integer( 0 ) );
320             }
321             getSpecies().put( species, h );
322         }
323     }
324
325     private static void errorInCommandLine() {
326         System.out.println( "\nORcount: Error in command line.\n" );
327         System.out.println( "Usage: \"\"" );
328         System.out.println( "\nOptions:" );
329         System.out.println( " -" );
330         System.out.println( "" );
331         System.exit( -1 );
332     } // errorInCommandLine()
333
334     /**
335      * Main method for this class.
336      * <p>
337      * (Last modified: 11/26/03)
338      * 
339      * @param args[1or2]
340      *            gene tree file name (in NHX format with species names in
341      *            species name fields and sequence names in sequence name
342      *            fields; unless -n option is used)
343      */
344     public static void main( final String args[] ) {
345         if ( args.length == 0 ) {
346             ORcount.errorInCommandLine();
347         }
348         final Phylogeny[] trees = new Phylogeny[ args.length ];
349         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
350         for( int i = 0; i < trees.length; ++i ) {
351             try {
352                 System.out.println( "Reading tree #" + i + "  [" + args[ i ] + "]" );
353                 final PhylogenyParser pp = ForesterUtil.createParserDependingOnFileType( new File( args[ i ] ), true );
354                 trees[ i ] = factory.create( new File( args[ i ] ), pp )[ 0 ];
355             }
356             catch ( final Exception e ) {
357                 System.out.println( "\nFailed to read \"" + args[ i ] + "\". Terminating.\n" );
358                 System.exit( -1 );
359             }
360         }
361         System.out.println( "Finished reading in trees.\n\n" );
362         final ORcount or_count = new ORcount( trees );
363         try {
364             System.out.println( "\n\n\n\"1:1 ORTHOLOGOUS GENE PAIRS\":\n" );
365             System.out.println( "\n\n\n\"SUPER ORTHOLOGOUS GENE PAIRS\":\n" );
366             or_count.countSuperOrthologousRelations( 0 );
367             or_count.printNames();
368             or_count.printCount();
369             // System.out.println( "\n\n\n\"SHARED ANCESTRAL CLADES\":\n");
370             // or_count.reset();
371             // or_count.countSharedAncestralClades( trees, 0 );
372         }
373         catch ( final Exception e ) {
374             System.out.println( "\nException. Terminating.\n" );
375             System.out.println( "\nException is: " + e + "\n" );
376             e.printStackTrace();
377             System.exit( -1 );
378         }
379         System.out.println( "\nDone." );
380         System.exit( 0 );
381     } // main ( String )
382 } // End of class ORcount.