# ===== REVISED ANALYSIS (Reviewer X) =====
# Paste into a new cell at the bottom of the notebook and run. Takes about 5-10 minutes.
# Needs: raw, df, OUT from the earlier cells. Saves nhanes_revision_results.zip.
import numpy as np, pandas as pd, json, os, zipfile
from scipy.optimize import minimize
from scipy.stats import t as tdist
from sklearn.metrics import roc_auc_score, roc_curve, cohen_kappa_score, confusion_matrix
from sklearn.model_selection import StratifiedKFold
RNG = np.random.default_rng(2026); B = 300
REV = "results_revision"; os.makedirs(REV, exist_ok=True)
log = {}

# ---------- 0. Rebuild the eligible sample with eye-level detail ----------
def col(df, *names):                                  # restore the notebook's lenient helper (used by build_cycle)
    for n in names:
        if n in df.columns: return df[n]
    return pd.Series(np.nan, index=df.index)

def col_strict(d, *names):
    for n in names:
        if n in d.columns: return d[n]
    raise KeyError(f"None of {names} found")          # no silent NaN columns any more

eye = []
for s in ["D", "E"]:
    o = raw[("OPXRET", s)]
    e = pd.DataFrame({"SEQN": o.SEQN,
                      "rl4_r": col_strict(o, "OPDDRL4"), "rl4_l": col_strict(o, "OPDSRL4"),
                      "ret_worse": col_strict(o, "OPDURET"),
                      "grbl_r": col_strict(o, "OPXDGRBL"), "grbl_l": col_strict(o, "OPXSGRBL"),
                      "me_r": col_strict(o, "OPDDME"), "me_l": col_strict(o, "OPDSME")})
    eye.append(e)
eye = pd.concat(eye, ignore_index=True)
full = pd.concat([build_cycle(s) for s in ["D", "E"]], ignore_index=True).merge(eye, on="SEQN", how="left")
elig = full[(full.age >= 40) & (full.dm_dx == 1)].copy()          # 1,174 expected
for c in ["rl4_r", "rl4_l"]: elig[c] = elig[c].where(elig[c].between(1, 4))
elig["n_grad"] = elig[["rl4_r", "rl4_l"]].notna().sum(axis=1)
photo_taken = elig[["grbl_r", "grbl_l"]].notna().any(axis=1)
elig["status"] = np.select([elig.n_grad > 0, photo_taken], ["Included (gradable)", "Photographed, ungradable"], "Not photographed")
elig.loc[(elig.status == "Included (gradable)") & elig.hba1c.isna(), "status"] = "Gradable, no HbA1c"
print(elig.status.value_counts())

# ---------- 1. Design-based estimation (domain analysis on the full design, t critical values) ----------
DES = full[full.age >= 40].reset_index(drop=True)                     # design frame keeps every PSU and stratum
N_PSU = DES.groupby(["strata", "psu"]).ngroups; N_STR = DES.strata.nunique()
DF = N_PSU - N_STR; TCRIT = tdist.ppf(0.975, DF)
log["design_df"] = int(DF)

def domain_mean(y, mask, frame=None):
    """Weighted mean of y over a domain, variance by linearization over the full design."""
    if frame is None: frame = DES
    d = (mask & y.notna()).astype(float).reindex(frame.index, fill_value=0)
    yy = y.reindex(frame.index).fillna(0); w = frame.wt.fillna(0)
    W = (w * d).sum(); m = (w * d * yy).sum() / W
    z = w * d * (yy - m) / W
    tot = pd.DataFrame({"z": z, "h": frame.strata, "i": frame.psu}).groupby(["h", "i"]).z.sum().reset_index()
    var = sum(len(g) / (len(g) - 1) * ((g.z - g.z.mean()) ** 2).sum() for _, g in tot.groupby("h") if len(g) > 1)
    se = np.sqrt(var); return m, m - TCRIT * se, m + TCRIT * se

def dprop(y, mask):
    m, lo, hi = domain_mean(y, mask); return m, max(lo, 0.0), min(hi, 1.0)

# attach eye detail to the analytic df
df = df.drop(columns=[c for c in ["rl4_r", "rl4_l", "ret_worse", "n_grad"] if c in df.columns]) \
       .merge(elig[["SEQN", "rl4_r", "rl4_l", "ret_worse", "n_grad"]], on="SEQN", how="left")
