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…

        r"\b(?:compared\s+(?:to|with)|versus|vs\.?|relative\s+to|than\s+(?:in|that\s+of|those\s+of)?)\s+([A-Za-z][^.;,]{3,85})",
        r"\b(?:vs\.?|versus|compared\s+(?:to|with))\s+\d+[^A-Za-z]{0,25}(?:in|for|of)\s+([A-Za-z][^.;,]{3,80})",
        r"\bwhile\s+([^.;,]{6,80})\s+(?:showed|remained|were|had|exhibited)",
        r"\bfor\s+([A-Za-z0-9_\-]+)\s+and\s+[A-Za-z0-9_\-\s\+]+,\s*respectively",
    ):
        m = re.search(pat, sent, flags=re.IGNORECASE)
        if m:
            cand = m.group(1).strip()
            if not re.match(r"^(?:\d|p\s*[<=>]|fig|table|supplementary)", cand, flags=re.IGNORECASE):
                comp_desc = cand
                break
    if not comp_desc:
        m_ko = re.search(r"\b([A-Za-z0-9]+)(?:−/−|-/-|\s+KO|\s+knockout)\s+SC-islets\b", sent)
        if m_ko:
            comp_desc = f"isogenic wild-type {m_ko.group(1)}+/+ SC-islet genotype control"
        else:
            return "", ""
    author_tag = f"{first_author} ({pub_year})" if first_author else f"({pub_year})"
    comp_x0_desc = comp_desc
    m_wt_ratio = re.search(r"showed\s+an?\s+(insulin:C-peptide\s+molar\s+ratio\s+of\s+0\.22\s*±\s*0\.11)", sent, flags=re.IGNORECASE)
    if m_wt_ratio:
        comp_x0_desc = f"{comp_desc}, {m_wt_ratio.group(1).strip()}"
    comp_x0 = f"Between-arm comparator ({comp_x0_desc}) in {author_tag}"
    comp_arm_label = f"Reference comparator condition ({comp_desc}) in {author_tag}"
    return comp_x0[:200], comp_arm_label[:200]


