"""METR21 actual-source study. Python standard library only.

Read three factual native CSV exports;reconstruct analytical frames and deterministic
group folds. No engine,derived CSV,expected coefficients or model-answer import.
Native R binary64 measurements are recovered from their17-digit exports then represented
as exact Fraction storage values;this does not claim exact real-world measurement.
Actual-source AIPW uses the declared exact1/1000 grid,ties to even,then1/20 clipping.
PLR uses unrounded exact nuisance predictions. No inference/causality certificate.
"""
from pathlib import Path
from fractions import Fraction as Q
from collections import defaultdict,Counter
import argparse,csv,json,hashlib,sys
sys.set_int_max_str_digits(200000)
ZERO=Q(0);ONE=Q(1);LAM=Q(1,100);CLIP=Q(1,20);GRID=1000;K=5
FILES={'country':'actual2500-county-mpdta-all6-fields.csv','person':'actual38408-NSW-all15-fields.csv','company':'actual410-NJPA-all46-fields.csv'}
def factual(p):
 with p.open(encoding='utf-8-sig',newline='')as f:return list(csv.DictReader(f))
def native(s):return None if s=='.'else Q.from_float(float(s))
def encoded(v):
 if v is None:return''
 if isinstance(v,(list,dict)):return json.dumps(v,ensure_ascii=False,separators=(',',':'),default=str)
 return str(v)
def write_csv(p,rr,head):
 with p.open('w',encoding='utf8',newline='')as f:
  w=csv.DictWriter(f,fieldnames=head);w.writeheader();w.writerows({k:encoded(r.get(k))for k in head}for r in rr)
def reconstruct(source):
 raw={k:factual(source/v)for k,v in FILES.items()};assert[len(raw[k])for k in FILES]==[2500,38408,410]
 models={};ledger=[];by=defaultdict(dict)
 for r in raw['country']:by[r['countyreal']][int(r['year'])]=r
 rr=[]
 for key,g in by.items():
  a,b=g[2003],g[2007];cohort=int(b['first.treat']);eligible=cohort in[0,2007];idx='county:'+str(int(key))
  ledger.append(dict(kind='country',id=idx,nativeID=key,sourceRows=[int(r['sourceRow'])for r in g.values()],eligible=eligible,reason=''if eligible else'earlier-cohort-outside-declared-target',nativeTreatment=cohort))
  if eligible:rr.append(dict(id=idx,group=idx,y=native(b['lemp']),d=Q(cohort==2007),x=[native(a['lemp']),native(a['lpop'])],sourceRows=[int(a['sourceRow']),int(b['sourceRow'])],nativeID=key))
 models['country']=rr;by=defaultdict(dict)
 for r in raw['person']:by[r['id']][int(r['year'])]=r
 rr=[]
 for key,g in by.items():
  a,b=g[1975],g[1978];eligible=a['experimental']=='1';idx='nsw-id:'+str(int(key));assert(a['treated']!='.')==eligible
  ledger.append(dict(kind='person',id=idx,nativeID=key,sourceRows=[int(a['sourceRow']),int(b['sourceRow'])],eligible=eligible,reason=''if eligible else'outside-full-experimental-frame',nativeTreatment=a['treated']))
  if eligible:
   assert a['treated']==b['treated']and a['re74']==b['re74']and a['black']==b['black']
   rr.append(dict(id=idx,group=idx,y=native(b['re']),d=Q(a['treated']),x=[native(a['re74']),native(a['black'])],sourceRows=[int(a['sourceRow']),int(b['sourceRow'])],nativeID=key))
 models['person']=rr;rr=[]
 for r in raw['company']:
  def fte(suffix):
   ss=[r[t+suffix]for t in['EMPFT','NMGRS','EMPPT']]
   return None if'.'in ss else Q(ss[0])+Q(ss[1])+Q(ss[2])/2
  pre,post=fte(''),fte('2');eligible=pre is not None and post is not None;idx='njpa-row:'+r['sourceRow']
  ledger.append(dict(kind='company',id=idx,nativeID=r['SHEET'],sourceRows=[int(r['sourceRow'])],eligible=eligible,reason=''if eligible else'baseline-FTE-missing'if pre is None else'post-FTE-missing',nativeTreatment=r['STATE']))
  if eligible:rr.append(dict(id=idx,group='sheet:'+r['SHEET'],y=post,d=Q(r['STATE']),x=[pre]+[Q(int(r['CHAIN'])==j)for j in[2,3,4]]+[Q(r['CO_OWNED'])],sourceRows=[int(r['sourceRow'])],nativeID=r['SHEET']))
 models['company']=rr
 for kind,rr in models.items():
  groups=sorted({r['group']for r in rr},key=lambda g:(hashlib.sha256(('METR21|'+kind+'|'+g).encode('utf8')).hexdigest(),g));folds={g:i%K for i,g in enumerate(groups)}
  for r in rr:assert None not in r['x']and r['y']is not None;r['fold']=folds[r['group']];r['weight']=ONE
 assert[len(models[k])for k in FILES]==[440,722,384]
 return models,ledger
