Debian Codegraph @

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

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