"""Offline reconstruction of published CBP size shares. Python standard library. No network, suppressed-cell reconstruction, modelled savings or firm-level records. """ from pathlib import Path import csv,hashlib,html,json from decimal import Decimal, getcontext getcontext().prec=32 BASE=Path(__file__).resolve().parent INDUSTRIES=[('541110','Offices of lawyers'),('541211','Offices of certified public accountants'), ('541213','Tax preparation services'),('541214','Payroll services'),('541219','Other accounting services')] BINS=[('<5','Fewer than 5'),('5_9','5–9'),('10_19','10–19'),('20_49','20–49'),('50_99','50–99'), ('100_249','100–249'),('250_499','250–499'),('500_999','500–999'),('1000','1,000 or more')] def percent(value,total): return Decimal(value)*100/Decimal(total) if value is not None else None def decimal_text(value): return '' if value is None else format(value.quantize(Decimal('0.0000000001')),'f') def available(raw,flag=None): if raw=='N' or flag=='N': return None if not raw.isascii() or not raw.isdecimal(): raise ValueError('Unexpected nonnumeric source cell') return int(raw) def write_csv(path,rows): with path.open('w',encoding='utf-8',newline='') as file: writer=csv.DictWriter(file,fieldnames=list(rows[0]),lineterminator='\n');writer.writeheader();writer.writerows(rows) def main(): selection=json.loads((BASE/'source-selection.json').read_text()) raw=(BASE/'selected-source.csv').read_bytes() if hashlib.sha256(raw).hexdigest()!=selection['selected_source_sha256']: raise ValueError('Selected-source bytes changed') rows=list(csv.DictReader(raw.decode('utf-8').splitlines()));assert len(rows)==5 bands=[];summary=[] for code,name in INDUSTRIES: found=[r for r in rows if r['naics']==code and r['uscode']=='98' and r['lfo']=='-'];assert len(found)==1 row=found[0];total_n=available(row['est']);total_e=available(row['emp'],row['emp_nf']);assert total_n and total_e cum_n=0;cum_e=0;median_n=None;median_e=None;median_e_before=None;median_e_after=None for key,label in BINS: n=available(row['n'+key]);e=available(row['e'+key],row['e'+key+'nf']) before_e=cum_e cum_n=cum_n+n if cum_n is not None and n is not None else None cum_e=cum_e+e if cum_e is not None and e is not None else None if median_n is None and cum_n is not None and Decimal(cum_n)>=Decimal(total_n)/2: median_n=label if median_e is None and cum_e is not None and Decimal(cum_e)>=Decimal(total_e)/2: median_e=label;median_e_before=percent(before_e,total_e);median_e_after=percent(cum_e,total_e) bands.append({'reference_year':2023,'naics':code,'industry':name,'size_class_key':key,'size_class':label, 'establishments_raw':row['n'+key],'mid_march_employment_raw':row['e'+key], 'employment_noise_flag':row['e'+key+'nf'],'establishments':n if n is not None else '', 'mid_march_employment':e if e is not None else '', 'establishment_share_percent':decimal_text(percent(n,total_n)), 'employment_share_percent':decimal_text(percent(e,total_e)), 'cumulative_establishment_share_percent':decimal_text(percent(cum_n,total_n)), 'cumulative_employment_share_percent':decimal_text(percent(cum_e,total_e)), 'source_csv_row':row['source_row']}) n10=available(row['n<5'])+available(row['n5_9']) e10=available(row['e<5'],row['e<5nf'])+available(row['e5_9'],row['e5_9nf']) nshare=percent(n10,total_n);eshare=percent(e10,total_e) summary.append({'reference_year':2023,'naics':code,'industry':name,'total_employer_establishments':total_n, 'total_mid_march_employment':total_e,'total_employment_noise_flag':row['emp_nf'], 'under10_establishments':n10,'under10_mid_march_employment':e10, 'under10_establishment_share_percent':decimal_text(nshare),'under10_employment_share_percent':decimal_text(eshare), 'difference_percentage_points':decimal_text(nshare-eshare), 'under10_employment_source_flags':row['e<5nf']+'/'+row['e5_9nf'], 'published_establishment_median_size_band':median_n, 'published_employment_weighted_median_size_band':median_e, 'employment_cumulative_before_median_percent':decimal_text(median_e_before), 'employment_cumulative_through_median_percent':decimal_text(median_e_after), 'unavailable_size_bins':sum(1 for key,_ in BINS if available(row['n'+key]) is None or available(row['e'+key],row['e'+key+'nf']) is None)}) out=BASE/'outputs';out.mkdir(exist_ok=True) write_csv(out/'size-bands.csv',bands);write_csv(out/'industry-summary.csv',summary) methods={'source_year':2023,'published_size_cells':45,'numeric_employment_cells':sum(b['mid_march_employment']!='' for b in bands), 'unavailable_cells_not_reconstructed':[{'naics':b['naics'],'size':b['size_class'],'raw_employment':b['mid_march_employment_raw'],'flag':b['employment_noise_flag']} for b in bands if b['mid_march_employment']==''], 'formula':'Each size-class count / its own industry total ×100. Under10 uses <5 and5–9 only. Difference is percentage points, not a percentage change.', 'median_formula':'First size bin where cumulative published count reaches half the reported industry total. Stop at any unavailable bin before crossing; never fill missing values.', 'median_caution':'Bands describe the published noise-infused distribution, not exact underlying medians. Other-accounting employment crosses50% near a bin boundary.', 'noise_caution':'G,H,J are disclosure-noise categories, not sampling confidence intervals. Values flaggedN remain unavailable even when the source numeric field is0.', 'industry_summary':summary} (out/'results.json').write_text(json.dumps(methods,indent=2)+'\n',encoding='utf-8') numeric=lambda value: 'Not available (N)' if value=='' else f'{int(value):,}' one=lambda value:'—' if value=='' else f'{Decimal(value):.1f}%' markup=[''] for b in bands: values=[b['industry']+' ('+b['naics']+')',b['size_class'],numeric(b['establishments']),one(b['establishment_share_percent']),numeric(b['mid_march_employment']),b['employment_noise_flag'],one(b['employment_share_percent'])] markup.append(''+''.join(('') for i,v in enumerate(values))+'') markup.append('
2023 U.S. employer establishments and published mid-March employment by establishment-size class. All legal forms; Census CBP. Employment is noise-infused. N means unavailable, including numeric0 with flagN.
Industry / NAICSSize classEstablishmentsShare of locationsReported March employmentNoise flagShare of employment
' if i==0 else '')+html.escape(v)+('' if i==0 else '
');(out/'size-bands.html').write_text('\n'.join(markup)+'\n',encoding='utf-8') print(json.dumps({'rows':len(bands),'industries':len(summary),'unavailable_bins':len(methods['unavailable_cells_not_reconstructed'])})) if __name__=='__main__':main()