scripts/verify_wave7_cellgemma_2p24_rebase.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_wave7_cellgemma_2p24_rebase.py · SHA-256: 5f31a6369f25031d…
a[1] = -an1
phi = (m_ss - 2.0 * m[-1] ** 2 - 2.0 * m[-2] ** 2) / (1.0 - 2.0 * an ** 2 - 2.0 * an1 ** 2)
sp = math.sqrt(phi)
for i in range(2, n - 2):
a[i] = m[i] / sp
num = sum(ai * xi for ai, xi in zip(a, s))
w = min(1.0, max(0.0, (num * num) / ss))
if w >= 1.0 - 1e-15:
return (w, 1.0)
if n == 3:
p = (6.0 / math.pi) * (math.asin(math.sqrt(w)) - math.asin(math.sqrt(0.75)))
return (w, max(0.0, min(1.0, p)))
lw = math.log(1.0 - w)
if n <= 11:
gam = 0.459 * n - 2.273
if lw >= gam - 1e-12:
return (w, 0.0)
y = -math.log(gam - lw)
mu = -0.0006714 * (n ** 3) + 0.025054 * (n ** 2) - 0.39978 * n + 0.5440
sig = math.exp(-0.0020322 * (n ** 3) + 0.062767 * (n ** 2) - 0.77857 * n + 1.3822)
else:
lx = math.log(n)
y = lw
mu = 0.0038915 * (lx ** 3) - 0.083751 * (lx ** 2) - 0.31082 * lx - 1.5861
sig = math.exp(0.0030302 * (lx ** 2) - 0.082676 * lx - 0.4803)
z = (y - mu) / sig
p = 0.5 * math.erfc(z / math.sqrt(2.0))
return (w, max(0.0, min(1.0, p)))
def _to_exact_fraction(val: Any) -> Optional[Fraction]:
if isinstance(val, Fraction):
return val
d = _to_exact_decimal(val)
if d is None:
return None
return Fraction(d)
def _all_signed_subset_sums_int(vals: Sequence[int]) -> list[int]:
sums = [0]
for v in vals:
sums = [s + v for s in sums] + [s - v for s in sums]
return sums
def _exact_sign_flip_p_from_fractions(fracs: Sequence[Fraction]) -> Optional[float]:
"""
Exact arbitrary-precision scaled-integer two-sided paired Fisher sign-flip p-value.
Eliminates ALL float subtraction drift and ALL ambient Decimal precision limits on boundary ties!
"""
n = len(fracs)
if n == 0:
return 1.0
if n > EXACT_SIGN_FLIP_MAX_N:
return None
lcm_den = 1
for f in fracs:
lcm_den = math.lcm(lcm_den, f.denominator)
ivals = [int(f * lcm_den) for f in fracs]
obs = abs(sum(ivals))
if obs == 0:
return 1.0
if all(v > 0 for v in ivals) or all(v < 0 for v in ivals):
return 2.0 / float(1 << n)
mid = n // 2
left_sums = _all_signed_subset_sums_int(ivals[:mid])
right_sums = sorted(_all_signed_subset_sums_int(ivals[mid:]))
nr = len(right_sums)
neg_obs = -obs
extreme = 0
for a in left_sums:
extreme += (nr - bisect_left(right_sums, obs - a)) + bisect_right(right_sums, neg_obs - a)
return min(1.0, extreme / float(1 << n))
def exact_two_sided_sign_flip_p(diffs: Sequence[Any]) -> Optional[float]:
"""Exact rational/scaled-integer two-sided Fisher sign-flip p-value for 1 <= n <= 20."""
fracs = [_to_exact_fraction(x) for x in diffs]
if any(f is None for f in fracs):
return None
return _exact_sign_flip_p_from_fractions([f for f in fracs if f is not None])
def exact_two_sided_sign_flip_paired_p(treated: Sequence[Any], control: Sequence[Any]) -> Optional[float]:
"""Exact rational/scaled-integer paired Fisher sign-flip forming (treated[i] - control[i]) in exact Fraction arithmetic."""
if len(treated) != len(control):
return None
fracs: list[Fraction] = []
for a, b in zip(treated, control):
fa = _to_exact_fraction(a)
fb = _to_exact_fraction(b)
if fa is None or fb is None:
return None
fracs.append(fa - fb)
return _exact_sign_flip_p_from_fractions(fracs)
def exact_hodges_lehmann_median(diff_fracs: Sequence[Fraction]) -> Fraction:
"""Exact rational Hodges-Lehmann one-sample estimator (median of all n(n+1)/2 Walsh averages)."""
n = len(diff_fracs)
require(n >= 1, "exact_hodges_lehmann_median requires at least one difference")
walsh_avgs = sorted((diff_fracs[i] + diff_fracs[j]) / 2 for i in range(n) for j in range(i, n))
nw = len(walsh_avgs)
if nw % 2 == 1:
return walsh_avgs[nw // 2]
return (walsh_avgs[nw // 2 - 1] + walsh_avgs[nw // 2]) / 2
def recompute_clopper_pearson_u95_decimal_n_eff(n_eff: int) -> Decimal:
"""Exact 75-digit Decimal Clopper-Pearson one-sided 95% upper bound for k=0 survivors at integer n_eff."""
return clopper_pearson_upper_decimal(0, n_eff, "0.05")
def _recompute_pirfenidone_peak_systemic_cmax_ug_ml(
times_h: Sequence[float],
cum_mg: Sequence[float],
*,
t_half_h: float,
vd_l: float,
) -> float:
"""
Mathematically tight supremum 1-compartment peak systemic plasma C_max (ug/mL = mg/L) over ALL
non-decreasing cumulative release schedules compatible with (times_h, cum_mg):
- Max carry-over at t_{i-1} occurs when all prior increments arrive as late as possible (amount_end)
- Max intra-interval peak occurs immediately after t_{i-1}+ when full dm_i arrives instantaneously
(amount_end + dm_i), strictly upper-bounding adjacent-boundary double bursts!
"""
ke = math.log(2.0) / t_half_h
amount_end = 0.0
max_mg = 0.0
for i in range(1, len(times_h)):
dt = times_h[i] - times_h[i - 1]
dm = cum_mg[i] - cum_mg[i - 1]
# Supremum peak at t_{i-1}+: prior carried-over mass + instantaneous full next-interval burst dm
peak_at_left = amount_end + dm
if peak_at_left > max_mg:
max_mg = peak_at_left
# Advance maximum possible carried-over mass at t_i (prior mass decays over dt, dm arrives at t_i-)
amount_end = amount_end * math.exp(-ke * dt) + dm
if amount_end > max_mg:
max_mg = amount_end
return max_mg / vd_l # mg/L == ug/mL
def _recompute_max_24h_cumulative_mg(times_h: Sequence[float], cum_mg: Sequence[float]) -> float:
"""
Exact mathematical supremum of C(s + 24) - C(s) over ALL start times s >= 0 and ALL
monotone non-decreasing cumulative release curves C(t) passing through (times_h[k], cum_mg[k]):
- Any single-interval release cum[i+1] - cum[i] can occur instantaneously inside a 24-h window.
- Any multi-interval pair (i, j) with j >= i + 2 can have s in [t_i, t_{i+1}) and s+24 in (t_{j-1}, t_j]
iff t_{j-1} - t_{i+1} < 24.0 (or t_j - t_i <= 24.0), achieving exact supremum cum[j] - cum[i].
Makes ZERO linear-interpolation assumptions (never undercounts step or non-grid 24-h windows!).
"""
n = len(times_h)
max_24 = 0.0
for i in range(n):
for j in range(i + 1, n):
dm = cum_mg[j] - cum_mg[i]
if j == i + 1 or (times_h[j] - times_h[i]) <= 24.0 + 1e-9 or (times_h[j - 1] - times_h[i + 1]) <= 24.0 + 1e-9:
if dm > max_24:
max_24 = dm
else:
break
return max_24
def _validate_dec134_washout_trace(
w_ts: Any, w_rem: Any, w_sha: Any,
w_span: Any, w_tail: Any, w_mass: Any,
w_t50: Any, w_mean: Any, w_t90: Any,
) -> bool:
"""
Shared fail-closed DEC-134 washout trace reconciler used by BOTH Readout-2 AND GATE-31:
- Verifies content SHA-256 against canonical JSON of the embedded raw trace
- Recomputes exact t50 (50% crossing) and t90 (10% crossing) brackets directly from raw series
(requiring full bracket upper edge <= 4.50 min for t50 and <= 11.0 min for t90, with no rebound!)
- Recomputes trapezoidal mean transit time (MTT = integral / r[0]) <= 5.50 min and reconciles to summary!
"""
if not (
isinstance(w_ts, list) and isinstance(w_rem, list) and len(w_ts) == len(w_rem) and len(w_ts) >= 5
and all(is_finite_num(x) for x in w_ts + w_rem)
and all(is_finite_num(x) for x in (w_span, w_tail, w_mass, w_t50, w_mean, w_t90))
and is_valid_sha256_hex(w_sha)
):
return False
expected_sha = sha256_bytes(canonical_json_bytes({"time_min": w_ts, "remaining_peak_pct": w_rem}))
if str(w_sha) != expected_sha:
return False
wtf = [float(x) for x in w_ts]
wrf = [float(x) for x in w_rem]
if (
wtf[0] != 0.0 or any(wtf[i] >= wtf[i + 1] for i in range(len(wtf) - 1))
or wtf[-1] < 15.0 or not (95.0 <= wrf[0] <= 105.0) or min(wrf) < 0.0 or wrf[-1] > 10.0
or abs(wtf[-1] - float(w_span)) > 0.25 or abs(wrf[-1] - float(w_tail)) > 0.5
or not (float(w_span) >= 15.0 and 0.0 <= float(w_tail) <= 10.0 and 80.0 <= float(w_mass) <= 120.0)
):
return False
# Exact raw crossing brackets for 50% (t50) and 10% (t90), enforcing no subsequent rebound!
t50_lo = t50_hi = None
t90_lo = t90_hi = None
for i in range(len(wtf)):
if t50_lo is None and wrf[i] <= 50.0 + 1e-9:
if abs(wrf[i] - 50.0) <= 1e-9:
t50_lo = t50_hi = wtf[i]
elif i > 0:
t50_lo, t50_hi = wtf[i - 1], wtf[i]
if t90_lo is None and wrf[i] <= 10.0 + 1e-9:
if abs(wrf[i] - 10.0) <= 1e-9:
t90_lo = t90_hi = wtf[i]
elif i > 0:
t90_lo, t90_hi = wtf[i - 1], wtf[i]
if t50_lo is None or t50_hi is None or t90_lo is None or t90_hi is None:
return False
# Reject any rebound back above 50% after t50_hi or above 10% after t90_hi
if any(wrf[i] > 50.0 + 1e-9 for i in range(len(wtf)) if wtf[i] > t50_hi + 1e-9):
return False
if any(wrf[i] > 10.0 + 1e-9 for i in range(len(wtf)) if wtf[i] > t90_hi + 1e-9):
return False
if t50_hi > 4.50 + 1e-9 or t90_hi > 11.0 + 1e-9:
return False
if not (t50_lo - 1e-6 <= float(w_t50) <= t50_hi + 1e-6) or not (t90_lo - 1e-6 <= float(w_t90) <= t90_hi + 1e-6):
return False
if not (0.0 < float(w_t50) <= 4.50 and float(w_t50) <= float(w_t90) <= 11.0):
return False
# Trapezoidal mean transit time (area under normalized remaining-peak curve)
area = sum(0.5 * (wrf[i - 1] + wrf[i]) * (wtf[i] - wtf[i - 1]) for i in range(1, len(wtf)))
mtt_recomp = area / wrf[0]
if not (0.0 < mtt_recomp <= 5.50 and 0.0 < float(w_mean) <= 5.50 and abs(float(w_mean) - mtt_recomp) <= 0.30):
return False
return True
def _check_allowed_keys(rec: Mapping[str, Any], allowed: FrozenSet[str], fails: list[str], tag: str) -> None:
extra = sorted(k for k in rec.keys() if k not in allowed)
if extra:
fails.append(f"FAIL_{tag}_UNKNOWN_OR_UNRECONCILED_FIELDS:{','.join(extra[:4])}")
def _check_forbidden_keys(rec: Mapping[str, Any], forbidden: FrozenSet[str], fails: list[str], code: str) -> None:
present = sorted(k for k in forbidden if k in rec)
if present:
fails.append(f"{code}:{','.join(present[:4])}")
def _validate_structured_exclusions(
excl_log: Any,
*,
expected_n: int,
analyzed_ids_norm: set[str],