Debian Codegraph @

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

raw symbols SCIP
1 /*
2 * ARGSubtreeSlideOperator.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 * RGSubtreeSlideOperator.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.MutableTree;
37 import dr.evolution.tree.NodeRef;
38 import dr.evolution.tree.Tree;
39 import dr.evomodel.arg.ARGModel;
40 import dr.evomodel.arg.ARGModel.Node;
41 import dr.evomodel.operators.SubtreeSlideOperator;
42 import dr.inference.operators.*;
43 import dr.math.MathUtils;
44 import dr.xml.*;
45
46 import java.util.ArrayList;
47
48 /**
49 * Implements the subtree slide move.
50 *
51 * @author Alexei Drummond
52 * @version $Id: ARGSubtreeSlideOperator.java,v 1.1.2.2 2006/11/06 01:38:30 msuchard Exp $
53 */
54 public class ARGSubtreeSlideOperator extends AbstractAdaptableOperator {
55 // SimpleMCMCOperator implements AdaptableMCMCOperator {
56
57 public static final String SUBTREE_SLIDE = "argSubtreeSlide";
58 // public static final String
59 public static final String SWAP_RATES = "swapRates";
60 public static final String SWAP_TRAITS = "swapTraits";
61 public static final String DIRICHLET_BRANCHES = "branchesAreScaledDirichlet";
62
63 private ARGModel tree = null;
64 private double size = 1.0;
65 private boolean gaussian = false;
66 private boolean swapRates;
67 private boolean swapTraits;
68 private boolean scaledDirichletBranches;
69 // private int mode = AdaptableMCMCOperator.DEFAULT;
70 // AdaptationMode model;
71
72 public ARGSubtreeSlideOperator(ARGModel tree, int weight, double size, boolean gaussian, boolean swapRates,
73 boolean swapTraits, boolean scaledDirichletBranches, AdaptationMode mode) {
74 super(mode);
75 this.tree = tree;
76 setWeight(weight);
77
78 this.size = size;
79 this.gaussian = gaussian;
80 this.swapRates = swapRates;
81 this.swapTraits = swapTraits;
82 this.scaledDirichletBranches = scaledDirichletBranches;
83
84 // this.mode = mode;
85 }
86
87 public void sanityCheck() {
88 int len = tree.getNodeCount();
89 for (int i = 0; i < len; i++) {
90 Node node = (Node) tree.getNode(i);
91 if (node.bifurcation) {
92 boolean equalChild = (node.leftChild == node.rightChild);
93 if ((equalChild && node.leftChild != null)) {
94 if (!node.leftChild.bifurcation && ((node.leftChild).leftParent == node))
95 ;
96 else {
97 System.err.println("Node " + (i + 1) + " is insane.");
98 System.err.println(tree.toGraphString());
99 System.exit(-1);
100 }
101 }
102 } else {
103 if ((node.leftChild != node.rightChild)) {
104 System.err.println("Node " + (i + 1) + " is insane.");
105 System.err.println(tree.toGraphString());
106 System.exit(-1);
107 }
108 }
109 }
110 }
111
112 /**
113 * Do a probablistic subtree slide move.
114 *
115 * @return the log-transformed hastings ratio
116 */
117 public double doOperation() {
118
119 // System.err.println("Starting Subtree Slide Operation.");
120 double logq = 0;
121
122 double oldTreeHeight = tree.getNodeHeight(tree.getRoot());
123
124 NodeRef i, newParent, newChild;
125
126 // 1. choose a random node avoiding root
127 ArrayList<NodeRef> potentialSubtrees = new ArrayList<NodeRef>();
128 int numPotentialSubtrees = this.getSlideableSubtrees(tree, potentialSubtrees);
129 // System.err.println("Slide:\n"+tree.toGraphString());
130 i = potentialSubtrees.get(MathUtils.nextInt(numPotentialSubtrees));
131
132 // logq = - Math.log(numPotentialSubtrees);
133
134 NodeRef iP = tree.getParent(i);
135
136 // TODO Start rewriting here.
137 NodeRef CiP = getOtherChild(tree, iP, i);
138 NodeRef PiP;
139 if (tree.isBifurcation(iP))
140 PiP = tree.getParent(iP);
141 else {
142 PiP = tree.getParent(iP, MathUtils.nextInt(2));
143 logq -= Math.log(2); // TODO check if really necessary.
144 }
145
146 // 2. choose a delta to move
147 double delta = getDelta();
148 double oldHeight = tree.getNodeHeight(iP);
149 double newHeight = oldHeight + delta;
150
151 //newHeight = tree.getNodeHeight(tree.getRoot()) + delta;
152
153 // 3. if the move is up
154 if (delta > 0) {
155
156 // 3.1 if the topology will change
157 if (PiP != null && tree.getNodeHeight(PiP) < newHeight) {
158
159 // find new parent
160 newParent = PiP;
161 newChild = iP;
162 while (tree.getNodeHeight(newParent) < newHeight) {
163 newChild = newParent;
164 if (tree.isBifurcation(newParent))
165 newParent = tree.getParent(newParent);
166 else {
167 newParent = tree.getParent(newParent, MathUtils.nextInt(2));
168 logq -= Math.log(2); // TODO check if correct.
169 }
170 if (newParent == null) break;
171 }
172
173 //System.err.println("No problem climbing");
174
175 // logq += Math.log(numPotentialSubtrees);
176
177 tree.beginTreeEdit();
178
179 // 3.1.1 if creating a new root
180 if (tree.isRoot(newChild)) {
181
182 if (true) {
183 tree.endTreeEdit();
184 try {
185 tree.checkTreeIsValid();
186 } catch (MutableTree.InvalidTreeException e) {
187 e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
188 }
189 throw new RuntimeException("Temporarily disable re-rooting");
190 }
191
192 //Parameter rootParameter = ((Node)newChild).heightParameter;
193 //Parameter otherParameter = ((Node)iP).heightParameter;
194 //tree.swapHeightParameters(newChild,iP);
195 tree.doubleRemoveChild(iP, CiP); // iP is always bifurcation
196 tree.doubleRemoveChild(PiP, iP); // PiP can be reassortment
197 tree.doubleAddChild(iP, newChild); // iP and newChild are always bifurcations, i still connected to iP
198 if (tree.isBifurcation(PiP))
199 tree.addChild(PiP, CiP);
200 else
201 tree.addChild(PiP, CiP);
202 tree.setRoot(iP);
203 //System.err.println("Creating new root!");
204 }
205 // 3.1.2 no new root
206 else {
207 boolean doubly = tree.isBifurcationDoublyLinked(newParent);
208
209 tree.doubleRemoveChild(iP, CiP); // iP bifurcation
210 tree.doubleRemoveChild(PiP, iP); // PiP can be reassortment
211 tree.doubleRemoveChild(newParent, newChild);
212 //tree.doubleAddChild(iP, newChild);
213
214 tree.doubleAddChild(PiP, CiP);
215 if (!doubly) {
216 tree.doubleAddChild(iP, newChild);
217 tree.doubleAddChild(newParent, iP);
218 } else {
219 tree.singleAddChild(newParent, iP);
220 tree.singleAddChildWithOneParent(iP, newChild);
221 tree.singleAddChild(newParent, newChild);
222 }
223 // System.err.println("No new root!");
224 }
225
226 // System.err.println("i ="+((Node)i).number);
227 // System.err.println("iP ="+((Node)iP).number);
228 // if( newParent != null )
229 // System.err.println("newParent ="+((Node)newParent).number+" "+tree.getNodeHeight(newParent));
230 // else
231 // System.err.println("newParent is above root");
232 // System.err.println("newChild ="+((Node)newChild).number+" "+tree.getNodeHeight(newChild));
233
234
235 tree.setNodeHeight(iP, newHeight);
236 // System.err.println("iP height ="+tree.getNodeHeight(iP));
237
238 // System.err.println("Intermediate slide up:\n"+tree.toGraphString());
239
240 tree.endTreeEdit();
241 try {
242 tree.checkTreeIsValid();
243 } catch (MutableTree.InvalidTreeException ite) {
244 throw new RuntimeException(ite.toString());
245 }
246
247 // 3.1.3 count the hypothetical sources of this destination.
248 int possibleSources = intersectingEdges(tree, newChild, iP, oldHeight, null);
249 // System.err.println("possible sources = " + possibleSources);
250
251 logq -= Math.log(possibleSources);
252 } else {
253 // 3.2
254 // just change the node height
255 tree.setNodeHeight(iP, newHeight);
256 logq = 0.0; // TODO check is losing -Log(2) is correct.
257 }
258
259 // System.err.println("Sanity check up-slide");
260 // sanityCheck();
261 }
262 // 4 if we are sliding the subtree down.
263 else {
264 // logq = 0;
265
266 // 4.0 is it a valid move?
267 if (tree.getNodeHeight(i) > newHeight) {
268 return Double.NEGATIVE_INFINITY;
269 }
270
271 // 4.1 will the move change the topology
272 if (tree.getNodeHeight(CiP) > newHeight) {
273 // System.err.println("Starting down-slide:\n"+tree.toGraphString());
274 ArrayList<NodeRef[]> newChildren = new ArrayList<NodeRef[]>();
275 int possibleDestinations = intersectingEdges(tree, CiP, iP, newHeight, newChildren);
276
277 // if no valid destinations then return a failure
278 if (newChildren.size() == 0) //{ return Double.NEGATIVE_INFINITY; }
279 throw new RuntimeException("no valid destinations");
280
281 // pick a random parent/child destination edge uniformly from options
282 int childIndex = MathUtils.nextInt(newChildren.size());
283 NodeRef[] draw = (NodeRef[]) newChildren.get(childIndex);
284 newChild = draw[1];
285 newParent = draw[0];
286 // ((NodeRef[])newChildren.get(childIndex))[1];
287 //int choice = MathUtils.nextInt(2);
288 NodeRef oops = null;
289 // if( tree.isBifurcation(newChild) )
290 // newParent = tree.getParent(newChild);
291 // else {
292 // //newParent = tree.getParent(newChild,MathUtils.nextInt(2));
293 // newParent = tree.getParent(newChild,choice);
294 // if( tree.getNodeHeight(newParent) < newHeight )
295 // newParent = tree.getParent(newChild,1-choice);
296 // oops = tree.getParent(newChild,1-choice);
297 // System.err.println("Grabbing random child.");
298 // logq -= Math.log(2); // TODO check ratio
299 // }
300 // //NodeRef oops
301 //newParent =
302
303 // logq += Math.log(possibleDestinations);
304
305 tree.beginTreeEdit();
306
307 // 4.1.1 if iP was root
308 if (tree.isRoot(iP)) {
309 // new root is CiP, but root cannot be a reassortment
310 if (!tree.isBifurcation(CiP))
311 throw new RuntimeException("root cannot be a reassortment");
312 boolean doubly = tree.isBifurcationDoublyLinked(newParent);
313 tree.doubleRemoveChild(iP, CiP);
314 tree.doubleRemoveChild(newParent, newChild);
315
316 // System.err.println("Down-slide disconnect:\n"+tree.toGraphString());
317 if (tree.isBifurcation(newChild))
318 tree.doubleAddChild(iP, newChild);
319 else
320 tree.singleAddChildWithOneParent(iP, newChild);
321 if (!doubly)
322 tree.doubleAddChild(newParent, iP);
323 else {
324 tree.singleAddChild(newParent, iP);
325 tree.singleAddChildWithOneParent(newParent, newChild);
326 }
327 //tree.doubleAddChild(newParent, iP);
328 //tree.swapHeightParameters(iP,CiP); // TODO
329 tree.setRoot(CiP);
330 // System.err.println("DOWN: Creating new root!"); // TODO still not tested
331 } else {
332 boolean doubly = tree.isBifurcationDoublyLinked(newParent); // or is it CiP = newParent?
333 tree.doubleRemoveChild(iP, CiP);
334 tree.doubleRemoveChild(PiP, iP);
335 tree.doubleRemoveChild(newParent, newChild);
336 // System.err.println("Down-slide disconnect:\n"+tree.toGraphString());
337 if (tree.isBifurcation(newChild))
338 tree.doubleAddChild(iP, newChild);
339 else
340 tree.singleAddChildWithOneParent(iP, newChild);
341 tree.doubleAddChild(PiP, CiP);
342 if (!doubly)
343 tree.doubleAddChild(newParent, iP); // Only works if iP is bifurcation
344 else {
345 tree.singleAddChild(newParent, iP);
346 tree.singleAddChildWithOneParent(newParent, newChild);
347 }
348 // System.err.println("DOWN: no new root!");
349 /* if( true ) {
350
351 try {
352 tree.endTreeEdit();
353 } catch(MutableTree.InvalidTreeException ite) {
354 throw new RuntimeException(ite.toString());
355 }
356 throw new OperatorFailedException("");
357 } */
358 }
359
360 tree.setNodeHeight(iP, newHeight);
361 // System.err.println("i = " + ((Node) i).number);
362 // System.err.println("iP = " + ((Node) iP).number);
363 // System.err.println("CiP = " + ((Node) CiP).number);
364 // System.err.println("newChild = " + ((Node) newChild).number + " "
365 // + tree.getNodeHeight(newChild));
366 // System.err.println("newParent = " + ((Node) newParent).number + " "
367 // + tree.getNodeHeight(newParent));
368 // if (oops != null)
369 // System.err.println("oops = " + ((Node) oops).number + " "
370 // + tree.getNodeHeight(oops));
371 // System.err.println("newHeight = " + newHeight);
372 // System.err.println("After slide down:\n"+tree.toGraphString());
373
374 tree.endTreeEdit();
375 try {
376 tree.checkTreeIsValid();
377 } catch (MutableTree.InvalidTreeException ite) {
378 throw new RuntimeException(ite.toString());
379 }
380
381 //logq = -Math.log((double) possibleDestinations);
382 logq += Math.log((double) possibleDestinations);
383
384
385 } else {
386 try {
387 tree.setNodeHeight(iP, newHeight);
388 } catch (Exception e) {
389 // System.err.println("iP =" + ((Node) iP).number);
390 // System.err.println("newHeight =" + newHeight);
391 //System.exit(-1);
392 }
393 logq = 0.0;
394 }
395 // System.err.println("After slide down:\n"+tree.toGraphString());
396 // System.err.println("Sanity check in down-slide.");
397 // sanityCheck();
398 }
399 /*
400 if (swapRates) {
401 NodeRef j = tree.getNode(MathUtils.nextInt(tree.getNodeCount()));
402 if (j != i) {
403 double tmp = tree.getNodeRate(i);
404 tree.setNodeRate(i, tree.getNodeRate(j));
405 tree.setNodeRate(j, tmp);
406 }
407
408 }
409
410 if (swapTraits) {
411 NodeRef j = tree.getNode(MathUtils.nextInt(tree.getNodeCount()));
412 if (j != i) {
413 double tmp = tree.getNodeTrait(i);
414 tree.setNodeTrait(i, tree.getNodeTrait(j));
415 tree.setNodeTrait(j, tmp);
416 }
417
418 }
419 */
420
421 // todo fix
422 // Reject all trees in which the root is doubly-
423 if (tree.isBifurcationDoublyLinked(tree.getRoot()))
424 throw new RuntimeException("invalid slide");
425
426 // todo -- check all ARGTree.Roots
427 if (!tree.validRoot())
428 throw new RuntimeException("Roots are invalid");
429
430 if (logq == Double.NEGATIVE_INFINITY)
431 throw new RuntimeException("invalid slide");
432 // System.err.println("Ending Subtree Slide Operation.");
433 //System.err.println("logq = "+logq);
434 // logq = 0;
435
436
437 if (scaledDirichletBranches) {
438 if (oldTreeHeight != tree.getNodeHeight(tree.getRoot()))
439 throw new RuntimeException("Temporarily disabled."); // TODO calculate Hastings ratio
440 }
441
442
443 return logq;
444 }
445
446 private double getDelta() {
447 if (!gaussian) {
448 return (MathUtils.nextDouble() * size) - (size / 2.0);
449 } else {
450 return MathUtils.nextGaussian() * size;
451 }
452 }
453
454 private int getSlideableSubtrees(ARGModel tree, ArrayList<NodeRef> potentials) {
455 int count = 0;
456 for (int i = 0, n = tree.getNodeCount(); i < n; i++) {
457 NodeRef node = tree.getNode(i);
458 if (!tree.isRoot(node) && tree.isBifurcation(node)
459 && tree.isBifurcation(tree.getParent(node))) {
460 if (potentials != null)
461 potentials.add(node);
462 count++;
463 }
464 }
465 return count;
466 }
467
468 private int intersectingEdges(ARGModel tree, NodeRef node, NodeRef parent, double height, ArrayList<NodeRef[]> directChildren) {
469
470 // if( tree.isBifurcation(node) ) {
471 //ree.getParent(node); tree.getMinParentNodeHeight(node);
472 //NodeRef parent = tree.getParent(node);
473 if (tree.getNodeHeight(parent) < height) return 0;
474
475 if (tree.getNodeHeight(node) < height) {
476 if (directChildren != null) {
477 NodeRef[] addition = new NodeRef[2];
478 addition[0] = parent;
479 addition[1] = node;
480 directChildren.add(addition);
481 }
482 //directChildren.add(node);
483 return 1;
484 }
485
486 int count = 0;
487 //for (int i = 0; i < tree.getChildCount(node); i++) {
488 count += intersectingEdges(tree, tree.getChild(node, 0), node, height, directChildren);
489 if (tree.isBifurcation(node))
490 count += intersectingEdges(tree, tree.getChild(node, 1), node, height, directChildren);
491
492 return count;
493 }
494 // Handle reassortment nodes
495 // // Only the parental edge which routines flows down is important
496 // NodeRef parent0 = tree.getParent(node,0);
497 // NodeRef parent1 = tree.getParent(node,1);
498 // double thisHeight = tree.getNodeHeight(node);
499 // double height0 = tree.getNodeHeight(parent0);
500 // double height1 = tree.getNodeHeight(parent1);
501 //
502 // if( (height0 < height) && (height1 < height) ) return 0;
503 // int count = 0;
504 // if( (thisHeight < height) && (height0 >= height) ) {
505 // if( directChildren !=null ) {
506 // NodeRef[] addition = new NodeRef[2];
507 // addition[0] = parent0;
508 // addition[1] = node;
509 // directChildren.add(addition);
510 // }
511 // //directChildren.add(node);
512 // count += 1;
513 // }
514 // if( (thisHeight < height) && (height1 >= height) ) {
515 // if( directChildren != null ) {
516 // NodeRef[] addition = new NodeRef[2];
517 // addition[0] = parent1;
518 // addition[1] = node;
519 // directChildren.add(addition);
520 // }
521 // //directChildren.add(node);
522 // count += 1;
523 // }
524 // if( count > 0 )
525 // return count;
526 //
527 // return intersectingEdges(tree, tree.getChild(node,0), height, directChildren);
528 // }
529
530 /**
531 * @return the other child of the given parent.
532 */
533 private NodeRef getOtherChild(Tree tree, NodeRef parent, NodeRef child) {
534
535 if (tree.getChild(parent, 0) == child) {
536 return tree.getChild(parent, 1);
537 } else {
538 return tree.getChild(parent, 0);
539 }
540 }
541
542 public double getSize() {
543 return size;
544 }
545
546 public void setSize(double size) {
547 this.size = size;
548 }
549
550 public double getAdaptableParameter() {
551 return Math.log(getSize());
552 }
553
554 public void setAdaptableParameter(double value) {
555 setSize(Math.exp(value));
556 }
557
558 public double getRawParameter() {
559 return getSize();
560 }
561
562 // public int getMode() {
563 // return mode;
564 // }
565
566 public String getAdaptableParameterName() {
567 return "size";
568 }
569
570 public String getOperatorName() {
571 return SUBTREE_SLIDE;
572 }
573
574 public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
575
576 public String getParserName() {
577 return SUBTREE_SLIDE;
578 }
579
580 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
581
582 boolean swapRates = false;
583 boolean swapTraits = false;
584 boolean scaledDirichletBranches = false;
585
586 AdaptationMode mode = AdaptationMode.parseMode(xo);
587
588 if (xo.hasAttribute(SWAP_RATES)) {
589 swapRates = xo.getBooleanAttribute(SWAP_RATES);
590 }
591 if (xo.hasAttribute(SWAP_TRAITS)) {
592 swapTraits = xo.getBooleanAttribute(SWAP_TRAITS);
593 }
594
595 if (xo.hasAttribute(DIRICHLET_BRANCHES)) {
596 scaledDirichletBranches = xo.getBooleanAttribute(DIRICHLET_BRANCHES);
597 }
598
599 ARGModel treeModel = (ARGModel) xo.getChild(ARGModel.class);
600 int weight = xo.getIntegerAttribute("weight");
601 double size = xo.getDoubleAttribute("size");
602 boolean gaussian = xo.getBooleanAttribute("gaussian");
603 return new ARGSubtreeSlideOperator(treeModel, weight, size, gaussian, swapRates,
604 swapTraits, scaledDirichletBranches, mode);
605 }
606
607 public String getParserDescription() {
608 return "An operator that slides a subtree.";
609 }
610
611 public Class getReturnType() {
612 return SubtreeSlideOperator.class;
613 }
614
615 public XMLSyntaxRule[] getSyntaxRules() {
616 return rules;
617 }
618
619 private final XMLSyntaxRule[] rules = {
620 AttributeRule.newIntegerRule("weight"),
621 AttributeRule.newDoubleRule("size"),
622 AttributeRule.newBooleanRule("gaussian"),
623 AttributeRule.newBooleanRule(SWAP_RATES, true),
624 AttributeRule.newBooleanRule(SWAP_TRAITS, true),
625 AttributeRule.newBooleanRule(AUTO_OPTIMIZE, true),
626 new ElementRule(ARGModel.class)
627 };
628 };
629
630 }