← zidingz.com

scenes.py

← Gallery · core.py · scenes.py · render.py · fidelity.py · export_live.py

"""Four scenes. Each is frame = F(analysis, t). Zvon and Disc are pure functions of t;
Sand and Locator carry state (particles, a track) and must be stepped in order."""
import numpy as np
from scipy import ndimage
import core
from core import FPS_A, NKEY

NAMES = "A B♭ B C C♯ D E♭ E F F♯ G G♯".split()


def key_env(A, thr=0.2, span=0.6, gamma=1.2, smooth=1.5, release=0.0, top=0, dyn=0.0):
    """Per-key emission amplitude 0..1: whitened key energy, normalised to the clip's own
    99.5th percentile (so a pianissimo opening still speaks), with an optional exponential
    release so that a struck note radiates a wave train rather than a single thin ring."""
    E = ndimage.gaussian_filter1d(A.Kc, smooth, axis=1)
    a = np.clip((E / (np.percentile(E, 99.5) + 1e-9) - thr) / span, 0, 1) ** gamma
    if top:                                   # keep only the `top` strongest keys per frame
        kth = np.sort(a, axis=0)[-top]
        a = a * (a >= kth)
    if dyn:                                   # follow the recording's real dynamics
        a = a * ((1 - dyn) + dyn * np.clip(A.loud, 0, 1) ** 0.6)
    if release > 0:
        g = np.exp(-1 / (release * FPS_A))
        for i in range(1, a.shape[1]): a[:, i] = np.maximum(a[:, i], a[:, i - 1] * g)
    return a


def vignette(w, h, s=0.55):
    y, x = np.mgrid[0:h, 0:w]
    r2 = ((x - w / 2) / (w / 2)) ** 2 + ((y - h / 2) / (h / 2)) ** 2
    return (1 - s * np.clip(r2 / 2, 0, 1) ** 1.5)[..., None]


# ------------------------------------------------------------------ 1. ZVON
class Zvon:
    """Retarded-time wavefield. 88 fixed emitters (one per key) laid out like a bell tower
    seen from above: angle = position on the circle of fifths, radius = octave.
    Pixel x at time t shows what each emitter was doing at t - |x - x_k| / c_k: the
    doppler-geo `heard()` model run forwards as a picture instead of backwards as a fit.
    Group speed c_k ~ wavelength^0.3 (deep-water-like dispersion): a chord struck together
    reaches the edge of frame bass-first, as an arpeggio."""

    def __init__(s, A, w, h, c0=0.42, seed=0):
        s.A, s.w, s.h = A, w, h
        k = np.arange(NKEY)
        th = 2 * np.pi * ((7 * k) % 12) / 12 - np.pi / 2
        rad = (0.035 + 0.30 * (k / 87.0) ** 0.9) * h
        s.sx = w / 2 + rad * np.cos(th); s.sy = h / 2 + rad * np.sin(th)
        s.lam = 0.20 * h * 2 ** (-k / 21.0)                # px; 108 px (A0) .. 6 px (C8) at 540p
        s.cg = c0 * h * (s.lam / s.lam[0]) ** 0.3           # px / s
        s.nu = np.minimum(s.cg / s.lam, 2.6)                # visible phase rate, Hz (kept under the frame Nyquist)
        s.env = key_env(A, thr=0.3, release=0.35, top=7, dyn=0.75)
        y, x = np.mgrid[0:h, 0:w].astype(np.float32)
        s.r = np.empty((NKEY, h, w), np.float32)
        for i in range(NKEY): s.r[i] = np.hypot(x - np.float32(s.sx[i]), y - np.float32(s.sy[i]))
        s.rmax = float(s.r.max())
        s.vig = vignette(w, h)

    def field(s, t):
        u = np.zeros((s.h, s.w), np.float32); e = np.zeros_like(u)
        for k in range(NKEY):
            i1 = int(min(t * FPS_A, s.A.T - 1)); i0 = int(max((t - s.rmax / s.cg[k]) * FPS_A, 0))
            if i1 <= i0 or s.env[k, i0:i1 + 1].max() < 0.03: continue
            tau = (t - s.r[k] / s.cg[k]) * FPS_A
            a = np.where(tau >= 0, s.env[k][np.clip(tau, 0, s.A.T - 1).astype(np.int32)], 0)
            a = a * (1.0 / np.sqrt(1 + s.r[k] / (0.08 * s.h)))
            u += a * np.cos(2 * np.pi * (s.r[k] / s.lam[k] - s.nu[k] * t))
            e += a
        return u, e

    def frame(s, t):
        u, e = s.field(t)
        img = core.signed(np.tanh(1.15 * u)) * (0.35 + 0.65 * np.tanh(2.5 * e))[..., None]
        return img * s.vig


