Thumbnail.

Buddhabrot

Description

The Buddhabrot is the probability distribution over the trajectories of points that escape the Mandelbrot fractal.

Made with Claude Sonnet 5.5

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

The Buddhabrot is the density plot of the *orbits* of points c that escape the
Mandelbrot iteration z -> z^2 + c.  Instead of colouring c, we colour every
point z that an escaping orbit passes through, so the picture shows where
doomed orbits like to travel.  Using three different iteration limits for the
red / green / blue channels gives the classic "Nebulabrot".

Pipeline
--------
1.  Density.  Importance-sampled orbits (a coarse escape-time map steers the
    samples towards the boundary of the set, each sample is weighted to keep
    the estimate unbiased), conjugate symmetry used to double every orbit,
    pure numpy.  Three histograms are kept: iteration limits 4000 / 400 / 40
    by default (red / green / blue).
2.  Smoothing.  The histograms are Gaussian-blurred and tone-mapped into a
    Nebulabrot target colour for every pixel.
3.  All-RGB assignment.  A bijection between pixels and the 2^24 colours that
    keeps all three colour dimensions smooth:
        * pixels and colours are each sorted by luma and cut into equal groups
        * inside a luma group they are sorted by hue and cut into sub-groups
        * inside a sub-group they are sorted by saturation
    and then matched rank-for-rank.  Brightness follows the density, hue
    follows the iteration depth, and no colour is used twice.

Usage
-----
    python buddhabrot.py                         # writes buddhabrot.png next to this script
    python buddhabrot.py --points 4000           # more orbit points (millions): smoother, slower
    python buddhabrot.py --workers 8             # use 8 processes
    python buddhabrot.py --density cache.npz     # save / reuse the density (tweak the look quickly)
    python buddhabrot.py --verify                # also checks every colour appears exactly once

