/ listening-for-chaos / chaos-apps
Sign in
listening-for-chaos / chaos-apps
Move the identical files (help, cursor, wav, scatter) to src/common/
Jeremy Magland <jmagland@flatironinstitute.org> committed commit 5ae1944901cd parent d1459b9 Browse files
18 changed files+20−314
README.mdmodified+1−0View file
@@ -4,6 +4,7 @@ Interactive apps for "Listening for chaos": struck dynamical systems heard as so
44
55 - `src/double-pendulum/`: double pendulum ([README](src/double-pendulum/README.md)), served at `/double-pendulum/`.
66 - `src/fput-chain/`: FPUT-beta chain ([README](src/fput-chain/README.md)), served at `/fput-chain/`.
7+- `src/common/`: code shared by the apps (help dialogs, chart cursor, WAV export, λ vs E scatter).
78 - `src/index.html`: landing page linking the apps.
89
910 Live site: https://chaos-apps--listening-for-chaos.vault1-sites.magland.org/ (built and deployed by `.github/workflows/pages.yml` on every push to main).
src/double-pendulum/cursor.ts →src/common/cursor.tsrenamed+0−0View file
No changes to the file's content.
src/double-pendulum/help.ts →src/common/help.tsrenamed+0−0View file
No changes to the file's content.
src/double-pendulum/scatter.ts →src/common/scatter.tsrenamed+0−0View file
No changes to the file's content.
src/double-pendulum/wav.ts →src/common/wav.tsrenamed+0−0View file
No changes to the file's content.
src/double-pendulum/README.mdmodified+2−2View 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 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 (default 17 J) 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 (`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; `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 (`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 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 (default 17 J) 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 (`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.
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
@@ -20,4 +20,4 @@ Live site: https://chaos-apps--listening-for-chaos.vault1-sites.magland.org/doub
2020
2121 Audio: a Web Worker (`audio-worker.ts`) integrates the audio copy with substeps of at most 3.2 ms of simulated time per sample, high-passes at 20 Hz, and streams 1024-sample chunks through a MessageChannel to an AudioWorklet (`audio-worklet.ts`) that plays them from a ring buffer, keeping about 0.25 s queued. The page shows how many times faster than real time the worker computes, and any dropouts. The worker also sends each chunk to the page, which feeds it to the audio spectrogram as the audio clock reaches it (2048-sample window, new column every 512 samples). The worker runs the same Lyapunov shadow on the note and sends one exponent and one energy value per 256 samples with each chunk; the page plots them in step with the spectrogram. The whole-note spectrogram keeps every column (pairs are averaged past 4096 columns) and draws only new pixel columns unless the axis or color scale changes.
2222
23-Code: `pendulum.ts` (physics), `sim.ts` (running simulation with energy target), `audio.ts` (audio setup), `signals.ts` (audible quantities), `lyapunov.ts` (Lyapunov exponent), `scatter.ts` (lambda vs energy), `cursor.ts` (shared hover/pin cursor), `poincare-core.ts`, `poincare-worker.ts`, `poincare.ts` (Poincare section), `atlas.ts` (cached sections for following the sound), `audio-shared.ts` (constants shared with the worker), `traces.ts` (strip charts), `spectrogram.ts` (whole-note spectrogram), `main.ts` (page).
23+Code: `pendulum.ts` (physics), `sim.ts` (running simulation with energy target), `audio.ts` (audio setup), `signals.ts` (audible quantities), `lyapunov.ts` (Lyapunov exponent), `../common/scatter.ts` (lambda vs energy), `../common/cursor.ts` (shared hover/pin cursor), `poincare-core.ts`, `poincare-worker.ts`, `poincare.ts` (Poincare section), `atlas.ts` (cached sections for following the sound), `audio-shared.ts` (constants shared with the worker), `traces.ts` (strip charts), `spectrogram.ts` (whole-note spectrogram), `main.ts` (page).
src/double-pendulum/main.tsmodified+4−4View file
@@ -1,10 +1,10 @@
11 import { AudioOut } from "./audio";
22 import { END_RATIO, LAMBDA_EVERY } from "./audio-shared";
3-import { newCursor } from "./cursor";
4-import { setupHelp } from "./help";
3+import { newCursor } from "../common/cursor";
4+import { setupHelp } from "../common/help";
55 import { PoincarePanel, formatEnergy } from "./poincare";
66 import { Lyapunov } from "./lyapunov";
7-import { ScatterPlot } from "./scatter";
7+import { ScatterPlot } from "../common/scatter";
88 import {
99 energy, kinetic, normalModes, potential, stepSize, topEnergy, type Params,
1010 } from "./pendulum";
@@ -12,7 +12,7 @@ import { SIGNALS, signalByKey } from "./signals";
1212 import { Sim } from "./sim";
1313 import { NoteSpectrogram } from "./spectrogram";
1414 import { TracePanel } from "./traces";
15-import { saveFile, wavBlob } from "./wav";
15+import { saveFile, wavBlob } from "../common/wav";
1616
1717 setupHelp();
1818
src/double-pendulum/spectrogram.tsmodified+1−1View file
@@ -5,7 +5,7 @@
55 // time (a time average would hide the broadband start of a chaotic note under
66 // its long, quiet, tonal tail).
77
8-import { attachCursor, type Cursor } from "./cursor";
8+import { attachCursor, type Cursor } from "../common/cursor";
99
1010 const HEIGHT = 200;
1111 const RANGE_DB = 60; // color range below the peak
src/double-pendulum/traces.tsmodified+1−1View file
@@ -9,7 +9,7 @@
99 // the panel's charts, and optionally with other charts) and the values there;
1010 // a click pins it.
1111
12-import { attachCursor, newCursor, type Cursor } from "./cursor";
12+import { attachCursor, newCursor, type Cursor } from "../common/cursor";
1313
1414 export interface Series {
1515 label: string;
src/fput-chain/README.mdmodified+4−4View file
@@ -2,13 +2,13 @@
22
33 Struck FPUT-beta chain, step 2 of "Listening for chaos" (after double-pendulum-chaos). Work in progress.
44
5-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) 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 (`lyapunov.ts`, two-trajectory Benettin method as in the pendulum app: 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 `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" 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 `traces.ts` and `cursor.ts` of double-pendulum-chaos, 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).
5+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) 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 (`lyapunov.ts`, two-trajectory Benettin method as in the pendulum app: 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 `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" 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 `traces.ts`, adapted from the pendulum app, 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`) 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 (`sound.ts`). Save WAV saves the last note as heard (16-bit mono PCM, peak at 0.9; `wav.ts`; named e.g. fput-N4-mass1-2.51J-v1-100Hz.wav). Chips (as in the pendulum app, plus Modes): Spectrogram (on; pendulum's `NoteSpectrogram`: 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 `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 (`scatter.ts` from the pendulum app: 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`) 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 (`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; pendulum's `NoteSpectrogram`: 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 `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`, `poincare-worker.ts`, `poincare.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 (`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
11-Each card and panel (chain, Parameters, Real time, Sped up · listen, Poincaré section) has a small "?" button that opens a short help dialog (`help.ts` from the pendulum app; the texts are `<template>`s in `index.html`).
11+Each card and panel (chain, Parameters, Real time, Sped up · listen, Poincaré section) has a small "?" button that opens a short help dialog (`../common/help.ts`; the texts are `<template>`s in `index.html`).
1212
1313 Live site: https://chaos-apps--listening-for-chaos.vault1-sites.magland.org/fput-chain/ (part of the chaos-apps site; see the top-level README).
1414
@@ -26,4 +26,4 @@ Live site: https://chaos-apps--listening-for-chaos.vault1-sites.magland.org/fput
2626 - Chaos for N = 4 (two-trajectory Lyapunov, 5000 / sqrt(k/m) s): none below E ~ 1 k d0^2; onset near 3 k d0^2; at the default 10 k d0^2, lambda ~0.1 sqrt(k/m) = 0.32 /s, energy shared by ~2.5 modes.
2727 - Symmetry: the quartic force couples odd modes only to odd modes, so a strike in an odd mode leaves the even modes at exactly zero (they stay off the bottom of the chart). A strike on one mass, other than the middle one, excites all modes.
2828
29-Code: `chain.ts` (physics, modes, strikes), `main.ts` (page), `traces.ts` and `cursor.ts` (charts), `signals.ts`, `render-worker.ts`, `sound.ts`, `spectrogram.ts`, `scatter.ts` (sound), `lyapunov.ts` (Lyapunov exponent, animation and sound), `poincare*.ts` (section, N = 2 and 3).
29+Code: `chain.ts` (physics, modes, strikes), `main.ts` (page), `traces.ts` and `../common/cursor.ts` (charts), `signals.ts`, `render-worker.ts`, `sound.ts`, `spectrogram.ts`, `../common/scatter.ts` (sound), `lyapunov.ts` (Lyapunov exponent, animation and sound), `poincare*.ts` (section, N = 2 and 3).
src/fput-chain/cursor.tsdeleted+0−30View file
@@ -1,30 +0,0 @@
1-// A time cursor shared by the charts of one card: hovering sets the time,
2-// a click pins it (another click releases it), leaving clears it unless
3-// pinned. Charts read it when they draw.
4-
5-export interface Cursor {
6- t: number | null; // time under the cursor (chart time units), or none
7- pinned: boolean;
8-}
9-
10-export const newCursor = (): Cursor => ({ t: null, pinned: false });
11-
12-// Wire mouse events on a canvas to a cursor; toTime maps an x position (0..1
13-// of the canvas width) to a time.
14-export function attachCursor(canvas: HTMLCanvasElement, cursor: Cursor, toTime: (frac: number) => number): void {
15- const at = (e: MouseEvent) => {
16- const r = canvas.getBoundingClientRect();
17- return toTime((e.clientX - r.left) / r.width);
18- };
19- canvas.style.cursor = "crosshair";
20- canvas.addEventListener("mousemove", (e) => {
21- if (!cursor.pinned) cursor.t = at(e);
22- });
23- canvas.addEventListener("mouseleave", () => {
24- if (!cursor.pinned) cursor.t = null;
25- });
26- canvas.addEventListener("click", (e) => {
27- cursor.pinned = !cursor.pinned;
28- cursor.t = at(e);
29- });
30-}
src/fput-chain/help.tsdeleted+0−21View file
@@ -1,21 +0,0 @@
1-// Help: each "?" button (data-help="name") opens one dialog showing the
2-// contents of <template id="help-name">. Esc, Close, or a click outside the
3-// dialog closes it. A "?" inside a <summary> does not fold its panel.
4-
5-export function setupHelp(): void {
6- const dialog = document.getElementById("help") as HTMLDialogElement;
7- const body = document.getElementById("help-body")!;
8- for (const button of document.querySelectorAll<HTMLButtonElement>("button.help")) {
9- button.addEventListener("click", (e) => {
10- e.preventDefault();
11- e.stopPropagation();
12- const t = document.getElementById(`help-${button.dataset.help}`) as HTMLTemplateElement;
13- body.replaceChildren(t.content.cloneNode(true));
14- dialog.showModal();
15- });
16- }
17- document.getElementById("help-close")!.addEventListener("click", () => dialog.close());
18- dialog.addEventListener("click", (e) => {
19- if (e.target === dialog) dialog.close(); // the backdrop
20- });
21-}
src/fput-chain/main.tsmodified+4−4View file
@@ -1,19 +1,19 @@
11 import {
22 Modes, Verlet, copyState, d0, energy, kinetic, newState, stepFor, potential, strikeMass, strikeMode, type Params, type State,
33 } from "./chain";
4-import { newCursor } from "./cursor";
5-import { setupHelp } from "./help";
4+import { newCursor } from "../common/cursor";
5+import { setupHelp } from "../common/help";
66 import { Lyapunov } from "./lyapunov";
77 import { LiveModeHistory, ModeHistory } from "./modehistory";
88 import { PoincarePanel } from "./poincare";
99 import { sectionDef } from "./poincare-core";
1010 import { END_RATIO, DIAG_EVERY, UNDAMPED_LENGTH, type RenderRequest, type RenderResult } from "./render-worker";
11-import { ScatterPlot } from "./scatter";
11+import { ScatterPlot } from "../common/scatter";
1212 import { SIGNALS, signalByKey } from "./signals";
1313 import { Player } from "./sound";
1414 import { NoteSpectrogram } from "./spectrogram";
1515 import { TracePanel, type Group } from "./traces";
16-import { saveFile, wavBlob } from "./wav";
16+import { saveFile, wavBlob } from "../common/wav";
1717
1818 setupHelp();
1919
src/fput-chain/modehistory.tsmodified+1−1View file
@@ -5,7 +5,7 @@
55 // decades, so the picture does not fade as the note decays. Columns arrive
66 // as the audio clock reaches them. An optional shared time cursor is drawn.
77
8-import { attachCursor, type Cursor } from "./cursor";
8+import { attachCursor, type Cursor } from "../common/cursor";
99 import { colormap } from "./spectrogram";
1010
1111 const HEIGHT = 160;
src/fput-chain/scatter.tsdeleted+0−206View file
@@ -1,206 +0,0 @@
1-// Scatter plot of the sound's Lyapunov exponent against its energy, one point
2-// per diagnostic sample, accumulated over notes. Points are colored by time
3-// into their note on a log scale (red just after the strike, then amber, blue
4-// late): the energy decays exponentially, so on a linear time scale nearly all
5-// of the high-energy part would share one color. For the same reason the
6-// energy axis is logarithmic. Earlier notes are faded. Hovering shows the
7-// nearest point's values in the legend row.
8-// Earlier notes are drawn once into a cached image (rebuilt when the axes
9-// change); each frame adds only the current note.
10-
11-const HEIGHT = 220; // CSS pixels
12-const TOP = 18; // legend row
13-const PAD = 6;
14-const MAX_POINTS = 200000;
15-const RAMP = [[194, 65, 45], [227, 162, 26], [47, 93, 138]]; // red -> amber -> blue
16-const LOG_T1 = 0.01; // log time scale: u = ln(1 + t/(LOG_T1 L)) / ln(1 + 1/LOG_T1), L = note length
17-const DOT = 3; // CSS pixels
18-const FONT = "11px ui-monospace, SFMono-Regular, Menlo, monospace";
19-const BINS = 16; // color steps along the note
20-
21-export class ScatterPlot {
22- canvas: HTMLCanvasElement;
23- private width: number;
24- private dpr = window.devicePixelRatio || 1;
25- private E = new Float32Array(MAX_POINTS);
26- private L = new Float32Array(MAX_POINTS);
27- private T = new Float32Array(MAX_POINTS); // s into the note
28- private note = new Int32Array(MAX_POINTS);
29- private n = 0;
30- private noteIndex = 0;
31- private noteStart = 0; // index of the current note's first point
32- private cache: HTMLCanvasElement;
33- private cacheKey = "";
34- private noteLength: number[] = []; // per note, for coloring (s)
35- private changed = true;
36- private hover: { x: number; y: number } | null = null;
37- // Current axes (data -> device pixels), set at draw.
38- private lgMin = -1; // log10 of the energy axis range
39- private lgMax = 0;
40- private lMin = -0.5;
41- private lMax = 2;
42-
43- constructor(width = 960) {
44- this.width = width;
45- this.canvas = document.createElement("canvas");
46- this.canvas.width = width * this.dpr;
47- this.canvas.height = HEIGHT * this.dpr;
48- this.canvas.style.cursor = "crosshair";
49- this.cache = document.createElement("canvas");
50- this.cache.width = this.canvas.width;
51- this.cache.height = this.canvas.height;
52- this.canvas.addEventListener("mousemove", (e) => {
53- const r = this.canvas.getBoundingClientRect();
54- this.hover = { x: ((e.clientX - r.left) / r.width) * this.width, y: ((e.clientY - r.top) / r.height) * HEIGHT };
55- this.changed = true;
56- });
57- this.canvas.addEventListener("mouseleave", () => {
58- this.hover = null;
59- this.changed = true;
60- });
61- }
62-
63- clear(): void {
64- this.n = 0;
65- this.noteStart = 0;
66- this.noteLength = [];
67- this.noteIndex = 0;
68- this.changed = true;
69- }
70-
71- // Start a new note expected to last about `length` seconds (for coloring).
72- newNote(length: number): void {
73- this.noteIndex = this.noteLength.length;
74- this.noteLength.push(length);
75- this.noteStart = this.n;
76- this.changed = true;
77- }
78-
79- // Final length of the current note.
80- setNoteLength(length: number): void {
81- if (this.noteLength.length) this.noteLength[this.noteIndex] = length;
82- this.changed = true;
83- }
84-
85- add(E: number, lambda: number, t: number): void {
86- if (!(E > 0) || !Number.isFinite(lambda) || this.n >= MAX_POINTS || !this.noteLength.length) return;
87- this.E[this.n] = E;
88- this.L[this.n] = lambda;
89- this.T[this.n] = t;
90- this.note[this.n] = this.noteIndex;
91- this.n++;
92- this.changed = true;
93- }
94-
95- private px(E: number): number {
96- return PAD + ((Math.log10(E) - this.lgMin) / (this.lgMax - this.lgMin)) * (this.width - 2 * PAD);
97- }
98-
99- private py(l: number): number {
100- return HEIGHT - PAD - ((l - this.lMin) / (this.lMax - this.lMin)) * (HEIGHT - TOP - 2 * PAD);
101- }
102-
103- // Points from..to, colored by time into their note, binned into BINS colors.
104- private drawPoints(ctx: CanvasRenderingContext2D, from: number, to: number, alpha: number): void {
105- const { E, L, T, note } = this;
106- const norm = Math.log(1 + 1 / LOG_T1);
107- const bin = (i: number) => {
108- const f = Math.min(1, T[i] / (this.noteLength[note[i]] || 1));
109- return Math.min(BINS - 1, Math.floor((Math.log(1 + f / LOG_T1) / norm) * BINS));
110- };
111- for (let b = 0; b < BINS; b++) {
112- const c = rampColor((b + 0.5) / BINS);
113- ctx.fillStyle = `rgba(${c[0]}, ${c[1]}, ${c[2]}, ${alpha})`;
114- for (let i = from; i < to; i++) {
115- if (bin(i) === b) ctx.fillRect(this.px(E[i]) - DOT / 2, this.py(L[i]) - DOT / 2, DOT, DOT);
116- }
117- }
118- }
119-
120- draw(): void {
121- if (!this.changed) return;
122- this.changed = false;
123- const { n, E, L, T, dpr } = this;
124- // Axes: energy (log) over the points, in whole decades; lambda including
125- // 0, padded.
126- let eMin = Infinity, eMax = 0, lMin = 0, lMax = 0;
127- for (let i = 0; i < n; i++) {
128- if (E[i] < eMin) eMin = E[i];
129- if (E[i] > eMax) eMax = E[i];
130- if (L[i] < lMin) lMin = L[i];
131- if (L[i] > lMax) lMax = L[i];
132- }
133- this.lgMin = n ? Math.floor(Math.log10(eMin)) : -1;
134- this.lgMax = n ? Math.ceil(Math.log10(eMax)) : 0;
135- if (this.lgMax <= this.lgMin) this.lgMax = this.lgMin + 1;
136- const span = lMax - lMin || 1;
137- this.lMin = lMin - 0.05 * span;
138- this.lMax = lMax + 0.05 * span;
139-
140- const ctx = this.canvas.getContext("2d")!;
141- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
142- ctx.clearRect(0, 0, this.width, HEIGHT);
143- // lambda = 0 line.
144- ctx.strokeStyle = "#ddd";
145- ctx.lineWidth = 1;
146- ctx.beginPath();
147- ctx.moveTo(0, this.py(0));
148- ctx.lineTo(this.width, this.py(0));
149- ctx.stroke();
150-
151- // Earlier notes (faded) from the cache, then the current note.
152- const key = `${this.lgMin}|${this.lgMax}|${this.lMin}|${this.lMax}|${this.noteStart}|${this.noteLength.length}`;
153- if (key !== this.cacheKey) {
154- this.cacheKey = key;
155- const cc = this.cache.getContext("2d")!;
156- cc.setTransform(dpr, 0, 0, dpr, 0, 0);
157- cc.clearRect(0, 0, this.width, HEIGHT);
158- this.drawPoints(cc, 0, this.noteStart, 0.35);
159- }
160- ctx.setTransform(1, 0, 0, 1, 0, 0);
161- ctx.drawImage(this.cache, 0, 0);
162- ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
163- this.drawPoints(ctx, this.noteStart, n, 0.85);
164-
165- // Nearest point to the mouse.
166- let near = -1;
167- if (this.hover) {
168- let best = 15 * 15; // within 15 px
169- for (let i = 0; i < n; i++) {
170- const dx = this.px(E[i]) - this.hover.x, dy = this.py(L[i]) - this.hover.y;
171- if (dx * dx + dy * dy < best) {
172- best = dx * dx + dy * dy;
173- near = i;
174- }
175- }
176- }
177- if (near >= 0) {
178- ctx.strokeStyle = "#23262b";
179- ctx.lineWidth = 1.25;
180- ctx.beginPath();
181- ctx.arc(this.px(E[near]), this.py(L[near]), 4, 0, 2 * Math.PI);
182- ctx.stroke();
183- }
184-
185- ctx.font = FONT;
186- ctx.textBaseline = "top";
187- ctx.fillStyle = "#2f5d8a";
188- const legend =
189- near >= 0
190- ? `E ${E[near].toPrecision(3)} J λ ${L[near].toFixed(3)} 1/s ${T[near].toFixed(2)} s into note`
191- : "λ (1/s) vs E (J)";
192- ctx.fillText(legend, 4, 3);
193- ctx.fillStyle = "#999";
194- ctx.textAlign = "right";
195- ctx.fillText(`E 1e${this.lgMin} … 1e${this.lgMax} (log) · λ ${this.lMin.toFixed(2)} … ${this.lMax.toFixed(2)}`, this.width - 4, 3);
196- ctx.textAlign = "left";
197- ctx.fillText("λ = 0", 4, this.py(0) + 2);
198- }
199-}
200-
201-// Color at u in [0, 1] along RAMP.
202-function rampColor(u: number): number[] {
203- const s = u * (RAMP.length - 1);
204- const i = Math.min(RAMP.length - 2, Math.floor(s)), w = s - i;
205- return RAMP[i].map((a, k) => Math.round(a + (RAMP[i + 1][k] - a) * w));
206-}
src/fput-chain/spectrogram.tsmodified+1−1View file
@@ -5,7 +5,7 @@
55 // time (a time average would hide the broadband start of a chaotic note under
66 // its long, quiet, tonal tail).
77
8-import { attachCursor, type Cursor } from "./cursor";
8+import { attachCursor, type Cursor } from "../common/cursor";
99
1010 const HEIGHT = 200;
1111 const RANGE_DB = 60; // color range below the peak
src/fput-chain/traces.tsmodified+1−1View file
@@ -9,7 +9,7 @@
99 // the panel's charts, and optionally with other charts) and the values there;
1010 // a click pins it.
1111
12-import { attachCursor, newCursor, type Cursor } from "./cursor";
12+import { attachCursor, newCursor, type Cursor } from "../common/cursor";
1313
1414 export interface Series {
1515 label: string;
src/fput-chain/wav.tsdeleted+0−38View file
@@ -1,38 +0,0 @@
1-// WAV export: a note as a 16-bit PCM mono WAV file, scaled so its peak is at
2-// 0.9 of full scale (so every saved note is equally loud and none clips).
3-
4-export function wavBlob(x: Float32Array, sampleRate: number): Blob {
5- let peak = 0;
6- for (const v of x) peak = Math.max(peak, Math.abs(v));
7- const g = peak > 0 ? 0.9 / peak : 0;
8- const buf = new ArrayBuffer(44 + 2 * x.length);
9- const v = new DataView(buf);
10- const text = (o: number, s: string) => {
11- for (let i = 0; i < s.length; i++) v.setUint8(o + i, s.charCodeAt(i));
12- };
13- text(0, "RIFF");
14- v.setUint32(4, 36 + 2 * x.length, true);
15- text(8, "WAVE");
16- text(12, "fmt ");
17- v.setUint32(16, 16, true); // fmt chunk size
18- v.setUint16(20, 1, true); // PCM
19- v.setUint16(22, 1, true); // mono
20- v.setUint32(24, sampleRate, true);
21- v.setUint32(28, 2 * sampleRate, true); // bytes per second
22- v.setUint16(32, 2, true); // bytes per frame
23- v.setUint16(34, 16, true); // bits per sample
24- text(36, "data");
25- v.setUint32(40, 2 * x.length, true);
26- for (let i = 0; i < x.length; i++) v.setInt16(44 + 2 * i, Math.round(32767 * Math.max(-1, Math.min(1, g * x[i]))), true);
27- return new Blob([buf], { type: "audio/wav" });
28-}
29-
30-// Hand a file to the browser to save.
31-export function saveFile(blob: Blob, name: string): void {
32- const url = URL.createObjectURL(blob);
33- const a = document.createElement("a");
34- a.href = url;
35- a.download = name;
36- a.click();
37- setTimeout(() => URL.revokeObjectURL(url), 1000);
38-}
↑↓ move↵openescclose