ExperimentsFable 5.2 Python art (30 images)

Fractal deep zoom, an image drawn with Python code by Fable 5.2. Opens the full-size image in a new tab.
#!/usr/bin/env python3
"""15 Fractal deep zoom.

A view into the Mandelbrot set at about 30 million times magnification (the
frame is 0.0000001 units wide). For every pixel the script counts how fast the
point escapes (with a smooth, fractional count) and estimates the distance to
the set, which draws the thin filaments cleanly. The counts are mapped to an
oil-paint palette. The picture is then repainted with about 200,000 brush
strokes that follow the spirals, and the strokes get the light and shadow of
thick paint.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/15-fractal-deep-zoom.py
"""
import os, time, math
import numpy as np
from multiprocessing import Pool
from PIL import Image, ImageDraw
from scipy import ndimage as ndi

W, H = 1600, 2000
T0 = time.time()
HERE = os.path.dirname(os.path.abspath(__file__))
OUT = os.path.join(HERE, '..', 'images', '15-fractal-deep-zoom.png')
F32 = np.float32

# Location (found by exploring): a pinwheel of spirals near the top of the set.
CX, CY = -0.16070135 + 0.10e-7, 1.0375665 + 0.02e-7
WIDTH = 1.0e-7
MAXIT = 6000
SSF = 1.5                         # fractal is computed at 2400 x 3000 and scaled down
FW, FH = int(W * SSF), int(H * SSF)
RESC = 1.0e6                      # escape radius (large, for a smooth count)


def mandel_rows(args):
    """Smooth escape count and distance estimate for rows r0..r1."""
    r0, r1 = args
    xs = CX + (np.arange(FW) - FW / 2 + 0.5) * WIDTH / FW
    ys = CY - (np.arange(r0, r1) - FH / 2 + 0.5) * WIDTH / FW
    c = (xs[None, :] + 1j * ys[:, None]).ravel()
    n = c.size
    nu = np.full(n, float(MAXIT)); de = np.zeros(n)
    z = np.zeros(n, complex); dz = np.zeros(n, complex)
    idx = np.arange(n)
    for it in range(MAXIT):
        dz = 2 * z * dz + 1
        z = z * z + c
        if it % 4 == 3:
            a2 = z.real * z.real + z.imag * z.imag
            esc = a2 > RESC * RESC
            if esc.any():
                a = np.sqrt(a2[esc])
                nu[idx[esc]] = it + 1 - np.log2(np.log(a) / math.log(RESC))
                de[idx[esc]] = a * np.log(a) / np.abs(dz[esc])
                keep = ~esc
                z = z[keep]; dz = dz[keep]; c = c[keep]; idx = idx[keep]
                if idx.size == 0:
                    break
    return nu.reshape(r1 - r0, FW), de.reshape(r1 - r0, FW)


def hexc(s):
    s = s.lstrip('#')
    return np.array([int(s[i:i + 2], 16) for i in (0, 2, 4)], F32) / 255.0


def smoothstep(a, b, x):
    t = np.clip((x - a) / (b - a), 0, 1)
    return t * t * (3 - 2 * t)


