iterating rio + cleanup
[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 4";
51     final static private String  PRG_DATE      = "2012.12.25";
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         //        Phylogeny species_tree = null;
245         //        try {
246         //            final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
247         //            species_tree = factory.create( species_tree_file, new PhyloXmlParser() )[ 0 ];
248         //        }
249         //        catch ( final Exception e ) {
250         //            e.printStackTrace();
251         //            System.exit( -1 );
252         //        }
253         final ALGORITHM algorithm;
254         if ( sdir ) {
255             algorithm = ALGORITHM.SDIR;
256         }
257         else {
258             algorithm = ALGORITHM.GSDIR;
259         }
260         try {
261             final RIO rio;
262             if ( ITERATING ) {
263                 final NHXParser p = new NHXParser();
264                 p.setReplaceUnderscores( false );
265                 p.setIgnoreQuotes( true );
266                 p.setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.YES );
267                 p.setSource( gene_trees_file );
268                 rio = RIO.executeAnalysis( p,
269                                            species_tree_file,
270                                            algorithm,
271                                            rerooting,
272                                            outgroup,
273                                            gt_first,
274                                            gt_last,
275                                            logfile != null,
276                                            true );
277             }
278             else {
279                 rio = RIO.executeAnalysis( gene_trees_file,
280                                            species_tree_file,
281                                            algorithm,
282                                            rerooting,
283                                            outgroup,
284                                            gt_first,
285                                            gt_last,
286                                            logfile != null,
287                                            true );
288             }
289             if ( algorithm == ALGORITHM.GSDIR ) {
290                 System.out.println( "Taxonomy linking based on : " + rio.getGSDIRtaxCompBase() );
291             }
292             final IntMatrix m;
293             if ( ITERATING ) {
294                 m = rio.getOrthologTable();
295             }
296             else {
297                 m = RIO.calculateOrthologTable( rio.getAnalyzedGeneTrees(), true );
298             }
299             final BasicDescriptiveStatistics stats = rio.getDuplicationsStatistics();
300             writeTable( orthology_outtable, stats.getN(), m );
301             if ( ( algorithm != ALGORITHM.SDIR ) && ( logfile != null ) ) {
302                 writeLogFile( logfile,
303                               rio,
304                               species_tree_file,
305                               gene_trees_file,
306                               orthology_outtable,
307                               PRG_NAME,
308                               PRG_VERSION,
309                               PRG_DATE,
310                               ForesterUtil.getForesterLibraryInformation() );
311             }
312             ;
313             final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#" );
314             System.out.println( "Mean number of duplications  : " + df.format( stats.arithmeticMean() ) + " (sd: "
315                     + df.format( stats.sampleStandardDeviation() ) + ") ("
316                     + df.format( 100.0 * stats.arithmeticMean() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
317             if ( stats.getN() > 3 ) {
318                 System.out.println( "Median number of duplications: " + df.format( stats.median() ) + " ("
319                         + df.format( 100.0 * stats.median() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
320             }
321             System.out.println( "Minimum duplications         : " + ( int ) stats.getMin() + " ("
322                     + df.format( 100.0 * stats.getMin() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
323             System.out.println( "Maximum duplications         : " + ( int ) stats.getMax() + " ("
324                     + df.format( 100.0 * stats.getMax() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
325             System.out.println( "Gene tree internal nodes     : " + rio.getIntNodesOfAnalyzedGeneTrees() );
326             System.out.println( "Gene tree external nodes     : " + rio.getExtNodesOfAnalyzedGeneTrees() );
327         }
328         catch ( final RIOException e ) {
329             ForesterUtil.fatalError( e.getLocalizedMessage() );
330         }
331         catch ( final SDIException e ) {
332             ForesterUtil.fatalError( e.getLocalizedMessage() );
333         }
334         catch ( final IOException e ) {
335             ForesterUtil.fatalError( e.getLocalizedMessage() );
336         }
337         catch ( final OutOfMemoryError e ) {
338             ForesterUtil.outOfMemoryError( e );
339         }
340         catch ( final Exception e ) {
341             ForesterUtil.unexpectedFatalError( e );
342         }
343         catch ( final Error e ) {
344             ForesterUtil.unexpectedFatalError( e );
345         }
346         time = System.currentTimeMillis() - time;
347         System.out.println( "Time: " + time + "ms" );
348         System.out.println( "OK" );
349         System.exit( 0 );
350     }
351
352     private final static void printHelp() {
353         System.out.println( "Usage" );
354         System.out.println();
355         System.out
356                 .println( PRG_NAME
357                         + " [options] <gene trees infile> <species tree infile> <all vs all orthology table outfile> [logfile]" );
358         System.out.println();
359         System.out.println( " Options" );
360         System.out.println( "  -" + GT_FIRST + "=<first>     : first gene tree to analyze (0-based index)" );
361         System.out.println( "  -" + GT_LAST + "=<last>      : last gene tree to analyze (0-based index)" );
362         System.out.println( "  -" + REROOTING_OPT
363                 + "=<re-rooting>: re-rooting method for gene trees, possible values or 'none', 'midpoint'," );
364         System.out.println( "                   or 'outgroup' (default: by minizming duplications)" );
365         System.out.println( "  -" + OUTGROUP
366                 + "=<outgroup>  : for rooting by outgroup, name of outgroup (external gene tree node)" );
367         System.out.println( "  -" + USE_SDIR
368                 + "             : to use SDIR instead of GSDIR (faster, but non-binary species trees are" );
369         System.out.println( "                   disallowed, as are most options)" );
370         System.out.println();
371         System.out.println( " Formats" );
372         System.out
373                 .println( "  The gene trees, as well as the species tree, ideally are in phyloXML (www.phyloxml.org) format," );
374         System.out
375                 .println( "  but can also be in New Hamphshire (Newick) or Nexus format as long as species information can be" );
376         System.out
377                 .println( "  extracted from the gene names (e.g. \"HUMAN\" from \"BCL2_HUMAN\") and matched to a single species" );
378         System.out.println( "  in the species tree." );
379         System.out.println();
380         System.out.println( " Examples" );
381         System.out.println( "  \"rio gene_trees.nh species.xml outtable.tsv log.txt\"" );
382         System.out.println();
383         System.out.println( " More information: http://code.google.com/p/forester/wiki/RIO" );
384         System.out.println();
385         System.exit( -1 );
386     }
387
388     private static void writeLogFile( final File logfile,
389                                       final RIO rio,
390                                       final File species_tree_file,
391                                       final File gene_trees_file,
392                                       final File outtable,
393                                       final String prg_name,
394                                       final String prg_v,
395                                       final String prg_date,
396                                       final String f ) throws IOException {
397         final EasyWriter out = ForesterUtil.createEasyWriter( logfile );
398         out.println( prg_name );
399         out.println( "version : " + prg_v );
400         out.println( "date    : " + prg_date );
401         out.println( "based on: " + f );
402         out.println( "----------------------------------" );
403         out.println( "Gene trees                                      : " + gene_trees_file );
404         out.println( "Species tree                                    : " + species_tree_file );
405         out.println( "All vs all orthology table                      : " + outtable );
406         out.flush();
407         out.println( rio.getLog().toString() );
408         out.close();
409         System.out.println( "Wrote log to \"" + logfile + "\"" );
410     }
411
412     private static void writeTable( final File table_outfile, final int gene_trees_analyzed, final IntMatrix m )
413             throws IOException {
414         final EasyWriter w = ForesterUtil.createEasyWriter( table_outfile );
415         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.###" );
416         df.setDecimalSeparatorAlwaysShown( false );
417         for( int i = 0; i < m.size(); ++i ) {
418             w.print( "\t" );
419             w.print( m.getLabel( i ) );
420         }
421         w.println();
422         for( int x = 0; x < m.size(); ++x ) {
423             w.print( m.getLabel( x ) );
424             for( int y = 0; y < m.size(); ++y ) {
425                 w.print( "\t" );
426                 if ( x == y ) {
427                     if ( m.get( x, y ) != gene_trees_analyzed ) {
428                         ForesterUtil.unexpectedFatalError( "diagonal value is off" );
429                     }
430                     w.print( "-" );
431                 }
432                 else {
433                     w.print( df.format( ( ( double ) m.get( x, y ) ) / gene_trees_analyzed ) );
434                 }
435             }
436             w.println();
437         }
438         w.close();
439         System.out.println( "Wrote table to \"" + table_outfile + "\"" );
440     }
441 }