# ===== Export measured blood pressure, albuminuria and the survey design frame =====
# Paste into a new cell in the same Colab session and run. Downloads nhanes_extra.zip.
# (If Colab has reset: Runtime -> Run all first, then run this cell.)
import zipfile
bpx = []
for s in ["D", "E"]:
    b = load("BPX", s)
    sy = b[[c for c in ["BPXSY1", "BPXSY2", "BPXSY3", "BPXSY4"] if c in b.columns]]
    di = b[[c for c in ["BPXDI1", "BPXDI2", "BPXDI3", "BPXDI4"] if c in b.columns]].where(lambda x: x > 0)
    bpx.append(pd.DataFrame({"SEQN": b.SEQN, "sbp": sy.mean(axis=1), "dbp": di.mean(axis=1)}))
bpx = pd.concat(bpx, ignore_index=True)
allc = pd.concat([build_cycle(s) for s in ["D", "E"]], ignore_index=True)
extra = allc[["SEQN", "acr"]].merge(bpx, on="SEQN", how="left")
extra[extra.SEQN.isin(df.SEQN)].to_csv("nhanes_extra.csv", index=False)
allc.loc[allc.age >= 40, ["SEQN", "age", "wt", "strata", "psu"]].to_csv("nhanes_design40.csv", index=False)
with zipfile.ZipFile("nhanes_extra.zip", "w") as z:
    z.write("nhanes_extra.csv"); z.write("nhanes_design40.csv")
try:
    from google.colab import files; files.download("nhanes_extra.zip")
except ImportError:
    print("Saved nhanes_extra.zip")
