Debian Codegraph @

src/dr/evomodel/operators/PrecisionMatrixGibbsOperator.java

raw symbols SCIP
1 /*
2 * PrecisionMatrixGibbsOperator.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.evomodel.continuous.AbstractMultivariateTraitLikelihood;
31 import dr.evomodel.continuous.SampledMultivariateTraitLikelihood;
32 import dr.inference.distribution.MultivariateDistributionLikelihood;
33 import dr.inference.distribution.MultivariateNormalDistributionModel;
34 import dr.inference.distribution.WishartGammalDistributionModel;
35 import dr.inference.model.DiagonalConstrainedMatrixView;
36 import dr.inference.model.MatrixParameterInterface;
37 import dr.inference.model.Parameter;
38 import dr.inference.operators.GibbsOperator;
39 import dr.inference.operators.MCMCOperator;
40 import dr.inference.operators.SimpleMCMCOperator;
41 import dr.math.distributions.WishartDistribution;
42 import dr.math.distributions.WishartStatistics;
43 import dr.math.distributions.WishartSufficientStatistics;
44 import dr.math.interfaces.ConjugateWishartStatisticsProvider;
45 import dr.math.matrixAlgebra.IllegalDimension;
46 import dr.math.matrixAlgebra.Matrix;
47 import dr.math.matrixAlgebra.SymmetricMatrix;
48 import dr.math.matrixAlgebra.Vector;
49 import dr.util.Attribute;
50 import dr.xml.*;
51
52 import java.util.List;
53
54 //import dr.math.matrixAlgebra.Matrix;
55
56 /**
57 * @author Marc Suchard
58 */
59 public class PrecisionMatrixGibbsOperator extends SimpleMCMCOperator implements GibbsOperator {
60
61 public static final String VARIANCE_OPERATOR = "precisionGibbsOperator";
62 // public static final String PRECISION_MATRIX = "precisionMatrix";
63 public static final String TREE_MODEL = "treeModel";
64 // public static final String OUTCOME = "outcome";
65 // public static final String MEAN = "mean";
66 public static final String DISTRIBUTION = "distribution";
67 public static final String PRIOR = "prior";
68 // public static final String TRAIT_MODEL = "traitModel";
69
70 private final AbstractMultivariateTraitLikelihood traitModel;
71 private AbstractMultivariateTraitLikelihood debugModel = null;
72 private final ConjugateWishartStatisticsProvider conjugateWishartProvider;
73 private final MultivariateDistributionLikelihood multivariateLikelihood;
74 private final Parameter meanParam;
75 private final MatrixParameterInterface precisionParam;
76
77 private double priorDf;
78 private SymmetricMatrix priorInverseScaleMatrix;
79 private final MutableTreeModel treeModel;
80 private final int dim;
81 private double numberObservations;
82 private final String traitName;
83 private final boolean isSampledTraitLikelihood;
84 private double pathWeight = 1.0;
85
86 private boolean wishartIsModel = false;
87 private WishartGammalDistributionModel priorModel = null;
88
89 public PrecisionMatrixGibbsOperator(
90 MultivariateDistributionLikelihood likelihood,
91 WishartStatistics priorDistribution,
92 double weight) {
93 super();
94
95 // Unnecessary variables
96 this.traitModel = null;
97 this.treeModel = null;
98 this.traitName = null;
99 this.conjugateWishartProvider = null;
100 this.isSampledTraitLikelihood = false;
101
102 this.multivariateLikelihood = likelihood;
103 MultivariateNormalDistributionModel density = (MultivariateNormalDistributionModel) likelihood.getDistribution();
104 this.meanParam = density.getMeanParameter();
105 this.precisionParam = density.getPrecisionMatrixParameter();
106 this.dim = meanParam.getDimension();
107
108 setupWishartStatistics(priorDistribution);
109 if (priorDistribution instanceof WishartGammalDistributionModel) {
110 wishartIsModel = true;
111 priorModel = (WishartGammalDistributionModel) priorDistribution;
112 }
113
114 setWeight(weight);
115 }
116
117 private void setupWishartStatistics(WishartStatistics priorDistribution) {
118 this.priorDf = priorDistribution.getDF();
119 this.priorInverseScaleMatrix = null;
120 double[][] scale = priorDistribution.getScaleMatrix();
121 if (scale != null)
122 this.priorInverseScaleMatrix =
123 (SymmetricMatrix) (new SymmetricMatrix(scale)).inverse();
124 }
125
126 @Deprecated
127 public PrecisionMatrixGibbsOperator(
128 MatrixParameterInterface precisionParam,
129 AbstractMultivariateTraitLikelihood traitModel,
130 WishartStatistics priorDistribution,
131 double weight) {
132 super();
133 this.traitModel = traitModel;
134 this.conjugateWishartProvider = null;
135 this.meanParam = null;
136 this.precisionParam = precisionParam;
137 // this.precisionParam = traitModel.getDiffusionModel().getPrecisionParameter();
138
139 setupWishartStatistics(priorDistribution);
140 if (priorDistribution instanceof WishartGammalDistributionModel) {
141 wishartIsModel = true;
142 priorModel = (WishartGammalDistributionModel) priorDistribution;
143 }
144
145 setWeight(weight);
146
147 this.treeModel = traitModel.getTreeModel();
148 traitName = traitModel.getTraitName();
149 dim = precisionParam.getRowDimension(); // assumed to be square
150
151 isSampledTraitLikelihood = (traitModel instanceof SampledMultivariateTraitLikelihood);
152
153 if (!isSampledTraitLikelihood &&
154 !(traitModel instanceof ConjugateWishartStatisticsProvider)) {
155 throw new RuntimeException("Only implemented for a SampledMultivariateTraitLikelihood or " +
156 "ConjugateWishartStatisticsProvider");
157 }
158
159 multivariateLikelihood = null;
160 }
161
162 public PrecisionMatrixGibbsOperator(
163 ConjugateWishartStatisticsProvider wishartStatisticsProvider,
164 MatrixParameterInterface extraPrecisionParam,
165 WishartStatistics priorDistribution,
166 double weight,
167 AbstractMultivariateTraitLikelihood debugModel) {
168 super();
169 this.traitModel = null;
170 this.debugModel = debugModel;
171 this.conjugateWishartProvider = wishartStatisticsProvider;
172 this.meanParam = null;
173 this.precisionParam = (extraPrecisionParam != null ? extraPrecisionParam :
174 conjugateWishartProvider.getPrecisionParameter());
175 isSampledTraitLikelihood = false;
176 this.treeModel = null;
177 this.traitName = null;
178
179 setupWishartStatistics(priorDistribution);
180 if (priorDistribution instanceof WishartGammalDistributionModel) {
181 wishartIsModel = true;
182 priorModel = (WishartGammalDistributionModel) priorDistribution;
183 }
184
185 setWeight(weight);
186
187 // this.treeModel = traitModel.getTreeModel();
188 // traitName = traitModel.getTraitName();
189 dim = precisionParam.getRowDimension(); // assumed to be square
190
191 // isSampledTraitLikelihood = (traitModel instanceof SampledMultivariateTraitLikelihood);
192
193 // if (!isSampledTraitLikelihood &&
194 // !(traitModel instanceof ConjugateWishartStatisticsProvider)) {
195 // throw new RuntimeException("Only implemented for a SampledMultivariateTraitLikelihood or " +
196 // "ConjugateWishartStatisticsProvider");
197 // }
198
199 multivariateLikelihood = null;
200 }
201
202 public void setPathParameter(double beta) {
203 if (beta < 0 || beta > 1) {
204 throw new IllegalArgumentException("Illegal path weight of " + beta);
205 }
206 pathWeight = beta;
207 }
208
209 public int getStepCount() {
210 return 1;
211 }
212
213 // private void incrementScaledSquareMatrix(double[][] out, double[][] in, double scalar, int dim) {
214 // for (int i = 0; i < dim; i++) {
215 // for (int j = 0; j < dim; j++) {
216 // out[i][j] += scalar * in[i][j];
217 // }
218 // }
219 // }
220
221 // private void zeroSquareMatrix(double[][] out, int dim) {
222 // for (int i = 0; i < dim; i++) {
223 // for (int j = 0; j < dim; j++) {
224 // out[i][j] = 0.0;
225 // }
226 // }
227 // }
228
229 private void incrementOuterProduct(double[][] S,
230 MultivariateDistributionLikelihood likelihood) {
231
232 double[] mean = likelihood.getDistribution().getMean();
233
234 numberObservations = 0;
235 List<Attribute<double[]>> dataList = likelihood.getDataList();
236 int count = 0;
237 for (Attribute<double[]> d : dataList) {
238
239 double[] data = d.getAttributeValue();
240 for (int i = 0; i < dim; i++) {
241 data[i] -= mean[i];
242 }
243
244 for (int i = 0; i < dim; i++) { // symmetric matrix,
245 for (int j = i; j < dim; j++) {
246 S[j][i] = S[i][j] += data[i] * data[j];
247 }
248 }
249 numberObservations += 1;
250 }
251 }
252
253 private void incrementOuterProduct(double[][] S,
254 ConjugateWishartStatisticsProvider integratedLikelihood) {
255
256
257 final WishartSufficientStatistics sufficientStatistics = integratedLikelihood.getWishartStatistics();
258 final double[] outerProducts = sufficientStatistics.getScaleMatrix();
259
260 final double df = sufficientStatistics.getDf();
261 if (DEBUG) {
262 System.err.println("OP df = " + df);
263 System.err.println("OP = " + new Vector(outerProducts));
264 }
265 // System.exit(-1);
266
267 if (debugModel != null) {
268 final WishartSufficientStatistics debug = ((ConjugateWishartStatisticsProvider) debugModel).getWishartStatistics();
269 System.err.println(df + " ?= " + debug.getDf());
270 System.err.println(new Vector(outerProducts));
271 System.err.println("");
272 System.err.println(new Vector(debug.getScaleMatrix()));
273 System.exit(-1);
274 }
275
276
277 // final double df = 2;
278
279 // final double df = integratedLikelihood.getTotalTreePrecision();
280
281 // System.err.println("OuterProducts = \n" + new Matrix(outerProducts));
282 // System.err.println("Total tree DF = " + df);
283 // System.exit(-1);
284
285 final int dim = S.length;
286 for (int i = 0; i < dim; i++) {
287 System.arraycopy(outerProducts, i * dim, S[i], 0, dim);
288 }
289 numberObservations = df;
290
291
292 // checkDiagonals(outerProducts);
293
294
295 }
296
297 // private void checkDiagonals(double[][] S) {
298 // for (int i = 0; i < S.length; ++i) {
299 // if (S[i][i] < 0.0) {
300 // System.err.println("ERROR diag(S)\n" + new Matrix(S));
301 // System.exit(-1);
302 // }
303 // }
304 // }
305
306 private void incrementOuterProduct(double[][] S, NodeRef node) {
307
308 if (!treeModel.isRoot(node)) {
309
310 NodeRef parent = treeModel.getParent(node);
311 double[] parentTrait = treeModel.getMultivariateNodeTrait(parent, traitName);
312 double[] childTrait = treeModel.getMultivariateNodeTrait(node, traitName);
313 double time = traitModel.getRescaledBranchLengthForPrecision(node);
314
315 if (time > 0) {
316
317 double sqrtTime = Math.sqrt(time);
318
319 double[] delta = new double[dim];
320
321 for (int i = 0; i < dim; i++)
322 delta[i] = (childTrait[i] - parentTrait[i]) / sqrtTime;
323
324 for (int i = 0; i < dim; i++) { // symmetric matrix,
325 for (int j = i; j < dim; j++)
326 S[j][i] = S[i][j] += delta[i] * delta[j];
327 }
328 numberObservations += 1; // This assumes a *single* observation per tip
329 }
330 }
331 // recurse down tree
332 for (int i = 0; i < treeModel.getChildCount(node); i++)
333 incrementOuterProduct(S, treeModel.getChild(node, i));
334 }
335
336 public double[][] getOperationScaleMatrixAndSetObservationCount() {
337
338 // calculate sum-of-the-weighted-squares matrix over tree
339 double[][] S = new double[dim][dim];
340 SymmetricMatrix S2;
341 SymmetricMatrix inverseS2 = null;
342 numberObservations = 0; // Need to reset, as incrementOuterProduct can be recursive
343
344 if (isSampledTraitLikelihood) {
345 incrementOuterProduct(S, treeModel.getRoot());
346 } else { // IntegratedTraitLikelihood
347 if (traitModel != null) { // is a tree
348 incrementOuterProduct(S, (ConjugateWishartStatisticsProvider) traitModel); // TODO deprecate usage
349 } else if (conjugateWishartProvider != null) {
350 incrementOuterProduct(S, conjugateWishartProvider);
351 } else { // is a normal-normal-wishart model
352 incrementOuterProduct(S, multivariateLikelihood);
353 }
354 }
355
356 try {
357 S2 = new SymmetricMatrix(S);
358 if (pathWeight != 1.0) {
359 S2 = (SymmetricMatrix) S2.product(pathWeight);
360 }
361 if (priorInverseScaleMatrix != null)
362 S2 = priorInverseScaleMatrix.add(S2);
363 inverseS2 = (SymmetricMatrix) S2.inverse();
364
365 // if (S[0][0] < 0.0) {
366 // System.err.println("ERROR A");
367 // System.err.println(new Matrix(S));
368 // }
369 //
370 // if (S2.component(0, 0) < 0.0) {
371 // System.err.println("ERROR B");
372 // System.err.println(S2);
373 // }
374 //
375 // if (inverseS2.component(0, 0) < 0.0) {
376 // System.err.println("ERROR C");
377 // System.err.println("S:\n" + new Matrix(S));
378 // System.err.println("S2:\n" + S2);
379 // System.err.println(inverseS2);
380 // }
381
382 } catch (IllegalDimension illegalDimension) {
383 illegalDimension.printStackTrace();
384 }
385
386 assert inverseS2 != null;
387
388 return inverseS2.toComponents();
389 }
390
391 public double doOperation() {
392
393 if (wishartIsModel) {
394 setupWishartStatistics(priorModel);
395 }
396
397 final double[][] scaleMatrix = getOperationScaleMatrixAndSetObservationCount();
398 final double treeDf = numberObservations;
399 final double df = priorDf + treeDf * pathWeight;
400
401 // if (scaleMatrix[0][0] < 0.0) {
402 // System.err.println("ERROR");
403 // System.err.println(new Matrix(scaleMatrix));
404 // }
405
406 double[][] draw = WishartDistribution.nextWishart(df, scaleMatrix);
407 // int tries = 0;
408 // int limit = 100;
409 // boolean success = false;
410 //
411 // double[][] draw = null;
412 //
413 // while (!success && tries < limit) {
414
415 if (DEBUG) {
416 System.err.println("draw = " + new Matrix(draw));
417 }
418
419 //
420 //
421 // draw = WishartDistribution.nextWishart(df, scaleMatrix);
422 //
423 // Matrix m = new Matrix(draw);
424 // try {
425 // double logDet = m.logDeterminant();
426 // if (Double.isNaN(logDet)) {
427 // System.err.println("Bad proposal!");
428 // System.err.println("df = " + df);
429 //
430 //// System.err.println(m);
431 //// System.exit(-1);
432 // } else {
433 // success = true;
434 // }
435 //
436 // } catch (IllegalDimension illegalDimension) {
437 // illegalDimension.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
438 // System.exit(-1);
439 // }
440 //
441 // tries++;
442 // }
443 //
444 // if (tries >= limit) {
445 // System.err.println("Too many attempts!");
446 // System.exit(-1);
447 // }
448
449 for (int i = 0; i < dim; i++) {
450 Parameter column = precisionParam.getParameter(i);
451 for (int j = 0; j < dim; j++)
452 column.setParameterValueQuietly(j, draw[j][i]);
453 }
454 precisionParam.fireParameterChangedEvent();
455
456 return 0;
457 }
458
459 public String getPerformanceSuggestion() {
460 return null;
461 }
462
463 public String getOperatorName() {
464 return VARIANCE_OPERATOR;
465 }
466
467 public static dr.xml.XMLObjectParser PARSER = new dr.xml.AbstractXMLObjectParser() {
468
469 public String getParserName() {
470 return VARIANCE_OPERATOR;
471 }
472
473 public Object parseXMLObject(XMLObject xo) throws XMLParseException {
474
475 double weight = xo.getDoubleAttribute(WEIGHT);
476
477 AbstractMultivariateTraitLikelihood traitModel = (AbstractMultivariateTraitLikelihood) xo.getChild(AbstractMultivariateTraitLikelihood.class);
478 ConjugateWishartStatisticsProvider ws = (ConjugateWishartStatisticsProvider) xo.getChild(ConjugateWishartStatisticsProvider.class);
479 if (ws == traitModel) {
480 ws = null;
481 }
482
483 MultivariateDistributionLikelihood prior = null;
484 MatrixParameterInterface precMatrix = null;
485 MultivariateDistributionLikelihood likelihood = null;
486
487 if (traitModel != null) {
488 precMatrix = traitModel.getDiffusionModel().getPrecisionParameter();
489 prior = (MultivariateDistributionLikelihood) xo.getChild(MultivariateDistributionLikelihood.class);
490 }
491
492 if (ws != null) {
493 precMatrix = ws.getPrecisionParameter();
494 prior = (MultivariateDistributionLikelihood) xo.getChild(MultivariateDistributionLikelihood.class);
495 }
496
497 if (traitModel == null && ws == null) { // generic likelihood and prior
498 for (int i = 0; i < xo.getChildCount(); ++i) {
499 MultivariateDistributionLikelihood density = (MultivariateDistributionLikelihood) xo.getChild(i);
500 if (density.getDistribution() instanceof WishartStatistics) {
501 prior = density;
502 } else if (density.getDistribution() instanceof MultivariateNormalDistributionModel) {
503 likelihood = density;
504 precMatrix = ((MultivariateNormalDistributionModel)
505 density.getDistribution()).getPrecisionMatrixParameter();
506 }
507 }
508
509 if (prior == null || likelihood == null) {
510 throw new XMLParseException(
511 "Must provide a multivariate normal likelihood and Wishart prior in element '" +
512 xo.getName() + "'\n"
513 );
514 }
515 }
516
517 if (!(prior.getDistribution() instanceof WishartStatistics)) {
518 throw new XMLParseException("Only a Wishart distribution is conjugate for Gibbs sampling");
519 }
520
521 // Make sure precMatrix is square and dim(precMatrix) = dim(parameter)
522 if (precMatrix.getColumnDimension() != precMatrix.getRowDimension()) {
523 throw new XMLParseException("The variance matrix is not square or of wrong dimension");
524 }
525
526 if (traitModel != null && ws == null) {
527
528 if (precMatrix instanceof DiagonalConstrainedMatrixView) {
529 precMatrix = (MatrixParameterInterface) xo.getChild(MatrixParameterInterface.class);
530
531 if (precMatrix == null) {
532 throw new XMLParseException("Must provide unconstrained precision matrix");
533 }
534 }
535
536 return new PrecisionMatrixGibbsOperator(
537 precMatrix,
538 traitModel, (WishartStatistics) prior.getDistribution(), weight
539 );
540 } else if (ws != null) {
541
542 if (precMatrix instanceof DiagonalConstrainedMatrixView) {
543 precMatrix = (MatrixParameterInterface) xo.getChild(MatrixParameterInterface.class);
544
545 if (precMatrix == null) {
546 throw new XMLParseException("Must provide unconstrained precision matrix");
547 }
548 } else {
549 precMatrix = null;
550 }
551
552 return new PrecisionMatrixGibbsOperator(
553 ws, precMatrix, (WishartStatistics) prior.getDistribution(), weight, traitModel
554 );
555
556 } else {
557 return new PrecisionMatrixGibbsOperator(likelihood, (WishartStatistics) prior.getDistribution(), weight);
558 }
559 }
560
561 //************************************************************************
562 // AbstractXMLObjectParser implementation
563 //************************************************************************
564
565 public String getParserDescription() {
566 return "This element returns a multivariate normal random walk operator on a given parameter.";
567 }
568
569 public Class getReturnType() {
570 return MCMCOperator.class;
571 }
572
573 public XMLSyntaxRule[] getSyntaxRules() {
574 return rules;
575 }
576
577 private XMLSyntaxRule[] rules = new XMLSyntaxRule[]{
578 AttributeRule.newDoubleRule(WEIGHT),
579 new ElementRule(AbstractMultivariateTraitLikelihood.class, true),
580 new ElementRule(ConjugateWishartStatisticsProvider.class, true),
581 new ElementRule(MultivariateDistributionLikelihood.class, 1, 2),
582 new ElementRule(MatrixParameterInterface.class, true),
583 };
584 };
585
586 private static final boolean DEBUG = false;
587 }