DES = DES.merge(df[["SEQN"]].assign(in_analysis=1), on="SEQN", how="left")
DES["in_analysis"] = DES.in_analysis.fillna(0).astype(bool)
DES = DES.merge(df[["SEQN", "dr_worse", "csme", "n_grad"]], on="SEQN", how="left", suffixes=("", "_a"))
INA = DES.in_analysis

# consistent stage definitions (CSME counted as sight-threatening everywhere)
for frame in (df, DES):
    frame["stage4"] = frame.dr_worse                                  # 1-4 NHANES levels (no CSME)
    frame["stage3"] = np.where(frame.dr_worse.isna(), np.nan,
                       np.where((frame.dr_worse >= 3) | (frame.csme == 1), 2, np.where(frame.dr_worse == 2, 1, 0)))
    # ICDR-aligned sensitivity grading from the detailed worse-eye level (OPDURET)
r = df.ret_worse
df["stage3_icdr"] = np.select([(r >= 31) | (df.csme == 1), r == 20], [2, 1], 0).astype(float)
df.loc[r.isna(), "stage3_icdr"] = df.loc[r.isna(), "stage3"]

# ---------- 2. Exclusions: who was dropped? ----------
rows = []
for st in ["Included (gradable)", "Gradable, no HbA1c", "Photographed, ungradable", "Not photographed"]:
    sub = elig[elig.status == st]
    if len(sub) == 0: continue
    rows.append({"Group": st, "n": len(sub), "Age, mean": round(np.average(sub.age, weights=sub.wt), 1),
                 "HbA1c, mean %": round(np.average(sub.hba1c.dropna(), weights=sub.wt[sub.hba1c.notna()]), 2) if sub.hba1c.notna().any() else None,
                 "Duration, median y": sub.duration.median(),
                 "Insulin, %": round(100 * np.average(sub.insulin.fillna(0), weights=sub.wt), 1)})
excl = pd.DataFrame(rows); print(excl.to_string(index=False)); excl.to_csv(f"{REV}/R1_exclusions.csv", index=False)

# ---------- 3. Table A redone: design-based HbA1c by stage ----------
DES_h = DES.merge(df[["SEQN", "hba1c"]], on="SEQN", how="left", suffixes=("_x", ""))
DES_h.index = DES.index
labs = {1: "No DR", 2: "Mild NPDR", 3: "Moderate to severe NPDR", 4: "PDR"}
tA = []
for k, lab in labs.items():
    m = INA & (DES.stage4 == k); v = domain_mean(DES_h.hba1c, m)
    tA.append({"Stage": lab, "n": int(m.sum()), "HbA1c weighted mean (95% CI)": f"{v[0]:.2f} ({v[1]:.2f}–{v[2]:.2f})"})
m = INA & (DES.csme == 1); v = domain_mean(DES_h.hba1c, m)
tA.append({"Stage": "CSME (any stage)", "n": int(m.sum()), "HbA1c weighted mean (95% CI)": f"{v[0]:.2f} ({v[1]:.2f}–{v[2]:.2f})"})
tA = pd.DataFrame(tA); print(tA.to_string(index=False)); tA.to_csv(f"{REV}/R2_hba1c_by_stage_design.csv", index=False)

# ---------- 4. Survey-weighted proportional-odds and cumulative-split logistic models ----------
def _ll_i(theta, y, X, K):
    cuts = np.cumsum(np.r_[theta[0], np.exp(theta[1:K - 1])]); b = theta[K - 1:]
    eta = X @ b
    F = lambda c: 1 / (1 + np.exp(-(c - eta)))
    cdf = np.column_stack([np.zeros(len(y))] + [F(c) for c in cuts] + [np.ones(len(y))])
    p = cdf[np.arange(len(y)), y + 1] - cdf[np.arange(len(y)), y]
    return np.log(np.clip(p, 1e-12, None))

def fit_po(y, X, w, K):
    """Weighted proportional-odds fit; y coded 0..K-1; returns params and per-observation log-lik fn."""
    th0 = np.r_[np.linspace(-1, 1, K - 1)[0], np.zeros(K - 2), np.zeros(X.shape[1])]
    f = lambda th: -(w * _ll_i(th, y, X, K)).sum() / w.sum()
    res = minimize(f, th0, method="BFGS", options={"maxiter": 5000})
    return res.x

