Debian Codegraph @

src/dr/evomodel/continuous/NonPhylogeneticMultivariateTraitLikelihood.java

raw symbols SCIP
1 /*
2 * NonPhylogeneticMultivariateTraitLikelihood.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.Tree;
31 import dr.evomodel.branchratemodel.BranchRateModel;
32 import dr.inference.model.CompoundParameter;
33 import dr.inference.model.Model;
34 import dr.inference.model.Parameter;
35 import dr.math.distributions.WishartSufficientStatistics;
36 import dr.math.matrixAlgebra.Matrix;
37 import dr.math.matrixAlgebra.Vector;
38 import dr.util.Citable;
39
40 import java.util.List;
41 import java.util.logging.Logger;
42
43 /**
44 * Integrated multivariate trait likelihood that assumes a fully-conjugate prior on the root and
45 * no underlying tree structure.
46 *
47 * @author Gabriela Cybis
48 * @author Marc A. Suchard
49 * @author Bridgett vonHoldt
50 */
51 public class NonPhylogeneticMultivariateTraitLikelihood extends FullyConjugateMultivariateTraitLikelihood {
52
53 public NonPhylogeneticMultivariateTraitLikelihood(String traitName,
54 MutableTreeModel treeModel,
55 MultivariateDiffusionModel diffusionModel,
56 CompoundParameter traitParameter,
57 Parameter deltaParameter,
58 List<Integer> missingIndices,
59 boolean cacheBranches,
60 boolean scaleByTime,
61 boolean useTreeLength,
62 BranchRateModel rateModel,
63 Model samplingDensity,
64 boolean reportAsMultivariate,
65 double[] rootPriorMean,
66 double rootPriorSampleSize,
67 List<RestrictedPartials> partials,
68 boolean reciprocalRates,
69 boolean exchangeableTips) {
70 super(traitName, treeModel, diffusionModel, traitParameter, deltaParameter, missingIndices, cacheBranches,
71 scaleByTime, useTreeLength, rateModel, null, null, null, samplingDensity, reportAsMultivariate, rootPriorMean,
72 partials, rootPriorSampleSize, reciprocalRates);
73 this.exchangeableTips = exchangeableTips;
74 this.zeroHeightTip = findZeroHeightTip(treeModel);
75 printInformtion2();
76 }
77
78 private int findZeroHeightTip(Tree tree) {
79 for (int i = 0; i < tree.getExternalNodeCount(); ++i) {
80 NodeRef tip = tree.getExternalNode(i);
81 if (tree.getNodeHeight(tip) == 0.0) {
82 return i;
83 }
84 }
85 return -1;
86 }
87
88 protected void printInformtion() {
89 // Do nothing yet
90 }
91
92 protected void printInformtion2() {
93 StringBuilder sb = new StringBuilder("Creating non-phylogenetic multivariate diffusion model:\n");
94 sb.append("\tTrait: ").append(traitName).append("\n");
95 sb.append("\tDiffusion process: ").append(diffusionModel.getId()).append("\n");
96 sb.append("\tExchangeable tips: ").append((exchangeableTips ? "yes" : "no"));
97 if (exchangeableTips) {
98 sb.append(" initial inverse-weight = ").append(1.0 / getLengthToRoot(treeModel.getExternalNode(0)));
99 }
100 sb.append("\n");
101 sb.append(extraInfo());
102 sb.append("\tPlease cite:\n");
103 sb.append(Citable.Utils.getCitationString(this));
104
105
106 sb.append("\n\tDiffusion dimension : ").append(dimTrait).append("\n");
107 sb.append( "\tNumber of observations: ").append(numData).append("\n");
108 Logger.getLogger("dr.evomodel").info(sb.toString());
109 }
110
111 protected double getTreeLength() {
112 double treeLength = 0;
113
114 double rootHeight = treeModel.getNodeHeight(treeModel.getRoot());
115 treeLength = 0;
116 for (int i = 0; i < treeModel.getExternalNodeCount(); i++) {
117 NodeRef node = treeModel.getExternalNode(i);
118 treeLength += rootHeight - treeModel.getNodeHeight(node); // Bug was here
119 }
120 return treeLength;
121 }
122
123 private class SufficientStatistics {
124 double sumWeight;
125 double productWeight;
126 double innerProduct;
127 int nonMissingTips;
128
129 SufficientStatistics(double sumWeight, double productWeight, double innerProduct, int nonMissingTips) {
130 this.sumWeight = sumWeight;
131 this.productWeight = productWeight;
132 this.innerProduct = innerProduct;
133 this.nonMissingTips = nonMissingTips;
134 }
135 }
136
137 protected double getLengthToRoot(NodeRef nodeRef) {
138 final double height;
139 if (exchangeableTips) {
140 height = getRescaledLengthToRoot(treeModel.getExternalNode(zeroHeightTip));
141 } else {
142 height = getRescaledLengthToRoot(nodeRef);
143 }
144 return height;
145 }
146
147 // Useful identity for computing outerproducts for Wishart statistics
148 // \sum (y_i - \bar{y}) (y_i - \bar{y})^{t} = \sum y_i y_i^{t} - n \bar{y} \bar{y}^t
149
150 private SufficientStatistics computeInnerProductsForTips(double[][] traitPrecision, double[] tmpVector) {
151
152 // Compute the contribution of each datum at the root
153 final int rootIndex = treeModel.getRoot().getNumber();
154 final int meanOffset = dim * rootIndex;
155
156 // Zero-out root mean
157 for (int d = 0; d < dim; ++d) {
158 meanCache[meanOffset + d] = 0;
159 }
160
161 double innerProducts = 0.0;
162
163 // Compute the contribution of each datum at the root
164 double productWeight = 1.0;
165 double sumWeight = 0.0;
166 int nonMissingTips = 0;
167 for (int i = 0; i < treeModel.getExternalNodeCount(); ++i) {
168 NodeRef tipNode = treeModel.getExternalNode(i);
169 final int tipNumber = tipNode.getNumber();
170
171 double tipWeight = 0.0;
172 if (!missingTraits.isCompletelyMissing(tipNumber)) {
173
174 tipWeight = 1.0 / getLengthToRoot(tipNode);
175
176 int tipOffset = dim * tipNumber;
177 int rootOffset = dim * rootIndex;
178
179 for (int datum = 0; datum < numData; ++datum) {
180 // TODO Make faster when dimTrait == 1
181
182 // Add weighted tip value
183 for (int d = 0; d < dimTrait; ++d) {
184 meanCache[rootOffset + d] += tipWeight * meanCache[tipOffset + d];
185 tmpVector[d] = meanCache[tipOffset + d];
186 }
187
188 // Compute outer product
189 double yAy = computeWeightedAverageAndSumOfSquares(tmpVector, Ay, traitPrecision, dimTrait,
190 tipWeight);
191 innerProducts += yAy;
192
193 if (DEBUG_NO_TREE) {
194 System.err.println("OP for " + tipNumber + " = " + yAy);
195 System.err.println("Value = " + new Vector(tmpVector));
196 System.err.print ("Prec =\n" + new Matrix(traitPrecision));
197 System.err.println("weight = " + tipWeight + "\n");
198 }
199
200 tipOffset += dimTrait;
201 rootOffset += dimTrait;
202 }
203
204 if (computeWishartStatistics) {
205 incrementOuterProducts(tipNumber, tipWeight);
206 }
207 }
208
209 if (tipWeight > 0.0) {
210 sumWeight += tipWeight;
211 productWeight *= tipWeight;
212 ++nonMissingTips;
213 }
214 }
215
216 lowerPrecisionCache[rootIndex] = sumWeight;
217 normalize(meanCache, meanOffset, dim, sumWeight);
218
219 if (computeWishartStatistics) {
220 incrementOuterProducts(rootIndex, -sumWeight);
221 wishartStatistics.incrementDf(-1);
222 }
223
224 return new SufficientStatistics(sumWeight, productWeight, innerProducts,
225 nonMissingTips);
226 }
227
228 private void normalize(double[] x, int offset, int dim, double weight) {
229 for (int d = 0; d < dim; ++d) {
230 x[offset + d] /= weight;
231 }
232 }
233
234 private void incrementOuterProducts(int nodeNumber, double nodeWeight) {
235
236 final double[] outerProduct = wishartStatistics.getScaleMatrix();
237
238 int tipOffset = dim * nodeNumber;
239 for (int datum = 0; datum < numData; ++datum) {
240 for (int i = 0; i < dim; ++i) {
241 double yi = meanCache[tipOffset + i];
242 for (int j = 0; j < dim; ++j) {
243 outerProduct[i * dim + j] += yi * meanCache[tipOffset +j] * nodeWeight;
244 }
245 }
246 tipOffset += dimTrait;
247 }
248
249 wishartStatistics.incrementDf(1); // Peeled one node
250 }
251
252 protected boolean peel() {
253 return false;
254 }
255
256 public double calculateLogLikelihood() {
257
258 double[][] traitPrecision = diffusionModel.getPrecisionmatrix();
259 double logDetTraitPrecision = Math.log(diffusionModel.getDeterminantPrecisionMatrix());
260 double[] marginalRoot = tmp2;
261
262 if (computeWishartStatistics) {
263 wishartStatistics = new WishartSufficientStatistics(dimTrait);
264 }
265
266 // Compute the contribution of each datum at the root
267 SufficientStatistics stats = computeInnerProductsForTips(traitPrecision, tmp2);
268
269 double conditionalSumWeight = stats.sumWeight;
270 double conditionalProductWeight = stats.productWeight;
271 double innerProducts = stats.innerProduct;
272 int nonMissingTips = stats.nonMissingTips;
273
274 // Add in prior and integrate
275 double sumWeight = conditionalSumWeight + rootPriorSampleSize;
276 double productWeight = conditionalProductWeight * rootPriorSampleSize;
277 double rootPrecision = productWeight / sumWeight;
278
279 final int rootIndex = treeModel.getRoot().getNumber();
280 int rootOffset = dim * rootIndex;
281
282 for (int datum = 0; datum < numData; ++datum) {
283
284 // Determine marginal root (scaled) mean
285 for (int d = 0; d < dimTrait; ++d) {
286 marginalRoot[d] = conditionalSumWeight * meanCache[rootOffset + d] + rootPriorSampleSize * rootPriorMean[d];
287 }
288
289 // Compute outer product contribution from prior
290 double yAy1 = computeWeightedAverageAndSumOfSquares(rootPriorMean, Ay, traitPrecision, dimTrait,
291 rootPriorSampleSize);
292 innerProducts += yAy1; // TODO Only need to compute once
293
294 if (DEBUG_NO_TREE) {
295 System.err.println("OP for root");
296 System.err.println("Value = " + new Vector(rootPriorMean));
297 System.err.print ("Prec = \n" + new Matrix(traitPrecision));
298 System.err.println("Weight = " + rootPriorSampleSize + "\n");
299 }
300
301 // Compute outer product differences to complete square
302 double yAy2 = computeWeightedAverageAndSumOfSquares(marginalRoot, Ay, traitPrecision, dimTrait,
303 1.0 / sumWeight);
304 innerProducts -= yAy2;
305
306 // Add prior on root contribution
307 if (computeWishartStatistics) {
308
309 final double[] outerProducts = wishartStatistics.getScaleMatrix();
310 final double weight = conditionalSumWeight * rootPriorSampleSize / sumWeight;
311
312 for (int i = 0; i < dimTrait; i++) {
313 final double diffi = meanCache[rootOffset + i] - rootPriorMean[i];
314 for (int j = 0; j < dimTrait; j++) {
315 outerProducts[i * dimTrait + j] += diffi * weight * (meanCache[rootOffset + j] - rootPriorMean[j]);
316 }
317 }
318 wishartStatistics.incrementDf(1);
319 }
320
321 rootOffset += dimTrait;
322 }
323
324 if (DEBUG_NO_TREE) {
325 System.err.println("SumWeight : " + sumWeight);
326 System.err.println("ProductWeight: " + productWeight);
327 System.err.println("Total OP : " + innerProducts);
328 }
329
330 // Compute log likelihood
331 double logLikelihood =
332 -LOG_SQRT_2_PI * dimTrait * nonMissingTips * numData
333 + 0.5 * logDetTraitPrecision * nonMissingTips * numData
334 + 0.5 * Math.log(rootPrecision) * dimTrait * numData
335 - 0.5 * innerProducts;
336
337 if (DEBUG_NO_TREE) {
338 System.err.println("logLikelihood (final) = " + logLikelihood);
339 System.err.println("numData = " + numData);
340 }
341
342 areStatesRedrawn = false; // Should redraw internal node states when needed
343 return logLikelihood;
344 }
345
346 private final boolean exchangeableTips;
347 private final int zeroHeightTip;
348
349 private static final boolean DEBUG_NO_TREE = false;
350 private static final boolean NO_RESCALING = false;
351 }