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