OpenIslet

scripts/build_cross_study_graph.py

Step 4: Full Recursive Schema Validator & Cross-Study Causal / Effect-Modifier Graph Builder

script Release v0.8.0 gen-eb955f8266035aba 62 KB · 5 sections

Use this file in any AI chat (paste-only or attachment-capable):

Download as text (.txt) Download section (.txt)

Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/build_cross_study_graph.py · SHA-256: 94a7b2be6571d9e1…

#!/usr/bin/env python3
"""
Step 4: Full Recursive Schema Validator & Cross-Study Causal / Effect-Modifier Graph Builder
1. Recursively validates all extracted JSON files in data/extracted/*.json against schemas/extraction_schema_v0.2.json
   (checking required fields, types, and enum values across all nested objects and arrays).
2. Builds the unified Cross-Study Causal & Effect-Modifier Graph (data/extracted/cross_study_discovery_graph.json):
   - Aggregates all atomic_effects (X -> Y | Z) across studies
   - Aggregates all effect_modifier_interactions (dEffect/dZ != 0) by modifier class Z1..Z8
   - Extracts all canonical biological concept nodes per edge/finding to link directed causal_mechanism_edges
     and cross_study_discovery_bridges across disconnected papers
   - Synthesizes explicit multi-study discovery chains (Study A -> Shared Biological Node -> Study B)
"""

from __future__ import annotations

import json
import re
from collections import defaultdict, Counter
from pathlib import Path
from typing import Any

BASE_DIR = Path(__file__).resolve().parent.parent
SCHEMA_PATH = BASE_DIR / "schemas" / "extraction_schema_v0.2.json"
EXTRACTED_DIR = BASE_DIR / "data" / "extracted"

