scripts/build_context_evidence_graph.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/build_context_evidence_graph.py · SHA-256: 2758ba22e378ffed…
if (
re.search(
r"(?i)(\bfinite[- ]element\s+(?:prediction|model)\b|\bmodel[- ]predicted\b"
r"|\bmodel\s+prediction,\s*not\s+a\s+measurement\b|\bsimulation\s+only\b|\bsimulation\s+parameter\b"
r"|\bsimulated\s+(?:core|critical|central|viability|oxygen|average|fraction|hypoxic|human|control|sonic|islet)\b"
r"|\bcfd\s+model\b|\bmathematical\s+safety\s+model\b|\bdescriptive\s+modeled\s+bank\b"
r"|\bmodelled\s+estimate\b|\blogistic[- ]regression\s+prediction\b"
r"|\bpo2_survival\b|\bmodels\s+barcode[- ]sharing\s+probabilities\b|\bmodeled\s+probability\b"
r"|\bpredicted\s+stability\b|\bextrapolation,\s*not\s+long[- ]term\s+observation\b"
r"|\bmonte\s+carlo\s+simulation\b|\bthiele[- ]modulus\s+calculation\b|\bcalculated\s+volumetric\s+ocr\b"
r"|\buse\s+a\s+simple\s+model\s+to\s+illustrate\b|\bmodeled\s+sequencing[- ]depth\s+saturation\b"
r"|\bchao2[- ]estimated\b|\btheoretical\s+limit\s+of\s+detection\b|\ban\s+estimate,\s*not\s+a\s+spike[- ]in\s+measurement\b"
r"|\bsuggested,\s*not\s+measured\b|\btheoretical\s+calculation\b"
r"|\b11[- ]gene\s+multiple\s+regression\s+model\b"
r"|\bpredicted\s+protein[- ]coding\s+consequence\b|\bestimated\s+test\s+sample\s+size\b)",
_o_sim_blob,
)
or re.search(r"\bA\d+_(?:model|sim|FEM|CFD|Model)_", str(o.get("comparison_arms") or ""))
or oid in CURATED_NON_EMPIRICAL_OUTCOME_IDS
) and o.get("evidence_provenance") not in ("computational_model_or_simulation", "mixed_measured_and_simulated_model", "mixed_empirical_and_computational"):
raise ValueError(
f"Outcome {oid} describes computational/simulated prediction without non-empirical evidence_provenance ({o.get('evidence_provenance')!r})"
)
_non_emp_prov = frozenset({
"computational_model_or_simulation",
"mixed_measured_and_simulated_model",
"mixed_empirical_and_computational",
"administrative_registry_record",
})
_title_only_pins = frozenset({"title_or_citation_metadata_only", "title"})
_link_indices_by_study: dict[str, list[int]] = {}
_fwd_cited_by: dict[str, set[str]] = {}
_seen_edge_ids: set[str] = set()
for e in edges:
_eid = e.get("edge_id")
if not isinstance(_eid, str) or not _eid.strip():
raise ValueError(f"Edge has missing or non-string edge_id: {_eid!r}")
if _eid in _seen_edge_ids:
raise ValueError(f"Duplicate edge_id {_eid!r} in CEG edges")
_seen_edge_ids.add(_eid)
qid = e.get("queue_id")
if qid not in studies:
raise ValueError(f"Edge {e.get('edge_id')} references missing study {qid}")
_lidx = e.get("link_index")
if type(_lidx) is not int or _lidx < 0:
raise ValueError(f"Edge {e.get('edge_id')} has invalid link_index={_lidx!r}")
_link_indices_by_study.setdefault(qid, []).append(_lidx)
_pce = e.get("primary_certification_eligible")
if type(_pce) is not bool:
raise ValueError(
f"Edge {e.get('edge_id')} primary_certification_eligible must be strict bool, got {_pce!r} ({type(_pce).__name__})"
)
if studies[qid].get("record_class") != "empirical_primary_study" and _pce is not False:
raise ValueError(f"Non-empirical study edge {e.get('edge_id')} ({studies[qid].get('record_class')}) cannot be primary_certification_eligible=True")
if _pce is True and e.get("applicability") == "domain_mismatch":
raise ValueError(f"Domain-mismatched edge {e.get('edge_id')} (applicability='domain_mismatch') cannot be primary_certification_eligible=True")
if _pce is True and e.get("relation") == "noninformative":
raise ValueError(f"Noninformative edge {e.get('edge_id')} (relation='noninformative') cannot be primary_certification_eligible=True")
if _pce is True and e.get("readiness") == "needs_primary_fulltext":
raise ValueError(f"Unauthenticated/title-only edge {e.get('edge_id')} (readiness='needs_primary_fulltext') cannot be primary_certification_eligible=True")
_st_pin = studies[qid].get("source_pin")
if _pce is True and isinstance(_st_pin, dict) and _st_pin.get("source_type") in _title_only_pins:
raise ValueError(f"Title-only study edge {e.get('edge_id')} cannot be primary_certification_eligible=True")
if _pce is True and e.get("evidence_provenance") in _non_emp_prov:
raise ValueError(f"Simulated/modeled edge {e.get('edge_id')} ({e.get('evidence_provenance')}) cannot be primary_certification_eligible=True")
if _pce is True and _eid in CURATED_INELIGIBLE_EDGE_IDS:
raise ValueError(f"Curated-ineligible edge {_eid} cannot be primary_certification_eligible=True")
if _pce is True and re.search(r"(?i)(\btitle[- ]only\b|\bno\s+measured\s+result\b|\bread\s+from\s+the\s+title\s+alone\b)", str(e.get("claim_summary") or "")):
raise ValueError(f"Edge {e.get('edge_id')} narrative states title-only / no measured result while primary_certification_eligible=True")
_cited_tuples = e.get("cited_outcome_tuples") or []
if len(_cited_tuples) != len(set(_cited_tuples)):
raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_tuples contains duplicate outcome(s): {_cited_tuples!r}")
if _pce is True and not _cited_tuples:
raise ValueError(f"Primary-certification-eligible edge {e.get('edge_id')} must cite at least one outcome (cited_outcome_tuples is empty)")
for tok in _cited_tuples:
if not isinstance(tok, str) or tok not in outcomes:
raise ValueError(f"Edge {e.get('edge_id')} cites unresolved outcome {tok}")
_fwd_cited_by.setdefault(tok, set()).add(str(e.get("edge_id")))
if _pce is True:
_oc = outcomes[tok]
_oc_qid = _oc.get("queue_id")
if _oc_qid not in studies or studies[_oc_qid].get("record_class") != "empirical_primary_study":
raise ValueError(
f"Primary-certification-eligible edge {e.get('edge_id')} cites outcome {tok} owned by non-empirical/duplicate study {_oc_qid} ({studies.get(_oc_qid, {}).get('record_class')})"
)
_oc_st_pin = studies[_oc_qid].get("source_pin")
if isinstance(_oc_st_pin, dict) and _oc_st_pin.get("source_type") in _title_only_pins:
raise ValueError(
f"Primary-certification-eligible edge {e.get('edge_id')} cites outcome {tok} owned by title-only study {_oc_qid} (source_type={_oc_st_pin.get('source_type')!r})"
)
if _oc.get("evidence_provenance") in _non_emp_prov:
raise ValueError(
f"Primary-certification-eligible edge {e.get('edge_id')} cites computational/simulated or mixed provenance outcome {tok} ({_oc.get('evidence_provenance')})"
)
_oc_sim_text = re.sub(
r"(?i)(\brandom\s+simulated\s+genes\b|\bin\s+silico-predicted\s+cas9\s+off-target\s+sites\b|\bsimulated\s+intraportal\s+hypoxia\b|\brelative\s+to\s+simulated\s+genes\b)",
"",
" ".join(str(_oc.get(k) or "") for k in ("endpoint_name", "quantitative_summary", "comparison_arms", "intervention_value", "assay_or_endpoint")),
)
if re.search(
r"(?i)(\bsimulated\b|\bin[\s-]+silico\b|\bcomputational\s+model\s+only\b|\bsimulation[- ]only\b|\bsimulation\s+only\b|\bmodel[- ]predicted\b|\bfinite[- ]element\s+(?:prediction|model)\b|\bmonte\s+carlo\s+simulation\b|\btheoretical\s+calculation\b)",
_oc_sim_text,
):
raise ValueError(
f"Primary-certification-eligible edge {e.get('edge_id')} cites outcome {tok} carrying simulation-only narrative"
)
_oc_pin_t = (_oc.get("source_pin") or {}).get("source_type") if isinstance(_oc.get("source_pin"), dict) else None
if _oc_pin_t in _title_only_pins:
raise ValueError(
f"Primary-certification-eligible edge {e.get('edge_id')} cites title-only outcome {tok} (source_type={_oc_pin_t!r})"
)
_cited_local = e.get("cited_outcome_ids")
if not isinstance(_cited_local, list):
raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_ids must be a list")
if len(_cited_local) != len(set(_cited_local)):
raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_ids contains duplicate outcome(s): {_cited_local!r}")
if _pce is True and not _cited_local:
raise ValueError(f"Primary-certification-eligible edge {e.get('edge_id')} must cite at least one outcome (cited_outcome_ids is empty)")
_resolved_local: set[str] = set()
for _loc in _cited_local:
if not isinstance(_loc, str) or not _loc.strip():
raise ValueError(f"Edge {e.get('edge_id')} has invalid cited_outcome_id {_loc!r}")
_full_loc = _loc if ":" in _loc else f"{qid}:{_loc}"
if _full_loc not in outcomes:
raise ValueError(f"Edge {e.get('edge_id')} cited_outcome_id {_loc!r} resolves to unresolved outcome {_full_loc!r}")
_resolved_local.add(_full_loc)
if _resolved_local != set(_cited_tuples):
raise ValueError(
f"Edge {e.get('edge_id')} cited_outcome_ids {sorted(_resolved_local)} mismatches cited_outcome_tuples {sorted(set(_cited_tuples))}"
)
for oid, _oc_sym in outcomes.items():
_bwd_edges = _oc_sym.get("cited_by_edge_ids")
if _bwd_edges is not None and not isinstance(_bwd_edges, list):
raise ValueError(f"Outcome {oid} cited_by_edge_ids must be a list or omitted, got {type(_bwd_edges).__name__}")
if _bwd_edges is not None and len(_bwd_edges) != len(set(_bwd_edges)):
raise ValueError(f"Outcome {oid} cited_by_edge_ids contains duplicate edge_id(s): {_bwd_edges!r}")
_bwd_set = set(_bwd_edges or [])
_fwd_set = _fwd_cited_by.get(oid, set())
if _bwd_set != _fwd_set:
raise ValueError(
f"Outcome {oid} cited_by_edge_ids {sorted(_bwd_set)} is asymmetric with citing edges {sorted(_fwd_set)}"
)
for qid, _idxs in _link_indices_by_study.items():
if sorted(_idxs) != list(range(len(_idxs))):
raise ValueError(f"Study {qid} has non-contiguous or out-of-range link_index sequence {sorted(_idxs)} (expected 0..{len(_idxs)-1})")
if studies[qid].get("links_count") != len(_idxs):
raise ValueError(f"Study {qid} links_count={studies[qid].get('links_count')} disagrees with {len(_idxs)} edges")
for eff_id, eff in effectors.items():
for sq in eff.get("linked_study_ids") or []:
if sq not in studies:
raise ValueError(f"Effector {eff_id} references missing study {sq}")
for sv in eff.get("linked_variable_ids") or []:
if sv not in arms:
raise ValueError(f"Effector {eff_id} references missing arm {sv}")
for tok in eff.get("linked_outcome_tuples") or []:
if not isinstance(tok, str) or tok not in outcomes:
raise ValueError(f"Effector {eff_id} references missing outcome {tok}")
gy_path = repo_root / GRAVEYARD_REL_PATH
if gy_path.is_file():
gy_ids = {row["graveyard_id"] for row in json.loads(gy_path.read_text(encoding="utf-8")).get("graveyard_entries", [])}
for g in graveyard:
if g.get("graveyard_id") not in gy_ids:
raise ValueError(f"CEG graveyard entry {g.get('graveyard_id')} missing from {GRAVEYARD_REL_PATH}")
# Global study<->arm ownership symmetry, outcomes_count, and same-study explicit outcome arm FKs
_actual_out_counts: dict[str, int] = {}
for _oid_g, _o_g in outcomes.items():
_oqid_g = _o_g.get("queue_id")
_actual_out_counts[_oqid_g] = _actual_out_counts.get(_oqid_g, 0) + 1
for _af in ("comparator_arm_id", "focal_arm_id", "intervention_arm_id"):
_av = _o_g.get(_af)
if _av is not None:
if not isinstance(_av, str) or not _av.strip():
raise ValueError(f"Outcome {_oid_g} has invalid {_af}={_av!r}")
_full_av = _av if _av.startswith("VAR:") else f"VAR:{_oqid_g}:{_av}"
if _full_av not in arms:
raise ValueError(f"Outcome {_oid_g} {_af}={_av!r} does not resolve in CEG arms")
if arms[_full_av].get("queue_id") != _oqid_g:
raise ValueError(f"Outcome {_oid_g} {_af}={_av!r} belongs to study {arms[_full_av].get('queue_id')!r}, not {_oqid_g!r}")
for _qid_g, _st_g in studies.items():
_st_vids = _st_g.get("variable_arm_ids") or []
if len(_st_vids) != len(set(_st_vids)):
raise ValueError(f"Study {_qid_g} has duplicate entries in variable_arm_ids")
for _vid_g in _st_vids:
if arms[_vid_g].get("queue_id") != _qid_g:
raise ValueError(f"Study {_qid_g} variable_arm_ids references arm {_vid_g} owned by {arms[_vid_g].get('queue_id')!r}")
if _st_g.get("outcomes_count") != _actual_out_counts.get(_qid_g, 0):
raise ValueError(f"Study {_qid_g} outcomes_count={_st_g.get('outcomes_count')} disagrees with actual {_actual_out_counts.get(_qid_g, 0)}")
for _vid_g, _a_g in arms.items():
_aq_g = _a_g.get("queue_id")
if _vid_g not in set(studies[_aq_g].get("variable_arm_ids") or []):
raise ValueError(f"Arm {_vid_g} owned by {_aq_g} is missing from study variable_arm_ids")
# Strict IIP-0034 & IIP-0035 new-record typed arm FKs, same-study joins, effector refs, no-partial-dossier span audit & full-leaf rolling-40 _SourceGuard
_iip0034_qids = frozenset({"PMID:17375075", "PMID:42020736", "PMID:42056515", "PMID:42749803"})
_iip0034_eids = frozenset({"PMID:17375075:L1", "PMID:42020736:L1", "PMID:42056515:L1", "PMID:42749803:L1", "M1522:L4"})
_iip0034_req_pmids = ("17375075", "39696686", "42020736", "42056515", "42749803")
_iip0035_qids = frozenset({"M0189", "M1407", "PMID:36944335", "PMID:39753706", "PMID:41436438", "PMID:41999746"})
_iip0035_expected_edge_bindings = {
"M0189:L1": ("M0189", ("M0189:O1", "M0189:O2"), "9489a2d260775e0591af72799e3a2297260f4b2df14dc29cdc59acbad01e7c7b"),
"M1407:L1": ("M1407", ("M1407:O1",), "97edc6fff8dca53a997b4d6c544eebad6253eba29f0cd720cf335994947f451a"),
"PMID:36944335:L1": ("PMID:36944335", ("PMID:36944335:O1",), "8177ff0a7f4837d6609155d02f26064aa674e6d6433d5519344421888b80d8cb"),
"PMID:39753706:L1": ("PMID:39753706", ("PMID:39753706:O1", "PMID:39753706:O2"), "7f8df9e1e6c03a9d386e2e57c0592bc28fe88d8694487daf36d324ef1efe40cf"),
"PMID:41436438:L1": ("PMID:41436438", ("PMID:41436438:O1",), "05ce92c5032f16e4b53d438cdcf9b63b4251d57a8769661be819ce1a104379d6"),
"PMID:41999746:L1": ("PMID:41999746", ("PMID:41999746:O1",), "9a30fdc5656e490bf78c93d018a740d8b67eb27c2059a73a0059279db2db9e33"),
"M0051:L4": ("M0051", ("M0051:O1", "M0051:O5"), "fa7fb021669e6a71f22cc4078dd477bda9904c47e819b2c250a9e2081f9962bf"),
"M0154:L3": ("M0154", ("M0154:O1", "M0154:O3", "M0154:O4"), "dfc1fb8e65f7db6084552b462c21532d9cab4d326ca13eef0f280e50e4cd5f2c"),
"M0159:L3": ("M0159", ("M0159:O2",), "1c18c658d8351a5128abb0b5a21846fa2a15fe4001b0b733cee5d650d51de8cc"),
"M0206:L3": ("M0206", ("M0206:O1", "M0206:O2", "M0206:O9", "M0206:O11", "M0206:O12", "M0206:O17"), "9c3f1e834d57b4683fcb135274c0cc00e482f0752ba61636b1dd595b75d796b5"),
"M0241:L3": ("M0241", ("M0241:O1", "M0241:O2", "M0241:O4"), "60a3e30568b5bd329c5595fbfb5fa779c344f597f0ba8f0bc84c049f9f24c00f"),
}
_iip0035_eids = frozenset(_iip0035_expected_edge_bindings)
_iip0035_adjudicated_inelig_legacy_outcomes = {
"M0051:L1": (("M0051:O1", "M0051:O5"), "fda2fee5e96b1ae2f699dea5a5919eef81acb185440cfdb446157be83fff582b"),
"M0051:L2": (("M0051:O1", "M0051:O5"), "b0b8d71b045b709de53cc8d8975a44f88bf343886f9944a8775f4f107b0acb29"),
"M0051:L3": (("M0051:O4",), "a1b650ca58d7ee3f65d7ce05ad380e3bcbe2de5515f58b2ad8ce2f5b9ce6e147"),
"M0154:L1": (("M0154:O1", "M0154:O2"), "b0b04b722d7ae4282cf253721cc6c9a536b39ba352dea2d69f2711eb947c5966"),
"M0154:L2": (("M0154:O1", "M0154:O3", "M0154:O4"), "54844b79b54e02a1ba799f3bc4cae9366b949d7ad737ab0ff317aec213f36667"),
"M0159:L1": (("M0159:O2", "M0159:O3"), "eec8033b2915fc19c425683bff865193b98e0534e520b52a50e07bb2cd980081"),
"M0159:L2": (("M0159:O1", "M0159:O2", "M0159:O3"), "c4ab223e2234ae63414688b3c3c0110cfba5f2f15c189331945cc3afccee5258"),
"M0206:L2": (("M0206:O9", "M0206:O12", "M0206:O10", "M0206:O14", "M0206:O17"), "bf2d25dc5e33e302309c364e95c85c87934028065912bf4673e67b27c91de241"),
"M0241:L1": (("M0241:O2", "M0241:O3"), "0415b7d3450a99d88ec2b370284472391a5b9c4399f1f72e05497c6eaac7f255"),
"M0241:L2": (("M0241:O1", "M0241:O4"), "fe8c8f2f7c3d40ba478a86ce88e9a9c49d7ca24f6df3a2f1b9a6f3fa807554bb"),
}
_iip0035_m206_l1_expected_sha = "c8f8cb8f03df508b94717777577b0e2b76754a49c0b55140cf7f02f2d57224c1"
_iip0035_expected_arm_digests = {
"VAR:M0189:A1": "9020bdec3108bc526a05cf1e13398c37e0b7d1c01d2f7a0b8a5129e8ff7dbd19",
"VAR:M0189:A2_allogeneic_ctrl": "d9a3ab49db3a1550ec72677e231e8f78c0669498b1ce87f9b3cc15809d9af47e",
"VAR:M1407:A1": "80003667e1218301f14566c81b6b226f12f08b72e8ebff76ea177c81e2e11ee8",
"VAR:PMID:36944335:A1": "223640329c6632b6a2bd0adb299ac60ed8629b709f0bd573a93abfd9335663d1",
"VAR:PMID:39753706:A1": "12df2f6220286f5d8e98d4f9f950e2dfc95f30e207cb367fb44e8a483ab195c5",
"VAR:PMID:39753706:A2_original_protocol_ctrl": "97ce0849c5fe173b9707d41139d258cc2c2038dff728c2301838e51fb7a776ad",