# ML13 standalone numerical counterpart; base R only.
# Reads native factual columns, reconstructs schedules/targets, and never reads
# the web engine, fitted JSON, Python outputs or computed answer CSVs.
# Arithmetic is binary64. Earliest candidate within 1e-12 of numerical minimum
# is retained; exact selection claims belong to the Fraction Python/web engine.
args <- commandArgs(trailingOnly=TRUE)
scriptarg <- grep("^--file=",commandArgs(),value=TRUE)
here <- if(dir.exists("ml13-sources")) getwd() else if(length(scriptarg)) dirname(normalizePath(sub("^--file=","",scriptarg[1]))) else getwd()
option <- function(key,default) { k<-match(key,args);if(is.na(k)) default else args[k+1] }
sourceDir<-option("--source",file.path(here,"ml13-sources"));outDir<-option("--out",file.path(here,"ml13-r-results"))
dir.create(outDir,recursive=TRUE,showWarnings=FALSE)
started<-proc.time()[3]
readnative<-function(name) read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses="character",na.strings=character(),stringsAsFactors=FALSE)
num<-function(x) {x[x%in%c("",".")]<-NA_character_;as.numeric(x)}
fmt<-function(x) ifelse(is.na(x),"",sprintf("%.17g",x))

# Vectorized SHA256 for the short ASCII keys used in this study.
# Unsigned words use exact integer-valued doubles; bit operations use safe
# 16-bit halves, avoiding R's reserved signed-INT_MIN/NA representation.
MOD<-2^32
xor32<-function(a,b) as.double(bitwXor(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwXor(as.integer(a%%65536),as.integer(b%%65536)))
and32<-function(a,b) as.double(bitwAnd(as.integer(floor(a/65536)),as.integer(floor(b/65536))))*65536+as.double(bitwAnd(as.integer(a%%65536),as.integer(b%%65536)))
rot<-function(x,n) floor(x/2^n)+(x%%2^n)*2^(32-n)
xor3<-function(a,b,c) xor32(xor32(a,b),c)
K<-c(0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2)
sha256<-function(strings) {
 n<-length(strings);bytes<-matrix(0,n,64)
 for(i in seq_len(n)) {v<-utf8ToInt(strings[i]);stopifnot(length(v)<56,all(v<128));if(length(v)) bytes[i,seq_along(v)]<-v;bytes[i,length(v)+1]<-128;bits<-length(v)*8;bytes[i,61:64]<-c(floor(bits/2^24)%%256,floor(bits/2^16)%%256,floor(bits/256)%%256,bits%%256)}
 w<-matrix(0,n,64)
 for(j in 1:16) {b<-4*(j-1)+1;w[,j]<-bytes[,b]*2^24+bytes[,b+1]*2^16+bytes[,b+2]*256+bytes[,b+3]}
 for(j in 17:64) {s0<-xor3(rot(w[,j-15],7),rot(w[,j-15],18),floor(w[,j-15]/8));s1<-xor3(rot(w[,j-2],17),rot(w[,j-2],19),floor(w[,j-2]/1024));w[,j]<-(w[,j-16]+s0+w[,j-7]+s1)%%MOD}
 init<-c(0x6a09e667,0xbb67ae85,0x3c6ef372,0xa54ff53a,0x510e527f,0x9b05688c,0x1f83d9ab,0x5be0cd19)
 state<-lapply(init,function(v) rep(v,n));a<-state[[1]];b<-state[[2]];c<-state[[3]];d<-state[[4]];e<-state[[5]];f<-state[[6]];g<-state[[7]];h<-state[[8]]
 for(j in 1:64) {S1<-xor3(rot(e,6),rot(e,11),rot(e,25));ch<-xor32(and32(e,f),and32(MOD-1-e,g));t1<-(h+S1+ch+K[j]+w[,j])%%MOD;S0<-xor3(rot(a,2),rot(a,13),rot(a,22));maj<-xor3(and32(a,b),and32(a,c),and32(b,c));t2<-(S0+maj)%%MOD;h<-g;g<-f;f<-e;e<-(d+t1)%%MOD;d<-c;c<-b;b<-a;a<-(t1+t2)%%MOD}
 end<-list(a,b,c,d,e,f,g,h);hex<-lapply(1:8,function(j){v<-(end[[j]]+init[j])%%MOD;paste0(sprintf("%04x",as.integer(floor(v/65536))),sprintf("%04x",as.integer(v%%65536)))})
 do.call(paste0,hex)
}
stopifnot(identical(sha256(c("abc","")),c("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad","e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855")))

loadData<-function(){
 wb<-readnative("actual64-country-four-indicators-original-2024.csv");codes<-c("NY.GDP.PCAP.KD","NY.GDP.MKTP.KD.ZG","FP.CPI.TOTL.ZG","SP.DYN.LE00.IN");iso<-sort(unique(wb$countryISO3));stopifnot(nrow(wb)==64,length(iso)==16)
 vals<-t(vapply(iso,function(s)num(wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))]),numeric(4)))
 country<-list(id=paste0(iso,":2024"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],y=ifelse(is.na(vals[,4]),NA_integer_,as.integer(vals[,4]>=80)),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=";"),character(1)),cat=integer())
 nls<-readnative("actual3613-NLS-original52-fields-and-nested-folds.csv")
 person<-list(id=paste0("person:",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=cbind(num(nls$ed76),num(nls$age76),num(nls$nearc4)),y=as.integer(num(nls$wage76)>=500),lineage=nls$sourceRow,cat=2L)
 ch<-readnative("actual3150-churn-original14-fields-and-nested-folds.csv")
 company<-list(id=paste0("customer:",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep("",nrow(ch)),x=cbind(num(ch[["Call  Failure"]]),num(ch$Complains),num(ch[["Subscription  Length"]]),num(ch[["Seconds of Use"]])),y=as.integer(ch$Churn),lineage=ch$sourceRow,cat=1L)
 stopifnot(nrow(nls)==3613,nrow(ch)==3150,identical(as.integer(ch$sourceRow[ch[["Charge  Amount"]]=="10"]),c(474L,2174L,2274L,2374L,2674L,2924L,2974L)))
 result<-list(country=country,person=person,company=company)
 for(k in names(result)){d<-result[[k]];d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;d$p<-ncol(d$x);result[[k]]<-d}
 stopifnot(sum(result$person$eligible)==3017);result
}
plans<-function(d){
 n<-length(d$id);A<-(d$sourceRow-1L)%%4L;B<-integer(n);B[order(sha256(paste0("ML13-B-outer|",d$id)),seq_len(n))]<-(seq_len(n)-1L)%%4L
 out<-list()
 for(name in c("A","B")){outer<-if(name=="A")A else B;inner<-list()
  for(o in 0:3){take<-which(outer!=o);v<-rep(NA_integer_,n)
   if(name=="A")v[take]<-(d$sourceRow[take]-1L)%%3L else {take<-take[order(sha256(paste0("ML13-B-inner-",o,"|",d$id[take])),take)];v[take]<-(seq_along(take)-1L)%%3L}
   inner[[o+1]]<-v
  };out[[name]]<-list(outer=outer,inner=inner)
 };out
}
configs<-function(p){s<-list(integer());for(k in 1:p)s<-c(s,combn(0:(p-1),k,simplify=FALSE));c(lapply(s,function(v)list(subset=v,alpha=1)),list(list(subset=0:(p-1),alpha=0)))}
tables<-setNames(lapply(1:10,function(i)list()),c("metrics","candidate-criteria","fold-criteria","fit-medians","fit-cells","outer-predictions","selected-predictions","covariance","lineage","frame-membership"))
add<-function(name,d){tables[[name]][[length(tables[[name]])+1L]]<<-d}
study<-function(kind,schedule,d,plan){
 n<-length(d$id);frame<-which(d$eligible);cs<-configs(d$p);cache<-list();registered<-character()
 tags<-function(...)data.frame(kind=kind,schedule=schedule,...,check.names=FALSE,stringsAsFactors=FALSE)
 register<-function(scope,fit,test,available){if(scope%in%registered)return(invisible(NULL));registered<<-c(registered,scope);role<-rep("outside",n);role[available]<-"excluded";role[fit]<-"train";role[test]<-"test";add("frame-membership",tags(scope=scope,id=d$id,sourceRow=d$sourceRow,eligible=as.integer(d$eligible),role=role))}
 pre<-function(fit){hit<-which(vapply(cache,function(item)identical(item$ids,fit),logical(1)));if(length(hit))return(cache[[hit[1]]]$medians);m<-vapply(seq_len(d$p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[fit,j]),numeric(1));cache[[length(cache)+1L]]<<-list(ids=fit,medians=m);m}
 transform<-function(m){z<-d$x;for(j in seq_len(d$p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j]);z}
 keys<-function(z,sub){if(!length(sub))return(rep("(constant)",nrow(z)));apply(z[,sub+1,drop=FALSE],1,function(v)paste(sprintf("%.17g",v),collapse="|"))}
 fitmodel<-function(ids,ci,scope){cfg<-cs[[ci+1]];m<-pre(ids);z<-transform(m);key<-keys(z,cfg$subset);lev<-unique(key[ids]);mass<-vapply(lev,function(k)sum(key[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][key[ids]==k]),integer(1));p<-(positive+cfg$alpha)/(mass+2*cfg$alpha);fallback<-(sum(d$y[ids])+cfg$alpha)/(length(ids)+2*cfg$alpha)
  add("fit-medians",tags(scope=scope,candidate=ci,subset=paste(cfg$subset,collapse=","),alphaExact=as.character(cfg$alpha),feature=0:(d$p-1),categorical=as.integer(0:(d$p-1)%in%d$cat),fitRows=length(ids),medianExact="",medianApprox=fmt(m)))
  add("fit-cells",tags(scope=scope,candidate=ci,cell=lev,mass=mass,positive=positive,probabilityExact="",probabilityApprox=fmt(p),fallbackExact="",fallbackApprox=fmt(fallback)))
  pred<-p[match(key,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[rowSums(is.na(d$x))>0]<-NA_real_
  list(pred=pred,unseen=unseen,ci=ci,scope=scope)
 }
 score<-function(model,test){loss<-sum((model$pred[test]-d$y[test])^2);list(total=loss,risk=loss/length(test))}
 emit<-function(model,ids,scope,fold,role,outer=FALSE){prob<-model$pred[ids];eligible<-d$eligible[ids];loss<-ifelse(eligible,(prob-d$y[ids])^2,NA_real_);reason<-ifelse(rowSums(is.na(d$x[ids,,drop=FALSE]))>0,"required-query-X-missing",ifelse(eligible,"","common-required-observation"));unseen<-ifelse(is.na(prob),"",as.character(as.integer(model$unseen[ids])));if(role!="final-query-with-training-overlap"){prob[!eligible]<-NA_real_;loss[!eligible]<-NA_real_;unseen[!eligible]<-"";reason[!eligible]<-"common-required-observation-or-positive-mass"}
  add(if(outer)"outer-predictions"else"selected-predictions",tags(role=role,scope=scope,fold=fold,candidate=model$ci,id=d$id[ids],sourceRow=d$sourceRow[ids],originalID=d$originalID[ids],eligible=as.integer(eligible),y=ifelse(is.na(d$y[ids]),"",as.character(d$y[ids])),probabilityExact="",probabilityApprox=fmt(prob),BrierExact="",BrierApprox=fmt(loss),unseenCell=unseen,reason=reason))
 }
 select<-function(available,labels,scope){fr<-available[d$eligible[available]];folds<-sort(unique(labels[fr]));stopifnot(length(folds)>=2,!anyNA(folds));results<-list()
  for(ci in 0:(length(cs)-1)){ff<-list();total<-0;macro<-0
   for(f in folds){train<-fr[labels[fr]!=f];test<-fr[labels[fr]==f];fs<-paste0(scope,"-fold-",f);register(fs,train,test,available);model<-fitmodel(train,ci,fs);s<-score(model,test);ff[[length(ff)+1]]<-list(fold=f,fit=model,test=test,total=s$total,risk=s$risk);total<-total+s$total;macro<-macro+s$risk
    add("fold-criteria",tags(scope=scope,candidate=ci,fold=f,trainingRows=length(train),testRows=length(test),testPositive=sum(d$y[test]),totalLossExact="",totalLossApprox=fmt(s$total),BrierExact="",BrierApprox=fmt(s$risk)))
   };results[[ci+1]]<-list(ci=ci,folds=ff,pooled=total/length(fr),macro=macro/length(folds))
  };values<-vapply(results,function(r)r$pooled,numeric(1));best<-which(values<=min(values)+1e-12)[1]-1L
  for(r in results){cfg<-cs[[r$ci+1]];add("candidate-criteria",tags(scope=scope,candidate=r$ci,subset=paste(cfg$subset,collapse=","),alphaExact=as.character(cfg$alpha),rows=length(fr),pooledExact="",pooledApprox=fmt(r$pooled),macroExact="",macroApprox=fmt(r$macro),selected=as.integer(r$ci==best)))}
  list(best=best,results=results)
 }
 metric<-function(name,value,unit="dimensionless")add("metrics",tags(metric=name,valueExact=if(unit=="dimensionless")""else as.character(value),valueApprox=fmt(value),unit=unit,defined=1L))
 outer<-plan$outer;losses<-numeric(4);risks<-numeric(4);choices<-integer(4)
 for(o in 0:3){available<-which(outer!=o);choice<-select(available,plan$inner[[o+1]],paste0("outer-",o,"-inner"));best<-choice$best;choices[o+1]<-best;train<-available[d$eligible[available]];test<-frame[outer[frame]==o];scope<-paste0("outer-",o,"-refit");register(scope,train,test,seq_len(n));model<-fitmodel(train,best,scope);s<-score(model,test);losses[o+1]<-s$total;risks[o+1]<-s$risk;emit(model,which(outer==o),scope,o,"outer-held",TRUE)
  for(ff in choice$results[[best+1]]$folds)emit(ff$fit,available[plan$inner[[o+1]][available]==ff$fold],paste0("outer-",o,"-inner"),ff$fold,"selected-inner-held")
  metric(paste0("outer",o,"SelectedCandidate"),best,"candidate index");metric(paste0("outer",o,"Rows"),length(test),"rows");metric(paste0("outer",o,"Brier"),s$risk)
 }
 pooled<-sum(losses)/length(frame);macro<-mean(risks);sel<-select(seq_len(n),outer,"full-selection");best<-sel$best
 for(ff in sel$results[[best+1]]$folds)emit(ff$fit,which(outer==ff$fold),"full-selection",ff$fold,"selected-full-CV-held")
 register("final-all-fit",frame,integer(),seq_len(n));final<-fitmodel(frame,best,"final-all-fit");emit(final,seq_len(n),"final-all-fit","all","final-query-with-training-overlap");training<-score(final,frame)$risk
 for(z in list(list("retainedRows",n,"rows"),list("eligibleRows",length(frame),"rows"),list("excludedRows",n-length(frame),"rows"),list("positiveRows",sum(d$y[frame]),"rows"),list("candidateCount",length(cs),"candidates"),list("nestedPooledBrier",pooled,"dimensionless"),list("nestedMacroBrier",macro,"dimensionless"),list("nonnestedMinimumBrier",sel$results[[best+1]]$pooled,"dimensionless"),list("nestedMinusNonnested",pooled-sel$results[[best+1]]$pooled,"dimensionless"),list("finalSelectedCandidate",best,"candidate index"),list("finalTrainingBrier",training,"dimensionless")))metric(z[[1]],z[[2]],z[[3]])
 risks
}
allData<-loadData();summaries<-list()
for(kind in names(allData)){d<-allData[[kind]];ps<-plans(d);L<-rbind(study(kind,"A",d,ps$A),study(kind,"B",d,ps$B));S<-cov(L);variance<-var(rowMeans(L));stopifnot(abs(sum(S)/16-variance)<1e-14)
 for(k in 1:4)for(j in 1:4)add("covariance",data.frame(kind=kind,completeRepeats=2,foldK=k-1,foldL=j-1,covarianceExact="",covarianceApprox=fmt(S[k,j]),macroVarianceExact="",macroVarianceApprox=fmt(variance),identityResidualExact="",interpretation="Descriptive same-data fixed A/B schedules; not population SE",stringsAsFactors=FALSE))
 line<-data.frame(kind=kind,id=d$id,sourceRow=d$sourceRow,originalID=d$originalID,indicatorSourceRows=d$lineage,eligible=as.integer(d$eligible),target=ifelse(is.na(d$y),"",as.character(d$y)),XExact="",missingFeatures=apply(is.na(d$x),1,function(v)paste(which(v)-1L,collapse=",")),missingTarget=as.integer(is.na(d$y)),stringsAsFactors=FALSE)
 for(name in c("A","B")){line[[paste0("outer",name)]]<-ps[[name]]$outer;for(o in 0:3)line[[paste0("inner",name,o)]]<-ifelse(is.na(ps[[name]]$inner[[o+1]]),"",as.character(ps[[name]]$inner[[o+1]]))}
 add("lineage",line)
}
outputs<-data.frame(file=character(),rows=integer(),columns=integer(),bodyFields=integer())
for(name in names(tables)){d<-do.call(rbind,tables[[name]]);p<-file.path(outDir,paste0("computed-",name,".csv"));write.csv(d,p,row.names=FALSE,na="",fileEncoding="UTF-8");outputs<-rbind(outputs,data.frame(file=basename(p),rows=nrow(d),columns=ncol(d),bodyFields=nrow(d)*ncol(d)))}
write.csv(outputs,file.path(outDir,"manifest.csv"),row.names=FALSE)
writeLines(c("ML13 base-R numerical reproduction. Native factual CSV columns only; targets and SHA256 schedules reconstructed.","All calculated Exact columns intentionally empty: R binary64 is not an arbitrary-precision rational engine.","Candidate rule: earliest within 1e-12 of numerical minimum; compare all actual choices/criteria with exact Python, not a general exact-tie promise.","A/B variance is a finite descriptive statistic for repeated partitions of the same observations, not population SE/CI.",paste("Elapsed seconds:",proc.time()[3]-started)),file.path(outDir,"arithmetic-scope.txt"))
cat("complete base-R numerical source study;",nrow(outputs),"tables;",sum(outputs$bodyFields),"body fields;",proc.time()[3]-started,"seconds\n")