CANONICAL_CONCEPT_PATTERNS: dict[str, str] = {
    "HLA_DR3_DR4_T1DE1_T1DE2_Endotype_Architecture": r"\b(HLA-DR3|HLA-DR4|DR3-DQ2|DR4-DQ8|DR3-T1D|DR4-T1D|T1DE1|T1DE2|IAA-first|GADA-first|endotype)\b",
    "MastCell_Histamine_CPA3_TPSAB1_Axis": r"\b(mast cell|histamine|tryptase|CPA3|TPSAB1|FcεRI|cromolyn|ketotifen|cetirizine)\b",
    "PMN_Neutrophil_NETosis_PAD4_CD99_CD200_Axis": r"\b(polymorphonuclear|\bPMN\b|\bPMNs\b|NETosis|neutrophil extracellular trap|PAD4|PADI4|CD99|CD200|myeloperoxidase)\b",
    "RIPK1_RIPK3_MLKL_Necroptosis_and_Ferroptosis_Axis": r"\b(RIPK1|RIPK3|MLKL|pMLKL|necroptosis|necrostatin|Nec-1|ferroptosis|GPX4|CXCL16|OxLDL)\b",
    "B2M_HLA_Class_I_Complex": r"\b(B2M|beta-2-microglobulin|HLA-A|HLA-B|HLA-C|HLA-ABC|MHC class I\b|MHC-I\b|HLA class I)\b",
    "CIITA_HLA_Class_II_Complex": r"\b(CIITA|HLA-DR|HLA-DQ|HLA-DP|MHC class II\b|MHC-II\b|HLA class II)\b",
    "CD47_SIRPa_DonotEatMe_Axis": r"\b(CD47|SIRP\s*alpha|SIRPα)\b",
    "HLA_E_NKG2A_Inhibitory_Axis": r"\b(HLA-E|HLA-G|Qa-1b|NKG2A|NKG2C|VMAPRTLVL|B2M-HLA-E)\b",
    "PVR_TIGIT_MICA_MICB_NKG2D_Axis": r"\b(PVR|CD155|TIGIT|MICA|MICB|ULBP1|ULBP2|NKG2D|NCR3LG1)\b",
    "PD_L1_CD274_Checkpoint": r"\b(PD-L1|PDL1|CD274|PD-1)\b",
    "HVEM_CD40_BTN3A1_Costimulation": r"\b(HVEM|TNFRSF14|CD40|CD80|CD86|BTN3A1|CTLA4|CTLA-4)\b",
    "FasL_FASLG_Treg_Tolerance_Signal": r"\b(FasL|SA-FasL|FASLG|CD95L)\b",
    "IL2_TGFb_IL10_FOXP3_Treg_Induction": r"\b(FOXP3|FoxP3|Treg|regulatory T cell|IL-10|TGF-beta|TGFB1|IL-2 mutein|2B10)\b",
    "CXCL10_CXCR3_Chemokine_Recruitment": r"\b(CXCL10|IP-10|CXCL9|CXCL11|CCL5|CXCR3)\b",
    "IFNg_IFNa_IL1b_TNFa_Cytokine_Challenge": r"\b(IFN-gamma|IFNγ|IFN-alpha|IFNα|IL-1beta|IL-1β|TNF-alpha|TNFα|pro-inflammatory cytokine)\b",
    "TYK2_JAK1_STAT1_IRF1_Signaling": r"\b(TYK2|TYK2i|BMS-986165|JAK1|JAK2|STAT1|STAT2|IRF1|IRF-1|ruxolitinib|SOCS1|PSMB8|TAP1)\b",
    "TNFAIP3_A20_NFkB_JNK_Brake": r"\b(TNFAIP3|\bA20\b|NF-kB|NF-κB)\b",
    "PTPN2_Phosphatase_STAT1_Brake": r"\b(PTPN2|TC-PTP)\b",
    "RNLS_Glycolytic_NADPH_GSH_Redox_Shield": r"\b(RNLS|Rnls|renalase|pargyline|NADPH|GSH:GSSG|glutathione)\b",
    "ER_Stress_UPR_IRE1_PERK_CHOP_TXNIP": r"\b(ER stress|unfolded protein response|UPR|IRE1|XBP1|sXBP1|PERK|ATF4|ATF6|CHOP|DDIT3|TXNIP|BiP|HSPA5|MANF|thapsigargin|tunicamycin|DTT|Akita)\b",
    "SERPINB9_GranzymeB_Perforin_Apoptosis_Axis": r"\b(SERPINB9|PI-9|granzyme|perforin|caspase-3|cleaved caspase)\b",
    "SLC30A8_ZnT8_Granule_Zinc_Autoantigen": r"\b(SLC30A8|ZnT8|ZnT8A)\b",
    "G6PC2_IGRP_Glycolytic_Autoantigen": r"\b(G6PC2|IGRP)\b",
    "GAD2_GAD65_GABA_Paracrine_Autoantigen": r"\b(GAD2|GAD65|GADA|\bGABA\b)\b",
    "INS_Preproinsulin_Signal_Peptide_DRiP": r"\b(preproinsulin|insulin signal peptide|PPI15-24|INS-DRiP|insulin B9-23)\b",
    "Hypoimmune_HIP_B2M_CIITA_CD47_Edit": r"\b(hypoimmune|HIP\s+(?:p-islet|pseudoislet|islet|iEC|iPSC|cell|mouse|mice|graft))\b",
    "CHGA_WE14_Hybrid_Insulin_Peptide_HIP": r"\b(hybrid insulin peptide|WE14|proinsulin[-\s]chromogranin|chromogranin A)\b",
    "IAPP_Amyloid_Oligomer_Inflammasome": r"\b(IAPP|hIAPP|islet amyloid|amylin|pramlintide|NLRP3)\b",
    "CXADR_IFIH1_Enterovirus_CVB_Infection": r"\b(CXADR|CAR-SIV|Coxsackie|CVB3|CVB4|enterovirus|IFIH1|MDA5)\b",
    "CD55_CD59_THBD_Complement_IBMIR_Axis": r"\b(CD55|CD59|CD46|CD39|ENTPD1|THBD|thrombomodulin|IBMIR|complement|tissue factor)\b",
    "Stage7_3D_Suspension_Cytoarchitecture": r"\b(Stage 7|3D suspension|3D aggregat|reaggregat|cluster diameter|microwell|AggreWell|organoid)\b",
    "MAFA_NKX6_1_PDX1_BetaCell_Identity": r"\b(MAFA|NKX6\.1|NKX6-1|PDX1|NEUROG3|NKX2\.2|ISL1|UCN3)\b",
    "WNT4_ESRRG_Mitochondrial_OXPHOS_Switch": r"\b(WNT4|ESRRG|ERR\s*gamma|ERRγ|OXPHOS|mitochondrial respiration|OCR|ECAR|LDHA|HK2|SLC16A1|MCT1|pyruvate)\b",
    "Biphasic_GSIS_and_Calcium_Coupling": r"\b(GSIS|glucose-stimulated insulin secretion|biphasic|first-phase|perifusion|C-peptide|calcium influx|KATP)\b",
    "Alpha_GCG_Delta_SST_Paracrine_CounterRegulation": r"\b(glucagon|\bGCG\b|somatostatin|\bSST\b|alpha cell|delta cell|paracrine)\b",
    "OffTarget_SLC18A1_Enterochromaffin_Depletion": r"\b(SLC18A1|enterochromaffin|SC-EC|TPH1|LMX1A)\b",
    "ZM447439_Aurora_G1_CellCycle_Exit": r"\b(ZM447439|aurora kinase|Ki-67|G0/G1|cell cycle exit|teratoma|iCasp9|HSV-TK)\b",
    "CD31_CD146_Microvessel_Inosculation": r"\b(microvessel|microvascular fragment|CD31|CD146|inosculation|anastomos|revasculariz|endothelial|HUVEC|iEC|VEGFA)\b",
    "Hypoxia_72h_Ischemia_and_O2_Scaffolds": r"\b(hypoxia|ischemi|oxygen tension|pO2|CaO2|calcium peroxide|perfluorocarbon|subcutaneous|omental|intramuscular)\b",
    "Alginate_or_Macrodevice_Encapsulation_FBR": r"\b(alginate|macroencapsul|microencapsul|TheraCyte|PEC-Direct|PEC-Encap|hydrogel|fibrotic|foreign body)\b",
    "Alloreactive_CD8_CD4_TCell_or_DSA_Attack": r"\b(alloreactive|allogeneic T|allograft rejection|PBMC|donor-specific antibod|DSA|CD8\+ T|CD4\+ T|cytotoxic T)\b",
    "Primary_NK_or_Macrophage_Innate_Cytotoxicity": r"\b(NK cell|natural killer|missing-self|missing self|macrophage|phagocytos)\b",
    "BetaCell_Survival_and_Glycemic_Cure": r"\b(normoglycemi|diabetes reversal|graft survival|beta-cell survival|cell viability|apoptosis|cell death|specific lysis)\b",
}


