Debian Codegraph @

src/dr/evomodel/treedatalikelihood/continuous/cdi/SafeMultivariateWithDriftIntegrator.java

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 package dr.evomodel.treedatalikelihood.continuous.cdi;
2
3 import dr.math.matrixAlgebra.WrappedVector;
4 import dr.math.matrixAlgebra.missingData.InversionResult;
•5 import org.ejml.data.DMatrixRMaj;
6 import org.ejml.dense.row.CommonOps_DDRM;
7
8 import static dr.math.matrixAlgebra.missingData.InversionResult.Code.NOT_OBSERVED;
9 import static dr.math.matrixAlgebra.missingData.MissingOps.*;
10
11 /**
12 * @author Marc A. Suchard
13 */
14
15 public class SafeMultivariateWithDriftIntegrator extends SafeMultivariateIntegrator {
16
17 private static boolean DEBUG = false;
18
19 public SafeMultivariateWithDriftIntegrator(PrecisionType precisionType, int numTraits, int dimTrait, int bufferCount,
20 int diffusionCount) {
21 super(precisionType, numTraits, dimTrait, bufferCount, diffusionCount);
22
23 allocateStorage();
24
25 System.err.println("Trying SafeMultivariateWithDriftIntegrator");
26 }
27
28 @Override
29 public double getBranchMatrices(int bufferIndex, double[] precision, double[] displacement) {
30
31 assert (precision != null);
32 assert (precision.length >= dimTrait * dimTrait);
33
34 assert (displacement != null);
35 assert (displacement.length >- dimTrait);
36
37 System.arraycopy(precisions, bufferIndex * dimTrait * dimTrait,
38 precision, 0, dimTrait * dimTrait);
39
40 System.arraycopy(displacements, bufferIndex * dimTrait,
41 displacement, 0, dimTrait);
42
43 return super.getBranchMatrices(bufferIndex, precision, displacement);
44 }
45
46 private static final boolean TIMING = false;
47
48 private double[] vector1;
49 private double[] vector2;
50
51 private void allocateStorage() {
52
53 displacements = new double[dimTrait * bufferCount];
54 precisions = new double[dimTrait * dimTrait * bufferCount];
55 variances = new double[dimTrait * dimTrait * bufferCount];
56 vector1 = new double[dimTrait];
57 vector2 = new double[dimTrait];
58 }
59
60 @Override
61 public void setDiffusionPrecision(int precisionIndex, final double[] matrix, double logDeterminant) {
62 super.setDiffusionPrecision(precisionIndex, matrix, logDeterminant);
63
64 assert (diffusions != null);
65 assert (inverseDiffusions != null);
66
67 final int offset = dimTrait * dimTrait * precisionIndex;
•68 DMatrixRMaj precision = wrap(diffusions, offset, dimTrait, dimTrait);
69 DMatrixRMaj variance = new DMatrixRMaj(dimTrait, dimTrait);
70 CommonOps_DDRM.invert(precision, variance);
71 unwrap(variance, inverseDiffusions, offset);
72
73 if (DEBUG) {
74 System.err.println("At precision index: " + precisionIndex);
75 System.err.println("precision: " + precision);
76 System.err.println("variance : " + variance);
77 }
78 }
79
80 public void updateBrownianDiffusionMatrices(int precisionIndex, final int[] probabilityIndices,
81 final double[] edgeLengths, final double[] driftRates,
82 int updateCount) {
83
84 assert (diffusions != null);
85 assert (probabilityIndices.length >= updateCount);
86 assert (edgeLengths.length >= updateCount);
87
88 if (DEBUG) {
89 System.err.println("Matrices (safe with drift):");
90 }
91
92 final int matrixSize = dimTrait * dimTrait;
93 final int unscaledOffset = matrixSize * precisionIndex;
94
95 if (TIMING) {
96 startTime("diffusion");
97 }
98
99 for (int up = 0; up < updateCount; ++up) {
100
101 if (DEBUG) {
102 System.err.println("\t" + probabilityIndices[up] + " <- " + edgeLengths[up]);
103 }
104
105 final double edgeLength = edgeLengths[up];
106 branchLengths[dimMatrix * probabilityIndices[up]] = edgeLength; // TODO Remove dimMatrix
107
108 final int scaledOffset = matrixSize * probabilityIndices[up];
109
110 scale(diffusions, unscaledOffset, 1.0 / edgeLength, precisions, scaledOffset, matrixSize);
111 scale(inverseDiffusions, unscaledOffset, edgeLength, variances, scaledOffset, matrixSize); // TODO Only if necessary
112 }
113
114 if (TIMING) {
115 endTime("diffusion");
116 }
117
118
119 if (driftRates != null) {
120
121 assert (displacements != null);
122 assert (driftRates.length >= updateCount * dimTrait);
123
124 if (TIMING) {
125 startTime("drift1");
126 }
127
128 int offset = 0;
129 for (int up = 0; up < updateCount; ++up) {
130
131 final double edgeLength = edgeLengths[up];
132 final int pio = dimTrait * probabilityIndices[up];
133
134 scale(driftRates, offset, edgeLength, displacements, pio, dimTrait);
135 offset += dimTrait;
136 }
137
138 if (TIMING) {
139 endTime("drift1");
140 }
141 }
142
143 precisionOffset = dimTrait * dimTrait * precisionIndex;
144 precisionLogDet = determinants[precisionIndex];
145 }
146
147 private static void scale(final double[] source,
148 final int sourceOffset,
149 final double scale,
150 final double[] destination,
151 final int destinationOffset,
152 final int length) {
153 for (int i = 0; i < length; ++i) {
154 destination[destinationOffset + i] = scale * source[sourceOffset + i];
155 }
156 }
157
158 @Override
159 public void updatePreOrderPartial(
160 final int kBuffer, // parent
161 final int iBuffer, // node
162 final int iMatrix,
163 final int jBuffer, // sibling
164 final int jMatrix) {
165
166 throw new RuntimeException("Not yet implemented");
167 }
168
169 @Override
170 protected void updatePartial(
171 final int kBuffer,
172 final int iBuffer,
173 final int iMatrix,
174 final int jBuffer,
175 final int jMatrix,
176 final boolean incrementOuterProducts
177 ) {
178
179 if (incrementOuterProducts) {
180 throw new RuntimeException("Outer-products are not supported.");
181 }
182
183 if (TIMING) {
184 startTime("total");
185 }
186
187 // Determine buffer offsets
188 int kbo = dimPartial * kBuffer;
189 int ibo = dimPartial * iBuffer;
190 int jbo = dimPartial * jBuffer;
191
192 // Determine matrix offsets
193 final int imo = dimTrait * dimTrait * iMatrix;
194 final int jmo = dimTrait * dimTrait * jMatrix;
195
196 // Read variance increments along descendent branches of k
197
198 // TODO Fix
199 // final double vi = variances[imo];
200 // final double vj = variances[jmo];
201
•202 final DMatrixRMaj Vd = wrap(inverseDiffusions, precisionOffset, dimTrait, dimTrait);
203 // final DMatrixRMaj Pd = wrap(diffusions, precisionOffset, dimTrait, dimTrait);
204
•205 final DMatrixRMaj Vdi = wrap(variances, imo, dimTrait, dimTrait);
206 final DMatrixRMaj Vdj = wrap(variances, jmo, dimTrait, dimTrait);
207
•208 final DMatrixRMaj Pdi = wrap(precisions, imo, dimTrait, dimTrait); // TODO Only if needed
209 final DMatrixRMaj Pdj = wrap(precisions, jmo, dimTrait, dimTrait); // TODO Only if needed
210
211 // TODO End fix
212
213 if (DEBUG) {
214 System.err.println("variance diffusion: " + Vd);
215 // System.err.println("\tvi: " + vi + " vj: " + vj);
216 System.err.println("precisionOffset = " + precisionOffset);
217 System.err.println("\tVdi: " + Vdi);
218 System.err.println("\tVdj: " + Vdj);
219 }
220
221 // For each trait // TODO in parallel
222 for (int trait = 0; trait < numTraits; ++trait) {
223
224 // Layout, offset, dim
225 // trait, 0, dT
226 // precision, dT, dT * dT
227 // variance, dT + dT * dT, dT * dT
228 // scalar, dT + 2 * dT * dT, 1
229
230 if (TIMING) {
231 startTime("peel1");
232 }
233
234 // Increase variance along the branches i -> k and j -> k
235
236 // A. Get current precision of i and j
237 // final double lpi = partials[ibo + dimTrait + 2 * dimTrait * dimTrait];
238 // final double lpj = partials[jbo + dimTrait + 2 * dimTrait * dimTrait];
239
•240 final DMatrixRMaj Pi = wrap(partials, ibo + dimTrait, dimTrait, dimTrait);
241 final DMatrixRMaj Pj = wrap(partials, jbo + dimTrait, dimTrait, dimTrait);
242
243 if (TIMING) {
244 endTime("peel1");
245 startTime("peel2");
246 }
247
248 // B. Integrate along branch using two matrix inversions
249 // final double lpip = Double.isInfinite(lpi) ?
250 // 1.0 / vi : lpi / (1.0 + lpi * vi);
251 // final double lpjp = Double.isInfinite(lpj) ?
252 // 1.0 / vj : lpj / (1.0 + lpj * vj);
253
254 InversionResult ci;
255 InversionResult cj;
256
•257 final DMatrixRMaj Pip = matrix2;
258 final DMatrixRMaj Pjp = matrix3;
259
260 // boolean useVariance = anyDiagonalInfinities(Pi) || anyDiagonalInfinities(Pj);
261 final boolean useVariancei = anyDiagonalInfinities(Pi);
262 final boolean useVariancej = anyDiagonalInfinities(Pj);
263
264 if (useVariancei) {
265
•266 final DMatrixRMaj Vip = matrix0;
267 final DMatrixRMaj Vi = wrap(partials, ibo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
268 // CommonOps_DDRM.add(Vi, vi, Vd, Vip); // TODO Fix
269 CommonOps_DDRM.add(Vi, Vdi, Vip);
270 ci = safeInvert(Vip, Pip, true);
271
272 } else {
273
•274 final DMatrixRMaj PiPlusPd = matrix0;
275 // CommonOps_DDRM.add(Pi, 1.0 / vi, Pd, PiPlusPd); // TODO Fix
276 CommonOps_DDRM.add(Pi, Pdi, PiPlusPd);
277 final DMatrixRMaj PiPlusPdInv = new DMatrixRMaj(dimTrait, dimTrait);
278 safeInvert(PiPlusPd, PiPlusPdInv, false);
•279 CommonOps_DDRM.mult(PiPlusPdInv, Pi, Pip);
280 CommonOps_DDRM.mult(Pi, Pip, PiPlusPdInv);
281 CommonOps_DDRM.add(Pi, -1, PiPlusPdInv, Pip);
282 ci = safeDeterminant(Pip, false);
283 }
284
285 if (useVariancej) {
286
•287 final DMatrixRMaj Vjp = matrix1;
288 final DMatrixRMaj Vj = wrap(partials, jbo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
289 // CommonOps_DDRM.add(Vj, vj, Vd, Vjp); // TODO Fix
290 CommonOps_DDRM.add(Vj, Vdj, Vjp);
291 cj = safeInvert(Vjp, Pjp, true);
292
293 } else {
294
•295 final DMatrixRMaj PjPlusPd = matrix1;
296 // CommonOps_DDRM.add(Pj, 1.0 / vj, Pd, PjPlusPd); // TODO Fix
297 CommonOps_DDRM.add(Pj, Pdj, PjPlusPd);
298 final DMatrixRMaj PjPlusPdInv = new DMatrixRMaj(dimTrait, dimTrait);
299 safeInvert(PjPlusPd, PjPlusPdInv, false);
•300 CommonOps_DDRM.mult(PjPlusPdInv, Pj, Pjp);
301 CommonOps_DDRM.mult(Pj, Pjp, PjPlusPdInv);
302 CommonOps_DDRM.add(Pj, -1, PjPlusPdInv, Pjp);
303 cj = safeDeterminant(Pjp, false);
304 }
305
306 if (TIMING) {
307 endTime("peel2");
308 startTime("peel3");
309 }
310
311 // Compute partial mean and precision at node k
312
313 // A. Partial precision and variance (for later use) using one matrix inversion
314 // final double lpk = lpip + lpjp;
315
•316 // final DMatrixRMaj Pk = new DMatrixRMaj(dimTrait, dimTrait);
317 final DMatrixRMaj Pk = matrix4;
318 CommonOps_DDRM.add(Pip, Pjp, Pk);
319
•320 // final DMatrixRMaj Vk = new DMatrixRMaj(dimTrait, dimTrait);
321 // final DMatrixRMaj Vk = matrix5;
322
323 // if (useVariance) {
324 //// InversionResult ck =
325 // safeInvert(Pk, Vk, true);
326 // }
327 // InversionResult ck = safeDeterminant(Pk, true);
328
329 // System.err.println(ck);
330 // System.err.println(ck2);
331 // System.exit(-1);
332
333 // B. Partial mean
334
335 if (TIMING) {
336 endTime("peel3");
337 startTime("peel4");
338 }
339
340 final double[] displacementi = vector1;
341 final double[] displacementj = vector2;
342
343 final int ido = dimTrait * iMatrix;
344 final int jdo = dimTrait * jMatrix;
345
346 for (int g = 0; g < dimTrait; ++g) {
347 displacementi[g] = partials[ibo + g] - displacements[ido + g];
348 displacementj[g] = partials[jbo + g] - displacements[jdo + g];
349 }
350
351 // final double[] tmp = new double[dimTrait];
352 final double[] tmp = vector0;
353 for (int g = 0; g < dimTrait; ++g) {
354 double sum = 0.0;
355 for (int h = 0; h < dimTrait; ++h) {
356 sum += Pip.unsafe_get(g, h) * displacementi[h];
357 sum += Pjp.unsafe_get(g, h) * displacementj[h];
358 }
359 tmp[g] = sum;
360 }
361
362 // for (int g = 0; g < dimTrait; ++g) {
363 // double sum = 0.0;
364 // for (int h = 0; h < dimTrait; ++h) {
365 // sum += Vk.unsafe_get(g, h) * tmp[h];
366 // }
367 // partials[kbo + g] = sum;
368 // }
369
370 final WrappedVector kPartials = new WrappedVector.Raw(partials, kbo, dimTrait);
371 final WrappedVector wrapTmp = new WrappedVector.Raw(tmp, 0, dimTrait);
372
373 // System.err.println(kPartials);
374 // System.err.println(ck.getDeterminant());
375
376 InversionResult ck = safeSolve(Pk, wrapTmp, kPartials, true);
377
378 // System.err.println(kPartials);
379 // System.err.println(ck.getDeterminant());
380 // System.exit(-1);
381
382 if (TIMING) {
383 endTime("peel4");
384 startTime("peel5");
385 }
386
387 // C. Store precision
388 // partials[kbo + dimTrait + 2 * dimTrait * dimTrait] = lpk;
389
390 unwrap(Pk, partials, kbo + dimTrait);
391
392 // if (useVariance) {
393 // unwrap(Vk, partials, kbo + dimTrait + dimTrait * dimTrait);
394 // }
395
396 if (TIMING) {
397 endTime("peel5");
398 }
399
400 if (DEBUG) {
401 System.err.println("\ttrait: " + trait);
402 System.err.println("Pi: " + Pi);
403 System.err.println("Pj: " + Pj);
404 System.err.println("Pk: " + Pk);
405 System.err.print("\t\tmean i:");
406 for (int e = 0; e < dimTrait; ++e) {
407 System.err.print(" " + partials[ibo + e]);
408 }
409 System.err.print("\t\tdisp i:");
410 for (int e = 0; e < dimTrait; ++e) {
411 System.err.print(" " + displacements[ido + e]);
412 }
413 System.err.println("");
414 System.err.print("\t\tmean j:");
415 for (int e = 0; e < dimTrait; ++e) {
416 System.err.print(" " + partials[jbo + e]);
417 }
418 System.err.print("\t\tdisp j:");
419 for (int e = 0; e < dimTrait; ++e) {
420 System.err.print(" " + displacements[jdo + e]);
421 }
422 System.err.println("");
423 System.err.print("\t\tmean k:");
424 for (int e = 0; e < dimTrait; ++e) {
425 System.err.print(" " + partials[kbo + e]);
426 }
427 System.err.println("");
428 }
429
430 // Computer remainder at node k
431 double remainder = 0.0;
432
433 if (DEBUG) {
434 System.err.println("i status: " + ci);
435 System.err.println("j status: " + cj);
436 System.err.println("k status: " + ck);
437 System.err.println("Pip: " + Pip);
438 // System.err.println("Vip: " + Vip);
439 System.err.println("Pjp: " + Pjp);
440 // System.err.println("Vjp: " + Vjp);
441 }
442
443 if (!(ci.getReturnCode() == NOT_OBSERVED || cj.getReturnCode() == NOT_OBSERVED)) {
444 // if (ci == InversionReturnCode.FULLY_OBSERVED && cj == InversionReturnCode.FULLY_OBSERVED) {
445 // TODO Fix for partially observed
446 // if (pi != 0 && pj != 0) {
447 //
448 if (TIMING) {
449 startTime("remain");
450 }
451
452 // Inner products
453 double SSk = 0;
454 double SSj = 0;
455 double SSi = 0;
456
457 // vector-matrix-vector TODO in parallel
458 for (int g = 0; g < dimTrait; ++g) {
459 // final double ig = partials[ibo + g];
460 // final double jg = partials[jbo + g];
461 final double ig = displacementi[g];
462 final double jg = displacementj[g];
463 final double kg = partials[kbo + g];
464
465 for (int h = 0; h < dimTrait; ++h) {
466 // final double ih = partials[ibo + h];
467 // final double jh = partials[jbo + h];
468 final double ih = displacementi[h];
469 final double jh = displacementj[h];
470 final double kh = partials[kbo + h];
471
472 SSi += ig * Pip.unsafe_get(g, h) * ih;
473 SSj += jg * Pjp.unsafe_get(g, h) * jh;
474 SSk += kg * Pk .unsafe_get(g, h) * kh;
475 }
476 }
477
•478 // final DMatrixRMaj Vt = new DMatrixRMaj(dimTrait, dimTrait);
479 // final DMatrixRMaj Vt = matrix6;
480 // CommonOps_DDRM.add(Vip, Vjp, Vt);
481
482 // if (DEBUG) {
483 // System.err.println("Vt: " + Vt);
484 // }
485
486 int dimensionChange = ci.getEffectiveDimension() + cj.getEffectiveDimension()
487 - ck.getEffectiveDimension();
488
489 // System.err.println(ci.getDeterminant());
•490 // System.err.println(CommonOps_DDRM.det(Vip));
491 //
492 // System.err.println(cj.getDeterminant());
•493 // System.err.println(CommonOps_DDRM.det(Vjp));
494 //
495 // System.err.println(1.0 / ck.getDeterminant());
•496 // System.err.println(CommonOps_DDRM.det(Vk));
497
498 remainder += -dimensionChange * LOG_SQRT_2_PI - 0.5 *
•499 // (Math.log(CommonOps_DDRM.det(Vip)) + Math.log(CommonOps_DDRM.det(Vjp)) - Math.log(CommonOps_DDRM.det(Vk)))
500 (Math.log(ci.getDeterminant()) + Math.log(cj.getDeterminant()) + Math.log(ck.getDeterminant()))
501 - 0.5 * (SSi + SSj - SSk);
502
503 // TODO Can get SSi + SSj - SSk from inner product w.r.t Pt (see outer-products below)?
504
505 if (DEBUG) {
506 System.err.println("\t\t\tSSi = " + (SSi));
507 System.err.println("\t\t\tSSj = " + (SSj));
508 System.err.println("\t\t\tSSk = " + (SSk));
509 System.err.println("\t\t\tdeti = " + Math.log(ci.getDeterminant()));
510 System.err.println("\t\t\tdetj = " + Math.log(ci.getDeterminant()));
511 System.err.println("\t\t\tdetk = " + Math.log(ci.getDeterminant()));
512 System.err.println("\t\tremainder: " + remainder);
513 // System.exit(-1);
514 }
515
516 if (TIMING) {
517 endTime("remain");
518 }
519
520 } // End if remainder
521
522 // Accumulate remainder up tree and store
523
524 remainders[kBuffer * numTraits + trait] = remainder
525 + remainders[iBuffer * numTraits + trait] + remainders[jBuffer * numTraits + trait];
526
527 // Get ready for next trait
528 kbo += dimPartialForTrait;
529 ibo += dimPartialForTrait;
530 jbo += dimPartialForTrait;
531
532 }
533
534 if (TIMING) {
535 endTime("total");
536 }
537 }
538
539 private double[] displacements;
540 }