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…

            ("CyT49", r"\bcyt49\b"),
            ("HEL46.11", r"\bhel46\.11\b"),
            ("HEL24.3", r"\bhel24\.3\b"),
        ):
            if re.search(pat, tl):
                cell_line = cl
                break
        if cell_line in ("HUES8", "WA01", "H1", "MEL1", "CyT49") and source_class in (
            "iPSC_healthy_donor",
            "iPSC_T1D_or_LADA_patient",
            "CiPSC_chemically_induced",
        ):
            source_class = "hESC"
    elif source_class == "EndoC_betaH1_or_H2_H3":
        if re.search(r"\bendoc-(?:β|beta)h3\b", tl):
            cell_line = "EndoC-βH3"
        elif re.search(r"\bendoc-(?:β|beta)?h1\b", tl):
            cell_line = "EndoC-βH1"
    elif source_class == "Rodent_Beta_Cell_Line_NIT1_MIN6_INS1":
        for cl, pat in (
            ("INS-1E", r"\bins-1e\b"),
            ("INS-1", r"\bins-1\b"),
            ("MIN6", r"\bmin-?6\b"),
            ("NIT-1", r"\bnit-1\b"),
        ):
            if re.search(pat, tl):
                cell_line = cl
                break

    if "stage 7" in tl or "s7w" in tl or "biphasic" in tl:
        stage = "Stage7_MetabolicallyMature_SC_Islet"
    elif "sc-islet" in tl or "sc-beta" in tl or "stage 6" in tl:
        stage = "Stage6_Immature_SC_Islet"
    elif "neurog3" in tl or "endocrine progenitor" in tl or "stage 5" in tl:
        stage = "Stage5_EndocrineProgenitor_NEUROG3"
    elif "pancreatic progenitor" in tl or "stage 4" in tl or "pdx1+nkx6" in tl:
        stage = "Stage4_PancreaticProgenitor_PDX1_NKX6_1"
    else:
        stage = "Primary_Mature_Islet"

    if source_class == "Primary_Human_Islet" and title and _HPSC_GENERIC_TITLE_RE.search(title):
        if pmid in _HPSC_EXACT_LINE_SOURCE_REPAIRS:
            source_class, cell_line = _HPSC_EXACT_LINE_SOURCE_REPAIRS[pmid]
        else:
            source_class = "hPSC_Derived_Unspecified_Line"
        if stage == "Primary_Mature_Islet" and pmid in _HPSC_PRIMARY_MATURE_STAGE_REPAIRS:
            stage = _HPSC_PRIMARY_MATURE_STAGE_REPAIRS[pmid]
    return source_class, cell_line, stage


def infer_transplant_site_and_niche(full_text: str) -> dict[str, Any]:
    tl = full_text.lower()
    if "portal vein" in tl or "intrahepatic" in tl:
        site = "Portal_Vein_Intrahepatic"
    elif "omentum" in tl or "omental" in tl:
        site = "Omental_Pouch"
    elif "prevascular" in tl or ("subcutaneous" in tl and any(k in tl for k in ("device", "microvessel", "scaffold", "hydrogel", "pouch", "catheter"))):
        site = "Subcutaneous_Prevascularized_or_Device"
    elif "subcutaneous" in tl:
        site = "Subcutaneous_Unmodified"
    elif "intramuscular" in tl or "quadricep" in tl or "hindlimb muscle" in tl or "rectus" in tl or "brachioradialis" in tl or "forearm" in tl:
        site = "Intramuscular_Forearm_or_Rectus"
    elif re.search(r"\b(?:anterior\s+chamber|intraocular)\b", tl):
        site = "Anterior_Chamber_Eye"
    elif "epididymal" in tl or "fat pad" in tl or "perigonadal" in tl:
        site = "Epididymal_or_Perigonadal_Fat_Pad"
    elif "kidney capsule" in tl or "renal subcapsular" in tl or "subcapsular" in tl:
        site = "Kidney_Capsule"
    elif re.search(r"\b(?:transplant\w*|graft\w*|recipient\w*|implant\w*|allograft\w*|xenograft\w*)\b", tl) and not re.search(r"\b(?:in\s+vitro\s+only|no\s+transplantation)\b", tl):
        site = "Unspecified_InVivo_or_Source_Site"
    else:
        site = "InVitro_Only"

    has_iec = bool(re.search(r"\biecs?\b", tl))
    if "microvessel" in tl or "microvascular fragment" in tl:
        vasc = "Microvascular_Fragment_CoAssembly"
    elif "pericyte" in tl and ("endothelial" in tl or has_iec or "huvec" in tl):
        vasc = "Endothelial_plus_Pericyte_Vascularized_Organoid"
    elif "endothelial" in tl or "huvec" in tl or has_iec:
        vasc = "Endothelial_CoCulture_iEC_HUVEC"
    else:
        vasc = "None_Avascular_Islet"

    o2, _ = classify_oxygen_bridge_carrier_hardened(full_text)

    biomaterial = None
    for bm in ("PEG-4MAL microgel", "alginate", "TheraCyte", "PEC-Direct", "PEC-Encap", "PTFE", "fibrin", "Matrigel", "collagen"):
        if bm.lower() in tl:
            biomaterial = bm
            break

    return {
        "transplant_site": site,
        "prevascularization_lead_time_days": None,
        "in_dish_vascular_assembly": vasc,
        "oxygen_bridge_72h_carrier": o2,
        "packing_density_ieq_per_cm2_or_ml": None,
        "number_of_distributed_micro_pockets": None,
        "staged_insertion_schedule": None,
        "encapsulation_or_biomaterial": biomaterial,
        "co_transplanted_cells_or_oxygen_source": None,
        "systemic_immunosuppression_regimen": "None" if "without immunosuppression" in tl or "nsg" in tl else None,
    }


