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
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
26 package org.forester.phylogeny;
28 import java.awt.Color;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collections;
34 import java.util.Comparator;
35 import java.util.HashSet;
36 import java.util.Iterator;
37 import java.util.List;
39 import java.util.SortedMap;
40 import java.util.TreeMap;
42 import org.forester.io.parsers.PhylogenyParser;
43 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
44 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
45 import org.forester.io.parsers.util.PhylogenyParserException;
46 import org.forester.phylogeny.data.BranchColor;
47 import org.forester.phylogeny.data.BranchWidth;
48 import org.forester.phylogeny.data.Confidence;
49 import org.forester.phylogeny.data.DomainArchitecture;
50 import org.forester.phylogeny.data.Event;
51 import org.forester.phylogeny.data.Identifier;
52 import org.forester.phylogeny.data.PhylogenyDataUtil;
53 import org.forester.phylogeny.data.Sequence;
54 import org.forester.phylogeny.data.Taxonomy;
55 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
56 import org.forester.phylogeny.factories.PhylogenyFactory;
57 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
58 import org.forester.util.BasicDescriptiveStatistics;
59 import org.forester.util.DescriptiveStatistics;
60 import org.forester.util.FailedConditionCheckException;
61 import org.forester.util.ForesterUtil;
63 public class PhylogenyMethods {
65 private static PhylogenyMethods _instance = null;
66 private PhylogenyNode _farthest_1 = null;
67 private PhylogenyNode _farthest_2 = null;
69 private PhylogenyMethods() {
70 // Hidden constructor.
74 * Calculates the distance between PhylogenyNodes node1 and node2.
79 * @return distance between node1 and node2
81 public double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) {
82 final PhylogenyNode lca =calculateLCA( node1, node2 );
83 final PhylogenyNode n1 = node1;
84 final PhylogenyNode n2 = node2;
85 return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) );
88 public double calculateFurthestDistance( final Phylogeny phylogeny ) {
89 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
94 PhylogenyNode node_1 = null;
95 PhylogenyNode node_2 = null;
96 double farthest_d = -Double.MAX_VALUE;
97 final PhylogenyMethods methods = PhylogenyMethods.getInstance();
98 final List<PhylogenyNode> ext_nodes = phylogeny.getRoot().getAllExternalDescendants();
99 for( int i = 1; i < ext_nodes.size(); ++i ) {
100 for( int j = 0; j < i; ++j ) {
101 final double d = methods.calculateDistance( ext_nodes.get( i ), ext_nodes.get( j ) );
103 throw new RuntimeException( "distance cannot be negative" );
105 if ( d > farthest_d ) {
107 node_1 = ext_nodes.get( i );
108 node_2 = ext_nodes.get( j );
112 _farthest_1 = node_1;
113 _farthest_2 = node_2;
117 final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) {
118 return calculateLCA( n1, n2 ).getNodeData().getEvent();
122 public Object clone() throws CloneNotSupportedException {
123 throw new CloneNotSupportedException();
126 public PhylogenyNode getFarthestNode1() {
130 public PhylogenyNode getFarthestNode2() {
134 final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) {
135 if ( n.isInternal() ) {
136 throw new IllegalArgumentException( "node is not external" );
138 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
139 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
140 final PhylogenyNode i = it.next();
141 if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) {
145 for( final PhylogenyNode d : to_delete ) {
146 phy.deleteSubtree( d, true );
148 phy.clearHashIdToNodeMap();
149 phy.externalNodesHaveChanged();
153 * Returns the LCA of PhylogenyNodes node1 and node2.
158 * @return LCA of node1 and node2
160 public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) {
161 if ( node1 == node2 ) {
164 if (( node1.getParent() == node2.getParent() ) /*&& node1.getParent() != null */ ) {
165 return node1.getParent();
167 int depth1 = node1.calculateDepth() ;
168 int depth2 = node2.calculateDepth() ;
169 while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) {
170 if ( depth1 > depth2 ) {
171 node1 = node1.getParent();
174 else if ( depth2 > depth1 ) {
175 node2 = node2.getParent();
179 if ( node1 == node2 ) {
182 node1 = node1.getParent();
183 node2 = node2.getParent();
188 throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" );
192 * Returns all orthologs of the external PhylogenyNode n of this Phylogeny.
193 * Orthologs are returned as List of node references.
195 * PRECONDITION: This tree must be binary and rooted, and speciation -
196 * duplication need to be assigned for each of its internal Nodes.
198 * Returns null if this Phylogeny is empty or if n is internal.
200 * external PhylogenyNode whose orthologs are to be returned
201 * @return Vector of references to all orthologous Nodes of PhylogenyNode n
202 * of this Phylogeny, null if this Phylogeny is empty or if n is
205 public List<PhylogenyNode> getOrthologousNodes( final Phylogeny phy, final PhylogenyNode node ) {
206 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
207 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
208 while ( it.hasNext() ) {
209 final PhylogenyNode temp_node = it.next();
210 if ( ( temp_node != node ) && isAreOrthologous( node, temp_node ) ) {
211 nodes.add( temp_node );
217 public static boolean isAreOrthologous( final PhylogenyNode node1, final PhylogenyNode node2 ) {
218 return !calculateLCA( node1, node2 ).isDuplication();
221 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
222 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
223 final Phylogeny[] trees = factory.create( file, parser );
224 if ( ( trees == null ) || ( trees.length == 0 ) ) {
225 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
230 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
232 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
233 for( final File file : files ) {
234 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
235 final Phylogeny[] trees = factory.create( file, parser );
236 if ( ( trees == null ) || ( trees.length == 0 ) ) {
237 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
239 tree_list.addAll( Arrays.asList( trees ) );
241 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
244 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
245 final PhylogenyNodeIterator it = phy.iteratorPostorder();
246 while ( it.hasNext() ) {
247 final PhylogenyNode n = it.next();
248 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
249 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
252 d = Double.parseDouble( n.getName() );
254 catch ( final Exception e ) {
258 n.getBranchData().addConfidence( new Confidence( d, "" ) );
266 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
267 final PhylogenyNodeIterator it = phy.iteratorPostorder();
268 while ( it.hasNext() ) {
269 final PhylogenyNode n = it.next();
270 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
273 value = Double.parseDouble( n.getName() );
275 catch ( final NumberFormatException e ) {
276 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
277 + e.getLocalizedMessage() );
279 if ( value >= 0.0 ) {
280 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
287 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
288 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
291 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
292 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
293 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
294 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
295 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
296 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
298 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
299 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
300 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
301 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
303 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
304 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
305 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
306 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
309 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
310 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
311 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
312 return n1.getNodeData().getSequence().getName().toLowerCase()
313 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
315 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
316 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
317 return n1.getNodeData().getSequence().getSymbol()
318 .compareTo( n2.getNodeData().getSequence().getSymbol() );
320 if ( ( n1.getNodeData().getSequence().getAccession() != null )
321 && ( n2.getNodeData().getSequence().getAccession() != null )
322 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
323 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
324 return n1.getNodeData().getSequence().getAccession().getValue()
325 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
328 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
329 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
334 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
337 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
338 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
339 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
340 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
341 return n1.getNodeData().getSequence().getName().toLowerCase()
342 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
344 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
345 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
346 return n1.getNodeData().getSequence().getSymbol()
347 .compareTo( n2.getNodeData().getSequence().getSymbol() );
349 if ( ( n1.getNodeData().getSequence().getAccession() != null )
350 && ( n2.getNodeData().getSequence().getAccession() != null )
351 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
352 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
353 return n1.getNodeData().getSequence().getAccession().getValue()
354 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
357 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
358 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
359 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
360 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
361 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
363 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
364 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
365 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
366 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
368 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
369 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
370 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
371 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
374 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
375 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
380 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
383 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
384 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
385 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
387 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
388 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
389 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
390 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
391 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
393 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
394 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
395 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
396 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
398 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
399 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
400 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
401 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
404 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
405 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
406 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
407 return n1.getNodeData().getSequence().getName().toLowerCase()
408 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
410 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
411 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
412 return n1.getNodeData().getSequence().getSymbol()
413 .compareTo( n2.getNodeData().getSequence().getSymbol() );
415 if ( ( n1.getNodeData().getSequence().getAccession() != null )
416 && ( n2.getNodeData().getSequence().getAccession() != null )
417 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
418 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
419 return n1.getNodeData().getSequence().getAccession().getValue()
420 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
426 Comparator<PhylogenyNode> c;
429 c = new PhylogenyNodeSortSequencePriority();
432 c = new PhylogenyNodeSortNodeNamePriority();
435 c = new PhylogenyNodeSortTaxonomyPriority();
437 final List<PhylogenyNode> descs = node.getDescendants();
438 Collections.sort( descs, c );
440 for( final PhylogenyNode desc : descs ) {
441 node.setChildNode( i++, desc );
445 final static public void transferNodeNameToField( final Phylogeny phy,
446 final PhylogenyMethods.PhylogenyNodeField field,
447 final boolean external_only ) throws PhyloXmlDataFormatException {
448 final PhylogenyNodeIterator it = phy.iteratorPostorder();
449 while ( it.hasNext() ) {
450 final PhylogenyNode n = it.next();
451 if ( external_only && n.isInternal() ) {
454 final String name = n.getName().trim();
455 if ( !ForesterUtil.isEmpty( name ) ) {
459 setTaxonomyCode( n, name );
461 case TAXONOMY_SCIENTIFIC_NAME:
463 if ( !n.getNodeData().isHasTaxonomy() ) {
464 n.getNodeData().setTaxonomy( new Taxonomy() );
466 n.getNodeData().getTaxonomy().setScientificName( name );
468 case TAXONOMY_COMMON_NAME:
470 if ( !n.getNodeData().isHasTaxonomy() ) {
471 n.getNodeData().setTaxonomy( new Taxonomy() );
473 n.getNodeData().getTaxonomy().setCommonName( name );
475 case SEQUENCE_SYMBOL:
477 if ( !n.getNodeData().isHasSequence() ) {
478 n.getNodeData().setSequence( new Sequence() );
480 n.getNodeData().getSequence().setSymbol( name );
484 if ( !n.getNodeData().isHasSequence() ) {
485 n.getNodeData().setSequence( new Sequence() );
487 n.getNodeData().getSequence().setName( name );
489 case TAXONOMY_ID_UNIPROT_1: {
490 if ( !n.getNodeData().isHasTaxonomy() ) {
491 n.getNodeData().setTaxonomy( new Taxonomy() );
494 final int i = name.indexOf( '_' );
496 id = name.substring( 0, i );
501 n.getNodeData().getTaxonomy()
502 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
505 case TAXONOMY_ID_UNIPROT_2: {
506 if ( !n.getNodeData().isHasTaxonomy() ) {
507 n.getNodeData().setTaxonomy( new Taxonomy() );
510 final int i = name.indexOf( '_' );
512 id = name.substring( i + 1, name.length() );
517 n.getNodeData().getTaxonomy()
518 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
522 if ( !n.getNodeData().isHasTaxonomy() ) {
523 n.getNodeData().setTaxonomy( new Taxonomy() );
525 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
533 static double addPhylogenyDistances( final double a, final double b ) {
534 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
537 else if ( a >= 0.0 ) {
540 else if ( b >= 0.0 ) {
543 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
546 // Helper for getUltraParalogousNodes( PhylogenyNode ).
547 public static boolean areAllChildrenDuplications( final PhylogenyNode n ) {
548 if ( n.isExternal() ) {
552 if ( n.isDuplication() ) {
554 for( final PhylogenyNode desc : n.getDescendants() ) {
555 if ( !areAllChildrenDuplications( desc ) ) {
567 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
568 if ( node.isExternal() ) {
572 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
574 while ( d != node ) {
575 if ( d.isCollapse() ) {
590 public static int calculateMaxDepth( final Phylogeny phy ) {
592 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
593 final PhylogenyNode node = iter.next();
594 final int steps = node.calculateDepth();
602 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
604 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
605 final PhylogenyNode node = iter.next();
606 final double d = node.calculateDistanceToRoot();
614 public static int countNumberOfPolytomies( final Phylogeny phy ) {
616 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
617 final PhylogenyNode n = iter.next();
618 if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
625 public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
626 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
627 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
628 final PhylogenyNode n = iter.next();
629 if ( !n.isExternal() ) {
630 stats.addValue( n.getNumberOfDescendants() );
636 public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
637 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
638 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
639 final PhylogenyNode n = iter.next();
640 if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
641 stats.addValue( n.getDistanceToParent() );
647 public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
648 final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
649 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
650 final PhylogenyNode n = iter.next();
651 if ( !n.isExternal() && !n.isRoot() ) {
652 if ( n.getBranchData().isHasConfidences() ) {
653 for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
654 final Confidence c = n.getBranchData().getConfidences().get( i );
655 if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
656 stats.add( i, new BasicDescriptiveStatistics() );
658 if ( !ForesterUtil.isEmpty( c.getType() ) ) {
659 if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
660 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
661 throw new IllegalArgumentException( "support values in node [" + n.toString()
662 + "] appear inconsistently ordered" );
665 stats.get( i ).setDescription( c.getType() );
667 stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
676 * Returns the set of distinct taxonomies of
677 * all external nodes of node.
678 * If at least one the external nodes has no taxonomy,
682 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
683 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
684 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
685 for( final PhylogenyNode n : descs ) {
686 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
689 tax_set.add( n.getNodeData().getTaxonomy() );
695 * Returns a map of distinct taxonomies of
696 * all external nodes of node.
697 * If at least one of the external nodes has no taxonomy,
701 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
702 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
703 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
704 for( final PhylogenyNode n : descs ) {
705 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
708 final Taxonomy t = n.getNodeData().getTaxonomy();
709 if ( tax_map.containsKey( t ) ) {
710 tax_map.put( t, tax_map.get( t ) + 1 );
719 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
720 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
722 for( final PhylogenyNode n : descs ) {
723 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
731 * Deep copies the phylogeny originating from this node.
733 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
734 if ( source == null ) {
738 final PhylogenyNode newnode = source.copyNodeData();
739 if ( !source.isExternal() ) {
740 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
741 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
749 * Shallow copies the phylogeny originating from this node.
751 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
752 if ( source == null ) {
756 final PhylogenyNode newnode = source.copyNodeDataShallow();
757 if ( !source.isExternal() ) {
758 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
759 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
766 public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
767 phy.clearHashIdToNodeMap();
768 for( final Integer id : to_delete ) {
769 phy.deleteSubtree( phy.getNode( id ), true );
771 phy.clearHashIdToNodeMap();
772 phy.externalNodesHaveChanged();
775 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
776 throws IllegalArgumentException {
777 for( final String element : node_names_to_delete ) {
778 if ( ForesterUtil.isEmpty( element ) ) {
781 List<PhylogenyNode> nodes = null;
782 nodes = p.getNodes( element );
783 final Iterator<PhylogenyNode> it = nodes.iterator();
784 while ( it.hasNext() ) {
785 final PhylogenyNode n = it.next();
786 if ( !n.isExternal() ) {
787 throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
789 p.deleteSubtree( n, true );
792 p.clearHashIdToNodeMap();
793 p.externalNodesHaveChanged();
796 public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
797 // final Set<Integer> to_delete = new HashSet<Integer>();
798 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
799 final PhylogenyNode n = it.next();
800 if ( n.getNodeData().isHasTaxonomy() ) {
801 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
802 //to_delete.add( n.getNodeId() );
803 phy.deleteSubtree( n, true );
807 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
810 phy.clearHashIdToNodeMap();
811 phy.externalNodesHaveChanged();
814 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
815 final Phylogeny p ) {
816 final PhylogenyNodeIterator it = p.iteratorExternalForward();
817 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
819 Arrays.sort( node_names_to_keep );
820 while ( it.hasNext() ) {
821 final String curent_name = it.next().getName();
822 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
823 to_delete[ i++ ] = curent_name;
826 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
827 final List<String> deleted = new ArrayList<String>();
828 for( final String n : to_delete ) {
829 if ( !ForesterUtil.isEmpty( n ) ) {
836 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
837 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
838 final Set<Integer> encountered = new HashSet<Integer>();
839 if ( !node.isExternal() ) {
840 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
841 for( PhylogenyNode current : exts ) {
842 descs.add( current );
843 while ( current != node ) {
844 current = current.getParent();
845 if ( encountered.contains( current.getId() ) ) {
848 descs.add( current );
849 encountered.add( current.getId() );
863 public static Color getBranchColorValue( final PhylogenyNode node ) {
864 if ( node.getBranchData().getBranchColor() == null ) {
867 return node.getBranchData().getBranchColor().getValue();
873 public static double getBranchWidthValue( final PhylogenyNode node ) {
874 if ( !node.getBranchData().isHasBranchWidth() ) {
875 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
877 return node.getBranchData().getBranchWidth().getValue();
883 public static double getConfidenceValue( final PhylogenyNode node ) {
884 if ( !node.getBranchData().isHasConfidences() ) {
885 return Confidence.CONFIDENCE_DEFAULT_VALUE;
887 return node.getBranchData().getConfidence( 0 ).getValue();
893 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
894 if ( !node.getBranchData().isHasConfidences() ) {
895 return new double[ 0 ];
897 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
899 for( final Confidence c : node.getBranchData().getConfidences() ) {
900 values[ i++ ] = c.getValue();
906 * Calculates the distance between PhylogenyNodes n1 and n2.
907 * PRECONDITION: n1 is a descendant of n2.
912 * @return distance between n1 and n2
914 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
917 if ( n1.getDistanceToParent() > 0.0 ) {
918 d += n1.getDistanceToParent();
926 * Returns taxonomy t if all external descendants have
927 * the same taxonomy t, null otherwise.
930 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
931 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
933 for( final PhylogenyNode n : descs ) {
934 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
937 else if ( tax == null ) {
938 tax = n.getNodeData().getTaxonomy();
940 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
947 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
948 final List<PhylogenyNode> children = node.getAllExternalDescendants();
949 PhylogenyNode farthest = null;
950 double longest = -Double.MAX_VALUE;
951 for( final PhylogenyNode child : children ) {
952 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
954 longest = PhylogenyMethods.getDistance( child, node );
960 public static PhylogenyMethods getInstance() {
961 if ( PhylogenyMethods._instance == null ) {
962 PhylogenyMethods._instance = new PhylogenyMethods();
964 return PhylogenyMethods._instance;
968 * Returns the largest confidence value found on phy.
970 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
971 double max = -Double.MAX_VALUE;
972 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
973 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
974 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
981 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
982 int min = Integer.MAX_VALUE;
985 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
987 if ( n.isInternal() ) {
988 d = n.getNumberOfDescendants();
998 * Convenience method for display purposes.
999 * Not intended for algorithms.
1001 public static String getSpecies( final PhylogenyNode node ) {
1002 if ( !node.getNodeData().isHasTaxonomy() ) {
1005 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
1006 return node.getNodeData().getTaxonomy().getScientificName();
1008 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1009 return node.getNodeData().getTaxonomy().getTaxonomyCode();
1012 return node.getNodeData().getTaxonomy().getCommonName();
1017 * Returns all Nodes which are connected to external PhylogenyNode n of this
1018 * Phylogeny by a path containing only speciation events. We call these
1019 * "super orthologs". Nodes are returned as Vector of references to Nodes.
1021 * PRECONDITION: This tree must be binary and rooted, and speciation -
1022 * duplication need to be assigned for each of its internal Nodes.
1024 * Returns null if this Phylogeny is empty or if n is internal.
1026 * external PhylogenyNode whose strictly speciation related Nodes
1027 * are to be returned
1028 * @return Vector of references to all strictly speciation related Nodes of
1029 * PhylogenyNode n of this Phylogeny, null if this Phylogeny is
1030 * empty or if n is internal
1032 public static List<PhylogenyNode> getSuperOrthologousNodes( final PhylogenyNode n ) {
1034 PhylogenyNode node = n, deepest = null;
1035 final List<PhylogenyNode> v = new ArrayList<PhylogenyNode>();
1036 if ( !node.isExternal() ) {
1039 while ( !node.isRoot() && !node.getParent().isDuplication() ) {
1040 node = node.getParent();
1043 deepest.setIndicatorsToZero();
1045 if ( !node.isExternal() ) {
1046 if ( node.getIndicator() == 0 ) {
1047 node.setIndicator( ( byte ) 1 );
1048 if ( !node.isDuplication() ) {
1049 node = node.getChildNode1();
1052 if ( node.getIndicator() == 1 ) {
1053 node.setIndicator( ( byte ) 2 );
1054 if ( !node.isDuplication() ) {
1055 node = node.getChildNode2();
1058 if ( ( node != deepest ) && ( node.getIndicator() == 2 ) ) {
1059 node = node.getParent();
1066 if ( node != deepest ) {
1067 node = node.getParent();
1070 node.setIndicator( ( byte ) 2 );
1073 } while ( ( node != deepest ) || ( deepest.getIndicator() != 2 ) );
1078 * Convenience method for display purposes.
1079 * Not intended for algorithms.
1081 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
1082 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
1085 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
1089 * Returns all Nodes which are connected to external PhylogenyNode n of this
1090 * Phylogeny by a path containing, and leading to, only duplication events.
1091 * We call these "ultra paralogs". Nodes are returned as Vector of
1092 * references to Nodes.
1094 * PRECONDITION: This tree must be binary and rooted, and speciation -
1095 * duplication need to be assigned for each of its internal Nodes.
1097 * Returns null if this Phylogeny is empty or if n is internal.
1099 * (Last modified: 10/06/01)
1102 * external PhylogenyNode whose ultra paralogs are to be returned
1103 * @return Vector of references to all ultra paralogs of PhylogenyNode n of
1104 * this Phylogeny, null if this Phylogeny is empty or if n is
1107 public static List<PhylogenyNode> getUltraParalogousNodes( final PhylogenyNode n ) {
1109 PhylogenyNode node = n;
1110 if ( !node.isExternal() ) {
1113 while ( !node.isRoot() && node.getParent().isDuplication() && areAllChildrenDuplications( node.getParent() ) ) {
1114 node = node.getParent();
1116 final List<PhylogenyNode> nodes = node.getAllExternalDescendants();
1121 public static String inferCommonPartOfScientificNameOfDescendants( final PhylogenyNode node ) {
1122 final List<PhylogenyNode> descs = node.getDescendants();
1124 for( final PhylogenyNode n : descs ) {
1125 if ( !n.getNodeData().isHasTaxonomy()
1126 || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1129 else if ( sn == null ) {
1130 sn = n.getNodeData().getTaxonomy().getScientificName().trim();
1133 String sn_current = n.getNodeData().getTaxonomy().getScientificName().trim();
1134 if ( !sn.equals( sn_current ) ) {
1135 boolean overlap = false;
1136 while ( ( sn.indexOf( ' ' ) >= 0 ) || ( sn_current.indexOf( ' ' ) >= 0 ) ) {
1137 if ( ForesterUtil.countChars( sn, ' ' ) > ForesterUtil.countChars( sn_current, ' ' ) ) {
1138 sn = sn.substring( 0, sn.lastIndexOf( ' ' ) ).trim();
1141 sn_current = sn_current.substring( 0, sn_current.lastIndexOf( ' ' ) ).trim();
1143 if ( sn.equals( sn_current ) ) {
1157 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
1158 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1159 if ( node.getChildNode( i ).isExternal() ) {
1167 * This is case insensitive.
1170 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
1171 final String[] providers ) {
1172 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
1173 final String my_tax_prov = tax.getIdentifier().getProvider();
1174 for( final String provider : providers ) {
1175 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
1186 private static boolean match( final String s,
1188 final boolean case_sensitive,
1189 final boolean partial ) {
1190 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1193 String my_s = s.trim();
1194 String my_query = query.trim();
1195 if ( !case_sensitive ) {
1196 my_s = my_s.toLowerCase();
1197 my_query = my_query.toLowerCase();
1200 return my_s.indexOf( my_query ) >= 0;
1203 return my_s.equals( my_query );
1207 public static void midpointRoot( final Phylogeny phylogeny ) {
1208 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
1211 final PhylogenyMethods methods = getInstance();
1212 final double farthest_d = methods.calculateFurthestDistance( phylogeny );
1213 final PhylogenyNode f1 = methods.getFarthestNode1();
1214 final PhylogenyNode f2 = methods.getFarthestNode2();
1215 if ( farthest_d <= 0.0 ) {
1218 double x = farthest_d / 2.0;
1219 PhylogenyNode n = f1;
1220 if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
1224 while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
1225 x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
1228 phylogeny.reRoot( n, x );
1229 phylogeny.recalculateNumberOfExternalDescendants( true );
1230 final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
1231 final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
1232 final double da = getDistance( a, phylogeny.getRoot() );
1233 final double db = getDistance( b, phylogeny.getRoot() );
1234 if ( Math.abs( da - db ) > 0.000001 ) {
1235 throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed: da="
1236 + da + ", db=" + db + ", diff=" + Math.abs( da - db ) );
1240 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
1241 final double max_bootstrap_value,
1242 final double max_normalized_value ) {
1243 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
1244 final PhylogenyNode node = iter.next();
1245 if ( node.isInternal() ) {
1246 final double confidence = getConfidenceValue( node );
1247 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
1248 if ( confidence >= max_bootstrap_value ) {
1249 setBootstrapConfidence( node, max_normalized_value );
1252 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
1259 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
1260 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1261 if ( phy.isEmpty() ) {
1264 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1265 nodes.add( iter.next() );
1270 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
1271 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
1272 final PhylogenyNode node = iter.next();
1277 if ( node.isInternal() ) {
1278 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
1279 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1280 final PhylogenyNode child_node = node.getChildNode( i );
1281 final Color child_color = getBranchColorValue( child_node );
1282 if ( child_color != null ) {
1284 red += child_color.getRed();
1285 green += child_color.getGreen();
1286 blue += child_color.getBlue();
1289 setBranchColorValue( node,
1290 new Color( ForesterUtil.roundToInt( red / n ),
1291 ForesterUtil.roundToInt( green / n ),
1292 ForesterUtil.roundToInt( blue / n ) ) );
1297 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
1298 if ( remove_me.isRoot() ) {
1299 throw new IllegalArgumentException( "ill advised attempt to remove root node" );
1301 if ( remove_me.isExternal() ) {
1302 phylogeny.deleteSubtree( remove_me, false );
1303 phylogeny.clearHashIdToNodeMap();
1304 phylogeny.externalNodesHaveChanged();
1307 final PhylogenyNode parent = remove_me.getParent();
1308 final List<PhylogenyNode> descs = remove_me.getDescendants();
1309 parent.removeChildNode( remove_me );
1310 for( final PhylogenyNode desc : descs ) {
1311 parent.addAsChild( desc );
1312 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
1313 desc.getDistanceToParent() ) );
1315 remove_me.setParent( null );
1316 phylogeny.clearHashIdToNodeMap();
1317 phylogeny.externalNodesHaveChanged();
1321 public static List<PhylogenyNode> searchData( final String query,
1322 final Phylogeny phy,
1323 final boolean case_sensitive,
1324 final boolean partial,
1325 final boolean search_domains ) {
1326 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1327 if ( phy.isEmpty() || ( query == null ) ) {
1330 if ( ForesterUtil.isEmpty( query ) ) {
1333 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1334 final PhylogenyNode node = iter.next();
1335 boolean match = false;
1336 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1339 else if ( node.getNodeData().isHasTaxonomy()
1340 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1343 else if ( node.getNodeData().isHasTaxonomy()
1344 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1347 else if ( node.getNodeData().isHasTaxonomy()
1348 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1351 else if ( node.getNodeData().isHasTaxonomy()
1352 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1353 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1359 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1360 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1361 I: for( final String syn : syns ) {
1362 if ( match( syn, query, case_sensitive, partial ) ) {
1368 if ( !match && node.getNodeData().isHasSequence()
1369 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1372 if ( !match && node.getNodeData().isHasSequence()
1373 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1377 && node.getNodeData().isHasSequence()
1378 && ( node.getNodeData().getSequence().getAccession() != null )
1379 && match( node.getNodeData().getSequence().getAccession().getValue(),
1385 if ( search_domains && !match && node.getNodeData().isHasSequence()
1386 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1387 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1388 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1389 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1395 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1396 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1397 I: while ( it.hasNext() ) {
1398 if ( match( it.next(), query, case_sensitive, partial ) ) {
1403 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1404 I: while ( it.hasNext() ) {
1405 if ( match( it.next(), query, case_sensitive, partial ) ) {
1418 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1419 final Phylogeny phy,
1420 final boolean case_sensitive,
1421 final boolean partial,
1422 final boolean search_domains ) {
1423 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1424 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1427 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1428 final PhylogenyNode node = iter.next();
1429 boolean all_matched = true;
1430 for( final String query : queries ) {
1431 boolean match = false;
1432 if ( ForesterUtil.isEmpty( query ) ) {
1435 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1438 else if ( node.getNodeData().isHasTaxonomy()
1439 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1442 else if ( node.getNodeData().isHasTaxonomy()
1443 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1446 else if ( node.getNodeData().isHasTaxonomy()
1447 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1450 else if ( node.getNodeData().isHasTaxonomy()
1451 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1452 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1458 else if ( node.getNodeData().isHasTaxonomy()
1459 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1460 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1461 I: for( final String syn : syns ) {
1462 if ( match( syn, query, case_sensitive, partial ) ) {
1468 if ( !match && node.getNodeData().isHasSequence()
1469 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1472 if ( !match && node.getNodeData().isHasSequence()
1473 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1477 && node.getNodeData().isHasSequence()
1478 && ( node.getNodeData().getSequence().getAccession() != null )
1479 && match( node.getNodeData().getSequence().getAccession().getValue(),
1485 if ( search_domains && !match && node.getNodeData().isHasSequence()
1486 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1487 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1488 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1489 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1495 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1496 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1497 I: while ( it.hasNext() ) {
1498 if ( match( it.next(), query, case_sensitive, partial ) ) {
1503 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1504 I: while ( it.hasNext() ) {
1505 if ( match( it.next(), query, case_sensitive, partial ) ) {
1512 all_matched = false;
1516 if ( all_matched ) {
1524 * Convenience method.
1525 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1527 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1528 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1531 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1532 if ( node.getBranchData().getBranchColor() == null ) {
1533 node.getBranchData().setBranchColor( new BranchColor() );
1535 node.getBranchData().getBranchColor().setValue( color );
1539 * Convenience method
1541 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1542 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1546 * Convenience method.
1547 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1549 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1550 setConfidence( node, confidence_value, "" );
1554 * Convenience method.
1555 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1557 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1558 Confidence c = null;
1559 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1560 c = node.getBranchData().getConfidence( 0 );
1563 c = new Confidence();
1564 node.getBranchData().addConfidence( c );
1567 c.setValue( confidence_value );
1570 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1571 if ( !node.getNodeData().isHasTaxonomy() ) {
1572 node.getNodeData().setTaxonomy( new Taxonomy() );
1574 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1578 * Convenience method to set the taxonomy code of a phylogeny node.
1582 * @param taxonomy_code
1583 * @throws PhyloXmlDataFormatException
1585 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1586 throws PhyloXmlDataFormatException {
1587 if ( !node.getNodeData().isHasTaxonomy() ) {
1588 node.getNodeData().setTaxonomy( new Taxonomy() );
1590 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1594 * Removes from Phylogeny to_be_stripped all external Nodes which are
1595 * associated with a species NOT found in Phylogeny reference.
1598 * a reference Phylogeny
1599 * @param to_be_stripped
1600 * Phylogeny to be stripped
1601 * @return number of external nodes removed from to_be_stripped
1603 public static int taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference, final Phylogeny to_be_stripped ) {
1604 final Set<String> ref_ext_taxo = new HashSet<String>();
1605 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1606 final PhylogenyNode n = it.next();
1607 if ( !n.getNodeData().isHasTaxonomy() ) {
1608 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1610 // ref_ext_taxo.add( getSpecies( n ) );
1611 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1612 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1614 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1615 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1618 System.out.println( " ref_ext_tax:" );
1619 for( final String string : ref_ext_taxo ) {
1620 System.out.println( string );
1622 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1623 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1624 final PhylogenyNode n = it.next();
1625 if ( !n.getNodeData().isHasTaxonomy() ) {
1626 nodes_to_delete.add( n );
1628 else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1629 && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1630 nodes_to_delete.add( n );
1633 System.out.println( " to delete:" );
1634 for( final PhylogenyNode string : nodes_to_delete ) {
1635 System.out.println( string.getNodeData().getTaxonomy().getTaxonomyCode() );
1637 for( final PhylogenyNode phylogenyNode : nodes_to_delete ) {
1638 to_be_stripped.deleteSubtree( phylogenyNode, true );
1640 to_be_stripped.clearHashIdToNodeMap();
1641 to_be_stripped.externalNodesHaveChanged();
1642 return nodes_to_delete.size();
1646 * Arranges the order of childern for each node of this Phylogeny in such a
1647 * way that either the branch with more children is on top (right) or on
1648 * bottom (left), dependent on the value of boolean order.
1651 * decides in which direction to order
1654 public static void orderAppearance( final PhylogenyNode n,
1655 final boolean order,
1656 final boolean order_ext_alphabetically,
1657 final DESCENDANT_SORT_PRIORITY pri ) {
1658 if ( n.isExternal() ) {
1662 PhylogenyNode temp = null;
1663 if ( ( n.getNumberOfDescendants() == 2 )
1664 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
1665 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
1666 temp = n.getChildNode1();
1667 n.setChild1( n.getChildNode2() );
1668 n.setChild2( temp );
1670 else if ( order_ext_alphabetically ) {
1671 boolean all_ext = true;
1672 for( final PhylogenyNode i : n.getDescendants() ) {
1673 if ( !i.isExternal() ) {
1679 PhylogenyMethods.sortNodeDescendents( n, pri );
1682 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
1683 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
1688 public static enum PhylogenyNodeField {
1691 TAXONOMY_SCIENTIFIC_NAME,
1692 TAXONOMY_COMMON_NAME,
1695 TAXONOMY_ID_UNIPROT_1,
1696 TAXONOMY_ID_UNIPROT_2,
1700 public static enum TAXONOMY_EXTRACTION {
1701 NO, YES, PFAM_STYLE_ONLY;
1704 public static enum DESCENDANT_SORT_PRIORITY {
1705 TAXONOMY, SEQUENCE, NODE_NAME;