inprogress
[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: https://sites.google.com/site/cmzmasek/home/software/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 import java.util.SortedMap;
35 import java.util.SortedSet;
36 import java.util.TreeMap;
37 import java.util.TreeSet;
38
39 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
40 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
41 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
42 import org.forester.io.writers.PhylogenyWriter;
43 import org.forester.phylogeny.Phylogeny;
44 import org.forester.phylogeny.PhylogenyMethods;
45 import org.forester.phylogeny.PhylogenyNode;
46 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
47 import org.forester.phylogeny.factories.PhylogenyFactory;
48 import org.forester.sdi.GSDI;
49 import org.forester.sdi.GSDII;
50 import org.forester.sdi.GSDIR;
51 import org.forester.sdi.SDIException;
52 import org.forester.sdi.SDIutil;
53 import org.forester.sdi.SDIutil.ALGORITHM;
54 import org.forester.util.CommandLineArguments;
55 import org.forester.util.EasyWriter;
56 import org.forester.util.ForesterConstants;
57 import org.forester.util.ForesterUtil;
58
59 public final class gsdi {
60
61     final static public boolean REPLACE_UNDERSCORES_IN_NH_SPECIES_TREE = true;
62     final static private String ALLOW_STRIPPING_OF_GENE_TREE_OPTION    = "g";
63     final static private String GSDIR_OPTION                           = "r";
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 TRANSFER_TAXONOMY_OPTION               = "t";
67     final static private String HELP_OPTION_1                          = "help";
68     final static private String HELP_OPTION_2                          = "h";
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 REMAPPED_SUFFIX                        = "_gsdi_remapped.txt";
72     final static private String PRG_NAME                               = "gsdi";
73     final static private String PRG_VERSION                            = "1.001";
74     final static private String PRG_DATE                               = "130325";
75     final static private String PRG_DESC                               = "general speciation duplication inference";
76     final static private String E_MAIL                                 = "phylosoft@gmail.com";
77     final static private String WWW                                    = "https://sites.google.com/site/cmzmasek/home/software/forester";
78
79     public static void main( final String args[] ) {
80         try {
81             ForesterUtil.printProgramInformation( PRG_NAME,
82                                                   PRG_DESC,
83                                                   PRG_VERSION,
84                                                   PRG_DATE,
85                                                   E_MAIL,
86                                                   WWW,
87                                                   ForesterUtil.getForesterLibraryInformation() );
88             CommandLineArguments cla = null;
89             try {
90                 cla = new CommandLineArguments( args );
91             }
92             catch ( final Exception e ) {
93                 ForesterUtil.fatalError( PRG_NAME, e.getMessage() );
94             }
95             if ( cla.isOptionSet( gsdi.HELP_OPTION_1 ) || cla.isOptionSet( gsdi.HELP_OPTION_2 ) ) {
96                 System.out.println();
97                 gsdi.print_help();
98                 System.exit( 0 );
99             }
100             else if ( ( args.length < 2 ) || ( cla.getNumberOfNames() != 3 ) ) {
101                 System.out.println();
102                 System.out.println( "Wrong number of arguments." );
103                 System.out.println();
104                 gsdi.print_help();
105                 System.exit( -1 );
106             }
107             final List<String> allowed_options = new ArrayList<String>();
108             allowed_options.add( gsdi.GSDIR_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             allowed_options.add( TRANSFER_TAXONOMY_OPTION );
113             final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
114             if ( dissallowed_options.length() > 0 ) {
115                 ForesterUtil.fatalError( gsdi.PRG_NAME, "unknown option(s): " + dissallowed_options );
116             }
117             execute( cla );
118         }
119         catch ( final IOException e ) {
120             ForesterUtil.fatalError( gsdi.PRG_NAME, e.getMessage() );
121         }
122     }
123
124     private static void execute( final CommandLineArguments cla ) throws IOException {
125         ALGORITHM base_algorithm = ALGORITHM.GSDI;
126         boolean most_parsimonous_duplication_model = false;
127         boolean allow_stripping_of_gene_tree = false;
128         if ( cla.isOptionSet( gsdi.GSDIR_OPTION ) ) {
129             base_algorithm = ALGORITHM.GSDIR;
130         }
131         if ( cla.isOptionSet( gsdi.MOST_PARSIMONIOUS_OPTION ) ) {
132             if ( base_algorithm == ALGORITHM.SDI ) {
133                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Cannot use most parsimonious duplication mode with SDI" );
134             }
135             most_parsimonous_duplication_model = true;
136         }
137         if ( cla.isOptionSet( gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION ) ) {
138             if ( base_algorithm == ALGORITHM.SDI ) {
139                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Cannot allow stripping of gene tree with SDI" );
140             }
141             allow_stripping_of_gene_tree = true;
142         }
143         boolean transfer_taxonomy = false;
144         if ( cla.isOptionSet( TRANSFER_TAXONOMY_OPTION ) ) {
145             transfer_taxonomy = true;
146         }
147         Phylogeny species_tree = null;
148         Phylogeny gene_tree = null;
149         File gene_tree_file = null;
150         File species_tree_file = null;
151         File out_file = null;
152         File log_file = null;
153         EasyWriter log_writer = null;
154         try {
155             gene_tree_file = cla.getFile( 0 );
156             species_tree_file = cla.getFile( 1 );
157             out_file = cla.getFile( 2 );
158             log_file = new File( ForesterUtil.removeSuffix( out_file.toString() ) + LOGFILE_SUFFIX );
159         }
160         catch ( final IllegalArgumentException e ) {
161             ForesterUtil.fatalError( gsdi.PRG_NAME, "error in command line: " + e.getMessage() );
162         }
163         if ( ForesterUtil.isReadableFile( gene_tree_file ) != null ) {
164             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( gene_tree_file ) );
165         }
166         if ( ForesterUtil.isReadableFile( species_tree_file ) != null ) {
167             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( species_tree_file ) );
168         }
169         if ( ForesterUtil.isWritableFile( out_file ) != null ) {
170             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( out_file ) );
171         }
172         if ( ForesterUtil.isWritableFile( log_file ) != null ) {
173             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( log_file ) );
174         }
175         try {
176             log_writer = ForesterUtil.createEasyWriter( log_file );
177         }
178         catch ( final IOException e ) {
179             ForesterUtil.fatalError( gsdi.PRG_NAME, "Failed to create [" + log_file + "]: " + e.getMessage() );
180         }
181         try {
182             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
183             gene_tree = factory.create( gene_tree_file, PhyloXmlParser.createPhyloXmlParserXsdValidating() )[ 0 ];
184         }
185         catch ( final IOException e ) {
186             fatalError( "error",
187                         "failed to read gene tree from [" + gene_tree_file + "]: " + e.getMessage(),
188                         log_writer );
189         }
190         try {
191             species_tree = SDIutil.parseSpeciesTree( gene_tree,
192                                                      species_tree_file,
193                                                      REPLACE_UNDERSCORES_IN_NH_SPECIES_TREE,
194                                                      true,
195                                                      TAXONOMY_EXTRACTION.NO );
196         }
197         catch ( final PhyloXmlDataFormatException e ) {
198             fatalError( "user error",
199                         "failed to transfer general node name, in [" + species_tree_file + "]: " + e.getMessage(),
200                         log_writer );
201         }
202         catch ( final SDIException e ) {
203             fatalError( "user error", e.getMessage(), log_writer );
204         }
205         catch ( final IOException e ) {
206             fatalError( "error",
207                         "Failed to read species tree from [" + species_tree_file + "]: " + e.getMessage(),
208                         log_writer );
209         }
210         gene_tree.setRooted( true );
211         species_tree.setRooted( true );
212         if ( !gene_tree.isCompletelyBinary() ) {
213             fatalError( "user error", "gene tree is not completely binary", log_writer );
214         }
215         if ( base_algorithm == ALGORITHM.SDI ) {
216             if ( !species_tree.isCompletelyBinary() ) {
217                 fatalError( "user error",
218                             "species tree is not completely binary, use GSDI or GSDIR instead",
219                             log_writer );
220             }
221         }
222         log_writer.println( PRG_NAME + " - " + PRG_DESC );
223         log_writer.println( "  version         : " + PRG_VERSION );
224         log_writer.println( "  date            : " + PRG_DATE );
225         log_writer.println( "  forester version: " + ForesterConstants.FORESTER_VERSION );
226         log_writer.println();
227         log_writer.println( "Start time                               : "
228                 + new SimpleDateFormat( "yyyyMMdd HH:mm:ss" ).format( new Date() ) );
229         System.out.println( "Start time                               : "
230                 + new SimpleDateFormat( "yyyyMMdd HH:mm:ss" ).format( new Date() ) );
231         log_writer.println( "Gene tree file                           : " + gene_tree_file.getCanonicalPath() );
232         System.out.println( "Gene tree file                           : " + gene_tree_file.getCanonicalPath() );
233         log_writer.println( "Gene tree name                           : "
234                 + ( ForesterUtil.isEmpty( gene_tree.getName() ) ? "" : gene_tree.getName() ) );
235         System.out.println( "Gene tree name                           : "
236                 + ( ForesterUtil.isEmpty( gene_tree.getName() ) ? "" : gene_tree.getName() ) );
237         log_writer.println( "Species tree file                        : " + species_tree_file.getCanonicalPath() );
238         System.out.println( "Species tree file                        : " + species_tree_file.getCanonicalPath() );
239         log_writer.println( "Species tree name                        : "
240                 + ( ForesterUtil.isEmpty( species_tree.getName() ) ? "" : gene_tree.getName() ) );
241         System.out.println( "Species tree name                        : "
242                 + ( ForesterUtil.isEmpty( species_tree.getName() ) ? "" : gene_tree.getName() ) );
243         System.out.println( "Transfer taxonomy                        : " + transfer_taxonomy );
244         GSDII gsdii = null;
245         final long start_time = new Date().getTime();
246         try {
247             if ( base_algorithm == ALGORITHM.GSDI ) {
248                 System.out.println( "Algorithm                                : GSDI" );
249                 log_writer.println( "Algorithm                                : GSDI" );
250             }
251             else if ( base_algorithm == ALGORITHM.GSDIR ) {
252                 System.out.println( "Algorithm                                : GSDIR" );
253                 log_writer.println( "Algorithm                                : GSDIR" );
254             }
255             System.out.println( "Use most parsimonous duplication model   : " + most_parsimonous_duplication_model );
256             System.out.println( "Allow stripping of gene tree nodes       : " + allow_stripping_of_gene_tree );
257             log_writer.println( "Use most parsimonous duplication model   : " + most_parsimonous_duplication_model );
258             log_writer.println( "Allow stripping of gene tree nodes       : " + allow_stripping_of_gene_tree );
259             log_writer.flush();
260             if ( base_algorithm == ALGORITHM.GSDI ) {
261                 gsdii = new GSDI( gene_tree,
262                                   species_tree,
263                                   most_parsimonous_duplication_model,
264                                   allow_stripping_of_gene_tree,
265                                   true,
266                                   transfer_taxonomy );
267             }
268             else if ( base_algorithm == ALGORITHM.GSDIR ) {
269                 gsdii = new GSDIR( gene_tree, species_tree, allow_stripping_of_gene_tree, true, transfer_taxonomy );
270             }
271         }
272         catch ( final SDIException e ) {
273             fatalError( "user error", e.getLocalizedMessage(), log_writer );
274         }
275         catch ( final IOException e ) {
276             fatalError( "error", e.toString(), log_writer );
277         }
278         catch ( final OutOfMemoryError e ) {
279             ForesterUtil.outOfMemoryError( e );
280         }
281         catch ( final Exception e ) {
282             e.printStackTrace();
283             fatalError( "unexpected error", e.toString(), log_writer );
284         }
285         System.out.println( "Running time (excluding I/O)             : " + ( new Date().getTime() - start_time )
286                 + "ms" );
287         log_writer.println( "Running time (excluding I/O)             : " + ( new Date().getTime() - start_time )
288                 + "ms" );
289         System.out.println( "Mapping based on                         : " + gsdii.getTaxCompBase() );
290         log_writer.println( "Mapping based on                         : " + gsdii.getTaxCompBase() );
291         try {
292             final PhylogenyWriter writer = new PhylogenyWriter();
293             if ( base_algorithm == ALGORITHM.GSDIR ) {
294                 writer.toPhyloXML( out_file, ( ( GSDIR ) gsdii ).getMinDuplicationsSumGeneTree(), 0 );
295             }
296             else {
297                 writer.toPhyloXML( out_file, gene_tree, 0 );
298             }
299         }
300         catch ( final IOException e ) {
301             ForesterUtil.fatalError( PRG_NAME,
302                                      "Failed to write to [" + out_file.getCanonicalPath() + "]: " + e.getMessage() );
303         }
304         System.out.println( "Wrote resulting gene tree to             : " + out_file.getCanonicalPath() );
305         log_writer.println( "Wrote resulting gene tree to             : " + out_file.getCanonicalPath() );
306         final File species_tree_used_file = new File( ForesterUtil.removeSuffix( out_file.toString() )
307                 + SUFFIX_FOR_SPECIES_TREE_USED );
308         try {
309             final PhylogenyWriter writer = new PhylogenyWriter();
310             writer.toPhyloXML( species_tree_used_file, species_tree, 0 );
311         }
312         catch ( final IOException e ) {
313             ForesterUtil.fatalError( PRG_NAME, "Failed to write to [" + species_tree_used_file.getCanonicalPath()
314                     + "]: " + e.getMessage() );
315         }
316         System.out.println( "Wrote (stripped) species tree to         : " + species_tree_used_file.getCanonicalPath() );
317         log_writer.println( "Wrote (stripped) species tree to         : " + species_tree_used_file.getCanonicalPath() );
318         if ( ( gsdii.getReMappedScientificNamesFromGeneTree() != null )
319                 && !gsdii.getReMappedScientificNamesFromGeneTree().isEmpty() ) {
320             System.out.println( "Number of gene tree species remapped     : "
321                     + gsdii.getReMappedScientificNamesFromGeneTree().size() );
322             log_writer.println( "Number of gene tree species remapped     : "
323                     + gsdii.getReMappedScientificNamesFromGeneTree().size() );
324             writeToRemappedFile( out_file, gsdii.getReMappedScientificNamesFromGeneTree(), log_writer );
325         }
326         System.out.println( "Number of external nodes in gene tree    : " + gene_tree.getNumberOfExternalNodes() );
327         log_writer.println( "Number of external nodes in gene tree    : " + gene_tree.getNumberOfExternalNodes() );
328         System.out.println( "Number of external nodes in species tree : " + species_tree.getNumberOfExternalNodes() );
329         log_writer.println( "Number of external nodes in species tree : " + species_tree.getNumberOfExternalNodes() );
330         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
331         System.out.println( "Number of polytomies in species tree     : " + poly );
332         log_writer.println( "Number of polytomies in species tree     : " + poly );
333         System.out.println( "External nodes stripped from gene tree   : "
334                 + gsdii.getStrippedExternalGeneTreeNodes().size() );
335         log_writer.println( "External nodes stripped from gene tree   : "
336                 + gsdii.getStrippedExternalGeneTreeNodes().size() );
337         System.out.println( "External nodes stripped from species tree: " + gsdii.getStrippedSpeciesTreeNodes().size() );
338         log_writer.println( "External nodes stripped from species tree: " + gsdii.getStrippedSpeciesTreeNodes().size() );
339         System.out.println();
340         System.out.println( "Number of speciations                    : " + gsdii.getSpeciationsSum() );
341         log_writer.println( "Number of speciations                    : " + gsdii.getSpeciationsSum() );
342         if ( ( base_algorithm == ALGORITHM.GSDIR ) ) {
343             final GSDIR gsdir = ( GSDIR ) gsdii;
344             System.out.println( "Minimal number of duplications           : " + gsdir.getMinDuplicationsSum() );
345             log_writer.println( "Minimal number of duplications           : " + gsdir.getMinDuplicationsSum() );
346         }
347         else if ( ( base_algorithm == ALGORITHM.GSDI ) ) {
348             final GSDI gsdi = ( GSDI ) gsdii;
349             System.out.println( "Number of duplications                   : " + gsdi.getDuplicationsSum() );
350             log_writer.println( "Number of duplications                   : " + gsdi.getDuplicationsSum() );
351             if ( !most_parsimonous_duplication_model ) {
352                 final int u = gsdi.getSpeciationOrDuplicationEventsSum();
353                 System.out.println( "Number of potential duplications         : " + u );
354                 log_writer.println( "Number of potential duplications         : " + u );
355             }
356         }
357         log_writer.println();
358         printMappedNodesToLog( log_writer, gsdii );
359         log_writer.println();
360         printStrippedGeneTreeNodesToLog( log_writer, gsdii );
361         System.out.println();
362         System.out.println( "Wrote log to                             : " + log_file.getCanonicalPath() );
363         System.out.println();
364         log_writer.close();
365     }
366
367     private static void fatalError( final String type, final String msg, final EasyWriter log_writer ) {
368         try {
369             log_writer.flush();
370             log_writer.println();
371             log_writer.print( type.toUpperCase() + ": " );
372             log_writer.println( msg );
373             log_writer.close();
374         }
375         catch ( final IOException e ) {
376             e.printStackTrace();
377         }
378         ForesterUtil.fatalError( gsdi.PRG_NAME, msg );
379     }
380
381     private static void print_help() {
382         System.out.println( "Usage: " + gsdi.PRG_NAME
383                 + " [-options] <gene tree in phyloXML format> <species tree> <outfile>" );
384         System.out.println();
385         System.out.println( "Options:" );
386         System.out.println( " -" + gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION
387                 + ": to allow stripping of gene tree nodes without a matching species" );
388         System.out.println( " -" + gsdi.MOST_PARSIMONIOUS_OPTION
389                 + ": use most parimonious duplication model for GSDI: " );
390         System.out.println( "     assign nodes as speciations which would otherwise be assiged" );
391         System.out.println( "     as potential duplications due to polytomies in the species tree" );
392         System.out.println( " -" + gsdi.GUESS_FORMAT_OF_SPECIES_TREE
393                 + ": to allow species tree in other formats than phyloXML (i.e. Newick, NHX, Nexus)" );
394         System.out.println( " -" + gsdi.GSDIR_OPTION
395                 + ": to use GSDIR algorithm instead of GSDI algorithm (re-rooting)" );
396         System.out.println( " -" + TRANSFER_TAXONOMY_OPTION
397                 + ": to transfer taxonomic data from species tree to gene tree\n" );
398         System.out.println();
399         System.out.println( "Gene tree:" );
400         System.out.println( " in phyloXM format, with taxonomy and sequence data in appropriate fields" );
401         System.out.println();
402         System.out.println( "Species tree:" );
403         System.out.println( " in phyloXML format (unless option -" + gsdi.GUESS_FORMAT_OF_SPECIES_TREE + " is used)" );
404         System.out.println();
405         System.out.println( "Example: gsdi -" + ALLOW_STRIPPING_OF_GENE_TREE_OPTION
406                 + " gene_tree.xml tree_of_life.xml out.xml" );
407         System.out.println();
408     }
409
410     private static void printMappedNodesToLog( final EasyWriter log_writer, final GSDII gsdi ) throws IOException {
411         final SortedSet<String> ss = new TreeSet<String>();
412         for( final PhylogenyNode n : gsdi.getMappedExternalSpeciesTreeNodes() ) {
413             ss.add( n.toString() );
414         }
415         log_writer.println( "The following " + ss.size() + " species were used: " );
416         for( final String s : ss ) {
417             log_writer.println( "  " + s );
418         }
419     }
420
421     private static void printStrippedGeneTreeNodesToLog( final EasyWriter log_writer, final GSDII gsdi )
422             throws IOException {
423         final SortedMap<String, Integer> sm = new TreeMap<String, Integer>();
424         for( final PhylogenyNode n : gsdi.getStrippedExternalGeneTreeNodes() ) {
425             final String s = n.toString();
426             if ( sm.containsKey( s ) ) {
427                 sm.put( s, sm.get( s ) + 1 );
428             }
429             else {
430                 sm.put( s, 1 );
431             }
432         }
433         log_writer.println( "The following " + sm.size() + " nodes were stripped from the gene tree: " );
434         for( final String s : sm.keySet() ) {
435             final int count = sm.get( s );
436             if ( count == 1 ) {
437                 log_writer.println( "  " + s );
438             }
439             else {
440                 log_writer.println( "  " + s + " [" + count + "]" );
441             }
442         }
443     }
444
445     private static void writeToRemappedFile( final File out_file,
446                                              final SortedSet<String> remapped,
447                                              final EasyWriter log_writer ) throws IOException {
448         final File file = new File( ForesterUtil.removeSuffix( out_file.toString() ) + REMAPPED_SUFFIX );
449         final EasyWriter remapped_writer = ForesterUtil.createEasyWriter( file );
450         for( final String s : remapped ) {
451             remapped_writer.println( s );
452         }
453         remapped_writer.close();
454         System.out.println( "Wrote remapped gene tree species to      : " + file.getCanonicalPath() );
455         log_writer.println( "Wrote remapped gene tree species to      : " + file.getCanonicalPath() );
456     }
457 }