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 final DecimalFormat pf = new java.text.DecimalFormat( "000" );
220 int gene_tree_ext_nodes = 0;
223 final boolean no_range = ( first < 0 ) || ( last < first );
224 while ( parser.hasNext() ) {
225 final Phylogeny gt = parser.next();
226 if ( no_range || ( ( i >= first ) && ( i <= last ) ) ) {
227 if ( gt.isEmpty() ) {
228 throw new RIOException( "gene tree #" + i + " is empty" );
230 if ( gt.getNumberOfExternalNodes() == 1 ) {
231 throw new RIOException( "gene tree #" + i + " has only one external node" );
234 ForesterUtil.updateProgress( i, pf );
236 if ( counter == 0 ) {
237 if ( algorithm == ALGORITHM.SDIR ) {
238 // Removes from species_tree all species not found in gene_tree.
239 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( gt, species_tree );
240 if ( species_tree.isEmpty() ) {
241 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
244 gene_tree_ext_nodes = gt.getNumberOfExternalNodes();
246 else if ( gene_tree_ext_nodes != gt.getNumberOfExternalNodes() ) {
247 throw new RIOException( "gene tree #" + i + " has a different number of external nodes ("
248 + gt.getNumberOfExternalNodes() + ") than the preceding gene tree(s) ("
249 + gene_tree_ext_nodes + ")" );
251 if ( algorithm == ALGORITHM.SDIR ) {
252 // Removes from gene_tree all species not found in species_tree.
253 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( species_tree, gt );
254 if ( gt.isEmpty() ) {
255 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
258 final Phylogeny analyzed_gt = performOrthologInference( gt,
264 RIO.calculateOrthologTable( analyzed_gt, true, counter );
269 if ( ( first >= 0 ) && ( counter == 0 ) && ( i > 0 ) ) {
270 throw new RIOException( "attempt to analyze first gene tree #" + first + " in a set of " + i );
276 postLog( species_tree, first, first + counter - 1 );
279 System.out.println();
280 System.out.println();
284 private final void inferOrthologs( final Phylogeny[] gene_trees,
285 final Phylogeny species_tree,
286 final ALGORITHM algorithm,
287 final String outgroup,
290 final boolean transfer_taxonomy ) throws SDIException, RIOException,
291 FileNotFoundException, IOException {
292 if ( algorithm == ALGORITHM.SDIR ) {
293 // Removes from species_tree all species not found in gene_tree.
294 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( gene_trees[ 0 ], species_tree );
295 if ( species_tree.isEmpty() ) {
296 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
299 final Phylogeny[] my_gene_trees;
300 if ( ( first >= 0 ) && ( last >= first ) && ( last < gene_trees.length ) ) {
301 my_gene_trees = new Phylogeny[ ( 1 + last ) - first ];
303 for( int i = first; i <= last; ++i ) {
304 my_gene_trees[ c++ ] = gene_trees[ i ];
308 my_gene_trees = gene_trees;
311 preLog( gene_trees.length, species_tree, algorithm, outgroup );
313 if ( _verbose && ( my_gene_trees.length >= 4 ) ) {
314 System.out.println();
316 _analyzed_gene_trees = new Phylogeny[ my_gene_trees.length ];
317 int gene_tree_ext_nodes = 0;
318 for( int i = 0; i < my_gene_trees.length; ++i ) {
319 final Phylogeny gt = my_gene_trees[ i ];
320 if ( gt.isEmpty() ) {
321 throw new RIOException( "gene tree #" + i + " is empty" );
323 if ( gt.getNumberOfExternalNodes() == 1 ) {
324 throw new RIOException( "gene tree #" + i + " has only one external node" );
326 if ( _verbose && ( my_gene_trees.length > 4 ) ) {
327 ForesterUtil.updateProgress( ( ( double ) i ) / my_gene_trees.length );
330 gene_tree_ext_nodes = gt.getNumberOfExternalNodes();
332 else if ( gene_tree_ext_nodes != gt.getNumberOfExternalNodes() ) {
333 throw new RIOException( "gene tree #" + i + " has a different number of external nodes ("
334 + gt.getNumberOfExternalNodes() + ") than the preceding gene tree(s) (" + gene_tree_ext_nodes
337 if ( algorithm == ALGORITHM.SDIR ) {
338 // Removes from gene_tree all species not found in species_tree.
339 PhylogenyMethods.taxonomyBasedDeletionOfExternalNodes( species_tree, gt );
340 if ( gt.isEmpty() ) {
341 throw new RIOException( "failed to establish species based mapping between gene and species trees" );
344 _analyzed_gene_trees[ i ] = performOrthologInference( gt,
352 postLog( species_tree, first, last );
354 if ( _verbose && ( my_gene_trees.length > 4 ) ) {
355 System.out.println();
356 System.out.println();
360 private final boolean log() {
364 private final void log( final String s ) {
366 _log.append( ForesterUtil.LINE_SEPARATOR );
369 private final void logRemovedGeneTreeNodes() {
370 log( "Species stripped from gene trees:" );
371 final SortedSet<String> rn = new TreeSet<String>();
372 for( final PhylogenyNode n : getRemovedGeneTreeNodes() ) {
373 final Taxonomy t = n.getNodeData().getTaxonomy();
374 switch ( getGSDIRtaxCompBase() ) {
376 rn.add( t.getTaxonomyCode() );
380 rn.add( t.getIdentifier().toString() );
383 case SCIENTIFIC_NAME: {
384 rn.add( t.getScientificName() );
389 for( final String s : rn ) {
395 private final Phylogeny performOrthologInference( final Phylogeny gene_tree,
396 final Phylogeny species_tree,
397 final ALGORITHM algorithm,
398 final String outgroup,
400 final boolean transfer_taxonomy ) throws SDIException,
402 final Phylogeny assigned_tree;
403 switch ( algorithm ) {
405 assigned_tree = performOrthologInferenceBySDI( gene_tree, species_tree );
409 assigned_tree = performOrthologInferenceByGSDI( gene_tree, species_tree, outgroup, i, transfer_taxonomy );
413 throw new IllegalArgumentException( "illegal algorithm: " + algorithm );
417 _ext_nodes = assigned_tree.getNumberOfExternalNodes();
418 _int_nodes = assigned_tree.getNumberOfInternalNodes();
420 else if ( _ext_nodes != assigned_tree.getNumberOfExternalNodes() ) {
421 throw new RIOException( "after stripping gene tree #" + i + " has a different number of external nodes ("
422 + assigned_tree.getNumberOfExternalNodes() + ") than the preceding gene tree(s) (" + _ext_nodes
425 return assigned_tree;
428 private final Phylogeny performOrthologInferenceByGSDI( final Phylogeny gene_tree,
429 final Phylogeny species_tree,
430 final String outgroup,
432 final boolean transfer_taxonomy ) throws SDIException,
434 final Phylogeny assigned_tree;
436 if ( _rerooting == REROOTING.BY_ALGORITHM ) {
437 final GSDIR gsdir = new GSDIR( gene_tree, species_tree, true, i == 0, transfer_taxonomy );
438 assigned_tree = gsdir.getMinDuplicationsSumGeneTree();
440 _removed_gene_tree_nodes = gsdir.getStrippedExternalGeneTreeNodes();
441 for( final PhylogenyNode r : _removed_gene_tree_nodes ) {
442 if ( !r.getNodeData().isHasTaxonomy() ) {
443 throw new RIOException( "node with no (appropriate) taxonomic information found in gene tree #"
444 + i + ": " + r.toString() );
449 _gsdir_tax_comp_base = gsdir.getTaxCompBase();
451 dups = gsdir.getMinDuplicationsSum();
454 if ( _rerooting == REROOTING.MIDPOINT ) {
455 PhylogenyMethods.midpointRoot( gene_tree );
457 else if ( _rerooting == REROOTING.OUTGROUP ) {
458 final PhylogenyNode n = gene_tree.getNode( outgroup );
459 gene_tree.reRoot( n );
461 final GSDI gsdi = new GSDI( gene_tree, species_tree, true, true, true, transfer_taxonomy );
462 _removed_gene_tree_nodes = gsdi.getStrippedExternalGeneTreeNodes();
463 for( final PhylogenyNode r : _removed_gene_tree_nodes ) {
464 if ( !r.getNodeData().isHasTaxonomy() ) {
465 throw new RIOException( "node with no (appropriate) taxonomic information found in gene tree #" + i
466 + ": " + r.toString() );
469 assigned_tree = gene_tree;
471 _gsdir_tax_comp_base = gsdi.getTaxCompBase();
473 dups = gsdi.getDuplicationsSum();
475 if ( ( i == 0 ) || ( dups < _duplications_stats.getMin() ) ) {
476 _min_dub_gene_tree = assigned_tree;
478 _duplications_stats.addValue( dups );
479 return assigned_tree;
482 private final Phylogeny performOrthologInferenceBySDI( final Phylogeny gene_tree, final Phylogeny species_tree )
483 throws SDIException {
484 final SDIR sdir = new SDIR();
485 return sdir.infer( gene_tree, species_tree, false, true, true, true, 1 )[ 0 ];
488 private final void postLog( final Phylogeny species_tree, final int first, final int last ) {
490 if ( ( getRemovedGeneTreeNodes() != null ) && ( getRemovedGeneTreeNodes().size() > 0 ) ) {
491 logRemovedGeneTreeNodes();
493 log( "Species tree external nodes (after stripping) : " + species_tree.getNumberOfExternalNodes() );
494 log( "Species tree polytomies (after stripping) : "
495 + PhylogenyMethods.countNumberOfPolytomies( species_tree ) );
496 log( "Taxonomy linking based on : " + getGSDIRtaxCompBase() );
497 final java.text.DecimalFormat df = new java.text.DecimalFormat( "0.#" );
498 if ( ( first >= 0 ) && ( last >= 0 ) ) {
499 log( "Gene trees analyzed range : " + first + "-" + last );
501 log( "Gene trees analyzed : " + _duplications_stats.getN() );
502 log( "Mean number of duplications : " + df.format( _duplications_stats.arithmeticMean() )
503 + " (sd: " + df.format( _duplications_stats.sampleStandardDeviation() ) + ")" + " ("
504 + df.format( ( 100.0 * _duplications_stats.arithmeticMean() ) / getIntNodesOfAnalyzedGeneTrees() )
506 if ( _duplications_stats.getN() > 3 ) {
507 log( "Median number of duplications : " + df.format( _duplications_stats.median() )
508 + " (" + df.format( ( 100.0 * _duplications_stats.median() ) / getIntNodesOfAnalyzedGeneTrees() )
511 log( "Minimum duplications : " + ( int ) _duplications_stats.getMin() + " ("
512 + df.format( ( 100.0 * _duplications_stats.getMin() ) / getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
513 log( "Maximum duplications : " + ( int ) _duplications_stats.getMax() + " ("
514 + df.format( ( 100.0 * _duplications_stats.getMax() ) / getIntNodesOfAnalyzedGeneTrees() ) + "%)" );
515 log( "Gene tree internal nodes : " + getIntNodesOfAnalyzedGeneTrees() );
516 log( "Gene tree external nodes : " + getExtNodesOfAnalyzedGeneTrees() );
519 private final void preLog( final int gene_trees,
520 final Phylogeny species_tree,
521 final ALGORITHM algorithm,
522 final String outgroup ) {
523 if ( gene_trees > 0 ) {
524 log( "Number of gene trees (total) : " + gene_trees );
526 log( "Algorithm : " + algorithm );
527 log( "Species tree external nodes (prior to stripping): " + species_tree.getNumberOfExternalNodes() );
528 log( "Species tree polytomies (prior to stripping) : "
529 + PhylogenyMethods.countNumberOfPolytomies( species_tree ) );
531 switch ( _rerooting ) {
533 rs = "minimizing duplications";
541 rs = "outgroup: " + outgroup;
549 log( "Re-rooting : " + rs );
552 public final static IntMatrix calculateOrthologTable( final Phylogeny[] analyzed_gene_trees, final boolean sort )
553 throws RIOException {
554 final List<String> labels = new ArrayList<String>();
555 final Set<String> labels_set = new HashSet<String>();
556 for( final PhylogenyNode n : analyzed_gene_trees[ 0 ].getExternalNodes() ) {
557 final String label = obtainLabel( labels_set, n );
558 labels_set.add( label );
562 Collections.sort( labels );
564 final IntMatrix m = new IntMatrix( labels );
566 for( final Phylogeny gt : analyzed_gene_trees ) {
568 updateCounts( m, counter, gt );
573 public final static RIO executeAnalysis( final File gene_trees_file,
574 final File species_tree_file,
575 final ALGORITHM algorithm,
576 final REROOTING rerooting,
577 final String outgroup,
580 final boolean produce_log,
581 final boolean verbose,
582 final boolean transfer_taxonomy ) throws IOException, SDIException,
584 final Phylogeny[] gene_trees = parseGeneTrees( gene_trees_file );
585 if ( gene_trees.length < 1 ) {
586 throw new RIOException( "\"" + gene_trees_file + "\" is devoid of appropriate gene trees" );
588 final Phylogeny species_tree = SDIutil.parseSpeciesTree( gene_trees[ 0 ],
592 TAXONOMY_EXTRACTION.NO );
593 return new RIO( gene_trees,
605 public final static RIO executeAnalysis( final File gene_trees_file,
606 final Phylogeny species_tree,
607 final ALGORITHM algorithm,
608 final REROOTING rerooting,
609 final String outgroup,
610 final boolean produce_log,
611 final boolean verbose,
612 final boolean transfer_taxonomy ) throws IOException, SDIException,
614 return new RIO( parseGeneTrees( gene_trees_file ),
626 public final static RIO executeAnalysis( final File gene_trees_file,
627 final Phylogeny species_tree,
628 final ALGORITHM algorithm,
629 final REROOTING rerooting,
630 final String outgroup,
633 final boolean produce_log,
634 final boolean verbose,
635 final boolean transfer_taxonomy ) throws IOException, SDIException,
637 return new RIO( parseGeneTrees( gene_trees_file ),
649 public final static RIO executeAnalysis( final IteratingPhylogenyParser p,
650 final File species_tree_file,
651 final ALGORITHM algorithm,
652 final REROOTING rerooting,
653 final String outgroup,
656 final boolean produce_log,
657 final boolean verbose,
658 final boolean transfer_taxonomy ) throws IOException, SDIException,
660 final Phylogeny g0 = p.next();
661 if ( ( g0 == null ) || g0.isEmpty() || ( g0.getNumberOfExternalNodes() < 2 ) ) {
662 throw new RIOException( "input file does not seem to contain any gene trees" );
664 final Phylogeny species_tree = SDIutil.parseSpeciesTree( g0,
668 TAXONOMY_EXTRACTION.NO );
682 public final static RIO executeAnalysis( final IteratingPhylogenyParser p,
683 final Phylogeny species_tree,
684 final ALGORITHM algorithm,
685 final REROOTING rerooting,
686 final String outgroup,
687 final boolean produce_log,
688 final boolean verbose,
689 final boolean transfer_taxonomy ) throws IOException, SDIException,
703 public final static RIO executeAnalysis( final IteratingPhylogenyParser p,
704 final Phylogeny species_tree,
705 final ALGORITHM algorithm,
706 final REROOTING rerooting,
707 final String outgroup,
710 final boolean produce_log,
711 final boolean verbose,
712 final boolean transfer_taxonomy ) throws IOException, SDIException,
726 public final static RIO executeAnalysis( final Phylogeny[] gene_trees, final Phylogeny species_tree )
727 throws IOException, SDIException, RIOException {
728 return new RIO( gene_trees,
731 REROOTING.BY_ALGORITHM,
740 public final static RIO executeAnalysis( final Phylogeny[] gene_trees,
741 final Phylogeny species_tree,
742 final ALGORITHM algorithm,
743 final REROOTING rerooting,
744 final String outgroup,
745 final boolean produce_log,
746 final boolean verbose,
747 final boolean transfer_taxonomy ) throws IOException, SDIException,
749 return new RIO( gene_trees,
761 public final static RIO executeAnalysis( final Phylogeny[] gene_trees,
762 final Phylogeny species_tree,
763 final ALGORITHM algorithm,
764 final REROOTING rerooting,
765 final String outgroup,
768 final boolean produce_log,
769 final boolean verbose,
770 final boolean transfer_taxonomy ) throws IOException, SDIException,
772 return new RIO( gene_trees,
784 private final static void calculateOrthologTable( final Phylogeny g, final boolean sort, final int counter )
785 throws RIOException {
786 if ( counter == 0 ) {
787 final List<String> labels = new ArrayList<String>();
788 final Set<String> labels_set = new HashSet<String>();
789 for( final PhylogenyNode n : g.getExternalNodes() ) {
790 final String label = obtainLabel( labels_set, n );
791 labels_set.add( label );
795 Collections.sort( labels );
797 _m = new IntMatrix( labels );
799 updateCounts( _m, counter, g );
802 private final static void checkPreconditions( final IteratingPhylogenyParser p,
803 final Phylogeny species_tree,
804 final REROOTING rerooting,
805 final String outgroup,
807 final int last ) throws RIOException, IOException {
808 final Phylogeny g0 = p.next();
809 if ( ( g0 == null ) || g0.isEmpty() ) {
810 throw new RIOException( "input file does not seem to contain any gene trees" );
812 if ( g0.getNumberOfExternalNodes() < 2 ) {
813 throw new RIOException( "input file does not seem to contain any useable gene trees" );
815 if ( !species_tree.isRooted() ) {
816 throw new RIOException( "species tree is not rooted" );
818 if ( !( ( last == DEFAULT_RANGE ) && ( first == DEFAULT_RANGE ) )
819 && ( ( last < first ) || ( last < 0 ) || ( first < 0 ) ) ) {
820 throw new RIOException( "attempt to set range (0-based) of gene to analyze to: from " + first + " to "
823 if ( ( rerooting == REROOTING.OUTGROUP ) && ForesterUtil.isEmpty( outgroup ) ) {
824 throw new RIOException( "outgroup not set for midpoint rooting" );
826 if ( ( rerooting != REROOTING.OUTGROUP ) && !ForesterUtil.isEmpty( outgroup ) ) {
827 throw new RIOException( "outgroup only used for midpoint rooting" );
829 if ( ( rerooting == REROOTING.MIDPOINT ) && ( PhylogenyMethods.calculateMaxDistanceToRoot( g0 ) <= 0 ) ) {
830 throw new RIOException( "attempt to use midpoint rooting on gene trees which seem to have no (positive) branch lengths (cladograms)" );
832 if ( rerooting == REROOTING.OUTGROUP ) {
834 g0.getNode( outgroup );
836 catch ( final IllegalArgumentException e ) {
837 throw new RIOException( "cannot perform re-rooting by outgroup: " + e.getLocalizedMessage() );
842 private final static void checkPreconditions( final Phylogeny[] gene_trees,
843 final Phylogeny species_tree,
844 final REROOTING rerooting,
845 final String outgroup,
847 final int last ) throws RIOException {
848 if ( !species_tree.isRooted() ) {
849 throw new RIOException( "species tree is not rooted" );
851 if ( !( ( last == DEFAULT_RANGE ) && ( first == DEFAULT_RANGE ) )
852 && ( ( last < first ) || ( last >= gene_trees.length ) || ( last < 0 ) || ( first < 0 ) ) ) {
853 throw new RIOException( "attempt to set range (0-based) of gene to analyze to: from " + first + " to "
854 + last + " (out of " + gene_trees.length + ")" );
856 if ( ( rerooting == REROOTING.OUTGROUP ) && ForesterUtil.isEmpty( outgroup ) ) {
857 throw new RIOException( "outgroup not set for midpoint rooting" );
859 if ( ( rerooting != REROOTING.OUTGROUP ) && !ForesterUtil.isEmpty( outgroup ) ) {
860 throw new RIOException( "outgroup only used for midpoint rooting" );
862 if ( ( rerooting == REROOTING.MIDPOINT )
863 && ( PhylogenyMethods.calculateMaxDistanceToRoot( gene_trees[ 0 ] ) <= 0 ) ) {
864 throw new RIOException( "attempt to use midpoint rooting on gene trees which seem to have no (positive) branch lengths (cladograms)" );
866 if ( rerooting == REROOTING.OUTGROUP ) {
868 gene_trees[ 0 ].getNode( outgroup );
870 catch ( final IllegalArgumentException e ) {
871 throw new RIOException( "cannot perform re-rooting by outgroup: " + e.getLocalizedMessage() );
876 private final static String obtainLabel( final Set<String> labels_set, final PhylogenyNode n ) throws RIOException {
878 if ( n.getNodeData().isHasSequence() && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getName() ) ) {
879 label = n.getNodeData().getSequence().getName();
881 else if ( n.getNodeData().isHasSequence() && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getSymbol() ) ) {
882 label = n.getNodeData().getSequence().getSymbol();
884 else if ( !ForesterUtil.isEmpty( n.getName() ) ) {
888 throw new RIOException( "node " + n + " has no appropriate label" );
890 if ( labels_set.contains( label ) ) {
891 throw new RIOException( "label " + label + " is not unique" );
896 private final static Phylogeny[] parseGeneTrees( final File gene_trees_file ) throws FileNotFoundException,
898 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
899 final PhylogenyParser p = ParserUtils.createParserDependingOnFileType( gene_trees_file, true );
900 if ( p instanceof NHXParser ) {
901 final NHXParser nhx = ( NHXParser ) p;
902 nhx.setReplaceUnderscores( false );
903 nhx.setIgnoreQuotes( true );
904 nhx.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
906 else if ( p instanceof NexusPhylogeniesParser ) {
907 final NexusPhylogeniesParser nex = ( NexusPhylogeniesParser ) p;
908 nex.setReplaceUnderscores( false );
909 nex.setIgnoreQuotes( true );
910 nex.setTaxonomyExtraction( TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
912 return factory.create( gene_trees_file, p );
915 private final static void removeSingleDescendentsNodes( final Phylogeny species_tree, final boolean verbose ) {
916 final int o = PhylogenyMethods.countNumberOfOneDescendantNodes( species_tree );
919 System.out.println( "warning: species tree has " + o
920 + " internal nodes with only one descendent which are therefore going to be removed" );
922 PhylogenyMethods.deleteInternalNodesWithOnlyOneDescendent( species_tree );
926 private final static void updateCounts( final IntMatrix m, final int counter, final Phylogeny g )
927 throws RIOException {
928 PhylogenyMethods.preOrderReId( g );
929 final HashMap<String, PhylogenyNode> map = PhylogenyMethods.createNameToExtNodeMap( g );
930 for( int x = 0; x < m.size(); ++x ) {
931 final String mx = m.getLabel( x );
932 final PhylogenyNode nx = map.get( mx );
934 throw new RIOException( "node \"" + mx + "\" not present in gene tree #" + counter );
938 for( int y = 0; y < m.size(); ++y ) {
939 my = m.getLabel( y );
942 throw new RIOException( "node \"" + my + "\" not present in gene tree #" + counter );
944 if ( !PhylogenyMethods.calculateLCAonTreeWithIdsInPreOrder( nx, ny ).isDuplication() ) {
945 m.inreaseByOne( x, y );
951 public enum REROOTING {
952 NONE, BY_ALGORITHM, MIDPOINT, OUTGROUP;