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…

                        ("uninfected_ctrl_per_unit_counts", "uninfected_ctrl_fp_k", "uninfected_ctrl_scored_n"),
                        ("spike_calibrant_per_unit_counts", "spike_calibrant_detected_k", "spike_calibrant_total_n"),
                        (
                            "fragile_infected_spike_per_unit_counts",
                            "fragile_infected_spike_detected_k",
                            "fragile_infected_spike_total_n",
                        ),
                    ):
                        if aux_puc_key in le:
                            any_puc_present = True
                            visited_containers.add(id(le))
                            _check_part(
                                le.get(aux_puc_key),
                                expected_k=le.get(aux_k_key),
                                expected_n=le.get(aux_n_key),
                                zero_tol=False,
                                check_agg_exceed=False,
                            )

    # 3. CD46 addendum (ALL submitted virus blocks, required or supplemental!)
    cd46 = payload.get("cd46_tropic_viral_addendum")
    if isinstance(cd46, dict):
        for vid, vb in cd46.items():
            if isinstance(vb, dict) and "per_unit_counts" in vb:
                any_puc_present = True
                visited_containers.add(id(vb))
                v_tag = str(vid).upper()
                _check_part(
                    vb.get("per_unit_counts"),
                    expected_k=vb.get("day28_5lineage_ddpcr_confirmed_k"),
                    expected_n=vb.get("day28_5lineage_cells_screened_per_lineage_min_n"),
                    zero_tol=True,
                    zt_tokens=(
                        "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                        f"FAIL_HARD_STOP_CD46_ADDENDUM_CONFIRMED_PERSISTENCE_{v_tag}",
                    ),
                    check_agg_exceed=True,
                )

    # 4. CD55 echovirus addendum (top-level AND ALL strains x ALL lineages, required or supplemental!)
    cd55 = payload.get("cd55_tropic_echovirus_addendum")
    if isinstance(cd55, dict):
        if "per_unit_counts" in cd55:
            any_puc_present = True
            visited_containers.add(id(cd55))
            _check_part(
                cd55.get("per_unit_counts"),
                expected_k=cd55.get("echovirus_persistence_confirmed_k"),
                expected_n=cd55.get("echovirus_cells_screened_per_lineage_min_n"),
                zero_tol=True,
                zt_tokens=(
                    "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                    "FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED",
                ),
                check_agg_exceed=True,
            )
        sr = cd55.get("strain_results")
        if isinstance(sr, dict):
            for sid, sb in sr.items():
                if not isinstance(sb, dict):
                    continue
                s_tag = str(sid).upper()
                if "per_unit_counts" in sb:
                    any_puc_present = True
                    visited_containers.add(id(sb))
                    _check_part(
                        sb.get("per_unit_counts"),
                        expected_k=0,
                        expected_n=None,
                        zero_tol=True,
                        zt_tokens=(
                            "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                            f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_K_UNIT_POS",
                        ),
                        check_agg_exceed=True,
                    )
                lm = sb.get("day28_persistence_by_lineage")
                if isinstance(lm, dict):
                    for lin_name, le in lm.items():
                        if isinstance(le, dict) and "per_unit_counts" in le:
                            any_puc_present = True
                            visited_containers.add(id(le))
                            l_tag = str(lin_name).upper()
                            _check_part(
                                le.get("per_unit_counts"),
                                expected_k=le.get("confirmed_k"),
                                expected_n=le.get("cells_screened_n"),
                                zero_tol=True,
                                zt_tokens=(
                                    "HARD_STOP_ADVERSE_PER_UNIT_VIRAL_PERSISTENCE",
                                    f"FAIL_HARD_STOP_CD55_ECHOVIRUS_PERSISTENCE_DETECTED_{s_tag}_{l_tag}_K_UNIT_POS",
                                ),
                                check_agg_exceed=True,
                            )

    # 5. Iterative whole-payload sweep for any uncovered `per_unit_counts` key anywhere in payload
    stack: List[Any] = [payload]
    seen_walk: set[int] = set()
    while stack:
        cur = stack.pop()
        cid = id(cur)
        if cid in seen_walk:
            continue
        seen_walk.add(cid)
        if isinstance(cur, dict):
            if cid not in visited_containers:
                for cur_k, raw_unc in cur.items():
                    if cur_k == "per_unit_counts" or (isinstance(cur_k, str) and cur_k.endswith("_per_unit_counts")):
                        any_puc_present = True
                        if isinstance(raw_unc, dict):
                            for uk, uv in raw_unc.items():
                                uk_low = str(uk).lower()
                                is_v = ("viral" in uk_low) or ("escape" in uk_low)
                                _check_part(
                                    uv,
                                    expected_k=0 if is_v else None,
                                    expected_n=None,
                                    zero_tol=is_v,
                                    zt_tokens=("HARD_STOP_ADVERSE_PER_UNIT_POST_AP1903_VIRAL_ESCAPE",) if is_v else (),
                                    check_agg_exceed=is_v,
                                )
                        else:
                            _check_part(raw_unc, expected_k=None, expected_n=None, zero_tol=False, check_agg_exceed=False)
            for v in cur.values():
                if isinstance(v, (dict, list)):
                    stack.append(v)
        elif isinstance(cur, list):
            for item in cur:
                if isinstance(item, (dict, list)):
                    stack.append(item)

    return {"any_per_unit_counts_present": any_puc_present}


