"rio" 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.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.17";
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         String outgroup = null;
114         if ( cla.isOptionSet( OUTGROUP ) ) {
115             if ( !cla.isOptionHasAValue( OUTGROUP ) ) {
116                 ForesterUtil.fatalError( PRG_NAME, "no value for -" + OUTGROUP );
117             }
118             outgroup = cla.getOptionValueAsCleanString( OUTGROUP );
119         }
120         REROOTING rerooting = REROOTING.BY_ALGORITHM;
121         if ( cla.isOptionSet( REROOTING_OPT ) ) {
122             if ( !cla.isOptionHasAValue( REROOTING_OPT ) ) {
123                 ForesterUtil.fatalError( PRG_NAME, "no value for -" + REROOTING_OPT );
124             }
125             final String rerooting_str = cla.getOptionValueAsCleanString( REROOTING_OPT ).toLowerCase();
126             if ( rerooting_str.equals( "none" ) ) {
127                 rerooting = REROOTING.NONE;
128             }
129             else if ( rerooting_str.equals( "midpoint" ) ) {
130                 rerooting = REROOTING.MIDPOINT;
131             }
132             else if ( rerooting_str.equals( "outgroup" ) ) {
133                 rerooting = REROOTING.OUTGROUP;
134             }
135             else {
136                 ForesterUtil.fatalError( PRG_NAME, "legal values for  -" + REROOTING_OPT
137                         + " are: none, midpoint, or outgroup (minizming duplications is default)" );
138             }
139         }
140         int gt_first = -1;
141         int gt_last = -1;
142         if ( cla.isOptionSet( GT_FIRST ) ) {
143             if ( !cla.isOptionHasAValue( GT_FIRST ) ) {
144                 ForesterUtil.fatalError( PRG_NAME, "no value for -" + GT_FIRST );
145             }
146             try {
147                 gt_first = cla.getOptionValueAsInt( GT_FIRST );
148             }
149             catch ( IOException e ) {
150                 ForesterUtil.fatalError( PRG_NAME, "could not parse integer for -" + GT_FIRST );
151             }
152         }
153         if ( cla.isOptionSet( GT_LAST ) ) {
154             if ( !cla.isOptionHasAValue( GT_LAST ) ) {
155                 ForesterUtil.fatalError( PRG_NAME, "no value for -" + GT_LAST );
156             }
157             try {
158                 gt_last = cla.getOptionValueAsInt( GT_LAST );
159             }
160             catch ( IOException e ) {
161                 ForesterUtil.fatalError( PRG_NAME, "could not parse integer for -" + GT_LAST );
162             }
163         }
164         ForesterUtil.fatalErrorIfFileNotReadable( PRG_NAME, gene_trees_file );
165         ForesterUtil.fatalErrorIfFileNotReadable( PRG_NAME, species_tree_file );
166         if ( orthology_outtable.exists() ) {
167             ForesterUtil.fatalError( PRG_NAME, "\"" + orthology_outtable + "\" already exists" );
168         }
169         boolean sdir = false;
170         if ( cla.isOptionSet( USE_SDIR ) ) {
171             if ( cla.isOptionHasAValue( USE_SDIR ) ) {
172                 ForesterUtil.fatalError( PRG_NAME, "no value allowed for -" + USE_SDIR );
173             }
174             sdir = true;
175             if ( logfile != null ) {
176                 ForesterUtil.fatalError( PRG_NAME, "logfile output only for GSDIR algorithm" );
177             }
178         }
179         long time = 0;
180         System.out.println( "Gene trees                : " + gene_trees_file );
181         System.out.println( "Species tree              : " + species_tree_file );
182         System.out.println( "All vs all orthology table: " + orthology_outtable );
183         if ( !sdir ) {
184             if ( logfile != null ) {
185                 System.out.println( "Logfile                   : " + logfile );
186             }
187             System.out.println( "Non binary species tree   : allowed (GSDIR algorithm)" );
188         }
189         else {
190             System.out.println( "Non binary species tree   : disallowed (SDIR algorithm)" );
191         }
192         time = System.currentTimeMillis();
193         Phylogeny species_tree = null;
194         try {
195             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
196             species_tree = factory.create( species_tree_file, new PhyloXmlParser() )[ 0 ];
197         }
198         catch ( final Exception e ) {
199             e.printStackTrace();
200             System.exit( -1 );
201         }
202         if ( !species_tree.isRooted() ) {
203             ForesterUtil.fatalError( PRG_NAME, "species tree is not rooted" );
204         }
205         final int o = PhylogenyMethods.countNumberOfOneDescendantNodes( species_tree );
206         if ( o > 0 ) {
207             ForesterUtil.printWarningMessage( PRG_NAME, "species tree has " + o
208                     + " internal nodes with only one descendent! Going to strip them." );
209             PhylogenyMethods.deleteInternalNodesWithOnlyOneDescendent( species_tree );
210             if ( PhylogenyMethods.countNumberOfOneDescendantNodes( species_tree ) > 0 ) {
211                 ForesterUtil.unexpectedFatalError( PRG_NAME, "stripping of one-desc nodes failed" );
212             }
213         }
214         final ALGORITHM algorithm;
215         if ( sdir ) {
216             algorithm = ALGORITHM.SDIR;
217         }
218         else {
219             algorithm = ALGORITHM.GSDIR;
220         }
221         try {
222             final RIO rio = RIO.executeAnalysis( gene_trees_file,
223                                                  species_tree,
224                                                  algorithm,
225                                                  rerooting,
226                                                  outgroup,
227                                                  logfile != null,
228                                                  true );
229             if ( algorithm == ALGORITHM.GSDIR ) {
230                 ForesterUtil.programMessage( PRG_NAME, "taxonomy linking based on: " + rio.getGSDIRtaxCompBase() );
231             }
232             tableOutput( orthology_outtable, rio );
233             if ( ( algorithm != ALGORITHM.SDIR ) && ( logfile != null ) ) {
234                 writeLogFile( logfile,
235                               rio,
236                               species_tree_file,
237                               gene_trees_file,
238                               orthology_outtable,
239                               PRG_NAME,
240                               PRG_VERSION,
241                               PRG_DATE,
242                               ForesterUtil.getForesterLibraryInformation() );
243             }
244             final BasicDescriptiveStatistics stats = rio.getDuplicationsStatistics();
245             final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#" );
246             ForesterUtil.programMessage( PRG_NAME,
247                                          "Mean number of duplications  : " + df.format( stats.arithmeticMean() )
248                                                  + " (sd: " + df.format( stats.sampleStandardDeviation() ) + ")" );
249             if ( stats.getN() > 3 ) {
250                 ForesterUtil.programMessage( PRG_NAME, "Median number of duplications: " + df.format( stats.median() ) );
251             }
252             ForesterUtil.programMessage( PRG_NAME, "Minimum duplications         : " + ( int ) stats.getMin() );
253             ForesterUtil.programMessage( PRG_NAME, "Maximum duplications         : " + ( int ) stats.getMax() );
254         }
255         catch ( final RIOException e ) {
256             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
257         }
258         catch ( final SDIException e ) {
259             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
260         }
261         catch ( final IOException e ) {
262             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
263         }
264         catch ( final Exception e ) {
265             ForesterUtil.unexpectedFatalError( PRG_NAME, e );
266         }
267         time = System.currentTimeMillis() - time;
268         ForesterUtil.programMessage( PRG_NAME, "time: " + time + "ms" );
269         ForesterUtil.programMessage( PRG_NAME, "OK" );
270         System.exit( 0 );
271     }
272
273     private final static void printHelp() {
274         System.out.println( "Usage" );
275         System.out.println();
276         System.out
277                 .println( PRG_NAME
278                         + " [options] <gene trees infile> <species tree infile> <all vs all orthology table outfile> [logfile]" );
279         System.out.println();
280         System.out.println( " Options" );
281         System.out.println( "  -" + GT_FIRST + "=<first>   : to" );
282         System.out.println( "  -" + GT_LAST + "=<last>    : to" );
283         System.out.println( "  -" + REROOTING_OPT + "           : to" );
284         System.out.println( "  -" + OUTGROUP + "=<outgroup>: tp" );
285         System.out.println( "  -" + USE_SDIR
286                 + "           : to use SDIR instead of GSDIR (faster, but non-binary species trees are disallowed)" );
287         System.out.println();
288         System.out.println( " Formats" );
289         System.out.println( "  The species tree is expected to be in phyloXML format." );
290         System.out
291                 .println( "  The gene trees ideally are in phyloXML as well, but can also be in New Hamphshire (Newick)" );
292         System.out.println( "  or Nexus format as long as species information can be extracted from the gene names" );
293         System.out.println( "  (e.g. \"HUMAN\" from \"BCL2_HUMAN\")." );
294         System.out.println();
295         System.out.println( " Examples" );
296         System.out.println( "  \"rio gene_trees.nh species.xml outtable.tsv log.txt\"" );
297         System.out.println();
298         System.out.println( " More information: http://code.google.com/p/forester/wiki/RIO" );
299         System.out.println();
300         System.exit( -1 );
301     }
302
303     private static void tableOutput( final File table_outfile, final RIO rio ) throws IOException, RIOException {
304         final IntMatrix m = RIO.calculateOrthologTable( rio.getAnalyzedGeneTrees(), true );
305         writeTable( table_outfile, rio, m );
306     }
307
308     private static void writeLogFile( final File logfile,
309                                       final RIO rio,
310                                       final File species_tree_file,
311                                       final File gene_trees_file,
312                                       final File outtable,
313                                       final String prg_name,
314                                       final String prg_v,
315                                       final String prg_date,
316                                       final String f ) throws IOException {
317         final EasyWriter out = ForesterUtil.createEasyWriter( logfile );
318         out.println( prg_name );
319         out.println( "version : " + prg_v );
320         out.println( "date    : " + prg_date );
321         out.println( "based on: " + f );
322         out.println( "----------------------------------" );
323         out.println( "Gene trees                                      : " + gene_trees_file );
324         out.println( "Species tree                                    : " + species_tree_file );
325         out.println( "All vs all orthology table                      : " + outtable );
326         out.flush();
327         out.println( rio.getLog().toString() );
328         out.close();
329         ForesterUtil.programMessage( PRG_NAME, "wrote log to \"" + logfile + "\"" );
330     }
331
332     private static void writeTable( final File table_outfile, final RIO rio, final IntMatrix m ) throws IOException {
333         final EasyWriter w = ForesterUtil.createEasyWriter( table_outfile );
334         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.###" );
335         df.setDecimalSeparatorAlwaysShown( false );
336         for( int i = 0; i < m.size(); ++i ) {
337             w.print( "\t" );
338             w.print( m.getLabel( i ) );
339         }
340         w.println();
341         for( int x = 0; x < m.size(); ++x ) {
342             w.print( m.getLabel( x ) );
343             for( int y = 0; y < m.size(); ++y ) {
344                 w.print( "\t" );
345                 if ( x == y ) {
346                     if ( m.get( x, y ) != rio.getAnalyzedGeneTrees().length ) {
347                         ForesterUtil.unexpectedFatalError( PRG_NAME, "diagonal value is off" );
348                     }
349                     w.print( "-" );
350                 }
351                 else {
352                     w.print( df.format( ( ( double ) m.get( x, y ) ) / rio.getAnalyzedGeneTrees().length ) );
353                 }
354             }
355             w.println();
356         }
357         w.close();
358         ForesterUtil.programMessage( PRG_NAME, "wrote table to \"" + table_outfile + "\"" );
359     }
360 }