Skip to content

Scientific gallery

Sixteen visual-debugging tools for real engineering problems, each one file under demo/gallery/, synthetic data only (numpy), runnable as a script (python demo/gallery/camera_isp.py opens the GUI). They were written as a newcomer would, from the agent skill alone, to find the rough edges of the library: eight in a first round, eight more (g2_*.py, second round) once those were fixed.

The images are snapshots (pipe.snapshot / pipe.sweep), regenerated by python scripts/make_gallery.py.

Camera ISP

Check every stage of a raw-to-RGB chain against the ground truth: a diverging error map with a colorbar shows where demosaicking and white balance go wrong, the PSNR sums it up.

Camera ISP

demo/gallery/camera_isp.py
"""Camera ISP: Bayer mosaic -> demosaic -> white balance -> gamma, checked against the ground truth.

What to look at: the error map (red = too bright, blue = too dark) lights up on edges and on the
fine stripes with nearest-neighbour demosaicking (zipper / colour aliasing) and turns uniformly
red or blue when the white balance gains are wrong. The PSNR in its title sums it up.
"""

from typing import Annotated, Literal

import numpy as np

from interactive_pipe import Image, interactive, interactive_pipeline, layout

SENSOR_GAINS = np.array([0.55, 1.0, 0.7])  # the sensor sees a greenish scene: WB must undo this


