Debian Codegraph @

src/dr/evomodel/continuous/FullyConjugateMultivariateTraitLikelihood.java

raw symbols SCIP
1 /*
2 * FullyConjugateMultivariateTraitLikelihood.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.TreeUtils;
31 import dr.evomodel.branchratemodel.BranchRateModel;
32 import dr.inference.model.*;
33 import dr.math.KroneckerOperation;
34 import dr.math.distributions.MultivariateNormalDistribution;
35 import dr.math.distributions.WishartSufficientStatistics;
36 import dr.math.interfaces.ConjugateWishartStatisticsProvider;
37 import dr.math.matrixAlgebra.IllegalDimension;
38 import dr.math.matrixAlgebra.Matrix;
39 import dr.math.matrixAlgebra.Vector;
40 import dr.xml.Reportable;
41
42 import java.util.*;
43
44 /**
45 * Integrated multivariate trait likelihood that assumes a fully-conjugate prior on the root.
46 * The fully-conjugate prior is a multivariate normal distribution with a precision scaled by
47 * diffusion process
48 *
49 * @author Marc A. Suchard
50 */
51 public class FullyConjugateMultivariateTraitLikelihood extends IntegratedMultivariateTraitLikelihood
52 implements ConjugateWishartStatisticsProvider, GibbsSampleFromTreeInterface, Reportable {
53
54 // public FullyConjugateMultivariateTraitLikelihood(String traitName,
55 // MutableTreeModel treeModel,
56 // MultivariateDiffusionModel diffusionModel,
57 // CompoundParameter traitParameter,
58 // Parameter deltaParameter,
59 // List<Integer> missingIndices,
60 // boolean cacheBranches,
61 // boolean scaleByTime,
62 // boolean useTreeLength,
63 // BranchRateModel rateModel,
64 // Model samplingDensity,
65 // boolean reportAsMultivariate,
66 // double[] rootPriorMean,
67 // double rootPriorSampleSize,
68 // boolean reciprocalRates) {
69 //
70 // super(traitName, treeModel, diffusionModel, traitParameter, deltaParameter, missingIndices, cacheBranches, scaleByTime,
71 // useTreeLength, rateModel, samplingDensity, reportAsMultivariate, reciprocalRates);
72 //
73 // // fully-conjugate multivariate normal with own mean and prior sample size
74 // this.rootPriorMean = rootPriorMean;
75 // this.rootPriorSampleSize = rootPriorSampleSize;
76 //
77 // priorInformationKnown = false;
78 // }
79 //
80 //
81 // public FullyConjugateMultivariateTraitLikelihood(String traitName,
82 // MutableTreeModel treeModel,
83 // MultivariateDiffusionModel diffusionModel,
84 // CompoundParameter traitParameter,
85 // Parameter deltaParameter,
86 // List<Integer> missingIndices,
87 // boolean cacheBranches,
88 // boolean scaleByTime,
89 // boolean useTreeLength,
90 // BranchRateModel rateModel,
91 // List<BranchRateModel> driftModels,
92 // Model samplingDensity,
93 // boolean reportAsMultivariate,
94 // double[] rootPriorMean,
95 // double rootPriorSampleSize,
96 // boolean reciprocalRates) {
97 //
98 // super(traitName, treeModel, diffusionModel, traitParameter, deltaParameter, missingIndices, cacheBranches, scaleByTime,
99 // useTreeLength, rateModel, driftModels, samplingDensity, reportAsMultivariate, reciprocalRates);
100 //
101 // // fully-conjugate multivariate normal with own mean and prior sample size
102 // this.rootPriorMean = rootPriorMean;
103 // this.rootPriorSampleSize = rootPriorSampleSize;
104 //
105 // priorInformationKnown = false;
106 // }
107
108 public FullyConjugateMultivariateTraitLikelihood(String traitName,
109 MutableTreeModel treeModel,
110 MultivariateDiffusionModel diffusionModel,
111 CompoundParameter traitParameter,
112 Parameter deltaParameter,
113 List<Integer> missingIndices,
114 boolean cacheBranches,
115 boolean scaleByTime,
116 boolean useTreeLength,
117 BranchRateModel rateModel,
118 List<BranchRateModel> driftModels,
119 List<BranchRateModel> optimalValues,
120 BranchRateModel strengthOfSelection,
121 Model samplingDensity,
122 boolean reportAsMultivariate,
123 double[] rootPriorMean,
124 List<RestrictedPartials> partials,
125 double rootPriorSampleSize,
126 boolean reciprocalRates) {
127
128 super(traitName, treeModel, diffusionModel, traitParameter, deltaParameter, missingIndices, cacheBranches, scaleByTime,
129 useTreeLength, rateModel, driftModels, optimalValues, strengthOfSelection, samplingDensity, partials, reportAsMultivariate, reciprocalRates);
130
131 // fully-conjugate multivariate normal with own mean and prior sample size
132 this.rootPriorMean = rootPriorMean;
133 this.rootPriorSampleSize = rootPriorSampleSize;
134
135 priorInformationKnown = false;
136 }
137
138
139 //TODO temporary function so everything will compile. Need to actually write this.
140 public FullyConjugateMultivariateTraitLikelihood semiClone(CompoundParameter traitParameter){
141 return this;
142 }
143
144 // public FullyConjugateMultivariateTraitLikelihood semiClone(CompoundParameter traitParameter){
145 // return new FullyConjugateMultivariateTraitLikelihood(this.traitName, this.treeModel, this.diffusionModel, traitParameter,
146 // this.deltaParameter, this.missingIndices, this.cacheBranches, this.scaleByTime, this.useTreeLength, this.getBranchRateModel(),
147 // this.optimalValues, this.strengthOfSelection, this.samplingDensity, this.reportAsMultivariate, this.rootPriorMean,
148 // this.rootPriorSampleSize, this.reciprocalRates);
149 // }
150
151 public double getRescaledLengthToRoot(NodeRef nodeRef) {
152
153 double length = 0;
154
155 if (!treeModel.isRoot(nodeRef)) {
156 NodeRef parent = treeModel.getParent(nodeRef);
157 length += getRescaledBranchLengthForPrecision(nodeRef) + getRescaledLengthToRoot(parent);
158 }
159
160 return length;
161 }
162
163
164 protected double calculateAscertainmentCorrection(int taxonIndex) {
165
166 NodeRef tip = treeModel.getNode(taxonIndex);
167 int nodeIndex = treeModel.getNode(taxonIndex).getNumber();
168
169 if (ascertainedData == null) { // Assumes that ascertained data are fixed
170 ascertainedData = new double[dimTrait];
171 }
172
173 // diffusionModel.diffusionPrecisionMatrixParameter.setParameterValue(0,2); // For debugging non-1 values
174 double[][] traitPrecision = diffusionModel.getPrecisionmatrix();
175 double logDetTraitPrecision = Math.log(diffusionModel.getDeterminantPrecisionMatrix());
176
177 double lengthToRoot = getRescaledLengthToRoot(tip);
178 double marginalPrecisionScalar = 1.0 / lengthToRoot + rootPriorSampleSize;
179 double logLikelihood = 0;
180
181 for (int datum = 0; datum < numData; ++datum) {
182
183 // Get observed trait value
184 System.arraycopy(meanCache, nodeIndex * dim + datum * dimTrait, ascertainedData, 0, dimTrait);
185
186 if (DEBUG_ASCERTAINMENT) {
187 System.err.println("Datum #" + datum);
188 System.err.println("Value: " + new Vector(ascertainedData));
189 System.err.println("Cond : " + lengthToRoot);
190 System.err.println("MargV: " + 1.0 / marginalPrecisionScalar);
191 System.err.println("MargP: " + marginalPrecisionScalar);
192 System.err.println("diffusion prec: " + new Matrix(traitPrecision));
193 }
194
195 double SSE;
196 if (dimTrait > 1) {
197 throw new RuntimeException("Still need to implement multivariate ascertainment correction");
198 } else {
199 double precision = traitPrecision[0][0] * marginalPrecisionScalar;
200
201 SSE = ascertainedData[0] * precision * ascertainedData[0];
202 }
203
204 double thisLogLikelihood = -LOG_SQRT_2_PI * dimTrait
205 + 0.5 * (logDetTraitPrecision + dimTrait * Math.log(marginalPrecisionScalar) - SSE);
206
207 if (DEBUG_ASCERTAINMENT) {
208 System.err.println("LogLik: " + thisLogLikelihood);
209 dr.math.distributions.NormalDistribution normal = new dr.math.distributions.NormalDistribution(0,
210 Math.sqrt(1.0 / (traitPrecision[0][0] * marginalPrecisionScalar)));
211 System.err.println("TTTLik: " + normal.logPdf(ascertainedData[0]));
212 if (datum >= 10) {
213 System.exit(-1);
214 }
215 }
216 logLikelihood += thisLogLikelihood;
217 }
218 return logLikelihood;
219 }
220
221 // public double getRootPriorSampleSize() {
222 // return rootPriorSampleSize;
223 // }
224
225 // public double[] getRootPriorMean() {
226 // double[] out = new double[rootPriorMean.length];
227 // System.arraycopy(rootPriorMean, 0, out, 0, out.length);
228 // return out;
229 // }
230
231 public WishartSufficientStatistics getWishartStatistics() {
232 computeWishartStatistics = true;
233 calculateLogLikelihood();
234 computeWishartStatistics = false;
235 return wishartStatistics;
236 }
237
238 @Override
239 public MatrixParameterInterface getPrecisionParameter() {
240 return diffusionModel.getPrecisionParameter();
241 }
242
243 // private double getLogPrecisionDetermination() {
244 // return Math.log(diffusionModel.getDeterminantPrecisionMatrix()) + dimTrait * Math.log(rootPriorSampleSize);
245 // }
246
247 protected void handleModelChangedEvent(Model model, Object object, int index) {
248
249 if (model == diffusionModel) {
250 priorInformationKnown = false;
251 }
252 super.handleModelChangedEvent(model, object, index);
253 }
254
255 @Override
256 protected void handleVariableChangedEvent(Variable variable, int index, Parameter.ChangeType type){
257 if(variable==traitParameter
258 &&(Parameter.ChangeType.ADDED==type || Parameter.ChangeType.REMOVED==type)
259 ){
260 dimKnown = false;
261 dim = traitParameter.getParameter(0).getDimension();
262 numData = dim / getDimTrait();
263 meanCache = new double[dim * treeModel.getNodeCount()];
264 // storedMeanCache = new double[meanCache.length];
265 drawnStates = new double[dim * treeModel.getNodeCount()];
266 }
267 PostPreKnown=false;
268 super.handleVariableChangedEvent(variable,index,type);
269 }
270
271 @Override
272 public void storeState() {
273 storedNumData = numData;
274 storedDim = dim;
275 super.storeState();
276 storedPostPreKnown=PostPreKnown;
277 storedDimKnown=dimKnown;
278 if(preP!=null)
279 System.arraycopy(preP, 0, storedPreP, 0,preP.length);
280 if(preMeans!=null){
281 for(int i = 0; i < preMeans.length; i++)
282 storedPreMeans[i] = preMeans[i].clone();
283 }
284
285 }
286
287 @Override
288 public void restoreState() {
289 dim = storedDim;
290 numData = storedNumData;
291 drawnStates = new double[dim * treeModel.getNodeCount()];
292 super.restoreState();
293 PostPreKnown=storedPostPreKnown;
294 priorInformationKnown = false;
295 double[] tempPreP = storedPreP;
296 storedPreP = preP;
297 preP = tempPreP;
298 preMeans=storedPreMeans;
299 double[][] preMeansTemp = preMeans;
300 preMeans = storedPreMeans;
301 storedPreMeans = preMeansTemp;
302 dimKnown=storedDimKnown;
303 }
304
305 public void makeDirty() {
306 super.makeDirty();
307 priorInformationKnown = false;
308 }
309
310 public double getPriorSampleSize() {
311 return rootPriorSampleSize;
312 }
313
314 public double[] getPriorMean() {
315 return rootPriorMean;
316 }
317
318 @Override
319 public boolean getComputeWishartSufficientStatistics() {
320 return computeWishartStatistics;
321 }
322
323 public void doPreOrderTraversal(NodeRef node) {
324
325 if(preP==null){
326 preP=new double[treeModel.getNodeCount()];
327 storedPreP=new double[treeModel.getNodeCount()];
328 }
329 if(!dimKnown){
330 preMeans=new double[treeModel.getNodeCount()][dim];
331 storedPreMeans=new double[treeModel.getNodeCount()][dim];
332 dimKnown=true;
333 }
334
335 final int thisNumber = node.getNumber();
336
337
338 if (treeModel.isRoot(node)) {
339 preP[thisNumber] = rootPriorSampleSize;
340 for (int j = 0; j < dim; j++) {
341 preMeans[thisNumber][j]
342 = rootPriorMean[j % dimTrait];
343 }
344
345
346 } else {
347
348 final NodeRef parentNode = treeModel.getParent(node);
349 final NodeRef sibNode = getSisterNode(node);
350
351 final int parentNumber = parentNode.getNumber();
352 final int sibNumber = sibNode.getNumber();
353
354
355
356 /*
357
358 if (treeModel.isRoot(parentNode)){
359 //partial precisions
360 final double precisionParent = rootPriorSampleSize;
361 final double precisionSib = postP[sibNumber];
362 final double thisPrecision=1/treeModel.getBranchLength(node);
363 double tp= precisionParent + precisionSib;
364 preP[thisNumber]= tp*thisPrecision/(tp+thisPrecision);
365
366 //partial means
367
368 for (int j =0; j<dim;j++){
369 preMeans[thisNumber][j] = (precisionParent*preMeans[parentNumber][j] + precisionSib*rootPriorMean[j])/(precisionParent+precisionSib);
370 }
371
372 }else{
373 */
374 //partial precisions
375 final double precisionParent = preP[parentNumber];
376 final double precisionSib = upperPrecisionCache[sibNumber];
377 final double thisPrecision = 1 / getRescaledBranchLengthForPrecision(node);
378 double tp = precisionParent + precisionSib;
379 preP[thisNumber] = tp * thisPrecision / (tp + thisPrecision);
380
381 //partial means
382
383 for (int j = 0; j < dim; j++) {
384 preMeans[thisNumber][j] = (precisionParent * preMeans[parentNumber][j] + precisionSib * cacheHelper.getMeanCache()[sibNumber*dim+j]) / (precisionParent + precisionSib);
385 }
386 }
387
388 if (treeModel.isExternal(node)) {
389 return;
390 } else {
391 doPreOrderTraversal(treeModel.getChild(node, 0));
392 doPreOrderTraversal(treeModel.getChild(node, 1));
393
394 }
395
396 }
397
398 public NodeRef getSisterNode(NodeRef node) {
399 NodeRef sib0 = treeModel.getChild(treeModel.getParent(node), 0);
400 NodeRef sib1 = treeModel.getChild(treeModel.getParent(node), 1);
401
402
403 if (sib0 == node) {
404 return sib1;
405 } else return sib0;
406
407 }
408
409 public double[] getConditionalMean(int taxa){
410 setup();
411
412
413 // double[] answer=new double[getRootNodeTrait().length];
414
415 double[] mean = new double[dim];
416 for (int i = 0; i < dim; i++) {
417 mean[i] = preMeans[taxa][i];
418 }
419
420 return mean;
421 }
422
423 public double[][] getConditionalMeans(){
424 setup();
425
426
427 // double[] answer=new double[getRootNodeTrait().length];
428
429
430 return preMeans;
431 }
432
433 public double getPrecisionFactor(int taxa){
434 setup();
435 return preP[taxa];
436 }
437
438 public double[] getPrecisionFactors(){
439 setup();
440 return preP;
441 }
442
443 public double[][] getConditionalPrecision(int taxa){
444 setup();
445
446
447
448
449 double[][] precisionParam =diffusionModel.getPrecisionmatrix();
450 // double[][] answer=new double[getRootNodeTrait().length][ getRootNodeTrait().length];
451 double p = getPrecisionFactor(taxa);
452
453 double[][] thisP = new double[dim][dim];
454 for (int i = 0; i < getNumData(); i++) {
455 for (int j = 0; j < getDimTrait(); j++) {
456 for (int k = 0; k < getDimTrait(); k++) {
457 // System.out.println("P: "+p);
458 // System.out.println("I: "+i+", J: "+j+" value:"+precisionParam[i][j]);
459 thisP[i * getDimTrait() + j][i * getDimTrait() + k] = p * precisionParam[j][k];
460
461 }
462 }
463 }
464
465 return thisP;
466
467 }
468
469 private void setup(){
470 if(!PostPreKnown){
471 double[][] traitPrecision = diffusionModel.getPrecisionmatrix();
472 double logDetTraitPrecision = Math.log(diffusionModel.getDeterminantPrecisionMatrix());
473
474 final boolean computeWishartStatistics = getComputeWishartSufficientStatistics();
475
476 if (computeWishartStatistics) {
477 wishartStatistics = new WishartSufficientStatistics(dimTrait);
478 }
479
480 // Use dynamic programming to compute conditional likelihoods at each internal node
481 postOrderTraverse(treeModel, treeModel.getRoot(), traitPrecision, logDetTraitPrecision, computeWishartStatistics);
482
483 doPreOrderTraversal(treeModel.getRoot());}
484 PostPreKnown=true;
485
486 }
487
488
489 protected void checkLogLikelihood(double loglikelihood, double logRemainders,
490 double[] conditionalRootMean, double conditionalRootPrecision,
491 double[][] traitPrecision) {
492
493 // System.err.println("root cmean : " + new Vector(conditionalRootMean));
494 // System.err.println("root cprec : " + conditionalRootPrecision);
495 // System.err.println("diffusion prec: " + new Matrix(traitPrecision));
496 //
497 // System.err.println("prior mean : " + new Vector(rootPriorMean));
498 // System.err.println("prior prec : " + rootPriorSampleSize);
499
500 double upperPrecision = conditionalRootPrecision * rootPriorSampleSize / (conditionalRootPrecision + rootPriorSampleSize);
501 // System.err.println("root cprec : " + upperPrecision);
502
503 double[][] newPrec = new double[traitPrecision.length][traitPrecision.length];
504
505 for (int i = 0; i < traitPrecision.length; ++i) {
506 for (int j = 0; j < traitPrecision.length; ++j) {
507 newPrec[i][j] = traitPrecision[i][j] * upperPrecision;
508 }
509 }
510 MultivariateNormalDistribution mvn = new MultivariateNormalDistribution(rootPriorMean, newPrec);
511 double logPdf = mvn.logPdf(conditionalRootMean);
512
513 if (Math.abs(loglikelihood - logRemainders - logPdf) > 1E-3) {
514
515 System.err.println("Got here subclass: " + loglikelihood);
516 System.err.println("logValue : " + (logRemainders + logPdf));
517 System.err.println("logRemainder = " + logRemainders);
518 System.err.println("");
519 }
520 // System.err.println("logRemainders : " + logRemainders);
521 // System.err.println("logPDF : " + logPdf);
522 // System.exit(-1);
523 }
524
525 protected double integrateLogLikelihoodAtRoot(double[] conditionalRootMean,
526 double[] marginalRootMean,
527 double[][] notUsed,
528 double[][] treePrecisionMatrix, double conditionalRootPrecision) {
529 final double square;
530 final double marginalPrecision = conditionalRootPrecision + rootPriorSampleSize;
531 final double marginalVariance = 1.0 / marginalPrecision;
532
533 // square : (Ay + Bz)' (A+B)^{-1} (Ay + Bz)
534
535 // A = conditionalRootPrecision * treePrecisionMatrix
536 // B = rootPriorSampleSize * treePrecisionMatrix
537
538 if (dimTrait > 1) {
539
540 computeWeightedAverage(conditionalRootMean, 0, conditionalRootPrecision, rootPriorMean, 0, rootPriorSampleSize,
541 marginalRootMean, 0, dimTrait);
542
543 square = computeQuadraticProduct(marginalRootMean, treePrecisionMatrix, marginalRootMean, dimTrait)
544 * marginalPrecision;
545
546 if (computeWishartStatistics) {
547
548 final double[] outerProducts = wishartStatistics.getScaleMatrix();
549
550 final double weight = conditionalRootPrecision * rootPriorSampleSize * marginalVariance;
551 for (int i = 0; i < dimTrait; i++) {
552 final double diffi = conditionalRootMean[i] - rootPriorMean[i];
553 for (int j = 0; j < dimTrait; j++) {
554 outerProducts[i * dimTrait + j] += diffi * weight * (conditionalRootMean[j] - rootPriorMean[j]);
555 }
556 }
557 wishartStatistics.incrementDf(1);
558 }
559 } else {
560 // 1D is very simple
561 final double x = conditionalRootMean[0] * conditionalRootPrecision + rootPriorMean[0] * rootPriorSampleSize;
562 square = x * x * treePrecisionMatrix[0][0] * marginalVariance;
563
564 if (computeWishartStatistics) {
565 final double[] outerProducts = wishartStatistics.getScaleMatrix();
566 final double y = conditionalRootMean[0] - rootPriorMean[0];
567 outerProducts[0] += y * y * conditionalRootPrecision * rootPriorSampleSize * marginalVariance;
568 wishartStatistics.incrementDf(1);
569 }
570 }
571
572 if (!priorInformationKnown) {
573 setRootPriorSumOfSquares(treePrecisionMatrix);
574 }
575
576 final double retValue = 0.5 * (dimTrait * Math.log(rootPriorSampleSize * marginalVariance) - zBz + square);
577
578 if (DEBUG) {
579 System.err.println("(Ay+Bz)(A+B)^{-1}(Ay+Bz) = " + square);
580 System.err.println("density = " + retValue);
581 System.err.println("zBz = " + zBz);
582 }
583
584 return retValue;
585 }
586
587 private void setRootPriorSumOfSquares(double[][] treePrecisionMatrix) {
588
589 zBz = computeQuadraticProduct(rootPriorMean, treePrecisionMatrix, rootPriorMean, dimTrait) * rootPriorSampleSize;
590 priorInformationKnown = true;
591 }
592
593 protected double[][] computeMarginalRootMeanAndVariance(double[] conditionalRootMean,
594 double[][] notUsed,
595 double[][] treeVarianceMatrix,
596 double conditionalRootPrecision) {
597
598 final double[][] outVariance = tmpM; // Use a temporary buffer, will stay valid for only a short while
599
600 computeWeightedAverage(conditionalRootMean, 0, conditionalRootPrecision, rootPriorMean, 0, rootPriorSampleSize,
601 conditionalRootMean, 0, dimTrait);
602
603 final double totalVariance = 1.0 / (conditionalRootPrecision + rootPriorSampleSize);
604 for (int i = 0; i < dimTrait; i++) {
605 for (int j = 0; j < dimTrait; j++) {
606 outVariance[i][j] = treeVarianceMatrix[i][j] * totalVariance;
607 }
608 }
609
610 return outVariance;
611 }
612
613 protected double[] rootPriorMean;
614 protected double rootPriorSampleSize;
615
616 double[] preP;
617 double[][] preMeans;
618
619 double[] storedPreP;
620 double[][] storedPreMeans;
621
622 Boolean PostPreKnown=false;
623 Boolean storedPostPreKnown=false;
624
625 private boolean priorInformationKnown = false;
626 private double zBz; // Prior sum-of-squares contribution
627
628 private boolean dimKnown=false;
629 private boolean storedDimKnown=false;
630 private int storedDim;
631 private int storedNumData;
632
633 protected boolean computeWishartStatistics = false;
634 private double[] ascertainedData = null;
635 private static final boolean DEBUG_ASCERTAINMENT = false;
636
637 private double vectorMin(double[] vec) {
638 double min = Double.MAX_VALUE;
639 for (int i = 0; i < vec.length; ++i) {
640 min = Math.min(min, vec[i]);
641 }
642 return min;
643 }
644
645 private double matrixMin(double[][] mat) {
646 double min = Double.MAX_VALUE;
647 for (int i = 0; i < mat.length; ++i) {
648 min = Math.min(min, vectorMin(mat[i]));
649 }
650 return min;
651 }
652
653 private double vectorMax(double[] vec) {
654 double max = - Double.MAX_VALUE;
655 for (int i = 0; i < vec.length; ++i) {
656 max = Math.max(max, vec[i]);
657 }
658 return max;
659 }
660
661 private double matrixMax(double[][] mat) {
662 double max = -Double.MAX_VALUE;
663 for (int i = 0; i < mat.length; ++i) {
664 max = Math.max(max, vectorMax(mat[i]));
665 }
666 return max;
667 }
668
669 private double vectorSum(double[] vec) {
670 double sum = 0.0;
671 for (int i = 0; i < vec.length; ++i) {
672 sum += vec[i];
673 }
674 return sum;
675 }
676
677 private double matrixSum(double[][] mat) {
678 double sum = 0.0;
679 for (int i = 0; i < mat.length; ++i) {
680 sum += vectorSum(mat[i]);
681 }
682 return sum;
683 }
684
685 @Override
686 public String getReport() {
687 StringBuilder sb = new StringBuilder();
688 // sb.append(this.g)
689 // System.err.println("Hello");
690 sb.append("Tree:\n");
691 sb.append(getId()).append("\t");
692 sb.append(treeModel.toString());
693 sb.append("\n\n");
694
695 double[][] treeVariance = computeTreeVariance(true);
696 double[][] traitPrecision = getDiffusionModel().getPrecisionmatrix();
697 Matrix traitVariance = new Matrix(traitPrecision).inverse();
698
699 double[][] jointVariance = KroneckerOperation.product(treeVariance, traitVariance.toComponents());
700
701 sb.append("Tree variance:\n");
702 sb.append(new Matrix(treeVariance));
703 sb.append(matrixMin(treeVariance)).append("\t").append(matrixMax(treeVariance)).append("\t").append(matrixSum(treeVariance));
704 sb.append("\n\n");
705 sb.append("Trait variance:\n");
706 sb.append(traitVariance);
707 sb.append("\n\n");
708 // sb.append("Joint variance:\n");
709 // sb.append(new Matrix(jointVariance));
710 // sb.append("\n\n");
711
712 sb.append("Tree dim: " + treeVariance.length + "\n");
713 sb.append("data dim: " + jointVariance.length);
714 sb.append("\n\n");
715
716 double[] data = new double[jointVariance.length];
717 System.arraycopy(meanCache, 0, data, 0, jointVariance.length);
718
719 if (nodeToClampMap != null) {
720 int offset = treeModel.getExternalNodeCount() * getDimTrait();
721 for(Map.Entry<NodeRef, RestrictedPartials> clamps : nodeToClampMap.entrySet()) {
722 double[] partials = clamps.getValue().getPartials();
723 for (int i = 0; i < partials.length; ++i) {
724 data[offset] = partials[i];
725 ++offset;
726 }
727 }
728 }
729
730 sb.append("Data:\n");
731 sb.append(new Vector(data)).append("\n");
732 sb.append(data.length).append("\t").append(vectorMin(data)).append("\t").append(vectorMax(data)).append("\t").append(vectorSum(data));
733 sb.append(treeModel.getNodeTaxon(treeModel.getExternalNode(0)).getId());
734 sb.append("\n\n");
735
736 MultivariateNormalDistribution mvn = new MultivariateNormalDistribution(new double[data.length], new Matrix(jointVariance).inverse().toComponents());
737 double logDensity = mvn.logPdf(data);
738 sb.append("logLikelihood: " + getLogLikelihood() + " == " + logDensity + "\n\n");
739
740 final WishartSufficientStatistics sufficientStatistics = getWishartStatistics();
741 final double[] outerProducts = sufficientStatistics.getScaleMatrix();
742
743 sb.append("Outer-products (DP):\n");
744 sb.append(new Vector(outerProducts));
745 sb.append(sufficientStatistics.getDf() + "\n");
746
747 Matrix treePrecision = new Matrix(treeVariance).inverse();
748 final int n = data.length / traitPrecision.length;
749 final int p = traitPrecision.length;
750 double[][] tmp = new double[n][p];
751
752 for (int i = 0; i < n; ++i) {
753 for (int j = 0; j < p; ++j) {
754 tmp[i][j] = data[i * p + j];
755 }
756 }
757 Matrix y = new Matrix(tmp);
758
759 Matrix S = null;
760 try {
761 S = y.transpose().product(treePrecision).product(y); // Using Matrix-Normal form
762 } catch (IllegalDimension illegalDimension) {
763 illegalDimension.printStackTrace();
764 }
765 sb.append("Outer-products (from tree variance:\n");
766 sb.append(S);
767 sb.append("\n\n");
768
769 return sb.toString();
770 }
771
772
773 class NodeToRootDistance {
774 NodeRef node;
775 double distance;
776
777 NodeToRootDistance(NodeRef node, double distance) {
778 this.node = node;
779 this.distance = distance;
780 }
781 }
782
783 class NodeToRootDistanceList extends ArrayList<NodeToRootDistance> {
784
785 NodeToRootDistanceList(NodeToRootDistanceList parentList) {
786 super(parentList);
787 }
788
789 NodeToRootDistanceList() {
790 super();
791 }
792 }
793
794 private void addNodeToList(final NodeRef thisNode, NodeToRootDistanceList parentList, NodeToRootDistanceList[] tipLists) {
795
796 if (!treeModel.isRoot(thisNode)) {
797 double increment = getRescaledBranchLengthForPrecision(thisNode);
798 if (parentList.size() > 0) {
799 increment += parentList.get(parentList.size() - 1).distance;
800 }
801 parentList.add(new NodeToRootDistance(thisNode, increment));
802 }
803
804 if (treeModel.isExternal(thisNode)) {
805 tipLists[thisNode.getNumber()] = parentList;
806 } else { // recurse
807 NodeToRootDistanceList shallowCopy = new NodeToRootDistanceList(parentList);
808 addNodeToList(treeModel.getChild(thisNode, 0), shallowCopy, tipLists);
809 addNodeToList(treeModel.getChild(thisNode, 1), parentList, tipLists);
810 }
811 }
812
813 private double getTimeBetweenNodeToRootLists(List<NodeToRootDistance> x, List<NodeToRootDistance> y) {
814 if (x.get(0) != y.get(0)) {
815 return 0.0;
816 }
817
818 int index = 1;
819 while (x.get(index) == y.get(index)) {
820 ++index;
821 }
822 return x.get(index - 1).distance;
823 }
824
825 public double[][] computeTreeVariance2(boolean includeRoot) {
826
827 final int tipCount = treeModel.getExternalNodeCount();
828 double[][] variance = new double[tipCount][tipCount];
829
830 NodeToRootDistanceList[] tipToRootDistances = new NodeToRootDistanceList[tipCount];
831
832 // Recurse down tree to generate lists
833 addNodeToList(treeModel.getRoot(), new NodeToRootDistanceList(), tipToRootDistances);
834
835 for (int i = 0; i < tipCount; ++i) {
836 // Fill in diagonal
837 List<NodeToRootDistance> iList = tipToRootDistances[i];
838 double marginalTime = iList.get(iList.size() - 1).distance;
839 variance[i][i] = marginalTime;
840
841 for (int j = i + 1; j < tipCount; ++j) {
842 List<NodeToRootDistance> jList = tipToRootDistances[j];
843
844 double time = getTimeBetweenNodeToRootLists(iList, jList);
845 variance[j][i] = variance[i][j] = time;
846 }
847 }
848
849 variance = removeMissingTipsInTreeVariance(variance); // Automatically prune missing tips
850
851 if (DEBUG) {
852 System.err.println("");
853 System.err.println("New tree (trimmed) conditional variance:\n" + new Matrix(variance));
854 }
855
856 if (includeRoot) {
857 for (int i = 0; i < variance.length; ++i) {
858 for (int j = 0; j < variance[i].length; ++j) {
859 variance[i][j] += 1.0 / getPriorSampleSize();
860 }
861 }
862 }
863
864 return variance;
865
866 }
867
868 public double[][] computeTreeVariance(boolean includeRoot) {
869 final int tipCount = treeModel.getExternalNodeCount();
870 int length = tipCount;
871
872 boolean DO_CLAMP = true;
873 if (DO_CLAMP && nodeToClampMap != null) {
874 length += nodeToClampMap.size();
875 }
876 // System.exit(-1);
877
878 double[][] variance = new double[length][length];
879
880 for (int i = 0; i < tipCount; i++) {
881
882 // Fill in diagonal
883 double marginalTime = getRescaledLengthToRoot(treeModel.getExternalNode(i));
884 variance[i][i] = marginalTime;
885
886 // Fill in upper right triangle,
887
888 for (int j = i + 1; j < tipCount; j++) {
889 NodeRef mrca = findMRCA(i, j);
890 variance[i][j] = getRescaledLengthToRoot(mrca);
891 }
892 }
893
894 if (DO_CLAMP && nodeToClampMap != null) {
895 List<RestrictedPartials> partialsList = new ArrayList<RestrictedPartials>();
896 for (Map.Entry<NodeRef, RestrictedPartials> keySet : nodeToClampMap.entrySet()) {
897 partialsList.add(keySet.getValue());
898 }
899
900 for (int i = 0; i < partialsList.size(); ++i) {
901 RestrictedPartials partials = partialsList.get(i);
902 NodeRef node = partials.getNode();
903
904 variance[tipCount + i][tipCount + i] = getRescaledLengthToRoot(node) +
905 1.0 / partials.getPriorSampleSize();
906
907 for (int j = 0; j < tipCount; ++j) {
908 NodeRef friend = treeModel.getExternalNode(j);
909 NodeRef mrca = TreeUtils.getCommonAncestor(treeModel, node, friend);
910 variance[j][tipCount + i] = getRescaledLengthToRoot(mrca);
911
912 }
913
914 for (int j = 0; j < i; ++j) {
915 NodeRef friend = partialsList.get(j).getNode();
916 NodeRef mrca = TreeUtils.getCommonAncestor(treeModel, node, friend);
917 variance[tipCount + j][tipCount + i] = getRescaledLengthToRoot(mrca);
918 }
919 }
920 }
921
922 // Make symmetric
923 for (int i = 0; i < length; i++) {
924 for (int j = i + 1; j < length; j++) {
925 variance[j][i] = variance[i][j];
926 }
927 }
928
929 // if (DEBUG) {
930 // System.err.println("");
931 // System.err.println("New tree conditional variance:\n" + new Matrix(variance));
932 // }
933 //
934 // variance = removeMissingTipsInTreeVariance(variance); // Automatically prune missing tips
935 //
936 // if (DEBUG) {
937 // System.err.println("");
938 // System.err.println("New tree (trimmed) conditional variance:\n" + new Matrix(variance));
939 // }
940
941 if (includeRoot) {
942 for (int i = 0; i < variance.length; ++i) {
943 for (int j = 0; j < variance[i].length; ++j) {
944 variance[i][j] += 1.0 / getPriorSampleSize();
945 }
946 }
947 }
948
949 return variance;
950 }
951
952 private NodeRef findMRCA(int iTip, int jTip) {
953 Set<String> leafNames = new HashSet<String>();
954 leafNames.add(treeModel.getTaxonId(iTip));
955 leafNames.add(treeModel.getTaxonId(jTip));
956 return TreeUtils.getCommonAncestorNode(treeModel, leafNames);
957 }
958
959 private double[][] removeMissingTipsInTreeVariance(double[][] variance) {
960
961 final int tipCount = treeModel.getExternalNodeCount();
962 final int nonMissing = countNonMissingTips();
963
964 if (nonMissing == tipCount) { // Do nothing
965 return variance;
966 }
967
968 double[][] outVariance = new double[nonMissing][nonMissing];
969
970 int iReal = 0;
971 for (int i = 0; i < tipCount; i++) {
972 if (!missingTraits.isCompletelyMissing(i)) {
973
974 int jReal = 0;
975 for (int j = 0; j < tipCount; j++) {
976 if (!missingTraits.isCompletelyMissing(i)) {
977
978 outVariance[iReal][jReal] = variance[i][j];
979
980 jReal++;
981 }
982 }
983 iReal++;
984 }
985 }
986 return outVariance;
987 }
988
989 private int countNonMissingTips() {
990 int tipCount = treeModel.getExternalNodeCount();
991 for (int i = 0; i < tipCount; i++) {
992 if (missingTraits.isCompletelyMissing(i)) {
993 tipCount--;
994 }
995 }
996 return tipCount;
997 }
998
999
1000 }