scripts/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py
Use this file in any AI chat (paste-only or attachment-capable):
Pinned raw file: https://openislet.org/files/gen-eb955f8266035aba/scripts/verify_iip0058_armz_ensc_isletsort_v2_and_2p24_portfolio.py · SHA-256: 33439d619c00fcc3…
qam = a - one
c = one
d = one - qab * x / qap
if abs(d) < fpmin:
d = fpmin
d = one / d
h = d
for m in range(1, max_iter + 1):
m2 = 2 * m
aa = m * (b - m) * x / ((qam + m2) * (a + m2))
d = one + aa * d
if abs(d) < fpmin:
d = fpmin
c = one + aa / c
if abs(c) < fpmin:
c = fpmin
d = one / d
h *= d * c
aa = -(a + m) * (qab + m) * x / ((a + m2) * (qap + m2))
d = one + aa * d
if abs(d) < fpmin:
d = fpmin
c = one + aa / c
if abs(c) < fpmin:
c = fpmin
d = one / d
delta = d * c
h *= delta
if abs(delta - one) <= eps:
return h
raise RuntimeError(f"Decimal incomplete beta continued fraction did not converge (a={a}, b={b}, x={x})")
def _reg_inc_beta_and_pdf_dec(
k_plus_1: int, n_minus_k: int, x: Decimal, log_beta_inv: Decimal
) -> tuple[Decimal, Decimal]:
"""High-precision regularized incomplete beta I_x(k+1, n-k) and d/dx I_x(k+1, n-k) in active Decimal context."""
one = Decimal(1)
if x <= 0:
return Decimal(0), Decimal(0)
if x >= one:
return one, Decimal(0)
a = Decimal(k_plus_1)
b = Decimal(n_minus_k)
log_bt = log_beta_inv + a * x.ln() + b * (one - x).ln()
bt = Decimal(0) if log_bt < Decimal("-50000") else log_bt.exp()
if x < (a + one) / (a + b + 2):
ib = bt * _betacf_dec(a, b, x) / a
else:
ib = one - bt * _betacf_dec(b, a, one - x) / b
pdf = bt / (x * (one - x))
return ib, pdf
def clopper_pearson_u95_decimal(k: int, n: int, alpha: float = 0.05) -> Decimal:
"""Error-controlled pure-stdlib Decimal one-sided (1 - alpha) Clopper-Pearson upper bound.
Exact port of W6-C1 (iip0055): enforces exact integer domain 1 <= n <= 10^12 and 0 <= k <= n,
evaluates Stirling ln(Gamma) and Lentz continued-fraction I_p(k+1, n-k) at 75-digit Decimal
precision (zero float64 lgamma cancellation at n=10^12), and certifies a conservative upper
bracket hi with I_lo < 1 - alpha <= I_hi and hi - lo <= 1e-28 * hi.
"""
_require(
isinstance(k, int) and not isinstance(k, bool) and isinstance(n, int) and not isinstance(n, bool),
f"clopper_pearson_u95 requires bounded strict integers, got k={k!r}, n={n!r}",
)
_require(1 <= n <= MAX_CLONOGENIC_CELLS, f"clopper_pearson_u95 n out of domain [1, {MAX_CLONOGENIC_CELLS}]: {n}")
_require(0 <= k <= n, f"clopper_pearson_u95 k out of domain [0, {n}]: {k}")
_require(
isinstance(alpha, (int, float))
and not isinstance(alpha, bool)
and math.isfinite(float(alpha))
and 0.0 < float(alpha) < 1.0,
f"Invalid alpha={alpha!r}",
)
a_f = float(alpha)
if k == n:
return Decimal(1)
with localcontext() as ctx:
ctx.prec = 75
a_d = Decimal(str(a_f))
if k == 0:
exact = Decimal(1) - (a_d.ln() / Decimal(n)).exp()
return +exact
target = Decimal(1) - a_d
a_int = k + 1
b_int = n - k
log_beta_inv = _lgamma_pos_int_dec(n + 1) - _lgamma_pos_int_dec(a_int) - _lgamma_pos_int_dec(b_int)
p_hat = Decimal(k) / Decimal(n)
lo = Decimal(0)
hi = Decimal(1)
z = Decimal("1.6448536269514722") if a_d <= Decimal("0.5") else Decimal("0")
se = (p_hat * (Decimal(1) - p_hat) / Decimal(n)).sqrt()
p = p_hat + z * se + Decimal("0.5") / Decimal(n)
if not (lo < p < hi):
p = (lo + hi) / Decimal(2)
tol = Decimal("1e-28")
for _ in range(200):
ib, pdf = _reg_inc_beta_and_pdf_dec(a_int, b_int, p, log_beta_inv)
err = ib - target
if err < 0:
lo = p
else:
hi = p
if hi - lo <= tol * max(hi, Decimal("1e-35")):
break
step_ok = False
if pdf > 0:
step = err / pdf
p_new = p - step
if lo < p_new < hi:
if abs(step) <= tol * max(p_new, Decimal("1e-35")):
eps_b = max(tol * p_new, Decimal("1e-45"))
p_hi = min(hi, p_new + eps_b)
p_lo = max(lo, p_new - eps_b)
ib_hi, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_hi, log_beta_inv)
if ib_hi >= target:
hi = p_hi
ib_lo, _ = _reg_inc_beta_and_pdf_dec(a_int, b_int, p_lo, log_beta_inv)
if ib_lo < target:
lo = p_lo
break
p = p_new
step_ok = True
if not step_ok:
p = (lo + hi) / Decimal(2)
_require(
hi - lo <= Decimal("1e-24") * max(hi, Decimal("1e-35")),
f"clopper_pearson_u95 bracket did not converge for k={k}, n={n}",
)
return +hi
def clopper_pearson_u95(k: int, n: int, alpha: float = 0.05) -> float:
"""Exact pure-stdlib monotone one-sided (1 - alpha) Clopper-Pearson binomial upper confidence bound.
Computes the certified 75-digit Decimal bound and rounds UPWARD to IEEE-754 float64
(via math.nextafter if Decimal.from_float(f) < exact_d) so U95 never understates.
"""
exact_d = clopper_pearson_u95_decimal(k, n, alpha=alpha)
if exact_d >= Decimal(1):
return 1.0
f = float(exact_d)
if Decimal.from_float(f) < exact_d:
f = math.nextafter(f, math.inf)
return min(1.0, f)
def one_sided_clopper_pearson_u95(k: int, n: int, alpha: float = 0.05) -> float:
"""Exact cancellation-free one-sided (1-alpha) upper Clopper-Pearson bound for k events in n trials.
Delegates positive counts (1 <= k <= n <= 10^12) to the certified 75-digit Decimal
clopper_pearson_u95 solver (zero float64 lgamma cancellation and zero OverflowError).
Supports underflow-free exact zero-event evaluation for 1 <= n <= 10^18.
"""
_require(
isinstance(k, int)
and not isinstance(k, bool)
and isinstance(n, int)
and not isinstance(n, bool)
and n > 0
and 0 <= k <= n,
f"Invalid k={k!r}, n={n!r}",
)
_require(
isinstance(alpha, (int, float))
and not isinstance(alpha, bool)
and math.isfinite(float(alpha))
and 0.0 < float(alpha) < 1.0,
f"Invalid alpha={alpha!r}",
)
if k == 0 and n > MAX_CLONOGENIC_CELLS:
_require(n <= 10**18, f"Zero-event n exceeds maximum supported denominator 10^18: {n}")
with localcontext() as ctx:
ctx.prec = 75
a_d = Decimal(str(float(alpha)))
exact_d = +(Decimal(1) - (a_d.ln() / Decimal(n)).exp())
f = float(exact_d)
if Decimal.from_float(f) < exact_d:
f = math.nextafter(f, math.inf)
return min(1.0, f)
return clopper_pearson_u95(k, n, alpha=alpha)
def verify_stage4_gp2_clinimacs(crystal_data: dict[str, Any]) -> dict[str, Any]:
g_s = crystal_data["gp2_7p6s"]
g_t = crystal_data["gp2_7p6t"]
ss_pairs = [(48, 59), (63, 157), (85, 172), (107, 145), (113, 177), (138, 146)]
ss_verified_7p6s = []
ss_verified_7p6t = []
for c1, c2 in ss_pairs:
ds = math.dist(g_s["ss_sg"][str(c1)], g_s["ss_sg"][str(c2)])
dt = math.dist(g_t["ss_sg"][str(c1)], g_t["ss_sg"][str(c2)])
_require(2.00 <= ds <= 2.10, f"GP2 7P6S disulfide C{c1}-C{c2} out of range: {ds:.3f} A")
_require(2.00 <= dt <= 2.10, f"GP2 7P6T disulfide C{c1}-C{c2} out of range: {dt:.3f} A")
ss_verified_7p6s.append({"uniprot_pair": [c1, c2], "sg_sg_dist_A": round(ds, 3)})
ss_verified_7p6t.append({"uniprot_pair": [c1, c2], "sg_sg_dist_A": round(dt, 3)})
# Separate actual deposited NAG heavy atoms vs protein Asn sequon atoms!
nag_7p6s = [pt for atoms in g_s["deposited_nag_atoms"].values() for pt in atoms]
nag_7p6t = [pt for atoms in g_t["deposited_nag_atoms"].values() for pt in atoms]
asn_7p6s = [pt for atoms in g_s["asn_sequon_atoms"].values() for pt in atoms]
asn_7p6t = [pt for atoms in g_t["asn_sequon_atoms"].values() for pt in atoms]
_require(len(g_s["deposited_nag_atoms"]) == 2, f"Expected 2 NAG sites in 7P6S, got {len(g_s['deposited_nag_atoms'])}")
_require(len(g_t["deposited_nag_atoms"]) == 3, f"Expected 3 NAG sites in 7P6T, got {len(g_t['deposited_nag_atoms'])}")
ep_defs = [
("G1_Unique_Nterm_Branch_C48_C59", list(range(49, 58)), "9/9", "9/9"),
("G2_Apical_D10C_Crest_TENSAGS", [70, 72, 76, 77, 78, 79, 80, 81, 82], "7/9", "5/9"),
("G3_Rigid_Equatorial_D10C_Ridge", [96, 97, 98, 109, 127, 128, 129, 158, 159, 160], "10/10", "6/10"),
("G4_C138_C146_Loop_and_W171", [142, 143, 144, 171], "4/4", "2/4"),
]
epitopes = []
for ename, ulist, surf_s, div_s in ep_defs:
d_nag_s = [min_dist_sets(g_s["ep_atoms"][str(u)], nag_7p6s) for u in ulist]
d_nag_t = [min_dist_sets(g_t["ep_atoms"][str(u)], nag_7p6t) for u in ulist]
d_asn_s = [min_dist_sets(g_s["ep_atoms"][str(u)], asn_7p6s) for u in ulist]
d_asn_t = [min_dist_sets(g_t["ep_atoms"][str(u)], asn_7p6t) for u in ulist]
bfs_s = [g_s["ep_bfacs"][str(u)] for u in ulist]
bfs_t = [g_t["ep_bfacs"][str(u)] for u in ulist]
epitopes.append({
"epitope_id": ename,
"residue_indices": ulist,
"surface_res": surf_s,
"divergent_or_absent_in_UMOD": div_s,
"min_dist_to_deposited_nag_7P6S_2sites_A": round(min(d_nag_s), 3),
"min_dist_to_deposited_nag_7P6T_3sites_A": round(min(d_nag_t), 3),
"min_dist_to_protein_asn_sequons_7P6S_4sites_A": round(min(d_asn_s), 3),
"min_dist_to_protein_asn_sequons_7P6T_4sites_A": round(min(d_asn_t), 3),
"mean_bfactor_7P6S_A2": round(sum(bfs_s) / len(bfs_s), 3),
"mean_bfactor_7P6T_A2": round(sum(bfs_t) / len(bfs_t), 3),
})
g3 = next(e for e in epitopes if e["epitope_id"] == "G3_Rigid_Equatorial_D10C_Ridge")
_require(abs(g3["mean_bfactor_7P6S_A2"] - 15.571) < 0.01, f"7P6S G3 B-factor drift: {g3}")
_require(abs(g3["mean_bfactor_7P6T_A2"] - 26.909) < 0.01, f"7P6T G3 B-factor drift: {g3}")
_require(g3["min_dist_to_deposited_nag_7P6S_2sites_A"] >= 13.0, f"7P6S G3 NAG dist drift: {g3}")
_require(g3["min_dist_to_deposited_nag_7P6T_3sites_A"] >= 12.7, f"7P6T G3 NAG dist drift: {g3}")
# Aghazadeh et al. 2022 (PMID:35364010) accurate tumor & denominator reporting
agha_0_of_11_u95 = one_sided_clopper_pearson_u95(0, 11) * 100.0
prospective_0_of_12_u95 = one_sided_clopper_pearson_u95(0, 12) * 100.0
_require(abs(agha_0_of_11_u95 - 23.8404) < 0.005, f"0/11 U95 drift: {agha_0_of_11_u95}")
_require(abs(prospective_0_of_12_u95 - 22.0922) < 0.005, f"0/12 U95 drift: {prospective_0_of_12_u95}")
# Separate total-loaded Aghazadeh yields (do NOT double-count GP2 prevalence!) from
# conditional per-GP2+ column capture sensitivity matrix!
# Disclose BOTH Aghazadeh Table 1 printed H9 mean (23.83% -> 4.196 B / 4.20 B) AND
# the arithmetic mean of the three displayed H9 replicates (23.38% -> 4.277 B / 4.28 B).
aghazadeh_table1_total_loaded_yields = [