def extract_canonical_concepts(text: str) -> list[str]:
    found = []
    for concept, pat in CANONICAL_CONCEPT_PATTERNS.items():
        if re.search(pat, text, flags=re.IGNORECASE):
            found.append(concept)
    return found


def validate_against_schema(instance: Any, schema_node: dict[str, Any], path: str = "$") -> None:
    """Apply the complete declared JSON Schema and reject non-JSON numbers.

    Python's JSON decoder accepts NaN and Infinity by default. They are not
    scientific observations and must fail before any graph aggregation.
    """
    import math
    from jsonschema import Draft202012Validator
    def finite_json(value, location):
        if isinstance(value, float) and not math.isfinite(value):
            raise ValueError(f"{location}: non-finite number is not valid JSON evidence")
        if isinstance(value, dict):
            for key, child in value.items():
                finite_json(child, f"{location}.{key}")
        elif isinstance(value, list):
            for index, child in enumerate(value):
                finite_json(child, f"{location}[{index}]")
    finite_json(instance, path)
    errors = list(Draft202012Validator(schema_node).iter_errors(instance))
    if errors:
        error = errors[0]
        suffix = "".join(f"[{part}]" if isinstance(part, int) else f".{part}" for part in error.absolute_path)
        raise ValueError(f"{path}{suffix}: {error.message}")


def _has_matched_cell_source_and_stage(left: dict, right: dict) -> bool:
    """Unknown labels are missing information, not evidence of compatibility."""
    for field in ("cell_source_class", "canonical_differentiation_stage_evaluated"):
        value = left.get(field)
        if not isinstance(value, str) or not value.strip() or value != right.get(field):
            return False
        if any(token in value.lower() for token in ("unknown", "unspecified", "mixed", "not_reported", "nonislet")):
            return False
    return True


