// A 2D two-component normal mixture and four MCMC samplers, one step at a // time: a JavaScript port of mixture_mcmc.py (same model, same samplers, same // interface, in camelCase). // // p(θ) = ½ N(θ | m₁, Σ₁) + ½ N(θ | m₂, Σ₂), m₁ = (−μ/2, 0), m₂ = (μ/2, 0), // Σₖ = diag(σₖ) [[1, ρₖ], [ρₖ, 1]] diag(σₖ), σₖ = (σₖ₁, σₖ₂). // // const model = new NormalMixture2D({ mu: 4, sigma: [[1, 1], [1, 1]], rho: [0, 0], tau: 1 }); // const s = new HMC(model, 0.2, { nSteps: 10, seed: 1 }); // const theta = s.next(); // one step; also s.theta, s.proposal, // // s.accepted, s.acceptProb, s.nIter, ... // s.stepSize = 0.3; // retune at any time // // Points are [θ₁, θ₂] arrays. The random numbers come from a seeded // generator here, so a chain is reproducible in JavaScript, but not the same // numbers as NumPy's. const LOG_2PI = Math.log(2 * Math.PI); function positive(name, v) { v = Number(v); if (!(Number.isFinite(v) && v > 0)) throw new RangeError(`${name} must be in (0, inf); got ${v}`); return v; } function openUnit(name, v) { v = Number(v); if (!(v > -1 && v < 1)) throw new RangeError(`${name} must be in (-1, 1); got ${v}`); return v; } function closedUnit(name, v) { v = Number(v); if (!(v >= 0 && v <= 1)) throw new RangeError(`${name} must be in [0, 1]; got ${v}`); return v; } // ---- random numbers --------------------------------------------------------- // sfc32, seeded through splitmix32: uniform() in [0, 1), normal() standard // normal (Box-Muller, both values used). export class Rng { constructor(seed = (Math.random() * 2 ** 32) >>> 0) { let s = seed >>> 0; const mix = () => { s = (s + 0x9e3779b9) >>> 0; let z = s; z = Math.imul(z ^ (z >>> 16), 0x85ebca6b); z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35); return (z ^ (z >>> 16)) >>> 0; }; this.a = mix(); this.b = mix(); this.c = mix(); this.d = mix(); this.spare = null; for (let i = 0; i < 12; i++) this.uniform(); } uniform() { let { a, b, c, d } = this; const t = (((a + b) >>> 0) + d) >>> 0; d = (d + 1) >>> 0; a = b ^ (b >>> 9); b = (c + (c << 3)) >>> 0; c = (c << 21) | (c >>> 11); c = (c + t) >>> 0; Object.assign(this, { a, b, c, d }); return t / 4294967296; } normal() { if (this.spare !== null) { const z = this.spare; this.spare = null; return z; } const u = 1 - this.uniform(); // (0, 1] const r = Math.sqrt(-2 * Math.log(u)); const a = 2 * Math.PI * this.uniform(); this.spare = r * Math.sin(a); return r * Math.cos(a); } normal2() { return [this.normal(), this.normal()]; } } // ---- the model ---------------------------------------------------------------- export class NormalMixture2D { // mu: distance between the means; sigma: [[σ₁₁, σ₁₂], [σ₂₁, σ₂₂]], per // component and axis; rho: [ρ₁, ρ₂]; tau: radius of the circle the chains // start on constructor({ mu = 4, sigma = [[1, 1], [1, 1]], rho = [0, 0], tau = 1 } = {}) { this.set({ mu, sigma, rho, tau }); } // validate and set any of mu, sigma, rho, tau; the next step uses them set({ mu = this.mu, sigma = this.sigma, rho = this.rho, tau = this.tau } = {}) { this.mu = positive('mu', mu); this.sigma = sigma.map((s, k) => s.map((v, j) => positive(`sigma[${k}][${j}]`, v))); this.rho = rho.map((r, k) => openUnit(`rho[${k}]`, r)); this.tau = positive('tau', tau); const h = this.mu / 2; this.means = [[-h, 0], [h, 0]]; // per component: covariance, precision and log(½ · normalization) this.comps = this.sigma.map(([s1, s2], k) => { const r = this.rho[k]; const c11 = s1 * s1, c12 = r * s1 * s2, c22 = s2 * s2; const det = c11 * c22 - c12 * c12; return { mx: this.means[k][0], my: this.means[k][1], c11, c12, c22, p11: c22 / det, p12: -c12 / det, p22: c11 / det, logNorm: -LOG_2PI - 0.5 * Math.log(det) + Math.log(0.5), }; }); return this; } logDensity([x, y]) { const [a, b] = this.comps.map((c) => { const dx = x - c.mx, dy = y - c.my; return c.logNorm - 0.5 * (dx * (c.p11 * dx + c.p12 * dy) + dy * (c.p12 * dx + c.p22 * dy)); }); const m = Math.max(a, b); if (m === -Infinity) return -Infinity; return m + Math.log(Math.exp(a - m) + Math.exp(b - m)); } // ∇ log p: minus the posterior-weighted P_k (θ − m_k) gradLogDensity([x, y]) { let gx = 0, gy = 0; const lp = [], pd = []; for (const c of this.comps) { const dx = x - c.mx, dy = y - c.my; const px = c.p11 * dx + c.p12 * dy, py = c.p12 * dx + c.p22 * dy; lp.push(c.logNorm - 0.5 * (dx * px + dy * py)); pd.push([px, py]); } const m = Math.max(lp[0], lp[1]); const w0 = Math.exp(lp[0] - m), w1 = Math.exp(lp[1] - m); const s = w0 + w1; gx = -(w0 * pd[0][0] + w1 * pd[1][0]) / s; gy = -(w0 * pd[0][1] + w1 * pd[1][1]) / s; return [gx, gy]; } initialPoint(rng) { const a = 2 * Math.PI * rng.uniform(); return [this.tau * Math.cos(a), this.tau * Math.sin(a)]; } // leapfrog / Langevin linear stability bound: 2 × the smallest principal std maxStableStepSize() { const lmin = Math.min(...this.comps.map(({ c11, c12, c22 }) => (c11 + c22) / 2 - Math.sqrt(((c11 - c22) / 2) ** 2 + c12 * c12))); return 2 * Math.sqrt(lmin); } // the exact marginal density of θ₁ (each component's is N(mₖ₁, σₖ₁²)) marginal1(x) { let p = 0; for (const c of this.comps) { const s = Math.sqrt(c.c11); p += 0.5 * Math.exp(-0.5 * ((x - c.mx) / s) ** 2) / (s * Math.sqrt(2 * Math.PI)); } return p; } // ground truth: mean 0 and Cov = ½ Σₖ (Σₖ + mₖ mₖᵀ); P(θ₁ > 0) truth() { const cov = [[0, 0], [0, 0]]; for (const c of this.comps) { cov[0][0] += 0.5 * (c.c11 + c.mx * c.mx); cov[0][1] += 0.5 * (c.c12 + c.mx * c.my); cov[1][1] += 0.5 * (c.c22 + c.my * c.my); } cov[1][0] = cov[0][1]; const erf = (z) => { // Abramowitz and Stegun 7.1.26 (|error| < 1.5e-7) const t = 1 / (1 + 0.3275911 * Math.abs(z)); const y = 1 - t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))) * Math.exp(-z * z); return z >= 0 ? y : -y; }; const right = this.comps.reduce((acc, c) => acc + 0.5 * 0.5 * (1 + erf(c.mx / Math.sqrt(2 * c.c11))), 0); return { mean: [0, 0], cov, right }; } } // ---- integrator --------------------------------------------------------------- // n leapfrog steps of size eps from (x, p), unit mass; path (optional) gets // each new position export function leapfrog(model, x, p, eps, n, path = null) { let g = model.gradLogDensity(x); p = [p[0] + 0.5 * eps * g[0], p[1] + 0.5 * eps * g[1]]; for (let i = 0; i < n; i++) { x = [x[0] + eps * p[0], x[1] + eps * p[1]]; if (path) path.push(x); g = model.gradLogDensity(x); if (i < n - 1) p = [p[0] + eps * g[0], p[1] + eps * g[1]]; } return [x, [p[0] + 0.5 * eps * g[0], p[1] + 0.5 * eps * g[1]]]; } export const hamiltonian = (model, x, p) => -model.logDensity(x) + 0.5 * (p[0] * p[0] + p[1] * p[1]); // ---- samplers ----------------------------------------------------------------- // next() advances one step and returns a copy of theta. After each step: // theta, proposal, accepted, acceptProb, nIter, nAccept, acceptanceRate. export class Sampler { constructor(model, stepSize, { theta0 = null, seed } = {}) { this.model = model; this.stepSize = stepSize; this.rng = new Rng(seed); this.reset(theta0); } get stepSize() { return this._eps; } set stepSize(v) { this._eps = positive('stepSize', v); } reset(theta0 = null) { this.theta = theta0 === null ? this.model.initialPoint(this.rng) : [Number(theta0[0]), Number(theta0[1])]; this.proposal = this.theta.slice(); this.accepted = null; this.acceptProb = NaN; this.nIter = this.nAccept = 0; } get acceptanceRate() { return this.nIter ? this.nAccept / this.nIter : NaN; } next() { this._step(); this.nIter++; this.nAccept += this.accepted ? 1 : 0; return this.theta.slice(); } draws(n) { return Array.from({ length: n }, () => this.next()); } // set acceptProb and accepted; NaN or −inf ratios reject _metropolis(logRatio) { if (!Number.isFinite(logRatio)) logRatio = logRatio === Infinity ? Infinity : -Infinity; this.acceptProb = Math.exp(Math.min(0, logRatio)); this.accepted = Math.log(this.rng.uniform()) < logRatio; return this.accepted; } } // θ' = θ + ε z, z ~ N(0, I); Metropolis accept export class RandomWalkMetropolis extends Sampler { _step() { const lp = (x) => this.model.logDensity(x); const [z1, z2] = this.rng.normal2(); this.proposal = [this.theta[0] + this.stepSize * z1, this.theta[1] + this.stepSize * z2]; if (this._metropolis(lp(this.proposal) - lp(this.theta))) this.theta = this.proposal; } } // θ' = θ + (ε²/2) ∇ log p(θ) + ε z. // adjust false: unadjusted Langevin (ULA), always moves (biased, may // diverge); a non-finite proposal is not taken and sets diverged. // adjust true: MALA, with the Metropolis-Hastings correction. export class Langevin extends Sampler { constructor(model, stepSize, { adjust = true, ...rest } = {}) { super(model, stepSize, rest); this.adjust = adjust; } get adjust() { return this._adjust; } set adjust(v) { this._adjust = Boolean(v); } reset(theta0 = null) { super.reset(theta0); this.diverged = false; } _mean(x) { const g = this.model.gradLogDensity(x); const h = 0.5 * this.stepSize ** 2; return [x[0] + h * g[0], x[1] + h * g[1]]; } _logQ(to, frm) { const m = this._mean(frm); const dx = to[0] - m[0], dy = to[1] - m[1]; return (-0.5 * (dx * dx + dy * dy)) / this.stepSize ** 2; } _step() { const x = this.theta; const m = this._mean(x); const [z1, z2] = this.rng.normal2(); const y = [m[0] + this.stepSize * z1, m[1] + this.stepSize * z2]; this.proposal = y; if (!this.adjust) { this.diverged = !(Number.isFinite(y[0]) && Number.isFinite(y[1])); this.accepted = !this.diverged; this.acceptProb = 1; } else { const lp = (v) => this.model.logDensity(v); this._metropolis(lp(y) - lp(x) + this._logQ(x, y) - this._logQ(y, x)); } if (this.accepted) this.theta = y; } } // One leapfrog step per iteration with partial momentum refresh, // p ← √(1 − γ) p + √γ z (γ = 1 is MALA); on rejection the momentum is // negated (Horowitz 1991). export class GeneralizedHMC extends Sampler { constructor(model, stepSize, { gamma = 0.1, ...rest } = {}) { super(model, stepSize, rest); this.gamma = gamma; } get gamma() { return this._gamma; } set gamma(v) { this._gamma = closedUnit('gamma', v); } reset(theta0 = null) { super.reset(theta0); this.momentum = this.rng.normal2(); } _step() { const g = this.gamma; const [z1, z2] = this.rng.normal2(); const a = Math.sqrt(1 - g), b = Math.sqrt(g); const p = [a * this.momentum[0] + b * z1, a * this.momentum[1] + b * z2]; const [x1, p1] = leapfrog(this.model, this.theta, p, this.stepSize, 1); this.proposal = x1; const h0 = hamiltonian(this.model, this.theta, p); const h1 = hamiltonian(this.model, x1, p1); if (this._metropolis(h0 - h1)) { this.theta = x1; this.momentum = p1; } else { this.momentum = [-p[0], -p[1]]; } } } // L leapfrog steps, unit mass, full momentum refresh. path holds the L + 1 // positions of the last trajectory (accepted or not). export class HMC extends Sampler { constructor(model, stepSize, { nSteps = 10, ...rest } = {}) { super(model, stepSize, rest); this.nSteps = nSteps; } get nSteps() { return this._L; } set nSteps(v) { if (!Number.isInteger(Number(v)) || v < 1) throw new RangeError(`nSteps must be a positive integer; got ${v}`); this._L = Number(v); } reset(theta0 = null) { super.reset(theta0); this.path = [this.theta.slice()]; } _step() { const p = this.rng.normal2(); const path = [this.theta]; const [x1, p1] = leapfrog(this.model, this.theta, p, this.stepSize, this.nSteps, path); this.path = path; this.proposal = x1; const h0 = hamiltonian(this.model, this.theta, p); const h1 = hamiltonian(this.model, x1, p1); if (this._metropolis(h0 - h1)) this.theta = x1; } }