in progress...
[jalview.git] / forester / java / src / org / forester / phylogeny / Phylogeny.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 // Copyright (C) 2000-2001 Washington University School of Medicine
8 // and Howard Hughes Medical Institute
9 // All rights reserved
10 //
11 // This library is free software; you can redistribute it and/or
12 // modify it under the terms of the GNU Lesser General Public
13 // License as published by the Free Software Foundation; either
14 // version 2.1 of the License, or (at your option) any later version.
15 //
16 // This library is distributed in the hope that it will be useful,
17 // but WITHOUT ANY WARRANTY; without even the implied warranty of
18 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 // Lesser General Public License for more details.
20 //
21 // You should have received a copy of the GNU Lesser General Public
22 // License along with this library; if not, write to the Free Software
23 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 //
25 // Contact: phylosoft @ gmail . com
26 // WWW: www.phylosoft.org/forester
27
28 package org.forester.phylogeny;
29
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
37 import java.util.Map;
38 import java.util.NoSuchElementException;
39 import java.util.Vector;
40
41 import org.forester.io.writers.PhylogenyWriter;
42 import org.forester.phylogeny.data.BranchData;
43 import org.forester.phylogeny.data.Confidence;
44 import org.forester.phylogeny.data.Identifier;
45 import org.forester.phylogeny.data.Sequence;
46 import org.forester.phylogeny.data.SequenceRelation;
47 import org.forester.phylogeny.data.SequenceRelation.SEQUENCE_RELATION_TYPE;
48 import org.forester.phylogeny.iterators.ExternalForwardIterator;
49 import org.forester.phylogeny.iterators.LevelOrderTreeIterator;
50 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
51 import org.forester.phylogeny.iterators.PostorderTreeIterator;
52 import org.forester.phylogeny.iterators.PreorderTreeIterator;
53 import org.forester.util.FailedConditionCheckException;
54 import org.forester.util.ForesterUtil;
55
56 public class Phylogeny {
57
58     public final static boolean                                 ALLOW_MULTIPLE_PARENTS_DEFAULT = false;
59     private PhylogenyNode                                       _root;
60     private boolean                                             _rooted;
61     private boolean                                             _allow_multiple_parents;
62     private String                                              _name;
63     private String                                              _type;
64     private String                                              _description;
65     private String                                              _distance_unit;
66     private Confidence                                          _confidence;
67     private Identifier                                          _identifier;
68     private boolean                                             _rerootable;
69     private HashMap<Integer, PhylogenyNode>                     _idhash;
70     private List<PhylogenyNode>                                 _external_nodes_set;
71     private Collection<Sequence>                                _sequenceRelationQueries;
72     private Collection<SequenceRelation.SEQUENCE_RELATION_TYPE> _relevant_sequence_relation_types;
73
74     /**
75      * Default Phylogeny constructor. Constructs an empty Phylogeny.
76      */
77     public Phylogeny() {
78         init();
79     }
80
81     /**
82      * Adds this Phylogeny to the list of child nodes of PhylogenyNode parent
83      * and sets the parent of this to parent.
84      * 
85      * @param n
86      *            the PhylogenyNode to add
87      */
88     public void addAsChild( final PhylogenyNode parent ) {
89         if ( isEmpty() ) {
90             throw new IllegalArgumentException( "Attempt to add an empty tree." );
91         }
92         if ( !isRooted() ) {
93             throw new IllegalArgumentException( "Attempt to add an unrooted tree." );
94         }
95         parent.addAsChild( getRoot() );
96         externalNodesHaveChanged();
97     }
98
99     public void addAsSibling( final PhylogenyNode sibling ) {
100         if ( isEmpty() ) {
101             throw new IllegalArgumentException( "Attempt to add an empty tree." );
102         }
103         if ( !isRooted() ) {
104             throw new IllegalArgumentException( "Attempt to add an unrooted tree." );
105         }
106         final int sibling_index = sibling.getChildNodeIndex();
107         final PhylogenyNode new_node = new PhylogenyNode();
108         final PhylogenyNode sibling_parent = sibling.getParent();
109         new_node.setChild1( sibling );
110         new_node.setChild2( getRoot() );
111         new_node.setParent( sibling_parent );
112         sibling.setParent( new_node );
113         sibling_parent.setChildNode( sibling_index, new_node );
114         final double new_dist = sibling.getDistanceToParent() == PhylogenyNode.DISTANCE_DEFAULT ? PhylogenyNode.DISTANCE_DEFAULT
115                 : sibling.getDistanceToParent() / 2;
116         new_node.setDistanceToParent( new_dist );
117         sibling.setDistanceToParent( new_dist );
118         externalNodesHaveChanged();
119     }
120
121     /**
122      * This calculates the height of the subtree emanating at n for rooted,
123      * tree-shaped phylogenies
124      * 
125      * @param n
126      *            the root-node of a subtree
127      * @return the height of the subtree emanating at n
128      */
129     public double calculateSubtreeHeight( final PhylogenyNode n ) {
130         if ( n.isExternal() || n.isCollapse() ) {
131             return ForesterUtil.isLargerOrEqualToZero( n.getDistanceToParent() );
132         }
133         else {
134             double max = -Double.MAX_VALUE;
135             for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
136                 final double l = calculateSubtreeHeight( n.getChildNode( i ) );
137                 if ( l > max ) {
138                     max = l;
139                 }
140             }
141             return max + ForesterUtil.isLargerOrEqualToZero( n.getDistanceToParent() );
142         }
143     }
144
145     /**
146      * Returns a deep copy of this Phylogeny.
147      * <p>
148      * (The resulting Phylogeny has its references in the external nodes
149      * corrected, if they are lacking/obsolete in this.)
150      */
151     public Phylogeny copy() {
152         return copy( _root );
153     }
154
155     /**
156      * Returns a shallow copy of this Phylogeny.
157      * <p>
158      * (The resulting Phylogeny has its references in the external nodes
159      * corrected, if they are lacking/obsolete in this.)
160      */
161     public Phylogeny copyShallow() {
162         return copyShallow( _root );
163     }
164
165     public Phylogeny copyShallow( final PhylogenyNode source ) {
166         final Phylogeny tree = new Phylogeny();
167         if ( isEmpty() ) {
168             tree.init();
169             return tree;
170         }
171         tree._rooted = _rooted;
172         tree._name = _name;
173         tree._description = _description;
174         tree._type = _type;
175         tree._rerootable = _rerootable;
176         tree._distance_unit = _distance_unit;
177         tree._confidence = _confidence;
178         tree._identifier = _identifier;
179         tree.setAllowMultipleParents( isAllowMultipleParents() );
180         tree._root = PhylogenyMethods.copySubTreeShallow( source );
181         return tree;
182     }
183
184     /**
185      * Returns a deep copy of this Phylogeny.
186      * <p>
187      * (The resulting Phylogeny has its references in the external nodes
188      * corrected, if they are lacking/obsolete in this.)
189      */
190     public Phylogeny copy( final PhylogenyNode source ) {
191         final Phylogeny tree = new Phylogeny();
192         if ( isEmpty() ) {
193             tree.init();
194             return tree;
195         }
196         tree._rooted = _rooted;
197         tree._name = new String( _name );
198         tree._description = new String( _description );
199         tree._type = new String( _type );
200         tree._rerootable = _rerootable;
201         tree._distance_unit = new String( _distance_unit );
202         if ( _confidence != null ) {
203             tree._confidence = ( Confidence ) _confidence.copy();
204         }
205         if ( _identifier != null ) {
206             tree._identifier = ( Identifier ) _identifier.copy();
207         }
208         tree.setAllowMultipleParents( isAllowMultipleParents() );
209         tree._root = PhylogenyMethods.copySubTree( source );
210         return tree;
211     }
212
213     /**
214      * Need the delete and/or rehash _idhash (not done automatically
215      * to allow client multiple deletions in linear time).
216      * Need to call 'recalculateNumberOfExternalDescendants(boolean)' after this 
217      * if tree is to be displayed.
218      * 
219      * @param remove_us the parent node of the subtree to be deleted
220      */
221     public void deleteSubtree( final PhylogenyNode remove_us, final boolean collapse_resulting_node_with_one_desc ) {
222         if ( isEmpty() ) {
223             return;
224         }
225         if ( remove_us.isRoot() ) {
226             init();
227             return;
228         }
229         if ( !collapse_resulting_node_with_one_desc ) {
230             remove_us.getParent().removeChildNode( remove_us );
231         }
232         else {
233             final PhylogenyNode removed_node = remove_us;
234             final PhylogenyNode p = remove_us.getParent();
235             if ( p.isRoot() ) {
236                 if ( p.getNumberOfDescendants() == 2 ) {
237                     if ( removed_node.isFirstChildNode() ) {
238                         setRoot( getRoot().getChildNode( 1 ) );
239                         getRoot().setParent( null );
240                     }
241                     else {
242                         setRoot( getRoot().getChildNode( 0 ) );
243                         getRoot().setParent( null );
244                     }
245                 }
246                 else {
247                     p.removeChildNode( removed_node.getChildNodeIndex() );
248                 }
249             }
250             else {
251                 final PhylogenyNode pp = removed_node.getParent().getParent();
252                 if ( p.getNumberOfDescendants() == 2 ) {
253                     final int pi = p.getChildNodeIndex();
254                     if ( removed_node.isFirstChildNode() ) {
255                         p.getChildNode( 1 ).setDistanceToParent( PhylogenyMethods.addPhylogenyDistances( p
256                                 .getDistanceToParent(), p.getChildNode( 1 ).getDistanceToParent() ) );
257                         pp.setChildNode( pi, p.getChildNode( 1 ) );
258                     }
259                     else {
260                         p.getChildNode( 0 ).setDistanceToParent( PhylogenyMethods.addPhylogenyDistances( p
261                                 .getDistanceToParent(), p.getChildNode( 0 ).getDistanceToParent() ) );
262                         pp.setChildNode( pi, p.getChildNode( 0 ) );
263                     }
264                 }
265                 else {
266                     p.removeChildNode( removed_node.getChildNodeIndex() );
267                 }
268             }
269         }
270         remove_us.setParent( null );
271         setIdHash( null );
272         externalNodesHaveChanged();
273     }
274
275     public void externalNodesHaveChanged() {
276         _external_nodes_set = null;
277     }
278
279     public String[] getAllExternalNodeNames() {
280         int i = 0;
281         if ( isEmpty() ) {
282             return null;
283         }
284         final String[] names = new String[ getNumberOfExternalNodes() ];
285         for( final PhylogenyNodeIterator iter = iteratorExternalForward(); iter.hasNext(); ) {
286             names[ i++ ] = new String( iter.next().getName() );
287         }
288         return names;
289     }
290
291     public Confidence getConfidence() {
292         return _confidence;
293     }
294
295     public String getDescription() {
296         return _description;
297     }
298
299     public String getDistanceUnit() {
300         return _distance_unit;
301     }
302
303     /**
304      * 
305      * Warning. The order of the returned nodes is random
306      * -- and hence cannot be relied on.
307      * 
308      * @return Unordered set of PhylogenyNode
309      */
310     public List<PhylogenyNode> getExternalNodes() {
311         if ( _external_nodes_set == null ) {
312             _external_nodes_set = new ArrayList<PhylogenyNode>();
313             for( final PhylogenyNodeIterator it = iteratorPostorder(); it.hasNext(); ) {
314                 final PhylogenyNode n = it.next();
315                 if ( n.isExternal() ) {
316                     _external_nodes_set.add( n );
317                 }
318             }
319         }
320         return _external_nodes_set;
321     }
322
323     /**
324      * Returns the number of duplications of this Phylogeny (int). A return
325      * value of -1 indicates that the number of duplications is unknown.
326      */
327     // public int getNumberOfDuplications() {
328     // return _number_of_duplications;
329     // } // getNumberOfDuplications()
330     /**
331      * Sets the number of duplications of this Phylogeny (int). A value of -1
332      * indicates that the number of duplications is unknown.
333      * 
334      * @param clean_nh
335      *            set to true for clean NH format
336      */
337     // public void setNumberOfDuplications( int i ) {
338     // if ( i < 0 ) {
339     // _number_of_duplications = -1;
340     // }
341     // else {
342     // _number_of_duplications = i;
343     // }
344     // } // setNumberOfDuplications( int )
345     /**
346      * Returns the first external PhylogenyNode.
347      */
348     public PhylogenyNode getFirstExternalNode() {
349         if ( isEmpty() ) {
350             throw new FailedConditionCheckException( "attempt to obtain first external node of empty phylogeney" );
351         }
352         PhylogenyNode node = getRoot();
353         while ( node.isInternal() ) {
354             node = node.getFirstChildNode();
355         }
356         return node;
357     }
358
359     /**
360      * This calculates the height for rooted, tree-shaped phylogenies. The
361      * height is the longest distance from the root to an external node. Please
362      * note. Child nodes of collapsed nodes are ignored -- which is useful for
363      * display purposes but might be misleading for other applications.
364      * 
365      * @return the height for rooted, tree-shaped phylogenies
366      */
367     public double getHeight() {
368         if ( isEmpty() ) {
369             return 0.0;
370         }
371         return calculateSubtreeHeight( getRoot() );
372     }
373
374     public Identifier getIdentifier() {
375         return _identifier;
376     }
377
378     // ---------------------------------------------------------
379     // Modification of Phylogeny topology and Phylogeny appearance
380     // ---------------------------------------------------------
381     private HashMap<Integer, PhylogenyNode> getIdHash() {
382         return _idhash;
383     }
384
385     /**
386      * Returns the name of this Phylogeny.
387      */
388     public String getName() {
389         return _name;
390     }
391
392     /**
393      * Finds the PhylogenyNode of this Phylogeny which has a matching ID number.
394      * Takes O(n) time. After method hashIDs() has been called it runs in
395      * constant time.
396      * 
397      * @param id
398      *            ID number (int) of the PhylogenyNode to find
399      * @return PhylogenyNode with matching ID, null if not found
400      */
401     public PhylogenyNode getNode( final int id ) throws NoSuchElementException {
402         if ( isEmpty() ) {
403             throw new NoSuchElementException( "attempt to get node in an empty phylogeny" );
404         }
405         if ( _idhash != null ) {
406             return _idhash.get( id );
407         }
408         else {
409             for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
410                 final PhylogenyNode node = iter.next();
411                 if ( node.getId() == id ) {
412                     return node;
413                 }
414             }
415         }
416         return null;
417     }
418
419     /**
420      * Returns a PhylogenyNode of this Phylogeny which has a matching name.
421      * Throws an Exception if seqname is not present in this or not unique.
422      * 
423      * @param name
424      *            name (String) of PhylogenyNode to find
425      * @return PhylogenyNode with matchin name
426      */
427     public PhylogenyNode getNode( final String name ) {
428         if ( isEmpty() ) {
429             return null;
430         }
431         final List<PhylogenyNode> nodes = getNodes( name );
432         if ( ( nodes == null ) || ( nodes.size() < 1 ) ) {
433             throw new IllegalArgumentException( "node named [" + name + "] not found" );
434         }
435         if ( nodes.size() > 1 ) {
436             throw new IllegalArgumentException( "node named [" + name + "] not unique" );
437         }
438         return nodes.get( 0 );
439     }
440
441     /**
442      * Return Node by TaxonomyId Olivier CHABROL :
443      * olivier.chabrol@univ-provence.fr
444      * 
445      * @param taxonomyID
446      *            search taxonomy identifier
447      * @param nodes
448      *            sublist node to search
449      * @return List node with the same taxonomy identifier
450      */
451     private List<PhylogenyNode> getNodeByTaxonomyID( final String taxonomyID, final List<PhylogenyNode> nodes ) {
452         final List<PhylogenyNode> retour = new ArrayList<PhylogenyNode>();
453         for( final PhylogenyNode node : nodes ) {
454             if ( taxonomyID.equals( PhylogenyMethods.getTaxonomyIdentifier( node ) ) ) {
455                 retour.add( node );
456             }
457         }
458         return retour;
459     }
460
461     /**
462      * Returns a List with references to all Nodes of this Phylogeny which have
463      * a matching name.
464      * 
465      * @param name
466      *            name (String) of Nodes to find
467      * @return Vector of references to Nodes of this Phylogeny with matching
468      *         names
469      * @see #getNodesWithMatchingSpecies(String)
470      */
471     public List<PhylogenyNode> getNodes( final String name ) {
472         if ( isEmpty() ) {
473             return null;
474         }
475         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
476         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
477             final PhylogenyNode n = iter.next();
478             if ( n.getName().equals( name ) ) {
479                 nodes.add( n );
480             }
481         }
482         return nodes;
483     }
484
485     public List<PhylogenyNode> getNodesViaSequenceName( final String seq_name ) {
486         if ( isEmpty() ) {
487             return null;
488         }
489         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
490         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
491             final PhylogenyNode n = iter.next();
492             if ( n.getNodeData().isHasSequence() && n.getNodeData().getSequence().getName().equals( seq_name ) ) {
493                 nodes.add( n );
494             }
495         }
496         return nodes;
497     }
498
499     public List<PhylogenyNode> getNodesViaTaxonomyCode( final String taxonomy_code ) {
500         if ( isEmpty() ) {
501             return null;
502         }
503         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
504         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
505             final PhylogenyNode n = iter.next();
506             if ( n.getNodeData().isHasTaxonomy()
507                     && n.getNodeData().getTaxonomy().getTaxonomyCode().equals( taxonomy_code ) ) {
508                 nodes.add( n );
509             }
510         }
511         return nodes;
512     }
513
514     /**
515      * Returns a Vector with references to all Nodes of this Phylogeny which
516      * have a matching species name.
517      * 
518      * @param specname
519      *            species name (String) of Nodes to find
520      * @return Vector of references to Nodes of this Phylogeny with matching
521      *         species names.
522      * @see #getNodes(String)
523      */
524     public List<PhylogenyNode> getNodesWithMatchingSpecies( final String specname ) {
525         if ( isEmpty() ) {
526             return null;
527         }
528         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
529         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
530             final PhylogenyNode n = iter.next();
531             if ( PhylogenyMethods.getSpecies( n ).equals( specname ) ) {
532                 nodes.add( n );
533             }
534         }
535         return nodes;
536     }
537
538     public PhylogenyNode getNodeViaSequenceName( final String seq_name ) {
539         if ( isEmpty() ) {
540             return null;
541         }
542         final List<PhylogenyNode> nodes = getNodesViaSequenceName( seq_name );
543         if ( ( nodes == null ) || ( nodes.size() < 1 ) ) {
544             throw new IllegalArgumentException( "node with sequence named [" + seq_name + "] not found" );
545         }
546         if ( nodes.size() > 1 ) {
547             throw new IllegalArgumentException( "node with sequence named [" + seq_name + "] not unique" );
548         }
549         return nodes.get( 0 );
550     }
551
552     public PhylogenyNode getNodeViaTaxonomyCode( final String taxonomy_code ) {
553         if ( isEmpty() ) {
554             return null;
555         }
556         final List<PhylogenyNode> nodes = getNodesViaTaxonomyCode( taxonomy_code );
557         if ( ( nodes == null ) || ( nodes.size() < 1 ) ) {
558             throw new IllegalArgumentException( "node with taxonomy code \"" + taxonomy_code + "\" not found" );
559         }
560         if ( nodes.size() > 1 ) {
561             throw new IllegalArgumentException( "node with taxonomy code \"" + taxonomy_code + "\" not unique" );
562         }
563         return nodes.get( 0 );
564     }
565
566     public int getNumberOfBranches() {
567         if ( isEmpty() ) {
568             return 0;
569         }
570         int c = 0;
571         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); iter.next() ) {
572             ++c;
573         }
574         if ( !isRooted() ) {
575             --c;
576         }
577         return c;
578     }
579
580     /**
581      * Returns the sum of external Nodes of this Phylogeny (int).
582      */
583     public int getNumberOfExternalNodes() {
584         if ( isEmpty() ) {
585             return 0;
586         }
587         return getExternalNodes().size();
588     }
589
590     /**
591      * Returns all paralogs of the external PhylogenyNode n of this Phylogeny.
592      * paralog are returned as List of node references.
593      * <p>
594      * PRECONDITION: This tree must be binary and rooted, and speciation -
595      * duplication need to be assigned for each of its internal Nodes.
596      * <p>
597      * Returns null if this Phylogeny is empty or if n is internal.
598      * <p>
599      * (Last modified: 11/22/00) Olivier CHABROL :
600      * olivier.chabrol@univ-provence.fr
601      * 
602      * @param n
603      *            external PhylogenyNode whose orthologs are to be returned
604      * @return Vector of references to all orthologous Nodes of PhylogenyNode n
605      *         of this Phylogeny, null if this Phylogeny is empty or if n is
606      *         internal
607      */
608     public List<PhylogenyNode> getParalogousNodes( final PhylogenyNode n, final String[] taxonomyCodeRange ) {
609         PhylogenyNode node = n;
610         PhylogenyNode prev = null;
611         final List<PhylogenyNode> v = new ArrayList<PhylogenyNode>();
612         final Map<PhylogenyNode, List<String>> map = new HashMap<PhylogenyNode, List<String>>();
613         getTaxonomyMap( getRoot(), map );
614         if ( !node.isExternal() || isEmpty() ) {
615             return null;
616         }
617         final String searchNodeSpeciesId = PhylogenyMethods.getTaxonomyIdentifier( n );
618         if ( !node.isExternal() || isEmpty() ) {
619             return null;
620         }
621         List<String> taxIdList = null;
622         final List<String> taxonomyCodeRangeList = Arrays.asList( taxonomyCodeRange );
623         while ( !node.isRoot() ) {
624             prev = node;
625             node = node.getParent();
626             taxIdList = map.get( node );
627             if ( node.isDuplication() && isContains( taxIdList, taxonomyCodeRangeList ) ) {
628                 if ( node.getChildNode1() == prev ) {
629                     v.addAll( getNodeByTaxonomyID( searchNodeSpeciesId, node.getChildNode2()
630                             .getAllExternalDescendants() ) );
631                 }
632                 else {
633                     v.addAll( getNodeByTaxonomyID( searchNodeSpeciesId, node.getChildNode1()
634                             .getAllExternalDescendants() ) );
635                 }
636             }
637         }
638         return v;
639     }
640
641     public Collection<SequenceRelation.SEQUENCE_RELATION_TYPE> getRelevantSequenceRelationTypes() {
642         if ( _relevant_sequence_relation_types == null ) {
643             _relevant_sequence_relation_types = new Vector<SEQUENCE_RELATION_TYPE>();
644         }
645         return _relevant_sequence_relation_types;
646     }
647
648     /**
649      * Returns the root PhylogenyNode of this Phylogeny.
650      */
651     public PhylogenyNode getRoot() {
652         return _root;
653     }
654
655     public Collection<Sequence> getSequenceRelationQueries() {
656         return _sequenceRelationQueries;
657     }
658
659     /**
660      * List all species contains in all leaf under a node Olivier CHABROL :
661      * olivier.chabrol@univ-provence.fr
662      * 
663      * @param node
664      *            PhylogenyNode whose sub node species are returned
665      * @return species contains in all leaf under the param node
666      */
667     private List<String> getSubNodeTaxonomy( final PhylogenyNode node ) {
668         final List<String> taxonomyList = new ArrayList<String>();
669         final List<PhylogenyNode> childs = node.getAllExternalDescendants();
670         String speciesId = null;
671         for( final PhylogenyNode phylogenyNode : childs ) {
672             // taxId = new Long(phylogenyNode.getTaxonomyID());
673             speciesId = PhylogenyMethods.getTaxonomyIdentifier( phylogenyNode );
674             if ( !taxonomyList.contains( speciesId ) ) {
675                 taxonomyList.add( speciesId );
676             }
677         }
678         return taxonomyList;
679     }
680
681     /**
682      * Create a map [<PhylogenyNode, List<String>], the list contains the
683      * species contains in all leaf under phylogeny node Olivier CHABROL :
684      * olivier.chabrol@univ-provence.fr
685      * 
686      * @param node
687      *            the tree root node
688      * @param map
689      *            map to fill
690      */
691     private void getTaxonomyMap( final PhylogenyNode node, final Map<PhylogenyNode, List<String>> map ) {
692         // node is leaf
693         if ( node.isExternal() ) {
694             return;
695         }
696         map.put( node, getSubNodeTaxonomy( node ) );
697         getTaxonomyMap( node.getChildNode1(), map );
698         getTaxonomyMap( node.getChildNode2(), map );
699     }
700
701     public String getType() {
702         return _type;
703     }
704
705     /**
706      * Hashes the ID number of each PhylogenyNode of this Phylogeny to its
707      * corresponding PhylogenyNode, in order to make method getNode( id ) run in
708      * constant time. Important: The user is responsible for calling this method
709      * (again) after this Phylogeny has been changed/created/renumbered.
710      */
711     public void hashIDs() {
712         if ( isEmpty() ) {
713             return;
714         }
715         setIdHash( new HashMap<Integer, PhylogenyNode>() );
716         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
717             final PhylogenyNode node = iter.next();
718             getIdHash().put( node.getId(), node );
719         }
720     }
721
722     /**
723      * Deletes this Phylogeny.
724      */
725     public void init() {
726         _root = null;
727         _rooted = false;
728         _name = "";
729         _description = "";
730         _type = "";
731         _distance_unit = "";
732         _idhash = null;
733         _confidence = null;
734         _identifier = null;
735         _rerootable = true;
736         setAllowMultipleParents( Phylogeny.ALLOW_MULTIPLE_PARENTS_DEFAULT );
737     }
738
739     private boolean isAllowMultipleParents() {
740         return _allow_multiple_parents;
741     }
742
743     /**
744      * Returns whether this is a completely binary tree (i.e. all internal nodes
745      * are bifurcations).
746      * 
747      */
748     public boolean isCompletelyBinary() {
749         if ( isEmpty() ) {
750             return false;
751         }
752         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
753             final PhylogenyNode node = iter.next();
754             if ( node.isInternal() && ( node.getNumberOfDescendants() != 2 ) ) {
755                 return false;
756             }
757         }
758         return true;
759     }
760
761     /**
762      * Util method to check if all element of a list is contains in the
763      * rangeList. Olivier CHABROL : olivier.chabrol@univ-provence.fr
764      * 
765      * @param list
766      *            list to be check
767      * @param rangeList
768      *            the range list to compare
769      * @return <code>true</code> if all param list element are contains in param
770      *         rangeList, <code>false</code> otherwise.
771      */
772     private boolean isContains( final List<String> list, final List<String> rangeList ) {
773         if ( list.size() > rangeList.size() ) {
774             return false;
775         }
776         String l = null;
777         for( final Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
778             l = iterator.next();
779             if ( !rangeList.contains( l ) ) {
780                 return false;
781             }
782         }
783         return true;
784     }
785
786     /**
787      * Checks whether a Phylogeny object is deleted (or empty).
788      * 
789      * @return true if the tree is deleted (or empty), false otherwise
790      */
791     public boolean isEmpty() {
792         return ( getRoot() == null );
793     }
794
795     public boolean isRerootable() {
796         return _rerootable;
797     }
798
799     /**
800      * Returns true is this Phylogeny is rooted.
801      */
802     public boolean isRooted() {
803         return _rooted;
804     } // isRooted()
805
806     public boolean isTree() {
807         return true;
808     }
809
810     public PhylogenyNodeIterator iteratorExternalForward() {
811         return new ExternalForwardIterator( this );
812     }
813
814     public PhylogenyNodeIterator iteratorLevelOrder() {
815         return new LevelOrderTreeIterator( this );
816     }
817
818     public PhylogenyNodeIterator iteratorPostorder() {
819         return new PostorderTreeIterator( this );
820     }
821
822     public PhylogenyNodeIterator iteratorPreorder() {
823         return new PreorderTreeIterator( this );
824     }
825
826     /**
827      * Resets the ID numbers of the nodes of this Phylogeny in level order,
828      * starting with start_label (for the root). <br>
829      * WARNING. After this method has been called, node IDs are no longer
830      * unique. 
831      */
832     public void levelOrderReID() {
833         if ( isEmpty() ) {
834             return;
835         }
836         _idhash = null;
837         int max = 0;
838         for( final PhylogenyNodeIterator it = iteratorPreorder(); it.hasNext(); ) {
839             final PhylogenyNode node = it.next();
840             if ( node.isRoot() ) {
841                 node.setId( PhylogenyNode.getNodeCount() );
842             }
843             else {
844                 node.setId( node.getParent().getId() + 1 );
845                 if ( node.getId() > max ) {
846                     max = node.getId();
847                 }
848             }
849         }
850         PhylogenyNode.setNodeCount( max + 1 );
851     }
852
853     /**
854      * Arranges the order of childern for each node of this Phylogeny in such a
855      * way that either the branch with more children is on top (right) or on
856      * bottom (left), dependent on the value of boolean order.
857      * 
858      * @param order
859      *            decides in which direction to order
860      */
861     public void orderAppearance( final boolean order ) throws RuntimeException {
862         if ( !isTree() ) {
863             throw new FailedConditionCheckException( "Attempt to order appearance on phylogeny which is not tree-like." );
864         }
865         if ( isEmpty() ) {
866             return;
867         }
868         orderAppearanceHelper( getRoot(), order );
869     }
870
871     // Helper method for "orderAppearance(boolean)".
872     // Traverses this Phylogeny recusively.
873     private void orderAppearanceHelper( final PhylogenyNode n, final boolean order ) {
874         if ( n.isExternal() ) {
875             return;
876         }
877         else {
878             PhylogenyNode temp = null;
879             // FIXME
880             if ( ( n.getNumberOfDescendants() == 2 )
881                     && ( n.getChildNode1().getNumberOfExternalNodes() != n.getChildNode2().getNumberOfExternalNodes() )
882                     && ( ( n.getChildNode1().getNumberOfExternalNodes() < n.getChildNode2().getNumberOfExternalNodes() ) == order ) ) {
883                 temp = n.getChildNode1();
884                 n.setChild1( n.getChildNode2() );
885                 n.setChild2( temp );
886             }
887             for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
888                 orderAppearanceHelper( n.getChildNode( i ), order );
889             }
890         }
891     }
892
893     public void preOrderReId() {
894         if ( isEmpty() ) {
895             return;
896         }
897         setIdHash( null );
898         int i = PhylogenyNode.getNodeCount();
899         for( final PhylogenyNodeIterator it = iteratorPreorder(); it.hasNext(); ) {
900             it.next().setId( i++ );
901         }
902         PhylogenyNode.setNodeCount( i );
903     }
904
905     /**
906      * Prints descriptions of all external Nodes of this Phylogeny to
907      * System.out.
908      */
909     public void printExtNodes() {
910         if ( isEmpty() ) {
911             return;
912         }
913         for( final PhylogenyNodeIterator iter = iteratorExternalForward(); iter.hasNext(); ) {
914             System.out.println( iter.next() + "\n" );
915         }
916     }
917
918     /**
919      * (Re)counts the number of children for each PhylogenyNode of this
920      * Phylogeny. As an example, this method needs to be called after a
921      * Phylogeny has been reRooted and it is to be displayed.
922      * 
923      * @param consider_collapsed_nodes
924      *            set to true to take into account collapsed nodes (collapsed
925      *            nodes have 1 child).
926      */
927     public void recalculateNumberOfExternalDescendants( final boolean consider_collapsed_nodes ) {
928         if ( isEmpty() ) {
929             return;
930         }
931         for( final PhylogenyNodeIterator iter = iteratorPostorder(); iter.hasNext(); ) {
932             final PhylogenyNode node = iter.next();
933             if ( node.isExternal() || ( consider_collapsed_nodes && node.isCollapse() ) ) {
934                 node.setSumExtNodes( 1 );
935             }
936             else {
937                 int sum = 0;
938                 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
939                     sum += node.getChildNode( i ).getNumberOfExternalNodes();
940                 }
941                 node.setSumExtNodes( sum );
942             }
943         }
944     }
945
946     /**
947      * Places the root of this Phylogeny on the parent branch of the
948      * PhylogenyNode with a corresponding ID. The new root is always placed on
949      * the middle of the branch. If the resulting reRooted Phylogeny is to be
950      * used any further, in most cases the following methods have to be called
951      * on the resulting Phylogeny:
952      * <p>
953      * <li>recalculateNumberOfExternalDescendants(boolean)
954      * <li>recalculateAndReset()
955      * 
956      * @param id
957      *            ID (int) of PhylogenyNode of this Phylogeny
958      */
959     public void reRoot( final int id ) {
960         reRoot( getNode( id ) );
961     }
962
963     /**
964      * Places the root of this Phylogeny on Branch b. The new root is always
965      * placed on the middle of the branch b.
966      * 
967      */
968     public void reRoot( final PhylogenyBranch b ) {
969         final PhylogenyNode n1 = b.getFirstNode();
970         final PhylogenyNode n2 = b.getSecondNode();
971         if ( n1.isExternal() ) {
972             reRoot( n1 );
973         }
974         else if ( n2.isExternal() ) {
975             reRoot( n2 );
976         }
977         else if ( ( n2 == n1.getChildNode1() ) || ( n2 == n1.getChildNode2() ) ) {
978             reRoot( n2 );
979         }
980         else if ( ( n1 == n2.getChildNode1() ) || ( n1 == n2.getChildNode2() ) ) {
981             reRoot( n1 );
982         }
983         else if ( ( n1.getParent() != null ) && n1.getParent().isRoot()
984                 && ( ( n1.getParent().getChildNode1() == n2 ) || ( n1.getParent().getChildNode2() == n2 ) ) ) {
985             reRoot( n1 );
986         }
987         else {
988             throw new IllegalArgumentException( "reRoot( Branch b ): b is not a branch." );
989         }
990     }
991
992     /**
993      * Places the root of this Phylogeny on the parent branch PhylogenyNode n.
994      * The new root is always placed on the middle of the branch.
995      * <p>
996      * If the resulting reRooted Phylogeny is to be used any further, in most
997      * cases the following three methods have to be called on the resulting
998      * Phylogeny:
999      * <ul>
1000      * <li>recalculateNumberOfExternalDescendants(boolean) <li>recalculateAndReset()
1001      * </ul>
1002      * <p>
1003      * (Last modified: 10/01/01)
1004      * 
1005      * @param n
1006      *            PhylogenyNode of this Phylogeny\
1007      */
1008     public void reRoot( final PhylogenyNode n ) {
1009         reRoot( n, -1 );
1010     }
1011
1012     public void reRoot( final PhylogenyNode n, final double distance_n_to_parent ) {
1013         if ( isEmpty() || ( getNumberOfExternalNodes() < 2 ) ) {
1014             return;
1015         }
1016         setRooted( true );
1017         if ( n.isRoot() ) {
1018             return;
1019         }
1020         else if ( n.getParent().isRoot() ) {
1021             if ( ( n.getParent().getNumberOfDescendants() == 2 ) && ( distance_n_to_parent >= 0 ) ) {
1022                 final double d = n.getParent().getChildNode1().getDistanceToParent()
1023                         + n.getParent().getChildNode2().getDistanceToParent();
1024                 PhylogenyNode other;
1025                 if ( n.getChildNodeIndex() == 0 ) {
1026                     other = n.getParent().getChildNode2();
1027                 }
1028                 else {
1029                     other = n.getParent().getChildNode1();
1030                 }
1031                 n.setDistanceToParent( distance_n_to_parent );
1032                 final double dm = d - distance_n_to_parent;
1033                 if ( dm >= 0 ) {
1034                     other.setDistanceToParent( dm );
1035                 }
1036                 else {
1037                     other.setDistanceToParent( 0 );
1038                 }
1039             }
1040             if ( n.getParent().getNumberOfDescendants() > 2 ) {
1041                 final int index = n.getChildNodeIndex();
1042                 final double dn = n.getDistanceToParent();
1043                 final PhylogenyNode prev_root = getRoot();
1044                 prev_root.getDescendants().remove( index );
1045                 final PhylogenyNode new_root = new PhylogenyNode();
1046                 new_root.setChildNode( 0, n );
1047                 new_root.setChildNode( 1, prev_root );
1048                 if ( n.getBranchDataDirectly() != null ) {
1049                     prev_root.setBranchData( ( BranchData ) n.getBranchDataDirectly().copy() );
1050                 }
1051                 setRoot( new_root );
1052                 if ( distance_n_to_parent >= 0 ) {
1053                     n.setDistanceToParent( distance_n_to_parent );
1054                     final double d = dn - distance_n_to_parent;
1055                     if ( d >= 0 ) {
1056                         prev_root.setDistanceToParent( d );
1057                     }
1058                     else {
1059                         prev_root.setDistanceToParent( 0 );
1060                     }
1061                 }
1062                 else {
1063                     if ( dn >= 0 ) {
1064                         final double d = dn / 2.0;
1065                         n.setDistanceToParent( d );
1066                         prev_root.setDistanceToParent( d );
1067                     }
1068                 }
1069             }
1070         }
1071         else {
1072             PhylogenyNode a = n;
1073             PhylogenyNode b = null;
1074             PhylogenyNode c = null;
1075             final PhylogenyNode new_root = new PhylogenyNode();
1076             double distance1 = 0.0;
1077             double distance2 = 0.0;
1078             BranchData branch_data_1 = null;
1079             BranchData branch_data_2 = null;
1080             b = a.getParent();
1081             c = b.getParent();
1082             new_root.setChildNode( 0, a );
1083             new_root.setChildNode( 1, b );
1084             distance1 = c.getDistanceToParent();
1085             if ( c.getBranchDataDirectly() != null ) {
1086                 branch_data_1 = ( BranchData ) c.getBranchDataDirectly().copy();
1087             }
1088             c.setDistanceToParent( b.getDistanceToParent() );
1089             if ( b.getBranchDataDirectly() != null ) {
1090                 c.setBranchData( ( BranchData ) b.getBranchDataDirectly().copy() );
1091             }
1092             if ( a.getBranchDataDirectly() != null ) {
1093                 b.setBranchData( ( BranchData ) a.getBranchDataDirectly().copy() );
1094             }
1095             // New root is always placed in the middle of the branch:
1096             if ( a.getDistanceToParent() == PhylogenyNode.DISTANCE_DEFAULT ) {
1097                 b.setDistanceToParent( PhylogenyNode.DISTANCE_DEFAULT );
1098             }
1099             else {
1100                 if ( distance_n_to_parent >= 0.0 ) {
1101                     final double diff = a.getDistanceToParent() - distance_n_to_parent;
1102                     a.setDistanceToParent( distance_n_to_parent );
1103                     b.setDistanceToParent( diff >= 0.0 ? diff : 0.0 );
1104                 }
1105                 else {
1106                     final double d = a.getDistanceToParent() / 2.0;
1107                     a.setDistanceToParent( d );
1108                     b.setDistanceToParent( d );
1109                 }
1110             }
1111             b.setChildNodeOnly( a.getChildNodeIndex( b ), c );
1112             // moving to the old root, swapping references:
1113             while ( !c.isRoot() ) {
1114                 a = b;
1115                 b = c;
1116                 c = c.getParent();
1117                 b.setChildNodeOnly( a.getChildNodeIndex( b ), c );
1118                 b.setParent( a );
1119                 distance2 = c.getDistanceToParent();
1120                 branch_data_2 = c.getBranchDataDirectly();
1121                 c.setDistanceToParent( distance1 );
1122                 c.setBranchData( branch_data_1 );
1123                 distance1 = distance2;
1124                 branch_data_1 = branch_data_2;
1125             }
1126             // removing the old root:
1127             if ( c.getNumberOfDescendants() == 2 ) {
1128                 final PhylogenyNode node = c.getChildNode( 1 - b.getChildNodeIndex( c ) );
1129                 node.setParent( b );
1130                 if ( ( c.getDistanceToParent() == PhylogenyNode.DISTANCE_DEFAULT )
1131                         && ( node.getDistanceToParent() == PhylogenyNode.DISTANCE_DEFAULT ) ) {
1132                     node.setDistanceToParent( PhylogenyNode.DISTANCE_DEFAULT );
1133                 }
1134                 else {
1135                     node.setDistanceToParent( ( c.getDistanceToParent() >= 0.0 ? c.getDistanceToParent() : 0.0 )
1136                             + ( node.getDistanceToParent() >= 0.0 ? node.getDistanceToParent() : 0.0 ) );
1137                 }
1138                 if ( c.getBranchDataDirectly() != null ) {
1139                     node.setBranchData( ( BranchData ) c.getBranchDataDirectly().copy() );
1140                 }
1141                 for( int i = 0; i < b.getNumberOfDescendants(); ++i ) {
1142                     if ( b.getChildNode( i ) == c ) {
1143                         b.setChildNodeOnly( i, node );
1144                         break;
1145                     }
1146                 }
1147             }
1148             else {
1149                 c.setParent( b );
1150                 c.removeChildNode( b.getChildNodeIndex( c ) );
1151             }
1152             setRoot( new_root );
1153         }
1154     }
1155
1156     /**
1157      * Sets all Nodes of this Phylogeny to not-collapsed.
1158      * <p>
1159      * In most cases methods adjustNodeCount(false) and recalculateAndReset()
1160      * need to be called after this method has been called.
1161      */
1162     public void setAllNodesToNotCollapse() {
1163         if ( isEmpty() ) {
1164             return;
1165         }
1166         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
1167             final PhylogenyNode node = iter.next();
1168             node.setCollapse( false );
1169         }
1170     }
1171
1172     private void setAllowMultipleParents( final boolean allow_multiple_parents ) {
1173         _allow_multiple_parents = allow_multiple_parents;
1174     }
1175
1176     public void setConfidence( final Confidence confidence ) {
1177         _confidence = confidence;
1178     }
1179
1180     public void setDescription( final String description ) {
1181         _description = description;
1182     }
1183
1184     public void setDistanceUnit( final String _distance_unit ) {
1185         this._distance_unit = _distance_unit;
1186     }
1187
1188     public void setIdentifier( final Identifier identifier ) {
1189         _identifier = identifier;
1190     }
1191
1192     void setIdHash( final HashMap<Integer, PhylogenyNode> idhash ) {
1193         _idhash = idhash;
1194     }
1195
1196     /**
1197      * Sets the indicators of all Nodes of this Phylogeny to 0.
1198      */
1199     public void setIndicatorsToZero() {
1200         if ( isEmpty() ) {
1201             return;
1202         }
1203         for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
1204             iter.next().setIndicator( ( byte ) 0 );
1205         }
1206     } // setIndicatorsToZero()
1207
1208     /**
1209      * Sets the name of this Phylogeny to s.
1210      */
1211     public void setName( final String s ) {
1212         _name = s;
1213     }
1214
1215     public void setRelevantSequenceRelationTypes( final Collection<SequenceRelation.SEQUENCE_RELATION_TYPE> types ) {
1216         _relevant_sequence_relation_types = types;
1217     }
1218
1219     public void setRerootable( final boolean rerootable ) {
1220         _rerootable = rerootable;
1221     }
1222
1223     public void setRoot( final PhylogenyNode n ) {
1224         _root = n;
1225     } // setRoot( PhylogenyNode )
1226
1227     /**
1228      * Sets whether this Phylogeny is rooted or not.
1229      */
1230     public void setRooted( final boolean b ) {
1231         _rooted = b;
1232     } // setRooted( boolean )
1233
1234     public void setSequenceRelationQueries( final Collection<Sequence> sequencesByName ) {
1235         _sequenceRelationQueries = sequencesByName;
1236     }
1237
1238     public void setType( final String type ) {
1239         _type = type;
1240     }
1241
1242     /**
1243      * Swaps the the two childern of a PhylogenyNode node of this Phylogeny.
1244      * <p>
1245      * (Last modified: 06/13/01)
1246      * 
1247      * @param node
1248      *            a PhylogenyNode of this Phylogeny
1249      */
1250     public void swapChildren( final PhylogenyNode node ) throws RuntimeException {
1251         if ( !isTree() ) {
1252             throw new FailedConditionCheckException( "Attempt to swap children on phylogeny which is not tree-like." );
1253         }
1254         if ( isEmpty() || node.isExternal() || ( node.getNumberOfDescendants() < 2 ) ) {
1255             return;
1256         }
1257         final PhylogenyNode first = node.getFirstChildNode();
1258         for( int i = 1; i < node.getNumberOfDescendants(); ++i ) {
1259             node.setChildNode( i - 1, node.getChildNode( i ) );
1260         }
1261         node.setChildNode( node.getNumberOfDescendants() - 1, first );
1262     } // swapChildren( PhylogenyNode )
1263
1264     public String toNewHampshire() {
1265         return toNewHampshire( false );
1266     }
1267
1268     public String toNewHampshire( final boolean simple_nh ) {
1269         try {
1270             return new PhylogenyWriter().toNewHampshire( this, simple_nh, true ).toString();
1271         }
1272         catch ( final IOException e ) {
1273             throw new Error( "this should not have happend: " + e.getMessage() );
1274         }
1275     }
1276
1277     public String toNewHampshireX() {
1278         try {
1279             return new PhylogenyWriter().toNewHampshireX( this ).toString();
1280         }
1281         catch ( final IOException e ) {
1282             throw new Error( "this should not have happend: " + e.getMessage() );
1283         }
1284     }
1285
1286     public String toNexus() {
1287         try {
1288             return new PhylogenyWriter().toNexus( this ).toString();
1289         }
1290         catch ( final IOException e ) {
1291             throw new Error( "this should not have happend: " + e.getMessage() );
1292         }
1293     }
1294
1295     public String toPhyloXML( final int phyloxml_level ) {
1296         try {
1297             return new PhylogenyWriter().toPhyloXML( this, phyloxml_level ).toString();
1298         }
1299         catch ( final IOException e ) {
1300             throw new Error( "this should not have happend: " + e.getMessage() );
1301         }
1302     }
1303
1304     // ---------------------------------------------------------
1305     // Writing of Phylogeny to Strings
1306     // ---------------------------------------------------------
1307     /**
1308      * Converts this Phylogeny to a New Hampshire X (String) representation.
1309      * 
1310      * @return New Hampshire X (String) representation of this
1311      * @see #toNewHampshireX()
1312      */
1313     @Override
1314     public String toString() {
1315         return toNewHampshireX();
1316     }
1317
1318     /**
1319      * Removes the root PhylogenyNode this Phylogeny.
1320      */
1321     public void unRoot() throws RuntimeException {
1322         if ( !isTree() ) {
1323             throw new FailedConditionCheckException( "Attempt to unroot a phylogeny which is not tree-like." );
1324         }
1325         if ( isEmpty() ) {
1326             return;
1327         }
1328         setIndicatorsToZero();
1329         if ( !isRooted() || ( getNumberOfExternalNodes() <= 1 ) ) {
1330             return;
1331         }
1332         setRooted( false );
1333         return;
1334     } // unRoot()
1335 }