def _is_downstream_readout_only(win: str, sym: str, req_re: re.Pattern[str], matched_alias: str | None = None) -> bool:
    """
    Returns True if the perturbation keyword in `win` is attached to an upstream subject
    while `sym` appears only as a downstream readout object (e.g. 'The knockout cells reduced B2M and INS expression').
    """
    # Bind to the actual source spelling. Re-searching only CD274 silently missed
    # PDL1 / PD-L1 aliases and converted IRF1 readouts into CD274 interventions.
    alias = matched_alias or sym
    m_sym = re.search(rf"(?<!\w){re.escape(alias)}(?!\w)", win, flags=re.IGNORECASE)
    if not m_sym:
        return False
    # Check if there is a direct perturbation bound tightly to sym (e.g. 'B2M KO', 'KO of B2M', 'B2M-/-', 'CRISPR B2M')
    direct_pat = re.compile(
        rf"(?:\b{re.escape(alias)}(?:\s*|-)(?:-/-|−/−|\bKO\b|\bknockout\b|\bknock-out\b|\bknockdown\b|\bdeletion\b|\bnull\b|\bdeficien\w+|\boverexpress\w+|\bmutation\b|\bmutant\b|\binhibition\b|\bsilenc\w+))|"
        rf"(?:\b(?:knockout|knock-out|KO|knockdown|deletion|ablation|silencing|overexpression|inhibition|loss|deficiency|mutation)\s+(?:of\s+)?(?:human\s+|mouse\s+|endogenous\s+)?(?:[A-Za-z0-9_-]+\s+and\s+)?\b{re.escape(alias)}\b)",
        flags=re.IGNORECASE,
    )
    if direct_pat.search(win):
        return False
    # If all perturbation matches precede a causal/readout verb and sym follows that verb (or precedes 'expression/transcripts/mRNA/levels')
    after_sym = win[m_sym.end() :]
    before_sym = win[: m_sym.start()]
    if re.match(
        r"^\s*(?:,\s*[A-Za-z0-9_-]+\s*,?\s*)?(?:and\s+[A-Za-z0-9_-]+\s+)?(?:mRNA\s+|protein\s+|gene\s+|surface\s+)?(?:expression|transcript\w*|levels?|secretion|staining|markers?|content|induction|(?:was|were)\s+(?:significantly\s+)?(?:reduc\w+|decreas\w+|increas\w+|alter\w+|chang\w+|suppress\w+|downregulat\w+|upregulat\w+))\b",
        after_sym,
        flags=re.IGNORECASE,
    ):
        if re.search(
            r"\b(?:reduc\w+|decreas\w+|increas\w+|downregulat\w+|upregulat\w+|induc\w+|suppress\w+|alter\w+|chang\w+|elevat\w+|lower\w+|showed|exhibited|assessed|measured|knockout|KO\b|-/-|−/−)\b",
            before_sym,
            flags=re.IGNORECASE,
        ):
            return True
    if req_re.search(before_sym) and not req_re.search(after_sym):
        if re.search(
            r"\b(?:knockout|knock-out|KO\b|-/-|−/−|knockdown|deletion|ablation|silencing|overexpression|deficien\w+|loss|mutation|mutant)\b[^.;]*?\b(?:reduc\w+|decreas\w+|increas\w+|downregulat\w+|upregulat\w+|induc\w+|suppress\w+|alter\w+|chang\w+|elevat\w+|lower\w+|impair\w+|abolish\w+)\b",
            before_sym,
            flags=re.IGNORECASE,
        ):
            return True
    # Target suggestions/background mentions are not experimental manipulations.
    if re.search(r"\b(?:potential|promising|candidate)\s+(?:therapeutic\s+)?target\b|target\s+for\s+(?:immuno)?therapy", win, re.I):
        return True
    return False


