OpenIslet

scripts/verify_iip0043_wholegraft_gate0v_and_calibration.py

IIP-0043 / DEC-122 (CAND-034 / EXP-031 — Bucket 1 Closure, Stage S3-R2 Remediated)

script Release v0.8.0 gen-eb955f8266035aba 1008 KB · 76 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_iip0043_wholegraft_gate0v_and_calibration.py · SHA-256: 20706180ed1ed6a2…

    ok = len(errs) == 0
    return ok, errs, {
        "authenticated": ok,
        "resolution_source": store_src,
        "self_attested_inline_record_ignored": inline_record_if_supplied is not None,
        "computed_sha256": computed_sha,
        "approved_by_authority_id": rec.get("approved_by_authority_id"),
        "record_product_variant_id": rec_pvid_canon,
        "record_operational_tier": rec.get("operational_tier"),
        "record_verdict": rec.get("verdict"),
        "record_underlying_gate0v_verdict": rec.get("underlying_gate0v_verdict"),
        "record_require_trusted_nw08_ocr_record": rec_req_ocr,
        "archived_process_payload_verified": archived_verified,
        "staged_autologous_contract_note": (
            "AUTOLOGOUS_D1B_PROCESS_QUAL is a staged autologous path contingent on legacy execution_supported "
            "promotion; legitimate upstream issuers must use autologous process-qualification PASS semantics "
            "(PASS_WHOLEGRAFT_AUTOLOGOUS_PROCESS_QUAL / PASS_COMPOSITE_AUTOLOGOUS_PROCESS_QUAL, never "
            "allogeneic PASS_WHOLEGRAFT_BANK_QUALIFICATION) with linked process archive evidence prior to activation."
        ),
        "deployment_prerequisite": (
            "Software record-content and SHA-256 verification require independent QA operator "
            "administration, write-restricted storage control, and separation of duties over "
            "--trusted-qualification-store as deployment prerequisites."
        ),
    }


