/ listening-for-chaos / chaos-apps
Sign in
listening-for-chaos / chaos-apps
Spectrogram: log frequency axis by default with a 'log f' chip for linear; rows show the loudest bin in their band; mode lines decided per line
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 63e5e6e27bc8 parent 90c1386 Browse files
10 changed files+101−25
src/beam/README.mdmodified+1−1View file
@@ -4,7 +4,7 @@ Struck beam with bending stiffness, step 3 of "Listening for chaos" (after doubl
44
55 Current state: N masses (2 to 64, default 8) on vertical rails, moving sideways only, with tension k, bending κ and a stretching nonlinearity k3 (below). Ends (a select next to Masses; changing it returns the beam to rest): clamped–clamped (default), pinned–pinned, or cantilever (clamped at the left, free at the right). Strike gives energy E (log slider, 10 µJ to 100 J, default 2.51 J) as velocity, on one mass alone (default mass 2) or in the shape of one normal mode. The card draws the beam from the side, displacements scaled to fit (scale given), with rails as faint lines, a hatched wall for a clamp and a triangle for a pin, plus the time, energy and relative energy error. The Ghost chip (as in fput-chain; controls in `../common/ghost.ts`) adds a second beam started from the same state with every mass moved by 10^k / sqrt(N) m (total offset 10^k m, k = -12 to -1, default -10), run in lockstep without renormalization and drawn in translucent orange underneath; restarted on Strike, on "Restart ghost", when switched on or when the offset changes; a readout gives the separation (root sum of squared displacement differences, m) and the time since the ghost started. Default strike: the separation stays near 1e-10 m for ~10 s, then grows to 1.7e-8 m by 39.5 s, e^5.1, matching λ since the strike (0.13 /s × 39.5 s). A "Real time" card on the right has chips: Mode bars (on; the current harmonic energy of each mode relative to the strike, log scale over 12 decades, with the number of modes sharing the energy, 1 / sum (E_n / sum E)^2, and the mode frequency range; `../common/modebars.ts`), Mode history (off; each mode's share of the harmonic energy over the last 300 s as a heat map, mode 1 at the bottom; `LiveModeHistory` in `../common/modehistory.ts`), and charts (`../common/traces.ts`): Lyapunov (on; the largest Lyapunov exponent over the last 10 s and since the strike, last 60 s shown, the first 5 s after a strike left out of the y range) Mode energies (off; log, last 60 s, values below 1e-12 of the strike left out), Energy error (off) and Separation (log, last 60 s; offered only with the ghost on). The exponent is the two-trajectory method of `../common/lyapunov.ts` with the beam's shadow in `lyapunov.ts`: a hidden second beam 1e-8 away, displacements in units of A / sqrt(N) and momenta in units of m omega_1 A / sqrt(N), A the mode-1 amplitude at the nonlinear scale. Speed 0.1x to 20x real time; Pause or space. Parameters (m, k, κ, k3, a, τ, stretching form) fold out with derived values (mode frequencies, ratios to mode 1, the nonlinear scale, integrator step); Apply returns the beam to rest.
66
7-"Sped up · listen" (as in fput-chain): each Strike renders the same strike in a worker (`render-worker.ts`), sped up so the lowest mode sounds at the Pitch (5 to 1000 Hz, default 100), and plays it; the page starts muted. A damped note is the whole decay to -60 dB. A red warning shows when the top mode is above half the sample rate (it would alias). Signals (`signals.ts`): velocity (default), displacement or acceleration of mass j (default 2), or the sum of accelerations (the net force of the supports). Replay, Save WAV (named e.g. beam-clamped-local-N8-mass2-2.51J-v2-100Hz.wav), spectrogram over the whole note with dashed lines at the mode pitches. Chips: Spectrogram (on), Modes (off; the note's mode-energy shares over the whole note, one column per 256 samples, from the worker; `ModeHistory` in `../common/modehistory.ts`), Lyapunov (on; the note's exponent over the last 10 s of physical time, from a shadow run in the worker; the first 5 s of physical time left out of the y range; the shadow runs only while this chart or λ vs E is shown, as it doubles the cost) Energy (log) and λ vs E (off; `../common/scatter.ts` as in fput-chain: one point per 256 samples, accumulated over notes, log energy axis, colored by time into the note, earlier notes faded, hover for values, Clear; not cleared when parameters change). All but λ vs E span the whole note and share one cursor (playhead while playing; hover, click to pin). The render loop is shared with fput-chain (`../common/note-render.ts`). The status line gives the render time (default note 1.0 to 1.4 s with the shadow, 0.6 s without).
7+"Sped up · listen" (as in fput-chain): each Strike renders the same strike in a worker (`render-worker.ts`), sped up so the lowest mode sounds at the Pitch (5 to 1000 Hz, default 100), and plays it; the page starts muted. A damped note is the whole decay to -60 dB. A red warning shows when the top mode is above half the sample rate (it would alias). Signals (`signals.ts`): velocity (default), displacement or acceleration of mass j (default 2), or the sum of accelerations (the net force of the supports). Replay, Save WAV (named e.g. beam-clamped-local-N8-mass2-2.51J-v2-100Hz.wav), spectrogram over the whole note with dashed lines at the mode pitches. Chips: Spectrogram (on; frequency axis logarithmic by default, from a round number at or below half the lowest mode pitch, with a "log f" chip to switch to linear from 0; each pixel row shows the loudest FFT bin in its band; mode lines each drawn only while at least 6 px from their neighbours: at the default note the six lowest are drawn, modes 7 and 8 are 2 px apart; on the old linear axis to 10 kHz the modes filled the bottom eighth), Modes (off; the note's mode-energy shares over the whole note, one column per 256 samples, from the worker; `ModeHistory` in `../common/modehistory.ts`), Lyapunov (on; the note's exponent over the last 10 s of physical time, from a shadow run in the worker; the first 5 s of physical time left out of the y range; the shadow runs only while this chart or λ vs E is shown, as it doubles the cost) Energy (log) and λ vs E (off; `../common/scatter.ts` as in fput-chain: one point per 256 samples, accumulated over notes, log energy axis, colored by time into the note, earlier notes faded, hover for values, Clear; not cleared when parameters change). All but λ vs E span the whole note and share one cursor (playhead while playing; hover, click to pin). The render loop is shared with fput-chain (`../common/note-render.ts`). The status line gives the render time (default note 1.0 to 1.4 s with the shadow, 0.6 s without).
88
99 Live site: https://chaos-apps--listening-for-chaos.vault1-sites.magland.org/beam/ (part of the chaos-apps site).
1010
src/beam/index.htmlmodified+1−0View file
@@ -106,6 +106,7 @@
106106 <button id="save-wav" type="button" disabled title="Save the last note as a WAV file">Save WAV</button>
107107 <span id="sound-chips" class="chips">
108108 <label class="chip"><input id="spec-toggle" type="checkbox" checked /><span>Spectrogram</span></label>
109+ <label class="chip" title="Logarithmic frequency axis (off: linear from 0)"><input id="spec-log" type="checkbox" checked /><span>log f</span></label>
109110 <label class="chip" title="Each mode's share of the energy over the note"><input id="modes-toggle" type="checkbox" /><span>Modes</span></label>
110111 </span>
111112 </div>
src/beam/main.tsmodified+3−1View file
@@ -295,6 +295,8 @@ const soundCursor = newCursor();
295295 const specFig = document.getElementById("spec-fig")!;
296296 const specToggle = document.getElementById("spec-toggle") as HTMLInputElement;
297297 specToggle.addEventListener("change", () => (specFig.hidden = !specToggle.checked));
298+const specLog = document.getElementById("spec-log") as HTMLInputElement; // log frequency axis
299+specLog.addEventListener("change", () => spec?.setLog(specLog.checked));
298300 let noteEnergy = NaN, noteLambda = NaN;
299301 const soundTraces = new TracePanel(
300302 document.getElementById("sound-chips")!,
@@ -399,7 +401,7 @@ worker.onmessage = (e: MessageEvent<RenderResult>) => {
399401 // below that longer, in proportion (as in the FPUT chain).
400402 const n = Math.min(16384, 2 ** Math.ceil(Math.log2((2048 * 30) / Math.min(30, pitch()))));
401403 spec = new NoteSpectrogram(
402- { dt: 1 / rate, n, nfft: 2 * n, hop: n / 4, refFreqs: modePitches(), width: 960 },
404+ { dt: 1 / rate, n, nfft: 2 * n, hop: n / 4, refFreqs: modePitches(), width: 960, log: specLog.checked },
403405 soundCursor,
404406 );
405407 spec.start(span);
src/common/spectrogram.tsmodified+86−19View file
@@ -3,14 +3,18 @@
33 // padded to `nfft`) becomes one column. The frequency axis tops out just
44 // above the highest frequency that comes within CONTENT_DB of the peak at any
55 // time (a time average would hide the broadband start of a chaotic note under
6-// its long, quiet, tonal tail).
6+// its long, quiet, tonal tail). It is linear from 0, or logarithmic from fmin,
7+// a round number at or below half the lowest reference frequency (so widely
8+// spread modes, as in a stiff beam, each get room, while the broadband start
9+// stays in view). Each pixel row shows the loudest FFT bin within its band of
10+// frequencies, so narrow lines are not missed where a row spans many bins.
711
812 import { attachCursor, type Cursor } from "./cursor";
913
1014 const HEIGHT = 200;
1115 const RANGE_DB = 60; // color range below the peak
1216 const CONTENT_DB = 40; // "significant" power for the frequency auto scale
13-const MIN_REF_GAP = 6; // px between reference lines, or none are drawn
17+const MIN_REF_GAP = 6; // px from a reference line to its neighbours, or it is not drawn
1418
1519 export interface SpectrogramOptions {
1620 dt: number; // sample spacing (s)
@@ -18,6 +22,7 @@ export interface SpectrogramOptions {
1822 nfft: number; // zero-padded FFT length (power of two)
1923 hop: number; // samples between columns
2024 refFreqs: number[]; // frequencies to mark with dashed lines (Hz)
25+ log?: boolean; // logarithmic frequency axis (default linear)
2126 width?: number; // columns kept and drawn (canvas width), default 480
2227 }
2328
@@ -30,6 +35,15 @@ function label(ctx: CanvasRenderingContext2D, text: string, x: number, y: number
3035 ctx.fillText(text, x + 3, y + 2);
3136 }
3237
38+// Largest 1, 2 or 5 times a power of ten that is <= x (allowing for
39+// round-off, so 49.9999999 gives 50).
40+function niceFloor(x: number): number {
41+ x *= 1 + 1e-9;
42+ const p = Math.pow(10, Math.floor(Math.log10(x)));
43+ for (const m of [5, 2, 1]) if (m * p <= x) return +(m * p).toPrecision(1);
44+ return p;
45+}
46+
3347 // Smallest 1, 2 or 5 times a power of ten that is >= x.
3448 function niceCeil(x: number): number {
3549 const p = Math.pow(10, Math.floor(Math.log10(x)));
@@ -127,6 +141,9 @@ export class NoteSpectrogram {
127141 private hold: Float64Array; // largest power in each bin over all raw columns
128142 private peak = 0;
129143 private fmax = 1;
144+ private log: boolean;
145+ private rowLo = new Int32Array(HEIGHT); // FFT bins shown in each pixel row
146+ private rowHi = new Int32Array(HEIGHT);
130147 private span = 10; // s shown across the width
131148 private drawnX = 0; // pixel columns already drawn
132149 private dirty = true; // full redraw needed
@@ -140,6 +157,7 @@ export class NoteSpectrogram {
140157 this.hop = opts.hop;
141158 this.bins = opts.nfft / 2 + 1;
142159 this.refFreqs = opts.refFreqs;
160+ this.log = opts.log ?? false;
143161 this.buf = new Float64Array(this.n);
144162 this.hann = new Float64Array(this.n);
145163 for (let i = 0; i < this.n; i++) this.hann[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / (this.n - 1));
@@ -178,6 +196,49 @@ export class NoteSpectrogram {
178196 this.dirty = true;
179197 }
180198
199+ setLog(log: boolean): void {
200+ this.log = log;
201+ this.dirty = true;
202+ }
203+
204+ private df(): number {
205+ return 1 / (2 * (this.bins - 1) * this.dt);
206+ }
207+
208+ // Bottom of the log axis (Hz): a round number at or below half the lowest
209+ // reference frequency (20 Hz without any), and at least one bin up.
210+ private fmin(): number {
211+ const lo = this.refFreqs.length ? Math.min(...this.refFreqs) / 2 : 20;
212+ return Math.max(niceFloor(lo), this.df());
213+ }
214+
215+ // Frequency (Hz) at pixel height y (0 at the top; fractional y allowed).
216+ private freqAt(y: number): number {
217+ const u = (HEIGHT - 1 - y) / (HEIGHT - 1); // 0 at the bottom, 1 at the top
218+ if (!this.log) return this.fmax * u;
219+ const fmin = this.fmin();
220+ return fmin * (this.fmax / fmin) ** u;
221+ }
222+
223+ // Pixel height of frequency f (inverse of freqAt).
224+ private yAt(f: number): number {
225+ const u = this.log ? Math.log(f / this.fmin()) / Math.log(this.fmax / this.fmin()) : f / this.fmax;
226+ return (HEIGHT - 1) * (1 - u);
227+ }
228+
229+ // The FFT bins each pixel row shows: those in its band of frequencies, or
230+ // the nearest one when the band holds none.
231+ private setRows(): void {
232+ const df = this.df(), last = this.bins - 1;
233+ for (let y = 0; y < HEIGHT; y++) {
234+ const fa = this.freqAt(Math.min(HEIGHT - 1, y + 0.5)), fb = this.freqAt(Math.max(0, y - 0.5));
235+ let lo = Math.ceil(fa / df), hi = Math.floor(fb / df);
236+ if (hi < lo) lo = hi = Math.round(this.freqAt(y) / df);
237+ this.rowLo[y] = Math.min(last, Math.max(0, lo));
238+ this.rowHi[y] = Math.min(last, Math.max(0, hi));
239+ }
240+ }
241+
181242 push(x: number): void {
182243 this.buf[this.nSamples % this.n] = x;
183244 this.nSamples++;
@@ -223,13 +284,15 @@ export class NoteSpectrogram {
223284
224285 draw(): void {
225286 const { bins, cols } = this;
226- const df = 1 / (2 * (bins - 1) * this.dt);
287+ const df = this.df();
227288 let holdPeak = 0;
228289 for (let k = 1; k < bins; k++) if (this.hold[k] > holdPeak) holdPeak = this.hold[k];
229290 let top = bins - 1;
230291 while (top > 1 && this.hold[top] < holdPeak * 10 ** (-CONTENT_DB / 10)) top--;
231292 if (cols.length > 0) {
232- const fmax = Math.min(niceCeil(1.2 * top * df), (bins - 1) * df);
293+ // On a log axis the top stays at least 4 fmin, so the axis spans a range.
294+ const floor = this.log ? 4 * this.fmin() : 0;
295+ const fmax = Math.min(niceCeil(Math.max(1.2 * top * df, floor)), (bins - 1) * df);
233296 if (fmax !== this.fmax) this.dirty = true;
234297 this.fmax = fmax;
235298 }
@@ -239,7 +302,10 @@ export class NoteSpectrogram {
239302 const t0 = this.n * this.dt; // the first column ends here
240303 const tReady = cols.length > 0 ? t0 + (cols.length - 0.5) * colDt : 0;
241304 const ready = Math.min(this.width, Math.max(0, Math.floor((tReady / this.span) * this.width)));
242- if (this.dirty) this.drawnX = 0;
305+ if (this.dirty) {
306+ this.drawnX = 0;
307+ this.setRows();
308+ }
243309 const cursorKey = this.cursor ? `${this.cursor.t}|${this.cursor.pinned}` : "";
244310 if (!this.dirty && ready <= this.drawnX && cursorKey === this.lastCursor) return;
245311 this.lastCursor = cursorKey;
@@ -257,9 +323,9 @@ export class NoteSpectrogram {
257323 if (!col) {
258324 data[p] = data[p + 1] = data[p + 2] = 246; // no data (yet)
259325 } else {
260- const f = (this.fmax * (HEIGHT - 1 - y)) / (HEIGHT - 1);
261- const k = Math.min(bins - 1, Math.round(f / df));
262- const db = 10 * Math.log10(col[k] + 1e-30);
326+ let pw = 0;
327+ for (let k = this.rowLo[y]; k <= this.rowHi[y]; k++) if (col[k] > pw) pw = col[k];
328+ const db = 10 * Math.log10(pw + 1e-30);
263329 colormap((db - (peakDb - RANGE_DB)) / RANGE_DB, data, p);
264330 }
265331 data[p + 3] = 255;
@@ -270,25 +336,26 @@ export class NoteSpectrogram {
270336
271337 const ctx = this.canvas.getContext("2d")!;
272338 ctx.putImageData(this.image, 0, 0);
273- const py = (f: number) => (HEIGHT - 1) * (1 - f / this.fmax);
339+ const py = (f: number) => this.yAt(f);
274340 ctx.strokeStyle = "rgba(255,255,255,0.7)";
275341 ctx.setLineDash([4, 4]);
276- // Reference lines only while they are far enough apart to read as
277- // separate lines (crowded together, their dashes merge into a solid
278- // on-off bar that looks like signal).
279- const shown = this.refFreqs.filter((f) => f < this.fmax).sort((a, b) => a - b);
280- let minGap = Infinity;
281- for (let i = 1; i < shown.length; i++) minGap = Math.min(minGap, py(shown[i - 1]) - py(shown[i]));
282- for (const f of minGap >= MIN_REF_GAP ? shown : []) {
342+ // Each reference line only where it is far enough from its neighbours to
343+ // read as a separate line (crowded together, their dashes merge into a
344+ // solid on-off bar that looks like signal).
345+ const fLow = this.log ? this.fmin() : 0;
346+ const ys = this.refFreqs.filter((f) => f > fLow && f < this.fmax).map(py).sort((a, b) => a - b);
347+ const apart = (i: number) =>
348+ (i === 0 || ys[i] - ys[i - 1] >= MIN_REF_GAP) && (i === ys.length - 1 || ys[i + 1] - ys[i] >= MIN_REF_GAP);
349+ for (const y of ys.filter((_, i) => apart(i))) {
283350 ctx.beginPath();
284- ctx.moveTo(0, py(f));
285- ctx.lineTo(this.width, py(f));
351+ ctx.moveTo(0, y);
352+ ctx.lineTo(this.width, y);
286353 ctx.stroke();
287354 }
288355 ctx.setLineDash([]);
289356 ctx.font = "12px ui-monospace, monospace";
290357 if (cols.length > 0) label(ctx, `${this.fmax} Hz`, 2, 2);
291- label(ctx, "0", 2, HEIGHT - 18);
358+ label(ctx, this.log ? `${this.fmin()} Hz` : "0", 2, HEIGHT - 18);
292359 const end = `${this.span.toFixed(1)} s`;
293360 label(ctx, end, this.width - ctx.measureText(end).width - 8, HEIGHT - 18);
294361 const ct = this.cursor?.t ?? null;
src/double-pendulum/README.mdmodified+1−1View file
@@ -2,7 +2,7 @@
22
33 Interactive double pendulum, step 1 of "Listening for chaos". Work in progress.
44
5-Current state: the pendulum hangs at rest until Strike, which starts it from hanging rest with the energy on the slider (default 50 J), plus a random relative jitter of up to 1e-9 in each angle and momentum (so chaotic strikes differ from one another while regular ones sound alike); Pause (or the space bar) pauses everything: the animation and the sound (the audio clock is suspended, so the note and every display fed by it stop where they are); Resume or Strike continues. The Ghost toggle (controls in `../common/ghost.ts`) adds a second pendulum (translucent orange) started from the same state with the outer arm's angle offset by 10^-12 to 10^-1 rad (default 10^-10), restarted on Strike or "Restart ghost", with a readout of the angular separation and the time since the ghost started: it grows exponentially when the motion is chaotic and stays tiny when it is regular. Charts "Separation" (ghost separation, log scale, last 30 s; its chip shows only with the ghost on) and "Lyapunov" (largest Lyapunov exponent over a 10 s window and since the strike, last 30 s; the first 5 s after a strike, where the values are large, are left out of the y range, here and in the sound's Lyapunov chart). Chart legends show 4 significant digits, ranges 3. Parameters (masses, lengths, g, decay time, presets) fold out underneath. The plots card is labelled "Real time" and the "Sped up · listen" panel's header says how much faster its run is (e.g. the whole decay, 262x faster: 62 min of motion in 14 s), since the two run on different clocks; the Follow options read "real time" and "sped up". Toggle chips choose the plots: live traces of energies, energy balance error, angles, momenta and bob positions. Each chart shows its time span at the bottom right ("last 10 s" when scrolling; the note length in the sound panel). The Poincare section panel (closed by default) has its own energy slider (log scale, from E_top / 1000 to 2 E_top, 59 mJ to 117.7 J at the defaults, where E_top is the both-inverted energy; default 17 J; on new parameters it keeps its position) and uses the same masses and lengths, without damping: each time the inner arm swings down through vertical moving right, the outer arm's angle and momentum are plotted. 42 orbits start on a grid inside the allowed region (outlined) and leave 300 dots each, computed in a Web Worker and drawn as they arrive; regular orbits trace closed curves, chaotic ones scatter. Hover to pick out an orbit (with its Lyapunov exponent), click inside the outline to start a new orbit there (with "Click to strike" on, the default, this also strikes the pendulum above from that exact state, at the section's energy, without jitter). The animated pendulum's own crossings are drawn as dark rings (the latest larger), so you can see which orbit it is on; only those within 5% of the section's energy are drawn (others would fall outside the allowed region; the legend then says "pendulum at 48 J, not shown"), and they clear on each strike. Follow stays selected; setting the section's energy by hand pauses everything, clears the recent crossings (rings and note trail) and shows the section at that energy, and Follow takes over again on resume. Follow: "real time" makes the section's energy track the pendulum's as it decays (recomputed after a 3% change, at most every 2 s); "sped up" (which opens the "Sped up · listen" panel) shows the playing note's crossings (sent by the audio worker with the samples, drawn as the audio clock reaches them) as a fading trail of the last 150, with the axes fitted to the note's current energy (zooming as it decays) and nothing computed live. Without an atlas only the outline is drawn behind the trail; with one, the atlas section nearest the current energy, fitted to the current allowed region (each point scaled by the ratio of the regions' extents in th2 and p2: exact at low energy, where sections are scaled copies, an approximation over the <~15% gaps between atlas energies). Trail dots are fitted the same way from their own energies. "Precompute sections" (shown only with Follow "sped up", until the atlas is complete) builds the atlas (`../common/atlas.ts`, configured in `atlas.ts`): sections at 24 energies log-spaced from 0.4% of to twice the both-inverted energy, 42 orbits x 150 crossings each, highest energy first, in its own worker (~80 s in the desktop app's browser pane), stored in IndexedDB per parameter set and deleted after 7 days. "Color by λ" colors orbits by Lyapunov exponent (log scale, blue regular to red chaotic). The "Sped up · listen" panel (above the section) starts closed; opening it switches the sound engine on (closing it switches it off) without playing anything; a line of text says to Strike (or click the section) until the first note. While it is open, every Strike plays a note: a separate, sped-up copy of the motion from the same strike; a damped note ends once it has decayed by 60 dB. Save WAV saves the current or last note as heard (as received from the audio worker, up to 120 s; 16-bit mono PCM, peak at 0.9; `../common/wav.ts`; named e.g. double-pendulum-50.0J-x2-100Hz.wav). The mute button (speaker icon; when muted it is tinted red and reads "Muted") starts muted and unmutes the first time the panel is opened; muted notes are still computed and shown, just silent. The panel also has "Signal" (which coordinate is heard), volume, pitch (where the small-amplitude lower mode lands, 30 to 1000 Hz, default 100 Hz; the readout gives both modes' pitches), and optional whole-note displays that do not scroll (strike at the left edge, end of the note at the right): a spectrogram of the sound (frequency axis up to just above the highest frequency that comes within 40 dB of the peak at any time in the note, so the broadband start of a chaotic note stays in view), the largest Lyapunov exponent of the motion being heard (10 s window, physical time), its energy (log scale, so the exponential decay is a straight line), and a scatter of lambda against energy accumulated over notes (log energy axis, since a note spends most of its time at low energy; colored by time into the note, earlier notes faded, Clear button). Spectrogram on by default. Each card and panel (and Parameters) has a small "?" button that opens a short help dialog (`../common/help.ts`; the texts are `<template>`s in `index.html`). Hovering over any chart (real time or sped up) shows a time cursor and the values there; a click pins it. Charts in the same card share the cursor. The time axis spans the predicted note length ((tau/2) ln 1e6 of physical time, divided by the speedup), is extended if the note runs longer, and is fitted to the note when it ends.
5+Current state: the pendulum hangs at rest until Strike, which starts it from hanging rest with the energy on the slider (default 50 J), plus a random relative jitter of up to 1e-9 in each angle and momentum (so chaotic strikes differ from one another while regular ones sound alike); Pause (or the space bar) pauses everything: the animation and the sound (the audio clock is suspended, so the note and every display fed by it stop where they are); Resume or Strike continues. The Ghost toggle (controls in `../common/ghost.ts`) adds a second pendulum (translucent orange) started from the same state with the outer arm's angle offset by 10^-12 to 10^-1 rad (default 10^-10), restarted on Strike or "Restart ghost", with a readout of the angular separation and the time since the ghost started: it grows exponentially when the motion is chaotic and stays tiny when it is regular. Charts "Separation" (ghost separation, log scale, last 30 s; its chip shows only with the ghost on) and "Lyapunov" (largest Lyapunov exponent over a 10 s window and since the strike, last 30 s; the first 5 s after a strike, where the values are large, are left out of the y range, here and in the sound's Lyapunov chart). Chart legends show 4 significant digits, ranges 3. Parameters (masses, lengths, g, decay time, presets) fold out underneath. The plots card is labelled "Real time" and the "Sped up · listen" panel's header says how much faster its run is (e.g. the whole decay, 262x faster: 62 min of motion in 14 s), since the two run on different clocks; the Follow options read "real time" and "sped up". Toggle chips choose the plots: live traces of energies, energy balance error, angles, momenta and bob positions. Each chart shows its time span at the bottom right ("last 10 s" when scrolling; the note length in the sound panel). The Poincare section panel (closed by default) has its own energy slider (log scale, from E_top / 1000 to 2 E_top, 59 mJ to 117.7 J at the defaults, where E_top is the both-inverted energy; default 17 J; on new parameters it keeps its position) and uses the same masses and lengths, without damping: each time the inner arm swings down through vertical moving right, the outer arm's angle and momentum are plotted. 42 orbits start on a grid inside the allowed region (outlined) and leave 300 dots each, computed in a Web Worker and drawn as they arrive; regular orbits trace closed curves, chaotic ones scatter. Hover to pick out an orbit (with its Lyapunov exponent), click inside the outline to start a new orbit there (with "Click to strike" on, the default, this also strikes the pendulum above from that exact state, at the section's energy, without jitter). The animated pendulum's own crossings are drawn as dark rings (the latest larger), so you can see which orbit it is on; only those within 5% of the section's energy are drawn (others would fall outside the allowed region; the legend then says "pendulum at 48 J, not shown"), and they clear on each strike. Follow stays selected; setting the section's energy by hand pauses everything, clears the recent crossings (rings and note trail) and shows the section at that energy, and Follow takes over again on resume. Follow: "real time" makes the section's energy track the pendulum's as it decays (recomputed after a 3% change, at most every 2 s); "sped up" (which opens the "Sped up · listen" panel) shows the playing note's crossings (sent by the audio worker with the samples, drawn as the audio clock reaches them) as a fading trail of the last 150, with the axes fitted to the note's current energy (zooming as it decays) and nothing computed live. Without an atlas only the outline is drawn behind the trail; with one, the atlas section nearest the current energy, fitted to the current allowed region (each point scaled by the ratio of the regions' extents in th2 and p2: exact at low energy, where sections are scaled copies, an approximation over the <~15% gaps between atlas energies). Trail dots are fitted the same way from their own energies. "Precompute sections" (shown only with Follow "sped up", until the atlas is complete) builds the atlas (`../common/atlas.ts`, configured in `atlas.ts`): sections at 24 energies log-spaced from 0.4% of to twice the both-inverted energy, 42 orbits x 150 crossings each, highest energy first, in its own worker (~80 s in the desktop app's browser pane), stored in IndexedDB per parameter set and deleted after 7 days. "Color by λ" colors orbits by Lyapunov exponent (log scale, blue regular to red chaotic). The "Sped up · listen" panel (above the section) starts closed; opening it switches the sound engine on (closing it switches it off) without playing anything; a line of text says to Strike (or click the section) until the first note. While it is open, every Strike plays a note: a separate, sped-up copy of the motion from the same strike; a damped note ends once it has decayed by 60 dB. Save WAV saves the current or last note as heard (as received from the audio worker, up to 120 s; 16-bit mono PCM, peak at 0.9; `../common/wav.ts`; named e.g. double-pendulum-50.0J-x2-100Hz.wav). The mute button (speaker icon; when muted it is tinted red and reads "Muted") starts muted and unmutes the first time the panel is opened; muted notes are still computed and shown, just silent. The panel also has "Signal" (which coordinate is heard), volume, pitch (where the small-amplitude lower mode lands, 30 to 1000 Hz, default 100 Hz; the readout gives both modes' pitches), and optional whole-note displays that do not scroll (strike at the left edge, end of the note at the right): a spectrogram of the sound (frequency axis up to just above the highest frequency that comes within 40 dB of the peak at any time in the note, so the broadband start of a chaotic note stays in view; frequency axis logarithmic by default, from a round number at or below half the lowest mode pitch, with a "log f" chip to switch to linear from 0; each pixel row shows the loudest FFT bin in its band), the largest Lyapunov exponent of the motion being heard (10 s window, physical time), its energy (log scale, so the exponential decay is a straight line), and a scatter of lambda against energy accumulated over notes (log energy axis, since a note spends most of its time at low energy; colored by time into the note, earlier notes faded, Clear button). Spectrogram on by default. Each card and panel (and Parameters) has a small "?" button that opens a short help dialog (`../common/help.ts`; the texts are `<template>`s in `index.html`). Hovering over any chart (real time or sped up) shows a time cursor and the values there; a click pins it. Charts in the same card share the cursor. The time axis spans the predicted note length ((tau/2) ln 1e6 of physical time, divided by the speedup), is extended if the note runs longer, and is fitted to the note when it ends.
66
77 Live site: https://chaos-apps--listening-for-chaos.vault1-sites.magland.org/double-pendulum/ (part of the chaos-apps site; see the top-level README).
88
src/double-pendulum/index.htmlmodified+1−0View file
@@ -75,6 +75,7 @@
7575 <label><span class="label">Volume</span> <input id="volume" type="range" min="0" max="1" step="0.01" value="0.5" /></label>
7676 <span id="audio-chips" class="chips">
7777 <label class="chip"><input id="audio-spec-toggle" type="checkbox" checked /><span>Spectrogram</span></label>
78+ <label class="chip" title="Logarithmic frequency axis (off: linear from 0)"><input id="audio-spec-log" type="checkbox" checked /><span>log f</span></label>
7879 </span>
7980 </div>
8081 <div class="row">
src/double-pendulum/main.tsmodified+3−1View file
@@ -210,9 +210,11 @@ showPitch();
210210 // the audio device's sample rate differs.
211211 // One time cursor for the sound card's charts (hover / click to pin).
212212 const soundCursor = newCursor();
213+const audioSpecLog = document.getElementById("audio-spec-log") as HTMLInputElement; // log frequency axis
214+audioSpecLog.addEventListener("change", () => audioSpec.setLog(audioSpecLog.checked));
213215 const makeAudioSpec = (rate: number) => {
214216 const s = new NoteSpectrogram(
215- { dt: 1 / rate, n: 2048, nfft: 4096, hop: 512, refFreqs: audioModeHz(), width: 960 },
217+ { dt: 1 / rate, n: 2048, nfft: 4096, hop: 512, refFreqs: audioModeHz(), width: 960, log: audioSpecLog.checked },
216218 soundCursor,
217219 );
218220 document.getElementById("audio-spectrogram")!.replaceChildren(s.canvas);
src/fput-chain/README.mdmodified+1−1View file
@@ -4,7 +4,7 @@ Struck FPUT-beta chain, step 2 of "Listening for chaos" (after double-pendulum-c
44
55 Current state: N masses (2 to 64, default 2) between two fixed walls, joined by springs with tension k d + k3 d^3. The chain sits at rest until Strike, which gives it energy E (log slider, 10 µJ to 100 J, default 2.51 J) as velocity, either on one mass j alone (default mass 1, a hammer blow at one end) or in the shape of one normal mode n. The left card animates the chain (top: to scale, rest spacing a; below: the same displacements drawn sideways as a profile, scaled to fit, with the scale given) with the time and the relative energy error. Speed: 0.1x to 20x real time (default 1x). The time and current energy show at the top left. The Ghost chip (as in the pendulum app; controls in `../common/ghost.ts`) adds a second chain started from the same state with every mass moved by the same amount, 10^k / sqrt(N) m (total offset 10^k m, k = -12 to -1, default -10; moving only the struck mass would put the offset along the motion itself, which does not grow), run in lockstep without renormalization and drawn in translucent orange underneath; restarted on Strike, on "Restart ghost" (from the chain's current state), when switched on or when the offset changes; a readout gives the separation (root sum of squared displacement differences, m) and the time since the ghost started, and a "Separation" chart (log, last 60 s; offered only with the ghost on) plots it. A "Lyapunov" chart (last 60 s; the first 5 s after a strike left out of its y range) shows the largest Lyapunov exponent over the last 10 s and since the strike (`../common/lyapunov.ts`, two-trajectory Benettin method shared with the pendulum app, with the chain's shadow in `lyapunov.ts`: a hidden shadow chain 1e-8 away, displacements in units of d0 and momenta in units of sqrt(m k) d0, renormalized every step). Checked (N = 4, mass-1 strike, 300 s): without damping 0.1 J ~0.05 to 0.1 /s (weak chaos; N = 4 onset is near 3 k d0^2 = 75 mJ), 0.5 J ~0.5 /s, 2.51 J ~0.9 /s, 25 J ~1.7 /s; with tau 540 s, 0.1 J falls to ~0.01 /s and 2.51 J falls from ~1.0 to ~0.3 /s by 300 s. The slider is labelled "Strike energy". Parameters (m, k, k3, a, tau) fold out underneath with derived values (mode frequencies, d0, nonlinear energy scale, integrator step); Apply or changing N returns the chain to rest. The "Real time" card on the right has toggle chips for its charts. "Mode history" (off by default) is a scrolling heat map of each mode's share of the harmonic energy, log10(E_n / sum E) over 6 decades (inferno colors, mode 1 at the bottom), over the last 300 s (`LiveModeHistory` in `../common/modehistory.ts`); the cascade of energy up the modes shows here (e.g. N = 32, mode-1 strike at 10 mJ: the top mode's share goes from ~1e-28 to ~1e-12 in 10 periods of mode 1 and ~3e-5 in 50 without damping; with tau 540 s the damping wins and the spread stalls near mode 17). "Mode bars" (`../common/modebars.ts`) shows the current harmonic energy of each normal mode relative to E on a log scale (12 decades), with the number of modes sharing the energy (inverse participation, 1 / sum (E_n / sum E)^2). The other chips are charts over time (from `../common/traces.ts` and `../common/cursor.ts`, with per-group colors and a legend capped at 8 series): displacements, velocities, spring stretches, mode energies (log, last 60 s; values below 1e-12 of E left out), energies (E, T, V, W dissipated) and the energy balance error ((E + W - E0) / E0); others last 10 s; sampled every 10 ms; hover for values, click to pin. Mode bars, displacements and mode energies are on by default. Masses, springs and modes share one color per index (four fixed colors for up to 4, a blue-to-red sweep beyond).
66
7-"Sped up · listen" (open by default, below the cards; otherwise as in the pendulum app): the header says how much faster it runs ("the whole decay, 321× faster: 62 min of motion in 12 s"; without damping "321× faster than the chain above"). The page starts muted (the mute button is tinted red and reads "Muted"; muted notes are still computed and shown); the audio context is created at the first Strike; closing the panel stops the note. While it is open each Strike plays a note, the same strike rendered in a Web Worker (`render-worker.ts`, on the loop shared with the beam app in `../common/note-render.ts`) sped up so the lowest linear mode sounds at the Pitch (5 to 1000 Hz, default 100; below ~20 Hz the lowest modes are below hearing but show in the spectrogram; the readout gives the lowest and highest mode pitches). A damped note is the whole decay, ending when its energy has fallen to 1e-6 of the strike's (-60 dB; predicted length (tau/2) ln 1e6 of physical time, 11.6 s of sound by default, measured 11.3 s; capped at twice that); undamped notes last 10 s. "Strike to hear the whole decay." shows until the first note; the status line gives the signal and note length ("computing…" while rendering). Replay plays the last strike again with the current settings (to compare signals). Signal (`signals.ts`): velocity (default), displacement or acceleration of mass j (default 1, the end mass, which is never at a node), force on the left wall (the first spring's tension), or sum of accelerations (the net wall force, in which even modes cancel). In one mass's motion mode n is weighted by sqrt(E_n) / omega_n, sqrt(E_n) or sqrt(E_n) omega_n. Each note is made zero-mean, scaled to a 0.9 peak (all signals equally loud; Volume sets the level) and faded out over its last 20 ms (`../common/sound.ts`). Save WAV saves the last note as heard (16-bit mono PCM, peak at 0.9; `../common/wav.ts`; named e.g. fput-N4-mass1-2.51J-v1-100Hz.wav). Chips (as in the pendulum app, plus Modes): Spectrogram (on; `NoteSpectrogram` in `../common/spectrogram.ts`: 2048-sample Hann, zero-pad 4096, hop 512, for pitches down to 30 Hz; below, the window lengthens in proportion (up to 16384 samples at 5 Hz, zero-pad 2x, hop a quarter window) so neighbouring low modes stay resolved; dashed lines at the linear mode pitches, drawn only while at least 6 px apart, since crowded together their dashes merged into a solid on-off bar at the bottom), Modes (off by default; the note's mode-energy history, each mode's share of the energy over the whole note, from the render worker, one column per 256 samples; `ModeHistory` in `../common/modehistory.ts`; a cascade that takes tens of mode-1 periods occupies only the first few percent of a whole-decay note, so Mode history in the Real time panel shows it better), Lyapunov (the note's largest Lyapunov exponent over the last 10 s of physical time, from a shadow run in the worker alongside the note; the first 5 s of physical time left out of the y range), Energy (log scale, so the decay is a straight line) and λ vs E (`../common/scatter.ts`: one point per 256 samples, accumulated over notes, log energy axis, colored by time into the note on a log scale, earlier notes faded, hover for values, Clear button). The first three span the whole note (strike at left, end at right) and fill in as the audio clock reaches each sample; one shared cursor (playhead while playing; hover for values, click to pin). Pause (or space) pauses the animation and the sound (audio context suspended). The note's Lyapunov shadow runs only while the Lyapunov chart or λ vs E is shown (it doubles the computation). Render time in the browser pane (with the Lyapunov shadow): ~0.6 s for N = 4, ~2 s for N = 32 (default strike). First look (N = 4, 2.51 J): λ ~1.3 /s at the strike, falling to ~0 by ~4 s of sound as the spectrogram resolves into lines; on λ vs E the note's points sit near 0 below ~0.1 J and rise to ~1.4 /s at the top.
7+"Sped up · listen" (open by default, below the cards; otherwise as in the pendulum app): the header says how much faster it runs ("the whole decay, 321× faster: 62 min of motion in 12 s"; without damping "321× faster than the chain above"). The page starts muted (the mute button is tinted red and reads "Muted"; muted notes are still computed and shown); the audio context is created at the first Strike; closing the panel stops the note. While it is open each Strike plays a note, the same strike rendered in a Web Worker (`render-worker.ts`, on the loop shared with the beam app in `../common/note-render.ts`) sped up so the lowest linear mode sounds at the Pitch (5 to 1000 Hz, default 100; below ~20 Hz the lowest modes are below hearing but show in the spectrogram; the readout gives the lowest and highest mode pitches). A damped note is the whole decay, ending when its energy has fallen to 1e-6 of the strike's (-60 dB; predicted length (tau/2) ln 1e6 of physical time, 11.6 s of sound by default, measured 11.3 s; capped at twice that); undamped notes last 10 s. "Strike to hear the whole decay." shows until the first note; the status line gives the signal and note length ("computing…" while rendering). Replay plays the last strike again with the current settings (to compare signals). Signal (`signals.ts`): velocity (default), displacement or acceleration of mass j (default 1, the end mass, which is never at a node), force on the left wall (the first spring's tension), or sum of accelerations (the net wall force, in which even modes cancel). In one mass's motion mode n is weighted by sqrt(E_n) / omega_n, sqrt(E_n) or sqrt(E_n) omega_n. Each note is made zero-mean, scaled to a 0.9 peak (all signals equally loud; Volume sets the level) and faded out over its last 20 ms (`../common/sound.ts`). Save WAV saves the last note as heard (16-bit mono PCM, peak at 0.9; `../common/wav.ts`; named e.g. fput-N4-mass1-2.51J-v1-100Hz.wav). Chips (as in the pendulum app, plus Modes): Spectrogram (on; `NoteSpectrogram` in `../common/spectrogram.ts`: 2048-sample Hann, zero-pad 4096, hop 512, for pitches down to 30 Hz; below, the window lengthens in proportion (up to 16384 samples at 5 Hz, zero-pad 2x, hop a quarter window) so neighbouring low modes stay resolved; dashed lines at the linear mode pitches, each drawn only while at least 6 px from its neighbours, since crowded together their dashes merged into a solid on-off bar; frequency axis logarithmic by default, from a round number at or below half the lowest mode pitch, with a "log f" chip to switch to linear from 0; each pixel row shows the loudest FFT bin in its band), Modes (off by default; the note's mode-energy history, each mode's share of the energy over the whole note, from the render worker, one column per 256 samples; `ModeHistory` in `../common/modehistory.ts`; a cascade that takes tens of mode-1 periods occupies only the first few percent of a whole-decay note, so Mode history in the Real time panel shows it better), Lyapunov (the note's largest Lyapunov exponent over the last 10 s of physical time, from a shadow run in the worker alongside the note; the first 5 s of physical time left out of the y range), Energy (log scale, so the decay is a straight line) and λ vs E (`../common/scatter.ts`: one point per 256 samples, accumulated over notes, log energy axis, colored by time into the note on a log scale, earlier notes faded, hover for values, Clear button). The first three span the whole note (strike at left, end at right) and fill in as the audio clock reaches each sample; one shared cursor (playhead while playing; hover for values, click to pin). Pause (or space) pauses the animation and the sound (audio context suspended). The note's Lyapunov shadow runs only while the Lyapunov chart or λ vs E is shown (it doubles the computation). Render time in the browser pane (with the Lyapunov shadow): ~0.6 s for N = 4, ~2 s for N = 32 (default strike). First look (N = 4, 2.51 J): λ ~1.3 /s at the strike, falling to ~0 by ~4 s of sound as the spectrogram resolves into lines; on λ vs E the note's points sit near 0 below ~0.1 J and rise to ~1.4 /s at the top.
88
99 Poincaré section (shown only for N = 2 and N = 3, below the sped-up panel, open; adapted from the pendulum app): its own energy slider (log, 10 µJ to 100 J, default 2.51 J), same parameters, no damping. N = 2: each time mass 1 passes its rest position moving right, mass 2's (u2, p2) is plotted. N = 3: only the symmetric family (u1 = u3, p1 = p3; only modes 1 and 3 move, since the cubic force couples odd modes only to odd modes), which is two-dimensional: each time mass 2 passes its rest position moving right, mass 1's (u1, p1) is plotted. On either section the springs are stretched by 0 or +-x, so V = vFactor (k x^2 / 2 + k3 x^4 / 4) (vFactor 2 or 4), the plotted momentum counts once (N = 2) or twice (N = 3) in the kinetic energy, the outline is where the crossing mass's momentum vanishes, and that momentum follows from E. 42 orbits seeded on a grid, 300 crossings each, in a worker (`poincare-core.ts`, the chain's section, on `../common/section.ts` and `../common/section-worker.ts`; `poincare.ts`, the panel's configuration for `../common/section-panel.ts`; integrator step stepFor(E), energy error < 5e-5; ~1 s per section offline, a few s in the pane), drawn as they arrive; per-orbit colors or Color by λ (each orbit's Lyapunov exponent over its run, log scale); hover to pick out an orbit with its λ; click inside the outline to add an orbit there, and with Click to strike (on) also strike the chain from that exact state (and play it, if the sound panel is open). Follow (as in the pendulum app): "real time" makes the section's energy track the chain's as it decays (recomputed after a 3% change, at most every 2 s, and at each strike); "sped up" (which opens the sped-up panel) shows the playing note's crossings (found in the render worker, for N = 3 only while exactly symmetric, and drawn as the audio clock reaches them) as a fading trail of the last 150, with the axes fitted to the note's current energy (refit every 2%) and each dot fitted from its own energy; nothing is computed live. "Precompute sections" (shown only with Follow "sped up" until complete) builds an atlas (`../common/atlas.ts`, configured in `atlas.ts`): sections at 32 energies log-spaced from 1 mJ to 100 J (a factor ~1.45 apart), 42 orbits x 150 crossings, highest first, in its own worker (~22 s in the pane for N = 3), stored in IndexedDB per N, m, k, k3 and deleted after 7 days; the sound view shows the atlas section nearest the current energy, fitted to its allowed region (exact in the linear regime, below ~25 mJ, where sections are scaled copies; an approximation across the gaps above). Without an atlas only the outline is drawn behind the trail. Setting the section's energy by hand pauses everything and clears the rings and the trail; Follow takes over again on Resume. The chain's own crossings show as dark rings when within 5% of the section's energy and, for N = 3, only while the chain is exactly symmetric (else the legend says "chain not symmetric, not shown"; strikes on mass 2 or on mode 1 or 3 are symmetric, mode shapes are made exactly mirror-symmetric for this). Findings: the two-mass chain appears regular at every energy tried (10 mJ to 100 J): nested closed curves and island chains, no chaotic sea; the grid orbits' λ falls as the run lengthens (at 10 J, median 0.045 /s over 300 crossings, 0.007 /s over 3000), as for regular orbits. A likely reason: in mode coordinates (u = S Q) the potential is (k/2) rho^2 + (k3/8) rho^4 with rho^2 = Q1^2 + 3 Q2^2, a function of one combination of the two modes. The N = 3 symmetric family is chaotic: grid orbits with λ > 0.1 /s: 0 of 42 at 25 mJ, 10 at 0.25 J (islands in a chaotic sea), 37 at 2.51 J. It is unstable to breaking the symmetry: an exactly symmetric start stays symmetric (the arithmetic is exactly mirror-symmetric), but an asymmetry of 1e-12 grows to full size within ~100 s at 0.25 to 25 J. The ghost and the Lyapunov shadow offset all masses equally, so after a symmetric strike they too stay symmetric and measure the exponent within the family.
1010
src/fput-chain/index.htmlmodified+1−0View file
@@ -95,6 +95,7 @@
9595 <button id="save-wav" type="button" disabled title="Save the last note as a WAV file">Save WAV</button>
9696 <span id="sound-chips" class="chips">
9797 <label class="chip"><input id="spec-toggle" type="checkbox" checked /><span>Spectrogram</span></label>
98+ <label class="chip" title="Logarithmic frequency axis (off: linear from 0)"><input id="spec-log" type="checkbox" checked /><span>log f</span></label>
9899 <label class="chip" title="Each mode's share of the energy over the note"><input id="modes-toggle" type="checkbox" /><span>Modes</span></label>
99100 </span>
100101 </div>
src/fput-chain/main.tsmodified+3−1View file
@@ -325,6 +325,8 @@ const soundCursor = newCursor();
325325 let spec: NoteSpectrogram | null = null;
326326 const specToggle = document.getElementById("spec-toggle") as HTMLInputElement;
327327 specToggle.addEventListener("change", () => (specFig.hidden = !specToggle.checked));
328+const specLog = document.getElementById("spec-log") as HTMLInputElement; // log frequency axis
329+specLog.addEventListener("change", () => spec?.setLog(specLog.checked));
328330 let noteEnergy = NaN, noteLambda = NaN;
329331 const soundTraces = new TracePanel(
330332 document.getElementById("sound-chips")!,
@@ -444,7 +446,7 @@ worker.onmessage = (e: MessageEvent<RenderResult>) => {
444446 // 16384 samples at 5 Hz).
445447 const n = Math.min(16384, 2 ** Math.ceil(Math.log2((2048 * 30) / Math.min(30, pitch()))));
446448 spec = new NoteSpectrogram(
447- { dt: 1 / rate, n, nfft: 2 * n, hop: n / 4, refFreqs: modePitches(), width: 960 },
449+ { dt: 1 / rate, n, nfft: 2 * n, hop: n / 4, refFreqs: modePitches(), width: 960, log: specLog.checked },
448450 soundCursor,
449451 );
450452 spec.start(span);
↑↓ move↵openescclose