Thumbnail.

E8 v3

Description

Another throw at visualizing E8 (mathematics). With Claude Sonnet 5.5 this time.

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

E8 is the exceptional Lie group whose root system is 240 vectors in 8-D space.
The 240 roots are the vertices of the Gosset 4_21 polytope; joining roots at
distance sqrt(2) gives its 6720 edges.  Looking along the *Coxeter plane*
(the plane the Coxeter element rotates by 2*pi/30) gives the classic picture of
eight concentric rings of 30 points with exact 30-fold symmetry -- the picture
used for E8 in "An Exceptionally Simple Theory of Everything".

Look
----
* the 6720 edges are hairlines, one pixel wide, each drawn with a little
  transparency so the density of the web builds up towards the centre
* the 240 roots are small beads, outlined in ink, each ring of 30 with its own hue
* the paper is a soft iridescent gradient

How it becomes all-RGB
----------------------
Lines and beads are rasterised with analytic anti-aliasing and merged into a
luma key (structure) and a hue key (a conic spectrum for the paper, one hue per
ring for the beads).  Pixels and the 2^24 colours are each sorted by luma, cut
into groups, sorted by hue inside the groups, and the colour side is cut into
blocks whose saturation runs up and down alternately (a serpentine), so colour
changes smoothly along the pixel order.  Matching rank for rank uses every
colour exactly once.

Usage:
    python e8.py                         # writes e8.png next to this script
    python e8.py --line 1.0 --dot 6.5    # hairline width and bead radius in pixels
    python e8.py --rotate 6 --verify

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

import argparse
import os
import time

import numpy as np
import matplotlib

matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.patches import Circle
from PIL import Image

W = H = 4096                  # 4096 * 4096 == 2**24 == number of 24-bit colours
NN = W * H
DPI = 100


# --------------------------------------------------------------------------
# E8 root system and Coxeter plane
# --------------------------------------------------------------------------
def simple_roots():
    h = 0.5
    return np.array([
        [h, -h, -h, -h, -h, -h, -h, h],
        [1, 1, 0, 0, 0, 0, 0, 0],
        [-1, 1, 0, 0, 0, 0, 0, 0],
        [0, -1, 1, 0, 0, 0, 0, 0],
        [0, 0, -1, 1, 0, 0, 0, 0],
        [0, 0, 0, -1, 1, 0, 0, 0],
        [0, 0, 0, 0, -1, 1, 0, 0],
        [0, 0, 0, 0, 0, -1, 1, 0],
    ], dtype=np.float64)


def all_roots(simple):
    """Close the simple roots under reflections -> all 240 roots."""
    def key(v):
        return tuple(np.round(v * 2).astype(int))

    found, frontier = {}, []
    for a in simple:
        for r in (a, -a):
            found[key(r)] = r
            frontier.append(r)
    while frontier:
        new = []
        for r in frontier:
            for a in simple:
                s = r - np.dot(r, a) * a          # roots have norm^2 == 2
                k = key(s)
                if k not in found:
                    found[k] = s
                    new.append(s)
        frontier = new
    roots = np.array(list(found.values()))
    assert len(roots) == 240, len(roots)
    return roots


def coxeter_element(simple):
    C = np.eye(8)
    for a in simple:
        C = C @ (np.eye(8) - np.outer(a, a))       # reflection: I - 2 a a^T / (a.a), a.a == 2
    return C


def coxeter_plane(C, m):
    """Orthonormal basis (a, b) of the eigenplane of C for eigenvalue exp(2 pi i m / 30)."""
    w, V = np.linalg.eig(C)
    i = np.argmin(np.abs(w - np.exp(2j * np.pi * m / 30)))
    v = V[:, i]
    a, b = v.real, v.imag
    a = a / np.linalg.norm(a)
    b = b - np.dot(a, b) * a
    return a, b / np.linalg.norm(b)


