/ interactive_tutorials / mcmc_sonification
Sign in
interactive_tutorials / mcmc_sonification
Listening for convergence: MCMC chains on a 2D mixture, sonified
A port of mixture_mcmc.py (two-component normal mixture; RWM, MALA, ULA, generalized HMC, HMC) and a page that plays every chain: pitch from θ₁, a pure-to-buzzy timbre from θ₂, optional rank-based notes, an agreement drone, and listen-back (live against halfway back). Below the plane the θ₁ marginal against the exact one and the traces; in the panel moments, split R̂ and acceptance rates. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 726adb60ca88 Browse files
14 changed files+2334−0
.gitignoreadded+11−0View file
@@ -0,0 +1,11 @@
1+# macOS
2+.DS_Store
3+
4+# Editors
5+.vscode/
6+.idea/
7+*.swp
8+
9+# Logs and temp files
10+*.log
11+*.tmp
README.mdadded+34−0View file
@@ -0,0 +1,34 @@
1+# Listening for convergence
2+
3+A minimal lab for hearing MCMC chains reach (or fail to reach) their stationary distribution, on a 2D mixture of two normals:
4+
5+ p(θ) = ½ 𝒩(θ | m₁, Σ₁) + ½ 𝒩(θ | m₂, Σ₂), m₁,₂ = (∓μ/2, 0), Σₖ = diag(σₖ) [[1, ρₖ], [ρₖ, 1]] diag(σₖ)
6+
7+```bash
8+npm run dev # serves app/ at http://127.0.0.1:8003
9+npm run check # node --check on every module, and runs the sampler check
10+node scripts/check-samplers.mjs # acceptance, mode switches and moments on the five targets
11+```
12+
13+Static `index.html`, `style.css` and ES modules, no build step; fonts bundled under `app/vendor/`.
14+
15+## What's in it
16+
17+- **Target**: the five settings of the notes (easy, separated, ridge, stiff, crossed), and sliders for μ, the four σ's, the two ρ's, and τ, the radius of the circle the chains start on. The plane shades the density on a log scale (3.5 decades), with equal scales on both axes.
18+- **Sampler**: random-walk Metropolis, MALA, ULA (unadjusted Langevin), generalized HMC (one leapfrog step, partial momentum refresh γ, momentum flipped on rejection) and HMC (L leapfrog steps), with step size ε; the stability limit of leapfrog and Langevin, 2 √λmin, is shown under it. All chains run the same sampler with the same tuning, each with its own seed.
19+- **Chains** (1 to 32, default 8): start at random points on the τ circle (*Restart*), or all at one point (click the plane). Each shows its last proposal (the HMC trajectory, or a line; dashed and crossed out if rejected) and a short trail. The chains start paused: *Run* sets them going and *Pause* stops them; *+1000* runs 1000 iterations of each at once, silently.
20+- **Sound** (the big button in the header): every iteration, each chain plays a note, all with the same sound, each chain from its own place in the stereo field. θ₁ sets the pitch: three octaves, C3 to C6, of the chosen scale and key (chromatic by default), over θ₁ = ±(μ/2 + 3.2 max σₖ₁). θ₂ sets the timbre, over θ₂ = ±3.2 max σₖ₂: an equal-power crossfade from a soft, nearly pure tone at the bottom to a bright, buzzy, nasal one at the top (a sawtooth-like spectrum with a formant near 2 kHz), matched in loudness so only the timbre changes. A rejected step repeats the note softly (or is silent). Chains that have mixed wander over both modes and play in the same registers; a chain stuck in one mode keeps to its octave, and a stalled one repeats itself. Tempo is iterations per second (default 50, 1 to 400 on a log scale); past 800 notes per second over all chains, the chains take turns, each playing every few iterations. Sustain (default 0.6 s) and volume as in the Duffing app; at most 192 notes sound at once (the oldest fades out).
21+- **Hearing mixing without knowing the target** (all in the Sound panel):
22+ - *Notes from: rank among all chains' draws*: pitch and timbre from the rank of θ₁ and θ₂ among the pooled draws after warm-up (a random sample of 4000 of them, refreshed four times a second) instead of θ itself. Pooled, the notes then spread evenly over the whole range; if the chains have mixed, each one does too and they sound alike, while a chain stuck in part of the space keeps to part of the range. A chain that moves slowly plays a stepwise melody; one that mixes fast jumps around at random.
23+ - *Drone* (default 50%): under the notes, per chain, a soft tone at the key's root (for θ₁) and one at its fifth (for θ₂), each detuned by 400 z² cents (up to an octave), z the chain's mean after warm-up minus the pooled mean, in pooled standard deviations. Chains that disagree beat and clash; as they agree (split R̂ → 1), the drone settles into a plain fifth. Silent while paused.
24+ - *Listen back*: 3 s of the chains as they run, a 0.6 s gap, then 3 s replayed from the history, centered halfway back (once there are three times that many draws), a gap, and live again; the plane holds still during the replay, and the hint says which iterations are playing. *Shuffled* plays random draws from the whole first half of the history instead of one stretch: the earlier distribution rather than one moment of it. A difference between live and replay means the chains have not settled; no difference is weaker evidence (3 s is a few hundred draws, and two stuck stretches sound alike).
25+ - None of these can reveal a mode no chain has found (*stiff*, with a gradient sampler): only wide starts, more chains and other samplers help there.
26+- **Draws**: below the plane, the θ₁ marginal of the draws after warm-up (the first half of each chain) against the exact mixture marginal, and each chain's θ₁ trace over its last 1000 draws (the modes' centers dashed, the end of warm-up marked). In the panel, each chain's acceptance rate, and the mean, variances, covariance and P(θ₁ > 0) of the pooled draws after warm-up against the exact values (mean 0, Cov = ½ Σₖ (Σₖ + mₖ mₖᵀ)), and split R̂ for θ₁ and θ₂ (highlighted above 1.05). Changing the target or the sampler keeps the chains where they are and starts a fresh set of draws.
27+
28+Things to try (from the notes): RWM on *separated* with ε = 0.1, 0.75, 2 and 4; GHMC at ε = 0.2 sweeping γ from 1 down to 0.01; HMC on *ridge* at ε = 0.5 (above the 0.45 limit: frozen); ULA on *ridge* at ε = 0.75 (diverges); every gradient sampler on *stiff* (they never find the needle; RWM with ε ≈ 2 does). There, MALA at ε = 0.5 gives split R̂ ≈ 1.00 while P(θ₁ > 0) is about 0.02 against ½: all chains agree, on the wrong answer, and they all keep to the low register. Start all chains in one mode of *separated* by clicking it, and listen for the first to cross.
29+
30+## Code
31+
32+- `app/js/mixture.js`: a port of `mixture_mcmc.py`, with the same model, samplers and interface in camelCase (`new HMC(model, 0.2, { nSteps: 10, seed: 1 })`, `s.next()`, `s.theta`, `s.proposal`, `s.accepted`, `s.acceptProb`, `s.path`, `s.momentum`, `s.diverged`, setters that validate), plus a seeded generator (sfc32 with Box-Muller normals), the exact θ₁ marginal, and the ground truth. The random numbers are not NumPy's, so a chain is not the same draw for draw as the Python one; `scripts/check-samplers.mjs` reproduces the notes' tables (acceptance rates, switches, the stiff-model lesson) instead.
33+- `app/js/voices.js`: the two tones (wavetables with an exponential decay, loudness matched by K-weighted RMS as in the Duffing app), the crossfade, the drone, and the scales.
34+- `app/main.js`: the chains, the scheduling on the audio clock, the plots and the statistics (split R̂ as in BDA3).
app/index.htmladded+124−0View file
@@ -0,0 +1,124 @@
1+<!doctype html>
2+<html lang="en">
3+<head>
4+ <meta charset="utf-8">
5+ <meta name="viewport" content="width=device-width, initial-scale=1">
6+ <title>Listening to MCMC</title>
7+ <link rel="stylesheet" href="style.css">
8+</head>
9+<body>
10+ <header>
11+ <div>
12+ <h1>Listening for convergence</h1>
13+ <p class="eq">
14+ <i>p</i>(<i>θ</i>) = ½ 𝒩(<i>θ</i> | <i>m</i><sub>1</sub>, Σ<sub>1</sub>) + ½ 𝒩(<i>θ</i> | <i>m</i><sub>2</sub>, Σ<sub>2</sub>),
15+ &nbsp;<i>m</i><sub>1,2</sub> = (∓<i>μ</i>/2, 0)
16+ </p>
17+ </div>
18+ <button id="sound" class="sound-button" aria-pressed="false">
19+ <span class="icon" aria-hidden="true">🔇</span>
20+ <span class="label">Turn sound on</span>
21+ </button>
22+ </header>
23+
24+ <div class="layout">
25+ <aside class="panel">
26+ <section class="group">
27+ <h2>Target</h2>
28+ <select id="preset" aria-label="Target preset"></select>
29+ <div id="model-sliders" class="sliders"></div>
30+ </section>
31+
32+ <section class="group">
33+ <h2>Sampler</h2>
34+ <select id="sampler" aria-label="Sampler">
35+ <option value="rwm">Random-walk Metropolis</option>
36+ <option value="mala">Langevin, adjusted (MALA)</option>
37+ <option value="ula">Langevin, unadjusted (ULA)</option>
38+ <option value="ghmc">Generalized HMC</option>
39+ <option value="hmc">HMC</option>
40+ </select>
41+ <div id="sampler-sliders" class="sliders"></div>
42+ <p id="limit" class="note"></p>
43+ </section>
44+
45+ <section class="group">
46+ <h2>Chains</h2>
47+ <div id="chain-sliders" class="sliders"></div>
48+ <div class="buttons">
49+ <button id="run" class="toggle" aria-pressed="false">▶ Run</button>
50+ <button id="restart">Restart</button>
51+ <button id="skip" title="Run 1000 iterations at once, without sound">+1000</button>
52+ </div>
53+ <ul id="chain-list" class="chain-list"></ul>
54+ </section>
55+
56+ <section class="group">
57+ <h2>Draws <span id="draws-note" class="note"></span></h2>
58+ <table id="stats" class="stats"></table>
59+ </section>
60+
61+ <section class="group sound">
62+ <h2>Sound</h2>
63+ <label class="row">
64+ <span>Notes from</span>
65+ <select id="pitch-map">
66+ <option value="value" selected>θ: θ₁ pitch, θ₂ timbre</option>
67+ <option value="rank">Rank among all chains' draws</option>
68+ </select>
69+ </label>
70+ <label class="row">
71+ <span>Drone</span>
72+ <input id="drone" type="range" min="0" max="1" step="0.01" value="0.5">
73+ <output></output>
74+ </label>
75+ <label class="row">
76+ <span>Listen back</span>
77+ <select id="listen">
78+ <option value="off" selected>Off</option>
79+ <option value="order">3 s live, then 3 s from halfway back</option>
80+ <option value="shuffled">3 s live, then 3 s shuffled from the first half</option>
81+ </select>
82+ </label>
83+ <label class="row">
84+ <span>Rejected</span>
85+ <select id="rejected">
86+ <option value="soft" selected>Repeat the note, softly</option>
87+ <option value="silent">Silent</option>
88+ </select>
89+ </label>
90+ <label class="row">
91+ <span>Scale</span>
92+ <select id="scale"></select>
93+ </label>
94+ <div class="row">
95+ <span>Key</span>
96+ <div id="keys" class="keys" role="group" aria-label="Key"></div>
97+ </div>
98+ <label class="row">
99+ <span>Tempo</span>
100+ <input id="tempo" type="range" min="0" max="1000" step="1">
101+ <output></output>
102+ </label>
103+ <label class="row">
104+ <span>Sustain</span>
105+ <input id="sustain" type="range">
106+ <output></output>
107+ </label>
108+ <label class="row">
109+ <span>Volume</span>
110+ <input id="volume" type="range" min="0" max="1" step="0.01" value="0.6">
111+ <output></output>
112+ </label>
113+ </section>
114+ </aside>
115+
116+ <div class="plot-wrap">
117+ <canvas id="plot"></canvas>
118+ <p id="hint" class="hint">Click to start every chain at a point</p>
119+ </div>
120+ </div>
121+
122+ <script type="module" src="main.js"></script>
123+</body>
124+</html>
app/js/mixture.jsadded+371−0View file
@@ -0,0 +1,371 @@
1+// A 2D two-component normal mixture and four MCMC samplers, one step at a
2+// time: a JavaScript port of mixture_mcmc.py (same model, same samplers, same
3+// interface, in camelCase).
4+//
5+// p(θ) = ½ N(θ | m₁, Σ₁) + ½ N(θ | m₂, Σ₂), m₁ = (−μ/2, 0), m₂ = (μ/2, 0),
6+// Σₖ = diag(σₖ) [[1, ρₖ], [ρₖ, 1]] diag(σₖ), σₖ = (σₖ₁, σₖ₂).
7+//
8+// const model = new NormalMixture2D({ mu: 4, sigma: [[1, 1], [1, 1]], rho: [0, 0], tau: 1 });
9+// const s = new HMC(model, 0.2, { nSteps: 10, seed: 1 });
10+// const theta = s.next(); // one step; also s.theta, s.proposal,
11+// // s.accepted, s.acceptProb, s.nIter, ...
12+// s.stepSize = 0.3; // retune at any time
13+//
14+// Points are [θ₁, θ₂] arrays. The random numbers come from a seeded
15+// generator here, so a chain is reproducible in JavaScript, but not the same
16+// numbers as NumPy's.
17+
18+const LOG_2PI = Math.log(2 * Math.PI);
19+
20+function positive(name, v) {
21+ v = Number(v);
22+ if (!(Number.isFinite(v) && v > 0)) throw new RangeError(`${name} must be in (0, inf); got ${v}`);
23+ return v;
24+}
25+
26+function openUnit(name, v) {
27+ v = Number(v);
28+ if (!(v > -1 && v < 1)) throw new RangeError(`${name} must be in (-1, 1); got ${v}`);
29+ return v;
30+}
31+
32+function closedUnit(name, v) {
33+ v = Number(v);
34+ if (!(v >= 0 && v <= 1)) throw new RangeError(`${name} must be in [0, 1]; got ${v}`);
35+ return v;
36+}
37+
38+// ---- random numbers ---------------------------------------------------------
39+
40+// sfc32, seeded through splitmix32: uniform() in [0, 1), normal() standard
41+// normal (Box-Muller, both values used).
42+export class Rng {
43+ constructor(seed = (Math.random() * 2 ** 32) >>> 0) {
44+ let s = seed >>> 0;
45+ const mix = () => {
46+ s = (s + 0x9e3779b9) >>> 0;
47+ let z = s;
48+ z = Math.imul(z ^ (z >>> 16), 0x85ebca6b);
49+ z = Math.imul(z ^ (z >>> 13), 0xc2b2ae35);
50+ return (z ^ (z >>> 16)) >>> 0;
51+ };
52+ this.a = mix(); this.b = mix(); this.c = mix(); this.d = mix();
53+ this.spare = null;
54+ for (let i = 0; i < 12; i++) this.uniform();
55+ }
56+
57+ uniform() {
58+ let { a, b, c, d } = this;
59+ const t = (((a + b) >>> 0) + d) >>> 0;
60+ d = (d + 1) >>> 0;
61+ a = b ^ (b >>> 9);
62+ b = (c + (c << 3)) >>> 0;
63+ c = (c << 21) | (c >>> 11);
64+ c = (c + t) >>> 0;
65+ Object.assign(this, { a, b, c, d });
66+ return t / 4294967296;
67+ }
68+
69+ normal() {
70+ if (this.spare !== null) {
71+ const z = this.spare;
72+ this.spare = null;
73+ return z;
74+ }
75+ const u = 1 - this.uniform(); // (0, 1]
76+ const r = Math.sqrt(-2 * Math.log(u));
77+ const a = 2 * Math.PI * this.uniform();
78+ this.spare = r * Math.sin(a);
79+ return r * Math.cos(a);
80+ }
81+
82+ normal2() { return [this.normal(), this.normal()]; }
83+}
84+
85+// ---- the model ----------------------------------------------------------------
86+
87+export class NormalMixture2D {
88+ // mu: distance between the means; sigma: [[σ₁₁, σ₁₂], [σ₂₁, σ₂₂]], per
89+ // component and axis; rho: [ρ₁, ρ₂]; tau: radius of the circle the chains
90+ // start on
91+ constructor({ mu = 4, sigma = [[1, 1], [1, 1]], rho = [0, 0], tau = 1 } = {}) {
92+ this.set({ mu, sigma, rho, tau });
93+ }
94+
95+ // validate and set any of mu, sigma, rho, tau; the next step uses them
96+ set({ mu = this.mu, sigma = this.sigma, rho = this.rho, tau = this.tau } = {}) {
97+ this.mu = positive('mu', mu);
98+ this.sigma = sigma.map((s, k) => s.map((v, j) => positive(`sigma[${k}][${j}]`, v)));
99+ this.rho = rho.map((r, k) => openUnit(`rho[${k}]`, r));
100+ this.tau = positive('tau', tau);
101+ const h = this.mu / 2;
102+ this.means = [[-h, 0], [h, 0]];
103+ // per component: covariance, precision and log(½ · normalization)
104+ this.comps = this.sigma.map(([s1, s2], k) => {
105+ const r = this.rho[k];
106+ const c11 = s1 * s1, c12 = r * s1 * s2, c22 = s2 * s2;
107+ const det = c11 * c22 - c12 * c12;
108+ return {
109+ mx: this.means[k][0], my: this.means[k][1],
110+ c11, c12, c22,
111+ p11: c22 / det, p12: -c12 / det, p22: c11 / det,
112+ logNorm: -LOG_2PI - 0.5 * Math.log(det) + Math.log(0.5),
113+ };
114+ });
115+ return this;
116+ }
117+
118+ logDensity([x, y]) {
119+ const [a, b] = this.comps.map((c) => {
120+ const dx = x - c.mx, dy = y - c.my;
121+ return c.logNorm - 0.5 * (dx * (c.p11 * dx + c.p12 * dy) + dy * (c.p12 * dx + c.p22 * dy));
122+ });
123+ const m = Math.max(a, b);
124+ if (m === -Infinity) return -Infinity;
125+ return m + Math.log(Math.exp(a - m) + Math.exp(b - m));
126+ }
127+
128+ // ∇ log p: minus the posterior-weighted P_k (θ − m_k)
129+ gradLogDensity([x, y]) {
130+ let gx = 0, gy = 0;
131+ const lp = [], pd = [];
132+ for (const c of this.comps) {
133+ const dx = x - c.mx, dy = y - c.my;
134+ const px = c.p11 * dx + c.p12 * dy, py = c.p12 * dx + c.p22 * dy;
135+ lp.push(c.logNorm - 0.5 * (dx * px + dy * py));
136+ pd.push([px, py]);
137+ }
138+ const m = Math.max(lp[0], lp[1]);
139+ const w0 = Math.exp(lp[0] - m), w1 = Math.exp(lp[1] - m);
140+ const s = w0 + w1;
141+ gx = -(w0 * pd[0][0] + w1 * pd[1][0]) / s;
142+ gy = -(w0 * pd[0][1] + w1 * pd[1][1]) / s;
143+ return [gx, gy];
144+ }
145+
146+ initialPoint(rng) {
147+ const a = 2 * Math.PI * rng.uniform();
148+ return [this.tau * Math.cos(a), this.tau * Math.sin(a)];
149+ }
150+
151+ // leapfrog / Langevin linear stability bound: 2 × the smallest principal std
152+ maxStableStepSize() {
153+ const lmin = Math.min(...this.comps.map(({ c11, c12, c22 }) =>
154+ (c11 + c22) / 2 - Math.sqrt(((c11 - c22) / 2) ** 2 + c12 * c12)));
155+ return 2 * Math.sqrt(lmin);
156+ }
157+
158+ // the exact marginal density of θ₁ (each component's is N(mₖ₁, σₖ₁²))
159+ marginal1(x) {
160+ let p = 0;
161+ for (const c of this.comps) {
162+ const s = Math.sqrt(c.c11);
163+ p += 0.5 * Math.exp(-0.5 * ((x - c.mx) / s) ** 2) / (s * Math.sqrt(2 * Math.PI));
164+ }
165+ return p;
166+ }
167+
168+ // ground truth: mean 0 and Cov = ½ Σₖ (Σₖ + mₖ mₖᵀ); P(θ₁ > 0)
169+ truth() {
170+ const cov = [[0, 0], [0, 0]];
171+ for (const c of this.comps) {
172+ cov[0][0] += 0.5 * (c.c11 + c.mx * c.mx);
173+ cov[0][1] += 0.5 * (c.c12 + c.mx * c.my);
174+ cov[1][1] += 0.5 * (c.c22 + c.my * c.my);
175+ }
176+ cov[1][0] = cov[0][1];
177+ const erf = (z) => {
178+ // Abramowitz and Stegun 7.1.26 (|error| < 1.5e-7)
179+ const t = 1 / (1 + 0.3275911 * Math.abs(z));
180+ const y = 1 - t * (0.254829592 + t * (-0.284496736 + t * (1.421413741 + t * (-1.453152027 + t * 1.061405429)))) * Math.exp(-z * z);
181+ return z >= 0 ? y : -y;
182+ };
183+ const right = this.comps.reduce((acc, c) => acc + 0.5 * 0.5 * (1 + erf(c.mx / Math.sqrt(2 * c.c11))), 0);
184+ return { mean: [0, 0], cov, right };
185+ }
186+}
187+
188+// ---- integrator ---------------------------------------------------------------
189+
190+// n leapfrog steps of size eps from (x, p), unit mass; path (optional) gets
191+// each new position
192+export function leapfrog(model, x, p, eps, n, path = null) {
193+ let g = model.gradLogDensity(x);
194+ p = [p[0] + 0.5 * eps * g[0], p[1] + 0.5 * eps * g[1]];
195+ for (let i = 0; i < n; i++) {
196+ x = [x[0] + eps * p[0], x[1] + eps * p[1]];
197+ if (path) path.push(x);
198+ g = model.gradLogDensity(x);
199+ if (i < n - 1) p = [p[0] + eps * g[0], p[1] + eps * g[1]];
200+ }
201+ return [x, [p[0] + 0.5 * eps * g[0], p[1] + 0.5 * eps * g[1]]];
202+}
203+
204+export const hamiltonian = (model, x, p) => -model.logDensity(x) + 0.5 * (p[0] * p[0] + p[1] * p[1]);
205+
206+// ---- samplers -----------------------------------------------------------------
207+
208+// next() advances one step and returns a copy of theta. After each step:
209+// theta, proposal, accepted, acceptProb, nIter, nAccept, acceptanceRate.
210+export class Sampler {
211+ constructor(model, stepSize, { theta0 = null, seed } = {}) {
212+ this.model = model;
213+ this.stepSize = stepSize;
214+ this.rng = new Rng(seed);
215+ this.reset(theta0);
216+ }
217+
218+ get stepSize() { return this._eps; }
219+ set stepSize(v) { this._eps = positive('stepSize', v); }
220+
221+ reset(theta0 = null) {
222+ this.theta = theta0 === null ? this.model.initialPoint(this.rng) : [Number(theta0[0]), Number(theta0[1])];
223+ this.proposal = this.theta.slice();
224+ this.accepted = null;
225+ this.acceptProb = NaN;
226+ this.nIter = this.nAccept = 0;
227+ }
228+
229+ get acceptanceRate() { return this.nIter ? this.nAccept / this.nIter : NaN; }
230+
231+ next() {
232+ this._step();
233+ this.nIter++;
234+ this.nAccept += this.accepted ? 1 : 0;
235+ return this.theta.slice();
236+ }
237+
238+ draws(n) { return Array.from({ length: n }, () => this.next()); }
239+
240+ // set acceptProb and accepted; NaN or −inf ratios reject
241+ _metropolis(logRatio) {
242+ if (!Number.isFinite(logRatio)) logRatio = logRatio === Infinity ? Infinity : -Infinity;
243+ this.acceptProb = Math.exp(Math.min(0, logRatio));
244+ this.accepted = Math.log(this.rng.uniform()) < logRatio;
245+ return this.accepted;
246+ }
247+}
248+
249+// θ' = θ + ε z, z ~ N(0, I); Metropolis accept
250+export class RandomWalkMetropolis extends Sampler {
251+ _step() {
252+ const lp = (x) => this.model.logDensity(x);
253+ const [z1, z2] = this.rng.normal2();
254+ this.proposal = [this.theta[0] + this.stepSize * z1, this.theta[1] + this.stepSize * z2];
255+ if (this._metropolis(lp(this.proposal) - lp(this.theta))) this.theta = this.proposal;
256+ }
257+}
258+
259+// θ' = θ + (ε²/2) ∇ log p(θ) + ε z.
260+// adjust false: unadjusted Langevin (ULA), always moves (biased, may
261+// diverge); a non-finite proposal is not taken and sets diverged.
262+// adjust true: MALA, with the Metropolis-Hastings correction.
263+export class Langevin extends Sampler {
264+ constructor(model, stepSize, { adjust = true, ...rest } = {}) {
265+ super(model, stepSize, rest);
266+ this.adjust = adjust;
267+ }
268+
269+ get adjust() { return this._adjust; }
270+ set adjust(v) { this._adjust = Boolean(v); }
271+
272+ reset(theta0 = null) {
273+ super.reset(theta0);
274+ this.diverged = false;
275+ }
276+
277+ _mean(x) {
278+ const g = this.model.gradLogDensity(x);
279+ const h = 0.5 * this.stepSize ** 2;
280+ return [x[0] + h * g[0], x[1] + h * g[1]];
281+ }
282+
283+ _logQ(to, frm) {
284+ const m = this._mean(frm);
285+ const dx = to[0] - m[0], dy = to[1] - m[1];
286+ return (-0.5 * (dx * dx + dy * dy)) / this.stepSize ** 2;
287+ }
288+
289+ _step() {
290+ const x = this.theta;
291+ const m = this._mean(x);
292+ const [z1, z2] = this.rng.normal2();
293+ const y = [m[0] + this.stepSize * z1, m[1] + this.stepSize * z2];
294+ this.proposal = y;
295+ if (!this.adjust) {
296+ this.diverged = !(Number.isFinite(y[0]) && Number.isFinite(y[1]));
297+ this.accepted = !this.diverged;
298+ this.acceptProb = 1;
299+ } else {
300+ const lp = (v) => this.model.logDensity(v);
301+ this._metropolis(lp(y) - lp(x) + this._logQ(x, y) - this._logQ(y, x));
302+ }
303+ if (this.accepted) this.theta = y;
304+ }
305+}
306+
307+// One leapfrog step per iteration with partial momentum refresh,
308+// p ← √(1 − γ) p + √γ z (γ = 1 is MALA); on rejection the momentum is
309+// negated (Horowitz 1991).
310+export class GeneralizedHMC extends Sampler {
311+ constructor(model, stepSize, { gamma = 0.1, ...rest } = {}) {
312+ super(model, stepSize, rest);
313+ this.gamma = gamma;
314+ }
315+
316+ get gamma() { return this._gamma; }
317+ set gamma(v) { this._gamma = closedUnit('gamma', v); }
318+
319+ reset(theta0 = null) {
320+ super.reset(theta0);
321+ this.momentum = this.rng.normal2();
322+ }
323+
324+ _step() {
325+ const g = this.gamma;
326+ const [z1, z2] = this.rng.normal2();
327+ const a = Math.sqrt(1 - g), b = Math.sqrt(g);
328+ const p = [a * this.momentum[0] + b * z1, a * this.momentum[1] + b * z2];
329+ const [x1, p1] = leapfrog(this.model, this.theta, p, this.stepSize, 1);
330+ this.proposal = x1;
331+ const h0 = hamiltonian(this.model, this.theta, p);
332+ const h1 = hamiltonian(this.model, x1, p1);
333+ if (this._metropolis(h0 - h1)) {
334+ this.theta = x1;
335+ this.momentum = p1;
336+ } else {
337+ this.momentum = [-p[0], -p[1]];
338+ }
339+ }
340+}
341+
342+// L leapfrog steps, unit mass, full momentum refresh. path holds the L + 1
343+// positions of the last trajectory (accepted or not).
344+export class HMC extends Sampler {
345+ constructor(model, stepSize, { nSteps = 10, ...rest } = {}) {
346+ super(model, stepSize, rest);
347+ this.nSteps = nSteps;
348+ }
349+
350+ get nSteps() { return this._L; }
351+ set nSteps(v) {
352+ if (!Number.isInteger(Number(v)) || v < 1) throw new RangeError(`nSteps must be a positive integer; got ${v}`);
353+ this._L = Number(v);
354+ }
355+
356+ reset(theta0 = null) {
357+ super.reset(theta0);
358+ this.path = [this.theta.slice()];
359+ }
360+
361+ _step() {
362+ const p = this.rng.normal2();
363+ const path = [this.theta];
364+ const [x1, p1] = leapfrog(this.model, this.theta, p, this.stepSize, this.nSteps, path);
365+ this.path = path;
366+ this.proposal = x1;
367+ const h0 = hamiltonian(this.model, this.theta, p);
368+ const h1 = hamiltonian(this.model, x1, p1);
369+ if (this._metropolis(h0 - h1)) this.theta = x1;
370+ }
371+}
app/js/voices.jsadded+292−0View file
@@ -0,0 +1,292 @@
1+// The sound of the chains, and the mapping from a point's θ₁ to its pitch.
2+//
3+// Every note is a crossfade (equal power) between two tones at its pitch,
4+// set by θ₂: a soft, nearly pure tone at the bottom of the plane, and a
5+// bright, buzzy, nasal one at the top (a sawtooth-like spectrum, its
6+// harmonics falling as 1/k^0.8, with a formant around 2 kHz). Both are
7+// rendered once per pitch and sustain into AudioBuffers from one period of
8+// their waveform (a wavetable), with a soft attack, an exponential decay
9+// (the sustain is the time to fade by 60 dB) and a short fade at the end,
10+// and matched in loudness: the RMS over each note's onset (its first
11+// LOUD_WINDOW s) after the K-weighting filter of ITU-R BS.1770 (a high shelf
12+// of +4 dB above about 1.7 kHz, where the ear is most sensitive, and a
13+// high-pass at 38 Hz). So top and bottom differ in timbre only, not in
14+// loudness. Under the notes, an optional drone (setDrone). Everything goes
15+// through a soft low-pass (6 kHz), a dark synthetic reverb and a limiter.
16+
17+export const DEFAULT_SCALE = 'Chromatic';
18+export const KEYS = ['C', 'C♯', 'D', 'E♭', 'E', 'F', 'F♯', 'G', 'A♭', 'A', 'B♭', 'B'];
19+export const DEFAULT_KEY = 9; // A
20+
21+// Scales as semitone offsets within an octave; null: continuous pitch.
22+export const SCALES = [
23+ { name: 'Major pentatonic', steps: [0, 2, 4, 7, 9] },
24+ { name: 'Minor pentatonic', steps: [0, 3, 5, 7, 10] },
25+ { name: 'Major', steps: [0, 2, 4, 5, 7, 9, 11] },
26+ { name: 'Natural minor', steps: [0, 2, 3, 5, 7, 8, 10] },
27+ { name: 'Harmonic minor', steps: [0, 2, 3, 5, 7, 8, 11] },
28+ { name: 'Whole tone', steps: [0, 2, 4, 6, 8, 10] },
29+ { name: 'Chromatic', steps: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11] },
30+ { name: 'Continuous', steps: null },
31+];
32+
33+const LOW = 130.81; // C3, the pitch at the low end of the range
34+const OCTAVES = 3; // up to C6 at the high end
35+
36+// The pitch (Hz) for u in [0, 1] (the low to high end of the range): the
37+// notes of the scale in the given key (0 = C, ..., 11 = B) that lie within
38+// OCTAVES octaves from LOW, spread evenly across the range; or continuous.
39+// The register stays put when the key changes, so a key change shifts the
40+// harmony, like a chord change.
41+export function pitchOf(u, scale, key = 0) {
42+ u = Math.min(1, Math.max(0, u));
43+ if (!scale.steps) return LOW * 2 ** (OCTAVES * u);
44+ const notes = [];
45+ for (let s = 0; s <= 12 * OCTAVES; s++) {
46+ if (scale.steps.includes((((s - key) % 12) + 12) % 12)) notes.push(s);
47+ }
48+ return LOW * 2 ** (notes[Math.round(u * (notes.length - 1))] / 12);
49+}
50+
51+export const SUSTAIN = { min: 0.1, max: 4, step: 0.1, default: 0.6 }; // s
52+const LOUD_WINDOW = 0.3; // s
53+const LOUDNESS = 0.12; // target K-weighted RMS over LOUD_WINDOW
54+
55+const TABLE = 2048; // samples per period in the wavetables
56+
57+// A tone at freq ringing for t60 s (the time to fade by 60 dB), with the
58+// harmonic amplitudes amp(k, freq), k = 1, 2, ... up to maxHz (and 0.45 of
59+// the sample rate): one period built additively, then read around at freq.
60+function tone(sr, freq, t60, amp, maxHz) {
61+ const K = Math.max(1, Math.floor(Math.min(maxHz, 0.45 * sr) / freq));
62+ const table = new Float32Array(TABLE + 1);
63+ for (let k = 1; k <= K; k++) {
64+ const a = amp(k, freq);
65+ if (!a) continue;
66+ for (let i = 0; i < TABLE; i++) table[i] += a * Math.sin((2 * Math.PI * k * i) / TABLE);
67+ }
68+ table[TABLE] = table[0];
69+ const len = Math.ceil(sr * t60);
70+ const out = new Float32Array(len);
71+ const step = (freq * TABLE) / sr;
72+ const decay = -6.9 / (t60 * sr);
73+ let ph = 0;
74+ for (let n = 0; n < len; n++) {
75+ const i = Math.floor(ph);
76+ const f = ph - i;
77+ out[n] = ((1 - f) * table[i] + f * table[i + 1]) * Math.exp(decay * n);
78+ ph += step;
79+ if (ph >= TABLE) ph -= TABLE;
80+ }
81+ return out;
82+}
83+
84+// The two tones θ₂ fades between. attack: s (raised cosine);
85+// render(sr, freq, t60).
86+export const TONES = [
87+ {
88+ name: 'Pure',
89+ attack: 0.005,
90+ // the fundamental, with a trace of the 2nd and 3rd harmonics, so low
91+ // notes still sound on small speakers
92+ render: (sr, f, t) => tone(sr, f, t, (k) => [0, 1, 0.08, 0.02][k] ?? 0, 4 * f),
93+ },
94+ {
95+ name: 'Buzzy',
96+ attack: 0.003,
97+ render: (sr, f, t) => tone(sr, f, t, (k, fr) => k ** -0.8 * (1 + 2.5 * Math.exp(-(((k * fr - 2000) / 900) ** 2))), 7000),
98+ },
99+];
100+
101+// A biquad filter applied to x, in place: [b0, b1, b2, a1, a2] (a0 = 1).
102+function biquad(x, [b0, b1, b2, a1, a2]) {
103+ let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
104+ for (let n = 0; n < x.length; n++) {
105+ const y = b0 * x[n] + b1 * x1 + b2 * x2 - a1 * y1 - a2 * y2;
106+ x2 = x1; x1 = x[n]; y2 = y1; y1 = y;
107+ x[n] = y;
108+ }
109+}
110+
111+// The K-weighting of ITU-R BS.1770 at sample rate sr (its two stages, from
112+// their analog prototypes): a high shelf, then a high-pass.
113+function kWeighting(sr) {
114+ let K = Math.tan((Math.PI * 1681.974450955533) / sr);
115+ const Q1 = 0.7071752369554196;
116+ const Vh = 10 ** (3.999843853973347 / 20);
117+ const Vb = Vh ** 0.4996667741545416;
118+ let a0 = 1 + K / Q1 + K * K;
119+ const shelf = [(Vh + (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - Vh)) / a0, (Vh - (Vb * K) / Q1 + K * K) / a0, (2 * (K * K - 1)) / a0, (1 - K / Q1 + K * K) / a0];
120+ K = Math.tan((Math.PI * 38.13547087602444) / sr);
121+ const Q2 = 0.5003270373238773;
122+ a0 = 1 + K / Q2 + K * K;
123+ const highpass = [1, -2, 1, (2 * (K * K - 1)) / a0, (1 - K / Q2 + K * K) / a0];
124+ return [shelf, highpass];
125+}
126+
127+// The K-weighted RMS of x (BS.1770's measure of loudness, without gating).
128+function loudness(x, sr) {
129+ const y = Float32Array.from(x);
130+ for (const stage of kWeighting(sr)) biquad(y, stage);
131+ let ss = 0;
132+ for (let n = 0; n < y.length; n++) ss += y[n] * y[n];
133+ return Math.sqrt(ss / y.length);
134+}
135+
136+// A tone's note at freq ringing for t60 s, as an AudioBuffer: with its
137+// attack and a short fade at the end, matched in loudness.
138+export function renderNote(ctx, voice, freq, t60) {
139+ const sr = ctx.sampleRate;
140+ const out = voice.render(sr, freq, t60);
141+ const att = Math.max(1, Math.floor(voice.attack * sr));
142+ const fade = Math.min(Math.floor(0.05 * sr), Math.floor(out.length / 4));
143+ for (let n = 0; n < out.length; n++) {
144+ const a = n < att ? 0.5 - 0.5 * Math.cos((Math.PI * n) / att) : 1;
145+ out[n] *= a * Math.min(1, (out.length - n) / fade);
146+ }
147+ const onset = out.subarray(0, Math.min(out.length, Math.floor(LOUD_WINDOW * sr)));
148+ const scale = LOUDNESS / (loudness(onset, sr) + 1e-12);
149+ for (let n = 0; n < out.length; n++) out[n] *= scale;
150+ const buf = ctx.createBuffer(1, out.length, sr);
151+ buf.copyToChannel(out, 0);
152+ return buf;
153+}
154+
155+// An exponentially decaying stereo noise tail, for the reverb.
156+function reverbImpulse(ctx, seconds = 1.6) {
157+ const len = Math.floor(ctx.sampleRate * seconds);
158+ const buf = ctx.createBuffer(2, len, ctx.sampleRate);
159+ for (let ch = 0; ch < 2; ch++) {
160+ const data = buf.getChannelData(ch);
161+ // noise, low-passed (about 2 kHz) so the tail is warm, not hissy
162+ let lp = 0;
163+ for (let n = 0; n < len; n++) {
164+ lp += 0.25 * (Math.random() * 2 - 1 - lp);
165+ data[n] = lp * Math.exp((-6.9 * n) / len);
166+ }
167+ }
168+ return buf;
169+}
170+
171+export function createSynth() {
172+ const ctx = new AudioContext();
173+ const master = ctx.createGain();
174+ const limiter = ctx.createDynamicsCompressor();
175+ limiter.threshold.value = -6;
176+ limiter.knee.value = 6;
177+ limiter.ratio.value = 12;
178+ limiter.attack.value = 0.003;
179+ limiter.release.value = 0.2;
180+ const tone = ctx.createBiquadFilter(); // a soft roll-off of the highs
181+ tone.type = 'lowpass';
182+ tone.frequency.value = 6000;
183+ tone.Q.value = 0.5;
184+ const dry = ctx.createGain();
185+ const wet = ctx.createGain();
186+ wet.gain.value = 0.45;
187+ const reverb = ctx.createConvolver();
188+ reverb.buffer = reverbImpulse(ctx);
189+ tone.connect(dry);
190+ dry.connect(master);
191+ dry.connect(reverb).connect(wet).connect(master);
192+ master.connect(limiter).connect(ctx.destination);
193+ const cache = new Map();
194+ // the notes still sounding, oldest first; past MAX_SOUNDING the oldest is
195+ // faded out, so fast tempos with many chains and long sustains stay light
196+ // (at 400 notes/s, 192 notes is about half a second)
197+ const MAX_SOUNDING = 192;
198+ let sounding = [];
199+ let sustain = SUSTAIN.default;
200+
201+ // the agreement drone: per chain, a soft triangle at the root (layer 0)
202+ // and one at the fifth (layer 1), each detuned by the page; with every
203+ // chain in tune, a plain fifth
204+ const droneOut = ctx.createGain();
205+ droneOut.gain.value = 0;
206+ droneOut.connect(tone);
207+ const droneLayers = [[], []];
208+ let droneRoot = 220;
209+ const droneFreq = (layer) => droneRoot * (layer ? 1.5 : 1);
210+
211+ return {
212+ ctx,
213+ setVolume(v) { master.gain.setTargetAtTime(v, ctx.currentTime, 0.02); },
214+ // the time (s) for each note to fade by 60 dB, for the notes from now on
215+ setSustain(s) {
216+ if (s === sustain) return;
217+ sustain = s;
218+ cache.clear();
219+ },
220+ // the drone: level in [0, 1] (0: silent), and cents[layer][chain]
221+ setDrone(level, cents) {
222+ const now = ctx.currentTime;
223+ droneOut.gain.setTargetAtTime(0.12 * level, now, 0.15);
224+ cents.forEach((list, layer) => {
225+ const oscs = droneLayers[layer];
226+ while (oscs.length < list.length) {
227+ const osc = ctx.createOscillator();
228+ osc.type = 'triangle';
229+ osc.frequency.value = droneFreq(layer);
230+ const g = ctx.createGain();
231+ g.gain.value = 0;
232+ osc.connect(g).connect(droneOut);
233+ osc.start();
234+ oscs.push({ osc, g });
235+ }
236+ while (oscs.length > list.length) {
237+ const { osc, g } = oscs.pop();
238+ g.gain.setTargetAtTime(0, now, 0.05);
239+ osc.stop(now + 0.4);
240+ }
241+ const share = (layer ? 0.6 : 1) / Math.sqrt(list.length);
242+ oscs.forEach(({ osc, g }, k) => {
243+ osc.detune.setTargetAtTime(list[k], now, 0.25);
244+ g.gain.setTargetAtTime(share, now, 0.1);
245+ });
246+ });
247+ },
248+ setDroneRoot(f) {
249+ droneRoot = f;
250+ droneLayers.forEach((oscs, layer) => {
251+ for (const { osc } of oscs) osc.frequency.setTargetAtTime(droneFreq(layer), ctx.currentTime, 0.05);
252+ });
253+ },
254+ // a note at freq, at time `when` (the context's clock), panned by pan in
255+ // [-1, 1], at level gain, its timbre bright in [0, 1] (0: pure, 1: buzzy)
256+ play(freq, when, { pan = 0, gain = 1, bright = 0.5 } = {}) {
257+ const level = ctx.createGain();
258+ level.gain.value = gain;
259+ const panner = ctx.createStereoPanner();
260+ panner.pan.value = pan;
261+ level.connect(panner).connect(tone);
262+ const srcs = TONES.map((voice, i) => {
263+ const key = `${i}:${Math.round(freq * 10)}`;
264+ let buf = cache.get(key);
265+ if (!buf) {
266+ buf = renderNote(ctx, voice, freq, sustain);
267+ if (cache.size > 400) cache.clear();
268+ cache.set(key, buf);
269+ }
270+ const src = ctx.createBufferSource();
271+ src.buffer = buf;
272+ const mix = ctx.createGain();
273+ mix.gain.value = i ? Math.sin((Math.PI / 2) * bright) : Math.cos((Math.PI / 2) * bright);
274+ src.connect(mix).connect(level);
275+ return src;
276+ });
277+ const buf = srcs[0].buffer;
278+ const t = Math.max(when, ctx.currentTime);
279+ for (const src of srcs) src.start(t);
280+ const end = t + buf.duration;
281+ sounding.push({ srcs, level, end });
282+ // drop those that have finished by now, then fade the excess
283+ if (sounding.length > MAX_SOUNDING) sounding = sounding.filter((n) => n.end >= ctx.currentTime);
284+ while (sounding.length > MAX_SOUNDING) {
285+ const old = sounding.shift();
286+ old.level.gain.setValueAtTime(old.level.gain.value, t);
287+ old.level.gain.linearRampToValueAtTime(0, t + 0.04);
288+ for (const src of old.srcs) src.stop(t + 0.05);
289+ }
290+ },
291+ };
292+}
app/main.jsadded+1046−0View file
@@ -0,0 +1,1046 @@
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).
40+
41+import { GeneralizedHMC, HMC, Langevin, NormalMixture2D, RandomWalkMetropolis } from './js/mixture.js';
42+import { createSynth, DEFAULT_KEY, DEFAULT_SCALE, KEYS, pitchOf, SCALES, SUSTAIN } from './js/voices.js';
43+
44+// the five targets of the notes (mixture_mcmc.md, "Interesting settings")
45+const BASE = { mu: 4, s11: 1, s12: 1, s21: 1, s22: 1, r1: 0, r2: 0 };
46+const 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+];
53+const DEFAULT_PRESET = 1;
54+
55+const MAX_CHAINS = 32;
56+const HIST_CAP = 1 << 17; // draws kept per chain; past it, thinned by 2
57+const LOOKAHEAD = 0.12; // s of iterations scheduled ahead
58+const TAIL = 0.3; // s of trail (at least 6 iterations)
59+const TRACE_LEN = 1000; // draws in the trace plot
60+const TEMPO = { min: 1, max: 400, default: 50 }; // iterations per second
61+const MAX_NOTE_RATE = 800; // notes per second, over all chains
62+const BINS = 64;
63+const SKIP = 1000; // iterations per "+1000"
64+const MARGIN = { left: 48, right: 12, top: 10 };
65+const REF_SIZE = 4000; // pooled draws ranks are taken against
66+const LISTEN = { live: 3, gap: 0.6, replay: 3 }; // s
67+
68+const $ = (id) => document.getElementById(id);
69+const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
70+const fmt2 = (v) => (v >= 1 ? v.toFixed(2) : v.toPrecision(2));
71+
72+// sliders: linear, or log (min > 0) over an integer 0..1000 input
73+const 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+];
83+const 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+];
88+const CHAIN_SLIDERS = [
89+ { key: 'count', label: 'Chains', min: 1, max: MAX_CHAINS, step: 1, fmt: (v) => String(v) },
90+];
91+
92+const params = { ...BASE, ...PRESETS[DEFAULT_PRESET].p, tau: 1 };
93+const tune = { kind: 'rwm', eps: 1, gamma: 0.1, L: 10, count: 8 };
94+
95+const canvas = $('plot');
96+const ctx = canvas.getContext('2d');
97+const densityLayer = document.createElement('canvas');
98+const dotsLayer = document.createElement('canvas');
99+
100+const model = new NormalMixture2D();
101+let range; // { X0, Y0 }: the θ₁, θ₂ half-ranges of pitch and timbre
102+let view; // { X, Y }: the half-ranges shown (equal scales)
103+let rects; // { main, hist, trace } in CSS px
104+let chains = [];
105+let startPoint = null; // null: starts on the τ circle; else [θ₁, θ₂]
106+let running = false; // paused until Run is pressed
107+let nextBeat = 0;
108+let beat = 0; // iterations scheduled so far, for the chains' turns
109+let tempo = TEMPO.default;
110+let synth = null;
111+let soundOn = false;
112+let key = DEFAULT_KEY;
113+let stats = null;
114+let statsAt = -Infinity;
115+let theme;
116+let ref = null; // sorted samples of the pooled θ₁ and θ₂, for ranks
117+let cycle = null; // listen back: { phase, until, ... }; null when off
118+let drone = null; // per chain detunes (cents), [θ₁ layer, θ₂ layer]
119+
120+// ---- chains -------------------------------------------------------------------
121+
122+function 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+ }
132+}
133+
134+const newHistory = () => ({ xs: new Float32Array(2 * HIST_CAP), n: 0, thin: 1, since: 0 });
135+
136+function 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++;
150+}
151+
152+const hueOf = (k) => (0.08 + k * 0.382) % 1;
153+
154+function newChain(k, theta0) {
155+ return { k, hue: hueOf(k), sampler: makeSampler(theta0), hist: newHistory(), queue: [], iters: 0, acc: 0 };
156+}
157+
158+function startOf() {
159+ return startPoint ? startPoint.slice() : null;
160+}
161+
162+// spread the chains over the stereo field
163+function 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;
166+}
167+
168+// a fresh set of draws, the chains staying where they are
169+function 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;
177+}
178+
179+// all chains from new starts (the τ circle, or the clicked point)
180+function restart() {
181+ chains = Array.from({ length: tune.count }, (_, k) => newChain(k, startOf()));
182+ setPans();
183+ newSegment();
184+}
185+
186+function 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();
191+}
192+
193+// the sampler changed kind: new samplers from where the chains are
194+function rebuildSamplers() {
195+ for (const c of chains) c.sampler = makeSampler(c.sampler.theta.slice());
196+ newSegment();
197+}
198+
199+function 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();
206+}
207+
208+// one iteration of chain c, recorded; returns the event for drawing and sound
209+function 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+ };
224+}
225+
226+// ---- the target ---------------------------------------------------------------------
227+
228+function 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();
241+}
242+
243+// ---- sound -------------------------------------------------------------------------
244+
245+const clock = () => (synth ? synth.ctx.currentTime : performance.now() / 1000);
246+const beatDt = () => 1 / tempo;
247+
248+// the rank of v in a sorted sample, in [0, 1] (ties: their middle)
249+function 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;
255+}
256+
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
259+function 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)];
262+}
263+
264+function 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 });
271+}
272+
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
276+function 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+ }
295+}
296+
297+// step every chain at each beat due within LOOKAHEAD, playing its note
298+function 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+ }
338+}
339+
340+function 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+ }
358+}
359+
360+function setRunning(on) {
361+ running = on;
362+ cycle = null;
363+ const btn = $('run');
364+ btn.setAttribute('aria-pressed', on);
365+ btn.textContent = on ? '❚❚ Pause' : '▶ Run';
366+}
367+
368+// SKIP iterations of every chain at once, silently
369+function 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;
381+}
382+
383+// ---- statistics ----------------------------------------------------------------------
384+
385+// split R̂ (Gelman et al., BDA3): each chain halved, between- against
386+// within-half variance
387+function 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);
402+}
403+
404+// the draws after warm-up (the second half of each chain), pooled
405+function 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+ };
457+}
458+
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)
462+function 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+ });
473+}
474+
475+const droneRoot = () => 130.81 * 2 ** (key / 12); // the key's root, C3 to B3
476+
477+function 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(/^-/, '−');
481+}
482+
483+function 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('');
509+}
510+
511+// ---- drawing ------------------------------------------------------------------------
512+
513+function 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') };
517+}
518+
519+const chainColor = (hue, alpha = 1) => `hsla(${Math.round(hue * 360)}, 80%, ${theme.light}, ${alpha})`;
520+
521+function 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);
527+}
528+
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
531+function 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) };
547+}
548+
549+const toPx = (r, [x, y]) => [r.x + ((x / view.X + 1) / 2) * r.w, r.y + ((1 - y / view.Y) / 2) * r.h];
550+
551+function 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);
556+}
557+
558+// the density, shaded on a log scale over 3.5 decades below its peak
559+function 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);
586+}
587+
588+function 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+ }
595+}
596+
597+function 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;
606+}
607+
608+// the dots of the iterations that have come due; the queues trimmed to the
609+// trail
610+function 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+ }
621+}
622+
623+const trailTime = () => Math.max(TAIL, 6 * beatDt());
624+
625+function 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);
629+}
630+
631+function 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();
668+}
669+
670+function 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();
690+}
691+
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
695+function 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();
761+}
762+
763+function 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);
774+}
775+
776+// the θ₁ marginal of the draws after warm-up (bars) and the exact one (line)
777+function 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);
806+}
807+
808+// θ₁ of each chain over its last TRACE_LEN draws, the modes' centers dashed
809+function 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);
858+}
859+
860+// the hint: what is playing while listening back
861+let hintText = '';
862+function 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+ }
880+}
881+
882+function 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();
907+}
908+
909+// ---- controls ------------------------------------------------------------------------
910+
911+// a group of sliders over the values in obj; onInput(key) after each change
912+function 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;
942+}
943+
944+function 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+ });
968+
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));
976+
977+ $('run').addEventListener('click', () => setRunning(!running));
978+ $('restart').addEventListener('click', () => {
979+ startPoint = null;
980+ restart();
981+ });
982+ $('skip').addEventListener('click', skipAhead);
983+
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));
1026+
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+ });
1037+}
1038+
1039+readTheme();
1040+matchMedia('(prefers-color-scheme: dark)').addEventListener('change', () => { readTheme(); resize(); });
1041+buildControls();
1042+applyModel();
1043+restart();
1044+new ResizeObserver(resize).observe(canvas);
1045+resize();
1046+requestAnimationFrame(frame);
app/style.cssadded+207−0View file
@@ -0,0 +1,207 @@
1+@font-face { font-family: "Source Serif 4"; font-weight: 300; src: url("vendor/fonts/source-serif-4-latin-300-normal.woff2") format("woff2"); }
2+@font-face { font-family: "Hanken Grotesk"; font-weight: 400; src: url("vendor/fonts/hanken-grotesk-latin-400-normal.woff2") format("woff2"); }
3+@font-face { font-family: "Hanken Grotesk"; font-weight: 600; src: url("vendor/fonts/hanken-grotesk-latin-600-normal.woff2") format("woff2"); }
4+
5+:root {
6+ --bg: #ffffff;
7+ --fg: #1c2954;
8+ --muted: #6b7491;
9+ --line: #dde1ea;
10+ --panel: #f5f6f9;
11+ --accent: #f6862d;
12+ --density: #2f4a9e;
13+ --dot-light: 46%;
14+ --font-head: "Tiempos Headline", "Source Serif 4", Georgia, serif;
15+ --font-body: "Founders Grotesk", "Hanken Grotesk", system-ui, sans-serif;
16+}
17+
18+@media (prefers-color-scheme: dark) {
19+ :root {
20+ --bg: #121418;
21+ --fg: #e6e8ee;
22+ --muted: #8d94a8;
23+ --line: #2a2e38;
24+ --panel: #1a1d23;
25+ --density: #9fb4f0;
26+ --dot-light: 66%;
27+ }
28+}
29+
30+* { box-sizing: border-box; }
31+
32+html, body { height: 100%; }
33+
34+body {
35+ margin: 0;
36+ display: flex;
37+ flex-direction: column;
38+ background: var(--bg);
39+ color: var(--fg);
40+ font-family: var(--font-body);
41+ font-size: 15px;
42+}
43+
44+header {
45+ padding: 14px 20px 6px;
46+ display: flex;
47+ align-items: center;
48+ justify-content: space-between;
49+ gap: 16px;
50+}
51+
52+/* the sound switch: large, and loud in color while the sound is off */
53+.sound-button {
54+ flex: none;
55+ display: flex;
56+ align-items: center;
57+ gap: 10px;
58+ padding: 10px 20px;
59+ border-radius: 999px;
60+ border: 2px solid var(--accent);
61+ background: var(--accent);
62+ color: #fff;
63+ font-size: 17px;
64+ font-weight: 600;
65+ box-shadow: 0 2px 10px rgba(246, 134, 45, 0.35);
66+}
67+.sound-button .icon { font-size: 20px; line-height: 1; }
68+.sound-button:hover { filter: brightness(1.05); }
69+.sound-button[aria-pressed="true"] { background: var(--panel); color: var(--fg); box-shadow: none; }
70+
71+h1 {
72+ margin: 0;
73+ font-family: var(--font-head);
74+ font-weight: 300;
75+ font-size: 26px;
76+}
77+
78+.eq { margin: 4px 0 0; font-family: var(--font-head); font-size: 17px; }
79+.eq i { font-family: var(--font-head); }
80+
81+.layout {
82+ flex: 1;
83+ min-height: 0;
84+ display: flex;
85+ gap: 16px;
86+ padding: 8px 20px 20px;
87+}
88+
89+.panel {
90+ flex: 0 0 300px;
91+ display: flex;
92+ flex-direction: column;
93+ gap: 14px;
94+ overflow-y: auto;
95+ padding-right: 4px;
96+}
97+
98+.group { display: flex; flex-direction: column; gap: 8px; }
99+.group + .group { padding-top: 14px; border-top: 1px solid var(--line); }
100+
101+h2 {
102+ margin: 0;
103+ font-size: 13px;
104+ font-weight: 600;
105+ letter-spacing: 0.04em;
106+ text-transform: uppercase;
107+ color: var(--muted);
108+}
109+h2 .note { text-transform: none; letter-spacing: 0; font-weight: 400; }
110+
111+.sliders { display: flex; flex-direction: column; gap: 6px; }
112+
113+.row {
114+ display: grid;
115+ grid-template-columns: 78px 1fr 56px;
116+ align-items: center;
117+ gap: 8px;
118+}
119+
120+.row[hidden] { display: none; }
121+.row > span { color: var(--muted); font-size: 14px; }
122+.row > select { grid-column: 2 / 4; }
123+.row output { font-variant-numeric: tabular-nums; font-size: 13px; text-align: right; }
124+.row sub, .row sup { font-size: 0.7em; }
125+
126+.note { margin: 0; color: var(--muted); font-size: 13px; }
127+
128+input[type="range"] { width: 100%; accent-color: var(--accent); }
129+
130+select, button {
131+ font: inherit;
132+ color: var(--fg);
133+ background: var(--panel);
134+ border: 1px solid var(--line);
135+ border-radius: 6px;
136+ padding: 6px 8px;
137+}
138+
139+button { cursor: pointer; }
140+
141+.buttons { display: grid; grid-template-columns: 1fr 1fr 1fr; gap: 6px; }
142+
143+.keys { grid-column: 2 / 4; display: grid; grid-template-columns: repeat(6, 1fr); gap: 4px; }
144+.keys button { padding: 3px 0; font-size: 13px; }
145+
146+.toggle[aria-pressed="true"], .keys button[aria-pressed="true"] { background: var(--accent); border-color: var(--accent); color: #fff; }
147+
148+.chain-list { list-style: none; margin: 0; padding: 0; display: flex; flex-wrap: wrap; gap: 6px; }
149+.chain-list:empty { display: none; }
150+.chain-list li {
151+ display: flex;
152+ align-items: center;
153+ gap: 6px;
154+ padding: 2px 8px;
155+ border: 1px solid var(--line);
156+ border-radius: 999px;
157+ font-size: 13px;
158+}
159+.chain-list .swatch { width: 10px; height: 10px; border-radius: 50%; }
160+.chain-list .acc { font-variant-numeric: tabular-nums; }
161+.chain-list li { padding: 1px 7px; font-size: 12px; gap: 5px; }
162+
163+.stats { border-collapse: collapse; font-size: 13px; font-variant-numeric: tabular-nums; }
164+.stats th, .stats td { padding: 2px 6px; text-align: right; }
165+.stats th { color: var(--muted); font-weight: 400; }
166+.stats th:first-child, .stats td:first-child { text-align: left; padding-left: 0; }
167+.stats td:first-child { color: var(--muted); }
168+.stats .off { color: var(--accent); font-weight: 600; }
169+
170+.plot-wrap {
171+ position: relative;
172+ flex: 1;
173+ min-width: 0;
174+ min-height: 0;
175+}
176+
177+#plot {
178+ position: absolute;
179+ inset: 0;
180+ width: 100%;
181+ height: 100%;
182+ cursor: crosshair;
183+ touch-action: manipulation;
184+}
185+
186+.hint {
187+ position: absolute;
188+ top: 8px;
189+ left: 52px;
190+ margin: 0;
191+ padding: 4px 10px;
192+ border-radius: 6px;
193+ background: var(--panel);
194+ color: var(--muted);
195+ font-size: 14px;
196+ pointer-events: none;
197+}
198+
199+@media (max-width: 760px) {
200+ header { padding: 12px 16px 4px; flex-wrap: wrap; }
201+ .sound-button { font-size: 15px; padding: 8px 16px; }
202+ h1 { font-size: 22px; }
203+ .layout { flex-direction: column; padding: 8px 16px 16px; }
204+ .panel { flex: none; overflow: visible; padding-right: 0; }
205+ .plot-wrap { flex: none; height: min(130vw, 85vh); order: -1; }
206+ body { height: auto; }
207+}
app/vendor/fonts/LICENSE-hanken-groteskadded+93−0View file
@@ -0,0 +1,93 @@
1+Copyright 2021 The Hanken Grotesk Project Authors (https://github.com/marcologous/hanken-grotesk) HankenGrotesk-Italic[wght].ttf: Copyright 2021 The Hanken Grotesk Project Authors (https://github.com/marcologous/hanken-grotesk)
2+
3+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4+This license is copied below, and is also available with a FAQ at:
5+http://scripts.sil.org/OFL
6+
7+
8+-----------------------------------------------------------
9+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10+-----------------------------------------------------------
11+
12+PREAMBLE
13+The goals of the Open Font License (OFL) are to stimulate worldwide
14+development of collaborative font projects, to support the font creation
15+efforts of academic and linguistic communities, and to provide a free and
16+open framework in which fonts may be shared and improved in partnership
17+with others.
18+
19+The OFL allows the licensed fonts to be used, studied, modified and
20+redistributed freely as long as they are not sold by themselves. The
21+fonts, including any derivative works, can be bundled, embedded,
22+redistributed and/or sold with any software provided that any reserved
23+names are not used by derivative works. The fonts and derivatives,
24+however, cannot be released under any other type of license. The
25+requirement for fonts to remain under this license does not apply
26+to any document created using the fonts or their derivatives.
27+
28+DEFINITIONS
29+"Font Software" refers to the set of files released by the Copyright
30+Holder(s) under this license and clearly marked as such. This may
31+include source files, build scripts and documentation.
32+
33+"Reserved Font Name" refers to any names specified as such after the
34+copyright statement(s).
35+
36+"Original Version" refers to the collection of Font Software components as
37+distributed by the Copyright Holder(s).
38+
39+"Modified Version" refers to any derivative made by adding to, deleting,
40+or substituting -- in part or in whole -- any of the components of the
41+Original Version, by changing formats or by porting the Font Software to a
42+new environment.
43+
44+"Author" refers to any designer, engineer, programmer, technical
45+writer or other person who contributed to the Font Software.
46+
47+PERMISSION & CONDITIONS
48+Permission is hereby granted, free of charge, to any person obtaining
49+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50+redistribute, and sell modified and unmodified copies of the Font
51+Software, subject to the following conditions:
52+
53+1) Neither the Font Software nor any of its individual components,
54+in Original or Modified Versions, may be sold by itself.
55+
56+2) Original or Modified Versions of the Font Software may be bundled,
57+redistributed and/or sold with any software, provided that each copy
58+contains the above copyright notice and this license. These can be
59+included either as stand-alone text files, human-readable headers or
60+in the appropriate machine-readable metadata fields within text or
61+binary files as long as those fields can be easily viewed by the user.
62+
63+3) No Modified Version of the Font Software may use the Reserved Font
64+Name(s) unless explicit written permission is granted by the corresponding
65+Copyright Holder. This restriction only applies to the primary font name as
66+presented to the users.
67+
68+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69+Software shall not be used to promote, endorse or advertise any
70+Modified Version, except to acknowledge the contribution(s) of the
71+Copyright Holder(s) and the Author(s) or with their explicit written
72+permission.
73+
74+5) The Font Software, modified or unmodified, in part or in whole,
75+must be distributed entirely under this license, and must not be
76+distributed under any other license. The requirement for fonts to
77+remain under this license does not apply to any document created
78+using the Font Software.
79+
80+TERMINATION
81+This license becomes null and void if any of the above conditions are
82+not met.
83+
84+DISCLAIMER
85+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93+OTHER DEALINGS IN THE FONT SOFTWARE.
app/vendor/fonts/LICENSE-source-serif-4added+93−0View file
@@ -0,0 +1,93 @@
1+Google Inc.
2+
3+This Font Software is licensed under the SIL Open Font License, Version 1.1.
4+This license is copied below, and is also available with a FAQ at:
5+http://scripts.sil.org/OFL
6+
7+
8+-----------------------------------------------------------
9+SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
10+-----------------------------------------------------------
11+
12+PREAMBLE
13+The goals of the Open Font License (OFL) are to stimulate worldwide
14+development of collaborative font projects, to support the font creation
15+efforts of academic and linguistic communities, and to provide a free and
16+open framework in which fonts may be shared and improved in partnership
17+with others.
18+
19+The OFL allows the licensed fonts to be used, studied, modified and
20+redistributed freely as long as they are not sold by themselves. The
21+fonts, including any derivative works, can be bundled, embedded,
22+redistributed and/or sold with any software provided that any reserved
23+names are not used by derivative works. The fonts and derivatives,
24+however, cannot be released under any other type of license. The
25+requirement for fonts to remain under this license does not apply
26+to any document created using the fonts or their derivatives.
27+
28+DEFINITIONS
29+"Font Software" refers to the set of files released by the Copyright
30+Holder(s) under this license and clearly marked as such. This may
31+include source files, build scripts and documentation.
32+
33+"Reserved Font Name" refers to any names specified as such after the
34+copyright statement(s).
35+
36+"Original Version" refers to the collection of Font Software components as
37+distributed by the Copyright Holder(s).
38+
39+"Modified Version" refers to any derivative made by adding to, deleting,
40+or substituting -- in part or in whole -- any of the components of the
41+Original Version, by changing formats or by porting the Font Software to a
42+new environment.
43+
44+"Author" refers to any designer, engineer, programmer, technical
45+writer or other person who contributed to the Font Software.
46+
47+PERMISSION & CONDITIONS
48+Permission is hereby granted, free of charge, to any person obtaining
49+a copy of the Font Software, to use, study, copy, merge, embed, modify,
50+redistribute, and sell modified and unmodified copies of the Font
51+Software, subject to the following conditions:
52+
53+1) Neither the Font Software nor any of its individual components,
54+in Original or Modified Versions, may be sold by itself.
55+
56+2) Original or Modified Versions of the Font Software may be bundled,
57+redistributed and/or sold with any software, provided that each copy
58+contains the above copyright notice and this license. These can be
59+included either as stand-alone text files, human-readable headers or
60+in the appropriate machine-readable metadata fields within text or
61+binary files as long as those fields can be easily viewed by the user.
62+
63+3) No Modified Version of the Font Software may use the Reserved Font
64+Name(s) unless explicit written permission is granted by the corresponding
65+Copyright Holder. This restriction only applies to the primary font name as
66+presented to the users.
67+
68+4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
69+Software shall not be used to promote, endorse or advertise any
70+Modified Version, except to acknowledge the contribution(s) of the
71+Copyright Holder(s) and the Author(s) or with their explicit written
72+permission.
73+
74+5) The Font Software, modified or unmodified, in part or in whole,
75+must be distributed entirely under this license, and must not be
76+distributed under any other license. The requirement for fonts to
77+remain under this license does not apply to any document created
78+using the Font Software.
79+
80+TERMINATION
81+This license becomes null and void if any of the above conditions are
82+not met.
83+
84+DISCLAIMER
85+THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
86+EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
87+MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
88+OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
89+COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
90+INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
91+DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
92+FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
93+OTHER DEALINGS IN THE FONT SOFTWARE.
app/vendor/fonts/hanken-grotesk-latin-400-normal.woff2added+0−0View file
Binary file not shown.
app/vendor/fonts/hanken-grotesk-latin-600-normal.woff2added+0−0View file
Binary file not shown.
app/vendor/fonts/source-serif-4-latin-300-normal.woff2added+0−0View file
Binary file not shown.
package.jsonadded+9−0View file
@@ -0,0 +1,9 @@
1+{
2+ "name": "mcmc-sonification",
3+ "private": true,
4+ "type": "module",
5+ "scripts": {
6+ "dev": "python3 -m http.server 8003 --bind 127.0.0.1 --directory app",
7+ "check": "for f in app/*.js app/js/*.js scripts/*.mjs; do node --check \"$f\" || exit 1; done && node scripts/check-samplers.mjs > /dev/null"
8+ }
9+}
scripts/check-samplers.mjsadded+54−0View file
@@ -0,0 +1,54 @@
1+// Runs the samplers on the five models of the notes (mixture_mcmc.md) and
2+// prints acceptance, mode switches (sign changes of θ₁), and the sample
3+// mean and covariance against the exact values: a check of the port.
4+// node scripts/check-samplers.mjs
5+import { NormalMixture2D, RandomWalkMetropolis, Langevin, GeneralizedHMC, HMC } from '../app/js/mixture.js';
6+
7+const MODELS = {
8+ easy: { mu: 3 },
9+ separated: { mu: 6 },
10+ ridge: { mu: 4, rho: [0.95, -0.95] },
11+ stiff: { mu: 4, sigma: [[1, 1], [0.1, 0.1]] },
12+ crossed: { mu: 4, sigma: [[2, 0.25], [0.25, 2]] },
13+};
14+
15+const RUNS = [
16+ ['RWM 0.1', (m) => new RandomWalkMetropolis(m, 0.1, { seed: 2 })],
17+ ['RWM 0.75', (m) => new RandomWalkMetropolis(m, 0.75, { seed: 2 })],
18+ ['RWM 2', (m) => new RandomWalkMetropolis(m, 2, { seed: 2 })],
19+ ['RWM 4', (m) => new RandomWalkMetropolis(m, 4, { seed: 2 })],
20+ ['MALA 0.2', (m) => new Langevin(m, 0.2, { seed: 2 })],
21+ ['MALA 0.5', (m) => new Langevin(m, 0.5, { seed: 2 })],
22+ ['MALA 1', (m) => new Langevin(m, 1, { seed: 2 })],
23+ ['ULA 0.2', (m) => new Langevin(m, 0.2, { adjust: false, seed: 2 })],
24+ ['ULA 0.75', (m) => new Langevin(m, 0.75, { adjust: false, seed: 2 })],
25+ ['GHMC .2/.01', (m) => new GeneralizedHMC(m, 0.2, { gamma: 0.01, seed: 2 })],
26+ ['GHMC .2/1', (m) => new GeneralizedHMC(m, 0.2, { gamma: 1, seed: 2 })],
27+ ['GHMC .5/.05', (m) => new GeneralizedHMC(m, 0.5, { gamma: 0.05, seed: 2 })],
28+ ['HMC .1/10', (m) => new HMC(m, 0.1, { nSteps: 10, seed: 2 }), 2000],
29+ ['HMC .25/20', (m) => new HMC(m, 0.25, { nSteps: 20, seed: 2 }), 2000],
30+ ['HMC .5/10', (m) => new HMC(m, 0.5, { nSteps: 10, seed: 2 }), 2000],
31+ ['HMC 1/5', (m) => new HMC(m, 1, { nSteps: 5, seed: 2 }), 2000],
32+];
33+
34+const f = (v, d = 2) => (Number.isFinite(v) ? v.toFixed(d) : String(v)).padStart(7);
35+for (const [name, args] of Object.entries(MODELS)) {
36+ const model = new NormalMixture2D(args);
37+ const t = model.truth();
38+ console.log(`\n${name}: max stable step ${model.maxStableStepSize().toFixed(2)}; exact var θ1 ${t.cov[0][0].toFixed(2)}, var θ2 ${t.cov[1][1].toFixed(2)}, cov ${t.cov[0][1].toFixed(2)}`);
39+ console.log(' sampler accept switches mean1 mean2 var1 var2 cov right');
40+ for (const [label, make, n = 5000] of RUNS) {
41+ const s = make(model);
42+ let m1 = 0, m2 = 0, s11 = 0, s22 = 0, s12 = 0, sw = 0, right = 0, prev = Math.sign(s.theta[0]);
43+ for (let i = 0; i < n; i++) {
44+ const [a, b] = s.next();
45+ m1 += a; m2 += b; s11 += a * a; s22 += b * b; s12 += a * b;
46+ const sg = Math.sign(a);
47+ if (sg && prev && sg !== prev) sw++;
48+ if (sg) prev = sg;
49+ right += a > 0;
50+ }
51+ m1 /= n; m2 /= n;
52+ console.log(` ${label.padEnd(13)} ${f(100 * s.acceptanceRate, 0)}% ${String(sw).padStart(8)} ${f(m1)} ${f(m2)} ${f(s11 / n - m1 * m1)} ${f(s22 / n - m2 * m2)} ${f(s12 / n - m1 * m2)} ${f(right / n)}${s.diverged ? ' diverged' : ''}`);
53+ }
54+}
↑↓ move↵openescclose