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