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.Identifier;
51 import org.forester.phylogeny.data.PhylogenyDataUtil;
52 import org.forester.phylogeny.data.Sequence;
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.phylogeny.iterators.PhylogenyNodeIterator;
57 import org.forester.util.BasicDescriptiveStatistics;
58 import org.forester.util.DescriptiveStatistics;
59 import org.forester.util.FailedConditionCheckException;
60 import org.forester.util.ForesterUtil;
62 public class PhylogenyMethods {
64 private static PhylogenyMethods _instance = null;
65 private final Set<Integer> _temp_hash_set = new HashSet<Integer>();
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 = obtainLCA( 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;
118 public Object clone() throws CloneNotSupportedException {
119 throw new CloneNotSupportedException();
122 public PhylogenyNode getFarthestNode1() {
126 public PhylogenyNode getFarthestNode2() {
131 * Returns the LCA of PhylogenyNodes node1 and node2.
136 * @return LCA of node1 and node2
138 public PhylogenyNode obtainLCA( final PhylogenyNode node1, final PhylogenyNode node2 ) {
139 _temp_hash_set.clear();
140 PhylogenyNode n1 = node1;
141 PhylogenyNode n2 = node2;
142 _temp_hash_set.add( n1.getId() );
143 while ( !n1.isRoot() ) {
145 _temp_hash_set.add( n1.getId() );
147 while ( !_temp_hash_set.contains( n2.getId() ) && !n2.isRoot() ) {
150 if ( !_temp_hash_set.contains( n2.getId() ) ) {
151 throw new IllegalArgumentException( "attempt to get LCA of two nodes which do not share a common root" );
157 * Returns all orthologs of the external PhylogenyNode n of this Phylogeny.
158 * Orthologs are returned as List of node references.
160 * PRECONDITION: This tree must be binary and rooted, and speciation -
161 * duplication need to be assigned for each of its internal Nodes.
163 * Returns null if this Phylogeny is empty or if n is internal.
165 * external PhylogenyNode whose orthologs are to be returned
166 * @return Vector of references to all orthologous Nodes of PhylogenyNode n
167 * of this Phylogeny, null if this Phylogeny is empty or if n is
170 public List<PhylogenyNode> getOrthologousNodes( final Phylogeny phy, final PhylogenyNode node ) {
171 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
172 final PhylogenyNodeIterator it = phy.iteratorExternalForward();
173 while ( it.hasNext() ) {
174 final PhylogenyNode temp_node = it.next();
175 if ( ( temp_node != node ) && isAreOrthologous( node, temp_node ) ) {
176 nodes.add( temp_node );
182 public boolean isAreOrthologous( final PhylogenyNode node1, final PhylogenyNode node2 ) {
183 return !obtainLCA( node1, node2 ).isDuplication();
186 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
187 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
188 final Phylogeny[] trees = factory.create( file, parser );
189 if ( ( trees == null ) || ( trees.length == 0 ) ) {
190 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
195 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
197 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
198 for( final File file : files ) {
199 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
200 final Phylogeny[] trees = factory.create( file, parser );
201 if ( ( trees == null ) || ( trees.length == 0 ) ) {
202 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
204 tree_list.addAll( Arrays.asList( trees ) );
206 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
209 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
210 final PhylogenyNodeIterator it = phy.iteratorPostorder();
211 while ( it.hasNext() ) {
212 final PhylogenyNode n = it.next();
213 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
214 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
217 d = Double.parseDouble( n.getName() );
219 catch ( final Exception e ) {
223 n.getBranchData().addConfidence( new Confidence( d, "" ) );
231 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
232 final PhylogenyNodeIterator it = phy.iteratorPostorder();
233 while ( it.hasNext() ) {
234 final PhylogenyNode n = it.next();
235 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
238 value = Double.parseDouble( n.getName() );
240 catch ( final NumberFormatException e ) {
241 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
242 + e.getLocalizedMessage() );
244 if ( value >= 0.0 ) {
245 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
252 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
253 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
256 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
257 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
258 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
259 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
260 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
261 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
263 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
264 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
265 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
266 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
268 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
269 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
270 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
271 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
274 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
275 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
276 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
277 return n1.getNodeData().getSequence().getName().toLowerCase()
278 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
280 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
281 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
282 return n1.getNodeData().getSequence().getSymbol()
283 .compareTo( n2.getNodeData().getSequence().getSymbol() );
285 if ( ( n1.getNodeData().getSequence().getAccession() != null )
286 && ( n2.getNodeData().getSequence().getAccession() != null )
287 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
288 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
289 return n1.getNodeData().getSequence().getAccession().getValue()
290 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
293 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
294 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
299 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
302 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
303 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
304 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
305 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
306 return n1.getNodeData().getSequence().getName().toLowerCase()
307 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
309 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
310 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
311 return n1.getNodeData().getSequence().getSymbol()
312 .compareTo( n2.getNodeData().getSequence().getSymbol() );
314 if ( ( n1.getNodeData().getSequence().getAccession() != null )
315 && ( n2.getNodeData().getSequence().getAccession() != null )
316 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
317 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
318 return n1.getNodeData().getSequence().getAccession().getValue()
319 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
322 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
323 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
324 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
325 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
326 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
328 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
329 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
330 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
331 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
333 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
334 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
335 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
336 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
339 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
340 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
345 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
348 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
349 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
350 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
352 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
353 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
354 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
355 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
356 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
358 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
359 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
360 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
361 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
363 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
364 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
365 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
366 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
369 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
370 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
371 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
372 return n1.getNodeData().getSequence().getName().toLowerCase()
373 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
375 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
376 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
377 return n1.getNodeData().getSequence().getSymbol()
378 .compareTo( n2.getNodeData().getSequence().getSymbol() );
380 if ( ( n1.getNodeData().getSequence().getAccession() != null )
381 && ( n2.getNodeData().getSequence().getAccession() != null )
382 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
383 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
384 return n1.getNodeData().getSequence().getAccession().getValue()
385 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
391 Comparator<PhylogenyNode> c;
394 c = new PhylogenyNodeSortSequencePriority();
397 c = new PhylogenyNodeSortNodeNamePriority();
400 c = new PhylogenyNodeSortTaxonomyPriority();
402 final List<PhylogenyNode> descs = node.getDescendants();
403 Collections.sort( descs, c );
405 for( final PhylogenyNode desc : descs ) {
406 node.setChildNode( i++, desc );
410 final static public void transferNodeNameToField( final Phylogeny phy,
411 final PhylogenyMethods.PhylogenyNodeField field,
412 final boolean external_only ) throws PhyloXmlDataFormatException {
413 final PhylogenyNodeIterator it = phy.iteratorPostorder();
414 while ( it.hasNext() ) {
415 final PhylogenyNode n = it.next();
416 if ( external_only && n.isInternal() ) {
419 final String name = n.getName().trim();
420 if ( !ForesterUtil.isEmpty( name ) ) {
424 setTaxonomyCode( n, name );
426 case TAXONOMY_SCIENTIFIC_NAME:
428 if ( !n.getNodeData().isHasTaxonomy() ) {
429 n.getNodeData().setTaxonomy( new Taxonomy() );
431 n.getNodeData().getTaxonomy().setScientificName( name );
433 case TAXONOMY_COMMON_NAME:
435 if ( !n.getNodeData().isHasTaxonomy() ) {
436 n.getNodeData().setTaxonomy( new Taxonomy() );
438 n.getNodeData().getTaxonomy().setCommonName( name );
440 case SEQUENCE_SYMBOL:
442 if ( !n.getNodeData().isHasSequence() ) {
443 n.getNodeData().setSequence( new Sequence() );
445 n.getNodeData().getSequence().setSymbol( name );
449 if ( !n.getNodeData().isHasSequence() ) {
450 n.getNodeData().setSequence( new Sequence() );
452 n.getNodeData().getSequence().setName( name );
454 case TAXONOMY_ID_UNIPROT_1: {
455 if ( !n.getNodeData().isHasTaxonomy() ) {
456 n.getNodeData().setTaxonomy( new Taxonomy() );
459 final int i = name.indexOf( '_' );
461 id = name.substring( 0, i );
466 n.getNodeData().getTaxonomy()
467 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
470 case TAXONOMY_ID_UNIPROT_2: {
471 if ( !n.getNodeData().isHasTaxonomy() ) {
472 n.getNodeData().setTaxonomy( new Taxonomy() );
475 final int i = name.indexOf( '_' );
477 id = name.substring( i + 1, name.length() );
482 n.getNodeData().getTaxonomy()
483 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
487 if ( !n.getNodeData().isHasTaxonomy() ) {
488 n.getNodeData().setTaxonomy( new Taxonomy() );
490 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
498 static double addPhylogenyDistances( final double a, final double b ) {
499 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
502 else if ( a >= 0.0 ) {
505 else if ( b >= 0.0 ) {
508 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
511 // Helper for getUltraParalogousNodes( PhylogenyNode ).
512 public static boolean areAllChildrenDuplications( final PhylogenyNode n ) {
513 if ( n.isExternal() ) {
517 if ( n.isDuplication() ) {
519 for( final PhylogenyNode desc : n.getDescendants() ) {
520 if ( !areAllChildrenDuplications( desc ) ) {
532 public static int calculateDepth( final PhylogenyNode node ) {
533 PhylogenyNode n = node;
535 while ( !n.isRoot() ) {
542 public static double calculateDistanceToRoot( final PhylogenyNode node ) {
543 PhylogenyNode n = node;
545 while ( !n.isRoot() ) {
546 if ( n.getDistanceToParent() > 0.0 ) {
547 d += n.getDistanceToParent();
554 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
555 if ( node.isExternal() ) {
559 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
561 while ( d != node ) {
562 if ( d.isCollapse() ) {
577 public static int calculateMaxDepth( final Phylogeny phy ) {
579 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
580 final PhylogenyNode node = iter.next();
581 final int steps = calculateDepth( node );
589 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
591 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
592 final PhylogenyNode node = iter.next();
593 final double d = calculateDistanceToRoot( node );
601 public static int countNumberOfPolytomies( final Phylogeny phy ) {
603 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
604 final PhylogenyNode n = iter.next();
605 if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
612 public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
613 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
614 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
615 final PhylogenyNode n = iter.next();
616 if ( !n.isExternal() ) {
617 stats.addValue( n.getNumberOfDescendants() );
623 public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
624 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
625 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
626 final PhylogenyNode n = iter.next();
627 if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
628 stats.addValue( n.getDistanceToParent() );
634 public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
635 final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
636 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
637 final PhylogenyNode n = iter.next();
638 if ( !n.isExternal() && !n.isRoot() ) {
639 if ( n.getBranchData().isHasConfidences() ) {
640 for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
641 final Confidence c = n.getBranchData().getConfidences().get( i );
642 if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
643 stats.add( i, new BasicDescriptiveStatistics() );
645 if ( !ForesterUtil.isEmpty( c.getType() ) ) {
646 if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
647 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
648 throw new IllegalArgumentException( "support values in node [" + n.toString()
649 + "] appear inconsistently ordered" );
652 stats.get( i ).setDescription( c.getType() );
654 stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
663 * Returns the set of distinct taxonomies of
664 * all external nodes of node.
665 * If at least one the external nodes has no taxonomy,
669 public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
670 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
671 final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
672 for( final PhylogenyNode n : descs ) {
673 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
676 tax_set.add( n.getNodeData().getTaxonomy() );
682 * Returns a map of distinct taxonomies of
683 * all external nodes of node.
684 * If at least one of the external nodes has no taxonomy,
688 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
689 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
690 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
691 for( final PhylogenyNode n : descs ) {
692 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
695 final Taxonomy t = n.getNodeData().getTaxonomy();
696 if ( tax_map.containsKey( t ) ) {
697 tax_map.put( t, tax_map.get( t ) + 1 );
706 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
707 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
709 for( final PhylogenyNode n : descs ) {
710 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
718 * Deep copies the phylogeny originating from this node.
720 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
721 if ( source == null ) {
725 final PhylogenyNode newnode = source.copyNodeData();
726 if ( !source.isExternal() ) {
727 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
728 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
736 * Shallow copies the phylogeny originating from this node.
738 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
739 if ( source == null ) {
743 final PhylogenyNode newnode = source.copyNodeDataShallow();
744 if ( !source.isExternal() ) {
745 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
746 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
753 public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
755 for( final Integer id : to_delete ) {
756 phy.deleteSubtree( phy.getNode( id ), true );
761 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
762 throws IllegalArgumentException {
763 for( int i = 0; i < node_names_to_delete.length; ++i ) {
764 if ( ForesterUtil.isEmpty( node_names_to_delete[ i ] ) ) {
767 List<PhylogenyNode> nodes = null;
768 nodes = p.getNodes( node_names_to_delete[ i ] );
769 final Iterator<PhylogenyNode> it = nodes.iterator();
770 while ( it.hasNext() ) {
771 final PhylogenyNode n = it.next();
772 if ( !n.isExternal() ) {
773 throw new IllegalArgumentException( "attempt to delete non-external node \""
774 + node_names_to_delete[ i ] + "\"" );
776 p.deleteSubtree( n, true );
781 public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
782 // final Set<Integer> to_delete = new HashSet<Integer>();
783 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
784 final PhylogenyNode n = it.next();
785 if ( n.getNodeData().isHasTaxonomy() ) {
786 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
787 //to_delete.add( n.getNodeId() );
788 phy.deleteSubtree( n, true );
792 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
796 phy.externalNodesHaveChanged();
797 // deleteExternalNodesNegativeSelection( to_delete, phy );
800 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
801 final Phylogeny p ) {
802 final PhylogenyNodeIterator it = p.iteratorExternalForward();
803 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
805 Arrays.sort( node_names_to_keep );
806 while ( it.hasNext() ) {
807 final String curent_name = it.next().getName();
808 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
809 to_delete[ i++ ] = curent_name;
812 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
813 final List<String> deleted = new ArrayList<String>();
814 for( final String n : to_delete ) {
815 if ( !ForesterUtil.isEmpty( n ) ) {
822 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
823 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
824 final Set<Integer> encountered = new HashSet<Integer>();
825 if ( !node.isExternal() ) {
826 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
827 for( PhylogenyNode current : exts ) {
828 descs.add( current );
829 while ( current != node ) {
830 current = current.getParent();
831 if ( encountered.contains( current.getId() ) ) {
834 descs.add( current );
835 encountered.add( current.getId() );
849 public static Color getBranchColorValue( final PhylogenyNode node ) {
850 if ( node.getBranchData().getBranchColor() == null ) {
853 return node.getBranchData().getBranchColor().getValue();
859 public static double getBranchWidthValue( final PhylogenyNode node ) {
860 if ( !node.getBranchData().isHasBranchWidth() ) {
861 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
863 return node.getBranchData().getBranchWidth().getValue();
869 public static double getConfidenceValue( final PhylogenyNode node ) {
870 if ( !node.getBranchData().isHasConfidences() ) {
871 return Confidence.CONFIDENCE_DEFAULT_VALUE;
873 return node.getBranchData().getConfidence( 0 ).getValue();
879 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
880 if ( !node.getBranchData().isHasConfidences() ) {
881 return new double[ 0 ];
883 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
885 for( final Confidence c : node.getBranchData().getConfidences() ) {
886 values[ i++ ] = c.getValue();
892 * Calculates the distance between PhylogenyNodes n1 and n2.
893 * PRECONDITION: n1 is a descendant of n2.
898 * @return distance between n1 and n2
900 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
903 if ( n1.getDistanceToParent() > 0.0 ) {
904 d += n1.getDistanceToParent();
912 * Returns taxonomy t if all external descendants have
913 * the same taxonomy t, null otherwise.
916 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
917 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
919 for( final PhylogenyNode n : descs ) {
920 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
923 else if ( tax == null ) {
924 tax = n.getNodeData().getTaxonomy();
926 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
933 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
934 final List<PhylogenyNode> children = node.getAllExternalDescendants();
935 PhylogenyNode farthest = null;
936 double longest = -Double.MAX_VALUE;
937 for( final PhylogenyNode child : children ) {
938 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
940 longest = PhylogenyMethods.getDistance( child, node );
946 public static PhylogenyMethods getInstance() {
947 if ( PhylogenyMethods._instance == null ) {
948 PhylogenyMethods._instance = new PhylogenyMethods();
950 return PhylogenyMethods._instance;
954 * Returns the largest confidence value found on phy.
956 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
957 double max = -Double.MAX_VALUE;
958 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
959 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
960 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
967 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
968 int min = Integer.MAX_VALUE;
971 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
973 if ( n.isInternal() ) {
974 d = n.getNumberOfDescendants();
984 * Convenience method for display purposes.
985 * Not intended for algorithms.
987 public static String getSpecies( final PhylogenyNode node ) {
988 if ( !node.getNodeData().isHasTaxonomy() ) {
991 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
992 return node.getNodeData().getTaxonomy().getScientificName();
994 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
995 return node.getNodeData().getTaxonomy().getTaxonomyCode();
998 return node.getNodeData().getTaxonomy().getCommonName();
1003 * Returns all Nodes which are connected to external PhylogenyNode n of this
1004 * Phylogeny by a path containing only speciation events. We call these
1005 * "super orthologs". Nodes are returned as Vector of references to Nodes.
1007 * PRECONDITION: This tree must be binary and rooted, and speciation -
1008 * duplication need to be assigned for each of its internal Nodes.
1010 * Returns null if this Phylogeny is empty or if n is internal.
1012 * external PhylogenyNode whose strictly speciation related Nodes
1013 * are to be returned
1014 * @return Vector of references to all strictly speciation related Nodes of
1015 * PhylogenyNode n of this Phylogeny, null if this Phylogeny is
1016 * empty or if n is internal
1018 public static List<PhylogenyNode> getSuperOrthologousNodes( final PhylogenyNode n ) {
1020 PhylogenyNode node = n, deepest = null;
1021 final List<PhylogenyNode> v = new ArrayList<PhylogenyNode>();
1022 if ( !node.isExternal() ) {
1025 while ( !node.isRoot() && !node.getParent().isDuplication() ) {
1026 node = node.getParent();
1029 deepest.setIndicatorsToZero();
1031 if ( !node.isExternal() ) {
1032 if ( node.getIndicator() == 0 ) {
1033 node.setIndicator( ( byte ) 1 );
1034 if ( !node.isDuplication() ) {
1035 node = node.getChildNode1();
1038 if ( node.getIndicator() == 1 ) {
1039 node.setIndicator( ( byte ) 2 );
1040 if ( !node.isDuplication() ) {
1041 node = node.getChildNode2();
1044 if ( ( node != deepest ) && ( node.getIndicator() == 2 ) ) {
1045 node = node.getParent();
1052 if ( node != deepest ) {
1053 node = node.getParent();
1056 node.setIndicator( ( byte ) 2 );
1059 } while ( ( node != deepest ) || ( deepest.getIndicator() != 2 ) );
1064 * Convenience method for display purposes.
1065 * Not intended for algorithms.
1067 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
1068 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
1071 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
1075 * Returns all Nodes which are connected to external PhylogenyNode n of this
1076 * Phylogeny by a path containing, and leading to, only duplication events.
1077 * We call these "ultra paralogs". Nodes are returned as Vector of
1078 * references to Nodes.
1080 * PRECONDITION: This tree must be binary and rooted, and speciation -
1081 * duplication need to be assigned for each of its internal Nodes.
1083 * Returns null if this Phylogeny is empty or if n is internal.
1085 * (Last modified: 10/06/01)
1088 * external PhylogenyNode whose ultra paralogs are to be returned
1089 * @return Vector of references to all ultra paralogs of PhylogenyNode n of
1090 * this Phylogeny, null if this Phylogeny is empty or if n is
1093 public static List<PhylogenyNode> getUltraParalogousNodes( final PhylogenyNode n ) {
1095 PhylogenyNode node = n;
1096 if ( !node.isExternal() ) {
1099 while ( !node.isRoot() && node.getParent().isDuplication() && areAllChildrenDuplications( node.getParent() ) ) {
1100 node = node.getParent();
1102 final List<PhylogenyNode> nodes = node.getAllExternalDescendants();
1107 public static String inferCommonPartOfScientificNameOfDescendants( final PhylogenyNode node ) {
1108 final List<PhylogenyNode> descs = node.getDescendants();
1110 for( final PhylogenyNode n : descs ) {
1111 if ( !n.getNodeData().isHasTaxonomy()
1112 || ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1115 else if ( sn == null ) {
1116 sn = n.getNodeData().getTaxonomy().getScientificName().trim();
1119 String sn_current = n.getNodeData().getTaxonomy().getScientificName().trim();
1120 if ( !sn.equals( sn_current ) ) {
1121 boolean overlap = false;
1122 while ( ( sn.indexOf( ' ' ) >= 0 ) || ( sn_current.indexOf( ' ' ) >= 0 ) ) {
1123 if ( ForesterUtil.countChars( sn, ' ' ) > ForesterUtil.countChars( sn_current, ' ' ) ) {
1124 sn = sn.substring( 0, sn.lastIndexOf( ' ' ) ).trim();
1127 sn_current = sn_current.substring( 0, sn_current.lastIndexOf( ' ' ) ).trim();
1129 if ( sn.equals( sn_current ) ) {
1143 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
1144 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1145 if ( node.getChildNode( i ).isExternal() ) {
1153 * This is case insensitive.
1156 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
1157 final String[] providers ) {
1158 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
1159 final String my_tax_prov = tax.getIdentifier().getProvider();
1160 for( final String provider : providers ) {
1161 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
1172 private static boolean match( final String s,
1174 final boolean case_sensitive,
1175 final boolean partial ) {
1176 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1179 String my_s = s.trim();
1180 String my_query = query.trim();
1181 if ( !case_sensitive ) {
1182 my_s = my_s.toLowerCase();
1183 my_query = my_query.toLowerCase();
1186 return my_s.indexOf( my_query ) >= 0;
1189 return my_s.equals( my_query );
1193 public static void midpointRoot( final Phylogeny phylogeny ) {
1194 if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
1197 final PhylogenyMethods methods = getInstance();
1198 final double farthest_d = methods.calculateFurthestDistance( phylogeny );
1199 final PhylogenyNode f1 = methods.getFarthestNode1();
1200 final PhylogenyNode f2 = methods.getFarthestNode2();
1201 if ( farthest_d <= 0.0 ) {
1204 double x = farthest_d / 2.0;
1205 PhylogenyNode n = f1;
1206 if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
1210 while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
1211 x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
1214 phylogeny.reRoot( n, x );
1215 phylogeny.recalculateNumberOfExternalDescendants( true );
1216 final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
1217 final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
1218 final double da = getDistance( a, phylogeny.getRoot() );
1219 final double db = getDistance( b, phylogeny.getRoot() );
1220 if ( Math.abs( da - db ) > 0.000001 ) {
1221 throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed: da="
1222 + da + ", db=" + db + ", diff=" + Math.abs( da - db ) );
1226 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
1227 final double max_bootstrap_value,
1228 final double max_normalized_value ) {
1229 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
1230 final PhylogenyNode node = iter.next();
1231 if ( node.isInternal() ) {
1232 final double confidence = getConfidenceValue( node );
1233 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
1234 if ( confidence >= max_bootstrap_value ) {
1235 setBootstrapConfidence( node, max_normalized_value );
1238 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
1245 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
1246 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1247 if ( phy.isEmpty() ) {
1250 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1251 nodes.add( iter.next() );
1256 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
1257 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
1258 final PhylogenyNode node = iter.next();
1263 if ( node.isInternal() ) {
1264 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
1265 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
1266 final PhylogenyNode child_node = node.getChildNode( i );
1267 final Color child_color = getBranchColorValue( child_node );
1268 if ( child_color != null ) {
1270 red += child_color.getRed();
1271 green += child_color.getGreen();
1272 blue += child_color.getBlue();
1275 setBranchColorValue( node,
1276 new Color( ForesterUtil.roundToInt( red / n ),
1277 ForesterUtil.roundToInt( green / n ),
1278 ForesterUtil.roundToInt( blue / n ) ) );
1283 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
1284 if ( remove_me.isRoot() ) {
1285 throw new IllegalArgumentException( "ill advised attempt to remove root node" );
1287 if ( remove_me.isExternal() ) {
1288 phylogeny.deleteSubtree( remove_me, false );
1291 final PhylogenyNode parent = remove_me.getParent();
1292 final List<PhylogenyNode> descs = remove_me.getDescendants();
1293 parent.removeChildNode( remove_me );
1294 for( final PhylogenyNode desc : descs ) {
1295 parent.addAsChild( desc );
1296 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
1297 desc.getDistanceToParent() ) );
1299 remove_me.setParent( null );
1300 phylogeny.setIdHash( null );
1301 phylogeny.externalNodesHaveChanged();
1305 public static List<PhylogenyNode> searchData( final String query,
1306 final Phylogeny phy,
1307 final boolean case_sensitive,
1308 final boolean partial ) {
1309 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1310 if ( phy.isEmpty() || ( query == null ) ) {
1313 if ( ForesterUtil.isEmpty( query ) ) {
1316 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1317 final PhylogenyNode node = iter.next();
1318 boolean match = false;
1319 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1322 else if ( node.getNodeData().isHasTaxonomy()
1323 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1326 else if ( node.getNodeData().isHasTaxonomy()
1327 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1330 else if ( node.getNodeData().isHasTaxonomy()
1331 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1334 else if ( node.getNodeData().isHasTaxonomy()
1335 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1336 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1342 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1343 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1344 I: for( final String syn : syns ) {
1345 if ( match( syn, query, case_sensitive, partial ) ) {
1351 if ( !match && node.getNodeData().isHasSequence()
1352 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1355 if ( !match && node.getNodeData().isHasSequence()
1356 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1360 && node.getNodeData().isHasSequence()
1361 && ( node.getNodeData().getSequence().getAccession() != null )
1362 && match( node.getNodeData().getSequence().getAccession().getValue(),
1368 if ( !match && node.getNodeData().isHasSequence()
1369 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1370 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1371 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1372 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1378 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1379 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1380 I: while ( it.hasNext() ) {
1381 if ( match( it.next(), query, case_sensitive, partial ) ) {
1386 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1387 I: while ( it.hasNext() ) {
1388 if ( match( it.next(), query, case_sensitive, partial ) ) {
1401 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1402 final Phylogeny phy,
1403 final boolean case_sensitive,
1404 final boolean partial ) {
1405 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1406 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1409 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1410 final PhylogenyNode node = iter.next();
1411 boolean all_matched = true;
1412 for( final String query : queries ) {
1413 boolean match = false;
1414 if ( ForesterUtil.isEmpty( query ) ) {
1417 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1420 else if ( node.getNodeData().isHasTaxonomy()
1421 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1424 else if ( node.getNodeData().isHasTaxonomy()
1425 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1428 else if ( node.getNodeData().isHasTaxonomy()
1429 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1432 else if ( node.getNodeData().isHasTaxonomy()
1433 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1434 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1440 else if ( node.getNodeData().isHasTaxonomy()
1441 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1442 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1443 I: for( final String syn : syns ) {
1444 if ( match( syn, query, case_sensitive, partial ) ) {
1450 if ( !match && node.getNodeData().isHasSequence()
1451 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1454 if ( !match && node.getNodeData().isHasSequence()
1455 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1459 && node.getNodeData().isHasSequence()
1460 && ( node.getNodeData().getSequence().getAccession() != null )
1461 && match( node.getNodeData().getSequence().getAccession().getValue(),
1467 if ( !match && node.getNodeData().isHasSequence()
1468 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1469 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1470 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1471 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1477 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1478 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1479 I: while ( it.hasNext() ) {
1480 if ( match( it.next(), query, case_sensitive, partial ) ) {
1485 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1486 I: while ( it.hasNext() ) {
1487 if ( match( it.next(), query, case_sensitive, partial ) ) {
1492 // final String[] bcp_ary = node.getNodeData().getBinaryCharacters()
1493 // .getPresentCharactersAsStringArray();
1494 // I: for( final String bc : bcp_ary ) {
1495 // if ( match( bc, query, case_sensitive, partial ) ) {
1500 // final String[] bcg_ary = node.getNodeData().getBinaryCharacters()
1501 // .getGainedCharactersAsStringArray();
1502 // I: for( final String bc : bcg_ary ) {
1503 // if ( match( bc, query, case_sensitive, partial ) ) {
1510 all_matched = false;
1514 if ( all_matched ) {
1522 * Convenience method.
1523 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1525 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1526 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1529 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1530 if ( node.getBranchData().getBranchColor() == null ) {
1531 node.getBranchData().setBranchColor( new BranchColor() );
1533 node.getBranchData().getBranchColor().setValue( color );
1537 * Convenience method
1539 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1540 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1544 * Convenience method.
1545 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1547 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1548 setConfidence( node, confidence_value, "" );
1552 * Convenience method.
1553 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1555 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1556 Confidence c = null;
1557 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1558 c = node.getBranchData().getConfidence( 0 );
1561 c = new Confidence();
1562 node.getBranchData().addConfidence( c );
1565 c.setValue( confidence_value );
1568 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1569 if ( !node.getNodeData().isHasTaxonomy() ) {
1570 node.getNodeData().setTaxonomy( new Taxonomy() );
1572 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1576 * Convenience method to set the taxonomy code of a phylogeny node.
1580 * @param taxonomy_code
1581 * @throws PhyloXmlDataFormatException
1583 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1584 throws PhyloXmlDataFormatException {
1585 if ( !node.getNodeData().isHasTaxonomy() ) {
1586 node.getNodeData().setTaxonomy( new Taxonomy() );
1588 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1592 * Removes from Phylogeny to_be_stripped all external Nodes which are
1593 * associated with a species NOT found in Phylogeny reference.
1596 * a reference Phylogeny
1597 * @param to_be_stripped
1598 * Phylogeny to be stripped
1599 * @return number of external nodes removed from to_be_stripped
1601 public static int taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference, final Phylogeny to_be_stripped ) {
1602 final Set<String> ref_ext_taxo = new HashSet<String>();
1603 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1604 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1605 ref_ext_taxo.add( getSpecies( it.next() ) );
1607 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1608 final PhylogenyNode n = it.next();
1609 if ( !ref_ext_taxo.contains( getSpecies( n ) ) ) {
1610 nodes_to_delete.add( n );
1613 for( final PhylogenyNode phylogenyNode : nodes_to_delete ) {
1614 to_be_stripped.deleteSubtree( phylogenyNode, true );
1616 return nodes_to_delete.size();
1620 * Arranges the order of childern for each node of this Phylogeny in such a
1621 * way that either the branch with more children is on top (right) or on
1622 * bottom (left), dependent on the value of boolean order.
1625 * decides in which direction to order
1628 public static void orderAppearance( final PhylogenyNode n,
1629 final boolean order,
1630 final boolean order_ext_alphabetically,
1631 final DESCENDANT_SORT_PRIORITY pri ) {
1632 if ( n.isExternal() ) {
1636 PhylogenyNode temp = null;
1637 if ( ( n.getNumberOfDescendants() == 2 )
1638 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
1639 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
1640 temp = n.getChildNode1();
1641 n.setChild1( n.getChildNode2() );
1642 n.setChild2( temp );
1644 else if ( order_ext_alphabetically ) {
1645 boolean all_ext = true;
1646 for( final PhylogenyNode i : n.getDescendants() ) {
1647 if ( !i.isExternal() ) {
1653 PhylogenyMethods.sortNodeDescendents( n, pri );
1656 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
1657 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
1662 public static enum PhylogenyNodeField {
1665 TAXONOMY_SCIENTIFIC_NAME,
1666 TAXONOMY_COMMON_NAME,
1669 TAXONOMY_ID_UNIPROT_1,
1670 TAXONOMY_ID_UNIPROT_2,
1674 public static enum TAXONOMY_EXTRACTION {
1675 NO, YES, PFAM_STYLE_ONLY;
1678 public static enum DESCENDANT_SORT_PRIORITY {
1679 TAXONOMY, SEQUENCE, NODE_NAME;