#!/usr/bin/env Rscript
# METR18 finite actual-data study, base R only. Binary64 approximations, not an
# exact rational engine. Unit row mass, centered intercept and a common complete
# frame. Proposed instruments are not certified valid/excluded/strong. Estimated
# independent-row HC0 does not resolve serial/cluster dependence. Scalar Z0 AR /
# Fieller and threshold4 are separate from the two-instrument 2SLS/GMM model.
args<-commandArgs(trailingOnly=TRUE)
source_dir<-if(length(args))args[1]else"../metr18-sources"
out<-if(length(args)>1)args[2]else"metr18-R-results"
if(dir.exists(out))stop("output directory must be fresh")
dir.create(out,recursive=TRUE)
read_native<-function(n)read.csv(file.path(source_dir,n),colClasses="character",check.names=FALSE,na.strings=NULL,stringsAsFactors=FALSE)
q<-function(v)vapply(v,function(s){if(is.na(s)||s==""||s==".")return(NA_real_);p<-strsplit(s,"/",fixed=TRUE)[[1]];if(length(p)>2)stop("malformed fraction");a<-suppressWarnings(as.numeric(p[1]));if(is.na(a))stop("malformed number");if(length(p)==1)return(a);b<-as.numeric(p[2]);if(!is.finite(b)||b==0)stop("invalid denominator");a/b},numeric(1),USE.NAMES=FALSE)
fmt<-function(x){if(length(x)!=1)stop("scalar required");if(is.na(x))return("");if(is.logical(x))return(if(x)"True"else"False");if(is.numeric(x))return(sprintf("%.17g",x));as.character(x)}
names_tables<-c("source-and-common-frame-ledger","country-lag-lineage","IV-diagnostics","centered-crossproducts-and-covariances","common-frame-predictions-residuals","AR-null-grid","Fieller-set-characterization","moment-weights-and-overid")
tables<-setNames(lapply(names_tables,function(x)list()),names_tables)
add<-function(name,row){tables[[name]][[length(tables[[name]])+1L]]<<-lapply(row,function(v)unname(fmt(v)))}
wb<-read_native("actual90-KOR-growth-CPI-original-1980-2024.csv")
lookup<-function(year,indicator){r<-wb[wb$year==as.character(year)&wb$indicatorID==indicator,,drop=FALSE];if(!nrow(r))return(NULL);stopifnot(nrow(r)==1);r}
country<-list();growth<-"NY.GDP.MKTP.KD.ZG";cpi<-"FP.CPI.TOTL.ZG"
for(year in 1980:2024){Y<-lookup(year,growth);X<-lookup(year,cpi);lags<-lapply(c(1,2),function(j)lookup(year-j,growth));lv<-vapply(lags,function(r)if(is.null(r))NA_real_ else q(r$valueExactToken),numeric(1));ls<-vapply(lags,function(r)if(is.null(r))""else r$originalSourceRow,character(1));add("country-lag-lineage",list(year=year,y=q(Y$valueExactToken),x=q(X$valueExactToken),z0=lv[1],z1=lv[2],ySource=Y$originalSourceRow,xSource=X$originalSourceRow,z0Source=ls[1],z1Source=ls[2],inDeclaredModel=year>=1982,reason=if(year<1982)"prior-two-year-lags-required"else""));if(year>=1982)country[[length(country)+1L]]<-list(id=paste0("KOR:",year),sourceRow=year,nativeID="KOR",y=q(Y$valueExactToken),x=q(X$valueExactToken),z=lv)}
nl<-read_native("actual3613-NLS-original52-fields.csv");people<-lapply(seq_len(nrow(nl)),function(i)list(id=paste0("nls-row:",i),sourceRow=i,nativeID=nl$id[i],y=q(nl$lwage76[i]),x=q(nl$ed76[i]),z=c(q(nl$nearc4[i]),q(nl$nearc2[i]))))
nj<-read_native("actual410-NJPA-original-codebook-fields.csv");company<-lapply(seq_len(nrow(nj)),function(i){r<-nj[i,,drop=FALSE];fte<-function(suffix){v<-vapply(c("EMPFT","NMGRS","EMPPT"),function(k)q(r[[paste0(k,suffix)]]),numeric(1));if(anyNA(v))NA_real_ else v[1]+v[2]+v[3]/2};a<-fte("");b<-fte("2");list(id=paste0("njpa-row:",i),sourceRow=i,nativeID=r$SHEET,y=b-a,x=q(r$WAGE_ST2)-q(r$WAGE_ST),z=c(q(r$STATE),q(r$CO_OWNED)))})
models<-list(country=country,person=people,company=company)
ar<-function(delta,pi,S,b,c=4){g<-delta-b*pi;v<-S[1,1]-2*b*S[1,2]+b*b*S[2,2];if(v<0)stop("negative variance");stat<-if(v)g*g/v else NA_real_;list(moment=g,variance=v,statistic=stat,status=if(v)"finite"else if(g)"positive-infinity"else"undefined-zero-over-zero",accepted=if(v)stat<=c else if(g)FALSE else NA)}
fieller<-function(delta,pi,S,c=4){if(S[1,1]<=0||det(S)<=0)stop("Fieller requires PD covariance");A<-pi*pi-c*S[2,2];B<--2*delta*pi+2*c*S[1,2];C<-delta*delta-c*S[1,1];disc<-B*B-4*A*C;center<-rad<-lo<-hi<-NA_real_
 if(A!=0){if(disc<0)shape<-if(A<0)"all-real"else"empty"else if(disc==0){center<--B/(2*A);shape<-if(A<0)"all-real"else"singleton";lo<-hi<-center}else{center<--B/(2*A);rad<-disc/(4*A*A);lo<-center-sqrt(rad);hi<-center+sqrt(rad);shape<-if(A<0)"two-rays"else"bounded-interval"}}
 else if(B!=0){center<--C/B;shape<-if(B>0)"left-half-line"else"right-half-line";if(B>0)hi<-center else lo<-center}else shape<-if(C<=0)"all-real"else"empty"
 list(A=A,B=B,C=C,discriminant=disc,setType=shape,rootCenter=center,rootRadicand=rad,lowerApprox=lo,upperApprox=hi,endpointApproximation="binary64 approximation; exact Python polynomial determines membership",threshold=c,covarianceConvention="estimated independent-row HC0, no degrees correction",probabilityCoverage="not automatically95%; threshold4is stipulated")}