def solve(A,b):
 # Full rank on every declared actual-source training arm with positive ridge.
 n=len(b);R=[row[:]+[b[i]]for i,row in enumerate(A)]
 for j in range(n):
  k=next((k for k in range(j,n)if R[k][j]),None)
  if k is None:raise ValueError('actual-source-positive-ridge-normal-matrix-singular')
  R[j],R[k]=R[k],R[j];d=R[j][j]
  for t in range(j,n+1):R[j][t]/=d
  for k in range(n):
   if k==j:continue
   d=R[k][j]
   for t in range(j,n+1):R[k][t]-=d*R[j][t]
 return[row[-1]for row in R]
def fit(training,response):
 if not training:raise ValueError('empty-declared-training-arm')
 p=len(training[0]['x']);n=p+1;mass=Q(len(training));mins=[min(r['x'][j]for r in training)for j in range(p)];ranges=[max(r['x'][j]for r in training)-mins[j]or ONE for j in range(p)]
 def design(x):return[ONE]+[(x[j]-mins[j])/ranges[j]for j in range(p)]
 Z=[design(r['x'])for r in training];G=[[sum(z[j]*z[k]for z in Z)/mass+(LAM if j==k and j>0 else ZERO)for k in range(n)]for j in range(n)];h=[sum(z[j]*r[response]for z,r in zip(Z,training))/mass for j in range(n)];beta=solve(G,h)
 predict=lambda x:sum(v*b for v,b in zip(design(x),beta));mse=sum((r[response]-predict(r['x']))**2 for r in training)/mass;pen=LAM*sum(b*b for b in beta[1:])
 return dict(minima=mins,ranges=ranges,beta=beta,G=G,h=h,predict=predict,n=len(training),MSE=mse,penalty=pen,objective=mse+pen,training=training)
def variance(values,groups,den):
 gg=defaultdict(Q)
 for s,g in zip(values,groups):gg[g]+=s
 return sum(s*s for s in values)/(den*den),sum(s*s for s in gg.values())/(den*den)
def study(models):
 tables={name:[]for name in['model-frame','fold-training-membership','fold-fit-metrics','fold-coefficients','fold-crossproducts','heldout-predictions','residual-scores','propensity-ledger','aipw-pseudo-outcomes','source-estimates','source-chart-points']}
 for kind,rr in models.items():
  pred={r['id']:{**r}for r in rr}
  for r in rr:tables['model-frame'].append(dict(kind=kind,**r))
  for k in range(K):
   train=[r for r in rr if r['fold']!=k];test=[r for r in rr if r['fold']==k]
   for name in['ell','m','mu0','mu1']:
    tt=[r for r in train if name not in['mu0','mu1']or r['d']==int(name[-1])];f=fit(tt,'d'if name=='m'else'y')
    tables['fold-fit-metrics'].append(dict(kind=kind,fold=k,target=name,nTrain=f['n'],nTest=len(test),rank=len(f['beta']),lambdaValue=LAM,MSE=f['MSE'],penalty=f['penalty'],objective=f['objective'],minima=f['minima'],ranges=f['ranges']))
    for r in tt:tables['fold-training-membership'].append(dict(kind=kind,fold=k,target=name,id=r['id'],group=r['group'],sourceRows=r['sourceRows']))
    for j,b in enumerate(f['beta']):tables['fold-coefficients'].append(dict(kind=kind,fold=k,target=name,index=j,beta=b,minimum=None if j==0 else f['minima'][j-1],range=None if j==0 else f['ranges'][j-1],RHS=f['h'][j]))
    for j,row in enumerate(f['G']):
     for l,v in enumerate(row):tables['fold-crossproducts'].append(dict(kind=kind,fold=k,target=name,row=j,column=l,value=v))
    for r in test:pred[r['id']][name]=f['predict'](r['x'])
  pp=[pred[r['id']]for r in rr];mass=Q(len(rr));num=den=ZERO
  for r in pp:r['U']=r['y']-r['ell'];r['V']=r['d']-r['m'];r['VU']=r['V']*r['U'];r['V2']=r['V']**2;num+=r['VU'];den+=r['V2']
  if not den:raise ValueError('actual-source-zero-residual-variation')
  theta=num/den
  for r in pp:
   r['psi']=r['V']*(r['U']-theta*r['V']);r['grid']=Q(round(r['m']*GRID),GRID);r['used']=max(CLIP,min(ONE-CLIP,r['grid']));r['clipped']=r['grid']!=r['used'];r['pseudo']=r['mu1']-r['mu0']+((r['y']-r['mu1'])/r['used']if r['d']else-(r['y']-r['mu0'])/(ONE-r['used']))
  tau=sum(r['pseudo']for r in pp)/mass;plrV=variance([r['psi']for r in pp],[r['group']for r in pp],den);aipwV=variance([r['pseudo']-tau for r in pp],[r['group']for r in pp],mass)
  assert sum(r['psi']for r in pp)==0
  unit={'country':'log teen-employment points','person':'recorded real earnings','company':'FTE employees'}[kind]
  metrics={'rows':mass,'groups':Q(len({r['group']for r in pp})),'treated':sum(r['d']for r in pp),'comparison':mass-sum(r['d']for r in pp),'PLRtheta':theta,'PLRnumerator':num,'PLRdenominator':den,'PLRnormalization':den/mass,'PLRmeanScore':sum(r['psi']for r in pp)/mass,'PLRrowHC0':plrV[0],'PLRgroupHC0':plrV[1],'AIPWtheta':tau,'AIPWnumerator':sum(r['pseudo']for r in pp),'AIPWrowHC0':aipwV[0],'AIPWgroupHC0':aipwV[1],'rawPropensityMin':min(r['m']for r in pp),'rawPropensityMax':max(r['m']for r in pp),'grid':Q(GRID),'clip':CLIP,'clippedRows':Q(sum(r['clipped']for r in pp)),'lambda':LAM}
  for name,v in metrics.items():
   metricunit='rows'if name in['rows','treated','comparison','clippedRows']else'groups'if name=='groups'else unit if name in['PLRtheta','PLRnumerator','PLRmeanScore','AIPWtheta','AIPWnumerator']else'('+unit+') squared'if name.endswith('HC0')else'dimensionless'
   tables['source-estimates'].append(dict(kind=kind,metric=name,value=v,unit=metricunit))
  for i,r in enumerate(pp):
   basic=dict(kind=kind,index=i,id=r['id'],group=r['group'],fold=r['fold']);tables['heldout-predictions'].append({**basic,**{j:r[j]for j in['y','d','ell','m','mu0','mu1']}});tables['residual-scores'].append({**basic,**{j:r[j]for j in['U','V','VU','V2','psi']}});tables['propensity-ledger'].append({**basic,'raw':r['m'],'grid':r['grid'],'used':r['used'],'gridDelta':r['grid']-r['m'],'clipped':r['clipped']});tables['aipw-pseudo-outcomes'].append({**basic,'y':r['y'],'d':r['d'],'mu0':r['mu0'],'mu1':r['mu1'],'used':r['used'],'pseudo':r['pseudo'],'centeredScore':r['pseudo']-tau})
   for chart,series,x,y in [('outcomes','observed',Q(i),r['y']),('outcomes','ell',Q(i),r['ell']),('residuals','U-on-V',r['V'],r['U']),('propensities','raw',Q(i),r['m']),('propensities','grid',Q(i),r['grid']),('propensities','used',Q(i),r['used']),('scores','PLR',Q(i),r['psi']),('scores','AIPW-centered',Q(i),r['pseudo']-tau)]:tables['source-chart-points'].append(dict(kind=kind,chart=chart,series=series,index=i,id=r['id'],x=x,y=y,unit=unit if chart!='propensities'else'probability prediction'))
 return tables
