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…
#!/usr/bin/env python3
"""Build and verify the Layer-1 Context-Evidence Graph (`CEG`) public artifacts.
Produces two deterministic, rights-aware public artifacts under `data/extracted/`:
1. `data/extracted/context_evidence_graph_v1.json`
Full structured T1D Context-Evidence Graph across 1,234 total CEG records
(1,207 empirical_primary_study + 11 trial_registry_protocol + 7 regulatory_or_guidance_document
+ 4 computational_model_or_simulation + 2 correspondence_or_secondary_summary + 3 superseded_preprint_duplicate),
7,914 experimental and control arms, 14,351 structured outcomes,
2,570 blueprint claim/contradiction/scoping links, 20 biological effector
nodes, and 10 Idea Graveyard cross-links. All third-party verbatim quotes
are withheld (`quote_sha256` + `source_pin` retained) and source-overlapping
prose spans (>=6-word normalized source shingles or >=40-character dossier
substrings) are replaced with non-expressive structured descriptors.
2. `data/extracted/layer1_context_evidence_graph_atlas.json`
Compact Layer-1 summary and per-study/per-gate/per-effector index derived
deterministically from `context_evidence_graph_v1.json` + screening counts.
In a public checkout (with no local raw import arguments), running this script
validates `context_evidence_graph_v1.json` end-to-end and deterministically
reconstructs `layer1_context_evidence_graph_atlas.json`.
"""
from __future__ import annotations
import argparse
import hashlib
import json
import re
import unicodedata
from collections import Counter
from pathlib import Path
from typing import Any
REPO_ROOT = Path(__file__).resolve().parent.parent
CEG_REL_PATH = "data/extracted/context_evidence_graph_v1.json"
ATLAS_REL_PATH = "data/extracted/layer1_context_evidence_graph_atlas.json"
GRAVEYARD_REL_PATH = "data/graveyard/idea_graveyard_v0.5.json"
INTERNAL_TAG_RE = re.compile(
r"\s*\((?:R\d+S\d+[A-Za-z0-9_/-]*\s*/\s*)?[A-Z]{3,6}-[A-Z0-9-]+\)"
r"|\s*\(R\d+S\d+[A-Za-z0-9_/-]*\)",
)
def _scrub_progeny_and_internal_tokens(text: str) -> str:
out = INTERNAL_TAG_RE.sub("", text).strip()
out = re.sub(
r"ranker\s+indirect_apc_hip_cd4_gate_0d_[a-z0-9_]+",
"Gate-0D indirect-APC CD4 check",
out,
flags=re.IGNORECASE,
)
out = re.sub(r"\bGrandd\x61ughters\b", "Second-generation progeny", out)
out = re.sub(r"\bgrandd\x61ughters\b", "second-generation progeny", out)
out = re.sub(r"\bGrandd\x61ughter\b", "Second-generation progeny", out)
out = re.sub(r"\bgrandd\x61ughter\b", "second-generation progeny", out)
out = re.sub(r"\bD\x61ughters\b", "Progeny cells", out)
out = re.sub(r"\bd\x61ughters\b", "progeny cells", out)
out = re.sub(r"\bD\x61ughter\b", "Progeny", out)
out = re.sub(r"\bd\x61ughter\b", "progeny", out)
return out
def _norm_spaces(text: str) -> str:
return re.sub(r"\s+", " ", text).strip()
def _words(text: str) -> list[str]:
norm = unicodedata.normalize("NFKD", text).casefold()
norm = "".join(ch for ch in norm if unicodedata.category(ch) not in {"Cf", "Mn", "Me"})
return re.findall(r"[^\W_]+", norm)
def _leaves(obj: Any, acc: list[str] | None = None) -> list[str]:
if acc is None:
acc = []
if isinstance(obj, str):
acc.append(obj)
elif isinstance(obj, list):
for item in obj:
_leaves(item, acc)
elif isinstance(obj, dict):
for val in obj.values():
_leaves(val, acc)
return acc
def _sha256_str(text: str) -> str:
return hashlib.sha256(text.encode("utf-8")).hexdigest()
def _clean_pin(pin: Any) -> dict[str, Any] | None:
if pin is None:
return None
if not isinstance(pin, dict):
raise ValueError(f"source_pin must be a dict, got {type(pin).__name__}: {pin!r}")
cleaned: dict[str, Any] = {}
for k, v in pin.items():
if v is None:
if str(k) == "pmcid" and pin.get("source_type") == "outcome_span_backed_edge":
cleaned["pmcid"] = None
continue
if isinstance(v, (int, bool)):
cleaned[str(k)] = v
elif isinstance(v, list):
cleaned[str(k)] = [_clean_pin(item) if isinstance(item, dict) else item for item in v]
elif isinstance(v, dict):
sub = _clean_pin(v)
if sub:
cleaned[str(k)] = sub
elif str(v).strip():
cleaned[str(k)] = str(v)
return cleaned or None
def _pin_tag(pin: dict[str, str] | None) -> str:
if not pin:
return "unpinned"
parts = [f"{k}={pin[k]}" for k in ("source_type", "table_id", "row_id", "col_id", "figure_id", "panel") if k in pin]
return ",".join(parts) if parts else "pinned"
def _scrub_internal_code(code: str) -> str:
# Normalize internal review-pass identifiers into neutral audit codes.
out = re.sub(r"^(?!AUDIT-|UNREVIEWED)[A-Z][A-Z0-9]{2,12}-", "AUDIT-", code)
out = re.sub(r"-R\d+S\d+-", "-", out)
out = re.sub(r"_R\d+S\d+\b", "", out)
return out
class _SourceGuard:
"""Fast O(N) detector for >=6-word source shingles and >=40-char dossier substrings."""
def __init__(self, study_shingles: dict[str, set[tuple[str, ...]]], dossier_texts: list[str]) -> None:
self.study_shingles = study_shingles
self.dossier_texts = [_norm_spaces(t) for t in dossier_texts if t]
# Build 40-char substring set from all local dossiers for exact O(1) prefix lookup
self.dossier_prefixes_40: dict[str, list[tuple[int, int]]] = {}
for d_idx, d_txt in enumerate(self.dossier_texts):
limit = max(0, len(d_txt) - 39)
for pos in range(limit):
p40 = d_txt[pos : pos + 40]
self.dossier_prefixes_40.setdefault(p40, []).append((d_idx, pos))
def overlaps(self, queue_id: str, text: str) -> bool:
if not text:
return False
ws = _words(text)
sh_set = self.study_shingles.get(queue_id)
if sh_set and len(ws) >= 6:
for idx in range(len(ws) - 5):
if tuple(ws[idx : idx + 6]) in sh_set:
return True
ns = _norm_spaces(text)
if len(ns) >= 40:
hits = self.dossier_prefixes_40.get(ns[:40])
if hits:
for d_idx, pos in hits:
if self.dossier_texts[d_idx].startswith(ns, pos):
return True
return False
def _structured_replacement(field: str, raw_text: str, meta: dict[str, Any]) -> str:
digest = _sha256_str(raw_text)
if field == "quantitative_summary":
return (
f"[Structured outcome {meta['outcome_id']} ({meta['queue_id']})"
f" | direction={meta['direction']}"
f" | stat={meta['stat_type']}"
f" | pin={meta['pin_tag']}"
f" | text_sha256={digest}]"
)
if field == "endpoint_name":
return (
f"[Structured endpoint {meta['outcome_id']} ({meta['queue_id']})"
f" | stat={meta['stat_type']}"
f" | pin={meta['pin_tag']}"
f" | text_sha256={digest}]"
)
if field == "claim_summary":
cited = ",".join(meta.get("cited_outcome_ids") or []) or "none"
return (
f"[Structured blueprint link {meta['edge_id']}"
f" | relation={meta['relation']}"
f" | applicability={meta['applicability']}"
f" | incorporation={meta['incorporation']}"
f" | outcomes={cited}"
f" | text_sha256={digest}]"
)
if field == "label":
return (
f"[Structured arm {meta['arm_id']} ({meta['queue_id']})"
f" | isolation={meta['causal_isolation']}"
f" | text_sha256={digest}]"
)
if field == "edits_or_interventions":
return f"[Structured intervention ({meta['queue_id']}:{meta['arm_id']}) | text_sha256={digest}]"
return f"[Structured {field} ({meta.get('queue_id', 'study')}) | text_sha256={digest}]"
def _classify_gates_and_designs(target: str) -> tuple[list[str], list[str]]:
t = target or ""
gates: list[str] = []
if re.search(r"\bGate\s*1\b|\bGSIS\b|\bparacrine\b|\bhypoglyc", t, re.I):
gates.append("1")
if re.search(r"\bGate\s*2A\b|\ballo|\bB2M\b|\bCIITA\b|\bHLA-[ABC]\b", t, re.I):
gates.append("2A")
if re.search(r"\bGate\s*2B\b|\bautoimmun|\bINS\b|\bSERPINB9\b|\bPD-L1\b|\bCD274\b|\bCXCL10\b|\bTYK2\b", t, re.I):
gates.append("2B")
if re.search(r"\bGate\s*2\b(?!\s*[AB])", t, re.I) and "2A" not in gates and "2B" not in gates:
gates.extend(["2A", "2B"])
if re.search(r"\bGate\s*3\b|\bNK\b|\bHLA-E\b|\bCD47\b|\bcomplement\b|\bIBMIR\b|\bTHBD\b|\bCD55\b|\bCD59\b", t, re.I):
gates.append("3")
if re.search(r"\bGate\s*4\b|\bcytokine\b|\bER[- ]stress\b|\bamyloid\b|\bIAPP\b|\bTXNIP\b|\bTNFAIP3\b|\bA20\b|\bGPX4\b|\bRNLS\b", t, re.I):
gates.append("4")
if re.search(r"\bGate\s*5\b|\boxygen\b|\bhypoxi|\bCaO2\b|\bpouch\b|\bvascular|\bMVF\b|\biCasp9\b|\bAAVS1\b|\bsafety\s+switch\b|\bsuicide\s+switch\b|\bteratoma\b|\bUCOE\b", t, re.I):
gates.append("5")
if not gates:
gates.append("cross_cutting")
designs: list[str] = []
if re.search(r"\bDesign\s*A\b|\bScenario\s*A\b|\bChassis\s*A\b|\bArm\s*1[AB]\b|\bLocus\s*[1234]\b", t, re.I):
designs.append("A")
if re.search(r"\bDesign\s*B\b|\bScenario\s*B\b|\bChassis\s*B\b|\bHLA-C\b|\bTYK2\b", t, re.I):
designs.append("B")
if re.search(r"\bDesign\s*X\b|\bIslet-X\b|\bChallenger\s*X\b|\bINS\b.*\bsignal|\bFasL\b", t, re.I):
designs.append("X")
if re.search(r"\bDesign\s*Y\b|\bDesign\s*Y-FullStack\b", t, re.I):
designs.append("Y")
if re.search(r"\bD1b(?:-Auto-C)?\b|\bDesign\s*D1b\b", t, re.I):
designs.append("D1b")
if not designs:
designs = ["A", "B", "X"]
return sorted(set(gates)), sorted(set(designs))
SUPERSEDED_PREPRINT_PMIDS_IN_CEG = frozenset({"37745505", "37905040", "39605713"})
CORRESPONDENCE_SECONDARY_PMIDS_IN_CEG = frozenset({"42430558", "40598585"})
VALID_CEG_RECORD_CLASSES = frozenset({
"empirical_primary_study",
"trial_registry_protocol",
"regulatory_or_guidance_document",
"computational_model_or_simulation",
"correspondence_or_secondary_summary",
"superseded_preprint_duplicate",
})
CURATED_INELIGIBLE_EDGE_IDS = frozenset({
"DOI:10.1016/j.celbio.2026.100455:L1",