Debian Codegraph @

src/dr/evomodel/tree/TreeModel.java

raw symbols SCIP
1 /*
2 * TreeModel.java
3 *
4 * Copyright (c) 2002-2017 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
24 */
25
26 package dr.evomodel.tree;
27
28 import dr.evolution.tree.*;
29 import dr.evolution.util.MutableTaxonListListener;
30 import dr.evolution.util.Taxon;
31 import dr.inference.model.*;
32 import dr.util.*;
33 import org.w3c.dom.Document;
34 import org.w3c.dom.Element;
35
36 import java.util.*;
37
38 /**
39 * A model component for trees.
40 *
41 * @author Andrew Rambaut
42 * @author Alexei Drummond
43 * @version $Id: TreeModel.java,v 1.129 2006/01/05 17:55:47 rambaut Exp $
44 */
45 public class TreeModel extends AbstractModel implements MutableTreeModel, Keywordable, Citable {
46
47 //
48 // Public stuff
49 //
50
51 public static final String TREE_MODEL = "treeModel";
52
53 private static final boolean TEST_NODE_BOUNDS = false;
54
55 public TreeModel(String name) {
56 super(name);
57 nodeCount = 0;
58 externalNodeCount = 0;
59 internalNodeCount = 0;
60 isTreeRandom = true;
61 }
62
63 public TreeModel(Tree tree) {
64 this(TREE_MODEL, tree, false, false, false);
65 }
66
67 public TreeModel(String id, Tree tree) { this(id, tree, false, false); }
68
69 public TreeModel(String id, Tree tree, boolean fixHeights, boolean fixTree) {
70
71 this(id, tree, false, fixHeights, fixTree);
72 setId(id);
73 }
74
75 /* New constructor that copies the attributes of Tree tree into the new TreeModel
76 * Useful for constructing a TreeModel from a NEXUS file entry
77 */
78
79 public TreeModel(String name, Tree tree, boolean copyAttributes, boolean fixHeights, boolean fixTree) {
80
81 super(name);
82
83 // get a rooted version of the tree to clone
84 FlexibleTree binaryTree = new FlexibleTree(tree, copyAttributes);
85 binaryTree.resolveTree();
86
87 // adjust the heights to be compatible with the tip dates and perturb
88 // any zero branches.
89 if (!fixHeights) {
90 MutableTree.Utils.correctHeightsForTips(binaryTree);
91 }
92
93 this.isTreeRandom = !fixTree;
94
95 // clone the node structure (this will create the individual parameters)
96 Node node = new Node(binaryTree, binaryTree.getRoot());
97
98 internalNodeCount = binaryTree.getInternalNodeCount();
99 externalNodeCount = binaryTree.getExternalNodeCount();
100
101 nodeCount = internalNodeCount + externalNodeCount;
102
103 nodes = new Node[nodeCount];
104 storedNodes = new Node[nodeCount];
105
106 int i = 0;
107 int j = externalNodeCount;
108
109 root = node;
110
111 do {
112 node = (Node) TreeUtils.postorderSuccessor(this, node);
113
114 if (node.isExternal()) {
115 node.number = i;
116
117 nodes[i] = node;
118 storedNodes[i] = new Node();
119 storedNodes[i].taxon = node.taxon;
120 storedNodes[i].number = i;
121
122 i++;
123 } else {
124 node.number = j;
125
126 nodes[j] = node;
127 storedNodes[j] = new Node();
128 storedNodes[j].number = j;
129
130 j++;
131 }
132 } while (node != root);
133
134 // must be done here to allow programmatic running of BEAST
135 setupHeightBounds();
136 }
137
138
139 boolean heightBoundsSetup = false;
140
141 public void setupHeightBounds() {
142
143 if (heightBoundsSetup) {
144 throw new IllegalArgumentException("Node height bounds set up twice");
145 }
146
147 for (int i = 0; i < nodeCount; i++) {
148 nodes[i].setupHeightBounds();
149 }
150
151 heightBoundsSetup = true;
152 }
153
154 /**
155 * Push a tree changed event into the event stack.
156 */
157 public void pushTreeChangedEvent() {
158 pushTreeChangedEvent(new TreeChangedEvent());
159 }
160
161 /**
162 * Push a tree changed event into the event stack.
163 */
164 public void pushTreeChangedEvent(NodeRef nodeRef) {
165 pushTreeChangedEvent(new TreeChangedEvent((Node) nodeRef));
166 }
167
168 /**
169 * Push a tree changed event into the event stack.
170 */
171 public void pushTreeChangedEvent(Node node, Parameter parameter, int index) {
172 pushTreeChangedEvent(new TreeChangedEvent(node, parameter, index));
173 }
174
175 /**
176 * Push a tree changed event into the event stack.
177 */
178 public void pushTreeChangedEvent(dr.evomodel.tree.TreeChangedEvent event) {
179
180 if (!isTreeRandom) throw new IllegalStateException("Attempting state change in fixed tree");
181
182 if (inEdit) {
183 treeChangedEvents.add(event);
184 } else {
185 listenerHelper.fireModelChanged(this, event);
186 }
187 }
188
189
190 protected void handleModelChangedEvent(Model model, Object object, int index) {
191 // no submodels so nothing to do
192 }
193
194 /**
195 * Called when a parameter changes.
196 */
197 public void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
198 final Node node = getNodeOfParameter((Parameter) variable);
199 if (type == Parameter.ChangeType.ALL_VALUES_CHANGED) {
200 //this signals events where values in all dimensions of a parameter is changed.
201 pushTreeChangedEvent(new TreeChangedEvent(node, (Parameter) variable, TreeChangedEvent.CHANGE_IN_ALL_INTERNAL_NODES));
202 } else {
203 pushTreeChangedEvent(node, (Parameter) variable, index);
204 }
205 }
206
207
208 private final List<dr.evomodel.tree.TreeChangedEvent> treeChangedEvents = new ArrayList<dr.evomodel.tree.TreeChangedEvent>();
209
210 public boolean hasRates() {
211 return hasRates;
212 }
213
214 public boolean inTreeEdit() {
215 return inEdit;
216 }
217
218 public class TreeChangedEvent implements dr.evomodel.tree.TreeChangedEvent {
219 static final int CHANGE_IN_ALL_INTERNAL_NODES = -2;
220
221 final Node node;
222 final Parameter parameter;
223 final int index;
224
225 public TreeChangedEvent() {
226 this(null, null, -1);
227 }
228
229 public TreeChangedEvent(Node node) {
230 this(node, null, -1);
231 }
232
233 public TreeChangedEvent(Node node, Parameter parameter, int index) {
234 this.node = node;
235 this.parameter = parameter;
236 this.index = index;
237 }
238
239 @Override
240 public int getIndex() {
241 return index;
242 }
243
244 @Override
245 public Node getNode() {
246 return node;
247 }
248
249 public Parameter getParameter() {
250 return parameter;
251 }
252
253 public boolean isTreeChanged() {
254 return parameter == null;
255 }
256
257 @Override
258 public boolean isNodeChanged() {
259 return node != null;
260 }
261
262 @Override
263 public boolean isNodeParameterChanged() {
264 return parameter != null;
265 }
266
267 public boolean isHeightChanged() {
268 return parameter == node.heightParameter;
269 }
270
271 public boolean isRateChanged() {
272 return parameter == node.rateParameter;
273 }
274
275 public boolean isTraitChanged(String name) {
276 return parameter == node.traitParameters.get(name);
277 }
278
279 public boolean areAllInternalHeightsChanged() {
280 if (parameter != null) {
281 return parameter == node.heightParameter && index == CHANGE_IN_ALL_INTERNAL_NODES;
282 }
283 return false;
284 }
285
286 }
287
288 // *****************************************************************
289 // Interface Tree
290 // *****************************************************************
291
292 /**
293 * Return the units that this tree is expressed in.
294 */
295 public Type getUnits() {
296 return units;
297 }
298
299 /**
300 * Sets the units that this tree is expressed in.
301 */
302 public void setUnits(Type units) {
303 this.units = units;
304 }
305
306 /**
307 * @return a count of the number of nodes (internal + external) in this
308 * tree.
309 */
310 public int getNodeCount() {
311 return nodeCount;
312 }
313
314 public boolean hasNodeHeights() {
315 return true;
316 }
317
318 public double getNodeHeight(NodeRef node) {
319 return ((Node) node).getHeight();
320 }
321
322 public final double getNodeHeightUpper(NodeRef node) {
323 return ((Node) node).heightParameter.getBounds().getUpperLimit(0);
324 }
325
326 public final double getNodeHeightLower(NodeRef node) {
327 return ((Node) node).heightParameter.getBounds().getLowerLimit(0);
328 }
329
330
331 /**
332 * @param node
333 * @return the rate parameter associated with this node.
334 */
335 public double getNodeRate(NodeRef node) {
336 if (!hasRates) {
337 return 1.0;
338 }
339 return ((Node) node).getRate();
340 }
341
342 public Object getNodeAttribute(NodeRef node, String name) {
343
344 if (name.equals("rate")) {
345 return getNodeRate(node);
346 }
347
348 return null;
349 }
350
351 public Iterator getNodeAttributeNames(NodeRef node) {
352 return new Iterator() {
353
354 int i = 0;
355 String[] attributes = {"rate"};
356
357 public boolean hasNext() {
358 return i < attributes.length;
359 }
360
361 public Object next() {
362 return attributes[i++];
363 }
364
365 public void remove() {
366 throw new UnsupportedOperationException("can't remove from this iterator!");
367 }
368 };
369 }
370
371 public boolean hasNodeTraits() {
372 return hasTraits;
373 }
374
375 public Map<String, Parameter> getTraitMap(NodeRef node) {
376 if (!hasTraits) throw new IllegalArgumentException("Trait parameters have not been created");
377 return ((Node) node).getTraitMap();
378 }
379
380 public double getNodeTrait(NodeRef node, String name) {
381 if (!hasTraits) throw new IllegalArgumentException("Trait parameters have not been created");
382 return ((Node) node).getTrait(name);
383 }
384
385 public Parameter getNodeTraitParameter(NodeRef node, String name) {
386 if (!hasTraits) throw new IllegalArgumentException("Trait parameters have not been created");
387 return ((Node) node).getTraitParameter(name);
388 }
389
390 public double[] getMultivariateNodeTrait(NodeRef node, String name) {
391 if (!hasTraits) throw new IllegalArgumentException("Trait parameters have not been created");
392 return ((Node) node).getMultivariateTrait(name);
393 }
394
395 public final void swapAllTraits(NodeRef node1, NodeRef node2) {
396 if (!hasTraits) throw new IllegalArgumentException("Trait parameters have not been created");
397 swapAllTraits((Node) node1, (Node) node2);
398 }
399
400 public Taxon getNodeTaxon(NodeRef node) {
401 return ((Node) node).taxon;
402 }
403
404 public void setNodeTaxon(NodeRef node, Taxon taxon) {
405 ((Node) node).taxon = taxon;
406 }
407
408 public boolean isExternal(NodeRef node) {
409 return ((Node) node).isExternal();
410 }
411
412 public boolean isRoot(NodeRef node) {
413 return (node == root);
414 }
415
416 public int getChildCount(NodeRef node) {
417 return ((Node) node).getChildCount();
418 }
419
420 public NodeRef getChild(NodeRef node, int i) {
421 return ((Node) node).getChild(i);
422 }
423
424 public NodeRef getParent(NodeRef node) {
425 return ((Node) node).parent;
426 }
427
428 public boolean hasBranchLengths() {
429 return true;
430 }
431
432 public double getBranchLength(NodeRef node) {
433 NodeRef parent = getParent(node);
434 if (parent == null) {
435 return 0.0;
436 }
437
438 return getNodeHeight(parent) - getNodeHeight(node);
439 }
440
441 public NodeRef getExternalNode(int i) {
442 return nodes[i];
443 }
444
445 public NodeRef getInternalNode(int i) {
446 return nodes[i + externalNodeCount];
447 }
448
449 public NodeRef getNode(int i) {
450 return nodes[i];
451 }
452
453 public NodeRef[] getNodes() {
454 return nodes;
455 }
456
457 /**
458 * Returns the number of external nodes.
459 */
460 public int getExternalNodeCount() {
461 return externalNodeCount;
462 }
463
464 /**
465 * Returns the ith internal node.
466 */
467 public int getInternalNodeCount() {
468 return internalNodeCount;
469 }
470
471 /**
472 * Returns the root node of this tree.
473 */
474 public NodeRef getRoot() {
475 return root;
476 }
477
478 // *****************************************************************
479 // Interface MutableTree
480 // *****************************************************************
481
482 /**
483 * Set a new node as root node.
484 */
485 public void setRoot(NodeRef newRoot) {
486
487 if (!inEdit) throw new RuntimeException("Must be in edit transaction to call this method!");
488
489 root = (Node) newRoot;
490
491 // We shouldn't need this because the addChild will already have fired appropriate events.
492 pushTreeChangedEvent(root);
493 }
494
495 public void addChild(NodeRef p, NodeRef c) {
496
497 if (!inEdit) throw new RuntimeException("Must be in edit transaction to call this method!");
498
499 Node parent = (Node) p;
500 Node child = (Node) c;
501 if (parent.hasChild(child)) throw new IllegalArgumentException("Child already exists in parent");
502
503 parent.addChild(child);
504 pushTreeChangedEvent(parent);
505 }
506
507 public void removeChild(NodeRef p, NodeRef c) {
508
509 if (!inEdit) throw new RuntimeException("Must be in edit transaction to call this method!");
510
511 Node parent = (Node) p;
512 Node child = (Node) c;
513
514 parent.removeChild(child);
515 }
516
517 public void replaceChild(NodeRef node, NodeRef child, NodeRef newChild) {
518 throw new RuntimeException("Unimplemented");
519 }
520
521 private Node oldRoot;
522
523 public boolean beginTreeEdit() {
524 if (inEdit) throw new RuntimeException("Already in edit transaction mode!");
525
526 oldRoot = root;
527
528 inEdit = true;
529
530 return false;
531 }
532
533 public void endTreeEdit() {
534 if (!inEdit) throw new RuntimeException("Not in edit transaction mode!");
535
536 inEdit = false;
537
538 if (root != oldRoot) {
539 swapParameterObjects(oldRoot, root);
540 }
541
542 if (TEST_NODE_BOUNDS) {
543 try {
544 checkTreeIsValid();
545 } catch (InvalidTreeException ite) {
546 throw new RuntimeException(ite.getMessage());
547 }
548 }
549
550 for (dr.evomodel.tree.TreeChangedEvent treeChangedEvent : treeChangedEvents) {
551 listenerHelper.fireModelChanged(this, treeChangedEvent);
552 }
553 treeChangedEvents.clear();
554 }
555
556 public void checkTreeIsValid() throws MutableTree.InvalidTreeException {
557 for (Node node : nodes) {
558 if (!node.heightParameter.isWithinBounds()) {
559 throw new InvalidTreeException("height parameter out of bounds");
560 }
561 }
562 }
563
564 public void setNodeHeight(NodeRef n, double height) {
565 ((Node) n).setHeight(height);
566 }
567
568
569 public void setNodeRate(NodeRef n, double rate) {
570 if (!hasRates) throw new IllegalArgumentException("Rate parameters have not been created");
571 ((Node) n).setRate(rate);
572
573 }
574
575 public void setNodeTrait(NodeRef n, String name, double value) {
576 if (!hasTraits) throw new IllegalArgumentException("Trait parameters have not been created");
577 ((Node) n).setTrait(name, value);
578 }
579
580 public void setMultivariateTrait(NodeRef n, String name, double[] value) {
581 if (!hasTraits) throw new IllegalArgumentException("Trait parameters have not been created");
582 ((Node) n).setMultivariateTrait(name, value);
583 }
584
585 public void setBranchLength(NodeRef node, double length) {
586 throw new UnsupportedOperationException("TreeModel cannot have branch lengths set");
587 }
588
589 public void setNodeAttribute(NodeRef node, String name, Object value) {
590 throw new UnsupportedOperationException("TreeModel does not use NodeAttributes");
591 }
592
593 // *****************************************************************
594 // Interface ModelComponent
595 // *****************************************************************
596
597 /**
598 * Store current state
599 */
600 protected void storeState() {
601
602 copyNodeStructure(storedNodes);
603 storedRootNumber = root.getNumber();
604
605 }
606
607 /**
608 * Restore the stored state
609 */
610 protected void restoreState() {
611
612 Node[] tmp = storedNodes;
613 storedNodes = nodes;
614 nodes = tmp;
615
616 root = nodes[storedRootNumber];
617 }
618
619 /**
620 * accept the stored state
621 */
622 protected void acceptState() {
623 } // nothing to do
624
625 /**
626 * Copies the node connections from this TreeModel's nodes array to the
627 * destination array. Basically it connects up the nodes in destination
628 * in the same way as this TreeModel is set up. This method is package
629 * private.
630 */
631 private void copyNodeStructure(Node[] destination) {
632
633 if (nodes.length != destination.length) {
634 throw new IllegalArgumentException("Node arrays are of different lengths");
635 }
636
637 for (int i = 0, n = nodes.length; i < n; i++) {
638 Node node0 = nodes[i];
639 Node node1 = destination[i];
640
641 // the parameter values are automatically stored and restored
642 // just need to keep the links
643 node1.heightParameter = node0.heightParameter;
644 node1.rateParameter = node0.rateParameter;
645 node1.traitParameters = node0.traitParameters;
646
647 if (node0.parent != null) {
648 node1.parent = storedNodes[node0.parent.getNumber()];
649 } else {
650 node1.parent = null;
651 }
652
653 if (node0.leftChild != null) {
654 node1.leftChild = storedNodes[node0.leftChild.getNumber()];
655 } else {
656 node1.leftChild = null;
657 }
658
659 if (node0.rightChild != null) {
660 node1.rightChild = storedNodes[node0.rightChild.getNumber()];
661 } else {
662 node1.rightChild = null;
663 }
664 }
665 }
666
667 /**
668 * Copies a different tree into the current treeModel. Needs to reconnect
669 * the existing internal and external nodes, taking into account that the
670 * node numbers of the external nodes may differ between the two trees.
671 */
672 public void adoptTreeStructure(Tree donor) {
673
674 /*System.err.println("internalNodeCount: " + this.internalNodeCount);
675 System.err.println("externalNodeCount: " + this.externalNodeCount);
676 for (int i = 0; i < this.nodeCount; i++) {
677 System.err.println(nodes[i]);
678 }*/
679
680 //first remove all the child nodes of the internal nodes
681 for (int i = this.externalNodeCount; i < this.nodeCount; i++) {
682 int childCount = nodes[i].getChildCount();
683 for (int j = 0; j < childCount; j++) {
684 nodes[i].removeChild(j);
685 }
686 }
687
688 // set-up nodes in this.nodes[] to mirror connectedness in donor via a simple recursion on donor.getRoot()
689 addNodeStructure(donor, donor.getRoot());
690
691 //Tree donor has no rates nor traits, only heights
692
693 }
694
695 /**
696 * Modifies the current tree by adopting the provided collection of edges
697 * @param edges Edges are provided as index: child number; parent: array entry
698 * @param nodeHeights Also sets the node heights to the provided values
699 * @param childOrder Array that contains whether a child node is left or right child
700 */
701 public void adoptTreeStructure(int[] edges, double[] nodeHeights, int[] childOrder, String[] taxaNames) {
702
703 int[] nodeMap = createNodeMap(taxaNames);
704
705 if (this.nodeCount != edges.length) {
706 throw new RuntimeException("Incorrect number of edges provided: " + edges.length + " versus " + this.nodeCount + " nodes.");
707 }
708
709 //first remove all the child nodes of the internal nodes
710 for (int i = this.externalNodeCount; i < this.nodeCount; i++) {
711 int childCount = nodes[i].getChildCount();
712 for (int j = 0; j < childCount; j++) {
713 nodes[i].removeChild(j);
714 }
715 }
716
717 //start with setting the external node heights
718 for (int i = 0; i < this.getExternalNodeCount(); i++) {
719 this.setNodeHeight(this.getExternalNode(nodeMap[i]), nodeHeights[i]);
720 }
721 //set the internal node heights
722 for (int i = 0; i < (this.getExternalNodeCount() - 1); i++) {
723 //No just restart counting, will fix later on in the code by adding additionalTaxa variable
724 this.setNodeHeight(this.getInternalNode(i), nodeHeights[this.getExternalNodeCount() + i]);
725 }
726
727 int newRootIndex = -1;
728 //now add the parent-child links again to ALL the nodes
729 for (int i = 0; i < edges.length; i++) {
730 if (edges[i] != -1) {
731 //make distinction between external nodes and internal nodes
732 if (i < this.getExternalNodeCount()) {
733 //external node
734 this.addChild(this.getNode(edges[i]), this.getExternalNode(nodeMap[i]));
735 System.out.println("external: " + edges[i] + " > " + nodeMap[i]);
736 } else {
737 //internal node
738 this.addChild(this.getNode(edges[i]), this.getNode(i));
739 System.out.println("internal: " + edges[i] + " > " + i);
740 }
741 } else {
742 newRootIndex = i;
743 }
744 }
745
746 //not possible to determine correct ordering of child nodes in the loop where they're being assigned
747 //hence perform possible swaps in a separate loop
748
749 for (int i = 0; i < edges.length; i++) {
750 if (edges[i] != -1) {
751 if(i < this.externalNodeCount) {
752 if (childOrder[i] == 0 && nodes[edges[i]].getChild(0) != nodes[nodeMap[i]]) {
753 //swap child nodes
754 Node childOne = nodes[edges[i]].removeChild(0);
755 Node childTwo = nodes[edges[i]].removeChild(1);
756 nodes[edges[i]].addChild(childTwo);
757 nodes[edges[i]].addChild(childOne);
758 }
759 }else{
760 if (childOrder[i] == 0 && nodes[edges[i]].getChild(0) != nodes[i]) {
761 //swap child nodes
762 Node childOne = nodes[edges[i]].removeChild(0);
763 Node childTwo = nodes[edges[i]].removeChild(1);
764 nodes[edges[i]].addChild(childTwo);
765 nodes[edges[i]].addChild(childOne);
766 }
767 }
768 }
769
770 }
771
772 this.setRoot(nodes[newRootIndex]);
773 }
774
775 private int[] createNodeMap(String[] taxaNames) {
776
777 System.out.println("Creating a node mapping:");
778
779 int external = this.getExternalNodeCount();
780
781 int[] nodeMap = new int[external];
782 for (int i = 0; i < taxaNames.length; i++) {
783 for (int j = 0; j < external; j++) {
784 if (taxaNames[i].equals(this.getNodeTaxon(this.getExternalNode(j)).getId())) {
785 //taxon found
786 nodeMap[i] = j;
787 }
788 }
789 }
790 return nodeMap;
791 }
792
793 /**
794 * Imports trait information from a file
795 * @param edges Edges are provided as index: child number; parent: array entry
796 * @param traitModels List of TreeParameterModel object that contain trait information
797 * @param traitValues Values to be copied into the List of TreeParameterModel objects
798 */
799 public void adoptTraitData(int[] edges, ArrayList<TreeParameterModel> traitModels, double[][] traitValues, String[] taxaNames) {
800 int[] nodeMap = createNodeMap(taxaNames);
801 int index = 0;
802
803 for (TreeParameterModel tpm : traitModels) {
804
805 for (int i = 0; i < this.getRoot().getNumber(); i++) {
806 if (i < this.getExternalNodeCount()) {
807 tpm.setNodeValue(this, this.getExternalNode(nodeMap[i]), traitValues[index][i]);
808 System.out.println("Setting external node " + this.getExternalNode(nodeMap[i]) + " to " + traitValues[index][i]);
809
810 } else {
811 tpm.setNodeValue(this, this.getNode(i), traitValues[index][i]);
812 System.out.println("Setting internal node " + this.getNode(i ) + " to " + traitValues[index][i]);
813 }
814 }
815
816 // In TreeParameterModel, when this.getRoot.getNumber() and rootNodeNumber.getValue(0) are not equal,
817 // handleRootMove() will get called and move parameter/trait values to different indices. Here, we
818 // preemptively move around trait values (if necessary) so that if handleRootMove() gets called, the
819 // trait values end up in the correct indices.
820 if(this.getRoot().getNumber() < edges.length-1){
821 tpm.setNodeValue(this, this.getNode(this.getRoot().getNumber()+1), traitValues[index][this.getNodeCount()-1]);
822 // System.out.println("Setting node " + this.getNode(this.getRoot().getNumber()+1) + " " + " to " + traitValues[index][this.getNodeCount()-1]);
823 }
824
825 for (int i = this.getRoot().getNumber()+2; i < edges.length; i++) {
826 tpm.setNodeValue(this, this.getNode(i), traitValues[index][i-1]);
827 // System.out.println("Setting node " + this.getNode(i ) + " to " + traitValues[index][i-1]);
828 }
829
830 index++;
831 }
832 }
833
834 /**
835 * Recursive algorithm to copy a proposed tree structure into the current treeModel.
836 */
837 private void addNodeStructure(Tree donorTree, NodeRef donorNode) {
838
839 NodeRef acceptorNode = null;
840 if (donorTree.isExternal(donorNode)) {
841 //external nodes can have different numbers between both trees
842 acceptorNode = this.nodes[this.getTaxonIndex(donorTree.getTaxonId(donorNode.getNumber()))];
843 } else {
844 //not really important for internal nodes
845 acceptorNode = this.nodes[donorNode.getNumber()];
846 }
847
848 setNodeHeight(acceptorNode, donorTree.getNodeHeight(donorNode));
849
850 //removing all child nodes up front currently works
851 //((Node)acceptorNode).leftChild = null;
852 //((Node)acceptorNode).rightChild = null;
853 /*int nrChildren = getChildCount(acceptorNode);
854 for (int i = 0; i < nrChildren; i++) {
855 this.removeChild(acceptorNode, this.getChild(acceptorNode, i));
856 }*/
857
858 for (int i = 0; i < donorTree.getChildCount(donorNode); i++) {
859 //add a check when the added child is an external node
860 if (donorTree.isExternal(donorTree.getChild(donorNode, i))) {
861 addChild(acceptorNode, this.nodes[this.getTaxonIndex(donorTree.getTaxonId(donorTree.getChild(donorNode, i).getNumber()))]);
862 } else {
863 addChild(acceptorNode, this.nodes[donorTree.getChild(donorNode, i).getNumber()]);
864 }
865 }
866
867 pushTreeChangedEvent(acceptorNode);
868
869 if (!donorTree.isExternal(donorNode)) {
870 for (int i = 0; i < donorTree.getChildCount(donorNode); i++) {
871 addNodeStructure(donorTree, donorTree.getChild(donorNode, i));
872 }
873 }
874
875 }
876
877 /**
878 * @return the number of statistics of this component.
879 */
880 public int getStatisticCount() {
881 return super.getStatisticCount() + 1;
882 }
883
884 /**
885 * @return the ith statistic of the component
886 */
887 public Statistic getStatistic(int i) {
888 if (i == super.getStatisticCount()) return root.heightParameter;
889 return super.getStatistic(i);
890 }
891
892 // public String getModelComponentName() {
893 // return TREE_MODEL;
894 // }
895
896 // **************************************************************
897 // TaxonList IMPLEMENTATION
898 // **************************************************************
899
900 /**
901 * @return a count of the number of taxa in the list.
902 */
903 public int getTaxonCount() {
904 return getExternalNodeCount();
905 }
906
907 /**
908 * @return the ith taxon in the list.
909 */
910 public Taxon getTaxon(int taxonIndex) {
911 return ((Node) getExternalNode(taxonIndex)).taxon;
912 }
913
914 /**
915 * @return the ID of the taxon of the ith external node. If it doesn't have
916 * a taxon, returns the ID of the node itself.
917 */
918 public String getTaxonId(int taxonIndex) {
919 Taxon taxon = getTaxon(taxonIndex);
920 if (taxon != null) {
921 return taxon.getId();
922 } else {
923 return null;
924 }
925 }
926
927 /**
928 * returns the index of the taxon with the given id.
929 */
930 public int getTaxonIndex(String id) {
931 for (int i = 0, n = getTaxonCount(); i < n; i++) {
932 if (getTaxonId(i).equals(id)) return i;
933 }
934 return -1;
935 }
936
937 /**
938 * returns the index of the given taxon.
939 */
940 public int getTaxonIndex(Taxon taxon) {
941 for (int i = 0, n = getTaxonCount(); i < n; i++) {
942 if (getTaxon(i) == taxon) return i;
943 }
944 return -1;
945 }
946
947 public List<Taxon> asList() {
948 List<Taxon> taxa = new ArrayList<Taxon>();
949 for (int i = 0, n = getTaxonCount(); i < n; i++) {
950 taxa.add(getTaxon(i));
951 }
952 return taxa;
953 }
954
955 public Iterator<Taxon> iterator() {
956 return new Iterator<Taxon>() {
957 private int index = -1;
958
959 public boolean hasNext() {
960 return index < getTaxonCount() - 1;
961 }
962
963 public Taxon next() {
964 index++;
965 return getTaxon(index);
966 }
967
968 public void remove() { /* do nothing */ }
969 };
970 }
971
972 /**
973 * @param taxonIndex the index of the taxon whose attribute is being fetched.
974 * @param name the name of the attribute of interest.
975 * @return an object representing the named attributed for the taxon of the given
976 * external node. If the node doesn't have a taxon then the nodes own attribute
977 * is returned.
978 */
979 public Object getTaxonAttribute(int taxonIndex, String name) {
980 Taxon taxon = getTaxon(taxonIndex);
981 if (taxon != null) {
982 return taxon.getAttribute(name);
983 }
984 return null;
985 }
986
987 // **************************************************************
988 // MutableTaxonList IMPLEMENTATION
989 // **************************************************************
990
991 public int addTaxon(Taxon taxon) {
992 throw new IllegalArgumentException("Cannot add taxon to a TreeModel");
993 }
994
995 public boolean removeTaxon(Taxon taxon) {
996 throw new IllegalArgumentException("Cannot add taxon to a TreeModel");
997 }
998
999 public void setTaxonId(int taxonIndex, String id) {
1000 throw new IllegalArgumentException("Cannot set taxon id in a TreeModel");
1001 }
1002
1003 public void setTaxonAttribute(int taxonIndex, String name, Object value) {
1004 throw new IllegalArgumentException("Cannot set taxon attribute in a TreeModel");
1005 }
1006
1007 public void addMutableTreeListener(MutableTreeListener listener) {
1008 } // Do nothing at the moment
1009
1010 public void addMutableTaxonListListener(MutableTaxonListListener listener) {
1011 } // Do nothing at the moment
1012
1013 // **************************************************************
1014 // Identifiable IMPLEMENTATION
1015 // **************************************************************
1016
1017 private String id = null;
1018
1019 /**
1020 * @return the id.
1021 */
1022 public String getId() {
1023 return id;
1024 }
1025
1026 /**
1027 * Sets the id.
1028 */
1029 public void setId(String id) {
1030 this.id = id;
1031 }
1032
1033 // **************************************************************
1034 // Attributable IMPLEMENTATION
1035 // **************************************************************
1036
1037 private Attributable.AttributeHelper treeAttributes = null;
1038
1039 /**
1040 * Sets an named attribute for this object.
1041 *
1042 * @param name the name of the attribute.
1043 * @param value the new value of the attribute.
1044 */
1045 public void setAttribute(String name, Object value) {
1046 if (treeAttributes == null)
1047 treeAttributes = new Attributable.AttributeHelper();
1048 treeAttributes.setAttribute(name, value);
1049 }
1050
1051 /**
1052 * @param name the name of the attribute of interest.
1053 * @return an object representing the named attributed for this object.
1054 */
1055 public Object getAttribute(String name) {
1056 if (treeAttributes == null)
1057 return null;
1058 else
1059 return treeAttributes.getAttribute(name);
1060 }
1061
1062 /**
1063 * @return an iterator of the attributes that this object has.
1064 */
1065 public Iterator<String> getAttributeNames() {
1066 if (treeAttributes == null)
1067 return null;
1068 else
1069 return treeAttributes.getAttributeNames();
1070 }
1071
1072 /**
1073 * @return a string containing a newick representation of the tree
1074 */
1075 public final String getNewick() {
1076 return TreeUtils.newick(this);
1077 }
1078
1079 /**
1080 * @return a string containing a newick representation of the tree
1081 */
1082 public String toString() {
1083 return getNewick();
1084 }
1085
1086 public Tree getCopy() {
1087 throw new UnsupportedOperationException("please don't call this function");
1088 }
1089
1090 // **************************************************************
1091 // XMLElement IMPLEMENTATION
1092 // **************************************************************
1093
1094 public Element createElement(Document document) {
1095 throw new RuntimeException("Not implemented yet");
1096 }
1097
1098 // ***********************************************************************
1099 // Private methods
1100 // ***********************************************************************
1101
1102 /**
1103 * @return the node that this parameter is a member of
1104 */
1105 public Node getNodeOfParameter(Parameter parameter) {
1106
1107 if (parameter == null) throw new IllegalArgumentException("Parameter is null!");
1108
1109 for (Node node : nodes) {
1110 if (node.heightParameter == parameter) {
1111 return node;
1112 }
1113 }
1114
1115 if (hasRates) {
1116 for (Node node : nodes) {
1117 if (node.rateParameter == parameter) {
1118 return node;
1119 }
1120 }
1121 }
1122 if (hasTraits) {
1123 for (Node node : nodes) {
1124 if (node.traitParameters.containsValue(parameter)) {
1125 return node;
1126 }
1127 }
1128 }
1129 throw new RuntimeException("Parameter not found in any nodes:" + parameter.getId() + " " + parameter.hashCode());
1130 // assume it is a trait parameter and return null
1131 // return null;
1132 }
1133
1134 /**
1135 * Get the root height parameter. Is private because it can only be called by the XMLParser
1136 */
1137 public Parameter getRootHeightParameter() {
1138
1139 return root.heightParameter;
1140 }
1141
1142 /**
1143 * @return the relevant node height parameter. Is private because it can only be called by the XMLParser
1144 */
1145 public Parameter createNodeHeightsParameter(boolean rootNode, boolean internalNodes, boolean leafNodes) {
1146
1147 if (!rootNode && !internalNodes && !leafNodes) {
1148 throw new IllegalArgumentException("At least one of rootNode, internalNodes or leafNodes must be true");
1149 }
1150
1151 CompoundParameter parameter = new CompoundParameter("nodeHeights(" + getId() + ")");
1152
1153 for (int i = externalNodeCount; i < nodeCount; i++) {
1154 if ((rootNode && nodes[i] == root) || (internalNodes && nodes[i] != root)) {
1155 parameter.addParameter(nodes[i].heightParameter);
1156 }
1157 }
1158
1159 if (leafNodes) {
1160 for (int i = 0; i < externalNodeCount; i++) {
1161 parameter.addParameter(nodes[i].heightParameter);
1162 }
1163 }
1164
1165 return parameter;
1166 }
1167
1168 public Parameter getLeafHeightParameter(NodeRef node) {
1169
1170 if (!isExternal(node)) {
1171 throw new RuntimeException("only leaves can be used with getLeafHeightParameter");
1172 }
1173
1174 isTipDateSampled = true;
1175
1176 return nodes[node.getNumber()].heightParameter;
1177 }
1178
1179 /**
1180 * @return the relevant node rate parameter. Is private because it can only be called by the XMLParser
1181 */
1182 public Parameter createNodeRatesParameter(double[] initialValues, boolean rootNode, boolean internalNodes, boolean leafNodes) {
1183
1184 if (!rootNode && !internalNodes && !leafNodes) {
1185 throw new IllegalArgumentException("At least one of rootNode, internalNodes or leafNodes must be true");
1186 }
1187
1188 CompoundParameter parameter = new CompoundParameter("nodeRates(" + getId() + ")");
1189
1190 hasRates = true;
1191
1192 for (int i = externalNodeCount; i < nodeCount; i++) {
1193 nodes[i].createRateParameter(initialValues);
1194 if ((rootNode && nodes[i] == root) || (internalNodes && nodes[i] != root)) {
1195 parameter.addParameter(nodes[i].rateParameter);
1196 }
1197 }
1198
1199 for (int i = 0; i < externalNodeCount; i++) {
1200 nodes[i].createRateParameter(initialValues);
1201 if (leafNodes) {
1202 parameter.addParameter(nodes[i].rateParameter);
1203 }
1204 }
1205
1206 return parameter;
1207 }
1208
1209 public Parameter createNodeTraitsParameter(String name, double[] initialValues) {
1210 return createNodeTraitsParameter(name, initialValues.length,
1211 initialValues, true, true, true, true);
1212 }
1213
1214 /**
1215 * Create a node traits parameter. Is private because it can only be called by the XMLParser
1216 */
1217 public Parameter createNodeTraitsParameter(String name, int dim, double[] initialValues,
1218 boolean rootNode, boolean internalNodes,
1219 boolean leafNodes, boolean firesTreeEvents) {
1220
1221 checkValidFlags(rootNode, internalNodes, leafNodes);
1222
1223 CompoundParameter parameter = new CompoundParameter(name);
1224
1225 hasTraits = true;
1226
1227 for (int i = externalNodeCount; i < nodeCount; i++) {
1228 nodes[i].createTraitParameter(name, dim, initialValues, firesTreeEvents);
1229 if ((rootNode && nodes[i] == root) || (internalNodes && nodes[i] != root)) {
1230 parameter.addParameter(nodes[i].getTraitParameter(name));
1231 }
1232 }
1233
1234 for (int i = 0; i < externalNodeCount; i++) {
1235 nodes[i].createTraitParameter(name, dim, initialValues, firesTreeEvents);
1236 if (leafNodes) {
1237 parameter.addParameter(nodes[i].getTraitParameter(name));
1238 }
1239 }
1240
1241 return parameter;
1242 }
1243
1244 public Parameter createNodeTraitsParameterAsMatrix(String name, int dim, double[] initialValues,
1245 boolean rootNode, boolean internalNodes,
1246 boolean leafNodes, boolean firesTreeEvents) {
1247
1248 checkValidFlags(rootNode, internalNodes, leafNodes);
1249
1250 final int rowDim = dim;
1251 final int colDim = (rootNode ? 1 : 0)
1252 + (internalNodes ? internalNodeCount - 1 : 0)
1253 + (leafNodes ? externalNodeCount : 0);
1254
1255 FastMatrixParameter parameter = new FastMatrixParameter(name, rowDim, colDim, 0.0);
1256 parameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY,
1257 rowDim * colDim));
1258
1259 hasTraits = true;
1260
1261 int parameterIndex = 0;
1262 for (int i = externalNodeCount; i < nodeCount; i++) {
1263 if ((rootNode && nodes[i] == root) || (internalNodes && nodes[i] != root)) {
1264 nodes[i].addTraitParameter(name, parameter.getParameter(parameterIndex), initialValues, firesTreeEvents);
1265 ++parameterIndex;
1266 }
1267 }
1268
1269 for (int i = 0; i < externalNodeCount; i++) {
1270 if (leafNodes) {
1271 nodes[i].addTraitParameter(name, parameter.getParameter(parameterIndex), initialValues, firesTreeEvents);
1272 ++parameterIndex;
1273 }
1274 }
1275
1276 return parameter;
1277 }
1278
1279 private void checkValidFlags(boolean rootNode, boolean internalNodes, boolean leafNodes) {
1280 if (!rootNode && !internalNodes && !leafNodes) {
1281 throw new IllegalArgumentException("At least one of rootNode, internalNodes or leafNodes must be true");
1282 }
1283 }
1284
1285 private void swapAllTraits(Node n1, Node n2) {
1286
1287 for (Map.Entry<String, Parameter> entry : n1.traitParameters.entrySet()) {
1288 Parameter p1 = n1.traitParameters.get(entry.getKey());
1289 Parameter p2 = n2.traitParameters.get(entry.getKey());
1290 final int dim = p1.getDimension();
1291 for (int i = 0; i < dim; i++) {
1292 double transfer = p1.getParameterValue(i);
1293 p1.setParameterValue(i, p2.getParameterValue(i));
1294 p2.setParameterValue(i, transfer);
1295 }
1296
1297 }
1298
1299 }
1300
1301 /**
1302 * This method swaps the parameter objects of the two nodes
1303 * but maintains the values in each node.
1304 * This method is used to ensure that root node of the tree
1305 * always has the same parameter object.
1306 */
1307 private void swapParameterObjects(Node n1, Node n2) {
1308
1309 double height1 = n1.getHeight();
1310 double height2 = n2.getHeight();
1311
1312 double rate1 = 1.0, rate2 = 1.0;
1313
1314 if (hasRates) {
1315 rate1 = n1.getRate();
1316 rate2 = n2.getRate();
1317 }
1318
1319 // swap all trait parameters
1320
1321 if (hasTraits) {
1322 Map<String, Parameter> traits1 = new HashMap<String, Parameter>();
1323 Map<String, Parameter> traits2 = new HashMap<String, Parameter>();
1324
1325 traits1.putAll(n1.traitParameters);
1326 traits2.putAll(n2.traitParameters);
1327
1328 Map<String, Parameter> temp = n1.traitParameters;
1329 n1.traitParameters = n2.traitParameters;
1330 n2.traitParameters = temp;
1331
1332 for (Map.Entry<String, Parameter> entry : traits1.entrySet()) {
1333 n1.traitParameters.get(entry.getKey()).setParameterValueQuietly(0, entry.getValue().getParameterValue(0));
1334 }
1335 for (Map.Entry<String, Parameter> entry : traits2.entrySet()) {
1336 n2.traitParameters.get(entry.getKey()).setParameterValueQuietly(0, entry.getValue().getParameterValue(0));
1337 }
1338 }
1339
1340 Parameter temp = n1.heightParameter;
1341 n1.heightParameter = n2.heightParameter;
1342 n2.heightParameter = temp;
1343
1344 if (hasRates) {
1345 temp = n1.rateParameter;
1346 n1.rateParameter = n2.rateParameter;
1347 n2.rateParameter = temp;
1348 }
1349
1350 n1.heightParameter.setParameterValueQuietly(0, height1);
1351 n2.heightParameter.setParameterValueQuietly(0, height2);
1352
1353 if (hasRates) {
1354 n1.rateParameter.setParameterValueQuietly(0, rate1);
1355 n2.rateParameter.setParameterValueQuietly(0, rate2);
1356 }
1357 }
1358
1359 // **************************************************************
1360 // Private inner classes
1361 // **************************************************************
1362
1363 public class Node implements NodeRef {
1364
1365 public Node parent;
1366 public Node leftChild, rightChild;
1367 private int number;
1368 public Parameter heightParameter;
1369 public Parameter rateParameter = null;
1370 //public Parameter traitParameter = null;
1371 public Taxon taxon = null;
1372
1373 Map<String, Parameter> traitParameters = new HashMap<String, Parameter>();
1374
1375 public Node() {
1376 parent = null;
1377 leftChild = rightChild = null;
1378 heightParameter = null;
1379 number = 0;
1380 taxon = null;
1381 }
1382
1383 /**
1384 * constructor used to clone a node and all children
1385 */
1386 public Node(Tree tree, NodeRef node) {
1387 parent = null;
1388 leftChild = rightChild = null;
1389
1390 heightParameter = new Parameter.Default(tree.getNodeHeight(node));
1391 addVariable(heightParameter);
1392
1393 number = node.getNumber();
1394 taxon = tree.getNodeTaxon(node);
1395 heightParameter.setId("" + number);
1396 for (int i = 0; i < tree.getChildCount(node); i++) {
1397 addChild(new Node(tree, tree.getChild(node, i)));
1398 }
1399 }
1400
1401 public final void setupHeightBounds() {
1402 heightParameter.addBounds(new NodeHeightBounds(heightParameter));
1403 }
1404
1405 public final void createRateParameter(double[] initialValues) {
1406 if (rateParameter == null) {
1407 if (initialValues != null) {
1408 rateParameter = new Parameter.Default(initialValues[0]);
1409 } else {
1410 rateParameter = new Parameter.Default(1.0);
1411 }
1412 setParameterId("rate", rateParameter);
1413 rateParameter.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, 0.0, 1));
1414 addVariable(rateParameter);
1415 }
1416 }
1417
1418 public final void createTraitParameter(String name, double[] initialValues, boolean firesTreeEvents) {
1419 createTraitParameter(name, initialValues.length, initialValues, firesTreeEvents);
1420 }
1421
1422 public final void addTraitParameter(String name, Parameter trait, double[] initialValues, boolean firesTreeEvents) {
1423 if (!traitParameters.containsKey(name)) {
1424 setParameterId(name, trait);
1425 setParameterValues(trait, trait.getDimension(), initialValues);
1426
1427 traitParameters.put(name, trait);
1428
1429 if (firesTreeEvents) {
1430 addVariable(trait);
1431 }
1432 }
1433 }
1434
1435 private void setParameterValues(Parameter parameter, int dim, double[] initialValues) {
1436 if (initialValues != null && initialValues.length > 0) {
1437 for (int i = 0; i < dim; i++) {
1438 if (initialValues.length == dim) {
1439 parameter.setParameterValue(i, initialValues[i]);
1440 } else {
1441 parameter.setParameterValue(i, initialValues[0]);
1442 }
1443 }
1444 }
1445 }
1446
1447 public final void createTraitParameter(String name, int dim, double[] initialValues, boolean firesTreeEvents) {
1448
1449 if (!traitParameters.containsKey(name)) {
1450
1451 Parameter trait = new Parameter.Default(dim);
1452 setParameterId(name, trait);
1453 trait.addBounds(new Parameter.DefaultBounds(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, dim));
1454
1455 setParameterValues(trait, dim, initialValues);
1456
1457 traitParameters.put(name, trait);
1458
1459 if (firesTreeEvents) {
1460 addVariable(trait);
1461 }
1462 }
1463 }
1464
1465 private void setParameterId(String name, Parameter trait) {
1466 if (isRoot()) {
1467 trait.setId("root." + name);
1468 } else if (isExternal()) {
1469 trait.setId(getTaxonId(getNumber()) + "." + name);
1470 } else {
1471 trait.setId("node" + getNumber() + "." + name);
1472 }
1473 }
1474
1475 public final double getHeight() {
1476 return heightParameter.getParameterValue(0);
1477 }
1478
1479 public final double getRate() {
1480 return rateParameter.getParameterValue(0);
1481 }
1482
1483 public final double getTrait(String name) {
1484 return traitParameters.get(name).getParameterValue(0);
1485 }
1486
1487 public final double[] getMultivariateTrait(String name) {
1488 return traitParameters.get(name).getParameterValues();
1489 }
1490
1491 public final Map<String, Parameter> getTraitMap() {
1492 return traitParameters;
1493 }
1494
1495 public final void setHeight(double height) {
1496 heightParameter.setParameterValue(0, height);
1497 }
1498
1499 public final void setRate(double rate) {
1500 //System.out.println("Rate set for parameter " + rateParameter.getParameterName());
1501 rateParameter.setParameterValue(0, rate);
1502 }
1503
1504 public final void setTrait(String name, double trait) {
1505 //System.out.println("Trait set for parameter " + traitParameter.getParameterName());
1506 traitParameters.get(name).setParameterValue(0, trait);
1507 }
1508
1509 public final void setMultivariateTrait(String name, double[] trait) {
1510 int dim = trait.length;
1511 for (int i = 0; i < dim; i++)
1512 traitParameters.get(name).setParameterValue(i, trait[i]);
1513 }
1514
1515 public int getNumber() {
1516 return number;
1517 }
1518
1519 public void setNumber(int n) {
1520 number = n;
1521 }
1522
1523 /**
1524 * Returns the number of children this node has.
1525 */
1526 public final int getChildCount() {
1527 int n = 0;
1528 if (leftChild != null) n++;
1529 if (rightChild != null) n++;
1530 return n;
1531 }
1532
1533 public Node getChild(int n) {
1534 if (n == 0) return leftChild;
1535 if (n == 1) return rightChild;
1536 throw new IllegalArgumentException("TreeModel.Nodes can only have 2 children");
1537 }
1538
1539 public boolean hasChild(Node node) {
1540 return (leftChild == node || rightChild == node);
1541 }
1542
1543 /**
1544 * add new child node
1545 *
1546 * @param node new child node
1547 */
1548 public void addChild(Node node) {
1549 if (leftChild == null) {
1550 leftChild = node;
1551 } else if (rightChild == null) {
1552 rightChild = node;
1553 } else {
1554 throw new IllegalArgumentException("TreeModel.Nodes can only have 2 children");
1555 }
1556 node.parent = this;
1557 }
1558
1559 /**
1560 * remove child
1561 *
1562 * @param node child to be removed
1563 */
1564 public Node removeChild(Node node) {
1565 if (leftChild == node) {
1566 leftChild = null;
1567 } else if (rightChild == node) {
1568 rightChild = null;
1569 } else {
1570 throw new IllegalArgumentException("Unknown child node");
1571 }
1572 node.parent = null;
1573 return node;
1574 }
1575
1576 /**
1577 * remove child
1578 *
1579 * @param n number of child to be removed
1580 */
1581 public Node removeChild(int n) {
1582 Node node;
1583 if (n == 0) {
1584 node = leftChild;
1585 leftChild = null;
1586 } else if (n == 1) {
1587 node = rightChild;
1588 rightChild = null;
1589 } else {
1590 throw new IllegalArgumentException("TreeModel.Nodes can only have 2 children");
1591 }
1592 node.parent = null;
1593 return node;
1594 }
1595
1596 public boolean hasNoChildren() {
1597 return (leftChild == null && rightChild == null);
1598 }
1599
1600 public boolean isExternal() {
1601 return hasNoChildren();
1602 }
1603
1604 public boolean isRoot() {
1605 return (parent == null);
1606 }
1607
1608 public String toString() {
1609 return "node " + number + ", height=" + getHeight() + (taxon != null ? ": " + taxon.getId() : "");
1610 }
1611
1612 public Parameter getTraitParameter(String name) {
1613 return traitParameters.get(name);
1614 }
1615 }
1616
1617 /**
1618 * This class provides bounds for parameters that represent a node height
1619 * in this tree model.
1620 */
1621 private class NodeHeightBounds implements Bounds<Double> {
1622
1623 public NodeHeightBounds(Parameter parameter) {
1624 nodeHeightParameter = parameter;
1625 }
1626
1627 public Double getUpperLimit(int i) {
1628
1629 Node node = getNodeOfParameter(nodeHeightParameter);
1630 if (node.isRoot()) {
1631 return Double.POSITIVE_INFINITY;
1632 } else {
1633 return node.parent.getHeight();
1634 }
1635 }
1636
1637 public Double getLowerLimit(int i) {
1638
1639 Node node = getNodeOfParameter(nodeHeightParameter);
1640 if (node.isExternal()) {
1641 return 0.0;
1642 } else {
1643 return Math.max(node.leftChild.getHeight(), node.rightChild.getHeight());
1644 }
1645 }
1646
1647 public int getBoundsDimension() {
1648 return 1;
1649 }
1650
1651
1652 private Parameter nodeHeightParameter = null;
1653 }
1654
1655 // ***********************************************************************
1656 // Interface: Keywordable
1657 // ***********************************************************************
1658
1659 @Override
1660 public void addKeyword(String keyword) {
1661 keywords.add(keyword);
1662 }
1663
1664 @Override
1665 public List<String> getKeywords() {
1666 return keywords;
1667 }
1668
1669 private final List<String> keywords = new ArrayList<String>();
1670
1671 // ***********************************************************************
1672 // Private members
1673 // ***********************************************************************
1674
1675
1676 /**
1677 * root node
1678 */
1679 private Node root = null;
1680 private int storedRootNumber;
1681
1682 /**
1683 * list of internal nodes (including root)
1684 */
1685 private Node[] nodes = null;
1686 private Node[] storedNodes = null;
1687
1688 /**
1689 * number of nodes (including root and tips)
1690 */
1691 private final int nodeCount;
1692
1693 /**
1694 * number of external nodes
1695 */
1696 private final int externalNodeCount;
1697
1698 /**
1699 * number of internal nodes (including root)
1700 */
1701 private final int internalNodeCount;
1702
1703 /**
1704 * holds the units of the trees branches.
1705 */
1706 private Type units = Type.SUBSTITUTIONS;
1707
1708 private boolean inEdit = false;
1709
1710 private boolean hasRates = false;
1711 private boolean hasTraits = false;
1712 private boolean isTipDateSampled = false;
1713 private final boolean isTreeRandom;
1714
1715 public boolean isTipDateSampled() {
1716 return isTipDateSampled;
1717 }
1718
1719 @Override
1720 public boolean isVariable() {
1721 return isTreeRandom;
1722 }
1723
1724 @Override
1725 public Citation.Category getCategory() {
1726 return Citation.Category.TREE_PRIORS;
1727 }
1728
1729 @Override
1730 public String getDescription() {
1731 return "Sampling tip dates model";
1732 }
1733
1734 @Override
1735 public List<Citation> getCitations() {
1736 if (isTipDateSampled()) {
1737 return Arrays.asList(new Citation(
1738 new Author[]{
1739 new Author("B", "Shapiro"),
1740 new Author("SYW", "Ho"),
1741 new Author("AJ", "Drummond"),
1742 new Author("MA", "Suchard"),
1743 new Author("OG", "Pybus"),
1744 new Author("A", "Rambaut"),
1745 },
1746 "A Bayesian phylogenetic method to estimate unknown sequence ages",
1747 2010,
1748 "Mol Biol Evol",
1749 28,
1750 879, 887,
1751 "10.1093/molbev/msq262"
1752 ),
1753 new Citation(
1754 new Author[]{
1755 new Author("AJ", "Drummond"),
1756 },
1757 "PhD Thesis",
1758 2002,
1759 "University of Auckland",
1760 ""
1761 ));
1762 } else {
1763 return Collections.EMPTY_LIST;
1764 }
1765 }
1766
1767 }