if(.Platform$OS.type=="windows")invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# STAT-07: base R actual atoms, exact-event CDFs and an explicit spread model.
args<-commandArgs(FALSE);filearg<-args[grepl("^--file=",args)]
if(length(filearg))setwd(dirname(normalizePath(sub("^--file=","",filearg[1]),winslash="/")))
workspace<-normalizePath("../..",winslash="/");common<-"\uc2e4\uc81c\ub370\uc774\ud130";data_dir<-"stats07-sources"
read_actual<-function(p)read.csv(p,fileEncoding="UTF-8-BOM",na.strings=c("","NA"),check.names=FALSE,stringsAsFactors=FALSE)
results<-numeric(0);add<-function(k,v){results[k]<<-as.numeric(v)}
near<-function(a,b,tol=1e-10)stopifnot(all(abs(a-b)<=tol*pmax(1,abs(a))))
fraction<-function(s){v<-strsplit(as.character(s),"/",fixed=TRUE)[[1]];as.numeric(v[1])/if(length(v)==2)as.numeric(v[2]) else 1}

vpop<-function(v)mean((v-mean(v))^2)
cpop<-function(x,y)mean((x-mean(x))*(y-mean(y)))
groups<-function(values,labels){mu<-mean(values);n<-length(values);out<-list();for(g in sort(unique(labels))){a<-values[labels==g];w<-length(a)/n;gm<-mean(a);gv<-vpop(a);out[[g]]<-c(n=length(a),weight=w,mean=gm,variance=gv,weightedMean=w*gm,withinTerm=w*gv,betweenTerm=w*(gm-mu)^2)};near(sum(vapply(out,function(z)z[["weightedMean"]],numeric(1))),mu);near(sum(vapply(out,function(z)z[["withinTerm"]]+z[["betweenTerm"]],numeric(1))),vpop(values));out}
W<-read_actual(file.path(common,"worldbank.csv"));W<-W[W$year==2024,];W<-W[order(W$country),];gdp<-W$gdp_pc;pop<-W$population;clabel<-ifelse(W$life_expectancy>=80,"life_ge_80","life_lt_80");CG<-groups(gdp,clabel)
archive<-file.path(workspace,"work/textbooks-2026/raw/penguins.csv");P<-read_actual(if(file.exists(archive))archive else file.path(common,"penguins.csv"));V<-P[!is.na(P$body_mass_g),];mass<-V$body_mass_g;flipper<-V$flipper_length_mm;PG<-groups(mass,V$species);stopifnot(nrow(W)==16,nrow(P)==344,nrow(V)==342)
S<-read_actual(file.path(data_dir,"actual-apple-paired-category-values-and-change.csv"));categories<-c("iPhone","Mac","iPad","Wearables, Home and Accessories","Services");sales<-list();sec<-file.path(workspace,"work/textbook-rewrite-2026/source-audit-math08/apple-2024.html")
if(file.exists(sec)){
 text<-paste(readLines(sec,encoding="UTF-8",warn=FALSE),collapse=" ");extract<-function(pattern,s)regmatches(s,gregexpr(pattern,s,perl=TRUE))[[1]];plain<-function(s)trimws(gsub("\\s+"," ",gsub("&#160;|&nbsp;"," ",gsub("<[^>]+>"," ",s),perl=TRUE)));tables<-extract("(?s)<table\\b.*?</table>",text);cand<-tables[vapply(tables,function(t)grepl("iPhone",plain(t),fixed=TRUE)&&grepl("Services",plain(t),fixed=TRUE),logical(1))];stopifnot(length(cand)>=1);rows<-extract("(?s)<tr\\b.*?</tr>",cand[1])
 for(category in categories){found<-FALSE;for(row in rows){cells<-vapply(extract("(?s)<t[dh]\\b.*?</t[dh]>",row),plain,character(1));if(length(cells)&&sub("\\s*\\([0-9]+\\)$","",cells[1])==category){values<-as.numeric(gsub(",","",cells[grepl("^[0-9]{1,3}(,[0-9]{3})+$",cells)],fixed=TRUE));stopifnot(length(values)==3);sales[[category]]<-setNames(values,c("2024","2023","2022"));found<-TRUE;break}};stopifnot(found)}
 x<-vapply(categories,function(c)sales[[c]][["2023"]],numeric(1));y<-vapply(categories,function(c)sales[[c]][["2024"]],numeric(1))
}else{x<-S$actual_FY2023_net_sales_million_nominalUSD;y<-S$actual_FY2024_net_sales_million_nominalUSD}

