Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : ORIX Cosmos10# File : DataPipeline/ephemeris/fetch_missions.py11# Description : Builds the missions pack from JPL Horizons spacecraft12# trajectories: adaptive sampling of barycentric state13# vectors, ORIXTRJ binary files, independent interpolation14# check, per-mission manifest (coverage, cadence, source15# notes, cited events). Standard library only.16# Module : DataPipeline17# Repository : https://git.spboucher.ai/orix-cosmos18# Project Website : https://www.orixlab.dev19# Created : 2026-11-2420# Last Modified : 2026-11-2421#22# =============================================================================23# AUTHOR & PROFESSIONAL AFFILIATION24# =============================================================================25#26# Author : Simon-Pierre Boucher27# Position : Professor of Finance28# Institution : Université du Québec en Outaouais (UQO)29# Department : Département des sciences administratives30# Organization : SP Boucher31#32# Website : https://spboucher.ai33# Git : https://git.spboucher.ai34#35# =============================================================================36# OFFICIAL CONTACT DIRECTORY37# =============================================================================38#39# General : info@spboucher.ai40# Professional : contact@spboucher.ai41# Direct : simon@spboucher.ai42# Research : research@spboucher.ai43# Development : dev@spboucher.ai44# Support : support@spboucher.ai45# Security/Admin : admin@spboucher.ai46# Notifications : notifications@spboucher.ai47#48# Preferred Contact: support@spboucher.ai49#50# =============================================================================51# COPYRIGHT & INTELLECTUAL PROPERTY52# =============================================================================53#54# Copyright (c) 202655# Simon-Pierre Boucher56#57# All rights reserved where applicable.58#59# This file is governed by the applicable project license,60# copyright notices, institutional agreements and relevant law.61#62# Unless expressly authorized by the applicable license or63# rights holder, copying, redistribution, sublicensing,64# publication and commercial exploitation are not permitted.65#66# Existing third-party rights and notices remain unaffected.67#68# =============================================================================69# CONFIDENTIALITY & SECURITY70# =============================================================================71#72# Classification : Public73# Distribution : Public repository; use is governed by the project license74# Security Contact : admin@spboucher.ai75#76# Access to this source does not independently grant permission77# to redistribute or disclose confidential materials.78#79# Do not embed credentials, private keys, access tokens,80# certificates or confidential personal information.81#82# =============================================================================83# LICENSE & MAINTENANCE84# =============================================================================85#86# License : None specified (no license file in this repository)87# Maintainer : Simon-Pierre Boucher88# Technical Contact: dev@spboucher.ai89#90# =============================================================================91# END OF SP BOUCHER SOURCE HEADER92# =============================================================================9394"""Usage: fetch_missions.py [mission-key ...]95 fetch_missions.py --manifest-only rewrite manifest.json from the pack as it is on disk (no network)9697For each mission the script98 1. asks Horizons for its data sheet and for the limits of its trajectory (probe requests outside the limits);99 2. samples the state relative to the solar system barycentre (ICRF, km, km/s, TDB) on a coarse grid, estimates100 the cubic-Hermite interpolation error of every interval from the data themselves, and re-samples the101 intervals above the tolerance on finer and finer grids (ladder LADDER_MIN);102 3. writes Resources/Packs/missions/<key>.trj (format ORIXTRJ v1, metres and m/s);103 4. fetches states at instants *between* samples and measures the real interpolation error (also saved as a104 test fixture);105 5. records everything in Resources/Packs/missions/manifest.json (pack manifest schema v1: files[], sources[],106 redistribution; the per-mission records are the extension key "missions").107108These are trajectories reconstructed or predicted by the navigation teams and served by JPL Horizons; they are109not live telemetry. Nothing is invented: where Horizons has no data, nothing is written.110"""111import hashlib112import json113import math114import os115import random116import re117import struct118import sys119import datetime120121sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))122import horizons as hz # noqa: E402123124PACK = os.path.join(hz.ROOT, "Resources", "Packs", "missions")125FIXTURES = os.path.join(hz.ROOT, "Packages", "CosmosEphemeris", "Tests", "Fixtures", "horizons")126LADDER_MIN = [2880, 240, 20, 2] # sampling steps, minutes (each divides the previous one)127TOLERANCE_KM = 1.0 # estimated interpolation error above which an interval is re-sampled128MAX_ROWS = 40000 # rows per request (Horizons limit is about 90 000)129MONTHS = ["JAN", "FEB", "MAR", "APR", "MAY", "JUN", "JUL", "AUG", "SEP", "OCT", "NOV", "DEC"]130NASA_V1 = "https://science.nasa.gov/mission/voyager/voyager-1/"131132# Events: only those stated by the JPL Horizons data sheet of the object (quote checked verbatim by this script)133# or by the cited NASA page (checked by hand on the stated date).134MISSIONS = [135 {"key": "voyager-1", "id": "naif:-31", "command": "-31", "name": "Voyager 1", "end_cap": "2050-01-01 00:00",136 "events": [137 {"date": "1977-09-05", "time_utc": "12:56:01", "label": "Launch", "source": NASA_V1,138 "quote": "Launch Date and Time Sept. 5, 1977 / 12:56:01 UT", "checked": "by hand, 2026-11-24",139 "note": "The Horizons data sheet prints 1977-Sep-06 for the launch, which contradicts its own trajectory start (1977-Sep-05 13:59 TDB); the NASA mission page is used instead."},140 {"date": "1979-03-05", "label": "Jupiter closest approach", "quote": "1979-Mar-05 Jupiter closest-approach, Io imaging"},141 {"date": "1980-11-12", "label": "Saturn encounter (Titan)", "quote": "1980-Nov-12 Saturn encounter, Titan"},142 {"date": "2012-08-25", "label": "Heliopause crossing", "quote": "2012-Aug-25 Passes heliopause and termination shock boundary"},143 ]},144 {"key": "voyager-2", "id": "naif:-32", "command": "-32", "name": "Voyager 2", "end_cap": "2050-01-01 00:00",145 "events": [146 {"date": "1977-08-20", "time_utc": "14:29", "label": "Launch", "quote": "1977-Aug-20 Launch from Kennedy Space Center @ 14:29 UTC"},147 {"date": "1979-07-09", "label": "Jupiter closest approach", "quote": "1979-Jul-09 Jupiter closest-approach"},148 {"date": "1981-08-25", "label": "Saturn encounter", "quote": "1981-Aug-25 Saturn encounter"},149 {"date": "1986-01-24", "label": "Uranus encounter", "quote": "1986-Jan-24 First Uranus encounter"},150 {"date": "1989-08-25", "label": "Neptune encounter", "quote": "1989-Aug-25 First Neptune encounter"},151 {"date": "2018-11-15", "label": "Heliopause crossing", "quote": "2018-Nov-15 Crossed heliopause, entered interstellar space"},152 ]},153 {"key": "cassini", "id": "naif:-82", "command": "-82", "name": "Cassini",154 "events": [155 {"date": "2005-01-14", "label": "Huygens probe lands on Titan", "quote": "It landed on Titan's surface on Jan. 14, 2005."},156 {"date": "2017-09-15", "time_utc": "10:31", "label": "Atmospheric entry at Saturn, end of mission",157 "quote": "Atmospheric entry begins; thrusters firing at 10% of capacity"},158 ]},159 {"key": "new-horizons", "id": "naif:-98", "command": "-98", "name": "New Horizons",160 "events": [161 {"date": "2006-01-19", "label": "Launch", "quote": "2006-Jan-19 ... launch"},162 {"date": "2007-02-28", "time_utc": "05:43", "label": "Jupiter gravity assist", "quote": "2007-Feb-28 ... Jupiter gravity assist (05:43 UTC"},163 {"date": "2015-07-14", "time_utc": "11:49:57", "label": "Pluto-Charon encounter", "quote": "2015-Jul-14 ... Pluto Charon encounter @ 11:49:57 UTC"},164 {"date": "2019-01-01", "time_utc": "05:33", "label": "Arrokoth (2014 MU69) flyby", "quote": "Arrokoth (2014 MU69) flyby @ 05:33 UTC"},165 ]},166 {"key": "parker-solar-probe", "id": "naif:-96", "command": "-96", "name": "Parker Solar Probe",167 "events": [168 {"date": "2018-08-12", "time_utc": "07:31", "label": "Launch", "quote": "2018-Aug-12 07:31 UTC from NASA Kennedy Space Center"},169 {"date": "2018-10-03", "time_utc": "08:44", "label": "Venus flyby 1", "quote": "2018-Oct-03: Venus Flyby #1 @ 8:44 UTC"},170 {"date": "2018-11-06", "time_utc": "03:27", "label": "Perihelion 1", "quote": "2018-Nov-06: Perihelion #1 @ 03:27 UTC"},171 {"date": "2019-12-26", "label": "Venus flyby 2", "quote": "2019-Dec-26: Venus flyby #2"},172 {"date": "2020-07-11", "label": "Venus flyby 3", "quote": "2020-Jul-11: Venus flyby #3"},173 {"date": "2021-02-20", "label": "Venus flyby 4", "quote": "2021-Feb-20: Venus flyby #4"},174 {"date": "2021-10-16", "label": "Venus flyby 5", "quote": "2021-Oct-16: Venus flyby #5"},175 {"date": "2023-08-21", "label": "Venus flyby 6", "quote": "2023-Aug-21: Venus flyby #6"},176 {"date": "2024-11-06", "label": "Venus flyby 7 (last)", "quote": "2024-Nov-06: Venus flyby #7 (last one)"},177 {"date": "2024-12-24", "label": "Perihelion 22 (first closest approach)", "quote": "2024-Dec-24: Perihelion #22 (first close approach)"},178 ]},179 {"key": "jwst", "id": "naif:-170", "command": "-170", "name": "James Webb Space Telescope",180 "events": [181 {"date": "2021-12-25", "time_utc": "12:20", "label": "Launch", "quote": "Launched by Ariane 5 booster on 2021-Dec-25 @ 12:20 UTC"},182 {"date": "2022-01-24", "time_utc": "19:00", "label": "Mid-course correction MCC2 (L2 halo orbit insertion burn)",183 "quote": "MCC2 (04:57 engine burn) began 2022-Jan-24 19:00 UTC"},184 ]},185 {"key": "apollo-8-s-ivb", "id": "mission:apollo-8-s-ivb", "command": "-399080", "name": "Apollo 8 S-IVB stage",186 "events": [{"date": "1968-12-21", "time_utc": "12:51", "label": "Apollo 8 launch", "quote": "Launched: December 21, 1968 @ 12:51 GMT/UTC"}]},187 {"key": "apollo-9-s-ivb", "id": "mission:apollo-9-s-ivb", "command": "-399090", "name": "Apollo 9 S-IVB stage",188 "events": [{"date": "1969-03-03", "time_utc": "16:00", "label": "Apollo 9 launch", "quote": "Launched: March 3, 1969 @ 16:00 GMT/UTC"}]},189 {"key": "apollo-10-s-ivb", "id": "mission:apollo-10-s-ivb", "command": "-399100", "name": "Apollo 10 S-IVB stage",190 "events": [{"date": "1969-05-18", "time_utc": "16:49", "label": "Apollo 10 launch", "quote": "Launched: May 18, 1969 @ 16:49 GMT/UTC"}]},191 {"key": "apollo-10-lm", "id": "mission:apollo-10-lm-ascent-stage", "command": "-399101", "name": "Apollo 10 lunar module ascent stage (Snoopy)",192 "events": [{"date": "1969-05-18", "time_utc": "16:49", "label": "Apollo 10 launch", "quote": "Launched: May 18, 1969 @ 16:49 GMT/UTC"}]},193 {"key": "apollo-11-s-ivb", "id": "mission:apollo-11-s-ivb", "command": "-399110", "name": "Apollo 11 S-IVB stage",194 "events": [{"date": "1969-07-16", "time_utc": "13:32", "label": "Apollo 11 launch", "quote": "Launched: July 16, 1969 @ 13:32 GMT/UTC"}]},195 {"key": "apollo-12-s-ivb", "id": "mission:apollo-12-s-ivb", "command": "-399120", "name": "Apollo 12 S-IVB stage",196 "events": [{"date": "1969-11-14", "time_utc": "16:22", "label": "Apollo 12 launch", "quote": "Launched: November 14, 1969 @ 16:22 GMT/UTC"}]},197]198199200# ---- time helpers: integer TDB seconds past J2000 <-> proleptic Gregorian calendar ----201202def days_from_civil(y, m, d):203 y -= m <= 2204 era = (y if y >= 0 else y - 399) // 400205 yoe = y - era * 400206 doy = (153 * (m + (-3 if m > 2 else 9)) + 2) // 5 + d - 1207 doe = yoe * 365 + yoe // 4 - yoe // 100 + doy208 return era * 146097 + doe - 719468 # days since 1970-01-01209210211J2000_DAYS = days_from_civil(2000, 1, 1)212213214def et_from_calendar(y, mo, d, h=0, mi=0, s=0):215 return (days_from_civil(y, mo, d) - J2000_DAYS) * 86400 + h * 3600 + mi * 60 + s - 43200216217218def calendar_from_et(et):219 total = et + 43200220 days, rem = divmod(total, 86400)221 z = days + J2000_DAYS + 719468222 era = (z if z >= 0 else z - 146096) // 146097223 doe = z - era * 146097224 yoe = (doe - doe // 1460 + doe // 36524 - doe // 146096) // 365225 y = yoe + era * 400226 doy = doe - (365 * yoe + yoe // 4 - yoe // 100)227 mp = (5 * doy + 2) // 153228 d = doy - (153 * mp + 2) // 5 + 1229 m = mp + (3 if mp < 10 else -9)230 y += m <= 2231 return "%04d-%02d-%02d %02d:%02d:%02d" % (y, m, d, rem // 3600, rem % 3600 // 60, rem % 60)232233234def parse_horizons_date(text):235 """'A.D. 1977-SEP-05 13:59:24.3830' -> float TDB seconds past J2000."""236 m = re.search(r"(\d{4})-([A-Za-z]{3})-(\d{2}) (\d{2}):(\d{2}):(\d{2})(\.\d+)?", text)237 y, mon, d, h, mi, s = int(m.group(1)), MONTHS.index(m.group(2).upper()) + 1, int(m.group(3)), int(m.group(4)), int(m.group(5)), int(m.group(6))238 return et_from_calendar(y, mon, d, h, mi, s) + float(m.group(7) or 0)239240241# ---- Horizons access ----242243def probe(command):244 """Data sheet text and trajectory limits (TDB s past J2000) of a spacecraft."""245 limits, sheet = [], None246 for start, stop, word in (("1900-01-01", "1900-01-02", "prior to"), ("2400-01-01", "2400-01-02", "after")):247 p = hz.vectors_params(command, "500@0", START_TIME=hz.quote(start), STOP_TIME=hz.quote(stop), STEP_SIZE=hz.quote("1d"))248 p["OBJ_DATA"] = hz.quote("YES")249 text = hz.query(p)250 m = re.search(r"No ephemeris for target .* %s (A\.D\. .*) TDB" % word, text)251 if not m:252 raise RuntimeError("cannot read the trajectory limit of %s:\n%s" % (command, text[-600:]))253 limits.append(parse_horizons_date(m.group(1)))254 if sheet is None:255 sheet = text.split("No ephemeris for target")[0]256 sheet = sheet[sheet.index("*****"):].rstrip() + "\n"257 return sheet, limits[0], limits[1]258259260def fetch_rows(command, times=None, start=None, count=None, step_s=None):261 """States (km, km/s) at explicit instants or on a uniform grid; returns [(et, [6 floats])]."""262 if times is not None:263 p = hz.vectors_params(command, "500@0", TLIST=",".join("'%s'" % calendar_from_et(t) for t in times))264 expected = list(times)265 else:266 if step_s % 60:267 raise ValueError("grid steps are whole minutes")268 p = hz.vectors_params(command, "500@0", START_TIME=hz.quote(calendar_from_et(start)),269 STOP_TIME=hz.quote(calendar_from_et(start + count * step_s)), STEP_SIZE=hz.quote("%dm" % (step_s // 60)))270 expected = [start + k * step_s for k in range(count + 1)]271 text = hz.query(p)272 rows = []273 for ln in hz.table_lines(text):274 cells = [c.strip() for c in ln.split(",")]275 rows.append((int(round(parse_horizons_date(cells[1]))), [float(c) for c in cells[2:8]]))276 if [r[0] for r in rows] != expected:277 raise RuntimeError("Horizons returned %d rows, %d expected (or shifted epochs) for %s" % (len(rows), len(expected), command))278 return rows, text279280281def fetch_grid(command, start, count, step_s):282 rows = []283 k = 0284 while k < count:285 n = min(MAX_ROWS, count - k)286 part, _ = fetch_rows(command, start=start + k * step_s, count=n, step_s=step_s)287 rows.extend(part if not rows else part[1:])288 k += n289 return rows290291292# ---- interpolation ----293294def hermite(t, a, b):295 """Cubic Hermite position between samples a=(et, state) and b at time t (km)."""296 h = b[0] - a[0]297 s = (t - a[0]) / h298 h00, h10, h01, h11 = 2 * s**3 - 3 * s**2 + 1, s**3 - 2 * s**2 + s, -2 * s**3 + 3 * s**2, s**3 - s**2299 return [h00 * a[1][i] + h10 * h * a[1][i + 3] + h01 * b[1][i] + h11 * h * b[1][i + 3] for i in range(3)]300301302def dist(p, q):303 return math.sqrt(sum((p[i] - q[i]) ** 2 for i in range(3)))304305306def flag_intervals(run):307 """Estimated error of each interval of a uniform run: the interpolant built on samples i-1 and i+1 is compared308 with sample i; its error is that of a step twice as long, i.e. about 16 times the error of the actual step."""309 n = len(run) - 1310 est = [0.0] * n311 if n < 2:312 return [float("inf")] * n313 for i in range(1, n):314 e = dist(hermite(run[i][0], run[i - 1], run[i + 1]), run[i][1]) / 16.0315 est[i - 1] = max(est[i - 1], e)316 est[i] = max(est[i], e)317 return est318319320def build(mission):321 command = mission["command"]322 sheet, lim0, lim1 = probe(command)323 start = int(math.ceil(lim0 / 60.0)) * 60324 end = int(math.floor(lim1 / 60.0)) * 60325 if "end_cap" in mission:326 y, mo, d = [int(x) for x in mission["end_cap"][:10].split("-")]327 end = min(end, et_from_calendar(y, mo, d))328 samples = {}329 level_counts = []330 final_estimate = 0.0331 # windows to sample at each level: (t0, t1)332 windows = [(start, end)]333 for level, step_min in enumerate(LADDER_MIN):334 step = step_min * 60335 last = level == len(LADDER_MIN) - 1336 next_windows = []337 new = 0338 for (t0, t1) in windows:339 count = (t1 - t0) // step340 tail = t0 + count * step341 if count >= 1:342 run = fetch_grid(command, t0, count, step)343 for et, st in run:344 if et not in samples:345 new += 1346 samples[et] = st347 est = flag_intervals(run)348 if last:349 final_estimate = max([final_estimate] + [e for e in est if e != float("inf")])350 else:351 j = 0352 while j < len(est):353 if est[j] > TOLERANCE_KM:354 k = j355 while k + 1 < len(est) and est[k + 1] > TOLERANCE_KM:356 k += 1357 next_windows.append((run[j][0], run[k + 1][0]))358 j = k + 1359 else:360 j += 1361 if tail < t1 and not last:362 next_windows.append((tail, t1))363 level_counts.append({"step_minutes": step_min, "windows": len(windows), "new_samples": new})364 hz.log(" level", step_min, "min:", len(windows), "windows,", new, "new samples")365 # merge touching / overlapping windows366 next_windows.sort()367 merged = []368 for w in next_windows:369 if merged and w[0] <= merged[-1][1]:370 merged[-1] = (merged[-1][0], max(merged[-1][1], w[1]))371 else:372 merged.append(w)373 windows = merged374 if not windows:375 break376 ordered = sorted(samples.items())377 return sheet, lim0, lim1, ordered, level_counts, final_estimate378379380def split_at_discontinuities(ordered):381 """Splits the samples where the source trajectory is discontinuous.382383 Horizons concatenates trajectory files delivered by the navigation teams; at some junctions (and at the384 joints of patched-conic design trajectories) the position jumps by kilometres to thousands of kilometres.385 Such a jump cannot be resolved by a finer step: at the finest step the interpolation-error estimate stays386 above the tolerance. Those intervals are removed (they become gaps) so that nothing is ever interpolated387 across a jump. The size recorded for a gap is the mismatch between the second sample and the first one388 propagated with the mean velocity (trapezoid rule) over the interval.389 """390 finest = LADDER_MIN[-1] * 60391 breaks = {}392 def mismatch(j):393 a, b = ordered[j], ordered[j + 1]394 h = b[0] - a[0]395 return dist([a[1][k] + 0.5 * h * (a[1][k + 3] + b[1][k + 3]) for k in range(3)], b[1])396 for i in range(1, len(ordered) - 1):397 if ordered[i][0] - ordered[i - 1][0] != finest or ordered[i + 1][0] - ordered[i][0] != finest:398 continue399 est = dist(hermite(ordered[i][0], ordered[i - 1], ordered[i + 1]), ordered[i][1]) / 16.0400 if est > TOLERANCE_KM:401 j = i - 1 if mismatch(i - 1) >= mismatch(i) else i402 breaks[j] = mismatch(j)403 segments, gaps, current = [], [], []404 for j, sample in enumerate(ordered):405 current.append(sample)406 if j in breaks:407 if len(current) >= 2:408 segments.append(current)409 gaps.append({"start_tdb_s": ordered[j][0], "end_tdb_s": ordered[j + 1][0],410 "start": calendar_from_et(ordered[j][0]) + " TDB", "end": calendar_from_et(ordered[j + 1][0]) + " TDB",411 "position_jump_km": breaks[j],412 "reason": "discontinuity of the trajectory served by Horizons (junction of trajectory solutions); not interpolated"})413 current = []414 if len(current) >= 2:415 segments.append(current)416 return segments, gaps417418419def check(mission, segments):420 """Real interpolation error at instants between samples (midpoints of intervals), against Horizons."""421 rng = random.Random(mission["key"])422 ordered = [s for seg in segments for s in seg]423 ends = set()424 k = -1425 for seg in segments:426 k += len(seg)427 ends.add(k) # index of the last sample of each segment: no interval starts there428 gaps = [(ordered[i + 1][0] - ordered[i][0], i) for i in range(len(ordered) - 1) if i not in ends]429 finest = min(g for g, _ in gaps)430 fine = [i for g, i in gaps if g == finest]431 picks = set(rng.sample(fine, min(30, len(fine))))432 every = [i for _, i in gaps]433 picks |= set(rng.sample(every, min(30, len(every))))434 picks = sorted(picks)435 times = [(ordered[i][0] + ordered[i + 1][0]) // 2 for i in picks]436 rows, texts = [], []437 for k in range(0, len(times), 15): # short URLs: 15 instants per request438 part, raw = fetch_rows(mission["command"], times=times[k:k + 15])439 rows.extend(part)440 texts.append(raw)441 text = "\n".join(texts) # several raw answers one after the other, unmodified442 errs = []443 for (i, (et, st)) in zip(picks, rows):444 errs.append((dist(hermite(et, ordered[i], ordered[i + 1]), st), ordered[i + 1][0] - ordered[i][0], et))445 name = "chk_" + mission["key"]446 os.makedirs(FIXTURES, exist_ok=True)447 with open(os.path.join(FIXTURES, name + ".txt"), "w", encoding="utf-8") as f:448 f.write(text)449 worst = max(errs)450 result = {"instants": len(errs), "max_error_m": worst[0] * 1000, "max_error_interval_s": worst[1],451 "max_error_at": calendar_from_et(worst[2]) + " TDB",452 "rms_error_m": 1000 * math.sqrt(sum(e[0] ** 2 for e in errs) / len(errs)),453 "method": "states requested from Horizons at the midpoints of %d distinct intervals (up to 30 of the finest step and up to 30 drawn at random, seeded), compared with the cubic Hermite interpolant of the pack samples" % len(errs)}454 return result, {"name": name, "kind": "trajectory-check", "target": mission["id"], "center": "naif:0",455 "frame": "icrf", "correction": "NONE", "units": "km, km/s; calendar dates are TDB"}456457458def write_trj(path, target, label, segments):459 ordered = [s for seg in segments for s in seg]460 table = 256 + 16 * len(segments)461 def field(s, n):462 b = s.encode("utf-8")463 assert len(b) < n464 return b + b"\0" * (n - len(b))465 with open(path, "wb") as f:466 f.write(b"ORIXTRJ\0")467 f.write(struct.pack("<IIIIQ", 1, table, 1, len(segments), len(ordered)))468 f.write(field(target, 64) + field("naif:0", 64) + field(label, 96))469 first = 0470 for seg in segments:471 f.write(struct.pack("<QQ", first, len(seg)))472 first += len(seg)473 for et, st in ordered:474 f.write(struct.pack("<7d", float(et), *[v * 1000.0 for v in st]))475476477def sha256(path):478 h = hashlib.sha256()479 with open(path, "rb") as f:480 for block in iter(lambda: f.read(1 << 20), b""):481 h.update(block)482 return h.hexdigest()483484485def main():486 manifest_path = os.path.join(PACK, "manifest.json")487 if "--manifest-only" in sys.argv[1:]:488 # Offline: keep the mission records and the retrieval date, re-read sizes and hashes from the disk.489 with open(manifest_path, encoding="utf-8") as f:490 old = json.load(f)491 save(manifest_path, old["missions"], retrieved=old.get("retrieved"))492 return493 wanted = set(sys.argv[1:])494 os.makedirs(os.path.join(PACK, "sources"), exist_ok=True)495 previous = {}496 if os.path.exists(manifest_path):497 with open(manifest_path, encoding="utf-8") as f:498 previous = {m["key"]: m for m in json.load(f)["missions"]}499 entries, fixtures = [], []500 for mission in MISSIONS:501 if wanted and mission["key"] not in wanted:502 if mission["key"] in previous:503 entries.append(previous[mission["key"]])504 continue505 hz.log("mission", mission["key"])506 sheet, lim0, lim1, ordered, levels, final_estimate = build(mission)507 normalised = re.sub(r"\s+", " ", sheet)508 events = []509 for ev in mission["events"]:510 ev = dict(ev)511 if "source" not in ev:512 if re.sub(r"\s+", " ", ev["quote"]) not in normalised:513 sys.exit("event quote not found verbatim in the Horizons sheet of %s: %s" % (mission["key"], ev["quote"]))514 ev["source"] = "JPL Horizons data sheet of object %s (file sources/%s.horizons.txt)" % (mission["command"], mission["key"])515 events.append(ev)516 with open(os.path.join(PACK, "sources", mission["key"] + ".horizons.txt"), "w", encoding="utf-8") as f:517 f.write(sheet)518 path = os.path.join(PACK, mission["key"] + ".trj")519 segments, gaps = split_at_discontinuities(ordered)520 ordered = [s for seg in segments for s in seg]521 write_trj(path, mission["id"], mission["name"] + " (JPL Horizons)", segments)522 result, fixture = check(mission, segments)523 fixtures.append(fixture)524 steps = {}525 for seg in segments:526 for i in range(len(seg) - 1):527 d = (seg[i + 1][0] - seg[i][0]) // 60528 steps[d] = steps.get(d, 0) + 1529 entries.append({530 "key": mission["key"], "id": mission["id"], "name": mission["name"], "horizons_id": mission["command"],531 "file": mission["key"] + ".trj", "bytes": os.path.getsize(path), "sha256": sha256(path),532 "center": "naif:0", "frame": "ICRF", "samples": len(ordered),533 "horizons_trajectory_limits_tdb": [calendar_from_et(int(lim0)) + " TDB", calendar_from_et(int(lim1)) + " TDB"],534 "coverage": [{"start_tdb_s": seg[0][0], "end_tdb_s": seg[-1][0],535 "start": calendar_from_et(seg[0][0]) + " TDB", "end": calendar_from_et(seg[-1][0]) + " TDB"} for seg in segments],536 "gaps": gaps,537 "cadence": {"interval_minutes_histogram": {str(k): v for k, v in sorted(steps.items())}, "levels": levels,538 "tolerance_km": TOLERANCE_KM,539 "largest_estimate_at_finest_step_before_splitting_km": final_estimate},540 "interpolation_check": result,541 "data_sheet": "sources/%s.horizons.txt" % mission["key"],542 "events": events,543 })544 hz.log(" ->", len(ordered), "samples,", len(segments), "segments,", os.path.getsize(path), "bytes, check max %.1f m" % result["max_error_m"])545 save(manifest_path, entries + [previous[m["key"]] for m in MISSIONS[MISSIONS.index(mission) + 1:] if m["key"] in previous])546 save(manifest_path, entries)547 # fixtures index548 path = os.path.join(FIXTURES, "index.json")549 index = {"source": "NASA/JPL Horizons API (https://ssd.jpl.nasa.gov/api/horizons.api)", "note": "Raw answers saved unmodified; test fixtures only.", "fixtures": []}550 if os.path.exists(path):551 with open(path) as f:552 index = json.load(f)553 names = {f["name"] for f in fixtures}554 index["fixtures"] = [f for f in index["fixtures"] if f["name"] not in names] + fixtures555 with open(path, "w") as f:556 json.dump(index, f, indent=1)557 f.write("\n")558559560SOURCE_ID = "jpl-horizons-spacecraft-trajectories"561SOURCE_NAME = "NASA/JPL Horizons API, https://ssd.jpl.nasa.gov/api/horizons.api (state vectors relative to the solar system barycentre, ICRF, TDB)"562NATURE = "Trajectories reconstructed (and, beyond the last tracking data, predicted) by the mission navigation teams as served by JPL Horizons. They are NOT live telemetry. The origin and quality of each trajectory is described in its Horizons data sheet (sources/)."563# Wording of Documentation/modules/CosmosEphemeris.md, section 5.2; no licence text of the source is quoted there.564LICENCE = ("NASA/JPL Horizons output, a work of NASA/JPL (U.S. Government). Credit: NASA/JPL-Caltech Solar System Dynamics. "565 "No explicit licence or redistribution text from the source is recorded (Documentation/modules/CosmosEphemeris.md).")566REDISTRIBUTION_NOTE = ("Derived from JPL Horizons output, for which the module documentation records a U.S. Government work credit but "567 "quotes no redistribution terms: marked localBuildOnly until the owner confirms the terms "568 "(rebuild locally with DataPipeline/ephemeris/fetch_missions.py).")569570571def save(path, entries, retrieved=None):572 """Writes the manifest (schema v1). Sizes and hashes of files[] are read from the disk and must agree with the mission records."""573 retrieved = retrieved or datetime.date.today().isoformat()574 files = []575 for m in entries:576 trj = os.path.join(PACK, m["file"])577 size, digest = os.path.getsize(trj), sha256(trj)578 if (size, digest) != (m["bytes"], m["sha256"]):579 sys.exit("%s does not match its mission record (size or SHA-256); rebuild the mission" % trj)580 files.append({"path": m["file"], "size": size, "sha256": digest, "role": "trajectory", "source": SOURCE_ID,581 "description": "%s: barycentric states, ORIXTRJ version 1" % m["name"], "mission": m["key"]})582 for m in entries:583 sheet = os.path.join(PACK, m["data_sheet"])584 files.append({"path": m["data_sheet"], "size": os.path.getsize(sheet), "sha256": sha256(sheet), "role": "data-sheet",585 "source": SOURCE_ID, "description": "%s: JPL Horizons data sheet of object %s, verbatim" % (m["name"], m["horizons_id"]),586 "mission": m["key"]})587 spans = [span for m in entries for span in m["coverage"]]588 manifest = {589 "schemaVersion": 1, "id": "missions", "version": "1.0.0", "kind": "missions",590 "title": {"en": "Spacecraft trajectories (JPL Horizons)", "fr": "Trajectoires d\u2019engins spatiaux (JPL Horizons)"},591 "description": {592 "en": "Barycentric trajectories of %d spacecraft and rocket stages sampled from JPL Horizons, with the Horizons data "593 "sheet of each object. Reconstructed or predicted by the mission navigation teams; not live telemetry." % len(entries),594 "fr": "Trajectoires barycentriques de %d engins spatiaux et étages de fusée, échantillonnées à partir de JPL Horizons, "595 "avec la fiche Horizons de chaque objet. Reconstituées ou prédites par les équipes de navigation des missions; "596 "il ne s\u2019agit pas de télémétrie en direct." % len(entries),597 },598 "retrieved": retrieved,599 "source": SOURCE_NAME,600 "nature": NATURE,601 "license": LICENCE,602 "redistribution": "localBuildOnly",603 "redistributionNote": REDISTRIBUTION_NOTE,604 "file_format": "ORIXTRJ version 1 (see Documentation/modules/CosmosEphemeris.md): t (TDB s past J2000), position (m), velocity (m/s), little-endian float64; cubic Hermite interpolation between samples",605 "sampling": "adaptive: steps of %s minutes; an interval is re-sampled at the next finer step when its estimated cubic-Hermite interpolation error exceeds %.1f km" % (", ".join(str(s) for s in LADDER_MIN), TOLERANCE_KM),606 "coverage": {"time_scale": "TDB seconds past J2000.0", "missions": len(entries),607 "start_tdb_s": min(s["start_tdb_s"] for s in spans) if spans else None,608 "end_tdb_s": max(s["end_tdb_s"] for s in spans) if spans else None,609 "note": "union bounds only; the spans and gaps of each trajectory are in missions[].coverage and missions[].gaps"},610 "installedSize": sum(f["size"] for f in files),611 "files": files,612 "sources": [{613 "id": SOURCE_ID, "name": SOURCE_NAME, "version": "Horizons, retrieved %s" % retrieved, "retrieved": retrieved,614 "url": "https://ssd.jpl.nasa.gov/api/horizons.api", "license": LICENCE,615 "method": "barycentric state vectors sampled adaptively, cubic Hermite interpolation; " + NATURE,616 }],617 "missions": entries,618 }619 with open(path, "w", encoding="utf-8") as f:620 json.dump(manifest, f, indent=2, sort_keys=True, ensure_ascii=False)621 f.write("\n")622623624if __name__ == "__main__":625 main()626