File size: 10,543 Bytes
b381c58
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
"""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   # true class prevalences p_k, filled from the data


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])       # x'beta_{optimal 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)]     # Medium arm is prior-best
    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
        # mu(x, i) = x'beta_i for the optimal arm, 0 for counterfactuals
        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_t = mu(x_t, a_t) + eta_t, mu = x'beta_i for the optimal arm and 0
            # for counterfactual arms (Section 5.1 "Ground Truth"), eta ~ N(0, sigma^2)
            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}")

    # Physician baseline: always Medium
    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)")

    # Offline full-information ceiling for the paper's own oracle class (per-arm
    # ridge on ALL 5528 patients). No online policy using this oracle can beat it.
    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}")

    # Theorem 1's own requirement at this scale, with C = 1 (no fudge factor).
    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))
                # Table 2: rows = true dosage stratum, cols = RCB assigned dosage
                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()