if(.Platform$OS.type=="windows")invisible(Sys.setlocale("LC_CTYPE","English_United States.utf8"))
# DATA-17: base R actual economic units, aggregation and fiscal calendars.
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<-"data17-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)
C<-read_actual(file.path(common,"college-proximity.csv"));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)};original<-list(person=part(1,5),nearc4=part(10,10),education=part(18,19),age=part(24,25),log_wage=part(86,97),metro=part(116,116),south=part(120,120));for(k in names(original)){stopifnot(identical(is.na(C[[k]]),is.na(original[[k]])));good<-!is.na(original[[k]]);near(C[[k]][good],original[[k]][good])};w<-original$log_wage[!is.na(original$log_wage)]}else{w<-C$log_wage[!is.na(C$log_wage)]}

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)
H<-read_actual(file.path(common,"korea-housing.csv"));O<-list();for(kind in c("nominal","real")){text<-paste(readLines(file.path(rawdir,paste0("korea-housing-",kind,".csv")),warn=FALSE),collapse=" ");nodes<-regmatches(text,gregexpr('<Obs[^>]+TIME_PERIOD="[^"]+"[^>]+OBS_VALUE="[^"]+"[^>]*>',text,perl=TRUE))[[1]];dates<-sub('.*TIME_PERIOD="([^"]+)".*',"\\1",nodes,perl=TRUE);v<-as.numeric(sub('.*OBS_VALUE="([^"]+)".*',"\\1",nodes,perl=TRUE));stopifnot(length(v)==180,all(H$quarter==dates));near(H[[kind]],v);O[[kind]]<-setNames(v,dates)}
Q<-read_actual(file.path(data_dir,"actual180-Korea-quarterly-nominal-real-housing-indices.csv"));stopifnot(nrow(Q)==180,all(Q$quarter==H$quarter),all(Q$quarter_index_is_end_of_quarter_price=="False"),all(Q$real_series_is_CPI_adjusted=="True"));near(Q$actual_nominal_index_source_decimal,H$nominal);near(Q$actual_real_index_source_decimal,H$real);near(Q$calendar_year,H$year);stopifnot(all(Q$coverage==ifelse(H$year<1986,"pre1986_land_prices","existing_residential_dwellings")))
G<-W[W$country=="KOR",];G<-G[order(G$year),];years<-1980:2024;stopifnot(all(G$year==years));nom<-setNames(vapply(years,function(y)mean(O$nominal[paste0(y,"-Q",1:4)]),numeric(1)),years);real<-setNames(vapply(years,function(y)mean(O$real[paste0(y,"-Q",1:4)]),numeric(1)),years);gdp<-setNames(G$gdp_pc,G$year);A<-read_actual(file.path(data_dir,"actual45-GDP-and-derived-housing-year-alignment.csv"));B<-read_actual(file.path(data_dir,"derived44-distinct-annual-mean-and-Q4-growth-targets.csv"));stopifnot(nrow(A)==45,nrow(B)==44,all(A$housing_annual_mean_independently_reported=="False"),all(A$housing_Q4_is_December_end_price=="False"),all(A$source_annual_GDPpc_repeated_as_quarterly_observation=="False"),all(B$growth_rates_are_same_target=="False"),all(B$housing_growth_is_GDPpc_causal_effect=="False"))
for(i in 1:45){y<-years[i];s<-as.character(y);vals<-c(gdp[s],nom[s],real[s],O$nominal[paste0(y,"-Q4")],O$real[paste0(y,"-Q4")],gdp[s]/gdp["2010"]*100,nom[s]/nom["2010"]*100,real[s]/real["2010"]*100);keys2<-c("actual_annual_GDPpc_constant2015USD_source_decimal","derived_nominal_four_quarter_mean_exact","derived_real_four_quarter_mean_exact","actual_nominal_Q4_index_source_decimal","actual_real_Q4_index_source_decimal","chosen_GDPpc_2010_equals100_exact","chosen_nominal_mean_2010_equals100_exact","chosen_real_mean_2010_equals100_exact");near(A$calendar_year[i],y);for(j in seq_along(vals)){near(fraction(A[[keys2[j]]][i]),vals[j]);add(paste0("country_",y,"_",keys2[j]),unname(vals[j]))};if(i>1){p<-as.character(y-1);vals<-c(gdp[s]/gdp[p]-1,nom[s]/nom[p]-1,real[s]/real[p]-1,O$nominal[paste0(y,"-Q4")]/O$nominal[paste0(y-1,"-Q4")]-1,O$real[paste0(y,"-Q4")]/O$real[paste0(y-1,"-Q4")]-1);ks<-c("derived_annual_GDPpc_growth_fraction_exact","derived_nominal_annual_mean_growth_fraction_exact","derived_real_annual_mean_growth_fraction_exact","derived_nominal_Q4_over_previous_Q4_growth_fraction_exact","derived_real_Q4_over_previous_Q4_growth_fraction_exact");near(B$calendar_year[i-1],y);for(j in seq_along(vals)){near(fraction(B[[ks[j]]][i-1]),vals[j]);add(paste0("country_",y,"_",ks[j]),unname(vals[j]))}}}
fred<-file.path(workspace,"work/textbook-rewrite-2026/source-audit-econ03/FRED-CPIAUCNS-table.html");text<-paste(readLines(fred,warn=FALSE,encoding="UTF-8"),collapse=" ");pat<-'<th[^>]*>[0-9]{4}-[0-9]{2}-[0-9]{2}</th>\\s*<td[^>]*>\\s*[0-9]+(?:\\.[0-9]+)?\\s*</td>';nodes<-regmatches(text,gregexpr(pat,text,perl=TRUE))[[1]];dates<-sub('.*<th[^>]*>([0-9-]+)</th>.*',"\\1",nodes,perl=TRUE);v<-sub('.*<td[^>]*>\\s*([0-9.]+)\\s*</td>.*',"\\1",nodes,perl=TRUE);nodes2<-regmatches(text,gregexpr('#[0-9]{4}-[0-9]{2}-[0-9]{2}\\|\\s*(?:[0-9]+(?:\\.[0-9]+)?|\\.)',text,perl=TRUE))[[1]];dates<-c(dates,sub('^#([0-9-]+)\\|.*',"\\1",nodes2,perl=TRUE));v<-c(v,sub('^#[0-9-]+\\|\\s*',"",nodes2,perl=TRUE));stopifnot(length(nodes)==1000,length(nodes2)==365,length(unique(dates))==1365);keep<-as.integer(substr(dates,1,4))%in%c(1976,2023,2024);dates<-dates[keep];v<-as.numeric(v[keep]);stopifnot(length(v)==36,all(!is.na(v)));S<-read_actual(file.path(data_dir,"actual36-US-CPI-months-for-three-explicit-price-years.csv"));stopifnot(all(S$date==dates));near(S$actual_CPIAUCNS_source_decimal,v);cp<-setNames(vapply(c(1976,2023,2024),function(y)mean(v[substr(dates,1,4)==as.character(y)]),numeric(1)),c(1976,2023,2024));S<-read_actual(file.path(data_dir,"derived-three-CPI-annual-means-from-published-months.csv"));stopifnot(nrow(S)==3,all(S$is_separately_reported_annual_BLS_statistic=="False"));near(fraction(S$derived_monthly_level_arithmetic_mean_exact),cp)
con<-unz(file.path(rawdir,"proximity.zip"),"nls.dat");lines<-readLines(con,warn=FALSE);close(con);rv<-trimws(substr(lines,128,132));rv[rv=="."]<-NA_character_;raws<-as.numeric(rv);wage<-raws[1]/100;S<-read_actual(file.path(data_dir,"actual-historical-hourly-wage-and-unavailable-time-fields.csv"));stopifnot(nrow(S)==1,S$payment_month_available_in_selected_source=="False",S$actual_work_hours_available_in_selected_source=="False");near(S$actual1976_raw_hourly_wage_cents,raws[1]);near(fraction(S$actual1976_hourly_wage_USD_exact),wage);near(S$source_raw_wages_available,sum(!is.na(raws)));near(S$source_trimmed_logs_available,sum(!is.na(C$log_wage)));S<-read_actual(file.path(data_dir,"explicit-three-price-year-unit-conversions-of-one-wage.csv"));stopifnot(nrow(S)==3,all(S$payment_month_price_matching_verified=="False"),all(S$individual_cost_of_living_estimated=="False"),all(S$actual_work_hours_imputed=="False"));for(i in 1:3){y<-c(1976,2023,2024)[i];cpi<-unname(cp[as.character(y)]);value<-wage*cpi/unname(cp["1976"]);near(S$reference_price_year[i],y);near(fraction(S$chosen_CPI_year_mean_exact[i]),cpi);near(fraction(S$base1976_CPI_year_mean_exact[i]),unname(cp["1976"]));near(fraction(S$derived_USD_per_hour_in_reference_price_unit_exact[i]),value);stopifnot(S$reference_year_wage_actually_observed[i]==if(y==1976)"True" else "False");add(paste0("person_",y,"_CPIAnnualMean"),cpi);add(paste0("person_",y,"_chosenPriceUnitWage"),value)};add("person_sourceRawAvailable",sum(!is.na(raws)));add("person_sourceLogAvailable",sum(!is.na(C$log_wage)));add("person_actual1976RawCents",raws[1])
text<-paste(readLines(file.path(workspace,"work/textbook-rewrite-2026/source-audit-math08/apple-2024.html"),encoding="UTF-8",warn=FALSE),collapse=" ");contexts<-regmatches(text,gregexpr('(?s)<xbrli:context id="[^"]+">.*?</xbrli:context>',text,perl=TRUE))[[1]];periods<-list();for(node in contexts)if(!grepl("<xbrli:segment>",node,fixed=TRUE)&&grepl("<xbrli:startDate>",node,fixed=TRUE)){id<-sub('.*<xbrli:context id="([^"]+)".*',"\\1",node,perl=TRUE);a<-sub('.*<xbrli:startDate>([^<]+)</xbrli:startDate>.*',"\\1",node,perl=TRUE);b<-sub('.*<xbrli:endDate>([^<]+)</xbrli:endDate>.*',"\\1",node,perl=TRUE);periods[[id]]<-c(a,b)};nodes<-regmatches(text,gregexpr('(?s)<ix:nonFraction[^>]*>.*?</ix:nonFraction>',text,perl=TRUE))[[1]];rows<-list();for(node in nodes)if(grepl('name="us-gaap:RevenueFromContractWithCustomerExcludingAssessedTax"',node,fixed=TRUE)&&grepl('unitRef="usd"',node,fixed=TRUE)&&grepl('scale="6"',node,fixed=TRUE)){id<-sub('.*contextRef="([^"]+)".*',"\\1",node,perl=TRUE);period<-periods[[id]];if(!is.null(period)){a<-as.Date(period[1]);b<-as.Date(period[2]);days<-as.integer(b-a)+1;y<-as.integer(format(b,"%Y"));if(days>300&&y%in%c(2023,2024)){value<-as.numeric(gsub(",","",gsub("<[^>]+>","",node),fixed=TRUE));rows[[as.character(y)]]<-data.frame(year=y,start=period[1],end=period[2],days=days,weeks=days/7,revenue=value)}}};F<-do.call(rbind,rows[c("2023","2024")]);stopifnot(nrow(F)==2);S<-read_actual(file.path(data_dir,"actual-two-Apple-XBRL-duration-sales-facts-and-calendar-days.csv"));stopifnot(nrow(S)==2,all(S$actual_period_start==F$start),all(S$actual_period_end==F$end),all(S$average_is_actual_daily_path=="False"));for(i in 1:2){vals<-c(inclusive_calendar_days=F$days[i],actual_fiscal_weeks=F$weeks[i],actual_nominal_net_sales_million_USD=F$revenue[i],mechanical_average_million_USD_per_day_exact=F$revenue[i]/F$days[i]);for(k in names(vals)){near(fraction(S[[k]][i]),vals[[k]]);add(paste0("company_FY",F$year[i],"_",k),vals[[k]])}}
S<-read_actual(file.path(data_dir,"actual-six-fiscal-calendar-overlaps-and-uniform-allocation-model.csv"));T<-read_actual(file.path(data_dir,"actual-three-calendar-coverage-checks-and-model-limits.csv"));stopifnot(nrow(S)==6,nrow(T)==3,all(S$allocated_subperiod_revenue_actually_observed=="False"),all(S$source_daily_uniformity_observed=="False"),all(T$model_amount_is_actual_calendar_annual_revenue=="False"),all(T$full_year_revenue_identified_from_two_FY_totals=="False"));index<-0;for(y in 2022:2024){jan<-as.Date(paste0(y,"-01-01"));dec<-as.Date(paste0(y,"-12-31"));covered<-numeric(0);modeled<-0;for(i in 1:2){index<-index+1;a<-max(jan,as.Date(F$start[i]));b<-min(dec,as.Date(F$end[i]));n<-max(0,as.integer(b-a)+1);fr<-n/F$days[i];allocation<-F$revenue[i]*fr;modeled<-modeled+allocation;if(n>0)covered<-union(covered,as.integer(seq(a,b,by="day")));near(S$target_calendar_year[index],y);near(S$source_fiscal_year[index],F$year[i]);near(S$actual_overlap_calendar_days[index],n);near(S$actual_source_fiscal_days[index],F$days[i]);near(fraction(S$derived_time_overlap_fraction_exact[index]),fr);near(fraction(S$explicit_uniform_within_FY_allocation_million_USD_exact[index]),allocation);add(paste0("company_calendar",y,"_FY",F$year[i],"_days"),n);add(paste0("company_calendar",y,"_FY",F$year[i],"_fraction"),fr);add(paste0("company_calendar",y,"_FY",F$year[i],"_uniformAllocation"),allocation)};days<-as.integer(dec-jan)+1;j<-y-2021;near(T$actual_calendar_days[j],days);near(T$days_covered_by_two_retained_FY_periods[j],length(covered));near(T$days_not_covered[j],days-length(covered));near(fraction(T$explicit_uniform_model_amount_over_covered_days_million_USD_exact[j]),modeled);stopifnot(T$entire_calendar_year_period_covered[j]==if(length(covered)==days)"True" else "False");add(paste0("company_calendar",y,"_calendarDays"),days);add(paste0("company_calendar",y,"_coveredDays"),length(covered));add(paste0("company_calendar",y,"_uncoveredDays"),days-length(covered));add(paste0("company_calendar",y,"_uniformCoveredAmount"),modeled)}
write.csv(data.frame(metric=names(results),value=unname(results)),"data17-r-results.csv",row.names=FALSE);cat("DATA-17:",length(results),"actual-source unit and calendar metrics independently checked.\n")
