Debian Codegraph @

src/dr/inference/operators/EllipticalSliceOperator.java

raw symbols SCIP
1 /*
2 * EllipticalSliceOperator.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.inference.operators;
27
28 import dr.inference.distribution.DistributionLikelihood;
29 import dr.inference.distribution.MultivariateDistributionLikelihood;
30 import dr.inference.distribution.NormalDistributionModel;
31 import dr.inference.distribution.ParametricDistributionModel;
32 import dr.inference.model.*;
33 import dr.inferencexml.operators.EllipticalSliceOperatorParser;
34 import dr.math.MathUtils;
35 import dr.math.distributions.CompoundGaussianProcess;
36 import dr.math.distributions.GaussianProcessRandomGenerator;
37 import dr.math.distributions.MultivariateNormalDistribution;
38 import dr.util.Attribute;
39 import dr.util.Transform;
40
41 import java.util.ArrayList;
42 import java.util.List;
43
44 /**
45 * Implements a generic multivariate slice sampler for a Gaussian prior
46 * <p/>
47 * See: Murray, Adams, et al.
48 *
49 * @author Marc A. Suchard
50 * @author Max Tolkoff
51 */
52
53 public class EllipticalSliceOperator extends SimpleMetropolizedGibbsOperator implements GibbsOperator {
54
55 private final GaussianProcessRandomGenerator gaussianProcess;
56
57 public EllipticalSliceOperator(Parameter variable, GaussianProcessRandomGenerator gaussianProcess,
58 boolean drawByRow, boolean signal) {
59 this(variable, gaussianProcess, drawByRow, signal, 0.0, false, false);
60
61 }
62
63 public EllipticalSliceOperator(Parameter variable, GaussianProcessRandomGenerator gaussianProcess,
64 boolean drawByRow, boolean signal, double bracketAngle,
65 boolean translationInvariant, boolean rotationInvariant) {
66 this.variable = variable;
67 this.gaussianProcess = gaussianProcess;
68 this.drawByRow = drawByRow; // TODO Fix!
69 this.signalConstituentParameters = signal;
70 this.bracketAngle = bracketAngle;
71
72 this.translationInvariant = translationInvariant; // TODO Delegrate into transformed variable
73 this.rotationInvariant = rotationInvariant;
74
75 if (bracketAngle < 0.0 || bracketAngle >= 2.0 * Math.PI) {
76 throw new IllegalArgumentException("Invalid bracket angle");
77 }
78
79 // Check dimensions of variable and gaussianProcess
80 int dimVariable = variable.getDimension();
81 double[] draw = (double[]) gaussianProcess.nextRandom();
82 int dimDraw = draw.length;
83
84 if (dimVariable != dimDraw) {
85 throw new IllegalArgumentException("Dimension of variable (" + dimVariable +
86 ") does not match dimension of Gaussian process draw (" + dimDraw + ")" );
87 }
88
89 // TODO Must set priorMean if gaussianProcess does not have a 0-mean.
90 }
91
92 public Variable<Double> getVariable() {
93 return variable;
94 }
95
96 private double getLogGaussianPrior() {
97 return (gaussianProcess.getLikelihood() == null) ?
98 gaussianProcess.logPdf(variable.getParameterValues()) :
99 gaussianProcess.getLikelihood().getLogLikelihood();
100 }
101
102 private void unwindCompoundLikelihood(Likelihood likelihood, List<Likelihood> list) {
103 if (likelihood instanceof CompoundLikelihood) {
104 for (Likelihood like : ((CompoundLikelihood) likelihood).getLikelihoods()) {
105 unwindCompoundLikelihood(like, list);
106 }
107 } else {
108 list.add(likelihood);
109 }
110 }
111
112 private List<Likelihood> unwindCompoundLikelihood(Likelihood likelihood) {
113 List<Likelihood> list = new ArrayList<Likelihood>();
114 unwindCompoundLikelihood(likelihood, list);
115 return list;
116 }
117
118 private boolean containsGaussianProcess(Likelihood likelihood) {
119 if (gaussianProcess instanceof CompoundGaussianProcess) {
120 return ((CompoundGaussianProcess) gaussianProcess).contains(likelihood);
121 } else {
122 return gaussianProcess == likelihood;
123 }
124 }
125
126 private double evaluateDensity(Likelihood likelihood, double pathParameter) {
127 double logPosterior = evaluate(likelihood, pathParameter);
128 double logGaussianPrior = getLogGaussianPrior() * pathParameter;
129
130 return logPosterior - logGaussianPrior;
131 }
132
133 public double doOperation(Likelihood likelihood) {
134
135 // System.err.println("Likelihood type:" + likelihood.getClass().getName());
136
137 if (MINIMAL_EVALUATION) {
138
139 List<Likelihood> fullList = unwindCompoundLikelihood(likelihood);
140
141 // List<Likelihood> removeList = new ArrayList<Likelihood>();
142
143 List<Likelihood> subList = new ArrayList<Likelihood>();
144 for (Likelihood like : fullList) {
145 if (!containsGaussianProcess(like)) {
146 subList.add(like);
147 } //else {
148 // removeList.add(like);
149 // }
150 }
151 CompoundLikelihood cl = new CompoundLikelihood(subList);
152 // CompoundLikelihood removeCl = new CompoundLikelihood(removeList);
153 // CompoundLikelihood fullCl = new CompoundLikelihood(fullList);
154
155 double logDensity = cl.getLogLikelihood();
156 double cutoffDensity = logDensity + MathUtils.randomLogDouble();
157 drawFromSlice(cl, cutoffDensity);
158
159 } else {
160
161 double logPosterior = evaluate(likelihood, pathParameter);
162 double logGaussianPrior = getLogGaussianPrior() * pathParameter;
163
164 // Cut-off depends only on non-GP contribution to posterior
165 double cutoffDensity = logPosterior - logGaussianPrior + MathUtils.randomLogDouble();
166 drawFromSlice(likelihood, cutoffDensity);
167 }
168
169 // No need to set variable, as SliceInterval has already done this (and recomputed posterior)
170 return 0;
171 }
172
173 private double[] pointOnEllipse(double[] x, double[] y, double phi, double[] priorMean) {
174 final int dim = x.length;
175 final double cos = Math.cos(phi);
176 final double sin = Math.sin(phi);
177
178 double[] r = new double[dim];
179
180 if (priorMean == null) {
181 for (int i = 0; i < dim; ++i) {
182 r[i] = x[i] * cos + y[i] * sin;
183 }
184 } else { // Non-0 prior mean
185 for (int i = 0; i < dim; ++i) {
186 r[i] = (x[i] - priorMean[i]) * cos + (y[i] - priorMean[i]) * sin + priorMean[i];
187 }
188 }
189 return r;
190 }
191
192 private static void translate(double[] x, int dim) {
193 double[] mean = new double[dim];
194 int k = 0;
195 for (int i = 0; i < x.length / dim; ++i) {
196 for (int j = 0; j < dim; ++j) {
197 mean[j] += x[k];
198 ++k;
199 }
200 }
201
202 for (int j = 0; j < dim; ++j) {
203 mean[j] /= (x.length / dim);
204 }
205
206 k = 0;
207 for (int i = 0; i < x.length / dim; ++i) {
208 for (int j = 0; j < dim; ++j) {
209 x[k] -= mean[j];
210 ++k;
211 }
212 }
213 }
214
215 // private static void rotate2d(double[] x) {
216 // final double theta = -Math.atan2(x[1], x[0]); // TODO Compute norm and avoid transcendentals
217 // final double sin = Math.sin(theta);
218 // final double cos = Math.cos(theta);
219 //
220 // int k = 0;
221 // for (int i = 0; i < x.length / 2; ++i) {
222 // double newX = x[k + 0] * cos - x[k + 1] * sin;
223 // double newY = x[k + 1] * cos + x[k + 0] * sin;
224 // x[k + 0] = newX;
225 // x[k + 1] = newY;
226 // k += 2;
227 // }
228 // }
229
230 private static void rotateNd(double[] x, int dim) {
231
232 for (int d = 1; d < dim; ++d) {
233
234 final double theta = -Math.atan2(x[d], x[0]); // TODO Compute norm and avoid transcendentals
235 final double sin = Math.sin(theta);
236 final double cos = Math.cos(theta);
237
238 int k = 0;
239 for (int i = 0; i < x.length / dim; ++i) {
240 double newX = x[k + 0] * cos - x[k + d] * sin;
241 double newY = x[k + d] * cos + x[k + 0] * sin;
242 x[k + 0] = newX;
243 x[k + d] = newY;
244 k += dim;
245 }
246 }
247 }
248
249 private static void rotate(double[] x, int dim) {
250
251 // if (dim == 2) {
252 // rotate2d(x);
253 // } else {
254 rotateNd(x, dim);
255 // }
256 }
257
258 public static void transformPoint(double[] x, boolean translationInvariant, boolean rotationInvariant, int dim) {
259
260 if (translationInvariant) {
261 translate(x, dim);
262 }
263
264 if (rotationInvariant) {
265 rotate(x, dim);
266 }
267 }
268
269 private void transformPoint(double[] x) {
270 transformPoint(x, translationInvariant, rotationInvariant, 2);
271 }
272
273 private void setAllParameterValues(double[] x) {
274 if (variable instanceof MatrixParameterInterface) {
275 ((MatrixParameterInterface) variable).setAllParameterValuesQuietly(x, 0);
276 } else {
277 for (int i = 0; i < x.length; ++i) {
278 variable.setParameterValueQuietly(i, x[i]);
279 }
280 }
281 }
282
283 private void setVariable(double[] x) {
284
285 transformPoint(x);
286
287 setAllParameterValues(x);
288
289 if (signalConstituentParameters) {
290 variable.fireParameterChangedEvent();
291 } else {
292 variable.fireParameterChangedEvent(-1, Variable.ChangeType.ALL_VALUES_CHANGED);
293 }
294 }
295
296 private void drawFromSlice(Likelihood likelihood, double cutoffDensity) {
297
298 double[] x = variable.getParameterValues();
299 double[] nu = (double[]) gaussianProcess.nextRandom();
300
301 double phi;
302 Interval phiInterval;
303
304 if (bracketAngle == 0.0) {
305 phi = MathUtils.nextDouble() * 2.0 * Math.PI;
306 phiInterval = new Interval(phi - 2.0 * Math.PI, phi);
307 } else {
308 double phi_min = -bracketAngle * MathUtils.nextDouble();
309 double phi_max = phi_min + bracketAngle;
310 phiInterval = new Interval(phi_min, phi_max);
311 phi = phiInterval.draw();
312 }
313
314
315 boolean done = false;
316 while (!done) {
317 double[] xx = pointOnEllipse(x, nu, phi, priorMean);
318 setVariable(xx);
319 double density = evaluate(likelihood, pathParameter);
320 density -= getLogGaussianPrior(); // Depends only on non-GP contribution to posterior
321
322 if (density > cutoffDensity) {
323 done = true;
324 } else {
325 phiInterval.adjust(phi);
326 phi = phiInterval.draw();
327 }
328 }
329 }
330
331 private void drawFromSlice(CompoundLikelihood likelihood, double cutoffDensity) {
332
333 double[] x = variable.getParameterValues();
334 double[] nu = (double[]) gaussianProcess.nextRandom();
335
336 double phi;
337 Interval phiInterval;
338
339 if (bracketAngle == 0.0) {
340 phi = MathUtils.nextDouble() * 2.0 * Math.PI;
341 phiInterval = new Interval(phi - 2.0 * Math.PI, phi);
342 } else {
343 double phi_min = -bracketAngle * MathUtils.nextDouble();
344 double phi_max = phi_min + bracketAngle;
345 phiInterval = new Interval(phi_min, phi_max);
346 phi = phiInterval.draw();
347 }
348
349
350 boolean done = false;
351 while (!done) {
352 double[] xx = pointOnEllipse(x, nu, phi, priorMean);
353 setVariable(xx);
354 double logDensity = likelihood.getLogLikelihood();
355
356 if (logDensity > cutoffDensity) {
357 done = true;
358 } else {
359 phiInterval.adjust(phi);
360 phi = phiInterval.draw();
361 }
362 }
363 }
364
365 private class Interval {
366 double lower;
367 double upper;
368
369 Interval(double lower, double upper) {
370 this.lower = lower;
371 this.upper = upper;
372 }
373
374 void adjust(double phi) {
375 if (phi > 0) {
376 upper = phi;
377 } else if (phi < 0) {
378 lower = phi;
379 } else {
380 throw new RuntimeException("Shrunk to current position; bad.");
381 }
382 }
383
384 double draw() {
385 return MathUtils.nextDouble() * (upper - lower) + lower;
386 }
387
388 }
389
390 public int getStepCount() {
391 return 1;
392 }
393
394 /**
395 * Set the path parameter for sampling from power-posterior
396 */
397 @Override
398 public void setPathParameter(double beta) {
399 pathParameter=beta;
400 }
401
402 public String getOperatorName() {
403 return EllipticalSliceOperatorParser.ELLIPTICAL_SLICE_SAMPLER;
404 }
405
406 public static void main(String[] arg) {
407
408 // Define normal model
409 Parameter thetaParameter = new Parameter.Default(new double[]{1.0, 0.0}); // Starting values
410 MaskedParameter meanParameter = new MaskedParameter(thetaParameter,
411 new Parameter.Default(new double[]{1.0, 0.0}), true);
412 TransformedParameter precParameter = new TransformedParameter(
413 new MaskedParameter(thetaParameter,
414 new Parameter.Default(new double[]{0.0, 1.0}), true),
415 new Transform.LogTransform(),
416 true
417 );
418
419 // System.err.println(thetaParameter);
420 // System.err.println(meanParameter);
421 // System.err.println(precParameter);
422
423 ParametricDistributionModel densityModel = new NormalDistributionModel(meanParameter, precParameter, true);
424 DistributionLikelihood likelihood = new DistributionLikelihood(densityModel);
425
426 // Define prior
427 MultivariateNormalDistribution priorDistribution = new MultivariateNormalDistribution(
428 new double[]{0.0, 0.0},
429 new double[][]{{0.001, 0.0}, {0.0, 0.001}}
430 );
431 MultivariateDistributionLikelihood prior = new MultivariateDistributionLikelihood(priorDistribution);
432 prior.addData(thetaParameter);
433
434 // Define data
435 // likelihood.addData(new Attribute.Default<double[]>("Data", new double[] {0.0, 2.0, 4.0}));
436 likelihood.addData(new Attribute.Default<double[]>("Data", new double[]{1, 2, 3, 4, 5, 6, 7, 8, 9}));
437
438 List<Likelihood> list = new ArrayList<Likelihood>();
439 list.add(likelihood);
440 list.add(prior);
441 CompoundLikelihood posterior = new CompoundLikelihood(0, list);
442 EllipticalSliceOperator sliceSampler = new EllipticalSliceOperator(thetaParameter, priorDistribution,
443 false, true);
444
445
446 final int dim = thetaParameter.getDimension();
447 final int length = 100000;
448 double[] mean = new double[dim];
449 double[] variance = new double[dim];
450 Parameter[] log = new Parameter[dim];
451 log[0] = meanParameter;
452 log[1] = precParameter;
453
454 for (int i = 0; i < length; i++) {
455 sliceSampler.doOperation(posterior);
456 for (int j = 0; j < dim; ++j) {
457 double x = log[j].getValue(0);
458 mean[j] += x;
459 variance[j] += x * x;
460 }
461 }
462 for (int j = 0; j < dim; ++j) {
463 mean[j] /= length;
464 variance[j] /= length;
465 variance[j] -= mean[j] * mean[j];
466 }
467 System.out.println("E(x)\tStErr(x)");
468 for (int j = 0; j < dim; ++j) {
469 System.out.println(mean[j] + " " + Math.sqrt(variance[j]));
470 }
471 }
472
473 private static final boolean MINIMAL_EVALUATION = true;
474
475 private double pathParameter = 1.0;
476 private final Parameter variable;
477 private int current;
478 private boolean drawByRow;
479 private boolean signalConstituentParameters;
480 private double[] priorMean = null;
481
482 private boolean center = true;
483 private double bracketAngle;
484
485 private boolean translationInvariant;
486 private boolean rotationInvariant;
487
488 /*
489 function [xx, cur_log_like] = elliptical_slice(xx, prior, log_like_fn, cur_log_like, angle_range, varargin)
490 %ELLIPTICAL_SLICE Markov chain update for a distribution with a Gaussian "prior" factored out
491 %
492 % [xx, cur_log_like] = elliptical_slice(xx, chol_Sigma, log_like_fn);
493 % OR
494 % [xx, cur_log_like] = elliptical_slice(xx, prior_sample, log_like_fn);
495 %
496 % Optional additional arguments: cur_log_like, angle_range, varargin (see below).
497 %
498 % A Markov chain update is applied to the D-element array xx leaving a
499 % "posterior" distribution
500 % P(xx) \propto N(xx;0,Sigma) L(xx)
501 % invariant. Where N(0,Sigma) is a zero-mean Gaussian distribution with
502 % covariance Sigma. Often L is a likelihood function in an inference problem.
503 %
504 % Inputs:
505 % xx Dx1 initial vector (can be any array with D elements)
506 %
507 % chol_Sigma DxD chol(Sigma). Sigma is the prior covariance of xx
508 % or:
509 % prior_sample Dx1 single sample from N(0, Sigma)
510 %
511 % log_like_fn @fn log_like_fn(xx, varargin{:}) returns 1x1 log likelihood
512 %
513 % Optional inputs:
514 % cur_log_like 1x1 log_like_fn(xx, varargin{:}) of initial vector.
515 % You can omit this argument or pass [].
516 % angle_range 1x1 Default 0: explore whole ellipse with break point at
517 % first rejection. Set in (0,2*pi] to explore a bracket of
518 % the specified width centred uniformly at random.
519 % You can omit this argument or pass [].
520 % varargin - any additional arguments are passed to log_like_fn
521 %
522 % Outputs:
523 % xx Dx1 (size matches input) perturbed vector
524 % cur_log_like 1x1 log_like_fn(xx, varargin{:}) of final vector
525
526 % Iain Murray, September 2009
527 % Tweak to interface and documentation, September 2010
528
529 % Reference:
530 % Elliptical slice sampling
531 % Iain Murray, Ryan Prescott Adams and David J.C. MacKay.
532 % The Proceedings of the 13th International Conference on Artificial
533 % Intelligence and Statistics (AISTATS), JMLR W&CP 9:541-548, 2010.
534
535 D = numel(xx);
536 if (nargin < 4) || isempty(cur_log_like)
537 cur_log_like = log_like_fn(xx, varargin{:});
538 end
539 if (nargin < 5) || isempty(angle_range)
540 angle_range = 0;
541 end
542
543 % Set up the ellipse and the slice threshold
544 if numel(prior) == D
545 % User provided a prior sample:
546 nu = reshape(prior, size(xx));
547 else
548 % User specified Cholesky of prior covariance:
549 if ~isequal(size(prior), [D D])
550 error('Prior must be given by a D-element sample or DxD chol(Sigma)');
551 end
552 nu = reshape(prior'*randn(D, 1), size(xx));
553 end
554 hh = log(rand) + cur_log_like;
555
556 % Set up a bracket of angles and pick a first proposal.
557 % "phi = (theta'-theta)" is a change in angle.
558 if angle_range <= 0
559 % Bracket whole ellipse with both edges at first proposed point
560 phi = rand*2*pi;
561 phi_min = phi - 2*pi;
562 phi_max = phi;
563 else
564 % Randomly center bracket on current point
565 phi_min = -angle_range*rand;
566 phi_max = phi_min + angle_range;
567 phi = rand*(phi_max - phi_min) + phi_min;
568 end
569
570 % Slice sampling loop
571 while true
572 % Compute xx for proposed angle difference and check if it's on the slice
573 xx_prop = xx*cos(phi) + nu*sin(phi);
574 cur_log_like = log_like_fn(xx_prop, varargin{:});
575 if cur_log_like > hh
576 % New point is on slice, ** EXIT LOOP **
577 break;
578 end
579 % Shrink slice to rejected point
580 if phi > 0
581 phi_max = phi;
582 elseif phi < 0
583 phi_min = phi;
584 else
585 error('BUG DETECTED: Shrunk to current position and still not acceptable.');
586 end
587 % Propose new angle difference
588 phi = rand*(phi_max - phi_min) + phi_min;
589 end
590 xx = xx_prop;
591 */
592
593 }