"""MIT; NexLevel. Reproduce AHS results from broad aggregate inputs only. No network, accounts, household records or individual control keys are needed. The source-to-aggregate recipe separately accepts the original SHA-bound ZIP. """ from pathlib import Path from collections import defaultdict import argparse,csv,json,math Z90=1.6448536269514722 def calc(v): full=v[0];se=math.sqrt(.025*sum((r-full)**2 for r in v[1:])) return {'estimate':full,'standard_error':se,'confidence_level':.90,'ci90_low':full-Z90*se,'ci90_high':full+Z90*se} def compute(path): rows=list(csv.DictReader(path.open(encoding='utf-8',newline=''))) bands=['0-validation','1','2','3-4','5-7','8-41'];weight_ids=['full']+[f'replicate{i}'for i in range(1,161)] lookup={(r['band'],r['weight_id']):r for r in rows} if len(rows)!=966 or len(lookup)!=966 or set(lookup)!={(b,w)for b in bands for w in weight_ids}:raise ValueError('Expected six broad bands times full+160weights') def vec(subset,column):return[sum(float(lookup[b,w][column])for b in subset)for w in weight_ids] active=vec(bands[1:],'weighted_units');jobs=vec(bands[1:],'weighted_job_entries');owners=vec(bands,'weighted_units') if any(v<=0 or not math.isfinite(v)for v in active+jobs+owners):raise ValueError('Invalid denominator') ratio=lambda a,b:[x/y for x,y in zip(a,b)] unit5=ratio(vec(bands[4:],'weighted_units'),active);entry5=ratio(vec(bands[4:],'weighted_job_entries'),jobs) out={'active_owner_units':calc(active),'all_owner_units_validation':calc(owners),'reported_job_entries':calc(jobs), 'two_plus_unit_share':calc(ratio(vec(bands[2:],'weighted_units'),active)), 'five_plus_unit_share':calc(unit5),'five_plus_job_entry_share':calc(entry5), 'mean_entries_per_active_unit':calc(ratio(jobs,active)), 'five_plus_job_share_minus_unit_share':calc([a-b for a,b in zip(entry5,unit5)])} byband=[] for band in bands[1:]: byband.append({'band':band,'unit_share':calc(ratio(vec([band],'weighted_units'),active)), 'entry_share':calc(ratio(vec([band],'weighted_job_entries'),jobs))}) return {'primary_estimates':out,'bands':byband,'confidence':'90%normalapproximation; ordinary160replicateweights; samplinguncertaintyonly', 'scope':'2023AHSnationalv1.1; activeowner-occupiedunits; source-defined jobentries inprevious-two-yearswindow; nohouseholdidentifiers', 'precision':'Floating-point sums can differ below1e-5forpopulation totals and1e-10forratios; displayed estimates/intervals agree. No such precision is claimed for measurement.'} if __name__=='__main__': ap=argparse.ArgumentParser();ap.add_argument('aggregate_csv',type=Path);ap.add_argument('--output',type=Path);a=ap.parse_args();x=compute(a.aggregate_csv) if a.output:a.output.write_text(json.dumps(x,indent=2)+'\n',encoding='utf-8',newline='\n') print(json.dumps(x,indent=2))