OpenIslet

scripts/extract_ring1_corpus.py

Step 5B (v0.3 Deep Quantitative & Canonical Graph Upgrade):

script Release v0.8.0 gen-eb955f8266035aba 296 KB · 22 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/extract_ring1_corpus.py · SHA-256: eee6ac565ed0fb16…

    for node_id, node_type, pat in CANONICAL_NODE_PATTERNS:
        if re.search(pat, text, flags=re.IGNORECASE):
            return node_id, node_type
    tl = text.lower()
    if any(k in tl for k in ("transplant", "graft", "implant", "site", "capsule", "portal", "subcutaneous")):
        return "Hypoxia_72h_Ischemia_and_O2_Scaffolds", "Biophysical_or_Vascular_Cue"
    if any(k in tl for k in ("t cell", "t-cell", "lymphocyte", "immune", "rejection", "allogen", "autoimmun")):
        return "Alloreactive_CD8_CD4_TCell_or_DSA_Attack", "Immune_or_Abiotic_Stressor"
    if any(k in tl for k in ("differenti", "stem cell", "ipsc", "hesc", "progenitor", "islet", "beta cell", "β-cell", "β cell")):
        return "MAFA_NKX6_1_PDX1_BetaCell_Identity", "Lineage_Identity_or_Maturation_State"
    if any(k in tl for k in ("insulin", "glucose", "secretion", "glycem", "c-peptide", "diabet")):
        return "Biphasic_GSIS_and_Calcium_Coupling", "Secreted_Hormone_or_Chemokine_DAMP"
    return None, None


def map_pillars(matched_pillars: list[str], full_text: str) -> list[str]:
    out = set()
    for mp in matched_pillars:
        if "Pillar1" in mp:
            out.add("Pillar1_Differentiation_Maturation_Cytoarchitecture")
        if "Pillar2" in mp:
            out.add("Pillar2_Immune_Cloaking_Autoantigen_Neoantigen_Stealth")
        if "Pillar3" in mp:
            out.add("Pillar3_Intrinsic_BetaCell_Genetic_Resilience_Amyloid_Viral")
        if "Pillar4" in mp:
            out.add("Pillar4_Engraftment_Vascularization_Oxygenation_Devices")

    tl = full_text.lower()
    if any(k in tl for k in ("sc-islet", "sc-beta", "differentiation", "stage 6", "stage 7", "mafa", "nkx6.1", "nkx6-1")):
        out.add("Pillar1_Differentiation_Maturation_Cytoarchitecture")
    if any(k in tl for k in ("b2m", "ciita", "cd47", "pd-l1", "hla-e", "fasl", "hypoimmun", "allogeneic", "autoantigen")):
        out.add("Pillar2_Immune_Cloaking_Autoantigen_Neoantigen_Stealth")
    if any(k in tl for k in ("er stress", "thapsigargin", "cytokine", "ifn", "tyk2", "rnls", "txnip", "iapp", "amyloid", "coxsackie", "enterovirus")):
        out.add("Pillar3_Intrinsic_BetaCell_Genetic_Resilience_Amyloid_Viral")
    if any(k in tl for k in ("transplant", "engraft", "vascular", "microvessel", "oxygen", "hypoxia", "encapsulat", "subcutaneous", "oment")):
        out.add("Pillar4_Engraftment_Vascularization_Oxygenation_Devices")

    if not out:
        out.add("Pillar1_Differentiation_Maturation_Cytoarchitecture")
    return sorted(list(out))


