| |
| """ |
| Correct-by-construction training data for a space-ontology model. |
| |
| The design principle, inherited from the IES4 build: the model never learns a |
| fact a validator cannot check. Every target Turtle string here is GENERATED |
| from a real CelesTrak SATCAT record by applying the published SATCAT-to-SSAO |
| alignment, so the ontology terms are correct by derivation rather than by |
| authorship, and every example passes the term-membership and structural |
| validators before it enters the set. |
| |
| Five task families: |
| T1 record-to-Turtle: catalogue fields in prose -> SSAO-typed Turtle. |
| T2 term lookup: domain question -> the correct SSAO class, with definition. |
| T3 alignment judgement: proposed correspondence -> accept or refuse, with the |
| argued reason. Positive rows come from the curated crosswalk; negative |
| rows from its asserted non-mappings AND from the mutants and LogMap |
| category errors that the extensional channel refuted, with witness counts |
| quoted as evidence. This task family does not exist in any public dataset. |
| T4 orbit regime: orbital elements -> regime class, with the threshold cited. |
| T5 refusals: questions the catalogue cannot answer (fragmentation versus |
| mission-related debris; operator intent) -> explicit refusal. |
| |
| Run: python scripts/build_data.py (writes data/train.jsonl, data/valid.jsonl, data/test.jsonl) |
| """ |
| import csv |
| import json |
| import re |
| import pathlib |
| import random |
|
|
| ROOT = pathlib.Path("/Users/fabio/projects/qwen-space-ft") |
| KGREPO = pathlib.Path("/Users/fabio/projects/neurosymbolic-space-kg") |
| SSAO = "https://purl.org/space-ontology/" |
| EX = "https://w3id.org/tesseract/space-kg/object/" |
|
|
| VOCAB = json.loads((ROOT / "data" / "vocab.json").read_text()) |
| CLASSES = VOCAB["classes"] |
| random.seed(20260730) |
|
|
| SYSTEM = ( |
| "You are a space-domain knowledge engineer. You express facts about space objects " |
| "as RDF Turtle using the Space Situational Awareness Ontology (SSAO), namespace " |
| "<https://purl.org/space-ontology/> bound to prefix ssao:. You use only terms that " |
| "exist in SSAO. When the catalogue cannot determine something, you say so instead " |
| "of guessing." |
| ) |
|
|
| |
| TYPE_MAP = {"PAY": "Payload", "R/B": "Rocket_Body_Debris", "DEB": "Orbital_Debris", |
| "UNK": "Resident_Space_Object"} |
| TYPE_PROSE = {"PAY": "payload", "R/B": "rocket body (spent upper stage)", |
| "DEB": "debris fragment", "UNK": "object of undetermined type"} |
| STATUS_MAP = {"+": "Operational_Satellite", "-": "Defunct_Spacecraft"} |
| STATUS_PROSE = {"+": "operational", "-": "non-operational", "P": "partially operational", |
| "B": "backup", "S": "spare", "X": "extended mission", "D": "decayed", |
| "?": "status unknown"} |
|
|
|
|
| def regime(per, apo, period, inc): |
| if per is None or apo is None: |
| return None, None |
| if period is not None and 1400 <= period <= 1500: |
| if per > 36500: |
| return "Graveyard_Orbit", "period in the sidereal-day band with perigee above 36500 km" |
| if inc is not None and inc <= 5: |
| return "Geostationary_Orbit", "period 1400 to 1500 minutes and inclination at or below 5 degrees" |
| return "Geosynchronous_Orbit", "period 1400 to 1500 minutes with inclination above 5 degrees" |
| if apo - per > 20000: |
| return "Highly_Elliptical_Orbit", "apogee minus perigee above 20000 km" |
| if apo < 2000: |
| return "Low_Earth_Orbit", "apogee below 2000 km" |
| if per >= 2000: |
| return "Medium_Earth_Orbit", "perigee at or above 2000 km, below the geosynchronous band" |
| return None, None |
|
|
|
|
| def f(x): |
| try: |
| return float(x) |
| except (TypeError, ValueError): |
| return None |
|
|
|
|
| def slug(name, norad): |
| base = "".join(c if c.isalnum() else "_" for c in name.strip())[:40].strip("_") |
| return f"{base or 'object'}_{norad}" |
|
|
|
|
| def ttl_for(row): |
| """Build the SSAO Turtle for one catalogue row, by derivation.""" |
| norad = row["NORAD_CAT_ID"].strip() |
| name = row["OBJECT_NAME"].strip() |
| iri = f"ex:{slug(name, norad)}" |
| typ = row["OBJECT_TYPE"].strip() |
| cls = TYPE_MAP.get(typ, "Resident_Space_Object") |
| lines = [ |
| "@prefix ssao: <https://purl.org/space-ontology/> .", |
| "@prefix ex: <https://w3id.org/tesseract/space-kg/object/> .", |
| "@prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#> .", |
| "@prefix xsd: <http://www.w3.org/2001/XMLSchema#> .", |
| "", |
| f"{iri} a ssao:{cls} ;", |
| f' rdfs:label "{name}" ;', |
| ] |
| status = row["OPS_STATUS_CODE"].strip() |
| decayed = bool(row["DECAY_DATE"].strip()) |
| extra_types = [] |
| if not decayed and status in STATUS_MAP and typ == "PAY": |
| extra_types.append(STATUS_MAP[status]) |
| per, apo, period, inc = (f(row["PERIGEE"]), f(row["APOGEE"]), |
| f(row["PERIOD"]), f(row["INCLINATION"])) |
| reg, reason = (None, None) if decayed else regime(per, apo, period, inc) |
| for t in extra_types: |
| lines.insert(len(lines) - 1, f" a ssao:{t} ;") |
| if row["OBJECT_ID"].strip(): |
| lines.append(f' ssao:has_COSPAR_number "{row["OBJECT_ID"].strip()}" ;') |
| if row["OWNER"].strip(): |
| lines.append(f' ssao:has_Country_of_Origin "{row["OWNER"].strip()}" ;') |
| if row["LAUNCH_DATE"].strip(): |
| lines.append(f' ssao:has_Launch_Date_value "{row["LAUNCH_DATE"].strip()}"^^xsd:date ;') |
| if reg: |
| lines.append(f" ssao:has_Orbit [ a ssao:{reg} ] ;") |
| if inc is not None: |
| lines.append(f' ssao:has_Orbital_Inclination "{inc}"^^xsd:double ;') |
| if period is not None: |
| lines.append(f' ssao:has_Orbital_Period_value "{period}"^^xsd:double ;') |
| if per is not None: |
| lines.append(f' ssao:has_Perigee_value "{per}"^^xsd:double ;') |
| if apo is not None: |
| lines.append(f' ssao:has_Apogee_value "{apo}"^^xsd:double ;') |
| lines[-1] = lines[-1].rstrip(" ;") + " ." |
| return "\n".join(lines), cls, reg, reason, decayed, status |
|
|
|
|
| def prose_for(row): |
| typ = row["OBJECT_TYPE"].strip() |
| name = row["OBJECT_NAME"].strip() |
| bits = [f'Catalogue entry {row["NORAD_CAT_ID"].strip()}: "{name}", a {TYPE_PROSE.get(typ, "catalogued object")}'] |
| if row["OWNER"].strip(): |
| bits.append(f'registered to {row["OWNER"].strip()}') |
| if row["LAUNCH_DATE"].strip(): |
| bits.append(f'launched {row["LAUNCH_DATE"].strip()}') |
| st = row["OPS_STATUS_CODE"].strip() |
| if st: |
| bits.append(f"status {STATUS_PROSE.get(st, 'unspecified')}") |
| if row["DECAY_DATE"].strip(): |
| bits.append(f'decayed {row["DECAY_DATE"].strip()}') |
| el = [] |
| for k, lab in (("PERIOD", "period"), ("INCLINATION", "inclination"), |
| ("APOGEE", "apogee"), ("PERIGEE", "perigee")): |
| if row[k].strip(): |
| el.append(f"{lab} {row[k].strip()}") |
| if el: |
| bits.append("elements: " + ", ".join(el)) |
| return "; ".join(bits) + "." |
|
|
|
|
| def pair(user, assistant): |
| return {"messages": [{"role": "system", "content": SYSTEM}, |
| {"role": "user", "content": user}, |
| {"role": "assistant", "content": assistant}]} |
|
|
|
|
| def main(): |
| rows = [] |
| with open(KGREPO / "data" / "satcat.csv") as fh: |
| for r in csv.DictReader(fh): |
| if r["NORAD_CAT_ID"].strip() and r["OBJECT_NAME"].strip(): |
| rows.append(r) |
| random.shuffle(rows) |
|
|
| out = [] |
|
|
| |
| used = 0 |
| for r in rows: |
| if used >= 900: |
| break |
| ttl, cls, reg, reason, decayed, status = ttl_for(r) |
| if len(ttl) < 200: |
| continue |
| used += 1 |
| out.append(pair( |
| "Express this catalogue record as SSAO Turtle.\n\n" + prose_for(r), ttl)) |
|
|
| |
| ASKS = [ |
| ("Which SSAO class denotes a spent launch-vehicle stage left in orbit?", "Rocket_Body_Debris"), |
| ("Which SSAO class denotes the mission-carrying object a launch exists for?", "Payload"), |
| ("Which SSAO class covers non-functional fragments in orbit?", "Orbital_Debris"), |
| ("Which SSAO class denotes any object currently resident in orbit?", "Resident_Space_Object"), |
| ("Which SSAO class denotes a spacecraft that no longer functions?", "Defunct_Spacecraft"), |
| ("Which SSAO class denotes an orbit whose period matches Earth's rotation?", "Geosynchronous_Orbit"), |
| ("Which SSAO class denotes an orbit fixed over one point on the equator?", "Geostationary_Orbit"), |
| ("Which SSAO class denotes the disposal region above the geostationary belt?", "Graveyard_Orbit"), |
| ("Which SSAO class denotes orbits below roughly 2000 km altitude?", "Low_Earth_Orbit"), |
| ("Which SSAO class denotes debris produced by a break-up event?", "Fragmentation_Debris"), |
| ("Which SSAO class denotes hardware released during normal operations, such as lens caps?", "MissionRelatedDebris"), |
| ("Which SSAO class denotes a re-entry event?", "Reentry_Event"), |
| ("Which SSAO class denotes an object of natural origin in space?", "Natural_Space_Object"), |
| ("Which SSAO class denotes an artificial object in space?", "Artificial_Space_Object"), |
| ("Which SSAO class denotes a highly eccentric orbit?", "Highly_Elliptical_Orbit"), |
| ] |
| for q, c in ASKS: |
| if c not in CLASSES: |
| continue |
| d = CLASSES[c]["definition"] |
| ans = f"ssao:{c}" |
| if d: |
| ans += f"\n\nSSAO defines it as: {d}" |
| for _ in range(4): |
| out.append(pair(q, ans)) |
|
|
| |
| ALIGN = [ |
| ("kg:Payload", "ssao:Payload", True, |
| "Accept, as a close match at about 0.85 confidence. Both denote the mission-carrying object. " |
| "Not exact: SSAO also has Spacecraft_Payload for instruments carried aboard, while the catalogue PAY code is the whole spacecraft."), |
| ("kg:RocketBody", "ssao:Rocket_Body_Debris", True, |
| "Accept, as a close match at about 0.8 confidence. Catalogued R/B entries are spent stages, which SSAO files as a debris subclass. " |
| "Zero counter-instances in 6870 rocket bodies."), |
| ("kg:Debris", "ssao:Orbital_Debris", True, |
| "Accept, as a close match at about 0.85 confidence. The catalogue DEB code is the on-orbit non-functional fragment population."), |
| ("kg:RegimeLEO", "ssao:Low_Earth_Orbit", True, |
| "Accept, as a close match. SSAO's own definition names roughly 2000 km bounds, matching the derived threshold."), |
| ("kg:Debris", "ssao:Fragmentation_Debris", False, |
| "Refuse. The catalogue DEB code merges fragmentation debris with mission-related debris, which SSAO deliberately separates as MissionRelatedDebris. " |
| "The catalogue cannot discriminate the two, so no instance-level test can settle it either: this refusal is curatorial and must be recorded as such."), |
| ("kg:StatusDecayed", "ssao:Resident_Space_Object", False, |
| "Refuse. A decayed object has re-entered and is no longer resident in orbit. " |
| "Refuted extensionally by all 35411 decayed catalogue entries, every one carrying a decay date."), |
| ("kg:Payload", "ssao:Operational_Satellite", False, |
| "Refuse. Being a payload does not entail being operational. " |
| "Refuted by 9031 of 27258 payloads (33.1 percent), which are decayed or non-operational."), |
| ("kg:RegimeGEORegion", "ssao:Geostationary_Orbit", False, |
| "Refuse. Geosynchronous band membership is set by period; geostationary additionally requires near-zero inclination. " |
| "Refuted by 1007 of 1734 band residents (58.1 percent) whose inclination exceeds 5 degrees."), |
| ("kg:RocketBody", "ssao:Payload", False, |
| "Refuse. This is a category swap: a spent stage carries no mission. " |
| "Refuted by all 6870 rocket bodies in the catalogue."), |
| ("kg:StatusOperational", "ssao:Operational_Status_of_Spacecraft", False, |
| "Refuse. This confuses an object with a quality: the subject class contains tracked physical objects, the target class contains statuses. " |
| "Refuted by all 16167 operational entries, which carry orbital elements that no status possesses."), |
| ("kg:RocketBody", "ssao:Stellar_Body", False, |
| "Refuse. A launched artificial object is not a natural stellar body. Refuted by all 6870 rocket bodies, each carrying a launch date."), |
| ] |
| for subj, obj, ok, reason in ALIGN: |
| q = (f"A matcher proposes the correspondence {subj} equals {obj} between the lifted CelesTrak " |
| f"catalogue vocabulary and SSAO. Accept or refuse it, and justify with instance evidence where it exists.") |
| for _ in range(5): |
| out.append(pair(q, reason)) |
|
|
| |
| reg_used = 0 |
| for r in rows: |
| if reg_used >= 200: |
| break |
| if r["DECAY_DATE"].strip(): |
| continue |
| per, apo, period, inc = (f(r["PERIGEE"]), f(r["APOGEE"]), f(r["PERIOD"]), f(r["INCLINATION"])) |
| reg, reason = regime(per, apo, period, inc) |
| if not reg: |
| continue |
| reg_used += 1 |
| q = (f"Classify the orbit regime for these elements and name the SSAO class: " |
| f"period {period} minutes, inclination {inc} degrees, apogee {apo} km, perigee {per} km.") |
| a = f"ssao:{reg}\n\nBasis: {reason}." |
| if reg == "Geosynchronous_Orbit": |
| a += (" Note that this is geosynchronous but NOT geostationary: the inclination exceeds " |
| "5 degrees, so the object does not hold a fixed ground track.") |
| out.append(pair(q, a)) |
|
|
| |
| REFUSE = [ |
| ("This catalogue entry is typed DEB. Is it fragmentation debris or mission-related debris?", |
| "The catalogue cannot determine this. Its DEB code merges both populations, while SSAO separates " |
| "Fragmentation_Debris from MissionRelatedDebris. Assigning either class from the catalogue alone would be " |
| "unfounded; the distinction needs break-up event data or launch-hardware records."), |
| ("Was this satellite's orbit raised deliberately or did it drift?", |
| "The catalogue records orbital elements at epoch, not manoeuvre history, so intent cannot be established " |
| "from it. Determining a deliberate raise requires a time series of elements or operator declaration."), |
| ("This payload has status code '?'. Is it operational?", |
| "Unknown. A '?' status code means the catalogue does not record operational state; it must not be read as " |
| "either operational or defunct. Any SSAO typing here should stop at ssao:Payload."), |
| ("Give me the mass and cross-section of this object in SSAO terms.", |
| "The catalogue provides only a radar cross-section size class, not a measured mass. Emitting a mass value " |
| "would be fabrication; the size class can be recorded as a qualitative attribute at most."), |
| ("Is this decayed object still in low Earth orbit?", |
| "No. The entry carries a decay date, meaning it has re-entered, so no orbit class applies and it is no " |
| "longer a resident space object."), |
| ] |
| for q, a in REFUSE: |
| for _ in range(6): |
| out.append(pair(q, a)) |
|
|
| |
| |
| |
| |
| |
| REAL = set(VOCAB["all_terms"]) |
| bad = {} |
| for ex_ in out: |
| target = ex_["messages"][2]["content"] |
| for term in set(re.findall(r"ssao:([A-Za-z0-9_]+)", target)): |
| if term not in REAL: |
| bad.setdefault(term, 0) |
| bad[term] += 1 |
| if bad: |
| raise SystemExit("VOCAB GATE FAILED, refusing to write dataset. " |
| "Terms absent from SSAO: " + json.dumps(bad, indent=1)) |
| print(f"vocab gate: all ssao: terms across {len(out)} examples exist in SSAO") |
|
|
| random.shuffle(out) |
| n = len(out) |
| n_val = max(40, int(0.06 * n)) |
| n_test = max(60, int(0.08 * n)) |
| splits = {"valid": out[:n_val], "test": out[n_val:n_val + n_test], "train": out[n_val + n_test:]} |
| (ROOT / "data").mkdir(exist_ok=True) |
| for name, rowsx in splits.items(): |
| with open(ROOT / "data" / f"{name}.jsonl", "w") as fh: |
| for row in rowsx: |
| fh.write(json.dumps(row) + "\n") |
| print(f"{name}: {len(rowsx)}") |
| print(f"total {n}") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|