Debian Codegraph @

src/dr/evomodel/coalescent/operators/GMRFMultilocusSkyrideBlockUpdateOperator.java

raw symbols SCIP
1 /*
2 * GMRFMultilocusSkyrideBlockUpdateOperator.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.coalescent.operators;
27
28 import dr.evomodel.coalescent.GMRFMultilocusSkyrideLikelihood;
29 import dr.evomodelxml.coalescent.operators.GMRFSkyrideBlockUpdateOperatorParser;
30 import dr.inference.model.MatrixParameter;
31 import dr.inference.model.Parameter;
32 import dr.inference.operators.*;
33 import dr.math.MathUtils;
34 import no.uib.cipr.matrix.*;
35
36 import java.util.List;
37 import java.util.logging.Logger;
38
39 /* A Metropolis-Hastings operator to update the log population sizes and precision parameter jointly under a Gaussian Markov random field prior
40 *
41 * @author Erik Bloomquist
42 * @author Marc Suchard
43 * @author Mandev Gill
44 * @version $Id: GMRFMultilocusSkylineBlockUpdateOperator.java,v 1.5 2007/03/20 11:26:49 msuchard Exp $
45 */
46 public class GMRFMultilocusSkyrideBlockUpdateOperator extends AbstractAdaptableOperator {
47
48 private static boolean FAIL_SILENTLY = true;
49
50 private double scaleFactor;
51 private double lambdaScaleFactor;
52 private int fieldLength;
53
54 private int maxIterations;
55 private double stopValue;
56
57 private Parameter popSizeParameter;
58 private Parameter precisionParameter;
59 private Parameter lambdaParameter;
60 private List<Parameter> betaParameter;
61 private List<MatrixParameter> covariates;
62
63 GMRFMultilocusSkyrideLikelihood gmrfField;
64
65 private double[] zeros;
66
67 public GMRFMultilocusSkyrideBlockUpdateOperator(GMRFMultilocusSkyrideLikelihood gmrfLikelihood,
68 double weight, AdaptationMode mode, double scaleFactor,
69 int maxIterations, double stopValue) {
70 super(mode);
71 gmrfField = gmrfLikelihood;
72 popSizeParameter = gmrfLikelihood.getPopSizeParameter();
73 precisionParameter = gmrfLikelihood.getPrecisionParameter();
74 lambdaParameter = gmrfLikelihood.getLambdaParameter();
75 betaParameter = gmrfLikelihood.getBetaListParameter();
76 covariates = gmrfLikelihood.getCovariates();
77
78 this.scaleFactor = scaleFactor;
79 lambdaScaleFactor = 0.0;
80 fieldLength = popSizeParameter.getDimension();
81
82 this.maxIterations = maxIterations;
83 this.stopValue = stopValue;
84 setWeight(weight);
85
86 zeros = new double[fieldLength];
87 }
88
89 private double getNewLambda(double currentValue, double lambdaScale) {
90 double a = MathUtils.nextDouble() * lambdaScale - lambdaScale / 2;
91 double b = currentValue + a;
92 if (b > 1)
93 b = 2 - b;
94 if (b < 0)
95 b = -b;
96
97 return b;
98 }
99
100 private double getNewPrecision(double currentValue, double scaleFactor) {
101 double length = scaleFactor - 1 / scaleFactor;
102 double returnValue;
103
104
105 if (scaleFactor == 1)
106 return currentValue;
107 if (MathUtils.nextDouble() < length / (length + 2 * Math.log(scaleFactor))) {
108 returnValue = (1 / scaleFactor + length * MathUtils.nextDouble()) * currentValue;
109 } else {
110 returnValue = Math.pow(scaleFactor, 2.0 * MathUtils.nextDouble() - 1) * currentValue;
111 }
112
113 return returnValue;
114 }
115
116 public DenseVector getMultiNormalMean(DenseVector CanonVector, BandCholesky Cholesky) {
117
118 DenseVector tempValue = new DenseVector(zeros);
119 DenseVector Mean = new DenseVector(zeros);
120
121 UpperTriangBandMatrix CholeskyUpper = Cholesky.getU();
122
123 // Assume Cholesky factorization of the precision matrix Q = LL^T
124
125 // 1. Solve L\omega = b
126
127 CholeskyUpper.transSolve(CanonVector, tempValue);
128
129 // 2. Solve L^T \mu = \omega
130
131 CholeskyUpper.solve(tempValue, Mean);
132
133 return Mean;
134 }
135
136 public DenseVector getMultiNormal(DenseVector StandNorm, DenseVector Mean, BandCholesky Cholesky) {
137
138 DenseVector returnValue = new DenseVector(zeros);
139
140 UpperTriangBandMatrix CholeskyUpper = Cholesky.getU();
141
142 // 3. Solve L^T v = z
143
144 CholeskyUpper.solve(StandNorm, returnValue);
145
146 // 4. Return x = \mu + v
147
148 returnValue.add(Mean);
149
150 return returnValue;
151 }
152
153
154 public static DenseVector getMultiNormal(DenseVector Mean, UpperSPDDenseMatrix Variance) {
155 int length = Mean.size();
156 DenseVector tempValue = new DenseVector(length);
157 DenseVector returnValue = new DenseVector(length);
158 UpperSPDDenseMatrix ab = Variance.copy();
159
160 for (int i = 0; i < returnValue.size(); i++)
161 tempValue.set(i, MathUtils.nextGaussian());
162
163 DenseCholesky chol = new DenseCholesky(length, true);
164 chol.factor(ab);
165
166 UpperTriangDenseMatrix x = chol.getU();
167
168 x.transMult(tempValue, returnValue);
169 returnValue.add(Mean);
170 return returnValue;
171 }
172
173
174 public static double logGeneralizedDeterminant(UpperTriangBandMatrix Matrix) {
175 double returnValue = 0;
176
177 for (int i = 0; i < Matrix.numColumns(); i++) {
178 if (Matrix.get(i, i) > 0.0000001) {
179 returnValue += Math.log(Matrix.get(i, i));
180 }
181 }
182
183 return returnValue;
184 }
185
186 public DenseVector getZBeta(List<MatrixParameter> covariates, List<Parameter> beta){
187
188 DenseVector temporaryVect = new DenseVector(fieldLength);
189
190 // TODO: Update for covariateMatrix block as well !!!
191
192 if(covariates != null) {
193 // DenseVector currentBeta = new DenseVector(beta.getParameterValues());
194 DenseVector currentBeta = new DenseVector(beta.size());
195 for(int i =0; i < beta.size(); i++){
196 currentBeta.set(i, beta.get(i).getParameterValue(0));
197 }
198
199 for (int i = 0; i < covariates.size(); i++) {
200 for (int j = 0; j < covariates.get(i).getColumnDimension(); j++) {
201 temporaryVect.set(j, covariates.get(i).getParameterValue(0, j) * currentBeta.get(i));
202 }
203 }
204 return temporaryVect;
205 }else{
206 return temporaryVect.zero();
207 }
208 }
209
210 public DenseVector newtonRaphson(double[] data1, double[] data2, DenseVector currentGamma,
211 SymmTridiagMatrix proposedQ, DenseVector ZBeta) {
212 return newNewtonRaphson(data1, data2, currentGamma, proposedQ, maxIterations, stopValue, ZBeta);
213 }
214
215 public static DenseVector newNewtonRaphson(double[] data1, double[] data2, DenseVector currentGamma, SymmTridiagMatrix proposedQ,
216 int maxIterations, double stopValue, DenseVector ZBeta) {
217
218 DenseVector iterateGamma = currentGamma.copy();
219 DenseVector tempValue = currentGamma.copy();
220
221 int numberIterations = 0;
222
223
224 while (gradient(data1, data2, iterateGamma, proposedQ, ZBeta).norm(Vector.Norm.Two) > stopValue) {
225 try {
226 jacobian(data2, iterateGamma, proposedQ).solve(gradient(data1, data2, iterateGamma, proposedQ, ZBeta), tempValue);
227 } catch (no.uib.cipr.matrix.MatrixNotSPDException e) {
228 if (FAIL_SILENTLY) {
229 // this replicates the old behaviour of throwing an OperatorFailedException and rejecting the move.
230 return null;
231 }
232 Logger.getLogger("dr.evomodel.coalescent.operators.GMRFMultilocusSkyrideBlockUpdateOperator").fine("Newton-Raphson F");
233 throw new RuntimeException("Newton Raphson algorithm did not converge within " + maxIterations + " step to a norm less than " + stopValue + "\n" +
234 "Try starting BEAST with a more accurate initial tree.");
235 } catch (no.uib.cipr.matrix.MatrixSingularException e) {
236 if (FAIL_SILENTLY) {
237 // this replicates the old behaviour of throwing an OperatorFailedException and rejecting the move.
238 return null;
239 }
240 Logger.getLogger("dr.evomodel.coalescent.operators.GMRFMultilocusSkyrideBlockUpdateOperator").fine("Newton-Raphson F");
241 throw new RuntimeException("Newton Raphson algorithm did not converge within " + maxIterations + " step to a norm less than " + stopValue + "\n" +
242 "Try starting BEAST with a more accurate initial tree.");
243 }
244
245 iterateGamma.add(tempValue);
246 numberIterations++;
247
248 if (numberIterations > maxIterations) {
249 if (FAIL_SILENTLY) {
250 // this replicates the old behaviour of throwing an OperatorFailedException and rejecting the move.
251 return null;
252 }
253 Logger.getLogger("dr.evomodel.coalescent.operators.GMRFMultilocusSkyrideBlockUpdateOperator").fine("Newton-Raphson F");
254 throw new RuntimeException("Newton Raphson algorithm did not converge within " + maxIterations + " step to a norm less than " + stopValue + "\n" +
255 "Try starting BEAST with a more accurate initial tree.");
256 }
257 }
258
259 Logger.getLogger("dr.evomodel.coalescent.operators.GMRFMultilocusSkyrideBlockUpdateOperator").fine("Newton-Raphson S");
260 return iterateGamma;
261
262 }
263
264 private static DenseVector gradient(double[] data1, double[] data2, DenseVector value,
265 SymmTridiagMatrix Q, DenseVector ZBeta) {
266
267 DenseVector returnValue = new DenseVector(value.size());
268 DenseVector returnValueCov = new DenseVector(ZBeta.size());
269 Q.mult(value, returnValue);
270 //check this
271 Q.mult(ZBeta, returnValueCov);
272 for (int i = 0; i < value.size(); i++) {
273 returnValue.set(i, -returnValue.get(i) +returnValueCov.get(i) - data1[i] + data2[i] * Math.exp(-value.get(i)));
274 }
275 return returnValue;
276 }
277
278
279 private static SPDTridiagMatrix jacobian(double[] data2, DenseVector value, SymmTridiagMatrix Q) {
280 SPDTridiagMatrix jacobian = new SPDTridiagMatrix(Q, true);
281 for (int i = 0, n = value.size(); i < n; i++) {
282 jacobian.set(i, i, jacobian.get(i, i) + Math.exp(-value.get(i)) * data2[i]);
283 }
284 return jacobian;
285 }
286
287 public double doOperation() {
288
289 double currentPrecision = precisionParameter.getParameterValue(0);
290 double proposedPrecision = this.getNewPrecision(currentPrecision, scaleFactor);
291
292 double currentLambda = this.lambdaParameter.getParameterValue(0);
293 double proposedLambda = this.getNewLambda(currentLambda, lambdaScaleFactor);
294
295 precisionParameter.setParameterValue(0, proposedPrecision);
296 lambdaParameter.setParameterValue(0, proposedLambda);
297
298 DenseVector currentGamma = new DenseVector(gmrfField.getPopSizeParameter().getParameterValues());
299 DenseVector proposedGamma;
300
301 SymmTridiagMatrix currentQ = gmrfField.getStoredScaledWeightMatrix(currentPrecision, currentLambda);
302 SymmTridiagMatrix proposedQ = gmrfField.getScaledWeightMatrix(proposedPrecision, proposedLambda);
303
304 double[] wNative = gmrfField.getSufficientStatistics();
305 double[] numCoalEv = gmrfField.getNumCoalEvents();
306
307 UpperSPDBandMatrix forwardQW = new UpperSPDBandMatrix(proposedQ, 1);
308 UpperSPDBandMatrix backwardQW = new UpperSPDBandMatrix(currentQ, 1);
309
310 BandCholesky forwardCholesky = new BandCholesky(wNative.length, 1, true);
311 BandCholesky backwardCholesky = new BandCholesky(wNative.length, 1, true);
312
313 DenseVector diagonal1 = new DenseVector(fieldLength);
314 DenseVector diagonal2 = new DenseVector(fieldLength);
315 DenseVector diagonal3 = new DenseVector(fieldLength);
316 DenseVector ZBetaVector = getZBeta(covariates, betaParameter);
317 DenseVector QZBetaProp = new DenseVector(fieldLength);
318 DenseVector QZBetaCurrent = new DenseVector(fieldLength);
319 forwardQW.mult(ZBetaVector, QZBetaProp);
320 backwardQW.mult(ZBetaVector, QZBetaCurrent);
321
322 DenseVector modeForward = newtonRaphson(numCoalEv, wNative, currentGamma, proposedQ.copy(), ZBetaVector);
323
324 if (modeForward == null) {
325 // used to pass on an OperatorFailedException
326 return Double.NEGATIVE_INFINITY;
327 }
328
329 for (int i = 0; i < fieldLength; i++) {
330 diagonal1.set(i, wNative[i] * Math.exp(-modeForward.get(i)));
331 diagonal2.set(i, modeForward.get(i) + 1);
332
333 forwardQW.set(i, i, diagonal1.get(i) + forwardQW.get(i, i));
334 //diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - 1);
335 diagonal1.set(i, QZBetaProp.get(i) + diagonal1.get(i) * diagonal2.get(i) - numCoalEv[i]);
336 }
337
338 forwardCholesky.factor(forwardQW.copy());
339
340 DenseVector forwardMean = getMultiNormalMean(diagonal1, forwardCholesky);
341
342 DenseVector stand_norm = new DenseVector(zeros);
343
344 for (int i = 0; i < zeros.length; i++)
345 stand_norm.set(i, MathUtils.nextGaussian());
346
347 proposedGamma = getMultiNormal(stand_norm, forwardMean, forwardCholesky);
348
349 /*
350 double hRatio = 0;
351 for (int i = 0; i < fieldLength; i++) {
352 diagonal1.set(i, proposedGamma.get(i) - forwardMean.get(i));
353 }
354 diagonal3.zero();
355 forwardQW.mult(diagonal1, diagonal3);
356
357 hRatio -= logGeneralizedDeterminant(forwardCholesky.getU() ) - 0.5 * diagonal1.dot(diagonal3);
358 */
359
360 for (int i = 0; i < fieldLength; i++)
361 popSizeParameter.setParameterValueQuietly(i, proposedGamma.get(i));
362
363 ((Parameter.Abstract) popSizeParameter).fireParameterChangedEvent();
364
365
366 double hRatio = 0;
367
368 diagonal1.zero();
369 diagonal2.zero();
370 diagonal3.zero();
371
372 DenseVector modeBackward = newtonRaphson(numCoalEv, wNative, proposedGamma, currentQ.copy(), ZBetaVector);
373
374 if (modeBackward == null) {
375 // used to pass on an OperatorFailedException
376 return Double.NEGATIVE_INFINITY;
377 }
378
379 for (int i = 0; i < fieldLength; i++) {
380 diagonal1.set(i, wNative[i] * Math.exp(-modeBackward.get(i)));
381 diagonal2.set(i, modeBackward.get(i) + 1);
382
383 backwardQW.set(i, i, diagonal1.get(i) + backwardQW.get(i, i));
384 //diagonal1.set(i, diagonal1.get(i) * diagonal2.get(i) - 1);
385 diagonal1.set(i, QZBetaCurrent.get(i) + diagonal1.get(i) * diagonal2.get(i) - numCoalEv[i]);
386 }
387
388 backwardCholesky.factor(backwardQW.copy());
389
390 DenseVector backwardMean = getMultiNormalMean(diagonal1, backwardCholesky);
391
392 for (int i = 0; i < fieldLength; i++) {
393 diagonal1.set(i, currentGamma.get(i) - backwardMean.get(i));
394 }
395
396 backwardQW.mult(diagonal1, diagonal3);
397
398 hRatio += logGeneralizedDeterminant(backwardCholesky.getU()) - 0.5 * diagonal1.dot(diagonal3);
399 hRatio -= logGeneralizedDeterminant(forwardCholesky.getU() ) - 0.5 * stand_norm.dot(stand_norm);
400
401 return hRatio;
402 }
403
404 //MCMCOperator INTERFACE
405
406 public final String getOperatorName() {
407 return GMRFSkyrideBlockUpdateOperatorParser.BLOCK_UPDATE_OPERATOR;
408 }
409
410 public double getAdaptableParameter() {
411 // return Math.log(scaleFactor);
412 return Math.sqrt(scaleFactor - 1);
413 }
414
415 public void setAdaptableParameter(double value) {
416 // scaleFactor = Math.exp(value);
417 scaleFactor = 1 + value * value;
418 }
419
420 public double getRawParameter() {
421 return scaleFactor;
422 }
423
424 public double getScaleFactor() {
425 return scaleFactor;
426 }
427
428 public String getAdaptableParameterName() {
429 return "scaleFactor";
430 }
431
432
433 }
434