#!/usr/bin/env python3
"""figures.py: the pictures for "The Nebra Sky", drawn from nebra-results.json.
Usage: figures.py --catalogue hyg_v44.csv.gz --photo disc.jpg [--out DIR]
Needs: numpy, scipy, Pillow, rsvg-convert, the Noto fonts
"""
from __future__ import annotations
import argparse
import base64
import io
import json
import subprocess
from pathlib import Path
import numpy as np
from PIL import Image, ImageEnhance
import skymatch as sm
HERE = Path(__file__).resolve().parent
INK = "#f6eff8"
MUTED = "#a99ab4"
FAINT = "#5b4d6b"
NIGHT = "#0f0c17"
ROSE = "#f45ba4"
VIOLET = "#a78bfa"
BLUE = "#60a5fa"
GOLD = "#f2c45a"
TEAL = "#5eead4"
FONT = "Noto Serif"
CONSTELLATIONS = dict(
item.split(":")
for item in (
"And:Andromeda,Ant:Antlia,Aps:Apus,Aql:Aquila,Aqr:Aquarius,Ara:Ara,Ari:Aries,"
"Aur:Auriga,Boo:Boötes,Cae:Caelum,Cam:Camelopardalis,Cap:Capricornus,Car:Carina,"
"Cas:Cassiopeia,Cen:Centaurus,Cep:Cepheus,Cet:Cetus,Cha:Chamaeleon,Cir:Circinus,"
"CMa:Canis Major,CMi:Canis Minor,Cnc:Cancer,Col:Columba,Com:Coma Berenices,"
"CrA:Corona Australis,CrB:Corona Borealis,Crt:Crater,Cru:Crux,Crv:Corvus,"
"CVn:Canes Venatici,Cyg:Cygnus,Del:Delphinus,Dor:Dorado,Dra:Draco,Equ:Equuleus,"
"Eri:Eridanus,For:Fornax,Gem:Gemini,Gru:Grus,Her:Hercules,Hor:Horologium,Hya:Hydra,"
"Hyi:Hydrus,Ind:Indus,Lac:Lacerta,Leo:Leo,Lep:Lepus,Lib:Libra,LMi:Leo Minor,"
"Lup:Lupus,Lyn:Lynx,Lyr:Lyra,Men:Mensa,Mic:Microscopium,Mon:Monoceros,Mus:Musca,"
"Nor:Norma,Oct:Octans,Oph:Ophiuchus,Ori:Orion,Pav:Pavo,Peg:Pegasus,Per:Perseus,"
"Phe:Phoenix,Pic:Pictor,PsA:Piscis Austrinus,Psc:Pisces,Pup:Puppis,Pyx:Pyxis,"
"Ret:Reticulum,Scl:Sculptor,Sco:Scorpius,Sct:Scutum,Ser:Serpens,Sex:Sextans,"
"Sge:Sagitta,Sgr:Sagittarius,Tau:Taurus,Tel:Telescopium,TrA:Triangulum Australe,"
"Tri:Triangulum,Tuc:Tucana,UMa:Ursa Major,UMi:Ursa Minor,Vel:Vela,Vir:Virgo,"
"Vol:Volans,Vul:Vulpecula"
).split(",")
)
GREEK = dict(zip(
"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(),
"αβγδεζηθικλμνξοπρστυφχψω",
)) # fmt: skip
# --------------------------------------------------------------------------------------
# SVG helpers
# --------------------------------------------------------------------------------------
class Svg:
def __init__(self, width: int, height: int):
self.width, self.height = width, height
self.parts = [
f'")
subprocess.run(
["rsvg-convert", "--unlimited", "-o", str(path)], input="".join(self.parts).encode(), check=True
)
print(f" {path.name}")
def crop_disc(photo: Image.Image, size: int, reach: float = 1.05) -> Image.Image:
(cx, cy), r = sm.CENTRE, sm.RADIUS * reach
return photo.crop((int(cx - r), int(cy - r), int(cx + r), int(cy + r))).resize((size, size), Image.LANCZOS)
def label_of(star: dict) -> str:
if star["proper"]:
return star["proper"]
letter = star["bayer"].split("-")[0]
if letter in GREEK:
return f"{GREEK[letter]} {star['con']}"
return ""
def place_labels(svg: Svg, items, size, taken, fill=INK) -> None:
"""Labels beside their points, skipping any that would sit on an earlier one."""
for x, y, text in items:
width = len(text) * size * 0.55
for dx, dy, anchor in ((12, -8, "start"), (-12, -8, "end"), (12, size + 6, "start"), (-12, size + 6, "end")):
left = x + dx - (width if anchor == "end" else 0)
box = (left, y + dy - size, left + width, y + dy + 4)
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)
if clear and box[0] > 4 and box[2] < svg.width - 4:
svg.text(x + dx, y + dy, text, size, fill, anchor, halo=True)
taken.append(box)
break
def sky_chart(svg: Svg, data: dict, chart: dict, dots: np.ndarray, cx, cy, radius, *, limit=3.5,
names=False, rim=True, matched_colour=GOLD) -> None: # fmt: skip
"""The stars around one fitted placement, with the dots drawn as rings."""
stars = data["stars"]
at = {}
for index, x, y in chart["stars"]:
if np.hypot(x, y) <= 1.07:
at[index] = (cx + radius * x, cy - radius * y)
if rim:
svg.circle(cx, cy, radius * 1.07, stroke=FAINT, width=2)
for index, (x, y) in at.items():
mag = stars[str(index)]["mag"]
if mag <= limit:
svg.star(x, y, mag)
else:
svg.circle(x, y, 1.0, fill=MUTED, opacity=0.35)
matched = {int(k): v for k, v in chart["matched"].items()}
for i, d in enumerate(dots):
x, y = cx + radius * d.real, cy - radius * d.imag
hit = i in matched
if hit and matched[i] in at:
sx, sy = at[matched[i]]
svg.line(x, y, sx, sy, matched_colour, 2)
svg.circle(x, y, radius * 0.045, stroke=matched_colour if hit else ROSE, width=2.5,
dash="" if hit else "5 4") # fmt: skip
if names:
taken = [(cx + radius * d.real - 18, cy - radius * d.imag - 18,
cx + radius * d.real + 18, cy - radius * d.imag + 18) for d in dots] # fmt: skip
chosen = sorted((i for i in set(matched.values()) if i in at), key=lambda i: stars[str(i)]["mag"])
items = [(*at[i], label_of(stars[str(i)])) for i in chosen if label_of(stars[str(i)])]
place_labels(svg, items, 21, taken)
groups: dict[str, list] = {}
for i in at:
if stars[str(i)]["mag"] <= limit:
groups.setdefault(stars[str(i)]["con"], []).append(at[i])
for con, points in sorted(groups.items(), key=lambda g: -len(g[1])):
if len(points) >= 3 and con in CONSTELLATIONS:
x, y = np.mean(points, axis=0)
width = len(CONSTELLATIONS[con]) * 17
box = (x - width / 2, y - 24, x + width / 2, y + 6)
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):
svg.text(x, y, CONSTELLATIONS[con].upper(), 22, VIOLET, halo=True, extra='letter-spacing="3"')
taken.append(box)
# --------------------------------------------------------------------------------------
# The figures
# --------------------------------------------------------------------------------------
def fig_dots(photo: Image.Image, out: Path) -> None:
size = 1200
svg = Svg(size, size)
svg.image(ImageEnhance.Brightness(crop_disc(photo, size)).enhance(0.75), 0, 0, size, size)
scale = size / 2 / 1.05
for group, dots, colour in (("field", sm.FIELD, ROSE), ("cluster", sm.CLUSTER, TEAL)):
for i, d in enumerate(dots):
x, y = size / 2 + scale * d.real, size / 2 - scale * d.imag
svg.circle(x, y, 30, stroke=colour, width=4)
if group == "field":
svg.text(x, y - 38, str(i + 1), 24, INK, halo=True)
svg.circle(40, 40, 14, stroke=ROSE, width=4)
svg.text(64, 49, "23 single dots", 28, INK, "start", halo=True)
svg.circle(40, 86, 14, stroke=TEAL, width=4)
svg.text(64, 95, "the cluster of seven", 28, INK, "start", halo=True)
svg.save(out / "nebra-dots.png")
def fig_cluster(data: dict, out: Path) -> None:
c = data["cluster"]
svg = Svg(1200, 640)
sky = np.array([complex(*p) for p in c["sky_xy"]])
disc = sm.CLUSTER - sm.CLUSTER.mean()
if c["shape_mirror"]:
disc = np.conj(disc)
fitted = complex(*c["shape_a"]) * disc + sky.mean()
def panel(points, cx, radius=190):
centred = points - points.mean()
k = radius / np.abs(centred).max()
return [(cx + k * p.real, 300 - k * p.imag) for p in centred], k, points.mean()
for x, y in panel(sm.CLUSTER, 300)[0]:
svg.circle(x, y, 28, fill=GOLD)
svg.text(300, 560, "On the disc", 36)
svg.text(300, 600, "a rosette: six around one", 24, MUTED)
placed, k, mean = panel(sky, 900)
mags = dict(zip(c["stars"], c["magnitudes"]))
taken = [(x - 14, y - 14, x + 14, y + 14) for x, y in placed]
for (x, y), name in zip(placed, c["stars"]):
svg.star(x, y, mags[name] - 1.2)
for k_sky, disc_index in enumerate(c["shape_order"]):
p = fitted[disc_index] - mean
x, y = 900 + k * p.real, 300 - k * p.imag
svg.line(x, y, *placed[k_sky], GOLD, 1.5, "4 4")
svg.circle(x, y, 17, stroke=GOLD, width=2.5)
place_labels(svg, [(x, y, n) for (x, y), n in zip(placed, c["stars"]) if n], 20, taken)
svg.text(900, 560, "In the sky", 36)
svg.text(900, 600, "the Pleiades, with the disc dots fitted on top (rings)", 24, MUTED)
svg.line(600, 80, 600, 600)
svg.save(out / "nebra-cluster.png")
def fig_scale(data: dict, sky: dict, out: Path) -> None:
c = data["cluster"]
svg = Svg(1200, 900)
alcyone = sky["proper"].index("Alcyone")
stars = np.flatnonzero(sky["mag"] <= 5.6)
centre = sky["vec"][alcyone]
away = np.degrees(np.arccos(np.clip(sky["vec"][stars] @ centre, -1, 1)))
stars = stars[away < 30]
z = sm.project(sky["vec"][stars], centre)
per_degree = 46.0
disc_radius = c["disc_degrees_to_scale"] / 2 * per_degree
# keep the cluster where it sits on the disc
offset = sm.CLUSTER.mean()
ox = 600 - disc_radius * offset.real
oy = 450 + disc_radius * offset.imag
for i, p in zip(stars, z):
x = ox + per_degree * np.degrees(p.real)
y = oy - per_degree * np.degrees(p.imag)
if -20 < x < 1220 and -20 < y < 920:
svg.star(x, y, sky["mag"][i])
if sky["mag"][i] < 3.2 and sky["proper"][i] not in ("", "Alcyone"):
svg.text(x + 14, y - 10, sky["proper"][i], 20, MUTED, "start", halo=True)
svg.circle(600, 450, disc_radius, stroke=GOLD, width=3)
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)
svg.text(ox + 20, oy - 40, "Pleiades", 26, INK, "start", halo=True)
moon = 0.52 / 2 * per_degree
svg.circle(90, 820, moon, fill=MUTED)
svg.text(120, 828, "the full Moon at the same scale", 22, MUTED, "start")
svg.save(out / "nebra-to-scale.png")
def fig_which(data: dict, out: Path) -> None:
index = data["main_index"]
run = data["runs"]["free"][index]
random = np.array([complex(*p) for p in run["examples"]["typical"]["dots"]])
svg = Svg(1200, 700)
for letter, cx, chart, dots, fit in (
("A", 300, data["charts"]["free_typical"], random, run["examples"]["typical"]["fit"]),
("B", 900, data["charts"]["free_hits"], sm.FIELD, run["hits"]["disc"]),
):
sky_chart(svg, data, chart, dots, cx, 320, 270, limit=data["settings"]["main"][0])
svg.text(cx, 660, letter, 44)
svg.text(cx + 40, 658, f"{fit['hits']} of 23 matched", 24, MUTED, "start")
svg.save(out / "nebra-which-is-which.png")
def fig_best(photo: Image.Image, data: dict, out: Path) -> None:
size = 1200
svg = Svg(size, size)
reach = 1.12
scale = size / 2 / reach
r = scale * 1.07
svg.add(f'')
dim = ImageEnhance.Brightness(crop_disc(photo, size, reach)).enhance(0.42)
svg.image(dim, 0, 0, size, size, "disc")
chart = data["charts"]["free_strict"]
sky_chart(svg, data, chart, sm.FIELD, 600, 600, scale, limit=data["settings"]["main"][0], names=True)
fit = data["runs"]["free"][data["main_index"]]["strict"]["disc"]
svg.text(32, 52, f"{fit['hits']} of 23 dots on a star", 30, GOLD, "start", halo=True)
svg.text(32, 92, f"the disc spans {chart['span_deg']:.0f}° of sky" + (", mirrored" if fit["mirror"] else ""), 24, INK, "start", halo=True)
svg.save(out / "nebra-best-fit.png")
def fig_chance(data: dict, out: Path) -> None:
svg = Svg(1200, 820)
index = data["main_index"]
panels = [
("free", "hits", "Anywhere in the sky: dots matched"),
("free", "strict", "Anywhere in the sky: strict score"),
("pinned", "hits", "Cluster on the Pleiades: dots matched"),
("pinned", "strict", "Cluster on the Pleiades: strict score"),
]
for n, (kind, score, title) in enumerate(panels):
x0, y0, w, h = 60 + (n % 2) * 580, 80 + (n // 2) * 390, 500, 250
block = data["runs"][kind][index][score]
null = np.array(block["null"])
disc = block["disc"]["hits" if score == "hits" else "score"]
if score == "hits":
edges = np.arange(min(null.min(), disc) - 0.5, max(null.max(), disc) + 1.5)
else:
edges = np.linspace(min(null.min(), disc) * 0.95, max(null.max(), disc) * 1.05, 30)
counts, _ = np.histogram(null, edges)
span = edges[-1] - edges[0]
px = lambda v: x0 + (v - edges[0]) / span * w
for left, right, count in zip(edges[:-1], edges[1:], counts):
bar = count / counts.max() * h
svg.add(f'')
svg.line(x0, y0 + h, x0 + w, y0 + h, MUTED)
ticks = (edges[:-1] + edges[1:]) / 2 if score == "hits" else np.linspace(edges[0], edges[-1], 5)
step = max(1, len(ticks) // 9) if score == "hits" else 1
for v in ticks[::step]:
svg.text(px(v), y0 + h + 26, f"{v:.0f}" if score == "hits" else f"{v:.2f}", 18, MUTED)
svg.line(px(disc), y0 - 6, px(disc), y0 + h, GOLD, 4)
svg.text(x0 + w / 2, y0 - 38, title, 25)
side = "start" if px(disc) < x0 + w * 0.6 else "end"
share = float(np.mean(null >= disc - 1e-4)) # the stored values have four decimals
svg.text(px(disc) + (10 if side == "start" else -10), y0 + 18, "the disc", 22, GOLD, side, halo=True)
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)
svg.text(600, 805, "bars: 1,000 random dot patterns, searched exactly like the disc", 22, MUTED)
svg.save(out / "nebra-chance.png")
def fig_spacing(data: dict, out: Path) -> None:
s = data["spacing"]
svg = Svg(1200, 560)
x0, y0, w, h = 80, 100, 1040, 340
random, field = np.array(s["random"]["variation"]), np.array(s["sky"]["variation"])
edges = np.linspace(0, 1.2, 73)
px = lambda v: x0 + v / 1.2 * w
shares = [np.histogram(v, edges)[0] / len(v) for v in (random, field)]
top = max(x.max() for x in shares)
for share, colour in zip(shares, (VIOLET, BLUE)):
path = f"M {px(edges[0]):.1f} {y0 + h}"
for left, right, value in zip(edges[:-1], edges[1:], share):
y = y0 + h - value / top * h
path += f" L {px(left):.1f} {y:.1f} L {px(right):.1f} {y:.1f}"
path += f" L {px(edges[-1]):.1f} {y0 + h} Z"
svg.add(f'')
svg.line(x0, y0 + h, x0 + w, y0 + h, MUTED)
for v in np.arange(0, 1.21, 0.2):
svg.text(px(v), y0 + h + 28, f"{v:.1f}", 18, MUTED)
disc = s["disc"]["variation"]
svg.line(px(disc), y0 - 20, px(disc), y0 + h, GOLD, 4)
svg.text(px(disc) + 12, y0 - 4, "the disc", 26, GOLD, "start", halo=True)
svg.text(600, 46, "How unevenly are 23 dots spaced?", 32)
svg.text(x0, y0 + h + 66, "← lattice-like", 22, MUTED, "start")
svg.text(x0 + w, y0 + h + 66, "clumped →", 22, MUTED, "end")
for k, (colour, text) in enumerate(((VIOLET, "random dots on the disc"), (BLUE, "the 23 brightest stars in a patch of sky"))):
svg.add(f'')
svg.text(738, 136 + k * 40, text, 21, INK, "start")
svg.text(600, 540, "variation of the distance to the nearest neighbour (standard deviation ÷ mean)", 20, MUTED)
svg.save(out / "nebra-spacing.png")
def fig_control(data: dict, out: Path) -> None:
rows = data["control"]["rows"]
svg = Svg(1200, 560)
x0, y0, w, h = 120, 100, 1000, 340
low, high = rows[0]["real"], rows[-1]["real"]
px = lambda v: x0 + (v - low) / (high - low) * w
py = lambda v: y0 + h - v * h
for v in (0, 0.25, 0.5, 0.75, 1):
svg.line(x0, py(v), x0 + w, py(v), FAINT, 1, "" if v == 0 else "3 6")
svg.text(x0 - 16, py(v) + 7, f"{v:.0%}", 20, MUTED, "end")
for r in rows:
svg.text(px(r["real"]), y0 + h + 32, str(r["real"]), 20, MUTED)
for key, colour, text in (("found_hits", VIOLET, "by dots matched"), ("found_strict", GOLD, "by the strict score")):
points = " ".join(f"{px(r['real']):.1f},{py(r[key]):.1f}" for r in rows)
svg.add(f'')
for r in rows:
svg.circle(px(r["real"]), py(r[key]), 7, fill=colour)
for k, (colour, text) in enumerate(((VIOLET, "judged by dots matched"), (GOLD, "judged by the strict score"))):
svg.line(160, 130 + k * 36, 200, 130 + k * 36, colour, 4)
svg.text(212, 137 + k * 36, text, 21, INK, "start")
svg.text(600, 48, "Would the search notice a real star map?", 32)
svg.text(600, 524, "true stars hidden among the 23 dots; line: how often the result beats 95 % of random patterns", 20, MUTED)
svg.save(out / "nebra-control.png")
def fig_cover(photo: Image.Image, data: dict, out: Path) -> None:
"""The disc, its left half as photographed, its right half as a star chart."""
svg = Svg(1200, 630)
rng = np.random.default_rng(3)
for x, y, r in zip(rng.uniform(0, 1200, 380), rng.uniform(0, 630, 380), rng.pareto(3, 380)):
svg.circle(x, y, min(2.4, 0.5 + r), fill=INK, opacity=0.4)
radius, reach = 285, 1.05
box = radius * reach
r = radius * 1.025
svg.add(f'')
svg.image(crop_disc(photo, 900, reach), 600 - box, 315 - box, 2 * box, 2 * box, "left")
svg.add('')
svg.add('')
svg.circle(600, 315, radius * 1.02, fill="#171029", stroke=GOLD, width=2)
chart = data["charts"]["free_hits"]
at = {i: (600 + radius * x, 315 - radius * y) for i, x, y in chart["stars"] if np.hypot(x, y) < 1.0}
for i, (x, y) in at.items():
svg.star(x, y, data["stars"][str(i)]["mag"])
matched = {int(k): v for k, v in chart["matched"].items()}
for i, d in enumerate(sm.FIELD):
x, y = 600 + radius * d.real, 315 - radius * d.imag
if i in matched and matched[i] in at:
svg.line(x, y, *at[matched[i]], GOLD, 2)
svg.circle(x, y, radius * 0.036, stroke=GOLD, width=2)
for d in sm.CLUSTER:
svg.circle(600 + radius * d.real, 315 - radius * d.imag, radius * 0.036, stroke=TEAL, width=2)
svg.add("")
svg.line(600, 14, 600, 616, INK, 1.5, "2 7", 0.8)
svg.save(out / "nebra-cover.png")
def main() -> None:
parser = argparse.ArgumentParser(description=__doc__.split("\n")[0])
parser.add_argument("--catalogue", type=Path, required=True)
parser.add_argument("--photo", type=Path, required=True)
parser.add_argument("--out", type=Path, default=HERE)
parser.add_argument("--results", type=Path, help="default: nebra-results.json in --out")
args = parser.parse_args()
data = json.loads((args.results or args.out / "nebra-results.json").read_text())
order = [[m, t] for m in sm.MAG_LIMITS for t in sm.TOLERANCES]
data["main_index"] = order.index(list(data["settings"]["main"]))
sky = sm.load_sky(args.catalogue)
photo = Image.open(args.photo).convert("RGB")
args.out.mkdir(parents=True, exist_ok=True)
photo.resize((2000, 2000), Image.LANCZOS).save(args.out / "nebra-disc.jpg", quality=86)
print(" nebra-disc.jpg")
fig_dots(photo, args.out)
fig_cluster(data, args.out)
fig_scale(data, sky, args.out)
fig_which(data, args.out)
fig_best(photo, data, args.out)
fig_chance(data, args.out)
fig_spacing(data, args.out)
fig_control(data, args.out)
fig_cover(photo, data, args.out)
if __name__ == "__main__":
main()