def _fraction_to_outward_dec(y_frac: Fraction, sig_digits: int) -> Tuple[Decimal, Decimal]:
    """
    Exact integer-long-division outward bracket [y_lo, y_hi] for rational y_frac > 0
    with at least sig_digits significant digits at ANY exponent scale (including 10^-200).
    Guarantees: 0 < y_lo <= y_frac <= y_hi with zero ambient Decimal rounding.
    """
    if y_frac == 0:
        return Decimal(0), Decimal(0)
    if y_frac < 0:
        raise ValueError("Require y_frac >= 0")
    p_num = y_frac.numerator
    q_den = y_frac.denominator
    # Choose shift so p_num * 10^shift / q_den >= 10^(sig_digits - 1)
    shift = max(0, len(str(q_den)) - len(str(p_num)) + 1) + sig_digits
    q_int, r_int = divmod(p_num * (10 ** shift), q_den)
    with _clean_dec_ctx(max(sig_digits + 20, len(str(q_int)) + 10), ROUND_FLOOR):
        y_lo = Decimal(q_int).scaleb(-shift)
    with _clean_dec_ctx(max(sig_digits + 20, len(str(q_int + 1)) + 10), ROUND_CEILING):
        y_hi = Decimal(q_int + (1 if r_int else 0)).scaleb(-shift)
    return y_lo, y_hi


