if(.Platform$OS.type=="windows")invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# ECON-02: 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<-"econ02-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}




rawdir<-file.path(workspace,"work/textbooks-2026/raw");W<-read_actual(file.path(common,"worldbank.csv"));rawfile<-file.path(rawdir,"worldbank-panel.json")
if(file.exists(rawfile)){text<-paste(readLines(rawfile,encoding="UTF-8",warn=FALSE),collapse=" ");pattern<-'\\{\\s*"indicator"\\s*:\\s*\\{[^}]*\\},\\s*"country"\\s*:\\s*\\{[^}]*\\},[^{}]*\\}';nodes<-regmatches(text,gregexpr(pattern,text,perl=TRUE))[[1]];stopifnot(length(nodes)==6480);extract<-function(s,pattern)sub(pattern,"\\1",s,perl=TRUE);indicator<-vapply(nodes,extract,character(1),pattern='.*"indicator"\\s*:\\s*\\{\\s*"id"\\s*:\\s*"([^"]+)".*');iso<-vapply(nodes,extract,character(1),pattern='.*"countryiso3code"\\s*:\\s*"([^"]+)".*');date<-vapply(nodes,extract,character(1),pattern='.*"date"\\s*:\\s*"([^"]+)".*');val<-vapply(nodes,extract,character(1),pattern='.*"date"\\s*:\\s*"[^"]+"\\s*,\\s*"value"\\s*:\\s*([^,}]+).*');val[val=="null"]<-NA_character_;value<-as.numeric(val);keys<-paste(iso,date,indicator,sep="|");for(i in 1:2){col<-c("gdp_pc","life_expectancy")[i];code<-c("NY.GDP.PCAP.KD","SP.DYN.LE00.IN")[i];v<-value[match(paste(W$country,W$year,code,sep="|"),keys)];stopifnot(identical(is.na(v),is.na(W[[col]])));good<-!is.na(v);near(v[good],W[[col]][good])}}
countries<-W[W$year==2024,];countries<-countries[order(countries$country),];stopifnot(nrow(countries)==16)

