inprogress
[jalview.git] / forester / java / src / org / forester / phylogeny / PhylogenyNode.java
index a11fbd0..3994605 100644 (file)
@@ -23,7 +23,7 @@
 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
 //
 // Contact: phylosoft @ gmail . com
-// WWW: www.phylosoft.org/forester
+// WWW: https://sites.google.com/site/cmzmasek/home/software/forester
 
 package org.forester.phylogeny;
 
@@ -32,24 +32,33 @@ import java.util.List;
 
 import org.forester.io.parsers.nhx.NHXFormatException;
 import org.forester.io.parsers.nhx.NHXParser;
+import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
+import org.forester.io.parsers.phyloxml.PhyloXmlUtil;
 import org.forester.phylogeny.data.BranchData;
 import org.forester.phylogeny.data.Confidence;
 import org.forester.phylogeny.data.NodeData;
 import org.forester.phylogeny.data.PhylogenyDataUtil;
-import org.forester.phylogeny.iterators.ChildNodeIteratorForward;
-import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
 import org.forester.phylogeny.iterators.PreorderTreeIterator;
 import org.forester.util.ForesterUtil;
 
-public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode> {
+/**
+ * Warning. Implementation of method 'compareTo' only looks at 
+ * node name. Thus, use of this class in SortedSets might lead
+ * to unexpected behavior.
+ *
+ */
+public final class PhylogenyNode implements Comparable<PhylogenyNode> {
 
-    private static int               _node_count = 0;
+    public enum NH_CONVERSION_SUPPORT_VALUE_STYLE {
+        NONE, IN_SQUARE_BRACKETS, AS_INTERNAL_NODE_NAMES;
+    }
+    private static long              NODE_COUNT       = 0;
     private byte                     _indicator;
-    private int                      _id;
+    private long                     _id;
     private int                      _sum_ext_nodes;
     private float                    _x;
     private float                    _y;
-    private double                   _distance_parent;
+    private double                   _distance_parent = PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
     private boolean                  _collapse;
     private PhylogenyNode            _parent;
     private PhylogenyNode            _link;
@@ -63,12 +72,17 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * Default constructor for PhylogenyNode.
      */
     public PhylogenyNode() {
-        init();
         setId( PhylogenyNode.getNodeCount() );
         PhylogenyNode.increaseNodeCount();
         setSumExtNodes( 1 ); // For ext node, this number is 1 (not 0!!)
     }
 
+    public void removeConnections() {
+        _parent = null;
+        _link = null;
+        _descendants = null;
+    }
+
     /**
      * Adds PhylogenyNode n to the list of child nodes and sets the _parent of n
      * to this.
@@ -76,9 +90,8 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * @param n
      *            the PhylogenyNode to add
      */
-    @Override
-    final public void addAsChild( final PhylogenyNodeI node ) {
-        final PhylogenyNode n = ( PhylogenyNode ) node;
+    final public void addAsChild( final PhylogenyNode node ) {
+        final PhylogenyNode n = node;
         addChildNode( n );
         n.setParent( this );
     }
@@ -96,6 +109,7 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     }
 
     @Override
+    // this is poor, as it only compares on names!
     final public int compareTo( final PhylogenyNode o ) {
         final PhylogenyNode n = o;
         if ( ( getName() == null ) || ( n.getName() == null ) ) {
@@ -186,12 +200,12 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
                 return ( this_data.getTaxonomy().isEqual( other_data.getTaxonomy() ) && this_data.getSequence()
                         .isEqual( other_data.getSequence() ) );
             }
-            else if ( this_data.isHasSequence() && other_data.isHasSequence() ) {
-                return ( this_data.getSequence().isEqual( other_data.getSequence() ) );
-            }
             else if ( this_data.isHasTaxonomy() && other_data.isHasTaxonomy() ) {
                 return ( this_data.getTaxonomy().isEqual( other_data.getTaxonomy() ) );
             }
+            else if ( this_data.isHasSequence() && other_data.isHasSequence() ) {
+                return ( this_data.getSequence().isEqual( other_data.getSequence() ) );
+            }
             else if ( getName().length() > 0 ) {
                 // Node name is not empty, and equal.
                 return true;
@@ -268,7 +282,6 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * @throws IllegalArgumentException
      *             if n is out of bounds
      */
-    @Override
     final public PhylogenyNode getChildNode( final int i ) {
         if ( isExternal() ) {
             throw new UnsupportedOperationException( "attempt to get the child node of an external node." );
@@ -333,6 +346,9 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     }
 
     final public List<PhylogenyNode> getDescendants() {
+        if ( _descendants == null ) {
+            _descendants = new ArrayList<PhylogenyNode>();
+        }
         return _descendants;
     }
 
@@ -340,7 +356,6 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * Returns the length of the branch leading to the _parent of this
      * PhylogenyNode (double).
      */
-    @Override
     final public double getDistanceToParent() {
         return _distance_parent;
     }
@@ -445,7 +460,7 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
             previous_node = current_node;
             current_node = current_node.getParent();
         }
-        if ( index < current_node.getNumberOfDescendants() - 1 ) {
+        if ( index < ( current_node.getNumberOfDescendants() - 1 ) ) {
             current_node = current_node.getChildNode( index + 1 );
         }
         while ( current_node.isInternal() && !current_node.isCollapse() ) {
@@ -471,20 +486,22 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     /**
      * Returns the ID (int) of this PhylogenyNode.
      */
-    @Override
-    final public int getId() {
+    final public long getId() {
         return _id;
     }
 
-    /**
-     * Returns the name of this node.
-     */
-    @Override
     final public String getName() {
         return getNodeData().getNodeName();
     }
 
+    final public List<PhylogenyNode> getAllDescendants() {
+        return _descendants;
+    }
+
     final public int getNumberOfDescendants() {
+        if ( _descendants == null ) {
+            return 0;
+        }
         return _descendants.size();
     }
 
@@ -576,13 +593,12 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
         return result;
     }
 
-    final private void init() {
-        _descendants = new ArrayList<PhylogenyNode>();
-        _parent = null;
-        _id = 0;
-        initializeData();
-    }
-
+    // final private void init() {
+    //_descendants = new ArrayList<PhylogenyNode>();
+    //  _parent = null; //TODO not needed?
+    //  _id = 0; //TODO not needed?
+    //initializeData(); //TODO not needed?
+    //}
     /**
      * Deletes data of this PhylogenyNode. Links to the other Nodes in the
      * Phylogeny, the ID and the sum of external nodes are NOT deleted. Field
@@ -590,18 +606,17 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * 
      * @see #getLink() (Last modified: 12/20/03)
      */
-    final public void initializeData() {
-        _indicator = 0;
-        _x = 0;
-        _y = 0;
-        //_node_name = "";
-        _distance_parent = PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
-        _collapse = false;
-        _link = null;
-        _branch_data = null;
-        _node_data = null;
-    }
-
+    //    final private void initializeData() {
+    //        _indicator = 0;
+    //        _x = 0;
+    //        _y = 0;
+    //        //_node_name = "";
+    //        _distance_parent = PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT;
+    //        _collapse = false;
+    //        _link = null;
+    //        _branch_data = null;
+    //        _node_data = null;
+    //    }
     /**
      * Returns whether this PhylogenyNode should be drawn as collapsed.
      */
@@ -623,6 +638,9 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * @return true if this PhylogenyNode is external, false otherwise
      */
     final public boolean isExternal() {
+        if ( _descendants == null ) {
+            return true;
+        }
         return ( getNumberOfDescendants() < 1 );
     }
 
@@ -714,6 +732,28 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
         return true;
     }
 
+    public final int calculateDepth() {
+        PhylogenyNode n = this;
+        int steps = 0;
+        while ( n._parent != null ) {
+            steps++;
+            n = n._parent;
+        }
+        return steps;
+    }
+
+    public final double calculateDistanceToRoot() {
+        PhylogenyNode n = this;
+        double d = 0.0;
+        while ( n._parent != null ) {
+            if ( n._distance_parent > 0.0 ) {
+                d += n._distance_parent;
+            }
+            n = n._parent;
+        }
+        return d;
+    }
+
     /**
      * Checks whether this PhylogenyNode is a root.
      * 
@@ -728,13 +768,6 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     }
 
     // ---------------------------------------------------------
-    // Iterator
-    // ---------------------------------------------------------
-    final public PhylogenyNodeIterator iterateChildNodesForward() {
-        return new ChildNodeIteratorForward( this );
-    }
-
-    // ---------------------------------------------------------
     // Basic printing
     // ---------------------------------------------------------
     /**
@@ -824,7 +857,6 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * Sets the length of the branch leading to the _parent of this
      * PhylogenyNode to double d.
      */
-    @Override
     final public void setDistanceToParent( final double d ) {
         _distance_parent = d;
     }
@@ -861,7 +893,6 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     /**
      * Sets the name of this node.
      */
-    @Override
     final public void setName( final String node_name ) {
         getNodeData().setNodeName( node_name );
     }
@@ -871,7 +902,7 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
      * should not be set to values lower than getNodeCount() -- which this method
      * does not allow.
      */
-    synchronized final protected void setId( final int i ) {
+    synchronized final protected void setId( final long i ) {
         if ( i < getNodeCount() ) {
             throw new IllegalArgumentException( "attempt to set node id to a value less than total node count (thus violating the uniqueness of node ids)" );
         }
@@ -881,7 +912,6 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     /**
      * Sets the _parent PhylogenyNode of this PhylogenyNode to n.
      */
-    @Override
     final public void setParent( final PhylogenyNode n ) {
         _parent = n;
     }
@@ -925,10 +955,18 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     // ---------------------------------------------------------
     final public String toNewHampshire( final boolean simple_nh,
                                         final boolean write_distance_to_parent,
-                                        final boolean write_support_values_in_brackets ) {
+                                        final NH_CONVERSION_SUPPORT_VALUE_STYLE svs ) {
         final StringBuilder sb = new StringBuilder();
         String data = "";
-        if ( !ForesterUtil.isEmpty( getName() ) ) {
+        if ( ( svs == NH_CONVERSION_SUPPORT_VALUE_STYLE.AS_INTERNAL_NODE_NAMES ) && !isExternal() ) {
+            if ( getBranchData().isHasConfidences()
+                    && ( getBranchData().getConfidence( 0 ).getValue() != Confidence.CONFIDENCE_DEFAULT_VALUE ) ) {
+                data = Confidence.FORMATTER.format( ForesterUtil
+                        .round( getBranchData().getConfidence( 0 ).getValue(),
+                                PhyloXmlUtil.ROUNDING_DIGITS_FOR_PHYLOXML_DOUBLE_OUTPUT ) );
+            }
+        }
+        else if ( !ForesterUtil.isEmpty( getName() ) ) {
             data = getName();
         }
         else if ( getNodeData().isHasTaxonomy() ) {
@@ -968,16 +1006,36 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
             sb.append( ":" );
             sb.append( getDistanceToParent() );
         }
-        if ( write_support_values_in_brackets && !isExternal() && getBranchData().isHasConfidences()
+        if ( ( svs == NH_CONVERSION_SUPPORT_VALUE_STYLE.IN_SQUARE_BRACKETS ) && !isExternal()
+                && getBranchData().isHasConfidences()
                 && ( getBranchData().getConfidence( 0 ).getValue() != Confidence.CONFIDENCE_DEFAULT_VALUE ) ) {
             sb.append( "[" );
-            sb.append( getBranchData().getConfidence( 0 ).getValue() );
+            sb.append( Confidence.FORMATTER.format( ForesterUtil
+                    .round( getBranchData().getConfidence( 0 ).getValue(),
+                            PhyloXmlUtil.ROUNDING_DIGITS_FOR_PHYLOXML_DOUBLE_OUTPUT ) ) );
             sb.append( "]" );
         }
         return sb.toString();
     }
 
     /**
+     * Swaps the the two childern of a PhylogenyNode node of this Phylogeny.
+     */
+    public final void swapChildren() throws RuntimeException {
+        if ( isExternal() ) {
+            throw new RuntimeException( "attempt to swap descendants of external node" );
+        }
+        if ( getNumberOfDescendants() != 2 ) {
+            throw new RuntimeException( "attempt to swap descendants of node with " + getNumberOfDescendants()
+                    + " descendants" );
+        }
+        final PhylogenyNode a = getChildNode( 0 );
+        final PhylogenyNode b = getChildNode( 1 );
+        setChildNode( 0, b );
+        setChildNode( 1, a );
+    }
+
+    /**
      * Converts this PhylogenyNode to a New Hampshire X (NHX) String
      * representation.
      */
@@ -1016,70 +1074,100 @@ public class PhylogenyNode implements PhylogenyNodeI, Comparable<PhylogenyNode>
     @Override
     final public String toString() {
         final StringBuilder sb = new StringBuilder();
-        if ( !ForesterUtil.isEmpty( getName() ) ) {
+        if ( getNodeData().isHasTaxonomy() ) {
+            if ( !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getScientificName() ) ) {
+                sb.append( getNodeData().getTaxonomy().getScientificName() );
+                sb.append( " " );
+            }
+            else if ( ( sb.length() <= 1 ) && !ForesterUtil.isEmpty( getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
+                sb.append( getNodeData().getTaxonomy().getTaxonomyCode() );
+                sb.append( " " );
+            }
+            else if ( getNodeData().getTaxonomy().getIdentifier() != null ) {
+                sb.append( getNodeData().getTaxonomy().getIdentifier().toString() );
+                sb.append( " " );
+            }
+        }
+        if ( getNodeData().isHasSequence() ) {
+            if ( !ForesterUtil.isEmpty( getNodeData().getSequence().getName() ) ) {
+                sb.append( getNodeData().getSequence().getName() );
+                sb.append( " " );
+            }
+            if ( !ForesterUtil.isEmpty( getNodeData().getSequence().getSymbol() ) ) {
+                sb.append( getNodeData().getSequence().getSymbol() );
+                sb.append( " " );
+            }
+            if ( getNodeData().getSequence().getAccession() != null ) {
+                sb.append( getNodeData().getSequence().getAccession().toString() );
+                sb.append( " " );
+            }
+        }
+        if ( ( sb.length() <= 1 ) && !ForesterUtil.isEmpty( getName() ) ) {
             sb.append( getName() );
             sb.append( " " );
         }
-        sb.append( "[" );
-        sb.append( getId() );
-        sb.append( "]" );
-        return sb.toString();
+        if ( sb.length() <= 1 ) {
+            sb.append( "[" );
+            sb.append( getId() );
+            sb.append( "]" );
+        }
+        return sb.toString().trim();
     }
 
     /**
      * Decreases the total number of all Nodes created so far by one.
      */
     final static synchronized void decreaseNodeCount() {
-        --PhylogenyNode._node_count;
+        --NODE_COUNT;
     }
 
     /**
      * Returns the total number of all Nodes created so far.
      * 
-     * @return total number of Nodes (int)
+     * @return total number of Nodes (long)
      */
-    synchronized final public static int getNodeCount() {
-        return PhylogenyNode._node_count;
+    synchronized final public static long getNodeCount() {
+        return NODE_COUNT;
     }
 
     /**
      * Increases the total number of all Nodes created so far by one.
      */
     synchronized final private static void increaseNodeCount() {
-        ++PhylogenyNode._node_count;
+        ++NODE_COUNT;
     }
 
     /**
-     * Sets the total number of all Nodes created so far to i (int).
+     * Sets the total number of all Nodes created so far to i.
      */
-    synchronized final static void setNodeCount( final int i ) {
-        PhylogenyNode._node_count = i;
+    synchronized final static void setNodeCount( final long i ) {
+        PhylogenyNode.NODE_COUNT = i;
     }
 
-    public static PhylogenyNode createInstanceFromNhxString( final String nhx ) throws NHXFormatException {
-        return new PhylogenyNode( nhx, PhylogenyMethods.TAXONOMY_EXTRACTION.NO, false );
+    public static PhylogenyNode createInstanceFromNhxString( final String nhx ) throws NHXFormatException,
+            PhyloXmlDataFormatException {
+        return new PhylogenyNode( nhx, NHXParser.TAXONOMY_EXTRACTION.NO, false );
     }
 
     public static PhylogenyNode createInstanceFromNhxString( final String nhx,
-                                                             final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction )
-            throws NHXFormatException {
+                                                             final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction )
+            throws NHXFormatException, PhyloXmlDataFormatException {
         return new PhylogenyNode( nhx, taxonomy_extraction, false );
     }
 
     public static PhylogenyNode createInstanceFromNhxString( final String nhx,
-                                                             final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
+                                                             final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction,
                                                              final boolean replace_underscores )
-            throws NHXFormatException {
+            throws NHXFormatException, PhyloXmlDataFormatException {
         return new PhylogenyNode( nhx, taxonomy_extraction, replace_underscores );
     }
 
     private PhylogenyNode( final String nhx,
-                           final PhylogenyMethods.TAXONOMY_EXTRACTION taxonomy_extraction,
-                           final boolean replace_underscores ) throws NHXFormatException {
-        init();
+                           final NHXParser.TAXONOMY_EXTRACTION taxonomy_extraction,
+                           final boolean replace_underscores ) throws NHXFormatException, PhyloXmlDataFormatException {
         NHXParser.parseNHX( nhx, this, taxonomy_extraction, replace_underscores );
         setId( PhylogenyNode.getNodeCount() );
         PhylogenyNode.increaseNodeCount();
-        setSumExtNodes( 1 ); // For ext node, this number is 1 (not 0!!)
+        setSumExtNodes( 1 ); // For ext node, this number is 1 (not 0!!).
     }
 }