Plan, apply and roll back changes to a production ontology, with a blast radius report and a proof an auditor can re-check.
Rust ai-nativedescription-logicsformal-verificationinfrastructure-as-codeisabelle-languageknowledge-graphleanlean4mcpmcp-serverontologyowlowl2reasoningrustshaclsparqltheorem-proving
{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"# bio-kg-triage: an ontology-grounded biomedical KG, validated\n",
"\n",
"Every edge in this knowledge graph is typed with the real **Biolink Model** vocabulary and passes a **closed-world vocabulary gate** before it enters the graph, the same gate benchmarked on schema.org and IES4 in [onto-correctness-bench](https://gov.tesseract.academy/research/ontology-correctness-benchmark). Data is live from the **Open Targets Platform**.\n",
"\n",
"**Press Runtime then Run all.** It builds a gene-disease KG from real Open Targets associations, then shows the grounded KG has 0 vocabulary violations while an ungrounded variant (one fabricated Biolink predicate) slips past SHACL but is caught by the gate.\n",
"\n",
"Code: https://github.com/fabio-rovai/open-ontologies/tree/main/case-studies/bio-kg-triage\n"
]
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"!pip -q install rdflib pyshacl requests\n"
]
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"VOCAB_URL = \"https://raw.githubusercontent.com/fabio-rovai/open-ontologies/main/case-studies/bio-kg-triage/data/biolink_vocab.json\"\n",
"import json, requests, rdflib\n",
"from rdflib import Graph, RDF, RDFS, URIRef, Literal\n",
"from rdflib.namespace import SH\n",
"from pyshacl import validate\n",
"\n",
"BL = \"https://w3id.org/biolink/vocab/\"\n",
"V = requests.get(VOCAB_URL, timeout=60).json()\n",
"DECLARED = set(V[\"declared\"]); POLICED = V[\"policed\"]\n",
"print(\"Biolink declared terms:\", len(DECLARED))\n",
"\n",
"TARGETS = {\"ENSG00000146648\":\"EGFR\",\"ENSG00000141510\":\"TP53\",\"ENSG00000133703\":\"KRAS\",\n",
" \"ENSG00000012048\":\"BRCA1\",\"ENSG00000171862\":\"PTEN\",\"ENSG00000157764\":\"BRAF\",\n",
" \"ENSG00000171094\":\"ALK\",\"ENSG00000136997\":\"MYC\"}\n",
"OT = \"https://api.platform.opentargets.org/api/v4/graphql\"\n",
"Q = '{ target(ensemblId:\"ID\"){ approvedSymbol associatedDiseases(page:{index:0,size:5}){ rows{ disease{ id name } score } } } }'\n",
"rows = []\n",
"for ens, sym in TARGETS.items():\n",
" r = requests.post(OT, json={\"query\": Q.replace(\"ID\", ens)}, timeout=60).json()\n",
" t = (r.get(\"data\") or {}).get(\"target\") or {}\n",
" for a in (t.get(\"associatedDiseases\") or {}).get(\"rows\", []):\n",
" rows.append({\"ensembl\":ens, \"symbol\":t.get(\"approvedSymbol\",sym),\n",
" \"disease_id\":a[\"disease\"][\"id\"], \"disease_name\":a[\"disease\"][\"name\"], \"score\":round(float(a[\"score\"]),4)})\n",
"print(\"fetched\", len(rows), \"real gene-disease associations from Open Targets\")\n",
"\n",
"def in_pol(i): return any(str(i).startswith(p) for p in POLICED)\n",
"def gate(g):\n",
" f = set()\n",
" for s,p,o in g:\n",
" if in_pol(p) and str(p) not in DECLARED: f.add(str(p))\n",
" if p==RDF.type and isinstance(o,URIRef) and in_pol(o) and str(o) not in DECLARED: f.add(str(o))\n",
" return sorted(f)\n",
"def dis_iri(d):\n",
" return \"http://purl.obolibrary.org/obo/\"+d if d.startswith((\"MONDO_\",\"HP_\",\"GO_\")) else \"https://identifiers.org/\"+d.replace(\"_\",\":\",1).lower()\n",
"def build(pred):\n",
" g = Graph()\n",
" for r in rows:\n",
" ge = URIRef(\"https://identifiers.org/ensembl:\"+r[\"ensembl\"]); di = URIRef(dis_iri(r[\"disease_id\"]))\n",
" g.add((ge,RDF.type,URIRef(BL+\"Gene\"))); g.add((ge,RDFS.label,Literal(r[\"symbol\"])))\n",
" g.add((di,RDF.type,URIRef(BL+\"Disease\"))); g.add((di,RDFS.label,Literal(r[\"disease_name\"])))\n",
" g.add((ge,URIRef(pred),di))\n",
" return g\n",
"def shapes():\n",
" s = Graph(); sh = URIRef(\"https://ex/shape\")\n",
" s.add((sh,RDF.type,SH.NodeShape)); s.add((sh,SH.targetClass,URIRef(BL+\"Gene\")))\n",
" b = URIRef(\"https://ex/shape/l\"); s.add((sh,SH.property,b)); s.add((b,SH.path,RDFS.label)); s.add((b,SH.minCount,Literal(1)))\n",
" return s\n",
"def evalg(name, g):\n",
" c,_,_ = validate(g, shacl_graph=shapes(), inference=\"none\")\n",
" fl = gate(g)\n",
" print(name, \"triples=\", len(g), \" SHACL conforms=\", str(c).lower(), \" closed-world violations=\", len(fl), fl)\n",
"\n",
"evalg(\"grounded \", build(BL+\"gene_associated_with_condition\")) # real Biolink predicate\n",
"evalg(\"ungrounded\", build(BL+\"associated_with_disease\")) # fabricated, not declared\n"
]
},
{
"cell_type": "code",
"metadata": {},
"execution_count": null,
"outputs": [],
"source": [
"print(\"Top gene-disease hypotheses by Open Targets score (each a validated Biolink triple):\\n\")\n",
"for i, r in enumerate(sorted(rows, key=lambda x: x[\"score\"], reverse=True)[:10], 1):\n",
" print(str(i).rjust(2) + \". \" + r[\"symbol\"].ljust(6) + \" -> \" + r[\"disease_name\"].ljust(45) + \" \" + str(r[\"score\"]))\n"
]
},
{
"cell_type": "markdown",
"metadata": {},
"source": [
"---\n",
"The grounded KG has **0 SHACL and 0 closed-world violations**; the ungrounded variant passes SHACL but the gate catches the fabricated predicate. Read the write-up: https://gov.tesseract.academy/research/ontology-grounded-biomedical-kg\n",
"\n",
"Built by Tesseract Academy.\n"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"name": "python3"
},
"language_info": {
"name": "python"
},
"colab": {
"provenance": []
}
},
"nbformat": 4,
"nbformat_minor": 5
}