if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Independent base-R matrix gradients and Hessians with observations held fixed.
country <- read.csv("math15-sources/korea-2014-2024-gdp-linear-projection.csv",check.names=FALSE)
house <- read.csv("math16-sources/household-2006-12-17-two-submeter-observations.csv",check.names=FALSE)
company <- read.csv("math16-sources/apple-sales-two-year-gram-input.csv",check.names=FALSE)
Xc <- cbind(1,country$centered_year_u);yc <- country$reported_GDPpc_constant2015USD_per_person
Yh <- as.matrix(house[,c("reported_kitchen_energy_Wh","reported_laundry_energy_Wh")]);hm <- unname(colMeans(Yh))
Xe <- cbind(as.numeric(company$reported_FY2023_net_sales_million_USD),c(0,0,0,0,1));ye <- as.numeric(company$reported_FY2024_net_sales_million_USD)
fitting <- function(X,y,p){n<-length(y);r<-drop(X%*%p)-y;list(loss=sum(r^2)/(2*n),g=drop(crossprod(X,r))/n,H=crossprod(X)/n)}
household <- function(p){r<-sweep(Yh,2,p,"-");list(loss=sum(r^2)/(2*nrow(r)),g=p-hm,H=diag(2))}
specs <- list(country=list(fun=function(p)fitting(Xc,yc,p),p=c(33000,700),h=c(50,10)),person=list(fun=household,p=hm,h=c(.1,.2)),company=list(fun=function(p)fitting(Xe,ye,p),p=c(1,0),h=c(.001,100)))
results<-c()
for(kind in names(specs)){
 z<-specs[[kind]];a<-z$fun(z$p);nextloss<-z$fun(z$p+z$h)$loss;quad<-drop(crossprod(z$h,a$H%*%z$h))/2
 opt<-z$p-drop(solve(a$H,a$g));optloss<-z$fun(opt)$loss
 vals<-c(loss=a$loss,g1=a$g[1],g2=a$g[2],h11=a$H[1,1],h12=a$H[1,2],h22=a$H[2,2],next_loss=nextloss,quadratic_term=quad,opt1=opt[1],opt2=opt[2],opt_loss=optloss)
 names(vals)<-paste(kind,names(vals),sep="_");results<-c(results,vals)
 stopifnot(abs(nextloss-(a$loss+sum(a$g*z$h)+quad))<1e-9*max(1,nextloss))
}
results<-c(results,base_f=4,base_fx=3,base_fy=5,chain_value=8,chain_ds=16,chain_dt=11)
write.csv(data.frame(metric=names(results),value=unname(results)),"math18-r-results.csv",row.names=FALSE)
cat("MATH-18: R matrix loss derivatives, Hessians and joint optima reproduced.\n")