def design_se(theta, y, X, w, K, strata, psu, n_beta):
    """Sandwich variance with linearization over PSUs within strata (computed on standardized X, rescaled back)."""
    sdx = X.std(0); sdx[sdx == 0] = 1; mux = X.mean(0)
    Xs = (X - mux) / sdx; w = w / w.mean()
    theta = fit_po(y, Xs, w, K)
    h = 1e-4; P = len(theta)
    X = Xs
    S = np.zeros((len(y), P))
    for j in range(P):
        e = np.zeros(P); e[j] = h
        S[:, j] = (_ll_i(theta + e, y, X, K) - _ll_i(theta - e, y, X, K)) / (2 * h)
    U = S * w[:, None]
    H = np.zeros((P, P))
    for j in range(P):
        e = np.zeros(P); e[j] = h
        gp = np.zeros(P); gm = np.zeros(P)
        for k in range(P):
            ek = np.zeros(P); ek[k] = h
            gp[k] = ((w * (_ll_i(theta + e + ek, y, X, K) - _ll_i(theta + e - ek, y, X, K))).sum()) / (2 * h)
            gm[k] = ((w * (_ll_i(theta - e + ek, y, X, K) - _ll_i(theta - e - ek, y, X, K))).sum()) / (2 * h)
        H[:, j] = (gp - gm) / (2 * h)
    tot = pd.DataFrame(U).assign(h=strata, i=psu).groupby(["h", "i"]).sum().reset_index()
    M = np.zeros((P, P))
    for _, g in tot.groupby("h"):
        if len(g) > 1:
            d = g.iloc[:, 2:].values - g.iloc[:, 2:].values.mean(0); M += len(g) / (len(g) - 1) * d.T @ d
    H = (H + H.T) / 2
    Hi = np.linalg.pinv(-H); V = Hi @ M @ Hi
    return np.sqrt(np.diag(V))[-n_beta:] / sdx

ORS = []
cc = df.dropna(subset=["hba1c", "duration", "age"]).copy()          # same n for crude and adjusted
log["n_ordinal_complete_case"] = len(cc)
y4 = (cc.stage4 - 1).astype(int).values; w = cc.wt.values
for label, cols in [("Crude", ["hba1c"]), ("Adjusted (duration, age)", ["hba1c", "duration", "age"])]:
    X = cc[cols].values.astype(float); th = fit_po(y4, X, w, 4)
    se = design_se(th, y4, X, w, 4, cc.strata.values, cc.psu.values, len(cols))
    b, s_ = th[3], se[0]
    ORS.append({"Model": f"Proportional odds, weighted: {label}", "n": len(cc), "OR per 1% HbA1c": round(np.exp(b), 2),
                "95% CI": f"{np.exp(b - TCRIT*s_):.2f}–{np.exp(b + TCRIT*s_):.2f}"})
# cumulative splits (checks the proportional-odds assumption: ORs should be similar)
for k, lab in [(2, "Split: mild NPDR or worse vs none"), (3, "Split: moderate NPDR or worse vs less"), (4, "Split: PDR vs less")]:
    yb = (cc.stage4 >= k).astype(int).values
    for label, cols in [("crude", ["hba1c"]), ("adjusted", ["hba1c", "duration", "age"])]:
        X = cc[cols].values.astype(float); th = fit_po(yb, X, w, 2)
        se = design_se(th, yb, X, w, 2, cc.strata.values, cc.psu.values, len(cols))
        b, s_ = th[1], se[0]
        ORS.append({"Model": f"{lab} ({label})", "n": len(cc), "OR per 1% HbA1c": round(np.exp(b), 2),
                    "95% CI": f"{np.exp(b - TCRIT*s_):.2f}–{np.exp(b + TCRIT*s_):.2f}"})
ORS = pd.DataFrame(ORS); print(ORS.to_string(index=False)); ORS.to_csv(f"{REV}/R3_weighted_ordinal_and_splits.csv", index=False)