def infer_fidelity_tier(
    full_text: str,
    mesh: list[str],
    pub_types: list[str],
    non_methods_text: str | None = None,
) -> str:
    tl = full_text.lower()
    nm = (non_methods_text if non_methods_text is not None else full_text).lower()
    mesh_lower = " ".join(mesh).lower()
    pt_lower = " ".join(pub_types).lower()

    # Exclude forward-looking preclinical conclusions (e.g. "sufficient preclinical testing to proceed
    # to a pilot phase I/II clinical trial") and Methods donor-consent/prior-study NCT numbers from
    # triggering Tier_1_Human_InVivo (ASTRA-05).
    nm_clean = re.sub(
        r"\b(?:preclinical\s+(?:testing|data|studies|work|evidence|results)\b[^.;\n]{0,60}"
        r"|(?:proceed|advance|move|translate|progress|pave\s+the\s+way)\s+(?:to|toward|towards|for)\s+(?:a\s+)?(?:pilot\s+|future\s+)?)"
        r"phase\s+(?:1/2|i/ii)\b",
        "",
        nm,
    )
    nm_clean = re.sub(
        r"(?:clinical\s+islet\s+transplantation\s+program|donor\s+consent|pharmacogenomics\s+of\s+bipolar\s+disorder\s+study)[^.;\n]{0,80}\bnct0\d+",
        "",
        nm_clean,
    )

    if "clinical trial" in pt_lower or any(k in nm_clean for k in ("nct0", "phase 1/2", "phase i/ii", "patients transplanted", "cadaveric t1d pancreas")):
        return "Tier_1_Human_InVivo"
    if any(k in tl for k in ("rhesus", "cynomolgus", "macaque", "nonhuman primate", "non-human primate", "humanized mice", "hu-pbmc", "nsg-sgm3", "blt mice")):
        return "Tier_2A_Human_Cells_InVivo_NHP_or_HumanizedMouse"
    if ("humans" in mesh_lower or any(k in tl for k in ("human islet", "sc-islet", "sc-beta", "hipsc", "hesc", "endoc-bh"))) and any(
        k in tl for k in ("autoreactive t", "cd8+ t", "nk cell", "pbmc", "autoantibod", "alloreactive", "cytotoxic t")
    ):
        return "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture"
    if "humans" in mesh_lower or any(k in tl for k in ("human islet", "sc-islet", "sc-beta", "hipsc", "hesc", "endoc-bh", "human pluripotent")):
        if not re.search(r"\bnon-?human\s+primate\b", tl):
            return "Tier_3_Human_Cells_AbioticStress_or_ImmunodeficientMouse"
    return "Tier_4_Rodent_or_Xenogeneic_Only"


# ---------------------------------------------------------------------------
# IIP-0030 (DEC-109): Hardened Clause-Scoped Oxygen-Bridge Carrier Classifier,
# Scoped Primary-Source hPSC Cell-Source Repairs, Comparator-Arm Carrier Guard,
# and Schema-Clean Curated Overrides (39326417, 36624157 atomic split, 40544428)
# ---------------------------------------------------------------------------

_CARRIER_FAMILY_TOKENS: dict[str, str] = {
    "cao2": r"(?:cao2|calcium\s+peroxide|oxygen[- ]?carrier|o2[- ]?carrier)",
    "pfc": r"(?:perfluor\w*|pfcs?\b|pfob\b|pftba\b|oxyfluor\b|oxycyte\b|fluosol\b|oxygen[- ]?carrier|o2[- ]?carrier)",
    "exog_o2": r"(?:(?:beta|\u03b2)[- ]?air|oxygen\s+chamber|electrochemical\s+oxygen|o2[- ]macrodevice|oxygen[- ]?generat\w*\s+(?:\w+\s+){0,2}(?:device|macrodevice|implant|chamber)|oxygen[- ]?carrier|o2[- ]?carrier)",
    "hb": r"(?:hemoglobin|haemoglobin|myoglobin|hb[- ]?vesicles?|hboc(?:-\d+)?|oxyglobin|hemopure|hemoxcell|hemarina|m101|oxygen[- ]?carrier|o2[- ]?carrier)",
}

_HARDENED_CAO2_PATTERNS: tuple[re.Pattern[str], ...] = (
    re.compile(r"(?i)\b(?:cao2|calcium\s+peroxide)\b"),
)

_PFC_EXCLUSION_RE = re.compile(
    r"(?i)\b(?:prefrontal\s+cortex|cortex|cortical|brain|fmri|pet\s+imaging|metabolic\s+imaging|"
    r"19f(?:\s*[-/]?\s*mri)?|mri\b|magnetic\s+resonance|contrast\s+agent|imaging\s+tracer|mri\s+tracer|"
    r"ultrasound\s+contrast|microbubble|"
    r"splenic\s+pfc|plaque[- ]forming|pfc\s+response|antibody[- ]forming|"
    r"perfluoro\s+elastomer|perfluoroelastomer|ptfe|ferrule|tubing|kruskal[- ]wallis)\b"
)

