/ interactive_tutorials / duffing_islands
Sign in
interactive_tutorials / duffing_islands
duffing_islands
Go to fileHistoryFork
appTrack octave, range and mono; faster tempos; audio-only WAV recording
scriptsTracks, SoundFonts, sessions, recording and MIDI
.gitignoreIslands in a sea of chaos: Duffing phase space with sonification
package.jsonTracks, SoundFonts, sessions, recording and MIDI
README.mdTrack octave, range and mono; faster tempos; audio-only WAV recording

Islands in a sea of chaos#

A minimal lab for the driven Duffing oscillator's phase space, a companion to the hardening and softening tutorial (same equation and units):

ẍ + δẋ ± (2πf₀)² x + αx³ = F cos Ωt

npm run dev     # serves app/ at http://127.0.0.1:8002, caching off
npm run check   # node --check on every module
node scripts/section-png.mjs out.png -220 2e7 0 5.6e4 490 1500 0.5   # render a section (for choosing presets)

Static index.html, style.css and ES modules, no build step; fonts bundled under app/vendor/.

What's in it#

  • Poincaré section: (x, ẋ) once per drive period, at drive phase 0. Seed orbits from the axes of the view fill it in live. Undamped, regular orbits draw closed curves (islands, island chains) and chaotic ones scatter over the sea. Damped, the seeds settle onto the attractors first.
  • Tempo and sound (top right): the global tempo (40 to 240 bpm, default 120), the big sound on/off button, and the master volume. A track played while the sound is off makes the button pulse.
  • Tracks (right panel, up to 8): each is an orbit and how it plays. Tracks start paused, so they can be set up first; each has play/pause, restart (from its start) and remove, and Play all, Pause all, Restart all act on every track. The open track shows its controls; click another track's header to open it.
  • Orbit: click the plot to place (or move) the open track's start, or drag its ring; click any start ring to open its track; shift-click (or + Add track, then click) for a new track. The orbit's dots fill in (larger, brighter), and while it plays a playhead walks it one drive period per beat, with a fading trail of the continuous motion through each period and a ring at each pluck. Changing a parameter or preset restarts nothing: the tracks carry on from where they are under the new equation, their dots recomputed from there, and the old dots (and the old section behind them) fade out as the new ones fill in. Restart takes a track back to its start.
  • Track settings: instrument, rhythm, tempo multiple, scale, key, range, mono, sustain (built-in instruments) or velocity (SoundFonts), and volume, two to a row where the card is wide enough. Each but the instrument has a link toggle: linked tracks share one value (change it on any of them and all follow), unlinked ones have their own. By default scale and key are linked.
  • Tempo multiple: each track advances one drive period per tick, at a multiple of the global tempo: ×1 (the default: 2 drive periods a second at 120 bpm), ×2, ×3, ×4, ×6, ×8, ×12, ×16, ×24, ×32, ×48, ×64, ×1/2, ×1/3, ×1/4, ×1/6, ×1/8, or a custom number or fraction (1/16 to 128, such as 3/2). The fastest blur into a texture or a buzz (×64 at 240 bpm is 256 notes a second), where Mono keeps them clean. Ticks fall on a grid aligned to the beat, so ×2 and ×3 meet on every beat and ×1/2 ticks on every other beat (polyrhythms); a track that starts playing joins at its next tick. Changing the tempo carries the beat on from where it is.
  • Notes: each pluck's pitch is set by x (left to right across the view: C3 to C6 by default), on the track's scale (minor pentatonic by default; major pentatonic, major, minors, whole tone, chromatic, or continuous) in its key (A by default). The key keeps the register and changes which notes x snaps to, so switching key while playing shifts the harmony like a chord change. The range sets the register: the note at the left edge (C0 to C6, C3 by default) and the octaves across the view (1 to 6, 3 by default), so a bass line and a melody can share one scale, and fewer octaves make x's notes wider apart. Its two menus are linked together. With Mono on, each note stops the track's note before it (a 40 ms fade), so the track plays one note at a time however long the sustain; off (the default), notes ring on and overlap. An island orbit plays a repeating pattern; a chaotic one wanders.
  • Custom notes (the last choice in the Scale menu): pick the notes yourself on a small piano in the track's card, by clicking keys or by pressing them on a MIDI keyboard (Web MIDI: Chrome, Edge or Firefox; the browser asks for permission the first time). Choosing Custom notes starts listening to the keyboard. The keys you hold down together become the notes: press them at once, or one after another without letting go of them all (or with the sustain pedal down); once every key is up, the next press starts a new set. Clicking a key on the piano adds or removes just that note (and, with the sound on, plays it on the track's instrument; keys pressed on the MIDI keyboard aren't played). Keys go to the open track's notes; Listening… toggles this, and Clear empties them. With Every octave (on by default) their pitch classes make a scale across the track's range; turn it off and the notes themselves are spread across the view from left to right, lowest to highest, so x picks among exactly those notes. A key change transposes them (the nearer way), and the range's first menu shifts them by octaves (its second doesn't apply); the piano shows them as they sound, so a key you press sounds as pressed. The notes go with the scale setting, so linked tracks share them; unlink a track's scale to give it its own. Switching to another scale and back keeps them.
  • Rhythm: natural, upward plucks wherever ẋ crosses 0 upward (the left turning point of each swing), at that x and at that moment in the slowed-down motion, so each orbit makes its own rhythm: lilting and nearly regular on an island, uneven in the sea. Both ways also plucks at the right turning point. Steady (the default) plucks once per drive period, at the section point.
  • Instruments: harp, marimba, vibraphone, electric piano, music box, ocarina, pizzicato and kalimba (a new track takes the first one not in use). Sustain (0.1 to 4 s, default 2) sets how long the notes ring, the same for every voice and pitch, so the voices differ only in timbre and attack, and all start equally loud. Volume is the track's level.
  • SoundFonts (optional): Load .sf2… (bottom of the tracks panel) loads one or more files; each one's presets join every track's instrument menu (a group per file), and the open track takes the first file's first preset. The list shows each file, its number of presets and the tracks using it; × removes one (its tracks go back to built-in instruments). Loading a file with the name of one already loaded replaces it, its tracks keeping their presets by name. Samples play as recorded, so Sustain doesn't apply to them; Velocity (1 to 127, with a little random jitter per note) picks their velocity layers. Each preset is matched in loudness to the built-in voices at velocity 100 near middle C. The files are remembered in the browser until × removes them.
  • MIDI knobs (optional): the Knobs button by the Equation heading puts a small chip on each equation slider and on the coupling. Click a slider's + and turn a knob on your controller (any MIDI control change, such as the knobs of an Arturia MiniLab); from then on that knob moves the slider, smoothly like dragging it. Knobs come in two kinds, told apart as you assign one (a relative knob turned steadily repeats itself, which an absolute one never does): an absolute knob sends its position, 0 to 127, and sweeps the slider's whole range; a relative (endless) one, such as the MiniLab's clickable browse knobs, sends steps left or right (64 ± n, 16 ± n or two's complement), and nudges the slider from where it is, by a 256th of its range a step (at least the slider's own step), more when turned faster. A chip shows its knob (CC number, channel if not 1, ↻ if relative); click it to assign another knob, switch its kind, or unassign it. A knob is assigned to one slider at a time. The assignments are kept in this browser (they belong to the controller, not the session, so they aren't in the session file or undone by Start over), and they work whether the chips are shown or not.
  • Coupling (optional, off by default; 1 to about 3000 s⁻¹ on a log scale): joins the playing tracks with the same tempo multiple into one system (one system per multiple), each pulled toward their mean by a spring and a damper on its difference (critically damped at rate r), leaving the mean motion as it was. Weakly coupled they nudge each other (and lose the energy of their mismatch, often settling into islands); strongly coupled they fall into step and play in unison, even in the chaotic sea. On the first preset, three sea orbits lock above about 900 s⁻¹. Whenever such a set of tracks changes (one played, paused, moved or removed, or its multiple changed) or the coupling changes, they carry on from where they are; only their dots are recomputed, coupled from there.
  • Recording (Record in the header, with Video or Audio (.wav) chosen in the menu beside it, which the browser remembers): Video records a video of the phase space alone (the dots, orbits, trails, plucks and start rings; no axes, labels or track numbers) with the sound as heard (after the master volume), for as long as you like; it turns the sound on. While recording, the header shows the time and size so far; Stop ends it, and Download video saves it: MP4 (H.264 and AAC) where the browser can record it, else WebM. The video is the plot's size on screen when the recording started (its longer side at most 1920 px; resizing the window meanwhile stretches it), 60 fps at about 8 Mbit/s (some 3.6 GB an hour). Everything you do while recording is in it, parameter changes included. Keep the tab in view: a hidden tab stops drawing frames. The page asks before closing with a recording not yet downloaded. Audio (.wav) records just the sound as heard (after the master volume and limiter), sample for sample, into a 16-bit stereo WAV at the audio device's rate (usually 48 kHz, about 11.5 MB a minute), saved with Download WAV. Keep the tab in view for this too: the notes are scheduled as the page draws, so a hidden tab falls silent.
  • Session (bottom of the equation panel): everything (the equation, coupling, tempo, master volume, and every track's settings, start, play state and where its playhead is) is saved in the browser as you go and restored on reload; the sound starts off. Save to file downloads it all as JSON, every loaded SoundFont included (their bytes in base64), and Open file… restores such a file, adding its SoundFonts (replacing loaded ones of the same name). Each track remembers its SoundFont by file name and its preset by number and name, so it finds them again even if the files are loaded in another order or a file changed. Start over goes back to the defaults (the SoundFonts stay).
  • Parameters: f₀ (negative: a double well), α, δ, F, Ω/2π, and the view's half-width in x. Presets: double well (islands in a sea; gentle drive with a thin chaotic layer; strong drive), pure cubic, hardening resonance island, and a damped strange attractor.

Physics and sound#

  • app/js/midi.js: the MIDI keyboard and controller (Web MIDI note-ons, note-offs, the sustain pedal and control changes from every input, including ones plugged in later).
  • app/js/session.js: the browser save (localStorage; the SoundFonts themselves in IndexedDB, one record per file, app/js/soundfont.js), and the file's base64 and download helpers. Restoring checks every value and falls back to the default for anything missing or out of range.
  • app/js/duffing.js: each drive period in N equal steps of a 4th-order Yoshida composition of a damping/kick/drift/kick/damping leapfrog (symplectic when undamped, so islands keep their shape over long runs), with the drive tabulated at the kick times. ω h ≤ 0.08 for the stiffest local frequency up to |x| = 1, past which an orbit has escaped.
  • Coupling (stepMany in duffing.js): each oscillator gets r² (x̄ − xₖ) + 2r (v̄ − vₖ), x̄ and v̄ the means of those not escaped. The damper part is solved exactly (the mean velocity is kept, differences decay by e^(−2rt)) in half steps around the kicks, the spring part joins the kicks. A damper alone would lock velocities but not positions (two orbits can glide along together in different wells), hence the spring.
  • app/js/voices.js: notes rendered once per voice, pitch and sustain into AudioBuffers, each ringing for the sustain (the fundamental's 60 dB decay time) and matched in loudness by the K-weighted RMS (ITU-R BS.1770's filter: +4 dB above about 1.7 kHz, high-pass at 38 Hz) over its first 0.3 s. Strings (harp, pizzicato) are Karplus-Strong. The string starts in a rounded triangle (plucked at 0.15 of its length, so harmonics 2 to 4 sit about 8, 14 and 21 dB below the fundamental), loops through a [¼, ½, ¼] low-pass (highs die away first) with an all-pass for fractional-delay tuning, and gets a 4 ms soft attack. Bars, tines and the ocarina are a few decaying sinusoids at the instrument's partial ratios (marimba 1 : 3.93 : 9.2; vibraphone 1 : 4 : 10 with tremolo); the electric piano is two-operator FM with a fading index. SoundFonts (app/js/soundfont.js) are parsed into regions (key and velocity ranges, root key, tuning, attenuation, loop, attack and release), preset and instrument levels combined as in the SF2 spec; modulators, filters and LFOs are not modelled except the velocity-to-attenuation curve. Unlooped samples play to their end; looped ones loop for 1.5 s, then fade over their release. Then a gentle 3.5 kHz low-pass, a dark synthetic reverb and a limiter. Notes are scheduled on the audio clock a little ahead of time, softer the more tracks play, through each track's gain (its volume); each track keeps at most 64 notes sounding (the oldest fades out in 40 ms), so fast tempos with long sustains stay light.
↑↓ move↵openescclose