Debian Codegraph @

src/dr/inference/operators/hmc/NewBouncyParticleOperator.java

raw symbols SCIP
1 /*
2 * NewHamiltonianMonteCarloOperator.java
3 *
4 * Copyright (c) 2002-2017 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.hmc;
27
28 import dr.evolution.tree.Tree;
29 import dr.evolution.tree.TreeTrait;
30 import dr.evomodel.treedatalikelihood.TreeDataLikelihood;
31 import dr.evomodel.treedatalikelihood.continuous.ContinuousDataLikelihoodDelegate;
32 import dr.evomodel.treedatalikelihood.continuous.MultivariateTraitDebugUtilities;
33 import dr.evomodel.treedatalikelihood.preorder.TipFullConditionalDistributionDelegate;
34 import dr.evomodel.treedatalikelihood.preorder.TipGradientViaFullConditionalDelegate;
35 import dr.inference.model.Parameter;
36 import dr.inference.operators.AdaptationMode;
37 import dr.inference.operators.SimpleMCMCOperator;
38 import dr.math.MathUtils;
39 import dr.math.distributions.NormalDistribution;
40
41 /**
42 * @author Zhenyu Zhang
43 * @author Marc A. Suchard
44 */
45
46 public class NewBouncyParticleOperator extends SimpleMCMCOperator {
47
48 private double t; //todo randomize the length a little bit.
49 private double[] v;
50 private double[] location;
51 private double[] phi_w;
52 private double[] mu;
53
54 final NormalDistribution drawDistribution;
55
56 // final GradientWrtParameterProvider gradientProvider;
57 final double[][] precisionMatrix;
58 // Something that returns the conditional distribution
59 protected Parameter parameter;
60 final double[][] sigma0; //np*np
61
62 private final TreeDataLikelihood treeDataLikelihood;
63 private final ContinuousDataLikelihoodDelegate likelihoodDelegate;
64
65 private final TreeTrait gradientProvider; //already the gradient, not really a provider.
66 private final TreeTrait densityProvider;
67 private final Tree tree;
68
69 //gradient/densityprovider is for each taxa? so precisionMatrix not necessary?( densityprovider is enough) divide mu and p matrix from the compact form?
70 // sigma0 is matrix np by np?
71
72
73
74 public NewBouncyParticleOperator(AdaptationMode mode, double weight,
75 TreeDataLikelihood treeDataLikelihood,
76 ContinuousDataLikelihoodDelegate likelihoodDelegate,
77 String traitName, Parameter parameter, double drawVariance) {
78
79 setWeight(weight);
80
81 this.treeDataLikelihood = treeDataLikelihood;
82 this.likelihoodDelegate = likelihoodDelegate;
83
84 this.parameter = parameter;
85
86 this.drawDistribution = new NormalDistribution(0, Math.sqrt(drawVariance));
87
88 location = getInitialPosition();
89 phi_w = getPhiw();
90 mu = getMU();
91
92
93 String gradientName = TipGradientViaFullConditionalDelegate.getName(traitName);
94 if (treeDataLikelihood.getTreeTrait(gradientName) == null) {
95 likelihoodDelegate.addFullConditionalGradientTrait(traitName);
96 }
97 gradientProvider = treeDataLikelihood.getTreeTrait(gradientName);
98 assert (gradientProvider != null);
99
100 String fcdName = TipFullConditionalDistributionDelegate.getName(traitName);
101 if (treeDataLikelihood.getTreeTrait(fcdName) == null) {
102 likelihoodDelegate.addFullConditionalDensityTrait(traitName);
103 }
104 densityProvider = treeDataLikelihood.getTreeTrait(fcdName);
105
106
107 assert (densityProvider != null);
108
109 this.tree = treeDataLikelihood.getTree();
110 this.precisionMatrix = likelihoodDelegate.getPrecisionParameter().getParameterAsMatrix();//todo: precison matrix for each species? (25*25?) not taking a taxon name?
111 this.sigma0 = getTreeVariance(); // //todo you only need the largest eigenvalue "Only ever call a very few # of times"
112
113 }
114
115 private double[][] getTreeVariance() {
116
117
118 double priorSampleSize = likelihoodDelegate.getRootProcessDelegate().getPseudoObservations();
119
120 return MultivariateTraitDebugUtilities.getTreeVariance(tree, 1.0,
121 /*Double.POSITIVE_INFINITY*/ priorSampleSize);
122 }
123
124 @Override
125 public String getOperatorName() {
126 return "Bouncy Particle operator";
127 }
128
129 @Override
130 public double doOperation() {
131
132 // Get all gradients; // in treeTipGradient why there is a "nTrait" that must be 1...??
133 //
134 // int offsetOutput = 0;
135 //
136 // for (int taxon = 0; taxon < nTaxa; ++taxon) {
137 // double[] taxonGradient = (double[]) gradientProvider.getTrait(tree, tree.getExternalNode(taxon));
138 // System.arraycopy(taxonGradient, 0, gradient, offsetOutput, taxonGradient.length);
139 // offsetOutput += taxonGradient.length;
140 // }
141
142 return 0.0;
143 }
144
145 private long count = 0;
146
147 private static final boolean DEBUG = false;
148
149
150 public double doOperation(double[] location, double[] v, double t, double[] phi_w) {
151
152
153 bpsOneStep();
154
155 return 0.0;
156 }
157
158 public void bpsOneStep() {
159
160
161 v = drawV(drawDistribution, location.length);
162
163
164 while (t > 0) {
165
166 double[] w = addArray(location, mu, true);
167 double[] phi_v = matrixMultiplier(precisionMatrix, v);
168 double w_phi_w = getDotProduct(w, phi_w);//todo multiple precision matrix should be a class.
169 double v_phi_w = getDotProduct(v, phi_w);//todo use a construct to store all of the temporary values.
170 double v_phi_v = getDotProduct(v, phi_v);
171
172 double tMin = Math.max(0.0, - v_phi_w/v_phi_v);
173
174 double U_min = energyProvider(phi_w, phi_v, w, tMin);
175
176
177 if( Double.isNaN(v_phi_w)){
178
179 System.exit(-99);
180 }
181 double bounceTime = getBounceTime(v_phi_v, v_phi_w, U_min, w_phi_w);
182
183 NewBouncyParticleOperator.TravelTime time_to_bdry = getTimeToBoundary(location, v);
184
185 bpsUpdate(time_to_bdry, bounceTime, t);
186
187
188 }
189
190
191 }
192
193 public double[][] getVectorizedPrecisionMatrix(){
194
195 int nTaxa = tree.getExternalNodeCount();
196 int dimTaxa = treeDataLikelihood.getDataLikelihoodDelegate().getTraitDim();
197
198 double[][] vectorizedPrecisionMatrix = new double[nTaxa][dimTaxa];
199
200 int offsetOutput = 0;
201
202 for (int taxon = 0; taxon < nTaxa; ++taxon) { //todo to finish. from online.
203
204 System.arraycopy(precisionMatrix, 0,vectorizedPrecisionMatrix,offsetOutput,dimTaxa);
205 offsetOutput += dimTaxa;
206
207 }
208
209 return vectorizedPrecisionMatrix;
210 }
211
212 public double[] getMU() { //todo combine getMU and getphiw and getVectorizedPrecisionMatrix
213
214 int nTaxa = tree.getExternalNodeCount();
215 int dimTaxa = treeDataLikelihood.getDataLikelihoodDelegate().getTraitDim();
216
217 double[] mu = new double[nTaxa * dimTaxa];
218
219 int offsetOutput = 0;
220
221 for (int taxon = 0; taxon < nTaxa; ++taxon) {
222
223 double[] tmp = (double[]) densityProvider.getTrait(tree, tree.getExternalNode(0));
224
225 // tmp: [0, ..., dim - 1] == mean
226 // tmp: [dim, ..., dim * (dim + 1) -1] == precision or tmp[dim] * precisionParameter
227
228 System.arraycopy(tmp, 0, mu, offsetOutput, dimTaxa);
229 offsetOutput += dimTaxa;
230 }
231
232 return mu;
233
234 }
235
236 public double[] getPhiw() { //todo check + or - ?
237
238 int offsetOutput = 0;
239 int nTaxa = tree.getExternalNodeCount();
240 int dimTaxa = treeDataLikelihood.getDataLikelihoodDelegate().getTraitDim();
241 double[] gradient = new double[nTaxa * dimTaxa];
242 //todo get rid of the code duplication to get gradient
243 for (int taxon = 0; taxon < nTaxa; ++taxon) {
244 double[] taxonGradient = (double[]) gradientProvider.getTrait(tree, tree.getExternalNode(taxon));
245 System.arraycopy(taxonGradient, 0, gradient, offsetOutput, taxonGradient.length);
246 offsetOutput += taxonGradient.length;
247 }
248 return gradient;
249 }
250
251 public void bpsUpdate(NewBouncyParticleOperator.TravelTime traveltime, double bouncetime, double timeRemain) {
252
253 if (timeRemain < Math.min(traveltime.minTime, bouncetime)) { //no event
254
255 location = addArray(location, getConstantVector(v, timeRemain), false);
256 t = 0.0;
257
258
259 } else if (traveltime.minTime <= bouncetime) { //against the boundary
260
261 location = addArray(location, getConstantVector(v, traveltime.minTime), false);
262 location[traveltime.minIndex] = 0.0;
263 v[traveltime.minIndex] = getConstantVector(v, -1.0)[traveltime.minIndex];
264 t -= traveltime.minTime;
265 phi_w = matrixMultiplier(precisionMatrix, addArray(location, mu, true)); //todo to deal with the duplicated code for updating phi_w
266
267
268 } else { //against the gradient
269
270 location = addArray(location, getConstantVector(v, bouncetime), false);
271 phi_w = matrixMultiplier(precisionMatrix,addArray(location, mu, true));
272 v = bounceAgainst(v, phi_w);
273 t -= bouncetime;
274
275 }
276
277 }
278
279 public double[] bounceAgainst(double[] v, double[] minusGrad) {
280
281 double[] finalV;
282 double[] verticalV;
283
284 verticalV = getConstantVector(minusGrad, getDotProduct(v, minusGrad)/getDotProduct(minusGrad, minusGrad));
285 finalV = addArray(v, getConstantVector(verticalV, -2.0), false);
286
287 return finalV;
288
289 }
290
291 public double getBounceTime(double v_phi_v, double v_phi_w, double U_min, double w_phi_w) {
292
293 double a = v_phi_v;
294 double b = 2 * v_phi_w;
295 double c = 2.0 * Math.log(1 - MathUtils.nextDouble()) - U_min + w_phi_w; //TODO CHCEK IF ROOT EXISTS
296
297 return (- b + Math.sqrt(b * b - 4 * a * c))/2/a;
298
299 }
300
301 public double energyProvider(double[] phi_w, double[] phi_v, double[] w, double t){
302
303 return getDotProduct(addArray(w, getConstantVector(v, t), false),
304 addArray(phi_w, getConstantVector(phi_v, t), false));
305
306 }
307
308 static double[] drawV(final NormalDistribution distribution, final int dim) {
309
310 double[] v = new double[dim];
311 for (int i = 0; i < dim; i++) {
312 v[i] = (Double) distribution.nextRandom();
313 }
314 return v;
315 }
316
317 public double[] matrixMultiplier(double[][] A, double[] B){
318
319 final int dim = B.length;
320 double[] mResult = new double[dim];
321
322 for (int i = 0; i < dim; i ++){
323 for (int j = 0; j< dim; j ++) {
324 mResult[i] += A[i][j] * B[j];
325 }
326
327 }
328 return mResult;
329 }
330
331 public NewBouncyParticleOperator.TravelTime getTimeToBoundary(double[] location, double[] v) {
332
333 double[] travelTime = elementWiseVectorDivisionAbsValue(location, v);
334
335 int index = 0;
336
337 double minTime = Double.MAX_VALUE;
338
339 for (int i = 0; i < travelTime.length; i ++) {
340 if (travelTime[i] != 0.0 && location[i] * v[i] < 0) {
341 if (travelTime[i] < minTime) {
342 index = i;
343 minTime = travelTime[i];
344 }
345 }
346 }
347
348 return new NewBouncyParticleOperator.TravelTime(travelTime, minTime, index);
349
350 }
351
352 public double[] elementWiseVectorDivisionAbsValue(double[] location, double[] y) {
353
354 final int dim = location.length;
355 double[] z = new double[dim];
356 for (int i = 0; i < dim; i++) {
357 z[i] = Math.abs(location[i] / y[i]); //todo make sure b[i] != 0
358 }
359 return z;
360 }
361
362 public static double[] addArray(double[] a, double[] b, boolean subtract) {
363
364 assert (a.length == b.length);
365 final int dim = a.length;
366
367 double result[] = new double[dim];
368 for (int i = 0; i < dim; i++) {
369 if(!subtract) {
370 result[i] = a[i] + b[i];
371 } else {
372 result[i] = a[i] - b[i];
373 }
374
375 }
376
377 return result;
378 }
379
380 public static double getDotProduct(double[] a, double[] b) { //todo get rid of code duplication
381
382 assert (a.length == b.length);
383 final int dim = a.length;
384
385 double total = 0.0;
386 for (int i = 0; i < dim; i++) {
387
388 total += a[i]*b[i];
389 }
390 return total;
391 }
392
393 public static double[] getConstantVector(double[] a, double c){
394
395 double[] cx = new double[a.length];
396 for (int i = 0; i < a.length; i ++){
397 cx[i] = a[i] * c;
398 }
399
400 return cx;
401 }
402
403 public class TravelTime {
404
405 double[] traveltime;
406 double minTime;
407 int minIndex;
408
409 public TravelTime (double[] traveltime, double minTime, int minIndex){
410 this.traveltime = traveltime;
411 this.minTime = minTime;
412 this.minIndex = minIndex;
413 }
414 }
415
416 public double[] getInitialPosition() {
417 return parameter.getParameterValues();
418 }
419
420 public double getT() {
421 //todo decompose the sigma0
422
423 return 1.0;
424 }
425
426 }