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