# AI15 standalone native-data reproduction; base R only. # Reused verbatim: prior ML15 public short-ASCII SHA256 infrastructure only. # New pair transformations, likelihood comparison and score kernel follow. # Usage: Rscript ai15-reproduce.R --source DIRECTORY --out DIRECTORY args<-commandArgs(trailingOnly=TRUE);fa<-grep('^--file=',commandArgs(),value=TRUE) here<-if(length(fa))dirname(normalizePath(sub('^--file=','',fa[1]),mustWork=TRUE))else getwd() option<-function(k,d){i<-match(k,args);if(is.na(i))d else args[i+1]} src<-option('--source',file.path(here,'ai15-sources'));out<-option('--out',file.path(getwd(),'ai15-R-results'));dir.create(out,recursive=TRUE,showWarnings=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"))) # AI15 native-only study kernel. Exact family ranking uses integer prime powers. # Floating scores/derivatives are approximations, not a general exact API. read0<-function(n)read.csv(file.path(src,n),colClasses='character',check.names=FALSE,na.strings=character(),stringsAsFactors=FALSE,encoding='UTF-8') fmt<-function(x)ifelse(is.na(x),'',sprintf('%.17g',x)) role0<-function(i)ifelse(i%%4==0,'test',ifelse(i%%4==1,'validation','train')) lab<-function(a,b)if(a>b)'1' else if(a=0),as.integer(x[2]<=3));cp[[length(cp)+1L]]<-pair0('country',paste0('country:',a,':',b),a,b,f(va),f(vb),lab(va[1]-va[2],vb[1]-vb[2]),'paired-native-countries','pending',paste0('[',rowsJSON(ar$sourceRow[1],ar$sourceRow[2]),',',rowsJSON(br$sourceRow[1],br$sourceRow[2]),']'),CS)} ord<-order(sha256(paste0('AI15-country-role|',vapply(cp,`[[`,'','id'))));for(rank in 0:7)cp[[ord[rank+1]]]$role<-role0(rank);pairs<-c(pairs,cp) ch<-read0('actual3150-churn-original14-fields.csv');stopifnot(nrow(ch)==3150,ncol(ch)==15,identical(as.integer(ch$sourceRow[ch[['Charge Amount']]=='10']),c(474L,2174L,2274L,2374L,2674L,2924L,2974L))) ord<-order(sha256(paste0('AI15-company-rows|',seq_len(nrow(ch)))),seq_len(nrow(ch)))[1:96] for(j in seq(1,95,2)){a<-ch[ord[j],,drop=FALSE];b<-ch[ord[j+1],,drop=FALSE];f<-function(r)c(as.integer(as.numeric(r$Complains)==0),as.integer(as.numeric(r[['Call Failure']])<=5));pairs[[length(pairs)+1L]]<-pair0('company',paste0('customers:',a$sourceRow,':',b$sourceRow),paste0('customer-row:',a$sourceRow),paste0('customer-row:',b$sourceRow),f(a),f(b),lab(1-as.numeric(a$Churn),1-as.numeric(b$Churn)),'anonymous-native-records',role0((j-1)/2),rowsJSON(a$sourceRow,b$sourceRow),BS)} stopifnot(length(pairs)==176,length(selected)==240) # Prime exponents are exact integer-valued doubles for these fixed tiny powers. # Compare likelihood ratios using base10000 integer limbs; no epsilon/log tie rule. mulSmall<-function(a,k){v<-a*k;carry<-0;for(j in seq_along(v)){z<-v[j]+carry;v[j]<-z%%10000;carry<-floor(z/10000)};while(carry>0){v<-c(v,carry%%10000);carry<-floor(carry/10000)};v} prodPrime<-function(e){a<-1;for(j in 1:3)if(e[j]>0)for(k in seq_len(e[j]))a<-mulSmall(a,c(2,3,5)[j]);a} compareLike<-function(a,b){d<-a-b;n<-prodPrime(pmax(d,0));q<-prodPrime(pmax(-d,0));if(length(n)!=length(q))return(sign(length(n)-length(q)));different<-which(n!=q);if(!length(different))0 else sign(n[max(different)]-q[max(different)])} bestLike<-function(ex){best<-1L;if(length(ex)>1)for(j in 2:length(ex))if(compareLike(ex[[j]],ex[[best]])>0)best<-j;best} plusFactors<-list(c(0,0,-1),c(0,-1,0),c(-1,0,0),c(1,-1,0),c(2,0,-1)) minusFactors<-rev(plusFactors) delta<-function(r)c(as.numeric(r$leftFeature0)-as.numeric(r$rightFeature0),as.numeric(r$leftFeature1)-as.numeric(r$rightFeature1)) py<-function(r)if(r$target=='1/2')0.5 else as.numeric(r$target) exponent<-function(r,t)sum(delta(r)*t) prob<-function(r,t){z<-2^exponent(r,t);z/(1+z)} exactP<-function(r,t)c('1/5','1/3','1/2','2/3','4/5')[exponent(r,t)+3] like<-function(rr,t){D<-if(any(vapply(rr,function(r)r$target=='1/2',FALSE)))2L else 1L;e<-c(0,0,0);for(r in rr){h<-exponent(r,t)+3;y<-py(r);e<-e+D*y*plusFactors[[h]]+D*(1-y)*minusFactors[[h]]};list(e=e,D=D,value=prod(c(2,3,5)^e))} score<-function(rr,t){n<-length(rr);if(!n)return(list(count=0,totalWeight=0,sumSquaredError=0,meanSquaredError=NA_real_,agreement=NA_real_,meanLogLoss=NA_real_));p<-vapply(rr,function(r)prob(r,t),0);y<-vapply(rr,py,0);sq<-(p-y)^2;agree<-ifelse(p==0.5,0.5,ifelse(p>0.5,y,1-y));list(count=n,totalWeight=n,sumSquaredError=sum(sq),meanSquaredError=mean(sq),agreement=mean(agree),meanLogLoss=mean(-y*log(p)-(1-y)*log1p(-p)))} derivative<-function(rr,t){g<-c(0,0);H<-matrix(0,2,2);for(r in rr){p<-prob(r,t);d<-delta(r);g<-g+(p-py(r))*d;H<-H+p*(1-p)*outer(d,d)};list(g=g,H=H)} grids<-list(feature0=list(c(-1,0),c(0,0),c(1,0)),feature1=list(c(0,-1),c(0,0),c(0,1)),both=lapply(-1:1,function(a)lapply(-1:1,function(b)c(a,b)))) grids$both<-do.call(c,grids$both) candidates<-list();scores<-list();derivatives<-list();predictions<-list();selections<-list();metrics<-list();full<-list() metric<-function(kind,profile,role,name,value){metrics[[length(metrics)+1L]]<<-list(case=kind,profile=profile,role=role,name=name,exact='',value=fmt(value),defined=if(is.na(value))'false' else 'true')} for(kind in c('country','person','company')){ rr<-Filter(function(r)r$kind==kind,pairs);tr<-Filter(function(r)r$role=='train',rr);va<-Filter(function(r)r$role=='validation',rr);winners<-list() for(family in names(grids)){ fits<-list() for(index in seq_along(grids[[family]])){ t<-grids[[family]][[index]];profile<-paste0(family,':',index-1);li<-like(tr,t);vl<-like(va,t);d<-derivative(tr,t) candidates[[length(candidates)+1L]]<-list(case=kind,profile=profile,family=family,index=as.character(index-1),theta0=as.character(t[1]),theta1=as.character(t[2]),poweredTrainingLikelihood=fmt(li$value),trainingPower=as.character(li$D),trainingPrime2=as.character(li$e[1]),trainingPrime3=as.character(li$e[2]),trainingPrime5=as.character(li$e[3]),poweredValidationLikelihood=fmt(vl$value),validationPower=as.character(vl$D),validationPrime2=as.character(vl$e[1]),validationPrime3=as.character(vl$e[2]),validationPrime5=as.character(vl$e[3])) metric(kind,profile,'train','poweredLikelihood',li$value);metric(kind,profile,'validation','poweredLikelihood',vl$value) for(role in c('train','validation','test')){s<-score(Filter(function(r)r$role==role,rr),t);scores[[length(scores)+1L]]<-c(list(case=kind,profile=profile,role=role),lapply(s,fmt));for(name in names(s))metric(kind,profile,role,name,s[[name]])} for(j in 1:2){derivatives[[length(derivatives)+1L]]<-list(case=kind,profile=profile,coordinate=paste0('a',j-1),type='gradient',value=fmt(d$g[j]));for(k in 1:2)derivatives[[length(derivatives)+1L]]<-list(case=kind,profile=profile,coordinate=paste0('a',j-1,',a',k-1),type='Hessian',value=fmt(d$H[j,k]))} for(r in rr){p<-prob(r,t);y<-py(r);predictions[[length(predictions)+1L]]<-list(case=kind,profile=profile,id=r$id,role=r$role,target=r$target,probability=exactP(r,t),squaredError=fmt((p-y)^2),agreement=fmt(if(p==0.5)0.5 else if(p>0.5)y else 1-y),nativeRows=r$nativeRows)} fits[[length(fits)+1L]]<-list(profile=profile,theta=t,li=li,vl=vl) } wi0<-bestLike(lapply(fits,function(x)x$li$e));winners[[length(winners)+1L]]<-fits[[wi0]] } chosen0<-bestLike(lapply(winners,function(x)x$vl$e));fit<-winners[[chosen0]] for(j in 1:3){w<-winners[[j]];selections[[length(selections)+1L]]<-list(case=kind,family=names(grids)[j],trainingWinnerProfile=w$profile,theta0=as.character(w$theta[1]),theta1=as.character(w$theta[2]),selected=if(j==chosen0)'true' else 'false',validationLikelihood=fmt(w$vl$value))} for(j in 1:2)metric(kind,'selected','selection',paste0('theta',j-1),fit$theta[j]);metric(kind,'selected','selection','selectedFamilyIndex',chosen0-1) full[[length(full)+1L]]<-list(case=kind,selectedFamily=names(grids)[chosen0],selectedProfile=fit$profile,theta=as.list(fit$theta),scope='Integer prime-exponent likelihood ranking exact for fixed factual grid; scores/derivatives/logs binary64 approximations,not general exact API') } write0<-function(name,rows){quoteCSV<-function(x)paste0('"',gsub('"','""',enc2utf8(as.character(x)),fixed=TRUE),'"');lines<-c(paste(quoteCSV(names(rows[[1]])),collapse=','),vapply(rows,function(r)paste(quoteCSV(unlist(r)),collapse=','),''));writeBin(charToRaw(enc2utf8(paste0(paste(lines,collapse='\n'),'\n'))),file.path(out,name))} outputs<-list('computed-selected-rating-observations.csv'=selected,'computed-pairs.csv'=pairs,'computed-candidates.csv'=candidates,'computed-role-scores.csv'=scores,'computed-derivatives.csv'=derivatives,'computed-all-candidate-predictions.csv'=predictions,'computed-selected-families.csv'=selections,'computed-metrics.csv'=metrics) for(n in names(outputs))write0(n,outputs[[n]]) escapeJSON<-function(x){x<-gsub('\\','\\\\',x,fixed=TRUE);x<-gsub('"','\\"',x,fixed=TRUE);x<-gsub('\n','\\n',x,fixed=TRUE);paste0('"',x,'"')} encode<-function(x){if(is.null(x))return('null');if(is.list(x)){n<-names(x);if(is.null(n))return(paste0('[',paste(vapply(x,encode,''),collapse=','),']'));return(paste0('{',paste(paste0(escapeJSON(n),':',vapply(x,encode,'')),collapse=','),'}'))};if(length(x)!=1)return(encode(as.list(x)));if(is.character(x))return(escapeJSON(x));if(is.logical(x))return(if(x)'true' else 'false');fmt(x)} writeLines(encode(list(arithmetic='Exact fixed-grid prime-exponent likelihood order; original tokens retained; other numeric scores/derivatives/logs binary64',cases=full)),file.path(out,'full-results.json'),useBytes=TRUE) writeLines(encode(list(scope='Native-only base R counterpart; no prepared models/results; original MovieLens conditions apply',pairs=length(pairs),rows=lapply(outputs,length))),file.path(out,'manifest.json'),useBytes=TRUE) cat('PASS AI15 native-only base R: ',length(pairs),' pairs,',length(predictions),' candidate predictions,',length(metrics),' metrics\n',sep='')