render_vega_disks.py

render_vega_disks.py (PY)
1#!/usr/bin/env python3
2"""
3Physically colored disk-resolved ray-traced renders of Vega (alpha Lyrae).
4=========================================================================
5Ray-traces the exact Roche equipotential surface Phi(x, y, z) = Phi_0, evaluates
6Espinosa Lara & Rieutord (2011) gravity darkening T_eff(theta) and Milne-Eddington
7wavelength-dependent gray radiative transfer I_lambda(T_eff, mu) across 380-780 nm,
8convolves with CIE 1931 2-deg color matching functions (Wyman-Sloan-Shirley 2013
9piecewise Gaussian fit), and converts XYZ -> linear sRGB -> sRGB gamma at matched
10exposure across all viewing inclinations.
11
12Pure Python + Pillow (zero numpy/scipy dependency).
13Writes vega_disks.png in the same directory.
14"""
15
16from __future__ import annotations
17
18import math
19from pathlib import Path
20from PIL import Image, ImageDraw, ImageFont
21
22from roche_vega import (
23 I_gray_lambda,
24 omega_from_Om_ratio,
25 roche_r,
26 surface_point,
27)
28
29
30# ---------------------------------------------------------------------------
31# 1. CIE 1931 2-deg color matching functions (Wyman, Sloan & Shirley 2013)
32# ---------------------------------------------------------------------------
33def cie_x_bar(lam_nm: float) -> float:
34 t1 = (lam_nm - 442.0) * (0.0624 if lam_nm < 442.0 else 0.0374)
35 t2 = (lam_nm - 599.8) * (0.0264 if lam_nm < 599.8 else 0.0323)
36 t3 = (lam_nm - 501.1) * (0.0490 if lam_nm < 501.1 else 0.0382)
37 return 0.362 * math.exp(-0.5 * t1 * t1) + 1.056 * math.exp(-0.5 * t2 * t2) - 0.065 * math.exp(-0.5 * t3 * t3)
38
39
40def cie_y_bar(lam_nm: float) -> float:
41 t1 = (lam_nm - 568.8) * (0.0213 if lam_nm < 568.8 else 0.0247)
42 t2 = (lam_nm - 530.9) * (0.0613 if lam_nm < 530.9 else 0.0322)
43 return 0.821 * math.exp(-0.5 * t1 * t1) + 0.286 * math.exp(-0.5 * t2 * t2)
44
45
46def cie_z_bar(lam_nm: float) -> float:
47 t1 = (lam_nm - 437.0) * (0.0845 if lam_nm < 437.0 else 0.0278)
48 t2 = (lam_nm - 459.0) * (0.0385 if lam_nm < 459.0 else 0.0725)
49 return 1.217 * math.exp(-0.5 * t1 * t1) + 0.681 * math.exp(-0.5 * t2 * t2)
50
51
52LAMS_NM = [380.0 + 5.0 * i for i in range(81)] # 380..780 nm in 5 nm steps
53CMF = [(lam * 1e-9, cie_x_bar(lam), cie_y_bar(lam), cie_z_bar(lam)) for lam in LAMS_NM]
54
55
56def xyz_from_T_mu(T_eff: float, mu: float) -> tuple[float, float, float]:
57 """Integrate Milne-Eddington emergent spectrum through CIE 1931 2-deg CMFs."""
58 X = Y = Z = 0.0
59 for i, (lam_m, xb, yb, zb) in enumerate(CMF):
60 w = 0.5 if (i == 0 or i == len(CMF) - 1) else 1.0
61 I = I_gray_lambda(lam_m, T_eff, mu)
62 X += w * I * xb
63 Y += w * I * yb
64 Z += w * I * zb
65 return X * 5.0, Y * 5.0, Z * 5.0
66
67
68def xyz_to_linear_srgb(X: float, Y: float, Z: float) -> tuple[float, float, float]:
69 r = 3.2404542 * X - 1.5371385 * Y - 0.4985314 * Z
70 g = -0.9692660 * X + 1.8760108 * Y + 0.0415560 * Z
71 b = 0.0556434 * X - 0.2040259 * Y + 1.0572252 * Z
72 return r, g, b
73
74
75def srgb_gamma(c: float) -> float:
76 if c <= 0.0:
77 return 0.0
78 if c >= 1.0:
79 return 1.0
80 if c <= 0.0031308:
81 return 12.92 * c
82 return 1.055 * (c ** (1.0 / 2.4)) - 0.055
83
84
85def teff_colormap(T: float, T_lo: float = 7000.0, T_hi: float = 10100.0) -> tuple[int, int, int]:
86 """Perceptually ordered thermal palette: amber (7,000 K) -> cream (9,100 K) -> ice blue (10,100 K)."""
87 stops = [
88 (0.00, (128, 38, 18)),
89 (0.32, (214, 112, 40)),
90 (0.60, (246, 202, 128)),
91 (0.76, (245, 242, 236)),
92 (0.90, (158, 208, 255)),
93 (1.00, (72, 148, 255)),
94 ]
95 t = max(0.0, min(1.0, (T - T_lo) / (T_hi - T_lo)))
96 for k in range(len(stops) - 1):
97 t0, c0 = stops[k]
98 t1, c1 = stops[k + 1]
99 if t <= t1:
100 f = (t - t0) / (t1 - t0) if t1 > t0 else 0.0
101 return (
102 int(round(c0[0] + f * (c1[0] - c0[0]))),
103 int(round(c0[1] + f * (c1[1] - c0[1]))),
104 int(round(c0[2] + f * (c1[2] - c0[2]))),
105 )
106 return stops[-1][1]
107
108
109# ---------------------------------------------------------------------------
110# 2. Precomputed lookup tables for fast exact ray-tracing
111# ---------------------------------------------------------------------------
112class SpectrumLUT:
113 def __init__(self, T_min: float = 5500.0, T_max: float = 10500.0, nT: int = 51, nMu: int = 41):
114 self.T_min = T_min
115 self.T_max = T_max
116 self.nT = nT
117 self.nMu = nMu
118 self.dT = (T_max - T_min) / (nT - 1)
119 self.dMu = 1.0 / (nMu - 1)
120 self.grid: list[list[tuple[float, float, float]]] = []
121 for i in range(nT):
122 T = T_min + i * self.dT
123 row = []
124 for j in range(nMu):
125 mu = max(1e-4, j * self.dMu)
126 row.append(xyz_from_T_mu(T, mu))
127 self.grid.append(row)
128
129 def lookup(self, T: float, mu: float) -> tuple[float, float, float]:
130 u = max(0.0, min(self.nT - 1.000001, (T - self.T_min) / self.dT))
131 v = max(0.0, min(self.nMu - 1.000001, mu / self.dMu))
132 i0 = int(u)
133 j0 = int(v)
134 fu = u - i0
135 fv = v - j0
136 g = self.grid
137 a = g[i0][j0]
138 b = g[i0 + 1][j0]
139 c = g[i0][j0 + 1]
140 d = g[i0 + 1][j0 + 1]
141 w00 = (1.0 - fu) * (1.0 - fv)
142 w10 = fu * (1.0 - fv)
143 w01 = (1.0 - fu) * fv
144 w11 = fu * fv
145 return (
146 w00 * a[0] + w10 * b[0] + w01 * c[0] + w11 * d[0],
147 w00 * a[1] + w10 * b[1] + w01 * c[1] + w11 * d[1],
148 w00 * a[2] + w10 * b[2] + w01 * c[2] + w11 * d[2],
149 )
150
151
152class StarProfileLUT:
153 """Tabulates ELR T_eff(theta) for a fixed rotation parameter w."""
154
155 def __init__(self, w: float, T_pole: float, nTh: int = 512):
156 self.w = w
157 self.T_pole = T_pole
158 self.nTh = nTh
159 self.half_pi = 0.5 * math.pi
160 self.dth = self.half_pi / (nTh - 1)
161 self.T_arr = []
162 for i in range(nTh):
163 th = i * self.dth
164 _, _, _, _, _, T_rel, _ = surface_point(th, w, model="elr")
165 self.T_arr.append(T_pole * T_rel)
166
167 def T_at_theta(self, theta: float) -> float:
168 th = math.pi - theta if theta > self.half_pi else theta
169 u = max(0.0, min(self.nTh - 1.000001, th / self.dth))
170 i0 = int(u)
171 f = u - i0
172 return (1.0 - f) * self.T_arr[i0] + f * self.T_arr[i0 + 1]
173
174
175# ---------------------------------------------------------------------------
176# 3. Exact orthographic Roche ray tracer
177# ---------------------------------------------------------------------------
178def roche_phi_minus_surf(x: float, y: float, z: float, w2: float, phi_surf: float) -> float:
179 """Signed Roche potential difference: negative inside the star, positive outside."""
180 r = math.sqrt(x * x + y * y + z * z)
181 if r < 1e-9:
182 return -1e9
183 return (-1.0 / r - 0.5 * w2 * (x * x + y * y)) - phi_surf
184
185
186def trace_pixel(
187 u: float,
188 v: float,
189 sin_i: float,
190 cos_i: float,
191 w2: float,
192 phi_surf: float,
193 star_lut: StarProfileLUT,
194 spec_lut: SpectrumLUT,
195) -> tuple[float, float, float, float, float] | None:
196 """Orthographic ray trace at sky-plane (u, v) in units of R_e."""
197 r2_sky = u * u + v * v
198 if r2_sky > 1.002:
199 return None
200 s_max = math.sqrt(max(0.0, 1.004 - r2_sky))
201 n_steps = 28
202 ds = (2.0 * s_max) / n_steps
203 s_prev = s_max
204 x0 = u
205
206 hit = False
207 s_hi = s_prev
208 s_lo = s_prev
209 for k in range(1, n_steps + 1):
210 s_cur = s_max - k * ds
211 y = -v * cos_i + s_cur * sin_i
212 z = v * sin_i + s_cur * cos_i
213 if roche_phi_minus_surf(x0, y, z, w2, phi_surf) <= 0.0:
214 s_hi = s_prev
215 s_lo = s_cur
216 hit = True
217 break
218 s_prev = s_cur
219
220 if not hit:
221 return None
222
223 for _ in range(30):
224 s_mid = 0.5 * (s_hi + s_lo)
225 y = -v * cos_i + s_mid * sin_i
226 z = v * sin_i + s_mid * cos_i
227 if roche_phi_minus_surf(x0, y, z, w2, phi_surf) <= 0.0:
228 s_lo = s_mid
229 else:
230 s_hi = s_mid
231
232 s_hit = 0.5 * (s_hi + s_lo)
233 x = x0
234 y = -v * cos_i + s_hit * sin_i
235 z = v * sin_i + s_hit * cos_i
236 r2 = x * x + y * y + z * z
237 r = math.sqrt(r2)
238 inv_r3 = 1.0 / (r2 * r)
239 nx = x * (inv_r3 - w2)
240 ny = y * (inv_r3 - w2)
241 nz = z * inv_r3
242 n_norm = math.sqrt(nx * nx + ny * ny + nz * nz)
243 nx /= n_norm
244 ny /= n_norm
245 nz /= n_norm
246 mu = ny * sin_i + nz * cos_i
247 if mu <= 0.0:
248 return None
249 theta = math.acos(max(-1.0, min(1.0, z / r)))
250 T_eff = star_lut.T_at_theta(theta)
251 X, Y, Z = spec_lut.lookup(T_eff, mu)
252 return X, Y, Z, T_eff, mu
253
254
255def render_disk(
256 size: int,
257 extent: float,
258 inc_deg: float,
259 w: float,
260 T_pole: float,
261 spec_lut: SpectrumLUT,
262):
263 """Render a (size x size) grid of raw linear XYZ values + T_eff map + diagnostics."""
264 inc = math.radians(inc_deg)
265 sin_i, cos_i = math.sin(inc), math.cos(inc)
266 w2 = w * w
267 phi_surf = -(1.0 + 0.5 * w2)
268 star_lut = StarProfileLUT(w, T_pole)
269
270 xyz_buf: list[tuple[float, float, float] | None] = [None] * (size * size)
271 teff_buf: list[float] = [0.0] * (size * size)
272 hit_mask = [False] * (size * size)
273 max_rgb = 0.0
274 total_X = total_Y = total_Z = 0.0
275 center_info = None
276
277 for py in range(size):
278 v = extent * (1.0 - 2.0 * (py + 0.5) / size)
279 row_off = py * size
280 for px in range(size):
281 u = extent * (2.0 * (px + 0.5) / size - 1.0)
282 res = trace_pixel(u, v, sin_i, cos_i, w2, phi_surf, star_lut, spec_lut)
283 if res is not None:
284 X, Y, Z, T_eff, mu = res
285 xyz_buf[row_off + px] = (X, Y, Z)
286 teff_buf[row_off + px] = T_eff
287 hit_mask[row_off + px] = True
288 r, g, b = xyz_to_linear_srgb(X, Y, Z)
289 m = max(r, g, b)
290 if m > max_rgb:
291 max_rgb = m
292 total_X += X
293 total_Y += Y
294 total_Z += Z
295 if py == size // 2 and px == size // 2:
296 center_info = (T_eff, mu, X, Y, Z)
297
298 pix_step = 2.0 * extent / size
299 aa_buf: list[tuple[float, float, float]] = [(0.0, 0.0, 0.0)] * (size * size)
300 aa_teff: list[tuple[float, float]] = [(0.0, 0.0)] * (size * size)
301 for py in range(size):
302 row_off = py * size
303 v_c = extent * (1.0 - 2.0 * (py + 0.5) / size)
304 for px in range(size):
305 idx = row_off + px
306 h = hit_mask[idx]
307 boundary = False
308 for dy in (-1, 0, 1):
309 ny = py + dy
310 if ny < 0 or ny >= size:
311 continue
312 for dx in (-1, 0, 1):
313 nx = px + dx
314 if nx < 0 or nx >= size:
315 continue
316 if hit_mask[ny * size + nx] != h:
317 boundary = True
318 break
319 if boundary:
320 break
321 if boundary:
322 u_c = extent * (2.0 * (px + 0.5) / size - 1.0)
323 sX = sY = sZ = sT = 0.0
324 hits = 0
325 for sy in range(4):
326 vv = v_c + ((sy + 0.5) / 4.0 - 0.5) * pix_step
327 for sx in range(4):
328 uu = u_c + ((sx + 0.5) / 4.0 - 0.5) * pix_step
329 res = trace_pixel(uu, vv, sin_i, cos_i, w2, phi_surf, star_lut, spec_lut)
330 if res is not None:
331 sX += res[0]
332 sY += res[1]
333 sZ += res[2]
334 sT += res[3]
335 hits += 1
336 aa_buf[idx] = (sX / 16.0, sY / 16.0, sZ / 16.0)
337 aa_teff[idx] = (sT / hits if hits else 0.0, hits / 16.0)
338 elif h:
339 aa_buf[idx] = xyz_buf[idx] # type: ignore[assignment]
340 aa_teff[idx] = (teff_buf[idx], 1.0)
341
342 T_eq = star_lut.T_at_theta(0.5 * math.pi)
343 s_tot = total_X + total_Y + total_Z
344 chrom = (total_X / s_tot, total_Y / s_tot) if s_tot > 0 else (0.0, 0.0)
345 return {
346 "buf": aa_buf,
347 "teff": aa_teff,
348 "max_rgb": max_rgb,
349 "total_Y": total_Y,
350 "chrom": chrom,
351 "T_pole": T_pole,
352 "T_eq": T_eq,
353 "R_ratio": 1.0 / roche_r(0.0, w),
354 "center": center_info,
355 }
356
357
358def load_font(size: int, bold: bool = False) -> ImageFont.FreeTypeFont | ImageFont.ImageFont:
359 candidates = (
360 [
361 "/usr/share/fonts/google-noto/NotoSans-Bold.ttf",
362 "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans-Bold.ttf",
363 "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Bold.ttf",
364 ]
365 if bold
366 else [
367 "/usr/share/fonts/google-noto/NotoSans-Regular.ttf",
368 "/usr/share/fonts/dejavu-sans-fonts/DejaVuSans.ttf",
369 "/usr/share/fonts/liberation-sans-fonts/LiberationSans-Regular.ttf",
370 ]
371 )
372 for p in candidates:
373 if Path(p).exists():
374 return ImageFont.truetype(p, size)
375 return ImageFont.load_default()
376
377
378def main():
379 spec_lut = SpectrumLUT(T_min=5500.0, T_max=10500.0, nT=51, nMu=41)
380
381 w_vega = omega_from_Om_ratio(0.774)
382 w_crit = omega_from_Om_ratio(0.990)
383 T_pole = 10070.0
384
385 panels = [
386 ("Vega · Pole-on (Earth)", "i = 6.2° · Ω/Ωc = 0.774", 6.2, w_vega),
387 ("Vega · Magic Honest Angle", "i = 54.7° · Ω/Ωc = 0.774", 54.74, w_vega),
388 ("Vega · Equator-on", "i = 90.0° · Ω/Ωc = 0.774", 90.0, w_vega),
389 ("Extreme · 99% Breakup", "i = 90.0° · Ω/Ωc = 0.990", 90.0, w_crit),
390 ]
391
392 disk_size = 340
393 extent = 1.15
394 renders = []
395 for title, sub, inc_deg, w in panels:
396 r = render_disk(disk_size, extent, inc_deg, w, T_pole, spec_lut)
397 renders.append((title, sub, r))
398
399 peak_ref = renders[0][2]["max_rgb"]
400 exposure = 0.98 / peak_ref
401 Y_ref = renders[0][2]["total_Y"]
402
403 pad_x = 24
404 gap_x = 18
405 top_hdr = 78
406 row_lbl_h = 28
407 cap_h = 78
408 cbar_h = 48
409 footer_h = 34
410 W = 2 * pad_x + 4 * disk_size + 3 * gap_x
411 H = top_hdr + row_lbl_h + disk_size + cap_h + row_lbl_h + disk_size + cbar_h + footer_h
412
413 BG = (8, 10, 15)
414 CARD_BG = (3, 4, 7)
415 BORDER = (34, 40, 56)
416 FG = (232, 238, 248)
417 MUTED = (148, 160, 182)
418 ACCENT = (126, 186, 255)
419
420 img = Image.new("RGB", (W, H), BG)
421 draw = ImageDraw.Draw(img)
422
423 f_title = load_font(22, bold=True)
424 f_sub = load_font(13, bold=False)
425 f_sec = load_font(13, bold=True)
426 f_card = load_font(14, bold=True)
427 f_meta = load_font(12, bold=False)
428
429 draw.text((pad_x, 16), "Vega (α Lyrae): Disk-Resolved CIE 1931 sRGB Ray-Traced Renders", fill=FG, font=f_title)
430 draw.text(
431 (pad_x, 45),
432 "Exact Roche equipotential + Espinosa Lara-Rieutord (2011) gravity darkening + Milne-Eddington gray RT (380-780 nm), matched exposure across all panels",
433 fill=MUTED,
434 font=f_sub,
435 )
436
437 row1_y = top_hdr
438 draw.text(
439 (pad_x, row1_y + 4),
440 "TRUE EYE COLOR · Matched-exposure CIE 1931 to sRGB (D65 white point; Vega pole center peak linear channel = 0.98)",
441 fill=ACCENT,
442 font=f_sec,
443 )
444 disk_y1 = row1_y + row_lbl_h
445
446 row2_y = disk_y1 + disk_size + cap_h
447 draw.text(
448 (pad_x, row2_y + 4),
449 "SURFACE EFFECTIVE TEMPERATURE T_eff(theta) · Same Roche geometry (7,000 K amber equator to 10,070 K blue-white polar caps)",
450 fill=ACCENT,
451 font=f_sec,
452 )
453 disk_y2 = row2_y + row_lbl_h
454
455 for idx, (title, sub, r) in enumerate(renders):
456 x0 = pad_x + idx * (disk_size + gap_x)
457 tile1 = Image.new("RGB", (disk_size, disk_size), CARD_BG)
458 tile2 = Image.new("RGB", (disk_size, disk_size), CARD_BG)
459 p1 = tile1.load()
460 p2 = tile2.load()
461 buf = r["buf"]
462 tbuf = r["teff"]
463 for py in range(disk_size):
464 ro = py * disk_size
465 for px in range(disk_size):
466 X, Y, Z = buf[ro + px]
467 if Y > 0.0:
468 lr, lg, lb = xyz_to_linear_srgb(X * exposure, Y * exposure, Z * exposure)
469 p1[px, py] = (
470 int(round(srgb_gamma(lr) * 255)),
471 int(round(srgb_gamma(lg) * 255)),
472 int(round(srgb_gamma(lb) * 255)),
473 )
474 T_val, cov = tbuf[ro + px]
475 if cov > 0.0:
476 tr, tg, tb = teff_colormap(T_val)
477 p2[px, py] = (
478 int(round(CARD_BG[0] * (1.0 - cov) + tr * cov)),
479 int(round(CARD_BG[1] * (1.0 - cov) + tg * cov)),
480 int(round(CARD_BG[2] * (1.0 - cov) + tb * cov)),
481 )
482
483 img.paste(tile1, (x0, disk_y1))
484 draw.rectangle([x0, disk_y1, x0 + disk_size - 1, disk_y1 + disk_size - 1], outline=BORDER, width=1)
485 img.paste(tile2, (x0, disk_y2))
486 draw.rectangle([x0, disk_y2, x0 + disk_size - 1, disk_y2 + disk_size - 1], outline=BORDER, width=1)
487
488 dV = -2.5 * math.log10(r["total_Y"] / Y_ref)
489 dV_str = "0.00 mag" if abs(dV) < 0.005 else f"{dV:+.2f} mag"
490 cx, cy = r["chrom"]
491 draw.text((x0 + 4, disk_y1 + disk_size + 8), title, fill=FG, font=f_card)
492 draw.text(
493 (x0 + 4, disk_y1 + disk_size + 28),
494 f"{sub} · Re/Rp = {r['R_ratio']:.3f}",
495 fill=MUTED,
496 font=f_meta,
497 )
498 draw.text(
499 (x0 + 4, disk_y1 + disk_size + 45),
500 f"Teq = {r['T_eq']:.0f} K · ΔV = {dV_str} · CIE ({cx:.3f}, {cy:.3f})",
501 fill=MUTED,
502 font=f_meta,
503 )
504
505 cb_w = 560
506 cb_h = 12
507 cb_x0 = (W - cb_w) // 2
508 cb_y0 = disk_y2 + disk_size + 14
509 for dx in range(cb_w):
510 T_s = 7000.0 + (dx / (cb_w - 1)) * 3100.0
511 draw.line([(cb_x0 + dx, cb_y0), (cb_x0 + dx, cb_y0 + cb_h)], fill=teff_colormap(T_s))
512 draw.rectangle([cb_x0, cb_y0, cb_x0 + cb_w - 1, cb_y0 + cb_h], outline=BORDER, width=1)
513 for tick_T in (7000, 7500, 8000, 8500, 9000, 9500, 10070):
514 tx = cb_x0 + int(round((tick_T - 7000.0) / 3100.0 * (cb_w - 1)))
515 draw.line([(tx, cb_y0 + cb_h), (tx, cb_y0 + cb_h + 4)], fill=MUTED)
516 lbl = f"{tick_T:,} K"
517 draw.text((tx - 20, cb_y0 + cb_h + 6), lbl, fill=MUTED, font=f_meta)
518
519 draw.text(
520 (pad_x, H - 24),
521 "Tp = 10,070 K (Monnier et al. 2012) · North rotation axis points up · All panels share identical R_e angular scale and radiometric exposure.",
522 fill=MUTED,
523 font=f_meta,
524 )
525
526 out_path = Path(__file__).resolve().with_name("vega_disks.png")
527 img.save(out_path, optimize=True)
528 print(f"Wrote {out_path} ({W}x{H})")
529
530
531if __name__ == "__main__":
532 main()
533