ExperimentsFable 5.2 Python art (30 images)
Image 14 of 30
Strange attractor
The Python script
Open script.py ↗ (opens in a new tab)#!/usr/bin/env python3
"""14 Strange attractor.
A Clifford attractor: the simple rule
x' = sin(a*y) + c*cos(a*x), y' = sin(b*x) + d*cos(b*y)
is applied again and again to about three million points at once. Every visit
is counted per pixel (more than 600 million visits in total). The counts are
compressed with a logarithm (tone mapping) so that both the faint veils and the
bright folds are visible, and the colour comes from how far a point jumps in
one step.
Fable 5.2 Python art experiment: every pixel comes from the code below.
Run: .venv/bin/python scripts/14-strange-attractor.py
"""
import os, time
import numpy as np
from PIL import Image
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', '14-strange-attractor.png')
F32 = np.float32
rng = np.random.default_rng(1414)
A, B, C, D = 1.7, 1.7, 0.6, 1.2
NPTS = 3_000_000
WARM, ITERS = 70, 210
def step(x, y):
return np.sin(A * y) + C * np.cos(A * x), np.sin(B * x) + D * np.cos(B * y)
# ----------------------------------------------------------------------------
# 1. Pilot run: find the bounds and the range of jump lengths
# ----------------------------------------------------------------------------
x = rng.uniform(-1, 1, 200000); y = rng.uniform(-1, 1, 200000)
for _ in range(60):
x, y = step(x, y)
x2, y2 = step(x, y)
jump = np.hypot(x2 - x, y2 - y)
J0, J1 = np.percentile(jump, [1, 99])
xmin, xmax, ymin, ymax = x.min(), x.max(), y.min(), y.max()
# Fit into the frame with a margin, keep the aspect ratio.
scale = min(W * 0.90 / (xmax - xmin), H * 0.90 / (ymax - ymin))
ox = W / 2 - scale * (xmin + xmax) / 2
oy = H / 2 - scale * (ymin + ymax) / 2 + 10
# ----------------------------------------------------------------------------
# 2. Main run: count visits, and add up two colour signals per pixel
# ----------------------------------------------------------------------------
x = rng.uniform(-1, 1, NPTS); y = rng.uniform(-1, 1, NPTS)
count = np.zeros(W * H, np.float64)
sum_j = np.zeros(W * H, np.float64) # jump length
sum_a = np.zeros(W * H, np.float64) # direction of travel (up or down)
for i in range(WARM + ITERS):
xn, yn = step(x, y)
if i >= WARM:
# sub-pixel jitter gives clean anti-aliasing
px = (xn * scale + ox + rng.random(NPTS) - 0.5)
py = (H - (yn * scale + oy) + rng.random(NPTS) - 0.5)
xi = np.rint(px).astype(np.int64); yi = np.rint(py).astype(np.int64)
ok = (xi >= 0) & (xi < W) & (yi >= 0) & (yi < H)
flat = yi[ok] * W + xi[ok]
j = np.clip((np.hypot(xn - x, yn - y)[ok] - J0) / (J1 - J0), 0, 1)
a = (yn - y)[ok] > 0
count += np.bincount(flat, minlength=W * H)
sum_j += np.bincount(flat, weights=j, minlength=W * H)
sum_a += np.bincount(flat, weights=a, minlength=W * H)
x, y = xn, yn
print('iterations done %.1fs, %.0f million points' % (time.time() - T0, count.sum() / 1e6))
count = count.reshape(H, W); sum_j = sum_j.reshape(H, W); sum_a = sum_a.reshape(H, W)
# ----------------------------------------------------------------------------
# 3. Tone mapping and colour
# ----------------------------------------------------------------------------
# Smooth the colour signals a little more than the density, so colour is calm
# where there are few points.
cs = ndi.gaussian_filter(count, 1.6) + 1e-6
mj = ndi.gaussian_filter(sum_j, 1.6) / cs
ma = ndi.gaussian_filter(sum_a, 1.6) / cs
ref = np.percentile(count[count > 0], 99.7)
# Adaptive smoothing: thin veils have few points per pixel, so average them
# over a small neighbourhood; dense folds stay perfectly sharp.
soft = ndi.gaussian_filter(count, 1.0)
wgt = np.exp(-soft / (ref * 0.03))
count = wgt * soft + (1 - wgt) * count
v = np.log1p(count * (60.0 / ref)) / np.log1p(60.0) # 0..1 (and above for the hottest folds)
v = v.astype(F32)
def ramp(t, stops):
pos = [p for p, _ in stops]
cols = np.array([[int(c[i:i + 2], 16) / 255 for i in (1, 3, 5)] for _, c in stops], F32)
return np.stack([np.interp(t, pos, cols[:, i]) for i in range(3)], -1).astype(F32)
# Short jumps are blue and teal, long jumps are gold, rose and violet.
t = np.clip(mj, 0, 1)
t = (t - np.percentile(t[count > 2], 2)) / (np.percentile(t[count > 2], 98) - np.percentile(t[count > 2], 2))
t = np.clip(t, 0, 1).astype(F32)
hue = ramp(t, [(0.0, '#2456ff'), (0.22, '#16c8d8'), (0.45, '#5df2a8'), (0.62, '#ffd35a'),
(0.80, '#ff6a5a'), (1.0, '#d36bff')])
# The direction signal moves the colour a little toward warm or cool.
shift = (ma.astype(F32) - 0.5)[..., None]
hue = np.clip(hue + shift * np.array([0.22, 0.02, -0.22], F32), 0, 1)
sat = hue + (hue - hue.mean(-1, keepdims=True)) * 0.25 # a little more saturation
body = v[..., None] ** 1.32 * np.clip(sat, 0, 1.2) * 1.45
hot = np.clip(v - 0.74, 0, None)[..., None] ** 1.5 * 4.0 * (0.50 + 0.50 * hue) # folds burn toward white
img = body + hot
# Glow: light from the dense folds spreads into the dark.
glow = sum(np.stack([ndi.gaussian_filter(img[..., c], s) for c in range(3)], -1) * w
for s, w in ((3, 0.20), (12, 0.16), (45, 0.14), (140, 0.12)))
img = img + glow
# Background: deep blue-black with a soft vignette and faint star-dust.
yy, xx = np.mgrid[0:H, 0:W].astype(F32)
rad = np.hypot((xx - W / 2) / (W * 0.72), (yy - H / 2) / (H * 0.72))
bg = np.array([0.010, 0.014, 0.034], F32) * (1.25 - 0.9 * np.clip(rad, 0, 1.2) ** 2)[..., None]
img = img + np.clip(bg, 0, None)
img = 1 - np.exp(-img * 1.35) # soft shoulder
img = np.clip(img, 0, 1) ** 0.92
img += rng.standard_normal((H, W, 1)).astype(F32) * 0.004
Image.fromarray((np.clip(img, 0, 1) * 255 + 0.5).astype(np.uint8)).save(OUT)
print('saved', os.path.normpath(OUT), '%.1fs' % (time.time() - T0))