study<-function(rows){good<-rows[vapply(rows,function(r)!anyNA(c(r$y,r$x,r$z)),logical(1))];n<-length(good);Y<-vapply(good,function(r)r$y,numeric(1));X<-vapply(good,function(r)r$x,numeric(1));Z<-do.call(rbind,lapply(good,function(r)r$z));my<-mean(Y);mx<-mean(X);mz<-colMeans(Z);y<-Y-my;x<-X-mx;z<-sweep(Z,2,mz,"-");G<-crossprod(z);Gi<-solve(G);ZX<-drop(crossprod(z,x));ZY<-drop(crossprod(z,y));thetaX<-drop(Gi%*%ZX);thetaY<-drop(Gi%*%ZY);xf<-drop(z%*%thetaX);yf<-drop(z%*%thetaY);Sxx<-sum(x*x);Sxy<-sum(x*y);projected<-sum(ZX*thetaX);ols<-Sxy/Sxx;iv<-sum(ZX*thetaY)/projected;u1<-y-iv*x;v<-x-xf;SSR<-sum(xf*xf);SSE<-sum(v*v);U<-crossprod(z*u1);Ui<-solve(U);beta2<-drop(crossprod(ZX,Ui%*%ZY)/crossprod(ZX,Ui%*%ZX));u2<-y-beta2*x;mom<-drop(crossprod(z,u2));J<-drop(crossprod(mom,Ui%*%mom));HC0<-Gi%*%crossprod(z*v)%*%Gi;wald<-drop(crossprod(thetaX,solve(HC0,thetaX)));ff<-(SSR/2)/(SSE/(n-3));zz<-z[,1];szz<-sum(zz*zz);delta<-sum(zz*y)/szz;pi<-sum(zz*x)/szz;uy<-y-delta*zz;ux<-x-pi*zz;Sigma<-crossprod(cbind(zz*uy,zz*ux))/szz^2
 predictions<-lapply(seq_len(n),function(i)list(id=good[[i]]$id,y=Y[i],x=X[i],z0=Z[i,1],z1=Z[i,2],yCentered=y[i],xCentered=x[i],z0Centered=z[i,1],z1Centered=z[i,2],firststageFit=mx+xf[i],firststageResidual=v[i],reducedFormYFit=my+yf[i],OLSFit=my+ols*x[i],IVFit=my+iv*x[i],IVResidual=u1[i],GMMFit=my+beta2*x[i],GMMResidual=u2[i],scalarYResidual=uy[i],scalarXResidual=ux[i]))
 list(n=n,q=2,means=list(y=my,x=mx,z=mz),centered=list(y=y,x=x,z=z),G=G,Gi=Gi,ZX=ZX,ZY=ZY,thetaX=thetaX,thetaY=thetaY,HC0Firststage=HC0,Sxx=Sxx,Sxy=Sxy,SSR=SSR,SSE=SSE,R2=SSR/Sxx,Fclassic=ff,HC0FirststageWald=wald,OLS=ols,IV=iv,IVIntercept=my-iv*mx,U=U,Ui=Ui,S=U/n,W=n*Ui,GMM=beta2,GMMIntercept=my-beta2*mx,J=J,degreesOfFreedom=1,JReference="chi-square(q-1)only under validity,strongidentification,CLT,consistentoptimalweight",scalar=list(delta=delta,pi=pi,ratio=delta/pi,Sigma=Sigma,fieller=fieller(delta,pi,Sigma)),predictions=predictions)}
