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