# METR15 standalone base-R numerical reproduction. No JSON/package/engine.
# Rscript metr15-reproduce.R metr15-sources metr15-reproduction-r
# The exact companion is Python/Fraction;QR/base-R uses binary64 arithmetic.
# Retained-vintage conditional diagnostics,not real-time/causal/cointegration tests.
options(stringsAsFactors=FALSE,digits=17)
a<-commandArgs(trailingOnly=TRUE);src<-if(length(a)>=1)a[1]else'metr15-sources';out<-if(length(a)>=2)a[2]else'metr15-reproduction-r';dir.create(out,recursive=TRUE,showWarnings=FALSE)
read<-function(n)read.csv(file.path(src,n),check.names=FALSE,colClasses='character',na.strings=NULL)
rat<-function(x){vapply(x,function(s){if(is.na(s)||s==''||s=='?')return(NA_real_);z<-strsplit(s,'/',fixed=TRUE)[[1]];if(length(z)==1)as.numeric(z)else as.numeric(z[1])/as.numeric(z[2])},0.0,USE.NAMES=FALSE)}
avg<-function(v)if(length(v))mean(v)else NA_real_
emit<-function(n,rows){x<-do.call(rbind,lapply(rows,function(z)as.data.frame(z,stringsAsFactors=FALSE,check.names=FALSE)));write.csv(x,file.path(out,n),row.names=FALSE,na='');nrow(x)}
wb<-read('actual180-KOR-four-indicators-original-1980-2024.csv');years<-as.character(1980:2024)
getwb<-function(id)rat(wb$originalValueToken[match(years,wb$date[wb$indicatorID==id])+(which(wb$indicatorID==id)[1]-1)])
# Source order is not assumed:match a composite key directly.
getwb<-function(id)rat(wb$originalValueToken[match(paste(years,id),paste(wb$date,wb$indicatorID))])
country<-data.frame(index=0:44,timeLabel=years,y=getwb('NY.GDP.MKTP.KD.ZG'),x=getwb('FP.CPI.TOTL.ZG'),GDPperCapita=getwb('NY.GDP.PCAP.KD'),lifeExpectancy=getwb('SP.DYN.LE00.IN'))
mm<-read('actual50400-household-original-nine-fields.csv');hh<-read('derived840-household-complete-hour-power-and-current.csv');py<-rat(mm$Global_active_power);px<-rat(mm$Global_intensity)
complete<-function(v)vapply(0:839,function(i){z<-v[(60*i+1):(60*i+60)];if(anyNA(z))NA_real_ else mean(z)},0.0)
person<-data.frame(index=0:839,timeLabel=hh$localHour,y=complete(py),x=complete(px));stopifnot(isTRUE(all.equal(person$y,rat(hh$completeHourPowerKW),tolerance=1e-12)),isTRUE(all.equal(person$x,rat(hh$completeHourCurrentA),tolerance=1e-12)))
rr<-read('actual2313-retail-SKU85123A-all-eight-fields.csv');dd<-read('derived374-retail-calendar-gross-units-weighted-price.csv');day<-floor(rat(rr$InvoiceDate))-40513;q<-rat(rr$Quantity);price<-rat(rr$UnitPrice)
gross<-vapply(0:373,function(i)sum(q[day==i&q>0]),0.0);amount<-vapply(0:373,function(i)sum(q[day==i&q>0]*price[day==i&q>0]),0.0);weighted<-ifelse(gross>0,amount/gross,NA_real_)
eligible<-dd$sourceWindowEdgeDay=='False'&as.integer(dd$allRetailerRecordedRows)>0&gross>0
company<-data.frame(index=0:373,timeLabel=dd$calendarDate,y=ifelse(eligible,gross,NA_real_),x=ifelse(eligible,weighted,NA_real_));stopifnot(isTRUE(all.equal(company$y,rat(dd$analysisGrossUnits),tolerance=1e-12)),isTRUE(all.equal(company$x,rat(dd$analysisWeightedPriceGBP),tolerance=1e-12)))
models<-list(country=country,person=person,company=company);origins<-list(country=c(30,35,40),person=c(672,696,720),company=c(335,342,349));horizons<-c(country=5,person=24,company=7);lags<-c(country=1,person=24,company=7);specs<-list('AR-only'=integer(0),'lagged-X'=1,'current-and-lagged-X'=0:1);modes<-c('last-calendar-X-scenario','retrospective-actual-X')
cal<-coefs<-lineage<-paths<-scalerows<-scores<-cross<-list();studies<-list()
score<-function(rows,name,scales){v<-rows$predictions[[name]];keep<-!is.na(rows$actual)&!is.na(v);e<-rows$actual[keep]-v[keep];o<-rows$origin[keep];aa<-bb<-numeric(0)
 for(i in seq_along(e)){s<-scales[[as.character(o[i])]];if(!is.na(s[1])&&s[1]!=0)aa<-c(aa,abs(e[i])/s[1]);if(!is.na(s[2])&&s[2]!=0)bb<-c(bb,e[i]^2/s[2])}
 z<-list(observedForecastPairs=length(e),zeroActualPairs=sum(rows$actual[keep]==0),meanError=avg(e),MAE=avg(abs(e)),MSE=avg(e^2),scaledAbsolutePairs=length(aa),scaledSquaredPairs=length(bb),MASE=avg(aa),meanSquaredScaledError=avg(bb),undefinedScalePairs=length(e)-length(aa));r<-list();for(k in names(z)){r[[k]]<-z[[k]];r[[paste0(k,'Approx')]]<-z[[k]]};r}
