ssao-space-instruct / scripts /extract_vocab.py
fabsssss's picture
Correct-by-construction SSAO instruct data with fail-closed vocabulary gate, plus baseline and tuned eval traces
68f8a08 verified
Raw
History Blame Contribute Delete
2.91 kB
#!/usr/bin/env python3
"""Extract the authoritative SSAO term set: the membership oracle for validation.
The Space Situational Awareness Ontology (Rovetto, as vendored by the NASA
mission-viz project) is the target vocabulary. Every ssao: term the model emits
must exist here, or it is a hallucination by construction.
"""
import json
import pathlib
from rdflib import Graph, RDF, RDFS, OWL, Namespace
ROOT = pathlib.Path("/Users/fabio/projects/qwen-space-ft")
KGREPO = pathlib.Path("/Users/fabio/projects/neurosymbolic-space-kg")
SSAO = "https://purl.org/space-ontology/"
SKOS = Namespace("http://www.w3.org/2004/02/skos/core#")
g = Graph()
g.parse(KGREPO / "ontology" / "SSAO_Rovetto.owl", format="turtle")
def local(u):
s = str(u)
return s.split("#")[-1].split("/")[-1]
def in_ns(u):
return str(u).startswith(SSAO)
classes = {}
for s in set(g.subjects(RDF.type, OWL.Class)) | set(g.subjects(RDF.type, RDFS.Class)):
if not in_ns(s):
continue
ln = local(s)
label = g.value(s, RDFS.label)
defn = g.value(s, SKOS.definition) or g.value(s, RDFS.comment)
supers = [local(o) for o in g.objects(s, RDFS.subClassOf) if in_ns(o)]
classes[ln] = {
"label": str(label) if label else ln.replace("_", " "),
"definition": str(defn)[:400] if defn else "",
"subClassOf": supers,
}
props = {}
for s in (set(g.subjects(RDF.type, OWL.ObjectProperty))
| set(g.subjects(RDF.type, OWL.DatatypeProperty))
| set(g.subjects(RDF.type, RDF.Property))):
if not in_ns(s):
continue
ln = local(s)
props[ln] = {
"definition": str(g.value(s, SKOS.definition) or g.value(s, RDFS.comment) or "")[:300],
"domain": [local(o) for o in g.objects(s, RDFS.domain) if in_ns(o)],
"range": [local(o) for o in g.objects(s, RDFS.range) if in_ns(o)],
}
# authoritative membership set: every ssao-namespaced term appearing anywhere
all_terms = sorted({local(n) for t in g for n in t if in_ns(n)})
# our own lifted catalogue vocabulary (the source side of the published alignment)
kgv = Graph()
kgv.parse(KGREPO / "kg" / "out" / "satcat-vocab.ttl", format="turtle")
KGNS = "https://w3id.org/tesseract/space-kg/"
kg_terms = sorted({local(s) for s in kgv.subjects(RDF.type, OWL.Class)
if str(s).startswith(KGNS)})
vocab = {
"ssao_namespace": SSAO,
"kg_namespace": KGNS,
"classes": classes,
"properties": props,
"class_names": sorted(classes),
"property_names": sorted(props),
"all_terms": all_terms,
"kg_class_names": kg_terms,
}
(ROOT / "data").mkdir(exist_ok=True)
(ROOT / "data" / "vocab.json").write_text(json.dumps(vocab, indent=1))
print(f"SSAO: {len(classes)} classes, {len(props)} properties, {len(all_terms)} terms total")
print(f"lifted catalogue vocabulary: {len(kg_terms)} classes")
print("sample classes:", ", ".join(sorted(classes)[:8]))