# METR20. Base R approximate numerical reproduction from ONLY three native CSVs.
# No JS engine, derived answers, model JSON, private modules or internet needed.
# Run: Rscript metr20-reproduce.R --data-dir PATH --out NEW_EMPTY_DIRECTORY
# Exact finite stored-value fractions are provided by the separate Python study.
options(stringsAsFactors=FALSE,digits=17)
args<-commandArgs(trailingOnly=TRUE)
getarg<-function(k,default=NULL){i<-match(k,args);if(is.na(i))return(default);if(i==length(args))stop('Missing argument value');args[i+1L]}
sourcearg<-commandArgs(FALSE);script<-sub('^--file=','',sourcearg[grepl('^--file=',sourcearg)][1]);here<-dirname(normalizePath(script,mustWork=TRUE));datadir<-getarg('--data-dir',if(dir.exists(file.path(here,'metr20-sources')))file.path(here,'metr20-sources')else file.path(here,'..','metr20-sources'));outdir<-getarg('--out');if(is.null(outdir))stop('Supply --out NEW_EMPTY_DIRECTORY');dir.create(outdir,recursive=TRUE,showWarnings=FALSE);if(length(list.files(outdir,all.files=TRUE,no..=TRUE)))stop('Use a new empty output directory;existing files are preserved.')
units<-c(country='log teen-employment points',person='recorded real earnings',company='FTE employees');clocks<-c(country='calendar year',person='calendar year',company='survey-wave index');steps<-c(country=1,person=3,company=1);files<-c(country='actual2500-county-mpdta-all6-fields.csv',person='actual38408-NSW-all15-fields.csv',company='actual410-NJPA-all46-fields.csv')
raw<-lapply(files,function(n)read.csv(file.path(datadir,n),colClasses='character',check.names=FALSE,na.strings=character()));stopifnot(identical(vapply(raw,nrow,0L),c(country=2500L,person=38408L,company=410L)))
num<-function(s)ifelse(s=='.',NA_real_,as.numeric(s));mean0<-function(v)if(length(v))mean(v)else NA_real_;var0<-function(v)if(length(v)>1L)sum((v-mean(v))^2)/(length(v)-1L)else NA_real_
tok<-function(v){if(length(v)!=1L)stop('Expected scalar');if(is.na(v))return('');if(is.logical(v))return(if(v)'true'else'false');if(is.numeric(v))return(sprintf('%.17g',unname(v)));as.character(v)}
tables<-new.env(parent=emptyenv());add<-function(name,row){if(!exists(name,tables,inherits=FALSE))tables[[name]]<-list();tables[[name]][[length(tables[[name]])+1L]]<-row}
save_table<-function(name){rr<-tables[[name]];head<-names(rr[[1]]);stopifnot(all(vapply(rr,function(r)identical(names(r),head),TRUE)));mat<-do.call(rbind,lapply(rr,function(r)vapply(r,tok,'')));write.table(mat,file.path(outdir,name),sep=',',row.names=FALSE,col.names=head,quote=TRUE,na='',qmethod='double')}
models<-list(country=list(),person=list(),company=list())
for(i in seq_len(nrow(raw$country))){r<-raw$country[i,];g<-as.integer(r$first.treat);if(!g)g<-NA_integer_;stopifnot(as.integer(r$treat)==as.integer(!is.na(g)));models$country[[i]]<-list(id=paste0('mpdta:',r$sourceRow),entity=paste0('county:',as.integer(r$countyreal)),time=as.integer(r$year),y=num(r$lemp),g=g,sourceRow=as.integer(r$sourceRow),nativeID=r$countyreal)}
for(i in seq_len(nrow(raw$person))){r<-raw$person[i,];selected<-as.integer(r$experimental)==1L;stopifnot(selected==(as.integer(r$sample)==1L),(r$treated!='.')==selected);if(selected){d<-as.integer(r$treated);stopifnot(d%in%0:1);models$person[[length(models$person)+1L]]<-list(id=paste0('nsw:',r$sourceRow),entity=paste0('nsw-id:',as.integer(r$id)),time=as.integer(r$year),y=num(r$re),g=if(d==1L)1978L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=as.character(as.integer(r$id)))}}
for(i in seq_len(nrow(raw$company))){r<-raw$company[i,];state<-as.integer(r$STATE);stopifnot(state%in%0:1);for(t in 0:1){suffix<-if(t==0)''else'2';v<-vapply(paste0(c('EMPFT','NMGRS','EMPPT'),suffix),function(k)num(r[[k]]),0);y<-if(anyNA(v))NA_real_ else v[1]+v[2]+v[3]/2;models$company[[length(models$company)+1L]]<-list(id=paste0('njpa:',r$sourceRow,':wave',t),entity=paste0('njpa-row:',r$sourceRow),time=t,y=unname(y),g=if(state==1L)1L else NA_integer_,sourceRow=as.integer(r$sourceRow),nativeID=r$SHEET)}}
stopifnot(identical(vapply(models,length,0L),c(country=2500L,person=1444L,company=820L)))
panel<-function(rows){G<-list();for(r in rows){key<-r$entity;u<-G[[key]];if(is.null(u))u<-list(g=r$g,rows=list());stopifnot(identical(u$g,r$g),is.null(u$rows[[as.character(r$time)]]));u$rows[[as.character(r$time)]]<-r;G[[key]]<-u};G}
cell<-function(G,g,t,step,control){b<-g-step;members<-list();T<-C<-list();for(key in names(G)){u<-G[[key]];target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));role<-if(target)'treated'else if(comp)'control'else'excluded-comparison';before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];yb<-if(is.null(before))NA_real_ else before$y;ya<-if(is.null(after))NA_real_ else after$y;eligible<-role!='excluded-comparison'&&!is.na(yb)&&!is.na(ya);reason<-if(role=='excluded-comparison')'target-or-already-exposed-cohort-not-valid-control'else if(is.null(before))'baseline-source-row-absent'else if(is.null(after))'target-time-source-row-absent'else if(is.na(yb))'baseline-outcome-missing'else if(is.na(ya))'target-outcome-missing'else'';m<-list(entity=key,nativeID=u$rows[[1]]$nativeID,g=u$g,role=role,eligible=eligible,baselineSourceId=if(is.null(before))NA_character_ else before$id,targetSourceId=if(is.null(after))NA_character_ else after$id,before=yb,after=ya,change=if(eligible)ya-yb else NA_real_,reason=reason);members[[key]]<-m;if(eligible){if(role=='treated')T[[length(T)+1L]]<-m else C[[length(C)+1L]]<-m}}
 change<-function(a)vapply(a,function(r)r$change,0);d<-mean0(change(T));e<-mean0(change(C));estimate<-if(is.na(d)||is.na(e))NA_real_ else d-e;defined<-!is.na(estimate);scores<-setNames(rep(NA_real_,length(members)),names(members));for(key in names(members)){m<-members[[key]];s<-if(!defined)NA_real_ else if(!m$eligible)0 else if(m$role=='treated')(m$change-d)/length(T)else-(m$change-e)/length(C);m$score<-s;scores[key]<-s;members[[key]]<-m};st<-var0(change(T));sc<-var0(change(C));v<-if(is.na(st)||is.na(sc))NA_real_ else st/length(T)+sc/length(C);level<-function(a,k)mean0(vapply(a,function(r)r[[k]],0))
 list(g=g,t=t,baseline=b,event=(t-g)/step,phase=if(t==b)'mechanical-reference'else if(t>=g)'post'else'pre-placebo',defined=defined,estimate=estimate,T=T,C=C,members=members,scores=scores,HC0=if(defined)sum(scores^2)else NA_real_,unbiased=v,treatedMeanBefore=level(T,'before'),treatedMeanAfter=level(T,'after'),treatedMeanChange=d,controlMeanBefore=level(C,'before'),controlMeanAfter=level(C,'after'),controlMeanChange=e)
}
covariance<-function(cells){n<-length(cells);V<-matrix(NA_real_,n,n);for(i in seq_len(n))for(j in seq_len(n))if(cells[[i]]$defined&&cells[[j]]$defined)V[i,j]<-sum(cells[[i]]$scores*cells[[j]]$scores);V}
aggregate_cells<-function(post,V,step){out<-list();push<-function(typ,key,ii,w){est<-if(!length(ii)||any(vapply(post[ii],function(z)is.na(z$estimate),TRUE)))NA_real_ else sum(w*vapply(post[ii],function(z)z$estimate,0));vv<-if(is.na(est)||anyNA(V[ii,ii,drop=FALSE]))NA_real_ else as.numeric(t(w)%*%V[ii,ii,drop=FALSE]%*%w);out[[length(out)+1L]]<<-list(type=typ,key=as.character(key),ii=ii,w=w,estimate=est,variance=vv)};positive<-which(vapply(post,function(c)length(c$T)>0L,TRUE));mass<-sum(vapply(post[positive],function(c)length(c$T),0));push('simple','overall',positive,if(mass)vapply(post[positive],function(c)length(c$T)/mass,0)else numeric())
 for(typ in c('event','calendar','group')){keys<-vapply(post,function(c)if(typ=='event')c$event else if(typ=='calendar')c$t else c$g,0);gg<-sort(unique(keys));cohortmass<-if(typ=='group')sum(vapply(gg,function(k)length(post[[which(keys==k)[1]]]$T),0))else 0;allii<-integer();allw<-numeric();for(key in gg){ii<-which(keys==key);jj<-ii[vapply(post[ii],function(c)length(c$T)>0L,TRUE)];if(typ=='group'){stopifnot(length(unique(vapply(post[ii],function(c)length(c$T),0)))<=1L);w<-if(length(jj))rep(1/length(jj),length(jj))else numeric();if(cohortmass){allii<-c(allii,jj);allw<-c(allw,w*length(post[[ii[1]]]$T)/cohortmass)}}else{total<-sum(vapply(post[jj],function(c)length(c$T),0));w<-if(total)vapply(post[jj],function(c)length(c$T)/total,0)else numeric()};push(typ,key,jj,w)};if(typ=='group')push(typ,'overall',allii,allw)};out}
