OpenIslet

scripts/verify_iip0035_d1b_auto_and_portfolio.py

Deterministic Autologous D1b-Auto-C v2 Mode-B Registry, 45-Cell Stage-0 Contract,

script Release v0.8.0 gen-eb955f8266035aba 288 KB · 23 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_iip0035_d1b_auto_and_portfolio.py · SHA-256: fedb990aeaedd116…

        if g0v_any_positive_k:
            if has_pvid_conflict or not is_fullstack:
                reasons.append("FAIL_HARD_STOP_D1_UNRESOLVED_PRODUCT_GLOBAL_GATE0V_DAY28_VP1_IE1_POSITIVE_EVENT")
            elif effective_l1_arm == "D1AUTO_V2_L1B_CD46WT_CD64T_GATE0V_COMPARATOR":
                reasons.append("FAIL_HARD_STOP_D1_L1B_GATE0V_DAY28_VP1_IE1_POSITIVE_EVENT_SWITCH_TO_L1A_IL1RN")
            else:
                reasons.append("FAIL_HARD_STOP_D1_L1A_GLOBAL_GATE0V_DAY28_VP1_IE1_POSITIVE_EVENT")
    eff_g0v_record = (
        outer_g0v_val
        if (outer_g0v_present and outer_g0v_val is not None)
        else (obs_g0v_rec if (obs_g0v_present and obs_g0v_rec is not None) else None)
    )

    def _cal_kwargs(prefix: str) -> Dict[str, Any]:
        """Resolve assay-local and panel-level calibration & sampling via shared typed resolver."""
        return _resolve_assay_calibration(observations, local_prefix=prefix)

    # Upfront raw 2-field patient_hla_c_alleles parsing shared across D1-01, full-product D1-08, AND L2 component path
    raw_hlac_present = "patient_hla_c_alleles" in observations
    raw_hlac_alleles = observations.get("patient_hla_c_alleles")
    parsed_hlac_alleles: List[str] | None = None
    derived_carries_hlac0304: bool | None = None
    unlisted_hlac_blocks_d1_08_negative = False
    if not raw_hlac_present:
        d1_01_raw_hla_c_input_status = "NOT_SUPPLIED"
    elif raw_hlac_alleles is None:
        d1_01_raw_hla_c_input_status = "EXPLICIT_NULL"
    elif isinstance(raw_hlac_alleles, str) and raw_hlac_alleles == "UNAVAILABLE":
        explicitly_unavailable.append("patient_hla_c_alleles")
        d1_01_raw_hla_c_input_status = "EXPLICIT_UNAVAILABLE"
    else:
        if (
            not isinstance(raw_hlac_alleles, list)
            or len(raw_hlac_alleles) != 2
            or not all(isinstance(a, str) and a == a.strip() and re.fullmatch(r"HLA-C\*[0-9]{2}:[0-9]{2}", a, re.ASCII) for a in raw_hlac_alleles)
        ):
            invalid_or_oob_keys.append("patient_hla_c_alleles")
            d1_01_raw_hla_c_input_status = "MALFORMED"
        else:
            parsed_hlac_alleles = list(raw_hlac_alleles)
            d1_01_raw_hla_c_input_status = "VALID_PAIR"
            if "HLA-C*03:04" in parsed_hlac_alleles:
                # Positive HLA-C*03:04 evidence is ALWAYS retained regardless of partner allele status
                derived_carries_hlac0304 = True
            elif all(a in _PINNED_KNOWN_HLAC_TWO_FIELD_INVENTORY for a in parsed_hlac_alleles):
                # Both alleles are verified against the version-pinned Lin 2023 Table 1 HLA-C inventory
                derived_carries_hlac0304 = False
            else:
                # Unlisted two-field token (e.g. HLA-C*00:00 / HLA-C*99:99) MUST HOLD negative carrier inference!
                derived_carries_hlac0304 = None
                unlisted_hlac_blocks_d1_08_negative = True

    def _cal_meta_from_cp(cp_obj: Dict[str, Any] | None, fallback_samp: Dict[str, Any] | None = None) -> Dict[str, Any] | None:
        if isinstance(cp_obj, dict):
            out_m: Dict[str, Any] = {
                "coverage_regime": cp_obj.get("coverage_regime"),
                "coverage_category": cp_obj.get("coverage_category"),
                "default_calibration_assumptions": cp_obj.get("default_calibration_assumptions"),
                "sampling_independence_provenance": cp_obj.get("sampling_independence_provenance"),
                "alpha_obs_str": cp_obj.get("alpha_obs_str"),
                "alpha_joint_total_str": cp_obj.get("alpha_joint_total_str"),
                "effective_detection_factor_str": cp_obj.get("effective_detection_factor_str"),
                "calibration_sources": cp_obj.get("calibration_sources"),
                "status": cp_obj.get("status"),
            }
            return out_m
        if isinstance(fallback_samp, dict):
            return {
                "coverage_regime": None,
                "coverage_category": None,
                "default_calibration_assumptions": None,
                "sampling_independence_provenance": fallback_samp.get("sampling_independence_provenance"),
                "alpha_obs_str": None,
                "alpha_joint_total_str": None,
                "effective_detection_factor_str": None,
                "calibration_sources": None,
                "status": "ARITHMETIC_WITHHELD",
            }
        return None

    # Clean locus-specific component-only evaluation path (carries full per-assay bound provenance & product-neutral Gate-0V adverse status!)
    if is_component:
        comp_gates = sorted(COMPONENT_APPLICABLE_GATES.get(pvid, ()))
        comp_reasons: List[str] = []
        comp_ap_cp: Dict[str, Any] | None = None
        comp_hlac_cp: Dict[str, Any] | None = None
        comp_t1d_cp: Dict[str, Any] | None = None
        comp_samp_meta: Dict[str, Any] = {}
        comp_d1_08_branch = "COMPONENT_ONLY_NOT_FULLSTACK"
        if pvid == "ISLET1_D1_AUTO_V2_L3_AAVS1_VTCN1_UCOE2S_ICASP9":
            ap_u95_cap_c = thr["ap1903_u95_max"]
            ap_surv_c = _dec("obs_d1_04_dec053_ap1903_icasp9_survivor_frac")
            ap_k_c = _strict_int("obs_d1_04_ap1903_survivor_count_k")
            ap_n_r = _strict_int("obs_d1_04_ap1903_raw_trials_n")
            ap_n_e = _strict_int("obs_d1_04_ap1903_effective_trials_n")
            if ap_n_r is not None and ap_n_e is not None and ap_n_r != ap_n_e:
                comp_reasons.append("FAIL_D1_04_CONFLICTING_RAW_AND_EFFECTIVE_TRIALS_N")
            ap_n_c = ap_n_r if ap_n_r is not None else ap_n_e
            if ap_surv_c is not None and ap_surv_c > ap_u95_cap_c:
                comp_reasons.append("FAIL_D1_04_DEC053_AP1903_ICASP9_SURVIVOR_FRAC_EXCEEDS_1E_8")
            _l3_ap_cal = _cal_kwargs("obs_d1_04_ap1903")
            comp_samp_meta["d1_04_ap1903"] = _l3_ap_cal
            if ap_k_c is None or ap_n_c is None or ap_n_c < 1 or ap_k_c > ap_n_c:
                if ap_k_c is not None and ap_k_c >= 1:
                    comp_reasons.append("FAIL_HARD_STOP_D1_04_AP1903_SURVIVOR_DETECTED")
                else:
                    comp_reasons.append("HOLD_D1_04_AP1903_GY018_INTEGER_KN_REQUIRED")
            else:
                comp_ap_cp = evaluate_sound_decimal_clopper_pearson_zero_event(
                    gate_id="D1_04_AP1903_ICASP9", k=ap_k_c, n_raw=ap_n_c,
                    max_u95_fraction=ap_u95_cap_c, **_l3_ap_cal,
                )
                if comp_ap_cp["status"] == "FAIL_HARD_STOP":
                    comp_reasons.append("FAIL_HARD_STOP_D1_04_AP1903_SURVIVOR_DETECTED")
                elif comp_ap_cp["status"] != "PASS":
                    comp_reasons.append(
                        "HOLD_D1_04_AP1903_INSUFFICIENT_INDEPENDENT_DENOMINATOR"
                        if comp_ap_cp["status"] == "HOLD_INCONCLUSIVE_INSUFFICIENT_INDEPENDENT_DENOMINATOR"
                        else f"HOLD_D1_04_AP1903_{comp_ap_cp['status']}"
                    )
                if ap_surv_c is not None:
                    with _clean_dec_ctx(40):
                        ap_exp_c = Decimal(ap_k_c) / Decimal(ap_n_c)
                        ap_tol_c = max(Decimal("0.05") * ap_exp_c, Decimal("1e-15"))
                        if (
                            (ap_k_c == 0 and ap_surv_c != Decimal(0))
                            or (ap_k_c > 0 and ap_surv_c <= Decimal(0))
                            or (ap_k_c > 0 and abs(ap_surv_c - ap_exp_c) > ap_tol_c)
                        ):
                            comp_reasons.append("FAIL_D1_04_AP1903_SURVIVOR_FRAC_INCONSISTENT_WITH_KN")
            l3_c = _dec("obs_d1_05_l3_day28_retention_pct")
            if l3_c is None:
                comp_reasons.append("HOLD_D1_05_L3_STAGE7_DAY28_RETENTION_REQUIRED")
            elif l3_c < thr["l3_ret_min"]:
                comp_reasons.append("FAIL_D1_05_L3_STAGE7_DAY28_RETENTION_BELOW_80PCT")
            vtcn_c = _dec("obs_d1_07_vtcn1_nrd1_sb7h4_shedding_pct")
            if vtcn_c is None:
                comp_reasons.append("HOLD_D1_07_MISSING_VTCN1_SHEDDING_ASSAY")
            elif vtcn_c > thr["vtcn1_shed_max"]:
                comp_reasons.append("FAIL_D1_07_VTCN1_NRD1_SB7H4_SHEDDING_EXCEEDS_10PCT_MUTAGENESIS_REQUIRED")
        elif pvid == "ISLET1_D1_AUTO_V2_L4_CLYBL_TANDEM_TUBA1B_FSP1_CHS4_CDK1_HTMPK_F105Y":
            chr13_c = observations.get("d1_04_chr13_clybl_tandem_404bp_independent_from_chr19_verified")
            if isinstance(chr13_c, str) and chr13_c == "UNAVAILABLE":
                explicitly_unavailable.append("d1_04_chr13_clybl_tandem_404bp_independent_from_chr19_verified")
                chr13_c = None
            elif chr13_c is not None and not isinstance(chr13_c, bool):
                invalid_or_oob_keys.append("d1_04_chr13_clybl_tandem_404bp_independent_from_chr19_verified")
                chr13_c = None
            elif chr13_c is False:
                comp_reasons.append("FAIL_D1_04_CHR13_CLYBL_TANDEM_INDEPENDENCE_FROM_CHR19_UNVERIFIED")
            if chr13_c is None:
                comp_reasons.append("HOLD_D1_04_L4_CHR13_INDEPENDENCE_REQUIRED")
            azt_chr19_c = observations.get("d1_04_azt_kill_measured_after_forced_chr19_loss")
            if isinstance(azt_chr19_c, str) and azt_chr19_c == "UNAVAILABLE":
                explicitly_unavailable.append("d1_04_azt_kill_measured_after_forced_chr19_loss")
                azt_chr19_c = None
            elif azt_chr19_c is not None and not isinstance(azt_chr19_c, bool):
                invalid_or_oob_keys.append("d1_04_azt_kill_measured_after_forced_chr19_loss")
                azt_chr19_c = None
            elif azt_chr19_c is False:
                comp_reasons.append("FAIL_D1_04_AZT_KILL_NOT_MEASURED_AFTER_FORCED_CHR19_LOSS")
            if azt_chr19_c is None:
                comp_reasons.append("HOLD_D1_04_AZT_KILL_FORCED_CHR19_LOSS_CONDITION_REQUIRED")
            leak_c = _dec("obs_d1_04_g0_beta_htmpk_leak_pct")
            elis_c = _dec("obs_d1_04_hlac07_ryafsgvay_elispot_above_bg_pct")
            azt_c = _dec("obs_d1_04_dec053_azt_dividing_log10_kill")
            l4_c = _dec("obs_d1_05_l4_day28_retention_pct")
            fsp_c = _dec("obs_d1_05_fsp1_ferroptosis_survival_pct")
            if leak_c is not None and leak_c > thr["htmpk_leak_max"]:
                comp_reasons.append("FAIL_D1_04_G0_BETA_HTMPK_F105Y_LEAK_EXCEEDS_0P1PCT")
            if elis_c is not None and elis_c > thr["elispot_max"]:
                comp_reasons.append("FAIL_D1_04_HLAC07_RYAFSGVAY_ELISPOT_EXCEEDS_0P1PCT_G0_GATE")
            if azt_c is not None and azt_c < thr["azt_kill_min"]:
                comp_reasons.append("FAIL_D1_04_DEC053_AZT_DIVIDING_KILL_BELOW_4LOG_AFTER_CHR19_LOSS")
            if l4_c is not None and l4_c < thr["l4_ret_min"]:
                comp_reasons.append("FAIL_D1_05_L4_STAGE7_DAY28_RETENTION_BELOW_80PCT")
            if fsp_c is not None and fsp_c < thr["fsp1_surv_min"]:
                comp_reasons.append("FAIL_D1_05_FSP1_FERROPTOSIS_SURVIVAL_BELOW_80PCT")
            if any(x is None for x in (leak_c, elis_c, azt_c, l4_c, fsp_c)) or azt_chr19_c is not True:
                comp_reasons.append("HOLD_D1_L4_COMPONENT_SUBGATES_INCOMPLETE")
        elif pvid == "ISLET1_D1_AUTO_V2_L2_CXCL10_SERPINB9_PDL1":
            hlac03_cap_c = thr["hlac03_u95_pct_max"]
            carries_c_present = "d1_08_patient_carries_hlac0304" in observations
            carries_c = observations.get("d1_08_patient_carries_hlac0304")
            carries_c_raw_explicit_unavail_or_invalid = False
            if carries_c_present and carries_c is None:
                carries_c_raw_explicit_unavail_or_invalid = True
            elif isinstance(carries_c, str) and carries_c == "UNAVAILABLE":
                explicitly_unavailable.append("d1_08_patient_carries_hlac0304")
                carries_c = None
                carries_c_raw_explicit_unavail_or_invalid = True
            elif carries_c is not None and not isinstance(carries_c, bool):
                invalid_or_oob_keys.append("d1_08_patient_carries_hlac0304")
                carries_c = None
                carries_c_raw_explicit_unavail_or_invalid = True
            if derived_carries_hlac0304 is not None:
                if isinstance(carries_c, bool) and carries_c != derived_carries_hlac0304:
                    comp_reasons.append("FAIL_D1_08_HLAC0304_CARRIER_STATUS_MISMATCH_WITH_RAW_HLA_C_GENOTYPE")
                    if derived_carries_hlac0304 is True:
                        carries_c = True
                elif carries_c is None and not carries_c_raw_explicit_unavail_or_invalid:
                    carries_c = derived_carries_hlac0304
            elif unlisted_hlac_blocks_d1_08_negative and carries_c is None and not carries_c_raw_explicit_unavail_or_invalid:
                comp_reasons.append("HOLD_D1_08_UNLISTED_RAW_HLAC_ALLELE_BLOCKS_NEGATIVE_DERIVATION")
            hlac03_t_c = _dec("obs_d1_08_hlac0304_tcell_lysis_u95_pct")
            hlac03_k_c = _strict_int("obs_d1_08_hlac0304_lysed_events_k")
            hlac03_n_c = _strict_int("obs_d1_08_hlac0304_scored_targets_n")
            t1d_k_c_extra = _strict_int("obs_d1_08_t1d_serum_c5b9_pos_events_k")
            if t1d_k_c_extra is not None and t1d_k_c_extra >= 1:
                comp_reasons.append("FAIL_HARD_STOP_D1_08_T1D_SERUM_C5B9_EVENT_DETECTED")
            _l2_hlac_cal = _cal_kwargs("obs_d1_08_hlac0304")
            comp_samp_meta["d1_08_hlac0304"] = _l2_hlac_cal
            if carries_c is True:
                comp_d1_08_branch = "L2_COMPONENT_HLAC0304_CARRIER_CD8_SUBGATE"
                c0304_pc_c = observations.get("d1_08_hlac0304_positive_control_valid")
                if isinstance(c0304_pc_c, str) and c0304_pc_c == "UNAVAILABLE":
                    explicitly_unavailable.append("d1_08_hlac0304_positive_control_valid")
                    c0304_pc_c = None
                elif c0304_pc_c is not None and not isinstance(c0304_pc_c, bool):
                    invalid_or_oob_keys.append("d1_08_hlac0304_positive_control_valid")
                    c0304_pc_c = None
                elif c0304_pc_c is False:
                    comp_reasons.append("FAIL_D1_08_HLAC0304_POSITIVE_CONTROL_INVALID")
                if c0304_pc_c is None:
                    comp_reasons.append("HOLD_D1_08_HLAC0304_POSITIVE_CONTROL_VALIDITY_REQUIRED")
                if hlac03_k_c is None or hlac03_n_c is None or hlac03_n_c < 1 or hlac03_k_c > hlac03_n_c:
                    if hlac03_k_c is not None and hlac03_k_c >= 1:
                        comp_reasons.append("FAIL_HARD_STOP_D1_08_HLAC0304_LYSIS_EVENT_DETECTED")
                    else:
                        comp_reasons.append("HOLD_D1_08_HLAC0304_GY018_INTEGER_KN_REQUIRED")
                        if hlac03_t_c is None:
                            comp_reasons.append("HOLD_D1_08_HLAC0304_REPORTED_U95_REQUIRED")
                else:
                    comp_hlac_cp = evaluate_sound_decimal_clopper_pearson_zero_event(
                        gate_id="D1_08_HLAC0304_TCELL_LYSIS", k=hlac03_k_c, n_raw=hlac03_n_c,
                        max_u95_fraction=_exact_pct_to_frac(hlac03_cap_c), reported_u95_pct=hlac03_t_c,
                        **_l2_hlac_cal,
                    )
                    if comp_hlac_cp["status"] == "FAIL_HARD_STOP":
                        comp_reasons.append("FAIL_HARD_STOP_D1_08_HLAC0304_LYSIS_EVENT_DETECTED")
                    elif comp_hlac_cp["status"] != "PASS":
                        comp_reasons.append(
                            "HOLD_D1_08_HLAC0304_INSUFFICIENT_INDEPENDENT_DENOMINATOR"
                            if comp_hlac_cp["status"] == "HOLD_INCONCLUSIVE_INSUFFICIENT_INDEPENDENT_DENOMINATOR"
                            else f"HOLD_D1_08_HLAC0304_{comp_hlac_cp['status']}"
                        )
                        if (
                            hlac03_t_c is not None
                            and hlac03_k_c == 0
                            and hlac03_t_c <= hlac03_cap_c