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…

        step = 1
        while _adjudicate_zero_event_vs_cap(hi_n, target_t_cap, alpha, target_eta, prec=prec) != "LE":
            lo_n = hi_n + 1
            hi_n = hi_n + step
            step *= 2

        # Binary search for exact minimal n_star in [lo_n, hi_n]
        while lo_n < hi_n:
            mid = (lo_n + hi_n) // 2
            adj_mid = _adjudicate_zero_event_vs_cap(mid, target_t_cap, alpha, target_eta, prec=prec)
            if adj_mid == "LE":
                hi_n = mid
            elif adj_mid == "GT":
                lo_n = mid + 1
            else:
                # Conservative: cannot prove mid clears, advance linearly only if needed
                lo_n = mid + 1

        n_cand = lo_n
        adj_n = _adjudicate_zero_event_vs_cap(n_cand, target_t_cap, alpha, target_eta, prec=prec)
        if n_cand == 1:
            adj_prev_gt = True
        else:
            adj_prev = _adjudicate_zero_event_vs_cap(n_cand - 1, target_t_cap, alpha, target_eta, prec=prec)
            adj_prev_gt = adj_prev == "GT"
        return n_cand, (adj_n == "LE"), adj_prev_gt

    with _clean_dec_ctx(max(prec + 45, 145), ROUND_HALF_EVEN):
        unclamped_ref: int | None = None
        if cap_frac == Decimal(1):
            # Clamped model: u(n) = min(1, (1 - alpha^(1/n))/eta_lower) <= 1 holds for ALL n >= 1 -> exact n = 1!
            n_star = 1
            at_n_verified_le = True
            prev_verified_gt = True
            if eta_lower < Decimal(1):
                # Record unclamped comparison (solving (1 - eta_lower)^n <= alpha) for diagnostic transparency
                unclamped_n, _, _ = _solve_unclamped_min_n(eta_lower, Decimal(1))
                unclamped_ref = unclamped_n
        else:
            n_star, at_n_verified_le, prev_verified_gt = _solve_unclamped_min_n(cap_frac, eta_lower)

        at_n = sound_zero_event_clopper_pearson_upper(n_star, alpha, eta_lower, prec=prec)
        at_n_minus_1 = (
            sound_zero_event_clopper_pearson_upper(n_star - 1, alpha, eta_lower, prec=prec)
            if n_star > 1
            else None
        )
        out_dict: Dict[str, Any] = {
            "cap_frac": str(cap_frac),
            "alpha": str(alpha),
            "eta_lower": str(eta_lower),
            "min_n_pass": n_star,
            "operational_n_rounded_up_500": ((n_star + 499) // 500) * 500,
            "u_at_min_n_upper_80d": at_n["u_thinned_upper_80d"],
            "u_at_min_n_pct": _dec_to_float_pct(at_n["u_thinned_upper_dec"], 8),
            "fail_n_minus_1": (n_star - 1) if n_star > 1 else None,
            "u_at_n_minus_1_pct": (
                _dec_to_float_pct(at_n_minus_1["u_thinned_upper_dec"], 8)
                if at_n_minus_1 is not None
                else None
            ),
            "boundary_strictly_verified": bool(at_n_verified_le and prev_verified_gt),
        }
        if unclamped_ref is not None:
            out_dict["unclamped_min_n_reference"] = unclamped_ref
        return out_dict


@lru_cache(maxsize=4096)
def exact_clopper_pearson_lower_calibrant(
    r_k: int,
    r_n: int,
    alpha_cal: Decimal,
    prec: int = 60,
) -> Decimal:
    """
    Provably conservative (<= true) one-sided Clopper-Pearson lower bound at level (1 - alpha_cal)
    for r_k successes out of r_n trials (100% isolated from ambient Decimal exponent/trap settings).
    """
    if not (_is_strict_int(r_k) and _is_strict_int(r_n) and 0 <= r_k <= r_n and r_n >= 1):
        raise ValueError("Require integer 0 <= r_k <= r_n and r_n >= 1")
    wprec = max(prec + 25, 64)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        if r_k == 0:
            return Decimal(0)
        if r_k == r_n:
            eta_lo, _ = _alpha_root_interval(alpha_cal, r_n, prec=prec)
            return eta_lo

        m = r_n - r_k
        lo_q = Decimal(0)
        hi_q = Decimal(1)
        iters = min(240, int(prec * 3.4) + 12)
        for _ in range(iters):
            with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
                mid = (lo_q + hi_q) / Decimal(2)
                if mid <= lo_q or mid >= hi_q:
                    break
            tail_lo, tail_hi = _binomial_tail_lower_eq_interval(m, r_n, mid, prec=wprec)
            if tail_lo > alpha_cal:
                lo_q = mid
            elif tail_hi <= alpha_cal:
                hi_q = mid
            else:
                break
        with _clean_dec_ctx(prec, ROUND_FLOOR):
            return max(Decimal(0), Decimal(1) - hi_q)


@lru_cache(maxsize=4096)
def exact_clopper_pearson_upper_general(
    k: int,
    n: int,
    alpha: Decimal,
    prec: int = 60,
) -> Decimal:
    """
    Provably conservative (>= true) one-sided Clopper-Pearson upper bound U(k, n; alpha)
    solving P(Bin(n, p) <= k) = alpha via outward-invariant bisection (100% isolated from
    ambient Decimal exponent range and Inexact traps).
    """
    if not (_is_strict_int(k) and _is_strict_int(n) and 0 <= k <= n and n >= 1):
        raise ValueError("Require integer 0 <= k <= n and n >= 1")
    wprec = max(prec + 25, 64)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        if k == n:
            return Decimal(1)
        if k == 0:
            return sound_zero_event_clopper_pearson_upper(n, alpha, Decimal(1), prec=prec)["u_thinned_upper_dec"]

        lo_p = Decimal(0)
        hi_p = Decimal(1)
        iters = min(240, int(prec * 3.4) + 12)
        for _ in range(iters):
            with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
                mid = (lo_p + hi_p) / Decimal(2)
                if mid <= lo_p or mid >= hi_p:
                    break
            tail_lo, tail_hi = _binomial_tail_lower_eq_interval(k, n, mid, prec=wprec)
            if tail_lo > alpha:
                lo_p = mid
            elif tail_hi <= alpha:
                hi_p = mid
            else:
                break
        with _clean_dec_ctx(prec, ROUND_CEILING):
            return min(Decimal(1), +hi_p)


def _clear_math_caches() -> None:
    _exact_ln_interval.cache_clear()
    _sound_zero_event_core.cache_clear()
    exact_clopper_pearson_lower_calibrant.cache_clear()
    exact_clopper_pearson_upper_general.cache_clear()
    exact_student_t_one_sided_95.cache_clear()


def _exact_floor_div_by_decimal(n: int, denom: Decimal) -> int:
    """
    R16-M2 Exact arbitrary-precision integer floor `floor(n / denom)` via exact rational
    arithmetic (`Fraction(n) // Fraction(denom)`). Eliminates finite-precision Decimal truncation
    even for huge admitted synthetic counts (e.g. `n = 10**80 + 1, deff = 1 -> 10**80 + 1`).
    """
    if not _is_strict_int(n) or n < 0:
        raise ValueError("n must be a non-negative integer")
    if not isinstance(denom, Decimal) or not denom.is_finite() or denom <= Decimal(0):
        raise ValueError("denom must be a finite positive Decimal")
    if n == 0:
        return 0
    if denom == Decimal(1):
        return int(n)
    # Guard against astronomically large positive exponents where denom > n trivially implies floor = 0
    if denom.adjusted() > len(str(n)) + 2:
        return 0
    return int(Fraction(n) // Fraction(denom))


def exact_component_probability_ratio_upper(
    k_treated: int,
    n_treated: int,
    alpha_treated: Decimal,
    denominator_lower_factors: Tuple[Decimal, ...],
    *,
    deff: Decimal = Decimal("1.0"),
    prec: int = 80,
) -> Dict[str, Any]:
    """
    R06-B2 + R08-M1 + R09-B2 Exact conservative component-probability ratio one-sided upper bound
    over the true mathematical ratio domain `R = p_treated / prod_i p_den_i in [0, +infinity)`:
      1. Bound the treated event probability on the actual treated effective sampling
         denominator `n_treated_eff = floor(n_treated / deff)` via outward `ROUND_CEILING`
         Clopper-Pearson `u_treated = U(k_treated, n_treated_eff; alpha_treated)`.
      2. Multiply the outward `ROUND_FLOOR` denominator component lower bounds
         `den_lower_prod = floor(prod(denominator_lower_factors))`.
      3. Form the unclamped conservative directional one-sided upper ratio limit
         `u_ratio = ceil(u_treated / den_lower_prod)` on `[0, +infinity)` (`+Infinity` when
         `den_lower_prod == 0` since `u_treated > 0`). NEVER clamped to `1.0`!
    Guarantees directional one-sided upper confidence `>= 1 - (alpha_treated + sum(alpha_den_i))`
    across the numerator and denominator component bounds via Bonferroni union bound (not a
    simultaneous two-sided interval at that same unsplit alpha), with ZERO adjusted-denominator
    Clopper-Pearson direction-of-coverage inversion and ZERO domain-clipping inversion.
    """
    if not (_is_strict_int(k_treated) and _is_strict_int(n_treated) and 0 <= k_treated <= n_treated and n_treated >= 1):
        raise ValueError("Require integer 0 <= k_treated <= n_treated and n_treated >= 1")
    if not isinstance(alpha_treated, Decimal) or not alpha_treated.is_finite() or not (Decimal(0) < alpha_treated < Decimal(1)):
        raise ValueError("alpha_treated must be a finite Decimal strictly in (0, 1)")
    if not isinstance(deff, Decimal) or not deff.is_finite() or deff < Decimal("1.0"):
        raise ValueError("deff must be a finite Decimal >= 1.0")
    if not denominator_lower_factors:
        raise ValueError("Require at least one denominator lower-bound factor")

    wprec = max(prec, 80)
    n_treated_eff = _exact_floor_div_by_decimal(n_treated, deff)
    with _clean_dec_ctx(wprec, ROUND_FLOOR):
        den_lower_prod = Decimal(1)
        for fac in denominator_lower_factors:
            if not isinstance(fac, Decimal) or not fac.is_finite() or fac < Decimal(0) or fac > Decimal(1):
                raise ValueError("Each denominator factor must be a finite Decimal in [0, 1]")
            den_lower_prod = den_lower_prod * fac

    if n_treated_eff < 1:
        k_treated_eff_upper: int | None = 0 if k_treated == 0 else None
        u_treated = Decimal(1)
    else:
        # R10-B3 Outward-upward effective numerator count:
        #   k_eff_upper = ceil(k_treated * n_treated_eff / n_treated)
        # guarantees k_eff_upper / n_treated_eff >= k_treated / n_treated unconditionally
        # (and equals k_treated when deff == 1.0, and equals 0 when k_treated == 0!).
        k_treated_eff_upper = (k_treated * n_treated_eff + n_treated - 1) // n_treated
        cp_prec = wprec if k_treated_eff_upper == 0 else min(wprec, 60)
        u_treated = exact_clopper_pearson_upper_general(k_treated_eff_upper, n_treated_eff, alpha_treated, prec=cp_prec)

    if den_lower_prod <= Decimal(0):
        u_ratio = Decimal("Infinity")
        u_ratio_str = "Infinity"
    else:
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            u_ratio = u_treated / den_lower_prod
        u_ratio_str = format(u_ratio, "f")

    # R11-B3: Exact Clopper-Pearson directional confidence authorization is STRICTLY narrowed to
    # `deff == 1.0` (verified independent binary observations, matching GY-018 and IIP-0044).
    # For `deff > 1.0`, variance-adjusted effective counts remain a non-authorizing diagnostic display
    # only and NEVER certify exact directional confidence or release authorization!
    is_exact_independent = bool(deff == Decimal("1.0"))
    return {
        "k_treated": k_treated,
        "n_treated_actual": n_treated,
        "deff": format(deff, "f"),
        "n_treated_eff": n_treated_eff,