#!/usr/bin/env python3
"""Placidus against Whole Sign houses for every recorded 2025 US birth time.

Takes the CDC/NCHS count of 2025 US births by month and recorded clock minute
(month_minute.csv from the ZodiScope birth time study, ../us-birth-times-2025/)
and casts the sky for every one of those minutes at 13 US cities with the NASA
JPL DE440 ephemeris (de440s.bsp) through Skyfield, tropical zodiac. For each
birth it finds the house of the Sun, the Moon and the eight planets in two
house systems, Placidus and Whole Sign, and counts how often they differ.

The public file has no state and no day of the month, so the model spreads each
month's births evenly over its days and places ALL births in one city at a time
(the method of the birth time study). City figures are model figures for "births
timed like the US in 2025, born in city X", never counts of real people there.

Usage:
  python3 house_systems.py --counts ../us-birth-times-2025/month_minute.csv \
      --ephem de440s.bsp --out house_systems_results.json
  python3 house_systems.py --check --ephem de440s.bsp \
      --counts ../us-birth-times-2025/month_minute.csv --results house_systems_results.json

Requires numpy and skyfield (tested with skyfield 1.55, numpy 2.0). The --check
mode also needs pyswisseph (2.10) and ephem (PyEphem 4.2), which compute planet
positions and Placidus cusps with their own code, independent of this script.
"""
from __future__ import annotations

import argparse
import calendar
import csv
import json
import math
from datetime import datetime, timedelta, timezone
from zoneinfo import ZoneInfo

import numpy as np
from skyfield.api import Loader
from skyfield.framelib import ecliptic_frame

SIGNS = ["Aries", "Taurus", "Gemini", "Cancer", "Leo", "Virgo", "Libra",
         "Scorpio", "Sagittarius", "Capricorn", "Aquarius", "Pisces"]

# Body name in this study, then its target in de440s.bsp.
BODIES = [
    ("Sun", "sun"), ("Moon", "moon"), ("Mercury", "mercury"), ("Venus", "venus"),
    ("Mars", "mars barycenter"), ("Jupiter", "jupiter barycenter"),
    ("Saturn", "saturn barycenter"), ("Uranus", "uranus barycenter"),
    ("Neptune", "neptune barycenter"), ("Pluto", "pluto barycenter"),
]
NAMES = [b[0] for b in BODIES]

# The 13 cities of the birth time study: name, latitude (deg N), longitude (deg E), zone.
CITIES = [
    ("Honolulu", 21.3069, -157.8583, "Pacific/Honolulu"),
    ("Miami", 25.7617, -80.1918, "America/New_York"),
    ("Houston", 29.7604, -95.3698, "America/Chicago"),
    ("Phoenix", 33.4484, -112.0740, "America/Phoenix"),
    ("Atlanta", 33.7490, -84.3880, "America/New_York"),
    ("Los Angeles", 34.0522, -118.2437, "America/Los_Angeles"),
    ("Denver", 39.7392, -104.9903, "America/Denver"),
    ("New York", 40.7128, -74.0060, "America/New_York"),
    ("Chicago", 41.8781, -87.6298, "America/Chicago"),
    ("Boston", 42.3601, -71.0589, "America/New_York"),
    ("Minneapolis", 44.9778, -93.2650, "America/Chicago"),
    ("Seattle", 47.6062, -122.3321, "America/Los_Angeles"),
    ("Anchorage", 61.2181, -149.9003, "America/Anchorage"),
]

SHIFT = 15  # minutes: the birth time error tested


