in progress...
[jalview.git] / forester / java / src / org / forester / application / rio.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // Copyright (C) 2000-2001 Washington University School of Medicine
8 // and Howard Hughes Medical Institute
9 // All rights reserved
10 //
11 // This library is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU Lesser General Public
13 // License as published by the Free Software Foundation; either
14 // version 2.1 of the License, or (at your option) any later version.
15 //
16 // This library is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 // Lesser General Public License for more details.
20 //
21 // You should have received a copy of the GNU Lesser General Public
22 // License along with this library; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 //
25 // Contact: phylosoft @ gmail . com
26 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
27
28 package org.forester.application;
29
30 import java.io.File;
31 import java.io.FilenameFilter;
32 import java.io.IOException;
33 import java.math.RoundingMode;
34 import java.util.ArrayList;
35 import java.util.Arrays;
36 import java.util.List;
37
38 import org.forester.datastructures.IntMatrix;
39 import org.forester.io.parsers.IteratingPhylogenyParser;
40 import org.forester.io.parsers.PhylogenyParser;
41 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
42 import org.forester.io.parsers.nhx.NHXParser;
43 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
44 import org.forester.io.parsers.phyloxml.PhyloXmlParser;
45 import org.forester.io.parsers.util.ParserUtils;
46 import org.forester.io.writers.PhylogenyWriter;
47 import org.forester.phylogeny.Phylogeny;
48 import org.forester.rio.RIO;
49 import org.forester.rio.RIO.REROOTING;
50 import org.forester.rio.RIOException;
51 import org.forester.sdi.SDIException;
52 import org.forester.sdi.SDIutil.ALGORITHM;
53 import org.forester.util.BasicDescriptiveStatistics;
54 import org.forester.util.CommandLineArguments;
55 import org.forester.util.EasyWriter;
56 import org.forester.util.ForesterUtil;
57
58 public class rio {
59
60     final static private String PRG_NAME                 = "rio";
61     final static private String PRG_VERSION              = "4.000 beta 11";
62     final static private String PRG_DATE                 = "170406";
63     final static private String E_MAIL                   = "phyloxml@gmail.com";
64     final static private String WWW                      = "https://sites.google.com/site/cmzmasek/home/software/forester";
65     final static private String HELP_OPTION_1            = "help";
66     final static private String HELP_OPTION_2            = "h";
67     final static private String GT_FIRST                 = "f";
68     final static private String GT_LAST                  = "l";
69     final static private String REROOTING_OPT            = "r";
70     final static private String OUTGROUP                 = "o";
71     final static private String RETURN_SPECIES_TREE      = "s";
72     final static private String RETURN_BEST_GENE_TREE    = "g";
73     final static private String USE_SDIR                 = "b";
74     final static private String TRANSFER_TAXONOMY_OPTION = "t";
75
76     public static void main( final String[] args ) {
77         ForesterUtil.printProgramInformation( PRG_NAME,
78                                               "resampled inference of orthologs",
79                                               PRG_VERSION,
80                                               PRG_DATE,
81                                               E_MAIL,
82                                               WWW,
83                                               ForesterUtil.getForesterLibraryInformation() );
84         CommandLineArguments cla = null;
85         try {
86             cla = new CommandLineArguments( args );
87         }
88         catch ( final Exception e ) {
89             ForesterUtil.fatalError( e.getMessage() );
90         }
91         if ( cla.isOptionSet( HELP_OPTION_1 ) || cla.isOptionSet( HELP_OPTION_2 ) || ( args.length == 0 ) ) {
92             printHelp();
93         }
94         if ( ( args.length < 3 ) || ( args.length > 11 ) || ( cla.getNumberOfNames() < 3 ) ) {
95             System.out.println();
96             System.out.println( "error: incorrect number of arguments" );
97             System.out.println();
98             printHelp();
99         }
100         final List<String> allowed_options = new ArrayList<String>();
101         allowed_options.add( GT_FIRST );
102         allowed_options.add( GT_LAST );
103         allowed_options.add( REROOTING_OPT );
104         allowed_options.add( OUTGROUP );
105         allowed_options.add( USE_SDIR );
106         allowed_options.add( RETURN_SPECIES_TREE );
107         allowed_options.add( RETURN_BEST_GENE_TREE );
108         allowed_options.add( TRANSFER_TAXONOMY_OPTION );
109         final String dissallowed_options = cla.validateAllowedOptionsAsString( allowed_options );
110         if ( dissallowed_options.length() > 0 ) {
111             ForesterUtil.fatalError( "unknown option(s): " + dissallowed_options );
112         }
113         final File gene_trees_file = cla.getFile( 0 );
114         final File species_tree_file = cla.getFile( 1 );
115         File orthology_outtable = cla.getFile( 2 );
116         File logfile;
117         if ( cla.getNumberOfNames() > 3 ) {
118             logfile = cla.getFile( 3 );
119             if ( logfile.exists() ) {
120                 ForesterUtil.fatalError( "\"" + logfile + "\" already exists" );
121             }
122         }
123         else {
124             logfile = null;
125         }
126         boolean sdir = false;
127         if ( cla.isOptionSet( USE_SDIR ) ) {
128             if ( cla.isOptionHasAValue( USE_SDIR ) ) {
129                 ForesterUtil.fatalError( "no value allowed for -" + USE_SDIR );
130             }
131             sdir = true;
132             if ( logfile != null ) {
133                 ForesterUtil.fatalError( "no logfile output for SDIR algorithm" );
134             }
135         }
136         String outgroup = null;
137         if ( cla.isOptionSet( OUTGROUP ) ) {
138             if ( !cla.isOptionHasAValue( OUTGROUP ) ) {
139                 ForesterUtil.fatalError( "no value for -" + OUTGROUP );
140             }
141             if ( sdir ) {
142                 ForesterUtil.fatalError( "no outgroup option for SDIR algorithm" );
143             }
144             outgroup = cla.getOptionValueAsCleanString( OUTGROUP );
145         }
146         REROOTING rerooting = REROOTING.BY_ALGORITHM;
147         if ( cla.isOptionSet( REROOTING_OPT ) ) {
148             if ( !cla.isOptionHasAValue( REROOTING_OPT ) ) {
149                 ForesterUtil.fatalError( "no value for -" + REROOTING_OPT );
150             }
151             if ( sdir ) {
152                 ForesterUtil.fatalError( "no re-rooting option for SDIR algorithm" );
153             }
154             final String rerooting_str = cla.getOptionValueAsCleanString( REROOTING_OPT ).toLowerCase();
155             if ( rerooting_str.equals( "none" ) ) {
156                 rerooting = REROOTING.NONE;
157             }
158             else if ( rerooting_str.equals( "midpoint" ) ) {
159                 rerooting = REROOTING.MIDPOINT;
160             }
161             else if ( rerooting_str.equals( "outgroup" ) ) {
162                 rerooting = REROOTING.OUTGROUP;
163             }
164             else {
165                 ForesterUtil
166                         .fatalError( "values for re-rooting are: 'none', 'midpoint', or 'outgroup' (minizming duplications is default)" );
167             }
168         }
169         if ( ForesterUtil.isEmpty( outgroup ) && ( rerooting == REROOTING.OUTGROUP ) ) {
170             ForesterUtil.fatalError( "selected re-rooting by outgroup, but outgroup not set" );
171         }
172         if ( !ForesterUtil.isEmpty( outgroup ) && ( rerooting != REROOTING.OUTGROUP ) ) {
173             ForesterUtil.fatalError( "outgroup set, but selected re-rooting by other approach" );
174         }
175         int gt_first = RIO.DEFAULT_RANGE;
176         int gt_last = RIO.DEFAULT_RANGE;
177         if ( cla.isOptionSet( GT_FIRST ) ) {
178             if ( !cla.isOptionHasAValue( GT_FIRST ) ) {
179                 ForesterUtil.fatalError( "no value for -" + GT_FIRST );
180             }
181             if ( sdir ) {
182                 ForesterUtil.fatalError( "no gene tree range option for SDIR algorithm" );
183             }
184             try {
185                 gt_first = cla.getOptionValueAsInt( GT_FIRST );
186             }
187             catch ( final IOException e ) {
188                 ForesterUtil.fatalError( "could not parse integer for -" + GT_FIRST + " option" );
189             }
190             if ( gt_first < 0 ) {
191                 ForesterUtil.fatalError( "attempt to set index of first tree to analyze to: " + gt_first );
192             }
193         }
194         if ( cla.isOptionSet( GT_LAST ) ) {
195             if ( !cla.isOptionHasAValue( GT_LAST ) ) {
196                 ForesterUtil.fatalError( "no value for -" + GT_LAST );
197             }
198             if ( sdir ) {
199                 ForesterUtil.fatalError( "no gene tree range option for SDIR algorithm" );
200             }
201             try {
202                 gt_last = cla.getOptionValueAsInt( GT_LAST );
203             }
204             catch ( final IOException e ) {
205                 ForesterUtil.fatalError( "could not parse integer for -" + GT_LAST + " option" );
206             }
207             if ( gt_last < 0 ) {
208                 ForesterUtil.fatalError( "attempt to set index of last tree to analyze to: " + gt_last );
209             }
210         }
211         if ( ( ( gt_last != RIO.DEFAULT_RANGE ) && ( gt_first != RIO.DEFAULT_RANGE ) ) && ( ( gt_last < gt_first ) ) ) {
212             ForesterUtil.fatalError( "attempt to set range (0-based) of gene to analyze to: from " + gt_first + " to "
213                     + gt_last );
214         }
215         File return_species_tree = null;
216         if ( !sdir && cla.isOptionSet( RETURN_SPECIES_TREE ) ) {
217             if ( !cla.isOptionHasAValue( RETURN_SPECIES_TREE ) ) {
218                 ForesterUtil.fatalError( "no value for -" + RETURN_SPECIES_TREE );
219             }
220             final String s = cla.getOptionValueAsCleanString( RETURN_SPECIES_TREE );
221             return_species_tree = new File( s );
222             if ( return_species_tree.exists() ) {
223                 ForesterUtil.fatalError( "\"" + return_species_tree + "\" already exists" );
224             }
225         }
226         File return_gene_tree = null;
227         if ( !sdir && cla.isOptionSet( RETURN_BEST_GENE_TREE ) ) {
228             if ( !cla.isOptionHasAValue( RETURN_BEST_GENE_TREE ) ) {
229                 ForesterUtil.fatalError( "no value for -" + RETURN_BEST_GENE_TREE );
230             }
231             final String s = cla.getOptionValueAsCleanString( RETURN_BEST_GENE_TREE );
232             return_gene_tree = new File( s );
233             if ( return_gene_tree.exists() ) {
234                 ForesterUtil.fatalError( "\"" + return_gene_tree + "\" already exists" );
235             }
236         }
237         boolean transfer_taxonomy = false;
238         if ( !sdir && cla.isOptionSet( TRANSFER_TAXONOMY_OPTION ) ) {
239             if ( return_gene_tree == null ) {
240                 ForesterUtil.fatalError( "no point in transferring taxonomy data without returning best gene tree" );
241             }
242             transfer_taxonomy = true;
243         }
244         ForesterUtil.fatalErrorIfFileNotReadable( gene_trees_file );
245         ForesterUtil.fatalErrorIfFileNotReadable( species_tree_file );
246         if ( orthology_outtable.exists() ) {
247             ForesterUtil.fatalError( "\"" + orthology_outtable + "\" already exists" );
248         }
249         long time = 0;
250         try {
251             System.out.println( "Gene trees                          :\t" + gene_trees_file.getCanonicalPath() );
252             System.out.println( "Species tree                        :\t" + species_tree_file.getCanonicalPath() );
253         }
254         catch ( final IOException e ) {
255             ForesterUtil.fatalError( e.getLocalizedMessage() );
256         }
257         System.out.println( "All vs all orthology results table  :\t" + orthology_outtable );
258         if ( logfile != null ) {
259             System.out.println( "Logfile                             :\t" + logfile );
260         }
261         if ( gt_first != RIO.DEFAULT_RANGE ) {
262             System.out.println( "First gene tree to analyze          :\t" + gt_first );
263         }
264         if ( gt_last != RIO.DEFAULT_RANGE ) {
265             System.out.println( "Last gene tree to analyze           :\t" + gt_last );
266         }
267         String rerooting_str = "";
268         switch ( rerooting ) {
269             case BY_ALGORITHM: {
270                 rerooting_str = "by minimizing duplications";
271                 break;
272             }
273             case MIDPOINT: {
274                 rerooting_str = "by midpoint method";
275                 break;
276             }
277             case OUTGROUP: {
278                 rerooting_str = "by outgroup: " + outgroup;
279                 break;
280             }
281             case NONE: {
282                 rerooting_str = "none";
283                 break;
284             }
285         }
286         System.out.println( "Re-rooting                          : \t" + rerooting_str );
287         if ( !sdir ) {
288             System.out.println( "Non binary species tree             :\tallowed" );
289         }
290         else {
291             System.out.println( "Non binary species tree             :\tdisallowed" );
292         }
293         if ( return_species_tree != null ) {
294             System.out.println( "Write used species tree to          :\t" + return_species_tree );
295         }
296         if ( return_gene_tree != null ) {
297             System.out.println( "Write best gene tree to             :\t" + return_gene_tree );
298             System.out.println( "Transfer taxonomic data             :\t" + transfer_taxonomy );
299         }
300         time = System.currentTimeMillis();
301         final ALGORITHM algorithm;
302         if ( sdir ) {
303             algorithm = ALGORITHM.SDIR;
304         }
305         else {
306             algorithm = ALGORITHM.GSDIR;
307         }
308         //////////////////////////
309         //////////////////////////
310         final boolean use_gene_trees_dir = true;
311         if ( use_gene_trees_dir ) {
312             final String LOGFILE_SUFFIX = "_RIO_log.tsv";
313             final String STRIPPED_SPECIES_TREE_SUFFIX = "_RIO_sst.xml";
314             final String ORTHO_OUTTABLE_SUFFIX = "_RIO_o_table.tsv";
315             final String OUT_GENE_TREE_SUFFIX = "_RIO_gene_tree.xml";
316             final String gene_trees_suffix = ".mlt";
317             final File indir = new File( "in" );
318             final File outdir = new File( "out" );
319             if ( !indir.exists() ) {
320                 ForesterUtil.fatalError( PRG_NAME, "in-directory [" + indir + "] does not exist" );
321             }
322             if ( !indir.isDirectory() ) {
323                 ForesterUtil.fatalError( PRG_NAME, "in-directory [" + indir + "] is not a directory" );
324             }
325             if ( outdir.exists() ) {
326                 if ( !outdir.isDirectory() ) {
327                     ForesterUtil.fatalError( PRG_NAME,
328                                              "out-directory [" + outdir + "] already exists but is not a directory" );
329                 }
330             }
331             else {
332                 final boolean success = outdir.mkdirs();
333                 if ( !success ) {
334                     ForesterUtil.fatalError( PRG_NAME, "could not create out-directory [" + outdir + "]" );
335                 }
336             }
337             final String species_tree_file_name = species_tree_file.getName();
338             final File gene_trees_files[] = indir.listFiles( new FilenameFilter() {
339
340                 @Override
341                 public boolean accept( final File dir, final String name ) {
342                     return ( ( name.endsWith( gene_trees_suffix ) ) && !( name.equals( species_tree_file_name ) ) );
343                 }
344             } );
345             if ( gene_trees_files.length < 1 ) {
346                 ForesterUtil.fatalError( PRG_NAME,
347                                          "in-directory [" + indir
348                                                  + "] does not contain any gene tree files with suffix "
349                                                  + gene_trees_suffix );
350             }
351             Arrays.sort( gene_trees_files );
352             System.out.print( "NAME" );
353             System.out.print( '\t' );
354             System.out.print( "EXT NODES" );
355             System.out.print( '\t' );
356             System.out.print( "MEAN DUP" );
357             System.out.print( '\t' );
358             System.out.print( "MEAN DUP SD" );
359             System.out.print( '\t' );
360             System.out.print( "MEDIAN DUP" );
361             System.out.print( '\t' );
362             System.out.print( "MIN DUP" );
363             System.out.print( '\t' );
364             System.out.print( "MAX DUP" );
365             System.out.print( '\t' );
366             System.out.print( "REMOVED EXT NODES" );
367             System.out.print( '\t' );
368             System.out.print( "N" );
369             System.out.println();
370             for( final File gf : gene_trees_files ) {
371                 String outname = gf.getName();
372                 if ( outname.indexOf( "." ) > 0 ) {
373                     outname = outname.substring( 0, outname.lastIndexOf( "." ) );
374                 }
375                 try {
376                     x( gf,
377                        species_tree_file,
378                        new File( outdir.getCanonicalFile() + "/" + outname + ORTHO_OUTTABLE_SUFFIX ),
379                        new File( outdir.getCanonicalFile() + "/" + outname + LOGFILE_SUFFIX ),
380                        outgroup,
381                        rerooting,
382                        gt_first,
383                        gt_last,
384                        new File( outdir.getCanonicalFile() + "/" + outname + STRIPPED_SPECIES_TREE_SUFFIX ),
385                        new File( outdir.getCanonicalFile() + "/" + outname + OUT_GENE_TREE_SUFFIX ),
386                        transfer_taxonomy,
387                        algorithm,
388                        true );
389                 }
390                 catch ( IOException e ) {
391                     // TODO Auto-generated catch block
392                     e.printStackTrace();
393                 }
394             }
395         }
396         else {
397             x( gene_trees_file,
398                species_tree_file,
399                orthology_outtable,
400                logfile,
401                outgroup,
402                rerooting,
403                gt_first,
404                gt_last,
405                return_species_tree,
406                return_gene_tree,
407                transfer_taxonomy,
408                algorithm,
409                false );
410         }
411         ////////////////////
412         ///////////////////
413         if ( !use_gene_trees_dir ) {
414             time = System.currentTimeMillis() - time;
415             System.out.println( "Time                                :\t" + time + "ms" );
416         }
417         System.exit( 0 );
418     }
419
420     private static final void x( final File gene_trees_file,
421                                  final File species_tree_file,
422                                  final File orthology_outtable,
423                                  final File logfile,
424                                  final String outgroup,
425                                  final REROOTING rerooting,
426                                  final int gt_first,
427                                  final int gt_last,
428                                  final File return_species_tree,
429                                  final File return_gene_tree,
430                                  final boolean transfer_taxonomy,
431                                  final ALGORITHM algorithm,
432                                  final boolean use_gene_trees_dir ) {
433         try {
434             final RIO rio;
435             boolean iterating = false;
436             final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
437             if ( p instanceof PhyloXmlParser ) {
438                 rio = RIO.executeAnalysis( gene_trees_file,
439                                            species_tree_file,
440                                            algorithm,
441                                            rerooting,
442                                            outgroup,
443                                            gt_first,
444                                            gt_last,
445                                            logfile != null,
446                                            true,
447                                            transfer_taxonomy );
448             }
449             else {
450                 iterating = true;
451                 if ( p instanceof NHXParser ) {
452                     final NHXParser nhx = ( NHXParser ) p;
453                     nhx.setReplaceUnderscores( false );
454                     nhx.setIgnoreQuotes( true );
455                     nhx.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGGRESSIVE );
456                 }
457                 else if ( p instanceof NexusPhylogeniesParser ) {
458                     final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) p;
459                     nex.setReplaceUnderscores( false );
460                     nex.setIgnoreQuotes( true );
461                     nex.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGGRESSIVE );
462                 }
463                 else {
464                     throw new RuntimeException( "unknown parser type: " + p );
465                 }
466                 final IteratingPhylogenyParser ip = ( IteratingPhylogenyParser ) p;
467                 ip.setSource( gene_trees_file );
468                 rio = RIO.executeAnalysis( ip,
469                                            species_tree_file,
470                                            algorithm,
471                                            rerooting,
472                                            outgroup,
473                                            gt_first,
474                                            gt_last,
475                                            logfile != null,
476                                            !use_gene_trees_dir,
477                                            transfer_taxonomy );
478             }
479             if ( !use_gene_trees_dir ) {
480                 if ( algorithm == ALGORITHM.GSDIR ) {
481                     System.out.println( "Taxonomy linking based on           :\t" + rio.getGSDIRtaxCompBase() );
482                 }
483             }
484             final IntMatrix m;
485             if ( iterating ) {
486                 m = rio.getOrthologTable();
487             }
488             else {
489                 m = RIO.calculateOrthologTable( rio.getAnalyzedGeneTrees(), true );
490             }
491             final BasicDescriptiveStatistics stats = rio.getDuplicationsStatistics();
492             writeTable( orthology_outtable, stats.getN(), m, !use_gene_trees_dir );
493             if ( ( algorithm != ALGORITHM.SDIR ) && ( logfile != null ) ) {
494                 writeLogFile( logfile,
495                               rio,
496                               species_tree_file,
497                               gene_trees_file,
498                               orthology_outtable,
499                               PRG_NAME,
500                               PRG_VERSION,
501                               PRG_DATE,
502                               ForesterUtil.getForesterLibraryInformation(),
503                               !use_gene_trees_dir );
504             }
505             if ( return_species_tree != null ) {
506                 writeTree( rio.getSpeciesTree(),
507                            return_species_tree,
508                            use_gene_trees_dir ? null : "Wrote (stripped) species tree to    :\t" );
509             }
510             if ( return_gene_tree != null ) {
511                 writeTree( rio.getMinDuplicationsGeneTree(),
512                            return_gene_tree,
513                            use_gene_trees_dir ? null : "Wrote one min duplication gene tree :\t" );
514             }
515             final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.##" );
516             final int min = ( int ) stats.getMin();
517             final int max = ( int ) stats.getMax();
518             final int median = ( int ) stats.median();
519             int min_count = 0;
520             int max_count = 0;
521             int median_count = 0;
522             for( double d : stats.getData() ) {
523                 if ( ( ( int ) d ) == min ) {
524                     ++min_count;
525                 }
526                 if ( ( ( int ) d ) == max ) {
527                     ++max_count;
528                 }
529                 if ( ( ( int ) d ) == median ) {
530                     ++median_count;
531                 }
532             }
533             final double min_count_percentage = ( 100.0 * min_count ) / stats.getN();
534             final double max_count_percentage = ( 100.0 * max_count ) / stats.getN();
535             final double median_count_percentage = ( 100.0 * median_count ) / stats.getN();
536             if ( use_gene_trees_dir ) {
537                 String name = gene_trees_file.getName();
538                 if ( name.indexOf( "." ) > 0 ) {
539                     name = name.substring( 0, name.lastIndexOf( "." ) );
540                 }
541                 System.out.print( name );
542                 System.out.print( '\t' );
543                 System.out.print( rio.getExtNodesOfAnalyzedGeneTrees() );
544                 System.out.print( '\t' );
545                 System.out.print( df.format( stats.arithmeticMean() ) );
546                 System.out.print( '\t' );
547                 System.out.print( df.format( stats.sampleStandardDeviation() ) );
548                 System.out.print( '\t' );
549                 if ( stats.getN() > 3 ) {
550                     System.out.print( df.format( median ) );
551                 }
552                 else {
553                     System.out.print( "" );
554                 }
555                 System.out.print( '\t' );
556                 System.out.print( min );
557                 System.out.print( '\t' );
558                 System.out.print( max );
559                 System.out.print( '\t' );
560                 System.out.print( rio.getRemovedGeneTreeNodes().size() );
561                 System.out.print( '\t' );
562                 System.out.print( stats.getN() );
563                 System.out.println();
564             }
565             else {
566                 System.out.println( "Gene tree internal nodes            :\t" + rio.getIntNodesOfAnalyzedGeneTrees() );
567                 System.out.println( "Gene tree external nodes            :\t" + rio.getExtNodesOfAnalyzedGeneTrees() );
568                 System.out.println( "Mean number of duplications         :\t" + df.format( stats.arithmeticMean() )
569                         + "\t" + df.format( ( 100.0 * stats.arithmeticMean() ) / rio.getIntNodesOfAnalyzedGeneTrees() )
570                         + "%\t(sd: " + df.format( stats.sampleStandardDeviation() ) + ")" );
571                 if ( stats.getN() > 3 ) {
572                     System.out.println( "Median number of duplications       :\t" + df.format( median ) + "\t"
573                             + df.format( ( 100.0 * median ) / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%" );
574                 }
575                 System.out.println( "Minimum duplications                :\t" + min + "\t"
576                         + df.format( ( 100.0 * min ) / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%" );
577                 System.out.println( "Maximum duplications                :\t" + ( int ) max + "\t"
578                         + df.format( ( 100.0 * max ) / rio.getIntNodesOfAnalyzedGeneTrees() ) + "%" );
579                 System.out.println( "Gene trees with median duplications :\t" + median_count + "\t"
580                         + df.format( median_count_percentage ) + "%" );
581                 System.out.println( "Gene trees with minimum duplications:\t" + min_count + "\t"
582                         + df.format( min_count_percentage ) + "%" );
583                 System.out.println( "Gene trees with maximum duplications:\t" + max_count + "\t"
584                         + df.format( max_count_percentage ) + "%" );
585                 System.out.println( "Removed ext gene tree nodes:\t" + rio.getRemovedGeneTreeNodes().size() );
586             }
587         }
588         catch ( final RIOException e ) {
589             ForesterUtil.fatalError( e.getLocalizedMessage() );
590         }
591         catch ( final SDIException e ) {
592             ForesterUtil.fatalError( e.getLocalizedMessage() );
593         }
594         catch ( final IOException e ) {
595             ForesterUtil.fatalError( e.getLocalizedMessage() );
596         }
597         catch ( final OutOfMemoryError e ) {
598             ForesterUtil.outOfMemoryError( e );
599         }
600         catch ( final Exception e ) {
601             ForesterUtil.unexpectedFatalError( e );
602         }
603         catch ( final Error e ) {
604             ForesterUtil.unexpectedFatalError( e );
605         }
606     }
607
608     private final static void printHelp() {
609         System.out.println( "Usage" );
610         System.out.println();
611         System.out.println( PRG_NAME
612                 + " [options] <gene trees infile> <species tree infile> <all vs all orthology table outfile> [logfile]" );
613         System.out.println();
614         System.out.println( " Options" );
615         System.out.println( "  -" + GT_FIRST + "=<first>     : first gene tree to analyze (0-based index)" );
616         System.out.println( "  -" + GT_LAST + "=<last>      : last gene tree to analyze (0-based index)" );
617         System.out.println( "  -" + REROOTING_OPT
618                 + "=<re-rooting>: re-rooting method for gene trees, possible values or 'none', 'midpoint'," );
619         System.out.println( "                   or 'outgroup' (default: by minizming duplications)" );
620         System.out.println( "  -" + OUTGROUP
621                 + "=<outgroup>  : for rooting by outgroup, name of outgroup (external gene tree node)" );
622         System.out
623                 .println( "  -" + RETURN_SPECIES_TREE + "=<outfile>   : to write the (stripped) species tree to file" );
624         System.out.println( "  -" + RETURN_BEST_GENE_TREE
625                 + "=<outfile>   : to write (one) minimal duplication gene tree to file" );
626         System.out.println( "  -" + TRANSFER_TAXONOMY_OPTION
627                 + "             : to transfer taxonomic data from species tree to returned minimal duplication gene tree\n"
628                 + "                   (if -" + RETURN_BEST_GENE_TREE + " option is used)" );
629         System.out.println( "  -" + USE_SDIR
630                 + "             : to use SDIR instead of GSDIR (faster, but non-binary species trees are" );
631         System.out.println( "                   disallowed, as are most options)" );
632         System.out.println();
633         System.out.println( " Formats" );
634         System.out
635                 .println( "  The gene trees, as well as the species tree, ideally are in phyloXML (www.phyloxml.org) format," );
636         System.out
637                 .println( "  but can also be in New Hamphshire (Newick) or Nexus format as long as species information can be" );
638         System.out
639                 .println( "  extracted from the gene names (e.g. \"HUMAN\" from \"BCL2_HUMAN\") and matched to a single species" );
640         System.out.println( "  in the species tree." );
641         System.out.println();
642         System.out.println( " Examples" );
643         System.out.println( "  rio gene_trees.nh species.xml outtable.tsv log.txt" );
644         System.out
645                 .println( "  rio -t -f=10 -l=100 -r=none -g=out_gene_tree.xml -s=stripped_species.xml gene_trees.xml species.xml outtable.tsv log.txt" );
646         System.out.println();
647         System.exit( -1 );
648     }
649
650     private static void writeLogFile( final File logfile,
651                                       final RIO rio,
652                                       final File species_tree_file,
653                                       final File gene_trees_file,
654                                       final File outtable,
655                                       final String prg_name,
656                                       final String prg_v,
657                                       final String prg_date,
658                                       final String f,
659                                       final boolean verbose )
660             throws IOException {
661         final EasyWriter out = ForesterUtil.createEasyWriter( logfile );
662         out.println( "# " + prg_name );
663         out.println( "# version : " + prg_v );
664         out.println( "# date    : " + prg_date );
665         out.println( "# based on: " + f );
666         out.println( "# ----------------------------------" );
667         out.println( "Gene trees                          :\t" + gene_trees_file.getCanonicalPath() );
668         out.println( "Species tree                        :\t" + species_tree_file.getCanonicalPath() );
669         out.println( "All vs all orthology table          :\t" + outtable.getCanonicalPath() );
670         out.flush();
671         out.println( rio.getLog().toString() );
672         out.close();
673         if ( verbose ) {
674             System.out.println( "Wrote log to                        :\t" + logfile.getCanonicalPath() );
675         }
676     }
677
678     private static void writeTable( final File table_outfile,
679                                     final int gene_trees_analyzed,
680                                     final IntMatrix m,
681                                     final boolean verbose )
682             throws IOException {
683         final EasyWriter w = ForesterUtil.createEasyWriter( table_outfile );
684         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.####" );
685         df.setDecimalSeparatorAlwaysShown( false );
686         df.setRoundingMode( RoundingMode.HALF_UP );
687         for( int i = 0; i < m.size(); ++i ) {
688             w.print( "\t" );
689             w.print( m.getLabel( i ) );
690         }
691         w.println();
692         for( int x = 0; x < m.size(); ++x ) {
693             w.print( m.getLabel( x ) );
694             for( int y = 0; y < m.size(); ++y ) {
695                 w.print( "\t" );
696                 if ( x == y ) {
697                     if ( m.get( x, y ) != gene_trees_analyzed ) {
698                         ForesterUtil.unexpectedFatalError( "diagonal value is off" );
699                     }
700                     w.print( "-" );
701                 }
702                 else {
703                     w.print( df.format( ( ( double ) m.get( x, y ) ) / gene_trees_analyzed ) );
704                 }
705             }
706             w.println();
707         }
708         w.close();
709         if ( verbose ) {
710             System.out.println( "Wrote table to                      :\t" + table_outfile.getCanonicalPath() );
711         }
712     }
713
714     private static void writeTree( final Phylogeny p, final File f, final String comment ) throws IOException {
715         final PhylogenyWriter writer = new PhylogenyWriter();
716         writer.toPhyloXML( f, p, 0 );
717         if ( comment != null ) {
718             System.out.println( comment + f.getCanonicalPath() );
719         }
720     }
721 }