"""NexLevel independent AHS concentration analysis; offline, Python3 only. Original computation from a frozen Census public-use ZIP. No household-level records/CONTROL keys are exported. Counts describe survey-defined job entries. """ from pathlib import Path from collections import Counter import argparse,csv,datetime,hashlib,io,json,math,zipfile SOURCE_SHA='720aaa18198f23f1d25b19630ba97105394f653f32acf6e3f907235bd2d73ac0' BANDS=[('1',1,1),('2',2,2),('3-4',3,4),('5-7',5,7),('8-41',8,41)] Z90=1.6448536269514722 def clean(s):return s.strip().strip("'") def digest(path): h=hashlib.sha256() with path.open('rb')as f: for b in iter(lambda:f.read(1024*1024),b''):h.update(b) return h.hexdigest() def ci(values): theta=values[0];variance=sum((x-theta)**2 for x in values[1:])*(4/160) se=math.sqrt(variance) return {'estimate':theta,'standard_error':se,'confidence_level':.90,'ci90_low':theta-Z90*se,'ci90_high':theta+Z90*se,'variance':variance} def run(source,output): if digest(source)!=SOURCE_SHA:raise ValueError('Frozen source ZIP SHA differs; no silent version substitution') weights=['WEIGHT']+[f'REPWEIGHT{i}'for i in range(1,161)] # Keep exact-count sums private for validation; public reproduction uses broad bands. units=[[0.0]*161 for n in range(42)];sample=[0]*42 all_owners=[0.0]*161;status=Counter();edit_flags=Counter();seen=set();owner_keys=set();invalid=[];mismatch=[] with zipfile.ZipFile(source)as z: with z.open('project.csv')as file: projects=Counter(clean(r['CONTROL'])for r in csv.DictReader(io.TextIOWrapper(file,encoding='utf-8-sig',newline=''))) with z.open('household.csv')as file: for r in csv.DictReader(io.TextIOWrapper(file,encoding='utf-8-sig',newline='')): status['source_household_rows']+=1;key=clean(r['CONTROL']) if key in seen:raise ValueError('Duplicate household CONTROL; stop') seen.add(key) if clean(r['INTSTATUS'])!='1'or clean(r['TENURE'])!='1':continue owner_keys.add(key) status['unweighted_owner_occupied']+=1 try: count=int(clean(r['REMODJOBS'])) if count<0 or count>41:raise ValueError('count outside0..41; not converted tozero') w=[float(clean(r[x]))for x in weights] if not all(math.isfinite(v)and v>=0 for v in w):raise ValueError('invalid/negative/nonfinite weight') except (ValueError,KeyError)as e:invalid.append(str(e));continue if projects[key]!=count:mismatch.append({'reported_count':count,'project_rows':projects[key]}) edit_flags[clean(r['JREMODJOBS'])]+=1;sample[count]+=1 for j,value in enumerate(w):units[count][j]+=value;all_owners[j]+=value outside_owner=set(projects)-owner_keys if invalid or mismatch or outside_owner:raise ValueError(f'Hold: invalid owner records={len(invalid)}, project-count mismatches={len(mismatch)}, outside-owner project keys={len(outside_owner)}') active=[sum(units[n][j]for n in range(1,42))for j in range(161)] jobs=[sum(n*units[n][j]for n in range(1,42))for j in range(161)] if not all(x>0 for x in active+jobs+all_owners):raise ValueError('Nonpositive full/replicate denominator') def sums(low,high,job=False):return[sum((n if job else 1)*units[n][j]for n in range(low,high+1))for j in range(161)] def ratio(n,d):return[x/y for x,y in zip(n,d)] two=sums(2,41);five=sums(5,41);five_jobs=sums(5,41,True) unit5=ratio(five,active);job5=ratio(five_jobs,jobs) primary={ 'active_owner_units':ci(active),'all_owner_units_validation':ci(all_owners),'reported_job_entries':ci(jobs), 'two_plus_unit_share':ci(ratio(two,active)), 'five_plus_unit_share':ci(unit5),'five_plus_job_entry_share':ci(job5), 'mean_entries_per_active_unit':ci(ratio(jobs,active)), 'five_plus_job_share_minus_unit_share':ci([a-b for a,b in zip(job5,unit5)])} bands=[];aggregate=[] for label,lo,hi in [('0-validation',0,0)]+BANDS: u=sums(lo,hi);v=sums(lo,hi,True);n=sum(sample[lo:hi+1]) if lo>0:bands.append({'band':label,'unweighted_active_units':n,'unweighted_job_entries':sum(k*sample[k]for k in range(lo,hi+1)),'weighted_units':ci(u),'weighted_job_entries':ci(v),'active_unit_share':ci(ratio(u,active)),'job_entry_share':ci(ratio(v,jobs))}) for j in range(161):aggregate.append({'band':label,'weight_id':'full'if j==0 else f'replicate{j}','unweighted_units':n,'weighted_units':format(u[j],'.17g'),'weighted_job_entries':format(v[j],'.17g')}) assert sum(b['unweighted_active_units']for b in bands)==sum(sample[1:]) result={'study_id':'NX-AHS-01','computed_at_UTC':datetime.datetime.now(datetime.timezone.utc).isoformat(),'source_zip_SHA256':SOURCE_SHA, 'source_release':'2023 AHS National Public Use File v1.1','source_period':'Rolling previous24months before2023interview; not calendar2022-2023 or annual2026', 'unit':'Owner-occupied housing unit, occupied interview INTSTATUS1/TENURE1. REMODJOBS is source-defined edited public-use job-entry count, not unrestricted real-world project or concurrent-task count.', 'raw_household_rows':status['source_household_rows'],'source_project_rows':sum(projects.values()),'outside_owner_project_keys':len(outside_owner),'unweighted_owner_units':status['unweighted_owner_occupied'],'unweighted_active_owner_units':sum(sample[1:]),'unweighted_job_entries':sum(n*sample[n]for n in range(1,42)), 'invalid_owner_records':len(invalid),'project_row_count_mismatches_in_owner_universe':len(mismatch), 'variance_method':'160ordinaryreplicateweights; recompute whole ratio for everyreplicate; variance=.025*sum((theta_r-theta_full)^2);90%normalintervalz=1.6448536269514722; no binomialSE or independence assumption for correlateddifference.', 'primary_estimates':primary,'bands':bands, 'limits':['Not a new NexLevel survey, customer study, household experiment or app-effect evaluation.','Survey recall, editing/imputation, grouped project definitions and nonsampling error remain; interval covers sampling uncertainty only.','No simultaneous-work, annual/current-demand, spending, DIY, region, need, quality, safety or savings inference.','No first-ever analysis claim; prior-art screen bounded.']} output.mkdir(parents=True,exist_ok=True) (output/'results.json').write_text(json.dumps(result,indent=2)+'\n',encoding='utf-8',newline='\n') with(output/'replicate-band-input.csv').open('w',encoding='utf-8',newline='')as f: w=csv.DictWriter(f,fieldnames=list(aggregate[0]),lineterminator='\n');w.writeheader();w.writerows(aggregate) # Exact sparse cells and edit-flag interpretations are deliberately not exported. print(json.dumps({'source_rows':result['raw_household_rows'],'unweighted_active_units':result['unweighted_active_owner_units'],'primary_estimates':primary},indent=2)) if __name__=='__main__': ap=argparse.ArgumentParser();ap.add_argument('source_zip',type=Path);ap.add_argument('--output',type=Path,required=True);a=ap.parse_args();run(a.source_zip,a.output)