#!/usr/bin/env python3 """skymatch.py: do the gold dots of the Nebra Sky Disc map onto real stars? The 23 dots outside the cluster of seven are laid on the sky of 1600 BC as seen from Nebra: any position, any rotation, mirrored or not, within a range of sizes. The same search is then run on random dot patterns, so that a "match" counts only if chance does not produce it just as well. Two scores are taken for every layout: hits how many dots have a star within the tolerance (the generous reading) strict matched / (dots + stars in the covered area - matched), which also counts the bright stars a map would have had to leave out Experiments: free search over the visible sky; search with the cluster pinned to the Pleiades; the cluster against the shape of the real Pleiades; the spacing of the dots; and two checks that the search can find a real pattern at all. Usage: skymatch.py --catalogue hyg_v44.csv.gz [--out DIR] [--layouts N] [--jobs N] Needs: numpy, scipy Output: nebra-results.json Dot positions are pixels in Wikimedia Commons "Himmelsscheibe.Nebra.vorne.P1034154.jpg" (4336 x 4336, CC0), found by circle detection and checked by eye. """ from __future__ import annotations import argparse import csv import gzip import itertools import json import multiprocessing as mp import os import time from pathlib import Path import numpy as np from scipy.spatial import cKDTree # -------------------------------------------------------------------------------------- # The disc # -------------------------------------------------------------------------------------- CENTRE = (2160.0, 2105.0) # of the disc in the photo RADIUS = 1900.0 # one disc unit in pixels; the disc is about 32 cm across # 23 single dots, then the cluster of seven FIELD_PX = [ (2217, 463), (2658, 621), (1337, 737), (1954, 790), (1024, 1035), (1647, 1167), (3328, 1054), (951, 1615), (588, 2042), (890, 2460), (2626, 1997), (3061, 1888), (2543, 2494), (836, 2933), (1396, 2896), (1994, 2903), (2502, 3113), (1229, 3298), (1771, 3408), (2145, 3469), (2684, 3537), (3029, 3166), (3452, 2932), ] # fmt: skip CLUSTER_PX = [ (2623, 997), (2329, 1136), (2542, 1192), (2804, 1234), (2345, 1341), (2735, 1425), (2532, 1500), ] # fmt: skip SUN_PX = (1654, 2076, 601) # centre and radius of the large round plate MOON_PX = [ (3209, 1306), (3411, 1436), (3590, 1661), (3692, 1952), (3680, 2154), (3568, 2379), (3411, 2558), (3187, 2693), (2985, 2771), (2760, 2771), (2985, 2648), (3187, 2469), (3321, 2244), (3366, 1975), (3355, 1795), (3288, 1549), ] # fmt: skip def to_disc(px) -> np.ndarray: """Photo pixels to disc coordinates: complex numbers, y upwards, disc radius 1.""" return np.array([complex(x - CENTRE[0], CENTRE[1] - y) / RADIUS for x, y in px]) FIELD = to_disc(FIELD_PX) CLUSTER = to_disc(CLUSTER_PX) N = len(FIELD) DOT_RADIUS = 66 / RADIUS # -------------------------------------------------------------------------------------- # Search settings # -------------------------------------------------------------------------------------- EPOCH = -1599 # astronomical year numbering: 1600 BC LATITUDE = 51.28 # Mittelberg near Nebra MIN_ALTITUDE = 3.0 # a star must climb at least this high to count as visible MAG_LIMITS = (3.5, 4.5) TOLERANCES = (0.035, 0.05, 0.07) # of the disc radius: about 6, 8 and 11 mm MAIN = (3.5, 0.05) SPAN = (25.0, 90.0) # angle on the sky covered by the disc radius twice over, degrees CENTRE_REACH = 18.0 # the disc centre lands at most this far from a tile centre, degrees TILES = 60 # tile centres on the whole sphere GRID = 0.003 # raster step of the star distance maps, projection units EXTENT = 1.2 # half width of a distance map PINNED_SPAN = (25.0, 120.0) ANCHORS = 40 def plane_radius(span: float) -> float: """Radius in the stereographic plane of a circle `span` degrees across.""" return 2 * np.tan(np.radians(span) / 4) # -------------------------------------------------------------------------------------- # The sky # -------------------------------------------------------------------------------------- def precession(year: float) -> np.ndarray: """Rotation from J2000 equatorial to the equator of `year` (IAU 1976, Meeus ch. 21).""" t = (year - 2000) / 100 arcsec = np.pi / 180 / 3600 zeta = (2306.2181 * t + 0.30188 * t**2 + 0.017998 * t**3) * arcsec z = (2306.2181 * t + 1.09468 * t**2 + 0.018203 * t**3) * arcsec theta = (2004.3109 * t - 0.42665 * t**2 - 0.041833 * t**3) * arcsec def rz(a): return np.array([[np.cos(a), -np.sin(a), 0], [np.sin(a), np.cos(a), 0], [0, 0, 1]]) def ry(a): return np.array([[np.cos(a), 0, -np.sin(a)], [0, 1, 0], [np.sin(a), 0, np.cos(a)]]) return rz(z) @ ry(theta) @ rz(zeta) def unit(ra: np.ndarray, dec: np.ndarray) -> np.ndarray: return np.stack([np.cos(dec) * np.cos(ra), np.cos(dec) * np.sin(ra), np.sin(dec)], axis=-1) def load_sky(path: Path) -> dict: """Stars to magnitude 5.6 at their places in 1600 BC.""" rows = [] with gzip.open(path, "rt", newline="") as handle: for r in csv.DictReader(handle): if r["proper"] != "Sol" and r["mag"] and float(r["mag"]) <= 5.6: rows.append(r) col = lambda name: np.array([float(r[name] or 0) for r in rows]) ra, dec = col("rarad"), col("decrad") years = EPOCH - 2000 dec1 = dec + col("pmdecrad") * years ra1 = ra + col("pmrarad") * years / np.cos(dec) # pmra includes the cos(dec) factor vec = unit(ra1, dec1) @ precession(EPOCH).T return { "vec": vec, "mag": col("mag"), "dec": np.degrees(np.arcsin(np.clip(vec[:, 2], -1, 1))), "proper": [r["proper"] for r in rows], "bayer": [r["bayer"] for r in rows], "con": [r["con"] for r in rows], } def visible(sky: dict, limit: float) -> np.ndarray: return np.flatnonzero((sky["mag"] <= limit) & (sky["dec"] >= LATITUDE - 90 + MIN_ALTITUDE)) def basis(c: np.ndarray) -> tuple[np.ndarray, np.ndarray]: """East and north unit vectors at the direction c.""" east = np.cross([0.0, 0.0, 1.0], c) east /= np.linalg.norm(east) return east, np.cross(c, east) def project(vec: np.ndarray, c: np.ndarray) -> np.ndarray: """Stereographic chart centred on c, as the sky is seen: north up, east to the left.""" east, north = basis(c) k = 2 / (1 + np.clip(vec @ c, -0.999, 1)) return -k * (vec @ east) + 1j * k * (vec @ north) def tile_centres() -> np.ndarray: i = np.arange(TILES) + 0.5 z = 1 - 2 * i / TILES phi = i * np.pi * (3 - np.sqrt(5)) pts = np.stack([np.sqrt(1 - z**2) * np.cos(phi), np.sqrt(1 - z**2) * np.sin(phi), z], axis=1) return pts[np.degrees(np.arcsin(pts[:, 2])) >= -28] def build_tiles(sky: dict, limit: float) -> list[dict]: stars = visible(sky, limit) axis = np.arange(-EXTENT, EXTENT + GRID, GRID) gx, gy = np.meshgrid(axis, axis) cells = np.stack([gx.ravel(), gy.ravel()], axis=1) tiles = [] for c in tile_centres(): z = project(sky["vec"][stars], c) near = (np.abs(z.real) < EXTENT) & (np.abs(z.imag) < EXTENT) z, idx = z[near], stars[near] if len(z) < 8: continue dist, _ = cKDTree(np.stack([z.real, z.imag], axis=1)).query(cells) i, j = np.nonzero(~np.eye(len(z), dtype=bool)) tiles.append( { "centre": c, "z": z, "star": idx, "dist": dist.astype(np.float32).reshape(len(axis), len(axis)), "i": i, "j": j, } ) return tiles # -------------------------------------------------------------------------------------- # The allowed area on the disc, and random layouts in it # -------------------------------------------------------------------------------------- def inside_polygon(points: np.ndarray, poly: np.ndarray) -> np.ndarray: inside = np.zeros(points.shape, dtype=bool) for a, b in zip(poly, np.roll(poly, -1)): crosses = (a.imag > points.imag) != (b.imag > points.imag) with np.errstate(divide="ignore", invalid="ignore"): x = a.real + (points.imag - a.imag) / (b.imag - a.imag) * (b.real - a.real) inside ^= crosses & (points.real < x) return inside def allowed_mask(margin: float, step: float = 0.005) -> np.ndarray: """Where a single dot could sit: inside the disc, off the sun, the moon and the cluster.""" axis = np.arange(-1, 1 + step, step) gx, gy = np.meshgrid(axis, axis) p = gx + 1j * gy ok = np.abs(p) <= np.abs(FIELD).max() + margin sun = to_disc([SUN_PX[:2]])[0] ok &= np.abs(p - sun) > SUN_PX[2] / RADIUS + DOT_RADIUS - margin moon = to_disc(MOON_PX) near_moon = np.min([np.abs(p - m) for m in moon], axis=0) < DOT_RADIUS - margin ok &= ~(inside_polygon(p, moon) | near_moon) centre = CLUSTER.mean() ok &= np.abs(p - centre) > np.abs(CLUSTER - centre).max() + 2 * DOT_RADIUS - margin return ok MASK_STEP = 0.005 PLACE = allowed_mask(0.0) COUNT = allowed_mask(0.05) # a little wider, for counting stars in the covered area def mask_at(mask: np.ndarray, w: np.ndarray) -> np.ndarray: col = np.clip(((w.real + 1) / MASK_STEP).astype(np.int32), 0, mask.shape[1] - 1) row = np.clip(((w.imag + 1) / MASK_STEP).astype(np.int32), 0, mask.shape[0] - 1) return mask[row, col] def min_gap(points: np.ndarray) -> float: d = np.abs(points[:, None] - points[None, :]) np.fill_diagonal(d, np.inf) return float(d.min()) def random_layout(rng: np.random.Generator, gap: float, n: int = N) -> np.ndarray: """n random dots in the allowed area, no two closer than gap.""" rows, cols = np.nonzero(PLACE) cells = cols * MASK_STEP - 1 + 1j * (rows * MASK_STEP - 1) while True: dots: list[complex] = [] for p in cells[rng.integers(len(cells), size=4000)]: if all(abs(p - q) >= gap for q in dots): dots.append(p) if len(dots) == n: return np.array(dots) def evenness(d: np.ndarray) -> tuple[float, float]: """Smallest nearest-neighbour distance, and how much those distances vary (0 = a lattice).""" gaps = np.abs(d[:, None] - d[None, :]) np.fill_diagonal(gaps, np.inf) nearest = gaps.min(axis=1) return float(nearest.min()), float(nearest.std() / nearest.mean()) def even_layout(rng: np.random.Generator, gap: float) -> np.ndarray: """A random layout pushed apart until its spacing is as regular as the disc's.""" target = evenness(FIELD)[1] while True: dots = random_layout(rng, gap) for _ in range(400): if evenness(dots)[1] <= target: return dots diff = dots[:, None] - dots[None, :] dist = np.abs(diff) np.fill_diagonal(dist, np.inf) # push the closest neighbour of every dot away a little, staying in the allowed area near = dist.argmin(axis=1) for i in rng.permutation(len(dots)): if dist[i, near[i]] < np.median(dist.min(axis=1)): step = diff[i, near[i]] / dist[i, near[i]] * 0.01 step += 0.004 * complex(*rng.standard_normal(2)) trial = dots[i] + step others = np.delete(dots, i) if mask_at(PLACE, np.array(trial)) and np.abs(others - trial).min() >= gap: dots[i] = trial # -------------------------------------------------------------------------------------- # Matching # -------------------------------------------------------------------------------------- def anchor_pairs(dots: np.ndarray) -> list[tuple[int, int]]: """Long dot pairs, every dot used about equally often. They fix each trial placement.""" pairs = [(a, b) for a, b in itertools.combinations(range(len(dots)), 2) if 0.7 <= abs(dots[a] - dots[b]) <= 1.5] # fmt: skip rng = np.random.default_rng(1) rng.shuffle(pairs) used = np.zeros(len(dots)) chosen = [] while pairs and len(chosen) < ANCHORS: best = min(range(len(pairs)), key=lambda k: used[pairs[k][0]] + used[pairs[k][1]]) a, b = pairs.pop(best) chosen.append((a, b)) used[a] += 1 used[b] += 1 return chosen def strict_score(hits: np.ndarray, inside: np.ndarray, n: int) -> np.ndarray: return hits / (n + np.maximum(inside, hits) - hits) def stars_inside(z: np.ndarray, a: np.ndarray, b: np.ndarray, mirror: bool) -> np.ndarray: """For each placement, the number of stars falling on the allowed area of the disc.""" out = np.empty(len(a), dtype=np.int32) for k in range(0, len(a), 4000): w = (z[None, :] - b[k : k + 4000, None]) / a[k : k + 4000, None] if mirror: w = np.conj(w) out[k : k + 4000] = mask_at(COUNT, w).sum(axis=1) return out def refit(z: np.ndarray, dots: np.ndarray, a: complex, b: complex, mirror: bool, tol: float): """Least squares over the matched pairs, repeated while it gains matches.""" w = np.conj(dots) if mirror else dots best = None for _ in range(4): d = np.abs((a * w + b)[:, None] - z[None, :]) star = d.argmin(axis=1) miss = d[np.arange(len(w)), star] / abs(a) ok = miss <= tol hits = len(set(star[ok].tolist())) key = (hits, -float(miss[ok].mean()) if hits else 0.0) if best is None or key > best[0]: best = (key, a, b, star, ok, miss) if ok.sum() < 3: break x, y = w[ok], z[star[ok]] xm, ym = x.mean(), y.mean() a = np.sum(np.conj(x - xm) * (y - ym)) / np.sum(np.abs(x - xm) ** 2) b = ym - a * xm return best class Best: """Keeps the best placement for both scores.""" def __init__(self, dots: np.ndarray, tol: float): self.dots, self.tol, self.n = dots, tol, len(dots) self.hits = {"key": (-1, 0.0)} self.strict = {"key": -1.0} def offer(self, tile: int, z, a: complex, b: complex, mirror: bool) -> None: key, a, b, star, ok, miss = refit(z, self.dots, a, b, mirror, self.tol) inside = int(stars_inside(z, np.array([a]), np.array([b]), mirror)[0]) s = float(strict_score(np.array(key[0]), np.array(inside), self.n)) record = { "tile": tile, "a": [a.real, a.imag], "b": [b.real, b.imag], "mirror": mirror, "hits": key[0], "inside": inside, "score": s, "error": -key[1], "pairs": [[int(i), int(star[i]), float(miss[i])] for i in np.flatnonzero(ok)], } # fmt: skip if key > self.hits["key"]: self.hits = {"key": key, **record} if s > self.strict["key"]: self.strict = {"key": s, **record} def screen(self, tile: int, z, a, b, hits, mirror: bool) -> None: """Pass the promising placements of one batch on to the refit.""" top = hits.max() if top >= self.hits["key"][0] - 1: for k in np.flatnonzero(hits >= top)[:3]: self.offer(tile, z, a[k], b[k], mirror) floor = max(self.strict["key"], 0.0) * 0.9 maybe = np.flatnonzero((hits / self.n > floor) & (hits >= 4)) if len(maybe): inside = stars_inside(z, a[maybe], b[maybe], mirror) s = strict_score(hits[maybe], inside, self.n) k = int(s.argmax()) if s[k] > floor: self.offer(tile, z, a[maybe[k]], b[maybe[k]], mirror) def result(self) -> dict: return {name: {k: v for k, v in getattr(self, name).items() if k != "key"} for name in ("hits", "strict")} # fmt: skip def free_search(dots: np.ndarray, tiles: list[dict], tol: float) -> dict: """Lay the dots anywhere on the visible sky.""" best = Best(dots, tol) low, high = (plane_radius(s) for s in SPAN) reach = plane_radius(2 * CENTRE_REACH) anchors = anchor_pairs(dots) for t, tile in enumerate(tiles): z, dist = tile["z"], tile["dist"] zi, zj = z[tile["i"]], z[tile["j"]] diff = zj - zi length = np.abs(diff) for mirror in (False, True): w = np.conj(dots) if mirror else dots for p, q in anchors: base = w[q] - w[p] span = abs(base) keep = np.flatnonzero((length >= low * span) & (length <= high * span)) a = diff[keep] / base b = zi[keep] - a * w[p] near = np.abs(b) <= reach a, b = a[near], b[near] if not len(a): continue limit = (tol * np.abs(a)).astype(np.float32) hits = np.zeros(len(a), dtype=np.int16) for dot in w: pos = a * dot + b col = np.clip((pos.real + EXTENT) / GRID + 0.5, 0, dist.shape[1] - 1) row = np.clip((pos.imag + EXTENT) / GRID + 0.5, 0, dist.shape[0] - 1) hits += dist[row.astype(np.int32), col.astype(np.int32)] <= limit best.screen(t, z, a, b, hits, mirror) return best.result() def pinned_tile(sky: dict, limit: float) -> dict: """A chart centred on the Pleiades, for the search with the cluster pinned to them.""" alcyone = sky["proper"].index("Alcyone") centre = sky["vec"][alcyone] stars = visible(sky, limit) cluster = np.degrees(np.arccos(np.clip(sky["vec"][stars] @ centre, -1, 1))) keep = (cluster > 2.0) & (cluster < 115) # the Pleiades themselves are spoken for stars = stars[keep] return {"centre": centre, "star": stars, "z": project(sky["vec"][stars], centre)} def pinned_search(dots: np.ndarray, tile: dict, tol: float) -> dict: """Every rotation and size that puts some dot exactly on some star, the cluster fixed.""" best = Best(dots, tol) z = tile["z"] anchor = CLUSTER.mean() low, high = (plane_radius(s) for s in PINNED_SPAN) for mirror in (False, True): w = np.conj(dots) if mirror else dots pin = np.conj(anchor) if mirror else anchor a = (z[None, :] / (w - pin)[:, None]).ravel() a = a[(np.abs(a) >= low) & (np.abs(a) <= high)] b = -a * pin # the cluster centre maps to 0, the Pleiades hits = np.zeros(len(a), dtype=np.int16) for k in range(0, len(a), 400): pos = a[k : k + 400, None] * w[None, :] + b[k : k + 400, None] near = np.abs(pos[:, :, None] - z[None, None, :]).min(axis=2) hits[k : k + 400] = (near <= tol * np.abs(a[k : k + 400, None])).sum(axis=1) # no free refit here: it would move the cluster off the Pleiades for k in np.flatnonzero(hits == hits.max())[:40]: record_pinned(best, "hits", z, a[k], b[k], mirror, int(hits[k])) inside = stars_inside(z, a, b, mirror) s = strict_score(hits, inside, len(dots)) record_pinned(best, "strict", z, a[s.argmax()], b[s.argmax()], mirror, int(hits[s.argmax()])) return best.result() def record_pinned(best: Best, name: str, z, a, b, mirror: bool, hits: int) -> None: w = np.conj(best.dots) if mirror else best.dots d = np.abs((a * w + b)[:, None] - z[None, :]) star = d.argmin(axis=1) miss = d[np.arange(len(w)), star] / abs(a) ok = miss <= best.tol inside = int(stars_inside(z, np.array([a]), np.array([b]), mirror)[0]) s = float(strict_score(np.array(hits), np.array(inside), best.n)) error = float(miss[ok].mean()) if ok.any() else 0.0 key = (hits, -error) if name == "hits" else s if key > getattr(best, name)["key"]: setattr(best, name, { "key": key, "tile": 0, "a": [a.real, a.imag], "b": [b.real, b.imag], "mirror": mirror, "hits": hits, "inside": inside, "score": s, "error": error, "pairs": [[int(i), int(star[i]), float(miss[i])] for i in np.flatnonzero(ok)], }) # fmt: skip # -------------------------------------------------------------------------------------- # Parallel runs # -------------------------------------------------------------------------------------- SHARED: dict = {} # filled before the workers fork def run_one(job): kind, setting, dots = job limit, tol = setting if kind == "free": return free_search(dots, SHARED["tiles"][limit], tol) return pinned_search(dots, SHARED["pinned"][limit], tol) def p_value(real: float, null: np.ndarray) -> float: """Share of random layouts scoring at least as well as the disc.""" return float((1 + np.sum(null >= real - 1e-9)) / (1 + len(null))) def compare(pool, kind: str, setting, layouts: list[np.ndarray]) -> dict: started = time.time() results = pool.map(run_one, [(kind, setting, d) for d in [FIELD, *layouts]], chunksize=1) real, null = results[0], results[1:] out = {"magnitude": setting[0], "tolerance": setting[1], "layouts": len(null)} for name, field in (("hits", "hits"), ("strict", "score")): values = np.array([r[name][field] for r in null]) out[name] = { "disc": real[name], "null": [round(float(v), 4) for v in values], "p": p_value(real[name][field], values), } sample = int(np.argsort([r["hits"]["hits"] for r in null])[len(null) // 2]) best = int(np.argmax([r["hits"]["hits"] - r["hits"]["error"] for r in null])) out["examples"] = { label: {"dots": [[p.real, p.imag] for p in layouts[k]], "fit": null[k]["hits"]} for label, k in (("typical", sample), ("luckiest", best)) } print( f" {kind:6s} mag {setting[0]} tol {setting[1]:.3f}: " f"hits {real['hits']['hits']} (p {out['hits']['p']:.3f}), " f"strict {real['strict']['score']:.3f} (p {out['strict']['p']:.3f}), " f"{time.time() - started:.0f} s", flush=True, ) return out # -------------------------------------------------------------------------------------- # Checks: can the search find a pattern that is really there? # -------------------------------------------------------------------------------------- def planted_layout(rng, sky: dict, real: int, noise: float, gap: float) -> np.ndarray | None: """A layout holding `real` true stars from one patch of sky, the rest random.""" stars = visible(sky, MAIN[0]) for _ in range(200): c = sky["vec"][rng.choice(stars[sky["dec"][stars] > 0])] a = plane_radius(rng.uniform(45, 75)) * np.exp(1j * rng.uniform(0, 2 * np.pi)) w = project(sky["vec"][stars], c) / a w = w[(np.abs(w) < 1) & mask_at(PLACE, w)] rng.shuffle(w) dots: list[complex] = [] for p in w: if all(abs(p - q) >= gap for q in dots) and len(dots) < real: dots.append(p) if len(dots) < real: continue dots = [p + noise * complex(*rng.standard_normal(2)) for p in dots] rows, cols = np.nonzero(PLACE) for k in rng.integers(len(rows), size=6000): p = complex(cols[k] * MASK_STEP - 1, rows[k] * MASK_STEP - 1) if len(dots) < N and all(abs(p - q) >= gap for q in dots): dots.append(p) if len(dots) == N: return np.array(dots) return None def control(pool, sky: dict, null_hits: np.ndarray, null_strict: np.ndarray, trials: int) -> dict: gap = min_gap(FIELD) bar_hits, bar_strict = np.quantile(null_hits, 0.95), np.quantile(null_strict, 0.95) rows = [] for real in (6, 9, 12, 13, 14, 15, 18): rng = np.random.default_rng(100 + real) layouts = [planted_layout(rng, sky, real, 0.015, gap) for _ in range(trials)] layouts = [d for d in layouts if d is not None] found = pool.map(run_one, [("free", MAIN, d) for d in layouts], chunksize=1) hits = np.array([r["hits"]["hits"] for r in found]) strict = np.array([r["strict"]["score"] for r in found]) rows.append( { "real": real, "trials": len(layouts), "median_hits": float(np.median(hits)), "median_strict": float(np.median(strict)), "found_hits": float(np.mean(hits > bar_hits)), "found_strict": float(np.mean(strict > bar_strict)), } ) print( f" control: {real:2d} true stars -> beats 95 % of chance in " f"{rows[-1]['found_hits']:.0%} (hits), {rows[-1]['found_strict']:.0%} (strict)", flush=True, ) return {"noise": 0.015, "bar_hits": float(bar_hits), "bar_strict": float(bar_strict), "rows": rows} # -------------------------------------------------------------------------------------- # The cluster of seven, and the spacing of the dots # -------------------------------------------------------------------------------------- def procrustes(source: np.ndarray, target: np.ndarray): """Best order, rotation, size and mirroring of source onto target. Error in target sizes.""" perms = np.array(list(itertools.permutations(range(len(source))))) size = np.sqrt(np.mean(np.abs(target - target.mean()) ** 2)) t = target - target.mean() best = (np.inf,) for mirror in (False, True): s = np.conj(source) if mirror else source s = s - s.mean() ordered = s[perms] a = (np.conj(ordered) @ t) / np.sum(np.abs(s) ** 2) err = np.sqrt(np.mean(np.abs(a[:, None] * ordered - t[None, :]) ** 2, axis=1)) / size k = int(err.argmin()) if err[k] < best[0]: best = (float(err[k]), mirror, perms[k], a[k]) return best def cluster_study(sky: dict, trials: int) -> dict: alcyone = sky["proper"].index("Alcyone") centre = sky["vec"][alcyone] away = np.degrees(np.arccos(np.clip(sky["vec"] @ centre, -1, 1))) near = np.flatnonzero(away < 1.5) nine = near[np.argsort(sky["mag"][near])][:9] # any seven of the nine brightest may be the ones meant, whichever fits best choices = [np.array(c) for c in itertools.combinations(nine, 7)] shapes = [project(sky["vec"][c], centre) for c in choices] def closest(dots: np.ndarray): fits = [procrustes(dots, shape) for shape in shapes] k = int(np.argmin([f[0] for f in fits])) return k, fits[k] chosen, (error, mirror, order, a) = closest(CLUSTER) seven, sky_shape = choices[chosen], shapes[chosen] vec = sky["vec"][nine] width = float(np.degrees(np.arccos(np.clip(vec @ vec.T, -1, 1))).max()) disc_width = max(abs(p - q) for p in CLUSTER for q in CLUSTER) rng = np.random.default_rng(7) gap = 0.75 * min_gap(CLUSTER) # room enough for random clusters to be drawn radius = np.abs(CLUSTER - CLUSTER.mean()).max() null = [] for _ in range(trials): dots: list[complex] = [] while len(dots) < 7: p = complex(*rng.uniform(-radius, radius, 2)) if abs(p) <= radius and all(abs(p - q) >= gap for q in dots): dots.append(p) elif rng.random() < 0.001: dots = [] null.append(closest(np.array(dots))[1][0]) null = np.array(null) # drawn to scale, how much sky would the disc hold, and what is in it? degrees_per_unit = width / disc_width disc_degrees = 2 * degrees_per_unit others = [ int(np.sum((sky["mag"] <= m) & (away < disc_degrees / 2) & (away > 1.5))) for m in (4.5, 5.0) ] return { "stars": [sky["proper"][i] or sky["bayer"][i] for i in seven], "magnitudes": [float(sky["mag"][i]) for i in seven], "nine": [sky["proper"][i] or sky["bayer"][i] for i in nine], "sky_xy": [[p.real, p.imag] for p in sky_shape], "sky_width_deg": width, "disc_width": float(disc_width), "share_of_disc": float(disc_width / 2), "disc_degrees_to_scale": float(disc_degrees), "other_stars_to_scale": {"4.5": others[0], "5.0": others[1]}, "shape_error": error, "shape_mirror": mirror, "shape_order": [int(i) for i in order], "shape_a": [a.real, a.imag], "shape_null": [round(float(v), 4) for v in null], "shape_p": float((1 + np.sum(null <= error)) / (1 + len(null))), } def spacing_study(sky: dict, trials: int) -> dict: """Nearest neighbour distances: the disc, random dots, and real star fields.""" rng = np.random.default_rng(11) touching = 2 * DOT_RADIUS # dots cannot overlap random = np.array([evenness(random_layout(rng, touching)) for _ in range(trials)]) stars = visible(sky, 5.0) fields = [] while len(fields) < trials: c = sky["vec"][rng.choice(stars[sky["dec"][stars] > -10])] a = plane_radius(rng.uniform(*SPAN)) w = project(sky["vec"][stars], c) / a mags = sky["mag"][stars] ok = np.flatnonzero((np.abs(w) < 1) & mask_at(PLACE, w)) if len(ok) >= N: fields.append(evenness(w[ok[np.argsort(mags[ok])][:N]])) fields = np.array(fields) low, spread = evenness(FIELD) return { "disc": {"min_gap": low, "variation": spread}, "random": {"min_gap": random[:, 0].round(4).tolist(), "variation": random[:, 1].round(4).tolist()}, "sky": {"min_gap": fields[:, 0].round(4).tolist(), "variation": fields[:, 1].round(4).tolist()}, "p_random": float((1 + np.sum(random[:, 1] <= spread)) / (1 + trials)), "p_sky": float((1 + np.sum(fields[:, 1] <= spread)) / (1 + trials)), } # -------------------------------------------------------------------------------------- # Main # -------------------------------------------------------------------------------------- def star_table(sky: dict, indices) -> dict: return { str(i): { "proper": sky["proper"][i], "bayer": sky["bayer"][i], "con": sky["con"][i], "mag": float(sky["mag"][i]), } # fmt: skip for i in sorted(set(int(i) for i in indices)) } def chart_of(sky: dict, tiles: list[dict], fit: dict) -> dict: """The stars around one fitted placement, in disc coordinates, for drawing.""" tile = tiles[fit["tile"]] a, b = complex(*fit["a"]), complex(*fit["b"]) deep = visible(sky, 5.0) w = (project(sky["vec"][deep], tile["centre"]) - b) / a if fit["mirror"]: w = np.conj(w) keep = np.abs(w) < 1.6 matched = {int(i): int(tile["star"][s]) for i, s, _ in fit["pairs"]} # the sky direction under the disc centre (w = 0, so z = b), from the inverse projection east, north = basis(tile["centre"]) x, y = -b.real / 2, b.imag / 2 r2 = x * x + y * y centre = ((1 - r2) * tile["centre"] + 2 * x * east + 2 * y * north) / (1 + r2) return { "stars": [[int(i), round(float(p.real), 4), round(float(p.imag), 4)] for i, p in zip(deep[keep], w[keep])], "matched": matched, "span_deg": float(np.degrees(4 * np.arctan(abs(a) / 2))), "centre_ra_h": float(np.degrees(np.arctan2(centre[1], centre[0])) % 360 / 15), "centre_dec": float(np.degrees(np.arcsin(centre[2]))), } def main() -> None: parser = argparse.ArgumentParser(description=__doc__.split("\n")[0]) parser.add_argument("--catalogue", type=Path, required=True, help="HYG CSV, gzipped") parser.add_argument("--out", type=Path, default=Path(__file__).resolve().parent) parser.add_argument("--layouts", type=int, default=1000, help="random layouts for the main run") parser.add_argument("--jobs", type=int, default=os.cpu_count()) args = parser.parse_args() started = time.time() sky = load_sky(args.catalogue) thuban = sky["proper"].index("Thuban") print(f"{len(sky['mag'])} stars; Thuban stood at declination {sky['dec'][thuban]:.1f} in 1600 BC") for limit in MAG_LIMITS: SHARED.setdefault("tiles", {})[limit] = build_tiles(sky, limit) SHARED.setdefault("pinned", {})[limit] = pinned_tile(sky, limit) print(f" magnitude {limit}: {len(visible(sky, limit))} visible stars") gap = min_gap(FIELD) rng = np.random.default_rng(2026) layouts = [random_layout(rng, gap) for _ in range(args.layouts)] fewer = layouts[: max(20, args.layouts // 5)] runs = {"free": [], "pinned": []} with mp.get_context("fork").Pool(args.jobs) as pool: for kind in ("free", "pinned"): for setting in itertools.product(MAG_LIMITS, TOLERANCES): runs[kind].append(compare(pool, kind, setting, layouts if setting == MAIN else fewer)) main_free = runs["free"][list(itertools.product(MAG_LIMITS, TOLERANCES)).index(MAIN)] checks = control( pool, sky, np.array(main_free["hits"]["null"]), np.array(main_free["strict"]["null"]), max(10, args.layouts // 10), ) # fmt: skip print(" against random layouts spaced as evenly as the disc:", flush=True) rng_even = np.random.default_rng(1600) even = [even_layout(rng_even, gap) for _ in range(args.layouts)] evened = { kind: [compare(pool, kind, (limit, MAIN[1]), even) for limit in MAG_LIMITS] for kind in ("free", "pinned") } cluster = cluster_study(sky, max(200, args.layouts // 2)) spacing = spacing_study(sky, max(200, args.layouts * 4)) # charts for the figures charts, used = {}, [] index = list(itertools.product(MAG_LIMITS, TOLERANCES)).index(MAIN) for kind, table in (("free", SHARED["tiles"][MAIN[0]]), ("pinned", [SHARED["pinned"][MAIN[0]]])): run = runs[kind][index] fits = { "hits": run["hits"]["disc"], "strict": run["strict"]["disc"], "typical": run["examples"]["typical"]["fit"], "luckiest": run["examples"]["luckiest"]["fit"], } for name, fit in fits.items(): chart = chart_of(sky, table, fit) charts[f"{kind}_{name}"] = chart used += [s[0] for s in chart["stars"]] results = { "epoch": "1600 BC", "latitude": LATITUDE, "dots": {"field": FIELD_PX, "cluster": CLUSTER_PX, "centre": CENTRE, "radius": RADIUS}, "settings": {"span_deg": SPAN, "min_gap": gap, "main": MAIN}, "visible": {str(m): int(len(visible(sky, m))) for m in MAG_LIMITS}, "runs": runs, "even": evened, "control": checks, "cluster": cluster, "spacing": spacing, "charts": charts, "stars": star_table(sky, used), } args.out.mkdir(parents=True, exist_ok=True) path = args.out / "nebra-results.json" path.write_text(json.dumps(results, separators=(",", ":"), default=float) + "\n") print( f"cluster: {cluster['share_of_disc']:.0%} of the disc width; to scale the disc would span " f"{cluster['disc_degrees_to_scale']:.1f} degrees; shape p {cluster['shape_p']:.3f}\n" f"spacing: evenness p {spacing['p_random']:.4f} against random dots, " f"{spacing['p_sky']:.4f} against star fields\n" f"wrote {path} in {time.time() - started:.0f} s" ) if __name__ == "__main__": main()