if(.Platform$OS.type=="windows") invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# Run beside data folders. Base R's QR-backed lm is independent of the exact Fraction companion.
file <- paste0(intToUtf8(c(0xC2E4,0xC81C,0xB370,0xC774,0xD130)),"/penguins.csv")
raw <- read.csv(file,na.strings=c("NA",""));raw$row_id <- seq_len(nrow(raw));rows <- raw[!is.na(raw$flipper_length_mm)&!is.na(raw$body_mass_g),]
rows$kg <- rows$body_mass_g/1000;rows$xc <- rows$flipper_length_mm-200
model <- lm(kg~xc,data=rows);e <- residuals(model)
results <- c(penguin_n=nrow(rows),penguin_c200=unname(coef(model)[1]),penguin_slope=unname(coef(model)[2]),penguin_sse=sum(e^2),penguin_row1_fitted=unname(fitted(model)[1]),penguin_row1_residual=unname(e[1]),penguin_sum_residual=sum(e),penguin_sum_centered_x_residual=sum(rows$xc*e))
x <- -2:2;y <- c(-1,0,2,2,4);m <- lm(y~x);r <- residuals(m)
results <- c(results,teaching_a=unname(coef(m)[1]),teaching_b=unname(coef(m)[2]),teaching_sse=sum(r^2),teaching_sum_residual=sum(r),teaching_sum_x_residual=sum(x*r))
g <- read.csv("math15-sources/korea-2014-2024-gdp-linear-projection.csv");gx <- g$year-2019;gy <- g$reported_GDPpc_constant2015USD_per_person;gm <- lm(gy~gx);ge <- residuals(gm)
results <- c(results,country_c2019=unname(coef(gm)[1]),country_slope=unname(coef(gm)[2]),country_sse=sum(ge^2),country_sum_residual=sum(ge),country_sum_centered_x_residual=sum(gx*ge))
h <- read.csv("math15-sources/household-2006-12-17-hourly-constant-projection.csv")
hc <- weighted.mean(h$mean_of_reported_minute_power_kW,h$duration_hours)
results <- c(results,household_constant_kw=hc,household_energy_kwh=sum(h$duration_hours*h$mean_of_reported_minute_power_kW),household_residual_sum=sum(h$mean_of_reported_minute_power_kW-hc))
blocks <- read.csv("math15-sources/household-unequal-duration-weighted-projection.csv")
results <- c(results,household_two_block_weighted=weighted.mean(blocks$mean_power_kW,blocks$duration_hours),household_two_block_unweighted=mean(blocks$mean_power_kW))
a <- read.csv("math15-sources/apple-sales-one-direction-projection.csv");ax <- as.numeric(a$reported_FY2023_net_sales_million_USD);ay <- as.numeric(a$reported_FY2024_net_sales_million_USD);alpha <- sum(ax*ay)/sum(ax^2);ae <- ay-alpha*ax
results <- c(results,company_alpha=alpha,company_sse=sum(ae^2),company_sum_residual=sum(ae),company_x_dot_residual=sum(ax*ae))
u <- c(1,1);v <- c(1,0);r11 <- sqrt(sum(u^2));q1 <- u/r11;r12 <- sum(q1*v);w <- v-r12*q1;r22 <- sqrt(sum(w^2));q2 <- w/r22
results <- c(results,gram_r11=r11,gram_r12=r12,gram_r22=r22,gram_q1_dot_q2=sum(q1*q2))
write.csv(data.frame(quantity=names(results),value=unname(results)),"math15-r-results.csv",row.names=FALSE)
cat("MATH-15:",nrow(rows),"actual penguins;",length(results),"quantities\n")
