OpenIslet

scripts/verify_iip0041_clinical_h1_cd64t_siglec.py

EXP-028 (CAND-031 / Target IIP-0041 — Bucket 2A) Remediated Verification Suite

script Release v0.8.0 gen-eb955f8266035aba 984 KB · 69 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/verify_iip0041_clinical_h1_cd64t_siglec.py · SHA-256: f004cf6d8259b8b4…

                sub = v_norm[i : i + min_run]
                pos = src_norm.find(sub)
                if pos != -1:
                    k = min_run
                    while i + k < len(v_norm) and pos + k < len(src_norm) and v_norm[i + k] == src_norm[pos + k]:
                        k += 1
                    intervals.append((pos, pos + k))
                    i += k
                else:
                    i += 1
    merged: list[tuple[int, int]] = []
    for s, e in sorted(intervals):
        if merged and s <= merged[-1][1]:
            merged[-1] = (merged[-1][0], max(merged[-1][1], e))
        else:
            merged.append((s, e))
    return {"max_single_field_shingle_chars": max_single, "max_single_field_name": max_field, "aggregate_verbatim_chars_ge25": sum(e - s for s, e in merged)}


def make_empty_readouts(**overrides: Any) -> dict[str, Any]:
    base: dict[str, Any] = {
        "specific_lysis_or_death_pct_mean": None, "specific_lysis_or_death_pct_sd": None,
        "cell_viability_pct_mean": None, "early_72h_graft_survival_pct": None,
        "time_to_vascular_inosculation_hours": None, "necrotic_core_or_damp_release_pct": None,
        "fibrotic_capsule_thickness_um": None, "in_vivo_graft_survival_days_median": None,
        "pct_graft_surviving_at_end_of_followup": None, "followup_duration_days": None,
        "static_gsis_stimulation_index_mean": None, "static_gsis_stimulation_index_sd": None,
        "dynamic_perifusion_first_phase_fold": None, "proinsulin_to_insulin_ratio": None,
        "in_vivo_stimulated_c_peptide_ng_ml": None, "de_novo_dsa_or_autoantibody_spreading_observed": None,
    }
    base.update(overrides)
    return base


def make_arm(
    arm_id: str,
    arm_label: str,
    *,
    cohort_id: str,
    is_reference_control: bool = False,
    sample_size_n: int | None = None,
    sample_size_unit: str = "unspecified_in_source",
    cell_source_class: str,
    cell_line_id: str | None = None,
    stage: str | None = None,
    site: str = "InVitro_Only",
    sys_is: str | None = None,
    challenges: list[dict[str, Any]] | None = None,
    readouts: dict[str, Any] | None = None,
) -> dict[str, Any]:
    ch_list = challenges or [{
        "challenge_type": "Unstressed_Baseline", "effector_to_target_ratio": None, "oxygen_pct": None,
        "glucose_concentration_mM": None, "duration_hours_or_days": None, "specific_autoantigen_or_hla_restriction": None,
    }]
    return {
        "arm_id": arm_id, "arm_label": arm_label, "cohort_id": cohort_id,
        "is_reference_control": is_reference_control,
        "sample_size_n": sample_size_n, "sample_size_unit": sample_size_unit,
        "gate1_substrate_and_differentiation": {
            "cell_source_class": cell_source_class, "cell_line_id": cell_line_id, "donor_hla_profile": None,
            "protocol_backbone": None, "canonical_differentiation_stage_evaluated": stage,
            "stage_small_molecules_and_factors": [], "cluster_mean_diameter_um": None,
            "pct_nkx6_1_cpeptide_double_pos": None, "pct_mafa_pos": None, "pct_alpha_gcg_pos": None,
            "pct_delta_sst_pos": None, "pct_off_target_enterochromaffin_slc18a1": None,
        },
        "gate2_3_4_genetic_and_epitope_edits": [],
        "gate5_engraftment_niche": {
            "transplant_site": site, "prevascularization_lead_time_days": None,
            "in_dish_vascular_assembly": "None_Avascular_Islet", "oxygen_bridge_72h_carrier": "None",
            "packing_density_ieq_per_cm2_or_ml": None, "number_of_distributed_micro_pockets": None,
            "staged_insertion_schedule": None, "encapsulation_or_biomaterial": None,
            "co_transplanted_cells_or_oxygen_source": None, "systemic_immunosuppression_regimen": sys_is,
        },
        "challenge_conditions": ch_list,
        "quantitative_readouts": make_empty_readouts(**(readouts or {})),
    }


