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…

            direction, penalty_observed = classify_sentence_direction_and_penalty(sent, target_gene=target_gene)

            v063_dir = _v063_classify_direction_for_sort(sent)
            v063_tm, v063_tsd, v063_cm, _, _, v063_lrr = _v063_parse_quantitative_numbers(sent, v063_dir)
            sort_priority = (
                1 if v063_lrr is not None else 0,
                1 if (v063_tm is not None and v063_cm is not None) else 0,
                1 if v063_tsd is not None else 0,
                1 if pval is not None else 0,
                1 if re.search(r"\bn\s*=\s*(\d+)\b", sent, flags=re.IGNORECASE) else 0,
            )

            t_mean, t_sd, c_mean, c_sd, unit, lrr = parse_quantitative_numbers(sent, direction)
            focal_x = identify_focal_factor(sent, study_edits, title)
            has_per_group_n = any(k in sl for k in ("per group", "each group", "per arm", "per condition"))
            out_y = sent[:140]

            is_comp = isinstance(lrr, (int, float))
            if is_comp:
                comp_x0, _ = _extract_comparator_clause(sent, study_edits, cell_source, stage, first_author, pub_year)
                if not comp_x0:
                    lrr = None
                    is_comp = False
                    unit = "quarantined_ambiguous_numeric"
                    comp_x0 = "Quarantined numeric observation (no explicit between-arm comparator clause in sentence)"
            elif t_mean is not None and c_mean is not None:
                comp_x0 = "Within-arm longitudinal or baseline-to-followup observation (not a between-arm treatment contrast)"
            else:
                comp_x0 = "Single-arm or qualitative observation (no paired numeric control in sentence)"

            eff_item = {
                "_sort_priority": sort_priority,
                "effect_id": "",
                "source_figure_or_table": src_label,
                "focal_factor_X": focal_x,
                "comparator_X0": comp_x0,
                "outcome_variable_Y": out_y,
                "outcome_domain": domain,
                "treatment_mean": t_mean,
                "treatment_sd_or_sem": t_sd,
                "treatment_n": n_val,
                "control_mean": c_mean,
                "control_sd_or_sem": c_sd,
                "control_n": n_val if (c_mean is not None and has_per_group_n) else None,
                "measurement_unit": unit,
                "log_response_ratio_or_smd": lrr,
                "p_value": pval,
                "effect_direction": direction,
                "secretome_or_differentiation_penalty_observed": penalty_observed,
                "conditioning_context_Z": {
                    "Z1_developmental_stage_and_timing": stage,
                    "Z2_genetic_background_and_allelic_dose": cell_source,
                    "Z3_immune_effector_and_stressor_pathway": domain,
                    "Z4_metabolic_and_glucose_load_state": "Study assay condition",
                    "Z5_cytoarchitecture_and_cluster_diameter": "3D islet / SC-islet cluster or monolayer",
                    "Z6_microenvironment_oxygen_and_vascular_niche": transplant_site,
                    "Z7_promoter_and_epigenetic_context": "Study construct / endogenous locus",
                    "Z8_species_age_and_sex_context": tier,
                },
                "verbatim_evidence_quote": sent,
                "focal_arm_id": f"pmid{pmid}_arm1_primary",
                "comparator_arm_id": f"pmid{pmid}_arm2_comparator" if is_comp else None,
            }
            _populate_effect_provenance(eff_item, dossier, dossier_sha, transplant_site)
            atomic_effects.append(eff_item)

        if modifier_pat.search(sent) and len(modifier_interactions) < 4:
            sl = sent.lower()
            if any(k in sl for k in ("stage", "maturation", "progenitor", "week", "day")):
                mclass = "Z1_Developmental_Timing_or_Stage"
            elif any(k in sl for k in ("dose", "concentration", "mfi", "heterozygous", "homozygous", "copy", "level")):
                mclass = "Z2_Genetic_Background_Zygosity_or_Surface_MFI_Dose"
            elif any(k in sl for k in ("ifn", "cytokine", "nk", "cd8", "cd4", "macrophage", "autoimmun", "allogen")):
                mclass = "Z3_Immune_Effector_Subset_or_Cytokine_Pathway"
            elif any(k in sl for k in ("glucose", "pyruvate", "er stress", "thapsigargin", "metaboli")):
                mclass = "Z4_Metabolic_Glucose_or_ER_Secretory_Load"
            elif any(k in sl for k in ("cluster", "diameter", "alpha", "delta", "paracrine", "reaggregat", "3d", "planar", "monolayer")):
                mclass = "Z5_Cytoarchitecture_Paracrine_or_Cluster_Diameter"
            elif any(k in sl for k in ("hypoxia", "oxygen", "subcutaneous", "oment", "vascular", "microvessel", "kidney")):
                mclass = "Z6_Oxygen_Tension_Vascular_Site_or_ECM_Niche"
            elif any(k in sl for k in ("promoter", "inducible", "constitutive", "silenc")):
                mclass = "Z7_Promoter_Locus_or_Epigenetic_Silencing_Window"
            else:
                mclass = "Z8_Species_Donor_Age_or_Recipient_Sex"

            mod_var_z, lvl1, lvl2 = split_contrast_clauses(sent, prev_sent)
            focal_x = identify_focal_factor(sent, study_edits, title)
            mod_type = (
                "Synergistic_Amplification"
                if "synerg" in sl or "amplif" in sl or "both" in sl
                else ("Complete_Bypass_or_Abrogation" if any(k in sl for k in ("abolish", "abrogat", "completely", "failed to", "but not")) else "Quantitative_Attenuation")
            )

            modifier_interactions.append({
                "interaction_id": f"pmid{pmid}_int{len(modifier_interactions)+1}",
                "source_figure_or_table": src_label,
                "focal_factor_X": focal_x,
                "outcome_Y": classify_outcome_domain(sent),
                "modifier_variable_Z": mod_var_z,
                "modifier_class": mclass,
                "level_1_condition_and_effect": lvl1,
                "level_2_condition_and_effect": lvl2,
                "modification_type": mod_type,
                "critical_threshold_value_and_unit": None,
                "mechanistic_explanation": sent,
            })

        if len(causal_edges) < 5:
            edge = extract_causal_edge_from_sentence(sent, src_label, pmid, study_edits, title)
            if edge is not None:
                causal_edges.append(edge)

        if any(k in sent.lower() for k in ("however", "limitation", "partial", "incomplete", "residual", "failed to", "did not prevent")) and len(residual_vectors) < 3:
            focal_x = identify_focal_factor(sent, study_edits, title)
            residual_vectors.append({
                "arm_or_intervention": focal_x,
                "residual_loss_or_limitation": sent,
                "escape_mechanism_identified": sent,
                "complementary_lever_needed": "Empirical head-to-head comparison required",
            })

        prev_sent = sent

    # Sign-independent selection up to the 8-effect per-study cap (Audit R07: no outcome-dependent harm/benefit truncation)
    atomic_effects.sort(
        key=lambda e: e.get("_sort_priority", (0, 0, 0, 0, 0)),
        reverse=True,
    )
    atomic_effects = [
        eff for eff in atomic_effects[:8]
        if not _is_opening_study_aim_sentence(eff.get("verbatim_evidence_quote") or "")
    ]
    seen_lrr_sigs: set[tuple[Any, Any]] = set()
    for idx_eff, eff in enumerate(atomic_effects, 1):
        eff.pop("_sort_priority", None)
        eff["effect_id"] = f"pmid{pmid}_eff{idx_eff}"
        if isinstance(eff.get("log_response_ratio_or_smd"), (int, float)):
            sig = (eff.get("treatment_mean"), eff.get("log_response_ratio_or_smd"))
            if sig in seen_lrr_sigs:
                eff["log_response_ratio_or_smd"] = None
                eff["comparator_arm_id"] = None
                eff["comparator_X0"] = "Duplicate caption/text mention of primary numeric contrast within same study (quarantined from duplicate LRR weighting)"
                _populate_effect_provenance(eff, dossier, dossier_sha, transplant_site)
            else:
                seen_lrr_sigs.add(sig)

    if not atomic_effects and abstract:
        raw_abs_sents = [s.strip() for s in re.split(r"(?<=[.!])\s+", abstract) if len(s.strip()) >= 25]
        first_abs_is_study_aim = bool(
            raw_abs_sents
            and re.search(r"\bthe\s+aims?\s+of\s+(?:this|the)\s+study\b", raw_abs_sents[0], flags=re.IGNORECASE)
        )
        abs_sents = [
            _trim_quote(s)
            for s in raw_abs_sents
            if not is_stat_boilerplate(s)
        ]
        if first_abs_is_study_aim:
            abs_sents = []
        abs_quote = abs_sents[0] if abs_sents else ("" if first_abs_is_study_aim else _trim_quote(abstract[:280]))
        if not abs_quote:
            bridges = {
                "collateral_and_pleiotropic_findings": pleiotropic_findings,
                "residual_failure_and_escape_vectors": residual_vectors,
                "regime_thresholds": regime_thresholds,
                "high_throughput_screen_hits": [],
            }
            return atomic_effects, modifier_interactions, causal_edges, bridges
        sole_study_gene = study_edits[0]["gene_symbol_hgnc"] if len(study_edits) == 1 else None
        fb_dir, fb_pen = classify_sentence_direction_and_penalty(abs_quote, target_gene=sole_study_gene)
        t_mean, t_sd, c_mean, c_sd, unit, lrr = parse_quantitative_numbers(abs_quote, fb_dir)
        focal_x = identify_focal_factor(abs_quote, study_edits, title)
        out_y = abs_quote[:160]
        is_comp = isinstance(lrr, (int, float))
        eff_fb = {
            "effect_id": f"pmid{pmid}_eff1",
            "source_figure_or_table": "Abstract",
            "focal_factor_X": focal_x,
            "comparator_X0": "Control condition" if is_comp else "Qualitative abstract observation (no quantitative Results sentence matched)",
            "outcome_variable_Y": out_y,
            "outcome_domain": classify_outcome_domain(abs_quote),
            "treatment_mean": t_mean,
            "treatment_sd_or_sem": t_sd,
            "treatment_n": None,
            "control_mean": c_mean,
            "control_sd_or_sem": c_sd,
            "control_n": None,
            "measurement_unit": unit,
            "log_response_ratio_or_smd": lrr,
            "p_value": None,
            "effect_direction": fb_dir,
            "secretome_or_differentiation_penalty_observed": fb_pen,
            "conditioning_context_Z": {
                "Z1_developmental_stage_and_timing": stage,
                "Z2_genetic_background_and_allelic_dose": cell_source,
                "Z3_immune_effector_and_stressor_pathway": classify_outcome_domain(abstract),
                "Z4_metabolic_and_glucose_load_state": "Reported in study",
                "Z5_cytoarchitecture_and_cluster_diameter": "Islet / beta-cell preparation",
                "Z6_microenvironment_oxygen_and_vascular_niche": transplant_site,
                "Z7_promoter_and_epigenetic_context": "Reported in study",
                "Z8_species_age_and_sex_context": tier,
            },
            "verbatim_evidence_quote": abs_quote,
            "focal_arm_id": f"pmid{pmid}_arm1_primary",
            "comparator_arm_id": f"pmid{pmid}_arm2_comparator" if is_comp else None,
        }
        _populate_effect_provenance(eff_fb, dossier, dossier_sha, transplant_site)
        atomic_effects.append(eff_fb)

    bridges = {
        "collateral_and_pleiotropic_findings": pleiotropic_findings,
        "residual_failure_and_escape_vectors": residual_vectors,
        "regime_thresholds": regime_thresholds,
        "high_throughput_screen_hits": [],
    }
    return atomic_effects, modifier_interactions, causal_edges, bridges


