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…

        k in sl
        for k in (
            "cell sorting yielded",
            "compared to non-sorted cells",
        )
    )

    # Pattern 3A: Explicit fold-change with ± SD/SEM (e.g., "4.14 ± 1.4-fold" in pmid41385368_eff4)
    m_fold_sd = re.search(
        r"(?<!log)[>~]?\s*(\d+\.?\d*)\s*(?:±|\+/-|\+-)\s*(\d+\.?\d*)\s*(?:-|\s)?fold\b",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_fold_sd:
        fc = _source_numeric_match(m_fold_sd, 1)
        fc_sd = _source_numeric_match(m_fold_sd, 2)
        if 0.05 <= fc <= 1000.0 and fc != 1.0:
            if has_multi_fold or has_mixed_up_down:
                return None, None, None, None, "quarantined_ambiguous_numeric", None
            if has_h and has_p:
                return None, None, None, None, "quarantined_mixed_polarity_endpoints", None
            if orient_sign != 0.0 and not is_protocol and not is_within_assay_stim:
                is_red = any(
                    k in sl
                    for k in ("decreas", "reduc", "lower", "downregulat", "inhibit", "suppress", "loss", "diminish", "attenuat")
                )
                if fc < 1.0:
                    lrr = round(math.log(fc), 4)
                elif is_red:
                    lrr = round(-abs(math.log(fc)), 4)
                else:
                    lrr = round(abs(math.log(fc)), 4)
                if (direction == "Protective_or_Improved" and lrr * orient_sign <= 0) or (
                    direction == "Deleterious_or_Impaired" and lrr * orient_sign >= 0
                ):
                    return None, None, None, None, "quarantined_ambiguous_numeric", None
                return fc, fc_sd, None, None, "fold_change_ratio", lrr
            return fc, fc_sd, None, None, "fold_change_ratio", None

    # Pattern 3B: Bare fold-change (e.g., "2.8-fold", "3.5 fold", ">2-fold") — excludes "± X-fold", "times", and "log2 fold"
    m_fold = re.search(
        r"(?<!log)(?<!±\s)(?<!±)(?<!\+/-\s)(?<!\+/-)(?<![\d.])[>~]?\s*(\d+\.?\d*)\s*(?:-|\s)?fold\b",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_fold:
        fc = _source_numeric_match(m_fold, 1)
        if 0.05 <= fc <= 1000.0 and fc != 1.0:
            if has_multi_fold or has_mixed_up_down:
                return None, None, None, None, "quarantined_ambiguous_numeric", None
            if has_h and has_p:
                return None, None, None, None, "quarantined_mixed_polarity_endpoints", None
            if orient_sign != 0.0 and not is_protocol and not is_within_assay_stim:
                is_red = any(
                    k in sl
                    for k in ("decreas", "reduc", "lower", "downregulat", "inhibit", "suppress", "loss", "diminish", "attenuat")
                )
                if fc < 1.0:
                    lrr = round(math.log(fc), 4)
                elif is_red:
                    lrr = round(-abs(math.log(fc)), 4)
                else:
                    lrr = round(abs(math.log(fc)), 4)
                if (direction == "Protective_or_Improved" and lrr * orient_sign <= 0) or (
                    direction == "Deleterious_or_Impaired" and lrr * orient_sign >= 0
                ):
                    return None, None, None, None, "quarantined_ambiguous_numeric", None
                return fc, None, None, None, "fold_change_ratio", lrr
            return fc, None, None, None, "fold_change_ratio", None

    # Pattern 4: Single mean +/- SD/SEM without comparator -> record treatment_mean & SD only; control_mean=None, lrr=None
    m_single_sd = re.search(
        rf"({num_tok})\s*(?:±|\+/-|\+-)\s*({num_tok})\s*(%|mg/dL|ng/mL|pmol|days|weeks|mmHg|µm|um|μL|µL|uL)",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_single_sd:
        v1 = _source_numeric_match(m_single_sd, 1)
        sd1 = _source_numeric_match(m_single_sd, 2)
        unit = m_single_sd.group(3)
        return v1, sd1, None, None, unit, None

    # Pattern 5: Single percentage without comparator -> record treatment_mean only; control_mean=None, lrr=None
    m_pct = re.search(r"(?<![\d,])(\d+\.?\d*)\s*%", sentence)
    if m_pct:
        pct = _source_numeric_match(m_pct, 1)
        if 0.0 <= pct <= 100.0:
            return pct, None, None, None, "%", None

    # Pattern 6: Single duration without comparator -> record reported duration only; control_mean=None, lrr=None
    m_dur = re.search(
        r"(?:for|over|up\s+to|more\s+than|after|within|at|>|~)\s+(\d+\.?\d*)\s*(days|day|weeks|week|months|month|hours|hr|hrs|\bh\b)",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_dur:
        val = _source_numeric_match(m_dur, 1)
        unit = m_dur.group(2).lower()
        return round(val, 2), None, None, None, unit, None

    # Pattern 7: Single physiological measurement without comparator -> record value & unit only; control_mean=None, lrr=None
    m_unit = re.search(
        rf"({num_tok})\s*(mg/dL|ng/mL|ng\s*ml(?:-1|⁻¹)|pg/mL|mM|µM|uM|nM|pmol|fmol|mmHg|µm|um|cells/mL|SI\b)",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_unit:
        val = _source_numeric_match(m_unit, 1)
        unit = m_unit.group(2)
        if re.fullmatch(r"ng\s*ml(?:-1|⁻¹)", unit, flags=re.IGNORECASE):
            unit = "ng/mL"
        return val, None, None, None, unit, None

    # Qualitative statement without explicit paired numbers -> keep all numeric fields None
    return None, None, None, None, "qualitative_statement", None


def parse_quantitative_numbers(
    sentence: str, direction: str
) -> tuple[float | None, float | None, float | None, float | None, str | None, float | None]:
    try:
        result = _parse_quantitative_numbers_unchecked(sentence, direction)
        for index in (0, 1, 2, 3, 5):
            if result[index] is not None:
                _finite_numeric_evidence(result[index], "Parsed numeric evidence")
        return result
    except _NumericEvidenceNotationError:
        return None, None, None, None, "quarantined_unsupported_numeric_notation", None
    except _NumericEvidenceBoundedError:
        return None, None, None, None, "quarantined_approximate_or_bounded_measurement", None
    except _NumericEvidenceDomainError:
        return None, None, None, None, "quarantined_nonfinite_numeric", None


STAT_VOCAB = set(
    """p n mean means sd sem se anova test tests t tukey bonferroni dunnett student students two tailed one way paired unpaired non
nonparametric mann whitney wilcoxon kruskal wallis fisher exact post hoc results result represent represents represented data are is were was be been presented
shown show shows as independent experiments experiment replicates replicate biological technical donors donor error bars bar standard deviation versus vs compared
comparison relative control controls untreated media alone ns significant significantly different difference differences values value from of the and or with to
in at for by a an each per group groups condition conditions same respective corrected correction multiple comparisons using calculated determined analysis
variance followed least statistical statistics three four five six seven eight nine ten twice out representative figure fig panel panels see supplementary
unless otherwise indicated denotes denote indicate indicated asterisks asterisk stars star level levels analyzed analysed performed carried cells cell treated
treatment wild type wt""".split()
)

HARM_SENT_RE = re.compile(
    r"\b(destr\w+|damag\w+|reject\w*|killed|killing|death|died|fail\w*|nonfunction\w+|necro\w+|dysfunction\w*|impair\w+|toxic\w*|lost|loss)\b",
    flags=re.IGNORECASE,
)
BEN_SENT_RE = re.compile(
    r"\b(improv\w+|protect\w+|surviv\w+|prolong\w+|restor\w+|normoglyc\w+|reversal|reversed|enhanc\w+)\b",
    flags=re.IGNORECASE,
)


def _is_opening_study_aim_sentence(q: str) -> bool:
    """Reject opening study-aim / pure-methods sentences with no reported empirical result (ASTRA-06)."""
    ql = (q or "").lower().strip()
    if re.search(
        r"\b(?:the\s+aims?\s+of\s+(?:this|the)\s+study|this\s+study\s+aimed\s+to|our\s+objective\s+was\s+to|the\s+goal\s+of\s+this\s+study)\b",
        ql,
    ):
        return True
    if re.match(r"^to\s+investigate\s+whether\b", ql) and not re.search(
        r"\b(?:we\s+(?:found|showed|demonstrated|observed|identified)|significant(?:ly)?|increased|decreased|reduced|inhibited|improved|protected|restored|prevented|elevated|suppressed)\b|p\s*[<=>]",
        ql,
    ):
        return True
    return False


def is_stat_boilerplate(q: str) -> bool:
    ql = q.lower().strip()
    if re.search(
        r"\b(?:the\s+aims?\s+of\s+(?:this|the)\s+study|this\s+study\s+aimed\s+to|our\s+objective\s+was\s+to|the\s+goal\s+of\s+this\s+study|in\s+a\s+similar\s+system\s+was\s+recently\s+shown\s+to)\b",
        ql,
    ):
        return True
    cw = [
        w
        for w in re.findall(r"[A-Za-z][A-Za-z\-']+", ql)
        if w not in STAT_VOCAB and len(w) > 2
    ]
    return (
        bool(re.search(r"(p\s*[<=>]|n\s*=|±|mean|anova|t-test|t test|sem|sd\b)", q, re.I))
        and len(cw) <= 3
    )


def strict_gene_match(sym: str, text: str) -> bool:
    s = sym.upper()
    t = text.upper()
    if s == "CAR":
        return bool(re.search(r"(?<![A-Z0-9])CAR(?![A-Z0-9])", t)) and "COXSACKIE" in t
    if s == "INS":
        return bool(re.search(r"(?<![A-Z0-9])INS(?![A-Z0-9])(?!-1)", t))
    if s.startswith("HLA-"):
        return bool(re.search(r"(?<![A-Z0-9])" + re.escape(s) + r"(?:W(?=[\d*])|(?![A-Z]))", t))
    return bool(re.search(r"(?<![A-Z0-9])" + re.escape(s) + r"(?![A-Z0-9])", t))


def _target_bound_atomic_clauses(sentence: str, study_edits: list[dict[str, Any]]) -> list[str]:
    """Split distinct target clauses before focal attribution, preserving source substrings.

    When clauses cannot be unambiguously separated, retain the sentence; its
    target-specific classifier still runs after focal selection. No text is joined.
    """
    genes = {e["gene_symbol_hgnc"] for e in study_edits if strict_gene_match(e["gene_symbol_hgnc"], sentence)}
    if len(genes) < 2:
        return [sentence]
    clauses = [x.strip() for x in re.split(
        r",\s*(?=(?:loss|deletion|knockout|downregulation|silencing|overexpression)\s+of\b)|"
        r"[,;]\s*(?:whereas|while|but|however)\s+", sentence, flags=re.I
    ) if x.strip()]
    clause_genes = [{g for g in genes if strict_gene_match(g, c)} for c in clauses]
    if len(clauses) > 1 and all(len(g) == 1 for g in clause_genes) and len(set.union(*clause_genes)) == len(genes):
        return clauses
    # A compound multi-target contrast that cannot be bound is not an atomic
    # single-target observation. Quarantine it rather than credit the first gene.
    if re.search(r"\b(?:while|whereas)\b|[,;]\s*(?:but|however)\b", sentence, re.I):
        return []
    return [sentence]


def identify_focal_factor(sentence: str, study_edits: list[dict[str, Any]], title: str) -> str:
    """Identifies the specific perturbation/intervention X acting in the sentence using strict word-boundary matching."""
    for ed in study_edits:
        gsym = ed["gene_symbol_hgnc"]
        if strict_gene_match(gsym, sentence):
            return f"{gsym} ({ed['edit_modality']} — {ed['functional_gate']})"

    if "HNF1A WT β-cells" in sentence and "HNF1A KO β-cells" in sentence and "HNF1A" in title:
        return "HNF1A KO (HNF1A−/−) SC-β cells vs isogenic HNF1A WT SC-β cells"

    first_half = sentence[: max(80, len(sentence) // 2)]
    node_id, _ = resolve_canonical_node(first_half)
    if node_id and "_" in node_id and not any(strict_gene_match(ed["gene_symbol_hgnc"], node_id) for ed in study_edits if not strict_gene_match(ed["gene_symbol_hgnc"], sentence)):
        if not strict_gene_match("INS", node_id) or strict_gene_match("INS", sentence):
            return node_id

    if len(study_edits) == 1 and not re.search(r"\b(?:UTP23|RAD21|MED30|USP18|MEG3)\b", sentence):
        ed0 = study_edits[0]
        g0 = ed0["gene_symbol_hgnc"]
        if g0 != "INS" or strict_gene_match("INS", sentence):
            return f"{g0} ({ed0['edit_modality']} — {ed0['functional_gate']})"

    t_node, _ = resolve_canonical_node(title)
    if t_node and (not strict_gene_match("INS", t_node) or strict_gene_match("INS", sentence)):
        if not any(strict_gene_match(ed["gene_symbol_hgnc"], t_node) for ed in study_edits if not strict_gene_match(ed["gene_symbol_hgnc"], sentence)):
            return t_node