render_figures.py

render_figures.py (PY)
1#!/usr/bin/env python3
2"""
3Render publication-grade visual artifacts for the Chenciner-Montgomery
43-body figure-eight exploration:
5
6 1. fig8_kam_atlas.png — 2-panel MEGNO phase-space atlas (full soaring KAM
7 continent + zoomed throat around the figure-eight and its unstable twin).
8 2. fig8_geometry_and_bifurcations.svg — 2x2 vector dashboard:
9 (A) Exact D3 Steiner deltoid mass-stability region at L=0,
10 (B) 2,250x spin-stabilization explosion across L in [0, 0.40],
11 (C) Real-space choreography vs. broken-choreography twin & 25%-asymmetric
12 rotating rosette (m=(1,1,0.75)),
13 (D) Montgomery's shape sphere S^2 showing the figure-eight dodging the
14 3 equatorial binary collision poles and a chaotic slingshot escape.
15
16Pure Python + Pillow (zero numpy/scipy dependency).
17"""
18
19from __future__ import annotations
20
21import csv
22import math
23import struct
24from pathlib import Path
25from PIL import Image, ImageDraw, ImageFont
26
27HERE = Path(__file__).resolve().parent
28
29U0_EQ = 0.347116888118927
30W0_EQ = 0.532724945388030
31U_TWIN = 0.339407411990859
32W_TWIN = 0.536184978151423
33R_H8 = math.hypot(U0_EQ, W0_EQ)
34
35
36def load_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
37 candidates = (
38 [
39 "/usr/share/fonts/google-noto/NotoSans-Bold.ttf",
40 "/usr/share/fonts/noto/NotoSans-Bold.ttf",
41 "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf",
42 "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
43 ]
44 if bold
45 else [
46 "/usr/share/fonts/google-noto/NotoSans-Regular.ttf",
47 "/usr/share/fonts/noto/NotoSans-Regular.ttf",
48 "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
49 "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
50 ]
51 )
52 for p in candidates:
53 if Path(p).exists():
54 return ImageFont.truetype(p, size)
55 return ImageFont.load_default()
56
57
58def lerp_rgb(c1: tuple[int, int, int], c2: tuple[int, int, int], t: float) -> tuple[int, int, int]:
59 t = max(0.0, min(1.0, t))
60 return (
61 int(round(c1[0] + (c2[0] - c1[0]) * t)),
62 int(round(c1[1] + (c2[1] - c1[1]) * t)),
63 int(round(c1[2] + (c2[2] - c1[2]) * t)),
64 )
65
66
67def megno_color(outcome: int, t_esc: float, megno: float, max_t: float) -> tuple[int, int, int]:
68 if outcome == 0:
69 if megno < 1.85:
70 t = max(0.0, min(1.0, megno / 1.85))
71 return lerp_rgb((255, 245, 200), (245, 178, 52), t)
72 if megno <= 2.35:
73 if megno <= 2.02:
74 t = (megno - 1.85) / 0.17
75 return lerp_rgb((118, 232, 245), (28, 128, 210), t)
76 t = (megno - 2.02) / 0.33
77 return lerp_rgb((28, 128, 210), (16, 62, 138), t)
78 t = min(1.0, math.log1p(megno - 2.35) / math.log1p(47.65))
79 if t < 0.45:
80 return lerp_rgb((255, 126, 78), (218, 52, 108), t / 0.45)
81 return lerp_rgb((218, 52, 108), (112, 34, 118), (t - 0.45) / 0.55)
82
83 s = min(1.0, math.log1p(max(0.0, t_esc)) / math.log1p(max_t))
84 base = lerp_rgb((9, 12, 20), (54, 46, 86), s ** 1.15)
85 if outcome == 1:
86 return lerp_rgb(base, (34, 102, 128), 0.32 * s)
87 if outcome == 2:
88 return lerp_rgb(base, (124, 96, 38), 0.32 * s)
89 if outcome == 3:
90 return lerp_rgb(base, (124, 46, 88), 0.32 * s)
91 return base
92
93
94def render_megno_panel(bin_path: Path, max_t: float) -> tuple[Image.Image, tuple[float, float, float, float]]:
95 raw = bin_path.read_bytes()
96 W, H = struct.unpack_from("<ii", raw, 0)
97 u0, u1, w0, w1 = struct.unpack_from("<4d", raw, 8)
98 off = 40
99 img = Image.new("RGB", (W, H))
100 px = bytearray(W * H * 3)
101 idx = 0
102 for k in range(W * H):
103 out, t_esc, meg = struct.unpack_from("<B3xff", raw, off + k * 12)
104 r, g, b = megno_color(out, t_esc, meg, max_t)
105 px[idx] = r
106 px[idx + 1] = g
107 px[idx + 2] = b
108 idx += 3
109 img.frombytes(bytes(px))
110 return img, (u0, u1, w0, w1)
111
112
113def draw_dashed_polyline(
114 draw: ImageDraw.ImageDraw,
115 pts: list[tuple[float, float]],
116 fill: tuple[int, int, int],
117 width: int = 2,
118 dash: float = 8.0,
119 gap: float = 6.0,
120) -> None:
121 if len(pts) < 2:
122 return
123 drawing = True
124 rem = dash
125 for i in range(len(pts) - 1):
126 x0, y0 = pts[i]
127 x1, y1 = pts[i + 1]
128 seg = math.hypot(x1 - x0, y1 - y0)
129 if seg < 1e-9:
130 continue
131 ux, uy = (x1 - x0) / seg, (y1 - y0) / seg
132 pos = 0.0
133 while pos < seg - 1e-9:
134 step = min(rem, seg - pos)
135 if drawing:
136 draw.line(
137 [(x0 + ux * pos, y0 + uy * pos), (x0 + ux * (pos + step), y0 + uy * (pos + step))],
138 fill=fill,
139 width=width,
140 )
141 pos += step
142 rem -= step
143 if rem <= 1e-9:
144 drawing = not drawing
145 rem = dash if drawing else gap
146
147
148def build_kam_atlas_png() -> None:
149 wing_img, (wu0, wu1, ww0, ww1) = render_megno_panel(HERE / "atlas_wing.bin", 60.0)
150 thrt_img, (tu0, tu1, tw0, tw1) = render_megno_panel(HERE / "atlas_throat.bin", 100.0)
151
152 PW, PH = 1000, 440
153 wing_panel = wing_img.resize((PW, PH), Image.Resampling.BICUBIC)
154 thrt_panel = thrt_img.resize((PW, PH), Image.Resampling.BICUBIC)
155
156 CW, CH = 1140, 1140
157 canvas = Image.new("RGB", (CW, CH), (11, 14, 21))
158 draw = ImageDraw.Draw(canvas)
159
160 f_title = load_font(22, bold=True)
161 f_sub = load_font(13, bold=False)
162 f_pt = load_font(15, bold=True)
163 f_lbl = load_font(12, bold=False)
164 f_sm = load_font(11, bold=False)
165
166 draw.text((78, 18), "Why the Figure-Eight Survives: MEGNO Phase-Space Atlas (L = 0)", fill=(238, 244, 255), font=f_title)
167 draw.text(
168 (78, 47),
169 "Equal-mass Euler collinear velocity slice r1=(1,0), r2=(-1,0), r3=(0,0), v1=v2=(u,w), v3=(-2u,-2w) | DOPRI5 variational MEGNO",
170 fill=(148, 162, 186),
171 font=f_sub,
172 )
173
174 panels = [
175 ("A. Full Soaring KAM Continent (60 periods, 1000x480 orbits)", wing_panel, (wu0, wu1, ww0, ww1), (78, 96), True),
176 ("B. Zoom into the Narrow Throat & Broken-Choreography Twin (100 periods, 840x400 orbits)", thrt_panel, (tu0, tu1, tw0, tw1), (78, 600), False),
177 ]
178
179 for title, pimg, (u0, u1, w0, w1), (ox, oy), is_wide in panels:
180 draw.text((ox, oy - 24), title, fill=(224, 232, 246), font=f_pt)
181 canvas.paste(pimg, (ox, oy))
182 draw.rectangle([ox - 1, oy - 1, ox + PW, oy + PH], outline=(58, 70, 96), width=1)
183
184 def to_px(u: float, w: float) -> tuple[float, float]:
185 return (
186 ox + (u - u0) / (u1 - u0) * (PW - 1),
187 oy + (w1 - w) / (w1 - w0) * (PH - 1),
188 )
189
190 arc_pts = []
191 for k in range(300):
192 u = u0 + (u1 - u0) * k / 299.0
193 rem = R_H8 * R_H8 - u * u
194 if rem <= 0:
195 continue
196 w = math.sqrt(rem)
197 if w0 <= w <= w1:
198 arc_pts.append(to_px(u, w))
199 draw_dashed_polyline(draw, arc_pts, fill=(226, 234, 248), width=2, dash=7.0, gap=5.0)
200 if arc_pts:
201 lx, ly = arc_pts[int(len(arc_pts) * (0.14 if is_wide else 0.78))]
202 draw.text((lx + 8, ly - 16), "H = H8 (fixed energy)", fill=(232, 240, 252), font=f_sm)
203
204 if is_wide:
205 bx0, by0 = to_px(tu0, tw1)
206 bx1, by1 = to_px(tu1, tw0)
207 box_pts = [(bx0, by0), (bx1, by0), (bx1, by1), (bx0, by1), (bx0, by0)]
208 draw_dashed_polyline(draw, box_pts, fill=(255, 224, 130), width=2, dash=6.0, gap=4.0)
209 draw.text((bx1 + 6, by0 - 4), "Panel B zoom", fill=(255, 224, 130), font=f_sm)
210
211 fx, fy = to_px(U0_EQ, W0_EQ)
212 tx, ty = to_px(U_TWIN, W_TWIN)
213
214 r = 7
215 draw.ellipse([fx - r, fy - r, fx + r, fy + r], outline=(255, 255, 255), width=2)
216 draw.line([(fx - 12, fy), (fx - 4, fy)], fill=(255, 255, 255), width=2)
217 draw.line([(fx + 4, fy), (fx + 12, fy)], fill=(255, 255, 255), width=2)
218 draw.line([(fx, fy - 12), (fx, fy - 4)], fill=(255, 255, 255), width=2)
219 draw.line([(fx, fy + 4), (fx, fy + 12)], fill=(255, 255, 255), width=2)
220
221 d = 6
222 draw.polygon([(tx, ty - d), (tx + d, ty), (tx, ty + d), (tx - d, ty)], fill=(255, 96, 82), outline=(255, 255, 255))
223
224 if is_wide:
225 draw.rectangle([fx + 12, fy + 12, fx + 158, fy + 31], fill=(11, 14, 21), outline=(92, 112, 145), width=1)
226 draw.text((fx + 17, fy + 14), "Figure-8 (tau1=1.9972)", fill=(255, 255, 255), font=f_sm)
227 draw.rectangle([tx - 184, ty - 34, tx - 10, ty - 15], fill=(11, 14, 21), outline=(215, 102, 92), width=1)
228 draw.text((tx - 178, ty - 31), "Unstable twin (tau1=2.0084)", fill=(255, 166, 150), font=f_sm)
229 else:
230 draw.line([(fx + 9, fy + 8), (fx + 45, fy + 38)], fill=(255, 255, 255), width=1)
231 draw.rectangle([fx + 45, fy + 28, fx + 275, fy + 64], fill=(12, 16, 26), outline=(140, 170, 210), width=1)
232 draw.text((fx + 53, fy + 32), "Stable Figure-Eight (choreography)", fill=(255, 255, 255), font=f_sm)
233 draw.text((fx + 53, fy + 47), "u=0.34712, w=0.53272 | tau1=+1.9972", fill=(140, 224, 245), font=f_sm)
234
235 draw.line([(tx - 8, ty - 8), (tx - 45, ty - 42)], fill=(255, 132, 118), width=1)
236 draw.rectangle([tx - 310, ty - 74, tx - 45, ty - 36], fill=(12, 16, 26), outline=(240, 110, 96), width=1)
237 draw.text((tx - 302, ty - 70), "Unstable Broken-Choreography Twin", fill=(255, 168, 152), font=f_sm)
238 draw.text((tx - 302, ty - 54), "u=0.33941, w=0.53618 | tau1=+2.0084", fill=(230, 195, 190), font=f_sm)
239
240 nx = 7 if is_wide else 9
241 for k in range(nx):
242 val = u0 + (u1 - u0) * k / (nx - 1)
243 x = ox + PW * k / (nx - 1)
244 draw.line([(x, oy + PH), (x, oy + PH + 5)], fill=(120, 134, 160), width=1)
245 lbl = f"{val:.2f}" if is_wide else f"{val:.3f}"
246 draw.text((x - 16, oy + PH + 8), lbl, fill=(168, 180, 202), font=f_sm)
247 ny = 5
248 for k in range(ny):
249 val = w0 + (w1 - w0) * k / (ny - 1)
250 y = oy + PH - PH * k / (ny - 1)
251 draw.line([(ox - 5, y), (ox, y)], fill=(120, 134, 160), width=1)
252 lbl = f"{val:.2f}" if is_wide else f"{val:.3f}"
253 draw.text((ox - 46, y - 6), lbl, fill=(168, 180, 202), font=f_sm)
254 draw.text((ox + PW // 2 - 90, oy + PH + 25), "u (parallel Euler velocity)", fill=(184, 196, 218), font=f_lbl)
255 draw.text((10, oy + PH // 2 - 12), "w", fill=(184, 196, 218), font=f_pt)
256
257 ly = 1084
258 lx0, lw, lh = 78, 520, 16
259 for i in range(lw):
260 t = i / (lw - 1)
261 if t < 0.20:
262 col = megno_color(0, 100.0, 1.85 * (t / 0.20), 100.0)
263 elif t < 0.50:
264 col = megno_color(0, 100.0, 1.85 + 0.50 * ((t - 0.20) / 0.30), 100.0)
265 elif t < 0.78:
266 u = (t - 0.50) / 0.28
267 col = megno_color(0, 100.0, 2.35 + (math.exp(u * math.log1p(47.65)) - 1.0), 100.0)
268 else:
269 u = 1.0 - (t - 0.78) / 0.22
270 col = megno_color(1, (math.exp(u * math.log1p(100.0)) - 1.0), 50.0, 100.0)
271 draw.line([(lx0 + i, ly), (lx0 + i, ly + lh)], fill=col, width=1)
272 draw.rectangle([lx0 - 1, ly - 1, lx0 + lw, ly + lh], outline=(72, 84, 110), width=1)
273 draw.text((lx0, ly + 21), "Resonant core (Y<1.8)", fill=(245, 200, 100), font=f_sm)
274 draw.text((lx0 + 148, ly + 21), "KAM torus (Y~2.0)", fill=(108, 212, 238), font=f_sm)
275 draw.text((lx0 + 278, ly + 21), "Chaotic web (Y>3)", fill=(245, 118, 128), font=f_sm)
276 draw.text((lx0 + 414, ly + 21), "Hyperbolic escape", fill=(154, 162, 192), font=f_sm)
277
278 draw.text((lx0 + lw + 30, ly - 2), "At fixed energy H = H8 (dashed arc), the unstable twin", fill=(182, 194, 214), font=f_sm)
279 draw.text((lx0 + lw + 30, ly + 15), "pinches the KAM waist down to |dv| ~ 0.008.", fill=(182, 194, 214), font=f_sm)
280
281 out_path = HERE / "fig8_kam_atlas.png"
282 canvas.save(out_path, optimize=True)
283 print(f"Wrote {out_path} ({CW}x{CH})")
284
285
286def build_geometry_and_bifurcations_svg() -> None:
287 del_rows = list(csv.DictReader((HERE / "mass_deltoid_boundary.csv").open()))
288 rot_rows = list(csv.DictReader((HERE / "rotating_mass_window.csv").open()))
289
290 trajs: dict[str, list[dict[str, float]]] = {}
291 with (HERE / "trajectories.csv").open() as f:
292 for row in csv.DictReader(f):
293 lbl = row["label"]
294 trajs.setdefault(lbl, []).append({k: float(v) for k, v in row.items() if k != "label"})
295
296 svg: list[str] = []
297 W, H = 1000, 860
298 svg.append(f'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 {W} {H}" width="{W}" height="{H}">')
299 svg.append('<rect width="100%" height="100%" fill="#0b0e15"/>')
300 svg.append(
301 "<style>"
302 'text { font-family: "Noto Sans", "DejaVu Sans", sans-serif; }'
303 ".hdr { fill: #eef4ff; font-size: 18px; font-weight: 700; }"
304 ".hsub { fill: #93a3be; font-size: 11.5px; }"
305 ".pt { fill: #e6eefc; font-size: 13.5px; font-weight: 700; }"
306 ".ps { fill: #8c9bb6; font-size: 10px; }"
307 ".lbl { fill: #a6b4cc; font-size: 10px; }"
308 ".lblb { fill: #dce6f7; font-size: 10px; font-weight: 600; }"
309 ".ax { stroke: #36425a; stroke-width: 1; }"
310 ".gr { stroke: #1a2132; stroke-width: 1; }"
311 ".card { fill: #0f1420; stroke: #222c42; stroke-width: 1; rx: 8; }"
312 "</style>"
313 )
314
315 svg.append('<text x="24" y="30" class="hdr">Symmetry, Catastrophe Geometry &amp; Spin Stabilization of the Figure-Eight</text>')
316 svg.append(
317 '<text x="24" y="48" class="hsub">'
318 "Exact s=6 order-12 Gauss-Legendre monodromy &amp; DOPRI5 nonlinear dynamics (m1+m2+m3=3, G=1)"
319 "</text>"
320 )
321
322 for cx, cy, cw, ch in [(20, 62, 470, 382), (510, 62, 470, 382), (20, 462, 470, 382), (510, 462, 470, 382)]:
323 svg.append(f'<rect x="{cx}" y="{cy}" width="{cw}" height="{ch}" class="card"/>')
324
325 # =========================================================================
326 # PANEL A: Exact D3 Mass-Simplex Stability Deltoid at L = 0
327 # =========================================================================
328 ax_cx, ax_cy = 255.0, 260.0
329 scale_a = 1.48e6 # 8.06e-5 -> ~119 px
330 svg.append('<text x="36" y="86" class="pt">A. L = 0 Mass-Simplex Stability Deltoid</text>')
331 svg.append('<text x="36" y="102" class="ps">360-ray 3-body boundary vs. exact Steiner deltoid (ratio 2.9999 : 1)</text>')
332
333 r_edge = 2.68666913e-5
334 pr_fold = r_edge * scale_a
335 pr_cusp = 3.0 * r_edge * scale_a
336 svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy:.1f}" r="{pr_fold:.1f}" fill="none" stroke="#1e2840" stroke-dasharray="3,4"/>')
337 svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy:.1f}" r="{pr_cusp:.1f}" fill="none" stroke="#1e2840" stroke-dasharray="3,4"/>')
338 svg.append(f'<text x="{ax_cx + pr_fold + 8:.1f}" y="{ax_cy + 18:.1f}" class="ps">r_fold = 2.69e-5</text>')
339 svg.append(f'<text x="{ax_cx + pr_cusp * 0.68:.1f}" y="{ax_cy - pr_cusp * 0.78:.1f}" class="ps">r_cusp = 8.06e-5</text>')
340
341 for deg, label in [(90, "+m3 (fold)"), (270, "-m3 (cusp)"), (210, "+m2"), (30, "-m2"), (330, "+m1"), (150, "-m1")]:
342 rad_a = math.radians(deg)
343 x2 = ax_cx + 128.0 * math.cos(rad_a)
344 y2 = ax_cy - 128.0 * math.sin(rad_a)
345 svg.append(f'<line x1="{ax_cx:.1f}" y1="{ax_cy:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke="#232e47" stroke-width="1"/>')
346 lx = ax_cx + 135.0 * math.cos(rad_a)
347 ly = ax_cy - 135.0 * math.sin(rad_a) + (4 if deg != 270 else 9)
348 anc = "middle" if deg in (90, 270) else ("start" if math.cos(rad_a) > 0 else "end")
349 svg.append(f'<text x="{lx:.1f}" y="{ly:.1f}" text-anchor="{anc}" class="lbl">{label}</text>')
350
351 pts_comp = [f"{ax_cx + float(r['s1']) * scale_a:.2f},{ax_cy - float(r['s2']) * scale_a:.2f}" for r in del_rows]
352 svg.append(f'<polygon points="{" ".join(pts_comp)}" fill="#1b7ea8" fill-opacity="0.30" stroke="#38d4f0" stroke-width="2.2"/>')
353
354 pts_st = []
355 for j in range(361):
356 t = 2.0 * math.pi * j / 360.0
357 ds1 = r_edge * (2.0 * math.sin(t) - math.sin(2.0 * t))
358 ds2 = -r_edge * (2.0 * math.cos(t) + math.cos(2.0 * t))
359 pts_st.append(f"{ax_cx + ds1 * scale_a:.2f},{ax_cy - ds2 * scale_a:.2f}")
360 svg.append(f'<polyline points="{" ".join(pts_st)}" fill="none" stroke="#ffd166" stroke-width="1.4" stroke-dasharray="5,4"/>')
361
362 svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy:.1f}" r="3.5" fill="#ffffff"/>')
363 svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy - pr_fold:.1f}" r="4" fill="#ff6b6b" stroke="#fff" stroke-width="1"/>')
364 svg.append(f'<circle cx="{ax_cx:.1f}" cy="{ax_cy + pr_cusp:.1f}" r="4" fill="#ffd166" stroke="#fff" stroke-width="1"/>')
365
366 svg.append('<line x1="36" y1="418" x2="56" y2="418" stroke="#38d4f0" stroke-width="2.2"/>')
367 svg.append('<text x="62" y="422" class="lbl">Exact 3-body boundary</text>')
368 svg.append('<line x1="36" y1="433" x2="56" y2="433" stroke="#ffd166" stroke-width="1.5" stroke-dasharray="5,4"/>')
369 svg.append('<text x="62" y="437" class="lbl">Analytical Steiner deltoid</text>')
370 svg.append('<text x="476" y="437" text-anchor="end" class="lblb">dtheta = 0 identically (R_phi T/2 sym.)</text>')
371
372 # =========================================================================
373 # PANEL B: Spin Stabilization — Mass Window vs Angular Momentum L
374 # =========================================================================
375 bx0, bx1, by0, by1 = 568.0, 962.0, 134.0, 396.0
376 svg.append('<text x="526" y="86" class="pt">B. Spin Stabilization: 2,250x Wider Mass Window</text>')
377 svg.append('<text x="526" y="102" class="ps">Linearly stable m3 = 1 + delta (m1=m2=1) vs. angular momentum L_iso</text>')
378
379 # Non-overlapping legend strip right above Panel B plot box
380 for lx, txt, col in [
381 (568, "Fold / Pitchfork (tau1=+2)", "#ffd166"),
382 (718, "Krein collision", "#c084fc"),
383 (816, "Period-doubling (tau2=-2)", "#4ade80"),
384 ]:
385 svg.append(f'<circle cx="{lx}" cy="119" r="3.2" fill="{col}"/>')
386 svg.append(f'<text x="{lx + 6}" y="122.5" class="ps">{txt}</text>')
387
388 def b_xy(L: float, delta_pct: float) -> tuple[float, float]:
389 x = bx0 + (L / 0.41) * (bx1 - bx0)
390 y = by1 - ((delta_pct - (-32.0)) / 52.0) * (by1 - by0)
391 return x, y
392
393 for dp in [-30, -20, -10, 0, 10, 20]:
394 _, gy = b_xy(0.0, dp)
395 cls = "ax" if dp == 0 else "gr"
396 svg.append(f'<line x1="{bx0:.1f}" y1="{gy:.1f}" x2="{bx1:.1f}" y2="{gy:.1f}" class="{cls}"/>')
397 svg.append(f'<text x="{bx0 - 8:.1f}" y="{gy + 3.5:.1f}" text-anchor="end" class="lbl">{dp:+d}%</text>')
398 for Lv in [0.0, 0.1, 0.2, 0.3, 0.4]:
399 gx, _ = b_xy(Lv, 0.0)
400 svg.append(f'<line x1="{gx:.1f}" y1="{by0:.1f}" x2="{gx:.1f}" y2="{by1:.1f}" class="gr"/>')
401 svg.append(f'<text x="{gx:.1f}" y="{by1 + 15:.1f}" text-anchor="middle" class="lbl">{Lv:.1f}</text>')
402 svg.append(f'<text x="{0.5*(bx0+bx1):.1f}" y="{by1 + 32:.1f}" text-anchor="middle" class="lbl">Angular momentum L_iso (r1_iso = 1)</text>')
403 svg.append(f'<text x="524" y="{0.5*(by0+by1):.1f}" transform="rotate(-90 524 {0.5*(by0+by1):.1f})" text-anchor="middle" class="lbl">m3 - 1 (%)</text>')
404
405 env_L = [0.0] + [float(r["L_iso"]) for r in rot_rows] + [0.3995]
406 env_hi = [0.00403] + [100.0 * float(r["delta_max"]) for r in rot_rows] + [0.0]
407 env_lo = [-0.01209] + [100.0 * float(r["delta_min"]) for r in rot_rows] + [0.0]
408
409 poly_pts = [f"{b_xy(L, h)[0]:.1f},{b_xy(L, h)[1]:.1f}" for L, h in zip(env_L, env_hi)] + [
410 f"{b_xy(L, l)[0]:.1f},{b_xy(L, l)[1]:.1f}" for L, l in zip(reversed(env_L), reversed(env_lo))
411 ]
412 svg.append(f'<polygon points="{" ".join(poly_pts)}" fill="#20a4b8" fill-opacity="0.28" stroke="#38d4f0" stroke-width="2"/>')
413
414 b_colors = {"tau1>+2": "#ffd166", "fold": "#ff6b6b", "KREIN": "#c084fc", "tau2<-2": "#4ade80"}
415 for r in rot_rows:
416 Lv = float(r["L_iso"])
417 for val_k, rsn_k in [("delta_max", "reason_max"), ("delta_min", "reason_min")]:
418 px, py = b_xy(Lv, 100.0 * float(r[val_k]))
419 col = b_colors.get(r[rsn_k], "#ffffff")
420 svg.append(f'<circle cx="{px:.1f}" cy="{py:.1f}" r="3.3" fill="{col}" stroke="#0b0e15" stroke-width="0.8"/>')
421
422 sx_v, sy_v = b_xy(0.15, -25.0)
423 svg.append(f'<circle cx="{sx_v:.1f}" cy="{sy_v:.1f}" r="5.2" fill="#ffd166" stroke="#ffffff" stroke-width="1.5"/>')
424 svg.append(f'<text x="{sx_v + 9:.1f}" y="{sy_v + 4:.1f}" class="lblb">m3=0.75 (1,000 orbits OK!)</text>')
425
426 x0_l, y0_l = b_xy(0.0, 0.0)
427 svg.append(f'<circle cx="{x0_l:.1f}" cy="{y0_l:.1f}" r="4" fill="#ff6b6b" stroke="#fff" stroke-width="1"/>')
428 svg.append(f'<text x="{x0_l + 8:.1f}" y="{y0_l - 22:.1f}" class="lbl">L=0: 0.016%</text>')
429 svg.append(f'<line x1="{x0_l + 2:.1f}" y1="{y0_l - 4:.1f}" x2="{x0_l + 18:.1f}" y2="{y0_l - 18:.1f}" stroke="#ff6b6b" stroke-width="1"/>')
430
431 xj, yj = b_xy(0.115, -16.5)
432 svg.append(f'<text x="{xj - 6:.1f}" y="{yj:.1f}" text-anchor="end" class="ps" fill="#7be0f5">L~0.115</text>')
433 svg.append(f'<text x="{xj - 6:.1f}" y="{yj + 12:.1f}" text-anchor="end" class="ps" fill="#7be0f5">tau1&lt;2 jump</text>')
434
435 xc, _ = b_xy(0.3995, 0.0)
436 svg.append(f'<line x1="{xc:.1f}" y1="{by0:.1f}" x2="{xc:.1f}" y2="{by1:.1f}" stroke="#4ade80" stroke-dasharray="3,4" stroke-width="1.2"/>')
437 svg.append(f'<text x="{xc - 6:.1f}" y="{by1 - 44:.1f}" text-anchor="end" class="lbl" fill="#4ade80">L_crit=0.3995</text>')
438 svg.append(f'<text x="{xc - 6:.1f}" y="{by1 - 31:.1f}" text-anchor="end" class="ps" fill="#4ade80">(tau2=-2)</text>')
439
440 # =========================================================================
441 # PANEL C: Real-Space Orbits
442 # =========================================================================
443 svg.append('<text x="36" y="486" class="pt">C. Choreography vs. Broken Twin &amp; Rotating Asymmetric Triple</text>')
444 svg.append('<text x="36" y="502" class="ps">Left: L=0 equal-mass figure-8 (gold) vs. unstable twin (coral) | Right: m=(1,1,0.75), L=0.15</text>')
445
446 c1x, c1y, c1s = 143.0, 666.0, 82.0
447 ca, sa = math.cos(-0.24552), math.sin(-0.24552)
448
449 def rot_pt(x: float, y: float) -> tuple[float, float]:
450 return ca * x - sa * y, sa * x + ca * y
451
452 for bidx, col, dash in [(1, "#ff7864", "3,3"), (2, "#ff7864", "3,3"), (3, "#ff4d6d", "4,2")]:
453 pts = [f"{c1x + rot_pt(p[f'x{bidx}'], p[f'y{bidx}'])[0] * c1s:.1f},{c1y - rot_pt(p[f'x{bidx}'], p[f'y{bidx}'])[1] * c1s:.1f}" for p in trajs["twin"][::4]]
454 svg.append(f'<polyline points="{" ".join(pts)}" fill="none" stroke="{col}" stroke-width="1.3" stroke-dasharray="{dash}" opacity="0.85"/>')
455
456 pts_st8 = [f"{c1x + rot_pt(p['x1'], p['y1'])[0] * c1s:.1f},{c1y - rot_pt(p['x1'], p['y1'])[1] * c1s:.1f}" for p in trajs["stable"][::3]]
457 svg.append(f'<polyline points="{" ".join(pts_st8)}" fill="none" stroke="#ffd166" stroke-width="2.4"/>')
458 p0 = trajs["stable"][0]
459 for bidx, col in [(1, "#38d4f0"), (2, "#38d4f0"), (3, "#ffd166")]:
460 rx, ry = rot_pt(p0[f"x{bidx}"], p0[f"y{bidx}"])
461 svg.append(f'<circle cx="{c1x + rx * c1s:.1f}" cy="{c1y - ry * c1s:.1f}" r="4.2" fill="{col}" stroke="#0b0e15" stroke-width="1"/>')
462 svg.append('<text x="143" y="810" text-anchor="middle" class="lbl">L=0: Equal-mass choreography</text>')
463 svg.append('<text x="143" y="824" text-anchor="middle" class="ps">Twin splits body 3 off shared loop</text>')
464
465 svg.append('<line x1="258" y1="520" x2="258" y2="830" stroke="#1e273c" stroke-width="1"/>')
466
467 c2x, c2y, c2s = 374.0, 666.0, 73.0
468 for bidx, col, op, sw in [(1, "#38d4f0", 0.55, 1.0), (2, "#5b8def", 0.55, 1.0), (3, "#ffd166", 0.90, 1.3)]:
469 pts = [f"{c2x + p[f'x{bidx}'] * c2s:.1f},{c2y - p[f'y{bidx}'] * c2s:.1f}" for p in trajs["rot_asym"][::3]]
470 svg.append(f'<polyline points="{" ".join(pts)}" fill="none" stroke="{col}" stroke-width="{sw}" opacity="{op}"/>')
471 pr0 = trajs["rot_asym"][0]
472 for bidx, col in [(1, "#38d4f0"), (2, "#5b8def"), (3, "#ffd166")]:
473 svg.append(f'<circle cx="{c2x + pr0[f"x{bidx}"] * c2s:.1f}" cy="{c2y - pr0[f"y{bidx}"] * c2s:.1f}" r="4" fill="{col}" stroke="#0b0e15" stroke-width="1"/>')
474 svg.append('<text x="374" y="810" text-anchor="middle" class="lbl">m=(1, 1, 0.75), L=0.15 (5 periods)</text>')
475 svg.append('<text x="374" y="824" text-anchor="middle" class="ps">Precesses 142.5 deg/orbit; survives 1000+T</text>')
476
477 # =========================================================================
478 # PANEL D: Montgomery's Shape Sphere S^2
479 # =========================================================================
480 svg.append('<text x="526" y="486" class="pt">D. Montgomery&apos;s Shape Sphere S²</text>')
481 svg.append('<text x="526" y="502" class="ps">Figure-eight dodges all 3 equatorial binary collisions; chaos falls into one</text>')
482
483 sx, sy, sR = 745.0, 658.0, 126.0
484 az, el = math.radians(18.0), math.radians(22.0)
485 caz, saz, cel, sel = math.cos(az), math.sin(az), math.cos(el), math.sin(el)
486
487 def proj_s2(w1: float, w2: float, w3: float) -> tuple[float, float, float]:
488 x1 = -saz * w1 + caz * w2
489 y1 = caz * w1 + saz * w2
490 z1 = w3
491 X = sx + sR * x1
492 Y = sy - sR * (z1 * cel - y1 * sel)
493 Z = y1 * cel + z1 * sel
494 return X, Y, Z
495
496 svg.append(
497 '<defs><radialGradient id="sg" cx="38%" cy="32%" r="65%">'
498 '<stop offset="0%" stop-color="#1d2b48"/><stop offset="70%" stop-color="#101728"/><stop offset="100%" stop-color="#090d16"/>'
499 "</radialGradient></defs>"
500 )
501 svg.append(f'<circle cx="{sx:.1f}" cy="{sy:.1f}" r="{sR:.1f}" fill="url(#sg)" stroke="#39496b" stroke-width="1.4"/>')
502
503 def draw_s2_curve(coords: list[tuple[float, float, float]], stroke_f: str, stroke_b: str,
504 w_f: float, w_b: float, dash_f: str = "", dash_b: str = "3,3") -> None:
505 seg_pts: list[str] = []
506 seg_front: bool | None = None
507 for w1, w2, w3 in coords:
508 X, Y, Z = proj_s2(w1, w2, w3)
509 is_f = Z >= 0.0
510 if seg_front is not None and is_f != seg_front and len(seg_pts) >= 2:
511 st = stroke_f if seg_front else stroke_b
512 sw = w_f if seg_front else w_b
513 da = f' stroke-dasharray="{dash_f if seg_front else dash_b}"' if (dash_f if seg_front else dash_b) else ""
514 svg.append(f'<polyline points="{" ".join(seg_pts)}" fill="none" stroke="{st}" stroke-width="{sw}"{da}/>')
515 seg_pts = [seg_pts[-1]]
516 seg_pts.append(f"{X:.1f},{Y:.1f}")
517 seg_front = is_f
518 if len(seg_pts) >= 2 and seg_front is not None:
519 st = stroke_f if seg_front else stroke_b
520 sw = w_f if seg_front else w_b
521 da = f' stroke-dasharray="{dash_f if seg_front else dash_b}"' if (dash_f if seg_front else dash_b) else ""
522 svg.append(f'<polyline points="{" ".join(seg_pts)}" fill="none" stroke="{st}" stroke-width="{sw}"{da}/>')
523
524 eq_pts = [(math.cos(2 * math.pi * k / 180), math.sin(2 * math.pi * k / 180), 0.0) for k in range(181)]
525 draw_s2_curve(eq_pts, "#4c618a", "#25314a", 1.3, 0.9, "", "3,3")
526 for lon_deg in [0, 60, 120]:
527 lr = math.radians(lon_deg)
528 mer = [(math.cos(lr) * math.cos(t), math.sin(lr) * math.cos(t), math.sin(t))
529 for t in [-math.pi + 2 * math.pi * k / 120 for k in range(121)]]
530 draw_s2_curve(mer, "#23304a", "#182034", 0.8, 0.6, "", "2,3")
531
532 colls = [
533 (-1.0, 0.0, "r1=r2 (back)"),
534 (0.5, 0.5 * math.sqrt(3.0), "r2=r3"),
535 (0.5, -0.5 * math.sqrt(3.0), "r1=r3"),
536 ]
537 # Back collision marker behind front trajectories
538 for w1c, w2c, txt in colls:
539 X, Y, Z = proj_s2(w1c, w2c, 0.0)
540 if Z < 0:
541 svg.append(f'<circle cx="{X:.1f}" cy="{Y:.1f}" r="4.2" fill="#ff4d6d" stroke="#ffffff" stroke-width="0.9" opacity="0.50"/>')
542 svg.append(f'<text x="{X + 9:.1f}" y="{Y - 6:.1f}" text-anchor="start" class="ps" fill="#c97284">{txt}</text>')
543
544 ch_pts = [(p["w1"], p["w2"], p["w3"]) for p in trajs["chaos"][::3]]
545 draw_s2_curve(ch_pts, "#c084fc", "#5c397a", 1.15, 0.7, "", "2,3")
546
547 tw_pts = [(p["w1"], p["w2"], p["w3"]) for p in trajs["twin"][::3]]
548 draw_s2_curve(tw_pts, "#ff6b6b", "#7a3338", 1.5, 0.9, "4,2", "2,3")
549
550 st_pts = [(p["w1"], p["w2"], p["w3"]) for p in trajs["stable"][::3]]
551 draw_s2_curve(st_pts, "#ffd166", "#8c7238", 2.5, 1.3, "", "3,3")
552
553 for w3p, txt in [(1.0, "Lagrange (+1)"), (-1.0, "Lagrange (-1)")]:
554 X, Y, _ = proj_s2(0.0, 0.0, w3p)
555 svg.append(f'<circle cx="{X:.1f}" cy="{Y:.1f}" r="3.6" fill="#4ade80" stroke="#0b0e15" stroke-width="1"/>')
556 svg.append(f'<text x="{X + 10:.1f}" y="{Y + 4:.1f}" class="ps" fill="#7be8a2">{txt}</text>')
557
558 # Front collision markers on top
559 for w1c, w2c, txt in colls:
560 X, Y, Z = proj_s2(w1c, w2c, 0.0)
561 if Z >= 0:
562 svg.append(f'<circle cx="{X:.1f}" cy="{Y:.1f}" r="4.8" fill="#ff4d6d" stroke="#ffffff" stroke-width="1.2"/>')
563 dx = -10 if X < sx else 10
564 anc = "end" if X < sx else "start"
565 svg.append(f'<text x="{X + dx:.1f}" y="{Y + 4:.1f}" text-anchor="{anc}" class="lblb" fill="#ff8fa3">{txt}</text>')
566
567 svg.append('<line x1="532" y1="822" x2="554" y2="822" stroke="#ffd166" stroke-width="2.5"/>')
568 svg.append('<text x="560" y="826" class="lbl">Figure-8</text>')
569 svg.append('<line x1="622" y1="822" x2="644" y2="822" stroke="#ff6b6b" stroke-width="1.6" stroke-dasharray="4,2"/>')
570 svg.append('<text x="650" y="826" class="lbl">Twin</text>')
571 svg.append('<line x1="692" y1="822" x2="714" y2="822" stroke="#c084fc" stroke-width="1.4"/>')
572 svg.append('<text x="720" y="826" class="lbl">Chaotic escape</text>')
573 svg.append('<circle cx="820" cy="822" r="4" fill="#ff4d6d" stroke="#fff" stroke-width="1"/>')
574 svg.append('<text x="829" y="826" class="lbl">Binary collisions</text>')
575
576 svg.append("</svg>")
577 out_svg = HERE / "fig8_geometry_and_bifurcations.svg"
578 out_svg.write_text("\n".join(svg), encoding="utf-8")
579 print(f"Wrote {out_svg} ({W}x{H})")
580
581
582if __name__ == "__main__":
583 build_kam_atlas_png()
584 build_geometry_and_bifurcations_svg()
585