if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Direct base-R SVD; no eigen-decomposition of a computed Gram matrix.
country <- read.csv("math16-sources/worldbank-2024-standardized-covariance-coordinates.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)
C <- as.matrix(country[,c("GDPpc_constant2015USD_per_person","life_expectancy_at_birth_years")]); C <- sweep(C,2,colMeans(C),"-"); C <- sweep(C,2,sqrt(colMeans(C^2)),"/")
P <- as.matrix(house[,c("reported_kitchen_energy_Wh","reported_laundry_energy_Wh")]); hm <- unname(colMeans(P)); H <- sweep(P,2,hm,"-")
R <- rbind(as.numeric(company$reported_FY2023_net_sales_million_USD),as.numeric(company$reported_FY2024_net_sales_million_USD))
matrices <- list(country=C,person=H,company=R);results <- c()
for(kind in names(matrices)){
  A <- matrices[[kind]]; z <- svd(A,nu=2,nv=2); B <- tcrossprod(z$u[,1]*z$d[1],z$v[,1])
  stopifnot(max(abs(sweep(z$u,2,z$d,"*")%*%t(z$v)-A))<1e-10*max(1,max(abs(A))))
  sse <- sum((A-B)^2); stopifnot(abs(sse-z$d[2]^2)<1e-10*max(1,sse))
  ap <- if(kind=="person")sweep(B,2,hm,"+")else if(kind=="company")t(B)else B
  vals <- c(m=nrow(A),n=ncol(A),s1=z$d[1],s2=z$d[2],sse=sse,retained=z$d[1]^2/sum(z$d^2),first_approx1=ap[1,1],first_approx2=ap[1,2])
  names(vals) <- paste(kind,names(vals),sep="_");results <- c(results,vals)
  if(kind=="person")results <- c(results,person_negative_count=sum(apply(ap<0,1,any)))
  if(kind=="company")results <- c(results,company_approx_total1=sum(ap[,1]),company_approx_total2=sum(ap[,2]))
}
write.csv(data.frame(metric=names(results),value=unname(results)),"math17-r-results.csv",row.names=FALSE)
cat("MATH-17: direct R svd(), rank-one errors and original frequencies reproduced.\n")
