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…

    p_adj = abs(p.adjusted()) if (isinstance(p, Decimal) and p.is_finite() and p != 0) else 0
    wprec = max(prec + 30, 125, p_adj + 40, len(str(n + 1)) + 30)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        if p <= Decimal(0):
            return Decimal(1), Decimal(1)
        if p >= Decimal(1):
            v = Decimal(1) if k >= n else Decimal(0)
            return v, v

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            p_lo = +p
            q_lo = Decimal(1) - p
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            p_hi = +p
            q_hi = Decimal(1) - p

        # Exact mode boundary check: k <= (n + 1) * p?
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            thresh_lo = Decimal(n + 1) * p_lo
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            thresh_hi = Decimal(n + 1) * p_hi

        if Decimal(k) <= thresh_lo:
            return _binomial_lower_tail_monotone_interval(k, n, p_lo, p_hi, q_lo, q_hi, prec)
        if Decimal(k) >= thresh_hi:
            # Complement: P(Bin(n, p) <= k) = 1 - P(Bin(n, q) <= n - k - 1), where n - k - 1 <= (n + 1) * q
            k_comp = n - k - 1
            if k_comp < 0:
                return Decimal(1), Decimal(1)
            c_lo, c_hi = _binomial_lower_tail_monotone_interval(k_comp, n, q_lo, q_hi, p_lo, p_hi, wprec)
            with _clean_dec_ctx(prec, ROUND_FLOOR):
                out_lo = max(Decimal(0), Decimal(1) - c_hi)
            with _clean_dec_ctx(prec, ROUND_CEILING):
                out_hi = min(Decimal(1), Decimal(1) - c_lo)
            return out_lo, out_hi

        # Mode-straddling fallback: k in (thresh_lo, thresh_hi)
        if k <= 120:
            tot_lo = Decimal(0)
            tot_hi = Decimal(0)
            for j in range(0, k + 1):
                c_int = math.comb(n, j)
                with _clean_dec_ctx(wprec, ROUND_FLOOR):
                    tot_lo = tot_lo + (+Decimal(c_int)) * _pow_directed(p_lo, j, wprec, ROUND_FLOOR) * _pow_directed(q_lo, n - j, wprec, ROUND_FLOOR)
                with _clean_dec_ctx(wprec, ROUND_CEILING):
                    tot_hi = tot_hi + (+Decimal(c_int)) * _pow_directed(p_hi, j, wprec, ROUND_CEILING) * _pow_directed(q_hi, n - j, wprec, ROUND_CEILING)
            with _clean_dec_ctx(prec, ROUND_FLOOR):
                out_lo = max(Decimal(0), min(Decimal(1), +tot_lo))
            with _clean_dec_ctx(prec, ROUND_CEILING):
                out_hi = max(Decimal(0), min(Decimal(1), +tot_hi))
            return out_lo, out_hi

        # Split: P(<= k) = P(<= k - 1) + f(k), where k - 1 <= (n+1)*p_lo
        lo_prev, hi_prev = _binomial_lower_tail_monotone_interval(k - 1, n, p_lo, p_hi, q_lo, q_hi, wprec)
        c_int = math.comb(n, k)
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            fk_lo = (+Decimal(c_int)) * _pow_directed(p_lo, k, wprec, ROUND_FLOOR) * _pow_directed(q_lo, n - k, wprec, ROUND_FLOOR)
            out_lo_w = lo_prev + fk_lo
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            fk_hi = (+Decimal(c_int)) * _pow_directed(p_hi, k, wprec, ROUND_CEILING) * _pow_directed(q_hi, n - k, wprec, ROUND_CEILING)
            out_hi_w = hi_prev + fk_hi
        with _clean_dec_ctx(prec, ROUND_FLOOR):
            out_lo = max(Decimal(0), min(Decimal(1), +out_lo_w))
        with _clean_dec_ctx(prec, ROUND_CEILING):
            out_hi = max(Decimal(0), min(Decimal(1), +out_hi_w))
        return out_lo, out_hi


