# Standalone base R4.5 reference for selected public E17 CSVs; binary64 numeric scope.
options(digits=17,warn=1)
Sys.setenv(TZ='UTC')
if(.Platform$OS.type=='windows')stopifnot(nzchar(Sys.setlocale('LC_CTYPE','English_United States.utf8')))
args <- grep('^--file=',commandArgs(FALSE),value=TRUE);stopifnot(length(args)==1)
BASE <- dirname(normalizePath(sub('^--file=','',args)));setwd(BASE)
read <- function(n)read.csv(file.path('econ17-sources',n),fileEncoding='UTF-8-BOM',colClasses='character',na.strings=NULL,check.names=FALSE)
Q <- function(x)vapply(x,function(s){v<-strsplit(gsub(',','',s),'/',fixed=TRUE)[[1]];if(length(v)==2)as.numeric(v[1])/as.numeric(v[2]) else as.numeric(v[1])},numeric(1))
M<-list();put<-function(k,x){stopifnot(length(x)==1,is.finite(x));M[[k]]<<-x}
levels<-read('actual-BEA-fixed-vintage-GDP-levels-and-derived-implicit-deflator.csv');quarters<-list()
for(i in seq_len(nrow(levels))){r<-levels[i,];N<-Q(r$sourceNominalToken);Y<-Q(r$sourceRealToken);P<-100*N/Y;for(k in c('nominal','real','derivedDeflator'))put(paste('country',r$period,k,sep='.'),switch(k,nominal=N,real=Y,derivedDeflator=P));if(r$period!='annual2024')quarters[[r$period]]<-c(N,Y,P)}
keys<-sort(names(quarters))
for(i in 2:length(keys)){a<-quarters[[keys[i-1]]];b<-quarters[[keys[i]]];put(paste0('country.',keys[i],'.ordinaryRealGrowth'),b[2]/a[2]-1);put(paste0('country.',keys[i],'.ordinaryDerivedDeflatorGrowth'),b[3]/a[3]-1);put(paste0('country.',keys[i],'.annualizedRealFromRoundedLevels'),(b[2]/a[2])^4-1);put(paste0('country.',keys[i],'.annualizedDerivedDeflatorFromRoundedLevels'),(b[3]/a[3])^4-1)}
rates<-read('actual-BEA-published-price-and-deflator-annualized-rates.csv')
for(i in seq_len(nrow(rates))){r<-rates[i,];put(paste0('country.',r$period,'.publishedPriceAnnualizedPercent'),Q(r$publishedGDPPriceIndexAnnualizedPercent));put(paste0('country.',r$period,'.publishedDeflatorAnnualizedPercent'),Q(r$publishedImplicitDeflatorAnnualizedPercent))}
people<-read('actual9876-ACS-income-and-published-adjustment-factor.csv');avail<-people[people$PINCP!='',];income<-Q(avail$PINCP);w<-Q(avail$PWGTP);factor<-Q(avail$ADJINC)/1e6
put('person.sourceRows',nrow(people));put('person.available',nrow(avail));put('person.unavailable',nrow(people)-nrow(avail));put('person.availablePersonWeight',sum(w));put('person.weightedRawMean',sum(w*income)/sum(w));put('person.weightedAdjustedMean',sum(w*income*factor)/sum(w));put('person.negative',sum(income<0));put('person.zero',sum(income==0));put('person.positive',sum(income>0))
display<-read('actual-four-ACS-positions-raw-and-derived-constant-dollar-income.csv')
for(i in seq_len(nrow(display))){r<-display[i,];stem<-paste0('person.row',r$source_row_id);put(paste0(stem,'.nominal'),Q(r$PINCP));put(paste0(stem,'.factor'),Q(r$ADJINC)/1e6);put(paste0(stem,'.adjusted'),Q(r$PINCP)*Q(r$ADJINC)/1e6);put(paste0(stem,'.weight'),Q(r$PWGTP))}
sku<-read('actual2313-retail-SKU85123A-original-XML-tokens-and-inclusion-flags.csv');periods<-read('derived13-retail-SKU-month-quantity-per-covered-day-and-weighted-price.csv');quant<-Q(sku$Quantity);price<-Q(sku$UnitPriceXMLToken);cancel<-startsWith(tolower(sku$InvoiceNo),'c');good<-quant>0&price>0&!cancel;put('company.skuRows',nrow(sku));put('company.months',nrow(periods));put('company.cancellationRows',sum(cancel));monthValues<-list()
for(i in seq_len(nrow(periods))){r<-periods[i,];ids<-sku$month==r$month;sel<-ids&good;qty<-sum(quant[sel]);amount<-sum(quant[sel]*price[sel]);days<-Q(r$coveredCalendarDays);wp<-amount/qty;rate<-qty/days;v<-list(sourceRows=sum(ids),positiveRows=sum(sel),quantity=qty,amount=amount,days=days,weightedPrice=wp,quantityPerDay=rate,partial=as.numeric(r$partialCalendarMonth=='True'));for(k in names(v))put(paste('company',r$month,k,sep='.'),v[[k]]);monthValues[[r$month]]<-c(rate,wp)}
a<-monthValues[['2011-01']];b<-monthValues[['2011-02']];put('company.JanFeb.quantityPerDayGrowth',b[1]/a[1]-1);put('company.JanFeb.weightedPriceGrowth',b[2]/a[2]-1)
assumed<-read('assumed-normalized-ADAS-scenarios-not-estimated.csv')
for(i in seq_len(nrow(assumed))){r<-assumed[i,];P<-(Q(r$a)-Q(r$c)+Q(r$d)*Q(r$Pe))/(Q(r$b)+Q(r$d));Y<-Q(r$a)-Q(r$b)*P;put(paste0('assumed.',r$scenario,'.P'),P);put(paste0('assumed.',r$scenario,'.Y'),Y)}
write.csv(data.frame(metric=names(M),value=vapply(M,identity,numeric(1))),file='econ17-r-results.csv',row.names=FALSE,quote=TRUE,fileEncoding='UTF-8');cat('metrics=',length(M),'\n',sep='')
