SPB Git

Repository Public

spk_subset.py 8.6 KB 194 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/spk_subset.py11# Description      : Extracts a short time window of chosen bodies from a12#                    remote NAIF SPK kernel using HTTP range requests (no full13#                    download) and writes a small, valid DAF/SPK file; used to14#                    build real type 2/3 test fixtures from15#                    multi-hundred-megabyte satellite kernels. 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: spk_subset.py URL OUT.bsp START_ET END_ET BODY [BODY ...]9697Only Chebyshev segments (SPK types 2 and 3) are handled. The output keeps the original records byte-for-byte98in value (re-encoded little-endian) and rewrites the segment directory for the reduced record count.99100NAIF rule on modified kernels: the result is a *modified* kernel, so it carries a different file name and an101internal file name stating who produced it; it is a test fixture, not a redistribution of the NAIF product.102"""103import struct104import sys105import time106import urllib.request107108UA = "orix-cosmos-pipeline/1.0"109110111def fetch(url, first, last):112    req = urllib.request.Request(url, headers={"User-Agent": UA, "Range": "bytes=%d-%d" % (first, last)})113    time.sleep(0.5)114    with urllib.request.urlopen(req, timeout=120) as resp:115        data = resp.read()116    if len(data) != last - first + 1:117        raise RuntimeError("range request returned %d bytes, %d expected" % (len(data), last - first + 1))118    return data119120121def main():122    url, out, t0, t1 = sys.argv[1], sys.argv[2], float(sys.argv[3]), float(sys.argv[4])123    bodies = [int(b) for b in sys.argv[5:]]124    rec = fetch(url, 0, 1023)125    if not rec[:8].startswith(b"DAF/SPK"):126        sys.exit("not an SPK")127    e = "<" if rec[88:96] == b"LTL-IEEE" else ">"128    nd, ni = struct.unpack(e + "ii", rec[8:16])129    fward = struct.unpack(e + "i", rec[76:80])[0]130    if (nd, ni) != (2, 6):131        sys.exit("unexpected ND/NI")132    found = []133    n = fward134    while n > 0:135        block = fetch(url, (n - 1) * 1024, n * 1024 + 1023)      # summary record + name record136        nxt, _prev, nsum = struct.unpack(e + "ddd", block[:24])137        for i in range(int(nsum)):138            o = 24 + i * 40139            s0, s1 = struct.unpack(e + "dd", block[o:o + 16])140            tgt, ctr, frame, typ, begin, end = struct.unpack(e + "6i", block[o + 16:o + 40])141            name = block[1024 + i * 40:1024 + (i + 1) * 40].decode("ascii", "replace").strip()142            if tgt in bodies and s0 <= t0 and s1 >= t1:143                found.append((tgt, ctr, frame, typ, begin, end, name))144        n = int(nxt)145    segments = []146    for body in bodies:147        match = [f for f in found if f[0] == body]148        if not match:149            sys.exit("no segment covers the window for body %d" % body)150        tgt, ctr, frame, typ, begin, end, name = match[-1]     # last one has priority, as in SPICE151        if typ not in (2, 3):152            sys.exit("body %d is stored as SPK type %d (only 2 and 3 are handled)" % (body, typ))153        init, intlen, rsize, count = struct.unpack(e + "4d", fetch(url, (end - 4) * 8, end * 8 - 1))154        rsize, count = int(rsize), int(count)155        i0 = max(0, int((t0 - init) // intlen))156        i1 = min(count - 1, int((t1 - init) // intlen))157        first_word = begin + i0 * rsize158        words = (i1 - i0 + 1) * rsize159        raw = fetch(url, (first_word - 1) * 8, (first_word - 1 + words) * 8 - 1)160        values = list(struct.unpack(e + "%dd" % words, raw))161        new_init = init + i0 * intlen162        values += [new_init, intlen, float(rsize), float(i1 - i0 + 1)]163        segments.append({"target": tgt, "center": ctr, "frame": frame, "type": typ, "name": name,164                         "start": new_init, "end": new_init + intlen * (i1 - i0 + 1), "words": values})165        print("body %d: type %d, centre %d, frame %d, %d records of %d words, interval %.0f s, \"%s\"" %166              (tgt, typ, ctr, frame, i1 - i0 + 1, rsize, intlen, name), file=sys.stderr)167168    # Write a little-endian DAF/SPK: file record, one summary record, one name record, data.169    address = 3 * 128 + 1170    summaries, names, payload = b"", b"", b""171    for s in segments:172        summaries += struct.pack("<dd6i", s["start"], s["end"], s["target"], s["center"], s["frame"], s["type"],173                                 address, address + len(s["words"]) - 1)174        names += s["name"].encode("ascii")[:40].ljust(40)175        payload += struct.pack("<%dd" % len(s["words"]), *s["words"])176        address += len(s["words"])177    source = url.rsplit("/", 1)[-1]178    ifname = ("ORIX COSMOS TEST SUBSET OF %s" % source).encode("ascii")[:60].ljust(60)179    ftp = b"FTPSTR:\r:\n:\r\n:\r\x00:\x81:\x10\xce:ENDFTP"180    file_record = b"DAF/SPK " + struct.pack("<ii", 2, 6) + ifname + struct.pack("<iii", 2, 2, address) + b"LTL-IEEE"181    file_record += b"\0" * 603 + ftp182    file_record = file_record.ljust(1024, b"\0")183    summary_record = (struct.pack("<ddd", 0.0, 0.0, float(len(segments))) + summaries).ljust(1024, b"\0")184    name_record = names.ljust(1024, b" ")185    data = file_record + summary_record + name_record + payload186    data += b"\0" * (-len(data) % 1024)187    with open(out, "wb") as f:188        f.write(data)189    print("wrote %s (%d bytes)" % (out, len(data)), file=sys.stderr)190191192if __name__ == "__main__":193    main()194
Files main
Menu

Theme