@lru_cache(maxsize=4096)
def _exact_ln_interval(a: Decimal, prec: int = 120) -> Tuple[Decimal, Decimal]:
    """
    Provably outward-directed interval [lo, hi] enclosing ln(a) for ALL finite Decimal a in (0, 1),
    using exact Fraction argument reduction + elementary +, -, *, / directed rounding
    (ZERO Decimal.ln() calls; handles arbitrary-digit inputs such as 0.125 - 1e-180,
    0.5, 0.5 +/- 1e-180, and 1 - 1e-180 with zero inward violations!).

    Argument reduction (exact in Q):
      Multiply x = Fraction(a) by 2^m until x in [1/2, 1).
      Then ln(a) = -2*atanh((1 - x)/(1 + x)) - m * 2*atanh(1/3).
    Recombination (strictly outward):
      m_ln2_hi = CEIL(m * ln2_hi), m_ln2_lo = FLOOR(m * ln2_lo)
      ln_a_lo  = FLOOR(-neg_lnb_hi - m_ln2_hi)
      ln_a_hi  = CEIL(-neg_lnb_lo - m_ln2_lo)
    """
    if not isinstance(a, Decimal) or not a.is_finite() or not (Decimal(0) < a < Decimal(1)):
        raise ValueError("a must be a finite Decimal strictly in (0, 1)")

    wprec = max(prec + 35, 145)

    def _two_atanh_frac_bounds(y_frac: Fraction) -> Tuple[Decimal, Decimal]:
        if y_frac == 0:
            return Decimal(0), Decimal(0)
        y_lo_raw, y_hi_raw = _fraction_to_outward_dec(y_frac, wprec)
        # Since 0 < y_frac <= 1/3, (1/9)^k < 10^-wprec after ~1.1 * wprec terms;
        # for tiny y_frac (<= 1e-6), 40 terms already gives remainder < 10^-480.
        terms = 40 if y_frac <= Fraction(1, 1_000_000) else max(165, int(wprec * 1.15) + 20)

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            y_lo = +y_lo_raw
            y2_lo = y_lo * y_lo
            p_lo = y_lo
            s_lo = Decimal(0)
            for k in range(terms):
                s_lo = s_lo + (p_lo / Decimal(2 * k + 1))
                p_lo = p_lo * y2_lo
            lo = Decimal(2) * s_lo

        with _clean_dec_ctx(wprec, ROUND_CEILING):
            y_hi = +y_hi_raw
            y2_hi = y_hi * y_hi
            p_hi = y_hi
            s_hi = Decimal(0)
            for k in range(terms):
                s_hi = s_hi + (p_hi / Decimal(2 * k + 1))
                p_hi = p_hi * y2_hi
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            one_minus_y2 = Decimal(1) - y2_hi
            denom_tail = Decimal(2 * terms + 1) * one_minus_y2
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            tail = (Decimal(2) * p_hi) / denom_tail
            hi = Decimal(2) * s_hi + tail
        return lo, hi

    x_frac = Fraction(a)
    m = 0
    while x_frac < Fraction(1, 2):
        x_frac *= 2
        m += 1
    y_b = (Fraction(1) - x_frac) / (Fraction(1) + x_frac)

    ln2_lo, ln2_hi = _two_atanh_frac_bounds(Fraction(1, 3)) if m > 0 else (Decimal(0), Decimal(0))
    neg_lnb_lo, neg_lnb_hi = _two_atanh_frac_bounds(y_b)

    # Critical outward recombination:
    # For LOWER bound on (-neg_lnb - m*ln2), we MUST round m*ln2_hi UP (ROUND_CEILING) before subtracting!
    # For UPPER bound on (-neg_lnb - m*ln2), we MUST round m*ln2_lo DOWN (ROUND_FLOOR) before subtracting!
    m_dec = Decimal(m)
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        m_ln2_hi = m_dec * ln2_hi
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        ln_a_lo_w = neg_lnb_hi.copy_negate() - m_ln2_hi
    with _clean_dec_ctx(prec, ROUND_FLOOR):
        ln_a_lo = +ln_a_lo_w

    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        m_ln2_lo = m_dec * ln2_lo
    with _clean_dec_ctx(wprec, ROUND_CEILING):
        ln_a_hi_w = neg_lnb_lo.copy_negate() - m_ln2_lo
    with _clean_dec_ctx(prec, ROUND_CEILING):
        ln_a_hi = +ln_a_hi_w

    return ln_a_lo, ln_a_hi


def _exact_exp_neg_interval(z_lo: Decimal, z_hi: Decimal, prec: int = 120) -> Tuple[Decimal, Decimal]:
    """
    Provably outward-directed interval [lo, hi] enclosing exp(-z) for z in [z_lo, z_hi] > 0,
    using ONLY elementary +, -, *, / with directed rounding (ZERO Decimal.exp() calls!).
    """
    if z_lo <= Decimal(0) or z_hi < z_lo:
        raise ValueError("Require 0 < z_lo <= z_hi")