| 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.treedatalikelihood.continuous; |
| 27 |
|
| 28 |
|
| 29 |
|
| 30 |
|
| 31 |
|
| 32 |
|
| 33 |
|
| 34 |
|
| 35 |
|
| 36 |
|
| 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() ? |
| 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 |
|
| 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 |
|
| 213 |
|
| 214 |
|
| 215 |
|
| 216 |
|
| 217 |
|
| 218 |
|
| 219 |
|
| 220 |
|
| 221 |
|
| 222 |
|
| 223 |
|
| 224 |
|
| 225 |
|
| 226 |
|
| 227 |
|
| 228 |
|
| 229 |
|
| 230 |
|
| 231 |
|
| 232 |
|
| 233 |
|
| 234 |
|
| 235 |
|
| 236 |
|
| 237 |
|
| 238 |
|
| 239 |
|
| 240 |
|
| 241 |
|
| 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 |
|
| 422 |
int[] cNotMissingJoint = new int[dimTrait * tipCount]; |
| 423 |
int[] cMissingJoint = new int[dimTrait * (tipCount - 1)]; |
| 424 |
|
| 425 |
|
| 426 |
for (int tipTrait = 0; tipTrait < dimTrait * tipCount; ++tipTrait) { |
| 427 |
cNotMissingJoint[tipTrait] = tipTrait; |
| 428 |
} |
| 429 |
|
| 430 |
|
| 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 |
|
| 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()); |
| 527 |
operations[k + 2] = getActiveMatrixIndex(op.getLeftChild()); |
| 528 |
operations[k + 3] = getActiveNodeIndex(op.getRightChild()); |
| 529 |
operations[k + 4] = getActiveMatrixIndex(op.getRightChild()); |
| 530 |
|
| 531 |
k += ContinuousDiffusionIntegrator.OPERATION_TUPLE_SIZE; |
| 532 |
} |
| 533 |
|
| 534 |
return nodeOperations.size(); |
| 535 |
} |
| 536 |
|
| 537 |
|
| 538 |
|
| 539 |
|
| 540 |
|
| 541 |
|
| 542 |
|
| 543 |
|
| 544 |
|
| 545 |
|
| 546 |
|
| 547 |
|
| 548 |
|
| 549 |
|
| 550 |
|
| 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 |
|
| 594 |
|
| 595 |
|
| 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) { |
| 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 |
|
| 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 |
|
| 693 |
|
| 694 |
|
| 695 |
|
| 696 |
|
| 697 |
|
| 698 |
|
| 699 |
|
| 700 |
@Override |
| 701 |
public void makeDirty() { |
| 702 |
updateDiffusionModel = true; |
| 703 |
fireModelChanged(); |
| 704 |
} |
| 705 |
|
| 706 |
@Override |
| 707 |
protected void handleModelChangedEvent(Model model, Object object, int index) { |
| 708 |
if (model == diffusionProcessDelegate) { |
| 709 |
updateDiffusionModel = true; |
| 710 |
|
| 711 |
fireModelChanged(); |
| 712 |
} else if (model == dataModel) { |
| 713 |
if (object == dataModel) { |
| 714 |
if (index == -1) { |
| 715 |
updateTipData.addFirst(index); |
| 716 |
fireModelChanged(); |
| 717 |
} else { |
| 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 |
|
| 733 |
} |
| 734 |
|
| 735 |
|
| 736 |
|
| 737 |
|
| 738 |
@Override |
| 739 |
public void storeState() { |
| 740 |
partialBufferHelper.storeState(); |
| 741 |
|
| 742 |
|
| 743 |
flip = true; |
| 744 |
|
| 745 |
storedBranchNormalization = branchNormalization; |
| 746 |
} |
| 747 |
|
| 748 |
|
| 749 |
|
| 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 |
|
| 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 |
|
| 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 |
} |