OpenIslet

scripts/verify_wave7_cellgemma_2p24_rebase.py

Wave-7 CellGemma-Islet (IIP-0062 to IIP-0065 / GATE-40 to GATE-43) Pure-CPU

script Release v0.8.0 gen-eb955f8266035aba 1.37 MB · 90 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_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…

                elif int(vk) >= 1:
                    fails.append(f"FAIL_GATE0V_VIRAL_ESCAPE_NONZERO:{tag}")
                if not (is_finite_num(casp) and float(casp) >= 5.0):
                    fails.append(f"FAIL_GATE0V_CASPASE_FOLD_LT_5X:{tag}")

                if amode != "SAME_72H_ALIQUOT" or not is_nonempty_str(aid):
                    holds.append(f"HOLD_GATE0V_NON_SAME_72H_ALIQUOT:{tag}")
                elif not (is_strict_int(pre_n) and is_strict_int(post_tot_k) and int(pre_n) == int(t72_n) and int(post_tot_k) == int(t72_k)):
                    holds.append(f"HOLD_GATE0V_ALIQUOT_COUNT_RECONCILIATION_MISMATCH:{tag}")
                elif is_strict_int(vk) and int(vk) > int(t72_k):
                    fails.append(f"FAIL_GATE0V_VIRAL_ESCAPE_EXCEEDS_TOTAL_SURVIVORS:{tag}")

                eta_eff_l: Optional[Decimal] = None
                if not all(is_strict_int(x) for x in (sh_k, sh_n, sf_k, sf_n)):
                    fails.append(f"FAIL_GATE0V_MISSING_RAW_SPIKE_CALIBRANT_COUNTS:{tag}")
                elif not (0 <= int(sh_k) <= int(sh_n) and int(sh_n) >= 1 and 0 <= int(sf_k) <= int(sf_n) and int(sf_n) >= 1):
                    fails.append(f"FAIL_GATE0V_INVALID_SPIKE_CALIBRANT_COUNTS:{tag}")
                else:
                    max_denom = max(max_denom, int(sh_n), int(sf_n))
                    eta_h = clopper_pearson_lower_decimal(int(sh_k), int(sh_n), "0.005")
                    eta_f = clopper_pearson_lower_decimal(int(sf_k), int(sf_n), "0.005")
                    eta_eff_l = min(eta_h, eta_f)
                    if certify_exact_ci and eta_eff_l < floor_eta_dec:
                        fails.append(f"FAIL_GATE0V_RECOMPUTED_DUAL_SPIKE_ETA_LT_0P80:{tag}")

                if certify_exact_ci and eta_eff_l is not None and s_veh_72 >= floor_veh_dec and is_strict_int(vk) and int(vk) >= 0 and is_strict_int(pre_n) and int(pre_n) >= 1:
                    with localcontext() as ctx:
                        ctx.prec = 75
                        ctx.rounding = ROUND_FLOOR
                        den1 = s_veh_72 * eta_eff_l
                        ctx.rounding = ROUND_CEILING
                        u_esc_tot = clopper_pearson_upper_decimal(int(vk), int(pre_n), "0.005") / den1
                    if u_esc_tot > cap_e1_dec:
                        if int(vk) == 0:
                            holds.append(f"HOLD_GATE0V_ESTIMAND1_TOTAL_ESCAPE_U_GT_1E_4:{tag}")
                        else:
                            fails.append(f"FAIL_GATE0V_ESTIMAND1_TOTAL_ESCAPE_U_GT_1E_4:{tag}")

                if emode != "DIRECT_INFECTED_VEHICLE_DENOMINATOR":
                    holds.append(f"HOLD_GATE0V_INDIRECT_CONDITIONAL_ESCAPE_UNSUPPORTED_FOR_RELEASE:{tag}")
                elif not is_strict_int(d_inf_k) or not (1 <= int(d_inf_k) <= int(v72_k) <= int(v72_n)):
                    fails.append(f"FAIL_GATE0V_INVALID_DIRECT_INFECTED_VEH_SURVIVOR_COUNT:{tag}")
                elif certify_exact_ci and eta_eff_l is not None and is_strict_int(vk) and int(vk) >= 0 and is_strict_int(pre_n) and int(pre_n) >= 1:
                    q_inf_veh_l = clopper_pearson_lower_decimal(int(d_inf_k), int(v72_n), "0.025")
                    if q_inf_veh_l <= Decimal(0):
                        holds.append(f"HOLD_GATE0V_DIRECT_INFECTED_VEH_L975_ZERO:{tag}")
                    else:
                        with localcontext() as ctx:
                            ctx.prec = 75
                            ctx.rounding = ROUND_FLOOR
                            den2 = q_inf_veh_l * eta_eff_l
                            ctx.rounding = ROUND_CEILING
                            u_esc_cond = clopper_pearson_upper_decimal(int(vk), int(pre_n), "0.020") / den2
                        if u_esc_cond > cap_e2_dec:
                            if int(vk) == 0:
                                holds.append(f"HOLD_GATE0V_ESTIMAND2_COND_ESCAPE_U_GT_1E_3:{tag}")
                            else:
                                fails.append(f"FAIL_GATE0V_ESTIMAND2_COND_ESCAPE_U_GT_1E_3:{tag}")

                if is_strict_int(vk) and is_strict_int(d_inf_k) and is_strict_int(sh_k) and is_strict_int(sh_n) and is_strict_int(sf_k) and is_strict_int(sf_n):
                    viral_parts = [
                        ("per_unit_counts_direct_infected_veh_72h", int(d_inf_k), int(v72_n), False),
                        ("per_unit_counts_viral_pos_72h", int(vk), int(t72_n), True),
                        ("per_unit_counts_spike_healthy", int(sh_k), int(sh_n), False),
                        ("per_unit_counts_spike_fragile", int(sf_k), int(sf_n), False),
                    ]
                    if is_mw or (not is_sc):
                        v_parsed: dict[str, Optional[dict[str, tuple[int, int]]]] = {}
                        for pk, ek, en, is_ve in viral_parts:
                            if cell.get(pk) is not None or is_mw:
                                pmap, adv, mm = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en, is_viral_escape=is_ve)
                                if adv:
                                    fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
                                if is_mw and mm:
                                    holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_PARTITION_MISMATCH:{tag}:{pk}")
                                v_parsed[pk] = pmap
                        if is_mw:
                            p_t72 = parsed_parts.get("per_unit_counts_treated_72h")
                            p_v72 = parsed_parts.get("per_unit_counts_veh_72h")
                            ref_u = set(p_t72.keys()) if p_t72 else None
                            for pk in ("per_unit_counts_direct_infected_veh_72h", "per_unit_counts_viral_pos_72h", "per_unit_counts_spike_healthy", "per_unit_counts_spike_fragile"):
                                if ref_u is not None and v_parsed.get(pk) is not None and set(v_parsed[pk].keys()) != ref_u:
                                    holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:{pk}")
                            p_dinf = v_parsed.get("per_unit_counts_direct_infected_veh_72h")
                            if p_dinf is not None and p_v72 is not None and set(p_dinf.keys()) == set(p_v72.keys()):
                                for uid in p_v72:
                                    dk, dn = p_dinf[uid]
                                    vk72, vn72 = p_v72[uid]
                                    if dn != vn72 or not (0 <= dk <= vk72 <= vn72):
                                        holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:direct_inf:{uid}")
                                        break
                            p_vir = v_parsed.get("per_unit_counts_viral_pos_72h")
                            if p_vir is not None and p_t72 is not None and set(p_vir.keys()) == set(p_t72.keys()):
                                for uid in p_t72:
                                    vrk, vrn = p_vir[uid]
                                    tk72, tn72 = p_t72[uid]
                                    if vrn != tn72 or not (0 <= vrk <= tk72 <= tn72):
                                        holds.append(f"HOLD_GATE0V_SAMPLING_UNIT_SUBSET_OR_ID_CONTRADICTION:{tag}:viral:{uid}")
                                        break
                    else:
                        for pk, ek, en, is_ve in viral_parts:
                            if cell.get(pk) is not None:
                                _, adv, _ = _parse_unit_partition(cell.get(pk), n_units=n_units_int, expected_k=ek, expected_n=en, is_viral_escape=is_ve)
                                if adv:
                                    fails.append(f"FAIL_GATE0V_ADVERSE_PER_UNIT_COUNTS:{tag}:{pk}")
                                holds.append(f"HOLD_GATE0V_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE:{tag}")

    if is_sc and n_units_int is not None and n_units_int < max_denom:
        holds.append("HOLD_GATE0V_SINGLE_CELL_UNITS_LT_MAX_DENOMINATOR")


