"""Generuje grafikę nagłówka strony kursu (assets/hero.*, assets/og.png, assets/favicon.png). Obraz jest *wynikiem obliczenia*: to baseny zbieżności metody Newtona (metody stycznych) dla wielomianu p(z) = z^3 - 1 na płaszczyźnie zespolonej. Każdy piksel z_0 to punkt startowy iteracji z_{k+1} = z_k - p(z_k) / p'(z_k) = z_k - (z_k^3 - 1) / (3 z_k^2), kolor mówi, do którego z trzech pierwiastków z jedynki trafiła iteracja, a jasność -- jak długo to trwało. Punkty, które zbiegają szybko, są ciemne; świecą punkty na granicy basenów, gdzie metoda „waha się” najdłużej. Trzy kolory to trzy światy z wykładu 1: numeryka (bursztyn), symbolika (indygo) i dowód formalny (zieleń). Uruchomienie (z katalogu głównego repozytorium): .venv/bin/python scripts/generate_hero.py """ from __future__ import annotations from pathlib import Path import numpy as np from PIL import Image, ImageDraw, ImageFont from scipy.ndimage import gaussian_filter ROOT = Path(__file__).resolve().parents[1] ASSETS = ROOT / "assets" # Kolory „trzech światów” (te same co w CSS strony). BG = np.array([11, 16, 32], dtype=float) # granat tła nagłówka WORLD_COLOURS = np.array( [ [245, 158, 11], # bursztyn -- numeryka [99, 102, 241], # indygo -- symbolika (CAS) [16, 185, 129], # zieleń -- dowód formalny ], dtype=float, ) ROOTS = np.exp(2j * np.pi * np.arange(3) / 3) # 1, e^{2πi/3}, e^{4πi/3} def newton_basins(width: int, height: int, centre: complex, half_width: float, max_iter: int = 80, tol: float = 1e-9): """Zwraca (indeks pierwiastka, gładki licznik iteracji) dla siatki punktów startowych.""" half_height = half_width * height / width xs = np.linspace(centre.real - half_width, centre.real + half_width, width) ys = np.linspace(centre.imag + half_height, centre.imag - half_height, height) z = xs[None, :] + 1j * ys[:, None] root_idx = np.full(z.shape, -1, dtype=np.int8) smooth = np.full(z.shape, float(max_iter)) active = np.ones(z.shape, dtype=bool) log_tol = np.log(tol) for k in range(1, max_iter + 1): za = z[active] with np.errstate(divide="ignore", invalid="ignore"): za = za - (za**3 - 1) / (3 * za**2) z[active] = za dist = np.abs(za[:, None] - ROOTS[None, :]) nearest = dist.argmin(axis=1) d = dist[np.arange(len(za)), nearest] done = d < tol if done.any(): idx = np.flatnonzero(active)[done] root_idx.flat[idx] = nearest[done] # Zbieżność kwadratowa: |e_k| ≈ |e_{k-1}|^2, więc log2(log|e_k| / log tol) # mierzy, „ile ułamka kroku” zostało -- licznik staje się ciągły. with np.errstate(divide="ignore"): frac = np.log2(np.maximum(np.log(np.maximum(d[done], 1e-300)) / log_tol, 1.0)) smooth.flat[idx] = k - frac active.flat[idx] = False if not active.any(): break return root_idx, smooth def render(width: int, height: int, centre: complex, half_width: float, supersample: int = 2) -> np.ndarray: W, H = width * supersample, height * supersample idx, smooth = newton_basins(W, H, centre, half_width) # Jasność: szybka zbieżność = ciemno, granica basenów = jasno. b = np.clip((smooth - 5.0) / 13.0, 0.0, 1.0) ** 1.25 # Nieliczne punkty bez zbieżności (np. trafiające w biegun z = 0) kolorujemy jak tło, # a lekkie rozmycie usuwa pojedyncze „drobinki” na skokach licznika iteracji. b = gaussian_filter(np.where(idx >= 0, b, 0.0), sigma=0.6 * supersample) colour = np.where(idx[..., None] >= 0, WORLD_COLOURS[np.maximum(idx, 0)], BG) base = BG + (colour - BG) * (0.07 + 0.93 * b[..., None]) # Delikatna poświata wokół granic. glow = gaussian_filter(b, sigma=9 * supersample)[..., None] img = base + 0.45 * glow * (colour - BG) img = np.clip(img, 0, 255) # Antyaliasing: uśrednienie bloków supersample×supersample. return img.reshape(height, supersample, width, supersample, 3).mean(axis=(1, 3)) def fade_left(img: np.ndarray, start: float, end: float) -> np.ndarray: """Wtapia lewą część obrazu w kolor tła (płynny krok smoothstep na odcinku [start, end]).""" w = img.shape[1] t = np.clip((np.arange(w) / (w - 1) - start) / (end - start), 0.0, 1.0) alpha = (t * t * (3 - 2 * t))[None, :, None] return BG + (img - BG) * alpha def to_uint8(img: np.ndarray, seed: int = 0) -> np.ndarray: """Kwantyzacja z ditheringiem — usuwa pasmowanie ciemnych, gładkich gradientów.""" rng = np.random.default_rng(seed) return np.clip(img + rng.uniform(-0.5, 0.5, img.shape), 0, 255).round().astype(np.uint8) def newton_orbit(z0: complex, steps: int = 12) -> list[complex]: pts = [z0] z = z0 for _ in range(steps): z = z - (z**3 - 1) / (3 * z**2) pts.append(z) return pts def to_pixel(z: complex, width: int, height: int, centre: complex, half_width: float): half_height = half_width * height / width x = (z.real - (centre.real - half_width)) / (2 * half_width) * (width - 1) y = ((centre.imag + half_height) - z.imag) / (2 * half_height) * (height - 1) return x, y def draw_orbit(im: Image.Image, z0: complex, centre: complex, half_width: float) -> None: """Rysuje trajektorię iteracji Newtona startującą z z0 (punkty + odcinki).""" width, height = im.size draw = ImageDraw.Draw(im, "RGBA") pts = [to_pixel(p, width, height, centre, half_width) for p in newton_orbit(z0)] scale = width / 2000 for (x0, y0), (x1, y1) in zip(pts, pts[1:]): draw.line([(x0, y0), (x1, y1)], fill=(255, 255, 255, 150), width=max(1, int(2 * scale))) for i, (x, y) in enumerate(pts): r = (7 if i == 0 else 4.5) * scale draw.ellipse([x - r, y - r, x + r, y + r], fill=(255, 255, 255, 230 if i == 0 else 190)) def find_font(size: int) -> ImageFont.FreeTypeFont | ImageFont.ImageFont: for name in ("/System/Library/Fonts/Supplemental/Arial Unicode.ttf", "/System/Library/Fonts/Helvetica.ttc", "/Library/Fonts/Arial Unicode.ttf", "DejaVuSans.ttf"): try: return ImageFont.truetype(name, size) except OSError: continue return ImageFont.load_default() def main() -> None: ASSETS.mkdir(exist_ok=True) # 1) Nagłówek strony: 2000×1250, prawa część kadru jest najważniejsza. centre, half_width = complex(-0.2, 0.0), 1.5 hero = Image.fromarray(to_uint8(fade_left(render(2000, 1250, centre, half_width, supersample=2), 0.0, 0.42))) # Opcjonalnie można dorysować trajektorię iteracji, np. # draw_orbit(hero, complex(0.5418251, -0.4161120), centre, half_width) # (start blisko punktu potrójnego granic: osiem skoków przed zbieżnością do z = 1). hero.save(ASSETS / "hero.jpg", quality=88, optimize=True, progressive=True) hero.save(ASSETS / "hero.webp", quality=84, method=6) # 2) Podgląd do udostępniania (Open Graph) 1200×630 z tytułem kursu. og = Image.fromarray(to_uint8(render(1200, 630, complex(-0.75, 0.55), 1.45, supersample=2))) shade = Image.new("RGBA", og.size, (0, 0, 0, 0)) ds = ImageDraw.Draw(shade) for x in range(820): # przyciemnienie lewej części pod tekst a = int(228 * (1 - x / 820) ** 1.2) ds.line([(x, 0), (x, og.size[1])], fill=(11, 16, 32, a)) og = Image.alpha_composite(og.convert("RGBA"), shade) d = ImageDraw.Draw(og) d.text((64, 190), "Komputerowe rozwiązywanie", font=find_font(54), fill=(248, 250, 252)) d.text((64, 256), "problemów matematycznych", font=find_font(54), fill=(248, 250, 252)) d.text((64, 346), "WMI UAM · semestr zimowy 2026/27", font=find_font(28), fill=(148, 163, 184)) d.text((64, 392), "Python · SymPy · SageMath · Lean", font=find_font(28), fill=(129, 140, 248)) og.convert("RGB").save(ASSETS / "og.png", optimize=True) # 3) Mała ikona (favicon) -- fragment tego samego obrazu. icon = Image.fromarray(to_uint8(render(128, 128, complex(0.0, 0.0), 1.3, supersample=2))) icon.save(ASSETS / "favicon.png", optimize=True) for p in ("hero.jpg", "hero.webp", "og.png", "favicon.png"): print(f"{p:12s} {(ASSETS / p).stat().st_size / 1024:8.1f} KiB") if __name__ == "__main__": main()