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