def _validate_lineage_hour0_density(
    spec: Mapping[str, Any],
    density_map: Any,
    *,
    required_lineages: FrozenSet[str],
    fails: list[str],
    prefix: str,
) -> bool:
    if not isinstance(density_map, Mapping):
        fails.append(f"FAIL_{prefix}_MISSING_LINEAGE_HOUR0_DENSITY_MAP")
        return False
    missing_lin = sorted(required_lineages - set(density_map.keys()))
    extra_lin = sorted(set(density_map.keys()) - REQUIRED_5_LINEAGES)
    if missing_lin:
        fails.append(f"FAIL_{prefix}_INCOMPLETE_LINEAGE_HOUR0_DENSITY:{','.join(missing_lin)}")
        return False
    if extra_lin:
        fails.append(f"FAIL_{prefix}_UNRECOGNIZED_HOUR0_LINEAGE:{','.join(extra_lin)}")
        return False

    ok = True
    allowed_lin = frozenset({
        "hlae_molecules_per_cell", "cd47_median_molecules_per_cell",
        "cd47_p10_molecules_per_cell", "autologous_hla_abc_preservation_pct",
    })
    for lin in sorted(density_map.keys()):
        d = density_map[lin]
        if not isinstance(d, Mapping):
            fails.append(f"FAIL_{prefix}_MALFORMED_HOUR0_LINEAGE:{lin}"); ok = False; continue
        _check_allowed_keys(d, allowed_lin, fails, f"{prefix}_HOUR0_{lin}")
        hlae = d.get("hlae_molecules_per_cell")
        cd47_m = d.get("cd47_median_molecules_per_cell")
        cd47_p10 = d.get("cd47_p10_molecules_per_cell")
        if spec["hla_e_engineered"]:
            if not (is_finite_num(hlae) and float(hlae) >= 15000.0):
                fails.append(f"FAIL_{prefix}_HLAE_HOUR0_BELOW_15000:{lin}"); ok = False
        else:
            if not (is_nonempty_str(hlae) and str(hlae).upper().startswith("N/A")):
                fails.append(f"FAIL_{prefix}_NON_HLAE_CONSTRUCT_MUST_DECLARE_NA_HLAE:{lin}"); ok = False

        if spec["cd47_engineered"]:
            if not (is_finite_num(cd47_m) and is_finite_num(cd47_p10)):
                fails.append(f"FAIL_{prefix}_CD47_HOUR0_MISSING:{lin}"); ok = False
            elif float(cd47_m) < 200000.0 or float(cd47_p10) < 180000.0 or float(cd47_p10) > float(cd47_m):
                fails.append(f"FAIL_{prefix}_CD47_HOUR0_GY009_BELOW_200K_180K:{lin}"); ok = False
        else:
            if not (
                is_nonempty_str(cd47_m) and str(cd47_m).upper().startswith("N/A")
                and is_nonempty_str(cd47_p10) and str(cd47_p10).upper().startswith("N/A")
            ):
                fails.append(f"FAIL_{prefix}_NON_CD47_CONSTRUCT_MUST_DECLARE_NA_CD47:{lin}"); ok = False

        if spec["autologous_self_hla"]:
            ahla = d.get("autologous_hla_abc_preservation_pct")
            if not (is_finite_num(ahla) and 85.0 <= float(ahla) <= 100.0):
                fails.append(f"FAIL_{prefix}_AUTOLOGOUS_HLA_ABC_BELOW_85PCT:{lin}"); ok = False
    return ok


def _validate_canonical_binding_v6(
    rec: Mapping[str, Any],
    *,
    allow_design_a: bool,
    coating_gate: bool,
    phase: str,
    require_materialization: bool = True,
    require_switches: bool = True,
    expected_candidate_gene: Optional[str] = None,
    expected_comparator_nt_lot_id: Optional[str] = None,
    expected_coating_identity: Optional[Mapping[str, str]] = None,
    require_gate31_on_design_a_r1: bool = False,
) -> tuple[
    Optional[Mapping[str, Any]], str, list[str], list[str],
    Optional[Mapping[str, Any]], Optional[Mapping[str, Any]], Optional[Mapping[str, Any]], Optional[Mapping[str, Any]],
]:
    fails: list[str] = []
    holds: list[str] = []
    scope_track = "PRIMARY"
    mat_ev: Optional[Mapping[str, Any]] = None
    sw_ev: Optional[Mapping[str, Any]] = None
    g0v_ev: Optional[Mapping[str, Any]] = None
    g31_ev: Optional[Mapping[str, Any]] = None

    raw_arm = str(rec.get("target_arm", "")).strip().upper()
    raw_prod = str(rec.get("product_id", "")).strip()
    raw_route = str(rec.get("route_id", "")).strip().upper()
    raw_bank = str(rec.get("bank_id", "")).strip()
    raw_lot = str(rec.get("lot_id", "")).strip()

    if not allow_design_a:
        if raw_arm in DESIGN_A_FORBIDDEN_ALIASES or raw_prod.upper() in DESIGN_A_FORBIDDEN_ALIASES:
            fails.append("FAIL_DESIGN_A_DRUG_FIREWALL_VIOLATION")
            return None, "BLOCKED_DESIGN_A", fails, holds, None, None, None, None

    if raw_prod in LEGACY_NON_TRANSFERABLE_PRODUCTS:
        fails.append("FAIL_LEGACY_PRODUCT_NON_TRANSFERABLE_TO_V090")
        return None, "BLOCKED_LEGACY", fails, holds, None, None, None, None

    spec = CANONICAL_WAVE6_PRODUCTS.get(raw_prod)
    if spec is None:
        fails.append("FAIL_UNRECOGNIZED_CANONICAL_PRODUCT_ID")
        return None, "INVALID", fails, holds, None, None, None, None

    if raw_arm != spec["arm"]:
        fails.append("FAIL_ARM_PRODUCT_MISMATCH")
    if raw_route not in spec["allowed_routes"]:
        fails.append("FAIL_ROUTE_NOT_ALLOWED_FOR_CANONICAL_PRODUCT")
    if not raw_bank or not raw_lot:
        fails.append("FAIL_MISSING_BANK_OR_LOT_ID")

    prod_s, bank_s, lot_s, route_s = raw_prod, raw_bank, raw_lot, raw_route

    if require_materialization and phase != "BENCH_UNEDITED":
        mat_ev = _validate_content_receipt(
            rec.get("materialization_evidence"),
            expected_stage="BANK_MATERIALIZATION", expected_prod=prod_s, expected_bank=bank_s,
            expected_lot=lot_s, expected_route=None, forbid_route=True,
            expected_scope="exact_product",
            allowed_extra_keys=frozenset({"edited_allele_qc_passed"}),
            fails=fails, holds=holds,
            missing_hold="HOLD_CANONICAL_BANK_MATERIALIZATION_MISSING",
            fail_code="FAIL_CANONICAL_BANK_MATERIALIZATION_FAILED",
            mismatch_code="FAIL_BANK_MATERIALIZATION_SCOPE_MISMATCH",
        )
        if mat_ev is not None and not (is_strict_bool(mat_ev.get("edited_allele_qc_passed")) and mat_ev["edited_allele_qc_passed"]):
            fails.append("FAIL_BANK_MATERIALIZATION_ALLELE_QC_FAILED")

    if coating_gate:
        pair = (raw_prod, raw_route)
        track_mode = str(rec.get("track_mode", "PRIMARY")).strip().upper()
        credit_scope = str(rec.get("credit_scope", "PRIMARY")).strip().upper()
        if pair in ACTIVE_PRIMARY_COATING_PAIRS:
            scope_track = "PRIMARY"
            if track_mode != "PRIMARY" or credit_scope != "PRIMARY":
                fails.append("FAIL_PRIMARY_PAIR_REQUIRES_PRIMARY_TRACK_AND_CREDIT_SCOPE")
        elif pair in DEFERRED_COATING_PAIRS:
            scope_track = "DEFERRED_NON_PRIMARY"
            if track_mode != "DEFERRED_NON_PRIMARY" or credit_scope != "NON_PRIMARY_TRACK_ONLY":
                fails.append("FAIL_DEFERRED_TRACK_CANNOT_CLAIM_PRIMARY_CREDIT")