990d1a1cf81bbeedbae2d39808738523086e0826
[jalview.git] / forester / java / src / org / forester / application / rio.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: https://sites.google.com/site/cmzmasek/home/software/forester
27
28 package org.forester.application;
29
30 import java.io.File;
31 import java.io.IOException;
32 import java.util.ArrayList;
33 import java.util.List;
34
35 import org.forester.datastructures.IntMatrix;
36 import org.forester.io.parsers.nhx.NHXParser;
37 import org.forester.rio.RIO;
38 import org.forester.rio.RIO.REROOTING;
39 import org.forester.rio.RIOException;
40 import org.forester.sdi.SDIException;
41 import org.forester.sdi.SDIutil.ALGORITHM;
42 import org.forester.util.BasicDescriptiveStatistics;
43 import org.forester.util.CommandLineArguments;
44 import org.forester.util.EasyWriter;
45 import org.forester.util.ForesterUtil;
46
47 public class rio {
48
49     final static private String  PRG_NAME      = "rio";
50     final static private String  PRG_VERSION   = "4.000 beta 5";
51     final static private String  PRG_DATE      = "2013.01.08";
52     final static private String  E_MAIL        = "czmasek@burnham.org";
53     final static private String  WWW           = "www.phylosoft.org/forester/";
54     final static private String  HELP_OPTION_1 = "help";
55     final static private String  HELP_OPTION_2 = "h";
56     final static private String  GT_FIRST      = "f";
57     final static private String  GT_LAST       = "l";
58     final static private String  REROOTING_OPT = "r";
59     final static private String  OUTGROUP      = "o";
60     final static private String  USE_SDIR      = "b";
61     private static final boolean ITERATING     = true;
62
63     public static void main( final String[] args ) {
64         ForesterUtil.printProgramInformation( PRG_NAME,
65                                               "resampled inference of orthologs",
66                                               PRG_VERSION,
67                                               PRG_DATE,
68                                               E_MAIL,
69                                               WWW,
70                                               ForesterUtil.getForesterLibraryInformation() );
71         CommandLineArguments cla = null;
72         try {
73             cla = new CommandLineArguments( args );
74         }
75         catch ( final Exception e ) {
76             ForesterUtil.fatalError( e.getMessage() );
77         }
78         if ( cla.isOptionSet( HELP_OPTION_1 ) || cla.isOptionSet( HELP_OPTION_2 ) || ( args.length == 0 ) ) {
79             printHelp();
80         }
81         if ( ( args.length < 3 ) || ( args.length > 9 ) ) {
82             System.out.println();
83             System.out.println( "error: incorrect number of arguments" );
84             System.out.println();
85             printHelp();
86         }
87         final List<String> allowed_options = new ArrayList<String>();
88         allowed_options.add( GT_FIRST );
89         allowed_options.add( GT_LAST );
90         allowed_options.add( REROOTING_OPT );
91         allowed_options.add( OUTGROUP );
92         allowed_options.add( USE_SDIR );
93         final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
94         if ( dissallowed_options.length() > 0 ) {
95             ForesterUtil.fatalError( "unknown option(s): " + dissallowed_options );
96         }
97         final File gene_trees_file = cla.getFile( 0 );
98         final File species_tree_file = cla.getFile( 1 );
99         final File orthology_outtable = cla.getFile( 2 );
100         final File logfile;
101         if ( cla.getNumberOfNames() > 3 ) {
102             logfile = cla.getFile( 3 );
103             if ( logfile.exists() ) {
104                 ForesterUtil.fatalError( "\"" + logfile + "\" already exists" );
105             }
106         }
107         else {
108             logfile = null;
109         }
110         boolean sdir = false;
111         if ( cla.isOptionSet( USE_SDIR ) ) {
112             if ( cla.isOptionHasAValue( USE_SDIR ) ) {
113                 ForesterUtil.fatalError( "no value allowed for -" + USE_SDIR );
114             }
115             sdir = true;
116             if ( logfile != null ) {
117                 ForesterUtil.fatalError( "no logfile output for SDIR algorithm" );
118             }
119         }
120         String outgroup = null;
121         if ( cla.isOptionSet( OUTGROUP ) ) {
122             if ( !cla.isOptionHasAValue( OUTGROUP ) ) {
123                 ForesterUtil.fatalError( "no value for -" + OUTGROUP );
124             }
125             if ( sdir ) {
126                 ForesterUtil.fatalError( "no outgroup option for SDIR algorithm" );
127             }
128             outgroup = cla.getOptionValueAsCleanString( OUTGROUP );
129         }
130         REROOTING rerooting = REROOTING.BY_ALGORITHM;
131         if ( cla.isOptionSet( REROOTING_OPT ) ) {
132             if ( !cla.isOptionHasAValue( REROOTING_OPT ) ) {
133                 ForesterUtil.fatalError( "no value for -" + REROOTING_OPT );
134             }
135             if ( sdir ) {
136                 ForesterUtil.fatalError( "no re-rooting option for SDIR algorithm" );
137             }
138             final String rerooting_str = cla.getOptionValueAsCleanString( REROOTING_OPT ).toLowerCase();
139             if ( rerooting_str.equals( "none" ) ) {
140                 rerooting = REROOTING.NONE;
141             }
142             else if ( rerooting_str.equals( "midpoint" ) ) {
143                 rerooting = REROOTING.MIDPOINT;
144             }
145             else if ( rerooting_str.equals( "outgroup" ) ) {
146                 rerooting = REROOTING.OUTGROUP;
147             }
148             else {
149                 ForesterUtil
150                         .fatalError( "values for re-rooting are: 'none', 'midpoint', or 'outgroup' (minizming duplications is default)" );
151             }
152         }
153         if ( ForesterUtil.isEmpty( outgroup ) && ( rerooting == REROOTING.OUTGROUP ) ) {
154             ForesterUtil.fatalError( "selected re-rooting by outgroup, but outgroup not set" );
155         }
156         if ( !ForesterUtil.isEmpty( outgroup ) && ( rerooting != REROOTING.OUTGROUP ) ) {
157             ForesterUtil.fatalError( "outgroup set, but selected re-rooting by other approach" );
158         }
159         int gt_first = RIO.DEFAULT_RANGE;
160         int gt_last = RIO.DEFAULT_RANGE;
161         if ( cla.isOptionSet( GT_FIRST ) ) {
162             if ( !cla.isOptionHasAValue( GT_FIRST ) ) {
163                 ForesterUtil.fatalError( "no value for -" + GT_FIRST );
164             }
165             if ( sdir ) {
166                 ForesterUtil.fatalError( "no gene tree range option for SDIR algorithm" );
167             }
168             try {
169                 gt_first = cla.getOptionValueAsInt( GT_FIRST );
170             }
171             catch ( final IOException e ) {
172                 ForesterUtil.fatalError( "could not parse integer for -" + GT_FIRST + " option" );
173             }
174             if ( gt_first < 0 ) {
175                 ForesterUtil.fatalError( "attempt to set index of first tree to analyze to: " + gt_first );
176             }
177         }
178         if ( cla.isOptionSet( GT_LAST ) ) {
179             if ( !cla.isOptionHasAValue( GT_LAST ) ) {
180                 ForesterUtil.fatalError( "no value for -" + GT_LAST );
181             }
182             if ( sdir ) {
183                 ForesterUtil.fatalError( "no gene tree range option for SDIR algorithm" );
184             }
185             try {
186                 gt_last = cla.getOptionValueAsInt( GT_LAST );
187             }
188             catch ( final IOException e ) {
189                 ForesterUtil.fatalError( "could not parse integer for -" + GT_LAST + " option" );
190             }
191             if ( gt_last < 0 ) {
192                 ForesterUtil.fatalError( "attempt to set index of last tree to analyze to: " + gt_last );
193             }
194         }
195         if ( ( ( gt_last != RIO.DEFAULT_RANGE ) && ( gt_first != RIO.DEFAULT_RANGE ) ) && ( ( gt_last < gt_first ) ) ) {
196             ForesterUtil.fatalError( "attempt to set range (0-based) of gene to analyze to: from " + gt_first + " to "
197                     + gt_last );
198         }
199         ForesterUtil.fatalErrorIfFileNotReadable( gene_trees_file );
200         ForesterUtil.fatalErrorIfFileNotReadable( species_tree_file );
201         if ( orthology_outtable.exists() ) {
202             ForesterUtil.fatalError( "\"" + orthology_outtable + "\" already exists" );
203         }
204         long time = 0;
205         System.out.println( "Gene trees                : " + gene_trees_file );
206         System.out.println( "Species tree              : " + species_tree_file );
207         System.out.println( "All vs all orthology table: " + orthology_outtable );
208         if ( logfile != null ) {
209             System.out.println( "Logfile                   : " + logfile );
210         }
211         if ( gt_first != RIO.DEFAULT_RANGE ) {
212             System.out.println( "First gene tree to analyze: " + gt_first );
213         }
214         if ( gt_last != RIO.DEFAULT_RANGE ) {
215             System.out.println( "Last gene tree to analyze : " + gt_last );
216         }
217         String rerooting_str = "";
218         switch ( rerooting ) {
219             case BY_ALGORITHM: {
220                 rerooting_str = "by minimizing duplications";
221                 break;
222             }
223             case MIDPOINT: {
224                 rerooting_str = "by midpoint method";
225                 break;
226             }
227             case OUTGROUP: {
228                 rerooting_str = "by outgroup: " + outgroup;
229                 break;
230             }
231             case NONE: {
232                 rerooting_str = "none";
233                 break;
234             }
235         }
236         System.out.println( "Re-rooting                : " + rerooting_str );
237         if ( !sdir ) {
238             System.out.println( "Non binary species tree   : allowed" );
239         }
240         else {
241             System.out.println( "Non binary species tree   : disallowed" );
242         }
243         time = System.currentTimeMillis();
244         final ALGORITHM algorithm;
245         if ( sdir ) {
246             algorithm = ALGORITHM.SDIR;
247         }
248         else {
249             algorithm = ALGORITHM.GSDIR;
250         }
251         try {
252             final RIO rio;
253             if ( ITERATING ) {
254                 final NHXParser p = new NHXParser();
255                 p.setReplaceUnderscores( false );
256                 p.setIgnoreQuotes( true );
257                 p.setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.YES );
258                 p.setSource( gene_trees_file );
259                 rio = RIO.executeAnalysis( p,
260                                            species_tree_file,
261                                            algorithm,
262                                            rerooting,
263                                            outgroup,
264                                            gt_first,
265                                            gt_last,
266                                            logfile != null,
267                                            true );
268             }
269             else {
270                 rio = RIO.executeAnalysis( gene_trees_file,
271                                            species_tree_file,
272                                            algorithm,
273                                            rerooting,
274                                            outgroup,
275                                            gt_first,
276                                            gt_last,
277                                            logfile != null,
278                                            true );
279             }
280             if ( algorithm == ALGORITHM.GSDIR ) {
281                 System.out.println( "Taxonomy linking based on : " + rio.getGSDIRtaxCompBase() );
282             }
283             final IntMatrix m;
284             if ( ITERATING ) {
285                 m = rio.getOrthologTable();
286             }
287             else {
288                 m = RIO.calculateOrthologTable( rio.getAnalyzedGeneTrees(), true );
289             }
290             final BasicDescriptiveStatistics stats = rio.getDuplicationsStatistics();
291             writeTable( orthology_outtable, stats.getN(), m );
292             if ( ( algorithm != ALGORITHM.SDIR ) && ( logfile != null ) ) {
293                 writeLogFile( logfile,
294                               rio,
295                               species_tree_file,
296                               gene_trees_file,
297                               orthology_outtable,
298                               PRG_NAME,
299                               PRG_VERSION,
300                               PRG_DATE,
301                               ForesterUtil.getForesterLibraryInformation() );
302             }
303             ;
304             final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#" );
305             System.out.println( "Mean number of duplications  : " + df.format( stats.arithmeticMean() ) + " (sd: "
306                     + df.format( stats.sampleStandardDeviation() ) + ") ("
307                     + df.format( 100.0 * stats.arithmeticMean() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
308             if ( stats.getN() > 3 ) {
309                 System.out.println( "Median number of duplications: " + df.format( stats.median() ) + " ("
310                         + df.format( 100.0 * stats.median() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
311             }
312             System.out.println( "Minimum duplications         : " + ( int ) stats.getMin() + " ("
313                     + df.format( 100.0 * stats.getMin() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
314             System.out.println( "Maximum duplications         : " + ( int ) stats.getMax() + " ("
315                     + df.format( 100.0 * stats.getMax() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
316             System.out.println( "Gene tree internal nodes     : " + rio.getIntNodesOfAnalyzedGeneTrees() );
317             System.out.println( "Gene tree external nodes     : " + rio.getExtNodesOfAnalyzedGeneTrees() );
318         }
319         catch ( final RIOException e ) {
320             ForesterUtil.fatalError( e.getLocalizedMessage() );
321         }
322         catch ( final SDIException e ) {
323             ForesterUtil.fatalError( e.getLocalizedMessage() );
324         }
325         catch ( final IOException e ) {
326             ForesterUtil.fatalError( e.getLocalizedMessage() );
327         }
328         catch ( final OutOfMemoryError e ) {
329             ForesterUtil.outOfMemoryError( e );
330         }
331         catch ( final Exception e ) {
332             ForesterUtil.unexpectedFatalError( e );
333         }
334         catch ( final Error e ) {
335             ForesterUtil.unexpectedFatalError( e );
336         }
337         time = System.currentTimeMillis() - time;
338         System.out.println( "Time: " + time + "ms" );
339         System.out.println( "OK" );
340         System.exit( 0 );
341     }
342
343     private final static void printHelp() {
344         System.out.println( "Usage" );
345         System.out.println();
346         System.out
347                 .println( PRG_NAME
348                         + " [options] <gene trees infile> <species tree infile> <all vs all orthology table outfile> [logfile]" );
349         System.out.println();
350         System.out.println( " Options" );
351         System.out.println( "  -" + GT_FIRST + "=<first>     : first gene tree to analyze (0-based index)" );
352         System.out.println( "  -" + GT_LAST + "=<last>      : last gene tree to analyze (0-based index)" );
353         System.out.println( "  -" + REROOTING_OPT
354                 + "=<re-rooting>: re-rooting method for gene trees, possible values or 'none', 'midpoint'," );
355         System.out.println( "                   or 'outgroup' (default: by minizming duplications)" );
356         System.out.println( "  -" + OUTGROUP
357                 + "=<outgroup>  : for rooting by outgroup, name of outgroup (external gene tree node)" );
358         System.out.println( "  -" + USE_SDIR
359                 + "             : to use SDIR instead of GSDIR (faster, but non-binary species trees are" );
360         System.out.println( "                   disallowed, as are most options)" );
361         System.out.println();
362         System.out.println( " Formats" );
363         System.out
364                 .println( "  The gene trees, as well as the species tree, ideally are in phyloXML (www.phyloxml.org) format," );
365         System.out
366                 .println( "  but can also be in New Hamphshire (Newick) or Nexus format as long as species information can be" );
367         System.out
368                 .println( "  extracted from the gene names (e.g. \"HUMAN\" from \"BCL2_HUMAN\") and matched to a single species" );
369         System.out.println( "  in the species tree." );
370         System.out.println();
371         System.out.println( " Examples" );
372         System.out.println( "  \"rio gene_trees.nh species.xml outtable.tsv log.txt\"" );
373         System.out.println();
374         System.out.println( " More information: http://code.google.com/p/forester/wiki/RIO" );
375         System.out.println();
376         System.exit( -1 );
377     }
378
379     private static void writeLogFile( final File logfile,
380                                       final RIO rio,
381                                       final File species_tree_file,
382                                       final File gene_trees_file,
383                                       final File outtable,
384                                       final String prg_name,
385                                       final String prg_v,
386                                       final String prg_date,
387                                       final String f ) throws IOException {
388         final EasyWriter out = ForesterUtil.createEasyWriter( logfile );
389         out.println( prg_name );
390         out.println( "version : " + prg_v );
391         out.println( "date    : " + prg_date );
392         out.println( "based on: " + f );
393         out.println( "----------------------------------" );
394         out.println( "Gene trees                                      : " + gene_trees_file );
395         out.println( "Species tree                                    : " + species_tree_file );
396         out.println( "All vs all orthology table                      : " + outtable );
397         out.flush();
398         out.println( rio.getLog().toString() );
399         out.close();
400         System.out.println( "Wrote log to \"" + logfile + "\"" );
401     }
402
403     private static void writeTable( final File table_outfile, final int gene_trees_analyzed, final IntMatrix m )
404             throws IOException {
405         final EasyWriter w = ForesterUtil.createEasyWriter( table_outfile );
406         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.###" );
407         df.setDecimalSeparatorAlwaysShown( false );
408         for( int i = 0; i < m.size(); ++i ) {
409             w.print( "\t" );
410             w.print( m.getLabel( i ) );
411         }
412         w.println();
413         for( int x = 0; x < m.size(); ++x ) {
414             w.print( m.getLabel( x ) );
415             for( int y = 0; y < m.size(); ++y ) {
416                 w.print( "\t" );
417                 if ( x == y ) {
418                     if ( m.get( x, y ) != gene_trees_analyzed ) {
419                         ForesterUtil.unexpectedFatalError( "diagonal value is off" );
420                     }
421                     w.print( "-" );
422                 }
423                 else {
424                     w.print( df.format( ( ( double ) m.get( x, y ) ) / gene_trees_analyzed ) );
425                 }
426             }
427             w.println();
428         }
429         w.close();
430         System.out.println( "Wrote table to \"" + table_outfile + "\"" );
431     }
432 }