gsdi work
[jalview.git] / forester / java / src / org / forester / phylogeny / PhylogenyNode.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.util.ArrayList;
31 import java.util.List;
32
33 import org.forester.io.parsers.nhx.NHXFormatException;
34 import org.forester.io.parsers.nhx.NHXParser;
35 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
36 import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
37 import org.forester.phylogeny.data.BranchData;
38 import org.forester.phylogeny.data.Confidence;
39 import org.forester.phylogeny.data.NodeData;
40 import org.forester.phylogeny.data.PhylogenyDataUtil;
41 import org.forester.phylogeny.iterators.PreorderTreeIterator;
42 import org.forester.util.ForesterUtil;
43
44 /**
45  * Warning. Implementation of method 'compareTo' only looks at 
46  * node name. Thus, use of this class in SortedSets might lead
47  * to unexpected behavior.
48  *
49  */
50 public final class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode> {
51
52     private static int               _node_count      = 0;
53     private byte                     _indicator;
54     private int                      _id;
55     private int                      _sum_ext_nodes;
56     private float                    _x;
57     private float                    _y;
58     private double                   _distance_parent = PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
59     private boolean                  _collapse;
60     private PhylogenyNode            _parent;
61     private PhylogenyNode            _link;
62     private ArrayList<PhylogenyNode> _descendants;
63     private NodeData                 _node_data;
64     private BranchData               _branch_data;
65     private float                    _x_secondary;
66     private float                    _y_secondary;
67
68     /**
69      * Default constructor for PhylogenyNode.
70      */
71     public PhylogenyNode() {
72         //  init();
73         setId( PhylogenyNode.getNodeCount() );
74         PhylogenyNode.increaseNodeCount();
75         setSumExtNodes( 1 ); // For ext node, this number is 1 (not 0!!)
76     }
77
78     public void removeConnections() {
79         _parent = null;
80         _link = null;
81         _descendants = null;
82     }
83
84     /**
85      * Adds PhylogenyNode n to the list of child nodes and sets the _parent of n
86      * to this.
87      * 
88      * @param n
89      *            the PhylogenyNode to add
90      */
91     @Override
92     final public void addAsChild( final PhylogenyNodeI node ) {
93         final PhylogenyNode n = ( PhylogenyNode ) node;
94         addChildNode( n );
95         n.setParent( this );
96     }
97
98     /**
99      * Adds PhylogenyNode n to the list of child nodes. But does NOT set the
100      * _parent of n to this.
101      * 
102      * @see addAsChild( PhylogenyNode n )
103      * @param n
104      *            the PhylogenyNode to add
105      */
106     final private void addChildNode( final PhylogenyNode child ) {
107         getDescendants().add( child );
108     }
109
110     @Override
111     // this is poor, as it only compares on names!
112     final public int compareTo( final PhylogenyNode o ) {
113         final PhylogenyNode n = o;
114         if ( ( getName() == null ) || ( n.getName() == null ) ) {
115             return 0;
116         }
117         return getName().compareTo( n.getName() );
118     }
119
120     // ---------------------------------------------------------
121     // Copy and delete Nodes, copy subtress
122     // ---------------------------------------------------------
123     /**
124      * Returns a new PhylogenyNode which has its data copied from this
125      * PhylogenyNode. Links to the other Nodes in the same Phylogeny are NOT
126      * copied (e.g. _link to _parent). Field "_link" IS copied.
127      * 
128      * @see #getLink() 
129      */
130     final public PhylogenyNode copyNodeData() {
131         final PhylogenyNode node = new PhylogenyNode();
132         PhylogenyNode.decreaseNodeCount();
133         node._id = _id;
134         node._sum_ext_nodes = _sum_ext_nodes;
135         node._indicator = _indicator;
136         node._x = _x;
137         node._y = _y;
138         node._distance_parent = _distance_parent;
139         node._collapse = _collapse;
140         node._link = _link;
141         if ( _node_data != null ) {
142             node._node_data = ( NodeData ) _node_data.copy();
143         }
144         if ( _branch_data != null ) {
145             node._branch_data = ( BranchData ) _branch_data.copy();
146         }
147         return node;
148     }
149
150     /**
151      * Returns a new PhylogenyNode which has the same data as this
152      * PhylogenyNode. Links to the other Nodes in the same Phylogeny are NOT
153      * copied (e.g. _link to _parent). Field "_link" IS copied.
154      * 
155      * @see #getLink() 
156      */
157     final public PhylogenyNode copyNodeDataShallow() {
158         final PhylogenyNode node = new PhylogenyNode();
159         PhylogenyNode.decreaseNodeCount();
160         node._id = _id;
161         node._sum_ext_nodes = _sum_ext_nodes;
162         node._indicator = _indicator;
163         node._x = _x;
164         node._y = _y;
165         node._distance_parent = _distance_parent;
166         node._collapse = _collapse;
167         node._link = _link;
168         node._node_data = _node_data;
169         node._branch_data = _branch_data;
170         return node;
171     }
172
173     @Override
174     /**
175      * Based on node name, sequence, and taxonomy.
176      * 
177      * 
178      */
179     final public boolean equals( final Object o ) {
180         if ( this == o ) {
181             return true;
182         }
183         else if ( o == null ) {
184             return false;
185         }
186         else if ( o.getClass() != this.getClass() ) {
187             throw new IllegalArgumentException( "attempt to check [" + this.getClass() + "] equality to " + o + " ["
188                     + o.getClass() + "]" );
189         }
190         else {
191             final PhylogenyNode other = ( PhylogenyNode ) o;
192             if ( !getName().equals( other.getName() ) ) {
193                 return false;
194             }
195             final NodeData this_data = getNodeData();
196             final NodeData other_data = other.getNodeData();
197             if ( ( this_data.isHasSequence() && other_data.isHasSequence() )
198                     && ( this_data.isHasTaxonomy() && other_data.isHasTaxonomy() ) ) {
199                 return ( this_data.getTaxonomy().isEqual( other_data.getTaxonomy() ) && this_data.getSequence()
200                         .isEqual( other_data.getSequence() ) );
201             }
202             else if ( this_data.isHasTaxonomy() && other_data.isHasTaxonomy() ) {
203                 return ( this_data.getTaxonomy().isEqual( other_data.getTaxonomy() ) );
204             }
205             else if ( this_data.isHasSequence() && other_data.isHasSequence() ) {
206                 return ( this_data.getSequence().isEqual( other_data.getSequence() ) );
207             }
208             else if ( getName().length() > 0 ) {
209                 // Node name is not empty, and equal.
210                 return true;
211             }
212             else {
213                 return false;
214             }
215         }
216     }
217
218     // ---------------------------------------------------------
219     // Obtaining of Nodes
220     // ---------------------------------------------------------
221     /**
222      * Returns a List containing references to all external children of this
223      * PhylogenyNode.
224      * 
225      * @return List of references to external Nodes
226      */
227     final public List<PhylogenyNode> getAllExternalDescendants() {
228         final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
229         if ( isExternal() ) {
230             nodes.add( this );
231             return nodes;
232         }
233         PhylogenyNode node1 = this;
234         while ( !node1.isExternal() ) {
235             node1 = node1.getFirstChildNode();
236         }
237         PhylogenyNode node2 = this;
238         while ( !node2.isExternal() ) {
239             node2 = node2.getLastChildNode();
240         }
241         while ( node1 != node2 ) {
242             nodes.add( node1 );
243             node1 = node1.getNextExternalNode();
244         }
245         nodes.add( node2 );
246         return nodes;
247     }
248
249     /**
250      * Returns a List containing references to all names of the external
251      * children of this PhylogenyNode.
252      * 
253      * @return List of references to names of external Nodes
254      */
255     final public List<String> getAllExternalDescendantsNames() {
256         final List<PhylogenyNode> c = getAllExternalDescendants();
257         final List<String> n = new ArrayList<String>( c.size() );
258         for( final PhylogenyNode phylogenyNode : c ) {
259             n.add( phylogenyNode.getName() );
260         }
261         return n;
262     }
263
264     final public BranchData getBranchData() {
265         if ( _branch_data == null ) {
266             _branch_data = new BranchData();
267         }
268         return _branch_data;
269     }
270
271     final BranchData getBranchDataDirectly() {
272         return _branch_data;
273     }
274
275     /**
276      * This return child node n of this node.
277      * 
278      * @param n
279      *            the index of the child to get
280      * @return the child node with index n
281      * @throws IllegalArgumentException
282      *             if n is out of bounds
283      */
284     @Override
285     final public PhylogenyNode getChildNode( final int i ) {
286         if ( isExternal() ) {
287             throw new UnsupportedOperationException( "attempt to get the child node of an external node." );
288         }
289         if ( ( i >= getNumberOfDescendants() ) || ( i < 0 ) ) {
290             throw new IllegalArgumentException( "attempt to get child node " + i + " of a node with "
291                     + getNumberOfDescendants() + " child nodes" );
292         }
293         return getDescendants().get( i );
294     }
295
296     /**
297      * Convenience method. Returns the first child PhylogenyNode of this
298      * PhylogenyNode.
299      */
300     final public PhylogenyNode getChildNode1() {
301         return getChildNode( 0 );
302     }
303
304     /**
305      * Convenience method. Returns the second child PhylogenyNode of this
306      * PhylogenyNode.
307      * <p>
308      * [last modified May 18, 2005 by CMZ]
309      */
310     final public PhylogenyNode getChildNode2() {
311         return getChildNode( 1 );
312     }
313
314     /**
315      * This gets the child node index of this node.
316      * <p>
317      * 
318      * @return the child node index of this node
319      * @throws UnsupportedOperationException
320      *             if this node is a root node
321      */
322     final public int getChildNodeIndex() {
323         return getChildNodeIndex( getParent() );
324     }
325
326     /**
327      * This gets the child node index of this node, given that parent is its
328      * parent
329      * <p>
330      * [last modified Aug 14, 2006 by CMZ]
331      * 
332      * @return the child node index of this node
333      * @throws UnsupportedOperationException
334      *             if this node is a root node
335      */
336     final public int getChildNodeIndex( final PhylogenyNode parent ) {
337         if ( isRoot() ) {
338             throw new UnsupportedOperationException( "Cannot get the child index for a root node." );
339         }
340         for( int i = 0; i < parent.getNumberOfDescendants(); ++i ) {
341             if ( parent.getChildNode( i ) == this ) {
342                 return i;
343             }
344         }
345         throw new RuntimeException( "Unexpected exception: Could not determine the child index for node: " + this );
346     }
347
348     final public List<PhylogenyNode> getDescendants() {
349         if ( _descendants == null ) {
350             _descendants = new ArrayList<PhylogenyNode>();
351         }
352         return _descendants;
353     }
354
355     /**
356      * Returns the length of the branch leading to the _parent of this
357      * PhylogenyNode (double).
358      */
359     @Override
360     final public double getDistanceToParent() {
361         return _distance_parent;
362     }
363
364     /**
365      * Convenience method. Returns the first child node of this node.
366      * <p>
367      * [last modified May 18, 2005 by CMZ]
368      * 
369      * @return the first child node of this node
370      */
371     public final PhylogenyNode getFirstChildNode() {
372         return getChildNode( 0 );
373     }
374
375     /**
376      * Returns the _indicator value of this PhylogenyNode.
377      */
378     public final byte getIndicator() {
379         return _indicator;
380     }
381
382     /**
383      * Convenience method. Returns the last child node of this node.
384      * <p>
385      * [last modified May 18, 2005 by CMZ]
386      * 
387      * @return the last child node of this node
388      */
389     public final PhylogenyNode getLastChildNode() {
390         return getChildNode( getNumberOfDescendants() - 1 );
391     }
392
393     /**
394      * Returns a refernce to the linked PhylogenyNode of this PhylogenyNode.
395      * Currently, this method is only used for the speciation-_duplication
396      * assignment algorithms.
397      */
398     public final PhylogenyNode getLink() {
399         return _link;
400     }
401
402     /**
403      * Returns a refernce to the next external PhylogenyNode of this
404      * PhylogenyNode. TODO should be in Phylogeny. Returns null if no next
405      * external node is available.
406      */
407     public final PhylogenyNode getNextExternalNode() {
408         if ( isInternal() ) {
409             throw new UnsupportedOperationException( "attempt to get next external node of an internal node" );
410         }
411         else if ( isLastExternalNode() ) {
412             return null;
413         }
414         int index = getChildNodeIndex();
415         PhylogenyNode previous_node = this;
416         PhylogenyNode current_node = getParent();
417         while ( !current_node.isRoot()
418                 && ( ( current_node.getNumberOfDescendants() == 1 ) || previous_node.isLastChildNode() ) ) {
419             index = current_node.getChildNodeIndex();
420             previous_node = current_node;
421             current_node = current_node.getParent();
422         }
423         current_node = current_node.getChildNode( index + 1 );
424         while ( current_node.isInternal() ) {
425             current_node = current_node.getFirstChildNode();
426         }
427         return current_node;
428     }
429
430     public final PhylogenyNode getNextExternalNodeWhileTakingIntoAccountCollapsedNodes() {
431         //TODO work on me ~~
432         if ( isInternal() && !isCollapse() ) {
433             throw new UnsupportedOperationException( "attempt to get next external node of an uncollapsed internal node" );
434         }
435         if ( isRoot() ) {
436             return null;
437         }
438         if ( getParent().isCollapse() ) {
439             throw new UnsupportedOperationException( "attempt to get next external node of node with a collapsed parent" );
440         }
441         // This checks if last node.
442         PhylogenyNode n = this;
443         boolean last = true;
444         while ( !n.isRoot() ) {
445             if ( !n.isLastChildNode() ) {
446                 last = false;
447                 break;
448             }
449             n = n.getParent();
450         }
451         if ( last ) {
452             return null;
453         }
454         int index = getChildNodeIndex();
455         PhylogenyNode previous_node = this;
456         PhylogenyNode current_node = getParent();
457         while ( !current_node.isRoot()
458                 && ( current_node.isCollapse() || ( current_node.getNumberOfDescendants() == 1 ) || previous_node
459                         .isLastChildNode() ) ) {
460             index = current_node.getChildNodeIndex();
461             previous_node = current_node;
462             current_node = current_node.getParent();
463         }
464         if ( index < current_node.getNumberOfDescendants() - 1 ) {
465             current_node = current_node.getChildNode( index + 1 );
466         }
467         while ( current_node.isInternal() && !current_node.isCollapse() ) {
468             current_node = current_node.getFirstChildNode();
469         }
470         return current_node;
471     }
472
473     public final NodeData getNodeData() {
474         if ( _node_data == null ) {
475             _node_data = new NodeData();
476         }
477         return _node_data;
478     }
479
480     final NodeData getNodeDataDirectly() {
481         return _node_data;
482     }
483
484     // ---------------------------------------------------------
485     // Set and get methods for Nodes
486     // ---------------------------------------------------------
487     /**
488      * Returns the ID (int) of this PhylogenyNode.
489      */
490     @Override
491     final public int getId() {
492         return _id;
493     }
494
495     /**
496      * Returns the name of this node.
497      */
498     @Override
499     final public String getName() {
500         return getNodeData().getNodeName();
501     }
502
503     final public List<PhylogenyNode> getAllDescendants() {
504        
505         return _descendants;
506     }
507     
508     
509     final public int getNumberOfDescendants() {
510         if ( _descendants == null ) {
511             return 0;
512         }
513         return _descendants.size();
514     }
515
516     /**
517      * Returns the total number of external Nodes originating from this
518      * PhylogenyNode (int).
519      */
520     final public int getNumberOfExternalNodes() {
521         return _sum_ext_nodes;
522     }
523
524     final public int getNumberOfParents() {
525         return 1;
526     }
527
528     /**
529      * Returns a refernce to the parent PhylogenyNode of this PhylogenyNode.
530      */
531     final public PhylogenyNode getParent() {
532         return _parent;
533     }
534
535     /**
536      * Returns a refernce to the next external PhylogenyNode of this
537      * PhylogenyNode. TODO should be in Phylogeny. Returns null if no next
538      * external node is available.
539      */
540     final public PhylogenyNode getPreviousExternalNode() {
541         if ( isInternal() ) {
542             throw new UnsupportedOperationException( "Cannot get the previous external node for an internal node." );
543         }
544         else if ( isRoot() /* TODO && tree is rooted */) {
545             throw new UnsupportedOperationException( "Cannot get the previous external node for a root node." );
546         }
547         else if ( isFirstExternalNode() ) {
548             throw new UnsupportedOperationException( "Attempt to get previous external node of the first external node." );
549         }
550         int index = getChildNodeIndex();
551         PhylogenyNode previous_node = this;
552         PhylogenyNode current_node = getParent();
553         while ( !current_node.isRoot()
554                 && ( ( current_node.getNumberOfDescendants() == 1 ) || previous_node.isFirstChildNode() ) ) {
555             index = current_node.getChildNodeIndex();
556             previous_node = current_node;
557             current_node = current_node.getParent();
558         }
559         current_node = current_node.getChildNode( index - 1 );
560         while ( current_node.isInternal() ) {
561             current_node = current_node.getLastChildNode();
562         }
563         return current_node;
564     }
565
566     /**
567      * Used for drawing of Trees.
568      */
569     final public float getXcoord() {
570         return _x;
571     }
572
573     final public float getXSecondary() {
574         return _x_secondary;
575     }
576
577     /**
578      * Used for drawing of Trees.
579      */
580     final public float getYcoord() {
581         return _y;
582     }
583
584     final public float getYSecondary() {
585         return _y_secondary;
586     }
587
588     @Override
589     final public int hashCode() {
590         final NodeData data = getNodeData();
591         if ( ( getName().length() < 1 ) && !data.isHasSequence() && !data.isHasTaxonomy() ) {
592             return super.hashCode();
593         }
594         int result = getName().hashCode();
595         if ( data.isHasSequence() ) {
596             result ^= data.getSequence().hashCode();
597         }
598         if ( data.isHasTaxonomy() ) {
599             result ^= data.getTaxonomy().hashCode();
600         }
601         return result;
602     }
603
604     // final private void init() {
605     //_descendants = new ArrayList<PhylogenyNode>();
606     //  _parent = null; //TODO not needed?
607     //  _id = 0; //TODO not needed?
608     //initializeData(); //TODO not needed?
609     //}
610     /**
611      * Deletes data of this PhylogenyNode. Links to the other Nodes in the
612      * Phylogeny, the ID and the sum of external nodes are NOT deleted. Field
613      * "_link" (_link to Nodes in other Phylogeny) IS deleted.
614      * 
615      * @see #getLink() (Last modified: 12/20/03)
616      */
617     //    final private void initializeData() {
618     //        _indicator = 0;
619     //        _x = 0;
620     //        _y = 0;
621     //        //_node_name = "";
622     //        _distance_parent = PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
623     //        _collapse = false;
624     //        _link = null;
625     //        _branch_data = null;
626     //        _node_data = null;
627     //    }
628     /**
629      * Returns whether this PhylogenyNode should be drawn as collapsed.
630      */
631     final public boolean isCollapse() {
632         return _collapse;
633     }
634
635     /**
636      * Returns true if this PhylogenyNode represents a _duplication event, false
637      * otherwise.
638      */
639     final public boolean isDuplication() {
640         return getNodeData().isHasEvent() && getNodeData().getEvent().isDuplication();
641     }
642
643     /**
644      * Checks whether this PhylogenyNode is external (tip).
645      * 
646      * @return true if this PhylogenyNode is external, false otherwise
647      */
648     final public boolean isExternal() {
649         if ( _descendants == null ) {
650             return true;
651         }
652         return ( getNumberOfDescendants() < 1 );
653     }
654
655     /**
656      * DOCUMENT ME!
657      * 
658      * @return DOCUMENT ME!
659      */
660     final public boolean isFirstChildNode() {
661         if ( isRoot() /* and tree is rooted TODO */) {
662             throw new UnsupportedOperationException( "Cannot determine whether the root is the first child node of its _parent." );
663         }
664         return ( getChildNodeIndex() == 0 );
665     }
666
667     /**
668      * DOCUMENT ME!
669      * 
670      * @return DOCUMENT ME!
671      */
672     final public boolean isFirstExternalNode() {
673         if ( isInternal() ) {
674             return false;
675         }
676         PhylogenyNode node = this;
677         while ( !node.isRoot() ) {
678             if ( !node.isFirstChildNode() ) {
679                 return false;
680             }
681             node = node.getParent();
682         }
683         return true;
684     }
685
686     /**
687      * Returns whether a _duplication or speciation event has been assigned for
688      * this PhylogenyNode.
689      */
690     final public boolean isHasAssignedEvent() {
691         if ( !getNodeData().isHasEvent() ) {
692             return false;
693         }
694         if ( ( getNodeData().getEvent() ).isUnassigned() ) {
695             return false;
696         }
697         return true;
698     }
699
700     /**
701      * Checks whether this PhylogenyNode is internal (tip).
702      * 
703      * @return true if this PhylogenyNode is external, false otherwise
704      */
705     final public boolean isInternal() {
706         return ( !isExternal() );
707     }
708
709     /**
710      * Returns true if this node is the last child node of its _parent.
711      * <p>
712      * [last modified June 01, 2005 by CMZ]
713      * 
714      * @return true if this node is the last child node of its _parent, false
715      *         otherwise
716      */
717     final public boolean isLastChildNode() {
718         if ( isRoot() /* and tree is rooted TODO */) {
719             throw new UnsupportedOperationException( "Cannot determine whether the root is the last child node of its _parent." );
720         }
721         return ( getChildNodeIndex() == ( getParent().getNumberOfDescendants() - 1 ) );
722     }
723
724     /**
725      * DOCUMENT ME!
726      * 
727      * @return DOCUMENT ME!
728      */
729     final public boolean isLastExternalNode() {
730         if ( isInternal() ) {
731             return false;
732         }
733         PhylogenyNode node = this;
734         while ( !node.isRoot() ) {
735             if ( !node.isLastChildNode() ) {
736                 return false;
737             }
738             node = node.getParent();
739         }
740         return true;
741     }
742
743     /**
744      * Checks whether this PhylogenyNode is a root.
745      * 
746      * @return true if this PhylogenyNode is the root, false otherwise
747      */
748     final public boolean isRoot() {
749         return _parent == null;
750     }
751
752     final public boolean isSpeciation() {
753         return getNodeData().isHasEvent() && getNodeData().getEvent().isSpeciation();
754     }
755
756     // ---------------------------------------------------------
757     // Basic printing
758     // ---------------------------------------------------------
759     /**
760      * Prints to the console the subtree originating from this PhylogenyNode in
761      * preorder.
762      */
763     public void preorderPrint() {
764         System.out.println( this + "\n" );
765         if ( isInternal() ) {
766             for( int i = 0; i < getNumberOfDescendants(); ++i ) {
767                 getChildNode( i ).preorderPrint();
768             }
769         }
770     }
771
772     final public void removeChildNode( final int i ) {
773         if ( isExternal() ) {
774             throw new UnsupportedOperationException( "cannot get the child node for a external node." );
775         }
776         if ( ( i >= getNumberOfDescendants() ) || ( i < 0 ) ) {
777             throw new IllegalArgumentException( "attempt to get child node " + i + " of a node with "
778                     + getNumberOfDescendants() + " child nodes." );
779         }
780         getDescendants().remove( i );
781     }
782
783     final public void removeChildNode( final PhylogenyNode remove_me ) {
784         removeChildNode( remove_me.getChildNodeIndex() );
785     }
786
787     final public void setBranchData( final BranchData branch_data ) {
788         _branch_data = branch_data;
789     }
790
791     /**
792      * Sets the first child PhylogenyNode of this PhylogenyNode to n.
793      */
794     final public void setChild1( final PhylogenyNode n ) {
795         setChildNode( 0, n );
796     }
797
798     /**
799      * Sets the second child PhylogenyNode of this PhylogenyNode to n.
800      */
801     final public void setChild2( final PhylogenyNode n ) {
802         setChildNode( 1, n );
803     }
804
805     /**
806      * Inserts PhylogenyNode n at the specified position i into the list of
807      * child nodes. This does not allow null slots in the list of child nodes:
808      * If i is larger than the number of child nodes, n is just added to the
809      * list, not place at index i.
810      * 
811      * @param i
812      *            the index of position where to add the child
813      * @param n
814      *            the PhylogenyNode to add
815      */
816     final public void setChildNode( final int i, final PhylogenyNode node ) {
817         node.setParent( this );
818         if ( getNumberOfDescendants() <= i ) {
819             addChildNode( node );
820         }
821         else {
822             getDescendants().set( i, node );
823         }
824     }
825
826     final void setChildNodeOnly( final int i, final PhylogenyNode node ) {
827         if ( getNumberOfDescendants() <= i ) {
828             addChildNode( node );
829         }
830         else {
831             getDescendants().set( i, node );
832         }
833     }
834
835     /**
836      * Sets whether this PhylogenyNode should be drawn as collapsed.
837      */
838     final public void setCollapse( final boolean b ) {
839         _collapse = b;
840     }
841
842     /**
843      * Sets the length of the branch leading to the _parent of this
844      * PhylogenyNode to double d.
845      */
846     @Override
847     final public void setDistanceToParent( final double d ) {
848         _distance_parent = d;
849     }
850
851     /**
852      * Sets the _indicator value of this PhylogenyNode to i.
853      */
854     final public void setIndicator( final byte i ) {
855         _indicator = i;
856     }
857
858     // --------------------------------------------------------------------
859     // Adjust methods (related to Phylogeny construction and
860     // Phylogeny modification)
861     // --------------------------------------------------------------------
862     /**
863      * Sets the indicators of all the children of this PhylogenyNode to zero.
864      */
865     final void setIndicatorsToZero() {
866         for( final PreorderTreeIterator it = new PreorderTreeIterator( this ); it.hasNext(); ) {
867             it.next().setIndicator( ( byte ) 0 );
868         }
869     }
870
871     /**
872      * Sets the linked PhylogenyNode of this PhylogenyNode to n. Currently, this
873      * method is only used for the speciation-_duplication assignment
874      * algorithms.
875      */
876     final public void setLink( final PhylogenyNode n ) {
877         _link = n;
878     }
879
880     /**
881      * Sets the name of this node.
882      */
883     @Override
884     final public void setName( final String node_name ) {
885         getNodeData().setNodeName( node_name );
886     }
887
888     /**
889      * Sets the Id of this PhylogenyNode to i. In most cases, this number
890      * should not be set to values lower than getNodeCount() -- which this method
891      * does not allow.
892      */
893     synchronized final protected void setId( final int i ) {
894         if ( i < getNodeCount() ) {
895             throw new IllegalArgumentException( "attempt to set node id to a value less than total node count (thus violating the uniqueness of node ids)" );
896         }
897         _id = i;
898     }
899
900     /**
901      * Sets the _parent PhylogenyNode of this PhylogenyNode to n.
902      */
903     @Override
904     final public void setParent( final PhylogenyNode n ) {
905         _parent = n;
906     }
907
908     /**
909      * Sets the total number of external Nodes originating from this
910      * PhylogenyNode to i (int).
911      */
912     final public void setSumExtNodes( final int i ) {
913         if ( i < 0 ) {
914             throw new IllegalArgumentException( "attempt to set sum of external nodes to less than one" );
915         }
916         _sum_ext_nodes = i;
917     }
918
919     /**
920      * Used for drawing of Trees.
921      */
922     final public void setXcoord( final float x ) {
923         _x = x;
924     }
925
926     final public void setXSecondary( final float x_secondary ) {
927         _x_secondary = x_secondary;
928     }
929
930     // -----------
931     /**
932      * Used for drawing of Trees.
933      */
934     final public void setYcoord( final float y ) {
935         _y = y;
936     }
937
938     final public void setYSecondary( final float y_secondary ) {
939         _y_secondary = y_secondary;
940     }
941
942     // ---------------------------------------------------------
943     // Writing of Nodes to Strings
944     // ---------------------------------------------------------
945     final public String toNewHampshire( final boolean simple_nh,
946                                         final boolean write_distance_to_parent,
947                                         final NH_CONVERSION_SUPPORT_VALUE_STYLE svs ) {
948         final StringBuilder sb = new StringBuilder();
949         String data = "";
950         if ( ( svs == NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES ) && !isExternal() ) {
951             if ( getBranchData().isHasConfidences()
952                     && ( getBranchData().getConfidence( 0 ).getValue() != Confidence.CONFIDENCE_DEFAULT_VALUE ) ) {
953                 data = Confidence.FORMATTER.format( ForesterUtil
954                         .round( getBranchData().getConfidence( 0 ).getValue(),
955                                 PhyloXmlUtil.ROUNDING_DIGITS_FOR_PHYLOXML_DOUBLE_OUTPUT ) );
956             }
957         }
958         else if ( !ForesterUtil.isEmpty( getName() ) ) {
959             data = getName();
960         }
961         else if ( getNodeData().isHasTaxonomy() ) {
962             if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
963                 data = getNodeData().getTaxonomy().getTaxonomyCode();
964             }
965             else if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getScientificName() ) ) {
966                 data = getNodeData().getTaxonomy().getScientificName();
967             }
968             else if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getCommonName() ) ) {
969                 data = getNodeData().getTaxonomy().getCommonName();
970             }
971             else if ( getNodeData().getTaxonomy().getTaxonomyCode() != null ) {
972                 data = getNodeData().getTaxonomy().getTaxonomyCode();
973             }
974         }
975         else if ( getNodeData().isHasSequence() ) {
976             if ( !ForesterUtil.isEmpty( getNodeData().getSequence().getName() ) ) {
977                 data = getNodeData().getSequence().getName();
978             }
979         }
980         if ( data.length() > 0 ) {
981             data = ForesterUtil.replaceIllegalNhCharacters( data );
982             if ( simple_nh && ( data.length() > 10 ) ) {
983                 data = data.substring( 0, 11 );
984             }
985             if ( ForesterUtil.isContainsParanthesesableNhCharacter( data ) ) {
986                 sb.append( '\'' );
987                 sb.append( data );
988                 sb.append( '\'' );
989             }
990             else {
991                 sb.append( data );
992             }
993         }
994         if ( write_distance_to_parent && ( getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) ) {
995             sb.append( ":" );
996             sb.append( getDistanceToParent() );
997         }
998         if ( ( svs == NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS ) && !isExternal()
999                 && getBranchData().isHasConfidences()
1000                 && ( getBranchData().getConfidence( 0 ).getValue() != Confidence.CONFIDENCE_DEFAULT_VALUE ) ) {
1001             sb.append( "[" );
1002             sb.append( Confidence.FORMATTER.format( ForesterUtil
1003                     .round( getBranchData().getConfidence( 0 ).getValue(),
1004                             PhyloXmlUtil.ROUNDING_DIGITS_FOR_PHYLOXML_DOUBLE_OUTPUT ) ) );
1005             sb.append( "]" );
1006         }
1007         return sb.toString();
1008     }
1009
1010     /**
1011      * Swaps the the two childern of a PhylogenyNode node of this Phylogeny.
1012      */
1013     public final void swapChildren() throws RuntimeException {
1014         if ( isExternal() ) {
1015             throw new RuntimeException( "attempt to swap descendants of external node" );
1016         }
1017         if ( getNumberOfDescendants() != 2 ) {
1018             throw new RuntimeException( "attempt to swap descendants of node with " + getNumberOfDescendants()
1019                     + " descendants" );
1020         }
1021         final PhylogenyNode a = getChildNode( 0 );
1022         final PhylogenyNode b = getChildNode( 1 );
1023         setChildNode( 0, b );
1024         setChildNode( 1, a );
1025     }
1026
1027     /**
1028      * Converts this PhylogenyNode to a New Hampshire X (NHX) String
1029      * representation.
1030      */
1031     final public String toNewHampshireX() {
1032         final StringBuffer sb = new StringBuffer();
1033         final StringBuffer s_nhx = new StringBuffer();
1034         if ( !ForesterUtil.isEmpty( getName() ) ) {
1035             final String name = ForesterUtil.replaceIllegalNhCharacters( getName() );
1036             if ( ForesterUtil.isContainsParanthesesableNhCharacter( name ) ) {
1037                 sb.append( '\'' );
1038                 sb.append( name );
1039                 sb.append( '\'' );
1040             }
1041             else {
1042                 sb.append( name );
1043             }
1044         }
1045         if ( getDistanceToParent() != PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
1046             sb.append( ":" );
1047             sb.append( getDistanceToParent() );
1048         }
1049         if ( getNodeDataDirectly() != null ) {
1050             s_nhx.append( getNodeDataDirectly().toNHX() );
1051         }
1052         if ( getBranchDataDirectly() != null ) {
1053             s_nhx.append( getBranchDataDirectly().toNHX() );
1054         }
1055         if ( s_nhx.length() > 0 ) {
1056             sb.append( "[&&NHX" );
1057             sb.append( s_nhx );
1058             sb.append( "]" );
1059         }
1060         return sb.toString();
1061     }
1062
1063     @Override
1064     final public String toString() {
1065         final StringBuilder sb = new StringBuilder();
1066         if ( !ForesterUtil.isEmpty( getName() ) ) {
1067             sb.append( getName() );
1068             sb.append( " " );
1069         }
1070         if ( getNodeData().isHasTaxonomy() ) {
1071             if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getScientificName() ) ) {
1072                 sb.append( getNodeData().getTaxonomy().getScientificName() );
1073                 sb.append( " " );
1074             }
1075             else if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
1076                 sb.append( getNodeData().getTaxonomy().getTaxonomyCode() );
1077                 sb.append( " " );
1078             }
1079             else if ( getNodeData().getTaxonomy().getIdentifier() != null ) {
1080                 sb.append( getNodeData().getTaxonomy().getIdentifier().toString() );
1081                 sb.append( " " );
1082             }
1083         }
1084         if ( getNodeData().isHasSequence() ) {
1085             if ( !ForesterUtil.isEmpty( getNodeData().getSequence().getName() ) ) {
1086                 sb.append( getNodeData().getSequence().getName() );
1087                 sb.append( " " );
1088             }
1089             else if ( !ForesterUtil.isEmpty( getNodeData().getSequence().getSymbol() ) ) {
1090                 sb.append( getNodeData().getSequence().getSymbol() );
1091                 sb.append( " " );
1092             }
1093             else if ( getNodeData().getSequence().getAccession() != null ) {
1094                 sb.append( getNodeData().getTaxonomy().getIdentifier().toString() );
1095                 sb.append( " " );
1096             }
1097         }
1098         if ( sb.length() <= 1 ) {
1099             sb.append( "[" );
1100             sb.append( getId() );
1101             sb.append( "]" );
1102         }
1103         return sb.toString().trim();
1104     }
1105
1106     /**
1107      * Decreases the total number of all Nodes created so far by one.
1108      */
1109     final static synchronized void decreaseNodeCount() {
1110         --PhylogenyNode._node_count;
1111     }
1112
1113     /**
1114      * Returns the total number of all Nodes created so far.
1115      * 
1116      * @return total number of Nodes (int)
1117      */
1118     synchronized final public static int getNodeCount() {
1119         return PhylogenyNode._node_count;
1120     }
1121
1122     /**
1123      * Increases the total number of all Nodes created so far by one.
1124      */
1125     synchronized final private static void increaseNodeCount() {
1126         ++PhylogenyNode._node_count;
1127     }
1128
1129     /**
1130      * Sets the total number of all Nodes created so far to i (int).
1131      */
1132     synchronized final static void setNodeCount( final int i ) {
1133         PhylogenyNode._node_count = i;
1134     }
1135
1136     public static PhylogenyNode createInstanceFromNhxString( final String nhx ) throws NHXFormatException,
1137             PhyloXmlDataFormatException {
1138         return new PhylogenyNode( nhx, PhylogenyMethods.TAXONOMY_EXTRACTION.NO, false );
1139     }
1140
1141     public static PhylogenyNode createInstanceFromNhxString( final String nhx,
1142                                                              final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction )
1143             throws NHXFormatException, PhyloXmlDataFormatException {
1144         return new PhylogenyNode( nhx, taxonomy_extraction, false );
1145     }
1146
1147     public static PhylogenyNode createInstanceFromNhxString( final String nhx,
1148                                                              final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
1149                                                              final boolean replace_underscores )
1150             throws NHXFormatException, PhyloXmlDataFormatException {
1151         return new PhylogenyNode( nhx, taxonomy_extraction, replace_underscores );
1152     }
1153
1154     private PhylogenyNode( final String nhx,
1155                            final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
1156                            final boolean replace_underscores ) throws NHXFormatException, PhyloXmlDataFormatException {
1157         //  init();
1158         NHXParser.parseNHX( nhx, this, taxonomy_extraction, replace_underscores );
1159         setId( PhylogenyNode.getNodeCount() );
1160         PhylogenyNode.increaseNodeCount();
1161         setSumExtNodes( 1 ); // For ext node, this number is 1 (not 0!!)
1162     }
1163 }