def _validate_graph_references(doc: dict, path: str) -> None:
    for collection, identifier in (("arms", "arm_id"), ("atomic_effects", "effect_id")):
        identifiers = [row[identifier] for row in doc[collection]]
        if any(not isinstance(value, str) or not value for value in identifiers) or len(identifiers) != len(set(identifiers)):
            raise ValueError(f"{path}: {identifier} values must be nonempty and unique")
    _meta = doc.get("study_metadata") or {}
    _src_type = str(_meta.get("source_text_type") or "")
    if _src_type == "Review_or_Commentary" and (doc.get("arms") or doc.get("atomic_effects")):
        raise ValueError(
            f"{path}: Review_or_Commentary record must have 0 primary arms and 0 primary atomic_effects"
        )
    _abstract_indexed = _meta.get("abstract_indexed")
    _title_norm = re.sub(r"\s+", " ", str(_meta.get("title") or "").strip()).rstrip(".?!:;").lower()
    _bib_re = re.compile(
        r"(?:\bDOI\b|10\.\d{4,9}/\S+"
        r"|\b(?:NEJM|N\.?\s*Engl\.?\s*J\.?\s*Med\.?|Correspondence|Letter)\b.{0,40}\b(?:19|20)\d{2}\b"
        r"|\b(?:19|20)\d{2}\b.{0,40}\b(?:NEJM|N\.?\s*Engl\.?\s*J\.?\s*Med\.?|Correspondence|Letter)\b"
        r"|\b\d{1,4}\(\d{1,3}\):\s*\d+\s*[-\u2013\u2014]\s*\d+\b)",
        flags=re.IGNORECASE,
    )
    _bib_strip_re = re.compile(
        r"(?:10\.\d{4,9}/[^\s,;)\]]+"
        r"|\b(?:doi|pmid|pmcid|nejm|n\.?\s*engl\.?\s*j\.?\s*med\.?|correspondence|letter|commentary|editorial|vol(?:ume)?|issue|no|pp?|et\s+al)\b"
        r"|\b(?:19|20)\d{2}\b"
        r"|\b\d{1,5}(?:\(\d{1,4}\))?(?::\s*\d+(?:[-\u2013\u2014]\d+)?)?\b"
        r"|[\s\(\)\[\]\{\}:;,.\-\u2013\u2014/]+)",
        flags=re.IGNORECASE,
    )
    _span_zero_re = re.compile(r"^[A-Za-z0-9_.\[\]]+\[0:(\d+)\]\|norm=(?:exact|whitespace_normalized)$")
    for _eff_p in doc.get("atomic_effects", []):
        _eid_p = str(_eff_p.get("effect_id") or "")
        _q_p = _eff_p.get("verbatim_evidence_quote")
        _sp_p = _eff_p.get("source_span")
        if (_q_p is None) != (_sp_p is None):
            raise ValueError(f"{path}: {_eid_p} R1/R2 violation — verbatim_evidence_quote and source_span must either both be null or both be non-null")
        if _q_p is None and _sp_p is None:
            if not (_src_type == "Citation_Only_No_Abstract_Indexed" and _abstract_indexed is False):
                raise ValueError(f"{path}: {_eid_p} R1 violation — null quote/source_span allowed strictly on Citation_Only_No_Abstract_Indexed with abstract_indexed=False")
            continue
        if isinstance(_sp_p, str) and _sp_p.startswith("abstract[") and (
            _src_type == "Citation_Only_No_Abstract_Indexed" or _abstract_indexed is False
        ):
            raise ValueError(f"{path}: {_eid_p} R1 violation — abstract[...] source_span {_sp_p!r} forbidden on citation-only/unindexed-abstract record")
        if isinstance(_q_p, str) and not _q_p.startswith(("[REDACTED_NON_OA_EXCERPT:", "[REDACTED_CONSERVATIVE_EXCERPT:")):
            _nq_p = re.sub(r"\s+", " ", _q_p.strip()).rstrip(".?!:;").lower()
            if _title_norm and _nq_p:
                if _nq_p == _title_norm:
                    raise ValueError(f"{path}: {_eid_p} R2 violation — verbatim_evidence_quote echoes study title")
                if _nq_p.startswith(_title_norm):
                    _rem_p = _nq_p[len(_title_norm):].strip()
                    if not _rem_p or _bib_strip_re.sub("", _rem_p) == "" or (
                        re.fullmatch(r"[\(\[].*[\)\]]", _rem_p) and _bib_re.search(_rem_p)
                    ):
                        raise ValueError(f"{path}: {_eid_p} R2 violation — verbatim_evidence_quote echoes title+bibliographic citation label")
            if isinstance(_sp_p, str):
                _m0 = _span_zero_re.match(_sp_p)
                if _m0 and int(_m0.group(1)) == len(_q_p) and _bib_re.search(_q_p):
                    raise ValueError(f"{path}: {_eid_p} R2 violation — coextensive [0:{len(_q_p)}] span carries bibliographic furniture")
    arms = {arm["arm_id"]: arm for arm in doc["arms"]}
    _subtrial_stop = {
        "pmid", "arm", "arms", "ctrl", "ref", "control", "controls", "cohort", "cohorts",
        "placebo", "matched", "reference", "comparator", "vehicle", "saline", "untreated",
        "daily", "monthly", "weekly", "systemic", "oral", "human", "murine", "mouse", "mice",
        "rat", "rats", "islet", "islets", "graft", "grafts", "cell", "cells", "cluster", "clusters",
        "group", "groups", "with", "without", "and", "the", "for", "from", "only", "alone",
        "overall", "primary", "adult", "wild", "type", "transgenic", "model", "models",
        "assay", "vitro", "vivo", "comparison", "baseline", "treated", "treatment", "therapy",
        "negative", "positive", "expressing", "full", "length", "table", "fig", "figure",
        "contrast", "blocking", "stimulated", "exposed", "variant", "variants", "fragment",
        "recombinant", "recombinants", "carrying", "lacking", "plus", "minus", "not", "all",
        "high", "low", "derived", "macrophage", "macrophages", "bone", "marrow", "c57bl",
        "bmdm", "porcine", "aortic", "endothelial", "paec", "liposome", "liposomes",
        "depleted", "intact", "autologous", "tpiat", "patients", "patient", "sequentially",
        "site", "sites", "supplementary", "extended", "data", "threshold", "dual",
        "over", "under", "after", "before", "during", "within", "between", "into", "onto",
        "than", "that", "this", "were", "have", "been", "showed", "overexpression",
        "expression", "knockout", "double", "single",
    }
    _short_domain_toks = {"wt", "ko", "ki", "tg", "c3", "c5", "5e", "6f", "d7", "o2", "h2"}
    def _g_tok_text(text: str) -> set[str]:
        low = (text or "").lower().replace("\u03b2", "beta")
        toks = set()
        if "primary human" in low or "primary adult human" in low:
            toks.add("primaryhuman")
        for t in re.findall(r"[a-z0-9]+", low):
            if t.isdigit():
                continue
            if (len(t) >= 3 or t in _short_domain_toks) and t not in _subtrial_stop:
                toks.add(t)
        return toks
    def _g_arm_disc_tokens(arm_obj: dict) -> set[str]:
        aid_clean = re.sub(r"^pmid\d+_arm\d+_?", "", str(arm_obj.get("arm_id") or "").lower())
        raw_lbl = str(arm_obj.get("arm_label") or "")
        if raw_lbl.startswith("[REDACTED_"):
            raw_lbl = ""
        toks = _g_tok_text(f"{aid_clean} {raw_lbl}")
        for t in list(toks):
            if "gtko" in t:
                toks.add("gtko")
            if "hcd64" in t:
                toks.add("hcd64")
            if "hiapp" in t:
                toks.add("hiapp")
        return toks
    def _g_tok_matches(tset_a: set[str], tset_b: set[str]) -> set[str]:
        hits = set()
        for a in tset_a:
            if a in tset_b:
                hits.add(a)
                continue
            if len(a) >= 5 and a.isalpha():
                for b in tset_b:
                    if len(b) >= 5 and b.isalpha() and (a.startswith(b) or b.startswith(a)):
                        hits.add(a)
                        break
        return hits
    def _g_fig_table_refs(text: str) -> tuple[set[str], set[str]]:
        low = (text or "").lower()
        figs: set[str] = set()
        tabs: set[str] = set()
        for _m_ft in re.finditer(r"\b(figs?|figures?|tables?)\.?\s*((?:[0-9]+[a-z]?|[ivxlcdm]+)(?:\s*(?:,\s*and|,|and)\s*(?:[0-9]+[a-z]?|[ivxlcdm]+))*)", low):
            _dest = tabs if _m_ft.group(1).startswith("table") else figs
            for _tok in re.findall(r"[0-9]+[a-z]?|[ivxlcdm]+", _m_ft.group(2)):
                if _tok != "and":
                    _dest.add(_tok)
        return figs, tabs
    _focal_arm_ids = [a["arm_id"] for a in doc.get("arms", []) if not a.get("is_reference_control", False)]
    _ref_arm_ids = [a["arm_id"] for a in doc.get("arms", []) if a.get("is_reference_control", False)]
    _toks_by_arm = {aid: _g_arm_disc_tokens(a) for aid, a in arms.items()}
    _figs_by_arm = {aid: (_g_fig_table_refs(str(a.get("arm_label") or "")) if not str(a.get("arm_label") or "").startswith("[REDACTED_") else (set(), set())) for aid, a in arms.items()}
    _univ_focal = set.intersection(*(_toks_by_arm[fid] for fid in _focal_arm_ids)) if len(_focal_arm_ids) >= 2 else set()
    _disc_focal = {fid: _toks_by_arm[fid] - _univ_focal for fid in _focal_arm_ids}
    _uniq_focal = {
        fid: _toks_by_arm[fid] - (set().union(*(_toks_by_arm[o] for o in _focal_arm_ids if o != fid)) if len(_focal_arm_ids) > 1 else set())