change<-y-x;AG<-groups(y,c(rep("hardware",4),"services"));stopifnot(sum(x)==383285,sum(y)==391035,identical(S$category,categories));near(x,S$actual_FY2023_net_sales_million_nominalUSD);near(y,S$actual_FY2024_net_sales_million_nominalUSD);near(change,S$paired_change_million_nominalUSD)
C<-read_actual(file.path(data_dir,"actual-country-values-and-conditional-mean-map.csv"));stopifnot(nrow(C)==16,identical(C$country,W$country));near(gdp,C$reported_GDPpc_constant2015USD_per_person);near(W$life_expectancy,C$reported_life_expectancy_years)
for(i in seq_len(nrow(C))){near(CG[[clabel[i]]][["mean"]],fraction(C$conditional_GDP_mean_exact[i]));near(gdp[i]-CG[[clabel[i]]][["mean"]],fraction(C$GDP_minus_conditional_mean_exact[i]));near(CG[[clabel[i]]][["mean"]]-mean(gdp),fraction(C$conditional_mean_minus_overall_mean_exact[i]));near(pop[i]/sum(pop),fraction(C$population_weight_exact[i]))}
C<-read_actual(file.path(data_dir,"actual-penguin-masses-and-species-conditional-mean-map.csv"));good<-!is.na(P$body_mass_g);stopifnot(nrow(C)==344,identical(is.na(C$reported_body_mass_g),!good));near(C$reported_body_mass_g[good],mass);near(C$reported_flipper_length_mm[good],flipper)
for(i in which(good)){near(PG[[P$species[i]]][["mean"]],fraction(C$species_conditional_mean_g_exact[i]));near(P$body_mass_g[i]-PG[[P$species[i]]][["mean"]],fraction(C$mass_minus_species_mean_g_exact[i]));near(P$body_mass_g[i]-mean(mass),fraction(C$mass_minus_overall_mean_g_exact[i]))}
allgroups<-list(country=CG,person=PG,company=AG);C<-read_actual(file.path(data_dir,"exact-conditional-moments-and-total-variance-contributions.csv"));stopifnot(nrow(C)==7)
groupkeys<-c(actual_valid_records="n",assigned_group_probability_exact="weight",conditional_mean_exact="mean",conditional_variance_exact="variance",weighted_mean_contribution_exact="weightedMean",within_variance_contribution_exact="withinTerm",between_variance_contribution_exact="betweenTerm")
for(i in seq_len(nrow(C))){z<-allgroups[[C$case[i]]][[C$group[i]]];for(stored in names(groupkeys)){key<-groupkeys[[stored]];value<-z[[key]];near(value,fraction(C[[stored]][i]));add(paste(C$case[i],C$group[i],key,sep="_"),value)}}
expected<-list();metric<-function(case,name,value){expected[[paste(case,name,sep="|")]]<<-value;add(paste(case,name,sep="_"),value)}
for(case in c("country","person","company")){values<-switch(case,country=gdp,person=mass,company=y);G<-allgroups[[case]];metric(case,"expectation",mean(values));metric(case,"second_moment",mean(values^2));metric(case,"variance",vpop(values));metric(case,"expected_conditional_variance",sum(vapply(G,function(z)z[["withinTerm"]],numeric(1))));metric(case,"variance_of_conditional_expectation",sum(vapply(G,function(z)z[["betweenTerm"]],numeric(1))))}
metric("country","population_weighted_expectation",sum(gdp*pop)/sum(pop));metric("person","unweighted_three_species_means",mean(vapply(PG,function(z)z[["mean"]],numeric(1))));metric("person","expectation_mass_kg",mean(mass)/1000);metric("person","variance_mass_kg",vpop(mass)/1000000);metric("person","expectation_flipper",mean(flipper));metric("person","expectation_flipper_times_mass",mean(flipper*mass));metric("person","product_of_expectations",mean(flipper)*mean(mass));metric("person","covariance_flipper_mass",cpop(flipper,mass))
vals<-c(expectation_FY2023=mean(x),expectation_FY2024=mean(y),expectation_paired_change=mean(change),variance_FY2023=vpop(x),variance_FY2024=vpop(y),covariance_two_years=cpop(x,y),variance_paired_change=vpop(change),incorrect_independence_reference_variance=vpop(x)+vpop(y),FY2024_sales_weighted_expectation=sum(y^2)/sum(y));for(k in names(vals))metric("company",k,vals[[k]])
near(mean(change),mean(y)-mean(x));near(vpop(change),vpop(x)+vpop(y)-2*cpop(x,y));near(vpop(change),23940885.2)
C<-read_actual(file.path(data_dir,"exact-law-moments-linearity-and-covariance-identities.csv"));stopifnot(nrow(C)==length(expected),nrow(C)==32)
for(i in seq_len(nrow(C))){value<-expected[[paste(C$case[i],C$quantity[i],sep="|")]];near(value,fraction(C$exact_fraction[i]));near(value,C$decimal80[i])}
vals<-c(country_actual_records=nrow(W),penguin_original_rows=nrow(P),penguin_valid_mass_records=nrow(V),company_actual_categories=length(categories),company_total_FY2023=sum(x),company_total_FY2024=sum(y),company_total_actual_change=sum(change),penguin_independent_column_ordered_pairs=nrow(V)^2);for(k in names(vals))add(k,vals[[k]])
write.csv(data.frame(metric=names(results),value=unname(results)),"stat07-r-results.csv",row.names=FALSE)
cat("STAT-07:",length(results),"numeric metrics independently recomputed with base R.\n")
