SPB Git

Repository Public

fetch_validation.py 19.6 KB 378 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/astrodynamics/fetch_validation.py11# Description      : Downloads the reference data the CosmosAstrodynamics tests12#                    are validated against (official SGP4 verification set,13#                    CelesTrak OMM samples, NASA eclipse and transit14#                    catalogues, JPL Horizons tables, Lambert reference cases)15#                    into Packages/CosmosAstrodynamics/Tests/Fixtures, with an16#                    index of URLs, dates and SHA-256. Standard library 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"""Fetches the validation fixtures of CosmosAstrodynamics.9697    python3 DataPipeline/astrodynamics/fetch_validation.py            # everything that is missing98    python3 DataPipeline/astrodynamics/fetch_validation.py --force    # download again99100Only official public archives are contacted (celestrak.org, web.archive.org for the 2012 edition of the CelesTrak101archive, eclipse.gsfc.nasa.gov, ssd.jpl.nasa.gov, ntrs.nasa.gov, datacenter.iers.org, raw.githubusercontent.com). Requests carry a generic102User-Agent and no personal data; they are sequential with a one-second pause. Raw downloads (archives) are kept under103DataPipeline/raw/astrodynamics/ (git-ignored). The fixtures are reference values for tests only, never production data.104"""105import hashlib106import io107import json108import os109import sys110import time111import urllib.parse112import urllib.request113import zipfile114115USER_AGENT = "orix-cosmos-pipeline/1.0"116ROOT = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", ".."))117FIXTURES = os.path.join(ROOT, "Packages", "CosmosAstrodynamics", "Tests", "Fixtures")118RAW = os.path.join(ROOT, "DataPipeline", "raw", "astrodynamics")119HORIZONS = "https://ssd.jpl.nasa.gov/api/horizons.api"120FORCE = "--force" in sys.argv121TODAY = time.strftime("%Y-%m-%d", time.gmtime())122_last = [0.0]123index = []124125126def get(url, timeout=300):127    wait = 1.0 - (time.time() - _last[0])128    if wait > 0:129        time.sleep(wait)130    last_error = None131    for attempt in range(4):132        try:133            req = urllib.request.Request(url, headers={"User-Agent": USER_AGENT})134            with urllib.request.urlopen(req, timeout=timeout) as resp:135                data = resp.read()136            _last[0] = time.time()137            return data138        except Exception as exc:  # retry on network errors139            last_error = exc140            time.sleep(5 * (attempt + 1))141    raise RuntimeError("download failed: %s (%s)" % (last_error, url))142143144def record(relative, url, note, data=None):145    path = os.path.join(FIXTURES, relative)146    if data is not None:147        os.makedirs(os.path.dirname(path), exist_ok=True)148        with open(path, "wb") as f:149            f.write(data)150    with open(path, "rb") as f:151        digest = hashlib.sha256(f.read()).hexdigest()152    index.append({"file": relative, "url": url, "note": note, "sha256": digest,153                  "bytes": os.path.getsize(path), "retrieved": TODAY})154    print("  %-52s %8d bytes" % (relative, os.path.getsize(path)))155156157def previous_entry(relative):158    path = os.path.join(FIXTURES, "index.json")159    if not os.path.exists(path):160        return None161    with open(path, encoding="utf-8") as f:162        for e in json.load(f)["fixtures"]:163            if e["file"] == relative:164                return e165    return None166167168def fetch_file(relative, url, note):169    path = os.path.join(FIXTURES, relative)170    if os.path.exists(path) and not FORCE:171        old = previous_entry(relative)172        if old:173            index.append(old)174            return175    record(relative, url, note, get(url))176177178def fetch_zip_member(relative, url, member, note, raw_name):179    path = os.path.join(FIXTURES, relative)180    if os.path.exists(path) and not FORCE:181        old = previous_entry(relative)182        if old:183            index.append(old)184            return185    os.makedirs(RAW, exist_ok=True)186    raw_path = os.path.join(RAW, raw_name)187    if not os.path.exists(raw_path) or FORCE:188        with open(raw_path, "wb") as f:189            f.write(get(url))190    with open(raw_path, "rb") as f:191        archive = f.read()192    with zipfile.ZipFile(io.BytesIO(archive)) as z:193        data = z.read(member)194    record(relative, url, note + " (member %s of the archive, archive SHA-256 %s)" %195           (member, hashlib.sha256(archive).hexdigest()), data)196197198def q(value):199    return "'" + str(value) + "'"200201202def horizons(relative, note, **params):203    path = os.path.join(FIXTURES, relative)204    base = {"format": "text", "OBJ_DATA": q("NO"), "MAKE_EPHEM": q("YES"), "CSV_FORMAT": q("YES")}205    for k, v in params.items():206        base[k] = v if str(v).startswith("'") else q(v)207    url = HORIZONS + "?" + urllib.parse.urlencode(base, quote_via=urllib.parse.quote)208    if os.path.exists(path) and not FORCE:209        old = previous_entry(relative)210        if old and old["url"] == url:211            index.append(old)212            return213    text = get(url).decode("utf-8", "replace")214    if "$$SOE" not in text:215        raise RuntimeError("Horizons returned no table for %s:\n%s" % (relative, text[-1500:]))216    record(relative, url, note, text.encode("utf-8"))217218219def observer(relative, note, command, start, stop, step, quantities="31"):220    """Geocentric apparent observer table, TT time tags printed as Julian dates, degrees, extra precision."""221    horizons(relative, note, COMMAND=command, EPHEM_TYPE="OBSERVER", CENTER="500@399", START_TIME=start,222             STOP_TIME=stop, STEP_SIZE=step, QUANTITIES=quantities, TIME_TYPE="TT", CAL_FORMAT="JD",223             ANG_FORMAT="DEG", EXTRA_PREC="YES")224225226def vectors(relative, note, command, center, start, stop, step, **extra):227    horizons(relative, note, COMMAND=command, EPHEM_TYPE="VECTORS", CENTER=center, START_TIME=start,228             STOP_TIME=stop, STEP_SIZE=step, REF_SYSTEM="ICRF", REF_PLANE="FRAME", VEC_TABLE="3",229             VEC_CORR="NONE", OUT_UNITS="KM-S", VEC_LABELS="NO", TIME_TYPE="TDB", **extra)230231232def main():233    os.makedirs(FIXTURES, exist_ok=True)234235    print("SGP4 verification set (Vallado, Crawford, Hujsak & Kelso 2006, AIAA 2006-6753)")236    # The archive currently on celestrak.org no longer carries the C++ expected output `tcppver.out` (it ships237    # per-satellite STK files and the Fortran/MATLAB outputs instead). The edition of 2012-07-16 that does contain238    # it is taken from the Internet Archive copy of the same CelesTrak URL.239    old = "https://web.archive.org/web/20131022161541id_/http://www.celestrak.com/publications/AIAA/2006-6753/AIAA-2006-6753.zip"240    fetch_zip_member("sgp4/tcppver.out", old, "SGP4/cpp/tcppver.out",241                     "expected output of the reference C++ implementation, verification run, WGS-72, opsmode 'a'",242                     "AIAA-2006-6753-20120716.zip")243    fetch_zip_member("sgp4/SGP4-VER.TLE", old, "SGP4/mat/SGP4-VER.TLE",244                     "verification element sets with start/stop/step in minutes appended to line 2",245                     "AIAA-2006-6753-20120716.zip")246    new = "https://celestrak.org/publications/AIAA/2006-6753/AIAA-2006-6753.zip"247    fetch_zip_member("sgp4/SGP4-VER.current.TLE", new, "sgp4/cpp/testsgp4/SGP4-VER.TLE",248                     "same file in the archive distributed today (must be byte-identical to SGP4-VER.TLE)",249                     "AIAA-2006-6753-current.zip")250    fetch_zip_member("sgp4/tforverf.out", new, "sgp4/for/tforverf.out",251                     "expected output of the Fortran reference in the archive distributed today (2015 run)",252                     "AIAA-2006-6753-current.zip")253254    print("CelesTrak GP data, one element set in four formats")255    for ext in ("tle", "json", "kvn", "xml"):256        fetch_file("omm/iss.%s" % ext, "https://celestrak.org/NORAD/elements/gp.php?CATNR=25544&FORMAT=%s" % ext,257                   "ISS (25544) general perturbations element set, format %s" % ext.upper())258259    print("NASA GSFC eclipse and transit catalogues (F. Espenak)")260    for c in ("1801-1900", "1901-2000", "2001-2100", "2101-2200"):261        fetch_file("nasa/SE%s.html" % c, "https://eclipse.gsfc.nasa.gov/SEcat5/SE%s.html" % c,262                   "Five Millennium Catalog of Solar Eclipses, %s" % c)263        fetch_file("nasa/LE%s.html" % c, "https://eclipse.gsfc.nasa.gov/LEcat5/LE%s.html" % c,264                   "Five Millennium Catalog of Lunar Eclipses, %s" % c)265    fetch_file("nasa/transit12.html", "https://eclipse.gsfc.nasa.gov/OH/transit12.html",266               "The 2012 Transit of Venus: geocentric contact times (Table 1)")267    fetch_file("nasa/MercuryCatalog.html", "https://eclipse.gsfc.nasa.gov/transit/catalog/MercuryCatalog.html",268               "Seven Century Catalog of Mercury Transits (contact times to the minute)")269    fetch_file("nasa/VenusCatalog.html", "https://eclipse.gsfc.nasa.gov/transit/catalog/VenusCatalog.html",270               "Six Millennium Catalog of Venus Transits (contact times to the minute)")271    fetch_file("nasa/SE2024Apr08Tpath.html", "https://eclipse.gsfc.nasa.gov/SEpath/SEpath2001/SE2024Apr08Tpath.html",272               "Path of the total solar eclipse of 2024 Apr 08 (central line, duration)")273274    print("Lambert reference cases")275    fetch_file("lambert/poliastro_test_iod.py.txt",276               "https://raw.githubusercontent.com/poliastro/poliastro/main/tests/test_iod.py",277               "poliastro test suite (MIT licence): Vallado example 7-5, Curtis examples 5.2 and 5.3, multi-revolution "278               "cases; stored with a .txt suffix so that it is never executed")279280    print("JPL Horizons (DE441): geocentric apparent ecliptic longitudes/latitudes of date, TT")281    observer("horizons/moon_eclon_2025.txt", "Moon, hourly, 2025-01-01..2025-04-01", "301",282             "2025-01-01 00:00", "2025-04-01 00:00", "1 h")283    observer("horizons/sun_eclon_2025.txt", "Sun, 6-hourly, 2025", "10", "2025-01-01 00:00", "2026-01-01 00:00", "6 h")284    observer("horizons/moon_eclon_1900.txt", "Moon, hourly, 1900-03", "301", "1900-03-01 00:00", "1900-04-01 00:00", "1 h")285    observer("horizons/sun_eclon_1900.txt", "Sun, 6-hourly, 1900-03", "10", "1900-03-01 00:00", "1900-04-01 00:00", "6 h")286    observer("horizons/moon_eclon_2100.txt", "Moon, hourly, 2100-03", "301", "2100-03-01 00:00", "2100-04-01 00:00", "1 h")287    observer("horizons/sun_eclon_2100.txt", "Sun, 6-hourly, 2100-03", "10", "2100-03-01 00:00", "2100-04-01 00:00", "6 h")288    observer("horizons/mars_eclon_2025.txt", "Mars, 6-hourly, around the opposition of January 2025", "499",289             "2025-01-01 00:00", "2025-02-01 00:00", "6 h")290    observer("horizons/venus_eclon_2025.txt", "Venus, 6-hourly, greatest elongation and inferior conjunction 2025", "299",291             "2025-01-01 00:00", "2025-04-01 00:00", "6 h")292    observer("horizons/jupiter_eclon_2026.txt", "Jupiter, 6-hourly, around the opposition of January 2026", "599",293             "2026-01-01 00:00", "2026-01-20 00:00", "6 h")294    observer("horizons/sun_eclon_2026.txt", "Sun, 6-hourly, January 2026", "10",295             "2026-01-01 00:00", "2026-01-20 00:00", "6 h")296297    print("JPL Horizons: transits (apparent RA/Dec and angular diameters, one-minute steps, TT)")298    for name, body, start, stop in (("mercury_2019", "199", "2019-11-11 12:00", "2019-11-11 19:00"),299                                    ("venus_2012", "299", "2012-06-05 21:30", "2012-06-06 05:30")):300        observer("horizons/transit_%s_planet.txt" % name, "planet during the transit", body, start, stop, "1 m", "2,13")301        observer("horizons/transit_%s_sun.txt" % name, "Sun during the transit", "10", start, stop, "1 m", "2,13")302303    print("JPL Horizons: geometric vectors (range rate for apsides)")304    vectors("horizons/earth_sun_2025.txt", "Earth relative to the Sun, hourly, around perihelion and aphelion 2025",305            "399", "500@10", "2025-01-01 00:00", "2025-01-08 00:00", "1 h")306    vectors("horizons/earth_sun_2025_aphelion.txt", "Earth relative to the Sun, hourly, around aphelion 2025",307            "399", "500@10", "2025-07-01 00:00", "2025-07-07 00:00", "1 h")308    vectors("horizons/moon_earth_2025.txt", "Moon relative to the Earth, 10-minute steps, January 2025 (perigee, apogee)",309            "301", "500@399", "2025-01-05 00:00", "2025-01-24 00:00", "10 m")310311    print("JPL Horizons: osculating elements (ICRF equator), for the element-extraction tests")312    for name, body, center in (("mars_sun", "4", "500@10"), ("moon_earth", "301", "500@399"), ("jupiter_sun", "5", "500@10")):313        horizons("horizons/elements_%s.txt" % name, "osculating elements, ICRF frame plane, TDB",314                 COMMAND=body, EPHEM_TYPE="ELEMENTS", CENTER=center, START_TIME="2025-01-01 00:00",315                 STOP_TIME="2025-01-03 00:00", STEP_SIZE="1 d", REF_SYSTEM="ICRF", REF_PLANE="FRAME",316                 OUT_UNITS="KM-S", TP_TYPE="ABSOLUTE", ELEM_LABELS="NO", TIME_TYPE="TDB")317318    print("NASA/TM-2010-216764 (Burke, Falck & McGuire): Earth-to-Mars energy minima 2026-2045")319    handbook = "porkchop/NASA-TM-2010-216764_tables_excerpt.txt"320    if os.path.exists(os.path.join(FIXTURES, handbook)) and previous_entry(handbook) and not FORCE:321        index.append(previous_entry(handbook))322    else:323        # The report is a 6.6 MB PDF; its text is extracted with pdftotext (poppler) when available.324        import shutil325        import subprocess326        url = "https://ntrs.nasa.gov/api/citations/20100037210/downloads/20100037210.pdf"327        os.makedirs(RAW, exist_ok=True)328        pdf = os.path.join(RAW, "NASA-TM-2010-216764.pdf")329        if not os.path.exists(pdf) or FORCE:330            with open(pdf, "wb") as f:331                f.write(get(url, timeout=900))332        if shutil.which("pdftotext") is None:333            raise RuntimeError("pdftotext (poppler) is needed to extract the tables of " + pdf)334        text = subprocess.run(["pdftotext", "-layout", pdf, "-"], check=True, capture_output=True).stdout.decode("utf-8", "replace")335        lines = text.splitlines()336        first = next(i for i, ln in enumerate(lines) if "TABLE 1." in ln) - 5337        last = next(i for i, ln in enumerate(lines) if "TABLE 13." in ln) + 12338        with open(pdf, "rb") as f:339            digest = hashlib.sha256(f.read()).hexdigest()340        record(handbook, url, "text of tables 1-13 (pdftotext -layout, lines %d-%d) of the report; PDF SHA-256 %s" % (first + 1, last, digest),341               ("\n".join(lines[first:last]) + "\n").encode("utf-8"))342343    print("IERS finals2000A excerpt (UT1-UTC for 2024), same file as the CosmosCoordinates fixture")344    excerpt = "iers/finals2000A_2024_excerpt.txt"345    if os.path.exists(os.path.join(FIXTURES, excerpt)) and previous_entry(excerpt) and not FORCE:346        index.append(previous_entry(excerpt))347    else:348        rows = [ln for ln in get("https://datacenter.iers.org/data/9/finals2000A.all").decode("ascii", "replace").splitlines()349                if ln[7:15].strip() and 60300 <= float(ln[7:15]) <= 60680]350        record(excerpt, "https://datacenter.iers.org/data/9/finals2000A.all",351               "rows MJD 60300..60680 of finals2000A.all (IERS Rapid Service/Prediction Center), unmodified",352               ("\n".join(rows) + "\n").encode("ascii"))353354    print("JPL Horizons: user-supplied TLE propagated by Horizons (SGP4), geocentric ICRF")355    with open(os.path.join(FIXTURES, "omm", "iss.tle"), encoding="utf-8") as f:356        tle = [ln.rstrip("\r\n") for ln in f if ln.strip()]357    line1 = [ln for ln in tle if ln.startswith("1 ")][0]358    year = 2000 + int(line1[18:20])359    doy = float(line1[20:32])360    jd0 = 367 * year - (7 * (year + 9 // 12)) // 4 + 275 * 1 // 9 + 1721013.5 + int(doy)361    start_jd = jd0 + 1.0            # 00:00 UTC on the day after the element-set epoch day362    horizons("horizons/iss_tle_icrf.txt",363             "ISS element set of omm/iss.tle propagated by Horizons, geocentric ICRF vectors, UTC time tags",364             COMMAND="TLE", TLE="'" + "\n".join(tle) + "'", EPHEM_TYPE="VECTORS", CENTER="500@399",365             START_TIME="JD%.1f" % start_jd, STOP_TIME="JD%.1f" % (start_jd + 2.0), STEP_SIZE="30 m",366             REF_SYSTEM="ICRF", REF_PLANE="FRAME", VEC_TABLE="2", VEC_CORR="NONE", OUT_UNITS="KM-S",367             VEC_LABELS="NO", TIME_TYPE="UT")368369    index.sort(key=lambda e: e["file"])370    with open(os.path.join(FIXTURES, "index.json"), "w", encoding="utf-8") as f:371        json.dump({"generated_by": "DataPipeline/astrodynamics/fetch_validation.py", "fixtures": index}, f, indent=1)372        f.write("\n")373    print("wrote index.json with %d entries" % len(index))374375376if __name__ == "__main__":377    main()378
Files main
Menu

Theme