// 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 `${has ? num(v) : '—'}`; }; $('stats').innerHTML = 'drawsexact' + rows.map(([a, b, c]) => `${a}${b}${c}`).join('') + `split R̂ θ₁${rh(st.rhat?.[0])}1` + `split R̂ θ₂${rh(st.rhat?.[1])}1`; $('chain-list').innerHTML = chains.map((c) => `
  • ${c.iters ? Math.round((100 * c.acc) / c.iters) : '–'}%
  • `).join(''); } // ---- drawing ------------------------------------------------------------------------ function readTheme() { const cs = getComputedStyle(document.documentElement); const v = (name) => cs.getPropertyValue(name).trim(); theme = { bg: v('--bg'), fg: v('--fg'), muted: v('--muted'), line: v('--line'), accent: v('--accent'), density: v('--density'), light: v('--dot-light') }; } const chainColor = (hue, alpha = 1) => `hsla(${Math.round(hue * 360)}, 80%, ${theme.light}, ${alpha})`; function clearLayer(layer) { const dpr = devicePixelRatio || 1; const c = layer.getContext('2d'); c.setTransform(1, 0, 0, 1, 0, 0); c.clearRect(0, 0, layer.width, layer.height); c.setTransform(dpr, 0, 0, dpr, 0, 0); } // the plane on top, then the θ₁ marginal, then the traces; the view of the // plane has equal scales on both axes and frames the target and the τ circle function layout() { const dpr = devicePixelRatio || 1; const W = canvas.width / dpr; const H = canvas.height / dpr; const traceH = clamp(0.19 * H, 70, 140); const histH = clamp(0.13 * H, 50, 100); const w = Math.max(10, W - MARGIN.left - MARGIN.right); const mainH = Math.max(10, H - MARGIN.top - 26 - histH - 18 - traceH - 22); const main = { x: MARGIN.left, y: MARGIN.top, w, h: mainH }; const hist = { x: MARGIN.left, y: main.y + mainH + 26, w, h: histH }; const trace = { x: MARGIN.left, y: hist.y + histH + 18, w, h: traceH }; rects = { main, hist, trace }; const needX = Math.max(range.X0, 1.15 * params.tau); const needY = Math.max(range.Y0, 1.15 * params.tau); const s = Math.min(main.w / (2 * needX), main.h / (2 * needY)); view = { X: main.w / (2 * s), Y: main.h / (2 * s) }; } const toPx = (r, [x, y]) => [r.x + ((x / view.X + 1) / 2) * r.w, r.y + ((1 - y / view.Y) / 2) * r.h]; function drawDot(dctx, r, theta) { if (!Number.isFinite(theta[0]) || !Number.isFinite(theta[1])) return; const [px, py] = toPx(r, theta); if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) return; dctx.fillRect(px - 0.9, py - 0.9, 1.8, 1.8); } // the density, shaded on a log scale over 3.5 decades below its peak function renderDensity() { clearLayer(densityLayer); if (!rects) return; const r = rects.main; const gw = Math.max(2, Math.ceil(r.w / 3)); const gh = Math.max(2, Math.ceil(r.h / 3)); const img = new ImageData(gw, gh); const hex = theme.density.replace('#', ''); const rgb = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16)); const logMax = Math.max(...model.means.map((m) => model.logDensity(m))); for (let j = 0; j < gh; j++) { const y = view.Y * (1 - (2 * (j + 0.5)) / gh); for (let i = 0; i < gw; i++) { const x = view.X * ((2 * (i + 0.5)) / gw - 1); const t = clamp(1 + (model.logDensity([x, y]) - logMax) / (3.5 * Math.LN10), 0, 1); const o = 4 * (j * gw + i); img.data[o] = rgb[0]; img.data[o + 1] = rgb[1]; img.data[o + 2] = rgb[2]; img.data[o + 3] = Math.round(255 * 0.42 * t ** 1.4); } } const tmp = document.createElement('canvas'); tmp.width = gw; tmp.height = gh; tmp.getContext('2d').putImageData(img, 0, 0); const dctx = densityLayer.getContext('2d'); dctx.imageSmoothingEnabled = true; dctx.drawImage(tmp, r.x, r.y, r.w, r.h); } function redrawDots() { clearLayer(dotsLayer); const dctx = dotsLayer.getContext('2d'); for (const c of chains) { dctx.fillStyle = chainColor(c.hue, 0.35); for (let i = 0; i < c.hist.n; i++) drawDot(dctx, rects.main, [c.hist.xs[2 * i], c.hist.xs[2 * i + 1]]); } } function resize() { const dpr = devicePixelRatio || 1; const { width, height } = canvas.getBoundingClientRect(); canvas.width = densityLayer.width = dotsLayer.width = Math.round(width * dpr); canvas.height = densityLayer.height = dotsLayer.height = Math.round(height * dpr); layout(); renderDensity(); redrawDots(); statsAt = -Infinity; } // the dots of the iterations that have come due; the queues trimmed to the // trail function drawDue(now) { const dctx = dotsLayer.getContext('2d'); const keep = trailTime() + 2 * beatDt(); for (const c of chains) { dctx.fillStyle = chainColor(c.hue, 0.35); for (const ev of c.queue) { if (ev.time > now) break; if (!ev.drawn) { drawDot(dctx, rects.main, ev.theta); ev.drawn = true; } } while (c.queue.length > 1 && c.queue[1].time < now - keep) c.queue.shift(); } } const trailTime = () => Math.max(TAIL, 6 * beatDt()); function niceStep(span) { const raw = span / 5; const p = 10 ** Math.floor(Math.log10(raw)); return [1, 2, 5, 10].map((m) => m * p).find((s) => s >= raw); } function drawAxes() { const r = rects.main; ctx.strokeStyle = theme.line; ctx.lineWidth = 1; ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1); ctx.fillStyle = theme.muted; ctx.font = '12px "Hanken Grotesk", system-ui, sans-serif'; const step = niceStep(2 * Math.min(view.X, view.Y)); ctx.textBaseline = 'top'; ctx.textAlign = 'center'; ctx.beginPath(); for (let x = Math.ceil(-view.X / step) * step; x <= view.X; x += step) { const [px] = toPx(r, [x, 0]); ctx.moveTo(px, r.y + r.h); ctx.lineTo(px, r.y + r.h + 4); ctx.fillText(num(x, step < 1 ? 1 : 0), px, r.y + r.h + 5); } ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; for (let y = Math.ceil(-view.Y / step) * step; y <= view.Y; y += step) { const [, py] = toPx(r, [0, y]); ctx.moveTo(r.x - 4, py); ctx.lineTo(r.x, py); ctx.fillText(num(y, step < 1 ? 1 : 0), r.x - 6, py); } ctx.stroke(); // the axis names, inside the plane's corners, clear of the tick labels ctx.textAlign = 'right'; ctx.textBaseline = 'bottom'; ctx.fillText('θ₁ → pitch', r.x + r.w - 6, r.y + r.h - 4); ctx.save(); ctx.translate(r.x + 6, r.y + r.h - 4); ctx.rotate(-Math.PI / 2); ctx.textAlign = 'left'; ctx.textBaseline = 'top'; ctx.fillText('θ₂ → timbre: pure to buzzy', 0, 0); ctx.restore(); } function drawStarts() { const r = rects.main; ctx.save(); ctx.strokeStyle = theme.muted; ctx.lineWidth = 1; if (startPoint) { const [px, py] = toPx(r, startPoint); ctx.beginPath(); ctx.moveTo(px - 7, py); ctx.lineTo(px + 7, py); ctx.moveTo(px, py - 7); ctx.lineTo(px, py + 7); ctx.stroke(); } else { const [cx, cy] = toPx(r, [0, 0]); const rad = (params.tau / view.X) * (r.w / 2); ctx.setLineDash([3, 4]); ctx.beginPath(); ctx.arc(cx, cy, rad, 0, 2 * Math.PI); ctx.stroke(); } ctx.restore(); } // each chain: a fading trail of its last positions, its last proposal (the // HMC trajectory, or a line), crossed out if rejected, its current point, // and a ring at each note function drawChains(now) { const r = rects.main; const dt = beatDt(); ctx.save(); ctx.beginPath(); ctx.rect(r.x, r.y, r.w, r.h); ctx.clip(); ctx.lineCap = 'round'; ctx.lineJoin = 'round'; for (const c of chains) { const due = c.queue.filter((ev) => ev.time <= now); const cur = due[due.length - 1]; const head = cur ? cur.theta : c.sampler.theta; // trail for (let i = 1; i < due.length; i++) { const alpha = 0.7 * (1 - (now - due[i].time) / trailTime()); if (alpha <= 0 || !due[i].accepted) continue; ctx.strokeStyle = chainColor(c.hue, alpha); ctx.lineWidth = 1.5; ctx.beginPath(); ctx.moveTo(...toPx(r, due[i - 1].theta)); ctx.lineTo(...toPx(r, due[i].theta)); ctx.stroke(); } if (cur) { const g = (now - cur.time) / Math.max(dt, 0.15); if (g < 1) { // the proposal ctx.strokeStyle = chainColor(c.hue, 0.8 * (1 - g)); ctx.lineWidth = 1.2; ctx.setLineDash(cur.accepted ? [] : [3, 3]); ctx.beginPath(); const pts = cur.path ?? [cur.from, cur.proposal]; pts.forEach((p, i) => (i ? ctx.lineTo(...toPx(r, p)) : ctx.moveTo(...toPx(r, p)))); ctx.stroke(); ctx.setLineDash([]); if (!cur.accepted && Number.isFinite(cur.proposal[0])) { const [qx, qy] = toPx(r, cur.proposal); ctx.beginPath(); ctx.moveTo(qx - 4, qy - 4); ctx.lineTo(qx + 4, qy + 4); ctx.moveTo(qx + 4, qy - 4); ctx.lineTo(qx - 4, qy + 4); ctx.stroke(); } // the note if (Number.isFinite(head[0])) { const [hx, hy] = toPx(r, head); ctx.strokeStyle = chainColor(c.hue, (cur.accepted ? 1 : 0.4) * (1 - g)); ctx.lineWidth = 2; ctx.beginPath(); ctx.arc(hx, hy, 5 + 12 * g, 0, 2 * Math.PI); ctx.stroke(); } } } if (Number.isFinite(head[0]) && Number.isFinite(head[1])) { const [hx, hy] = toPx(r, head); ctx.fillStyle = chainColor(c.hue); ctx.strokeStyle = theme.bg; ctx.lineWidth = 1.5; ctx.beginPath(); ctx.arc(hx, hy, 5, 0, 2 * Math.PI); ctx.fill(); ctx.stroke(); } } ctx.restore(); } function caption(text, r) { ctx.font = '12px "Hanken Grotesk", system-ui, sans-serif'; ctx.textBaseline = 'top'; ctx.textAlign = 'left'; const w = ctx.measureText(text).width; ctx.fillStyle = theme.bg; ctx.globalAlpha = 0.8; ctx.fillRect(r.x + 2, r.y + 2, w + 8, 17); ctx.globalAlpha = 1; ctx.fillStyle = theme.muted; ctx.fillText(text, r.x + 6, r.y + 4); } // the θ₁ marginal of the draws after warm-up (bars) and the exact one (line) function drawHist() { const r = rects.hist; ctx.strokeStyle = theme.line; ctx.lineWidth = 1; ctx.beginPath(); ctx.moveTo(r.x, r.y + r.h + 0.5); ctx.lineTo(r.x + r.w, r.y + r.h + 0.5); ctx.stroke(); const K = 200; const exact = Array.from({ length: K + 1 }, (_, i) => model.marginal1(view.X * ((2 * i) / K - 1))); const h = stats?.hist; const top = 1.1 * Math.max(...exact, ...(h ?? [0])); const py = (v) => r.y + r.h - (v / top) * (r.h - 4); if (h) { ctx.fillStyle = theme.density; ctx.globalAlpha = 0.35; const bw = r.w / BINS; h.forEach((v, i) => { if (v > 0) ctx.fillRect(r.x + i * bw + 0.5, py(v), bw - 1, r.y + r.h - py(v)); }); ctx.globalAlpha = 1; } ctx.strokeStyle = theme.accent; ctx.lineWidth = 2; ctx.beginPath(); exact.forEach((v, i) => { const px = r.x + (i / K) * r.w; if (i) ctx.lineTo(px, py(v)); else ctx.moveTo(px, py(v)); }); ctx.stroke(); caption('θ₁ marginal: draws after warm-up (bars), exact (line)', r); } // θ₁ of each chain over its last TRACE_LEN draws, the modes' centers dashed function drawTrace() { const r = rects.trace; ctx.strokeStyle = theme.line; ctx.lineWidth = 1; ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1); const py = (x) => r.y + ((1 - x / view.X) / 2) * r.h; ctx.setLineDash([3, 4]); ctx.beginPath(); for (const m of [-params.mu / 2, params.mu / 2]) { ctx.moveTo(r.x, py(m)); ctx.lineTo(r.x + r.w, py(m)); } ctx.stroke(); ctx.setLineDash([]); const n = Math.max(0, ...chains.map((c) => c.hist.n)); const from = Math.max(0, n - TRACE_LEN); const px = (i) => r.x + ((i - from) / (TRACE_LEN - 1)) * r.w; ctx.save(); ctx.beginPath(); ctx.rect(r.x, r.y, r.w, r.h); ctx.clip(); // the end of warm-up, if in view const warm = Math.floor(n / 2); if (warm > from && n > 1) { ctx.strokeStyle = theme.muted; ctx.beginPath(); ctx.moveTo(px(warm), r.y); ctx.lineTo(px(warm), r.y + r.h); ctx.stroke(); } ctx.lineWidth = 1.2; for (const c of chains) { ctx.strokeStyle = chainColor(c.hue, 0.85); ctx.beginPath(); for (let i = from; i < c.hist.n; i++) { const y = py(clamp(c.hist.xs[2 * i], -1e6, 1e6)); if (i === from) ctx.moveTo(px(i), y); else ctx.lineTo(px(i), y); } ctx.stroke(); } ctx.restore(); caption(`θ₁ traces, last ${TRACE_LEN} draws${chains[0]?.hist.thin > 1 ? ` (every ${chains[0].hist.thin}th)` : ''}`, r); ctx.fillStyle = theme.muted; ctx.textAlign = 'right'; ctx.textBaseline = 'top'; ctx.fillText(`iteration ${chains[0]?.iters ?? 0}`, r.x + r.w, r.y + r.h + 4); ctx.textAlign = 'right'; ctx.textBaseline = 'middle'; ctx.fillText('θ₁', r.x - 8, r.y + r.h / 2); } // the hint: what is playing while listening back let hintText = ''; function showHint(now) { let text = 'Click to start every chain at a point'; if (cycle && running) { if (cycle.phase === 'replay' && now >= cycle.until - LISTEN.replay) { const a = cycle.start * cycle.thin; text = $('listen').value === 'shuffled' ? `◀ Listening back: random draws from the first half (iterations 0–${cycle.half * cycle.thin})` : `◀ Listening back: iterations ${a}–${a + Math.round(LISTEN.replay * tempo) * cycle.thin} (halfway back)`; } else if (cycle.phase === 'live') { text = '▶ Now: the chains as they run'; } else { text = '…'; } } if (text !== hintText) { hintText = text; $('hint').textContent = text; } } function frame() { requestAnimationFrame(frame); if (!canvas.width || !canvas.height) return; schedule(); const now = clock(); drawDue(now); if (now - statsAt > 0.25) { stats = chains.length ? computeStats() : null; statsAt = now; renderStats(); if (synth && drone) synth.setDrone(running ? Number($('drone').value) : 0, drone); } showHint(now); const dpr = devicePixelRatio || 1; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.fillStyle = theme.bg; ctx.fillRect(0, 0, canvas.width, canvas.height); ctx.drawImage(densityLayer, 0, 0); ctx.drawImage(dotsLayer, 0, 0); ctx.setTransform(dpr, 0, 0, dpr, 0, 0); drawAxes(); drawStarts(); drawChains(now); drawHist(); drawTrace(); } // ---- controls ------------------------------------------------------------------------ // a group of sliders over the values in obj; onInput(key) after each change function buildSliders(container, specs, obj, onInput) { const toInput = (s, v) => (s.log ? Math.round((1000 * Math.log(v / s.min)) / Math.log(s.max / s.min)) : v); const fromInput = (s, u) => (s.log ? s.min * (s.max / s.min) ** (u / 1000) : u); container.innerHTML = specs.map((s) => ` `).join(''); const rows = new Map([...container.children].map((row) => [row.dataset.key, row])); const show = () => { for (const s of specs) { const row = rows.get(s.key); row.querySelector('input').value = toInput(s, obj[s.key]); row.querySelector('output').textContent = s.fmt(obj[s.key]); if (s.only) row.hidden = !s.only.includes(tune.kind); } }; for (const s of specs) { const row = rows.get(s.key); row.querySelector('input').addEventListener('input', (e) => { let v = fromInput(s, Number(e.target.value)); if (s.log) v = Number(v.toPrecision(2)); obj[s.key] = v; row.querySelector('output').textContent = s.fmt(v); onInput(s.key); }); } show(); return show; } function buildControls() { const presetSel = $('preset'); presetSel.innerHTML = PRESETS.map((pr, i) => ``).join('') + ''; const showModel = buildSliders($('model-sliders'), MODEL_SLIDERS, params, (k) => { if (k === 'tau') { // only the starts change, not the target model.tau = params.tau; layout(); renderDensity(); redrawDots(); return; } presetSel.value = 'custom'; applyModel(); newSegment(); }); presetSel.addEventListener('change', () => { if (presetSel.value === 'custom') return; Object.assign(params, BASE, PRESETS[presetSel.value].p); showModel(); applyModel(); newSegment(); }); const showSampler = buildSliders($('sampler-sliders'), SAMPLER_SLIDERS, tune, retune); $('sampler').addEventListener('change', (e) => { tune.kind = e.target.value; showSampler(); rebuildSamplers(); }); buildSliders($('chain-sliders'), CHAIN_SLIDERS, tune, () => setChainCount(tune.count)); $('run').addEventListener('click', () => setRunning(!running)); $('restart').addEventListener('click', () => { startPoint = null; restart(); }); $('skip').addEventListener('click', skipAhead); $('scale').innerHTML = SCALES.map((s) => `${s.name}`).join(''); $('keys').innerHTML = KEYS.map((k, i) => ``).join(''); $('keys').addEventListener('click', (e) => { const btn = e.target.closest('button[data-key]'); if (!btn) return; key = Number(btn.dataset.key); for (const b of $('keys').children) b.setAttribute('aria-pressed', b === btn); synth?.setDroneRoot(droneRoot()); }); // tempo on a log scale, TEMPO.min to TEMPO.max iterations per second const tmp = $('tempo'); const span = Math.log(TEMPO.max / TEMPO.min); tmp.value = Math.round((1000 * Math.log(tempo / TEMPO.min)) / span); const tempoOut = () => { tmp.nextElementSibling.textContent = `${tempo} /s`; }; tmp.addEventListener('input', () => { tempo = Math.round(TEMPO.min * Math.exp((Number(tmp.value) / 1000) * span)); tempoOut(); }); tempoOut(); const sus = $('sustain'); Object.assign(sus, { min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, value: SUSTAIN.default }); const susOut = () => { sus.nextElementSibling.textContent = `${Number(sus.value).toFixed(1)} s`; }; sus.addEventListener('input', () => { susOut(); synth?.setSustain(Number(sus.value)); }); susOut(); const dr = $('drone'); const drOut = () => { dr.nextElementSibling.textContent = Number(dr.value) ? `${Math.round(100 * dr.value)}%` : 'off'; }; dr.addEventListener('input', () => { drOut(); if (synth && drone) synth.setDrone(running ? Number(dr.value) : 0, drone); }); drOut(); const vol = $('volume'); const volOut = () => { vol.nextElementSibling.textContent = `${Math.round(100 * vol.value)}%`; }; vol.addEventListener('input', () => { volOut(); if (synth && soundOn) synth.setVolume(Number(vol.value)); }); volOut(); $('sound').addEventListener('click', () => setSound(!soundOn)); // a click in the plane starts every chain there canvas.addEventListener('pointerdown', (e) => { const rect = canvas.getBoundingClientRect(); const r = rects.main; const px = e.clientX - rect.left; const py = e.clientY - rect.top; if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) return; startPoint = [((px - r.x) / r.w * 2 - 1) * view.X, (1 - (py - r.y) / r.h * 2) * view.Y]; restart(); }); } readTheme(); matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); }); buildControls(); applyModel(); restart(); new ResizeObserver(resize).observe(canvas); resize(); requestAnimationFrame(frame);