def _populate_effect_provenance(
    eff: dict[str, Any], dossier: dict[str, Any], dossier_sha: str, transplant_site: str
) -> None:
    q = eff.get("verbatim_evidence_quote") or ""
    p_tokens = _pvalue_tokens(q)
    if len(p_tokens) == 1:
        relation, bound = p_tokens[0]
        eff["p_value_relation"] = relation
        eff["p_value_bound"] = float(bound)
        eff["p_value"] = float(bound) if relation == "=" else None
    else:
        eff["p_value"] = None
        eff["p_value_relation"] = None
        eff["p_value_bound"] = None
    eff["direction_adjudication_method"] = "rule_based_heuristic"
    sl = q.lower()
    src_label = eff.get("source_figure_or_table") or "Results"
    t_mean = eff.get("treatment_mean")
    t_sd = eff.get("treatment_sd_or_sem")
    c_mean = eff.get("control_mean")
    c_sd = eff.get("control_sd_or_sem")
    lrr = eff.get("log_response_ratio_or_smd")
    if lrr is not None and (not isinstance(t_mean, (int, float)) or ("fold" not in q.lower() and not isinstance(c_mean, (int, float)))):
        eff["log_response_ratio_or_smd"] = lrr = None
        eff["comparator_arm_id"] = None
        eff["measurement_unit"] = "quarantined_unbound_numeric_operand"
    if lrr is None:
        eff["control_mean"] = None
        eff["control_sd_or_sem"] = None
        c_mean = None
        c_sd = None
    n_val = eff.get("treatment_n")

    if t_sd is not None or c_sd is not None:
        if re.search(r"\bs\.?e\.?m\.?\b|standard\s+error", sl):
            eff["dispersion_type"] = "SEM"
        elif re.search(r"\bs\.?d\.?\b|standard\s+deviation", sl):
            eff["dispersion_type"] = "SD"
        else:
            eff["dispersion_type"] = "unspecified_in_quote"
    else:
        eff["dispersion_type"] = "Not_Reported_in_Source_Sentence"

    sl_context = (
        q
        + " "
        + str(eff.get("outcome_variable_Y") or "")
        + " "
        + str((eff.get("conditioning_context_Z") or {}).get("Z8_species_age_and_sex_context") or "")
    ).lower()
    eff["n_unit"] = _infer_n_unit_from_quote(sl_context, n_val)
    previous_censoring_note = str(eff.get("censoring_note") or "")
    eff["censoring_note"] = (
        "Right-censored at last reported follow-up timepoint if graft remained functional"
        if any(k in sl for k in ("day", "week", "month", "follow-up", "survival", "censor", "ongoing"))
        else "Not_Time_To_Event_Endpoint"
    )
    if previous_censoring_note.startswith("Right-censored"):
        eff["censoring_note"] = previous_censoring_note
    eff["endpoint_polarity_registry"] = _infer_endpoint_polarity_registry(
        (eff.get("outcome_variable_Y") or "") + " " + q
    )
    eff["dossier_sha256"] = dossier_sha
    raw_q = eff.get("verbatim_evidence_quote")
    eff["source_span"] = None if raw_q is None else _resolve_dossier_character_span(raw_q, dossier, src_label)
    pmid_str = str(dossier.get("pmid") or "")
    eff["quote_source_dossier_pmid"] = pmid_str if pmid_str else None
    if pmid_str in PEER_REVIEWED_TO_PREPRINT_MAP and isinstance(eff.get("source_span"), str) and eff["source_span"].startswith("fulltext_data_sections."):
        own_ft = dossier.get("fulltext_data_sections") or {}
        eff_ft = _get_effective_fulltext_sections(pmid_str, dossier)
        if eff_ft is not own_ft and eff_ft != own_ft:
            pre_pmid = PEER_REVIEWED_TO_PREPRINT_MAP[pmid_str]
            pre_dp = DOSSIER_DIR / f"{pre_pmid}.json"
            if pre_dp.exists():
                pre_dos = json.loads(pre_dp.read_text(encoding="utf-8"))
                eff["dossier_sha256"] = _compute_dossier_sha256(pre_pmid, pre_dos)
                eff["quote_source_dossier_pmid"] = pre_pmid
    if isinstance(lrr, (int, float)) and isinstance(t_mean, (int, float)) and isinstance(c_mean, (int, float)):
        eff["statistic_type"] = "log_response_ratio_paired_means"
    elif isinstance(lrr, (int, float)):
        eff["statistic_type"] = "log_response_ratio_fold_change"
    elif isinstance(t_mean, (int, float)):
        eff["statistic_type"] = "single_arm_descriptive_only"
    elif str(eff.get("measurement_unit") or "").startswith("quarantined_"):
        eff["statistic_type"] = "quarantined_ambiguous_numeric"
    else:
        eff["statistic_type"] = "qualitative_statement_only"

    m_tp_multi = re.search(
        r"(?<!Figure\s)(?<!Figures\s)(?<!Fig\.\s)(?<!Figs\.\s)\b(\d+\.?\d*\s*(?:or|and)\s*(?:\d+\.?\d*\s*(?:hr|hrs|hours|day|days|wk|weeks|week|mo|months|month|min|minutes)|\d+\.?\d*\s+[hH]|\d+\.?\d*h))\b",
        q,
        flags=re.IGNORECASE,
    )
    m_tp = m_tp_multi or re.search(
        r"(?<!Figure\s)(?<!Figures\s)(?<!Fig\.\s)(?<!Figs\.\s)\b(\d+\.?\d*\s*(?:hr|hrs|hours|day|days|wk|weeks|week|mo|months|month|min|minutes)|\d+\.?\d*\s+[hH]|\d+\.?\d*h)\b",
        q,
    )
    previous_contrast = eff.get("contrast_metadata") or {}
    timepoint_str = m_tp.group(1) if m_tp else previous_contrast.get("timepoint")
    cond_z = eff.get("conditioning_context_Z") or {}
    if eff["statistic_type"] == "log_response_ratio_paired_means":
        ctype = "between_arm_comparative_paired_means"
    elif eff["statistic_type"] in ("log_response_ratio_fold_change", "standardized_mean_difference"):
        ctype = "between_arm_comparative_fold_ratio"
    elif isinstance(t_mean, (int, float)) and isinstance(c_mean, (int, float)):
        ctype = "longitudinal_or_within_arm_descriptive"
    elif eff["statistic_type"] == "quarantined_ambiguous_numeric":
        ctype = "quarantined_ambiguous_multi_clause_or_multi_ratio"
    elif isinstance(t_mean, (int, float)):
        if eff["censoring_note"].startswith("Right-censored"):
            ctype = "right_censored_followup_observation"
        else:
            ctype = "single_arm_descriptive_only"
    elif previous_contrast.get("contrast_type") == "right_censored_followup_observation" and timepoint_str:
        ctype = "right_censored_followup_observation"
    else:
        ctype = "qualitative_statement_only"

    eff["contrast_metadata"] = {
        "intervention_label": str(eff.get("focal_factor_X") or "Study_Intervention")[:160],
        "comparator_label": str(eff.get("comparator_X0") or "No_Between_Arm_Comparator")[:160] if isinstance(lrr, (int, float)) else None,
        "endpoint_name": str(eff.get("outcome_domain") or "Outcome")[:120],
        "timepoint": timepoint_str,
        "population_or_model": f"{cond_z.get('Z2_genetic_background_and_allelic_dose', 'Unknown')} ({cond_z.get('Z8_species_age_and_sex_context', 'Unknown')})",
        "units": str(eff.get("measurement_unit") or "qualitative_statement"),
        "contrast_type": ctype,
    }


