Debian Codegraph @

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

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
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.DenseMatrix64F;
6 import org.ejml.ops.CommonOps;
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 SafeMultivariateIntegrator extends MultivariateIntegrator {
16
17 private static boolean DEBUG = false;
18
19 public SafeMultivariateIntegrator(PrecisionType precisionType, int numTraits, int dimTrait, int bufferCount,
20 int diffusionCount) {
21 super(precisionType, numTraits, dimTrait, bufferCount, diffusionCount);
22
23 // assert precisionType == PrecisionType.FULL;
24 //
25 // allocateStorage();
26 //
27 // if (TIMING) {
28 // times = new HashMap<String, Long>();
29 // } else {
30 // times = null;
31 // }
32
33 System.err.println("Trying SafeMultivariateIntegrator");
34 }
35
36 // @Override
37 // public String getReport() {
38 //
39 // StringBuilder sb = new StringBuilder();
40 //
41 // if (TIMING) {
42 // sb.append("\nTIMING:");
43 // for (String key : times.keySet()) {
44 // String value = String.format("%4.3e", (double) times.get(key));
45 // sb.append("\n" + key + "\t\t" + value);
46 // }
47 // sb.append("\n");
48 // }
49 // return sb.toString();
50 // }
51
52 private static final boolean TIMING = false;
53
54 // private final Map<String, Long> times;
55 //
56 // private DenseMatrix64F matrix0;
57 // private DenseMatrix64F matrix1;
58 // private DenseMatrix64F matrix2;
59 // private DenseMatrix64F matrix3;
60 // private DenseMatrix64F matrix4;
61 // private DenseMatrix64F matrix5;
62 // private DenseMatrix64F matrix6;
63 //
64 // private double[] vector0;
65
66 // private void allocateStorage() {
67 // inverseDiffusions = new double[dimTrait * dimTrait * diffusionCount];
68 //
69 // vector0 = new double[dimTrait];
70 // matrix0 = new DenseMatrix64F(dimTrait, dimTrait);
71 // matrix1 = new DenseMatrix64F(dimTrait, dimTrait);
72 // matrix2 = new DenseMatrix64F(dimTrait, dimTrait);
73 // matrix3 = new DenseMatrix64F(dimTrait, dimTrait);
74 // matrix4 = new DenseMatrix64F(dimTrait, dimTrait);
75 // matrix5 = new DenseMatrix64F(dimTrait, dimTrait);
76 // matrix6 = new DenseMatrix64F(dimTrait, dimTrait);
77 // }
78
79 // @Override
80 // public void setDiffusionPrecision(int precisionIndex, final double[] matrix, double logDeterminant) {
81 // super.setDiffusionPrecision(precisionIndex, matrix, logDeterminant);
82 //
83 // assert (inverseDiffusions != null);
84 //
85 // final int offset = dimTrait * dimTrait * precisionIndex;
86 // DenseMatrix64F precision = wrap(diffusions, offset, dimTrait, dimTrait);
87 // DenseMatrix64F variance = new DenseMatrix64F(dimTrait, dimTrait);
88 // CommonOps.invert(precision, variance);
89 // unwrap(variance, inverseDiffusions, offset);
90 //
91 // if (DEBUG) {
92 // System.err.println("At precision index: " + precisionIndex);
93 // System.err.println("precision: " + precision);
94 // System.err.println("variance : " + variance);
95 // }
96 // }
97
98 // @Override
99 // public boolean requireDataAugmentationForOuterProducts() {
100 // return true;
101 // }
102
103 // @Override
104 // public void updatePreOrderPartial(
105 // final int kBuffer, // parent
106 // final int iBuffer, // node
107 // final int iMatrix,
108 // final int jBuffer, // sibling
109 // final int jMatrix) {
110 //
111 // // Determine buffer offsets
112 // int kbo = dimPartial * kBuffer;
113 // int ibo = dimPartial * iBuffer;
114 // int jbo = dimPartial * jBuffer;
115 //
116 // // Determine matrix offsets
117 // final int imo = dimMatrix * iMatrix;
118 // final int jmo = dimMatrix * jMatrix;
119 //
120 // // Read variance increments along descendent branches of k
121 // final double vi = branchLengths[imo];
122 // final double vj = branchLengths[jmo];
123 //
124 // final DenseMatrix64F Vd = wrap(inverseDiffusions, precisionOffset, dimTrait, dimTrait);
125 //
126 // if (DEBUG) {
127 // System.err.println("updatePreOrderPartial for node " + iBuffer);
128 //// System.err.println("variance diffusion: " + Vd);
129 // System.err.println("\tvi: " + vi + " vj: " + vj);
130 //// System.err.println("precisionOffset = " + precisionOffset);
131 // }
132 //
133 // // For each trait // TODO in parallel
134 // for (int trait = 0; trait < numTraits; ++trait) {
135 //
136 // // A. Get current precision of k and j
137 // final DenseMatrix64F Pk = wrap(prePartials, kbo + dimTrait, dimTrait, dimTrait);
138 //// final DenseMatrix64F Pj = wrap(partials, jbo + dimTrait, dimTrait, dimTrait);
139 //
140 //// final DenseMatrix64F Vk = wrap(prePartials, kbo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
141 // final DenseMatrix64F Vj = wrap(partials, jbo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
142 //
143 // // B. Inflate variance along sibling branch using matrix inversion
144 //// final DenseMatrix64F Vjp = new DenseMatrix64F(dimTrait, dimTrait);
145 // final DenseMatrix64F Vjp = matrix0;
146 // CommonOps.add(Vj, vj, Vd, Vjp);
147 //
148 //// final DenseMatrix64F Pjp = new DenseMatrix64F(dimTrait, dimTrait);
149 // final DenseMatrix64F Pjp = matrix1;
150 // InversionResult cj = safeInvert(Vjp, Pjp, false);
151 //
152 //// final DenseMatrix64F Pip = new DenseMatrix64F(dimTrait, dimTrait);
153 // final DenseMatrix64F Pip = matrix2;
154 // CommonOps.add(Pk, Pjp, Pip);
155 //
156 //// final DenseMatrix64F Vip = new DenseMatrix64F(dimTrait, dimTrait);
157 // final DenseMatrix64F Vip = matrix3;
158 // InversionResult cip = safeInvert(Pip, Vip, false);
159 //
160 // // C. Compute prePartial mean
161 //// final double[] tmp = new double[dimTrait];
162 // final double[] tmp = vector0;
163 // for (int g = 0; g < dimTrait; ++g) {
164 // double sum = 0.0;
165 // for (int h = 0; h < dimTrait; ++h) {
166 // sum += Pk.unsafe_get(g, h) * prePartials[kbo + h]; // Read parent
167 // sum += Pjp.unsafe_get(g, h) * partials[jbo + h]; // Read sibling
168 // }
169 // tmp[g] = sum;
170 // }
171 // for (int g = 0; g < dimTrait; ++g) {
172 // double sum = 0.0;
173 // for (int h = 0; h < dimTrait; ++h) {
174 // sum += Vip.unsafe_get(g, h) * tmp[h];
175 // }
176 // prePartials[ibo + g] = sum; // Write node
177 // }
178 //
179 // // C. Inflate variance along node branch
180 // final DenseMatrix64F Vi = Vip;
181 // CommonOps.add(vi, Vd, Vip, Vi);
182 //
183 //// final DenseMatrix64F Pi = new DenseMatrix64F(dimTrait, dimTrait);
184 // final DenseMatrix64F Pi = matrix4;
185 // InversionResult ci = safeInvert(Vi, Pi, false);
186 //
187 // // X. Store precision results for node
188 // unwrap(Pi, prePartials, ibo + dimTrait);
189 // unwrap(Vi, prePartials, ibo + dimTrait + dimTrait * dimTrait);
190 //
191 // if (DEBUG) {
192 // System.err.println("trait: " + trait);
193 // System.err.println("pM: " + new WrappedVector.Raw(prePartials, kbo, dimTrait));
194 // System.err.println("pP: " + Pk);
195 // System.err.println("sM: " + new WrappedVector.Raw(partials, jbo, dimTrait));
196 // System.err.println("sV: " + Vj);
197 // System.err.println("sVp: " + Vjp);
198 // System.err.println("sPp: " + Pjp);
199 // System.err.println("Pip: " + Pip);
200 // System.err.println("cM: " + new WrappedVector.Raw(prePartials, ibo, dimTrait));
201 // System.err.println("cV: " + Vi);
202 // }
203 //
204 // // Get ready for next trait
205 // kbo += dimPartialForTrait;
206 // ibo += dimPartialForTrait;
207 // jbo += dimPartialForTrait;
208 // }
209 // }
210
211 @Override
212 protected void updatePartial(
213 final int kBuffer,
214 final int iBuffer,
215 final int iMatrix,
216 final int jBuffer,
217 final int jMatrix,
218 final boolean incrementOuterProducts
219 ) {
220
221 if (incrementOuterProducts) {
222 throw new RuntimeException("Outer-products are not supported.");
223 }
224
225 if (TIMING) {
226 startTime("total");
227 }
228
229 // Determine buffer offsets
230 int kbo = dimPartial * kBuffer;
231 int ibo = dimPartial * iBuffer;
232 int jbo = dimPartial * jBuffer;
233
234 // Determine matrix offsets
235 final int imo = dimMatrix * iMatrix;
236 final int jmo = dimMatrix * jMatrix;
237
238 // Read variance increments along descendent branches of k
239 final double vi = branchLengths[imo];
240 final double vj = branchLengths[jmo];
241
242 final DenseMatrix64F Vd = wrap(inverseDiffusions, precisionOffset, dimTrait, dimTrait);
243 final DenseMatrix64F Pd = wrap(diffusions, precisionOffset, dimTrait, dimTrait);
244
245 if (DEBUG) {
246 System.err.println("variance diffusion: " + Vd);
247 System.err.println("\tvi: " + vi + " vj: " + vj);
248 System.err.println("precisionOffset = " + precisionOffset);
249 }
250
251 // For each trait // TODO in parallel
252 for (int trait = 0; trait < numTraits; ++trait) {
253
254 // Layout, offset, dim
255 // trait, 0, dT
256 // precision, dT, dT * dT
257 // variance, dT + dT * dT, dT * dT
258 // scalar, dT + 2 * dT * dT, 1
259
260 if (TIMING) {
261 startTime("peel1");
262 }
263
264 // Increase variance along the branches i -> k and j -> k
265
266 // A. Get current precision of i and j
267 final double lpi = partials[ibo + dimTrait + 2 * dimTrait * dimTrait];
268 final double lpj = partials[jbo + dimTrait + 2 * dimTrait * dimTrait];
269
270 final DenseMatrix64F Pi = wrap(partials, ibo + dimTrait, dimTrait, dimTrait);
271 final DenseMatrix64F Pj = wrap(partials, jbo + dimTrait, dimTrait, dimTrait);
272
273 if (TIMING) {
274 endTime("peel1");
275 startTime("peel2");
276 }
277
278 // B. Integrate along branch using two matrix inversions
279 final double lpip = Double.isInfinite(lpi) ?
280 1.0 / vi : lpi / (1.0 + lpi * vi);
281 final double lpjp = Double.isInfinite(lpj) ?
282 1.0 / vj : lpj / (1.0 + lpj * vj);
283
284 InversionResult ci;
285 InversionResult cj;
286
287 final DenseMatrix64F Pip = matrix2;
288 final DenseMatrix64F Pjp = matrix3;
289
290 // boolean useVariance = anyDiagonalInfinities(Pi) || anyDiagonalInfinities(Pj);
291 final boolean useVariancei = anyDiagonalInfinities(Pi);
292 final boolean useVariancej = anyDiagonalInfinities(Pj);
293
294 if (useVariancei) {
295
296 final DenseMatrix64F Vip = matrix0;
297 final DenseMatrix64F Vi = wrap(partials, ibo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
298 CommonOps.add(Vi, vi, Vd, Vip);
299 ci = safeInvert(Vip, Pip, true);
300
301 } else {
302
303 final DenseMatrix64F PiPlusPd = matrix0;
304 CommonOps.add(Pi, 1.0 / vi, Pd, PiPlusPd);
305 final DenseMatrix64F PiPlusPdInv = new DenseMatrix64F(dimTrait, dimTrait);
306 safeInvert(PiPlusPd, PiPlusPdInv, false);
307 CommonOps.mult(PiPlusPdInv, Pi, Pip);
308 CommonOps.mult(Pi, Pip, PiPlusPdInv);
309 CommonOps.add(Pi, -1, PiPlusPdInv, Pip);
310 ci = safeDeterminant(Pip, false);
311 }
312
313 if (useVariancej) {
314
315 final DenseMatrix64F Vjp = matrix1;
316 final DenseMatrix64F Vj = wrap(partials, jbo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
317 CommonOps.add(Vj, vj, Vd, Vjp);
318 cj = safeInvert(Vjp, Pjp, true);
319
320 } else {
321
322 final DenseMatrix64F PjPlusPd = matrix1;
323 CommonOps.add(Pj, 1.0 / vj, Pd, PjPlusPd);
324 final DenseMatrix64F PjPlusPdInv = new DenseMatrix64F(dimTrait, dimTrait);
325 safeInvert(PjPlusPd, PjPlusPdInv, false);
326 CommonOps.mult(PjPlusPdInv, Pj, Pjp);
327 CommonOps.mult(Pj, Pjp, PjPlusPdInv);
328 CommonOps.add(Pj, -1, PjPlusPdInv, Pjp);
329 cj = safeDeterminant(Pjp, false);
330 }
331
332 // if (useVariance) {
333 //
334 // final DenseMatrix64F Vip = matrix0;
335 // final DenseMatrix64F Vjp = matrix1;
336 //
337 // final DenseMatrix64F Vi = wrap(partials, ibo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
338 // final DenseMatrix64F Vj = wrap(partials, jbo + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
339 //
340 // CommonOps.add(Vi, vi, Vd, Vip);
341 // CommonOps.add(Vj, vj, Vd, Vjp);
342 //
343 // ci = safeInvert(Vip, Pip, true);
344 // cj = safeInvert(Vjp, Pjp, true);
345 // } else {
346 //
347 // final DenseMatrix64F PiPlusPd = matrix0;
348 // final DenseMatrix64F PjPlusPd = matrix1;
349 //
350 // CommonOps.add(Pi, 1.0 / vi, Pd, PiPlusPd);
351 // CommonOps.add(Pj, 1.0 / vj, Pd, PjPlusPd);
352 //
353 // final DenseMatrix64F PiPlusPdInv = new DenseMatrix64F(dimTrait, dimTrait);
354 // final DenseMatrix64F PjPlusPdInv = new DenseMatrix64F(dimTrait, dimTrait);
355 //
356 // safeInvert(PiPlusPd, PiPlusPdInv, false);
357 // safeInvert(PjPlusPd, PjPlusPdInv, false);
358 //
359 // CommonOps.mult(PiPlusPdInv, Pi, Pip);
360 // CommonOps.mult(PjPlusPdInv, Pj, Pjp);
361 //
362 // CommonOps.mult(Pi, Pip, PiPlusPdInv);
363 // CommonOps.mult(Pj, Pjp, PjPlusPdInv);
364 //
365 // CommonOps.add(Pi, -1, PiPlusPdInv, Pip);
366 // CommonOps.add(Pj, -1, PjPlusPdInv, Pjp);
367 //
368 // ci = safeDeterminant(Pip, false);
369 // cj = safeDeterminant(Pjp, false);
370 // }
371
372 if (TIMING) {
373 endTime("peel2");
374 startTime("peel2a");
375 }
376
377
378 if (TIMING) {
379 endTime("peel2a");
380 startTime("peel3");
381 }
382
383 // Compute partial mean and precision at node k
384
385 // A. Partial precision and variance (for later use) using one matrix inversion
386 final double lpk = lpip + lpjp;
387
388 // final DenseMatrix64F Pk = new DenseMatrix64F(dimTrait, dimTrait);
389 final DenseMatrix64F Pk = matrix4;
390 CommonOps.add(Pip, Pjp, Pk);
391
392 // final DenseMatrix64F Vk = new DenseMatrix64F(dimTrait, dimTrait);
393 // final DenseMatrix64F Vk = matrix5;
394
395 // if (useVariance) {
396 //// InversionResult ck =
397 // safeInvert(Pk, Vk, true);
398 // }
399 // InversionResult ck = safeDeterminant(Pk, true);
400
401 // System.err.println(ck);
402 // System.err.println(ck2);
403 // System.exit(-1);
404
405 // B. Partial mean
406
407 if (TIMING) {
408 endTime("peel3");
409 startTime("peel4");
410 }
411
412 // final double[] tmp = new double[dimTrait];
413 final double[] tmp = vector0;
414 for (int g = 0; g < dimTrait; ++g) {
415 double sum = 0.0;
416 for (int h = 0; h < dimTrait; ++h) {
417 sum += Pip.unsafe_get(g, h) * partials[ibo + h];
418 sum += Pjp.unsafe_get(g, h) * partials[jbo + h];
419 }
420 tmp[g] = sum;
421 }
422
423 // for (int g = 0; g < dimTrait; ++g) {
424 // double sum = 0.0;
425 // for (int h = 0; h < dimTrait; ++h) {
426 // sum += Vk.unsafe_get(g, h) * tmp[h];
427 // }
428 // partials[kbo + g] = sum;
429 // }
430
431 final WrappedVector kPartials = new WrappedVector.Raw(partials, kbo, dimTrait);
432 final WrappedVector wrapTmp = new WrappedVector.Raw(tmp, 0, dimTrait);
433
434 // System.err.println(kPartials);
435 // System.err.println(ck.getDeterminant());
436
437 InversionResult ck = safeSolve(Pk, wrapTmp, kPartials, true);
438
439 // System.err.println(kPartials);
440 // System.err.println(ck.getDeterminant());
441 // System.exit(-1);
442
443 // TODO Use safeSolve just above
444
445 if (TIMING) {
446 endTime("peel4");
447 startTime("peel5");
448 }
449
450 // C. Store precision
451 partials[kbo + dimTrait + 2 * dimTrait * dimTrait] = lpk;
452
453 unwrap(Pk, partials, kbo + dimTrait);
454
455 // if (useVariance) {
456 // unwrap(Vk, partials, kbo + dimTrait + dimTrait * dimTrait);
457 // }
458
459 if (TIMING) {
460 endTime("peel5");
461 }
462
463 if (DEBUG) {
464 System.err.println("\ttrait: " + trait);
465 System.err.println("Pi: " + Pi);
466 System.err.println("Pj: " + Pj);
467 System.err.println("Pk: " + Pk);
468 System.err.print("\t\tmean i:");
469 for (int e = 0; e < dimTrait; ++e) {
470 System.err.print(" " + partials[ibo + e]);
471 }
472 System.err.print("\t\tmean j:");
473 for (int e = 0; e < dimTrait; ++e) {
474 System.err.print(" " + partials[jbo + e]);
475 }
476 System.err.print("\t\tmean k:");
477 for (int e = 0; e < dimTrait; ++e) {
478 System.err.print(" " + partials[kbo + e]);
479 }
480 System.err.println("");
481 }
482
483 // Computer remainder at node k
484 double remainder = 0.0;
485
486 if (DEBUG) {
487 System.err.println("i status: " + ci);
488 System.err.println("j status: " + cj);
489 System.err.println("k status: " + ck);
490 System.err.println("Pip: " + Pip);
491 // System.err.println("Vip: " + Vip);
492 System.err.println("Pjp: " + Pjp);
493 // System.err.println("Vjp: " + Vjp);
494 }
495
496 if (!(ci.getReturnCode() == NOT_OBSERVED || cj.getReturnCode() == NOT_OBSERVED)) {
497 // if (ci == InversionReturnCode.FULLY_OBSERVED && cj == InversionReturnCode.FULLY_OBSERVED) {
498 // TODO Fix for partially observed
499 // if (pi != 0 && pj != 0) {
500 //
501 if (TIMING) {
502 startTime("remain");
503 }
504
505 // Inner products
506 double SSk = 0;
507 double SSj = 0;
508 double SSi = 0;
509
510 // vector-matrix-vector TODO in parallel
511 for (int g = 0; g < dimTrait; ++g) {
512 final double ig = partials[ibo + g];
513 final double jg = partials[jbo + g];
514 final double kg = partials[kbo + g];
515
516 for (int h = 0; h < dimTrait; ++h) {
517 final double ih = partials[ibo + h];
518 final double jh = partials[jbo + h];
519 final double kh = partials[kbo + h];
520
521 SSi += ig * Pip.unsafe_get(g, h) * ih;
522 SSj += jg * Pjp.unsafe_get(g, h) * jh;
523 SSk += kg * Pk .unsafe_get(g, h) * kh;
524 }
525 }
526
527 // final DenseMatrix64F Vt = new DenseMatrix64F(dimTrait, dimTrait);
528 // final DenseMatrix64F Vt = matrix6;
529 // CommonOps.add(Vip, Vjp, Vt);
530
531 // if (DEBUG) {
532 // System.err.println("Vt: " + Vt);
533 // }
534
535 int dimensionChange = ci.getEffectiveDimension() + cj.getEffectiveDimension()
536 - ck.getEffectiveDimension();
537
538 // System.err.println(ci.getDeterminant());
539 // System.err.println(CommonOps.det(Vip));
540 //
541 // System.err.println(cj.getDeterminant());
542 // System.err.println(CommonOps.det(Vjp));
543 //
544 // System.err.println(1.0 / ck.getDeterminant());
545 // System.err.println(CommonOps.det(Vk));
546
547 remainder += -dimensionChange * LOG_SQRT_2_PI - 0.5 *
548 // (Math.log(CommonOps.det(Vip)) + Math.log(CommonOps.det(Vjp)) - Math.log(CommonOps.det(Vk)))
549 (Math.log(ci.getDeterminant()) + Math.log(cj.getDeterminant()) + Math.log(ck.getDeterminant()))
550 - 0.5 * (SSi + SSj - SSk);
551
552 // TODO Can get SSi + SSj - SSk from inner product w.r.t Pt (see outer-products below)?
553
554 if (DEBUG) {
555 System.err.println("\t\t\tSSi = " + (SSi));
556 System.err.println("\t\t\tSSj = " + (SSj));
557 System.err.println("\t\t\tSSk = " + (SSk));
558 System.err.println("\t\t\tdeti = " + Math.log(ci.getDeterminant()));
559 System.err.println("\t\t\tdetj = " + Math.log(ci.getDeterminant()));
560 System.err.println("\t\t\tdetk = " + Math.log(ci.getDeterminant()));
561 System.err.println("\t\tremainder: " + remainder);
562 // System.exit(-1);
563 }
564
565 if (TIMING) {
566 endTime("remain");
567 }
568
569 } // End if remainder
570
571 // Accumulate remainder up tree and store
572
573 remainders[kBuffer * numTraits + trait] = remainder
574 + remainders[iBuffer * numTraits + trait] + remainders[jBuffer * numTraits + trait];
575
576 // Get ready for next trait
577 kbo += dimPartialForTrait;
578 ibo += dimPartialForTrait;
579 jbo += dimPartialForTrait;
580
581 }
582
583 if (TIMING) {
584 endTime("total");
585 }
586 }
587
588 // private final Map<String, Long> startTimes = new HashMap<String, Long>();
589 //
590 // private void startTime(String key) {
591 // startTimes.put(key, System.nanoTime());
592 // }
593 //
594 // private void endTime(String key) {
595 // long start = startTimes.get(key);
596 //
597 // Long total = times.get(key);
598 // if (total == null) {
599 // total = new Long(0);
600 // }
601 //
602 // long run = total + (System.nanoTime() - start);
603 // times.put(key, run);
604 //
605 //// System.err.println("run = " + run);
606 //// System.exit(-1);
607 // }
608
609 // private void incrementTiming(long start, long end, String key) {
610 // Long total = times.get(key);
611 //
612 // System.err.println(start + " " + end + " " + key);
613 // System.exit(-1);
614 // if (total == null) {
615 // total = new Long(0);
616 // times.put(key, total);
617 // }
618 // total += (end - start);
619 //// times.put(key, total);
620 // }
621
622 @Override
623 public void calculateRootLogLikelihood(int rootBufferIndex, int priorBufferIndex, final double[] logLikelihoods,
624 boolean incrementOuterProducts) {
625 assert(logLikelihoods.length == numTraits);
626
627 if (DEBUG) {
628 System.err.println("Root calculation for " + rootBufferIndex);
629 System.err.println("Prior buffer index is " + priorBufferIndex);
630 }
631
632 int rootOffset = dimPartial * rootBufferIndex;
633 int priorOffset = dimPartial * priorBufferIndex;
634
635 final DenseMatrix64F Pd = wrap(diffusions, precisionOffset, dimTrait, dimTrait);
636 // final DenseMatrix64F Vd = wrap(inverseDiffusions, precisionOffset, dimTrait, dimTrait);
637
638 // TODO For each trait in parallel
639 for (int trait = 0; trait < numTraits; ++trait) {
640
641 final DenseMatrix64F Proot = wrap(partials, rootOffset + dimTrait, dimTrait, dimTrait);
642 final DenseMatrix64F Pprior = wrap(partials, priorOffset + dimTrait, dimTrait, dimTrait);
643
644 // final DenseMatrix64F Vroot = wrap(partials, rootOffset + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
645 // final DenseMatrix64F Vprior = wrap(partials, priorOffset + dimTrait + dimTrait * dimTrait, dimTrait, dimTrait);
646
647 // TODO Block below is for the conjugate prior ONLY
648 {
649 // final DenseMatrix64F Vtmp = new DenseMatrix64F(dimTrait, dimTrait);
650 // CommonOps.mult(Vd, Vprior, Vtmp);
651 // Vprior.set(Vtmp);
652
653 final DenseMatrix64F Ptmp = new DenseMatrix64F(dimTrait, dimTrait);
654 CommonOps.mult(Pd, Pprior, Ptmp);
655 Pprior.set(Ptmp); // TODO What does this do?
656 }
657
658 final DenseMatrix64F Vtotal = new DenseMatrix64F(dimTrait, dimTrait);
659 // CommonOps.add(Vroot, Vprior, Vtotal);
660
661 final DenseMatrix64F Ptotal = new DenseMatrix64F(dimTrait, dimTrait);
662 CommonOps.invert(Vtotal, Ptotal); // TODO Can return determinant at same time to avoid extra QR decomp
663
664 final DenseMatrix64F tmp1 = new DenseMatrix64F(dimTrait, dimTrait);
665 final DenseMatrix64F tmp2 = new DenseMatrix64F(dimTrait, dimTrait);
666 CommonOps.add(Proot, Pprior, Ptotal);
667 CommonOps.invert(Ptotal, Vtotal);
668 CommonOps.mult(Vtotal, Proot, tmp1);
669 CommonOps.mult(Proot, tmp1, tmp2);
670 CommonOps.add(Proot, -1.0, tmp2, Ptotal);
671
672 double SS = 0;
673 for (int g = 0; g < dimTrait; ++g) {
674 final double gDifference = partials[rootOffset + g] - partials[priorOffset + g];
675
676 for (int h = 0; h < dimTrait; ++h) {
677 final double hDifference = partials[rootOffset + h] - partials[priorOffset + h];
678
679 SS += gDifference * Ptotal.unsafe_get(g, h) * hDifference;
680 }
681 }
682
683 final double logLike = -dimTrait * LOG_SQRT_2_PI
684 // - 0.5 * Math.log(CommonOps.det(Vtotal))
685 + 0.5 * Math.log(CommonOps.det(Ptotal))
686 - 0.5 * SS;
687
688 final double remainder = remainders[rootBufferIndex * numTraits + trait];
689 logLikelihoods[trait] = logLike + remainder;
690
691 if (incrementOuterProducts) {
692
693 assert false : "Should not get here";
694
695 // int opo = dimTrait * dimTrait * trait;
696 // int opd = precisionOffset;
697 //
698 // double rootScalar = partials[rootOffset + dimTrait + 2 * dimTrait * dimTrait];
699 // final double priorScalar = partials[priorOffset + dimTrait];
700 //
701 // if (!Double.isInfinite(priorScalar)) {
702 // rootScalar = rootScalar * priorScalar / (rootScalar + priorScalar);
703 // }
704 //
705 // for (int g = 0; g < dimTrait; ++g) {
706 // final double gDifference = partials[rootOffset + g] - partials[priorOffset + g];
707 //
708 // for (int h = 0; h < dimTrait; ++h) {
709 // final double hDifference = partials[rootOffset + h] - partials[priorOffset + h];
710 //
711 // outerProducts[opo] += gDifference * hDifference
712 //// * Ptotal.unsafe_get(g, h) / diffusions[opd];
713 // * rootScalar;
714 // ++opo;
715 // ++opd;
716 // }
717 // }
718 //
719 // degreesOfFreedom[trait] += 1; // incremenent degrees-of-freedom
720 }
721
722 if (DEBUG) {
723 System.err.print("mean:");
724 for (int g = 0; g < dimTrait; ++g) {
725 System.err.print(" " + partials[rootOffset + g]);
726 }
727 System.err.println("");
728 System.err.println("Proot: " + Proot);
729 // System.err.println("Vroot: " + Vroot);
730 System.err.println("Pprior: " + Pprior);
731 // System.err.println("Vprior: " + Vprior);
732 System.err.println("Ptotal: " + Ptotal);
733 // System.err.println("Vtotal: " + Vtotal);
734 // System.err.println("prec: " + partials[rootOffset + dimTrait]);
735 System.err.println("\t" + logLike + " " + (logLike + remainder));
736
737 if (incrementOuterProducts) {
738 System.err.println("Outer-products:" + wrap(outerProducts, dimTrait * dimTrait * trait, dimTrait, dimTrait));
739 }
740 }
741
742 rootOffset += dimPartialForTrait;
743 priorOffset += dimPartialForTrait;
744 }
745
746 if (DEBUG) {
747 System.err.println("End");
748 }
749 }
750 }