Debian Codegraph @

src/dr/evolution/colouring/BasicColourSampler.java

raw symbols SCIP
1 /*
2 * BasicColourSampler.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.evolution.colouring;
27
28 import dr.evolution.alignment.Alignment;
29 import dr.evolution.coalescent.structure.MetaPopulation;
30 import dr.evolution.tree.NodeRef;
31 import dr.evolution.tree.Tree;
32 import dr.evolution.util.TaxonList;
33 import dr.math.MathUtils;
34
35
36 /**
37 * @author Alexei Drummond
38 * @author Gerton Lunter
39 * @author Andrew Rambaut
40 * <p/>
41 * This is the old version. It samples like a substitution model, except that nodes are biased
42 * towards populations with low Ne, since coalescences are more likely to occur there.
43 * <p/>
44 * It seems to work less well than a straight substitution-like model (such as Greg Ewing uses).
45 * The reason is that although the bias is correct, along branches the bias works the other way.
46 * By incorporating bias at the nodes, the problem along branches gets worse, and this seems to
47 * affect the acceptance probabilities more than having the right bias at the nodes helps. So,
48 * although the code still accepts the population sizes, it ignores it now.
49 * @version $Id: BasicColourSampler.java,v 1.16 2006/09/11 09:33:01 gerton Exp $
50 */
51 public class BasicColourSampler implements ColourSampler {
52
53 static final int maxIterations = 1000;
54
55 public BasicColourSampler(Alignment tipColours, Tree tree) {
56
57 if (tipColours.getSiteCount() != 1) {
58 throw new IllegalArgumentException("Tip colour alignment must consist of a single column!");
59 }
60
61 nodeColours = new int[tree.getNodeCount()];
62 colourCount = tipColours.getDataType().getStateCount();
63
64 leafColourCounts = new int[colourCount];
65
66 // initialize external node colours
67 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
68 NodeRef node = tree.getExternalNode(i);
69 int colour = tipColours.getState(tipColours.getTaxonIndex(tree.getTaxonId(i)), 0);
70 nodeColours[node.getNumber()] = colour;
71 leafColourCounts[colour]++;
72 }
73
74 nodePartials = new double[tree.getNodeCount()][colourCount];
75 }
76
77 public BasicColourSampler(TaxonList[] tipColours, Tree tree) {
78
79 nodeColours = new int[tree.getNodeCount()];
80 colourCount = tipColours.length + 1;
81
82 leafColourCounts = new int[colourCount];
83
84 // initialize external node colours
85 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
86 NodeRef node = tree.getExternalNode(i);
87 int colour = 0;
88 for (int j = 0; j < tipColours.length; j++) {
89 if (tipColours[j].getTaxonIndex(tree.getTaxonId(i)) != -1) {
90 colour = j + 1;
91 }
92 }
93 nodeColours[node.getNumber()] = colour;
94
95 leafColourCounts[colour]++;
96 }
97
98 nodePartials = new double[tree.getNodeCount()][colourCount];
99 }
100
101 public int[] getLeafColourCounts() {
102 return leafColourCounts;
103 }
104
105 /**
106 * Colours the tree probabilistically with the given migration rates
107 *
108 * @param colourChangeMatrix the colour change rate parameters
109 */
110 public DefaultTreeColouring sampleTreeColouring(Tree tree, ColourChangeMatrix colourChangeMatrix, MetaPopulation mp) {
111 DefaultTreeColouring colouring = new DefaultTreeColouring(2, tree);
112
113 double[] N = mp.getPopulationSizes(0);
114
115 double[] rootPartials = prune(tree, tree.getRoot(), colourChangeMatrix, N);
116
117 // Sampling is conditional on data; so normalize by the probability of the
118 // data under the proposal distribution
119 double normalization = 0.0;
120 for (int i = 0; i < rootPartials.length; i++) {
121 normalization += colourChangeMatrix.getEquilibrium(i) * rootPartials[i];
122 }
123
124 sampleInternalNodes(tree, tree.getRoot(), colourChangeMatrix);
125
126 sampleBranchColourings(colouring, tree, tree.getRoot(), colourChangeMatrix);
127
128 double logP = calculateLogProbabilityDensity(colouring, tree, tree.getRoot(), colourChangeMatrix, N) - Math.log(normalization);
129
130 colouring.setLogProbabilityDensity(logP);
131
132 return colouring;
133 }
134
135 /**
136 * @param node
137 */
138 private final int getColour(NodeRef node) {
139 return nodeColours[node.getNumber()];
140 }
141
142 /**
143 * @param node
144 */
145 private final void setColour(NodeRef node, int colour) {
146 if (colour >= 0 && colour < colourCount) {
147 nodeColours[node.getNumber()] = colour;
148 } else {
149 throw new IllegalArgumentException("colour value " + colour + " + is outside of range of colours, [0, " + Integer.toString(colourCount - 1) + "]");
150 }
151 }
152
153 /*****************************************************************************************
154 *
155 * Probability- and sampling-related code follows
156 *
157 */
158
159
160 /**
161 * Calculate probability of data at descendants from node, given a color at the node ('partials'),
162 * by a Felsenstein-like pruning algorithm. (First step in the color sampling algorithm)
163 * Side effect: updates nodePartials[] for this node and all its descendants.
164 *
165 * @param node
166 * @return the partials of this node
167 */
168 private final double[] prune(Tree tree, NodeRef node, ColourChangeMatrix mm, double[] N) {
169
170 double[] p = new double[colourCount];
171
172 if (tree.isExternal(node)) {
173 p[getColour(node)] = 1.0;
174 return p;
175 }
176
177 // Note: assuming binary tree!
178 NodeRef leftChild = tree.getChild(node, 0);
179 NodeRef rightChild = tree.getChild(node, 1);
180
181 double[] left = prune(tree, leftChild, mm, N);
182 double[] right = prune(tree, rightChild, mm, N);
183
184 double nodeHeight = tree.getNodeHeight(node);
185
186 double leftTime = nodeHeight - tree.getNodeHeight(tree.getChild(node, 0));
187 double rightTime = nodeHeight - tree.getNodeHeight(tree.getChild(node, 1));
188
189 for (int i = 0; i < p.length; i++) {
190
191 double leftSum = 0.0;
192 double rightSum = 0.0;
193
194 // looping over colours in left and right children
195 for (int j = 0; j < left.length; j++) {
196 // forwardTimeEvolution conditions on the parent state i, i.e. time
197 // runs in the natural direction (forward from parent to child)
198 leftSum += left[j] * mm.forwardTimeEvolution(i, j, leftTime);
199 rightSum += right[j] * mm.forwardTimeEvolution(i, j, rightTime);
200 }
201 p[i] = leftSum * rightSum;
202
203 // Condition on the formal variable
204 // (Removed - this didn't work; without it the sampler is robust)
205 /*
206 if (N != null) {
207 p[i] /= N[i];
208 }
209 */
210 }
211
212 nodePartials[node.getNumber()] = p;
213
214 return p;
215 }
216
217
218 /**
219 * Samples internal node colours (from root to tips)
220 * Requires the results from Felsenstein Backwards pruning, in nodePartials[] (see prune())
221 * Side effect: updates nodeColours[]
222 */
223 private final void sampleInternalNodes(Tree tree, NodeRef node, ColourChangeMatrix mm) {
224
225 double[] backward = nodePartials[node.getNumber()];
226 double[] forward;
227
228 if (tree.isRoot(node)) {
229
230 forward = mm.getEquilibrium();
231
232 } else {
233
234 NodeRef parent = tree.getParent(node);
235 int parentColour = getColour(parent);
236 double time = tree.getNodeHeight(parent) - tree.getNodeHeight(node);
237 forward = new double[backward.length];
238 for (int i = 0; i < backward.length; i++) {
239 forward[i] = mm.forwardTimeEvolution(parentColour, i, time);
240 }
241
242 }
243
244 // Calculate the (unnormalized) probability for each colour, given the data and the
245 // parent colour
246 for (int i = 0; i < backward.length; i++) {
247 forward[i] *= backward[i];
248 }
249
250 // Sample a colour
251 int colour = MathUtils.randomChoicePDF(forward);
252 setColour(node, colour);
253
254 // Recursively sample down the tree
255 for (int i = 0; i < tree.getChildCount(node); i++) {
256 NodeRef child = tree.getChild(node, i);
257 if (!tree.isExternal(child)) {
258 sampleInternalNodes(tree, child, mm);
259 }
260 }
261 }
262
263 /**
264 * Samples the colours on a tree branch, between node and its parent, conditional on the colour at these nodes.
265 *
266 * @param node the node above which to sample changes
267 */
268 private void sampleBranchColourings(DefaultTreeColouring colouring, Tree tree, NodeRef node, ColourChangeMatrix mm) {
269
270 if (!tree.isRoot(node)) {
271 NodeRef parent = tree.getParent(node);
272
273 int parentColour = getColour(parent);
274 int childColour = getColour(node);
275 double parentHeight = tree.getNodeHeight(parent);
276 double childHeight = tree.getNodeHeight(node);
277
278 // Sample migration events on this branch, as a list of ColourChange-s
279 DefaultBranchColouring history = sampleConditionalBranchColouring(parentColour, parentHeight, childColour, childHeight, mm);
280
281 // Assign these migrations to the branch (attached to the child)
282 colouring.setBranchColouring(node, history);
283 }
284
285 for (int i = 0; i < tree.getChildCount(node); i++) {
286 sampleBranchColourings(colouring, tree, tree.getChild(node, i), mm);
287 }
288 }
289
290 private DefaultBranchColouring sampleConditionalBranchColouring(int parentColour, double parentHeight,
291 int childColour, double childHeight, ColourChangeMatrix mm) {
292
293 DefaultBranchColouring history = new DefaultBranchColouring(parentColour, childColour);
294 int currentColour;
295 double currentHeight;
296 int iterationsLeft = maxIterations;
297 double time;
298
299 // Reject until we get the child colour
300 do {
301
302 history.clear();
303 currentColour = parentColour;
304 currentHeight = parentHeight;
305
306 // Sample events until we reach the child
307 do {
308
309 // Sample a waiting time
310 double totalRate = -mm.getForwardRate(currentColour, currentColour);
311 double U;
312
313 do {
314 U = MathUtils.nextDouble();
315 } while (U == 0.0);
316
317 // Neat trick (Rasmus Nielsen):
318 // If colours of parent and child differ, sample conditioning on at least 1 event
319 if ((parentColour != childColour) && (history.getNumEvents() == 0)) {
320
321 double minU = Math.exp(-totalRate * (parentHeight - childHeight));
322 U = minU + U * (1.0 - minU);
323
324 }
325
326 // Calculate the waiting time, and update currentHeight
327 time = -Math.log(U) / totalRate;
328 currentHeight -= time;
329
330 if (currentHeight > childHeight) {
331 // Not yet reached the child. "Sample" an event
332 currentColour = 1 - currentColour;
333 // Add it to the list
334 history.addEvent(currentColour, currentHeight);
335 }
336
337 } while (currentHeight > childHeight);
338
339 iterationsLeft -= 1;
340
341 } while ((currentColour != childColour) && (iterationsLeft > 0));
342
343 if (currentColour != childColour) {
344 // Extreme migration rates may cause difficulty for the rejection sampler
345 // Print a warning and add a bogus event somewhat near where you'd want it.
346 double previousEventHeight = currentHeight + time;
347 double finalEventHeight = childHeight + 0.01 * (previousEventHeight - childHeight);
348 history.addEvent(childColour, finalEventHeight);
349
350 System.out.println("dr.evolution.colouring.BranchColourSampler: failed to generate sample after " + maxIterations + " trials.");
351 System.out.println(": parentColour=" + parentColour);
352 System.out.println(": parentHeight=" + parentHeight);
353 System.out.println(": childColour=" + childColour);
354 System.out.println(": childHeight=" + childHeight);
355 System.out.println(": migration rate 0->1 = " + mm.getForwardRate(0, 1));
356 System.out.println(": migration rate 1->0 = " + mm.getForwardRate(1, 0));
357 }
358
359 return history;
360
361 }
362
363
364 /**
365 * Calculates log probability density of the proposal colouring of the tree on the branch leading to this node,
366 * and everything descending from it.
367 */
368 private final double calculateLogProbabilityDensity(TreeColouring colouring, Tree tree, NodeRef node, ColourChangeMatrix mm, double[] N) {
369
370 double p = 1.0;
371
372 if (tree.isRoot(node)) {
373
374 p = mm.getEquilibrium(colouring.getNodeColour(node));
375
376 } else {
377
378 NodeRef parent = tree.getParent(node);
379 BranchColouring history = colouring.getBranchColouring(node); // note - it is attached to the child node
380
381 int fromColour = colouring.getNodeColour(parent);
382 double fromHeight = tree.getNodeHeight(parent);
383
384 // Loop over all events, forward in time (i.e. down the tree)
385 for (int i = 1; i <= history.getNumEvents(); i++) {
386
387 // get colour below this node.
388 int toColour = history.getForwardColourBelow(i);
389 // get new height
390 double toHeight = history.getForwardTime(i);
391 // factor in the exit probability
392 p *= Math.exp(-(fromHeight - toHeight) * (-mm.getForwardRate(fromColour, fromColour)));
393 // and the event itself
394 p *= mm.getForwardRate(fromColour, toColour);
395
396 fromHeight = toHeight;
397 fromColour = toColour;
398
399 }
400
401 // Include the exit probability on the branch from the last migration event to the child.
402 double toHeight = tree.getNodeHeight(node);
403 p *= Math.exp(-(fromHeight - toHeight) * (-mm.getForwardRate(fromColour, fromColour)));
404
405 // Include the contribution of the formal variable (if this is an internal node)
406 // (Removed)
407 /*
408 if (!tree.isExternal(node) && N != null) {
409 p /= N[fromColour];
410 }
411 */
412 }
413
414 double logP = Math.log(p);
415
416 for (int i = 0; i < tree.getChildCount(node); i++) {
417 logP += calculateLogProbabilityDensity(colouring, tree, tree.getChild(node, i), mm, N);
418 }
419
420 return logP;
421 }
422
423
424 //
425 // Calculates the Lebesgue measure of the space of migration events for the number of migration events
426 // on each branch as specified by TreeColouring.
427 //
428 public static final double calculateLogNormalization(TreeColouring colouring, Tree tree, NodeRef node) {
429
430 final double arbitraryScaleFactor = 1.0;
431
432 double logn = 0.0;
433
434 if (!tree.isRoot(node)) {
435
436 double norm = 1.0;
437 double t = tree.getNodeHeight(tree.getParent(node)) - tree.getNodeHeight(node);
438 int events = colouring.getBranchColouring(node).getNumEvents();
439
440 for (int i = 1; i <= events; i++) {
441
442 norm *= t / i;
443
444 }
445
446 logn = arbitraryScaleFactor * Math.log(norm);
447
448 }
449
450 for (int i = 0; i < tree.getChildCount(node); i++) {
451 logn += calculateLogNormalization(colouring, tree, tree.getChild(node, i));
452 }
453
454 return logn;
455
456 }
457
458
459 public double getProposalProbability(TreeColouring treeColouring, Tree tree, ColourChangeMatrix colourChangeMatrix, MetaPopulation mp) {
460
461 throw new IllegalArgumentException("Not implemented for BasicColourSampler; you can only use <ColouredOperator>s");
462
463 }
464
465
466 private final int colourCount;
467
468 private int[] nodeColours;
469
470 private double[][] nodePartials;
471
472 private final int[] leafColourCounts;
473 }