def detect_genetic_edits(title: str, abstract: str = "", full_text: str = "") -> list[dict[str, Any]]:
    """
    Strictly discriminates active genetic/pharmacological perturbations of a target gene
    from passive immunostaining/marker mentions!
    A gene is included ONLY if:
      (a) It appears in the study Title or Abstract alongside a perturbation/functional keyword, OR
      (b) Within a +/- 140 character window around the gene match in full_text, there is an explicit
          perturbation keyword (KO, CRISPR, shRNA, mutation, overexpression, inhibitor, etc.)
          and NOT solely a passive immunostaining marker phrase.
    """
    edits = []
    seen = set()
    title_abs = f"{title} . {abstract}" if abstract else title
    effective_full_text = full_text or title_abs

    for spec in TARGET_GENE_SPECS:
        sym = spec["symbol"]
        if sym in seen:
            continue

        pat = re.compile(spec["pattern"], flags=re.IGNORECASE)
        is_perturbed = False
        matched_context = ""

        # Check title + abstract first (sentence-bounded window; title matches must also satisfy req_re)
        req_re = STRICT_GENETIC_EDIT_RE if sym in ENDOGENOUS_LINEAGE_MARKERS else PERTURBATION_CONTEXT_RE
        passive_readout_re = re.compile(
            rf"\b{re.escape(sym)}\b\s+(?:mrna\s+|protein\s+|gene\s+)?(?:expression|secretion|levels?|transcripts?)\s+(?:and\s+secretion\s+)?(?:was|were)\s+(?:assessed|measured|quantified|analyzed|determined|increased|decreased)",
            flags=re.IGNORECASE,
        )
        for m in pat.finditer(title_abs):
            start = max(0, m.start() - 95)
            end = min(len(title_abs), m.end() + 95)
            left_sep = max(title_abs.rfind(". ", start, m.start()), title_abs.rfind("; ", start, m.start()))
            if left_sep != -1:
                start = left_sep + 2
            right_dot = title_abs.find(". ", m.end(), end)
            right_semi = title_abs.find("; ", m.end(), end)
            right_cands = [idx for idx in (right_dot, right_semi) if idx != -1]
            if right_cands:
                end = min(right_cands) + 1
            win = title_abs[start:end]
            win_clean = re.sub(
                r"\b(?:membrane\s+attack\s+complex-inhibitory\s+protein|complement\s+inhibitory\s+receptors?)\b",
                " ",
                win,
                flags=re.IGNORECASE,
            )
            if (
                req_re.search(win_clean)
                and not PASSIVE_MARKER_ONLY_RE.search(win)
                and not passive_readout_re.search(win)
                and not _is_downstream_readout_only(win, sym, req_re, m.group(0))
            ):
                is_perturbed = True
                matched_context = win.strip()
                break

        # If not in title/abstract, check full_text windows with strict sentence-bounded perturbation requirement
        if not is_perturbed:
            for m in pat.finditer(effective_full_text):
                start = max(0, m.start() - 90)
                end = min(len(effective_full_text), m.end() + 90)
                left_sep = max(effective_full_text.rfind(". ", start, m.start()), effective_full_text.rfind("; ", start, m.start()))
                if left_sep != -1:
                    start = left_sep + 2
                right_dot = effective_full_text.find(". ", m.end(), end)
                right_semi = effective_full_text.find("; ", m.end(), end)
                right_cands = [idx for idx in (right_dot, right_semi) if idx != -1]
                if right_cands:
                    end = min(right_cands) + 1
                win = effective_full_text[start:end]
                win_clean = re.sub(
                    r"\b(?:membrane\s+attack\s+complex-inhibitory\s+protein|complement\s+inhibitory\s+receptors?)\b",
                    " ",
                    win,
                    flags=re.IGNORECASE,
                )
                if (
                    req_re.search(win_clean)
                    and not PASSIVE_MARKER_ONLY_RE.search(win)
                    and not passive_readout_re.search(win)
                    and not _is_downstream_readout_only(win, sym, req_re, m.group(0))
                ):
                    is_perturbed = True
                    matched_context = win.strip()
                    break

        if is_perturbed:
            seen.add(sym)
            # Infer modality from context window if possible
            wl = matched_context.lower()
            modality = spec["default_modality"]
            if any(k in wl for k in ("shrna", "sirna", "knockdown", "crispri")):
                modality = "CRISPRi_or_shRNA_Knockdown"
            elif re.search(r"\b(?:base[ -]edit\w*|abe8e|adenine\s+base\s+editor|cytosine\s+base\s+editor)\b", wl):
                modality = "BaseEdit_ABE_or_CBE_Epitope_or_Splice"
            elif re.search(r"\bprime[ -]edit\w*\b", wl):
                modality = "PrimeEdit"