


Another throw at visualizing a https://en.wikipedia.org/wiki/Penrose_diagram. With Claude Sonnet 5.5 this time.
#!/usr/bin/env python3 """ Penrose diagram -- an all-RGB image (4096 x 4096, every 24-bit colour exactly once) The subject is the maximally extended Schwarzschild spacetime (Kruskal-Szekeres extension), drawn as a Penrose-Carter conformal diagram. Everything is computed analytically, nothing is traced by eye. Mathematics (units 2M = 1, rho = r / 2M) ---------------------------------------- Kruskal-Szekeres null coordinates a = T + X , b = X - T (rho - 1) e^rho = X^2 - T^2 = a b (defines r(T, X)) Conformal compactification T + X = tan((tau + chi)/2) X - T = tan((chi - tau)/2) * the whole manifold maps to the hexagon |tau| <= pi/2, |tau| + |chi| <= pi * the singularity r = 0 <=> a b = -1 <=> tau = +-pi/2 (exactly straight) * null infinity I+- : tau + |chi| = pi, |chi| - tau = pi * horizons r = 2M <=> a = 0 or b = 0 (the two 45-degree diagonals) Curves drawn r = const outside : (X, T) = sqrt(G) (cosh s, sinh s), G = (rho-1)e^rho > 0 r = const inside : (X, T) = sqrt(-G) (sinh s, +-cosh s), G < 0 t = const : straight lines through the bifurcation sphere, T = tanh(t/4M) X outside, X = tanh(t/4M) T inside free fall from rest at r = R0 (exact cycloid, continued through the horizon): rho = rho0 (1 + cos eta)/2 , q = sqrt(rho0 - 1) , x = tan(eta/2) Phi = q [eta + (rho0/2)(eta + sin eta)] a = (q + x) e^{(rho + Phi)/2} / sqrt(1 + x^2) b = (q - x) e^{(rho - Phi)/2} / sqrt(1 + x^2) (finite and smooth across the horizon, ends exactly on a b = -1) Region shading uses the exact r(T, X) from the Lambert W function: rho = 1 + W0(G / e). How the picture becomes all-RGB ------------------------------- Vector layers (lines, type) are rasterised at 4096^2 with analytic anti-aliasing (matplotlib / Agg). They are merged into three smooth scalar fields for every pixel: a luma key (structure), a hue key (a conic spectrum) and a saturation key. Pixels and the 2^24 colours are each sorted by luma, cut into groups, sorted by hue inside the groups, cut again and sorted by saturation, then matched rank-for-rank, so every colour is used exactly once and edges stay crisp. Usage: python penrose.py # writes penrose.png next to this script python penrose.py --verify # also checks every colour appears exactly once python penrose.py --serif "Georgia" # use another installed serif font for the type Requires: numpy, Pillow, matplotlib. Needs roughly 2.5 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.font_manager import FontProperties from matplotlib.patches import Circle, PathPatch from matplotlib.path import Path from matplotlib.textpath import TextPath, text_to_path from matplotlib.transforms import Affine2D from PIL import Image PI = np.pi W = H = 4096 # 4096 * 4096 == 2**24 == number of 24-bit colours NN = W * H DPI = 100 # ---- layout (pixels) ----------------------------------------------------- S = 555.0 # pixels per unit of tau / chi CX, CY = 2048.0, 1800.0 # screen position of the bifurcation sphere matplotlib.rcParams["mathtext.fontset"] = "stix" matplotlib.rcParams["lines.scale_dashes"] = False matplotlib.rcParams["path.simplify"] = False # -------------------------------------------------------------------------- # Mathematics # -------------------------------------------------------------------------- def lambertw0(x): """Principal branch of the Lambert W function (vectorised Halley iteration).""" x = np.maximum(np.asarray(x, dtype=np.float64), -1.0 / np.e + 1e-15) p = np.sqrt(np.maximum(2.0 * (np.e * x + 1.0), 0.0)) w_branch = -1.0 + p - p * p / 3.0 + 11.0 * p ** 3 / 72.0 w_neg = x / (1.0 + x) w_pos = np.log1p(np.maximum(x, 0.0)) w = np.where(x < -0.25, w_branch, np.where(x < 0, w_neg, w_pos)) for _ in range(12): ew = np.exp(w) f = w * ew - x den = ew * (w + 1.0) - (w + 2.0) * f / (2.0 * w + 2.0) w = w - f / den return w def penrose_from_null(a, b): """(tau, chi) from the Kruskal null coordinates a = T + X, b = X - T.""" al, be = np.arctan(a), np.arctan(b) return al - be, al + be def penrose_from_kruskal(T, X): return penrose_from_null(T + X, X - T) def screen(tau, chi): return CX + S * np.asarray(chi), CY - S * np.asarray(tau) def G_of_rho(rho): return (rho - 1.0) * np.exp(rho) def curve_r_outside(rho, n=6000, smax=13.0): """r = const > 2M : a timelike hyperbola from i- to i+ (right exterior).""" sg = np.sqrt(G_of_rho(rho)) s = np.linspace(-smax, smax, n) return penrose_from_kruskal(sg * np.sinh(s), sg * np.cosh(s)) def curve_r_inside(rho, upper=True, n=6000, smax=13.0): """r = const < 2M : a spacelike hyperbola inside the black (upper) / white hole.""" sg = np.sqrt(-G_of_rho(rho)) s = np.linspace(-smax, smax, n) T = sg * np.cosh(s) * (1 if upper else -1) return penrose_from_kruskal(T, sg * np.sinh(s)) def line_t_outside(slope, n=6000): """t = const outside : T = slope X through the bifurcation sphere (regions III and I).""" u = np.linspace(-PI / 2 + 1e-9, PI / 2 - 1e-9, n) lam = np.tan(u) return penrose_from_kruskal(slope * lam, lam) def line_t_inside(slope, n=3000): """t = const inside : X = slope T, from the white-hole singularity to the black-hole one.""" lim = 1.0 / np.sqrt(1.0 - slope ** 2) # T^2 - X^2 = 1 (singularity) lam = np.linspace(-lim, lim, n) return penrose_from_kruskal(lam, slope * lam) def geodesic(rho0, eta): """Radial free fall from rest at rho0 (right exterior), exact Kruskal null coordinates.""" q = np.sqrt(rho0 - 1.0) rho = rho0 / 2.0 * (1.0 + np.cos(eta)) x = np.tan(eta / 2.0) phi = q * (eta + rho0 / 2.0 * (eta + np.sin(eta))) s = np.sqrt(1.0 + x * x) a = (q + x) * np.exp((rho + phi) / 2.0) / s b = (q - x) * np.exp((rho - phi) / 2.0) / s return penrose_from_null(a, b) # -------------------------------------------------------------------------- # Hilbert-free colour matching (luma -> hue -> 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): """Pixels: luma groups of g1, then ordered along the group by the hue key.""" 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): """Colours: luma groups of g1, hue-sorted, then cut into blocks of g2 whose saturation runs up and down alternately (a serpentine), so colour changes smoothly along the pixel order.""" 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) # inside block: ascending / descending return o[np.argsort(key, kind="stable")] def gaussian_blur(a, sigma): f = np.fft.rfft2(a) fy = np.fft.fftfreq(a.shape[0]).astype(np.float32)[:, None] fx = np.fft.rfftfreq(a.shape[1]).astype(np.float32)[None, :] f *= np.exp(-2.0 * (np.pi * sigma) ** 2 * (fx * fx + fy * fy)).astype(np.float32) return np.fft.irfft2(f, s=a.shape).astype(np.float32) # -------------------------------------------------------------------------- # Vector drawing helpers (matplotlib / Agg, data coordinates == pixels) # -------------------------------------------------------------------------- def PT(px): """pixels -> points at our DPI.""" return px * 72.0 / DPI class Layer: def __init__(self): self.fig = plt.figure(figsize=(W / DPI, H / DPI), dpi=DPI, facecolor="black") self.ax = self.fig.add_axes([0, 0, 1, 1]) self.ax.set_xlim(0, W) self.ax.set_ylim(H, 0) self.ax.axis("off") def line(self, xs, ys, width, dash=None, cap="round"): kw = dict(color="white", lw=PT(width), solid_capstyle=cap, solid_joinstyle="round", dash_capstyle="butt", antialiased=True, snap=False) if dash: kw["linestyle"] = (0, (PT(dash[0]), PT(dash[1]))) self.ax.plot(xs, ys, **kw) def ring(self, x, y, r, width): self.ax.add_patch(Circle((x, y), r, fill=False, ec="white", lw=PT(width), snap=False)) def disc(self, x, y, r): self.ax.add_patch(Circle((x, y), r, fc="white", ec="none", lw=0, snap=False)) def polygon(self, pts): p = Path(np.asarray(pts + [pts[0]], dtype=float), [Path.MOVETO] + [Path.LINETO] * (len(pts) - 1) + [Path.CLOSEPOLY]) self.ax.add_patch(PathPatch(p, fc="white", ec="none", lw=0, snap=False)) def path(self, path, transform): self.ax.add_patch(PathPatch(path, transform=transform + self.ax.transData, fc="white", ec="none", lw=0, snap=False)) def grab(self): self.fig.canvas.draw() a = np.asarray(self.fig.canvas.buffer_rgba())[..., 0].astype(np.float32) / 255.0 plt.close(self.fig) return a class Typeface: def __init__(self, serif): self.roman = FontProperties(family=[serif, "STIXGeneral", "DejaVu Serif"]) self.italic = FontProperties(family=[serif, "STIXGeneral", "DejaVu Serif"], style="italic") self.bold = FontProperties(family=[serif, "STIXGeneral", "DejaVu Serif"], weight="bold") def run(self, s, kind, size, tracking=0.0): """Return (Path in y-up units with baseline y=0, advance width) for one run of text.""" if kind == "math": tp = TextPath((0, 0), s, size=size, prop=self.roman) p = Path(tp.vertices.copy(), tp.codes.copy()) ext = p.get_extents() return p, ext.x1 + 0.06 * size fp = {"caps": self.roman, "roman": self.roman, "italic": self.italic, "bold": self.bold}[kind] if tracking == 0.0: tp = TextPath((0, 0), s, size=size, prop=fp) p = Path(tp.vertices.copy(), tp.codes.copy()) w = text_to_path.get_text_width_height_descent(s, _sized(fp, size), False)[0] return p, w paths, x = [], 0.0 for ch in s: if ch == " ": x += 0.30 * size + tracking * size continue tp = TextPath((x, 0), ch, size=size, prop=fp) paths.append(Path(tp.vertices.copy(), tp.codes.copy())) x += text_to_path.get_text_width_height_descent(ch, _sized(fp, size), False)[0] + tracking * size return Path.make_compound_path(*paths), x - tracking * size def _sized(fp, size): f = fp.copy() f.set_size(size) return f def place_text(layer, tf, pieces, x, y, ha="center", va="base", rot=0.0, gap=0.0): """pieces: list of (string, kind, size, tracking). Anchor at pixel (x, y).""" paths, cursor = [], 0.0 for s, kind, size, tracking in pieces: p, adv = tf.run(s, kind, size, tracking) paths.append(Affine2D().translate(cursor, 0).transform_path(p)) cursor += adv + gap cursor -= gap path = Path.make_compound_path(*paths) ext = path.get_extents() ax_ = {"left": ext.x0, "center": cursor / 2.0, "right": cursor}[ha] ay_ = {"base": 0.0, "center": (ext.y0 + ext.y1) / 2.0}[va] tr = Affine2D().translate(-ax_, -ay_).scale(1, -1).rotate_deg(-rot).translate(x, y) layer.path(path, tr) return cursor def text_width(tf, pieces, gap=0.0): c = 0.0 for s, kind, size, tracking in pieces: c += tf.run(s, kind, size, tracking)[1] + gap return c - gap # -------------------------------------------------------------------------- # Geometry layers # -------------------------------------------------------------------------- HEX = [(PI, 0.0), (PI / 2, PI / 2), (-PI / 2, PI / 2), (-PI, 0.0), (-PI / 2, -PI / 2), (PI / 2, -PI / 2)] RHO_EXT = [1.12, 1.3, 1.6, 2.2, 3.4, 6.0, 12.0] # r/2M for the exterior r = const curves RHO_INT = [0.2, 0.4, 0.6, 0.8] # r/2M inside the horizon T_SLOPES = [np.tanh(0.5 * k) for k in range(0, 5)] # t/4M = 0, 0.5, ..., 2 RHO0 = 1.5 # free fall from rest at r = 3M ETA_CONES = [0.0, 0.85, 1.55, 2.2, 2.75] def screen_hex(): return [screen(t, c) for c, t in HEX] def geometry_layers(): minor, major, world = Layer(), Layer(), Layer() # ---- constant-r curves (both exteriors, both interiors) ---------------- for rho in RHO_EXT: tau, chi = curve_r_outside(rho) for sgn in (1, -1): x, y = screen(tau, sgn * chi) minor.line(x, y, 3.6) for rho in RHO_INT: for upper in (True, False): tau, chi = curve_r_inside(rho, upper) x, y = screen(tau, chi) minor.line(x, y, 3.6) # ---- constant-t lines: dashed, through the bifurcation sphere -------------- for sl in T_SLOPES: for sgn in ((1,) if sl == 0 else (1, -1)): tau, chi = line_t_outside(sgn * sl) x, y = screen(tau, chi) minor.line(x, y, 3.2, dash=(26, 18)) tau, chi = line_t_inside(sgn * sl) x, y = screen(tau, chi) minor.line(x, y, 3.2, dash=(26, 18)) # ---- hairline decorations ------------------------------------------------ # (drawn by the typography stage so they can follow the text widths) # ---- major: outline, horizons, markers ------------------------------------ pts = screen_hex() # null infinity (four edges) for i in (0, 2, 3, 5): p, q = pts[i], pts[(i + 1) % 6] major.line([p[0], q[0]], [p[1], q[1]], 8.0) # singularities: thick line + hatching on the outside for i, outward in ((1, -1), (4, 1)): p, q = pts[i], pts[(i + 1) % 6] major.line([p[0], q[0]], [p[1], q[1]], 13.0, cap="butt") x0, x1 = sorted((p[0], q[0])) y0 = p[1] for xt in np.arange(x0 + 18, x1 - 10, 30.0): major.line([xt, xt + 20 * 0.9], [y0 + outward * 6, y0 + outward * 38], 3.4) # event horizons: the two diagonals for a_, b_ in ((pts[1], pts[4]), (pts[2], pts[5])): major.line([a_[0], b_[0]], [a_[1], b_[1]], 6.0) # bifurcation sphere, i0, i+- major.disc(CX, CY, 15) for tau, chi in [(0, PI), (0, -PI), (PI / 2, PI / 2), (PI / 2, -PI / 2), (-PI / 2, PI / 2), (-PI / 2, -PI / 2)]: x, y = screen(tau, chi) major.ring(x, y, 17, 5.5) # ---- free-fall worldlines + light cones --------------------------------------- eta = np.linspace(0.0, PI - 1e-7, 9000) tau, chi = geodesic(RHO0, eta) for sgn in (1, -1): x, y = screen(tau, sgn * chi) world.line(x, y, 9.0) # arrowheads (exterior and interior) for e_arrow in (0.95, 2.35): e0 = np.array([e_arrow - 0.02, e_arrow + 0.02]) t0, c0 = geodesic(RHO0, e0) xa, ya = screen(t0, sgn * c0) ex, ey = geodesic(RHO0, np.array([e_arrow])) xm, ym = screen(ex, sgn * ey) d = np.array([xa[1] - xa[0], ya[1] - ya[0]]) d /= np.hypot(*d) n = np.array([-d[1], d[0]]) tip = np.array([xm[0], ym[0]]) + d * 26 base = np.array([xm[0], ym[0]]) - d * 20 world.polygon([tuple(tip), tuple(base + n * 19), tuple(base - n * 19)]) # light cones along the worldline for ec in ETA_CONES: et, ec_chi = geodesic(RHO0, np.array([ec])) xc, yc = screen(et[0], sgn * ec_chi[0]) for dx, dy in ((1, 1), (1, -1)): L = 58.0 / np.hypot(dx, dy) world.line([xc - dx * L, xc + dx * L], [yc - dy * L, yc + dy * L], 4.2) world.disc(xc, yc, 7.5) return minor.grab(), major.grab(), world.grab() # -------------------------------------------------------------------------- # Typography layers # -------------------------------------------------------------------------- def typography_layers(tf): title, labels, equations = Layer(), Layer(), Layer() hair = Layer() # hairline rules (drawn with the minor-line tier) # ---- title block ---------------------------------------------------------------- cx = W / 2 line1 = [("THE MAXIMALLY EXTENDED", "caps", 58, 0.46)] w1 = text_width(tf, line1) place_text(title, tf, line1, cx, 262) for sgn in (-1, 1): x0 = cx + sgn * (w1 / 2 + 70) hair.line([x0, x0 + sgn * 330], [262 - 21, 262 - 21], 4.0, cap="butt") place_text(title, tf, [("SCHWARZSCHILD SPACETIME", "caps", 168, 0.045)], cx, 470) place_text(title, tf, [("Penrose\u2013Carter conformal diagram of the Kruskal\u2013Szekeres extension", "italic", 66, 0.0)], cx, 596) hair.line([cx - 270, cx + 270], [668, 668], 4.0, cap="butt") # ---- diagram labels --------------------------------------------------------------- s2 = np.sqrt(0.5) I_SIZE, K_SIZE = 86, 78 for sgn in (1, -1): ha = "left" if sgn > 0 else "right" # script I labels at the edge midpoints for tsgn, sup in ((1, "+"), (-1, "\u2212")): xm, ym = screen(tsgn * PI / 4, sgn * 3 * PI / 4) lab = r"$\mathscr{I}^{%s}$" % ("+" if tsgn > 0 else "-") place_text(labels, tf, [(lab, "math", I_SIZE, 0)], xm + sgn * 74 * s2 + sgn * 18, ym - tsgn * 74 * s2, ha="center", va="center") # i0 , i+ , i- x, y = screen(0, sgn * PI) place_text(labels, tf, [(r"$i^{0}$", "math", K_SIZE, 0)], x + sgn * 86, y, ha="center", va="center") for tsgn, sup in ((1, "+"), (-1, "-")): x, y = screen(tsgn * PI / 2, sgn * PI / 2) place_text(labels, tf, [(r"$i^{%s}$" % sup, "math", K_SIZE, 0)], x + sgn * 10, y - tsgn * 82, ha="center", va="center") # singularity captions for tsgn, word in ((1, "FUTURE SINGULARITY"), (-1, "PAST SINGULARITY")): _, y = screen(tsgn * PI / 2, 0) pieces = [(word, "caps", 38, 0.30), (r"$r=0$", "math", 54, 0)] place_text(labels, tf, pieces, CX, y - tsgn * 76, va="center", gap=34) # region numerals and captions for (tau, chi, num, cap) in [(0.0, 1.78, "I", "OUR UNIVERSE"), (0.0, -1.78, "III", "ANOTHER UNIVERSE"), (0.62, 0.0, "II", "BLACK HOLE"), (-0.62, 0.0, "IV", "WHITE HOLE")]: x, y = screen(tau, chi) place_text(labels, tf, [(num, "italic", 150, 0.0)], x, y - 20, va="center") place_text(labels, tf, [(cap, "caps", 32, 0.34)], x, y + 74, va="center") # horizon captions, set along the diagonals for (tau, chi, rot, off, text) in [(1.00, 1.00, 45, (1, 1), "FUTURE HORIZON"), (-1.00, 1.00, -45, (1, -1), "PAST HORIZON"), (1.00, -1.00, -45, (-1, 1), "FUTURE HORIZON"), (-1.00, -1.00, 45, (-1, -1), "PAST HORIZON")]: x, y = screen(tau, chi) d = 34 * s2 place_text(labels, tf, [(text, "caps", 30, 0.28), (r"$r=2M$", "math", 40, 0)], x + off[0] * d, y + off[1] * d, rot=rot, va="center", gap=26) # observer captions x, y = screen(0.0, 1.964) place_text(labels, tf, [("free fall from rest", "italic", 40, 0.0), (r"$r=3M$", "math", 42, 0)], x + 18, y + 190, gap=14, va="center", ha="left") # ---- bottom panel: equations --------------------------------------------------- cols = [ ("SCHWARZSCHILD METRIC", [r"$ds^{2}=-\left(1-\frac{2M}{r}\right)dt^{2}+\left(1-\frac{2M}{r}\right)^{-1}dr^{2}$", r"$+\ r^{2}\left(d\theta^{2}+\sin^{2}\theta\,d\varphi^{2}\right)$"]), ("KRUSKAL\u2013SZEKERES", [r"$\left(\frac{r}{2M}-1\right)e^{\,r/2M}=X^{2}-T^{2}$", r"$\tanh\frac{t}{4M}=\frac{T}{X}\qquad(r>2M)$"]), ("COMPACTIFICATION", [r"$T\pm X=\tan\frac{\tau\pm\chi}{2}$", r"$\mathscr{I}^{\pm}:\ \tau\pm|\chi|=\pm\pi\qquad r=0:\ \tau=\pm\frac{\pi}{2}$"]), ] col_x = [CX - 1340, CX, CX + 1340] for (head, eqs), x in zip(cols, col_x): hw = text_width(tf, [(head, "caps", 34, 0.26)]) place_text(labels, tf, [(head, "caps", 34, 0.26)], x, 3016) hair.line([x - hw / 2, x + hw / 2], [3050, 3050], 3.6, cap="butt") for k, eq in enumerate(eqs): size = 58 while text_width(tf, [(eq, "math", size, 0)]) > 1240: size -= 2 place_text(equations, tf, [(eq, "math", size, 0)], x, 3185 + k * 138, va="center") # ---- legend --------------------------------------------------------------------------- ly = 3560 hair.line([CX - 1500, CX + 1500], [ly - 92, ly - 92], 3.2, cap="butt") items = [("solid", [(r"$r=\mathrm{const}$", "math", 46, 0)]), ("dash", [(r"$t=\mathrm{const}$", "math", 46, 0)]), ("world", [("free-fall geodesic", "italic", 44, 0.0)]), ("cone", [("light cone", "italic", 44, 0.0)])] widths = [150 + 24 + text_width(tf, it[1]) for it in items] spacing = 150 x = CX - (sum(widths) + spacing * (len(items) - 1)) / 2 for (kind, pieces), w_ in zip(items, widths): xs0, xs1 = x, x + 150 if kind == "solid": hair.line([xs0, xs1], [ly, ly], 3.6) elif kind == "dash": hair.line([xs0, xs1], [ly, ly], 3.2, dash=(26, 18)) elif kind == "world": hair.line([xs0, xs1], [ly, ly], 9.0) else: xc = (xs0 + xs1) / 2 for dx, dy in ((1, 1), (1, -1)): hair.line([xc - dx * 40, xc + dx * 40], [ly - dy * 40, ly + dy * 40], 4.2) hair.disc(xc, ly, 7.5) place_text(equations, tf, pieces, xs1 + 24, ly, ha="left", va="center") x += w_ + spacing # ---- footer ------------------------------------------------------------------------------- foot = [("16 777 216 COLOURS \u00b7 EACH USED EXACTLY ONCE", "caps", 32, 0.34)] fw = text_width(tf, foot) place_text(equations, tf, foot, CX, 3920) for sgn in (-1, 1): x0 = CX + sgn * (fw / 2 + 60) hair.line([x0, x0 + sgn * 520], [3920 - 12, 3920 - 12], 3.4, cap="butt") return title.grab(), labels.grab(), equations.grab(), hair.grab() # -------------------------------------------------------------------------- # Scalar fields # -------------------------------------------------------------------------- def hexagon_distance(px, py): """Distance in pixels from each point to the hexagon outline (outside points only matter).""" pts = screen_hex() d = np.full(px.shape, 1e9, dtype=np.float32) for i in range(6): ax_, ay_ = pts[i] bx_, by_ = pts[(i + 1) % 6] vx, vy = bx_ - ax_, by_ - ay_ t = np.clip(((px - ax_) * vx + (py - ay_) * vy) / (vx * vx + vy * vy), 0.0, 1.0) d = np.minimum(d, np.hypot(px - (ax_ + t * vx), py - (ay_ + t * vy))) return d def base_fields(): """Background / region luma key (light paper, darker physical shading) plus hue and saturation keys.""" luma = np.empty((H, W), dtype=np.float32) hue = np.empty((H, W), dtype=np.float32) sat = np.empty((H, W), dtype=np.float32) region = np.zeros((H, W), dtype=np.uint8) # 0 paper, 1 exterior I, 2 exterior III, 3 black hole, 4 white hole xs = np.arange(W, dtype=np.float64)[None, :] + 0.5 step = 128 for r0 in range(0, H, step): ys = np.arange(r0, min(r0 + step, H), dtype=np.float64)[:, None] + 0.5 tau = (CY - ys) / S chi = (xs - CX) / S inside = (np.abs(tau) < PI / 2) & (np.abs(chi) + np.abs(tau) < PI) # exact r(T, X) from the Lambert W function ta = np.clip((chi + tau) / 2, -PI / 2 + 1e-9, PI / 2 - 1e-9) tb = np.clip((chi - tau) / 2, -PI / 2 + 1e-9, PI / 2 - 1e-9) G = np.tan(ta) * np.tan(tb) rho = 1.0 + lambertw0(G / np.e) exterior = np.abs(chi) > np.abs(tau) pot = np.clip(1.0 / np.maximum(rho, 1e-6), 0.0, 1.0) # 2M / r : 1 at the horizon, 0 at infinity s_ = np.clip(1.0 - rho, 0.0, 1.0) # 0 at the horizon .. 1 at r = 0 # exteriors: darker (deeper "potential well") towards the horizon # interiors: darkest at the singularities fill = np.where(exterior, 0.52 - 0.20 * pot ** 0.7, 0.34 - 0.26 * s_ ** 1.4) rn = np.clip(np.hypot(xs - W / 2, ys - H / 2) / 2900.0, 0.0, 1.0) bg = 0.70 + 0.30 * rn ** 1.3 # paper: lightest in the corners d = hexagon_distance(np.broadcast_to(xs, (ys.shape[0], W)), np.broadcast_to(ys, (ys.shape[0], W))) shade = 0.10 * np.exp(-d / 140.0) # soft shadow hugging the diagram luma[r0:r0 + step] = np.where(inside, fill, bg - shade) reg = np.zeros(inside.shape, dtype=np.uint8) reg[inside & (chi > np.abs(tau))] = 1 reg[inside & (chi < -np.abs(tau))] = 2 reg[inside & (tau > np.abs(chi))] = 3 reg[inside & (tau < -np.abs(chi))] = 4 region[r0:r0 + step] = reg theta = (np.arctan2(ys - CY, xs - CX) / (2 * PI) + 0.5) hue[r0:r0 + step] = (theta + 0.12 * rn) % 1.0 sat[r0:r0 + step] = rn return luma, hue, sat, region # -------------------------------------------------------------------------- # Refinement: local colour swaps towards a smooth target # -------------------------------------------------------------------------- def smooth_target(img, ink, region, sigma): """Region-aware, ink-aware blur of the colour image (normalised convolution).""" tgt = img.astype(np.float32).copy() free = (ink < 0.004) for rid in range(5): m = ((region == rid) & free).astype(np.float32) if not m.any(): continue den = gaussian_blur(m, sigma) ok = (m > 0) & (den > 1e-3) for c in range(3): num = gaussian_blur(img[..., c].astype(np.float32) * m, sigma) ch = tgt[..., c] ch[ok] = num[ok] / den[ok] return tgt def refine(img, ink, region, iters, sigma, log): """Pairwise swaps of neighbouring pixels that bring both colours closer to their targets. Swapping keeps the set of colours unchanged, so every colour is still used exactly once. """ tgt = smooth_target(img, ink, region, sigma) col = img.astype(np.float32) # ink pixels keep their sharp colours: their target is themselves hard = ink >= 0.004 tgt[hard] = col[hard] rng = np.random.default_rng(7) sizes = [1, 2, 4, 8, 16, 32, 16, 8, 4, 2] for it in range(iters): d = sizes[(it // 2) % len(sizes)] axis = it % 2 ph = int(rng.integers(0, 2 * d)) n = ((W if axis == 1 else H) - ph) // (2 * d) if axis == 1: sl = (slice(None), slice(ph, ph + n * 2 * d)) shp = (H, n, 2, d, 3) else: sl = (slice(ph, ph + n * 2 * d), slice(None)) shp = (n, 2, d, W, 3) V = col[sl].reshape(shp) T = tgt[sl].reshape(shp) if axis == 1: A, B, TA, TB = V[:, :, 0], V[:, :, 1], T[:, :, 0], T[:, :, 1] else: A, B, TA, TB = V[:, 0], V[:, 1], T[:, 0], T[:, 1] gain = (((A - TA) ** 2).sum(-1) + ((B - TB) ** 2).sum(-1) - ((A - TB) ** 2).sum(-1) - ((B - TA) ** 2).sum(-1)) m = gain > 2.0 a = A[m].copy() A[m] = B[m] B[m] = a if it % 20 == 0: log(f"refine {it:3d}/{iters} swapped {m.mean() * 100:5.1f}%") return col.astype(np.uint8) # -------------------------------------------------------------------------- # Main # -------------------------------------------------------------------------- def main(): here = os.path.dirname(os.path.abspath(__file__)) ap = argparse.ArgumentParser(description="All-RGB Penrose diagram generator") ap.add_argument("-o", "--output", default=os.path.join(here, "penrose.png")) ap.add_argument("--serif", default="STIXGeneral", help="serif font family for the typography") ap.add_argument("--glow", type=float, default=0.05, help="strength of the soft glow around lines and type") ap.add_argument("--refine", type=int, default=24, help="local colour-swap passes (0 disables)") ap.add_argument("--sigma", type=float, default=6.0, help="blur radius of the smooth target used by the refinement") ap.add_argument("--verify", action="store_true", help="check that every colour appears exactly once") 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=12, help="log2 of the saturation block size used for colour matching") 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) tf = Typeface(args.serif) log("drawing geometry (analytic curves)") minor, major, world = geometry_layers() log("setting type") title, labels, equations, hair = typography_layers(tf) log("building scalar fields") luma, hue, sat, region = base_fields() yy = (np.arange(H, dtype=np.float32)[:, None] / H) xx = (np.arange(W, dtype=np.float32)[None, :] / W) ramp = 0.010 * (0.6 * xx + 0.4 * yy) # tiny smooth tie-break inside each tier text_all = np.maximum(np.maximum(title, labels), equations) # soft halo of light around the ink (lifts the paper a little right next to the strokes) ink = np.maximum(np.maximum(major, world), text_all) luma += args.glow * gaussian_blur(ink, 9.0) * 1.5 # knock thin lines out of a small halo around the type so the letters stay clean knock = np.clip(gaussian_blur(text_all, 7.0) * 4.0, 0.0, 1.0) minor_k = np.maximum(minor, hair) * (1.0 - knock) world_k = world * (1.0 - knock) def over(key, cov, level): key += cov * (level + ramp - key) over(luma, minor_k, 0.14) # thin grid lines over(luma, world_k, 0.07) # worldlines over(luma, major, 0.09) # outline / horizons over(luma, equations, 0.05) over(luma, labels, 0.03) over(luma, title, 0.00) # the very darkest colours go to the title ink_cov = np.maximum.reduce([minor_k, world_k, major, equations, labels, title]) ink_cov = np.maximum(ink_cov, ink * 0) # keep dtype del minor, major, world, title, labels, equations, hair, knock, minor_k, world_k, ink, text_all log("ordering pixels") op = order_pixels(luma.ravel().astype(np.float64), hue.ravel().astype(np.float64), G1) del luma, hue, sat 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.refine > 0: log("smoothing target and refining by local swaps") img = refine(img, ink_cov, region, args.refine, args.sigma, log) del ink_cov, region 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()
| Date | |
|---|---|
| Colors | 16,777,216 |
| Pixels | 16,777,216 |
| Dimensions | 4,096 × 4,096 |
| Bytes | 31,630,696 |
