/ interactive_tutorials / mcmc_sonification
Sign in
interactive_tutorials / mcmc_sonification
mcmc_sonification / app / main.js
1046 lines · 38.7 KBCodeBlameHistory
726adb6Listening for convergence: MCMC chains on a 2D mixture, sonifiedJeremy Magland 1// Listening for convergence: several MCMC chains on a 2D two-component
2// normal mixture (js/mixture.js, a port of mixture_mcmc.py), each playing a
3// note per iteration (js/voices.js), so you can hear whether they have
4// reached the stationary distribution.
5//
6// - All chains run the same sampler with the same tuning (random-walk
7// Metropolis, MALA, ULA, generalized HMC or HMC), each from its own start
8// and seed: by default random points on the circle of radius τ, or, after
9// a click, all from the clicked point.
10// - Each iteration, each chain plays a note, all with the same sound: pitch
11// from θ₁ (left to right over three octaves of the chosen scale, the range
12// set by the target, not the window), timbre from θ₂ (a soft pure tone at
13// the bottom, a bright buzzy one at the top), and each chain at its own
14// place in the stereo field.
15// A rejected step repeats the note softly (or is silent). Mixed chains
16// wander over both modes and play in the same register; stuck chains
17// drone on in one. Past MAX_NOTE_RATE notes per second (many chains, fast
18// tempo), the chains take turns: each plays every stride-th iteration.
19// - Pitch and timbre from rank (optional): instead of θ itself, its rank
20// among the pooled draws after warm-up (a sample of REF_SIZE of them,
21// refreshed with the statistics). Needs no knowledge of the target: mixed
22// chains each play evenly over the whole range, alike; a stuck chain keeps
23// to part of it.
24// - The agreement drone: under the notes, per chain, a soft tone at the
25// key's root (for θ₁) and one at its fifth (for θ₂), each detuned by how
26// far the chain's mean after warm-up is from the pooled mean, in pooled
27// standard deviations z (400 z² cents, up to an octave). Chains that
28// disagree beat and clash; as they agree (split R̂ towards 1), the drone
29// settles into unison.
30// - Listen back (optional): LISTEN.live s of the chains as they run, a short
31// gap, LISTEN.replay s replayed from the history halfway back (or, shuffled,
32// random draws from its first half), a gap, and live again. The replay is
33// heard, not shown: the plane holds still meanwhile.
34// - Below the plane: the θ₁ marginal of the draws after warm-up (the first
35// half of each chain) against the exact one, and the θ₁ traces; in the
36// panel, the moments of the draws against the exact ones, split R̂, and
37// each chain's acceptance rate.
38// - Changing the target or the sampler keeps the chains where they are and
39// starts a fresh set of draws (the old ones were for other settings).
41import { GeneralizedHMC, HMC, Langevin, NormalMixture2D, RandomWalkMetropolis } from './js/mixture.js';
42import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN } from './js/voices.js';
44// the five targets of the notes (mixture_mcmc.md, "Interesting settings")
45const BASE = { mu: 4, s11: 1, s12: 1, s21: 1, s22: 1, r1: 0, r2: 0 };
46const PRESETS = [
47 { name: 'Easy: overlapping modes', p: { mu: 3 } },
48 { name: 'Separated: a low-density gap', p: { mu: 6 } },
49 { name: 'Ridge: crossed thin ridges', p: { mu: 4, r1: 0.95, r2: -0.95 } },
50 { name: 'Stiff: a wide mode and a needle', p: { mu: 4, s21: 0.1, s22: 0.1 } },
51 { name: 'Crossed: a horizontal and a vertical bar', p: { mu: 4, s11: 2, s12: 0.25, s21: 0.25, s22: 2 } },
52];
53const DEFAULT_PRESET = 1;
55const MAX_CHAINS = 32;
56const HIST_CAP = 1 << 17; // draws kept per chain; past it, thinned by 2
57const LOOKAHEAD = 0.12; // s of iterations scheduled ahead
58const TAIL = 0.3; // s of trail (at least 6 iterations)
59const TRACE_LEN = 1000; // draws in the trace plot
60const TEMPO = { min: 1, max: 400, default: 50 }; // iterations per second
61const MAX_NOTE_RATE = 800; // notes per second, over all chains
62const BINS = 64;
63const SKIP = 1000; // iterations per "+1000"
64const MARGIN = { left: 48, right: 12, top: 10 };
65const REF_SIZE = 4000; // pooled draws ranks are taken against
66const LISTEN = { live: 3, gap: 0.6, replay: 3 }; // s
68const $ = (id) => document.getElementById(id);
69const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
70const fmt2 = (v) => (v >= 1 ? v.toFixed(2) : v.toPrecision(2));
72// sliders: linear, or log (min > 0) over an integer 0..1000 input
73const MODEL_SLIDERS = [
74 { key: 'mu', label: 'μ', min: 0.5, max: 10, step: 0.1, fmt: (v) => v.toFixed(1) },
75 { key: 's11', label: 'σ<sub>11</sub>', min: 0.05, max: 4, log: true, fmt: fmt2 },
76 { key: 's12', label: 'σ<sub>12</sub>', min: 0.05, max: 4, log: true, fmt: fmt2 },
77 { key: 's21', label: 'σ<sub>21</sub>', min: 0.05, max: 4, log: true, fmt: fmt2 },
78 { key: 's22', label: 'σ<sub>22</sub>', min: 0.05, max: 4, log: true, fmt: fmt2 },
79 { key: 'r1', label: 'ρ<sub>1</sub>', min: -0.99, max: 0.99, step: 0.01, fmt: (v) => v.toFixed(2) },
80 { key: 'r2', label: 'ρ<sub>2</sub>', min: -0.99, max: 0.99, step: 0.01, fmt: (v) => v.toFixed(2) },
81 { key: 'tau', label: 'τ (starts)', min: 0.1, max: 8, step: 0.1, fmt: (v) => v.toFixed(1) },
82];
83const SAMPLER_SLIDERS = [
84 { key: 'eps', label: 'Step ε', min: 0.01, max: 5, log: true, fmt: fmt2 },
85 { key: 'gamma', label: 'Refresh γ', min: 0.001, max: 1, log: true, fmt: fmt2, only: ['ghmc'] },
86 { key: 'L', label: 'Leapfrog L', min: 1, max: 100, step: 1, fmt: (v) => String(v), only: ['hmc'] },
87];
88const CHAIN_SLIDERS = [
89 { key: 'count', label: 'Chains', min: 1, max: MAX_CHAINS, step: 1, fmt: (v) => String(v) },
90];
92const params = { ...BASE, ...PRESETS[DEFAULT_PRESET].p, tau: 1 };
93const tune = { kind: 'rwm', eps: 1, gamma: 0.1, L: 10, count: 8 };
95const canvas = $('plot');
96const ctx = canvas.getContext('2d');
97const densityLayer = document.createElement('canvas');
98const dotsLayer = document.createElement('canvas');
100const model = new NormalMixture2D();
101let range; // { X0, Y0 }: the θ₁, θ₂ half-ranges of pitch and timbre
102let view; // { X, Y }: the half-ranges shown (equal scales)
103let rects; // { main, hist, trace } in CSS px
104let chains = [];
105let startPoint = null; // null: starts on the τ circle; else [θ₁, θ₂]
106let running = false; // paused until Run is pressed
107let nextBeat = 0;
108let beat = 0; // iterations scheduled so far, for the chains' turns
109let tempo = TEMPO.default;
110let synth = null;
111let soundOn = false;
112let key = DEFAULT_KEY;
113let stats = null;
114let statsAt = -Infinity;
115let theme;
116let ref = null; // sorted samples of the pooled θ₁ and θ₂, for ranks
117let cycle = null; // listen back: { phase, until, ... }; null when off
118let drone = null; // per chain detunes (cents), [θ₁ layer, θ₂ layer]
120// ---- chains -------------------------------------------------------------------
122function makeSampler(theta0) {
123 const seed = (Math.random() * 2 ** 32) >>> 0;
124 const opts = { theta0, seed };
125 switch (tune.kind) {
126 case 'mala': return new Langevin(model, tune.eps, { ...opts, adjust: true });
127 case 'ula': return new Langevin(model, tune.eps, { ...opts, adjust: false });
128 case 'ghmc': return new GeneralizedHMC(model, tune.eps, { ...opts, gamma: tune.gamma });
129 case 'hmc': return new HMC(model, tune.eps, { ...opts, nSteps: tune.L });
130 default: return new RandomWalkMetropolis(model, tune.eps, opts);
131 }
134const newHistory = () => ({ xs: new Float32Array(2 * HIST_CAP), n: 0, thin: 1, since: 0 });
136function record(h, [x, y]) {
137 if (++h.since < h.thin) return;
138 h.since = 0;
139 if (h.n === HIST_CAP) {
140 for (let i = 0; i < HIST_CAP / 2; i++) {
141 h.xs[2 * i] = h.xs[4 * i];
142 h.xs[2 * i + 1] = h.xs[4 * i + 1];
143 }
144 h.n = HIST_CAP / 2;
145 h.thin *= 2;
146 }
147 h.xs[2 * h.n] = x;
148 h.xs[2 * h.n + 1] = y;
149 h.n++;
152const hueOf = (k) => (0.08 + k * 0.382) % 1;
154function newChain(k, theta0) {
155 return { k, hue: hueOf(k), sampler: makeSampler(theta0), hist: newHistory(), queue: [], iters: 0, acc: 0 };
158function startOf() {
159 return startPoint ? startPoint.slice() : null;
162// spread the chains over the stereo field
163function setPans() {
164 const n = chains.length;
165 for (const c of chains) c.pan = n > 1 ? -0.6 + (1.2 * c.k) / (n - 1) : 0;
168// a fresh set of draws, the chains staying where they are
169function newSegment() {
170 for (const c of chains) {
171 c.hist = newHistory();
172 c.iters = c.acc = 0;
173 }
174 clearLayer(dotsLayer);
175 stats = null;
176 statsAt = -Infinity;
179// all chains from new starts (the τ circle, or the clicked point)
180function restart() {
181 chains = Array.from({ length: tune.count }, (_, k) => newChain(k, startOf()));
182 setPans();
183 newSegment();
186function setChainCount(n) {
187 if (n < chains.length) chains = chains.slice(0, n);
188 while (chains.length < n) chains.push(newChain(chains.length, startOf()));
189 setPans();
190 newSegment();
193// the sampler changed kind: new samplers from where the chains are
194function rebuildSamplers() {
195 for (const c of chains) c.sampler = makeSampler(c.sampler.theta.slice());
196 newSegment();
199function retune() {
200 for (const c of chains) {
201 c.sampler.stepSize = tune.eps;
202 if (tune.kind === 'ghmc') c.sampler.gamma = tune.gamma;
203 if (tune.kind === 'hmc') c.sampler.nSteps = tune.L;
204 }
205 newSegment();
208// one iteration of chain c, recorded; returns the event for drawing and sound
209function stepChain(c, time) {
210 const s = c.sampler;
211 const from = s.theta.slice();
212 const theta = s.next();
213 c.iters++;
214 c.acc += s.accepted ? 1 : 0;
215 record(c.hist, theta);
216 return {
217 time, from, theta,
218 proposal: s.proposal.slice(),
219 path: tune.kind === 'hmc' ? s.path : null,
220 accepted: Boolean(s.accepted),
221 diverged: Boolean(s.diverged),
222 drawn: false,
223 };
226// ---- the target ---------------------------------------------------------------------
228function applyModel() {
229 model.set({
230 mu: params.mu,
231 sigma: [[params.s11, params.s12], [params.s21, params.s22]],
232 rho: [params.r1, params.r2],
233 tau: params.tau,
234 });
235 const X0 = params.mu / 2 + 3.2 * Math.max(params.s11, params.s21);
236 const Y0 = 3.2 * Math.max(params.s12, params.s22);
237 range = { X0, Y0 };
238 $('limit').textContent = `Stability limit of leapfrog and Langevin: ε < ${fmt2(model.maxStableStepSize())}`;
239 layout();
240 renderDensity();
243// ---- sound -------------------------------------------------------------------------
245const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
246const beatDt = () => 1 / tempo;
248// the rank of v in a sorted sample, in [0, 1] (ties: their middle)
249function rankOf(sorted, v) {
250 let lo = 0, hi = sorted.length;
251 while (lo < hi) { const m = (lo + hi) >> 1; if (sorted[m] < v) lo = m + 1; else hi = m; }
252 let up = lo;
253 while (up < sorted.length && sorted[up] === v) up++;
254 return (lo + up) / 2 / sorted.length;
257// a draw's place on the pitch and timbre scales, both in [0, 1]: from θ over
258// the target's range, or from its rank among the pooled draws
259function placeOf([x, y]) {
260 if ($('pitch-map').value === 'rank' && ref) return [rankOf(ref.x, x), rankOf(ref.y, y)];
261 return [(x + range.X0) / (2 * range.X0), clamp((y + range.Y0) / (2 * range.Y0), 0, 1)];
264function playNote(c, theta, accepted, time, gain) {
265 const [x, y] = theta;
266 if (!Number.isFinite(x) || !Number.isFinite(y)) return;
267 if (!accepted && $('rejected').value === 'silent') return;
268 const scale = SCALES[$('scale').selectedIndex];
269 const [u, bright] = placeOf(theta);
270 synth.play(pitchOf(u, scale, key), time, { pan: c.pan, gain: gain * (accepted ? 1 : 0.3), bright });
273// the next phase of listening back, from time t = cycle.until; a replay
274// needs three times its length of history (so it is clear of the live
275// stretch just heard), else the chains play on live
276function advanceCycle(t) {
277 const len = Math.round(LISTEN.replay * tempo);
278 const n = Math.min(...chains.map((c) => c.hist.n));
279 switch (cycle.phase) {
280 case 'live':
281 cycle = n >= 3 * len ? { phase: 'gap', next: 'replay', until: t + LISTEN.gap } : { phase: 'live', until: t + LISTEN.live };
282 break;
283 case 'gap':
284 if (cycle.next === 'replay') {
285 // from halfway back: the draws centered on the middle of the history
286 const start = Math.floor((n - len) / 2);
287 cycle = { phase: 'replay', until: t + LISTEN.replay, start, half: Math.floor(n / 2), j: 0, thin: chains[0].hist.thin };
288 } else {
289 cycle = { phase: 'live', until: t + LISTEN.live };
290 }
291 break;
292 default:
293 cycle = { phase: 'gap', next: 'live', until: t + LISTEN.gap };
294 }
297// step every chain at each beat due within LOOKAHEAD, playing its note
298function schedule() {
299 const now = clock();
300 // fallen behind (a stalled frame, a hidden tab), or paused: carry on from
301 // now rather than catch up in a burst
302 if (nextBeat < now) nextBeat = now + 0.02;
303 if (!running) return;
304 const dt = beatDt();
305 // the chains' turns, and the level: softer the more notes overlap (about
306 // the notes per second that sound, times 0.15 s)
307 const stride = Math.ceil((chains.length * tempo) / MAX_NOTE_RATE);
308 const rate = (chains.length * tempo) / stride;
309 const gain = 1 / Math.sqrt(Math.max(chains.length, 0.15 * rate));
310 const listen = $('listen').value;
311 if (listen === 'off' || !soundOn) cycle = null;
312 else if (!cycle) cycle = { phase: 'live', until: nextBeat + LISTEN.live };
313 while (nextBeat < now + LOOKAHEAD) {
314 if (cycle && nextBeat >= cycle.until) advanceCycle(cycle.until);
315 const phase = cycle ? cycle.phase : 'live';
316 const plays = (c) => soundOn && synth && (beat + c.k) % stride === 0;
317 if (phase === 'live') {
318 for (const c of chains) {
319 const ev = stepChain(c, nextBeat);
320 c.queue.push(ev);
321 if (plays(c) && !ev.diverged) playNote(c, ev.theta, ev.accepted, nextBeat, gain);
322 }
323 } else if (phase === 'replay') {
324 // the recorded draws (a repeat of the one before was a rejection), or
325 // random ones from the first half
326 for (const c of chains) {
327 const h = c.hist;
328 const i = listen === 'shuffled' ? Math.floor(Math.random() * cycle.half) : Math.min(h.n - 1, cycle.start + cycle.j);
329 const theta = [h.xs[2 * i], h.xs[2 * i + 1]];
330 const accepted = listen === 'shuffled' || i === 0 || theta[0] !== h.xs[2 * i - 2] || theta[1] !== h.xs[2 * i - 1];
331 if (plays(c)) playNote(c, theta, accepted, nextBeat, gain);
332 }
333 cycle.j++;
334 }
335 nextBeat += dt;
336 beat++;
337 }
340function setSound(on) {
341 soundOn = on;
342 const btn = $('sound');
343 btn.setAttribute('aria-pressed', on);
344 btn.querySelector('.icon').textContent = on ? '🔊' : '🔇';
345 btn.querySelector('.label').textContent = on ? 'Sound on' : 'Turn sound on';
346 if (on && !synth) {
347 // the clock switches to the audio context's
348 synth = createSynth();
349 synth.setSustain(Number($('sustain').value));
350 synth.setDroneRoot(droneRoot());
351 for (const c of chains) c.queue = [];
352 nextBeat = 0;
353 }
354 if (synth) {
355 synth.ctx.resume();
356 synth.setVolume(on ? Number($('volume').value) : 0);
357 }
360function setRunning(on) {
361 running = on;
362 cycle = null;
363 const btn = $('run');
364 btn.setAttribute('aria-pressed', on);
365 btn.textContent = on ? '❚❚ Pause' : '▶ Run';
368// SKIP iterations of every chain at once, silently
369function skipAhead() {
370 const r = rects.main;
371 const dctx = dotsLayer.getContext('2d');
372 for (const c of chains) {
373 dctx.fillStyle = chainColor(c.hue, 0.35);
374 for (let i = 0; i < SKIP; i++) {
375 const ev = stepChain(c, 0);
376 drawDot(dctx, r, ev.theta);
377 }
378 c.queue = [];
379 }
380 statsAt = -Infinity;
383// ---- statistics ----------------------------------------------------------------------
385// split R̂ (Gelman et al., BDA3): each chain halved, between- against
386// within-half variance
387function splitRhat(seqs) {
388 const halves = [];
389 for (const s of seqs) {
390 const h = Math.floor(s.length / 2);
391 if (h < 2) return NaN;
392 halves.push(s.subarray(0, h), s.subarray(s.length - h));
393 }
394 const n = halves[0].length;
395 const m = halves.length;
396 const means = halves.map((h) => h.reduce((a, v) => a + v, 0) / n);
397 const vars = halves.map((h, i) => h.reduce((a, v) => a + (v - means[i]) ** 2, 0) / (n - 1));
398 const W = vars.reduce((a, v) => a + v, 0) / m;
399 const mbar = means.reduce((a, v) => a + v, 0) / m;
400 const B = (n / (m - 1)) * means.reduce((a, v) => a + (v - mbar) ** 2, 0);
401 return Math.sqrt((((n - 1) / n) * W + B / n) / W);
404// the draws after warm-up (the second half of each chain), pooled
405function computeStats() {
406 const n = Math.min(...chains.map((c) => c.hist.n));
407 const start = Math.floor(n / 2);
408 const kept = n - start;
409 const s1 = [], s2 = [];
410 let m1 = 0, m2 = 0, q11 = 0, q22 = 0, q12 = 0, right = 0, N = 0;
411 const counts = new Float64Array(BINS);
412 for (const c of chains) {
413 const a = new Float64Array(kept), b = new Float64Array(kept);
414 for (let i = 0; i < kept; i++) {
415 const x = c.hist.xs[2 * (start + i)];
416 const y = c.hist.xs[2 * (start + i) + 1];
417 a[i] = x; b[i] = y;
418 m1 += x; m2 += y; q11 += x * x; q22 += y * y; q12 += x * y;
419 right += x > 0;
420 N++;
421 const bin = Math.floor(((x + view.X) / (2 * view.X)) * BINS);
422 if (bin >= 0 && bin < BINS) counts[bin]++;
423 }
424 s1.push(a); s2.push(b);
425 }
426 const iters = chains[0]?.iters ?? 0;
427 if (!N) {
428 ref = null;
429 drone = droneOf(chains.map((c) => [c.sampler.theta[0]]), chains.map((c) => [c.sampler.theta[1]]));
430 return { iters, kept: 0 };
431 }
432 m1 /= N; m2 /= N;
433 // the reference for ranks: a random sample of the pooled draws, sorted
434 if (N >= 20) {
435 const R = Math.min(REF_SIZE, N);
436 const rx = new Float64Array(R), ry = new Float64Array(R);
437 for (let j = 0; j < R; j++) {
438 const k = Math.floor(Math.random() * chains.length);
439 const i = Math.floor(Math.random() * kept);
440 rx[j] = s1[k][i];
441 ry[j] = s2[k][i];
442 }
443 ref = { x: rx.sort(), y: ry.sort() };
444 } else {
445 ref = null;
446 }
447 drone = droneOf(s1, s2);
448 const binW = (2 * view.X) / BINS;
449 return {
450 iters, kept,
451 mean: [m1, m2],
452 cov: [[q11 / N - m1 * m1, q12 / N - m1 * m2], [0, q22 / N - m2 * m2]],
453 right: right / N,
454 rhat: [splitRhat(s1), splitRhat(s2)],
455 hist: Array.from(counts, (k) => k / (N * binW)),
456 };
459// the drone's detunes (cents) per chain, for θ₁ and θ₂: 400 z² (signed, up
460// to an octave), z the chain's mean from the pooled mean in pooled standard
461// deviations (from the chains' current points before there are draws)
462function droneOf(s1, s2) {
463 return [s1, s2].map((seqs) => {
464 const means = seqs.map((a) => a.reduce((p, v) => p + v, 0) / a.length);
465 const all = seqs.flatMap((a) => Array.from(a));
466 const m = all.reduce((p, v) => p + v, 0) / all.length;
467 const sd = Math.sqrt(all.reduce((p, v) => p + (v - m) ** 2, 0) / all.length) || 1;
468 return means.map((mk) => {
469 const z = (mk - m) / sd;
470 return Number.isFinite(z) ? Math.sign(z) * Math.min(1200, 400 * z * z) : 1200;
471 });
472 });
475const droneRoot = () => 130.81 * 2 ** (key / 12); // the key's root, C3 to B3
477function num(v, d = 2) {
478 if (!Number.isFinite(v)) return '—';
479 if (Math.abs(v) < 1e-9) v = 0;
480 return (Math.abs(v) < 1e4 ? v.toFixed(d) : v.toExponential(1)).replace(/^-/, '−');
483function renderStats() {
484 const t = model.truth();
485 const st = stats ?? { iters: 0, kept: 0 };
486 $('draws-note').textContent = `· ${st.iters} per chain, the first half warm-up`;
487 const has = st.kept > 0;
488 const rows = [
489 ['mean θ₁', has ? num(st.mean[0]) : '—', '0'],
490 ['mean θ₂', has ? num(st.mean[1]) : '—', '0'],
491 ['var θ₁', has ? num(st.cov[0][0]) : '—', num(t.cov[0][0])],
492 ['var θ₂', has ? num(st.cov[1][1]) : '—', num(t.cov[1][1])],
493 ['cov', has ? num(st.cov[0][1]) : '—', num(t.cov[0][1])],
494 ['P(θ₁ > 0)', has ? num(st.right) : '—', num(t.right)],
495 ];
496 const rh = (v) => {
497 const off = !Number.isFinite(v) || v > 1.05;
498 return `<td class="${has && off ? 'off' : ''}">${has ? num(v) : '—'}</td>`;
499 };
500 $('stats').innerHTML = '<tr><th></th><th>draws</th><th>exact</th></tr>'
501 + rows.map(([a, b, c]) => `<tr><td>${a}</td><td>${b}</td><td>${c}</td></tr>`).join('')
502 + `<tr><td>split R̂ θ₁</td>${rh(st.rhat?.[0])}<td>1</td></tr>`
503 + `<tr><td>split R̂ θ₂</td>${rh(st.rhat?.[1])}<td>1</td></tr>`;
504 $('chain-list').innerHTML = chains.map((c) => `
505 <li>
506 <span class="swatch" style="background: ${chainColor(c.hue)}"></span>
507 <span class="acc">${c.iters ? Math.round((100 * c.acc) / c.iters) : '–'}%</span>
508 </li>`).join('');
511// ---- drawing ------------------------------------------------------------------------
513function readTheme() {
514 const cs = getComputedStyle(document.documentElement);
515 const v = (name) => cs.getPropertyValue(name).trim();
516 theme = { bg: v('--bg'), fg: v('--fg'), muted: v('--muted'), line: v('--line'), accent: v('--accent'), density: v('--density'), light: v('--dot-light') };
519const chainColor = (hue, alpha = 1) => `hsla(${Math.round(hue * 360)}, 80%, ${theme.light}, ${alpha})`;
521function clearLayer(layer) {
522 const dpr = devicePixelRatio || 1;
523 const c = layer.getContext('2d');
524 c.setTransform(1, 0, 0, 1, 0, 0);
525 c.clearRect(0, 0, layer.width, layer.height);
526 c.setTransform(dpr, 0, 0, dpr, 0, 0);
529// the plane on top, then the θ₁ marginal, then the traces; the view of the
530// plane has equal scales on both axes and frames the target and the τ circle
531function layout() {
532 const dpr = devicePixelRatio || 1;
533 const W = canvas.width / dpr;
534 const H = canvas.height / dpr;
535 const traceH = clamp(0.19 * H, 70, 140);
536 const histH = clamp(0.13 * H, 50, 100);
537 const w = Math.max(10, W - MARGIN.left - MARGIN.right);
538 const mainH = Math.max(10, H - MARGIN.top - 26 - histH - 18 - traceH - 22);
539 const main = { x: MARGIN.left, y: MARGIN.top, w, h: mainH };
540 const hist = { x: MARGIN.left, y: main.y + mainH + 26, w, h: histH };
541 const trace = { x: MARGIN.left, y: hist.y + histH + 18, w, h: traceH };
542 rects = { main, hist, trace };
543 const needX = Math.max(range.X0, 1.15 * params.tau);
544 const needY = Math.max(range.Y0, 1.15 * params.tau);
545 const s = Math.min(main.w / (2 * needX), main.h / (2 * needY));
546 view = { X: main.w / (2 * s), Y: main.h / (2 * s) };
549const toPx = (r, [x, y]) => [r.x + ((x / view.X + 1) / 2) * r.w, r.y + ((1 - y / view.Y) / 2) * r.h];
551function drawDot(dctx, r, theta) {
552 if (!Number.isFinite(theta[0]) || !Number.isFinite(theta[1])) return;
553 const [px, py] = toPx(r, theta);
554 if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) return;
555 dctx.fillRect(px - 0.9, py - 0.9, 1.8, 1.8);
558// the density, shaded on a log scale over 3.5 decades below its peak
559function renderDensity() {
560 clearLayer(densityLayer);
561 if (!rects) return;
562 const r = rects.main;
563 const gw = Math.max(2, Math.ceil(r.w / 3));
564 const gh = Math.max(2, Math.ceil(r.h / 3));
565 const img = new ImageData(gw, gh);
566 const hex = theme.density.replace('#', '');
567 const rgb = [0, 2, 4].map((i) => parseInt(hex.slice(i, i + 2), 16));
568 const logMax = Math.max(...model.means.map((m) => model.logDensity(m)));
569 for (let j = 0; j < gh; j++) {
570 const y = view.Y * (1 - (2 * (j + 0.5)) / gh);
571 for (let i = 0; i < gw; i++) {
572 const x = view.X * ((2 * (i + 0.5)) / gw - 1);
573 const t = clamp(1 + (model.logDensity([x, y]) - logMax) / (3.5 * Math.LN10), 0, 1);
574 const o = 4 * (j * gw + i);
575 img.data[o] = rgb[0]; img.data[o + 1] = rgb[1]; img.data[o + 2] = rgb[2];
576 img.data[o + 3] = Math.round(255 * 0.42 * t ** 1.4);
577 }
578 }
579 const tmp = document.createElement('canvas');
580 tmp.width = gw;
581 tmp.height = gh;
582 tmp.getContext('2d').putImageData(img, 0, 0);
583 const dctx = densityLayer.getContext('2d');
584 dctx.imageSmoothingEnabled = true;
585 dctx.drawImage(tmp, r.x, r.y, r.w, r.h);
588function redrawDots() {
589 clearLayer(dotsLayer);
590 const dctx = dotsLayer.getContext('2d');
591 for (const c of chains) {
592 dctx.fillStyle = chainColor(c.hue, 0.35);
593 for (let i = 0; i < c.hist.n; i++) drawDot(dctx, rects.main, [c.hist.xs[2 * i], c.hist.xs[2 * i + 1]]);
594 }
597function resize() {
598 const dpr = devicePixelRatio || 1;
599 const { width, height } = canvas.getBoundingClientRect();
600 canvas.width = densityLayer.width = dotsLayer.width = Math.round(width * dpr);
601 canvas.height = densityLayer.height = dotsLayer.height = Math.round(height * dpr);
602 layout();
603 renderDensity();
604 redrawDots();
605 statsAt = -Infinity;
608// the dots of the iterations that have come due; the queues trimmed to the
609// trail
610function drawDue(now) {
611 const dctx = dotsLayer.getContext('2d');
612 const keep = trailTime() + 2 * beatDt();
613 for (const c of chains) {
614 dctx.fillStyle = chainColor(c.hue, 0.35);
615 for (const ev of c.queue) {
616 if (ev.time > now) break;
617 if (!ev.drawn) { drawDot(dctx, rects.main, ev.theta); ev.drawn = true; }
618 }
619 while (c.queue.length > 1 && c.queue[1].time < now - keep) c.queue.shift();
620 }
623const trailTime = () => Math.max(TAIL, 6 * beatDt());
625function niceStep(span) {
626 const raw = span / 5;
627 const p = 10 ** Math.floor(Math.log10(raw));
628 return [1, 2, 5, 10].map((m) => m * p).find((s) => s >= raw);
631function drawAxes() {
632 const r = rects.main;
633 ctx.strokeStyle = theme.line;
634 ctx.lineWidth = 1;
635 ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
636 ctx.fillStyle = theme.muted;
637 ctx.font = '12px "Hanken Grotesk", system-ui, sans-serif';
638 const step = niceStep(2 * Math.min(view.X, view.Y));
639 ctx.textBaseline = 'top';
640 ctx.textAlign = 'center';
641 ctx.beginPath();
642 for (let x = Math.ceil(-view.X / step) * step; x <= view.X; x += step) {
643 const [px] = toPx(r, [x, 0]);
644 ctx.moveTo(px, r.y + r.h);
645 ctx.lineTo(px, r.y + r.h + 4);
646 ctx.fillText(num(x, step < 1 ? 1 : 0), px, r.y + r.h + 5);
647 }
648 ctx.textAlign = 'right';
649 ctx.textBaseline = 'middle';
650 for (let y = Math.ceil(-view.Y / step) * step; y <= view.Y; y += step) {
651 const [, py] = toPx(r, [0, y]);
652 ctx.moveTo(r.x - 4, py);
653 ctx.lineTo(r.x, py);
654 ctx.fillText(num(y, step < 1 ? 1 : 0), r.x - 6, py);
655 }
656 ctx.stroke();
657 // the axis names, inside the plane's corners, clear of the tick labels
658 ctx.textAlign = 'right';
659 ctx.textBaseline = 'bottom';
660 ctx.fillText('θ₁ → pitch', r.x + r.w - 6, r.y + r.h - 4);
661 ctx.save();
662 ctx.translate(r.x + 6, r.y + r.h - 4);
663 ctx.rotate(-Math.PI / 2);
664 ctx.textAlign = 'left';
665 ctx.textBaseline = 'top';
666 ctx.fillText('θ₂ → timbre: pure to buzzy', 0, 0);
667 ctx.restore();
670function drawStarts() {
671 const r = rects.main;
672 ctx.save();
673 ctx.strokeStyle = theme.muted;
674 ctx.lineWidth = 1;
675 if (startPoint) {
676 const [px, py] = toPx(r, startPoint);
677 ctx.beginPath();
678 ctx.moveTo(px - 7, py); ctx.lineTo(px + 7, py);
679 ctx.moveTo(px, py - 7); ctx.lineTo(px, py + 7);
680 ctx.stroke();
681 } else {
682 const [cx, cy] = toPx(r, [0, 0]);
683 const rad = (params.tau / view.X) * (r.w / 2);
684 ctx.setLineDash([3, 4]);
685 ctx.beginPath();
686 ctx.arc(cx, cy, rad, 0, 2 * Math.PI);
687 ctx.stroke();
688 }
689 ctx.restore();
692// each chain: a fading trail of its last positions, its last proposal (the
693// HMC trajectory, or a line), crossed out if rejected, its current point,
694// and a ring at each note
695function drawChains(now) {
696 const r = rects.main;
697 const dt = beatDt();
698 ctx.save();
699 ctx.beginPath();
700 ctx.rect(r.x, r.y, r.w, r.h);
701 ctx.clip();
702 ctx.lineCap = 'round';
703 ctx.lineJoin = 'round';
704 for (const c of chains) {
705 const due = c.queue.filter((ev) => ev.time <= now);
706 const cur = due[due.length - 1];
707 const head = cur ? cur.theta : c.sampler.theta;
708 // trail
709 for (let i = 1; i < due.length; i++) {
710 const alpha = 0.7 * (1 - (now - due[i].time) / trailTime());
711 if (alpha <= 0 || !due[i].accepted) continue;
712 ctx.strokeStyle = chainColor(c.hue, alpha);
713 ctx.lineWidth = 1.5;
714 ctx.beginPath();
715 ctx.moveTo(...toPx(r, due[i - 1].theta));
716 ctx.lineTo(...toPx(r, due[i].theta));
717 ctx.stroke();
718 }
719 if (cur) {
720 const g = (now - cur.time) / Math.max(dt, 0.15);
721 if (g < 1) {
722 // the proposal
723 ctx.strokeStyle = chainColor(c.hue, 0.8 * (1 - g));
724 ctx.lineWidth = 1.2;
725 ctx.setLineDash(cur.accepted ? [] : [3, 3]);
726 ctx.beginPath();
727 const pts = cur.path ?? [cur.from, cur.proposal];
728 pts.forEach((p, i) => (i ? ctx.lineTo(...toPx(r, p)) : ctx.moveTo(...toPx(r, p))));
729 ctx.stroke();
730 ctx.setLineDash([]);
731 if (!cur.accepted && Number.isFinite(cur.proposal[0])) {
732 const [qx, qy] = toPx(r, cur.proposal);
733 ctx.beginPath();
734 ctx.moveTo(qx - 4, qy - 4); ctx.lineTo(qx + 4, qy + 4);
735 ctx.moveTo(qx + 4, qy - 4); ctx.lineTo(qx - 4, qy + 4);
736 ctx.stroke();
737 }
738 // the note
739 if (Number.isFinite(head[0])) {
740 const [hx, hy] = toPx(r, head);
741 ctx.strokeStyle = chainColor(c.hue, (cur.accepted ? 1 : 0.4) * (1 - g));
742 ctx.lineWidth = 2;
743 ctx.beginPath();
744 ctx.arc(hx, hy, 5 + 12 * g, 0, 2 * Math.PI);
745 ctx.stroke();
746 }
747 }
748 }
749 if (Number.isFinite(head[0]) && Number.isFinite(head[1])) {
750 const [hx, hy] = toPx(r, head);
751 ctx.fillStyle = chainColor(c.hue);
752 ctx.strokeStyle = theme.bg;
753 ctx.lineWidth = 1.5;
754 ctx.beginPath();
755 ctx.arc(hx, hy, 5, 0, 2 * Math.PI);
756 ctx.fill();
757 ctx.stroke();
758 }
759 }
760 ctx.restore();
763function caption(text, r) {
764 ctx.font = '12px "Hanken Grotesk", system-ui, sans-serif';
765 ctx.textBaseline = 'top';
766 ctx.textAlign = 'left';
767 const w = ctx.measureText(text).width;
768 ctx.fillStyle = theme.bg;
769 ctx.globalAlpha = 0.8;
770 ctx.fillRect(r.x + 2, r.y + 2, w + 8, 17);
771 ctx.globalAlpha = 1;
772 ctx.fillStyle = theme.muted;
773 ctx.fillText(text, r.x + 6, r.y + 4);
776// the θ₁ marginal of the draws after warm-up (bars) and the exact one (line)
777function drawHist() {
778 const r = rects.hist;
779 ctx.strokeStyle = theme.line;
780 ctx.lineWidth = 1;
781 ctx.beginPath();
782 ctx.moveTo(r.x, r.y + r.h + 0.5);
783 ctx.lineTo(r.x + r.w, r.y + r.h + 0.5);
784 ctx.stroke();
785 const K = 200;
786 const exact = Array.from({ length: K + 1 }, (_, i) => model.marginal1(view.X * ((2 * i) / K - 1)));
787 const h = stats?.hist;
788 const top = 1.1 * Math.max(...exact, ...(h ?? [0]));
789 const py = (v) => r.y + r.h - (v / top) * (r.h - 4);
790 if (h) {
791 ctx.fillStyle = theme.density;
792 ctx.globalAlpha = 0.35;
793 const bw = r.w / BINS;
794 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)); });
795 ctx.globalAlpha = 1;
796 }
797 ctx.strokeStyle = theme.accent;
798 ctx.lineWidth = 2;
799 ctx.beginPath();
800 exact.forEach((v, i) => {
801 const px = r.x + (i / K) * r.w;
802 if (i) ctx.lineTo(px, py(v)); else ctx.moveTo(px, py(v));
803 });
804 ctx.stroke();
805 caption('θ₁ marginal: draws after warm-up (bars), exact (line)', r);
808// θ₁ of each chain over its last TRACE_LEN draws, the modes' centers dashed
809function drawTrace() {
810 const r = rects.trace;
811 ctx.strokeStyle = theme.line;
812 ctx.lineWidth = 1;
813 ctx.strokeRect(r.x + 0.5, r.y + 0.5, r.w - 1, r.h - 1);
814 const py = (x) => r.y + ((1 - x / view.X) / 2) * r.h;
815 ctx.setLineDash([3, 4]);
816 ctx.beginPath();
817 for (const m of [-params.mu / 2, params.mu / 2]) {
818 ctx.moveTo(r.x, py(m));
819 ctx.lineTo(r.x + r.w, py(m));
820 }
821 ctx.stroke();
822 ctx.setLineDash([]);
823 const n = Math.max(0, ...chains.map((c) => c.hist.n));
824 const from = Math.max(0, n - TRACE_LEN);
825 const px = (i) => r.x + ((i - from) / (TRACE_LEN - 1)) * r.w;
826 ctx.save();
827 ctx.beginPath();
828 ctx.rect(r.x, r.y, r.w, r.h);
829 ctx.clip();
830 // the end of warm-up, if in view
831 const warm = Math.floor(n / 2);
832 if (warm > from && n > 1) {
833 ctx.strokeStyle = theme.muted;
834 ctx.beginPath();
835 ctx.moveTo(px(warm), r.y);
836 ctx.lineTo(px(warm), r.y + r.h);
837 ctx.stroke();
838 }
839 ctx.lineWidth = 1.2;
840 for (const c of chains) {
841 ctx.strokeStyle = chainColor(c.hue, 0.85);
842 ctx.beginPath();
843 for (let i = from; i < c.hist.n; i++) {
844 const y = py(clamp(c.hist.xs[2 * i], -1e6, 1e6));
845 if (i === from) ctx.moveTo(px(i), y); else ctx.lineTo(px(i), y);
846 }
847 ctx.stroke();
848 }
849 ctx.restore();
850 caption(`θ₁ traces, last ${TRACE_LEN} draws${chains[0]?.hist.thin > 1 ? ` (every ${chains[0].hist.thin}th)` : ''}`, r);
851 ctx.fillStyle = theme.muted;
852 ctx.textAlign = 'right';
853 ctx.textBaseline = 'top';
854 ctx.fillText(`iteration ${chains[0]?.iters ?? 0}`, r.x + r.w, r.y + r.h + 4);
855 ctx.textAlign = 'right';
856 ctx.textBaseline = 'middle';
857 ctx.fillText('θ₁', r.x - 8, r.y + r.h / 2);
860// the hint: what is playing while listening back
861let hintText = '';
862function showHint(now) {
863 let text = 'Click to start every chain at a point';
864 if (cycle && running) {
865 if (cycle.phase === 'replay' && now >= cycle.until - LISTEN.replay) {
866 const a = cycle.start * cycle.thin;
867 text = $('listen').value === 'shuffled'
868 ? `◀ Listening back: random draws from the first half (iterations 0–${cycle.half * cycle.thin})`
869 : `◀ Listening back: iterations ${a}–${a + Math.round(LISTEN.replay * tempo) * cycle.thin} (halfway back)`;
870 } else if (cycle.phase === 'live') {
871 text = '▶ Now: the chains as they run';
872 } else {
873 text = '…';
874 }
875 }
876 if (text !== hintText) {
877 hintText = text;
878 $('hint').textContent = text;
879 }
882function frame() {
883 requestAnimationFrame(frame);
884 if (!canvas.width || !canvas.height) return;
885 schedule();
886 const now = clock();
887 drawDue(now);
888 if (now - statsAt > 0.25) {
889 stats = chains.length ? computeStats() : null;
890 statsAt = now;
891 renderStats();
892 if (synth && drone) synth.setDrone(running ? Number($('drone').value) : 0, drone);
893 }
894 showHint(now);
895 const dpr = devicePixelRatio || 1;
896 ctx.setTransform(1, 0, 0, 1, 0, 0);
897 ctx.fillStyle = theme.bg;
898 ctx.fillRect(0, 0, canvas.width, canvas.height);
899 ctx.drawImage(densityLayer, 0, 0);
900 ctx.drawImage(dotsLayer, 0, 0);
901 ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
902 drawAxes();
903 drawStarts();
904 drawChains(now);
905 drawHist();
906 drawTrace();
909// ---- controls ------------------------------------------------------------------------
911// a group of sliders over the values in obj; onInput(key) after each change
912function buildSliders(container, specs, obj, onInput) {
913 const toInput = (s, v) => (s.log ? Math.round((1000 * Math.log(v / s.min)) / Math.log(s.max / s.min)) : v);
914 const fromInput = (s, u) => (s.log ? s.min * (s.max / s.min) ** (u / 1000) : u);
915 container.innerHTML = specs.map((s) => `
916 <label class="row" data-key="${s.key}">
917 <span>${s.label}</span>
918 <input type="range" min="${s.log ? 0 : s.min}" max="${s.log ? 1000 : s.max}" step="${s.log ? 1 : s.step}">
919 <output></output>
920 </label>`).join('');
921 const rows = new Map([...container.children].map((row) => [row.dataset.key, row]));
922 const show = () => {
923 for (const s of specs) {
924 const row = rows.get(s.key);
925 row.querySelector('input').value = toInput(s, obj[s.key]);
926 row.querySelector('output').textContent = s.fmt(obj[s.key]);
927 if (s.only) row.hidden = !s.only.includes(tune.kind);
928 }
929 };
930 for (const s of specs) {
931 const row = rows.get(s.key);
932 row.querySelector('input').addEventListener('input', (e) => {
933 let v = fromInput(s, Number(e.target.value));
934 if (s.log) v = Number(v.toPrecision(2));
935 obj[s.key] = v;
936 row.querySelector('output').textContent = s.fmt(v);
937 onInput(s.key);
938 });
939 }
940 show();
941 return show;
944function buildControls() {
945 const presetSel = $('preset');
946 presetSel.innerHTML = PRESETS.map((pr, i) => `<option value="${i}"${i === DEFAULT_PRESET ? ' selected' : ''}>${pr.name}</option>`).join('')
947 + '<option value="custom" hidden>Custom</option>';
948 const showModel = buildSliders($('model-sliders'), MODEL_SLIDERS, params, (k) => {
949 if (k === 'tau') {
950 // only the starts change, not the target
951 model.tau = params.tau;
952 layout();
953 renderDensity();
954 redrawDots();
955 return;
956 }
957 presetSel.value = 'custom';
958 applyModel();
959 newSegment();
960 });
961 presetSel.addEventListener('change', () => {
962 if (presetSel.value === 'custom') return;
963 Object.assign(params, BASE, PRESETS[presetSel.value].p);
964 showModel();
965 applyModel();
966 newSegment();
967 });
969 const showSampler = buildSliders($('sampler-sliders'), SAMPLER_SLIDERS, tune, retune);
970 $('sampler').addEventListener('change', (e) => {
971 tune.kind = e.target.value;
972 showSampler();
973 rebuildSamplers();
974 });
975 buildSliders($('chain-sliders'), CHAIN_SLIDERS, tune, () => setChainCount(tune.count));
977 $('run').addEventListener('click', () => setRunning(!running));
978 $('restart').addEventListener('click', () => {
979 startPoint = null;
980 restart();
981 });
982 $('skip').addEventListener('click', skipAhead);
984 $('scale').innerHTML = SCALES.map((s) => `<option${s.name === DEFAULT_SCALE ? ' selected' : ''}>${s.name}</option>`).join('');
985 $('keys').innerHTML = KEYS.map((k, i) => `<button data-key="${i}" aria-pressed="${i === key}">${k}</button>`).join('');
986 $('keys').addEventListener('click', (e) => {
987 const btn = e.target.closest('button[data-key]');
988 if (!btn) return;
989 key = Number(btn.dataset.key);
990 for (const b of $('keys').children) b.setAttribute('aria-pressed', b === btn);
991 synth?.setDroneRoot(droneRoot());
992 });
993 // tempo on a log scale, TEMPO.min to TEMPO.max iterations per second
994 const tmp = $('tempo');
995 const span = Math.log(TEMPO.max / TEMPO.min);
996 tmp.value = Math.round((1000 * Math.log(tempo / TEMPO.min)) / span);
997 const tempoOut = () => { tmp.nextElementSibling.textContent = `${tempo} /s`; };
998 tmp.addEventListener('input', () => {
999 tempo = Math.round(TEMPO.min * Math.exp((Number(tmp.value) / 1000) * span));
1000 tempoOut();
1001 });
1002 tempoOut();
1003 const sus = $('sustain');
1004 Object.assign(sus, { min: SUSTAIN.min, max: SUSTAIN.max, step: SUSTAIN.step, value: SUSTAIN.default });
1005 const susOut = () => { sus.nextElementSibling.textContent = `${Number(sus.value).toFixed(1)} s`; };
1006 sus.addEventListener('input', () => {
1007 susOut();
1008 synth?.setSustain(Number(sus.value));
1009 });
1010 susOut();
1011 const dr = $('drone');
1012 const drOut = () => { dr.nextElementSibling.textContent = Number(dr.value) ? `${Math.round(100 * dr.value)}%` : 'off'; };
1013 dr.addEventListener('input', () => {
1014 drOut();
1015 if (synth && drone) synth.setDrone(running ? Number(dr.value) : 0, drone);
1016 });
1017 drOut();
1018 const vol = $('volume');
1019 const volOut = () => { vol.nextElementSibling.textContent = `${Math.round(100 * vol.value)}%`; };
1020 vol.addEventListener('input', () => {
1021 volOut();
1022 if (synth && soundOn) synth.setVolume(Number(vol.value));
1023 });
1024 volOut();
1025 $('sound').addEventListener('click', () => setSound(!soundOn));
1027 // a click in the plane starts every chain there
1028 canvas.addEventListener('pointerdown', (e) => {
1029 const rect = canvas.getBoundingClientRect();
1030 const r = rects.main;
1031 const px = e.clientX - rect.left;
1032 const py = e.clientY - rect.top;
1033 if (px < r.x || px > r.x + r.w || py < r.y || py > r.y + r.h) return;
1034 startPoint = [((px - r.x) / r.w * 2 - 1) * view.X, (1 - (py - r.y) / r.h * 2) * view.Y];
1035 restart();
1036 });
1039readTheme();
1040matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); });
1041buildControls();
1042applyModel();
1043restart();
1044new ResizeObserver(resize).observe(canvas);
1045resize();
1046requestAnimationFrame(frame);
↑↓ move↵openescclose