Srishti280992's picture
Add incentivized exploration reproduction bundle
b381c58 verified
Raw
History Blame Contribute Delete
4.72 kB
"""Environments: synthetic stochastic-covariate linear bandit (Appendix F.1
Settings 1-4) and the PharmGKB / IWPC warfarin dosing environment (Section 5.1)."""
import numpy as np
import pandas as pd
class SyntheticEnv:
"""Stochastic covariates x_t ~ P_X (uniform on the unit sphere, so ||x||=1
as Corollary 1 assumes and Sigma = I/d, phi0 = 1/d), arm parameters drawn
from the public Gaussian prior beta_i ~ N(beta_{i,0}, Sigma_{i,0}).
Mean rewards mu(x,i) = offset + x'beta_i are kept inside [0,1] (the paper's
model assumes mu(x_t) in [0,1]^K) via offset = 0.5.
"""
def __init__(self, K, d, sigma, beta0, Sigma0, offset=0.5, rng=None):
self.K, self.d, self.sigma, self.offset = K, d, float(sigma), float(offset)
self.rng = rng if rng is not None else np.random.default_rng(0)
self.beta = np.array([
self.rng.multivariate_normal(np.asarray(beta0[i], float),
np.asarray(Sigma0[i], float))
for i in range(K)])
self.phi0 = 1.0 / d # lambda_min(E[xx']) for the unit sphere
def context(self):
z = self.rng.standard_normal(self.d)
return z / np.linalg.norm(z)
def mean_rewards(self, x):
return self.offset + self.beta @ x
def pull(self, x, arm):
return float(self.mean_rewards(x)[arm] + self.sigma * self.rng.standard_normal())
# ------------------------------------------------------------------ warfarin
DOSE_COL = "Therapeutic Dose of Warfarin"
def build_warfarin(csv_path):
"""Feature construction per Appendix F.4: demographics, diagnosis, pre-existing
diagnoses, three medications, CYP2C9 + VKORC1 genotypes; categoricals -> dummies;
all missing values -> 0. Target: dose bucket Low <3, Medium 3-7, High >7 mg/day."""
df = pd.read_csv(csv_path, low_memory=False)
df = df[df[DOSE_COL].notna()].reset_index(drop=True)
feats = {}
# -- Demographics ------------------------------------------------------
g = df.get("Gender")
feats["male"] = (g == "male").astype(float) if g is not None else 0.0
feats["female"] = (g == "female").astype(float) if g is not None else 0.0
for r in ["White", "Asian", "Black or African American", "Unknown"]:
feats[f"race_{r}"] = (df["Race (OMB)"] == r).astype(float)
for e in df["Ethnicity (OMB)"].dropna().unique():
feats[f"eth_{e}"] = (df["Ethnicity (OMB)"] == e).astype(float)
age = df["Age"].astype(str).str.extract(r"(\d+)")[0].astype(float) / 10.0
feats["age"] = age.fillna(0.0)
for c in ["Height (cm)", "Weight (kg)"]:
v = pd.to_numeric(df[c], errors="coerce").fillna(0.0)
feats[c] = v / (v.max() if v.max() > 0 else 1.0)
# -- Diagnosis (reason for treatment): 1 if a reason is recorded --------
ind = df["Indication for Warfarin Treatment"].astype(str)
for k, code in enumerate(["1", "2", "3", "4", "5", "6", "7", "8"]):
feats[f"indication_{code}"] = ind.str.contains(code, regex=False).astype(float)
feats["indication_known"] = (df["Indication for Warfarin Treatment"].notna()).astype(float)
# -- Pre-existing diagnoses -------------------------------------------
for c in ["Diabetes", "Congestive Heart Failure and/or Cardiomyopathy",
"Valve Replacement", "Current Smoker"]:
feats[c] = pd.to_numeric(df[c], errors="coerce").fillna(0.0).clip(0, 1)
# -- Medications: aspirin, Tylenol, Zocor only (rest set to 0) ---------
for c in ["Aspirin", "Acetaminophen or Paracetamol (Tylenol)", "Simvastatin (Zocor)"]:
feats[c] = pd.to_numeric(df[c], errors="coerce").fillna(0.0).clip(0, 1)
# -- Genetics: CYP2C9 + VKORC1 consensus dummies -----------------------
cyp = df["CYP2C9 consensus"].fillna("missing")
for lv in ["*1/*1", "*1/*2", "*1/*3", "*2/*2", "*2/*3", "*3/*3", "*1/*5",
"*1/*6", "*1/*11", "*1/*13", "*1/*14", "missing"]:
feats[f"cyp_{lv}"] = (cyp == lv).astype(float)
for snp in ["-1639", "497", "1173", "1542", "3730", "2255", "-4451"]:
col = f"VKORC1 {snp} consensus"
if col in df.columns:
v = df[col].fillna("missing")
for lv in sorted(v.unique()):
feats[f"vk{snp}_{lv}"] = (v == lv).astype(float)
feats["gender_missing"] = df["Gender"].isna().astype(float)
X = pd.DataFrame(feats).astype(float).fillna(0.0)
X = X.loc[:, X.std(axis=0) > 0] # drop all-constant columns
X.insert(0, "intercept", 1.0)
dose = df[DOSE_COL].astype(float) / 7.0 # mg/week -> mg/day
arm = np.where(dose < 3.0, 0, np.where(dose <= 7.0, 1, 2))
return X.values, arm, dose.values, list(X.columns)