Thumbnail.

Amplituhedron v2

Description

Another stab at a visualization of The Amplituhedron. With Claude Sonnet 5.5 this time.

#!/usr/bin/env python3
"""
Amplituhedron  --  an all-RGB image (4096 x 4096, every 24-bit colour exactly once)

The amplituhedron is the "positive geometry" whose volume encodes particle
scattering amplitudes.  In its simplest incarnation it is the cyclic polytope:
the convex hull of points on the moment curve (t, t^2, t^3) with t increasing.
Its facets are given by Gale's evenness condition, which for a 3-D cyclic
polytope on n vertices gives the 2(n-2) triangles
    {0, i, i+1}   and   {i, i+1, n-1}.

How the picture is made
-----------------------
1.  Build the cyclic polytope, rotate it, project it orthographically and
    z-buffer rasterise its triangular facets (pure numpy, no other deps).
2.  Turn every pixel into a single scalar "key":
      * background : radial falloff + interference ripples radiating from the
                     projected vertices (waves of "amplitude")
      * facets     : one block of keys per facet, ordered along the facet
                     strip, shaded by Lambert light + nested-triangle contours
      * edges and vertices get the very last keys
3.  Walk the RGB cube along a 3-D Hilbert curve (Skilling's algorithm), which
    visits all 2^24 colours exactly once with neighbouring steps being
    neighbouring colours.
4.  Sort pixels by key and hand out the Hilbert-ordered colours in that order.
    Every colour is used exactly once, and the structure of the key shows up
    as smooth colour flow with a fine fractal grain.

Usage:
    python amplituhedron.py                       # writes amplituhedron.png next to this script
    python amplituhedron.py -o out.png --vertices 13 --seed 7
    python amplituhedron.py --verify              # also checks all 16,777,216 colours are unique

Requires: numpy, Pillow.   Needs roughly 1.5 GB of RAM.
"""

import argparse
import os
import time

import numpy as np
from PIL import Image

SIZE = 4096                   # 4096 * 4096 == 2**24 == number of 24-bit colours
BITS = 8                      # bits per colour channel


# --------------------------------------------------------------------------
# Hilbert curve through the RGB cube
# --------------------------------------------------------------------------
def hilbert_colours():
    """Return uint8 array (2**24, 3): colour at each position along a 3-D Hilbert curve."""
    n = 1 << (3 * BITS)
    h = np.arange(n, dtype=np.uint32)

    # de-interleave the Hilbert integer into the "transposed" form
    X = [np.zeros(n, dtype=np.uint32) for _ in range(3)]
    for j in range(BITS):
        for i in range(3):
            X[i] |= ((h >> np.uint32(3 * j + 2 - i)) & np.uint32(1)) << np.uint32(j)
    del h

    # Skilling's TransposetoAxes
    t = X[2] >> np.uint32(1)
    for i in (2, 1):
        X[i] ^= X[i - 1]
    X[0] ^= t
    Q = 2
    while Q != (1 << BITS):
        P = np.uint32(Q - 1)
        q = np.uint32(Q)
        for i in (2, 1, 0):
            cond = (X[i] & q) != 0
            X[0] ^= np.where(cond, P, np.uint32(0))
            if i:
                tt = np.where(cond, np.uint32(0), (X[0] ^ X[i]) & P)
                X[0] ^= tt
                X[i] ^= tt
        Q <<= 1

    out = np.empty((n, 3), dtype=np.uint8)
    for i in range(3):
        out[:, i] = X[i].astype(np.uint8)
    return out


# --------------------------------------------------------------------------
# The amplituhedron (cyclic polytope) geometry
# --------------------------------------------------------------------------
def rotation(ax, ay, az):
    cx, sx, cy, sy, cz, sz = np.cos(ax), np.sin(ax), np.cos(ay), np.sin(ay), np.cos(az), np.sin(az)
    Rx = np.array([[1, 0, 0], [0, cx, -sx], [0, sx, cx]])
    Ry = np.array([[cy, 0, sy], [0, 1, 0], [-sy, 0, cy]])
    Rz = np.array([[cz, -sz, 0], [sz, cz, 0], [0, 0, 1]])
    return Rz @ Ry @ Rx


def build_polytope(n, rng):
    t = np.linspace(-1.0, 1.0, n)
    pts = np.stack([t, t ** 2, t ** 3], axis=1)
    pts -= pts.mean(axis=0)
    pts /= np.abs(pts).max()
    # a pleasant, slightly randomised viewing angle
    R = rotation(0.55 + rng.uniform(-0.1, 0.1),
                 -0.65 + rng.uniform(-0.1, 0.1),
                 0.25 + rng.uniform(-0.1, 0.1))
    pts = pts @ R.T

    # Gale evenness facets for d = 3
    tris = [(0, i, i + 1) for i in range(1, n - 1)] + \
           [(i, i + 1, n - 1) for i in range(0, n - 2)]

    centre = pts.mean(axis=0)
    return pts, tris, centre


