#!/usr/bin/env Rscript
# ML11 actual-source companion, base R only, binary64 approximation.
# Unit observations; complete cases; range geometry fitted on training rows.
# Unlike the web/Python exact rational calculation, comparisons within 1e-12
# are treated as numerical ties. This tolerance is a documented approximation.
# It is not a probability sample, a causal study, or a global Kmeans solver.
args <- commandArgs(trailingOnly=TRUE)
source_dir <- if(length(args)>=1) args[1] else "../ml11-sources"
output_dir <- if(length(args)>=2) args[2] else "ml11-R-results"
dir.create(output_dir,recursive=TRUE,showWarnings=FALSE)
tol <- 1e-12
num <- function(x) { y<-suppressWarnings(as.numeric(x)); if(any(is.na(y)&nzchar(x)&x!="."))stop("malformed numeric token");y }
frac <- function(x) { vapply(x,function(z){if(is.na(z)||z==""||z==".")return(NA_real_);v<-strsplit(z,"/",fixed=TRUE)[[1]];if(length(v)==1)return(num(v));if(length(v)!=2||num(v[2])==0)stop("fraction");num(v[1])/num(v[2])},numeric(1)) }
rd <- function(name) read.csv(file.path(source_dir,name),check.names=FALSE,colClasses="character",stringsAsFactors=FALSE,na.strings=NULL)
fmt <- function(x) { if(length(x)!=1)stop("scalar required");if(is.null(x)||is.na(x))return("");if(is.logical(x))return(if(x)"True"else"False");if(is.character(x))return(x);format(x,digits=17,scientific=FALSE,trim=TRUE) }
jnums <- function(x) paste0("[",paste(vapply(x,fmt,character(1)),collapse=","),"]")
jstrings <- function(x) paste0("[",paste(paste0('"',x,'"'),collapse=","),"]")
jcenters <- function(X) paste0("[",paste(vapply(seq_len(nrow(X)),function(i)jstrings(vapply(X[i,],fmt,character(1))),character(1)),collapse=","),"]")
wb<-rd("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));countryX<-t(vapply(iso,function(k)vapply(codes,function(c){r<-wb[wb$countryISO3==k&wb$indicatorID==c,,drop=FALSE];stopifnot(nrow(r)==1,r$date=="2024");frac(r$originalValueToken)},numeric(1)),numeric(4)))
nl<-rd("actual3613-NLS-original52-fields-and-clustering-selection.csv");nlsX<-cbind(frac(nl$ed76),frac(nl$age76),frac(nl$wage76)/100);ch<-rd("actual3150-churn-original14-fields-and-clustering-selection.csv");chX<-sapply(c("Call  Failure","Subscription  Length","Charge  Amount","Seconds of Use"),function(k)frac(ch[[k]]))
mk <- function(ids,X,sourceRows,native,annotation,all_train=FALSE) {complete<-rowSums(is.na(X))==0;role<-ifelse(!complete,"excluded",ifelse(!all_train&as.integer(seq_along(ids))%%5==0,"outer-test","train"));tr<-which(role=="train");N<-length(tr);m<-min(120,N);audit<-tr[floor((0:(m-1))*(N-1)/(m-1))+1];starts<-list(c(0,floor(N/2),N-1),c(floor(N/4),floor(N/2),floor(3*N/4)),c(floor(N/5),floor(2*N/5),floor(4*N/5)));list(ids=ids,X=X,sourceRows=sourceRows,native=native,annotation=annotation,role=role,tr=tr,outer=which(role=="outer-test"),audit=audit,starts=lapply(starts,function(v)match(tr[v+1],tr))) }
models<-list(country=mk(paste0(iso,":2024"),countryX,paste0(iso,":2024"),iso,rep("",length(iso)),TRUE),person=mk(paste0("person:",nl$sourceRow),nlsX,nl$sourceRow,nl$id,rep("",nrow(nl))),company=mk(paste0("customer:",ch$sourceRow),chX,ch$sourceRow,rep("",nrow(ch)),ch$Churn))
stopifnot(all(models$person$role==nl$role),all(models$company$role==ch$role))
dmatrix <- function(X,Y,scale) { n<-nrow(X);k<-nrow(Y);if(!n||!k)return(matrix(numeric(0),n,k));Z<-matrix(0,n,k);for(j in seq_len(ncol(X))) Z<-Z+outer(X[,j],Y[,j],"-")^2/scale[j]^2;Z }
assign_to <- function(X,C,scale) {D<-dmatrix(X,C,scale);if(!nrow(X))return(list(labels=integer(0),loss=numeric(0),ties=list()));ties<-lapply(seq_len(nrow(X)),function(i)which(D[i,]<=min(D[i,])+tol)-1L);labels<-vapply(ties,function(v)v[1],integer(1));list(labels=labels,loss=D[cbind(seq_len(nrow(X)),labels+1L)],ties=ties) }
km <- function(X,Q,start,scale) {C<-X[start,,drop=FALSE];a<-assign_to(X,C,scale);loss<-sum(a$loss);trace<-list(list(iteration=0,SSE=loss,lossBefore=NA,lossAfterCenterUpdate=NA,centerShiftTerm=NA,identityResidual=NA,changedRows=NA,emptyClusters=integer(0),centers=C));converged<-FALSE
 for(it in 1:20){new<-C;empty<-integer(0);for(k in seq_len(nrow(C))){idx<-which(a$labels==k-1L);if(length(idx))new[k,]<-colMeans(X[idx,,drop=FALSE])else empty<-c(empty,k-1L)};updated<-sum(vapply(seq_len(nrow(X)),function(i)sum(((X[i,]-new[a$labels[i]+1L,])/scale)^2),numeric(1)));shift<-sum(vapply(seq_len(nrow(C)),function(k)sum(a$labels==k-1L)*sum(((C[k,]-new[k,])/scale)^2),numeric(1)));b<-assign_to(X,new,scale);nextloss<-sum(b$loss);changed<-sum(a$labels!=b$labels);trace[[length(trace)+1L]]<-list(iteration=it,SSE=nextloss,lossBefore=loss,lossAfterCenterUpdate=updated,centerShiftTerm=shift,identityResidual=loss-updated-shift,changedRows=changed,emptyClusters=empty,centers=new);a<-b;loss<-nextloss;C<-new;if(!changed){converged<-TRUE;break}}
 list(centers=C,counts=tabulate(a$labels+1L,nbins=nrow(C)),assignment=a,queries=assign_to(Q,C,scale),trace=trace,SSE=loss,mean=loss/nrow(X),outerMean=if(nrow(Q))mean(assign_to(Q,C,scale)$loss)else NA_real_,iterations=length(trace)-1L,converged=converged) }
hier <- function(D,cutK=3L) {n<-nrow(D);groups<-lapply(seq_len(n),function(i)i-1L);nodes<-0:(n-1L);sz<-rep(1,n);G<-matrix(NA_real_,2*n-1L,2*n-1L);G[seq_len(n),seq_len(n)]<-D;merges<-list();partition<-NULL
 cut<-function(){out<-integer(n);for(i in seq_along(groups))out[groups[[i]]+1L]<-i-1L;out}
 if(length(groups)==cutK)partition<-cut()
 while(length(groups)>1L){o<-order(vapply(groups,min,integer(1)));groups<-groups[o];nodes<-nodes[o];sz<-sz[o];best<-Inf;bi<-bj<-NA_integer_;for(i in seq_len(length(groups)-1L))for(j in(i+1L):length(groups)){v<-G[nodes[i]+1L,nodes[j]+1L];if(v<best-tol){best<-v;bi<-i;bj<-j}};newnode<-n+length(merges);members<-sort(c(groups[[bi]],groups[[bj]]));merges[[length(merges)+1L]]<-list(node=newnode,left=nodes[bi],right=nodes[bj],height=best,count=length(members),sourceIndices=members);keep<-setdiff(seq_along(groups),c(bi,bj));for(t in keep){v<-(sz[bi]*G[nodes[bi]+1L,nodes[t]+1L]+sz[bj]*G[nodes[bj]+1L,nodes[t]+1L])/(sz[bi]+sz[bj]);G[newnode+1L,nodes[t]+1L]<-G[nodes[t]+1L,newnode+1L]<-v};newsize<-sz[bi]+sz[bj];groups<-c(groups[keep],list(members));nodes<-c(nodes[keep],newnode);sz<-c(sz[keep],newsize);if(length(groups)==cutK){o<-order(vapply(groups,min,integer(1)));groups<-groups[o];nodes<-nodes[o];sz<-sz[o];partition<-cut()}}
 list(merges=merges,partition=partition) }
density <- function(D,ids) {near<-lapply(seq_len(nrow(D)),function(i)which(D[i,]<=1/16+tol));core<-lengths(near)>=5;lab<-rep(-1L,nrow(D));comps<-list();for(s in seq_len(nrow(D)))if(core[s]&&lab[s]<0){v<-length(comps);queue<-s;lab[s]<-v;members<-integer(0);while(length(queue)){i<-queue[1];queue<-queue[-1];members<-c(members,i);for(j in near[[i]])if(core[j]&&lab[j]<0){lab[j]<-v;queue<-c(queue,j)}};comps[[length(comps)+1L]]<-sort(members)};rows<-lapply(seq_len(nrow(D)),function(i){reached<-if(core[i])lab[i]else sort(unique(lab[near[[i]][core[near[[i]]]]]));list(id=ids[i],cluster=if(length(reached))reached[1]else-1L,type=if(core[i])"core"else if(length(reached))"border"else"noise",neighborCount=length(near[[i]]),neighborIDs=ids[near[[i]]],reachableCoreComponents=reached,ambiguousBorder=!core[i]&&length(reached)>1L)});list(rows=rows,clusters=length(comps),coreRows=sum(core),borderRows=sum(vapply(rows,function(r)r$type=="border",logical(1))),noiseRows=sum(vapply(rows,function(r)r$type=="noise",logical(1))),ambiguousBorderRows=sum(vapply(rows,function(r)r$ambiguousBorder,logical(1)))) }
evaluate <- function(D,labels,ids,exclude_noise=FALSE) {idx<-which(!exclude_noise|labels!=-1L);groups<-unique(labels[idx]);valid<-length(groups)>=2&&length(groups)<length(idx);rows<-lapply(idx,function(i){same<-idx[labels[idx]==labels[i]];a<-b<-s<-NA_real_;if(valid){if(length(same)==1){a<-s<-0}else{a<-mean(D[i,setdiff(same,i)]);b<-min(vapply(setdiff(groups,labels[i]),function(g)mean(D[i,idx[labels[idx]==g]]),numeric(1)));s<-if(max(a,b)) (b-a)/max(a,b)else 0}};list(id=ids[i],cluster=labels[i],a=a,b=b,silhouette=s,singleton=length(same)==1L)});list(rows=rows,evaluatedRows=length(idx),silhouette=if(valid)mean(vapply(rows,function(r)r$silhouette,numeric(1)))else NA_real_) }
names_tables<-c("clustering-metrics","training-geometry","kmeans-centers","kmeans-assignments","kmeans-iteration-ledger","hierarchy-merges","density-neighborhoods","audit-silhouettes","audit-pairwise-dissimilarities","source-eligibility-and-annotation");tables<-setNames(lapply(names_tables,function(x)list()),names_tables)
append_row<-function(name,row){tables[[name]][[length(tables[[name]])+1L]]<<-lapply(row,function(x)unname(fmt(x)))}
metric<-function(kind,profile,name,value,unit="dimensionless"){if(name%in%c("trainingRows","outerRows","auditRows","algorithmRows","coreRows","borderRows","noiseRows","ambiguousBorderRows","evaluatedRows")||startsWith(name,"clusterCount-"))unit<-"rows"else if(name=="iterations")unit<-"iterations"else if(name=="merges")unit<-"merges"else if(name%in%c("clusters","occupiedClusters","cutK"))unit<-"clusters"else if(name=="converged")unit<-"indicator (0/1)";append_row("clustering-metrics",list(kind=kind,profile=profile,metric=name,value=value,unit=unit))}
silrows<-function(kind,profile,e){for(r in e$rows)append_row("audit-silhouettes",c(list(kind=kind,profile=profile),r))}
for(kind in names(models)){M<-models[[kind]];X<-M$X[M$tr,,drop=FALSE];Q<-M$X[M$outer,,drop=FALSE];A<-M$X[M$audit,,drop=FALSE];scale<-apply(X,2,function(v)max(v)-min(v));scale[scale==0]<-1;mu<-colMeans(X);var<-colMeans(sweep(X,2,mu,"-")^2);D<-dmatrix(A,A,scale);ids<-M$ids[M$audit]
 for(j in seq_len(ncol(X)))append_row("training-geometry",list(kind=kind,feature=j-1L,trainingRows=nrow(X),mean=mu[j],massVariance=var[j],range=max(X[,j])-min(X[,j]),scaleSquared=scale[j]^2,constant=var[j]==0))
 for(i in seq_len(nrow(M$X)))append_row("source-eligibility-and-annotation",list(kind=kind,id=M$ids[i],sourceRow=M$sourceRows[i],originalID=M$native[i],role=M$role[i],complete=!anyNA(M$X[i,]),audit=i%in%M$audit,x0=M$X[i,1],x1=M$X[i,2],x2=M$X[i,3],x3=if(ncol(M$X)==4)M$X[i,4]else NA_real_,ChurnAnnotation=M$annotation[i]))
 for(i in seq_len(nrow(D)))for(j in seq_len(nrow(D)))append_row("audit-pairwise-dissimilarities",list(kind=kind,id1=ids[i],id2=ids[j],squaredDissimilarity=D[i,j]))
 for(start in 0:2){profile<-paste0("kmeans-start-",start);z<-km(X,Q,M$starts[[start+1L]],scale);labels<-z$assignment$labels[match(M$audit,M$tr)];e<-evaluate(D,labels,ids);vals<-list(trainingRows=nrow(X),outerRows=nrow(Q),trainingSSE=z$SSE,trainingMeanSquaredDissimilarity=z$mean,outerMeanSquaredDissimilarity=z$outerMean,iterations=z$iterations,converged=as.integer(z$converged),occupiedClusters=sum(z$counts>0),auditRows=e$evaluatedRows,auditSilhouette=e$silhouette);for(n in names(vals))metric(kind,profile,n,vals[[n]]);for(k in 0:2){metric(kind,profile,paste0("clusterCount-",k),z$counts[k+1L],"rows");for(j in seq_len(ncol(X)))append_row("kmeans-centers",list(kind=kind,profile=profile,cluster=k,feature=j-1L,value=z$centers[k+1L,j],count=z$counts[k+1L]))};for(role in c("train","outer-test")){idx<-if(role=="train")M$tr else M$outer;r<-if(role=="train")z$assignment else z$queries;for(i in seq_along(idx))append_row("kmeans-assignments",list(kind=kind,profile=profile,role=role,id=M$ids[idx[i]],cluster=r$labels[i],squaredDissimilarity=r$loss[i],tiedCenters=jnums(r$ties[[i]])))};for(r in z$trace)append_row("kmeans-iteration-ledger",list(kind=kind,profile=profile,iteration=r$iteration,SSE=r$SSE,lossBefore=r$lossBefore,lossAfterCenterUpdate=r$lossAfterCenterUpdate,centerShiftTerm=r$centerShiftTerm,identityResidual=r$identityResidual,changedRows=r$changedRows,emptyClusters=jnums(r$emptyClusters),centers=jcenters(r$centers)));silrows(kind,profile,e)}
 profile<-"hierarchy-average";h<-hier(D);e<-evaluate(D,h$partition,ids);for(n in c("algorithmRows","merges","cutK","auditSilhouette")){v<-switch(n,algorithmRows=nrow(D),merges=length(h$merges),cutK=3,auditSilhouette=e$silhouette);metric(kind,profile,n,v)};for(r in h$merges)append_row("hierarchy-merges",list(kind=kind,node=r$node,left=r$left,right=r$right,height=r$height,count=r$count,sourceIndices=jnums(r$sourceIndices)));silrows(kind,profile,e)
 profile<-"density-default";d<-density(D,ids);e<-evaluate(D,vapply(d$rows,function(r)r$cluster,integer(1)),ids,TRUE);vals<-list(algorithmRows=nrow(D),clusters=d$clusters,coreRows=d$coreRows,borderRows=d$borderRows,noiseRows=d$noiseRows,ambiguousBorderRows=d$ambiguousBorderRows,evaluatedRows=e$evaluatedRows,auditSilhouette=e$silhouette);for(n in names(vals))metric(kind,profile,n,vals[[n]]);for(r in d$rows)append_row("density-neighborhoods",list(kind=kind,id=r$id,cluster=r$cluster,type=r$type,neighborCount=r$neighborCount,neighborIDs=jstrings(r$neighborIDs),reachableCoreComponents=jnums(r$reachableCoreComponents),ambiguousBorder=r$ambiguousBorder));silrows(kind,profile,e)
}
for(name in names(tables)){rows<-tables[[name]];df<-as.data.frame(do.call(rbind,lapply(rows,unlist)),stringsAsFactors=FALSE,check.names=FALSE);write.table(df,file.path(output_dir,paste0("computed-",name,".csv")),sep=",",row.names=FALSE,col.names=TRUE,quote=TRUE,qmethod="double",na="",eol="\n",fileEncoding="UTF-8")}
writeLines(c("Arithmetic: base R binary64 approximation; absolute comparison tolerance 1e-12.","Fifteen profiles; three fixed Kmeans starts and audit hierarchy/density per source.","Alltraining range geometry. No random-sampling, causal, fullsource tree or global-optimum claim.",paste(names(tables),vapply(tables,length,integer(1)),sep=":")),file.path(output_dir,"study-manifest.txt"))
cat("Completed fifteen actual-source profiles and ten CSV tables.\n")