def main():
    rng = np.random.default_rng(1515)

    # ------------------------------------------------------------------
    # 1. Fractal data (8 processes, in strips)
    # ------------------------------------------------------------------
    strips = [(r, min(r + 100, FH)) for r in range(0, FH, 100)]
    with Pool(8) as pool:
        parts = pool.map(mandel_rows, strips)
    nu = np.vstack([p[0] for p in parts]); de = np.vstack([p[1] for p in parts])
    inside = nu >= MAXIT
    print('fractal done %.1fs  inside %.4f  iterations %.0f..%.0f' % (
        time.time() - T0, inside.mean(), nu.min(), nu[~inside].max()))

    # ------------------------------------------------------------------
    # 2. Colour
    # ------------------------------------------------------------------
    v = np.log(nu)
    # Rank equalisation: every part of the palette gets the same share of the picture.
    flat = v.ravel()
    order = np.argsort(flat, kind='stable')
    rank = np.empty(flat.size, F32); rank[order] = np.linspace(0, 1, flat.size, dtype=F32)
    t = rank.reshape(v.shape)
    # Blend with the plain log count so that bands keep some of their true spacing.
    vn = ((v - v.min()) / (np.percentile(v, 99.5) - v.min())).astype(F32)
    t = 0.75 * t + 0.25 * np.clip(vn, 0, 1)

    STOPS = [(0.00, '#081530'), (0.12, '#17507f'), (0.24, '#58b3bf'), (0.35, '#f4ecd6'), (0.47, '#f2b441'),
             (0.60, '#d75a25'), (0.73, '#8a1c3c'), (0.87, '#331143'), (1.00, '#081530')]
    pos = [p for p, _ in STOPS]; cols = np.array([hexc(c) for _, c in STOPS])
    CYCLES, OFFSET = 1.55, 0.02
    ph = (t * CYCLES + OFFSET) % 1.0
    rgb = np.stack([np.interp(ph, pos, cols[:, i]) for i in range(3)], -1).astype(F32)
    # The crowded hearts of the spirals (highest counts) glow in one warm colour.
    # Without this, the palette would cycle faster than the pixels and turn to mud.
    core = smoothstep(0.86, 0.985, t)[..., None]
    rgb = rgb * (1 - core) + hexc('#fff0c4') * core

    # Distance estimate: darken close to the set, so filaments read as ink lines.
    px = WIDTH / FW
    dn = np.clip(de / px, 1e-3, 1e6)
    ink = smoothstep(-1.6, 0.6, np.log(dn)).astype(F32)            # 0 on a filament, 1 away from it
    ink = 1 - (1 - ink) * (1 - core[..., 0])                       # no ink inside the glowing cores
    rgb *= (0.42 + 0.58 * ink)[..., None]
    rgb[inside] = hexc('#050810')

    # Slope light: treat the smooth count as a height map.
    hmap = ndi.gaussian_filter(t, 1.5)
    gy, gx = np.gradient(hmap)
    slope = np.clip((-gx * 0.6 - gy * 0.8) * 60, -1, 1)
    rgb *= (1 + 0.22 * slope * ink)[..., None]

    # Scale down to the final size.
    src = np.stack([np.asarray(Image.fromarray(rgb[..., c]).resize((W, H), Image.LANCZOS)) for c in range(3)], -1)
    src = np.clip(src, 0, 1).astype(F32)
    print('colour done %.1fs' % (time.time() - T0))

    # ------------------------------------------------------------------
    # 3. Painterly finish: repaint with brush strokes
    # ------------------------------------------------------------------
    lum = src.mean(-1)
    ls = ndi.gaussian_filter(lum, 2.5)
    sy = ndi.sobel(ls, 0); sx = ndi.sobel(ls, 1)
    # Structure tensor: a smooth field of edge directions.
    jxx = ndi.gaussian_filter(sx * sx, 7); jyy = ndi.gaussian_filter(sy * sy, 7); jxy = ndi.gaussian_filter(sx * sy, 7)
    theta = 0.5 * np.arctan2(2 * jxy, jxx - jyy) + math.pi / 2       # along the edges
    detail = ndi.gaussian_filter(np.hypot(sx, sy), 3)
    detail /= np.percentile(detail, 95)

    PS = 2                                                          # strokes are drawn at 2x for smooth edges
    under = np.stack([ndi.gaussian_filter(src[..., c], 14) for c in range(3)], -1)
    canvas = Image.fromarray((np.clip(under, 0, 1) * 255).astype(np.uint8)).resize((W * PS, H * PS), Image.BILINEAR)
    height = Image.new('L', (W * PS, H * PS), 128)
    dc = ImageDraw.Draw(canvas); dh = ImageDraw.Draw(height)

    # (brush width, grid spacing, minimum detail, length factor)
    LAYERS = [(34, 17, 0.0, 3.2), (18, 9.5, 0.0, 3.2), (10, 5.5, 0.15, 3.0), (5, 3.0, 0.40, 3.2), (3, 2.1, 0.75, 3.5)]
    total = 0
    for bw, sp, dmin, lf in LAYERS:
        blur = np.stack([ndi.gaussian_filter(src[..., c], bw * 0.22) for c in range(3)], -1)
        gxs = np.arange(sp / 2, W, sp); gys = np.arange(sp / 2, H, sp)
        X, Y = np.meshgrid(gxs, gys)
        X = (X + rng.uniform(-sp / 2, sp / 2, X.shape)).ravel(); Y = (Y + rng.uniform(-sp / 2, sp / 2, Y.shape)).ravel()
        xi = np.clip(X.astype(int), 0, W - 1); yi = np.clip(Y.astype(int), 0, H - 1)
        keep = detail[yi, xi] >= dmin
        X, Y, xi, yi = X[keep], Y[keep], xi[keep], yi[keep]
        order = rng.permutation(X.size)
        th = theta[yi, xi] + rng.normal(0, 0.11, X.size)
        ln = bw * lf * rng.uniform(0.6, 1.25, X.size) / 2
        col = blur[yi, xi] * rng.uniform(0.93, 1.07, (X.size, 1)) + rng.normal(0, 0.012, (X.size, 3))
        col8 = (np.clip(col, 0, 1) * 255).astype(np.uint8)
        hv = rng.integers(60, 200, X.size)
        r = bw * PS / 2
        for k in order:
            x0 = (X[k] - math.cos(th[k]) * ln[k]) * PS; y0 = (Y[k] - math.sin(th[k]) * ln[k]) * PS
            x1 = (X[k] + math.cos(th[k]) * ln[k]) * PS; y1 = (Y[k] + math.sin(th[k]) * ln[k]) * PS
            c = tuple(int(q) for q in col8[k]); hgt = int(hv[k])
            wpx = int(bw * PS)
            dc.line((x0, y0, x1, y1), fill=c, width=wpx)
            dc.ellipse((x0 - r, y0 - r, x0 + r, y0 + r), fill=c); dc.ellipse((x1 - r, y1 - r, x1 + r, y1 + r), fill=c)
            dh.line((x0, y0, x1, y1), fill=hgt, width=wpx)
            dh.ellipse((x0 - r, y0 - r, x0 + r, y0 + r), fill=hgt); dh.ellipse((x1 - r, y1 - r, x1 + r, y1 + r), fill=hgt)
        total += X.size
    print('strokes: %d  %.1fs' % (total, time.time() - T0))

    paint = np.asarray(canvas.resize((W, H), Image.LANCZOS), F32) / 255.0
    # Glaze: let some of the exact fractal show through the paint, most of all
    # where the detail is finest, so the spirals keep their sparkle.
    glaze = (0.22 + 0.33 * np.clip(detail, 0, 1))[..., None]
    paint = paint * (1 - glaze) + src * glaze
    hm = np.asarray(height.resize((W, H), Image.LANCZOS), F32) / 255.0

    # Bristle marks: fine noise stretched along the stroke direction (approximated
    # by mixing a horizontally and a vertically stretched noise field).
    nh = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), (0.7, 5)); nh /= nh.std()
    nv = ndi.gaussian_filter(rng.standard_normal((H, W)).astype(F32), (5, 0.7)); nv /= nv.std()
    wv = np.sin(theta) ** 2
    bristle = nh * (1 - wv) + nv * wv
    hm = ndi.gaussian_filter(hm, 0.9) + 0.035 * bristle
    hy, hx = np.gradient(hm)
    relief = np.clip((-hx * 0.62 - hy * 0.78) * 4.2, -0.30, 0.30)
    paint = paint * (1 + relief[..., None])
    paint += np.clip(relief, 0, 1)[..., None] * 0.05                      # small wet highlights

    # Canvas weave and a gentle colour lift.
    yy, xx = np.mgrid[0:H, 0:W].astype(F32)
    weave = 0.5 * np.sin(xx * 2.1) * np.sin(yy * 2.1)
    paint *= (1 + 0.018 * weave)[..., None]
    mean = paint.mean(-1, keepdims=True)
    paint = mean + (paint - mean) * 1.12
    paint = np.clip(paint * 1.04, 0, 1) ** 0.96
    Image.fromarray((np.clip(paint, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
    print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))


if __name__ == '__main__':
    main()