# ===== NHANES 2005–2008: race/ethnicity, albuminuria, kidney function, eye history =====
# Works on its own (no other cells needed). Downloads nhanes_extra2.csv at the end.
import pandas as pd, numpy as np, io, urllib.request

def get(name, cycle_letter, year):
    urls = [f"https://wwwn.cdc.gov/Nchs/Data/Nhanes/Public/{year}/DataFiles/{name}_{cycle_letter}.xpt",
            f"https://wwwn.cdc.gov/Nchs/Nhanes/{year}-{year+1}/{name}_{cycle_letter}.XPT"]
    for u in urls:
        try:
            raw = urllib.request.urlopen(u, timeout=120).read()
            if raw[:6] == b"HEADER":
                return pd.read_sas(io.BytesIO(raw), format="xport")
        except Exception as e:
            print("  tried", u, "->", e)
    raise RuntimeError(f"Could not download {name}_{cycle_letter}")

out = []
for L, yr in [("D", 2005), ("E", 2007)]:
    demo = get("DEMO", L, yr)[["SEQN", "RIDRETH1", "RIAGENDR", "RIDAGEYR"]]
    alb  = get("ALB_CR", L, yr)
    bio  = get("BIOPRO", L, yr)[["SEQN", "LBXSCR"]]
    diq  = get("DIQ", L, yr)
    if not [c for c in alb.columns if c.upper() == "URDACT"]:
        alb["URDACT"] = alb["URXUMA"] / alb["URXUCR"] * 100
    eye = [c for c in ["DIQ080"] if c in diq.columns]
    out.append(demo.merge(alb[["SEQN", "URDACT"]], on="SEQN", how="left")
                   .merge(bio, on="SEQN", how="left").merge(diq[["SEQN"] + eye], on="SEQN", how="left"))
x = pd.concat(out, ignore_index=True)
scr, age, fem = x.LBXSCR, x.RIDAGEYR, x.RIAGENDR == 2          # eGFR, CKD-EPI 2021 (race-free)
k = np.where(fem, 0.7, 0.9); a = np.where(fem, -0.241, -0.302)
x["egfr"] = 142 * np.minimum(scr / k, 1) ** a * np.maximum(scr / k, 1) ** -1.200 * 0.9938 ** age * np.where(fem, 1.012, 1)
x = x.rename(columns={"URDACT": "acr", "RIDRETH1": "race_eth", "DIQ080": "dr_told"})
x[["SEQN", "race_eth", "acr", "egfr", "dr_told"]].to_csv("nhanes_extra2.csv", index=False)
try:
    from google.colab import files; files.download("nhanes_extra2.csv")
except ImportError:
    print("Saved nhanes_extra2.csv")
