| """Section 5.1 -- personalized warfarin dosing on the PharmGKB/IWPC cohort. |
| |
| Paper setup (verbatim, Section 5.1 "RCB Setup"): |
| "The total number of trials is set at T = 5528, with reward noise sigma_hat = 0.054 |
| estimated from the true optimal dosing of warfarin after scaling. To create an |
| online decision-making scenario, we simulate the process across 10 random |
| permutations of patient arrivals, averaging the results over these permutations. |
| The exploration budget eps is varied among [0.025, 0.035, 0.045]. The minimum gap |
| tau_P0 is set at 0.005. The prior variance is defined as Sigma = [0.4, 0.6, 0.8] Id, |
| and the prior means are beta_{2,0} = 0.05 x Id, beta_{1,0} = beta_{3,0} = 0_d." |
| |
| Full grid: 3 budgets x 3 prior variances x 10 permutations = 90 runs of T = 5528. |
| """ |
|
|
| import argparse, json, os, sys, time |
| import numpy as np |
| from sklearn.linear_model import LinearRegression |
|
|
| os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))) |
| sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..")) |
| from rcb.core import RCB, N_eps, L_eps |
| from rcb.env import build_warfarin |
|
|
| PREV = None |
|
|
|
|
| def ground_truth(X, arm, dose): |
| """Appendix F.4 / Section 5.1 ground truth: scale the optimal dose into [0,1] |
| (min 0, max 1); per dosage group, regress the scaled dose on the covariates to |
| get beta_i; the true mean reward of a patient is x'beta_i for the *optimal* arm |
| and 0 for every counterfactual arm.""" |
| s = (dose - dose.min()) / (dose.max() - dose.min()) |
| betas = [] |
| for i in range(3): |
| m = arm == i |
| lr = LinearRegression(fit_intercept=False).fit(X[m], s[m]) |
| betas.append(lr.coef_) |
| betas = np.array(betas) |
| mu_opt = np.einsum("ij,ij->i", X, betas[arm]) |
| sigma_hat = float(np.std(s)) |
| return betas, mu_opt, s, sigma_hat |
|
|
|
|
| def weighted_risk_score(correct, arm, prev): |
| """Section 5.1: Score = sum_k p_k ( I(Correct|k) - I(Incorrect|k) ) = sum_k p_k (2 a_k - 1).""" |
| sc = 0.0 |
| for k in range(3): |
| m = arm == k |
| a = correct[m].mean() if m.sum() else 0.0 |
| sc += prev[k] * (2 * a - 1) |
| return sc |
|
|
|
|
| def effective_phi0(X): |
| """Assumption 3 requires lambda_min(E[xx']) >= phi0 > 0. On the IWPC design this |
| eigenvalue is exactly 0 (the dummy encoding is rank deficient), so we substitute |
| the smallest *positive* eigenvalue -- the tightest value for which the assumption |
| is not vacuous. This substitution is reported in the logbook.""" |
| ev = np.linalg.eigvalsh(X.T @ X / len(X)) |
| return float(ev[ev > 1e-8].min()) |
|
|
|
|
| def run_one(X, arm, mu_opt, sigma, eps, prior_var, seed, tau_P0=0.005, rho_P0=0.95, |
| C_N=None, gamma_const=4.0, phi0=None, use_empirical_EF=True, |
| reward="continuous", rng_noise=None, N_override=None): |
| rng = np.random.default_rng(seed) |
| n, d = X.shape |
| K = 3 |
| order = rng.permutation(n) |
|
|
| beta0 = [np.zeros(d), 0.05 * np.ones(d), np.zeros(d)] |
| Sigma0 = [prior_var * np.eye(d) for _ in range(K)] |
| if phi0 is None: |
| phi0 = effective_phi0(X) |
|
|
| N = N_eps(K, d, sigma, eps, tau_P0, phi0, C=C_N) if N_override is None else float(N_override) |
| L = L_eps(eps, tau_P0, rho_P0) |
|
|
| algo = RCB(K, d, sigma, beta0, Sigma0, N=max(1, N), L=L, offset=0.0, |
| phi0=phi0, trust_mode="linear", trust_rate=1.0, |
| gamma_const=gamma_const, use_empirical_EF=use_empirical_EF, rng=rng) |
|
|
| regret = np.empty(n); gains = np.empty(n); correct = np.empty(n, bool) |
| rec_by_patient = np.empty(n, int) |
| cum = 0.0 |
| for t, idx in enumerate(order): |
| x = X[idx] |
| rec, info = algo.recommend(x) |
| rec_by_patient[idx] = rec |
| gains[t] = algo.dbic_gain_expected(x, algo.rec_kernel(x, info)) |
| ok = rec == arm[idx] |
| correct[t] = ok |
| |
| cum += mu_opt[idx] - (mu_opt[idx] if ok else 0.0) |
| regret[t] = cum |
| if reward == "binary": |
| y = 1.0 if ok else 0.0 |
| else: |
| |
| |
| y = (mu_opt[idx] if ok else 0.0) + sigma * rng.standard_normal() |
| algo.update(x, rec, y, info) |
|
|
| return dict(regret=regret, gain=gains, correct=correct, order=order, |
| rec_by_patient=rec_by_patient, |
| Tcold=algo.Tcold if algo.Tcold else n, N=N, L=L, phi0=phi0) |
|
|
|
|
| def main(): |
| ap = argparse.ArgumentParser() |
| ap.add_argument("--data", default="data/iwpc_warfarin_5528.csv") |
| ap.add_argument("--out", default="outputs/warfarin.json") |
| ap.add_argument("--perms", type=int, default=10) |
| ap.add_argument("--C_N", type=float, default=None, required=True, |
| help="implementation constant multiplying Theorem 1's N(eps)") |
| ap.add_argument("--N", type=int, default=None, |
| help="explicit per-arm cold-start size (overrides C_N * Theorem 1)") |
| ap.add_argument("--reward", default="binary", choices=["binary", "continuous"], |
| help="Section 5.1 states y_t = 1{correct arm} (binary); the " |
| "'Ground Truth' paragraph instead implies y = x'beta_opt.") |
| ap.add_argument("--EF", default="theory", choices=["theory", "empirical"], |
| help="source of E_{F,delta}(|T_{m-1}|) in Algorithm 2 line 10") |
| ap.add_argument("--phi0", type=float, default=1.0, |
| help="Assumption 3 lambda_min(E[xx']); <=0 means use the smallest " |
| "positive eigenvalue of the empirical design") |
| args = ap.parse_args() |
|
|
| X, arm, dose, cols = build_warfarin(args.data) |
| betas, mu_opt, s, sigma_hat = ground_truth(X, arm, dose) |
| n, d = X.shape |
| prev = np.bincount(arm, minlength=3) / n |
| phi0 = args.phi0 if args.phi0 > 0 else effective_phi0(X) |
| print(f"patients={n} features={d} sigma_hat={sigma_hat:.3f} prevalence={prev.round(3)}") |
| print(f"reward={args.reward} EF={args.EF} phi0={phi0:.6g}") |
|
|
| |
| phys_correct = (arm == 1) |
| phys_score = weighted_risk_score(phys_correct, arm, prev) |
| print(f"physician weighted risk score = {phys_score:.3f} (paper: 0.20)") |
|
|
| |
| |
| lam = 1e-2 |
| bh = [] |
| for i in range(3): |
| yv = (arm == i).astype(float) if args.reward == "binary" else np.where(arm == i, mu_opt, 0.0) |
| bh.append(np.linalg.solve(X.T @ X + lam * np.eye(d), X.T @ yv)) |
| pred = (X @ np.array(bh).T).argmax(1) |
| ceil_cm = np.array([[float((pred[arm == k] == j).mean()) for j in range(3)] for k in range(3)]) |
| print(f"offline oracle ceiling: err={1 - (pred == arm).mean():.4f} " |
| f"score={weighted_risk_score(pred == arm, arm, prev):+.4f}") |
|
|
| |
| N_thm1 = {e: N_eps(3, d, sigma_hat, e, 0.005, phi0, C=1.0) for e in [0.025, 0.035, 0.045]} |
| print("Theorem 1 required N(eps) at C=1: " + |
| " ".join(f"{e}:{v:.0f}" for e, v in N_thm1.items()) + f" (T = {n})") |
|
|
| res = {"meta": dict(n=n, d=d, sigma_hat=sigma_hat, prevalence=prev.tolist(), |
| physician_score=phys_score, |
| physician_error=float(1 - phys_correct.mean()), |
| C_N=args.C_N, reward=args.reward, EF=args.EF, phi0=phi0, |
| ceiling_error=float(1 - (pred == arm).mean()), |
| ceiling_score=weighted_risk_score(pred == arm, arm, prev), |
| ceiling_confusion=ceil_cm.tolist(), |
| N_theorem1_C1={str(k): v for k, v in N_thm1.items()}, |
| columns=cols), "runs": []} |
|
|
| t0 = time.time() |
| for eps in [0.025, 0.035, 0.045]: |
| for pv in [0.4, 0.6, 0.8]: |
| regs, errs, gns, scores, conf, tcolds = [], [], [], [], [], [] |
| for p in range(args.perms): |
| r = run_one(X, arm, mu_opt, sigma_hat, eps, pv, seed=1000 * p + 7, |
| C_N=args.C_N, reward=args.reward, phi0=phi0, |
| use_empirical_EF=(args.EF == "empirical"), |
| N_override=args.N) |
| regs.append(r["regret"]); gns.append(r["gain"]) |
| errs.append(1 - np.cumsum(r["correct"]) / np.arange(1, n + 1)) |
| rp = r["rec_by_patient"] |
| scores.append(weighted_risk_score(rp == arm, arm, prev)) |
| |
| cm = np.zeros((3, 3)) |
| for k in range(3): |
| m = arm == k |
| for j in range(3): |
| cm[k, j] = (rp[m] == j).mean() |
| conf.append(cm) |
| tcolds.append(r["Tcold"]) |
| entry = dict(eps=eps, prior_var=pv, |
| regret_mean=float(np.mean([g[-1] for g in regs])), |
| regret_curve=np.mean(regs, 0)[::20].tolist(), |
| error_final=float(np.mean([e[-1] for e in errs])), |
| error_curve=np.mean(errs, 0)[::20].tolist(), |
| gain_curve=np.mean(gns, 0)[::20].tolist(), |
| gain_min=float(np.min(np.mean(gns, 0))), |
| frac_gain_below_negeps=float(np.mean(np.mean(gns, 0) < -eps)), |
| score=float(np.mean(scores)), score_sd=float(np.std(scores)), |
| confusion=np.mean(conf, 0).tolist(), |
| Tcold=float(np.mean(tcolds)), N=r["N"], L=r["L"]) |
| res["runs"].append(entry) |
| print(f"eps={eps} Sigma={pv}I | N={r['N']:.1f} L={r['L']:.1f} " |
| f"Tcold={np.mean(tcolds):.0f} | err={entry['error_final']:.3f} " |
| f"score={entry['score']:.3f} regret={entry['regret_mean']:.0f} " |
| f"min-gain={entry['gain_min']:+.4f}") |
|
|
| res["physician_confusion"] = [[0, 1, 0], [0, 1, 0], [0, 1, 0]] |
| res["wall_clock_s"] = time.time() - t0 |
| os.makedirs(os.path.dirname(args.out), exist_ok=True) |
| json.dump(res, open(args.out, "w")) |
| print(f"wrote {args.out} in {res['wall_clock_s']:.0f}s") |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|