"rio" work
[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 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 HELP_OPTION_1                          = "help";
67     final static private String HELP_OPTION_2                          = "h";
68     final static private String SUFFIX_FOR_SPECIES_TREE_USED           = "_species_tree_used.xml";
69     final static private String LOGFILE_SUFFIX                         = "_gsdi_log.txt";
70     final static private String REMAPPED_SUFFIX                        = "_gsdi_remapped.txt";
71     final static private String PRG_NAME                               = "gsdi";
72     final static private String PRG_VERSION                            = "1.000";
73     final static private String PRG_DATE                               = "120629";
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() != 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.GSDIR_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         ALGORITHM base_algorithm = ALGORITHM.GSDI;
124         boolean most_parsimonous_duplication_model = false;
125         boolean allow_stripping_of_gene_tree = false;
126         if ( cla.isOptionSet( gsdi.GSDIR_OPTION ) ) {
127             base_algorithm = ALGORITHM.GSDIR;
128         }
129         if ( cla.isOptionSet( gsdi.MOST_PARSIMONIOUS_OPTION ) ) {
130             if ( base_algorithm == ALGORITHM.SDI ) {
131                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Cannot use most parsimonious duplication mode with SDI" );
132             }
133             most_parsimonous_duplication_model = true;
134         }
135         if ( cla.isOptionSet( gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION ) ) {
136             if ( base_algorithm == ALGORITHM.SDI ) {
137                 ForesterUtil.fatalError( gsdi.PRG_NAME, "Cannot allow stripping of gene tree with SDI" );
138             }
139             allow_stripping_of_gene_tree = true;
140         }
141         Phylogeny species_tree = null;
142         Phylogeny gene_tree = null;
143         File gene_tree_file = null;
144         File species_tree_file = null;
145         File out_file = null;
146         File log_file = null;
147         EasyWriter log_writer = null;
148         try {
149             gene_tree_file = cla.getFile( 0 );
150             species_tree_file = cla.getFile( 1 );
151             out_file = cla.getFile( 2 );
152             log_file = new File( ForesterUtil.removeSuffix( out_file.toString() ) + LOGFILE_SUFFIX );
153         }
154         catch ( final IllegalArgumentException e ) {
155             ForesterUtil.fatalError( gsdi.PRG_NAME, "error in command line: " + e.getMessage() );
156         }
157         if ( ForesterUtil.isReadableFile( gene_tree_file ) != null ) {
158             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( gene_tree_file ) );
159         }
160         if ( ForesterUtil.isReadableFile( species_tree_file ) != null ) {
161             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isReadableFile( species_tree_file ) );
162         }
163         if ( ForesterUtil.isWritableFile( out_file ) != null ) {
164             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( out_file ) );
165         }
166         if ( ForesterUtil.isWritableFile( log_file ) != null ) {
167             ForesterUtil.fatalError( gsdi.PRG_NAME, ForesterUtil.isWritableFile( log_file ) );
168         }
169         try {
170             log_writer = ForesterUtil.createEasyWriter( log_file );
171         }
172         catch ( final IOException e ) {
173             ForesterUtil.fatalError( gsdi.PRG_NAME, "Failed to create [" + log_file + "]: " + e.getMessage() );
174         }
175         try {
176             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
177             gene_tree = factory.create( gene_tree_file, new PhyloXmlParser() )[ 0 ];
178         }
179         catch ( final IOException e ) {
180             fatalError( "error",
181                         "failed to read gene tree from [" + gene_tree_file + "]: " + e.getMessage(),
182                         log_writer );
183         }
184         try {
185             species_tree = SDIutil.parseSpeciesTree( gene_tree,
186                                                      species_tree_file,
187                                                      REPLACE_UNDERSCORES_IN_NH_SPECIES_TREE,
188                                                      true,
189                                                      TAXONOMY_EXTRACTION.NO );
190         }
191         catch ( final PhyloXmlDataFormatException e ) {
192             fatalError( "user error",
193                         "failed to transfer general node name, in [" + species_tree_file + "]: " + e.getMessage(),
194                         log_writer );
195         }
196         catch ( final SDIException e ) {
197             fatalError( "user error", e.getMessage(), log_writer );
198         }
199         catch ( final IOException e ) {
200             fatalError( "error",
201                         "Failed to read species tree from [" + species_tree_file + "]: " + e.getMessage(),
202                         log_writer );
203         }
204         gene_tree.setRooted( true );
205         species_tree.setRooted( true );
206         if ( !gene_tree.isCompletelyBinary() ) {
207             fatalError( "user error", "gene tree is not completely binary", log_writer );
208         }
209         if ( base_algorithm == ALGORITHM.SDI ) {
210             if ( !species_tree.isCompletelyBinary() ) {
211                 fatalError( "user error",
212                             "species tree is not completely binary, use GSDI or GSDIR instead",
213                             log_writer );
214             }
215         }
216         log_writer.println( PRG_NAME + " - " + PRG_DESC );
217         log_writer.println( "  version         : " + PRG_VERSION );
218         log_writer.println( "  date            : " + PRG_DATE );
219         log_writer.println( "  forester version: " + ForesterConstants.FORESTER_VERSION );
220         log_writer.println();
221         log_writer.println( "Start time                               : "
222                 + new SimpleDateFormat( "yyyyMMdd HH:mm:ss" ).format( new Date() ) );
223         System.out.println( "Start time                               : "
224                 + new SimpleDateFormat( "yyyyMMdd HH:mm:ss" ).format( new Date() ) );
225         log_writer.println( "Gene tree file                           : " + gene_tree_file.getCanonicalPath() );
226         System.out.println( "Gene tree file                           : " + gene_tree_file.getCanonicalPath() );
227         log_writer.println( "Gene tree name                           : "
228                 + ( ForesterUtil.isEmpty( gene_tree.getName() ) ? "" : gene_tree.getName() ) );
229         System.out.println( "Gene tree name                           : "
230                 + ( ForesterUtil.isEmpty( gene_tree.getName() ) ? "" : gene_tree.getName() ) );
231         log_writer.println( "Species tree file                        : " + species_tree_file.getCanonicalPath() );
232         System.out.println( "Species tree file                        : " + species_tree_file.getCanonicalPath() );
233         log_writer.println( "Species tree name                        : "
234                 + ( ForesterUtil.isEmpty( species_tree.getName() ) ? "" : gene_tree.getName() ) );
235         System.out.println( "Species tree name                        : "
236                 + ( ForesterUtil.isEmpty( species_tree.getName() ) ? "" : gene_tree.getName() ) );
237         GSDII gsdii = null;
238         final long start_time = new Date().getTime();
239         try {
240             if ( base_algorithm == ALGORITHM.GSDI ) {
241                 System.out.println( "Algorithm       : GSDI" );
242                 log_writer.println( "Algorithm       : GSDI" );
243             }
244             else if ( base_algorithm == ALGORITHM.GSDIR ) {
245                 System.out.println( "Algorithm       : GSDIR" );
246                 log_writer.println( "Algorithm       : GSDIR" );
247             }
248             System.out.println( "Use most parsimonous duplication model   : " + most_parsimonous_duplication_model );
249             System.out.println( "Allow stripping of gene tree nodes       : " + allow_stripping_of_gene_tree );
250             log_writer.println( "Use most parsimonous duplication model   : " + most_parsimonous_duplication_model );
251             log_writer.println( "Allow stripping of gene tree nodes       : " + allow_stripping_of_gene_tree );
252             log_writer.flush();
253             if ( base_algorithm == ALGORITHM.GSDI ) {
254                 gsdii = new GSDI( gene_tree,
255                                   species_tree,
256                                   most_parsimonous_duplication_model,
257                                   allow_stripping_of_gene_tree,
258                                   true );
259             }
260             else if ( base_algorithm == ALGORITHM.GSDIR ) {
261                 gsdii = new GSDIR( gene_tree, species_tree, allow_stripping_of_gene_tree, true );
262             }
263         }
264         catch ( final SDIException e ) {
265             fatalError( "user error", e.getLocalizedMessage(), log_writer );
266         }
267         catch ( final IOException e ) {
268             fatalError( "error", e.toString(), log_writer );
269         }
270         catch ( final Exception e ) {
271             e.printStackTrace();
272             fatalError( "unexpected error", e.toString(), log_writer );
273         }
274         System.out.println( "Running time (excluding I/O)             : " + ( new Date().getTime() - start_time )
275                 + "ms" );
276         log_writer.println( "Running time (excluding I/O)             : " + ( new Date().getTime() - start_time )
277                 + "ms" );
278         System.out.println( "Mapping based on                         : " + gsdii.getTaxCompBase() );
279         log_writer.println( "Mapping based on                         : " + gsdii.getTaxCompBase() );
280         if ( ( base_algorithm == ALGORITHM.GSDIR ) ) {
281             final GSDIR gsdir = ( GSDIR ) gsdii;
282             System.out.println( "Duplications sum statistics              : " + gsdir.getMinDuplicationsSum() );
283             log_writer.println( "Duplications sum statistics              : " + gsdir.getMinDuplicationsSum() );
284         }
285         try {
286             final PhylogenyWriter writer = new PhylogenyWriter();
287             if ( base_algorithm == ALGORITHM.GSDIR ) {
288                 writer.toPhyloXML( out_file,
289                                    ( ( GSDIR ) gsdii ).getMinDuplicationsSumGeneTrees(),
290                                    0,
291                                    ForesterUtil.LINE_SEPARATOR );
292             }
293             else {
294                 writer.toPhyloXML( out_file, gene_tree, 0 );
295             }
296         }
297         catch ( final IOException e ) {
298             ForesterUtil.fatalError( PRG_NAME,
299                                      "Failed to write to [" + out_file.getCanonicalPath() + "]: " + e.getMessage() );
300         }
301         System.out.println( "Wrote resulting gene tree to             : " + out_file.getCanonicalPath() );
302         log_writer.println( "Wrote resulting gene tree to             : " + out_file.getCanonicalPath() );
303         final File species_tree_used_file = new File( ForesterUtil.removeSuffix( out_file.toString() )
304                 + SUFFIX_FOR_SPECIES_TREE_USED );
305         try {
306             final PhylogenyWriter writer = new PhylogenyWriter();
307             writer.toPhyloXML( species_tree_used_file, species_tree, 0 );
308         }
309         catch ( final IOException e ) {
310             ForesterUtil.fatalError( PRG_NAME, "Failed to write to [" + species_tree_used_file.getCanonicalPath()
311                     + "]: " + e.getMessage() );
312         }
313         System.out.println( "Wrote (stripped) species tree to         : " + species_tree_used_file.getCanonicalPath() );
314         log_writer.println( "Wrote (stripped) species tree to         : " + species_tree_used_file.getCanonicalPath() );
315         if ( ( gsdii.getReMappedScientificNamesFromGeneTree() != null )
316                 && !gsdii.getReMappedScientificNamesFromGeneTree().isEmpty() ) {
317             System.out.println( "Number of gene tree species remapped     : "
318                     + gsdii.getReMappedScientificNamesFromGeneTree().size() );
319             log_writer.println( "Number of gene tree species remapped     : "
320                     + gsdii.getReMappedScientificNamesFromGeneTree().size() );
321             writeToRemappedFile( out_file, gsdii.getReMappedScientificNamesFromGeneTree(), log_writer );
322         }
323         System.out.println( "Number of external nodes in gene tree    : " + gene_tree.getNumberOfExternalNodes() );
324         log_writer.println( "Number of external nodes in gene tree    : " + gene_tree.getNumberOfExternalNodes() );
325         System.out.println( "Number of external nodes in species tree : " + species_tree.getNumberOfExternalNodes() );
326         log_writer.println( "Number of external nodes in species tree : " + species_tree.getNumberOfExternalNodes() );
327         final int poly = PhylogenyMethods.countNumberOfPolytomies( species_tree );
328         System.out.println( "Number of polytomies in species tree     : " + poly );
329         log_writer.println( "Number of polytomies in species tree     : " + poly );
330         System.out.println( "External nodes stripped from gene tree   : "
331                 + gsdii.getStrippedExternalGeneTreeNodes().size() );
332         log_writer.println( "External nodes stripped from gene tree   : "
333                 + gsdii.getStrippedExternalGeneTreeNodes().size() );
334         System.out.println( "External nodes stripped from species tree: " + gsdii.getStrippedSpeciesTreeNodes().size() );
335         log_writer.println( "External nodes stripped from species tree: " + gsdii.getStrippedSpeciesTreeNodes().size() );
336         System.out.println();
337         System.out.println( "Number of speciations                    : " + gsdii.getSpeciationsSum() );
338         log_writer.println( "Number of speciations                    : " + gsdii.getSpeciationsSum() );
339         if ( ( base_algorithm == ALGORITHM.GSDIR ) ) {
340             final GSDIR gsdir = ( GSDIR ) gsdii;
341             System.out.println( "Minimal number of duplications           : " + gsdir.getMinDuplicationsSum() );
342             log_writer.println( "Minimal number of duplications           : " + gsdir.getMinDuplicationsSum() );
343         }
344         else if ( ( base_algorithm == ALGORITHM.GSDI ) ) {
345             final GSDI gsdi = ( GSDI ) gsdii;
346             System.out.println( "Number of duplications                   : " + gsdi.getDuplicationsSum() );
347             log_writer.println( "Number of duplications                   : " + gsdi.getDuplicationsSum() );
348             if ( !most_parsimonous_duplication_model ) {
349                 final int u = gsdi.getSpeciationOrDuplicationEventsSum();
350                 System.out.println( "Number of potential duplications         : " + u );
351                 log_writer.println( "Number of potential duplications         : " + u );
352             }
353         }
354         log_writer.println();
355         printMappedNodesToLog( log_writer, gsdii );
356         log_writer.println();
357         printStrippedGeneTreeNodesToLog( log_writer, gsdii );
358         System.out.println();
359         System.out.println( "Wrote log to                             : " + log_file.getCanonicalPath() );
360         System.out.println();
361         log_writer.close();
362     }
363
364     private static void fatalError( final String type, final String msg, final EasyWriter log_writer ) {
365         try {
366             log_writer.flush();
367             log_writer.println();
368             log_writer.print( type.toUpperCase() + ": " );
369             log_writer.println( msg );
370             log_writer.close();
371         }
372         catch ( final IOException e ) {
373             e.printStackTrace();
374         }
375         ForesterUtil.fatalError( gsdi.PRG_NAME, msg );
376     }
377
378     private static void print_help() {
379         System.out.println( "Usage: " + gsdi.PRG_NAME
380                 + " [-options] <gene tree in phyloXML format> <species tree> <outfile>" );
381         System.out.println();
382         System.out.println( "Options:" );
383         System.out.println( " -" + gsdi.ALLOW_STRIPPING_OF_GENE_TREE_OPTION
384                 + ": to allow stripping of gene tree nodes without a matching species" );
385         System.out.println( " -" + gsdi.MOST_PARSIMONIOUS_OPTION
386                 + ": use most parimonious duplication model for GSDI: " );
387         System.out.println( "     assign nodes as speciations which would otherwise be assiged" );
388         System.out.println( "     as potential duplications due to polytomies in the species tree" );
389         System.out.println( " -" + gsdi.GUESS_FORMAT_OF_SPECIES_TREE
390                 + ": to allow species tree in other formats than phyloXML (i.e. Newick, NHX, Nexus)" );
391         System.out.println( " -" + gsdi.GSDIR_OPTION
392                 + ": to use GSDIR algorithm instead of GSDI algorithm (re-rooting)" );
393         System.out.println();
394         System.out.println( "Gene tree:" );
395         System.out.println( " in phyloXM format, with taxonomy and sequence data in appropriate fields" );
396         System.out.println();
397         System.out.println( "Species tree:" );
398         System.out.println( " in phyloXML format (unless option -" + gsdi.GUESS_FORMAT_OF_SPECIES_TREE + " is used)" );
399         System.out.println();
400         System.out.println( "Example: gsdi -" + ALLOW_STRIPPING_OF_GENE_TREE_OPTION
401                 + " gene_tree.xml tree_of_life.xml out.xml" );
402         System.out.println();
403     }
404
405     private static void printMappedNodesToLog( final EasyWriter log_writer, final GSDII gsdi ) throws IOException {
406         final SortedSet<String> ss = new TreeSet<String>();
407         for( final PhylogenyNode n : gsdi.getMappedExternalSpeciesTreeNodes() ) {
408             ss.add( n.toString() );
409         }
410         log_writer.println( "The following " + ss.size() + " species were used: " );
411         for( final String s : ss ) {
412             log_writer.println( "  " + s );
413         }
414     }
415
416     private static void printStrippedGeneTreeNodesToLog( final EasyWriter log_writer, final GSDII gsdi )
417             throws IOException {
418         final SortedMap<String, Integer> sm = new TreeMap<String, Integer>();
419         for( final PhylogenyNode n : gsdi.getStrippedExternalGeneTreeNodes() ) {
420             final String s = n.toString();
421             if ( sm.containsKey( s ) ) {
422                 sm.put( s, sm.get( s ) + 1 );
423             }
424             else {
425                 sm.put( s, 1 );
426             }
427         }
428         log_writer.println( "The following " + sm.size() + " nodes were stripped from the gene tree: " );
429         for( final String s : sm.keySet() ) {
430             final int count = sm.get( s );
431             if ( count == 1 ) {
432                 log_writer.println( "  " + s );
433             }
434             else {
435                 log_writer.println( "  " + s + " [" + count + "]" );
436             }
437         }
438     }
439
440     private static void writeToRemappedFile( final File out_file,
441                                              final SortedSet<String> remapped,
442                                              final EasyWriter log_writer ) throws IOException {
443         final File file = new File( ForesterUtil.removeSuffix( out_file.toString() ) + REMAPPED_SUFFIX );
444         final EasyWriter remapped_writer = ForesterUtil.createEasyWriter( file );
445         for( final String s : remapped ) {
446             remapped_writer.println( s );
447         }
448         remapped_writer.close();
449         System.out.println( "Wrote remapped gene tree species to      : " + file.getCanonicalPath() );
450         log_writer.println( "Wrote remapped gene tree species to      : " + file.getCanonicalPath() );
451     }
452 }