for(kind in names(models)){
 s<-models[[kind]]
 for(i in seq_len(nrow(s)))cal[[length(cal)+1]]<-list(kind=kind,index=s$index[i],timeLabel=s$timeLabel[i],Y=s$y[i],X=s$x[i],YApprox=s$y[i],XApprox=s$x[i])
 for(mode in modes){records<-list(origin=integer(0),horizon=integer(0),targetIndex=integer(0),actual=numeric(0),predictions=setNames(lapply(specs,function(z)numeric(0)),names(specs)));scales<-list()
  for(origin in origins[[kind]]){
   train<-s[s$index<origin,];lag<-lags[kind];delta<-train$y[(lag+1):nrow(train)]-train$y[1:(nrow(train)-lag)];delta<-delta[!is.na(delta)];scale<-c(avg(abs(delta)),avg(delta^2));scales[[as.character(origin)]]<-scale
   scalerows[[length(scalerows)+1]]<-list(kind=kind,mode=mode,origin=origin,lag=unname(lag),trainingCalendarRows=nrow(train),observedPairCount=length(delta),absoluteScale=scale[1],squaredScale=scale[2],absoluteScaleApprox=scale[1],squaredScaleApprox=scale[2])
   horizon<-horizons[kind];future<-if(mode==modes[1])rep(tail(train$x,1),horizon)else s$x[origin+seq_len(horizon)];preds<-list()
   for(name in names(specs)){
    xl<-specs[[name]];n<-nrow(train);Ylag<-c(NA_real_,head(train$y,-1));X<-cbind(intercept=1,Ylag1=Ylag)
    for(l in xl)X<-cbind(X,setNames(data.frame(if(l==0)train$x else c(NA_real_,head(train$x,-1))),paste0('Xlag',l)))
    X<-as.matrix(X);use<-complete.cases(cbind(train$y,X));XX<-X[use,,drop=FALSE];y<-train$y[use];qrfit<-qr(XX,tol=1e-12,LAPACK=FALSE);stopifnot(qrfit$rank==ncol(XX));b<-qr.coef(qrfit,y);fit<-drop(XX%*%b);res<-y-fit;rss<-sum(res^2);df<-length(y)-qrfit$rank
    for(j in seq_along(b))coefs[[length(coefs)+1]]<-list(kind=kind,mode=mode,origin=origin,model=name,feature=colnames(XX)[j],coefficient=b[j],coefficientApprox=b[j],rank=qrfit$rank,parameters=ncol(XX),fitRows=length(y),RSS=rss,RSSApprox=rss,residualDF=df)
    for(j in seq_along(y))lineage[[length(lineage)+1]]<-list(kind=kind,mode=mode,origin=origin,model=name,index=train$index[use][j],transformedObserved=y[j],fitted=fit[j],residual=res[j],fittedApprox=fit[j],residualApprox=res[j])
    ystate<-train$y;xstate<-c(train$x,future);pp<-rep(NA_real_,horizon)
    for(h in seq_len(horizon)){t<-origin+h-1;f<-c(1,ystate[t]);for(l in xl)f<-c(f,xstate[t-l+1]);z<-0
     for(j in seq_along(b))if(b[j]!=0){if(is.na(f[j])){z<-NA_real_;break}else z<-z+b[j]*f[j]}
     pp[h]<-z;ystate<-c(ystate,z);actual<-s$y[t+1]
     paths[[length(paths)+1]]<-list(kind=kind,mode=mode,origin=origin,model=name,horizon=h,index=t,timeLabel=s$timeLabel[t+1],futureX=future[h],prediction=z,actual=actual,predictionApprox=z,actualApprox=actual,unresolvedSymbols='')
    };preds[[name]]<-pp
   }
   records$origin<-c(records$origin,rep(origin,horizon));records$horizon<-c(records$horizon,seq_len(horizon));records$targetIndex<-c(records$targetIndex,origin+seq_len(horizon)-1);records$actual<-c(records$actual,s$y[origin+seq_len(horizon)])
   for(name in names(specs))records$predictions[[name]]<-c(records$predictions[[name]],preds[[name]])
  }
  matched<-!is.na(records$actual)&Reduce(`&`,lapply(records$predictions,function(v)!is.na(v)))
  subsetRecords<-function(r,keep){r$origin<-r$origin[keep];r$horizon<-r$horizon[keep];r$targetIndex<-r$targetIndex[keep];r$actual<-r$actual[keep];r$predictions<-lapply(r$predictions,function(v)v[keep]);r}
  for(frame in c('available','matched'))for(name in names(specs))scores[[length(scores)+1]]<-c(list(kind=kind,mode=mode,frame=frame,model=name),score(if(frame=='available')records else subsetRecords(records,matched),name,scales))
  studies[[paste(kind,mode,sep='|')]]<-list(records=records,matched=matched,scales=scales)
 }
 st1<-studies[[paste(kind,modes[1],sep='|')]];st2<-studies[[paste(kind,modes[2],sep='|')]];keys<-function(st)paste(st$records$origin,st$records$horizon,sep=':');common<-intersect(keys(st1)[st1$matched],keys(st2)[st2$matched])
 for(mode in modes){st<-studies[[paste(kind,mode,sep='|')]];for(name in names(specs))cross[[length(cross)+1]]<-c(list(kind=kind,mode=mode,model=name,commonKeys=length(common)),score(subsetRecords(st$records,keys(st)%in%common),name,st$scales))}
}
level<-list();levfit<-lm.fit(cbind(1,country$GDPperCapita),country$lifeExpectancy)
for(i in seq_len(nrow(country)))level[[i]]<-list(index=i-1,year=country$timeLabel[i],GDPPerCapita=country$GDPperCapita[i],lifeExpectancy=country$lifeExpectancy[i],GDPPerCapitaApprox=country$GDPperCapita[i],lifeExpectancyApprox=country$lifeExpectancy[i],fitted=levfit$fitted.values[i],fittedApprox=levfit$fitted.values[i],residual=levfit$residuals[i],residualApprox=levfit$residuals[i])
tables<-list('model-calendar.csv'=cal,'fit-coefficients.csv'=coefs,'fit-row-lineage.csv'=lineage,'forecast-paths.csv'=paths,'evaluation-scores.csv'=scores,'training-scales.csv'=scalerows,'cross-mode-matched-scores.csv'=cross,'level-diagnostic.csv'=level)
sizes<-sapply(names(tables),function(n)emit(n,tables[[n]]));write.table(data.frame(file=names(sizes),rows=sizes),file.path(out,'row-counts.csv'),sep=',',row.names=FALSE);cat('Base-R QR reproduction complete\n');print(sizes)
