2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
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
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.
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.
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
25 // Contact: phylosoft @ gmail . com
26 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
28 package org.forester.rio;
31 import java.io.FileNotFoundException;
32 import java.io.IOException;
33 import java.text.DecimalFormat;
34 import java.util.ArrayList;
35 import java.util.Collections;
36 import java.util.HashMap;
37 import java.util.HashSet;
38 import java.util.List;
40 import java.util.SortedSet;
41 import java.util.TreeSet;
43 import org.forester.datastructures.IntMatrix;
44 import org.forester.io.parsers.IteratingPhylogenyParser;
45 import org.forester.io.parsers.PhylogenyParser;
46 import org.forester.io.parsers.nexus.NexusPhylogeniesParser;
47 import org.forester.io.parsers.nhx.NHXParser;
48 import org.forester.io.parsers.nhx.NHXParser.TAXONOMY_EXTRACTION;
49 import org.forester.io.parsers.util.ParserUtils;
50 import org.forester.phylogeny.Phylogeny;
51 import org.forester.phylogeny.PhylogenyMethods;
52 import org.forester.phylogeny.PhylogenyNode;
53 import org.forester.phylogeny.data.Taxonomy;
54 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
55 import org.forester.phylogeny.factories.PhylogenyFactory;
56 import org.forester.sdi.GSDI;
57 import org.forester.sdi.GSDIR;
58 import org.forester.sdi.SDIException;
59 import org.forester.sdi.SDIR;
60 import org.forester.sdi.SDIutil;
61 import org.forester.sdi.SDIutil.ALGORITHM;
62 import org.forester.sdi.SDIutil.TaxonomyComparisonBase;
63 import org.forester.util.BasicDescriptiveStatistics;
64 import org.forester.util.ForesterUtil;
66 public final class RIO {
68 public static final int DEFAULT_RANGE = -1;
69 private static final int END_OF_GT = Integer.MAX_VALUE;
70 private static IntMatrix _m;
71 private Phylogeny[] _analyzed_gene_trees;
72 private List<PhylogenyNode> _removed_gene_tree_nodes;
73 private int _ext_nodes;
74 private int _int_nodes;
75 private TaxonomyComparisonBase _gsdir_tax_comp_base;
76 private final StringBuilder _log;
77 private final BasicDescriptiveStatistics _duplications_stats;
78 private final boolean _produce_log;
79 private final boolean _verbose;
80 private final REROOTING _rerooting;
81 private final Phylogeny _species_tree;
82 private Phylogeny _min_dub_gene_tree;
84 private RIO( final IteratingPhylogenyParser p,
85 final Phylogeny species_tree,
86 final ALGORITHM algorithm,
87 final REROOTING rerooting,
88 final String outgroup,
91 final boolean produce_log,
92 final boolean verbose,
93 final boolean transfer_taxonomy ) throws IOException, SDIException, RIOException {
94 if ( ( last == DEFAULT_RANGE ) && ( first >= 0 ) ) {
97 else if ( ( first == DEFAULT_RANGE ) && ( last >= 0 ) ) {
100 removeSingleDescendentsNodes( species_tree, verbose );
102 checkPreconditions( p, species_tree, rerooting, outgroup, first, last );
103 _produce_log = produce_log;
105 _rerooting = rerooting;
108 _log = new StringBuilder();
109 _gsdir_tax_comp_base = null;
110 _analyzed_gene_trees = null;
111 _removed_gene_tree_nodes = null;
112 _duplications_stats = new BasicDescriptiveStatistics();
114 inferOrthologs( p, species_tree, algorithm, outgroup, first, last, transfer_taxonomy );
115 _species_tree = species_tree;
118 private RIO( final Phylogeny[] gene_trees,
119 final Phylogeny species_tree,
120 final ALGORITHM algorithm,
121 final REROOTING rerooting,
122 final String outgroup,
125 final boolean produce_log,
126 final boolean verbose,
127 final boolean transfer_taxonomy ) throws IOException, SDIException, RIOException {
128 if ( ( last == DEFAULT_RANGE ) && ( first >= 0 ) ) {
129 last = gene_trees.length - 1;
131 else if ( ( first == DEFAULT_RANGE ) && ( last >= 0 ) ) {
134 removeSingleDescendentsNodes( species_tree, verbose );
135 checkPreconditions( gene_trees, species_tree, rerooting, outgroup, first, last );
136 _produce_log = produce_log;
138 _rerooting = rerooting;
141 _log = new StringBuilder();
142 _gsdir_tax_comp_base = null;
143 _analyzed_gene_trees = null;
144 _removed_gene_tree_nodes = null;
145 _duplications_stats = new BasicDescriptiveStatistics();
146 inferOrthologs( gene_trees, species_tree, algorithm, outgroup, first, last, transfer_taxonomy );
147 _species_tree = species_tree;
150 public final Phylogeny[] getAnalyzedGeneTrees() {
151 return _analyzed_gene_trees;
154 public final BasicDescriptiveStatistics getDuplicationsStatistics() {
155 return _duplications_stats;
159 * Returns the numbers of number of ext nodes in gene trees analyzed (after
162 * @return number of ext nodes in gene trees analyzed (after stripping)
164 public final int getExtNodesOfAnalyzedGeneTrees() {
168 public final TaxonomyComparisonBase getGSDIRtaxCompBase() {
169 return _gsdir_tax_comp_base;
173 * Returns the numbers of number of int nodes in gene trees analyzed (after
176 * @return number of int nodes in gene trees analyzed (after stripping)
178 public final int getIntNodesOfAnalyzedGeneTrees() {
182 public final StringBuilder getLog() {
186 final public Phylogeny getMinDuplicationsGeneTree() {
187 return _min_dub_gene_tree;
190 public final IntMatrix getOrthologTable() {
194 public final List<PhylogenyNode> getRemovedGeneTreeNodes() {
195 return _removed_gene_tree_nodes;
198 public final Phylogeny getSpeciesTree() {
199 return _species_tree;
202 private final void inferOrthologs( final IteratingPhylogenyParser parser,
203 final Phylogeny species_tree,
204 final ALGORITHM algorithm,
205 final String outgroup,
208 final boolean transfer_taxonomy ) throws SDIException, RIOException,
209 FileNotFoundException, IOException {
210 if ( !parser.hasNext() ) {
211 throw new RIOException( "no gene trees to analyze" );
214 preLog( -1, species_tree, algorithm, outgroup );
217 System.out.println();
219 int gene_tree_ext_nodes = 0;
222 final boolean no_range = ( first < 0 ) || ( last < first );
223 while ( parser.hasNext() ) {
224 final Phylogeny gt = parser.next();
225 if ( no_range || ( ( i >= first ) && ( i <= last ) ) ) {
226 if ( gt.isEmpty() ) {
227 throw new RIOException( "gene tree #" + i + " is empty" );
229 if ( gt.getNumberOfExternalNodes() == 1 ) {
230 throw new RIOException( "gene tree #" + i + " has only one external node" );
233 System.out.print( "\r" + i );
235 if ( counter == 0 ) {
236 if ( algorithm == ALGORITHM.SDIR ) {
237 // Removes from species_tree all species not found in gene_tree.
238 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( gt, species_tree );
239 if ( species_tree.isEmpty() ) {
240 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
243 gene_tree_ext_nodes = gt.getNumberOfExternalNodes();
245 else if ( gene_tree_ext_nodes != gt.getNumberOfExternalNodes() ) {
246 throw new RIOException( "gene tree #" + i + " has a different number of external nodes ("
247 + gt.getNumberOfExternalNodes() + ") than the preceding gene tree(s) ("
248 + gene_tree_ext_nodes + ")" );
250 if ( algorithm == ALGORITHM.SDIR ) {
251 // Removes from gene_tree all species not found in species_tree.
252 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( species_tree, gt );
253 if ( gt.isEmpty() ) {
254 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
257 final Phylogeny analyzed_gt = performOrthologInference( gt,
263 RIO.calculateOrthologTable( analyzed_gt, true, counter );
269 System.out.print( "\rGene trees analyzed :\t" + counter );
271 if ( ( first >= 0 ) && ( counter == 0 ) && ( i > 0 ) ) {
272 throw new RIOException( "attempt to analyze first gene tree #" + first + " in a set of " + i );
278 postLog( species_tree, first, ( first + counter ) - 1 );
281 System.out.println();
282 System.out.println();
286 private final void inferOrthologs( final Phylogeny[] gene_trees,
287 final Phylogeny species_tree,
288 final ALGORITHM algorithm,
289 final String outgroup,
292 final boolean transfer_taxonomy ) throws SDIException, RIOException,
293 FileNotFoundException, IOException {
294 if ( algorithm == ALGORITHM.SDIR ) {
295 // Removes from species_tree all species not found in gene_tree.
296 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( gene_trees[ 0 ], species_tree );
297 if ( species_tree.isEmpty() ) {
298 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
301 final Phylogeny[] my_gene_trees;
302 if ( ( first >= 0 ) && ( last >= first ) && ( last < gene_trees.length ) ) {
303 my_gene_trees = new Phylogeny[ ( 1 + last ) - first ];
305 for( int i = first; i <= last; ++i ) {
306 my_gene_trees[ c++ ] = gene_trees[ i ];
310 my_gene_trees = gene_trees;
313 preLog( gene_trees.length, species_tree, algorithm, outgroup );
315 if ( _verbose && ( my_gene_trees.length >= 4 ) ) {
316 System.out.println();
318 _analyzed_gene_trees = new Phylogeny[ my_gene_trees.length ];
319 int gene_tree_ext_nodes = 0;
320 for( int i = 0; i < my_gene_trees.length; ++i ) {
321 final Phylogeny gt = my_gene_trees[ i ];
322 if ( gt.isEmpty() ) {
323 throw new RIOException( "gene tree #" + i + " is empty" );
325 if ( gt.getNumberOfExternalNodes() == 1 ) {
326 throw new RIOException( "gene tree #" + i + " has only one external node" );
328 if ( _verbose && ( my_gene_trees.length > 4 ) ) {
329 ForesterUtil.updateProgress( ( ( double ) i ) / my_gene_trees.length );
332 gene_tree_ext_nodes = gt.getNumberOfExternalNodes();
334 else if ( gene_tree_ext_nodes != gt.getNumberOfExternalNodes() ) {
335 throw new RIOException( "gene tree #" + i + " has a different number of external nodes ("
336 + gt.getNumberOfExternalNodes() + ") than the preceding gene tree(s) (" + gene_tree_ext_nodes
339 if ( algorithm == ALGORITHM.SDIR ) {
340 // Removes from gene_tree all species not found in species_tree.
341 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( species_tree, gt );
342 if ( gt.isEmpty() ) {
343 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
346 _analyzed_gene_trees[ i ] = performOrthologInference( gt,
354 postLog( species_tree, first, last );
356 if ( _verbose && ( my_gene_trees.length > 4 ) ) {
357 System.out.println();
358 System.out.println();
362 private final boolean log() {
366 private final void log( final String s ) {
368 _log.append( ForesterUtil.LINE_SEPARATOR );
371 private final void logRemovedGeneTreeNodes() {
372 log( "Species stripped from gene trees:" );
373 final SortedSet<String> rn = new TreeSet<String>();
374 for( final PhylogenyNode n : getRemovedGeneTreeNodes() ) {
375 final Taxonomy t = n.getNodeData().getTaxonomy();
376 switch ( getGSDIRtaxCompBase() ) {
378 rn.add( t.getTaxonomyCode() );
382 rn.add( t.getIdentifier().toString() );
385 case SCIENTIFIC_NAME: {
386 rn.add( t.getScientificName() );
391 for( final String s : rn ) {
397 private final Phylogeny performOrthologInference( final Phylogeny gene_tree,
398 final Phylogeny species_tree,
399 final ALGORITHM algorithm,
400 final String outgroup,
402 final boolean transfer_taxonomy ) throws SDIException,
404 final Phylogeny assigned_tree;
405 switch ( algorithm ) {
407 assigned_tree = performOrthologInferenceBySDI( gene_tree, species_tree );
411 assigned_tree = performOrthologInferenceByGSDI( gene_tree, species_tree, outgroup, i, transfer_taxonomy );
415 throw new IllegalArgumentException( "illegal algorithm: " + algorithm );
419 _ext_nodes = assigned_tree.getNumberOfExternalNodes();
420 _int_nodes = assigned_tree.getNumberOfInternalNodes();
422 else if ( _ext_nodes != assigned_tree.getNumberOfExternalNodes() ) {
423 throw new RIOException( "after stripping gene tree #" + i + " has a different number of external nodes ("
424 + assigned_tree.getNumberOfExternalNodes() + ") than the preceding gene tree(s) (" + _ext_nodes
427 return assigned_tree;
430 private final Phylogeny performOrthologInferenceByGSDI( final Phylogeny gene_tree,
431 final Phylogeny species_tree,
432 final String outgroup,
434 final boolean transfer_taxonomy ) throws SDIException,
436 final Phylogeny assigned_tree;
438 if ( _rerooting == REROOTING.BY_ALGORITHM ) {
439 final GSDIR gsdir = new GSDIR( gene_tree, species_tree, true, i == 0, transfer_taxonomy );
440 assigned_tree = gsdir.getMinDuplicationsSumGeneTree();
442 _removed_gene_tree_nodes = gsdir.getStrippedExternalGeneTreeNodes();
443 for( final PhylogenyNode r : _removed_gene_tree_nodes ) {
444 if ( !r.getNodeData().isHasTaxonomy() ) {
445 throw new RIOException( "node with no (appropriate) taxonomic information found in gene tree #"
446 + i + ": " + r.toString() );
451 _gsdir_tax_comp_base = gsdir.getTaxCompBase();
453 dups = gsdir.getMinDuplicationsSum();
456 if ( _rerooting == REROOTING.MIDPOINT ) {
457 PhylogenyMethods.midpointRoot( gene_tree );
459 else if ( _rerooting == REROOTING.OUTGROUP ) {
460 final PhylogenyNode n = gene_tree.getNode( outgroup );
461 gene_tree.reRoot( n );
463 final GSDI gsdi = new GSDI( gene_tree, species_tree, true, true, true, transfer_taxonomy );
464 _removed_gene_tree_nodes = gsdi.getStrippedExternalGeneTreeNodes();
465 for( final PhylogenyNode r : _removed_gene_tree_nodes ) {
466 if ( !r.getNodeData().isHasTaxonomy() ) {
467 throw new RIOException( "node with no (appropriate) taxonomic information found in gene tree #" + i
468 + ": " + r.toString() );
471 assigned_tree = gene_tree;
473 _gsdir_tax_comp_base = gsdi.getTaxCompBase();
475 dups = gsdi.getDuplicationsSum();
477 if ( ( i == 0 ) || ( dups < _duplications_stats.getMin() ) ) {
478 _min_dub_gene_tree = assigned_tree;
480 _duplications_stats.addValue( dups );
481 return assigned_tree;
484 private final Phylogeny performOrthologInferenceBySDI( final Phylogeny gene_tree, final Phylogeny species_tree )
485 throws SDIException {
486 final SDIR sdir = new SDIR();
487 return sdir.infer( gene_tree, species_tree, false, true, true, true, 1 )[ 0 ];
490 private final void postLog( final Phylogeny species_tree, final int first, final int last ) {
492 if ( ( getRemovedGeneTreeNodes() != null ) && ( getRemovedGeneTreeNodes().size() > 0 ) ) {
493 logRemovedGeneTreeNodes();
495 log( "Species tree external nodes (after stripping) : " + species_tree.getNumberOfExternalNodes() );
496 log( "Species tree polytomies (after stripping) : "
497 + PhylogenyMethods.countNumberOfPolytomies( species_tree ) );
498 log( "Taxonomy linking based on : " + getGSDIRtaxCompBase() );
499 final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#" );
500 if ( ( first >= 0 ) && ( last >= 0 ) ) {
501 log( "Gene trees analyzed range : " + first + "-" + last );
503 log( "Gene trees analyzed : " + _duplications_stats.getN() );
504 log( "Mean number of duplications : " + df.format( _duplications_stats.arithmeticMean() )
505 + " (sd: " + df.format( _duplications_stats.sampleStandardDeviation() ) + ")" + " ("
506 + df.format( ( 100.0 * _duplications_stats.arithmeticMean() ) / getIntNodesOfAnalyzedGeneTrees() )
508 if ( _duplications_stats.getN() > 3 ) {
509 log( "Median number of duplications : " + df.format( _duplications_stats.median() )
510 + " (" + df.format( ( 100.0 * _duplications_stats.median() ) / getIntNodesOfAnalyzedGeneTrees() )
513 log( "Minimum duplications : " + ( int ) _duplications_stats.getMin() + " ("
514 + df.format( ( 100.0 * _duplications_stats.getMin() ) / getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
515 log( "Maximum duplications : " + ( int ) _duplications_stats.getMax() + " ("
516 + df.format( ( 100.0 * _duplications_stats.getMax() ) / getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
517 log( "Gene tree internal nodes : " + getIntNodesOfAnalyzedGeneTrees() );
518 log( "Gene tree external nodes : " + getExtNodesOfAnalyzedGeneTrees() );
521 private final void preLog( final int gene_trees,
522 final Phylogeny species_tree,
523 final ALGORITHM algorithm,
524 final String outgroup ) {
525 if ( gene_trees > 0 ) {
526 log( "Number of gene trees (total) : " + gene_trees );
528 log( "Algorithm : " + algorithm );
529 log( "Species tree external nodes (prior to stripping): " + species_tree.getNumberOfExternalNodes() );
530 log( "Species tree polytomies (prior to stripping) : "
531 + PhylogenyMethods.countNumberOfPolytomies( species_tree ) );
533 switch ( _rerooting ) {
535 rs = "minimizing duplications";
543 rs = "outgroup: " + outgroup;
551 log( "Re-rooting : " + rs );
554 public final static IntMatrix calculateOrthologTable( final Phylogeny[] analyzed_gene_trees, final boolean sort )
555 throws RIOException {
556 final List<String> labels = new ArrayList<String>();
557 final Set<String> labels_set = new HashSet<String>();
558 for( final PhylogenyNode n : analyzed_gene_trees[ 0 ].getExternalNodes() ) {
559 final String label = obtainLabel( labels_set, n );
560 labels_set.add( label );
564 Collections.sort( labels );
566 final IntMatrix m = new IntMatrix( labels );
568 for( final Phylogeny gt : analyzed_gene_trees ) {
570 updateCounts( m, counter, gt );
575 public final static RIO executeAnalysis( final File gene_trees_file,
576 final File species_tree_file,
577 final ALGORITHM algorithm,
578 final REROOTING rerooting,
579 final String outgroup,
582 final boolean produce_log,
583 final boolean verbose,
584 final boolean transfer_taxonomy ) throws IOException, SDIException,
586 final Phylogeny[] gene_trees = parseGeneTrees( gene_trees_file );
587 if ( gene_trees.length < 1 ) {
588 throw new RIOException( "\"" + gene_trees_file + "\" is devoid of appropriate gene trees" );
590 final Phylogeny species_tree = SDIutil.parseSpeciesTree( gene_trees[ 0 ],
594 TAXONOMY_EXTRACTION.NO );
595 return new RIO( gene_trees,
607 public final static RIO executeAnalysis( final File gene_trees_file,
608 final Phylogeny species_tree,
609 final ALGORITHM algorithm,
610 final REROOTING rerooting,
611 final String outgroup,
612 final boolean produce_log,
613 final boolean verbose,
614 final boolean transfer_taxonomy ) throws IOException, SDIException,
616 return new RIO( parseGeneTrees( gene_trees_file ),
628 public final static RIO executeAnalysis( final File gene_trees_file,
629 final Phylogeny species_tree,
630 final ALGORITHM algorithm,
631 final REROOTING rerooting,
632 final String outgroup,
635 final boolean produce_log,
636 final boolean verbose,
637 final boolean transfer_taxonomy ) throws IOException, SDIException,
639 return new RIO( parseGeneTrees( gene_trees_file ),
651 public final static RIO executeAnalysis( final IteratingPhylogenyParser p,
652 final File species_tree_file,
653 final ALGORITHM algorithm,
654 final REROOTING rerooting,
655 final String outgroup,
658 final boolean produce_log,
659 final boolean verbose,
660 final boolean transfer_taxonomy ) throws IOException, SDIException,
662 final Phylogeny g0 = p.next();
663 if ( ( g0 == null ) || g0.isEmpty() || ( g0.getNumberOfExternalNodes() < 2 ) ) {
664 throw new RIOException( "input file does not seem to contain any gene trees" );
666 final Phylogeny species_tree = SDIutil.parseSpeciesTree( g0,
670 TAXONOMY_EXTRACTION.NO );
684 public final static RIO executeAnalysis( final IteratingPhylogenyParser p,
685 final Phylogeny species_tree,
686 final ALGORITHM algorithm,
687 final REROOTING rerooting,
688 final String outgroup,
689 final boolean produce_log,
690 final boolean verbose,
691 final boolean transfer_taxonomy ) throws IOException, SDIException,
705 public final static RIO executeAnalysis( final IteratingPhylogenyParser p,
706 final Phylogeny species_tree,
707 final ALGORITHM algorithm,
708 final REROOTING rerooting,
709 final String outgroup,
712 final boolean produce_log,
713 final boolean verbose,
714 final boolean transfer_taxonomy ) throws IOException, SDIException,
728 public final static RIO executeAnalysis( final Phylogeny[] gene_trees, final Phylogeny species_tree )
729 throws IOException, SDIException, RIOException {
730 return new RIO( gene_trees,
733 REROOTING.BY_ALGORITHM,
742 public final static RIO executeAnalysis( final Phylogeny[] gene_trees,
743 final Phylogeny species_tree,
744 final ALGORITHM algorithm,
745 final REROOTING rerooting,
746 final String outgroup,
747 final boolean produce_log,
748 final boolean verbose,
749 final boolean transfer_taxonomy ) throws IOException, SDIException,
751 return new RIO( gene_trees,
763 public final static RIO executeAnalysis( final Phylogeny[] gene_trees,
764 final Phylogeny species_tree,
765 final ALGORITHM algorithm,
766 final REROOTING rerooting,
767 final String outgroup,
770 final boolean produce_log,
771 final boolean verbose,
772 final boolean transfer_taxonomy ) throws IOException, SDIException,
774 return new RIO( gene_trees,
786 private final static void calculateOrthologTable( final Phylogeny g, final boolean sort, final int counter )
787 throws RIOException {
788 if ( counter == 0 ) {
789 final List<String> labels = new ArrayList<String>();
790 final Set<String> labels_set = new HashSet<String>();
791 for( final PhylogenyNode n : g.getExternalNodes() ) {
792 final String label = obtainLabel( labels_set, n );
793 labels_set.add( label );
797 Collections.sort( labels );
799 _m = new IntMatrix( labels );
801 updateCounts( _m, counter, g );
804 private final static void checkPreconditions( final IteratingPhylogenyParser p,
805 final Phylogeny species_tree,
806 final REROOTING rerooting,
807 final String outgroup,
809 final int last ) throws RIOException, IOException {
810 final Phylogeny g0 = p.next();
811 if ( ( g0 == null ) || g0.isEmpty() ) {
812 throw new RIOException( "input file does not seem to contain any gene trees" );
814 if ( g0.getNumberOfExternalNodes() < 2 ) {
815 throw new RIOException( "input file does not seem to contain any useable gene trees" );
817 if ( !species_tree.isRooted() ) {
818 throw new RIOException( "species tree is not rooted" );
820 if ( !( ( last == DEFAULT_RANGE ) && ( first == DEFAULT_RANGE ) )
821 && ( ( last < first ) || ( last < 0 ) || ( first < 0 ) ) ) {
822 throw new RIOException( "attempt to set range (0-based) of gene to analyze to: from " + first + " to "
825 if ( ( rerooting == REROOTING.OUTGROUP ) && ForesterUtil.isEmpty( outgroup ) ) {
826 throw new RIOException( "outgroup not set for midpoint rooting" );
828 if ( ( rerooting != REROOTING.OUTGROUP ) && !ForesterUtil.isEmpty( outgroup ) ) {
829 throw new RIOException( "outgroup only used for midpoint rooting" );
831 if ( ( rerooting == REROOTING.MIDPOINT ) && ( PhylogenyMethods.calculateMaxDistanceToRoot( g0 ) <= 0 ) ) {
832 throw new RIOException( "attempt to use midpoint rooting on gene trees which seem to have no (positive) branch lengths (cladograms)" );
834 if ( rerooting == REROOTING.OUTGROUP ) {
836 g0.getNode( outgroup );
838 catch ( final IllegalArgumentException e ) {
839 throw new RIOException( "cannot perform re-rooting by outgroup: " + e.getLocalizedMessage() );
844 private final static void checkPreconditions( final Phylogeny[] gene_trees,
845 final Phylogeny species_tree,
846 final REROOTING rerooting,
847 final String outgroup,
849 final int last ) throws RIOException {
850 if ( !species_tree.isRooted() ) {
851 throw new RIOException( "species tree is not rooted" );
853 if ( !( ( last == DEFAULT_RANGE ) && ( first == DEFAULT_RANGE ) )
854 && ( ( last < first ) || ( last >= gene_trees.length ) || ( last < 0 ) || ( first < 0 ) ) ) {
855 throw new RIOException( "attempt to set range (0-based) of gene to analyze to: from " + first + " to "
856 + last + " (out of " + gene_trees.length + ")" );
858 if ( ( rerooting == REROOTING.OUTGROUP ) && ForesterUtil.isEmpty( outgroup ) ) {
859 throw new RIOException( "outgroup not set for midpoint rooting" );
861 if ( ( rerooting != REROOTING.OUTGROUP ) && !ForesterUtil.isEmpty( outgroup ) ) {
862 throw new RIOException( "outgroup only used for midpoint rooting" );
864 if ( ( rerooting == REROOTING.MIDPOINT )
865 && ( PhylogenyMethods.calculateMaxDistanceToRoot( gene_trees[ 0 ] ) <= 0 ) ) {
866 throw new RIOException( "attempt to use midpoint rooting on gene trees which seem to have no (positive) branch lengths (cladograms)" );
868 if ( rerooting == REROOTING.OUTGROUP ) {
870 gene_trees[ 0 ].getNode( outgroup );
872 catch ( final IllegalArgumentException e ) {
873 throw new RIOException( "cannot perform re-rooting by outgroup: " + e.getLocalizedMessage() );
878 private final static String obtainLabel( final Set<String> labels_set, final PhylogenyNode n ) throws RIOException {
880 if ( n.getNodeData().isHasSequence() && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
881 label = n.getNodeData().getSequence().getName();
883 else if ( n.getNodeData().isHasSequence() && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getSymbol() ) ) {
884 label = n.getNodeData().getSequence().getSymbol();
886 else if ( n.getNodeData().isHasSequence()
887 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getGeneName() ) ) {
888 label = n.getNodeData().getSequence().getGeneName();
890 else if ( !ForesterUtil.isEmpty( n.getName() ) ) {
894 throw new RIOException( "node " + n + " has no appropriate label" );
896 if ( labels_set.contains( label ) ) {
897 throw new RIOException( "label " + label + " is not unique" );
902 private final static Phylogeny[] parseGeneTrees( final File gene_trees_file ) throws FileNotFoundException,
904 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
905 final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
906 if ( p instanceof NHXParser ) {
907 final NHXParser nhx = ( NHXParser ) p;
908 nhx.setReplaceUnderscores( false );
909 nhx.setIgnoreQuotes( true );
910 nhx.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGGRESSIVE );
912 else if ( p instanceof NexusPhylogeniesParser ) {
913 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) p;
914 nex.setReplaceUnderscores( false );
915 nex.setIgnoreQuotes( true );
916 nex.setTaxonomyExtraction( TAXONOMY_EXTRACTION.AGGRESSIVE );
918 return factory.create( gene_trees_file, p );
921 private final static void removeSingleDescendentsNodes( final Phylogeny species_tree, final boolean verbose ) {
922 final int o = PhylogenyMethods.countNumberOfOneDescendantNodes( species_tree );
925 System.out.println( "warning: species tree has " + o
926 + " internal nodes with only one descendent which are therefore going to be removed" );
928 PhylogenyMethods.deleteInternalNodesWithOnlyOneDescendent( species_tree );
932 private final static void updateCounts( final IntMatrix m, final int counter, final Phylogeny g )
933 throws RIOException {
934 PhylogenyMethods.preOrderReId( g );
935 final HashMap<String, PhylogenyNode> map = PhylogenyMethods.createNameToExtNodeMap( g );
936 for( int x = 0; x < m.size(); ++x ) {
937 final String mx = m.getLabel( x );
938 final PhylogenyNode nx = map.get( mx );
940 throw new RIOException( "node \"" + mx + "\" not present in gene tree #" + counter );
944 for( int y = 0; y < m.size(); ++y ) {
945 my = m.getLabel( y );
948 throw new RIOException( "node \"" + my + "\" not present in gene tree #" + counter );
950 if ( !PhylogenyMethods.calculateLCAonTreeWithIdsInPreOrder( nx, ny ).isDuplication() ) {
951 m.inreaseByOne( x, y );
957 public enum REROOTING {
958 NONE, BY_ALGORITHM, MIDPOINT, OUTGROUP;