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