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