midpoint rooting is faster
[jalview.git] / forester / java / src / org / forester / phylogeny / PhylogenyMethods.java
1 // $Id:
2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
4 //
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
7 // All rights reserved
8 //
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.
13 //
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.
18 //
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
22 //
23 // Contact: phylosoft @ gmail . com
24 // WWW: www.phylosoft.org/forester
25
26 package org.forester.phylogeny;
27
28 import java.awt.Color;
29 import java.io.File;
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;
39 import java.util.Set;
40 import java.util.SortedMap;
41 import java.util.TreeMap;
42
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.BranchColor;
48 import org.forester.phylogeny.data.BranchWidth;
49 import org.forester.phylogeny.data.Confidence;
50 import org.forester.phylogeny.data.DomainArchitecture;
51 import org.forester.phylogeny.data.Event;
52 import org.forester.phylogeny.data.Identifier;
53 import org.forester.phylogeny.data.PhylogenyDataUtil;
54 import org.forester.phylogeny.data.Sequence;
55 import org.forester.phylogeny.data.Taxonomy;
56 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
57 import org.forester.phylogeny.factories.PhylogenyFactory;
58 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
59 import org.forester.util.BasicDescriptiveStatistics;
60 import org.forester.util.DescriptiveStatistics;
61 import org.forester.util.ForesterUtil;
62
63 public class PhylogenyMethods {
64
65     //private static PhylogenyMethods _instance   = null;
66     //private final PhylogenyNode     _farthest_1 = null;
67     //private final PhylogenyNode     _farthest_2 = null;
68     private PhylogenyMethods() {
69         // Hidden constructor.
70     }
71
72     //    public double calculateFurthestDistance( final Phylogeny phylogeny ) {
73     //        if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
74     //            return 0.0;
75     //        }
76     //        _farthest_1 = null;
77     //        _farthest_2 = null;
78     //        PhylogenyNode node_1 = null;
79     //        PhylogenyNode node_2 = null;
80     //        double farthest_d = -Double.MAX_VALUE;
81     //        final PhylogenyMethods methods = PhylogenyMethods.getInstance();
82     //        final List<PhylogenyNode> ext_nodes = phylogeny.getRoot().getAllExternalDescendants();
83     //        for( int i = 1; i < ext_nodes.size(); ++i ) {
84     //            for( int j = 0; j < i; ++j ) {
85     //                final double d = methods.calculateDistance( ext_nodes.get( i ), ext_nodes.get( j ) );
86     //                if ( d < 0.0 ) {
87     //                    throw new RuntimeException( "distance cannot be negative" );
88     //                }
89     //                if ( d > farthest_d ) {
90     //                    farthest_d = d;
91     //                    node_1 = ext_nodes.get( i );
92     //                    node_2 = ext_nodes.get( j );
93     //                }
94     //            }
95     //        }
96     //        _farthest_1 = node_1;
97     //        _farthest_2 = node_2;
98     //        return farthest_d;
99     //    }
100     @Override
101     public Object clone() throws CloneNotSupportedException {
102         throw new CloneNotSupportedException();
103     }
104
105     // public PhylogenyNode getFarthestNode1() {
106     //      return _farthest_1;
107     // }
108     //  public PhylogenyNode getFarthestNode2() {
109     //      return _farthest_2;
110     //  }
111     public static DescriptiveStatistics calculatBranchLengthStatistics( final Phylogeny phy ) {
112         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
113         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
114             final PhylogenyNode n = iter.next();
115             if ( !n.isRoot() && ( n.getDistanceToParent() >= 0.0 ) ) {
116                 stats.addValue( n.getDistanceToParent() );
117             }
118         }
119         return stats;
120     }
121
122     public static List<DescriptiveStatistics> calculatConfidenceStatistics( final Phylogeny phy ) {
123         final List<DescriptiveStatistics> stats = new ArrayList<DescriptiveStatistics>();
124         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
125             final PhylogenyNode n = iter.next();
126             if ( !n.isExternal() && !n.isRoot() ) {
127                 if ( n.getBranchData().isHasConfidences() ) {
128                     for( int i = 0; i < n.getBranchData().getConfidences().size(); ++i ) {
129                         final Confidence c = n.getBranchData().getConfidences().get( i );
130                         if ( ( i > ( stats.size() - 1 ) ) || ( stats.get( i ) == null ) ) {
131                             stats.add( i, new BasicDescriptiveStatistics() );
132                         }
133                         if ( !ForesterUtil.isEmpty( c.getType() ) ) {
134                             if ( !ForesterUtil.isEmpty( stats.get( i ).getDescription() ) ) {
135                                 if ( !stats.get( i ).getDescription().equalsIgnoreCase( c.getType() ) ) {
136                                     throw new IllegalArgumentException( "support values in node [" + n.toString()
137                                             + "] appear inconsistently ordered" );
138                                 }
139                             }
140                             stats.get( i ).setDescription( c.getType() );
141                         }
142                         stats.get( i ).addValue( ( ( c != null ) && ( c.getValue() >= 0 ) ) ? c.getValue() : 0 );
143                     }
144                 }
145             }
146         }
147         return stats;
148     }
149
150     /**
151      * Calculates the distance between PhylogenyNodes node1 and node2.
152      * 
153      * 
154      * @param node1
155      * @param node2
156      * @return distance between node1 and node2
157      */
158     public static double calculateDistance( final PhylogenyNode node1, final PhylogenyNode node2 ) {
159         final PhylogenyNode lca = calculateLCA( node1, node2 );
160         final PhylogenyNode n1 = node1;
161         final PhylogenyNode n2 = node2;
162         return ( PhylogenyMethods.getDistance( n1, lca ) + PhylogenyMethods.getDistance( n2, lca ) );
163     }
164
165     /**
166      * Returns the LCA of PhylogenyNodes node1 and node2.
167      * 
168      * 
169      * @param node1
170      * @param node2
171      * @return LCA of node1 and node2
172      */
173     public final static PhylogenyNode calculateLCA( PhylogenyNode node1, PhylogenyNode node2 ) {
174         if ( node1 == null ) {
175             throw new IllegalArgumentException( "first argument (node) is null" );
176         }
177         if ( node2 == null ) {
178             throw new IllegalArgumentException( "second argument (node) is null" );
179         }
180         if ( node1 == node2 ) {
181             return node1;
182         }
183         if ( ( node1.getParent() == node2.getParent() ) ) {
184             return node1.getParent();
185         }
186         int depth1 = node1.calculateDepth();
187         int depth2 = node2.calculateDepth();
188         while ( ( depth1 > -1 ) && ( depth2 > -1 ) ) {
189             if ( depth1 > depth2 ) {
190                 node1 = node1.getParent();
191                 depth1--;
192             }
193             else if ( depth2 > depth1 ) {
194                 node2 = node2.getParent();
195                 depth2--;
196             }
197             else {
198                 if ( node1 == node2 ) {
199                     return node1;
200                 }
201                 node1 = node1.getParent();
202                 node2 = node2.getParent();
203                 depth1--;
204                 depth2--;
205             }
206         }
207         throw new IllegalArgumentException( "illegal attempt to calculate LCA of two nodes which do not share a common root" );
208     }
209
210     /**
211      * Returns the LCA of PhylogenyNodes node1 and node2.
212      * Precondition: ids are in pre-order (or level-order).
213      * 
214      * 
215      * @param node1
216      * @param node2
217      * @return LCA of node1 and node2
218      */
219     public final static PhylogenyNode calculateLCAonTreeWithIdsInPreOrder( PhylogenyNode node1, PhylogenyNode node2 ) {
220         if ( node1 == null ) {
221             throw new IllegalArgumentException( "first argument (node) is null" );
222         }
223         if ( node2 == null ) {
224             throw new IllegalArgumentException( "second argument (node) is null" );
225         }
226         while ( node1 != node2 ) {
227             if ( node1.getId() > node2.getId() ) {
228                 node1 = node1.getParent();
229             }
230             else {
231                 node2 = node2.getParent();
232             }
233         }
234         return node1;
235     }
236
237     public static short calculateMaxBranchesToLeaf( final PhylogenyNode node ) {
238         if ( node.isExternal() ) {
239             return 0;
240         }
241         short max = 0;
242         for( PhylogenyNode d : node.getAllExternalDescendants() ) {
243             short steps = 0;
244             while ( d != node ) {
245                 if ( d.isCollapse() ) {
246                     steps = 0;
247                 }
248                 else {
249                     steps++;
250                 }
251                 d = d.getParent();
252             }
253             if ( max < steps ) {
254                 max = steps;
255             }
256         }
257         return max;
258     }
259
260     public static int calculateMaxDepth( final Phylogeny phy ) {
261         int max = 0;
262         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
263             final PhylogenyNode node = iter.next();
264             final int steps = node.calculateDepth();
265             if ( steps > max ) {
266                 max = steps;
267             }
268         }
269         return max;
270     }
271
272     public static double calculateMaxDistanceToRoot( final Phylogeny phy ) {
273         double max = 0.0;
274         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
275             final PhylogenyNode node = iter.next();
276             final double d = node.calculateDistanceToRoot();
277             if ( d > max ) {
278                 max = d;
279             }
280         }
281         return max;
282     }
283
284     public static int calculateNumberOfExternalNodesWithoutTaxonomy( final PhylogenyNode node ) {
285         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
286         int x = 0;
287         for( final PhylogenyNode n : descs ) {
288             if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
289                 x++;
290             }
291         }
292         return x;
293     }
294
295     public static DescriptiveStatistics calculatNumberOfDescendantsPerNodeStatistics( final Phylogeny phy ) {
296         final DescriptiveStatistics stats = new BasicDescriptiveStatistics();
297         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
298             final PhylogenyNode n = iter.next();
299             if ( !n.isExternal() ) {
300                 stats.addValue( n.getNumberOfDescendants() );
301             }
302         }
303         return stats;
304     }
305
306     public static int countNumberOfOneDescendantNodes( final Phylogeny phy ) {
307         int count = 0;
308         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
309             final PhylogenyNode n = iter.next();
310             if ( !n.isExternal() && ( n.getNumberOfDescendants() == 1 ) ) {
311                 count++;
312             }
313         }
314         return count;
315     }
316
317     public static int countNumberOfPolytomies( final Phylogeny phy ) {
318         int count = 0;
319         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
320             final PhylogenyNode n = iter.next();
321             if ( !n.isExternal() && ( n.getNumberOfDescendants() > 2 ) ) {
322                 count++;
323             }
324         }
325         return count;
326     }
327
328     public static final HashMap<String, PhylogenyNode> createNameToExtNodeMap( final Phylogeny phy ) {
329         final HashMap<String, PhylogenyNode> nodes = new HashMap<String, PhylogenyNode>();
330         for( final PhylogenyNodeIterator iter = phy.iteratorExternalForward(); iter.hasNext(); ) {
331             final PhylogenyNode n = iter.next();
332             nodes.put( n.getName(), n );
333         }
334         return nodes;
335     }
336
337     public static void deleteExternalNodesNegativeSelection( final Set<Integer> to_delete, final Phylogeny phy ) {
338         phy.clearHashIdToNodeMap();
339         for( final Integer id : to_delete ) {
340             phy.deleteSubtree( phy.getNode( id ), true );
341         }
342         phy.clearHashIdToNodeMap();
343         phy.externalNodesHaveChanged();
344     }
345
346     public static void deleteExternalNodesNegativeSelection( final String[] node_names_to_delete, final Phylogeny p )
347             throws IllegalArgumentException {
348         for( final String element : node_names_to_delete ) {
349             if ( ForesterUtil.isEmpty( element ) ) {
350                 continue;
351             }
352             List<PhylogenyNode> nodes = null;
353             nodes = p.getNodes( element );
354             final Iterator<PhylogenyNode> it = nodes.iterator();
355             while ( it.hasNext() ) {
356                 final PhylogenyNode n = it.next();
357                 if ( !n.isExternal() ) {
358                     throw new IllegalArgumentException( "attempt to delete non-external node \"" + element + "\"" );
359                 }
360                 p.deleteSubtree( n, true );
361             }
362         }
363         p.clearHashIdToNodeMap();
364         p.externalNodesHaveChanged();
365     }
366
367     public static void deleteExternalNodesPositiveSelection( final Set<Taxonomy> species_to_keep, final Phylogeny phy ) {
368         //   final Set<Integer> to_delete = new HashSet<Integer>();
369         for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
370             final PhylogenyNode n = it.next();
371             if ( n.getNodeData().isHasTaxonomy() ) {
372                 if ( !species_to_keep.contains( n.getNodeData().getTaxonomy() ) ) {
373                     //to_delete.add( n.getNodeId() );
374                     phy.deleteSubtree( n, true );
375                 }
376             }
377             else {
378                 throw new IllegalArgumentException( "node " + n.getId() + " has no taxonomic data" );
379             }
380         }
381         phy.clearHashIdToNodeMap();
382         phy.externalNodesHaveChanged();
383     }
384
385     public static List<String> deleteExternalNodesPositiveSelection( final String[] node_names_to_keep,
386                                                                      final Phylogeny p ) {
387         final PhylogenyNodeIterator it = p.iteratorExternalForward();
388         final String[] to_delete = new String[ p.getNumberOfExternalNodes() ];
389         int i = 0;
390         Arrays.sort( node_names_to_keep );
391         while ( it.hasNext() ) {
392             final String curent_name = it.next().getName();
393             if ( Arrays.binarySearch( node_names_to_keep, curent_name ) < 0 ) {
394                 to_delete[ i++ ] = curent_name;
395             }
396         }
397         PhylogenyMethods.deleteExternalNodesNegativeSelection( to_delete, p );
398         final List<String> deleted = new ArrayList<String>();
399         for( final String n : to_delete ) {
400             if ( !ForesterUtil.isEmpty( n ) ) {
401                 deleted.add( n );
402             }
403         }
404         return deleted;
405     }
406
407     final public static void deleteInternalNodesWithOnlyOneDescendent( final Phylogeny phy ) {
408         final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
409         for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
410             final PhylogenyNode n = iter.next();
411             if ( !n.isExternal() && ( n.getNumberOfDescendants() == 1 ) ) {
412                 to_delete.add( n );
413             }
414         }
415         for( final PhylogenyNode d : to_delete ) {
416             PhylogenyMethods.removeNode( d, phy );
417         }
418         phy.clearHashIdToNodeMap();
419         phy.externalNodesHaveChanged();
420     }
421
422     final public static void deleteNonOrthologousExternalNodes( final Phylogeny phy, final PhylogenyNode n ) {
423         if ( n.isInternal() ) {
424             throw new IllegalArgumentException( "node is not external" );
425         }
426         final ArrayList<PhylogenyNode> to_delete = new ArrayList<PhylogenyNode>();
427         for( final PhylogenyNodeIterator it = phy.iteratorExternalForward(); it.hasNext(); ) {
428             final PhylogenyNode i = it.next();
429             if ( !PhylogenyMethods.getEventAtLCA( n, i ).isSpeciation() ) {
430                 to_delete.add( i );
431             }
432         }
433         for( final PhylogenyNode d : to_delete ) {
434             phy.deleteSubtree( d, true );
435         }
436         phy.clearHashIdToNodeMap();
437         phy.externalNodesHaveChanged();
438     }
439
440     public static List<PhylogenyNode> getAllDescendants( final PhylogenyNode node ) {
441         final List<PhylogenyNode> descs = new ArrayList<PhylogenyNode>();
442         final Set<Integer> encountered = new HashSet<Integer>();
443         if ( !node.isExternal() ) {
444             final List<PhylogenyNode> exts = node.getAllExternalDescendants();
445             for( PhylogenyNode current : exts ) {
446                 descs.add( current );
447                 while ( current != node ) {
448                     current = current.getParent();
449                     if ( encountered.contains( current.getId() ) ) {
450                         continue;
451                     }
452                     descs.add( current );
453                     encountered.add( current.getId() );
454                 }
455             }
456         }
457         return descs;
458     }
459
460     /**
461      * 
462      * Convenience method
463      * 
464      * @param node
465      * @return
466      */
467     public static Color getBranchColorValue( final PhylogenyNode node ) {
468         if ( node.getBranchData().getBranchColor() == null ) {
469             return null;
470         }
471         return node.getBranchData().getBranchColor().getValue();
472     }
473
474     /**
475      * Convenience method
476      */
477     public static double getBranchWidthValue( final PhylogenyNode node ) {
478         if ( !node.getBranchData().isHasBranchWidth() ) {
479             return BranchWidth.BRANCH_WIDTH_DEFAULT_VALUE;
480         }
481         return node.getBranchData().getBranchWidth().getValue();
482     }
483
484     /**
485      * Convenience method
486      */
487     public static double getConfidenceValue( final PhylogenyNode node ) {
488         if ( !node.getBranchData().isHasConfidences() ) {
489             return Confidence.CONFIDENCE_DEFAULT_VALUE;
490         }
491         return node.getBranchData().getConfidence( 0 ).getValue();
492     }
493
494     /**
495      * Convenience method
496      */
497     public static double[] getConfidenceValuesAsArray( final PhylogenyNode node ) {
498         if ( !node.getBranchData().isHasConfidences() ) {
499             return new double[ 0 ];
500         }
501         final double[] values = new double[ node.getBranchData().getConfidences().size() ];
502         int i = 0;
503         for( final Confidence c : node.getBranchData().getConfidences() ) {
504             values[ i++ ] = c.getValue();
505         }
506         return values;
507     }
508
509     final public static Event getEventAtLCA( final PhylogenyNode n1, final PhylogenyNode n2 ) {
510         return calculateLCA( n1, n2 ).getNodeData().getEvent();
511     }
512
513     /**
514      * Returns taxonomy t if all external descendants have 
515      * the same taxonomy t, null otherwise.
516      * 
517      */
518     public static Taxonomy getExternalDescendantsTaxonomy( final PhylogenyNode node ) {
519         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
520         Taxonomy tax = null;
521         for( final PhylogenyNode n : descs ) {
522             if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
523                 return null;
524             }
525             else if ( tax == null ) {
526                 tax = n.getNodeData().getTaxonomy();
527             }
528             else if ( n.getNodeData().getTaxonomy().isEmpty() || !tax.isEqual( n.getNodeData().getTaxonomy() ) ) {
529                 return null;
530             }
531         }
532         return tax;
533     }
534
535     public static PhylogenyNode getFurthestDescendant( final PhylogenyNode node ) {
536         final List<PhylogenyNode> children = node.getAllExternalDescendants();
537         PhylogenyNode farthest = null;
538         double longest = -Double.MAX_VALUE;
539         for( final PhylogenyNode child : children ) {
540             if ( PhylogenyMethods.getDistance( child, node ) > longest ) {
541                 farthest = child;
542                 longest = PhylogenyMethods.getDistance( child, node );
543             }
544         }
545         return farthest;
546     }
547
548     // public static PhylogenyMethods getInstance() {
549     //     if ( PhylogenyMethods._instance == null ) {
550     //         PhylogenyMethods._instance = new PhylogenyMethods();
551     //    }
552     //    return PhylogenyMethods._instance;
553     //  }
554     /**
555      * Returns the largest confidence value found on phy.
556      */
557     static public double getMaximumConfidenceValue( final Phylogeny phy ) {
558         double max = -Double.MAX_VALUE;
559         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
560             final double s = PhylogenyMethods.getConfidenceValue( iter.next() );
561             if ( ( s != Confidence.CONFIDENCE_DEFAULT_VALUE ) && ( s > max ) ) {
562                 max = s;
563             }
564         }
565         return max;
566     }
567
568     static public int getMinimumDescendentsPerInternalNodes( final Phylogeny phy ) {
569         int min = Integer.MAX_VALUE;
570         int d = 0;
571         PhylogenyNode n;
572         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
573             n = it.next();
574             if ( n.isInternal() ) {
575                 d = n.getNumberOfDescendants();
576                 if ( d < min ) {
577                     min = d;
578                 }
579             }
580         }
581         return min;
582     }
583
584     /**
585      * Convenience method for display purposes.
586      * Not intended for algorithms.
587      */
588     public static String getSpecies( final PhylogenyNode node ) {
589         if ( !node.getNodeData().isHasTaxonomy() ) {
590             return "";
591         }
592         else if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
593             return node.getNodeData().getTaxonomy().getScientificName();
594         }
595         if ( !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
596             return node.getNodeData().getTaxonomy().getTaxonomyCode();
597         }
598         else {
599             return node.getNodeData().getTaxonomy().getCommonName();
600         }
601     }
602
603     /**
604      * Convenience method for display purposes.
605      * Not intended for algorithms.
606      */
607     public static String getTaxonomyIdentifier( final PhylogenyNode node ) {
608         if ( !node.getNodeData().isHasTaxonomy() || ( node.getNodeData().getTaxonomy().getIdentifier() == null ) ) {
609             return "";
610         }
611         return node.getNodeData().getTaxonomy().getIdentifier().getValue();
612     }
613
614     public final static boolean isAllDecendentsAreDuplications( final PhylogenyNode n ) {
615         if ( n.isExternal() ) {
616             return true;
617         }
618         else {
619             if ( n.isDuplication() ) {
620                 for( final PhylogenyNode desc : n.getDescendants() ) {
621                     if ( !isAllDecendentsAreDuplications( desc ) ) {
622                         return false;
623                     }
624                 }
625                 return true;
626             }
627             else {
628                 return false;
629             }
630         }
631     }
632
633     public static boolean isHasExternalDescendant( final PhylogenyNode node ) {
634         for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
635             if ( node.getChildNode( i ).isExternal() ) {
636                 return true;
637             }
638         }
639         return false;
640     }
641
642     /*
643      * This is case insensitive.
644      * 
645      */
646     public synchronized static boolean isTaxonomyHasIdentifierOfGivenProvider( final Taxonomy tax,
647                                                                                final String[] providers ) {
648         if ( ( tax.getIdentifier() != null ) && !ForesterUtil.isEmpty( tax.getIdentifier().getProvider() ) ) {
649             final String my_tax_prov = tax.getIdentifier().getProvider();
650             for( final String provider : providers ) {
651                 if ( provider.equalsIgnoreCase( my_tax_prov ) ) {
652                     return true;
653                 }
654             }
655             return false;
656         }
657         else {
658             return false;
659         }
660     }
661
662     public static void midpointRoot( final Phylogeny phylogeny ) {
663         if ( ( phylogeny.getNumberOfExternalNodes() < 2 ) || ( calculateMaxDistanceToRoot( phylogeny ) <= 0 ) ) {
664             return;
665         }
666         int counter = 0;
667         final int total_nodes = phylogeny.getNodeCount();
668         while ( true ) {
669             if ( ++counter > total_nodes ) {
670                 throw new RuntimeException( "this should not have happened: midpoint rooting does not converge" );
671             }
672             PhylogenyNode a = null;
673             double da = 0;
674             double db = 0;
675             for( int i = 0; i < phylogeny.getRoot().getNumberOfDescendants(); ++i ) {
676                 final PhylogenyNode f = getFurthestDescendant( phylogeny.getRoot().getChildNode( i ) );
677                 final double df = getDistance( f, phylogeny.getRoot() );
678                 if ( df > 0 ) {
679                     if ( df > da ) {
680                         db = da;
681                         da = df;
682                         a = f;
683                     }
684                     else if ( df > db ) {
685                         db = df;
686                     }
687                 }
688             }
689             final double diff = da - db;
690             if ( diff < 0.000001 ) {
691                 break;
692             }
693             double x = da - ( diff / 2.0 );
694             while ( ( x > a.getDistanceToParent() ) && !a.isRoot() ) {
695                 x -= ( a.getDistanceToParent() > 0 ? a.getDistanceToParent() : 0 );
696                 a = a.getParent();
697             }
698             phylogeny.reRoot( a, x );
699         }
700         phylogeny.recalculateNumberOfExternalDescendants( true );
701     }
702
703     public static void midpointRootOLD( final Phylogeny phylogeny ) {
704         //   if ( phylogeny.getNumberOfExternalNodes() < 2 ) {
705         //       return;
706         //   }
707         //    final PhylogenyMethods methods = getInstance();
708         //final double farthest_d = methods.calculateFurthestDistance( phylogeny );
709         // final PhylogenyNode f1 = methods.getFarthestNode1();
710         // final PhylogenyNode f2 = methods.getFarthestNode2();
711         //        if ( farthest_d <= 0.0 ) {
712         //            return;
713         //        }
714         //        double x = farthest_d / 2.0;
715         //        PhylogenyNode n = f1;
716         //        if ( PhylogenyMethods.getDistance( f1, phylogeny.getRoot() ) < PhylogenyMethods.getDistance( f2, phylogeny
717         //                .getRoot() ) ) {
718         //            n = f2;
719         //        }
720         //        while ( ( x > n.getDistanceToParent() ) && !n.isRoot() ) {
721         //            x -= ( n.getDistanceToParent() > 0 ? n.getDistanceToParent() : 0 );
722         //            n = n.getParent();
723         //        }
724         //        phylogeny.reRoot( n, x );
725         //        phylogeny.recalculateNumberOfExternalDescendants( true );
726         //        final PhylogenyNode a = getFurthestDescendant( phylogeny.getRoot().getChildNode1() );
727         //        final PhylogenyNode b = getFurthestDescendant( phylogeny.getRoot().getChildNode2() );
728         //        final double da = getDistance( a, phylogeny.getRoot() );
729         //        final double db = getDistance( b, phylogeny.getRoot() );
730         //        if ( Math.abs( da - db ) > 0.000001 ) {
731         //            throw new FailedConditionCheckException( "this should not have happened: midpoint rooting failed:  da="
732         //                    + da + ",  db=" + db + ",  diff=" + Math.abs( da - db ) );
733         //        }
734     }
735
736     public static void normalizeBootstrapValues( final Phylogeny phylogeny,
737                                                  final double max_bootstrap_value,
738                                                  final double max_normalized_value ) {
739         for( final PhylogenyNodeIterator iter = phylogeny.iteratorPreorder(); iter.hasNext(); ) {
740             final PhylogenyNode node = iter.next();
741             if ( node.isInternal() ) {
742                 final double confidence = getConfidenceValue( node );
743                 if ( confidence != Confidence.CONFIDENCE_DEFAULT_VALUE ) {
744                     if ( confidence >= max_bootstrap_value ) {
745                         setBootstrapConfidence( node, max_normalized_value );
746                     }
747                     else {
748                         setBootstrapConfidence( node, ( confidence * max_normalized_value ) / max_bootstrap_value );
749                     }
750                 }
751             }
752         }
753     }
754
755     public static List<PhylogenyNode> obtainAllNodesAsList( final Phylogeny phy ) {
756         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
757         if ( phy.isEmpty() ) {
758             return nodes;
759         }
760         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
761             nodes.add( iter.next() );
762         }
763         return nodes;
764     }
765
766     /**
767      * Returns the set of distinct taxonomies of
768      * all external nodes of node.
769      * If at least one the external nodes has no taxonomy,
770      * null is returned.
771      * 
772      */
773     public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
774         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
775         final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
776         for( final PhylogenyNode n : descs ) {
777             if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
778                 return null;
779             }
780             tax_set.add( n.getNodeData().getTaxonomy() );
781         }
782         return tax_set;
783     }
784
785     /**
786      * Returns a map of distinct taxonomies of
787      * all external nodes of node.
788      * If at least one of the external nodes has no taxonomy,
789      * null is returned.
790      * 
791      */
792     public static SortedMap<Taxonomy, Integer> obtainDistinctTaxonomyCounts( final PhylogenyNode node ) {
793         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
794         final SortedMap<Taxonomy, Integer> tax_map = new TreeMap<Taxonomy, Integer>();
795         for( final PhylogenyNode n : descs ) {
796             if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
797                 return null;
798             }
799             final Taxonomy t = n.getNodeData().getTaxonomy();
800             if ( tax_map.containsKey( t ) ) {
801                 tax_map.put( t, tax_map.get( t ) + 1 );
802             }
803             else {
804                 tax_map.put( t, 1 );
805             }
806         }
807         return tax_map;
808     }
809
810     /**
811      * Arranges the order of childern for each node of this Phylogeny in such a
812      * way that either the branch with more children is on top (right) or on
813      * bottom (left), dependent on the value of boolean order.
814      * 
815      * @param order
816      *            decides in which direction to order
817      * @param pri 
818      */
819     public static void orderAppearance( final PhylogenyNode n,
820                                         final boolean order,
821                                         final boolean order_ext_alphabetically,
822                                         final DESCENDANT_SORT_PRIORITY pri ) {
823         if ( n.isExternal() ) {
824             return;
825         }
826         else {
827             PhylogenyNode temp = null;
828             if ( ( n.getNumberOfDescendants() == 2 )
829                     && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
830                     && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
831                 temp = n.getChildNode1();
832                 n.setChild1( n.getChildNode2() );
833                 n.setChild2( temp );
834             }
835             else if ( order_ext_alphabetically ) {
836                 boolean all_ext = true;
837                 for( final PhylogenyNode i : n.getDescendants() ) {
838                     if ( !i.isExternal() ) {
839                         all_ext = false;
840                         break;
841                     }
842                 }
843                 if ( all_ext ) {
844                     PhylogenyMethods.sortNodeDescendents( n, pri );
845                 }
846             }
847             for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
848                 orderAppearance( n.getChildNode( i ), order, order_ext_alphabetically, pri );
849             }
850         }
851     }
852
853     public static void postorderBranchColorAveragingExternalNodeBased( final Phylogeny p ) {
854         for( final PhylogenyNodeIterator iter = p.iteratorPostorder(); iter.hasNext(); ) {
855             final PhylogenyNode node = iter.next();
856             double red = 0.0;
857             double green = 0.0;
858             double blue = 0.0;
859             int n = 0;
860             if ( node.isInternal() ) {
861                 //for( final PhylogenyNodeIterator iterator = node.iterateChildNodesForward(); iterator.hasNext(); ) {
862                 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
863                     final PhylogenyNode child_node = node.getChildNode( i );
864                     final Color child_color = getBranchColorValue( child_node );
865                     if ( child_color != null ) {
866                         ++n;
867                         red += child_color.getRed();
868                         green += child_color.getGreen();
869                         blue += child_color.getBlue();
870                     }
871                 }
872                 setBranchColorValue( node,
873                                      new Color( ForesterUtil.roundToInt( red / n ),
874                                                 ForesterUtil.roundToInt( green / n ),
875                                                 ForesterUtil.roundToInt( blue / n ) ) );
876             }
877         }
878     }
879
880     public static final void preOrderReId( final Phylogeny phy ) {
881         if ( phy.isEmpty() ) {
882             return;
883         }
884         phy.setIdToNodeMap( null );
885         int i = PhylogenyNode.getNodeCount();
886         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
887             it.next().setId( i++ );
888         }
889         PhylogenyNode.setNodeCount( i );
890     }
891
892     public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final File file ) throws IOException {
893         final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
894         final Phylogeny[] trees = factory.create( file, parser );
895         if ( ( trees == null ) || ( trees.length == 0 ) ) {
896             throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
897         }
898         return trees;
899     }
900
901     public final static Phylogeny[] readPhylogenies( final PhylogenyParser parser, final List<File> files )
902             throws IOException {
903         final List<Phylogeny> tree_list = new ArrayList<Phylogeny>();
904         for( final File file : files ) {
905             final PhylogenyFactory factory = ParserBasedPhylogenyFactory.getInstance();
906             final Phylogeny[] trees = factory.create( file, parser );
907             if ( ( trees == null ) || ( trees.length == 0 ) ) {
908                 throw new PhylogenyParserException( "Unable to parse phylogeny from file: " + file );
909             }
910             tree_list.addAll( Arrays.asList( trees ) );
911         }
912         return tree_list.toArray( new Phylogeny[ tree_list.size() ] );
913     }
914
915     public static void removeNode( final PhylogenyNode remove_me, final Phylogeny phylogeny ) {
916         if ( remove_me.isRoot() ) {
917             throw new IllegalArgumentException( "ill advised attempt to remove root node" );
918         }
919         if ( remove_me.isExternal() ) {
920             phylogeny.deleteSubtree( remove_me, false );
921             phylogeny.clearHashIdToNodeMap();
922             phylogeny.externalNodesHaveChanged();
923         }
924         else {
925             final PhylogenyNode parent = remove_me.getParent();
926             final List<PhylogenyNode> descs = remove_me.getDescendants();
927             parent.removeChildNode( remove_me );
928             for( final PhylogenyNode desc : descs ) {
929                 parent.addAsChild( desc );
930                 desc.setDistanceToParent( addPhylogenyDistances( remove_me.getDistanceToParent(),
931                                                                  desc.getDistanceToParent() ) );
932             }
933             remove_me.setParent( null );
934             phylogeny.clearHashIdToNodeMap();
935             phylogeny.externalNodesHaveChanged();
936         }
937     }
938
939     public static List<PhylogenyNode> searchData( final String query,
940                                                   final Phylogeny phy,
941                                                   final boolean case_sensitive,
942                                                   final boolean partial,
943                                                   final boolean search_domains ) {
944         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
945         if ( phy.isEmpty() || ( query == null ) ) {
946             return nodes;
947         }
948         if ( ForesterUtil.isEmpty( query ) ) {
949             return nodes;
950         }
951         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
952             final PhylogenyNode node = iter.next();
953             boolean match = false;
954             if ( match( node.getName(), query, case_sensitive, partial ) ) {
955                 match = true;
956             }
957             else if ( node.getNodeData().isHasTaxonomy()
958                     && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
959                 match = true;
960             }
961             else if ( node.getNodeData().isHasTaxonomy()
962                     && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
963                 match = true;
964             }
965             else if ( node.getNodeData().isHasTaxonomy()
966                     && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
967                 match = true;
968             }
969             else if ( node.getNodeData().isHasTaxonomy()
970                     && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
971                     && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
972                               query,
973                               case_sensitive,
974                               partial ) ) {
975                 match = true;
976             }
977             else if ( node.getNodeData().isHasTaxonomy() && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
978                 final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
979                 I: for( final String syn : syns ) {
980                     if ( match( syn, query, case_sensitive, partial ) ) {
981                         match = true;
982                         break I;
983                     }
984                 }
985             }
986             if ( !match && node.getNodeData().isHasSequence()
987                     && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
988                 match = true;
989             }
990             if ( !match && node.getNodeData().isHasSequence()
991                     && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
992                 match = true;
993             }
994             if ( !match
995                     && node.getNodeData().isHasSequence()
996                     && ( node.getNodeData().getSequence().getAccession() != null )
997                     && match( node.getNodeData().getSequence().getAccession().getValue(),
998                               query,
999                               case_sensitive,
1000                               partial ) ) {
1001                 match = true;
1002             }
1003             if ( search_domains && !match && node.getNodeData().isHasSequence()
1004                     && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1005                 final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1006                 I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1007                     if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1008                         match = true;
1009                         break I;
1010                     }
1011                 }
1012             }
1013             if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1014                 Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1015                 I: while ( it.hasNext() ) {
1016                     if ( match( it.next(), query, case_sensitive, partial ) ) {
1017                         match = true;
1018                         break I;
1019                     }
1020                 }
1021                 it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1022                 I: while ( it.hasNext() ) {
1023                     if ( match( it.next(), query, case_sensitive, partial ) ) {
1024                         match = true;
1025                         break I;
1026                     }
1027                 }
1028             }
1029             if ( match ) {
1030                 nodes.add( node );
1031             }
1032         }
1033         return nodes;
1034     }
1035
1036     public static List<PhylogenyNode> searchDataLogicalAnd( final String[] queries,
1037                                                             final Phylogeny phy,
1038                                                             final boolean case_sensitive,
1039                                                             final boolean partial,
1040                                                             final boolean search_domains ) {
1041         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
1042         if ( phy.isEmpty() || ( queries == null ) || ( queries.length < 1 ) ) {
1043             return nodes;
1044         }
1045         for( final PhylogenyNodeIterator iter = phy.iteratorPreorder(); iter.hasNext(); ) {
1046             final PhylogenyNode node = iter.next();
1047             boolean all_matched = true;
1048             for( final String query : queries ) {
1049                 boolean match = false;
1050                 if ( ForesterUtil.isEmpty( query ) ) {
1051                     continue;
1052                 }
1053                 if ( match( node.getName(), query, case_sensitive, partial ) ) {
1054                     match = true;
1055                 }
1056                 else if ( node.getNodeData().isHasTaxonomy()
1057                         && match( node.getNodeData().getTaxonomy().getTaxonomyCode(), query, case_sensitive, partial ) ) {
1058                     match = true;
1059                 }
1060                 else if ( node.getNodeData().isHasTaxonomy()
1061                         && match( node.getNodeData().getTaxonomy().getCommonName(), query, case_sensitive, partial ) ) {
1062                     match = true;
1063                 }
1064                 else if ( node.getNodeData().isHasTaxonomy()
1065                         && match( node.getNodeData().getTaxonomy().getScientificName(), query, case_sensitive, partial ) ) {
1066                     match = true;
1067                 }
1068                 else if ( node.getNodeData().isHasTaxonomy()
1069                         && ( node.getNodeData().getTaxonomy().getIdentifier() != null )
1070                         && match( node.getNodeData().getTaxonomy().getIdentifier().getValue(),
1071                                   query,
1072                                   case_sensitive,
1073                                   partial ) ) {
1074                     match = true;
1075                 }
1076                 else if ( node.getNodeData().isHasTaxonomy()
1077                         && !node.getNodeData().getTaxonomy().getSynonyms().isEmpty() ) {
1078                     final List<String> syns = node.getNodeData().getTaxonomy().getSynonyms();
1079                     I: for( final String syn : syns ) {
1080                         if ( match( syn, query, case_sensitive, partial ) ) {
1081                             match = true;
1082                             break I;
1083                         }
1084                     }
1085                 }
1086                 if ( !match && node.getNodeData().isHasSequence()
1087                         && match( node.getNodeData().getSequence().getName(), query, case_sensitive, partial ) ) {
1088                     match = true;
1089                 }
1090                 if ( !match && node.getNodeData().isHasSequence()
1091                         && match( node.getNodeData().getSequence().getSymbol(), query, case_sensitive, partial ) ) {
1092                     match = true;
1093                 }
1094                 if ( !match
1095                         && node.getNodeData().isHasSequence()
1096                         && ( node.getNodeData().getSequence().getAccession() != null )
1097                         && match( node.getNodeData().getSequence().getAccession().getValue(),
1098                                   query,
1099                                   case_sensitive,
1100                                   partial ) ) {
1101                     match = true;
1102                 }
1103                 if ( search_domains && !match && node.getNodeData().isHasSequence()
1104                         && ( node.getNodeData().getSequence().getDomainArchitecture() != null ) ) {
1105                     final DomainArchitecture da = node.getNodeData().getSequence().getDomainArchitecture();
1106                     I: for( int i = 0; i < da.getNumberOfDomains(); ++i ) {
1107                         if ( match( da.getDomain( i ).getName(), query, case_sensitive, partial ) ) {
1108                             match = true;
1109                             break I;
1110                         }
1111                     }
1112                 }
1113                 if ( !match && ( node.getNodeData().getBinaryCharacters() != null ) ) {
1114                     Iterator<String> it = node.getNodeData().getBinaryCharacters().getPresentCharacters().iterator();
1115                     I: while ( it.hasNext() ) {
1116                         if ( match( it.next(), query, case_sensitive, partial ) ) {
1117                             match = true;
1118                             break I;
1119                         }
1120                     }
1121                     it = node.getNodeData().getBinaryCharacters().getGainedCharacters().iterator();
1122                     I: while ( it.hasNext() ) {
1123                         if ( match( it.next(), query, case_sensitive, partial ) ) {
1124                             match = true;
1125                             break I;
1126                         }
1127                     }
1128                 }
1129                 if ( !match ) {
1130                     all_matched = false;
1131                     break;
1132                 }
1133             }
1134             if ( all_matched ) {
1135                 nodes.add( node );
1136             }
1137         }
1138         return nodes;
1139     }
1140
1141     /**
1142      * Convenience method.
1143      * Sets value for the first confidence value (created if not present, values overwritten otherwise). 
1144      */
1145     public static void setBootstrapConfidence( final PhylogenyNode node, final double bootstrap_confidence_value ) {
1146         setConfidence( node, bootstrap_confidence_value, "bootstrap" );
1147     }
1148
1149     public static void setBranchColorValue( final PhylogenyNode node, final Color color ) {
1150         if ( node.getBranchData().getBranchColor() == null ) {
1151             node.getBranchData().setBranchColor( new BranchColor() );
1152         }
1153         node.getBranchData().getBranchColor().setValue( color );
1154     }
1155
1156     /**
1157      * Convenience method
1158      */
1159     public static void setBranchWidthValue( final PhylogenyNode node, final double branch_width_value ) {
1160         node.getBranchData().setBranchWidth( new BranchWidth( branch_width_value ) );
1161     }
1162
1163     /**
1164      * Convenience method.
1165      * Sets value for the first confidence value (created if not present, values overwritten otherwise). 
1166      */
1167     public static void setConfidence( final PhylogenyNode node, final double confidence_value ) {
1168         setConfidence( node, confidence_value, "" );
1169     }
1170
1171     /**
1172      * Convenience method.
1173      * Sets value for the first confidence value (created if not present, values overwritten otherwise). 
1174      */
1175     public static void setConfidence( final PhylogenyNode node, final double confidence_value, final String type ) {
1176         Confidence c = null;
1177         if ( node.getBranchData().getNumberOfConfidences() > 0 ) {
1178             c = node.getBranchData().getConfidence( 0 );
1179         }
1180         else {
1181             c = new Confidence();
1182             node.getBranchData().addConfidence( c );
1183         }
1184         c.setType( type );
1185         c.setValue( confidence_value );
1186     }
1187
1188     public static void setScientificName( final PhylogenyNode node, final String scientific_name ) {
1189         if ( !node.getNodeData().isHasTaxonomy() ) {
1190             node.getNodeData().setTaxonomy( new Taxonomy() );
1191         }
1192         node.getNodeData().getTaxonomy().setScientificName( scientific_name );
1193     }
1194
1195     /**
1196      * Convenience method to set the taxonomy code of a phylogeny node.
1197      * 
1198      * 
1199      * @param node
1200      * @param taxonomy_code
1201      * @throws PhyloXmlDataFormatException 
1202      */
1203     public static void setTaxonomyCode( final PhylogenyNode node, final String taxonomy_code )
1204             throws PhyloXmlDataFormatException {
1205         if ( !node.getNodeData().isHasTaxonomy() ) {
1206             node.getNodeData().setTaxonomy( new Taxonomy() );
1207         }
1208         node.getNodeData().getTaxonomy().setTaxonomyCode( taxonomy_code );
1209     }
1210
1211     final static public void sortNodeDescendents( final PhylogenyNode node, final DESCENDANT_SORT_PRIORITY pri ) {
1212         class PhylogenyNodeSortTaxonomyPriority implements Comparator<PhylogenyNode> {
1213
1214             @Override
1215             public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1216                 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1217                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1218                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1219                         return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1220                                 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1221                     }
1222                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1223                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1224                         return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1225                                 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1226                     }
1227                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1228                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1229                         return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1230                                 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1231                     }
1232                 }
1233                 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1234                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1235                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1236                         return n1.getNodeData().getSequence().getName().toLowerCase()
1237                                 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1238                     }
1239                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1240                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1241                         return n1.getNodeData().getSequence().getSymbol()
1242                                 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1243                     }
1244                     if ( ( n1.getNodeData().getSequence().getAccession() != null )
1245                             && ( n2.getNodeData().getSequence().getAccession() != null )
1246                             && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1247                             && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1248                         return n1.getNodeData().getSequence().getAccession().getValue()
1249                                 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1250                     }
1251                 }
1252                 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1253                     return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1254                 }
1255                 return 0;
1256             }
1257         }
1258         class PhylogenyNodeSortSequencePriority implements Comparator<PhylogenyNode> {
1259
1260             @Override
1261             public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
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() );
1267                     }
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() );
1272                     }
1273                     if ( ( n1.getNodeData().getSequence().getAccession() != null )
1274                             && ( n2.getNodeData().getSequence().getAccession() != null )
1275                             && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1276                             && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1277                         return n1.getNodeData().getSequence().getAccession().getValue()
1278                                 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1279                     }
1280                 }
1281                 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1282                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1283                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1284                         return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1285                                 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1286                     }
1287                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1288                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1289                         return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1290                                 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1291                     }
1292                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1293                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1294                         return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1295                                 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1296                     }
1297                 }
1298                 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1299                     return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1300                 }
1301                 return 0;
1302             }
1303         }
1304         class PhylogenyNodeSortNodeNamePriority implements Comparator<PhylogenyNode> {
1305
1306             @Override
1307             public int compare( final PhylogenyNode n1, final PhylogenyNode n2 ) {
1308                 if ( ( !ForesterUtil.isEmpty( n1.getName() ) ) && ( !ForesterUtil.isEmpty( n2.getName() ) ) ) {
1309                     return n1.getName().toLowerCase().compareTo( n2.getName().toLowerCase() );
1310                 }
1311                 if ( n1.getNodeData().isHasTaxonomy() && n2.getNodeData().isHasTaxonomy() ) {
1312                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getScientificName() ) )
1313                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getScientificName() ) ) ) {
1314                         return n1.getNodeData().getTaxonomy().getScientificName().toLowerCase()
1315                                 .compareTo( n2.getNodeData().getTaxonomy().getScientificName().toLowerCase() );
1316                     }
1317                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getTaxonomyCode() ) )
1318                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1319                         return n1.getNodeData().getTaxonomy().getTaxonomyCode()
1320                                 .compareTo( n2.getNodeData().getTaxonomy().getTaxonomyCode() );
1321                     }
1322                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getTaxonomy().getCommonName() ) )
1323                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getTaxonomy().getCommonName() ) ) ) {
1324                         return n1.getNodeData().getTaxonomy().getCommonName().toLowerCase()
1325                                 .compareTo( n2.getNodeData().getTaxonomy().getCommonName().toLowerCase() );
1326                     }
1327                 }
1328                 if ( n1.getNodeData().isHasSequence() && n2.getNodeData().isHasSequence() ) {
1329                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getName() ) )
1330                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getName() ) ) ) {
1331                         return n1.getNodeData().getSequence().getName().toLowerCase()
1332                                 .compareTo( n2.getNodeData().getSequence().getName().toLowerCase() );
1333                     }
1334                     if ( ( !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getSymbol() ) )
1335                             && ( !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getSymbol() ) ) ) {
1336                         return n1.getNodeData().getSequence().getSymbol()
1337                                 .compareTo( n2.getNodeData().getSequence().getSymbol() );
1338                     }
1339                     if ( ( n1.getNodeData().getSequence().getAccession() != null )
1340                             && ( n2.getNodeData().getSequence().getAccession() != null )
1341                             && !ForesterUtil.isEmpty( n1.getNodeData().getSequence().getAccession().getValue() )
1342                             && !ForesterUtil.isEmpty( n2.getNodeData().getSequence().getAccession().getValue() ) ) {
1343                         return n1.getNodeData().getSequence().getAccession().getValue()
1344                                 .compareTo( n2.getNodeData().getSequence().getAccession().getValue() );
1345                     }
1346                 }
1347                 return 0;
1348             }
1349         }
1350         Comparator<PhylogenyNode> c;
1351         switch ( pri ) {
1352             case SEQUENCE:
1353                 c = new PhylogenyNodeSortSequencePriority();
1354                 break;
1355             case NODE_NAME:
1356                 c = new PhylogenyNodeSortNodeNamePriority();
1357                 break;
1358             default:
1359                 c = new PhylogenyNodeSortTaxonomyPriority();
1360         }
1361         final List<PhylogenyNode> descs = node.getDescendants();
1362         Collections.sort( descs, c );
1363         int i = 0;
1364         for( final PhylogenyNode desc : descs ) {
1365             node.setChildNode( i++, desc );
1366         }
1367     }
1368
1369     /**
1370      * Removes from Phylogeny to_be_stripped all external Nodes which are
1371      * associated with a species NOT found in Phylogeny reference.
1372      * 
1373      * @param reference
1374      *            a reference Phylogeny
1375      * @param to_be_stripped
1376      *            Phylogeny to be stripped
1377      * @return nodes removed from to_be_stripped
1378      */
1379     public static List<PhylogenyNode> taxonomyBasedDeletionOfExternalNodes( final Phylogeny reference,
1380                                                                             final Phylogeny to_be_stripped ) {
1381         final Set<String> ref_ext_taxo = new HashSet<String>();
1382         for( final PhylogenyNodeIterator it = reference.iteratorExternalForward(); it.hasNext(); ) {
1383             final PhylogenyNode n = it.next();
1384             if ( !n.getNodeData().isHasTaxonomy() ) {
1385                 throw new IllegalArgumentException( "no taxonomic data in node: " + n );
1386             }
1387             //  ref_ext_taxo.add( getSpecies( n ) );
1388             if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
1389                 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getScientificName() );
1390             }
1391             if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1392                 ref_ext_taxo.add( n.getNodeData().getTaxonomy().getTaxonomyCode() );
1393             }
1394         }
1395         final ArrayList<PhylogenyNode> nodes_to_delete = new ArrayList<PhylogenyNode>();
1396         for( final PhylogenyNodeIterator it = to_be_stripped.iteratorExternalForward(); it.hasNext(); ) {
1397             final PhylogenyNode n = it.next();
1398             if ( !n.getNodeData().isHasTaxonomy() ) {
1399                 nodes_to_delete.add( n );
1400             }
1401             else if ( !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getScientificName() ) )
1402                     && !( ref_ext_taxo.contains( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
1403                 nodes_to_delete.add( n );
1404             }
1405         }
1406         for( final PhylogenyNode n : nodes_to_delete ) {
1407             to_be_stripped.deleteSubtree( n, true );
1408         }
1409         to_be_stripped.clearHashIdToNodeMap();
1410         to_be_stripped.externalNodesHaveChanged();
1411         return nodes_to_delete;
1412     }
1413
1414     final static public void transferInternalNamesToBootstrapSupport( final Phylogeny phy ) {
1415         final PhylogenyNodeIterator it = phy.iteratorPostorder();
1416         while ( it.hasNext() ) {
1417             final PhylogenyNode n = it.next();
1418             if ( !n.isExternal() && !ForesterUtil.isEmpty( n.getName() ) ) {
1419                 double value = -1;
1420                 try {
1421                     value = Double.parseDouble( n.getName() );
1422                 }
1423                 catch ( final NumberFormatException e ) {
1424                     throw new IllegalArgumentException( "failed to parse number from [" + n.getName() + "]: "
1425                             + e.getLocalizedMessage() );
1426                 }
1427                 if ( value >= 0.0 ) {
1428                     n.getBranchData().addConfidence( new Confidence( value, "bootstrap" ) );
1429                     n.setName( "" );
1430                 }
1431             }
1432         }
1433     }
1434
1435     final static public void transferInternalNodeNamesToConfidence( final Phylogeny phy ) {
1436         final PhylogenyNodeIterator it = phy.iteratorPostorder();
1437         while ( it.hasNext() ) {
1438             final PhylogenyNode n = it.next();
1439             if ( !n.isExternal() && !n.getBranchData().isHasConfidences() ) {
1440                 if ( !ForesterUtil.isEmpty( n.getName() ) ) {
1441                     double d = -1.0;
1442                     try {
1443                         d = Double.parseDouble( n.getName() );
1444                     }
1445                     catch ( final Exception e ) {
1446                         d = -1.0;
1447                     }
1448                     if ( d >= 0.0 ) {
1449                         n.getBranchData().addConfidence( new Confidence( d, "" ) );
1450                         n.setName( "" );
1451                     }
1452                 }
1453             }
1454         }
1455     }
1456
1457     final static public void transferNodeNameToField( final Phylogeny phy,
1458                                                       final PhylogenyNodeField field,
1459                                                       final boolean external_only ) throws PhyloXmlDataFormatException {
1460         final PhylogenyNodeIterator it = phy.iteratorPostorder();
1461         while ( it.hasNext() ) {
1462             final PhylogenyNode n = it.next();
1463             if ( external_only && n.isInternal() ) {
1464                 continue;
1465             }
1466             final String name = n.getName().trim();
1467             if ( !ForesterUtil.isEmpty( name ) ) {
1468                 switch ( field ) {
1469                     case TAXONOMY_CODE:
1470                         n.setName( "" );
1471                         setTaxonomyCode( n, name );
1472                         break;
1473                     case TAXONOMY_SCIENTIFIC_NAME:
1474                         n.setName( "" );
1475                         if ( !n.getNodeData().isHasTaxonomy() ) {
1476                             n.getNodeData().setTaxonomy( new Taxonomy() );
1477                         }
1478                         n.getNodeData().getTaxonomy().setScientificName( name );
1479                         break;
1480                     case TAXONOMY_COMMON_NAME:
1481                         n.setName( "" );
1482                         if ( !n.getNodeData().isHasTaxonomy() ) {
1483                             n.getNodeData().setTaxonomy( new Taxonomy() );
1484                         }
1485                         n.getNodeData().getTaxonomy().setCommonName( name );
1486                         break;
1487                     case SEQUENCE_SYMBOL:
1488                         n.setName( "" );
1489                         if ( !n.getNodeData().isHasSequence() ) {
1490                             n.getNodeData().setSequence( new Sequence() );
1491                         }
1492                         n.getNodeData().getSequence().setSymbol( name );
1493                         break;
1494                     case SEQUENCE_NAME:
1495                         n.setName( "" );
1496                         if ( !n.getNodeData().isHasSequence() ) {
1497                             n.getNodeData().setSequence( new Sequence() );
1498                         }
1499                         n.getNodeData().getSequence().setName( name );
1500                         break;
1501                     case TAXONOMY_ID_UNIPROT_1: {
1502                         if ( !n.getNodeData().isHasTaxonomy() ) {
1503                             n.getNodeData().setTaxonomy( new Taxonomy() );
1504                         }
1505                         String id = name;
1506                         final int i = name.indexOf( '_' );
1507                         if ( i > 0 ) {
1508                             id = name.substring( 0, i );
1509                         }
1510                         else {
1511                             n.setName( "" );
1512                         }
1513                         n.getNodeData().getTaxonomy()
1514                                 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1515                         break;
1516                     }
1517                     case TAXONOMY_ID_UNIPROT_2: {
1518                         if ( !n.getNodeData().isHasTaxonomy() ) {
1519                             n.getNodeData().setTaxonomy( new Taxonomy() );
1520                         }
1521                         String id = name;
1522                         final int i = name.indexOf( '_' );
1523                         if ( i > 0 ) {
1524                             id = name.substring( i + 1, name.length() );
1525                         }
1526                         else {
1527                             n.setName( "" );
1528                         }
1529                         n.getNodeData().getTaxonomy()
1530                                 .setIdentifier( new Identifier( id, PhyloXmlUtil.UNIPROT_TAX_PROVIDER ) );
1531                         break;
1532                     }
1533                     case TAXONOMY_ID: {
1534                         if ( !n.getNodeData().isHasTaxonomy() ) {
1535                             n.getNodeData().setTaxonomy( new Taxonomy() );
1536                         }
1537                         n.getNodeData().getTaxonomy().setIdentifier( new Identifier( name ) );
1538                         break;
1539                     }
1540                 }
1541             }
1542         }
1543     }
1544
1545     static double addPhylogenyDistances( final double a, final double b ) {
1546         if ( ( a >= 0.0 ) && ( b >= 0.0 ) ) {
1547             return a + b;
1548         }
1549         else if ( a >= 0.0 ) {
1550             return a;
1551         }
1552         else if ( b >= 0.0 ) {
1553             return b;
1554         }
1555         return PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
1556     }
1557
1558     /**
1559      * Deep copies the phylogeny originating from this node.
1560      */
1561     static PhylogenyNode copySubTree( final PhylogenyNode source ) {
1562         if ( source == null ) {
1563             return null;
1564         }
1565         else {
1566             final PhylogenyNode newnode = source.copyNodeData();
1567             if ( !source.isExternal() ) {
1568                 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1569                     newnode.setChildNode( i, PhylogenyMethods.copySubTree( source.getChildNode( i ) ) );
1570                 }
1571             }
1572             return newnode;
1573         }
1574     }
1575
1576     /**
1577      * Shallow copies the phylogeny originating from this node.
1578      */
1579     static PhylogenyNode copySubTreeShallow( final PhylogenyNode source ) {
1580         if ( source == null ) {
1581             return null;
1582         }
1583         else {
1584             final PhylogenyNode newnode = source.copyNodeDataShallow();
1585             if ( !source.isExternal() ) {
1586                 for( int i = 0; i < source.getNumberOfDescendants(); ++i ) {
1587                     newnode.setChildNode( i, PhylogenyMethods.copySubTreeShallow( source.getChildNode( i ) ) );
1588                 }
1589             }
1590             return newnode;
1591         }
1592     }
1593
1594     /**
1595      * Calculates the distance between PhylogenyNodes n1 and n2.
1596      * PRECONDITION: n1 is a descendant of n2.
1597      * 
1598      * @param n1
1599      *            a descendant of n2
1600      * @param n2
1601      * @return distance between n1 and n2
1602      */
1603     private static double getDistance( PhylogenyNode n1, final PhylogenyNode n2 ) {
1604         double d = 0.0;
1605         while ( n1 != n2 ) {
1606             if ( n1.getDistanceToParent() > 0.0 ) {
1607                 d += n1.getDistanceToParent();
1608             }
1609             n1 = n1.getParent();
1610         }
1611         return d;
1612     }
1613
1614     private static boolean match( final String s,
1615                                   final String query,
1616                                   final boolean case_sensitive,
1617                                   final boolean partial ) {
1618         if ( ForesterUtil.isEmpty( s ) || ForesterUtil.isEmpty( query ) ) {
1619             return false;
1620         }
1621         String my_s = s.trim();
1622         String my_query = query.trim();
1623         if ( !case_sensitive ) {
1624             my_s = my_s.toLowerCase();
1625             my_query = my_query.toLowerCase();
1626         }
1627         if ( partial ) {
1628             return my_s.indexOf( my_query ) >= 0;
1629         }
1630         else {
1631             return my_s.equals( my_query );
1632         }
1633     }
1634
1635     public static enum DESCENDANT_SORT_PRIORITY {
1636         TAXONOMY, SEQUENCE, NODE_NAME;
1637     }
1638
1639     public static enum PhylogenyNodeField {
1640         CLADE_NAME,
1641         TAXONOMY_CODE,
1642         TAXONOMY_SCIENTIFIC_NAME,
1643         TAXONOMY_COMMON_NAME,
1644         SEQUENCE_SYMBOL,
1645         SEQUENCE_NAME,
1646         TAXONOMY_ID_UNIPROT_1,
1647         TAXONOMY_ID_UNIPROT_2,
1648         TAXONOMY_ID;
1649     }
1650 }