Requires: numpy, Pillow.   Memory: about 1 GB plus ~0.8 GB per worker.
"""

import argparse
import multiprocessing as mp
import os
import sys
import time
from multiprocessing import shared_memory

import numpy as np
from PIL import Image

N = 4096                       # 4096 * 4096 == 2**24 == number of 24-bit colours
NN = N * N

# view window: real axis runs vertically (-Re up: the antenna points to the sky), imaginary axis horizontally
RE_TOP = 1.00
HALF = 1.50                    # half-height of the window in the complex plane
SCALE = N / (2 * HALF)         # pixels per unit

# sampling domain for c (upper half plane; the lower half is the mirror image)
CELL = 1.0 / 256
DOM_RE0, DOM_RE1, DOM_IM1 = -2.0, 2.0, 2.0
NX = int((DOM_RE1 - DOM_RE0) / CELL)
NY = int(DOM_IM1 / CELL)

BATCH = 400_000                  # c-values per batch
DEPOSIT_CHUNK = 65_536         # c-values per cache-friendly deposit chunk
FLUSH = 12_000_000             # buffered histogram entries before a flush


# --------------------------------------------------------------------------
# Escape times (vectorised, with cycle detection so interior points bail out)
# --------------------------------------------------------------------------
def _iterate(idx, cr, ci, zr, zi, sr, si, i0, i1, n_out):
    """Run iterations i0..i1 on the still-active orbits, recording escape iterations in n_out."""
    for i in range(i0, i1 + 1):
        t = zr * zr - zi * zi + cr
        zi = 2.0 * zr * zi + ci
        zr = t
        esc = (zr * zr + zi * zi) > 4.0
        if (i & (i - 1)) == 0:                      # Brent: remember z at powers of two
            sr, si = zr, zi
            drop = esc
        else:
            drop = esc | ((np.abs(zr - sr) + np.abs(zi - si)) < 1e-12)
        if esc.any():
            n_out[idx[esc]] = i
        if drop.any():
            keep = ~drop
            idx, cr, ci, zr, zi, sr, si = (a[keep] for a in (idx, cr, ci, zr, zi, sr, si))
            if idx.size == 0:
                break
    return idx, cr, ci, zr, zi, sr, si


def escape_times(cr, ci, limit, first=48, chunk=131072):
    """Iteration at which |z| first exceeds 2 (>=1), or -1 if it never does within `limit`.

    Interior points bail out early through cycle detection.  The first iterations run in
    cache-sized chunks; the few long-lived survivors are then iterated together.
    """
    total = cr.shape[0]
    n = np.full(total, -1, dtype=np.int32)
    first = min(first, limit)
    parts = []
    for s in range(0, total, chunk):
        e = min(s + chunk, total)
        z = np.zeros(e - s)
        parts.append(_iterate(np.arange(s, e), cr[s:e].copy(), ci[s:e].copy(), z, z.copy(),
                              z.copy(), z.copy(), 1, first, n))
    if limit > first:
        state = [np.concatenate([p[k] for p in parts]) for k in range(7)]
        if state[0].size:
            _iterate(*state, first + 1, limit, n)
    return n


def in_main_bulbs(x, y):
    q = (x - 0.25) ** 2 + y ** 2
    return (q * (q + (x - 0.25)) < 0.25 * y ** 2) | ((x + 1.0) ** 2 + y ** 2 < 0.0625)


def importance_map(limit, min_iter, alpha=0.5, floor=50.0):
    """Per-cell sampling probability (flattened, un-normalised) over the c-domain."""
    cx = DOM_RE0 + (np.arange(NX) + 0.5) * CELL
    cy = (np.arange(NY) + 0.5) * CELL
    CX, CY = np.meshgrid(cx, cy)
    n = escape_times(CX.ravel(), CY.ravel(), limit).reshape(NY, NX)
    m = np.where(n >= min_iter, n - 1, 0).astype(np.float32)
    # 5x5 max-dilation so cells touching the boundary are not starved
    pad = np.pad(m, 2)
    d = m.copy()
    for dy in range(5):
        for dx in range(5):
            d = np.maximum(d, pad[dy:dy + NY, dx:dx + NX])
    p = np.power(d, alpha) + floor ** alpha

    # cells that can never contribute: outside |c| <= 2, or wholly inside the cardioid / bulb
    far = np.hypot(CX, CY) > 2.0 + CELL
    h = CELL / 2
    inside = in_main_bulbs(CX, CY)
    for sx in (-h, h):
        for sy in (-h, h):
            inside &= in_main_bulbs(CX + sx, CY + sy)
    p[far | inside | (d == 0)] = 0.0              # d == 0: deep interior or beyond |c| = 2
    return p.ravel().astype(np.float64)


# --------------------------------------------------------------------------
# Orbit deposition
# --------------------------------------------------------------------------
class Sampler:
    def __init__(self, probs, limits, hist, flip, min_iter):
        self.cdf = np.cumsum(probs)
        self.cdf /= self.cdf[-1]
        self.w = np.zeros_like(probs)
        nz = probs > 0
        self.w[nz] = probs[nz].mean() / probs[nz]            # mean weight 1: histogram unit ~ one sample hit
        self.lim_r, self.lim_g, self.lim_b = limits          # 4000, 400, 40
        self.hist = hist                                      # (3, NN) float32: classes 0,1,2
        self.flip = flip
        self.min_iter = min_iter

    def batch(self, seed):
        rng = np.random.default_rng(seed)
        u = rng.random(BATCH)
        cell = np.minimum(np.searchsorted(self.cdf, u, side="right"), self.cdf.size - 1)
        cr = DOM_RE0 + ((cell % NX) + rng.random(BATCH)) * CELL
        ci = ((cell // NX) + rng.random(BATCH)) * CELL
        w = self.w[cell]

        n = escape_times(cr, ci, self.lim_r)
        ok = n >= self.min_iter
        cr, ci, w, n = cr[ok], ci[ok], w[ok], n[ok]
        if n.size == 0:
            return 0
        return self._deposit(cr, ci, w, n)

    def _deposit(self, cr, ci, w, nesc):
        order = np.argsort(-nesc, kind="stable")              # longest orbits first
        cr, ci, w, nesc = cr[order], ci[order], w[order].astype(np.float32), nesc[order]
        bufs = ([], [], [])
        wts = ([], [], [])
        state = [0, 0]                                         # buffered entries, points
        for s in range(0, nesc.size, DEPOSIT_CHUNK):          # cache-sized chunks
            e = min(s + DEPOSIT_CHUNK, nesc.size)
            self._deposit_chunk(cr[s:e], ci[s:e], w[s:e], nesc[s:e], bufs, wts, state)
        self._flush(bufs, wts)
        return state[1]

    def _deposit_chunk(self, cr, ci, w, nesc, bufs, wts, state):
        neg = -nesc
        c2 = int(np.count_nonzero(nesc > self.lim_g))         # red only
        c12 = int(np.count_nonzero(nesc > self.lim_b))        # red + green
        zr = np.zeros(cr.size)
        zi = np.zeros(cr.size)
        for i in range(1, int(nesc[0])):
            k = int(np.searchsorted(neg, -i, side="left"))    # orbits with more than i steps
            if k == 0:
                break
            a, b = zr[:k], zi[:k]
            t = a * a - b * b + cr[:k]
            zi[:k] = 2.0 * a * b + ci[:k]
            zr[:k] = t
            state[1] += k

            row = (RE_TOP - zr[:k]) * SCALE
            col = (zi[:k] + HALF) * SCALE
            if not self.flip:
                row = N - row
            r = row.astype(np.int32)
            c = col.astype(np.int32)
            bad = (r.view(np.uint32) >= N) | (c.view(np.uint32) >= N)
            idx1 = r * N + c
            idx2 = r * N + (N - 1 - c)                         # mirror (conjugate orbit)
            np.putmask(idx1, bad, NN)                          # NN is a dump bin
            np.putmask(idx2, bad, NN)

            for cls, (lo, hi) in enumerate(((c12, k), (c2, min(k, c12)), (0, min(k, c2)))):
                if hi <= lo:
                    continue
                bufs[cls].append(idx1[lo:hi])
                bufs[cls].append(idx2[lo:hi])
                ww = w[lo:hi]
                wts[cls].append(ww)
                wts[cls].append(ww)
                state[0] += 2 * (hi - lo)
            if state[0] >= FLUSH:
                self._flush(bufs, wts)
                state[0] = 0

    def _flush(self, bufs, wts):
        for cls in range(3):
            if bufs[cls]:
                idx = np.concatenate(bufs[cls])
                wt = np.concatenate(wts[cls])
                bc = np.bincount(idx, weights=wt, minlength=NN + 1)
                self.hist[cls] += bc[:NN].astype(np.float32)
                bufs[cls].clear()
                wts[cls].clear()


# --------------------------------------------------------------------------
# Multiprocessing glue
# --------------------------------------------------------------------------
_state = {}


def _init_worker(shm_name, slot_counter, probs, limits, flip, min_iter):
    shm = shared_memory.SharedMemory(name=shm_name)
    with slot_counter.get_lock():
        slot = slot_counter.value
        slot_counter.value += 1
    hist = np.ndarray((3, NN), dtype=np.float32, buffer=shm.buf, offset=slot * 3 * NN * 4)
    _state["shm"] = shm
    _state["sampler"] = Sampler(probs, limits, hist, flip, min_iter)


def _run_batch(seed):
    return _state["sampler"].batch(seed)


def compute_density(points_target, workers, limits, flip, min_iter, seed, log):
    log("importance map for the sampler")
    probs = importance_map(limits[0], min_iter)
    budget = int(points_target * 1e6)
    t0 = time.time()
    done = 0
    next_seed = seed * 1_000_003

    def report():
        el = time.time() - t0
        rate = done / max(el, 1e-9)
        eta = (budget - done) / max(rate, 1e-9)
        log(f"{done / 1e6:9.1f} M / {budget / 1e6:.0f} M orbit points   {rate / 1e6:5.1f} M/s   eta {eta:5.0f}s")

    if workers <= 1:
        hist = np.zeros((3, NN), dtype=np.float32)
        s = Sampler(probs, limits, hist, flip, min_iter)
        last = time.time()
        while done < budget:
            done += s.batch(next_seed)
            next_seed += 1
            if time.time() - last > 15:
                report()
                last = time.time()
        report()
        return hist

    shm = shared_memory.SharedMemory(create=True, size=workers * 3 * NN * 4)
    try:
        np.ndarray((workers, 3, NN), dtype=np.float32, buffer=shm.buf)[:] = 0
        counter = mp.Value("i", 0)
        with mp.Pool(workers, initializer=_init_worker,
                     initargs=(shm.name, counter, probs, limits, flip, min_iter)) as pool:
            pending = []
            finished = 0
            last = time.time()
            while True:
                # keep the workers busy, but never queue more than the remaining budget needs
                avg = done / finished if finished else None
                while len(pending) < 2 * workers and (
                        (avg is None and len(pending) < workers) or
                        (avg is not None and done + len(pending) * avg < budget)):
                    pending.append(pool.apply_async(_run_batch, (next_seed,)))
                    next_seed += 1
                still = []
                for r in pending:
                    if r.ready():
                        done += r.get()
                        finished += 1
                    else:
                        still.append(r)
                pending = still
                if time.time() - last > 15:
                    report()
                    last = time.time()
                if not pending and done >= budget:
                    break
                if not pending and finished:
                    continue                       # budget not met yet: loop queues more
                time.sleep(0.05)
            report()
        allh = np.ndarray((workers, 3, NN), dtype=np.float32, buffer=shm.buf)
        hist = allh.sum(axis=0)
    finally:
        shm.close()
        shm.unlink()
    return hist


# --------------------------------------------------------------------------
# Smoothing, tone mapping and the colour bijection
# --------------------------------------------------------------------------
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)


def adaptive_smooth(d, sigma0, target, max_sigma=64.0):
    """Blur each pixel just enough to average roughly `target` effective samples.

    Bright, well-sampled regions keep fine detail (sigma0); the faint outer haze,
    where the raw histogram is mostly shot noise, is smoothed much more strongly.
    Implemented as a blend between a ladder of Gaussian blurs of the same histogram.
    """
    sigmas = [sigma0]
    while sigmas[-1] < max_sigma:
        sigmas.append(sigmas[-1] * 2.0)
    blurs = [np.maximum(gaussian_blur(d, s), 0.0) for s in sigmas]
    # approximate number of samples averaged = blurred density * kernel area
    out = blurs[-1].copy()
    chosen = np.full(d.shape, float(len(sigmas) - 1), dtype=np.float32)
    for lvl in range(len(sigmas) - 2, -1, -1):
        area = 4.0 * np.pi * sigmas[lvl] ** 2
        # fractional level: how comfortably this scale already meets the target
        enough = np.clip(blurs[lvl] * area / target, 0.0, 1.0)
        chosen = np.where(enough >= 1.0, float(lvl), chosen)
    # smooth the choice itself so the transitions between scales are invisible
    chosen = gaussian_blur(chosen, sigma0 * 3.0)
    chosen = np.clip(chosen, 0.0, len(sigmas) - 1.0)
    lo = np.floor(chosen).astype(np.int32)
    hi = np.minimum(lo + 1, len(sigmas) - 1)
    frac = chosen - lo
    out = np.zeros_like(d)
    for lvl in range(len(sigmas)):
        wgt = np.where(lo == lvl, 1.0 - frac, 0.0) + np.where(hi == lvl, frac, 0.0)
        if lvl == len(sigmas) - 1:
            wgt = np.where(lo == lvl, 1.0, wgt)
        out += wgt.astype(np.float32) * blurs[lvl]
    return out


def tone(d, gamma, pct=99.6):
    pos = d[::13, ::7]
    pos = pos[pos > 0]
    ref = np.percentile(pos, pct) if pos.size else 1.0
    return np.clip(d / ref, 0.0, 1.0) ** gamma


def target_fields(hist, sigma, gamma, target, hue_sigma, vignette):
    """Per-pixel luma key, hue key, saturation key (all smooth, float64 in [0,1))."""
    h0, h1, h2 = hist
    raw = (h0 + h1 + h2, h0 + h1, h0)                         # R: deep, G: medium, B: shallow

    # luma: adaptively smoothed so the faint outer haze is not just shot noise
    tr, tg, tb = (tone(adaptive_smooth(d, sigma, target), gamma) for d in raw)

    # hue / saturation: only the large-scale colour balance matters -> heavy blur
    hr, hg, hb = (tone(gaussian_blur(d, hue_sigma), gamma) for d in raw)

    yy, xx = np.mgrid[0:N, 0:N].astype(np.float32)
    xx = (xx - N / 2) / (N / 2)
    yy = (yy - N / 2) / (N / 2)
    rad = np.hypot(xx, yy)
    ang = np.arctan2(yy, xx)

    # the radial term is a smooth tie-break: it turns the faint haze into a soft vignette
    luma = 0.30 * tr + 0.50 * tg + 0.20 * tb + vignette * (1.0 - rad / 1.6)
    vx = 2 * hr - hg - hb + 0.05 * np.cos(ang + 2.0 * rad)
    vy = np.sqrt(3.0) * (hg - hb) + 0.05 * np.sin(ang + 2.0 * rad)
    hue = (np.arctan2(vy, vx) / (2 * np.pi)) % 1.0
    mx = np.maximum(np.maximum(hr, hg), hb)
    mn = np.minimum(np.minimum(hr, hg), hb)
    sat = (mx - mn) / (mx + 0.05) + 0.1 * rad
    return (luma.ravel().astype(np.float64),
            np.clip(hue.ravel(), 0, 0.999999).astype(np.float64),
            sat.ravel().astype(np.float64))


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 grouped_order(luma, hue, sat, g1, g2):
    """Order 0..N-1 so that position p has: luma group p//g1, hue-sorted inside, then sat inside g2-blocks."""
    pos = np.arange(luma.size) // g1
    o = np.argsort(luma, kind="stable")
    o = o[np.argsort(pos + hue[o], kind="stable")]
    pos2 = np.arange(luma.size) // g2
    o = o[np.argsort(pos2 + sat[o] * 0.999999, kind="stable")]
    return o


