8af048644de65dc41f875f821d42e16d2e352fe3
[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.IOException;
32 import java.util.ArrayList;
33 import java.util.List;
34 import java.util.SortedSet;
35 import java.util.TreeSet;
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.PhylogenyNode;
41 import org.forester.phylogeny.data.Taxonomy;
42 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
43 import org.forester.phylogeny.factories.PhylogenyFactory;
44 import org.forester.rio.RIO;
45 import org.forester.rio.RIOException;
46 import org.forester.rio.RIO.REROOTING;
47 import org.forester.sdi.SDIException;
48 import org.forester.sdi.SDIutil.ALGORITHM;
49 import org.forester.util.BasicDescriptiveStatistics;
50 import org.forester.util.CommandLineArguments;
51 import org.forester.util.EasyWriter;
52 import org.forester.util.ForesterUtil;
53
54 public class rio {
55
56     final static private String PRG_NAME      = "rio";
57     final static private String PRG_VERSION   = "4.000 beta 2";
58     final static private String PRG_DATE      = "2012.12.14";
59     final static private String E_MAIL        = "czmasek@burnham.org";
60     final static private String WWW           = "www.phylosoft.org/forester/";
61     final static private String HELP_OPTION_1 = "help";
62     final static private String HELP_OPTION_2 = "h";
63     final static private String USE_SDIR      = "b";
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 < 3 ) || ( args.length > 5 ) ) {
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( USE_SDIR );
91         final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
92         if ( dissallowed_options.length() > 0 ) {
93             ForesterUtil.fatalError( PRG_NAME, "unknown option(s): " + dissallowed_options );
94         }
95         final File gene_trees_file = cla.getFile( 0 );
96         final File species_tree_file = cla.getFile( 1 );
97         final File othology_outtable = cla.getFile( 2 );
98         final File logfile;
99         if ( cla.getNumberOfNames() > 3 ) {
100             logfile = cla.getFile( 3 );
101             if ( logfile.exists() ) {
102                 ForesterUtil.fatalError( PRG_NAME, "\"" + logfile + "\" already exists" );
103             }
104         }
105         else {
106             logfile = null;
107         }
108         String outgroup = "";
109         ForesterUtil.fatalErrorIfFileNotReadable( PRG_NAME, gene_trees_file );
110         ForesterUtil.fatalErrorIfFileNotReadable( PRG_NAME, species_tree_file );
111         if ( othology_outtable.exists() ) {
112             ForesterUtil.fatalError( PRG_NAME, "\"" + othology_outtable + "\" already exists" );
113         }
114         boolean sdir = false;
115         if ( cla.isOptionSet( USE_SDIR ) ) {
116             sdir = true;
117             if ( logfile != null ) {
118                 ForesterUtil.fatalError( PRG_NAME, "logfile output only for GSDIR algorithm" );
119             }
120         }
121         long time = 0;
122         System.out.println( "Gene trees                : " + gene_trees_file );
123         System.out.println( "Species tree              : " + species_tree_file );
124         System.out.println( "All vs all orthology table: " + othology_outtable );
125         if ( !sdir ) {
126             if ( logfile != null ) {
127                 System.out.println( "Logfile                   : " + logfile );
128             }
129             System.out.println( "Non binary species tree   : allowed (GSDIR algorithm)" );
130         }
131         else {
132             System.out.println( "Non binary species tree   : disallowed (SDIR algorithm)" );
133         }
134         time = System.currentTimeMillis();
135         Phylogeny species_tree = null;
136         try {
137             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
138             species_tree = factory.create( species_tree_file, new PhyloXmlParser() )[ 0 ];
139         }
140         catch ( final Exception e ) {
141             e.printStackTrace();
142             System.exit( -1 );
143         }
144         if ( !species_tree.isRooted() ) {
145             ForesterUtil.fatalError( PRG_NAME, "species tree is not rooted" );
146         }
147         final ALGORITHM algorithm;
148         if ( sdir ) {
149             algorithm = ALGORITHM.SDIR;
150         }
151         else {
152             algorithm = ALGORITHM.GSDIR;
153         }
154         try {
155             final RIO rio = new RIO( gene_trees_file, species_tree, algorithm, REROOTING.BY_ALGORITHM, outgroup ,  logfile != null, true );
156             if ( algorithm == ALGORITHM.GSDIR ) {
157                 ForesterUtil.programMessage( PRG_NAME, "taxonomy linking based on: " + rio.getGSDIRtaxCompBase() );
158             }
159             tableOutput( othology_outtable, rio );
160             if ( ( algorithm == ALGORITHM.GSDIR ) && ( logfile != null ) ) {
161                 writeLogFile( logfile, rio );
162             }
163             final BasicDescriptiveStatistics stats = rio.getDuplicationsStatistics();
164             ForesterUtil.programMessage( PRG_NAME, "Mean: " + stats.arithmeticMean() + "("  + stats.sampleStandardDeviation() + ")" );
165             ForesterUtil.programMessage( PRG_NAME, "Min: " + (int) stats.getMin() );
166             ForesterUtil.programMessage( PRG_NAME, "Max: " + (int) stats.getMax() );
167             
168         }
169         catch ( final RIOException e ) {
170             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
171         }
172         catch ( final SDIException e ) {
173             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
174         }
175         catch ( final IOException e ) {
176             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
177         }
178         catch ( final Exception e ) {
179             ForesterUtil.unexpectedFatalError( PRG_NAME, e );
180         }
181       
182         time = System.currentTimeMillis() - time;
183         ForesterUtil.programMessage( PRG_NAME, "time: " + time + "ms" );
184         ForesterUtil.programMessage( PRG_NAME, "OK" );
185         System.exit( 0 );
186     }
187
188     private static void writeLogFile( final File logfile, final RIO rio ) throws IOException {
189         final EasyWriter out = ForesterUtil.createEasyWriter( logfile );
190         out.println( "Species stripped from gene trees:" );
191         final SortedSet<String> rn = new TreeSet<String>();
192         for( final PhylogenyNode n : rio.getRemovedGeneTreeNodes() ) {
193             final Taxonomy t = n.getNodeData().getTaxonomy();
194             switch ( rio.getGSDIRtaxCompBase() ) {
195                 case CODE: {
196                     rn.add( t.getTaxonomyCode() );
197                     break;
198                 }
199                 case ID: {
200                     rn.add( t.getIdentifier().toString() );
201                     break;
202                 }
203                 case SCIENTIFIC_NAME: {
204                     rn.add( t.getScientificName() );
205                     break;
206                 }
207             }
208         }
209         for( final String s : rn ) {
210             out.println( s );
211         }
212         out.println();
213         out.println( "Some information about duplication numbers in gene trees:" );
214         out.println( rio.getLog().toString() );
215         out.close();
216         ForesterUtil.programMessage( PRG_NAME, "wrote log to \"" + logfile + "\"" );
217     }
218
219     private static void tableOutput( final File table_outfile, final RIO rio ) throws IOException, RIOException {
220         final IntMatrix m = RIO.calculateOrthologTable( rio.getAnalyzedGeneTrees(), true );
221         writeTable( table_outfile, rio, m );
222     }
223
224     private static void writeTable( final File table_outfile, final RIO rio, final IntMatrix m ) throws IOException {
225         final EasyWriter w = ForesterUtil.createEasyWriter( table_outfile );
226         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.###" );
227         df.setDecimalSeparatorAlwaysShown( false );
228         for( int i = 0; i < m.size(); ++i ) {
229             w.print( "\t" );
230             w.print( m.getLabel( i ) );
231         }
232         w.println();
233         for( int x = 0; x < m.size(); ++x ) {
234             w.print( m.getLabel( x ) );
235             for( int y = 0; y < m.size(); ++y ) {
236                 w.print( "\t" );
237                 if ( x == y ) {
238                     if ( m.get( x, y ) != rio.getAnalyzedGeneTrees().length ) {
239                         ForesterUtil.unexpectedFatalError( PRG_NAME, "diagonal value is off" );
240                     }
241                     w.print( "-" );
242                 }
243                 else {
244                     w.print( df.format( ( ( double ) m.get( x, y ) ) / rio.getAnalyzedGeneTrees().length ) );
245                 }
246             }
247             w.println();
248         }
249         w.close();
250         ForesterUtil.programMessage( PRG_NAME, "wrote table to \"" + table_outfile + "\"" );
251     }
252
253     private final static void printHelp() {
254         System.out.println( "Usage" );
255         System.out.println();
256         System.out
257                 .println( PRG_NAME
258                         + " [options] <gene trees infile> <species tree infile> <all vs all orthology table outfile> [logfile]" );
259         System.out.println();
260         System.out.println( " Options" );
261         System.out.println( "  -" + USE_SDIR
262                 + " : to use SDIR instead of GSDIR (faster, but non-binary species trees are disallowed)" );
263         System.out.println();
264         System.out.println( " Formats" );
265         System.out.println( "  The species tree is expected to be in phyloXML format." );
266         System.out
267                 .println( "  The gene trees ideally are in phyloXML as well, but can also be in New Hamphshire (Newick)" );
268         System.out.println( "  or Nexus format as long as species information can be extracted from the gene names" );
269         System.out.println( "  (e.g. \"HUMAN\" from \"BCL2_HUMAN\")." );
270         System.out.println();
271         System.out.println( " Examples" );
272         System.out.println( "  \"rio gene_trees.nh species.xml outtable.tsv log.txt\"" );
273         System.out.println();
274         System.out.println( " More information: http://code.google.com/p/forester/wiki/RIO" );
275         System.out.println();
276         System.exit( -1 );
277     }
278 }