twfe<-function(G,times){ledger<-list();good<-list();for(key in names(G)){u<-G[[key]];absent<-times[!as.character(times)%in%names(u$rows)];missing<-times[vapply(times,function(t){r<-u$rows[[as.character(t)]];!is.null(r)&&is.na(r$y)},TRUE)];eligible<-length(times)>0L&&!length(absent)&&!length(missing);ledger[[length(ledger)+1L]]<-list(entity=key,g=u$g,nativeID=u$rows[[1]]$nativeID,eligible=eligible,absentTimes=paste(absent,collapse=','),missingOutcomeTimes=paste(missing,collapse=','),originalRows=length(u$rows));if(eligible)good[[key]]<-u};rows<-list();for(key in names(good))for(t in times){r<-good[[key]]$rows[[as.character(t)]];r$D<-as.integer(!is.na(r$g)&&t>=r$g);rows[[length(rows)+1L]]<-r};em<-lapply(good,function(u)list(D=mean(vapply(times,function(t)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(u$rows[as.character(times)],function(r)r$y,0))));tm<-lapply(times,function(t)list(D=mean(vapply(good,function(u)as.integer(!is.na(u$g)&&t>=u$g),0)),Y=mean(vapply(good,function(u)u$rows[[as.character(t)]]$y,0))));names(tm)<-as.character(times);gd<-mean0(vapply(rows,function(r)r$D,0));gy<-mean0(vapply(rows,function(r)r$y,0));num<-den<-0
 for(i in seq_along(rows)){r<-rows[[i]];r$residualD<-r$D-em[[r$entity]]$D-tm[[as.character(r$time)]]$D+gd;r$residualY<-r$y-em[[r$entity]]$Y-tm[[as.character(r$time)]]$Y+gy;num<-num+r$residualD*r$residualY;den<-den+r$residualD^2;rows[[i]]<-r};beta<-if(den!=0)num/den else NA_real_;weights<-list();for(i in seq_along(rows)){r<-rows[[i]];r$projectionCoefficient<-if(den!=0)r$residualD/den else NA_real_;r$regressionResidual<-if(!is.na(beta))r$residualY-beta*r$residualD else NA_real_;rows[[i]]<-r;if(r$D==1L){k<-paste(r$g,r$time,sep=':');z<-weights[[k]];if(is.null(z))z<-list(g=r$g,t=r$time,rows=0,coefficient=if(den!=0)0 else NA_real_);z$rows<-z$rows+1L;if(den!=0)z$coefficient<-z$coefficient+r$projectionCoefficient;weights[[k]]<-z}};list(ledger=ledger,rows=rows,num=num,den=den,beta=beta,weights=weights,balancedEntities=length(good))}
adjacent_pre<-function(G,g,t,step,control){b<-t-step;T<-C<-numeric();for(u in G){target<-!is.na(u$g)&&u$g==g;comp<-is.na(u$g)||(control=='notyet'&&!is.na(u$g)&&u$g>max(t,b));if(!target&&!comp)next;before<-u$rows[[as.character(b)]];after<-u$rows[[as.character(t)]];if(!is.null(before)&&!is.null(after)&&!is.na(before$y)&&!is.na(after$y)){if(target)T<-c(T,after$y-before$y)else C<-c(C,after$y-before$y)}};if(!length(T)||!length(C))NA_real_ else mean(T)-mean(C)}
metric<-function(kind,config,name,value,unit)add('computed-source-fit-metrics.csv',list(kind=kind,configuration=config,metric=name,value=value,numeric=value,unit=unit));point<-function(plot,kind,series,key,x,y,unit)add('computed-source-chart-points.csv',list(plot=plot,kind=kind,series=series,key=key,x=x,y=y,numericY=y,unit=unit));summary<-list()
for(kind in names(models)){
 rows<-models[[kind]];G<-panel(rows);times<-sort(unique(vapply(rows,function(r)r$time,0)));cohorts<-sort(unique(na.omit(vapply(rows,function(r)r$g,0))));step<-unname(steps[kind]);unit<-unname(units[kind]);tf<-twfe(G,times);summary[[kind]]<-list(nativeRows=nrow(raw[[kind]]),modelRows=length(rows),entities=length(G),times=times,cohorts=cohorts,unit=unit,step=step,clock=unname(clocks[kind]),TWFE=tf$beta,balancedEntities=tf$balancedEntities)
 for(r in rows){add('computed-source-model-panel.csv',c(list(kind=kind),r,list(D=as.integer(!is.na(r$g)&&r$time>=r$g),observed=!is.na(r$y),unit=unit,periodUnit=unname(clocks[kind]))));if(!is.na(r$y))point(paste0(kind,'-levels'),kind,if(is.na(r$g))'never'else paste0('g',r$g),r$id,r$time,r$y,unit)}
 for(r in tf$ledger)add('computed-twfe-frame-ledger.csv',c(list(kind=kind),r));for(r in tf$rows)add('computed-twfe-rows.csv',c(list(kind=kind),r,list(unit=unit)));ii<-0L
 weightOrder<-order(vapply(tf$weights,function(z)z$g,0),vapply(tf$weights,function(z)z$t,0));for(z in tf$weights[weightOrder]){add('computed-twfe-cell-weights.csv',list(kind=kind,cohort=z$g,time=z$t,rows=z$rows,coefficient=z$coefficient,unit='dimensionless'));if(kind=='country')point('country-twfe-weights',kind,'TWFE',paste(z$g,z$t,sep=':'),ii,z$coefficient,'dimensionless');ii<-ii+1L}
 metric(kind,'balanced','TWFE',tf$beta,unit);metric(kind,'balanced','TWFEdenominator',tf$den,'dimensionless');metric(kind,'balanced','balancedEntities',tf$balancedEntities,'entities')
 if(kind%in%c('person','company'))for(u in G){r0<-u$rows[[as.character(times[1])]];r1<-u$rows[[as.character(tail(times,1))]];if(!is.null(r0)&&!is.null(r1)&&!is.na(r0$y)&&!is.na(r1$y))point(paste0(kind,'-changes'),kind,if(is.na(u$g))'comparison'else'treated',r0$entity,u$rows[[1]]$sourceRow,r1$y-r0$y,unit)}
 for(control in c('never','notyet')){
  cells<-list();for(g in cohorts)for(t in times)cells[[length(cells)+1L]]<-cell(G,g,t,step,control);V<-covariance(cells);post<-Filter(function(c)c$phase=='post',cells);Vp<-covariance(post);aggs<-aggregate_cells(post,Vp,step)
  for(i in seq_along(cells)){c<-cells[[i]];cr<-list(kind=kind,control=control,cellIndex=i-1L,cohort=c$g,time=c$t,baseline=c$baseline,event=c$event,phase=c$phase,defined=c$defined,treatedPairs=length(c$T),controlPairs=length(c$C));for(k in c('estimate','treatedMeanBefore','treatedMeanAfter','treatedMeanChange','controlMeanBefore','controlMeanAfter','controlMeanChange','HC0','unbiased'))cr[[k]]<-c[[k]];add('computed-cohort-cell-estimates.csv',c(cr,list(outcomeUnit=unit,varianceUnit=paste0('(',unit,') squared'))));for(m in c$members)add('computed-entity-cell-membership.csv',c(list(kind=kind,control=control,cohort=c$g,time=c$t,baseline=c$baseline),m,list(outcomeUnit=unit)));metric(kind,control,paste0('contrast:g',c$g,':t',c$t),c$estimate,unit)}
  for(i in seq_along(cells))for(j in seq_along(cells))add('computed-cell-score-covariance.csv',list(kind=kind,control=control,rowCell=i-1L,columnCell=j-1L,rowCohort=cells[[i]]$g,rowTime=cells[[i]]$t,columnCohort=cells[[j]]$g,columnTime=cells[[j]]$t,value=V[i,j],unit=paste0('(',unit,') squared')))
  for(a in aggs){add('computed-aggregation-targets.csv',list(kind=kind,control=control,type=a$type,target=a$key,estimate=a$estimate,variance=a$variance,sumCoefficients=sum(a$w),selectedCells=length(a$ii),outcomeUnit=unit,varianceUnit=paste0('(',unit,') squared')));for(z in seq_along(a$ii)){i<-a$ii[z];w<-a$w[z];c<-post[[i]];add('computed-aggregation-linear-weights.csv',list(kind=kind,control=control,type=a$type,target=a$key,sourcePostCell=i-1L,cohort=c$g,time=c$t,event=c$event,declaredPairWeight=length(c$T),coefficient=w,cellEstimate=c$estimate,contribution=w*c$estimate,unit=unit))};metric(kind,control,paste(a$type,a$key,sep=':'),a$estimate,unit);if(kind=='country'&&a$type=='event')point('country-event-contrasts',kind,control,a$key,as.integer(a$key),a$estimate,unit)}
  if(kind=='country')for(c in post)point('country-cohort-contrasts',kind,paste0(control,':g',c$g),paste(c$g,c$t,sep=':'),c$t,c$estimate,unit)
  for(g in cohorts){pre<-vapply(times[times<g],function(t)adjacent_pre(G,g,t,step,control),0);pre<-pre[!is.na(pre)];scale<-if(length(pre))max(abs(pre))else NA_real_;est<-Filter(function(c)c$g==g&&c$t==g,cells)[[1]]$estimate;defined<-!is.na(scale)&&!is.na(est);preJSON<-if(length(pre))paste0('[',paste(paste0('"',vapply(as.list(pre),tok,''),'"'),collapse=','),']')else'[]';add('computed-sensitivity-budgets.csv',list(kind=kind,control=control,cohort=g,estimate=est,preContrastsJSON=preJSON,scale=scale,M=1,horizon=1,biasBudget=if(defined)scale else NA_real_,lower=if(defined)est-scale else NA_real_,upper=if(defined)est+scale else NA_real_,defined=defined,confidenceLevel='not a confidence interval',unit=unit))}
 }
}
for(n in ls(tables))save_table(n)
capture.output(dput(list(chapter='METR-20',method='Base R approximate finite-source study;not exact rational or an inference certificate',sourceMD5=tools::md5sum(file.path(datadir,files)),summary=summary)),file=file.path(outdir,'study-summary-R.txt'));cat('METR20 base R source study OK\n');for(n in ls(tables))cat(n,length(tables[[n]]),'rows\n')
