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: https://sites.google.com/site/cmzmasek/home/software/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.HashMap;
36 import java.util.HashSet;
37 import java.util.Iterator;
38 import java.util.List;
40 import java.util.SortedMap;
41 import java.util.TreeMap;
43 import org.forester.io.parsers.PhylogenyParser;
44 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
45 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
46 import org.forester.io.parsers.util.PhylogenyParserException;
47 import org.forester.phylogeny.data.Accession;
48 import org.forester.phylogeny.data.Annotation;
49 import org.forester.phylogeny.data.BranchColor;
50 import org.forester.phylogeny.data.BranchWidth;
51 import org.forester.phylogeny.data.Confidence;
52 import org.forester.phylogeny.data.DomainArchitecture;
53 import org.forester.phylogeny.data.Event;
54 import org.forester.phylogeny.data.Identifier;
55 import org.forester.phylogeny.data.PhylogenyDataUtil;
56 import org.forester.phylogeny.data.Sequence;
57 import org.forester.phylogeny.data.Taxonomy;
58 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
59 import org.forester.phylogeny.factories.PhylogenyFactory;
60 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
61 import org.forester.util.BasicDescriptiveStatistics;
62 import org.forester.util.DescriptiveStatistics;
63 import org.forester.util.ForesterUtil;
65 public class PhylogenyMethods {
67 private PhylogenyMethods() {
68 // Hidden constructor.
72 public Object clone() throws CloneNotSupportedException {
73 throw new CloneNotSupportedException();
76 public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
77 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
78 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
79 final PhylogenyNode n = iter.next();
80 if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
81 stats.addValue( n.getDistanceToParent() );
87 public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
88 final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
89 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
90 final PhylogenyNode n = iter.next();
91 if ( !n.isExternal() && !n.isRoot() ) {
92 if ( n.getBranchData().isHasConfidences() ) {
93 for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
94 final Confidence c = n.getBranchData().getConfidences().get( i );
95 if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
96 stats.add( i, new BasicDescriptiveStatistics() );
98 if ( !ForesterUtil.isEmpty( c.getType() ) ) {
99 if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
100 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
101 throw new IllegalArgumentException( "support values in node [" + n.toString()
102 + "] appear inconsistently ordered" );
105 stats.get( i ).setDescription( c.getType() );
107 stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
116 * Calculates the distance between PhylogenyNodes node1 and node2.
121 * @return distance between node1 and node2
123 public static double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) {
124 final PhylogenyNode lca = calculateLCA( node1, node2 );
125 final PhylogenyNode n1 = node1;
126 final PhylogenyNode n2 = node2;
127 return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) );
131 * Returns the LCA of PhylogenyNodes node1 and node2.
136 * @return LCA of node1 and node2
138 public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) {
139 if ( node1 == null ) {
140 throw new IllegalArgumentException( "first argument (node) is null" );
142 if ( node2 == null ) {
143 throw new IllegalArgumentException( "second argument (node) is null" );
145 if ( node1 == node2 ) {
148 if ( ( node1.getParent() == node2.getParent() ) ) {
149 return node1.getParent();
151 int depth1 = node1.calculateDepth();
152 int depth2 = node2.calculateDepth();
153 while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) {
154 if ( depth1 > depth2 ) {
155 node1 = node1.getParent();
158 else if ( depth2 > depth1 ) {
159 node2 = node2.getParent();
163 if ( node1 == node2 ) {
166 node1 = node1.getParent();
167 node2 = node2.getParent();
172 throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" );
176 * Returns the LCA of PhylogenyNodes node1 and node2.
177 * Precondition: ids are in pre-order (or level-order).
182 * @return LCA of node1 and node2
184 public final static PhylogenyNode calculateLCAonTreeWithIdsInPreOrder( PhylogenyNode node1, PhylogenyNode node2 ) {
185 if ( node1 == null ) {
186 throw new IllegalArgumentException( "first argument (node) is null" );
188 if ( node2 == null ) {
189 throw new IllegalArgumentException( "second argument (node) is null" );
191 while ( node1 != node2 ) {
192 if ( node1.getId() > node2.getId() ) {
193 node1 = node1.getParent();
196 node2 = node2.getParent();
202 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
203 if ( node.isExternal() ) {
207 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
209 while ( d != node ) {
210 if ( d.isCollapse() ) {
225 public static int calculateMaxDepth( final Phylogeny phy ) {
227 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
228 final PhylogenyNode node = iter.next();
229 final int steps = node.calculateDepth();
237 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
239 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
240 final PhylogenyNode node = iter.next();
241 final double d = node.calculateDistanceToRoot();
249 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
250 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
252 for( final PhylogenyNode n : descs ) {
253 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
260 public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
261 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
262 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
263 final PhylogenyNode n = iter.next();
264 if ( !n.isExternal() ) {
265 stats.addValue( n.getNumberOfDescendants() );
271 public final static void collapseSubtreeStructure( final PhylogenyNode n ) {
272 final List<PhylogenyNode> eds = n.getAllExternalDescendants();
273 final List<Double> d = new ArrayList<Double>();
274 for( final PhylogenyNode ed : eds ) {
275 d.add( calculateDistanceToAncestor( n, ed ) );
277 for( int i = 0; i < eds.size(); ++i ) {
278 n.setChildNode( i, eds.get( i ) );
279 eds.get( i ).setDistanceToParent( d.get( i ) );
283 public static int countNumberOfOneDescendantNodes( final Phylogeny phy ) {
285 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
286 final PhylogenyNode n = iter.next();
287 if ( !n.isExternal() && ( n.getNumberOfDescendants() == 1 ) ) {
294 public static int countNumberOfPolytomies( final Phylogeny phy ) {
296 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
297 final PhylogenyNode n = iter.next();
298 if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
305 public static final HashMap<String, PhylogenyNode> createNameToExtNodeMap( final Phylogeny phy ) {
306 final HashMap<String, PhylogenyNode> nodes = new HashMap<String, PhylogenyNode>();
307 final List<PhylogenyNode> ext = phy.getExternalNodes();
308 for( final PhylogenyNode n : ext ) {
309 nodes.put( n.getName(), n );
314 public static void deleteExternalNodesNegativeSelection( final Set<Long> to_delete, final Phylogeny phy ) {
315 for( final Long id : to_delete ) {
316 phy.deleteSubtree( phy.getNode( id ), true );
318 phy.clearHashIdToNodeMap();
319 phy.externalNodesHaveChanged();
322 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
323 throws IllegalArgumentException {
324 for( final String element : node_names_to_delete ) {
325 if ( ForesterUtil.isEmpty( element ) ) {
328 List<PhylogenyNode> nodes = null;
329 nodes = p.getNodes( element );
330 final Iterator<PhylogenyNode> it = nodes.iterator();
331 while ( it.hasNext() ) {
332 final PhylogenyNode n = it.next();
333 if ( !n.isExternal() ) {
334 throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
336 p.deleteSubtree( n, true );
339 p.clearHashIdToNodeMap();
340 p.externalNodesHaveChanged();
343 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
344 final Phylogeny p ) {
345 final PhylogenyNodeIterator it = p.iteratorExternalForward();
346 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
348 Arrays.sort( node_names_to_keep );
349 while ( it.hasNext() ) {
350 final String curent_name = it.next().getName();
351 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
352 to_delete[ i++ ] = curent_name;
355 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
356 final List<String> deleted = new ArrayList<String>();
357 for( final String n : to_delete ) {
358 if ( !ForesterUtil.isEmpty( n ) ) {
365 public static void deleteExternalNodesPositiveSelectionT( final List<Taxonomy> species_to_keep, final Phylogeny phy ) {
366 final Set<Long> to_delete = new HashSet<Long>();
367 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
368 final PhylogenyNode n = it.next();
369 if ( n.getNodeData().isHasTaxonomy() ) {
370 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
371 to_delete.add( n.getId() );
375 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
378 deleteExternalNodesNegativeSelection( to_delete, phy );
381 final public static void deleteInternalNodesWithOnlyOneDescendent( final Phylogeny phy ) {
382 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
383 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
384 final PhylogenyNode n = iter.next();
385 if ( ( !n.isExternal() ) && ( n.getNumberOfDescendants() == 1 ) ) {
389 for( final PhylogenyNode d : to_delete ) {
390 PhylogenyMethods.removeNode( d, phy );
392 phy.clearHashIdToNodeMap();
393 phy.externalNodesHaveChanged();
396 final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) {
397 if ( n.isInternal() ) {
398 throw new IllegalArgumentException( "node is not external" );
400 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
401 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
402 final PhylogenyNode i = it.next();
403 if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) {
407 for( final PhylogenyNode d : to_delete ) {
408 phy.deleteSubtree( d, true );
410 phy.clearHashIdToNodeMap();
411 phy.externalNodesHaveChanged();
414 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
415 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
416 final Set<Long> encountered = new HashSet<Long>();
417 if ( !node.isExternal() ) {
418 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
419 for( PhylogenyNode current : exts ) {
420 descs.add( current );
421 while ( current != node ) {
422 current = current.getParent();
423 if ( encountered.contains( current.getId() ) ) {
426 descs.add( current );
427 encountered.add( current.getId() );
441 public static Color getBranchColorValue( final PhylogenyNode node ) {
442 if ( node.getBranchData().getBranchColor() == null ) {
445 return node.getBranchData().getBranchColor().getValue();
451 public static double getBranchWidthValue( final PhylogenyNode node ) {
452 if ( !node.getBranchData().isHasBranchWidth() ) {
453 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
455 return node.getBranchData().getBranchWidth().getValue();
461 public static double getConfidenceValue( final PhylogenyNode node ) {
462 if ( !node.getBranchData().isHasConfidences() ) {
463 return Confidence.CONFIDENCE_DEFAULT_VALUE;
465 return node.getBranchData().getConfidence( 0 ).getValue();
471 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
472 if ( !node.getBranchData().isHasConfidences() ) {
473 return new double[ 0 ];
475 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
477 for( final Confidence c : node.getBranchData().getConfidences() ) {
478 values[ i++ ] = c.getValue();
483 final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) {
484 return calculateLCA( n1, n2 ).getNodeData().getEvent();
488 * Returns taxonomy t if all external descendants have
489 * the same taxonomy t, null otherwise.
492 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
493 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
495 for( final PhylogenyNode n : descs ) {
496 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
499 else if ( tax == null ) {
500 tax = n.getNodeData().getTaxonomy();
502 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
509 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
510 final List<PhylogenyNode> children = node.getAllExternalDescendants();
511 PhylogenyNode farthest = null;
512 double longest = -Double.MAX_VALUE;
513 for( final PhylogenyNode child : children ) {
514 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
516 longest = PhylogenyMethods.getDistance( child, node );
522 // public static PhylogenyMethods getInstance() {
523 // if ( PhylogenyMethods._instance == null ) {
524 // PhylogenyMethods._instance = new PhylogenyMethods();
526 // return PhylogenyMethods._instance;
529 * Returns the largest confidence value found on phy.
531 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
532 double max = -Double.MAX_VALUE;
533 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
534 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
535 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
542 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
543 int min = Integer.MAX_VALUE;
546 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
548 if ( n.isInternal() ) {
549 d = n.getNumberOfDescendants();
559 * Convenience method for display purposes.
560 * Not intended for algorithms.
562 public static String getSpecies( final PhylogenyNode node ) {
563 if ( !node.getNodeData().isHasTaxonomy() ) {
566 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
567 return node.getNodeData().getTaxonomy().getScientificName();
569 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
570 return node.getNodeData().getTaxonomy().getTaxonomyCode();
573 return node.getNodeData().getTaxonomy().getCommonName();
578 * Convenience method for display purposes.
579 * Not intended for algorithms.
581 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
582 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
585 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
588 public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) {
589 if ( n.isExternal() ) {
593 if ( n.isDuplication() ) {
594 for( final PhylogenyNode desc : n.getDescendants() ) {
595 if ( !isAllDecendentsAreDuplications( desc ) ) {
607 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
608 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
609 if ( node.getChildNode( i ).isExternal() ) {
617 * This is case insensitive.
620 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
621 final String[] providers ) {
622 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
623 final String my_tax_prov = tax.getIdentifier().getProvider();
624 for( final String provider : providers ) {
625 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
636 public static void midpointRoot( final Phylogeny phylogeny ) {
637 if ( ( phylogeny.getNumberOfExternalNodes() < 2 ) || ( calculateMaxDistanceToRoot( phylogeny ) <= 0 ) ) {
641 final int total_nodes = phylogeny.getNodeCount();
643 if ( ++counter > total_nodes ) {
644 throw new RuntimeException( "this should not have happened: midpoint rooting does not converge" );
646 PhylogenyNode a = null;
649 for( int i = 0; i < phylogeny.getRoot().getNumberOfDescendants(); ++i ) {
650 final PhylogenyNode f = getFurthestDescendant( phylogeny.getRoot().getChildNode( i ) );
651 final double df = getDistance( f, phylogeny.getRoot() );
658 else if ( df > db ) {
663 final double diff = da - db;
664 if ( diff < 0.000001 ) {
667 double x = da - ( diff / 2.0 );
668 while ( ( x > a.getDistanceToParent() ) && !a.isRoot() ) {
669 x -= ( a.getDistanceToParent() > 0 ? a.getDistanceToParent() : 0 );
672 phylogeny.reRoot( a, x );
674 phylogeny.recalculateNumberOfExternalDescendants( true );
677 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
678 final double max_bootstrap_value,
679 final double max_normalized_value ) {
680 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
681 final PhylogenyNode node = iter.next();
682 if ( node.isInternal() ) {
683 final double confidence = getConfidenceValue( node );
684 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
685 if ( confidence >= max_bootstrap_value ) {
686 setBootstrapConfidence( node, max_normalized_value );
689 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
696 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
697 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
698 if ( phy.isEmpty() ) {
701 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
702 nodes.add( iter.next() );
708 * Returns a map of distinct taxonomies of
709 * all external nodes of node.
710 * If at least one of the external nodes has no taxonomy,
714 public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
715 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
716 final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
717 for( final PhylogenyNode n : descs ) {
718 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
721 final Taxonomy t = n.getNodeData().getTaxonomy();
722 if ( tax_map.containsKey( t ) ) {
723 tax_map.put( t, tax_map.get( t ) + 1 );
733 * Arranges the order of childern for each node of this Phylogeny in such a
734 * way that either the branch with more children is on top (right) or on
735 * bottom (left), dependent on the value of boolean order.
738 * decides in which direction to order
741 public static void orderAppearance( final PhylogenyNode n,
743 final boolean order_ext_alphabetically,
744 final DESCENDANT_SORT_PRIORITY pri ) {
745 if ( n.isExternal() ) {
749 PhylogenyNode temp = null;
750 if ( ( n.getNumberOfDescendants() == 2 )
751 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
752 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
753 temp = n.getChildNode1();
754 n.setChild1( n.getChildNode2() );
757 else if ( order_ext_alphabetically ) {
758 boolean all_ext = true;
759 for( final PhylogenyNode i : n.getDescendants() ) {
760 if ( !i.isExternal() ) {
766 PhylogenyMethods.sortNodeDescendents( n, pri );
769 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
770 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
775 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
776 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
777 final PhylogenyNode node = iter.next();
782 if ( node.isInternal() ) {
783 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
784 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
785 final PhylogenyNode child_node = node.getChildNode( i );
786 final Color child_color = getBranchColorValue( child_node );
787 if ( child_color != null ) {
789 red += child_color.getRed();
790 green += child_color.getGreen();
791 blue += child_color.getBlue();
794 setBranchColorValue( node,
795 new Color( ForesterUtil.roundToInt( red / n ),
796 ForesterUtil.roundToInt( green / n ),
797 ForesterUtil.roundToInt( blue / n ) ) );
802 public static final void preOrderReId( final Phylogeny phy ) {
803 if ( phy.isEmpty() ) {
806 phy.setIdToNodeMap( null );
807 long i = PhylogenyNode.getNodeCount();
808 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
809 it.next().setId( i++ );
811 PhylogenyNode.setNodeCount( i );
814 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
815 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
816 final Phylogeny[] trees = factory.create( file, parser );
817 if ( ( trees == null ) || ( trees.length == 0 ) ) {
818 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
823 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
825 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
826 for( final File file : files ) {
827 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
828 final Phylogeny[] trees = factory.create( file, parser );
829 if ( ( trees == null ) || ( trees.length == 0 ) ) {
830 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
832 tree_list.addAll( Arrays.asList( trees ) );
834 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
837 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
838 if ( remove_me.isRoot() ) {
839 if ( remove_me.getNumberOfDescendants() == 1 ) {
840 final PhylogenyNode desc = remove_me.getDescendants().get( 0 );
841 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
842 desc.getDistanceToParent() ) );
843 desc.setParent( null );
844 phylogeny.setRoot( desc );
845 phylogeny.clearHashIdToNodeMap();
848 throw new IllegalArgumentException( "attempt to remove a root node with more than one descendants" );
851 else if ( remove_me.isExternal() ) {
852 phylogeny.deleteSubtree( remove_me, false );
853 phylogeny.clearHashIdToNodeMap();
854 phylogeny.externalNodesHaveChanged();
857 final PhylogenyNode parent = remove_me.getParent();
858 final List<PhylogenyNode> descs = remove_me.getDescendants();
859 parent.removeChildNode( remove_me );
860 for( final PhylogenyNode desc : descs ) {
861 parent.addAsChild( desc );
862 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
863 desc.getDistanceToParent() ) );
865 remove_me.setParent( null );
866 phylogeny.clearHashIdToNodeMap();
867 phylogeny.externalNodesHaveChanged();
871 public static List<PhylogenyNode> searchData( final String query,
873 final boolean case_sensitive,
874 final boolean partial,
875 final boolean search_domains ) {
876 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
877 if ( phy.isEmpty() || ( query == null ) ) {
880 if ( ForesterUtil.isEmpty( query ) ) {
883 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
884 final PhylogenyNode node = iter.next();
885 boolean match = false;
886 if ( match( node.getName(), query, case_sensitive, partial ) ) {
889 else if ( node.getNodeData().isHasTaxonomy()
890 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
893 else if ( node.getNodeData().isHasTaxonomy()
894 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
897 else if ( node.getNodeData().isHasTaxonomy()
898 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
901 else if ( node.getNodeData().isHasTaxonomy()
902 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
903 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
909 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
910 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
911 I: for( final String syn : syns ) {
912 if ( match( syn, query, case_sensitive, partial ) ) {
918 if ( !match && node.getNodeData().isHasSequence()
919 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
922 if ( !match && node.getNodeData().isHasSequence()
923 && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) {
926 if ( !match && node.getNodeData().isHasSequence()
927 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
931 && node.getNodeData().isHasSequence()
932 && ( node.getNodeData().getSequence().getAccession() != null )
933 && match( node.getNodeData().getSequence().getAccession().getValue(),
939 if ( search_domains && !match && node.getNodeData().isHasSequence()
940 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
941 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
942 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
943 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
950 if ( !match && node.getNodeData().isHasSequence()
951 && ( node.getNodeData().getSequence().getAnnotations() != null ) ) {
952 for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) {
953 if ( match( ann.getDesc(), query, case_sensitive, partial ) ) {
957 if ( match( ann.getRef(), query, case_sensitive, partial ) ) {
963 if ( !match && node.getNodeData().isHasSequence()
964 && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) {
965 for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) {
966 if ( match( x.getComment(), query, case_sensitive, partial ) ) {
970 if ( match( x.getSource(), query, case_sensitive, partial ) ) {
974 if ( match( x.getValue(), query, case_sensitive, partial ) ) {
981 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
982 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
983 I: while ( it.hasNext() ) {
984 if ( match( it.next(), query, case_sensitive, partial ) ) {
989 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
990 I: while ( it.hasNext() ) {
991 if ( match( it.next(), query, case_sensitive, partial ) ) {
1004 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1005 final Phylogeny phy,
1006 final boolean case_sensitive,
1007 final boolean partial,
1008 final boolean search_domains ) {
1009 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1010 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1013 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1014 final PhylogenyNode node = iter.next();
1015 boolean all_matched = true;
1016 for( final String query : queries ) {
1017 boolean match = false;
1018 if ( ForesterUtil.isEmpty( query ) ) {
1021 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1024 else if ( node.getNodeData().isHasTaxonomy()
1025 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1028 else if ( node.getNodeData().isHasTaxonomy()
1029 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1032 else if ( node.getNodeData().isHasTaxonomy()
1033 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1036 else if ( node.getNodeData().isHasTaxonomy()
1037 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1038 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1044 else if ( node.getNodeData().isHasTaxonomy()
1045 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1046 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1047 I: for( final String syn : syns ) {
1048 if ( match( syn, query, case_sensitive, partial ) ) {
1054 if ( !match && node.getNodeData().isHasSequence()
1055 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1058 if ( !match && node.getNodeData().isHasSequence()
1059 && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) {
1062 if ( !match && node.getNodeData().isHasSequence()
1063 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1067 && node.getNodeData().isHasSequence()
1068 && ( node.getNodeData().getSequence().getAccession() != null )
1069 && match( node.getNodeData().getSequence().getAccession().getValue(),
1075 if ( search_domains && !match && node.getNodeData().isHasSequence()
1076 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1077 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1078 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1079 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1086 if ( !match && node.getNodeData().isHasSequence()
1087 && ( node.getNodeData().getSequence().getAnnotations() != null ) ) {
1088 for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) {
1089 if ( match( ann.getDesc(), query, case_sensitive, partial ) ) {
1093 if ( match( ann.getRef(), query, case_sensitive, partial ) ) {
1099 if ( !match && node.getNodeData().isHasSequence()
1100 && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) {
1101 for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) {
1102 if ( match( x.getComment(), query, case_sensitive, partial ) ) {
1106 if ( match( x.getSource(), query, case_sensitive, partial ) ) {
1110 if ( match( x.getValue(), query, case_sensitive, partial ) ) {
1117 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1118 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1119 I: while ( it.hasNext() ) {
1120 if ( match( it.next(), query, case_sensitive, partial ) ) {
1125 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1126 I: while ( it.hasNext() ) {
1127 if ( match( it.next(), query, case_sensitive, partial ) ) {
1134 all_matched = false;
1138 if ( all_matched ) {
1146 * Convenience method.
1147 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1149 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1150 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1153 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1154 if ( node.getBranchData().getBranchColor() == null ) {
1155 node.getBranchData().setBranchColor( new BranchColor() );
1157 node.getBranchData().getBranchColor().setValue( color );
1161 * Convenience method
1163 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1164 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1168 * Convenience method.
1169 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1171 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1172 setConfidence( node, confidence_value, "" );
1176 * Convenience method.
1177 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1179 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1180 Confidence c = null;
1181 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1182 c = node.getBranchData().getConfidence( 0 );
1185 c = new Confidence();
1186 node.getBranchData().addConfidence( c );
1189 c.setValue( confidence_value );
1192 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1193 if ( !node.getNodeData().isHasTaxonomy() ) {
1194 node.getNodeData().setTaxonomy( new Taxonomy() );
1196 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1200 * Convenience method to set the taxonomy code of a phylogeny node.
1204 * @param taxonomy_code
1205 * @throws PhyloXmlDataFormatException
1207 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1208 throws PhyloXmlDataFormatException {
1209 if ( !node.getNodeData().isHasTaxonomy() ) {
1210 node.getNodeData().setTaxonomy( new Taxonomy() );
1212 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1215 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
1216 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
1219 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1220 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1221 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1222 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1223 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1224 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1226 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1227 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1228 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1229 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1231 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1232 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1233 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1234 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1237 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1238 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1239 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1240 return n1.getNodeData().getSequence().getName().toLowerCase()
1241 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1243 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1244 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1245 return n1.getNodeData().getSequence().getSymbol()
1246 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1248 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) )
1249 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) {
1250 return n1.getNodeData().getSequence().getGeneName()
1251 .compareTo( n2.getNodeData().getSequence().getGeneName() );
1253 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1254 && ( n2.getNodeData().getSequence().getAccession() != null )
1255 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1256 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1257 return n1.getNodeData().getSequence().getAccession().getValue()
1258 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1261 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1262 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1267 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
1270 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1271 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1272 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1273 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1274 return n1.getNodeData().getSequence().getName().toLowerCase()
1275 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1277 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1278 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1279 return n1.getNodeData().getSequence().getSymbol()
1280 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1282 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) )
1283 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) {
1284 return n1.getNodeData().getSequence().getGeneName()
1285 .compareTo( n2.getNodeData().getSequence().getGeneName() );
1287 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1288 && ( n2.getNodeData().getSequence().getAccession() != null )
1289 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1290 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1291 return n1.getNodeData().getSequence().getAccession().getValue()
1292 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1295 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1296 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1297 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1298 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1299 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1301 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1302 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1303 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1304 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1306 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1307 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1308 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1309 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1312 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1313 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1318 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
1321 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1322 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1323 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1325 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1326 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1327 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1328 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1329 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1331 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1332 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1333 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1334 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1336 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1337 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1338 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1339 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1342 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1343 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1344 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1345 return n1.getNodeData().getSequence().getName().toLowerCase()
1346 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1348 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1349 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1350 return n1.getNodeData().getSequence().getSymbol()
1351 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1353 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) )
1354 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) {
1355 return n1.getNodeData().getSequence().getGeneName()
1356 .compareTo( n2.getNodeData().getSequence().getGeneName() );
1358 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1359 && ( n2.getNodeData().getSequence().getAccession() != null )
1360 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1361 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1362 return n1.getNodeData().getSequence().getAccession().getValue()
1363 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1369 Comparator<PhylogenyNode> c;
1372 c = new PhylogenyNodeSortSequencePriority();
1375 c = new PhylogenyNodeSortNodeNamePriority();
1378 c = new PhylogenyNodeSortTaxonomyPriority();
1380 final List<PhylogenyNode> descs = node.getDescendants();
1381 Collections.sort( descs, c );
1383 for( final PhylogenyNode desc : descs ) {
1384 node.setChildNode( i++, desc );
1389 * Removes from Phylogeny to_be_stripped all external Nodes which are
1390 * associated with a species NOT found in Phylogeny reference.
1393 * a reference Phylogeny
1394 * @param to_be_stripped
1395 * Phylogeny to be stripped
1396 * @return nodes removed from to_be_stripped
1398 public static List<PhylogenyNode> taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference,
1399 final Phylogeny to_be_stripped ) {
1400 final Set<String> ref_ext_taxo = new HashSet<String>();
1401 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1402 final PhylogenyNode n = it.next();
1403 if ( !n.getNodeData().isHasTaxonomy() ) {
1404 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1406 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1407 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1409 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1410 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1412 if ( ( n.getNodeData().getTaxonomy().getIdentifier() != null )
1413 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) {
1414 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() );
1417 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1418 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1419 final PhylogenyNode n = it.next();
1420 if ( !n.getNodeData().isHasTaxonomy() ) {
1421 nodes_to_delete.add( n );
1423 else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1424 && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1425 && !( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) && ref_ext_taxo.contains( n
1426 .getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ) ) ) {
1427 nodes_to_delete.add( n );
1430 for( final PhylogenyNode n : nodes_to_delete ) {
1431 to_be_stripped.deleteSubtree( n, true );
1433 to_be_stripped.clearHashIdToNodeMap();
1434 to_be_stripped.externalNodesHaveChanged();
1435 return nodes_to_delete;
1438 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
1439 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1440 while ( it.hasNext() ) {
1441 final PhylogenyNode n = it.next();
1442 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
1445 value = Double.parseDouble( n.getName() );
1447 catch ( final NumberFormatException e ) {
1448 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
1449 + e.getLocalizedMessage() );
1451 if ( value >= 0.0 ) {
1452 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
1459 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
1460 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1461 while ( it.hasNext() ) {
1462 final PhylogenyNode n = it.next();
1463 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
1464 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
1467 d = Double.parseDouble( n.getName() );
1469 catch ( final Exception e ) {
1473 n.getBranchData().addConfidence( new Confidence( d, "" ) );
1481 final static public void transferNodeNameToField( final Phylogeny phy,
1482 final PhylogenyNodeField field,
1483 final boolean external_only ) throws PhyloXmlDataFormatException {
1484 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1485 while ( it.hasNext() ) {
1486 final PhylogenyNode n = it.next();
1487 if ( external_only && n.isInternal() ) {
1490 final String name = n.getName().trim();
1491 if ( !ForesterUtil.isEmpty( name ) ) {
1495 setTaxonomyCode( n, name );
1497 case TAXONOMY_SCIENTIFIC_NAME:
1499 if ( !n.getNodeData().isHasTaxonomy() ) {
1500 n.getNodeData().setTaxonomy( new Taxonomy() );
1502 n.getNodeData().getTaxonomy().setScientificName( name );
1504 case TAXONOMY_COMMON_NAME:
1506 if ( !n.getNodeData().isHasTaxonomy() ) {
1507 n.getNodeData().setTaxonomy( new Taxonomy() );
1509 n.getNodeData().getTaxonomy().setCommonName( name );
1511 case SEQUENCE_SYMBOL:
1513 if ( !n.getNodeData().isHasSequence() ) {
1514 n.getNodeData().setSequence( new Sequence() );
1516 n.getNodeData().getSequence().setSymbol( name );
1520 if ( !n.getNodeData().isHasSequence() ) {
1521 n.getNodeData().setSequence( new Sequence() );
1523 n.getNodeData().getSequence().setName( name );
1525 case TAXONOMY_ID_UNIPROT_1: {
1526 if ( !n.getNodeData().isHasTaxonomy() ) {
1527 n.getNodeData().setTaxonomy( new Taxonomy() );
1530 final int i = name.indexOf( '_' );
1532 id = name.substring( 0, i );
1537 n.getNodeData().getTaxonomy()
1538 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1541 case TAXONOMY_ID_UNIPROT_2: {
1542 if ( !n.getNodeData().isHasTaxonomy() ) {
1543 n.getNodeData().setTaxonomy( new Taxonomy() );
1546 final int i = name.indexOf( '_' );
1548 id = name.substring( i + 1, name.length() );
1553 n.getNodeData().getTaxonomy()
1554 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1558 if ( !n.getNodeData().isHasTaxonomy() ) {
1559 n.getNodeData().setTaxonomy( new Taxonomy() );
1561 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
1569 static double addPhylogenyDistances( final double a, final double b ) {
1570 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
1573 else if ( a >= 0.0 ) {
1576 else if ( b >= 0.0 ) {
1579 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
1582 static double calculateDistanceToAncestor( final PhylogenyNode anc, PhylogenyNode desc ) {
1584 boolean all_default = true;
1585 while ( anc != desc ) {
1586 if ( desc.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
1587 d += desc.getDistanceToParent();
1588 if ( all_default ) {
1589 all_default = false;
1592 desc = desc.getParent();
1594 if ( all_default ) {
1595 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
1601 * Deep copies the phylogeny originating from this node.
1603 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
1604 if ( source == null ) {
1608 final PhylogenyNode newnode = source.copyNodeData();
1609 if ( !source.isExternal() ) {
1610 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1611 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
1619 * Shallow copies the phylogeny originating from this node.
1621 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
1622 if ( source == null ) {
1626 final PhylogenyNode newnode = source.copyNodeDataShallow();
1627 if ( !source.isExternal() ) {
1628 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1629 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
1637 * Calculates the distance between PhylogenyNodes n1 and n2.
1638 * PRECONDITION: n1 is a descendant of n2.
1641 * a descendant of n2
1643 * @return distance between n1 and n2
1645 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
1647 while ( n1 != n2 ) {
1648 if ( n1.getDistanceToParent() > 0.0 ) {
1649 d += n1.getDistanceToParent();
1651 n1 = n1.getParent();
1656 private static boolean match( final String s,
1658 final boolean case_sensitive,
1659 final boolean partial ) {
1660 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1663 String my_s = s.trim();
1664 String my_query = query.trim();
1665 if ( !case_sensitive ) {
1666 my_s = my_s.toLowerCase();
1667 my_query = my_query.toLowerCase();
1670 return my_s.indexOf( my_query ) >= 0;
1673 return my_s.equals( my_query );
1677 public static enum DESCENDANT_SORT_PRIORITY {
1678 TAXONOMY, SEQUENCE, NODE_NAME;
1681 public static enum PhylogenyNodeField {
1684 TAXONOMY_SCIENTIFIC_NAME,
1685 TAXONOMY_COMMON_NAME,
1688 TAXONOMY_ID_UNIPROT_1,
1689 TAXONOMY_ID_UNIPROT_2,