@lru_cache(maxsize=4096)
def _sound_zero_event_core(
    n: int,
    alpha: Decimal,
    eta_lower: Decimal,
    prec: int,
) -> Tuple[Decimal, Decimal, Decimal]:
    wprec = max(prec + 35, 130, len(str(n)) + 35)
    with _clean_dec_ctx(wprec, ROUND_HALF_EVEN):
        ln_lo, ln_hi = _exact_ln_interval(alpha, prec=wprec)
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            z_lo = ln_hi.copy_negate() / Decimal(n)
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            z_hi = ln_lo.copy_negate() / Decimal(n)

        u_raw_lo, u_raw_hi = _exact_one_minus_exp_neg_interval(z_lo, z_hi, prec=wprec)

        with _clean_dec_ctx(prec, ROUND_CEILING):
            u_thinned_upper = u_raw_hi / eta_lower
            if u_thinned_upper > Decimal(1):
                u_thinned_upper = Decimal(1)
            u_raw_upper_out = +u_raw_hi
        with _clean_dec_ctx(prec, ROUND_FLOOR):
            u_thinned_lower = u_raw_lo / eta_lower
            if u_thinned_lower < Decimal(0):
                u_thinned_lower = Decimal(0)
            if u_thinned_lower > Decimal(1):
                u_thinned_lower = Decimal(1)
        return u_raw_upper_out, u_thinned_lower, u_thinned_upper


def sound_zero_event_clopper_pearson_upper(
    n: int,
    alpha: Decimal,
    eta_lower: Decimal = Decimal(1),
    prec: int = 80,
) -> Dict[str, Any]:
    """
    Compute provably outward-directed interval [u_thinned_lower, u_thinned_upper] enclosing:
        p_upper = min(1, (1 - alpha^(1/n)) / eta_lower)
    using exact Fraction reduction + pure elementary Taylor bounds (ZERO Decimal.ln()/exp(),
    ZERO ambient Decimal operations, immune to Inexact traps & hostile prec=4 / narrow Emin contexts!).
    """
    if not _is_strict_int(n) or n < 1:
        raise ValueError("n must be a positive integer")
    if not isinstance(alpha, Decimal) or not alpha.is_finite() or not (Decimal(0) < alpha < Decimal(1)):
        raise ValueError("alpha must be a finite Decimal strictly in (0, 1)")
    if not isinstance(eta_lower, Decimal) or not eta_lower.is_finite() or not (Decimal(0) < eta_lower <= Decimal(1)):
        raise ValueError("eta_lower must be a finite Decimal in (0, 1]")

    with _clean_dec_ctx(max(prec + 35, 130, len(str(n)) + 35), ROUND_HALF_EVEN):
        u_raw_upper_out, u_thinned_lower, u_thinned_upper = _sound_zero_event_core(n, alpha, eta_lower, prec)
        return {
            "n": n,
            "alpha": str(alpha),
            "eta_lower": str(eta_lower),
            "u_raw_upper_80d": format(u_raw_upper_out, "f"),
            "u_thinned_lower_80d": format(u_thinned_lower, "f"),
            "u_thinned_upper_80d": format(u_thinned_upper, "f"),
            "u_thinned_upper_dec": u_thinned_upper,
            "u_thinned_lower_dec": u_thinned_lower,
            "u_thinned_upper_pct_6dp": _dec_to_float_pct(u_thinned_upper, 6),
        }


def _adjudicate_zero_event_vs_cap(
    n: int,
    cap_frac: Decimal,
    alpha: Decimal,
    eta_lower: Decimal,
    *,
    prec: int = 80,
) -> str:
    """
    Three-valued provably sound adjudication of the clamped zero-event upper bound:
        min(1, (1 - alpha^(1/n)) / eta_lower) <= cap_frac
    Returns:
      - "LE"            : STRICTLY proven <= cap_frac
      - "GT"            : STRICTLY proven >  cap_frac
      - "INDETERMINATE" : straddles even at elevated precision & exact-rational budget exceeded
    NEVER infers "GT" from the complement of a one-sided "LE" check!
    """
    if cap_frac >= Decimal(1):
        return "LE"
    t_scale = max(0, -cap_frac.adjusted()) + max(0, -eta_lower.adjusted())
    a_scale = max(0, -alpha.adjusted())
    n_digits = len(str(n))
    base_wprec = max(prec + 40, 140, t_scale + 80, a_scale + 80, n_digits + 60)

    # Escalating outward binary-exponentiation brackets on q^n = (1 - cap_frac * eta_lower)^n vs alpha
    for extra in (0, 140, 360):
        wprec = base_wprec + extra
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            t_lo = cap_frac * eta_lower
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            t_hi = cap_frac * eta_lower
        if t_lo >= Decimal(1):
            return "LE"
        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            q_lo = max(Decimal(0), Decimal(1) - t_hi)
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            q_hi = min(Decimal(1), Decimal(1) - t_lo)
        q_n_hi = _pow_directed(q_hi, n, wprec, ROUND_CEILING)
        if q_n_hi <= alpha:
            return "LE"
        q_n_lo = _pow_directed(q_lo, n, wprec, ROUND_FLOOR)
        if q_n_lo > alpha:
            return "GT"

    # Exact rational adjudication whenever outward brackets straddle (handles exact ties like 0.9**4097!)
    t_frac = Fraction(cap_frac) * Fraction(eta_lower)
    if t_frac >= 1:
        return "LE"
    q_frac = Fraction(1) - t_frac
    max_bits = max(q_frac.numerator.bit_length(), q_frac.denominator.bit_length())
    if n * max_bits <= 8_000_000:
        return "LE" if (q_frac ** n) <= Fraction(alpha) else "GT"
    return "INDETERMINATE"