def _num_in_quote(val: Any, quote: str, field_name: str = "") -> bool:
    if val is None or isinstance(val, bool):
        return val is None
    q_clean = re.sub(r"(\d)\u00b7(\d)", r"\1.\2", (quote or "")).replace(",", "").replace("\u2212", "-")
    if field_name == "p_value":
        try:
            number = Decimal(str(val))
        except (InvalidOperation, TypeError, ValueError):
            return False
        return any(op == "=" and number == parsed for op, parsed in _pvalue_tokens(quote))
    if field_name in ("sample_size_n", "treatment_n", "control_n"):
        # A number in a reagent catalogue, dose or timepoint is not a sample size.
        ns = [int(m.group(1).replace(",", "")) for m in re.finditer(
            r"\bn\s*=\s*(\d+(?:,\d{3})*)(?![\d.]|\s*[-–−]\s*\d)|"
            r"\b(?:sample\s+size|total\s+of)\s+(?:n\s*=\s*)?(\d+(?:,\d{3})*)\s*(?=patients?\b|mice\b|donors?\b|replicates?\b|cells?\b)",
            quote, re.I
        ) if m.group(1)]
        ns += [int(m.group(2).replace(",", "")) for m in re.finditer(
            r"\b(sample\s+size|total\s+of)\s+(\d+(?:,\d{3})*)\s*(?:patients?|mice|donors?|replicates?|cells?)\b", quote, re.I)]
        # Written counts with an explicit recipient/sample role are also source
        # operands (e.g. Hu: "one allogeneic rhesus macaque each"), unlike doses.
        written_numbers = {"one": 1, "two": 2, "three": 3, "four": 4, "five": 5,
                           "six": 6, "seven": 7, "eight": 8, "nine": 9, "ten": 10}
        for match in re.finditer(
            r"\b(one|two|three|four|five|six|seven|eight|nine|ten)\s+"
            r"(?:allogeneic\s+)?(?:rhesus\s+)?(?:macaques?|monkeys?|animals?|recipients?|donors?|patients?)\s+"
            r"(?:each\b|per\s+(?:arm|group)\b|in\s+each\s+(?:arm|group)\b)", quote, re.I):
            ns.append(written_numbers[match.group(1).lower()])
        if field_name == "sample_size_n":
            for match in re.finditer(
                r"\b(one|two|three|four|five|six|seven|eight|nine|ten)\s+"
                r"(?:male\s+|female\s+)?(?:cynomolgus\s+|rhesus\s+)?(?:macaques?|monkeys?)\b", quote, re.I):
                ns.append(written_numbers[match.group(1).lower()])
            for match in re.finditer(
                r"\bseries\s+of\s+(\d+(?:,\d{3})*)\s+pancreas\s+transplants?\b|"
                r"\binvolving\s+(\d+(?:,\d{3})*)\s+hiPSCs?\b|"
                r"\b(?:across|from)\s+(?:all\s+)?(\d+(?:,\d{3})*)\s+(?:different\s+|tested\s+)?donors?\b",
                quote, re.I):
                tok = match.group(1) or match.group(2) or match.group(3)
                if tok:
                    ns.append(int(tok.replace(",", "")))
        if isinstance(val, (int, float)) and not isinstance(val, bool) and float(val).is_integer() and int(val) in ns:
            return True
        return (field_name in ("treatment_n", "control_n") and isinstance(val, (int, float))
                and "observation periods" in quote.lower() and len(re.findall(r">\d+", quote)) == int(val))

    if field_name in ("treatment_mean", "treatment_sd_or_sem", "control_mean", "control_sd_or_sem"):
        direction = classify_sentence_direction_and_penalty(quote)[0]
        operands = parse_quantitative_numbers(quote, direction)
        if operands[0] is None and direction == "Neutral_or_NonInferior":
            cand_uL = parse_quantitative_numbers(quote, "Descriptive_or_Unoriented")
            if cand_uL[4] in ("μL", "µL", "uL") and cand_uL[2] is None and cand_uL[5] is None:
                operands = cand_uL
        operand = operands[{"treatment_mean": 0, "treatment_sd_or_sem": 1, "control_mean": 2, "control_sd_or_sem": 3}[field_name]]
        if operand is None:
            m_clause_pair = re.search(
                r"(?<!from\s)(\d+(?:\.\d+)?)\s*(?:\u00b1|\+/-|\+-)\s*(\d+(?:\.\d+)?)\s*(?:nmol/L|pmol/mL|pmol/L|mmol/L|ng/mL|mg/dL|%|mmHg)?\s*"
                r"(?:vs\.?|versus|compared\s+to|compared\s+with)\s*"
                r"(\d+(?:\.\d+)?)\s*(?:\u00b1|\+/-|\+-)\s*(\d+(?:\.\d+)?)\s*(nmol/L|pmol/mL|pmol/L|mmol/L|ng/mL|mg/dL|%|mmHg)\b",
                quote or "",
                flags=re.IGNORECASE,
            )
            if m_clause_pair:
                operand = m_clause_pair.group({"treatment_mean": 1, "treatment_sd_or_sem": 2, "control_mean": 3, "control_sd_or_sem": 4}[field_name])
        if operand is None and field_name in ("treatment_mean", "control_mean"):
            m_resp_pair = re.search(
                r"\bwere\s+(\d+(?:\.\d+)?)%\s+and\s+(\d+(?:\.\d+)?)%,\s*respectively",
                quote or "",
                flags=re.IGNORECASE,
            )
            if m_resp_pair:
                operand = m_resp_pair.group(1 if field_name == "treatment_mean" else 2)
        if field_name in ("treatment_mean", "control_mean"):
            m_avg_resp = re.search(
                r"\baverage\s+of\s+(\d+(?:\.\d+)?)%\s+and\s+(\d+(?:\.\d+)?)%[^.]*\bin\s+activated\s+and\s+resting\b[^.]*,\s*respectively",
                quote or "",
                flags=re.IGNORECASE,
            )
            if m_avg_resp:
                operand = m_avg_resp.group(2 if field_name == "treatment_mean" else 1)
        if operand is None:
            return False
        try:
            return Decimal(str(val)) == Decimal(str(operand))
        except (InvalidOperation, TypeError, ValueError):
            return False

    def _has_bounded_num(token: str) -> bool:
        if not token:
            return False
        if field_name in ("point_estimate", "ci_95_lower", "ci_95_upper") and not token.startswith("-"):
            return bool(re.search(rf"(?:(?<=^)|(?<=[^\d.\-])|(?<=\d-)){re.escape(token)}(?!\d)(?!\.\d)", q_clean))
        return bool(re.search(rf"(?<![\d.]){re.escape(token)}(?!\d)(?!\.\d)", q_clean))