File size: 14,920 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 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | """Figures for the reproduction logbook.
Palette: validated categorical slots (validate_palette.js, light mode, ALL CHECKS PASS).
Every figure ships its raw data as CSV alongside the HTML, which serves as the table
view the contrast WARN obligates.
"""
import json, os, sys
import numpy as np
import plotly.graph_objects as go
os.chdir(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))
OUT = "figs"
P = ["#2a78d6", "#e87ba4", "#eda100", "#1baf7a", "#4a3aa7"] # categorical slots
INK, INK2, GRID = "#0b0b0b", "#52514e", "rgba(120,118,110,0.22)"
def base(fig, title, xt, yt, logx=False, logy=False):
fig.update_layout(
title=dict(text=title, font=dict(size=15, color=INK)),
paper_bgcolor="rgba(0,0,0,0)", plot_bgcolor="rgba(0,0,0,0)",
font=dict(family="Inter, system-ui, sans-serif", size=12, color=INK2),
margin=dict(l=64, r=132, t=54, b=52), hovermode="x unified",
legend=dict(bgcolor="rgba(0,0,0,0)", borderwidth=0, font=dict(color=INK2)),
width=780, height=420)
for ax, t, lg in ((fig.update_xaxes, xt, logx), (fig.update_yaxes, yt, logy)):
ax(title_text=t, type="log" if lg else "linear", gridcolor=GRID,
zeroline=False, linecolor=GRID, ticks="outside", tickcolor=GRID,
title_font=dict(color=INK2))
return fig
def endlabel(fig, x, y, text, color):
fig.add_annotation(x=np.log10(x) if fig.layout.xaxis.type == "log" else x,
y=np.log10(y) if fig.layout.yaxis.type == "log" else y,
text=text, showarrow=False, xanchor="left", xshift=8,
font=dict(color=color, size=11))
def save(fig, name, rows, header):
os.makedirs(OUT, exist_ok=True)
fig.write_html(f"{OUT}/{name}.html", include_plotlyjs="cdn", full_html=True)
with open(f"{OUT}/{name}.csv", "w") as f:
f.write(",".join(header) + "\n")
for r in rows:
f.write(",".join(str(v) for v in r) + "\n")
print(f"wrote {OUT}/{name}.html + .csv")
# ------------------------------------------------------------------ Claim 1
def fig_rate(path="outputs/claim1_rate.json"):
"""Exploitation-stage regret vs T: the sqrt(T) half of Theorem 2, confirmed."""
f = json.load(open(path))["fits"]
fig = go.Figure(); rows = []
keys = [k for k in f if k.startswith("T:")]
for i, k in enumerate(keys):
T, R, s = f[k]["x"], f[k]["exploit"], f[k]["slope_exploit"]
lab = k[2:].replace("_", ", ").replace("K", "K=").replace("d", "d=")
fig.add_trace(go.Scatter(x=T, y=R, mode="lines+markers", name=f"{lab} (slope {s:.3f})",
line=dict(color=P[i], width=2), marker=dict(size=8)))
endlabel(fig, T[-1], R[-1], f"{s:.3f}", P[i])
rows += [[lab, t, r] for t, r in zip(T, R)]
T = np.array(f[keys[0]]["x"], float)
ref = f[keys[0]]["exploit"][0] * np.sqrt(T / T[0])
fig.add_trace(go.Scatter(x=T, y=ref, mode="lines", name="√T reference (slope 0.5)",
line=dict(color=INK2, width=2, dash="dot")))
base(fig, "Claim 1 — exploitation-stage regret vs horizon T (5 seeds, T up to 2¹⁷)",
"T (rounds, log)", "regret accrued after the cold start (log)", True, True)
save(fig, "claim1_rate_T", rows, ["config", "T", "exploitation_regret"])
def fig_rate_Kd(path="outputs/claim1_rate.json"):
"""Exploitation-stage regret vs K and vs d: sqrt(d) holds, sqrt(K) does not."""
f = json.load(open(path))["fits"]
fig = go.Figure(); rows = []
for i, (k, lab) in enumerate([("K", "vs K (d=5)"), ("d", "vs d (K=5)")]):
x, y, s = f[k]["x"], f[k]["exploit"], f[k]["slope_exploit"]
fig.add_trace(go.Scatter(x=x, y=y, mode="lines+markers",
name=f"{lab} — slope {s:.3f}",
line=dict(color=P[i], width=2), marker=dict(size=8)))
endlabel(fig, x[-1], y[-1], f"{s:.3f}", P[i])
rows += [[lab, a, b] for a, b in zip(x, y)]
xs = np.array([2, 20], float)
y0 = f["K"]["exploit"][0]
fig.add_trace(go.Scatter(x=xs, y=y0 * np.sqrt(xs / 2), mode="lines",
name="√· reference — Theorem 2's claimed slope 0.5",
line=dict(color=INK2, width=2, dash="dot")))
base(fig, "Claim 1 — exploitation regret vs arms K and dimension d (T = 2¹⁷)",
"K or d (log)", "exploitation-stage regret (log)", True, True)
save(fig, "claim1_rate_Kd", rows, ["sweep", "value", "exploitation_regret"])
def fig_warfarin_ablation(path="outputs/warfarin_ablation.json"):
"""Which reading of the paper's under-specified §5.1 setup reproduces Table 2?
Distance is the L1 distance between the 3x3 dosage-correction matrix and Table 2."""
d = json.load(open(path))
fig = go.Figure(); rows = []
labs, vals, cols = [], [], []
for c in d["ceilings"]:
labs.append(f"offline ceiling<br>{c['reward']} reward")
vals.append(c["conf_L1_vs_paper"]); cols.append(P[4])
rows.append(["ceiling", c["reward"], "-", "-", c["conf_L1_vs_paper"],
c["error"], c["score"]])
for e in d["spec_grid"]:
labs.append(f"{e['reward']}<br>E_F={e['EF']}, φ₀={e['phi0']}")
vals.append(e["conf_L1_vs_paper"])
cols.append(P[0] if e["reward"] == "binary" else P[1])
rows.append(["online RCB", e["reward"], e["EF"], e["phi0"],
e["conf_L1_vs_paper"], e["error"], e["score"]])
order = np.argsort(vals)
fig.add_trace(go.Bar(x=[labs[i] for i in order], y=[vals[i] for i in order],
marker_color=[cols[i] for i in order],
hovertemplate="%{x}<br>L1 distance to Table 2: %{y:.3f}<extra></extra>"))
base(fig, "Warfarin §5.1 — distance to the paper's Table 2 under each reading "
"of the under-specified setup",
"specification", "L1 distance of the 3×3 correction matrix to Table 2")
fig.update_layout(height=470, margin=dict(l=64, r=40, t=54, b=120))
save(fig, "warfarin_ablation", rows,
["policy", "reward", "EF", "phi0", "L1_to_table2", "error", "weighted_risk_score"])
def fig_warfarin_N(path="outputs/warfarin_ablation.json"):
"""Cold-start length vs clinical quality: the Claim-2 tradeoff on real data."""
d = json.load(open(path))
s = [e for e in d["N_sweep"] if e["Tcold"] < 5528]
fig = go.Figure()
fig.add_trace(go.Scatter(x=[e["Tcold"] for e in s], y=[e["score"] for e in s],
mode="lines+markers", name="RCB weighted risk score",
line=dict(color=P[0], width=2), marker=dict(size=9),
text=[f"N={e['N']}" for e in s],
hovertemplate="T_cold=%{x:.0f} (%{text})<br>score=%{y:.3f}<extra></extra>"))
for yv, lab, col in [(0.291, "paper's reported RCB score 0.291", "#c0392b"),
(d["ceilings"][0]["score"], "offline full-data oracle ceiling 0.352", P[4]),
(d["meta"]["physician_score"], "physician baseline 0.224", INK2)]:
fig.add_hline(y=yv, line=dict(color=col, width=2, dash="dot"),
annotation_text=lab, annotation_font_color=col)
base(fig, "Warfarin — the price of incentives, measured: longer cold start ⇒ worse clinical score",
"cold-start length T_cold (patients)", "weighted risk score")
save(fig, "warfarin_N", [[e["N"], e["Tcold"], e["error"], e["score"]] for e in d["N_sweep"]],
["N", "Tcold", "error", "weighted_risk_score"])
def fig_gain(path="outputs/syn_s1.json"):
d = json.load(open(path))["setting1"]
fig = go.Figure(); rows = []
sel = [e for e in d if e["d"] == 5][:4]
for i, e in enumerate(sel):
fig.add_trace(go.Bar(x=[f"K={e['K']}"], y=[e["gain_frac_ok"]],
marker_color=P[i], name=f"K={e['K']}", showlegend=False,
text=[f"{e['gain_frac_ok']:.3f}"], textposition="outside"))
rows.append([e["K"], e["d"], e["gain_frac_ok"], e["gain_min"]])
fig.add_hline(y=1.0, line=dict(color=INK2, width=2, dash="dot"),
annotation_text="required by Definition 1", annotation_font_color=INK2)
base(fig, "Claim 1 — fraction of rounds satisfying the ε-DBIC constraint (d=5, T=10⁵)",
"arms", "fraction of rounds with expected gain ≥ −ε")
fig.update_yaxes(range=[0, 1.15])
save(fig, "claim1_dbic", rows, ["K", "d", "frac_gain_ge_-eps", "min_gain"])
# ------------------------------------------------------------------ Claim 2
def fig_feasibility(path="outputs/feas.json"):
d = json.load(open(path))["thm1_feasibility"]
fig = go.Figure()
tags = [e["tag"] for e in d]; ratio = [e["ratio"] for e in d]
fig.add_trace(go.Bar(y=tags, x=ratio, orientation="h", marker_color=P[0],
text=[f"{r:,.0f}×" for r in ratio], textposition="outside",
showlegend=False))
fig.add_vline(x=1.0, line=dict(color="#c0392b", width=2, dash="dot"),
annotation_text="cold start = the paper's own horizon T",
annotation_font_color="#c0392b")
base(fig, "Claim 2 — Theorem 1's prescribed cold start K·L·N(ε), as a multiple of T",
"K·L·N(ε) / T (log scale)", "", True)
fig.update_layout(height=460, margin=dict(l=190, r=110, t=54, b=52))
save(fig, "claim2_feasibility", [[e["tag"].replace(",", ";"), e["T"], e["N"], e["L"], e["cold"], e["ratio"]]
for e in d],
["config", "T", "N_eps", "L", "K_L_N", "ratio_to_T"])
def fig_tradeoff(path="outputs/syn_s3.json"):
d = json.load(open(path))["setting3"]
fig = go.Figure(); rows = []
for i, lam in enumerate([3, 5, 10]):
sub = sorted([e for e in d if e["lam"] == lam], key=lambda e: e["eps"])
fig.add_trace(go.Scatter(x=[e["eps"] for e in sub], y=[e["regret"] for e in sub],
mode="lines+markers", name=f"Σ₀ = (1/{lam})·I",
line=dict(color=P[i], width=2), marker=dict(size=9)))
endlabel(fig, sub[-1]["eps"], sub[-1]["regret"], f"1/{lam}", P[i])
rows += [[lam, e["eps"], e["N"], e["Tcold"], e["regret"], e["frac_ok"]] for e in sub]
base(fig, "Claim 2 — incentive budget ε vs cumulative regret (Setting 3, T=5×10⁴, K=d=5)",
"incentive budget ε", "cumulative regret R(T) (log)", False, True)
save(fig, "claim2_tradeoff", rows, ["inv_lambda", "eps", "N", "Tcold", "regret", "frac_dbic_ok"])
def fig_Neps():
from rcb.core import N_eps
fig = go.Figure(); rows = []
specs = [("K (cubic)", [2, 3, 5, 10, 20, 40], lambda v: N_eps(v, 5, .05, .05, .01, 1.), 3.0),
("d at σ=0.05 (paper's own noise)", [2, 5, 10, 20, 50, 100, 200],
lambda v: N_eps(5, v, .05, .05, .01, 1.), None),
("τ+ε (inverse quadratic)", [.02, .03, .04, .06, .11],
lambda v: N_eps(5, 5, .05, v - .01, .01, 1.), -2.0)]
for i, (lab, xs, f, th) in enumerate(specs):
ys = [f(v) for v in xs]
s = float(np.polyfit(np.log(xs), np.log(ys), 1)[0])
fig.add_trace(go.Scatter(x=xs, y=ys, mode="lines+markers",
name=f"{lab} — fitted {s:+.3f}"
+ (f" (paper {th:+.0f})" if th else " (paper +1)"),
line=dict(color=P[i], width=2), marker=dict(size=8)))
endlabel(fig, xs[-1], ys[-1], f"{s:+.2f}", P[i])
rows += [[lab, v, y] for v, y in zip(xs, ys)]
base(fig, "Claim 2 — measured exponents of Theorem 1's N(ε)",
"parameter value (log)", "N(ε) (log)", True, True)
save(fig, "claim2_Neps", rows, ["sweep", "value", "N_eps"])
# ------------------------------------------------------------------ warfarin
def fig_warfarin(path="outputs/warfarin.json"):
d = json.load(open(path))
fig = go.Figure(); rows = []
for i, eps in enumerate([0.025, 0.035, 0.045]):
e = [x for x in d["runs"] if x["eps"] == eps and x["prior_var"] == 0.4][0]
y = e["error_curve"]; x = list(range(0, 20 * len(y), 20))
fig.add_trace(go.Scatter(x=x[5:], y=y[5:], mode="lines", name=f"RCB, ε={eps}",
line=dict(color=P[i], width=2)))
endlabel(fig, x[-1], y[-1], f"{y[-1]:.2f}", P[i])
rows += [[eps, a, b] for a, b in zip(x, y)]
for yv, lab, col in [(0.35, "paper's reported RCB error ≈ 0.35", "#c0392b"),
(d["meta"]["physician_error"], "physician (always Medium)", INK2),
(0.3238, "offline full-data oracle ceiling 0.324", "#4a3aa7")]:
fig.add_hline(y=yv, line=dict(color=col, width=2, dash="dot"),
annotation_text=lab, annotation_font_color=col,
annotation_position="top right")
base(fig, "Warfarin (§5.1) — fraction of incorrect dosing decisions, Σ₀=0.4·I, 10 permutations",
"patients seen", "cumulative error rate")
fig.update_yaxes(range=[0.28, 0.62])
save(fig, "warfarin_error", rows, ["eps", "t", "error_rate"])
def fig_gamma(path="outputs/warfarin_gamma_sweep.json"):
d = json.load(open(path))
fig = go.Figure()
g = [e["gamma_mult"] for e in d["sweep"]]
fig.add_trace(go.Scatter(x=g, y=[e["error"] for e in d["sweep"]], mode="lines+markers",
name="RCB error rate", line=dict(color=P[0], width=2),
marker=dict(size=9)))
fig.add_trace(go.Scatter(x=g, y=[e["explore"] for e in d["sweep"]], mode="lines+markers",
name="forced exploration fraction",
line=dict(color=P[3], width=2), marker=dict(size=9)))
for yv, lab, col in [(0.35, "paper's reported 0.35", "#c0392b"),
(d["ceiling_error"], "offline oracle ceiling", "#4a3aa7"),
(d["physician_error"], "physician baseline", INK2)]:
fig.add_hline(y=yv, line=dict(color=col, width=2, dash="dot"),
annotation_text=lab, annotation_font_color=col)
base(fig, "Warfarin — RCB error rate vs exploration aggressiveness (γ multiplier)",
"multiplier on the spread parameter γ_m (log)", "rate", True)
fig.update_yaxes(range=[0, 0.62])
save(fig, "warfarin_gamma", [[e["gamma_mult"], e["error"], e["explore"], e["b_acc"],
e["score"]] for e in d["sweep"]],
["gamma_mult", "error", "explore_frac", "oracle_b_acc", "weighted_risk_score"])
if __name__ == "__main__":
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
for name in sys.argv[1:] or ["warfarin", "gamma", "feasibility", "Neps"]:
globals()[f"fig_{name}"]()
|