Debian Codegraph @

src/dr/evomodel/epidemiology/casetocase/operators/TransmissionSubtreeSlideB.java

raw symbols SCIP
1 /*
2 * TransmissionSubtreeSlideB.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 package dr.evomodel.epidemiology.casetocase.operators;
27
28 import dr.evolution.tree.NodeRef;
29 import dr.evolution.tree.Tree;
30 import dr.evomodel.epidemiology.casetocase.AbstractCase;
31 import dr.evomodel.epidemiology.casetocase.BranchMapModel;
32 import dr.evomodel.epidemiology.casetocase.CaseToCaseTreeLikelihood;
33 import dr.evomodel.operators.AbstractTreeOperator;
34 import dr.evomodel.tree.TreeModel;
35 import dr.inference.operators.*;
36 import dr.math.MathUtils;
37 import dr.xml.*;
38
39 import java.util.ArrayList;
40 import java.util.List;
41
42 /**
43 * Implements the subtree slide move where the slide moves an entire subtree of the transmission tree.
44 *
45 * @author Matthew Hall
46 *
47 */
48 public class TransmissionSubtreeSlideB extends AbstractTreeOperator implements AdaptableMCMCOperator {
49
50 private CaseToCaseTreeLikelihood c2cLikelihood;
51 private TreeModel tree;
52 private double size = 1.0;
53 private boolean gaussian = false;
54 private final boolean swapInRandomRate;
55 private final boolean swapInRandomTrait;
56 private final boolean resampleInfectionTimes;
57 private AdaptationMode mode = AdaptationMode.DEFAULT;
58 private static final boolean DEBUG = false;
59 public static final String TRANSMISSION_SUBTREE_SLIDE_B = "transmissionSubtreeSlideB";
60 public static final String SWAP_RATES = "swapInRandomRate";
61 public static final String SWAP_TRAITS = "swapInRandomTrait";
62 public static final String TARGET_ACCEPTANCE = "targetAcceptance";
63
64 public TransmissionSubtreeSlideB(CaseToCaseTreeLikelihood c2cLikelihood, double weight, double size,
65 boolean gaussian, boolean swapRates, boolean swapTraits, AdaptationMode mode,
66 boolean resampleInfectionTimes) {
67 this.c2cLikelihood = c2cLikelihood;
68 tree = c2cLikelihood.getTreeModel();
69 setWeight(weight);
70
71 if (size == 0.0) {
72 double b = 0.0;
73 for (int k = 0; k < tree.getNodeCount(); ++k) {
74 b += tree.getBranchLength(tree.getNode(k));
75 }
76 size = b / (2 * tree.getNodeCount());
77 }
78
79 this.size = size;
80 this.gaussian = gaussian;
81 this.swapInRandomRate = swapRates;
82 this.swapInRandomTrait = swapTraits;
83
84 this.resampleInfectionTimes = resampleInfectionTimes;
85
86 this.mode = mode;
87 }
88
89 /**
90 * Do a probablistic subtree slide move.
91 *
92 * @return the log-transformed hastings ratio
93 */
94 public double doOperation() {
95
96
97 if(DEBUG){
98 c2cLikelihood.outputTreeToFile("beforeTSSB.nex", false);
99 }
100
101
102 BranchMapModel branchMap = c2cLikelihood.getBranchMap();
103
104 double logq;
105
106 NodeRef i;
107
108 // 1. choose a random eligible node avoiding root
109 do {
110 i = tree.getNode(MathUtils.nextInt(tree.getNodeCount()));
111 } while (!eligibleForMove(i, tree, branchMap));
112
113 final NodeRef iP = tree.getParent(i);
114 final NodeRef CiP = getOtherChild(tree, iP, i);
115 final NodeRef PiP = tree.getParent(iP);
116
117 // 2. choose a delta to move
118 final double delta = getDelta();
119 final double oldHeight = tree.getNodeHeight(iP);
120 final double newHeight = oldHeight + delta;
121
122 AbstractCase iCase = branchMap.get(i.getNumber());
123 AbstractCase iPCase = branchMap.get(iP.getNumber());
124 AbstractCase CiPCase = branchMap.get(CiP.getNumber());
125 AbstractCase PiPCase = null;
126 if(PiP!=null){
127 PiPCase = branchMap.get(PiP.getNumber());
128 }
129
130 if(resampleInfectionTimes) {
131 // what happens on i's branch (there has always been a change)
132
133 iCase.setInfectionBranchPosition(MathUtils.nextDouble());
134
135 // what happens between PiP and CiP
136
137 if (PiPCase == null || CiPCase != PiPCase) {
138
139 CiPCase.setInfectionBranchPosition(MathUtils.nextDouble());
140
141 }
142 }
143
144
145 // 3. if the move is down
146 if (delta > 0) {
147
148
149 // 3.1 if the topology will change
150 if (PiP != null && tree.getNodeHeight(PiP) < newHeight) {
151 // find new parent
152 NodeRef newParent = PiP;
153 NodeRef newChild = iP;
154 while (tree.getNodeHeight(newParent) < newHeight) {
155 newChild = newParent;
156 newParent = tree.getParent(newParent);
157 if (newParent == null) break;
158 }
159
160 tree.beginTreeEdit();
161
162 // 3.1.1 if creating a new root
163 if (tree.isRoot(newChild)) {
164 tree.removeChild(iP, CiP);
165 tree.removeChild(PiP, iP);
166 tree.addChild(iP, newChild);
167 tree.addChild(PiP, CiP);
168 tree.setRoot(iP);
169 //System.err.println("Creating new root!");
170
171 if (tree.hasNodeTraits()) {
172 // **********************************************
173 // swap traits and rates so that root keeps it trait and rate values
174 // **********************************************
175
176 tree.swapAllTraits(newChild, iP);
177
178 }
179
180 if (tree.hasRates()) {
181 final double rootNodeRate = tree.getNodeRate(newChild);
182 tree.setNodeRate(newChild, tree.getNodeRate(iP));
183 tree.setNodeRate(iP, rootNodeRate);
184 }
185
186 // **********************************************
187
188 }
189 // 3.1.2 no new root
190 else {
191 tree.removeChild(iP, CiP);
192 tree.removeChild(PiP, iP);
193 tree.removeChild(newParent, newChild);
194 tree.addChild(iP, newChild);
195 tree.addChild(PiP, CiP);
196 tree.addChild(newParent, iP);
197 //System.err.println("No new root!");
198 }
199
200 tree.setNodeHeight(iP, newHeight);
201
202 tree.endTreeEdit();
203
204 // 3.1.3 count the hypothetical sources of this destination.
205 final int possibleSources = intersectingEdges(tree, newChild, oldHeight, null);
206
207 logq = -Math.log(possibleSources);
208
209 // Randomly assign iP the partition of either its parent or the child that is not i, and adjust q
210 // appropriately
211
212 if(PiPCase != CiPCase){
213 logq += Math.log(0.5);
214 }
215
216 AbstractCase newiPCase;
217
218
219 AbstractCase newChildCase = branchMap.get(newChild.getNumber());
220
221 if(newParent != null && branchMap.get(newParent.getNumber())!=branchMap.get(newChild.getNumber())){
222 if(MathUtils.nextInt(2)==0){
223 newiPCase = branchMap.get(newParent.getNumber());
224 } else {
225 newiPCase = newChildCase;
226 }
227
228 if(resampleInfectionTimes) {
229 //whichever we picked for iP, it's the new child's case whose infection branch is modified
230 // (even if this infection branch is iP's branch)
231
232 newChildCase.setInfectionBranchPosition(MathUtils.nextDouble());
233
234 }
235
236 logq += Math.log(2);
237
238 } else {
239 newiPCase = newChildCase;
240
241 // if iP is now the root its case infection time has changed. If not, then there is no infection
242 // on this branch
243
244 if(resampleInfectionTimes) {
245 if (newParent == null) {
246 newChildCase.setInfectionBranchPosition(MathUtils.nextDouble());
247 }
248 }
249 }
250
251 branchMap.set(iP.getNumber(), newiPCase, true);
252
253 } else {
254 // just change the node height
255
256 // todo you could actually randomise whether the subtree containing iP is changed here
257
258 tree.setNodeHeight(iP, newHeight);
259 logq = 0.0;
260 }
261 }
262 // 4 if we are sliding the subtree up.
263 else {
264
265 // 4.0 is it a valid move?
266 if (tree.getNodeHeight(i) > newHeight) {
267 return Double.NEGATIVE_INFINITY;
268 }
269
270 // 4.1 will the move change the topology?
271 if (tree.getNodeHeight(CiP) > newHeight) {
272
273 List<NodeRef> newChildren = new ArrayList<NodeRef>();
274 final int possibleDestinations = intersectingEdges(tree, CiP, newHeight, newChildren);
275
276 // if no valid destinations then return a failure
277 if (newChildren.size() == 0) {
278 return Double.NEGATIVE_INFINITY;
279 }
280
281 // pick a random parent/child destination edge uniformly from options
282 final int childIndex = MathUtils.nextInt(newChildren.size());
283 NodeRef newChild = newChildren.get(childIndex);
284 NodeRef newParent = tree.getParent(newChild);
285
286 tree.beginTreeEdit();
287
288 // 4.1.1 if iP was root
289 if (tree.isRoot(iP)) {
290 // new root is CiP
291 tree.removeChild(iP, CiP);
292 tree.removeChild(newParent, newChild);
293 tree.addChild(iP, newChild);
294 tree.addChild(newParent, iP);
295 tree.setRoot(CiP);
296
297 if (tree.hasNodeTraits()) {
298 // **********************************************
299 // swap traits and rates, so that root keeps it trait and rate values
300 // **********************************************
301
302 tree.swapAllTraits(iP, CiP);
303
304 }
305
306 if (tree.hasRates()) {
307 final double rootNodeRate = tree.getNodeRate(iP);
308 tree.setNodeRate(iP, tree.getNodeRate(CiP));
309 tree.setNodeRate(CiP, rootNodeRate);
310 }
311
312 // **********************************************
313
314 //System.err.println("DOWN: Creating new root!");
315 } else {
316 tree.removeChild(iP, CiP);
317 tree.removeChild(PiP, iP);
318 tree.removeChild(newParent, newChild);
319 tree.addChild(iP, newChild);
320 tree.addChild(PiP, CiP);
321 tree.addChild(newParent, iP);
322 //System.err.println("DOWN: no new root!");
323 }
324
325 tree.setNodeHeight(iP, newHeight);
326
327 tree.endTreeEdit();
328
329 logq = Math.log(possibleDestinations);
330
331 // Randomly assign iP the partition of either its parent or the child that is not i, and adjust q
332 // appropriately
333
334 if(PiP!=null && PiPCase != CiPCase){
335 logq += Math.log(0.5);
336 }
337
338 AbstractCase newiPCase;
339
340 AbstractCase newChildCase = branchMap.get(newChild.getNumber());
341
342 if(branchMap.get(newParent.getNumber())!=branchMap.get(newChild.getNumber())){
343 if(MathUtils.nextInt(2)==0){
344 newiPCase = branchMap.get(newParent.getNumber());
345 } else {
346 newiPCase = newChildCase;
347 }
348
349 if(resampleInfectionTimes) {
350 //whichever we picked for iP, it's the new child's case whose infection branch is modified
351 // (even if this infection branch is iP's branch)
352
353 newChildCase.setInfectionBranchPosition(MathUtils.nextDouble());
354 }
355
356 logq += Math.log(2);
357 } else {
358 //upward, so don't have to worry about newParent being the root if the topology changed
359
360 newiPCase = newChildCase;
361
362 }
363
364 branchMap.set(iP.getNumber(), newiPCase, true);
365
366 } else {
367
368 tree.setNodeHeight(iP, newHeight);
369 logq = 0.0;
370 }
371 }
372
373 if (swapInRandomRate) {
374 final NodeRef j = tree.getNode(MathUtils.nextInt(tree.getNodeCount()));
375 if (j != i) {
376 final double tmp = tree.getNodeRate(i);
377 tree.setNodeRate(i, tree.getNodeRate(j));
378 tree.setNodeRate(j, tmp);
379 }
380
381 }
382
383 if (swapInRandomTrait) {
384 final NodeRef j = tree.getNode(MathUtils.nextInt(tree.getNodeCount()));
385 if (j != i) {
386
387 tree.swapAllTraits(i, j);
388
389 // final double tmp = tree.getNodeTrait(i, TRAIT);
390 // tree.setNodeTrait(i, TRAIT, tree.getNodeTrait(j, TRAIT));
391 // tree.setNodeTrait(j, TRAIT, tmp);
392 }
393
394 }
395
396 // just return -Inf: will reject move
397 // if (logq == Double.NEGATIVE_INFINITY) throw new OperatorFailedException("invalid slide");
398
399 if (DEBUG) {
400 c2cLikelihood.getTreeModel().checkPartitions();
401 c2cLikelihood.outputTreeToFile("afterTSSB.nex", false);
402 }
403
404
405 return logq;
406 }
407
408 private double getDelta() {
409 if (!gaussian) {
410 return (MathUtils.nextDouble() * size) - (size / 2.0);
411 } else {
412 return MathUtils.nextGaussian() * size;
413 }
414 }
415
416 private boolean eligibleForMove(NodeRef node, TreeModel tree, BranchMapModel branchMap){
417 // to be eligible for this move, the node's parent must exist and be in a different partition to itself. This
418 // forces the parent to be in the same partition as either its grandchild or its child.
419
420 return (!tree.isRoot(node) && branchMap.get(tree.getParent(node).getNumber())
421 !=branchMap.get(node.getNumber()));
422 }
423
424 //intersectingEdges is the same as in normal STS, since there's no additional restriction in this case on where
425 // nodes can go, and the move does not modify eligibility for itself
426
427 private int intersectingEdges(Tree tree, NodeRef node, double height, List<NodeRef> directChildren) {
428
429 final NodeRef parent = tree.getParent(node);
430
431 if (tree.getNodeHeight(parent) < height) return 0;
432
433 if (tree.getNodeHeight(node) < height) {
434 if (directChildren != null) directChildren.add(node);
435 return 1;
436 }
437
438 int count = 0;
439 for (int i = 0; i < tree.getChildCount(node); i++) {
440 count += intersectingEdges(tree, tree.getChild(node, i), height, directChildren);
441 }
442 return count;
443 }
444
445 public double getSize() {
446 return size;
447 }
448
449 public void setSize(double size) {
450 this.size = size;
451 }
452
453 public double getAdaptableParameter() {
454 return Math.log(getSize());
455 }
456
457 public void setAdaptableParameter(double value) {
458 setSize(Math.exp(value));
459 }
460
461 public double getRawParameter() {
462 return getSize();
463 }
464
465 public AdaptationMode getMode() {
466 return mode;
467 }
468
469 @Override
470 public double getTargetAcceptanceProbability() {
471 return AbstractAdaptableOperator.DEFAULT_ADAPTATION_TARGET;
472 }
473
474 @Override
475 public String getAdaptableParameterName() {
476 return "size";
477 }
478
479 public double getMinimumAcceptanceLevel() {
480 return MINIMUM_ACCEPTANCE_LEVEL;
481 }
482
483 public double getMaximumAcceptanceLevel() {
484 return MAXIMUM_ACCEPTANCE_LEVEL;
485 }
486
487 public double getMinimumGoodAcceptanceLevel() {
488 return MINIMUM_GOOD_ACCEPTANCE_LEVEL;
489 }
490
491 public double getMaximumGoodAcceptanceLevel() {
492 return MAXIMUM_GOOD_ACCEPTANCE_LEVEL;
493 }
494
495 @Override
496 public String getPerformanceSuggestion() {
497 return "";
498 }
499
500 public String getOperatorName() {
501 return TRANSMISSION_SUBTREE_SLIDE_B + " (" + tree.getId() + ")";
502 }
503
504 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
505
506 public static final String RESAMPLE_INFECTION_TIMES = "resampleInfectionTimes";
507
508 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
509
510 boolean swapRates = xo.getAttribute(SWAP_RATES, false);
511 boolean swapTraits = xo.getAttribute(SWAP_TRAITS, false);
512
513 AdaptationMode mode = AdaptationMode.DEFAULT;
514 if (xo.hasAttribute(AdaptableMCMCOperator.AUTO_OPTIMIZE)) {
515 if (xo.getBooleanAttribute(AdaptableMCMCOperator.AUTO_OPTIMIZE)) {
516 mode = AdaptationMode.ADAPTATION_ON;
517 } else {
518 mode = AdaptationMode.ADAPTATION_OFF;
519 }
520 }
521
522 CaseToCaseTreeLikelihood c2cL = (CaseToCaseTreeLikelihood)xo.getChild(CaseToCaseTreeLikelihood.class);
523 final double weight = xo.getDoubleAttribute(MCMCOperator.WEIGHT);
524
525 final double targetAcceptance = xo.getAttribute(TARGET_ACCEPTANCE, 0.234);
526
527 final double size = xo.getAttribute("size", 1.0);
528
529 if (Double.isInfinite(size) || size <= 0.0) {
530 throw new XMLParseException("size attribute must be positive and not infinite. was " + size +
531 " for tree " + c2cL.getTreeModel().getId() );
532 }
533
534 boolean resampleInfectionTimes = false;
535
536 if(xo.hasAttribute(RESAMPLE_INFECTION_TIMES)) {
537 resampleInfectionTimes = xo.getBooleanAttribute(RESAMPLE_INFECTION_TIMES);
538 }
539
540 final boolean gaussian = xo.getBooleanAttribute("gaussian");
541 TransmissionSubtreeSlideB operator = new TransmissionSubtreeSlideB(c2cL, weight, size, gaussian,
542 swapRates, swapTraits, mode, resampleInfectionTimes);
543 // operator.setTargetAcceptanceProbability(targetAcceptance);
544
545 return operator;
546 }
547
548 public String getParserDescription() {
549 return "An operator that slides a phylogenetic subtree and a transmission subtree simultaneously.";
550 }
551
552 public Class getReturnType() {
553 return TransmissionSubtreeSlideA.class;
554 }
555
556 public String getParserName() {
557 return TRANSMISSION_SUBTREE_SLIDE_B;
558 }
559
560 public XMLSyntaxRule[] getSyntaxRules() {
561 return rules;
562 }
563
564 private final XMLSyntaxRule[] rules = {
565 AttributeRule.newDoubleRule(MCMCOperator.WEIGHT),
566 // Make size optional. If not given or equals zero, size is set to half of average tree branch length.
567 AttributeRule.newDoubleRule("size", true),
568 AttributeRule.newDoubleRule(TARGET_ACCEPTANCE, true),
569 AttributeRule.newBooleanRule("gaussian"),
570 AttributeRule.newBooleanRule(SWAP_RATES, true),
571 AttributeRule.newBooleanRule(SWAP_TRAITS, true),
572 AttributeRule.newBooleanRule(AdaptableMCMCOperator.AUTO_OPTIMIZE, true),
573 AttributeRule.newBooleanRule(RESAMPLE_INFECTION_TIMES, true),
574 new ElementRule(CaseToCaseTreeLikelihood.class)
575 };
576 };
577
578 }