def locate_exact_span(dossier: dict[str, Any], quote_substring: str) -> tuple[str, str, str]:
    """Locate quote_substring in abstract, results_paragraphs, or figure_legends and return (span, source_type, fig_or_sec)."""
    abs_txt = dossier.get("abstract") or ""
    idx = abs_txt.find(quote_substring)
    if idx >= 0:
        return f"abstract[{idx}:{idx + len(quote_substring)}]|norm=exact", "abstract", "Abstract"
    ft = dossier.get("fulltext_data_sections") or {}
    for i, p in enumerate(ft.get("results_paragraphs") or []):
        idx = p.find(quote_substring)
        if idx >= 0:
            return f"fulltext_data_sections.results_paragraphs[{i}][{idx}:{idx + len(quote_substring)}]|norm=exact", "results_text", f"Results P[{i}]"
    for i, fg in enumerate(ft.get("figure_legends") or []):
        cap = fg.get("caption") or ""
        idx = cap.find(quote_substring)
        if idx >= 0:
            return f"fulltext_data_sections.figure_legends[{i}].caption[{idx}:{idx + len(quote_substring)}]|norm=exact", "figure_legend", fg.get("label") or f"Figure {i + 1}"
    raise ValueError(f"PMID {dossier.get('pmid')}: quote not found in dossier: {quote_substring!r}")


def make_effect(
    *,
    pmid: str,
    effect_id: str,
    dossier: dict[str, Any],
    dos_sha: str,
    focal_arm_id: str,
    comparator_arm_id: str | None,
    cohort_id: str,
    focal_factor_X: str,
    comparator_X0: str,
    comparator_label: str | None,
    outcome_variable_Y: str,
    outcome_domain: str,
    effect_direction: str,
    quote_substring: str,
    stage: str | None,
    cell_source: str,
    site: str,
    tier: str,
    treatment_mean: float | None = None,
    control_mean: float | None = None,
    point_estimate: float | None = None,
    effect_notes: str | None = None,
    treatment_n: int | None = None,
    control_n: int | None = None,
    measurement_unit: str = "qualitative_statement",
    statistic_type: str = "qualitative_statement_only",
    contrast_type: str = "qualitative_statement_only",
    polarity_class: str = "Qualitative_or_Unoriented_Endpoint",
    orientation_sign: int = 0,
    matched_lexicon_term: str = "none_or_mixed",
    n_unit: str = "unspecified_in_source",
    censoring_note: str = "Not_Time_To_Event_Endpoint",
    timepoint: str | None = None,
    population_or_model: str | None = None,
    penalty_flag: bool = False,
) -> dict[str, Any]:
    span, _src_type, src_fig = locate_exact_span(dossier, quote_substring)
    if not (len(quote_substring) <= 240):
        raise ValueError(f"PMID {pmid}: quote > 240 chars ({len(quote_substring)})!")
    p_tokens = erc._pvalue_tokens(quote_substring)
    p_rel, p_bnd = (p_tokens[0] if len(p_tokens) == 1 else (None, None))
    p_bnd_f = float(p_bnd) if p_bnd is not None else None
    p_exact = p_bnd_f if p_rel == "=" else None
    lrr: float | None = None
    if statistic_type == "log_response_ratio_paired_means":
        if not (treatment_mean is not None and control_mean is not None and treatment_mean > 0 and control_mean > 0):
            raise ValueError('Verification check failed: treatment_mean is not None and control_mean is not None and treatment_mean > 0 and control_mean > 0')
        lrr = round(math.log(treatment_mean / control_mean), 4)
    elif statistic_type == "log_response_ratio_fold_change":
        if not (treatment_mean is not None and treatment_mean > 0 and treatment_mean != 1.0 and control_mean is None):
            raise ValueError('Verification check failed: treatment_mean is not None and treatment_mean > 0 and treatment_mean != 1.0 and control_mean is None')
        sign_mult = (
            1.0
            if (effect_direction == "Protective_or_Improved" and orientation_sign > 0)
            or (effect_direction == "Deleterious_or_Impaired" and orientation_sign < 0)
            else -1.0
        )
        lrr = round(sign_mult * abs(math.log(treatment_mean)), 4)
    return {
        "effect_id": effect_id,
        "source_figure_or_table": src_fig,
        "focal_factor_X": focal_factor_X,
        "comparator_X0": comparator_X0,
        "outcome_variable_Y": outcome_variable_Y,
        "outcome_domain": outcome_domain,
        "treatment_mean": treatment_mean, "treatment_sd_or_sem": None, "treatment_n": treatment_n,
        "control_mean": control_mean, "control_sd_or_sem": None, "control_n": control_n,
        "measurement_unit": measurement_unit,
        "log_response_ratio_or_smd": lrr,
        "point_estimate": point_estimate,
        "effect_notes": effect_notes,
        "p_value": p_exact,
        "effect_direction": effect_direction,
        "secretome_or_differentiation_penalty_observed": penalty_flag,
        "conditioning_context_Z": {
            "Z1_developmental_stage_and_timing": stage or "Not_Applicable_NonIslet_Model",
            "Z2_genetic_background_and_allelic_dose": cell_source,
            "Z3_immune_effector_and_stressor_pathway": outcome_domain,
            "Z4_metabolic_and_glucose_load_state": "Assay condition per primary study",
            "Z5_cytoarchitecture_and_cluster_diameter": "Not_Applicable_or_Unspecified",
            "Z6_microenvironment_oxygen_and_vascular_niche": site,
            "Z7_promoter_and_epigenetic_context": "Endogenous_or_Study_Locus",
            "Z8_species_age_and_sex_context": population_or_model or tier,
        },
        "verbatim_evidence_quote": quote_substring,
        "focal_arm_id": focal_arm_id,
        "comparator_arm_id": comparator_arm_id,
        "p_value_relation": p_rel,
        "p_value_bound": p_bnd_f,
        "direction_adjudication_method": "source_adjudicated_curated_override",
        "dispersion_type": "Not_Reported_in_Source_Sentence",
        "n_unit": n_unit,
        "censoring_note": censoring_note,
        "endpoint_polarity_registry": {
            "polarity_class": polarity_class,
            "orientation_sign": int(orientation_sign),
            "matched_lexicon_term": matched_lexicon_term,
        },
        "dossier_sha256": dos_sha,
        "source_span": span,
        "quote_source_dossier_pmid": pmid,
        "statistic_type": statistic_type,
        "contrast_metadata": {
            "cohort_id": cohort_id,
            "intervention_label": focal_factor_X,
            "comparator_label": comparator_label,
            "endpoint_name": outcome_domain,
            "timepoint": timepoint,
            "population_or_model": population_or_model or f"{cell_source} ({tier})",
            "units": measurement_unit,
            "contrast_type": contrast_type,
        },
    }


