Overview
A lava lamp — a physical, analogue, thermodynamic system — is filmed continuously and translated, in real time, into continuously evolving audio. Each wax blob spawns a voice when it is detected and keeps that voice for its whole life: its height, speed, temperature (read from its colour), shape and geometric evolution all become sound. The merging of two blobs, the bifurcation of one, a blob coming to rest at the top of the lamp — these are the harmonic and dissonant events of the score.
Above the voices sits a score grammar that listens to the whole lamp at once. It decides where phrases end, what the pulse is, which chord the ensemble is leaning toward, and which blob is leading — and it does all of this from the topology of the image rather than from a composer's hand. The lamp never repeats itself, so every run is a new piece.
The idea behind the project is that heat convection is the compositional agent. The system is not a controller for a synthesiser and not a visualiser for a lamp; it is an attempt to read a closed physical system as a score, with enough musical grammar that the reading sounds like a piece rather than a sonification. The name nods to Agostino Di Scipio's Audible Ecosystemics.
The system has three tiers. Tracking turns camera frames into blobs with stable identities, using 0-dimensional persistent homology (H0) as the notion of what counts as a blob, optical flow to carry identity between frames, and a physics-informed Kalman filter that knows how buoyant wax moves. Voices bind each blob to a slot in a sixteen-voice polyphonic synthesiser that a human player can also own, so the lamp and the player share one instrument. The score grammar borrows the structural categories of Lerdahl and Jackendoff's Generative Theory of Tonal Music (GTTM) — grouping, meter, time-span reduction, prolongation — and treats them as a control decomposition for generation, with the lamp's topology as the evidence those categories need. On top of the grammar, a motion-driven melody layer gives each blob a line, a physically modelled synth palette makes the hierarchy audible as instrumentation, and an optional neural timbre-transfer stage lets the whole lamp be heard through pre-trained RAVE models.
Media
Short captures from the development rig — single-camera capture, voice-slot overlay, merge tree, and the keyboard controller wired through the pygame input window.
One Pass Through the Loop
Eight stages run as a continuous loop at roughly 15 frames per second. Each stage is described with what it does and, in italics, why it exists — usually a specific thing that went wrong without it.
Capture & Calibration
A USB camera at 1280×960. A one-time freehand calibration lets you paint over typical wax at different temperatures and mark the lamp's vertical range; the system derives wax-colour bounds in HSV space, the region of interest and the persistence threshold, saved as lamp_profile.json. A frozen per-pixel median background is captured once and subtracted from every frame.
Why frozen: an adaptive background model absorbed slow wax (half a pixel per frame) into the background within a second, and the blob vanished. A median that never adapts cannot forget the wax. The w key re-captures it on a running lamp.
Topological Detection
The foreground mask, intersected with the wax-colour mask and cleaned morphologically, is handed to GUDHI's CubicalComplex for H0 persistence. Features above the persistence threshold are kept; each is enriched with contour moments (orientation, elongation, Hu invariants) and a wrap-safe circular-mean hue classified into rising, falling or turning.
Why persistence: a tiny bright blob and a large dim one are both significant, and an area threshold gets one of them wrong. Persistence measures how prominent a feature is relative to its surroundings across every intensity threshold at once — prominence, not size.
Identity: Flow, Topology, Physics
Dense optical flow carries every track's mask forward to the new frame; overlap between advected masks and detections gives the matches, with ambiguous overlaps resolved by distance in the persistence diagram rather than pixel space. A five-state Kalman filter [x, y, vx, vy, ay] with a buoyancy prior predicts motion. Blobs lost for up to fifteen seconds are recognised when they return by a topological fingerprint. A stability layer fuses fragments, completes partial views, re-associates new regions with coasting tracks, and confirms births over three detection cycles.
Why: a blob's identity is its mask, solved once at birth, not a per-frame nearest-centroid guess. Per-frame matching caused a storm of phantom births and deaths every time wax went briefly transparent or reversed direction, and each phantom birth was a new voice with a strike.
Binding & Voice Pool
A BindingManager turns birth, death, merge and split into voice-slot lifecycle calls on a sixteen-slot VoiceManager. A blob can tie to a pre-armed empty voice, resurrect a zombie, or spawn a fresh BLOB_ONLY slot. Any tracked blob left without a voice — re-identified, or born while the pool was full — is bound on the next frame. Each voice runs a routing matrix mapping blob features onto synth parameters.
Why the voice is the first-class object: through v3 the system was a one-way translator, blob → sound. Making the voice a slot that outlives any blob is what lets a player pre-arm a voice and hand it to the next blob born, and what lets a blob's sound continue through a tracking gap.
Score Governor
The ScoreGovernor reads all tracked blobs, the merge tree and the persistence diagram together and emits a ScoreState each frame: phrase boundaries, an elastic tempo and meter, a harmonic field on the Tonnetz, a tension value, a prominence ranking, and continuous role weights for every blob. It stamps governor-derived sources onto each blob so the routing matrix can read them.
Why: six independent voices are a texture, not a piece. The governor is what makes them an ensemble, and it does so without choosing a leader — every blob both plays and governs, weighted by a softmax, so leadership drifts rather than switching.
Articulation: Melody, Patterns, Pairs
Three short-note generators run on top of the sustained drones. The melody layer fires per-blob notes from a motion-driven hazard accumulator, pitched by a hysteretic height band. The pattern layer gives each blob a Euclidean rhythm on the governor's elastic clock. The most prominent third of blobs gain a paired octave-down voice with real note-offs.
Why: a drone follows a blob's position; a line follows its path. Hazard onsets mean a still blob speaks occasionally and a turning blob speaks in clusters, which is what motion sounds like.
Synthesis & Space
SuperCollider renders one \mpeVoiceRich per active slot — a wavetable oscillator through a morphing low/band/high-pass filter with a vowel formant from height — plus physically modelled hits (plucked strings for ornaments, piano hammers for the paired heads, bowed or plucked melody notes by whether the blob is expanding or shrinking), an orchestral swell on every birth, and a master reverb "space" whose size, haze and blooms follow the score state.
Why instrumentation: the time-span hierarchy — heads and ornaments — should be audible as a difference in instrument, not only in density.
RAVE Timbre Transfer optional
The finished mix is split to a private bus and re-synthesised by one or more pre-trained RAVE neural audio models running inside SuperCollider, in parallel, each adding its wet signal back before the master space. Off by default; toggled live.
Why parallel: "birds + organ" should be the lamp heard through two ears at once, not birds-of-an-organ.
Pipeline Architecture
Three tiers, each additive on the one below. Tracking produces blobs with stable identities; the voice pool binds them to synth slots shared with a player; the score grammar reads all blobs together and feeds back into the voices through the same routing matrix the player uses. Node order in SuperCollider is execution order, so the split, the RAVE models and the master space simply sit at the tail of the graph.
Temporal coherence — five layers
A blob takes 90–180 seconds to rise from base to top. Identity must survive detection noise, transparency dips and turning-point storms across that whole timescale, and five mechanisms stack up to make it so: (1) the flow-advected mask is always present even when the detector loses the blob; (2) fingerprint re-identification recovers a lost track for fifteen seconds; (3) the zombie voice pool holds the sound for a further four seconds; (4) the voice slot itself outlives any blob and can be authored, edited and tied to a future blob by the player; (5) voice continuity guarantees that any tracked blob without a voice gets one, so a re-identified blob never sits silent. Identity exists above the lamp.
Tracking
Persistent homology as a significance filter
Rather than detecting blobs by thresholding intensity or filtering by area — both of which conflate size with significance — persistence measures how prominent a blob is relative to its local surroundings across a continuous range of thresholds. The H0 persistence diagram treats the greyscale image as a scalar function: as a threshold sweeps from high to low intensity, connected components born at blob peaks die when they merge with a brighter neighbour. A blob's persistence is the intensity gap between its peak and the saddle where it merges. The input is inverted so OpenCV's "bright = foreground" matches GUDHI's sublevel-set sweep; downscaling keeps the computation under ~40 ms. A branch deduplication pass removes same-branch sub-features using the elder rule, and the merge tree the computation produces is kept: it is a per-frame hierarchy of the wax, and the score grammar reads its depth and its saddle events directly.
Flow-advected mask identity
Farneback dense optical flow estimates a displacement at every pixel between consecutive frames. Each track owns a binary mask initialised from its birth contour; every frame the mask is remapped forward by the flow, and every fifth frame it is blended 50/50 with the current detection contour to counteract drift. A blob that briefly becomes semi-transparent and disappears from the persistence diagram does not fire a death event — its mask continues to exist and be advected. When several advected masks overlap one detection, the ambiguity is resolved by a cost that weights distance in the persistence diagram's birth–death plane at 75%, pixel distance at 15% and hue at 10%: two blobs at similar positions but different thermal states are told apart where a position-only assignment would guess.
Physics-informed buoyancy Kalman
Lava-lamp blobs do not move at constant velocity: they decelerate to near zero at the top and bottom as buoyancy reverses and accelerate through the middle. The tracker's Kalman filter adds a fifth state, vertical acceleration, with mean-reverting dynamics and a directional prior from the thermal direction read off the hue. Measurement noise adapts with height — high near the top and bottom (trust the physics, expect a turn), low mid-column (trust the detection) — so predictions are most accurate at the turning points, which is exactly where identity is most ambiguous.
One blob, one voice: the stability layer v4.13
The symptom this layer fixes: a stationary blob whose detected region fluctuates — growing, shrinking to a core, splitting into lobes, dropping out for a cycle — produced a stream of new voices, each with a birth strike, gliding away from the blob, instead of one voice that stayed with it. The cause is that a persistence region is a contrast measurement, and a still blob near the top or bottom pool hovers right at the threshold. StableBlobTracker wraps the tracker with a pre-pass and a post-pass, each fix behind its own switch: touching detections that lie mostly inside one track's mask are fused; a lone detection much smaller than a track's known extent is treated as a partial view and its centroid pulled only 15% of the way; a newly born track is offered to tracks that missed this cycle and re-associated by overlap coefficient, folding the measurement into the old id with no strike; remaining births are tentative and hidden until seen on three consecutive cycles; coasting velocity is damped; and a track whose smoothed speed is under 0.3 px/frame enters a stationary mode that keeps mid-column measurement noise and holds still.
Voices and the Player
Voice-slot architecture v4.0
A Voice is a slot in a fixed pool of sixteen, holding full synth state, a routing matrix and a lifecycle state independent of any blob. IDLE accepts only a spawn or a create-empty. BLOB_ONLY runs the routing matrix and forwards no keyboard input. KEYBOARD_ONLY accepts notes and edits but ignores blob updates. HYBRID accepts both — the player's notes set base values, the routing matrix adds modulation on top. ZOMBIE is a transient state with a timer. Every continuous parameter is tracked as a base value, a smoothed current value and a target, and first-order lag on the SuperCollider side ensures changes never click.
The player is a second driver of the same object. A pygame window turns the laptop keyboard into a sixteen-voice surface with a Performance mode (play notes on the selected slot) and an Edit mode (walk a parameter tree). All input is funnelled through a Controller protocol emitting ControllerEvents, so an external MIDI surface or a tablet is a new adapter and nothing downstream changes. The closed acoustic feedback loop of earlier designs was retired here: the loop now closes through the player's ears and hands.
Routing matrix
Every voice carries a list of Routing(source → destination, depth, curve) tuples. Sources read blob features each frame — height, horizontal position, velocities, speed, acceleration, persistence, area and their rates of change, hue, elongation, orientation, age — and, once the governor is running, score sources: tension, prominence rank, phrase position, beat phase, surprisal, ambiguity, merge-tree depth and role weight. Destinations write to synth parameters — pitch, cutoff, resonance, amplitude, pan, wavetable position, envelope times, detune, shimmer, noise, drive, filter mode. Curves are pre-tabulated lookups (linear, log, exponential, S-curve, square root). Default routings put height on pitch, persistence on level, elongation on resonance, orientation on pan, speed and area on wavetable position; pitch routings from several sources accumulate semitones rather than overwriting. Because governance arrives through the same matrix, the player can rewire score-level control live from the Edit surface.
The zombie voice pool
When a turning blob fires death then birth in quick succession, the release tail of the dead voice stacks against the attack of the new one — the nine-second phantom polyphony that plagued v3.0. On a blob's death its voice's slot becomes ZOMBIE: the synth node stays alive with its level scaled to 0.35, audibly softening without triggering a release. Before any new blob is given a fresh voice, the binding manager scans the zombies for one within ~15% of lamp height whose persistence is within a factor of three; the closest wins and morphs seamlessly toward the new target. Zombies older than four seconds release normally. A HYBRID voice the player has used in the last five seconds detaches to KEYBOARD_ONLY instead — the player keeps it; only the blob bind drops.
Voice continuity v4.12
A voice was only ever bound on a tracker birth event. When a blob flickered out of detection, the tracker emitted a death, the voice was zombified and eventually freed; when the blob was found again the tracker restored its old id through the re-identification buffer and, by design, emitted no birth. Nothing re-bound it, so the blob stayed labelled with its id, with no slot and no sound, for the rest of its life. The same hole opened when the pool was full at birth and a slot freed later. Now, after each frame's events, any tracked blob older than eight frames without a slot is bound — resurrected from a matching zombie if one exists, else given a fresh voice without the birth strike, since it is not a new blob. Two smaller fixes travel with it: a live voice never drops below 40% of its base level under governance (it can be pushed to the background, not muted), and the beat-phase dip on amplitude is applied as a proportional factor rather than a fixed subtraction, so a quiet voice is not silenced by the same accent that a loud voice barely notices.
The Topological Score Grammar
This is the part that turns voices into a piece. The design borrows the categories of GTTM — grouping, meter, time-span reduction, prolongation — and treats them as a decomposition of control, with Temperley's preference-rule machinery underneath and Hasty's projective meter for the clock. GTTM is a theory of listening, not generation; here its structural categories are repurposed, and the lamp's persistent homology supplies the evidence. Nothing is elected: every blob both plays and governs, and structural commitments come from probabilistic posteriors, so they move gradually and crossfades are a by-product rather than a feature.
How a preference is decided v4.2 · v4.9.5
Temperley's framework has two halves, and the score grammar uses both. The first is scoring. A rule is a small function that grades a candidate analysis — a meter hypothesis, a triad — between 0 and 1 against the current evidence, and every rule carries a weight. A candidate's preference score for the frame is the weighted sum of its grades:
No rule can veto: a candidate that fails one rule can still win on the others. The weights start from a hand-set file and can be changed live from the Edit surface.
The second half is choosing: take the analysis that scores best over time, with a penalty for changing your mind. Each module keeps a small beam of candidates and runs Viterbi over it:
Staying with the current analysis costs nothing; changing costs a fixed switching cost (by default 3 for meter, 2 for harmony), the counterpart of the penalty Temperley charges for a modulation. A rival therefore has to out-score the incumbent's accumulated path rather than win a single frame, which is what keeps the pulse and the harmony from flickering. The incumbent is always kept in the beam so the penalty always applies, and path scores decay by a forgetting factor of 0.95–0.98 per frame, so the analysis describes a trailing window rather than the whole run. The committed analysis is the best path. The softmax of the path scores is a posterior over every candidate, and that posterior, not a timer, is what consumers blend by: when the evidence shifts, probability mass moves from incumbent to rival over several frames, and every parameter read through it crossfades by itself.
One departure from Temperley: his rule scores and penalties add across the piece, whereas here the per-frame sum is logged before it enters the path, so across frames scores multiply like likelihoods. A frame on which a candidate scores near zero costs it more than a strong frame earns it.
The same rules serve three other shapes of decision. Continuous quantities — the meter's period and phase — weight the particles of a particle filter instead of a beam. Grouping scores only the hypothesis "boundary", because a boundary is an event rather than a competing state (below). Prominence and tension are weighted sums smoothed over time, with no decode.
Grouping — where phrases end v4.4 · v4.9.3
A phrase boundary is an event, not a state. Earlier versions modelled "boundary" and "continue" as two competing states in a beam with a switching cost, and every symptom followed from that category error (the commit test collapsed to a single unreachable threshold, a refractory period had to be bolted on, a phrase-length preference had to be hand-coded). The replacement is a product of two learned distributions:
h(τ) is the hazard of an online Gamma distribution fitted to the intervals between boundaries observed so far, evaluated at the time since the last boundary — the piece learns its own phrase-length distribution. It is near zero just after a boundary (the refractory period, for free) and peaks near the typical phrase length. Φ(z) is the probability that the evidence is out of the ordinary: a weighted sum of GTTM-style rules — a merge-tree saddle event, Bayesian online change-point detection on kinetic energy, occupancy entropy and coherence, a spike in the Wasserstein distance between successive persistence diagrams, a persistence-gated change in blob count, lifecycle events of blobs that have been tracked for at least three seconds, several cues coinciding — standardised online by its median and median absolute deviation, so the brightness of a particular lamp cancels. The two act as a soft AND, combined as odds: the hazard's odds are multiplied by Φ(z)/(1 − Φ(z)), a likelihood ratio that is exactly 1 for ordinary evidence and is clipped so that a single frame can move the decision only so far. Early in a phrase the hazard is near zero and no amount of evidence fires a boundary; an overdue phrase is held back while the lamp is quieter than usual. Commitment is decoded rather than drawn. The module carries several competing segmentations, each an assertion about where the last boundary fell; every frame each one either continues or places a boundary now, and only the best-scoring paths are kept — a beam Viterbi over a hidden semi-Markov model. A boundary is committed once it has stood on the best path for 1.5 seconds, so it is confirmed by what follows it as well as by the frame it occurred on, and a run is reproducible from its evidence. Boundary strength is still graded for free. The only number carrying a musical opinion is the prior phrase length, a quantity in seconds you can reason about.
Meter — the pulse
The lamp moves on 90–180 second cycles; a tactus lives at 0.4–2 seconds. The governor folds each blob's rise/fall period, and the periodicities of system-level signals (kinetic energy, flux, occupancy entropy, centre of mass), into the tactus range by repeated halving, then runs the preference-rule beam over (period, beats-per-bar) hypotheses. Four rules score them: periodicity, the most heavily weighted, for how strongly the lamp's signals and blobs repeat at the candidate period or a simple multiple of it; a London prior favouring a tactus near 0.7 s; cardinality, so that three bodies lean toward a three-beat bar; and period ratio, so that a 3:2 ratio between two blobs' cycles favours a three-beat bar and other ratios favour two or four. Changing meter pays a switching cost of 3, so a new pulse has to be better for a while before it takes over. The beam is blended half and half with a particle filter over continuous period and phase, whose particles are weighted mainly by how well blob turnarounds fall on their grid. The result drives an ElasticClock. Events are not hard-quantised: they are pulled toward the grid with a strength set by the Kuramoto order parameter of the blobs' phases, so a coherent lamp plays in time and an incoherent one drifts — the meter is as rigid as the lamp is synchronised.
Time-span — who leads
Each blob gets a prominence score from its integrated persistence over its whole life, its depth in the merge tree (root-adjacent blobs are structural), how strongly its motion correlates with the lamp's aggregate flux, whether it is a re-identified blob returning like a theme, the kinetic energy integrated along its path, and whether its voice currently sits on a strong beat and a chord tone of the harmonic field. The ranking is read everywhere: by the routing matrix as a foreground/background mixer, by the pattern layer to decide who carries the busy ornamental hits (low rank) and who keeps the sustained voice plus a paired, articulated octave-down partner (the top third). That is the Schenkerian head/ornament reading, made audible as instrumentation.
Prolongation — tension
Tension is a smoothed composite of the surprisal of the lamp's current macrostate under a Markov model learned online over symbols (blob count, energy level, spread), the Wasserstein distance between the current persistence diagram and the lamp's equilibrium diagram, kinetic energy relative to its reference, and the conditional entropy of the Markov chain. Ambiguity is the normalised conditional entropy alone. Both are read by the pattern transforms, the harmony walker, the melody scale, the synth palette and the master space, so the whole ensemble leans the same way at once.
Harmony — the field
A TonnetzWalker moves between triads on the neo-Riemannian Tonnetz by the parsimonious P, L and R operations (and compound moves under high tension). A move is proposed each frame and scored by preference rules: parsimony (fewer voice-leading moves), a step gate that licenses a move only when a topological change budget — accumulated diagram distance — has been spent, a direction rule that walks away from the home triad when the lamp is leaving equilibrium and back when it returns, size licensing for compound moves, and fit to the pitch classes actually sounding. The current triad always competes as the stay-put candidate and a move pays a switching cost of 2, so a new chord needs sustained support rather than one good frame. The committed triad plus added tones under ambiguity is the pitch field every generator draws from; harmonic gravitation pulls the sustained voices toward chord tones in proportion to confidence. The predicted next triad is quietly pre-sounded at a gain equal to the posterior mass on non-current candidates, so the listener hears where the harmony might go before it goes.
Roles without an election
Governance is a set of continuous softmax role weights. For each of five roles — grouping, meter, time-span, prolongation, harmony — every blob and a few system-level virtual signals receive a raw score: periodicity of vertical motion for meter, slowness for harmony, erraticness (permutation entropy) for prolongation, nearness to the merge-tree root for grouping, prominence for time-span. A softmax with temperature 0.6 turns the scores into weights that sum to one; scores are smoothed and absent blobs decay. There is no handover code and no crossfade timer. When blob A stops oscillating cleanly and blob B starts, A's meter score falls, B's rises, and the weights cross over by themselves — the listener hears the pulse migrate rather than switch.
Patterns and schemata
Each blob owns a Euclidean rhythm E(k, n): the slot count n is the number of beats in one of the blob's own rise/fall cycles (so a slow blob gets a long, sparse cycle and a fast one a short, busy one), the hit count k grows with area, and the pattern is transformed Tidal-style — degraded less as tension rises, arpeggiated over the pitch field, swung by elongation, doubled at a boundary. Area, persistence, elongation and period are three-second moving averages so the rhythm cannot flip frame to frame. Separately, a small lexicon of Gjerdingen-style schemata (plateau, prinner, cadence and others) gives the ornamental layer a melodic contour, chosen at each boundary by a Markov chain biased by tension and entropy.
Melody and Rhythm
The drones are continuous; this layer gives each blob a line. It was chosen as the smallest pair of additions with the largest audible effect: without an onset generator nothing in a rhythm layer has a trigger to act on, and without discrete pitch motion there is no melody for the turning-point cadence to resolve.
Hazard-driven onsets
Each blob owns an accumulator. Every frame it gains h · dt, where the instantaneous rate h = h₀ (1 + a·speed + b·accel) is capped at one note per second, and when the accumulator crosses 1 a note fires and it resets to a small random residual. A still blob plays roughly one note every four seconds; a blob mid-rise or at a turning point plays a cluster. Because the accumulator integrates, a burst of motion yields a run of notes rather than a single trigger, and a slow blob still eventually speaks. A refractory floor prevents machine-gun retriggering, and nothing fires in a blob's first half second while the Kalman filter settles. The same hazard idea that decides phrase boundaries decides note onsets, one level down.
Height-band pitch with hysteresis and contour inertia
The lamp is divided into ten horizontal bands — five scale degrees across two octaves — and each band maps to a degree. A blob's band only changes when its centroid leaves the current band by a quarter of a band height, so a blob hovering at a boundary never flickers between two pitches. The band is an attractor, not the note: the note that actually sounds walks toward it in steps whose size depends on speed (slow → stepwise, fast → thirds and leaps) and whose direction follows the blob's direction of travel only after that direction has been held for 0.8 seconds. A reversal is a turning point and forces resolution onto the band, which is the cadence.
Coupling to the governor
Two couplings, both silently off when the governor is not running. The five-note scale is derived from the field: the three pitch classes of the current triad plus the two diatonic neighbour degrees the current schema's contour uses most, with the triad root placed within half an octave of a register note — so the register is a tessitura, not a key. The scale is latched on a beat boundary so it never changes between a note's selection and its sounding; C major with the default neighbours gives exactly the C pentatonic that plays with the governor off. And a note that fires is delayed toward the nearest beat line by the same Kuramoto elastic strength the pattern layer uses — only delays are possible, so the pull is one-sided — meaning a locked lamp plays on the grid and a free one does not. Durations are whole beats of the elastic clock chosen by area; an expanding blob plays legato and a shrinking one staccato; each note copies its drone's current timbre so a blob's melody sounds like its voice.
Sound
The synth palette v4.10
Every classic SynthDef has a richer drop-in sibling that accepts exactly the control names the Python side already sends, plus a few extras, so no message had to change and the two palettes can be swapped live with the ensemble migrating voice by voice. \mpeVoiceRich is a wavetable oscillator reading across sixteen buffers (analogue shapes, harmonic sweeps, formants, metallic partials) through parallel low-, band- and high-pass filters crossfaded by a continuous fmode, with a vowel formant set by height (oh at the bottom, ee at the top), sub-octave weight by area and chorus width by sideways drift. \mpeHitRich renders the ornamental pattern layer as a plucked string and the paired head voice as a piano hammer. \melodyHitRich is bowed when the blob is expanding and plucked when shrinking, bow pressure from speed. \blobStrikeRich is an orchestral swell on every birth — a noise-puff excitation under harmonic partials with a bowed-string rise. With sc3-plugins absent, stock UGens substitute.
The master space
\lavaMaster sits at the tail of the synth graph, reads the complete mix and replaces it with a processed stereo image. Its parameters are driven every frame from the score state: harmonic ambiguity sets reverb time (ambiguity is haze), tension sets damping and pre-reverb drive (tension is a bright tail), phrase position sets the wet mix so a phrase dissolves toward its boundary, surprisal sets the feedback of a Greyhole diffuser, the Kuramoto order sets modulation depth (incoherent motion is drift), the smoothed blob count sets room size (fewer blobs, bigger room), and every grouping boundary triggers a bloom proportional to its strength. The predicted next triad is held quietly by three \preSoundRich nodes alongside it.
RAVE Timbre Transfer v4.11–v4.14
A final, optional stage runs the finished lava mix through one or more pre-trained RAVE models — the Realtime Audio Variational autoEncoder from IRCAM — inside SuperCollider via the nn.ar extension. The lamp plays the rich palette untouched until the layer is switched on.
Signal path
A \raveSplit node copies the main bus to a private bus and scales the dry signal by 1 − mix. One \raveXfer_<model> node per active model reads that copy, runs the model, and adds its wet output back to the main bus at mix / √n, panned to a fixed position in the bank. Both are placed before the master space, so the reverb treats the transferred timbre like any other voice. One SynthDef per model is forced by nn.ar's design — a model is bound at build time and every node owns an independent instance — so an inactive model costs nothing; nodes are gated with a fade rather than freed outright because nn.ar blocks the audio thread while joining its inference thread on destruction.
Why a parallel bank, not a series chain
Several models can be on at once, and each reads the same dry copy: "birds + organ" is the lamp heard through two ears at once, not birds-of-an-organ. Nineteen models are listed best-first for the lamp. Models trained on pitched, sustained instrumental sound — the SOL orchestral set, MusicNet chamber music, the organ archive, the magnetic-resonator piano — follow the drones' pitch and dynamics, so the lamp's harmony survives the transfer; voice models follow it loosely; texture models (birds, water, percussion) mostly map loudness to texture and lose the pitch. Latency is about 0.7 seconds for non-causal models; on 90–180 second cycles that reads as a halo rather than an echo, so the dry path is deliberately not delayed to align.
Player Controls
Two OS windows run simultaneously: an OpenCV video window with the overlay graphics, and a pygame window that captures keyboard events. The pygame window must hold focus for music keys; the video window only receives toggle keys. TAB cycles the keyboard window through PERFORMANCE, EDIT and RAVE.
Video-window keys
| Key | Action |
|---|---|
| q | Quit |
| v t o m f c | Toggle HUD · tracking overlay · contours · merge tree · optical flow · mask windows |
| n | Melody layer on/off |
| p | Rich / classic synth palette (live; voices migrate one by one) |
| x / k | Bypass / respawn the master space |
| a | RAVE layer on/off |
| b / w | Re-capture the background reference (cold / warm, lamp already running) |
| [ / ] | Persistence threshold −/+ 2.0 |
Performance mode
Plays notes on the selected slot. KEYBOARD_ONLY and HYBRID slots respond; BLOB_ONLY slots ignore notes until claimed as HYBRID in Edit mode. The number row selects slots 0–9; the lower letter row is one chromatic octave, the upper row the next.
| 1 … 0 | Select slot 0–9 |
| Z S X D C V G B H N J M , L . | Lower octave, chromatic |
| Q 2 W 3 E R 5 T 6 Y 7 U I O P | Upper octave, chromatic |
| [ / ] | Octave down / up |
| SPACE | All notes off |
Edit mode — parameter families, binding, governor
Letter keys select a parameter family on the selected slot; arrow keys walk and adjust parameters, with - / = as coarse versions. The governor family exposes rule weights, the phrase prior, temperature and smoothing constants live; edits are mirrored to governor_runtime.json.
| Key | Action |
|---|---|
| P W E F M | Pitch · wave · envelope · filter · mod (routing list) families |
| G | Governor family — gov.<module>.<key> weights and constants |
| ← → / ↑ ↓ | Cycle parameter / fine adjust |
| B | CLAIM_HYBRID — promote BLOB_ONLY → HYBRID |
| N | CREATE_EMPTY — next IDLE slot becomes KEYBOARD_ONLY |
| T | TIE_BLOB — bind selected KEYBOARD_ONLY slot to the next blob born |
| D | DETACH — break the blob bind; voice continues as KEYBOARD_ONLY |
| R | Reset the focused parameter to default (in the governor family on reset_learning, restore the phrase prior) |
| C | Clear all routings on the selected slot |
RAVE tab
| Key | Action |
|---|---|
| home row, then Q W E T Y U I | Toggle model 0–18 (the tab lists each with its loaded/missing status and sample rate) |
| SPACE | Layer on/off |
| ↑ ↓ / + − | Wet mix ±0.05 / ±0.25 |
| ← → | Input gain ÷ / × 1.4 |
| Z / R | All models off / re-read status |
Voice-state ring legend
In the video overlay, every tracked blob bound to a slot gets a coloured ring encoding the slot's lifecycle state; the selected slot's ring is drawn thicker.
Version History
Each iteration addressed concrete failure modes observed in the previous one. The arc runs from generic multi-object tracking toward methods that exploit the physics and topology of a lava lamp; from autonomous translator to performable instrument; and from independent voices to a governed ensemble.
v1.0Initial Implementation
OpenCV SimpleBlobDetector with an HSV colour mask, nearest-centroid Hungarian assignment, constant-velocity Kalman, OSC bridge to SuperCollider. No identity fingerprinting; spurious births and deaths on every transparency fluctuation.
v2.0Topological Detection
GUDHI H0 persistence replaced the blob detector — a topological significance filter in place of an area threshold. Contour moments, coast-and-retire, three SynthDefs, a warm-up gate against ghost IDs.
v3.xPhysics-Grounded, Flow-Advected
Optical-flow mask advection became the identity carrier. Wasserstein-inspired topological matching, the five-state buoyancy Kalman, birth fingerprinting for re-identification, hue-derived thermal direction. v3.2 added the zombie voice pool and froze the background model against turning-point storms.
v4.0MPE Edition — Voice Slots & Player Agency
The voice became the first-class object: a sixteen-slot pool with lifecycle states, a per-voice routing matrix, the \mpeVoice wavetable SynthDef, a pygame keyboard controller with Performance and Edit modes, bidirectional blob ↔ voice binding, and a Controller protocol. The plinth, feedback speaker and three-camera concept were retired.
v4.1Frozen Background, Detection Cadence
A frozen per-pixel median background replaced the adaptive model (slow wax was being absorbed within a second). The heavy vision stack runs every K-th frame and predicts between. A dimension-ordering bug in the GUDHI call was fixed and the merge tree pruned to detected wax.
v4.2 – v4.5Topological Score Grammar
The governor layer: system-state tracker with entropies, change-point detection and a learned Markov model; preference-rule beams and particle filters; the elastic clock; the Tonnetz walker; the schema lexicon; the pattern language. v4.4 replaced the Viterbi grouping beam with the hazard × evidence event model after diagnosing the category error. v4.5 wired the pattern layer and governor routings that had been implemented but never called.
v4.6 – v4.8Pairs and Calibration
Ambiguity normalised by the observed alphabet (a fixed divisor had saturated and frozen four couplings); the paired articulated voice for the top third by prominence, rendered through self-freeing hit nodes so there are real note-offs.
v4.9Melody & Rhythm, Evidence Quietened
The hazard-onset / band-pitch melody layer, then its couplings to the governor (scale from the field, onset pull). The grouping evidence was quietened: a lifecycle gate ignores events from blobs younger than three seconds, a persistence-gated effective blob count replaces the raw count, and pattern features are three-second moving averages. Pitch routings accumulate semitones; the Lava Climb game feed was removed.
v4.10Rich Synth Palette
Drop-in rich SynthDefs with physical models for hits and melody, per-voice extras (formant, sub, chorus), the \lavaMaster space driven by the score state, and the predicted-triad pre-sound finally spawned. A latent inversion of the height source was fixed.
v4.11RAVE Timbre Transfer
Split node plus one transfer node per active model via nn.ar, parallel bank, RAVE tab in the keyboard window. The birth strike was rewritten as an orchestral swell. A NaN guard was added to every feedback SynthDef.
v4.12Voice Continuity
Every tracked blob gets a voice: re-identified or missed-at-birth blobs are bound on the next frame, live voices are floored at 40% of base level, the beat dip is proportional.
v4.13 – v4.14Tracker Stability, Nineteen Modelscurrent
One blob, one voice: fragment fusion, partial-view completion, re-association, birth confirmation, damped coasting and stationary mode. Seven models from IRCAM's ACIDS catalogue added and the bank ordered by fit with the lamp. A one-shot SuperCollider loader (dso_main.scd) brings up the whole synthesis half in order and waits for each file to be truly ready.
Build
Hardware
| Component | Purpose |
|---|---|
| Mac (Intel or M-series) | Central compute — vision, GUDHI, SuperCollider, keyboard input. RAVE inference is the heaviest load; an Intel Mac needs a larger inference buffer. |
| USB webcam (Logitech C920 / Brio) | Primary camera, calibrated at 1280×960, on an articulated arm 30–40 cm from the lamp |
| Lava lamp (e.g. Mathmos Astro) | The instrument |
| Audio interface + monitors, or a USB speaker | Stereo output from SuperCollider |
| Behringer DeepMind 6 (optional) | Analogue voice for one or two slots, chosen for six voices matching a typical blob count and smooth CC response on 90–180 s cycles |
| MIDI controller (planned) | Faderfox EC4 or MIDI Fighter Twister behind the same Controller protocol |
Software stack
Python 3.11 (pinned for GUDHI and current OpenCV wheels on macOS) in a conda environment: opencv-python, numpy, scipy, gudhi, python-osc, pygame. SuperCollider 3.13+, with sc3-plugins optional (stock fallbacks are built in) and nn.ar for RAVE. Evaluate dso_main.scd once to boot the server at 48 kHz and load the five synthesis files in order — classic SynthDefs and wavetables, hits, melody, rich palette, RAVE — then python audible_lava.py. First run opens the calibration GUI. Every layer has a command-line switch (--no-governor, --no-melody, --classic-synths, --no-rave, --no-continuity, --no-stable-tracker and others), and every Python module ships with a test suite that needs no camera, server or keyboard window.
Guides & Reference
Build documentation and companions for the major implementation steps, hosted as PDFs.
Lineage & Novelty
Di Scipio's Audible Ecosystemics, Xenakis's stochastic macrostates, Lerdahl and Jackendoff's GTTM and Lerdahl's tonal tension, Temperley's preference rules, Hasty's Meter as Rhythm and London's tactus prior, Cohn and Lewin's Tonnetz, Gjerdingen's schemata, Toussaint's Euclidean rhythms, Huron and Meyer on expectation. GTTM is a theory of listening, not generation; here its structural categories are repurposed as a generative control decomposition, and the lamp's persistent homology supplies the evidence those categories need.
To the best of the author's knowledge, this is the first work to combine: (1) a physical lava lamp as live input; (2) H0 persistent homology as a blob-significance filter; (3) flow-advected mask identity with Wasserstein-inspired topological matching; (4) a physics-informed buoyancy Kalman with directional priors; (5) topological fingerprinting for re-identification; (6) thermodynamic hue as a phase indicator driving musical parameters; (7) a zombie voice pool preserving sonic identity across detection gaps; (8) a bidirectional voice-slot architecture in which blob features and player input share one polysynthesiser; (9) a GTTM-shaped score grammar whose evidence is the merge tree and persistence diagram of the image, with softmax role governance and a learned hazard model of phrase length; and (10) RAVE timbre transfer as a final stage on the governed mix.