# --------------------------------------------------------------------------
# Colour matching (luma -> hue -> serpentine saturation, rank for rank)
# --------------------------------------------------------------------------
def all_colours():
    i = np.arange(NN, dtype=np.uint32)
    r = (i >> 16).astype(np.float32)
    g = ((i >> 8) & 255).astype(np.float32)
    b = (i & 255).astype(np.float32)
    luma = 0.299 * r + 0.587 * g + 0.114 * b
    hue = (np.arctan2(np.sqrt(3.0) * (g - b), 2 * r - g - b) / (2 * np.pi)) % 1.0
    mx = np.maximum(np.maximum(r, g), b)
    mn = np.minimum(np.minimum(r, g), b)
    sat = (mx - mn) / np.maximum(mx, 1.0)
    return (luma.astype(np.float64), np.clip(hue, 0, 0.999999).astype(np.float64),
            sat.astype(np.float64))


def order_pixels(luma, hue, g1):
    pos = np.arange(luma.size) // g1
    o = np.argsort(luma, kind="stable")
    return o[np.argsort(pos + hue[o], kind="stable")]


def order_colours(luma, hue, sat, g1, g2):
    pos = np.arange(luma.size) // g1
    o = np.argsort(luma, kind="stable")
    o = o[np.argsort(pos + hue[o], kind="stable")]
    blk = np.arange(luma.size) // g2
    sgn = np.where(blk % 2 == 0, 1.0, -1.0)
    key = blk + 0.5 + 0.499 * sgn * (2.0 * sat[o] - 1.0)
    return o[np.argsort(key, kind="stable")]


# --------------------------------------------------------------------------
# Rasterising the web
# --------------------------------------------------------------------------
def PT(px):
    return px * 72.0 / DPI


def draw_web(segments, line_px, alpha, rings, radii):
    """Hairline web with accumulating transparency -> coverage in [0, 1]."""
    fig = plt.figure(figsize=(W / DPI, H / DPI), dpi=DPI, facecolor="black")
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(0, W)
    ax.set_ylim(H, 0)
    ax.axis("off")
    ax.add_collection(LineCollection(segments, colors=[(1, 1, 1, alpha)], linewidths=PT(line_px),
                                     capstyle="butt", antialiaseds=True, snap=False))
    if rings:
        for r in radii:
            ax.add_patch(Circle((W / 2, H / 2), r, fill=False, ec=(1, 1, 1, 0.22), lw=PT(line_px), snap=False))
    fig.canvas.draw()
    cov = np.asarray(fig.canvas.buffer_rgba())[..., 0].astype(np.float32) / 255.0
    plt.close(fig)
    return cov


# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def main():
    here = os.path.dirname(os.path.abspath(__file__))
    ap = argparse.ArgumentParser(description="All-RGB E8 generator")
    ap.add_argument("-o", "--output", default=os.path.join(here, "e8.png"))
    ap.add_argument("--rotate", type=float, default=0.0, help="extra rotation in degrees")
    ap.add_argument("--line", type=float, default=1.0, help="edge width in pixels")
    ap.add_argument("--alpha", type=float, default=0.38, help="opacity of each edge (the web builds up where edges overlap)")
    ap.add_argument("--dot", type=float, default=6.5, help="bead radius in pixels")
    ap.add_argument("--rings", action="store_true", help="draw the eight Coxeter rings as faint guides")
    ap.add_argument("--group", type=int, default=16, help="log2 of the luma group size used for colour matching")
    ap.add_argument("--block", type=int, default=10, help="log2 of the serpentine block size used for colour matching")
    ap.add_argument("--verify", action="store_true", help="check that every colour appears exactly once")
    args = ap.parse_args()
    g1, g2 = 1 << args.group, 1 << args.block

    t0 = time.time()
    log = lambda m: print(f"[{time.time() - t0:6.1f}s] {m}", flush=True)

    # ---- geometry --------------------------------------------------------
    log("building the E8 root system")
    simple = simple_roots()
    roots = all_roots(simple)
    C = coxeter_element(simple)
    a1, b1 = coxeter_plane(C, 1)

    gram = roots @ roots.T
    ii, jj = np.where(np.triu(np.abs(gram - 1.0) < 1e-9, k=1))
    log(f"{len(roots)} roots, {len(ii)} edges")

    rot = np.deg2rad(args.rotate) + np.pi / 2
    x, y = roots @ a1, roots @ b1
    px = x * np.cos(rot) - y * np.sin(rot)
    py = x * np.sin(rot) + y * np.cos(rot)
    scale = 0.455 * W / np.hypot(px, py).max()
    PX = W / 2 + px * scale
    PY = H / 2 - py * scale

    rad1 = np.hypot(px, py)
    levels = np.unique(np.round(rad1, 4))
    ring = np.searchsorted(levels, np.round(rad1, 4))               # 0 (inner) .. 7 (outer)
    ang_v = (np.arctan2(PY - H / 2, PX - W / 2) / (2 * np.pi)) % 1.0

    # ---- hairline web -----------------------------------------------------------
    log("drawing the 6720 hairlines")
    segs = np.stack([np.stack([PX[ii], PY[ii]], 1), np.stack([PX[jj], PY[jj]], 1)], 1)
    web = draw_web(segs, args.line, args.alpha, args.rings, levels * scale)

    # ---- luma / hue keys for the paper and the web ------------------------------
    log("building keys")
    yy, xx = np.mgrid[0:H, 0:W].astype(np.float32)
    xx -= W / 2
    yy -= H / 2
    rn = np.clip(np.hypot(xx, yy) / 2900.0, 0.0, 1.0)
    luma = 0.62 + 0.38 * rn ** 1.25                                  # paper: lightest in the corners
    hue = ((np.arctan2(yy, xx) / (2 * np.pi) + 0.5) + 0.10 * rn) % 1.0
    del xx, yy, rn

    ramp = 0.010 * (0.6 * np.arange(W, dtype=np.float32)[None, :] / W + 0.4 * np.arange(H, dtype=np.float32)[:, None] / H)
    INK = 0.08
    luma += web * (INK + ramp - luma)                                # ink web (thin, translucent)
    del web, ramp

    # ---- reserve a dedicated band of luma ranks for the beads -----------------------
    sample = luma[::7, ::7]
    thr = float(np.quantile(sample, 0.58))
    luma[luma > thr] += 0.5                                           # open a gap just above `thr`
    bead_lo = thr + 0.10

    # ---- beads: ink outline + filled disc, one hue per ring -----------------------------
    log("drawing the 240 beads")
    R = args.dot
    win = int(np.ceil(R)) + 3
    for v in range(len(roots)):
        cx, cy = PX[v], PY[v]
        x0, y0 = int(np.floor(cx)) - win, int(np.floor(cy)) - win
        gx = (np.arange(x0, x0 + 2 * win + 1) + 0.5 - cx)[None, :]
        gy = (np.arange(y0, y0 + 2 * win + 1) + 0.5 - cy)[:, None]
        d = np.hypot(gx, gy)
        fill = np.clip(R - d + 0.5, 0.0, 1.0)
        outline = np.clip(1.15 - np.abs(d - R), 0.0, 1.0)
        # soft top-left highlight inside the bead (a few ranks of luma only)
        shade = 0.05 * np.clip((gx + gy) / (2 * R) + 0.5, 0.0, 1.0)
        sl = (slice(y0, y0 + 2 * win + 1), slice(x0, x0 + 2 * win + 1))
        sub = luma[sl]
        sub += fill * (bead_lo + shade - sub)
        sub += outline * (INK - sub)
        h_ = hue[sl]
        hue_v = ((ring[v] + 0.5) / 8.0 + 0.02 * ang_v[v]) % 1.0
        h_ += fill * (1.0 - outline) * (hue_v - h_)

    # ---- assign colours -----------------------------------------------------------------
    log("ordering pixels")
    op = order_pixels(luma.ravel().astype(np.float64), hue.ravel().astype(np.float64), g1)
    del luma, hue

    log("ordering the 16,777,216 colours")
    lc, hc, sc = all_colours()
    oc = order_colours(lc, hc, sc, g1, g2)
    del lc, hc, sc

    log("assigning colours")
    img = np.empty((NN, 3), dtype=np.uint8)
    img[op, 0] = (oc >> 16).astype(np.uint8)
    img[op, 1] = ((oc >> 8) & 255).astype(np.uint8)
    img[op, 2] = (oc & 255).astype(np.uint8)
    del op, oc
    img = img.reshape(H, W, 3)

    if args.verify:
        log("verifying")
        packed = (img[..., 0].astype(np.uint32) << 16) | (img[..., 1].astype(np.uint32) << 8) | img[..., 2]
        seen = np.zeros(NN, 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
83 entries

Stats

Date
Colors16,777,216
Pixels16,777,216
Dimensions4,096 × 4,096
Bytes31,596,326