SPB Git

Repository Public

fetch_elements.py 14.3 KB 281 lines python

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_elements.py11# Description      : Queries JPL Horizons for osculating orbital elements at12#                    one epoch (natural satellites, dwarf planets, asteroids,13#                    comets absent from DE440s), writes kepler_elements.json14#                    into the core pack, and saves comparison vectors at epoch15#                    ± 1/10/100/1000 days as test fixtures. Standard library16#                    only.17# Module           : DataPipeline18# Repository       : https://git.spboucher.ai/orix-cosmos19# Project Website  : https://www.orixlab.dev20# Created          : 2026-11-2421# Last Modified    : 2026-11-2422#23# =============================================================================24# AUTHOR & PROFESSIONAL AFFILIATION25# =============================================================================26#27# Author           : Simon-Pierre Boucher28# Position         : Professor of Finance29# Institution      : Université du Québec en Outaouais (UQO)30# Department       : Département des sciences administratives31# Organization     : SP Boucher32#33# Website          : https://spboucher.ai34# Git              : https://git.spboucher.ai35#36# =============================================================================37# OFFICIAL CONTACT DIRECTORY38# =============================================================================39#40# General          : info@spboucher.ai41# Professional     : contact@spboucher.ai42# Direct           : simon@spboucher.ai43# Research         : research@spboucher.ai44# Development      : dev@spboucher.ai45# Support          : support@spboucher.ai46# Security/Admin   : admin@spboucher.ai47# Notifications    : notifications@spboucher.ai48#49# Preferred Contact: support@spboucher.ai50#51# =============================================================================52# COPYRIGHT & INTELLECTUAL PROPERTY53# =============================================================================54#55# Copyright (c) 202656# Simon-Pierre Boucher57#58# All rights reserved where applicable.59#60# This file is governed by the applicable project license,61# copyright notices, institutional agreements and relevant law.62#63# Unless expressly authorized by the applicable license or64# rights holder, copying, redistribution, sublicensing,65# publication and commercial exploitation are not permitted.66#67# Existing third-party rights and notices remain unaffected.68#69# =============================================================================70# CONFIDENTIALITY & SECURITY71# =============================================================================72#73# Classification   : Public74# Distribution     : Public repository; use is governed by the project license75# Security Contact : admin@spboucher.ai76#77# Access to this source does not independently grant permission78# to redistribute or disclose confidential materials.79#80# Do not embed credentials, private keys, access tokens,81# certificates or confidential personal information.82#83# =============================================================================84# LICENSE & MAINTENANCE85# =============================================================================86#87# License          : None specified (no license file in this repository)88# Maintainer       : Simon-Pierre Boucher89# Technical Contact: dev@spboucher.ai90#91# =============================================================================92# END OF SP BOUCHER SOURCE HEADER93# =============================================================================9495"""Usage: fetch_elements.py9697The elements feed the Keplerian (two-body) provider: an explicit approximation whose error grows away from the98epoch (measured by the test suite against the fixtures written here; see Documentation/modules/CosmosEphemeris.md).99Elements are referred to ICRF axes (Horizons REF_PLANE=FRAME): inclination to the ICRF equator, node from the100ICRF x axis. Satellites are referred to the centre of their planet, heliocentric bodies to the centre of the Sun.101"""102import datetime103import json104import math105import os106import re107import subprocess108import sys109import time110import urllib.parse111import urllib.request112113sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))114import horizons as hz  # noqa: E402115116PACK = os.path.join(hz.ROOT, "Resources", "Packs", "core-ephemeris")117FIXTURES = os.path.join(hz.ROOT, "Packages", "CosmosEphemeris", "Tests", "Fixtures", "horizons")118EPOCH_JD = 2461406.5            # 2027-Jan-01 00:00 TDB119VALID_JD = (2396752.5, 2506352.5)   # DE440s span: the chain to the barycentre needs the planets120OFFSETS_D = [-1000, -100, -10, -1, 0, 1, 10, 100, 1000]121DEG = math.pi / 180.0122123SATELLITES = [  # (NAIF id, name, planet)124    (401, "Phobos", 499), (402, "Deimos", 499),125    (501, "Io", 599), (502, "Europa", 599), (503, "Ganymede", 599), (504, "Callisto", 599),126    (601, "Mimas", 699), (602, "Enceladus", 699), (603, "Tethys", 699), (604, "Dione", 699), (605, "Rhea", 699),127    (606, "Titan", 699), (607, "Hyperion", 699), (608, "Iapetus", 699),128    (701, "Ariel", 799), (702, "Umbriel", 799), (703, "Titania", 799), (704, "Oberon", 799), (705, "Miranda", 799),129    (801, "Triton", 899), (802, "Nereid", 899),130    (901, "Charon", 999),131]132# Numbered small bodies: NAIF id = 20000000 + number (NAIF extended scheme, the one Horizons reports).133ASTEROIDS = [  # (number, name, kind)134    (1, "Ceres", "dwarfPlanet"), (2, "Pallas", "asteroid"), (4, "Vesta", "asteroid"), (10, "Hygiea", "asteroid"),135    (433, "Eros", "asteroid"), (99942, "Apophis", "asteroid"), (101955, "Bennu", "asteroid"),136    (136199, "Eris", "dwarfPlanet"), (136108, "Haumea", "dwarfPlanet"), (136472, "Makemake", "dwarfPlanet"),137    (225088, "Gonggong", "dwarfPlanet"), (50000, "Quaoar", "dwarfPlanet"), (90377, "Sedna", "dwarfPlanet"),138    (90482, "Orcus", "dwarfPlanet"),139]140COMETS = [("1P", "1P/Halley"), ("2P", "2P/Encke"), ("67P", "67P/Churyumov-Gerasimenko"), ("C/1995 O1", "C/1995 O1 (Hale-Bopp)")]141SYSTEMS = [(499, 4), (599, 5), (699, 6), (799, 7), (899, 8), (999, 9)]142# Bodies whose two-body error is measured against Horizons (fixtures).143CHECKS = [("501", "500@599", "naif:501", "naif:599"), ("502", "500@599", "naif:502", "naif:599"),144          ("606", "500@699", "naif:606", "naif:699"), ("401", "500@499", "naif:401", "naif:499"),145          ("801", "500@899", "naif:801", "naif:899"), ("901", "500@999", "naif:901", "naif:999"),146          ("1;", "500@10", "naif:20000001", "naif:10"), ("DES=1P; CAP;", "500@10", None, "naif:10"),147          ("599", "500@5", "naif:599", "naif:5"), ("699", "500@6", "naif:699", "naif:6"), ("999", "500@9", "naif:999", "naif:9")]148149150def lookup_comet(pdes):151    url = "https://ssd.jpl.nasa.gov/api/horizons_lookup.api?" + urllib.parse.urlencode({"sstr": pdes})152    time.sleep(hz.DELAY_S)153    req = urllib.request.Request(url, headers={"User-Agent": hz.USER_AGENT})154    with urllib.request.urlopen(req, timeout=60) as resp:155        data = json.load(resp)156    for r in data.get("result", []):157        if r.get("pdes") == pdes and "comet" in r.get("type", ""):158            return int(r["spkid"])159    raise RuntimeError("no Horizons SPK id for comet " + pdes)160161162def elements(command, center):163    params = {164        "COMMAND": hz.quote(command), "OBJ_DATA": hz.quote("NO"), "MAKE_EPHEM": hz.quote("YES"),165        "EPHEM_TYPE": hz.quote("ELEMENTS"), "CENTER": hz.quote(center), "REF_PLANE": hz.quote("FRAME"),166        "REF_SYSTEM": hz.quote("ICRF"), "TLIST": "'%.1f'" % EPOCH_JD, "TLIST_TYPE": hz.quote("JD"),167        "OUT_UNITS": hz.quote("KM-S"), "CSV_FORMAT": hz.quote("YES"), "TIME_TYPE": hz.quote("TDB"),168    }169    text = hz.query(params)170    lines = hz.table_lines(text)171    if len(lines) != 1:172        raise RuntimeError("expected one row of elements for " + command)173    cells = [c.strip() for c in lines[0].split(",")]174    if abs(float(cells[0]) - EPOCH_JD) > 1e-9:175        raise RuntimeError("unexpected epoch for " + command)176    names = ["EC", "QR", "IN", "OM", "W", "Tp", "N", "MA", "TA", "A", "AD", "PR"]177    raw = dict(zip(names, cells[2:14]))          # strings exactly as printed by Horizons178    gm = re.search(r"Keplerian GM\s*:\s*([0-9.Ee+-]+)\s*km\^3/s\^2", text)179    if not gm:180        raise RuntimeError("no Keplerian GM in the Horizons header for " + command)181    target = re.search(r"Target body name:\s*(.*?)\s*\{source:\s*(.*?)\}", text)182    return raw, gm.group(1), (target.group(1).strip(), target.group(2).strip()), hz.build_url(dict(params, format="text"))183184185def body_entry(obj_id, name, kind, center_id, command, center):186    raw, gm, (horizons_name, source), url = elements(command, center)187    return {188        "id": obj_id, "name": name, "kind": kind, "center": center_id,189        "horizons_command": command, "horizons_center": center, "horizons_target": horizons_name,190        "horizons_solution": source, "query_url": url,191        "epoch_jd_tdb": EPOCH_JD,192        "eccentricity": float(raw["EC"]),193        "periapsis_distance_m": float(raw["QR"]) * 1000.0,194        "inclination_rad": float(raw["IN"]) * DEG,195        "ascending_node_rad": float(raw["OM"]) * DEG,196        "arg_periapsis_rad": float(raw["W"]) * DEG,197        "periapsis_time_jd_tdb": float(raw["Tp"]),198        "gm_m3_s2": float(gm) * 1e9,199        "horizons_raw": dict(raw, GM_km3_s2=gm, units="km, km/s, degrees, Julian day (Tp), deg/s (N), s (PR)"),200    }201202203def main():204    bodies = []205    for code, name, planet in SATELLITES:206        bodies.append(body_entry("naif:%d" % code, name, "moon", "naif:%d" % planet, str(code), "500@%d" % planet))207        hz.log("ok", name)208    for number, name, kind in ASTEROIDS:209        bodies.append(body_entry("naif:%d" % (20000000 + number), name, kind, "naif:10", "%d;" % number, "500@10"))210        bodies[-1]["mpc_number"] = number211        hz.log("ok", name)212    halley_id = None213    for pdes, name in COMETS:214        spkid = lookup_comet(pdes)215        # CAP: the apparition solution closest to (not after) the present date, as Horizons recommends for periodic comets.216        command = "DES=%s; CAP;" % pdes if pdes.endswith("P") else "DES=%s;" % pdes217        bodies.append(body_entry("naif:%d" % spkid, name, "comet", "naif:10", command, "500@10"))218        if pdes == "1P":219            halley_id = "naif:%d" % spkid220        hz.log("ok", name, spkid)221222    systems = [{"planet": "naif:%d" % p, "barycenter": "naif:%d" % b,223                "satellites": [e["id"] for e in bodies if e["center"] == "naif:%d" % p and e["id"] != "naif:802"]}224               for p, b in SYSTEMS]225    doc = {226        "format": 1,227        "title": "Osculating orbital elements for the Keplerian (two-body) provider",228        "warning": "APPROXIMATION. Each body follows the unperturbed conic that osculates its JPL orbit at the epoch. Perturbations (planetary oblateness, mutual and solar perturbations, non-gravitational forces of comets) are ignored; the position error grows with the time elapsed from the epoch. Measured errors: Documentation/modules/CosmosEphemeris.md.",229        "epoch_jd_tdb": EPOCH_JD,230        "epoch": "2027-01-01 00:00:00 TDB",231        "frame": "ICRF (inclination to the ICRF equator, node from the ICRF x axis)",232        "valid_from_jd_tdb": VALID_JD[0], "valid_to_jd_tdb": VALID_JD[1],233        "validity_note": "Interval over which the provider answers (the DE440s span, needed to chain to the barycentre). It is not an accuracy claim.",234        "provenance": {235            "id": "jpl-horizons-osculating-elements", "source": "NASA/JPL Horizons, osculating elements (EPHEM_TYPE=ELEMENTS)",236            "version": "Horizons solutions named per body in horizons_solution", "retrieved": datetime.date.today().isoformat(),237            "license": "NASA/JPL Horizons output (U.S. Government work). Credit: NASA/JPL-Caltech Solar System Dynamics.",238            "url": "https://ssd.jpl.nasa.gov/api/horizons.api",239            "method": "elements copied from Horizons (km → m, degrees → radians); GM is the 'Keplerian GM' Horizons used to derive them",240        },241        "systems": systems,242        "systems_note": "Planet centre relative to the system barycentre is estimated as −Σ (GM_i/GM_system)·r_i over the listed satellites (GM from gm_de440.tpc); satellites without a GM there are ignored.",243        "bodies": bodies,244    }245    with open(os.path.join(PACK, "kepler_elements.json"), "w") as f:246        json.dump(doc, f, indent=1)247        f.write("\n")248    hz.log("wrote", len(bodies), "bodies")249250    # Comparison vectors (ICRF, km, km/s) at epoch + offsets.251    os.makedirs(FIXTURES, exist_ok=True)252    fixtures = []253    for command, center, target_id, center_id in CHECKS:254        if target_id is None:255            target_id = halley_id256        name = "kep_%s_from_%s" % (target_id.split(":")[1], center_id.split(":")[1])257        params = hz.vectors_params(command, center, TLIST=",".join("'%.1f'" % (EPOCH_JD + d) for d in OFFSETS_D), TLIST_TYPE="JD")258        text = hz.query(params)259        if len(hz.parse_vectors(text)) != len(OFFSETS_D):260            sys.exit("unexpected row count for " + name)261        with open(os.path.join(FIXTURES, name + ".txt"), "w", encoding="utf-8") as f:262            f.write(text)263        fixtures.append({"name": name, "kind": "kepler-check", "target": target_id, "center": center_id, "frame": "icrf",264                         "correction": "NONE", "units": "km, km/s, s; times are TDB Julian dates", "params": params,265                         "url": hz.build_url(dict(params, format="text"))})266        hz.log("ok", name)267    path = os.path.join(FIXTURES, "index.json")268    index = {"source": "NASA/JPL Horizons API (https://ssd.jpl.nasa.gov/api/horizons.api)", "note": "Raw answers saved unmodified; test fixtures only.", "fixtures": []}269    if os.path.exists(path):270        with open(path) as f:271            index = json.load(f)272    index["fixtures"] = [f for f in index["fixtures"] if f["kind"] != "kepler-check"] + fixtures273    with open(path, "w") as f:274        json.dump(index, f, indent=1)275        f.write("\n")276    subprocess.check_call([sys.executable, "-I", os.path.join(os.path.dirname(os.path.abspath(__file__)), "build_core_manifest.py"), hz.ROOT])277278279if __name__ == "__main__":280    main()281
Files main
Menu

Theme