Debian Codegraph @

src/dr/evomodel/continuous/IntegratedMultivariateTraitLikelihood.java

raw symbols SCIP
1 /*
2 * IntegratedMultivariateTraitLikelihood.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.continuous;
27
28 import dr.evolution.tree.MutableTreeModel;
29 import dr.evolution.tree.NodeRef;
30 import dr.evolution.tree.Tree;
31 import dr.evomodel.branchratemodel.BranchRateModel;
32 import dr.inference.loggers.LogColumn;
33 import dr.inference.model.CompoundParameter;
34 import dr.inference.model.Model;
35 import dr.inference.model.Parameter;
36 import dr.inference.model.Variable;
37 import dr.math.distributions.MultivariateNormalDistribution;
38 import dr.math.distributions.WishartSufficientStatistics;
39 import dr.math.matrixAlgebra.Matrix;
40 import dr.math.matrixAlgebra.SymmetricMatrix;
41 import dr.math.matrixAlgebra.Vector;
42 import dr.util.Author;
43 import dr.util.Citation;
44
45 import java.util.*;
46
47 /**
48 * A multivariate trait likelihood that analytically integrates out the unobserved trait values at all internal
49 * and root nodes
50 *
51 * @author Marc A. Suchard
52 */
53 public abstract class IntegratedMultivariateTraitLikelihood extends AbstractMultivariateTraitLikelihood {
54
55 public static final double LOG_SQRT_2_PI = 0.5 * Math.log(2 * Math.PI);
56
57 // public IntegratedMultivariateTraitLikelihood(String traitName,
58 // MutableTreeModel treeModel,
59 // MultivariateDiffusionModel diffusionModel,
60 // CompoundParameter traitParameter,
61 // List<Integer> missingIndices,
62 // boolean cacheBranches, boolean scaleByTime, boolean useTreeLength,
63 // BranchRateModel rateModel, Model samplingDensity,
64 // boolean reportAsMultivariate,
65 // boolean reciprocalRates) {
66 //
67 // this(traitName, treeModel, diffusionModel, traitParameter, null, missingIndices, cacheBranches, scaleByTime,
68 // useTreeLength, rateModel, samplingDensity, reportAsMultivariate, reciprocalRates);
69 // }
70 //
71 // public IntegratedMultivariateTraitLikelihood(String traitName,
72 // MutableTreeModel treeModel,
73 // MultivariateDiffusionModel diffusionModel,
74 // CompoundParameter traitParameter,
75 // Parameter deltaParameter,
76 // List<Integer> missingIndices,
77 // boolean cacheBranches, boolean scaleByTime, boolean useTreeLength,
78 // BranchRateModel rateModel, Model samplingDensity,
79 // boolean reportAsMultivariate,
80 // boolean reciprocalRates) {
81 // this(traitName, treeModel, diffusionModel, traitParameter, deltaParameter, missingIndices, cacheBranches,
82 // scaleByTime, useTreeLength, rateModel, null, samplingDensity, reportAsMultivariate, reciprocalRates);
83 // }
84
85
86 protected final CacheHelper cacheHelper;
87
88 public IntegratedMultivariateTraitLikelihood(String traitName,
89 MutableTreeModel treeModel,
90 MultivariateDiffusionModel diffusionModel,
91 CompoundParameter traitParameter,
92 Parameter deltaParameter,
93 List<Integer> missingIndices,
94 boolean cacheBranches, boolean scaleByTime, boolean useTreeLength,
95 BranchRateModel rateModel,
96 List<BranchRateModel> driftModels,
97 List<BranchRateModel> optimalValues,
98 BranchRateModel strengthOfSelection,
99 Model samplingDensity,
100 List<RestrictedPartials> clamps,
101 boolean reportAsMultivariate,
102 boolean reciprocalRates) {
103
104 super(traitName, treeModel, diffusionModel, traitParameter, deltaParameter, missingIndices, cacheBranches, scaleByTime,
105 useTreeLength, rateModel, driftModels,
106 optimalValues, strengthOfSelection,
107 samplingDensity, reportAsMultivariate, reciprocalRates);
108
109
110 partialsCount = treeModel.getNodeCount();
111 if (clamps != null) {
112 for (RestrictedPartials partials : clamps) {
113 partials.setIndex(partialsCount);
114 addRestrictedPartials(partials);
115 ++partialsCount;
116 }
117 spareIndex = partialsCount;
118 ++partialsCount;
119 setupClamps();
120 }
121
122 // Delegate caches to helper
123 // meanCache = new double[dim * treeModel.getNodeCount()];
124 if (driftModels != null) {
125 cacheHelper = new DriftCacheHelper(dim * partialsCount, cacheBranches); // new DriftCacheHelper ....
126 } else if (optimalValues != null) {
127 cacheHelper = new OUCacheHelper(dim * partialsCount, cacheBranches);
128 } else {
129 cacheHelper = new CacheHelper(dim * partialsCount, cacheBranches);
130 }
131
132 drawnStates = new double[dim * partialsCount];
133 upperPrecisionCache = new double[partialsCount];
134 lowerPrecisionCache = new double[partialsCount];
135 logRemainderDensityCache = new double[partialsCount];
136
137 if (cacheBranches) {
138 // storedMeanCache = new double[dim * treeModel.getNodeCount()];
139 storedUpperPrecisionCache = new double[partialsCount];
140 storedLowerPrecisionCache = new double[partialsCount];
141 storedLogRemainderDensityCache = new double[partialsCount];
142 }
143
144 // Set up reusable temporary storage
145 Ay = new double[dimTrait];
146 tmpM = new double[dimTrait][dimTrait];
147 tmp2 = new double[dimTrait];
148
149 zeroDimVector = new double[dim];
150
151 missingTraits = new MissingTraits.CompletelyMissing(treeModel, missingIndices, dim);
152 setTipDataValuesForAllNodes();
153
154 }
155
156 // public IntegratedMultivariateTraitLikelihood(String traitName,
157 // MutableTreeModel treeModel,
158 // MultivariateDiffusionModel diffusionModel,
159 // CompoundParameter traitParameter,
160 // Parameter deltaParameter,
161 // List<Integer> missingIndices,
162 // boolean cacheBranches, boolean scaleByTime, boolean useTreeLength,
163 // BranchRateModel rateModel,
164 // List<BranchRateModel> optimalValues,
165 // BranchRateModel strengthOfSelection,
166 // Model samplingDensity,
167 // boolean reportAsMultivariate,
168 // boolean reciprocalRates) {
169 //
170 // super(traitName, treeModel, diffusionModel, traitParameter, deltaParameter, missingIndices, cacheBranches, scaleByTime,
171 // useTreeLength, rateModel, optimalValues, strengthOfSelection, samplingDensity, reportAsMultivariate, reciprocalRates);
172 //
173 // // Delegate caches to helper
174 // meanCache = new double[dim * treeModel.getNodeCount()];
175 //
176 // if (optimalValues != null) {
177 // cacheHelper = new OUCacheHelper(dim * treeModel.getNodeCount(), cacheBranches);
178 // } else {
179 // cacheHelper = new CacheHelper(dim * treeModel.getNodeCount(), cacheBranches);
180 // }
181 //
182 //
183 // drawnStates = new double[dim * treeModel.getNodeCount()];
184 // upperPrecisionCache = new double[treeModel.getNodeCount()];
185 // lowerPrecisionCache = new double[treeModel.getNodeCount()];
186 // logRemainderDensityCache = new double[treeModel.getNodeCount()];
187 //
188 // if (cacheBranches) {
189 // storedMeanCache = new double[dim * treeModel.getNodeCount()];
190 // storedUpperPrecisionCache = new double[treeModel.getNodeCount()];
191 // storedLowerPrecisionCache = new double[treeModel.getNodeCount()];
192 // storedLogRemainderDensityCache = new double[treeModel.getNodeCount()];
193 // }
194 //
195 // // Set up reusable temporary storage
196 // Ay = new double[dimTrait];
197 // tmpM = new double[dimTrait][dimTrait];
198 // tmp2 = new double[dimTrait];
199 //
200 // zeroDimVector = new double[dim];
201 //
202 // missingTraits = new MissingTraits.CompletelyMissing(treeModel, missingIndices, dim);
203 // setTipDataValuesForAllNodes();
204 //
205 // }
206
207
208 private void setTipDataValuesForAllNodes() {
209 for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
210 NodeRef node = treeModel.getExternalNode(i);
211 setTipDataValuesForNode(node);
212 }
213 missingTraits.handleMissingTips();
214 }
215
216 @SuppressWarnings("unused")
217 public double getTotalTreePrecision() {
218 getLogLikelihood(); // Do peeling if necessary
219 final int rootIndex = treeModel.getRoot().getNumber();
220 return lowerPrecisionCache[rootIndex];
221 }
222
223 private void setTipDataValuesForNode(NodeRef node) {
224 // Set tip data values
225 int index = node.getNumber();
226 double[] traitValue = traitParameter.getParameter(index).getParameterValues();
227 if (traitValue.length < dim) {
228 throw new RuntimeException("The trait parameter for the tip with index, " + index + ", is too short");
229 }
230
231 cacheHelper.setTipMeans(traitValue, dim, index, node);
232 // System.arraycopy(traitValue, 0, meanCache
233 //// cacheHelper.getMeanCache()
234 // , dim * index, dim);
235 }
236
237 public double[] getTipDataValues(int index) {
238 double[] traitValue = new double[dim];
239 System.arraycopy(cacheHelper.getMeanCache(), dim * index, traitValue, 0, dim);
240 return traitValue;
241 }
242
243 public void setTipDataValuesForNode(int index, double[] traitValue) {
244 // Set tip data values
245 // cacheHelper.copyToMeanCache(traitValue, dim*index, dim);
246 cacheHelper.setTipMeans(traitValue, dim, index);
247 //System.arraycopy(traitValue, 0, meanCache, dim * index, dim);
248 makeDirty();
249 }
250
251 protected String extraInfo() {
252 return "\tSample internal node traits: false\n";
253 }
254
255 @Override
256 public Citation.Category getCategory() {
257 return Citation.Category.TRAIT_MODELS;
258 }
259
260 @Override
261 public String getDescription() {
262 return super.getDescription() + " (first citation) with efficiently integrated internal traits (second citation)";
263 }
264
265 public List<Citation> getCitations() {
266 List<Citation> citationList = new ArrayList<Citation>(super.getCitations());
267 citationList.add(new Citation(
268 new Author[] {
269 new Author("OG", "Pybus"),
270 new Author("MA", "Suchard"),
271 new Author("P", "Lemey"),
272 new Author("F", "Bernadin"),
273 new Author("A", "Rambaut"),
274 new Author("FW", "Crawford"),
275 new Author("RR", "Gray"),
276 new Author("N", "Arinaminpathy"),
277 new Author("S", "Stramer"),
278 new Author("MP", "Busch"),
279 new Author("E", "Delwart")
280 },
281 "Unifying the spatial epidemiology and evolution of emerging epidemics",
282 2012,
283 "Proceedings of the National Academy of Sciences",
284 109,
285 15066, 15071,
286 Citation.Status.PUBLISHED
287 ));
288 return citationList;
289 }
290
291 public double getLogDataLikelihood() {
292 return getLogLikelihood();
293 }
294
295 private void setupClamps() {
296 if (nodeToClampMap == null) {
297 nodeToClampMap = new HashMap<NodeRef, RestrictedPartials>();
298 }
299 nodeToClampMap.clear();
300
301 recursiveSetupClamp(treeModel, treeModel.getRoot(), new BitSet());
302
303 anyClamps = (nodeToClampMap.size() > 0);
304 }
305
306 private void recursiveSetupClamp(Tree tree, NodeRef node, BitSet tips) {
307
308 if (tree.isExternal(node)) {
309 tips.set(node.getNumber());
310 } else {
311 for (int i = 0; i < tree.getChildCount(node); i++) {
312 NodeRef child = tree.getChild(node, i);
313
314 BitSet childTips = new BitSet();
315 recursiveSetupClamp(tree, child, childTips);
316 tips.or(childTips);
317 }
318
319 if (clampList.containsKey(tips)) {
320 RestrictedPartials partials = clampList.get(tips);
321 partials.setNode(node);
322 nodeToClampMap.put(node, partials);
323 }
324 }
325 }
326
327 public abstract boolean getComputeWishartSufficientStatistics();
328
329 public double calculateLogLikelihood() {
330
331 if (updateRestrictedNodePartials) {
332 if (clampList != null) {
333 setupClamps();
334 }
335 updateRestrictedNodePartials = false;
336 }
337
338 double logLikelihood = 0;
339 double[][] traitPrecision = diffusionModel.getPrecisionmatrix();
340 double logDetTraitPrecision = Math.log(diffusionModel.getDeterminantPrecisionMatrix());
341 double[] conditionalRootMean = tmp2;
342
343 final boolean computeWishartStatistics = getComputeWishartSufficientStatistics();
344
345 if (computeWishartStatistics) {
346 wishartStatistics = new WishartSufficientStatistics(dimTrait);
347 }
348
349 // Use dynamic programming to compute conditional likelihoods at each internal node
350 postOrderTraverse(treeModel, treeModel.getRoot(), traitPrecision, logDetTraitPrecision, computeWishartStatistics);
351
352 if (DEBUG) {
353 System.err.println("mean: " + new Vector(cacheHelper.getMeanCache()));
354 System.err.println("correctedMean: " + new Vector(cacheHelper.getCorrectedMeanCache()));
355 System.err.println("upre: " + new Vector(upperPrecisionCache));
356 System.err.println("lpre: " + new Vector(lowerPrecisionCache));
357 System.err.println("cach: " + new Vector(logRemainderDensityCache));
358 }
359
360 // Compute the contribution of each datum at the root
361 final int rootIndex = treeModel.getRoot().getNumber();
362
363 // Precision scalar of datum conditional on root
364 double conditionalRootPrecision = lowerPrecisionCache[rootIndex];
365
366 for (int datum = 0; datum < numData; datum++) {
367
368 double thisLogLikelihood = 0;
369
370 // Get conditional mean of datum conditional on root
371 // System.arraycopy(meanCache, rootIndex * dim + datum * dimTrait, conditionalRootMean, 0, dimTrait);
372 System.arraycopy(cacheHelper.getMeanCache(), rootIndex * dim + datum * dimTrait, conditionalRootMean, 0, dimTrait);
373
374 if (DEBUG) {
375 System.err.println("Datum #" + datum);
376 System.err.println("root mean: " + new Vector(conditionalRootMean));
377 System.err.println("root prec: " + conditionalRootPrecision);
378 System.err.println("diffusion prec: " + new Matrix(traitPrecision));
379 }
380
381 // B = root prior precision
382 // z = root prior mean
383 // A = likelihood precision
384 // y = likelihood mean
385
386 // y'Ay
387 double yAy = computeWeightedAverageAndSumOfSquares(conditionalRootMean, Ay, traitPrecision, dimTrait,
388 conditionalRootPrecision); // Also fills in Ay
389
390 if (conditionalRootPrecision != 0) {
391 thisLogLikelihood += -LOG_SQRT_2_PI * dimTrait
392 + 0.5 * (logDetTraitPrecision + dimTrait * Math.log(conditionalRootPrecision) - yAy);
393 }
394
395 if (DEBUG) {
396 double[][] T = new double[dimTrait][dimTrait];
397 for (int i = 0; i < dimTrait; i++) {
398 for (int j = 0; j < dimTrait; j++) {
399 T[i][j] = traitPrecision[i][j] * conditionalRootPrecision;
400 }
401 }
402 System.err.println("Conditional root MVN precision = \n" + new Matrix(T));
403 System.err.println("Conditional root MVN density = " + MultivariateNormalDistribution.logPdf(
404 conditionalRootMean, new double[dimTrait], T,
405 Math.log(MultivariateNormalDistribution.calculatePrecisionMatrixDeterminate(T)), 1.0));
406 }
407
408 if (integrateRoot) {
409 // Integrate root trait out against rootPrior
410 thisLogLikelihood += integrateLogLikelihoodAtRoot(conditionalRootMean, Ay, tmpM, traitPrecision,
411 conditionalRootPrecision); // Ay is destroyed
412 }
413
414 if (DEBUG) {
415 System.err.println("yAy = " + yAy);
416 System.err.println("logLikelihood (before remainders) = " + thisLogLikelihood +
417 " (should match conditional root MVN density when root not integrated out)");
418 }
419
420 logLikelihood += thisLogLikelihood;
421 }
422
423 logLikelihood += sumLogRemainders();
424 if (DEBUG) {
425 System.out.println("logLikelihood is " + logLikelihood);
426 }
427
428 if (DEBUG) { // Root trait is univariate!!!
429 System.err.println("logLikelihood (final) = " + logLikelihood);
430 // checkViaLargeMatrixInversion();
431 }
432
433 if (DEBUG_PNAS) {
434 checkLogLikelihood(logLikelihood, sumLogRemainders(), conditionalRootMean,
435 conditionalRootPrecision, traitPrecision);
436
437 // Check log remainder densities
438
439 for (int i = 0; i < logRemainderDensityCache.length; ++i) {
440 if (logRemainderDensityCache[i] < -1E10) {
441 System.err.println(logRemainderDensityCache[i] + " @ " + i);
442 }
443
444 }
445
446 }
447
448 areStatesRedrawn = false; // Should redraw internal node states when needed
449 return logLikelihood;
450 }
451
452 protected void checkLogLikelihood(double loglikelihood, double logRemainders,
453 double[] conditionalRootMean, double conditionalRootPrecision,
454 double[][] traitPrecision) {
455 // Do nothing; for checking PNAS paper
456 }
457
458 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
459 if (variable == traitParameter) { // A tip value got updated
460 if (index > dimTrait * numData * treeModel.getExternalNodeCount()) {
461 throw new RuntimeException("Attempting to update an invalid index");
462 }
463
464 if (index != -1) {
465 cacheHelper.setMeanCache(index, traitParameter.getValue(index));
466 } else {
467 for (int idx = 0; idx < traitParameter.getDimension(); ++idx) {
468 cacheHelper.setMeanCache(idx, traitParameter.getValue(idx));
469 }
470 }
471 // meanCache[index] = traitParameter.getValue(index);
472 likelihoodKnown = false;
473 // if (!cacheBranches) {
474 // throw new RuntimeException("Must cache means in IMTL if they are random");
475 // }
476 // TODO Need better solution. If tips are random, cacheBranches should be true (to get reset).
477 // TODO However, jitter calls setParameterValue() on the tips at initialization
478 }
479 super.handleVariableChangedEvent(variable, index, type);
480 }
481
482 protected static double computeWeightedAverageAndSumOfSquares(double[] y, double[] Ay, double[][] A,
483 int dim, double scale) {
484 // returns Ay and yAy
485 double yAy = 0;
486 for (int i = 0; i < dim; i++) {
487 Ay[i] = 0;
488 for (int j = 0; j < dim; j++)
489 Ay[i] += A[i][j] * y[j] * scale;
490 yAy += y[i] * Ay[i];
491 }
492 return yAy;
493 }
494
495 private double sumLogRemainders() {
496 double sumLogRemainders = 0;
497 for (double r : logRemainderDensityCache)
498 sumLogRemainders += r;
499 // Could skip leafs
500 return sumLogRemainders;
501 }
502
503 protected abstract double integrateLogLikelihoodAtRoot(double[] conditionalRootMean,
504 double[] marginalRootMean,
505 double[][] temporaryStorage,
506 double[][] treePrecisionMatrix,
507 double conditionalRootPrecision);
508
509 public void makeDirty() {
510 super.makeDirty();
511 areStatesRedrawn = false;
512 }
513
514 void postOrderTraverse(MutableTreeModel treeModel, NodeRef node, double[][] precisionMatrix,
515 double logDetPrecisionMatrix, boolean cacheOuterProducts) {
516
517 final int thisNumber = node.getNumber();
518
519 if (treeModel.isExternal(node)) {
520
521 // Fill in precision scalar, traitValues already filled in
522
523 if (missingTraits.isCompletelyMissing(thisNumber)) {
524 upperPrecisionCache[thisNumber] = 0;
525 lowerPrecisionCache[thisNumber] = 0; // Needed in the pre-order traversal
526 } else { // not missing tip trait
527 // changeou
528 // upperPrecisionCache[thisNumber] = (1.0 / getRescaledBranchLengthForPrecision(node)) * Math.pow(cacheHelper.getOUFactor(node), 2);
529 upperPrecisionCache[thisNumber] = cacheHelper.getUpperPrecFactor(node) * Math.pow(cacheHelper.getOUFactor(node), 2);
530 lowerPrecisionCache[thisNumber] = Double.POSITIVE_INFINITY;
531 }
532 return;
533 }
534
535 final NodeRef childNode0 = treeModel.getChild(node, 0);
536 final NodeRef childNode1 = treeModel.getChild(node, 1);
537
538 postOrderTraverse(treeModel, childNode0, precisionMatrix, logDetPrecisionMatrix, cacheOuterProducts);
539 postOrderTraverse(treeModel, childNode1, precisionMatrix, logDetPrecisionMatrix, cacheOuterProducts);
540
541 final int childNumber0 = childNode0.getNumber();
542 final int childNumber1 = childNode1.getNumber();
543 final int meanOffset0 = dim * childNumber0;
544 final int meanOffset1 = dim * childNumber1;
545 final int meanThisOffset = dim * thisNumber;
546
547 final double precision0 = upperPrecisionCache[childNumber0];
548 final double precision1 = upperPrecisionCache[childNumber1];
549 final double totalPrecision = precision0 + precision1;
550
551 final double factorOU0 = cacheHelper.getOUFactor(childNode0);
552 final double factorOU1 = cacheHelper.getOUFactor(childNode1);
553
554 doPeel(thisNumber,
555 meanThisOffset, meanOffset0, meanOffset1,
556 totalPrecision, precision0, precision1,
557 missingTraits,
558 thisNumber,
559 precisionMatrix, logDetPrecisionMatrix,
560 factorOU0, factorOU1,
561 cacheOuterProducts
562 , node, childNode0, childNode1 // TODO arguments to remove
563 , true
564 , false
565 );
566
567 final boolean DO_CLAMP = true;
568 final boolean debug = false;
569
570 if (DO_CLAMP && nodeToClampMap != null && nodeToClampMap.containsKey(node)) { // TODO precompute boolean contains for all nodes
571 RestrictedPartials clamp = nodeToClampMap.get(node);
572 final int clampIndex = clamp.getIndex();
573 final int clampOffset = dim * clampIndex;
574 final int spareOffset = dim * spareIndex;
575
576 // Copy partial into meanCache // TODO Only when value changes
577 for (int i = 0; i < dim; ++i) {
578 meanCache[clampOffset + i] = clamp.getPartial(i);
579 }
580
581 if (debug) {
582 System.err.println("BEFORE");
583 System.err.println(new Vector(logRemainderDensityCache));
584 System.err.println(new Vector(meanCache));
585 System.err.println(new Vector(lowerPrecisionCache));
586 System.err.println(new Vector(upperPrecisionCache));
587 System.err.println("");
588 }
589
590 final double precisionThis = lowerPrecisionCache[thisNumber];
591 final double precisionClamp = clamp.getPriorSampleSize() / rescaleLength(1.0);
592 final double precisionNew = precisionThis + precisionClamp;
593
594 doPeel(spareIndex,
595 spareOffset, meanThisOffset, clampOffset,
596 precisionNew, precisionThis, precisionClamp,
597 missingTraits,
598 clampIndex,
599 precisionMatrix, logDetPrecisionMatrix,
600 1.0, 1.0, // TODO Do yet figured out for OU models
601 cacheOuterProducts,
602 node, null, null
603 , true
604 , false
605 );
606
607 // Move values from clampIndex -> thisIndex
608 lowerPrecisionCache[thisNumber] = lowerPrecisionCache[spareIndex];
609 upperPrecisionCache[thisNumber] = upperPrecisionCache[spareIndex];
610
611 for (int i = 0; i < dim; ++i) {
612 meanCache[meanThisOffset + i] = meanCache[spareOffset + i];
613 }
614 }
615
616 if (debug) {
617 System.err.println(thisNumber);
618 System.err.println(new Vector(logRemainderDensityCache));
619 System.err.println(new Vector(meanCache));
620 System.err.println(new Vector(lowerPrecisionCache));
621 System.err.println(new Vector(upperPrecisionCache));
622 System.err.println("");
623 }
624 }
625
626 private void doPeel(int thisNumber,
627 int meanThisOffset, int meanOffset0, int meanOffset1,
628 double totalPrecision, double precision0, double precision1,
629 MissingTraits missingTraits,
630 int remainderNumber,
631 double[][] precisionMatrix, double logDetPrecisionMatrix,
632 double factorOU0, double factorOU1,
633 boolean cacheOuterProducts,
634 NodeRef node, NodeRef childNode0, NodeRef childNode1, boolean integrable, boolean debug) {
635 lowerPrecisionCache[thisNumber] = totalPrecision;
636
637 // changeou
638 cacheHelper.computeMeanCaches(meanThisOffset, meanOffset0, meanOffset1,
639 totalPrecision, precision0, precision1, missingTraits, node, childNode0, childNode1);
640
641 if (!treeModel.isRoot(node)) {
642 // Integrate out trait value at this node
643 //changeou
644 // double thisPrecision = 1.0 / getRescaledBranchLengthForPrecision(node);
645 double thisPrecision = cacheHelper.getUpperPrecFactor(node);
646 if (Double.isInfinite(thisPrecision)) {
647 // must handle this case for ouprocess
648 upperPrecisionCache[thisNumber] = totalPrecision;
649 } else {
650 upperPrecisionCache[thisNumber] = (totalPrecision * thisPrecision / (totalPrecision + thisPrecision)) * Math.pow(cacheHelper.getOUFactor(node), 2);
651 }
652 }
653
654 // Compute logRemainderDensity
655
656 logRemainderDensityCache[remainderNumber] = 0;
657
658 if (precision0 != 0 && precision1 != 0 && integrable) {
659 // changeou
660 incrementRemainderDensities(
661 precisionMatrix,
662 logDetPrecisionMatrix, remainderNumber, meanThisOffset,
663 meanOffset0, meanOffset1,
664 precision0, precision1,
665 factorOU0, factorOU1,
666 cacheOuterProducts);
667 }
668 }
669
670 private void incrementRemainderDensities(double[][] precisionMatrix,
671 double logDetPrecisionMatrix,
672 int thisIndex,
673 int thisOffset,
674 int childOffset0,
675 int childOffset1,
676 double precision0,
677 double precision1,
678 double OUFactor0,
679 double OUFactor1,
680 boolean cacheOuterProducts) {
681
682 final double remainderPrecision = precision0 * precision1 / (precision0 + precision1);
683
684 if (cacheOuterProducts) {
685 incrementOuterProducts(thisOffset, childOffset0, childOffset1, precision0, precision1);
686 }
687
688 for (int k = 0; k < numData; k++) {
689
690 double childSS0 = 0;
691 double childSS1 = 0;
692 double crossSS = 0;
693
694 for (int i = 0; i < dimTrait; i++) {
695
696 // In case of no drift, getCorrectedMeanCache() simply returns mean cache
697 // final double wChild0i = meanCache[childOffset0 + k * dimTrait + i] * precision0;
698 final double wChild0i = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + i] * precision0;
699 // final double wChild1i = meanCache[childOffset1 + k * dimTrait + i] * precision1;
700 final double wChild1i = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + i] * precision1;
701
702 for (int j = 0; j < dimTrait; j++) {
703
704 // subtract "correction"
705 //final double child0j = meanCache[childOffset0 + k * dimTrait + j];
706 final double child0j = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + j];
707 // subtract "correction"
708 //final double child1j = meanCache[childOffset1 + k * dimTrait + j];
709 final double child1j = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + j];
710
711 childSS0 += wChild0i * precisionMatrix[i][j] * child0j;
712 childSS1 += wChild1i * precisionMatrix[i][j] * child1j;
713
714 // make sure meanCache in following is not "corrected"
715 // crossSS += (wChild0i + wChild1i) * precisionMatrix[i][j] * meanCache[thisOffset + k * dimTrait + j];
716 crossSS += (wChild0i + wChild1i) * precisionMatrix[i][j] * cacheHelper.getMeanCache()[thisOffset + k * dimTrait + j];
717 }
718 }
719
720 logRemainderDensityCache[thisIndex] +=
721 -dimTrait * LOG_SQRT_2_PI
722 + 0.5 * (dimTrait * Math.log(remainderPrecision) + logDetPrecisionMatrix)
723 - 0.5 * (childSS0 + childSS1 - crossSS)
724 // changeou
725 - dimTrait * (Math.log(OUFactor0) + Math.log(OUFactor1));
726
727
728 if (DEBUG && logRemainderDensityCache[thisIndex] > 1E2) {
729 System.err.println(thisIndex);
730 System.err.println(logRemainderDensityCache[thisIndex]);
731 System.err.println("rP = " + remainderPrecision);
732 System.err.println("p0 = " + precision0);
733 System.err.println("p1 = " + precision1 + "\n");
734 System.err.println(new Matrix(precisionMatrix));
735 System.err.println(childSS0);
736 System.err.println(childSS1);
737 System.err.println(crossSS);
738
739
740 for (int i = 0; i < dimTrait; ++i) {
741 System.err.println("\t"
742 + cacheHelper.getCorrectedMeanCache()[childOffset0 + 0 * dimTrait + i] + " "
743 + cacheHelper.getCorrectedMeanCache()[childOffset1 + 0 * dimTrait + i]
744 );
745 }
746 System.exit(-1);
747 }
748 // double tempnum = childSS0 + childSS1 - crossSS;
749 // System.err.println("childSS0 + childSS1 - crossSS: " + tempnum);
750 }
751 // System.err.println("logRemainderDensity: " + logRemainderDensityCache[thisIndex]);
752 // System.err.println("thisIndex: " + thisIndex);
753 // System.err.println("remainder precision: " + remainderPrecision);
754 // System.err.println("precision0: " + precision0);
755 // System.err.println("precision1: " + precision1);
756 // System.err.println("precision0*precision1: " + precision0*precision1);
757
758 // System.err.println("logDetPrecisionMatrix: " + logDetPrecisionMatrix);
759
760 }
761
762 private void incrementOuterProducts(int thisOffset,
763 int childOffset0,
764 int childOffset1,
765 double precision0,
766 double precision1) {
767
768 final double[] outerProduct = wishartStatistics.getScaleMatrix();
769
770 // for (int k = 0; k < numData; k++) {
771 //
772 // for (int i = 0; i < dimTrait; i++) {
773 //
774 // // final double wChild0i = meanCache[childOffset0 + k * dimTrait + i] * precision0;
775 // // final double wChild1i = meanCache[childOffset1 + k * dimTrait + i] * precision1;
776 // final double wChild0i = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + i] * precision0;
777 // final double wChild1i = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + i] * precision1;
778 //
779 // for (int j = 0; j < dimTrait; j++) {
780 //
781 // //final double child0j = meanCache[childOffset0 + k * dimTrait + j];
782 // //final double child1j = meanCache[childOffset1 + k * dimTrait + j];
783 // final double child0j = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + j];
784 // final double child1j = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + j];
785 //
786 //// outerProduct[i][j] += wChild0i * child0j;
787 //// outerProduct[i][j] += wChild1i * child1j;
788 ////
789 //// //outerProduct[i][j] -= (wChild0i + wChild1i) * meanCache[thisOffset + k * dimTrait + j];
790 //// outerProduct[i][j] -= (wChild0i + wChild1i) * cacheHelper.getMeanCache()[thisOffset + k * dimTrait + j];
791 // outerProduct[i][j] += wChild0i * child0j;
792 // outerProduct[i][j] += wChild1i * child1j;
793 //
794 // //outerProduct[i][j] -= (wChild0i + wChild1i) * meanCache[thisOffset + k * dimTrait + j];
795 // outerProduct[i][j] -= (wChild0i + wChild1i) * cacheHelper.getMeanCache()[thisOffset + k * dimTrait + j];
796 // }
797 // }
798 // }
799
800 // final double[][] increment = new double[dimTrait][dimTrait];
801 //
802 // for (int k = 0; k < numData; k++) {
803 //
804 // for (int i = 0; i < dimTrait; i++) {
805 //
806 // final double child0i = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + i];
807 // final double child1i = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + i];
808 // final double nodei = cacheHelper.getMeanCache()[thisOffset + k * dimTrait + i];
809 //
810 // for (int j = 0; j < dimTrait; j++) {
811 // final double child0j = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + j];
812 // final double child1j = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + j];
813 // final double nodej = cacheHelper.getMeanCache()[thisOffset + k * dimTrait + j];
814 //
815 // final double inc =
816 // (child0i * child0j - nodei * nodej) * precision0 +
817 // (child1i * child1j - nodei * nodej) * precision1;
818 //
819 // increment[i][j] += inc;
820 //// outerProduct[i][j] += inc;
821 // }
822 // }
823 // }
824
825 // final double[][] increment2 = new double[dimTrait][dimTrait];
826 //
827 //
828 // for (int k = 0; k < numData; k++) {
829 //
830 // for (int i = 0; i < dimTrait; i++) {
831 //
832 // final double child0i = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + i];
833 // final double child1i = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + i];
834 //// final double nodei = cacheHelper.getMeanCache()[thisOffset + k * dimTrait + i];
835 //
836 // for (int j = 0; j < dimTrait; j++) {
837 // final double child0j = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + j];
838 // final double child1j = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + j];
839 //// final double nodej = cacheHelper.getMeanCache()[thisOffset + k * dimTrait + j];
840 //
841 // final double inc = (child0i * child0j + child1i * child1j
842 // - child0i * child1j - child1i * child0j) * weight;
843 //
844 // increment2[i][j] += inc;
845 // }
846 // }
847 // }
848 //
849 // final double[][] increment3 = new double[dimTrait][dimTrait];
850
851 if (precision0 == 0.0 || precision1 == 0.0) {
852 System.err.println("ZERO PRECISION");
853 // System.exit(-1);
854 }
855
856 if (precision0 < 1E-16 || precision1 < 1E-16) {
857 System.err.println("LOW PRECISION");
858 }
859
860 final double weight = precision0 * precision1 / (precision0 + precision1);
861
862 for (int k = 0; k < numData; k++) {
863
864 for (int i = 0; i < dimTrait; i++) {
865
866 final double child0i = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + i];
867 final double child1i = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + i];
868
869 for (int j = 0; j < dimTrait; j++) {
870 final double child0j = cacheHelper.getCorrectedMeanCache()[childOffset0 + k * dimTrait + j];
871 final double child1j = cacheHelper.getCorrectedMeanCache()[childOffset1 + k * dimTrait + j];
872
873 final double inc = (child0i - child1i) * (child0j - child1j) * weight;
874
875 outerProduct[i * dimTrait + j] += inc;
876 // increment3[i][j] += inc;
877 }
878 }
879 }
880
881
882 // double det = increment3[0][0] * increment3[1][1] - increment3[0][1] * increment3[1][0];
883 //
884 // System.err.println("INC Check\n"
885 // + new Matrix(increment) + "\n"
886 // + new Matrix(increment2) + "\n"
887 // + new Matrix(increment3) +"\n"
888 // + det + "\n\n");
889
890
891
892 // For numerical stability: Ensure increment is positive-definite
893 // if (checkIsPositiveDefinite(increment)) {
894 // for (int i = 0; i < dimTrait; ++i) {
895 // for (int j = 0; j < dimTrait; ++j) {
896 // outerProduct[i][j] += increment3[i][j];
897 // }
898 // }
899 // }
900 // else {
901 //
902 // System.err.println("ERROR INC\n" + new Matrix(increment) + "\n" + new Matrix(increment3) + "\n\n");
903 //// System.exit(-1);
904 //
905 // }
906
907 wishartStatistics.incrementDf(numData); // Peeled one node
908 }
909
910 // private boolean checkIsPositiveDefinite(double[][] S) {
911 //
912 // final int dim = S.length;
913 //
914 // for (int i = 0; i < dim; ++i) {
915 // if (S[i][i] < 0.0) return false;
916 // }
917 //
918 // if (dim == 2) {
919 // return (S[0][0] * S[1][1] > S[0][1] * S[1][0]);
920 // } else {
921 // try {
922 // return (new Matrix(S).isPD());
923 // } catch (IllegalDimension illegalDimension) {
924 // illegalDimension.printStackTrace();
925 // }
926 // }
927 // return false;
928 // }
929
930 // private boolean checkDiagonals(double[][] S) {
931 // for (int i = 0; i < S.length; ++i) {
932 // if (S[i][i] < 0.0) {
933 // System.err.println("IMTL ERROR diag(S)\n" + new Matrix(S));
934 // return false;
935 // }
936 // }
937 // return true;
938 // }
939
940 // private void computeWeightedMeanCache(int thisOffset,
941 // int childOffset0,
942 // int childOffset1,
943 // double precision0,
944 // double precision1) {
945 //
946 // final double totalVariance = 1.0 / (precision0 + precision1);
947 // for (int i = 0; i < dim; i++) {
948 // meanCache[thisOffset + i] = (meanCache[childOffset0 + i] * precision0 +
949 // meanCache[childOffset1 + i] * precision1)
950 // * totalVariance;
951 // }
952 // }
953
954 protected double[] getRootNodeTrait() {
955 return getTraitForNode(treeModel, treeModel.getRoot(), traitName);
956 }
957
958 public double[] getTraitForNode(Tree tree, NodeRef node, String traitName) {
959
960 // if (tree != treeModel) {
961 // throw new RuntimeException("Can only reconstruct states on treeModel given to constructor");
962 // }
963
964 getLogLikelihood();
965
966 if (!areStatesRedrawn)
967 redrawAncestralStates();
968
969 int index = node.getNumber();
970
971 double[] trait = new double[dim];
972 System.arraycopy(drawnStates, index * dim, trait, 0, dim);
973 return trait;
974 }
975
976 public void redrawAncestralStates() {
977
978 double[][] treePrecision = diffusionModel.getPrecisionmatrix();
979 double[][] treeVariance = new SymmetricMatrix(treePrecision).inverse().toComponents();
980
981 preOrderTraverseSample(treeModel, treeModel.getRoot(), 0, treePrecision, treeVariance);
982
983 if (DEBUG) {
984 System.err.println("all draws = " + new Vector(drawnStates));
985 }
986
987 areStatesRedrawn = true;
988 }
989
990 public void storeState() {
991 super.storeState();
992
993 if (cacheBranches) {
994 // System.arraycopy(meanCache, 0, storedMeanCache, 0, meanCache.length);
995 cacheHelper.store();
996 System.arraycopy(upperPrecisionCache, 0, storedUpperPrecisionCache, 0, upperPrecisionCache.length);
997 System.arraycopy(lowerPrecisionCache, 0, storedLowerPrecisionCache, 0, lowerPrecisionCache.length);
998 System.arraycopy(logRemainderDensityCache, 0, storedLogRemainderDensityCache, 0, logRemainderDensityCache.length);
999 }
1000
1001 // savedUpdateRestrictedNodePartials = updateRestrictedNodePartials;
1002 //
1003 // if (clampList != null) {
1004 // savedClampList = new HashMap<BitSet, RestrictedPartials>(clampList);
1005 // }
1006 //
1007 // if (nodeToClampMap != null) {
1008 // savedNodeToClampMap = new HashMap<NodeRef, RestrictedPartials>(nodeToClampMap);
1009 // }
1010 }
1011
1012 public void restoreState() {
1013 super.restoreState();
1014
1015 if (cacheBranches) {
1016 double[] tmp;
1017
1018 cacheHelper.restore();
1019 // tmp = storedMeanCache;
1020 // storedMeanCache = meanCache;
1021 // meanCache = tmp;
1022
1023 tmp = storedUpperPrecisionCache;
1024 storedUpperPrecisionCache = upperPrecisionCache;
1025 upperPrecisionCache = tmp;
1026
1027 tmp = storedLowerPrecisionCache;
1028 storedLowerPrecisionCache = lowerPrecisionCache;
1029 lowerPrecisionCache = tmp;
1030
1031 tmp = storedLogRemainderDensityCache;
1032 storedLogRemainderDensityCache = logRemainderDensityCache;
1033 logRemainderDensityCache = tmp;
1034 }
1035
1036 // updateRestrictedNodePartials = savedUpdateRestrictedNodePartials;
1037 //
1038 // if (savedClampList != null) {
1039 // clampList = savedClampList;
1040 // }
1041 //
1042 // if (savedNodeToClampMap != null) {
1043 // nodeToClampMap = savedNodeToClampMap;
1044 // }
1045 }
1046
1047
1048 // Computes x^t A y, used many times in these computations
1049
1050 protected static double computeQuadraticProduct(double[] x, double[][] A, double[] y, int dim) {
1051 double sum = 0;
1052 for (int i = 0; i < dim; i++) {
1053 for (int j = 0; j < dim; j++) {
1054 sum += x[i] * A[i][j] * y[j];
1055 }
1056 }
1057 return sum;
1058 }
1059
1060 // Computes the weighted average of two vectors, used many times in these computations
1061
1062 public static void computeWeightedAverage(double[] in0, int offset0, double weight0,
1063 double[] in1, int offset1, double weight1,
1064 double[] out2, int offset2,
1065 int length) {
1066
1067 // final double totalInverseWeight = 1.0 / (weight0 + weight1);
1068 for (int i = 0; i < length; i++) {
1069 // out2[offset2 + i] = (in0[offset0 + i] * weight0 + in1[offset1 + i] * weight1) * totalInverseWeight;
1070 out2[offset2 + i] = (in0[offset0 + i] * weight0 + in1[offset1 + i] * weight1) / (weight0 + weight1);
1071 }
1072 }
1073
1074
1075 protected void computeCorrectedWeightedAverage(int offset0, double weight0, NodeRef childNode0,
1076 int offset1, double weight1, NodeRef childNode1,
1077 int offset2,
1078 int length, NodeRef thisNode) {
1079
1080 final double totalInverseWeight = 1.0 / (weight0 + weight1);
1081 // TODO fix
1082 // final double length0 = getRescaledBranchLength(childNode0);
1083 // final double length1 = getRescaledBranchLength(childNode1);
1084 // final double thisLength = getRescaledBranchLength(thisNode);
1085 double[] shift;
1086 if (!treeModel.isRoot(thisNode)) {
1087 shift = getShiftForBranchLength(thisNode);
1088 } else {
1089 shift = null;
1090 }
1091 double[] shiftChild0 = getShiftForBranchLength(childNode0);
1092 double[] shiftChild1 = getShiftForBranchLength(childNode1);
1093
1094 if (treeModel.isExternal(childNode0)) {
1095 for (int i = 0; i < length; i++) {
1096 correctedMeanCache[offset0 + i] = meanCache[offset0 + i] - shiftChild0[i];
1097 }
1098 }
1099
1100 if (treeModel.isExternal(childNode1)) {
1101 for (int i = 0; i < length; i++) {
1102 correctedMeanCache[offset1 + i] = meanCache[offset1 + i] - shiftChild1[i];
1103 }
1104 }
1105
1106 for (int i = 0; i < length; i++) {
1107
1108 // meanCache[offset2 + i] = ((meanCache[offset0 + i] - shiftChild0[i]) * weight0 + (meanCache[offset1 + i] - shiftChild1[i]) * weight1) * totalInverseWeight;
1109 meanCache[offset2 + i] = (correctedMeanCache[offset0 + i] * weight0 + correctedMeanCache[offset1 + i] * weight1) * totalInverseWeight;
1110 if (!treeModel.isRoot(thisNode)) {
1111 correctedMeanCache[offset2 + i] = meanCache[offset2 + i] - shift[i];
1112 } else {
1113 correctedMeanCache[offset2 + i] = meanCache[offset2 + i];
1114 }
1115 }
1116 }
1117
1118
1119 protected void computeCorrectedOUWeightedAverage(int offset0, double weight0, NodeRef childNode0,
1120 int offset1, double weight1, NodeRef childNode1,
1121 int offset2,
1122 int length, NodeRef thisNode) {
1123
1124 final double totalInverseWeight = 1.0 / (weight0 + weight1);
1125
1126 double[] optimal;
1127 double selection;
1128
1129 if (!treeModel.isRoot(thisNode)) {
1130 optimal = getOptimalValue(thisNode);
1131 selection = getTimeScaledSelection(thisNode);
1132 } else {
1133 optimal = null;
1134 selection = 1;
1135 }
1136 double[] optimalChild0 = getOptimalValue(childNode0);
1137 double[] optimalChild1 = getOptimalValue(childNode1);
1138 double selectionChild0 = getTimeScaledSelection(childNode0);
1139 double selectionChild1 = getTimeScaledSelection(childNode1);
1140
1141 /*
1142
1143 if (treeModel.isExternal(childNode0)) {
1144 for (int i = 0; i < length; i++) {
1145 correctedMeanCache[offset0 + i] = (meanCache[offset0 + i] - selectionChild0 * optimalChild0[i]) / (1 - selectionChild0);
1146 }
1147 }
1148
1149 if (treeModel.isExternal(childNode1)) {
1150 for (int i = 0; i < length; i++) {
1151 correctedMeanCache[offset1 + i] = (meanCache[offset1 + i] - selectionChild1 * optimalChild1[i]) / (1 - selectionChild1);
1152 }
1153 }
1154
1155 for (int i = 0; i < length; i++) {
1156
1157 // meanCache[offset2 + i] = ((meanCache[offset0 + i] - shiftChild0[i]) * weight0 + (meanCache[offset1 + i] - shiftChild1[i]) * weight1) * totalInverseWeight;
1158 meanCache[offset2 + i] = (correctedMeanCache[offset0 + i] * weight0 + correctedMeanCache[offset1 + i] * weight1) * totalInverseWeight;
1159 if (!treeModel.isRoot(thisNode)) {
1160 correctedMeanCache[offset2 + i] = (meanCache[offset2 + i] - selection * optimal[i]) / (1 - selection);
1161 } else {
1162 correctedMeanCache[offset2 + i] = meanCache[offset2 + i];
1163 }
1164 }
1165
1166 */
1167
1168 if (treeModel.isExternal(childNode0)) {
1169 for (int i = 0; i < length; i++) {
1170 correctedMeanCache[offset0 + i] = Math.exp(selectionChild0) * meanCache[offset0 + i] - (Math.exp(selectionChild0) - 1) * optimalChild0[i];
1171 }
1172 }
1173
1174 if (treeModel.isExternal(childNode1)) {
1175 for (int i = 0; i < length; i++) {
1176 correctedMeanCache[offset1 + i] = Math.exp(selectionChild1) * meanCache[offset1 + i] - (Math.exp(selectionChild1) - 1) * optimalChild1[i];
1177 }
1178 }
1179
1180 for (int i = 0; i < length; i++) {
1181
1182 // meanCache[offset2 + i] = ((meanCache[offset0 + i] - shiftChild0[i]) * weight0 + (meanCache[offset1 + i] - shiftChild1[i]) * weight1) * totalInverseWeight;
1183 meanCache[offset2 + i] = (correctedMeanCache[offset0 + i] * weight0 + correctedMeanCache[offset1 + i] * weight1) * totalInverseWeight;
1184 if (!treeModel.isRoot(thisNode)) {
1185 correctedMeanCache[offset2 + i] = Math.exp(selection) * meanCache[offset2 + i] - (Math.exp(selection) - 1) * optimal[i];
1186 } else {
1187 correctedMeanCache[offset2 + i] = meanCache[offset2 + i];
1188 }
1189 }
1190
1191
1192 }
1193
1194
1195 protected abstract double[][] computeMarginalRootMeanAndVariance(double[] conditionalRootMean,
1196 double[][] treePrecisionMatrix,
1197 double[][] treeVarianceMatrix,
1198 double conditionalRootPrecision);
1199
1200
1201 private void preOrderTraverseSample(MutableTreeModel treeModel, NodeRef node, int parentIndex, double[][] treePrecision,
1202 double[][] treeVariance) {
1203 // System.err.println("preOrderTraverseSample got called!!");
1204 // System.exit(-1);
1205 final int thisIndex = node.getNumber();
1206
1207 if (treeModel.isRoot(node)) {
1208 // draw root
1209
1210 double[] rootMean = new double[dimTrait];
1211 final int rootIndex = treeModel.getRoot().getNumber();
1212 double rootPrecision = lowerPrecisionCache[rootIndex];
1213
1214 for (int datum = 0; datum < numData; datum++) {
1215 // System.arraycopy(meanCache, thisIndex * dim + datum * dimTrait, rootMean, 0, dimTrait);
1216 System.arraycopy(cacheHelper.getMeanCache(), thisIndex * dim + datum * dimTrait, rootMean, 0, dimTrait);
1217
1218 double[][] variance = computeMarginalRootMeanAndVariance(rootMean, treePrecision, treeVariance,
1219 rootPrecision);
1220
1221 double[] draw = MultivariateNormalDistribution.nextMultivariateNormalVariance(rootMean, variance);
1222
1223 if (DEBUG_PREORDER) {
1224 Arrays.fill(draw, 1.0);
1225 }
1226
1227 System.arraycopy(draw, 0, drawnStates, rootIndex * dim + datum * dimTrait, dimTrait);
1228 // DEBUG=true;
1229 if (DEBUG) {
1230 System.err.println("Root mean: " + new Vector(rootMean));
1231 System.err.println("Root var : " + new Matrix(variance));
1232 System.err.println("Root draw: " + new Vector(draw));
1233 }
1234 }
1235 } else { // draw conditional on parentState
1236
1237 if (!missingTraits.isCompletelyMissing(thisIndex)
1238 && !missingTraits.isPartiallyMissing(thisIndex)) {
1239
1240 //System.arraycopy(meanCache, thisIndex * dim, drawnStates, thisIndex * dim, dim);
1241 System.arraycopy(cacheHelper.getMeanCache(), thisIndex * dim, drawnStates, thisIndex * dim, dim);
1242 // System.err.println("I got here");
1243 // System.exit(-1);
1244 } else {
1245
1246 // System.err.println("I got here");
1247 // System.exit(-1);
1248
1249 if (missingTraits.isPartiallyMissing(thisIndex)) {
1250 throw new RuntimeException("Partially missing values are not yet implemented");
1251 }
1252 // This code should work for sampling a missing tip trait as well, but needs testing
1253
1254 // parent trait at drawnStates[parentOffset]
1255 double precisionToParent = 1.0 / getRescaledBranchLengthForPrecision(node);
1256 double precisionOfNode = lowerPrecisionCache[thisIndex];
1257 double totalPrecision = precisionOfNode + precisionToParent;
1258
1259 double[] mean = Ay; // temporary storage
1260 double[][] var = tmpM; // temporary storage
1261
1262 for (int datum = 0; datum < numData; datum++) {
1263
1264 int parentOffset = parentIndex * dim + datum * dimTrait;
1265 int thisOffset = thisIndex * dim + datum * dimTrait;
1266 // DEBUG=true;
1267 if (DEBUG) {
1268 double[] parentValue = new double[dimTrait];
1269 System.arraycopy(drawnStates, parentOffset, parentValue, 0, dimTrait);
1270 System.err.println("Parent draw: " + new Vector(parentValue));
1271 if (parentValue[0] != drawnStates[parentOffset]) {
1272 throw new RuntimeException("Error in setting indices");
1273 }
1274 }
1275
1276 for (int i = 0; i < dimTrait; i++) {
1277 mean[i] = ((drawnStates[parentOffset + i] + cacheHelper.getShift(node)[i]) * precisionToParent
1278 //mean[i] = (drawnStates[parentOffset + i] * precisionToParent
1279 // + meanCache[thisOffset + i] * precisionOfNode) / totalPrecision;
1280 + cacheHelper.getMeanCache()[thisOffset + i] * precisionOfNode) / totalPrecision;
1281 for (int j = 0; j < dimTrait; j++) {
1282 var[i][j] = treeVariance[i][j] / totalPrecision;
1283 }
1284 }
1285 double[] draw = MultivariateNormalDistribution.nextMultivariateNormalVariance(mean, var);
1286 System.arraycopy(draw, 0, drawnStates, thisOffset, dimTrait);
1287
1288 if (DEBUG) {
1289 System.err.println("Int prec: " + totalPrecision);
1290 System.err.println("Int mean: " + new Vector(mean));
1291 System.err.println("Int var : " + new Matrix(var));
1292 System.err.println("Int draw: " + new Vector(draw));
1293 System.err.println("");
1294 }
1295 }
1296 }
1297 }
1298
1299 if (peel() && !treeModel.isExternal(node)) {
1300 preOrderTraverseSample(treeModel, treeModel.getChild(node, 0), thisIndex, treePrecision, treeVariance);
1301 preOrderTraverseSample(treeModel, treeModel.getChild(node, 1), thisIndex, treePrecision, treeVariance);
1302 }
1303 }
1304
1305 protected void handleModelChangedEvent(Model model, Object object, int index) {
1306
1307 if (driftModels != null && driftModels.contains(model)) {
1308 if (cacheBranches) {
1309 updateAllNodes();
1310 } else {
1311 likelihoodKnown = false;
1312 }
1313 } else if (optimalValues != null && optimalValues.contains(model)) {
1314 if (cacheBranches) {
1315 updateAllNodes();
1316 } else {
1317 likelihoodKnown = false;
1318 }
1319 } else if(strengthOfSelection != null){
1320 if (cacheBranches) {
1321 updateAllNodes();
1322 } else {
1323 likelihoodKnown = false;
1324 }
1325 } else{
1326 super.handleModelChangedEvent(model, object, index);
1327 }
1328 }
1329
1330 protected boolean peel() {
1331 return true;
1332 }
1333
1334 public LogColumn[] getColumns() {
1335 return new LogColumn[]{
1336 new LikelihoodColumn(getId())};
1337 }
1338
1339 protected boolean areStatesRedrawn = false;
1340
1341 protected double[] meanCache;
1342 protected double[] correctedMeanCache;
1343
1344 class CacheHelper {
1345
1346 public CacheHelper(int cacheLength, boolean cacheBranches) {
1347 // modify code later so we can uncomment the following
1348
1349 meanCache = new double[cacheLength];
1350 this.cacheBranches = cacheBranches;
1351 if (cacheBranches) {
1352 storedMeanCache = new double[cacheLength];
1353 }
1354
1355 }
1356
1357 public double[] getShift(NodeRef node) {
1358
1359 double[] shift = new double[dimTrait * numData];
1360 for (int i = 0; i < dim; ++i) {
1361 shift[i] = 0;
1362 }
1363 return shift;
1364 }
1365
1366 public double[] getMeanCache() {
1367 return meanCache;
1368 }
1369
1370 public double[] getCorrectedMeanCache() {
1371 return meanCache;
1372 }
1373
1374 public void store() {
1375 // if (cacheBranches) {
1376 if(storedMeanCache.length != meanCache.length)
1377 storedMeanCache = new double[meanCache.length];
1378 System.arraycopy(meanCache, 0, storedMeanCache, 0, meanCache.length);
1379 // }
1380 }
1381
1382 public void restore() {
1383 // if (cacheBranches) {
1384 double[] tmp = storedMeanCache;
1385 storedMeanCache = meanCache;
1386 meanCache = tmp;
1387 // }
1388 }
1389
1390 public double getOUFactor(NodeRef node) {
1391 return 1;
1392 }
1393
1394 public double getUpperPrecFactor(NodeRef node) {
1395 return 1.0 / getRescaledBranchLengthForPrecision(node);
1396 }
1397
1398 protected boolean cacheBranches;
1399 // private double[] meanCache;
1400 // private double[] storedMeanCache;
1401
1402 // public void computeMeanCaches(int meanThisOffset, int meanOffset0, int meanOffset1,
1403 // double precision0, double precision1, MissingTraits missingTraits) {
1404 // //To change body of created methods use File | Settings | File Templates.
1405 // }
1406
1407 public void computeMeanCaches(int meanThisOffset, int meanOffset0, int meanOffset1,
1408 double totalPrecision, double precision0, double precision1, MissingTraits missingTraits,
1409 NodeRef thisNode, NodeRef node0, NodeRef node1) {
1410 if (totalPrecision == 0) {
1411 System.arraycopy(zeroDimVector, 0, meanCache, meanThisOffset, dim);
1412 } else {
1413 // Delegate in case either child is partially missing
1414 // computeCorrectedWeightedAverage
1415 missingTraits.computeWeightedAverage(meanCache,
1416 meanOffset0, precision0,
1417 meanOffset1, precision1,
1418 meanThisOffset, dim);
1419 }
1420 }
1421
1422 // public void setTipMeans(double[] meanCache, double[] traitValue, int dim, int index, NodeRef node) {
1423 public void setTipMeans(double[] traitValue, int dim, int index, NodeRef node) {
1424 System.arraycopy(traitValue, 0, meanCache, dim * index, dim);
1425 }
1426
1427 public void setTipMeans(double[] traitValue, int dim, int index) {
1428 System.arraycopy(traitValue, 0, meanCache, dim * index, dim);
1429 }
1430
1431 public void copyToMeanCache(double[] src, int destPos, int length) {
1432 System.arraycopy(src, 0, meanCache, destPos, length);
1433 }
1434
1435 public void setMeanCache(int index, double value) {
1436 meanCache[index] = value;
1437 }
1438
1439
1440 }
1441
1442 class StandarizedCacheHelper extends CacheHelper {
1443
1444 public StandarizedCacheHelper(int dim, int nodeCount, boolean cacheBranches) {
1445 super(dim * nodeCount, cacheBranches);
1446 this.dim = dim;
1447 this.nodeCount = nodeCount;
1448
1449
1450 }
1451
1452 public void setTipMeans(double[] traitValue, int dim, int index, NodeRef node) {
1453 //System.arraycopy(traitValue, 0, meanCache, dim * index, dim);
1454 for (int i = 0; i < dim; ++i) {
1455 setMeanCache(dim * index + i, traitValue[i]);
1456 }
1457 }
1458
1459 public void setTipMeans(double[] traitValue, int dim, int index) {
1460 // System.arraycopy(traitValue, 0, meanCache, dim * index, dim);
1461 for (int i = 0; i < dim; ++i) {
1462 setMeanCache(dim * index + i, traitValue[i]);
1463 }
1464 }
1465
1466 // public void copyToMeanCache(double[] src, int destPos, int length) {
1467 // System.arraycopy(src, 0, meanCache, destPos, length);
1468 // }
1469
1470 public void setMeanCache(int index, double value) {
1471 final int thisDim = index % dim;
1472 meanCache[index] = value;
1473 }
1474
1475 private final int dim;
1476 private final int nodeCount;
1477 }
1478
1479 class DriftCacheHelper extends CacheHelper {
1480
1481 public DriftCacheHelper(int cacheLength, boolean cacheBranches) {
1482 super(cacheLength, cacheBranches);
1483 correctedMeanCache = new double[cacheLength];
1484 }
1485
1486 public double[] getShift(NodeRef node) {
1487 return getShiftForBranchLength(node);
1488 }
1489
1490 public double[] getCorrectedMeanCache() {
1491 return correctedMeanCache;
1492 }
1493
1494
1495 public double getOUFactor(NodeRef node) {
1496 return 1;
1497 }
1498
1499 public double getUpperPrecFactor(NodeRef node) {
1500 return 1.0 / getRescaledBranchLengthForPrecision(node);
1501 }
1502
1503 public void setTipMeans(double[] traitValue, int dim, int index, NodeRef node) {
1504 System.arraycopy(traitValue, 0, meanCache, dim * index, dim);
1505 /*
1506 double[] shift = getShiftForBranchLength(node);
1507 for (int i = 0; i < dim; i++) {
1508 correctedMeanCache[dim * index + i] = traitValue[i] - shift[i];
1509 }
1510 */
1511 }
1512
1513 public void computeMeanCaches(int meanThisOffset, int meanOffset0, int meanOffset1,
1514 double totalPrecision, double precision0, double precision1, MissingTraits missingTraits,
1515 NodeRef thisNode, NodeRef node0, NodeRef node1) {
1516 if (totalPrecision == 0) {
1517 System.arraycopy(zeroDimVector, 0, meanCache, meanThisOffset, dim);
1518 } else {
1519 // Delegate in case either child is partially missing
1520 // computeCorrectedWeightedAverage
1521 computeCorrectedWeightedAverage(
1522 meanOffset0, precision0, node0,
1523 meanOffset1, precision1, node1,
1524 meanThisOffset, dim, thisNode);
1525 }
1526 }
1527
1528
1529 // private double[] correctedMeanCache;
1530 }
1531
1532
1533 class OUCacheHelper extends CacheHelper {
1534
1535 public OUCacheHelper(int cacheLength, boolean cacheBranches) {
1536 super(cacheLength, cacheBranches);
1537 correctedMeanCache = new double[cacheLength];
1538 }
1539
1540 public double[] getCorrectedMeanCache() {
1541 return correctedMeanCache;
1542 }
1543
1544 public double getOUFactor(NodeRef node) {
1545 // return 1 - getTimeScaledSelection(node);
1546 return Math.exp(-getTimeScaledSelection(node));
1547 }
1548
1549 public double getUpperPrecFactor(NodeRef node) {
1550 return (2 * strengthOfSelection.getBranchRate(treeModel, node)) / (1 - Math.exp(-2 * getTimeScaledSelection(node)));
1551 }
1552
1553
1554 public void setTipMeans(double[] traitValue, int dim, int index, NodeRef node) {
1555 System.arraycopy(traitValue, 0, meanCache, dim * index, dim);
1556 }
1557
1558
1559 public void computeMeanCaches(int meanThisOffset, int meanOffset0, int meanOffset1,
1560 double totalPrecision, double precision0, double precision1, MissingTraits missingTraits,
1561 NodeRef thisNode, NodeRef node0, NodeRef node1) {
1562 if (totalPrecision == 0) {
1563 System.arraycopy(zeroDimVector, 0, meanCache, meanThisOffset, dim);
1564 } else {
1565 // Delegate in case either child is partially missing
1566 // computeCorrectedWeightedAverage
1567 computeCorrectedOUWeightedAverage(
1568 meanOffset0, precision0, node0,
1569 meanOffset1, precision1, node1,
1570 meanThisOffset, dim, thisNode);
1571 }
1572 }
1573
1574 }
1575
1576 private CacheHelper createCacheHelper(IntegratedDiffusionType type, int cacheLength, boolean cacheBranches) {
1577 CacheHelper helper = null;
1578 switch (type) {
1579 case PLAIN:
1580 helper = new CacheHelper(cacheLength, cacheBranches);
1581 break;
1582 case SCALED:
1583 helper = new CacheHelper(cacheLength, cacheBranches);
1584 break;
1585 case DRIFT:
1586 helper = new DriftCacheHelper(cacheLength, cacheBranches);
1587 break;
1588 case OU:
1589 helper = new OUCacheHelper(cacheLength, cacheBranches);
1590 break;
1591 }
1592 return helper;
1593 }
1594
1595 public enum IntegratedDiffusionType {
1596 PLAIN,
1597 SCALED,
1598 DRIFT,
1599 OU,
1600 }
1601
1602 // protected boolean hasDrift;
1603
1604 protected double[] upperPrecisionCache;
1605 protected double[] lowerPrecisionCache;
1606 private double[] logRemainderDensityCache;
1607
1608 // private double[] storedMeanCache;
1609 protected double[] storedMeanCache;
1610 private double[] storedUpperPrecisionCache;
1611 private double[] storedLowerPrecisionCache;
1612 private double[] storedLogRemainderDensityCache;
1613
1614 protected double[] drawnStates;
1615
1616 protected final boolean integrateRoot = true; // Set to false if conditioning on root value (not fully implemented)
1617 // protected final boolean integrateRoot = false;
1618 protected static boolean DEBUG = false;
1619 protected static boolean DEBUG_PREORDER = false;
1620 protected static boolean DEBUG_PNAS = false;
1621
1622 private double[] zeroDimVector;
1623
1624 protected WishartSufficientStatistics wishartStatistics;
1625
1626 // Reusable temporary storage
1627 protected double[] Ay;
1628 protected double[][] tmpM;
1629 protected double[] tmp2;
1630
1631 protected final MissingTraits missingTraits;
1632
1633 // class NodeClamp {
1634 // private double trait[];
1635 // private double precision;
1636 //
1637 // List<Integer> tipList;
1638 //
1639 //// BitSet tipSet;
1640 //
1641 // NodeClamp(double trait[], double precision) {
1642 //// tipSet = Tree.Utils.getTipsBitSetForTaxa(tree, taxa);
1643 //// this.tipSet = tipSet;
1644 // this.trait = trait;
1645 // this.precision = precision;
1646 // }
1647 //
1648 // double[] getTrait() { return trait; }
1649 //
1650 // double getTrait(int i) { return trait[i]; }
1651 //
1652 // double getPrecision() { return precision; }
1653 //
1654 //// BitSet getTipSet() { return tipSet; }
1655 //
1656 // }
1657
1658 @Override
1659 protected void addRestrictedPartials(RestrictedPartials nodeClamp) {
1660 if (clampList == null) {
1661 clampList = new HashMap<BitSet, RestrictedPartials>();
1662 }
1663 clampList.put(nodeClamp.getTipBitSet(), nodeClamp);
1664 addModel(nodeClamp);
1665
1666 System.err.println("Added a CLAMP!");
1667 }
1668
1669 // protected boolean clampsKnown = false;
1670 protected Map<BitSet, RestrictedPartials> clampList = null;
1671 // protected Map<BitSet, RestrictedPartials> savedClampList;
1672 protected Map<NodeRef, RestrictedPartials> nodeToClampMap = null;
1673 // protected Map<NodeRef, RestrictedPartials> savedNodeToClampMap;
1674
1675 private int partialsCount;
1676 private int spareIndex;
1677
1678 protected boolean anyClamps = false;
1679
1680 }