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