# METR19: standalone full-source restricted educational dynamic AR1.
# Base R binary64 approximation, NOT exact rational algebra or a reference test.
# No saved coefficients/derived result CSV/engine/Python imports. Official Stata
# firm source is a distributed teaching panel, possibly altered, not new evidence.
# Usage: Rscript actual-source-study.R --sources source-dir --output fresh-dir
# Same collapsed lag2..3 D and same-frame system; no controls/year effects,
# Windmeijer correction, standardized m1/m2, p-values or causal certificate.
args <- commandArgs(trailingOnly=TRUE)
arg <- function(key) { i <- match(key,args); if(is.na(i)||i==length(args)) stop(key); args[i+1L] }
sourceDir <- arg('--sources'); outputDir <- arg('--output')
if(dir.exists(outputDir)) stop('fresh output directory required')
dir.create(outputDir,recursive=TRUE)
num <- function(x) {
 if(is.na(x)||x==''||x=='.') return(NA_real_)
 p <- strsplit(as.character(x),'/',fixed=TRUE)[[1L]]
 if(length(p)==1L) as.numeric(p[1L]) else if(length(p)==2L) as.numeric(p[1L])/as.numeric(p[2L]) else stop('numeric token')
}
readNative <- function(name) read.csv(file.path(sourceDir,name),colClasses='character',check.names=FALSE,stringsAsFactors=FALSE,na.strings=NULL)
countryRaw <- readNative('actual240-country-GDPpc-original-2010-2024.csv')
country <- data.frame(id=paste0(countryRaw$countryISO3,':',countryRaw$date),entity=countryRaw$countryISO3,time=as.integer(countryRaw$date),y=vapply(countryRaw$originalValueToken,num,0.0)/1000,sourceRow=as.integer(countryRaw$sourceRow),stringsAsFactors=FALSE)
personRaw <- readNative('actual3613-NLS-original52-fields.csv')
person <- do.call(rbind,lapply(seq_len(nrow(personRaw)),function(i) data.frame(id=paste0('nls:',personRaw$sourceRow[i],':',c(1976,1978,1980)),entity=paste0('nls-id:',personRaw$id[i]),time=c(1976L,1978L,1980L),y=vapply(c(personRaw$wage76[i],personRaw$wage78[i],personRaw$wage80[i]),num,0.0)/100,sourceRow=as.integer(personRaw$sourceRow[i]),stringsAsFactors=FALSE)))
companyRaw <- readNative('actual-firm-abdata-all-native-fields.csv')
company <- data.frame(id=paste0('abdata:',companyRaw$sourceRow),entity=paste0('firm:',companyRaw$id),time=as.integer(vapply(companyRaw$year,num,0.0)),y=vapply(companyRaw$n,num,0.0),sourceRow=as.integer(companyRaw$sourceRow),stringsAsFactors=FALSE)
models <- list(country=list(rows=country,step=1L,unit='thousand constant 2015 USD/person'),person=list(rows=person,step=2L,unit='nominal USD/hour'),company=list(rows=company,step=1L,unit='native stored natural-log employment n'))
fmt <- function(v) if(length(v)==0L||is.na(v)) '' else if(is.character(v)) v else format(v,digits=17,scientific=FALSE,trim=TRUE)
dot <- function(x,y) sum(x*y)
inv <- function(A) if(!length(A)) NULL else tryCatch(solve(A),error=function(e)NULL)
ledger <- function(rows,step) {
 key <- paste(rows$entity,rows$time,sep='|'); if(anyDuplicated(key)) stop('duplicate entity/calendar')
 a <- match(paste(rows$entity,rows$time-step,sep='|'),key); b <- match(paste(rows$entity,rows$time-2L*step,sep='|'),key)
 lagY <- rows$y[a]; second <- rows$y[b]; pair <- !is.na(rows$y)&!is.na(lagY); eligible <- pair&!is.na(second)
 data.frame(rows,lagID=ifelse(is.na(a),'',rows$id[a]),lagY=lagY,secondLagID=ifelse(is.na(b),'',rows$id[b]),secondLagY=second,delta=rows$y-lagY,deltaLag=lagY-second,pairEligible=as.integer(pair),differenceEligible=as.integer(eligible),stringsAsFactors=FALSE)
}
fit <- function(rows,step,system) {
 L <- ledger(rows,step); eligible <- which(L$differenceEligible==1L); groups <- split(seq_len(nrow(rows)),rows$entity); eq <- list(); seen <- integer(0)
 for(i in eligible) {
  rr <- rows[groups[[L$entity[i]]],,drop=FALSE]; t <- L$time[i]; ii <- match(t-c(2L,3L)*step,rr$time); zz <- rr$y[ii]; present <- !is.na(zz); instruments <- as.list(zz[present]); names(instruments) <- as.character(c(2L,3L)[present]); seen <- union(seen,c(2L,3L)[present])
  eq[[length(eq)+1L]] <- list(id=paste0('D:',L$id[i]),nativeID=L$id[i],entity=L$entity[i],time=t,block='D',Y=L$delta[i],X=L$deltaLag[i],instruments=instruments)
  if(system) eq[[length(eq)+1L]] <- list(id=paste0('L:',L$id[i]),nativeID=L$id[i],entity=L$entity[i],time=t,block='L',Y=L$y[i],X=L$lagY[i],instruments=list('1'=L$deltaLag[i]))
 }
 cols <- lapply(sort(seen),function(l)list(block='D',lag=l)); if(system&&length(eq)) cols[[length(cols)+1L]] <- list(block='L',lag=1L)
 q <- length(cols); H <- matrix(0,q,q); ZZ <- matrix(0,q,q); d <- rep(0,q); b <- rep(0,q)
 for(i in seq_along(eq)) {
  e <- eq[[i]]; e$Z <- vapply(cols,function(c)if(c$block==e$block&&!is.null(e$instruments[[as.character(c$lag)]]))e$instruments[[as.character(c$lag)]] else 0,0.0); eq[[i]] <- e
  ZZ <- ZZ+tcrossprod(e$Z); d <- d+e$Z*e$X; b <- b+e$Z*e$Y
 }
 groupEq <- split(seq_along(eq),vapply(eq,function(e)e$entity,''))
 for(ii in groupEq) for(i in ii) for(j in ii) {
  e <- eq[[i]]; f <- eq[[j]]; if(e$block!=f$block) next
  w <- if(e$block=='D') if(i==j)2 else if(abs(e$time-f$time)==step)-1 else 0 else as.numeric(i==j)
  if(w!=0) H <- H+w*outer(e$Z,f$Z)
 }
 estimate <- function(W) {
  if(is.null(W)) return(NULL); v <- as.numeric(W%*%d); den <- dot(d,v); if(den==0||!is.finite(den)) return(NULL)
  beta <- dot(b,v)/den; gi <- lapply(groupEq,function(ii)rep(0,q)); residuals <- vapply(eq,function(e)e$Y-beta*e$X,0.0)
  for(i in seq_along(eq)) {e <- eq[[i]];gi[[e$entity]] <- gi[[e$entity]]+e$Z*residuals[i]}
  U <- matrix(0,q,q); s <- rep(0,q); for(g in gi){U <- U+tcrossprod(g);s <- s+g}
  list(beta=beta,den=den,W=W,U=U,s=s,gi=gi,residuals=residuals,criterion=dot(s,as.numeric(W%*%s)),sandwich=dot(v,as.numeric(U%*%v))/den^2)
 }
 first <- estimate(inv(H)); second <- if(is.null(first))NULL else estimate(inv(first$U))
 list(ledger=L,equations=eq,columns=cols,H=H,ZZ=ZZ,d=d,b=b,first=first,second=second,entities=length(groupEq),q=q)
}
buckets <- new.env(parent=emptyenv())
emit <- function(name,row) {
 if(!exists(name,envir=buckets,inherits=FALSE)){b <- new.env(parent=emptyenv());b$n <- 0L;assign(name,b,envir=buckets)}
 b <- get(name,envir=buckets);b$n <- b$n+1L;assign(paste0('r',b$n),lapply(row,fmt),envir=b)
}
summaries <- list()
for(kind in names(models)) {
 M <- models[[kind]];rows <- M$rows;step <- M$step;unit <- M$unit;L <- ledger(rows,step)
 for(i in seq_len(nrow(L))) emit('computed-panel-lag-ledger',c(list(kind=kind,unit=unit,step=step),as.list(L[i,,drop=FALSE])))
 for(t in sort(unique(rows$time))) {
  v <- rows$y[rows$time==t&!is.na(rows$y)];emit('computed-source-time-summary',list(kind=kind,time=t,unit=unit,observed=length(v),missing=sum(rows$time==t&is.na(rows$y)),mean=if(length(v))mean(v)else NA,minimum=if(length(v))min(v)else NA,maximum=if(length(v))max(v)else NA))
 }
 for(system in c(FALSE,TRUE)) {
  label <- paste0(kind,if(system)'-system'else'-difference');f <- fit(rows,step,system);first <- f$first;second <- f$second;chosen <- if(!is.null(second))second else first
  metrics <- list(sourceSlots=nrow(rows),observedY=sum(!is.na(rows$y)),sourceEntities=length(unique(rows$entity)),activeEntities=f$entities,currentLagPairRows=sum(L$pairEligible),differenceEquations=sum(vapply(f$equations,function(e)e$block=='D',TRUE)),levelEquations=sum(vapply(f$equations,function(e)e$block=='L',TRUE)),instrumentCount=f$q,firstDefined=as.integer(!is.null(first)),secondDefined=as.integer(!is.null(second)),rhoFirst=if(is.null(first))NA else first$beta,rhoSecond=if(is.null(second))NA else second$beta,firstCriterion=if(is.null(first))NA else first$criterion,J=if(is.null(second))NA else second$criterion,firstSandwich=if(is.null(first))NA else first$sandwich,secondSandwich=if(is.null(second))NA else second$sandwich,referenceDF=if(is.null(second))NA else f$q-1L)
  for(name in names(metrics))emit('computed-source-fit-metrics',list(configuration=label,metric=name,approximate=metrics[[name]],value=metrics[[name]],unit=if(name=='firstCriterion')paste0('(',unit,') squared')else if(grepl('^rho|^J|Sandwich',name))'dimensionless'else'count'))
  for(i in seq_along(f$equations)) {
   e <- f$equations[[i]];z <- rep(NA_real_,3L);z[seq_len(f$q)] <- e$Z
   emit('computed-equations-and-instruments',list(configuration=label,id=e$id,entity=e$entity,time=e$time,block=e$block,unit=unit,Y=e$Y,X=e$X,Z1=z[1],Z2=z[2],Z3=z[3]))
   if(!is.null(chosen))emit('computed-fitted-equation-residuals',list(configuration=label,id=e$id,entity=e$entity,time=e$time,block=e$block,coefficientSource=if(is.null(second))'first'else'second',Y=e$Y,fitted=chosen$beta*e$X,residual=chosen$residuals[i],unit=unit))
   for(j in seq_len(f$q)) {
    c <- f$columns[[j]];observed <- e$block==c$block&&!is.null(e$instruments[[as.character(c$lag)]]);emit('computed-instrument-slot-availability',list(configuration=label,equationID=e$id,column=paste0(c$block,':lag',c$lag),observed=as.integer(observed),structuralZero=as.integer(!observed),value=e$Z[j],reason=if(observed)'observed-native-level-or-difference'else if(e$block!=c$block)'other-block'else'unavailable-lag'))
   }
  }
  matrices <- list(initialMetric=f$H,instrumentGram=f$ZZ);if(!is.null(first))matrices <- c(matrices,list(firstWeight=first$W,firstClusterOuter=first$U));if(!is.null(second))matrices <- c(matrices,list(secondWeight=second$W,finalClusterOuter=second$U))
  for(name in names(matrices)) {A <- matrices[[name]];for(i in seq_len(nrow(A)))for(j in seq_len(ncol(A)))emit('computed-weight-and-covariance-matrices',list(configuration=label,matrix=name,row=i,column=j,approximate=A[i,j]))}
  for(stage in c('first','second')){st <- f[[stage]];if(!is.null(st))for(entity in names(st$gi))for(j in seq_len(f$q))emit('computed-entity-moment-contributions',list(configuration=label,stage=stage,entity=entity,column=paste0(f$columns[[j]]$block,':lag',f$columns[[j]]$lag),approximate=st$gi[[entity]][j]))}
  products <- list(numeric(0),numeric(0))
  if(!is.null(chosen)) {
   indices <- which(vapply(f$equations,function(e)e$block=='D',TRUE));D <- f$equations[indices];ddKeys <- vapply(D,function(e)paste(e$entity,e$time,sep='|'),'');res <- chosen$residuals[indices]
   for(i in seq_along(D))for(lag in 1:2) {
    e <- D[[i]];prior <- match(paste(e$entity,e$time-lag*step,sep='|'),ddKeys)
    if(!is.na(prior)) {value <- res[i]*res[prior];products[[lag]] <- c(products[[lag]],value);emit('computed-residual-lag-products',list(configuration=label,entity=e$entity,time=e$time,previousTime=e$time-lag*step,lag=lag,step=step,currentID=e$id,previousID=D[[prior]]$id,currentResidual=res[i],previousResidual=res[prior],product=value))}
   }
  }
  for(lag in 1:2){vv <- products[[lag]];metrics[[paste0('serial',lag,'Pairs')]] <- length(vv);metrics[[paste0('serial',lag,'Mean')]] <- if(length(vv))mean(vv)else NA;for(name in c('pairs','sum','mean'))emit('computed-residual-support-summary',list(configuration=label,lag=lag,statistic=name,approximate=switch(name,pairs=length(vv),sum=sum(vv),mean=if(length(vv))mean(vv)else NA),unit=if(name=='pairs')'count'else paste0('(',unit,') squared'),scope='Raw residual products, not standardized m1/m2'))}
  summaries[[label]] <- metrics
 }
}
manifest <- list()
for(name in ls(buckets)) {
 b <- get(name,envir=buckets);rr <- lapply(seq_len(b$n),function(i)get(paste0('r',i),envir=b));cols <- names(rr[[1L]]);M <- do.call(rbind,lapply(rr,function(r)unlist(r,use.names=FALSE)));df <- as.data.frame(M,stringsAsFactors=FALSE);names(df) <- cols
 write.csv(df,file.path(outputDir,paste0(name,'.csv')),row.names=FALSE,na='',fileEncoding='UTF-8');manifest[[name]] <- list(rows=nrow(df),columns=ncol(df))
}
json <- function(x) {
 if(is.list(x)) {if(is.null(names(x)))paste0('[',paste(vapply(x,json,''),collapse=','),']')else paste0('{',paste(paste0('"',names(x),'":',vapply(x,json,'')),collapse=','),'}')}
 else if(length(x)!=1L)paste0('[',paste(vapply(as.list(x),json,''),collapse=','),']')
 else if(is.na(x))'null' else if(is.character(x))paste0('"',gsub('"','\\"',x,fixed=TRUE),'"')else if(is.logical(x))tolower(as.character(x))else format(x,digits=17,scientific=TRUE,trim=TRUE)
}
writeLines(json(list(method='Base R binary64 approximation, not exact',configurations=summaries,outputs=manifest,scope='Same restricted educational six configurations. No inferential/causal certificate. Numerical inversion/cancellation may fail even when the exact engine is defined.')),file.path(outputDir,'summary.json'),useBytes=TRUE)
cat(json(list(status='completed',configurations=length(summaries),CSV=length(manifest))), '\n')
