SPB Git

Repository Public

build_core_manifest.py 14.2 KB 287 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/build_core_manifest.py11# Description      : Writes Resources/Packs/core-ephemeris/manifest.json in12#                    pack manifest schema v1 (files with sizes and SHA-256,13#                    sources[] with URL, licence, citation and retrieval date,14#                    redistribution, coverage read from the SPK itself).15#                    Standard library only, no network.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: build_core_manifest.py <repository root>9596Re-run after any file of the pack changes (fetch_kernels.sh and fetch_elements.py call it)."""97import hashlib98import json99import os100import struct101import sys102103NAIF = "https://naif.jpl.nasa.gov/pub/naif/generic_kernels"104LICENCE_NAIF = ("NASA/JPL NAIF generic kernel. NAIF rules (https://naif.jpl.nasa.gov/naif/rules.html): "105                "\"SPICE kernels placed on the NAIF server may be downloaded and used by anyone\"; "106                "\"Redistribution of SPICE kernels distributed by NAIF is permitted as long as they have not been modified.\" "107                "Distributed here unmodified. Acknowledgement of NAIF/SPICE is encouraged.")108# Used only when kepler_elements.json carries no provenance record of its own (fetch_elements.py writes one).109LICENCE_HORIZONS = ("NASA/JPL Horizons output (U.S. Government work). Credit: NASA/JPL-Caltech Solar System Dynamics.")110NO_TERMS_HORIZONS = " No explicit licence or redistribution text from the source is recorded (Documentation/modules/CosmosEphemeris.md)."111METHOD_UNMODIFIED = "downloaded from the NAIF server and distributed byte-for-byte unmodified (DataPipeline/ephemeris/fetch_kernels.sh)"112# Pack file -> manifest entry (schema v1 keys: role, source, url, description) and the source record it declares.113FILES = {114    "de440s.bsp": {115        "url": NAIF + "/spk/planets/de440s.bsp", "role": "spk", "source": "jpl-de440s",116        "description": "JPL planetary and lunar ephemeris DE440, short version (1849-2150), SPK type 2"},117    "naif0012.tls": {118        "url": NAIF + "/lsk/naif0012.tls", "role": "lsk", "source": "naif-lsk-naif0012",119        "description": "NAIF leap seconds kernel (last leap second 2017-01-01)"},120    "pck00011.tpc": {121        "url": NAIF + "/pck/pck00011.tpc", "role": "pck", "source": "naif-pck00011",122        "description": "NAIF planetary constants kernel: radii and IAU 2015 orientation models"},123    "gm_de440.tpc": {124        "url": NAIF + "/pck/gm_de440.tpc", "role": "gm", "source": "naif-gm-de440",125        "description": "GM (mass parameter) values consistent with DE440"},126    "kepler_elements.json": {127        "url": "https://ssd.jpl.nasa.gov/api/horizons.api", "role": "kepler-elements", "source": "jpl-horizons-osculating-elements",128        "description": "Osculating orbital elements at one epoch for natural satellites, dwarf planets, asteroids and comets absent from DE440s (approximation; error grows away from the epoch)"},129}130SOURCES = {131    "jpl-de440s": {132        "name": "NASA/JPL planetary and lunar ephemeris DE440 (short SPK de440s.bsp)", "version": "DE440",133        "url": NAIF + "/spk/planets/de440s.bsp", "license": LICENCE_NAIF, "method": METHOD_UNMODIFIED,134        "citation": "Park, R. S., Folkner, W. M., Williams, J. G., Boggs, D. H. (2021). The JPL Planetary and Lunar Ephemerides DE440 and DE441. The Astronomical Journal 161, 105."},135    "naif-lsk-naif0012": {136        "name": "NASA/JPL NAIF leap seconds kernel naif0012.tls", "version": "naif0012.tls",137        "url": NAIF + "/lsk/naif0012.tls", "license": LICENCE_NAIF, "method": METHOD_UNMODIFIED},138    "naif-pck00011": {139        "name": "NASA/JPL NAIF planetary constants kernel pck00011.tpc (IAU WGCCRE 2015)", "version": "pck00011.tpc",140        "url": NAIF + "/pck/pck00011.tpc", "license": LICENCE_NAIF, "method": METHOD_UNMODIFIED,141        "citation": "Archinal, B. A. et al. (2018). Report of the IAU Working Group on Cartographic Coordinates and Rotational Elements: 2015. Celestial Mechanics and Dynamical Astronomy 130, 22."},142    "naif-gm-de440": {143        "name": "NASA/JPL NAIF mass parameters gm_de440.tpc (DE440)", "version": "gm_de440.tpc",144        "url": NAIF + "/pck/gm_de440.tpc", "license": LICENCE_NAIF, "method": METHOD_UNMODIFIED},145}146TITLE = {147    "en": "Core ephemeris (JPL DE440s, NAIF LSK/PCK/GM, osculating elements)",148    "fr": "Éphémérides de base (JPL DE440s, noyaux NAIF LSK/PCK/GM, éléments osculateurs)",149}150DESCRIPTION = {151    "en": "Positions of the Sun, the planets and the Moon from the JPL DE440s ephemeris (1849-2150), the NAIF leap-second, "152          "planetary-constant and mass-parameter kernels, and osculating orbital elements from JPL Horizons for natural "153          "satellites, dwarf planets, asteroids and comets (two-body approximation).",154    "fr": "Positions du Soleil, des planètes et de la Lune tirées des éphémérides JPL DE440s (1849-2150), noyaux NAIF des "155          "secondes intercalaires, des constantes planétaires et des paramètres de masse, et éléments orbitaux osculateurs "156          "de JPL Horizons pour les satellites naturels, les planètes naines, les astéroïdes et les comètes "157          "(approximation à deux corps).",158}159# Conservative: the pack is redistributable only if every file is covered by quoted terms that permit it.160REDISTRIBUTION_NOTE_KERNELS_ONLY = (161    "The NAIF kernels are shipped unmodified under the NAIF rules quoted in license, which permit redistribution.")162REDISTRIBUTION_NOTE_ELEMENTS = (163    "The four NAIF kernels are shipped unmodified under the NAIF rules quoted in license, which permit redistribution. "164    "kepler_elements.json is derived from JPL Horizons output, for which the module documentation records a U.S. Government "165    "work credit but quotes no redistribution terms: the pack is marked localBuildOnly until the owner confirms the terms "166    "of that file (rebuild locally with DataPipeline/ephemeris/fetch_kernels.sh and fetch_elements.py).")167168169def elements_source(path, retrieved):170    """Source record of kepler_elements.json, copied from the provenance block written by fetch_elements.py."""171    prov = {}172    try:173        with open(path, encoding="utf-8") as f:174            prov = json.load(f).get("provenance") or {}175    except (OSError, ValueError):176        pass177    out = {178        "name": prov.get("source") or "NASA/JPL Horizons, osculating elements (EPHEM_TYPE=ELEMENTS)",179        "version": prov.get("version") or "",180        "url": prov.get("url") or "https://ssd.jpl.nasa.gov/api/horizons.api",181        "retrieved": prov.get("retrieved") or retrieved,182        "license": (prov.get("license") or LICENCE_HORIZONS) + NO_TERMS_HORIZONS,183    }184    if prov.get("method"):185        out["method"] = prov["method"]186    return out187188189def sha256(path):190    h = hashlib.sha256()191    with open(path, "rb") as f:192        for block in iter(lambda: f.read(1 << 20), b""):193            h.update(block)194    return h.hexdigest()195196197def spk_coverage(path):198    """Reads the DAF summaries and returns (per-body coverage, segment types). Independent of the Swift reader."""199    with open(path, "rb") as f:200        rec = f.read(1024)201        fmt = rec[88:96].decode("ascii", "replace")202        e = "<" if fmt.startswith("LTL") else ">"203        nd, ni = struct.unpack(e + "ii", rec[8:16])204        fward = struct.unpack(e + "i", rec[76:80])[0]205        size = nd + (ni + 1) // 2206        bodies, types = {}, set()207        n = fward208        while n > 0:209            f.seek((n - 1) * 1024)210            rec = f.read(1024)211            nxt, _prev, nsum = struct.unpack(e + "ddd", rec[:24])212            for i in range(int(nsum)):213                o = 24 + i * size * 8214                t0, t1 = struct.unpack(e + "dd", rec[o:o + 16])215                tgt, ctr, _frame, typ, _b, _e = struct.unpack(e + "6i", rec[o + 16:o + 40])216                types.add(typ)217                cur = bodies.setdefault(str(tgt), {"center": ctr, "start_tdb_s": t0, "end_tdb_s": t1})218                cur["start_tdb_s"] = min(cur["start_tdb_s"], t0)219                cur["end_tdb_s"] = max(cur["end_tdb_s"], t1)220            n = int(nxt)221    return bodies, sorted(types)222223224def main():225    root = sys.argv[1]226    pack = os.path.join(root, "Resources", "Packs", "core-ephemeris")227    raw = os.path.join(root, "DataPipeline", "raw", "ephemeris")228    retrieved = None229    if os.path.exists(os.path.join(raw, "RETRIEVED")):230        retrieved = open(os.path.join(raw, "RETRIEVED")).read().strip()231    files, sources = [], []232    for name, meta in FILES.items():233        path = os.path.join(pack, name)234        if not os.path.exists(path):235            if name == "kepler_elements.json":236                continue  # produced later by fetch_elements.py237            sys.exit("missing pack file: " + path)238        entry = {"path": name, "size": os.path.getsize(path), "sha256": sha256(path)}239        entry.update(meta)240        files.append(entry)241        if meta["source"] in SOURCES:242            source = dict(SOURCES[meta["source"]])243            if retrieved:244                source["retrieved"] = retrieved245        else:246            source = elements_source(path, retrieved)247        source = {k: v for k, v in source.items() if v is not None}248        source["id"] = meta["source"]249        sources.append(source)250    has_elements = any(f["path"] == "kepler_elements.json" for f in files)251    bodies, types = spk_coverage(os.path.join(pack, "de440s.bsp"))252    start = max(b["start_tdb_s"] for b in bodies.values())253    end = min(b["end_tdb_s"] for b in bodies.values())254    manifest = {255        "schemaVersion": 1,256        "id": "core-ephemeris",257        "version": "1.0.0",258        "kind": "ephemeris",259        "title": TITLE,260        "description": DESCRIPTION,261        "retrieved": retrieved,262        "license": LICENCE_NAIF + (" kepler_elements.json: " + next(s["license"] for s in sources if s["id"] == "jpl-horizons-osculating-elements") if has_elements else ""),263        "redistribution": "localBuildOnly" if has_elements else "redistributable",264        "redistributionNote": REDISTRIBUTION_NOTE_ELEMENTS if has_elements else REDISTRIBUTION_NOTE_KERNELS_ONLY,265        "acknowledgement": "Ephemeris and constants: NASA/JPL-Caltech, Navigation and Ancillary Information Facility (NAIF) and Solar System Dynamics group.",266        "coverage": {267            "time_scale": "TDB seconds past J2000.0",268            "common_start_tdb_s": start, "common_end_tdb_s": end,269            "common_start_jd_tdb": 2451545.0 + start / 86400.0, "common_end_jd_tdb": 2451545.0 + end / 86400.0,270            "spk_segment_types": types,271            "bodies": bodies,272        },273        "installedSize": sum(f["size"] for f in files),274        "files": files,275        "sources": sources,276    }277    if manifest["retrieved"] is None:278        del manifest["retrieved"]279    with open(os.path.join(pack, "manifest.json"), "w", encoding="utf-8") as f:280        json.dump(manifest, f, indent=2, sort_keys=True, ensure_ascii=False)281        f.write("\n")282    print("manifest", os.path.join(pack, "manifest.json"), "-", len(files), "files")283284285if __name__ == "__main__":286    main()287
Files main
Menu

Theme