38efa35c45705301af4fb546ec39df50e0dd613c
[jalview.git] / forester / java / src / org / forester / rio / 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: www.phylosoft.org/forester
27
28 package org.forester.rio;
29
30 import java.io.File;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.util.ArrayList;
34 import java.util.Collections;
35 import java.util.HashMap;
36 import java.util.HashSet;
37 import java.util.List;
38 import java.util.Set;
39 import java.util.SortedSet;
40 import java.util.TreeSet;
41
42 import org.forester.datastructures.IntMatrix;
43 import org.forester.io.parsers.PhylogenyParser;
44 import org.forester.io.parsers.nhx.NHXParser;
45 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
46 import org.forester.io.parsers.util.ParserUtils;
47 import org.forester.phylogeny.Phylogeny;
48 import org.forester.phylogeny.PhylogenyMethods;
49 import org.forester.phylogeny.PhylogenyNode;
50 import org.forester.phylogeny.data.Taxonomy;
51 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
52 import org.forester.phylogeny.factories.PhylogenyFactory;
53 import org.forester.sdi.GSDI;
54 import org.forester.sdi.GSDIR;
55 import org.forester.sdi.SDIException;
56 import org.forester.sdi.SDIR;
57 import org.forester.sdi.SDIutil;
58 import org.forester.sdi.SDIutil.ALGORITHM;
59 import org.forester.sdi.SDIutil.TaxonomyComparisonBase;
60 import org.forester.util.BasicDescriptiveStatistics;
61 import org.forester.util.ForesterUtil;
62
63 public final class RIO {
64
65     public static final int                  DEFAULT_RANGE = -1;
66     private Phylogeny[]                      _analyzed_gene_trees;
67     private List<PhylogenyNode>              _removed_gene_tree_nodes;
68     private int                              _ext_nodes;
69     private TaxonomyComparisonBase           _gsdir_tax_comp_base;
70     private final StringBuilder              _log;
71     private final BasicDescriptiveStatistics _duplications_stats;
72     private final boolean                    _produce_log;
73     private final boolean                    _verbose;
74     private final REROOTING                  _rerooting;
75
76     private RIO( final Phylogeny[] gene_trees,
77                  final Phylogeny species_tree,
78                  final ALGORITHM algorithm,
79                  final REROOTING rerooting,
80                  final String outgroup,
81                  int first,
82                  int last,
83                  final boolean produce_log,
84                  final boolean verbose ) throws IOException, SDIException, RIOException {
85         if ( ( last == DEFAULT_RANGE ) && ( first >= 0 ) ) {
86             last = gene_trees.length - 1;
87         }
88         else if ( ( first == DEFAULT_RANGE ) && ( last >= 0 ) ) {
89             first = 0;
90         }
91         removeSingleDescendentsNodes( species_tree, verbose );
92         checkPreconditions( gene_trees, species_tree, rerooting, outgroup, first, last );
93         _produce_log = produce_log;
94         _verbose = verbose;
95         _rerooting = rerooting;
96         _ext_nodes = -1;
97         _log = new StringBuilder();
98         _gsdir_tax_comp_base = null;
99         _analyzed_gene_trees = null;
100         _removed_gene_tree_nodes = null;
101         _duplications_stats = new BasicDescriptiveStatistics();
102         inferOrthologs( gene_trees, species_tree, algorithm, outgroup, first, last );
103     }
104
105     public final Phylogeny[] getAnalyzedGeneTrees() {
106         return _analyzed_gene_trees;
107     }
108
109     public final BasicDescriptiveStatistics getDuplicationsStatistics() {
110         return _duplications_stats;
111     }
112
113     /**
114      * Returns the numbers of number of ext nodes in gene trees analyzed (after
115      * stripping).
116      * 
117      * @return number of ext nodes in gene trees analyzed (after stripping)
118      */
119     public final int getExtNodesOfAnalyzedGeneTrees() {
120         return _ext_nodes;
121     }
122
123     public final TaxonomyComparisonBase getGSDIRtaxCompBase() {
124         return _gsdir_tax_comp_base;
125     }
126
127     public final StringBuilder getLog() {
128         return _log;
129     }
130
131     public final List<PhylogenyNode> getRemovedGeneTreeNodes() {
132         return _removed_gene_tree_nodes;
133     }
134
135     private final void inferOrthologs( final Phylogeny[] gene_trees,
136                                        final Phylogeny species_tree,
137                                        final ALGORITHM algorithm,
138                                        final String outgroup,
139                                        final int first,
140                                        final int last ) throws SDIException, RIOException, FileNotFoundException,
141             IOException {
142         if ( algorithm == ALGORITHM.SDIR ) {
143             // Removes from species_tree all species not found in gene_tree.
144             PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( gene_trees[ 0 ], species_tree );
145             if ( species_tree.isEmpty() ) {
146                 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
147             }
148         }
149         final Phylogeny[] my_gene_trees;
150         if ( ( first >= 0 ) && ( last >= first ) && ( last < gene_trees.length ) ) {
151             my_gene_trees = new Phylogeny[ 1 + last - first ];
152             int c = 0;
153             for( int i = first; i <= last; ++i ) {
154                 my_gene_trees[ c++ ] = gene_trees[ i ];
155             }
156         }
157         else {
158             my_gene_trees = gene_trees;
159         }
160         if ( log() ) {
161             preLog( gene_trees, species_tree, algorithm, outgroup, first, last );
162         }
163         if ( _verbose && ( my_gene_trees.length >= 4 ) ) {
164             System.out.println();
165         }
166         _analyzed_gene_trees = new Phylogeny[ my_gene_trees.length ];
167         int gene_tree_ext_nodes = 0;
168         for( int i = 0; i < my_gene_trees.length; ++i ) {
169             final Phylogeny gt = my_gene_trees[ i ];
170             if ( _verbose && ( my_gene_trees.length > 4 ) ) {
171                 ForesterUtil.updateProgress( ( ( double ) i ) / my_gene_trees.length );
172             }
173             if ( i == 0 ) {
174                 gene_tree_ext_nodes = gt.getNumberOfExternalNodes();
175             }
176             else if ( gene_tree_ext_nodes != gt.getNumberOfExternalNodes() ) {
177                 throw new RIOException( "gene tree #" + ( i + 1 ) + " has a different number of external nodes ("
178                         + gt.getNumberOfExternalNodes() + ") than the preceding gene trees (" + gene_tree_ext_nodes
179                         + ")" );
180             }
181             if ( algorithm == ALGORITHM.SDIR ) {
182                 // Removes from gene_tree all species not found in species_tree.
183                 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( species_tree, gt );
184                 if ( gt.isEmpty() ) {
185                     throw new RIOException( "failed to establish species based mapping between gene and species trees" );
186                 }
187             }
188             _analyzed_gene_trees[ i ] = performOrthologInference( gt, species_tree, algorithm, outgroup, i );
189         }
190         if ( log() ) {
191             postLog( species_tree );
192         }
193         if ( _verbose && ( my_gene_trees.length > 4 ) ) {
194             System.out.println();
195             System.out.println();
196         }
197     }
198
199     private final boolean log() {
200         return _produce_log;
201     }
202
203     private final void log( final String s ) {
204         _log.append( s );
205         _log.append( ForesterUtil.LINE_SEPARATOR );
206     }
207
208     private final void logRemovedGeneTreeNodes() {
209         log( "Species stripped from gene trees:" );
210         final SortedSet<String> rn = new TreeSet<String>();
211         for( final PhylogenyNode n : getRemovedGeneTreeNodes() ) {
212             final Taxonomy t = n.getNodeData().getTaxonomy();
213             switch ( getGSDIRtaxCompBase() ) {
214                 case CODE: {
215                     rn.add( t.getTaxonomyCode() );
216                     break;
217                 }
218                 case ID: {
219                     rn.add( t.getIdentifier().toString() );
220                     break;
221                 }
222                 case SCIENTIFIC_NAME: {
223                     rn.add( t.getScientificName() );
224                     break;
225                 }
226             }
227         }
228         for( final String s : rn ) {
229             log( s );
230         }
231         log( "" );
232     }
233
234     private final Phylogeny performOrthologInference( final Phylogeny gene_tree,
235                                                       final Phylogeny species_tree,
236                                                       final ALGORITHM algorithm,
237                                                       final String outgroup,
238                                                       final int i ) throws SDIException, RIOException {
239         final Phylogeny assigned_tree;
240         switch ( algorithm ) {
241             case SDIR: {
242                 assigned_tree = performOrthologInferenceBySDI( gene_tree, species_tree );
243                 break;
244             }
245             case GSDIR: {
246                 assigned_tree = performOrthologInferenceByGSDI( gene_tree, species_tree, outgroup, i );
247                 break;
248             }
249             default: {
250                 throw new IllegalArgumentException( "illegal algorithm: " + algorithm );
251             }
252         }
253         if ( i == 0 ) {
254             _ext_nodes = assigned_tree.getNumberOfExternalNodes();
255         }
256         else if ( _ext_nodes != assigned_tree.getNumberOfExternalNodes() ) {
257             throw new RIOException( "after stripping gene tree #" + ( i + 1 )
258                     + " has a different number of external nodes (" + assigned_tree.getNumberOfExternalNodes()
259                     + ") than the preceding gene trees (" + _ext_nodes + ")" );
260         }
261         return assigned_tree;
262     }
263
264     private final Phylogeny performOrthologInferenceByGSDI( final Phylogeny gene_tree,
265                                                             final Phylogeny species_tree,
266                                                             final String outgroup,
267                                                             final int i ) throws SDIException, RIOException {
268         final Phylogeny assigned_tree;
269         if ( _rerooting == REROOTING.BY_ALGORITHM ) {
270             final GSDIR gsdir = new GSDIR( gene_tree, species_tree, true, i == 0 );
271             final List<Phylogeny> assigned_trees = gsdir.getMinDuplicationsSumGeneTrees();
272             if ( i == 0 ) {
273                 _removed_gene_tree_nodes = gsdir.getStrippedExternalGeneTreeNodes();
274                 for( final PhylogenyNode r : _removed_gene_tree_nodes ) {
275                     if ( !r.getNodeData().isHasTaxonomy() ) {
276                         throw new RIOException( "node with no (appropriate) taxonomic information found in gene tree #1: "
277                                 + r.toString() );
278                     }
279                 }
280             }
281             final List<Integer> shortests = GSDIR.getIndexesOfShortestTree( assigned_trees );
282             assigned_tree = assigned_trees.get( shortests.get( 0 ) );
283             if ( log() ) {
284                 writeStatsToLog( i, gsdir, shortests );
285             }
286             if ( i == 0 ) {
287                 _gsdir_tax_comp_base = gsdir.getTaxCompBase();
288             }
289             _duplications_stats.addValue( gsdir.getMinDuplicationsSum() );
290         }
291         else {
292             if ( _rerooting == REROOTING.MIDPOINT ) {
293                 PhylogenyMethods.midpointRoot( gene_tree );
294             }
295             else if ( _rerooting == REROOTING.OUTGROUP ) {
296                 final PhylogenyNode n = gene_tree.getNode( outgroup );
297                 gene_tree.reRoot( n );
298             }
299             final GSDI gsdi = new GSDI( gene_tree, species_tree, true, true, true );
300             _removed_gene_tree_nodes = gsdi.getStrippedExternalGeneTreeNodes();
301             for( final PhylogenyNode r : _removed_gene_tree_nodes ) {
302                 if ( !r.getNodeData().isHasTaxonomy() ) {
303                     throw new RIOException( "node with no (appropriate) taxonomic information found in gene tree #1: "
304                             + r.toString() );
305                 }
306             }
307             assigned_tree = gene_tree;
308             if ( i == 0 ) {
309                 _gsdir_tax_comp_base = gsdi.getTaxCompBase();
310             }
311             _duplications_stats.addValue( gsdi.getDuplicationsSum() );
312         }
313         return assigned_tree;
314     }
315
316     private final Phylogeny performOrthologInferenceBySDI( final Phylogeny gene_tree, final Phylogeny species_tree )
317             throws SDIException {
318         final SDIR sdir = new SDIR();
319         return sdir.infer( gene_tree, species_tree, false, true, true, true, 1 )[ 0 ];
320     }
321
322     private final void postLog( final Phylogeny species_tree ) {
323         log( "" );
324         if ( getRemovedGeneTreeNodes().size() > 0 ) {
325             logRemovedGeneTreeNodes();
326         }
327         log( "Species tree external nodes (after stripping)   : " + species_tree.getNumberOfExternalNodes() );
328         log( "Species tree polytomies (after stripping)       : "
329                 + PhylogenyMethods.countNumberOfPolytomies( species_tree ) );
330         log( "Taxonomy linking based on                       : " + getGSDIRtaxCompBase() );
331         final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#" );
332         log( "Gene trees analyzed                             : " + _duplications_stats.getN() );
333         log( "Mean number of duplications                     : " + df.format( _duplications_stats.arithmeticMean() )
334                 + " (sd: " + df.format( _duplications_stats.sampleStandardDeviation() ) + ")" );
335         if ( _duplications_stats.getN() > 3 ) {
336             log( "Median number of duplications                   : " + df.format( _duplications_stats.median() ) );
337         }
338         log( "Minimum duplications                            : " + ( int ) _duplications_stats.getMin() );
339         log( "Maximum duplications                            : " + ( int ) _duplications_stats.getMax() );
340     }
341
342     private final void preLog( final Phylogeny[] gene_trees,
343                                final Phylogeny species_tree,
344                                final ALGORITHM algorithm,
345                                final String outgroup,
346                                final int first,
347                                final int last ) {
348         log( "Number of gene tree (total)                     : " + gene_trees.length );
349         log( "Algorithm                                       : " + algorithm );
350         log( "Species tree external nodes (prior to stripping): " + species_tree.getNumberOfExternalNodes() );
351         log( "Species tree polytomies (prior to stripping)    : "
352                 + PhylogenyMethods.countNumberOfPolytomies( species_tree ) );
353         String rs = "";
354         switch ( _rerooting ) {
355             case BY_ALGORITHM: {
356                 rs = "minimizing duplications";
357                 break;
358             }
359             case MIDPOINT: {
360                 rs = "midpoint";
361                 break;
362             }
363             case OUTGROUP: {
364                 rs = "outgroup: " + outgroup;
365                 break;
366             }
367             case NONE: {
368                 rs = "none";
369                 break;
370             }
371         }
372         log( "Re-rooting                                      : " + rs );
373         if ( ( first >= 0 ) || ( last >= 0 ) ) {
374             log( "Gene trees analyzed range                       : " + first + "-" + last );
375         }
376         if ( _rerooting == REROOTING.BY_ALGORITHM ) {
377             writeLogSubHeader();
378         }
379     }
380
381     private final void writeLogSubHeader() {
382         _log.append( ForesterUtil.LINE_SEPARATOR );
383         _log.append( "Some information about duplication numbers in gene trees:" );
384         _log.append( ForesterUtil.LINE_SEPARATOR );
385         _log.append( "#" );
386         _log.append( "\t" );
387         _log.append( "re-rootings with minimal number of duplications" );
388         _log.append( "/" );
389         _log.append( "total root placements" );
390         _log.append( "\t" );
391         _log.append( "duplications range" );
392         _log.append( "\t" );
393         _log.append( "mininal duplication re-rootings with shortest tree heigth" );
394         _log.append( ForesterUtil.LINE_SEPARATOR );
395     }
396
397     private final void writeStatsToLog( final int i, final GSDIR gsdir, final List<Integer> shortests ) {
398         final BasicDescriptiveStatistics stats = gsdir.getDuplicationsSumStats();
399         _log.append( i );
400         _log.append( "\t" );
401         _log.append( gsdir.getMinDuplicationsSumGeneTrees().size() );
402         _log.append( "/" );
403         _log.append( stats.getN() );
404         _log.append( "\t" );
405         _log.append( ( int ) stats.getMin() );
406         _log.append( "-" );
407         _log.append( ( int ) stats.getMax() );
408         _log.append( "\t" );
409         _log.append( shortests.size() );
410         _log.append( ForesterUtil.LINE_SEPARATOR );
411     }
412
413     public final static IntMatrix calculateOrthologTable( final Phylogeny[] analyzed_gene_trees, final boolean sort )
414             throws RIOException {
415         final List<String> labels = new ArrayList<String>();
416         final Set<String> labels_set = new HashSet<String>();
417         String label;
418         for( final PhylogenyNode n : analyzed_gene_trees[ 0 ].getExternalNodes() ) {
419             if ( n.getNodeData().isHasSequence() && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
420                 label = n.getNodeData().getSequence().getName();
421             }
422             else if ( n.getNodeData().isHasSequence()
423                     && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getSymbol() ) ) {
424                 label = n.getNodeData().getSequence().getSymbol();
425             }
426             else if ( !ForesterUtil.isEmpty( n.getName() ) ) {
427                 label = n.getName();
428             }
429             else {
430                 throw new RIOException( "node " + n + " has no appropriate label" );
431             }
432             if ( labels_set.contains( label ) ) {
433                 throw new RIOException( "label " + label + " is not unique" );
434             }
435             labels_set.add( label );
436             labels.add( label );
437         }
438         if ( sort ) {
439             Collections.sort( labels );
440         }
441         final IntMatrix m = new IntMatrix( labels );
442         int counter = 0;
443         for( final Phylogeny gt : analyzed_gene_trees ) {
444             counter++;
445             PhylogenyMethods.preOrderReId( gt );
446             final HashMap<String, PhylogenyNode> map = PhylogenyMethods.createNameToExtNodeMap( gt );
447             for( int x = 0; x < m.size(); ++x ) {
448                 final String mx = m.getLabel( x );
449                 final PhylogenyNode nx = map.get( mx );
450                 if ( nx == null ) {
451                     throw new RIOException( "node \"" + mx + "\" not present in gene tree #" + counter );
452                 }
453                 String my;
454                 PhylogenyNode ny;
455                 for( int y = 0; y < m.size(); ++y ) {
456                     my = m.getLabel( y );
457                     ny = map.get( my );
458                     if ( ny == null ) {
459                         throw new RIOException( "node \"" + my + "\" not present in gene tree #" + counter );
460                     }
461                     if ( !PhylogenyMethods.calculateLCAonTreeWithIdsInPreOrder( nx, ny ).isDuplication() ) {
462                         m.inreaseByOne( x, y );
463                     }
464                 }
465             }
466         }
467         return m;
468     }
469
470     public final static RIO executeAnalysis( final File gene_trees_file,
471                                              final File species_tree_file,
472                                              final ALGORITHM algorithm,
473                                              final REROOTING rerooting,
474                                              final String outgroup,
475                                              final int first,
476                                              final int last,
477                                              final boolean produce_log,
478                                              final boolean verbose ) throws IOException, SDIException, RIOException {
479         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
480         final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
481         if ( p instanceof NHXParser ) {
482             final NHXParser nhx = ( NHXParser ) p;
483             nhx.setReplaceUnderscores( false );
484             nhx.setIgnoreQuotes( true );
485             nhx.setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.YES );
486         }
487         final Phylogeny[] gene_trees = factory.create( gene_trees_file, p );
488         if ( gene_trees.length < 1 ) {
489             throw new RIOException( "\"" + gene_trees_file + "\" is devoid of appropriate gene trees" );
490         }
491         final Phylogeny species_tree = SDIutil.parseSpeciesTree( gene_trees[ 0 ],
492                                                                  species_tree_file,
493                                                                  false,
494                                                                  true,
495                                                                  TAXONOMY_EXTRACTION.NO );
496         return new RIO( gene_trees, species_tree, algorithm, rerooting, outgroup, first, last, produce_log, verbose );
497     }
498
499     public final static RIO executeAnalysis( final File gene_trees_file,
500                                              final Phylogeny species_tree,
501                                              final ALGORITHM algorithm,
502                                              final REROOTING rerooting,
503                                              final String outgroup,
504                                              final boolean produce_log,
505                                              final boolean verbose ) throws IOException, SDIException, RIOException {
506         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
507         final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
508         if ( p instanceof NHXParser ) {
509             final NHXParser nhx = ( NHXParser ) p;
510             nhx.setReplaceUnderscores( false );
511             nhx.setIgnoreQuotes( true );
512             nhx.setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.YES );
513         }
514         final Phylogeny[] gene_trees = factory.create( gene_trees_file, p );
515         return new RIO( gene_trees,
516                         species_tree,
517                         algorithm,
518                         rerooting,
519                         outgroup,
520                         DEFAULT_RANGE,
521                         DEFAULT_RANGE,
522                         produce_log,
523                         verbose );
524     }
525
526     public final static RIO executeAnalysis( final File gene_trees_file,
527                                              final Phylogeny species_tree,
528                                              final ALGORITHM algorithm,
529                                              final REROOTING rerooting,
530                                              final String outgroup,
531                                              final int first,
532                                              final int last,
533                                              final boolean produce_log,
534                                              final boolean verbose ) throws IOException, SDIException, RIOException {
535         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
536         final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
537         if ( p instanceof NHXParser ) {
538             final NHXParser nhx = ( NHXParser ) p;
539             nhx.setReplaceUnderscores( false );
540             nhx.setIgnoreQuotes( true );
541             nhx.setTaxonomyExtraction( NHXParser.TAXONOMY_EXTRACTION.YES );
542         }
543         final Phylogeny[] gene_trees = factory.create( gene_trees_file, p );
544         if ( gene_trees.length < 1 ) {
545             throw new RIOException( "\"" + gene_trees_file + "\" is devoid of appropriate gene trees" );
546         }
547         return new RIO( gene_trees, species_tree, algorithm, rerooting, outgroup, first, last, produce_log, verbose );
548     }
549
550     public final static RIO executeAnalysis( final Phylogeny[] gene_trees, final Phylogeny species_tree )
551             throws IOException, SDIException, RIOException {
552         return new RIO( gene_trees,
553                         species_tree,
554                         ALGORITHM.GSDIR,
555                         REROOTING.BY_ALGORITHM,
556                         null,
557                         DEFAULT_RANGE,
558                         DEFAULT_RANGE,
559                         false,
560                         false );
561     }
562
563     public final static RIO executeAnalysis( final Phylogeny[] gene_trees,
564                                              final Phylogeny species_tree,
565                                              final ALGORITHM algorithm,
566                                              final REROOTING rerooting,
567                                              final String outgroup,
568                                              final boolean produce_log,
569                                              final boolean verbose ) throws IOException, SDIException, RIOException {
570         return new RIO( gene_trees,
571                         species_tree,
572                         algorithm,
573                         rerooting,
574                         outgroup,
575                         DEFAULT_RANGE,
576                         DEFAULT_RANGE,
577                         produce_log,
578                         verbose );
579     }
580
581     public final static RIO executeAnalysis( final Phylogeny[] gene_trees,
582                                              final Phylogeny species_tree,
583                                              final ALGORITHM algorithm,
584                                              final REROOTING rerooting,
585                                              final String outgroup,
586                                              final int first,
587                                              final int last,
588                                              final boolean produce_log,
589                                              final boolean verbose ) throws IOException, SDIException, RIOException {
590         return new RIO( gene_trees, species_tree, algorithm, rerooting, outgroup, first, last, produce_log, verbose );
591     }
592
593     private final static void checkPreconditions( final Phylogeny[] gene_trees,
594                                                   final Phylogeny species_tree,
595                                                   final REROOTING rerooting,
596                                                   final String outgroup,
597                                                   final int first,
598                                                   final int last ) throws RIOException {
599         if ( !species_tree.isRooted() ) {
600             throw new RIOException( "species tree is not rooted" );
601         }
602         if ( !( ( last == DEFAULT_RANGE ) && ( first == DEFAULT_RANGE ) )
603                 && ( ( last < first ) || ( last >= gene_trees.length ) || ( last < 0 ) || ( first < 0 ) ) ) {
604             throw new RIOException( "attempt to set range (0-based) of gene to analyze to: from " + first + " to "
605                     + last + " (out of " + gene_trees.length + ")" );
606         }
607         if ( ( rerooting == REROOTING.OUTGROUP ) && ForesterUtil.isEmpty( outgroup ) ) {
608             throw new RIOException( "outgroup not set for midpoint rooting" );
609         }
610         if ( ( rerooting != REROOTING.OUTGROUP ) && !ForesterUtil.isEmpty( outgroup ) ) {
611             throw new RIOException( "outgroup only used for midpoint rooting" );
612         }
613         if ( ( rerooting == REROOTING.MIDPOINT )
614                 && ( PhylogenyMethods.calculateMaxDistanceToRoot( gene_trees[ 0 ] ) <= 0 ) ) {
615             throw new RIOException( "attempt to use midpoint rooting on gene trees which seem to have no (positive) branch lengths (cladograms)" );
616         }
617         if ( rerooting == REROOTING.OUTGROUP ) {
618             try {
619                 gene_trees[ 0 ].getNode( outgroup );
620             }
621             catch ( final IllegalArgumentException e ) {
622                 throw new RIOException( "cannot perform re-rooting by outgroup: " + e.getLocalizedMessage() );
623             }
624         }
625     }
626
627     private final static void removeSingleDescendentsNodes( final Phylogeny species_tree, final boolean verbose ) {
628         final int o = PhylogenyMethods.countNumberOfOneDescendantNodes( species_tree );
629         if ( o > 0 ) {
630             if ( verbose ) {
631                 System.out.println( "warning: species tree has " + o
632                         + " internal nodes with only one descendent which are therefore going to be removed" );
633             }
634             PhylogenyMethods.deleteInternalNodesWithOnlyOneDescendent( species_tree );
635         }
636     }
637
638     public enum REROOTING {
639         NONE, BY_ALGORITHM, MIDPOINT, OUTGROUP;
640     }
641 }