if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Base-R independent source replay. No cases, engine, model JSON or Python results are numeric inputs.
a<-commandArgs(FALSE);f<-a[grepl("^--file=",a)];if(length(f))setwd(dirname(normalizePath(sub("^--file=","",f[1]),winslash="/")))
D<-"metr03-sources";rawdir<-file.path("../..","work/textbooks-2026/raw");publicOnly<-Sys.getenv("TEXTBOOK_PUBLIC_ONLY")=="1";metrics<-numeric();modes<-character();checks<-0
put<-function(k,v)metrics[k]<<-as.numeric(v)
near<-function(a,b,tol=3e-10){a<-as.numeric(a);b<-as.numeric(b);checks<<-checks+length(a);stopifnot(length(a)==length(b),identical(is.na(a),is.na(b)));ok<-!is.na(a);stopifnot(all(abs(a[ok]-b[ok])<=tol*pmax(1,abs(a[ok]),abs(b[ok]))))}
exact<-function(a,b){checks<<-checks+length(a);stopifnot(identical(as.character(a),as.character(b)))}
fraction<-function(s){if(is.na(s)||s=="")return(NA_real_);v<-strsplit(s,"/",fixed=TRUE)[[1]];as.numeric(v[1])/if(length(v)==2)as.numeric(v[2])else 1}
fq<-function(x)vapply(as.character(x),fraction,numeric(1))
read<-function(n)read.csv(file.path(D,n),fileEncoding="UTF-8-BOM",colClasses="character",na.strings=c("","NA"),check.names=FALSE)
sel<-list(country=read("actual16-country-2024-GDP-longevity-ILO-unemployment.csv"),person=read("actual3613-person-schooling-age-trimmed-log-wages.csv"),company=read("actual410-establishment-before-after-FTE-state-and-components.csv"));source<-list()
p<-file.path(rawdir,"worldbank-panel.json")
if(!publicOnly&&file.exists(p)){
 txt<-paste(readLines(p,encoding="UTF-8",warn=FALSE),collapse=" ");pat<-'\\{\\s*"indicator"\\s*:\\s*\\{[^}]*\\},\\s*"country"\\s*:\\s*\\{[^}]*\\},[^{}]*\\}';nodes<-regmatches(txt,gregexpr(pat,txt,perl=TRUE))[[1]];stopifnot(length(nodes)==6480)
 extract<-function(s,p)sub(p,"\\1",s,perl=TRUE)
 ind<-vapply(nodes,extract,character(1),p='.*"indicator"\\s*:\\s*\\{\\s*"id"\\s*:\\s*"([^"]+)".*');iso<-vapply(nodes,extract,character(1),p='.*"countryiso3code"\\s*:\\s*"([^"]+)".*');date<-vapply(nodes,extract,character(1),p='.*"date"\\s*:\\s*"([^"]+)".*');v<-vapply(nodes,extract,character(1),p='.*"date"\\s*:\\s*"[^"]+"\\s*,\\s*"value"\\s*:\\s*([^,}]+).*');v[v=="null"]<-NA_character_;v<-as.numeric(v)
 ids<-which(date=="2024"&ind=="NY.GDP.PCAP.KD");ids<-ids[order(iso[ids])];j<-match(paste(iso[ids],"2024","SP.DYN.LE00.IN"),paste(iso,date,ind));k<-match(paste(iso[ids],"2024","SL.UEM.TOTL.ZS"),paste(iso,date,ind))
 source$country<-data.frame(sourceRow=ids,x0SourceRow=j,x1SourceRow=k,code=iso[ids],group=ifelse(v[j]>=80,"life_ge_80","life_lt_80"),x0=v[j],x1=v[k],y=v[ids],weight=1);modes["country"]<-"original retained API reread; original download2026-10-20"
}else{source$country<-sel$country;for(k in setdiff(names(source$country),c("code","group")))source$country[[k]]<-fq(source$country[[k]]);modes["country"]<-"public whole source records; no new request"}
p<-file.path(rawdir,"proximity.zip")
if(!publicOnly&&file.exists(p)){
 lines<-readLines(unz(p,"nls.dat"),warn=FALSE);stopifnot(length(lines)==3613);part<-function(a,b){s<-trimws(substr(lines,a,b));s[s=="."]<-NA_character_;as.numeric(s)};x<-part(18,19)
 source$person<-data.frame(sourceRow=seq_along(lines),code=as.character(part(1,5)),group=ifelse(x<=12,"schooling_le12","schooling_gt12"),x0=x,x1=part(24,25),y=part(86,97),weight=1);modes["person"]<-"original fixed-width schooling/recorded age/source-trimmed1976log wages"
}else{source$person<-sel$person;for(k in setdiff(names(source$person),c("code","group")))source$person[[k]]<-fq(source$person[[k]]);modes["person"]<-"public whole source records; missing603 preserved"}
p<-file.path(rawdir,"njmin.zip")
if(!publicOnly&&file.exists(p)){
 lines<-readLines(unz(p,"public.dat"),warn=FALSE);stopifnot(length(lines)==410);part<-function(a,b){s<-trimws(substr(lines,a,b));s[s=="."]<-NA_character_;as.numeric(s)}
 source$company<-data.frame(sourceRow=seq_along(lines),code=as.character(part(1,3)),chain=part(5,5),group=ifelse(part(9,9)==1,"NJ","PA"),x0=part(26,30)+.5*part(32,36)+part(38,42),x1=part(9,9),y=part(122,126)+.5*part(128,132)+part(134,138),weight=1,ftBefore=part(26,30),ptBefore=part(32,36),managersBefore=part(38,42),ftAfter=part(122,126),ptAfter=part(128,132),managersAfter=part(134,138));modes["company"]<-"original within-source-row two-wave FTE;both407 preserved"
}else{source$company<-sel$company;for(k in setdiff(names(source$company),c("code","group")))source$company[[k]]<-fq(source$company[[k]]);modes["company"]<-"public whole source records;incomplete26 preserved"}
for(kind in names(source)){
 r<-source[[kind]];s<-sel[[kind]];exact(nrow(r),nrow(s));for(k in c("code","group"))exact(r[[k]],s[[k]])
 for(k in setdiff(names(s),c("code","group")))near(r[[k]],fq(s[[k]]))
}
calculate<-function(rows){
 p<-rows[complete.cases(rows[c("x0","x1","y")]),];x<-p$x0;z<-p$x1;y<-p$y;n<-length(y);A<-cbind(1,x,z);full<-lm.fit(A,y);stopifnot(full$rank==3);abc<-as.numeric(full$coefficients);a<-abc[1];b<-abc[2];c<-abc[3];fit<-as.numeric(A%*%abc);e<-y-fit
 short<-lm.fit(cbind(1,x),y);sc<-as.numeric(short$coefficients);sf<-as.numeric(cbind(1,x)%*%sc);xc<-lm.fit(cbind(1,z),x);yc<-lm.fit(cbind(1,z),y);rx<-as.numeric(xc$residuals);ry<-as.numeric(yc$residuals);delta<-as.numeric(lm.fit(cbind(1,x),z)$coefficients[2]);mx<-mean(x);mz<-mean(z);my<-mean(y);xx<-sum((x-mx)^2);zz<-sum((z-mz)^2);xz<-sum((x-mx)*(z-mz));xy<-sum((x-mx)*(y-my));zy<-sum((z-mz)*(y-my));yy<-sum((y-my)^2);num<-sum(rx*ry);den<-sum(rx^2);sse<-sum(e^2);shortsse<-sum((y-sf)^2)
 near(b,num/den);near(sc[2],b+c*delta);near(e,ry-b*rx);near(as.numeric(crossprod(A,e))/n,rep(0,3),1e-6)
 values<-c(n=n,meanX=mx,meanZ=mz,meanY=my,Sxx=xx,Szz=zz,Sxz=xz,Sxy=xy,Szy=zy,SST=yy,centeredDeterminant=xx*zz-xz^2,intercept=a,targetSlope=b,controlSlope=c,shortIntercept=sc[1],shortSlope=sc[2],ZonXSlope=delta,omissionDifference=sc[2]-b,XonZIntercept=as.numeric(xc$coefficients[1]),XonZSlope=as.numeric(xc$coefficients[2]),YonZIntercept=as.numeric(yc$coefficients[1]),YonZSlope=as.numeric(yc$coefficients[2]),FWLNumerator=num,FWLDenominator=den,SSE=sse,MSE=sse/n,shortSSE=shortsse,shortMSE=shortsse/n,R2=1-sse/yy)
 list(values=values,pairs=p,prediction=fit,residual=e,rx=rx,ry=ry,short=sf,A=A,y=y)
}
S<-read("actual-multiple-regression-and-FWL-summaries-exact.csv");FIT<-read("actual-all-source-rows-full-short-fits-and-FWL-residuals.csv");G<-read("actual-normal-equation-Gram-and-rhs-exact.csv")
for(kind in names(source)){
 rows<-source[[kind]];z<-calculate(rows);v<-z$values;s<-S[S$case==kind,]
 for(k in names(v)){put(paste(kind,k,sep="_"),v[k]);near(v[k],fq(s[[k]]))}
 for(k in c("sourceRecords","completeRecords","unavailableRecords")){num<-switch(k,sourceRecords=nrow(rows),completeRecords=nrow(z$pairs),unavailableRecords=nrow(rows)-nrow(z$pairs));near(num,as.numeric(s[[k]]));put(paste(kind,k,sep="_"),num)}
 fr<-FIT[FIT$case==kind,];exact(rows$sourceRow,fr$sourceRow);exact(rows$code,fr$code);exact(rows$group,fr$group);near(rows$x0,fq(fr$x_exact));near(rows$x1,fq(fr$z_exact));near(rows$y,fq(fr$y_exact));complete<-complete.cases(rows[c("x0","x1","y")]);exact(ifelse(complete,"True","False"),fr$contributes)
 for(k in c("full_prediction_exact","full_residual_exact","residualized_x_exact","residualized_y_exact","short_prediction_exact")){
  vv<-switch(k,full_prediction_exact=z$prediction,full_residual_exact=z$residual,residualized_x_exact=z$rx,residualized_y_exact=z$ry,short_prediction_exact=z$short);pred<-rep(NA_real_,nrow(rows));pred[complete]<-vv;near(pred,fq(fr[[k]]))
 }
 gs<-G[G$case==kind,];for(i in seq_len(nrow(gs))){ii<-as.integer(gs$row[i])+1;jj<-as.integer(gs$column[i])+1;vv<-if(gs$kind[i]=="Gram")sum(z$A[,ii]*z$A[,jj])else sum(z$A[,ii]*z$y);near(vv,fraction(gs$value_exact[i]))}
}
exact(source$company$sourceRow[source$company$code=="407"],c(42,168))
T<-read("assumed-eight-row-two-predictor-teaching-table.csv");toy<-data.frame(x0=c(0,0,1,1,2,2,3,3),x1=c(0,1,0,1,1,2,1,2),y=c(0,5,4,5,8,11,10,13));near(toy$x0,fq(T$x));near(toy$x1,fq(T$z));near(toy$y,fq(T$y));z<-calculate(toy);v<-z$values
for(k in c("intercept","targetSlope","controlSlope","shortSlope","MSE","SSE","FWLNumerator","FWLDenominator","centeredDeterminant","R2","omissionDifference"))put(paste0("assumed_",k),v[k])
we<-data.frame(x=c(0,1,0,1),z=c(0,0,1,1),y=c(0,2,4,5),w=c(1,2,3,4));wf<-lm.wfit(cbind(1,we$x,we$z),we$y,we$w);wmse<-sum(we$w*wf$residuals^2)/sum(we$w);rry<-c(-1,1,0);rrx<-c(-.5,.5,0);badx<-c(-.5,.5,-.5)
other<-c(hoursToMinutesTarget=as.numeric(v["targetSlope"])/60,Y100MSE=as.numeric(v["MSE"])*10000,centeredIntercept=as.numeric(v["intercept"])+as.numeric(v["targetSlope"])*1.5+as.numeric(v["controlSlope"]),weightedExampleTarget=as.numeric(wf$coefficients[2]),weightedExampleMSE=wmse,mismatchedSubsetSlope=sum(badx*rry)/sum(badx^2),correctSubsetSlope=sum(rrx*rry)/sum(rrx^2),singularOnRelationPrediction=.5+2*4)
for(k in names(other))put(paste0("assumed_",k),other[k])
write.csv(data.frame(metric=names(metrics),value=as.numeric(metrics)),"metr03-r-results.csv",row.names=FALSE)
write.csv(data.frame(kind=names(modes),inputMode=unname(modes),selectedComparisons=checks),"metr03-r-input-audit.csv",row.names=FALSE)
cat("METR03 base R:",length(metrics),"metrics;",checks,"comparisons;public-only",publicOnly,"\n")
