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