1#!/usr/bin/env python3
2"""figures.py: the pictures for "The Nebra Sky", drawn from nebra-results.json.
3
4Usage: figures.py --catalogue hyg_v44.csv.gz --photo disc.jpg [--out DIR]
5Needs: numpy, scipy, Pillow, rsvg-convert, the Noto fonts
6"""
7
8from __future__ import annotations
9
10import argparse
11import base64
12import io
13import json
14import subprocess
15from pathlib import Path
16
17import numpy as np
18from PIL import Image, ImageEnhance
19
20import skymatch as sm
21
22HERE = Path(__file__).resolve().parent
23
24INK = "#f6eff8"
25MUTED = "#a99ab4"
26FAINT = "#5b4d6b"
27NIGHT = "#0f0c17"
28ROSE = "#f45ba4"
29VIOLET = "#a78bfa"
30BLUE = "#60a5fa"
31GOLD = "#f2c45a"
32TEAL = "#5eead4"
33FONT = "Noto Serif"
34
35CONSTELLATIONS = dict(
36 item.split(":")
37 for item in (
38 "And:Andromeda,Ant:Antlia,Aps:Apus,Aql:Aquila,Aqr:Aquarius,Ara:Ara,Ari:Aries,"
39 "Aur:Auriga,Boo:Boötes,Cae:Caelum,Cam:Camelopardalis,Cap:Capricornus,Car:Carina,"
40 "Cas:Cassiopeia,Cen:Centaurus,Cep:Cepheus,Cet:Cetus,Cha:Chamaeleon,Cir:Circinus,"
41 "CMa:Canis Major,CMi:Canis Minor,Cnc:Cancer,Col:Columba,Com:Coma Berenices,"
42 "CrA:Corona Australis,CrB:Corona Borealis,Crt:Crater,Cru:Crux,Crv:Corvus,"
43 "CVn:Canes Venatici,Cyg:Cygnus,Del:Delphinus,Dor:Dorado,Dra:Draco,Equ:Equuleus,"
44 "Eri:Eridanus,For:Fornax,Gem:Gemini,Gru:Grus,Her:Hercules,Hor:Horologium,Hya:Hydra,"
45 "Hyi:Hydrus,Ind:Indus,Lac:Lacerta,Leo:Leo,Lep:Lepus,Lib:Libra,LMi:Leo Minor,"
46 "Lup:Lupus,Lyn:Lynx,Lyr:Lyra,Men:Mensa,Mic:Microscopium,Mon:Monoceros,Mus:Musca,"
47 "Nor:Norma,Oct:Octans,Oph:Ophiuchus,Ori:Orion,Pav:Pavo,Peg:Pegasus,Per:Perseus,"
48 "Phe:Phoenix,Pic:Pictor,PsA:Piscis Austrinus,Psc:Pisces,Pup:Puppis,Pyx:Pyxis,"
49 "Ret:Reticulum,Scl:Sculptor,Sco:Scorpius,Sct:Scutum,Ser:Serpens,Sex:Sextans,"
50 "Sge:Sagitta,Sgr:Sagittarius,Tau:Taurus,Tel:Telescopium,TrA:Triangulum Australe,"
51 "Tri:Triangulum,Tuc:Tucana,UMa:Ursa Major,UMi:Ursa Minor,Vel:Vela,Vir:Virgo,"
52 "Vol:Volans,Vul:Vulpecula"
53 ).split(",")
54)
55GREEK = dict(zip(
56 "Alp Bet Gam Del Eps Zet Eta The Iot Kap Lam Mu Nu Xi Omi Pi Rho Sig Tau Ups Phi Chi Psi Ome".split(),
57 "αβγδεζηθικλμνξοπρστυφχψω",
58)) # fmt: skip
59
60
61# --------------------------------------------------------------------------------------
62# SVG helpers
63# --------------------------------------------------------------------------------------
64class Svg:
65 def __init__(self, width: int, height: int):
66 self.width, self.height = width, height
67 self.parts = [
68 f'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
69 f'width="{width}" height="{height}" viewBox="0 0 {width} {height}">'
70 '<defs><radialGradient id="sky" cx="50%" cy="45%" r="70%">'
71 f'<stop offset="0%" stop-color="#241a38"/><stop offset="100%" stop-color="{NIGHT}"/>'
72 "</radialGradient>"
73 '<radialGradient id="halo"><stop offset="0%" stop-color="#fff" stop-opacity="0.55"/>'
74 '<stop offset="100%" stop-color="#fff" stop-opacity="0"/></radialGradient></defs>'
75 '<rect width="100%" height="100%" fill="url(#sky)"/>'
76 ]
77
78 def add(self, markup: str) -> None:
79 self.parts.append(markup)
80
81 def circle(self, x, y, r, fill="none", stroke="none", width=1.0, opacity=1.0, dash="") -> None:
82 extra = f' stroke-dasharray="{dash}"' if dash else ""
83 self.add(
84 f'<circle cx="{x:.1f}" cy="{y:.1f}" r="{r:.2f}" fill="{fill}" stroke="{stroke}" '
85 f'stroke-width="{width}" opacity="{opacity}"{extra}/>'
86 )
87
88 def line(self, x1, y1, x2, y2, stroke=FAINT, width=1.0, dash="", opacity=1.0) -> None:
89 extra = f' stroke-dasharray="{dash}"' if dash else ""
90 self.add(
91 f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}" y2="{y2:.1f}" stroke="{stroke}" '
92 f'stroke-width="{width}" opacity="{opacity}"{extra}/>'
93 )
94
95 def text(self, x, y, content, size=24, fill=INK, anchor="middle", halo=False, extra="") -> None:
96 content = content.replace("&", "&").replace("<", "<")
97 attrs = f'x="{x:.1f}" y="{y:.1f}" font-size="{size}" font-family="{FONT}" text-anchor="{anchor}" {extra}'
98 if halo:
99 self.add(f'<text {attrs} fill="none" stroke="{NIGHT}" stroke-width="5" stroke-linejoin="round" opacity="0.85">{content}</text>')
100 self.add(f'<text {attrs} fill="{fill}">{content}</text>')
101
102 def star(self, x, y, mag, fill=INK) -> None:
103 r = max(1.1, (5.9 - mag) * 1.25)
104 if mag < 3:
105 self.circle(x, y, r * 3.2, fill="url(#halo)")
106 self.circle(x, y, r, fill=fill, opacity=min(1.0, 0.45 + (5.5 - mag) * 0.2))
107
108 def image(self, picture: Image.Image, x, y, w, h, clip: str = "", opacity=1.0) -> None:
109 buffer = io.BytesIO()
110 picture.save(buffer, "JPEG", quality=90)
111 data = base64.b64encode(buffer.getvalue()).decode()
112 extra = f' clip-path="url(#{clip})"' if clip else ""
113 self.add(
114 f'<image x="{x}" y="{y}" width="{w}" height="{h}" opacity="{opacity}"{extra} '
115 f'xlink:href="data:image/jpeg;base64,{data}"/>'
116 )
117
118 def save(self, path: Path) -> None:
119 self.add("</svg>")
120 subprocess.run(
121 ["rsvg-convert", "--unlimited", "-o", str(path)], input="".join(self.parts).encode(), check=True
122 )
123 print(f" {path.name}")
124
125
126def crop_disc(photo: Image.Image, size: int, reach: float = 1.05) -> Image.Image:
127 (cx, cy), r = sm.CENTRE, sm.RADIUS * reach
128 return photo.crop((int(cx - r), int(cy - r), int(cx + r), int(cy + r))).resize((size, size), Image.LANCZOS)
129
130
131def label_of(star: dict) -> str:
132 if star["proper"]:
133 return star["proper"]
134 letter = star["bayer"].split("-")[0]
135 if letter in GREEK:
136 return f"{GREEK[letter]} {star['con']}"
137 return ""
138
139
140def place_labels(svg: Svg, items, size, taken, fill=INK) -> None:
141 """Labels beside their points, skipping any that would sit on an earlier one."""
142 for x, y, text in items:
143 width = len(text) * size * 0.55
144 for dx, dy, anchor in ((12, -8, "start"), (-12, -8, "end"), (12, size + 6, "start"), (-12, size + 6, "end")):
145 left = x + dx - (width if anchor == "end" else 0)
146 box = (left, y + dy - size, left + width, y + dy + 4)
147 clear = all(box[2] < t[0] or box[0] > t[2] or box[3] < t[1] or box[1] > t[3] for t in taken)
148 if clear and box[0] > 4 and box[2] < svg.width - 4:
149 svg.text(x + dx, y + dy, text, size, fill, anchor, halo=True)
150 taken.append(box)
151 break
152
153
154def sky_chart(svg: Svg, data: dict, chart: dict, dots: np.ndarray, cx, cy, radius, *, limit=3.5,
155 names=False, rim=True, matched_colour=GOLD) -> None: # fmt: skip
156 """The stars around one fitted placement, with the dots drawn as rings."""
157 stars = data["stars"]
158 at = {}
159 for index, x, y in chart["stars"]:
160 if np.hypot(x, y) <= 1.07:
161 at[index] = (cx + radius * x, cy - radius * y)
162 if rim:
163 svg.circle(cx, cy, radius * 1.07, stroke=FAINT, width=2)
164 for index, (x, y) in at.items():
165 mag = stars[str(index)]["mag"]
166 if mag <= limit:
167 svg.star(x, y, mag)
168 else:
169 svg.circle(x, y, 1.0, fill=MUTED, opacity=0.35)
170 matched = {int(k): v for k, v in chart["matched"].items()}
171 for i, d in enumerate(dots):
172 x, y = cx + radius * d.real, cy - radius * d.imag
173 hit = i in matched
174 if hit and matched[i] in at:
175 sx, sy = at[matched[i]]
176 svg.line(x, y, sx, sy, matched_colour, 2)
177 svg.circle(x, y, radius * 0.045, stroke=matched_colour if hit else ROSE, width=2.5,
178 dash="" if hit else "5 4") # fmt: skip
179 if names:
180 taken = [(cx + radius * d.real - 18, cy - radius * d.imag - 18,
181 cx + radius * d.real + 18, cy - radius * d.imag + 18) for d in dots] # fmt: skip
182 chosen = sorted((i for i in set(matched.values()) if i in at), key=lambda i: stars[str(i)]["mag"])
183 items = [(*at[i], label_of(stars[str(i)])) for i in chosen if label_of(stars[str(i)])]
184 place_labels(svg, items, 21, taken)
185 groups: dict[str, list] = {}
186 for i in at:
187 if stars[str(i)]["mag"] <= limit:
188 groups.setdefault(stars[str(i)]["con"], []).append(at[i])
189 for con, points in sorted(groups.items(), key=lambda g: -len(g[1])):
190 if len(points) >= 3 and con in CONSTELLATIONS:
191 x, y = np.mean(points, axis=0)
192 width = len(CONSTELLATIONS[con]) * 17
193 box = (x - width / 2, y - 24, x + width / 2, y + 6)
194 if all(box[2] < t[0] or box[0] > t[2] or box[3] < t[1] or box[1] > t[3] for t in taken):
195 svg.text(x, y, CONSTELLATIONS[con].upper(), 22, VIOLET, halo=True, extra='letter-spacing="3"')
196 taken.append(box)
197
198
199# --------------------------------------------------------------------------------------
200# The figures
201# --------------------------------------------------------------------------------------
202def fig_dots(photo: Image.Image, out: Path) -> None:
203 size = 1200
204 svg = Svg(size, size)
205 svg.image(ImageEnhance.Brightness(crop_disc(photo, size)).enhance(0.75), 0, 0, size, size)
206 scale = size / 2 / 1.05
207 for group, dots, colour in (("field", sm.FIELD, ROSE), ("cluster", sm.CLUSTER, TEAL)):
208 for i, d in enumerate(dots):
209 x, y = size / 2 + scale * d.real, size / 2 - scale * d.imag
210 svg.circle(x, y, 30, stroke=colour, width=4)
211 if group == "field":
212 svg.text(x, y - 38, str(i + 1), 24, INK, halo=True)
213 svg.circle(40, 40, 14, stroke=ROSE, width=4)
214 svg.text(64, 49, "23 single dots", 28, INK, "start", halo=True)
215 svg.circle(40, 86, 14, stroke=TEAL, width=4)
216 svg.text(64, 95, "the cluster of seven", 28, INK, "start", halo=True)
217 svg.save(out / "nebra-dots.png")
218
219
220def fig_cluster(data: dict, out: Path) -> None:
221 c = data["cluster"]
222 svg = Svg(1200, 640)
223 sky = np.array([complex(*p) for p in c["sky_xy"]])
224 disc = sm.CLUSTER - sm.CLUSTER.mean()
225 if c["shape_mirror"]:
226 disc = np.conj(disc)
227 fitted = complex(*c["shape_a"]) * disc + sky.mean()
228
229 def panel(points, cx, radius=190):
230 centred = points - points.mean()
231 k = radius / np.abs(centred).max()
232 return [(cx + k * p.real, 300 - k * p.imag) for p in centred], k, points.mean()
233
234 for x, y in panel(sm.CLUSTER, 300)[0]:
235 svg.circle(x, y, 28, fill=GOLD)
236 svg.text(300, 560, "On the disc", 36)
237 svg.text(300, 600, "a rosette: six around one", 24, MUTED)
238 placed, k, mean = panel(sky, 900)
239 mags = dict(zip(c["stars"], c["magnitudes"]))
240 taken = [(x - 14, y - 14, x + 14, y + 14) for x, y in placed]
241 for (x, y), name in zip(placed, c["stars"]):
242 svg.star(x, y, mags[name] - 1.2)
243 for k_sky, disc_index in enumerate(c["shape_order"]):
244 p = fitted[disc_index] - mean
245 x, y = 900 + k * p.real, 300 - k * p.imag
246 svg.line(x, y, *placed[k_sky], GOLD, 1.5, "4 4")
247 svg.circle(x, y, 17, stroke=GOLD, width=2.5)
248 place_labels(svg, [(x, y, n) for (x, y), n in zip(placed, c["stars"]) if n], 20, taken)
249 svg.text(900, 560, "In the sky", 36)
250 svg.text(900, 600, "the Pleiades, with the disc dots fitted on top (rings)", 24, MUTED)
251 svg.line(600, 80, 600, 600)
252 svg.save(out / "nebra-cluster.png")
253
254
255def fig_scale(data: dict, sky: dict, out: Path) -> None:
256 c = data["cluster"]
257 svg = Svg(1200, 900)
258 alcyone = sky["proper"].index("Alcyone")
259 stars = np.flatnonzero(sky["mag"] <= 5.6)
260 centre = sky["vec"][alcyone]
261 away = np.degrees(np.arccos(np.clip(sky["vec"][stars] @ centre, -1, 1)))
262 stars = stars[away < 30]
263 z = sm.project(sky["vec"][stars], centre)
264 per_degree = 46.0
265 disc_radius = c["disc_degrees_to_scale"] / 2 * per_degree
266 # keep the cluster where it sits on the disc
267 offset = sm.CLUSTER.mean()
268 ox = 600 - disc_radius * offset.real
269 oy = 450 + disc_radius * offset.imag
270 for i, p in zip(stars, z):
271 x = ox + per_degree * np.degrees(p.real)
272 y = oy - per_degree * np.degrees(p.imag)
273 if -20 < x < 1220 and -20 < y < 920:
274 svg.star(x, y, sky["mag"][i])
275 if sky["mag"][i] < 3.2 and sky["proper"][i] not in ("", "Alcyone"):
276 svg.text(x + 14, y - 10, sky["proper"][i], 20, MUTED, "start", halo=True)
277 svg.circle(600, 450, disc_radius, stroke=GOLD, width=3)
278 svg.text(600, 450 + disc_radius + 38, f"the disc, if its cluster is drawn to scale: {c['disc_degrees_to_scale']:.1f}° across", 26, GOLD, halo=True)
279 svg.text(ox + 20, oy - 40, "Pleiades", 26, INK, "start", halo=True)
280 moon = 0.52 / 2 * per_degree
281 svg.circle(90, 820, moon, fill=MUTED)
282 svg.text(120, 828, "the full Moon at the same scale", 22, MUTED, "start")
283 svg.save(out / "nebra-to-scale.png")
284
285
286def fig_which(data: dict, out: Path) -> None:
287 index = data["main_index"]
288 run = data["runs"]["free"][index]
289 random = np.array([complex(*p) for p in run["examples"]["typical"]["dots"]])
290 svg = Svg(1200, 700)
291 for letter, cx, chart, dots, fit in (
292 ("A", 300, data["charts"]["free_typical"], random, run["examples"]["typical"]["fit"]),
293 ("B", 900, data["charts"]["free_hits"], sm.FIELD, run["hits"]["disc"]),
294 ):
295 sky_chart(svg, data, chart, dots, cx, 320, 270, limit=data["settings"]["main"][0])
296 svg.text(cx, 660, letter, 44)
297 svg.text(cx + 40, 658, f"{fit['hits']} of 23 matched", 24, MUTED, "start")
298 svg.save(out / "nebra-which-is-which.png")
299
300
301def fig_best(photo: Image.Image, data: dict, out: Path) -> None:
302 size = 1200
303 svg = Svg(size, size)
304 reach = 1.12
305 scale = size / 2 / reach
306 r = scale * 1.07
307 svg.add(f'<clipPath id="disc"><circle cx="600" cy="600" r="{r:.0f}"/></clipPath>')
308 dim = ImageEnhance.Brightness(crop_disc(photo, size, reach)).enhance(0.42)
309 svg.image(dim, 0, 0, size, size, "disc")
310 chart = data["charts"]["free_strict"]
311 sky_chart(svg, data, chart, sm.FIELD, 600, 600, scale, limit=data["settings"]["main"][0], names=True)
312 fit = data["runs"]["free"][data["main_index"]]["strict"]["disc"]
313 svg.text(32, 52, f"{fit['hits']} of 23 dots on a star", 30, GOLD, "start", halo=True)
314 svg.text(32, 92, f"the disc spans {chart['span_deg']:.0f}° of sky" + (", mirrored" if fit["mirror"] else ""), 24, INK, "start", halo=True)
315 svg.save(out / "nebra-best-fit.png")
316
317
318def fig_chance(data: dict, out: Path) -> None:
319 svg = Svg(1200, 820)
320 index = data["main_index"]
321 panels = [
322 ("free", "hits", "Anywhere in the sky: dots matched"),
323 ("free", "strict", "Anywhere in the sky: strict score"),
324 ("pinned", "hits", "Cluster on the Pleiades: dots matched"),
325 ("pinned", "strict", "Cluster on the Pleiades: strict score"),
326 ]
327 for n, (kind, score, title) in enumerate(panels):
328 x0, y0, w, h = 60 + (n % 2) * 580, 80 + (n // 2) * 390, 500, 250
329 block = data["runs"][kind][index][score]
330 null = np.array(block["null"])
331 disc = block["disc"]["hits" if score == "hits" else "score"]
332 if score == "hits":
333 edges = np.arange(min(null.min(), disc) - 0.5, max(null.max(), disc) + 1.5)
334 else:
335 edges = np.linspace(min(null.min(), disc) * 0.95, max(null.max(), disc) * 1.05, 30)
336 counts, _ = np.histogram(null, edges)
337 span = edges[-1] - edges[0]
338 px = lambda v: x0 + (v - edges[0]) / span * w
339 for left, right, count in zip(edges[:-1], edges[1:], counts):
340 bar = count / counts.max() * h
341 svg.add(f'<rect x="{px(left) + 1:.1f}" y="{y0 + h - bar:.1f}" width="{max(1, px(right) - px(left) - 2):.1f}" height="{bar:.1f}" fill="{VIOLET}" opacity="0.8"/>')
342 svg.line(x0, y0 + h, x0 + w, y0 + h, MUTED)
343 ticks = (edges[:-1] + edges[1:]) / 2 if score == "hits" else np.linspace(edges[0], edges[-1], 5)
344 step = max(1, len(ticks) // 9) if score == "hits" else 1
345 for v in ticks[::step]:
346 svg.text(px(v), y0 + h + 26, f"{v:.0f}" if score == "hits" else f"{v:.2f}", 18, MUTED)
347 svg.line(px(disc), y0 - 6, px(disc), y0 + h, GOLD, 4)
348 svg.text(x0 + w / 2, y0 - 38, title, 25)
349 side = "start" if px(disc) < x0 + w * 0.6 else "end"
350 share = float(np.mean(null >= disc - 1e-4)) # the stored values have four decimals
351 svg.text(px(disc) + (10 if side == "start" else -10), y0 + 18, "the disc", 22, GOLD, side, halo=True)
352 svg.text(px(disc) + (10 if side == "start" else -10), y0 + 44, f"{share:.0%} of random do as well", 18, INK, side, halo=True)
353 svg.text(600, 805, "bars: 1,000 random dot patterns, searched exactly like the disc", 22, MUTED)
354 svg.save(out / "nebra-chance.png")
355
356
357def fig_spacing(data: dict, out: Path) -> None:
358 s = data["spacing"]
359 svg = Svg(1200, 560)
360 x0, y0, w, h = 80, 100, 1040, 340
361 random, field = np.array(s["random"]["variation"]), np.array(s["sky"]["variation"])
362 edges = np.linspace(0, 1.2, 73)
363 px = lambda v: x0 + v / 1.2 * w
364 shares = [np.histogram(v, edges)[0] / len(v) for v in (random, field)]
365 top = max(x.max() for x in shares)
366 for share, colour in zip(shares, (VIOLET, BLUE)):
367 path = f"M {px(edges[0]):.1f} {y0 + h}"
368 for left, right, value in zip(edges[:-1], edges[1:], share):
369 y = y0 + h - value / top * h
370 path += f" L {px(left):.1f} {y:.1f} L {px(right):.1f} {y:.1f}"
371 path += f" L {px(edges[-1]):.1f} {y0 + h} Z"
372 svg.add(f'<path d="{path}" fill="{colour}" fill-opacity="0.35" stroke="{colour}" stroke-width="2"/>')
373 svg.line(x0, y0 + h, x0 + w, y0 + h, MUTED)
374 for v in np.arange(0, 1.21, 0.2):
375 svg.text(px(v), y0 + h + 28, f"{v:.1f}", 18, MUTED)
376 disc = s["disc"]["variation"]
377 svg.line(px(disc), y0 - 20, px(disc), y0 + h, GOLD, 4)
378 svg.text(px(disc) + 12, y0 - 4, "the disc", 26, GOLD, "start", halo=True)
379 svg.text(600, 46, "How unevenly are 23 dots spaced?", 32)
380 svg.text(x0, y0 + h + 66, "← lattice-like", 22, MUTED, "start")
381 svg.text(x0 + w, y0 + h + 66, "clumped →", 22, MUTED, "end")
382 for k, (colour, text) in enumerate(((VIOLET, "random dots on the disc"), (BLUE, "the 23 brightest stars in a patch of sky"))):
383 svg.add(f'<rect x="700" y="{120 + k * 40}" width="26" height="18" fill="{colour}" fill-opacity="0.6"/>')
384 svg.text(738, 136 + k * 40, text, 21, INK, "start")
385 svg.text(600, 540, "variation of the distance to the nearest neighbour (standard deviation ÷ mean)", 20, MUTED)
386 svg.save(out / "nebra-spacing.png")
387
388
389def fig_control(data: dict, out: Path) -> None:
390 rows = data["control"]["rows"]
391 svg = Svg(1200, 560)
392 x0, y0, w, h = 120, 100, 1000, 340
393 low, high = rows[0]["real"], rows[-1]["real"]
394 px = lambda v: x0 + (v - low) / (high - low) * w
395 py = lambda v: y0 + h - v * h
396 for v in (0, 0.25, 0.5, 0.75, 1):
397 svg.line(x0, py(v), x0 + w, py(v), FAINT, 1, "" if v == 0 else "3 6")
398 svg.text(x0 - 16, py(v) + 7, f"{v:.0%}", 20, MUTED, "end")
399 for r in rows:
400 svg.text(px(r["real"]), y0 + h + 32, str(r["real"]), 20, MUTED)
401 for key, colour, text in (("found_hits", VIOLET, "by dots matched"), ("found_strict", GOLD, "by the strict score")):
402 points = " ".join(f"{px(r['real']):.1f},{py(r[key]):.1f}" for r in rows)
403 svg.add(f'<polyline points="{points}" fill="none" stroke="{colour}" stroke-width="4"/>')
404 for r in rows:
405 svg.circle(px(r["real"]), py(r[key]), 7, fill=colour)
406 for k, (colour, text) in enumerate(((VIOLET, "judged by dots matched"), (GOLD, "judged by the strict score"))):
407 svg.line(160, 130 + k * 36, 200, 130 + k * 36, colour, 4)
408 svg.text(212, 137 + k * 36, text, 21, INK, "start")
409 svg.text(600, 48, "Would the search notice a real star map?", 32)
410 svg.text(600, 524, "true stars hidden among the 23 dots; line: how often the result beats 95 % of random patterns", 20, MUTED)
411 svg.save(out / "nebra-control.png")
412
413
414def fig_cover(photo: Image.Image, data: dict, out: Path) -> None:
415 """The disc, its left half as photographed, its right half as a star chart."""
416 svg = Svg(1200, 630)
417 rng = np.random.default_rng(3)
418 for x, y, r in zip(rng.uniform(0, 1200, 380), rng.uniform(0, 630, 380), rng.pareto(3, 380)):
419 svg.circle(x, y, min(2.4, 0.5 + r), fill=INK, opacity=0.4)
420 radius, reach = 285, 1.05
421 box = radius * reach
422 r = radius * 1.025
423 svg.add(f'<clipPath id="left"><path d="M 600 {315 - r} A {r} {r} 0 0 0 600 {315 + r} Z"/></clipPath>')
424 svg.image(crop_disc(photo, 900, reach), 600 - box, 315 - box, 2 * box, 2 * box, "left")
425 svg.add('<clipPath id="right"><rect x="600" y="0" width="600" height="630"/></clipPath>')
426 svg.add('<g clip-path="url(#right)">')
427 svg.circle(600, 315, radius * 1.02, fill="#171029", stroke=GOLD, width=2)
428 chart = data["charts"]["free_hits"]
429 at = {i: (600 + radius * x, 315 - radius * y) for i, x, y in chart["stars"] if np.hypot(x, y) < 1.0}
430 for i, (x, y) in at.items():
431 svg.star(x, y, data["stars"][str(i)]["mag"])
432 matched = {int(k): v for k, v in chart["matched"].items()}
433 for i, d in enumerate(sm.FIELD):
434 x, y = 600 + radius * d.real, 315 - radius * d.imag
435 if i in matched and matched[i] in at:
436 svg.line(x, y, *at[matched[i]], GOLD, 2)
437 svg.circle(x, y, radius * 0.036, stroke=GOLD, width=2)
438 for d in sm.CLUSTER:
439 svg.circle(600 + radius * d.real, 315 - radius * d.imag, radius * 0.036, stroke=TEAL, width=2)
440 svg.add("</g>")
441 svg.line(600, 14, 600, 616, INK, 1.5, "2 7", 0.8)
442 svg.save(out / "nebra-cover.png")
443
444
445def main() -> None:
446 parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
447 parser.add_argument("--catalogue", type=Path, required=True)
448 parser.add_argument("--photo", type=Path, required=True)
449 parser.add_argument("--out", type=Path, default=HERE)
450 parser.add_argument("--results", type=Path, help="default: nebra-results.json in --out")
451 args = parser.parse_args()
452
453 data = json.loads((args.results or args.out / "nebra-results.json").read_text())
454 order = [[m, t] for m in sm.MAG_LIMITS for t in sm.TOLERANCES]
455 data["main_index"] = order.index(list(data["settings"]["main"]))
456 sky = sm.load_sky(args.catalogue)
457 photo = Image.open(args.photo).convert("RGB")
458 args.out.mkdir(parents=True, exist_ok=True)
459
460 photo.resize((2000, 2000), Image.LANCZOS).save(args.out / "nebra-disc.jpg", quality=86)
461 print(" nebra-disc.jpg")
462 fig_dots(photo, args.out)
463 fig_cluster(data, args.out)
464 fig_scale(data, sky, args.out)
465 fig_which(data, args.out)
466 fig_best(photo, data, args.out)
467 fig_chance(data, args.out)
468 fig_spacing(data, args.out)
469 fig_control(data, args.out)
470 fig_cover(photo, data, args.out)
471
472
473if __name__ == "__main__":
474 main()