if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Independent base R arithmetic from retained actual source cells/aggregates.
# No cases/model JSON, Python numerical results or fitted demand estimates used.
# Chen(2015), UCI Online Retail, DOI 10.24432/C5BW33, CC BY 4.0.
# Full original XLSX audit is separately executed by Python; this R copy uses
# selected original stock/account rows plus the declared full location table.
readsource<-function(f) read.csv(file.path("econ06-sources",f),colClasses="character",check.names=FALSE,fileEncoding="UTF-8-BOM")
stock<-readsource("actual-source-order-selected-stock-all-lines.csv")
account<-readsource("actual-source-order-selected-account-all-lines.csv")
geo<-readsource("actual-all-line-country-label-aggregates.csv")
rat<-function(s) vapply(s,function(x){if(grepl("/",x,fixed=TRUE)){z<-strsplit(x,"/",fixed=TRUE)[[1]];as.numeric(z[1])/as.numeric(z[2])}else as.numeric(x)},numeric(1))
M<-numeric();metric<-function(k,v){M[k]<<-v}
positive<-function(r) as.numeric(r$Quantity)>0 & as.numeric(r$UnitPrice)>0 & !startsWith(toupper(r$InvoiceNo),"C")
metric("source_location_labels",nrow(geo));metric("source_lines_from_location_totals",sum(as.numeric(geo$all_original_source_lines)));metric("positive_lines_from_location_totals",sum(as.numeric(geo$declared_positive_non_cancel_lines)))
fields<-c("all_original_source_lines","declared_positive_non_cancel_lines","signed_recorded_line_amount_GBP_exact","declared_positive_line_amount_GBP_exact")
suffix<-c("all_lines","positive_lines","signed_GBP","positive_GBP")
for(i in seq_len(nrow(geo)))for(j in seq_along(fields)) metric(sprintf("location_%02d_%s",i,suffix[j]),rat(geo[[fields[j]]][i]))
for(prefix in c("stock","account")){
 r<-if(prefix=="stock")stock else account;p<-positive(r);amount<-as.numeric(r$Quantity)*as.numeric(r$UnitPrice)
 metric(paste0(prefix,"_source_lines"),nrow(r));metric(paste0(prefix,"_positive_lines"),sum(p));metric(paste0(prefix,"_invoice_codes"),length(unique(r$InvoiceNo)));metric(paste0(prefix,"_product_codes"),length(unique(r$StockCode)));metric(paste0(prefix,"_cancellation_lines"),sum(startsWith(toupper(r$InvoiceNo),"C")));metric(paste0(prefix,"_signed_GBP"),sum(amount));metric(paste0(prefix,"_positive_GBP"),sum(amount[p]))
}
codes<-unique(account$InvoiceNo)
for(i in seq_along(codes)){
 r<-account[account$InvoiceNo==codes[i],,drop=FALSE];metric(sprintf("invoice_%02d_lines",i),nrow(r));metric(sprintf("invoice_%02d_signed_GBP",i),sum(as.numeric(r$Quantity)*as.numeric(r$UnitPrice)))
}
stock$month<-format(as.Date(floor(as.numeric(stock$InvoiceDate)),origin="1899-12-30"),"%Y-%m")
periods<-list()
for(month in sort(unique(stock$month))){
 r<-stock[stock$month==month & positive(stock),,drop=FALSE];q<-sum(as.numeric(r$Quantity));a<-sum(as.numeric(r$Quantity)*as.numeric(r$UnitPrice));p<-a/q
 first<-as.Date(paste0(month,"-01"));nextfirst<-seq(first,by="month",length.out=2)[2];days<-if(month=="2011-12")9 else as.numeric(nextfirst-first);daily<-q/days;periods[[month]]<-c(q=q,p=p,daily=daily);stem<-paste0("period_",gsub("-","_",month))
 metric(paste0(stem,"_lines"),nrow(r));metric(paste0(stem,"_quantity"),q);metric(paste0(stem,"_amount_GBP"),a);metric(paste0(stem,"_weighted_price_GBP"),p);metric(paste0(stem,"_units_per_calendar_day"),daily);metric(paste0(stem,"_calendar_days"),days)
}
a<-periods[["2011-01"]];b<-periods[["2011-02"]];q0<-a["q"];q1<-b["q"];p0<-a["p"];p1<-b["p"];d0<-a["daily"];d1<-b["daily"];gq<-2*(d1-d0)/(d1+d0);gp<-2*(p1-p0)/(p1+p0)
metric("daily_midpoint_quantity_change",gq);metric("midpoint_price_change",gp);metric("daily_signed_midpoint_ratio",gq/gp);metric("monthly_signed_midpoint_ratio",(2*(q1-q0)/(q1+q0))/gp);metric("daily_signed_base_ratio",((d1-d0)/d0)/((p1-p0)/p0));metric("daily_reversed_midpoint_ratio",(2*(d0-d1)/(d0+d1))/(2*(p0-p1)/(p0+p1)));metric("daily_pence_midpoint_ratio",gq/(2*(100*p1-100*p0)/(100*p1+100*p0)))
write.table(data.frame(metric=names(M),value=unname(M)),"econ06-r-results.csv",sep=",",row.names=FALSE,quote=FALSE)
cat(length(M),"independent base-R source metrics\n")
