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