# ML14 standalone public counterpart, base R only.
# Inputs are only the three factual CSVs; derived columns/previous model answers unused.
# Binary64 arithmetic, not arbitrary-precision Fraction. At numerical cost ties
# within 1e-12 retain the earliest candidate. Exact claims belong to Python/web.
# SHA256 infrastructure below is reused verbatim from the previous public study.
args<-commandArgs(trailingOnly=TRUE);filearg<-grep("^--file=",commandArgs(),value=TRUE)
here<-if(dir.exists("ml14-sources"))getwd()else if(length(filearg))dirname(normalizePath(sub("^--file=","",filearg[1])))else getwd()
option<-function(key,default){i<-match(key,args);if(is.na(i))default else args[i+1]}
sourceDir<-option("--source",file.path(here,"ml14-sources"));outDir<-option("--out",file.path(getwd(),"ml14-r-results"));dir.create(outDir,recursive=TRUE,showWarnings=FALSE)
num<-function(x){x[x%in%c("",".")]<-NA_character_;as.numeric(x)}
fmt<-function(x)ifelse(is.na(x),"",sprintf("%.17g",x))
ratio<-function(a,b)if(b==0)NA_real_ else a/b
readnative<-function(name)read.csv(file.path(sourceDir,name),check.names=FALSE,colClasses="character",na.strings=character(),stringsAsFactors=FALSE)
# 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)
 tokens<-t(vapply(iso,function(s)wb$originalValueToken[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],character(4)));vals<-matrix(num(as.vector(tokens)),nrow=nrow(tokens))
 country<-list(id=paste0(iso,":2024"),sourceRow=1:16,originalID=iso,x=vals[,1:3,drop=FALSE],rawX=tokens[,1:3,drop=FALSE],nativeTarget=tokens[,4],y=as.integer(vals[,4]>=80),group=ifelse(is.na(vals[,1]),NA_character_,as.character(as.integer(vals[,1]>=25000))),lineage=vapply(iso,function(s)paste(wb$sourceRow[match(paste(s,codes),paste(wb$countryISO3,wb$indicatorID))],collapse=";"),character(1)),cat=integer(),units=c("constant2015USD/person","annualPercent","annualPercent"))
 nls<-readnative("actual3613-NLS-original52-fields-groups-roles.csv");raw<-cbind(nls$ed76,nls$age76,nls$nearc4)
 person<-list(id=paste0("person:",nls$sourceRow),sourceRow=as.integer(nls$sourceRow),originalID=nls$id,x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=nls$wage76,y=as.integer(num(nls$wage76)>=500),group=ifelse(nls$black%in%c("","."),NA_character_,nls$black),lineage=nls$sourceRow,cat=2L,units=c("years","years","nativeCategory"))
 ch<-readnative("actual3150-churn-original14-fields-groups-roles.csv");raw<-cbind(ch[["Call  Failure"]],ch$Complains,ch[["Subscription  Length"]],ch[["Seconds of Use"]])
 company<-list(id=paste0("customer:",ch$sourceRow),sourceRow=as.integer(ch$sourceRow),originalID=rep("",nrow(ch)),x=matrix(num(as.vector(raw)),nrow=nrow(raw)),rawX=raw,nativeTarget=ch$Churn,y=as.integer(ch$Churn),group=ifelse(ch[["Tariff Plan"]]%in%c("","."),NA_character_,ch[["Tariff Plan"]]),lineage=ch$sourceRow,cat=1L,units=c("count","nativeCategory","months","seconds"))
 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]];n<-length(d$id);d$eligible<-!is.na(d$y)&rowSums(is.na(d$x))==0;hash<-sha256(paste0("ML14-role|",k,"|",d$id));rank<-integer(n);rank[order(hash,seq_len(n))]<-seq_len(n)-1L;d$plannedRole<-ifelse(rank%%5==0,"test",ifelse(rank%%5==1,"validation","train"));d$role<-ifelse(d$eligible,d$plannedRole,"excluded");result[[k]]<-d}
 stopifnot(sum(result$person$eligible)==3017);result
}
fitmodel<-function(d){
 ids<-which(d$role=="train");p<-ncol(d$x);m<-vapply(seq_len(p),function(j)if((j-1)%in%d$cat)NA_real_ else median(d$x[ids,j]),numeric(1));z<-d$x
 for(j in seq_len(p))if(!((j-1)%in%d$cat))z[,j]<-as.numeric(z[,j]>m[j])
 keys<-apply(z,1,function(v)paste(fmt(v),collapse="|"));lev<-unique(keys[ids]);mass<-vapply(lev,function(k)sum(keys[ids]==k),integer(1));positive<-vapply(lev,function(k)sum(d$y[ids][keys[ids]==k]),integer(1));prob<-(positive+1)/(mass+2);fallback<-(sum(d$y[ids])+1)/(length(ids)+2);pred<-prob[match(keys,lev)];unseen<-is.na(pred);pred[unseen]<-fallback;pred[!d$eligible]<-NA_real_;unseen[!d$eligible]<-NA
 list(ids=ids,medians=m,z=z,keys=keys,lev=lev,mass=mass,positive=positive,prob=prob,fallback=fallback,pred=pred,unseen=unseen)
}
measure<-function(d,p,ids,t=.5,cost=c(1,1)){
 use<-ids[d$eligible[ids]&!is.na(p[ids])];y<-d$y[use];a<-if(is.character(t))rep(t=="always-positive",length(use))else p[use]>=t
 TP<-sum(a&y==1);FP<-sum(a&y==0);FN<-sum(!a&y==1);TN<-sum(!a&y==0);P<-TP+FN;N<-FP+TN;W<-P+N;PP<-TP+FP;PN<-TN+FN;TPR<-ratio(TP,P);TNR<-ratio(TN,N);bs<-sum((p[use]-y)^2);tc<-FP*cost[1]+FN*cost[2]
 list(TP=TP,FP=FP,FN=FN,TN=TN,mass=W,positiveTargetMass=P,negativeTargetMass=N,predictedPositiveMass=PP,predictedNegativeMass=PN,prevalence=ratio(P,W),selectionRate=ratio(PP,W),accuracy=ratio(TP+TN,W),precision=ratio(TP,PP),negativePredictiveValue=ratio(TN,PN),TPR=TPR,FPR=ratio(FP,N),TNR=TNR,FNR=ratio(FN,P),F1=ratio(2*TP,2*TP+FP+FN),balancedAccuracy=if(is.na(TPR)||is.na(TNR))NA_real_ else(TPR+TNR)/2,Brier=ratio(bs,W),BrierSum=bs,totalCost=tc,meanCost=ratio(tc,W))
}
curves<-function(d,p,ids){
 use<-ids[d$eligible[ids]&!is.na(p[ids])];scores<-sort(unique(p[use]),decreasing=TRUE);policies<-c(list("always-negative"),as.list(scores));points<-lapply(policies,function(t){m<-measure(d,p,ids,t);c(list(policy=t),m[c("TP","FP","FN","TN","TPR","FPR","precision")],list(recall=m$TPR))})
 pos<-use[d$y[use]==1];neg<-use[d$y[use]==0];U<-0;for(i in pos)U<-U+sum(p[i]>p[neg])+.5*sum(p[i]==p[neg])
 AP<-0;trap<-0;lastR<-0;lastP<-1
 if(length(pos)&&length(scores))for(j in seq_along(scores)){z<-points[[j+1]];AP<-AP+(z$recall-lastR)*z$precision;trap<-trap+(z$recall-lastR)*(z$precision+lastP)/2;lastR<-z$recall;lastP<-z$precision}
 list(points=points,ROC_AUC=ratio(U,length(pos)*length(neg)),averagePrecision=if(length(pos))AP else NA_real_,PRTrapezoidWithInitialPrecisionOne=if(length(pos))trap else NA_real_)
}
calibrate<-function(d,p,ids){
 use<-ids[d$eligible[ids]&!is.na(p[ids])];W<-length(use);pi<-if(W)mean(d$y[use])else NA_real_;bins<-list();ECE<-rel<-res<-correction<-0
 whichbin<-findInterval(p[use],seq(0,1,.2),rightmost.closed=TRUE,all.inside=TRUE)
 for(b in 1:5){rr<-use[whichbin==b];w<-length(rr);mp<-if(w)mean(p[rr])else NA_real_;o<-if(w)mean(d$y[rr])else NA_real_;variance<-if(w)mean((p[rr]-mp)^2)else NA_real_;covariance<-if(w)mean((p[rr]-mp)*(d$y[rr]-o))else NA_real_;bc<-variance-2*covariance;gap<-mp-o
  bins[[b]]<-list(mass=w,meanPrediction=mp,eventRate=o,gap=gap,absoluteGap=abs(gap),scoreVariance=variance,scoreTargetCovariance=covariance,withinBinCorrection=bc,rows=w,ids=d$id[rr])
  if(w){share<-w/W;ECE<-ECE+share*abs(gap);rel<-rel+share*gap^2;res<-res+share*(o-pi)^2;correction<-correction+share*bc}
 };bs<-if(W)mean((p[use]-d$y[use])^2)else NA_real_;unc<-pi*(1-pi)
 list(bins=bins,ECE=if(W)ECE else NA_real_,Brier=bs,reliability=if(W)rel else NA_real_,resolution=if(W)res else NA_real_,uncertainty=unc,withinBinCorrection=if(W)correction else NA_real_,BrierIdentityResidual=bs-(unc-res+rel+correction))
}
counts<-c("mass","positiveTargetMass","negativeTargetMass","predictedPositiveMass","predictedNegativeMass");rates<-c("prevalence","selectionRate","accuracy","precision","negativePredictiveValue","TPR","FPR","TNR","FNR","F1","balancedAccuracy","Brier","BrierSum","totalCost","meanCost")
tables<-setNames(lapply(1:10,function(i)list()),c("predictions","lineage","fit-medians","fit-cells","validation-candidates","test-metrics","test-curves","calibration-bins","group-metrics","chart-points"))
add<-function(name,row)tables[[name]][[length(tables[[name]])+1L]]<<-row
scalars<-function(m,keys){out<-list();for(k in keys){out[[paste0(k,"Exact")]]<-"";out[[paste0(k,"Approx")]]<-fmt(m[[k]])};out}
tagrow<-function(kind,...)c(list(kind=kind),list(...))
point<-function(kind,chart,series,index,x,y,xunit="dimensionless",yunit="dimensionless",role="test",tag=""){add("chart-points",tagrow(kind,chart=chart,series=series,index=index,xExact="",xApprox=fmt(x),yExact="",yApprox=fmt(y),xUnit=xunit,yUnit=yunit,role=role,tag=tag))}
study<-function(kind,d){
 f<-fitmodel(d);n<-length(d$id);train<-which(d$role=="train");validation<-which(d$role=="validation");test<-which(d$role=="test");p<-f$pred;cv<-curves(d,p,test);cal<-calibrate(d,p,test)
 for(i in seq_len(n)){
  reason<-if(d$eligible[i])""else"required-X-or-Y-missing";transformed<-if(d$eligible[i])paste(fmt(f$z[i,]),collapse="|")else""
  add("predictions",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],plannedRole=d$plannedRole[i],role=d$role[i],group=ifelse(is.na(d$group[i]),"",d$group[i]),eligible=as.integer(d$eligible[i]),targetExact=fmt(d$y[i]),probabilityExact="",probabilityApprox=fmt(p[i]),unseenCell=ifelse(is.na(f$unseen[i]),"",as.character(as.integer(f$unseen[i]))),transformedX=transformed,reason=reason))
  raw<-d$rawX[i,];raw[raw%in%c("",".")]<-"";nativeY<-d$nativeTarget[i];if(nativeY%in%c("","."))nativeY<-""
  add("lineage",tagrow(kind,id=d$id[i],sourceRow=d$sourceRow[i],originalID=d$originalID[i],nativeSourceRows=d$lineage[i],rawX=paste(raw,collapse="|"),nativeTarget=nativeY,derivedTarget=fmt(d$y[i]),nativeGroup=ifelse(is.na(d$group[i]),"",d$group[i]),plannedRole=d$plannedRole[i],role=d$role[i],eligible=as.integer(d$eligible[i]),analyticalMass="1",reason=reason))
 }
 for(j in seq_len(ncol(d$x)))add("fit-medians",tagrow(kind,feature=j-1,categorical=as.integer((j-1)%in%d$cat),fitRows=length(train),medianExact="",medianApprox=fmt(f$medians[j]),unit=d$units[j]))
 for(j in seq_along(f$lev))add("fit-cells",tagrow(kind,cell=f$lev[j],trainingRows=f$mass[j],positiveRows=f$positive[j],probabilityExact="",probabilityApprox=fmt(f$prob[j]),fallbackExact="",fallbackApprox=fmt(f$fallback)))
 for(j in seq_along(cv$points)){
  z<-cv$points[[j]];t<-z$policy;add("test-curves",c(tagrow(kind,point=j-1,policy=if(is.character(t))t else"threshold",thresholdExact="",thresholdApprox=if(is.character(t))""else fmt(t)),scalars(z,c("TP","FP","FN","TN","TPR","FPR","precision","recall"))))
  point(kind,"roc","ROC",j-1,z$FPR,z$TPR);point(kind,"pr","PR-observed",j-1,z$recall,z$precision)
 }
 for(b in 1:5){z<-cal$bins[[b]];add("calibration-bins",c(tagrow(kind,bin=b-1,leftExact=c("0","1/5","2/5","3/5","4/5")[b],rightExact=c("1/5","2/5","3/5","4/5","1")[b],rightClosed=as.integer(b==5),rows=z$rows,ids=paste(z$ids,collapse=";")),scalars(z,c("mass","meanPrediction","eventRate","gap","absoluteGap","scoreVariance","scoreTargetCovariance","withinBinCorrection"))));point(kind,"reliability","Binary event rate",b-1,z$meanPrediction,z$eventRate,tag=paste0("rows=",z$rows))}
 for(j in seq_along(test)){i<-test[j];point(kind,"test-scores","Training-fitted probability",j-1,j,p[i],"test-row position","probability",tag=d$id[i]);point(kind,"test-scores","Observed Y",j-1,j,d$y[i],"test-row position","binary target",tag=d$id[i])}
 scenarioNames<-c("equal","miss-five","alarm-five");costs<-list(c(1,1),c(1,5),c(5,1))
 for(s in 1:3){name<-scenarioNames[s];cost<-costs[[s]];grid<-c(list("always-negative"),as.list(sort(unique(p[validation]),decreasing=TRUE)));candidates<-lapply(grid,function(t)measure(d,p,validation,t,cost));values<-vapply(candidates,function(m)m$meanCost,numeric(1));best<-which(values<=min(values)+1e-12)[1];chosen<-grid[[best]];ev<-measure(d,p,test,chosen,cost)
  for(j in seq_along(grid)){t<-grid[[j]];m<-candidates[[j]];cell<-setNames(lapply(c("TP","FP","FN","TN"),function(k)fmt(m[[k]])),paste0(c("TP","FP","FN","TN"),"Exact"));add("validation-candidates",c(tagrow(kind,scenario=name,candidate=j-1,selected=as.integer(j==best),policy=if(is.character(t))t else"threshold",thresholdExact="",thresholdApprox=if(is.character(t))""else fmt(t),feasible=1,reasons=""),cell,scalars(m,c(counts,"TPR","FPR","precision","meanCost","totalCost"))));point(kind,"validation-cost",name,j-1,j-1,m$meanCost,"candidate index","hypothetical cost units/mass","validation",if(is.character(t))t else fmt(t))}
  m<-c(ev,cv[c("ROC_AUC","averagePrecision","PRTrapezoidWithInitialPrecisionOne")],cal[c("ECE","reliability","resolution","uncertainty","withinBinCorrection","BrierIdentityResidual")])
  for(k in c("TP","FP","FN","TN",counts,rates,"ROC_AUC","averagePrecision","PRTrapezoidWithInitialPrecisionOne","ECE","reliability","resolution","uncertainty","withinBinCorrection","BrierIdentityResidual")){
   unit<-if(k%in%c("TP","FP","FN","TN",counts))"rows"else if(k=="totalCost")"hypothetical cost units"else if(k=="meanCost")"hypothetical cost units/mass"else if(k=="BrierSum")"sum squared-probability loss"else"dimensionless"
   add("test-metrics",tagrow(kind,scenario=name,metric=k,valueExact="",valueApprox=fmt(m[[k]]),unit=unit))
  }
  lev<-unique(d$group[test][!is.na(d$group[test])]);sets<-c(list(test),lapply(lev,function(g)test[!is.na(d$group[test])&d$group[test]==g]),list(test[is.na(d$group[test])]))
  types<-c("overall",rep("known",length(lev)),"unknown");tokens<-c("all",lev,"")
  for(j in seq_along(sets)){ids<-sets[[j]];m<-measure(d,p,ids,chosen,cost);cell<-setNames(lapply(c("TP","FP","FN","TN"),function(k)fmt(m[[k]])),paste0(c("TP","FP","FN","TN"),"Exact"));add("group-metrics",c(tagrow(kind,scenario=name,groupType=types[j],groupToken=tokens[j],retainedRows=length(ids)),cell,scalars(m,c(counts,rates))));if(types[j]=="known")point(kind,"group-TPR",name,j-2,j-2,m$TPR,"declared group position","TPR",tag=tokens[j])}
 }
 invisible(NULL)
}
allData<-loadData();for(kind in names(allData))study(kind,allData[[kind]])
manifest<-list()
for(name in names(tables)){rows<-tables[[name]];heads<-names(rows[[1]]);stopifnot(all(vapply(rows,function(r)identical(names(r),heads),logical(1))));d<-as.data.frame(do.call(rbind,lapply(rows,function(r)unlist(r,use.names=FALSE))),stringsAsFactors=FALSE);names(d)<-heads;p<-file.path(outDir,paste0("computed-",name,".csv"));write.csv(d,p,row.names=FALSE,na="",fileEncoding="UTF-8");manifest[[name]]<-data.frame(file=basename(p),rows=nrow(d),columns=ncol(d),bodyFields=nrow(d)*ncol(d))}
write.csv(do.call(rbind,manifest),file.path(outDir,"manifest.csv"),row.names=FALSE)
writeLines(c("Binary64 base-R counterpart. Exact columns for general rational results deliberately blank.","Factual native columns only; targets, groups, SHA roles and training cell scores reconstructed.","Earliest candidate within1e-12 of numerical validation minimum; not universal exact selection.","Costs hypothetical; group audits descriptive, not intervention/fairness certificates."),file.path(outDir,"arithmetic-scope.txt"))
cat("PASS ML14 standalone base-R; tables",length(tables),"; eligible",sum(allData$country$eligible),sum(allData$person$eligible),sum(allData$company$eligible),"\n")
