Debian Codegraph @

src/dr/math/distributions/WishartDistribution.java

raw symbols SCIP
1 /*
2 * WishartDistribution.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.math.distributions;
27
28 import dr.math.GammaFunction;
29 import dr.math.MathUtils;
30 import dr.math.matrixAlgebra.CholeskyDecomposition;
31 import dr.math.matrixAlgebra.IllegalDimension;
32 import dr.math.matrixAlgebra.Matrix;
33
34 /**
35 * @author Marc Suchard
36 */
37 public class WishartDistribution implements MultivariateDistribution, WishartStatistics {
38
39 public static final String TYPE = "Wishart";
40
41 private double df;
42 private int dim;
43 private double[][] scaleMatrix;
44 private double[] Sinv;
45 private Matrix SinvMat;
46 private double logNormalizationConstant;
47
48 /**
49 * A Wishart distribution class for \nu degrees of freedom and scale matrix S
50 * Expectation = \nu * S
51 *
52 * @param df degrees of freedom
53 * @param scaleMatrix scaleMatrix
54 */
55
56 public WishartDistribution(double df, double[][] scaleMatrix) {
57 this.df = df;
58 this.scaleMatrix = scaleMatrix;
59 this.dim = scaleMatrix.length;
60
61 SinvMat = new Matrix(scaleMatrix).inverse();
62 double[][] tmp = SinvMat.toComponents();
63 Sinv = new double[dim * dim];
64 for (int i = 0; i < dim; i++) {
65 System.arraycopy(tmp[i], 0, Sinv, i * dim, dim);
66 }
67
68 computeNormalizationConstant();
69 }
70
71 public WishartDistribution(int dim) { // returns a non-informative (unormalizable) density
72 this.df = 0;
73 this.scaleMatrix = null;
74 this.dim = dim;
75 logNormalizationConstant = 0.0;
76 }
77
78
79 private void computeNormalizationConstant() {
80 logNormalizationConstant = computeNormalizationConstant(new Matrix(scaleMatrix), df, dim);
81 }
82
83 public static double computeNormalizationConstant(Matrix Sinv, double df, int dim) {
84
85 if (df == 0) {
86 return 0.0;
87 }
88
89 double logNormalizationConstant = 0;
90 try {
91 logNormalizationConstant = -df / 2.0 * Math.log(Sinv.determinant());
92 } catch (IllegalDimension illegalDimension) {
93 illegalDimension.printStackTrace();
94 }
95 logNormalizationConstant -= df * dim / 2.0 * Math.log(2);
96 logNormalizationConstant -= dim * (dim - 1) / 4.0 * Math.log(Math.PI);
97 for (int i = 1; i <= dim; i++) {
98 logNormalizationConstant -= GammaFunction.lnGamma((df + 1 - i) / 2.0);
99 }
100 return logNormalizationConstant;
101 }
102
103
104 public String getType() {
105 return TYPE;
106 }
107
108 public double[][] getScaleMatrix() {
109 return scaleMatrix;
110 }
111
112 public double[] getMean() {
113 return null;
114 }
115
116 public void testMe() {
117
118 int length = 100000;
119
120 double save1 = 0;
121 double save2 = 0;
122 double save3 = 0;
123 double save4 = 0;
124
125 for (int i = 0; i < length; i++) {
126
127 double[][] draw = nextWishart();
128 save1 += draw[0][0];
129 save2 += draw[0][1];
130 save3 += draw[1][0];
131 save4 += draw[1][1];
132
133 }
134
135 save1 /= length;
136 save2 /= length;
137 save3 /= length;
138 save4 /= length;
139
140 System.err.println("S1: " + save1);
141 System.err.println("S2: " + save2);
142 System.err.println("S3: " + save3);
143 System.err.println("S4: " + save4);
144
145
146 }
147
148 public double getDF() {
149 return df;
150 }
151
152 public double[][] nextWishart() {
153 return nextWishart(df, scaleMatrix);
154 }
155
156 /**
157 * Generate a random draw from a Wishart distribution
158 * Follows Odell and Feiveson (1996) JASA 61, 199-203
159 * <p/>
160 * Returns a random variable with expectation = df * scaleMatrix
161 *
162 * @param df degrees of freedom
163 * @param scaleMatrix scaleMatrix
164 * @return a random draw
165 */
166 public static double[][] nextWishart(double df, double[][] scaleMatrix) {
167
168 int dim = scaleMatrix.length;
169 double[][] draw = new double[dim][dim];
170
171 double[][] z = new double[dim][dim];
172
173 for (int i = 0; i < dim; i++) {
174 for (int j = 0; j < i; j++) {
175 z[i][j] = MathUtils.nextGaussian();
176 }
177 }
178
179 for (int i = 0; i < dim; i++)
180 z[i][i] = Math.sqrt(MathUtils.nextGamma((df - i) * 0.5, 0.5)); // sqrt of chisq with df-i dfs
181
182 double[][] cholesky = new double[dim][dim];
183 for (int i = 0; i < dim; i++) {
184 for (int j = i; j < dim; j++)
185 cholesky[i][j] = cholesky[j][i] = scaleMatrix[i][j];
186 }
187
188 try {
189 cholesky = (new CholeskyDecomposition(cholesky)).getL();
190 // caution: this returns the lower triangular form
191 } catch (IllegalDimension illegalDimension) {
192 throw new RuntimeException("Numerical exception in WishartDistribution");
193 }
194
195 double[][] result = new double[dim][dim];
196
197 for (int i = 0; i < dim; i++) {
198 for (int j = 0; j < dim; j++) { // lower triangular
199 for (int k = 0; k < dim; k++) // can also be shortened
200 result[i][j] += cholesky[i][k] * z[k][j];
201 }
202 }
203
204 for (int i = 0; i < dim; i++) { // lower triangular, so more efficiency is possible
205 for (int j = 0; j < dim; j++) {
206 for (int k = 0; k < dim; k++)
207 draw[i][j] += result[i][k] * result[j][k]; // transpose of 2nd element
208 }
209 }
210
211 return draw;
212 }
213
214 public double logPdf(double[] x) {
215 if (x.length == 4) { // bivariate
216 return logPdf2D(x, Sinv, df, dim, logNormalizationConstant);
217 } else {
218 return logPdfSlow(x);
219 }
220 }
221
222 public double logPdfSlow(double[] x) {
223 Matrix W = new Matrix(x, dim, dim);
224 return logPdf(W, SinvMat, df, dim, logNormalizationConstant);
225 }
226
227 public static double logPdf2D(double[] W, double[] Sinv, double df, int dim, double logNormalizationConstant) {
228
229 final double det = W[0] * W[3] - W[1] * W[2];
230 if (det <= 0) {
231 return Double.NEGATIVE_INFINITY;
232 }
233
234 double logDensity = Math.log(det);
235 logDensity *= 0.5 * (df - dim - 1);
236
237 // logDensity -= 0.5 * tr(Sinv %*% W)
238 final double trace = Sinv[0] * W[0] + Sinv[1] * W[2] + Sinv[2] * W[1] + Sinv[3] * W[3];
239 logDensity -= 0.5 * trace;
240
241 logDensity += logNormalizationConstant;
242
243 return logDensity;
244 }
245
246
247 public static double logPdf(Matrix W, Matrix Sinv, double df, int dim, double logNormalizationConstant) {
248
249 double logDensity = 0;
250
251 try {
252 // if (!W.isPD()) { // TODO isPD() does not appear to work
253 // return Double.NEGATIVE_INFINITY;
254 // }
255
256 logDensity = W.logDeterminant(); // Returns NaN is W is not positive-definite.
257
258 if (Double.isInfinite(logDensity) || Double.isNaN(logDensity)) {
259 return Double.NEGATIVE_INFINITY;
260 }
261
262 logDensity *= 0.5;
263 logDensity *= df - dim - 1;
264
265 // need only diagonal, no? seems a waste to compute
266 // the whole matrix
267 if (Sinv != null) {
268 Matrix product = Sinv.product(W);
269
270 for (int i = 0; i < dim; i++)
271 logDensity -= 0.5 * product.component(i, i);
272 }
273
274 } catch (IllegalDimension illegalDimension) {
275 illegalDimension.printStackTrace();
276 }
277
278 logDensity += logNormalizationConstant;
279 return logDensity;
280 }
281
282 public static void testBivariateMethod() {
283 System.out.println("Testing new computations ...");
284 WishartDistribution wd = new WishartDistribution(5, new double[][]{{2.0, -0.5}, {-0.5, 2.0}});
285 double[] W = new double[]{4.0, 1.0, 1.0, 3.0};
286 System.out.println("Fast logPdf = " + wd.logPdf(W));
287 System.out.println("Slow logPdf = " + wd.logPdfSlow(W));
288 }
289
290 public static void main(String[] argv) {
291 WishartDistribution wd = new WishartDistribution(2, new double[][]{{500.0}});
292 // The above is just an approximation
293 GammaDistribution gd = new GammaDistribution(1.0 / 1000.0, 1000.0);
294 double[] x = new double[]{1.0};
295 System.out.println("Wishart, df=2, scale = 500, PDF(1.0): " + wd.logPdf(x));
296 System.out.println("Gamma, shape = 1/1000, scale = 1000, PDF(1.0): " + gd.logPdf(x[0]));
297
298 wd = new WishartDistribution(4, new double[][]{{5.0}});
299 gd = new GammaDistribution(2.0, 10.0);
300 x = new double[]{1.0};
301 System.out.println("Wishart, df=4, scale = 5, PDF(1.0): " + wd.logPdf(x));
302 System.out.println("Gamma, shape = 1/1000, scale = 10, PDF(1.0): " + gd.logPdf(x[0]));
303 // These tests show the correspondence between a 1D Wishart and a Gamma
304
305 wd = new WishartDistribution(1);
306 x = new double[]{0.1};
307 System.out.println("Wishart, uninformative, PDF(0.1): " + wd.logPdf(x));
308 x = new double[]{1.0};
309 System.out.println("Wishart, uninformative, PDF(1.0): " + wd.logPdf(x));
310 x = new double[]{10.0};
311 System.out.println("Wishart, uninformative, PDF(10.0): " + wd.logPdf(x));
312 // These tests show the correspondence between a 1D Wishart and a Gamma
313 testBivariateMethod();
314
315 }
316 }