c3411086cf3ff5789d3163ab828accc29a23b8e4
[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.NodeData;
37 import org.forester.phylogeny.iterators.ChildNodeIteratorForward;
38 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
39 import org.forester.phylogeny.iterators.PreorderTreeIterator;
40 import org.forester.util.ForesterUtil;
41
42 public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode> {
43
44     /** Value of -99.0 is used as default value. */
45     public final static double       DISTANCE_DEFAULT = -1024.0;
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() ) {
417             throw new UnsupportedOperationException( "attempt to get next external node of an internal node" );
418         }
419         else if ( isLastExternalNode() ) {
420             return null;
421         }
422         int index = getChildNodeIndex();
423         PhylogenyNode previous_node = this;
424         PhylogenyNode current_node = getParent();
425         while ( !current_node.isRoot()
426                 && ( ( current_node.getNumberOfDescendants() == 1 ) || previous_node.isLastChildNode() ) ) {
427             index = current_node.getChildNodeIndex();
428             previous_node = current_node;
429             current_node = current_node.getParent();
430         }
431         current_node = current_node.getChildNode( index + 1 );
432         while ( current_node.isInternal() ) {
433             current_node = current_node.getFirstChildNode();
434         }
435         return current_node;
436     }
437     
438     public final NodeData getNodeData() {
439         if ( _node_data == null ) {
440             _node_data = new NodeData();
441         }
442         return _node_data;
443     }
444
445     final NodeData getNodeDataDirectly() {
446         return _node_data;
447     }
448
449     // ---------------------------------------------------------
450     // Set and get methods for Nodes
451     // ---------------------------------------------------------
452     /**
453      * Returns the ID (int) of this PhylogenyNode.
454      */
455     @Override
456     final public int getId() {
457         return _id;
458     }
459
460     /**
461      * Returns the name of this node.
462      */
463     @Override
464     final public String getName() {
465         return getNodeData().getNodeName();
466     }
467
468     final public int getNumberOfDescendants() {
469         return _descendants.size();
470     }
471
472     /**
473      * Returns the total number of external Nodes originating from this
474      * PhylogenyNode (int).
475      */
476     final public int getNumberOfExternalNodes() {
477         return _sum_ext_nodes;
478     }
479
480     final public int getNumberOfParents() {
481         return 1;
482     }
483
484     /**
485      * Returns a refernce to the parent PhylogenyNode of this PhylogenyNode.
486      */
487     final public PhylogenyNode getParent() {
488         return _parent;
489     }
490
491     /**
492      * Returns a refernce to the next external PhylogenyNode of this
493      * PhylogenyNode. TODO should be in Phylogeny. Returns null if no next
494      * external node is available.
495      */
496     final public PhylogenyNode getPreviousExternalNode() {
497         if ( isInternal() ) {
498             throw new UnsupportedOperationException( "Cannot get the previous external node for an internal node." );
499         }
500         else if ( isRoot() /* TODO && tree is rooted */) {
501             throw new UnsupportedOperationException( "Cannot get the previous external node for a root node." );
502         }
503         else if ( isFirstExternalNode() ) {
504             throw new UnsupportedOperationException( "Attempt to get previous external node of the first external node." );
505         }
506         int index = getChildNodeIndex();
507         PhylogenyNode previous_node = this;
508         PhylogenyNode current_node = getParent();
509         while ( !current_node.isRoot()
510                 && ( ( current_node.getNumberOfDescendants() == 1 ) || previous_node.isFirstChildNode() ) ) {
511             index = current_node.getChildNodeIndex();
512             previous_node = current_node;
513             current_node = current_node.getParent();
514         }
515         current_node = current_node.getChildNode( index - 1 );
516         while ( current_node.isInternal() ) {
517             current_node = current_node.getLastChildNode();
518         }
519         return current_node;
520     }
521
522     /**
523      * Used for drawing of Trees.
524      */
525     final public float getXcoord() {
526         return _x;
527     }
528
529     final public float getXSecondary() {
530         return _x_secondary;
531     }
532
533     /**
534      * Used for drawing of Trees.
535      */
536     final public float getYcoord() {
537         return _y;
538     }
539
540     final public float getYSecondary() {
541         return _y_secondary;
542     }
543
544     @Override
545     final public int hashCode() {
546         final NodeData data = getNodeData();
547         if ( ( getName().length() < 1 ) && !data.isHasSequence() && !data.isHasTaxonomy() ) {
548             return super.hashCode();
549         }
550         int result = getName().hashCode();
551         if ( data.isHasSequence() ) {
552             result ^= data.getSequence().hashCode();
553         }
554         if ( data.isHasTaxonomy() ) {
555             result ^= data.getTaxonomy().hashCode();
556         }
557         return result;
558     }
559
560     final private void init() {
561         _descendants = new ArrayList<PhylogenyNode>();
562         _parent = null;
563         _id = 0;
564         initializeData();
565     }
566
567     /**
568      * Deletes data of this PhylogenyNode. Links to the other Nodes in the
569      * Phylogeny, the ID and the sum of external nodes are NOT deleted. Field
570      * "_link" (_link to Nodes in other Phylogeny) IS deleted.
571      * 
572      * @see #getLink() (Last modified: 12/20/03)
573      */
574     final public void initializeData() {
575         _indicator = 0;
576         _x = 0;
577         _y = 0;
578         //_node_name = "";
579         _distance_parent = PhylogenyNode.DISTANCE_DEFAULT;
580         _collapse = false;
581         _link = null;
582         _branch_data = null;
583         _node_data = null;
584     }
585
586     /**
587      * Returns whether this PhylogenyNode should be drawn as collapsed.
588      */
589     final public boolean isCollapse() {
590         return _collapse;
591     }
592
593     /**
594      * Returns true if this PhylogenyNode represents a _duplication event, false
595      * otherwise.
596      */
597     final public boolean isDuplication() {
598         return getNodeData().isHasEvent() && getNodeData().getEvent().isDuplication();
599     }
600
601     /**
602      * Checks whether this PhylogenyNode is external (tip).
603      * 
604      * @return true if this PhylogenyNode is external, false otherwise
605      */
606     final public boolean isExternal() {
607         return ( getNumberOfDescendants() < 1 );
608     }
609
610     /**
611      * DOCUMENT ME!
612      * 
613      * @return DOCUMENT ME!
614      */
615     final public boolean isFirstChildNode() {
616         if ( isRoot() /* and tree is rooted TODO */) {
617             throw new UnsupportedOperationException( "Cannot determine whether the root is the first child node of its _parent." );
618         }
619         return ( getChildNodeIndex() == 0 );
620     }
621
622     /**
623      * DOCUMENT ME!
624      * 
625      * @return DOCUMENT ME!
626      */
627     final public boolean isFirstExternalNode() {
628         if ( isInternal() ) {
629             return false;
630         }
631         PhylogenyNode node = this;
632         while ( !node.isRoot() ) {
633             if ( !node.isFirstChildNode() ) {
634                 return false;
635             }
636             node = node.getParent();
637         }
638         return true;
639     }
640
641     /**
642      * Returns whether a _duplication or speciation event has been assigned for
643      * this PhylogenyNode.
644      */
645     final public boolean isHasAssignedEvent() {
646         if ( !getNodeData().isHasEvent() ) {
647             return false;
648         }
649         if ( ( getNodeData().getEvent() ).isUnassigned() ) {
650             return false;
651         }
652         return true;
653     }
654
655     /**
656      * Checks whether this PhylogenyNode is internal (tip).
657      * 
658      * @return true if this PhylogenyNode is external, false otherwise
659      */
660     final public boolean isInternal() {
661         return ( !isExternal() );
662     }
663
664     /**
665      * Returns true if this node is the last child node of its _parent.
666      * <p>
667      * [last modified June 01, 2005 by CMZ]
668      * 
669      * @return true if this node is the last child node of its _parent, false
670      *         otherwise
671      */
672     final public boolean isLastChildNode() {
673         if ( isRoot() /* and tree is rooted TODO */) {
674             throw new UnsupportedOperationException( "Cannot determine whether the root is the last child node of its _parent." );
675         }
676         return ( getChildNodeIndex() == ( getParent().getNumberOfDescendants() - 1 ) );
677     }
678
679     /**
680      * DOCUMENT ME!
681      * 
682      * @return DOCUMENT ME!
683      */
684     final public boolean isLastExternalNode() {
685         if ( isInternal() ) {
686             return false;
687         }
688         PhylogenyNode node = this;
689         while ( !node.isRoot() ) {
690             if ( !node.isLastChildNode() ) {
691                 return false;
692             }
693             node = node.getParent();
694         }
695         return true;
696     }
697
698     /**
699      * Checks whether this PhylogenyNode is a root.
700      * 
701      * @return true if this PhylogenyNode is the root, false otherwise
702      */
703     final public boolean isRoot() {
704         return _parent == null;
705     }
706
707     final public boolean isSpeciation() {
708         return getNodeData().isHasEvent() && getNodeData().getEvent().isSpeciation();
709     }
710
711     // ---------------------------------------------------------
712     // Iterator
713     // ---------------------------------------------------------
714     final public PhylogenyNodeIterator iterateChildNodesForward() {
715         return new ChildNodeIteratorForward( this );
716     }
717
718     // ---------------------------------------------------------
719     // Basic printing
720     // ---------------------------------------------------------
721     /**
722      * Prints to the console the subtree originating from this PhylogenyNode in
723      * preorder.
724      */
725     public void preorderPrint() {
726         System.out.println( this + "\n" );
727         if ( isInternal() ) {
728             for( int i = 0; i < getNumberOfDescendants(); ++i ) {
729                 getChildNode( i ).preorderPrint();
730             }
731         }
732     }
733
734     final public void removeChildNode( final int i ) {
735         if ( isExternal() ) {
736             throw new UnsupportedOperationException( "cannot get the child node for a external node." );
737         }
738         if ( ( i >= getNumberOfDescendants() ) || ( i < 0 ) ) {
739             throw new IllegalArgumentException( "attempt to get child node " + i + " of a node with "
740                     + getNumberOfDescendants() + " child nodes." );
741         }
742         getDescendants().remove( i );
743     }
744
745     final public void removeChildNode( final PhylogenyNode remove_me ) {
746         removeChildNode( remove_me.getChildNodeIndex() );
747     }
748
749     final public void setBranchData( final BranchData branch_data ) {
750         _branch_data = branch_data;
751     }
752
753     /**
754      * Sets the first child PhylogenyNode of this PhylogenyNode to n.
755      */
756     final public void setChild1( final PhylogenyNode n ) {
757         setChildNode( 0, n );
758     }
759
760     /**
761      * Sets the second child PhylogenyNode of this PhylogenyNode to n.
762      */
763     final public void setChild2( final PhylogenyNode n ) {
764         setChildNode( 1, n );
765     }
766
767     /**
768      * Inserts PhylogenyNode n at the specified position i into the list of
769      * child nodes. This does not allow null slots in the list of child nodes:
770      * If i is larger than the number of child nodes, n is just added to the
771      * list, not place at index i.
772      * 
773      * @param i
774      *            the index of position where to add the child
775      * @param n
776      *            the PhylogenyNode to add
777      */
778     final public void setChildNode( final int i, final PhylogenyNode node ) {
779         node.setParent( this );
780         if ( getNumberOfDescendants() <= i ) {
781             addChildNode( node );
782         }
783         else {
784             getDescendants().set( i, node );
785         }
786     }
787
788     final void setChildNodeOnly( final int i, final PhylogenyNode node ) {
789         if ( getNumberOfDescendants() <= i ) {
790             addChildNode( node );
791         }
792         else {
793             getDescendants().set( i, node );
794         }
795     }
796
797     /**
798      * Sets whether this PhylogenyNode should be drawn as collapsed.
799      */
800     final public void setCollapse( final boolean b ) {
801         _collapse = b;
802     }
803
804     /**
805      * Sets the length of the branch leading to the _parent of this
806      * PhylogenyNode to double d.
807      */
808     @Override
809     final public void setDistanceToParent( final double d ) {
810         _distance_parent = d;
811     }
812
813     /**
814      * Sets the _indicator value of this PhylogenyNode to i.
815      */
816     final public void setIndicator( final byte i ) {
817         _indicator = i;
818     }
819
820     // --------------------------------------------------------------------
821     // Adjust methods (related to Phylogeny construction and
822     // Phylogeny modification)
823     // --------------------------------------------------------------------
824     /**
825      * Sets the indicators of all the children of this PhylogenyNode to zero.
826      */
827     final void setIndicatorsToZero() {
828         for( final PreorderTreeIterator it = new PreorderTreeIterator( this ); it.hasNext(); ) {
829             it.next().setIndicator( ( byte ) 0 );
830         }
831     }
832
833     /**
834      * Sets the linked PhylogenyNode of this PhylogenyNode to n. Currently, this
835      * method is only used for the speciation-_duplication assignment
836      * algorithms.
837      */
838     final public void setLink( final PhylogenyNode n ) {
839         _link = n;
840     }
841
842     /**
843      * Sets the name of this node.
844      */
845     @Override
846     final public void setName( final String node_name ) {
847         getNodeData().setNodeName( node_name );
848     }
849
850     /**
851      * Sets the Id of this PhylogenyNode to i. In most cases, this number
852      * should not be set to values lower than getNodeCount() -- which this method
853      * does not allow.
854      */
855     synchronized final protected void setId( final int i ) {
856         if ( i < getNodeCount() ) {
857             throw new IllegalArgumentException( "attempt to set node id to a value less than total node count (thus violating the uniqueness of node ids)" );
858         }
859         _id = i;
860     }
861
862     /**
863      * Sets the _parent PhylogenyNode of this PhylogenyNode to n.
864      */
865     @Override
866     final public void setParent( final PhylogenyNode n ) {
867         _parent = n;
868     }
869
870     /**
871      * Sets the total number of external Nodes originating from this
872      * PhylogenyNode to i (int).
873      */
874     final public void setSumExtNodes( final int i ) {
875         if ( i < 0 ) {
876             throw new IllegalArgumentException( "attempt to set sum of external nodes to less than one" );
877         }
878         _sum_ext_nodes = i;
879     }
880
881     /**
882      * Used for drawing of Trees.
883      */
884     final public void setXcoord( final float x ) {
885         _x = x;
886     }
887
888     final public void setXSecondary( final float x_secondary ) {
889         _x_secondary = x_secondary;
890     }
891
892     // -----------
893     /**
894      * Used for drawing of Trees.
895      */
896     final public void setYcoord( final float y ) {
897         _y = y;
898     }
899
900     final public void setYSecondary( final float y_secondary ) {
901         _y_secondary = y_secondary;
902     }
903
904     // ---------------------------------------------------------
905     // Writing of Nodes to Strings
906     // ---------------------------------------------------------
907     final public String toNewHampshire( final boolean simple_nh, final boolean write_distance_to_parent ) {
908         final StringBuilder sb = new StringBuilder();
909         String data = "";
910         if ( !ForesterUtil.isEmpty( getName() ) ) {
911             data = getName();
912         }
913         else if ( getNodeData().isHasTaxonomy() ) {
914             if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
915                 data = getNodeData().getTaxonomy().getTaxonomyCode();
916             }
917             else if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getScientificName() ) ) {
918                 data = getNodeData().getTaxonomy().getScientificName();
919             }
920             else if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getCommonName() ) ) {
921                 data = getNodeData().getTaxonomy().getCommonName();
922             }
923             else if ( getNodeData().getTaxonomy().getTaxonomyCode() != null ) {
924                 data = getNodeData().getTaxonomy().getTaxonomyCode();
925             }
926         }
927         else if ( getNodeData().isHasSequence() ) {
928             if ( !ForesterUtil.isEmpty( getNodeData().getSequence().getName() ) ) {
929                 data = getNodeData().getSequence().getName();
930             }
931         }
932         if ( data.length() > 0 ) {
933             data = ForesterUtil.replaceIllegalNhCharacters( data );
934             if ( simple_nh && ( data.length() > 10 ) ) {
935                 data = data.substring( 0, 11 );
936             }
937             if ( ForesterUtil.isContainsParanthesesableNhCharacter( data ) ) {
938                 sb.append( '\'' );
939                 sb.append( data );
940                 sb.append( '\'' );
941             }
942             else {
943                 sb.append( data );
944             }
945         }
946         if ( ( getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT ) && write_distance_to_parent ) {
947             sb.append( ":" );
948             sb.append( getDistanceToParent() );
949         }
950         return sb.toString();
951     }
952
953     /**
954      * Converts this PhylogenyNode to a New Hampshire X (NHX) String
955      * representation.
956      */
957     final public String toNewHampshireX() {
958         final StringBuffer sb = new StringBuffer();
959         final StringBuffer s_nhx = new StringBuffer();
960         if ( !ForesterUtil.isEmpty( getName() ) ) {
961             final String name = ForesterUtil.replaceIllegalNhCharacters( getName() );
962             if ( ForesterUtil.isContainsParanthesesableNhCharacter( name ) ) {
963                 sb.append( '\'' );
964                 sb.append( name );
965                 sb.append( '\'' );
966             }
967             else {
968                 sb.append( name );
969             }
970         }
971         if ( getDistanceToParent() != PhylogenyNode.DISTANCE_DEFAULT ) {
972             sb.append( ":" );
973             sb.append( getDistanceToParent() );
974         }
975         if ( getNodeDataDirectly() != null ) {
976             s_nhx.append( getNodeDataDirectly().toNHX() );
977         }
978         if ( getBranchDataDirectly() != null ) {
979             s_nhx.append( getBranchDataDirectly().toNHX() );
980         }
981         if ( s_nhx.length() > 0 ) {
982             sb.append( "[&&NHX" );
983             sb.append( s_nhx );
984             sb.append( "]" );
985         }
986         return sb.toString();
987     }
988
989     @Override
990     final public String toString() {
991         final StringBuilder sb = new StringBuilder();
992         if ( !ForesterUtil.isEmpty( getName() ) ) {
993             sb.append( getName() );
994             sb.append( " " );
995         }
996         sb.append( "[" );
997         sb.append( getId() );
998         sb.append( "]" );
999         return sb.toString();
1000     }
1001
1002     /**
1003      * Decreases the total number of all Nodes created so far by one.
1004      */
1005     final static synchronized void decreaseNodeCount() {
1006         --PhylogenyNode._node_count;
1007     }
1008
1009     /**
1010      * Returns the total number of all Nodes created so far.
1011      * 
1012      * @return total number of Nodes (int)
1013      */
1014     synchronized final public static int getNodeCount() {
1015         return PhylogenyNode._node_count;
1016     }
1017
1018     /**
1019      * Increases the total number of all Nodes created so far by one.
1020      */
1021     synchronized final private static void increaseNodeCount() {
1022         ++PhylogenyNode._node_count;
1023     }
1024
1025     /**
1026      * Sets the total number of all Nodes created so far to i (int).
1027      */
1028     synchronized final static void setNodeCount( final int i ) {
1029         PhylogenyNode._node_count = i;
1030     }
1031
1032     public static PhylogenyNode createInstanceFromNhxString( final String nhx ) throws NHXFormatException {
1033         return new PhylogenyNode( nhx, ForesterUtil.TAXONOMY_EXTRACTION.NO, false );
1034     }
1035
1036     public static PhylogenyNode createInstanceFromNhxString( final String nhx,
1037                                                              final ForesterUtil.TAXONOMY_EXTRACTION taxonomy_extraction )
1038             throws NHXFormatException {
1039         return new PhylogenyNode( nhx, taxonomy_extraction, false );
1040     }
1041
1042     public static PhylogenyNode createInstanceFromNhxString( final String nhx,
1043                                                              final ForesterUtil.TAXONOMY_EXTRACTION taxonomy_extraction,
1044                                                              final boolean replace_underscores )
1045             throws NHXFormatException {
1046         return new PhylogenyNode( nhx, taxonomy_extraction, replace_underscores );
1047     }
1048
1049     private PhylogenyNode( final String nhx,
1050                            final ForesterUtil.TAXONOMY_EXTRACTION taxonomy_extraction,
1051                            final boolean replace_underscores ) throws NHXFormatException {
1052         init();
1053         NHXParser.parseNHX( nhx, this, taxonomy_extraction, replace_underscores );
1054         setId( PhylogenyNode.getNodeCount() );
1055         PhylogenyNode.increaseNodeCount();
1056         setSumExtNodes( 1 ); // For ext node, this number is 1 (not 0!!)
1057     }
1058 }