_HARDENED_PFC_PATTERNS: tuple[re.Pattern[str], ...] = (
    # Specific PFC oxygen-delivery compounds / commercial oxygen emulsions
    re.compile(
        r"(?i)\b(?:perfluorodecalin|perfluorooctyl\s+bromide|perfluorotributylamine|"
        r"pfob|pftba|oxyfluor|oxycyte|fluosol)\b"
    ),
    # Generic perfluorocarbon requires oxygen-delivery / encapsulation / islet context (blocks bare MRI/imaging mentions)
    re.compile(
        r"(?i)(?:\bperfluorocarbon\w*\b.{0,80}\b(?:oxygen\w*|o2\b|hypoxi\w*|carrier|emulsion|nanoemulsion|droplet|hydrogel|scaffold|encapsul\w*|preserv\w*|islet\w*|po2)\b"
        r"|\b(?:oxygen[- ]?carrying|oxygen\w*|hypoxi\w*|carrier|emulsified|nanoemulsion|hydrogel|scaffold|encapsul\w*)\b.{0,55}\bperfluorocarbon\w*\b)"
    ),
    # Uppercase PFC/PFCs with bidirectional oxygen-carrier/emulsion context
    re.compile(
        r"(?-i:\bPFCs?\b)(?=.{0,80}(?i:oxygen|o2\b|emulsion|nanoemulsion|droplet|carrier|perfluor|islet\s+po2))"
    ),
    re.compile(
        r"(?i:oxygen[- ]?carrying|emulsified|nanoemulsion|perfluor\w*|emulsion\s+containing.{0,20}|vol%\s+(?:oxygen|o2)[^\n.;]{0,30})"
        r".{0,45}(?-i:\bPFCs?\b)"
    ),
    # Lowercase pfc only when directly paired with emulsion/nanoemulsion/oxygen-carrier (never Kruskal-Wallis (pFC))
    re.compile(
        r"(?i)\bpfc\s+(?:emulsion|nanoemulsion|droplets?|oxygen[- ]?carrier|o2[- ]?carrier)\b"
    ),
)

_HARDENED_EXOG_O2_PATTERNS: tuple[re.Pattern[str], ...] = (
    re.compile(r"(?i)(?:\b|(?<=\s))(?:beta|\u03b2)[- ]?air\b"),
    re.compile(r"(?i)\b(?:oxygen\s+chamber|electrochemical\s+oxygen|o2[- ]macrodevice)\b"),
    re.compile(r"(?i)\b(?:oxygen[- ]?generat\w*|wireless[, ]+(?:battery[- ]?free\s+)?oxygenation)\s+(?:\w+\s+){0,3}(?:device|macrodevice|implant|chamber|platform)s?\b"),
)

