# ===== Partial proportional odds model (HbA1c effect allowed to differ at PDR) =====
# Paste below the revision cell and run (same session). Saves nhanes_partialpo.zip.
def _ll_ppo(theta, y, X, j_np):
    """4-level stage (0..3). Cut-points c1<c2<c3; common betas; extra coefficient for column j_np at the PDR cut."""
    c = np.cumsum(np.r_[theta[0], np.exp(theta[1:3])]); b = theta[3:3 + X.shape[1]]; g = theta[-1]
    eta = X @ b
    S = [1 / (1 + np.exp(-(eta - c[0]))), 1 / (1 + np.exp(-(eta - c[1]))), 1 / (1 + np.exp(-(eta + g * X[:, j_np] - c[2])))]
    P = np.column_stack([1 - S[0], S[0] - S[1], S[1] - S[2], S[2]])
    return np.log(np.clip(P[np.arange(len(y)), y], 1e-12, None))

def fit_ppo(y, X, w, j_np):
    th0 = np.r_[-1.0, 0.0, 0.0, np.zeros(X.shape[1]), 0.0]
    f = lambda th: -(w * _ll_ppo(th, y, X, j_np)).sum() / w.sum()
    return minimize(f, th0, method="BFGS", options={"maxiter": 5000}).x

def design_se_ppo(y, X, w, j_np, strata, psu):
    sdx = X.std(0); sdx[sdx == 0] = 1; Xs = (X - X.mean(0)) / sdx; w = w / w.mean()
    th = fit_ppo(y, Xs, w, j_np); P = len(th); h = 1e-4
    S = np.zeros((len(y), P))
    for k in range(P):
        e = np.zeros(P); e[k] = h; S[:, k] = (_ll_ppo(th + e, y, Xs, j_np) - _ll_ppo(th - e, y, Xs, j_np)) / (2 * h)
    U = S * w[:, None]
    H = np.zeros((P, P))
    for a in range(P):
        ea = np.zeros(P); ea[a] = h
        for b_ in range(P):
            eb = np.zeros(P); eb[b_] = h
            H[a, b_] = (w * (_ll_ppo(th + ea + eb, y, Xs, j_np) - _ll_ppo(th + ea - eb, y, Xs, j_np)
                             - _ll_ppo(th - ea + eb, y, Xs, j_np) + _ll_ppo(th - ea - eb, y, Xs, j_np))).sum() / (4 * h * h)
    tot = pd.DataFrame(U).assign(h=strata, i=psu).groupby(["h", "i"]).sum().reset_index()
    M = np.zeros((P, P))
    for _, gdf in tot.groupby("h"):
        if len(gdf) > 1:
            d = gdf.iloc[:, 2:].values - gdf.iloc[:, 2:].values.mean(0); M += len(gdf) / (len(gdf) - 1) * d.T @ d
    Hi = np.linalg.pinv(-H); V = Hi @ M @ Hi
    # back to original HbA1c scale: beta_orig = beta_s / sd
    i_b = 3 + j_np; i_g = P - 1; s = sdx[j_np]
    b_mild = th[i_b] / s; se_b = np.sqrt(V[i_b, i_b]) / s
    b_pdr = (th[i_b] + th[i_g]) / s; se_pdr = np.sqrt(V[i_b, i_b] + V[i_g, i_g] + 2 * V[i_b, i_g]) / s
    se_g = np.sqrt(V[i_g, i_g]) / s; z = th[i_g] / np.sqrt(V[i_g, i_g])
    return b_mild, se_b, b_pdr, se_pdr, th[i_g] / s, se_g, z

ppo_rows = []
for label, cols in [("Crude", ["hba1c"]), ("Adjusted (duration, age)", ["hba1c", "duration", "age"])]:
    X = cc[cols].values.astype(float)
    bm, sm, bp, sp, g, sg, z = design_se_ppo(y4, X, cc.wt.values, 0, cc.strata.values, cc.psu.values)
    p = 2 * tdist.sf(abs(z), DF)
    ppo_rows.append({"Model": label, "n": len(cc),
                     "OR per 1% HbA1c, mild and moderate cut-points": f"{np.exp(bm):.2f} ({np.exp(bm-TCRIT*sm):.2f}–{np.exp(bm+TCRIT*sm):.2f})",
                     "OR per 1% HbA1c, PDR cut-point": f"{np.exp(bp):.2f} ({np.exp(bp-TCRIT*sp):.2f}–{np.exp(bp+TCRIT*sp):.2f})",
                     "Ratio of ORs (PDR vs lower)": f"{np.exp(g):.2f} ({np.exp(g-TCRIT*sg):.2f}–{np.exp(g+TCRIT*sg):.2f})",
                     "p for difference": f"{p:.2g}"})
ppo = pd.DataFrame(ppo_rows); print(ppo.to_string(index=False))
ppo.to_csv(f"{REV}/R7_partial_proportional_odds.csv", index=False)
with zipfile.ZipFile("nhanes_partialpo.zip", "w") as z_:
    z_.write(f"{REV}/R7_partial_proportional_odds.csv", "R7_partial_proportional_odds.csv")
try:
    from google.colab import files; files.download("nhanes_partialpo.zip")
except ImportError:
    print("Saved nhanes_partialpo.zip")
