#!/usr/bin/env python3
"""Reproduce the public benchmark CSV from the original NHANES XPT files. No network access.
Usage: python reproduce_weight_benchmarks.py /path/to/nhanes_files
Dependencies: numpy, pandas, scipy. Only published rows are printed; suppressed numbers remain unreported.
"""
from pathlib import Path
import sys, csv, hashlib
import numpy as np, pandas as pd
from scipy.stats import f,t
P=Path(sys.argv[1]); PUBLIC=Path(__file__).resolve().parent
EXPECTED={'DEMO_L.xpt': 'ca4374a158b493b8b0163e1388da21d57a18d1b9cecff2aa4e2fa2bec494fe23', 'BMX_L.xpt': '44440c416d9ad709e8b1708a5975378ab4d5b18edc39eb5015c2ae7186500170'}
for name,digest in EXPECTED.items():
 assert hashlib.sha256((P/name).read_bytes()).hexdigest()==digest, name
d=pd.read_sas(P/'DEMO_L.xpt',format='xport'); b=pd.read_sas(P/'BMX_L.xpt',format='xport'); assert d.SEQN.is_unique and b.SEQN.is_unique
x=d.merge(b,on='SEQN',how='left',validate='one_to_one').query('RIDSTATR==2').copy(); w=x.WTMEC2YR.to_numpy(); wt=x.BMXWT.to_numpy(); adult=x.RIDAGEYR.to_numpy()>=20; valid=adult&np.isfinite(wt); clean=valid&x.BMIWT.isna().to_numpy(); missing=adult&~valid; print('domain',len(x),adult.sum(),valid.sum(),clean.sum(),missing.sum(),100*w[missing].sum()/w[adult].sum()); groups=x[['SDMVSTRA','SDMVPSU']].to_numpy(); strata=np.unique(groups[:,0]); pairs=[[(groups[:,0]==s)&(groups[:,1]==p) for p in np.unique(groups[groups[:,0]==s,1])] for s in strata]; assert all(len(g)==2 for g in pairs); df=len(strata)

def est(th,dom):
 n=int(dom.sum()); above=wt>th; denom=sum(w[dom]); pp=sum(w[dom&above])/denom; count=int((dom&above).sum()); z=np.zeros(len(w)); z[dom]=w[dom]*(above[dom].astype(float)-pp)/denom
 var=0
 for g in pairs:
  cluster=np.array([sum(z[i]) for i in g]); var+=2*((cluster-cluster.mean())**2).sum()
 if pp==0 or pp==1 or var==0: return dict(n=n,positive_n=count,pct=pp*100,lo=None,hi=None,se=None,screen=False,effective_n=None,df=df)
 ne=pp*(1-pp)/var; ne_adj=min(n,ne*(t.ppf(.975,n-1)/t.ppf(.975,df))**2); a=pp*ne_adj; bb=ne_adj-a
 # equivalent exact beta quantiles using F quantiles
 fl=f.ppf(.025,2*a,2*(bb+1)); fu=f.ppf(.975,2*(a+1),2*bb); lo=a*fl/(bb+1+a*fl); hi=(a+1)*fu/(bb+(a+1)*fu); width=hi-lo
 screen=n>=30 and min(n,ne)>=30 and df>=8 and count>0 and width<.30 and not(width>.05 and width/pp>1.30)
 return dict(n=n,positive_n=count,pct=pp*100,lo=lo*100,hi=hi*100,se=var**.5*100,screen=bool(screen),effective_n=min(n,ne),df=df)

fields=['estimated_percent_above','ci95_lower_percent','ci95_upper_percent','exclude_measurement_comments_percent','missing_weight_all_below_percent','missing_weight_all_above_percent']
lookup={}
for row in csv.DictReader((PUBLIC/'threshold_benchmarks.csv').open()):
 v,u=float(row['threshold']),row['printed_unit']; th=v*(.45359237 if u=='lb' else 1); a=est(th,valid); c=est(th,clean); bounds=[100*sum(w[valid&(wt>th)])/sum(w[adult]),100*(sum(w[valid&(wt>th)])+sum(w[missing]))/sum(w[adult])]
 show=bool(a['screen'] and a['positive_n']>=30 and th/.45359237<400 and a['lo'] is not None); assert (row['reporting']=='DISPLAY')==show; assert abs(float(row['threshold_kg'])-th)<1e-9
 for key,val in zip(fields,[a['pct'],a['lo'],a['hi'],c['pct'],*bounds]):
  if show: assert abs(float(row[key])-val)<.000051
  else: assert row[key]==''
 lookup[v,u]=row
for row in csv.DictReader((PUBLIC/'product_label_threshold_mapping.csv').open()):
 q=lookup[float(row['threshold']),row['printed_unit']]
 for key in fields+['reporting','threshold_kg']: assert row[key]==q[key]
print('All published benchmark and mapping values reproduced; suppressed cells remain blank.')
