"""Validators that keep the synthetic biology data honest - the analogue of iesval.py. Three families, one per training slice: validate_biolink : parse + Biolink category/predicate membership (bmt vocab) + entity CURIE reality (OBO/gene) + subject/object category conformance to the association's declared ranges (with subclass closure). validate_gocam : gocam pydantic Model round-trips + every GO/RO/UniProt/taxon CURIE is real and used in the correct aspect (MF/BP/CC). validate_grounding: the (mention -> CURIE) pair exists in the real ontology release. Run under .venvdata.""" import json, pathlib, re from rdflib import Graph import bioseed as S BLV = S.BLV CAT_CAMEL = BLV["cat_camel"]; ASSOC_CAMEL = BLV["assoc_camel"]; PRED_SNAKE = BLV["pred_snake"] CAT_ANC = BLV["cat_ancestors"]; ASSOC = BLV["associations"] BL = S.PREFIX["biolink"]; RDFNS = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" # Biolink association slots that are legitimately biolink: predicates but are NOT edge predicates ASSOC_SLOTS = {"predicate", "knowledge_level", "agent_type", "subject", "object", "primary_knowledge_source", "aggregator_knowledge_source", "publications"} def _bl_local(iri): return iri[len(BL):] if iri.startswith(BL) else None def validate_biolink(ttl, min_triples=5): g = Graph() try: g.parse(data=ttl, format="turtle") except Exception as e: return False, f"parse error: {str(e)[:100]}", 0, {} n = len(g) if n < min_triples: return False, f"too few triples ({n})", n, {} bl_terms = set() # every biolink: local name that appears for s, p, o in g: for node in (s, p, o): loc = _bl_local(str(node)) if loc is not None: bl_terms.add(loc) # classify biolink terms into class-like (CamelCase) vs predicate-like (snake) bad = [] for term in bl_terms: if term[:1].isupper(): # a class if term not in CAT_CAMEL and term not in ASSOC_CAMEL: bad.append(term) else: # a predicate / slot if term not in PRED_SNAKE and term not in ASSOC_SLOTS: bad.append(term) halluc = len(bad) / len(bl_terms) if bl_terms else 1.0 if bad: return False, f"unknown biolink terms: {sorted(bad)[:6]}", n, {"halluc": halluc} # entity CURIE reality: every non-biolink, non-rdf IRI must reverse to a real CURIE unreal = [] ents = set() for s, p, o in g: for node in (s, o): iri = str(node) if iri.startswith(BL) or iri.startswith(RDFNS) or iri.startswith("urn:"): continue if not str(node).startswith("http"): continue cur = S.iri_to_curie(iri) if cur is None or not S.is_real(cur): unreal.append(cur or iri[:50]) else: ents.add((iri, cur)) if unreal: return False, f"non-existent entities: {unreal[:4]}", n, {"halluc": halluc} # association subject/object conformance to declared ranges (subclass closure) typ = {} for s, _, o in g.triples((None, __import__("rdflib").RDF.type, None)): loc = _bl_local(str(o)) if loc: typ.setdefault(str(s), set()).add(loc) checked = viol = 0 RDF = __import__("rdflib").RDF for a in list(typ): acls = [c for c in typ[a] if c in ASSOC_CAMEL] if not acls: continue spec = ASSOC[ASSOC_CAMEL[acls[0]]] subj = g.value(__import__("rdflib").URIRef(a), RDF.subject) obj = g.value(__import__("rdflib").URIRef(a), RDF.object) for node, rng in ((subj, spec["subject_range"]), (obj, spec["object_range"])): if node is None: continue cats = [CAT_CAMEL[c] for c in typ.get(str(node), ()) if c in CAT_CAMEL] if not cats: continue checked += 1 ok = any(rng == c or rng in CAT_ANC.get(c, []) for c in cats) if not ok: viol += 1 struct = 1.0 if checked == 0 else 1.0 - viol / checked return True, "ok", n, {"halluc": halluc, "struct_conf": struct, "checked": checked, "entities": len(ents)} # ------------------------------ GO-CAM ------------------------------ _GO_MF = {t[0] for t in S.GO_SPLIT["MF"]}; _GO_BP = {t[0] for t in S.GO_SPLIT["BP"]} _GO_CC = {t[0] for t in S.GO_SPLIT["CC"]} def validate_gocam(text): import yaml from gocam.datamodel import Model try: d = yaml.safe_load(text); m = Model(**d) except Exception as e: return False, f"gocam schema invalid: {str(e)[:100]}", {} if not m.activities: return False, "no activities", {} bad = [] for a in m.activities: eb = getattr(a, "enabled_by", None) if eb and eb.term and not S.is_real(eb.term): bad.append(("enabled_by", eb.term)) mf = getattr(a, "molecular_function", None) if mf and mf.term and mf.term not in _GO_MF: bad.append(("molecular_function!MF", mf.term)) bp = getattr(a, "part_of", None) if bp and bp.term and bp.term not in _GO_BP: bad.append(("part_of!BP", bp.term)) oi = getattr(a, "occurs_in", None) if oi and oi.term and not (oi.term in _GO_CC or S.is_real(oi.term)): bad.append(("occurs_in", oi.term)) for ca in (a.causal_associations or []): if ca.predicate and ca.predicate not in S.CAUSAL_RO: bad.append(("causal_pred", ca.predicate)) if m.taxon and m.taxon not in S.TAXA: bad.append(("taxon", m.taxon)) if bad: return False, f"unreal/misused terms: {bad[:5]}", {"n_act": len(m.activities)} return True, "ok", {"n_act": len(m.activities)} # ---------------------------- OBO grounding ---------------------------- def validate_grounding(curie, expected_label): lab = S.label_of(curie) if lab is None: return False, f"{curie} not in ontology" if expected_label and lab.lower() != expected_label.lower(): return False, f"label mismatch: {curie} is '{lab}' not '{expected_label}'" return True, "ok" if __name__ == "__main__": # smoke: a correct-by-construction Biolink graph passes; a hallucinated term fails. good = S.biolink_turtle("gene to disease association", "NCBIGene:672", "gene", "associated with", "MONDO:0007254", "disease") print("REAL biolink ->", validate_biolink(good)[:2], validate_biolink(good)[3]) bad = good.replace("associated_with", "telepathically_linked_to") print("HALLUC pred ->", validate_biolink(bad)[:2]) fake = good.replace("MONDO_0007254", "MONDO_9999999") print("FAKE entity ->", validate_biolink(fake)[:2]) print("grounding real ->", validate_grounding("GO:0006281", "DNA repair")) print("grounding fake ->", validate_grounding("GO:9999999", "DNA repair"))