Debian Codegraph @

src/dr/evomodel/treedatalikelihood/continuous/ContinuousDataLikelihoodDelegate.java

raw symbols SCIP
1 /*
2 * ContinuousDataLikelihoodDelegate.java
3 *
4 * Copyright (c) 2002-2016 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.treedatalikelihood.continuous;
27
28 /*
29 * ContinuousDataLikelihoodDelegate
30 *
31 * A DataLikelihoodDelegate for continuous traits
32 *
33 * @author Andrew Rambaut
34 * @author Marc Suchard
35 * @author Philippe Lemey
36 * @version $Id$
37 */
38
39 import dr.evolution.tree.MutableTreeModel;
40 import dr.evolution.tree.NodeRef;
41 import dr.evolution.tree.Tree;
42 import dr.evolution.tree.TreeTraitProvider;
43 import dr.evolution.util.Taxon;
44 import dr.evolution.util.TaxonList;
45 import dr.evomodel.branchratemodel.BranchRateModel;
46 import dr.evomodel.continuous.MultivariateDiffusionModel;
47 import dr.evomodel.treedatalikelihood.*;
48 import dr.evomodel.treedatalikelihood.continuous.cdi.*;
49 import dr.evomodel.treedatalikelihood.preorder.ConditionalVarianceAndTransform;
50 import dr.evomodel.treedatalikelihood.preorder.ProcessSimulationDelegate;
51 import dr.evomodel.treedatalikelihood.preorder.TipFullConditionalDistributionDelegate;
52 import dr.evomodel.treedatalikelihood.preorder.TipGradientViaFullConditionalDelegate;
53 import dr.inference.model.*;
54 import dr.math.KroneckerOperation;
55 import dr.math.distributions.MultivariateNormalDistribution;
56 import dr.math.distributions.WishartSufficientStatistics;
57 import dr.math.interfaces.ConjugateWishartStatisticsProvider;
58 import dr.math.matrixAlgebra.Matrix;
59 import dr.util.Citable;
60 import dr.util.Citation;
61 import dr.util.CommonCitations;
62
63 import java.util.*;
64 import java.util.logging.Logger;
65
66 public class ContinuousDataLikelihoodDelegate extends AbstractModel implements DataLikelihoodDelegate,
67 ConjugateWishartStatisticsProvider, Citable {
68
69 private final int numTraits;
70 private final int dimTrait;
71 private final PrecisionType precisionType;
72 private final ContinuousRateTransformation rateTransformation;
73 private final Tree tree;
74 private final BranchRateModel rateModel;
75 private final ConjugateRootTraitPrior rootPrior;
76 private final boolean forceCompletelyObserved;
77
78 private double branchNormalization;
79 private double storedBranchNormalization;
80
81 private boolean allowSingular = false;
82
83 private TreeDataLikelihood callbackLikelihood = null;
84
85 public ContinuousDataLikelihoodDelegate(Tree tree,
86 DiffusionProcessDelegate diffusionProcessDelegate,
87 ContinuousTraitPartialsProvider dataModel,
88 ConjugateRootTraitPrior rootPrior,
89 ContinuousRateTransformation rateTransformation,
90 BranchRateModel rateModel,
91 boolean allowSingular) {
92 this(tree, diffusionProcessDelegate, dataModel, rootPrior, rateTransformation, rateModel,
93 false, allowSingular);
94 }
95
96 public ContinuousDataLikelihoodDelegate(Tree tree,
97 DiffusionProcessDelegate diffusionProcessDelegate,
98 ContinuousTraitPartialsProvider dataModel,
99 ConjugateRootTraitPrior rootPrior,
100 ContinuousRateTransformation rateTransformation,
101 BranchRateModel rateModel,
102 boolean forceCompletelyObserved,
103 boolean allowSingular) {
104
105 super("ContinuousDataLikelihoodDelegate");
106 final Logger logger = Logger.getLogger("dr.evomodel.treedatalikelihood");
107
108 logger.info("Using ContinuousDataLikelihood Delegate");
109
110 this.diffusionProcessDelegate = diffusionProcessDelegate;
111 addModel(diffusionProcessDelegate);
112
113 this.dataModel = dataModel;
114 if (dataModel instanceof Model) {
115 addModel((Model) dataModel);
116 }
117
118 if (rateModel != null) {
119 addModel(rateModel);
120 }
121
122 this.numTraits = dataModel.getTraitCount();
123 this.dimTrait = dataModel.getTraitDimension();
124
125 this.precisionType = diffusionProcessDelegate.hasDrift() ? // TODO Handle drift in Basic/SCALAR integrator
126 PrecisionType.FULL :
127 forceCompletelyObserved ?
128 PrecisionType.SCALAR :
129 dataModel.getPrecisionType();
130
131 this.rateTransformation = rateTransformation;
132 this.tree = tree;
133 this.rateModel = rateModel;
134 this.rootPrior = rootPrior;
135
136 this.forceCompletelyObserved = forceCompletelyObserved;
137 this.allowSingular = allowSingular;
138
139 int nodeCount = tree.getNodeCount();
140 tipCount = tree.getExternalNodeCount();
141 int internalNodeCount = nodeCount - tipCount;
142
143 branchUpdateIndices = new int[nodeCount];
144 branchLengths = new double[nodeCount];
145
146 // one or two partials buffer for each tip and two for each internal node (for store restore)
147 partialBufferHelper = new BufferIndexHelper(nodeCount,
148 dataModel.bufferTips() ? 0 : tipCount);
149
150 int partialBufferCount = partialBufferHelper.getBufferCount();
151 int matrixBufferCount = diffusionProcessDelegate.getEigenBufferCount();
152
153 rootProcessDelegate = new RootProcessDelegate.FullyConjugate(rootPrior, precisionType, numTraits,
154 partialBufferCount, matrixBufferCount);
155
156 partialBufferCount += rootProcessDelegate.getExtraPartialBufferCount();
157 matrixBufferCount += rootProcessDelegate.getExtraMatrixBufferCount();
158
159 operations = new int[(internalNodeCount + rootProcessDelegate.getExtraPartialBufferCount())
160 * ContinuousDiffusionIntegrator.OPERATION_TUPLE_SIZE];
161
162 try {
163
164 ContinuousDiffusionIntegrator base;
165 if (precisionType == PrecisionType.SCALAR) {
166
167 base = new ContinuousDiffusionIntegrator.Basic(
168 precisionType,
169 numTraits,
170 dimTrait,
171 partialBufferCount,
172 matrixBufferCount
173 );
174
175 } else if (precisionType == PrecisionType.FULL) {
176
177 if (diffusionProcessDelegate instanceof DriftDiffusionModelDelegate) {
178 base = new SafeMultivariateWithDriftIntegrator(
179 precisionType,
180 numTraits,
181 dimTrait,
182 partialBufferCount,
183 matrixBufferCount
184 );
185 } else {
186 if (allowSingular) {
187 base = new SafeMultivariateIntegrator(
188 precisionType,
189 numTraits,
190 dimTrait,
191 partialBufferCount,
192 matrixBufferCount
193 );
194 } else {
195 base = new MultivariateIntegrator(
196 precisionType,
197 numTraits,
198 dimTrait,
199 partialBufferCount,
200 matrixBufferCount
201 );
202 }
203 }
204
205 } else {
206 throw new RuntimeException("Not yet implemented");
207 }
208
209 cdi = base;
210 System.err.println("Base CDI is " + cdi.getClass().getCanonicalName());
211
212 // TODO Make separate library
213 // cdi = CDIFactory.loadCDIInstance();
214 //
215 // InstanceDetails instanceDetails = cdi.getDetails();
216 // ResourceDetails resourceDetails = null;
217 //
218 // if (instanceDetails != null) {
219 // resourceDetails = CDIFactory.getResourceDetails(instanceDetails.getResourceNumber());
220 // if (resourceDetails != null) {
221 // StringBuilder sb = new StringBuilder(" Using CDI resource ");
222 // sb.append(resourceDetails.getNumber()).append(": ");
223 // sb.append(resourceDetails.getName()).append("\n");
224 // if (resourceDetails.getDescription() != null) {
225 // String[] description = resourceDetails.getDescription().split("\\|");
226 // for (String desc : description) {
227 // if (desc.trim().length() > 0) {
228 // sb.append(" ").append(desc.trim()).append("\n");
229 // }
230 // }
231 // }
232 // sb.append(" with instance flags: ").append(instanceDetails.toString());
233 // logger.info(sb.toString());
234 // } else {
235 // logger.info(" Error retrieving CDI resource for instance: " + instanceDetails.toString());
236 // }
237 // } else {
238 // logger.info(" No external CDI resources available, or resource list/requirements not met, using Java implementation");
239 // }
240
241 // Check tip data
242 for (int i = 0; i < tipCount; i++) {
243 final NodeRef node = tree.getExternalNode(i);
244 final int index = node.getNumber();
245
246 assert (i == index);
247
248 if (!checkDataAlignment(node, tree)) {
249 throw new TaxonList.MissingTaxonException("Missing taxon");
250 }
251 }
252
253 setAllTipData(dataModel.bufferTips());
254
255 rootProcessDelegate.setRootPartial(cdi);
256
257 updateDiffusionModel = true;
258
259 } catch (TaxonList.MissingTaxonException mte) {
260 throw new RuntimeException(mte.toString());
261 }
262 }
263
264 TreeDataLikelihood getCallbackLikelihood() { return callbackLikelihood; }
265
266 public PrecisionType getPrecisionType() {
267 return precisionType;
268 }
269
270 public ContinuousTraitPartialsProvider getDataModel() { return dataModel; }
271
272 public RootProcessDelegate getRootProcessDelegate() {
273 return rootProcessDelegate;
274 }
275
276 public ConjugateRootTraitPrior getRootPrior() { return rootPrior; }
277
278 @Override
279 public String getReport() {
280
281 StringBuilder sb = new StringBuilder();
282 sb.append("Tree:\n");
283 sb.append(callbackLikelihood.getId()).append("\t");
284
285 sb.append(cdi.getReport());
286
287 final Tree tree = callbackLikelihood.getTree();
288 sb.append(tree.toString());
289 sb.append("\n\n");
290
291 final double normalization = rateTransformation.getNormalization();
292 final double priorSampleSize = rootProcessDelegate.getPseudoObservations();
293
294 double[][] treeStructure = MultivariateTraitDebugUtilities.getTreeVariance(tree, 1.0, Double.POSITIVE_INFINITY);
295 sb.append("Tree structure:\n");
296 sb.append(new Matrix(treeStructure));
297 sb.append("\n\n");
298
299 double[][] treeVariance = MultivariateTraitDebugUtilities.getTreeVariance(tree, normalization, priorSampleSize);
300 double[][] traitPrecision = getDiffusionModel().getPrecisionmatrix();
301 Matrix traitVariance = new Matrix(traitPrecision).inverse();
302
303 double[][] jointVariance = KroneckerOperation.product(treeVariance, traitVariance.toComponents());
304
305 Matrix treeV = new Matrix(treeVariance);
306 Matrix treeP = treeV.inverse();
307
308 sb.append("Tree variance:\n");
309 sb.append(treeV);
310 sb.append("Tree precision:\n");
311 sb.append(treeP);
312 sb.append("\n\n");
313
314 sb.append("Trait variance:\n");
315 sb.append(traitVariance);
316 sb.append("\n\n");
317
318 sb.append("Joint variance:\n");
319 sb.append(new Matrix(jointVariance));
320 sb.append("\n\n");
321
322 double[][] treeDrift = MultivariateTraitDebugUtilities.getTreeDrift(tree, diffusionProcessDelegate);
323 if (diffusionProcessDelegate.hasDrift()) {
324 sb.append("Tree drift:\n");
325 sb.append(new Matrix(treeDrift));
326 sb.append("\n\n");
327 }
328 double[] drift = KroneckerOperation.vectorize(treeDrift);
329
330 final int datumLength = tipCount * dimTrait;
331
332 sb.append("Tree dim : ").append(treeVariance.length).append("\n");
333 sb.append("dimTrait : ").append(dimTrait).append("\n");
334 sb.append("numTraits: ").append(numTraits).append("\n");
335 sb.append("jVar dim : ").append(jointVariance.length).append("\n");
336 sb.append("datum dim: ").append(datumLength);
337 sb.append("\n\n");
338
339 double[] data = dataModel.getParameter().getParameterValues();
340
341 if (dataModel instanceof ContinuousTraitDataModel) {
342 for (int tip = 0; tip < tipCount; ++tip) {
343 double[] tipData = ((ContinuousTraitDataModel) dataModel).getTipObservation(tip, precisionType);
344 System.arraycopy(tipData, 0, data, tip * numTraits * dimTrait, numTraits * dimTrait);
345 }
346 }
347
348 sb.append("data: ").append(new dr.math.matrixAlgebra.Vector(data));
349 sb.append("\n\n");
350
351 double[][] graphStructure = MultivariateTraitDebugUtilities.getGraphVariance(tree, 1.0,
352 priorSampleSize);
353 double[][] jointGraphVariance = KroneckerOperation.product(graphStructure, traitVariance.toComponents());
354
355 sb.append("graph structure:\n");
356 sb.append(new Matrix(graphStructure));
357 sb.append("\n\n");
358
359 double[] priorMean = rootPrior.getMean();
360 sb.append("prior mean: ").append(new dr.math.matrixAlgebra.Vector(priorMean));
361 sb.append("\n\n");
362
363 for (int index = 0; index < drift.length / dimTrait; ++index) {
364 for (int dim = 0; dim < dimTrait; ++dim) {
365 drift[index * dimTrait + dim] += priorMean[dim];
366 }
367 }
368
369 for (int trait = 0; trait < numTraits; ++trait) {
370 sb.append("Trait #").append(trait).append("\n");
371
372 double[] rawDatum = new double[datumLength];
373
374 List<Integer> missing = new ArrayList<Integer>();
375 int index = 0;
376 for (int tip = 0; tip < tipCount; ++tip) {
377 for (int dim = 0; dim < dimTrait; ++dim) {
378 double d = data[tip * dimTrait * numTraits + trait * dimTrait + dim];
379 rawDatum[index] = d;
380 if (Double.isNaN(d)) {
381 missing.add(index);
382 }
383 ++index;
384 }
385 }
386
387 double[][] varianceDatum = jointVariance;
388 double[] datum = rawDatum;
389
390 double[] driftDatum = drift;
391
392 int[] notMissingIndices;
393 if (missing.size() > 0) {
394 notMissingIndices = new int[datumLength - missing.size()];
395 int offsetNotMissing = 0;
396 for (int i = 0; i < datumLength; ++i) {
397 if (!missing.contains(i)) {
398 notMissingIndices[offsetNotMissing] = i;
399 ++offsetNotMissing;
400 }
401 }
402
403 datum = Matrix.gatherEntries(rawDatum, notMissingIndices);
404 varianceDatum = Matrix.gatherRowsAndColumns(jointVariance, notMissingIndices, notMissingIndices);
405
406 driftDatum = Matrix.gatherEntries(drift, notMissingIndices);
407 }
408
409 sb.append("datum : ").append(new dr.math.matrixAlgebra.Vector(datum)).append("\n");
410
411 sb.append("drift : ").append(new dr.math.matrixAlgebra.Vector(driftDatum)).append("\n");
412
413 sb.append("variance:\n");
414 sb.append(new Matrix(varianceDatum));
415
416 MultivariateNormalDistribution mvn = new MultivariateNormalDistribution(driftDatum, new Matrix(varianceDatum).inverse().toComponents());
417 double logDensity = mvn.logPdf(datum);
418 sb.append("\n\n");
419 sb.append("logDatumLikelihood: ").append(logDensity).append("\n\n");
420
421 // Compute joint for internal nodes
422 int[] cNotMissingJoint = new int[dimTrait * tipCount];
423 int[] cMissingJoint = new int[dimTrait * (tipCount - 1)];
424
425 // External nodes
426 for (int tipTrait = 0; tipTrait < dimTrait * tipCount; ++tipTrait) {
427 cNotMissingJoint[tipTrait] = tipTrait;
428 }
429
430 // Internal nodes
431 for (int tipTrait = dimTrait * tipCount; tipTrait < dimTrait * (2 * tipCount - 1); ++tipTrait) {
432 cMissingJoint[tipTrait - dimTrait * tipCount] = tipTrait;
433 }
434
435 double[] rawDatumJoint = new double[dimTrait * (2 * tipCount - 1)];
436 System.arraycopy(rawDatum, 0, rawDatumJoint, 0, rawDatum.length);
437
438 double[][] driftJointMatrix = MultivariateTraitDebugUtilities.getGraphDrift(tree, diffusionProcessDelegate);
439 double[] driftJoint = KroneckerOperation.vectorize(driftJointMatrix);
440
441 for (int idx = 0; idx < driftJoint.length / dimTrait; ++idx) {
442 for (int dim = 0; dim < dimTrait; ++dim) {
443 driftJoint[idx * dimTrait + dim] += priorMean[dim];
444 }
445 }
446
447 ConditionalVarianceAndTransform cVarianceJoint = new ConditionalVarianceAndTransform(
448 new Matrix(jointGraphVariance), cMissingJoint, cNotMissingJoint);
449
450 double[] cMeanJoint = cVarianceJoint.getConditionalMean(rawDatumJoint, 0, driftJoint, 0);
451
452 sb.append("cDriftJoint: ").append(new dr.math.matrixAlgebra.Vector(driftJoint)).append("\n\n");
453
454 sb.append("cMeanInternalJoint: ").append(new dr.math.matrixAlgebra.Vector(cMeanJoint)).append("\n\n");
455
456 // Compute full conditional distributions
457 sb.append("Full conditional distributions:\n");
458
459
460 int[] cMissing = new int[dimTrait];
461 int[] cNotMissing = new int[tipCount * dimTrait - dimTrait];
462
463 for (int tip = 0; tip < tipCount; ++tip) {
464
465 for (int cTrait = 0; cTrait < dimTrait; ++cTrait) {
466 cMissing[cTrait] = tip * dimTrait + cTrait;
467 }
468
469 for (int m = 0; m < tip * dimTrait; ++m) {
470 cNotMissing[m] = m;
471 }
472
473 for (int m = (tip + 1) * dimTrait; m < tipCount * dimTrait; ++m) {
474 cNotMissing[m - dimTrait] = m;
475 }
476
477 ConditionalVarianceAndTransform cVariance = new ConditionalVarianceAndTransform(
478 new Matrix(jointVariance), cMissing, cNotMissing);
479
480 double[] cMean = cVariance.getConditionalMean(rawDatum, 0, drift, 0);
481
482 sb.append("cMean #").append(tip).append(" ").append(new dr.math.matrixAlgebra.Vector(cMean))
483 .append("\n");
484 }
485 }
486
487 return sb.toString();
488 }
489
490 @Override
491 public final int getTraitCount() {
492 return numTraits;
493 }
494
495 @Override
496 public final int getTraitDim() {
497 return dimTrait;
498 }
499
500 @Override
501 public RateRescalingScheme getRateRescalingScheme() {
502 return rateTransformation.getRateRescalingScheme();
503 }
504
505 public final ContinuousDiffusionIntegrator getIntegrator() {
506 return cdi;
507 }
508
509 final ContinuousRateTransformation getRateTransformation() {
510 return rateTransformation;
511 }
512
513 @Override
514 public void setCallback(TreeDataLikelihood treeDataLikelihood) {
515 this.callbackLikelihood = treeDataLikelihood;
516 }
517
518 @Override
519 public int vectorizeNodeOperations(final List<ProcessOnTreeDelegate.NodeOperation> nodeOperations,
520 final int[] operations) {
521
522 int k = 0;
523 for (NodeOperation op : nodeOperations) {
524
525 operations[k ] = getActiveNodeIndex(op.getNodeNumber());
526 operations[k + 1] = getActiveNodeIndex(op.getLeftChild()); // source node 1
527 operations[k + 2] = getActiveMatrixIndex(op.getLeftChild()); // source matrix 1
528 operations[k + 3] = getActiveNodeIndex(op.getRightChild()); // source node 2
529 operations[k + 4] = getActiveMatrixIndex(op.getRightChild()); // source matrix 2
530
531 k += ContinuousDiffusionIntegrator.OPERATION_TUPLE_SIZE;
532 }
533
534 return nodeOperations.size();
535 }
536
537 // public static String getStringOfVectorizedOperations(final int[] operations, final int count) {
538 // StringBuilder sb = new StringBuilder();
539 // int k = 0;
540 // for (int i = 0; i < count; ++i) {
541 // sb.append(operations[k ]).append(" ");
542 // sb.append(operations[k + 1]).append(" ");
543 // sb.append(operations[k + 2]).append(" ");
544 // sb.append(operations[k + 3]).append(" ");
545 // sb.append(operations[k + 4]).append("\n");
546 //
547 // k += ContinuousDiffusionIntegrator.OPERATION_TUPLE_SIZE;
548 // }
549 //
550 // return sb.toString();
551 // }
552
553 public DiffusionProcessDelegate getDiffusionProcessDelegate() { return diffusionProcessDelegate; }
554
555 public MultivariateDiffusionModel getDiffusionModel() {
556 return diffusionProcessDelegate.getDiffusionModel(0);
557 }
558
559 private void setAllTipData(boolean flip) {
560 for (int index = 0; index < tipCount; index++) {
561 setTipData(index, flip);
562 }
563 updateTipData.clear();
564 }
565
566 private void setTipData(int tipIndex, boolean flip) {
567 if (flip) {
568 partialBufferHelper.flipOffset(tipIndex);
569 }
570
571 final double[] tipPartial = dataModel.getTipPartial(tipIndex, forceCompletelyObserved);
572 setTipDataDirectly(tipIndex, tipPartial);
573 }
574
575 void setTipDataDirectly(int tipIndex, double[] tipPartial) {
576 cdi.setPostOrderPartial(partialBufferHelper.getOffsetIndex(tipIndex),
577 tipPartial);
578 }
579
580 private boolean checkDataAlignment(NodeRef node, Tree tree) {
581 int index = node.getNumber();
582 String name1 = dataModel.getParameter().getParameter(index).getParameterName();
583 Taxon taxon = tree.getNodeTaxon(node);
584 return name1.contains(taxon.getId());
585 }
586
587 @Override
588 public TreeTraversal.TraversalType getOptimalTraversalType() {
589 return TreeTraversal.TraversalType.POST_ORDER;
590 }
591
592 /**
593 * Calculate the log likelihood of the current state.
594 *
595 * @return the log likelihood.
596 */
597 @Override
598 public double calculateLikelihood(List<BranchOperation> branchOperations, List<NodeOperation> nodeOperations,
599 int rootNodeNumber) throws LikelihoodException {
600
601 branchNormalization = rateTransformation.getNormalization();
602
603 int branchUpdateCount = 0;
604 for (BranchOperation op : branchOperations) {
605 branchUpdateIndices[branchUpdateCount] = op.getBranchNumber();
606 branchLengths[branchUpdateCount] = op.getBranchLength() * branchNormalization;
607 branchUpdateCount ++;
608 }
609
610 if (!updateTipData.isEmpty()) {
611 if (updateTipData.getFirst() == -1) { // Update all tips
612 setAllTipData(flip);
613 } else {
614 while(!updateTipData.isEmpty()) {
615 int tipIndex = updateTipData.removeFirst();
616 setTipData(tipIndex, flip);
617 }
618 }
619 }
620
621 if (updateDiffusionModel) {
622 diffusionProcessDelegate.setDiffusionModels(cdi, flip);
623 }
624
625 if (branchUpdateCount > 0) {
626 diffusionProcessDelegate.updateDiffusionMatrices(
627 cdi,
628 branchUpdateIndices,
629 branchLengths,
630 branchUpdateCount,
631 flip);
632 }
633
634 if (flip) {
635 // Flip all the buffers to be written to first...
636 for (NodeOperation op : nodeOperations) {
637 partialBufferHelper.flipOffset(op.getNodeNumber());
638 }
639 }
640
641 int operationCount = vectorizeNodeOperations(nodeOperations, operations);
642
643 int[] degreesOfFreedom = null;
644 double[] outerProducts = null;
645
646 if (computeWishartStatistics) {
647 degreesOfFreedom = new int[numTraits];
648 outerProducts = new double[dimTrait * dimTrait * numTraits];
649 cdi.setWishartStatistics(degreesOfFreedom, outerProducts);
650 }
651
652 cdi.updatePostOrderPartials(operations, operationCount, computeWishartStatistics);
653
654 double[] logLikelihoods = new double[numTraits];
655
656 rootProcessDelegate.calculateRootLogLikelihood(cdi, partialBufferHelper.getOffsetIndex(rootNodeNumber),
657 logLikelihoods, computeWishartStatistics);
658
659 if (computeWishartStatistics) {
660 cdi.getWishartStatistics(degreesOfFreedom, outerProducts);
661 wishartStatistics = new WishartSufficientStatistics(
662 degreesOfFreedom,
663 outerProducts
664 );
665
666 } else {
667 wishartStatistics = null;
668 }
669
670 double logL = 0.0;
671 for (double d : logLikelihoods) {
672 logL += d;
673 }
674
675 updateDiffusionModel = false;
676
677 return logL;
678 }
679
680 public final int getActiveNodeIndex(final int index) {
681 return partialBufferHelper.getOffsetIndex(index);
682 }
683
684 public final int getActiveMatrixIndex(final int index) {
685 return diffusionProcessDelegate.getMatrixIndex(index);
686 }
687
688 public void getPostOrderPartial(final int nodeNumber, double[] vector) {
689 cdi.getPostOrderPartial(getActiveNodeIndex(nodeNumber), vector);
690 }
691
692 // public void getPostOrderPartial(final int nodeNumber, double[] vector, double[] matrix, double[] displacement) {
693 // cdi.getPostOrderPartial(getActiveNodeIndex(nodeNumber), vector, matrix, displacement);
694 // }
695 //
696 // public void getPreOrderPartial(final int nodeNumber, double[] vector) {
697 // cdi.getPreOrderPartial(getActiveNodeIndex(nodeNumber), vector);
698 // }
699
700 @Override
701 public void makeDirty() {
702 updateDiffusionModel = true;
703 fireModelChanged(); // Signal simulation processes
704 }
705
706 @Override
707 protected void handleModelChangedEvent(Model model, Object object, int index) {
708 if (model == diffusionProcessDelegate) {
709 updateDiffusionModel = true;
710 // Tell TreeDataLikelihood to update all nodes
711 fireModelChanged();
712 } else if (model == dataModel) {
713 if (object == dataModel) {
714 if (index == -1) { // all taxa updated
715 updateTipData.addFirst(index);
716 fireModelChanged();
717 } else { // only one taxon updated
718 updateTipData.addLast(index);
719 fireModelChanged(this, index);
720 }
721 }
722
723 } else if (model instanceof BranchRateModel) {
724 fireModelChanged();
725 } else {
726 throw new RuntimeException("Unknown model component");
727 }
728 }
729
730 @Override
731 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type) {
732 // Do nothing
733 }
734
735 /**
736 * Stores the additional state other than model components
737 */
738 @Override
739 public void storeState() {
740 partialBufferHelper.storeState();
741
742 // turn on double buffering flipping (may have been turned off to enable a rescale)
743 flip = true;
744
745 storedBranchNormalization = branchNormalization;
746 }
747
748 /**
749 * Restore the additional stored state
750 */
751 @Override
752 public void restoreState() {
753 partialBufferHelper.restoreState();
754
755 branchNormalization = storedBranchNormalization;
756 }
757
758 @Override
759 protected void acceptState() {
760 }
761
762 // **************************************************************
763 // INSTANCE CITABLE
764 // **************************************************************
765
766 @Override
767 public Citation.Category getCategory() {
768 return Citation.Category.TRAIT_MODELS;
769 }
770
771 @Override
772 public String getDescription() {
773 return "TODO";
774 }
775
776 @Override
777 public List<Citation> getCitations() {
778 return Collections.singletonList(CommonCitations.LEMEY_2010_PHYLOGEOGRAPHY);
779 }
780
781 // **************************************************************
782 // INSTANCE VARIABLES
783 // **************************************************************
784
785 private final int tipCount;
786
787 private final int[] branchUpdateIndices;
788 private final double[] branchLengths;
789
790 private final int[] operations;
791
792 private boolean flip = true;
793 private final BufferIndexHelper partialBufferHelper;
794
795 private final DiffusionProcessDelegate diffusionProcessDelegate;
796
797 private final RootProcessDelegate rootProcessDelegate;
798
799 private final ContinuousTraitPartialsProvider dataModel;
800
801 private final ContinuousDiffusionIntegrator cdi;
802
803 private boolean updateDiffusionModel;
804
805 private final Deque<Integer> updateTipData = new ArrayDeque<Integer>();
806
807 private WishartSufficientStatistics wishartStatistics = null;
808
809 private boolean computeWishartStatistics = false;
810
811 @Override
812 public WishartSufficientStatistics getWishartStatistics() {
813 return wishartStatistics;
814 }
815
816 void setComputeWishartStatistics(boolean computeWishartStatistics) {
817 this.computeWishartStatistics = computeWishartStatistics;
818 }
819
820 @Override
821 public MatrixParameterInterface getPrecisionParameter() {
822 return getDiffusionModel().getPrecisionParameter();
823 }
824
825 public void addFullConditionalGradientTrait(String traitName) {
826
827 ProcessSimulationDelegate gradientDelegate = new TipGradientViaFullConditionalDelegate(traitName,
828 (MutableTreeModel) getCallbackLikelihood().getTree(),
829 getDiffusionModel(),
830 (ContinuousTraitDataModel) getDataModel(), getRootPrior(),
831 getRateTransformation(), this);
832
833 TreeTraitProvider traitProvider = new ProcessSimulation(getCallbackLikelihood(), gradientDelegate);
834
835 getCallbackLikelihood().addTraits(traitProvider.getTreeTraits());
836 }
837
838 public void addFullConditionalDensityTrait(String traitName) {
839
840 ProcessSimulationDelegate gradientDelegate = new TipFullConditionalDistributionDelegate(traitName,
841 getCallbackLikelihood().getTree(),
842 getDiffusionModel(),
843 getDataModel(), getRootPrior(),
844 getRateTransformation(), this);
845
846 TreeTraitProvider traitProvider = new ProcessSimulation(getCallbackLikelihood(), gradientDelegate);
847
848 getCallbackLikelihood().addTraits(traitProvider.getTreeTraits());
849 }
850
851 static ContinuousDataLikelihoodDelegate createObservedDataOnly(ContinuousDataLikelihoodDelegate likelihoodDelegate) {
852 return new ContinuousDataLikelihoodDelegate(likelihoodDelegate.tree,
853 likelihoodDelegate.diffusionProcessDelegate,
854 likelihoodDelegate.dataModel,
855 likelihoodDelegate.rootPrior,
856 likelihoodDelegate.rateTransformation,
857 likelihoodDelegate.rateModel,
858 true,
859 likelihoodDelegate.allowSingular);
860 }
861
862 static ContinuousDataLikelihoodDelegate createWithMissingData(ContinuousDataLikelihoodDelegate likelihoodDelegate) {
863
864 if (!(likelihoodDelegate.dataModel instanceof ContinuousTraitDataModel)) {
865 throw new IllegalArgumentException("Not yet implemented");
866 }
867
868 List<Integer> originalMissingIndices = ((ContinuousTraitDataModel) likelihoodDelegate.dataModel).getOriginalMissingIndices();
869
870 if (originalMissingIndices.size() == 0) {
871 throw new IllegalArgumentException("ContinuousDataLikelihoodDelegate has no missing traits");
872 }
873
874 ContinuousTraitPartialsProvider newDataModel = new ContinuousTraitDataModel(((ContinuousTraitDataModel) likelihoodDelegate.dataModel).getName(),
875 likelihoodDelegate.dataModel.getParameter(),
876 ((ContinuousTraitDataModel) likelihoodDelegate.dataModel).getOriginalMissingIndices(),
877 true,
878 likelihoodDelegate.getTraitDim(), PrecisionType.FULL);
879
880 return new ContinuousDataLikelihoodDelegate(likelihoodDelegate.tree,
881 likelihoodDelegate.diffusionProcessDelegate,
882 newDataModel,
883 likelihoodDelegate.rootPrior,
884 likelihoodDelegate.rateTransformation,
885 likelihoodDelegate.rateModel,
886 false,
887 likelihoodDelegate.allowSingular);
888 }
889 }