SPB Git

Repository Public

parse_facts.py 71.1 KB 1,266 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/textures/parse_facts.py11# Description      : Parses the cached NSSDCA fact sheets, JPL SSD12#                    physical-parameter tables, JPL SBDB records and PDS13#                    Ring-Moon Systems Node ring tables14#                    (DataPipeline/raw/facts) into the versioned15#                    DataPipeline/textures/data/facts.json (SI units, per-value16#                    provenance, nothing guessed). 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"""Usage: python3 -I parse_facts.py <repository root>9697Input : DataPipeline/raw/facts/*  (written by fetch_facts.sh; untrusted web pages, only parsed as text)98Output: DataPipeline/textures/data/facts.json99100Rules101  * Every number is read from a source page. A quantity the sources do not give is omitted (never 0, never guessed).102  * Units are converted to SI; the string exactly as published is kept in "published".103  * When two sources give the same quantity the primary record is JPL SSD for mass / GM / radii / density /104    geometric albedo and NSSDCA otherwise; the other records are kept under "alternates".105  * "status": observed = a value the source publishes as a measurement or adopted constant; computed = the source106    says it derived the value from other values (JPL "[*]", unit conversions of a diameter, synchronous rotation);107    estimated = the source marks it approximate ("~", "rough estimate", upper limits).108The script ends with a self-check and exits non-zero when it fails."""109import datetime110import html111import json112import math113import os114import re115import sys116117AU = 149_597_870_700.0          # m, IAU 2012 (exact)118DAY = 86_400.0                  # s119JULIAN_YEAR = 365.25 * DAY      # s120DEG = math.pi / 180.0121122P_NSSDCA = "nssdca-planetary-fact-sheets"123P_JPL_PLANETS = "jpl-ssd-planets-phys-par"124P_JPL_SATS = "jpl-ssd-sats-phys-par"125P_SBDB = "jpl-sbdb"126P_RMS = "pds-rms-ring-tables"127128# Which source wins when several give the same key (see module docstring).129JPL_PRIMARY_KEYS = {"mass", "gm", "meanRadius", "equatorialRadius", "meanDensity", "geometricAlbedo"}130SOURCE_RANK_JPL = [P_JPL_PLANETS, P_JPL_SATS, P_SBDB, P_NSSDCA]131SOURCE_RANK_NSSDCA = [P_NSSDCA, P_JPL_PLANETS, P_JPL_SATS, P_SBDB]132SOURCE_RANK_SBDB_ORBIT = [P_SBDB, P_JPL_PLANETS, P_JPL_SATS, P_NSSDCA]133ORBIT_KEYS = {"semiMajorAxis", "eccentricity", "inclination", "siderealOrbitPeriod"}134135136# ----------------------------------------------------------------------------------------------- text helpers137138def read(raw, name):139    with open(os.path.join(raw, name), encoding="utf-8", errors="replace") as f:140        return f.read()141142143def clean(fragment):144    """HTML fragment -> one line of text; <sup>x</sup> becomes ^x so that 10<sup>24</sup> reads 10^24."""145    t = re.sub(r"<(script|style).*?</\1>", "", fragment, flags=re.S | re.I)146    t = re.sub(r"<sup>\s*(.*?)\s*</sup>", r"^\1", t, flags=re.S | re.I)147    t = re.sub(r"<sub>\s*(.*?)\s*</sub>", r"\1", t, flags=re.S | re.I)148    t = html.unescape(re.sub(r"<[^>]+>", " ", t)).replace(" ", " ")149    return re.sub(r"\s+", " ", t).strip()150151152def table_rows(page):153    """All table rows of a page as lists of cell strings. Cells are split on the opening tag because some154    JPL rows do not close their <td>."""155    rows = []156    for tr in re.findall(r"<tr\b[^>]*>(.*?)(?=<tr\b|</table>|</tbody>|$)", page, flags=re.S | re.I):157        cells = re.split(r"<t[dh]\b[^>]*>", tr, flags=re.I)[1:]158        rows.append([clean(c) for c in cells])159    return rows160161162def text_lines(page):163    t = re.sub(r"<(script|style).*?</\1>", "", page, flags=re.S | re.I)164    t = re.sub(r"<sup>\s*(.*?)\s*</sup>", r"^\1", t, flags=re.S | re.I)165    t = re.sub(r"</tr>|<br ?/?>|</p>|</h\d>|</li>|</div>", "\n", t, flags=re.I)166    t = html.unescape(re.sub(r"<[^>]+>", "", t)).replace(" ", " ")167    return [re.sub(r"[ \t]+", " ", l).strip() for l in t.split("\n") if l.strip()]168169170NUM = r"[-+]?(?:\d[\d,]*\.?\d*|\.\d+)"171172173def number(s):174    """Parses '1,988,400.', '3 x 10^-6', '10^-5', '5x10^-6', '4.95x10^15', '662.2e-9'. Returns None when no number."""175    s = s.strip().replace("−", "-").replace("×", "x")176    m = re.fullmatch(r"(%s)\s*x\s*10\^?\s*([-+]?\d+)" % NUM, s)177    if m:178        return float(m.group(1).replace(",", "")) * 10.0 ** int(m.group(2))179    m = re.fullmatch(r"10\^\s*([-+]?\d+)", s)180    if m:181        return 10.0 ** int(m.group(1))182    m = re.fullmatch(r"(%s)(?:[eE]([-+]?\d+))?" % NUM, s)183    if m:184        v = float(m.group(1).replace(",", ""))185        return v * 10.0 ** int(m.group(2)) if m.group(2) else v186    return None187188189def last_updated(page):190    m = re.search(r"Last Updated:\s*([0-9]{1,2} [A-Za-z]+ [0-9]{4})", clean(page))191    if not m:192        return None193    return datetime.datetime.strptime(m.group(1), "%d %B %Y").strftime("%Y-%m-%d")194195196def rec(value, unit, published, provenance, status="observed", uncertainty=None, citation=None, note=None, **extra):197    r = {"value": value, "unit": unit}198    if uncertainty is not None:199        r["uncertainty"] = uncertainty200    r["status"] = status201    r["provenance"] = provenance202    if citation:203        r["citation"] = citation204    r["published"] = published205    if note:206        r["note"] = note207    r.update({k: v for k, v in extra.items() if v is not None})208    return r209210211class Bodies:212    """Collects every record per body and key, then picks the primary one."""213214    def __init__(self):215        self.meta = {}216        self.records = {}217        self.extra = {}218219    def define(self, oid, name, kind, parent, sbdb=False):220        self.meta[oid] = {"name": name, "kind": kind, "parent": parent, "sbdb": sbdb}221        self.records.setdefault(oid, {})222        self.extra.setdefault(oid, {})223224    def add(self, oid, key, record):225        self.records[oid].setdefault(key, []).append(record)226227    def set_extra(self, oid, key, value):228        self.extra[oid][key] = value229230    def export(self):231        out = {}232        for oid, meta in self.meta.items():233            props, alts = {}, {}234            for key, recs in self.records[oid].items():235                rank = SOURCE_RANK_JPL if key in JPL_PRIMARY_KEYS else SOURCE_RANK_NSSDCA236                if meta["sbdb"]:237                    # Small bodies: current SBDB orbit solution first for the orbit, JPL tables first for the rest238                    # (the NSSDCA asteroid/comet sheets are dated 2016 and rounded).239                    rank = SOURCE_RANK_SBDB_ORBIT if key in ORBIT_KEYS else SOURCE_RANK_JPL240                for r in recs:241                    if r.get("note", "").startswith("negative = retrograde") and r["value"] >= 0:242                        del r["note"]243                ordered = sorted(enumerate(recs), key=lambda ir: (rank.index(ir[1]["provenance"]), ir[0]))244                props[key] = ordered[0][1]245                if len(ordered) > 1:246                    alts[key] = [r for _, r in ordered[1:]]247            body = {"name": meta["name"], "kind": meta["kind"]}248            if meta["parent"]:249                body["parent"] = meta["parent"]250            body["properties"] = dict(sorted(props.items()))251            if alts:252                body["alternates"] = dict(sorted(alts.items()))253            body.update(self.extra[oid])254            out[oid] = body255        return out256257258# ----------------------------------------------------------------------------------------------- NSSDCA planets259260SPECIES_FIX = {"4He": "He-4", "20Ne": "Ne-20", "22Ne": "Ne-22", "40Ar": "Ar-40", "36Ar": "Ar-36"}261262# label regex -> (key, factor to SI, SI unit, note)263NSSDCA_ROWS = [264    (r"^Mass \(10\^24 kg\)", "mass", 1e24, "kg", None),265    (r"^GM \(x 10\^6 km\^3/s\^2\)", "gm", 1e15, "m^3/s^2", None),266    (r"^Equatorial radius( \(1 bar level\))? \(km\)", "equatorialRadius", 1e3, "m", None),267    (r"^Volumetric mean radius \(km\)", "meanRadius", 1e3, "m", None),268    (r"^Mean density \(kg/m\^3\)", "meanDensity", 1.0, "kg/m^3", None),269    (r"^(Surface )?[Gg]ravity \((mean|eq\.)(, 1 bar)?\) \(m/s\^2\)|^Surface gravity \(m/s\^2\)", "surfaceGravity", 1.0, "m/s^2", "LABEL"),270    (r"^Escape velocity \(km/s\)", "escapeVelocity", 1e3, "m/s", None),271    (r"^Bond albedo", "bondAlbedo", 1.0, "1", None),272    (r"^Geometric albedo", "geometricAlbedo", 1.0, "1", None),273    (r"^(V-band|Visual) magnitude V\(1,0\)", "visualMagnitudeV0", 1.0, "mag", None),274    (r"^Black-body temperature \(K\)", "blackBodyTemperature", 1.0, "K", None),275    (r"^Luminosity \(10\^24 J/s\)", "luminosity", 1e24, "W", None),276    (r"^Semimajor axis \(10\^6 km\)", "semiMajorAxis", 1e9, "m", None),277    (r"^(Sidereal orbit|Revolution) period \(days\)", "siderealOrbitPeriod", DAY, "s", None),278    (r"^Orbit inclination \(deg\)", "inclination", DEG, "rad", "inclination of the orbit to the ecliptic (fact-sheet notes)"),279    (r"^Inclination to ecliptic \(deg\)", "inclination", DEG, "rad", "inclination of the orbit to the ecliptic"),280    (r"^Orbit eccentricity", "eccentricity", 1.0, "1", None),281    (r"^Sidereal rotation period \(hrs\)", "siderealRotationPeriod", 3600.0, "s", "negative = retrograde rotation, as published"),282    (r"^Obliquity to orbit \(deg\)", "obliquity", DEG, "rad", "obliquity to orbit"),283    (r"^Obliquity to ecliptic \(deg\.?\)", "obliquity", DEG, "rad", "published as obliquity to the ecliptic (not to an orbit)"),284]285286287def parse_composition(lines, start):288    """Reads the 'Major' / 'Minor (ppm)' block that follows an 'Atmospheric composition' heading."""289    block, published = [], []290    for l in lines[start:start + 9]:291        if re.match(r"(Aerosols|Numbers do not|Water is highly|Note that|Notes on|Satellites of|The Moon|\(The atmosphere|Composition of|Author|Charon)", l):292            break293        block.append(l)294        published.append(l)295    text = " ".join(block)296    head, _, rest = text.partition(":")297    # Split major / minor parts.298    m = re.search(r"Minor \(ppm\)\s*:", rest)299    major = rest[:m.start()] if m else rest300    minor = rest[m.end():] if m else ""301    major = re.sub(r"^\s*Major\s*:", "", major.strip())302    out = []303304    def add(species, fraction, published_text, uncertainty=None, minor_flag=False):305        e = {"species": SPECIES_FIX.get(species, species), "fraction": fraction, "published": published_text.strip()}306        if uncertainty is not None:307            e["uncertainty"] = uncertainty308        if minor_flag:309            e["minor"] = True310        out.append(e)311312    # "78.08% Nitrogen (N2)"  or  "Carbon Dioxide (CO2) - 95.1%"  or  "Methane (CH4) 1.5% (0.5%)"313    pat_a = re.compile(r"(%s)%%\s+[A-Za-z ]+?\((\w+)\)" % NUM)314    pat_b = re.compile(r"[A-Za-z ]+?\((\w+)\)\s*-?\s*(%s)%%(?:\s*\((%s)%%\))?" % (NUM, NUM))315    found_a = list(pat_a.finditer(major))316    # Percent-first lists ("78.08% Nitrogen (N2)") start with a number; name-first lists do not.317    if found_a and re.match(r"\s*\d", major):318        for m2 in found_a:319            add(m2.group(2), number(m2.group(1)) / 100.0, m2.group(0))320    else:321        for m2 in pat_b.finditer(major):322            unc = number(m2.group(3)) / 100.0 if m2.group(3) else None323            add(m2.group(1), number(m2.group(2)) / 100.0, m2.group(0), unc)324    # Minor constituents in ppm: "Argon (Ar) - 9340" / "CH4 - 1.94" / "Methane (CH4) - 3000 (1000)"325    for m2 in re.finditer(r"(?:\((\w+)\)|(?<![\w(])([A-Z][A-Za-z]*\d))\s*-\s*(%s)(?:\s*\((%s)\))?" % (NUM, NUM), minor):326        species = m2.group(1) or m2.group(2)327        unc = number(m2.group(4)) * 1e-6 if m2.group(4) else None328        add(species, number(m2.group(3)) * 1e-6, m2.group(0) + " ppm", unc, True)329    return re.sub(r"\s*Major$", "", head.strip()), out, " | ".join(published)330331332def parse_nssdca_planet(B, raw, oid, fname, column_name, giant=False):333    page = read(raw, fname)334    updated = last_updated(page)335    title = clean(re.search(r"<title>(.*?)</title>", page, re.S | re.I).group(1))336    cite = "NSSDCA %s (D. R. Williams, NASA GSFC), last updated %s" % (title, updated)337    rows = table_rows(page)338    if not any(r and r[0].startswith("Mass") for r in rows):339        # The Earth sheet is a preformatted text block ("label   value" per line), not an HTML table.340        rows = [l.rsplit(" ", 1) for l in text_lines(page) if " " in l]341    seen = set()342    for row in rows:343        if len(row) < 2:344            continue345        label, cell = row[0], row[1]346        for pattern, key, factor, unit, note in NSSDCA_ROWS:347            if not re.search(pattern, label) or (key, pattern) in seen:348                continue349            seen.add((key, pattern))350            v = number(cell)351            if v is None:352                continue353            if note == "LABEL":354                note = "published as '%s'" % label355                if "1 bar" in label or giant:356                    note += " (at the 1 bar level)"357            if key == "semiMajorAxis" and oid == "naif:301":358                note = "geocentric orbit"359            if key == "siderealRotationPeriod" and oid == "naif:10":360                note = "adopted period at 16 deg latitude; the rotation rate varies with latitude (source footnote)"361            B.add(oid, key, rec(v * factor, unit, "%s = %s" % (label, cell), P_NSSDCA, citation=cite, note=note))362        if re.match(r"Number of natural satellites", label):363            v = number(cell)364            if v is not None:365                B.set_extra(oid, "moonCount", {366                    "value": int(v), "asOf": updated,367                    "asOfBasis": "'Last Updated' date printed on the source page (the page does not date the count itself)",368                    "provenance": P_NSSDCA, "citation": cite, "published": "%s = %s" % (label, cell)})369        if re.match(r"Planetary ring system", label):370            B.set_extra(oid, "hasRingSystemPublished", cell.strip().lower() == "yes")371    # Free-text atmosphere block.372    lines = text_lines(page)373    ranges = {}374    for i, l in enumerate(lines):375        m = re.match(r"Surface [Pp]ressure(?: \(night\))?:\s*(.*)", l)376        if m:377            txt = m.group(1)378            m2 = re.match(r"(<~|~|<)?\s*(%s(?:\s*x\s*10\^-?\d+)?)\s*(mb|bars?|microbar)\b" % NUM, txt)379            if m2 and not txt.startswith(">>"):380                scale = {"mb": 100.0, "bar": 1e5, "bars": 1e5, "microbar": 0.1}[m2.group(3)]381                approx = m2.group(1) or ""382                note = l.split(":")[0]383                extra = {}384                if "<" in approx:385                    extra["limit"] = "upper"386                    note += "; published as an upper limit"387                B.add(oid, "surfacePressure", rec(number(m2.group(2)) * scale, "Pa", l, P_NSSDCA,388                                                  status="estimated" if approx else "observed", citation=cite, note=note, **extra))389            elif txt.startswith(">>"):390                B.set_extra(oid, "surfacePressureNote", "No surface: the source publishes '%s'." % l)391        m = re.match(r"(Average temperature|Temperature at 1 bar|Effective temperature):\s*(~)?\s*(%s) K" % NUM, l)392        if m:393            key = "effectiveTemperature" if m.group(1).startswith("Effective") else "meanSurfaceTemperature"394            note = {"Average temperature": "average temperature (mean over the entire surface, fact-sheet notes)",395                    "Temperature at 1 bar": "temperature at the 1 bar level (no solid surface)",396                    "Effective temperature": "effective temperature of the photosphere"}[m.group(1)]397            B.add(oid, key, rec(number(m.group(3)), "K", l, P_NSSDCA, status="estimated" if m.group(2) else "observed",398                                citation=cite, note=note))399        m = re.match(r"(Diurnal temperature range(?: \(equator\))?|Surface temperature):\s*~?(%s)\s*K?\s*(?:to|-)\s*(%s) K" % (NUM, NUM), l)400        if m:401            ranges["surfaceTemperature"] = {"min": number(m.group(2)), "max": number(m.group(3)), "unit": "K",402                                            "provenance": P_NSSDCA, "citation": cite, "published": l,403                                            "note": m.group(1)}404        m = re.match(r"Scale height:\s*~?(%s) km$" % NUM, l)405        if m:406            B.add(oid, "atmosphereScaleHeight", rec(number(m.group(1)) * 1e3, "m", l, P_NSSDCA, citation=cite,407                                                    note="pressure scale height as published"))408        m = re.match(r"Mean molecular weight:\s*~?(%s)$" % NUM, l)409        if m:410            B.add(oid, "meanMolecularWeight", rec(number(m.group(1)) * 1e-3, "kg/mol", l, P_NSSDCA, citation=cite))411        if re.match(r"(Atmospheric composition|Photosphere Composition)", l):412            if "Column abundances" in l:413                B.set_extra(oid, "atmosphere", {"constituents": [], "published": " | ".join(lines[i:i + 5]), "provenance": P_NSSDCA,414                                                "citation": cite,415                                                "note": "Surface-bounded exosphere; the source gives column abundances, not volume fractions, so no fraction is stored."})416                continue417            text = l418            start = i419            if oid == "naif:10":420                # "Major elements: H - 90.965%, He - 8.889%"421                nxt = lines[i + 1]422                cons = [{"species": s, "fraction": number(v) / 100.0, "published": "%s - %s%%" % (s, v)}423                        for s, v in re.findall(r"\b([A-Z][a-z]?) - (%s)%%" % NUM, nxt)]424                B.set_extra(oid, "atmosphere", {"constituents": cons, "published": l + " | " + nxt, "provenance": P_NSSDCA,425                                                "citation": cite, "basis": "photosphere composition, major elements (by number, as published)"})426                continue427            if oid == "naif:999":428                lines_for = [l.replace("Atmospheric composition:", "Atmospheric composition: Major:")]429                head, cons, published = parse_composition(lines_for, 0)430                published = l431            else:432                head, cons, published = parse_composition(lines, start)433            if cons:434                B.set_extra(oid, "atmosphere", {"constituents": cons, "published": published, "provenance": P_NSSDCA,435                                                "citation": cite, "basis": head})436    if ranges:437        B.set_extra(oid, "ranges", ranges)438    return page, lines, cite439440441# ----------------------------------------------------------------------------------------------- NSSDCA satellites442443def sat_name(cell):444    return re.sub(r"\s*\(.*", "", cell).strip()445446447def parse_nssdca_sat_sheet(B, raw, fname, wanted, planet_name):448    """wanted: {satellite name: object id}. Bulk row: name | mass 10^20 kg | radius km | density | albedo.449    Orbital row: name | a 10^3 km | a (planet radii) | period d (R = retrograde) | rotation d or S | incl deg | ecc."""450    page = read(raw, fname)451    updated = last_updated(page)452    cite = "NSSDCA %s Satellite Fact Sheet (D. R. Williams, NASA GSFC), last updated %s" % (planet_name, updated)453    rows = table_rows(page)454    # The page holds two tables in order (bulk, orbital); the first occurrence of a name is the bulk row.455    seen = {}456    for row in rows:457        if not row:458            continue459        name = sat_name(row[0])460        if name not in wanted:461            continue462        oid = wanted[name]463        occurrence = seen.get(name, 0)464        seen[name] = occurrence + 1465        cells = row[1:]466        if occurrence == 0 and len(cells) >= 4:467            v = number(cells[0])468            if v is not None:469                B.add(oid, "mass", rec(v * 1e20, "kg", "Mass (10^20 kg) = %s" % cells[0], P_NSSDCA, citation=cite))470            v = number(cells[1])471            if v is not None:472                B.add(oid, "meanRadius", rec(v * 1e3, "m", "Radius (km) = %s" % cells[1], P_NSSDCA, citation=cite,473                                             note="published as a single radius"))474            elif "x" in cells[1]:475                B.set_extra(oid, "triaxialRadiiPublished", {"published": "Radius (km) = %s" % cells[1],476                                                            "semiAxes": [number(x) * 1e3 for x in cells[1].split("x")],477                                                            "unit": "m", "provenance": P_NSSDCA, "citation": cite})478            v = number(cells[2])479            if v is not None:480                B.add(oid, "meanDensity", rec(v, "kg/m^3", "Mean density (kg/m^3) = %s" % cells[2], P_NSSDCA, citation=cite))481            v = number(cells[3])482            if v is not None:483                B.add(oid, "geometricAlbedo", rec(v, "1", "Visual geometric albedo = %s" % cells[3], P_NSSDCA, citation=cite))484            elif cells[3].strip():485                B.set_extra(oid, "geometricAlbedoNote", "Source publishes two values (leading / trailing hemisphere): %s" % cells[3])486        elif occurrence == 1 and len(cells) >= 6:487            a = number(cells[0])488            if a is not None:489                B.add(oid, "semiMajorAxis", rec(a * 1e6, "m", "Semi-major axis (10^3 km) = %s" % cells[0], P_NSSDCA, citation=cite,490                                                note="orbit about %s" % {"Jovian": "Jupiter", "Saturnian": "Saturn", "Uranian": "Uranus", "Neptunian": "Neptune"}[planet_name]))491            retro = cells[2].strip().endswith("R")492            period = number(cells[2].strip().rstrip("R"))493            if period is not None:494                B.add(oid, "siderealOrbitPeriod", rec(period * DAY, "s", "Orbital period (days) = %s" % cells[2], P_NSSDCA, citation=cite,495                                                      note="R = retrograde orbit as published" if retro else None))496            rot = cells[3].strip()497            if rot == "S" and period is not None:498                sign = -1.0 if retro else 1.0499                note = "source publishes 'S' (synchronous rotation: same as the orbital period)"500                if retro:501                    note += "; negative because the orbit is published as retrograde (R)"502                B.add(oid, "siderealRotationPeriod", rec(sign * period * DAY, "s", "Rotation period = S; orbital period (days) = %s" % cells[2],503                                                         P_NSSDCA, status="computed", citation=cite, note=note))504            elif number(rot) is not None:505                B.add(oid, "siderealRotationPeriod", rec(number(rot) * DAY, "s", "Rotation period (days) = %s" % rot, P_NSSDCA, citation=cite))506            elif rot == "C":507                B.set_extra(oid, "rotationNote", "Source publishes 'C' (chaotic rotation): no rotation period.")508            v = number(cells[4])509            if v is not None:510                B.add(oid, "inclination", rec(v * DEG, "rad", "Inclination (degrees) = %s" % cells[4], P_NSSDCA, citation=cite,511                                              note="to the planet's equator (fact-sheet notes: 'For satellites, this is with respect to the planet's equator')"))512            v = number(cells[5])513            if v is not None:514                B.add(oid, "eccentricity", rec(v, "1", "Eccentricity = %s" % cells[5], P_NSSDCA, citation=cite,515                                               note="forced eccentricity for the Galilean satellites (fact-sheet notes)" if planet_name == "Jovian" else None))516    missing = [n for n in wanted if seen.get(n, 0) < 2]517    if missing:518        raise SystemExit("%s: satellites not found in both tables: %s" % (fname, missing))519520521def parse_mars_sats(B, page, cite):522    rows = table_rows(page)523    start = next(i for i, r in enumerate(rows) if len(r) >= 2 and r[0].startswith("Phobos") and r[1].startswith("Deimos") or524                 (len(r) >= 3 and r[1].startswith("Phobos")))525    cite = cite + ", table 'Satellites of Mars'"526    table = {527        r"^Semimajor axis\* \(km\)": ("semiMajorAxis", 1e3, "m", "mean orbital distance from the centre of Mars"),528        r"^Sidereal orbit period \(days\)": ("siderealOrbitPeriod", DAY, "s", None),529        r"^Sidereal rotation period \(days\)": ("siderealRotationPeriod", DAY, "s", None),530        r"^Orbital inclination \(deg\)": ("inclination", DEG, "rad", "to the planet's equator (fact-sheet notes)"),531        r"^Orbital eccentricity": ("eccentricity", 1.0, "1", None),532        r"^Mass \(10\^15 kg\)": ("mass", 1e15, "kg", None),533        r"^Mean density \(kg/m\^3\)": ("meanDensity", 1.0, "kg/m^3", None),534        r"^Geometric albedo": ("geometricAlbedo", 1.0, "1", None),535        r"^Visual magnitude V\(1,0\)": ("visualMagnitudeV0", 1.0, "mag", None),536    }537    for row in rows[start + 1:]:538        if len(row) < 3:539            continue540        for pattern, (key, factor, unit, note) in table.items():541            if re.search(pattern, row[0]):542                for oid, cell in (("naif:401", row[1]), ("naif:402", row[2])):543                    v = number(cell)544                    if v is not None:545                        B.add(oid, key, rec(v * factor, unit, "%s = %s" % (row[0], cell), P_NSSDCA, citation=cite, note=note))546547548def parse_charon(B, lines, cite):549    cite = cite + ", section 'Charon (P1)'"550    i = lines.index("Charon (P1)")551    table = {552        r"^Mean distance from Pluto \(km\)": ("semiMajorAxis", 1e3, "m", "mean distance from Pluto"),553        r"^Sidereal orbit period \(days\)": ("siderealOrbitPeriod", DAY, "s", None),554        r"^Sidereal rotation period \(days\)": ("siderealRotationPeriod", DAY, "s", None),555        r"^Orbital inclination to Pluto \(deg\)": ("inclination", DEG, "rad", "orbital inclination to Pluto (as published)"),556        r"^Orbital eccentricity": ("eccentricity", 1.0, "1", None),557        r"^Equatorial radius \(km\)": ("equatorialRadius", 1e3, "m", None),558        r"^Mass \(10\^21 kg\)": ("mass", 1e21, "kg", None),559        r"^Mean density \(kg/m\^3\)": ("meanDensity", 1.0, "kg/m^3", None),560        r"^Surface gravity \(m/s\^2\)": ("surfaceGravity", 1.0, "m/s^2", "published as 'Surface gravity'"),561        r"^Escape velocity \(km/s\)": ("escapeVelocity", 1e3, "m/s", None),562        r"^Geometric Albedo": ("geometricAlbedo", 1.0, "1", None),563        r"^Bond Albedo": ("bondAlbedo", 1.0, "1", None),564    }565    for l in lines[i + 1:i + 16]:566        for pattern, (key, factor, unit, note) in table.items():567            m = re.match(pattern + r"\s+(%s)$" % NUM, l)568            if m:569                B.add("naif:901", key, rec(number(m.group(1)) * factor, unit, l, P_NSSDCA, citation=cite, note=note))570571572def parse_small_worlds(B, raw):573    """'Solar System Small Worlds Fact Sheet': one column per body; used for mean temperature, gravity and escape574    velocity of the large moons (the per-planet satellite sheets do not give them)."""575    page = read(raw, "nssdca_galileanfact_table.html")576    cite = "NSSDCA Solar System Small Worlds Fact Sheet (D. R. Williams, NASA GSFC), last updated %s" % last_updated(page)577    rows = table_rows(page)578    header = next(r for r in rows if len(r) > 5 and "CALLISTO" in r[1])579    cols = {"CALLISTO": "naif:504", "GANYMEDE": "naif:503", "EUROPA": "naif:502", "IO": "naif:501", "MOON": "naif:301",580            "MERCURY": "naif:199", "PLUTO": "naif:999", "TITAN": "naif:606", "TRITON": "naif:801", "CERES": "naif:20000001"}581    table = {582        "Gravity (m/s^2)": ("surfaceGravity", lambda v: v, "m/s^2", "published as 'Gravity'"),583        "Escape Velocity (km/s)": ("escapeVelocity", lambda v: v * 1e3, "m/s", None),584        "Mean Temperature (C)": ("meanSurfaceTemperature", lambda v: v + 273.15, "K", "mean temperature, published in degrees Celsius"),585        "Rotation Period (hours)": ("siderealRotationPeriod", lambda v: v * 3600.0, "s", "negative = retrograde rotation, as published"),586        "Density (kg/m^3)": ("meanDensity", lambda v: v, "kg/m^3", None),587        "Mass (10^21kg)": ("mass", lambda v: v * 1e21, "kg", None),588    }589    for row in rows:590        if not row or row[0] not in table:591            continue592        key, conv, unit, note = table[row[0]]593        for j, head in enumerate(header):594            oid = cols.get(head.strip())595            if oid is None or j >= len(row):596                continue597            v = number(row[j])598            if v is None:599                continue600            # The sheet rounds heavily; it is the only NSSDCA source for these three keys on moons.601            if key == "meanSurfaceTemperature" and oid == "naif:999":602                # The 2016 sheet prints -225 C for Pluto, outside the 24 - 38 K surface range of the current Pluto603                # sheet: not stored as a property (the range is kept under "ranges").604                B.set_extra(oid, "meanSurfaceTemperatureNote",605                            "%s prints 'Mean Temperature (C) = %s' for Pluto, inconsistent with the 24 - 38 K surface range of the Pluto fact sheet; not stored." % (cite, row[j]))606                continue607            if key in ("siderealRotationPeriod", "meanDensity", "mass") and oid not in ("naif:20000001",):608                if key != "siderealRotationPeriod" or oid not in ("naif:801",):609                    continue610            B.add(oid, key, rec(conv(v), unit, "%s = %s (%s)" % (row[0], row[j], head.strip()), P_NSSDCA, citation=cite, note=note))611612613def parse_asteroids(B, raw):614    page = read(raw, "nssdca_asteroidfact.html")615    cite = "NSSDCA Asteroid Fact Sheet (D. R. Williams, NASA GSFC), last updated %s; orbit values for epoch JD 2457400.5" % last_updated(page)616    wanted = {"Ceres": "naif:20000001", "Vesta": "naif:20000004", "Eros": "naif:20000433"}617    for row in table_rows(page):618        if len(row) < 10 or row[1].strip() not in wanted:619            continue620        oid = wanted[row[1].strip()]621        dia, mass, rot, per, _cls, a, e, inc = row[2:10]622        v = number(dia)623        if v is not None:624            B.add(oid, "meanRadius", rec(v * 500.0, "m", "Diameter (km) = %s" % dia, P_NSSDCA, status="computed", citation=cite,625                                         note="half of the published diameter"))626        elif "x" in dia:627            B.set_extra(oid, "triaxialDiametersPublished", {"published": "Diameter (km) = %s" % dia, "provenance": P_NSSDCA, "citation": cite})628        v = number(mass)629        if v is not None:630            B.add(oid, "mass", rec(v * 1e15, "kg", "~Mass (10^15 kg) = %s" % mass, P_NSSDCA, status="estimated", citation=cite,631                                   note="the sheet states that most masses are only rough estimates"))632        m = re.match(r"(%s)\s*hrs" % NUM, rot)633        if m:634            B.add(oid, "siderealRotationPeriod", rec(number(m.group(1)) * 3600.0, "s", "Rotation period = %s" % rot, P_NSSDCA, citation=cite))635        m = re.match(r"(%s)\s*yrs" % NUM, per)636        if m:637            B.add(oid, "siderealOrbitPeriod", rec(number(m.group(1)) * JULIAN_YEAR, "s", "Orbital period = %s" % per, P_NSSDCA, citation=cite,638                                                  note="published in years; converted with the Julian year (365.25 d)"))639        m = re.match(r"(%s)\s*AU" % NUM, a)640        if m:641            B.add(oid, "semiMajorAxis", rec(number(m.group(1)) * AU, "m", "Semi-major axis = %s" % a, P_NSSDCA, citation=cite))642        if number(e) is not None:643            B.add(oid, "eccentricity", rec(number(e), "1", "Orbital eccentricity = %s" % e, P_NSSDCA, citation=cite))644        m = re.match(r"(%s)\s*deg" % NUM, inc)645        if m:646            B.add(oid, "inclination", rec(number(m.group(1)) * DEG, "rad", "Orbital inclination = %s" % inc, P_NSSDCA, citation=cite,647                                          note="to the ecliptic"))648649650def parse_comets(B, raw):651    page = read(raw, "nssdca_cometfact.html")652    cite = "NSSDCA Comet Fact Sheet (D. R. Williams, NASA GSFC), last updated %s" % last_updated(page)653    wanted = {"Halley": "naif:1000036", "Churyumov-Gerasimenko": "naif:1000012"}654    for row in table_rows(page):655        if len(row) < 8 or row[1].strip() not in wanted:656            continue657        oid = wanted[row[1].strip()]658        per, _date, _q, a, e, inc = row[2:8]659        m = re.match(r"~?(%s)\s*yrs" % NUM, per)660        if m:661            B.add(oid, "siderealOrbitPeriod", rec(number(m.group(1)) * JULIAN_YEAR, "s", "Orbital period = %s" % per, P_NSSDCA, citation=cite,662                                                  note="published in years; converted with the Julian year (365.25 d)"))663        m = re.match(r"~?(%s)\s*AU" % NUM, a)664        if m:665            B.add(oid, "semiMajorAxis", rec(number(m.group(1)) * AU, "m", "Semi-major axis = %s" % a, P_NSSDCA, citation=cite))666        if number(e) is not None:667            B.add(oid, "eccentricity", rec(number(e), "1", "Orbital eccentricity = %s" % e, P_NSSDCA, citation=cite))668        m = re.match(r"(%s)\s*deg" % NUM, inc)669        if m:670            B.add(oid, "inclination", rec(number(m.group(1)) * DEG, "rad", "Orbital inclination = %s" % inc, P_NSSDCA, citation=cite,671                                          note="to the ecliptic"))672673674# ----------------------------------------------------------------------------------------------- JPL SSD675676def parse_jpl_planets(B, raw, ids):677    page = read(raw, "jpl_planets_phys_par.html")678    # Reference letters: "[B]" followed by the reference text.679    refs = {}680    tail = page[page.find("References"):]681    for m in re.finditer(r"\[\s*(?:<[^>]+>\s*)*([A-Z*])\s*(?:<[^>]+>\s*)*\]\s*(?:</[^>]+>\s*)*(.*?)(?=<(?:dt|tr|li|p)\b|\Z)", tail, flags=re.S):682        text = clean(m.group(2))683        if text and m.group(1) not in refs:684            refs[m.group(1)] = text685    cols = [("equatorialRadius", 1e3, "m", "Equatorial Radius (km)", None),686            ("meanRadius", 1e3, "m", "Mean Radius (km)", "radius of a sphere with the equivalent volume"),687            ("mass", None, "kg", None, None),688            ("meanDensity", 1e3, "kg/m^3", "Bulk Density (g cm^-3)", None),689            ("siderealRotationPeriod", DAY, "s", "Sidereal Rotation Period (d)", "negative = retrograde rotation, as published"),690            ("siderealOrbitPeriod", JULIAN_YEAR, "s", "Sidereal Orbital Period (y)", "published in years; converted with the Julian year (365.25 d)"),691            ("visualMagnitudeV0", 1.0, "mag", "V(1,0) (mag)", None),692            ("geometricAlbedo", 1.0, "1", "Geometric Albedo", None),693            ("surfaceGravity", 1.0, "m/s^2", "Equatorial Gravity (m s^-2)", "published as 'Equatorial Gravity'"),694            ("escapeVelocity", 1e3, "m/s", "Escape Velocity (km s^-1)", None)]695    mass_factor, mass_label = None, None696    found = set()697    for row in table_rows(page):698        if len(row) >= 4 and re.search(r"\(×10\^(\d+) kg\)", " ".join(row)):699            exp = int(re.search(r"\(×10\^(\d+) kg\)", " ".join(row)).group(1))700            mass_factor, mass_label = 10.0 ** exp, "Mass (×10^%d kg)" % exp701            continue702        if not row or row[0] not in ids or len(row) < 11:703            continue704        oid = ids[row[0]]705        found.add(row[0])706        for (key, factor, unit, label, note), cell in zip(cols, row[1:11]):707            if key == "mass":708                factor, label = mass_factor, mass_label709            m = re.match(r"(%s)\s*\[\s*([A-Z*])\s*\](?:\s*±\s*(%s))?" % (NUM, NUM), cell)710            if not m:711                continue712            v = number(m.group(1))713            unc = number(m.group(3)) * factor if m.group(3) else None714            letter = m.group(2)715            status = "computed" if letter == "*" else "observed"716            B.add(oid, key, rec(v * factor, unit, "%s = %s" % (label, cell), P_JPL_PLANETS, status=status, uncertainty=unc,717                                citation="[%s] %s" % (letter, refs.get(letter, "")), note=note))718    missing = set(ids) - found719    if missing:720        raise SystemExit("jpl_planets_phys_par.html: rows not found: %s" % sorted(missing))721722723def parse_jpl_sats(B, raw, ids):724    page = read(raw, "jpl_sats_phys_par.html")725    # Ephemeris reference modals: <div class="modal" id="JUP365"> ... <b>Reference:</b> text</li>726    eph_refs = {}727    for m in re.finditer(r'<div class="modal" id="([A-Z0-9]+)".*?<b>Reference:</b>(.*?)</li>', page, flags=re.S):728        eph_refs[m.group(1)] = clean(m.group(2))729    radius_refs = []730    m = re.search(r"Mean Radius References.*?<ol[^>]*>(.*?)</ol>", page, flags=re.S)731    if m:732        radius_refs = [clean(x) for x in re.findall(r"<li>(.*?)</li>", m.group(1), flags=re.S)]733    found = set()734    for row in table_rows(page):735        if len(row) < 12 or not row[2].isdigit():736            continue737        code = int(row[2])738        if code not in ids:739            continue740        oid = ids[code]741        found.add(code)742        gm, gms, gmref, rad, rads, radref, den, dens, denref = row[3:12]743        if number(gm) == 0 and number(gms) == 0:744            # Placeholder row ("0.00000 ± 0.00000"): the table holds no GM for this satellite.745            B.set_extra(oid, "gmNote", "JPL SSD lists GM = %s ± %s [%s] (placeholder, no determination): not stored." % (gm, gms, gmref.strip()))746        elif number(gm) is not None:747            ref = gmref.strip()748            cit = "%s: %s" % (ref, eph_refs[ref]) if ref in eph_refs else ("JPL planetary ephemeris %s" % ref if ref else None)749            B.add(oid, "gm", rec(number(gm) * 1e9, "m^3/s^2", "GM (km^3/s^2) = %s ± %s [%s]" % (gm, gms, ref), P_JPL_SATS,750                                 uncertainty=number(gms) * 1e9 if number(gms) is not None else None, citation=cit))751        if number(rad) is not None:752            ref = radref.strip()753            cit = "[%s] %s" % (ref, radius_refs[int(ref) - 1]) if ref.isdigit() and int(ref) <= len(radius_refs) else None754            B.add(oid, "meanRadius", rec(number(rad) * 1e3, "m", "Mean Radius (km) = %s ± %s [%s]" % (rad, rads, ref), P_JPL_SATS,755                                         uncertainty=number(rads) * 1e3 if number(rads) is not None else None, citation=cit,756                                         note="radius of a sphere with the equivalent volume"))757        if number(den) is not None:758            star = denref.strip() == "*"759            B.add(oid, "meanDensity", rec(number(den) * 1e3, "kg/m^3", "Mean Density (g/cm^3) = %s ± %s [%s]" % (den, dens, denref.strip()), P_JPL_SATS,760                                          status="computed" if star else "observed",761                                          uncertainty=number(dens) * 1e3 if number(dens) is not None else None,762                                          citation="[*] derived by JPL SSD from the tabulated GM and mean radius" if star else None))763    missing = set(ids) - found764    return sorted(missing)765766767def parse_sbdb(B, raw, fname, oid, elements_primary=True):768    d = json.loads(read(raw, fname))769    full = d["object"]["fullname"]770    orbit = d["orbit"]771    cite_orbit = "JPL SBDB orbit solution %s for %s (osculating elements at epoch JD %s TDB, heliocentric ecliptic J2000; solution date %s)" % (772        orbit.get("orbit_id"), full, orbit.get("epoch"), orbit.get("soln_date"))773    el = {e["name"]: e for e in orbit["elements"]}774    table = {"a": ("semiMajorAxis", AU, "m", "au"), "e": ("eccentricity", 1.0, "1", ""), "i": ("inclination", DEG, "rad", "deg"),775             "per": ("siderealOrbitPeriod", DAY, "s", "d")}776    for name, (key, factor, unit, pub_unit) in table.items():777        e = el.get(name)778        if not e or e.get("value") is None:779            continue780        v = float(e["value"])781        sigma = float(e["sigma"]) * factor if e.get("sigma") not in (None, "") else None782        B.add(oid, key, rec(v * factor, unit, "%s = %s %s" % (e["title"], e["value"], pub_unit), P_SBDB, status="computed", uncertainty=sigma,783                            citation=cite_orbit, note="osculating element at epoch JD %s (changes with time); inclination is to the ecliptic" % orbit.get("epoch"),784                            epochJD=float(orbit["epoch"])))785    for p in d.get("phys_par", []):786        name, val, sig = p["name"], p.get("value"), p.get("sigma")787        ref = p.get("ref")788        notes = p.get("notes")789        pub = "%s = %s%s %s" % (p.get("title") or name, val, " ± %s" % sig if sig else "", p.get("units") or "")790791        def s(factor):792            try:793                return float(sig) * factor if sig else None794            except ValueError:795                return None796        try:797            if name == "GM":798                B.add(oid, "gm", rec(float(val) * 1e9, "m^3/s^2", pub.strip(), P_SBDB, uncertainty=s(1e9), citation=ref, note=notes))799            elif name == "diameter":800                B.add(oid, "meanRadius", rec(float(val) * 500.0, "m", pub.strip(), P_SBDB, status="computed", uncertainty=s(500.0), citation=ref,801                                             note="half of the published effective diameter" + ("; " + notes if notes else "")))802            elif name == "density":803                B.add(oid, "meanDensity", rec(float(val) * 1e3, "kg/m^3", pub.strip(), P_SBDB, uncertainty=s(1e3), citation=ref, note=notes))804            elif name == "rot_per":805                B.add(oid, "siderealRotationPeriod", rec(float(val) * 3600.0, "s", pub.strip(), P_SBDB, uncertainty=s(3600.0), citation=ref,806                                                         note=(notes or "")[:300] or None))807            elif name == "albedo":808                B.add(oid, "geometricAlbedo", rec(float(val), "1", pub.strip(), P_SBDB, uncertainty=s(1.0), citation=ref, note=notes))809            elif name == "extent":810                B.set_extra(oid, "extentPublished", {"published": pub.strip(), "provenance": P_SBDB, "citation": ref, "note": notes})811        except (TypeError, ValueError):812            continue813814815# ----------------------------------------------------------------------------------------------- rings816817def depth_fields(text):818    """Optical depth cell -> dict of opticalDepth / opticalDepthRange / opticalDepthLimit (only what parses cleanly)."""819    t = text.strip().replace("−", "-")820    if not t:821        return {}822    out = {}823    m = re.fullmatch(r"(.+?)\s+to\s+(.+)", t) or re.fullmatch(r"([\d.]+)\s*-\s*([\d.]+)", t)824    if m:825        lo, hi = number(m.group(1).lstrip("~ ")), number(m.group(2).lstrip("~> "))826        if lo is not None and hi is not None:827            out["opticalDepthRange"] = [lo, hi]828            if ">" in m.group(2):829                out["opticalDepthRangeNote"] = "upper bound published as a lower limit (%s)" % m.group(2).strip()830        return out831    m = re.fullmatch(r"(~|≤|≥|<<|<|>)?\s*(.+?)", t)832    v = number(m.group(2)) if m else None833    if v is not None:834        out["opticalDepth"] = v835        mark = m.group(1) or ""836        if mark in ("≤", "<", "<<"):837            out["opticalDepthLimit"] = "upper"838        elif mark in ("≥", ">"):839            out["opticalDepthLimit"] = "lower"840        elif mark == "~":841            out["opticalDepthApproximate"] = True842    return out843844845def km(text):846    v = number(text.strip().lstrip("~ ").strip())847    return v * 1e3 if v is not None else None848849850def parse_rings(raw):851    rings = {}852    # ---- Saturn (PDS RMS: inner / outer boundary)853    page = read(raw, "rms_saturn_tables.html")854    comps = []855    for row in table_rows(page):856        if len(row) >= 8 and number(row[1].lstrip("~")) is not None and row[0] != "Feature" and re.search(r"Ring|Gap|Division|Region|Ringlet", row[0]):857            c = {"name": row[0]}858            if km(row[1]) is not None:859                c["innerRadius"] = km(row[1])860            if km(row[2]) is not None:861                c["outerRadius"] = km(row[2])862            if "innerRadius" in c and "outerRadius" in c:863                c["width"] = c["outerRadius"] - c["innerRadius"]864            else:865                # Narrow faint rings published by a single radius.866                c["radius"] = c.pop("innerRadius")867            c.update(depth_fields(row[3]))868            if row[4].strip():869                c["type"] = row[4].strip()870            c["published"] = {"innerBoundaryKm": row[1], "outerBoundaryKm": row[2], "opticalDepth": row[3],871                              "footnotes": row[6].strip(), "comments": row[7].strip()}872            comps.append(c)873        if row and row[0].startswith("Pan") and len(row) > 4:874            break875    sources = []876    m = re.search(r"Sources</h\d>(.*?)<h\d", page, flags=re.S | re.I)877    if m:878        sources = [clean(x) for x in re.findall(r"<li>(.*?)</li>", m.group(1), flags=re.S)]879    rings["naif:699"] = {"provenance": P_RMS, "citation": "PDS Ring-Moon Systems Node, 'Vital Statistics for Saturn's Rings and Inner Satellites', table 'Rings of Saturn'",880                         "footnoteSources": sources, "components": comps}881    # NSSDCA Saturn ring sheet (edge list) -> albedo and optical depth per main ring, kept as an alternate.882    page = read(raw, "nssdca_satringfact.html")883    cite = "NSSDCA Saturnian Rings Fact Sheet (D. R. Williams, NASA GSFC), last updated %s" % last_updated(page)884    edges = {}885    for row in table_rows(page):886        if len(row) < 3:887            continue888        m = re.match(r"([A-G]) (inner|outer) edge|(F ring|Cassini division)", row[0])889        if not m:890            continue891        edges[row[0]] = row892    alt = []893894    def rng(cell):895        m = re.fullmatch(r"\s*([\d.]+)\s*-\s*([\d.]+)\s*", cell)896        if m:897            return [float(m.group(1)), float(m.group(2))]898        return None899900    for letter in "DCBAGE":901        inner, outer = edges.get("%s inner edge" % letter), edges.get("%s outer edge" % letter)902        if not inner or not outer:903            continue904        c = {"name": "%s Ring" % letter, "innerRadius": km(inner[1]), "outerRadius": km(outer[1])}905        c.update(depth_fields(inner[3]) if len(inner) > 3 else {})906        if len(inner) > 4:907            if rng(inner[4]):908                c["albedoRange"] = rng(inner[4])909            elif number(inner[4]) is not None:910                c["albedo"] = number(inner[4])911        c["published"] = {"innerEdge": inner, "outerEdge": outer}912        alt.append(c)913    if "F ring" in edges:914        r = edges["F ring"]915        c = {"name": "F Ring", "radius": km(r[1])}916        c.update(depth_fields(r[3]))917        if number(r[4]) is not None:918            c["albedo"] = number(r[4])919        c["published"] = {"row": r}920        alt.append(c)921    if "Cassini division" in edges:922        r = edges["Cassini division"]923        cells = [x for x in r[1:] if x.strip()]924        c = {"name": "Cassini Division", "published": {"row": r}}925        if cells:926            c.update(depth_fields(cells[0]))927        if len(cells) > 1 and rng(cells[1]):928            c["albedoRange"] = rng(cells[1])929        alt.append(c)930    rings["naif:699"]["alternate"] = {"provenance": P_NSSDCA, "citation": cite,931                                      "note": "Albedo and optical depth are published per ring edge row; values of the inner-edge row are used.",932                                      "components": alt}933    # Merge the NSSDCA albedo into the matching RMS component (the RMS table has no albedo column).934    by_name = {c["name"]: c for c in alt}935    for c in comps:936        a = by_name.get(c["name"])937        if a:938            for k in ("albedo", "albedoRange"):939                if k in a:940                    c[k] = a[k]941                    c["albedoProvenance"] = P_NSSDCA942943    # ---- Jupiter (PDS RMS: inner / outer boundary, thickness)944    page = read(raw, "rms_jupiter_tables.html")945    comps = []946    for row in table_rows(page):947        if len(row) >= 6 and row[0] != "Feature" and km(row[1]) is not None and re.search(r"Halo|Ring|Extension", row[0]):948            name = re.sub(r"\s*\[\d+\]", "", row[0])949            c = {"name": name, "innerRadius": km(row[1]), "outerRadius": km(row[2])}950            c["width"] = c["outerRadius"] - c["innerRadius"]951            c.update(depth_fields(re.sub(r"\s", " ", row[3]).replace("~ ", "~")))952            t = number(row[4].lstrip("~≤ ").strip())953            if t is not None:954                c["thickness"] = t * 1e3955            c["published"] = {"innerBoundaryKm": row[1], "outerBoundaryKm": row[2], "opticalDepth": row[3], "thicknessKm": row[4], "notes": row[5]}956            comps.append(c)957    rings["naif:599"] = {"provenance": P_RMS, "citation": "PDS Ring-Moon Systems Node, 'Vital Statistics for Jupiter's Rings and Inner Satellites' (Murray & Dermott 1999; Burns et al. 1999, Science 284, 1146)",958                         "components": comps}959    page = read(raw, "nssdca_jupringfact.html")960    cite = "NSSDCA Jupiter Rings Fact Sheet (D. R. Williams, NASA GSFC), last updated %s" % last_updated(page)961    for row in table_rows(page):962        if row and row[0] == "Main Ring" and len(row) > 5 and number(row[5].lstrip("~")) is not None:963            for c in comps:964                if c["name"] == "Main Ring":965                    c["albedo"] = number(row[5].lstrip("~"))966                    c["albedoProvenance"] = P_NSSDCA967                    c["published"]["albedo"] = "%s (%s)" % (row[5], cite)968969    # ---- Uranus / Neptune (PDS RMS: middle radius and width; albedo from NSSDCA)970    def narrow(fname, planet, cols_depth, nssdca_file, aliases):971        page = read(raw, fname)972        comps = []973        for row in table_rows(page):974            if len(row) <= cols_depth or row[0] in ("Feature", "Name"):975                continue976            # A missing </tr> glues the next ring name to the notes of the Epsilon row on the Uranus page.977            name = row[0].split("   ")[-1].strip()978            name = re.sub(r"^.*\.\s+", "", name)979            if km(row[1]) is None or "Semimajor" in " ".join(row):980                continue981            if len(row) > 6 and re.match(r"^[\d.]+$", row[2].strip()) and re.match(r"^[\d.<~ ]+$", row[3].strip()) and len(comps) and planet != "Uranus" and False:982                continue983            c = {"name": name, "radius": km(row[1])}984            w = row[2].strip()985            m = re.fullmatch(r"([\d,.]+)\s+to\s+([\d,.]+)", w)986            if m:987                c["widthRange"] = [number(m.group(1)) * 1e3, number(m.group(2)) * 1e3]988            else:989                m = re.fullmatch(r"(~|<)?\s*([\d,.]+)", w)990                if m:991                    c["width"] = number(m.group(2)) * 1e3992                    if m.group(1) == "<":993                        c["widthLimit"] = "upper"994                    elif m.group(1) == "~":995                        c["widthApproximate"] = True996                    else:997                        c["innerRadius"] = c["radius"] - c["width"] / 2998                        c["outerRadius"] = c["radius"] + c["width"] / 2999                        c["edgesComputedFromWidth"] = True1000            c.update(depth_fields(row[cols_depth].replace("~ ", "~").replace("≤ ", "≤").replace("≥ ", "≥")))1001            c["published"] = {"middleBoundaryKm": row[1], "widthKm": row[2], "opticalDepth": row[cols_depth]}1002            if planet == "Uranus":1003                c["published"]["eccentricity"] = row[3]1004                c["published"]["inclinationDeg"] = row[4]1005            comps.append(c)1006            if name in ("R/2003 U 1", "Adams"):1007                break1008        npage = read(raw, nssdca_file)1009        cite = "NSSDCA %s Rings Fact Sheet (D. R. Williams, NASA GSFC), last updated %s" % (planet, last_updated(npage))1010        for row in table_rows(npage):1011            if len(row) < 5:1012                continue1013            n = re.sub(r"\s*\(.*", "", row[0]).strip()1014            target = aliases.get(n, n)1015            a = re.fullmatch(r"~?\s*([\d.]+)", row[4].strip())1016            if not a:1017                continue1018            for c in comps:1019                if c["name"] == target and "albedo" not in c:1020                    c["albedo"] = float(a.group(1)) * 1e-31021                    c["albedoProvenance"] = P_NSSDCA1022                    c["published"]["albedo"] = "Albedo (x 10^-3) = %s (%s)" % (row[4], cite)1023        return comps10241025    comps = narrow("rms_uranus_tables.html", "Uranus", 5, "nssdca_uranringfact.html", {"6": "Six", "5": "Five", "4": "Four"})1026    rings["naif:799"] = {"provenance": P_RMS, "citation": "PDS Ring-Moon Systems Node, 'Vital Statistics for Uranus's Rings and Inner Satellites', table 'Rings of Uranus'",1027                         "components": comps}1028    comps = narrow("rms_neptune_tables.html", "Neptune", 3, "nssdca_nepringfact.html", {"LeVerrier": "Le Verrier"})1029    rings["naif:899"] = {"provenance": P_RMS, "citation": "PDS Ring-Moon Systems Node, 'Vital Statistics for Neptune's Rings and Inner Satellites' (Murray & Dermott 1999)",1030                         "components": comps}1031    return rings103210331034# ----------------------------------------------------------------------------------------------- main10351036def main():1037    if len(sys.argv) != 2:1038        raise SystemExit(__doc__)1039    root = os.path.abspath(sys.argv[1])1040    raw = os.path.join(root, "DataPipeline", "raw", "facts")1041    if not os.path.isfile(os.path.join(raw, "RETRIEVED")):1042        raise SystemExit("raw cache missing: run DataPipeline/textures/fetch_facts.sh first")1043    retrieved = open(os.path.join(raw, "RETRIEVED")).read().strip()10441045    B = Bodies()1046    SUN = "naif:10"1047    B.define(SUN, "Sun", "star", None)1048    planets = [("naif:199", "Mercury", "mercury", False), ("naif:299", "Venus", "venus", False), ("naif:399", "Earth", "earth", False),1049               ("naif:499", "Mars", "mars", False), ("naif:599", "Jupiter", "jupiter", True), ("naif:699", "Saturn", "saturn", True),1050               ("naif:799", "Uranus", "uranus", True), ("naif:899", "Neptune", "neptune", True)]1051    for oid, name, _, _ in planets:1052        B.define(oid, name, "planet", SUN)1053    B.define("naif:999", "Pluto", "dwarfPlanet", SUN)1054    moons = {"naif:301": ("Moon", "naif:399"), "naif:401": ("Phobos", "naif:499"), "naif:402": ("Deimos", "naif:499"),1055             "naif:501": ("Io", "naif:599"), "naif:502": ("Europa", "naif:599"), "naif:503": ("Ganymede", "naif:599"), "naif:504": ("Callisto", "naif:599"),1056             "naif:601": ("Mimas", "naif:699"), "naif:602": ("Enceladus", "naif:699"), "naif:603": ("Tethys", "naif:699"), "naif:604": ("Dione", "naif:699"),1057             "naif:605": ("Rhea", "naif:699"), "naif:606": ("Titan", "naif:699"), "naif:607": ("Hyperion", "naif:699"), "naif:608": ("Iapetus", "naif:699"),1058             "naif:701": ("Ariel", "naif:799"), "naif:702": ("Umbriel", "naif:799"), "naif:703": ("Titania", "naif:799"), "naif:704": ("Oberon", "naif:799"),1059             "naif:705": ("Miranda", "naif:799"), "naif:801": ("Triton", "naif:899"), "naif:802": ("Nereid", "naif:899"), "naif:901": ("Charon", "naif:999")}1060    for oid, (name, parent) in moons.items():1061        B.define(oid, name, "moon", parent)1062    # Small-body ids follow Resources/Packs/core-ephemeris/kepler_elements.json (NAIF 20000000 + number; comets = SBDB SPK-ID).1063    smalls = [("naif:20000001", "Ceres", "dwarfPlanet", "sbdb_ceres.json"), ("naif:20136199", "Eris", "dwarfPlanet", "sbdb_eris.json"),1064              ("naif:20136108", "Haumea", "dwarfPlanet", "sbdb_haumea.json"), ("naif:20136472", "Makemake", "dwarfPlanet", "sbdb_makemake.json"),1065              ("naif:20000004", "Vesta", "asteroid", "sbdb_vesta.json"), ("naif:20000433", "Eros", "asteroid", "sbdb_eros.json"),1066              ("naif:1000036", "1P/Halley", "comet", "sbdb_halley.json"), ("naif:1000012", "67P/Churyumov-Gerasimenko", "comet", "sbdb_67p.json")]1067    for oid, name, kind, _ in smalls:1068        B.define(oid, name, kind, SUN, sbdb=True)10691070    # NSSDCA planet sheets (first data column = the body, second = Earth).1071    parse_nssdca_planet(B, raw, SUN, "nssdca_sunfact.html", "Sun")1072    mars_page = pluto_lines = mars_cite = pluto_cite = None1073    for oid, name, stem, giant in planets:1074        page, lines, cite = parse_nssdca_planet(B, raw, oid, "nssdca_%sfact.html" % stem, name, giant)1075        if stem == "mars":1076            mars_page, mars_cite = page, cite1077    _, pluto_lines, pluto_cite = parse_nssdca_planet(B, raw, "naif:999", "nssdca_plutofact.html", "Pluto")1078    parse_nssdca_planet(B, raw, "naif:301", "nssdca_moonfact.html", "Moon")1079    # The Earth column of the Earth sheet has no orbit inclination row other than 0.000 (reference plane): kept as published.1080    parse_mars_sats(B, mars_page, mars_cite)1081    parse_charon(B, pluto_lines, pluto_cite)1082    parse_nssdca_sat_sheet(B, raw, "nssdca_joviansatfact.html", {"Io": "naif:501", "Europa": "naif:502", "Ganymede": "naif:503", "Callisto": "naif:504"}, "Jovian")1083    parse_nssdca_sat_sheet(B, raw, "nssdca_saturniansatfact.html", {"Mimas": "naif:601", "Enceladus": "naif:602", "Tethys": "naif:603", "Dione": "naif:604",1084                                                                    "Rhea": "naif:605", "Titan": "naif:606", "Hyperion": "naif:607", "Iapetus": "naif:608"}, "Saturnian")1085    parse_nssdca_sat_sheet(B, raw, "nssdca_uraniansatfact.html", {"Ariel": "naif:701", "Umbriel": "naif:702", "Titania": "naif:703", "Oberon": "naif:704",1086                                                                  "Miranda": "naif:705"}, "Uranian")1087    parse_nssdca_sat_sheet(B, raw, "nssdca_neptuniansatfact.html", {"Triton": "naif:801", "Nereid": "naif:802"}, "Neptunian")1088    parse_small_worlds(B, raw)1089    parse_asteroids(B, raw)1090    parse_comets(B, raw)10911092    # JPL SSD tables.1093    parse_jpl_planets(B, raw, {"Mercury": "naif:199", "Venus": "naif:299", "Earth": "naif:399", "Mars": "naif:499", "Jupiter": "naif:599",1094                               "Saturn": "naif:699", "Uranus": "naif:799", "Neptune": "naif:899", "Ceres": "naif:20000001", "Pluto": "naif:999",1095                               "Eris": "naif:20136199", "Makemake": "naif:20136472", "Haumea": "naif:20136108"})1096    missing_sats = parse_jpl_sats(B, raw, {int(oid.split(":")[1]): oid for oid in moons})10971098    # JPL SBDB (small bodies).1099    for oid, _, _, fname in smalls:1100        parse_sbdb(B, raw, fname, oid)1101    parse_sbdb(B, raw, "sbdb_pluto.json", "naif:999")11021103    bodies = B.export()1104    rings = parse_rings(raw)11051106    provenance = [1107        {"id": P_NSSDCA, "source": "NASA Space Science Data Coordinated Archive (NSSDCA) Planetary Fact Sheets, D. R. Williams, NASA Goddard Space Flight Center",1108         "version": "pages as served on %s (each record cites the 'Last Updated' date of its page)" % retrieved, "retrieved": retrieved,1109         "license": "U.S. Government work (NASA). The fact-sheet pages carry no licence or copyright notice. NASA Images and Media Usage Guidelines "1110                    "(https://www.nasa.gov/nasa-brand-center/images-and-media/): \"NASA content [...] generally are not subject to copyright in the United States\"; "1111                    "\"NASA should be acknowledged as the source of the material.\" The sheets state that the values \"are not 'official' values\" and are subject to change.",1112         "url": "https://nssdc.gsfc.nasa.gov/planetary/planetfact.html",1113         "method": "HTML tables and text parsed by DataPipeline/textures/parse_facts.py; units converted to SI; published strings kept",1114         "citation": "Williams, D. R., NASA NSSDCA Planetary Fact Sheets, NASA Goddard Space Flight Center, https://nssdc.gsfc.nasa.gov/planetary/planetfact.html (retrieved %s). "1115                     "Sources listed by the sheets: IAU/IAG Working Group Reports 2006 and 2015; Astronomical Almanac 2000, 2001, 2020; Global Earth Physics (AGU, 1995); "1116                     "Astrophysical Quantities (Allen 1981, 2000); JPL ephemeris DE430/DE431; IAU bulletins; journal articles." % retrieved},1117        {"id": P_JPL_PLANETS, "source": "NASA/JPL Solar System Dynamics, Planetary Physical Parameters",1118         "version": "page as served on %s" % retrieved, "retrieved": retrieved,1119         "license": "U.S. Government-sponsored work (NASA/JPL-Caltech); no licence statement on the page. Citation requested by https://ssd.jpl.nasa.gov/about/ : "1120                    "\"NASA/JPL Solar System Dynamics. Data retrieved on (Downloaded Year, Month, Date). (Title of the Page). https://ssd.jpl.nasa.gov\"",1121         "url": "https://ssd.jpl.nasa.gov/planets/phys_par.html",1122         "method": "HTML table parsed; value, ± uncertainty and reference letter kept per cell; '[*]' cells are marked computed",1123         "citation": "NASA/JPL Solar System Dynamics. Data retrieved on %s. Planetary Physical Parameters. https://ssd.jpl.nasa.gov" % retrieved},1124        {"id": P_JPL_SATS, "source": "NASA/JPL Solar System Dynamics, Planetary Satellite Physical Parameters",1125         "version": "page as served on %s" % retrieved, "retrieved": retrieved,1126         "license": "U.S. Government-sponsored work (NASA/JPL-Caltech); no licence statement on the page. Citation requested by https://ssd.jpl.nasa.gov/about/ : "1127                    "\"NASA/JPL Solar System Dynamics. Data retrieved on (Downloaded Year, Month, Date). (Title of the Page). https://ssd.jpl.nasa.gov\"",1128         "url": "https://ssd.jpl.nasa.gov/sats/phys_par/",1129         "method": "HTML table parsed (GM, mean radius, mean density with sigma and reference); '*' densities are marked computed",1130         "citation": "NASA/JPL Solar System Dynamics. Data retrieved on %s. Planetary Satellite Physical Parameters. https://ssd.jpl.nasa.gov" % retrieved},1131        {"id": P_SBDB, "source": "NASA/JPL Small-Body Database (SBDB) API, version 1.3",1132         "version": "API 1.3, records as served on %s" % retrieved, "retrieved": retrieved,1133         "license": "U.S. Government-sponsored work (NASA/JPL-Caltech); no licence statement in the API documentation (https://ssd-api.jpl.nasa.gov/doc/sbdb.html). "1134                    "Citation requested by https://ssd.jpl.nasa.gov/about/ for SSD data.",1135         "url": "https://ssd-api.jpl.nasa.gov/sbdb.api",1136         "method": "JSON records (phys-par=1, full-prec=1); osculating heliocentric ecliptic J2000 elements at the solution epoch; per-value reference kept",1137         "citation": "NASA/JPL Solar System Dynamics. Data retrieved on %s. Small-Body Database (SBDB API). https://ssd.jpl.nasa.gov" % retrieved},1138        {"id": P_RMS, "source": "NASA Planetary Data System, Ring-Moon Systems Node (SETI Institute), 'Vital Statistics' ring tables",1139         "version": "pages as served on %s" % retrieved, "retrieved": retrieved,1140         "license": "NASA Planetary Data System node web page; no licence or copyright statement on the tables. PDS asks users to cite the data and its providers "1141                    "(https://pds.nasa.gov/datastandards/citing/). The tables themselves cite Murray & Dermott (1999) and the papers listed under 'footnoteSources'.",1142         "url": "https://pds-rings.seti.org/saturn/saturn_tables.html",1143         "method": "HTML tables parsed (Saturn, Jupiter: inner/outer boundary; Uranus, Neptune: middle radius and width); ring albedos merged from the NSSDCA ring fact sheets",1144         "citation": "PDS Ring-Moon Systems Node, Vital Statistics for the rings of Saturn, Jupiter, Uranus and Neptune, https://pds-rings.seti.org (retrieved %s); "1145                     "Murray, C. D., Dermott, S. F. (1999) Solar System Dynamics, Cambridge University Press." % retrieved},1146    ]11471148    # Published zeros (kept because the source literally prints 0).1149    zeros = []1150    for oid, b in bodies.items():1151        for group in ("properties",):1152            for key, r in b[group].items():1153                if r["value"] == 0:1154                    zeros.append({"body": oid, "key": key, "published": r["published"], "provenance": r["provenance"]})1155        for key, lst in b.get("alternates", {}).items():1156            for r in lst:1157                if r["value"] == 0:1158                    zeros.append({"body": oid, "key": key, "published": r["published"], "provenance": r["provenance"], "alternate": True})11591160    for oid, b in bodies.items():1161        if b.get("moonCount", {}).get("value") == 0:1162            zeros.append({"body": oid, "key": "moonCount", "published": b["moonCount"]["published"], "provenance": b["moonCount"]["provenance"]})11631164    out = {1165        "format": 1,1166        "retrieved": retrieved,1167        "generator": "DataPipeline/textures/parse_facts.py",1168        "units": "SI (m, s, kg, rad, K, Pa); fractions are by volume unless 'basis' says otherwise",1169        "notes": [1170            "A quantity missing from the sources is absent; nothing is defaulted.",1171            "JPL SSD is primary for mass, GM, radii, density and geometric albedo; NSSDCA for the other keys; other sources are under 'alternates'.",1172            "Small bodies (Ceres, Vesta, Eros, Eris, Haumea, Makemake, 1P, 67P): orbit keys come first from the current JPL SBDB solution (osculating, epoch in 'epochJD'), other keys first from the JPL tables.",1173            "Extra per-body fields beyond the base schema: ranges, hasRingSystemPublished, surfacePressureNote, triaxialRadiiPublished, triaxialDiametersPublished, extentPublished, rotationNote, geometricAlbedoNote, gmNote; extra property keys: atmosphereScaleHeight (m), meanMolecularWeight (kg/mol).",1174            "Radii and GM used for dynamics and rendering come from the NAIF kernels of the core-ephemeris pack, not from this file.",1175            "Satellites not listed in the JPL satellite table: %s" % (", ".join("naif:%d" % c for c in missing_sats) or "none"),1176        ],1177        "provenance": provenance,1178        "bodies": bodies,1179        "rings": rings,1180        "publishedZeros": zeros,1181    }11821183    # ------------------------------------------------------------------------------------------- self-check1184    errors = []11851186    def prop(oid, key):1187        return bodies.get(oid, {}).get("properties", {}).get(key)11881189    def close(v, ref, tol):1190        return v is not None and abs(v - ref) <= tol * abs(ref)11911192    e = prop("naif:399", "mass")1193    if not e or not close(e["value"], 5.97e24, 2e-3):1194        errors.append("Earth mass not ~5.97e24 kg: %s" % e)1195    e = prop("naif:499", "meanDensity")1196    if not e or not close(e["value"], 3934.0, 1e-3):1197        errors.append("Mars mean density not ~3934 kg/m^3: %s" % e)1198    if not prop("naif:606", "gm"):1199        errors.append("Titan GM missing")1200    b = next((c for c in rings.get("naif:699", {}).get("components", []) if c["name"] == "B Ring"), None)1201    if not b or not close(b.get("innerRadius"), 91_975e3, 1e-6) or "outerRadius" not in b:1202        errors.append("Saturn B ring radii missing: %s" % b)1203    for planet in ("naif:599", "naif:799", "naif:899"):1204        if not rings.get(planet, {}).get("components"):1205            errors.append("no ring components for %s" % planet)1206    ids = {p["id"] for p in provenance}1207    zero_keys = {(z["body"], z["key"], z["published"]) for z in zeros}1208    for oid, bdy in bodies.items():1209        if not bdy["properties"]:1210            errors.append("%s has no property" % oid)1211        recs = list(bdy["properties"].items()) + [(k, r) for k, lst in bdy.get("alternates", {}).items() for r in lst]1212        for key, r in recs:1213            if r.get("provenance") not in ids:1214                errors.append("%s.%s has no valid provenance" % (oid, key))1215            if not isinstance(r["value"], (int, float)) or math.isnan(r["value"]) or math.isinf(r["value"]):1216                errors.append("%s.%s is not a finite number" % (oid, key))1217            if r["value"] == 0:1218                digits = re.sub(r"[^0-9]", "", r["published"].split("=")[-1])1219                if (oid, key, r["published"]) not in zero_keys or not digits or set(digits) != {"0"}:1220                    errors.append("%s.%s is 0 but the source does not literally publish 0: %s" % (oid, key, r["published"]))1221            if not r.get("published"):1222                errors.append("%s.%s has no published string" % (oid, key))1223        for extra in ("atmosphere", "moonCount"):1224            if extra in bdy and bdy[extra].get("provenance") not in ids:1225                errors.append("%s.%s has no valid provenance" % (oid, extra))1226    for oid, r in rings.items():1227        if r.get("provenance") not in ids:1228            errors.append("rings %s has no provenance" % oid)1229    # Sanity anchors on parsed text blocks.1230    for oid, n in (("naif:399", 2), ("naif:499", 5), ("naif:299", 2), ("naif:599", 2), ("naif:999", 3)):1231        cons = [c for c in bodies[oid].get("atmosphere", {}).get("constituents", []) if not c.get("minor")]1232        if len(cons) < n:1233            errors.append("%s: expected at least %d major atmospheric constituents, parsed %d" % (oid, n, len(cons)))1234    for oid in ("naif:399", "naif:499", "naif:599", "naif:699", "naif:799", "naif:899", "naif:999"):1235        if "moonCount" not in bodies[oid]:1236            errors.append("%s: moon count not parsed" % oid)12371238    dest = os.path.join(root, "DataPipeline", "textures", "data")1239    os.makedirs(dest, exist_ok=True)1240    path = os.path.join(dest, "facts.json")1241    if errors:1242        for e in errors:1243            print("SELF-CHECK FAILED:", e, file=sys.stderr)1244        raise SystemExit(1)1245    def tidy(x):1246        # Unit conversions leave binary noise (4.9999999999999996e-06): keep 13 significant digits.1247        if isinstance(x, float):1248            return float("%.13g" % x)1249        if isinstance(x, dict):1250            return {k: tidy(v) for k, v in x.items()}1251        if isinstance(x, list):1252            return [tidy(v) for v in x]1253        return x12541255    with open(path + ".tmp", "w", encoding="utf-8") as f:1256        json.dump(tidy(out), f, indent=1, ensure_ascii=False)1257        f.write("\n")1258    os.replace(path + ".tmp", path)1259    n_props = sum(len(b["properties"]) for b in bodies.values())1260    print("wrote %s: %d bodies, %d primary properties, %d ring systems, %d published zeros; self-check passed" % (1261        os.path.relpath(path, root), len(bodies), n_props, len(rings), len(zeros)))126212631264if __name__ == "__main__":1265    main()1266
Files main
Menu

Theme