# AI09 standalone base-R reproduction. No packages, JS engine or private answers.
# Usage: Rscript ai09-reproduce.R source_directory output_directory
# R uses finite binary64 arithmetic; Python Fraction companion retains exact values.
args <- commandArgs(trailingOnly=TRUE)
source_dir <- if(length(args)>=1) args[1] else "ai09-sources"
output_dir <- if(length(args)>=2) args[2] else "ai09-reproduced-R"
dir.create(output_dir,recursive=TRUE,showWarnings=FALSE)
options(digits=17)
raw <- read.csv(file.path(source_dir,"actual5620-original64pixels-and-label.csv"),
                colClasses="character",check.names=FALSE,stringsAsFactors=FALSE)
stopifnot(nrow(raw)==5620)
chosen <- raw[raw$cnnRole!="unused",,drop=FALSE]
pixel_names <- unlist(lapply(0:7,function(y)paste0("pixel_r",y,"c",0:7)))
records <- lapply(seq_len(nrow(chosen)),function(i){
 r <- chosen[i,,drop=FALSE]
 p <- matrix(as.numeric(r[1,pixel_names]),8,8,byrow=TRUE)
 stopifnot(all(p>=0 & p<=16))
 list(id=r$originId,sourceFile=r$sourceFile,sourceRow=as.integer(r$sourceRow),
      role=r$cnnRole,label=as.integer(r$digit),pixels=p)
})
subset_role <- function(role) Filter(function(r) r$role==role,records)
training<-subset_role("train");validation<-subset_role("validation");testing<-subset_role("test")
stopifnot(length(training)==40,length(validation)==20,length(testing)==60)
parameter_names <- c(unlist(lapply(0:2,function(y)paste0("K[0,0,",y,",",0:2,"]"))),
 "convBias[0]",unlist(lapply(0:9,function(k)paste0("H[",k,",",0:8,"]"))),paste0("headBias[",0:9,"]"))