# ---------- 5. HbA1c cut-offs: sensitivity/specificity at fixed 7, 8, 9% (design-based) ----------
cut_rows = []
DES_h["stage3"] = DES.stage3; DES_h["stage4"] = DES.stage4
for thr_lab, case in [("Any DR (incl. CSME)", DES_h.stage3 >= 1), ("Moderate NPDR or worse, or CSME", DES_h.stage3 == 2), ("PDR", DES_h.stage4 == 4)]:
    case = case & INA; noncase = INA & ~case & DES_h.stage3.notna()
    for c in [7, 8, 9]:
        pos = (DES_h.hba1c >= c).astype(float)
        se_ = dprop(pos, case); sp_ = dprop(1 - pos, noncase)
        cut_rows.append({"Threshold": thr_lab, "Cases": int(case.sum()), "HbA1c cut-off": f"≥{c}%",
                         "Sensitivity (95% CI)": f"{se_[0]:.2f} ({se_[1]:.2f}–{se_[2]:.2f})",
                         "Specificity (95% CI)": f"{sp_[0]:.2f} ({sp_[1]:.2f}–{sp_[2]:.2f})"})
    yv = case[INA].astype(int).values; xv = DES_h.hba1c[INA].values; auc_ = round(roc_auc_score(yv, xv), 3)
    for rr in cut_rows[-3:]: rr["Unweighted AUC of HbA1c"] = auc_
cuts = pd.DataFrame(cut_rows); print(cuts.to_string(index=False)); cuts.to_csv(f"{REV}/R4_fixed_cutoffs.csv", index=False)

# Youden J curve (descriptive): shows whether the optimum is flat
fig, ax = plt.subplots(figsize=(6, 4))
for lab, yv in [("Any DR", (df.stage3 >= 1)), ("Moderate+ or CSME", (df.stage3 == 2)), ("PDR", (df.stage4 == 4))]:
    fpr, tpr, thr = roc_curve(yv.astype(int), df.hba1c); keep = (thr > 5) & (thr < 11)
    ax.plot(thr[keep], (tpr - fpr)[keep], label=lab)
ax.set_xlabel("HbA1c cut-off (%)"); ax.set_ylabel("Youden J (sensitivity + specificity − 1)"); ax.legend()
plt.tight_layout(); plt.savefig(f"{REV}/R_fig_youden_curves.png", dpi=300); plt.close()

# ---------- 6. Stage prediction, all 842 with bootstrap optimism correction (primary) ----------
df["age_c"] = df.age.clip(upper=80)                                   # harmonize age top-codes (80 vs 85)
CLIN = ["duration", "age_c", "female", "insulin", "oral_med", "htn", "obese", "smoker", "mi"]
SM = {"S0: clinical only (no HbA1c)": CLIN,
      "S1: HbA1c only": ["hba1c"],
      "S2: HbA1c + duration": ["hba1c", "duration"],
      "S3: HbA1c + clinical": ["hba1c"] + CLIN}

class PO:
    def __init__(self, feats): self.f = feats
    def _X(self, d): return ((d[self.f].fillna(self.med) - self.mu) / self.sd).values.astype(float)
    def fit(self, d, ycol="stage3"):
        self.med = d[self.f].median().fillna(0); Xr = d[self.f].fillna(self.med)
        self.mu, self.sd = Xr.mean(), Xr.std().fillna(1).replace(0, 1)
        self.th = fit_po(d[ycol].astype(int).values, self._X(d), np.ones(len(d)), 3); return self
    def proba(self, d):
        th = self.th; cuts = np.cumsum(np.r_[th[0], np.exp(th[1:2])]); eta = self._X(d) @ th[2:]
        F = lambda c: 1 / (1 + np.exp(-(c - eta)))
        c1, c2 = F(cuts[0]), F(cuts[1])
        return np.column_stack([c1, c2 - c1, 1 - c2])

def ordinal_c(y, s):
    conc = tot = 0.0
    for a in range(3):
        for b_ in range(a + 1, 3):
            sa, sb = s[y == a], s[y == b_]
            if len(sa) and len(sb):
                d = sb[None, :] - sa[:, None]; conc += (d > 0).sum() + 0.5 * (d == 0).sum(); tot += d.size
    return conc / tot

def cal_slope(y, p):
    p = np.clip(p, 1e-6, 1 - 1e-6); lp = np.log(p / (1 - p))
    th = fit_po(y.astype(int), lp.reshape(-1, 1), np.ones(len(y)), 2); return th[1]

def pick_cuts(y, P):
    """Prespecified rule: thresholds on cumulative probabilities chosen by Youden in the fitting data."""
    def yj(yb, s):
        fpr, tpr, thr = roc_curve(yb, s); return thr[np.argmax(tpr - fpr)]
    return yj((y >= 1).astype(int), P[:, 1] + P[:, 2]), yj((y == 2).astype(int), P[:, 2])

