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: www.phylosoft.org/forester
28 package org.forester.rio;
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;
39 import java.util.SortedSet;
40 import java.util.TreeSet;
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;
63 public final class RIO {
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;
76 private RIO( final Phylogeny[] gene_trees,
77 final Phylogeny species_tree,
78 final ALGORITHM algorithm,
79 final REROOTING rerooting,
80 final String outgroup,
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;
88 else if ( ( first == DEFAULT_RANGE ) && ( last >= 0 ) ) {
91 removeSingleDescendentsNodes( species_tree, verbose );
92 checkPreconditions( gene_trees, species_tree, rerooting, outgroup, first, last );
93 _produce_log = produce_log;
95 _rerooting = rerooting;
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 );
105 public final Phylogeny[] getAnalyzedGeneTrees() {
106 return _analyzed_gene_trees;
109 public final BasicDescriptiveStatistics getDuplicationsStatistics() {
110 return _duplications_stats;
114 * Returns the numbers of number of ext nodes in gene trees analyzed (after
117 * @return number of ext nodes in gene trees analyzed (after stripping)
119 public final int getExtNodesOfAnalyzedGeneTrees() {
123 public final TaxonomyComparisonBase getGSDIRtaxCompBase() {
124 return _gsdir_tax_comp_base;
127 public final StringBuilder getLog() {
131 public final List<PhylogenyNode> getRemovedGeneTreeNodes() {
132 return _removed_gene_tree_nodes;
135 private final void inferOrthologs( final Phylogeny[] gene_trees,
136 final Phylogeny species_tree,
137 final ALGORITHM algorithm,
138 final String outgroup,
140 final int last ) throws SDIException, RIOException, FileNotFoundException,
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" );
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 ];
153 for( int i = first; i <= last; ++i ) {
154 my_gene_trees[ c++ ] = gene_trees[ i ];
158 my_gene_trees = gene_trees;
161 preLog( gene_trees, species_tree, algorithm, outgroup, first, last );
163 if ( _verbose && ( my_gene_trees.length >= 4 ) ) {
164 System.out.println();
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 );
174 gene_tree_ext_nodes = gt.getNumberOfExternalNodes();
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
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" );
188 _analyzed_gene_trees[ i ] = performOrthologInference( gt, species_tree, algorithm, outgroup, i );
191 postLog( species_tree );
193 if ( _verbose && ( my_gene_trees.length > 4 ) ) {
194 System.out.println();
195 System.out.println();
199 private final boolean log() {
203 private final void log( final String s ) {
205 _log.append( ForesterUtil.LINE_SEPARATOR );
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() ) {
215 rn.add( t.getTaxonomyCode() );
219 rn.add( t.getIdentifier().toString() );
222 case SCIENTIFIC_NAME: {
223 rn.add( t.getScientificName() );
228 for( final String s : rn ) {
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 ) {
242 assigned_tree = performOrthologInferenceBySDI( gene_tree, species_tree );
246 assigned_tree = performOrthologInferenceByGSDI( gene_tree, species_tree, outgroup, i );
250 throw new IllegalArgumentException( "illegal algorithm: " + algorithm );
254 _ext_nodes = assigned_tree.getNumberOfExternalNodes();
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 + ")" );
261 return assigned_tree;
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();
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: "
281 final List<Integer> shortests = GSDIR.getIndexesOfShortestTree( assigned_trees );
282 assigned_tree = assigned_trees.get( shortests.get( 0 ) );
284 writeStatsToLog( i, gsdir, shortests );
287 _gsdir_tax_comp_base = gsdir.getTaxCompBase();
289 _duplications_stats.addValue( gsdir.getMinDuplicationsSum() );
292 if ( _rerooting == REROOTING.MIDPOINT ) {
293 PhylogenyMethods.midpointRoot( gene_tree );
295 else if ( _rerooting == REROOTING.OUTGROUP ) {
296 final PhylogenyNode n = gene_tree.getNode( outgroup );
297 gene_tree.reRoot( n );
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: "
307 assigned_tree = gene_tree;
309 _gsdir_tax_comp_base = gsdi.getTaxCompBase();
311 _duplications_stats.addValue( gsdi.getDuplicationsSum() );
313 return assigned_tree;
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 ];
322 private final void postLog( final Phylogeny species_tree ) {
324 if ( getRemovedGeneTreeNodes().size() > 0 ) {
325 logRemovedGeneTreeNodes();
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() ) );
338 log( "Minimum duplications : " + ( int ) _duplications_stats.getMin() );
339 log( "Maximum duplications : " + ( int ) _duplications_stats.getMax() );
342 private final void preLog( final Phylogeny[] gene_trees,
343 final Phylogeny species_tree,
344 final ALGORITHM algorithm,
345 final String outgroup,
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 ) );
354 switch ( _rerooting ) {
356 rs = "minimizing duplications";
364 rs = "outgroup: " + outgroup;
372 log( "Re-rooting : " + rs );
373 if ( ( first >= 0 ) || ( last >= 0 ) ) {
374 log( "Gene trees analyzed range : " + first + "-" + last );
376 if ( _rerooting == REROOTING.BY_ALGORITHM ) {
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 );
387 _log.append( "re-rootings with minimal number of duplications" );
389 _log.append( "total root placements" );
391 _log.append( "duplications range" );
393 _log.append( "mininal duplication re-rootings with shortest tree heigth" );
394 _log.append( ForesterUtil.LINE_SEPARATOR );
397 private final void writeStatsToLog( final int i, final GSDIR gsdir, final List<Integer> shortests ) {
398 final BasicDescriptiveStatistics stats = gsdir.getDuplicationsSumStats();
401 _log.append( gsdir.getMinDuplicationsSumGeneTrees().size() );
403 _log.append( stats.getN() );
405 _log.append( ( int ) stats.getMin() );
407 _log.append( ( int ) stats.getMax() );
409 _log.append( shortests.size() );
410 _log.append( ForesterUtil.LINE_SEPARATOR );
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>();
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();
422 else if ( n.getNodeData().isHasSequence()
423 && !ForesterUtil.isEmpty( n.getNodeData().getSequence().getSymbol() ) ) {
424 label = n.getNodeData().getSequence().getSymbol();
426 else if ( !ForesterUtil.isEmpty( n.getName() ) ) {
430 throw new RIOException( "node " + n + " has no appropriate label" );
432 if ( labels_set.contains( label ) ) {
433 throw new RIOException( "label " + label + " is not unique" );
435 labels_set.add( label );
439 Collections.sort( labels );
441 final IntMatrix m = new IntMatrix( labels );
443 for( final Phylogeny gt : analyzed_gene_trees ) {
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 );
451 throw new RIOException( "node \"" + mx + "\" not present in gene tree #" + counter );
455 for( int y = 0; y < m.size(); ++y ) {
456 my = m.getLabel( y );
459 throw new RIOException( "node \"" + my + "\" not present in gene tree #" + counter );
461 if ( !PhylogenyMethods.calculateLCAonTreeWithIdsInPreOrder( nx, ny ).isDuplication() ) {
462 m.inreaseByOne( x, y );
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,
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 );
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" );
491 final Phylogeny species_tree = SDIutil.parseSpeciesTree( gene_trees[ 0 ],
495 TAXONOMY_EXTRACTION.NO );
496 return new RIO( gene_trees, species_tree, algorithm, rerooting, outgroup, first, last, produce_log, verbose );
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 );
514 final Phylogeny[] gene_trees = factory.create( gene_trees_file, p );
515 return new RIO( gene_trees,
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,
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 );
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" );
547 return new RIO( gene_trees, species_tree, algorithm, rerooting, outgroup, first, last, produce_log, verbose );
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,
555 REROOTING.BY_ALGORITHM,
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,
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,
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 );
593 private final static void checkPreconditions( final Phylogeny[] gene_trees,
594 final Phylogeny species_tree,
595 final REROOTING rerooting,
596 final String outgroup,
598 final int last ) throws RIOException {
599 if ( !species_tree.isRooted() ) {
600 throw new RIOException( "species tree is not rooted" );
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 + ")" );
607 if ( ( rerooting == REROOTING.OUTGROUP ) && ForesterUtil.isEmpty( outgroup ) ) {
608 throw new RIOException( "outgroup not set for midpoint rooting" );
610 if ( ( rerooting != REROOTING.OUTGROUP ) && !ForesterUtil.isEmpty( outgroup ) ) {
611 throw new RIOException( "outgroup only used for midpoint rooting" );
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)" );
617 if ( rerooting == REROOTING.OUTGROUP ) {
619 gene_trees[ 0 ].getNode( outgroup );
621 catch ( final IllegalArgumentException e ) {
622 throw new RIOException( "cannot perform re-rooting by outgroup: " + e.getLocalizedMessage() );
627 private final static void removeSingleDescendentsNodes( final Phylogeny species_tree, final boolean verbose ) {
628 final int o = PhylogenyMethods.countNumberOfOneDescendantNodes( species_tree );
631 System.out.println( "warning: species tree has " + o
632 + " internal nodes with only one descendent which are therefore going to be removed" );
634 PhylogenyMethods.deleteInternalNodesWithOnlyOneDescendent( species_tree );
638 public enum REROOTING {
639 NONE, BY_ALGORITHM, MIDPOINT, OUTGROUP;