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 ) || ( cla.getNumberOfNames() < 3 ) ) {
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             System.out.println( "Transfer taxonomic data   : " + transfer_taxonomy );
291         }
292         time = System.currentTimeMillis();
293         final ALGORITHM algorithm;
294         if ( sdir ) {
295             algorithm = ALGORITHM.SDIR;
296         }
297         else {
298             algorithm = ALGORITHM.GSDIR;
299         }
300         try {
301             final RIO rio;
302             boolean iterating = false;
303             final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
304             if ( p instanceof PhyloXmlParser ) {
305                 rio = RIO.executeAnalysis( gene_trees_file,
306                                            species_tree_file,
307                                            algorithm,
308                                            rerooting,
309                                            outgroup,
310                                            gt_first,
311                                            gt_last,
312                                            logfile != null,
313                                            true,
314                                            transfer_taxonomy );
315             }
316             else {
317                 iterating = true;
318                 if ( p instanceof NHXParser ) {
319                     final NHXParser nhx = ( NHXParser ) p;
320                     nhx.setReplaceUnderscores( false );
321                     nhx.setIgnoreQuotes( true );
322                     nhx.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGRESSIVE );
323                 }
324                 else if ( p instanceof NexusPhylogeniesParser ) {
325                     final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) p;
326                     nex.setReplaceUnderscores( false );
327                     nex.setIgnoreQuotes( true );
328                     nex.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGRESSIVE );
329                 }
330                 else {
331                     throw new RuntimeException( "unknown parser type: " + p );
332                 }
333                 final IteratingPhylogenyParser ip = ( IteratingPhylogenyParser ) p;
334                 ip.setSource( gene_trees_file );
335                 rio = RIO.executeAnalysis( ip,
336                                            species_tree_file,
337                                            algorithm,
338                                            rerooting,
339                                            outgroup,
340                                            gt_first,
341                                            gt_last,
342                                            logfile != null,
343                                            true,
344                                            transfer_taxonomy );
345             }
346             if ( algorithm == ALGORITHM.GSDIR ) {
347                 System.out.println( "Taxonomy linking based on : " + rio.getGSDIRtaxCompBase() );
348             }
349             final IntMatrix m;
350             if ( iterating ) {
351                 m = rio.getOrthologTable();
352             }
353             else {
354                 m = RIO.calculateOrthologTable( rio.getAnalyzedGeneTrees(), true );
355             }
356             final BasicDescriptiveStatistics stats = rio.getDuplicationsStatistics();
357             writeTable( orthology_outtable, stats.getN(), m );
358             if ( ( algorithm != ALGORITHM.SDIR ) && ( logfile != null ) ) {
359                 writeLogFile( logfile,
360                               rio,
361                               species_tree_file,
362                               gene_trees_file,
363                               orthology_outtable,
364                               PRG_NAME,
365                               PRG_VERSION,
366                               PRG_DATE,
367                               ForesterUtil.getForesterLibraryInformation() );
368             }
369             if ( return_species_tree != null ) {
370                 writeTree( rio.getSpeciesTree(), return_species_tree, "Wrote (stripped) species tree to" );
371             }
372             if ( return_gene_tree != null ) {
373                 String tt = "";
374                 if ( transfer_taxonomy ) {
375                     tt = "(with transferred taxonomic data) ";
376                 }
377                 writeTree( rio.getMinDuplicationsGeneTree(),
378                            return_gene_tree,
379                            "Wrote (one) minimal duplication gene tree " + tt + "to" );
380             }
381             final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#" );
382             System.out.println( "Mean number of duplications  : " + df.format( stats.arithmeticMean() ) + " (sd: "
383                     + df.format( stats.sampleStandardDeviation() ) + ") ("
384                     + df.format( 100.0 * stats.arithmeticMean() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
385             if ( stats.getN() > 3 ) {
386                 System.out.println( "Median number of duplications: " + df.format( stats.median() ) + " ("
387                         + df.format( 100.0 * stats.median() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
388             }
389             System.out.println( "Minimum duplications         : " + ( int ) stats.getMin() + " ("
390                     + df.format( 100.0 * stats.getMin() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
391             System.out.println( "Maximum duplications         : " + ( int ) stats.getMax() + " ("
392                     + df.format( 100.0 * stats.getMax() / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
393             System.out.println( "Gene tree internal nodes     : " + rio.getIntNodesOfAnalyzedGeneTrees() );
394             System.out.println( "Gene tree external nodes     : " + rio.getExtNodesOfAnalyzedGeneTrees() );
395         }
396         catch ( final RIOException e ) {
397             ForesterUtil.fatalError( e.getLocalizedMessage() );
398         }
399         catch ( final SDIException e ) {
400             ForesterUtil.fatalError( e.getLocalizedMessage() );
401         }
402         catch ( final IOException e ) {
403             ForesterUtil.fatalError( e.getLocalizedMessage() );
404         }
405         catch ( final OutOfMemoryError e ) {
406             ForesterUtil.outOfMemoryError( e );
407         }
408         catch ( final Exception e ) {
409             ForesterUtil.unexpectedFatalError( e );
410         }
411         catch ( final Error e ) {
412             ForesterUtil.unexpectedFatalError( e );
413         }
414         time = System.currentTimeMillis() - time;
415         System.out.println( "Time: " + time + "ms" );
416         System.out.println( "OK" );
417         System.exit( 0 );
418     }
419
420     private final static void printHelp() {
421         System.out.println( "Usage" );
422         System.out.println();
423         System.out
424                 .println( PRG_NAME
425                         + " [options] <gene trees infile> <species tree infile> <all vs all orthology table outfile> [logfile]" );
426         System.out.println();
427         System.out.println( " Options" );
428         System.out.println( "  -" + GT_FIRST + "=<first>     : first gene tree to analyze (0-based index)" );
429         System.out.println( "  -" + GT_LAST + "=<last>      : last gene tree to analyze (0-based index)" );
430         System.out.println( "  -" + REROOTING_OPT
431                 + "=<re-rooting>: re-rooting method for gene trees, possible values or 'none', 'midpoint'," );
432         System.out.println( "                   or 'outgroup' (default: by minizming duplications)" );
433         System.out.println( "  -" + OUTGROUP
434                 + "=<outgroup>  : for rooting by outgroup, name of outgroup (external gene tree node)" );
435         System.out
436                 .println( "  -" + RETURN_SPECIES_TREE + "=<outfile>   : to write the (stripped) species tree to file" );
437         System.out.println( "  -" + RETURN_BEST_GENE_TREE
438                 + "=<outfile>   : to write (one) minimal duplication gene tree to file" );
439         System.out
440                 .println( "  -"
441                         + TRANSFER_TAXONOMY_OPTION
442                         + "             : to transfer taxonomic data from species tree to returned minimal duplication gene tree\n"
443                         + "                   (if -" + RETURN_BEST_GENE_TREE + " option is used)" );
444         System.out.println( "  -" + USE_SDIR
445                 + "             : to use SDIR instead of GSDIR (faster, but non-binary species trees are" );
446         System.out.println( "                   disallowed, as are most options)" );
447         System.out.println();
448         System.out.println( " Formats" );
449         System.out
450                 .println( "  The gene trees, as well as the species tree, ideally are in phyloXML (www.phyloxml.org) format," );
451         System.out
452                 .println( "  but can also be in New Hamphshire (Newick) or Nexus format as long as species information can be" );
453         System.out
454                 .println( "  extracted from the gene names (e.g. \"HUMAN\" from \"BCL2_HUMAN\") and matched to a single species" );
455         System.out.println( "  in the species tree." );
456         System.out.println();
457         System.out.println( " Examples" );
458         System.out.println( "  \"rio gene_trees.nh species.xml outtable.tsv log.txt\"" );
459         System.out.println();
460         System.out.println( " More information: http://code.google.com/p/forester/wiki/RIO" );
461         System.out.println();
462         System.exit( -1 );
463     }
464
465     private static void writeLogFile( final File logfile,
466                                       final RIO rio,
467                                       final File species_tree_file,
468                                       final File gene_trees_file,
469                                       final File outtable,
470                                       final String prg_name,
471                                       final String prg_v,
472                                       final String prg_date,
473                                       final String f ) throws IOException {
474         final EasyWriter out = ForesterUtil.createEasyWriter( logfile );
475         out.println( prg_name );
476         out.println( "version : " + prg_v );
477         out.println( "date    : " + prg_date );
478         out.println( "based on: " + f );
479         out.println( "----------------------------------" );
480         out.println( "Gene trees                                      : " + gene_trees_file );
481         out.println( "Species tree                                    : " + species_tree_file );
482         out.println( "All vs all orthology table                      : " + outtable );
483         out.flush();
484         out.println( rio.getLog().toString() );
485         out.close();
486         System.out.println( "Wrote log to \"" + logfile + "\"" );
487     }
488
489     private static void writeTable( final File table_outfile, final int gene_trees_analyzed, final IntMatrix m )
490             throws IOException {
491         final EasyWriter w = ForesterUtil.createEasyWriter( table_outfile );
492         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.###" );
493         df.setDecimalSeparatorAlwaysShown( false );
494         for( int i = 0; i < m.size(); ++i ) {
495             w.print( "\t" );
496             w.print( m.getLabel( i ) );
497         }
498         w.println();
499         for( int x = 0; x < m.size(); ++x ) {
500             w.print( m.getLabel( x ) );
501             for( int y = 0; y < m.size(); ++y ) {
502                 w.print( "\t" );
503                 if ( x == y ) {
504                     if ( m.get( x, y ) != gene_trees_analyzed ) {
505                         ForesterUtil.unexpectedFatalError( "diagonal value is off" );
506                     }
507                     w.print( "-" );
508                 }
509                 else {
510                     w.print( df.format( ( ( double ) m.get( x, y ) ) / gene_trees_analyzed ) );
511                 }
512             }
513             w.println();
514         }
515         w.close();
516         System.out.println( "Wrote table to \"" + table_outfile + "\"" );
517     }
518
519     private static void writeTree( final Phylogeny p, final File f, final String comment ) throws IOException {
520         final PhylogenyWriter writer = new PhylogenyWriter();
521         writer.toPhyloXML( f, p, 0 );
522         System.out.println( comment + " \"" + f + "\"" );
523     }
524 }