| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
|
| 16 |
|
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 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 |
|
| 46 |
|
| 47 |
|
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
public class FullyConjugateMultivariateTraitLikelihood extends IntegratedMultivariateTraitLikelihood |
| 52 |
implements ConjugateWishartStatisticsProvider, GibbsSampleFromTreeInterface, Reportable { |
| 53 |
|
| 54 |
|
| 55 |
|
| 56 |
|
| 57 |
|
| 58 |
|
| 59 |
|
| 60 |
|
| 61 |
|
| 62 |
|
| 63 |
|
| 64 |
|
| 65 |
|
| 66 |
|
| 67 |
|
| 68 |
|
| 69 |
|
| 70 |
|
| 71 |
|
| 72 |
|
| 73 |
|
| 74 |
|
| 75 |
|
| 76 |
|
| 77 |
|
| 78 |
|
| 79 |
|
| 80 |
|
| 81 |
|
| 82 |
|
| 83 |
|
| 84 |
|
| 85 |
|
| 86 |
|
| 87 |
|
| 88 |
|
| 89 |
|
| 90 |
|
| 91 |
|
| 92 |
|
| 93 |
|
| 94 |
|
| 95 |
|
| 96 |
|
| 97 |
|
| 98 |
|
| 99 |
|
| 100 |
|
| 101 |
|
| 102 |
|
| 103 |
|
| 104 |
|
| 105 |
|
| 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 |
|
| 132 |
this.rootPriorMean = rootPriorMean; |
| 133 |
this.rootPriorSampleSize = rootPriorSampleSize; |
| 134 |
|
| 135 |
priorInformationKnown = false; |
| 136 |
} |
| 137 |
|
| 138 |
|
| 139 |
|
| 140 |
public FullyConjugateMultivariateTraitLikelihood semiClone(CompoundParameter traitParameter){ |
| 141 |
return this; |
| 142 |
} |
| 143 |
|
| 144 |
|
| 145 |
|
| 146 |
|
| 147 |
|
| 148 |
|
| 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) { |
| 170 |
ascertainedData = new double[dimTrait]; |
| 171 |
} |
| 172 |
|
| 173 |
|
| 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 |
|
| 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 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 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 |
|
| 244 |
|
| 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 |
|
| 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 |
|
| 359 |
|
| 360 |
|
| 361 |
|
| 362 |
|
| 363 |
|
| 364 |
|
| 365 |
|
| 366 |
|
| 367 |
|
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
|
| 374 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 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 |
|
| 458 |
|
| 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 |
|
| 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 |
|
| 494 |
|
| 495 |
|
| 496 |
|
| 497 |
|
| 498 |
|
| 499 |
|
| 500 |
double upperPrecision = conditionalRootPrecision * rootPriorSampleSize / (conditionalRootPrecision + rootPriorSampleSize); |
| 501 |
|
| 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 |
|
| 521 |
|
| 522 |
|
| 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 |
|
| 534 |
|
| 535 |
|
| 536 |
|
| 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 |
|
| 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; |
| 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; |
| 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 |
|
| 689 |
|
| 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 |
|
| 709 |
|
| 710 |
|
| 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); |
| 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 { |
| 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 |
|
| 833 |
addNodeToList(treeModel.getRoot(), new NodeToRootDistanceList(), tipToRootDistances); |
| 834 |
|
| 835 |
for (int i = 0; i < tipCount; ++i) { |
| 836 |
|
| 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); |
| 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 |
|
| 877 |
|
| 878 |
double[][] variance = new double[length][length]; |
| 879 |
|
| 880 |
for (int i = 0; i < tipCount; i++) { |
| 881 |
|
| 882 |
|
| 883 |
double marginalTime = getRescaledLengthToRoot(treeModel.getExternalNode(i)); |
| 884 |
variance[i][i] = marginalTime; |
| 885 |
|
| 886 |
|
| 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 |
|
| 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 |
|
| 930 |
|
| 931 |
|
| 932 |
|
| 933 |
|
| 934 |
|
| 935 |
|
| 936 |
|
| 937 |
|
| 938 |
|
| 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) { |
| 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 |
} |