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