G<-W[W$country=="KOR"&W$year>=2014&W$year<=2024,];G<-G[order(G$year),];stopifnot(nrow(G)==11);base<-G$gdp_pc[1];last<-G$gdp_pc[11];a<-(last-base)/10;k<-log(last/base)/10;S<-read_actual(file.path(data_dir,"actual11-Korea-GDP-and-explicit-two-anchor-models.csv"));stopifnot(nrow(S)==11,all(S$model_values_are_actual_annual_observations=="False"));near(S$actual_GDPpc_constant2015USD_source_decimal,G$gdp_pc);near(S$year,G$year)
for(i in 1:11){t<-G$year[i]-2014;linear<-base+a*t;exponential<-base*exp(k*t);slope<-k*exponential;near(fraction(S$chosen_two_anchor_linear_exact[i]),linear);near(fraction(S$linear_slope_USD_per_person_per_year_exact[i]),a);near(S$chosen_two_anchor_exponential_Decimal80_approx[i],exponential);near(S$exponential_slope_USD_per_person_per_year_Decimal80_approx[i],slope);vals<-c(actualGDPpc=G$gdp_pc[i],linear=linear,exponential=exponential,exponentialSlope=slope,linearMinusActual=linear-G$gdp_pc[i],exponentialMinusActual=exponential-G$gdp_pc[i]);for(name in names(vals))add(paste0("country_",G$year[i],"_",name),vals[[name]])};add("country_linear_slope",a);add("country_exponential_continuous_rate",k)
archive<-file.path(rawdir,"proximity.zip");if(file.exists(archive)){con<-unz(archive,"nls.dat");lines<-readLines(con,warn=FALSE);close(con);part<-function(a,b){s<-trimws(substr(lines,a,b));s[s=="."]<-NA_character_;as.numeric(s)};code<-part(1,5);wage<-part(128,132);logs<-part(86,97)}else{S<-read.csv(file.path(root,"econ01-sources/actual3613-Card-raw-wages-and-distinct-trimmed-logs.csv"),fileEncoding="UTF-8-BOM",na.strings="",check.names=FALSE);code<-S$source_person_code;wage<-S$actual1976_raw_hourly_wage_cents;logs<-S$actual1976_source_trimmed_log_hourly_wage_cents};stopifnot(length(wage)==3613,code[1]==2,wage[1]==548);w<-wage[1]/100;S<-read_actual(file.path(data_dir,"actual-anonymous-wage-anchor-and-explicit-assumption-flags.csv"));stopifnot(nrow(S)==1,S$time_budget_and_preference_are_observed=="False",S$additional_paid_work_offered_by_source=="False");near(S$source_row_id,1);near(S$original_person_code,code[1]);near(S$actual1976_raw_hourly_wage_cents_source_decimal,wage[1]);near(fraction(S$actual1976_raw_hourly_wage_USD_exact),w);vals<-c(records=length(wage),rawAvailable=sum(!is.na(wage)),logAvailable=sum(!is.na(logs)),rawUnavailable=sum(is.na(wage)),logUnavailable=sum(is.na(logs)),rawAvailableLogUnavailable=sum(!is.na(wage)&is.na(logs)),firstRawCents=wage[1],firstHourly1976USD=w);for(name in names(vals))add(paste0("person_",name),vals[[name]])
S<-read_actual(file.path(data_dir,"explicit-hypothetical-quasilinear-time-choice-profiles.csv"));stopifnot(nrow(S)==16,all(S$choice_and_preferences_are_actual_observations=="False"),all(S$extra_work_availability_is_assumed=="True"));index<-0;for(v in c(0,8,12,20))for(gamma in c(.5,1))for(pay in c(w,w+1)){l<-max(0,min(24,(v-pay)/gamma));h<-24-l;cash<-pay*h;utility<-cash+v*l-gamma*l*l/2;vals<-c(v=v,gamma=gamma,wage=pay,leisure=l,work=h,cash=cash,utility=utility);keys<-c("assumed_leisure_initial_value_USDequiv_per_hour_exact","assumed_gamma_USDequiv_per_hour_squared_exact","hourly_wage_1976USD_exact","chosen_optimal_leisure_hours_exact","chosen_work_hours_exact","conditional_gross_cash1976USD_exact","hypothetical_utility_USDequiv_exact");for(j in seq_along(vals)){near(fraction(S[[keys[j]]][index+1]),vals[j]);add(paste0("person_scenario",index,"_",names(vals)[j]),unname(vals[j]))};stopifnot(S$wage_is_actual_source_anchor[index+1]==if(pay==w)"True" else "False");near(S$chosen_daily_time_budget_hours[index+1],24);for(trial in 0:24)stopifnot(utility+1e-10>=pay*(24-trial)+v*trial-gamma*trial^2/2);index<-index+1}
apple<-file.path(workspace,"work/textbook-rewrite-2026/source-audit-math08/apple-2024.html");if(file.exists(apple)){markup<-paste(readLines(apple,encoding="UTF-8",warn=FALSE),collapse=" ");clean<-function(s){s<-gsub("<[^>]+>"," ",s);s<-gsub("&nbsp;|&#160;|&amp;"," ",s);trimws(gsub("[[:space:]]+"," ",s))};plain<-clean(markup);stopifnot(grepl("2024 and 2022 spanned 52 weeks each",plain,fixed=TRUE));rows<-regmatches(markup,gregexpr("(?is)<tr\\b[^>]*>.*?</tr>",markup,perl=TRUE))[[1]];hits<-list();for(row in rows){t<-clean(row);if(startsWith(t,"Total net sales")){v<-regmatches(t,gregexpr("\\b[0-9][0-9,]*\\b",t,perl=TRUE))[[1]];if(length(v)==3)hits[[length(hits)+1]]<-as.numeric(gsub(",","",v,fixed=TRUE))}};stopifnot(length(hits)>0);for(v in hits)near(v,hits[[1]]);revenue<-hits[[1]][1]}else{S<-read_actual(file.path(data_dir,"actual-Apple-total-annual-net-sales-anchor.csv"));revenue<-S$actual_total_net_sales_million_USD_source_decimal};stopifnot(revenue==391035);S<-read_actual(file.path(data_dir,"actual-Apple-total-annual-net-sales-anchor.csv"));stopifnot(nrow(S)==1,S$actual_unit_price_and_volume_identified=="False");near(S$source_fiscal_year,2024);near(S$source_fiscal_weeks,52);near(S$actual_total_net_sales_million_USD_source_decimal,revenue);add("company_actual_revenue_millionUSD",revenue);add("company_actual_fiscal_weeks",52)
S<-read_actual(file.path(data_dir,"explicit-nonidentified-price-volume-decompositions.csv"));stopifnot(nrow(S)==3,all(S$price_or_quantity_actually_reported=="False"),all(S$composite_unit_is_actual_individual_product=="False"));for(i in 1:3){price<-c(500,1000,1500)[i];q<-revenue/price;near(S$actual_revenue_anchor_million_USD[i],revenue);near(fraction(S$assumed_composite_unit_price_USD_exact[i]),price);near(fraction(S$implied_composite_quantity_million_units_exact[i]),q);add(paste0("company_decomposition",i-1,"_price"),price);add(paste0("company_decomposition",i-1,"_quantity"),q)}
S<-read_actual(file.path(data_dir,"explicit-two-demand-slope-revenue-model-profiles.csv"));stopifnot(nrow(S)==6,all(S$model_price_volume_demand_or_marginal_revenue_identified_from_source=="False"));index<-0;p0<-1000;q0<-revenue/p0;for(b in c(1,4))for(delta in c(-10,0,10)){q<-q0+delta;p<-p0-b*delta;rev<-p*q;mr<-p-b*q;vals<-c(b=b,q=q,p=p,revenue=rev,marginalRevenue=mr);keys<-c("assumed_inverse_demand_slope_USD_per_million_units_exact","assumed_composite_quantity_million_units_exact","assumed_composite_unit_price_USD_exact","assumed_model_revenue_million_USD_exact","assumed_revenue_slope_USD_per_unit_exact");for(j in seq_along(vals)){near(fraction(S[[keys[j]]][index+1]),vals[j]);add(paste0("company_profile",index,"_",names(vals)[j]),unname(vals[j]))};near(S$actual_disclosed_revenue_anchor_million_USD[index+1],revenue);index<-index+1}
write.csv(data.frame(metric=names(results),value=unname(results)),"econ02-r-results.csv",row.names=FALSE);cat("ECON-02:",length(results),"actual-source and explicitly assumed model metrics independently checked.\n")
