3df2a743afa1fbed90ec3fde0e9fbb86c0e00972
[jalview.git] / forester / java / src / org / forester / application / gsdi.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 // All rights reserved
8 //
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
13 //
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
18 //
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.application;
27
28 import java.io.File;
29 import java.io.IOException;
30 import java.io.Writer;
31 import java.text.SimpleDateFormat;
32 import java.util.ArrayList;
33 import java.util.Date;
34 import java.util.List;
35
36 import org.forester.io.parsers.PhylogenyParser;
37 import org.forester.io.parsers.nhx.NHXParser;
38 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
39 import org.forester.io.parsers.util.ParserUtils;
40 import org.forester.io.writers.PhylogenyWriter;
41 import org.forester.phylogeny.Phylogeny;
42 import org.forester.phylogeny.PhylogenyMethods;
43 import org.forester.phylogeny.PhylogenyNode;
44 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
45 import org.forester.phylogeny.factories.PhylogenyFactory;
46 import org.forester.sdi.GSDI;
47 import org.forester.sdi.SDI;
48 import org.forester.sdi.SDI.TaxonomyComparisonBase;
49 import org.forester.sdi.SDIse;
50 import org.forester.sdi.SdiException;
51 import org.forester.util.CommandLineArguments;
52 import org.forester.util.ForesterConstants;
53 import org.forester.util.ForesterUtil;
54
55 public final class gsdi {
56
57     private enum BASE_ALGORITHM {
58         GSDI, SDI
59     }
60     final static public boolean REPLACE_UNDERSCORES_IN_NH_SPECIES_TREE     = true;
61     final static private String STRIP_OPTION                               = "s";
62     final static private String ALLOW_STRIPPING_OF_GENE_TREE_OPTION        = "g";
63     final static private String SDI_OPTION                                 = "b";
64     final static private String MOST_PARSIMONIOUS_OPTION                   = "m";
65     final static private String GUESS_FORMAT_OF_SPECIES_TREE               = "q";
66     final static private String HELP_OPTION_1                              = "help";
67     final static private String HELP_OPTION_2                              = "h";
68     final static private String DEFAULT_OUTFILE_SUFFIX                     = "_gsdi_out.phylo.xml";
69     final static private String SUFFIX_FOR_LIST_OF_STIPPED_GENE_TREE_NODES = "_stripped_gene_tree_nodes.txt";
70     final static private String LOGFILE_SUFFIX                             = "_gsdi_log.txt";
71     final static private String PRG_NAME                                   = "gsdi";
72     final static private String PRG_VERSION                                = "0.901";
73     final static private String PRG_DATE                                   = "120608";
74     final static private String PRG_DESC                                   = "general speciation duplication inference";
75     final static private String E_MAIL                                     = "phylosoft@gmail.com";
76     final static private String WWW                                        = "www.phylosoft.org/forester";
77
78     public static void main( final String args[] ) {
79         try {
80             ForesterUtil.printProgramInformation( PRG_NAME,
81                                                   PRG_DESC,
82                                                   PRG_VERSION,
83                                                   PRG_DATE,
84                                                   E_MAIL,
85                                                   WWW,
86                                                   ForesterUtil.getForesterLibraryInformation() );
87             CommandLineArguments cla = null;
88             try {
89                 cla = new CommandLineArguments( args );
90             }
91             catch ( final Exception e ) {
92                 ForesterUtil.fatalError( PRG_NAME, e.getMessage() );
93             }
94             if ( cla.isOptionSet( gsdi.HELP_OPTION_1 ) || cla.isOptionSet( gsdi.HELP_OPTION_2 ) ) {
95                 System.out.println();
96                 gsdi.print_help();
97                 System.exit( 0 );
98             }
99             else if ( ( args.length < 2 ) || ( cla.getNumberOfNames() < 2 ) || ( cla.getNumberOfNames() > 3 ) ) {
100                 System.out.println();
101                 System.out.println( "Wrong number of arguments." );
102                 System.out.println();
103                 gsdi.print_help();
104                 System.exit( -1 );
105             }
106             final List<String> allowed_options = new ArrayList<String>();
107             allowed_options.add( gsdi.STRIP_OPTION );
108             allowed_options.add( gsdi.SDI_OPTION );
109             allowed_options.add( gsdi.GUESS_FORMAT_OF_SPECIES_TREE );
110             allowed_options.add( gsdi.MOST_PARSIMONIOUS_OPTION );
111             allowed_options.add( gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION );
112             final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
113             if ( dissallowed_options.length() > 0 ) {
114                 ForesterUtil.fatalError( gsdi.PRG_NAME, "unknown option(s): " + dissallowed_options );
115             }
116             execute( cla );
117         }
118         catch ( final IOException e ) {
119             ForesterUtil.fatalError( gsdi.PRG_NAME, e.getMessage() );
120         }
121     }
122
123     private static void execute( final CommandLineArguments cla ) throws IOException {
124         BASE_ALGORITHM base_algorithm = BASE_ALGORITHM.GSDI;
125         boolean strip_species_tree = false;
126         boolean most_parsimonous_duplication_model = false;
127         boolean species_tree_in_phyloxml = true;
128         boolean allow_stripping_of_gene_tree = false;
129         if ( cla.isOptionSet( gsdi.STRIP_OPTION ) ) {
130             strip_species_tree = true;
131         }
132         if ( cla.isOptionSet( gsdi.SDI_OPTION ) ) {
133             base_algorithm = BASE_ALGORITHM.SDI;
134         }
135         if ( cla.isOptionSet( gsdi.MOST_PARSIMONIOUS_OPTION ) ) {
136             if ( base_algorithm != BASE_ALGORITHM.GSDI ) {
137                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Can only use most parsimonious duplication mode with GSDI" );
138             }
139             most_parsimonous_duplication_model = true;
140         }
141         if ( cla.isOptionSet( gsdi.GUESS_FORMAT_OF_SPECIES_TREE ) ) {
142             species_tree_in_phyloxml = false;
143         }
144         if ( cla.isOptionSet( gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION ) ) {
145             if ( base_algorithm != BASE_ALGORITHM.GSDI ) {
146                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Can only allow stripping of gene tree with GSDI" );
147             }
148             allow_stripping_of_gene_tree = true;
149         }
150         Phylogeny species_tree = null;
151         Phylogeny gene_tree = null;
152         File gene_tree_file = null;
153         File species_tree_file = null;
154         File out_file = null;
155         File log_file = null;
156         Writer log_writer = null;
157         try {
158             gene_tree_file = cla.getFile( 0 );
159             species_tree_file = cla.getFile( 1 );
160             if ( cla.getNumberOfNames() == 3 ) {
161                 out_file = cla.getFile( 2 );
162             }
163             else {
164                 out_file = new File( ForesterUtil.removeSuffix( gene_tree_file.toString() ) + DEFAULT_OUTFILE_SUFFIX );
165             }
166             log_file = new File( ForesterUtil.removeSuffix( out_file.toString() ) + LOGFILE_SUFFIX );
167         }
168         catch ( final IllegalArgumentException e ) {
169             ForesterUtil.fatalError( gsdi.PRG_NAME, "error in command line: " + e.getMessage() );
170         }
171         if ( ForesterUtil.isReadableFile( gene_tree_file ) != null ) {
172             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( gene_tree_file ) );
173         }
174         if ( ForesterUtil.isReadableFile( species_tree_file ) != null ) {
175             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( species_tree_file ) );
176         }
177         if ( ForesterUtil.isWritableFile( out_file ) != null ) {
178             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( out_file ) );
179         }
180         if ( ForesterUtil.isWritableFile( log_file ) != null ) {
181             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( log_file ) );
182         }
183         try {
184             log_writer = ForesterUtil.createBufferedWriter( log_file );
185         }
186         catch ( final IOException e ) {
187             ForesterUtil.fatalError( gsdi.PRG_NAME, "Failed to create [" + log_file + "]: " + e.getMessage() );
188         }
189         try {
190             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
191             gene_tree = factory.create( gene_tree_file, new PhyloXmlParser() )[ 0 ];
192         }
193         catch ( final IOException e ) {
194             ForesterUtil.fatalError( gsdi.PRG_NAME,
195                                      "Failed to read gene tree from [" + gene_tree_file + "]: " + e.getMessage() );
196         }
197         try {
198             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
199             if ( species_tree_in_phyloxml ) {
200                 species_tree = factory.create( species_tree_file, new PhyloXmlParser() )[ 0 ];
201             }
202             else {
203                 final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( species_tree_file, true );
204                 if ( REPLACE_UNDERSCORES_IN_NH_SPECIES_TREE && ( p instanceof NHXParser ) ) {
205                     ( ( NHXParser ) p ).setReplaceUnderscores( true );
206                 }
207                 species_tree = factory.create( species_tree_file, p )[ 0 ];
208                 final TaxonomyComparisonBase comp_base = GSDI.determineTaxonomyComparisonBase( gene_tree );
209                 switch ( comp_base ) {
210                     case SCIENTIFIC_NAME:
211                         PhylogenyMethods
212                                 .transferNodeNameToField( species_tree,
213                                                           PhylogenyMethods.PhylogenyNodeField.TAXONOMY_ID_UNIPROT_1 );
214                         break;
215                     case CODE:
216                         PhylogenyMethods.transferNodeNameToField( species_tree,
217                                                                   PhylogenyMethods.PhylogenyNodeField.TAXONOMY_CODE );
218                         break;
219                     case ID:
220                         PhylogenyMethods.transferNodeNameToField( species_tree,
221                                                                   PhylogenyMethods.PhylogenyNodeField.TAXONOMY_ID );
222                         break;
223                     default:
224                         ForesterUtil.fatalError( gsdi.PRG_NAME, "unable to determine comparison base" );
225                 }
226             }
227         }
228         catch ( final IOException e ) {
229             ForesterUtil.fatalError( gsdi.PRG_NAME,
230                                      "Failed to read species tree from [" + gene_tree_file + "]: " + e.getMessage() );
231         }
232         gene_tree.setRooted( true );
233         species_tree.setRooted( true );
234         if ( !gene_tree.isCompletelyBinary() ) {
235             log_writer.write( "User Error: gene tree is not completely binary" );
236             log_writer.write( ForesterUtil.LINE_SEPARATOR );
237             log_writer.close();
238             ForesterUtil.fatalError( gsdi.PRG_NAME, "gene tree is not completely binary" );
239         }
240         if ( base_algorithm != BASE_ALGORITHM.GSDI ) {
241             if ( !species_tree.isCompletelyBinary() ) {
242                 log_writer.write( "User Error: species tree is not completely binary, use GSDI instead" );
243                 log_writer.write( ForesterUtil.LINE_SEPARATOR );
244                 log_writer.close();
245                 ForesterUtil.fatalError( gsdi.PRG_NAME, "species tree is not completely binary, use GSDI instead" );
246             }
247         }
248         // For timing.
249         // gene_tree = Helper.createBalancedTree( 10 );
250         // species_tree = Helper.createBalancedTree( 13 );
251         // species_tree = Helper.createUnbalancedTree( 1024 );
252         // gene_tree = Helper.createUnbalancedTree( 8192 );
253         // species_tree = gene_tree.copyTree();
254         // gene_tree = species_tree.copyTree();
255         // Helper.numberSpeciesInOrder( species_tree );
256         // Helper.numberSpeciesInOrder( gene_tree );
257         // Helper.randomizeSpecies( 1, 8192, gene_tree );
258         // Helper.intervalNumberSpecies( gene_tree, 4096 );
259         // Helper.numberSpeciesInDescOrder( gene_tree );
260         log_writer.write( PRG_NAME + " - " + PRG_DESC );
261         log_writer.write( ForesterUtil.LINE_SEPARATOR );
262         log_writer.write( "  version         : " + PRG_VERSION );
263         log_writer.write( ForesterUtil.LINE_SEPARATOR );
264         log_writer.write( "  date            : " + PRG_DATE );
265         log_writer.write( ForesterUtil.LINE_SEPARATOR );
266         log_writer.write( "  forester version: " + ForesterConstants.FORESTER_VERSION );
267         log_writer.write( ForesterUtil.LINE_SEPARATOR );
268         log_writer.write( ForesterUtil.LINE_SEPARATOR );
269         log_writer.write( "Start time: " + new SimpleDateFormat( "yyyyMMdd HH:mm:ss" ).format( new Date() ) );
270         log_writer.write( ForesterUtil.LINE_SEPARATOR );
271         log_writer.write( "Gene tree file: " + gene_tree_file.getCanonicalPath() );
272         log_writer.write( ForesterUtil.LINE_SEPARATOR );
273         log_writer.write( "Gene tree name: "
274                 + ( ForesterUtil.isEmpty( gene_tree.getName() ) ? "" : gene_tree.getName() ) );
275         log_writer.write( ForesterUtil.LINE_SEPARATOR );
276         log_writer.write( "Species tree file: " + species_tree_file.getCanonicalPath() );
277         log_writer.write( ForesterUtil.LINE_SEPARATOR );
278         log_writer.write( "Species tree name: "
279                 + ( ForesterUtil.isEmpty( species_tree.getName() ) ? "" : gene_tree.getName() ) );
280         log_writer.write( ForesterUtil.LINE_SEPARATOR );
281         System.out.println();
282         System.out.println( "Strip species tree: " + strip_species_tree );
283         log_writer.write( "Strip species tree: " + strip_species_tree );
284         log_writer.write( ForesterUtil.LINE_SEPARATOR );
285         SDI sdi = null;
286         final long start_time = new Date().getTime();
287         try {
288             if ( base_algorithm == BASE_ALGORITHM.GSDI ) {
289                 System.out.println();
290                 System.out.println( "Use most parsimonous duplication model: " + most_parsimonous_duplication_model );
291                 System.out.println( "Allow stripping of gene tree nodes    : " + allow_stripping_of_gene_tree );
292                 log_writer.write( "Use most parsimonous duplication model: " + most_parsimonous_duplication_model );
293                 log_writer.write( ForesterUtil.LINE_SEPARATOR );
294                 log_writer.write( "Allow stripping of gene tree nodes    : " + allow_stripping_of_gene_tree );
295                 log_writer.write( ForesterUtil.LINE_SEPARATOR );
296                 log_writer.flush();
297                 sdi = new GSDI( gene_tree,
298                                 species_tree,
299                                 most_parsimonous_duplication_model,
300                                 allow_stripping_of_gene_tree,
301                                 strip_species_tree );
302             }
303             else {
304                 System.out.println();
305                 System.out.println( "Using SDIse algorithm" );
306                 log_writer.write( "Using SDIse algorithm" );
307                 log_writer.write( ForesterUtil.LINE_SEPARATOR );
308                 log_writer.flush();
309                 sdi = new SDIse( gene_tree, species_tree );
310             }
311         }
312         catch ( final SdiException e ) {
313             log_writer.write( "User Error: " + e.getLocalizedMessage() );
314             log_writer.write( ForesterUtil.LINE_SEPARATOR );
315             log_writer.close();
316             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
317         }
318         catch ( final IOException e ) {
319             log_writer.write( "Error: " + e );
320             log_writer.write( ForesterUtil.LINE_SEPARATOR );
321             log_writer.close();
322             ForesterUtil.fatalError( PRG_NAME, e.toString() );
323         }
324         catch ( final Exception e ) {
325             log_writer.write( "Error: " + e );
326             log_writer.write( ForesterUtil.LINE_SEPARATOR );
327             log_writer.close();
328             e.printStackTrace();
329             System.exit( -1 );
330         }
331         System.out.println();
332         System.out.println( "Running time (excluding I/O): " + ( new Date().getTime() - start_time ) + "ms" );
333         log_writer.write( "Running time (excluding I/O): " + ( new Date().getTime() - start_time ) + "ms" );
334         log_writer.write( ForesterUtil.LINE_SEPARATOR );
335         try {
336             final PhylogenyWriter writer = new PhylogenyWriter();
337             writer.toPhyloXML( out_file, gene_tree, 0 );
338         }
339         catch ( final IOException e ) {
340             ForesterUtil.fatalError( PRG_NAME, "Failed to write to [" + out_file + "]: " + e.getMessage() );
341         }
342         System.out.println();
343         System.out.println( "Successfully wrote resulting gene tree to: " + out_file );
344         System.out.println();
345         log_writer.write( "Wrote resulting gene tree to: " + out_file );
346         log_writer.write( ForesterUtil.LINE_SEPARATOR );
347         if ( base_algorithm == BASE_ALGORITHM.SDI ) {
348             sdi.computeMappingCostL();
349             System.out.println( "Mapping cost                    : " + sdi.computeMappingCostL() );
350             log_writer.write( "Mapping cost                    : " + sdi.computeMappingCostL() );
351             log_writer.write( ForesterUtil.LINE_SEPARATOR );
352         }
353         System.out.println( "Number of duplications          : " + sdi.getDuplicationsSum() );
354         log_writer.write( "Number of duplications          : " + sdi.getDuplicationsSum() );
355         log_writer.write( ForesterUtil.LINE_SEPARATOR );
356         if ( ( base_algorithm == BASE_ALGORITHM.GSDI ) ) {
357             final GSDI gsdi = ( GSDI ) sdi;
358             if ( !most_parsimonous_duplication_model ) {
359                 final int duplications = gsdi.getSpeciationOrDuplicationEventsSum();
360                 System.out.println( "Number of potential duplications: " + duplications );
361                 log_writer.write( "Number of potential duplications: " + duplications );
362                 log_writer.write( ForesterUtil.LINE_SEPARATOR );
363             }
364             final int spec = gsdi.getSpeciationsSum();
365             System.out.println( "Number of speciations            : " + spec );
366             log_writer.write( "Number of speciations            : " + spec );
367             log_writer.write( ForesterUtil.LINE_SEPARATOR );
368             for( PhylogenyNode n : gsdi.getMappedExternalSpeciesTreeNodes() ) {
369                 System.out.println( n.toString() );
370             }
371         }
372         System.out.println();
373         log_writer.close();
374         //  some stat on gene tree:
375         //      filename, name
376         //      number of external nodes, strppided nodes
377         //  some stats on sepcies tree, external nodes,
378         //  filename, name
379         //  internal nodes
380         //  how many of which are polytomies
381         //wrote log file to
382         //  if ( allow_stripping_of_gene_tree ) {
383         //      stripped x nodes, y external nodes remain
384         //  }
385     }
386
387     private static void print_help() {
388         System.out.println( "Usage: " + gsdi.PRG_NAME
389                 + " [-options] <gene tree in phyloXML format> <species tree in phyloXML format> [outfile]" );
390         System.out.println();
391         System.out.println( "Options:" );
392         //    System.out.println( " -" + gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION + ": to allow stripping of gene tree nodes without a matching species in the species tree (writes list of stripped nodes to " + );
393         System.out.println( " -" + gsdi.STRIP_OPTION
394                 + ": to strip the species tree of unneeded species prior to duplication inference" );
395         System.out.println( " -" + gsdi.SDI_OPTION + ": to use SDI algorithm instead of GSDI algorithm" );//TODO gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION not allowed
396         System.out.println( " -" + gsdi.MOST_PARSIMONIOUS_OPTION
397                 + ": use most parimonious duplication model for GSDI: " );
398         System.out.println( "     assign nodes as speciations which would otherwise be assiged" );
399         System.out.println( "     as unknown because of polytomies in the species tree" );
400         System.out.println( " -" + gsdi.GUESS_FORMAT_OF_SPECIES_TREE
401                 + ": to allow species tree in other formats than phyloXML (i.e. Newick, NHX, Nexus)" );
402         System.out.println();
403         System.out.println( "Species tree:" );
404         System.out
405                 .println( " In phyloXML format (unless option -"
406                         + gsdi.GUESS_FORMAT_OF_SPECIES_TREE
407                         + " is used, in which case the species matching between gene tree and species tree must be via scientific name), with taxonomy data in appropriate fields" );
408         System.out.println();
409         System.out.println( "Gene tree:" );
410         System.out.println( " In phyloXM format, with taxonomy and sequence data in appropriate fields" );
411         System.out.println();
412         System.out.println( "Example:" );
413         //  System.out.println( "gsdi 
414         //    System.out.println();
415         System.out.println( "Note -- GSDI algorithm is under development" );
416         System.out.println();
417     }
418 }