Debian Codegraph @

src/dr/evomodel/arg/operators/ObsoleteARGAddRemoveEventOperator.java

raw symbols SCIP
1 /*
2 * ObsoleteARGAddRemoveEventOperator.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 * AddRemoveSubtreeOperator.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 package dr.evomodel.arg.operators;
35
36 import dr.evolution.tree.NodeRef;
37 import dr.evolution.tree.Tree;
38 import dr.evolution.tree.TreeUtils;
39 import dr.evomodel.arg.ARGModel;
40 import dr.evomodel.arg.ARGModel.Node;
41 import dr.evomodelxml.tree.TreeModelParser;
42 import dr.inference.model.CompoundParameter;
43 import dr.inference.model.Parameter;
44 import dr.inference.operators.*;
45 import dr.math.MathUtils;
46 import dr.math.functionEval.GammaFunction;
47 import dr.xml.*;
48
49 import java.util.ArrayList;
50
51 /**
52 * Implements the subtree slide move.
53 *
54 * @author Marc Suchard
55 * @version $Id: ObsoleteARGAddRemoveEventOperator.java,v 1.18.2.4 2006/11/06 01:38:30 msuchard Exp $
56 */
57 public class ObsoleteARGAddRemoveEventOperator extends AbstractAdaptableOperator {
58 // SimpleMCMCOperator implements AdaptableMCMCOperator {
59
60 public static final String SUBTREE_SLIDE = "addremoveARGEvent";
61 public static final String SWAP_RATES = "swapRates";
62 public static final String SWAP_TRAITS = "swapTraits";
63 public static final String MAX_VALUE = "maxTips";
64 public static final String SINGLE_PARTITION = "singlePartitionProbability";
65 public static final String IS_RECOMBINATION = "isRecombination";
66
67 public static final String JUST_INTERNAL = "justInternalNodes";
68 public static final String INTERNAL_AND_ROOT = "internalAndRootNodes";
69 public static final String NODE_RATES = TreeModelParser.NODE_RATES;
70
71 private ARGModel arg = null;
72 private double size = 1.0;
73 private boolean gaussian = false;
74 private double singlePartitionProbability = 0.0;
75 private boolean isRecombination = false;
76 // private boolean swapRates;
77 // private boolean swapTraits;
78 // private int mode = AdaptableMCMCOperator.DEFAULT;
79 private CompoundParameter internalNodeParameters;
80 private CompoundParameter internalAndRootNodeParameters;
81 private CompoundParameter nodeRates;
82 // private int maxTips = 1;
83
84 public ObsoleteARGAddRemoveEventOperator(ARGModel arg, int weight, double size, boolean gaussian,
85 boolean swapRates, boolean swapTraits, AdaptationMode mode,
86 CompoundParameter param1,
87 CompoundParameter param2,
88 CompoundParameter param3,
89 double singlePartitionProbability, boolean isRecombination) {
90 super(mode);
91 this.arg = arg;
92 setWeight(weight);
93 // this.maxTips = maxTips;
94 this.size = size;
95 this.gaussian = gaussian;
96 // this.swapRates = swapRates;
97 // this.swapTraits = swapTraits;
98 this.internalNodeParameters = param1;
99 this.internalAndRootNodeParameters = param2;
100 this.nodeRates = param3;
101 this.singlePartitionProbability = singlePartitionProbability;
102 this.isRecombination = isRecombination;
103
104 // this.mode = mode;
105 }
106
107
108 /**
109 * Do a add/remove reassortment node operation
110 *
111 * @return the log-transformed hastings ratio
112 */
113 public double doOperation() {
114 // System.err.println("Starting AddRemove Operation");
115
116 double logq = 0;
117 try {
118 if (MathUtils.nextDouble() < 0.5)
119 logq = AddOperation();
120 else
121 logq = RemoveOperation();
122 } catch (ARGOperatorFailedException ofe) {
123 if (ofe.getMessage().compareTo("No reassortment nodes to remove.") != 0) {
124 System.err.println("Catch: " + ofe.getMessage());
125 // System.exit(-1);
126 }
127 }
128 if (arg.isBifurcationDoublyLinked(arg.getRoot()))
129 throw new RuntimeException("trouble with double-rooted root");
130 return logq;
131 }
132
133 /*
134 private ArrayList<NodeRef> getPotentialSubtreesToMerge() {
135 ArrayList<NodeRef> potentials = new ArrayList<NodeRef>();
136 int n = arg.getNodeCount();
137 for(int i=0; i<n; i++) {
138 Node node = (Node)arg.getNode(i);
139 if( node.dupSister != null ) {
140 potentials.add(node);
141 }
142 }
143 return potentials;
144 }
145
146 private int countPotentialSubtreesToMerge() {
147 int count = 0;
148 //ArrayList<NodeRef> potentials = new ArrayList<NodeRef>();
149 int n = arg.getNodeCount();
150 for(int i=0; i<n; i++) {
151 Node node = (Node)arg.getNode(i);
152 if( node.dupSister != null ) {
153 //potentials.add(node);
154 count++;
155 }
156 }
157 //return potentials;
158 return count;
159 }
160 */
161
162 /*
163 * Generates a list of all branches in the ARG, there each branch leads up the ARG from the saved nodes
164 *
165 * Should return a deterministic function of # bifurcations and # reassortments
166 *
167 */
168
169 private int findPotentialReassortmentNodes(ArrayList<NodeRef> list) {
170 int count = 0;
171 int n = arg.getNodeCount();
172 for (int i = 0; i < n; i++) {
173 Node node = (Node) arg.getNode(i);
174 if (node.leftParent != null) { // rules out only the root; may subclass for different types of problems
175 list.add(node);
176 count++;
177 if (node.isReassortment()) {
178 list.add(node);
179 count++; // reassortment nodes have two parent branches
180 }
181 }
182 }
183 // int check = arg.getNodeCount() + arg.getReassortmentNodeCount() - 1;
184 // if( check != count ) {
185 // System.err.println("What the fuck?");
186 // System.exit(-1);
187 // }
188 return count;
189 }
190
191 private int findCurrentReassortmentNodes(ArrayList<NodeRef> list) {
192 int count = 0;
193 int n = arg.getNodeCount();
194 Node root = (Node) arg.getRoot();
195 for (int i = 0; i < n; i++) {
196 Node node = (Node) arg.getNode(i);
197 if (node.isReassortment() && (node.leftParent != root && node.rightParent != root)) {
198 if (list != null)
199 list.add(node);
200 count++;
201 }
202 }
203 return count;
204 }
205
206 /*private double RemoveOperation() throws OperatorFailedException {
207 arg.beginTreeEdit();
208 if (arg.getReassortmentNodeCount() > 0)
209 arg.removeNullCounter();
210 try {
211 arg.endTreeEdit();
212 } catch (MutableTree.InvalidTreeException ite) {
213 throw new RuntimeException(ite.toString() + "\n" + arg.toString()
214 + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot()));
215 }
216 arg.pushTreeSizeChangedEvent();
217 return 0;
218 }*/
219
220 /* private double AddOperation() throws OperatorFailedException {
221 arg.beginTreeEdit();
222 arg.addNullCounter();
223 try {
224 arg.endTreeEdit();
225 } catch (MutableTree.InvalidTreeException ite) {
226 throw new RuntimeException(ite.toString() + "\n" + arg.toString()
227 + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot()));
228 }
229 arg.pushTreeSizeChangedEvent();
230 return 0;
231 }
232 */
233
234 private double RemoveOperation() throws ARGOperatorFailedException {
235 double logq = 0;
236
237 // System.err.println("Starting remove ARG operation.");
238
239 // 1. Draw reassortment node uniform randomly
240
241 ArrayList<NodeRef> potentialNodes = new ArrayList<NodeRef>();
242
243 int totalPotentials = findCurrentReassortmentNodes(potentialNodes);
244 if (totalPotentials == 0)
245 throw new ARGOperatorFailedException("No reassortment nodes to remove.");
246 Node recNode = (Node) potentialNodes.get(MathUtils.nextInt(totalPotentials));
247 logq += Math.log(totalPotentials);
248
249 double reverseReassortmentSpan = 0;
250 double reverseBifurcationSpan = 0;
251
252 arg.beginTreeEdit();
253 boolean doneSomething = false;
254 Node recParent = recNode.leftParent;
255 Node recChild = recNode.leftChild;
256 if (recNode.leftParent == recNode.rightParent) { // Doubly linked.
257 Node recGrandParent = recParent.leftParent;
258
259 reverseReassortmentSpan = arg.getNodeHeight(recParent) - arg.getNodeHeight(recChild);
260 reverseBifurcationSpan = arg.getNodeHeight(recGrandParent) - arg.getNodeHeight(recChild);
261 if (arg.isRoot(recParent)) { // This case should never happen as double links
262 arg.setRoot(recChild); // to root can not be added or removed.
263 } else {
264 //Node recGrandParent = recParent1.leftParent; // And currently recParent must be a bifurcatio
265 // System.err.println("recGrand ="+recGrandParent.number);
266 arg.doubleRemoveChild(recGrandParent, recParent);
267 arg.doubleRemoveChild(recNode, recChild);
268 if (recGrandParent.bifurcation)
269 arg.singleAddChild(recGrandParent, recChild);
270 else
271 arg.doubleAddChild(recGrandParent, recChild);
272 }
273 doneSomething = true;
274 // There are not left/right choices to be made for doubly linked removals.
275 // End doubly linked.
276 } else { // Two different parents.
277 Node recParent1 = recNode.leftParent;
278 Node recParent2 = recNode.rightParent;
279 if ((!recParent1.bifurcation && !recParent2.bifurcation) ||
280 (!recParent1.bifurcation && recParent2.isRoot()) ||
281 (!recParent2.bifurcation && recParent1.isRoot())) {
282
283 arg.endTreeEdit();
284
285 // try {
286 // arg.checkTreeIsValid();
287 // } catch (MutableTree.InvalidTreeException ite) {
288 // throw new RuntimeException(ite.toString() + "\n" + arg.toString()
289 // + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot()));
290 // }
291 throw new ARGOperatorFailedException("Not reversible deletion.");
292 }
293 if (!recParent1.bifurcation || recParent1.isRoot()) { // One orientation is valid
294 recParent1 = recNode.rightParent;
295 recParent2 = recNode.leftParent;
296 } else if (recParent2.bifurcation && !recParent2.isRoot()) { // Both orientations are valid
297 if (MathUtils.nextDouble() < 0.5) { // choose equally likely
298 recParent1 = recNode.rightParent;
299 recParent2 = recNode.leftParent;
300 }
301 logq += Math.log(2);
302 }
303 // System.err.println("recNode ="+recNode.number);
304 // System.err.println("recParent1 ="+recParent1.number);
305 // System.err.println("recParent2 ="+recParent2.number);
306
307 Node recGrandParent = recParent1.leftParent; // And currently recParent must be a bifurcatio
308 // System.err.println("recGrand ="+recGrandParent.number);
309 //Node recChild = recNode.leftChild;
310 Node otherChild = recParent1.leftChild;
311 if (otherChild == recNode)
312 otherChild = recParent1.rightChild;
313 // System.err.println("recChild ="+recChild.number);
314 // System.err.println("otherChild ="+otherChild.number);
315 reverseReassortmentSpan = Math.min(arg.getNodeHeight(recParent1), arg.getNodeHeight(recParent2))
316 - arg.getNodeHeight(recChild);
317 reverseBifurcationSpan = arg.getNodeHeight(recGrandParent)
318 - Math.max(arg.getNodeHeight(recChild), arg.getNodeHeight(otherChild));
319 if (recGrandParent.bifurcation)
320 arg.singleRemoveChild(recGrandParent, recParent1);
321 else
322 arg.doubleRemoveChild(recGrandParent, recParent1);
323
324 arg.singleRemoveChild(recParent1, otherChild);
325 if (recParent2.bifurcation)
326 arg.singleRemoveChild(recParent2, recNode);
327 else
328 arg.doubleRemoveChild(recParent2, recNode);
329 arg.doubleRemoveChild(recNode, recChild);
330 if (otherChild != recChild) {
331 if (recGrandParent.bifurcation)
332 arg.singleAddChild(recGrandParent, otherChild);
333 else
334 arg.doubleAddChild(recGrandParent, otherChild);
335 if (recParent2.bifurcation)
336 arg.singleAddChild(recParent2, recChild);
337 else
338 arg.doubleAddChild(recParent2, recChild);
339 } else {
340 if (recGrandParent.bifurcation)
341 arg.singleAddChildWithOneParent(recGrandParent, otherChild);
342 else
343 arg.doubleAddChildWithOneParent(recGrandParent, otherChild);
344 if (recParent2.bifurcation)
345 arg.singleAddChildWithOneParent(recParent2, recChild);
346 else
347 arg.doubleAddChildWithOneParent(recParent2, recChild);
348 }
349 // System.err.println("Sanity check in Remove Operator");
350 // sanityCheck();
351 // System.err.println("End Remove Operator in sanity check");
352 doneSomething = true;
353 // Check for node height troubles
354
355 if ((recChild.getHeight() > recParent2.getHeight()) ||
356 (otherChild.getHeight() > recGrandParent.getHeight())) {
357 arg.endTreeEdit();
358 throw new RuntimeException("How did I get here?");
359 }
360 recParent = recParent1;
361 }
362 if (doneSomething) {
363 // System.err.println("Trying to remove "+recNode.number+" and "+recParent.number);
364 //
365 arg.contractARGWithRecombinant(recParent, recNode,
366 internalNodeParameters, internalAndRootNodeParameters, nodeRates);
367 }
368 // System.err.println("End ARG\n"+arg.toGraphString());
369
370
371 arg.pushTreeSizeChangedEvent();
372 arg.endTreeEdit();
373 // try {
374 // arg.checkTreeIsValid();
375 // } catch (MutableTree.InvalidTreeException ite) {
376 // throw new RuntimeException(ite.toString() + "\n" + arg.toString()
377 // + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot()));
378 // }
379
380 // System.err.println("Checking remove validity.");
381
382 // todo -- check all ARGTree.Roots
383 // if (!arg.validRoot())
384 // throw new OperatorFailedException("Roots are invalid");
385
386 // logq -= Math.log(reverseBifurcationSpan) + Math.log(reverseReassortmentSpan); // TODO removed? because of prior ratio
387 logq -= Math.log(arg.getNodeCount() + arg.getReassortmentNodeCount() - 1); // findPotentialRessortmentNodes()
388 logq -= Math.log(this.findPotentialAttachmentSisters(recChild,
389 arg.getNodeHeight(recChild), null));
390 // System.err.println(drawRandomPartitioning(null));
391 // logq -= drawRandomPartitioning(null);
392
393 // System.err.println("End remove ARG operation.");
394
395
396 int nodes = arg.getInternalNodeCount() - 1;
397 logq += lnGamma(nodes) - lnGamma(nodes + 2); // TODO move into prior
398
399 logq += 3 * Math.log(2);
400
401 logq = 0;
402
403 return logq; // 1 / total potentials * 1 / 2 (if valid) * length1 * length2 * attachmentSisters
404 }
405
406 private static double lnGamma(double x) {
407 if (x == 1 || x == 2)
408 return 0.0;
409 return GammaFunction.logGamma(x);
410 }
411
412 private void checkAllHeights() {
413 int len = arg.getInternalNodeCount();
414 System.err.println("# internal nodes = " + len);
415 int n = internalNodeParameters.getParameterCount();
416 System.err.println("VSCP (" + n + ")");
417 for (int i = 0; i < n; i++) {
418 System.err.println(internalNodeParameters.getParameterValue(i));
419 }
420 n = arg.getInternalNodeCount();
421 System.err.println("Checking all internal nodes (" + n + ") via tree:");
422 for (int i = 0; i < n; i++) {
423 NodeRef node = arg.getInternalNode(i);
424 System.err.print(TreeUtils.uniqueNewick(arg, node) + " ");
425 System.err.println(((Node) node).getHeight());
426 }
427 }
428
429 /*private void checkAllPartitionLabels() {
430 int len = arg.getExternalNodeCount();
431 System.err.println("Tip Partitions:");
432 for(int i=0; i<len; i++) {
433 Node node = (Node)arg.getExternalNode(i);
434 BitSet partSet = node.partitionSet;
435 System.err.print(Tree.Utils.uniqueNewick(arg, node)+":");
436 for(int j=partSet.nextSetBit(0); j>=0; j=partSet.nextSetBit(j+1)) {
437 System.err.print(" "+j);
438 }
439 System.err.println();
440 }
441 }*/
442
443 /* private ArrayList<NodeRef> getPotentialTipsToMerge() {
444 ArrayList<NodeRef> potentials = new ArrayList<NodeRef>();
445 int len = arg.getExternalNodeCount();
446 for(int i=0; i<len; i++){
447 NodeRef nr = arg.getExternalNode(i);
448 BitSet pS = ((Node)nr).partitionSet;
449 if( pS.cardinality() == 1)
450 potentials.add(nr);
451 }
452 return potentials;
453 }
454
455 private ArrayList<Node> getSameTaxonTips(Node asMe) {
456 ArrayList<Node> potentials = new ArrayList<Node>();
457 int len = arg.getExternalNodeCount();
458 Taxon same = asMe.taxon;
459 for(int i=0; i<len; i++){
460 Node n = (Node)arg.getExternalNode(i);
461 if( (n != asMe) && (n.taxon == same) )
462 potentials.add(n);
463 }
464 return potentials;
465 }
466
467 private ArrayList<NodeRef> getPotentialTipsToSplit() {
468 ArrayList<NodeRef> potentials = new ArrayList<NodeRef>();
469 int len = arg.getExternalNodeCount();
470 for(int i=0; i<len; i++) {
471 NodeRef nr = arg.getExternalNode(i);
472 BitSet pS = ((Node)nr).partitionSet;
473 if( pS.cardinality() > 1 ) // can be split
474 potentials.add(nr);
475 }
476 return potentials;
477 }*/
478
479 /*;private int drawOnePartition(BitSet partitionSet) {
480 int draw = MathUtils.nextInt(partitionSet.cardinality());
481 // System.err.println("draw = "+draw);
482 int result = partitionSet.nextSetBit(0);
483 for (int i = 0; i < draw; i++)
484 result = partitionSet.nextSetBit(result + 1);
485 return result;
486 }*/
487
488 // private BitSet bsTransportor = null;
489 /*
490 private ArrayList<NodeRef> getPotentialSubtreesToSplit() {
491 ArrayList<NodeRef> potentials = new ArrayList<NodeRef>();
492 // Start with all possible nodes except the root
493 BitSet bsTmp = null;
494 int len = arg.getNodeCount();
495 for(int i=0; i<len; i++) {
496 NodeRef nr = arg.getNode(i);
497 if( ! arg.isRoot(nr) ) {
498 // All tips of nr must have at least two partitions
499 ArrayList<NodeRef> allTips = arg.getDescendantTipNodes(nr);
500 int n = allTips.size();
501 boolean valid = true;
502 for(int j=0; valid && j<n; j++) {
503 BitSet pS = ((Node)allTips.get(j)).partitionSet;
504 if( j == 0 ) {
505 bsTmp = (BitSet)pS.clone();
506 }
507 else
508 bsTmp.and(pS);
509 if( pS.cardinality() == 1 ) // can be split
510 valid = false;
511 }
512 if( valid && (bsTmp.cardinality()>1) )
513 potentials.add(nr);
514 }
515 }
516 bsTransportor = bsTmp;
517 return potentials;
518 }
519 */
520 /* private int countPotentialSubtreesToSplit() {
521 // ArrayList<NodeRef> potentials = new ArrayList<NodeRef>();
522 int count = 0;
523 // Start with all possible nodes except the root
524 BitSet bsTmp = null;
525 int len = arg.getNodeCount();
526 for(int i=0; i<len; i++) {
527 NodeRef nr = arg.getNode(i);
528 if( ! arg.isRoot(nr) ) {
529 // All tips of nr must have at least two partitions
530 ArrayList<NodeRef> allTips = arg.getDescendantTipNodes(nr);
531 int n = allTips.size();
532 boolean valid = true;
533 for(int j=0; valid && j<n; j++) {
534 BitSet pS = ((Node)allTips.get(j)).partitionSet;
535 if( j == 0 ) {
536 bsTmp = (BitSet)pS.clone();
537 }
538 else
539 bsTmp.and(pS);
540 if( pS.cardinality() == 1 ) // can be split
541 valid = false;
542 }
543 if( valid && (bsTmp.cardinality()>1) )
544 //potentials.add(nr);
545 count++;
546 }
547 }
548 bsTransportor = bsTmp;
549 //return potentials;
550 return count;
551 }*/
552
553 // private ArrayList<NodeRef> getPotentialReattachments(double min) {
554 // ArrayList<NodeRef> potentials = new ArrayList<NodeRef>();
555 // int len = arg.getNodeCount();
556 // for(int i=0; i<len; i++) {
557 // NodeRef nr = arg.getNode(i);
558 // if( !arg.isRoot(nr) && (arg.getMinParentNodeHeight(nr) > min) ) {
559 // // Do not reroot and reattach only above current height
560 //
561 // potentials.add(nr);
562 // }
563 // }
564 // return potentials;
565 // }
566
567 private int findPotentialAttachmentSisters(NodeRef rec, double min, ArrayList<NodeRef> list) {
568 int count = 0;
569 int len = arg.getNodeCount();
570 for (int i = 0; i < len; i++) {
571 Node nr = (Node) arg.getNode(i);
572 if (!nr.isRoot()) {
573 if (arg.getNodeHeight(nr.leftParent) > min) {
574 // can add node somewhere between min and nr.parent
575 if (list != null)
576 list.add(nr);
577 count++;
578 }
579 if (nr.isReassortment() && arg.getNodeHeight(nr.rightParent) > min) {
580 if (list != null)
581 list.add(nr);
582 count++;
583 }
584 }
585 }
586 return count;
587 }
588
589 private double drawRandomPartitioning(Parameter partitioning) {
590 double logq = 0;
591 int len = arg.getNumberOfPartitions();
592 if (len == 2) {
593 boolean first = MathUtils.nextBoolean();
594 if (partitioning != null) {
595 if (first)
596 partitioning.setParameterValueQuietly(0, 1.0);
597 else
598 partitioning.setParameterValueQuietly(1, 1.0);
599 }
600 return Math.log(2);
601 }
602 if (isRecombination) {
603 logq += drawRandomRecombination(partitioning);
604 } else {
605 logq += drawRandomReassortment(partitioning);
606 }
607 return logq;
608 }
609
610
611 private double drawRandomReassortment(Parameter partitioning) {
612 int len = arg.getNumberOfPartitions();
613 double logq = 0;
614 if (MathUtils.nextDouble() < singlePartitionProbability) {
615 if (partitioning != null)
616 partitioning.setParameterValueQuietly(MathUtils.nextInt(len), 1.0);
617 return Math.log(len);
618 }
619 int[] permutation = MathUtils.permuted(len);
620 int cut = MathUtils.nextInt(len - 1);
621 for (int i = 0; i < len; i++) {
622 logq += Math.log(i + 1);
623 if (i > cut && partitioning != null)
624 partitioning.setParameterValueQuietly(permutation[i], 1.0);
625 }
626 logq += Math.log(len - 1);
627 return logq;
628 }
629
630 private double drawRandomRecombination(Parameter partitioning) {
631 int len = arg.getNumberOfPartitions();
632 double logq = 0;
633 double leftValue = MathUtils.nextInt(2);
634 double rightValue = 1.0 - leftValue;
635 logq += Math.log(2);
636 if (partitioning != null) {
637 int cut = MathUtils.nextInt(len - 1);
638 for (int i = 0; i <= cut; i++)
639 partitioning.setParameterValueQuietly(i, leftValue);
640 for (int i = cut + 1; i < len; i++)
641 partitioning.setParameterValueQuietly(i, rightValue);
642 }
643 logq += Math.log(len - 1);
644 return logq;
645 }
646
647
648 private double AddOperation() throws ARGOperatorFailedException {
649 double logq = 0;
650
651 // System.err.println("Starting add ARG operation. ... "+arg.getReassortmentNodeCount());
652 // Draw potential places to add a reassortment node
653
654 ArrayList<NodeRef> potentialNodes = new ArrayList<NodeRef>();
655 int totalPotentials = findPotentialReassortmentNodes(potentialNodes);
656 if (totalPotentials == 0) {
657 System.err.println("Should never get here AA");
658 System.exit(-1);
659 throw new ARGOperatorFailedException("No more nodes to recombine.");
660 }
661 Node recNode = (Node) potentialNodes.get(MathUtils
662 .nextInt(totalPotentials));
663 Node recParentL = recNode.leftParent;
664 Node recParentR = recNode.rightParent;
665 Node recParent = recParentL;
666 if ((recParentL != recParentR) && MathUtils.nextDouble() > 0.5)
667 recParent = recParentR;
668
669 logq += Math.log(totalPotentials);
670
671 double minHeight = arg.getNodeHeight(recNode); // Attachment must occur
672 // previous to this time
673
674 ArrayList<NodeRef> attachments = new ArrayList<NodeRef>();
675 int totalAttachments = findPotentialAttachmentSisters(recNode,
676 minHeight, attachments);
677 if (totalAttachments == 0) {
678 // System.err.println("Should never get here AB");
679 // System.exit(-1);
680
681 throw new ARGOperatorFailedException("no more attachment points for this recomb");
682 }
683 Node sisNode = (Node) attachments.get(MathUtils
684 .nextInt(totalAttachments));
685 Node sisParentL = sisNode.leftParent;
686 Node sisParentR = sisNode.rightParent;
687 Node sisParent = sisParentL;
688 if (sisParentL != sisParentR) {
689 if (arg.getNodeHeight(sisParentL) <= minHeight)
690 sisParent = sisParentR;
691 else if (arg.getNodeHeight(sisParentR) > minHeight
692 && MathUtils.nextDouble() > 0.5)
693 sisParent = sisParentR;
694 }
695
696 logq += Math.log(totalAttachments);
697
698 Node newBifurcation = arg.new Node();
699 Node newReassortment = arg.new Node();
700 newReassortment.bifurcation = false;
701 double sisHeight = sisNode.getHeight();
702 if (sisHeight < minHeight) {
703 sisHeight = minHeight;
704 }
705 double spHeight = arg.getNodeHeight(sisParent);
706 double totalLength = spHeight - sisHeight;
707
708 double newLength = sisHeight + MathUtils.nextDouble() * totalLength;
709
710 logq -= Math.log(totalLength); // prior ratio
711
712 newBifurcation.heightParameter = new Parameter.Default(newLength);
713 newBifurcation.setupHeightBounds();
714
715 logq += Math.log(totalLength); // Uniform[spHeight, sisHeight]
716
717 double topHeight = newLength;
718 double recParentHeight = arg.getNodeHeight(recParent);
719 if (topHeight > recParentHeight)
720 topHeight = recParentHeight;
721 double recHeight = arg.getNodeHeight(recNode);
722 totalLength = topHeight - recHeight;
723 newLength = recHeight + MathUtils.nextDouble() * totalLength;
724
725 logq -= Math.log(totalLength); // prior ratio
726
727 newReassortment.heightParameter = new Parameter.Default(newLength);
728 newReassortment.setupHeightBounds();
729 logq += Math.log(totalLength); // Uniform[bifurcationHeight,recNodeHeight]
730
731 arg.beginTreeEdit();
732 if (sisParent.bifurcation)
733 arg.singleRemoveChild(sisParent, sisNode);
734 else
735 arg.doubleRemoveChild(sisParent, sisNode);
736 if (sisNode != recNode) {
737 if (recParent.bifurcation)
738 arg.singleRemoveChild(recParent, recNode);
739 else
740 arg.doubleRemoveChild(recParent, recNode);
741 }
742 if (sisParent.bifurcation)
743 arg.singleAddChild(sisParent, newBifurcation);
744 else
745 arg.doubleAddChild(sisParent, newBifurcation);
746 if (sisNode != recNode)
747 arg.singleAddChild(newBifurcation, sisNode);
748 arg.doubleAddChild(newReassortment, recNode);
749
750 /* BitSet bitLeft = new BitSet();
751 BitSet bitRight = new BitSet();
752 if (MathUtils.nextDouble() < 0.5) {
753 bitLeft.set(0);
754 bitRight.set(1);
755 } else {
756 bitLeft.set(1);
757 bitRight.set(0);
758 }
759 logq += Math.log(2.0);*/
760 Parameter partitioning = new Parameter.Default(arg.getNumberOfPartitions());
761
762 // logq += drawRandomPartitioning(partitioning); // TODO add back in
763
764 /* System.err.print("p: ");
765 double[] v = partitioning.getParameterValues();
766 for (double d : v)
767 System.err.print(d+" ");
768 System.err.println("");*/
769
770
771 if (sisNode != recNode) {
772 arg.addChildAsRecombinant(newBifurcation, recParent,
773 newReassortment, partitioning);
774 } else {
775 arg.addChildAsRecombinant(newBifurcation, newBifurcation,
776 newReassortment, partitioning);
777 }
778
779 /* if (sisNode != recNode) {
780 arg.addChildAsRecombinant(newBifurcation, recParent,
781 newReassortment, bitLeft, bitRight);
782 } else {
783 arg.addChildAsRecombinant(newBifurcation, newBifurcation,
784 newReassortment, bitLeft, bitRight);
785 }*/
786 arg.expandARGWithRecombinant(newBifurcation, newReassortment,
787 internalNodeParameters,
788 internalAndRootNodeParameters,
789 nodeRates);
790 // arg.addNewHeightParameter(newReassortment.heightParameter,internalNodeParameters);
791 // arg.expandNodesWithRecombinant(arg.getRoot(), recNR);
792 // arg.expandNodesWithSubtree(arg.getRoot(), newSubtree);
793 // arg.reconstructTrees();
794 //
795 // System.err.println("End ARG\n" + arg.toGraphString()); System.err.println("recNode = " + recNode.number);
796 // System.err.println("recParent = " + recParent.number);
797 // System.err.println("sisNode = " + sisNode.number);
798 // System.err.println("sisParent = " + sisParent.number);
799 //System.exit(-1);
800 // ARGTree tree = new ARGTree(arg);
801 // System.err.println("Reassortment nodes =
802 // "+arg.getReassortmentNodeCount());
803 // //System.exit(-1);
804 // //System.err.println("ARGTree = "+Tree.Utils.uniqueNewick(tree,
805 // tree.getRoot()));
806 // tree = new ARGTree(arg, 0);
807 // System.err.println("Part 0 = " + tree.toString());
808 // tree = new ARGTree(arg, 1);
809 // System.err.println("Part 1 = " + tree.toString());
810 // //if( recNode == sisNode)
811 //System.exit(-1);
812 // System.err.println("Sanity check in Add Operation");
813 // sanityCheck();
814 // System.err.println("End Add Operator sanity check");
815
816 arg.pushTreeSizeChangedEvent();
817
818 arg.endTreeEdit();
819
820 // try {
821 // arg.checkTreeIsValid();
822 // } catch (MutableTree.InvalidTreeException ite) {
823 // throw new RuntimeException(ite.toString() + "\n" + arg.toString()
824 // + "\n" + Tree.Utils.uniqueNewick(arg, arg.getRoot()));
825 // }
826
827 // System.err.println("Checking add validity.");
828 // todo -- check all ARGTree.Roots
829 // if (!arg.validRoot())
830 // throw new OperatorFailedException("Roots are invalid");
831
832 // System.err.println("Made it thru once!");
833
834 // System.exit(-1);
835 // times++;
836 // System.err.println("Adds = "+times);
837 // if( times >= 4 )
838 // throw new OperatorFailedException("Do many tries!");
839 // System.err.println("Add a recomb node.");
840 // int cnt = arg.getReassortmentNodeCount();
841 // if (cnt > 20)
842 // throw new OperatorFailedException("No more than X reassortments");
843
844 logq -= Math.log(findCurrentReassortmentNodes(null));
845 if (!(recNode.leftParent.isBifurcation() && recNode.rightParent.isRoot()) &&
846 !(recNode.rightParent.isBifurcation() && recNode.leftParent.isRoot()))
847 logq -= Math.log(2.0);
848
849 // System.err.println("End add ARG operation.");
850
851 int nodes = arg.getInternalNodeCount() - 1;
852 logq += lnGamma(nodes) - lnGamma(nodes - 2); // TODO move into prior
853
854 logq = 0;
855 return logq;
856 }
857
858 // if( !recParent1.bifurcation || recParent1.isRoot() ) { // One orientation is valid
859
860
861 public void sanityCheck() {
862 int len = arg.getNodeCount();
863 for (int i = 0; i < len; i++) {
864 Node node = (Node) arg.getNode(i);
865 if (node.bifurcation) {
866 boolean equalChild = (node.leftChild == node.rightChild);
867 if ((equalChild && node.leftChild != null)) {
868 if (!node.leftChild.bifurcation && ((node.leftChild).leftParent == node))
869 ;
870 else {
871 System.err.println("Node " + (i + 1) + " is insane.");
872 System.err.println(arg.toGraphString());
873 System.exit(-1);
874 }
875 }
876 } else {
877 if ((node.leftChild != node.rightChild)) {
878 System.err.println("Node " + (i + 1) + " is insane.");
879 System.err.println(arg.toGraphString());
880 System.exit(-1);
881 }
882 }
883 if (!node.isRoot()) {
884 double d;
885 d = node.getHeight();
886 }
887 }
888 }
889
890 private int times = 0;
891
892 private double getDelta() {
893 if (!gaussian) {
894 return (MathUtils.nextDouble() * size) - (size / 2.0);
895 } else {
896 return MathUtils.nextGaussian() * size;
897 }
898 }
899
900 private int intersectingEdges(Tree tree, NodeRef node, double height, ArrayList directChildren) {
901
902 NodeRef parent = arg.getParent(node);
903
904 if (arg.getNodeHeight(parent) < height) return 0;
905
906 if (arg.getNodeHeight(node) < height) {
907 if (directChildren != null) directChildren.add(node);
908 return 1;
909 }
910
911 int count = 0;
912 for (int i = 0; i < arg.getChildCount(node); i++) {
913 count += intersectingEdges(tree, arg.getChild(node, i), height, directChildren);
914 }
915 return count;
916 }
917
918 /**
919 * @return the other child of the given parent.
920 */
921 private NodeRef getOtherChild(Tree tree, NodeRef parent, NodeRef child) {
922
923 if (arg.getChild(parent, 0) == child) {
924 return arg.getChild(parent, 1);
925 } else {
926 return arg.getChild(parent, 0);
927 }
928 }
929
930 public double getSize() {
931 return size;
932 }
933
934 public void setSize(double size) {
935 this.size = size;
936 }
937
938 public double getAdaptableParameter() {
939 return Math.log(getSize());
940 }
941
942 public void setAdaptableParameter(double value) {
943 setSize(Math.exp(value));
944 }
945
946 public double getRawParameter() {
947 return getSize();
948 }
949
950 public String getAdaptableParameterName() {
951 return "size";
952 }
953
954 public String getOperatorName() {
955 return SUBTREE_SLIDE;
956 }
957
958 public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
959
960 public String getParserName() {
961 return SUBTREE_SLIDE;
962 }
963
964 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
965
966 boolean swapRates = false;
967 boolean swapTraits = false;
968
969 double singlePartitionProbability = 0.0;
970 boolean isRecombination = false;
971
972 // int mode = AdaptableMCMCOperator.DEFAULT;
973 // if (xo.hasAttribute(AUTO_OPTIMIZE)) {
974 // if (xo.getBooleanAttribute(AUTO_OPTIMIZE)) {
975 // mode = AdaptableMCMCOperator.ADAPTATION_ON;
976 // } else {
977 // mode = AdaptableMCMCOperator.ADAPTATION_OFF;
978 // }
979 // }
980
981 AdaptationMode mode = AdaptationMode.parseMode(xo);
982
983 if (xo.hasAttribute(SINGLE_PARTITION)) {
984 singlePartitionProbability = xo.getDoubleAttribute(SINGLE_PARTITION);
985 }
986
987 if (xo.hasAttribute(IS_RECOMBINATION)) {
988 isRecombination = xo.getBooleanAttribute(IS_RECOMBINATION);
989
990 }
991
992 if (xo.hasAttribute(SWAP_RATES)) {
993 swapRates = xo.getBooleanAttribute(SWAP_RATES);
994 }
995 if (xo.hasAttribute(SWAP_TRAITS)) {
996 swapTraits = xo.getBooleanAttribute(SWAP_TRAITS);
997 }
998 Object obj = xo.getChild(ARGModel.class);
999 //TreeModel tmp = (TreeModel)xo.getChild(TreeModel.class);
1000 ARGModel treeModel = null;
1001 //if( (tmp.TREE_MODEL).compareTo(VariableSizeTreeModel.TREE_MODEL) == 0) {
1002 if (obj instanceof ARGModel) {
1003 //System.err.println("Found VSTM");
1004 treeModel = (ARGModel) obj;
1005 } else {
1006 System.err.println("Must specify a variable size tree model to use the AddRemoveSubtreeOperators");
1007 System.exit(-1);
1008 }
1009
1010 // bug, getChild(String) returns an xmlObject; not in XML rules
1011 CompoundParameter parameter1 = null; //(CompoundParameter) xo.getChild(JUST_INTERNAL);
1012 CompoundParameter parameter2 = null; //CompoundParameter) xo.getChild(INTERNAL_AND_ROOT);
1013 CompoundParameter parameter3 = null; //(CompoundParameter) xo.getChild(NODE_RATES);
1014
1015 int weight = xo.getIntegerAttribute("weight");
1016 // int maxTips = xo.getIntegerAttribute(MAX_VALUE);
1017 double size = xo.getDoubleAttribute("size");
1018 boolean gaussian = xo.getBooleanAttribute("gaussian");
1019 return new ObsoleteARGAddRemoveEventOperator(treeModel, weight, size, gaussian, swapRates, swapTraits,
1020 mode, parameter1, parameter2, parameter3, singlePartitionProbability, isRecombination);
1021 }
1022
1023 public String getParserDescription() {
1024 return "An operator that slides a subarg.";
1025 }
1026
1027 public Class getReturnType() {
1028 return ObsoleteARGAddRemoveEventOperator.class;
1029 }
1030
1031 public XMLSyntaxRule[] getSyntaxRules() {
1032 return rules;
1033 }
1034
1035 private final XMLSyntaxRule[] rules = {
1036 AttributeRule.newIntegerRule("weight"),
1037 // AttributeRule.newIntegerRule(MAX_VALUE),
1038 AttributeRule.newDoubleRule("size"),
1039 AttributeRule.newBooleanRule("gaussian"),
1040 AttributeRule.newBooleanRule(SWAP_RATES, true),
1041 AttributeRule.newBooleanRule(SWAP_TRAITS, true),
1042 AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
1043 new ElementRule(ARGModel.class)//,
1044 // new ElementRule(Parameter.class)
1045 };
1046 };
1047
1048 }