SPB Git

Repository Public

build_objects.py 51.3 KB 833 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/build_objects.py11# Description      : Builds the non-stellar catalogue packs from the cached raw12#                    files (exoplanets, exoplanet-candidates, deep-sky,13#                    galaxies, galaxies-2mrs, satellites, minor-bodies) and the14#                    database of the starter pack (named and bright stars,15#                    constellations, Messier and bright NGC objects). Missing16#                    values stay absent; published uncertainties and limit17#                    flags are kept. Deterministic.18# Module           : DataPipeline19# Repository       : https://git.spboucher.ai/orix-cosmos20# Project Website  : https://www.orixlab.dev21# Created          : 2026-11-2422# Last Modified    : 2026-11-2423#24# =============================================================================25# AUTHOR & PROFESSIONAL AFFILIATION26# =============================================================================27#28# Author           : Simon-Pierre Boucher29# Position         : Professor of Finance30# Institution      : Université du Québec en Outaouais (UQO)31# Department       : Département des sciences administratives32# Organization     : SP Boucher33#34# Website          : https://spboucher.ai35# Git              : https://git.spboucher.ai36#37# =============================================================================38# OFFICIAL CONTACT DIRECTORY39# =============================================================================40#41# General          : info@spboucher.ai42# Professional     : contact@spboucher.ai43# Direct           : simon@spboucher.ai44# Research         : research@spboucher.ai45# Development      : dev@spboucher.ai46# Support          : support@spboucher.ai47# Security/Admin   : admin@spboucher.ai48# Notifications    : notifications@spboucher.ai49#50# Preferred Contact: support@spboucher.ai51#52# =============================================================================53# COPYRIGHT & INTELLECTUAL PROPERTY54# =============================================================================55#56# Copyright (c) 202657# Simon-Pierre Boucher58#59# All rights reserved where applicable.60#61# This file is governed by the applicable project license,62# copyright notices, institutional agreements and relevant law.63#64# Unless expressly authorized by the applicable license or65# rights holder, copying, redistribution, sublicensing,66# publication and commercial exploitation are not permitted.67#68# Existing third-party rights and notices remain unaffected.69#70# =============================================================================71# CONFIDENTIALITY & SECURITY72# =============================================================================73#74# Classification   : Public75# Distribution     : Public repository; use is governed by the project license76# Security Contact : admin@spboucher.ai77#78# Access to this source does not independently grant permission79# to redistribute or disclose confidential materials.80#81# Do not embed credentials, private keys, access tokens,82# certificates or confidential personal information.83#84# =============================================================================85# LICENSE & MAINTENANCE86# =============================================================================87#88# License          : None specified (no license file in this repository)89# Maintainer       : Simon-Pierre Boucher90# Technical Contact: dev@spboucher.ai91#92# =============================================================================93# END OF SP BOUCHER SOURCE HEADER94# =============================================================================9596"""Usage: build_objects.py [--out DIR] [pack ...]     (default: all packs; run build_stars.py first for `starter`)"""97import glob98import gzip99import html100import json101import math102import os103import re104import struct105import sys106import tarfile107108import sources109import starfile as sf110from common import PACKS, RAW, SchemaError, fnum, inum, log, read_csv, write_json111from designations import CONSTELLATIONS, CON_CASE112from fetch_sources import CELESTRAK_GROUPS, NEA_MEASURED, OPENNGC_TAG, STELLARIUM_TAG, TOI_COLUMNS, nea_columns113from store import PC, Store, measured114115RAD = math.pi / 180.0116VERSION = "1.0.0"117C_KM_S = 299792.458118UNVERIFIED = "unverified"119120121def open_store(out_dir, pack_id, prov_ids):122    pack_dir = os.path.join(out_dir, pack_id)123    os.makedirs(pack_dir, exist_ok=True)124    table = dict(sources.all_sources(), **sources.object_sources())125    built = max(table[p]["retrieved"] for p in prov_ids)126    store = Store(os.path.join(pack_dir, "catalog.sqlite"), pack_id, VERSION, built)127    for pid in prov_ids:128        store.provenance(pid, **table[pid])129    return store, pack_dir, built130131132def close_store(store, pack_dir, pack_id, title, built, licence, ack, redistribution, coverage, extra=None):133    store.close()134    draft = {"id": pack_id, "title": title, "version": VERSION, "retrieved": built, "licence": licence,135             "acknowledgement": ack, "redistribution": redistribution, "sources": store.provenances,136             "counts": dict(sorted(store.counts.items())), "coverage": coverage}137    draft.update(extra or {})138    write_json(os.path.join(pack_dir, "pack.json"), draft)139    log("pack %s: %s" % (pack_id, draft["counts"]))140141142def sexagesimal(text, hours):143    """'00:42:44.35' or '7 12 35.0' -> radians. Sign handled for '-00:..'."""144    parts = re.split(r"[:\s]+", text.strip())145    sign = -1.0 if parts[0].startswith("-") else 1.0146    v = sum(abs(float(p)) / 60 ** k for k, p in enumerate(parts))147    return sign * v * (15 if hours else 1) * RAD148149150def strip_tags(text):151    return " ".join(html.unescape(re.sub(r"<[^>]+>", " ", text or "")).split()) or None152153154# ---------------------------------------------------------------- exoplanets155156NEA_FIELDS = {  # archive column -> (record property, status)157    "pl_orbper": ("orbitalPeriodDays", "observed"), "pl_orbsmax": ("semiMajorAxisAU", "observed"),158    "pl_orbeccen": ("eccentricity", "observed"), "pl_orbincl": ("inclinationDeg", "observed"),159    "pl_orblper": ("argumentOfPeriastronDeg", "observed"), "pl_orbtper": ("timeOfPeriastronBJD", "observed"),160    "pl_tranmid": ("transitMidpointBJD", "observed"), "pl_rade": ("radiusEarth", "observed"),161    "pl_radj": ("radiusJupiter", "observed"), "pl_bmasse": ("massEarth", "observed"),162    "pl_bmassj": ("massJupiter", "observed"), "pl_dens": ("densityGramPerCm3", "computed"),163    "pl_eqt": ("equilibriumTemperatureK", "computed"), "pl_insol": ("insolationEarth", "computed"),164    "pl_trandep": ("transitDepthPercent", "observed"), "pl_trandur": ("transitDurationHours", "observed"),165    "pl_rvamp": ("radialVelocityAmplitudeMPerS", "observed"),166}167HOST_FIELDS = {168    "st_teff": "effectiveTemperatureK", "st_rad": "radiusSolar", "st_mass": "massSolar", "st_met": "metallicityDex",169    "st_logg": "surfaceGravityLogCgs", "st_lum": "luminosityLogSolar", "st_age": "ageGyr",170    "st_radv": "radialVelocityKmPerS", "st_rotp": "rotationPeriodDays",171}172173174def nea_measured(r, col, status):175    return measured(fnum(r[col]), plus=fnum(r[col + "err1"]), minus=fnum(r[col + "err2"]), limit=inum(r[col + "lim"]) or None,176                    status=status)177178179def host_identifier(r):180    """One object, one identifier: a host with a Hipparcos number is hip:<n>, else its Gaia DR3 source, else its name."""181    m = re.match(r"HIP (\d+)", r["hip_name"].strip())182    if m:183        return "hip:%d" % int(m.group(1))184    m = re.match(r"Gaia DR3 (\d+)", r["gaia_dr3_id"].strip())185    if m:186        return "gaia3:%d" % int(m.group(1))187    return "exohost:" + r["hostname"].strip()188189190def build_exoplanets(out_dir):191    store, pack_dir, built = open_store(out_dir, "exoplanets", ["nasa-exoplanet-archive-pscomppars"])192    prov = "nasa-exoplanet-archive-pscomppars"193    rows = list(read_csv(os.path.join(RAW, "nea", "pscomppars.csv"), nea_columns()))194    if len(rows) < 5000:195        raise SchemaError("pscomppars: only %d rows" % len(rows))196    hosts = {}197    for r in rows:198        hosts.setdefault(host_identifier(r), []).append(r)199    host_of_name = {}200    for hid in sorted(hosts):201        group = hosts[hid]202        r = group[0]203        ra, dec = fnum(r["ra"]), fnum(r["dec"])204        # an ObjectID is encoded by Swift's synthesised Codable as {"raw": "<namespace>:<key>"}205        rec = {"hostName": r["hostname"].strip(), "planets": [{"raw": "exo:" + p["pl_name"].strip()} for p in group],206               "references": {}}207        m = re.match(r"HIP (\d+)", r["hip_name"].strip())208        rec["hip"] = int(m.group(1)) if m else None209        rec["hd"] = r["hd_name"].strip() or None210        rec["tic"] = r["tic_id"].strip() or None211        for key, col in (("gaiaDR2", "gaia_dr2_id"), ("gaiaDR3", "gaia_dr3_id")):212            m = re.search(r"(\d+)$", r[col].strip())213            rec[key] = int(m.group(1)) if m else None214        rec["starCount"], rec["planetCount"] = inum(r["sy_snum"]), inum(r["sy_pnum"])215        rec["spectralType"] = r["st_spectype"].strip() or None216        rec["rightAscension"] = measured(ra * RAD if ra is not None else None)217        rec["declination"] = measured(dec * RAD if dec is not None else None)218        rec["parallaxMas"] = measured(fnum(r["sy_plx"]), plus=fnum(r["sy_plxerr1"]), minus=fnum(r["sy_plxerr2"]))219        rec["properMotionRAMasPerYear"] = measured(fnum(r["sy_pmra"]), sym=fnum(r["sy_pmraerr1"]))220        rec["properMotionDecMasPerYear"] = measured(fnum(r["sy_pmdec"]), sym=fnum(r["sy_pmdecerr1"]))221        d, dp, dm = fnum(r["sy_dist"]), fnum(r["sy_disterr1"]), fnum(r["sy_disterr2"])222        rec["distance"] = measured(d * PC if d is not None else None, plus=dp * PC if dp is not None else None,223                                   minus=dm * PC if dm is not None else None, status="computed")224        rec["magnitudeV"] = measured(fnum(r["sy_vmag"]), sym=fnum(r["sy_vmagerr1"]))225        rec["magnitudeG"] = measured(fnum(r["sy_gaiamag"]), sym=fnum(r["sy_gaiamagerr1"]))226        rec["magnitudeK"] = measured(fnum(r["sy_kmag"]), sym=fnum(r["sy_kmagerr1"]))227        for col, prop in HOST_FIELDS.items():228            rec[prop] = nea_measured(r, col, "estimated" if col in ("st_age", "st_mass", "st_rad", "st_lum") else "observed")229            ref = strip_tags(r[col + "_reflink"])230            if rec[prop] is not None and ref:231                rec["references"][prop] = ref232        name = r["hostname"].strip()233        designations = [(1, "NEA", name)]234        for text in (r["hip_name"], r["hd_name"], r["tic_id"], r["gaia_dr3_id"], r["gaia_dr2_id"]):235            if text.strip():236                designations.append((2, None, text.strip()))237        store.add(hid, "star", name, "observed", prov, ra=ra * RAD if ra is not None else None,238                  dec=dec * RAD if dec is not None else None, mag=fnum(r["sy_vmag"]) or fnum(r["sy_gaiamag"]),239                  record_type="hostStar", record=rec, designations=designations)240        host_of_name[name] = hid241    missing = {"pl_rade": 0, "pl_bmasse": 0, "pl_orbper": 0, "pl_orbeccen": 0}242    for r in sorted(rows, key=lambda x: x["pl_name"]):243        name = r["pl_name"].strip()244        hid = host_identifier(r)245        rec = {"host": {"raw": hid}, "hostName": r["hostname"].strip(), "letter": r["pl_letter"].strip() or None,246               "discoveryMethod": r["discoverymethod"].strip() or None, "discoveryYear": inum(r["disc_year"]),247               "discoveryReference": strip_tags(r["disc_refname"]), "discoveryFacility": r["disc_facility"].strip() or None,248               "controversial": inum(r["pl_controv_flag"]) == 1, "circumbinary": inum(r["cb_flag"]) == 1,249               "massProvenance": r["pl_bmassprov"].strip() or None, "references": {}}250        for col, (prop, status) in NEA_FIELDS.items():251            if col in ("pl_bmasse", "pl_bmassj") and "relationship" in r["pl_bmassprov"]:252                status = "estimated"  # mass from a mass-radius relation, not measured253            if col in ("pl_rade", "pl_radj") and "relationship" in (r["pl_rade_reflink"] + r["pl_radj_reflink"]).lower():254                status = "estimated"255            rec[prop] = nea_measured(r, col, status)256            ref = strip_tags(r[col + "_reflink"])257            if rec[prop] is not None and ref:258                rec["references"][prop] = ref259            if col in missing and rec[prop] is None:260                missing[col] += 1261        ra, dec = fnum(r["ra"]), fnum(r["dec"])262        store.add("exo:" + name, "exoplanet", name, "observed", prov, ra=ra * RAD if ra is not None else None,263                  dec=dec * RAD if dec is not None else None, mag=fnum(r["sy_vmag"]) or fnum(r["sy_gaiamag"]), parent=hid,264                  record_type="exoplanet", record=rec, designations=[(1, "NEA", name)])265    close_store(store, pack_dir, "exoplanets", "Confirmed exoplanets and their host stars (NASA Exoplanet Archive)", built,266                "No licence stated by the source; acknowledgement required", sources.object_sources()[prov]["citation"],267                {"allowed": UNVERIFIED, "statement": "Local build only until the terms are confirmed: the NASA Exoplanet Archive states no licence for redistribution of its tables; it requires the standard acknowledgement and citation of the original references."},268                {"content": "%d confirmed planets around %d hosts at retrieval." % (len(rows), len(hosts)),269                 "caveat": "pscomppars is a composite: each parameter comes from the reference the archive prefers, so a row is not one self-consistent solution. Missing parameters stay absent: %s." % ", ".join("%s absent for %d planets" % (k, v) for k, v in sorted(missing.items())),270                 "masses": "The mass column may hold a true mass, M sin i or a value from a mass-radius relation (field massProvenance); the last kind is flagged 'estimated'.",271                 "identity": "A host with a Hipparcos number is hip:<n>; otherwise gaia3:<Gaia DR3 source_id> as given by the archive; otherwise exohost:<name>."})272273274def build_candidates(out_dir):275    store, pack_dir, built = open_store(out_dir, "exoplanet-candidates", ["nasa-exoplanet-archive-toi"])276    prov = "nasa-exoplanet-archive-toi"277    n = 0278    dispositions = {}279    for r in sorted(read_csv(os.path.join(RAW, "nea", "toi.csv"), TOI_COLUMNS), key=lambda x: float(x["toi"])):280        toi = r["toi"].strip()281        disp = r["tfopwg_disp"].strip() or None282        dispositions[disp or "none"] = dispositions.get(disp or "none", 0) + 1283        d, de = fnum(r["st_dist"]), fnum(r["st_disterr1"])284        rec = {"toi": toi, "tic": r["tid"].strip(), "disposition": disp,285               "orbitalPeriodDays": measured(fnum(r["pl_orbper"]), sym=fnum(r["pl_orbpererr1"]), status="estimated"),286               "transitMidpointBJD": measured(fnum(r["pl_tranmid"]), sym=fnum(r["pl_tranmiderr1"]), status="estimated"),287               "transitDurationHours": measured(fnum(r["pl_trandurh"]), sym=fnum(r["pl_trandurherr1"]), status="estimated"),288               "transitDepthPpm": measured(fnum(r["pl_trandep"]), sym=fnum(r["pl_trandeperr1"]), status="estimated"),289               "radiusEarth": measured(fnum(r["pl_rade"]), sym=fnum(r["pl_radeerr1"]), status="estimated"),290               "insolationEarth": measured(fnum(r["pl_insol"]), status="estimated"),291               "equilibriumTemperatureK": measured(fnum(r["pl_eqt"]), status="estimated"),292               "tessMagnitude": measured(fnum(r["st_tmag"]), sym=fnum(r["st_tmagerr1"])),293               "stellarDistance": measured(d * PC if d is not None else None, sym=de * PC if de is not None else None, status="computed"),294               "stellarEffectiveTemperatureK": measured(fnum(r["st_teff"]), sym=fnum(r["st_tefferr1"]), status="estimated"),295               "stellarRadiusSolar": measured(fnum(r["st_rad"]), sym=fnum(r["st_raderr1"]), status="estimated"),296               "created": r["toi_created"].strip() or None, "updated": r["rowupdate"].strip() or None}297        ra, dec = fnum(r["ra"]), fnum(r["dec"])298        # a period of exactly 0 is the archive's code for "single transit, period unknown"299        if rec["orbitalPeriodDays"] and rec["orbitalPeriodDays"]["value"] == 0:300            rec["orbitalPeriodDays"] = None301        store.add("toi:" + toi, "exoplanet", "TOI-" + toi, "estimated", prov, ra=ra * RAD, dec=dec * RAD, mag=fnum(r["st_tmag"]),302                  record_type="candidate", record=rec, designations=[(0, "TOI", "TOI-" + toi, False)])303        n += 1304    if n < 5000:305        raise SchemaError("toi: only %d rows" % n)306    close_store(store, pack_dir, "exoplanet-candidates", "TESS Objects of Interest (candidates, not confirmed planets)", built,307                "No licence stated by the source; acknowledgement required", sources.object_sources()[prov]["citation"],308                {"allowed": UNVERIFIED, "statement": "Local build only until the terms are confirmed (same situation as the exoplanets pack)."},309                {"content": "%d TOIs. TFOPWG dispositions: %s." % (n, ", ".join("%s %d" % kv for kv in sorted(dispositions.items()))),310                 "caveat": "Candidates: every object has status 'estimated'. FP and FA are false positives/alarms kept for reference; CP and KP duplicate planets of the exoplanets pack under their TOI number (no cross-identification is attempted)."})311312313# ---------------------------------------------------------------- deep sky (OpenNGC)314315NGC_COLUMNS = ["Name", "Type", "RA", "Dec", "Const", "MajAx", "MinAx", "PosAng", "B-Mag", "V-Mag", "J-Mag", "H-Mag", "K-Mag",316               "SurfBr", "Hubble", "Pax", "RadVel", "Redshift", "M", "NGC", "IC", "Identifiers", "Common names", "NED notes",317               "OpenNGC notes", "Sources"]318KIND_OF_TYPE = {"G": "galaxy", "GPair": "galaxy", "GTrpl": "galaxy", "GGroup": "galaxy", "OCl": "starCluster",319                "GCl": "starCluster", "*Ass": "starCluster", "Cl+N": "starCluster", "PN": "nebula", "HII": "nebula",320                "DrkN": "nebula", "EmN": "nebula", "Neb": "nebula", "RfN": "nebula", "SNR": "nebula", "*": "star",321                "**": "star", "Nova": "star", "Other": "other"}322323324def ngc_identifier(name):325    """'NGC0224' -> ('ngc:224', 'NGC 224'); 'IC0002 NED01' -> ('ic:2NED01', 'IC 2 NED01'); addendum 'Mel022' -> ('mel:22', 'Mel 22')."""326    m = re.match(r"^(NGC|IC)(\d{4})(.*)$", name)327    if m:328        suffix = m.group(3).strip()329        key = str(int(m.group(2))) + suffix.replace(" ", "")330        return "%s:%s" % (m.group(1).lower(), key), ("%s %d %s" % (m.group(1), int(m.group(2)), suffix)).strip()331    m = re.match(r"^([A-Za-z]+)(\d+)(.*)$", name)332    if not m:333        return "ongc:" + name, name334    return "%s:%d%s" % (m.group(1).lower(), int(m.group(2)), m.group(3)), "%s %d%s" % (m.group(1), int(m.group(2)), m.group(3))335336337def openngc_rows():338    rows = []339    for fname in ("NGC_%s.csv" % OPENNGC_TAG, "addendum_%s.csv" % OPENNGC_TAG):340        rows += list(read_csv(os.path.join(RAW, "openngc", fname), NGC_COLUMNS, delimiter=";"))341    if len(rows) < 13000:342        raise SchemaError("OpenNGC: only %d rows" % len(rows))343    return rows344345346def openngc_objects():347    """Returns (objects, messier) where objects is a list of dicts ready for Store.add and messier maps M number -> id."""348    rows = openngc_rows()349    aliases = {}350    for r in rows:351        if r["Type"] == "Dup":352            target = ("NGC%04d" % int(r["NGC"])) if r["NGC"].strip().isdigit() else (("IC%04d" % int(r["IC"])) if r["IC"].strip().isdigit() else None)353            if target:354                aliases.setdefault(target, []).append(ngc_identifier(r["Name"])[1])355    objects, messier = [], {}356    for r in rows:357        if r["Type"] in ("Dup", "NonEx") or not r["RA"].strip():358            continue359        oid, display = ngc_identifier(r["Name"])360        prefix = oid.split(":")[0]361        v, b = fnum(r["V-Mag"]), fnum(r["B-Mag"])362        common = [c.strip() for c in r["Common names"].split(",") if c.strip()]363        m = inum(r["M"])364        rec = {"typeCode": r["Type"], "constellation": CON_CASE.get(r["Const"].strip().lower()),365               "majorAxisArcmin": measured(fnum(r["MajAx"])), "minorAxisArcmin": measured(fnum(r["MinAx"])),366               "positionAngleDeg": measured(fnum(r["PosAng"])), "magnitudeB": measured(b), "magnitudeV": measured(v),367               "magnitudeJ": measured(fnum(r["J-Mag"])), "magnitudeH": measured(fnum(r["H-Mag"])),368               "magnitudeK": measured(fnum(r["K-Mag"])), "surfaceBrightness": measured(fnum(r["SurfBr"])),369               "hubbleType": r["Hubble"].strip() or None, "radialVelocityKmPerS": measured(fnum(r["RadVel"])),370               "redshift": measured(fnum(r["Redshift"])), "parallaxMas": measured(fnum(r["Pax"])), "messier": m,371               "commonNames": common, "sources": r["Sources"].strip() or None,372               "notes": "; ".join(x for x in (r["NED notes"].strip(), r["OpenNGC notes"].strip()) if x) or None}373        designations = [(0, {"ngc": "NGC", "ic": "IC"}.get(prefix, "OpenNGC"), display, False)]374        name = display375        if m:376            designations.append((2, "Messier", "M %d" % m, False))377            name = "M %d" % m378            messier[m] = oid379        elif prefix == "m":380            messier[int(oid.split(":")[1])] = oid381        elif common:382            name = common[0]383        designations += [(1, "common name", c) for c in common]384        designations += [(2, None, a, False) for a in aliases.get(r["Name"], [])]385        designations += [(2, None, x.strip(), False) for x in r["Identifiers"].split(",") if x.strip()]386        objects.append(dict(oid=oid, kind=KIND_OF_TYPE.get(r["Type"], "other"), name=name, status="observed", prov="openngc",387                            ra=sexagesimal(r["RA"], True), dec=sexagesimal(r["Dec"], False), mag=v if v is not None else b,388                            record_type="deepSky", record=rec, designations=designations))389    objects.sort(key=lambda o: o["oid"])390    if messier.get(31) != "ngc:224" or len(messier) < 105:391        raise SchemaError("OpenNGC: Messier cross-identification looks wrong (M31 -> %r, %d Messier objects)" % (messier.get(31), len(messier)))392    return objects, messier393394395OPENNGC_LICENCE = "CC BY-SA 4.0 (OpenNGC)"396OPENNGC_REDIS = {"allowed": "yes", "statement": "CC BY-SA 4.0: redistribution and adaptation allowed with attribution to OpenNGC (Mattia Verga) and under the same licence."}397398399def build_deep_sky(out_dir):400    store, pack_dir, built = open_store(out_dir, "deep-sky", ["openngc"])401    objects, messier = openngc_objects()402    for o in objects:403        store.add(**o)404    close_store(store, pack_dir, "deep-sky", "NGC, IC and Messier objects (OpenNGC)", built, OPENNGC_LICENCE,405                sources.object_sources()["openngc"]["citation"], OPENNGC_REDIS,406                {"content": "%d objects (%d Messier). Duplicate catalogue entries are aliases of their target; non-existent entries are dropped." % (len(objects), len(messier)),407                 "caveat": "No uncertainties are published by OpenNGC. Magnitudes and sizes mix sources (LEDA, SIMBAD, HEASARC), see the per-field source codes. The redshift is the main SIMBAD value; no distance is derived from it."})408409410# ---------------------------------------------------------------- constellations411412def precession_b1875_to_j2000():413    """Rotation matrix taking B1875.0 equatorial vectors to J2000.0 (IAU 1976 precession, Lieske et al. 1977)."""414    jd_b1875 = 2415020.31352 + (1875.0 - 1900.0) * 365.242198781415    t = (jd_b1875 - 2451545.0) / 36525.0416    arcsec = RAD / 3600.0417    zeta = (2306.2181 * t + 0.30188 * t * t + 0.017998 * t ** 3) * arcsec418    z = (2306.2181 * t + 1.09468 * t * t + 0.018203 * t ** 3) * arcsec419    theta = (2004.3109 * t - 0.42665 * t * t - 0.041833 * t ** 3) * arcsec420    cz, sz, ct, st, cx, sx = math.cos(z), math.sin(z), math.cos(theta), math.sin(theta), math.cos(zeta), math.sin(zeta)421    # P(J2000 -> date) = Rz(-z) Ry(theta) Rz(-zeta); its transpose takes date -> J2000422    p = [[cz * ct * cx - sz * sx, -cz * ct * sx - sz * cx, -cz * st],423         [sz * ct * cx + cz * sx, -sz * ct * sx + cz * cx, -sz * st],424         [st * cx, -st * sx, ct]]425    return [[p[j][i] for j in range(3)] for i in range(3)]426427428def constellation_objects(hip_positions):429    """88 constellation objects with boundaries (J2000) and figures. `hip_positions`: HIP -> (ra, dec) radians."""430    with open(os.path.join(RAW, "stellarium", "modern_index_%s.json" % STELLARIUM_TAG), encoding="utf-8") as f:431        culture = json.load(f)432    if culture.get("edges_epoch") != "B1875" or len(culture["constellations"]) != 88:433        raise SchemaError("Stellarium sky culture: unexpected layout")434    rot = precession_b1875_to_j2000()435436    def to_j2000(ra, dec):437        v = sf.unit(ra, dec)438        w = [sum(rot[i][j] * v[j] for j in range(3)) for i in range(3)]439        return (math.atan2(w[1], w[0]) % (2 * math.pi), math.asin(max(-1.0, min(1.0, w[2]))))440441    step = 0.25 * RAD442    boundaries = {}443    for edge in culture["edges"]:444        parts = edge.split()445        if len(parts) != 8 or parts[1] not in ("M+", "M-", "P+", "P-"):446            raise SchemaError("Stellarium edge not understood: " + edge)447        ra1, dec1, ra2, dec2 = sexagesimal(parts[2], True), sexagesimal(parts[3], False), sexagesimal(parts[4], True), sexagesimal(parts[5], False)448        if parts[1][0] == "M":   # along a meridian of B1875: constant right ascension449            n = max(1, int(math.ceil(abs(dec2 - dec1) / step)))450            pts = [(ra1, dec1 + (dec2 - dec1) * k / n) for k in range(n + 1)]451        else:                     # along a parallel of B1875: constant declination, direction given by the sign452            d = (ra2 - ra1) % (2 * math.pi) if parts[1][1] == "+" else -((ra1 - ra2) % (2 * math.pi))453            n = max(1, int(math.ceil(abs(d) * math.cos(dec1) / step)))454            pts = [((ra1 + d * k / n) % (2 * math.pi), dec1) for k in range(n + 1)]455        line = [to_j2000(*p) for p in pts]456        for label in parts[6:8]:457            abbr = CON_CASE.get(label[:3].lower())458            if abbr is None:459                raise SchemaError("unknown constellation label %r in edge %s" % (label, edge))460            boundaries.setdefault(abbr, []).append(line)461    validate_boundaries(boundaries)462    names = {c[0]: c for c in CONSTELLATIONS}463    objects = []464    for c in culture["constellations"]:465        abbr = c["id"].split()[-1]466        if abbr not in names:467            raise SchemaError("unknown constellation id " + c["id"])468        figure, vectors = [], []469        for line in c["lines"]:470            poly = []471            for h in line:472                if not isinstance(h, int) or h not in hip_positions:473                    raise SchemaError("figure of %s uses %r, which is not a Hipparcos star of the new reduction" % (abbr, h))474                ra, dec = hip_positions[h]475                poly.append({"ra": ra, "dec": dec, "hip": h})476                vectors.append(sf.unit(ra, dec))477            figure.append(poly)478        sx, sy, sz = (sum(v[i] for v in vectors) for i in range(3))479        rec = {"abbreviation": abbr, "name": names[abbr][1], "genitive": names[abbr][2],480               "englishName": c.get("common_name", {}).get("english"),481               "boundaries": [[{"ra": ra, "dec": dec} for ra, dec in line] for line in boundaries[abbr]], "figure": figure}482        designations = [(1, "IAU", names[abbr][1]), (2, "IAU", names[abbr][2], False), (2, "IAU", abbr, False)]483        if rec["englishName"]:484            designations.append((1, "English", rec["englishName"]))485        objects.append(dict(oid="con:" + abbr, kind="constellation", name=names[abbr][1], status="observed", prov="stellarium-modern",486                            ra=math.atan2(sy, sx) % (2 * math.pi), dec=math.atan2(sz, math.hypot(sx, sy)), record_type="constellation",487                            record=rec, designations=designations))488    objects.sort(key=lambda o: o["oid"])489    return objects490491492def validate_boundaries(boundaries):493    """Independent check of the precession: every J2000 boundary point of VizieR VI/49 (Davenhall & Leggett 1989)494    must lie within 0.02 degree of our polylines of the same constellation. VI/49 is not copied into the pack."""495    path = os.path.join(RAW, "vizier", "VI_49_bound_20.dat.gz")496    if not os.path.exists(path):497        raise SchemaError("VI/49 reference file missing: cannot validate the constellation boundaries")498    worst, n = 0.0, 0499    with gzip.open(path, "rt") as f:500        for k, line in enumerate(f):501            if k % 7:502                continue  # one point in seven is plenty503            ra, dec, label = float(line[0:11]) * RAD, float(line[12:23]) * RAD, line[24:28].strip()504            abbr = CON_CASE[label[:3].lower()]505            u = sf.unit(ra, dec)506            best = min(sf.separation(u, sf.unit(*p)) for poly in boundaries[abbr] for p in poly)507            worst = max(worst, best)508            n += 1509    # polyline vertices are 0.25 degree apart: a point between two vertices is at most 0.125 degree from one of them510    if worst > (0.125 + 0.02) * RAD:511        raise SchemaError("constellation boundaries disagree with VI/49 by %.4f degree" % (worst / RAD))512    log("constellation boundaries: %d VI/49 points checked, largest distance to a vertex %.4f degree" % (n, worst / RAD))513514515# ---------------------------------------------------------------- starter516517def build_starter(out_dir):518    pack_dir = os.path.join(out_dir, "starter")519    part_path = os.path.join(pack_dir, "stars_part.json")520    if not os.path.exists(part_path):521        raise SchemaError("starter: run build_stars.py first (no %s)" % part_path)522    with open(part_path, encoding="utf-8") as f:523        part = json.load(f)524    store, pack_dir, built = open_store(out_dir, "starter", ["esa-hipparcos-2007", "esa-hipparcos-1997", "esa-gaia-dr3", "gaia-edr3-gcns",525                                                             "bailer-jones-2021", "iau-csn", "hyg-v41", "openngc", "stellarium-modern"])526    hip_positions = {}527    for oid, name, prov, ra, dec, mag, designations, sptype in part["rows"]:528        store.add(oid, "star", name, "observed", prov, ra=ra, dec=dec, mag=mag, designations=[tuple(d) for d in designations], count=False)529        store.star_text(oid, sptype)530        if oid.startswith("hip:"):531            hip_positions[int(oid[4:])] = (ra, dec)532    for o in constellation_objects(hip_positions):533        store.add(**o)534    objects, messier = openngc_objects()535    kept = 0536    for o in objects:537        rec = o["record"]538        bright = o["mag"] is not None and o["mag"] <= 10.0539        if rec["messier"] or o["oid"].startswith("m:") or rec["commonNames"] or bright:540            store.add(**o)541            kept += 1542    store.counts["star"] = part["counts"]["records"]543    os.remove(part_path)544    close_store(store, pack_dir, "starter", "Starter catalogue: bright, named and nearest stars, constellations, Messier and bright NGC/IC objects", built,545                part["licence"] + "; CC BY-SA 4.0 (OpenNGC, Stellarium constellation data)",546                sources.GAIA_ACK + " OpenNGC (M. Verga), Stellarium sky culture 'modern', IAU Working Group on Star Names, HYG database (D. Nash).",547                {"allowed": "non-commercial", "statement": part["redistribution"][1] + " OpenNGC and Stellarium constellation data: CC BY-SA 4.0."},548                {"stars": part["selection"], "distances": part["distances"], "parallax_zero_point": part["zero_point"],549                 "deep_sky": "%d OpenNGC objects: all Messier objects, objects with a common name, and objects with V (or B) <= 10." % kept,550                 "constellations": "88 IAU constellations: boundaries precessed from B1875 to J2000, traditional figure lines (a convention, not a physical grouping).",551                 "exoplanets": "Planets are not in this pack (the NASA Exoplanet Archive states no redistribution licence): the host stars with a Hipparcos number are present as stars; install the exoplanets pack for the planets.",552                 "local_group": "Local Group galaxies are present only through their NGC/IC/Messier entries (M 31, M 33, NGC 6822, IC 10, ...); the full compilation is in the galaxies pack."},553                {"starFlag": sf.FLAG_STARTER})554555556# ---------------------------------------------------------------- galaxies557558def read_fits_table(path):559    """Minimal reader of the first binary-table extension of a FITS file (A, E, D, I, J columns)."""560    with open(path, "rb") as f:561        data = f.read()562563    def header(off):564        cards = {}565        while True:566            card = data[off:off + 80].decode("ascii", "replace")567            off += 80568            if card.startswith("END"):569                break570            m = re.match(r"(\w+)\s*=\s*('([^']*)'|[^/]*)", card)571            if m:572                cards[m.group(1)] = (m.group(3) if m.group(3) is not None else m.group(2)).strip()573        return cards, ((off + 2879) // 2880) * 2880574    _, off = header(0)575    h, off = header(off)576    if h.get("XTENSION") != "BINTABLE":577        raise SchemaError("%s: first extension is not a binary table" % path)578    n, width, nf = int(h["NAXIS2"]), int(h["NAXIS1"]), int(h["TFIELDS"])579    fmt, names = ">", []580    for k in range(1, nf + 1):581        m = re.match(r"(\d*)([AEDIJ])", h["TFORM%d" % k])582        count, code = int(m.group(1) or 1), m.group(2)583        fmt += ("%ds" % count) if code == "A" else {"E": "f", "D": "d", "I": "h", "J": "i"}[code] * count584        names.append(h["TTYPE%d" % k])585    s = struct.Struct(fmt)586    if s.size != width:587        raise SchemaError("%s: row width %d does not match the column formats (%d)" % (path, width, s.size))588    rows = []589    for i in range(n):590        values = s.unpack_from(data, off + i * width)591        rows.append({k: (v.decode("ascii", "replace").strip() if isinstance(v, bytes) else v) for k, v in zip(names, values)})592    return rows593594595LOCAL_GROUP_IDS = {"Andromeda": "ngc:224", "Triangulum": "ngc:598", "SMC": "ngc:292"}  # M 31, M 33, NGC 292596597598def in_range(v, lo, hi):599    """The compilation codes a missing value with a number outside the physical range (99.99, 999.9, ...)."""600    return v if v is not None and v == v and lo < v < hi else None601602603def build_galaxies(out_dir):604    store, pack_dir, built = open_store(out_dir, "galaxies", ["mcconnachie-2012", "abell-aco-1989"])605    rows = read_fits_table(os.path.join(RAW, "localgroup", "NearbyGalaxies_Jan2021_PUBLIC.fits"))606    expected = ["GalaxyName", "RA", "Dec", "dmod", "dmod+", "dmod-", "vh", "vh+", "vh-", "Vmag", "Vmag+", "Vmag-", "PA", "e=1-b/a", "rh", "[Fe/H]", "References"]607    if [c for c in expected if c not in rows[0]]:608        raise SchemaError("Local Group table: missing columns")609    _, messier = openngc_objects()610    n_lg = 0611    for r in rows:612        raw_name = r["GalaxyName"]613        name = raw_name.lstrip("*")614        if name in ("TheGalaxy", "The Galaxy", "MilkyWay"):615            continue616        m = re.match(r"^(NGC|IC)\s*(\d+)$", name)617        mm = re.match(r"^M(\d+)$", name)618        if m:619            oid = "%s:%d" % (m.group(1).lower(), int(m.group(2)))620        elif mm and int(mm.group(1)) in messier:621            oid = messier[int(mm.group(1))]622        else:623            oid = LOCAL_GROUP_IDS.get(name, "lg:" + name)624        dmod, dp, dm = in_range(r["dmod"], 10, 35), in_range(r["dmod+"], 0, 5), in_range(r["dmod-"], 0, 5)625        dist = None626        if dmod is not None:627            d = 10 ** (dmod / 5 + 1)628            plus = 10 ** ((dmod + dp) / 5 + 1) - d if dp is not None else None629            minus = d - 10 ** ((dmod - dm) / 5 + 1) if dm is not None else None630            dist = measured(d * PC, plus=plus * PC if plus is not None else None, minus=minus * PC if minus is not None else None, status="computed")631        vh = in_range(r["vh"], -900, 900)632        v = in_range(r["Vmag"], -30, 30)633        rec = {"catalog": "McConnachie (2012), January 2021 update", "redshiftFrame": "heliocentric" if vh is not None else None,634               "recessionVelocityKmPerS": measured(vh, plus=in_range(r["vh+"], 0, 90), minus=in_range(r["vh-"], 0, 90)),635               "redshift": measured(vh / C_KM_S if vh is not None else None, status="computed"),636               "redshiftIndependentDistance": dist, "distanceModulus": measured(dmod, plus=dp, minus=dm),637               "magnitudeV": measured(v, plus=in_range(r["Vmag+"], 0, 9), minus=in_range(r["Vmag-"], 0, 9)),638               "halfLightRadiusArcmin": measured(in_range(r["rh"], 0, 900)), "ellipticity": measured(in_range(r["e=1-b/a"], -0.001, 1)),639               "positionAngleDeg": measured(in_range(r["PA"], -0.001, 360.001)), "metallicityFeH": measured(in_range(r["[Fe/H]"], -6, 2)),640               "subgroup": "marked '*' in the source table" if raw_name.startswith("*") else None, "references": r["References"] or None}641        pretty = re.sub(r"^([A-Z]{2,})(?=\d)", r"\1 ", re.sub(r"(?<=[a-z])(?=[A-Z0-9])", " ", name))642        store.add(oid, "galaxy", pretty, "observed", "mcconnachie-2012", ra=sexagesimal(r["RA"], True), dec=sexagesimal(r["Dec"], False),643                  mag=v, record_type="galaxy", record=rec, designations=[(1, "McConnachie", pretty)] + ([(1, "McConnachie", name)] if name != pretty else []))644        n_lg += 1645    n_ab = 0646    for table, part in (("VII_110A_table3.dat.gz", "north"), ("VII_110A_table4.dat.gz", "south")):647        with gzip.open(os.path.join(RAW, "vizier", table), "rt") as f:648            for line in f:649                line = line.rstrip("\n").ljust(150)650                number = int(line[0:4])651                ra = (int(line[86:88]) + float(line[89:93]) / 60) * 15 * RAD652                dec = (int(line[95:97]) + int(line[98:100]) / 60) * RAD * (-1 if line[94] == "-" else 1)653                z = fnum(line[133:138])654                rec = {"abellNumber": number, "part": part, "richnessClass": inum(line[140]), "distanceClass": inum(line[142]),655                       "magnitudeTenth": measured(fnum(line[144:148])), "redshift": measured(z),656                       "redshiftFrame": "heliocentric" if z is not None else None, "bautzMorganType": line[42:49].strip() or None,657                       "memberCount": inum(line[52:55])}658                store.add("abell:%d" % number, "galaxyCluster", "Abell %d" % number, "observed", "abell-aco-1989", ra=ra, dec=dec,659                          mag=fnum(line[144:148]), record_type="galaxyCluster", record=rec,660                          designations=[(0, "Abell", "Abell %d" % number, False), (2, "ACO", "ACO %d" % number, False)])661                n_ab += 1662    if n_ab != 4076:663        raise SchemaError("Abell/ACO: %d clusters, 4076 expected" % n_ab)664    close_store(store, pack_dir, "galaxies", "Dwarf galaxies of the Local Group and its surroundings (McConnachie 2012, 2021 update) and Abell/ACO rich clusters", built,665                "No licence stated (McConnachie compilation); VizieR terms not verified (Abell/ACO)", "McConnachie (2012), AJ 144, 4; Abell, Corwin & Olowin (1989), ApJS 70, 1; VizieR (CDS).",666                {"allowed": UNVERIFIED, "statement": "Local build only until the terms are confirmed: the Local Group compilation carries no licence statement, and the CDS rules of usage for VizieR catalogues could not be read on the retrieval date (page unavailable)."},667                {"content": "%d dwarf galaxies in and around the Local Group (the compilation lists the satellites and isolated dwarfs out to about 3 Mpc, including the Magellanic Clouds and M 33; the Milky Way and M 31 themselves are not rows of it); %d Abell/ACO clusters (2712 northern, 1364 southern)." % (n_lg, n_ab),668                 "distances": "Local Group: redshift-independent distances from the published distance modulus (status 'computed'). Clusters: only the published redshift (Struble & Rood 1987, treated as heliocentric) is stored where it exists; no distance is stored, the cosmology module computes it at run time.",669                 "caveat": "Abell positions are given to 0.1 minute of time and 1 arcminute. The Abell catalogue is a visual selection on photographic plates, complete only for rich clusters at |b| > 30 degrees and z < 0.2."})670671672def build_2mrs(out_dir):673    store, pack_dir, built = open_store(out_dir, "galaxies-2mrs", ["2mrs"])674    _, messier = openngc_objects()675    with tarfile.open(os.path.join(RAW, "2mrs", "2mrs_v240.tgz")) as tar:676        lines = tar.extractfile("catalog/2mrs_1175_done.dat").read().decode("ascii").splitlines()677    header = [line for line in lines if line.startswith("#ID")]678    if not header or header[0].split()[-6:] != ["ts", "v", "e_v", "c", "vsrc", "CAT_ID"]:679        raise SchemaError("2MRS: unexpected header")680    n = 0681    for line in lines:682        if line.startswith("#") or not line.strip():683            continue684        t = line.split()685        # 29 columns, but the morphological type can be blank or hold a space and the catalogue name can hold a686        # space: anchor on the 19-character bibliographic code of the redshift (column vsrc)687        j = max((i for i, x in enumerate(t) if len(x) == 19 and re.match(r"^(19|20)\d\d", x)), default=-1)688        if len(t) < 28 or j < 26 or j + 1 >= len(t):689            raise SchemaError("2MRS: line not understood: %s" % line[:80])690        try:691            v, ev = float(t[j - 3]), float(t[j - 2])692            numeric = [float(x) for x in t[1:21]]693        except ValueError as exc:694            raise SchemaError("2MRS: non-numeric field in line: %s" % line[:80]) from exc695        tmid, cat, vsrc = t[0], " ".join(t[j + 1:]), t[j]696        morphology = " ".join(t[22:j - 4]) or None697        oid = None698        m = re.match(r"^(NGC|IC)_(\d{4})$", cat)699        mm = re.match(r"^MESSIER_(\d{3})$", cat)700        if m:701            oid = "%s:%d" % (m.group(1).lower(), int(m.group(2)))702        elif mm:703            oid = messier.get(int(mm.group(1)))704        if oid is None or store.has(oid):705            oid = "2masx:" + tmid706        k = numeric[7]   # k_tc: total Ks magnitude, extinction-corrected707        rec = {"catalog": "2MRS", "morphology": morphology, "redshiftFrame": "heliocentric",708               "recessionVelocityKmPerS": measured(v, sym=ev), "redshift": measured(v / C_KM_S, sym=ev / C_KM_S, status="computed"),709               "redshiftReference": vsrc, "magnitudeK": measured(k, sym=numeric[13])}710        name = cat.replace("_", " ")711        name = re.sub(r"^(NGC|IC|MESSIER|UGC|PGC|ESO|MCG) 0*", lambda x: {"MESSIER": "M"}.get(x.group(1), x.group(1)) + " ", name)712        store.add(oid, "galaxy", name, "observed", "2mrs", ra=float(t[1]) * RAD, dec=float(t[2]) * RAD, mag=k, record_type="galaxy",713                  record=rec, designations=[(0, "2MASX", "2MASX J" + tmid, False), (2, None, name, False)])714        n += 1715    if n != 43533:716        raise SchemaError("2MRS: %d galaxies, 43533 expected" % n)717    close_store(store, pack_dir, "galaxies-2mrs", "2MASS Redshift Survey (Huchra et al. 2012): 43 533 galaxies with redshifts", built,718                "Not redistributable (request of the 2MRS team)", sources.object_sources()["2mrs"]["citation"],719                {"allowed": "no", "statement": "Local build only — not redistributable. The 2MRS README asks: \"Please do not redistribute any of these files.\" Build it on the user's machine with DataPipeline/catalogs."},720                {"content": "%d galaxies, Ks <= 11.75 (extinction-corrected), |b| >= 5 degrees (>= 8 degrees towards the bulge), 97.6 %% complete in redshift." % n,721                 "redshifts": "Stored: heliocentric cz (km/s) with its error and z = cz/c. No distance is stored: distances from redshift are computed at run time by the cosmology module (peculiar velocities are not corrected).",722                 "identity": "Galaxies whose 2MRS catalogue name is an NGC, IC or Messier entry share the identifier of the deep-sky pack (ngc:<n>, ic:<n>); the others are 2masx:<2MASS designation>."})723724725# ---------------------------------------------------------------- satellites, minor bodies726727def build_satellites(out_dir):728    store, pack_dir, built = open_store(out_dir, "satellites", ["celestrak-gp"])729    objects = {}730    for group in CELESTRAK_GROUPS:731        with open(os.path.join(RAW, "celestrak", "gp_%s.json" % group), encoding="utf-8") as f:732            data = json.load(f)733        for e in data:734            missing = [k for k in ("OBJECT_NAME", "EPOCH", "MEAN_MOTION", "ECCENTRICITY", "INCLINATION", "RA_OF_ASC_NODE", "ARG_OF_PERICENTER", "MEAN_ANOMALY", "NORAD_CAT_ID") if k not in e]735            if missing:736                raise SchemaError("CelesTrak %s: missing %s" % (group, missing))737            o = objects.setdefault(int(e["NORAD_CAT_ID"]), {"e": e, "groups": []})738            o["groups"].append(group)739    epochs = sorted(o["e"]["EPOCH"] for o in objects.values())740    for norad in sorted(objects):741        e, groups = objects[norad]["e"], objects[norad]["groups"]742        rec = {"noradID": norad, "objectName": e["OBJECT_NAME"], "internationalDesignator": e.get("OBJECT_ID"), "epoch": e["EPOCH"],743               "meanMotionRevPerDay": e["MEAN_MOTION"], "eccentricity": e["ECCENTRICITY"], "inclinationDeg": e["INCLINATION"],744               "raanDeg": e["RA_OF_ASC_NODE"], "argumentOfPericenterDeg": e["ARG_OF_PERICENTER"], "meanAnomalyDeg": e["MEAN_ANOMALY"],745               "bstar": e.get("BSTAR"), "meanMotionDot": e.get("MEAN_MOTION_DOT"), "meanMotionDDot": e.get("MEAN_MOTION_DDOT"),746               "elementSetNumber": e.get("ELEMENT_SET_NO"), "revolutionAtEpoch": e.get("REV_AT_EPOCH"),747               "classification": e.get("CLASSIFICATION_TYPE"), "ephemerisType": e.get("EPHEMERIS_TYPE"), "groups": groups}748        designations = [(1, "CelesTrak", e["OBJECT_NAME"]), (0, "NORAD", "NORAD %d" % norad, False)]749        if e.get("OBJECT_ID"):750            designations.append((2, "COSPAR", e["OBJECT_ID"], False))751        store.add("norad:%d" % norad, "artificialSatellite", e["OBJECT_NAME"], "computed", "celestrak-gp", parent="naif:399",752                  record_type="satellite", record=rec, designations=designations)753    close_store(store, pack_dir, "satellites", "Artificial satellites: GP element sets (CelesTrak snapshot)", built,754                "No licence stated by the source", sources.object_sources()["celestrak-gp"]["citation"],755                {"allowed": UNVERIFIED, "statement": "Local build only until the terms are confirmed: CelesTrak states a usage policy (one download per data update, stop on HTTP errors) but no redistribution licence; the elements originate from the U.S. Space Force."},756                {"content": "%d objects from the groups %s." % (len(objects), ", ".join(CELESTRAK_GROUPS)),757                 "epochs": "Element-set epochs from %s to %s (UTC). Each record keeps its own epoch: SGP4 positions degrade by kilometres per day of age for low orbits, so the data age must be shown." % (epochs[0], epochs[-1]),758                 "caveat": "Dated snapshot, not a live feed. Elements are SGP4 mean elements: they must be propagated with SGP4 only."})759760761def build_minor_bodies(out_dir):762    store, pack_dir, built = open_store(out_dir, "minor-bodies", ["jpl-sbdb"])763    counts = {}764    for fname, kind in (("asteroids_numbered_H10.json", "asteroid"), ("comets_numbered.json", "comet")):765        with open(os.path.join(RAW, "sbdb", fname), encoding="utf-8") as f:766            data = json.load(f)767        fields = data["fields"]768        need = ["spkid", "full_name", "pdes", "name", "class", "H", "epoch", "e", "a", "q", "i", "om", "w", "ma", "tp", "per", "n", "orbit_id"]769        if [c for c in need if c not in fields] or int(data["count"]) != len(data["data"]):770            raise SchemaError("SBDB %s: unexpected fields or count" % fname)771        for row in sorted(data["data"], key=lambda x: int(x[0])):772            r = dict(zip(fields, row))773            number = int(r["pdes"]) if kind == "asteroid" and str(r["pdes"]).isdigit() else None774            full = " ".join(r["full_name"].split())775            rec = {"designation": r["pdes"], "number": number, "orbitClass": r["class"],776                   "absoluteMagnitudeH": measured(fnum(r["H"])), "slopeG": measured(fnum(r["G"])),777                   "cometTotalMagnitudeM1": measured(fnum(r["M1"])), "diameterKm": measured(fnum(r["diameter"])),778                   "albedo": measured(fnum(r["albedo"])), "rotationPeriodHours": measured(fnum(r["rot_per"])),779                   "gmKm3PerS2": measured(fnum(r["GM"])), "epochJD": fnum(r["epoch"]),780                   "eccentricity": measured(fnum(r["e"]), sym=fnum(r["sigma_e"]), status="computed"),781                   "semiMajorAxisAU": measured(fnum(r["a"]), sym=fnum(r["sigma_a"]), status="computed"),782                   "perihelionDistanceAU": measured(fnum(r["q"]), status="computed"),783                   "inclinationDeg": measured(fnum(r["i"]), sym=fnum(r["sigma_i"]), status="computed"),784                   "ascendingNodeDeg": measured(fnum(r["om"]), status="computed"),785                   "argumentOfPerihelionDeg": measured(fnum(r["w"]), status="computed"),786                   "meanAnomalyDeg": measured(fnum(r["ma"]), status="computed"),787                   "timeOfPerihelionJD": measured(fnum(r["tp"]), status="computed"),788                   "periodDays": measured(fnum(r["per"]), status="computed"),789                   "meanMotionDegPerDay": measured(fnum(r["n"]), status="computed"),790                   "orbitSolution": r["orbit_id"], "conditionCode": r["condition_code"]}791            if kind == "asteroid":792                name = ("%s %s" % (r["pdes"], r["name"])) if r["name"] else full793                designations = [(0, "MPC", name, bool(r["name"]))]794                if r["name"]:795                    designations.append((1, "IAU", r["name"]))796                designations.append((2, "MPC", "(%s)" % r["pdes"], False))797            else:798                name = full799                designations = [(0, "MPC", full, True), (2, "MPC", r["pdes"], False)]800                if r["name"]:801                    designations.append((1, "IAU", "Comet " + r["name"]))802            store.add("naif:%d" % int(r["spkid"]), kind, name, "observed", "jpl-sbdb", mag=fnum(r["H"]) if kind == "asteroid" else fnum(r["M1"]),803                      parent="naif:10", record_type="minorBody", record=rec, designations=designations)804            counts[kind] = counts.get(kind, 0) + 1805    close_store(store, pack_dir, "minor-bodies", "Minor bodies: numbered asteroids with H <= 10 and numbered periodic comets (JPL SBDB)", built,806                "No licence stated by the source", sources.object_sources()["jpl-sbdb"]["citation"],807                {"allowed": UNVERIFIED, "statement": "Local build only until the terms are confirmed: the SBDB API documentation states no licence (NASA/JPL-Caltech data; credit requested)."},808                {"content": "%d asteroids, %d comets." % (counts.get("asteroid", 0), counts.get("comet", 0)),809                 "identifiers": "naif:<SPK-ID>: 20000000 + number for numbered asteroids (Horizons extended numbering, e.g. naif:20000001 = Ceres, as in core-ephemeris/kepler_elements.json) and the JPL 1000xxx codes for comets (naif:1000036 = 1P/Halley).",810                 "caveat": "Osculating elements at the epoch of each record (heliocentric, ecliptic J2000). They give an approximate two-body orbit only: no planetary perturbations, no non-gravitational forces (comets). Positions derived from them are 'estimated' and degrade away from the epoch; several comet solutions are decades old."})811812813BUILDERS = {"exoplanets": build_exoplanets, "exoplanet-candidates": build_candidates, "deep-sky": build_deep_sky,814            "galaxies": build_galaxies, "galaxies-2mrs": build_2mrs, "satellites": build_satellites,815            "minor-bodies": build_minor_bodies, "starter": build_starter}816817818def main(argv):819    args = argv[1:]820    out_dir = PACKS821    if "--out" in args:822        i = args.index("--out")823        out_dir = args[i + 1]824        del args[i:i + 2]825    for name in args or list(BUILDERS):826        if name not in BUILDERS:827            sys.exit("unknown pack %r\n%s" % (name, __doc__))828        BUILDERS[name](out_dir)829830831if __name__ == "__main__":832    main(sys.argv)833
Files main
Menu

Theme