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