#!/usr/bin/env python3 """Fetch heliocentric ecliptic positions (no velocities) from the JPL Horizons API, one file per body and year. Standard library only; adapted from /planet-alignments-earthquakes/fetch_horizons.py. Each reply is saved as Horizons sent it, and fetch-log.jsonl gets the query URL, size, SHA-256 and time. python3 -I fetch_horizons_pos.py [ ...] e.g. python3 -I fetch_horizons_pos.py 1h 2010 2026 199 299 399 499 599 699 799 899 Each year's table runs from 31 December of the year before, 22:00, to 1 January of the year after, 02:00 (TDB), so consecutive tables overlap by a few hours. The Sun (10) is the coordinate origin. """ import datetime import hashlib import json import pathlib import sys import time import urllib.parse import urllib.request API = "https://ssd.jpl.nasa.gov/api/horizons.api" UA = "factchecked-research/1.0" def query_url(body, start, stop, step): params = { "format": "text", "COMMAND": f"'{body}'", "OBJ_DATA": "'NO'", "MAKE_EPHEM": "'YES'", "EPHEM_TYPE": "'VECTORS'", "CENTER": "'500@10'", "START_TIME": f"'{start}'", "STOP_TIME": f"'{stop}'", "STEP_SIZE": f"'{step}'", "REF_PLANE": "'ECLIPTIC'", "REF_SYSTEM": "'ICRF'", "OUT_UNITS": "'AU-D'", "VEC_TABLE": "'1'", "VEC_CORR": "'NONE'", "CSV_FORMAT": "'YES'", "VEC_LABELS": "'NO'", "TIME_DIGITS": "'MINUTES'", } return API + "?" + urllib.parse.urlencode(params, quote_via=urllib.parse.quote) def main(): outdir = pathlib.Path(sys.argv[1]) step, y0, y1 = sys.argv[2], int(sys.argv[3]), int(sys.argv[4]) bodies = sys.argv[5:] outdir.mkdir(parents=True, exist_ok=True) log = outdir / "fetch-log.jsonl" for year in range(y0, y1 + 1): start, stop = f"{year - 1}-12-31 22:00", f"{year + 1}-01-01 02:00" for body in bodies: name = f"{body}_{year}_{step}.txt" path = outdir / name if path.exists(): continue url = query_url(body, start, stop, step) for attempt in range(4): try: req = urllib.request.Request(url, headers={"User-Agent": UA}) with urllib.request.urlopen(req, timeout=300) as r: data = r.read() break except Exception as e: # network hiccup: wait and retry print("retry", body, year, e, flush=True) time.sleep(10 * (attempt + 1)) else: raise SystemExit(f"failed: {url}") text = data.decode("utf-8") if "$$SOE" not in text or "$$EOE" not in text: raise SystemExit(f"no ephemeris in reply for {body} {year}:\n{text[:2000]}") path.write_bytes(data) rec = {"file": name, "url": url, "bytes": len(data), "sha256": hashlib.sha256(data).hexdigest(), "fetched_utc": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")} with log.open("a", encoding="utf-8", newline="\n") as f: f.write(json.dumps(rec) + "\n") print("got", name, len(data), flush=True) time.sleep(1.5) if __name__ == "__main__": main()