# ------------------------------------------------------------------ 2. SAND
class Sand:
    """Chladni plate. Each sounding key drives the plate mode whose eigenfrequency
    (~ m^2 + n^2 for a thin plate) matches its pitch; grains random-walk in proportion to
    the local vibration |u| and so collect on the nodal lines, where the plate is still."""

    def __init__(s, A, w, h, n=220000, seed=1):
        s.A, s.w, s.h = A, w, h
        s.rng = np.random.default_rng(seed)
        s.p = s.rng.uniform(-1, 1, (n, 2)).astype(np.float32)
        s.env = key_env(A, thr=0.3, smooth=10, top=5)
        pairs = [(m, n_) for m in range(1, 26) for n_ in range(0, m)]
        ev = np.array([m * m + n_ * n_ for m, n_ in pairs], float)
        s.modes = []
        for k in range(NKEY):
            target = 2.0 * 2 ** (k / 12.0 * 0.62)           # compressed: 7 octaves of pitch -> 4.5 octaves of plate
            j = np.argsort(np.abs(np.log(ev / target)))[:3]
            m, n_ = pairs[j[k % 3 % len(j)]]
            s.modes.append((m, n_, 1 if (k % 12) in (0, 2, 3, 5, 7, 8, 10) else -1))
        s.side = int(h * 0.94)
        s.buf = np.zeros((s.side, s.side), np.float32)
        s.vig = vignette(w, h, 0.4)

    def u(s, t, p):
        a = s.A.at(s.env, t); top = np.argsort(a)[::-1][:7]
        x, y = (p[:, 0] + 1) * (np.pi / 2), (p[:, 1] + 1) * (np.pi / 2)
        out = np.zeros(len(p), np.float32); tot = 1e-6
        for k in top:
            if a[k] < 0.02: continue
            m, n_, sg = s.modes[k]
            out += a[k] * (np.cos(m * x) * np.cos(n_ * y) + sg * np.cos(n_ * x) * np.cos(m * y)); tot += a[k]
        return out / max(tot, 0.35), tot

    def frame(s, t, sub=8):
        strike = float(s.A.at(s.A.flux, t))
        for _ in range(sub):
            u, tot = s.u(t, s.p)
            step = (0.0012 + 0.05 * np.abs(u) * min(tot, 1.5) + 0.012 * max(strike - 0.6, 0))[:, None]
            s.p += step * s.rng.standard_normal(s.p.shape).astype(np.float32)
            s.p = np.abs(s.p + 1) - 1; s.p = 1 - np.abs(1 - s.p)     # reflect at the plate edge
        H, _, _ = np.histogram2d(s.p[:, 1], s.p[:, 0], bins=s.side, range=[[-1, 1], [-1, 1]])
        s.buf = 0.5 * s.buf + 0.5 * ndimage.gaussian_filter(H.astype(np.float32), 0.6)
        dens = s.buf / (len(s.p) / s.side ** 2)
        img = np.zeros((s.h, s.w, 3)); img[:] = (6, 7, 12)
        x0, y0 = (s.w - s.side) // 2, (s.h - s.side) // 2
        img[y0:y0 + s.side, x0:x0 + s.side] = core.GOLD(1 - np.exp(-0.42 * dens))
        return img * s.vig


