Debian Codegraph @

src/dr/evomodel/continuous/DebugableIntegratedMultivariateTraitLikelihood.java

raw symbols SCIP
1 /*
2 * DebugableIntegratedMultivariateTraitLikelihood.java
3 *
4 * Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
5 *
6 * This file is part of BEAST.
7 * See the NOTICE file distributed with this work for additional
8 * information regarding copyright ownership and licensing.
9 *
10 * BEAST is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU Lesser General Public License as
12 * published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * BEAST is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU Lesser General Public License for more details.
19 *
20 * You should have received a copy of the GNU Lesser General Public
21 * License along with BEAST; if not, write to the
22 * Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
23 * Boston, MA 02110-1301 USA
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.CompoundParameter;
33 import dr.inference.model.Model;
34 import dr.math.KroneckerOperation;
35 import dr.math.distributions.MultivariateNormalDistribution;
36 import dr.math.matrixAlgebra.Matrix;
37 import dr.math.matrixAlgebra.SymmetricMatrix;
38 import dr.math.matrixAlgebra.Vector;
39
40 import java.util.HashSet;
41 import java.util.List;
42 import java.util.Set;
43
44 /**
45 * This class contains all of the O(number of tips^2) functions to debug the dynamic programming in its superclasses
46 *
47 * @author Marc A Suchard
48 */
49 public class DebugableIntegratedMultivariateTraitLikelihood extends SemiConjugateMultivariateTraitLikelihood {
50
51 public DebugableIntegratedMultivariateTraitLikelihood(String traitName,
52 MutableTreeModel treeModel,
53 MultivariateDiffusionModel diffusionModel,
54 CompoundParameter traitParameter,
55 List<Integer> missingIndices,
56 boolean cacheBranches,
57 boolean scaleByTime,
58 boolean useTreeLength,
59 BranchRateModel rateModel,
60 Model samplingDensity,
61 boolean reportAsMultivariate,
62 MultivariateNormalDistribution rootPrior,
63 boolean reciprocalRates,
64 List<RestrictedPartials> partials) {
65
66 super(traitName, treeModel, diffusionModel, traitParameter, missingIndices, cacheBranches,
67 scaleByTime, useTreeLength, rateModel, samplingDensity, reportAsMultivariate,
68 rootPrior, reciprocalRates, partials);
69 }
70
71 protected double[] fillLeafTraits(int datum) {
72
73 final int tipCount = treeModel.getExternalNodeCount();
74
75 final int nonMissingTipCount = countNonMissingTips();
76
77 double[] traits = new double[dimTrait * nonMissingTipCount];
78 int index = 0;
79 for (int i = 0; i < tipCount; i++) {
80
81 if (!missingTraits.isCompletelyMissing(i)) {
82 for (int k = 0; k < dimTrait; k++) {
83 traits[index++] = meanCache[dim * i + datum * dimTrait + k];
84 }
85 }
86 }
87 return traits;
88 }
89
90 protected double[][] removeMissingTipsInTreeVariance(double[][] variance) {
91
92 final int tipCount = treeModel.getExternalNodeCount();
93 final int nonMissing = countNonMissingTips();
94
95 if (nonMissing == tipCount) { // Do nothing
96 return variance;
97 }
98
99 double[][] outVariance = new double[nonMissing][nonMissing];
100
101 int iReal = 0;
102 for (int i = 0; i < tipCount; i++) {
103 if (!missingTraits.isCompletelyMissing(i)) {
104
105 int jReal = 0;
106 for (int j = 0; j < tipCount; j++) {
107 if (!missingTraits.isCompletelyMissing(i)) {
108
109 outVariance[iReal][jReal] = variance[i][j];
110
111 jReal++;
112 }
113 }
114 iReal++;
115 }
116 }
117 return outVariance;
118 }
119
120 protected double[][] computeTreeTraitPrecision(double[][] traitPrecision) {
121 double[][] treePrecision = computeTreePrecision();
122 if (dimTrait > 1) {
123 treePrecision = KroneckerOperation.product(treePrecision, traitPrecision);
124 } else {
125 final double precision = traitPrecision[0][0];
126 for (int i = 0; i < treePrecision.length; i++) {
127 for (int j = 0; j < treePrecision[i].length; j++) {
128 treePrecision[i][j] *= precision;
129 }
130 }
131 }
132 return treePrecision;
133 }
134
135 public double[][] computeTreePrecision() {
136 return new SymmetricMatrix(computeTreeVariance()).inverse().toComponents();
137 }
138
139 private NodeRef findMRCA(int iTip, int jTip) {
140 Set<String> leafNames = new HashSet<String>();
141 leafNames.add(treeModel.getTaxonId(iTip));
142 leafNames.add(treeModel.getTaxonId(jTip));
143 return TreeUtils.getCommonAncestorNode(treeModel, leafNames);
144 }
145
146 public int getNumberOfDatum() {
147 return numData * countNonMissingTips();
148 }
149
150 protected double integrateLogLikelihoodAtRootFromFullTreeMatrix(double[][] treeTraitPrecisionMatrix,
151 double[] tipTraits) {
152
153 double logLikelihood = 0;
154 final int tipCount = countNonMissingTips();
155
156 // 1^t\Sigma^{-1} y + Pz
157 double[] mean = Ay;
158 for (int i = 0; i < dimTrait; i++) {
159 mean[i] = 0;
160 for (int j = 0; j < dimTrait; j++) {
161 mean[i] += rootPriorPrecision[i][j] * rootPriorMean[j];
162 }
163
164 for (int j = 0; j < tipCount; j++) {
165 final int rowOffset = j * dimTrait + i;
166 for (int k = 0; k < tipCount * dimTrait; k++) {
167 mean[i] += treeTraitPrecisionMatrix[rowOffset][k] * tipTraits[k];
168 }
169 }
170 }
171
172 // 1^t \Sigma^{-1} 1 + P
173 double[][] precision = tmpM;
174 for (int i = 0; i < dimTrait; i++) {
175 for (int j = 0; j < dimTrait; j++) {
176 precision[i][j] = rootPriorPrecision[i][j];
177 for (int k = 0; k < tipCount; k++) {
178 for (int l = 0; l < tipCount; l++) {
179 precision[i][j] += treeTraitPrecisionMatrix[k * dimTrait + i][l * dimTrait + j];
180 }
181 }
182 }
183 }
184 double[] normalizedMean = tmp2;
185 double[][] variance = new SymmetricMatrix(precision).inverse().toComponents();
186 for (int i = 0; i < dimTrait; i++) {
187 normalizedMean[i] = 0.0;
188 for (int j = 0; j < dimTrait; j++) {
189 normalizedMean[i] += variance[i][j] * mean[j];
190 }
191 }
192 mean = normalizedMean;
193
194 // We know: y ~ MVN(x, A) and x ~ N(m, B)
195 // Therefore p(x | y) = N( (A+B)^{-1}(Ay + Bm), A + B)
196 // We want: p( y ) = p( y | x ) p( x ) / p( x | y ) for any value x, say x = 0
197
198 logLikelihood += MultivariateNormalDistribution.logPdf(
199 rootPriorMean, new double[rootPriorMean.length], rootPriorPrecision,
200 logRootPriorPrecisionDeterminant, 1.0
201 );
202
203 logLikelihood -= MultivariateNormalDistribution.logPdf(
204 mean, new double[mean.length], precision,
205 Math.log(MultivariateNormalDistribution.calculatePrecisionMatrixDeterminate(precision)), 1.0
206 );
207
208 if (DEBUG) {
209 System.err.println("Mean = " + new Vector(mean));
210 System.err.println("Prec = " + new Matrix(precision));
211 System.err.println("log density = " + logLikelihood);
212 }
213 return logLikelihood;
214 }
215
216 public double[][] computeTreeVariance() {
217 final int tipCount = treeModel.getExternalNodeCount();
218 double[][] variance = new double[tipCount][tipCount];
219
220 for (int i = 0; i < tipCount; i++) {
221
222 // Fill in diagonal
223 double marginalTime = getRescaledLengthToRoot(treeModel.getExternalNode(i));
224 variance[i][i] = marginalTime;
225
226 // Fill in upper right triangle,
227
228 for (int j = i + 1; j < tipCount; j++) {
229 NodeRef mrca = findMRCA(i, j);
230 variance[i][j] = getRescaledLengthToRoot(mrca);
231 }
232 }
233
234 // Make symmetric
235 for (int i = 0; i < tipCount; i++) {
236 for (int j = i + 1; j < tipCount; j++) {
237 variance[j][i] = variance[i][j];
238 }
239 }
240
241 if (DEBUG) {
242 System.err.println("");
243 System.err.println("New tree conditional variance:\n" + new Matrix(variance));
244 }
245
246 variance = removeMissingTipsInTreeVariance(variance); // Automatically prune missing tips
247
248 if (DEBUG) {
249 System.err.println("");
250 System.err.println("New tree (trimmed) conditional variance:\n" + new Matrix(variance));
251 }
252
253 return variance;
254 }
255
256 protected int countNonMissingTips() {
257 int tipCount = treeModel.getExternalNodeCount();
258 for (int i = 0; i < tipCount; i++) {
259 if (missingTraits.isCompletelyMissing(i)) {
260 tipCount--;
261 }
262 }
263 return tipCount;
264 }
265
266 public void checkViaLargeMatrixInversion() {
267
268 // Perform a check based on filling in the (dimTrait * tipCount) * (dimTrait * tipCount) precision matrix
269 // And then integrating out the root trait value
270
271 // Form \Sigma^{-1} (precision) = (tree precision) %x% (trait precision)
272
273 double[][] treeTraitPrecisionMatrix = computeTreeTraitPrecision(diffusionModel.getPrecisionmatrix());
274
275 double totalLogDensity = 0;
276
277 for (int datum = 0; datum < numData; datum++) {
278
279 double[] tipTraits = fillLeafTraits(datum);
280
281 System.err.println("Datum #" + datum);
282 System.err.println("tipTraits = " + new Vector(tipTraits));
283 System.err.println("tipPrecision = \n" + new Matrix(treeTraitPrecisionMatrix));
284
285 double checkLogLikelihood = MultivariateNormalDistribution.logPdf(tipTraits, new double[tipTraits.length], treeTraitPrecisionMatrix,
286 Math.log(MultivariateNormalDistribution.calculatePrecisionMatrixDeterminate(treeTraitPrecisionMatrix)), 1.0);
287
288 System.err.println("tipDensity = " + checkLogLikelihood + " (should match final likelihood when root not integrated out and no missing data)");
289
290 // Convolve root prior
291 if (integrateRoot) {
292 checkLogLikelihood += integrateLogLikelihoodAtRootFromFullTreeMatrix(treeTraitPrecisionMatrix, tipTraits);
293 }
294 totalLogDensity += checkLogLikelihood;
295 }
296 System.err.println("Total logLikelihood (via tree) = " + totalLogDensity);
297 }
298
299 private double[][] computeTipTraitOuterProduct(int tip0, int tip1) {
300 double[][] outerProduct = new double[dimTrait][dimTrait];
301
302 final int offset0 = dim * tip0;
303 final int offset1 = dim * tip1;
304
305 for (int i = 0; i < dimTrait; i++) {
306 for (int j = 0; j < dimTrait; j++) {
307 for (int k = 0; k < numData; k++) {
308 outerProduct[i][j] += meanCache[offset0 + k * dimTrait + i] * meanCache[offset1 + k * dimTrait + j];
309 }
310 }
311 }
312 return outerProduct;
313 }
314
315 private void computeAllTipTraitOuterProducts() {
316 final int nTips = treeModel.getExternalNodeCount();
317
318 if (tipTraitOuterProducts == null) {
319 tipTraitOuterProducts = new double[nTips][nTips][][];
320 }
321
322 for (int i = 0; i < nTips; i++) {
323 if (!missingTraits.isCompletelyMissing(i)) {
324 tipTraitOuterProducts[i][i] = computeTipTraitOuterProduct(i, i);
325 for (int j = i + 1; j < nTips; j++) {
326 if (!missingTraits.isCompletelyMissing(i)) {
327 tipTraitOuterProducts[j][i] = tipTraitOuterProducts[i][j] = computeTipTraitOuterProduct(i, j);
328 } else {
329 tipTraitOuterProducts[j][i] = tipTraitOuterProducts[i][j] = null;
330 }
331 }
332 } else {
333 for (int j = 0; j < nTips; j++) {
334 tipTraitOuterProducts[i][j] = null;
335 }
336 }
337 }
338 }
339
340 // Returns the outer product of the tip traits for taxon 0 and taxon 1,
341 // or null if either taxon 0 or taxon 1 is missing
342
343 public double[][] getTipTraitOuterProduct(int tip0, int tip1) {
344 if (updateOuterProducts) {
345 computeAllTipTraitOuterProducts();
346 updateOuterProducts = false;
347 }
348 return tipTraitOuterProducts[tip0][tip1];
349 }
350
351 protected boolean updateOuterProducts = true;
352 protected double[][][][] tipTraitOuterProducts = null;
353 }