#!/usr/bin/env python3
# verify_mde.py — re-walk of the "missing comparator" lead rationale claim:
#   "At 67 per arm the third [cohort] detects only 14.5 to 19.4 point differences."
# Source: https://musesolvescancer.com/api/research-branches (lead 01855785),
# PMID 42434737 — 134 matched patients -> ~67/arm.
#
# Two standard approximations are re-walked, alpha=0.05 two-sided, power=0.80:
#  A) simplified one-term:  delta = (z_a+z_b) * sqrt(2*p2*(1-p2)/n)
#  B) two-term (H0 pooled + H1 unpooled):  delta solved so that
#     delta = z_a*sqrt(2*pbar*(1-pbar)/n) + z_b*sqrt((p1(1-p1)+p2(1-p2))/n)
# Zero dependencies.

import math

N = 67
Z_A = 1.959963984540054  # Phi^-1(1 - alpha/2)
Z_B = 0.841621233572914  # Phi^-1(0.80)


def mde_simple(p2, n=N):
    return (Z_A + Z_B) * math.sqrt(2 * p2 * (1 - p2) / n)


def mde_twoterm(p2, n=N):
    lo, hi = 1e-6, 1.0 - p2 - 1e-6
    for _ in range(200):
        d = (lo + hi) / 2
        p1 = p2 + d
        pbar = (p1 + p2) / 2
        need = (Z_A * math.sqrt(2 * pbar * (1 - pbar) / n)
                + Z_B * math.sqrt((p1 * (1 - p1) + p2 * (1 - p2)) / n))
        if need <= d:
            hi = d
        else:
            lo = d
    return (lo + hi) / 2


def main():
    print("claim: 67/arm detects only 14.5-19.4 point differences "
          "(two-proportion, alpha=0.05 two-sided, power=0.80)")
    print(f"{'baseline p2':>12} {'simple MDE pp':>14} {'two-term MDE pp':>16}")
    simple_band = []
    p2 = 0.05
    while p2 <= 0.501:
        s, t = mde_simple(p2), mde_twoterm(p2)
        if 0.145 <= s <= 0.194:
            simple_band.append(p2)
        print(f"{p2:>12.2f} {s * 100:>14.1f} {t * 100:>16.1f}")
        p2 += 0.05
    print()
    if simple_band:
        print(f"A) simplified formula reproduces the cited 14.5-19.4pp band "
              f"at baseline rates {simple_band[0]:.2f}-{simple_band[-1]:.2f} "
              f"-> matches the claim exactly (10-20% event rate).")
    print("B) fuller two-term calculation gives MDE ~16-24pp across "
          "baselines 0.05-0.50 — the claim is at the optimistic edge "
          "but correct in order of magnitude.")
    print("VERDICT: CONFIRMED WITH REFINEMENT. Under the simplified formula "
          "the band is exact (baselines 10-20%); under the two-term formula "
          "the true MDE is slightly larger (~16-24pp). Substantive conclusion "
          "unchanged: a 67/arm cohort can only detect very large absolute "
          "differences and is underpowered for moderate effects.")


if __name__ == "__main__":
    main()
