cjerzak's picture
Upload 24 files
748dd7d verified
parse_env_flag <- function(name, default = FALSE) {
value <- Sys.getenv(name, unset = if (default) "true" else "false")
tolower(trimws(value)) %in% c("1", "true", "yes", "y")
}
find_replication_root <- function() {
file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
script_dir <- character()
if (length(file_arg) > 0) {
script_path <- sub("^--file=", "", file_arg[[1]])
script_dir <- dirname(normalizePath(script_path, mustWork = FALSE))
}
candidates <- unique(Filter(
nzchar,
c(
Sys.getenv("IMAGEDECONFOUND_REPLICATION_ROOT", unset = ""),
getwd(),
dirname(getwd()),
dirname(dirname(getwd())),
script_dir,
dirname(script_dir)
)
))
for (candidate in candidates) {
candidate <- normalizePath(candidate, winslash = "/", mustWork = FALSE)
if (!dir.exists(candidate)) {
next
}
if (file.exists(file.path(candidate, "code", "lib", "call_CI_Conf_5k_3yr.R")) &&
dir.exists(file.path(candidate, "data", "interim")) &&
dir.exists(file.path(candidate, "results"))) {
return(candidate)
}
}
stop("Could not locate the replication root. Set IMAGEDECONFOUND_REPLICATION_ROOT explicitly.")
}
set_replication_root <- function(root = NULL, quiet = FALSE) {
root <- normalizePath(root %||% find_replication_root(), winslash = "/", mustWork = FALSE)
options(replication.root = root)
setwd(root)
if (!quiet) {
message("Replication root: ", root)
}
invisible(root)
}
`%||%` <- function(lhs, rhs) {
if (is.null(lhs) || length(lhs) == 0) {
return(rhs)
}
lhs
}
bundle_results_root <- function(root = getOption("replication.root")) {
file.path(root, "results", "per_run_csv", "Epoch5EarlyStopNewTreatDefLabelS_Run2")
}
bundle_results_processed_dir <- function(root = getOption("replication.root")) {
file.path(bundle_results_root(root), "results_processed")
}
bundle_public_results_dir <- function(root = getOption("replication.root")) {
file.path(root, "results", "processed")
}
bundle_tables_dir <- function(root = getOption("replication.root")) {
file.path(root, "tables")
}
ensure_dir <- function(path) {
dir.create(path, recursive = TRUE, showWarnings = FALSE)
invisible(path)
}
resolve_external_path <- function(envvar, default_relative) {
root <- getOption("replication.root", default = find_replication_root())
env_value <- Sys.getenv(envvar, unset = "")
if (nzchar(env_value)) {
return(normalizePath(env_value, winslash = "/", mustWork = FALSE))
}
normalizePath(file.path(root, default_relative), winslash = "/", mustWork = FALSE)
}
run_replication_script <- function(script_relative, overrides = list()) {
root <- set_replication_root(quiet = TRUE)
script_path <- file.path(root, script_relative)
if (!file.exists(script_path)) {
stop("Missing script: ", script_path)
}
keep_names <- unique(c(
names(overrides),
get0("KeepObjectsAcrossAnalysisStrings", ifnotfound = character(), inherits = TRUE)
))
env <- new.env(parent = globalenv())
if (length(overrides) > 0) {
list2env(overrides, envir = env)
}
env$KeepObjectsAcrossAnalysisStrings <- keep_names
sys.source(script_path, envir = env)
invisible(env)
}
copy_named_files <- function(files, destination_dir, overwrite = TRUE) {
ensure_dir(destination_dir)
if (length(files) == 0) {
return(invisible(character()))
}
ok <- file.copy(files, destination_dir, overwrite = overwrite)
if (any(!ok)) {
failed <- basename(files[!ok])
warning("Some files failed to copy: ", paste(failed, collapse = ", "))
}
invisible(files[ok])
}
sync_results_processed <- function(overwrite = TRUE) {
source_dir <- bundle_results_processed_dir()
destination_dir <- bundle_public_results_dir()
if (!dir.exists(source_dir)) {
warning("No nested results_processed directory found at ", source_dir)
return(invisible(character()))
}
files <- list.files(source_dir, full.names = TRUE)
copied <- copy_named_files(files, destination_dir, overwrite = overwrite)
message("Synced ", length(copied), " processed result files into results/processed.")
invisible(copied)
}
sync_table_assets <- function(overwrite = TRUE) {
results_dir <- bundle_public_results_dir()
tables_dir <- bundle_tables_dir()
tex_files <- list.files(results_dir, pattern = "\\.tex$", full.names = TRUE)
copied <- copy_named_files(tex_files, tables_dir, overwrite = overwrite)
if (length(copied) > 0) {
message("Synced ", length(copied), " LaTeX table/macro files into tables/.")
}
invisible(copied)
}
compute_sha256 <- function(path) {
sha256sum_bin <- Sys.which("sha256sum")
shasum_bin <- Sys.which("shasum")
if (nzchar(sha256sum_bin)) {
output <- system2(sha256sum_bin, shQuote(path), stdout = TRUE, stderr = TRUE)
return(strsplit(output[[1]], "\\s+")[[1]][[1]])
}
if (nzchar(shasum_bin)) {
output <- system2(shasum_bin, c("-a", "256", shQuote(path)), stdout = TRUE, stderr = TRUE)
return(strsplit(output[[1]], "\\s+")[[1]][[1]])
}
NA_character_
}
verify_manifest_file <- function(manifest_path, verify_hash = TRUE) {
if (!file.exists(manifest_path)) {
message("Manifest not found at ", manifest_path, ". Skipping checksum verification.")
return(invisible(NULL))
}
manifest <- read.csv(manifest_path, stringsAsFactors = FALSE)
required_columns <- c("path", "size_bytes", "sha256", "role")
missing_columns <- setdiff(required_columns, names(manifest))
if (length(missing_columns) > 0) {
stop("Manifest is missing columns: ", paste(missing_columns, collapse = ", "))
}
root <- getOption("replication.root", default = find_replication_root())
resolved_paths <- file.path(root, manifest$path)
exists_flag <- file.exists(resolved_paths)
if (!all(exists_flag)) {
stop(
"Manifest references missing files: ",
paste(manifest$path[!exists_flag], collapse = ", ")
)
}
actual_sizes <- file.info(resolved_paths)$size
if (!all(actual_sizes == manifest$size_bytes)) {
bad_rows <- which(actual_sizes != manifest$size_bytes)
stop(
"Manifest size mismatch for: ",
paste(manifest$path[bad_rows], collapse = ", ")
)
}
if (verify_hash) {
sample_hash <- compute_sha256(resolved_paths[[1]])
if (is.na(sample_hash)) {
message("No SHA-256 utility found. Skipping checksum verification.")
return(invisible(manifest))
}
actual_hashes <- vapply(resolved_paths, compute_sha256, character(1))
if (!all(actual_hashes == manifest$sha256)) {
bad_rows <- which(actual_hashes != manifest$sha256)
stop(
"Manifest checksum mismatch for: ",
paste(manifest$path[bad_rows], collapse = ", ")
)
}
}
message("Manifest verification passed for ", nrow(manifest), " files.")
invisible(manifest)
}
verify_bundle <- function(verify_hash = TRUE) {
root <- set_replication_root(quiet = TRUE)
required_dirs <- c(
"code/lib",
"data/interim",
"data/country_regions",
"results/per_run_csv/Epoch5EarlyStopNewTreatDefLabelS_Run2",
"results/processed",
"figures/manuscript",
"tables",
"env",
"manifests"
)
required_files <- c(
"README.md",
"code/common.R",
"code/00_verify_bundle.R",
"code/01_rebuild_paper_outputs.R",
"code/02_run_main_ate_optional.R",
"code/03_run_within_unit_robustness.R",
"code/04_consolidate_results.R",
"code/05_build_figures_tables.R",
"data/interim/dhs_5k_confounders.csv",
"data/interim/dhs_treated_sector_3yr.csv",
"data/interim/africa_oda_sector_group.csv",
"results/processed/ICA_xruns_all_vt_emb_3yr_2013.csv",
"results/processed/wb_vs_ch_sector_scatter_WithinUnitVar.pdf",
"env/R_packages.txt",
"env/requirements-image-download.txt",
"manifests/external_requirements.md"
)
missing_dirs <- required_dirs[!dir.exists(file.path(root, required_dirs))]
missing_files <- required_files[!file.exists(file.path(root, required_files))]
if (length(missing_dirs) > 0 || length(missing_files) > 0) {
problems <- c(
if (length(missing_dirs) > 0) paste("Missing directories:", paste(missing_dirs, collapse = ", ")),
if (length(missing_files) > 0) paste("Missing files:", paste(missing_files, collapse = ", "))
)
stop(paste(problems, collapse = " | "))
}
expected_run_counts <- c(
vt_3yr_noX = 99L,
vt_3yr_onlyFE = 100L,
vt_3yr_onlyX = 100L,
vt_3yr_onlyXandFE = 100L,
vt_3yr_withFE = 100L,
vt_3yr_withX = 400L,
vt_3yr_withXandFE = 100L,
vt_3yr_unitFE = 100L,
vt_3yr_did = 49L
)
run_root <- bundle_results_root(root)
actual_run_counts <- vapply(
names(expected_run_counts),
function(name) {
length(list.files(file.path(run_root, name), pattern = "\\.csv$", full.names = TRUE))
},
integer(1)
)
if (any(actual_run_counts < expected_run_counts)) {
bad <- names(actual_run_counts)[actual_run_counts < expected_run_counts]
stop(
"Incomplete per-run CSV directories: ",
paste(
sprintf("%s (%s < %s)", bad, actual_run_counts[bad], expected_run_counts[bad]),
collapse = ", "
)
)
}
results_processed_n <- length(list.files(bundle_public_results_dir(root), full.names = TRUE))
if (results_processed_n < 100L) {
stop("results/processed looks incomplete: found only ", results_processed_n, " files.")
}
manuscript_fig_n <- length(list.files(file.path(root, "figures", "manuscript"), full.names = TRUE))
if (manuscript_fig_n < 100L) {
stop("figures/manuscript looks incomplete: found only ", manuscript_fig_n, " files.")
}
verify_manifest_file(
file.path(root, "manifests", "file_manifest.csv"),
verify_hash = verify_hash
)
summary <- list(
root = root,
per_run_csv_counts = actual_run_counts,
results_processed_n = results_processed_n,
manuscript_fig_n = manuscript_fig_n
)
message("Bundle verification passed.")
invisible(summary)
}