render_drums.py

render_drums.py (PY)
1#!/usr/bin/env python3
2"""
3Render high-resolution Chladni eigenfunction comparisons and spectral plots
4for the Gordon-Webb-Wolpert (1992) isospectral drums.
5
6Reads drum_solver outputs (or compiles & runs drum_solver.c if needed) and writes:
7 - gww_drums_chladni.png (4-mode x 2-drum Chladni nodal gallery at N=96)
8 - gww_nodal_and_convergence.svg (nodal-domain splits k=1..50 & O(h^4/3) vs O(h^2) convergence)
9
10Pure Python + Pillow (zero numpy/scipy dependency).
11"""
12
13from __future__ import annotations
14
15import math
16import struct
17import subprocess
18import tempfile
19from pathlib import Path
20from PIL import Image, ImageDraw, ImageFont
21
22HERE = Path(__file__).resolve().parent
23
24DRUM_A_TRIS = [
25 ((0, 0), (1, 0), (0, 1)),
26 ((0, 0), (-1, 0), (0, -1)),
27 ((1, -1), (1, -2), (0, -1)),
28 ((0, 0), (1, 0), (0, -1)),
29 ((1, -1), (1, 0), (0, -1)),
30 ((1, -1), (1, -2), (2, -1)),
31 ((2, -2), (1, -2), (2, -1)),
32]
33DRUM_B_TRIS = [
34 ((0, 0), (1, 0), (0, 1)),
35 ((0, 0), (-1, 0), (0, -1)),
36 ((1, 1), (1, 2), (0, 1)),
37 ((0, 0), (1, 0), (0, -1)),
38 ((1, 1), (1, 0), (0, 1)),
39 ((1, 1), (1, 2), (2, 1)),
40 ((0, 2), (1, 2), (0, 1)),
41]
42DRUM_A_POLY = [(1, 0), (0, 1), (0, 0), (-1, 0), (1, -2), (2, -2), (2, -1), (1, -1)]
43DRUM_B_POLY = [(0, 0), (-1, 0), (0, -1), (1, 0), (1, 1), (2, 1), (1, 2), (0, 2)]
44
45# Interior glued edges (shared by 2 triangles)
46def internal_edges(tris):
47 counts: dict[tuple[tuple[int, int], tuple[int, int]], int] = {}
48 for t in tris:
49 for k in range(3):
50 a, b = t[k], t[(k + 1) % 3]
51 key = (a, b) if a < b else (b, a)
52 counts[key] = counts.get(key, 0) + 1
53 return [e for e, c in counts.items() if c == 2]
54
55
56INT_A = internal_edges(DRUM_A_TRIS)
57INT_B = internal_edges(DRUM_B_TRIS)
58
59
60def load_font(size: int, bold: bool = False):
61 candidates = (
62 [
63 "/usr/share/fonts/google-noto/NotoSans-Bold.ttf",
64 "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf",
65 "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Bold.ttf",
66 ]
67 if bold
68 else [
69 "/usr/share/fonts/google-noto/NotoSans-Regular.ttf",
70 "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
71 "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Regular.ttf",
72 ]
73 )
74 for p in candidates:
75 if Path(p).exists():
76 return ImageFont.truetype(p, size)
77 return ImageFont.load_default()
78
79
80def diverging_color(val: float) -> tuple[int, int, int]:
81 """
82 Diverging blue (-) / charcoal (0) / warm gold-amber (+) palette with smooth gamma,
83 giving glowing high-contrast positive & negative vibration lobes separated by crisp nodal lines.
84 val in [-1, 1].
85 """
86 v = max(-1.0, min(1.0, val))
87 # Gentle nonlinear stretch so subtle lobes remain clearly readable
88 mag = abs(v) ** 0.72
89 if v >= 0.0:
90 # Warm gold / coral-orange positive lobe
91 stops = [
92 (0.00, (24, 28, 38)),
93 (0.25, (148, 86, 36)),
94 (0.60, (232, 152, 54)),
95 (1.00, (255, 232, 150)),
96 ]
97 else:
98 # Deep cobalt / electric cyan negative lobe
99 stops = [
100 (0.00, (24, 28, 38)),
101 (0.25, (34, 88, 154)),
102 (0.60, (66, 158, 236)),
103 (1.00, (186, 238, 255)),
104 ]
105 for k in range(len(stops) - 1):
106 t0, c0 = stops[k]
107 t1, c1 = stops[k + 1]
108 if mag <= t1:
109 f = (mag - t0) / (t1 - t0) if t1 > t0 else 0.0
110 return (
111 int(round(c0[0] + f * (c1[0] - c0[0]))),
112 int(round(c0[1] + f * (c1[1] - c0[1]))),
113 int(round(c0[2] + f * (c1[2] - c0[2]))),
114 )
115 return stops[-1][1]
116
117
118def load_mode_bin(path: Path):
119 with open(path, "rb") as f:
120 N, W, H, min_gx, min_gy, k1 = struct.unpack("<6i", f.read(24))
121 lam, = struct.unpack("<d", f.read(8))
122 grid = struct.unpack(f"<{W * H}d", f.read(8 * W * H))
123 return N, W, H, min_gx, min_gy, k1, lam, grid
124
125
126def draw_dashed_line(draw: ImageDraw.ImageDraw, p0, p1, color, dash=6, gap=5, width=1):
127 x0, y0 = p0
128 x1, y1 = p1
129 dist = math.hypot(x1 - x0, y1 - y0)
130 if dist < 1e-6:
131 return
132 ux, uy = (x1 - x0) / dist, (y1 - y0) / dist
133 s = 0.0
134 while s < dist:
135 e = min(dist, s + dash)
136 draw.line([(x0 + ux * s, y0 + uy * s), (x0 + ux * e, y0 + uy * e)], fill=color, width=width)
137 s += dash + gap
138
139
140def render_mode_tile(bin_path: Path, poly, int_edges, tile_w: int, tile_h: int, scale_px: float):
141 N, W, H, min_gx, min_gy, k1, lam, grid = load_mode_bin(bin_path)
142 # Bounding box in unit coordinates
143 xs = [p[0] for p in poly]
144 ys = [p[1] for p in poly]
145 cx = 0.5 * (min(xs) + max(xs))
146 cy = 0.5 * (min(ys) + max(ys))
147
148 # Peak amplitude for normalization (and ensure positive ground state)
149 maxv = 0.0
150 sum_signed = 0.0
151 for v in grid:
152 if not math.isnan(v):
153 if abs(v) > maxv:
154 maxv = abs(v)
155 sum_signed += v
156 sign = -1.0 if (k1 == 1 and sum_signed < 0.0) else 1.0
157 if maxv <= 0.0:
158 maxv = 1.0
159
160 CARD_BG = (11, 14, 21)
161 tile = Image.new("RGB", (tile_w, tile_h), CARD_BG)
162 pix = tile.load()
163
164 def to_px(x: float, y: float) -> tuple[float, float]:
165 return (tile_w * 0.5 + (x - cx) * scale_px, tile_h * 0.5 - (y - cy) * scale_px)
166
167 # Bilinear sample from grid + crisp Chladni zero-contour detection
168 def sample_grid(fx: float, fy: float) -> float | None:
169 gx = fx * N - min_gx
170 gy = fy * N - min_gy
171 ix = int(math.floor(gx))
172 iy = int(math.floor(gy))
173 if ix < 0 or iy < 0 or ix >= W - 1 or iy >= H - 1:
174 return None
175 tx = gx - ix
176 ty = gy - iy
177 v00 = grid[iy * W + ix]
178 v10 = grid[iy * W + ix + 1]
179 v01 = grid[(iy + 1) * W + ix]
180 v11 = grid[(iy + 1) * W + ix + 1]
181 # Treat NaN boundary neighbors as 0 (Dirichlet boundary condition!) only if inside polygon
182 # Check point-in-polygon via exact winding/even-odd test? Faster: if ALL 4 are NaN -> outside.
183 # Even cleaner: exact point-in-polygon check first!
184 c00 = 0.0 if math.isnan(v00) else v00
185 c10 = 0.0 if math.isnan(v10) else v10
186 c01 = 0.0 if math.isnan(v01) else v01
187 c11 = 0.0 if math.isnan(v11) else v11
188 return sign * ((1 - tx) * (1 - ty) * c00 + tx * (1 - ty) * c10 + (1 - tx) * ty * c01 + tx * ty * c11) / maxv
189
190 def point_in_poly(x: float, y: float) -> bool:
191 inside = False
192 n = len(poly)
193 j = n - 1
194 for i in range(n):
195 xi, yi = poly[i]
196 xj, yj = poly[j]
197 if ((yi > y) != (yj > y)) and (x < (xj - xi) * (y - yi) / (yj - yi) + xi):
198 inside = not inside
199 j = i
200 return inside
201
202 # Evaluate scalar field on pixel grid
203 field: list[float | None] = [None] * (tile_w * tile_h)
204 for py in range(tile_h):
205 y = cy + (tile_h * 0.5 - (py + 0.5)) / scale_px
206 ro = py * tile_w
207 for px in range(tile_w):
208 x = cx + ((px + 0.5) - tile_w * 0.5) / scale_px
209 if point_in_poly(x, y):
210 field[ro + px] = sample_grid(x, y)
211
212 # Shade pixels + highlight Chladni nodal lines (sign change across adjacent interior pixels)
213 for py in range(tile_h):
214 ro = py * tile_w
215 for px in range(tile_w):
216 v = field[ro + px]
217 if v is None:
218 continue
219 # Check for zero-crossing with right/down/left/up interior neighbors
220 nodal = False
221 if k1 > 1:
222 for dx, dy in ((1, 0), (-1, 0), (0, 1), (0, -1)):
223 nx, ny = px + dx, py + dy
224 if 0 <= nx < tile_w and 0 <= ny < tile_h:
225 nv = field[ny * tile_w + nx]
226 if nv is not None and ((v > 0.0 and nv <= 0.0) or (v < 0.0 and nv >= 0.0)):
227 # Only light up the side closer to zero for a crisp 1.5px nodal line
228 if abs(v) <= abs(nv) * 1.15:
229 nodal = True
230 break
231 if nodal:
232 pix[px, py] = (248, 250, 255)
233 else:
234 pix[px, py] = diverging_color(v)
235
236 draw = ImageDraw.Draw(tile)
237 # Faint dashed internal triangle creases
238 for a, b in int_edges:
239 draw_dashed_line(draw, to_px(a[0], a[1]), to_px(b[0], b[1]), (185, 195, 215), dash=4, gap=4, width=1)
240
241 # Crisp outer polygon boundary
242 pts_px = [to_px(x, y) for x, y in poly]
243 draw.polygon(pts_px, outline=(235, 240, 250))
244 for i in range(len(pts_px)):
245 draw.line([pts_px[i], pts_px[(i + 1) % len(pts_px)]], fill=(235, 240, 250), width=2)
246
247 return tile, lam
248
249
250def build_chladni_plate(prefix: str, out_png: Path):
251 spec = {}
252 with open(f"{prefix}_spectrum.tsv") as f:
253 f.readline()
254 for line in f:
255 p = line.strip().split("\t")
256 spec[int(p[0])] = (float(p[1]), int(p[7]), int(p[8]), float(p[10]))
257
258 modes = [
259 (1, "Mode k = 1 · Ground State", "Single positive lobe; hub A[3] holds 51%, B[1] = 0.08%"),
260 (4, "Mode k = 4 · First Nodal Split", "Drum B is Courant-sharp (4), Drum A is not (3)"),
261 (9, "Mode k = 9 · Tiled Base Triangle (5π²)", "Zero along every crease; O(h²), scale = 3"),
262 (20, "Mode k = 20 · Widest Split (6 vs 9)", "Identical pitch to 10⁻¹⁴, 3-domain gap"),
263 ]
264
265 tile_w, tile_h = 340, 320
266 scale_px = 86.0 # identical geometric scale for BOTH Drum A and Drum B!
267 pad_x = 24
268 gap_x = 18
269 top_hdr = 82
270 col_hdr = 52
271 row_gap = 22
272 left_lbl = 36
273 footer_h = 44
274
275 W = pad_x + left_lbl + 4 * tile_w + 3 * gap_x + pad_x
276 H = top_hdr + col_hdr + 2 * tile_h + row_gap + footer_h
277
278 BG = (8, 10, 15)
279 BORDER = (36, 44, 62)
280 FG = (234, 240, 250)
281 MUTED = (148, 160, 182)
282 ACCENT = (126, 186, 255)
283 GOLD = (248, 200, 104)
284
285 img = Image.new("RGB", (W, H), BG)
286 draw = ImageDraw.Draw(img)
287
288 f_title = load_font(22, bold=True)
289 f_sub = load_font(13, bold=False)
290 f_col = load_font(14, bold=True)
291 f_meta = load_font(12, bold=False)
292 f_badge = load_font(12, bold=True)
293 f_row = load_font(14, bold=True)
294
295 draw.text(
296 (pad_x, 16),
297 "Can You Hear the Shape of a Drum? Gordon-Webb-Wolpert Isospectral Polygons (N = 96)",
298 fill=FG,
299 font=f_title,
300 )
301 draw.text(
302 (pad_x, 46),
303 "Same area (3.5), same perimeter (6 + 3*sqrt(2)), identical Dirichlet spectrum to 10^-13 — yet 20/50 modes split into different Chladni nodal counts",
304 fill=MUTED,
305 font=f_sub,
306 )
307
308 y_rowA = top_hdr + col_hdr
309 y_rowB = y_rowA + tile_h + row_gap
310
311 # Row tags on left margin
312 draw.text((pad_x, y_rowA + tile_h // 2 - 20), "A", fill=ACCENT, font=load_font(22, bold=True))
313 draw.text((pad_x, y_rowB + tile_h // 2 - 20), "B", fill=GOLD, font=load_font(22, bold=True))
314
315 for ci, (k, title, note) in enumerate(modes):
316 x0 = pad_x + left_lbl + ci * (tile_w + gap_x)
317 lam, nA, nB, tscale = spec[k]
318 lam_d = lam / 4.0 # Driscoll scaling (leg = 2)
319
320 draw.text((x0 + 2, top_hdr + 2), title, fill=FG, font=f_col)
321 split_tag = f"SPLIT: {nA} vs {nB}" if nA != nB else f"matched: {nA} vs {nB}"
322 draw.text(
323 (x0 + 2, top_hdr + 21),
324 f"λ/4 = {lam_d:.4f} · {split_tag}",
325 fill=(GOLD if nA != nB else ACCENT),
326 font=f_meta,
327 )
328 draw.text((x0 + 2, top_hdr + 36), note, fill=MUTED, font=load_font(11, bold=False))
329
330 tileA, _ = render_mode_tile(Path(f"{prefix}_mode{k}_A.bin"), DRUM_A_POLY, INT_A, tile_w, tile_h, scale_px)
331 tileB, _ = render_mode_tile(Path(f"{prefix}_mode{k}_B.bin"), DRUM_B_POLY, INT_B, tile_w, tile_h, scale_px)
332
333 img.paste(tileA, (x0, y_rowA))
334 draw.rectangle([x0, y_rowA, x0 + tile_w - 1, y_rowA + tile_h - 1], outline=BORDER, width=1)
335 draw.text((x0 + 10, y_rowA + 8), f"Drum A · ν = {nA}", fill=FG, font=f_badge)
336
337 img.paste(tileB, (x0, y_rowB))
338 draw.rectangle([x0, y_rowB, x0 + tile_w - 1, y_rowB + tile_h - 1], outline=BORDER, width=1)
339 draw.text((x0 + 10, y_rowB + 8), f"Drum B · ν = {nB}", fill=FG, font=f_badge)
340
341 draw.text(
342 (pad_x, H - 28),
343 "Gold = positive lobe (+u) · Blue = negative lobe (-u) · White curves = Chladni nodal lines (u = 0) · Dashed lines = 7-triangle Fano tiling · Equal Euclidean scale across all panels",
344 fill=MUTED,
345 font=f_meta,
346 )
347
348 img.save(out_png, optimize=True)
349 print(f"Wrote {out_png} ({W}x{H})")
350
351
352def build_svg(work_dir: Path, out_svg: Path):
353 """2-panel SVG: (Left) Nodal domain counts nu_A(k) vs nu_B(k) for k=1..50 vs Courant bound;
354 (Right) Non-monotonic O(h^4/3) vs O(h^2) convergence of modes k=1,2,3 vs tiled mode k=9."""
355 spec96 = {}
356 with open(work_dir / "drum_N96_spectrum.tsv") as f:
357 f.readline()
358 for line in f:
359 p = line.strip().split("\t")
360 spec96[int(p[0])] = (float(p[1]) / 4.0, int(p[7]), int(p[8]), float(p[10]))
361
362 Ns = [16, 24, 32, 48, 64, 96]
363 conv = {k: [] for k in (1, 2, 3, 9)}
364 for N in Ns:
365 with open(work_dir / f"drum_N{N}_spectrum.tsv") as f:
366 f.readline()
367 for line in f:
368 p = line.strip().split("\t")
369 k = int(p[0])
370 if k in conv:
371 conv[k].append(float(p[1]) / 4.0)
372
373 # Driscoll (1997) / exact 5*pi^2/4 references
374 refs = {
375 1: 2.5379439998,
376 2: 3.6555097135,
377 3: 5.1755593562,
378 9: 5.0 * math.pi * math.pi / 4.0,
379 }
380
381 W, H = 980, 420
382 # Left plot box: x=[64..470], y=[64..355]
383 # Right plot box: x=[555..945], y=[64..355]
384 parts = [
385 f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}">',
386 '<rect width="100%" height="100%" fill="#0b0e15"/>',
387 '<style>',
388 'text { font-family: "Noto Sans", "DejaVu Sans", sans-serif; }',
389 '.t { fill: #eaf0fa; font-size: 15px; font-weight: 700; }',
390 '.s { fill: #94a0b6; font-size: 11px; }',
391 '.ax { stroke: #364058; stroke-width: 1; }',
392 '.gr { stroke: #1b2232; stroke-width: 1; }',
393 '.lbl { fill: #a8b4ca; font-size: 11px; }',
394 '</style>',
395 ]
396
397 # Left panel: Nodal domain counts k=1..50
398 lx0, lx1, ly0, ly1 = 62, 468, 68, 354
399 parts.append(f'<text x="{lx0}" y="30" class="t">Nodal Domain Counts ν(k): Hearing Fails, Seeing Splits</text>')
400 parts.append(f'<text x="{lx0}" y="48" class="s">First 50 Dirichlet modes (N=96): 20/50 splits stable across N=48..96</text>')
401
402 def lx(k): return lx0 + (k - 1) / 49.0 * (lx1 - lx0)
403 def ly(v): return ly1 - (v / 32.0) * (ly1 - ly0)
404
405 for v in (0, 5, 10, 15, 20, 25, 30):
406 y = ly(v)
407 parts.append(f'<line x1="{lx0}" y1="{y:.1f}" x2="{lx1}" y2="{y:.1f}" class="gr"/>')
408 parts.append(f'<text x="{lx0 - 8}" y="{y + 4:.1f}" text-anchor="end" class="lbl">{v}</text>')
409 for k in (1, 10, 20, 30, 40, 50):
410 x = lx(k)
411 parts.append(f'<line x1="{x:.1f}" y1="{ly0}" x2="{x:.1f}" y2="{ly1}" class="gr"/>')
412 parts.append(f'<text x="{x:.1f}" y="{ly1 + 16}" text-anchor="middle" class="lbl">{k}</text>')
413 parts.append(f'<rect x="{lx0}" y="{ly0}" width="{lx1 - lx0}" height="{ly1 - ly0}" fill="none" class="ax"/>')
414 parts.append(f'<text x="{(lx0+lx1)/2:.1f}" y="{ly1 + 36}" text-anchor="middle" class="lbl">Mode index k</text>')
415 parts.append(f'<text x="20" y="{(ly0+ly1)/2:.1f}" text-anchor="middle" transform="rotate(-90 20 {(ly0+ly1)/2:.1f})" class="lbl">Connected nodal domains ν(k)</text>')
416
417 # Courant bound line ν = k (clipped to ν <= 32)
418 parts.append(f'<line x1="{lx(1):.1f}" y1="{ly(1):.1f}" x2="{lx(32):.1f}" y2="{ly(32):.1f}" stroke="#4e5c78" stroke-dasharray="4 4" stroke-width="1.2"/>')
419 parts.append(f'<text x="{lx(21):.1f}" y="{ly(25):.1f}" class="s">Courant bound ν ≤ k</text>')
420
421 # Pleijel asymptotic line (2/j0)^2 * k ≈ 0.6917 k? No, wait: Pleijel is limsup <= 0.6917 k; draw vertical split bars + dots!
422 for k in range(1, 51):
423 _, nA, nB, tscale = spec96[k]
424 x = lx(k)
425 yA, yB = ly(nA), ly(nB)
426 if nA != nB:
427 parts.append(f'<line x1="{x:.1f}" y1="{yA:.1f}" x2="{x:.1f}" y2="{yB:.1f}" stroke="#ffffff" stroke-opacity="0.45" stroke-width="1.5"/>')
428 if tscale > 2.0:
429 # Tiled base-triangle mode diamond
430 parts.append(f'<circle cx="{x:.1f}" cy="{yA:.1f}" r="4.6" fill="none" stroke="#9ef0b0" stroke-width="1.5"/>')
431 parts.append(f'<circle cx="{x:.1f}" cy="{yA:.1f}" r="3.0" fill="#5aa8ff"/>')
432 parts.append(f'<circle cx="{x:.1f}" cy="{yB:.1f}" r="3.0" fill="#f5b952"/>')
433
434 # Annotate k=4, k=9, k=20, k=44
435 parts.append(f'<text x="{lx(4)+6:.1f}" y="{ly(4)-6:.1f}" class="s">k=4 (3 vs 4)</text>')
436 parts.append(f'<text x="{lx(20)+5:.1f}" y="{ly(9)-6:.1f}" class="s">k=20 (6 vs 9)</text>')
437 parts.append(f'<text x="{lx(44)-4:.1f}" y="{ly(28)-9:.1f}" text-anchor="end" class="s">k=44 tiled (28)</text>')
438
439 # Legend left
440 parts.append(f'<circle cx="{lx0+12}" cy="{ly0+16}" r="3.5" fill="#5aa8ff"/><text x="{lx0+21}" y="{ly0+20}" class="lbl">Drum A</text>')
441 parts.append(f'<circle cx="{lx0+82}" cy="{ly0+16}" r="3.5" fill="#f5b952"/><text x="{lx0+91}" y="{ly0+20}" class="lbl">Drum B</text>')
442 parts.append(f'<circle cx="{lx0+154}" cy="{ly0+16}" r="4.5" fill="none" stroke="#9ef0b0" stroke-width="1.5"/><text x="{lx0+164}" y="{ly0+20}" class="lbl">Tiled T₀ mode</text>')
443
444 # Right panel: Signed discretization error (lam_h - lam_true) / lam_true vs h = 1/N
445 rx0, rx1, ry0, ry1 = 556, 954, 68, 354
446 parts.append(f'<text x="{rx0}" y="30" class="t">Signed Error: +h⁴/³ Corner Singularity vs. -h² Stencil</text>')
447 parts.append(f'<text x="{rx0}" y="48" class="s">Modes k=2,3 cross zero non-monotonically; tiled k=9 has zero singularity</text>')
448
449 def rx(h): return rx0 + (h / 0.066) * (rx1 - rx0)
450 # Signed relative error in percent: [-1.2%, +0.3%]
451 ymin, ymax = -1.2, 0.35
452 def ry(pct): return ry1 - ((pct - ymin) / (ymax - ymin)) * (ry1 - ry0)
453
454 for pct in (-1.0, -0.5, 0.0, 0.25):
455 y = ry(pct)
456 cls = "ax" if pct == 0.0 else "gr"
457 parts.append(f'<line x1="{rx0}" y1="{y:.1f}" x2="{rx1}" y2="{y:.1f}" class="{cls}"/>')
458 parts.append(f'<text x="{rx0 - 8}" y="{y + 4:.1f}" text-anchor="end" class="lbl">{pct:+.2f}%</text>')
459 for N in (96, 48, 32, 24, 16):
460 x = rx(1.0 / N)
461 parts.append(f'<line x1="{x:.1f}" y1="{ry0}" x2="{x:.1f}" y2="{ry1}" class="gr"/>')
462 parts.append(f'<text x="{x:.1f}" y="{ry1 + 16}" text-anchor="middle" class="lbl">1/{N}</text>')
463 parts.append(f'<rect x="{rx0}" y="{ry0}" width="{rx1 - rx0}" height="{ry1 - ry0}" fill="none" class="ax"/>')
464 parts.append(f'<text x="{(rx0+rx1)/2:.1f}" y="{ry1 + 36}" text-anchor="middle" class="lbl">Grid spacing h = 1/N</text>')
465 parts.append(f'<text x="506" y="{(ry0+ry1)/2:.1f}" text-anchor="middle" transform="rotate(-90 506 {(ry0+ry1)/2:.1f})" class="lbl">Relative error (λ_h − λ_true) / λ_true</text>')
466
467 styles = {
468 1: ("#5aa8ff", "k=1 (+h⁴/³ dominates)"),
469 2: ("#f5b952", "k=2 (arch turnaround)"),
470 3: ("#ff7a90", "k=3 (arch turnaround)"),
471 9: ("#9ef0b0", "k=9 tiled (pure -h²)"),
472 }
473 for idx_m, k in enumerate((1, 2, 3, 9)):
474 col, lbl = styles[k]
475 pts_s = []
476 for N, v in zip(Ns, conv[k]):
477 pct = 100.0 * (v - refs[k]) / refs[k]
478 pts_s.append((rx(1.0 / N), ry(pct)))
479 # Include origin (0, 0)
480 d = f"M {rx(0):.1f},{ry(0):.1f} " + " ".join(f"L {x:.1f},{y:.1f}" for x, y in reversed(pts_s))
481 parts.append(f'<path d="{d}" fill="none" stroke="{col}" stroke-width="2.0"/>')
482 for x, y in pts_s:
483 parts.append(f'<circle cx="{x:.1f}" cy="{y:.1f}" r="3.2" fill="{col}"/>')
484 ly_leg = ry1 - 74 + idx_m * 17
485 parts.append(f'<line x1="{rx0+12}" y1="{ly_leg}" x2="{rx0+28}" y2="{ly_leg}" stroke="{col}" stroke-width="2.2"/>')
486 parts.append(f'<text x="{rx0+34}" y="{ly_leg+4}" class="lbl">{lbl}</text>')
487
488 parts.append("</svg>")
489 out_svg.write_text("\n".join(parts) + "\n")
490 print(f"Wrote {out_svg}")
491
492
493def main():
494 with tempfile.TemporaryDirectory(prefix="gww_drums_") as td:
495 work = Path(td)
496 exe = work / "drum_solver"
497 subprocess.run(
498 ["gcc", "-O3", "-march=native", "-Wall", "-Wextra", str(HERE / "drum_solver.c"), "-lm", "-o", str(exe)],
499 check=True,
500 )
501 for N in (16, 24, 32, 48, 64):
502 subprocess.run([str(exe), str(N), "50", str(work / f"drum_N{N}")], check=True)
503 subprocess.run([str(exe), "96", "50", str(work / "drum_N96"), "1,4,9,20"], check=True)
504 build_chladni_plate(str(work / "drum_N96"), HERE / "gww_drums_chladni.png")
505 build_svg(work, HERE / "gww_nodal_and_convergence.svg")
506
507
508if __name__ == "__main__":
509 main()
510