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