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
bio-kg-triage: add AMR pathogen linkage (CARD + NCBITaxon)
FABIOTESS9a98c0a41369
diff --git a/case-studies/bio-kg-triage/.gitignore b/case-studies/bio-kg-triage/.gitignoreindex 32c6b30f..2f833a01 100644--- a/case-studies/bio-kg-triage/.gitignore+++ b/case-studies/bio-kg-triage/.gitignore@@ -4,3 +4,10 @@ __pycache__/data/biolink-model.yamldata/aro.obodata/*.obo+data/nodes.dmp+data/merged.dmp+data/delnodes.dmp+data/taxdump.tar.gz+data/card-data.tar.bz2+data/card/+build/pathogen-kg-grounded.ttldiff --git a/case-studies/bio-kg-triage/BUILD_REPORT.md b/case-studies/bio-kg-triage/BUILD_REPORT.mdindex 8fd189ed..13fd9f34 100644--- a/case-studies/bio-kg-triage/BUILD_REPORT.md+++ b/case-studies/bio-kg-triage/BUILD_REPORT.md@@ -11,6 +11,8 @@ in `results/` is produced by `src/pipeline.py`; none is hand-entered.| Open Targets Platform | api.platform.opentargets.org/api/v4/graphql (live) | structured gene-disease associations + scores || PubTator3 (NLM) | ncbi.nlm.nih.gov/research/pubtator3-api (live) | literature-extracted gene-disease relations || CARD / ARO | purl.obolibrary.org/obo/aro.obo (~76 k lines) | AMR vocabulary + real "confers resistance to" relationships |+| CARD data | card.mcmaster.ca/latest/data (card.json, 4.6 MB tar) | resistance-gene to organism (NCBI taxid) links |+| NCBI taxonomy | ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz (75 MB) | current valid taxids (nodes.dmp) + retired ids (merged.dmp) |Fetched 2026-07-20. Targets queried: EGFR, TP53, KRAS, BRCA1, PTEN, BRAF, ALK, MYC (8 real humangenes by Ensembl id); top 5 associated diseases each -> 40 associations.@@ -52,6 +54,18 @@ namespace. Grounded KG 1,283 triples, **0** violations; the ungrounded twin poinfabricated `ARO_9999999` and the gate rejects it. This shows the gate generalising to a thirdbiomedical ontology.+## AMR pathogen linkage (`src/pathogen.py`)++CARD's `card.json` records, for each resistance determinant, the organisms its reference sequences+come from (NCBI taxid). We build 6,404 `gene in_taxon organism` edges over 740 organisms and police+three namespaces at once: ARO (the gene) against ARO's terms, Biolink (the `in_taxon` predicate and+the `Gene`/`OrganismTaxon` types) against Biolink, and NCBITaxon (the organism) against the current+NCBI taxonomy (2,871,791 taxids parsed from `nodes.dmp`). SHACL conforms. The gate catches an+injected fabricated taxid (`NCBITaxon_99999999`). Separately, run against the current taxonomy, it+flags 17 organism ids in CARD as not current; cross-checking `merged.dmp` confirms all 17 are+retired-and-merged taxa (0 unexplained), so this is a data-freshness catch, not fabrication, and it+is a real signal SHACL and a well-formedness check both miss.+## The structured result, precisely- Grounded KG (284 triples): SHACL `conforms=true`, **0** closed-world violations.@@ -62,10 +76,10 @@ biomedical ontology.## Limits of the claim (do not overstate)-1. **AMR pathogen linkage is not built.** The AMR layer grounds resistance-determinant to drug- edges from ARO and validates them, but does not yet link resistance genes to pathogens via- NCBITaxon; CARD prevalence data is the next input. The AMR KG also uses a deterministic 800-edge- slice of ARO's 5,053 resistance relationships (logged, not silent).+1. **The resistance-to-drug layer uses a slice.** It builds from a deterministic 800-edge slice of+ ARO's 5,053 resistance relationships (logged, not silent); the pathogen layer uses all 6,404+ gene-organism links. The 17 retired taxon ids the pathogen gate flags are real deprecated NCBI+ ids CARD still carries, reported as a finding, not smoothed over.2. **The triage score is Open Targets'.** We did not build a scoring model. The contribution isthat ranking on a *validated* graph cannot surface a fabricated edge; the score itself is areal external silver-truth signal, presented with provenance.diff --git a/case-studies/bio-kg-triage/README.md b/case-studies/bio-kg-triage/README.mdindex 8b0c7e2c..71f3e942 100644--- a/case-studies/bio-kg-triage/README.md+++ b/case-studies/bio-kg-triage/README.md@@ -20,25 +20,32 @@ evidence. It covers all three with three grounded layers.Three layers, each built from a real public source, typed with a real ontology, and validated bythe closed-world gate (full table in [`results/SUMMARY.md`](results/SUMMARY.md)):-| Layer | Source | Grounded triples | Closed-world violations | Ungrounded twin |-|---|---|--:|--:|---|-| Structured (target-disease) | Open Targets + Biolink | 284 | **0** | caught |-| Literature | PubTator3 + Biolink | 169 | **0** | caught |-| Antimicrobial resistance | CARD / ARO | 1283 | **0** | caught |--In every layer the grounded KG has **0 SHACL and 0 closed-world vocabulary violations**, and an-ungrounded twin, identical but for one fabricated term (a nonexistent Biolink predicate, or a-nonexistent ARO id), still reports `conforms=true` under SHACL while the closed-world gate rejects-it. The same open-world hole, on the biomedical vocabulary and on a third ontology (ARO).+| Layer | Source | Ontology policed | Grounded triples | Closed-world result |+|---|---|---|--:|---|+| Structured (target-disease) | Open Targets | Biolink | 284 | **0** violations; twin caught |+| Literature | PubTator3 | Biolink | 169 | **0** violations; twin caught |+| AMR (resistance-to-drug) | CARD / ARO | ARO | 1,283 | **0** violations; twin caught |+| AMR pathogen linkage | CARD + NCBI taxonomy | ARO + Biolink + NCBITaxon | 20,692 | fabricated taxid caught; 17 retired ids flagged |++In the first three layers the grounded KG has **0 SHACL and 0 closed-world vocabulary violations**,+and an ungrounded twin, identical but for one fabricated term, still reports `conforms=true` under+SHACL while the closed-world gate rejects it. The same open-world hole, across the biomedical+vocabulary, a second ontology (ARO), and a third (NCBITaxon).- **Structured** ([`src/pipeline.py`](src/pipeline.py)): 40 live gene-disease associations from the**Open Targets Platform**, typed with the **Biolink Model** (868 declared terms).- **Literature** ([`src/pubtator.py`](src/pubtator.py)): 57 gene-disease relations machine-extracted- by **PubTator3** from 40 PubMed abstracts across the eight target genes. This is the- fragmented-literature-to-KG step, grounded.+ by **PubTator3** from 40 PubMed abstracts across the eight target genes. The fragmented-literature-+ to-KG step, grounded.- **AMR** ([`src/amr.py`](src/amr.py)): 800 of 5,053 real "confers resistance to" relationships from- **CARD's Antibiotic Resistance Ontology** (8,564 declared terms); the gate polices the ARO- namespace, showing it generalises to a third ontology and the AMR domain.+ **CARD's Antibiotic Resistance Ontology** (8,564 declared terms); the gate polices the ARO namespace.+- **AMR pathogen linkage** ([`src/pathogen.py`](src/pathogen.py)): 6,404 gene-organism edges over 740+ organisms from **CARD's card.json**, policing **three namespaces at once**, ARO for the gene, Biolink+ for the types and `in_taxon` predicate, and **NCBITaxon against the current NCBI taxonomy**+ (2,871,791 taxids from `nodes.dmp`). A fabricated taxon id is caught; and, run against the current+ taxonomy, the gate flags **17 organism ids in CARD as no longer current**, all confirmed+ retired-and-merged in NCBI's `merged.dmp`. That is a real data-freshness signal that open-world+ SHACL, and a naive "is it a number" check, both miss.## Triage@@ -71,17 +78,19 @@ guarantees the edges use only real terms before they are committed. Neither does./run-demo.sh # fetches Biolink, ARO, live Open Targets and PubTator3 data; builds + validates all three layers```-Requires Python 3.10+ and network access (Open Targets GraphQL and PubTator3 are queried live).+Requires Python 3.10+ and network access (Open Targets, PubTator3, CARD and the NCBI taxonomy dump+are fetched live). The pathogen layer downloads the 75 MB NCBI taxdump once.## Honest scope-See [`BUILD_REPORT.md`](BUILD_REPORT.md). What is built and validated: the structured target-disease-layer (Open Targets), the literature front end (PubTator3 relations), and the AMR layer (CARD/ARO),-each with the closed-world gate demonstrated on real data. Remaining honest limits: the AMR layer-uses a deterministic 800-edge slice of ARO's 5,053 resistance relationships and does not yet link-resistance genes to pathogens via NCBITaxon (CARD prevalence data is the next input); PubTator3's-associations are its own machine extraction, with its confidence scores, not re-verified by us; and-the triage ranks on Open Targets' own score, presented with provenance, not a new scoring method.+See [`BUILD_REPORT.md`](BUILD_REPORT.md). Built and validated: the structured target-disease layer+(Open Targets), the literature front end (PubTator3), the AMR resistance-to-drug layer (CARD/ARO),+and the AMR pathogen linkage (CARD + NCBITaxon). Remaining honest limits: the resistance-to-drug+layer uses a deterministic 800-edge slice of ARO's 5,053 relationships (logged, not hidden);+PubTator3's associations are its own machine extraction with its confidence scores, not re-verified+by us; and the triage ranks on Open Targets' own score, presented with provenance, not a new scoring+method. The 17 retired taxon ids the pathogen gate flags are a feature, not an error: they are real+but deprecated NCBI ids that CARD still carries.---diff --git a/case-studies/bio-kg-triage/results/SUMMARY.md b/case-studies/bio-kg-triage/results/SUMMARY.mdindex 38c3308f..4566b2b4 100644--- a/case-studies/bio-kg-triage/results/SUMMARY.md+++ b/case-studies/bio-kg-triage/results/SUMMARY.md@@ -1,15 +1,15 @@-# Results summary - three grounded layers+# Results summary: four grounded layers-Every layer builds a KG from a REAL public source, types it with a real ontology, and runs the closed-world vocabulary gate. In every layer the grounded KG has **0 closed-world violations**, and an ungrounded twin (one fabricated term) passes SHACL but is caught by the gate.+Every layer builds a KG from a REAL public source, types it with a real ontology, and runs the closed-world vocabulary gate. Grounded KGs validate clean; ungrounded twins (one fabricated term) pass SHACL but are caught by the gate.-| Layer | Source | Grounded triples | Closed-world violations | Ungrounded fake |-|---|---|--:|--:|---|-| Structured (target-disease) | Open Targets + Biolink | 284 | 0 | caught |-| Literature | PubTator3 + Biolink | 169 | 0 | caught |-| Antimicrobial resistance | CARD/ARO | 1283 | 0 | caught |+| Layer | Source | Ontology policed | Grounded triples | Closed-world result |+|---|---|---|--:|---|+| Structured (target-disease) | Open Targets | Biolink | 284 | 0 violations; twin caught |+| Literature | PubTator3 | Biolink | 169 | 0 violations; twin caught |+| AMR (resistance-to-drug) | CARD / ARO | ARO | 1283 | 0 violations; twin caught |+| AMR pathogen linkage | CARD + NCBI taxonomy | ARO + Biolink + NCBITaxon | 20692 | see below |- **Structured**: 40 live Open Targets gene-disease associations, Biolink-typed.-- **Literature**: 57 gene-disease relations machine-extracted by PubTator3 from 40 PubMed abstracts; all 8 target genes carry literature edges (ALK, BRAF, BRCA1, EGFR, KRAS, MYC, PTEN, TP53).-- **AMR**: 800 of 5053 real 'confers resistance to' relationships from CARD's Antibiotic Resistance Ontology (8564 declared terms); the gate polices the ARO namespace, a third ontology.--Triage (structured layer), top hypotheses by Open Targets score, each a validated Biolink triple: see [`triage.md`](triage.md).\ No newline at end of file+- **Literature**: 57 gene-disease relations from PubTator3 across 40 PubMed abstracts; all 8 target genes carry edges.+- **AMR (resistance-to-drug)**: 800 of 5053 real 'confers resistance to' relationships from CARD's ARO (8564 terms).+- **AMR pathogen linkage**: 6404 gene-organism edges over 740 organisms from CARD's card.json, policing THREE namespaces at once (ARO gene, Biolink type/predicate, NCBITaxon organism against 2,871,791 current NCBI taxids). A fabricated taxon id is caught; and, run against the CURRENT taxonomy, the gate flags **17 organism ids in CARD as no longer current** (all 17 confirmed retired-and-merged in NCBI's merged.dmp, 0 unexplained), a real data-freshness signal that open-world SHACL misses.\ No newline at end of filediff --git a/case-studies/bio-kg-triage/results/results_pathogen.json b/case-studies/bio-kg-triage/results/results_pathogen.jsonnew file mode 100644index 00000000..f028accb--- /dev/null+++ b/case-studies/bio-kg-triage/results/results_pathogen.json@@ -0,0 +1,29 @@+{+ "source": "CARD card.json (gene-organism) + current NCBI taxonomy (nodes.dmp)",+ "edges": 6404,+ "distinct_organisms": 740,+ "policed_namespaces": [+ "ARO",+ "Biolink",+ "NCBITaxon"+ ],+ "ncbi_current_taxids": 2871791,+ "grounded_shacl_conforms": true,+ "organism_ids_flagged_not_current": 17,+ "of_which_retired_and_merged": 17,+ "of_which_unexplained": 0,+ "retired_examples": [+ "1144672",+ "1194538",+ "1214076",+ "1217697",+ "1217698",+ "1217700",+ "1217701",+ "1217702",+ "1217703",+ "1217706"+ ],+ "ungrounded_shacl_conforms": true,+ "injected_fabricated_taxid_caught": true+}\ No newline at end of filediff --git a/case-studies/bio-kg-triage/run-demo.sh b/case-studies/bio-kg-triage/run-demo.shindex 48e63c1c..10a3e1c8 100755--- a/case-studies/bio-kg-triage/run-demo.sh+++ b/case-studies/bio-kg-triage/run-demo.sh@@ -23,3 +23,8 @@ echo; echo "See results/SUMMARY.md, results/triage.md, results/results.json"./.venv/bin/python src/pubtator.py./.venv/bin/python src/amr.pyecho; echo "See results/SUMMARY.md, results/results.json, results_literature.json, results_amr.json"++# --- AMR pathogen linkage (CARD card.json + NCBI taxonomy) ---+[ -f data/card/card.json ] || { curl -sL https://card.mcmaster.ca/latest/data -o data/card-data.tar.bz2; mkdir -p data/card; tar xjf data/card-data.tar.bz2 -C data/card; }+[ -f data/nodes.dmp ] || { curl -sL https://ftp.ncbi.nlm.nih.gov/pub/taxonomy/taxdump.tar.gz -o data/taxdump.tar.gz; tar xzf data/taxdump.tar.gz -C data nodes.dmp merged.dmp delnodes.dmp; }+./.venv/bin/python src/pathogen.pydiff --git a/case-studies/bio-kg-triage/src/pathogen.py b/case-studies/bio-kg-triage/src/pathogen.pynew file mode 100644index 00000000..97efe587--- /dev/null+++ b/case-studies/bio-kg-triage/src/pathogen.py@@ -0,0 +1,130 @@+"""+AMR pathogen linkage (#60, completing the layer): link resistance genes to the pathogens+they occur in, grounded in three real vocabularies at once.++Source: CARD's card.json gives, for each resistance determinant (ARO id), the organisms its+reference sequences come from (NCBI taxonomy id). We build gene -> in_taxon -> organism edges+and police THREE namespaces against their real authorities:+ - ARO (the resistance determinant) against ARO's declared terms (aro.obo);+ - Biolink (the types and predicate) against the Biolink Model;+ - NCBITaxon (the organism) against the CURRENT NCBI taxonomy (nodes.dmp, 2.87M taxids).++Two things fall out. A fabricated taxon id injected into the ungrounded twin is caught, as+before. And, run against the CURRENT taxonomy, the gate also flags organism ids in CARD that+are no longer current (retired and merged in NCBI's merged.dmp), a data-freshness signal that+open-world SHACL and a naive "is it a number" check both miss.+"""+import json, os+import rdflib+from rdflib import Graph, RDF, RDFS, URIRef, Literal+from rdflib.namespace import SH+from pyshacl import validate++ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))+DATA, BUILD, RES = (os.path.join(ROOT, d) for d in ("data", "build", "results"))+BL = "https://w3id.org/biolink/vocab/"+OBO = "http://purl.obolibrary.org/obo/"+ARO_NS = OBO + "ARO_"; TAX_NS = OBO + "NCBITaxon_"+POLICED = [ARO_NS, TAX_NS, BL]++def load_declared():+ d = set()+ # ARO terms+ for line in open(os.path.join(DATA, "aro.obo"), encoding="utf-8"):+ if line.startswith("id: ARO:"):+ d.add(ARO_NS + line[8:].strip())+ # Biolink terms+ d |= set(json.load(open(os.path.join(DATA, "biolink_vocab.json")))["declared"])+ # current NCBI taxonomy+ for line in open(os.path.join(DATA, "nodes.dmp"), encoding="utf-8"):+ d.add(TAX_NS + line.split("\t", 1)[0].strip())+ return d++def load_merged():+ m = set()+ p = os.path.join(DATA, "merged.dmp")+ if os.path.exists(p):+ for line in open(p, encoding="utf-8"):+ m.add(TAX_NS + line.split("\t", 1)[0].strip())+ return m++def card_pairs():+ d = json.load(open(os.path.join(DATA, "card", "card.json")))+ pairs = {}+ for k, v in d.items():+ if not (isinstance(v, dict) and v.get("ARO_accession")):+ continue+ aro = v["ARO_accession"]; gname = v.get("ARO_name", aro)+ for sid, seq in v.get("model_sequences", {}).get("sequence", {}).items():+ tax = seq.get("NCBI_taxonomy", {})+ tid = tax.get("NCBI_taxonomy_id")+ if tid:+ pairs[(aro, str(tid))] = (gname, tax.get("NCBI_taxonomy_name", str(tid)))+ return [(a, t, n[0], n[1]) for (a, t), n in pairs.items()]++def build(pairs, fabricate=False):+ g = Graph()+ for i, (aro, tid, gname, oname) in enumerate(pairs):+ gene = URIRef(ARO_NS + aro.replace("ARO:", ""))+ org = URIRef(TAX_NS + ("99999999" if (fabricate and i == 0) else tid))+ g.add((gene, RDF.type, URIRef(BL + "Gene"))); g.add((gene, RDFS.label, Literal(gname)))+ g.add((org, RDF.type, URIRef(BL + "OrganismTaxon"))); g.add((org, RDFS.label, Literal(oname)))+ g.add((gene, URIRef(BL + "in_taxon"), org))+ return g++def in_pol(i): return any(str(i).startswith(p) for p in POLICED)+def gate(g, declared):+ flags = set()+ for s, p, o in g:+ if in_pol(p) and str(p) not in declared: flags.add(str(p))+ for node in (s, o):+ if isinstance(node, URIRef) and str(node).startswith((ARO_NS, TAX_NS)) and str(node) not in declared:+ flags.add(str(node))+ if p == RDF.type and isinstance(o, URIRef) and in_pol(o) and str(o) not in declared:+ flags.add(str(o))+ return sorted(flags)++def shapes():+ s = Graph(); sh = URIRef("https://ex/path/shape")+ s.add((sh, RDF.type, SH.NodeShape)); s.add((sh, SH.targetClass, URIRef(BL + "Gene")))+ b = URIRef("https://ex/path/shape/l"); s.add((sh, SH.property, b)); s.add((b, SH.path, RDFS.label)); s.add((b, SH.minCount, Literal(1)))+ return s++def main():+ declared = load_declared(); merged = load_merged()+ pairs = card_pairs()+ organisms = {t for _, t, _, _ in pairs}+ print(f"[*] CARD gene-organism links: {len(pairs)} edges over {len(organisms)} distinct organisms")++ grounded = build(pairs, fabricate=False)+ ungrounded = build(pairs, fabricate=True)+ grounded.serialize(os.path.join(BUILD, "pathogen-kg-grounded.ttl"), format="turtle")++ c, _, _ = validate(grounded, shacl_graph=shapes(), inference="none")+ flags = gate(grounded, declared)+ tax_flags = [f for f in flags if f.startswith(TAX_NS)]+ retired = [f for f in tax_flags if f in merged] # retired-and-merged (data freshness)+ fabricated = [f for f in tax_flags if f not in merged]++ cu, _, _ = validate(ungrounded, shacl_graph=shapes(), inference="none")+ ung_flags = gate(ungrounded, declared)+ injected_caught = (TAX_NS + "99999999") in ung_flags++ out = {+ "source": "CARD card.json (gene-organism) + current NCBI taxonomy (nodes.dmp)",+ "edges": len(pairs), "distinct_organisms": len(organisms),+ "policed_namespaces": ["ARO", "Biolink", "NCBITaxon"],+ "ncbi_current_taxids": sum(1 for _ in open(os.path.join(DATA, "nodes.dmp"), encoding="utf-8")),+ "grounded_shacl_conforms": bool(c),+ "organism_ids_flagged_not_current": len(tax_flags),+ "of_which_retired_and_merged": len(retired),+ "of_which_unexplained": len(fabricated),+ "retired_examples": [f.split("_")[-1] for f in retired[:10]],+ "ungrounded_shacl_conforms": bool(cu),+ "injected_fabricated_taxid_caught": injected_caught,+ }+ json.dump(out, open(os.path.join(RES, "results_pathogen.json"), "w"), indent=2)+ print(json.dumps(out, indent=2))++if __name__ == "__main__":+ main()