SUPERSEDED_PREPRINT_MAP = {
    "40832357": "41202120",  # Preprint of Science Advances 2025 peer-reviewed paper (41202120)
    "37502937": "38661000",  # Preprint of Nature Communications 2024 peer-reviewed paper (38661000)
    "38496417": "38975343",  # Preprint of Journal of Autoimmunity 2024 peer-reviewed paper (38975343)
    "38766166": "40335415",  # Preprint of Nature Communications 2025 peer-reviewed paper (40335415)
    "39149298": "39232561",  # Preprint of Science Advances 2024 peer-reviewed paper (39232561)
    "39211206": "40892543",  # Preprint of Journal of Clinical Investigation 2025 peer-reviewed paper (40892543)
    "39763971": "40875294",  # Preprint of Diabetologia 2025 peer-reviewed paper (40875294)
    "40236391": "40614820",  # Preprint of iScience 2025 peer-reviewed paper (40614820)
    "40777266": "42120510",  # Preprint of Nature Communications 2026 peer-reviewed paper (42120510)
    "41542419": "42158573",  # Preprint of Journal of Biomedical Materials Research 2026 peer-reviewed paper (42158573)
    "39211191": "41372150",  # Preprint of Nature Biomedical Engineering 2025 peer-reviewed paper (41372150, outside Ring 1)
    "37886586": "40737125",  # Preprint of Nature Communications 2025 peer-reviewed paper (40737125, outside Ring 1)
    "41509220": "42787837",  # Preprint of Diabetes 2026 peer-reviewed paper (42787837, outside Ring 1)
    "37905040": "38985991",  # Preprint of Molecular Metabolism 2024 peer-reviewed paper (38985991, outside Ring 1)
}

PEER_REVIEWED_TO_PREPRINT_MAP = {v: k for k, v in SUPERSEDED_PREPRINT_MAP.items()}


CONFIRMED_NARRATIVE_REVIEW_PMIDS: frozenset[str] = frozenset({
    "16435302",  # Pearl-Yafe & Askenasy 2006 (BioEssays): narrative review of FasL in diabetes/islet tx
    "38099391",  # Yang & Wang 2023 (Minerva Endocrinol): narrative review ("Update on the ZNT8 epitope...")
    "41574859",  # Narrative review ("Stem Cell Therapy as a Regenerative Strategy in Hereditary Pancreatitis...")
    "42613697",  # Dushyant & Singh 2026: narrative review ("Regenerative Approaches in Type 1 Diabetes...")
})


def _apply_bibliographic_evidence_scope(record: dict, dossier: dict) -> None:
    """Reviews are bibliography/context, never independent experimental arms.

    Their source text remains in the dossier for citation tracing. Harvested