def _adjudicate_supplemental_pathogen_adverse_data(
    path_id: str,
    pblock: Any,
    *,
    deff: Decimal | None,
    alpha_obs_tier: Decimal,
    hard_stops: List[str],
    holds: List[str],
    adjudicated_log: List[str],
    check_unit_basis_fn: Any = None,
) -> None:
    """
    B6 / R03-B1 rule: Never silently drop submitted pathogen results in abbreviated tiers!
    Any submitted adverse finding in a supplemental pathogen block MUST trigger FAIL_HARD_STOP,
    and any submitted malformed/uncalibrated control or confirmation data MUST fail closed (HOLD).
    """
    p_tag = str(path_id).upper()
    adjudicated_log.append(f"supplemental_pathogen:{path_id}")
    if not isinstance(pblock, dict):
        holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_INVALID_PATHOGEN_BLOCK_{p_tag}")
        return

    for comp_key in ("endocrine_72h_log10_pfu_u95", "vascular_72h_log10_pfu_u95", "coculture_72h_log10_pfu_u95"):
        v = _to_exact_decimal(pblock.get(comp_key))
        if v is not None and v > Decimal("2.0"):
            hard_stops.append(f"FAIL_GATE0V_B_SUPPLEMENTAL_ACUTE_TITER_EXCEEDS_2LOG10_{p_tag}_{comp_key.upper()}")

    for comp_key in ("endocrine_day14_log10_reduction_l95", "vascular_day14_log10_reduction_l95"):
        v = _to_exact_decimal(pblock.get(comp_key))
        if v is not None and v < Decimal("3.0"):
            hard_stops.append(f"FAIL_GATE0V_B_SUPPLEMENTAL_DAY14_CLEARANCE_BELOW_3LOG10_{p_tag}_{comp_key.upper()}")

    rna_k = pblock.get("day14_negative_strand_or_ie1_rna_positive_wells_k")
    if _is_strict_int(rna_k) and rna_k > 0:
        hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_ACTIVE_VIRAL_RNA_DETECTED_{p_tag}")

    day28_pfu = _to_exact_decimal(pblock.get("day28_supernatant_infectious_pfu_ml"))
    if day28_pfu is not None and day28_pfu > Decimal(0):
        hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_DAY28_INFECTIOUS_SHEDDING_{p_tag}")

    delta_l95 = _to_exact_decimal(pblock.get("edited_minus_wt_day14_log10_reduction_l95"))
    if delta_l95 is not None and delta_l95 < Decimal("-0.50"):
        hard_stops.append(f"FAIL_GATE0V_B_SUPPLEMENTAL_ANTIVIRAL_COMPETENCE_LOSS_EXCEEDS_0P5_LOG10_{p_tag}")

    lat_arm = pblock.get("day28_latent_and_defective_genome_arm")
    if isinstance(lat_arm, dict):
        dd_k = lat_arm.get("ddpcr_positive_events_k")
        if _is_strict_int(dd_k) and dd_k >= 1:
            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_LATENT_OR_DEFECTIVE_GENOME_DETECTED_{p_tag}_K_{dd_k}")
        dd_targets = lat_arm.get("ddpcr_targets")
        if isinstance(dd_targets, dict):
            for tname, tentry in dd_targets.items():
                if isinstance(tentry, dict) and _is_strict_int(tentry.get("k")) and tentry["k"] >= 1:
                    hard_stops.append(
                        f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_LATENT_TARGET_DETECTED_{p_tag}_{str(tname).upper()}_K_{tentry['k']}"
                    )
        react_pfu = _to_exact_decimal(lat_arm.get("reactivation_7d_outgrowth_pfu_ml"))
        if react_pfu is not None and react_pfu > Decimal(0):
            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_B_SUPPLEMENTAL_{p_tag}_LATENT_REACTIVATION_OUTGROWTH")

    unass_ro = pblock.get("unassigned_fraction_viral_readout")
    if isinstance(unass_ro, dict):
        uk2 = unass_ro.get("stage2_confirmed_infectious_k")
        if _is_strict_int(uk2) and uk2 >= 1:
            hard_stops.append(f"FAIL_HARD_STOP_GATE0V_SUPPLEMENTAL_CONFIRMED_VIRAL_POSITIVE_UNASSIGNED_{p_tag}_K_{uk2}")
        uk1 = unass_ro.get("stage1_screen_positive_k")
        un2 = unass_ro.get("stage2_sorted_for_confirmation_n")
        if _is_strict_int(uk1) and _is_strict_int(un2) and un2 != uk1:
            holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNCONFIRMED_UNASSIGNED_STAGE1_HITS_{p_tag}")

    lin_data = pblock.get("day28_persistence_by_lineage")
    if isinstance(lin_data, dict):
        alpha_05 = Decimal("0.05")
        max_neg_ctrl_fpr_u95 = Decimal("0.0015")
        min_eta_cal = Decimal("0.80")
        for lin_name, entry in lin_data.items():
            lin_tag = str(lin_name).upper()
            if lin_name not in GRAFT_LINEAGES:
                holds.append(f"HOLD_UNRECOGNIZED_LINEAGE_KEY_GATE0V_B_SUPPLEMENTAL_{p_tag}_{lin_tag}")
            if not isinstance(entry, dict):
                holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_INVALID_LINEAGE_ENTRY_{p_tag}_{lin_tag}")
                continue
            k2 = entry.get("stage2_confirmed_infectious_k")
            if _is_strict_int(k2) and k2 >= 1:
                hard_stops.append(
                    f"FAIL_HARD_STOP_GATE0V_SUPPLEMENTAL_CONFIRMED_VIRAL_POSITIVE_{p_tag}_{lin_tag}_K_{k2}"
                )
            k1 = entry.get("stage1_screen_positive_k")
            n2 = entry.get("stage2_sorted_for_confirmation_n")
            if k1 is not None or n2 is not None:
                if not (_is_strict_int(k1) and _is_strict_int(n2) and n2 == k1):
                    holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNCONFIRMED_STAGE1_HITS_{p_tag}_{lin_tag}")
            uc_k = entry.get("uninfected_ctrl_fp_k")
            uc_n = entry.get("uninfected_ctrl_scored_n")
            if uc_k is not None or uc_n is not None:
                if check_unit_basis_fn is not None:
                    check_unit_basis_fn(
                        entry.get("uninfected_ctrl_per_unit_counts"),
                        k_val=uc_k,
                        n_val=uc_n,
                        label=f"SUPP_NEG_CTRL_{p_tag}_{lin_tag}",
                    )
                if not (_is_strict_int(uc_k) and _is_strict_int(uc_n) and uc_n >= 20_000 and 0 <= uc_k <= uc_n):
                    holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNDERPOWERED_UNINFECTED_FPR_CTRL_{p_tag}_{lin_tag}")
                else:
                    fpr_u95 = exact_clopper_pearson_upper_general(uc_k, uc_n, alpha_05, prec=60)
                    if fpr_u95 > max_neg_ctrl_fpr_u95:
                        holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_UNINFECTED_CTRL_FPR_U95_EXCEEDS_0P15PCT_{p_tag}_{lin_tag}")
            rk_i = entry.get("spike_calibrant_detected_k")
            rn_i = entry.get("spike_calibrant_total_n")
            frk_i = entry.get("fragile_infected_spike_detected_k")
            frn_i = entry.get("fragile_infected_spike_total_n")
            if any(x is not None for x in (rk_i, rn_i, frk_i, frn_i)):
                if check_unit_basis_fn is not None:
                    check_unit_basis_fn(
                        entry.get("spike_calibrant_per_unit_counts"),
                        k_val=rk_i,
                        n_val=rn_i,
                        label=f"SUPP_SPIKE_CAL_HEALTHY_{p_tag}_{lin_tag}",
                    )
                    check_unit_basis_fn(
                        entry.get("fragile_infected_spike_per_unit_counts"),
                        k_val=frk_i,
                        n_val=frn_i,
                        label=f"SUPP_SPIKE_CAL_FRAGILE_{p_tag}_{lin_tag}",
                    )
                if not (
                    _is_strict_int(rk_i) and _is_strict_int(rn_i) and rn_i >= 1 and 0 <= rk_i <= rn_i
                    and _is_strict_int(frk_i) and _is_strict_int(frn_i) and frn_i >= 1 and 0 <= frk_i <= frn_i
                ):
                    holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_INVALID_DUAL_SPIKE_CALIBRANT_{p_tag}_{lin_tag}")
                else:
                    eta_eff_l = min(
                        exact_clopper_pearson_lower_calibrant(rk_i, rn_i, alpha_obs_tier, prec=80),
                        exact_clopper_pearson_lower_calibrant(frk_i, frn_i, alpha_obs_tier, prec=80),
                    )
                    if eta_eff_l < min_eta_cal:
                        holds.append(f"HOLD_GATE0V_B_SUPPLEMENTAL_CALIBRANT_SENSITIVITY_BELOW_0P80_{p_tag}_{lin_tag}")