def build_and_validate_evidence_bundle(live_pm: dict[str, dict[str, Any]]) -> dict[str, Any]:
    DOSSIERS_DIR.mkdir(parents=True, exist_ok=True)
    # Fetch OA full-text results paragraphs + figure legends for the 2 CC-BY 4.0 net-new studies
    ft_42875686 = fetch_epmc_fulltext_sections("PMC13668765")
    time.sleep(0.3)
    ft_37643018 = fetch_epmc_fulltext_sections("PMC10619436")

    def _ch(ctype: str, *, dur: float | None = None, ag: str | None = None) -> list[dict[str, Any]]:
        return [{
            "challenge_type": ctype, "effector_to_target_ratio": None, "oxygen_pct": None,
            "glucose_concentration_mM": None, "duration_hours_or_days": dur,
            "specific_autoantigen_or_hla_restriction": ag,
        }]

    # 8 strictly net-new empirical studies upgraded to full multi-arm quantitative WORKFLOW.md §5.6 depth (R4 closed!):
    # Every CEG text string is written freshly to have ZERO >=6-word overlap with any dossier abstract/title/results/figures,
    # ZERO "See primary source" / "See primary study follow-up" placeholders, and ZERO post-hoc OpenIslet editorializing in outcomes!
    study_specs: list[dict[str, Any]] = [
        # ------------------------------------------------------------------
        # 1. PMID:42875686 (Rana et al. Adv Sci Oct 2026 — CC-BY 4.0 full text)
        # Retiered per primary source: human EA.hy926/HUVEC is an immortalized endothelial cell line (CEG T5_Rodent_or_CellLine, NOT islet T4);
        # Ring-1 eff1 upgraded to comparative log_response_ratio_fold_change (~7-fold); eff2/3/5/6 comparative descriptive (NOT single_arm_descriptive_only).
        # ------------------------------------------------------------------
        {
            "pmid": "42875686", "ceg_qid": "PMID:42875686", "citation_short": "Rana 2026",
            "oa_pub_allowed": True, "oa_lic": "CC-BY 4.0", "ft_sections": ft_42875686,
            "pillars": ["Pillar2_Immune_Cloaking_Autoantigen_Neoantigen_Stealth", "Pillar4_Engraftment_Vascularization_Oxygenation_Devices"],
            "tier": "Tier_2B_Human_Cells_InVitro_HumanImmune_or_AutoAb_CoCulture",
            "ceg_tier": "T5_Rodent_or_CellLine",
            "ceg_model": "Human EA.hy926/HUVEC immortalized/vascular endothelial monolayers + human PBMC/serum in vitro (non-islet T5); Balb/c->C57BL/6 mouse aortic allograft Day 2/5/15 (T5); ACI->Lewis rat kidney allograft Day 7 (T5)",
            "ceg_immune": "Human PBMC/NK cytotoxicity & human serum C3b deposition (Siglec-7/-9); IS-free murine aortic & rat renal allograft rejection",
            "ceg_donor_source": "Human EA.hy926/HUVEC monolayers + 2 human PBMC donors; Balb/c->C57BL/6 mice (n=3-8/group); ACI->Lewis rats (n=4/group)",
            "ceg_follow_up": "48 h in vitro rewarming retention; Day 2/5/15 mouse aortic allograft; Day 7 rat kidney allograft (no systemic IS)",
            "ceg_target": "Gate 3 / Gate 5 / zero-edit peri-transplant Siglec-7/-9 luminal glycoengineering comparator",
            "ceg_topics": ["EFF:Humoral_DSA_FcR_ADCC_Complement_CDC", "EFF:Leukocyte_Endothelial_Adhesion_ICAM1_LFA1", "EFF:Macrophage_Myeloid_SIRPa_Phagocytosis"],
            "arms": [