94e6f5c63090f043436c4b21d794c766410957f2
[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: www.phylosoft.org/forester
27
28 package org.forester.application;
29
30 import java.io.File;
31 import java.io.FileWriter;
32 import java.io.IOException;
33 import java.io.PrintWriter;
34 import java.util.ArrayList;
35 import java.util.List;
36
37 import org.forester.datastructures.IntMatrix;
38 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
39 import org.forester.phylogeny.Phylogeny;
40 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
41 import org.forester.phylogeny.factories.PhylogenyFactory;
42 import org.forester.sdi.RIO;
43 import org.forester.util.CommandLineArguments;
44 import org.forester.util.EasyWriter;
45 import org.forester.util.ForesterUtil;
46
47 public class rio {
48
49     final static private String PRG_NAME              = "rio";
50     final static private String PRG_VERSION           = "3.00 beta 2";
51     final static private String PRG_DATE              = "2012.11.30";
52     final static private String E_MAIL                = "czmasek@burnham.org";
53     final static private String WWW                   = "www.phylosoft.org/forester/";
54     final static private String HELP_OPTION_1         = "help";
55     final static private String HELP_OPTION_2         = "h";
56     final static private String QUERY_OPTION          = "q";
57     final static private String SORT_OPTION           = "s";
58     final static private String OUTPUT_ULTRA_P_OPTION = "u";
59     final static private String CUTOFF_ULTRA_P_OPTION = "cu";
60     final static private String CUTOFF_ORTHO_OPTION   = "co";
61     final static private String TABLE_OUTPUT_OPTION   = "t";
62
63     public static void main( final String[] args ) {
64         ForesterUtil.printProgramInformation( PRG_NAME,
65                                               "resampled inference of orthologs",
66                                               PRG_VERSION,
67                                               PRG_DATE,
68                                               E_MAIL,
69                                               WWW,
70                                               ForesterUtil.getForesterLibraryInformation() );
71         CommandLineArguments cla = null;
72         try {
73             cla = new CommandLineArguments( args );
74         }
75         catch ( final Exception e ) {
76             ForesterUtil.fatalError( PRG_NAME, e.getMessage() );
77         }
78         if ( cla.isOptionSet( HELP_OPTION_1 ) || cla.isOptionSet( HELP_OPTION_2 ) || ( args.length == 0 ) ) {
79             printHelp();
80         }
81         if ( ( args.length < 2 ) || ( args.length > 10 ) ) {
82             System.out.println();
83             System.out.println( "[" + PRG_NAME + "] incorrect number of arguments" );
84             System.out.println();
85             printHelp();
86         }
87         final List<String> allowed_options = new ArrayList<String>();
88         allowed_options.add( QUERY_OPTION );
89         allowed_options.add( SORT_OPTION );
90         allowed_options.add( CUTOFF_ULTRA_P_OPTION );
91         allowed_options.add( CUTOFF_ORTHO_OPTION );
92         allowed_options.add( TABLE_OUTPUT_OPTION );
93         allowed_options.add( OUTPUT_ULTRA_P_OPTION );
94         final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
95         if ( dissallowed_options.length() > 0 ) {
96             ForesterUtil.fatalError( PRG_NAME, "unknown option(s): " + dissallowed_options );
97         }
98         final File gene_trees_file = cla.getFile( 0 );
99         final File species_tree_file = cla.getFile( 1 );
100         File outfile = null;
101         if ( cla.getNumberOfNames() > 2 ) {
102             outfile = cla.getFile( 2 );
103         }
104         ForesterUtil.fatalErrorIfFileNotReadable( PRG_NAME, gene_trees_file );
105         ForesterUtil.fatalErrorIfFileNotReadable( PRG_NAME, species_tree_file );
106         if ( ( outfile != null ) && outfile.exists() ) {
107             ForesterUtil.fatalError( PRG_NAME, "[" + outfile + "] already exists" );
108         }
109         String query = null;
110         if ( cla.isOptionSet( QUERY_OPTION ) ) {
111             query = cla.getOptionValue( QUERY_OPTION );
112         }
113         File table_outfile = null;
114         if ( cla.isOptionSet( TABLE_OUTPUT_OPTION ) ) {
115             table_outfile = new File( cla.getOptionValue( TABLE_OUTPUT_OPTION ) );
116             if ( table_outfile.exists() ) {
117                 ForesterUtil.fatalError( PRG_NAME, "[" + table_outfile + "] already exists" );
118             }
119         }
120         boolean output_ultraparalogs = false;
121         if ( cla.isOptionSet( OUTPUT_ULTRA_P_OPTION ) ) {
122             output_ultraparalogs = true;
123         }
124         double cutoff_for_orthologs = 50;
125         double cutoff_for_ultra_paralogs = 50;
126         int sort = 1;
127         try {
128             if ( cla.isOptionSet( CUTOFF_ORTHO_OPTION ) ) {
129                 cutoff_for_orthologs = cla.getOptionValueAsDouble( CUTOFF_ORTHO_OPTION );
130                 if ( query == null ) {
131                     ForesterUtil.fatalError( PRG_NAME, "missing query name, type \"rio -h\" for help" );
132                 }
133                 if ( outfile == null ) {
134                     ForesterUtil.fatalError( PRG_NAME, "missing outfile, type \"rio -h\" for help" );
135                 }
136             }
137             if ( cla.isOptionSet( CUTOFF_ULTRA_P_OPTION ) ) {
138                 cutoff_for_ultra_paralogs = cla.getOptionValueAsDouble( CUTOFF_ULTRA_P_OPTION );
139                 output_ultraparalogs = true;
140             }
141             if ( cla.isOptionSet( SORT_OPTION ) ) {
142                 sort = cla.getOptionValueAsInt( SORT_OPTION );
143             }
144         }
145         catch ( final Exception e ) {
146             ForesterUtil.fatalError( PRG_NAME, "error in command line: " + e.getLocalizedMessage() );
147         }
148         if ( ( cutoff_for_orthologs < 0 ) || ( cutoff_for_ultra_paralogs < 0 ) || ( sort < 0 ) || ( sort > 2 ) ) {
149             ForesterUtil.fatalError( PRG_NAME, "numberical option out of range, type \"rio -h\" for help" );
150         }
151         if ( ( ( query == null ) && ( ( outfile != null ) || output_ultraparalogs ) ) ) {
152             ForesterUtil.fatalError( PRG_NAME, "missing query name, type \"rio -h\" for help" );
153         }
154         if ( ( output_ultraparalogs && ( outfile == null ) ) || ( ( query != null ) && ( outfile == null ) ) ) {
155             ForesterUtil.fatalError( PRG_NAME, "missing outfile, type \"rio -h\" for help" );
156         }
157         long time = 0;
158         System.out.println( "Gene trees                : " + gene_trees_file );
159         System.out.println( "Species tree              : " + species_tree_file );
160         if ( query != null ) {
161             System.out.println( "Query                     : " + query );
162             System.out.println( "Outfile                   : " + outfile );
163             System.out.println( "Sort                      : " + sort );
164             System.out.println( "Cutoff for  orthologs     : " + cutoff_for_orthologs );
165             if ( output_ultraparalogs ) {
166                 System.out.println( "Cutoff for ultra paralogs : " + cutoff_for_ultra_paralogs );
167             }
168         }
169         if ( table_outfile != null ) {
170             System.out.println( "Table output              : " + table_outfile );
171         }
172         System.out.println();
173         time = System.currentTimeMillis();
174         Phylogeny species_tree = null;
175         try {
176             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
177             species_tree = factory.create( species_tree_file, new PhyloXmlParser() )[ 0 ];
178         }
179         catch ( final Exception e ) {
180             e.printStackTrace();
181             System.exit( -1 );
182         }
183         if ( !species_tree.isRooted() ) {
184             ForesterUtil.fatalError( PRG_NAME, "species tree is not rooted" );
185         }
186         if ( !species_tree.isCompletelyBinary() ) {
187             ForesterUtil.fatalError( PRG_NAME, "species tree is not completely binary" );
188         }
189         try {
190             RIO rio;
191             if ( ForesterUtil.isEmpty( query ) ) {
192                 rio = new RIO( gene_trees_file, species_tree );
193             }
194             else {
195                 rio = new RIO( gene_trees_file, species_tree, query );
196             }
197             if ( outfile != null ) {
198                 final StringBuilder output = new StringBuilder();
199                 output.append( rio.inferredOrthologsToString( query, sort, cutoff_for_orthologs ) );
200                 if ( output_ultraparalogs ) {
201                     output.append( "\n\nUltra paralogs:\n" );
202                     output.append( rio.inferredUltraParalogsToString( query, cutoff_for_ultra_paralogs ) );
203                 }
204                 output.append( "\n\nSort priority: " + RIO.getOrder( sort ) );
205                 output.append( "\nExt nodes    : " + rio.getExtNodesOfAnalyzedGeneTrees() );
206                 output.append( "\nSamples      : " + rio.getNumberOfSamples() + "\n" );
207                 final PrintWriter out = new PrintWriter( new FileWriter( outfile ), true );
208                 out.println( output );
209                 out.close();
210             }
211             if ( table_outfile != null ) {
212                 tableOutput( table_outfile, rio );
213             }
214         }
215         catch ( final IllegalArgumentException e ) {
216             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
217         }
218         catch ( final Exception e ) {
219             ForesterUtil.printErrorMessage( PRG_NAME, e.getLocalizedMessage() );
220             e.printStackTrace();
221             System.exit( -1 );
222         }
223         if ( outfile != null ) {
224             ForesterUtil.programMessage( PRG_NAME, "wrote results to \"" + outfile + "\"" );
225         }
226         time = System.currentTimeMillis() - time;
227         ForesterUtil.programMessage( PRG_NAME, "time: " + time + "ms" );
228         ForesterUtil.programMessage( PRG_NAME, "OK" );
229         System.exit( 0 );
230     }
231
232     private static void tableOutput( final File table_outfile, final RIO rio ) throws IOException {
233         final IntMatrix m = RIO.calculateOrthologTable( rio.getAnalyzedGeneTrees() );
234         writeTable( table_outfile, rio, m );
235     }
236
237     private static void writeTable( final File table_outfile, final RIO rio, final IntMatrix m ) throws IOException {
238         final EasyWriter w = ForesterUtil.createEasyWriter( table_outfile );
239         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.###" );
240         df.setDecimalSeparatorAlwaysShown( false );
241         w.print( "\t" );
242         for( int i = 0; i < m.size(); ++i ) {
243             w.print( "\t" );
244             w.print( m.getLabel( i ) );
245         }
246         w.println();
247         for( int x = 0; x < m.size(); ++x ) {
248             w.print( m.getLabel( x ) );
249             w.print( "\t" );
250             for( int y = 0; y < m.size(); ++y ) {
251                 w.print( "\t" );
252                 if ( x == y ) {
253                     if ( m.get( x, y ) != rio.getNumberOfSamples() ) {
254                         ForesterUtil.unexpectedFatalError( PRG_NAME, "diagonal value is off" );
255                     }
256                     w.print( "-" );
257                 }
258                 else {
259                     w.print( df.format( ( ( double ) m.get( x, y ) ) / rio.getNumberOfSamples() ) );
260                 }
261             }
262             w.println();
263         }
264         w.close();
265         ForesterUtil.programMessage( PRG_NAME, "wrote table to \"" + table_outfile + "\"" );
266     }
267
268     private final static void printHelp() {
269         System.out.println( "Usage" );
270         System.out.println();
271         System.out.println( PRG_NAME + " [options] <gene trees file> <species tree file> [outfile]" );
272         System.out.println();
273         System.out.println( " Options" );
274         System.out.println( "  -" + CUTOFF_ORTHO_OPTION + " : cutoff for ortholog output (default: 50)" );
275         System.out.println( "  -" + TABLE_OUTPUT_OPTION
276                 + "  : file-name for output table of all vs. all ortholgy support" );
277         System.out.println( "  -" + QUERY_OPTION
278                 + "  : name for query (sequence/node), if this is used, [outfile] is required as well" );
279         System.out.println( "  -" + SORT_OPTION + "  : sort (default: 1)" );
280         System.out.println( "  -" + OUTPUT_ULTRA_P_OPTION
281                 + "  : to output ultra-paralogs (species specific expansions/paralogs)" );
282         System.out.println( "  -" + CUTOFF_ULTRA_P_OPTION + " : cutoff for ultra-paralog output (default: 50)" );
283         System.out.println();
284         System.out.println( " Note" );
285         System.out.println( "  Either output of all vs. all ortholgy support with -t=<output table> and/or output for" );
286         System.out.println( "  one query sequence with -q=<query name> and a [outfile] are required." );
287         System.out.println();
288         System.out.println( " Sort" );
289         System.out.println( RIO.getOrderHelp().toString() );
290         System.out.println( " Formats" );
291         System.out.println( "  The species tree is expected to be in phyloXML format." );
292         System.out
293                 .println( "  The gene trees ideally are in phyloXML as well, but can also be in New Hamphshire (Newick)" );
294         System.out.println( "  or Nexus format as long as species information can be extracted from the gene names" );
295         System.out.println( "  (e.g. \"HUMAN\" from \"BCL2_HUMAN\")." );
296         System.out.println();
297         System.out.println( " Examples" );
298         System.out.println( "  \"rio gene_trees.nh species.xml outfile -q=BCL2_HUMAN -t=outtable -u -cu=60 -co=60\"" );
299         System.out.println( "  \"rio gene_trees.nh species.xml -t=outtable\"" );
300         System.out.println();
301         System.out.println( " More information: http://code.google.com/p/forester/wiki/RIO" );
302         System.out.println();
303         System.exit( -1 );
304     }
305 }