if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Independent base R reproduction from actual public selected history/line CSV.
# Saved case/model JSON and Python results are not calculation inputs.
# Original HTML/XLSX reading is independently performed by Python, not claimed here.
# All schedules, rounded GBP2.55 anchor and fixed quantity are explicit assumptions.
readsource<-function(f) read.csv(file.path("econ07-sources",f),colClasses="character",check.names=FALSE,fileEncoding="UTF-8-BOM")
rat<-function(s) unname(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)))
h<-readsource("actual-HMRC-historical-standard-rates.csv");a<-readsource("actual-source-first-retail-line-preserved.csv")
M<-numeric();metric<-function(k,v) M[k]<<-unname(v)
r0<-rat(h$statutory_standard_rate_exact[6]);r1<-rat(h$statutory_standard_rate_exact[7]);p<-51/20;q<-as.numeric(a$Quantity);ps0<-p/(1+r0)
metric("historical_rate_rows",nrow(h));metric("source_quantity",q);metric("source_recorded_price_GBP",as.numeric(a$UnitPrice));metric("source_recorded_amount_GBP",q*as.numeric(a$UnitPrice))
for(i in seq_len(nrow(h))){metric(sprintf("history_%d_rate",i),rat(h$statutory_standard_rate_exact[i]));metric(sprintf("history_%d_percent",i),100*rat(h$statutory_standard_rate_exact[i]))}
metric("rate_change_percentage_points",100*(r1-r0));metric("relative_statutory_rate_change",(r1-r0)/r0);metric("assumed_fixed_net_gross_growth",(1+r1)/(1+r0)-1)
for(i in 1:2){r<-c(r0,r1)[i];v<-c(gross=100*(1+r),tax=100*r,tax_share_of_gross=r/(1+r));for(k in names(v))metric(sprintf("fixed_net_%d_%s",i,k),v[k])}
for(i in 1:2)for(j in 1:2){
 r<-c(r0,r1)[i];net<-if(j==1)p/(1+r)else p;gross<-if(j==1)p else p*(1+r);tax<-gross-net
 v<-c(net_per_unit_GBP=net,tax_per_unit_GBP=tax,gross_per_unit_GBP=gross,total_net_GBP=q*net,total_tax_GBP=q*tax,total_gross_GBP=q*gross)
 for(k in names(v))metric(sprintf("account_%d_%d_%s",i,j,k),v[k])
}
rates<-sort(unique(c((0:40)/100,r0)))
equilibrium<-function(alpha,beta,gamma,delta,r){
 # Solve seller receipt first, then recover quantity: independent algebraic path.
 seller<-(delta*alpha+beta*gamma)/(beta+(1+r)*delta);quantity<-(seller-gamma)/delta;buyer<-(1+r)*seller;wedge<-buyer-seller
 cs<-beta*quantity^2/2;ps<-delta*quantity^2/2;rev<-wedge*quantity;qe<-(alpha-gamma)/(beta+delta);best<-(alpha-gamma)^2/(2*(beta+delta));total<-(alpha-gamma)*quantity-(beta+delta)*quantity^2/2;dwl<-(beta+delta)*(qe-quantity)^2/2
 stopifnot(abs(cs+ps+rev-total)<1e-9,abs(best-total-dwl)<1e-9)
 c(assumed_quantity=quantity,buyer_price_GBP_per_unit=buyer,seller_price_GBP_per_unit=seller,per_unit_wedge_GBP=wedge,consumer_surplus_GBP=cs,producer_surplus_GBP=ps,tax_revenue_GBP=rev,total_surplus_GBP=total,efficient_quantity=qe,efficient_total_surplus_GBP=best,deadweight_loss_GBP=dwl)
}
for(index in 1:2){
 name<-c("A","B")[index];beta<-c(.1,.5)[index];delta<-c(.05,.2)[index];alpha<-p+beta*q;gamma<-ps0-delta*q
 v<-c(alpha=alpha,beta=beta,gamma=gamma,delta=delta);for(k in names(v))metric(paste0("model_",name,"_",k),v[k])
 for(i in seq_along(rates)){v<-equilibrium(alpha,beta,gamma,delta,rates[i]);for(k in names(v))metric(sprintf("model_%s_rate_%02d_%s",name,i-1,k),v[k])}
 old<-equilibrium(alpha,beta,gamma,delta,r0);new<-equilibrium(alpha,beta,gamma,delta,r1);dpc<-new["buyer_price_GBP_per_unit"]-old["buyer_price_GBP_per_unit"];dps<-new["seller_price_GBP_per_unit"]-old["seller_price_GBP_per_unit"];dt<-dpc-dps
 vals<-c(quantity_change=unname(new["assumed_quantity"]-old["assumed_quantity"]),buyer_price_change_GBP=unname(dpc),seller_price_change_GBP=unname(dps),per_unit_wedge_change_GBP=unname(dt),buyer_share_of_extra_unit_wedge=unname(dpc/dt),seller_share_of_extra_unit_wedge=unname(-dps/dt),consumer_surplus_change_GBP=unname(new["consumer_surplus_GBP"]-old["consumer_surplus_GBP"]),producer_surplus_change_GBP=unname(new["producer_surplus_GBP"]-old["producer_surplus_GBP"]),tax_revenue_change_GBP=unname(new["tax_revenue_GBP"]-old["tax_revenue_GBP"]),deadweight_loss_change_GBP=unname(new["deadweight_loss_GBP"]-old["deadweight_loss_GBP"]))
 for(k in names(vals))metric(paste0("incidence_",name,"_",k),vals[k])
}
write.table(data.frame(metric=names(M),value=unname(M)),"econ07-r-results.csv",sep=",",row.names=FALSE,quote=FALSE)
cat("ECON07 base R independent metrics:",length(M),"\n")
