Debian Codegraph @

src/dr/evomodel/treedatalikelihood/preorder/MultivariateConditionalOnTipsRealizedDelegate.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.preorder;
2
3 import dr.evolution.tree.Tree;
4 import dr.evomodel.continuous.MultivariateDiffusionModel;
5 import dr.evomodel.treedatalikelihood.continuous.*;
6 import dr.math.distributions.MultivariateNormalDistribution;
7 import dr.math.matrixAlgebra.Matrix;
8 import dr.math.matrixAlgebra.WrappedVector;
9 import org.ejml.data.DenseMatrix64F;
10 import org.ejml.ops.CommonOps;
11
12 import static dr.math.matrixAlgebra.missingData.MissingOps.*;
13
14 /**
15 * @author Marc A. Suchard
16 */
17 public class MultivariateConditionalOnTipsRealizedDelegate extends ConditionalOnTipsRealizedDelegate {
18
19 private static final boolean DEBUG = false;
20
21 final private PartiallyMissingInformation missingInformation;
22
23 public MultivariateConditionalOnTipsRealizedDelegate(String name, Tree tree,
24 MultivariateDiffusionModel diffusionModel,
25 ContinuousTraitPartialsProvider dataModel,
26 ConjugateRootTraitPrior rootPrior,
27 ContinuousRateTransformation rateTransformation,
28 ContinuousDataLikelihoodDelegate likelihoodDelegate) {
29 super(name, tree, diffusionModel, dataModel, rootPrior, rateTransformation, likelihoodDelegate);
30 missingInformation = new PartiallyMissingInformation(tree, dataModel, likelihoodDelegate);
31 }
32
33 @Override
34 protected void simulateTraitForRoot(final int offsetSample, final int offsetPartial) {
35
36 // TODO Bad programming -- should not need to know about internal layout
37 // Layout, offset, dim
38 // trait, 0, dT
39 // precision, dT, dT * dT
40 // variance, dT + dT * dT, dT * dT
41 // scalar, dT + 2 * dT * dT, 1
42
43 // Integrate out against prior
44 final DenseMatrix64F rootPrec = wrap(partialNodeBuffer, offsetPartial + dimTrait, dimTrait, dimTrait);
45 final DenseMatrix64F priorPrec = new DenseMatrix64F(dimTrait, dimTrait);
46 CommonOps.mult(Pd, wrap(partialPriorBuffer, offsetPartial + dimTrait, dimTrait, dimTrait), priorPrec);
47
48 final DenseMatrix64F totalPrec = new DenseMatrix64F(dimTrait, dimTrait);
49 CommonOps.add(rootPrec, priorPrec, totalPrec);
50
51 final DenseMatrix64F totalVar = new DenseMatrix64F(dimTrait, dimTrait);
52 safeInvert(totalPrec, totalVar, false);
53
54 final double[] tmp = new double[dimTrait];
55 final double[] mean = new double[dimTrait];
56
57 for (int g = 0; g < dimTrait; ++g) {
58 double sum = 0.0;
59 for (int h = 0; h < dimTrait; ++h) {
60 sum += rootPrec.unsafe_get(g, h) * partialNodeBuffer[offsetPartial + h];
61 sum += priorPrec.unsafe_get(g, h) * partialPriorBuffer[offsetPartial + h];
62 }
63 tmp[g] = sum;
64 }
65 for (int g = 0; g < dimTrait; ++g) {
66 double sum = 0.0;
67 for (int h = 0; h < dimTrait; ++h) {
68 sum += totalVar.unsafe_get(g, h) * tmp[h];
69 }
70 mean[g] = sum;
71 }
72
73 final double[][] cholesky = getCholeskyOfVariance(totalVar.getData(), dimTrait);
74
75 MultivariateNormalDistribution.nextMultivariateNormalCholesky(
76 mean, 0, // input mean
77 cholesky, 1.0, // input variance
78 sample, offsetSample, // output sample
79 tmpEpsilon);
80
81 if (DEBUG) {
82 System.err.println("Attempt to simulate root");
83 System.err.println("Root mean: " + new WrappedVector.Raw(partialNodeBuffer, offsetPartial, dimTrait));
84 System.err.println("Root prec: " + rootPrec);
85 System.err.println("Prior mean: " + new WrappedVector.Raw(partialPriorBuffer, offsetPartial, dimTrait));
86 System.err.println("Prior prec: " + priorPrec);
87 System.err.println("Total prec: " + totalPrec);
88 System.err.println("Total var: " + totalVar);
89
90
91 System.err.println("draw mean: " + new WrappedVector.Raw(mean, 0, dimTrait));
92 System.err.println("sample: " + new WrappedVector.Raw(sample, offsetSample, dimTrait));
93 }
94 }
95
96 // boolean extremeValue(final DenseMatrix64F x) {
97 // return extremeValue(new WrappedVector.Raw(x.getData(), 0, x.getNumElements()));
98 // }
99 //
100 // boolean extremeValue(final WrappedVector x) {
101 // boolean valid = true;
102 // for (int i = 0; i < x.getDim() && (valid); ++i) {
103 // if (Double.isNaN(x.get(i)) || Math.abs(x.get(i)) > 1E2) {
104 // valid = false;
105 // }
106 // }
107 // return !valid;
108 // }
109
110 @Override
111 protected void simulateTraitForNode(final int nodeIndex,
112 final int traitIndex,
113 final int offsetSample,
114 final int offsetParent,
115 final int offsetPartial,
116 final int isExternal,
117 final double branchPrecision) {
118
119 if (isExternal == 1) { // Is external
120 simulateTraitForExternalNode(nodeIndex, traitIndex, offsetSample, offsetParent, offsetPartial, branchPrecision);
121 } else {
122 simulateTraitForInternalNode(offsetSample, offsetParent, offsetPartial, branchPrecision);
123 }
124 }
125
126 private void simulateTraitForExternalNode(final int nodeIndex,
127 final int traitIndex,
128 final int offsetSample,
129 final int offsetParent,
130 final int offsetPartial,
131 final double branchPrecision) {
132
133 final DenseMatrix64F P0 = wrap(partialNodeBuffer, offsetPartial + dimTrait, dimTrait, dimTrait);
134 final int missingCount = countFiniteDiagonals(P0);
135
136 if (missingCount == 0) { // Completely observed
137
138 System.arraycopy(partialNodeBuffer, offsetPartial, sample, offsetSample, dimTrait);
139
140 } else {
141
142 final int zeroCount = countZeroDiagonals(P0);
143 if (zeroCount == dimTrait) { // All missing completely at random
144
145 final double sqrtScale = Math.sqrt(1.0 / branchPrecision);
146
147 // TODO Drift?
148 assert (!likelihoodDelegate.getDiffusionProcessDelegate().hasDrift());
149
150 MultivariateNormalDistribution.nextMultivariateNormalCholesky(
151 sample, offsetParent, // input mean
152 cholesky, sqrtScale, // input variance
153 sample, offsetSample, // output sample
154 tmpEpsilon);
155
156 } else {
157
158 if (missingCount == dimTrait) { // All missing, but not completely at random
159
160 simulateTraitForInternalNode(offsetSample, offsetParent, offsetPartial, branchPrecision);
161
162 } else { // Partially observed
163
164 System.arraycopy(partialNodeBuffer, offsetPartial, sample, offsetSample, dimTrait); // copy observed values
165
166 final PartiallyMissingInformation.HashedIntArray indices = missingInformation.getMissingIndices(nodeIndex, traitIndex);
167 final int[] observed = indices.getComplement();
168 final int[] missing = indices.getArray();
169
170 final DenseMatrix64F V1 = new DenseMatrix64F(dimTrait, dimTrait);
171 CommonOps.scale(1.0 / branchPrecision, Vd, V1);
172
173 ConditionalVarianceAndTransform2 transform =
174 new ConditionalVarianceAndTransform2(
175 V1, missing, observed
176 ); // TODO Cache (via delegated function)
177
178 final DenseMatrix64F cP0 = new DenseMatrix64F(missing.length, missing.length);
179 gatherRowsAndColumns(P0, cP0, missing, missing);
180
181 final WrappedVector cM2 = transform.getConditionalMean(
182 partialNodeBuffer, offsetPartial, // Tip value
183 sample, offsetParent); // Parent value
184
185 final DenseMatrix64F cP1 = transform.getConditionalPrecision();
186
187 final DenseMatrix64F cP2 = new DenseMatrix64F(missing.length, missing.length);
188 final DenseMatrix64F cV2 = new DenseMatrix64F(missing.length, missing.length);
189 CommonOps.add(cP0, cP1, cP2);
190
191 safeInvert(cP2, cV2, false);
192 double[][] cC2 = getCholeskyOfVariance(cV2.getData(), missing.length);
193
194 // TODO Drift?
195 assert (!likelihoodDelegate.getDiffusionProcessDelegate().hasDrift());
196
197 MultivariateNormalDistribution.nextMultivariateNormalCholesky(
198 cM2, // input mean
199 cC2, 1.0, // input variance
200 new WrappedVector.Indexed(sample, offsetSample, missing, missing.length), // output sample
201 tmpEpsilon);
202
203
204 if (DEBUG) {
205 final WrappedVector M0 = new WrappedVector.Raw(partialNodeBuffer, offsetPartial, dimTrait);
206
207 final WrappedVector M1 = new WrappedVector.Raw(sample, offsetParent, dimTrait);
208 final DenseMatrix64F P1 = new DenseMatrix64F(dimTrait, dimTrait);
209 CommonOps.scale(branchPrecision, Pd, P1);
210
211 final WrappedVector newSample = new WrappedVector.Raw(sample, offsetSample, dimTrait);
212
213 System.err.println("sT F E N");
214 System.err.println("M0: " + M0);
215 System.err.println("P0: " + P0);
216 System.err.println("");
217 System.err.println("M1: " + M1);
218 System.err.println("P1: " + P1);
219 System.err.println("");
220 System.err.println("cP0: " + cP0);
221 System.err.println("cM2: " + cM2);
222 System.err.println("cP1: " + cP1);
223 System.err.println("cP2: " + cP2);
224 System.err.println("cV2: " + cV2);
225 System.err.println("cC2: " + new Matrix(cC2));
226 System.err.println("SS: " + newSample);
227 System.err.println("");
228 }
229 }
230 }
231 }
232 }
233
234 private WrappedVector getMeanWithDrift(double[] mean, int offsetMean, double[] drift, int dim) {
235 for (int i = 0;i < dim; ++i) {
236 tmpDrift[i] = mean[offsetMean + i] + drift[i];
237 }
238 return new WrappedVector.Raw(tmpDrift, 0, dimTrait);
239 }
240
241 private void simulateTraitForInternalNode(final int offsetSample,
242 final int offsetParent,
243 final int offsetPartial,
244 final double branchPrecision) {
245
246 if (!Double.isInfinite(branchPrecision)) {
247
248 final WrappedVector M0 = new WrappedVector.Raw(partialNodeBuffer, offsetPartial, dimTrait);
249 final DenseMatrix64F P0 = wrap(partialNodeBuffer, offsetPartial + dimTrait, dimTrait, dimTrait);
250
251 final WrappedVector M1;
252 final DenseMatrix64F P1;
253
254 if (hasNoDrift) {
255 M1 = new WrappedVector.Raw(sample, offsetParent, dimTrait);
256 P1 = new DenseMatrix64F(dimTrait, dimTrait);
257 CommonOps.scale(branchPrecision, Pd, P1);
258 } else {
259 M1 = getMeanWithDrift(sample, offsetParent, displacementBuffer, dimTrait);
260 P1 = DenseMatrix64F.wrap(dimTrait, dimTrait, precisionBuffer);
261 }
262
263 // boolean DEBUG_PRECISION = false;
264 //
265 // if (DEBUG_PRECISION) {
266 // DenseMatrix64F tP1 = new DenseMatrix64F(dimTrait, dimTrait);
267 // CommonOps.scale(branchPrecision, Pd, tP1);
268 //
269 // for (int i = 0; i < dimTrait; ++i) {
270 // for (int j = 0; j < dimTrait; ++j) {
271 // if (Math.abs(tP1.get(i,j) - P1.get(i,j)) != 0.0) {
272 // System.err.println("Unequal");
273 // System.exit(-1);
274 // }
275 // }
276 // }
277 // }
278
279 final WrappedVector M2 = new WrappedVector.Raw(tmpMean, 0, dimTrait);
280 final DenseMatrix64F P2 = new DenseMatrix64F(dimTrait, dimTrait);
281 final DenseMatrix64F V2 = new DenseMatrix64F(dimTrait, dimTrait);
282
283 CommonOps.add(P0, P1, P2);
284 safeInvert(P2, V2, false);
285 weightedAverage(M0, P0, M1, P1, M2, V2, dimTrait);
286
287 double[][] C2 = getCholeskyOfVariance(V2.getData(), dimTrait);
288
289 MultivariateNormalDistribution.nextMultivariateNormalCholesky(
290 M2.getBuffer(), 0, // input mean
291 C2, 1.0, // input variance
292 sample, offsetSample, // output sample
293 tmpEpsilon);
294
295 if (DEBUG) {
296 System.err.println("sT F I N");
297 System.err.println("M0: " + M0);
298 System.err.println("P0: " + P0);
299 System.err.println("M1: " + M1);
300 System.err.println("P1: " + P1);
301 System.err.println("M2: " + M2);
302 System.err.println("V2: " + V2);
303 System.err.println("C2: " + new Matrix(C2));
304 System.err.println("SS: " + new WrappedVector.Raw(sample, offsetSample, dimTrait));
305 System.err.println("");
306
307 if (!check(M2)) {
308 System.exit(-1);
309 }
310 }
311
312 } else {
313
314 System.arraycopy(sample, offsetParent, sample, offsetSample, dimTrait);
315
316 if (DEBUG) {
317 System.err.println("sT F I N infinite branch precision");
318 System.err.println("SS: " + new WrappedVector.Raw(sample, offsetSample, dimTrait));
319 }
320 }
321 }
322
323 private boolean check(WrappedVector m2) {
324 for (int i = 0; i < m2.getDim(); ++i) {
325 if (Double.isNaN(m2.get(i))) {
326 return false;
327 }
328 }
329 return true;
330 }
331 }