_HARDENED_HB_PATTERNS: tuple[re.Pattern[str], ...] = (
    re.compile(r"(?i)\b(?:hemoxcell|hemarina|hboc(?:-\d+)?|oxyglobin|hemopure)\b"),
    re.compile(r"(?i)\barenicola\s+marina\b.{0,45}\b(?:m101|hemoglobin|haemoglobin|oxygen|o2)\b"),
    re.compile(
        r"(?i)(?:(?<!clone\s)(?<!strain\s)(?<!line\s)\bm101\b.{0,65}(?:g/l|mg/ml|oxygen|o2|hypoxia|preserv\w*|islet|viab\w*|carrier|arenicola|hemarina|extracellular)"
        r"|(?:preserv\w*|supplement\w*|oxygen\w*|hypoxia|hemoxcell|arenicola|hemarina|carrier).{0,55}(?<!clone\s)(?<!strain\s)(?<!line\s)\bm101\b)"
    ),
    re.compile(r"(?i)\b(?:hb[- ]?vesicles?|hemoglobin[- ]?vesicles?|haemoglobin[- ]?vesicles?)\b"),
    re.compile(
        r"(?i)\b(?:hemoglobin|haemoglobin|myoglobin)\s*[-/]?\s*"
        r"(?:based|loaded|encapsulated|conjugated|cross[- ]?linked|containing|functionalized)\s*"
        r"(?:hydrogel|scaffold|matrix|alginate|peg(?:-\d*mal)?|gel\b|microsphere|microparticle|nanoparticle|"
        r"oxygen\s+carrier|o2\s+carrier|vesicle|biomaterial|microcapsule)"
    ),
    # Reverse-order PEG-hemoglobin / pegylated hemoglobin / alginate-hemoglobin / cell-free hemoglobin perfusate
    re.compile(r"(?i)\b(?:peg|pegylated|alginate|hydrogel|scaffold|matrix)\s*[- ]\s*(?:hemoglobin|haemoglobin|myoglobin|hb)\b"),
    re.compile(r"(?i)\bcell[- ]free\s+(?:hemoglobin|haemoglobin)\b.{0,60}\b(?:perfus\w*|oxygen\w*|o2\b|carrier|islet|preserv\w*|hypoxi\w*|solution|medium)\b"),
    re.compile(r"(?i)\b(?:perfus\w*|oxygen\w*|carrier|preserv\w*)\b.{0,50}\bcell[- ]free\s+(?:hemoglobin|haemoglobin)\b"),
    # American & British spelling: polymerized/polymerised, cross-linked, extracellular, marine hemoglobin/haemoglobin
    re.compile(r"(?i)\b(?:cross[- ]?linked|polymeri[sz]ed|pegylated|extracellular|marine(?:\s+worm)?)\s+(?:hemoglobin|haemoglobin|myoglobin)\b"),
    re.compile(
        r"(?i)\b(?:hydrogel|scaffold|alginate|peg(?:-\d*mal)?|matrix|oxygen\s+carrier|o2\s+carrier)\s+"
        r"(?:containing|loaded\s+with|functionalized\s+with|supplemented\s+with|conjugated\s+(?:to|with))\s+"
        r"(?:hemoglobin|haemoglobin|myoglobin)\b"
    ),
)

_HPSC_GENERIC_TITLE_RE = re.compile(
    r"(?i)\b(?:hpscs?|hsc[- ]islets?|human\s+pluripotent\s+stem[- ]cell[- ]derived|"
    r"pluripotent\s+stem[- ]cell[- ]derived|stem[- ]cell[- ]derived\s+(?:pancreatic\s+|fully\s+differentiated\s+)?(?:islets?|beta|\u03b2|endocrine|pancreatic\s+endoderm)|"
    r"stem\s+cell[- ]derived,?\s+fully\s+differentiated\s+islets?)\b"
)

# Individually source-verified stage repairs strictly for the 7 hPSC records
# that otherwise fell through to semantically contradictory "Primary_Mature_Islet".
_HPSC_PRIMARY_MATURE_STAGE_REPAIRS: dict[str, str | None] = {
    "31756031": "Stage6_Immature_SC_Islet",      # Davis 2019: in vitro SC-beta zinc enrichment
    "34345868": "InVivo_Engrafted_Maturation",   # Kenty 2021: retrieval of in-vivo engrafted SC-beta cells in mice (HUES-8 hESC)
    "34861146": "InVivo_Engrafted_Maturation",   # Ramzy 2021: Phase 1/2 PEC-01 implanted in vivo -> mature beta cells at 1 yr
    "36624157": "InVivo_Engrafted_Maturation",   # Liang 2023: NHP sub-ARS CiPSC-islets survive and mature in vivo
    "37040771": None,                            # Zhu 2023: multi-stage in vitro H1/WA01 differentiation + primary human donor pancreas comparison
    "40544428": "InVivo_Engrafted_Maturation",   # Reichman 2025: Zimislecel Phase 1-2 human portal-vein infusion (12 mo)
    "40987274": "InVivo_Engrafted_Maturation",   # Xiong & Berggren 2025: Preview of vascularized hPSC-islets maturation/in vivo grafts
}

