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