def project(pts, size):
    xy = pts[:, :2].copy()
    lo, hi = xy.min(axis=0), xy.max(axis=0)
    span = (hi - lo).max()
    scale = 0.80 * size / span
    xy = (xy - (lo + hi) / 2) * scale
    sx = size / 2 + xy[:, 0]
    sy = size / 2 - xy[:, 1]
    return sx, sy, pts[:, 2] * scale


def rasterise(pts, tris, centre, size):
    sx, sy, sz = project(pts, size)
    F = len(tris)

    zbuf = np.full((size, size), -np.inf, dtype=np.float32)
    fid = np.full((size, size), -1, dtype=np.int16)
    dist = np.zeros((size, size), dtype=np.float32)     # px distance to nearest facet edge
    grad = np.zeros((size, size), dtype=np.float32)     # smooth gradient across a facet

    light = np.array([-0.45, 0.55, 0.70])
    light /= np.linalg.norm(light)
    lam = np.zeros(F, dtype=np.float32)

    for f, (a, b, c) in enumerate(tris):
        # lighting from the true 3-D normal, oriented outwards
        nrm = np.cross(pts[b] - pts[a], pts[c] - pts[a])
        nrm /= np.linalg.norm(nrm) + 1e-12
        if np.dot(nrm, pts[a] - centre) < 0:
            nrm = -nrm
        lam[f] = 0.25 + 0.75 * max(0.0, float(np.dot(nrm, light)))

        x0, y0, z0 = sx[a], sy[a], sz[a]
        x1, y1, z1 = sx[b], sy[b], sz[b]
        x2, y2, z2 = sx[c], sy[c], sz[c]
        D = (y1 - y2) * (x0 - x2) + (x2 - x1) * (y0 - y2)
        if abs(D) < 1e-6:
            continue
        len12 = np.hypot(x1 - x2, y1 - y2)
        len20 = np.hypot(x2 - x0, y2 - y0)
        len01 = np.hypot(x0 - x1, y0 - y1)

        bx0 = max(int(np.floor(min(x0, x1, x2))), 0)
        bx1 = min(int(np.ceil(max(x0, x1, x2))) + 1, size)
        by0 = max(int(np.floor(min(y0, y1, y2))), 0)
        by1 = min(int(np.ceil(max(y0, y1, y2))) + 1, size)
        px = (np.arange(bx0, bx1, dtype=np.float32) + 0.5)[None, :]
        py = (np.arange(by0, by1, dtype=np.float32) + 0.5)[:, None]

        l0 = ((y1 - y2) * (px - x2) + (x2 - x1) * (py - y2)) / D
        l1 = ((y2 - y0) * (px - x2) + (x0 - x2) * (py - y2)) / D
        l2 = 1.0 - l0 - l1
        inside = (l0 >= 0) & (l1 >= 0) & (l2 >= 0)
        z = l0 * z0 + l1 * z1 + l2 * z2

        zb = zbuf[by0:by1, bx0:bx1]
        m = inside & (z > zb)
        if not m.any():
            continue
        d = np.minimum(np.minimum(l0 * abs(D) / len12, l1 * abs(D) / len20), l2 * abs(D) / len01)
        zb[m] = z[m]
        fid[by0:by1, bx0:bx1][m] = f
        dist[by0:by1, bx0:bx1][m] = d[m]
        grad[by0:by1, bx0:bx1][m] = (l1 - l2)[m]

    return sx, sy, sz, zbuf, fid, dist, grad, lam


# --------------------------------------------------------------------------
# Key field
# --------------------------------------------------------------------------
def background_key(sx, sy, size, rng):
    """Radial falloff plus interference ripples emitted by every vertex."""
    key = np.empty((size, size), dtype=np.float32)
    xs = np.arange(size, dtype=np.float32)[None, :] + 0.5
    n = len(sx)
    phases = rng.uniform(0, 2 * np.pi, n).astype(np.float32)
    step = 256
    for r0 in range(0, size, step):
        ys = np.arange(r0, min(r0 + step, size), dtype=np.float32)[:, None] + 0.5
        acc = np.zeros((ys.shape[0], size), dtype=np.float32)
        for k in range(n):
            dk = np.hypot(xs - sx[k], ys - sy[k])
            acc += np.cos(dk / 38.0 + phases[k]) / (1.0 + dk / 900.0)
        acc /= n
        r = np.hypot(xs - size / 2, ys - size / 2) / (size * 0.72)
        key[r0:r0 + step] = 0.55 * np.clip(r, 0, 1) + 0.45 * (0.5 + 0.5 * np.tanh(2.2 * acc))
    return np.clip(key, 0, 0.999)