theta <- c(as.numeric(0:8==4),0)
state <- 17
for(j in 1:90){state <- (16807*state)%%2147483647;theta <- c(theta,if(2*state<2147483647) -1/20 else 1/20)}
theta <- c(theta,rep(0,10))
forward <- function(parameters,row){
 image <- row$pixels/16
 patches <- matrix(0,36,9)
 at <- 1L
 for(y in 1:6)for(x in 1:6){
  patches[at,] <- as.vector(t(image[y:(y+2),x:(x+2),drop=FALSE]));at<-at+1L
 }
 z <- as.numeric(patches%*%parameters[1:9]+parameters[10])
 a <- pmax(0,z)
 feature <- numeric(9);at<-1L
 for(y in 0:2)for(x in 0:2){
  pos <- unlist(lapply(0:1,function(j)(2*y+j)*6+2*x+0:1+1))
  feature[at] <- mean(a[pos]);at<-at+1L
 }
 head <- matrix(parameters[11:100],10,9,byrow=TRUE)
 scores <- as.numeric(head%*%feature+parameters[101:110])
 list(image=image,patches=patches,z=z,a=a,features=feature,scores=scores)
}
loss_signals <- function(parameters,rows){
 gradient <- numeric(110);loss<-0
 head <- matrix(parameters[11:100],10,9,byrow=TRUE)
 for(row in rows){
  f <- forward(parameters,row);target<-as.numeric(0:9==row$label)
  residual <- f$scores-target
  loss <- loss+sum(residual^2)/(2*length(rows));seed<-residual/length(rows)
  gradient[101:110] <- gradient[101:110]+seed
  gradient[11:100] <- gradient[11:100]+as.vector(t(outer(seed,f$features)))
  feature_signal <- as.numeric(t(head)%*%seed)
  pre_signal <- numeric(36)
  for(y in 0:5)for(x in 0:5){
   at <- y*6+x+1
   pre_signal[at] <- if(f$z[at]>0) feature_signal[(y%/%2)*3+x%/%2+1]/4 else 0
  }
  gradient[1:9] <- gradient[1:9]+as.numeric(t(f$patches)%*%pre_signal)
  gradient[10] <- gradient[10]+sum(pre_signal)
 }
 list(loss=loss,gradient=gradient)
}
checkpoints<-list();parameter_rows<-list();signal_rows<-list();update_rows<-list();metric_rows<-list()
for(t in 0:2){
 tr<-loss_signals(theta,training);va<-loss_signals(theta,validation)
 checkpoints[[t+1]]<-list(index=t,parameters=theta,trainLoss=tr$loss,validationLoss=va$loss,gradient=tr$gradient)
 metric_rows[[length(metric_rows)+1]]<-c(t,"train","meanHalfSquaredScoreLoss",tr$loss)
 metric_rows[[length(metric_rows)+1]]<-c(t,"validation","meanHalfSquaredScoreLoss",va$loss)
 for(j in 1:110){
  parameter_rows[[length(parameter_rows)+1]]<-c(t,j-1,parameter_names[j],if(j==10 || j>=101)"bias" else "weight",theta[j])
  signal_rows[[length(signal_rows)+1]]<-c(t,j-1,parameter_names[j],tr$gradient[j])
 }
 if(t<2){
  next_theta<-theta-tr$gradient/100
  for(j in 1:110)update_rows[[length(update_rows)+1]]<-c(t+1,j-1,parameter_names[j],theta[j],tr$gradient[j],1/100,next_theta[j])
  theta<-next_theta
 }
}
selected <- which.min(vapply(checkpoints,function(c)c$validationLoss,0))-1L
parameters <- checkpoints[[selected+1]]$parameters
shift <- function(row){row$pixels<-cbind(rep(0,8),row$pixels[,1:7,drop=FALSE]);row}
shifted_test <- lapply(testing,shift)
classify <- function(scores){
 k<-which.max(scores);other<-max(scores[-k])
 list(label=k-1L,margin=scores[k]-other,ties=which(scores==scores[k])-1L)
}
evaluate_task <- function(task,rows){
 confusion <- matrix(0,10,10);prediction_rows<-list()
 for(row in rows){
  f<-forward(parameters,row);p<-classify(f$scores)
  confusion[row$label+1,p$label+1]<-confusion[row$label+1,p$label+1]+1
  loss<-sum((f$scores-as.numeric(0:9==row$label))^2)/2
  prediction_rows[[length(prediction_rows)+1]]<-c(task,row$id,row$sourceFile,row$sourceRow,row$role,row$label,p$label,p$margin,paste(p$ties,collapse="|"),as.integer(p$label==row$label),loss,f$scores)
 }
 per_class<-list()
 for(k in 0:9){
  support<-sum(confusion[k+1,]);predicted<-sum(confusion[,k+1]);tp<-confusion[k+1,k+1]
  per_class[[k+1]]<-c(task,k,support,predicted,tp,if(predicted>0)tp/predicted else NA,if(support>0)tp/support else NA)
 }
 list(confusion=confusion,predictions=prediction_rows,perClass=per_class,accuracy=sum(diag(confusion))/length(rows))
}
tasks <- list(native=testing,shifted=shifted_test,audit=training)
evaluations <- lapply(names(tasks),function(task)evaluate_task(task,tasks[[task]]));names(evaluations)<-names(tasks)
stage_rows <- list()
for(task in c("original","shifted")){
 rows <- if(task=="original") records else shifted_test
 for(row in rows){
  f <- forward(parameters,row)
  stages<-list(convolution=f$z,relu=f$a,pooled=f$features,flattened=f$features,scores=f$scores)
  widths<-c(convolution=6,relu=6,pooled=3,flattened=9,scores=10)
  for(stage in names(stages)){
   values<-stages[[stage]];width<-widths[[stage]]
   for(j in seq_along(values))stage_rows[[length(stage_rows)+1]]<-c(task,row$id,row$role,stage,(j-1)%/%width,(j-1)%%width,values[j])
  }
 }
}
# Vectors combine labels and numbers, so preserve 17-digit numeric tokens before
# combination rather than relying on R's shortened character coercion.
# Every CSV numeric cell is rewritten from its full numeric source below.
precise <- function(x)ifelse(is.na(x),"",format(x,digits=17,scientific=TRUE,trim=TRUE))
for(i in seq_along(parameter_rows))parameter_rows[[i]][5]<-sprintf("%.17g",checkpoints[[as.integer(parameter_rows[[i]][1])+1]]$parameters[as.integer(parameter_rows[[i]][2])+1])
for(i in seq_along(signal_rows))signal_rows[[i]][4]<-sprintf("%.17g",checkpoints[[as.integer(signal_rows[[i]][1])+1]]$gradient[as.integer(signal_rows[[i]][2])+1])
for(i in seq_along(metric_rows)){t<-as.integer(metric_rows[[i]][1])+1;metric_rows[[i]][4]<-sprintf("%.17g",if(metric_rows[[i]][2]=="train")checkpoints[[t]]$trainLoss else checkpoints[[t]]$validationLoss)}
for(i in seq_along(update_rows)){
 t<-as.integer(update_rows[[i]][1]);j<-as.integer(update_rows[[i]][2])+1
 update_rows[[i]][4:7]<-sprintf("%.17g",c(checkpoints[[t]]$parameters[j],checkpoints[[t]]$gradient[j],.01,checkpoints[[t+1]]$parameters[j]))
}
# Recreate stage and prediction display tokens with explicit full precision.
at<-1L
for(task in c("original","shifted"))for(row in if(task=="original")records else shifted_test){
 f<-forward(parameters,row)
 for(values in list(f$z,f$a,f$features,f$features,f$scores))for(v in values){
  stage_rows[[at]][7]<-sprintf("%.17g",v);at<-at+1L
 }
}
for(task in names(tasks))for(i in seq_along(tasks[[task]])){
 row<-tasks[[task]][[i]];f<-forward(parameters,row);p<-classify(f$scores)
 loss<-sum((f$scores-as.numeric(0:9==row$label))^2)/2
 evaluations[[task]]$predictions[[i]][c(8,11:21)]<-sprintf("%.17g",c(p$margin,loss,f$scores))
}
emit <- function(name,header,rows){
 tab<-as.data.frame(do.call(rbind,rows),stringsAsFactors=FALSE);names(tab)<-header
 write.table(tab,file.path(output_dir,name),sep=",",row.names=FALSE,col.names=TRUE,quote=TRUE,na="")
}
emit("checkpoints.csv",c("checkpoint","role","metric","value"),metric_rows)
emit("parameters.csv",c("checkpoint","parameterIndex","parameter","kind","value"),parameter_rows)
emit("training-signals.csv",c("checkpoint","parameterIndex","parameter","signal"),signal_rows)
emit("updates.csv",c("update","parameterIndex","parameter","oldValue","oldSignal","learningRate","newValue"),update_rows)
emit("stage-values.csv",c("task","originId","role","stage","row","column","value"),stage_rows)
emit("predictions.csv",c("task","originId","sourceFile","sourceRow","sourceRole","observed","predicted","scoreMargin","tiedClasses","correct","halfSquaredScoreLoss",paste0("score",0:9)),unlist(lapply(evaluations,function(e)e$predictions),recursive=FALSE))
confusion_rows<-list();per_class_rows<-list()
for(task in names(tasks)){
 e<-evaluations[[task]]
 for(y in 0:9)for(x in 0:9)confusion_rows[[length(confusion_rows)+1]]<-c(task,y,x,e$confusion[y+1,x+1])
 for(k in 0:9){
  support<-sum(e$confusion[k+1,]);predicted<-sum(e$confusion[,k+1]);tp<-e$confusion[k+1,k+1]
  per_class_rows[[length(per_class_rows)+1]]<-c(task,k,support,predicted,tp,if(predicted) sprintf("%.17g",tp/predicted) else NA,if(support) sprintf("%.17g",tp/support) else NA)
 }
}
emit("confusion.csv",c("task","observed","predicted","count"),confusion_rows)
emit("per-class.csv",c("task","class","support","predictedCount","truePositive","precision","recall"),per_class_rows)
shifted_pixels<-list()
for(row in shifted_test)for(y in 0:7)for(x in 0:7){
 v<-row$pixels[y+1,x+1]
 shifted_pixels[[length(shifted_pixels)+1]]<-c(row$id,row$sourceRow,y,x,v,sprintf("%.17g",v/16))
}
emit("shifted-pixels.csv",c("originId","sourceRow","row","column","nativeCount","normalizedValue"),shifted_pixels)
summary_rows<-list(c("selectedCheckpoint",selected),c("parameters",110),c("updates",2),
 c("nativeAccuracy",sprintf("%.17g",evaluations$native$accuracy)),
 c("shiftedAccuracy",sprintf("%.17g",evaluations$shifted$accuracy)),
 c("auditAccuracy",sprintf("%.17g",evaluations$audit$accuracy)))
emit("R-summary.csv",c("metric","value"),summary_rows)
cat("Base-R standalone CNN completed. Selected checkpoint:",selected,"\n")
for(task in names(tasks))cat(task,"accuracy:",sprintf("%.17g",evaluations[[task]]$accuracy),"\n")
