OpenIslet

scripts/verify_wave7_cellgemma_2p24_rebase.py

Wave-7 CellGemma-Islet (IIP-0062 to IIP-0065 / GATE-40 to GATE-43) Pure-CPU

script Release v0.8.0 gen-eb955f8266035aba 1.37 MB · 90 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_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…

    return isinstance(val, str) and len(val) == 64 and all(c in "0123456789abcdefABCDEF" for c in val)


def compute_receipt_sha256(ev: Mapping[str, Any]) -> str:
    """Canonical SHA-256 of receipt content excluding receipt_sha256 itself (tamper-evident offline integrity)."""
    body = {k: v for k, v in ev.items() if k != "receipt_sha256"}
    return sha256_bytes(canonical_json_bytes(body))


def parse_utc_iso_ts(val: Any) -> Optional[datetime]:
    """Strict ISO-8601 UTC timestamp parser (requires YYYY-MM-DDTHH:MM:SSZ or +00:00, real calendar date)."""
    if not is_nonempty_str(val):
        return None
    s = str(val).strip()
    if s.endswith("Z"):
        s = s[:-1] + "+00:00"
    if len(s) < 25 or "T" not in s:
        return None
    try:
        dt = datetime.fromisoformat(s)
    except ValueError:
        return None
    if dt.tzinfo is None or dt.utcoffset() != timezone.utc.utcoffset(dt):
        return None
    return dt.astimezone(timezone.utc)


def _to_exact_decimal(val: Any) -> Optional[Decimal]:
    """Convert int/Decimal/finite-float/numeric-str (never bool) to exact finite Decimal without big-int float coercion."""
    if isinstance(val, bool) or val is None:
        return None
    if isinstance(val, Decimal):
        return val if val.is_finite() else None
    if isinstance(val, int):
        return Decimal(val)
    if isinstance(val, float):
        if not math.isfinite(val):
            return None
        return Decimal(str(val))
    if isinstance(val, str):
        s = val.strip()
        if not s:
            return None
        try:
            d = Decimal(s)
        except InvalidOperation:
            return None
        return d if d.is_finite() else None
    return None


# --- Pure-stdlib exact statistical helpers (zero scipy/numpy dependency!) ---

def _betainc_cf(a: float, b: float, x: float) -> float:
    """Modified Lentz continued fraction for regularized incomplete beta I_x(a, b)."""
    max_iter = 400
    eps = 3.0e-15
    fpmin = 1.0e-300
    qab = a + b
    qap = a + 1.0
    qam = a - 1.0
    c = 1.0
    d = 1.0 - qab * x / qap
    if abs(d) < fpmin:
        d = fpmin
    d = 1.0 / d
    h = d
    for m in range(1, max_iter + 1):
        m2 = 2 * m
        aa = m * (b - m) * x / ((qam + m2) * (a + m2))
        d = 1.0 + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = 1.0 + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = 1.0 / d
        h *= d * c
        aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
        d = 1.0 + aa * d
        if abs(d) < fpmin:
            d = fpmin
        c = 1.0 + aa / c
        if abs(c) < fpmin:
            c = fpmin
        d = 1.0 / d
        delta = d * c
        h *= delta
        if abs(delta - 1.0) < eps:
            break
    return h


def regularized_incomplete_beta(a: float, b: float, x: float) -> float:
    """Exact pure-stdlib regularized incomplete beta function I_x(a, b)."""
    if x <= 0.0:
        return 0.0
    if x >= 1.0:
        return 1.0
    bt = math.exp(
        math.lgamma(a + b) - math.lgamma(a) - math.lgamma(b)
        + a * math.log(x) + b * math.log(1.0 - x)
    )
    if x < (a + 1.0) / (a + b + 2.0):
        return bt * _betainc_cf(a, b, x) / a
    return 1.0 - bt * _betainc_cf(b, a, 1.0 - x) / b


def student_t_two_sided_p(t_abs: float, df: float) -> float:
    """Exact pure-stdlib two-sided Student-t p-value P(|T_df| >= t_abs) for arbitrary real df > 0."""
    if t_abs <= 0.0:
        return 1.0
    df_f = float(df)
    x = df_f / (df_f + t_abs * t_abs)
    return regularized_incomplete_beta(0.5 * df_f, 0.5, x)


@lru_cache(maxsize=512)
def student_t_one_sided_crit(alpha: float, df: float) -> float:
    """Exact pure-stdlib one-sided Student-t quantile t_{1-alpha, df} for arbitrary real df > 0."""
    df_f = float(df)
    target_two_sided = 2.0 * alpha
    lo = 0.0
    hi = 2.0
    while student_t_two_sided_p(hi, df_f) > target_two_sided:
        hi *= 2.0
    for _ in range(90):
        mid = 0.5 * (lo + hi)
        if student_t_two_sided_p(mid, df_f) > target_two_sided:
            lo = mid
        else:
            hi = mid
    return hi