def triangle_wave(x):
    f = x - np.floor(x)
    return np.abs(2 * f - 1)


def build_key(sx, sy, sz, zbuf, fid, dist, grad, lam, size, rng):
    F = len(lam)
    key = background_key(sx, sy, size, rng).astype(np.float64)

    face = fid >= 0
    f = fid[face].astype(np.int64)
    d = dist[face]
    shade = 0.45 * lam[f] + 0.35 * triangle_wave(d / 85.0) + 0.20 * (0.5 + 0.5 * grad[face])
    shade = np.clip(shade, 0.0, 0.999)
    # facets sit after the background (keys 0..1); each one owns its own block
    key[face] = 2.0 + f * 1.25 + shade

    edge_base = 2.0 + F * 1.25 + 1.0
    edge = face & (dist < 3.0)
    key[edge] = edge_base + 0.5 * (1.0 - np.clip(dist[edge] / 3.0, 0, 1))

    # vertices: glowing discs, only if visible (not hidden behind a facet)
    vert_base = edge_base + 2.0
    R = 34.0
    for k in range(len(sx)):
        cx, cy = int(round(sx[k])), int(round(sy[k]))
        if not (0 <= cx < size and 0 <= cy < size):
            continue
        if sz[k] < zbuf[cy, cx] - 2.0:            # hidden behind the surface
            continue
        x0, x1 = max(cx - int(R), 0), min(cx + int(R) + 1, size)
        y0, y1 = max(cy - int(R), 0), min(cy + int(R) + 1, size)
        gx = (np.arange(x0, x1) + 0.5 - sx[k])[None, :]
        gy = (np.arange(y0, y1) + 0.5 - sy[k])[:, None]
        rr = np.hypot(gx, gy)
        sel = rr < R
        sub = key[y0:y1, x0:x1]
        sub[sel] = vert_base + (1.0 - rr[sel] / R)
    # a touch of noise: dithers ties and gives the colour flow its fine grain
    key += rng.random((size, size), dtype=np.float32) * 0.0025
    return key


# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def main():
    here = os.path.dirname(os.path.abspath(__file__))
    ap = argparse.ArgumentParser(description="All-RGB Amplituhedron generator")
    ap.add_argument("-o", "--output", default=os.path.join(here, "amplituhedron.png"))
    ap.add_argument("-n", "--vertices", type=int, default=12, help="vertices of the cyclic polytope (>=4)")
    ap.add_argument("--seed", type=int, default=2026)
    ap.add_argument("--verify", action="store_true", help="check that every colour appears exactly once")
    args = ap.parse_args()
    if args.vertices < 4:
        ap.error("--vertices must be at least 4")

    t0 = time.time()
    log = lambda m: print(f"[{time.time() - t0:6.1f}s] {m}", flush=True)
    rng = np.random.default_rng(args.seed)

    log("building cyclic polytope (amplituhedron)")
    pts, tris, centre = build_polytope(args.vertices, rng)
    log(f"{len(tris)} facets, rasterising")
    sx, sy, sz, zbuf, fid, dist, grad, lam = rasterise(pts, tris, centre, SIZE)

    log("computing key field")
    key = build_key(sx, sy, sz, zbuf, fid, dist, grad, lam, SIZE, rng)
    del zbuf, fid, dist, grad

    log("sorting pixels")
    order = np.argsort(key.ravel(), kind="stable")
    del key

    log("walking the RGB cube along a Hilbert curve")
    colours = hilbert_colours()

    log("assigning colours")
    img = np.empty((SIZE * SIZE, 3), dtype=np.uint8)
    img[order] = colours
    del order, colours
    img = img.reshape(SIZE, SIZE, 3)

    if args.verify:
        log("verifying")
        packed = (img[..., 0].astype(np.uint32) << 16) | (img[..., 1].astype(np.uint32) << 8) | img[..., 2]
        seen = np.zeros(1 << 24, dtype=bool)
        seen[packed.ravel()] = True
        assert seen.all(), "some colours are missing!"
        log("OK: all 16,777,216 colours present exactly once")
        del packed, seen

    log(f"writing {args.output}")
    Image.fromarray(img, "RGB").save(args.output, optimize=False, compress_level=6)
    log("done")


if __name__ == "__main__":
    main()

Author

ACJ
80 entries

Stats

Date
Colors16,777,216
Pixels16,777,216
Dimensions4,096 × 4,096
Bytes40,412,432