SPB Git

Repository Public

horizons.py 8.1 KB 215 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/horizons.py11# Description      : Minimal, polite client of the JPL Horizons API (sequential12#                    requests, delay, on-disk cache of raw responses) and13#                    parsers for its CSV vector / element / observer tables.14#                    Standard library only.15# Module           : DataPipeline16# Repository       : https://git.spboucher.ai/orix-cosmos17# Project Website  : https://www.orixlab.dev18# Created          : 2026-11-2419# Last Modified    : 2026-11-2420#21# =============================================================================22# AUTHOR & PROFESSIONAL AFFILIATION23# =============================================================================24#25# Author           : Simon-Pierre Boucher26# Position         : Professor of Finance27# Institution      : Université du Québec en Outaouais (UQO)28# Department       : Département des sciences administratives29# Organization     : SP Boucher30#31# Website          : https://spboucher.ai32# Git              : https://git.spboucher.ai33#34# =============================================================================35# OFFICIAL CONTACT DIRECTORY36# =============================================================================37#38# General          : info@spboucher.ai39# Professional     : contact@spboucher.ai40# Direct           : simon@spboucher.ai41# Research         : research@spboucher.ai42# Development      : dev@spboucher.ai43# Support          : support@spboucher.ai44# Security/Admin   : admin@spboucher.ai45# Notifications    : notifications@spboucher.ai46#47# Preferred Contact: support@spboucher.ai48#49# =============================================================================50# COPYRIGHT & INTELLECTUAL PROPERTY51# =============================================================================52#53# Copyright (c) 202654# Simon-Pierre Boucher55#56# All rights reserved where applicable.57#58# This file is governed by the applicable project license,59# copyright notices, institutional agreements and relevant law.60#61# Unless expressly authorized by the applicable license or62# rights holder, copying, redistribution, sublicensing,63# publication and commercial exploitation are not permitted.64#65# Existing third-party rights and notices remain unaffected.66#67# =============================================================================68# CONFIDENTIALITY & SECURITY69# =============================================================================70#71# Classification   : Public72# Distribution     : Public repository; use is governed by the project license73# Security Contact : admin@spboucher.ai74#75# Access to this source does not independently grant permission76# to redistribute or disclose confidential materials.77#78# Do not embed credentials, private keys, access tokens,79# certificates or confidential personal information.80#81# =============================================================================82# LICENSE & MAINTENANCE83# =============================================================================84#85# License          : None specified (no license file in this repository)86# Maintainer       : Simon-Pierre Boucher87# Technical Contact: dev@spboucher.ai88#89# =============================================================================90# END OF SP BOUCHER SOURCE HEADER91# =============================================================================9293"""Shared helpers of the ephemeris pipeline.9495Only https://ssd.jpl.nasa.gov/api/horizons.api is contacted. Requests carry a generic User-Agent and no personal96data. Every raw response is cached under DataPipeline/raw/ephemeris/horizons-cache/ (git-ignored) keyed by the97SHA-256 of the query, so re-running a script does not hit the service again.98"""99import hashlib100import json101import os102import sys103import time104import urllib.parse105import urllib.request106107API = "https://ssd.jpl.nasa.gov/api/horizons.api"108USER_AGENT = "orix-cosmos-pipeline/1.0"109DELAY_S = 1.0110ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))111CACHE = os.path.join(ROOT, "DataPipeline", "raw", "ephemeris", "horizons-cache")112_last_request = [0.0]113114115def quote(value):116    """Horizons wants string values wrapped in single quotes."""117    return "'" + str(value) + "'"118119120def build_url(params):121    return API + "?" + urllib.parse.urlencode(params, quote_via=urllib.parse.quote)122123124def query(params, use_cache=True):125    """Returns the raw text of a Horizons answer for `params` (dict of API parameters, already quoted)."""126    params = dict(params)127    params.setdefault("format", "text")128    url = build_url(params)129    key = hashlib.sha256(url.encode()).hexdigest()130    path = os.path.join(CACHE, key + ".txt")131    if use_cache and os.path.exists(path):132        with open(path, encoding="utf-8") as f:133            return f.read()134    wait = DELAY_S - (time.time() - _last_request[0])135    if wait > 0:136        time.sleep(wait)137    last_error = None138    for attempt in range(4):139        try:140            req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})141            with urllib.request.urlopen(req, timeout=180) as resp:142                text = resp.read().decode("utf-8", "replace")143            _last_request[0] = time.time()144            break145        except Exception as exc:  # network errors and HTTP 5xx: back off and retry146            last_error = exc147            time.sleep(5 * (attempt + 1))148    else:149        raise RuntimeError("Horizons request failed: %s (%s)" % (last_error, url))150    os.makedirs(CACHE, exist_ok=True)151    with open(path, "w", encoding="utf-8") as f:152        f.write(text)153    return text154155156def table_lines(text):157    """Lines between $$SOE and $$EOE; raises with the service's message when there is no table."""158    if "$$SOE" not in text or "$$EOE" not in text:159        tail = "\n".join(text.strip().splitlines()[-12:])160        raise ValueError("Horizons returned no ephemeris table:\n" + tail)161    body = text.split("$$SOE", 1)[1].split("$$EOE", 1)[0]162    return [ln for ln in body.splitlines() if ln.strip()]163164165def parse_vectors(text):166    """CSV vector table (VEC_TABLE=2 or 3) -> list of (jd_tdb, [x, y, z, vx, vy, vz], extra floats)."""167    rows = []168    for ln in table_lines(text):169        cells = [c.strip() for c in ln.split(",")]170        jd = float(cells[0])171        vals = [float(c) for c in cells[2:] if c != ""]172        rows.append((jd, vals[:6], vals[6:]))173    return rows174175176def vectors_params(command, center, **over):177    p = {178        "COMMAND": quote(command), "OBJ_DATA": quote("NO"), "MAKE_EPHEM": quote("YES"),179        "EPHEM_TYPE": quote("VECTORS"), "CENTER": quote(center), "REF_PLANE": quote("FRAME"),180        "REF_SYSTEM": quote("ICRF"), "VEC_TABLE": quote("3"), "VEC_CORR": quote("NONE"),181        "OUT_UNITS": quote("KM-S"), "CSV_FORMAT": quote("YES"), "VEC_LABELS": quote("NO"),182        "TIME_TYPE": quote("TDB"),183    }184    for k, v in over.items():185        p[k] = v if v.startswith("'") else quote(v)186    return p187188189def jd_to_et(jd):190    """TDB Julian date -> TDB seconds past J2000 (the Instant of the Swift code)."""191    return (jd - 2451545.0) * 86400.0192193194def calendar(jd):195    """Proleptic Gregorian calendar date YYYY-MM-DD HH:MM of a Julian date (for request START/STOP strings)."""196    z = int(jd + 0.5)197    f = jd + 0.5 - z198    a = z + 32044199    b = (4 * a + 3) // 146097200    c = a - 146097 * b // 4201    d = (4 * c + 3) // 1461202    e = c - 1461 * d // 4203    m = (5 * e + 2) // 153204    day = e - (153 * m + 2) // 5 + 1205    month = m + 3 - 12 * (m // 10)206    year = 100 * b + d - 4800 + m // 10207    minutes = int(round(f * 1440))208    if minutes == 1440:209        return calendar(jd + 0.5 / 1440)210    return "%04d-%02d-%02d %02d:%02d" % (year, month, day, minutes // 60, minutes % 60)211212213def log(*args):214    print(*args, file=sys.stderr, flush=True)215
Files main
Menu

Theme