Published
Edited
Apr 13, 2021
1 fork
Importers
7 stars
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
/*
* p: position
* q: momentum
* epsilon: step size
*/
leapfrog_step = function(p, q, epsilon, negative_gradient) {
q = math.add(q, math.multiply(epsilon / 2, negative_gradient(p)));
p = math.add(p, math.multiply(epsilon, q));
q = math.add(q, math.multiply(epsilon / 2, negative_gradient(p)));
return ({ position: p, momentum: q });
}
Insert cell
Insert cell
leapfrog = function(steps, epsilon, log_density, gradient_log_density, p_init, q_init) {
const negative_log_density = (x) => math.multiply(-1, log_density(x));
const negative_gradient_log_density = (x) => math.multiply(-1, gradient_log_density(x));
// Calculate initial kinetic and potential energy
const K0 = math.sum(q_init.map((d) => Math.pow(d, 2))) / 2;
const P0 = negative_log_density(p_init);

const K = [K0];
const P = [P0];
const p = [p_init];
const q = [q_init];

// Run leapfrog integrator
for(let step = 1; step < steps; step++) {
// Apply leapfrog integration step to get next values
// for theta, momentum
const next_step = leapfrog_step(p[step - 1], q[step - 1], epsilon, negative_gradient_log_density);
p[step] = next_step.position;
q[step] = next_step.momentum;
// Calculate kinetic and potential energy
K[step] = math.sum(q[step].map((d) => Math.pow(d, 2))) / 2;
P[step] = negative_log_density(p[step]);
}
return ({
K, P,
p,
q,
divergent: P[P.length - 1] > 10000
});
}
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more