OpenIslet

scripts/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py

Provisional IIP-0058 / DEC-139 / GATE-37 / GY-036 (Round-14 Blueprint Alignment; staged in iip0058/):

script Release v0.8.0 gen-eb955f8266035aba 837 KB · 62 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_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py · SHA-256: 33439d619c00fcc3…

    )
    t_ev = caller_ev_res["resolved_val"]
    t_n = caller_n_res["resolved_val"]
    t_wk = caller_wk_res["resolved_wk"]
    t_host = caller_host_res["resolved_val"]
    t_lot = payload.get("teratoma_lot_id")
    t_dose = caller_dose_res["resolved_val"]
    per_animals = payload.get("per_animal_exposures")
    u95_pct: Optional[float] = None

    if _is_strict_int(t_ev) and _is_strict_int(t_n) and 0 < t_n <= MAX_CLONOGENIC_CELLS and t_ev >= 0:
        if t_ev > t_n:
            failures.append("IMPOSSIBLE_TERATOMA_EVENTS_GT_N")
    if t_lot is None:
        holds.append("MISSING_teratoma_lot_id")
    elif not _is_nonempty_str(t_lot):
        failures.append("INVALID_teratoma_lot_id")
    elif valid_lot is not None and t_lot != valid_lot:
        failures.append("FAIL_TERATOMA_LOT_ID_MISMATCH")

    def _audit_gp2_animal_list(
        entries: Any,
        *,
        expected_n: Any,
        expected_ev: Any,
        expected_lot: Optional[str],
        prefix: str,
    ) -> tuple[Optional[int], int, int, int, dict[str, dict[str, Any]], set[str], dict[str, str], bool, bool]:
        """Validate every animal in a GP2 per-animal roster under strict ASCII canonical ID grammar
        & separator-first -> digit-padding-second 1-to-1 canonical equivalence (Audit R7-04 / R8-07 / R9-05 / R10-06 / R10-07),
        deduplicate by canonical unique animal, audit dose>=1e7, lot, host, followup_weeks>=26, and strict
        bool tumor_detected, build a canonical-ID-keyed normalized record map (order-insensitive!), and
        report roster integrity-failure & missing-field flags separately."""
        r_failures: list[str] = []
        r_holds: list[str] = []
        if not isinstance(entries, list) or len(entries) == 0:
            failures.append(f"INVALID_{prefix}per_animal_exposures")
            return None, 0, 1, 0, {}, set(), {}, True, True
        if _is_strict_int(expected_n) and expected_n > 0 and len(entries) != expected_n:
            r_failures.append(f"FAIL_{prefix}GP2_PER_ANIMAL_EXPOSURE_COUNT_MISMATCH")
        if len(entries) < 12:
            r_failures.append(f"FAIL_{prefix}GP2_PER_ANIMAL_EXPOSURES_LT_12")
        seen_collapsed_ids: set[str] = set()
        seen_compact_ids: set[str] = set()
        raw_by_canon: dict[str, str] = {}
        positive_animals: set[str] = set()
        animal_records: dict[str, dict[str, Any]] = {}
        raw_confirmed_tumors = 0
        unknown_outcomes = 0
        doses: list[int] = []

        def _mark_arch_incomplete_field(field_name: str) -> None:
            if prefix.startswith("ARCHIVE_"):
                code = f"HOLD_INCOMPLETE_ARCHIVED_PER_ANIMAL_ROSTER_FIELD:{field_name}"
                if code not in r_holds:
                    r_holds.append(code)

        for entry in entries:
            if not isinstance(entry, dict):
                r_failures.append(f"INVALID_{prefix}per_animal_exposure_entry")
                unknown_outcomes += 1
                continue
            aid = entry.get("animal_id")
            cmp_aid = ""
            is_new_animal = False
            if not isinstance(aid, str) or not aid:
                r_failures.append(f"INVALID_{prefix}GP2_ANIMAL_ID")
            else:
                if not _is_canonical_id(aid):
                    r_failures.append(f"FAIL_{prefix}GP2_NONCANONICAL_ANIMAL_ID")
                col_aid, cmp_aid = _canonical_id_keys(aid)
                if not cmp_aid:
                    r_failures.append(f"INVALID_{prefix}GP2_ANIMAL_ID")
                elif col_aid in seen_collapsed_ids or cmp_aid in seen_compact_ids:
                    if cmp_aid in raw_by_canon and raw_by_canon[cmp_aid] != aid:
                        if "FAIL_NONUNIQUE_CANONICAL_EQUIVALENCE_ID" not in r_failures:
                            r_failures.append("FAIL_NONUNIQUE_CANONICAL_EQUIVALENCE_ID")
                    r_failures.append(f"FAIL_{prefix}GP2_DUPLICATE_ANIMAL_ID")
                else:
                    seen_collapsed_ids.add(col_aid)
                    seen_compact_ids.add(cmp_aid)
                    raw_by_canon[cmp_aid] = aid
                    is_new_animal = True

            alot = entry.get("lot_id")
            if alot is None:
                r_holds.append(f"HOLD_MISSING_{prefix}GP2_ANIMAL_LOT_ID")
                _mark_arch_incomplete_field("lot_id")
            elif not _is_nonempty_str(alot):
                r_failures.append(f"INVALID_{prefix}GP2_ANIMAL_LOT_ID")
            elif expected_lot is not None and alot != expected_lot:
                r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_LOT_ID_MISMATCH")

            # Challenge dose >= 1e7 (strict int), conflict-checked across aliases; missing/None -> HOLD
            dose_vals: list[int] = []
            dose_present = False
            dose_has_explicit_none = False
            for dk in ENSC_ROW_DOSE_ALIASES:
                if dk in entry:
                    if entry[dk] is None:
                        dose_has_explicit_none = True
                    else:
                        dose_present = True
                        dv = entry[dk]
                        if not _is_strict_int(dv) or dv <= 0 or dv > MAX_CLONOGENIC_CELLS:
                            r_failures.append(f"INVALID_{prefix}GP2_ANIMAL_DOSE_CELLS")
                        else:
                            dose_vals.append(dv)
                            if dv < 10_000_000:
                                r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_EXPOSURE_DOSE_LT_1E7_CELLS")
                            else:
                                doses.append(dv)
            if not dose_present or dose_has_explicit_none:
                r_holds.append(f"HOLD_MISSING_{prefix}GP2_ANIMAL_DOSE_CELLS")
                _mark_arch_incomplete_field("challenge_dose_cells")
            if len(dose_vals) >= 2 and any(v != dose_vals[0] for v in dose_vals[1:]):
                r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_DOSE_ALIAS_CONFLICT")

            host_vals: list[str] = []
            for hk in ENSC_ROW_HOST_ALIASES:
                if hk in entry and entry[hk] is not None:
                    hv = entry[hk]
                    if not _is_canonical_id(hv) or hv != "SCID-Beige":
                        r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_WRONG_HOST_STRAIN")
                    else:
                        host_vals.append(hv)
            if len(host_vals) >= 2 and len(set(host_vals)) > 1:
                r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_HOST_STRAIN_ALIAS_CONFLICT")

            wk_vals: list[float] = []
            wk_present = False
            wk_has_explicit_none = False
            for wk_k in ENSC_ROW_FOLLOWUP_ALIASES:
                if wk_k in entry:
                    if entry[wk_k] is None:
                        wk_has_explicit_none = True
                    else:
                        wk_present = True
                        wv = entry[wk_k]
                        if not _is_num(wv) or float(wv) <= 0.0:
                            r_failures.append(f"INVALID_{prefix}GP2_ANIMAL_FOLLOWUP_WEEKS")
                        else:
                            wvf = float(wv)
                            wk_vals.append(wvf)
                            if wvf < 26.0:
                                r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_FOLLOWUP_LT_26WK")
            if not wk_present or wk_has_explicit_none:
                r_holds.append(f"HOLD_MISSING_{prefix}GP2_ANIMAL_FOLLOWUP_WEEKS")
                _mark_arch_incomplete_field("followup_weeks")
            if len(wk_vals) >= 2 and any(abs(v - wk_vals[0]) > 1e-12 for v in wk_vals[1:]):
                r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_FOLLOWUP_ALIAS_CONFLICT")

            # Mandatory per-animal tumor_detected (conflict-checked against all outcome aliases if co-supplied)
            outcome_keys_present = [ok for ok in ENSC_ROW_OUTCOME_ALIASES if ok in entry]
            row_outcome: Optional[bool] = None
            if not outcome_keys_present:
                unknown_outcomes += 1
                r_holds.append(f"HOLD_{prefix}GP2_ANIMAL_TUMOR_OUTCOME_MISSING_OR_UNKNOWN")
                _mark_arch_incomplete_field("teratoma_detected")
            else:
                row_pos = False
                row_bools: list[bool] = []
                row_has_none = False
                row_has_invalid = False
                for ok in outcome_keys_present:
                    ov = entry[ok]
                    if ov is True:
                        row_pos = True
                        row_bools.append(True)
                    elif ov is False:
                        row_bools.append(False)
                    elif ov is None:
                        row_has_none = True
                    else:
                        row_has_invalid = True
                if row_pos:
                    raw_confirmed_tumors += 1
                    row_outcome = True
                    if cmp_aid:
                        positive_animals.add(cmp_aid)
                    r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_TUMOR_DETECTED")
                if row_has_none:
                    unknown_outcomes += 1
                    r_holds.append(f"HOLD_{prefix}GP2_ANIMAL_TUMOR_OUTCOME_UNKNOWN")
                    _mark_arch_incomplete_field("teratoma_detected")
                if row_has_invalid:
                    r_failures.append(f"INVALID_{prefix}GP2_ANIMAL_TUMOR_DETECTED")
                    unknown_outcomes += 1
                if len(set(row_bools)) > 1:
                    r_failures.append(f"FAIL_{prefix}GP2_ANIMAL_TUMOR_OUTCOME_FIELD_CONTRADICTION")
                if not row_pos and not row_has_invalid and False in row_bools:
                    row_outcome = False

            if cmp_aid:
                if is_new_animal:
                    animal_records[cmp_aid] = {
                        "raw_id": aid,
                        "lot_id": alot if _is_nonempty_str(alot) else None,
                        "challenge_dose_cells": float(dose_vals[0]) if dose_vals else None,
                        "followup_weeks": wk_vals[0] if wk_vals else None,
                        "teratoma_detected": row_outcome,
                    }
                elif row_outcome is True and cmp_aid in animal_records:
                    animal_records[cmp_aid]["teratoma_detected"] = True

            _audit_canonical_identifier_fields(entry, label=f"{prefix}GP2_ROW", failures=r_failures, skip_keys=frozenset({"animal_id"}))

        distinct_canonical_animals = len(seen_compact_ids)
        derived_tumors = len(positive_animals) if positive_animals else raw_confirmed_tumors
        if distinct_canonical_animals < 12:
            r_failures.append(f"FAIL_{prefix}GP2_DISTINCT_CANONICAL_ANIMALS_LT_12")
        if _is_strict_int(expected_n) and expected_n > 0 and distinct_canonical_animals != expected_n:
            r_failures.append(f"FAIL_{prefix}GP2_DISTINCT_CANONICAL_ANIMAL_COUNT_MISMATCH")

        # Always reconcile confirmed tumors even if other animals have unknown outcomes (Review #8 / Audit R4-06)!
        if _is_strict_int(expected_ev) and expected_ev >= 0:
            if max(derived_tumors, raw_confirmed_tumors) > expected_ev:
                r_failures.append(f"FAIL_{prefix}GP2_TERATOMA_EVENT_COUNT_CONTRADICTS_CONFIRMED_TUMORS")
            elif unknown_outcomes == 0 and derived_tumors != expected_ev:
                r_failures.append(f"FAIL_{prefix}GP2_TERATOMA_EVENT_COUNT_MISMATCH")

        for rf in r_failures:
            if rf == "FAIL_NONUNIQUE_CANONICAL_EQUIVALENCE_ID" and rf in failures:
                continue
            failures.append(rf)
        for rh in r_holds:
            if rh.startswith("HOLD_INCOMPLETE_ARCHIVED_PER_ANIMAL_ROSTER_FIELD:") and rh in holds:
                continue
            holds.append(rh)
        pure_positive_codes = {f"FAIL_{prefix}GP2_ANIMAL_TUMOR_DETECTED"}
        has_integrity_failure = any(rf not in pure_positive_codes for rf in r_failures)
        has_missing_fields = bool(r_holds)
        return (
            (min(doses) if doses else None),
            derived_tumors,
            unknown_outcomes,
            distinct_canonical_animals,
            animal_records,
            seen_compact_ids,
            raw_by_canon,
            has_integrity_failure,
            has_missing_fields,
        )

    def _reconcile_gp2_animal_records(
        rec_a: Mapping[str, Mapping[str, Any]],
        rec_b: Mapping[str, Mapping[str, Any]],
        *,
        mismatch_code: str,
        alias_conflict_code: Optional[str] = None,