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…

    m_pair = re.search(
        r"(from\s+)?(\d+\.?\d*)\s*(%|fold|mg/dL|ng/mL|days|weeks|months|µm|um)\s*"
        r"(vs\.?|versus|compared\s+to|compared\s+with|to)\s*"
        r"(\d+\.?\d*)\s*(%|fold|mg/dL|ng/mL|days|weeks|months|µm|um)?",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_pair:
        has_from = bool(m_pair.group(1))
        v1, u1, sep, v2 = _source_numeric_operand(m_pair.group(2)), m_pair.group(3), m_pair.group(4).lower(), _source_numeric_operand(m_pair.group(5))
        if sep == "to" and not has_from:
            return None, None, None, None, u1, None
        t_mean, c_mean = (v2, v1) if has_from else (v1, v2)
        if has_h and has_p:
            return None, None, None, None, "quarantined_mixed_polarity_endpoints", None
        if t_mean > 0 and c_mean > 0 and orient_sign != 0.0 and not is_protocol:
            lrr = round(_log_response_ratio(t_mean, c_mean), 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 t_mean, None, c_mean, None, u1, lrr
        return None, None, None, None, u1, None
    if direction == "Neutral_or_NonInferior" or any(
        k in sl
        for k in (
            "unchanged",
            "no significant difference",
            "not significantly different",
            "was not prolonged",
            "did not increase",
            "did not decrease",
            "did not affect",
        )
    ):
        return None, None, None, None, "qualitative_statement", None
    m_fold = re.search(r"(?<!log)[>~]?\s*(\d+\.?\d*)\s*(?:-|\s)?fold\b", sentence, flags=re.IGNORECASE)
    if m_fold:
        fc = _source_numeric_operand(m_fold.group(1))
        if 0.05 <= fc <= 1000.0 and fc != 1.0:
            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:
                is_red = any(
                    k in sl
                    for k in ("decreas", "reduc", "lower", "downregulat", "inhibit", "suppress", "loss", "diminish", "attenuat")
                )
                lrr = round(math.log(fc), 4) if fc < 1.0 else (round(-abs(math.log(fc)), 4) if is_red else 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
    m_single_sd = re.search(
        r"(\d+\.?\d*)\s*(?:±|\+/-|\+-)\s*(\d+\.?\d*)\s*(%|mg/dL|ng/mL|pmol|days|weeks|mmHg|µm|um)",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_single_sd:
        return _source_numeric_operand(m_single_sd.group(1)), _source_numeric_operand(m_single_sd.group(2)), None, None, m_single_sd.group(3), None
    return None, None, None, None, "qualitative_statement", None


def _parse_quantitative_numbers_unchecked(
    sentence: str, direction: str
) -> tuple[float | None, float | None, float | None, float | None, str | None, float | None]:
    """
    Extracts (treatment_mean, treatment_sd, control_mean, control_sd, measurement_unit, log_response_ratio_or_smd)
    from a quantitative sentence in Results, Figure Legends, or Abstract.
    Strict Zero-Fabrication, Contrast-Provenance & Polarity-Quarantine Rule (v0.6.4):
      - Never invents a comparator or baseline value when only a single number is reported.
      - Never assigns a synthetic numeric LRR to qualitative, single-arm, longitudinal within-arm ('from X to Y'),
        or within-assay secretagogue/cytokine challenge statements.
      - Parses mean +/- SD/SEM fold-changes ('4.14 ± 1.4-fold') before bare fold-changes so the dispersion term
        after '±' is never misread as the point estimate.
      - Quarantines sentences with multiple fold-change clauses, fold ranges, or mixed increase+decrease polarity.
      - Requires a single unambiguous endpoint polarity class (has_lex_h != has_lex_p) for numeric LRR.
    """
    sl = sentence.lower()
    # An approximate estimate or an inequality is not an exact ratio. Retain
    # its source sentence, but leave the quantitative contrast unmeasured.
    qualified_fold = (
        r"(?:[<>≤≥~≈]|\b(?:at\s+least|at\s+most|more\s+than|less\s+than|"
        r"greater\s+than|fewer\s+than|up\s+to|nearly|almost|over|under|approximately|approx\.?|about|around|roughly)\s+)"
        r"\s*(?:an?\s+)?\d+(?:\.\d+)?(?:\s*(?:±|\+/-)\s*\d+(?:\.\d+)?)?\s*-?fold\b"
    )
    if re.search(qualified_fold, sl):
        return None, None, None, None, "quarantined_approximate_or_bounded_fold_change", None
    has_h = any(k in sl for k in LEX_H)
    has_p = any(k in sl for k in LEX_P)
    orient_sign = -1.0 if (has_h and not has_p) else (1.0 if (has_p and not has_h) else 0.0)
    is_protocol = any(
        k in sl
        for k in (
            "stimulated with",
            "incubated with",
            "cultured with",
            "treated with",
            "supplemented with",
            "concentration",
            "physiological",
            "monitored",
            "quantified",
            "ranging from",
            "between ",
            "heatmap",
            "depicting",
            "log2 fold",
            "not functional",
            "triglyceride",
        )
    )

    # Full unit token pattern that captures composite/rate units (e.g. ng/mL/min, pg/mL, hours, PD-L1+ cells/mm2)
    unit_tok = r"(?:PD-L1\+\s+cells/mm2|%|(?:-|\s)?fold\b|[a-zA-Zµμ]+(?:/[a-zA-Z0-9µμ²³+-]+)+|\b(?:days|weeks|months|hours|years|min|sec|h|s|pmol|mmol|nmol|µmol|umol|mg|ng|pg|µg|ug|mM|nM|µM|uM|pM|mmHg|µm|um|mm|cm|mL|L|dL|cells|islets|mice|patients)\b)"
    supported_pair_units = {
        "%", "fold", "mg/dl", "ng/ml", "ng/ml/min", "pg/ml", "uiu/ml", "µiu/ml", "pmol", "pmol/l",
        "mmol/l", "mm", "nm", "um", "µm", "mmhg", "days", "weeks", "months", "hours", "h",
        "cells/mm2", "pd-l1+ cells/mm2",
    }
    longitudinal_timepoint_re = re.compile(
        r"\b(baseline|follow-up|follow\s+up|pre-transplant\w*|post-transplant\w*|before\s+and\s+after|prior\s+to\s+and\s+after|day\s+\d+|week\s+\d+|month\s+\d+)\b",
        flags=re.IGNORECASE,
    )

    # Pattern 1: Explicit paired mean +/- SD/SEM comparison
    # (e.g., "68.4 ± 4.2% vs. 14.1 ± 2.1%" or "from 12.5 ± 1.2% to 48.0 ± 3.5%")
    num_tok = r"\d+(?:,\d{3})*(?:\.\d+)?"
    m_pair_sd = re.search(
        rf"(from\s+)?({num_tok})\s*(?:±|\+/-|\+-)\s*(?:{_NUMERIC_QUALIFIER})?({num_tok})\s*({unit_tok})?\s*"
        rf"(vs\.?|versus|compared\s+to|compared\s+with|to)\s*"
        rf"(?:{_NUMERIC_QUALIFIER})?({num_tok})\s*(?:±|\+/-|\+-)\s*(?:{_NUMERIC_QUALIFIER})?({num_tok})\s*({unit_tok})?",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_pair_sd:
        has_from = bool(m_pair_sd.group(1))
        v1 = _source_numeric_match(m_pair_sd, 2, exact=True)
        sd1 = _source_numeric_match(m_pair_sd, 3, exact=True)
        u1 = (m_pair_sd.group(4) or "").strip() or None
        sep = m_pair_sd.group(5).lower()
        v2 = _source_numeric_match(m_pair_sd, 6, exact=True)
        sd2 = _source_numeric_match(m_pair_sd, 7, exact=True)
        u2 = (m_pair_sd.group(8) or "").strip() or None
        if u1 and u2 and u1.lower() != u2.lower():
            return None, None, None, None, "quarantined_mismatched_units", None
        unit = u1 or u2 or "reported_units"
        if unit != "reported_units" and unit.lower().lstrip("- ") not in supported_pair_units:
            return None, None, None, None, "quarantined_unsupported_unit", None
        if sep == "to" and not has_from:
            return None, None, None, None, unit, None
        if has_from:
            t_mean, t_sd, c_mean, c_sd = v2, sd2, v1, sd1
            if "respectively" not in sl or longitudinal_timepoint_re.search(sentence) or unit.lower().lstrip("- ") in ("pd-l1+ cells/mm2", "cells/mm2"):
                return t_mean, t_sd, c_mean, c_sd, unit, None
        else:
            t_mean, t_sd, c_mean, c_sd = v1, sd1, v2, sd2
            if unit.lower().lstrip("- ") in ("pd-l1+ cells/mm2", "cells/mm2"):
                return t_mean, t_sd, c_mean, c_sd, unit, None
        if has_h and has_p:
            return None, None, None, None, "quarantined_mixed_polarity_endpoints", None
        if t_mean > 0 and c_mean > 0 and orient_sign != 0.0 and not is_protocol:
            lrr = round(_log_response_ratio(t_mean, c_mean), 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 t_mean, t_sd, c_mean, c_sd, unit, lrr
        return None, None, None, None, unit, None

    # Pattern 2: Explicit paired values with explicit comparison token (vs, versus, compared to/with, or from X to Y)
    m_pair = re.search(
        rf"(from\s+)?({num_tok})\s*({unit_tok})\s*"
        rf"(vs\.?|versus|compared\s+to|compared\s+with|to)\s*"
        rf"(?:{_NUMERIC_QUALIFIER})?({num_tok})(?:\s*({unit_tok}))?",
        sentence,
        flags=re.IGNORECASE,
    )
    if m_pair:
        has_from = bool(m_pair.group(1))
        v1 = _source_numeric_match(m_pair, 2, exact=True)
        u1 = m_pair.group(3).strip()
        sep = m_pair.group(4).lower()
        v2 = _source_numeric_match(m_pair, 5, exact=True)
        u2 = (m_pair.group(6) or "").strip() or None
        if not u2 or u1.lower() != u2.lower():
            return None, None, None, None, "quarantined_mismatched_units", None
        if u1.lower().lstrip("- ") not in supported_pair_units:
            return None, None, None, None, "quarantined_unsupported_unit", None
        if sep == "to" and not has_from:
            return None, None, None, None, u1, None
        if has_from:
            t_mean, c_mean = v2, v1
            return t_mean, None, c_mean, None, u1, None
        else:
            t_mean, c_mean = v1, v2
        if has_h and has_p:
            return None, None, None, None, "quarantined_mixed_polarity_endpoints", None
        if t_mean > 0 and c_mean > 0 and orient_sign != 0.0 and not is_protocol:
            lrr = round(_log_response_ratio(t_mean, c_mean), 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 t_mean, None, c_mean, None, u1, lrr
        return None, None, None, None, u1, None

    if direction == "Neutral_or_NonInferior" or any(
        k in sl
        for k in (
            "unchanged",
            "no significant difference",
            "not significantly different",
            "was not prolonged",
            "did not increase",
            "did not decrease",
            "did not affect",
        )
    ):
        return None, None, None, None, "qualitative_statement", None

    has_multi_fold = (
        len(re.findall(r"\b(?:\d+\.?\d*|two|three|four|five|six|seven|eight|nine|ten)\s*(?:-|\s)?fold\b", sl)) > 1
        or bool(re.search(r"\b\d+\.?\d*\s*[-–]\s*\d+\.?\d*\s*[-–]?\s*(?:or\s+|and\s+|to\s+)?\d*\.?\d*\s*(?:-|\s)?fold\b", sl))
        or bool(re.search(r"\b\d+\.?\d*[-–]?\s*(?:to|and|or)\s*\d+\.?\d*\s*(?:-|\s)?fold\b", sl))
    )
    has_mixed_up_down = (
        any(k in sl for k in ("increas", "upregulat", "elevat", "higher", "enhanc", "induc"))
        and any(k in sl for k in ("decreas", "reduc", "lower", "downregulat", "inhibit", "suppress", "attenuat", "diminish"))
    )
    is_within_assay_stim = (
        any(
            k in sl
            for k in (
                "in response to glucose",
                "upon high glucose challenge",
                "exposed to high glucose",
                "upon 10 μm ionomycin",
                "upon 10 um ionomycin",
                "glibenclamide stimulation",
                "upon kcl",
                "depolarization",
                "exposure with these cytokines",
                "caspase-3/7 activation",
                "glucose-stimulated insulin secretion (gsis) was increased",
            )
        )
        and not any(k in sl for k in ("compared", "versus", "vs.", "wild-type", "unedited", "non-sorted"))
    ) or any(