File size: 16,878 Bytes
68f8a08
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#!/usr/bin/env python3
"""
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."
)

# ---- the published alignment: catalogue kind/status/regime -> SSAO class ----
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 = []

    # ---- T1 record -> Turtle (the bulk) ----
    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))

    # ---- T2 term lookup ----
    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))

    # ---- T3 alignment judgement (unique to this dataset) ----
    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))

    # ---- T4 orbit regime from elements ----
    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))

    # ---- T5 refusals ----
    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))

    # ---- FAIL-CLOSED VOCABULARY GATE ----
    # Every ssao: term appearing in any target must exist in the real ontology.
    # This exists because an earlier version of this script invented camelCase
    # property names (hasOrbit, hasInclination) that SSAO does not define; the
    # whole point of the project is that such terms must be impossible to ship.
    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()