Debian Codegraph @

src/dr/evomodel/arg/ARGModel.java

raw symbols SCIP
1 /*
2 * ARGModel.java
3 *
4 * Copyright (c) 2002-2015 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 /*
27 * ARGModel.java
28 *
29 * (c) 2002-2005 BEAST Development Core Team
30 *
31 * This package may be distributed under the
32 * Lesser Gnu Public Licence (LGPL)
33 */
34
35 package dr.evomodel.arg;
36
37 import dr.evolution.tree.*;
38 import dr.evolution.util.MutableTaxonListListener;
39 import dr.evolution.util.Taxon;
40 import dr.evomodel.arg.likelihood.ARGLikelihood;
41 import dr.evomodel.tree.TreeChangedEvent;
42 import dr.evomodelxml.tree.TreeModelParser;
43 import dr.inference.loggers.LogColumn;
44 import dr.inference.loggers.Loggable;
45 import dr.inference.loggers.NumberColumn;
46 import dr.inference.model.*;
47 import dr.inference.parallel.MPIServices;
48 import dr.math.MathUtils;
49 import dr.util.Attributable;
50 import dr.util.NumberFormatter;
51 import dr.xml.*;
52 import org.jdom.Document;
53 import org.jdom.Element;
54
55 import java.util.ArrayList;
56 import java.util.Iterator;
57 import java.util.List;
58 import java.util.StringTokenizer;
59 import java.util.logging.Logger;
60
61 /**
62 * A model component for trees.
63 *
64 * @author Marc A. Suchard
65 * @author Eric Bloomquist
66 */
67 public class ARGModel extends AbstractModel implements MutableTree, Loggable {
68
69
70 public static final String TREE_MODEL = "argTreeModel";
71 public static final String ROOT_HEIGHT = TreeModelParser.ROOT_HEIGHT;
72 public static final String LEAF_HEIGHT = "leafHeight";
73 public static final String NODE_HEIGHTS = "nodeHeights";
74 public static final String NODE_RATES = TreeModelParser.NODE_RATES;
75 public static final String NODE_TRAITS = TreeModelParser.NODE_TRAITS;
76 public static final String ROOT_NODE = "rootNode";
77 public static final String INTERNAL_NODES = "internalNodes";
78 public static final String LEAF_NODES = "leafNodes";
79 public static final String TAXON = "taxon";
80 public static final String GRAPH_ELEMENT = "graph";
81 public static final String NODE_ELEMENT = "node";
82 public static final String EDGE_ELEMENT = "edge";
83 public static final String ID_ATTRIBUTE = XMLParser.ID;
84 public static final String EDGE_FROM = "source";
85 public static final String EDGE_TO = "target";
86 public static final String TAXON_NAME = "taxonName";
87 public static final String EDGE_LENGTH = "len";
88 public static final String EDGE_PARTITIONS = "edgePartitions";
89 public static final String IS_TIP = "isTip";
90 public static final String IS_ROOT = "isRoot";
91 public static final String LEFT_PARENT = "leftParent";
92 public static final String RIGHT_PARENT = "rightParent";
93 public static final String LEFT_CHILD = "leftChild";
94 public static final String RIGHT_CHILD = "rightChild";
95 public static final String NODE_HEIGHT = "nodeHeight";
96 public static final String IS_REASSORTMENT = "true";
97 public static final String NUM_PARTITIONS = "numberOfPartitions";
98 public static final String GRAPH_SIZE = "size=\"6,6\"";
99 public static final String DOT_EDGE_DEF = "edge[style=\"setlinewidth(2)\",arrowhead=none]";
100 public static final String DOT_NODE_DEF = "node[shape=plaintext,width=auto,fontname=Helvitica,fontsize=10]";
101
102 public static final int LEFT = 0;
103 public static final int RIGHT = 1;
104
105 public static final String PARTITION_TYPE = "partitionType";
106 public static final String REASSORTMENT_PARTITION = "reassortment";
107 public static final String RECOMBINATION_PARTITION = "recombination";
108 public static final String PARTITION_DEFAULT_TYPE = REASSORTMENT_PARTITION;
109
110 // ***********************************************************************
111 // Private members
112 // ***********************************************************************
113
114 protected int storedRootNumber;
115 protected int nodeCount;
116 protected int storedNodeCount;
117 protected int externalNodeCount;
118 protected int internalNodeCount;
119 protected int storedInternalNodeCount;
120 protected boolean inEdit = false;
121
122 protected Node root = null;
123 public ArrayList<Node> nodes = null;
124 public ArrayList<Node> storedNodes = null;
125 protected Parameter[] addedParameters = null;
126 protected Parameter[] removedParameters = null;
127 protected Parameter addedPartitioningParameter = null;
128 protected Parameter removedPartitioningParameter = null;
129 protected CompoundParameter partitioningParameters;
130 protected CompoundParameter storedInternalNodeHeights;
131 protected CompoundParameter storedInternalAndRootNodeHeights;
132 protected CompoundParameter storedNodeRates;
133 protected Node[] addedNodes = null;
134 protected Node[] removedNodes = null;
135
136 // private int units = SUBSTITUTIONS;
137 private Type units;
138 private boolean hasRates = false;
139 private boolean hasTraits = false;
140 private int nullCounter = 0;
141 private int storedNullCounter;
142
143 protected String partitionType = PARTITION_DEFAULT_TYPE;
144
145
146 public ARGModel(ArrayList<Node> nodes, Node root, int numberPartitions,
147 int externalNodeCount) {
148 super(TREE_MODEL);
149 this.nodes = nodes;
150 this.root = root;
151 this.maxNumberOfPartitions = numberPartitions;
152 this.externalNodeCount = externalNodeCount;
153 if (nodes != null)
154 this.nodeCount = nodes.size();
155 this.internalNodeCount = this.nodeCount - externalNodeCount;
156 }
157
158 public ARGModel(Tree tree) {
159
160 super(TREE_MODEL);
161 // System.err.println("constructor for TreeModel");
162 partitioningParameters = new CompoundParameter("partitioning");
163 // initialize(tree);
164 // }
165
166 // protected void initialize(Tree tree) {
167 // System.err.println("init for TreeModel");
168 // System.exit(-1);
169 // get a rooted version of the tree to clone
170 FlexibleTree binaryTree = new FlexibleTree(tree);
171 binaryTree.resolveTree();
172
173 // clone the node structure (this will create the individual parameters
174 Node node = new Node(binaryTree, binaryTree.getRoot());
175
176 internalNodeCount = binaryTree.getInternalNodeCount();
177 externalNodeCount = binaryTree.getExternalNodeCount();
178
179 nodeCount = internalNodeCount + externalNodeCount;
180
181 // nodes = new Node[nodeCount];
182 // storedNodes = new Node[nodeCount];
183 nodes = new ArrayList<Node>(nodeCount);
184 storedNodes = new ArrayList<Node>(nodeCount);
185 for (int i = 0; i < nodeCount; i++) {
186 nodes.add(null);
187 storedNodes.add(null);
188 }
189 int i = 0;
190 int j = externalNodeCount;
191
192 root = node;
193
194 // System.err.println("Going to do postOrder");
195
196 do {
197 node = (Node) TreeUtils.postorderSuccessor(this, node);
198
199 if (node.isExternal()) {
200 node.number = i;
201
202 // nodes[i] = node;
203 // storedNodes[i] = new Node();
204 // storedNodes[i].taxon = node.taxon;
205 // storedNodes[i].number = i;
206 nodes.set(i, node);
207 Node copy = new Node();
208 copy.taxon = node.taxon;
209 copy.number = i;
210 storedNodes.set(i, copy);
211
212 i++;
213 } else {
214 node.number = j;
215
216 // nodes[j] = node;
217 // storedNodes[j] = new Node();
218 // storedNodes[j].number = j;
219 nodes.set(j, node);
220 Node copy = new Node();
221 copy.number = j;
222 storedNodes.set(j, copy);
223
224 j++;
225 }
226 } while (node != root);
227
228 // System.err.println("Succeed in post-order");
229
230 // ARGTree t = new ARGTree(this,0);
231 // System.err.println(Tree.Utils.uniqueNewick(t, t.getRoot()));
232 // System.err.println(this.toGraphString());
233 // System.exit(-1);
234
235 }
236
237 private double nextTime(int nTaxa, double pSize, double rRate) {
238 double t = (double) nTaxa;
239
240 double s = t * (t - 1 + rRate) / (2.0 * pSize);
241 return MathUtils.nextExponential(s);
242 }
243
244 private boolean nextEventIsBifurcation(int nTaxa, double rRate) {
245 double a = (double) (nTaxa - 1) / (nTaxa - 1 + rRate);
246 if (MathUtils.nextDouble() < a) {
247 return true;
248 }
249 return false;
250 }
251
252 private class SimulateSticks {
253 public final Node mySon;
254 public final boolean leftStick;
255
256 public SimulateSticks(Node son, boolean left) {
257 mySon = son;
258 leftStick = left;
259 }
260 }
261
262 public ARGModel(int ntaxa, double popSize, double rRate) {
263 super("Simulator");
264
265 ArrayList<SimulateSticks> currentStickList = new ArrayList<SimulateSticks>(50);
266 ArrayList<Node> currentNodeList = new ArrayList<Node>(50);
267
268 nodes = new ArrayList<Node>();
269
270 int nodeNumber = 0;
271
272 for (int i = 0; i < ntaxa; i++) {
273 Node node = new Node();
274 node.heightParameter = new Parameter.Default(0.0);
275 nodes.add(node);
276 currentNodeList.add(node);
277 node.bifurcation = true;
278 node.number = nodeNumber;
279 nodeNumber++;
280
281 node.taxon = new Taxon("" + nodeNumber);
282 SimulateSticks stickGuy = new SimulateSticks(node, true);
283 currentStickList.add(stickGuy);
284 }
285
286 double currentHeight = 0;
287
288 while (currentStickList.size() > 1) {
289 currentHeight = currentHeight + nextTime(currentStickList.size(), popSize, rRate);
290
291 if (nextEventIsBifurcation(currentStickList.size(), rRate)) {
292 SimulateSticks[] sticks = new SimulateSticks[2];
293
294 for (int i = 0; i < 2; i++) {
295 int randomDraw = MathUtils.nextInt(currentStickList.size());
296 sticks[i] = currentStickList.get(randomDraw);
297 currentStickList.remove(randomDraw);
298 }
299
300 Node node = new Node();
301 nodes.add(node);
302 node.heightParameter = new Parameter.Default(currentHeight);
303 node.number = nodeNumber;
304 nodeNumber++;
305 node.bifurcation = true;
306 SimulateSticks stickGuy = new SimulateSticks(node, true);
307
308 if (sticks[0].mySon == sticks[1].mySon) {
309 Node child = sticks[0].mySon;
310 node.leftChild = child;
311 node.rightChild = child;
312 child.rightParent = node;
313 child.leftParent = node;
314
315 currentNodeList.remove(currentNodeList.indexOf(child));
316 currentNodeList.add(node);
317 currentStickList.add(stickGuy);
318 } else {
319 Node child1 = sticks[0].mySon;
320 Node child2 = sticks[1].mySon;
321
322 node.leftChild = child1;
323 node.rightChild = child2;
324
325 if (child1.bifurcation) {
326 child1.leftParent = node;
327 child1.rightParent = node;
328 currentNodeList.remove(currentNodeList.indexOf(child1));
329 } else {
330 if (sticks[0].leftStick) {
331 child1.leftParent = node;
332 } else {
333 child1.rightParent = node;
334 }
335 if (child1.leftParent != null && child1.rightParent != null) {
336 currentNodeList.remove(currentNodeList.indexOf(child1));
337 }
338 }
339
340 if (child2.bifurcation) {
341 child2.leftParent = node;
342 child2.rightParent = node;
343 currentNodeList.remove(currentNodeList.indexOf(child2));
344 } else {
345 if (sticks[1].leftStick) {
346 child2.leftParent = node;
347 } else {
348 child2.rightParent = node;
349 }
350 if (child2.leftParent != null && child2.rightParent != null) {
351 currentNodeList.remove(currentNodeList.indexOf(child2));
352 }
353 }
354 currentNodeList.add(node);
355 currentStickList.add(stickGuy);
356 }
357 } else {
358 int randomDraw = MathUtils.nextInt(currentStickList.size());
359 SimulateSticks stick = currentStickList.get(randomDraw);
360 currentStickList.remove(randomDraw);
361
362 Node node = new Node();
363 nodes.add(node);
364 node.heightParameter = new Parameter.Default(currentHeight);
365 node.number = nodeNumber;
366 nodeNumber++;
367 node.bifurcation = false;
368 SimulateSticks leftStickGuy = new SimulateSticks(node, true);
369 SimulateSticks rightStickGuy = new SimulateSticks(node, false);
370
371 Node child = stick.mySon;
372 node.leftChild = child;
373 node.rightChild = child;
374
375 if (child.bifurcation) {
376 child.leftParent = node;
377 child.rightParent = node;
378 currentNodeList.remove(currentNodeList.indexOf(child));
379 } else {
380 if (stick.leftStick) {
381 child.leftParent = node;
382 } else {
383 child.rightParent = node;
384 }
385 if (child.leftParent != null & child.rightParent != null) {
386 currentNodeList.remove(currentNodeList.indexOf(child));
387 }
388 }
389
390 currentNodeList.add(node);
391 currentStickList.add(leftStickGuy);
392 currentStickList.add(rightStickGuy);
393 }
394
395 }
396
397 root = currentNodeList.get(0);
398
399 //nodeNumber--;
400
401 // nodes = new Node[nodeNumber];
402
403
404 }
405
406
407 public int possibleInternalNodePermuations() {
408
409 int max = getInternalNodeCount();
410 ArrayList<Double> remainingHeights = new ArrayList<Double>(max - 1);
411
412 for (Node node : nodes) {
413 if (!node.isExternal() && !node.isRoot())
414 remainingHeights.add(node.getHeight());
415 }
416
417 int firstNode = 0;
418 while (nodes.get(firstNode).isExternal() || nodes.get(firstNode).isRoot())
419 firstNode++;
420
421 int result = possibleInternalNodePermutations(firstNode, remainingHeights);
422
423 // Restore heights
424 int i = 0;
425 for (Node node : nodes) {
426 if (!node.isExternal() && !node.isRoot()) {
427 node.setHeight(remainingHeights.get(i++));
428 }
429 }
430
431 return factorial(max - 1) - result;
432 }
433
434 private int factorial(int x) {
435 int result = 1;
436 for (int i = 2; i <= x; i++)
437 result *= i;
438 return result;
439 }
440
441
442 private int possibleInternalNodePermutations(int nodeNumber, ArrayList<Double> remainingHeights) {
443
444 int total = 0;
445
446 if (remainingHeights.size() == 0) {
447 return 0;
448 }
449
450 int newNodeNumber = nodeNumber + 1;
451 if (remainingHeights.size() > 1) {
452 while (nodes.get(newNodeNumber).isExternal() || nodes.get(newNodeNumber).isRoot())
453 newNodeNumber++;
454 }
455
456 Node nr = nodes.get(nodeNumber);
457
458 for (double height : remainingHeights) {
459
460 if (height < getNodeHeight(getParent(nr, 0)) &&
461 height < getNodeHeight(getParent(nr, 1))) {
462 setNodeHeight(nr, height);
463
464 ArrayList<Double> copy0 = deepCopy(remainingHeights);
465 if (!copy0.contains(height))
466 System.err.println("where did i go?");
467 copy0.remove(height);
468
469 total += possibleInternalNodePermutations(newNodeNumber, copy0);
470
471 } else {
472 // The remaining permutations will not work
473 total += factorial(remainingHeights.size() - 1);
474 }
475
476 }
477
478 return total;
479 }
480
481
482 private ArrayList<Double> deepCopy(ArrayList<Double> in) {
483 ArrayList<Double> out = new ArrayList<Double>();
484 for (double d : in) {
485 out.add(d);
486 }
487 return out;
488 }
489
490 private static boolean containsLessThan(int[] a, int b) {
491 for (int c : a) {
492 if (c < b)
493 return true;
494 }
495 return false;
496 }
497
498 public static void main(String[] args) {
499 ARGModel arg = new ARGModel(8, 20.0, 0.5);
500 System.out.println(arg.toARGSummary());
501 System.out.println(arg.getReassortmentNodeCount());
502 System.out.println(arg.toExtendedNewick());
503 // BufferedWriter out = null;
504 //
505 // try {
506 // out = new BufferedWriter(new FileWriter("rejections.txt"));
507 // } catch (Exception e) {
508 // System.exit(-1);
509 // }
510 //
511 // int rejections = 0;
512 //
513 // MathUtils.setSeed(97695);
514 //
515 // ArrayList<String> trees = new ArrayList<String>(10000);
516 //
517 // while (rejections < 100) {
518 // ARGModel arg = new ARGModel(3, 6.0, 1.0);
519 // String s = "";
520 // if (arg.getReassortmentNodeCount() < 2) {
521 // s = arg.toStrippedNewick();
522 // }
523 //
524 // if (!s.equals("") && !trees.contains(s)) {
525 // trees.add(s);
526 // System.out.println("Total Current Size = " + trees.size() + " Rejections= " + rejections);
527 // rejections = 0;
528 // } else {
529 // rejections++;
530 // }
531 // }
532 //
533 // System.out.println("\n************************************");
534 // System.out.println("Simulating trees");
535 //
536 // Collections.sort(trees);
537 // int[] freq = new int[trees.size()];
538 // int[] mcmcFreq = new int[trees.size()];
539 // rejections = 0;
540 //
541 // while (containsLessThan(freq, 10000)) {
542 // ARGModel arg = new ARGModel(3, 6.0, 1.0);
543 // String s = null;
544 // if (arg.getReassortmentNodeCount() < 2) {
545 // s = arg.toStrippedNewick();
546 // }
547 //
548 // if (s != null) {
549 // freq[Collections.binarySearch(trees, s)]++;
550 // }
551 // rejections++;
552 // if (rejections % 1000000 == 0) {
553 // System.out.println(rejections);
554 // }
555 // }
556 //
557 //// System.out.println("\n************************************");
558 //// System.out.println("Analyzing MCMC results");
559 ////
560 //// BufferedReader read = null;
561 //// try{
562 //// read = new BufferedReader( new FileReader("prior.args"));
563 //// String s = read.readLine();
564 //// s = read.readLine();
565 ////
566 //// while(s != null){
567 //// mcmcFreq[Collections.binarySearch(trees, s)]++;
568 //// s = read.readLine();
569 //// }
570 ////
571 //// }catch(Exception e){
572 //// System.exit(-1);
573 //// }
574 //
575 // System.out.println("\n************************************");
576 // System.out.println("Printing Results");
577 //
578 //
579 // try {
580 // out = new BufferedWriter(new FileWriter("coalescent.sim"));
581 //
582 // rejections = 0;
583 // for (String s : trees) {
584 // if (mcmcFreq[rejections] > -1) {
585 // out.write(s + " " + freq[rejections] + " " + mcmcFreq[rejections] + " \n");
586 // }
587 // rejections++;
588 // }
589 // out.flush();
590 // } catch (Exception IOException) {
591 // System.exit(-1);
592 // }
593
594 }
595
596 /**
597 * Packs and sends ARG state, including connectedness, heightparameters and
598 * partitioning parameters.
599 *
600 * @param toRank
601 */
602
603 @Override
604 public void sendState(int toRank) {
605 sendStateNoParameters(toRank);
606 int cnt = 0;
607 for (Node node : nodes) {
608 node.number = cnt;
609 cnt++;
610 }
611 final int size = nodes.size();
612 MPIServices.sendInt(size, toRank);
613 int[] intMsg = new int[size * 7];
614 double[] doubleMsg = new double[size];
615 int indexNode = 0;
616 int indexHeight = 0;
617 int indexPartition = 0;
618 ArrayList<Parameter> partList = new ArrayList<Parameter>();
619 for (Node node : nodes) {
620 intMsg[indexNode++] = node.number;
621
622 if (node.leftParent != null)
623 intMsg[indexNode++] = node.leftParent.number;
624 else
625 intMsg[indexNode++] = -1;
626 if (node.rightParent != null)
627 intMsg[indexNode++] = node.rightParent.number;
628 else
629 intMsg[indexNode++] = -1;
630 if (node.leftChild != null)
631 intMsg[indexNode++] = node.leftChild.number;
632 else
633 intMsg[indexNode++] = -1;
634 if (node.rightChild != null)
635 intMsg[indexNode++] = node.rightChild.number;
636 else
637 intMsg[indexNode++] = -1;
638
639 if (node.partitioning != null) {
640 intMsg[indexNode++] = indexPartition++;
641 partList.add(node.partitioning);
642 } else {
643 intMsg[indexNode++] = -1;
644 }
645
646 if (node.bifurcation)
647 intMsg[indexNode++] = 1;
648 else
649 intMsg[indexNode++] = 0;
650
651 doubleMsg[indexHeight++] = node.heightParameter
652 .getParameterValue(0);
653 }
654 MPIServices.sendIntArray(intMsg, toRank);
655 MPIServices.sendDoubleArray(doubleMsg, toRank);
656 MPIServices.sendInt(partList.size(), toRank);
657 for (Parameter partition : partList) {
658 // System.err.println("Sending a partition.");
659 double[] values = partition.getParameterValues();
660 // System.err.println("length = "+values.length);
661 MPIServices.sendDoubleArray(partition.getParameterValues(), toRank);
662 }
663 // partitioningParameters.sendState(toRank);
664 MPIServices.sendInt(((Node) getRoot()).number, toRank);
665 }
666
667 @Override
668 public void receiveState(int fromRank) {
669 receiveStateNoParameters(fromRank);
670 final int newNodeCount = MPIServices.receiveInt(fromRank);
671 // while (newNodeCount < nodes.size())
672 // nodes.remove(0);
673 int[] intMsg = MPIServices.receiveIntArray(fromRank, newNodeCount * 7);
674 double[] doubleMsg = MPIServices.receiveDoubleArray(fromRank,
675 newNodeCount);
676 int partitionLength = MPIServices.receiveInt(fromRank);
677 // System.err.println("Attemping to receive "+partitionLength+"
678 // partitions.");
679 final int length = getNumberOfPartitions();
680 // System.err.println("Expected length = "+length);
681 while (partitionLength > partitioningParameters.getParameterCount()) {
682 Parameter newPartition = new Parameter.Default(length);
683 partitioningParameters.addParameter(newPartition);
684 }
685
686 for (int i = 0; i < partitionLength; i++) {
687 double[] values = MPIServices.receiveDoubleArray(fromRank, length);
688 // System.err.println("Received.");
689 Parameter param = partitioningParameters.getParameter(i);
690 // System.err.println("null? "+ (param == null ? "Yes" : "No"));
691 for (int j = 0; j < length; j++) {
692 // System.err.println("setting value #"+j+ " = "+values[j]);
693
694 param.setParameterValueQuietly(j, values[j]);
695 }
696 // System.err.println("Values set");
697 }
698 // System.err.println("Done with partition receive.");
699
700 int root = MPIServices.receiveInt(fromRank);
701 // System.err.println("Start reconstructing ARG");
702
703 beginTreeEdit();
704 while (newNodeCount > nodes.size()) {
705 Node newNode = new Node();
706 newNode.heightParameter = new Parameter.Default(0.0);
707 nodes.add(newNode);
708 }
709 // System.err.println("extra height added");
710 int nodeInt;
711 int indexNode = 0;
712 int indexHeight = 0;
713 int indexPartition = 0;
714 for (int i = 0; i < newNodeCount; i++) {
715 Node node = nodes.get(i);
716 node.number = intMsg[indexNode++];
717
718 nodeInt = intMsg[indexNode++];
719 if (nodeInt != -1)
720 node.leftParent = nodes.get(nodeInt);
721 else
722 node.leftParent = null;
723 nodeInt = intMsg[indexNode++];
724 if (nodeInt != -1)
725 node.rightParent = nodes.get(nodeInt);
726 else
727 node.rightParent = null;
728 nodeInt = intMsg[indexNode++];
729 if (nodeInt != -1)
730 node.leftChild = nodes.get(nodeInt);
731 else
732 node.leftChild = null;
733 nodeInt = intMsg[indexNode++];
734 if (nodeInt != -1)
735 node.rightChild = nodes.get(nodeInt);
736 else
737 node.rightChild = null;
738 // Parameter heightParam =
739 node.heightParameter.setParameterValueQuietly(0,
740 doubleMsg[indexHeight++]);
741 int whichPartitionParameter = intMsg[indexNode++];
742 if (whichPartitionParameter != -1) {
743 // System.err.println("Setting partition para");
744
745 node.partitioning = partitioningParameters
746 .getParameter(whichPartitionParameter);
747 // System.err.println("Done setting param");
748 }
749
750 if (intMsg[indexNode++] == 1)
751 node.bifurcation = true;
752 else
753 node.bifurcation = false;
754
755 }
756 // System.err.println("Recovered all nodes");
757 setRoot(nodes.get(root));
758 // try {
759 endTreeEditFast();
760 // todo fire an ARG changed event???
761
762 // } catch (InvalidTreeException e) {
763 // throw new RuntimeException("Unable to unpack ARG correctly");
764 // e.printStackTrace(); //To change body of catch statement use File |
765 // Settings | File Templates.
766 // }
767
768 }
769
770 public boolean isAncestral() {
771
772 //zero everything first.
773 for (int i = 0; i < getNodeCount(); i++) {
774 Node x = (Node) getNode(i);
775
776 x.fullAncestralMaterial = false;
777 x.hasSomeAncestralMaterial = false;
778
779 if (x.ancestralMaterial == null) {
780 x.ancestralMaterial = new boolean[getNumberOfPartitions()];
781 }
782
783 for (int j = 0; j < x.ancestralMaterial.length; j++) {
784 x.ancestralMaterial[j] = false;
785 }
786
787 }
788
789 //post order up with the external nodes
790
791 for (int i = 0; i < getExternalNodeCount(); i++) {
792 Node currentNode = (Node) getExternalNode(i);
793
794 currentNode.fullAncestralMaterial = true;
795 currentNode.hasSomeAncestralMaterial = true;
796
797 for (int j = 0; j < currentNode.ancestralMaterial.length; j++) {
798 currentNode.ancestralMaterial[j] = true;
799 }
800
801 currentNode.leftParent.setAncestralMaterial(currentNode.ancestralMaterial);
802 }
803
804
805 //check that everything has some ancestral stuff.
806 for (int i = 0, n = getNodeCount(); i < n; i++) {
807 Node currentNode = (Node) getNode(i);
808
809 if (!currentNode.hasSomeAncestralMaterial) {
810 return false;
811 }
812 }
813
814
815 return true;
816 }
817
818
819 public CompoundParameter getPartitioningParameters() {
820 return partitioningParameters;
821 }
822
823 public void setupHeightBounds() {
824 for (Node node : nodes) {
825 node.setupHeightBounds();
826 }
827 }
828
829 // public static final String
830
831 private String getNameOfNode(Node node) {
832 if (node.taxon == null)
833 return "n" + Integer.toString(node.number);
834 else
835 return node.taxon.getId();
836 // return Integer.toString(node.number);
837 }
838
839 public static final int MAX_LABEL_COUNT = 10;
840
841 private Element makeEdge(Node from, Node to) {
842 Element edgeElement = new Element(EDGE_ELEMENT);
843 edgeElement.setAttribute(EDGE_FROM, getNameOfNode(from));
844 edgeElement.setAttribute(EDGE_TO, getNameOfNode(to));
845 edgeElement.setAttribute(EDGE_LENGTH, Double
846 .toString(getNodeHeight(from) - getNodeHeight(to)));
847 if (to.isReassortment()) {
848 double[] bits = to.partitioning.getParameterValues();
849 int length = bits.length;
850 StringBuilder sb = new StringBuilder();
851 boolean isLeft = (from == to.leftParent);
852 int countLabels = 0;
853 for (int i = 0; i < length; i++) {
854 if ((isLeft && bits[i] == 0) || (!isLeft && bits[i] == 1)) {
855 sb.append(i);
856 sb.append(" ");
857 countLabels++;
858 }
859
860 }
861 if (countLabels < MAX_LABEL_COUNT)
862 edgeElement.setAttribute(EDGE_PARTITIONS, sb.toString().trim());
863 }
864 return edgeElement;
865 }
866
867 private Element makeNode(Node node) {
868 Element nodeElement = new Element(NODE_ELEMENT);
869 nodeElement.setAttribute(ID_ATTRIBUTE, getNameOfNode(node));
870 if (node.taxon != null) {
871 nodeElement.setAttribute(IS_TIP, "true");
872 nodeElement.setAttribute(TAXON_NAME, node.taxon.getId());
873 // nodeElement.setAttribute("style","filled");
874 // nodeElement.setAttribute("fillcolor","blue");
875 }
876 if (node.isRoot()) {
877 nodeElement.setAttribute(IS_ROOT, "true");
878 }
879 if (node.isReassortment()) {
880 nodeElement.setAttribute(IS_REASSORTMENT, "true");
881 }
882 nodeElement
883 .setAttribute(NODE_HEIGHT, Double.toString(node.getHeight()));
884 return nodeElement;
885 }
886
887 private Element makeNodeFullInfo(Node node) {
888 Element nodeElement = new Element(NODE_ELEMENT);
889 nodeElement.setAttribute(ID_ATTRIBUTE, getNameOfNode(node));
890
891 if (node.isRoot()) {
892 nodeElement.setAttribute(IS_ROOT, "true");
893 } else {
894 nodeElement.setAttribute(LEFT_PARENT,
895 getNameOfNode(node.leftParent));
896 nodeElement.setAttribute(RIGHT_PARENT,
897 getNameOfNode(node.rightParent));
898 }
899
900 if (node.taxon != null) {
901 nodeElement.setAttribute(IS_TIP, "true");
902 nodeElement.setAttribute(TAXON_NAME, node.taxon.getId());
903 } else {
904 nodeElement.setAttribute(LEFT_CHILD, getNameOfNode(node.leftChild));
905 nodeElement.setAttribute(RIGHT_CHILD,
906 getNameOfNode(node.rightChild));
907 }
908 nodeElement
909 .setAttribute(NODE_HEIGHT, Double.toString(node.getHeight()));
910
911 return nodeElement;
912 }
913
914 public ARGModel fromXML(Element rootElement) {
915
916 int numPartitions = Integer.parseInt(rootElement
917 .getAttributeValue(NUM_PARTITIONS));
918 int external = 0;
919
920 // count # of nodeElements
921 List<Element> nodeList = rootElement.getChildren(NODE_ELEMENT);
922 ArrayList<Node> nodes = new ArrayList<Node>();
923 Node rootNode = null;
924 // System.err.println("node # = "+nodeList.size());
925 // System.exit(-1);
926 for (Element nodeElement : nodeList) {
927 Node node = new Node();
928 nodes.add(node);
929 String isRoot = nodeElement.getAttributeValue(IS_ROOT);
930 if (isRoot != null && isRoot.compareTo("true") == 0)
931 rootNode = node;
932 String isReassortment = nodeElement
933 .getAttributeValue(IS_REASSORTMENT);
934 if (isReassortment != null && isReassortment.compareTo("true") == 0)
935 node.bifurcation = false;
936 else
937 node.bifurcation = true;
938 double height = Double.parseDouble(nodeElement
939 .getAttributeValue(NODE_HEIGHT));
940
941 node.heightParameter = new Parameter.Default(height);
942 node.setHeight(height);
943
944 String isTip = nodeElement.getAttributeValue(IS_TIP);
945 if (isTip != null && isTip.compareTo("true") == 0) {
946 external++;
947 String taxonName = nodeElement.getAttributeValue(TAXON_NAME);
948 node.taxon = new Taxon(taxonName); // todo reuse taxonList
949 }
950 }
951
952 List<Element> edgeList = rootElement.getChildren(EDGE_ELEMENT);
953 for (Element edgeElement : edgeList) {
954 int target = Integer.parseInt(edgeElement
955 .getAttributeValue(EDGE_TO));
956 int source = Integer.parseInt(edgeElement
957 .getAttributeValue(EDGE_FROM));
958 Node targetNode = nodes.get(target);
959 Node sourceNode = nodes.get(source);
960
961 if (targetNode.isBifurcation()) {
962 targetNode.leftParent = targetNode.rightParent = sourceNode;
963 } else {
964 if (targetNode.leftParent == null)
965 targetNode.leftParent = sourceNode;
966 else {
967 targetNode.rightParent = sourceNode;
968 String partitionInfo = edgeElement
969 .getAttributeValue(EDGE_PARTITIONS);
970 Parameter partitioning = null;
971 // if (partitionInfo != null && sourceNode.leftChild !=
972 // null) {
973 partitioning = new Parameter.Default(numPartitions, 0.0);
974 StringTokenizer st = new StringTokenizer(partitionInfo);
975 while (st.hasMoreTokens()) {
976 int which = Integer.parseInt(st.nextToken());
977 partitioning.setParameterValueQuietly(which, 1.0);
978 }
979 // }
980 targetNode.partitioning = partitioning;
981
982 }
983 }
984
985 if (sourceNode.leftChild == null)
986 sourceNode.leftChild = targetNode;
987 // sourceNode.
988 // }
989 else {
990 sourceNode.rightChild = targetNode;
991 // sourceNode.partitioning = partitioning;
992 }
993 // todo parse partition info
994 }
995
996 return new ARGModel(nodes, rootNode, numPartitions, external);
997 }
998
999 public Element toXML() {
1000
1001 // toGraphStringCompressed(true);
1002
1003 int cnt = 0;
1004 for (Node node : nodes)
1005 node.number = cnt++;
1006
1007 Element graphElement = new Element(GRAPH_ELEMENT);
1008 graphElement.setAttribute("edgedefault", "directed");
1009 graphElement.setAttribute(NUM_PARTITIONS, Integer
1010 .toString(getNumberOfPartitions()));
1011
1012 for (Node node : nodes) {
1013
1014 graphElement.addContent(makeNode(node));
1015 // Add edge to left parent if not root
1016 if (node.leftParent != null) {
1017 graphElement.addContent(makeEdge(node.leftParent, node));
1018
1019 }
1020 // Add edge to right parent if reassortment
1021 if (node.rightParent != null && node.isReassortment()) {
1022 graphElement.addContent(makeEdge(node.rightParent, node));
1023 }
1024
1025 }
1026
1027 // System.err.println("start = "+nodes.size());
1028 // ARGModel test = fromXML(graphElement);
1029 // System.err.println(test.toGraphString());
1030
1031 // System.err.println("old 0:"+getNewick(0));
1032 // System.err.println("old 1:"+getNewick(1));
1033 // System.err.println("old 2:"+getNewick(2));
1034 // System.err.println("new 0:"+test.getNewick(0));
1035
1036 return graphElement;
1037 }
1038
1039 public String toStrippedNewick() {
1040 String s = root.toExtendedNewick() + ";";
1041 // s = s.replaceAll("[0-9a-zA-Z]", "");
1042 s = s.replaceAll("[^(),<>;]", "");
1043 return s;
1044
1045 }
1046
1047 public String toExtendedNewick() {
1048 // StringBuffer sb = new StringBuffer();
1049 return root.toExtendedNewick() + ";";
1050 }
1051
1052 /**
1053 * Push a tree changed event into the event stack.
1054 */
1055 public void pushTreeChangedEvent() {
1056 pushTreeChangedEvent(new ARGTreeChangedEvent());
1057 }
1058
1059 public void pushTreeSizeChangedEvent() {
1060 throw new RuntimeException("No longer supported; use updated operators");
1061 }
1062
1063 public void pushTreeSizeIncreasedEvent() {
1064 pushTreeChangedEvent(new ARGTreeChangedEvent(+1));
1065 }
1066
1067 public void pushTreeSizeDecreasedEvent() {
1068 pushTreeChangedEvent(new ARGTreeChangedEvent(-1));
1069 }
1070
1071 /**
1072 * Push a tree changed event into the event stack.
1073 */
1074 public void pushTreeChangedEvent(NodeRef nodeRef) {
1075 pushTreeChangedEvent(new ARGTreeChangedEvent((Node) nodeRef));
1076 }
1077
1078 /**
1079 * Push a tree changed event into the event stack.
1080 */
1081 public void pushTreeChangedEvent(Node node, Parameter parameter, int index) {
1082 pushTreeChangedEvent(new ARGTreeChangedEvent(node, parameter, index));
1083 }
1084
1085 /**
1086 * Push a tree changed event into the event stack.
1087 */
1088 public void pushTreeChangedEvent(TreeChangedEvent event) {
1089 if (inEdit) {
1090 treeChangedEvents.add(event);
1091 } else {
1092 listenerHelper.fireModelChanged(this, event);
1093 }
1094 }
1095
1096 protected void handleModelChangedEvent(Model model, Object object, int index) {
1097 // no submodels so nothing to do
1098 }
1099
1100 /**
1101 * Called when a parameter changes.
1102 */
1103 public void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
1104
1105 Node node = getNodeOfParameter((Parameter) variable);
1106 pushTreeChangedEvent(node, (Parameter) variable, index);
1107 }
1108
1109 private ArrayList<ARGLikelihood> likelihoodCalculators;
1110
1111 private int maxNumberOfPartitions;
1112
1113 public int getNumberOfPartitions() {
1114 return maxNumberOfPartitions;
1115 }
1116
1117 public int addLikelihoodCalculator(ARGLikelihood calc) {
1118 // int len = 0;
1119 if (likelihoodCalculators == null) {
1120 likelihoodCalculators = new ArrayList<ARGLikelihood>();
1121 }
1122 likelihoodCalculators.add(calc);
1123 int len = likelihoodCalculators.size() - 1;
1124 maxNumberOfPartitions = likelihoodCalculators.size();
1125 System.err.println("Add calculator for partition #" + len);
1126 setPartitionRecursively(getRoot(), len);
1127 return len;
1128 }
1129
1130 public int getMaxPartitionNumber() {
1131 return maxNumberOfPartitions;
1132 }
1133
1134 protected final List<TreeChangedEvent> treeChangedEvents = new ArrayList<TreeChangedEvent>();
1135
1136 public class ARGTreeChangedEvent implements TreeChangedEvent {
1137
1138 final Node node;
1139
1140 final Parameter parameter;
1141
1142 final int index;
1143
1144 int size = 0;
1145
1146 public ARGTreeChangedEvent() {
1147 this(null, null, -1);
1148 }
1149
1150 // public TreeChangedEvent(ARGModel arg) {
1151 // this(null, null, -1);
1152 // size = true;
1153 // }
1154
1155 public ARGTreeChangedEvent(Node node) {
1156 this(node, null, -1);
1157 }
1158
1159 public ARGTreeChangedEvent(Node node, Parameter parameter, int index) {
1160 this.node = node;
1161 this.parameter = parameter;
1162 this.index = index;
1163 }
1164
1165 public ARGTreeChangedEvent(int sizeChanged) {
1166 this(null, null, -1);
1167 size = sizeChanged;
1168 }
1169
1170 public int getIndex() {
1171 return index;
1172 }
1173
1174 public Node getNode() {
1175 return node;
1176 }
1177
1178 public Parameter getParameter() {
1179 return parameter;
1180 }
1181
1182 public int getSize() {
1183 return size;
1184 }
1185
1186 public boolean isSizeChanged() {
1187 return !(size == 0);
1188 }
1189
1190 public boolean isTreeChanged() {
1191 return parameter == null;
1192 }
1193
1194 public boolean isNodeChanged() {
1195 return node != null;
1196 }
1197
1198 public boolean isNodeParameterChanged() {
1199 return parameter != null;
1200 }
1201
1202 public boolean isHeightChanged() {
1203 return parameter == node.heightParameter;
1204 }
1205
1206 public boolean isRateChanged() {
1207 return parameter == node.rateParameter;
1208 }
1209
1210 public boolean isTraitChanged() {
1211 return parameter == node.traitParameter;
1212 }
1213 }
1214
1215 // *****
1216 // Interface Loggable
1217 // *****
1218
1219 public LogColumn[] getColumns() {
1220 int numColumns = 3;
1221 // numColumns += this.getMaxPartitionNumber();
1222 // LogColumn[] logColumns = new LogColumn[numColumns +
1223 // getMaxPartitionNumber()];
1224 LogColumn[] logColumns = new LogColumn[3];
1225 //logColumns[0] = new IsReassortmentColumn("isReassortment");
1226 logColumns[0] = new CountReassortmentColumn("numberReassortments");
1227 logColumns[1] = new ExtremeNodeHeightColumn("maxNodeHeight") {
1228 double getStartValue() {
1229 return 0;
1230 }
1231
1232 double compare(double currentValue, double newValue) {
1233 if (newValue > currentValue)
1234 return newValue;
1235 return currentValue;
1236 }
1237 };
1238 logColumns[2] = new ExtremeNodeHeightColumn("minNodeHeight") {
1239 double getStartValue() {
1240 return 0;
1241 }
1242
1243 double compare(double currentValue, double newValue) {
1244 if (newValue == 0) {
1245 return currentValue;
1246 } else if (currentValue == 0) {
1247 return newValue;
1248 }
1249 if (newValue < currentValue)
1250 return newValue;
1251 return currentValue;
1252 }
1253 };
1254 /*logColumns[4] = new NumberColumn("Left Node"){
1255 public double getDoubleValue() {
1256 Node a = (Node) getRoot();
1257 return a.leftChild.getHeight();
1258 }
1259 };
1260 logColumns[5] = new NumberColumn("Right Node"){
1261 public double getDoubleValue() {
1262 Node a = (Node) getRoot();
1263 return a.rightChild.getHeight();
1264 }
1265 };
1266 logColumns[6] = new NumberColumn("Reassort Height"){
1267 public double getDoubleValue() {
1268 double b = 0;
1269 for(Node a : nodes){
1270 if(a.isReassortment()){
1271 b = a.getHeight();
1272 break;
1273 }
1274 }
1275 return b;
1276 }
1277 };*/
1278
1279 // logColumns[2] = new IsRootTooHighColumn("isRootTooHigh");
1280 // for (int i = 0; i < getMaxPartitionNumber(); i++)
1281 // logColumns[4 + i] = new ArgTreeHeightColumn("argTreeHeight", this,
1282 // i);
1283 return logColumns;
1284 }
1285
1286 private abstract class ExtremeNodeHeightColumn extends NumberColumn {
1287
1288 public ExtremeNodeHeightColumn(String label) {
1289 super(label);
1290 }
1291
1292 abstract double compare(double currentValue, double newValue);
1293
1294 /*
1295 * { if (newValue > currentValue) return newValue; return currentValue; }
1296 */
1297
1298 abstract double getStartValue();
1299
1300 public double getDoubleValue() {
1301 double criticalValue = getStartValue();
1302 for (Node node : nodes) {
1303 double nodeHeight = node.heightParameter.getParameterValue(0);
1304 if (nodeHeight > 0 && !isRoot(node)) {
1305 criticalValue = compare(criticalValue, nodeHeight);
1306 }
1307 }
1308 return criticalValue;
1309 }
1310 }
1311
1312 private class ArgTreeHeightColumn extends NumberColumn {
1313
1314 private final int partition;
1315
1316 private final ARGModel argModel;
1317
1318 public ArgTreeHeightColumn(String label, ARGModel argModel,
1319 int partition) {
1320 super(label + partition);
1321 this.argModel = argModel;
1322 this.partition = partition;
1323 }
1324
1325 public double getDoubleValue() {
1326 ARGTree argTree = new ARGTree(argModel, partition);
1327 return argTree.getNodeHeight(argTree.getRoot());
1328 // return (new ARGTree(
1329 }
1330 }
1331
1332 private class IsReassortmentColumn extends NumberColumn {
1333
1334 public IsReassortmentColumn(String label) {
1335 super(label); // To change body of overridden methods use File |
1336 // Settings | File Templates.
1337 }
1338
1339 public double getDoubleValue() {
1340 return getReassortmentNodeCount() == 0 ? 0 : 1;
1341 }
1342 }
1343
1344 private class IsRootTooHighColumn extends NumberColumn {
1345
1346 public IsRootTooHighColumn(String label) {
1347 super(label); // To change body of overridden methods use File |
1348 // Settings | File Templates.
1349 }
1350
1351 public double getDoubleValue() {
1352 return isBifurcationDoublyLinked(getRoot()) ? 1 : 0;
1353 }
1354 }
1355
1356 private class CountReassortmentColumn extends NumberColumn {
1357
1358 public CountReassortmentColumn(String label) {
1359 super(label); // To change body of overridden methods use File |
1360 // Settings | File Templates.
1361 }
1362
1363 public double getDoubleValue() {
1364 return getReassortmentNodeCount();
1365 }
1366 }
1367
1368 public void setPartitionType(String partitionType) {
1369 this.partitionType = partitionType;
1370 }
1371
1372 public String getPartitionType() {
1373 return partitionType;
1374 }
1375
1376 public boolean isRecombinationPartitionType() {
1377 if (partitionType.equals(RECOMBINATION_PARTITION)) {
1378 return true;
1379 }
1380 return false;
1381 }
1382
1383 // *****************************************************************
1384 // Interface Tree
1385 // *****************************************************************
1386
1387 /**
1388 * Return the units that this tree is expressed in.
1389 */
1390 public final Type getUnits() {
1391 return units;
1392 }
1393
1394 public void setUnits(Type units) {
1395 this.units = units;
1396
1397 }
1398
1399 /**
1400 * Sets the units that this tree is expressed in.
1401 */
1402
1403 /**
1404 * @return a count of the number of nodes (internal + external) in this
1405 * tree.
1406 */
1407 public final int getNodeCount() {
1408 return nodes.size();
1409 }
1410
1411 public final boolean hasNodeHeights() {
1412 return true;
1413 }
1414
1415 public NodeRef getMirrorNode(NodeRef node) {
1416
1417 // for(Node argNode: nodes) {
1418 // if (((Node)node).mirrorNode == argNode)
1419 // System.err.println("Found (in getMirrorNode)");
1420 // }
1421
1422 return ((Node) node).mirrorNode;
1423 }
1424
1425 public final double getNodeHeight(NodeRef node) {
1426
1427 // System.err.println(Tree.Utils.uniqueNewick(this, node));
1428 // ((Node)node))
1429
1430 return ((Node) node).getHeight();
1431 }
1432
1433 public final double getMinParentNodeHeight(NodeRef nr) {
1434 Node node = (Node) nr;
1435 return Math.min(node.leftParent.getHeight(), node.rightParent
1436 .getHeight());
1437 }
1438
1439 public final double getNodeHeightUpper(NodeRef node) {
1440 return ((Node) node).heightParameter.getBounds().getUpperLimit(0);
1441 }
1442
1443 public final double getNodeHeightLower(NodeRef node) {
1444 return ((Node) node).heightParameter.getBounds().getLowerLimit(0);
1445 }
1446
1447 /**
1448 * @param nodeRef
1449 * @return the rate parameter associated with this node.
1450 */
1451 public final double getNodeRate(NodeRef nodeRef, int partition) {
1452 if (!hasRates) {
1453 return 1.0;
1454 }
1455
1456
1457 return 0.0;
1458 }
1459
1460 public Object getNodeAttribute(NodeRef node, String name) {
1461 throw new UnsupportedOperationException(
1462 "ARGModel does not use NodeAttributes");
1463 }
1464
1465 public Iterator getNodeAttributeNames(NodeRef node) {
1466 throw new UnsupportedOperationException(
1467 "ARGModel does not use NodeAttributes");
1468 }
1469
1470 public double getNodeTrait(NodeRef node) {
1471 if (!hasTraits)
1472 throw new IllegalArgumentException(
1473 "Trait parameters have not been created");
1474 return ((Node) node).getTrait();
1475 }
1476
1477 public final Taxon getNodeTaxon(NodeRef node) {
1478 return ((Node) node).taxon;
1479 }
1480
1481 public final boolean isExternal(NodeRef node) {
1482 return ((Node) node).isExternal();
1483 }
1484
1485 public final boolean isInternal(NodeRef node) {
1486 return !this.isExternal(node);
1487 }
1488
1489 public final boolean isRoot(NodeRef node) {
1490 return (node == root);
1491 }
1492
1493 public final boolean isBifurcation(NodeRef node) {
1494 return ((Node) node).isBifurcation();
1495 }
1496
1497 public final boolean isBifurcationDoublyLinked(NodeRef node) {
1498 return ((Node) node).isBifurcationDoublyLinked();
1499 }
1500
1501 public final boolean isReassortment(NodeRef node) {
1502 return ((Node) node).isReassortment();
1503 }
1504
1505 public final int countReassortmentNodes(NodeRef nr) {
1506 Node node = (Node) nr;
1507 int count = node.countReassortmentChild(this);
1508 // int count = 0;
1509 return (count / 2);
1510 }
1511
1512 public final int getChildCount(NodeRef node) {
1513 return ((Node) node).getChildCount();
1514 }
1515
1516
1517 public final NodeRef getOtherChild(NodeRef parent, NodeRef wrongChild) {
1518 Node p = (Node) parent;
1519 Node c = (Node) wrongChild;
1520
1521 if (p.leftChild == c) {
1522 return p.rightChild;
1523 }
1524 return p.leftChild;
1525 }
1526
1527 public final NodeRef getBrother(NodeRef node) {
1528 Node n = (Node) node;
1529
1530 if (n.isReassortment()) {
1531 return node;
1532 }
1533 Node p = n.leftParent;
1534
1535 if (p.leftChild == n) {
1536 return p.rightChild;
1537 }
1538
1539 return p.leftChild;
1540 }
1541
1542 /**
1543 * If i = 0, the left child is returned, else if i = 1, the right child is
1544 * returned.
1545 *
1546 * @return The child of the entered node.
1547 */
1548 public final NodeRef getChild(NodeRef node, int i) {
1549 return ((Node) node).getChild(i);
1550 }
1551
1552 public final NodeRef getChild(NodeRef node, int i, int partition) {
1553 return ((Node) node).getChild(i, partition);
1554 }
1555
1556 // public final NodeRef getParent(NodeRef node) { return
1557 // ((Node)node).parent; }
1558 public final NodeRef getParent(NodeRef node) {
1559 Node left = ((Node) node).leftParent;
1560 Node right = ((Node) node).rightParent;
1561 if (left == right)
1562 return left;
1563 else
1564 throw new IllegalArgumentException(
1565 "No single parent for reassorted node");
1566 }
1567
1568 /**
1569 * @param node The child noderef
1570 * @param i i = 0 (left parent) i = 1 (right parent)
1571 * @return The corresponding parent noderef
1572 */
1573 public final NodeRef getParent(NodeRef node, int i) {
1574 if (i == 0)
1575 return ((Node) node).leftParent;
1576 if (i == 1)
1577 return ((Node) node).rightParent;
1578 throw new IllegalArgumentException(
1579 "ARGModel.Node can only have two parents");
1580 }
1581
1582 public final boolean hasBranchLengths() {
1583 return true;
1584 }
1585
1586 public final double getBranchLength(NodeRef node) {
1587 NodeRef parent = getParent(node);
1588 if (parent == null) {
1589 return 0.0;
1590 }
1591
1592 return getNodeHeight(parent) - getNodeHeight(node);
1593 }
1594
1595 public final NodeRef getExternalNode(int i) {
1596 return nodes.get(i);
1597 }
1598
1599 public final NodeRef getInternalNode(int i) {
1600 return nodes.get(i + externalNodeCount);
1601 }
1602
1603 public final NodeRef getNode(int i) {
1604 return nodes.get(i);
1605 }
1606
1607 /**
1608 * Returns the number of external nodes.
1609 */
1610 public final int getExternalNodeCount() {
1611 return externalNodeCount;
1612 }
1613
1614 /**
1615 * Returns the ith internal node.
1616 */
1617 public final int getInternalNodeCount() {
1618 return internalNodeCount;
1619 }
1620
1621
1622 public final int getReassortmentNodeCount() {
1623 int cnt = 0;
1624 for (Node node : nodes) {
1625 if (!node.bifurcation)
1626 cnt++;
1627 }
1628 return cnt;
1629 }
1630
1631 // public final int getReassortmentNodeCount() { return nullCounter; }
1632
1633 public void addNullCounter() {
1634 nullCounter++;
1635 }
1636
1637 public void removeNullCounter() {
1638 nullCounter--;
1639 }
1640
1641 /**
1642 * Returns the root node of this tree.
1643 */
1644 public final NodeRef getRoot() {
1645 return root;
1646 }
1647
1648 public final NodeRef getRoot(int partition) {
1649 // TODO
1650 return null;
1651 }
1652
1653 // *****************************************************************
1654 // Interface MutableTree
1655 // *****************************************************************
1656
1657 /**
1658 * Set a new node as root node.
1659 */
1660 public final void setRoot(NodeRef newRoot) {
1661
1662 if (!inEdit)
1663 throw new RuntimeException(
1664 "Must be in edit transaction to call this method!");
1665
1666 root = (Node) newRoot;
1667
1668 // We shouldn't need this because the addChild will already have fired
1669 // appropriate events.
1670 // pushTreeChangedEvent();
1671 }
1672
1673 public void swapHeightParameters(NodeRef n1, NodeRef n2) {
1674 Node node1 = (Node) n1;
1675 Node node2 = (Node) n2;
1676 double height1 = node1.getHeight();
1677 double height2 = node2.getHeight();
1678 Parameter trans = node1.heightParameter;
1679 node1.heightParameter = node2.heightParameter;
1680 node2.heightParameter = trans;
1681 node1.setHeight(height1);
1682 node2.setHeight(height2);
1683
1684 }
1685
1686 /**
1687 * Links <code>parent</code> with <code>child</code>. If
1688 * <code>parent</code> is a bifurcation node,
1689 * the method calls <code>singleAddChild(parent,child)</code>,
1690 * otherwise, the method calls <code>doubleAddChild(parent,child)</code>.
1691 *
1692 * @throws RuntimeException if not in edit mode.
1693 * @see <code>singleAddChild(NodeRef parent, NodeRef child)</code>
1694 * @see <code>doubleAddChild(NodeRef parent, NodeRef child)</code>
1695 */
1696 public void addChild(NodeRef parent, NodeRef child) {
1697 checkEditMode();
1698
1699 Node p = (Node) parent;
1700 Node c = (Node) child;
1701
1702 if (p.bifurcation) {
1703 p.singleAddChild(c);
1704 } else {
1705 p.doubleAddChild(c);
1706 }
1707 }
1708
1709 public void addChildWithSingleParent(NodeRef parent, NodeRef child) {
1710 checkEditMode();
1711
1712 Node p = (Node) parent;
1713 Node c = (Node) child;
1714
1715 if (p.bifurcation) {
1716 p.singleAddChildWithOneParent(c);
1717 } else {
1718 p.doubleAddChildWithOneParent(c);
1719 }
1720
1721 }
1722
1723
1724 /**
1725 * Makes a link between <code>parent</code> and <code>child</code>.
1726 * By default, if <code>parent</code> has a null reference for both
1727 * it's children, <code>child</code> will become the left child of
1728 * <code>parent</code>, otherwise <code>child</code> will become
1729 * the right child of <code>parent</code>. <br><br>If the right parent
1730 * of <code>child</code> is <code>null</code>, <code>parent</code>
1731 * will become the parent, the same thing will happen for the left parent
1732 * of <code>child</code>.
1733 *
1734 * @param parent the <code>NodeRef</code> that will become the parent of <code>child</code>
1735 * @param child the <code>NodeRef</code> that will become the child of <code>parent</code>
1736 * @throws RuntimeException if the you are not in edit transaction mode
1737 * @throws IllegalArgumentException if <code>parent</code> already has two children.
1738 */
1739 public void singleAddChild(NodeRef parent, NodeRef child) {
1740
1741 if (!inEdit) {
1742 throw new RuntimeException(
1743 "must be in edit transaction to call this method!");
1744 }
1745
1746 Node p = (Node) parent;
1747 Node c = (Node) child;
1748 p.singleAddChild(c);
1749 }
1750
1751 public void singleAddChildWithOneParent(NodeRef p, NodeRef c) {
1752
1753 if (!inEdit)
1754 throw new RuntimeException(
1755 "Must be in edit transaction to call this method!");
1756
1757 Node parent = (Node) p;
1758 Node child = (Node) c;
1759 parent.singleAddChildWithOneParent(child);
1760 }
1761
1762 public void doubleAddChild(NodeRef p, NodeRef c) {
1763
1764 if (!inEdit)
1765 throw new RuntimeException(
1766 "Must be in edit transaction to call this method!");
1767
1768 Node parent = (Node) p;
1769 Node child = (Node) c;
1770 parent.doubleAddChild(child);
1771 }
1772
1773 public void doubleAddChildWithOneParent(NodeRef p, NodeRef c) {
1774
1775 if (!inEdit)
1776 throw new RuntimeException(
1777 "Must be in edit transaction to call this method!");
1778
1779 Node parent = (Node) p;
1780 Node child = (Node) c;
1781 parent.doubleAddChildWithOneParent(child);
1782 }
1783
1784 public void addChildAsRecombinant(NodeRef p1, NodeRef p2, NodeRef c,
1785 Parameter partitioning) {
1786 // public void addChildAsRecombinant(NodeRef p1, NodeRef p2, NodeRef c,
1787 // BitSet bs1, BitSet bs2) {
1788 if (!inEdit)
1789 throw new RuntimeException(
1790 "Must be in edit transaction to call this method!");
1791 Node parent1 = (Node) p1;
1792 Node parent2 = (Node) p2;
1793 Node child = (Node) c;
1794 // if (parent1.hasChild(child) || parent2.hasChild(child)) throw new
1795 // IllegalArgumentException("Child already exists in parent");
1796 // if (parent2.hasChild(child)) throw new
1797 // IllegalArgumentException("Child already exists in")
1798 parent1.addChildRecombinant(child, partitioning);
1799 parent2.addChildRecombinant(child, partitioning);
1800 // if( parent2.getChildCount() == 1 )
1801 // parent2.addChildNoParentConnection(node);
1802 }
1803
1804 /**
1805 * Removes the link between <code>parent</code> and
1806 * <code>child</code>. If <code>parent</code> is a bifurcation node,
1807 * the method calls <code>singleRemoveChild(parent, child)</code>,
1808 * otherwise, the method calls <code>doubleRemoveChild(parent,child)</code>.
1809 *
1810 * @throws RuntimeException if not in edit mode.
1811 * @see <code>singleRemoveChild(NodeRef parent, NodeRef child)</code>
1812 * @see <code>doubleRemoveChild(NodeRef parent, NodeRef child)</code>
1813 */
1814 public void removeChild(NodeRef parent, NodeRef child) {
1815 checkEditMode();
1816
1817 Node p = (Node) parent;
1818 Node c = (Node) child;
1819
1820 p.doubleRemoveChild(c);
1821 }
1822
1823 public void replaceChild(NodeRef node, NodeRef child, NodeRef newChild) {
1824
1825 }
1826
1827 /**
1828 * Removes the link between the parent and the child. This method should be
1829 * called when the child's parents are both the same. After the method is
1830 * called the parent will have two null references for children, and the
1831 * child will have two null references for parents.
1832 *
1833 * @param parent The parent NodeRef
1834 * @param child The child NodeRef
1835 * // * @see doubleAddChild()
1836 * // * @see singleAddChild()
1837 * // * @see removeChild()
1838 * // * @see singleRemoveChild()
1839 */
1840 public void doubleRemoveChild(NodeRef parent, NodeRef child) {
1841 checkEditMode();
1842
1843 Node p = (Node) parent;
1844 Node c = (Node) child;
1845
1846 p.doubleRemoveChild(c);
1847 }
1848
1849 public void singleRemoveChild(NodeRef p, NodeRef c) {
1850 checkEditMode();
1851
1852 Node parent = (Node) p;
1853 Node child = (Node) c;
1854
1855 parent.singleRemoveChild(child);
1856 }
1857
1858 protected Node oldRoot;
1859
1860
1861 public boolean beginTreeEdit() {
1862 if (inEdit)
1863 throw new RuntimeException("Alreading in edit transaction mode!");
1864
1865 oldRoot = root;
1866
1867 inEdit = true;
1868
1869 return false;
1870 }
1871
1872 public void endTreeEdit() {
1873 if (!inEdit)
1874 throw new RuntimeException("Not in edit transaction mode!");
1875
1876 inEdit = false;
1877
1878 if (root != oldRoot) {
1879 swapParameterObjects(oldRoot, root);
1880 }
1881
1882 // ystem.err.println("There are "+treeChangedEvents.size()+" events
1883 // waiting");
1884 // System.exit(-1);
1885 for(TreeChangedEvent treeChangedEvent : treeChangedEvents) {
1886 listenerHelper.fireModelChanged(this, treeChangedEvent);
1887 }
1888 treeChangedEvents.clear();
1889 }
1890
1891 public void checkTreeIsValid() throws MutableTree.InvalidTreeException {
1892 for (Node node : nodes) {
1893 if (!node.heightParameter.isWithinBounds()) {
1894 throw new InvalidTreeException("height parameter out of bounds");
1895 }
1896 }
1897 }
1898
1899 private void endTreeEditFast() {
1900 inEdit = false;
1901 }
1902
1903 public void setNodeHeight(NodeRef n, double height) {
1904 ((Node) n).setHeight(height);
1905 }
1906
1907 public void setNodeRate(NodeRef n, double rate) {
1908 if (!hasRates)
1909 throw new IllegalArgumentException(
1910 "Rate parameters have not been created");
1911 ((Node) n).setRate(rate);
1912
1913 }
1914
1915 public void setNodeTrait(NodeRef n, double value) {
1916 if (!hasTraits)
1917 throw new IllegalArgumentException(
1918 "Trait parameters have not been created");
1919 ((Node) n).setTrait(value);
1920 }
1921
1922 public void setNodeNumber(NodeRef node, int n) {
1923 node.setNumber(n);
1924 }
1925
1926 public void setBranchLength(NodeRef node, double length) {
1927 throw new UnsupportedOperationException(
1928 "ARGModel cannot have branch lengths set");
1929 }
1930
1931 public void setNodeAttribute(NodeRef node, String name, Object value) {
1932 throw new UnsupportedOperationException(
1933 "ARGModel does not use NodeAttributes");
1934 }
1935
1936 // *****************************************************************
1937 // Interface ModelComponent
1938 // *****************************************************************
1939
1940 /**
1941 * Store current state
1942 */
1943 protected void storeState() {
1944 /*
1945 * System.err.println("Storing state"); this.checkBranchSanity();
1946 * System.err.println("sane before operation");
1947 */
1948 copyNodeStructure(storedNodes);
1949 // storedRootNumber = storedNodes.indexOf(root.getNumber();
1950 storedRootNumber = nodes.indexOf(root);
1951 storedNodeCount = nodeCount;
1952 storedInternalNodeCount = internalNodeCount;
1953 addedParameters = null;
1954 addedPartitioningParameter = null;
1955 addedNodes = null;
1956 removedParameters = null;
1957 removedPartitioningParameter = null;
1958 removedNodes = null;
1959 storedNullCounter = nullCounter;
1960 // System.err.println("Stored: "+Tree.Utils.uniqueNewick(this,
1961 // getRoot()));
1962 // System.err.println("Stored : "+this.toString());
1963 }
1964
1965 /**
1966 * Restore the stored state
1967 */
1968 protected void restoreState() {
1969
1970 ArrayList<Node> tmp = storedNodes;
1971 storedNodes = nodes;
1972 nodes = tmp;
1973 root = nodes.get(storedRootNumber);
1974
1975 nodeCount = storedNodeCount;
1976 internalNodeCount = storedInternalNodeCount;
1977
1978 //This part occurs true when we add a new arg event
1979 //onto the root.
1980
1981 if (addedParameters != null) {
1982 if (addedParameters.length == 5) {
1983 removeVariable(addedParameters[0]);
1984 removeVariable(addedParameters[1]);
1985 removeVariable(addedParameters[2]);
1986 removeVariable(addedParameters[3]);
1987
1988 storedInternalNodeHeights.removeParameter(addedParameters[0]);
1989 storedInternalNodeHeights.removeParameter(addedParameters[4]);
1990
1991 storedInternalAndRootNodeHeights.removeParameter(addedParameters[0]);
1992 storedInternalAndRootNodeHeights.removeParameter(addedParameters[1]);
1993
1994 storedNodeRates.removeParameter(addedParameters[2]);
1995 } else {
1996 storedInternalNodeHeights.removeParameter(addedParameters[0]);
1997 storedInternalNodeHeights.removeParameter(addedParameters[1]);
1998
1999 removeVariable(addedParameters[0]);
2000 removeVariable(addedParameters[1]);
2001
2002 storedInternalAndRootNodeHeights
2003 .removeParameter(addedParameters[0]);
2004 storedInternalAndRootNodeHeights
2005 .removeParameter(addedParameters[1]);
2006
2007 removeVariable(addedParameters[2]);
2008 removeVariable(addedParameters[3]);
2009 storedNodeRates.removeParameter(addedParameters[2]);
2010 // storedNodeRates.removeVariable(addedParameters[3]);
2011 }
2012 }
2013 if (addedPartitioningParameter != null) {
2014 partitioningParameters.removeParameter(addedPartitioningParameter);
2015 removeVariable(addedPartitioningParameter);
2016 }
2017 if (removedParameters != null) {
2018 storedInternalNodeHeights.addParameter(removedParameters[0]);
2019 storedInternalNodeHeights.addParameter(removedParameters[1]);
2020 addVariable(removedParameters[0]);
2021 addVariable(removedParameters[1]);
2022
2023 storedInternalAndRootNodeHeights.addParameter(removedParameters[0]);
2024 storedInternalAndRootNodeHeights.addParameter(removedParameters[1]);
2025
2026 addVariable(removedParameters[2]);
2027 addVariable(removedParameters[3]);
2028 storedNodeRates.addParameter(removedParameters[2]);
2029 // storedNodeRates.addVariable(removedParameters[3]);
2030
2031 }
2032
2033 if (removedPartitioningParameter != null) {
2034 partitioningParameters.addParameter(removedPartitioningParameter);
2035 addVariable(removedPartitioningParameter);
2036 }
2037
2038
2039 nullCounter = storedNullCounter;
2040 }
2041
2042 /**
2043 * accept the stored state
2044 */
2045 protected void acceptState() {
2046 // System.err.println("Accepted ARG\n"+this.toGraphString());
2047 } // nothing to do
2048
2049 /**
2050 * Adopt the state of the model component from source.
2051 */
2052 protected void adoptState(Model source) {
2053 }
2054
2055 /*
2056 * public void addNewHeightParameters(Parameter newbie1, Parameter newbie2,
2057 * CompoundParameter internalNodeParameters,
2058 * CompoundParameter internalAndRootNodeParameters) {
2059 * addVariable(newbie1); addVariable(newbie2); addedParameters = new
2060 * Parameter[2]; addedParameters[0] = newbie1; addedParameters[1] = newbie2;
2061 *
2062 * storedInternalNodeHeights = internalNodeParameters;
2063 * storedInternalNodeHeights.addVariable(newbie1);
2064 * storedInternalNodeHeights.addVariable(newbie2);
2065 *
2066 *//*
2067 * storedInternalAndRootNodeHeights = internalAndRootNodeParameters;
2068 * storedInternalAndRootNodeHeights.addVariable(newbie1);
2069 * storedInternalAndRootNodeHeights.addVariable(newbie2);
2070 *//*
2071 * }
2072 */
2073
2074 public void expandARG(Node newbie1, Node newbie2,
2075 CompoundParameter internalNodeParameters,
2076 CompoundParameter internalAndRootNodeParameters,
2077 CompoundParameter nodeRates) {
2078
2079 addVariable(newbie1.heightParameter);
2080 addVariable(newbie2.heightParameter);
2081 addVariable(newbie2.partitioning);
2082
2083 addVariable(newbie1.rateParameter);
2084 addVariable(newbie2.rateParameter);
2085
2086 addedParameters = new Parameter[4];
2087 addedParameters[0] = newbie1.heightParameter;
2088 addedParameters[1] = newbie2.heightParameter;
2089 addedParameters[2] = newbie1.rateParameter;
2090 addedParameters[3] = newbie2.rateParameter;
2091 addedPartitioningParameter = newbie2.partitioning;
2092
2093 storedInternalNodeHeights = internalNodeParameters;
2094 storedInternalNodeHeights.addParameter(newbie1.heightParameter);
2095 storedInternalNodeHeights.addParameter(newbie2.heightParameter);
2096
2097 storedInternalAndRootNodeHeights = internalAndRootNodeParameters;
2098 storedInternalAndRootNodeHeights.addParameter(newbie1.heightParameter);
2099 storedInternalAndRootNodeHeights.addParameter(newbie2.heightParameter);
2100
2101 storedNodeRates = nodeRates;
2102 storedNodeRates.addParameter(newbie1.rateParameter);
2103 // storedNodeRates.addVariable(newbie2.rateParameter);
2104
2105
2106 partitioningParameters.addParameter(newbie2.partitioning);
2107 nodes.add(newbie1);
2108 nodes.add(newbie2);
2109 internalNodeCount += 2;
2110
2111 // pushTreeSizeIncreasedEvent();
2112
2113 }
2114
2115 public void expandARGWithRecombinant(Node newbie1, Node newbie2,
2116 CompoundParameter internalNodeParameters,
2117 CompoundParameter internalAndRootNodeParameters,
2118 CompoundParameter nodeRates) {
2119 // System.err.println("attempting to expand");
2120
2121 addVariable(newbie1.heightParameter);
2122 addVariable(newbie2.heightParameter);
2123 addVariable(newbie2.partitioning);
2124
2125 // System.err.println("expand 0");
2126
2127 addVariable(newbie1.rateParameter);
2128 addVariable(newbie2.rateParameter);
2129
2130 // System.err.println("expand 1");
2131
2132 addedParameters = new Parameter[4];
2133 addedParameters[0] = newbie1.heightParameter;
2134 addedParameters[1] = newbie2.heightParameter;
2135 addedParameters[2] = newbie1.rateParameter;
2136 addedParameters[3] = newbie2.rateParameter;
2137 addedPartitioningParameter = newbie2.partitioning;
2138
2139 // System.err.println("expand 2");
2140
2141 storedInternalNodeHeights = internalNodeParameters;
2142 storedInternalNodeHeights.addParameter(newbie1.heightParameter);
2143 storedInternalNodeHeights.addParameter(newbie2.heightParameter);
2144
2145 storedInternalAndRootNodeHeights = internalAndRootNodeParameters;
2146 storedInternalAndRootNodeHeights.addParameter(newbie1.heightParameter);
2147 storedInternalAndRootNodeHeights.addParameter(newbie2.heightParameter);
2148
2149 storedNodeRates = nodeRates;
2150 storedNodeRates.addParameter(newbie1.rateParameter);
2151 storedNodeRates.addParameter(newbie2.rateParameter);
2152
2153 // System.err.println("expand 3");
2154
2155 partitioningParameters.addParameter(newbie2.partitioning);
2156 nodes.add(newbie1);
2157 nodes.add(newbie2);
2158 internalNodeCount += 2;
2159 // sanityNodeCheck(internalNodeParameters);
2160 // pushTreeSizeIncreasedEvent();
2161
2162 // System.err.println("done expand");
2163
2164 }
2165
2166 public void sanityNodeCheck(CompoundParameter inodes) {
2167 int len = inodes.getParameterCount();
2168 for (int i = 0; i < len; i++) {
2169 Parameter p = inodes.getParameter(i);
2170 for (int j = 0; j < internalNodeCount; j++) {
2171 Node node = (Node) getInternalNode(j);
2172 if (node.heightParameter == p) {
2173 if (isRoot(node)) {
2174 System.err
2175 .println("Root height found in internal nodes");
2176 System.exit(-1);
2177 }
2178 }
2179
2180 }
2181 }
2182 }
2183
2184 public void contractARGWithRecombinantNewRoot(Node oldie,
2185 Node oldRoot, Node newRoot,
2186 CompoundParameter internalNodeParameters,
2187 CompoundParameter internalAndRootNodeParameters,
2188 CompoundParameter nodeRates) {
2189 removeVariable(oldie.heightParameter);
2190 removeVariable(oldRoot.heightParameter);
2191 removeVariable(oldie.partitioning);
2192
2193 removeVariable(oldie.rateParameter);
2194 removeVariable(oldie.rateParameter);
2195
2196 removedParameters = new Parameter[4];
2197 removedParameters[0] = oldie.heightParameter;
2198 removedParameters[1] = oldRoot.heightParameter;
2199 removedParameters[2] = oldie.rateParameter;
2200 removedParameters[3] = oldRoot.rateParameter;
2201
2202 partitioningParameters.removeParameter(oldie.partitioning);
2203 removedPartitioningParameter = oldie.partitioning;
2204 storedInternalNodeHeights = internalNodeParameters;
2205
2206 storedInternalNodeHeights.removeParameter(oldie.heightParameter);
2207
2208 storedInternalAndRootNodeHeights = internalAndRootNodeParameters;
2209 storedInternalAndRootNodeHeights
2210 .removeParameter(oldie.heightParameter);
2211 storedInternalAndRootNodeHeights
2212 .removeParameter(oldRoot.heightParameter);
2213
2214 storedNodeRates = nodeRates;
2215 storedNodeRates.removeParameter(oldie.rateParameter);
2216 storedNodeRates.removeParameter(oldRoot.rateParameter);
2217
2218 nodes.remove(oldie);
2219 nodes.remove(oldRoot);
2220 internalNodeCount -= 2;
2221
2222 this.setRoot(newRoot);
2223 // pushTreeSizeDecreasedEvent();
2224
2225
2226 }
2227
2228
2229 public void contractARG(Node oldie1, Node oldie2,
2230 CompoundParameter internalNodeParameters,
2231 CompoundParameter internalAndRootNodeParameters,
2232 CompoundParameter nodeRates) {
2233
2234 removeVariable(oldie1.heightParameter);
2235 removeVariable(oldie2.heightParameter);
2236 removeVariable(oldie2.partitioning);
2237
2238
2239 removeVariable(oldie1.rateParameter);
2240 removeVariable(oldie2.rateParameter);
2241
2242
2243 removedParameters = new Parameter[4];
2244 removedParameters[0] = oldie1.heightParameter;
2245 removedParameters[1] = oldie2.heightParameter;
2246 removedParameters[2] = oldie1.rateParameter;
2247 removedParameters[3] = oldie2.rateParameter;
2248
2249
2250 partitioningParameters.removeParameter(oldie2.partitioning);
2251 removedPartitioningParameter = oldie2.partitioning;
2252 storedInternalNodeHeights = internalNodeParameters;
2253 storedInternalNodeHeights.removeParameter(oldie1.heightParameter);
2254 storedInternalNodeHeights.removeParameter(oldie2.heightParameter);
2255
2256
2257 storedInternalAndRootNodeHeights = internalAndRootNodeParameters;
2258 storedInternalAndRootNodeHeights.removeParameter(oldie1.heightParameter);
2259 storedInternalAndRootNodeHeights.removeParameter(oldie2.heightParameter);
2260
2261
2262 storedNodeRates = nodeRates;
2263 storedNodeRates.removeParameter(oldie1.rateParameter);
2264 // storedNodeRates.removeVariable(oldie2.rateParameter);
2265
2266 nodes.remove(oldie1);
2267 nodes.remove(oldie2);
2268
2269 internalNodeCount -= 2;
2270 // pushTreeSizeDecreasedEvent();
2271 }
2272
2273
2274 /**
2275 * Cleans up the arg model after a deletion event.
2276 *
2277 * @param oldie1
2278 * @param oldie2
2279 * @param internalNodeParameters
2280 * @param internalAndRootNodeParameters
2281 * @param nodeRates
2282 */
2283 public void contractARGWithRecombinant(Node oldie1, Node oldie2,
2284 CompoundParameter internalNodeParameters,
2285 CompoundParameter internalAndRootNodeParameters,
2286 CompoundParameter nodeRates) {
2287
2288 removeVariable(oldie1.heightParameter);
2289 removeVariable(oldie2.heightParameter);
2290 removeVariable(oldie2.partitioning);
2291
2292
2293 removeVariable(oldie1.rateParameter);
2294 removeVariable(oldie2.rateParameter);
2295
2296
2297 removedParameters = new Parameter[4];
2298 removedParameters[0] = oldie1.heightParameter;
2299 removedParameters[1] = oldie2.heightParameter;
2300 removedParameters[2] = oldie1.rateParameter;
2301 removedParameters[3] = oldie2.rateParameter;
2302
2303
2304 partitioningParameters.removeParameter(oldie2.partitioning);
2305 removedPartitioningParameter = oldie2.partitioning;
2306 storedInternalNodeHeights = internalNodeParameters;
2307 storedInternalNodeHeights.removeParameter(oldie1.heightParameter);
2308 storedInternalNodeHeights.removeParameter(oldie2.heightParameter);
2309
2310
2311 storedInternalAndRootNodeHeights = internalAndRootNodeParameters;
2312 storedInternalAndRootNodeHeights
2313 .removeParameter(oldie1.heightParameter);
2314 storedInternalAndRootNodeHeights
2315 .removeParameter(oldie2.heightParameter);
2316
2317
2318 storedNodeRates = nodeRates;
2319 storedNodeRates.removeParameter(oldie1.rateParameter);
2320 storedNodeRates.removeParameter(oldie2.rateParameter);
2321
2322 nodes.remove(oldie1);
2323 nodes.remove(oldie2);
2324
2325 internalNodeCount -= 2;
2326 // pushTreeSizeDecreasedEvent();
2327 }
2328
2329 public boolean argStoreCheck() {
2330 if (storedInternalNodeHeights.getDimension() == this.internalNodeCount)
2331 return true;
2332 return false;
2333 }
2334
2335 /**
2336 * Copies the node connections from this ARGModel's nodes array to the
2337 * destination array. Basically it connects up the nodes in destination in
2338 * the same way as this ARGModel is set up. This method is package private.
2339 */
2340 void copyNodeStructure(ArrayList<Node> destination) {
2341
2342 // if ( nodes.length != destination.length ) {
2343 // throw new IllegalArgumentException("Node arrays are of different
2344 // lengths");
2345 // }
2346 while (destination.size() < nodes.size())
2347 destination.add(new Node());
2348 while (destination.size() > nodes.size())
2349 destination.remove(0);
2350 int n = nodes.size();
2351 // System.err.println("node.size = "+n);
2352 for (int i = 0; i < n; i++) {
2353 // for( Node node0 : nodes ) {
2354 Node node0 = nodes.get(i);
2355 Node node1 = destination.get(i);
2356
2357 // the parameter values are automatically stored and restored
2358 // just need to keep the links
2359 node1.heightParameter = node0.heightParameter;
2360 node1.rateParameter = node0.rateParameter;
2361 node1.traitParameter = node0.traitParameter;
2362 node1.partitioning = node0.partitioning;
2363
2364 node1.taxon = node0.taxon;
2365 node1.bifurcation = node0.bifurcation;
2366 node1.number = node0.number;
2367 node1.myHashCode = node0.myHashCode;
2368 // node1.partitionSet = (BitSet)node0.partitionSet.clone();
2369 // if (node0.leftPartition != null) {
2370 // node1.leftPartition = (BitSet) node0.leftPartition.clone();
2371 // } else {
2372 // node1.leftPartition = null;
2373 // }
2374 // if (node0.rightPartition != null) {
2375 // node1.rightPartition = (BitSet) node0.rightPartition.clone();
2376 // } else {
2377 // node1.rightPartition = null;
2378 // }
2379 //
2380
2381 if (node0.leftParent != null) {
2382 node1.leftParent = // storedNodes.get(node0.leftParent.getNumber());
2383 storedNodes.get(nodes.indexOf(node0.leftParent));
2384 } else {
2385 node1.leftParent = null;
2386 }
2387
2388 if (node0.rightParent != null) {
2389 node1.rightParent = // storedNodes.get(node0.rightParent.getNumber());
2390 storedNodes.get(nodes.indexOf(node0.rightParent));
2391 } else {
2392 node1.rightParent = null;
2393 }
2394
2395 if (node0.leftChild != null) {
2396 node1.leftChild = // storedNodes.get(node0.leftChild.getNumber());
2397 storedNodes.get(nodes.indexOf(node0.leftChild));
2398 } else {
2399 node1.leftChild = null;
2400 }
2401
2402 if (node0.rightChild != null) {
2403 node1.rightChild = // storedNodes.get(node0.rightChild.getNumber());
2404 storedNodes.get(nodes.indexOf(node0.rightChild));
2405 } else {
2406 node1.rightChild = null;
2407 }
2408 }
2409 }
2410
2411 public void setPartitionRecursively(NodeRef nr, int partition) {
2412 Node node = (Node) nr;
2413 node.setPartitionRecursively(partition);
2414 }
2415
2416 /**
2417 * @return the number of statistics of this component.
2418 */
2419 public int getStatisticCount() {
2420 return 1;
2421 }
2422
2423 /**
2424 * @return the ith statistic of the component
2425 */
2426 public Statistic getStatistic(int i) {
2427 if (i == 0)
2428 return root.heightParameter;
2429 throw new IllegalArgumentException();
2430 }
2431
2432 public String getModelComponentName() {
2433 return TREE_MODEL;
2434 }
2435
2436 // **************************************************************
2437 // TaxonList IMPLEMENTATION
2438 // **************************************************************
2439
2440 /**
2441 * @return a count of the number of taxa in the list.
2442 */
2443 public int getTaxonCount() {
2444 return getExternalNodeCount();
2445 }
2446
2447 /**
2448 * @return the ith taxon in the list.
2449 */
2450 public Taxon getTaxon(int taxonIndex) {
2451 return ((Node) getExternalNode(taxonIndex)).taxon;
2452 }
2453
2454 /**
2455 * @return the ID of the taxon of the ith external node. If it doesn't have
2456 * a taxon, returns the ID of the node itself.
2457 */
2458 public String getTaxonId(int taxonIndex) {
2459 Taxon taxon = getTaxon(taxonIndex);
2460 if (taxon != null) {
2461 return taxon.getId();
2462 } else {
2463 return null;
2464 }
2465 }
2466
2467 /**
2468 * returns the index of the taxon with the given id.
2469 */
2470 public int getTaxonIndex(String id) {
2471 for (int i = 0, n = getTaxonCount(); i < n; i++) {
2472 if (getTaxonId(i).equals(id))
2473 return i;
2474 }
2475 return -1;
2476 }
2477
2478 /**
2479 * returns the index of the given taxon.
2480 */
2481 public int getTaxonIndex(Taxon taxon) {
2482 for (int i = 0, n = getTaxonCount(); i < n; i++) {
2483 if (getTaxon(i) == taxon)
2484 return i;
2485 }
2486 return -1;
2487 }
2488
2489 public List<Taxon> asList() {
2490 List<Taxon> taxa = new ArrayList<Taxon>();
2491 for (int i = 0, n = getTaxonCount(); i < n; i++) {
2492 taxa.add(getTaxon(i));
2493 }
2494 return taxa;
2495 }
2496
2497 public Iterator<Taxon> iterator() {
2498 return new Iterator<Taxon>() {
2499 private int index = -1;
2500
2501 public boolean hasNext() {
2502 return index < getTaxonCount() - 1;
2503 }
2504
2505 public Taxon next() {
2506 index++;
2507 return getTaxon(index);
2508 }
2509
2510 public void remove() { /* do nothing */ }
2511 };
2512 }
2513
2514 /**
2515 * @param taxonIndex the index of the taxon whose attribute is being fetched.
2516 * @param name the name of the attribute of interest.
2517 * @return an object representing the named attributed for the taxon of the
2518 * given external node. If the node doesn't have a taxon then the
2519 * nodes own attribute is returned.
2520 */
2521 public final Object getTaxonAttribute(int taxonIndex, String name) {
2522 Taxon taxon = getTaxon(taxonIndex);
2523 if (taxon != null) {
2524 return taxon.getAttribute(name);
2525 }
2526 return null;
2527 }
2528
2529 // **************************************************************
2530 // MutableTaxonList IMPLEMENTATION
2531 // **************************************************************
2532
2533 public int addTaxon(Taxon taxon) {
2534 throw new IllegalArgumentException("Cannot add taxon to a ARGModel");
2535 }
2536
2537 public boolean removeTaxon(Taxon taxon) {
2538 throw new IllegalArgumentException("Cannot add taxon to a ARGModel");
2539 }
2540
2541 public void setTaxonId(int taxonIndex, String id) {
2542 throw new IllegalArgumentException("Cannot set taxon id in a ARGModel");
2543 }
2544
2545 public void setTaxonAttribute(int taxonIndex, String name, Object value) {
2546 throw new IllegalArgumentException(
2547 "Cannot set taxon attribute in a ARGModel");
2548 }
2549
2550 public void addMutableTreeListener(MutableTreeListener listener) {
2551 } // Do nothing at the moment
2552
2553 public void addMutableTaxonListListener(MutableTaxonListListener listener) {
2554 } // Do nothing at the moment
2555
2556 // **************************************************************
2557 // Identifiable IMPLEMENTATION
2558 // **************************************************************
2559
2560 protected String id = null;
2561
2562 /**
2563 * @return the id.
2564 */
2565 public String getId() {
2566 return id;
2567 }
2568
2569 /**
2570 * Sets the id.
2571 */
2572 public void setId(String id) {
2573 this.id = id;
2574 }
2575
2576 // **************************************************************
2577 // Attributable IMPLEMENTATION
2578 // **************************************************************
2579
2580 private Attributable.AttributeHelper treeAttributes = null;
2581
2582 /**
2583 * Sets an named attribute for this object.
2584 *
2585 * @param name the name of the attribute.
2586 * @param value the new value of the attribute.
2587 */
2588 public void setAttribute(String name, Object value) {
2589 if (treeAttributes == null)
2590 treeAttributes = new Attributable.AttributeHelper();
2591 treeAttributes.setAttribute(name, value);
2592 }
2593
2594 /**
2595 * @param name the name of the attribute of interest.
2596 * @return an object representing the named attributed for this object.
2597 */
2598 public Object getAttribute(String name) {
2599 if (treeAttributes == null)
2600 return null;
2601 else
2602 return treeAttributes.getAttribute(name);
2603 }
2604
2605 /**
2606 * @return an iterator of the attributes that this object has.
2607 */
2608 public Iterator<String> getAttributeNames() {
2609 if (treeAttributes == null)
2610 return null;
2611 else
2612 return treeAttributes.getAttributeNames();
2613 }
2614
2615 /**
2616 * @return a string containing a newick representation of the tree
2617 */
2618 public final String getNewick(int partition) {
2619 return TreeUtils.newick(new ARGTree(this, partition));
2620 // return Tree.Utils.newick(this);
2621 }
2622
2623 /**
2624 * Checks whether <code>ARGMode</code> is in edit mode.
2625 *
2626 * @throws RuntimeException if the <code>ARGModel</code> is not in edit mode.
2627 */
2628 private void checkEditMode() throws RuntimeException {
2629 if (!inEdit)
2630 throw new RuntimeException("Not in edit transaction mode!");
2631 }
2632
2633 public void checkBranchSanity() {
2634 boolean plotted = false;
2635 for (Node node : nodes) {
2636 if (!node.isRoot()) {
2637 double length1 = 0;
2638 double length2 = 0;
2639 if (node.leftParent != null)
2640 length1 = getNodeHeight(node.leftParent)
2641 - getNodeHeight(node);
2642 if (node.rightParent != null)
2643 length2 = getNodeHeight(node.rightParent)
2644 - getNodeHeight(node);
2645 if (String.valueOf(length1).equals("NaN")
2646 || String.valueOf(length2).equals("NaN")) {
2647 if (!plotted) {
2648 System.err.println(toGraphString());
2649 plotted = true;
2650 }
2651 System.err.println("Caught the NaN: node=" + node.number
2652 + " (" + node.getHeight() + ") lp="
2653 + node.leftParent.number + " ("
2654 + node.leftParent.getHeight() + ") rp="
2655 + node.rightParent.number + " ("
2656 + node.rightParent.getHeight() + ")");
2657 System.exit(-1);
2658 }
2659 }
2660 }
2661
2662 }
2663
2664 /**
2665 * @return a string containing an extended newick representation of the tree
2666 */
2667 public String toString() {
2668 // StringBuffer sb = new StringBuffer();
2669 // for (int i = 0; i < maxNumberOfPartitions; i++) {
2670 // sb.append(i + ": ");
2671 // sb.append(getNewick(i));
2672 // }
2673 // return new String(sb);
2674 return toExtendedNewick();
2675 }
2676
2677 public static final String nullEdge = " -";
2678
2679 public void appendGraphStringOld(StringBuffer sb) {
2680 int cnt = 0;
2681
2682 for (Node node : nodes)
2683 node.number = cnt++;
2684
2685 cnt = 0;
2686 for (Node node : nodes) {
2687 sb.append(cnt == 0 ? "[" : ",[");
2688 cnt++;
2689 sb.append(node.number + ":");
2690
2691 if (node.leftParent == null)
2692 sb.append(nullEdge);
2693 else
2694 sb.append(" " + node.leftParent.number);
2695
2696 if (node.rightParent == null)
2697 sb.append(nullEdge);
2698 else
2699 sb.append(" " + node.rightParent.number);
2700
2701 if (node.leftChild == null)
2702 sb.append(nullEdge);
2703 else
2704 sb.append(" " + node.leftChild.number);
2705
2706 if (node.rightChild == null)
2707 sb.append(nullEdge);
2708 else
2709 sb.append(" " + node.rightChild.number);
2710 // sb.append(" " + node.bifurcation);
2711 if (node.taxon != null)
2712 sb.append(" " + node.taxon.toString());
2713 // if (node.leftPartition != null)
2714 // sb.append(" l");
2715 // if (node.rightPartition != null)
2716 // sb.append(" r");
2717 sb.append("]");
2718 //
2719 // );
2720 }
2721 // sb.append("Root = " + ((Node) getRoot()).number + "\n");
2722 // sb.append("\n");
2723 }
2724
2725 public boolean validRoot() {
2726 // todo -- there must be a way to some graph properties to do this
2727 // check.
2728 boolean valid = true;
2729 for (int i = 0; valid && i < maxNumberOfPartitions; i++) {
2730 ARGTree argTree = new ARGTree(this, i);
2731 if (argTree.wasRootTrimmed())
2732 valid = false;
2733 }
2734 return valid;
2735 }
2736
2737 public String toGraphString() {
2738 int cnt = 1;
2739 for (Node node : nodes) {
2740 node.number = cnt;
2741 cnt++;
2742 }
2743 StringBuffer sb = new StringBuffer();
2744 sb.append("Total length: " + nodes.size() + "\n");
2745 for (Node node : nodes) {
2746 sb.append(node.number + ":");
2747
2748 if (node.leftParent == null)
2749 sb.append(" 0");
2750 else
2751 sb.append(" " + node.leftParent.number);
2752
2753 if (node.rightParent == null)
2754 sb.append(" 0");
2755 else
2756 sb.append(" " + node.rightParent.number);
2757
2758 if (node.leftChild == null)
2759 sb.append(" 0");
2760 else
2761 sb.append(" " + node.leftChild.number);
2762
2763 if (node.rightChild == null)
2764 sb.append(" 0");
2765 else
2766 sb.append(" " + node.rightChild.number);
2767 // sb.append(" " + node.bifurcation);
2768 if (node.taxon != null)
2769 sb.append(" " + node.taxon.toString());
2770 if (node.partitioning != null)
2771 sb.append(" p");
2772 /*
2773 * if (node.leftPartition != null) sb.append(" l"); if
2774 * (node.rightPartition != null) sb.append(" r");
2775 */
2776 sb.append("\t" + getNodeHeight(node));
2777 sb.append("\n");
2778 }
2779 sb.append("Root = " + ((Node) getRoot()).number + "\n");
2780 return new String(sb);
2781 }
2782
2783 public ARGModel fromGraphStringCompressed(String source) {
2784 StringTokenizer st1 = new StringTokenizer(source, ":");
2785 int numberNodes = Integer.parseInt(st1.nextToken());
2786 int numberPartitions = Integer.parseInt(st1.nextToken());
2787 int rootNumber = Integer.parseInt(st1.nextToken());
2788 int external = 0;
2789
2790 ArrayList<Node> nodes = new ArrayList<Node>();
2791 for (int i = 0; i < numberNodes; i++) {
2792 Node node = new Node();
2793 node.number = i;
2794 nodes.add(node);
2795 }
2796
2797 for (int i = 0; i < numberNodes; i++) {
2798 String nodeString = st1.nextToken();
2799 StringTokenizer st2 = new StringTokenizer(nodeString);
2800 Node node = nodes.get(i);
2801 int lP = Integer.parseInt(st2.nextToken());
2802 int rP = Integer.parseInt(st2.nextToken());
2803 int lC = Integer.parseInt(st2.nextToken());
2804 int rC = Integer.parseInt(st2.nextToken());
2805 if (lP != -1)
2806 node.leftParent = nodes.get(lP);
2807 if (rP != -1)
2808 node.rightParent = nodes.get(rP);
2809 if (lC != -1)
2810 node.leftChild = nodes.get(lC);
2811 if (rC != -1)
2812 node.rightChild = nodes.get(rC);
2813 double height = Double.parseDouble(st2.nextToken());
2814 node.heightParameter = new Parameter.Default(height);
2815 String name = st2.nextToken();
2816 if (name.compareTo("NA") != 0) {
2817 node.taxon = new Taxon(name); // todo saveList
2818 external++;
2819 }
2820 String p = st2.nextToken();
2821 if (p.compareTo("NA") == 0)
2822 node.bifurcation = true;
2823 else {
2824 node.bifurcation = false;
2825 node.partitioning = new Parameter.Default(numberPartitions, 0.0);
2826 node.partitioning.setParameterValueQuietly(Integer.parseInt(p),
2827 1.0);
2828 while (st2.hasMoreTokens())
2829 node.partitioning.setParameterValueQuietly(Integer
2830 .parseInt(st2.nextToken()), 1.0);
2831 }
2832 }
2833
2834 return new ARGModel(nodes, nodes.get(rootNumber), numberPartitions,
2835 external);
2836
2837 // return null;
2838 }
2839
2840
2841 /**
2842 * Gives a summary of the ARG model. Should only
2843 * be used for debugging purposes because it's really slow.
2844 *
2845 * @return a summary of the ARG model.
2846 */
2847 public String toARGSummary() {
2848 NumberFormatter format = new NumberFormatter(4);
2849
2850 String space = " ";
2851
2852 String a = "----------------------\n" +
2853 "ARG Summary \n---------------------- \n";
2854
2855 a += "Number of nodes: " + nodes.size() + "\n";
2856 a += "Number of partitions: " + maxNumberOfPartitions + "\n";
2857 a += "Number of Reassorments: " + this.getReassortmentNodeCount() + "\n";
2858 a += "Root number: " + getRoot().getNumber() + "\n";
2859 a += "Node Summary"
2860 + "\n----------------------------------------\n" +
2861 "ID LP RP LC RC Height" + space + "TX \n" +
2862 "----------------------------------------\n";
2863
2864 for (Node node : nodes) {
2865 a += node.getNumber() + space;
2866
2867 if (node.leftParent == null) a += "-1" + space;
2868 else a += " " + node.leftParent.number + space;
2869 if (node.rightParent == null) a += "-1" + space;
2870 else a += " " + node.rightParent.number + space;
2871 if (node.leftChild == null) a += "-1" + space;
2872 else a += " " + node.leftChild.number + space;
2873 if (node.rightChild == null) a += "-1" + space;
2874 else a += " " + node.rightChild.number + space;
2875
2876 a += format.formatDecimal(getNodeHeight(node), 4) + space;
2877
2878 if (node.partitioning != null) {
2879 for (int i = 0, n = getNumberOfPartitions(); i < n; i++) {
2880 a += node.partitioning.getParameterValue(i) + space;
2881 }
2882 }
2883
2884 if (node.taxon == null) {
2885 a += "internal" + space;
2886 } else {
2887 a += node.taxon + space;
2888 }
2889 a += "\n";
2890 }
2891 a += "\nInduced Trees" +
2892 "\n----------------------------------------\n";
2893 // for(int i = 0; i < maxNumberOfPartitions; i++){
2894 // ARGTree tree = new ARGTree(this,i);
2895 // a += "Partition " + i + "\n " + tree.toString() + "\n";
2896 // }
2897
2898 return a;
2899 }
2900
2901 public String toGraphStringCompressed(boolean recurse) {
2902 int cnt = 0;
2903 for (Node node : nodes) {
2904 node.number = cnt;
2905 cnt++;
2906 }
2907 StringBuffer sb = new StringBuffer();
2908 // sb.append("Total length: " + nodes.size() + "\n");
2909 sb.append(nodes.size());
2910 sb.append(":");
2911 sb.append(maxNumberOfPartitions);
2912 sb.append(":");
2913 sb.append(getRoot().getNumber());
2914 for (Node node : nodes) {
2915 sb.append(":");
2916
2917 if (node.leftParent == null)
2918 sb.append(" -1");
2919 else
2920 sb.append(" " + node.leftParent.number);
2921
2922 if (node.rightParent == null)
2923 sb.append(" -1");
2924 else
2925 sb.append(" " + node.rightParent.number);
2926
2927 if (node.leftChild == null)
2928 sb.append(" -1");
2929 else
2930 sb.append(" " + node.leftChild.number);
2931
2932 if (node.rightChild == null)
2933 sb.append(" -1");
2934 else
2935 sb.append(" " + node.rightChild.number);
2936 sb.append(" " + getNodeHeight(node));
2937 // sb.append(" " + node.bifurcation);
2938 if (node.taxon != null)
2939 sb.append(" " + node.taxon.toString());
2940 else
2941 sb.append(" NA");
2942 if (node.partitioning != null) {
2943 // sb.append(" p");
2944 double[] bits = node.partitioning.getParameterValues();
2945 for (int i = 0; i < bits.length; i++) {
2946 if (bits[i] == 1) {
2947 sb.append(" " + i);
2948 }
2949 }
2950
2951 } else {
2952 sb.append(" NA");
2953 }
2954
2955 /*
2956 * if (node.leftPartition != null) sb.append(" l"); if
2957 * (node.rightPartition != null) sb.append(" r");
2958 */
2959 // sb.append("\t" + getNodeHeight(node));
2960 // sb.append("\n");
2961 }
2962 // sb.append("Root = " + ((Node) getRoot()).number + "\n");
2963
2964 String rtn = new String(sb);
2965
2966 /*
2967 * if ( recurse ) { ARGModel test = fromGraphStringCompressed(rtn);
2968 * System.err.println("OLD 0: "+getNewick(0)); System.err.println("NEW
2969 * 0: "+test.getNewick(0)); System.err.println("OLD:
2970 * "+toGraphStringCompressed(false)); System.err.println("NEW:
2971 * "+test.toGraphStringCompressed(false)); }
2972 */
2973
2974 return new String(sb);
2975 }
2976
2977 public Tree getCopy() {
2978 throw new UnsupportedOperationException(
2979 "please don't call this function");
2980 }
2981
2982 // **************************************************************
2983 // XMLElement IMPLEMENTATION
2984 // **************************************************************
2985
2986 public Element createElement(Document document) {
2987 throw new RuntimeException("Not implemented yet");
2988 }
2989
2990
2991 // ***********************************************************************
2992 // Private methods
2993 // ***********************************************************************
2994
2995 /**
2996 * @return the node that this parameter is a member of
2997 */
2998 protected Node getNodeOfParameter(Parameter parameter) {
2999
3000 if (parameter == null)
3001 throw new IllegalArgumentException("Parameter is null!");
3002
3003 // for (int i =0; i < nodes.length; i++) {
3004 for (Node node : nodes) {
3005 if (node.heightParameter == parameter) {
3006 return node;
3007 }
3008 if (hasRates && node.rateParameter == parameter) {
3009 return node;
3010 }
3011 if (hasTraits && node.traitParameter == parameter) {
3012 return node;
3013 }
3014 }
3015 throw new RuntimeException("Parameter not found in any nodes:"
3016 + parameter.getId());
3017 }
3018
3019 /**
3020 * Get the root height parameter. Is private because it can only be called
3021 * by the XMLParser
3022 */
3023 public Parameter getRootHeightParameter() {
3024
3025 return root.heightParameter;
3026 }
3027
3028 /**
3029 * @return the relevant node height parameter. Is private because it can
3030 * only be called by the XMLParser
3031 */
3032 public Parameter createNodeHeightsParameter(boolean rootNode,
3033 boolean internalNodes, boolean leafNodes) {
3034
3035 if (!rootNode && !internalNodes && !leafNodes) {
3036 throw new IllegalArgumentException(
3037 "At least one of rootNode, internalNodes or leafNodes must be true");
3038 }
3039
3040 CompoundParameter parameter = new CompoundParameter("nodeHeights");
3041 // System.err.println("Constructed nodeHeights");
3042 for (int i = externalNodeCount; i < nodeCount; i++) {
3043 Node node = nodes.get(i);
3044 if ((rootNode && node == root) || (internalNodes && node != root)) {
3045 parameter.addParameter(node.heightParameter);
3046 }
3047 }
3048
3049 if (leafNodes) {
3050 for (int i = 0; i < externalNodeCount; i++) {
3051 parameter.addParameter(nodes.get(i).heightParameter);
3052 }
3053 }
3054
3055 return parameter;
3056 }
3057
3058 public Parameter getLeafHeightParameter(NodeRef nr) {
3059 Node node = (Node) nr;
3060 if (!isExternal(node)) {
3061 throw new RuntimeException(
3062 "only root and leaves can be used with setNodeHeightParameter");
3063 }
3064
3065 return nodes.get(nodes.indexOf(node)).heightParameter;
3066 }
3067
3068 /**
3069 * @return the relevant node rate parameter. Is private because it can only
3070 * be called by the XMLParser
3071 */
3072 public Parameter createNodeRatesParameter(boolean rootNode,
3073 boolean internalNodes, boolean leafNodes, int numberPartitions) {
3074
3075 if (!rootNode && !internalNodes && !leafNodes) {
3076 throw new IllegalArgumentException(
3077 "At least one of rootNode, internalNodes or leafNodes must be true");
3078 }
3079
3080 CompoundParameter parameter = new CompoundParameter(TreeModelParser.NODE_RATES);
3081
3082 hasRates = true;
3083
3084 for (int i = externalNodeCount; i < nodeCount; i++) {
3085 Node node = nodes.get(i);
3086 node.createRateParameter(numberPartitions);
3087 if ((rootNode && node == root) || (internalNodes && node != root)) {
3088 parameter.addParameter(node.rateParameter);
3089 }
3090 }
3091
3092 for (int i = 0; i < externalNodeCount; i++) {
3093 Node node = nodes.get(i);
3094 node.createRateParameter(numberPartitions);
3095 if (leafNodes) {
3096 parameter.addParameter(node.rateParameter);
3097 }
3098 }
3099
3100 return parameter;
3101 }
3102
3103 /**
3104 * Create a node traits parameter. Is private because it can only be called
3105 * by the XMLParser
3106 */
3107 public Parameter createNodeTraitsParameter(boolean rootNode,
3108 boolean internalNodes, boolean leafNodes) {
3109
3110 if (!rootNode && !internalNodes && !leafNodes) {
3111 throw new IllegalArgumentException(
3112 "At least one of rootNode, internalNodes or leafNodes must be true");
3113 }
3114
3115 CompoundParameter parameter = new CompoundParameter(TreeModelParser.NODE_TRAITS);
3116
3117 hasTraits = true;
3118
3119 for (int i = externalNodeCount; i < nodeCount; i++) {
3120 Node node = nodes.get(i);
3121 node.createTraitParameter();
3122 if ((rootNode && node == root) || (internalNodes && node != root)) {
3123 parameter.addParameter(node.traitParameter);
3124 }
3125 }
3126
3127 for (int i = 0; i < externalNodeCount; i++) {
3128 Node node = nodes.get(i);
3129 node.createTraitParameter();
3130 if (leafNodes) {
3131 parameter.addParameter(node.traitParameter);
3132 }
3133 }
3134
3135 return parameter;
3136 }
3137
3138 /**
3139 * This method swaps the parameter objects of the two nodes but maintains
3140 * the values in each node. This method is used to ensure that root node of
3141 * the tree always has the same parameter object.
3142 */
3143 private void swapParameterObjects(Node n1, Node n2) {
3144
3145 double height1 = n1.getHeight();
3146 double height2 = n2.getHeight();
3147
3148 double rate1 = 1.0, rate2 = 1.0;
3149 double trait1 = 0.0, trait2 = 0.0;
3150
3151 if (hasRates) {
3152 System.exit(-1);
3153
3154 rate1 = n1.getRate(0);
3155 rate2 = n2.getRate(0);
3156 }
3157
3158 if (hasTraits) {
3159 trait1 = n1.getTrait();
3160 trait2 = n2.getTrait();
3161 }
3162
3163 Parameter temp = n1.heightParameter;
3164 n1.heightParameter = n2.heightParameter;
3165 n2.heightParameter = temp;
3166
3167 if (hasRates) {
3168 temp = n1.rateParameter;
3169 n1.rateParameter = n2.rateParameter;
3170 n2.rateParameter = temp;
3171 }
3172
3173 if (hasTraits) {
3174 temp = n1.traitParameter;
3175 n1.traitParameter = n2.traitParameter;
3176 n2.traitParameter = temp;
3177 }
3178
3179 n1.heightParameter.setParameterValueQuietly(0, height1);
3180 n2.heightParameter.setParameterValueQuietly(0, height2);
3181
3182 if (hasRates) {
3183 n1.rateParameter.setParameterValueQuietly(0, rate1);
3184 n2.rateParameter.setParameterValueQuietly(0, rate2);
3185 }
3186
3187 if (hasTraits) {
3188 n1.traitParameter.setParameterValueQuietly(0, trait1);
3189 n2.traitParameter.setParameterValueQuietly(0, trait2);
3190 }
3191
3192 }
3193
3194 // **************************************************************
3195 // Private inner classes
3196 // **************************************************************
3197 public class Node implements NodeRef {
3198
3199 public boolean[] ancestralMaterial;
3200 public boolean fullAncestralMaterial;
3201 public boolean hasSomeAncestralMaterial;
3202
3203 public boolean hasReassortmentAncestor() {
3204 Node a = this;
3205
3206 while (a != null) {
3207 if (!a.bifurcation) {
3208 return true;
3209 } else {
3210 a = a.leftParent;
3211 }
3212 }
3213
3214
3215 return false;
3216 }
3217
3218 public void setAncestralMaterial(boolean[] childAncestralMaterial) {
3219 if (fullAncestralMaterial) {
3220 return;
3221 }
3222
3223 fullAncestralMaterial = true;
3224
3225 for (int i = 0; i < ancestralMaterial.length; i++) {
3226 ancestralMaterial[i] = ancestralMaterial[i] || childAncestralMaterial[i];
3227
3228 fullAncestralMaterial = fullAncestralMaterial && ancestralMaterial[i];
3229 hasSomeAncestralMaterial = hasSomeAncestralMaterial || ancestralMaterial[i];
3230 }
3231
3232 if (bifurcation) {
3233 if (this.leftParent != null)
3234 this.leftParent.setAncestralMaterial(ancestralMaterial);
3235 } else {
3236 boolean[] leftAncestralMaterial = new boolean[ancestralMaterial.length];
3237 boolean[] rightAncestralMaterial = new boolean[ancestralMaterial.length];
3238
3239 System.arraycopy(ancestralMaterial, 0, leftAncestralMaterial, 0, leftAncestralMaterial.length);
3240 System.arraycopy(ancestralMaterial, 0, rightAncestralMaterial, 0, rightAncestralMaterial.length);
3241
3242 for (int i = 0; i < ancestralMaterial.length; i++) {
3243 if (partitioning.getParameterValue(i) == 0.0) {
3244 rightAncestralMaterial[i] = false;
3245 } else {
3246 leftAncestralMaterial[i] = false;
3247 }
3248 }
3249
3250 this.leftParent.setAncestralMaterial(leftAncestralMaterial);
3251 this.rightParent.setAncestralMaterial(rightAncestralMaterial);
3252 }
3253 }
3254
3255
3256 public int myHashCode = 0;
3257
3258 public int hashCode() {
3259 if (myHashCode == 0) {
3260 myHashCode = super.hashCode();
3261 }
3262 return myHashCode;
3263 }
3264
3265 public boolean equals(Object o) {
3266 return hashCode() == o.hashCode();
3267 }
3268
3269
3270 public NodeRef mirrorNode;
3271
3272 public Node leftParent, rightParent;
3273
3274 public Node leftChild, rightChild;
3275
3276 public int number;
3277
3278 public Parameter heightParameter;
3279
3280 //First half of the rate parameter represent the rates
3281 //Second half represents 0-1 indicators
3282
3283 public Parameter rateParameter = null;
3284
3285 public Parameter traitParameter = null;
3286
3287 public Taxon taxon = null;
3288
3289 // public BitSet leftPartition = null;
3290 // public BitSet rightPartition = null;
3291 // public Node dupSister = null;
3292 // public Node linkSister = null;
3293 // public Node dupParent = null;
3294
3295 // public Node leftParent;
3296 // public Node rightParent;
3297
3298 // public int leftPartition;
3299 // public int rightPartition;
3300
3301 public Parameter partitioning;
3302
3303 public boolean bifurcation = true;
3304
3305 public int countReassortmentChild(Tree tree) {
3306 // int cnt = 0;
3307 if (isExternal())
3308 return 0;
3309 // if( leftChild == null ) {
3310 // System.err.println("left is null");
3311 // System.err.println("is reassort = "+isReassortment());
3312 // System.err.println("right child = "+Tree.Utils.uniqueNewick(tree,
3313 // rightChild));
3314 // }
3315 // if( rightChild == null ) {
3316 // System.err.println("right is null");
3317 // System.err.println("is reassort = "+isReassortment());
3318 // System.err.println("left child = "+Tree.Utils.uniqueNewick(tree,
3319 // leftChild));
3320 // }
3321 if (isReassortment()) {
3322 return 1 + leftChild.countReassortmentChild(tree);
3323 } else if (isBifurcationDoublyLinked()) {
3324 return leftChild.countReassortmentChild(tree);
3325 } else {
3326 return leftChild.countReassortmentChild(tree)
3327 + rightChild.countReassortmentChild(tree);
3328 }
3329 }
3330
3331 public Node() {
3332 leftParent = rightParent = null;
3333 leftChild = rightChild = null;
3334 heightParameter = null;
3335 number = 0;
3336 taxon = null;
3337 // leftPartition = null;
3338 // rightPartition = null;
3339 partitioning = null;
3340 }
3341
3342 /**
3343 * Constructor to build an ARG into a bifurcating tree
3344 *
3345 * @param node
3346 */
3347 public Node(Node node) {
3348 leftParent = rightParent = null;
3349 leftChild = rightChild = null;
3350 heightParameter = node.heightParameter;
3351 taxon = node.taxon;
3352 number = node.number;
3353 // if( node.isReassortment() ) {
3354 // Node parent = leftParent;
3355 // parent.removeChild(this);
3356 // return new Node(leftChild);
3357 // } else {
3358 if (node.leftChild != null) {
3359 if (node.leftChild.isReassortment())
3360 singleAddChild(new Node(node.leftChild.leftChild));
3361 else
3362 singleAddChild(new Node(node.leftChild));
3363 }
3364 if (node.rightChild != null) {
3365 if (node.rightChild.isReassortment())
3366 singleAddChild(new Node(node.rightChild.leftChild));
3367 else
3368 singleAddChild(new Node(node.rightChild));
3369 }
3370 // }
3371 }
3372
3373 /**
3374 * constructor used to clone a node and all children with no
3375 * reassortments
3376 */
3377 public Node(Tree tree, NodeRef node) {
3378 leftParent = rightParent = null;
3379 leftChild = rightChild = null;
3380 // leftPartition = new BitSet();
3381 // leftPartition.set(0);
3382 // leftPartition = null;
3383 // rightPartition = new BitSet();
3384 // rightPartition.set(0);
3385 // rightPartition = null;
3386 partitioning = null;
3387 heightParameter = new Parameter.Default(tree.getNodeHeight(node));
3388 addVariable(heightParameter);
3389
3390 number = node.getNumber();
3391 taxon = tree.getNodeTaxon(node);
3392
3393 for (int i = 0; i < tree.getChildCount(node); i++) {
3394 singleAddChild(new Node(tree, tree.getChild(node, i)));
3395 }
3396 // System.err.println("Built initial tree");
3397 // System.exit(-1);
3398 }
3399
3400 // public Node(Node node, int partition)
3401 // {
3402 // leftParent = rightParent = null;
3403 // leftChild = rightChild = null;
3404 // leftPartition = node.leftPartition;
3405 // rightPartition = node.rightPartition;
3406 // //leftPartition = rightPartition = null;
3407 // heightParameter = node.heightParameter;
3408 // number = node.number;
3409 // taxon = node.taxon;
3410 // bifurcation = node.bifurcation;
3411 // // System.err.println("Examinging "+number);
3412 // Node left;
3413 // if( node.leftChild != null ) {
3414 // Node left = node.getChild(0,partition);
3415 // }
3416 // Node right;
3417 // if( node.rightChild != null ) {
3418 // Node right = node.getChild(1,partition);
3419 // }
3420 //
3421 // if( left != null ) {
3422 // // System.err.println("Adding "+number+"->"+left.number);
3423 // singleAddChild(new Node(left,partition));
3424 // }
3425 // }
3426 //
3427 // if( right != null ) {
3428 // // System.err.println("Adding "+number+"->"+right.number);
3429 // singleAddChild(new Node(right,partition));
3430 // }
3431 // }
3432 // }
3433
3434 public Node(Node inode, int partition) { //, ArrayList<Node> nodes) {
3435 leftParent = rightParent = null;
3436 leftChild = rightChild = null;
3437 Node node = inode;
3438 while (node.isBifurcationDoublyLinked()) {
3439 node = node.leftChild.leftChild;
3440 // System.err.println("Does this do anything?");
3441 }
3442 heightParameter = node.heightParameter;
3443 number = node.number;
3444 taxon = node.taxon;
3445 bifurcation = true;
3446
3447 mirrorNode = node;
3448
3449 if (node.isExternal())
3450 // nodes.add(this);
3451 return;
3452 else {
3453 Node left, right;
3454 left = node.getChild(0, partition);
3455 right = node.getChild(1, partition);
3456 if (left != null || right != null) {
3457 if (left != null) {
3458 singleAddChild(new Node(left, partition));
3459 }
3460 if (right != null) {
3461 singleAddChild(new Node(right, partition));
3462 }
3463 // nodes.add(this);
3464 }
3465 }
3466 }
3467
3468 public void setPartitionRecursively(int partition) {
3469 boolean onLeft = MathUtils.nextBoolean();
3470 if (leftChild != null) {
3471 // if( leftPartition != null )
3472 // leftPartition.set(partition);
3473 if (partitioning != null && onLeft)
3474 partitioning.setParameterValue(partition, 1);
3475 leftChild.setPartitionRecursively(partition);
3476 }
3477 if (rightChild != null) {
3478 // if( leftPartition != null )
3479 // rightPartition.set(partition);
3480 if (partitioning != null && !onLeft)
3481 partitioning.setParameterValue(partition, 1);
3482 rightChild.setPartitionRecursively(partition);
3483 }
3484
3485 }
3486
3487 public void stripOutDeadEnds() {
3488 if (leftChild != null)
3489 leftChild.stripOutDeadEnds();
3490 if (rightChild != null && rightChild != leftChild)
3491 rightChild.stripOutDeadEnds();
3492 if (taxon == null && leftChild == null && rightChild == null)
3493 leftParent.doubleRemoveChild(this);
3494 }
3495
3496 public Node stripOutSingleChildNodes(Node cRoot) {
3497 // Node rtn = cRoot;
3498 int childCount = getChildCount();
3499 if (childCount == 0) {
3500 return cRoot;
3501 }
3502 if (childCount == 2) {
3503 if (hasEqualChildren()) {
3504 return leftChild.stripOutSingleChildNodes(leftChild);
3505 }
3506 leftChild.stripOutSingleChildNodes(cRoot);
3507 rightChild.stripOutSingleChildNodes(cRoot);
3508 return cRoot;
3509 }
3510 if (isRoot()) {
3511 if (leftChild != null) {
3512 leftChild.leftParent = leftChild.rightParent = null;
3513 return leftChild.stripOutSingleChildNodes(leftChild);
3514 } else {
3515 rightChild.leftParent = rightChild.rightParent = null;
3516 return rightChild.stripOutSingleChildNodes(rightChild);
3517 }
3518 }
3519 // System.err.println("Unlinking "+number);
3520 Node parent = leftParent;
3521 Node child = leftChild;
3522 if (child == null)
3523 child = rightChild;
3524 parent.doubleRemoveChild(this);
3525 doubleRemoveChild(child);
3526 parent.singleAddChild(child);
3527 return child.stripOutSingleChildNodes(cRoot);
3528 }
3529
3530 public final void setupHeightBounds() {
3531 heightParameter.addBounds(new NodeHeightBounds(heightParameter));
3532 }
3533
3534
3535 public final void createRateParameter(int numberPartitions) {
3536 if (rateParameter == null) {
3537
3538 double[] startingRateValues = new double[numberPartitions];
3539
3540 for (int i = 0; i < startingRateValues.length; i++) {
3541 startingRateValues[i] = 1.0;
3542 }
3543
3544 rateParameter = new Parameter.Default(startingRateValues);
3545
3546 if (isRoot()) {
3547 rateParameter.setId("root.rate");
3548 } else if (isExternal()) {
3549 rateParameter.setId(getTaxonId(getNumber()) + ".rate");
3550 } else {
3551 rateParameter.setId("node" + getNumber() + ".rate");
3552 }
3553 rateParameter.addBounds(new Parameter.DefaultBounds(
3554 Double.POSITIVE_INFINITY, 0, startingRateValues.length));
3555 addVariable(rateParameter);
3556 }
3557 }
3558
3559 public final void createTraitParameter() {
3560 if (traitParameter == null) {
3561 traitParameter = new Parameter.Default(1.0);
3562 if (isRoot()) {
3563 traitParameter.setId("root.trait");
3564 } else if (isExternal()) {
3565 traitParameter.setId(getTaxonId(getNumber()) + ".trait");
3566 } else {
3567 traitParameter.setId("node" + getNumber() + ".trait");
3568 }
3569 rateParameter.addBounds(new Parameter.DefaultBounds(
3570 Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, 1));
3571
3572 addVariable(traitParameter);
3573 }
3574 }
3575
3576 public final double getHeight() {
3577 return heightParameter.getParameterValue(0);
3578 }
3579
3580 public final double getRate(int partition) {
3581
3582
3583 return rateParameter.getParameterValue(partition);
3584 }
3585
3586 public final double getTrait() {
3587 return traitParameter.getParameterValue(0);
3588 }
3589
3590 public final void setHeight(double height) {
3591 heightParameter.setParameterValue(0, height);
3592 }
3593
3594 public final void setRate(double rate) {
3595 // System.out.println("Rate set for parameter " +
3596 // rateParameter.getParameterName());
3597 rateParameter.setParameterValue(0, rate);
3598 }
3599
3600 public final void setTrait(double trait) {
3601 // System.out.println("Trait set for parameter " +
3602 // traitParameter.getParameterName());
3603 traitParameter.setParameterValue(0, trait);
3604 }
3605
3606 public int getNumber() {
3607 return number;
3608 }
3609
3610 public void setNumber(int n) {
3611 number = n;
3612 }
3613
3614 /**
3615 * Returns the number of children this node has.
3616 */
3617 public final int getChildCount() {
3618 int n = 0;
3619 if (leftChild != null)
3620 n++;
3621 if (rightChild != null && bifurcation)
3622 n++;
3623 return n;
3624 }
3625
3626 public final int getParentCount() {
3627 int n = 0;
3628 if (leftParent != null)
3629 n++;
3630 if (rightParent != null)
3631 n++;
3632 return n;
3633 }
3634
3635 public Node getChild(int n) {
3636 if (n == 0)
3637 return leftChild;
3638 if (n == 1)
3639 return rightChild;
3640 throw new IllegalArgumentException(
3641 "ARGModel.Nodes can only have up to 2 children");
3642 }
3643
3644
3645 private boolean isBifurcationDoublyLinked() {
3646 return bifurcation && (leftChild == rightChild)
3647 && leftChild != null;
3648 }
3649
3650 private boolean recombinantIsLinked(Node parent, int partition) {
3651 boolean left = leftParent == parent;
3652 boolean right = rightParent == parent;
3653 final double partitionSide = partitioning
3654 .getParameterValue(partition);
3655 if (left && partitionSide == 0)
3656 return true;
3657 if (right && partitionSide == 1)
3658 return true;
3659 return false;
3660
3661 }
3662
3663 public int getDescendentTipCount() {
3664 if (isExternal())
3665 return 1;
3666 return leftChild.getDescendentTipCount()
3667 + rightChild.getDescendentTipCount();
3668 }
3669
3670 public boolean checkForNullRights() {
3671 if (isExternal())
3672 return false;
3673 if (rightChild == null)
3674 return true;
3675 else
3676 return rightChild.checkForNullRights()
3677 || leftChild.checkForNullRights();
3678 }
3679
3680 private Node findNextTreeNode(Node parent, int partition) { // searches
3681 // down the
3682 // ARG for
3683 // the next
3684 // bifurcation
3685 // or tip
3686 if (isExternal())
3687 return this;
3688 Node next = this;
3689 while (next.isReassortment()) {
3690 if (recombinantIsLinked(parent, partition))
3691 return leftChild.findNextTreeNode(parent, partition);
3692 else
3693 return null;
3694 }
3695 // if( leftChild.findNextTreeMode())
3696 next = leftChild.findNextTreeNode(parent, partition);
3697 if (next == null)
3698 next = rightChild.findNextTreeNode(parent, partition);
3699 if (next == null) // TODO Error check for removal
3700 throw new IllegalArgumentException("Can't find next tree node.");
3701 return next;
3702 }
3703
3704 private Node getChild(int n, int partition) { // Assuming an acyclic
3705 // bifurcating tree
3706 Node child = null;
3707 if (n == 0) // Handle left side
3708 child = leftChild;
3709 if (n == 1) // Handle right side
3710 child = rightChild;
3711 if (child.isExternal())
3712 return child;
3713 if (child.isBifurcationDoublyLinked()) {
3714 // System.err.println("Passing double from
3715 // "+number+"->"+child.leftChild.number);
3716 return child.leftChild.getChild(0, partition);
3717 }
3718 if (child.isReassortment()) {
3719 if (child.recombinantIsLinked(this, partition))
3720 return child.getChild(0, partition);
3721 else
3722 return null;
3723 }
3724 if (child.leftChild.isReassortment()
3725 && child.rightChild.isReassortment()) {
3726 if (child.leftChild.recombinantIsLinked(child, partition))
3727 return child;
3728 if (child.rightChild.recombinantIsLinked(child, partition))
3729 return child;
3730 return null;
3731 }
3732 return child;
3733 }
3734
3735 public Node getParent(int n) {
3736 if (n == 0)
3737 return leftParent;
3738 if (n == 1)
3739 return rightParent;
3740 throw new IllegalArgumentException(
3741 "ARGModel.Nodes can only have 2 parents");
3742 }
3743
3744 public boolean hasChild(Node node) {
3745 return (leftChild == node || rightChild == node);
3746 }
3747
3748 /**
3749 * add new child node
3750 *
3751 * @param node new child node
3752 */
3753 public void singleAddChild(Node node) {
3754 if (leftChild == null) {
3755 leftChild = node;
3756 } else if (rightChild == null) {
3757 rightChild = node;
3758 } else {
3759 throw new IllegalArgumentException(
3760 "ARGModel.Nodes can only have 2 children");
3761 }
3762 // if( node.leftParent == null )
3763 if (node.leftParent == null)
3764 node.leftParent = this;
3765 if (node.rightParent == null)
3766 node.rightParent = this;
3767 }
3768
3769 public void singleAddChildWithOneParent(Node node) {
3770 if (leftChild == null) {
3771 leftChild = node;
3772 } else if (rightChild == null) {
3773 rightChild = node;
3774 } else {
3775 throw new IllegalArgumentException("ARGModel.Node " + number
3776 + " can only have 2 children");
3777 }
3778 // if( node.leftParent == null )
3779 if (node.leftParent == null) {
3780 node.leftParent = this;
3781 } else if (node.rightParent == null) {
3782 node.rightParent = this;
3783 } else {
3784 throw new IllegalArgumentException(
3785 "ARGModel.Nodes can only have 2 parents");
3786 }
3787 }
3788
3789 public void doubleAddChild(Node node) {
3790 if (leftChild == null) {
3791 leftChild = node;
3792 }
3793 if (rightChild == null) {
3794 rightChild = node;
3795 }// else {
3796 // throw new IllegalArgumentException("ARGModel.Nodes can only have
3797 // 2 children");
3798 // }
3799 // if( node.leftParent == null )
3800 if (node.leftParent == null)
3801 node.leftParent = this;
3802 if (node.rightParent == null)
3803 node.rightParent = this;
3804 }
3805
3806 public void doubleAddChildWithOneParent(Node node) {
3807 if (leftChild == null) {
3808 leftChild = node;
3809 }
3810 if (rightChild == null) {
3811 rightChild = node;
3812 }// else {
3813 // throw new IllegalArgumentException("ARGModel.Nodes can only have
3814 // 2 children");
3815 // }
3816 if (node.leftParent == null) {
3817 node.leftParent = this;
3818 } else if (node.rightParent == null) {
3819 node.rightParent = this;
3820 } else {
3821 throw new IllegalArgumentException(
3822 "ARGModel.Nodes can only have 2 parents");
3823 }
3824 }
3825
3826 public void addChildNoParentConnection(Node node) {
3827 if (leftChild == null)
3828 leftChild = node;
3829 else if (rightChild == null)
3830 rightChild = node;
3831 else
3832 throw new IllegalArgumentException(
3833 "Nodes can only have 2 children.");
3834 }
3835
3836 // public void addChild()
3837
3838 // public void addChildRecombinant(Node node, BitSet partition) {
3839
3840 public void addChildRecombinant(Node node, Parameter partition) {
3841 // if( leftChild == null && rightChild == null ) {
3842 // leftChild = rightChild = node;
3843 // } else
3844 // if( leftChild == null && rightChild == null ) {
3845 // System.err.println("yep");
3846 // //System.exit(-1);
3847 // leftChild = rightChild = node;
3848 // }
3849 if (leftChild == null)
3850 leftChild = node;
3851 // leftPartition = partition;
3852 if (rightChild == null)
3853 rightChild = node;
3854 // rightPartition = partition;
3855 // } else {
3856 // throw new IllegalArgumentException("Nodes can only have 2
3857 // children.");
3858 // }
3859 // node.parent = null;
3860 if (node.leftParent == null) {
3861 node.leftParent = this;
3862 // node.leftPartition = partition;
3863 node.partitioning = partition;
3864 } else if (node.rightParent == null) {
3865 node.rightParent = this;
3866 // node.rightPartition = partition;
3867 node.partitioning = partition;
3868 } else {
3869 throw new IllegalArgumentException(
3870 "Recombinant nodes can only have 2 parents.");
3871 }
3872 }
3873
3874 /**
3875 * remove child
3876 *
3877 * @param node child to be removed
3878 */
3879 public Node doubleRemoveChild(Node node) {
3880 boolean found = false;
3881 if (leftChild == node) {
3882 leftChild = null;
3883 // leftPartition = null;
3884 found = true;
3885 }
3886 if (rightChild == node) {
3887 rightChild = null;
3888 // rightPartition = null;
3889 found = true;
3890 }
3891 if (!found)
3892 throw new IllegalArgumentException("Unknown child node");
3893 if (node.leftParent == this)
3894 node.leftParent = null;
3895 // node.leftPartition = null;
3896 if (node.rightParent == this)
3897 node.rightParent = null;
3898 // node.rightPartition = null;
3899 return node;
3900 }
3901
3902 public Node singleRemoveChild(Node node) {
3903 // boolean found = false;
3904 if (leftChild == node) {
3905 leftChild = null;
3906 // leftPartition = null;
3907 // found = true;
3908 } else if (rightChild == node) {
3909 rightChild = null;
3910 // rightPartition = null;
3911 // found = true;
3912 }
3913 // if( !found )
3914 else
3915 throw new IllegalArgumentException("Unknown child node");
3916 if (node.bifurcation) {
3917 node.leftParent = node.rightParent = null;
3918 return null;
3919 }
3920 if (node.leftParent == this)
3921 node.leftParent = null;
3922 // node.leftPartition = null;
3923 else if (node.rightParent == this)
3924 node.rightParent = null;
3925 // node.rightPartition = null;
3926 return node;
3927 }
3928
3929 /**
3930 * remove child
3931 *
3932 * @param n number of child to be removed
3933 */
3934 public Node removeChild(int n) {
3935 Node node;
3936 if (n == 0) {
3937 node = leftChild;
3938 leftChild = null;
3939 } else if (n == 1) {
3940 node = rightChild;
3941 rightChild = null;
3942 } else {
3943 throw new IllegalArgumentException(
3944 "TreeModel.Nodes can only have 2 children");
3945 }
3946 if (node.leftParent == this)
3947 node.leftParent = null;
3948 if (node.rightParent == this)
3949 node.rightParent = null;
3950 return node;
3951 }
3952
3953 public boolean hasChildren() {
3954 return (leftChild != null || rightChild != null);
3955 }
3956
3957 public boolean isExternal() {
3958 return !hasChildren();
3959 }
3960
3961 public boolean isRoot() {
3962 return (leftParent == null && rightParent == null);
3963 }
3964
3965 public boolean hasEqualChildren() {
3966 return (leftChild == rightChild);
3967 }
3968
3969 public boolean isBifurcation() {
3970 return bifurcation;
3971 }
3972
3973 // public boolean isReassortment() { return hasChildren() && (leftChild
3974 // == rightChild); }
3975 public boolean isReassortment() {
3976 return !bifurcation;
3977 }
3978
3979 private String toExtendedNewick() {
3980
3981 if (isExternal())
3982 return taxon.getId();
3983
3984 if (isBifurcation()) {
3985 String left = leftChild.toExtendedNewick();
3986 String right = rightChild.toExtendedNewick();
3987 if (left.compareTo(right) < 0)
3988 return "(" + left + "," + right + ")";
3989 else
3990 return "(" + right + "," + left + ")";
3991 }
3992 // must be a reassortment node
3993 return "<" + leftChild.toExtendedNewick() + ">";
3994 }
3995
3996 public String toString() {
3997 if (taxon == null) {
3998 return "" + number;
3999 }
4000 return "" + number + " (" + taxon.getId() + ")";
4001 }
4002 }
4003
4004 /**
4005 * This class provides bounds for parameters that represent a node height in
4006 * this tree model.
4007 */
4008 private class NodeHeightBounds implements Bounds<Double> {
4009
4010 public NodeHeightBounds(Parameter parameter) {
4011 nodeHeightParameter = parameter;
4012 }
4013
4014 public Double getUpperLimit(int i) {
4015 // I think only upper bounds are of concern with linked subtrees
4016 // because everything below has only one parameter
4017 // TODO -- check this!
4018 Node node = getNodeOfParameter(nodeHeightParameter);
4019 // Returns the first node in nodes[] with this height parameter
4020
4021 if (node.isRoot()) {
4022 return Double.POSITIVE_INFINITY;
4023 // return 10.0;
4024 } else {
4025 if (node.leftParent == null) {
4026 System.err.println("leftParent of " + node.number
4027 + " is null");
4028 }
4029 if (node.rightParent == null) {
4030 System.err.println("rightParent of " + node.number
4031 + " is null");
4032 }
4033 return Math.min(node.leftParent.getHeight(), node.rightParent
4034 .getHeight());
4035 }
4036 }
4037
4038 public Double getLowerLimit(int i) {
4039
4040 Node node = getNodeOfParameter(nodeHeightParameter);
4041 // System.err.println("Is node recombinant?
4042 // "+node.isReassortment());
4043 if (node.isExternal()) {
4044 return 0.0;
4045 } else {
4046 if (node.leftChild == null)
4047 System.err.println("Node " + node.number
4048 + " has null leftChild");
4049 if (node.rightChild == null)
4050 System.err.println("Node " + node.number
4051 + " has null rightChild");
4052 // System.err.println(node.number+" "+(node.leftChild==null)+"
4053 // "+(node.rightChild==null));
4054 return Math.max(node.leftChild.getHeight(), node.rightChild
4055 .getHeight());
4056 }
4057 }
4058
4059 public int getBoundsDimension() {
4060 return 1;
4061 }
4062
4063 private Parameter nodeHeightParameter = null;
4064 }
4065
4066 public double getNodeRate(NodeRef node) {
4067 if (true)
4068 throw new RuntimeException("This should not be called");
4069
4070 return 0;
4071 }
4072
4073 ///////////////////////////////////////////////////////////////////////
4074 //PARSER
4075 ///////////////////////////////////////////////////////////////////////
4076
4077 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
4078
4079 public String getParserName() {
4080 return TREE_MODEL;
4081 }
4082
4083 public String[] getParserNames() {
4084 return new String[]{
4085 getParserName(), "argModel"
4086 };
4087 }
4088
4089 /**
4090 * @return a tree object based on the XML element it was passed.
4091 */
4092 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
4093
4094 Tree tree = (Tree) xo.getChild(Tree.class);
4095 ARGModel treeModel = new ARGModel(tree);
4096
4097 Logger.getLogger("dr.evomodel").info("Creating the tree model, '" + xo.getId() + "'");
4098
4099 if (xo.hasAttribute(PARTITION_TYPE)) {
4100 treeModel.partitionType = xo.getStringAttribute(PARTITION_TYPE);
4101
4102 if (!treeModel.partitionType.equals(REASSORTMENT_PARTITION) &&
4103 !treeModel.partitionType.equals(RECOMBINATION_PARTITION)) {
4104 throw new XMLParseException("Must use either correct partition type");
4105 }
4106 }
4107
4108 int numberPartitions = 1;
4109
4110 if (xo.hasAttribute(NUM_PARTITIONS)) {
4111 numberPartitions = xo.getIntegerAttribute(NUM_PARTITIONS);
4112 }
4113
4114
4115 Logger.getLogger("dr.evomodel").info(
4116 xo.getId() + " has partition type: " + treeModel.partitionType);
4117
4118 for (int i = 0; i < xo.getChildCount(); i++) {
4119 if (xo.getChild(i) instanceof XMLObject) {
4120
4121 XMLObject cxo = (XMLObject) xo.getChild(i);
4122
4123 if (cxo.getName().equals(ROOT_HEIGHT)) {
4124
4125 ParameterParser.replaceParameter(cxo, treeModel
4126 .getRootHeightParameter());
4127
4128 } else if (cxo.getName().equals(LEAF_HEIGHT)) {
4129
4130 String taxonName;
4131 if (cxo.hasAttribute(TAXON)) {
4132 taxonName = cxo.getStringAttribute(TAXON);
4133 } else {
4134 throw new XMLParseException(
4135 "taxa element missing from leafHeight element in treeModel element");
4136 }
4137
4138 int index = treeModel.getTaxonIndex(taxonName);
4139 if (index == -1) {
4140 throw new XMLParseException(
4141 "taxon "
4142 + taxonName
4143 + " not found for leafHeight element in treeModel element");
4144 }
4145 NodeRef node = treeModel.getExternalNode(index);
4146 ParameterParser.replaceParameter(cxo, treeModel
4147 .getLeafHeightParameter(node));
4148
4149 } else if (cxo.getName().equals(NODE_HEIGHTS)) {
4150
4151 boolean rootNode = false;
4152 boolean internalNodes = false;
4153 boolean leafNodes = false;
4154
4155 if (cxo.hasAttribute(ROOT_NODE)) {
4156 rootNode = cxo.getBooleanAttribute(ROOT_NODE);
4157 }
4158
4159 if (cxo.hasAttribute(INTERNAL_NODES)) {
4160 internalNodes = cxo
4161 .getBooleanAttribute(INTERNAL_NODES);
4162 }
4163
4164 if (cxo.hasAttribute(LEAF_NODES)) {
4165 leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
4166 }
4167
4168 if (!rootNode && !internalNodes && !leafNodes) {
4169 throw new XMLParseException(
4170 "one or more of root, internal or leaf nodes must be " +
4171 "selected for the nodeHeights element");
4172 }
4173
4174 ParameterParser.replaceParameter(cxo, treeModel
4175 .createNodeHeightsParameter(rootNode,
4176 internalNodes, leafNodes));
4177
4178 } else if (cxo.getName().equals(NODE_RATES)) {
4179
4180 boolean rootNode = false;
4181 boolean internalNodes = false;
4182 boolean leafNodes = false;
4183
4184 if (cxo.hasAttribute(ROOT_NODE)) {
4185 rootNode = cxo.getBooleanAttribute(ROOT_NODE);
4186 }
4187
4188 if (cxo.hasAttribute(INTERNAL_NODES)) {
4189 internalNodes = cxo
4190 .getBooleanAttribute(INTERNAL_NODES);
4191 }
4192
4193 if (cxo.hasAttribute(LEAF_NODES)) {
4194 leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
4195 }
4196
4197 // if (rootNode) {
4198 // throw new XMLParseException("root node does not have
4199 // a rate parameter");
4200 // }
4201
4202 if (!rootNode && !internalNodes && !leafNodes) {
4203 throw new XMLParseException(
4204 "one or more of root, internal or leaf nodes must be selected for the nodeRates element");
4205 }
4206
4207 ParameterParser.replaceParameter(cxo, treeModel
4208 .createNodeRatesParameter(rootNode,
4209 internalNodes, leafNodes, numberPartitions));
4210
4211 } else if (cxo.getName().equals(NODE_TRAITS)) {
4212
4213 boolean rootNode = false;
4214 boolean internalNodes = false;
4215 boolean leafNodes = false;
4216
4217 if (cxo.hasAttribute(ROOT_NODE)) {
4218 rootNode = cxo.getBooleanAttribute(ROOT_NODE);
4219 }
4220
4221 if (cxo.hasAttribute(INTERNAL_NODES)) {
4222 internalNodes = cxo
4223 .getBooleanAttribute(INTERNAL_NODES);
4224 }
4225
4226 if (cxo.hasAttribute(LEAF_NODES)) {
4227 leafNodes = cxo.getBooleanAttribute(LEAF_NODES);
4228 }
4229
4230 if (!rootNode && !internalNodes && !leafNodes) {
4231 throw new XMLParseException(
4232 "one or more of root, internal or leaf nodes must be selected for the nodeTraits element");
4233 }
4234
4235 ParameterParser.replaceParameter(cxo, treeModel
4236 .createNodeTraitsParameter(rootNode,
4237 internalNodes, leafNodes));
4238
4239 } else {
4240 throw new XMLParseException("illegal child element in "
4241 + getParserName() + ": " + cxo.getName());
4242 }
4243
4244 } else if (xo.getChild(i) instanceof Tree) {
4245 // do nothing - already handled
4246 } else {
4247 throw new XMLParseException("illegal child element in "
4248 + getParserName() + ": " + xo.getChildName(i) + " "
4249 + xo.getChild(i));
4250 }
4251 }
4252
4253
4254 treeModel.setupHeightBounds();
4255
4256 Logger.getLogger("dr.evomodel").info(
4257 " initial tree topology = "
4258 + TreeUtils.uniqueNewick(treeModel, treeModel
4259 .getRoot()));
4260 return treeModel;
4261 }
4262
4263 // ************************************************************************
4264 // AbstractXMLObjectParser implementation
4265 // ************************************************************************
4266
4267 public String getParserDescription() {
4268 return "This element represents a model of the tree. The tree model includes and attributes of the nodes "
4269 + "including the age (or <i>height</i>) and the rate of evolution at each node in the tree.";
4270 }
4271
4272 public String getExample() {
4273 return "<!-- the tree model as special sockets for attaching parameters to various aspects of the tree -->\n"
4274 + "<!-- The treeModel below shows the standard setup with a parameter associated with the root height -->\n"
4275 + "<!-- a parameter associated with the internal node heights (minus the root height) and -->\n"
4276 + "<!-- a parameter associates with all the internal node heights -->\n"
4277 + "<!-- Notice that these parameters are overlapping -->\n"
4278 + "<!-- The parameters are subsequently used in operators to propose changes to the tree node heights -->\n"
4279 + "<treeModel id=\"treeModel1\">\n"
4280 + " <tree idref=\"startingTree\"/>\n"
4281 + " <rootHeight>\n"
4282 + " <parameter id=\"treeModel1.rootHeight\"/>\n"
4283 + " </rootHeight>\n"
4284 + " <nodeHeights internalNodes=\"true\" rootNode=\"false\">\n"
4285 + " <parameter id=\"treeModel1.internalNodeHeights\"/>\n"
4286 + " </nodeHeights>\n"
4287 + " <nodeHeights internalNodes=\"true\" rootNode=\"true\">\n"
4288 + " <parameter id=\"treeModel1.allInternalNodeHeights\"/>\n"
4289 + " </nodeHeights>\n" + "</treeModel>";
4290
4291 }
4292
4293 public Class getReturnType() {
4294 return ARGModel.class;
4295 }
4296
4297 public XMLSyntaxRule[] getSyntaxRules() {
4298 return rules;
4299 }
4300
4301 private final String[] partitionFormats = {REASSORTMENT_PARTITION, RECOMBINATION_PARTITION};
4302
4303 private final XMLSyntaxRule[] rules = {
4304 new StringAttributeRule(PARTITION_TYPE, "Describes the partition structure of the model",
4305 partitionFormats, true),
4306 new ElementRule(Tree.class),
4307 new ElementRule(
4308 ROOT_HEIGHT,
4309 Parameter.class,
4310 "A parameter definition with id only (cannot be a reference!)",
4311 false),
4312 new ElementRule(
4313 NODE_HEIGHTS,
4314 new XMLSyntaxRule[]{
4315 AttributeRule
4316 .newBooleanRule(ROOT_NODE, true,
4317 "If true the root height is included in the parameter"),
4318 AttributeRule
4319 .newBooleanRule(
4320 INTERNAL_NODES,
4321 true,
4322 "If true the internal node heights (minus the root) are included in the parameter"),
4323 new ElementRule(Parameter.class,
4324 "A parameter definition with id only (cannot be a reference!)")},
4325 1, Integer.MAX_VALUE)};
4326
4327 public Parameter oldGetParameter(XMLObject xo) throws XMLParseException {
4328 // public Parameter getParameter(XMLObject xo) throws XMLParseException {
4329
4330
4331 int paramCount = 0;
4332 Parameter param = null;
4333 for (int i = 0; i < xo.getChildCount(); i++) {
4334 if (xo.getChild(i) instanceof Parameter) {
4335 param = (Parameter) xo.getChild(i);
4336 paramCount += 1;
4337 }
4338 }
4339
4340 if (paramCount == 0) {
4341 throw new XMLParseException(
4342 "no parameter element in treeModel " + xo.getName()
4343 + " element");
4344 } else if (paramCount > 1) {
4345 throw new XMLParseException(
4346 "More than one parameter element in treeModel "
4347 + xo.getName() + " element");
4348 }
4349
4350 return param;
4351 }
4352
4353 // todo check to make sure that Andrew's static routine works with this old code
4354 public void oldReplaceParameter(XMLObject xo, Parameter newParam)
4355 // public void replaceParameter(XMLObject xo, Parameter newParam)
4356
4357 throws XMLParseException {
4358
4359 for (int i = 0; i < xo.getChildCount(); i++) {
4360
4361 if (xo.getChild(i) instanceof Parameter) {
4362
4363 XMLObject rxo = null;
4364 Object obj = xo.getRawChild(i);
4365
4366 if (obj instanceof Reference) {
4367 rxo = ((Reference) obj).getReferenceObject();
4368 } else if (obj instanceof XMLObject) {
4369 rxo = (XMLObject) obj;
4370 } else {
4371 throw new XMLParseException(
4372 "object reference not available");
4373 }
4374
4375 if (rxo.getChildCount() > 0) {
4376 throw new XMLParseException(
4377 "No child elements allowed in parameter element.");
4378 }
4379
4380 if (rxo.hasAttribute(XMLParser.IDREF)) {
4381 throw new XMLParseException("References to "
4382 + xo.getName()
4383 + " parameters are not allowed in treeModel.");
4384 }
4385
4386 if (rxo.hasAttribute(ParameterParser.VALUE)) {
4387 throw new XMLParseException("Parameters in "
4388 + xo.getName()
4389 + " have values set automatically.");
4390 }
4391
4392 if (rxo.hasAttribute(ParameterParser.UPPER)) {
4393 throw new XMLParseException("Parameters in "
4394 + xo.getName()
4395 + " have bounds set automatically.");
4396 }
4397
4398 if (rxo.hasAttribute(ParameterParser.LOWER)) {
4399 throw new XMLParseException("Parameters in "
4400 + xo.getName()
4401 + " have bounds set automatically.");
4402 }
4403
4404 if (rxo.hasAttribute(XMLParser.ID)) {
4405
4406 newParam.setId(rxo.getStringAttribute(XMLParser.ID));
4407 }
4408
4409 rxo.setNativeObject(newParam);
4410
4411 return;
4412 }
4413 }
4414 }
4415 };
4416
4417
4418 }