# Primary-source verification recovered exact cell-source classes and named lines for 7 of the 15
# Primary_Human_Islet stem-cell misclassifications (remaining 8 map to hPSC_Derived_Unspecified_Line):
_HPSC_EXACT_LINE_SOURCE_REPAIRS: dict[str, tuple[str, str | None]] = {
    "34345868": ("hESC", "HUES8"),
    "36497105": ("hESC", "MEL1"),
    "36624157": ("CiPSC_chemically_induced", "hCiPSC-8# (hPSC-8)"),
    "37040771": ("hESC", "H1/WA01"),
    "37809993": ("iPSC_healthy_donor", "TkDN4-M"),
    "40544428": ("hESC", "Undisclosed proprietary hESC line (zimislecel / VX-880; USAN-documented hESC origin)"),
    "40700651": ("hESC", "WA01/H1"),
}

_COMPARATOR_EXPLICIT_NO_O2_RE = re.compile(
    r"(?i)\b(?:unoxygenated|non[- ]?oxygenated|without\s+(?:exogenous\s+)?(?:oxygen\w*|o2\b|carrier|cao2|pfc|hemoglobin|hemoxcell)|"
    r"no\s+(?:exogenous\s+)?(?:oxygen\w*|o2\b|carrier|cao2|pfc|hemoglobin|hemoxcell)|"
    r"(?:oxygen|o2|cao2|pfc|hemoglobin)[- ]free|passive\s+(?:diffusion|control)|unpowered|sham\s+device)\b"
)


def _split_carrier_clauses(text: str) -> list[str]:
    clauses: list[str] = []
    for sent in re.split(r"(?<=[.!?])\s+|\n+", text):
        sent = sent.strip()
        if not sent:
            continue
        # Split contrasting comparator prefixes ("Unlike prior perfluorocarbon..., HEMOXCell was administered")
        # and clause boundaries (";" or ", whereas/while/but/however/without") so negating one carrier
        # does not silence a genuinely administered carrier in the main clause.
        sub = re.split(
            r"\s*;\s*"
            r"|,\s+(?=(?:whereas|while|but|however|yet|without|free\s+of|lacking|devoid\s+of)\b)"
            r"|(?<=,\s)(?=(?:our|we|the|islets|cells|grafts|hemoxcell|m101|hboc|perfluor\w*|pfob|cao2|calcium\s+peroxide)\b)",
            sent,
            flags=re.IGNORECASE,
        )
        for piece in sub:
            piece = piece.strip()
            if piece:
                clauses.append(piece)
    return clauses


def _clause_negates_family(clause: str, family: str) -> bool:
    tok = _CARRIER_FAMILY_TOKENS[family]
    # 1. Leading comparator clause ("Unlike prior perfluorocarbon emulsions...", "Compared with prior HBOC...")
    if re.search(
        rf"(?i)\b(?:unlike|instead\s+of|rather\s+than|compared\s+(?:to|with)\s+(?:prior|previous|conventional|existing))\s+"
        rf"(?:prior\s+|previous\s+|conventional\s+|existing\s+)?(?:[\w-]+\s+){{0,4}}{tok}",
        clause,
    ):
        return True
    # 2. Explicit negative quantifier before carrier ("no HEMOXCell", "uses no added oxygen carrier", "without hemoglobin", "not loaded with CaO2")
    if re.search(
        rf"(?i)\b(?:uses?|used|using|contains?|containing|administered|loaded\s+with|supplemented\s+with)?\s*"
        rf"(?:no|without|free\s+of|lacking|devoid\s+of|absent|not\s+(?:loaded\s+with|supplemented\s+with|containing|using|treated\s+with))\s+"
        rf"(?:added\s+|any\s+|exogenous\s+)?(?:[\w-]+\s+){{0,3}}{tok}",
        clause,
    ):
        return True
    # 3. Carrier followed by negative passive verb ("No HEMOXCell was administered", "CaO2 was not loaded", "HEMOXCell was omitted")
    if re.search(
        rf"(?i)\b{tok}\b.{{0,40}}\b(?:was|were|is|are)\s+(?:not\s+(?:administered|used|added|loaded|included|supplied)|omitted|absent|excluded)\b",
        clause,
    ):
        return True
    # 4. Suffix "-free" ("CaO2-free", "hemoglobin-free", "PFC-free")