# ------------------------------------------------------------------ 3. LOCATOR
class Locator:
    """Left: whitened log-frequency spectrogram with the Viterbi ridge (dg.ridge) in cyan,
    the same picture as doppler-geo/figures/map_E1.png. Right: the harmony 'geolocated'
    on Euler's Tonnetz. Every lattice node glows with its pitch class's energy; because the
    lattice is a torus unrolled, the true position repeats as aliases (the mirrored strips
    of the Doppler map), and a tracker with a continuity prior picks one and follows it."""
    E1 = np.array([1.0, 0.0]); E2 = np.array([0.5, -np.sqrt(3) / 2])     # +fifth, +major third

    def __init__(s, A, w, h, t0=0.0):
        from PIL import ImageFont
        s.A, s.w, s.h = A, w, h
        s.lw = int(w * 0.44); s.rw = w - s.lw
        s.cell = h / 5.2
        s.pos = np.array([0.0, 0.0]); s.cam = s.pos.copy(); s.trail = []
        s.ridge, _ = core.ridge(A.W, 36 * core.BPS, 75 * core.BPS, max_jump=4, jump_cost=1.2)
        s.ridge_s = ndimage.gaussian_filter1d(s.ridge.astype(float), 2)
        # triads: (root pc, quality) -> lattice offsets of the three nodes (in i,j) and centroid
        s.tri = {}
        for r in range(12):
            s.tri[(r, "M")] = [(0, 0), (1, 0), (0, 1)]       # root, fifth, major third
            s.tri[(r, "m")] = [(0, 0), (1, 0), (1, -1)]      # root, fifth, minor third (= fifth - major third)
        s.font = ImageFont.load_default()
        cands = ["/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", "/System/Library/Fonts/Supplemental/Arial Unicode.ttf"]
        try:
            import matplotlib; cands.insert(0, matplotlib.get_data_path() + "/fonts/ttf/DejaVuSans.ttf")
        except Exception: pass
        for f in cands:
            try: s.font = ImageFont.truetype(f, max(11, int(h / 42))); break
            except Exception: pass
        # start on D (pc 5 with A=0): find i,j with 7i+4j = 5 mod 12 -> i=-1? solve by search near origin
        s.pos = s._nearest_nodes(5, np.zeros(2))[0].astype(float)
        s.cam = s.pos @ np.stack([s.E1, s.E2])

    @staticmethod
    def pc(i, j): return (7 * i + 4 * j) % 12

    def _nearest_nodes(s, pc, ij, R=4):
        i0, j0 = np.round(ij).astype(int)
        c = [(i, j) for i in range(i0 - R, i0 + R + 1) for j in range(j0 - R, j0 + R + 1) if s.pc(i, j) == pc]
        c.sort(key=lambda q: np.hypot(*((np.array(q) - ij) @ np.stack([s.E1, s.E2]))))
        return np.array(c)

    def step(s, t):
        ch = s.A.at(s.A.chroma_h, t)
        B = np.stack([s.E1, s.E2]); best = None
        for (r, q), offs in s.tri.items():
            a3 = ch[r], ch[(r + 7) % 12], ch[(r + (4 if q == "M" else 3)) % 12]
            score = 2.2 * (a3[0] * a3[1] * a3[2] + 1e-6) ** (1 / 3) + 0.5 * a3[0]      # all three notes must be present; root breaks ties
            for base in s._nearest_nodes(r, s.pos, R=3)[:3]:
                cen = base + np.mean(offs, axis=0)
                d = np.hypot(*((cen - s.pos) @ B))
                v = score - 0.10 * d
                if best is None or v > best[0]: best = (v, cen, (r, q))
        s.vel = 0.80 * getattr(s, 'vel', 0) + 0.012 * (best[1] - s.pos); s.pos += s.vel      # damped spring: a vehicle, not a cursor
        xy = s.pos @ B
        s.cam += 0.03 * (xy - s.cam)
        s.trail.append(xy.copy()); s.label = best[2]
        return ch

    def frame(s, t):
        from PIL import Image, ImageDraw
        ch = s.step(t)
        img = np.zeros((s.h, s.w, 3)); img[:] = (6, 7, 12)
        # --- left: spectrogram window, 12 s, 'now' at 70 %
        span = 12.0; tt = t - 0.94 * span + span * np.arange(s.lw) / s.lw
        ii = np.clip((tt * FPS_A).astype(int), 0, s.A.T - 1)
        f0, f1 = 24 * core.BPS, 84 * core.BPS
        rows = np.linspace(f1 - 1, f0, s.h).astype(int)
        S = s.A.W[rows][:, ii] * ((tt >= 0) & (tt <= t))[None, :]
        img[:, :s.lw] = core.MAGMA(S / 3.6)
        pil = Image.fromarray(img.astype(np.uint8)); d = ImageDraw.Draw(pil, "RGBA")
        past = np.nonzero((tt >= 0) & (tt <= t))[0]
        if len(past) > 2:
            ys = (f1 - 1 - s.ridge_s[ii[past]]) / (f1 - f0) * s.h
            d.line(list(zip(past.tolist(), ys.tolist())), fill=(90, 230, 240, 200), width=2)
        d.line([(s.lw, 0), (s.lw, s.h)], fill=(40, 44, 60, 255), width=1)
        img = np.asarray(pil).astype(float)
        # --- right: Tonnetz heat
        y, x = np.mgrid[0:s.h, 0:s.rw].astype(float)
        X = (x - s.rw / 2) / s.cell + s.cam[0]; Y = -(y - s.h / 2) / s.cell + s.cam[1]
        Binv = np.linalg.inv(np.stack([s.E1, s.E2]))
        I = X * Binv[0, 0] + Y * Binv[1, 0]; J = X * Binv[0, 1] + Y * Binv[1, 1]
        heat = np.zeros_like(X)
        for di in (0, 1):
            for dj in (0, 1):
                i = np.floor(I) + di; j = np.floor(J) + dj
                px = i * s.E1[0] + j * s.E2[0]; py = i * s.E1[1] + j * s.E2[1]
                d2 = (X - px) ** 2 + (Y - py) ** 2
                heat += ch[((7 * i + 4 * j) % 12).astype(int)] ** 2.6 * np.exp(-d2 / (2 * 0.25 ** 2))
        img[:, s.lw:] = core.GOLD(0.04 + 0.80 * heat)
        pil = Image.fromarray(np.clip(img, 0, 255).astype(np.uint8)); d = ImageDraw.Draw(pil, "RGBA")
        def to_px(xy): return (s.lw + s.rw / 2 + (xy[0] - s.cam[0]) * s.cell, s.h / 2 - (xy[1] - s.cam[1]) * s.cell)
        ic, jc = np.round(s.cam @ Binv).astype(int)
        for i in range(ic - 6, ic + 7):
            for j in range(jc - 6, jc + 7):
                p = to_px(i * s.E1 + j * s.E2)
                if p[0] < s.lw + 8 or p[0] > s.w - 8: continue
                c = ch[s.pc(i, j)]
                d.text(p, NAMES[s.pc(i, j)], font=s.font, fill=(20, 10, 8, 255) if c > 0.8 else (235, 225, 205, int(70 + 300 * c)), anchor="mm")
        tr = s.trail[-1500:]
        if len(tr) > 2:
            pts = [to_px(q) for q in tr]
            pts = [(max(px, s.lw + 1), py) for px, py in pts]
            n = len(pts)
            for a0 in range(0, n - 1, 20):
                seg = pts[a0:a0 + 21]
                d.line(seg, fill=(90, 230, 240, int(40 + 180 * (a0 / n) ** 2)), width=2)
            px, py = pts[-1]; d.ellipse([px - 5, py - 5, px + 5, py + 5], outline=(90, 230, 240, 255), width=2)
        r, q = s.label
        d.text((s.w - 14, s.h - 14), f"fix: {NAMES[r]} {'major' if q == 'M' else 'minor'}", font=s.font, fill=(90, 230, 240, 230), anchor="rs")
        d.text((12, s.h - 14), "whitened log-f spectrogram · Viterbi ridge", font=s.font, fill=(235, 225, 205, 150), anchor="ls")
        d.text((s.lw + 12, s.h - 14), "Tonnetz (5ths → , maj 3rds ↗)", font=s.font, fill=(235, 225, 205, 150), anchor="ls")
        return np.asarray(pil).astype(float)


