Debian Codegraph @

src/dr/evomodel/operators/TraitGibbsOperator.java

raw symbols SCIP
1 /*
2 * TraitGibbsOperator.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.operators;
27
28 import dr.evolution.tree.MutableTreeModel;
29 import dr.evolution.tree.NodeRef;
30 import dr.evolution.util.Taxon;
31 import dr.evomodel.continuous.AbstractMultivariateTraitLikelihood;
32 import dr.evomodel.continuous.SampledMultivariateTraitLikelihood;
33 import dr.geo.GeoSpatialCollectionModel;
34 import dr.geo.GeoSpatialDistribution;
35 import dr.inference.distribution.MultivariateDistributionLikelihood;
36 import dr.inference.model.MatrixParameter;
37 import dr.inference.operators.GibbsOperator;
38 import dr.inference.operators.MCMCOperator;
39 import dr.inference.operators.SimpleMCMCOperator;
40 import dr.math.MathUtils;
41 import dr.math.distributions.MultivariateDistribution;
42 import dr.math.distributions.MultivariateNormalDistribution;
43 import dr.math.matrixAlgebra.SymmetricMatrix;
44 import dr.xml.*;
45
46 import java.util.HashMap;
47 import java.util.Map;
48 import java.util.logging.Logger;
49
50 /**
51 * @author Marc Suchard
52 */
53 public class TraitGibbsOperator extends SimpleMCMCOperator implements GibbsOperator {
54
55 public static final String GIBBS_OPERATOR = "traitGibbsOperator";
56 public static final String INTERNAL_ONLY = "onlyInternalNodes";
57 public static final String TIP_WITH_PRIORS_ONLY = "onlyTipsWithPriors";
58 public static final String NODE_PRIOR = "nodePrior";
59 public static final String NODE_LABEL = "taxon";
60 public static final String ROOT_PRIOR = "rootPrior";
61
62 private final MutableTreeModel treeModel;
63 private final MatrixParameter precisionMatrixParameter;
64 private final SampledMultivariateTraitLikelihood traitModel;
65 private final int dim;
66 private final String traitName;
67
68 private Map<Taxon, GeoSpatialDistribution> nodeGeoSpatialPrior;
69 private Map<Taxon, MultivariateNormalDistribution> nodeMVNPrior;
70 private GeoSpatialCollectionModel parameterPrior = null;
71
72 private boolean onlyInternalNodes = true;
73 private boolean onlyTipsWithPriors = true;
74 private boolean sampleRoot = false;
75 private double[] rootPriorMean;
76 private double[][] rootPriorPrecision;
77 private final int maxTries = 10000;
78
79 public TraitGibbsOperator(SampledMultivariateTraitLikelihood traitModel, boolean onlyInternalNodes,
80 boolean onlyTipsWithPriors) {
81 super();
82 this.traitModel = traitModel;
83 this.treeModel = traitModel.getTreeModel();
84 this.precisionMatrixParameter = (MatrixParameter) traitModel.getDiffusionModel().getPrecisionParameter();
85 this.traitName = traitModel.getTraitName();
86 this.onlyInternalNodes = onlyInternalNodes;
87 this.onlyTipsWithPriors = onlyTipsWithPriors;
88 this.dim = treeModel.getMultivariateNodeTrait(treeModel.getRoot(), traitName).length;
89 Logger.getLogger("dr.evomodel").info("Using *NEW* trait Gibbs operator");
90 }
91
92 public void setRootPrior(MultivariateNormalDistribution rootPrior) {
93 rootPriorMean = rootPrior.getMean();
94 rootPriorPrecision = rootPrior.getScaleMatrix();
95 sampleRoot = true;
96 }
97
98 public void setTaxonPrior(Taxon taxon, MultivariateDistribution distribution) {
99
100 if (distribution instanceof GeoSpatialDistribution) {
101 if (nodeGeoSpatialPrior == null) {
102 nodeGeoSpatialPrior = new HashMap<Taxon, GeoSpatialDistribution>();
103 }
104 nodeGeoSpatialPrior.put(taxon, (GeoSpatialDistribution) distribution);
105
106 } else if (distribution instanceof MultivariateNormalDistribution) {
107 if (nodeMVNPrior == null) {
108 nodeMVNPrior = new HashMap<Taxon, MultivariateNormalDistribution>();
109 }
110 nodeMVNPrior.put(taxon, (MultivariateNormalDistribution) distribution);
111 } else {
112 throw new RuntimeException("Only flat/truncated geospatial and multivariate normal distributions allowed");
113 }
114 }
115
116 public void setParameterPrior(GeoSpatialCollectionModel distribution) {
117 parameterPrior = distribution;
118 }
119
120 public int getStepCount() {
121 return 1;
122 }
123
124 private boolean nodeGeoSpatialPriorExists(NodeRef node) {
125 return nodeGeoSpatialPrior != null && nodeGeoSpatialPrior.containsKey(treeModel.getNodeTaxon(node));
126 }
127
128 private boolean nodeMVNPriorExists(NodeRef node) {
129 return nodeMVNPrior != null && nodeMVNPrior.containsKey(treeModel.getNodeTaxon(node));
130 }
131
132 public double doOperation() {
133
134 NodeRef node = null;
135 final NodeRef root = treeModel.getRoot();
136
137 while (node == null) {
138 if (onlyInternalNodes)
139 node = treeModel.getInternalNode(MathUtils.nextInt(
140 treeModel.getInternalNodeCount()));
141 else {
142 node = treeModel.getNode(MathUtils.nextInt(
143 treeModel.getNodeCount()));
144 if (onlyTipsWithPriors &&
145 (treeModel.getChildCount(node) == 0) && // Is a tip
146 !nodeGeoSpatialPriorExists(node)) { // Does not have a prior
147 node = null;
148 }
149 }
150 if (!sampleRoot && node == root)
151 node = null;
152 } // select any internal (or internal/external) node
153
154 final double[] initialValue = treeModel.getMultivariateNodeTrait(node, traitName);
155
156 MeanPrecision mp;
157
158 if (node != root)
159 mp = operateNotRoot(node);
160 else
161 mp = operateRoot(node);
162
163 final Taxon taxon = treeModel.getNodeTaxon(node);
164
165 // final boolean nodePriorExists = nodeGeoSpatialPrior != null && nodeGeoSpatialPrior.containsKey(taxon);
166 final boolean nodePriorExists = nodeGeoSpatialPriorExists(node);
167
168 // if (!onlyInternalNodes) {
169 // final boolean isTip = (treeModel.getChildCount(node) == 0);
170 // if (!nodePriorExists && isTip)
171 // System.err.println("Warning: sampling taxon '"+treeModel.getNodeTaxon(node).getId()
172 // +"' tip trait without a prior!!!");
173 // }
174
175 int count = 0;
176
177 final boolean parameterPriorExists = parameterPrior != null;
178
179 double[] draw;
180
181 do {
182 do {
183 if (count > maxTries) {
184 treeModel.setMultivariateTrait(node, traitName, initialValue); // TODO Add to MTT interface
185 throw new RuntimeException("Truncated Gibbs is stuck!");
186 }
187
188 draw = MultivariateNormalDistribution.nextMultivariateNormalPrecision(
189 mp.mean, mp.precision);
190 count++;
191
192 } while (nodePriorExists && // There is a prior for this node
193 (nodeGeoSpatialPrior.get(taxon)).logPdf(draw) == Double.NEGATIVE_INFINITY); // And draw is invalid under prior
194 // TODO Currently only works for flat/truncated priors, make work for MVN
195
196 treeModel.setMultivariateTrait(node, traitName, draw);
197
198 } while (parameterPriorExists &&
199 (parameterPrior.getLogLikelihood() == Double.NEGATIVE_INFINITY));
200
201 return 0;
202 }
203
204 private MeanPrecision operateNotRoot(NodeRef node) {
205
206 double[][] precision = precisionMatrixParameter.getParameterAsMatrix();
207
208 NodeRef parent = treeModel.getParent(node);
209
210 double[] mean = new double[dim];
211
212 double weight = 1.0 / traitModel.getRescaledBranchLengthForPrecision(node);
213
214 double[] trait = treeModel.getMultivariateNodeTrait(parent, traitName);
215
216 for (int i = 0; i < dim; i++)
217 mean[i] = trait[i] * weight;
218
219 double weightTotal = weight;
220 for (int j = 0; j < treeModel.getChildCount(node); j++) {
221 NodeRef child = treeModel.getChild(node, j);
222 trait = treeModel.getMultivariateNodeTrait(child, traitName);
223 weight = 1.0 / traitModel.getRescaledBranchLengthForPrecision(child);
224
225 for (int i = 0; i < dim; i++)
226 mean[i] += trait[i] * weight;
227
228 weightTotal += weight;
229 }
230
231 for (int i = 0; i < dim; i++) {
232 mean[i] /= weightTotal;
233 for (int j = i; j < dim; j++)
234 precision[j][i] = precision[i][j] *= weightTotal;
235 }
236
237 if (nodeMVNPriorExists(node)) {
238 throw new RuntimeException("Still trying to implement multivariate normal taxon priors");
239 }
240
241 return new MeanPrecision(mean, precision);
242 }
243
244 class MeanPrecision {
245 final double[] mean;
246 final double[][] precision;
247
248 MeanPrecision(double[] mean, double[][] precision) {
249 this.mean = mean;
250 this.precision = precision;
251 }
252 }
253
254 private MeanPrecision operateRoot(NodeRef node) {
255
256 double[] trait;
257 double weightTotal = 0.0;
258
259 double[] weightedAverage = new double[dim];
260
261 double[][] precision = precisionMatrixParameter.getParameterAsMatrix();
262
263 for (int k = 0; k < treeModel.getChildCount(node); k++) {
264 NodeRef child = treeModel.getChild(node, k);
265 trait = treeModel.getMultivariateNodeTrait(child, traitName);
266 final double weight = 1.0 / traitModel.getRescaledBranchLengthForPrecision(child);
267
268 for (int i = 0; i < dim; i++) {
269 for (int j = 0; j < dim; j++)
270 weightedAverage[i] += precision[i][j] * weight * trait[j];
271 }
272
273 weightTotal += weight;
274 }
275
276 for (int i = 0; i < dim; i++) {
277 for (int j = 0; j < dim; j++) {
278 weightedAverage[i] += rootPriorPrecision[i][j] * rootPriorMean[j];
279 precision[i][j] = precision[i][j] * weightTotal + rootPriorPrecision[i][j];
280 }
281 }
282
283 double[][] variance = new SymmetricMatrix(precision).inverse().toComponents();
284
285 trait = new double[dim];
286 for (int i = 0; i < dim; i++) {
287 for (int j = 0; j < dim; j++)
288 trait[i] += variance[i][j] * weightedAverage[j];
289 }
290
291 return new MeanPrecision(trait, precision);
292 }
293
294 public String getPerformanceSuggestion() {
295 return null;
296 }
297
298 public String getOperatorName() {
299 return GIBBS_OPERATOR;
300 }
301
302 public static XMLObjectParser PARSER = new AbstractXMLObjectParser() {
303
304 public String getParserName() {
305 return GIBBS_OPERATOR;
306 }
307
308 private final String[] names = {GIBBS_OPERATOR, "internalTraitGibbsOperator"};
309
310 public String[] getParserNames() {
311 return names;
312 }
313
314 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
315
316 double weight = xo.getDoubleAttribute(WEIGHT);
317 boolean onlyInternalNodes = xo.getAttribute(INTERNAL_ONLY, true);
318 boolean onlyTipsWithPriors = xo.getAttribute(TIP_WITH_PRIORS_ONLY, true);
319 SampledMultivariateTraitLikelihood traitModel = (SampledMultivariateTraitLikelihood) xo.getChild(AbstractMultivariateTraitLikelihood.class);
320
321 TraitGibbsOperator operator = new TraitGibbsOperator(traitModel, onlyInternalNodes, onlyTipsWithPriors);
322 operator.setWeight(weight);
323
324 // Get root prior
325
326 XMLObject cxo = xo.getChild(ROOT_PRIOR);
327 if (cxo != null) {
328
329 MultivariateDistributionLikelihood rootPrior = (MultivariateDistributionLikelihood) cxo.getChild(MultivariateDistributionLikelihood.class);
330 if (!(rootPrior.getDistribution() instanceof MultivariateDistribution))
331 throw new XMLParseException("Only multivariate normal priors allowed for Gibbs sampling the root trait");
332 operator.setRootPrior((MultivariateNormalDistribution) rootPrior.getDistribution());
333 }
334
335
336 // Get node priors
337 for (int i = 0; i < xo.getChildCount(); i++) {
338 if (xo.getChild(i) instanceof MultivariateDistributionLikelihood) {
339 MultivariateDistribution dist = ((MultivariateDistributionLikelihood) xo.getChild(i)).getDistribution();
340 if (dist instanceof GeoSpatialDistribution) {
341 GeoSpatialDistribution prior = (GeoSpatialDistribution) dist;
342 String nodeLabel = prior.getLabel();
343 Taxon taxon = getTaxon(traitModel.getTreeModel(), nodeLabel);
344 operator.setTaxonPrior(taxon, prior);
345 System.err.println("Adding truncated prior for taxon '" + taxon + "'");
346 }
347 }
348 }
349
350 GeoSpatialCollectionModel collectionModel = (GeoSpatialCollectionModel) xo.getChild(GeoSpatialCollectionModel.class);
351 if (collectionModel != null) {
352 operator.setParameterPrior(collectionModel);
353 System.err.println("Adding truncated prior '" + collectionModel.getId() +
354 "' for parameter '" + collectionModel.getParameter().getId() + "'");
355 }
356
357 return operator;
358 }
359
360 private Taxon getTaxon(MutableTreeModel treeModel, String taxonLabel) throws XMLParseException {
361 // Get taxon node from tree
362 int index = treeModel.getTaxonIndex(taxonLabel);
363 if (index == -1) {
364 throw new XMLParseException("Taxon '" + taxonLabel + "' not found for geoSpatialDistribution element in traitGibbsOperator element");
365 }
366 return treeModel.getTaxon(index);
367 }
368
369 //************************************************************************
370 // AbstractXMLObjectParser implementation
371 //************************************************************************
372
373 public String getParserDescription() {
374 return "This element returns a multivariate Gibbs operator on traits for possible all nodes.";
375 }
376
377 public Class getReturnType() {
378 return MCMCOperator.class;
379 }
380
381 public XMLSyntaxRule[] getSyntaxRules() {
382 return rules;
383 }
384
385 private final XMLSyntaxRule[] rules = {
386 AttributeRule.newDoubleRule(WEIGHT),
387 AttributeRule.newBooleanRule(INTERNAL_ONLY, true),
388 AttributeRule.newBooleanRule(TIP_WITH_PRIORS_ONLY, true),
389 new ElementRule(SampledMultivariateTraitLikelihood.class),
390 // new ElementRule(NODE_PRIOR, new XMLSyntaxRule[] {
391 // AttributeRule.newStringRule(NODE_LABEL),
392 // new ElementRule(MultivariateDistributionLikelihood.class),
393 // }),
394 new ElementRule(MultivariateDistributionLikelihood.class, 0, Integer.MAX_VALUE),
395 new ElementRule(ROOT_PRIOR,
396 new XMLSyntaxRule[]{
397 new ElementRule(MultivariateDistributionLikelihood.class)
398 }, true),
399 new ElementRule(GeoSpatialCollectionModel.class, true),
400 };
401
402 };
403
404 }