if(.Platform$OS.type=="windows")invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# ECON-04: base R original anchors and explicitly assumed constrained choices.
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<-"econ04-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}




fraction<-function(s)vapply(as.character(s),function(v){if(is.na(v)||v=="")return(NA_real_);a<-strsplit(v,"/",fixed=TRUE)[[1]];as.numeric(a[1])/if(length(a)==2)as.numeric(a[2]) else 1},numeric(1),USE.NAMES=FALSE)
rawdir<-file.path(workspace,"work/textbooks-2026/raw");pdf<-file.path(workspace,"work/textbook-rewrite-2026/source-audit-econ01/MOEF-2025-original-budget-enacted-2024-12-10.pdf");lines<-system2("pdftotext",c("-layout",shQuote(pdf),"-"),stdout=TRUE);stopifnot(is.null(attr(lines,"status")));line<-lines[grepl("\ucd1d\uc9c0\ucd9c(\uc99d\uac00\uc728)",lines,fixed=TRUE)][1];nums<-regmatches(line,gregexpr("[0-9][0-9,]*\\.[0-9]+",line))[[1]];levels<-as.numeric(nums[c(1,2,4)]);values<-function(token){line<-tail(lines[grepl(token,lines,fixed=TRUE)],1);as.numeric(regmatches(line,gregexpr("[0-9][0-9,]*\\.[0-9]+",line))[[1]])[1:3]};rd<-values("R&D");culture<-values("\ubb38\ud654");S<-read_actual(file.path(data_dir,"actual-nine-government-budget-total-and-two-sector-references.csv"));stopifnot(nrow(S)==9,all(S$actual_outturn=="False"));vs<-list(total_expenditure=levels,R_and_D=rd,culture_sports_tourism=culture);index<-0;for(k in names(vs))for(i in 1:3){index<-index+1;y<-c(2024,2025,2025)[i];st<-c("enacted_original","proposal","enacted_original")[i];near(fraction(S$reported_trillion_KRW[index]),vs[[k]][i]);near(S$source_year[index],y);stopifnot(S$category[index]==k,S$budget_status[index]==st);add(paste0("source_government_",k,"_",y,"_",st),vs[[k]][i])};M<-rd[3]+culture[3]
con<-unz(file.path(rawdir,"proximity.zip"),"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);raw<-part(128,132);logs<-part(86,97);S<-read_actual(file.path(data_dir,"actual3613-Card-raw-wages-and-distinct-trimmed-logs.csv"));stopifnot(nrow(S)==3613,length(lines)==3613,identical(is.na(raw),is.na(S$actual1976_raw_hourly_wage_cents)),identical(is.na(logs),is.na(S$actual1976_source_trimmed_log_hourly_wage_cents)),all(S$raw_wage_available==ifelse(is.na(raw),"False","True")),all(S$source_trimmed_log_available==ifelse(is.na(logs),"False","True")));near(S$source_row_id,1:3613);near(S$source_person_code,code);near(S$actual1976_raw_hourly_wage_cents[!is.na(raw)],raw[!is.na(raw)]);near(S$actual1976_source_trimmed_log_hourly_wage_cents[!is.na(logs)],logs[!is.na(logs)]);wage<-raw[1]/100;v<-c(rows=length(lines),rawAvailable=sum(!is.na(raw)),logAvailable=sum(!is.na(logs)),rawWithoutLog=sum(!is.na(raw)&is.na(logs)),firstCode=code[1],firstRawCents=raw[1],firstHourlyUSD=wage);for(k in names(v))add(paste0("source_person_",k),v[[k]])
markup<-paste(readLines(file.path(workspace,"work/textbook-rewrite-2026/source-audit-math08/apple-2024.html"),warn=FALSE,encoding="UTF-8"),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),grepl("2023 spanned 53 weeks",plain,fixed=TRUE));rows<-regmatches(markup,gregexpr("(?is)<tr\\b[^>]*>.*?</tr>",markup,perl=TRUE))[[1]];financial<-function(label){hits<-list();for(row in rows){t<-clean(row);if(startsWith(tolower(t),tolower(label))&&grepl("^(\\$|[0-9]|\\()",trimws(substring(t,nchar(label)+1)),perl=TRUE)){t<-gsub("[0-9]+(?:\\.[0-9]+)?[[:space:]]*%"," ",t,perl=TRUE);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]]);hits[[1]]};R<-financial("Research and development");G<-financial("Selling, general and administrative");E<-financial("Total operating expenses");S<-read_actual(file.path(data_dir,"actual-two-Apple-operating-expense-references.csv"));stopifnot(nrow(S)==2,all(S$is_actual_household_consumption=="False"),all(S$physical_input_units_available=="False"));for(j in 1:2){i<-c(2,1)[j];y<-c(2023,2024)[j];v<-c(source_fiscal_weeks=c(53,52)[j],actual_RD_million_USD=R[i],actual_SGA_million_USD=G[i],actual_operating_expenses_million_USD=E[i]);near(S$source_fiscal_year[j],y);near(R[i]+G[i],E[i]);for(k in names(v)){near(fraction(S[[k]][j]),v[[k]]);add(paste0("source_company_",y,"_",k),v[[k]])}}
S<-read_actual(file.path(data_dir,"explicit-six-country-Cobb-share-choices.csv"));alphas<-c(0,.25,.5,.75,rd[3]/M,1);stopifnot(nrow(S)==6,all(S$weights_estimated_from_data=="False"),all(S$legal_transfer_feasibility_established=="False"),all(S$actual_welfare_gain_identified=="False"));for(i in 1:6){a<-alphas[i];x<-a*M;y<-(1-a)*M;v<-c(assumed_Cobb_RD_share_exact=a,assumed_two_item_budget_trillion_KRW_exact=M,hypothetical_RD_choice_trillion_KRW_exact=x,hypothetical_culture_choice_trillion_KRW_exact=y,difference_from_reported_RD_trillion_exact=x-rd[3],difference_from_reported_culture_trillion_exact=y-culture[3]);for(k in names(v)){near(fraction(S[[k]][i]),v[[k]]);add(paste0("country_scenario",i-1,"_",k),v[[k]])};stopifnot(S$original_reported_bundle_is_model_optimum[i]==if(i==5)"True" else "False")}
S<-read_actual(file.path(data_dir,"explicit-four-preferences-compatible-with-reported-country-bundle.csv"));stopifnot(nrow(S)==4,all(S$preference_identified_by_budget_data=="False"),all(S$actual_government_optimality_established=="False"),all(S$reported_bundle_is_one_model_optimum=="True"));near(fraction(S$actual_reference_RD_trillion_exact),rep(rd[3],4));near(fraction(S$actual_reference_culture_trillion_exact),rep(culture[3],4));near(fraction(S$assumed_envelope_trillion_exact),rep(M,4));stopifnot(all(S$model_optimum_set==c("reported_bundle","reported_bundle","entire_frontier","entire_budget_triangle")),all(S$model_optimum_is_unique==c("True","True","False","False")));for(i in 1:4)add(paste0("country_compatiblePreference",i-1,"_unique"),as.integer(i<=2));near(rd[3]/M,37/48);near(rd[3]/culture[3],37/11)
S<-read_actual(file.path(data_dir,"explicit-nine-person-time-budget-Cobb-choices.csv"));stopifnot(nrow(S)==9,all(S$extra_paid_hours_available_is_assumption=="True"),all(S$observed_actual_leisure_or_consumption=="False"),all(S$actual_labor_supply_elasticity_identified=="False"));i<-0;for(V in c(0,40,200))for(a in c(.25,.5,.75)){i<-i+1;T<-24;W<-V+wage*T;uncapped<-(1-a)*W/wage;ell<-min(T,uncapped);h<-T-ell;c<-V+wage*h;near(c+wage*ell,W);stopifnot(ell>=0,ell<=T,h>=0);if(ell<T)near(a*wage*ell,(1-a)*c)else stopifnot((1-a)/ell-a*wage/c>=-1e-14);v<-c(assumed_Cobb_consumption_share_exact=a,assumed_time_endowment_hours_exact=T,assumed_nonlabor_income_1976_USD_exact=V,observed_hourly_wage_1976_USD_exact=wage,assumed_full_income_1976_USD_exact=W,unconstrained_Cobb_leisure_hours_exact=uncapped,hypothetical_leisure_hours_exact=ell,hypothetical_work_hours_exact=h,hypothetical_consumption_1976_USD_exact=c);for(k in names(v)){near(fraction(S[[k]][i]),v[[k]]);add(paste0("person_scenario",i-1,"_",k),v[[k]])};stopifnot(S$time_upper_bound_binds[i]==if(ell==T)"True" else "False")}
S<-read_actual(file.path(data_dir,"explicit-four-company-Cobb-share-choices.csv"));stopifnot(nrow(S)==4,all(S$weights_estimated_from_data=="False"),all(S$actual_liquid_transfer_feasibility_established=="False"),all(S$actual_productivity_gain_identified=="False"));alphas<-c(.25,.5,.75,R[1]/E[1]);for(i in 1:4){a<-alphas[i];x<-a*E[1];y<-(1-a)*E[1];v<-c(assumed_Cobb_RD_share_exact=a,assumed_fixed_expense_envelope_million_USD_exact=E[1],hypothetical_RD_choice_million_USD_exact=x,hypothetical_SGA_choice_million_USD_exact=y,difference_from_reported_RD_million_USD_exact=x-R[1],difference_from_reported_SGA_million_USD_exact=y-G[1]);for(k in names(v)){near(fraction(S[[k]][i]),v[[k]]);add(paste0("company_scenario",i-1,"_",k),v[[k]])};stopifnot(S$reported_bundle_is_model_optimum[i]==if(i==4)"True" else "False")}
S<-read_actual(file.path(data_dir,"explicit-four-ordinal-ranking-bundles.csv"));stopifnot(nrow(S)==4,all(S$values_are_measured_happiness=="False"),all(S$ranking_preserved=="True"));x<-1:4;y<-4:1;for(i in 1:4){u<-x[i]*y[i];v<-c(assumed_bundle_x_exact=x[i],assumed_bundle_y_exact=y[i],chosen_utility_xy_exact=u,strict_increasing_square_transform_on_nonnegative_values_exact=u^2);for(k in names(v)){near(fraction(S[[k]][i]),v[[k]]);add(paste0("ordinal_bundle",i-1,"_",k),v[[k]])}};stopifnot(all(outer(x*y,x*y,">")==outer((x*y)^2,(x*y)^2,">")))
write.csv(data.frame(metric=names(results),value=unname(results)),"econ04-r-results.csv",row.names=FALSE);cat("ECON-04:",length(results),"actual-source anchors and constrained-choice metrics independently checked.\n")
