OpenIslet

scripts/verify_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py

W6-C3 (Provisional Next-Free IIP-0057 / DEC-138 / GATE-36 / GY-035; staging slot iip0057,

script Release v0.8.0 gen-eb955f8266035aba 412 KB · 32 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_iip0057_foundry_v2_shield_invvax_insl82i_cuffv2.py · SHA-256: 1c63dcf649c42be4…

        if paired_u95 is not None and adcc_alias != paired_u95:
            fail_reasons.append(f"{rtag}CD16_ADCC_ALIAS_MISMATCH:{adcc_alias}!={paired_u95}")

    # Pathway-specific GY-025 classical, lectin, alternative, and overall 20% NHS complement bounds
    c4_vals: dict[str, float | None] = {}
    for cpfx, tag in (("classical_c4b2a_residual", "GY025_CLASSICAL_C4B2A"), ("lectin_c4b2a_residual", "GY025_LECTIN_C4B2A")):
        has_l, l_raw = _opt(f"{cpfx}_l95_pct")
        has_u, u_raw = _opt(f"{cpfx}_u95_pct")
        lv = _require_bounded_float(l_raw, f"{pfx}{cpfx}_l95_pct", lo=0.0, hi=100.0) if has_l else None
        uv = _require_bounded_float(u_raw, f"{pfx}{cpfx}_u95_pct", lo=0.0, hi=100.0) if has_u else None
        c4_vals[f"{cpfx}_l95_pct"] = lv
        c4_vals[f"{cpfx}_u95_pct"] = uv
        if lv is not None and uv is not None and lv > uv:
            fail_reasons.append(f"{rtag}{tag}_INTERVAL_INVERTED:{lv}>{uv}")
        if lv is not None and lv > 10.0:
            fail_reasons.append(f"{rtag}{tag}_L95_EXCEEDS_10_FAIL:{lv}%")
        elif uv is not None and uv > 10.0:
            hold_reasons.append(f"{rtag}{tag}_U95_EXCEEDS_10_HOLD:{uv}%")
    if "classical_c4b2a_l95_pct" in src and src["classical_c4b2a_l95_pct"] is not None:
        c4_alias = _require_bounded_float(src["classical_c4b2a_l95_pct"], f"{pfx}classical_c4b2a_l95_pct", lo=0.0, hi=100.0)
        if c4_alias > 10.0:
            fail_reasons.append(f"{rtag}CLASSICAL_C4B2A_L95_ALIAS_FAIL:{c4_alias}%")
        if c4_vals["classical_c4b2a_residual_l95_pct"] is not None and c4_alias != c4_vals["classical_c4b2a_residual_l95_pct"]:
            fail_reasons.append(f"{rtag}CLASSICAL_C4B2A_L95_ALIAS_MISMATCH:{c4_alias}!={c4_vals['classical_c4b2a_residual_l95_pct']}")

    c5_vals: dict[str, float | None] = {}
    for key, tag in (
        ("alternative_c5b9_residual_u95_pct", "GY025_ALTERNATIVE_C5B9"),
        ("overall_20pct_nhs_c5b9_residual_u95_pct", "GY025_OVERALL_20PCT_NHS_C5B9"),
    ):
        has_k, k_raw = _opt(key)
        val = _require_bounded_float(k_raw, f"{pfx}{key}", lo=0.0, hi=100.0) if has_k else None
        c5_vals[key] = val
        if val is not None:
            if val > 15.0:
                fail_reasons.append(f"{rtag}{tag}_U95_FAIL:{val}%")
            elif val > 5.0:
                hold_reasons.append(f"{rtag}{tag}_U95_INTERMEDIATE:{val}%")

    drop_vals: dict[str, float | None] = {}
    for key, tag in (
        ("classical_c4d_c5b9_drop_pct", "CLASSICAL_COMPLEMENT"),
        ("lectin_c4d_c5b9_drop_pct", "LECTIN_COMPLEMENT"),
        ("alternative_c3b_c5b9_drop_pct", "ALTERNATIVE_COMPLEMENT"),
    ):
        has_k, k_raw = _opt(key)
        val = _require_bounded_float(k_raw, f"{pfx}{key}", lo=0.0, hi=100.0) if has_k else None
        drop_vals[key] = val
        if val is not None:
            if val < 70.0:
                fail_reasons.append(f"{rtag}{tag}_BLOCKADE_FAIL:{val}%")
            elif val < 90.0:
                hold_reasons.append(f"{rtag}{tag}_BLOCKADE_INTERMEDIATE:{val}%")

    # Governing GY-025 exact-stack efferocytosis & Gate 0G pericyte recruitment endpoints (EXACT cutoffs, ZERO tolerance!)
    has_eff_abs, eff_abs_raw = _opt("exact_stack_efferocytosis_abs_pct")
    eff_abs = _require_bounded_float(eff_abs_raw, f"{pfx}exact_stack_efferocytosis_abs_pct", lo=0.0, hi=100.0) if has_eff_abs else None
    if eff_abs is not None and eff_abs < 80.0:
        fail_reasons.append(f"{rtag}GY025_EXACT_STACK_EFFEROCYTOSIS_ABS_FAIL:{eff_abs!r}%<80.0%")

    has_eff_wt, eff_wt_raw = _opt("exact_stack_efferocytosis_pct_of_wt")
    eff_wt = _require_bounded_float(eff_wt_raw, f"{pfx}exact_stack_efferocytosis_pct_of_wt", lo=0.0, hi=200.0) if has_eff_wt else None
    if eff_wt is not None and eff_wt < 70.0:
        fail_reasons.append(f"{rtag}GY025_EXACT_STACK_EFFEROCYTOSIS_WT_FAIL:{eff_wt!r}%<70.0%")

    has_peri_wt, peri_wt_raw = _opt("exact_stack_pericyte_recruitment_pct_of_wt")
    peri_wt = _require_bounded_float(peri_wt_raw, f"{pfx}exact_stack_pericyte_recruitment_pct_of_wt", lo=0.0, hi=200.0) if has_peri_wt else None
    if peri_wt is not None and peri_wt < 70.0:
        fail_reasons.append(f"{rtag}GY025_EXACT_STACK_PERICYTE_RECRUITMENT_WT_FAIL:{peri_wt!r}%<70.0%")

    # Vascular safety endpoints (GY-025 PLVAP+ iEC + THBD APC/aPTT + PMN lysis)
    has_t50, t50_raw = _opt("plvap_iec_morphogenesis_t50_h")
    t50 = _require_bounded_float(t50_raw, f"{pfx}plvap_iec_morphogenesis_t50_h", lo=0.0, hi=1e6, strict_lo=True) if has_t50 else None
    if t50 is not None:
        if t50 > 48.0:
            fail_reasons.append(f"{rtag}GY025_PLVAP_IEC_MORPHOGENESIS_T50_FAIL:{t50}h")
        elif t50 > 36.0:
            hold_reasons.append(f"{rtag}GY025_PLVAP_IEC_MORPHOGENESIS_T50_HOLD:{t50}h")

    has_viab, viab_raw = _opt("plvap_iec_viability_pct")
    viab = _require_bounded_float(viab_raw, f"{pfx}plvap_iec_viability_pct", lo=0.0, hi=100.0) if has_viab else None
    if viab is not None:
        if viab < 70.0:
            fail_reasons.append(f"{rtag}GY025_PLVAP_IEC_VIABILITY_FAIL:{viab}%")
        elif viab < 85.0:
            hold_reasons.append(f"{rtag}GY025_PLVAP_IEC_VIABILITY_HOLD:{viab}%")

    has_thbd, thbd_raw = _opt("thbd_h2o2_apc_retention_pct")
    apc_ret = _require_bounded_float(thbd_raw, f"{pfx}thbd_h2o2_apc_retention_pct", lo=0.0, hi=100.0) if has_thbd else None
    if apc_ret is not None:
        if apc_ret < 70.0:
            fail_reasons.append(f"{rtag}THBD_APC_RETENTION_FAIL:{apc_ret}%")
        elif apc_ret < 85.0:
            hold_reasons.append(f"{rtag}THBD_APC_RETENTION_INTERMEDIATE:{apc_ret}%")

    has_aptt, aptt_raw = _opt("bulk_aptt_ratio")
    aptt = _require_bounded_float(aptt_raw, f"{pfx}bulk_aptt_ratio", lo=0.0, hi=100.0, strict_lo=True) if has_aptt else None
    if aptt is not None:
        if aptt > 1.30:
            fail_reasons.append(f"{rtag}BULK_APTT_SAFETY_FAIL:{aptt}x")
        elif aptt > 1.15:
            hold_reasons.append(f"{rtag}BULK_APTT_INTERMEDIATE:{aptt}x")

    has_pmn, pmn_raw = _opt("pmn_residual_lysis_pct")
    pmn = _require_bounded_float(pmn_raw, f"{pfx}pmn_residual_lysis_pct", lo=0.0, hi=100.0) if has_pmn else None
    if pmn is not None:
        if pmn > 15.0:
            fail_reasons.append(f"{rtag}PMN_LYSIS_FAIL:{pmn}%")
        elif pmn > 5.0:
            hold_reasons.append(f"{rtag}PMN_LYSIS_INTERMEDIATE:{pmn}%")

    return {
        "core_cuff_proteins": parsed_core,
        "parsed_conj": parsed_conj,
        "scalars": {
            "study_id": study_id,
            "free_thiol_um": free_thiol_um,
            "coimmobilized_cd200r_accessibility_verified": cd200r_acc,
            "coimmobilized_cd200r_binding_pct_of_unhindered": cd200r_bind,
            "fasl_present": fasl_present,
            "fasl_lcms_below_llod": fasl_below,
            "retired_cfh_19_445_absent": cfh_absent,
            "monomer_pct": mono,
            "retention_30d_pct": ret30,
            "leaching_30d_serum_pct": lch,
            "paired_igg_depleted_control_included": pctrl,
            "adcc_donor_n": adn,
            "intact_serum_total_killing_u95_pct": intact_u95,
            "paired_igg_attributable_cd16_adcc_u95_pct": paired_u95,
            **c4_vals,
            **c5_vals,
            **drop_vals,
            "exact_stack_efferocytosis_abs_pct": eff_abs,
            "exact_stack_efferocytosis_pct_of_wt": eff_wt,
            "exact_stack_pericyte_recruitment_pct_of_wt": peri_wt,
            "plvap_iec_morphogenesis_t50_h": t50,
            "plvap_iec_viability_pct": viab,
            "thbd_h2o2_apc_retention_pct": apc_ret,
            "bulk_aptt_ratio": aptt,
            "pmn_residual_lysis_pct": pmn,
        },
    }


def evaluate_gate34_cuff_v2(
    obs: dict[str, Any],
    arm_manifest: dict[str, Any] | None = None,
    *,
    trusted_evidence_store: dict[str, dict[str, Any]] | None = None,
) -> dict[str, Any]:
    """Fail-closed Gate 34-CUFF-V2 evaluator (Round-5: ALL governing endpoints derived directly from verified current_assay_evidence_record, ZERO threshold tolerance)."""
    try:
        if not isinstance(obs, dict):
            raise ValueError("obs must be dict")
        check_strictly_finite(obs, "gate34_cuff_v2_obs")

        fail_reasons: list[str] = []
        missing_fields: list[str] = []
        hold_reasons: list[str] = []

        verified_manifest = _verify_manifest_context(arm_manifest, obs, fail_reasons, missing_fields)
        _, arm_entry = _check_arm_and_design_a_invariants(obs, "cuff_v2_eligible", verified_manifest, fail_reasons, missing_fields)

        obs_eval = _evaluate_cuff_measurements(
            obs, is_archive=False, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
        )

        cur_raw = obs.get("current_assay_evidence_record") if "current_assay_evidence_record" in obs else None
        if cur_raw is not None and not isinstance(cur_raw, dict):
            raise ValueError("current_assay_evidence_record must be dict")

        if isinstance(cur_raw, dict):
            cur_eval = _evaluate_cuff_measurements(
                cur_raw, is_archive=True, fail_reasons=fail_reasons, missing_fields=missing_fields, hold_reasons=hold_reasons
            )
            if obs_eval["core_cuff_proteins"] is not None and cur_eval["core_cuff_proteins"] is not None:
                if set(cur_eval["core_cuff_proteins"]) != set(obs_eval["core_cuff_proteins"]) or len(cur_eval["core_cuff_proteins"]) != len(obs_eval["core_cuff_proteins"]):
                    fail_reasons.append(
                        f"CUFF_ASSAY_BINDING_MISMATCH:core_cuff_proteins:{cur_eval['core_cuff_proteins']}!={obs_eval['core_cuff_proteins']}"
                    )
            for prot in ("sCR1_v2", "THBD-M406L", "CD200-ECD"):
                op = obs_eval["parsed_conj"].get(prot)
                cp = cur_eval["parsed_conj"].get(prot)
                if op is not None and cp is not None:
                    for subk, ov in op.items():
                        if subk in cp and cp[subk] != ov:
                            fail_reasons.append(f"CUFF_ASSAY_BINDING_MISMATCH:conj.{prot}.{subk}:{cp[subk]!r}!={ov!r}")
            # Enforce EXACT equality (ZERO numeric tolerance!) across ALL 31 scalar Cuff governing fields!
            for fld, obs_v in obs_eval["scalars"].items():
                cur_v = cur_eval["scalars"].get(fld)
                if obs_v is not None and cur_v is not None:
                    if type(obs_v) is bool or type(cur_v) is bool:
                        if obs_v is not cur_v:
                            fail_reasons.append(f"CUFF_ASSAY_BINDING_MISMATCH:{fld}:{cur_v}!={obs_v}")
                    elif cur_v != obs_v:
                        fail_reasons.append(f"CUFF_ASSAY_BINDING_MISMATCH:{fld}:{cur_v!r}!={obs_v!r}")

        return _verify_upstream_evidence_and_finalize(
            obs,
            CANONICAL_GATE34_MODULE_SOURCES["cuff"],
            None,
            arm_entry,
            trusted_evidence_store,
            fail_reasons,
            missing_fields,
            hold_reasons,
            verified_manifest=verified_manifest,
        )
    except ValueError as exc:
        return _malformed_rejection(exc)


def _evaluate_invvax_measurements(
    src: dict[str, Any],
    *,
    is_archive: bool,
    fail_reasons: list[str],
    missing_fields: list[str],
    hold_reasons: list[str],
) -> dict[str, Any]:
    """Validate and enforce ALL governing InvVax measurements & cutoffs directly on `src` (ZERO threshold tolerance)."""
    pfx = "current_assay_evidence_record." if is_archive else ""
    rtag = "ARCHIVE_" if is_archive else ""

    def _opt(key: str) -> tuple[bool, Any]:
        if key not in src or src[key] is None:
            missing_fields.append(f"{pfx}{key}")
            return False, None
        return True, src[key]

    has_study, study_raw = _opt("study_id")
    study_id = _require_canonical_ascii_id(study_raw, f"{pfx}study_id", rtag=rtag, fail_reasons=fail_reasons) if has_study else None

    # Registered 3-administration pre-transplant schedule
    has_days, days_raw = _opt("administration_days")
    admin_days: list[int] | None = None
    if has_days:
        if not isinstance(days_raw, (list, tuple)) or len(days_raw) == 0:
            raise ValueError(f"{pfx}administration_days must be non-empty list of ints")
        admin_days = [_require_exact_int(d, f"{pfx}administration_days[]", lo=-365, hi=365) for d in days_raw]
        if len(admin_days) != 3:
            fail_reasons.append(f"{rtag}INVVAX_REQUIRES_EXACTLY_3_ADMINISTRATIONS_FAIL:count={len(admin_days)}:{admin_days}")
        if any(admin_days[i] >= admin_days[i + 1] for i in range(len(admin_days) - 1)):
            fail_reasons.append(f"{rtag}ADMINISTRATION_DAYS_NOT_STRICTLY_ASCENDING:{admin_days}")
        if any(d > -7 for d in admin_days):
            fail_reasons.append(f"{rtag}ADMINISTRATION_DAY_VIOLATES_PRE_TRANSPLANT_WINDOW:{admin_days}")

    has_last, last_raw = _opt("last_dose_day")
    last_dose_day = _require_exact_int(last_raw, f"{pfx}last_dose_day", lo=-365, hi=365) if has_last else None
    if last_dose_day is not None: