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…

            vb = cd46.get(vid)
            if isinstance(vb, dict):
                vp = _try_part(vb.get("day28_5lineage_ddpcr_confirmed_k"), vb.get("day28_5lineage_cells_screened_per_lineage_min_n"))
                if vp is not None:
                    vb["per_unit_counts"] = vp

    cd55 = payload.get("cd55_tropic_echovirus_addendum")
    if isinstance(cd55, dict) and isinstance(cd55.get("strain_results"), dict):
        for sb in cd55["strain_results"].values():
            if isinstance(sb, dict) and isinstance(sb.get("day28_persistence_by_lineage"), dict):
                for le in sb["day28_persistence_by_lineage"].values():
                    if isinstance(le, dict):
                        ep = _try_part(le.get("confirmed_k"), le.get("cells_screened_n"))
                        if ep is not None:
                            le["per_unit_counts"] = ep

    ap = payload.get("gate0v_kill_stress_ap1903")
    if isinstance(ap, dict):
        for reg, rb in ap.items():
            if not isinstance(rb, dict):
                continue
            for lb in rb.values():
                if not isinstance(lb, dict):
                    continue
                puc: Dict[str, Any] = {}
                for k_name, k_key, n_key in (
                    ("veh_24h", "veh_24h_viable_n", "veh_24h_input_n"),
                    ("ap1903_24h", "ap1903_24h_viable_survivors_k", "ap1903_24h_input_n"),
                    ("veh_72h", "veh_72h_viable_n", "veh_72h_input_n"),
                    ("ap1903_72h", "ap1903_72h_viable_survivors_k", "ap1903_72h_input_n"),
                ):
                    pt = _try_part(lb.get(k_key), lb.get(n_key))
                    if pt is not None:
                        puc[k_name] = pt
                if reg in INFECTED_AP1903_REGIMES:
                    vk_v = lb.get("post_ap1903_viable_viral_pos_k")
                    n_in_v = lb.get("pre_ap1903_lineage_input_cells_n")
                    a72_part = puc.get("ap1903_72h")
                    if (
                        a72_part is not None
                        and _is_strict_int(vk_v)
                        and _is_strict_int(n_in_v)
                        and n_in_v == lb.get("ap1903_72h_input_n")
                        and 0 <= vk_v <= sum(int(p["k"]) for p in a72_part)
                    ):
                        puc["infected_viral_pos_72h"] = _build_subset_unit_partition(vk_v, a72_part)
                    else:
                        pt_vp = _try_part(vk_v, n_in_v)
                        if pt_vp is not None:
                            puc["infected_viral_pos_72h"] = pt_vp
                    div_k = lb.get("pretreat_infected_veh_survivor_n")
                    if div_k is not None:
                        v72_part = puc.get("veh_72h")
                        if (
                            v72_part is not None
                            and _is_strict_int(div_k)
                            and 0 <= div_k <= sum(int(p["k"]) for p in v72_part)
                        ):
                            puc["direct_infected_veh_72h"] = _build_subset_unit_partition(div_k, v72_part)
                        else:
                            pt_div = _try_part(div_k, lb.get("veh_72h_input_n"))
                            if pt_div is not None:
                                puc["direct_infected_veh_72h"] = pt_div
                    pt_sc = _try_part(lb.get("spike_calibrant_detected_k"), lb.get("spike_calibrant_total_n"))
                    if pt_sc is not None:
                        puc["spike_calibrant"] = pt_sc
                    pt_fsc = _try_part(
                        lb.get("fragile_infected_spike_detected_k"),
                        lb.get("fragile_infected_spike_total_n"),
                    )
                    if pt_fsc is not None:
                        puc["fragile_infected_spike_calibrant"] = pt_fsc
                if puc:
                    lb["per_unit_counts"] = puc
    return payload


def _inspect_per_unit_counts(
    raw_partition: Any,
    *,
    expected_units_n: int | None,
    expected_k: int | None,
    expected_n: int | None,
) -> Dict[str, Any]:
    """
    R12-B1 + R13-B1 + R13-B2 Exhaustive zero-early-return validator and adverse-row scanner for
    per-estimand `per_unit_counts`:
      - NEVER early-returns on a malformed row (`NON_DICT_UNIT_ENTRY`, `INVALID_UNIT_ID`,
        `INVALID_UNIT_DICT_ENTRY`, `DUPLICATE_UNIT_ID`, etc.): collects ALL schema errors AND scans
        EVERY interpretable dict row in the collection regardless of row-ID validity.
      - Tracks `any_pos_k`, `any_k_gt_n`, `sum_interp_k`, `sum_interp_n`, `interpretable_rows_n`,
        and canonical `unit_map: {unit_id: (k_u, n_u)}` for cross-estimand same-unit reconciliation.
      - Enforces `expected_units_n >= MIN_INDEPENDENT_BIOLOGICAL_UNITS_N (6)`, `len == expected_units_n`,
        unique valid `unit_id`s, strict ints `n_u > 0` and `0 <= k_u <= n_u`, and exact arithmetic
        reconciliation `sum(n_u) == expected_n` AND `sum(k_u) == expected_k`.
    """
    any_pos_k = False
    any_k_gt_n = False
    sum_interp_k = 0
    sum_interp_n = 0
    interpretable_rows_n = 0
    sum_valid_k = 0
    sum_valid_n = 0
    errors: List[str] = []
    seen_uids: set[str] = set()
    unit_map: Dict[str, Tuple[int, int]] = {}
    total_rows = 0

    def _add_err(code: str) -> None:
        if code not in errors:
            errors.append(code)

    raw_items: List[Tuple[Any, Any, bool]] = []
    if isinstance(raw_partition, list):
        total_rows = len(raw_partition)
        for item in raw_partition:
            if not isinstance(item, dict):
                _add_err("NON_DICT_UNIT_ENTRY")
                continue
            raw_items.append((item.get("unit_id"), item, True))
    elif isinstance(raw_partition, dict):
        total_rows = len(raw_partition)
        for uid, item in raw_partition.items():
            if not isinstance(item, dict):
                _add_err("INVALID_UNIT_DICT_ENTRY")
                continue
            raw_items.append((uid, item, False))
    else:
        return {
            "reconciled_ok": False,
            "any_pos_k": False,
            "any_k_gt_n": False,
            "sum_interp_k": 0,
            "sum_interp_n": 0,
            "interpretable_rows_n": 0,
            "reason_code": "MISSING_OR_NON_COLLECTION_PER_UNIT_COUNTS",
            "all_errors": ["MISSING_OR_NON_COLLECTION_PER_UNIT_COUNTS"],
            "unit_map": {},
        }

    for uid, item, is_list_entry in raw_items:
        k_u = item.get("k")
        n_u = item.get("n")
        k_is_int = _is_strict_int(k_u)
        n_is_int = _is_strict_int(n_u)
        if k_is_int or n_is_int:
            interpretable_rows_n += 1
        if k_is_int:
            if k_u >= 1:
                any_pos_k = True
            if k_u >= 0:
                sum_interp_k += int(k_u)
        if n_is_int and n_u >= 0:
            sum_interp_n += int(n_u)
        if k_is_int and n_is_int and n_u >= 0 and k_u > n_u:
            any_k_gt_n = True

        uid_ok = _is_valid_identifier(uid)
        if not uid_ok:
            _add_err("INVALID_UNIT_ID" if is_list_entry else "INVALID_UNIT_DICT_ENTRY")
        elif uid in seen_uids:
            _add_err("DUPLICATE_UNIT_ID")
            uid_ok = False
        else:
            seen_uids.add(uid)

        counts_ok = bool(k_is_int and n_is_int and n_u > 0 and 0 <= k_u <= n_u)
        if not counts_ok:
            _add_err("INVALID_UNIT_COUNT_DOMAIN")
        elif uid_ok:
            sum_valid_k += int(k_u)
            sum_valid_n += int(n_u)
            unit_map[str(uid)] = (int(k_u), int(n_u))

    if not (_is_strict_int(expected_units_n) and expected_units_n >= MIN_INDEPENDENT_BIOLOGICAL_UNITS_N):
        _add_err("INSUFFICIENT_INDEPENDENT_BIOLOGICAL_UNITS")
    elif total_rows != expected_units_n or len(unit_map) != expected_units_n:
        if not errors:
            _add_err("UNIT_COUNT_LENGTH_MISMATCH")

    if not (_is_strict_int(expected_k) and _is_strict_int(expected_n) and expected_n >= 1 and 0 <= expected_k <= expected_n):
        _add_err("INVALID_AGGREGATE_COUNTS")
    elif not errors and (sum_valid_n != expected_n or sum_valid_k != expected_k):
        _add_err("UNIT_SUM_MISMATCH")

    reconciled_ok = len(errors) == 0
    return {
        "reconciled_ok": reconciled_ok,
        "any_pos_k": any_pos_k,
        "any_k_gt_n": any_k_gt_n,
        "sum_interp_k": sum_interp_k,
        "sum_interp_n": sum_interp_n,
        "interpretable_rows_n": interpretable_rows_n,
        "reason_code": "OK" if reconciled_ok else errors[0],
        "all_errors": errors,
        "unit_map": unit_map,
    }


def _validate_per_unit_counts(
    raw_partition: Any,
    *,
    expected_units_n: int | None,
    expected_k: int | None,
    expected_n: int | None,
) -> Tuple[bool, bool, str]:
    """Backwards-compatible 3-tuple wrapper around `_inspect_per_unit_counts` (zero early returns)."""
    info = _inspect_per_unit_counts(
        raw_partition,
        expected_units_n=expected_units_n,
        expected_k=expected_k,
        expected_n=expected_n,
    )
    return bool(info["reconciled_ok"]), bool(info["any_pos_k"]), str(info["reason_code"])


def _scan_all_submitted_per_unit_counts_adverse(
    payload: Any,
    *,
    raw_deff_dec: Decimal | None,
    hard_stops: List[str],
    required_kill_regimes: Tuple[str, ...] = (),
) -> Dict[str, Any]:
    """
    R13-B1 Dedicated pre-schema adverse `per_unit_counts` scanner executed BEFORE any sampling-class,
    required-vs-supplemental, or row-ID schema early return:
      - Scans EVERY arm (required AND supplemental stress regimes, pathogen arms, latent ddPCR arms
        and targets, CD46/CD55 addenda, extra lineages/strains/targets, plus a whole-payload sweep)
        in BOTH single-cell AND multi-well modes (and even when `clustering_and_independence_spec`
        is missing or invalid!).
      - On post-AP1903 viral-positive escape (`infected_viral_pos_72h` / `post_ap1903_*viral_pos*`):
        ANY interpretable unit dict row with `k >= 1` immediately records deterministic biological
        `FAIL_HARD_STOP` (`HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE`).
      - On any zero-tolerance viral persistence estimand (Gate 0V-B, latent ddPCR, CD46, CD55):
        ANY interpretable unit dict row with `k >= 1` immediately records deterministic biological
        `FAIL_HARD_STOP` (`HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE`).
      - On any `per_unit_counts` estimand with `k_u > n_u` OR any adverse-event estimand where
        interpretable unit rows sum to `k > declared aggregate k` (e.g., unit reports positive
        survivor while aggregate claims `0`) OR where AP1903 24h/72h unit counts conclusively breach
        the kill floor at `deff == 1.0`, immediately records deterministic `FAIL_HARD_STOP`
        (`HARD_STOP_ADVERSE_PER_UNIT_CONTRADICTS_AGGREGATE_OR_BREACHES_KILL_FLOOR`).
      - Reports `any_per_unit_counts_present` so single-cell mode (`INDEPENDENT_SINGLE_CELL_OR_LIMITING_DILUTION_UNIT`)
        can fail closed on ANY submitted `per_unit_counts` (`HOLD_UNEXPECTED_PER_UNIT_COUNTS_IN_SINGLE_CELL_MODE`).
    """
    any_puc_present = False
    visited_containers: set[int] = set()

    def _append_hs(tok: str) -> None:
        if tok not in hard_stops:
            hard_stops.append(tok)