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