#!/usr/bin/env python3 """Reproduce the frozen 2026 six-city twilight table using Python's standard library. Usage: python3 reproduce-v1.py [directory-containing-the-downloads] The event formula is a Python translation of SunCalc 1.9.0, not an independent astronomical model. A separate NOAA/Meeus solar-position root solver checks 24 disclosed city/date samples. Model agreement is not observed-sky accuracy. SunCalc source header: (c) 2011-2015, Vladimir Agafonkin. The original SunCalc 1.9.0 LICENSE is retained verbatim below: Copyright (c) 2014, Vladimir Agafonkin All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """ import csv import json import math from datetime import datetime, timezone from pathlib import Path import sys RAD = math.pi / 180 sin, cos, tan = math.sin, math.cos, math.tan EVENTS = [('sunset', -0.833), ('civil_end', -6), ('nautical_end', -12), ('astronomical_end', -18)] def translated_events(date, city): d = datetime.fromisoformat(date + 'T20:00:00+00:00').timestamp() / 86400 + 2440587.5 - 2451545 lw, phi = -city['longitude'] * RAD, city['latitude'] * RAD cycle = math.floor(d - 0.0009 - lw / (2 * math.pi) + 0.5) ds = 0.0009 + lw / (2 * math.pi) + cycle anomaly = RAD * (357.5291 + 0.98560028 * ds) ecliptic = anomaly + RAD * (1.9148 * sin(anomaly) + 0.02 * sin(2 * anomaly) + 0.0003 * sin(3 * anomaly) + 102.9372) + math.pi dec = math.asin(sin(ecliptic) * sin(RAD * 23.4397)) result = {} for key, angle in EVENTS: q = (sin(angle * RAD) - sin(phi) * sin(dec)) / (cos(phi) * cos(dec)) if not -1 <= q <= 1: result[key] = None continue hour = math.acos(q) transit = 0.0009 + (hour + lw) / (2 * math.pi) + cycle julian = 2451545 + transit + 0.0053 * sin(anomaly) - 0.0069 * sin(2 * ecliptic) result[key] = (julian - 2440587.5) * 86400 return result def noaa_altitude(timestamp, lat, lon): """NOAA published Meeus solar-position equations; geometric centre altitude. Equations documented by NOAA's solar calculator. No live NOAA API is used, no atmosphere/terrain correction is applied to twilight altitudes. """ jd = timestamp / 86400 + 2440587.5 t = (jd - 2451545) / 36525 l = (280.46646 + t * (36000.76983 + t * 0.0003032)) % 360 m = 357.52911 + t * (35999.05029 - 0.0001537 * t) ecc = 0.016708634 - t * (0.000042037 + 0.0000001267 * t) center = (sin(m * RAD) * (1.914602 - t * (0.004817 + 0.000014 * t)) + sin(2 * m * RAD) * (0.019993 - 0.000101 * t) + sin(3 * m * RAD) * 0.000289) omega = 125.04 - 1934.136 * t apparent = l + center - 0.00569 - 0.00478 * sin(omega * RAD) mean_ob = 23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60) / 60 ob = mean_ob + 0.00256 * cos(omega * RAD) dec = math.asin(sin(ob * RAD) * sin(apparent * RAD)) y = tan(ob * RAD / 2) ** 2 eot = 4 / RAD * (y * sin(2 * l * RAD) - 2 * ecc * sin(m * RAD) + 4 * ecc * y * sin(m * RAD) * cos(2 * l * RAD) - 0.5 * y * y * sin(4 * l * RAD) - 1.25 * ecc * ecc * sin(2 * m * RAD)) utc_minutes = (timestamp % 86400) / 60 ha = (((utc_minutes + eot + 4 * lon) % 1440) / 4 - 180) * RAD return math.asin(sin(lat * RAD) * sin(dec) + cos(lat * RAD) * cos(dec) * cos(ha)) / RAD def numerical_event(estimate, angle, city): lo, hi = estimate - 1800, estimate + 1800 fn = lambda ts: noaa_altitude(ts, city['latitude'], city['longitude']) - angle if not (fn(lo) > 0 > fn(hi)): raise ValueError('Evening event not bracketed') for _ in range(42): mid = (lo + hi) / 2 if fn(mid) > 0: lo = mid else: hi = mid return (lo + hi) / 2 def main(): folder = Path(sys.argv[1]) if len(sys.argv) > 1 else Path(__file__).resolve().parent cities = {c['id']: c for c in json.loads((folder / 'cities-v1.json').read_text())} rows = list(csv.DictReader((folder / 'daily-v1.csv').open(newline=''))) if len(rows) != 2190 or len({(r['city_id'], r['date']) for r in rows}) != 2190: raise ValueError('Expected 2190 distinct city/date rows') max_seconds = 0 crosscheck = [] sample_dates = {'2026-03-20', '2026-06-21', '2026-09-22', '2026-12-21'} for row in rows: city = cities[row['city_id']] calc = translated_events(row['date'], city) for key, angle in EVENTS: expected = datetime.fromisoformat(row[key + '_utc'].replace('Z', '+00:00')).timestamp() delta = abs(calc[key] - expected) max_seconds = max(max_seconds, delta) if delta > 0.002: raise ValueError('Reproduction mismatch: ' + str(row)) for stage, key in [('civil', 'civil_end'), ('nautical', 'nautical_end'), ('astronomical', 'astronomical_end')]: if abs((calc[key] - calc['sunset']) / 60 - float(row[stage + '_minutes'])) > 0.001: raise ValueError('Duration mismatch') if row['date'] in sample_dates: alt_events = {key: numerical_event(calc[key], angle, city) for key, angle in EVENTS} event_delta = {key: round(abs(alt_events[key] - calc[key]) / 60, 4) for key, _ in EVENTS} duration_delta = {stage: round(abs((alt_events[key] - alt_events['sunset']) - (calc[key] - calc['sunset'])) / 60, 4) for stage, key in [('civil', 'civil_end'), ('nautical', 'nautical_end'), ('astronomical', 'astronomical_end')]} crosscheck.append({'cityId': city['id'], 'date': row['date'], 'eventDifferenceMinutes': event_delta, 'durationDifferenceMinutes': duration_delta}) report = {'reproducedRows': len(rows), 'reproducedEvents': len(rows) * 4, 'maxReproductionDifferenceSeconds': round(max_seconds, 6), 'noaaMeeusCrosscheckRows': len(crosscheck), 'maxCrosscheckEventDifferenceMinutes': max(max(x['eventDifferenceMinutes'].values()) for x in crosscheck), 'maxCrosscheckDurationDifferenceMinutes': max(max(x['durationDifferenceMinutes'].values()) for x in crosscheck), 'crosscheck': crosscheck, 'scope': 'Formula reproduction and a 24-row separate model check; not observed sky brightness or an official NOAA/USNO certification.'} print(json.dumps(report, indent=2)) if __name__ == '__main__': main()