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;
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.Accession;
47 import org.forester.phylogeny.data.Annotation;
48 import org.forester.phylogeny.data.BranchColor;
49 import org.forester.phylogeny.data.BranchWidth;
50 import org.forester.phylogeny.data.Confidence;
51 import org.forester.phylogeny.data.DomainArchitecture;
52 import org.forester.phylogeny.data.Event;
53 import org.forester.phylogeny.data.Identifier;
54 import org.forester.phylogeny.data.PhylogenyDataUtil;
55 import org.forester.phylogeny.data.Sequence;
56 import org.forester.phylogeny.data.Taxonomy;
57 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
58 import org.forester.phylogeny.factories.PhylogenyFactory;
59 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
60 import org.forester.util.BasicDescriptiveStatistics;
61 import org.forester.util.DescriptiveStatistics;
62 import org.forester.util.ForesterUtil;
64 public class PhylogenyMethods {
66 private PhylogenyMethods() {
67 // Hidden constructor.
71 public Object clone() throws CloneNotSupportedException {
72 throw new CloneNotSupportedException();
75 public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
76 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
77 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
78 final PhylogenyNode n = iter.next();
79 if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
80 stats.addValue( n.getDistanceToParent() );
86 public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
87 final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
88 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
89 final PhylogenyNode n = iter.next();
90 if ( !n.isExternal() && !n.isRoot() ) {
91 if ( n.getBranchData().isHasConfidences() ) {
92 for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
93 final Confidence c = n.getBranchData().getConfidences().get( i );
94 if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
95 stats.add( i, new BasicDescriptiveStatistics() );
97 if ( !ForesterUtil.isEmpty( c.getType() ) ) {
98 if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
99 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
100 throw new IllegalArgumentException( "support values in node [" + n.toString()
101 + "] appear inconsistently ordered" );
104 stats.get( i ).setDescription( c.getType() );
106 stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
115 * Calculates the distance between PhylogenyNodes node1 and node2.
120 * @return distance between node1 and node2
122 public static double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) {
123 final PhylogenyNode lca = calculateLCA( node1, node2 );
124 final PhylogenyNode n1 = node1;
125 final PhylogenyNode n2 = node2;
126 return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) );
130 * Returns the LCA of PhylogenyNodes node1 and node2.
135 * @return LCA of node1 and node2
137 public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) {
138 if ( node1 == null ) {
139 throw new IllegalArgumentException( "first argument (node) is null" );
141 if ( node2 == null ) {
142 throw new IllegalArgumentException( "second argument (node) is null" );
144 if ( node1 == node2 ) {
147 if ( ( node1.getParent() == node2.getParent() ) ) {
148 return node1.getParent();
150 int depth1 = node1.calculateDepth();
151 int depth2 = node2.calculateDepth();
152 while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) {
153 if ( depth1 > depth2 ) {
154 node1 = node1.getParent();
157 else if ( depth2 > depth1 ) {
158 node2 = node2.getParent();
162 if ( node1 == node2 ) {
165 node1 = node1.getParent();
166 node2 = node2.getParent();
171 throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" );
175 * Returns the LCA of PhylogenyNodes node1 and node2.
176 * Precondition: ids are in pre-order (or level-order).
181 * @return LCA of node1 and node2
183 public final static PhylogenyNode calculateLCAonTreeWithIdsInPreOrder( PhylogenyNode node1, PhylogenyNode node2 ) {
184 if ( node1 == null ) {
185 throw new IllegalArgumentException( "first argument (node) is null" );
187 if ( node2 == null ) {
188 throw new IllegalArgumentException( "second argument (node) is null" );
190 while ( node1 != node2 ) {
191 if ( node1.getId() > node2.getId() ) {
192 node1 = node1.getParent();
195 node2 = node2.getParent();
201 public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
202 if ( node.isExternal() ) {
206 for( PhylogenyNode d : node.getAllExternalDescendants() ) {
208 while ( d != node ) {
209 if ( d.isCollapse() ) {
224 public static int calculateMaxDepth( final Phylogeny phy ) {
226 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
227 final PhylogenyNode node = iter.next();
228 final int steps = node.calculateDepth();
236 public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
238 for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
239 final PhylogenyNode node = iter.next();
240 final double d = node.calculateDistanceToRoot();
248 public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
249 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
251 for( final PhylogenyNode n : descs ) {
252 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
259 public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
260 final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
261 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
262 final PhylogenyNode n = iter.next();
263 if ( !n.isExternal() ) {
264 stats.addValue( n.getNumberOfDescendants() );
270 public final static void collapseSubtreeStructure( final PhylogenyNode n ) {
271 final List<PhylogenyNode> eds = n.getAllExternalDescendants();
272 final List<Double> d = new ArrayList<Double>();
273 for( final PhylogenyNode ed : eds ) {
274 d.add( calculateDistanceToAncestor( n, ed ) );
276 for( int i = 0; i < eds.size(); ++i ) {
277 n.setChildNode( i, eds.get( i ) );
278 eds.get( i ).setDistanceToParent( d.get( i ) );
282 public static int countNumberOfOneDescendantNodes( final Phylogeny phy ) {
284 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
285 final PhylogenyNode n = iter.next();
286 if ( !n.isExternal() && ( n.getNumberOfDescendants() == 1 ) ) {
293 public static int countNumberOfPolytomies( final Phylogeny phy ) {
295 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
296 final PhylogenyNode n = iter.next();
297 if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
304 public static final HashMap<String, PhylogenyNode> createNameToExtNodeMap( final Phylogeny phy ) {
305 final HashMap<String, PhylogenyNode> nodes = new HashMap<String, PhylogenyNode>();
306 final List<PhylogenyNode> ext = phy.getExternalNodes();
307 for( final PhylogenyNode n : ext ) {
308 nodes.put( n.getName(), n );
313 public static void deleteExternalNodesNegativeSelection( final Set<Long> to_delete, final Phylogeny phy ) {
314 for( final Long id : to_delete ) {
315 phy.deleteSubtree( phy.getNode( id ), true );
317 phy.clearHashIdToNodeMap();
318 phy.externalNodesHaveChanged();
321 public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
322 throws IllegalArgumentException {
323 for( final String element : node_names_to_delete ) {
324 if ( ForesterUtil.isEmpty( element ) ) {
327 List<PhylogenyNode> nodes = null;
328 nodes = p.getNodes( element );
329 final Iterator<PhylogenyNode> it = nodes.iterator();
330 while ( it.hasNext() ) {
331 final PhylogenyNode n = it.next();
332 if ( !n.isExternal() ) {
333 throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
335 p.deleteSubtree( n, true );
338 p.clearHashIdToNodeMap();
339 p.externalNodesHaveChanged();
342 public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
343 final Phylogeny p ) {
344 final PhylogenyNodeIterator it = p.iteratorExternalForward();
345 final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
347 Arrays.sort( node_names_to_keep );
348 while ( it.hasNext() ) {
349 final String curent_name = it.next().getName();
350 if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
351 to_delete[ i++ ] = curent_name;
354 PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
355 final List<String> deleted = new ArrayList<String>();
356 for( final String n : to_delete ) {
357 if ( !ForesterUtil.isEmpty( n ) ) {
364 public static void deleteExternalNodesPositiveSelectionT( final List<Taxonomy> species_to_keep, final Phylogeny phy ) {
365 final Set<Long> to_delete = new HashSet<Long>();
366 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
367 final PhylogenyNode n = it.next();
368 if ( n.getNodeData().isHasTaxonomy() ) {
369 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
370 to_delete.add( n.getId() );
374 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
377 deleteExternalNodesNegativeSelection( to_delete, phy );
380 final public static void deleteInternalNodesWithOnlyOneDescendent( final Phylogeny phy ) {
381 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
382 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
383 final PhylogenyNode n = iter.next();
384 if ( ( !n.isExternal() ) && ( n.getNumberOfDescendants() == 1 ) ) {
388 for( final PhylogenyNode d : to_delete ) {
389 PhylogenyMethods.removeNode( d, phy );
391 phy.clearHashIdToNodeMap();
392 phy.externalNodesHaveChanged();
395 final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) {
396 if ( n.isInternal() ) {
397 throw new IllegalArgumentException( "node is not external" );
399 final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
400 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
401 final PhylogenyNode i = it.next();
402 if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) {
406 for( final PhylogenyNode d : to_delete ) {
407 phy.deleteSubtree( d, true );
409 phy.clearHashIdToNodeMap();
410 phy.externalNodesHaveChanged();
413 public final static List<List<PhylogenyNode>> divideIntoSubTrees( final Phylogeny phy,
414 final double min_distance_to_root ) {
415 if ( min_distance_to_root <= 0 ) {
416 throw new IllegalArgumentException( "attempt to use min distance to root of: " + min_distance_to_root );
418 final List<List<PhylogenyNode>> l = new ArrayList<List<PhylogenyNode>>();
419 setAllIndicatorsToZero( phy );
420 for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
421 final PhylogenyNode n = it.next();
422 if ( n.getIndicator() != 0 ) {
425 l.add( divideIntoSubTreesHelper( n, min_distance_to_root ) );
427 throw new RuntimeException( "this should not have happened" );
433 public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
434 final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
435 final Set<Long> encountered = new HashSet<Long>();
436 if ( !node.isExternal() ) {
437 final List<PhylogenyNode> exts = node.getAllExternalDescendants();
438 for( PhylogenyNode current : exts ) {
439 descs.add( current );
440 while ( current != node ) {
441 current = current.getParent();
442 if ( encountered.contains( current.getId() ) ) {
445 descs.add( current );
446 encountered.add( current.getId() );
460 public static Color getBranchColorValue( final PhylogenyNode node ) {
461 if ( node.getBranchData().getBranchColor() == null ) {
464 return node.getBranchData().getBranchColor().getValue();
470 public static double getBranchWidthValue( final PhylogenyNode node ) {
471 if ( !node.getBranchData().isHasBranchWidth() ) {
472 return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
474 return node.getBranchData().getBranchWidth().getValue();
480 public static double getConfidenceValue( final PhylogenyNode node ) {
481 if ( !node.getBranchData().isHasConfidences() ) {
482 return Confidence.CONFIDENCE_DEFAULT_VALUE;
484 return node.getBranchData().getConfidence( 0 ).getValue();
490 public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
491 if ( !node.getBranchData().isHasConfidences() ) {
492 return new double[ 0 ];
494 final double[] values = new double[ node.getBranchData().getConfidences().size() ];
496 for( final Confidence c : node.getBranchData().getConfidences() ) {
497 values[ i++ ] = c.getValue();
502 final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) {
503 return calculateLCA( n1, n2 ).getNodeData().getEvent();
507 * Returns taxonomy t if all external descendants have
508 * the same taxonomy t, null otherwise.
511 public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
512 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
514 for( final PhylogenyNode n : descs ) {
515 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
518 else if ( tax == null ) {
519 tax = n.getNodeData().getTaxonomy();
521 else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
528 public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
529 final List<PhylogenyNode> children = node.getAllExternalDescendants();
530 PhylogenyNode farthest = null;
531 double longest = -Double.MAX_VALUE;
532 for( final PhylogenyNode child : children ) {
533 if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
535 longest = PhylogenyMethods.getDistance( child, node );
541 // public static PhylogenyMethods getInstance() {
542 // if ( PhylogenyMethods._instance == null ) {
543 // PhylogenyMethods._instance = new PhylogenyMethods();
545 // return PhylogenyMethods._instance;
548 * Returns the largest confidence value found on phy.
550 static public double getMaximumConfidenceValue( final Phylogeny phy ) {
551 double max = -Double.MAX_VALUE;
552 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
553 final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
554 if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
561 static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
562 int min = Integer.MAX_VALUE;
565 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
567 if ( n.isInternal() ) {
568 d = n.getNumberOfDescendants();
578 * Convenience method for display purposes.
579 * Not intended for algorithms.
581 public static String getSpecies( final PhylogenyNode node ) {
582 if ( !node.getNodeData().isHasTaxonomy() ) {
585 else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
586 return node.getNodeData().getTaxonomy().getScientificName();
588 if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
589 return node.getNodeData().getTaxonomy().getTaxonomyCode();
592 return node.getNodeData().getTaxonomy().getCommonName();
597 * Convenience method for display purposes.
598 * Not intended for algorithms.
600 public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
601 if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
604 return node.getNodeData().getTaxonomy().getIdentifier().getValue();
607 public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) {
608 if ( n.isExternal() ) {
612 if ( n.isDuplication() ) {
613 for( final PhylogenyNode desc : n.getDescendants() ) {
614 if ( !isAllDecendentsAreDuplications( desc ) ) {
626 public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
627 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
628 if ( node.getChildNode( i ).isExternal() ) {
636 * This is case insensitive.
639 public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
640 final String[] providers ) {
641 if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
642 final String my_tax_prov = tax.getIdentifier().getProvider();
643 for( final String provider : providers ) {
644 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
655 public static void midpointRoot( final Phylogeny phylogeny ) {
656 if ( ( phylogeny.getNumberOfExternalNodes() < 2 ) || ( calculateMaxDistanceToRoot( phylogeny ) <= 0 ) ) {
660 final int total_nodes = phylogeny.getNodeCount();
662 if ( ++counter > total_nodes ) {
663 throw new RuntimeException( "this should not have happened: midpoint rooting does not converge" );
665 PhylogenyNode a = null;
668 for( int i = 0; i < phylogeny.getRoot().getNumberOfDescendants(); ++i ) {
669 final PhylogenyNode f = getFurthestDescendant( phylogeny.getRoot().getChildNode( i ) );
670 final double df = getDistance( f, phylogeny.getRoot() );
677 else if ( df > db ) {
682 final double diff = da - db;
683 if ( diff < 0.000001 ) {
686 double x = da - ( diff / 2.0 );
687 while ( ( x > a.getDistanceToParent() ) && !a.isRoot() ) {
688 x -= ( a.getDistanceToParent() > 0 ? a.getDistanceToParent() : 0 );
691 phylogeny.reRoot( a, x );
693 phylogeny.recalculateNumberOfExternalDescendants( true );
696 public static void normalizeBootstrapValues( final Phylogeny phylogeny,
697 final double max_bootstrap_value,
698 final double max_normalized_value ) {
699 for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
700 final PhylogenyNode node = iter.next();
701 if ( node.isInternal() ) {
702 final double confidence = getConfidenceValue( node );
703 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
704 if ( confidence >= max_bootstrap_value ) {
705 setBootstrapConfidence( node, max_normalized_value );
708 setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
715 public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
716 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
717 if ( phy.isEmpty() ) {
720 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
721 nodes.add( iter.next() );
727 * Returns a map of distinct taxonomies of
728 * all external nodes of node.
729 * If at least one of the external nodes has no taxonomy,
733 public static Map<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
734 final List<PhylogenyNode> descs = node.getAllExternalDescendants();
735 final Map<Taxonomy, Integer> tax_map = new HashMap<Taxonomy, Integer>();
736 for( final PhylogenyNode n : descs ) {
737 if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
740 final Taxonomy t = n.getNodeData().getTaxonomy();
741 if ( tax_map.containsKey( t ) ) {
742 tax_map.put( t, tax_map.get( t ) + 1 );
752 * Arranges the order of childern for each node of this Phylogeny in such a
753 * way that either the branch with more children is on top (right) or on
754 * bottom (left), dependent on the value of boolean order.
757 * decides in which direction to order
760 public static void orderAppearance( final PhylogenyNode n,
762 final boolean order_ext_alphabetically,
763 final DESCENDANT_SORT_PRIORITY pri ) {
764 if ( n.isExternal() ) {
768 PhylogenyNode temp = null;
769 if ( ( n.getNumberOfDescendants() == 2 )
770 && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
771 && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
772 temp = n.getChildNode1();
773 n.setChild1( n.getChildNode2() );
776 else if ( order_ext_alphabetically ) {
777 boolean all_ext = true;
778 for( final PhylogenyNode i : n.getDescendants() ) {
779 if ( !i.isExternal() ) {
785 PhylogenyMethods.sortNodeDescendents( n, pri );
788 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
789 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
794 public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
795 for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
796 final PhylogenyNode node = iter.next();
801 if ( node.isInternal() ) {
802 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
803 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
804 final PhylogenyNode child_node = node.getChildNode( i );
805 final Color child_color = getBranchColorValue( child_node );
806 if ( child_color != null ) {
808 red += child_color.getRed();
809 green += child_color.getGreen();
810 blue += child_color.getBlue();
813 setBranchColorValue( node,
814 new Color( ForesterUtil.roundToInt( red / n ),
815 ForesterUtil.roundToInt( green / n ),
816 ForesterUtil.roundToInt( blue / n ) ) );
821 public static final void preOrderReId( final Phylogeny phy ) {
822 if ( phy.isEmpty() ) {
825 phy.setIdToNodeMap( null );
826 long i = PhylogenyNode.getNodeCount();
827 for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
828 it.next().setId( i++ );
830 PhylogenyNode.setNodeCount( i );
833 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
834 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
835 final Phylogeny[] trees = factory.create( file, parser );
836 if ( ( trees == null ) || ( trees.length == 0 ) ) {
837 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
842 public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
844 final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
845 for( final File file : files ) {
846 final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
847 final Phylogeny[] trees = factory.create( file, parser );
848 if ( ( trees == null ) || ( trees.length == 0 ) ) {
849 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
851 tree_list.addAll( Arrays.asList( trees ) );
853 return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
856 public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
857 if ( remove_me.isRoot() ) {
858 if ( remove_me.getNumberOfDescendants() == 1 ) {
859 final PhylogenyNode desc = remove_me.getDescendants().get( 0 );
860 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
861 desc.getDistanceToParent() ) );
862 desc.setParent( null );
863 phylogeny.setRoot( desc );
864 phylogeny.clearHashIdToNodeMap();
867 throw new IllegalArgumentException( "attempt to remove a root node with more than one descendants" );
870 else if ( remove_me.isExternal() ) {
871 phylogeny.deleteSubtree( remove_me, false );
872 phylogeny.clearHashIdToNodeMap();
873 phylogeny.externalNodesHaveChanged();
876 final PhylogenyNode parent = remove_me.getParent();
877 final List<PhylogenyNode> descs = remove_me.getDescendants();
878 parent.removeChildNode( remove_me );
879 for( final PhylogenyNode desc : descs ) {
880 parent.addAsChild( desc );
881 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
882 desc.getDistanceToParent() ) );
884 remove_me.setParent( null );
885 phylogeny.clearHashIdToNodeMap();
886 phylogeny.externalNodesHaveChanged();
890 public static List<PhylogenyNode> searchData( final String query,
892 final boolean case_sensitive,
893 final boolean partial,
894 final boolean search_domains ) {
895 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
896 if ( phy.isEmpty() || ( query == null ) ) {
899 if ( ForesterUtil.isEmpty( query ) ) {
902 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
903 final PhylogenyNode node = iter.next();
904 boolean match = false;
905 if ( match( node.getName(), query, case_sensitive, partial ) ) {
908 else if ( node.getNodeData().isHasTaxonomy()
909 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
912 else if ( node.getNodeData().isHasTaxonomy()
913 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
916 else if ( node.getNodeData().isHasTaxonomy()
917 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
920 else if ( node.getNodeData().isHasTaxonomy()
921 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
922 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
928 else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
929 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
930 I: for( final String syn : syns ) {
931 if ( match( syn, query, case_sensitive, partial ) ) {
937 if ( !match && node.getNodeData().isHasSequence()
938 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
941 if ( !match && node.getNodeData().isHasSequence()
942 && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) {
945 if ( !match && node.getNodeData().isHasSequence()
946 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
950 && node.getNodeData().isHasSequence()
951 && ( node.getNodeData().getSequence().getAccession() != null )
952 && match( node.getNodeData().getSequence().getAccession().getValue(),
958 if ( search_domains && !match && node.getNodeData().isHasSequence()
959 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
960 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
961 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
962 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
969 if ( !match && node.getNodeData().isHasSequence()
970 && ( node.getNodeData().getSequence().getAnnotations() != null ) ) {
971 for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) {
972 if ( match( ann.getDesc(), query, case_sensitive, partial ) ) {
976 if ( match( ann.getRef(), query, case_sensitive, partial ) ) {
982 if ( !match && node.getNodeData().isHasSequence()
983 && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) {
984 for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) {
985 if ( match( x.getComment(), query, case_sensitive, partial ) ) {
989 if ( match( x.getSource(), query, case_sensitive, partial ) ) {
993 if ( match( x.getValue(), query, case_sensitive, partial ) ) {
1000 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1001 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1002 I: while ( it.hasNext() ) {
1003 if ( match( it.next(), query, case_sensitive, partial ) ) {
1008 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1009 I: while ( it.hasNext() ) {
1010 if ( match( it.next(), query, case_sensitive, partial ) ) {
1023 public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1024 final Phylogeny phy,
1025 final boolean case_sensitive,
1026 final boolean partial,
1027 final boolean search_domains ) {
1028 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1029 if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1032 for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1033 final PhylogenyNode node = iter.next();
1034 boolean all_matched = true;
1035 for( final String query : queries ) {
1036 boolean match = false;
1037 if ( ForesterUtil.isEmpty( query ) ) {
1040 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1043 else if ( node.getNodeData().isHasTaxonomy()
1044 && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1047 else if ( node.getNodeData().isHasTaxonomy()
1048 && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1051 else if ( node.getNodeData().isHasTaxonomy()
1052 && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1055 else if ( node.getNodeData().isHasTaxonomy()
1056 && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1057 && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1063 else if ( node.getNodeData().isHasTaxonomy()
1064 && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1065 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1066 I: for( final String syn : syns ) {
1067 if ( match( syn, query, case_sensitive, partial ) ) {
1073 if ( !match && node.getNodeData().isHasSequence()
1074 && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1077 if ( !match && node.getNodeData().isHasSequence()
1078 && match( node.getNodeData().getSequence().getGeneName(), query, case_sensitive, partial ) ) {
1081 if ( !match && node.getNodeData().isHasSequence()
1082 && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1086 && node.getNodeData().isHasSequence()
1087 && ( node.getNodeData().getSequence().getAccession() != null )
1088 && match( node.getNodeData().getSequence().getAccession().getValue(),
1094 if ( search_domains && !match && node.getNodeData().isHasSequence()
1095 && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1096 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1097 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1098 if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1105 if ( !match && node.getNodeData().isHasSequence()
1106 && ( node.getNodeData().getSequence().getAnnotations() != null ) ) {
1107 for( final Annotation ann : node.getNodeData().getSequence().getAnnotations() ) {
1108 if ( match( ann.getDesc(), query, case_sensitive, partial ) ) {
1112 if ( match( ann.getRef(), query, case_sensitive, partial ) ) {
1118 if ( !match && node.getNodeData().isHasSequence()
1119 && ( node.getNodeData().getSequence().getCrossReferences() != null ) ) {
1120 for( final Accession x : node.getNodeData().getSequence().getCrossReferences() ) {
1121 if ( match( x.getComment(), query, case_sensitive, partial ) ) {
1125 if ( match( x.getSource(), query, case_sensitive, partial ) ) {
1129 if ( match( x.getValue(), query, case_sensitive, partial ) ) {
1136 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1137 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1138 I: while ( it.hasNext() ) {
1139 if ( match( it.next(), query, case_sensitive, partial ) ) {
1144 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1145 I: while ( it.hasNext() ) {
1146 if ( match( it.next(), query, case_sensitive, partial ) ) {
1153 all_matched = false;
1157 if ( all_matched ) {
1164 public static void setAllIndicatorsToZero( final Phylogeny phy ) {
1165 for( final PhylogenyNodeIterator it = phy.iteratorPostorder(); it.hasNext(); ) {
1166 it.next().setIndicator( ( byte ) 0 );
1171 * Convenience method.
1172 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1174 public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1175 setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1178 public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1179 if ( node.getBranchData().getBranchColor() == null ) {
1180 node.getBranchData().setBranchColor( new BranchColor() );
1182 node.getBranchData().getBranchColor().setValue( color );
1186 * Convenience method
1188 public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1189 node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1193 * Convenience method.
1194 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1196 public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1197 setConfidence( node, confidence_value, "" );
1201 * Convenience method.
1202 * Sets value for the first confidence value (created if not present, values overwritten otherwise).
1204 public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1205 Confidence c = null;
1206 if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1207 c = node.getBranchData().getConfidence( 0 );
1210 c = new Confidence();
1211 node.getBranchData().addConfidence( c );
1214 c.setValue( confidence_value );
1217 public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1218 if ( !node.getNodeData().isHasTaxonomy() ) {
1219 node.getNodeData().setTaxonomy( new Taxonomy() );
1221 node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1225 * Convenience method to set the taxonomy code of a phylogeny node.
1229 * @param taxonomy_code
1230 * @throws PhyloXmlDataFormatException
1232 public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1233 throws PhyloXmlDataFormatException {
1234 if ( !node.getNodeData().isHasTaxonomy() ) {
1235 node.getNodeData().setTaxonomy( new Taxonomy() );
1237 node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1240 final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
1241 class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
1244 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1245 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1246 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1247 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1248 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1249 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1251 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1252 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1253 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1254 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1256 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1257 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1258 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1259 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1262 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1263 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1264 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1265 return n1.getNodeData().getSequence().getName().toLowerCase()
1266 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1268 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1269 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1270 return n1.getNodeData().getSequence().getSymbol()
1271 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1273 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) )
1274 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) {
1275 return n1.getNodeData().getSequence().getGeneName()
1276 .compareTo( n2.getNodeData().getSequence().getGeneName() );
1278 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1279 && ( n2.getNodeData().getSequence().getAccession() != null )
1280 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1281 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1282 return n1.getNodeData().getSequence().getAccession().getValue()
1283 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1286 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1287 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1292 class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
1295 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1296 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1297 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1298 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1299 return n1.getNodeData().getSequence().getName().toLowerCase()
1300 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1302 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1303 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1304 return n1.getNodeData().getSequence().getSymbol()
1305 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1307 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) )
1308 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) {
1309 return n1.getNodeData().getSequence().getGeneName()
1310 .compareTo( n2.getNodeData().getSequence().getGeneName() );
1312 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1313 && ( n2.getNodeData().getSequence().getAccession() != null )
1314 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1315 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1316 return n1.getNodeData().getSequence().getAccession().getValue()
1317 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1320 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1321 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1322 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1323 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1324 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1326 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1327 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1328 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1329 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1331 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1332 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1333 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1334 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1337 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1338 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1343 class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
1346 public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1347 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1348 return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1350 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1351 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1352 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1353 return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1354 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1356 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1357 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1358 return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1359 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1361 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1362 && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1363 return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1364 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1367 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1368 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1369 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1370 return n1.getNodeData().getSequence().getName().toLowerCase()
1371 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1373 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1374 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1375 return n1.getNodeData().getSequence().getSymbol()
1376 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1378 if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getGeneName() ) )
1379 && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getGeneName() ) ) ) {
1380 return n1.getNodeData().getSequence().getGeneName()
1381 .compareTo( n2.getNodeData().getSequence().getGeneName() );
1383 if ( ( n1.getNodeData().getSequence().getAccession() != null )
1384 && ( n2.getNodeData().getSequence().getAccession() != null )
1385 && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1386 && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1387 return n1.getNodeData().getSequence().getAccession().getValue()
1388 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1394 Comparator<PhylogenyNode> c;
1397 c = new PhylogenyNodeSortSequencePriority();
1400 c = new PhylogenyNodeSortNodeNamePriority();
1403 c = new PhylogenyNodeSortTaxonomyPriority();
1405 final List<PhylogenyNode> descs = node.getDescendants();
1406 Collections.sort( descs, c );
1408 for( final PhylogenyNode desc : descs ) {
1409 node.setChildNode( i++, desc );
1414 * Removes from Phylogeny to_be_stripped all external Nodes which are
1415 * associated with a species NOT found in Phylogeny reference.
1418 * a reference Phylogeny
1419 * @param to_be_stripped
1420 * Phylogeny to be stripped
1421 * @return nodes removed from to_be_stripped
1423 public static List<PhylogenyNode> taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference,
1424 final Phylogeny to_be_stripped ) {
1425 final Set<String> ref_ext_taxo = new HashSet<String>();
1426 for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1427 final PhylogenyNode n = it.next();
1428 if ( !n.getNodeData().isHasTaxonomy() ) {
1429 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1431 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1432 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1434 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1435 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1437 if ( ( n.getNodeData().getTaxonomy().getIdentifier() != null )
1438 && !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getIdentifier().getValue() ) ) {
1439 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() );
1442 final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1443 for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1444 final PhylogenyNode n = it.next();
1445 if ( !n.getNodeData().isHasTaxonomy() ) {
1446 nodes_to_delete.add( n );
1448 else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1449 && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1450 && !( ( n.getNodeData().getTaxonomy().getIdentifier() != null ) && ref_ext_taxo.contains( n
1451 .getNodeData().getTaxonomy().getIdentifier().getValuePlusProvider() ) ) ) {
1452 nodes_to_delete.add( n );
1455 for( final PhylogenyNode n : nodes_to_delete ) {
1456 to_be_stripped.deleteSubtree( n, true );
1458 to_be_stripped.clearHashIdToNodeMap();
1459 to_be_stripped.externalNodesHaveChanged();
1460 return nodes_to_delete;
1463 final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
1464 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1465 while ( it.hasNext() ) {
1466 final PhylogenyNode n = it.next();
1467 if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
1470 value = Double.parseDouble( n.getName() );
1472 catch ( final NumberFormatException e ) {
1473 throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
1474 + e.getLocalizedMessage() );
1476 if ( value >= 0.0 ) {
1477 n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
1484 final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
1485 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1486 while ( it.hasNext() ) {
1487 final PhylogenyNode n = it.next();
1488 if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
1489 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
1492 d = Double.parseDouble( n.getName() );
1494 catch ( final Exception e ) {
1498 n.getBranchData().addConfidence( new Confidence( d, "" ) );
1506 final static public void transferNodeNameToField( final Phylogeny phy,
1507 final PhylogenyNodeField field,
1508 final boolean external_only ) throws PhyloXmlDataFormatException {
1509 final PhylogenyNodeIterator it = phy.iteratorPostorder();
1510 while ( it.hasNext() ) {
1511 final PhylogenyNode n = it.next();
1512 if ( external_only && n.isInternal() ) {
1515 final String name = n.getName().trim();
1516 if ( !ForesterUtil.isEmpty( name ) ) {
1520 setTaxonomyCode( n, name );
1522 case TAXONOMY_SCIENTIFIC_NAME:
1524 if ( !n.getNodeData().isHasTaxonomy() ) {
1525 n.getNodeData().setTaxonomy( new Taxonomy() );
1527 n.getNodeData().getTaxonomy().setScientificName( name );
1529 case TAXONOMY_COMMON_NAME:
1531 if ( !n.getNodeData().isHasTaxonomy() ) {
1532 n.getNodeData().setTaxonomy( new Taxonomy() );
1534 n.getNodeData().getTaxonomy().setCommonName( name );
1536 case SEQUENCE_SYMBOL:
1538 if ( !n.getNodeData().isHasSequence() ) {
1539 n.getNodeData().setSequence( new Sequence() );
1541 n.getNodeData().getSequence().setSymbol( name );
1545 if ( !n.getNodeData().isHasSequence() ) {
1546 n.getNodeData().setSequence( new Sequence() );
1548 n.getNodeData().getSequence().setName( name );
1550 case TAXONOMY_ID_UNIPROT_1: {
1551 if ( !n.getNodeData().isHasTaxonomy() ) {
1552 n.getNodeData().setTaxonomy( new Taxonomy() );
1555 final int i = name.indexOf( '_' );
1557 id = name.substring( 0, i );
1562 n.getNodeData().getTaxonomy()
1563 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1566 case TAXONOMY_ID_UNIPROT_2: {
1567 if ( !n.getNodeData().isHasTaxonomy() ) {
1568 n.getNodeData().setTaxonomy( new Taxonomy() );
1571 final int i = name.indexOf( '_' );
1573 id = name.substring( i + 1, name.length() );
1578 n.getNodeData().getTaxonomy()
1579 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1583 if ( !n.getNodeData().isHasTaxonomy() ) {
1584 n.getNodeData().setTaxonomy( new Taxonomy() );
1586 n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
1594 static double addPhylogenyDistances( final double a, final double b ) {
1595 if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
1598 else if ( a >= 0.0 ) {
1601 else if ( b >= 0.0 ) {
1604 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
1607 static double calculateDistanceToAncestor( final PhylogenyNode anc, PhylogenyNode desc ) {
1609 boolean all_default = true;
1610 while ( anc != desc ) {
1611 if ( desc.getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
1612 d += desc.getDistanceToParent();
1613 if ( all_default ) {
1614 all_default = false;
1617 desc = desc.getParent();
1619 if ( all_default ) {
1620 return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
1626 * Deep copies the phylogeny originating from this node.
1628 static PhylogenyNode copySubTree( final PhylogenyNode source ) {
1629 if ( source == null ) {
1633 final PhylogenyNode newnode = source.copyNodeData();
1634 if ( !source.isExternal() ) {
1635 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1636 newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
1644 * Shallow copies the phylogeny originating from this node.
1646 static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
1647 if ( source == null ) {
1651 final PhylogenyNode newnode = source.copyNodeDataShallow();
1652 if ( !source.isExternal() ) {
1653 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1654 newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
1661 private final static List<PhylogenyNode> divideIntoSubTreesHelper( final PhylogenyNode node,
1662 final double min_distance_to_root ) {
1663 final List<PhylogenyNode> l = new ArrayList<PhylogenyNode>();
1664 final PhylogenyNode r = moveTowardsRoot( node, min_distance_to_root );
1665 for( final PhylogenyNode ext : r.getAllExternalDescendants() ) {
1666 if ( ext.getIndicator() != 0 ) {
1667 throw new RuntimeException( "this should not have happened" );
1669 ext.setIndicator( ( byte ) 1 );
1676 * Calculates the distance between PhylogenyNodes n1 and n2.
1677 * PRECONDITION: n1 is a descendant of n2.
1680 * a descendant of n2
1682 * @return distance between n1 and n2
1684 private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
1686 while ( n1 != n2 ) {
1687 if ( n1.getDistanceToParent() > 0.0 ) {
1688 d += n1.getDistanceToParent();
1690 n1 = n1.getParent();
1695 private static boolean match( final String s,
1697 final boolean case_sensitive,
1698 final boolean partial ) {
1699 if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1702 String my_s = s.trim();
1703 String my_query = query.trim();
1704 if ( !case_sensitive ) {
1705 my_s = my_s.toLowerCase();
1706 my_query = my_query.toLowerCase();
1709 return my_s.indexOf( my_query ) >= 0;
1712 return my_s.equals( my_query );
1716 private final static PhylogenyNode moveTowardsRoot( final PhylogenyNode node, final double min_distance_to_root ) {
1717 PhylogenyNode n = node;
1718 PhylogenyNode prev = node;
1719 while ( min_distance_to_root < n.calculateDistanceToRoot() ) {
1726 public static enum DESCENDANT_SORT_PRIORITY {
1727 NODE_NAME, SEQUENCE, TAXONOMY;
1730 public static enum PhylogenyNodeField {
1735 TAXONOMY_COMMON_NAME,
1737 TAXONOMY_ID_UNIPROT_1,
1738 TAXONOMY_ID_UNIPROT_2,
1739 TAXONOMY_SCIENTIFIC_NAME;