Skip to content

Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.

5.3 KB
Raw Blame
"""
Emit the four SKOS concept schemes (materials, processes, domains, colours) as
Turtle, from the source-of-truth taxonomy modules.

Standards reused (no bespoke class ontology is minted):
  * SKOS            — concept schemes, hierarchy, labels
  * Getty AAT       — verified skos:exactMatch (from data/getty_alignment.json)
  * CIDOC-CRM       — material concepts are also typed crm:E57_Material,
                      process concepts crm:E55_Type, so the taxonomy plugs
                      straight into the Linked Art / CIDOC-CRM instance graph.

Only two local terms are introduced, and only because no standard vocabulary
carries them: mod:thermalBehaviour and mod:origin (polymer-science facets).
They are declared as annotation properties in ontology/facets.ttl.
"""
import json, os, sys

sys.path.insert(0, os.path.dirname(__file__))
import materials_taxonomy as M
import process_taxonomy as P
import concept_taxonomy as D

ROOT = os.path.dirname(os.path.dirname(__file__))
BASE = "https://ontology.tesseract.academy/modip/"
NS = {
    "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#",
    "skos": "http://www.w3.org/2004/02/skos/core#",
    "dct": "http://purl.org/dc/terms/",
    "rdfs": "http://www.w3.org/2000/01/rdf-schema#",
    "crm": "http://www.cidoc-crm.org/cidoc-crm/",
    "aat": "http://vocab.getty.edu/aat/",
    "mod": BASE + "prop/",
    "mat": BASE + "materials/",
    "proc": BASE + "processes/",
    "dom": BASE + "domains/",
    "col": BASE + "colours/",
}


def esc(s):
    return s.replace("\\", "\\\\").replace('"', '\\"')


def header():
    lines = ["# Generated by build_taxonomies.py — do not edit by hand.",
             "# CC BY 4.0 (see LICENSE). Getty AAT alignments © J. Paul Getty Trust (ODC-By)."]
    for p, u in NS.items():
        lines.append(f"@prefix {p}: <{u}> .")
    lines.append("")
    return "\n".join(lines)


def emit_scheme(concepts, prefix, scheme_id, scheme_title, resolve_mod,
                getty=None, crm_type=None, resolve_fn=None):
    """concepts: dict id->{pref,broader,alt,...}; returns TTL string."""
    getty = getty or {}
    out = [header()]
    scheme_uri = f"{prefix}:{scheme_id}"
    out.append(f"{prefix}:{scheme_id} a skos:ConceptScheme ;")
    out.append(f'    dct:title "{esc(scheme_title)}"@en ;')
    out.append(f'    dct:license <https://creativecommons.org/licenses/by/4.0/> .')
    out.append("")
    for cid, c in concepts.items():
        subj = f"{prefix}:{cid}"
        out.append(f"{subj} a skos:Concept" + (f", {crm_type}" if crm_type else "") + " ;")
        out.append(f'    skos:prefLabel "{esc(c["pref"])}"@en ;')
        for a in dict.fromkeys(c.get("alt", [])):
            if a.lower() != c["pref"].lower():
                out.append(f'    skos:altLabel "{esc(a)}"@en ;')
        if c.get("broader"):
            out.append(f"    skos:broader {prefix}:{c['broader']} ;")
        else:
            out.append(f"    skos:topConceptOf {scheme_uri} ;")
        # polymer-science facets (materials only)
        if resolve_mod:
            if c.get("thermal"):
                out.append(f'    mod:thermalBehaviour "{c["thermal"]}" ;')
            if c.get("origin"):
                out.append(f'    mod:origin "{c["origin"]}" ;')
        if c.get("note"):
            out.append(f'    skos:scopeNote "{esc(c["note"])}"@en ;')
        g = getty.get(cid)
        if g:
            out.append(f"    skos:exactMatch <{g['aat']}> ;")
        out.append(f"    skos:inScheme {scheme_uri} .")
        out.append("")
    return "\n".join(out)


def main():
    getty = {}
    gp = os.path.join(ROOT, "data", "getty_alignment.json")
    if os.path.exists(gp):
        getty = json.load(open(gp))
    os.makedirs(os.path.join(ROOT, "ontology"), exist_ok=True)

    ttl = emit_scheme(M.CONCEPTS, "mat", "materials",
                      "MoDiP Materials Taxonomy", resolve_mod=True,
                      getty=getty, crm_type="crm:E57_Material")
    open(os.path.join(ROOT, "ontology", "materials.ttl"), "w").write(ttl)

    ttl = emit_scheme(P.PROCESSES, "proc", "processes",
                      "MoDiP Manufacturing-Process Taxonomy", resolve_mod=False,
                      crm_type="crm:E55_Type")
    open(os.path.join(ROOT, "ontology", "processes.ttl"), "w").write(ttl)

    ttl = emit_scheme(D.DCONCEPTS, "dom", "domains",
                      "MoDiP Domain-Concept Taxonomy", resolve_mod=False,
                      crm_type="crm:E55_Type")
    open(os.path.join(ROOT, "ontology", "domains.ttl"), "w").write(ttl)

    # facets declaration
    facets = header() + """
mod:thermalBehaviour a rdf:Property ;
    rdfs:label "thermal behaviour"@en ;
    rdfs:comment "Polymer-science facet: thermoplastic | thermoset | elastomer | tpe. Local extension; no standard vocabulary carries this facet."@en ;
    rdfs:domain crm:E57_Material .

mod:origin a rdf:Property ;
    rdfs:label "material origin"@en ;
    rdfs:comment "Polymer-science facet: synthetic | semisynthetic | biobased | natural. Local extension."@en ;
    rdfs:domain crm:E57_Material .
"""
    open(os.path.join(ROOT, "ontology", "facets.ttl"), "w").write(facets)

    print(f"materials: {len(M.CONCEPTS)} concepts, {sum(1 for c in M.CONCEPTS if c in getty)} Getty-aligned")
    print(f"processes: {len(P.PROCESSES)} concepts")
    print(f"domains:   {len(D.DCONCEPTS)} concepts")
    print(f"Getty AAT alignments: {len(getty)}")


if __name__ == "__main__":
    main()