def _binom_cdf_le_decimal(k: int, n: int, p: Decimal) -> Decimal:
    """Exact high-precision Decimal P(Bin(n, p) <= k) using shortest tail."""
    one = Decimal(1)
    q = one - p
    if k < 0:
        return Decimal(0)
    if k >= n:
        return one
    if p <= Decimal(0):
        return one
    if p >= one:
        return Decimal(0)
    # Use log-space starting term + exact recurrence for numerical stability at any n
    if k <= n - k:
        # Sum j = 0 .. k
        if k == 0:
            return (Decimal(n) * q.ln()).exp()
        # Start at mode or j=0 safely via ln
        term = (Decimal(n) * q.ln()).exp()
        if term == 0:
            # Start at j=k and sum downward
            ln_c = Decimal(0)
            for j in range(1, k + 1):
                ln_c += Decimal(n - j + 1).ln() - Decimal(j).ln()
            term = (ln_c + Decimal(k) * p.ln() + Decimal(n - k) * q.ln()).exp()
            s = term
            for j in range(k, 0, -1):
                term = term * Decimal(j) * q / (Decimal(n - j + 1) * p)
                s += term
                if term == 0:
                    break
            return min(one, s)
        s = term
        for j in range(1, k + 1):
            term = term * Decimal(n - j + 1) * p / (Decimal(j) * q)
            s += term
        return min(one, s)
    # Complement: 1 - P(Bin(n, q) <= n - k - 1)
    return max(Decimal(0), one - _binom_cdf_le_decimal(n - k - 1, n, q))


@lru_cache(maxsize=4096)
def clopper_pearson_upper_decimal(k: int, n: int, alpha_str: str) -> Decimal:
    """Exact 70-digit outward-rounded (ceiling) Decimal one-sided Clopper-Pearson upper bound."""
    from decimal import localcontext, ROUND_CEILING
    with localcontext() as ctx:
        ctx.prec = 75
        one = Decimal(1)
        alpha = Decimal(alpha_str)
        if k >= n:
            return one
        if k == 0:
            val = one - (alpha.ln() / Decimal(n)).exp()
            return min(one, val + Decimal("1e-60"))
        # Solve P(Bin(n, p) <= k) == alpha (decreasing in p): hi satisfies CDF <= alpha
        lo = Decimal(0)
        hi = one
        for _ in range(210):
            mid = (lo + hi) / Decimal(2)
            if _binom_cdf_le_decimal(k, n, mid) > alpha:
                lo = mid
            else:
                hi = mid
        ctx.rounding = ROUND_CEILING
        return min(one, (hi + Decimal("1e-55")).quantize(Decimal("1e-50")))


@lru_cache(maxsize=4096)
def clopper_pearson_lower_decimal(k: int, n: int, alpha_str: str) -> Decimal:
    """Exact 70-digit outward-rounded (floor) Decimal one-sided Clopper-Pearson lower bound."""
    from decimal import localcontext, ROUND_FLOOR
    with localcontext() as ctx:
        ctx.prec = 75
        zero = Decimal(0)
        one = Decimal(1)
        alpha = Decimal(alpha_str)
        if k <= 0:
            return zero
        if k >= n:
            val = (alpha.ln() / Decimal(n)).exp()
            return max(zero, val - Decimal("1e-60"))
        # Solve P(Bin(n, p) >= k) == alpha <=> P(Bin(n, p) <= k - 1) == 1 - alpha (decreasing in p)
        target = one - alpha
        lo = zero
        hi = one
        for _ in range(210):
            mid = (lo + hi) / Decimal(2)
            if _binom_cdf_le_decimal(k - 1, n, mid) > target:
                lo = mid
            else:
                hi = mid
        ctx.rounding = ROUND_FLOOR
        return max(zero, (lo - Decimal("1e-55")).quantize(Decimal("1e-50")))


def clopper_pearson_upper(k: int, n: int, alpha: float) -> float:
    return float(clopper_pearson_upper_decimal(k, n, str(alpha)))


def clopper_pearson_lower(k: int, n: int, alpha: float) -> float:
    return float(clopper_pearson_lower_decimal(k, n, str(alpha)))


def holm_bonferroni_adjust(p_map: Mapping[str, float]) -> dict[str, float]:
    """Exact step-down Holm-Bonferroni adjusted p-values across a full candidate family."""
    items = sorted(((k, float(v)) for k, v in p_map.items()), key=lambda kv: (kv[1], kv[0]))
    m = len(items)
    adj: dict[str, float] = {}
    running_max = 0.0
    for idx, (k, p_raw) in enumerate(items):
        val = min(1.0, (m - idx) * p_raw)
        if val < running_max:
            val = running_max
        running_max = val
        adj[k] = val