Repository Public
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/build_planetary.py11# Description : Assembles the versioned planetary data file from the12# parsed facts (data/facts.json), the texture registry13# (data/assets.json) and the curated inputs14# (curated/*.json): derived quantities, atmosphere optical15# models, ring systems, texture layers, illustration16# descriptors and the provenance table. Writes17# data/planetary.json and the generated Swift source that18# embeds it in CosmosPlanetary. Standard library only.19# Module : DataPipeline20# Repository : https://git.spboucher.ai/orix-cosmos21# Project Website : https://www.orixlab.dev22# Created : 2026-11-2423# Last Modified : 2026-11-2424#25# =============================================================================26# AUTHOR & PROFESSIONAL AFFILIATION27# =============================================================================28#29# Author : Simon-Pierre Boucher30# Position : Professor of Finance31# Institution : Université du Québec en Outaouais (UQO)32# Department : Département des sciences administratives33# Organization : SP Boucher34#35# Website : https://spboucher.ai36# Git : https://git.spboucher.ai37#38# =============================================================================39# OFFICIAL CONTACT DIRECTORY40# =============================================================================41#42# General : info@spboucher.ai43# Professional : contact@spboucher.ai44# Direct : simon@spboucher.ai45# Research : research@spboucher.ai46# Development : dev@spboucher.ai47# Support : support@spboucher.ai48# Security/Admin : admin@spboucher.ai49# Notifications : notifications@spboucher.ai50#51# Preferred Contact: support@spboucher.ai52#53# =============================================================================54# COPYRIGHT & INTELLECTUAL PROPERTY55# =============================================================================56#57# Copyright (c) 202658# Simon-Pierre Boucher59#60# All rights reserved where applicable.61#62# This file is governed by the applicable project license,63# copyright notices, institutional agreements and relevant law.64#65# Unless expressly authorized by the applicable license or66# rights holder, copying, redistribution, sublicensing,67# publication and commercial exploitation are not permitted.68#69# Existing third-party rights and notices remain unaffected.70#71# =============================================================================72# CONFIDENTIALITY & SECURITY73# =============================================================================74#75# Classification : Public76# Distribution : Public repository; use is governed by the project license77# Security Contact : admin@spboucher.ai78#79# Access to this source does not independently grant permission80# to redistribute or disclose confidential materials.81#82# Do not embed credentials, private keys, access tokens,83# certificates or confidential personal information.84#85# =============================================================================86# LICENSE & MAINTENANCE87# =============================================================================88#89# License : None specified (no license file in this repository)90# Maintainer : Simon-Pierre Boucher91# Technical Contact: dev@spboucher.ai92#93# =============================================================================94# END OF SP BOUCHER SOURCE HEADER95# =============================================================================9697"""Usage: build_planetary.py <repository root>9899Run after parse_facts.py and build_textures.py. The JSON layout is the Codable layout of100Packages/CosmosPlanetary/Sources/PlanetaryModel.swift (CosmosCore.Measured, Quantity {"si": x}, ObjectID {"raw": "..."})."""101import datetime102import json103import math104import os105import sys106107DATA_VERSION = "1.0.0"108DERIVED_ID = "orix-derived-gm-radius"109110111def oid(raw):112 return {"raw": raw}113114115def measured(record, quantity=True, status=None, provenance=None):116 """CosmosCore.Measured<Quantity> (quantity=True) or Measured<Double>."""117 out = {"value": {"si": record["value"]} if quantity else record["value"], "status": status or record["status"]}118 if record.get("uncertainty") is not None:119 out["uncertainty"] = {"symmetric": {"_0": record["uncertainty"]}}120 prov = provenance or record.get("provenance")121 if prov:122 out["provenance"] = prov123 return out124125126def annotation(record):127 out = {"unit": record.get("unit", "")}128 for key in ("published", "note", "citation"):129 if record.get(key):130 out[key] = record[key]131 return out132133134# property key in facts.json -> (section, Swift property, typed quantity?)135PHYSICAL = {136 "mass": ("mass", True), "gm": ("gm", False), "meanRadius": ("meanRadius", True), "equatorialRadius": ("equatorialRadius", True),137 "meanDensity": ("meanDensity", False), "surfaceGravity": ("publishedSurfaceGravity", False), "escapeVelocity": ("publishedEscapeVelocity", True),138 "siderealRotationPeriod": ("siderealRotationPeriod", True), "obliquity": ("obliquity", True),139 "blackBodyTemperature": ("blackBodyTemperature", True), "meanSurfaceTemperature": ("meanSurfaceTemperature", True),140 "effectiveTemperature": ("effectiveTemperature", True), "bondAlbedo": ("bondAlbedo", False), "geometricAlbedo": ("geometricAlbedo", False),141 "surfacePressure": ("surfacePressure", False), "atmosphereScaleHeight": ("atmosphereScaleHeight", True), "luminosity": ("luminosity", False),142 "meanMolecularWeight": ("meanMolecularWeight", False), "visualMagnitudeV0": ("visualMagnitudeV0", False),143}144ORBIT = {"semiMajorAxis": ("semiMajorAxis", True), "eccentricity": ("eccentricity", False), "inclination": ("inclination", True),145 "siderealOrbitPeriod": ("siderealPeriod", True)}146147148def rayleigh(mix, gases, consts, pressure, temperature, wavelengths_nm):149 """Rayleigh volume scattering coefficients (1/m) of a gas mixture at pressure (Pa) and temperature (K)."""150 known = {g: x for g, x in mix.items() if g in gases}151 total = sum(known.values())152 refractivity_stp = sum(x / total * gases[g]["refractivitySTP"] for g, x in known.items())153 king = sum(x / total * gases[g]["kingFactor"] for g, x in known.items())154 number_density = pressure / (consts["boltzmannJoulePerKelvin"] * temperature)155 n_minus_1 = refractivity_stp * number_density / consts["loschmidtPerCubicMeter"]156 out = {}157 for channel, nm in wavelengths_nm.items():158 lam = nm * 1e-9159 out[channel] = 32 * math.pi ** 3 * n_minus_1 ** 2 * king / (3 * number_density * lam ** 4)160 return out, total, sorted(known)161162163def build_atmosphere(spec, body, props, cur, gm_over_r2):164 consts, gases = cur["constants"], cur["gases"]165 params = []166 if "pressurePa" in spec:167 pressure = spec["pressurePa"]168 p_basis = spec.get("levelBasis", "")169 else:170 pressure = props["surfacePressure"]["value"]171 p_basis = f"surface pressure {props['surfacePressure'].get('published', '')} (NSSDCA fact sheet)"172 if "temperatureK" in spec:173 temperature = spec["temperatureK"]174 t_basis = spec.get("levelBasis", "")175 else:176 rec = props["meanSurfaceTemperature"]177 temperature = rec["value"]178 t_basis = f"temperature {rec.get('published', '')} ({rec.get('note', '')})"179 if "gasMix" in spec:180 mix = spec["gasMix"]181 g_basis = spec["gasBasis"]182 else:183 mix = {c["species"]: c["fraction"] for c in body["atmosphere"]["constituents"]}184 g_basis = "composition by volume from the NSSDCA fact sheet"185 beta, covered, used = rayleigh(mix, gases, consts, pressure, temperature, cur["wavelengthsNanometers"])186 # Scale height: published value when the reference level is the published one, otherwise k T / (mu g).187 mu = sum(x * m for x, m in ((mix.get(g, 0) / covered, w) for g, w in188 (("N2", 28.0134), ("O2", 31.998), ("Ar", 39.948), ("CO2", 44.0095), ("H2", 2.01588), ("He", 4.002602), ("CH4", 16.0425))))189 computed_h = consts["boltzmannJoulePerKelvin"] * temperature / (mu * consts["atomicMassKg"] * gm_over_r2)190 if spec.get("scaleHeight") == "computed" or "atmosphereScaleHeight" not in props:191 scale_height = computed_h192 h_basis = (f"H = k T / (mu g) with T = {temperature:g} K, mu = {mu:.2f} u (standard atomic weights), g = GM / R^2 = {gm_over_r2:.3f} m/s^2")193 h_status = "estimated"194 else:195 scale_height = props["atmosphereScaleHeight"]["value"]196 h_basis = f"published pressure scale height ({props['atmosphereScaleHeight'].get('published', '')}, NSSDCA fact sheet)"197 h_status = "estimated"198 params.append({"name": "rayleighScattering", "status": "estimated",199 "basis": (f"Derived: {cur['rayleighFormula']} Inputs: P = {pressure:g} Pa ({p_basis}); T = {temperature:g} K ({t_basis}); "200 f"gases {', '.join(used)} covering {covered * 100:.1f} % of the volume ({g_basis}).")})201 params.append({"name": "rayleighScaleHeight", "status": h_status, "basis": h_basis})202 zero = {"r": 0.0, "g": 0.0, "b": 0.0}203 mie = spec.get("mie")204 if mie:205 mie_h = mie.get("scaleHeightMeters") or scale_height206 ext = mie["verticalOpticalDepth"] / mie_h207 ssa = mie["singleScatteringAlbedo"]208 mie_ext = {c: ext for c in "rgb"}209 mie_sca = {c: ext * ssa[c] for c in "rgb"}210 asym = mie["asymmetry"]211 params += mie["parameters"]212 params.append({"name": "mieScaleHeight", "status": "estimated",213 "basis": "Aerosol scale height " + ("as cited for the extinction" if mie.get("scaleHeightMeters") else "set equal to the gas scale height (well-mixed dust)") + "."})214 else:215 mie_h, mie_ext, mie_sca, asym = scale_height, dict(zero), dict(zero), 0.0216 params.append({"name": "mieScattering", "status": "hypothetical",217 "basis": "No aerosol model: set to zero. Clouds and hazes are not represented by this layer."})218 rule = cur["topHeightRule"]219 params.append({"name": "topHeight", "status": "estimated", "basis": rule["basis"]})220 statuses = [p["status"] for p in params]221 overall = "hypothetical" if any(s == "hypothetical" for s in statuses if s) and mie else "estimated"222 return {223 "referenceLevel": spec["referenceLevel"], "wavelengthsNanometers": cur["wavelengthsNanometers"],224 "rayleighScattering": beta, "rayleighScaleHeight": scale_height,225 "mieScattering": mie_sca, "mieExtinction": mie_ext, "mieScaleHeight": mie_h, "mieAsymmetry": asym,226 "absorption": dict(zero), "absorptionCenterHeight": 0.0, "absorptionHalfWidth": 0.0,227 "topHeight": rule["scaleHeights"] * scale_height,228 "status": overall, "provenance": "atmosphere-derived-rayleigh", "parameters": params, "summary": spec["summary"],229 }230231232def earth_atmosphere(cur):233 e = cur["earth"]234 out = {k: e[k] for k in ("referenceLevel", "rayleighScattering", "rayleighScaleHeight", "mieScattering", "mieExtinction", "mieScaleHeight",235 "mieAsymmetry", "absorption", "absorptionCenterHeight", "absorptionHalfWidth", "topHeight", "parameters", "summary")}236 out["wavelengthsNanometers"] = cur["wavelengthsNanometers"]237 out["status"] = "computed"238 out["provenance"] = "atmosphere-earth-bruneton-hillaire"239 for key in ("rayleighScaleHeight", "mieScaleHeight", "mieAsymmetry", "absorptionCenterHeight", "absorptionHalfWidth", "topHeight"):240 out[key] = float(out[key])241 return out242243244def build_rings(ring, prov_default):245 comps, segments = [], []246 for c in ring["components"]:247 prov = ring.get("provenance", prov_default)248249 def m(value, quantity, status="observed", provenance=prov):250 return measured({"value": value, "status": status, "provenance": provenance}, quantity=quantity)251 out = {"name": c["name"]}252 if c.get("type"):253 out["type"] = c["type"]254 edge_status = "computed" if c.get("edgesComputedFromWidth") else "observed"255 if "innerRadius" in c:256 out["innerRadius"] = m(c["innerRadius"], True, edge_status)257 if "outerRadius" in c:258 out["outerRadius"] = m(c["outerRadius"], True, edge_status)259 if "radius" in c:260 out["centerRadius"] = m(c["radius"], True)261 if "width" in c:262 out["width"] = m(c["width"], True, "estimated" if c.get("widthApproximate") else "observed")263 if "opticalDepth" in c:264 out["opticalDepth"] = m(c["opticalDepth"], False, "estimated" if c.get("opticalDepthApproximate") else "observed")265 if "opticalDepthRange" in c:266 out["opticalDepthRange"] = {"low": c["opticalDepthRange"][0], "high": c["opticalDepthRange"][1]}267 if "albedo" in c:268 out["albedo"] = m(c["albedo"], False, provenance=c.get("albedoProvenance", prov))269 if "albedoRange" in c:270 out["albedoRange"] = {"low": c["albedoRange"][0], "high": c["albedoRange"][1]}271 notes = [c[k] for k in ("opticalDepthRangeNote",) if c.get(k)]272 if c.get("edgesComputedFromWidth"):273 notes.append("inner and outer radii computed from the published centre radius and width")274 if notes:275 out["note"] = "; ".join(notes)276 comps.append(out)277 # Radial profile segment: needs both edges and an optical depth (single value, or the midpoint of a range).278 tau = c.get("opticalDepth")279 if tau is None and "opticalDepthRange" in c:280 tau = 0.5 * (c["opticalDepthRange"][0] + c["opticalDepthRange"][1])281 if tau is not None and "innerRadius" in c and "outerRadius" in c:282 seg = {"name": c["name"], "innerRadius": c["innerRadius"], "outerRadius": c["outerRadius"], "opticalDepth": tau,283 "opacity": 1 - math.exp(-tau), "status": "estimated"}284 alb = c.get("albedo")285 if alb is None and "albedoRange" in c:286 alb = 0.5 * (c["albedoRange"][0] + c["albedoRange"][1])287 if alb is not None:288 seg["albedo"] = alb289 segments.append(seg)290 # Narrower components override the broad region that contains them: order by decreasing width.291 segments.sort(key=lambda s: -(s["outerRadius"] - s["innerRadius"]))292 return {293 "provenance": ring.get("provenance", prov_default), "citation": ring.get("citation", ""), "components": comps, "segments": segments,294 "profileStatus": "estimated",295 "profileNote": ("Piecewise-constant radial profile built from the tabulated normal optical depth of each component (single value, or the midpoint of the "296 "published range): opacity = 1 - exp(-tau) at normal incidence. Segments are ordered from the broadest to the narrowest; where they "297 "overlap, the narrower one applies. Real rings have structure at every scale that a table cannot carry."),298 "colourNote": ("No radial colour profile is provided: no public-domain colour profile was integrated. Albedo values, where published, are grey reflectances. "299 "Any hue applied by a renderer is illustrative and must be labelled as such."),300 }301302303def main():304 if len(sys.argv) < 2:305 raise SystemExit(__doc__)306 root = os.path.abspath(sys.argv[1])307 here = os.path.join(root, "DataPipeline", "textures")308309 def load(*parts):310 return json.load(open(os.path.join(here, *parts), encoding="utf-8"))311 facts, assets = load("data", "facts.json"), load("data", "assets.json")312 sources, cur_atm, cur_bodies, cur_ill = load("sources.json"), load("curated", "atmospheres.json"), load("curated", "bodies.json"), load("curated", "illustration.json")313 src_by_id = {s["id"]: s for s in sources["sources"]}314 raw_index = json.load(open(os.path.join(root, "DataPipeline", "raw", "textures", "RAW_INDEX.json")))315316 provenance = [dict((k, v) for k, v in p.items() if v is not None) for p in facts["provenance"]]317 provenance.append({"id": DERIVED_ID, "source": "ORIX Cosmos derivation from GM and mean radius", "version": "1",318 "license": "Derived values; inputs are cited public data.",319 "method": "surface gravity g = GM / R^2 and escape velocity v = sqrt(2 GM / R), with GM and the volumetric mean radius R of the same body from the JPL SSD physical-parameter tables (rotation and oblateness neglected)."})320 provenance += cur_atm["provenance"]321322 def texture_layer(entry):323 src = src_by_id[entry["source"]]324 lic = sources["licences"][src["licence"]]325 mode = entry["mode"]326 layer = {327 "role": entry["role"], "nature": entry["nature"], "description": entry["description"],328 "provenance": src["id"], "credit": src["credit"], "licence": f"{lic['name']}: {lic['summary']}", "licenceURL": lic["url"],329 "sourceTitle": src["title"], "sourceURL": src["page"],330 "projection": {"kind": "equirectangular", "convention": sources["convention"]["id"], "centerLongitudeDegrees": 0.0,331 "longitudeRange": "-180...180, east-positive", "latitude": entry["sourceConvention"]["latitude"]},332 "sourceConvention": {"leftEdgeEastLongitudeDegrees": float(entry["sourceConvention"]["lonLeftEdgeDeg"]),333 "westPositive": bool(entry["sourceConvention"].get("westPositive", False)),334 "latitude": entry["sourceConvention"]["latitude"]},335 "orientationCheck": {"method": entry["orientationCheck"]["method"]},336 "encoding": {"format": "jpeg" if entry["files"][0]["path"].endswith(".jpg") else "png", "description": entry["encoding"],337 "sRGB": mode in ("color", "mono", "hdr", "cloud"), "bitsPerChannel": 16 if mode == "data16" else 8,338 "channels": {"color": 3, "mono": 3, "hdr": 3, "cloud": 4, "normal": 3}.get(mode, 1)},339 "levels": [{"pack": f["pack"], "path": f["path"], "width": f["width"], "height": f["height"], "bytes": f["bytes"], "sha256": f["sha256"]}340 for f in sorted(entry["files"], key=lambda f: f["width"])],341 }342 check = entry["orientationCheck"]343 for key, name in (("detail", "detail"), ("feature", "feature"), ("expectation", "expectation")):344 if check.get(key):345 layer["orientationCheck"][name] = check[key]346 if "lonEastDeg" in check:347 layer["orientationCheck"]["longitudeEastDegrees"] = float(check["lonEastDeg"])348 layer["orientationCheck"]["latitudeDegrees"] = float(check["latDeg"])349 for key in ("wavelengths", "coverageGaps"):350 if entry.get(key):351 layer[key] = entry[key]352 if "validLatitudeRange" in entry:353 v = entry["validLatitudeRange"]354 layer["validLatitudeRange"] = {"northDegrees": float(v["northDeg"]), "southDegrees": float(v["southDeg"]), "fill": v["fill"]}355 if "elevation" in entry:356 e = entry["elevation"]357 layer["elevation"] = {"metersPerUnit": float(e["metersPerUnit"]), "offsetMeters": float(e["offsetMeters"]), "reference": e["reference"]}358 if "normal" in entry:359 layer["normal"] = {"radiusMeters": float(entry["normal"]["radiusMeters"]), "slopeExaggeration": float(entry["normal"]["slopeExaggeration"]),360 "space": entry["normal"]["space"]}361 if "exposure" in entry:362 layer["exposure"] = float(entry["exposure"])363 return layer364365 used_sources = []366 layers_by_body = {}367 for entry in assets["layers"]:368 if not entry["files"]:369 continue370 layers_by_body.setdefault(entry["body"], []).append(texture_layer(entry))371 if entry["source"] not in used_sources:372 used_sources.append(entry["source"])373 for sid in used_sources:374 src = src_by_id[sid]375 lic = sources["licences"][src["licence"]]376 provenance.append({"id": sid, "source": src["title"], "version": raw_index["sources"][sid]["sha256"][:16],377 "retrieved": raw_index["sources"][sid]["retrieved"], "license": f"{lic['name']} ({lic['url']}): {lic['summary']}",378 "url": src["page"], "citation": f"{src['credit']}. {src['citation']}",379 "method": "Converted by DataPipeline/textures (longitude roll to the ORIX map convention, area-average resampling, re-encoding); see Documentation/modules/CosmosPlanetary.md."})380381 atm_specs = {s["body"]: s for s in cur_atm["derived"]}382 bodies = []383 for body_id, body in facts["bodies"].items():384 props = body["properties"]385 physical, orbit, notes = {}, {}, {}386 for key, rec in props.items():387 if key in PHYSICAL:388 name, quantity = PHYSICAL[key]389 physical[name] = measured(rec, quantity)390 notes[name] = annotation(rec)391 elif key in ORBIT:392 name, quantity = ORBIT[key]393 orbit[name] = measured(rec, quantity)394 notes["orbit." + name] = annotation(rec)395 if rec.get("epochJD") is not None:396 orbit["elementsEpochJD"] = rec["epochJD"]397 if "inclination" in props and props["inclination"].get("note"):398 orbit["inclinationReference"] = props["inclination"]["note"]399 if body.get("parent"):400 orbit["primary"] = oid(body["parent"])401 gm_over_r2 = None402 if "gm" in props and "meanRadius" in props:403 gm, r = props["gm"]["value"], props["meanRadius"]["value"]404 gm_over_r2 = gm / r ** 2405 physical["surfaceGravity"] = {"value": gm_over_r2, "status": "computed", "provenance": DERIVED_ID}406 physical["escapeVelocity"] = {"value": {"si": math.sqrt(2 * gm / r)}, "status": "computed", "provenance": DERIVED_ID}407 basis = (f"from GM = {gm:.6g} m^3/s^2 ({props['gm']['provenance']}) and mean radius = {r:.6g} m ({props['meanRadius']['provenance']}); "408 "rotation and oblateness neglected")409 notes["surfaceGravity"] = {"unit": "m/s^2", "note": "g = GM / R^2 " + basis}410 notes["escapeVelocity"] = {"unit": "m/s", "note": "v = sqrt(2 GM / R) " + basis}411 out = {"id": oid(body_id), "name": body["name"], "kind": body["kind"], "physical": physical, "orbit": orbit, "annotations": notes,412 "textures": layers_by_body.get(body_id, [])}413 if body.get("parent"):414 out["parent"] = oid(body["parent"])415 bulk = cur_bodies["bulkType"].get(body_id)416 if bulk:417 out["bulkType"] = bulk418 if body.get("ranges", {}).get("surfaceTemperature"):419 r = body["ranges"]["surfaceTemperature"]420 if r.get("min") is not None and r.get("max") is not None:421 lo = r["min"]["value"] if isinstance(r["min"], dict) else r["min"]422 hi = r["max"]["value"] if isinstance(r["max"], dict) else r["max"]423 out["surfaceTemperatureRange"] = {"low": lo, "high": hi}424 atm = body.get("atmosphere")425 if atm and atm.get("constituents"):426 out["atmosphereComposition"] = {427 "constituents": [dict({"species": c["species"], "fraction": c["fraction"], "minor": bool(c.get("minor", False))},428 **({"published": c["published"]} if c.get("published") else {})) for c in atm["constituents"]],429 "status": "observed", "provenance": atm["provenance"],430 **({"basis": atm["basis"]} if atm.get("basis") else {}), **({"published": atm["published"]} if atm.get("published") else {})}431 if body.get("moonCount"):432 mc = body["moonCount"]433 out["moonCount"] = {"value": mc["value"], "asOf": mc["asOf"], "asOfBasis": mc.get("asOfBasis", ""), "provenance": mc["provenance"]}434 if body_id == cur_atm["earth"]["body"]:435 out["atmosphere"] = earth_atmosphere(cur_atm)436 elif body_id in atm_specs and gm_over_r2 is not None:437 out["atmosphere"] = build_atmosphere(atm_specs[body_id], body, props, cur_atm, gm_over_r2)438 if body_id in facts["rings"]:439 out["rings"] = build_rings(facts["rings"][body_id], "pds-rms-ring-tables")440 if not out["textures"]:441 style = cur_ill["bulkTypeStyles"].get(bulk or "", {"style": "crateredRock", "color": {"r": 0.3, "g": 0.3, "b": 0.3}})442 ill = {"status": "hypothetical", "style": style["style"], "basis": cur_ill["solarSystemRule"]}443 albedo = props.get("geometricAlbedo", {}).get("value")444 if albedo is not None and bulk != "star":445 level = min(max(albedo, 0.04), 0.9)446 ill["baseColor"] = {"r": level, "g": level, "b": level}447 ill["basis"] += f" Grey level = geometric albedo {albedo:g} ({props['geometricAlbedo']['provenance']})."448 else:449 ill["baseColor"] = style["color"]450 ill["basis"] += " No geometric albedo is published in the sources: the neutral colour of the bulk type is used (artistic)."451 out["illustration"] = ill452 if body_id in cur_bodies["noMap"]:453 out["mappingNote"] = cur_bodies["noMap"][body_id]454 bodies.append(out)455456 unavailable = [{"subject": f"{facts['bodies'][b]['name']} ({b}): global surface map", "reason": reason} for b, reason in cur_bodies["noMap"].items() if b in facts["bodies"]]457 unavailable += cur_bodies["otherUnavailable"]458 unavailable += [{"subject": f"{n['body']} {n['role']}", "reason": n["reason"]} for n in assets.get("notBuilt", [])]459 conv = sources["convention"]460 dataset = {461 "format": 1, "version": DATA_VERSION, "generated": datetime.date.today().isoformat(), "factsRetrieved": facts["retrieved"],462 "provenance": provenance,463 "mapConvention": {"id": conv["id"], "projection": conv["projection"], "rows": conv["rows"], "columns": conv["columns"], "uv": conv["uv"],464 "latitude": conv["latitude"], "colour": conv["colour"]},465 "bodies": bodies,466 "skyLayers": layers_by_body.get("sky:icrf", []),467 "skyConvention": ("Sky layers use the same lookup as body maps with right ascension in place of east longitude and declination in place of latitude "468 "(ICRF/J2000): u = 0.5 + RA/360 (RA in -180...180 degrees), v = 0.5 - Dec/180. Viewed as a flat picture the image is therefore the mirror "469 "of the sky as seen from inside the celestial sphere; the published SVS files (centre RA 0h, RA increasing to the left) were mirrored."),470 "unavailable": unavailable,471 "exoplanetIllustration": {"rule": cur_ill["exoplanetRule"], "note": cur_ill["note"],472 "classes": [dict({"id": c["id"], "style": c["style"], "color": c["color"], "basis": c["basis"]},473 **({"maxRadiusEarth": c["maxRadiusEarth"]} if "maxRadiusEarth" in c else {}),474 **({"maxEquilibriumTemperatureKelvin": c["maxEquilibriumTemperatureK"]} if "maxEquilibriumTemperatureK" in c else {}))475 for c in cur_ill["exoplanetClasses"]]},476 }477 text = json.dumps(dataset, indent=1, ensure_ascii=False) + "\n"478 out_json = os.path.join(here, "data", "planetary.json")479 with open(out_json, "w", encoding="utf-8") as f:480 f.write(text)481 compact = json.dumps(dataset, ensure_ascii=False, separators=(",", ":"))482 if '"""#' in compact:483 raise SystemExit('the data contains the sequence """# and cannot be embedded in a raw string literal')484 swift = os.path.join(root, "Packages", "CosmosPlanetary", "Sources", "PlanetaryDataEmbedded.swift")485 with open(swift, "w", encoding="utf-8") as f:486 f.write("// ORIX Cosmos\n// File: Packages/CosmosPlanetary/Sources/PlanetaryDataEmbedded.swift\n"487 "// Description: Generated file — do not edit. The planetary data set (DataPipeline/textures/data/planetary.json, compact form) embedded as a string so that the module needs no resource bundle. Regenerate with DataPipeline/textures/build_planetary.py.\n"488 "//\n// Author: Simon-Pierre Boucher\n// Contact: contact@spboucher.ai\n\n"489 "enum PlanetaryDataEmbedded {\n"490 f" static let version = \"{DATA_VERSION}\"\n"491 " static let json: String = #\"\"\"\n" + compact + "\n\"\"\"#\n}\n")492 with_tex = sum(1 for b in bodies if b["textures"])493 print(f"planetary.json: {len(bodies)} bodies ({with_tex} with texture layers, {sum(1 for b in bodies if 'atmosphere' in b)} with an atmosphere model, "494 f"{sum(1 for b in bodies if 'rings' in b)} with rings), {len(provenance)} provenance records, {len(text) / 1e3:.0f} kB")495496497if __name__ == "__main__":498 main()499