def _adjudicate_kill_regime_lineage_arm(
    reg: str,
    lin: str,
    lblock: Dict[str, Any],
    *,
    deff: Decimal | None,
    hard_stops: List[str],
    holds: List[str],
    is_supplemental: bool = False,
    sampling_spec_valid: bool = True,
    sampling_unit_class: str | None = None,
    indep_units_n: int | None = None,
    sampling_tracker: Dict[str, Any] | None = None,
) -> Tuple[bool, Dict[str, Any]]:
    """
    Single unified fail-closed Gate 0V-Kill adjudicator shared by BOTH required stress arms
    and submitted supplemental stress arms in abbreviated tiers (R03-B1 + R12-B1):
      - NEVER certifies exact directional confidence when `clustering_and_independence_spec` is
        missing/invalid (`deff is None`), clustered (`deff > 1.0`), has `< 6` independent biological
        units, or lacks reconciled per-estimand `per_unit_counts` / unit-matched single-cell basis.
      - Recomputes paired 24-h (>= 99.9%) and 72-h (>= 4.0 log10) vehicle-adjusted kill
        bounds directly from raw integer counts (Bonferroni 0.025 + 0.025 = 0.050).
      - Preserves deterministic biological FAIL_HARD_STOPs (`vk >= 1`, `caspase < 5.0x`,
        `k_treated > n_treated`, `surv_n > n_in`) even when exact confidence is uncertified!
      - Applies full infected-arm caspase-9/3 blockade (< 5.0x -> FAIL_HARD_STOP), viable
        viral-positive survivor veto (`vk >= 1` -> FAIL_HARD_STOP, checked unconditionally
        so no HOLD can mask a hard stop), aliquot reconciliation, dual healthy + fragile
        spike calibrant (`eta >= 0.80`), Estimand 1 (`U_esc,total <= 1e-4`, sum 0.035),
        and Estimand 2 (`U_esc,cond <= 1e-3`, direct or indirect sum 0.050).
    """
    reg_tag = str(reg).upper()
    lin_tag = str(lin).upper()
    sup_hs = "SUPPLEMENTAL_" if is_supplemental else ""
    sup_hd = "SUPPLEMENTAL_" if is_supplemental else ""

    cap_frac_kill_esc_total = Decimal("0.0001")  # 0.01% (4.0 log10) per total input at risk (proposed)
    cap_frac_kill_esc_cond = Decimal("0.001")    # 0.10% (3.0 log10) conditional per infected cell (proposed)
    alpha_paired_veh = Decimal("0.025")
    alpha_paired_surv = Decimal("0.025")
    alpha_e1_eta = Decimal("0.005")
    alpha_e1_esc = Decimal("0.005")
    alpha_e2_ind_veh = Decimal("0.015")
    alpha_e2_ind_prev = Decimal("0.015")
    alpha_e2_ind_eta = Decimal("0.005")
    alpha_e2_ind_esc = Decimal("0.015")
    alpha_e2_dir_inf_veh = Decimal("0.025")
    alpha_e2_dir_eta = Decimal("0.005")
    alpha_e2_dir_esc = Decimal("0.020")
    min_eta_cal = Decimal("0.80")
    min_s_veh = Decimal("0.10")

    def _append_unique(target_list: List[str], token: str) -> None:
        if token not in target_list:
            target_list.append(token)

    v24_v = lblock.get("veh_24h_viable_n")
    v24_n = lblock.get("veh_24h_input_n")
    a24_n = lblock.get("ap1903_24h_input_n")
    a24_k = lblock.get("ap1903_24h_viable_survivors_k")

    v72_v = lblock.get("veh_72h_viable_n")
    v72_n = lblock.get("veh_72h_input_n")
    a72_n = lblock.get("ap1903_72h_input_n")
    a72_k = lblock.get("ap1903_72h_viable_survivors_k")

    is_infected_arm = reg in INFECTED_AP1903_REGIMES
    casp_fold_raw = lblock.get("caspase9_3_activity_fold_over_vehicle")
    vk_raw = lblock.get("post_ap1903_viable_viral_pos_k")
    n_in = lblock.get("pre_ap1903_lineage_input_cells_n")
    direct_inf_veh_k = lblock.get("pretreat_infected_veh_survivor_n")
    rk = lblock.get("spike_calibrant_detected_k")
    rn = lblock.get("spike_calibrant_total_n")
    frk = lblock.get("fragile_infected_spike_detected_k")
    frn = lblock.get("fragile_infected_spike_total_n")

    # R12-B1 + R17-B1: Track ALL binomial denominators (including stressed-arm recovery calibrants!)
    # & validate per-estimand sampling-unit partitions on EVERY count entering Clopper-Pearson bounds!
    arm_partition_ok = True
    arm_denoms: List[int] = [
        int(d_n)
        for d_n in (
            v24_n,
            a24_n,