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