2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
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
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.
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.
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
25 // Contact: phylosoft @ gmail . com
26 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
28 package org.forester.phylogeny;
30 import java.io.IOException;
31 import java.util.ArrayList;
32 import java.util.Arrays;
33 import java.util.Collection;
34 import java.util.HashMap;
35 import java.util.Iterator;
36 import java.util.List;
38 import java.util.NoSuchElementException;
39 import java.util.Vector;
41 import org.forester.io.writers.PhylogenyWriter;
42 import org.forester.phylogeny.PhylogenyNode.NH_CONVERSION_SUPPORT_VALUE_STYLE;
43 import org.forester.phylogeny.data.BranchData;
44 import org.forester.phylogeny.data.Confidence;
45 import org.forester.phylogeny.data.Identifier;
46 import org.forester.phylogeny.data.PhylogenyDataUtil;
47 import org.forester.phylogeny.data.Sequence;
48 import org.forester.phylogeny.data.SequenceRelation;
49 import org.forester.phylogeny.data.SequenceRelation.SEQUENCE_RELATION_TYPE;
50 import org.forester.phylogeny.iterators.ExternalForwardIterator;
51 import org.forester.phylogeny.iterators.LevelOrderTreeIterator;
52 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
53 import org.forester.phylogeny.iterators.PostorderTreeIterator;
54 import org.forester.phylogeny.iterators.PreorderTreeIterator;
55 import org.forester.util.FailedConditionCheckException;
56 import org.forester.util.ForesterUtil;
58 public class Phylogeny {
60 public final static boolean ALLOW_MULTIPLE_PARENTS_DEFAULT = false;
61 private PhylogenyNode _root;
62 private boolean _rooted;
63 private boolean _allow_multiple_parents;
66 private String _description;
67 private String _distance_unit;
68 private Confidence _confidence;
69 private Identifier _identifier;
70 private boolean _rerootable;
71 private HashMap<Integer, PhylogenyNode> _id_to_node_map;
72 private List<PhylogenyNode> _external_nodes_set;
73 private Collection<Sequence> _sequenceRelationQueries;
74 private Collection<SequenceRelation.SEQUENCE_RELATION_TYPE> _relevant_sequence_relation_types;
77 * Default Phylogeny constructor. Constructs an empty Phylogeny.
84 * Adds this Phylogeny to the list of child nodes of PhylogenyNode parent
85 * and sets the parent of this to parent.
88 * the PhylogenyNode to add
90 public void addAsChild( final PhylogenyNode parent ) {
92 throw new IllegalArgumentException( "Attempt to add an empty tree." );
95 throw new IllegalArgumentException( "Attempt to add an unrooted tree." );
97 parent.addAsChild( getRoot() );
98 externalNodesHaveChanged();
101 public void addAsSibling( final PhylogenyNode sibling ) {
103 throw new IllegalArgumentException( "Attempt to add an empty tree." );
106 throw new IllegalArgumentException( "Attempt to add an unrooted tree." );
108 final int sibling_index = sibling.getChildNodeIndex();
109 final PhylogenyNode new_node = new PhylogenyNode();
110 final PhylogenyNode sibling_parent = sibling.getParent();
111 new_node.setChild1( sibling );
112 new_node.setChild2( getRoot() );
113 new_node.setParent( sibling_parent );
114 sibling.setParent( new_node );
115 sibling_parent.setChildNode( sibling_index, new_node );
116 final double new_dist = sibling.getDistanceToParent() == PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ? PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT
117 : sibling.getDistanceToParent() / 2;
118 new_node.setDistanceToParent( new_dist );
119 sibling.setDistanceToParent( new_dist );
120 externalNodesHaveChanged();
124 * This calculates the height of the subtree emanating at n for rooted,
125 * tree-shaped phylogenies
128 * the root-node of a subtree
129 * @return the height of the subtree emanating at n
131 public double calculateSubtreeHeight( final PhylogenyNode n ) {
132 if ( n.isExternal() || n.isCollapse() ) {
133 return ForesterUtil.isLargerOrEqualToZero( n.getDistanceToParent() );
136 double max = -Double.MAX_VALUE;
137 for( int i = 0; i < n.getNumberOfDescendants(); ++i ) {
138 final double l = calculateSubtreeHeight( n.getChildNode( i ) );
143 return max + ForesterUtil.isLargerOrEqualToZero( n.getDistanceToParent() );
147 public void clearHashIdToNodeMap() {
148 setIdToNodeMap( null );
152 * Returns a deep copy of this Phylogeny.
154 * (The resulting Phylogeny has its references in the external nodes
155 * corrected, if they are lacking/obsolete in this.)
157 public Phylogeny copy() {
158 return copy( _root );
162 * Returns a deep copy of this Phylogeny.
164 * (The resulting Phylogeny has its references in the external nodes
165 * corrected, if they are lacking/obsolete in this.)
167 public Phylogeny copy( final PhylogenyNode source ) {
168 final Phylogeny tree = new Phylogeny();
173 tree._rooted = _rooted;
174 tree._name = new String( _name );
175 tree._description = new String( _description );
176 tree._type = new String( _type );
177 tree._rerootable = _rerootable;
178 tree._distance_unit = new String( _distance_unit );
179 if ( _confidence != null ) {
180 tree._confidence = ( Confidence ) _confidence.copy();
182 if ( _identifier != null ) {
183 tree._identifier = ( Identifier ) _identifier.copy();
185 tree.setAllowMultipleParents( isAllowMultipleParents() );
186 tree._root = PhylogenyMethods.copySubTree( source );
191 * Returns a shallow copy of this Phylogeny.
193 * (The resulting Phylogeny has its references in the external nodes
194 * corrected, if they are lacking/obsolete in this.)
196 public Phylogeny copyShallow() {
197 return copyShallow( _root );
200 public Phylogeny copyShallow( final PhylogenyNode source ) {
201 final Phylogeny tree = new Phylogeny();
206 tree._rooted = _rooted;
208 tree._description = _description;
210 tree._rerootable = _rerootable;
211 tree._distance_unit = _distance_unit;
212 tree._confidence = _confidence;
213 tree._identifier = _identifier;
214 tree.setAllowMultipleParents( isAllowMultipleParents() );
215 tree._root = PhylogenyMethods.copySubTreeShallow( source );
220 * Need to call clearHashIdToNodeMap() afterwards (not done automatically
221 * to allow client multiple deletions in linear time).
222 * Need to call 'recalculateNumberOfExternalDescendants(boolean)' after this
223 * if tree is to be displayed.
225 * @param remove_us the parent node of the subtree to be deleted
227 public void deleteSubtree( final PhylogenyNode remove_us, final boolean collapse_resulting_node_with_one_desc ) {
228 if ( isEmpty() || ( remove_us.isRoot() && ( getNumberOfExternalNodes() != 1 ) ) ) {
231 if ( remove_us.isRoot() && ( getNumberOfExternalNodes() == 1 ) ) {
234 else if ( !collapse_resulting_node_with_one_desc ) {
235 remove_us.getParent().removeChildNode( remove_us );
238 final PhylogenyNode removed_node = remove_us;
239 final PhylogenyNode p = remove_us.getParent();
241 if ( p.getNumberOfDescendants() == 2 ) {
242 if ( removed_node.isFirstChildNode() ) {
243 setRoot( getRoot().getChildNode( 1 ) );
244 getRoot().setParent( null );
247 setRoot( getRoot().getChildNode( 0 ) );
248 getRoot().setParent( null );
252 p.removeChildNode( removed_node.getChildNodeIndex() );
256 final PhylogenyNode pp = removed_node.getParent().getParent();
257 if ( p.getNumberOfDescendants() == 2 ) {
258 final int pi = p.getChildNodeIndex();
259 if ( removed_node.isFirstChildNode() ) {
260 p.getChildNode( 1 ).setDistanceToParent( PhylogenyMethods.addPhylogenyDistances( p
261 .getDistanceToParent(), p.getChildNode( 1 ).getDistanceToParent() ) );
262 pp.setChildNode( pi, p.getChildNode( 1 ) );
265 p.getChildNode( 0 ).setDistanceToParent( PhylogenyMethods.addPhylogenyDistances( p
266 .getDistanceToParent(), p.getChildNode( 0 ).getDistanceToParent() ) );
267 pp.setChildNode( pi, p.getChildNode( 0 ) );
271 p.removeChildNode( removed_node.getChildNodeIndex() );
275 remove_us.removeConnections();
276 externalNodesHaveChanged();
279 public void externalNodesHaveChanged() {
280 _external_nodes_set = null;
283 public String[] getAllExternalNodeNames() {
288 final String[] names = new String[ getNumberOfExternalNodes() ];
289 for( final PhylogenyNodeIterator iter = iteratorExternalForward(); iter.hasNext(); ) {
290 names[ i++ ] = new String( iter.next().getName() );
295 public Confidence getConfidence() {
299 public String getDescription() {
303 public String getDistanceUnit() {
304 return _distance_unit;
309 * Warning. The order of the returned nodes is random
310 * -- and hence cannot be relied on.
312 * @return Unordered set of PhylogenyNode
314 public List<PhylogenyNode> getExternalNodes() {
315 if ( _external_nodes_set == null ) {
316 _external_nodes_set = new ArrayList<PhylogenyNode>();
317 for( final PhylogenyNodeIterator it = iteratorPostorder(); it.hasNext(); ) {
318 final PhylogenyNode n = it.next();
319 if ( n.isExternal() ) {
320 _external_nodes_set.add( n );
324 return _external_nodes_set;
328 * Returns the number of duplications of this Phylogeny (int). A return
329 * value of -1 indicates that the number of duplications is unknown.
331 // public int getNumberOfDuplications() {
332 // return _number_of_duplications;
333 // } // getNumberOfDuplications()
335 * Sets the number of duplications of this Phylogeny (int). A value of -1
336 * indicates that the number of duplications is unknown.
339 * set to true for clean NH format
341 // public void setNumberOfDuplications( int i ) {
343 // _number_of_duplications = -1;
346 // _number_of_duplications = i;
348 // } // setNumberOfDuplications( int )
350 * Returns the first external PhylogenyNode.
352 public PhylogenyNode getFirstExternalNode() {
354 throw new FailedConditionCheckException( "attempt to obtain first external node of empty phylogeney" );
356 PhylogenyNode node = getRoot();
357 while ( node.isInternal() ) {
358 node = node.getFirstChildNode();
364 * This calculates the height for rooted, tree-shaped phylogenies. The
365 * height is the longest distance from the root to an external node. Please
366 * note. Child nodes of collapsed nodes are ignored -- which is useful for
367 * display purposes but might be misleading for other applications.
369 * @return the height for rooted, tree-shaped phylogenies
371 public double getHeight() {
375 return calculateSubtreeHeight( getRoot() );
378 public Identifier getIdentifier() {
383 * Returns the name of this Phylogeny.
385 public String getName() {
390 * Finds the PhylogenyNode of this Phylogeny which has a matching ID number.
391 * @return PhylogenyNode with matching ID, null if not found
393 public PhylogenyNode getNode( final int id ) throws NoSuchElementException {
395 throw new NoSuchElementException( "attempt to get node in an empty phylogeny" );
397 if ( ( getIdToNodeMap() == null ) || getIdToNodeMap().isEmpty() ) {
400 return getIdToNodeMap().get( id );
404 * Returns a PhylogenyNode of this Phylogeny which has a matching name.
405 * Throws an Exception if seqname is not present in this or not unique.
408 * name (String) of PhylogenyNode to find
409 * @return PhylogenyNode with matchin name
411 public PhylogenyNode getNode( final String name ) {
415 final List<PhylogenyNode> nodes = getNodes( name );
416 if ( ( nodes == null ) || ( nodes.size() < 1 ) ) {
417 throw new IllegalArgumentException( "node named \"" + name + "\" not found" );
419 if ( nodes.size() > 1 ) {
420 throw new IllegalArgumentException( "node named \"" + name + "\" not unique" );
422 return nodes.get( 0 );
426 * This is time-inefficient since it runs a iterator each time it is called.
429 public int getNodeCount() {
434 for( final PhylogenyNodeIterator it = iteratorPreorder(); it.hasNext(); it.next() ) {
441 * Returns a List with references to all Nodes of this Phylogeny which have
445 * name (String) of Nodes to find
446 * @return Vector of references to Nodes of this Phylogeny with matching
448 * @see #getNodesWithMatchingSpecies(String)
450 public List<PhylogenyNode> getNodes( final String name ) {
454 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
455 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
456 final PhylogenyNode n = iter.next();
457 if ( n.getName().equals( name ) ) {
464 public List<PhylogenyNode> getNodesViaSequenceName( final String seq_name ) {
468 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
469 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
470 final PhylogenyNode n = iter.next();
471 if ( n.getNodeData().isHasSequence() && n.getNodeData().getSequence().getName().equals( seq_name ) ) {
478 public List<PhylogenyNode> getNodesViaTaxonomyCode( final String taxonomy_code ) {
482 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
483 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
484 final PhylogenyNode n = iter.next();
485 if ( n.getNodeData().isHasTaxonomy()
486 && n.getNodeData().getTaxonomy().getTaxonomyCode().equals( taxonomy_code ) ) {
494 * Returns a Vector with references to all Nodes of this Phylogeny which
495 * have a matching species name.
498 * species name (String) of Nodes to find
499 * @return Vector of references to Nodes of this Phylogeny with matching
501 * @see #getNodes(String)
503 public List<PhylogenyNode> getNodesWithMatchingSpecies( final String specname ) {
507 final List<PhylogenyNode> nodes = new ArrayList<PhylogenyNode>();
508 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
509 final PhylogenyNode n = iter.next();
510 if ( PhylogenyMethods.getSpecies( n ).equals( specname ) ) {
517 public PhylogenyNode getNodeViaSequenceName( final String seq_name ) {
521 final List<PhylogenyNode> nodes = getNodesViaSequenceName( seq_name );
522 if ( ( nodes == null ) || ( nodes.size() < 1 ) ) {
523 throw new IllegalArgumentException( "node with sequence named [" + seq_name + "] not found" );
525 if ( nodes.size() > 1 ) {
526 throw new IllegalArgumentException( "node with sequence named [" + seq_name + "] not unique" );
528 return nodes.get( 0 );
531 public PhylogenyNode getNodeViaTaxonomyCode( final String taxonomy_code ) {
535 final List<PhylogenyNode> nodes = getNodesViaTaxonomyCode( taxonomy_code );
536 if ( ( nodes == null ) || ( nodes.size() < 1 ) ) {
537 throw new IllegalArgumentException( "node with taxonomy code \"" + taxonomy_code + "\" not found" );
539 if ( nodes.size() > 1 ) {
540 throw new IllegalArgumentException( "node with taxonomy code \"" + taxonomy_code + "\" not unique" );
542 return nodes.get( 0 );
545 public int getNumberOfBranches() {
550 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); iter.next() ) {
559 public int getNumberOfInternalNodes() {
564 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
565 if ( iter.next().isInternal() ) {
576 * Returns the sum of external Nodes of this Phylogeny (int).
578 public int getNumberOfExternalNodes() {
582 return getExternalNodes().size();
586 * Returns all paralogs of the external PhylogenyNode n of this Phylogeny.
587 * paralog are returned as List of node references.
589 * PRECONDITION: This tree must be binary and rooted, and speciation -
590 * duplication need to be assigned for each of its internal Nodes.
592 * Returns null if this Phylogeny is empty or if n is internal.
594 * (Last modified: 11/22/00) Olivier CHABROL :
595 * olivier.chabrol@univ-provence.fr
598 * external PhylogenyNode whose orthologs are to be returned
599 * @return Vector of references to all orthologous Nodes of PhylogenyNode n
600 * of this Phylogeny, null if this Phylogeny is empty or if n is
603 public List<PhylogenyNode> getParalogousNodes( final PhylogenyNode n, final String[] taxonomyCodeRange ) {
604 PhylogenyNode node = n;
605 PhylogenyNode prev = null;
606 final List<PhylogenyNode> v = new ArrayList<PhylogenyNode>();
607 final Map<PhylogenyNode, List<String>> map = new HashMap<PhylogenyNode, List<String>>();
608 getTaxonomyMap( getRoot(), map );
609 if ( !node.isExternal() || isEmpty() ) {
612 final String searchNodeSpeciesId = PhylogenyMethods.getTaxonomyIdentifier( n );
613 if ( !node.isExternal() || isEmpty() ) {
616 List<String> taxIdList = null;
617 final List<String> taxonomyCodeRangeList = Arrays.asList( taxonomyCodeRange );
618 while ( !node.isRoot() ) {
620 node = node.getParent();
621 taxIdList = map.get( node );
622 if ( node.isDuplication() && isContains( taxIdList, taxonomyCodeRangeList ) ) {
623 if ( node.getChildNode1() == prev ) {
624 v.addAll( getNodeByTaxonomyID( searchNodeSpeciesId, node.getChildNode2()
625 .getAllExternalDescendants() ) );
628 v.addAll( getNodeByTaxonomyID( searchNodeSpeciesId, node.getChildNode1()
629 .getAllExternalDescendants() ) );
636 public Collection<SequenceRelation.SEQUENCE_RELATION_TYPE> getRelevantSequenceRelationTypes() {
637 if ( _relevant_sequence_relation_types == null ) {
638 _relevant_sequence_relation_types = new Vector<SEQUENCE_RELATION_TYPE>();
640 return _relevant_sequence_relation_types;
644 * Returns the root PhylogenyNode of this Phylogeny.
646 public PhylogenyNode getRoot() {
650 public Collection<Sequence> getSequenceRelationQueries() {
651 return _sequenceRelationQueries;
654 public String getType() {
659 * Deletes this Phylogeny.
668 _id_to_node_map = null;
672 setAllowMultipleParents( Phylogeny.ALLOW_MULTIPLE_PARENTS_DEFAULT );
676 * Returns whether this is a completely binary tree (i.e. all internal nodes
680 public boolean isCompletelyBinary() {
684 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
685 final PhylogenyNode node = iter.next();
686 if ( node.isInternal() && ( node.getNumberOfDescendants() != 2 ) ) {
694 * Checks whether a Phylogeny object is deleted (or empty).
696 * @return true if the tree is deleted (or empty), false otherwise
698 public boolean isEmpty() {
699 return ( getRoot() == null );
702 public boolean isRerootable() {
707 * Returns true is this Phylogeny is rooted.
709 public boolean isRooted() {
713 public boolean isTree() {
717 public PhylogenyNodeIterator iteratorExternalForward() {
718 return new ExternalForwardIterator( this );
721 public PhylogenyNodeIterator iteratorLevelOrder() {
722 return new LevelOrderTreeIterator( this );
725 public PhylogenyNodeIterator iteratorPostorder() {
726 return new PostorderTreeIterator( this );
729 public PhylogenyNodeIterator iteratorPreorder() {
730 return new PreorderTreeIterator( this );
734 * Resets the ID numbers of the nodes of this Phylogeny in level order,
735 * starting with start_label (for the root). <br>
736 * WARNING. After this method has been called, node IDs are no longer
739 public void levelOrderReID() {
743 _id_to_node_map = null;
745 for( final PhylogenyNodeIterator it = iteratorPreorder(); it.hasNext(); ) {
746 final PhylogenyNode node = it.next();
747 if ( node.isRoot() ) {
748 node.setId( PhylogenyNode.getNodeCount() );
751 node.setId( node.getParent().getId() + 1 );
752 if ( node.getId() > max ) {
757 PhylogenyNode.setNodeCount( max + 1 );
761 * Prints descriptions of all external Nodes of this Phylogeny to
764 public void printExtNodes() {
768 for( final PhylogenyNodeIterator iter = iteratorExternalForward(); iter.hasNext(); ) {
769 System.out.println( iter.next() + "\n" );
774 * (Re)counts the number of children for each PhylogenyNode of this
775 * Phylogeny. As an example, this method needs to be called after a
776 * Phylogeny has been reRooted and it is to be displayed.
778 * @param consider_collapsed_nodes
779 * set to true to take into account collapsed nodes (collapsed
780 * nodes have 1 child).
782 public void recalculateNumberOfExternalDescendants( final boolean consider_collapsed_nodes ) {
786 for( final PhylogenyNodeIterator iter = iteratorPostorder(); iter.hasNext(); ) {
787 final PhylogenyNode node = iter.next();
788 if ( node.isExternal() || ( consider_collapsed_nodes && node.isCollapse() ) ) {
789 node.setSumExtNodes( 1 );
793 for( int i = 0; i < node.getNumberOfDescendants(); ++i ) {
794 sum += node.getChildNode( i ).getNumberOfExternalNodes();
796 node.setSumExtNodes( sum );
802 * Places the root of this Phylogeny on the parent branch of the
803 * PhylogenyNode with a corresponding ID. The new root is always placed on
804 * the middle of the branch. If the resulting reRooted Phylogeny is to be
805 * used any further, in most cases the following methods have to be called
806 * on the resulting Phylogeny:
808 * <li>recalculateNumberOfExternalDescendants(boolean)
809 * <li>recalculateAndReset()
812 * ID (int) of PhylogenyNode of this Phylogeny
814 public void reRoot( final int id ) {
815 reRoot( getNode( id ) );
819 * Places the root of this Phylogeny on Branch b. The new root is always
820 * placed on the middle of the branch b.
823 public void reRoot( final PhylogenyBranch b ) {
824 final PhylogenyNode n1 = b.getFirstNode();
825 final PhylogenyNode n2 = b.getSecondNode();
826 if ( n1.isExternal() ) {
829 else if ( n2.isExternal() ) {
832 else if ( ( n2 == n1.getChildNode1() ) || ( n2 == n1.getChildNode2() ) ) {
835 else if ( ( n1 == n2.getChildNode1() ) || ( n1 == n2.getChildNode2() ) ) {
838 else if ( ( n1.getParent() != null ) && n1.getParent().isRoot()
839 && ( ( n1.getParent().getChildNode1() == n2 ) || ( n1.getParent().getChildNode2() == n2 ) ) ) {
843 throw new IllegalArgumentException( "reRoot( Branch b ): b is not a branch." );
848 * Places the root of this Phylogeny on the parent branch PhylogenyNode n.
849 * The new root is always placed on the middle of the branch.
851 * If the resulting reRooted Phylogeny is to be used any further, in most
852 * cases the following three methods have to be called on the resulting
855 * <li>recalculateNumberOfExternalDescendants(boolean) <li>recalculateAndReset()
858 * (Last modified: 10/01/01)
861 * PhylogenyNode of this Phylogeny\
863 public void reRoot( final PhylogenyNode n ) {
867 public void reRoot( final PhylogenyNode n, final double distance_n_to_parent ) {
868 if ( isEmpty() || ( getNumberOfExternalNodes() < 2 ) ) {
875 else if ( n.getParent().isRoot() ) {
876 if ( ( n.getParent().getNumberOfDescendants() == 2 ) && ( distance_n_to_parent >= 0 ) ) {
877 final double d = n.getParent().getChildNode1().getDistanceToParent()
878 + n.getParent().getChildNode2().getDistanceToParent();
880 if ( n.getChildNodeIndex() == 0 ) {
881 other = n.getParent().getChildNode2();
884 other = n.getParent().getChildNode1();
886 n.setDistanceToParent( distance_n_to_parent );
887 final double dm = d - distance_n_to_parent;
889 other.setDistanceToParent( dm );
892 other.setDistanceToParent( 0 );
895 if ( n.getParent().getNumberOfDescendants() > 2 ) {
896 final int index = n.getChildNodeIndex();
897 final double dn = n.getDistanceToParent();
898 final PhylogenyNode prev_root = getRoot();
899 prev_root.getDescendants().remove( index );
900 final PhylogenyNode new_root = new PhylogenyNode();
901 new_root.setChildNode( 0, n );
902 new_root.setChildNode( 1, prev_root );
903 if ( n.getBranchDataDirectly() != null ) {
904 prev_root.setBranchData( ( BranchData ) n.getBranchDataDirectly().copy() );
907 if ( distance_n_to_parent >= 0 ) {
908 n.setDistanceToParent( distance_n_to_parent );
909 final double d = dn - distance_n_to_parent;
911 prev_root.setDistanceToParent( d );
914 prev_root.setDistanceToParent( 0 );
919 final double d = dn / 2.0;
920 n.setDistanceToParent( d );
921 prev_root.setDistanceToParent( d );
928 PhylogenyNode b = null;
929 PhylogenyNode c = null;
930 final PhylogenyNode new_root = new PhylogenyNode();
931 double distance1 = 0.0;
932 double distance2 = 0.0;
933 BranchData branch_data_1 = null;
934 BranchData branch_data_2 = null;
937 new_root.setChildNode( 0, a );
938 new_root.setChildNode( 1, b );
939 distance1 = c.getDistanceToParent();
940 if ( c.getBranchDataDirectly() != null ) {
941 branch_data_1 = ( BranchData ) c.getBranchDataDirectly().copy();
943 c.setDistanceToParent( b.getDistanceToParent() );
944 if ( b.getBranchDataDirectly() != null ) {
945 c.setBranchData( ( BranchData ) b.getBranchDataDirectly().copy() );
947 if ( a.getBranchDataDirectly() != null ) {
948 b.setBranchData( ( BranchData ) a.getBranchDataDirectly().copy() );
950 // New root is always placed in the middle of the branch:
951 if ( a.getDistanceToParent() == PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) {
952 b.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
955 if ( distance_n_to_parent >= 0.0 ) {
956 final double diff = a.getDistanceToParent() - distance_n_to_parent;
957 a.setDistanceToParent( distance_n_to_parent );
958 b.setDistanceToParent( diff >= 0.0 ? diff : 0.0 );
961 final double d = a.getDistanceToParent() / 2.0;
962 a.setDistanceToParent( d );
963 b.setDistanceToParent( d );
966 b.setChildNodeOnly( a.getChildNodeIndex( b ), c );
967 // moving to the old root, swapping references:
968 while ( !c.isRoot() ) {
972 b.setChildNodeOnly( a.getChildNodeIndex( b ), c );
974 distance2 = c.getDistanceToParent();
975 branch_data_2 = c.getBranchDataDirectly();
976 c.setDistanceToParent( distance1 );
977 c.setBranchData( branch_data_1 );
978 distance1 = distance2;
979 branch_data_1 = branch_data_2;
981 // removing the old root:
982 if ( c.getNumberOfDescendants() == 2 ) {
983 final PhylogenyNode node = c.getChildNode( 1 - b.getChildNodeIndex( c ) );
985 if ( ( c.getDistanceToParent() == PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT )
986 && ( node.getDistanceToParent() == PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT ) ) {
987 node.setDistanceToParent( PhylogenyDataUtil.BRANCH_LENGTH_DEFAULT );
990 node.setDistanceToParent( ( c.getDistanceToParent() >= 0.0 ? c.getDistanceToParent() : 0.0 )
991 + ( node.getDistanceToParent() >= 0.0 ? node.getDistanceToParent() : 0.0 ) );
993 if ( c.getBranchDataDirectly() != null ) {
994 node.setBranchData( ( BranchData ) c.getBranchDataDirectly().copy() );
996 for( int i = 0; i < b.getNumberOfDescendants(); ++i ) {
997 if ( b.getChildNode( i ) == c ) {
998 b.setChildNodeOnly( i, node );
1005 c.removeChildNode( b.getChildNodeIndex( c ) );
1007 setRoot( new_root );
1012 * Sets all Nodes of this Phylogeny to not-collapsed.
1014 * In most cases methods adjustNodeCount(false) and recalculateAndReset()
1015 * need to be called after this method has been called.
1017 public void setAllNodesToNotCollapse() {
1021 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
1022 final PhylogenyNode node = iter.next();
1023 node.setCollapse( false );
1027 public void setConfidence( final Confidence confidence ) {
1028 _confidence = confidence;
1031 public void setDescription( final String description ) {
1032 _description = description;
1035 public void setDistanceUnit( final String _distance_unit ) {
1036 this._distance_unit = _distance_unit;
1039 public void setIdentifier( final Identifier identifier ) {
1040 _identifier = identifier;
1043 public void setIdToNodeMap( final HashMap<Integer, PhylogenyNode> idhash ) {
1044 _id_to_node_map = idhash;
1048 * Sets the indicators of all Nodes of this Phylogeny to 0.
1050 public void setIndicatorsToZero() {
1054 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
1055 iter.next().setIndicator( ( byte ) 0 );
1057 } // setIndicatorsToZero()
1060 * Sets the name of this Phylogeny to s.
1062 public void setName( final String s ) {
1066 public void setRelevantSequenceRelationTypes( final Collection<SequenceRelation.SEQUENCE_RELATION_TYPE> types ) {
1067 _relevant_sequence_relation_types = types;
1070 public void setRerootable( final boolean rerootable ) {
1071 _rerootable = rerootable;
1074 public void setRoot( final PhylogenyNode n ) {
1079 * Sets whether this Phylogeny is rooted or not.
1081 public void setRooted( final boolean b ) {
1083 } // setRooted( boolean )
1085 public void setSequenceRelationQueries( final Collection<Sequence> sequencesByName ) {
1086 _sequenceRelationQueries = sequencesByName;
1089 public void setType( final String type ) {
1093 public String toNewHampshire() {
1094 return toNewHampshire( false, NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
1097 public String toNewHampshire( final boolean simple_nh,
1098 final NH_CONVERSION_SUPPORT_VALUE_STYLE nh_conversion_support_style ) {
1100 return new PhylogenyWriter().toNewHampshire( this, simple_nh, true, nh_conversion_support_style )
1103 catch ( final IOException e ) {
1104 throw new Error( "this should not have happend: " + e.getMessage() );
1108 public String toNewHampshireX() {
1110 return new PhylogenyWriter().toNewHampshireX( this ).toString();
1112 catch ( final IOException e ) {
1113 throw new Error( "this should not have happend: " + e.getMessage() );
1117 public String toNexus() {
1118 return toNexus( NH_CONVERSION_SUPPORT_VALUE_STYLE.NONE );
1121 public String toNexus( final NH_CONVERSION_SUPPORT_VALUE_STYLE svs ) {
1123 return new PhylogenyWriter().toNexus( this, svs ).toString();
1125 catch ( final IOException e ) {
1126 throw new Error( "this should not have happend: " + e.getMessage() );
1130 public String toPhyloXML( final int phyloxml_level ) {
1132 return new PhylogenyWriter().toPhyloXML( this, phyloxml_level ).toString();
1134 catch ( final IOException e ) {
1135 throw new Error( "this should not have happend: " + e.getMessage() );
1139 // ---------------------------------------------------------
1140 // Writing of Phylogeny to Strings
1141 // ---------------------------------------------------------
1143 * Converts this Phylogeny to a New Hampshire X (String) representation.
1145 * @return New Hampshire X (String) representation of this
1146 * @see #toNewHampshireX()
1149 public String toString() {
1150 return toNewHampshireX();
1154 * Removes the root PhylogenyNode this Phylogeny.
1156 public void unRoot() throws RuntimeException {
1158 throw new FailedConditionCheckException( "Attempt to unroot a phylogeny which is not tree-like." );
1163 setIndicatorsToZero();
1164 if ( !isRooted() || ( getNumberOfExternalNodes() <= 1 ) ) {
1171 private HashMap<Integer, PhylogenyNode> getIdToNodeMap() {
1172 return _id_to_node_map;
1176 * Return Node by TaxonomyId Olivier CHABROL :
1177 * olivier.chabrol@univ-provence.fr
1180 * search taxonomy identifier
1182 * sublist node to search
1183 * @return List node with the same taxonomy identifier
1185 private List<PhylogenyNode> getNodeByTaxonomyID( final String taxonomyID, final List<PhylogenyNode> nodes ) {
1186 final List<PhylogenyNode> retour = new ArrayList<PhylogenyNode>();
1187 for( final PhylogenyNode node : nodes ) {
1188 if ( taxonomyID.equals( PhylogenyMethods.getTaxonomyIdentifier( node ) ) ) {
1196 * List all species contains in all leaf under a node Olivier CHABROL :
1197 * olivier.chabrol@univ-provence.fr
1200 * PhylogenyNode whose sub node species are returned
1201 * @return species contains in all leaf under the param node
1203 private List<String> getSubNodeTaxonomy( final PhylogenyNode node ) {
1204 final List<String> taxonomyList = new ArrayList<String>();
1205 final List<PhylogenyNode> childs = node.getAllExternalDescendants();
1206 String speciesId = null;
1207 for( final PhylogenyNode phylogenyNode : childs ) {
1208 // taxId = new Long(phylogenyNode.getTaxonomyID());
1209 speciesId = PhylogenyMethods.getTaxonomyIdentifier( phylogenyNode );
1210 if ( !taxonomyList.contains( speciesId ) ) {
1211 taxonomyList.add( speciesId );
1214 return taxonomyList;
1218 * Create a map [<PhylogenyNode, List<String>], the list contains the
1219 * species contains in all leaf under phylogeny node Olivier CHABROL :
1220 * olivier.chabrol@univ-provence.fr
1223 * the tree root node
1227 private void getTaxonomyMap( final PhylogenyNode node, final Map<PhylogenyNode, List<String>> map ) {
1229 if ( node.isExternal() ) {
1232 map.put( node, getSubNodeTaxonomy( node ) );
1233 getTaxonomyMap( node.getChildNode1(), map );
1234 getTaxonomyMap( node.getChildNode2(), map );
1237 private boolean isAllowMultipleParents() {
1238 return _allow_multiple_parents;
1242 * Util method to check if all element of a list is contains in the
1243 * rangeList. Olivier CHABROL : olivier.chabrol@univ-provence.fr
1248 * the range list to compare
1249 * @return <code>true</code> if all param list element are contains in param
1250 * rangeList, <code>false</code> otherwise.
1252 private boolean isContains( final List<String> list, final List<String> rangeList ) {
1253 if ( list.size() > rangeList.size() ) {
1257 for( final Iterator<String> iterator = list.iterator(); iterator.hasNext(); ) {
1258 l = iterator.next();
1259 if ( !rangeList.contains( l ) ) {
1267 * Hashes the ID number of each PhylogenyNode of this Phylogeny to its
1268 * corresponding PhylogenyNode, in order to make method getNode( id ) run in
1269 * constant time. Important: The user is responsible for calling this method
1270 * (again) after this Phylogeny has been changed/created/renumbered.
1272 private void reHashIdToNodeMap() {
1276 setIdToNodeMap( new HashMap<Integer, PhylogenyNode>() );
1277 for( final PhylogenyNodeIterator iter = iteratorPreorder(); iter.hasNext(); ) {
1278 final PhylogenyNode node = iter.next();
1279 getIdToNodeMap().put( node.getId(), node );
1283 private void setAllowMultipleParents( final boolean allow_multiple_parents ) {
1284 _allow_multiple_parents = allow_multiple_parents;