# ------------------------------------------------------------------ 4. DISC
class Disc:
    """Spiral spectrogram: one turn per octave, so angle = pitch class and every octave of a
    note lies on one spoke. In log-frequency a harmonic series is a fixed template (the
    property dg.to_logf uses to make Doppler templates translation-invariant), so each note
    appears as the same small constellation: partials 1,2,4 on its spoke, 3 a fifth round
    (210.6 deg), 5 at 115.9 deg, 7 at 290.6 deg. Stiff piano strings run sharp
    (f_n = n f0 sqrt(1 + B n^2)), which shows as the outer partials curling ahead of the spoke.
    A slow afterglow keeps the last few seconds; the format is a 78 rpm side."""

    def __init__(s, A, w, h, bps=12):
        s.A, s.w, s.h = A, w, h; s.bps = bps
        fc, L = core.logspec(A.x, bps=bps); s.W = core.whiten(L, fmed=8 * bps + 1); s.T = s.W.shape[1]
        nb = s.W.shape[0]; noct = nb / (12 * bps)
        y, x = np.mgrid[0:h, 0:w].astype(float)
        dx, dy = x - w / 2, y - h / 2
        r = np.hypot(dx, dy); th = (np.arctan2(dx, -dy) / (2 * np.pi)) % 1.0     # 0 at top, clockwise; A at top
        r0, r1 = 0.10 * h, 0.485 * h; dr = (r1 - r0) / noct
        pos = (r - r0) / dr
        octv = np.round(pos - th)
        off = pos - th - octv
        b = (octv + th) * 12 * bps
        s.valid = (b >= 0) & (b < nb - 1)
        s.idx = np.clip(b, 0, nb - 1).astype(np.int32)
        s.wt = np.exp(-(off / 0.27) ** 2) * s.valid
        s.groove = 0.035 * (0.5 + 0.5 * np.cos(2 * np.pi * off)) * s.valid
        s.label = ((r > 0.035 * h) & (r < 0.085 * h))
        s.glow = np.zeros((h, w), np.float32); s.acc = np.zeros((h, w), np.float32)
        s.spoke = 0.03 * (np.abs(((th * 12 + 0.5) % 1) - 0.5) < 0.012) * s.valid
        s.vig = vignette(w, h, 0.5)

    def frame(s, t):
        i = min(int(t * FPS_A), s.T - 1)
        col = s.W[:, max(i - 1, 0):i + 1].mean(1)
        now = np.clip(col[s.idx] / 2.2, 0, 1.3) ** 1.3 * s.wt
        s.glow = np.maximum(now, s.glow * 0.94)
        s.acc += now / (FPS_A * 6)                  # the side is cut as it plays: a slow engraving of everything heard so far
        v = np.clip(0.9 * s.glow + 0.6 * ndimage.gaussian_filter(s.glow, s.h / 120) + 0.33 * np.tanh(s.acc) + s.groove + s.spoke, 0, 1)
        img = core.GOLD(v)
        img[s.label] = img[s.label] * 0.3 + np.array([70, 20, 26]) * 0.7
        return img * s.vig


SCENES = {"zvon": Zvon, "sand": Sand, "locator": Locator, "disc": Disc}