units<-list(country=c("annual growth percentage points","annual CPI percentage points"),person=c("recorded log-wage points","schooling years"),company=c("FTE change","nominal USD/hour starting-wage change"));full<-list()
for(kind in names(models)){rows<-models[[kind]];cat("Rebuilding",kind,"from native tokens\n");r<-study(rows);full[[kind]]<-r;yu<-units[[kind]][1];xu<-units[[kind]][2]
 for(row in rows){vals<-setNames(c(row$y,row$x,row$z[1],row$z[2]),c("y","x","z0","z1"));miss<-names(vals)[is.na(vals)];add("source-and-common-frame-ledger",list(kind=kind,id=row$id,sourceRow=row$sourceRow,nativeID=row$nativeID,y=row$y,x=row$x,z0=row$z[1],z1=row$z[2],eligible=!length(miss),excludedBecause=paste(miss,collapse=","),analysisWeight=1))}
 metric<-function(name,v,u)add("IV-diagnostics",list(kind=kind,metric=name,value=v,unit=u))
 metric("sourceModelRows",length(rows),"rows");metric("completeRows",r$n,"rows");metric("excludedRows",length(rows)-r$n,"rows");metric("declaredInstruments",2,"instruments")
 for(pair in list(c("OLS","OLS"),c("twoInstrument2SLS","IV"),c("twoStepGMM","GMM")))metric(pair[1],r[[pair[2]]],paste(yu,"per",xu))
 metric("twoInstrument2SLSIntercept",r$IVIntercept,yu)
 for(pair in list(c("firststageR2","R2"),c("classicalFirststageF","Fclassic"),c("HC0FirststageWald","HC0FirststageWald"),c("overidJ","J")))metric(pair[1],r[[pair[2]]],"dimensionless")
 metric("firststageResidualDF",r$n-3,"degrees of freedom");metric("overidReferenceDF",1,"degrees of freedom");metric("singleInstrumentDelta",r$scalar$delta,"outcome units per Z0 unit");metric("singleInstrumentPi",r$scalar$pi,"regressor units per Z0 unit");metric("singleInstrumentRatio",r$scalar$ratio,paste(yu,"per",xu))
 for(name in c("G","Gi","HC0Firststage")){v<-r[[name]];for(i in 1:2)for(j in 1:2)add("centered-crossproducts-and-covariances",list(kind=kind,quantity=name,row=i-1,column=j-1,value=v[i,j],normalization="centered sums; HC0 slope covariance uses sums"))}
 for(name in c("ZX","ZY","thetaX","thetaY"))for(i in 1:2)add("centered-crossproducts-and-covariances",list(kind=kind,quantity=name,row=i-1,column=0,value=r[[name]][i],normalization="centered sums or declared slope vector"))
 for(i in 1:2)for(j in 1:2)add("centered-crossproducts-and-covariances",list(kind=kind,quantity="scalarRFHC0",row=i-1,column=j-1,value=r$scalar$Sigma[i,j],normalization="covariance of actual slope estimates; not root-n covariance"))
 for(row in r$predictions)add("common-frame-predictions-residuals",c(list(kind=kind),row))
 bounds<-switch(kind,country=c(-2,5),person=c(-1,1),company=c(-20,20))
 for(i in 0:200){beta<-bounds[1]+diff(bounds)*i/200;v<-ar(r$scalar$delta,r$scalar$pi,r$scalar$Sigma,beta);add("AR-null-grid",c(list(kind=kind,index=i,beta0=beta),v,list(criticalValue=4,gridScope="predeclared visualization viewport; exact whole-real set separately characterized")))}
 add("Fieller-set-characterization",c(list(kind=kind),r$scalar$fieller))
 for(name in c("U","Ui","S","W")){v<-r[[name]];norm<-switch(name,U="sum zi zi prime u1 squared, uncentered moments",Ui="inverse of U",S="U/n",W="inverse(S)=n*inverse(U)");for(i in 1:2)for(j in 1:2)add("moment-weights-and-overid",list(kind=kind,quantity=name,row=i-1,column=j-1,value=v[i,j],normalization=norm))}
 mom<-drop(crossprod(r$centered$z,vapply(r$predictions,function(z)z$GMMResidual,numeric(1))));for(i in 1:2)add("moment-weights-and-overid",list(kind=kind,quantity="secondStepSummedMoment",row=i-1,column=0,value=mom[i],normalization="sum zi (yi-beta2 xi); J=s prime inverse(U) s"))
}
for(name in names(tables)){rows<-tables[[name]];df<-as.data.frame(do.call(rbind,lapply(rows,unlist)),stringsAsFactors=FALSE,check.names=FALSE);write.table(df,file.path(out,paste0("computed-",name,".csv")),sep=",",row.names=FALSE,col.names=TRUE,quote=TRUE,qmethod="double",na="",eol="\n",fileEncoding="UTF-8")}
dput(full,file.path(out,"full-source-study.Rtext"));writeLines(c("METR18: base R binary64 approximate finite study; no exact rational label.","Common complete frames43/3010/351, unit row mass.","Eight CSVs; no engine/source-model/computed inputs read.","Single-instrument0 AR/Fieller with stipulated threshold4 is not automatically a95%two-instrument interval.","Candidate instrument exclusion, strongidentification, serial/cluster dependence and causal interpretation unverified."),file.path(out,"study-manifest.txt"));cat("Completed three actual cases and eight CSVs.\n")
