Debian Codegraph @

src/dr/evolution/colouring/StructuredColourSampler.java

raw symbols SCIP
1 /*
2 * StructuredColourSampler.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 import java.text.DecimalFormat;
36 import java.util.ArrayList;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.TreeMap;
40
41 /**
42 * @author Gerton Lunter
43 * @version $Id: StructuredColourSampler.java,v 1.11 2006/09/11 09:33:01 gerton Exp $
44 * <p/>
45 * Samples tree colourings from a proposal distribution based on
46 * Felsenstein mutation process; biased at the nodes for coalescent rates;
47 * and biased at edges using a mean-field approximation of the branch
48 * colourings. This should improve performance for unequal population sizes
49 */
50 public class StructuredColourSampler implements ColourSampler {
51
52 static final int maxIterations = 1000;
53 static final double tinyTime = 1.0e-6; // to deal with discontinuous demograhpic models
54
55 // debugging flags
56 static final boolean debugMessages = false;
57 static final boolean debugMeanColours = false;
58 static final boolean debugNodePartials = false;
59 static final boolean debugSampleLikelihoods = false;
60 static final boolean debugRejectionSampler = false;
61 static final boolean debugProposalProbabilityCalculator = false;
62 double _totalIntegratedRate;
63 static final DecimalFormat df = new DecimalFormat("###.####");
64
65 // tuning parameters
66 static final double propAffected = 0.0; /* proportion of lineages deemed affected by conditioning on a single one */
67 private boolean useNodeBias = false;
68 private boolean useBranchBias = false;
69 private boolean useSecondColourIteration = true;
70
71 public StructuredColourSampler(Alignment tipColours, Tree tree, boolean nodeBias, boolean branchBias, boolean secondIteration) {
72
73 if (tipColours.getSiteCount() != 1) {
74 throw new IllegalArgumentException("Tip colour alignment must consist of a single column!");
75 }
76
77 nodeColours = new int[tree.getNodeCount()];
78 colourCount = tipColours.getDataType().getStateCount();
79
80 leafColourCounts = new int[colourCount];
81 // initialize external node colours
82 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
83 NodeRef node = tree.getExternalNode(i);
84 int colour = tipColours.getState(tipColours.getTaxonIndex(tree.getTaxonId(i)), 0);
85 nodeColours[node.getNumber()] = colour;
86 leafColourCounts[colour]++;
87 }
88
89 useNodeBias = nodeBias;
90 useBranchBias = branchBias;
91 useSecondColourIteration = secondIteration;
92
93 initialize(tree); // uses only tree constants (number of tips, etc)
94
95 }
96
97 public StructuredColourSampler(TaxonList[] tipColours, Tree tree, boolean nodeBias, boolean branchBias, boolean secondIteration) {
98
99 nodeColours = new int[tree.getNodeCount()];
100 colourCount = tipColours.length + 1;
101
102 leafColourCounts = new int[colourCount];
103
104 // initialize external node colours
105 for (int i = 0; i < tree.getExternalNodeCount(); i++) {
106 NodeRef node = tree.getExternalNode(i);
107 int colour = 0;
108 for (int j = 0; j < tipColours.length; j++) {
109 if (tipColours[j].getTaxonIndex(tree.getTaxonId(i)) != -1) {
110 colour = j + 1;
111 }
112 }
113 nodeColours[node.getNumber()] = colour;
114 leafColourCounts[colour]++;
115 }
116
117 useNodeBias = nodeBias;
118 useBranchBias = branchBias;
119 useSecondColourIteration = secondIteration;
120
121 initialize(tree); // uses only tree constants (number of tips etc)
122
123 }
124
125 public int[] getLeafColourCounts() {
126 return leafColourCounts;
127 }
128
129 private void initialize(Tree tree) {
130
131 nodePartials = new double[tree.getNodeCount()][colourCount];
132 meanColourCounts = new double[tree.getNodeCount()][colourCount];
133 nodeColoursEM = new int[tree.getNodeCount()][];
134 nodePartialsEM = new double[tree.getNodeCount()][][];
135 equilibriumColours = new double[colourCount];
136
137 }
138
139 private void computeIntervals(Tree tree, MetaPopulation mp) {
140
141 // dumb implementation using a sorted map - slowish but simple
142 TreeMap<Double, ArrayList<NodeRef>> intervals = new TreeMap<Double, ArrayList<NodeRef>>();
143 int numnodes = tree.getNodeCount();
144 for (int i = 0; i < numnodes; i++) {
145 NodeRef node = tree.getNode(i);
146 Double height = new Double(tree.getNodeHeight(node));
147 if (intervals.containsKey(height)) {
148 (intervals.get(height)).add(node);
149 } else {
150 ArrayList<NodeRef> list = new ArrayList<NodeRef>(1);
151 list.add(node);
152 intervals.put(height, list);
153 }
154 }
155 node2Interval = new int[numnodes];
156 interval2Height = new double[intervals.size()];
157 avgN0 = new double[intervals.size()];
158 avgN1 = new double[intervals.size()];
159 Iterator<Double> iter = intervals.keySet().iterator();
160 int interval = 0;
161 while (iter.hasNext()) {
162 Double height = iter.next();
163 interval2Height[interval] = height.doubleValue();
164 List<NodeRef> nodes = intervals.get(height);
165 for (int i = 0; i < nodes.size(); i++) {
166 node2Interval[(nodes.get(i)).getNumber()] = interval;
167 }
168 // now initialize the effective (i.e. harmonic average) N's
169 if (interval > 0) {
170 double prevtime = interval2Height[interval - 1];
171 double curtime = height.doubleValue();
172 avgN0[interval - 1] = (curtime - prevtime) / mp.getIntegral(prevtime, curtime, 0);
173 avgN1[interval - 1] = (curtime - prevtime) / mp.getIntegral(prevtime, curtime, 1);
174 }
175 interval += 1;
176 }
177 numIntervals = interval;
178 }
179
180
181 /**
182 * Main entry point. Colours the tree probabilistically with the given migration rates
183 *
184 * @param colourChangeMatrix the colour change rate parameters
185 */
186 // public TreeColouring sampleTreeColouring(Tree tree, ColourChangeMatrix colourChangeMatrix, double[] N) {
187 public DefaultTreeColouring sampleTreeColouring(Tree tree, ColourChangeMatrix colourChangeMatrix, MetaPopulation mp) {
188
189 //double[] N = mp.getPopulationSizes(0);
190
191 populateEquilibriumColourArray(colourChangeMatrix);
192
193 // Build array of node indices, arranged by height
194 computeIntervals(tree, mp);
195
196 DefaultTreeColouring colouring = new DefaultTreeColouring(2, tree);
197
198 // Calculate root partials, and those of all other nodes
199 logNodePartialsRescaling = 0.0;
200 prune(tree, tree.getRoot(), colourChangeMatrix);
201
202 // fill meanColourCounts array
203 calculateMeanColourCounts(tree, colourChangeMatrix);
204
205 // Prune again, but now using mean colour counts for each interval
206 logNodePartialsRescaling = 0.0;
207 double[] rootPartials = pruneEM(tree, tree.getRoot(), colourChangeMatrix, mp);
208
209 // Re-calculate meanColourCounts, and do a final pruning step
210 if (useSecondColourIteration) {
211 calculateMeanColourCountsEM(tree, tree.getRoot(), colourChangeMatrix);
212 logNodePartialsRescaling = 0.0;
213 rootPartials = pruneEM(tree, tree.getRoot(), colourChangeMatrix, mp);
214 }
215
216 // Sampling is conditional on data; so normalize by the probability of the
217 // data under the proposal distribution
218 double normalization = 0.0;
219 for (int i = 0; i < colourCount; i++) {
220 normalization += equilibriumColours[i] * rootPartials[i];
221 }
222 double logNormalization = Math.log(normalization) + logNodePartialsRescaling;
223
224 double logP = sampleEM(tree, tree.getRoot(), colourChangeMatrix, mp, colouring) - logNormalization;
225
226 colouring.setLogProbabilityDensity(logP);
227
228 //JFrame frame = new JFrame();
229 //ColouredTreeComponent comp = new ColouredTreeComponent()
230
231 if (debugProposalProbabilityCalculator) {
232 double logP2 = getProposalProbability(colouring, tree, colourChangeMatrix, mp);
233 System.out.println("Sampling proposal probability " + logP + ", re-calculated as " + logP2 + " (norm=" + logNormalization + ")");
234 }
235
236 return colouring;
237 }
238
239 /**
240 * Returns proposal probability density of a tree colouring
241 *
242 * @param treeColouring
243 * @param tree
244 * @param colourChangeMatrix
245 * @param mp
246 * @return probability density
247 */
248 public double getProposalProbability(TreeColouring treeColouring, Tree tree, ColourChangeMatrix colourChangeMatrix, MetaPopulation mp) {
249
250 //double[] N = mp.getPopulationSizes(0);
251
252 populateEquilibriumColourArray(colourChangeMatrix);
253
254 // Build array of node indices, arranged by height
255 computeIntervals(tree, mp);
256
257 // Calculate root partials, and those of all other nodes
258 logNodePartialsRescaling = 0.0;
259 prune(tree, tree.getRoot(), colourChangeMatrix);
260
261 // fill meanColourCounts array
262 calculateMeanColourCounts(tree, colourChangeMatrix);
263
264 // Prune again, but now using mean colour counts for each interval
265 logNodePartialsRescaling = 0.0;
266 double[] rootPartials = pruneEM(tree, tree.getRoot(), colourChangeMatrix, mp);
267
268 // Re-calculate meanColourCounts, and do a final pruning step
269 if (useSecondColourIteration) {
270 calculateMeanColourCountsEM(tree, tree.getRoot(), colourChangeMatrix);
271 logNodePartialsRescaling = 0.0;
272 rootPartials = pruneEM(tree, tree.getRoot(), colourChangeMatrix, mp);
273 }
274
275 // Sampling is conditional on data; so normalize by the probability of the
276 // data under the proposal distribution
277 double normalization = 0.0;
278 for (int i = 0; i < colourCount; i++) {
279 normalization += equilibriumColours[i] * rootPartials[i];
280 }
281
282 double logP = calculateEMProposal(tree, tree.getRoot(), colourChangeMatrix, mp, treeColouring);
283
284 return logP - Math.log(normalization) - logNodePartialsRescaling;
285
286 }
287
288
289 /**
290 * @param node
291 */
292 private int getColour(NodeRef node) {
293 return nodeColours[node.getNumber()];
294 }
295
296 /**
297 * @param node
298 */
299 private void setColour(NodeRef node, int colour) {
300 if (colour >= 0 && colour < colourCount) {
301 nodeColours[node.getNumber()] = colour;
302 } else {
303 throw new IllegalArgumentException("colour value " + colour + " + is outside of range of colours, [0, " + Integer.toString(colourCount - 1) + "]");
304 }
305 }
306
307
308 /**
309 * **************************************************************************************
310 * <p/>
311 * Probability- and sampling-related code follows
312 */
313
314
315 void populateEquilibriumColourArray(ColourChangeMatrix colourChangeMatrix) {
316
317 // fill equilibrium colour array
318 for (int clr = 0; clr < colourCount; clr++) {
319 equilibriumColours[clr] = colourChangeMatrix.getEquilibrium(clr);
320 }
321
322 }
323
324
325 /* Returns probability of colours at a node, based on pruning output */
326 double[] getMeanColours(int nodeNum, ColourChangeMatrix colourChangeMatrix) {
327
328 double c[] = new double[colourCount];
329 double norm = 0.0;
330 for (int i = 0; i < colourCount; i++) {
331 c[i] = nodePartials[nodeNum][i] * equilibriumColours[i];
332 norm += c[i];
333 }
334 for (int i = 0; i < colourCount; i++) {
335 c[i] /= norm;
336 }
337 return c;
338 }
339
340 /* Returns probability of colours at an node-based intreval, based on pruning output */
341 double[] getMeanColoursEM(int nodeNum, int relativeInterval, ColourChangeMatrix colourChangeMatrix) {
342
343 double c[] = new double[colourCount];
344 double norm = 0.0;
345 for (int i = 0; i < colourCount; i++) {
346 c[i] = nodePartialsEM[nodeNum][relativeInterval][i] * equilibriumColours[i];
347 norm += c[i];
348 }
349 for (int i = 0; i < colourCount; i++) {
350 c[i] /= norm;
351 }
352 return c;
353 }
354
355
356 // Recursively fills meanColourCounts with derived counts for intervals;
357 // utility function for computeMeanColourCounts below
358 void fillMeanColourCounts(Tree tree, NodeRef node, ColourChangeMatrix colourChangeMatrix) {
359
360 if (!tree.isRoot(node)) {
361
362 NodeRef parent = tree.getParent(node);
363 int parentNum = parent.getNumber();
364 int nodeNum = node.getNumber();
365
366 double[] parentColours = getMeanColours(parentNum, colourChangeMatrix);
367 double[] childColours = getMeanColours(nodeNum, colourChangeMatrix);
368
369 for (int i = 0; i < colourCount; i++) {
370 // calculate expected colour at parent and child end of branch
371 double meanColour = (parentColours[i] + childColours[i]) / 2.0;
372 meanColourCounts[node2Interval[nodeNum]][i] += meanColour;
373 meanColourCounts[node2Interval[parentNum]][i] -= meanColour;
374 }
375
376 }
377
378 if (!tree.isExternal(node)) {
379
380 // Note: assuming binary tree!
381 NodeRef leftChild = tree.getChild(node, 0);
382 NodeRef rightChild = tree.getChild(node, 1);
383
384 fillMeanColourCounts(tree, leftChild, colourChangeMatrix);
385 fillMeanColourCounts(tree, rightChild, colourChangeMatrix);
386
387 }
388
389 }
390
391
392 // Recursively fills meanColourCounts with derived counts for intervals;
393 // utility function for computeMeanColourCountsEM below
394 void calculateMeanColourCountsEM(Tree tree, NodeRef node, ColourChangeMatrix colourChangeMatrix) {
395
396 if (tree.isRoot(node)) {
397
398 // empty the meanColourCounts array
399 for (int clr = 0; clr < colourCount; clr++) {
400 for (int i = 0; i < meanColourCounts.length; i++) {
401 meanColourCounts[i][clr] = 0.0;
402 }
403 }
404
405 } else {
406
407 NodeRef parent = tree.getParent(node);
408 int parentNum = parent.getNumber();
409 int nodeNum = node.getNumber();
410
411 int bottomInterval = node2Interval[nodeNum];
412 int topInterval = node2Interval[parentNum];
413
414 double[] belowColours = getMeanColoursEM(nodeNum, 0, colourChangeMatrix);
415 double[] aboveColours;
416
417 for (int relInterval = 0; relInterval < topInterval - bottomInterval; relInterval++) {
418
419 int aboveInterval = relInterval + 1;
420
421 if (aboveInterval + bottomInterval < topInterval) {
422 aboveColours = getMeanColoursEM(nodeNum, aboveInterval, colourChangeMatrix);
423 } else {
424 if (!tree.isRoot(parent)) {
425 aboveColours = getMeanColoursEM(parentNum, 0, colourChangeMatrix);
426 } else {
427 aboveColours = belowColours;
428 }
429 }
430
431 for (int i = 0; i < colourCount; i++) {
432 double meanColour = (aboveColours[i] + belowColours[i]) / 2.0;
433 meanColourCounts[relInterval + bottomInterval][i] += meanColour;
434 }
435
436 belowColours = aboveColours;
437 }
438
439 }
440
441 if (!tree.isExternal(node)) {
442
443 // Note: assuming binary tree!
444 NodeRef leftChild = tree.getChild(node, 0);
445 NodeRef rightChild = tree.getChild(node, 1);
446
447 calculateMeanColourCountsEM(tree, leftChild, colourChangeMatrix);
448 calculateMeanColourCountsEM(tree, rightChild, colourChangeMatrix);
449
450 }
451
452 if (tree.isRoot(node) && debugMeanColours) {
453 for (int i = 0; i < numIntervals; i++) {
454 System.out.println("EM Interval " + i + " height=" + interval2Height[i] + " ");
455 double sum = 0.0;
456 for (int clr = 0; clr < colourCount; clr++) {
457 System.out.print("c=" + clr + " mean=" + meanColourCounts[i][clr] + " ");
458 sum += meanColourCounts[i][clr];
459 }
460 System.out.println(" sum=" + sum);
461 }
462 }
463 }
464
465
466 // Computes the meanColourCounts array for the intervals
467 void calculateMeanColourCounts(Tree tree, ColourChangeMatrix colourChangeMatrix) {
468
469 // empty the meanColourCounts array
470 for (int clr = 0; clr < colourCount; clr++) {
471 for (int i = 0; i < meanColourCounts.length; i++) {
472 meanColourCounts[i][clr] = 0.0;
473 }
474 }
475
476 // populate meanColourCounts array, so that sum of counts before and including an interval,
477 // give average colour counts for that interval.
478 fillMeanColourCounts(tree, tree.getRoot(), colourChangeMatrix);
479
480 // Sum out, so that actual count gives average colour count on interval
481 for (int clr = 0; clr < colourCount; clr++) {
482 double sum = 0.0;
483 for (int i = 0; i < meanColourCounts.length; i++) {
484 sum += meanColourCounts[i][clr];
485 meanColourCounts[i][clr] = sum;
486 }
487 }
488
489 if (debugMeanColours) {
490 for (int i = 0; i < numIntervals; i++) {
491 System.out.println("Interval " + i + " height=" + interval2Height[i] + " ");
492 double sum = 0.0;
493 for (int clr = 0; clr < colourCount; clr++) {
494 System.out.print("c=" + clr + " mean=" + meanColourCounts[i][clr] + " ");
495 sum += meanColourCounts[i][clr];
496 }
497 System.out.println(" sum=" + sum);
498 }
499 }
500 }
501
502
503 /**
504 * Calculate probability of data at descendants from node, given a color at the node ('partials'),
505 * by a Felsenstein-like pruning algorithm. (First step in the color sampling algorithm)
506 * Side effect: updates nodePartials[] for this node and all its descendants.
507 *
508 * @param node
509 * @return the partials of this node
510 */
511 private double[] prune(Tree tree, NodeRef node, ColourChangeMatrix mm) {
512
513 double[] p = new double[colourCount];
514
515 if (tree.isExternal(node)) {
516 p[getColour(node)] = 1.0;
517 } else {
518
519 // Note: assuming binary tree!
520 NodeRef leftChild = tree.getChild(node, 0);
521 NodeRef rightChild = tree.getChild(node, 1);
522
523 double[] left = prune(tree, leftChild, mm);
524 double[] right = prune(tree, rightChild, mm);
525
526 double nodeHeight = tree.getNodeHeight(node);
527
528 double leftTime = nodeHeight - tree.getNodeHeight(tree.getChild(node, 0));
529 double rightTime = nodeHeight - tree.getNodeHeight(tree.getChild(node, 1));
530
531 double maxp = 0.0;
532 for (int i = 0; i < colourCount; i++) {
533
534 double leftSum = 0.0;
535 double rightSum = 0.0;
536
537 // looping over colours in left and right children
538 for (int j = 0; j < colourCount; j++) {
539 // forwardTimeEvolution conditions on the parent state i, i.e. time
540 // runs in the natural direction (forward from parent to child)
541 leftSum += mm.forwardTimeEvolution(i, j, leftTime) * left[j];
542 rightSum += mm.forwardTimeEvolution(i, j, rightTime) * right[j];
543 }
544 p[i] = leftSum * rightSum;
545 // This version does not condition on the formal variable, because
546 // that tends to bias towards the small population, whereas no correction
547 // for bias towards the large population on branches is made at this stage
548
549 if (p[i] > maxp) {
550 maxp = p[i];
551 }
552
553 }
554
555 // take care of underflow
556 if (maxp < 1.0e-100) {
557 for (int i = 0; i < colourCount; i++) {
558 p[i] *= 1.0e+100;
559 }
560 logNodePartialsRescaling -= Math.log(1.0e+100);
561 }
562
563 }
564
565 nodePartials[node.getNumber()] = p;
566
567 if (debugNodePartials) {
568 prettyPrint("Node " + node.getNumber() + " prune=", p);
569 }
570
571 return p;
572 }
573
574
575 /* Calculates the result of multiplying the vector vec with the matrix Exp[{{-a,b},{c,-d}}] */
576 static double[] matrixEvolve(double[] mx, int current) {
577
578 double a = mx[0];
579 double b = mx[1];
580 double c = mx[2];
581 double d = mx[3];
582
583 /*
584 double[] vec = new double[2];
585 vec[current] = 1.0;
586 double S = Math.sqrt( (a-d)*(a-d) + 4*b*c );
587 double c00,c01,c10,c11;
588 if (S < 1.0e-5 ) {
589 c00 = Math.exp( -a );
590 c11 = Math.exp( -d );
591 c01 = b*c00;
592 c10 = c*c11;
593 } else {
594 double T = Math.exp( -(a+d+S)/2.0 );
595 double U = Math.exp( -(a+d-S)/2.0 );
596 c00 = ( (d-a+S)*U - (d-a-S)*T ) / (2*S);
597 c01 = ( b*(U-T) ) / S;
598 c10 = ( c*(U-T) ) / S;
599 c11 = ( (a-d+S)*U - (a-d-S)*T ) / (2*S);
600 }
601 double v0 = vec[0] * c00 + vec[1] * c10;
602 vec[1] = vec[0] * c01 + vec[1] * c11;
603 vec[0] = v0;
604 return vec;
605 */
606
607 double S = Math.sqrt((a - d) * (a - d) + 4 * b * c);
608 if (S < 1.0e-5) {
609 if (current == 0) {
610 a = Math.exp(-a);
611 return new double[]{a, b * a};
612 } else {
613 d = Math.exp(-d);
614 return new double[]{c * d, d};
615 }
616 } else {
617 double T = Math.exp(-(a + d + S) / 2.0);
618 double U = Math.exp(-(a + d - S) / 2.0);
619 if (current == 0) {
620 return new double[]{((d - a + S) * U - (d - a - S) * T) / (2 * S), (b * (U - T)) / S};
621 } else {
622 return new double[]{(c * (U - T)) / S, ((a - d + S) * U - (a - d - S) * T) / (2 * S)};
623 }
624 }
625 }
626
627
628 /* Calculates the result of multiplying the matrix Exp[{{-a,b},{c,-d}}] with vec */
629 static void matrixPullBack(double[] mx, double[] vec) {
630
631 double a = mx[0];
632 double b = mx[1];
633 double c = mx[2];
634 double d = mx[3];
635
636 double S = Math.sqrt((a - d) * (a - d) + 4 * b * c);
637 double c00, c01, c10, c11;
638 if (S < 1.0e-5) {
639 c00 = Math.exp(-a);
640 c11 = Math.exp(-d);
641 c01 = b * c00;
642 c10 = c * c11;
643 } else {
644 double T = Math.exp(-(a + d + S) / 2.0);
645 double U = Math.exp(-(a + d - S) / 2.0);
646 c00 = ((d - a + S) * U - (d - a - S) * T) / (2 * S);
647 c01 = (b * (U - T)) / S;
648 c10 = (c * (U - T)) / S;
649 c11 = ((a - d + S) * U - (a - d - S) * T) / (2 * S);
650 }
651 double v0 = vec[0] * c00 + vec[1] * c01;
652 vec[1] = vec[0] * c10 + vec[1] * c11;
653 vec[0] = v0;
654 }
655
656
657 double[] calculateMatrixElts(int curinterval, NodeRef affectedNode, Tree tree, double time, double N0, double N1, ColourChangeMatrix mm) {
658
659 double meancolour0 = meanColourCounts[curinterval][0];
660 double meancolour1 = meanColourCounts[curinterval][1];
661 double lineages = meancolour0 + meancolour1;
662
663 // get coalescent rate for colour 0
664 double coalescent0 = ((propAffected * (lineages - 1)) + (1.0 - propAffected) * (meancolour0 - 1)) / (2.0 * N0) * time;
665 if (coalescent0 < 0.0) {
666 coalescent0 = 0.0;
667 }
668 // same for colour 1
669 double coalescent1 = ((propAffected * (lineages - 1)) + (1.0 - propAffected) * (meancolour1 - 1)) / (2.0 * N1) * time;
670 if (coalescent1 < 0.0) {
671 coalescent1 = 0.0;
672 }
673 if (!useBranchBias) {
674 coalescent0 = 0.0;
675 coalescent1 = 0.0;
676 }
677 // partial conditioning on survival; take away coalescences that are
678 // common to both colours
679 double commonCoalescentRate = Math.min(coalescent0, coalescent1);
680 /* debug */
681 //commonCoalescentRate = 0.0;
682 coalescent0 -= commonCoalescentRate;
683 coalescent1 -= commonCoalescentRate;
684 // get forward rates
685 double fwrate01 = mm.getForwardRate(0, 1) * time;
686 double fwrate10 = mm.getForwardRate(1, 0) * time;
687 // next, evolve 'with leakage'. Matrix:
688 // 0->1 : rate01; diagonal 0 : -rate01-coalescent0
689 // 1->0 : rate10; diagonal 1 : -rate10-coalescent1
690 return new double[]{fwrate01 + coalescent0, fwrate01, fwrate10, fwrate10 + coalescent1};
691 }
692
693
694 /* Calculates partial branch probabilities with mean-field coalescent correction */
695 /* Inputs are the partials at the child node; results on branch are stored in nodePartialsEM[][][] */
696 /* This version is for two colours only */
697 double[] pruneBranchEM(ColourChangeMatrix mm, double[] inState, NodeRef parent, NodeRef child, Tree tree, MetaPopulation mp) {
698
699 // Get interval above parent (highest) and above child (lowest)
700 int topInterval = node2Interval[parent.getNumber()];
701 int bottomInterval = node2Interval[child.getNumber()];
702
703 // Make a result array and a current state
704 double[][] partials = new double[topInterval - bottomInterval][2];
705 double[] state = inState.clone();
706 int curinterval = bottomInterval;
707
708 while (curinterval != topInterval) {
709
710 // Store current state
711 partials[curinterval - bottomInterval][0] = state[0];
712 partials[curinterval - bottomInterval][1] = state[1];
713 // Calculate partials at top of current interval
714 double time = interval2Height[curinterval + 1] - interval2Height[curinterval];
715 //double effectiveN0 = time / mp.getIntegral( lowertime, uppertime, 0 );
716 //double effectiveN1 = time / mp.getIntegral( lowertime, uppertime, 1 );
717 double[] mxElts = calculateMatrixElts(curinterval, child, tree, time, avgN0[curinterval], avgN1[curinterval], mm);
718 matrixPullBack(mxElts, state);
719 // update for next interval
720 curinterval += 1;
721 }
722
723 // Store branch partials (including child's, excluding parent's) at child
724 nodePartialsEM[child.getNumber()] = partials;
725
726 // Return parent's partials
727 return state;
728 }
729
730
731 /**
732 * Calculate probability of data at descendants from node, given a color at the node ('partials'),
733 * by a Felsenstein-like pruning algorithm. (First step in the color sampling algorithm)
734 * Side effect: updates nodePartials[] and nodePartialsEM[][] for this node and all its descendants.
735 * This version uses mean-field coalescence correction and formal variable correction
736 */
737 private double[] pruneEM(Tree tree, NodeRef node, ColourChangeMatrix mm, MetaPopulation mp) {
738
739 double[] p = new double[colourCount];
740
741 if (tree.isExternal(node)) {
742
743 p[getColour(node)] = 1.0;
744
745 } else {
746
747 // Note: assuming binary tree!
748 NodeRef leftChild = tree.getChild(node, 0);
749 NodeRef rightChild = tree.getChild(node, 1);
750
751 // Obtain partials at the child nodes
752 double[] left = pruneEM(tree, leftChild, mm, mp);
753 double[] right = pruneEM(tree, rightChild, mm, mp);
754
755 // Calculate partials at parent node
756 // (Side effect: calculates partials for each interval along branch in nodePartialsEM)
757 double[] leftBranchPartials = pruneBranchEM(mm, left, node, leftChild, tree, mp);
758 double[] rightBranchPartials = pruneBranchEM(mm, right, node, rightChild, tree, mp);
759
760 double maxp = 0.0;
761 for (int i = 0; i < colourCount; i++) {
762
763 p[i] = leftBranchPartials[i] * rightBranchPartials[i];
764
765 // Condition on the formal variable
766 if (useNodeBias) {
767 p[i] *= mm.getEquilibrium(i) / mp.getDemographic(tree.getNodeHeight(node) - tinyTime, i);
768 }
769
770 if (p[i] > maxp) {
771 maxp = p[i];
772 }
773
774 }
775
776 // take care of underflow
777 if (maxp < 1.0e-100) {
778 for (int i = 0; i < colourCount; i++) {
779 p[i] *= 1.0e+100;
780 }
781 logNodePartialsRescaling -= Math.log(1.0e+100);
782 }
783
784 }
785
786 // Store results for the sampling step
787 nodePartials[node.getNumber()] = p;
788
789 if (debugNodePartials) {
790 prettyPrint("Node " + node.getNumber() + " pruneEM=", p);
791 }
792
793 return p;
794 }
795
796
797 /**
798 * Samples internal node colours (from root to tips) and events
799 * Precondition: parent node has been sampled, descendants have not
800 * Requires the results from Felsenstein Backwards pruning, in nodePartials(EM)[] (see pruneEM())
801 * Side effect: updates nodeColours[]
802 */
803 private double sampleEM(Tree tree, NodeRef node, ColourChangeMatrix mm, MetaPopulation mp, DefaultTreeColouring colouring) {
804
805 double[] forward;
806 double[] posterior;
807 int colour;
808 DefaultBranchColouring history = null;
809 double logLikelihood = 0.0;
810
811 if (tree.isRoot(node)) {
812
813 _totalIntegratedRate = 0.0; /* for debugging */
814
815 forward = mm.getEquilibrium();
816 double[] backward = nodePartials[node.getNumber()];
817 posterior = new double[colourCount];
818 double max = -1.0;
819 double min = 1.0;
820 for (int i = 0; i < forward.length; i++) {
821 posterior[i] = forward[i] * backward[i];
822 max = Math.max(max, posterior[i]);
823 min = Math.min(min, posterior[i]);
824 }
825 if (debugMessages && min < 0.0) {
826 System.out.println("Aargh, negative probabilities " + min + " " + max);
827 }
828 if (debugMessages && max < 1.0e-200) {
829 System.out.println("Hmm, very small numbers indeed " + max);
830 }
831 // Sample a colour
832 colour = MathUtils.randomChoicePDF(posterior);
833 // Add likelihood of (unconditional) probability
834 logLikelihood += Math.log(forward[colour]);
835
836 } else {
837
838 int nodeNum = node.getNumber();
839 double[][] backward = nodePartialsEM[nodeNum];
840 int bottomInterval = node2Interval[nodeNum];
841 // Allocate array for interval node colours
842 nodeColoursEM[nodeNum] = new int[backward.length];
843 // Start from parent, and sample colours for interval nodes
844 colour = getColour(tree.getParent(node));
845 // Allocate event history
846 history = new DefaultBranchColouring(colour, colour);
847 // Allocate posterior probabilities
848 posterior = new double[colourCount];
849
850 // Go down the branch (from parent to child)
851 for (int relinterval = backward.length - 1; relinterval >= 0; relinterval--) {
852
853 int interval = relinterval + bottomInterval;
854 double childHeight = interval2Height[interval];
855 double uppertime = interval2Height[interval + 1];
856 double time = uppertime - childHeight;
857 double[] mxElts = calculateMatrixElts(interval, node, tree, time, avgN0[interval], avgN1[interval], mm);
858 forward = matrixEvolve(mxElts, colour);
859 // Calculate posterior for interval node
860 for (int i = 0; i < colourCount; i++) {
861 posterior[i] = forward[i] * backward[relinterval][i];
862 }
863 // Sample a colour
864 int childColour = MathUtils.randomChoicePDF(posterior);
865 // Store colour
866 nodeColoursEM[nodeNum][relinterval] = childColour;
867 // Sample events conditional on parent and child colour
868 //System.out.println("node="+node.getNumber()+" parent="+colour+" child="+childColour+" interval="+relinterval+" time="+time);
869 logLikelihood += sampleConditionalBranchColouringEM(node, colour, childColour, time, childHeight, mxElts, history);
870
871 // update colour
872 colour = childColour;
873 }
874
875 // Store history for branch at child node
876 colouring.setBranchColouring(node, history);
877 }
878
879 // store colour in node
880 setColour(node, colour);
881
882 // add contribution of formal variable - except if this is a leaf,
883 // since there is no corresponding coalescent event
884 if (!tree.isExternal(node) && useNodeBias) {
885 double childTime = tree.getNodeHeight(node);
886 logLikelihood += Math.log(mm.getEquilibrium(colour) / mp.getDemographic(childTime - tinyTime, colour));
887 }
888
889 // Recursively sample down the tree
890 for (int i = 0; i < tree.getChildCount(node); i++) {
891 NodeRef child = tree.getChild(node, i);
892 logLikelihood += sampleEM(tree, child, mm, mp, colouring);
893 }
894
895 if (debugSampleLikelihoods && tree.isRoot(node)) {
896 System.out.println("Sampled likelihood " + logLikelihood);
897 System.out.println("Integrated exit rate " + _totalIntegratedRate);
898 System.out.println("sampleEMProposal node=" + node.getNumber() + " logL=" + logLikelihood);
899 }
900
901 //System.out.println("sampleEM node="+node.getNumber()+"\tlogL="+logLikelihood);
902
903 return logLikelihood;
904 }
905
906 /**
907 * This samples events along an interval, and adds these events to a BranchColouring.
908 * Also returns the (unconditional) log probability density for these events
909 */
910 private double sampleConditionalBranchColouringEM(
911 NodeRef node,
912 int parentColour,
913 int childColour,
914 double time,
915 double childHeight,
916 double[] matrixElements,
917 DefaultBranchColouring initialBranchColouring) {
918
919 DefaultBranchColouring history = new DefaultBranchColouring(parentColour, childColour);
920
921 int iterations = 0;
922 int currentColour;
923 double currentHeight, dt;
924 double logLikelihood;
925 boolean reject, firstEvent;
926 double _sumRate = 0.0;
927 String _msg = "";
928
929 // Reject until we get the child colour
930 do {
931
932 history.clear();
933 currentColour = parentColour;
934 currentHeight = time;
935 logLikelihood = 0.0;
936 reject = false;
937 firstEvent = true;
938 if (debugRejectionSampler) {
939 _sumRate = 0.0;
940 _msg = "sample (iter=" + iterations + ") from " + parentColour + " to " + childColour + " at " + df.format(childHeight) + " over " + df.format(time) + " rate=" + df.format(matrixElements[3 * parentColour] / time) + "\n";
941 }
942
943 // Sample events until we reach the child
944 do {
945
946 // Sample a waiting time
947 double totalRate, migrationRate;
948 if (currentColour == 0) {
949 totalRate = matrixElements[0] / time;
950 migrationRate = matrixElements[1] / time;
951 } else {
952 totalRate = matrixElements[3] / time;
953 migrationRate = matrixElements[2] / time;
954 }
955 double U;
956
957 do {
958 U = MathUtils.nextDouble();
959 } while (U == 0.0);
960
961 // Neat trick (Rasmus Nielsen):
962 // If colours of parent and child differ, condition on at least 1 event
963 if (firstEvent && (parentColour != childColour)) {
964
965 double minU = Math.exp(-totalRate * time);
966 U = minU + U * (1.0 - minU);
967
968 }
969
970 // Calculate the waiting time, and update currentHeight
971 dt = -Math.log(U) / totalRate;
972 currentHeight -= dt;
973
974 if (currentHeight > 0) {
975 // Not yet reached the child. Sample an event.
976 // Neat trick II: condition on first event being a migration event
977 // Also, don't bother calculating a random sample if coalescent events
978 // have zero rate
979 if (debugRejectionSampler) {
980 _sumRate += totalRate * dt;
981 _msg = _msg + "rate=" + df.format(totalRate) + "\ttime=" + df.format(dt) + "\tintrate=" + df.format(totalRate * dt) + "\n";
982 }
983
984 if (firstEvent ||
985 (migrationRate == totalRate) ||
986 (MathUtils.nextDouble() < migrationRate / totalRate)) {
987 // migration event
988 //System.out.println("Event height="+(currentHeight + childHeight));
989 currentColour = 1 - currentColour;
990 // Add it to the list
991 history.addEvent(currentColour, currentHeight + childHeight);
992
993 // Update likelihood
994 logLikelihood += (-totalRate * dt) + Math.log(migrationRate);
995
996 // ... replaces this to keep in log space
997 // likelihood *= Math.exp( -totalRate * dt ) * migrationRate;
998 } else {
999 // coalescent event
1000 reject = true;
1001 }
1002 } else {
1003 if (debugRejectionSampler) {
1004 _sumRate += totalRate * (currentHeight + dt);
1005 _msg = _msg + "rate=" + df.format(totalRate) + "\ttime=" + df.format(currentHeight + dt) + "\tintrate=" + df.format(totalRate * (currentHeight + dt)) + "\n";
1006 }
1007 // Update likelihood, no event until child
1008 //System.out.println(" totalRate="+totalRate+" dt="+(currentHeight+dt)+" time="+time);
1009
1010 logLikelihood += -totalRate * (currentHeight + dt);
1011 // ... replaces this to keep in log space
1012 //likelihood *= Math.exp( -totalRate * (currentHeight + dt) );
1013 }
1014
1015 firstEvent = false;
1016
1017 } while ((!reject) && (currentHeight > 0));
1018
1019 iterations += 1;
1020 if (currentColour != childColour) {
1021 reject = true;
1022 }
1023
1024 } while (reject && (iterations < maxIterations));
1025
1026 if (debugRejectionSampler) {
1027 _totalIntegratedRate += _sumRate;
1028 System.out.print(_msg);
1029 }
1030
1031 if (reject) {
1032 // Extreme migration rates may cause difficulty for the rejection sampler
1033 // Print a warning and add a bogus event somewhat near where you'd want it.
1034 if (currentColour != childColour) {
1035 double previousEventHeight = currentHeight + dt;
1036 double finalEventHeight = 0.01 * previousEventHeight;
1037 history.addEvent(childColour, finalEventHeight + childHeight);
1038
1039 if (debugMessages) {
1040 System.out.println("dr.evolution.colouring.BranchColourSampler: failed to generate sample after " + maxIterations + " trials.");
1041 System.out.println(": height=" + time);
1042 System.out.println(": childColour=" + childColour);
1043 System.out.println(": childHeight=" + childHeight);
1044 System.out.println(": migration rate 0->1 = " + matrixElements[1]);
1045 System.out.println(": migration rate 1->0 = " + matrixElements[2]);
1046 System.out.println(": total rate 0 = " + matrixElements[0]);
1047 System.out.println(": total rate 1 = " + matrixElements[3]);
1048 }
1049 }
1050 }
1051
1052 // Add this interval's history to the previously sampled history
1053 initialBranchColouring.addHistory(history);
1054
1055 //System.out.println("sampleConditionalBranchColouringEM child="+node.getNumber()+"\tchildH="+childHeight+"\tlogL="+Math.log(likelihood)+"\tevents="+history.getNumEvents()+"\tfinal clr="+childColour);
1056
1057 return logLikelihood;
1058 }
1059
1060
1061 /**
1062 * Calculates proposal density for given colouring
1063 * Requires the results from Felsenstein Backwards pruning, in nodePartials(EM)[] (see pruneEM())
1064 */
1065 private double calculateEMProposal(Tree tree, NodeRef node, ColourChangeMatrix mm, MetaPopulation mp, TreeColouring colouring) {
1066
1067 double[] forward;
1068 int colour;
1069 BranchColouring history = null;
1070 double logLikelihood = 0.0;
1071
1072 if (tree.isRoot(node)) {
1073
1074 forward = mm.getEquilibrium();
1075 // Get root colour
1076 colour = colouring.getNodeColour(node);
1077 // Add likelihood of (unconditional) probability
1078 logLikelihood += Math.log(forward[colour]);
1079
1080 } else {
1081
1082 int nodeNum = node.getNumber();
1083 double[][] backward = nodePartialsEM[nodeNum];
1084 int bottomInterval = node2Interval[nodeNum];
1085 // Get branch colouring
1086 history = colouring.getBranchColouring(node);
1087
1088 // Go down the branch (from parent to child)
1089 for (int relinterval = backward.length - 1; relinterval >= 0; relinterval--) {
1090
1091 int interval = relinterval + bottomInterval;
1092 double childHeight = interval2Height[interval];
1093 double uppertime = interval2Height[interval + 1];
1094 double time = uppertime - childHeight;
1095 double[] mxElts = calculateMatrixElts(interval, node, tree, time, avgN0[interval], avgN1[interval], mm);
1096 logLikelihood += calculateConditionalBranchColouringEM(node, time, childHeight, mxElts, history);
1097 }
1098
1099 colour = colouring.getNodeColour(node);
1100
1101 }
1102
1103 if (!tree.isExternal(node) && useNodeBias) {
1104 double childTime = tree.getNodeHeight(node);
1105 logLikelihood += Math.log(mm.getEquilibrium(colour) / mp.getDemographic(childTime - tinyTime, colour));
1106 }
1107
1108 // Recursively sample down the tree
1109 for (int i = 0; i < tree.getChildCount(node); i++) {
1110 NodeRef child = tree.getChild(node, i);
1111 logLikelihood += calculateEMProposal(tree, child, mm, mp, colouring);
1112 }
1113
1114 //System.out.println("calculateEMProposal node="+node.getNumber()+"\tlogL="+logLikelihood);
1115
1116 return logLikelihood;
1117 }
1118
1119 /**
1120 * This samples events along an interval, and adds these events to a BranchColouring.
1121 * Also returns the (unconditional) log probability density for these events
1122 */
1123 private double calculateConditionalBranchColouringEM(
1124 NodeRef node,
1125 double time,
1126 double childHeight,
1127 double[] matrixElements,
1128 BranchColouring branchColouring) {
1129
1130 double currentHeight = time + childHeight;
1131 int nextEvent = branchColouring.getNextForwardEvent(currentHeight);
1132 int currentColour = branchColouring.getForwardColourBelow(nextEvent - 1);
1133 double logLikelihood = 0.0;
1134 int numEvents = 0;
1135
1136 while (currentHeight > childHeight) {
1137
1138 double nextEventHeight;
1139 //System.out.println("nextEvent="+nextEvent+" total="+branchColouring.getNumEvents());
1140 if (nextEvent == branchColouring.getNumEvents() + 1) {
1141 nextEventHeight = childHeight - 1.0; // past child
1142 } else {
1143 nextEventHeight = branchColouring.getForwardTime(nextEvent);
1144 //System.out.println("Event height="+nextEventHeight);
1145 }
1146
1147 double dt = currentHeight - nextEventHeight;
1148
1149 double totalRate, migrationRate;
1150 if (currentColour == 0) {
1151 totalRate = matrixElements[0] / time;
1152 migrationRate = matrixElements[1] / time;
1153 } else {
1154 totalRate = matrixElements[3] / time;
1155 migrationRate = matrixElements[2] / time;
1156 }
1157
1158 if (nextEventHeight < childHeight) {
1159 // no event - include exit probability, and done.
1160 dt = currentHeight - childHeight;
1161 //System.out.println(" totalRate="+totalRate+" dt="+dt+" time="+time);
1162
1163 logLikelihood += -totalRate * dt;
1164 // ... replaces this to keep in log space
1165 //likelihood *= Math.exp( -totalRate * dt );
1166 } else {
1167 // proper migration event
1168
1169 logLikelihood += (-totalRate * dt) + Math.log(migrationRate);
1170 // ... replaces this to keep in log space
1171 //likelihood *= Math.exp( -totalRate * dt ) * migrationRate;
1172
1173 currentColour = branchColouring.getForwardColourBelow(nextEvent);
1174 numEvents += 1;
1175 }
1176
1177 currentHeight = nextEventHeight;
1178 nextEvent += 1;
1179
1180 }
1181
1182 //System.out.println("calculateConditionalBranchColouring child="+node.getNumber()+"\tchildH="+childHeight+"\tlogL="+Math.log(likelihood)+"\tevents="+numEvents+"\tfinal clr="+currentColour);
1183
1184 return logLikelihood;
1185 }
1186
1187
1188 private void prettyPrint(String label, double[] vec) {
1189 System.out.print(label + "= (");
1190 for (double x : vec) {
1191 System.out.print(x + ", ");
1192
1193 }
1194 System.out.println(")");
1195
1196 }
1197
1198 // Testing code
1199 static void testMatrix(double[] m, double[] r) {
1200 if (Math.abs(matrixEvolve(m, 0)[0] - r[0]) > 1.0e-6) {
1201 throw new Error("1");
1202 }
1203 if (Math.abs(matrixEvolve(m, 0)[1] - r[1]) > 1.0e-6) {
1204 throw new Error("2");
1205 }
1206 if (Math.abs(matrixEvolve(m, 1)[0] - r[2]) > 1.0e-6) {
1207 throw new Error("3");
1208 }
1209 if (Math.abs(matrixEvolve(m, 1)[1] - r[3]) > 1.0e-6) {
1210 throw new Error("4");
1211 }
1212 double vec0[] = {1, 0};
1213 double vec1[] = {0, 1};
1214 matrixPullBack(m, vec0);
1215 matrixPullBack(m, vec1);
1216 if (Math.abs(vec0[0] - r[0]) > 1.0e-6) {
1217 throw new Error("5");
1218 }
1219 if (Math.abs(vec0[1] - r[2]) > 1.0e-6) {
1220 throw new Error("7");
1221 }
1222 if (Math.abs(vec1[0] - r[1]) > 1.0e-6) {
1223 throw new Error("6");
1224 }
1225 if (Math.abs(vec1[1] - r[3]) > 1.0e-6) {
1226 throw new Error("8");
1227 }
1228 }
1229
1230 public static void main(String[] args) {
1231
1232 double m[] = {5.0, 3.0, 2.0, 3.0};
1233 double result[] = {0.0811818, 0.145616, 0.097077, 0.178259};
1234 testMatrix(m, result);
1235 System.out.println("First matrix OK");
1236 double m2[] = {1.0, 1.0, 0.0, 1.0};
1237 double result2[] = {0.367879, 0.367879, 0, 0.367879};
1238 testMatrix(m2, result2);
1239 System.out.println("Second matrix OK");
1240 double m3[] = {1.0, 0.0, 1.0, 1.0};
1241 double result3[] = {0.367879, 0.0, 0.367879, 0.367879};
1242 testMatrix(m3, result3);
1243 System.out.println("Third matrix OK");
1244
1245 }
1246
1247 private final int colourCount;
1248
1249 private final int[] nodeColours;
1250
1251 private final int[] leafColourCounts;
1252
1253 private double[][] meanColourCounts; // [i][c] = approximate number of lineages coloured c in interval i
1254
1255 private int[][] nodeColoursEM; // [n][r] = colour of lineage above node n and interval r (relative)
1256
1257 private double[][] nodePartials; // [node][colour] = p(descendant data | node colour)
1258
1259 private double[][][] nodePartialsEM; // [node][rel.interval][colour] = p(desc | node clr)
1260
1261 private double logNodePartialsRescaling; // rescaling factor to prevent underflow
1262
1263 private double[] equilibriumColours;
1264
1265 private int[] node2Interval; // linear index for interval corresponding to (child) node
1266
1267 private double[] interval2Height;
1268
1269 private double[] avgN0;
1270 private double[] avgN1;
1271
1272 private int numIntervals;
1273 }