def min_n_for_zero_event_cap(
    cap_frac: Decimal,
    alpha: Decimal,
    eta_lower: Decimal = Decimal(1),
    prec: int = 80,
) -> Dict[str, Any]:
    """
    Find exact minimum positive integer n such that the clamped zero-event upper bound
        min(1, (1 - alpha^(1/n)) / eta_lower) <= cap_frac
    using dynamically boosted precision (handling tiny caps such as 1e-106 without 1 - cap rounding
    to 1), valid unit-cap handling (cap = 1.0 -> exact clamped n = 1, distinct from unclamped),
    three-valued exact/interval adjudication (handling large ties such as alpha = 0.9**4097 -> n = 4,097),
    and strict two-sided proof for boundary_strictly_verified (n proven LE AND n-1 proven GT).
    """
    if not isinstance(cap_frac, Decimal) or not cap_frac.is_finite() or not (Decimal(0) < cap_frac <= Decimal(1)):
        raise ValueError("cap_frac must be a finite Decimal in (0, 1]")
    if not isinstance(alpha, Decimal) or not alpha.is_finite() or not (Decimal(0) < alpha < Decimal(1)):
        raise ValueError("alpha must be a finite Decimal strictly in (0, 1)")
    if not isinstance(eta_lower, Decimal) or not eta_lower.is_finite() or not (Decimal(0) < eta_lower <= Decimal(1)):
        raise ValueError("eta_lower must be a finite Decimal in (0, 1]")

    def _solve_unclamped_min_n(target_t_cap: Decimal, target_eta: Decimal) -> Tuple[int, bool, bool]:
        """Solve minimum n >= 1 for (1 - target_t_cap * target_eta)^n <= alpha with dynamic precision."""
        t_scale = max(0, -target_t_cap.adjusted()) + max(0, -target_eta.adjusted())
        a_scale = max(0, -alpha.adjusted())
        sig_digits = (
            len(target_t_cap.as_tuple().digits)
            + len(target_eta.as_tuple().digits)
            + len(alpha.as_tuple().digits)
        )
        wprec = max(prec + 45, 145, t_scale + a_scale + 90, sig_digits + 60)

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            t_lo = target_t_cap * target_eta
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            t_hi = target_t_cap * target_eta
        if t_lo >= Decimal(1):
            return 1, True, True

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            q_lo = Decimal(1) - t_hi
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            q_hi = Decimal(1) - t_lo
        if q_lo <= Decimal(0):
            return 1, True, True

        ln_a_lo, ln_a_hi = _exact_ln_interval(alpha, prec=wprec)
        ln_q_lo_b, _ = _exact_ln_interval(q_lo, prec=wprec)
        _, ln_q_hi_b = _exact_ln_interval(q_hi, prec=wprec)

        with _clean_dec_ctx(wprec, ROUND_FLOOR):
            n_lo_est = int((ln_a_hi.copy_negate() / ln_q_lo_b.copy_negate()).to_integral_value(rounding=ROUND_FLOOR))
        with _clean_dec_ctx(wprec, ROUND_CEILING):
            n_hi_est = int((ln_a_lo.copy_negate() / ln_q_hi_b.copy_negate()).to_integral_value(rounding=ROUND_CEILING))

        lo_n = max(1, n_lo_est - 2)
        hi_n = max(lo_n, n_hi_est + 2)

        # Ensure lo_n - 1 (if > 1) is strictly GT and hi_n is strictly LE
        while lo_n > 1 and _adjudicate_zero_event_vs_cap(lo_n, target_t_cap, alpha, target_eta, prec=prec) == "LE":
            hi_n = lo_n
            lo_n = max(1, lo_n - max(1, (hi_n - lo_n) + 1))