SPB Git

Repository Public

store.py 12.7 KB 269 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/catalogs/store.py11# Description      : Writer of the SQLite store of a catalogue pack (schema12#                    version 1: meta, provenance, objects, designations, FTS513#                    trigram name index, blobs, star_text), JSON encoding of14#                    Measured values as Swift's Codable expects them, and15#                    manifest generation with SHA-256.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# =============================================================================9394import json95import math96import os97import sqlite39899from common import sha256_file, write_json100from designations import normalize101102SCHEMA_VERSION = 1103PC = 149597870700.0 * 648000.0 / math.pi  # parsec in metres (IAU 2015 B2)104105SCHEMA = """106CREATE TABLE meta(key TEXT PRIMARY KEY, value TEXT NOT NULL) WITHOUT ROWID;107CREATE TABLE provenance(id TEXT PRIMARY KEY, source TEXT NOT NULL, version TEXT NOT NULL, retrieved TEXT,108  license TEXT NOT NULL, url TEXT, method TEXT, citation TEXT) WITHOUT ROWID;109CREATE TABLE objects(oid INTEGER PRIMARY KEY, id TEXT NOT NULL UNIQUE, kind TEXT NOT NULL, name TEXT NOT NULL,110  status TEXT NOT NULL, provenance TEXT REFERENCES provenance(id), ra REAL, dec REAL, zone INTEGER, mag REAL,111  parent TEXT, record_type TEXT, record TEXT);112CREATE TABLE designations(oid INTEGER NOT NULL REFERENCES objects(oid), role INTEGER NOT NULL, catalog TEXT,113  display TEXT NOT NULL, norm TEXT NOT NULL, PRIMARY KEY(norm, oid)) WITHOUT ROWID;114CREATE VIRTUAL TABLE names_fts USING fts5(norm, display UNINDEXED, oid UNINDEXED, tokenize='trigram');115CREATE TABLE blobs(name TEXT PRIMARY KEY, content BLOB NOT NULL) WITHOUT ROWID;116CREATE TABLE star_text(id TEXT PRIMARY KEY, spectral_type TEXT) WITHOUT ROWID;117"""118INDEXES = """119CREATE INDEX objects_zone ON objects(zone, ra) WHERE zone IS NOT NULL;120CREATE INDEX objects_kind ON objects(kind, mag);121CREATE INDEX objects_parent ON objects(parent) WHERE parent IS NOT NULL;122CREATE INDEX designations_oid ON designations(oid);123"""124125126def measured(value, sym=None, plus=None, minus=None, limit=None, status="observed", prov=None, epoch=None):127    """JSON form of Swift `Measured<Double>` (synthesised Codable). None stays None: unknown is never 0.128    `limit`: 1 = upper limit, -1 = lower limit (NASA Exoplanet Archive convention)."""129    if value is None:130        return None131    out = {"value": value, "status": status}132    if limit == 1:133        out["uncertainty"] = {"upperLimit": {}}134    elif limit == -1:135        out["uncertainty"] = {"lowerLimit": {}}136    elif plus is not None and minus is not None:137        p, m = abs(plus), abs(minus)138        out["uncertainty"] = {"symmetric": {"_0": p}} if p == m else {"asymmetric": {"plus": p, "minus": m}}139    elif sym is not None:140        out["uncertainty"] = {"symmetric": {"_0": abs(sym)}}141    if prov:142        out["provenance"] = prov143    if epoch is not None:144        out["epoch"] = epoch145    return out146147148def compact(record):149    """Drops None values (Swift optionals are omitted, not null) recursively in dicts."""150    return {k: (compact(v) if isinstance(v, dict) and "value" not in v else v) for k, v in record.items() if v is not None}151152153class Store:154    def __init__(self, path, pack_id, pack_version, built):155        if os.path.exists(path):156            os.remove(path)157        self.path = path158        self.db = sqlite3.connect(path)159        self.db.executescript("PRAGMA journal_mode=OFF; PRAGMA synchronous=OFF; PRAGMA page_size=4096;" + SCHEMA)160        for k, v in (("schema_version", str(SCHEMA_VERSION)), ("pack_id", pack_id), ("pack_version", pack_version),161                     ("built", built)):162            self.db.execute("INSERT INTO meta VALUES(?,?)", (k, v))163        self.ids = {}164        self.counts = {}165        self.provenances = []166167    def provenance(self, pid, source, version, retrieved, license, url=None, method=None, citation=None):168        self.db.execute("INSERT OR REPLACE INTO provenance VALUES(?,?,?,?,?,?,?,?)",169                        (pid, source, version, retrieved, license, url, method, citation))170        entry = {"id": pid, "source": source, "version": version, "retrieved": retrieved, "license": license,171                 "url": url, "method": method, "citation": citation}172        self.provenances = [p for p in self.provenances if p["id"] != pid] + [{k: v for k, v in entry.items() if v is not None}]173174    def has(self, oid):175        return oid in self.ids176177    def add(self, oid, kind, name, status, prov, ra=None, dec=None, mag=None, parent=None, record_type=None,178            record=None, designations=(), count=True):179        """Adds an object. `designations`: iterable of (role, catalog, display[, fts]) with role 0 primary180        designation, 1 proper name, 2 alias; names (role 1) are indexed for substring/fuzzy search unless fts181        is given explicitly. ra/dec in radians (ICRS)."""182        if oid in self.ids:183            raise ValueError("duplicate object id " + oid)184        zone = None185        if ra is not None and dec is not None:186            zone = max(0, min(179, int(math.floor(math.degrees(dec) + 90))))187        text = json.dumps(compact(record), ensure_ascii=False, separators=(",", ":"), sort_keys=True) if record is not None else None188        cur = self.db.execute("INSERT INTO objects(id, kind, name, status, provenance, ra, dec, zone, mag, parent, record_type, record)"189                              " VALUES(?,?,?,?,?,?,?,?,?,?,?,?)",190                              (oid, kind, name, status, prov, ra, dec, zone, mag, parent, record_type, text))191        rowid = cur.lastrowid192        self.ids[oid] = rowid193        if count:194            self.counts[kind] = self.counts.get(kind, 0) + 1195        self.designate(oid, designations)196        return rowid197198    def designate(self, oid, designations):199        rowid = self.ids[oid]200        for d in designations:201            role, catalog, display = d[0], d[1], d[2]202            if not display or not display.strip():203                continue204            display = " ".join(display.split())205            norm = normalize(display)206            if not norm:207                continue208            cur = self.db.execute("INSERT OR IGNORE INTO designations VALUES(?,?,?,?,?)", (rowid, role, catalog, display, norm))209            fts = d[3] if len(d) > 3 else role == 1210            if fts and cur.rowcount:211                self.db.execute("INSERT INTO names_fts(norm, display, oid) VALUES(?,?,?)", (norm, display, rowid))212213    def blob(self, name, content):214        self.db.execute("INSERT OR REPLACE INTO blobs VALUES(?,?)", (name, content))215216    def star_text(self, oid, spectral_type):217        if spectral_type:218            self.db.execute("INSERT OR REPLACE INTO star_text VALUES(?,?)", (oid, spectral_type))219220    def close(self):221        self.db.executescript(INDEXES)222        self.db.execute("INSERT INTO names_fts(names_fts) VALUES('optimize')")223        self.db.commit()224        self.db.execute("ANALYZE")225        self.db.commit()226        self.db.execute("VACUUM")227        self.db.commit()228        check = self.db.execute("PRAGMA integrity_check").fetchone()[0]229        self.db.close()230        if check != "ok":231            raise RuntimeError("integrity check failed for %s: %s" % (self.path, check))232233234def write_manifest(pack_dir, pack_id, title, version, retrieved, licence, acknowledgement, redistribution, files,235                   sources, counts, coverage, star_flag=None, title_fr=None, description=None):236    """Writes manifest.json to pack-manifest schema v1 (DataPipeline/packs/schema/pack-manifest.v1.schema.json).237    `files`: list of (name, role, description). `redistribution`: (class, statement) with class in238    yes | non-commercial | unverified | no. The schema knows two values: `redistributable` (classes yes and239    non-commercial; the condition is spelled out in the extension key `redistributionTerms`) and `localBuildOnly`240    (classes unverified and no). Extension keys: redistributionTerms, acknowledgement, retrieved, counts, starFlag."""241    primary = sources[0]["id"] if sources else None242    entries = []243    for name, role, text in files:244        p = os.path.join(pack_dir, name)245        entry = {"path": name, "size": os.path.getsize(p), "sha256": sha256_file(p), "role": role, "description": text}246        if primary:247            entry["source"] = primary248        entries.append(entry)249    cls, statement = redistribution250    srcs = []251    for src in sources:252        e = {"id": src["id"], "name": src.get("name") or src["source"], "version": src["version"], "license": src["license"]}253        for k in ("url", "retrieved", "citation", "method"):254            if src.get(k):255                e[k] = src[k]256        srcs.append(e)257    manifest = {"schemaVersion": 1, "id": pack_id, "version": version, "kind": "satellites" if pack_id == "satellites" else "catalogue",258                "title": {"en": title, "fr": title_fr or title},259                "description": description or {"en": title},260                "installedSize": sum(e["size"] for e in entries), "files": entries, "sources": srcs, "license": licence,261                "coverage": coverage,262                "redistribution": "redistributable" if cls in ("yes", "non-commercial") else "localBuildOnly",263                "redistributionTerms": {"class": cls, "statement": statement},264                "acknowledgement": acknowledgement, "retrieved": retrieved, "counts": counts}265    if star_flag is not None:266        manifest["starFlag"] = star_flag267    write_json(os.path.join(pack_dir, "manifest.json"), manifest)268    return manifest269
Files main
Menu

Theme