class Sky:
    """Ecliptic longitudes of the ten bodies, GAST and true obliquity at every UT
    minute of a span (apparent geocentric positions, ecliptic and equinox of date)."""

    def __init__(self, ephem_path: str, start_utc: datetime, minutes: int):
        load = Loader(".")
        self.ts = load.timescale(builtin=True)
        eph = load(ephem_path)
        earth = eph["earth"]
        self.start = start_utc
        self.lon = np.empty((len(BODIES), minutes))
        self.gast = np.empty(minutes)
        self.eps = np.empty(minutes)
        chunk = 100_000
        for a in range(0, minutes, chunk):
            b = min(minutes, a + chunk)
            m = np.arange(a, b, dtype=float)
            t = self.ts.utc(start_utc.year, start_utc.month, start_utc.day,
                            start_utc.hour, start_utc.minute + m)
            e = earth.at(t)
            for k, (_, target) in enumerate(BODIES):
                _, lon, _ = e.observe(eph[target]).apparent().frame_latlon(ecliptic_frame)
                self.lon[k, a:b] = lon.degrees
            self.gast[a:b] = t.gast
            T = (t.tt - 2451545.0) / 36525.0
            eps0 = (84381.406 - 46.836769 * T - 0.0001831 * T**2) / 3600.0
            _, d_eps = t._nutation_angles_radians
            self.eps[a:b] = eps0 + np.degrees(d_eps)

    def index(self, utc: datetime) -> int:
        return int((utc - self.start).total_seconds() // 60)


# ---------------------------------------------------------------------------
# Houses
# ---------------------------------------------------------------------------

def ascendant(ramc_deg, eps_deg, lat_deg):
    ramc, e, phi = np.radians(ramc_deg), np.radians(eps_deg), math.radians(lat_deg)
    asc = np.degrees(np.arctan2(np.cos(ramc), -(np.sin(ramc) * np.cos(e) + math.tan(phi) * np.sin(e))))
    return asc % 360.0


def midheaven(ramc_deg, eps_deg):
    ramc, e = np.radians(ramc_deg), np.radians(eps_deg)
    return np.degrees(np.arctan2(np.sin(ramc), np.cos(ramc) * np.cos(e))) % 360.0


def placidus_cusps(ramc_deg, eps_deg, lat_deg, iterations=30):
    """Twelve Placidus cusps (N x 12, degrees). Cusps 11, 12, 2 and 3 by the
    semi-arc method: the cusp of house 11 is the ecliptic point whose right
    ascension is RAMC + DSA/3, where DSA is that point's own diurnal semi-arc
    (house 12: RAMC + 2 DSA/3; house 2: RAMC + 180 - 2 NSA/3; house 3:
    RAMC + 180 - NSA/3, NSA = 180 - DSA). Solved by fixed-point iteration.
    Valid south of the polar circle, where every ecliptic point rises and sets
    (all 13 study cities). North of it Placidus is not always defined; this
    code then returns NaN and the study stops (see city_model)."""
    ramc = np.asarray(ramc_deg, dtype=float)
    e = np.radians(np.asarray(eps_deg, dtype=float))
    tphi = math.tan(math.radians(lat_deg))

    def solve(base, sign, frac, nocturnal):
        ra = np.radians(base + sign * 30.0 * (3 * frac))  # equal-RA start
        for _ in range(iterations):
            lam = np.arctan2(np.sin(ra), np.cos(ra) * np.cos(e))
            dec = np.arcsin(np.sin(e) * np.sin(lam))
            x = -tphi * np.tan(dec)
            with np.errstate(invalid="ignore"):
                dsa = np.degrees(np.arccos(x))  # NaN when |x| > 1
            arc = (180.0 - dsa) if nocturnal else dsa
            ra = np.radians(base + sign * frac * arc)
        lam = np.degrees(np.arctan2(np.sin(ra), np.cos(ra) * np.cos(e))) % 360.0
        return lam

    c = np.empty(ramc.shape + (12,))
    c[..., 9] = midheaven(ramc, np.degrees(e))
    c[..., 0] = ascendant(ramc, np.degrees(e), lat_deg)
    c[..., 10] = solve(ramc, +1, 1 / 3, False)          # 11th
    c[..., 11] = solve(ramc, +1, 2 / 3, False)          # 12th
    c[..., 1] = solve(ramc + 180.0, -1, 2 / 3, True)    # 2nd
    c[..., 2] = solve(ramc + 180.0, -1, 1 / 3, True)    # 3rd
    for i, j in ((3, 9), (4, 10), (5, 11), (6, 0), (7, 1), (8, 2)):
        c[..., i] = (c[..., j] + 180.0) % 360.0
    return c


def house_of(lon, cusps):
    """House number 1-12 of each longitude against N x 12 cusps."""
    lon = np.asarray(lon)[..., None]
    start = cusps
    end = np.roll(cusps, -1, axis=-1)
    width = (end - start) % 360.0
    inside = ((lon - start) % 360.0) < width
    return np.argmax(inside, axis=-1) + 1


def sign_of(lon):
    return (np.floor(np.asarray(lon) / 30.0).astype(int)) % 12


def whole_sign_house(lon, asc):
    return (sign_of(lon) - sign_of(asc)) % 12 + 1


# ---------------------------------------------------------------------------
# Birth weights (the method of ../us-birth-times-2025/sky_model.py)
# ---------------------------------------------------------------------------

def local_minutes_to_ut_index(sky: Sky, year: int, zone: str):
    """For every local clock minute of `year`: month, minute of day, UT index,
    days in month. Clock times in the spring-forward gap take the pre-change
    offset (fold=0); in the repeated autumn hour the first pass is used."""
    tz = ZoneInfo(zone)
    months, mods, idx, dim = [], [], [], []
    d = datetime(year, 1, 1)
    base_mod = np.arange(1440)
    while d.year == year:
        ndays = calendar.monthrange(year, d.month)[1]
        offs = np.empty(1440)
        for h in range(24):
            offs[h * 60:(h + 1) * 60] = d.replace(hour=h, tzinfo=tz).utcoffset().total_seconds() / 60.0
        local0 = sky.index(d.replace(tzinfo=timezone.utc))
        idx.append(local0 + base_mod - offs.astype(int))
        months.append(np.full(1440, d.month))
        mods.append(base_mod)
        dim.append(np.full(1440, ndays))
        d += timedelta(days=1)
    return (np.concatenate(months), np.concatenate(mods),
            np.concatenate(idx), np.concatenate(dim))


def read_counts(path: str):
    table = np.zeros((13, 1440))
    with open(path, newline="") as f:
        for row in csv.DictReader(f):
            t = row["time_hhmm"].strip()
            if t in ("9999", ""):
                continue
            hhmm = int(t)
            table[int(row["month"]), (hhmm // 100) * 60 + hhmm % 100] += int(row["births"])
    return table


# ---------------------------------------------------------------------------
# One city
# ---------------------------------------------------------------------------

def chart_at(sky: Sky, j, lat, lon):
    ramc = (sky.gast[j] * 15.0 + lon) % 360.0
    eps = sky.eps[j]
    cusps = placidus_cusps(ramc, eps, lat)
    pl = sky.lon[:, j]                       # 10 x N
    plac = np.stack([house_of(pl[k], cusps) for k in range(len(BODIES))])
    whole = whole_sign_house(pl, cusps[:, 0][None, :])
    return cusps, plac, whole


def city_model(sky: Sky, year: int, city, table):
    name, lat, lon, zone = city
    months, mods, idx, dim = local_minutes_to_ut_index(sky, year, zone)
    w = table[months, mods] / dim
    W = w.sum()
    ones = np.ones_like(w)

    def share(mask, weights=w):
        return float(weights[mask].sum() / weights.sum())

    cusps, plac, whole = chart_at(sky, idx, lat, lon)
    if np.isnan(cusps).any():
        raise SystemExit(f"{name}: Placidus cusps undefined at some minute; city is too far north")
    differ = plac != whole                    # 10 x N
    n_differ = differ.sum(axis=0)
    seven = differ[:7]                       # Sun to Saturn

    res = {"city": name, "lat": lat, "lon": lon, "zone": zone, "births_modelled": float(W)}
    res["planet_changes_house"] = {
        NAMES[k]: {"births": share(differ[k]), "sky": share(differ[k], ones)} for k in range(len(BODIES))}
    # Direction: is the Whole Sign house one later than the Placidus house?
    res["planet_whole_sign_one_later"] = {
        NAMES[k]: float(w[differ[k] & (((whole[k] - plac[k]) % 12) == 1)].sum() / w[differ[k]].sum())
        for k in range(len(BODIES))}
    res["planet_whole_sign_one_earlier"] = {
        NAMES[k]: float(w[differ[k] & (((plac[k] - whole[k]) % 12) == 1)].sum() / w[differ[k]].sum())
        for k in range(len(BODIES))}
    res["any_of_10_changes"] = {"births": share(n_differ > 0), "sky": share(n_differ > 0, ones)}
    res["any_of_sun_to_saturn_changes"] = {"births": share(seven.any(axis=0))}
    res["sun_or_moon_changes"] = {"births": share(differ[0] | differ[1])}
    res["mean_planets_changing_of_10"] = float((w * n_differ).sum() / W)
    res["planets_changing_distribution"] = {int(k): share(n_differ == k) for k in range(11)}
    res["half_or_more_of_10_change"] = share(n_differ >= 5)

    # Placidus house sizes and intercepted signs.
    width = (np.roll(cusps, -1, axis=-1) - cusps) % 360.0
    cusp_signs = sign_of(cusps)
    # Vectorised distinct-sign count: a 12-bit mask per chart.
    bits = np.zeros(len(w), dtype=np.int64)
    for i in range(12):
        bits |= (1 << cusp_signs[:, i].astype(np.int64))
    distinct = np.array([bin(int(b)).count("1") for b in np.unique(bits)])
    lookup = dict(zip(np.unique(bits).tolist(), distinct.tolist()))
    n_distinct = np.vectorize(lookup.get)(bits)
    intercepted = 12 - n_distinct
    res["intercepted_signs_any"] = {"births": share(intercepted > 0), "sky": share(intercepted > 0, ones)}
    res["intercepted_pairs_mean"] = float((w * intercepted).sum() / W / 2)
    maxw, minw = width.max(axis=1), width.min(axis=1)

    def wquant(x, q):
        o = np.argsort(x)
        cw = np.cumsum(w[o]) / W
        return float(x[o][np.searchsorted(cw, q)])

    res["largest_house_deg"] = {"median": wquant(maxw, 0.5), "max": float(maxw.max())}
    res["smallest_house_deg"] = {"median": wquant(minw, 0.5), "min": float(minw.min())}
    res["largest_house_over_45deg"] = share(maxw > 45.0)
    res["largest_house_over_60deg"] = share(maxw > 60.0)

    # The Midheaven's Whole Sign house (it starts the 10th in Placidus).
    mc_ws = whole_sign_house(cusps[:, 9], cusps[:, 0])
    res["mc_whole_sign_house"] = {int(h): share(mc_ws == h) for h in range(1, 13) if share(mc_ws == h) > 0}
    res["mc_outside_whole_sign_10th"] = share(mc_ws != 10)

    # A birth time SHIFT minutes off, either way (location fixed).
    for label, sys_idx in (("placidus", 1), ("whole_sign", 2)):
        moved_any = np.zeros(len(w), dtype=bool)
        moved_count = np.zeros(len(w))
        for s in (+SHIFT, -SHIFT):
            out = chart_at(sky, idx + s, lat, lon)
            moved = (out[sys_idx] != (plac if sys_idx == 1 else whole))
            moved_any |= moved.any(axis=0)
            moved_count = np.maximum(moved_count, moved.sum(axis=0))
        res[f"time_off_{SHIFT}min_{label}"] = {
            "any_planet_moves_births": share(moved_any),
            "any_planet_moves_sky": share(moved_any, ones),
            "mean_planets_moving_when_any": float((w * moved_count)[moved_any].sum() / w[moved_any].sum()),
        }
    # Rising sign changes within SHIFT minutes either way (the Whole Sign trigger).
    asc_sign = sign_of(cusps[:, 0])
    rs = np.zeros(len(w), dtype=bool)
    for s in (+SHIFT, -SHIFT):
        j = idx + s
        a2 = ascendant((sky.gast[j] * 15.0 + lon) % 360.0, sky.eps[j], lat)
        rs |= sign_of(a2) != asc_sign
    res[f"rising_sign_changes_within_{SHIFT}min"] = share(rs)

    # Sun by birth hour (local clock): share of births with a different Sun house.
    hour = mods // 60
    res["sun_changes_by_birth_hour"] = {
        int(h): float(w[(hour == h) & differ[0]].sum() / w[hour == h].sum()) for h in range(24)}
    res["sun_hours_per_day_different_sky"] = float(differ[0].mean() * 24)
    res["moon_hours_per_day_different_sky"] = float(differ[1].mean() * 24)
    # Which pairs of houses the Sun moves between, by births.
    pairs = {}
    for p in range(1, 13):
        for q in range(1, 13):
            if p == q:
                continue
            m = differ[0] & (plac[0] == p) & (whole[0] == q)
            v = float(w[m].sum() / W)
            if v > 0.005:
                pairs[f"{p}->{q}"] = v
    res["sun_moves_placidus_to_whole_sign"] = dict(sorted(pairs.items(), key=lambda kv: -kv[1]))
    return res


# ---------------------------------------------------------------------------
# Independent checks
# ---------------------------------------------------------------------------

def _plain_house(lon, cusps):
    """Independent house lookup for the checks (plain Python, no numpy, no
    study helpers): the house whose cusp the longitude has most recently passed."""
    for i in range(12):
        start, end = cusps[i], cusps[(i + 1) % 12]
        if (lon - start) % 360.0 < (end - start) % 360.0:
            return i + 1
    raise ValueError("no house")


def _plain_whole_sign(lon, asc):
    return (int(lon // 30) - int(asc // 30)) % 12 + 1


def check(ephem_path: str):
    """1. Our Placidus cusps against pyswisseph's swe.houses_armc on 20,000
    random (RAMC, obliquity, latitude) sets, latitudes 0-65 degrees.
    2. The whole pipeline (Skyfield DE440 planets, our sidereal time and cusps)
    against an independent one (PyEphem planets with its own VSOP87 and lunar
    theory, pyswisseph cusps from swe.houses on the UT Julian day) for 5,000
    random 2025 birth minutes in random study cities: houses in both systems.
    Prints the differences; exits 1 if a cusp differs by more than 0.01 deg."""
    import random
    import sys
    import ephem
    import swisseph as swe

    rng = random.Random(2025)
    worst = 0.0
    for _ in range(20_000):
        armc, eps, lat = rng.uniform(0, 360), rng.uniform(23.43, 23.45), rng.uniform(0, 65)
        cs, _ = swe.houses_armc(armc, lat, eps, b"P")
        ours = placidus_cusps(np.array([armc]), np.array([eps]), lat)[0]
        d = np.abs((ours - np.array(cs[:12]) + 180) % 360 - 180).max()
        worst = max(worst, float(d))
    print(f"check 1: largest Placidus cusp difference vs swe.houses_armc: {worst * 3600:.4f} arcsec")
    ok = worst < 0.01

    start = datetime(2024, 12, 31, tzinfo=timezone.utc)
    sky = Sky(ephem_path, start, 368 * 1440)
    bodies = [ephem.Sun(), ephem.Moon(), ephem.Mercury(), ephem.Venus(), ephem.Mars(),
              ephem.Jupiter(), ephem.Saturn(), ephem.Uranus(), ephem.Neptune(), ephem.Pluto()]
    mism_p = mism_w = total = 0
    max_planet = 0.0
    near = []
    for _ in range(5000):
        name, lat, lon, zone = rng.choice(CITIES)
        local = datetime(2025, 1, 1) + timedelta(minutes=rng.randrange(365 * 1440))
        utc = local.replace(tzinfo=ZoneInfo(zone)).astimezone(timezone.utc)
        j = sky.index(utc)
        cusps, plac, whole = chart_at(sky, np.array([j]), lat, lon)
        jd = swe.julday(utc.year, utc.month, utc.day, utc.hour + utc.minute / 60.0)
        cs, ascmc = swe.houses(jd, lat, lon, b"P")
        cs = np.array(cs[:12])
        obs = ephem.Observer()
        obs.date = utc.strftime("%Y/%m/%d %H:%M:%S")
        for k, b in enumerate(bodies):
            b.compute(obs.date, epoch=obs.date)
            ecl = ephem.Ecliptic(ephem.Equatorial(b.ra, b.dec, epoch=obs.date), epoch=obs.date)
            plon = math.degrees(ecl.lon)
            max_planet = max(max_planet, abs((plon - sky.lon[k, j] + 180) % 360 - 180))
            hp = _plain_house(plon, list(cs))
            hw = _plain_whole_sign(plon, cs[0])
            total += 1
            if hp != plac[k, 0]:
                mism_p += 1
                near.append(float(np.abs((cusps[0] - sky.lon[k, j] + 180) % 360 - 180).min()))
            if hw != whole[k, 0]:
                mism_w += 1
    print(f"check 2: {total} planet placements. Placidus house differs in {mism_p}, "
          f"Whole Sign house in {mism_w}. Largest planet longitude gap (PyEphem vs Skyfield DE440): "
          f"{max_planet * 3600:.1f} arcsec")
    if near:
        print(f"         every Placidus mismatch sits within {max(near) * 60:.2f} arcmin of a cusp")
    if not ok:
        print("FAIL: our Placidus code disagrees with the Swiss Ephemeris")
        sys.exit(1)


def resample(counts_path: str, results_path: str, n: int = 20_000):
    """3. The headline shares again, by a separate route that shares no code
    with the study: draw n births per city at random from the CDC counts (a
    random day of the birth month), convert the clock time with zoneinfo, take
    planets from PyEphem and Placidus cusps from pyswisseph's swe.houses, and
    count. Sampling error at n = 20,000 is about 0.7 points (95%) for a share
    near 50%."""
    import random
    import ephem
    import swisseph as swe

    counts = {}
    with open(counts_path, newline="") as f:  # read again here, without the study's reader
        for row in csv.DictReader(f):
            t = row["time_hhmm"].strip()
            if t and t != "9999":
                key = (int(row["month"]), int(t[:2]) * 60 + int(t[2:]))
                counts[key] = counts.get(key, 0) + int(row["births"])
    keys = sorted(counts)
    weights = [counts[k] for k in keys]
    published = {c["city"]: c for c in json.load(open(results_path))["cities"]}
    rng = random.Random(1590)
    bodies = [ephem.Sun(), ephem.Moon(), ephem.Mercury(), ephem.Venus(), ephem.Mars(),
              ephem.Jupiter(), ephem.Saturn(), ephem.Uranus(), ephem.Neptune(), ephem.Pluto()]
    for name, lat, lon, zone in [c for c in CITIES if c[0] in ("Miami", "New York", "Anchorage")]:
        differ = np.zeros(len(bodies))
        any10 = inter = mc_out = 0
        for (m, mod) in rng.choices(keys, weights=weights, k=n):
            day = rng.randint(1, calendar.monthrange(2025, m)[1])
            local = datetime(2025, m, day, mod // 60, mod % 60, tzinfo=ZoneInfo(zone))
            utc = local.astimezone(timezone.utc)
            jd = swe.julday(utc.year, utc.month, utc.day, utc.hour + utc.minute / 60.0)
            cs, ascmc = swe.houses(jd, lat, lon, b"P")
            cs = np.array(cs[:12])
            date = ephem.Date(utc.strftime("%Y/%m/%d %H:%M:%S"))
            moved = 0
            for k, b in enumerate(bodies):
                b.compute(date, epoch=date)
                plon = math.degrees(ephem.Ecliptic(ephem.Equatorial(b.ra, b.dec, epoch=date), epoch=date).lon)
                hp = _plain_house(plon, list(cs))
                hw = _plain_whole_sign(plon, cs[0])
                if hp != hw:
                    differ[k] += 1
                    moved += 1
            any10 += moved > 0
            inter += len({int(c // 30) for c in cs}) < 12
            mc_out += (int(ascmc[1] // 30) - int(cs[0] // 30)) % 12 + 1 != 10
        pub = published[name]
        print(f"check 3, {name} ({n} sampled births): resampled vs published, gap in points")
        gaps = []
        rows = [(b, differ[k] / n, pub['planet_changes_house'][b]['births']) for k, b in enumerate(NAMES)]
        rows += [("any of 10", any10 / n, pub['any_of_10_changes']['births']),
                 ("intercepted", inter / n, pub['intercepted_signs_any']['births']),
                 ("MC outside WS 10th", mc_out / n, pub['mc_outside_whole_sign_10th'])]
        for label, a, b in rows:
            gaps.append(abs(a - b) * 100)
            print(f"  {label:18} {a * 100:6.2f}%  {b * 100:6.2f}%  {abs(a - b) * 100:4.2f}")
        print(f"  largest gap {max(gaps):.2f} points")


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--ephem", required=True)
    ap.add_argument("--counts")
    ap.add_argument("--year", type=int, default=2025)
    ap.add_argument("--out")
    ap.add_argument("--check", action="store_true")
    ap.add_argument("--results", help="with --check and --counts: also resample the published results")
    args = ap.parse_args()
    if args.check:
        check(args.ephem)
        if args.counts and args.results:
            resample(args.counts, args.results)
        return
    year = args.year
    start = datetime(year - 1, 12, 31, tzinfo=timezone.utc)
    days = 366 + (1 if calendar.isleap(year) else 0) + 2
    sky = Sky(args.ephem, start, days * 1440)
    table = read_counts(args.counts)
    results = {
        "year": year,
        "ephemeris": "JPL DE440 (de440s.bsp) via Skyfield",
        "zodiac": "tropical",
        "bodies": NAMES,
        "time_error_minutes": SHIFT,
        "method_note": ("Each month's 2025 CDC births by recorded clock minute are spread evenly over "
                        "the days of that month and cast at each city in turn. Placidus cusps by the "
                        "semi-arc method; Whole Sign houses from the Ascendant's sign. Model figures, "
                        "not counts of people born in the city."),
        "cities": [city_model(sky, year, c, table) for c in CITIES],
    }
    with open(args.out, "w") as f:
        json.dump(results, f, indent=2)
    print("wrote", args.out)


if __name__ == "__main__":
    main()
