de949a87f25aaec11ee02ef79f949d743f59edea
[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.text.SimpleDateFormat;
31 import java.util.ArrayList;
32 import java.util.Date;
33 import java.util.List;
34
35 import org.forester.io.parsers.PhylogenyParser;
36 import org.forester.io.parsers.nhx.NHXParser;
37 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
38 import org.forester.io.parsers.util.ParserUtils;
39 import org.forester.io.writers.PhylogenyWriter;
40 import org.forester.phylogeny.Phylogeny;
41 import org.forester.phylogeny.PhylogenyMethods;
42 import org.forester.phylogeny.PhylogenyNode;
43 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
44 import org.forester.phylogeny.factories.PhylogenyFactory;
45 import org.forester.sdi.GSDI;
46 import org.forester.sdi.SDI;
47 import org.forester.sdi.SDI.TaxonomyComparisonBase;
48 import org.forester.sdi.SDIse;
49 import org.forester.sdi.SdiException;
50 import org.forester.util.CommandLineArguments;
51 import org.forester.util.EasyWriter;
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 ALLOW_STRIPPING_OF_GENE_TREE_OPTION        = "g";
62     final static private String SDI_OPTION                                 = "b";
63     final static private String MOST_PARSIMONIOUS_OPTION                   = "m";
64     final static private String GUESS_FORMAT_OF_SPECIES_TREE               = "q";
65     final static private String HELP_OPTION_1                              = "help";
66     final static private String HELP_OPTION_2                              = "h";
67     final static private String DEFAULT_OUTFILE_SUFFIX                     = "_gsdi_out.xml";
68     final static private String SUFFIX_FOR_LIST_OF_STIPPED_GENE_TREE_NODES = "_stripped_gene_tree_nodes.txt";
69     final static private String SUFFIX_FOR_SPECIES_TREE_USED               = "_species_tree_used.xml";
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.SDI_OPTION );
108             allowed_options.add( gsdi.GUESS_FORMAT_OF_SPECIES_TREE );
109             allowed_options.add( gsdi.MOST_PARSIMONIOUS_OPTION );
110             allowed_options.add( gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION );
111             final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
112             if ( dissallowed_options.length() > 0 ) {
113                 ForesterUtil.fatalError( gsdi.PRG_NAME, "unknown option(s): " + dissallowed_options );
114             }
115             execute( cla );
116         }
117         catch ( final IOException e ) {
118             ForesterUtil.fatalError( gsdi.PRG_NAME, e.getMessage() );
119         }
120     }
121
122     private static void execute( final CommandLineArguments cla ) throws IOException {
123         BASE_ALGORITHM base_algorithm = BASE_ALGORITHM.GSDI;
124         boolean most_parsimonous_duplication_model = false;
125         boolean species_tree_in_phyloxml = true;
126         boolean allow_stripping_of_gene_tree = false;
127         if ( cla.isOptionSet( gsdi.SDI_OPTION ) ) {
128             base_algorithm = BASE_ALGORITHM.SDI;
129         }
130         if ( cla.isOptionSet( gsdi.MOST_PARSIMONIOUS_OPTION ) ) {
131             if ( base_algorithm != BASE_ALGORITHM.GSDI ) {
132                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Can only use most parsimonious duplication mode with GSDI" );
133             }
134             most_parsimonous_duplication_model = true;
135         }
136         if ( cla.isOptionSet( gsdi.GUESS_FORMAT_OF_SPECIES_TREE ) ) {
137             species_tree_in_phyloxml = false;
138         }
139         if ( cla.isOptionSet( gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION ) ) {
140             if ( base_algorithm != BASE_ALGORITHM.GSDI ) {
141                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Can only allow stripping of gene tree with GSDI" );
142             }
143             allow_stripping_of_gene_tree = true;
144         }
145         Phylogeny species_tree = null;
146         Phylogeny gene_tree = null;
147         File gene_tree_file = null;
148         File species_tree_file = null;
149         File out_file = null;
150         File log_file = null;
151         EasyWriter log_writer = null;
152         try {
153             gene_tree_file = cla.getFile( 0 );
154             species_tree_file = cla.getFile( 1 );
155             if ( cla.getNumberOfNames() == 3 ) {
156                 out_file = cla.getFile( 2 );
157             }
158             else {
159                 out_file = new File( ForesterUtil.removeSuffix( gene_tree_file.toString() ) + DEFAULT_OUTFILE_SUFFIX );
160             }
161             log_file = new File( ForesterUtil.removeSuffix( out_file.toString() ) + LOGFILE_SUFFIX );
162         }
163         catch ( final IllegalArgumentException e ) {
164             ForesterUtil.fatalError( gsdi.PRG_NAME, "error in command line: " + e.getMessage() );
165         }
166         if ( ForesterUtil.isReadableFile( gene_tree_file ) != null ) {
167             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( gene_tree_file ) );
168         }
169         if ( ForesterUtil.isReadableFile( species_tree_file ) != null ) {
170             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( species_tree_file ) );
171         }
172         if ( ForesterUtil.isWritableFile( out_file ) != null ) {
173             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( out_file ) );
174         }
175         if ( ForesterUtil.isWritableFile( log_file ) != null ) {
176             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( log_file ) );
177         }
178         try {
179             log_writer = ForesterUtil.createEasyWriter( log_file );
180         }
181         catch ( final IOException e ) {
182             ForesterUtil.fatalError( gsdi.PRG_NAME, "Failed to create [" + log_file + "]: " + e.getMessage() );
183         }
184         try {
185             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
186             gene_tree = factory.create( gene_tree_file, new PhyloXmlParser() )[ 0 ];
187         }
188         catch ( final IOException e ) {
189             ForesterUtil.fatalError( gsdi.PRG_NAME,
190                                      "Failed to read gene tree from [" + gene_tree_file + "]: " + e.getMessage() );
191         }
192         try {
193             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
194             if ( species_tree_in_phyloxml ) {
195                 species_tree = factory.create( species_tree_file, new PhyloXmlParser() )[ 0 ];
196             }
197             else {
198                 final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( species_tree_file, true );
199                 if ( REPLACE_UNDERSCORES_IN_NH_SPECIES_TREE && ( p instanceof NHXParser ) ) {
200                     ( ( NHXParser ) p ).setReplaceUnderscores( true );
201                 }
202                 species_tree = factory.create( species_tree_file, p )[ 0 ];
203                 final TaxonomyComparisonBase comp_base = GSDI.determineTaxonomyComparisonBase( gene_tree );
204                 switch ( comp_base ) {
205                     case SCIENTIFIC_NAME:
206                         PhylogenyMethods
207                                 .transferNodeNameToField( species_tree,
208                                                           PhylogenyMethods.PhylogenyNodeField.TAXONOMY_ID_UNIPROT_1 );
209                         break;
210                     case CODE:
211                         PhylogenyMethods.transferNodeNameToField( species_tree,
212                                                                   PhylogenyMethods.PhylogenyNodeField.TAXONOMY_CODE );
213                         break;
214                     case ID:
215                         PhylogenyMethods.transferNodeNameToField( species_tree,
216                                                                   PhylogenyMethods.PhylogenyNodeField.TAXONOMY_ID );
217                         break;
218                     default:
219                         ForesterUtil.fatalError( gsdi.PRG_NAME, "unable to determine comparison base" );
220                 }
221             }
222         }
223         catch ( final IOException e ) {
224             ForesterUtil.fatalError( gsdi.PRG_NAME,
225                                      "Failed to read species tree from [" + gene_tree_file + "]: " + e.getMessage() );
226         }
227         gene_tree.setRooted( true );
228         species_tree.setRooted( true );
229         if ( !gene_tree.isCompletelyBinary() ) {
230             log_writer.println( "User Error: gene tree is not completely binary" );
231             log_writer.close();
232             ForesterUtil.fatalError( gsdi.PRG_NAME, "gene tree is not completely binary" );
233         }
234         if ( base_algorithm != BASE_ALGORITHM.GSDI ) {
235             if ( !species_tree.isCompletelyBinary() ) {
236                 log_writer.println( "User Error: species tree is not completely binary, use GSDI instead" );
237                 log_writer.close();
238                 ForesterUtil.fatalError( gsdi.PRG_NAME, "species tree is not completely binary, use GSDI instead" );
239             }
240         }
241         // For timing.
242         // gene_tree = Helper.createBalancedTree( 10 );
243         // species_tree = Helper.createBalancedTree( 13 );
244         // species_tree = Helper.createUnbalancedTree( 1024 );
245         // gene_tree = Helper.createUnbalancedTree( 8192 );
246         // species_tree = gene_tree.copyTree();
247         // gene_tree = species_tree.copyTree();
248         // Helper.numberSpeciesInOrder( species_tree );
249         // Helper.numberSpeciesInOrder( gene_tree );
250         // Helper.randomizeSpecies( 1, 8192, gene_tree );
251         // Helper.intervalNumberSpecies( gene_tree, 4096 );
252         // Helper.numberSpeciesInDescOrder( gene_tree );
253         log_writer.println( PRG_NAME + " - " + PRG_DESC );
254         log_writer.println( "  version         : " + PRG_VERSION );
255         log_writer.println( "  date            : " + PRG_DATE );
256         log_writer.println( "  forester version: " + ForesterConstants.FORESTER_VERSION );
257         log_writer.println( "Start time: " + new SimpleDateFormat( "yyyyMMdd HH:mm:ss" ).format( new Date() ) );
258         log_writer.println( "Gene tree file: " + gene_tree_file.getCanonicalPath() );
259         log_writer.println( "Gene tree name: "
260                 + ( ForesterUtil.isEmpty( gene_tree.getName() ) ? "" : gene_tree.getName() ) );
261         log_writer.println( "Species tree file: " + species_tree_file.getCanonicalPath() );
262         log_writer.println( "Species tree name: "
263                 + ( ForesterUtil.isEmpty( species_tree.getName() ) ? "" : gene_tree.getName() ) );
264         System.out.println();
265         SDI sdi = null;
266         final long start_time = new Date().getTime();
267         try {
268             if ( base_algorithm == BASE_ALGORITHM.GSDI ) {
269                 System.out.println();
270                 System.out.println( "Use most parsimonous duplication model: " + most_parsimonous_duplication_model );
271                 System.out.println( "Allow stripping of gene tree nodes    : " + allow_stripping_of_gene_tree );
272                 log_writer.println( "Use most parsimonous duplication model: " + most_parsimonous_duplication_model );
273                 log_writer.write( "Allow stripping of gene tree nodes    : " + allow_stripping_of_gene_tree );
274                 log_writer.flush();
275                 sdi = new GSDI( gene_tree,
276                                 species_tree,
277                                 most_parsimonous_duplication_model,
278                                 allow_stripping_of_gene_tree,
279                                 true );
280             }
281             else {
282                 System.out.println();
283                 System.out.println( "Using SDIse algorithm" );
284                 log_writer.println( "Using SDIse algorithm" );
285                 log_writer.flush();
286                 sdi = new SDIse( gene_tree, species_tree );
287             }
288         }
289         catch ( final SdiException e ) {
290             log_writer.println( "User Error: " + e.getLocalizedMessage() );
291             log_writer.close();
292             ForesterUtil.fatalError( PRG_NAME, e.getLocalizedMessage() );
293         }
294         catch ( final IOException e ) {
295             log_writer.println( "Error: " + e );
296             log_writer.close();
297             ForesterUtil.fatalError( PRG_NAME, e.toString() );
298         }
299         catch ( final Exception e ) {
300             log_writer.println( "Error: " + e );
301             log_writer.close();
302             e.printStackTrace();
303             System.exit( -1 );
304         }
305         System.out.println();
306         System.out.println( "Running time (excluding I/O): " + ( new Date().getTime() - start_time ) + "ms" );
307         log_writer.println( "Running time (excluding I/O): " + ( new Date().getTime() - start_time ) + "ms" );
308         try {
309             final PhylogenyWriter writer = new PhylogenyWriter();
310             writer.toPhyloXML( out_file, gene_tree, 0 );
311         }
312         catch ( final IOException e ) {
313             ForesterUtil.fatalError( PRG_NAME, "Failed to write to [" + out_file + "]: " + e.getMessage() );
314         }
315         System.out.println();
316         System.out.println( "Wrote resulting gene tree to: " + out_file );
317         System.out.println();
318         log_writer.println( "Wrote resulting gene tree to: " + out_file );
319         if ( base_algorithm == BASE_ALGORITHM.SDI ) {
320             sdi.computeMappingCostL();
321             System.out.println( "Mapping cost                    : " + sdi.computeMappingCostL() );
322             log_writer.println( "Mapping cost                    : " + sdi.computeMappingCostL() );
323         }
324         System.out.println( "Number of duplications          : " + sdi.getDuplicationsSum() );
325         log_writer.println( "Number of duplications          : " + sdi.getDuplicationsSum() );
326         if ( ( base_algorithm == BASE_ALGORITHM.GSDI ) ) {
327             final GSDI gsdi = ( GSDI ) sdi;
328             File species_tree_used_file = new File( out_file + SUFFIX_FOR_SPECIES_TREE_USED );
329             try {
330                 final PhylogenyWriter writer = new PhylogenyWriter();
331                 writer.toPhyloXML( species_tree_used_file, gsdi.getSpeciesTree(), 0 );
332             }
333             catch ( final IOException e ) {
334                 ForesterUtil.fatalError( PRG_NAME,
335                                          "Failed to write to [" + species_tree_used_file + "]: " + e.getMessage() );
336             }
337             System.out.println();
338             System.out.println( "Wrote used species tree to: " + species_tree_used_file );
339             System.out.println();
340             log_writer.println( "Wrote used species tree to: " + species_tree_used_file );
341             if ( !most_parsimonous_duplication_model ) {
342                 final int duplications = gsdi.getSpeciationOrDuplicationEventsSum();
343                 System.out.println( "Number of potential duplications: " + duplications );
344                 log_writer.println( "Number of potential duplications: " + duplications );
345             }
346             final int spec = gsdi.getSpeciationsSum();
347             System.out.println( "Number of speciations            : " + spec );
348             log_writer.println( "Number of speciations            : " + spec );
349             for( PhylogenyNode n : gsdi.getMappedExternalSpeciesTreeNodes() ) {
350                 System.out.println( n.toString() );
351             }
352         }
353         System.out.println();
354         log_writer.close();
355         //  some stat on gene tree:
356         //      filename, name
357         //      number of external nodes, strppided nodes
358         //  some stats on sepcies tree, external nodes,
359         //  filename, name
360         //  internal nodes
361         //  how many of which are polytomies
362         //wrote log file to
363         //  if ( allow_stripping_of_gene_tree ) {
364         //      stripped x nodes, y external nodes remain
365         //  }
366     }
367
368     private static void print_help() {
369         System.out.println( "Usage: " + gsdi.PRG_NAME
370                 + " [-options] <gene tree in phyloXML format> <species tree in phyloXML format> [outfile]" );
371         System.out.println();
372         System.out.println( "Options:" );
373         //    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 " + );
374         System.out.println( " -" + gsdi.SDI_OPTION + ": to use SDI algorithm instead of GSDI algorithm" );//TODO gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION not allowed
375         System.out.println( " -" + gsdi.MOST_PARSIMONIOUS_OPTION
376                 + ": use most parimonious duplication model for GSDI: " );
377         System.out.println( "     assign nodes as speciations which would otherwise be assiged" );
378         System.out.println( "     as unknown because of polytomies in the species tree" );
379         System.out.println( " -" + gsdi.GUESS_FORMAT_OF_SPECIES_TREE
380                 + ": to allow species tree in other formats than phyloXML (i.e. Newick, NHX, Nexus)" );
381         System.out.println();
382         System.out.println( "Species tree:" );
383         System.out
384                 .println( " In phyloXML format (unless option -"
385                         + gsdi.GUESS_FORMAT_OF_SPECIES_TREE
386                         + " 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" );
387         System.out.println();
388         System.out.println( "Gene tree:" );
389         System.out.println( " In phyloXM format, with taxonomy and sequence data in appropriate fields" );
390         System.out.println();
391         System.out.println( "Example:" );
392         //  System.out.println( "gsdi 
393         //    System.out.println();
394         System.out.println( "Note -- GSDI algorithm is under development" );
395         System.out.println();
396     }
397 }