if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
C<-read.csv("math15-sources/korea-2014-2024-gdp-linear-projection.csv",check.names=FALSE);y<-C$reported_GDPpc_constant2015USD_per_person;x<-C$centered_year_u
a<-mean(y);b<-sum(x*y)/sum(x^2)
P<-read.csv("math10-sources/power-2006-12-17.csv",check.names=FALSE)
key<-names(P)[tolower(names(P))%in%c("global_active_power","kw","global_active_power_kw")][1];p<-P[[key]]
A<-read.csv("math16-sources/apple-sales-two-year-gram-input.csv",check.names=FALSE)
sales<-as.numeric(A$reported_FY2023_net_sales_million_USD);target<-as.numeric(A$reported_FY2024_net_sales_million_USD);xx<-sum(sales^2);xy<-sum(sales*target);alpha<-xy/xx;loss<-function(z)sum((z*sales-target)^2)/(2*length(sales))
results<-c(country_n=length(y),country_min=min(y),country_max=max(y),country_min_year=C$year[which.min(y)],country_max_year=C$year[which.max(y)],country_intercept=a,country_slope=b,country_model_min=a-5*b,country_model_max=a+5*b,power_n=length(p),power_mean=mean(p),power_min=min(p),power_max=max(p),power_min_count=sum(p==min(p)),power_max_count=sum(p==max(p)),power_constant_min_loss=mean((p-mean(p))^2)/2,company_alpha=alpha,company_curvature=xx/length(sales),company_interval_min_alpha=1.01,company_interval_min_loss=loss(1.01),company_interval_max_alpha=.95,company_interval_max_loss=loss(.95),company_derivative_at_min=(xx*1.01-xy)/length(sales),company_unrestricted_loss=loss(alpha),local_min_minus1=-5/12,global_min_2=-8/3)
stopifnot(identical(which(p==min(p))-1L,c(172L,263L)),identical(which(p==max(p))-1L,543L))
write.csv(data.frame(metric=names(results),value=unname(results)),"math19-r-results.csv",row.names=FALSE)
cat("MATH-19: R record extrema/all ties, OLS and bounded-loss candidates reproduced.\n")