# --------------------------------------------------------------------------
# Main
# --------------------------------------------------------------------------
def main():
    here = os.path.dirname(os.path.abspath(__file__))
    ap = argparse.ArgumentParser(description="All-RGB Buddhabrot generator")
    ap.add_argument("-o", "--output", default=os.path.join(here, "buddhabrot.png"))
    ap.add_argument("--points", type=float, default=1500.0, help="orbit points to deposit, in millions")
    ap.add_argument("--workers", type=int, default=max(1, min(4, (os.cpu_count() or 2) - 1)))
    ap.add_argument("--limits", type=int, nargs=3, default=(4000, 400, 40), metavar=("R", "G", "B"),
                    help="iteration limits for the red / green / blue channels")
    ap.add_argument("--min-iter", type=int, default=20,
                    help="ignore orbits that escape sooner than this (removes the diffuse haze)")
    ap.add_argument("--blur", type=float, default=1.0, help="Gaussian blur sigma in pixels")
    ap.add_argument("--target", type=float, default=1500.0,
                    help="effective samples averaged per pixel by the adaptive smoother (higher = smoother)")
    ap.add_argument("--hue-blur", type=float, default=14.0, help="blur sigma (pixels) for the hue field")
    ap.add_argument("--vignette", type=float, default=0.08,
                    help="strength of the smooth radial tie-break that calms the faint outer haze")
    ap.add_argument("--gamma", type=float, default=0.55, help="tone-mapping exponent (smaller = brighter shadows)")
    ap.add_argument("--flip", action="store_true", help="put +Re (the cardioid side) at the top instead")
    ap.add_argument("--seed", type=int, default=1)
    ap.add_argument("--density", default=None, help=".npz cache: reuse it if present, else compute and save it")
    ap.add_argument("--verify", action="store_true", help="check that every colour appears exactly once")
    args = ap.parse_args()

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

    if args.density and os.path.exists(args.density):
        log(f"loading density from {args.density}")
        z = np.load(args.density)
        hist = z["hist"]
    else:
        limits = tuple(sorted(args.limits, reverse=True))
        hist = compute_density(args.points, args.workers, limits, args.flip, args.min_iter, args.seed, log)
        if args.density:
            log(f"saving density to {args.density}")
            np.savez_compressed(args.density, hist=hist)
    hist = hist.reshape(3, N, N)

    log("smoothing and tone mapping")
    luma_p, hue_p, sat_p = target_fields(hist, args.blur, args.gamma, args.target, args.hue_blur, args.vignette)
    del hist

    log("ordering pixels")
    op = grouped_order(luma_p, hue_p, sat_p, 4096, 128)
    del luma_p, hue_p, sat_p

    log("ordering the 16,777,216 colours")
    luma_c, hue_c, sat_c = all_colours()
    oc = grouped_order(luma_c, hue_c, sat_c, 4096, 128)
    del luma_c, hue_c, sat_c

    log("assigning colours")
    img = np.empty((NN, 3), dtype=np.uint8)
    cr = (oc >> 16).astype(np.uint8)
    cg = ((oc >> 8) & 255).astype(np.uint8)
    cb = (oc & 255).astype(np.uint8)
    img[op, 0] = cr
    img[op, 1] = cg
    img[op, 2] = cb
    del op, oc, cr, cg, cb
    img = img.reshape(N, N, 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__":
    mp.freeze_support()
    main()

Author

ACJ
81 entries

Stats

Date
Colors16,777,216
Pixels16,777,216
Dimensions4,096 × 4,096
Bytes32,785,597