def classify(P, c): return np.where(P[:, 2] >= c[1], 2, np.where(P[:, 1] + P[:, 2] >= c[0], 1, 0))

def metrics(y, P, c):
    pred = classify(P, c); cm = confusion_matrix(y, pred, labels=[0, 1, 2]); rec = cm.diagonal() / cm.sum(1).clip(min=1)
    return {"Ordinal C-index": ordinal_c(y, P @ np.arange(3)),
            "AUC, any DR": roc_auc_score((y >= 1).astype(int), P[:, 1] + P[:, 2]),
            "AUC, moderate+": roc_auc_score((y == 2).astype(int), P[:, 2]),
            "Cal. slope, any DR": cal_slope((y >= 1).astype(int), P[:, 1] + P[:, 2]),
            "Cal. slope, moderate+": cal_slope((y == 2).astype(int), P[:, 2]),
            "Weighted kappa": cohen_kappa_score(y, pred, weights="quadratic"),
            "Recall no DR": rec[0], "Recall mild": rec[1], "Recall moderate+": rec[2]}

def boot_eval(data, ycol="stage3", reps=B, tag="primary"):
    y = data[ycol].astype(int).values; out, apparent, boots = [], {}, {}
    fits = {n: PO(f).fit(data, ycol) for n, f in SM.items()}
    for n, m in fits.items():
        P = m.proba(data); apparent[n] = metrics(y, P, pick_cuts(y, P))
    opt = {n: {k: [] for k in apparent[n]} for n in SM}; app_b = {n: {k: [] for k in apparent[n]} for n in SM}
    for r_ in range(reps):
        idx = RNG.integers(0, len(data), len(data)); bd = data.iloc[idx]; yb = y[idx]
        if len(np.unique(yb)) < 3: continue
        for n, f in SM.items():
            m = PO(f).fit(bd, ycol); Pb = m.proba(bd); c = pick_cuts(yb, Pb)
            mb = metrics(yb, Pb, c); mo = metrics(y, m.proba(data), c)
            for k in mb: opt[n][k].append(mb[k] - mo[k]); app_b[n][k].append(mb[k])
    for n in SM:
        row = {"Analysis": tag, "Model": n}
        for k in apparent[n]:
            o = np.mean(opt[n][k]); corr = apparent[n][k] - o
            ab = np.array(app_b[n][k]); lo, hi = corr + np.percentile(ab, [2.5, 97.5]) - ab.mean()
            row[k] = f"{corr:.2f} ({lo:.2f}–{hi:.2f})"
        out.append(row)
    # paired differences vs S0 and S3 vs S1 (C-index and moderate+ AUC)
    diffs = []
    for a, b_ in [("S1: HbA1c only", "S0: clinical only (no HbA1c)"), ("S3: HbA1c + clinical", "S0: clinical only (no HbA1c)"), ("S3: HbA1c + clinical", "S1: HbA1c only")]:
        for k in ["Ordinal C-index", "AUC, moderate+"]:
            d_app = apparent[a][k] - apparent[b_][k]
            d_opt = np.mean(opt[a][k]) - np.mean(opt[b_][k])
            raw_d = np.array(app_b[a][k]) - np.array(app_b[b_][k]); dist = (d_app - d_opt) + raw_d - raw_d.mean()
            diffs.append({"Analysis": tag, "Comparison": f"{a.split(':')[0]} − {b_.split(':')[0]}", "Metric": k,
                          "Difference (95% CI)": f"{d_app - d_opt:+.3f} ({np.percentile(dist,2.5):+.3f} to {np.percentile(dist,97.5):+.3f})"})
    return pd.DataFrame(out), pd.DataFrame(diffs), fits

prim, prim_d, fits = boot_eval(df)
print(prim.to_string(index=False)); print(prim_d.to_string(index=False))

