/ interactive_tutorials / mcmc_sonification
Sign in
interactive_tutorials / mcmc_sonification
mcmc_sonification / app / js / mixture.js
371 lines · 12.4 KBCodeBlameHistory
726adb6Listening for convergence: MCMC chains on a 2D mixture, sonifiedJeremy Magland 1// A 2D two-component normal mixture and four MCMC samplers, one step at a
2// time: a JavaScript port of mixture_mcmc.py (same model, same samplers, same
3// interface, in camelCase).
4//
5// p(θ) = ½ N(θ | m₁, Σ₁) + ½ N(θ | m₂, Σ₂), m₁ = (−μ/2, 0), m₂ = (μ/2, 0),
6// Σₖ = diag(σₖ) [[1, ρₖ], [ρₖ, 1]] diag(σₖ), σₖ = (σₖ₁, σₖ₂).
7//
8// const model = new NormalMixture2D({ mu: 4, sigma: [[1, 1], [1, 1]], rho: [0, 0], tau: 1 });
9// const s = new HMC(model, 0.2, { nSteps: 10, seed: 1 });
10// const theta = s.next(); // one step; also s.theta, s.proposal,
11// // s.accepted, s.acceptProb, s.nIter, ...
12// s.stepSize = 0.3; // retune at any time
13//
14// Points are [θ₁, θ₂] arrays. The random numbers come from a seeded
15// generator here, so a chain is reproducible in JavaScript, but not the same
16// numbers as NumPy's.
18const LOG_2PI = Math.log(2 * Math.PI);
20function positive(name, v) {
21 v = Number(v);
22 if (!(Number.isFinite(v) && v > 0)) throw new RangeError(`${name} must be in (0, inf); got ${v}`);
23 return v;
26function openUnit(name, v) {
27 v = Number(v);
28 if (!(v > -1 && v < 1)) throw new RangeError(`${name} must be in (-1, 1); got ${v}`);
29 return v;
32function closedUnit(name, v) {
33 v = Number(v);
34 if (!(v >= 0 && v <= 1)) throw new RangeError(`${name} must be in [0, 1]; got ${v}`);
35 return v;
38// ---- random numbers ---------------------------------------------------------
40// sfc32, seeded through splitmix32: uniform() in [0, 1), normal() standard
41// normal (Box-Muller, both values used).
42export class Rng {
43 constructor(seed = (Math.random() * 2 ** 32) >>> 0) {
44 let s = seed >>> 0;
45 const mix = () => {
46 s = (s + 0x9e3779b9) >>> 0;
47 let z = s;
48 z = Math.imul(z ^ (z >>> 16), 0x85ebca6b);
49 z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35);
50 return (z ^ (z >>> 16)) >>> 0;
51 };
52 this.a = mix(); this.b = mix(); this.c = mix(); this.d = mix();
53 this.spare = null;
54 for (let i = 0; i < 12; i++) this.uniform();
55 }
57 uniform() {
58 let { a, b, c, d } = this;
59 const t = (((a + b) >>> 0) + d) >>> 0;
60 d = (d + 1) >>> 0;
61 a = b ^ (b >>> 9);
62 b = (c + (c << 3)) >>> 0;
63 c = (c << 21) | (c >>> 11);
64 c = (c + t) >>> 0;
65 Object.assign(this, { a, b, c, d });
66 return t / 4294967296;
67 }
69 normal() {
70 if (this.spare !== null) {
71 const z = this.spare;
72 this.spare = null;
73 return z;
74 }
75 const u = 1 - this.uniform(); // (0, 1]
76 const r = Math.sqrt(-2 * Math.log(u));
77 const a = 2 * Math.PI * this.uniform();
78 this.spare = r * Math.sin(a);
79 return r * Math.cos(a);
80 }
82 normal2() { return [this.normal(), this.normal()]; }
85// ---- the model ----------------------------------------------------------------
87export class NormalMixture2D {
88 // mu: distance between the means; sigma: [[σ₁₁, σ₁₂], [σ₂₁, σ₂₂]], per
89 // component and axis; rho: [ρ₁, ρ₂]; tau: radius of the circle the chains
90 // start on
91 constructor({ mu = 4, sigma = [[1, 1], [1, 1]], rho = [0, 0], tau = 1 } = {}) {
92 this.set({ mu, sigma, rho, tau });
93 }
95 // validate and set any of mu, sigma, rho, tau; the next step uses them
96 set({ mu = this.mu, sigma = this.sigma, rho = this.rho, tau = this.tau } = {}) {
97 this.mu = positive('mu', mu);
98 this.sigma = sigma.map((s, k) => s.map((v, j) => positive(`sigma[${k}][${j}]`, v)));
99 this.rho = rho.map((r, k) => openUnit(`rho[${k}]`, r));
100 this.tau = positive('tau', tau);
101 const h = this.mu / 2;
102 this.means = [[-h, 0], [h, 0]];
103 // per component: covariance, precision and log(½ · normalization)
104 this.comps = this.sigma.map(([s1, s2], k) => {
105 const r = this.rho[k];
106 const c11 = s1 * s1, c12 = r * s1 * s2, c22 = s2 * s2;
107 const det = c11 * c22 - c12 * c12;
108 return {
109 mx: this.means[k][0], my: this.means[k][1],
110 c11, c12, c22,
111 p11: c22 / det, p12: -c12 / det, p22: c11 / det,
112 logNorm: -LOG_2PI - 0.5 * Math.log(det) + Math.log(0.5),
113 };
114 });
115 return this;
116 }
118 logDensity([x, y]) {
119 const [a, b] = this.comps.map((c) => {
120 const dx = x - c.mx, dy = y - c.my;
121 return c.logNorm - 0.5 * (dx * (c.p11 * dx + c.p12 * dy) + dy * (c.p12 * dx + c.p22 * dy));
122 });
123 const m = Math.max(a, b);
124 if (m === -Infinity) return -Infinity;
125 return m + Math.log(Math.exp(a - m) + Math.exp(b - m));
126 }
128 // ∇ log p: minus the posterior-weighted P_k (θ − m_k)
129 gradLogDensity([x, y]) {
130 let gx = 0, gy = 0;
131 const lp = [], pd = [];
132 for (const c of this.comps) {
133 const dx = x - c.mx, dy = y - c.my;
134 const px = c.p11 * dx + c.p12 * dy, py = c.p12 * dx + c.p22 * dy;
135 lp.push(c.logNorm - 0.5 * (dx * px + dy * py));
136 pd.push([px, py]);
137 }
138 const m = Math.max(lp[0], lp[1]);
139 const w0 = Math.exp(lp[0] - m), w1 = Math.exp(lp[1] - m);
140 const s = w0 + w1;
141 gx = -(w0 * pd[0][0] + w1 * pd[1][0]) / s;
142 gy = -(w0 * pd[0][1] + w1 * pd[1][1]) / s;
143 return [gx, gy];
144 }
146 initialPoint(rng) {
147 const a = 2 * Math.PI * rng.uniform();
148 return [this.tau * Math.cos(a), this.tau * Math.sin(a)];
149 }
151 // leapfrog / Langevin linear stability bound: 2 × the smallest principal std
152 maxStableStepSize() {
153 const lmin = Math.min(...this.comps.map(({ c11, c12, c22 }) =>
154 (c11 + c22) / 2 - Math.sqrt(((c11 - c22) / 2) ** 2 + c12 * c12)));
155 return 2 * Math.sqrt(lmin);
156 }
158 // the exact marginal density of θ₁ (each component's is N(mₖ₁, σₖ₁²))
159 marginal1(x) {
160 let p = 0;
161 for (const c of this.comps) {
162 const s = Math.sqrt(c.c11);
163 p += 0.5 * Math.exp(-0.5 * ((x - c.mx) / s) ** 2) / (s * Math.sqrt(2 * Math.PI));
164 }
165 return p;
166 }
168 // ground truth: mean 0 and Cov = ½ Σₖ (Σₖ + mₖ mₖᵀ); P(θ₁ > 0)
169 truth() {
170 const cov = [[0, 0], [0, 0]];
171 for (const c of this.comps) {
172 cov[0][0] += 0.5 * (c.c11 + c.mx * c.mx);
173 cov[0][1] += 0.5 * (c.c12 + c.mx * c.my);
174 cov[1][1] += 0.5 * (c.c22 + c.my * c.my);
175 }
176 cov[1][0] = cov[0][1];
177 const erf = (z) => {
178 // Abramowitz and Stegun 7.1.26 (|error| < 1.5e-7)
179 const t = 1 / (1 + 0.3275911 * Math.abs(z));
180 const y = 1 - t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))) * Math.exp(-z * z);
181 return z >= 0 ? y : -y;
182 };
183 const right = this.comps.reduce((acc, c) => acc + 0.5 * 0.5 * (1 + erf(c.mx / Math.sqrt(2 * c.c11))), 0);
184 return { mean: [0, 0], cov, right };
185 }
188// ---- integrator ---------------------------------------------------------------
190// n leapfrog steps of size eps from (x, p), unit mass; path (optional) gets
191// each new position
192export function leapfrog(model, x, p, eps, n, path = null) {
193 let g = model.gradLogDensity(x);
194 p = [p[0] + 0.5 * eps * g[0], p[1] + 0.5 * eps * g[1]];
195 for (let i = 0; i < n; i++) {
196 x = [x[0] + eps * p[0], x[1] + eps * p[1]];
197 if (path) path.push(x);
198 g = model.gradLogDensity(x);
199 if (i < n - 1) p = [p[0] + eps * g[0], p[1] + eps * g[1]];
200 }
201 return [x, [p[0] + 0.5 * eps * g[0], p[1] + 0.5 * eps * g[1]]];
204export const hamiltonian = (model, x, p) => -model.logDensity(x) + 0.5 * (p[0] * p[0] + p[1] * p[1]);
206// ---- samplers -----------------------------------------------------------------
208// next() advances one step and returns a copy of theta. After each step:
209// theta, proposal, accepted, acceptProb, nIter, nAccept, acceptanceRate.
210export class Sampler {
211 constructor(model, stepSize, { theta0 = null, seed } = {}) {
212 this.model = model;
213 this.stepSize = stepSize;
214 this.rng = new Rng(seed);
215 this.reset(theta0);
216 }
218 get stepSize() { return this._eps; }
219 set stepSize(v) { this._eps = positive('stepSize', v); }
221 reset(theta0 = null) {
222 this.theta = theta0 === null ? this.model.initialPoint(this.rng) : [Number(theta0[0]), Number(theta0[1])];
223 this.proposal = this.theta.slice();
224 this.accepted = null;
225 this.acceptProb = NaN;
226 this.nIter = this.nAccept = 0;
227 }
229 get acceptanceRate() { return this.nIter ? this.nAccept / this.nIter : NaN; }
231 next() {
232 this._step();
233 this.nIter++;
234 this.nAccept += this.accepted ? 1 : 0;
235 return this.theta.slice();
236 }
238 draws(n) { return Array.from({ length: n }, () => this.next()); }
240 // set acceptProb and accepted; NaN or −inf ratios reject
241 _metropolis(logRatio) {
242 if (!Number.isFinite(logRatio)) logRatio = logRatio === Infinity ? Infinity : -Infinity;
243 this.acceptProb = Math.exp(Math.min(0, logRatio));
244 this.accepted = Math.log(this.rng.uniform()) < logRatio;
245 return this.accepted;
246 }
249// θ' = θ + ε z, z ~ N(0, I); Metropolis accept
250export class RandomWalkMetropolis extends Sampler {
251 _step() {
252 const lp = (x) => this.model.logDensity(x);
253 const [z1, z2] = this.rng.normal2();
254 this.proposal = [this.theta[0] + this.stepSize * z1, this.theta[1] + this.stepSize * z2];
255 if (this._metropolis(lp(this.proposal) - lp(this.theta))) this.theta = this.proposal;
256 }
259// θ' = θ + (ε²/2) ∇ log p(θ) + ε z.
260// adjust false: unadjusted Langevin (ULA), always moves (biased, may
261// diverge); a non-finite proposal is not taken and sets diverged.
262// adjust true: MALA, with the Metropolis-Hastings correction.
263export class Langevin extends Sampler {
264 constructor(model, stepSize, { adjust = true, ...rest } = {}) {
265 super(model, stepSize, rest);
266 this.adjust = adjust;
267 }
269 get adjust() { return this._adjust; }
270 set adjust(v) { this._adjust = Boolean(v); }
272 reset(theta0 = null) {
273 super.reset(theta0);
274 this.diverged = false;
275 }
277 _mean(x) {
278 const g = this.model.gradLogDensity(x);
279 const h = 0.5 * this.stepSize ** 2;
280 return [x[0] + h * g[0], x[1] + h * g[1]];
281 }
283 _logQ(to, frm) {
284 const m = this._mean(frm);
285 const dx = to[0] - m[0], dy = to[1] - m[1];
286 return (-0.5 * (dx * dx + dy * dy)) / this.stepSize ** 2;
287 }
289 _step() {
290 const x = this.theta;
291 const m = this._mean(x);
292 const [z1, z2] = this.rng.normal2();
293 const y = [m[0] + this.stepSize * z1, m[1] + this.stepSize * z2];
294 this.proposal = y;
295 if (!this.adjust) {
296 this.diverged = !(Number.isFinite(y[0]) && Number.isFinite(y[1]));
297 this.accepted = !this.diverged;
298 this.acceptProb = 1;
299 } else {
300 const lp = (v) => this.model.logDensity(v);
301 this._metropolis(lp(y) - lp(x) + this._logQ(x, y) - this._logQ(y, x));
302 }
303 if (this.accepted) this.theta = y;
304 }
307// One leapfrog step per iteration with partial momentum refresh,
308// p ← √(1 − γ) p + √γ z (γ = 1 is MALA); on rejection the momentum is
309// negated (Horowitz 1991).
310export class GeneralizedHMC extends Sampler {
311 constructor(model, stepSize, { gamma = 0.1, ...rest } = {}) {
312 super(model, stepSize, rest);
313 this.gamma = gamma;
314 }
316 get gamma() { return this._gamma; }
317 set gamma(v) { this._gamma = closedUnit('gamma', v); }
319 reset(theta0 = null) {
320 super.reset(theta0);
321 this.momentum = this.rng.normal2();
322 }
324 _step() {
325 const g = this.gamma;
326 const [z1, z2] = this.rng.normal2();
327 const a = Math.sqrt(1 - g), b = Math.sqrt(g);
328 const p = [a * this.momentum[0] + b * z1, a * this.momentum[1] + b * z2];
329 const [x1, p1] = leapfrog(this.model, this.theta, p, this.stepSize, 1);
330 this.proposal = x1;
331 const h0 = hamiltonian(this.model, this.theta, p);
332 const h1 = hamiltonian(this.model, x1, p1);
333 if (this._metropolis(h0 - h1)) {
334 this.theta = x1;
335 this.momentum = p1;
336 } else {
337 this.momentum = [-p[0], -p[1]];
338 }
339 }
342// L leapfrog steps, unit mass, full momentum refresh. path holds the L + 1
343// positions of the last trajectory (accepted or not).
344export class HMC extends Sampler {
345 constructor(model, stepSize, { nSteps = 10, ...rest } = {}) {
346 super(model, stepSize, rest);
347 this.nSteps = nSteps;
348 }
350 get nSteps() { return this._L; }
351 set nSteps(v) {
352 if (!Number.isInteger(Number(v)) || v < 1) throw new RangeError(`nSteps must be a positive integer; got ${v}`);
353 this._L = Number(v);
354 }
356 reset(theta0 = null) {
357 super.reset(theta0);
358 this.path = [this.theta.slice()];
359 }
361 _step() {
362 const p = this.rng.normal2();
363 const path = [this.theta];
364 const [x1, p1] = leapfrog(this.model, this.theta, p, this.stepSize, this.nSteps, path);
365 this.path = path;
366 this.proposal = x1;
367 const h0 = hamiltonian(this.model, this.theta, p);
368 const h1 = hamiltonian(this.model, x1, p1);
369 if (this._metropolis(h0 - h1)) this.theta = x1;
370 }
↑↓ move↵openescclose