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