def make_scene(h=192, w=256):
    """Ground truth sRGB image: a hue ramp, a zone plate (fine detail) and a few flat patches."""
    y, x = np.mgrid[0:h, 0:w] / max(h, w)
    hue = np.stack([np.sin(6 * x + k * 2.1) * 0.4 + 0.5 for k in range(3)], axis=-1)
    zone = 0.5 + 0.45 * np.cos(250 * ((x - 0.75) ** 2 + (y - 0.25) ** 2))
    img = hue * (0.6 + 0.4 * zone[..., None])
    img[h // 2 :, : w // 3] = [0.8, 0.3, 0.2]
    img[h // 2 :, w // 3 : 2 * w // 3] = [0.5, 0.5, 0.5]
    return np.clip(img, 0, 1)


def conv3(img, k):
    """3x3 correlation with reflect padding (numpy only)."""
    p = np.pad(img, 1, mode="reflect")
    return sum(k[i, j] * p[i : i + img.shape[0], j : j + img.shape[1]] for i in range(3) for j in range(3))


@interactive
def mosaic(gt, noise: Annotated[float, (0.0, 0.05), "Sensor noise"] = 0.01):
    """Linearise, apply the sensor colour response, sample an RGGB Bayer pattern, add noise."""
    linear = gt**2.2 * SENSOR_GAINS
    raw = np.zeros(gt.shape[:2])
    raw[0::2, 0::2], raw[0::2, 1::2] = linear[0::2, 0::2, 0], linear[0::2, 1::2, 1]
    raw[1::2, 0::2], raw[1::2, 1::2] = linear[1::2, 0::2, 1], linear[1::2, 1::2, 2]
    return np.clip(raw + noise * np.random.default_rng(0).standard_normal(raw.shape), 0, 1)


@interactive
def demosaic(raw, method: Literal["bilinear", "nearest"] = "bilinear"):
    masks = np.zeros(raw.shape + (3,))
    masks[0::2, 0::2, 0] = masks[1::2, 1::2, 2] = 1
    masks[0::2, 1::2, 1] = masks[1::2, 0::2, 1] = 1
    if method == "nearest":
        k = np.array([[0, 0, 0], [0, 1, 1], [0, 1, 1]], float)
    else:
        k = np.array([[1, 2, 1], [2, 4, 2], [1, 2, 1]], float)
    return np.stack([conv3(raw * masks[..., c], k) / conv3(masks[..., c], k) for c in range(3)], axis=-1)


@interactive
def white_balance(
    rgb, red: Annotated[float, (0.5, 3.0), "Red gain"] = 1.8, blue: Annotated[float, (0.5, 3.0), "Blue gain"] = 1.4
):
    return np.clip(rgb * np.array([red, 1.0, blue]), 0, 1)


@interactive
def gamma(rgb, gamma: Annotated[float, (1.0, 3.0), "Gamma"] = 2.2):
    return rgb ** (1 / gamma)


@interactive
def compare(out, gt):
    layout.style("error", colormap="RdBu_r", center=0, colorbar=True, vmin=-0.3, vmax=0.3)
    psnr = 10 * np.log10(1 / np.mean((out - gt) ** 2))
    return Image((out - gt).mean(axis=-1), title=f"error, PSNR {psnr:.2f} dB")


@interactive_pipeline(gui="auto")
def camera_isp(gt):
    raw = mosaic(gt)
    rgb = demosaic(raw)
    balanced = white_balance(rgb)
    out = gamma(balanced)
    error = compare(out, gt)
    return [[out, gt], [raw, error]]


if __name__ == "__main__":
    camera_isp(make_scene())

Frequency-domain filtering

Place a band-pass mask (one range slider for both radii) on the log-spectrum and see what each band of frequencies contributes to the image; a matplotlib figure gives the radial power profile.

Frequency-domain filtering

demo/gallery/frequency_filtering.py
"""Frequency-domain filtering: a band-pass mask between two radii, applied to the image spectrum.

What to look at: the log-spectrum shows the periodic stripe pattern as two bright peaks; move the
band so that it keeps them (the filtered image becomes the stripes alone) or excludes them (the
stripes vanish). The radial power profile shows where the band sits in the spectrum, and the
ringing that a hard mask edge produces as you lower the softness.
"""

import numpy as np
from matplotlib.figure import Figure

from interactive_pipe import RangeControl, interactive, interactive_pipeline, layout


def make_image(n=256):
    """Gray scene: smooth blobs + a periodic stripe pattern + white noise."""
    y, x = np.mgrid[0:n, 0:n] / n
    blobs = np.exp(-((x - 0.3) ** 2 + (y - 0.4) ** 2) / 0.02) + 0.6 * np.exp(-((x - 0.7) ** 2 + (y - 0.7) ** 2) / 0.01)
    stripes = 0.15 * np.sin(2 * np.pi * (40 * x + 25 * y))
    noise = 0.05 * np.random.default_rng(0).standard_normal((n, n))
    return np.clip(0.2 + 0.6 * blobs + stripes + noise, 0, 1)


def radius(shape):
    """Normalised frequency radius of every FFT bin (0 at DC, 0.5 at Nyquist along an axis)."""
    fy, fx = np.meshgrid(
        np.fft.fftshift(np.fft.fftfreq(shape[0])), np.fft.fftshift(np.fft.fftfreq(shape[1])), indexing="ij"
    )
    return np.hypot(fx, fy)


@interactive()
def spectrum(img):
    layout.style("log_spectrum", title="spectrum", colormap="magma", vmin=1.0, colorbar="log10 |FFT|")
    f = np.fft.fftshift(np.fft.fft2(img))
    return f, np.log10(np.abs(f) + 1e-6)


BAND = RangeControl((0.1, 0.3), [0.0, 0.71], name="band (cycles/px)")  # one slider, used by two filters


@interactive(band=BAND, softness=(0.01, [0.0, 0.05]))
def band_pass(f, band=(0.1, 0.3), softness=0.01):
    r, s = radius(f.shape), max(softness, 1e-4)
    mask = 1 / (1 + np.exp(-(r - band[0]) / s)) / (1 + np.exp((r - band[1]) / s))
    return f * mask, mask


@interactive()
def inverse(f):
    out = np.real(np.fft.ifft2(np.fft.ifftshift(f)))
    return (out - out.min()) / (np.ptp(out) + 1e-12)


@interactive(band=BAND)
def radial_profile(f, band=(0.1, 0.3)):
    idx = np.round(radius(f.shape) * 100).astype(int).ravel()  # 0.01 cycle/px bins
    power = np.bincount(idx, np.abs(f.ravel()) ** 2) / np.maximum(np.bincount(idx), 1)
    fig = Figure(figsize=(5, 3.5), layout="tight")
    ax = fig.subplots()
    ax.semilogy(np.arange(power.size) / 100, power)
    ax.axvspan(*band, color="tab:orange", alpha=0.25, label="band")
    ax.set(xlabel="radius (cycles / pixel)", ylabel="mean power")
    ax.legend()
    return fig


@interactive_pipeline(gui="auto")
def frequency_filtering(img):
    f, log_spectrum = spectrum(img)
    filtered_f, mask = band_pass(f)
    filtered = inverse(filtered_f)
    profile = radial_profile(f)
    return [[img, log_spectrum, mask], [filtered, profile]]


if __name__ == "__main__":
    frequency_filtering(make_image())

1D signal filtering

Compare a windowed-sinc FIR and a Butterworth IIR low-pass on a noisy chirp: time is frequency, so the filtered curve fades out at the cutoff; the Bode plot shows magnitude and phase on twin axes.

1D signal filtering

demo/gallery/signal_filtering.py
"""1D signal processing: low-pass filtering a noisy chirp with an FIR or an IIR filter.

What to look at: the chirp sweeps from 2 Hz to 60 Hz, so time is frequency here: the filtered
signal fades out where the chirp crosses the cutoff. Compare the FIR (linear phase: a constant delay
of (taps-1)/2 samples, a phase linear in frequency) with the Butterworth IIR (a sharp roll-off from a few
coefficients, but a curved phase, so a frequency-dependent delay). The Bode plot shows magnitude and phase on twin axes.
"""

import numpy as np
from matplotlib.figure import Figure

from interactive_pipe import Control, Curve, SingleCurve, interactive, interactive_pipeline

FS = 500.0  # sampling rate, Hz
CUTOFF = Control(25.0, [2.0, 100.0], name="cutoff (Hz)")  # one slider for design and bode


@interactive(noise=(0.3, [0.0, 1.0]))
def chirp(noise=0.3):
    t = np.arange(0, 4.0, 1 / FS)
    clean = np.sin(2 * np.pi * (2 * t + 29 / 4 * t**2))  # 2 Hz -> 60 Hz in 4 s
    noisy = clean + noise * np.random.default_rng(0).standard_normal(t.size)
    return t, noisy, clean


@interactive(
    kind=("FIR", ["FIR", "IIR"]),
    cutoff=CUTOFF,
    taps=(41, [3, 201], "FIR taps"),
    iir_order=(4, [1, 8], "IIR order"),
)
def design(kind="FIR", cutoff=25.0, taps=41, iir_order=4):
    """Return (b, a): a Hamming windowed-sinc FIR, or a Butterworth IIR (bilinear transform)."""
    if kind == "FIR":
        n = np.arange(taps) - (taps - 1) / 2
        b = np.sinc(2 * cutoff / FS * n) * np.hamming(taps)
        return b / b.sum(), np.array([1.0])
    k = np.arange(1, iir_order + 1)
    poles = 2 * FS * np.tan(np.pi * cutoff / FS) * np.exp(1j * np.pi * (2 * k + iir_order - 1) / (2 * iir_order))
    a = np.real(np.poly((1 + poles / (2 * FS)) / (1 - poles / (2 * FS))))
    b = np.poly(-np.ones(iir_order))
    return b * a.sum() / b.sum(), a


@interactive()
def apply_filter(x, b, a):
    """Direct-form difference equation (numpy only, no scipy)."""
    fir = np.convolve(x, b)[: x.size]
    y = np.zeros(a.size - 1 + x.size)  # leading zeros: past outputs before t=0
    for n in range(x.size):
        y[n + a.size - 1] = fir[n] - np.dot(a[:0:-1], y[n : n + a.size - 1])
    return y[a.size - 1 :]


@interactive()
def plot_signals(t, noisy, filtered, clean):
    return Curve(
        [
            SingleCurve(t, noisy, style="c-", label="noisy", linewidth=1, alpha=0.4),
            SingleCurve(t, clean, style="k-", label="clean", linewidth=1),
            SingleCurve(t, filtered, style="r-", label="filtered", linewidth=2),
        ],
        xlabel="time (s)  ~  chirp frequency 2 Hz -> 60 Hz",
        ylim=(-2.5, 2.5),
        grid=True,
    )


@interactive(cutoff=CUTOFF)
def bode(b, a, cutoff=25.0):
    n = 4096
    f = np.fft.rfftfreq(n, 1 / FS)
    h = np.fft.rfft(b, n) / np.fft.rfft(a, n)
    fig = Figure(figsize=(5, 3.5))
    ax = fig.subplots()
    ax.semilogx(f[1:], 20 * np.log10(np.abs(h[1:]) + 1e-12), "b")
    ax.set(xlabel="frequency (Hz)", ylabel="magnitude (dB)", ylim=(-80, 5))
    ax.grid(True, which="both", alpha=0.3)
    ax.axvline(cutoff, color="gray", linestyle=":")
    twin = ax.twinx()
    twin.semilogx(f[1:], np.degrees(np.unwrap(np.angle(h[1:]))), "r")
    twin.set_ylabel("phase (deg)", color="r")
    fig.tight_layout()
    return fig


@interactive_pipeline(gui="auto")
def signal_filtering():
    t, noisy, clean = chirp()
    b, a = design()
    filtered = apply_filter(noisy, b, a)
    signals = plot_signals(t, noisy, filtered, clean)
    response = bode(b, a)
    return signals, response


if __name__ == "__main__":
    signal_filtering()

Detection overlay

Tune a threshold + connected-components detector: boxes drawn with interactive_pipe.draw (green true positives, red false positives, yellow misses), a table of detections and precision / recall.

Detection overlay

The sweep chose the defaults: a low threshold needs a minimal area to reject noise specks.

Detection overlay: sweep

demo/gallery/blob_detection.py
"""Detection overlay: threshold + connected components on noisy blobs, scored against the ground truth.

What to look at: green boxes are true positives, red boxes false positives (noise specks, merged
blobs), yellow circles are missed blobs. Lower the threshold and the faint blobs appear but so does
noise; raise the minimal area to remove the specks. Precision / recall (in the title) sum it up; the
table lists every detection with its area and peak intensity.
"""

from typing import Annotated

import numpy as np

from interactive_pipe import Image, Table, draw, interactive, interactive_pipeline

RNG = np.random.default_rng(3)
CENTERS = RNG.uniform(16, 240, size=(14, 2))  # ground-truth blob centres (x, y)
AMPLITUDES = RNG.uniform(0.15, 0.8, size=14)


def make_image(n=256):
    y, x = np.mgrid[0:n, 0:n]
    img = sum(a * np.exp(-((x - cx) ** 2 + (y - cy) ** 2) / 80) for (cx, cy), a in zip(CENTERS, AMPLITUDES))
    return np.clip(0.1 + img + 0.06 * RNG.standard_normal((n, n)), 0, 1)


def label(mask):
    """4-connected components (numpy + a Python flood fill, no scipy): list of (ys, xs) per component."""
    seen, comps = np.zeros_like(mask), []
    for start in zip(*np.nonzero(mask)):
        if seen[start]:
            continue
        stack, pix = [start], []
        seen[start] = True
        while stack:
            y, x = stack.pop()
            pix.append((y, x))
            for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
                if 0 <= ny < mask.shape[0] and 0 <= nx < mask.shape[1] and mask[ny, nx] and not seen[ny, nx]:
                    seen[ny, nx] = True
                    stack.append((ny, nx))
        comps.append(tuple(np.array(pix).T))
    return comps


@interactive
def detect(
    img,
    threshold: Annotated[float, (0.0, 1.0), "Threshold"] = 0.25,
    min_area: Annotated[int, (1, 100), "Min area (px)"] = 20,
):
    comps = [c for c in label(img > threshold) if len(c[0]) >= min_area]
    boxes = np.array([(xs.min(), ys.min(), xs.max(), ys.max()) for ys, xs in comps]).reshape(-1, 4)
    return dict(box=boxes, area=[len(ys) for ys, _ in comps], peak=[img[c].max() for c in comps])


@interactive
def score(img, det, max_dist: Annotated[float, (1.0, 15.0), "Match radius (px)"] = 6.0):
    centers = (det["box"][:, :2] + det["box"][:, 2:]) / 2
    dist = np.linalg.norm(centers[:, None] - CENTERS[None], axis=-1)  # detections x ground truth
    tp = dist.min(axis=1, initial=np.inf) < max_dist
    found = dist.min(axis=0, initial=np.inf) < max_dist
    overlay = draw.boxes(img, det["box"], labels=range(len(tp)), color=["lime" if t else "red" for t in tp])
    overlay = draw.points(overlay, CENTERS[~found], color="yellow", radius=6, filled=False)
    title = f"precision {tp.mean() if len(tp) else 0:.2f}, recall {found.mean():.2f}"
    columns = dict(
        id=np.arange(len(tp)), x=det["box"][:, 0], y=det["box"][:, 1], area=det["area"], peak=det["peak"], match=tp
    )
    return Image(overlay, title=title), Table(columns)


@interactive_pipeline(gui="auto")
def blob_detection(img):
    detections = detect(img)
    overlay, table = score(img, detections)
    return img, overlay, table


if __name__ == "__main__":
    blob_detection(make_image())

Optimisation trace

Watch gradient descent, momentum, Nesterov and Adam cross the Rosenbrock valley: contour figure with the trajectory, loss curve, a Literal dropdown for the optimiser and a log-scale learning-rate slider.

Optimisation trace

One sweep over the dropdown compares the four optimisers at the same learning rate.

Optimisation trace: sweep

demo/gallery/optimizer_trace.py
"""Optimisation trace: gradient descent variants on the Rosenbrock valley.

What to look at: plain gradient descent zig-zags across the narrow curved valley and crawls along
its floor; momentum and Nesterov overshoot then accelerate along it; Adam normalises the step per
axis. Raise the learning rate until the trajectory diverges (the loss curve shoots up), and compare
how many steps each method needs to reach the minimum at (1, 1).
"""

from typing import Annotated, Literal

import numpy as np
from matplotlib.figure import Figure

from interactive_pipe import Curve, interactive, interactive_pipeline

X, Y = np.meshgrid(np.linspace(-2, 2, 200), np.linspace(-1, 3, 200))


def loss(p):
    return (1 - p[..., 0]) ** 2 + 10 * (p[..., 1] - p[..., 0] ** 2) ** 2


def grad(p):
    x, y = p
    return np.array([-2 * (1 - x) - 40 * x * (y - x**2), 20 * (y - x**2)])


@interactive
def optimize(
    optimizer: Literal["gd", "momentum", "nesterov", "adam"] = "momentum",
    lr: Annotated[float, (1e-4, 0.3, "log"), "learning rate"] = 0.01,
    momentum: Annotated[float, (0.0, 0.99), "Momentum / beta1"] = 0.9,
    steps: Annotated[int, (1, 500), "Steps"] = 150,
):
    p, v, s = np.array([-1.5, 2.5]), np.zeros(2), np.zeros(2)
    path = [p]
    for k in range(1, steps + 1):
        if optimizer == "gd":
            p = p - lr * grad(p)
        elif optimizer in ("momentum", "nesterov"):
            g = grad(p - lr * momentum * v) if optimizer == "nesterov" else grad(p)
            v = momentum * v + g
            p = p - lr * v
        else:  # adam
            g = grad(p)
            v, s = momentum * v + (1 - momentum) * g, 0.999 * s + 0.001 * g**2
            p = p - 10 * lr * (v / (1 - momentum**k)) / (np.sqrt(s / (1 - 0.999**k)) + 1e-8)
        if np.abs(p).max() > 1e3:  # diverged: stop before overflowing
            break
        path.append(p)
    return np.array(path)


@interactive()
def contour(path):
    fig = Figure()
    ax = fig.subplots()
    ax.contour(X, Y, np.log10(loss(np.stack([X, Y], axis=-1)) + 1e-3), levels=20, cmap="viridis")
    ax.plot(path[:, 0], path[:, 1], "r.-", markersize=3, linewidth=1)
    ax.plot(1, 1, "k*", markersize=12)
    ax.set(xlim=(-2, 2), ylim=(-1, 3), xlabel="x", ylabel="y", title=f"end at ({path[-1, 0]:.2f}, {path[-1, 1]:.2f})")
    return fig


@interactive()
def loss_curve(path):
    return Curve([[np.arange(len(path)), np.log10(loss(path) + 1e-12), "b-", "log10 loss"]], xlabel="step", grid=True)


@interactive_pipeline(gui="auto")
def optimizer_trace():
    path = optimize()
    trajectory = contour(path)
    losses = loss_curve(path)
    return trajectory, losses


if __name__ == "__main__":
    optimizer_trace()

Lens calibration

Recover radial distortion coefficients by eye: the corrected checkerboard straightens and the residual vectors (from each true corner) shrink; the RMS is in the cell title.

Lens calibration

demo/gallery/lens_calibration.py
"""Geometry / calibration: undistort a checkerboard seen through a homography and a radial lens distortion.

What to look at: the camera has an unknown radial distortion (k1, k2). Tune the estimated
coefficients until the corrected board has straight lines: the residual vectors (scaled up, drawn
from each true corner position) shrink and the RMS in the title drops. A wrong k1 sign gives
residuals pointing outward / inward that grow with the distance to the image centre.
"""

import numpy as np

from interactive_pipe import Image, draw, interactive, interactive_pipeline

H, W = 240, 320
K_TRUE = (-0.25, 0.08)  # the camera's distortion, to be recovered
HOMOGRAPHY = np.array([[1.1, 0.25, -0.1], [-0.15, 1.0, 0.05], [0.2, 0.15, 1.0]])  # board plane -> normalised image


def distort(u, k, iterations=10):
    """Inverse of undistort (fixed point): undistorted normalised coords -> distorted ones."""
    d = u.copy()
    for _ in range(iterations):
        r2 = (d**2).sum(-1, keepdims=True)
        d = u / (1 + k[0] * r2 + k[1] * r2**2)
    return np.where(np.abs(undistort(d, k) - u).max(-1, keepdims=True) < 1e-3, d, np.nan)  # NaN: not invertible


def undistort(d, k):
    r2 = (d**2).sum(-1, keepdims=True)
    return d * (1 + k[0] * r2 + k[1] * r2**2)


def to_pixels(n):
    return n * W / 2 + np.array([W / 2, H / 2])


def pixel_grid():
    y, x = np.mgrid[0:H, 0:W]
    return (np.stack([x, y], -1) - np.array([W / 2, H / 2])) / (W / 2)


def board(u):
    """Checkerboard seen at undistorted normalised coords u (8x6 squares on the unit plane)."""
    p = np.concatenate([u, np.ones(u.shape[:-1] + (1,))], -1) @ np.linalg.inv(HOMOGRAPHY).T
    bx, by = p[..., 0] / p[..., 2], p[..., 1] / p[..., 2]
    inside = (np.abs(bx) < 0.8) & (np.abs(by) < 0.6)  # NaN coordinates fall outside: gray
    return np.where(inside, ((np.floor(bx * 5) + np.floor(by * 5)) % 2) * 0.8 + 0.1, 0.5)


def true_corners():
    bx, by = np.meshgrid(np.arange(-3, 4) / 5, np.arange(-2, 3) / 5)
    p = np.stack([bx, by, np.ones_like(bx)], -1).reshape(-1, 3) @ HOMOGRAPHY.T
    return p[:, :2] / p[:, 2:]


@interactive()
def capture():
    return board(undistort(pixel_grid(), K_TRUE))


@interactive(k1=(0.0, [-0.5, 0.5]), k2=(0.0, [-0.2, 0.2]), arrow_scale=(3.0, [1.0, 20.0]))
def correct(k1=0.0, k2=0.0, arrow_scale=3.0):
    corrected = board(undistort(distort(pixel_grid(), (k1, k2)), K_TRUE))
    truth = true_corners()
    estimated = undistort(distort(truth, K_TRUE), (k1, k2))  # detected corners, undistorted with (k1, k2)
    start, end = to_pixels(truth), to_pixels(truth + arrow_scale * (estimated - truth))
    rms = np.sqrt(((to_pixels(estimated) - start) ** 2).sum(-1).mean())
    out = draw.lines(corrected, np.stack([start, end], 1), color="red", width=2)
    out = draw.points(out, start, color="lime", radius=2)
    return Image(out, title=f"corrected, residual RMS {rms:.2f} px (x{arrow_scale:g})")


@interactive_pipeline(gui="auto")
def lens_calibration():
    captured = capture()
    corrected = correct()
    return captured, corrected


if __name__ == "__main__":
    lens_calibration()

PID control

Tune a PID on a lightly damped second-order plant: step response and command as curves, open-loop Bode plot with crossover and phase margin; the three gains come from one filter so that both the simulation and the Bode plot use the same sliders.

PID control

The sweep shows what the derivative gain and actuator saturation do to the step response.

PID control: sweep

demo/gallery/pid_control.py
"""Control engineering: PID control of a lightly damped second-order plant.

What to look at: with P only the response settles with a static error and rings; I removes the
error but adds overshoot; D damps the ringing. Watch the command: a large Kd gives a kick at the
step, and the actuator saturation (u_max) slows everything down and causes integral wind-up.
The open-loop Bode plot shows the gain crossover and the phase margin: a small margin = ringing.
"""

from typing import Annotated

import numpy as np
from matplotlib.figure import Figure

from interactive_pipe import Control, Curve, interactive, interactive_pipeline

WN, ZETA = 2 * np.pi * 1.0, 0.15  # plant: natural frequency 1 Hz, damping 0.15
DT, T_END, TAU_D = 1e-3, 6.0, 0.01  # time step, duration, derivative filter time constant (s)
# named controls in an alias: one slider each, shared by simulate() and bode()
Kp = Annotated[float, Control(2.0, [0.0, 10.0], name="Kp")]
Ki = Annotated[float, Control(3.0, [0.0, 20.0], name="Ki")]
Kd = Annotated[float, Control(0.15, [0.0, 1.0], name="Kd")]


@interactive
def simulate(kp: Kp = 2.0, ki: Ki = 3.0, kd: Kd = 0.15, u_max: Annotated[float, (0.5, 20.0), "u_max"] = 20.0):
    t = np.arange(0, T_END, DT)
    ref = (t >= 0.5).astype(float)
    y = dy = integral = d_filt = prev_err = 0.0
    out, cmd = np.zeros_like(t), np.zeros_like(t)
    for i, r in enumerate(ref):
        err = r - y
        d_filt += (DT / TAU_D) * ((err - prev_err) / DT - d_filt)
        u = kp * err + ki * integral + kd * d_filt
        u_sat = np.clip(u, -u_max, u_max)
        integral += err * DT
        prev_err = err
        dy += DT * (WN**2 * (u_sat - y) - 2 * ZETA * WN * dy)
        y += DT * dy
        out[i], cmd[i] = y, u_sat
    response = Curve(
        [[t, ref, "k--", "reference"], [t, out, "b-", "output"]], xlabel="time (s)", ylim=(-0.2, 2.0), grid=True
    )
    command = Curve([[t, cmd, "r-", "command u"]], xlabel="time (s)", grid=True)
    return response, command


@interactive
def bode(kp: Kp = 2.0, ki: Ki = 3.0, kd: Kd = 0.15):
    w = np.logspace(-1, 3, 800)
    s = 1j * w
    loop = (kp + ki / s + kd * s / (1 + TAU_D * s)) * WN**2 / (s**2 + 2 * ZETA * WN * s + WN**2)
    mag, phase = 20 * np.log10(np.abs(loop)), np.degrees(np.unwrap(np.angle(loop)))
    fig = Figure()
    ax_mag, ax_phase = fig.subplots(2, 1, sharex=True)
    ax_mag.semilogx(w / (2 * np.pi), mag)
    ax_mag.axhline(0, color="gray", linewidth=0.8)
    ax_phase.semilogx(w / (2 * np.pi), phase)
    ax_phase.axhline(-180, color="gray", linewidth=0.8)
    cross = np.nonzero(np.diff(np.sign(mag)) < 0)[0]
    if len(cross):
        fc, margin = w[cross[-1]] / (2 * np.pi), 180 + phase[cross[-1]]
        for ax in (ax_mag, ax_phase):
            ax.axvline(fc, color="tab:orange", linestyle=":")
        ax_mag.set_title(f"crossover {fc:.2f} Hz, margin {margin:.0f} deg")
    ax_mag.set_ylabel("gain (dB)")
    ax_phase.set(ylabel="phase (deg)", xlabel="frequency (Hz)")
    return fig


@interactive_pipeline(gui="auto")
def pid_control():
    response, command = simulate()
    open_loop = bode()
    return [[response, open_loop], [command]]


if __name__ == "__main__":
    pid_control()

Stateful simulation (edge case)

A Gray-Scott reaction-diffusion animated by a clock. Pipelines are pure functions of their controls, simulations are not: the state lives in context and each run advances it to the clock (t); snapshots and sweeps start each picture from a fresh context, so they stay reproducible.

Stateful simulation (edge case)

demo/gallery/reaction_diffusion.py
"""Edge case: a stateful simulation (Gray-Scott reaction-diffusion) animated by a clock.

What to look at: spots, stripes or labyrinths grow from a small seed depending on feed / kill.
The state lives in `context` and each run advances it to the clock: `t` seconds = `t * speed` steps
from the seed (moving feed / kill continues the simulation with the new values). Snapshots and sweeps
start each picture from an empty context, so `snapshot(t=4)` is reproducible. A run advances at most
2000 steps (the title shows the step reached), so the GUI stays responsive when the clock jumps.
"""

from typing import Annotated

import numpy as np

from interactive_pipe import TimeControl, context, interactive, interactive_pipeline, layout

N = 128


def seed():
    u, v = np.ones((N, N)), np.zeros((N, N))
    u[N // 2 - 8 : N // 2 + 8, N // 2 - 8 : N // 2 + 8], v[N // 2 - 8 : N // 2 + 8, N // 2 - 8 : N // 2 + 8] = 0.5, 0.25
    v += 0.02 * np.random.default_rng(0).random((N, N))
    return u, v


def laplacian(a):
    return np.roll(a, 1, 0) + np.roll(a, -1, 0) + np.roll(a, 1, 1) + np.roll(a, -1, 1) - 4 * a


@interactive(t=TimeControl(update_interval_ms=50))
def simulate(
    t=0.0,
    feed: Annotated[float, (0.01, 0.08), "feed"] = 0.037,
    kill: Annotated[float, (0.04, 0.07), "kill"] = 0.06,
    speed: Annotated[int, (100, 2000), "steps / second"] = 500,
):
    """Advance the state kept in the context up to the clock."""
    target = int(t * speed)
    state = context.get("sim")
    if state is None or state["step"] > target:  # first run, or the clock went back
        state = dict(step=0, uv=seed())
    u, v = state["uv"]
    for _ in range(min(target - state["step"], 2000)):
        uvv = u * v * v
        u, v = u + 0.16 * laplacian(u) - uvv + feed * (1 - u), v + 0.08 * laplacian(v) + uvv - (feed + kill) * v
        state["step"] += 1
    state["uv"] = u, v
    context["sim"] = state
    layout.style("v", title=f"v at step {state['step']}", colormap="inferno", vmin=0, vmax=0.4, colorbar=True)
    return v


@interactive_pipeline(gui="auto")
def reaction_diffusion():
    v = simulate()
    return v


if __name__ == "__main__":
    reaction_diffusion()

Second round

Eight more examples, written the same way after the first round's fixes.

Stereo block matching

Block matching on a random-dot stereo pair: disparity and diverging error heatmaps with colorbars against the ground truth, a PointControl probe on the left view that plots the matching cost of one pixel.

Stereo block matching

A larger window trades noise for blurred edges (the error concentrates on the depth discontinuities).

Stereo block matching: sweep

demo/gallery/g2_stereo_matching.py
"""Stereo vision: block matching between two views of a synthetic scene.

What to look at: the disparity map recovers the three depth planes (background 4 px, disc 9 px,
square 14 px); the error map (diverging, 0 = white) shows the "fattening" of the foreground at
depth edges, which grows with the window size, and the speckle due to sensor noise, which shrinks
with it. The left strip is seen by the left camera only: no match there.
A search range below 14 px clips the square. Click on the left view: the matching cost of that
pixel against every candidate disparity is plotted; a sharp single minimum = a reliable match.
"""

from typing import Annotated

import numpy as np

from interactive_pipe import Curve, PointControl, draw, interactive, interactive_pipeline, layout, to_pixels

H, W = 120, 160


def make_views(seed=0):
    """Left / right views and the ground-truth disparity of the left view (pixels)."""
    rng = np.random.default_rng(seed)
    texture = rng.random((H, W + 32))
    texture = 0.5 * texture + 0.25 * np.roll(texture, 1, axis=1) + 0.25 * np.roll(texture, 1, axis=0)
    y, x = np.mgrid[:H, :W]
    disparity = np.full((H, W), 4.0)
    disparity[(x - 50) ** 2 + (y - 60) ** 2 < 25**2] = 9.0
    disparity[30:80, 95:145] = 14.0
    left = texture[y, x + 16 - disparity.astype(int)]  # left(x) = right(x - d)
    right = texture[:, 16 : 16 + W]
    noise = 0.15 * rng.standard_normal((2, H, W))  # sensor noise: what a larger window averages out
    return np.clip(left + noise[0], 0, 1), np.clip(right + noise[1], 0, 1), disparity


def box_sum(img, radius):
    """Sum over a (2r+1)^2 window, edges replicated (integral image)."""
    padded = np.pad(img, radius, mode="edge")
    integral = np.pad(padded.cumsum(0).cumsum(1), ((1, 0), (1, 0)))
    k = 2 * radius + 1
    return integral[k:, k:] - integral[:-k, k:] - integral[k:, :-k] + integral[:-k, :-k]


@interactive
def block_match(
    left,
    right,
    window: Annotated[int, (1, 9), "window radius"] = 5,
    max_disparity: Annotated[int, (4, 24), "search range (px)"] = 20,
):
    costs = np.stack([box_sum((left - np.roll(right, d, axis=1)) ** 2, window) for d in range(max_disparity + 1)])
    for name in ("truth", "disparity"):  # truth is an input: styled by name from any filter
        layout.style(name, colormap="viridis", vmin=0, vmax=24, colorbar=True, unit="px")
    return costs.argmin(axis=0).astype(float), costs


@interactive
def disparity_error(disparity, truth):
    error = disparity - truth
    bad = np.mean(np.abs(error) > 1)
    title = f"error: {100 * bad:.1f}% pixels off by > 1 px"
    layout.style("error", title=title, colormap="RdBu_r", vmin=-8, vmax=8, colorbar="disparity error (px)")
    return error


@interactive(probe=PointControl((0.3, 0.5), on="marked"))
def cost_curve(left, costs, probe=(0.3, 0.5)):
    col, row = to_pixels(probe, left)
    curve = costs[:, row, col]
    best = int(curve.argmin())
    title = f"matching cost, minimum at {best} px"
    plot = Curve([[np.arange(len(curve)), curve, "b.-", f"pixel ({col}, {row})"]], xlabel="disparity (px)", title=title)
    return draw.points(left, [(col, row)], color="red"), plot


@interactive_pipeline(gui="auto")
def g2_stereo_matching(left, right, truth):
    disparity, costs = block_match(left, right)
    error = disparity_error(disparity, truth)
    marked, cost = cost_curve(left, costs)
    return [[marked, right, cost], [truth, disparity, error]]


if __name__ == "__main__":
    g2_stereo_matching(*make_views())

Segmentation

Threshold or k-means segmentation of a noisy synthetic scene: draw.mask overlay with the mean IoU in its title, a confusion Table, and a RegionControl on the overlay feeding a histogram figure with the thresholds.

Segmentation

demo/gallery/g2_segmentation.py
"""Segmentation debugging: two thresholds or k-means on a noisy three-region image.

What to look at: without smoothing, noise makes salt-and-pepper labels and the IoU in the overlay
title stays low; a radius of 2 fixes it; more smoothing blurs the edges and, as the ring (0.8) and
background (0.2) blend through the disc level (0.5), every ring edge gets a false "disc" band: the
confusion table shows it as ring / background pixels predicted as disc. Shift-drag a rectangle on
the overlay: the histogram of the region and the two thresholds are drawn; a region across a
boundary shows two modes, the thresholds belong in the valley between them. K-means finds the valley without being told.
"""

from typing import Annotated, Literal

import numpy as np
from matplotlib.figure import Figure

from interactive_pipe import (
    RangeControl,
    RegionControl,
    Table,
    context,
    draw,
    interactive,
    interactive_pipeline,
    layout,
    to_pixels,
)

LEVELS = (0.2, 0.5, 0.8)  # true mean intensity of each class
COLORS = ((0.9, 0.2, 0.2), (0.2, 0.8, 0.2), (0.2, 0.4, 1.0))


def make_image(size=160, sigma=0.15, seed=1):
    """Noisy image and its ground-truth labels (0 background, 1 disc, 2 ring)."""
    y, x = np.mgrid[:size, :size] / size
    r = np.hypot(x - 0.55, y - 0.5)
    labels = np.where(r < 0.18, 1, np.where((r > 0.28) & (r < 0.38), 2, 0))
    labels[(x < 0.2) & (y < 0.3)] = 2
    noisy = np.take(LEVELS, labels) + sigma * np.random.default_rng(seed).standard_normal(labels.shape)
    return np.clip(noisy, 0, 1), labels


@interactive
def smooth(img, radius: Annotated[int, (0, 6), "smoothing radius"] = 2):
    padded, k = np.pad(img, radius, mode="edge"), 2 * radius + 1
    windows = np.lib.stride_tricks.sliding_window_view(padded, (k, k))
    return windows.mean(axis=(-2, -1))


@interactive(thresholds=RangeControl((0.35, 0.65), [0.0, 1.0]))
def segment(img, method: Literal["thresholds", "k-means"] = "thresholds", thresholds=(0.35, 0.65)):
    if method == "k-means":
        centers = np.array([0.1, 0.5, 0.9])
        for _ in range(10):
            labels = np.abs(img[..., None] - centers).argmin(axis=-1)
            centers = np.array([img[labels == k].mean() if np.any(labels == k) else centers[k] for k in range(3)])
        thresholds = tuple((centers[:-1] + centers[1:]) / 2)
    context["thresholds"] = thresholds  # for the histogram
    return np.digitize(img, thresholds)


@interactive
def evaluate(img, labels, truth):
    overlay = img
    for k, color in enumerate(COLORS):
        overlay = draw.mask(overlay, labels == k, color=color)
    iou = [np.sum((labels == k) & (truth == k)) / np.sum((labels == k) | (truth == k)) for k in range(3)]
    layout.style("overlay", title=f"mean IoU {np.mean(iou):.2f}")
    confusion = {"truth \\ predicted": ["background", "disc", "ring"]}
    for k, name in enumerate(["background", "disc", "ring"]):
        confusion[name] = [int(np.sum((truth == t) & (labels == k))) for t in range(3)]
    return overlay, Table(confusion, title="confusion (pixels)")


@interactive(roi=RegionControl((0.4, 0.3, 0.9, 0.7), on="overlay"))
def histogram(img, roi=(0.4, 0.3, 0.9, 0.7)):
    x0, y0, x1, y1 = to_pixels(roi, img)
    ax = Figure(figsize=(4, 3)).subplots()
    ax.hist(img[y0:y1, x0:x1].ravel(), bins=50, range=(0, 1), color="gray")
    for t in context["thresholds"]:
        ax.axvline(t, color="k", linestyle="--")
    ax.set_title(f"region ({x0}, {y0}) - ({x1}, {y1})")
    ax.set_xlabel("intensity")
    return ax


@interactive_pipeline(gui="auto")
def g2_segmentation(img, truth):
    smoothed = smooth(img)
    labels = segment(smoothed)
    overlay, confusion = evaluate(img, labels, truth)
    hist = histogram(smoothed)
    return [[smoothed, overlay], [hist, confusion]]


if __name__ == "__main__":
    g2_segmentation(*make_image())

Kalman tracking

Constant-velocity and constant-acceleration Kalman filters on a track that turns: trajectory figure, normalised innovation Curve, RMS table. One log slider each for q and r drives both filters (a shared Control).

Kalman tracking

Too little process noise and the constant-velocity filter cannot follow the turn; around q = 100 both agree.

Kalman tracking: sweep

demo/gallery/g2_kalman_tracking.py
"""Tracking: two Kalman filters (constant velocity, constant acceleration) on a noisy 2D path.

What to look at: the target turns sharply at t = 4 s. With a small process noise q the
constant-velocity filter is smooth but overshoots the turn, and its normalised innovation (the
surprise of each new measurement, ~1 when the filter is consistent) jumps far above 1 there; a
large q (1e4) follows the turn but lets the measurement noise through; q = 100 is the best compromise
here (see the RMS table). The constant-acceleration model handles the turn with a smaller q. The
same q and r sliders drive both filters: one slider each, on a log scale.
"""

import numpy as np
from matplotlib.figure import Figure

from interactive_pipe import Control, Curve, Table, interactive, interactive_pipeline

DT, N = 0.05, 200
Q = Control(1.0, [1e-2, 1e5], scale="log", name="process noise q")
R = Control(1.0, [1e-2, 1e2], scale="log", name="measurement noise r")


def make_track(sigma=1.0, seed=2):
    """True positions (N, 2) and noisy measurements: straight, a sharp turn at t = 4 s, straight."""
    t = np.arange(N) * DT
    heading = np.where(t < 4, 0.0, np.minimum(t - 4, 0.5) * np.pi)  # 90 degrees in 0.5 s
    velocity = 5 * np.stack([np.cos(heading), np.sin(heading)], axis=-1)
    truth = np.cumsum(velocity * DT, axis=0)
    return truth, truth + sigma * np.random.default_rng(seed).standard_normal(truth.shape)


def kalman(measurements, q, r, order):
    """Per-axis polynomial model of `order` (1 = velocity, 2 = acceleration). Returns estimates, NIS."""
    n = order + 1
    F = np.array(
        [[DT ** max(j - i, 0) / np.prod(range(1, j - i + 1)) if j >= i else 0 for j in range(n)] for i in range(n)]
    )
    G = np.array([DT ** (n - k) / np.prod(range(1, n - k + 1)) for k in range(n)])[:, None]
    Qm, H = q * G @ G.T, np.eye(1, n)
    x, P = np.zeros((n, 2)), np.eye(n) * 100.0
    x[0] = measurements[0]
    estimates, nis = [], []
    for z in measurements:
        x, P = F @ x, F @ P @ F.T + Qm
        S = (H @ P @ H.T).item() + r
        innovation = z - (H @ x)[0]
        K = P @ H.T / S
        x, P = x + K @ innovation[None], (np.eye(n) - K @ H) @ P
        estimates.append(x[0].copy())
        nis.append(innovation @ innovation / S / 2)  # normalised innovation squared, per axis
    return np.array(estimates), np.array(nis)


@interactive(q=Q, r=R)
def constant_velocity(measurements, q=1.0, r=1.0):
    return kalman(measurements, q, r, order=1)


@interactive(q=Q, r=R)
def constant_acceleration(measurements, q=1.0, r=1.0):
    return kalman(measurements, q, r, order=2)


@interactive
def compare(truth, measurements, cv, cv_nis, ca, ca_nis):
    ax = Figure(figsize=(5, 4)).subplots()
    ax.plot(*measurements.T, "k.", markersize=2, label="measurements")
    ax.plot(*truth.T, "k-", linewidth=1, label="truth")
    ax.plot(*cv.T, "r-", label="constant velocity")
    ax.plot(*ca.T, "b-", label="constant acceleration")
    ax.legend(loc="upper left", fontsize=8)
    t = np.arange(N) * DT
    innovation = Curve(
        [
            [t, cv_nis, "r-", "constant velocity"],
            [t, ca_nis, "b-", "constant acceleration"],
            [t, np.ones(N), "k--", "consistent"],
        ],
        xlabel="time (s)",
        title="normalised innovation",
    )
    rms = {"model": ["constant velocity", "constant acceleration", "measurements"]}
    rms["RMS error"] = [f"{np.sqrt(np.mean((est - truth) ** 2)):.2f}" for est in (cv, ca, measurements)]
    rms["mean NIS"] = [f"{cv_nis.mean():.2f}", f"{ca_nis.mean():.2f}", "-"]
    return ax, innovation, Table(rms)


@interactive_pipeline(gui="auto")
def g2_kalman_tracking(truth, measurements):
    cv, cv_nis = constant_velocity(measurements)
    ca, ca_nis = constant_acceleration(measurements)
    trajectory, innovation, errors = compare(truth, measurements, cv, cv_nis, ca, ca_nis)
    return [[trajectory, innovation, errors]]


if __name__ == "__main__":
    g2_kalman_tracking(*make_track())

Beamforming

Array factor of a steered uniform linear array: polar figure with the beam width and side-lobe level in the title, and a heatmap of the array factor versus element spacing with its axes (layout.style(extent=..., xlabel=..., ylabel=...)) where the grating lobes appear.

Beamforming

A Hann taper lowers the side lobes; more elements narrow the beam.

Beamforming: sweep

demo/gallery/g2_beamforming.py
"""Antenna arrays: array factor of a uniform linear array steered by phase shifts.

What to look at: the main lobe narrows as the number of elements grows (beamwidth ~ 1 / (N d)).
Spacing above half a wavelength brings grating lobes (copies of the main lobe) into visible
space: the heatmap of the array factor versus spacing shows where they appear, sooner when the
beam is steered off broadside. A Hann taper lowers the side lobes (-13 dB to -31 dB) at the cost of
a wider main lobe.
"""

from typing import Annotated

import numpy as np
from matplotlib.figure import Figure

from interactive_pipe import Control, interactive, interactive_pipeline, layout

ANGLES = np.linspace(-90, 90, 361)  # degrees from broadside
SPACINGS = np.linspace(0.1, 2.0, 120)  # in wavelengths
# one slider each, shared by both filters
ELEMENTS = Control(8, [2, 32], name="elements")
STEERING = Control(20.0, [-60.0, 60.0], name="steering (deg)")
TAPER = Control("uniform", ["uniform", "hann"], name="taper")


def array_factor_db(n, spacing, steering, taper, angles=ANGLES):
    weights = np.hanning(n + 2)[1:-1] if taper == "hann" else np.ones(n)
    phase = 2 * np.pi * spacing * (np.sin(np.radians(angles))[..., None] - np.sin(np.radians(steering)))
    response = np.abs(np.exp(1j * phase * np.arange(n)) @ weights) / weights.sum()
    return 20 * np.log10(np.maximum(response, 1e-5))


@interactive(elements=ELEMENTS, steering=STEERING, taper=TAPER)
def pattern(
    elements=8,
    spacing: Annotated[float, (0.1, 2.0), "spacing (wavelengths)"] = 0.5,
    steering=20.0,
    taper="uniform",
):
    gain = array_factor_db(elements, spacing, steering, taper)
    lo = hi = int(np.argmin(np.abs(ANGLES - steering)))  # main lobe: walk down to the nulls around the peak
    while lo > 0 and gain[lo - 1] < gain[lo]:
        lo -= 1
    while hi < len(gain) - 1 and gain[hi + 1] < gain[hi]:
        hi += 1
    side = max(gain[:lo].max(initial=-100), gain[hi + 1 :].max(initial=-100))
    width = np.ptp(ANGLES[lo:hi][gain[lo:hi] > -3])
    layout.style("polar", title=f"-3 dB width {width:.1f} deg, highest side lobe {side:.1f} dB")
    ax = Figure(figsize=(4, 3)).add_subplot(projection="polar")
    ax.plot(np.radians(ANGLES), np.maximum(gain, -40) + 40, "b-")
    ax.set_thetalim(-np.pi / 2, np.pi / 2)
    ax.set_theta_zero_location("N")
    ax.set_theta_direction(-1)
    ax.set_rlabel_position(-90)
    ax.set_yticks([10, 20, 30, 40], ["-30", "-20", "-10", "0 dB"])
    return ax


@interactive(elements=ELEMENTS, steering=STEERING, taper=TAPER)
def spacing_map(elements=8, steering=20.0, taper="uniform"):
    rows = [array_factor_db(elements, d, steering, taper, angles=np.arange(-90, 91)) for d in SPACINGS]
    layout.style("spacing_vs_angle", title="array factor vs spacing", colormap="magma", vmin=-40, vmax=0)
    # rows run from 0.1 (top) to 2 wavelengths (bottom): extent = (left, right, bottom, top)
    axes = dict(extent=(-90, 90, 2.0, 0.1), xlabel="angle (deg)", ylabel="spacing (wavelengths)")
    layout.style("spacing_vs_angle", colorbar="array factor (dB)", **axes)
    return np.array(rows)


@interactive_pipeline(gui="auto")
def g2_beamforming():
    polar = pattern()
    spacing_vs_angle = spacing_map()
    return polar, spacing_vs_angle


if __name__ == "__main__":
    g2_beamforming()

DCT compression

8x8 block DCT with a quality slider shared by the codec and the rate-distortion curve: reconstruction, diverging error heatmap, rate-distortion Curve and table; a checkbox zeroes the high frequencies.

DCT compression

The blocking artefacts and the error on the stripes fade as the quality rises.

DCT compression: sweep

demo/gallery/g2_dct_compression.py
"""Image compression: 8x8 block DCT with a JPEG-style quantisation table scaled by a quality factor.

What to look at: at low quality the error map shows ringing around the edges and the stripes, and
the 8x8 blocks: at quality 5 even the smooth gradient becomes a staircase of flat blocks. Rate
(entropy of the quantised coefficients, bits per pixel) and PSNR both grow with the quality: the
rate-distortion curve marks the current point. "zero high frequencies" keeps only the 3x3 lowest
frequencies of each block: the stripes, a high frequency, disappear.
"""

import numpy as np

from interactive_pipe import Control, Curve, Table, interactive, interactive_pipeline, layout

B = 8
k, n = np.meshgrid(np.arange(B), np.arange(B), indexing="ij")
DCT = np.sqrt(2 / B) * np.cos(np.pi * (2 * n + 1) * k / (2 * B))
DCT[0] /= np.sqrt(2)  # orthonormal DCT-II matrix
QUALITY = Control(50, [1, 100], name="quality")  # shared by both filters
ZERO_HIGH = Control(False, name="zero high frequencies")
JPEG_LUMA = 1 + (np.add.outer(np.arange(B), np.arange(B)) * 6 + 10)  # simplified: grows with frequency


def make_image(size=128):
    y, x = np.mgrid[:size, :size] / size
    img = 0.2 + 0.6 * x  # smooth gradient
    img[(x - 0.7) ** 2 + (y - 0.3) ** 2 < 0.04] = 0.9  # sharp-edged disc
    img[y > 0.6] = 0.5 + 0.3 * np.sin(2 * np.pi * 40 * x[y > 0.6])  # fine stripes
    img[(y > 0.1) & (y < 0.45) & (x > 0.1) & (x < 0.4)] = 0.15  # dark patch
    return img


def code(img, quality, zero_high):
    """Quantised DCT coefficients per block, shape (H/8, W/8, 8, 8), and the reconstruction."""
    scale = 5000 / quality if quality < 50 else 200 - 2 * quality
    step = np.maximum(JPEG_LUMA * scale / 100, 1) / 255
    blocks = img.reshape(img.shape[0] // B, B, img.shape[1] // B, B).transpose(0, 2, 1, 3)
    coefs = np.round(DCT @ blocks @ DCT.T / step)
    if zero_high:
        coefs[..., 3:, :] = coefs[..., :, 3:] = 0
    recon = (DCT.T @ (coefs * step) @ DCT).transpose(0, 2, 1, 3).reshape(img.shape)
    return coefs, np.clip(recon, 0, 1)


def rate_psnr(img, coefs, recon):
    _, counts = np.unique(coefs, return_counts=True)
    p = counts / counts.sum()
    return float(-(p * np.log2(p)).sum()), float(10 * np.log10(1 / np.mean((recon - img) ** 2)))


@interactive(quality=QUALITY, zero_high=ZERO_HIGH)
def compress(img, quality=50, zero_high=False):
    coefs, recon = code(img, quality, zero_high)
    rate, psnr = rate_psnr(img, coefs, recon)
    layout.style("reconstruction", title=f"quality {quality}: {rate:.2f} bpp, PSNR {psnr:.1f} dB")
    layout.style("error", colormap="RdBu_r", center=0, vmin=-0.2, vmax=0.2, colorbar="reconstruction - original")
    return recon, recon - img


@interactive(quality=QUALITY, zero_high=ZERO_HIGH)
def rate_distortion(img, quality=50, zero_high=False):
    qualities = [5, 10, 20, 30, 50, 70, 85, 95]
    points = np.array([rate_psnr(img, *code(img, q, zero_high)) for q in qualities])
    current = rate_psnr(img, *code(img, quality, zero_high))
    curve = Curve(
        [[points[:, 0], points[:, 1], "b.-", "quality 5 ... 95"], [[current[0]], [current[1]], "ro", "current"]],
        xlabel="rate (bits per pixel)",
        ylabel="PSNR (dB)",
        grid=True,
    )
    table = Table(
        {"quality": qualities, "rate (bpp)": np.round(points[:, 0], 2), "PSNR (dB)": np.round(points[:, 1], 1)}
    )
    return curve, table


@interactive_pipeline(gui="auto")
def g2_dct_compression(img):
    reconstruction, error = compress(img)
    rd, rd_table = rate_distortion(img)
    return [[img, reconstruction, error], [rd, rd_table]]


if __name__ == "__main__":
    g2_dct_compression(make_image())

Heat diffusion

An explicit 2D heat equation stepped by a slider; the solver state is cached in context keyed on the controls, so moving the step forward continues the simulation while snapshots stay reproducible.

Heat diffusion

Cold edges drain the heat, insulated edges keep the mean temperature.

Heat diffusion: sweep

demo/gallery/g2_heat_diffusion.py
"""Numerical simulation: explicit finite differences for the 2D heat equation, stepped by a slider.

What to look at: heat spreads from the hot bar into the plate; with cold edges (Dirichlet) the
plate cools down towards 0, with insulated edges (Neumann) the mean temperature stays constant
(see the title). The scheme is stable only for r = D dt / dx^2 <= 0.25: above it, a checkerboard
grows from the hot bar and the field explodes within a few hundred steps.
The state is cached in `context` keyed on the parameters, so moving the step slider forward only
computes the new steps; every frame is still a function of the controls (snapshots reproducible).
"""

from typing import Annotated, Literal

import numpy as np

from interactive_pipe import Curve, context, interactive, interactive_pipeline, layout

N = 64


def initial_plate():
    plate = np.zeros((N, N))
    plate[20:44, 30:34] = 100.0  # hot bar, degrees
    return plate


def step_once(u, r, edges):
    padded = np.pad(u, 1, mode="edge" if edges == "insulated" else "constant")
    laplacian = padded[:-2, 1:-1] + padded[2:, 1:-1] + padded[1:-1, :-2] + padded[1:-1, 2:] - 4 * u
    return u + r * laplacian


@interactive
def simulate(
    plate,
    step: Annotated[int, (0, 2000), "time step"] = 300,
    r: Annotated[float, (0.05, 0.3), "r = D dt / dx^2"] = 0.2,
    edges: Literal["cold", "insulated"] = "cold",
):
    key = (r, edges, plate.tobytes())
    cached = context.get("heat")  # (key, step, field) of the last run, if it was the same simulation
    if cached is not None and cached[0] == key and cached[1] <= step:
        done, u = cached[1], cached[2]
    else:
        done, u = 0, plate.astype(float)
    with np.errstate(over="ignore", invalid="ignore"):
        for _ in range(step - done):
            u = step_once(u, r, edges)
    context["heat"] = (key, step, u)
    title = f"step {step}: mean {np.mean(u):.3g}, max {np.max(u):.3g} deg C"
    layout.style("temperature", title=title, colormap="inferno", vmin=0, vmax=20, colorbar=True, unit="deg C")
    return u


@interactive
def profile(temperature):
    middle = Curve([[np.arange(N), temperature[N // 2], "r-", "row 32"]], xlabel="x (cells)", ylabel="deg C")
    return middle


@interactive_pipeline(gui="auto")
def g2_heat_diffusion(plate):
    temperature = simulate(plate)
    cross_section = profile(temperature)
    return temperature, cross_section


if __name__ == "__main__":
    g2_heat_diffusion(initial_plate())

Training curves

Loss curves of a learning-rate sweep: metric dropdown (Literal), exponential smoothing, a log-scale checkbox (Curve(yscale="log")), the best run in the title and a summary table; an empty selection shows an empty plot and table.

Training curves

Unsmoothed, the last value names the wrong run best; smoothing ranks lr 0.03 first.

Training curves: sweep

demo/gallery/g2_training_curves.py
"""Machine learning: inspect the loss curves of a learning-rate sweep (synthetic runs).

What to look at: raw curves are too noisy to rank the runs (with no smoothing, the last value names
lr 0.01 the best by luck); an exponential moving average (0.9) makes it clear that lr 0.03 wins.
A log scale shows that the lr 0.3 run diverges and the lr 0.001 run is still improving. The "best
run" readout and the summary table follow the chosen metric. Raise the selection threshold until
no run passes it: the plot and the table say so instead of failing.
"""

from typing import Annotated, Literal

import numpy as np

from interactive_pipe import Curve, SingleCurve, Table, interactive, interactive_pipeline, layout

STEPS = np.arange(1, 501)


def make_runs(seed=3):
    """{run name: {metric: values}} for a learning-rate sweep."""
    rng = np.random.default_rng(seed)
    runs = {}
    for lr, floor in ((0.001, 0.30), (0.01, 0.12), (0.03, 0.08), (0.1, 0.15), (0.3, None)):
        if floor is None:  # too large: diverges after a while
            train = 2.0 * np.exp(-STEPS / 50) + 0.4 + np.maximum(STEPS - 200, 0) ** 2 / 2e4
        else:
            train = 2.0 * np.exp(-lr * STEPS / 0.5) + floor
        val = train * 1.1 + 0.02 * STEPS / 500
        noisy = {
            "train loss": train * np.exp(0.3 * rng.standard_normal(STEPS.size)),
            "val loss": val * np.exp(0.3 * rng.standard_normal(STEPS.size)),
        }
        noisy["val accuracy"] = 1 / (1 + noisy["val loss"])
        runs[f"lr {lr}"] = noisy
    return runs


def ema(values, smoothing):
    out, acc = np.empty_like(values), values[0]
    for i, v in enumerate(values):
        acc = smoothing * acc + (1 - smoothing) * v
        out[i] = acc
    return out


@interactive
def inspect_runs(
    runs,
    metric: Literal["train loss", "val loss", "val accuracy"] = "val loss",
    smoothing: Annotated[float, (0.0, 0.99), "smoothing"] = 0.9,
    log_scale: Annotated[bool, "log scale"] = True,
    threshold: Annotated[float, (0.0, 1.0), "show runs with final val accuracy above"] = 0.0,
):
    selected = {name: m for name, m in runs.items() if m["val accuracy"][-20:].mean() > threshold}
    lower_is_better = metric != "val accuracy"
    lines = [SingleCurve(x=STEPS, y=ema(m[metric], smoothing), label=name) for name, m in selected.items()]
    curves = Curve(lines, xlabel="step", ylabel=metric, grid=True, yscale="log" if log_scale else None)
    final = {name: float(ema(m[metric], smoothing)[-1]) for name, m in selected.items()}
    best = (min if lower_is_better else max)(final, key=final.get) if final else None
    layout.style("curves", title=f"best: {best} ({final[best]:.3f})" if best else "no run above the threshold")
    rows = [
        {"run": name, f"final {metric}": f"{value:.3f}", "best": "*" if name == best else ""}
        for name, value in final.items()
    ]
    return curves, Table(rows, title=f"{len(rows)} of {len(runs)} runs")


@interactive_pipeline(gui="auto")
def g2_training_curves(runs):
    curves, summary = inspect_runs(runs)
    return curves, summary


if __name__ == "__main__":
    g2_training_curves(make_runs())

Audio effects

A guitar-pedal chain (distortion, low-pass, delay) on a synthetic chord: waveform and spectrum Curves, a spectrogram with time and frequency axes, and the result played in the Qt window with audio.set(signal, sample_rate).

Audio effects

The feedback of the delay repeats the attack every 250 ms.

Audio effects: sweep

demo/gallery/g2_audio_effects.py
"""Audio: a synthetic A major chord through a guitar-pedal chain (distortion, low-pass, delay).

What to look at: the drive saturates the waveform (flat tops) and adds harmonics, visible as new
horizontal lines in the spectrogram and new peaks in the spectrum; the low-pass cutoff removes
them again. The delay repeats the attack every "delay" ms (vertical stripes in the spectrogram,
decaying with the feedback). In the Qt window the result is played after every change.
"""

from typing import Annotated

import numpy as np

from interactive_pipe import Curve, audio, interactive, interactive_pipeline, layout

RATE = 16000


def make_chord(seconds=1.5):
    t = np.arange(int(seconds * RATE)) / RATE
    notes = (220.0, 277.18, 329.63)  # A3, C#4, E4
    chord = sum(np.sin(2 * np.pi * f * t) + 0.3 * np.sin(4 * np.pi * f * t) for f in notes)
    return 0.25 * chord * np.exp(-5 * t) * np.minimum(t / 0.01, 1)  # pluck: fast attack, slow decay


@interactive
def low_pass(signal, cutoff: Annotated[float, (100.0, 8000.0), "cutoff (Hz)"] = 3000.0):
    alpha = 1 - np.exp(-2 * np.pi * cutoff / RATE)  # one-pole filter, twice for 12 dB / octave
    out = signal.copy()
    for _ in range(2):
        acc = 0.0
        for i, x in enumerate(out):
            acc += alpha * (x - acc)
            out[i] = acc
    return out


@interactive
def distortion(signal, drive: Annotated[float, (1.0, 30.0), "drive"] = 3.0):
    return np.tanh(drive * signal) / np.tanh(drive)


@interactive
def delay(
    signal,
    delay_ms: Annotated[float, (20.0, 400.0), "delay (ms)"] = 250.0,
    feedback: Annotated[float, (0.0, 0.9), "feedback"] = 0.4,
    mix: Annotated[float, (0.0, 1.0), "mix"] = 0.5,
):
    d = int(delay_ms * RATE / 1000)
    dry = np.pad(signal, (0, 3 * d))
    wet = np.zeros_like(dry)
    for i in range(d, len(wet)):  # echo: y[n] = x[n - d] + feedback * y[n - d]
        wet[i] = dry[i - d] + feedback * wet[i - d]
    out = (1 - mix) * dry + mix * wet
    out /= max(1.0, np.abs(out).max())
    audio.set(out, RATE)  # played in the Qt window (from the start after each change); nothing headless
    audio.play()
    return out


@interactive
def analyse(signal):
    t = np.arange(len(signal)) / RATE * 1000
    window = slice(int(0.1 * RATE), int(0.13 * RATE))
    waveform = Curve([[t[window], signal[window], "b-", "output"]], xlabel="time (ms)", ylim=(-1.05, 1.05))
    frames = np.lib.stride_tricks.sliding_window_view(signal, 512)[::128] * np.hanning(512)
    spec = np.abs(np.fft.rfft(frames, axis=-1)).T[:97][::-1]  # 0-3 kHz, low frequencies at the bottom
    spec_db = 20 * np.log10(spec / spec.max() + 1e-6)
    seconds = len(signal) / RATE
    axes = dict(extent=(0, seconds, 0, 3000), xlabel="time (s)", ylabel="frequency (Hz)")
    layout.style("spectrogram", title="spectrogram", colormap="magma", vmin=-60, vmax=0, colorbar="dB", **axes)
    freqs = np.fft.rfftfreq(len(signal), 1 / RATE)
    spectrum = np.abs(np.fft.rfft(signal))
    spectrum = 20 * np.log10(spectrum / spectrum.max() + 1e-6)
    keep = freqs < 3000
    return waveform, spec_db, Curve([[freqs[keep], spectrum[keep], "k-", "spectrum"]], xlabel="Hz", ylabel="dB")


@interactive_pipeline(gui="auto")
def g2_audio_effects(chord):
    driven = distortion(chord)
    toned = low_pass(driven)
    output = delay(toned)
    waveform, spectrogram, spectrum = analyse(output)
    return [[waveform, spectrum], [spectrogram]]


if __name__ == "__main__":
    g2_audio_effects(make_chord())