# ---------- 7. Secondary: cycle split (train 2005–06, test 2007–08) with bootstrap CIs on the test set ----------
tr, te = df[df.cycle == "D"], df[df.cycle == "E"]; yte = te.stage3.astype(int).values
sec = []
for n, f in SM.items():
    m = PO(f).fit(tr); c = pick_cuts(tr.stage3.astype(int).values, m.proba(tr)); Pt = m.proba(te)
    pt = metrics(yte, Pt, c); bs = {k: [] for k in pt}
    for _ in range(B):
        i = RNG.integers(0, len(te), len(te))
        if len(np.unique(yte[i])) < 3: continue
        for k, v in metrics(yte[i], Pt[i], c).items(): bs[k].append(v)
    sec.append({"Analysis": "cycle split", "Model": n, **{k: f"{pt[k]:.2f} ({np.percentile(bs[k],2.5):.2f}–{np.percentile(bs[k],97.5):.2f})" for k in pt}})
sec = pd.DataFrame(sec); print(sec.to_string(index=False))

# ---------- 8. Sensitivity analyses ----------
both, both_d, _ = boot_eval(df[df.n_grad == 2], reps=100, tag="both eyes gradable")
icdr, icdr_d, _ = boot_eval(df, ycol="stage3_icdr", reps=100, tag="ICDR-aligned grading")
allperf = pd.concat([prim, sec, both, icdr], ignore_index=True); allperf.to_csv(f"{REV}/R5_stage_prediction_all.csv", index=False)
pd.concat([prim_d, both_d, icdr_d]).to_csv(f"{REV}/R6_paired_differences.csv", index=False)
log["n_both_eyes_gradable"] = int((df.n_grad == 2).sum())
log["stage3_counts"] = df.stage3.value_counts().sort_index().to_dict()
log["stage3_icdr_counts"] = df.stage3_icdr.value_counts().sort_index().to_dict()

# ---------- 9. Calibration plots (10-fold cross-validated probabilities) ----------
fig, axes = plt.subplots(1, 2, figsize=(10, 4.5))
for ax, n in zip(axes, ["S0: clinical only (no HbA1c)", "S3: HbA1c + clinical"]):
    P = np.zeros((len(df), 3))
    for a, b_ in StratifiedKFold(10, shuffle=True, random_state=7).split(df, df.stage3):
        P[b_] = PO(SM[n]).fit(df.iloc[a]).proba(df.iloc[b_])
    for lab, p, yv in [("Any DR", P[:, 1] + P[:, 2], df.stage3 >= 1), ("Moderate+", P[:, 2], df.stage3 == 2)]:
        q = pd.qcut(p, 10, duplicates="drop"); g = pd.DataFrame({"p": p, "y": yv.astype(int).values}).groupby(q, observed=True).mean()
        ax.plot(g.p, g.y, "o-", label=lab)
    ax.plot([0, 1], [0, 1], "k:", lw=0.8); ax.set_title(n, fontsize=10)
    ax.set_xlabel("Predicted probability"); ax.set_ylabel("Observed proportion"); ax.legend()
plt.tight_layout(); plt.savefig(f"{REV}/R_fig_calibration.png", dpi=300); plt.close()

# ---------- 10. Export S0 (clinical-only stage model) for mBRSET, with the grading map fixed in advance ----------
m0 = fits["S0: clinical only (no HbA1c)"]
json.dump({"model": "proportional odds, 3 stages (0 none, 1 mild NPDR, 2 moderate+ or DME)",
           "features": m0.f, "theta": list(map(float, m0.th)), "note": "theta = [cut1, log(cut2-cut1), betas on standardized features]",
           "mean": m0.mu.to_dict(), "sd": m0.sd.to_dict(), "median_impute": m0.med.to_dict(),
           "age_cap": 80,
           "mBRSET_mapping": {"ICDR 0": 0, "ICDR 1 (microaneurysms only)": 1, "ICDR 2, 3, 4": 2, "DME present": 2},
           "primary_NHANES_grading": "NHANES 4-level worse eye; mild NPDR includes early NPDR (level 31)",
           "ICDR_aligned_sensitivity": "OPDURET: 10-15 none, 20 mild, >=31 moderate+, plus CSME"},
          open(f"{REV}/S0_model_for_mBRSET.json", "w"), indent=2)
json.dump(log, open(f"{REV}/revision_log.json", "w"), indent=2, default=str)

with zipfile.ZipFile("nhanes_revision_results.zip", "w") as z:
    for f in os.listdir(REV): z.write(os.path.join(REV, f), f)
try:
    from google.colab import files; files.download("nhanes_revision_results.zip")
except ImportError:
    print("Saved nhanes_revision_results.zip")
