// Listening for convergence: several MCMC chains on a 2D two-component // normal mixture (js/mixture.js, a port of mixture_mcmc.py), each playing a // note per iteration (js/voices.js), so you can hear whether they have // reached the stationary distribution. // // - All chains run the same sampler with the same tuning (random-walk // Metropolis, MALA, ULA, generalized HMC or HMC), each from its own start // and seed: by default random points on the circle of radius τ, or, after // a click, all from the clicked point. // - Each iteration, each chain plays a note, all with the same sound: pitch // from θ₁ (left to right over three octaves of the chosen scale, the range // set by the target, not the window), timbre from θ₂ (a soft pure tone at // the bottom, a bright buzzy one at the top), and each chain at its own // place in the stereo field. // A rejected step repeats the note softly (or is silent). Mixed chains // wander over both modes and play in the same register; stuck chains // drone on in one. Past MAX_NOTE_RATE notes per second (many chains, fast // tempo), the chains take turns: each plays every stride-th iteration. // - Pitch and timbre from rank (optional): instead of θ itself, its rank // among the pooled draws after warm-up (a sample of REF_SIZE of them, // refreshed with the statistics). Needs no knowledge of the target: mixed // chains each play evenly over the whole range, alike; a stuck chain keeps // to part of it. // - The agreement drone: under the notes, per chain, a soft tone at the // key's root (for θ₁) and one at its fifth (for θ₂), each detuned by how // far the chain's mean after warm-up is from the pooled mean, in pooled // standard deviations z (400 z² cents, up to an octave). Chains that // disagree beat and clash; as they agree (split R̂ towards 1), the drone // settles into unison. // - Listen back (optional): LISTEN.live s of the chains as they run, a short // gap, LISTEN.replay s replayed from the history halfway back (or, shuffled, // random draws from its first half), a gap, and live again. The replay is // heard, not shown: the plane holds still meanwhile. // - Below the plane: the θ₁ marginal of the draws after warm-up (the first // half of each chain) against the exact one, and the θ₁ traces; in the // panel, the moments of the draws against the exact ones, split R̂, and // each chain's acceptance rate. // - Changing the target or the sampler keeps the chains where they are and // starts a fresh set of draws (the old ones were for other settings). import { GeneralizedHMC, HMC, Langevin, NormalMixture2D, RandomWalkMetropolis } from './js/mixture.js'; import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN } from './js/voices.js'; // the five targets of the notes (mixture_mcmc.md, "Interesting settings") const BASE = { mu: 4, s11: 1, s12: 1, s21: 1, s22: 1, r1: 0, r2: 0 }; const PRESETS = [ { name: 'Easy: overlapping modes', p: { mu: 3 } }, { name: 'Separated: a low-density gap', p: { mu: 6 } }, { name: 'Ridge: crossed thin ridges', p: { mu: 4, r1: 0.95, r2: -0.95 } }, { name: 'Stiff: a wide mode and a needle', p: { mu: 4, s21: 0.1, s22: 0.1 } }, { name: 'Crossed: a horizontal and a vertical bar', p: { mu: 4, s11: 2, s12: 0.25, s21: 0.25, s22: 2 } }, ]; const DEFAULT_PRESET = 1; const MAX_CHAINS = 32; const HIST_CAP = 1 << 17; // draws kept per chain; past it, thinned by 2 const LOOKAHEAD = 0.12; // s of iterations scheduled ahead const TAIL = 0.3; // s of trail (at least 6 iterations) const TRACE_LEN = 1000; // draws in the trace plot const TEMPO = { min: 1, max: 400, default: 50 }; // iterations per second const MAX_NOTE_RATE = 800; // notes per second, over all chains const BINS = 64; const SKIP = 1000; // iterations per "+1000" const MARGIN = { left: 48, right: 12, top: 10 }; const REF_SIZE = 4000; // pooled draws ranks are taken against const LISTEN = { live: 3, gap: 0.6, replay: 3 }; // s const $ = (id) => document.getElementById(id); const clamp = (v, a, b) => Math.min(b, Math.max(a, v)); const fmt2 = (v) => (v >= 1 ? v.toFixed(2) : v.toPrecision(2)); // sliders: linear, or log (min > 0) over an integer 0..1000 input const MODEL_SLIDERS = [ { key: 'mu', label: 'μ', min: 0.5, max: 10, step: 0.1, fmt: (v) => v.toFixed(1) }, { key: 's11', label: 'σ11', min: 0.05, max: 4, log: true, fmt: fmt2 }, { key: 's12', label: 'σ12', min: 0.05, max: 4, log: true, fmt: fmt2 }, { key: 's21', label: 'σ21', min: 0.05, max: 4, log: true, fmt: fmt2 }, { key: 's22', label: 'σ22', min: 0.05, max: 4, log: true, fmt: fmt2 }, { key: 'r1', label: 'ρ1', min: -0.99, max: 0.99, step: 0.01, fmt: (v) => v.toFixed(2) }, { key: 'r2', label: 'ρ2', min: -0.99, max: 0.99, step: 0.01, fmt: (v) => v.toFixed(2) }, { key: 'tau', label: 'τ (starts)', min: 0.1, max: 8, step: 0.1, fmt: (v) => v.toFixed(1) }, ]; const SAMPLER_SLIDERS = [ { key: 'eps', label: 'Step ε', min: 0.01, max: 5, log: true, fmt: fmt2 }, { key: 'gamma', label: 'Refresh γ', min: 0.001, max: 1, log: true, fmt: fmt2, only: ['ghmc'] }, { key: 'L', label: 'Leapfrog L', min: 1, max: 100, step: 1, fmt: (v) => String(v), only: ['hmc'] }, ]; const CHAIN_SLIDERS = [ { key: 'count', label: 'Chains', min: 1, max: MAX_CHAINS, step: 1, fmt: (v) => String(v) }, ]; const params = { ...BASE, ...PRESETS[DEFAULT_PRESET].p, tau: 1 }; const tune = { kind: 'rwm', eps: 1, gamma: 0.1, L: 10, count: 8 }; const canvas = $('plot'); const ctx = canvas.getContext('2d'); const densityLayer = document.createElement('canvas'); const dotsLayer = document.createElement('canvas'); const model = new NormalMixture2D(); let range; // { X0, Y0 }: the θ₁, θ₂ half-ranges of pitch and timbre let view; // { X, Y }: the half-ranges shown (equal scales) let rects; // { main, hist, trace } in CSS px let chains = []; let startPoint = null; // null: starts on the τ circle; else [θ₁, θ₂] let running = false; // paused until Run is pressed let nextBeat = 0; let beat = 0; // iterations scheduled so far, for the chains' turns let tempo = TEMPO.default; let synth = null; let soundOn = false; let key = DEFAULT_KEY; let stats = null; let statsAt = -Infinity; let theme; let ref = null; // sorted samples of the pooled θ₁ and θ₂, for ranks let cycle = null; // listen back: { phase, until, ... }; null when off let drone = null; // per chain detunes (cents), [θ₁ layer, θ₂ layer] // ---- chains ------------------------------------------------------------------- function makeSampler(theta0) { const seed = (Math.random() * 2 ** 32) >>> 0; const opts = { theta0, seed }; switch (tune.kind) { case 'mala': return new Langevin(model, tune.eps, { ...opts, adjust: true }); case 'ula': return new Langevin(model, tune.eps, { ...opts, adjust: false }); case 'ghmc': return new GeneralizedHMC(model, tune.eps, { ...opts, gamma: tune.gamma }); case 'hmc': return new HMC(model, tune.eps, { ...opts, nSteps: tune.L }); default: return new RandomWalkMetropolis(model, tune.eps, opts); } } const newHistory = () => ({ xs: new Float32Array(2 * HIST_CAP), n: 0, thin: 1, since: 0 }); function record(h, [x, y]) { if (++h.since < h.thin) return; h.since = 0; if (h.n === HIST_CAP) { for (let i = 0; i < HIST_CAP / 2; i++) { h.xs[2 * i] = h.xs[4 * i]; h.xs[2 * i + 1] = h.xs[4 * i + 1]; } h.n = HIST_CAP / 2; h.thin *= 2; } h.xs[2 * h.n] = x; h.xs[2 * h.n + 1] = y; h.n++; } const hueOf = (k) => (0.08 + k * 0.382) % 1; function newChain(k, theta0) { return { k, hue: hueOf(k), sampler: makeSampler(theta0), hist: newHistory(), queue: [], iters: 0, acc: 0 }; } function startOf() { return startPoint ? startPoint.slice() : null; } // spread the chains over the stereo field function setPans() { const n = chains.length; for (const c of chains) c.pan = n > 1 ? -0.6 + (1.2 * c.k) / (n - 1) : 0; } // a fresh set of draws, the chains staying where they are function newSegment() { for (const c of chains) { c.hist = newHistory(); c.iters = c.acc = 0; } clearLayer(dotsLayer); stats = null; statsAt = -Infinity; } // all chains from new starts (the τ circle, or the clicked point) function restart() { chains = Array.from({ length: tune.count }, (_, k) => newChain(k, startOf())); setPans(); newSegment(); } function setChainCount(n) { if (n < chains.length) chains = chains.slice(0, n); while (chains.length < n) chains.push(newChain(chains.length, startOf())); setPans(); newSegment(); } // the sampler changed kind: new samplers from where the chains are function rebuildSamplers() { for (const c of chains) c.sampler = makeSampler(c.sampler.theta.slice()); newSegment(); } function retune() { for (const c of chains) { c.sampler.stepSize = tune.eps; if (tune.kind === 'ghmc') c.sampler.gamma = tune.gamma; if (tune.kind === 'hmc') c.sampler.nSteps = tune.L; } newSegment(); } // one iteration of chain c, recorded; returns the event for drawing and sound function stepChain(c, time) { const s = c.sampler; const from = s.theta.slice(); const theta = s.next(); c.iters++; c.acc += s.accepted ? 1 : 0; record(c.hist, theta); return { time, from, theta, proposal: s.proposal.slice(), path: tune.kind === 'hmc' ? s.path : null, accepted: Boolean(s.accepted), diverged: Boolean(s.diverged), drawn: false, }; } // ---- the target --------------------------------------------------------------------- function applyModel() { model.set({ mu: params.mu, sigma: [[params.s11, params.s12], [params.s21, params.s22]], rho: [params.r1, params.r2], tau: params.tau, }); const X0 = params.mu / 2 + 3.2 * Math.max(params.s11, params.s21); const Y0 = 3.2 * Math.max(params.s12, params.s22); range = { X0, Y0 }; $('limit').textContent = `Stability limit of leapfrog and Langevin: ε < ${fmt2(model.maxStableStepSize())}`; layout(); renderDensity(); } // ---- sound ------------------------------------------------------------------------- const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000); const beatDt = () => 1 / tempo; // the rank of v in a sorted sample, in [0, 1] (ties: their middle) function rankOf(sorted, v) { let lo = 0, hi = sorted.length; while (lo < hi) { const m = (lo + hi) >> 1; if (sorted[m] < v) lo = m + 1; else hi = m; } let up = lo; while (up < sorted.length && sorted[up] === v) up++; return (lo + up) / 2 / sorted.length; } // a draw's place on the pitch and timbre scales, both in [0, 1]: from θ over // the target's range, or from its rank among the pooled draws function placeOf([x, y]) { if ($('pitch-map').value === 'rank' && ref) return [rankOf(ref.x, x), rankOf(ref.y, y)]; return [(x + range.X0) / (2 * range.X0), clamp((y + range.Y0) / (2 * range.Y0), 0, 1)]; } function playNote(c, theta, accepted, time, gain) { const [x, y] = theta; if (!Number.isFinite(x) || !Number.isFinite(y)) return; if (!accepted && $('rejected').value === 'silent') return; const scale = SCALES[$('scale').selectedIndex]; const [u, bright] = placeOf(theta); synth.play(pitchOf(u, scale, key), time, { pan: c.pan, gain: gain * (accepted ? 1 : 0.3), bright }); } // the next phase of listening back, from time t = cycle.until; a replay // needs three times its length of history (so it is clear of the live // stretch just heard), else the chains play on live function advanceCycle(t) { const len = Math.round(LISTEN.replay * tempo); const n = Math.min(...chains.map((c) => c.hist.n)); switch (cycle.phase) { case 'live': cycle = n >= 3 * len ? { phase: 'gap', next: 'replay', until: t + LISTEN.gap } : { phase: 'live', until: t + LISTEN.live }; break; case 'gap': if (cycle.next === 'replay') { // from halfway back: the draws centered on the middle of the history const start = Math.floor((n - len) / 2); cycle = { phase: 'replay', until: t + LISTEN.replay, start, half: Math.floor(n / 2), j: 0, thin: chains[0].hist.thin }; } else { cycle = { phase: 'live', until: t + LISTEN.live }; } break; default: cycle = { phase: 'gap', next: 'live', until: t + LISTEN.gap }; } } // step every chain at each beat due within LOOKAHEAD, playing its note function schedule() { const now = clock(); // fallen behind (a stalled frame, a hidden tab), or paused: carry on from // now rather than catch up in a burst if (nextBeat < now) nextBeat = now + 0.02; if (!running) return; const dt = beatDt(); // the chains' turns, and the level: softer the more notes overlap (about // the notes per second that sound, times 0.15 s) const stride = Math.ceil((chains.length * tempo) / MAX_NOTE_RATE); const rate = (chains.length * tempo) / stride; const gain = 1 / Math.sqrt(Math.max(chains.length, 0.15 * rate)); const listen = $('listen').value; if (listen === 'off' || !soundOn) cycle = null; else if (!cycle) cycle = { phase: 'live', until: nextBeat + LISTEN.live }; while (nextBeat < now + LOOKAHEAD) { if (cycle && nextBeat >= cycle.until) advanceCycle(cycle.until); const phase = cycle ? cycle.phase : 'live'; const plays = (c) => soundOn && synth && (beat + c.k) % stride === 0; if (phase === 'live') { for (const c of chains) { const ev = stepChain(c, nextBeat); c.queue.push(ev); if (plays(c) && !ev.diverged) playNote(c, ev.theta, ev.accepted, nextBeat, gain); } } else if (phase === 'replay') { // the recorded draws (a repeat of the one before was a rejection), or // random ones from the first half for (const c of chains) { const h = c.hist; const i = listen === 'shuffled' ? Math.floor(Math.random() * cycle.half) : Math.min(h.n - 1, cycle.start + cycle.j); const theta = [h.xs[2 * i], h.xs[2 * i + 1]]; const accepted = listen === 'shuffled' || i === 0 || theta[0] !== h.xs[2 * i - 2] || theta[1] !== h.xs[2 * i - 1]; if (plays(c)) playNote(c, theta, accepted, nextBeat, gain); } cycle.j++; } nextBeat += dt; beat++; } } function setSound(on) { soundOn = on; const btn = $('sound'); btn.setAttribute('aria-pressed', on); btn.querySelector('.icon').textContent = on ? '🔊' : '🔇'; btn.querySelector('.label').textContent = on ? 'Sound on' : 'Turn sound on'; if (on && !synth) { // the clock switches to the audio context's synth = createSynth(); synth.setSustain(Number($('sustain').value)); synth.setDroneRoot(droneRoot()); for (const c of chains) c.queue = []; nextBeat = 0; } if (synth) { synth.ctx.resume(); synth.setVolume(on ? Number($('volume').value) : 0); } } function setRunning(on) { running = on; cycle = null; const btn = $('run'); btn.setAttribute('aria-pressed', on); btn.textContent = on ? '❚❚ Pause' : '▶ Run'; } // SKIP iterations of every chain at once, silently function skipAhead() { const r = rects.main; const dctx = dotsLayer.getContext('2d'); for (const c of chains) { dctx.fillStyle = chainColor(c.hue, 0.35); for (let i = 0; i < SKIP; i++) { const ev = stepChain(c, 0); drawDot(dctx, r, ev.theta); } c.queue = []; } statsAt = -Infinity; } // ---- statistics ---------------------------------------------------------------------- // split R̂ (Gelman et al., BDA3): each chain halved, between- against // within-half variance function splitRhat(seqs) { const halves = []; for (const s of seqs) { const h = Math.floor(s.length / 2); if (h < 2) return NaN; halves.push(s.subarray(0, h), s.subarray(s.length - h)); } const n = halves[0].length; const m = halves.length; const means = halves.map((h) => h.reduce((a, v) => a + v, 0) / n); const vars = halves.map((h, i) => h.reduce((a, v) => a + (v - means[i]) ** 2, 0) / (n - 1)); const W = vars.reduce((a, v) => a + v, 0) / m; const mbar = means.reduce((a, v) => a + v, 0) / m; const B = (n / (m - 1)) * means.reduce((a, v) => a + (v - mbar) ** 2, 0); return Math.sqrt((((n - 1) / n) * W + B / n) / W); } // the draws after warm-up (the second half of each chain), pooled function computeStats() { const n = Math.min(...chains.map((c) => c.hist.n)); const start = Math.floor(n / 2); const kept = n - start; const s1 = [], s2 = []; let m1 = 0, m2 = 0, q11 = 0, q22 = 0, q12 = 0, right = 0, N = 0; const counts = new Float64Array(BINS); for (const c of chains) { const a = new Float64Array(kept), b = new Float64Array(kept); for (let i = 0; i < kept; i++) { const x = c.hist.xs[2 * (start + i)]; const y = c.hist.xs[2 * (start + i) + 1]; a[i] = x; b[i] = y; m1 += x; m2 += y; q11 += x * x; q22 += y * y; q12 += x * y; right += x > 0; N++; const bin = Math.floor(((x + view.X) / (2 * view.X)) * BINS); if (bin >= 0 && bin < BINS) counts[bin]++; } s1.push(a); s2.push(b); } const iters = chains[0]?.iters ?? 0; if (!N) { ref = null; drone = droneOf(chains.map((c) => [c.sampler.theta[0]]), chains.map((c) => [c.sampler.theta[1]])); return { iters, kept: 0 }; } m1 /= N; m2 /= N; // the reference for ranks: a random sample of the pooled draws, sorted if (N >= 20) { const R = Math.min(REF_SIZE, N); const rx = new Float64Array(R), ry = new Float64Array(R); for (let j = 0; j < R; j++) { const k = Math.floor(Math.random() * chains.length); const i = Math.floor(Math.random() * kept); rx[j] = s1[k][i]; ry[j] = s2[k][i]; } ref = { x: rx.sort(), y: ry.sort() }; } else { ref = null; } drone = droneOf(s1, s2); const binW = (2 * view.X) / BINS; return { iters, kept, mean: [m1, m2], cov: [[q11 / N - m1 * m1, q12 / N - m1 * m2], [0, q22 / N - m2 * m2]], right: right / N, rhat: [splitRhat(s1), splitRhat(s2)], hist: Array.from(counts, (k) => k / (N * binW)), }; } // the drone's detunes (cents) per chain, for θ₁ and θ₂: 400 z² (signed, up // to an octave), z the chain's mean from the pooled mean in pooled standard // deviations (from the chains' current points before there are draws) function droneOf(s1, s2) { return [s1, s2].map((seqs) => { const means = seqs.map((a) => a.reduce((p, v) => p + v, 0) / a.length); const all = seqs.flatMap((a) => Array.from(a)); const m = all.reduce((p, v) => p + v, 0) / all.length; const sd = Math.sqrt(all.reduce((p, v) => p + (v - m) ** 2, 0) / all.length) || 1; return means.map((mk) => { const z = (mk - m) / sd; return Number.isFinite(z) ? Math.sign(z) * Math.min(1200, 400 * z * z) : 1200; }); }); } const droneRoot = () => 130.81 * 2 ** (key / 12); // the key's root, C3 to B3 function num(v, d = 2) { if (!Number.isFinite(v)) return '—'; if (Math.abs(v) < 1e-9) v = 0; return (Math.abs(v) < 1e4 ? v.toFixed(d) : v.toExponential(1)).replace(/^-/, '−'); } function renderStats() { const t = model.truth(); const st = stats ?? { iters: 0, kept: 0 }; $('draws-note').textContent = `· ${st.iters} per chain, the first half warm-up`; const has = st.kept > 0; const rows = [ ['mean θ₁', has ? num(st.mean[0]) : '—', '0'], ['mean θ₂', has ? num(st.mean[1]) : '—', '0'], ['var θ₁', has ? num(st.cov[0][0]) : '—', num(t.cov[0][0])], ['var θ₂', has ? num(st.cov[1][1]) : '—', num(t.cov[1][1])], ['cov', has ? num(st.cov[0][1]) : '—', num(t.cov[0][1])], ['P(θ₁ > 0)', has ? num(st.right) : '—', num(t.right)], ]; const rh = (v) => { const off = !Number.isFinite(v) || v > 1.05; return `