HEAD={
 'model-frame':['kind','id','group','fold','nativeID','sourceRows','y','d','x','weight'],
 'full-selection-ledger':['kind','id','nativeID','sourceRows','eligible','reason','nativeTreatment'],
 'fold-training-membership':['kind','fold','target','id','group','sourceRows'],
 'fold-fit-metrics':['kind','fold','target','nTrain','nTest','rank','lambdaValue','MSE','penalty','objective','minima','ranges'],
 'fold-coefficients':['kind','fold','target','index','beta','minimum','range','RHS'],
 'fold-crossproducts':['kind','fold','target','row','column','value'],
 'heldout-predictions':['kind','index','id','group','fold','y','d','ell','m','mu0','mu1'],
 'residual-scores':['kind','index','id','group','fold','U','V','VU','V2','psi'],
 'propensity-ledger':['kind','index','id','group','fold','raw','grid','used','gridDelta','clipped'],
 'aipw-pseudo-outcomes':['kind','index','id','group','fold','y','d','mu0','mu1','used','pseudo','centeredScore'],
 'source-estimates':['kind','metric','value','unit'],
 'source-chart-points':['kind','chart','series','index','id','x','y','unit']}
def main():
 p=argparse.ArgumentParser();p.add_argument('--source-dir',type=Path,required=True);p.add_argument('--out',type=Path,required=True);a=p.parse_args();a.out.mkdir(parents=True,exist_ok=True);models,ledger=reconstruct(a.source_dir);tables=study(models);tables['full-selection-ledger']=ledger
 files=[]
 for name,rr in tables.items():
  dest=a.out/('computed-'+name+'.csv');write_csv(dest,rr,HEAD[name]);files.append(dict(file=dest.name,rows=len(rr),columns=len(HEAD[name]),sha256=hashlib.sha256(dest.read_bytes()).hexdigest()))
 report=dict(chapter='METR-21',arithmetic='Exact Python Fraction finite storage arithmetic;not infinite measurement accuracy',models={k:len(v)for k,v in models.items()},parameters=dict(K=K,lambdaValue=str(LAM),scale='outer-training/arm-only range',propensityGrid=GRID,clip=str(CLIP)),files=files,claim='Finite declared post-level adjusted score experiments;no automatic causal or confidence certification')
 (a.out/'source-reproduction-summary.json').write_text(json.dumps(report,indent=2)+'\n',encoding='utf8');print(json.dumps(report))
if __name__=='__main__':main()
