cjerzak commited on
Commit
748dd7d
·
verified ·
1 Parent(s): 31f29f9

Upload 24 files

Browse files
code/00_verify_bundle.R ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+
3
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
4
+ script_path <- sub("^--file=", "", file_arg[[1]])
5
+ source(file.path(dirname(normalizePath(script_path, mustWork = FALSE)), "common.R"))
6
+
7
+ root <- set_replication_root()
8
+ verify_hash <- !parse_env_flag("IMAGEDECONFOUND_SKIP_HASH", default = FALSE)
9
+ summary <- verify_bundle(verify_hash = verify_hash)
10
+
11
+ cat("\nBundle summary\n")
12
+ cat("Root: ", summary$root, "\n", sep = "")
13
+ cat("Processed result files: ", summary$results_processed_n, "\n", sep = "")
14
+ cat("Manuscript figure assets: ", summary$manuscript_fig_n, "\n", sep = "")
15
+ cat("Per-run CSV directories:\n")
16
+ for (name in names(summary$per_run_csv_counts)) {
17
+ cat(" - ", name, ": ", summary$per_run_csv_counts[[name]], "\n", sep = "")
18
+ }
code/01_rebuild_paper_outputs.R ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+
3
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
4
+ script_path <- sub("^--file=", "", file_arg[[1]])
5
+ source(file.path(dirname(normalizePath(script_path, mustWork = FALSE)), "common.R"))
6
+
7
+ root <- set_replication_root()
8
+ message("Rebuilding consolidated outputs, figures, and tables from bundled replication assets.")
9
+
10
+ sys.source(file.path(root, "code", "04_consolidate_results.R"), envir = new.env(parent = globalenv()))
11
+ sys.source(file.path(root, "code", "05_build_figures_tables.R"), envir = new.env(parent = globalenv()))
12
+
13
+ message("Rebuild complete.")
code/02_run_main_ate_optional.R ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+
3
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
4
+ script_path <- sub("^--file=", "", file_arg[[1]])
5
+ source(file.path(dirname(normalizePath(script_path, mustWork = FALSE)), "common.R"))
6
+
7
+ root <- set_replication_root()
8
+ args <- commandArgs(trailingOnly = TRUE)
9
+ if (length(args) == 0) {
10
+ stop("Pass one or more outer-sequence row indices. Example: Rscript code/02_run_main_ate_optional.R 1")
11
+ }
12
+
13
+ resave_tfrecords <- parse_env_flag("IMAGEDECONFOUND_RESAVE_TFRECORDS", default = FALSE)
14
+ tfrecord_home <- resolve_external_path("IMAGEDECONFOUND_TFRECORD_HOME", "external_artifacts/tfrecords")
15
+ image_root <- resolve_external_path("IMAGEDECONFOUND_IMAGE_ROOT", "external_artifacts/images/dhs_tifs_5k_3yr")
16
+
17
+ ensure_dir(tfrecord_home)
18
+
19
+ if (!resave_tfrecords) {
20
+ tfrecord_n <- length(list.files(tfrecord_home, pattern = "\\.tfrecord$", full.names = TRUE))
21
+ if (tfrecord_n == 0) {
22
+ stop(
23
+ "No TFRecord files were found in ", tfrecord_home, ". ",
24
+ "Either place the required TFRecords there or rerun with IMAGEDECONFOUND_RESAVE_TFRECORDS=true ",
25
+ "after downloading the excluded image files locally."
26
+ )
27
+ }
28
+ } else if (!dir.exists(image_root)) {
29
+ stop(
30
+ "IMAGEDECONFOUND_RESAVE_TFRECORDS=true but the image directory does not exist: ",
31
+ image_root
32
+ )
33
+ }
34
+
35
+ run_replication_script(
36
+ "code/lib/call_CI_Conf_5k_3yr.R",
37
+ overrides = list(
38
+ SAVE_RESULTS_FOLDER_OVERRIDE = "per_run_csv/Epoch5EarlyStopNewTreatDefLabelS_Run2",
39
+ X_APPROACH_OPTIONS_OVERRIDE = c(
40
+ "noX", "onlyX", "onlyFE", "onlyXandFE",
41
+ "withX", "withFE", "withXandFE"
42
+ ),
43
+ REQUIRE_EXPLICIT_OUTER_SEQ = TRUE,
44
+ TFRECORD_HOME_OVERRIDE = tfrecord_home,
45
+ IMAGE_ROOT_OVERRIDE = image_root,
46
+ RESAVE_TFRECORDS_OVERRIDE = resave_tfrecords
47
+ )
48
+ )
code/03_run_within_unit_robustness.R ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+
3
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
4
+ script_path <- sub("^--file=", "", file_arg[[1]])
5
+ source(file.path(dirname(normalizePath(script_path, mustWork = FALSE)), "common.R"))
6
+
7
+ set_replication_root()
8
+ message("Running bundled within-unit robustness analyses (unit FE and DiD).")
9
+
10
+ run_replication_script(
11
+ "code/lib/call_CI_Conf_5k_3yr.R",
12
+ overrides = list(
13
+ SAVE_RESULTS_FOLDER_OVERRIDE = "per_run_csv/Epoch5EarlyStopNewTreatDefLabelS_Run2",
14
+ X_APPROACH_OPTIONS_OVERRIDE = c("unitFE", "did"),
15
+ REQUIRE_EXPLICIT_OUTER_SEQ = FALSE,
16
+ RESAVE_TFRECORDS_OVERRIDE = FALSE
17
+ )
18
+ )
code/04_consolidate_results.R ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+
3
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
4
+ script_path <- sub("^--file=", "", file_arg[[1]])
5
+ source(file.path(dirname(normalizePath(script_path, mustWork = FALSE)), "common.R"))
6
+
7
+ root <- set_replication_root()
8
+ results_root_relative <- "./results/per_run_csv/Epoch5EarlyStopNewTreatDefLabelS_Run2"
9
+ results_root <- file.path(root, "results", "per_run_csv", "Epoch5EarlyStopNewTreatDefLabelS_Run2")
10
+
11
+ ensure_dir(file.path(results_root, "results_processed"))
12
+
13
+ message("Consolidating main image-confounding outputs.")
14
+ run_replication_script(
15
+ "code/lib/consolidate_CI_output_across_runs.R",
16
+ overrides = list(
17
+ CONSOLIDATE_RESULTS_DIR_OVERRIDE = results_root_relative
18
+ )
19
+ )
20
+
21
+ message("Consolidating unit fixed-effects robustness outputs.")
22
+ run_replication_script(
23
+ "code/lib/consolidate_CI_output_across_did.R",
24
+ overrides = list(
25
+ WITHIN_UNIT_RESULTS_DIR_OVERRIDE = file.path(results_root_relative, "vt_3yr_unitFE"),
26
+ WITHIN_UNIT_OUTPUT_OVERRIDE = file.path(
27
+ results_root_relative,
28
+ "results_processed",
29
+ "wb_vs_ch_sector_scatter_WithinUnitVar.pdf"
30
+ ),
31
+ WITHIN_UNIT_CAPTION_OVERRIDE = "Estimation method: Unit fixed effects."
32
+ )
33
+ )
34
+
35
+ message("Consolidating difference-in-differences robustness outputs.")
36
+ run_replication_script(
37
+ "code/lib/consolidate_CI_output_across_did.R",
38
+ overrides = list(
39
+ WITHIN_UNIT_RESULTS_DIR_OVERRIDE = file.path(results_root_relative, "vt_3yr_did"),
40
+ WITHIN_UNIT_OUTPUT_OVERRIDE = file.path(
41
+ results_root_relative,
42
+ "results_processed",
43
+ "wb_vs_ch_sector_scatter_DiD.pdf"
44
+ ),
45
+ WITHIN_UNIT_CAPTION_OVERRIDE = "Estimation method: Difference-in-differences."
46
+ )
47
+ )
48
+
49
+ sync_results_processed()
50
+ sync_table_assets()
51
+
52
+ unit_fe_plot <- file.path(root, "results", "processed", "wb_vs_ch_sector_scatter_WithinUnitVar.pdf")
53
+ unit_fe_alias <- file.path(root, "results", "processed", "wb_vs_ch_sector_scatter_WithinUnitFE.pdf")
54
+ if (file.exists(unit_fe_plot)) {
55
+ file.copy(unit_fe_plot, unit_fe_alias, overwrite = TRUE)
56
+ }
57
+
58
+ message("Consolidated outputs are available in results/processed.")
code/05_build_figures_tables.R ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+
3
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
4
+ script_path <- sub("^--file=", "", file_arg[[1]])
5
+ source(file.path(dirname(normalizePath(script_path, mustWork = FALSE)), "common.R"))
6
+
7
+ root <- set_replication_root()
8
+ ensure_dir(file.path(root, "figures"))
9
+ ensure_dir(file.path(root, "tables"))
10
+
11
+ message("Rebuilding descriptive figures.")
12
+ run_replication_script("code/lib/chart_projects.R")
13
+ run_replication_script("code/lib/chart_dhs_projs.R")
14
+
15
+ message("Rebuilding descriptive tables.")
16
+ run_replication_script("code/lib/prep_desc_stats.R")
17
+ sync_table_assets()
18
+
19
+ message("Figures are available in figures/ and tables are available in tables/.")
code/06_list_run_grid.R ADDED
@@ -0,0 +1,41 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env Rscript
2
+
3
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
4
+ script_path <- sub("^--file=", "", file_arg[[1]])
5
+ source(file.path(dirname(normalizePath(script_path, mustWork = FALSE)), "common.R"))
6
+
7
+ set_replication_root()
8
+
9
+ args <- commandArgs(trailingOnly = TRUE)
10
+ grid_name <- if (length(args) > 0) args[[1]] else "main"
11
+
12
+ fund_sect_params <- c(
13
+ "ch_430", "ch_520", "ch_700", "ch_140", "ch_230", "ch_220",
14
+ "ch_310", "ch_160", "wb_330", "wb_410", "ch_110", "ch_210",
15
+ "wb_240", "wb_220", "ch_150", "ch_120", "wb_320", "wb_230",
16
+ "wb_110", "wb_120", "wb_310", "wb_160", "wb_140", "wb_210", "wb_150"
17
+ )
18
+
19
+ if (identical(grid_name, "within_unit")) {
20
+ x_approach_options <- c("unitFE", "did")
21
+ } else if (identical(grid_name, "main")) {
22
+ x_approach_options <- c(
23
+ "noX", "onlyX", "onlyFE", "onlyXandFE",
24
+ "withX", "withFE", "withXandFE"
25
+ )
26
+ } else {
27
+ stop("Unknown grid name: ", grid_name, ". Use 'main' or 'within_unit'.")
28
+ }
29
+
30
+ combos <- expand.grid(
31
+ X_approach = x_approach_options,
32
+ vision_backbone = "vt",
33
+ fund_sect_param = fund_sect_params,
34
+ RUN_MODE = c("MAIN", "ROBUST_NO_NTL", "ROBUST_BUFFER", "ROBUST_STRICT"),
35
+ stringsAsFactors = FALSE
36
+ )
37
+ combos <- combos[order(grepl("only", combos$X_approach), decreasing = TRUE), ]
38
+ combos$row_id <- seq_len(nrow(combos))
39
+ combos <- combos[, c("row_id", "X_approach", "vision_backbone", "fund_sect_param", "RUN_MODE")]
40
+
41
+ write.table(combos, row.names = FALSE, sep = ",", quote = FALSE)
code/common.R ADDED
@@ -0,0 +1,317 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ parse_env_flag <- function(name, default = FALSE) {
2
+ value <- Sys.getenv(name, unset = if (default) "true" else "false")
3
+ tolower(trimws(value)) %in% c("1", "true", "yes", "y")
4
+ }
5
+
6
+ find_replication_root <- function() {
7
+ file_arg <- grep("^--file=", commandArgs(FALSE), value = TRUE)
8
+ script_dir <- character()
9
+ if (length(file_arg) > 0) {
10
+ script_path <- sub("^--file=", "", file_arg[[1]])
11
+ script_dir <- dirname(normalizePath(script_path, mustWork = FALSE))
12
+ }
13
+
14
+ candidates <- unique(Filter(
15
+ nzchar,
16
+ c(
17
+ Sys.getenv("IMAGEDECONFOUND_REPLICATION_ROOT", unset = ""),
18
+ getwd(),
19
+ dirname(getwd()),
20
+ dirname(dirname(getwd())),
21
+ script_dir,
22
+ dirname(script_dir)
23
+ )
24
+ ))
25
+
26
+ for (candidate in candidates) {
27
+ candidate <- normalizePath(candidate, winslash = "/", mustWork = FALSE)
28
+ if (!dir.exists(candidate)) {
29
+ next
30
+ }
31
+ if (file.exists(file.path(candidate, "code", "lib", "call_CI_Conf_5k_3yr.R")) &&
32
+ dir.exists(file.path(candidate, "data", "interim")) &&
33
+ dir.exists(file.path(candidate, "results"))) {
34
+ return(candidate)
35
+ }
36
+ }
37
+
38
+ stop("Could not locate the replication root. Set IMAGEDECONFOUND_REPLICATION_ROOT explicitly.")
39
+ }
40
+
41
+ set_replication_root <- function(root = NULL, quiet = FALSE) {
42
+ root <- normalizePath(root %||% find_replication_root(), winslash = "/", mustWork = FALSE)
43
+ options(replication.root = root)
44
+ setwd(root)
45
+ if (!quiet) {
46
+ message("Replication root: ", root)
47
+ }
48
+ invisible(root)
49
+ }
50
+
51
+ `%||%` <- function(lhs, rhs) {
52
+ if (is.null(lhs) || length(lhs) == 0) {
53
+ return(rhs)
54
+ }
55
+ lhs
56
+ }
57
+
58
+ bundle_results_root <- function(root = getOption("replication.root")) {
59
+ file.path(root, "results", "per_run_csv", "Epoch5EarlyStopNewTreatDefLabelS_Run2")
60
+ }
61
+
62
+ bundle_results_processed_dir <- function(root = getOption("replication.root")) {
63
+ file.path(bundle_results_root(root), "results_processed")
64
+ }
65
+
66
+ bundle_public_results_dir <- function(root = getOption("replication.root")) {
67
+ file.path(root, "results", "processed")
68
+ }
69
+
70
+ bundle_tables_dir <- function(root = getOption("replication.root")) {
71
+ file.path(root, "tables")
72
+ }
73
+
74
+ ensure_dir <- function(path) {
75
+ dir.create(path, recursive = TRUE, showWarnings = FALSE)
76
+ invisible(path)
77
+ }
78
+
79
+ resolve_external_path <- function(envvar, default_relative) {
80
+ root <- getOption("replication.root", default = find_replication_root())
81
+ env_value <- Sys.getenv(envvar, unset = "")
82
+ if (nzchar(env_value)) {
83
+ return(normalizePath(env_value, winslash = "/", mustWork = FALSE))
84
+ }
85
+ normalizePath(file.path(root, default_relative), winslash = "/", mustWork = FALSE)
86
+ }
87
+
88
+ run_replication_script <- function(script_relative, overrides = list()) {
89
+ root <- set_replication_root(quiet = TRUE)
90
+ script_path <- file.path(root, script_relative)
91
+ if (!file.exists(script_path)) {
92
+ stop("Missing script: ", script_path)
93
+ }
94
+
95
+ keep_names <- unique(c(
96
+ names(overrides),
97
+ get0("KeepObjectsAcrossAnalysisStrings", ifnotfound = character(), inherits = TRUE)
98
+ ))
99
+
100
+ env <- new.env(parent = globalenv())
101
+ if (length(overrides) > 0) {
102
+ list2env(overrides, envir = env)
103
+ }
104
+ env$KeepObjectsAcrossAnalysisStrings <- keep_names
105
+
106
+ sys.source(script_path, envir = env)
107
+ invisible(env)
108
+ }
109
+
110
+ copy_named_files <- function(files, destination_dir, overwrite = TRUE) {
111
+ ensure_dir(destination_dir)
112
+ if (length(files) == 0) {
113
+ return(invisible(character()))
114
+ }
115
+
116
+ ok <- file.copy(files, destination_dir, overwrite = overwrite)
117
+ if (any(!ok)) {
118
+ failed <- basename(files[!ok])
119
+ warning("Some files failed to copy: ", paste(failed, collapse = ", "))
120
+ }
121
+ invisible(files[ok])
122
+ }
123
+
124
+ sync_results_processed <- function(overwrite = TRUE) {
125
+ source_dir <- bundle_results_processed_dir()
126
+ destination_dir <- bundle_public_results_dir()
127
+
128
+ if (!dir.exists(source_dir)) {
129
+ warning("No nested results_processed directory found at ", source_dir)
130
+ return(invisible(character()))
131
+ }
132
+
133
+ files <- list.files(source_dir, full.names = TRUE)
134
+ copied <- copy_named_files(files, destination_dir, overwrite = overwrite)
135
+ message("Synced ", length(copied), " processed result files into results/processed.")
136
+ invisible(copied)
137
+ }
138
+
139
+ sync_table_assets <- function(overwrite = TRUE) {
140
+ results_dir <- bundle_public_results_dir()
141
+ tables_dir <- bundle_tables_dir()
142
+ tex_files <- list.files(results_dir, pattern = "\\.tex$", full.names = TRUE)
143
+ copied <- copy_named_files(tex_files, tables_dir, overwrite = overwrite)
144
+ if (length(copied) > 0) {
145
+ message("Synced ", length(copied), " LaTeX table/macro files into tables/.")
146
+ }
147
+ invisible(copied)
148
+ }
149
+
150
+ compute_sha256 <- function(path) {
151
+ sha256sum_bin <- Sys.which("sha256sum")
152
+ shasum_bin <- Sys.which("shasum")
153
+
154
+ if (nzchar(sha256sum_bin)) {
155
+ output <- system2(sha256sum_bin, shQuote(path), stdout = TRUE, stderr = TRUE)
156
+ return(strsplit(output[[1]], "\\s+")[[1]][[1]])
157
+ }
158
+ if (nzchar(shasum_bin)) {
159
+ output <- system2(shasum_bin, c("-a", "256", shQuote(path)), stdout = TRUE, stderr = TRUE)
160
+ return(strsplit(output[[1]], "\\s+")[[1]][[1]])
161
+ }
162
+ NA_character_
163
+ }
164
+
165
+ verify_manifest_file <- function(manifest_path, verify_hash = TRUE) {
166
+ if (!file.exists(manifest_path)) {
167
+ message("Manifest not found at ", manifest_path, ". Skipping checksum verification.")
168
+ return(invisible(NULL))
169
+ }
170
+
171
+ manifest <- read.csv(manifest_path, stringsAsFactors = FALSE)
172
+ required_columns <- c("path", "size_bytes", "sha256", "role")
173
+ missing_columns <- setdiff(required_columns, names(manifest))
174
+ if (length(missing_columns) > 0) {
175
+ stop("Manifest is missing columns: ", paste(missing_columns, collapse = ", "))
176
+ }
177
+
178
+ root <- getOption("replication.root", default = find_replication_root())
179
+ resolved_paths <- file.path(root, manifest$path)
180
+ exists_flag <- file.exists(resolved_paths)
181
+ if (!all(exists_flag)) {
182
+ stop(
183
+ "Manifest references missing files: ",
184
+ paste(manifest$path[!exists_flag], collapse = ", ")
185
+ )
186
+ }
187
+
188
+ actual_sizes <- file.info(resolved_paths)$size
189
+ if (!all(actual_sizes == manifest$size_bytes)) {
190
+ bad_rows <- which(actual_sizes != manifest$size_bytes)
191
+ stop(
192
+ "Manifest size mismatch for: ",
193
+ paste(manifest$path[bad_rows], collapse = ", ")
194
+ )
195
+ }
196
+
197
+ if (verify_hash) {
198
+ sample_hash <- compute_sha256(resolved_paths[[1]])
199
+ if (is.na(sample_hash)) {
200
+ message("No SHA-256 utility found. Skipping checksum verification.")
201
+ return(invisible(manifest))
202
+ }
203
+
204
+ actual_hashes <- vapply(resolved_paths, compute_sha256, character(1))
205
+ if (!all(actual_hashes == manifest$sha256)) {
206
+ bad_rows <- which(actual_hashes != manifest$sha256)
207
+ stop(
208
+ "Manifest checksum mismatch for: ",
209
+ paste(manifest$path[bad_rows], collapse = ", ")
210
+ )
211
+ }
212
+ }
213
+
214
+ message("Manifest verification passed for ", nrow(manifest), " files.")
215
+ invisible(manifest)
216
+ }
217
+
218
+ verify_bundle <- function(verify_hash = TRUE) {
219
+ root <- set_replication_root(quiet = TRUE)
220
+
221
+ required_dirs <- c(
222
+ "code/lib",
223
+ "data/interim",
224
+ "data/country_regions",
225
+ "results/per_run_csv/Epoch5EarlyStopNewTreatDefLabelS_Run2",
226
+ "results/processed",
227
+ "figures/manuscript",
228
+ "tables",
229
+ "env",
230
+ "manifests"
231
+ )
232
+ required_files <- c(
233
+ "README.md",
234
+ "code/common.R",
235
+ "code/00_verify_bundle.R",
236
+ "code/01_rebuild_paper_outputs.R",
237
+ "code/02_run_main_ate_optional.R",
238
+ "code/03_run_within_unit_robustness.R",
239
+ "code/04_consolidate_results.R",
240
+ "code/05_build_figures_tables.R",
241
+ "data/interim/dhs_5k_confounders.csv",
242
+ "data/interim/dhs_treated_sector_3yr.csv",
243
+ "data/interim/africa_oda_sector_group.csv",
244
+ "results/processed/ICA_xruns_all_vt_emb_3yr_2013.csv",
245
+ "results/processed/wb_vs_ch_sector_scatter_WithinUnitVar.pdf",
246
+ "env/R_packages.txt",
247
+ "env/requirements-image-download.txt",
248
+ "manifests/external_requirements.md"
249
+ )
250
+
251
+ missing_dirs <- required_dirs[!dir.exists(file.path(root, required_dirs))]
252
+ missing_files <- required_files[!file.exists(file.path(root, required_files))]
253
+ if (length(missing_dirs) > 0 || length(missing_files) > 0) {
254
+ problems <- c(
255
+ if (length(missing_dirs) > 0) paste("Missing directories:", paste(missing_dirs, collapse = ", ")),
256
+ if (length(missing_files) > 0) paste("Missing files:", paste(missing_files, collapse = ", "))
257
+ )
258
+ stop(paste(problems, collapse = " | "))
259
+ }
260
+
261
+ expected_run_counts <- c(
262
+ vt_3yr_noX = 99L,
263
+ vt_3yr_onlyFE = 100L,
264
+ vt_3yr_onlyX = 100L,
265
+ vt_3yr_onlyXandFE = 100L,
266
+ vt_3yr_withFE = 100L,
267
+ vt_3yr_withX = 400L,
268
+ vt_3yr_withXandFE = 100L,
269
+ vt_3yr_unitFE = 100L,
270
+ vt_3yr_did = 49L
271
+ )
272
+
273
+ run_root <- bundle_results_root(root)
274
+ actual_run_counts <- vapply(
275
+ names(expected_run_counts),
276
+ function(name) {
277
+ length(list.files(file.path(run_root, name), pattern = "\\.csv$", full.names = TRUE))
278
+ },
279
+ integer(1)
280
+ )
281
+
282
+ if (any(actual_run_counts < expected_run_counts)) {
283
+ bad <- names(actual_run_counts)[actual_run_counts < expected_run_counts]
284
+ stop(
285
+ "Incomplete per-run CSV directories: ",
286
+ paste(
287
+ sprintf("%s (%s < %s)", bad, actual_run_counts[bad], expected_run_counts[bad]),
288
+ collapse = ", "
289
+ )
290
+ )
291
+ }
292
+
293
+ results_processed_n <- length(list.files(bundle_public_results_dir(root), full.names = TRUE))
294
+ if (results_processed_n < 100L) {
295
+ stop("results/processed looks incomplete: found only ", results_processed_n, " files.")
296
+ }
297
+
298
+ manuscript_fig_n <- length(list.files(file.path(root, "figures", "manuscript"), full.names = TRUE))
299
+ if (manuscript_fig_n < 100L) {
300
+ stop("figures/manuscript looks incomplete: found only ", manuscript_fig_n, " files.")
301
+ }
302
+
303
+ verify_manifest_file(
304
+ file.path(root, "manifests", "file_manifest.csv"),
305
+ verify_hash = verify_hash
306
+ )
307
+
308
+ summary <- list(
309
+ root = root,
310
+ per_run_csv_counts = actual_run_counts,
311
+ results_processed_n = results_processed_n,
312
+ manuscript_fig_n = manuscript_fig_n
313
+ )
314
+
315
+ message("Bundle verification passed.")
316
+ invisible(summary)
317
+ }
code/lib/AidDeconfound_Branch.R ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Script: AidDeconfound_Branch.R
2
+ {
3
+ if(!"RUN_MODE" %in% ls()){
4
+ RUN_MODE <- "MAIN" # : Standard analysis (Original submission settings) - uses main tfrecords + same confounder files (BOTH WRITTEN)
5
+ #RUN_MODE <- "ROBUST_NO_NTL" # : Excludes pre-treatment Nighttime Lights (Bias) - uses main tfrecords + same confounder files (BOTH WRITTEN)
6
+ #RUN_MODE <- "ROBUST_BUFFER" # : Increases buffer to 10km (Displacement) - requires own tfrecords + diff confounder files (BOTH WRITTEN)
7
+ #RUN_MODE <- "ROBUST_STRICT" # : Excludes ADM2/Precision 3 projects (Unit of Analysis) - requires own tfrecords + diff confounder files
8
+ }
9
+
10
+ # --- AUTO-CONFIGURATION BASED ON MODE ---
11
+ robust_params <- list()
12
+ if (RUN_MODE == "MAIN") {
13
+ robust_params$exclude_NTL <- FALSE # Done
14
+ robust_params$strict_precision <- FALSE
15
+ robust_params$large_buffer <- FALSE # partial -> reconsider
16
+ robust_params$suffix <- "" # No suffix for main file
17
+ robust_params$RUN_MODE <- "MAIN"
18
+ } else if (RUN_MODE == "ROBUST_NO_NTL") {
19
+ robust_params$exclude_NTL <- TRUE
20
+ robust_params$strict_precision <- FALSE
21
+ robust_params$large_buffer <- FALSE
22
+ robust_params$suffix <- "_NoNTL"
23
+ robust_params$RUN_MODE <- "ROBUST_NO_NTL"
24
+ } else if (RUN_MODE == "ROBUST_STRICT") {
25
+ robust_params$exclude_NTL <- FALSE
26
+ robust_params$strict_precision <- TRUE
27
+ robust_params$large_buffer <- FALSE
28
+ robust_params$suffix <- "_StrictPrec"
29
+ robust_params$RUN_MODE <- "ROBUST_STRICT"
30
+ } else if (RUN_MODE == "ROBUST_BUFFER") {
31
+ robust_params$exclude_NTL <- FALSE
32
+ robust_params$strict_precision <- FALSE
33
+ robust_params$large_buffer <- TRUE # Activates 10km buffer
34
+ robust_params$suffix <- "_LargeBuff"
35
+ robust_params$RUN_MODE <- "ROBUST_BUFFER"
36
+ }
37
+ print(paste0(">>> STARTING RUN MODE: ", RUN_MODE))
38
+ print(paste0(">>> FILE SUFFIX: ", robust_params$suffix))
39
+
40
+ }
code/lib/call_CI_Conf_5k_3yr.R ADDED
@@ -0,0 +1,1575 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ # Script: call_CI_Conf_5k_3yr.R
3
+ # install.packages("~/Documents/causalimages-software/causalimages",repos = NULL, type = "source",force = F)
4
+ # devtools::install_github(repo = "cjerzak/causalimages-software/causalimages")
5
+ # causalimages::BuildBackend()
6
+ # conda activate jax_gpu
7
+ # uv pip install --upgrade tensorflow optax torch transformers pillow tf-keras equinox jmp
8
+ # uv pip install jax==0.5.0
9
+ #
10
+ # call_CI_Conf_5k_3yr.R
11
+ # Desc: Calls Causal Image Confounding over DHS points.
12
+ # Uses three-year composite images, three-year averages of
13
+ # confounders. Caller specifies computer vision backbone parameter.
14
+ library(causalimages); options(error = NULL)
15
+ library(dplyr)
16
+
17
+ replication_root <- getOption("replication.root", default = getwd())
18
+ setwd(replication_root)
19
+
20
+ # key branch parameters
21
+ SaveResultsFolder <- get0("SAVE_RESULTS_FOLDER_OVERRIDE",
22
+ ifnotfound = "per_run_csv/Epoch5EarlyStopNewTreatDefLabelS_Run2")
23
+ ReSaveTFRecords <- get0(
24
+ "RESAVE_TFRECORDS_OVERRIDE",
25
+ ifnotfound = tolower(Sys.getenv("IMAGEDECONFOUND_RESAVE_TFRECORDS",
26
+ unset = "false")) %in% c("1", "true", "yes")
27
+ )
28
+ JustCheckNaiveATEs <- FALSE
29
+ plotResults <- TRUE
30
+ ForceRerunResults <- TRUE
31
+
32
+ #conda_env <- sample( c("CausalImagesEnv" ,"jax_gpu"),prob=c(0.75,0.25),size=1)
33
+ conda_env <- get0("CONDA_ENV_OVERRIDE",
34
+ ifnotfound = Sys.getenv("IMAGEDECONFOUND_CONDA_ENV",
35
+ unset = "CausalImagesEnv")) # (uses CPU)
36
+ #conda_env <- "jax_gpu" # 0.5s
37
+ #conda_env <- "jax_cpu" # 0.9s
38
+
39
+ # Define memory to allocate
40
+ work_root <- Sys.getenv("WORK", unset = "")
41
+ if(nzchar(work_root) &&
42
+ !dir.exists(file.path(work_root, "ImageDeconfoundAid")) &&
43
+ conda_env=="jax_gpu"){
44
+ Sys.setenv(
45
+ XLA_PYTHON_CLIENT_PREALLOCATE = "true" ,
46
+ XLA_PYTHON_CLIENT_MEM_FRACTION = as.character(0.90 / 5),
47
+ XLA_PYTHON_CLIENT_ALLOCATOR = "platform" # Helps on Metal to reduce fragmentation
48
+ )
49
+ }
50
+ #rm(list=ls()[!ls() %in% (Keeps <- c("t0","KeepObjectsAcrossAnalysisStrings","conda_env", "PrepData","RunAnalysis","AnalyzeResults"))] )
51
+ source("./code/lib/call_CI_Conf_5k_3yr_Helpers.R")
52
+
53
+ # Create all parameter combinations based on bash script
54
+ default_x_approach_options <- c("noX", "onlyX", "onlyFE", "onlyXandFE",
55
+ "withX", "withFE", "withXandFE")
56
+ X_approach_options <- get0("X_APPROACH_OPTIONS_OVERRIDE",
57
+ ifnotfound = default_x_approach_options)
58
+ if(ReSaveTFRecords){ X_approach_options <- c("noX") }
59
+
60
+ tfrecord_home <- normalizePath(
61
+ get0("TFRECORD_HOME_OVERRIDE",
62
+ ifnotfound = Sys.getenv("IMAGEDECONFOUND_TFRECORD_HOME",
63
+ unset = "./external_artifacts/tfrecords")),
64
+ winslash = "/",
65
+ mustWork = FALSE
66
+ )
67
+ dir.create(tfrecord_home, recursive = TRUE, showWarnings = FALSE)
68
+
69
+ # key modeling parameters
70
+ earlyStopThreshold <- TRUE
71
+ kFolds = 2L
72
+ nSGD <- "dynamic"; MAX_CLASS_EPOCHS <- 5L
73
+ #nSGD <- 100L
74
+ batchSize <- 32L
75
+ if(abs(get_total_ram_gb() - 32)<2){ batchSize <- 24L }
76
+ if(abs(get_total_ram_gb() - 16)<2){ batchSize <- 12L }
77
+ learningRateMax = 5*10^(-3)*batchSize/512
78
+ nDepth_ImageRep = 8L
79
+ nWidth_ImageRep = 256L
80
+ dropoutRate = 0.1
81
+ droppathRate = 0.1
82
+ useTrainingPertubations <- FALSE
83
+ nonLinearScaler = NULL
84
+
85
+ args <- commandArgs(trailingOnly = TRUE)
86
+ {
87
+ fund_sect_params <- c("ch_430", "ch_520", "ch_700", "ch_140", "ch_230", "ch_220",
88
+ "ch_310", "ch_160", "wb_330", "wb_410", "ch_110", "ch_210",
89
+ "wb_240", "wb_220", "ch_150", "ch_120", "wb_320", "wb_230",
90
+ "wb_110", "wb_120", "wb_310", "wb_160", "wb_140", "wb_210", "wb_150")
91
+
92
+ # Create combinations for both R1 and R2
93
+ COMBS_MAT <- {expand.grid(
94
+ X_approach = X_approach_options,
95
+ vision_backbone = "vt",
96
+
97
+ fund_sect_param = fund_sect_params,
98
+ #fund_sect_param = "wb_160", # test case
99
+
100
+ RUN_MODE = c("MAIN","ROBUST_NO_NTL","ROBUST_BUFFER","ROBUST_STRICT"), # ALL
101
+ #RUN_MODE = c("MAIN","ROBUST_BUFFER","ROBUST_STRICT"), # just new tfrecords
102
+ #RUN_MODE = "MAIN", # just run specific analysis
103
+
104
+ stringsAsFactors = FALSE
105
+ )}
106
+ head(COMBS_MAT)
107
+ print(dim(COMBS_MAT))
108
+
109
+ # order dataset
110
+ #COMBS_MAT <- COMBS_MAT[order(apply(COMBS_MAT, 1, function(x){ rlang::hash(paste(x, collapse = "_")) })),]
111
+ COMBS_MAT <- COMBS_MAT[order( grepl(COMBS_MAT$X_approach, pattern="only"),decreasing=T ),]
112
+ which( grepl(COMBS_MAT$X_approach,pattern="only")) # 1:75
113
+
114
+ # Extract the specific combination
115
+ COMBS_MAT$ReSaveTFRecords <- ReSaveTFRecords
116
+ if(length(args) == 0 && isTRUE(get0("REQUIRE_EXPLICIT_OUTER_SEQ", ifnotfound = FALSE))){
117
+ stop("No outer-sequence argument supplied. Pass one or more COMBS_MAT row indices to run this script.")
118
+ }
119
+ if(length(args) == 0){
120
+ #OUTER_SEQ <- 1
121
+ OUTER_SEQ <- 1:nrow(COMBS_MAT)
122
+ #OUTER_SEQ <- which(COMBS_MAT$X_approach=="onlyXandFE")[1]
123
+ }
124
+ if(length(args) != 0){
125
+ pdf(file = NULL);options(device = NULL) # All subsequent base plots go to null device
126
+ OUTER_SEQ <- as.integer(args[1])
127
+ }
128
+
129
+ for(OUTER_ in OUTER_SEQ){
130
+ selected_combo <- COMBS_MAT[OUTER_, ]
131
+
132
+ # source the analysis robustnests branch - depends on COMBS_MAT
133
+ RUN_MODE <- as.character(selected_combo["RUN_MODE"])
134
+ source("./code/lib/AidDeconfound_Branch.R")
135
+ data_suffix_model_input <- robust_params$suffix
136
+ if( robust_params$RUN_MODE %in% c("MAIN","ROBUST_NO_NTL") ){
137
+ data_suffix_model_input <- ""
138
+ }
139
+
140
+ # Set the variables as expected by the rest of the script
141
+ fund_sect_param <- selected_combo$fund_sect_param
142
+ time_approach <- "3yr" # Fixed as per script defaults
143
+ vision_backbone <- selected_combo$vision_backbone
144
+ X_approach <- selected_combo$X_approach
145
+ ReSaveTFRecords <- selected_combo$ReSaveTFRecords # Fixed as per script defaults
146
+ run <- paste0(vision_backbone, "_", time_approach, "_", X_approach)
147
+
148
+ # set seed
149
+ set.seed(as.numeric(as.character(unlist(lapply(strsplit(fund_sect_param,split="_"),function(l_){l_[2]})))),
150
+ kind="Wichmann-Hill");
151
+
152
+ saveName <- paste(fund_sect_param,
153
+ time_approach,
154
+ vision_backbone,
155
+ X_approach, sep = "_")
156
+
157
+ XForceModal <- FALSE; if(X_approach %in% c("onlyX","onlyFE","onlyXandFE")){
158
+ XForceModal <- TRUE; nDepth_ImageRep <- 1L
159
+ }
160
+
161
+ ################################################################################
162
+ # Initial setup, parameter processing, reading input files
163
+ ################################################################################
164
+ results_dir <- paste0("./results/",SaveResultsFolder, "/", run,"/")
165
+ dir.create(paste0("./results/",SaveResultsFolder), recursive = TRUE, showWarnings = FALSE)
166
+ #create the results directory for this run if it doesn't exist already
167
+ if (!dir.exists(results_dir)) { dir.create(results_dir) }
168
+ sector_param <- sub(".*_(\\d+).*", "\\1", fund_sect_param)
169
+ funder_param <- sub("(wb|ch).*", "\\1", fund_sect_param)
170
+ other_funder <- ifelse(funder_param=="wb","ch","wb")
171
+
172
+ ##### read confounder and treatment data from files
173
+ dhs_confounders_df <- read.csv(sprintf("./data/interim/dhs_5k_confounders%s.csv",data_suffix_model_input)) %>%
174
+ select(-year) %>% #remove survey year column that could be confused with oda year
175
+ mutate(across(starts_with("log_ch_loan_proj_n"),as.numeric)) #ensure numeric not integer
176
+
177
+ #get list of all dhs_id's and their iso3 for use below
178
+ dhs_iso3_df <- dhs_confounders_df %>%
179
+ distinct(dhs_id,iso3)
180
+
181
+ #get treated by this funder
182
+ # sort(table(paste0(dhs_t_df$funder,"_",dhs_t_df$sector)))
183
+ dhs_t_df <- read.csv(sprintf("./data/interim/dhs_treated_sector_3yr%s.csv",data_suffix_model_input)) %>%
184
+ filter(sector==sector_param & funder==funder_param & year_group!="2014:2016") %>%
185
+ #exclude DHS points where confounder data not available
186
+ inner_join(dhs_confounders_df %>%
187
+ select(dhs_id, ID_adm2), by = join_by(dhs_id))
188
+
189
+ #get logged count of projects in other sectors for each dhs point and year group
190
+ dhs_other_sect_n_df <- read.csv(sprintf("./data/interim/dhs_treated_sector_3yr%s.csv",data_suffix_model_input)) %>%
191
+ filter(sector!=sector_param & funder==funder_param &
192
+ #exclude DHS points where confounder data not available
193
+ dhs_id %in% dhs_confounders_df$dhs_id & year_group!="2014:2016") %>%
194
+ group_by(dhs_id, year_group) %>%
195
+ summarize(other_sect_n=sum(proj_count),.groups="drop") %>%
196
+ mutate(log_other_sect_n=log(other_sect_n + 1)) %>%
197
+ ungroup() %>%
198
+ select(-other_sect_n)
199
+
200
+ #get logged count of the other funder's simultaneous projects
201
+ dhs_treated_other_funder_n_df <- read.csv(sprintf("./data/interim/dhs_treated_sector_3yr%s.csv",data_suffix_model_input)) %>%
202
+ filter(funder==other_funder &
203
+ #exclude DHS points where confounder data not available
204
+ dhs_id %in% dhs_confounders_df$dhs_id & year_group!="2014:2016") %>%
205
+ group_by(dhs_id, year_group) %>%
206
+ summarize(treated_other_funder_n=sum(proj_count),.groups="drop") %>%
207
+ mutate(log_treated_other_funder_n=log(treated_other_funder_n + 1)) %>%
208
+ ungroup() %>%
209
+ select(-treated_other_funder_n)
210
+
211
+ #identify countries where funder is operating in this sector
212
+ funder_sector_iso3 <- dhs_confounders_df %>%
213
+ filter(dhs_id %in% (dhs_t_df %>% pull(dhs_id))) %>%
214
+ distinct(iso3) %>% pull(iso3)
215
+
216
+ #identify all dhs_points in countries where funder is operating in this sector
217
+ dhs_in_operating_countries <- dhs_iso3_df %>%
218
+ filter(iso3 %in% funder_sector_iso3) %>%
219
+ pull(dhs_id)
220
+
221
+ #construct 3yr controls, limiting to countries where funder operated in sector
222
+ year_group_v <- c('2002:2004', '2005:2007', '2008:2010', '2011:2013') #, '2014:2016')
223
+
224
+ #generate dataframe of all dhs points for all year groups in operating countries
225
+ all_t_c_df <- data.frame(expand.grid(year_group = year_group_v,
226
+ dhs_id = dhs_in_operating_countries))
227
+
228
+ #construct controls
229
+ dhs_c_df <- all_t_c_df %>%
230
+ #exclude dhs_points treated in each year_group
231
+ anti_join(dhs_t_df,by=c("dhs_id","year_group")) %>%
232
+ #exclude DHS points where confounder data not available, get ID_adm2
233
+ inner_join(dhs_confounders_df %>%
234
+ select(dhs_id, ID_adm2), by = join_by(dhs_id))
235
+
236
+ #get neighbor project counts for spillover effects
237
+ adm2_adjacent_3yr_treat_count_df <- read.csv(sprintf("./data/interim/adm2_adjacent_3yr_treat_count%s.csv",data_suffix_model_input)) %>%
238
+ filter(year_group!="2014:2016")
239
+
240
+ #define variable order and names for boxplots and dropped cols variables
241
+ var_order_all <- c("iwi_est_post_oda","log_pc_nl_pre_oda","log_avg_pop_dens",
242
+ "log_avg_min_to_city",
243
+ "log_dist_km_to_gold","log_dist_km_to_gems",
244
+ "log_dist_km_to_dia","log_dist_km_to_petro",
245
+ "leader_birthplace","log_ch_loan_proj_n",
246
+ "log_3yr_pre_conflict_deaths","log_disasters",
247
+ "election_year","unsc_aligned_us","unsc_non_aligned_us",
248
+ "country_gini",
249
+ "corruption_control", "gov_effectiveness", "political_stability",
250
+ "reg_quality", "rule_of_law","voice_accountability",
251
+ "landsat578","log_treated_other_funder_n","log_other_sect_n",
252
+ "log_total_neighbor_projs")
253
+ var_labels_all <- c("Wealth","Nightlights per cap", "Pop Density",
254
+ "Minutes to City", "Dist to Gold",
255
+ "Dist to Gems", "Dist to Diam",
256
+ "Dist to Oil", "Leader birthplace", "China Loan Projs",
257
+ "Conflict deaths", "Natural Disasters", "Election year",
258
+ "UNSC US Aligned","UNSC Non-US Align", "Country gini",
259
+ "Cntry Cntrl Corruption", "Cntry Gov Effective",
260
+ "Cntry Political Stability","Cntry Reg Quality",
261
+ "Cntry Rule of Law","Cntry Voice/Account",
262
+ "Landsat 5,7,& 8","Other Funder Treat n","Other Sector Proj n",
263
+ "Adj ADM2 Proj n")
264
+
265
+ ################################################################################
266
+ # Function called by AnalyzeImageConfounding to read images
267
+ ################################################################################
268
+ if(FALSE){ # sanity check
269
+ setwd(getOption("replication.root", default = getwd())); options(error = NULL)
270
+ dhs_confounders_df <- read.csv(sprintf("./data/interim/dhs_5k_confounders%s.csv",data_suffix_model_input))
271
+ analyzeThis_ <- "angola_2006/00000.tif"
272
+ i_<-grep(dhs_confounders_df$image_file_5k_3yr,pattern=analyzeThis_)
273
+ c(dhs_confounders_df$lat[i_],dhs_confounders_df$lon[i_])
274
+ im <- terra::rast(file.path(
275
+ get0("IMAGE_ROOT_OVERRIDE",
276
+ ifnotfound = Sys.getenv("IMAGEDECONFOUND_IMAGE_ROOT",
277
+ unset = "./external_artifacts/images/dhs_tifs_5k_3yr")),
278
+ analyzeThis_
279
+ ))
280
+ band_ <- sample(20,1)
281
+ plot(unlist(lapply(im,function(l_) {sd(matrix(l_))})))
282
+ which(unlist(lapply(im,function(l_) {sd(matrix(l_))}))==0)
283
+ causalimages::image2(matrix(im[[band_]],nrow =175,ncol=174,byrow=T))
284
+ }
285
+
286
+ acquireImageRepFromDisk_orig <- function(keys, training = FALSE) {
287
+ #imageWidth <- imageHeight <- 167L
288
+ imageWidth <- imageHeight <- 164L
289
+ NBANDS <- 5L
290
+ nkeys <- length(keys)
291
+
292
+ # Pre‐allocate: [n_images × H × W × bands]
293
+ imgs_array <- array(0, dim = c(nkeys, imageHeight, imageWidth, NBANDS))
294
+
295
+ for (idx in seq_along(keys)) {
296
+ key_ <- keys[idx]
297
+
298
+ # extract the "2002:2004"‐style suffix and the .tif path
299
+ oda_year_group <- sub(".*\\.tif(.*)", "\\1", key_)
300
+ image_file <- sub("(.*\\.tif).*", "\\1", key_)
301
+
302
+ # choose which layers to pull
303
+ nIncrement <- 5
304
+ bands_to_select <- case_when(
305
+ oda_year_group == '2002:2004' ~ seq(1, nIncrement),
306
+ oda_year_group == '2005:2007' ~ seq(nIncrement + 1, 2 * nIncrement),
307
+ oda_year_group == '2008:2010' ~ seq(2 * nIncrement + 1, 3 * nIncrement),
308
+ oda_year_group == '2011:2013' ~ seq(3 * nIncrement + 1, 4 * nIncrement),
309
+ oda_year_group == '2014:2016' ~ seq(4 * nIncrement + 1, 5 * nIncrement)
310
+ )
311
+
312
+ for (b in seq_len(NBANDS)) {
313
+ # print(c(key_,b))
314
+ band_num <- bands_to_select[b]
315
+ layer_name <- paste0(gsub(".*/(\\d{5})\\.tif$", "\\1", image_file),"_", band_num)
316
+ ras <- terra::rast(
317
+ gsub(image_file,pattern = "_c1_",replace="_"),
318
+ lyrs = band_num)
319
+ TifDims <- dim(ras)[1:2]
320
+ vals <- c(terra::values(ras)) / 0.0001 # apply scale factor
321
+ # reshape into H×W matrix (row‐major)
322
+ img_mat <- matrix(vals, nrow = TifDims[1], ncol = TifDims[2], byrow = TRUE)
323
+ #img_mat <- img_mat[1:imageWidth,1:imageHeight]
324
+ # causalimages::image2(img_mat)# sanity check
325
+ imgs_array[idx,
326
+ 1:min(c(imageWidth,TifDims[1])),
327
+ 1:min(c(imageWidth,TifDims[2])),
328
+ b] <- img_mat[1:min(c(imageWidth,TifDims[1])),
329
+ 1:min(c(imageWidth,TifDims[2]))]
330
+ }
331
+ }
332
+
333
+ return( imgs_array )
334
+ }
335
+ acquireImageRepFromDisk <- function(keys, image_size = 164L, NBANDS = 5L, scale_by = 0.0001) {
336
+ imageWidth <- imageHeight <- as.integer(image_size)
337
+ nkeys <- length(keys)
338
+ imgs_array <- array(0, dim = c(nkeys, imageHeight, imageWidth, NBANDS))
339
+ image_root <- normalizePath(
340
+ get0("IMAGE_ROOT_OVERRIDE",
341
+ ifnotfound = Sys.getenv("IMAGEDECONFOUND_IMAGE_ROOT",
342
+ unset = "./external_artifacts/images/dhs_tifs_5k_3yr")),
343
+ winslash = "/",
344
+ mustWork = FALSE
345
+ )
346
+
347
+ year_groups <- c("2002:2004","2005:2007","2008:2010","2011:2013","2014:2016")
348
+ nIncrement <- 5L
349
+
350
+ for (idx in seq_len(nkeys)) {
351
+ key_ <- keys[[idx]]
352
+ oda_year_group <- sub(".*\\.tif(.*)", "\\1", key_)
353
+ image_file <- sub("(.*\\.tif).*", "\\1", key_)
354
+ src_file <- file.path(image_root,
355
+ gsub(pattern = "_c1_", replacement = "_", x = image_file))
356
+
357
+ grp_idx <- match(oda_year_group, year_groups)
358
+ bands_all <- seq.int((grp_idx - 1L) * nIncrement + 1L, grp_idx * nIncrement)
359
+ bands_to_select <- bands_all[seq_len(NBANDS)]
360
+
361
+ ras <- terra::rast(src_file, lyrs = bands_to_select) # read all bands at once
362
+ dims <- dim(ras) # rows, cols, nlyr
363
+ tif_h <- dims[1]; tif_w <- dims[2]
364
+ H <- min(imageHeight, tif_h); W <- min(imageWidth, tif_w)
365
+
366
+ # values() returns an ncell × NBANDS matrix when nlyr > 1
367
+ V <- as.matrix(terra::values(ras)) / scale_by
368
+ for (b in seq_len(NBANDS)) {
369
+ mat <- matrix(V[, b], nrow = tif_h, ncol = tif_w, byrow = TRUE)
370
+ imgs_array[idx, seq_len(H), seq_len(W), b] <- mat[seq_len(H), seq_len(W)]
371
+ }
372
+ }
373
+
374
+ imgs_array
375
+ }
376
+
377
+ ################################################################################
378
+ # Set tabular confounding variables based on start year
379
+ ################################################################################
380
+ treat_count <- nrow(dhs_t_df)
381
+ control_count <- nrow(dhs_c_df)
382
+
383
+ if(!file.exists(paste0(results_dir,
384
+ "ICA_",
385
+ fund_sect_param, "_",
386
+ run,
387
+ "_iFINAL",
388
+ robust_params$suffix,
389
+ ".csv")) | ForceRerunResults){
390
+ if (treat_count < 80) {
391
+ print(treat_count)
392
+ print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
393
+ " Skipping ",fund_sect_param," because fewer than threshold treated (",
394
+ treat_count,")"))
395
+ next
396
+ } else if (control_count == 0) {
397
+ print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
398
+ " Skipping ",fund_sect_param," because no controls"))
399
+ next
400
+ } else {
401
+ print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
402
+ " Processing ",fund_sect_param,
403
+ ", treat n:",treat_count,
404
+ ", control n: ",control_count,
405
+ ", run: ",run,
406
+ ", nSGD: ",nSGD,
407
+ ", backbone: ",vision_backbone
408
+ ))
409
+
410
+ ##############################################################################
411
+ # combine treated & controls into same dataframe, join with confounders,
412
+ # and adjust to be appropriate for start year
413
+ ##############################################################################
414
+ obs_year_group_df <- rbind(
415
+ dhs_t_df %>%
416
+ mutate(treated=1) %>%
417
+ select(dhs_id,year_group,treated),
418
+ dhs_c_df %>%
419
+ mutate(treated=0) %>%
420
+ select(dhs_id,year_group,treated)
421
+ ) %>%
422
+ left_join(dhs_confounders_df,by="dhs_id") %>%
423
+ #get count of projects in neighboring adm2s for the period
424
+ left_join(adm2_adjacent_3yr_treat_count_df,by=join_by("ID_adm2","year_group"),
425
+ multiple="all") %>%
426
+ #replace NAs with 0s for dhs points without neighboring projects
427
+ mutate(log_total_neighbor_projs=if_else(is.na(log_total_neighbor_projs),
428
+ 0,log_total_neighbor_projs)) %>%
429
+ #get logged count of funder's projs in other sectors for both treated and controls
430
+ left_join(dhs_other_sect_n_df,by=c("dhs_id","year_group")) %>%
431
+ #replace NAs with 0s for dhs points untreated in other sectors
432
+ mutate(log_other_sect_n=if_else(is.na(log_other_sect_n),0,log_other_sect_n)) %>%
433
+ #get logged count of other funder's projs for both treated and controls
434
+ left_join(dhs_treated_other_funder_n_df,by=c("dhs_id","year_group")) %>%
435
+ #replace NAs with 0s for dhs points untreated by the other funder
436
+ mutate(log_treated_other_funder_n = if_else(is.na(log_treated_other_funder_n),
437
+ 0,log_treated_other_funder_n)) %>%
438
+ mutate(
439
+ iwi_est_post_oda = case_when(
440
+ year_group == '2002:2004' ~ iwi_2005_2007_est,
441
+ year_group == '2005:2007' ~ iwi_2008_2010_est,
442
+ year_group == '2008:2010' ~ iwi_2011_2013_est,
443
+ year_group == '2011:2013' ~ iwi_2014_2016_est,
444
+ year_group == '2014:2016' ~ iwi_2017_2019_est),
445
+ log_dist_km_to_gold = log_dist_km_to_gold_2001,
446
+ log_dist_km_to_petro = case_when(
447
+ year_group == '2002:2004' ~ log_dist_km_to_petro_1999_2001,
448
+ year_group == '2005:2007' ~ log_dist_km_to_petro_2002_2004,
449
+ year_group == '2008:2010' ~ log_dist_km_to_petro_2005_2007,
450
+ year_group == '2011:2013' ~ log_dist_km_to_petro_2008_2010,
451
+ year_group == '2014:2016' ~ log_dist_km_to_petro_2011_2013),
452
+ log_pc_nl_pre_oda = case_when(
453
+ year_group == '2002:2004' ~ log_pc_nl_2000_2001,
454
+ year_group == '2005:2007' ~ log_pc_nl_2002_2004,
455
+ year_group == '2008:2010' ~ log_pc_nl_2005_2007,
456
+ year_group == '2011:2013' ~ log_pc_nl_2008_2010,
457
+ year_group == '2014:2016' ~ log_pc_nl_2011_2013),
458
+ log_avg_pop_dens = case_when(
459
+ year_group == '2002:2004' ~ log_avg_pop_dens_2000_2001,
460
+ year_group == '2005:2007' ~ log_avg_pop_dens_2002_2004,
461
+ year_group == '2008:2010' ~ log_avg_pop_dens_2005_2007,
462
+ year_group == '2011:2013' ~ log_avg_pop_dens_2008_2010,
463
+ year_group == '2014:2016' ~ log_avg_pop_dens_2011_2013),
464
+ leader_birthplace = case_when(
465
+ year_group == '2002:2004' ~ leader_1999_2001,
466
+ year_group == '2005:2007' ~ leader_2002_2004,
467
+ year_group == '2008:2010' ~ leader_2005_2007,
468
+ year_group == '2011:2013' ~ leader_2008_2010,
469
+ year_group == '2014:2016' ~ leader_2011_2013),
470
+ log_3yr_pre_conflict_deaths = case_when(
471
+ year_group == '2002:2004' ~ log_deaths1999_2001,
472
+ year_group == '2005:2007' ~ log_deaths2002_2004,
473
+ year_group == '2008:2010' ~ log_deaths2005_2007,
474
+ year_group == '2011:2013' ~ log_deaths2008_2010,
475
+ year_group == '2014:2016' ~ log_deaths2011_2013),
476
+ log_disasters = case_when(
477
+ year_group == '2002:2004' ~ log_disasters1999_2001,
478
+ year_group == '2005:2007' ~ log_disasters2002_2004,
479
+ year_group == '2008:2010' ~ log_disasters2005_2007,
480
+ year_group == '2011:2013' ~ log_disasters2008_2010,
481
+ year_group == '2014:2016' ~ log_disasters2011_2013),
482
+ log_ch_loan_proj_n = as.numeric(case_when(
483
+ year_group == '2002:2004' ~ log_ch_loan_proj_n_2002_2004,
484
+ year_group == '2005:2007' ~ log_ch_loan_proj_n_2005_2007,
485
+ year_group == '2008:2010' ~ log_ch_loan_proj_n_2008_2010,
486
+ year_group == '2011:2013' ~ log_ch_loan_proj_n_2011_2013,
487
+ year_group == '2014:2016' ~ log_ch_loan_proj_n_2014_2016)),
488
+ #set indicator variables for the combination of satellite images in pre-project images
489
+ #Landsat 5 only in images from 1990:1998, excluded here because of missing data
490
+ #Landsat 5&7 in images from 1999:2010 - won't include this column to avoid collinearity
491
+ #Landsat 5,7, & 8 in images from 2011:2013
492
+ landsat578 = if_else(year_group %in% c('2011:2013','2014:2016'),1,0)
493
+ #Landsat 7&8 in images from 2014:2019 - we aren't using any of these
494
+ )
495
+
496
+ #join to country-level parameters, which are year specific, and construct year group data
497
+ country_confounders_df <- read.csv(sprintf("./data/interim/country_confounders%s.csv",data_suffix_model_input)) %>%
498
+ #exclude countries where we don't have dhs points
499
+ filter(iso3 %in% dhs_iso3_df$iso3) %>%
500
+ select(-country) %>%
501
+ #set year group to pre-treatment 3-year span for join below
502
+ mutate(year_group = case_when(
503
+ year %in% 1999:2001 ~ '2002:2004',
504
+ year %in% 2002:2004 ~ '2005:2007',
505
+ year %in% 2005:2007 ~ '2008:2010',
506
+ year %in% 2008:2010 ~ '2011:2013',
507
+ year %in% 2011:2013 ~ '2014:2016')) %>%
508
+ group_by(iso3,year_group) %>%
509
+ #calculate the max for binary variables (three-year group 1 if any year was 1)
510
+ summarize(across(c("election_year","unsc_aligned_us","unsc_non_aligned_us"),
511
+ ~max(., na.rm = TRUE)),
512
+ #calculate a mean for each year group for each continuous variable
513
+ across(c("country_gini","polity2","log_gdp_per_cap_USD2015","corruption_control",
514
+ "gov_effectiveness","political_stability","reg_quality",
515
+ "rule_of_law","voice_accountability"),
516
+ ~mean(., na.rm = TRUE))) %>%
517
+ ungroup()
518
+
519
+ run_df <- obs_year_group_df %>%
520
+ left_join(country_confounders_df,
521
+ by=c("iso3", "year_group"))
522
+
523
+ #create input_df and write to file
524
+ pre_shuffle_df <- run_df %>%
525
+ select(dhs_id, country, iso3, ID_adm2, lat, lon, treated, log_treated_other_funder_n,
526
+ log_other_sect_n, year_group, image_file_5k_3yr, iwi_est_post_oda,
527
+ log_pc_nl_pre_oda, log_avg_min_to_city, log_avg_pop_dens,
528
+ log_3yr_pre_conflict_deaths, log_disasters, log_ch_loan_proj_n,
529
+ leader_birthplace, log_dist_km_to_gold, log_dist_km_to_gems,
530
+ log_dist_km_to_dia, log_dist_km_to_petro, election_year,
531
+ unsc_aligned_us, unsc_non_aligned_us,country_gini,
532
+ corruption_control,gov_effectiveness, political_stability,
533
+ reg_quality, rule_of_law, voice_accountability, landsat578,
534
+ log_total_neighbor_projs) %>%
535
+ rename(adm2 = ID_adm2) %>%
536
+ #extract first year of group to use in function
537
+ mutate(first_year_group = as.integer(sub("^(\\d{4}).*", "\\1",year_group)))
538
+
539
+ #shuffle data to reorder it before use; set.seed call makes it reproducible
540
+ set.seed(sector_param,kind="Wichmann-Hill");
541
+ input_df <- pre_shuffle_df[sample(x=1:nrow(pre_shuffle_df),size=nrow(pre_shuffle_df),replace=FALSE),]
542
+
543
+ if ( robust_params$large_buffer ) {
544
+ # --- ROBUSTNESS: coarsen outcome to ~13.4km grid when large_buffer is on ---
545
+ message(">>> ROBUSTNESS CHECK: Aggregating IWI_est_post_oda to ~13.4km outcome grid")
546
+
547
+ # Always keep the original 5km outcome around, so we never re-aggregate a
548
+ # previously aggregated value if this script is re-run.
549
+ if (!"iwi_est_post_oda_5k" %in% names(input_df)) {
550
+ input_df$iwi_est_post_oda_5k <- input_df$iwi_est_post_oda
551
+ }
552
+ base_iwi <- input_df$iwi_est_post_oda_5k
553
+
554
+ # Build sf object in a metric CRS for distance-based neighbors
555
+ dhs_sf <- sf::st_as_sf(input_df,
556
+ coords = c("lon", "lat"),
557
+ crs = 4326)
558
+ # Any metric CRS is fine; 3857 keeps it simple
559
+ dhs_sf <- sf::st_transform(dhs_sf, 3857)
560
+
561
+ # Neighbors within ~6.7km (to approximate a 2x2 grid of 6.7km pixels ≈ 13.4km)
562
+ nb_list <- sf::st_is_within_distance(dhs_sf, dhs_sf, dist = 6700)
563
+ # nb_list <- nngeo::st_nn(dhs_sf, dhs_sf, k = 5, returnDist = FALSE, progress = FALSE) # alt option based on nearest neighors
564
+
565
+ # Average IWI across each neighborhood (including self)
566
+ iwi_coarse <- vapply(
567
+ nb_list,
568
+ FUN.VALUE = numeric(1),
569
+ FUN = function(idx) mean(base_iwi[idx], na.rm = TRUE)
570
+ )
571
+
572
+ # Overwrite the outcome used downstream; everything else (conf_matrix, plots, etc.)
573
+ # now sees the coarser 13.4km outcome.
574
+ input_df$iwi_est_post_oda <- iwi_coarse
575
+ }
576
+
577
+ write.csv(input_df, paste0("./data/interim/input_",
578
+ run,"_",fund_sect_param,
579
+ robust_params$suffix,
580
+ ".csv"),row.names = FALSE)
581
+
582
+ if (nrow(input_df[!complete.cases(input_df),]) > 0) {
583
+ print(paste0("Stopping because incomplete cases. See ./data/interim/input_",
584
+ run,"_",fund_sect_param,robust_params$suffix,".csv"))
585
+ } else {
586
+ conf_matrix <- data.frame(
587
+ "first_year_group" =input_df$first_year_group - 2001,
588
+
589
+ #"landsat578" =input_df$landsat578, #pre-treat image
590
+ "log_total_neighbor_projs" =input_df$log_total_neighbor_projs, #neighbor ADM2s
591
+
592
+ "log_pc_nl_pre_oda" =input_df$log_pc_nl_pre_oda, #scene level
593
+ "log_avg_min_to_city" =input_df$log_avg_min_to_city, #scene level
594
+ "log_avg_pop_dens" =input_df$log_avg_pop_dens, #scene level
595
+ "log_dist_km_to_gold" =input_df$log_dist_km_to_gold, #scene level
596
+ "log_dist_km_to_gems" =input_df$log_dist_km_to_gems, #scene level
597
+ "log_dist_km_to_dia" =input_df$log_dist_km_to_dia, #scene level
598
+ "log_dist_km_to_petro" =input_df$log_dist_km_to_petro, #scene level
599
+
600
+ "log_treated_other_funder_n" =input_df$log_treated_other_funder_n, #inherited from ADM2
601
+ "log_ch_loan_proj_n" =input_df$log_ch_loan_proj_n, #inherited from ADM1, ADM2
602
+ "log_other_sect_n" =input_df$log_other_sect_n, #inherited from ADM2
603
+ "log_3yr_pre_conflict_deaths"=input_df$log_3yr_pre_conflict_deaths, #inherited from ADM1
604
+ "log_disasters" =input_df$log_disasters, #inherited from ADM1,2,or3
605
+ "leader_birthplace" =input_df$leader_birthplace, #inherited from ADM1
606
+
607
+ "election_year" =input_df$election_year, #country level
608
+ "unsc_aligned_us" =input_df$unsc_aligned_us, #country level
609
+ "unsc_non_aligned_us" =input_df$unsc_non_aligned_us, #country level
610
+ "country_gini" =input_df$country_gini, #country level
611
+ "corruption_control" =input_df$corruption_control, #country level
612
+ "gov_effectiveness" =input_df$gov_effectiveness, #country level
613
+ "political_stability" =input_df$political_stability, #country level
614
+ "reg_quality" =input_df$reg_quality, #country level
615
+ "rule_of_law" =input_df$rule_of_law, #country level
616
+ "voice_accountability" =input_df$voice_accountability #country level
617
+ )
618
+ # summary(lm(input_df$treated~as.matrix(conf_matrix)))
619
+ # add multiple columns for adm2 fixed effects variables
620
+ # conf_matrix <- cbind(as.matrix(conf_matrix, model.matrix(~ adm2 - 1, input_df)))
621
+ # all(row.names(conf_matrix) == row.names(input_df))
622
+
623
+ # conf_matrix <-
624
+ # as.matrix(data.frame(
625
+ # "first_year_group" =input_df$first_year_group - 2001,
626
+ # #"first_year_group_squared" =(input_df$first_year_group - 2001)^2,
627
+ # "log_pc_nl_pre_oda" =input_df$log_pc_nl_pre_oda, #scene level
628
+ # "log_avg_min_to_city" =input_df$log_avg_min_to_city, #scene level
629
+ # "log_avg_pop_dens" =input_df$log_avg_pop_dens, #scene level
630
+ # "log_dist_km_to_gold" =input_df$log_dist_km_to_gold, #scene level
631
+ # "log_dist_km_to_gems" =input_df$log_dist_km_to_gems, #scene level
632
+ # "log_dist_km_to_dia" =input_df$log_dist_km_to_dia, #scene level
633
+ # "log_dist_km_to_petro" =input_df$log_dist_km_to_petro, #scene level
634
+ # "log_treated_other_funder_n" =input_df$log_treated_other_funder_n, #inherited from ADM2
635
+ # "log_ch_loan_proj_n" =input_df$log_ch_loan_proj_n, #inherited from ADM1, ADM2
636
+ # "log_other_sect_n" =input_df$log_other_sect_n, #inherited from ADM2
637
+ # "log_3yr_pre_conflict_deaths"=input_df$log_3yr_pre_conflict_deaths, #inherited from ADM1
638
+ # "log_disasters" =input_df$log_disasters, #inherited from ADM1,2,or3
639
+ # "leader_birthplace" =input_df$leader_birthplace, #inherited from ADM1
640
+ # "election_year" =input_df$election_year, #country level
641
+ # "unsc_aligned_us" =input_df$unsc_aligned_us, #country level
642
+ # "unsc_non_aligned_us" =input_df$unsc_non_aligned_us, #country level
643
+ # "country_gini" =input_df$country_gini, #country level
644
+ # "corruption_control" =input_df$corruption_control, #country level
645
+ # "gov_effectiveness" =input_df$gov_effectiveness, #country level
646
+ # "political_stability" =input_df$political_stability, #country level
647
+ # "reg_quality" =input_df$reg_quality, #country level
648
+ # "rule_of_law" =input_df$rule_of_law, #country level
649
+ # "voice_accountability" =input_df$voice_accountability, #country level
650
+ # "landsat578" =input_df$landsat578, #pre-treat image
651
+ # "log_total_neighbor_projs" =input_df$log_total_neighbor_projs #neighbor ADM2s
652
+ # ))
653
+
654
+ #remove any columns that have insufficient cross-treatment variability before passing to function
655
+ before_cols <- colnames(conf_matrix)
656
+ conf_matrix <- scale(conf_matrix)
657
+ SD_THRES <- 0.25
658
+ conf_matrix <- conf_matrix[,which((apply(conf_matrix[input_df$treated==0,],2,sd) > SD_THRES &
659
+ apply(conf_matrix[input_df$treated==1,],2,sd) > SD_THRES &
660
+ apply(conf_matrix,2,sd) > SD_THRES))]
661
+ if( mean(is.na(conf_matrix)) > 0){stop("Some NAs in conf_matrix")}
662
+ if( ncol(conf_matrix) < 1){stop("Some no columns left in conf_matrix")}
663
+ # apply(conf_matrix,2,sd)
664
+ #conf_matrix <- conf_matrix[,which(apply(conf_matrix,2,sd)>0)]
665
+ dropped_cols <- setdiff(before_cols, colnames(conf_matrix))
666
+ dropped_labels <- paste(na.omit(var_labels_all[match(setdiff(before_cols,
667
+ colnames(conf_matrix)),
668
+ var_order_all)]),collapse="; ")
669
+ # note: some ADM2 fixed effects dropped also
670
+ if (dropped_labels != "") {
671
+ print(paste("Dropped for 0 SD: ", dropped_labels))
672
+ }
673
+
674
+ #remove no-variation columns from the variables that control later figures
675
+ var_order <- setdiff(var_order_all,dropped_cols)
676
+ var_labels <- setdiff(var_labels_all,
677
+ var_labels_all[match(setdiff(before_cols,
678
+ colnames(conf_matrix)),var_order_all)])
679
+
680
+ #cleanup unneeded objects in memory before calling function
681
+ rm(country_confounders_df, dhs_c_df,dhs_confounders_df,
682
+ dhs_iso3_df,dhs_t_df,funder_sector_iso3,obs_year_group_df,
683
+ run_df, pre_shuffle_df)
684
+
685
+ ################################################################################
686
+ # Generate tf_records file for this sector/funder/time_approach if not present
687
+ ################################################################################
688
+ # if (vision_backbone=="emb") {
689
+ # tf_rec_filename <- paste0("./data/interim/tfrecords/",fund_sect_param,"_",
690
+ # time_approach,"_5k_emb.tfrecord")
691
+ #
692
+ # if (!file.exists(tf_rec_filename)) {
693
+ # print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
694
+ # " Start creating tfrecord file: ",tf_rec_filename))
695
+ #
696
+ # causalimages::WriteTfRecord(file = tf_rec_filename,
697
+ # uniqueImageKeys = paste0(input_df$image_file_5k_3yr,
698
+ # input_df$year_group),
699
+ # acquireImageFxn = acquireImageRepFromDisk,
700
+ # conda_env = NULL,
701
+ # conda_env_required = T
702
+ # )
703
+ # print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
704
+ # " Finished creating tfrecord file: ",tf_rec_filename))
705
+ # }
706
+ # } else {
707
+ # setup for balanced sampling
708
+ if (fund_sect_param %in% c("wb_220","ch_520")) {
709
+ testFrac <- 20/length(input_df$iwi_est_post_oda) #ctj edit
710
+ #testFrac <- 0.1
711
+ }
712
+ if( !(fund_sect_param %in% c("wb_220","ch_520"))) {
713
+ testFrac <- .01 # special cases
714
+ }
715
+
716
+ # define train test splits (avoid overlap in ADM2)
717
+ {
718
+ # Get unique ADM2 regions with their treatment/control counts
719
+ adm2_summary <- input_df %>%
720
+ group_by(adm2) %>%
721
+ summarise(
722
+ n_treated = sum(treated == 1),
723
+ n_control = sum(treated == 0),
724
+ n_total = n(),
725
+ has_both = (n_treated > 0) & (n_control > 0),
726
+ .groups = 'drop'
727
+ )
728
+
729
+ # Separate ADM2s that have both treatment and control from those that don't
730
+ adm2_with_both <- adm2_summary %>%
731
+ filter(has_both) %>%
732
+ pull(adm2)
733
+
734
+ adm2_only_treated <- adm2_summary %>%
735
+ filter(n_treated > 0 & n_control == 0) %>%
736
+ pull(adm2)
737
+
738
+ adm2_only_control <- adm2_summary %>%
739
+ filter(n_treated == 0 & n_control > 0) %>%
740
+ pull(adm2)
741
+
742
+ # Calculate target test set size
743
+ n_test_adm2 <- max(2, ceiling(length(unique(input_df$adm2)) * testFrac))
744
+
745
+ # Sample ADM2s for test set, ensuring representation of both treatment types
746
+ test_adm2s <- c()
747
+
748
+ # First, add some ADM2s that have both treatment and control
749
+ if(length(adm2_with_both) > 0) {
750
+ n_both_for_test <- min(ceiling(n_test_adm2 * 0.5), length(adm2_with_both))
751
+ test_adm2s <- c(test_adm2s, sample(adm2_with_both, n_both_for_test))
752
+ }
753
+
754
+ # Then add some treatment-only and control-only ADM2s if available
755
+ remaining_slots <- n_test_adm2 - length(test_adm2s)
756
+ if(remaining_slots > 0) {
757
+ # Add some treatment-only ADM2s
758
+ if(length(adm2_only_treated) > 0) {
759
+ n_treated_for_test <- min(ceiling(remaining_slots * 0.5), length(adm2_only_treated))
760
+ test_adm2s <- c(test_adm2s, sample(adm2_only_treated, n_treated_for_test))
761
+ }
762
+
763
+ # Add some control-only ADM2s
764
+ remaining_slots <- n_test_adm2 - length(test_adm2s)
765
+ if(length(adm2_only_control) > 0 && remaining_slots > 0) {
766
+ n_control_for_test <- min(remaining_slots, length(adm2_only_control))
767
+ test_adm2s <- c(test_adm2s, sample(adm2_only_control, n_control_for_test))
768
+ }
769
+ }
770
+
771
+ # Define indices based on ADM2 membership
772
+ TestIndices <- which(input_df$adm2 %in% test_adm2s)
773
+ TrainIndices <- which(!(input_df$adm2 %in% test_adm2s))
774
+
775
+ # Separate control and treatment indices for the TFRecordControl
776
+ TestControlIndices <- which(input_df$adm2 %in% test_adm2s & input_df$treated == 0)
777
+ TrainControlIndices <- which(!(input_df$adm2 %in% test_adm2s) & input_df$treated == 0)
778
+ TestTreatmentIndices <- which(input_df$adm2 %in% test_adm2s & input_df$treated == 1)
779
+ TrainTreatmentIndices <- which(!(input_df$adm2 %in% test_adm2s) & input_df$treated == 1)
780
+
781
+ # Update TFRecordControl
782
+ TFRecordControl = list(
783
+ "nTest" = length(TestIndices),
784
+ "nControlTrain" = length(TrainControlIndices),
785
+ "nTreatmentTrain" = length(TrainTreatmentIndices)
786
+ )
787
+
788
+ # Verify no ADM2 overlap
789
+ train_adm2s <- unique( input_df$adm2[TrainIndices] )
790
+ test_adm2s_verify <- unique( input_df$adm2[TestIndices] )
791
+ if(length(intersect(train_adm2s, test_adm2s_verify)) > 0) {
792
+ stop("ERROR: ADM2 overlap detected between train and test sets!")
793
+ }
794
+
795
+ # Print summary statistics
796
+ cat("\n=== ADM2-based Train/Test Split Summary ===\n")
797
+ cat(sprintf("Total ADM2 regions: %d\n", length(unique(input_df$adm2))))
798
+ cat(sprintf("Test ADM2 regions: %d\n", length(test_adm2s)))
799
+ cat(sprintf("Train ADM2 regions: %d\n", length(train_adm2s)))
800
+ cat(sprintf("\nTest set: %d observations (%d treated, %d control)\n",
801
+ length(TestIndices), length(TestTreatmentIndices), length(TestControlIndices)))
802
+ cat(sprintf("Train set: %d observations (%d treated, %d control)\n",
803
+ length(TrainIndices), length(TrainTreatmentIndices), length(TrainControlIndices)))
804
+ cat(sprintf("Test fraction: %.2f%%\n", 100 * length(TestIndices) / nrow(input_df)))
805
+ if( sum(input_df$treated[TrainControlIndices]) > 0){ stop("Some treatment indices in TrainControlIndices")}
806
+ if( mean(input_df$treated[TrainTreatmentIndices]) < 1){ stop("Some control indices in TrainTreatmentIndices")}
807
+
808
+ # Update the data scrambling to respect the new indices
809
+ set.seed(9939L, kind="Wichmann-Hill");
810
+ SCRAMBLED_ORDER <- c(sample(TestIndices),
811
+ sample(TrainControlIndices),
812
+ sample(TrainTreatmentIndices))
813
+ set.seed(sector_param, kind="Wichmann-Hill")
814
+ input_df <- input_df[SCRAMBLED_ORDER,] # FE is later based on this
815
+ conf_matrix <- conf_matrix[SCRAMBLED_ORDER,] # this denotes "X"
816
+ plot(input_df$treated[1:length(TestIndices)])
817
+ plot(input_df$treated[-c(1:(length(TestIndices)+length(TrainControlIndices) ))])
818
+ }
819
+
820
+ # old definition of TFRecordControl
821
+ #{
822
+ #n_test_size <- as.integer(round(testFrac * length(unique(paste0(input_df$image_file_5k_3yr,
823
+ # input_df$year_group))) ))
824
+ #TestIndices <- c(which(input_df$treated== 0)[TestC <- 1:ceiling(n_test_size/2)],
825
+ # which(input_df$treated== 1)[TestT <- 1:ceiling(n_test_size/2)])
826
+ #ControlIndices <- which(input_df$treated== 0)[-TestC]
827
+ #TreatmentIndices <- which(input_df$treated== 1)[-TestT]
828
+
829
+ #TFRecordControl = list("nTest" = length(TestIndices),
830
+ # "nControl" = length(ControlIndices),
831
+ # "nTreatment" = length(TreatmentIndices))
832
+
833
+ # scramble all the indices now WITHIN type and select data according to indices
834
+ #if(!all(row.names(conf_matrix) == row.names(input_df))){ stop("Misalignment between conf_matrix and input_df...") }
835
+ # set.seed(999L,kind="Wichmann-Hill"); input_df <- input_df[SCRAMBLED_ORDER <-
836
+ # c(sample(TestIndices),
837
+ # sample(ControlIndices),
838
+ # sample(TreatmentIndices)),]; set.seed(sector_param,kind="Wichmann-Hill");
839
+ #conf_matrix <- conf_matrix[SCRAMBLED_ORDER,]
840
+ #}
841
+
842
+ tf_rec_filename <- file.path(
843
+ tfrecord_home,
844
+ paste0(fund_sect_param, "_", time_approach, "_5k_bal",
845
+ data_suffix_model_input, ".tfrecord")
846
+ )
847
+
848
+ #if ( !file.exists(tf_rec_filename) | ReSaveTFRecords ) {
849
+ if ( ReSaveTFRecords ) {
850
+ print(sprintf("Creating file: %s", tf_rec_filename))
851
+ print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
852
+ " Start creating tfrecord file: ",tf_rec_filename))
853
+
854
+ print(sprintf("DHS head: %s", paste(head(input_df$dhs_id),collapse=", ")))
855
+ causalimages::WriteTfRecord(file = tf_rec_filename,
856
+ uniqueImageKeys = unique(paste0(input_df$image_file_5k_3yr,
857
+ input_df$year_group)),
858
+ acquireImageFxn = acquireImageRepFromDisk,
859
+ conda_env = conda_env,
860
+ conda_env_required = TRUE)
861
+ print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
862
+ " Finished creating tfrecord file: ",tf_rec_filename))
863
+ }
864
+ # }
865
+
866
+ # Define the fixed effects matrix
867
+ {
868
+ fe_matrix <- scale( model.matrix(~ adm2 - 1, input_df) )
869
+
870
+ # Remove columns with insufficient variability
871
+ before_cols <- colnames(fe_matrix)
872
+ fe_matrix <- fe_matrix[,!(apply(fe_matrix[input_df$treated==0,],2,sd) < SD_THRES |
873
+ apply(fe_matrix[input_df$treated==1,],2,sd) < SD_THRES)]
874
+ dropped_fe_cols <- setdiff(before_cols, colnames(fe_matrix))
875
+ if (length(dropped_fe_cols) > 0) {
876
+ print(paste("Dropped FE columns for 0 SD:", paste(dropped_fe_cols, collapse = "; ")))
877
+ }
878
+ }
879
+
880
+ if(any( row.names(input_df) != row.names(conf_matrix) )){stop("Misalignment between input_df and conf_matrix ")}
881
+ if(any( row.names(fe_matrix) != row.names(conf_matrix) )){stop("Misalignment between fe_matrix and conf_matrix")}
882
+ ###############################
883
+ # call AnalyzeImageConfounding
884
+ ###############################
885
+ # write.csv(file = "~/Downloads/input_df.csv", input_df); write.csv(file = "~/Downloads/conf_matrix.csv", conf_matrix)
886
+ # conf_matrix <- read.csv(file = "~/Downloads/conf_matrix.csv"); input_df <- read.csv(file = "~/Downloads/input_df.csv")
887
+ if(!ReSaveTFRecords){
888
+ if(nSGD =="dynamic"){
889
+ # epochs = batchSize * nSGD / datasize
890
+ # nSGD = epochs * datasize / batchSize
891
+ nSGD <- as.integer(round(max(100,
892
+ min((MAX_CLASS_EPOCHS*table(input_df$treated)) / (batchSize/2)) ) ))
893
+ print(sprintf("Selected nSGD: %.3i", nSGD))
894
+ }
895
+
896
+ if(X_approach %in% c("noX","did","unitFE")){ X_USE <- NULL }
897
+ if(X_approach %in% c("withX","onlyX")){ X_USE <- conf_matrix }
898
+ if(X_approach %in% c("withFE","onlyFE")){ X_USE <- fe_matrix }
899
+ if(X_approach %in% c("withXandFE","onlyXandFE")){ X_USE <- cbind(conf_matrix, fe_matrix) }
900
+
901
+ if( X_approach == "did"){
902
+ source("./code/lib/call_CI_Conf_5k_3yr_DiD.R")
903
+ }
904
+ if( X_approach == "unitFE"){
905
+ source("./code/lib/call_CI_Conf_5k_3yr_unitFE.R")
906
+ }
907
+ if( !X_approach %in% c("did","unitFE")){
908
+
909
+ # sanity check for treatment status arrangement
910
+ {
911
+ # table(input_df$treated)
912
+ checkADM2_bal <- do.call(
913
+ plyr::rbind.fill,
914
+ tapply(
915
+ input_df$treated,
916
+ paste0(input_df$adm2, "_", input_df$year_group),
917
+ function(x) {
918
+ # drop NAs in treated
919
+ x <- x[!is.na(x)]
920
+ # ensure both 0 and 1 are present as levels
921
+ tab <- table(factor(x, levels = c(0, 1)))
922
+ # proportions; if group is empty, return zeros
923
+ prop <- if (sum(tab) > 0) as.numeric(tab) / sum(tab) else c(0, 0)
924
+ data.frame(X0 = prop[1], X1 = prop[2], stringsAsFactors = FALSE)
925
+ }
926
+ )
927
+ )
928
+ # proportions - are they all 0 or 1?
929
+ (table(checkADM2_bal[,2]))
930
+ prop.table(table(checkADM2_bal[,2]))
931
+ # plot(checkADM2_bal[,1], checkADM2_bal[,2])
932
+ # table(table(apply(round(conf_matrix,3L),1,function(x){paste(x,collapse="_")})))
933
+ # summary( lm(input_df$treated~conf_matrix) )
934
+ }
935
+
936
+ if( robust_params$exclude_NTL ){ # drop nightlights in robustness test
937
+ nCol_predrop <- ncol(X_USE)
938
+ X_USE <- X_USE[,!colnames(X_USE) %in% "log_pc_nl_pre_oda"]
939
+ if(ncol(X_USE) == nCol_predrop){ warning("Dropping nightlights failed! Nighltight already dropped") }
940
+ if(ncol(X_USE) != nCol_predrop){ warning("Nightlights success! Nighltight dropped in robustness") }
941
+ }
942
+
943
+ if(JustCheckNaiveATEs){
944
+ # Compute Meta Parameters and Naive Statistics
945
+ n_treat <- sum(input_df$treated == 1)
946
+ n_control <- sum(input_df$treated == 0)
947
+
948
+ # Calculate means safely (handle potential 0 counts gracefully)
949
+ mean_treat <- if(n_treat > 0) mean(input_df$iwi_est_post_oda[input_df$treated == 1],na.rm=T) else NA
950
+ mean_control <- if(n_control > 0) mean(input_df$iwi_est_post_oda[input_df$treated == 0],na.rm=T) else NA
951
+ diff_means <- mean_treat - mean_control
952
+
953
+ # Create Data Frame of Results
954
+ naive_results_df <- data.frame(
955
+ fund_sect_param = fund_sect_param,
956
+ funder = funder_param,
957
+ sector = sector_param,
958
+ vision_backbone = vision_backbone,
959
+ X_approach = X_approach,
960
+ n_treated = n_treat,
961
+ n_control = n_control,
962
+ n_total = n_treat + n_control,
963
+ mean_treated = mean_treat,
964
+ mean_control = mean_control,
965
+ naive_ate = diff_means,
966
+ save_name = saveName,
967
+ robust_suffix = robust_params$suffix,
968
+ timestamp = as.character(Sys.time())
969
+ )
970
+
971
+ # Output Results
972
+ output_file_naive <- file.path("./results", SaveResultsFolder,
973
+ paste0("NaiveATEAnalysis_", saveName,
974
+ robust_params$suffix, ".csv"))
975
+
976
+ # Ensure the directory exists
977
+ write.csv(naive_results_df, output_file_naive, row.names = FALSE)
978
+ print(paste0("Naive ATE computed: ", round(diff_means, 5), ". Saved to: ", output_file_naive))
979
+ }
980
+ if(!JustCheckNaiveATEs){
981
+ if(vision_backbone=="vt") {
982
+ print(dim(input_df)); print(TFRecordControl)
983
+ ImageConfoundingAnalysis <- causalimages::AnalyzeImageConfounding(
984
+ obsW = input_df$treated,
985
+ obsY = input_df$iwi_est_post_oda,
986
+ file = tf_rec_filename,
987
+ X = X_USE,
988
+ XCrossModal = TRUE,
989
+ XForceModal = XForceModal,
990
+ #concatenate the image file location and oda year group into a single keys parameter
991
+ imageKeysOfUnits = paste0(input_df$image_file_5k_3yr,input_df$year_group),
992
+ nBoot = 1000L,
993
+ lat = input_df$lat,
994
+ long = input_df$lon,
995
+ conda_env = conda_env,
996
+ conda_env_required = TRUE,
997
+ figuresTag = paste0(fund_sect_param,"_",run,"_i","FINAL", robust_params$suffix),
998
+ figuresPath = results_dir, # figures saved here
999
+ plotBands=c(3,2,1), #red, green, blue
1000
+ kFolds = kFolds,
1001
+ learningRateMax = learningRateMax,
1002
+ nDepth_ImageRep = nDepth_ImageRep,
1003
+ nWidth_ImageRep = nWidth_ImageRep,
1004
+ batchSize = batchSize,
1005
+ dropoutRate = dropoutRate,
1006
+ droppathRate = droppathRate,
1007
+ nonLinearScaler = nonLinearScaler,
1008
+ earlyStopThreshold = earlyStopThreshold,
1009
+ plotResults = plotResults,
1010
+ nDepth_Dense = 1L,
1011
+ imageModelClass = "VisionTransformer",
1012
+ optimizeImageRep = TRUE,
1013
+ nSGD = nSGD,
1014
+ testFrac = testFrac,
1015
+ TFRecordControl = TFRecordControl,
1016
+ atError = 'stop'
1017
+ )
1018
+ }
1019
+ if(vision_backbone=="emb") {
1020
+ ImageConfoundingAnalysis <- causalimages::AnalyzeImageConfounding(
1021
+ obsW = input_df$treated,
1022
+ obsY = input_df$iwi_est_post_oda,
1023
+ X = X_USE,
1024
+ file = tf_rec_filename,
1025
+ #concatenate the image file location and oda year group into a single keys parameter
1026
+ imageKeysOfUnits = paste0(input_df$image_file_5k_3yr,input_df$year_group),
1027
+ nBoot = 10L, #costly operation; do few
1028
+ lat = input_df$lat,
1029
+ long = input_df$lon,
1030
+ conda_env = conda_env, # not using conda env
1031
+ conda_env_required = TRUE,
1032
+ plotResults = FALSE,
1033
+ kFolds = 1L,
1034
+ figuresTag = paste0(fund_sect_param,"_",run,"_i","FINAL",robust_params$suffix),
1035
+ figuresPath = results_dir, # figures saved here
1036
+ plotBands=c(3,2,1), #red, green, blue
1037
+ learningRateMax = learningRateMax,
1038
+ nDepth_ImageRep = nDepth_ImageRep,
1039
+ nWidth_ImageRep = nWidth_ImageRep,
1040
+ batchSize = as.integer(4L*batchSize),
1041
+ dropoutRate = dropoutRate,
1042
+ droppathRate = droppathRate,
1043
+ nonLinearScaler = nonLinearScaler,
1044
+ earlyStopThreshold = earlyStopThreshold,
1045
+ nDepth_Dense = 1L,
1046
+ imageModelClass = "VisionTransformer",
1047
+ optimizeImageRep = FALSE,
1048
+ nSGD = nSGD,
1049
+ atError = 'debug'
1050
+ )
1051
+ }
1052
+
1053
+ # sanity checks
1054
+ {
1055
+ plot(ImageConfoundingAnalysis$prW_est[ImageConfoundingAnalysis$testIndices],
1056
+ input_df$treated[ImageConfoundingAnalysis$testIndices],
1057
+ cex = 0.15)
1058
+ pROC::auc(pROC::roc(
1059
+ response = input_df$treated[ImageConfoundingAnalysis$testIndices],
1060
+ predictor = ImageConfoundingAnalysis$prW_est[ImageConfoundingAnalysis$testIndices],
1061
+ levels = c(0, 1), direction = "<"))
1062
+ tapply(ImageConfoundingAnalysis$prW_est[ImageConfoundingAnalysis$testIndices],
1063
+ input_df$treated[ImageConfoundingAnalysis$testIndices], summary)
1064
+ FBeta_max <- max(as.numeric(as.character((sapply(seq(0.1,0.9,by=0.1),function(thres_){
1065
+ try(yardstick::f_meas_vec(
1066
+ as.factor(input_df$treated[ImageConfoundingAnalysis$testIndices]),
1067
+ as.factor(1*(ImageConfoundingAnalysis$prW_est[ImageConfoundingAnalysis$testIndices]>thres_)),
1068
+ beta = 2) ,T)
1069
+ })))),na.rm=T)
1070
+
1071
+ # Note, for indices, see:
1072
+ # ImageConfoundingAnalysis$ModelEvaluationMetrics$AUC_out
1073
+ # ImageConfoundingAnalysis$ModelEvaluationMetrics$AUPRC_out
1074
+ # ImageConfoundingAnalysis$ModelEvaluationMetrics$FBeta_OUT
1075
+ # ImageConfoundingAnalysis$testIndices
1076
+ # table(input_df$treated[ImageConfoundingAnalysis$testIndices])
1077
+ # ImageConfoundingAnalysis$trainIndices
1078
+ }
1079
+
1080
+ ica_df <- data.frame(t(unlist(ImageConfoundingAnalysis))) %>%
1081
+ select(-starts_with("prW_est"),-starts_with("SalienceX.adm2"),
1082
+ -starts_with("SalienceX_se.adm2"),-starts_with("SGD_loss_vec"),
1083
+ -starts_with("tauHat_propensityHajek_vec"),-starts_with("trainIndices"),
1084
+ -starts_with("testIndices"))
1085
+ output_df <- cbind(data.frame(run,fund_sect_param,treat_count,control_count,
1086
+ dropped_labels,
1087
+ ica_df))
1088
+ print(paste0("[",format(Sys.time(), "%Y-%m-%d %H:%M:%S"),"]",
1089
+ " Writing to ",results_dir,"ICA_",fund_sect_param,"_",run,"_i",
1090
+ "FINAL",
1091
+ robust_params$suffix,
1092
+ ".csv"))
1093
+ write.csv(output_df,paste0(results_dir,"ICA_",fund_sect_param,"_",run,"_i",
1094
+ "FINAL",
1095
+ robust_params$suffix,
1096
+ ".csv"),row.names = FALSE)
1097
+
1098
+ ############################################################################
1099
+ # generate plots for this run
1100
+ ############################################################################
1101
+ library(tidyr)
1102
+ library(ggplot2)
1103
+
1104
+ #plot the distribution of other sector project counts
1105
+ log_other_sect_projs <- input_df %>%
1106
+ mutate(year_color=as.factor(year_group)) %>%
1107
+ ggplot(aes(log_other_sect_n, color=year_color)) +
1108
+ geom_density() +
1109
+ labs(x = paste0(toupper(funder_param)," project count (log + 1) in sectors other than ",sector_param),
1110
+ y = "Density across DHS points",
1111
+ title=paste0(toupper(funder_param),
1112
+ " project count (log + 1) by year group in sectors other than ",
1113
+ sector_param),
1114
+ color="Year Group") +
1115
+ theme_bw()
1116
+
1117
+ ggsave(paste0(results_dir,fund_sect_param,"_15other_sect_projs_",run,robust_params$suffix,".pdf"),
1118
+ log_other_sect_projs,
1119
+ width=6, height = 6, dpi=300,
1120
+ bg="white", units="in")
1121
+
1122
+ long_funder <- case_when(
1123
+ startsWith(fund_sect_param, "ch") ~ "China",
1124
+ startsWith(fund_sect_param, "wb") ~ "World Bank",
1125
+ startsWith(fund_sect_param, "both") ~ "Both China & World Bank"
1126
+ )
1127
+
1128
+ sector_names_df <- read.csv(sprintf("./data/interim/sector_group_names%s.csv",robust_params$suffix)) %>%
1129
+ mutate(sec_pre_name = paste0(ad_sector_names," (",ad_sector_codes,")"))
1130
+
1131
+ sector_name <- sector_names_df %>%
1132
+ filter(ad_sector_codes==sector_param) %>%
1133
+ pull(sec_pre_name)
1134
+
1135
+ # Convert to long format for boxplots
1136
+ long_input_df <- input_df %>%
1137
+ select(treated,all_of(var_order)) %>%
1138
+ tidyr::pivot_longer(c(-treated),names_to="variable_name", values_to="value")
1139
+
1140
+ sub_l1 <- paste("Funder:",long_funder," Sector:", sector_name)
1141
+ sub_l2 <- ifelse(nzchar(dropped_labels),
1142
+ paste0("Dropped due to no variation: ", dropped_labels),
1143
+ "")
1144
+
1145
+ combined_boxplot <- ggplot(long_input_df, aes(x = factor(treated), y = value)) +
1146
+ geom_boxplot() +
1147
+ labs(title = "Distribution of Wealth Outcome and Confounders for Treated and Control Neighborhoods",
1148
+ subtitle = paste(sub_l1,sub_l2,sep="\n"),
1149
+ x = paste0("Treatment/Control: 0:control (n ",control_count,"), 1:treated (n ",treat_count,")"),
1150
+ y = "Value",
1151
+ color = "Highest Pr(T=1)",
1152
+ fill = "Lowest Pr(T=1)") +
1153
+ facet_wrap(~ variable_name, scales = "free") +
1154
+ facet_wrap(~ factor(variable_name, levels = var_order, labels = var_labels), scales = "free") +
1155
+ theme_bw() +
1156
+ theme(panel.grid = element_blank())
1157
+
1158
+ ggsave(paste0(results_dir,fund_sect_param,"_20boxplots_",run,robust_params$suffix, ".pdf"),
1159
+ combined_boxplot,
1160
+ width=10, height = 8, dpi=300,
1161
+ bg="white", units="in")
1162
+
1163
+ #############################################################################
1164
+ ##### create a scatterplot comparing confounders to outcome variable
1165
+ #############################################################################
1166
+ # Set the treated color based on funder
1167
+ treat_color <- case_when(
1168
+ startsWith(fund_sect_param, "ch") ~ "indianred1",
1169
+ startsWith(fund_sect_param, "wb") ~ "mediumblue"
1170
+ )
1171
+
1172
+ #Convert to longer format for density plots, leaving outcome as separate column
1173
+ hybrid_input_df <- input_df %>%
1174
+ select(treated,all_of(var_order)) %>%
1175
+ tidyr::pivot_longer(c(-treated,-iwi_est_post_oda),names_to="variable_name", values_to="value")
1176
+
1177
+ outcome_confounders_plot <- ggplot(hybrid_input_df, aes(x = iwi_est_post_oda, y=value, color = factor(treated))) +
1178
+ geom_point(alpha = 0.3) +
1179
+ facet_wrap(~ variable_name, scales = "free_y", ncol = 3) +
1180
+ facet_wrap(~ factor(variable_name, levels = var_order, labels = var_labels), scales = "free") +
1181
+ labs(title = "Confounders vs. Estimated wealth for Treated and Control Neighborhoods",
1182
+ subtitle = paste(sub_l1,sub_l2,sep="\n"),
1183
+ x = "Estimated Wealth Index one 3-year lag after project commitment period",
1184
+ y = "Value",
1185
+ color="") +
1186
+ scale_color_manual(values = c("gray60", treat_color),
1187
+ labels = c("Control", "Treated")) +
1188
+ theme_bw() +
1189
+ theme(panel.grid = element_blank(),
1190
+ legend.position = "top",
1191
+ legend.justification = c("right","top"),
1192
+ legend.margin=margin(0,0,0,0),
1193
+ legend.direction="horizontal")
1194
+
1195
+ ggsave(paste0(results_dir,fund_sect_param,"_30conf_iwi_",run, robust_params$suffix, ".png"),
1196
+ outcome_confounders_plot,
1197
+ width=10, height = 8, dpi=300,
1198
+ bg="white", units="in")
1199
+
1200
+ ##########################################################################
1201
+ ##### generate treatment/control map
1202
+ ##########################################################################
1203
+ library(tmap)
1204
+ #tmap_options(check.and.fix = TRUE)
1205
+ tmap::tm_check_fix()
1206
+ projection <- "ESRI:102023"
1207
+
1208
+ #convert DHS points df to sf object
1209
+ input_sf <- sf::st_as_sf(input_df, coords=c("lon","lat"),crs="EPSG:4326") %>%
1210
+ sf::st_transform(crs=sf::st_crs(projection))
1211
+ ###############################################################
1212
+ #### Load administrative borders and ISO list excluding islands
1213
+ ###############################################################
1214
+ africa_map_isos_df <- read.csv("./data/interim/africa_map_isos.csv")
1215
+
1216
+ country_borders <- sf::read_sf("./data/country_regions/gadm28_adm0.shp") %>%
1217
+ filter(ISO %in% africa_map_isos_df$iso3)
1218
+ sf::st_crs(country_borders) = "EPSG:4326"
1219
+ country_borders <- sf::st_transform(country_borders,crs=sf::st_crs(projection))
1220
+ country_borders <- sf::st_make_valid(country_borders)
1221
+
1222
+ ########################
1223
+ #### Generate map
1224
+ ########################
1225
+ treat_control_map <- tm_shape(country_borders) +
1226
+ tm_borders(lwd=2) +
1227
+ tm_shape(input_sf[input_sf$treated == 0, ]) +
1228
+ tm_dots(size=.3, col="gray80", alpha=.3) +
1229
+ tm_shape(input_sf[input_sf$treated == 1, ]) +
1230
+ tm_dots(size=.5, col=treat_color, alpha=.3) +
1231
+ tm_add_legend(type = "fill"
1232
+ , col = c(treat_color,"gray80")
1233
+ , labels = c(paste0("Treated (n ",treat_count,")"),
1234
+ paste0("Control (n ",control_count,")"))) +
1235
+ tm_layout(main.title.size=1,
1236
+ main.title = paste0(long_funder,": ",sector_name,"\nTreatment and Control Locations (2002-2013)"),
1237
+ main.title.position=c("center","top"),
1238
+ legend.position = c("left", "bottom"),
1239
+ legend.text.size = 1,
1240
+ legend.width=-1,
1241
+ frame = T ,
1242
+ legend.outside = F,
1243
+ outer.margins = c(0, 0, 0, 0),
1244
+ legend.outside.size = .25
1245
+ )
1246
+ tmap_save(treat_control_map,paste0(results_dir,fund_sect_param,"_10map_",run,robust_params$suffix, ".png"))
1247
+
1248
+ library(glmnet); library(scales)
1249
+ #####################################################################
1250
+ #function to estimate ATE and standard error with ridge regression
1251
+ #####################################################################
1252
+ est_ate_with_se_ridge <- function(X, obsW, obsY, nBoot = 100, trainIndices, testIndices) {
1253
+ ate_vec <- c();
1254
+ pb <- txtProgressBar(min = 0, max = nBoot, style = 3) # Initialize progress bar
1255
+ for (i in 1L:(nBoot + 1L)) {
1256
+ if(i %%10 ==0){print(sprintf("Boot %s of %s",i,nBoot))}
1257
+ setTxtProgressBar(pb, i)
1258
+ if(i != (nBoot + 1L)){ boot_indices <- sample(1:length(obsY), length(obsY), replace = TRUE) }
1259
+ if(i == (nBoot + 1L)){ boot_indices <- 1:length(obsY) }
1260
+ ridge_model <- glmnet::cv.glmnet(
1261
+ x = as.matrix(X[boot_indices,]),
1262
+ y = as.matrix(obsW[boot_indices]),
1263
+ nfolds = 5,
1264
+ alpha = 0, # alpha = 0 is the ridge penalty
1265
+ type.measure = "auc",
1266
+ family = "binomial")
1267
+ obs_treated <- obsW[boot_indices]
1268
+ obs_outcome <- obsY[boot_indices]
1269
+ est_pr_treated <- predict(ridge_model, s = "lambda.min",
1270
+ newx = as.matrix(X[boot_indices,]), type = "response")
1271
+ # Trim propensity scores to avoid division by zero in IPW
1272
+ est_pr_treated <- pmax(0.01, pmin(0.99, est_pr_treated))
1273
+ ate_vec[i] <- sum(obs_outcome*prop.table(obs_treated/c(est_pr_treated))) -
1274
+ sum(obs_outcome*prop.table((1-obs_treated)/c(1-est_pr_treated) ))
1275
+ if(i == (nBoot + 1L)) {
1276
+ # Create a data frame with predicted probabilities, and actual treatment status
1277
+ ridge_result_df <- data.frame(predicted_probs = est_pr_treated,
1278
+ treated = obs_treated)
1279
+ # Plot it in thesis style
1280
+ ridge_conf_density <- ggplot(ridge_result_df, aes(x = lambda.min, fill = factor(treated))) +
1281
+ geom_density(alpha = 0.5) +
1282
+ labs(title = "Ridge regression: Density Plot for\nEstimated Pr(T=1 | Tabular Covariates)",
1283
+ subtitle = paste(sub_l1,sub_l2,sep="\n"),
1284
+ x = "Predicted Treatment Propensity",
1285
+ y = "Density",
1286
+ fill="Status") +
1287
+ scale_fill_manual(values = c("gray80", treat_color),
1288
+ labels = c("Control", "Treated")) +
1289
+ scale_x_continuous(labels=label_number_auto(),limits=c(0,1)) +
1290
+ theme_bw() +
1291
+ theme(panel.grid = element_blank())
1292
+ #save
1293
+ ggsave(paste0(results_dir,fund_sect_param,"_50ridge_prop_",run,robust_params$suffix,".pdf"),
1294
+ ridge_conf_density,
1295
+ width=6, height = 4, dpi=300,
1296
+ bg="white", units="in")
1297
+ # Plot it in AnalyzeImageConfounding style
1298
+ try({
1299
+ print("Plotting ridge tabular only propensity histogram...")
1300
+ pdf(sprintf("%s%s_55ridge_prop_%s%s.pdf",results_dir,fund_sect_param,run,robust_params$suffix))
1301
+ {
1302
+ par(mfrow=c(1,1))
1303
+ d0 <- density(est_pr_treated[obsW==0])
1304
+ d1 <- density(est_pr_treated[obsW==1])
1305
+ plot(d1,lwd=2,xlim = c(-0.1,1.1),ylim =c(0,max(c(d1$y,d0$y),na.rm=T)*1.2),
1306
+ cex.axis = 1.2,ylab = "",xaxt = "n",
1307
+ xlab = paste0(fund_sect_param,"_",run,"_i","FINAL"),
1308
+ main = "Density Plots for \n Estimated Pr(T=1 | Tabular Covariates)",cex.main = 2)
1309
+ axis(1, at = seq(0,1,by = 0.25))
1310
+ points(d0,lwd=2,type = "l",col="gray",lty=2)
1311
+ text(d0$x[which.max(d0$y)[1]],
1312
+ max(d0$y,na.rm=T)*1.1,label = "T = 0",col="gray",cex=2)
1313
+ text(d1$x[which.max(d1$y)[1]],
1314
+ max(d1$y,na.rm=T)*1.1,label = "T = 1",col="black",cex=2)
1315
+ }
1316
+ dev.off()
1317
+ }, T)
1318
+ # run again for coefficients / use cross-validation to choose lambda
1319
+ cv_model_ridge <- cv.glmnet(x=as.matrix(X[boot_indices,]),
1320
+ y=as.matrix(obsW[boot_indices]),
1321
+ nfolds=5,
1322
+ family = "binomial",
1323
+ alpha = 0)
1324
+ best_lambda_ridge <- cv_model_ridge$lambda.min
1325
+ # Fit model with best lambda
1326
+ ridge_model_best <- glmnet(x=as.matrix(X[boot_indices,]),
1327
+ y=as.matrix(obsW[boot_indices]),
1328
+ family = "binomial", alpha = 0,
1329
+ lambda = best_lambda_ridge)
1330
+ ridge_coeffs_df <- broom::tidy(ridge_model_best)
1331
+ } #end of last iteration check
1332
+ } #end of for loop
1333
+ close(pb) # Close the progress bar after the loop
1334
+ # Compute model evaluation metrics using provided train/test indices
1335
+ ridge_model_metrics <- glmnet::cv.glmnet(
1336
+ x = as.matrix(X[trainIndices,]),
1337
+ y = as.matrix(obsW[trainIndices]),
1338
+ nfolds = 5,
1339
+ alpha = 0,
1340
+ type.measure = "auc",
1341
+ family = "binomial"
1342
+ )
1343
+ est_pr_treated_metrics <- predict(ridge_model_metrics, s = "lambda.min",
1344
+ newx = as.matrix(X), type = "response")
1345
+ baseline_pr <- mean(obsW[trainIndices])
1346
+ pr_baseline <- rep(baseline_pr, length(obsW))
1347
+ binaryCrossLoss <- function(W, prW) { -mean(W * log(prW) + (1 - W) * log(1 - prW)) }
1348
+ classError <- function(W, prW) { mean((prW > 0.5 & W == 0) | (prW <= 0.5 & W == 1)) }
1349
+ in_sample <- trainIndices
1350
+ out_sample <- testIndices
1351
+ lossCE_IN <- binaryCrossLoss(obsW[in_sample], est_pr_treated_metrics[in_sample])
1352
+ lossCE_OUT <- binaryCrossLoss(obsW[out_sample], est_pr_treated_metrics[out_sample])
1353
+ lossCE_IN_baseline <- binaryCrossLoss(obsW[in_sample], pr_baseline[in_sample])
1354
+ lossCE_OUT_baseline <- binaryCrossLoss(obsW[out_sample], pr_baseline[out_sample])
1355
+ ClassError_IN <- classError(obsW[in_sample], est_pr_treated_metrics[in_sample])
1356
+ ClassError_OUT <- classError(obsW[out_sample], est_pr_treated_metrics[out_sample])
1357
+ ClassError_IN_baseline <- classError(obsW[in_sample], pr_baseline[in_sample])
1358
+ ClassError_OUT_baseline <- classError(obsW[out_sample], pr_baseline[out_sample])
1359
+ AUC_IN <- pROC::auc(pROC::roc(obsW[in_sample], est_pr_treated_metrics[in_sample], levels = c(0, 1), direction = "<"))
1360
+ AUC_OUT <- pROC::auc(pROC::roc(obsW[out_sample], est_pr_treated_metrics[out_sample], levels = c(0, 1), direction = "<"))
1361
+ AUPRC_IN <- PRROC::pr.curve(scores.class0 = est_pr_treated_metrics[in_sample][obsW[in_sample] == 1],
1362
+ scores.class1 = est_pr_treated_metrics[in_sample][obsW[in_sample] == 0],
1363
+ curve = FALSE)$auc.integral
1364
+ AUPRC_OUT <- PRROC::pr.curve(scores.class0 = est_pr_treated_metrics[out_sample][obsW[out_sample] == 1],
1365
+ scores.class1 = est_pr_treated_metrics[out_sample][obsW[out_sample] == 0],
1366
+ curve = FALSE)$auc.integral
1367
+ ModelEvaluationMetrics <- list(
1368
+ AUC_out = AUC_OUT,
1369
+ AUC_in = AUC_IN,
1370
+ AUPRC_out = AUPRC_OUT,
1371
+ AUPRC_in = AUPRC_IN,
1372
+ CELoss_out = lossCE_OUT,
1373
+ CELoss_out_baseline = lossCE_OUT_baseline,
1374
+ CELoss_in = lossCE_IN,
1375
+ CELoss_in_baseline = lossCE_IN_baseline,
1376
+ ClassError_out = ClassError_OUT,
1377
+ ClassError_out_baseline = ClassError_OUT_baseline,
1378
+ ClassError_in = ClassError_IN,
1379
+ ClassError_in_baseline = ClassError_IN_baseline
1380
+ )
1381
+ return(list(
1382
+ "ate" = ate_vec[length(ate_vec)],
1383
+ "ate_se" = sd(ate_vec[-length(ate_vec)]),
1384
+ "coeffs_df" = ridge_coeffs_df,
1385
+ "ModelEvaluationMetrics" = ModelEvaluationMetrics))
1386
+ } #end of est_ate_with_se_ridge
1387
+
1388
+ ############################################################################
1389
+ ##### ridge regression for treatment probabilities with tabular covs only
1390
+ ############################################################################
1391
+ if(X_approach == "withX"){
1392
+ nBoot <- 100 # tabular nBoot
1393
+ # do bootstrap with tabular only results
1394
+ {
1395
+ output <- est_ate_with_se_ridge(X=conf_matrix,
1396
+ obsW=input_df$treated,
1397
+ obsY=input_df$iwi_est_post_oda,
1398
+ nBoot=nBoot,
1399
+ trainIndices = ImageConfoundingAnalysis$trainIndices,
1400
+ testIndices = ImageConfoundingAnalysis$testIndices)
1401
+ treat_prob_log_r_df <- output$coeffs_df %>%
1402
+ rename(ridge_est=estimate)
1403
+ output_df <- data.frame("fund_sect_param"=fund_sect_param,
1404
+ "ate_ridge"=output$ate,
1405
+ "ate_se_ridge"=output$ate_se,
1406
+ t(unlist(output$ModelEvaluationMetrics)))
1407
+ write.csv(output_df,
1408
+ paste0(results_dir,fund_sect_param,sprintf("_ridge_tab_only%s.csv",robust_params$suffix)),
1409
+ row.names=FALSE)
1410
+ }
1411
+
1412
+ # do bootstrap with fixed effects only results
1413
+ {
1414
+ # Run bootstrap with fixed effects only
1415
+ output_fe <- est_ate_with_se_ridge(X = fe_matrix,
1416
+ obsW = input_df$treated,
1417
+ obsY = input_df$iwi_est_post_oda,
1418
+ nBoot = nBoot,
1419
+ trainIndices = ImageConfoundingAnalysis$trainIndices,
1420
+ testIndices = ImageConfoundingAnalysis$testIndices)
1421
+ treat_prob_log_r_fe_df <- output_fe$coeffs_df %>%
1422
+ rename(ridge_est = estimate)
1423
+
1424
+ output_fe_df <- data.frame("fund_sect_param" = fund_sect_param,
1425
+ "ate_ridge_fe" = output_fe$ate,
1426
+ "ate_se_ridge_fe" = output_fe$ate_se,
1427
+ t(unlist(output_fe$ModelEvaluationMetrics)))
1428
+
1429
+ write.csv(output_fe_df,
1430
+ paste0(results_dir, fund_sect_param, sprintf("_ridge_fe_only%s.csv",robust_params$suffix)),
1431
+ row.names = FALSE)
1432
+ }
1433
+ }
1434
+
1435
+ ############################################################################
1436
+ ##### add SalienceX & .se to df, save, and plot ridge and SalienceX values
1437
+ ############################################################################
1438
+ #extract tabular confounder salience values from image confounding output
1439
+ if(X_approach == "withX"){
1440
+ if (vision_backbone %in% c("vt")) {
1441
+ #doesn't have se for Salience scores
1442
+ tab_conf_salience_df <- ica_df %>%
1443
+ select(starts_with("SalienceX.")) %>%
1444
+ rename_with(~sub("^SalienceX\\.", "", .), starts_with("SalienceX.")) %>%
1445
+ pivot_longer(cols=everything())
1446
+
1447
+ #join to dataframe with ridge output
1448
+ tab_conf_compare_df <- treat_prob_log_r_df %>%
1449
+ right_join(tab_conf_salience_df, join_by("term"=="name")) %>%
1450
+ rename(Salience_AIC = value)
1451
+ }
1452
+ if( vision_backbone %in% "emb") {
1453
+ tab_conf_salience_df <- ica_df %>%
1454
+ select(starts_with("SalienceX")) %>%
1455
+ pivot_longer(cols=everything()) %>%
1456
+ tidyr::separate_wider_delim(name,delim=".",names=c("measure","term")) %>%
1457
+ pivot_wider(names_from = measure, values_from=value) %>%
1458
+ mutate(SalienceX_tscore = abs(SalienceX/SalienceX_se),
1459
+ SalienceX_sig = ifelse(SalienceX_tscore >= 1.96, "*",""))
1460
+
1461
+ #join to dataframe with ridge output
1462
+ tab_conf_compare_df <- treat_prob_log_r_df %>%
1463
+ right_join(tab_conf_salience_df, by="term") %>%
1464
+ rename(Salience_AIC = SalienceX)
1465
+ }
1466
+
1467
+ #write to file
1468
+ write.csv(tab_conf_compare_df,
1469
+ paste0(results_dir,fund_sect_param,"_tab_conf_compare_", run, robust_params$suffix, ".csv"),
1470
+ row.names = FALSE)
1471
+
1472
+ #plot these
1473
+ #before doing so, remove ADM2 variables
1474
+ tab_conf_compare_df <- tab_conf_compare_df %>%
1475
+ filter(!grepl("adm2",term))
1476
+ #determine the limits of the plot
1477
+ max_abs_value_x <- max(abs(tab_conf_compare_df$ridge_est),na.rm=T)
1478
+ max_abs_value_y <- max(abs(tab_conf_compare_df$Salience_AIC),na.rm=T)
1479
+
1480
+ tab_est_images <- tab_conf_compare_df %>%
1481
+ mutate(term=case_match(term,
1482
+ "log_pc_nl_pre_oda" ~ "percap_nightlights",
1483
+ "log_avg_min_to_city" ~ "min_to_city",
1484
+ "log_avg_pop_dens" ~ "pop_dens",
1485
+ "log_3yr_pre_conflict_deaths" ~ "conflict_deaths",
1486
+ "log_disasters" ~ "natural_disasters",
1487
+ "log_ch_loan_proj_n" ~ "ch_loan_projs",
1488
+ "log_dist_km_to_gold" ~ "dist_to_gold",
1489
+ "log_dist_km_to_gems" ~ "dist_to_gems",
1490
+ "log_dist_km_to_dia" ~ "dist_to_dia",
1491
+ "log_dist_km_to_petro" ~ "dist_to_petro",
1492
+ "log_total_neighbor_projs" ~ "neighbor_oda",
1493
+ "log_other_sect_n" ~ "other_sector_oda",
1494
+ "log_treated_other_funder_n" ~ "other_funder_oda",
1495
+ .default=term)) %>%
1496
+ ggplot(aes(x = ridge_est, y = Salience_AIC, label = term)) +
1497
+ geom_point(color=treat_color) +
1498
+ ggrepel::geom_text_repel(box.padding = 1,max.overlaps=Inf,color=treat_color,
1499
+ segment.color="gray80") +
1500
+ geom_vline(xintercept=0,color="gray80") +
1501
+ geom_hline(yintercept=0, color="gray80") +
1502
+ geom_abline(intercept=0, slope=1, linetype="dashed",color="gray80") +
1503
+ labs(title = "Tabular confounder estimates with and without images",
1504
+ subtitle = paste(sub_l1,sub_l2,sep="\n"),
1505
+ x = "Tabular covariates only: Ridge estimate",
1506
+ y = "Salience with Image Confounding") +
1507
+ coord_cartesian(xlim=c(-1*max_abs_value_x,max_abs_value_x),
1508
+ ylim=c(-1*max_abs_value_y,max_abs_value_y)) +
1509
+ theme_bw() +
1510
+ theme(panel.grid = element_blank())
1511
+
1512
+ #save
1513
+ ggsave(paste0(results_dir,fund_sect_param,"_90xy_tab_conf_images_",run,robust_params$suffix,".pdf"),
1514
+ tab_est_images,
1515
+ width=6, height = 6, dpi=300,
1516
+ bg="white", units="in")
1517
+ }
1518
+
1519
+ ############################################################################
1520
+ #print these messages again to be at the end of the logfile
1521
+ ############################################################################
1522
+ if (dropped_labels != "") {
1523
+ print(paste("Done! Dropped for 0 SD: ", dropped_labels))
1524
+ }
1525
+ print("Done with call_CI_Conf_5k_3yr.R iteration!")
1526
+ }
1527
+ }
1528
+ }
1529
+ }
1530
+ }
1531
+ }
1532
+ }
1533
+ }
1534
+ }
1535
+
1536
+ if(FALSE){# Check JAX
1537
+ reticulate::use_condaenv("jax_gpu",required=TRUE)
1538
+ jax <- reticulate::import("jax")
1539
+ jax$numpy$array(4.)
1540
+ }
1541
+ if(FALSE){ # Check naive ATEs
1542
+ # 1. Identify the directory and list all Naive ATE files
1543
+ target_path <- file.path("./results", SaveResultsFolder)
1544
+ all_naive_df <- do.call(rbind, lapply(list.files(target_path,
1545
+ pattern = "NaiveATEAnalysis_.*\\.csv$",
1546
+ full.names = TRUE), read.csv))
1547
+ plot(all_naive_df$naive_ate,col=(all_naive_df$funder=="ch")+1)
1548
+
1549
+ # --- Heterogeneity by Funder ---
1550
+ cat("\n[Analysis 1] Mean Naive ATE (Wealth Index) by Funder:\n")
1551
+ funder_stats <- all_naive_df %>%
1552
+ group_by(funder) %>%
1553
+ summarize(
1554
+ Mean_Naive_ATE = mean(naive_ate, na.rm = TRUE),
1555
+ Median_Naive_ATE = median(naive_ate, na.rm = TRUE),
1556
+ SD_Naive_ATE = sd(naive_ate, na.rm = TRUE),
1557
+ N_Sectors = n()
1558
+ )
1559
+ print(funder_stats)
1560
+
1561
+ # --- Sector-Level Outliers ---
1562
+ cat("\n[Analysis 2] Top 3 Most Positive and Negative Sector Associations:\n")
1563
+ top_bottom_sectors <- all_naive_df %>%
1564
+ arrange(desc(naive_ate)) %>%
1565
+ select(funder, sector, n_treated, n_control, naive_ate) %>%
1566
+ slice(c(1:3, (n()-2):n()))
1567
+ print(top_bottom_sectors)
1568
+
1569
+ # Save the aggregated file for easy inspection later
1570
+ write.csv(all_naive_df,
1571
+ file.path(target_path, "Aggregated_Naive_ATE_Results.csv"),
1572
+ row.names = FALSE)
1573
+ print(paste0("Aggregated results saved to: ", file.path(target_path, "Aggregated_Naive_ATE_Results.csv")))
1574
+ }
1575
+
code/lib/call_CI_Conf_5k_3yr_DiD.R ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Script: call_CI_Conf_5k_3k_DiD.R
2
+ # de Chaisemartin & D’Haultfœuille (2020/2022)
3
+ {
4
+ # Assume full data is in 'input_df' (tibble/data.frame with columns: dhs_id, year_group, treated, iwi_est_post_oda)
5
+ # Map year_group (chr) to numeric time (midpoint of bins for ordering)
6
+ library(tidyr)
7
+ input_df <- input_df %>%
8
+ mutate(time = case_when(
9
+ year_group == "2002:2004" ~ 2003,
10
+ year_group == "2005:2007" ~ 2006,
11
+ year_group == "2008:2010" ~ 2009,
12
+ year_group == "2011:2013" ~ 2012,
13
+ TRUE ~ NA_real_ # Extend as needed for more bins
14
+ )) %>% drop_na(time) # Drop invalid year_groups if any
15
+
16
+ if(FALSE){
17
+ write.csv(input_df,
18
+ file = sprintf("./%s/InputData_%s_DiD.csv",results_dir, fund_sect_param))
19
+ }
20
+
21
+ did_dyn <- DIDmultiplegt::did_multiplegt(
22
+ mode = "dyn",
23
+ input_df, # data
24
+ outcome = "iwi_est_post_oda", # outcome variable
25
+ group = "dhs_id", # group (unit) id
26
+ time = "time", # time variable (numeric)
27
+ treatment = "treated", # treatment (0/1)
28
+ cluster = "dhs_id", # cluster for SEs
29
+ ci_level = 95, # confidence level
30
+ graph_off = FALSE # show event-study graph (FALSE to show, TRUE to hide)
31
+ )
32
+
33
+ # write to disk
34
+ write.csv(file = sprintf("./%s/%s_unitFE.csv",results_dir, fund_sect_param),
35
+ cbind("fund_sect_param"=fund_sect_param,
36
+ "time_approach"=time_approach,
37
+ "vision_backbone"=vision_backbone,
38
+ "X_approach"=X_approach,
39
+ "run"=run,
40
+ unlist(did_dyn$results$ATE)))
41
+ print("Done with DiD estimation!")
42
+ }
43
+
code/lib/call_CI_Conf_5k_3yr_Helpers.R ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ get_total_ram_gb <- function() {
3
+ os <- Sys.info()["sysname"]
4
+ if (os == "Linux") {
5
+ meminfo <- readLines("/proc/meminfo")
6
+ total_line <- grep("MemTotal:", meminfo)
7
+ total_kb <- as.numeric(gsub("[^0-9]", "", meminfo[total_line]))
8
+ return(total_kb / 1024^2)
9
+ } else if (os == "Darwin") {
10
+ total_bytes <- as.numeric(system("sysctl -n hw.memsize", intern = TRUE))
11
+ return(total_bytes / 1024^3)
12
+ } else if (os == "Windows") {
13
+ mem_lines <- system("wmic MemoryChip get Capacity", intern = TRUE)
14
+ capacities <- as.numeric(mem_lines[grepl("^[0-9]+$", trimws(mem_lines))])
15
+ total_bytes <- sum(capacities)
16
+ return(total_bytes / 1024^3)
17
+ } else {
18
+ stop("Unsupported OS")
19
+ }
20
+ }
21
+ }
code/lib/call_CI_Conf_5k_3yr_unitFE.R ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Unit FE analysis
2
+ {
3
+ {
4
+ input_df$IWI <- input_df$iwi_est_post_oda
5
+ input_df[input_df$dhs_id==sample(input_df$dhs_id,1),c(
6
+ "dhs_id","year_group","treated","IWI")]
7
+
8
+ input_noNAs <- na.omit(input_df[, c("dhs_id", "first_year_group", "iwi_est_post_oda", "treated", "adm2")])
9
+ library(plm);library(clubSandwich);library(sandwich);library(lmtest)
10
+ pdata <- pdata.frame(input_noNAs, index = c("dhs_id","first_year_group"))
11
+ demeaned_est <- plm(iwi_est_post_oda ~ treated,
12
+ effect = "twoways",
13
+ data = pdata, model = "within")
14
+ summary(demeaned_est) # treated 0.63017 0.10251 6.1476 8.058e-10 ***
15
+
16
+ # For the main model
17
+ vcov_main <- vcovCR(demeaned_est, cluster = pdata$adm2, type = "CR1") # CR1 is a common finite-sample correction; alternatives: CR0, CR2, CR3
18
+ coeftest_main <- coeftest(demeaned_est, vcov = vcov_main)
19
+
20
+ # write to disk
21
+ write.csv(file = sprintf("./%s/%s_unitFE%s.csv",results_dir, fund_sect_param, robust_params$suffix),
22
+ cbind("fund_sect_param"=fund_sect_param,
23
+ "time_approach"=time_approach,
24
+ "vision_backbone"=vision_backbone,
25
+ "X_approach"=X_approach,
26
+ "run"=run,
27
+ "Estimate" = coeftest_main[1],
28
+ "SE" = coeftest_main[2]
29
+ ))
30
+ print("Done with unit FE estimation!")
31
+ }
32
+ }
code/lib/chart_dhs_projs.R ADDED
@@ -0,0 +1,173 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ################################################################################
2
+ # chart_dhs.R: charts and descriptive stats on dhs points and their intersection
3
+ # with projects by sector
4
+ ################################################################################
5
+ setwd(getOption("replication.root", default = getwd())); options(error = NULL)
6
+ library(dplyr)
7
+ library(tidyr)
8
+ library(ggplot2)
9
+
10
+ KeepObjectsAcrossAnalysisStrings <- get0("KeepObjectsAcrossAnalysisStrings", ifnotfound = character())
11
+ try(rm(list=ls()[!ls() %in% (Keeps <- c("t0",KeepObjectsAcrossAnalysisStrings))] ),T)
12
+
13
+ #get dhs treatment/control counts for actual (not estimated) DHS points
14
+ treat_control_actual_dhs_df <- read.csv("./data/interim/dhs_treat_control_3yr_actual_counts.csv")
15
+
16
+ ###########################################################
17
+ #calc dhs treatment/control counts for estimated DHS points
18
+ ###########################################################
19
+ ##### read confounder and treatment data from files
20
+ dhs_confounders_df <- read.csv("./data/interim/dhs_5k_confounders.csv") %>%
21
+ dplyr::select(-year) #remove survey year column that could be confused with oda year
22
+
23
+ #get list of all dhs_id's and their iso3 for use below from confounder set
24
+ #since those without confounder data are not usable
25
+ dhs_iso3_df <- dhs_confounders_df %>%
26
+ distinct(dhs_id,iso3)
27
+
28
+ #get treated for all funders and sectors
29
+ dhs_t_df <- read.csv("./data/interim/dhs_treated_sector_3yr.csv") %>%
30
+ #exclude DHS points where confounder data not available
31
+ inner_join(dhs_confounders_df %>%
32
+ dplyr::select(dhs_id, ID_adm2), by = join_by(dhs_id)) %>%
33
+ filter(year_group!="2014:2016")
34
+
35
+ ##### calculate control points #############################
36
+ #identify countries where each funder is operating in each sector
37
+ funder_sector_iso3 <- dhs_t_df %>%
38
+ #join to dhs_confounders to get iso3 and limit to dhs points with confounder data
39
+ inner_join(dhs_confounders_df, by="dhs_id") %>%
40
+ distinct(funder,sector,iso3)
41
+
42
+ #create a record for each year_group for panel data
43
+ year_group_v <- c('2002:2004', '2005:2007', '2008:2010', '2011:2013')
44
+
45
+ #generate dataframe of all dhs points for all year groups in operating countries
46
+ all_t_c_df <- funder_sector_iso3 %>%
47
+ #create a row for each year group
48
+ crossing(year_group = year_group_v) %>%
49
+ #create a row for each dhs_id
50
+ left_join(dhs_iso3_df,by="iso3",
51
+ multiple = "all")
52
+
53
+ #remove treated funder/sector/dhs/year_group observations to construct controls
54
+ dhs_c_df <- all_t_c_df %>%
55
+ #exclude dhs_points treated in each year_group
56
+ anti_join(dhs_t_df,by=c("sector","funder","dhs_id","year_group"))
57
+
58
+ treat_dhs_count_df <- dhs_t_df %>%
59
+ group_by(funder,sector) %>%
60
+ summarize(treat_n = n()) %>%
61
+ ungroup()
62
+
63
+ control_dhs_count_df <- dhs_c_df %>%
64
+ group_by(funder,sector) %>%
65
+ summarize(control_n = n()) %>%
66
+ ungroup()
67
+
68
+ #join control and treated into a single dataframe
69
+ treat_control_est_dhs_df <- treat_dhs_count_df %>%
70
+ left_join(control_dhs_count_df, by=c("funder","sector")) %>%
71
+ rename(est_iwi_treat_n = treat_n,
72
+ est_iwi_control_n = control_n)
73
+
74
+ #join with t/c counts from actual IWI DHS locations rather than estimates
75
+ t_c_est_act_df <- treat_control_est_dhs_df %>%
76
+ left_join(treat_control_actual_dhs_df, by=c("funder","sector")) %>%
77
+ rename(act_iwi_treat_n = treat_n,
78
+ act_iwi_control_n = control_n) %>%
79
+ mutate(act_iwi_treat_n = ifelse(is.na(act_iwi_treat_n),0,act_iwi_treat_n),
80
+ act_iwi_control_n = ifelse(is.na(act_iwi_control_n),0,act_iwi_control_n))
81
+
82
+ write.csv(t_c_est_act_df,"./tables/dhs_treat_control_est_act_compare.csv",row.names=FALSE)
83
+
84
+ #adjust for display
85
+ sector_names_df <- read.csv("./data/interim/sector_group_names.csv") %>%
86
+ mutate(sec_pre_name = paste0(ad_sector_names," (",ad_sector_codes,")")) %>%
87
+ dplyr::select(ad_sector_codes, sec_pre_name)
88
+
89
+ t_c_est_act_display_df <- t_c_est_act_df %>%
90
+ left_join(sector_names_df,join_by(sector==ad_sector_codes)) %>%
91
+ pivot_longer(
92
+ cols = c(est_iwi_treat_n, est_iwi_control_n, act_iwi_treat_n, act_iwi_control_n),
93
+ names_to = "count_name",
94
+ values_to = "count_obs"
95
+ ) %>%
96
+ unite("funder_count_name", funder, count_name, sep = "_") %>%
97
+ pivot_wider(
98
+ names_from = funder_count_name,
99
+ values_from = count_obs
100
+ ) %>%
101
+ dplyr::select(-sector)
102
+
103
+ #write display version
104
+ write.csv(t_c_est_act_display_df,"./tables/dhs_treat_control_est_act_display.csv",row.names=FALSE)
105
+
106
+ #################################################################################
107
+ #xy plots to compare treated and control n for actual and estimated wealth
108
+ #################################################################################
109
+
110
+ #determine the limits of the plot
111
+ max_abs_value <- max(abs(t_c_est_act_df$est_iwi_treat_n),
112
+ abs(t_c_est_act_df$act_iwi_treat_n),
113
+ na.rm=T)
114
+
115
+ treated_est_act <- t_c_est_act_df %>%
116
+ ggplot(aes(x = act_iwi_treat_n, y = est_iwi_treat_n, color=funder,
117
+ label=sector)) +
118
+ geom_point() +
119
+ ggrepel::geom_text_repel(box.padding = .1,max.overlaps=Inf,show.legend=FALSE) +
120
+ scale_color_manual(name = "Funder",
121
+ values = c("ch"="indianred1","wb"="mediumblue"),
122
+ labels = c("China","World Bank")) +
123
+ geom_abline(intercept=0, slope=1, linetype="dashed",color="gray80") +
124
+ labs(title = "Treated Observations: Actual DHS Versus Estimated Wealth Outcomes\nBy Funder and Sector Number",
125
+ x = "Actual DHS Wealth Data Treated Number (Cross-Sectional Data)",
126
+ y = "Estimated Wealth Data Treated Number (Panel Data)",
127
+ legend = "Funder") +
128
+ coord_cartesian(xlim=c(0,max_abs_value),
129
+ ylim=c(0,max_abs_value)) +
130
+ theme_bw() +
131
+ theme(panel.grid = element_blank())
132
+
133
+ #save
134
+ ggsave("./figures/xy_treated_n_est_act.pdf",
135
+ treated_est_act,
136
+ width=8, height = 6, dpi=300,
137
+ bg="white", units="in")
138
+
139
+
140
+ #determine the limits of the plot
141
+ max_abs_value_tc <- max(abs(t_c_est_act_df$est_iwi_treat_n),
142
+ abs(t_c_est_act_df$act_iwi_treat_n),
143
+ abs(t_c_est_act_df$est_iwi_control_n),
144
+ abs(t_c_est_act_df$act_iwi_control_n),
145
+ na.rm=T)
146
+
147
+ t_c_est_act_fig <- t_c_est_act_df %>%
148
+ pivot_longer(cols=starts_with("est"),names_to="var_est",values_to="estimated_n") %>%
149
+ mutate(var=ifelse(grepl("_iwi_treat_n",var_est),"Treated","Control")) %>%
150
+ dplyr::select(-var_est) %>%
151
+ mutate(actual_n=ifelse(var=="Treated",act_iwi_treat_n,act_iwi_control_n)) %>%
152
+ dplyr::select(-act_iwi_treat_n,-act_iwi_control_n ) %>%
153
+ ggplot(aes(x = actual_n, y = estimated_n, color=funder,
154
+ label=sector)) +
155
+ facet_wrap(var ~ funder,scales="free",
156
+ labeller=labeller(funder=c("ch"="China","wb"="World Bank"))) +
157
+ geom_point(show.legend=FALSE) +
158
+ ggrepel::geom_text_repel(box.padding = .1,max.overlaps=Inf,show.legend=FALSE) +
159
+ scale_color_manual(values = c("ch"="indianred1","wb"="mediumblue"),
160
+ labels = c("China","World Bank")) +
161
+ geom_abline(intercept=0, slope=1, linetype="dashed",color="gray80") +
162
+ labs(title = "Observation Number With Actual DHS Versus Estimated Wealth Outcomes\nBy Funder and Sector Number",
163
+ x = "Actual DHS Wealth Data Observations (Cross-Sectional Data)",
164
+ y = "Estimated Wealth Data Observations (Panel Data)",
165
+ legend = "Funder") +
166
+ theme_bw() +
167
+ theme(panel.grid = element_blank())
168
+
169
+ #save
170
+ ggsave("./figures/xy_cntrl_treated_n_est_act.pdf",
171
+ t_c_est_act_fig,
172
+ width=8, height = 8, dpi=300,
173
+ bg="white", units="in")
code/lib/chart_projects.R ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ################################################################################
2
+ # chart_projects.R: charts and descriptive stats on projects
3
+ ################################################################################
4
+ library(dplyr)
5
+ library(ggplot2)
6
+
7
+ KeepObjectsAcrossAnalysisStrings <- get0("KeepObjectsAcrossAnalysisStrings", ifnotfound = character())
8
+ rm(list=ls()[!ls() %in% (Keeps <- c("t0",KeepObjectsAcrossAnalysisStrings))] )
9
+ setwd(getOption("replication.root", default = getwd()))
10
+
11
+ #read consolidated project list
12
+ oda_df <- read.csv("./data/interim/africa_oda_sector_group.csv") %>%
13
+ filter(transactions_start_year >= 2002 &
14
+ transactions_start_year <= 2013 )
15
+
16
+ ### Project counts by year and funder
17
+ proj_year_count <- oda_df %>%
18
+ group_by(funder, transactions_start_year) %>%
19
+ count() %>%
20
+ ggplot(aes(x = transactions_start_year, y = n, fill = funder)) +
21
+ geom_bar(stat = "identity", position = "dodge") +
22
+ labs(title = "African aid by start year and funder",
23
+ x = "Transaction Start Year", y = "Project Count") +
24
+ theme_bw() +
25
+ theme(panel.grid = element_blank()) +
26
+ scale_x_continuous(breaks = unique(oda_df$transactions_start_year),
27
+ labels = unique(oda_df$transactions_start_year)) +
28
+ guides(fill = guide_legend(title = "Funder")) +
29
+ theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
30
+ scale_fill_manual(values = c("CH" = "indianred1", "WB" = "mediumblue"),
31
+ labels = c("China","World Bank"))
32
+
33
+ ggsave("./figures/proj_year_counts.png",proj_year_count, width=6, height = 4, dpi=300,
34
+ bg="white", units="in")
35
+
36
+
37
+ # proj_year_prec_count <- oda_df %>%
38
+ # group_by(funder, transactions_start_year, precision_code) %>%
39
+ # count() %>%
40
+ # ggplot(aes(x = transactions_start_year, y = n, fill = funder, alpha=precision_code/4)) +
41
+ # geom_bar(stat = "identity", position = "dodge",color = "black", width = 0.7) +
42
+ # labs(title = "Count of African aid projects by start year",
43
+ # x = "Transaction Start Year", y = "Count") +
44
+ # theme_minimal() +
45
+ # scale_x_continuous(breaks = unique(oda_df$transactions_start_year),
46
+ # labels = unique(oda_df$transactions_start_year)) +
47
+ # guides(fill = guide_legend(title = "Funder"),
48
+ # alpha = guide_legend(title= "Precision Code")) +
49
+ # scale_alpha_continuous(breaks=c(.25,.5,.75,1),labels = c("1 Exact", "2 Near", "3 ADM2", "4 ADM1")) +
50
+ # theme(axis.text.x = element_text(angle = 45, hjust = 1))
51
+
52
+ ### Project counts by year, funder, and precision
53
+ proj_year_prec_count <- oda_df %>%
54
+ group_by(funder, transactions_start_year, precision_code) %>%
55
+ count() %>%
56
+ ggplot(aes(x = transactions_start_year, y = n, fill = funder, alpha = factor(precision_code/4))) +
57
+ geom_bar(stat = "identity", position = position_dodge(width = .9), width = 0.7) +
58
+ labs(title = "African aid project location counts by start year and precision",
59
+ x = "Transaction Start Year", y = "Count") +
60
+ theme_bw() +
61
+ theme(panel.grid = element_blank()) +
62
+ scale_x_continuous(breaks = unique(oda_df$transactions_start_year),
63
+ labels = unique(oda_df$transactions_start_year)) +
64
+ guides(fill = guide_legend(title = "Funder"),
65
+ alpha = guide_legend(title = "Precision Code")) +
66
+ scale_alpha_manual(values = c(1, 0.75, 0.5, 0.25),
67
+ labels = c("1 Exact", "2 Near", "3 ADM2", "4 ADM1")) +
68
+ theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
69
+ scale_fill_manual(values = c("CH" = "indianred1", "WB" = "mediumblue"),
70
+ labels = c("China","World Bank"))
71
+
72
+
73
+ ggsave("./figures/proj_year_prec_counts.png",proj_year_prec_count, width=6, height = 4, dpi=300,
74
+ bg="white", units="in")
75
+
76
+ ### Project Precision Counts
77
+ proj_prec_count <- oda_df %>%
78
+ group_by(funder, precision_code) %>%
79
+ count() %>%
80
+ ggplot(aes(x = factor(precision_code), y = n, fill = funder)) +
81
+ geom_bar(stat = "identity", position = "dodge") +
82
+ labs(title = "African aid project location counts by precision and funder",
83
+ x = "Precision Code", y = "Project location count") +
84
+ theme_bw() +
85
+ theme(panel.grid = element_blank()) +
86
+ guides(fill = guide_legend(title = "Funder"),
87
+ alpha = guide_legend(title = "Precision Code")) +
88
+ scale_x_discrete(labels = c("1 Exact", "2 Near", "3 ADM2", "4 ADM1")) +
89
+ theme(axis.text.x = element_text(angle = 45, hjust = 1)) +
90
+ scale_fill_manual(values = c("CH" = "indianred1", "WB" = "mediumblue"),
91
+ labels = c("China","World Bank"))
92
+
93
+ ggsave("./figures/proj_prec_counts.png", proj_prec_count, width = 6, height = 4, dpi = 300,
94
+ bg = "white", units = "in")
95
+
96
+
97
+ oda_df %>%
98
+ filter(precision_code %in% c(1,3)) %>%
99
+ group_by(funder, location_type_name, location_type_code, geographic_exactness) %>%
100
+ count() %>%
101
+ filter(geographic_exactness==2)
102
+ #The only records with "approximate" are Chinese ADM2, 3, or 4 projects.
103
+ # funder location_type_name location_type_code geographic_exactness n
104
+ # <chr> <chr> <chr> <int> <int>
105
+ # 1 CH fourth-order administrative division ADM4 2 2
106
+ # 2 CH second-order administrative division ADM2 2 45
107
+ # 3 CH third-order administrative division ADM3 2 4
108
+
109
+
110
+ ### Location Type Codes
111
+ #plot top location type codes
112
+ loc_type_plot <- oda_df %>%
113
+ filter(precision_code %in% c(1,3)) %>%
114
+ group_by(funder, location_type_name, location_type_code, geographic_exactness) %>%
115
+ count() %>%
116
+ filter(n > 10) %>%
117
+ mutate(geographic_exactness = factor(geographic_exactness / 2)) %>%
118
+ ggplot(aes(y = reorder(location_type_name,n), x = n, fill = funder, alpha=geographic_exactness)) +
119
+ #geom_bar(stat = "identity", position = "dodge") +
120
+ geom_bar(stat = "identity", position = position_dodge(width = .9), width = 0.7) +
121
+ labs(title = "Most Frequent Location Types (n>10)",
122
+ subtitle = "Aid Project Precision 1 or 3",
123
+ y = "Location Type", x = "Count") +
124
+ theme_bw() +
125
+ theme(panel.grid = element_blank()) +
126
+ guides(fill = guide_legend(title = "Funder"),
127
+ alpha = guide_legend(title = "Geographic Exactness")) +
128
+ scale_alpha_manual(values = c(.5, 1),
129
+ labels = c("1 Exact", "2 Approximate")) +
130
+ scale_fill_manual(values = c("CH" = "indianred1", "WB" = "mediumblue"),
131
+ labels = c("China", "World Bank"))
132
+
133
+ ggsave("./figures/top_loc_types.png",loc_type_plot, width=6, height = 4, dpi=300,
134
+ bg="white", units="in")
135
+
136
+ ### Count by Country
137
+ country_plot <- oda_df %>%
138
+ filter(precision_code %in% c(1,2,3)) %>%
139
+ group_by(funder, recipients) %>%
140
+ count() %>%
141
+ ggplot(aes(y = recipients, x = n, fill = funder)) +
142
+ geom_bar(stat = "identity", position = "dodge") +
143
+ labs(title = "Aid projects by recipients and funder",
144
+ subtitle = "Aid Project Precision 1, 2, and 3",
145
+ y = "Recipient(s)", x = "Count") +
146
+ theme_bw() +
147
+ theme(panel.grid = element_blank()) +
148
+ guides(fill = guide_legend(title = "Funder")) +
149
+ scale_fill_manual(values = c("CH" = "indianred1", "WB" = "mediumblue"),
150
+ labels = c("China", "World Bank"))
151
+
152
+ ggsave("./figures/country_counts.png",country_plot, width=6, height = 8, dpi=300,
153
+ bg="white", units="in")
154
+
155
+ ### Count by Sector
156
+ sector_plot <- oda_df %>%
157
+ filter(precision_code %in% c(1,2,3)) %>%
158
+ group_by(funder, ad_sector_names) %>%
159
+ mutate(ad_sector_names = paste0(substr(ad_sector_names, 1, 30),
160
+ " (",ad_sector_codes,")")) %>%
161
+ count() %>%
162
+ ggplot(aes(y = ad_sector_names, x = n, fill = funder)) +
163
+ geom_bar(stat = "identity", position = "dodge") +
164
+ labs(title = "African Aid projects 2002-2013 by sector and funder",
165
+ subtitle = "Aid Project Precisions: Exact, Near, and ADM2",
166
+ y = "Sector", x = "Count") +
167
+ theme_bw() +
168
+ theme(panel.grid = element_blank()) +
169
+ guides(fill = guide_legend(title = "Funder")) +
170
+ scale_fill_manual(values = c("CH" = "indianred1", "WB" = "mediumblue"),
171
+ labels = c("China", "World Bank"))
172
+
173
+ ggsave("./figures/sector_counts.png",sector_plot, width=8, height = 8, dpi=300,
174
+ bg="white", units="in")
175
+
176
+
177
+ ### Project length by sector
178
+ sector_length_plot <- oda_df %>%
179
+ filter(precision_code %in% c(1,2,3)) %>%
180
+ mutate(start_year=as.integer(sub("^(\\d{4})-.*","\\1",start_actual_isodate)),
181
+ end_year=as.integer(sub("^(\\d{4})-.*","\\1",end_actual_isodate)),
182
+ proj_length = ifelse(is.na(end_year) | is.na(start_year),-1,
183
+ end_year - start_year)) %>%
184
+ mutate(ad_sector_names = paste0(substr(ad_sector_names, 1, 30),
185
+ " (",ad_sector_codes,")")) %>%
186
+ group_by(funder, ad_sector_names, proj_length) %>%
187
+ ggplot(aes(y = ad_sector_names, x = proj_length, color = funder)) +
188
+ geom_boxplot(outlier.color=NULL) +
189
+ geom_vline(xintercept=0,color="gray80") +
190
+ labs(title = "African aid project length (years) by Sector and Funder (2002-2013)",
191
+ subtitle = "Includes only projects of precisions: Exact, Near, and ADM2",
192
+ y = "Sector", x = "Project Length (Years, -1 = Unknown end date)") +
193
+ theme_bw() +
194
+ theme(panel.grid = element_blank()) +
195
+ guides(color = guide_legend(title = "Funder")) +
196
+ scale_color_manual(values = c("CH" = "indianred1", "WB" = "mediumblue"),
197
+ labels = c("China", "World Bank")) +
198
+ scale_x_continuous(n.breaks=14)
199
+
200
+ ggsave("./figures/sector_proj_length.png",sector_length_plot, width=10, height = 8, dpi=300,
201
+ bg="white", units="in")
code/lib/consolidate_CI_output_across_did.R ADDED
@@ -0,0 +1,139 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ #consolidate_CI_output_across_runs.R
3
+ # install.packages("~/Documents/causalimages-software/causalimages",repos = NULL, type = "source",force = F)
4
+ # install.packages("~/Documents/helpeRs-software/helpeRs",repos = NULL, type = "source",force = F)
5
+ # consolidate .csv files produced by AnalyzeCausalImages runs (after 9/9)
6
+ # into a single csv
7
+ # v4 makes graphs for Latitude Analysis and ModelEvaluationMetrics
8
+ # parameter: run version ("v9","v10",etc)
9
+ KeepObjectsAcrossAnalysisStrings <- get0("KeepObjectsAcrossAnalysisStrings", ifnotfound = character())
10
+ try(rm(list=ls()[!ls() %in% (Keeps <- c("t0",KeepObjectsAcrossAnalysisStrings))] ),T)
11
+
12
+ # set wd and load packages
13
+ setwd(getOption("replication.root", default = getwd())); options(error = NULL)
14
+
15
+ # load packages
16
+ library(dplyr);library(data.table);library(ggplot2);library(ggtext);library(tidyr)
17
+
18
+ results_dir <- get0(
19
+ "WITHIN_UNIT_RESULTS_DIR_OVERRIDE",
20
+ ifnotfound = "./results/per_run_csv/Epoch5EarlyStopNewTreatDefLabelS_Run2/vt_3yr_unitFE/"
21
+ )
22
+ output_file <- get0(
23
+ "WITHIN_UNIT_OUTPUT_OVERRIDE",
24
+ ifnotfound = file.path(dirname(results_dir), "results_processed",
25
+ "wb_vs_ch_sector_scatter_WithinUnitVar.pdf")
26
+ )
27
+ plot_caption <- get0("WITHIN_UNIT_CAPTION_OVERRIDE",
28
+ ifnotfound = "Estimation method: Unit FE.")
29
+ csvs <- list.files(results_dir)
30
+ csvs <- csvs[grepl(csvs,pattern="\\.csv")]
31
+ csvs <- csvs[!grepl("^InputData_", csvs)]
32
+ csvs <- csvs[grepl("unitFE.*\\.csv$", csvs)]
33
+ my_df <- c(); for(csv in csvs){
34
+ #my_df <- rbind(my_df, read.csv(sprintf("./results/did/%s",csv)))
35
+ my_df <- rbind(my_df, read.csv(sprintf("%s/%s",results_dir, csv)))
36
+ }
37
+
38
+ # ---- Packages ----
39
+ # If needed: install.packages(c("dplyr","tidyr","ggplot2","ggrepel"))
40
+ library(dplyr)
41
+ library(tidyr)
42
+ library(ggplot2)
43
+ library(ggrepel)
44
+
45
+ # ---- Prep: normalize the fund-sector column name ----
46
+ df <- my_df
47
+ if ("fund_sect_param" %in% names(df)) {
48
+ df$fund_sect_str <- df$fund_sect_param
49
+ } else if ("fund_sect" %in% names(df)) {
50
+ df$fund_sect_str <- df$fund_sect
51
+ } else {
52
+ stop("Expected a 'fund_sect_param' or 'fund_sect' column with values like 'ch_110'/'wb_110'.")
53
+ }
54
+
55
+ # If CI bounds aren't present, derive 95% CI from SE
56
+ if (!("LB.CI" %in% names(df)) && ("SE" %in% names(df))) {
57
+ df$LB.CI <- df$Estimate - 1.96 * df$SE
58
+ }
59
+ if (!("UB.CI" %in% names(df)) && ("SE" %in% names(df))) {
60
+ df$UB.CI <- df$Estimate + 1.96 * df$SE
61
+ }
62
+
63
+ # df[df$fund_sect_param %in% c("wb_150","wb_310"),]
64
+
65
+ # ---- Extract prefix (ch/wb) and sector code ----
66
+ df2 <- df %>%
67
+ mutate(prefix = sub("_.*$", "", fund_sect_str),
68
+ sector_code = as.integer(sub("^.*_", "", fund_sect_str))) %>%
69
+ filter(prefix %in% c("ch", "wb"))
70
+
71
+ # ---- Resolve duplicates per (prefix, sector_code) if any ----
72
+ # Keep the row with the largest N for stability; adjust if you prefer another rule.
73
+ df2_unique <- df2 %>%
74
+ #arrange(desc(N)) %>%
75
+ arrange(desc(SE)) %>%
76
+ group_by(prefix, sector_code) %>%
77
+ slice(1) %>%
78
+ ungroup()
79
+
80
+ # ---- Pivot wide: one row per sector with CH & WB side-by-side ----
81
+ wide <- df2_unique %>%
82
+ dplyr::select(prefix, sector_code, Estimate, LB.CI, UB.CI) %>%
83
+ tidyr::pivot_wider(
84
+ names_from = prefix,
85
+ values_from = c(Estimate, LB.CI, UB.CI),
86
+ names_sep = "."
87
+ ) %>%
88
+ dplyr::rename(
89
+ ch_est = Estimate.ch, ch_lb = LB.CI.ch, ch_ub = UB.CI.ch,
90
+ wb_est = Estimate.wb, wb_lb = LB.CI.wb, wb_ub = UB.CI.wb
91
+ ) %>%
92
+ dplyr::filter(!is.na(ch_est), !is.na(wb_est)) %>%
93
+ dplyr::arrange(sector_code)
94
+
95
+ if(FALSE){ wide <- df2_unique %>%
96
+ select(prefix, sector_code, Estimate, LB.CI, UB.CI) %>%
97
+ pivot_wider(
98
+ names_from = prefix,
99
+ values_from = c(Estimate, LB.CI, UB.CI),
100
+ names_sep = "."
101
+ ) %>%
102
+ rename(
103
+ ch_est = Estimate.ch, ch_lb = LB.CI.ch, ch_ub = UB.CI.ch,
104
+ wb_est = Estimate.wb, wb_lb = LB.CI.wb, wb_ub = UB.CI.wb
105
+ ) %>%
106
+ filter(!is.na(ch_est), !is.na(wb_est)) %>%
107
+ arrange(sector_code)
108
+ }
109
+
110
+ # ---- Plot: Y = China vs X = World Bank; 95% CI crosshairs ----
111
+ p <- ggplot(wide, aes(x = wb_est, y = ch_est, label = sector_code)) +
112
+ # horizontal CI for WB (x)
113
+ geom_errorbarh(aes(xmin = wb_lb, xmax = wb_ub),
114
+ height = 0, alpha = 0.25, linewidth = 0.6) +
115
+ # vertical CI for CH (y)
116
+ geom_errorbar(aes(ymin = ch_lb, ymax = ch_ub),
117
+ width = 0, alpha = 0.25, linewidth = 0.6) +
118
+ geom_point(size = 2) +
119
+ geom_abline(slope = 1, intercept = 0, linetype = "dashed", linewidth = 0.4, alpha = 0.7) +
120
+ ggrepel::geom_text_repel(size = 3, max.overlaps = 50) +
121
+ coord_equal() +
122
+ labs(
123
+ title = "Sector ATT estimates: China vs. World Bank",
124
+ subtitle = "Each point is a sector code; crosshairs show 95% CIs",
125
+ x = "World Bank estimate (95% CI)",
126
+ y = "China estimate (95% CI)",
127
+ caption = plot_caption
128
+ ) +
129
+ geom_hline(yintercept = 0, linetype = "dashed", color = "gray60", linewidth = 0.3) +
130
+ geom_vline(xintercept = 0, linetype = "dashed", color = "gray60", linewidth = 0.3) +
131
+ theme_minimal(base_size = 18) +
132
+ theme(panel.grid = element_blank()) # Removes background gridding
133
+
134
+ print(p)
135
+
136
+ # ---- Optional: save to file ----
137
+ ggsave(output_file,
138
+ p, width = 8, height = 8, dpi = 300)
139
+ }
code/lib/consolidate_CI_output_across_runs.R ADDED
The diff for this file is too large to render. See raw diff
 
code/lib/optional/get_images/GetImageRun_3y.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script: GetImageRun_3y.py
4
+ Orchestrates Google Earth Engine exports for DHS cluster points.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as dt
10
+ import os
11
+ from pathlib import Path
12
+ import pandas as pd
13
+ import ee
14
+
15
+ # Local package
16
+ from satellite_sampling_5k_3y_ctj import export_images
17
+
18
+ # --------------------------------------------------------------------------- #
19
+ # Configuration #
20
+ # --------------------------------------------------------------------------- #
21
+ ROOT_DIR = os.environ.get(
22
+ 'IMAGEDECONFOUND_REPLICATION_ROOT',
23
+ str(Path(__file__).resolve().parents[3])
24
+ )
25
+ INTERIM_DATA_DIR = os.path.join(ROOT_DIR, 'data', 'interim')
26
+ DATA_DIR = os.environ.get(
27
+ 'IMAGEDECONFOUND_IMAGE_DOWNLOAD_ROOT',
28
+ os.path.join(ROOT_DIR, 'external_artifacts', 'images')
29
+ )
30
+ DHS_FILE = os.path.join(INTERIM_DATA_DIR, 'dhs_est_iwi.csv')
31
+
32
+ SPAN_LENGTH_YRS = 3 # each frame is a 3‑year composite
33
+ NUM_WORKERS = 8 # concurrent EE tasks to launch
34
+
35
+ # --------------------------------------------------------------------------- #
36
+ # Helper #
37
+ # --------------------------------------------------------------------------- #
38
+
39
+ def _already_downloaded(row: pd.Series, folder: str, min_bytes: int = 2_600_000) -> bool:
40
+ """True iff the expected .tif exists and is larger than the safety margin."""
41
+ tif = os.path.join(folder, f"{row['dhs_id']}.tif")
42
+ return os.path.isfile(tif) and os.stat(tif).st_size > min_bytes
43
+
44
+ # --------------------------------------------------------------------------- #
45
+ # Main #
46
+ # --------------------------------------------------------------------------- #
47
+
48
+ def main() -> None:
49
+ os.chdir(ROOT_DIR) # keep relative paths tidy
50
+
51
+ # ---- GEE session ------------------------------------------------------- #
52
+ ee.Authenticate() # cached after first run
53
+ ee.Initialize(opt_url='https://earthengine-highvolume.googleapis.com')
54
+
55
+ # ---- Load DHS clusters -------------------------------------------------- #
56
+ df = pd.read_csv(DHS_FILE)
57
+ grouped = df.groupby(['country', 'year'])
58
+
59
+ for (country, year), survey_df in grouped:
60
+ ts = dt.datetime.now().strftime('%d.%b %Y %H:%M:%S')
61
+ print(f'Downloading images for {country}-{year} … {ts}')
62
+
63
+ out_dir = os.path.join(DATA_DIR,
64
+ f'dhs_tifs_5k_3yr/{country}_{year}')
65
+ os.makedirs(out_dir, exist_ok=True)
66
+
67
+ mask = ~survey_df.apply(_already_downloaded, axis=1, folder=out_dir)
68
+ to_do = survey_df[mask]
69
+
70
+ if to_do.empty:
71
+ print(f' ✓ all {len(survey_df)} tiles already present')
72
+ continue
73
+
74
+ export_images(to_do, out_dir,
75
+ span_length=SPAN_LENGTH_YRS,
76
+ num_workers=NUM_WORKERS)
77
+
78
+
79
+ if __name__ == '__main__': # ***** CRUCIAL for multiprocessing *****
80
+ main()
code/lib/optional/get_images/GetImageRun_annual.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Script: GetImageRun_annual.py
4
+ Orchestrates Google Earth Engine exports for DHS cluster points.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import datetime as dt
10
+ import os
11
+ from pathlib import Path
12
+ import pandas as pd
13
+ import ee
14
+
15
+ # Local package
16
+ from satellite_sampling_5k_annual_ctj import export_images
17
+
18
+ # --------------------------------------------------------------------------- #
19
+ # Configuration #
20
+ # --------------------------------------------------------------------------- #
21
+ ROOT_DIR = os.environ.get(
22
+ 'IMAGEDECONFOUND_REPLICATION_ROOT',
23
+ str(Path(__file__).resolve().parents[3])
24
+ )
25
+ INTERIM_DATA_DIR = os.path.join(ROOT_DIR, 'data', 'interim')
26
+ DATA_DIR = os.environ.get(
27
+ 'IMAGEDECONFOUND_IMAGE_DOWNLOAD_ROOT',
28
+ os.path.join(ROOT_DIR, 'external_artifacts', 'images')
29
+ )
30
+ DHS_FILE = os.path.join(INTERIM_DATA_DIR, 'dhs_est_iwi.csv')
31
+
32
+ SPAN_LENGTH_YRS = 1 # each frame is a X‑year composite
33
+ NUM_WORKERS = 9 # concurrent EE tasks to launch
34
+
35
+ # --------------------------------------------------------------------------- #
36
+ # Helper #
37
+ # --------------------------------------------------------------------------- #
38
+
39
+ def _already_downloaded(row: pd.Series, folder: str, min_bytes: int = 2_600_000) -> bool:
40
+ """True iff the expected .tif exists and is larger than the safety margin."""
41
+ tif = os.path.join(folder, f"{row['dhs_id']}.tif")
42
+ return os.path.isfile(tif) and os.stat(tif).st_size > min_bytes
43
+
44
+ # --------------------------------------------------------------------------- #
45
+ # Main #
46
+ # --------------------------------------------------------------------------- #
47
+
48
+ def main() -> None:
49
+ os.chdir(ROOT_DIR) # keep relative paths tidy
50
+
51
+ # ---- GEE session ------------------------------------------------------- #
52
+ ee.Authenticate() # cached after first run
53
+ ee.Initialize(opt_url='https://earthengine-highvolume.googleapis.com')
54
+
55
+ # ---- Load DHS clusters -------------------------------------------------- #
56
+ df = pd.read_csv(DHS_FILE)
57
+ grouped = df.groupby(['country', 'year'])
58
+
59
+ for (country, year), survey_df in grouped:
60
+ ts = dt.datetime.now().strftime('%d.%b %Y %H:%M:%S')
61
+ print(f'Downloading images for {country}-{year} … {ts}')
62
+
63
+ out_dir = os.path.join(DATA_DIR,
64
+ f'dhs_tifs_annual/{country}_{year}')
65
+ os.makedirs(out_dir, exist_ok=True)
66
+
67
+ mask = ~survey_df.apply(_already_downloaded, axis=1, folder=out_dir)
68
+ to_do = survey_df[mask]
69
+
70
+ if to_do.empty:
71
+ print(f' ✓ all {len(survey_df)} tiles already present')
72
+ continue
73
+
74
+ export_images(to_do, out_dir,
75
+ span_length=SPAN_LENGTH_YRS,
76
+ num_workers=NUM_WORKERS)
77
+
78
+
79
+ if __name__ == '__main__': # ***** CRUCIAL for multiprocessing *****
80
+ main()
code/lib/optional/get_images/gee_exporter_collection2.py ADDED
@@ -0,0 +1,209 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Script: gee_exporter_collection2.py
2
+
3
+ import ee
4
+
5
+ class GeeExporter:
6
+
7
+ NULL_TOKEN = 0
8
+
9
+ def __init__(self, filterpoly: ee.Geometry, start_year: int,
10
+ end_year: int, ms_bands: list,
11
+ include_nl: bool = False) -> None:
12
+ """
13
+ Class for handling Landsat data in GEE
14
+ :param filterpoly: ee.Geometry
15
+ :param start_date: str, string representation of start date
16
+ :param end_date: str, string representation of end date
17
+ :param ms_bands: list of multispectral bands to keep from the collections
18
+ """
19
+ self.filterpoly = filterpoly
20
+ self.start_year = start_year
21
+ self.end_year = end_year
22
+ self.start_date = f'{start_year}-01-01'
23
+ self.end_date = f'{end_year}-12-31'
24
+ self.include_nl = include_nl
25
+
26
+ self.l8 = self.init_coll('LANDSAT/LC08/C02/T1_L2', self.start_date, self.end_date)
27
+ self.l7 = self.init_coll('LANDSAT/LE07/C02/T1_L2', self.start_date, self.end_date)
28
+ self.l5 = self.init_coll('LANDSAT/LT05/C02/T1_L2', self.start_date, self.end_date)
29
+
30
+ self.merged = self.l5.merge(self.l7).merge(self.l8).sort('system:time_start')
31
+ self.merged = self.merged.map(self.mask_qaclear).select(ms_bands)
32
+
33
+ # Adds background to use for missing Landsat images
34
+ background = ee.Image([self.NULL_TOKEN] * len(ms_bands)).rename(ms_bands)
35
+ self.background = background.cast(dict(zip(ms_bands, ['float'] * len(ms_bands))))
36
+
37
+ def init_coll(self, name: str, start_date: str, end_date: str) -> ee.ImageCollection:
38
+ """
39
+ Creates a standardised ee.ImageCollection containing images of desired points
40
+ between the desired start and end dates.
41
+ :param name: str, name of collection
42
+ :param start_date: str, string representation of start date
43
+ :param end_date: str, string representation of end date
44
+ :return: ee.ImageCollection
45
+ """
46
+ img_col = ee.ImageCollection(name).filterBounds(self.filterpoly).filterDate(start_date, end_date)
47
+
48
+ is_landsat_8 = name.startswith('LANDSAT/LC08')
49
+ if is_landsat_8:
50
+ return img_col.map(self.rename_l8).map(self.rescale)
51
+ else:
52
+ return img_col.map(self.rename_l57).map(self.rescale)
53
+
54
+ @staticmethod
55
+ def mask_qaclear(img: ee.Image) -> ee.Image:
56
+ """
57
+ Masks out unusable pixels
58
+ :param img: ee.Image, Landsat 5/7/8 image containing 'QA_PIXEL' band
59
+ :return: ee.Image, input image with cloud-shadow, snow, cloud, and unclear
60
+ pixels masked out
61
+
62
+ Bitmask for QA_PIXEL
63
+ Bit 0: Fill
64
+ Bit 1: Dilated Cloud
65
+ Bit 2: Unused (L5/7) or Cirrus (L8)
66
+ Bit 3: Cloud
67
+ Bit 4: Cloud Shadow
68
+ Bit 5: Snow
69
+ Bit 6: Clear
70
+ 0: Cloud or Dilated Cloud bits are set
71
+ 1: Cloud and Dilated Cloud bits are not set
72
+ Bit 7: Water
73
+ Also has confidence bits, which I am not using here
74
+ """
75
+ # Get the QA_PIXEL band
76
+ qa = img.select('QA_PIXEL')
77
+
78
+ # Create masks for clouds, cloud shadows, and snow
79
+ cloud_mask = qa.bitwiseAnd(1 << 3).Or(qa.bitwiseAnd(1 << 1))
80
+ cloud_shadow_mask = qa.bitwiseAnd(1 << 4)
81
+ snow_mask = qa.bitwiseAnd(1 << 5)
82
+
83
+ # Combine masks
84
+ mask = cloud_mask.Or(cloud_shadow_mask).Or(snow_mask)
85
+
86
+ # Return the image with masked pixels
87
+ return img.updateMask(mask.Not())
88
+
89
+ @staticmethod
90
+ def rename_l8(img: ee.Image) -> ee.Image:
91
+ """
92
+ Renames bands for a Landsat 8 image
93
+ :param img: ee.Image, Landsat 8 image
94
+ :return: ee.Image, with bands renamed
95
+ See: https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LC08_C02_T1_L2
96
+ Name Scale Factor Description
97
+ SR_B1 2.75e-05 Band 1 (ultra blue, coastal aerosol) surface reflectance
98
+ SR_B2 2.75e-05 Band 2 (blue) surface reflectance
99
+ SR_B3 2.75e-05 Band 3 (green) surface reflectance
100
+ SR_B4 2.75e-05 Band 4 (red) surface reflectance
101
+ SR_B5 2.75e-05 Band 5 (near infrared) surface reflectance
102
+ SR_B6 2.75e-05 Band 6 (shortwave infrared 1) surface reflectance
103
+ SR_B7 2.75e-05 Band 7 (shortwave infrared 2) surface reflectance
104
+ several more here - included in newnames as their standard values
105
+ """
106
+ newnames = ['SR_B1', 'BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2',
107
+ 'SR_QA_AEROSOL', 'ST_B10', 'ST_ATRAN', 'ST_CDIST', 'ST_DRAD', 'ST_EMIS',
108
+ 'ST_EMSD', 'ST_QA', 'ST_TRAD', 'ST_URAD', 'QA_PIXEL', 'QA_RADSAT']
109
+ return img.rename(newnames)
110
+
111
+ @staticmethod
112
+ def rename_l57(img: ee.Image) -> ee.Image:
113
+ """
114
+ Renames bands for a Landsat 5/7 image
115
+ :param img: ee.Image, Landsat 5/7 image
116
+ :return: ee.Image, with bands renamed
117
+ See: https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LT05_C02_T1_SR
118
+ https://developers.google.com/earth-engine/datasets/catalog/LANDSAT_LE07_C02_T1_L2
119
+ Name Scale Factor Description
120
+ SR_B1 2.75e-05 Band 1 (blue) surface reflectance
121
+ SR_B2 2.75e-05 Band 2 (green) surface reflectance
122
+ SR_B3 2.75e-05 Band 3 (red) surface reflectance
123
+ SR_B4 2.75e-05 Band 4 (near infrared) surface reflectance
124
+ SR_B5 2.75e-05 Band 5 (shortwave infrared 1) surface reflectance
125
+ SR_B7 2.75e-05 Band 7 (shortwave infrared 2) surface reflectance
126
+ several more here - included in newnames as their standard values
127
+ """
128
+ newnames = ['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2',
129
+ 'SR_ATMOS_OPACITY', 'SR_CLOUD_QA', 'ST_B6', 'ST_ATRAN', 'ST_CDIST',
130
+ 'ST_DRAD', 'ST_EMIS', 'ST_EMSD', 'ST_QA', 'ST_TRAD', 'ST_URAD',
131
+ 'QA_PIXEL', 'QA_RADSAT']
132
+ return img.rename(newnames)
133
+
134
+ @staticmethod
135
+ def rescale(img: ee.Image) -> ee.Image:
136
+ """
137
+ Rescales Landsat 5, 7, or 8 image to common scale
138
+ :param img: ee.Image, Landsat 5/7/8 image, with bands already renamed
139
+ by rename_l57() or rename_l8()
140
+ :return: ee.Image, optical and qa bands only, with bands rescaled
141
+ """
142
+ opt = img.select(['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1', 'SWIR2'])
143
+ masks = img.select(['QA_PIXEL'])
144
+
145
+ opt = opt.multiply(0.0000275)
146
+
147
+ scaled = ee.Image.cat([opt, masks]).copyProperties(img)
148
+ # system properties are not copied
149
+ scaled = scaled.set('system:time_start', img.get('system:time_start'))
150
+ return scaled
151
+
152
+ def get_timeseries_image(self, span_length):
153
+ """
154
+ Produce a sequential collection where each image represents a non-overlapping time period.
155
+ The time series starts at 'start_year', ends at 'end_year' and each image is a composite of
156
+ 'span_length' number of years.
157
+ :param start_year: int, earliest year to include in the time series
158
+ :param end_year: int, last possible year to include in the time series.
159
+ Can be left out depending on the 'span_length'.
160
+ :param span_length: int, number of years for each
161
+ :return: ee.ImageCollection, collection with a time series of images
162
+ """
163
+
164
+ # Create list of tuples containing start and end year for each timespan
165
+ start_years = ee.List.sequence(self.start_year, self.end_year,
166
+ span_length)
167
+ end_years = ee.List.sequence(self.start_year + span_length - 1,
168
+ self.end_year, span_length)
169
+ spans = start_years.zip(end_years)
170
+
171
+ # Define inner function
172
+ def get_span_image(span: ee.List) -> ee.Image:
173
+ """
174
+ Get image with median band values between two dates. Created as an
175
+ inner function of 'get_images' since the GEE API doesn't allow maped
176
+ functions to access client side variables. This is a functional work-
177
+ around.
178
+ :param span: ee.List, tuple containing two integer values representing
179
+ the start and end year of the timespan.
180
+ :return: ee.Image, image representation for the given time period
181
+ """
182
+
183
+ # Excplicilty cast mapped value as list. Extract start and end date
184
+ span = ee.List(span)
185
+ start_date = ee.Date.fromYMD(span.get(0), 1, 1)
186
+ end_date = ee.Date.fromYMD(span.get(1), 12, 31)
187
+
188
+ # Get time span median values for multispectral bands
189
+ #img = self.merged.filterDate(start_date, end_date).median() # ctj edit
190
+ img = self.merged.filterDate(start_date, end_date).median().toFloat() # ctj edit
191
+
192
+ # Add background values for pixel locations without any images
193
+ img = ee.ImageCollection([self.background, img]).mosaic() # orig code
194
+ #img = ee.ImageCollection([img, self.background]).mosaic() # ctj edit
195
+
196
+ # Clip image to remove unnecessary regions
197
+ img = img.clip(self.filterpoly)
198
+
199
+ return img.set('system:time_start', start_date.millis())
200
+
201
+ # Create one image per time span
202
+ span_images = ee.ImageCollection.fromImages(spans.map(get_span_image))
203
+
204
+ # Converts collection of span_images to a single multi-band image
205
+ # containing all of the bands of every span_image in the collection
206
+ out_image = span_images.toBands()
207
+
208
+ return out_image
209
+
code/lib/optional/get_images/satellite_sampling_5k_3y_ctj.py ADDED
@@ -0,0 +1,245 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script: satellite_sampling_5k_3y_v3_cj.py
3
+ Launches parallel Earth-Engine Image → Drive export tasks,
4
+ but first waits for free slots in the EE queue to keep under the 3000-task limit.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import time
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type
13
+ from functools import partial
14
+ import pandas as pd
15
+ import shutil
16
+ import ee
17
+ import requests
18
+ import zipfile
19
+ import random
20
+ import time
21
+ import rasterio
22
+ import errno
23
+
24
+ from gee_exporter_collection2 import GeeExporter
25
+
26
+ # --------------------------------------------------------------------------- #
27
+ # Configuration
28
+ # --------------------------------------------------------------------------- #
29
+ _SCALE = 30
30
+ #_CRS = 'EPSG:4326'
31
+ _CRS = 'EPSG:3857'
32
+ _NUM_WORKERS = 10 # tune to your bandwidth/CPU
33
+ #_MAX_QUEUE_TASKS = 3000 # EE’s hard limit
34
+ _MAX_QUEUE_TASKS = 200 # EE’s hard limit
35
+ _POLL_INTERVAL = 30 # seconds between checks
36
+ _MS_BANDS = ['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1']
37
+
38
+
39
+ def _wait_for_queue_space(slots_needed: int) -> None:
40
+ """Block until at least slots_needed queue slots free up."""
41
+ while True:
42
+ all_tasks = ee.batch.Task.list()
43
+ active = sum(1 for t in all_tasks
44
+ if t.status().get('state') in ('READY','RUNNING'))
45
+ available = _MAX_QUEUE_TASKS - active
46
+
47
+ if available >= slots_needed:
48
+ return
49
+
50
+ print(f"[EE Queue full] {active} tasks in queue (limit {_MAX_QUEUE_TASKS}). "
51
+ f"Need {slots_needed}. Waiting {_POLL_INTERVAL}s…")
52
+ time.sleep(_POLL_INTERVAL)
53
+
54
+
55
+ @retry(
56
+ wait=wait_exponential(multiplier=1, min=10, max=60),
57
+ stop=stop_after_attempt(10),
58
+ retry=retry_if_exception_type((OSError, requests.exceptions.RequestException))
59
+ )
60
+ def write_with_retry(path: str, url: str, chunk_size: int = 1024*1024):
61
+ """
62
+ Download from `url` and safely write to `path` on flaky filesystems.
63
+ Retries on network and local I/O errors (including ESTALE/Timeout).
64
+ """
65
+ # 1) Make sure the containing dir exists
66
+ os.makedirs(os.path.dirname(path), exist_ok=True)
67
+
68
+ tmp_path = path + ".tmp"
69
+ try:
70
+ # 2) Stream‐download
71
+ with requests.get(url, stream=True) as r:
72
+ r.raise_for_status()
73
+ with open(tmp_path, "wb") as f:
74
+ for chunk in r.iter_content(chunk_size):
75
+ f.write(chunk)
76
+
77
+ # 3) Atomic rename into place
78
+ os.replace(tmp_path, path)
79
+
80
+ except OSError as e:
81
+ # Clean up partial tmp file
82
+ try:
83
+ os.remove(tmp_path)
84
+ except Exception:
85
+ pass
86
+
87
+ # Only retry on transient mount errors
88
+ if e.errno in (errno.ESTALE, errno.ETIMEDOUT, errno.EIO):
89
+ raise
90
+ # Otherwise re-raise without retry
91
+ raise
92
+
93
+
94
+ @retry(
95
+ wait=wait_exponential(multiplier=1, min=4, max=60), # Wait 4s to 10s between retries
96
+ stop=stop_after_attempt(10), # Retry up to 5 times
97
+ retry=retry_if_exception_type(requests.exceptions.RequestException)
98
+ )
99
+ def _download_one(row: pd.Series, dst_folder: str, span_len: int) -> int:
100
+ import rasterio
101
+
102
+ time.sleep(random.uniform(1, 5))
103
+ geom = ee.Geometry.Point([row['lon'], row['lat']]).buffer(2_500)
104
+
105
+ # Define the 3-year spans you want, in order:
106
+ spans = [
107
+ (1999, 2001),
108
+ (2002, 2004),
109
+ (2005, 2007),
110
+ (2008, 2010),
111
+ (2011, 2013),
112
+ (2014, 2016),
113
+ ]
114
+
115
+ extracted = {}
116
+ zip_paths = []
117
+
118
+ # Loop over each span, download its ZIP and extract the 5 MS bands
119
+ _wait_for_queue_space(1)
120
+ for span_i, (start_year, end_year) in enumerate(spans):
121
+
122
+ # note: cloud handling, etc. is performed in GeeExporter()
123
+ exporter = GeeExporter(
124
+ filterpoly=geom,
125
+ start_year=start_year,
126
+ end_year=end_year,
127
+ ms_bands=_MS_BANDS
128
+ )
129
+ img = exporter.get_timeseries_image(span_len)
130
+
131
+ try:
132
+ bands = img.bandNames().getInfo()
133
+ except Exception as e:
134
+ print(f" ⚠️ Span {start_year}-{end_year}: failed to fetch band names, skipping. ({e})")
135
+ continue
136
+ if not bands:
137
+ print(f" • Span {start_year}-{end_year}: no data, skipping.")
138
+ continue
139
+
140
+ url = img.getDownloadURL({
141
+ 'scale': _SCALE,
142
+ 'crs': _CRS,
143
+ 'region': geom
144
+ })
145
+ print(f"[DEBUG] Download URL for span {start_year}-{end_year}: {url!r}")
146
+
147
+ zip_path = os.path.join(dst_folder, f"{row['dhs_id']}_{start_year}_{end_year}.zip")
148
+ zip_paths.append(zip_path)
149
+
150
+ # safe write
151
+ write_with_retry(zip_path, url)
152
+
153
+ # unsafe write
154
+ #with requests.get(url, stream=True) as r:
155
+ # r.raise_for_status()
156
+ # with open(zip_path, 'wb') as f:
157
+ # for chunk in r.iter_content(1024*1024):
158
+ # f.write(chunk)
159
+
160
+ # Unzip and save each band as its own TIFF
161
+ with zipfile.ZipFile(zip_path, 'r') as z:
162
+ for member in z.namelist():
163
+ if not member.lower().endswith('.tif'):
164
+ continue
165
+ band_name = os.path.splitext(os.path.basename(member))[0].split('_')[-1].upper()
166
+ if band_name not in _MS_BANDS:
167
+ continue
168
+ dst_tif = os.path.join(
169
+ dst_folder,
170
+ f"{row['dhs_id']}_{start_year}_{end_year}_{band_name}.tif"
171
+ )
172
+ with z.open(member) as src, open(dst_tif, 'wb') as out:
173
+ shutil.copyfileobj(src, out)
174
+ extracted[(span_i, band_name)] = dst_tif
175
+
176
+ if not extracted:
177
+ return None
178
+
179
+ # Build the final multi-band TIFF
180
+ first_key = next(iter(extracted))
181
+ with rasterio.open(extracted[first_key]) as src0:
182
+ meta = src0.meta.copy()
183
+
184
+ num_spans = len(spans)
185
+ ms_count = len(_MS_BANDS)
186
+
187
+ # total bands = spans × ms_bands
188
+ meta.update(count = num_spans * ms_count)
189
+
190
+ out_tif = os.path.join(dst_folder, os.path.basename(row['image_file_5k_3yr']))
191
+ with rasterio.open(out_tif, 'w', **meta) as dst:
192
+ for span_i in range(num_spans):
193
+ for idx, band_name in enumerate(_MS_BANDS, start=1):
194
+ key = (span_i, band_name)
195
+ if key not in extracted:
196
+ continue
197
+ # and write into contiguous slots
198
+ dest_band = span_i * ms_count + idx
199
+ with rasterio.open(extracted[key]) as src:
200
+ dst.write(src.read(1), dest_band)
201
+
202
+ # — quick QC: did we really get the band‐count we asked for?
203
+ with rasterio.open(out_tif) as chk:
204
+ expected = num_spans * ms_count
205
+ if chk.count != expected:
206
+ raise RuntimeError(f"QC failed: expected {expected} bands, got {chk.count}")
207
+
208
+ # Clean up all intermediate files
209
+ for path in extracted.values():
210
+ os.remove(path)
211
+ for zp in zip_paths:
212
+ os.remove(zp)
213
+
214
+ return row.name
215
+
216
+
217
+ def export_images(df: pd.DataFrame,
218
+ save_dir: str,
219
+ span_length: int = 3,
220
+ num_workers: int = _NUM_WORKERS) -> None:
221
+ """
222
+ For each row in df (must have 'lat','lon','year'), builds a
223
+ span_length-year composite and downloads it locally.
224
+
225
+ Parameters
226
+ ----------
227
+ df : pandas.DataFrame with columns 'lat', 'lon', 'year'
228
+ save_dir : directory to write the unzipped TIFF(s)
229
+ span_length : number of years per composite (e.g. 3)
230
+ num_workers : number of parallel download threads
231
+ """
232
+ os.makedirs(save_dir, exist_ok=True)
233
+
234
+ rows = [row for _, row in df.iterrows()]
235
+
236
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
237
+ for idx in executor.map(
238
+ lambda r: _download_one(r, save_dir, span_length),
239
+ rows
240
+ ):
241
+ # Only print if the download succeeded (idx is not None)
242
+ if idx is not None:
243
+ print(f' • Finished download for row {idx:05d}')
244
+
245
+ print(f'Downloaded all {len(rows)} composites into:\n {save_dir}')
code/lib/optional/get_images/satellite_sampling_5k_annual_ctj.py ADDED
@@ -0,0 +1,253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Script: satellite_sampling_5k_annual.py
3
+ Launches parallel Earth-Engine Image → Drive export tasks,
4
+ but first waits for free slots in the EE queue to keep under the 3000-task limit.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import os
10
+ import time
11
+ from concurrent.futures import ThreadPoolExecutor
12
+ from tenacity import retry, wait_exponential, stop_after_attempt, retry_if_exception_type
13
+ from functools import partial
14
+ import pandas as pd
15
+ import shutil
16
+ import ee
17
+ import requests
18
+ import zipfile
19
+ import random
20
+ import time
21
+ import rasterio
22
+ import errno
23
+
24
+ from gee_exporter_collection2 import GeeExporter
25
+
26
+ # --------------------------------------------------------------------------- #
27
+ # Configuration
28
+ # --------------------------------------------------------------------------- #
29
+ _SCALE = 30
30
+ #_CRS = 'EPSG:4326'
31
+ _CRS = 'EPSG:3857'
32
+ _NUM_WORKERS = 10 # tune to your bandwidth/CPU
33
+ #_MAX_QUEUE_TASKS = 3000 # EE’s hard limit
34
+ _MAX_QUEUE_TASKS = 200 # EE’s hard limit
35
+ _POLL_INTERVAL = 30 # seconds between checks
36
+ _MS_BANDS = ['BLUE', 'GREEN', 'RED', 'NIR', 'SWIR1']
37
+
38
+
39
+ def _wait_for_queue_space(slots_needed: int) -> None:
40
+ """Block until at least slots_needed queue slots free up."""
41
+ while True:
42
+ all_tasks = ee.batch.Task.list()
43
+ active = sum(1 for t in all_tasks
44
+ if t.status().get('state') in ('READY','RUNNING'))
45
+ available = _MAX_QUEUE_TASKS - active
46
+
47
+ if available >= slots_needed:
48
+ return
49
+
50
+ print(f"[EE Queue full] {active} tasks in queue (limit {_MAX_QUEUE_TASKS}). "
51
+ f"Need {slots_needed}. Waiting {_POLL_INTERVAL}s…")
52
+ time.sleep(_POLL_INTERVAL)
53
+
54
+
55
+ @retry(
56
+ wait=wait_exponential(multiplier=1, min=10, max=60),
57
+ stop=stop_after_attempt(10),
58
+ retry=retry_if_exception_type((OSError, requests.exceptions.RequestException))
59
+ )
60
+ def write_with_retry(path: str, url: str, chunk_size: int = 1024*1024):
61
+ """
62
+ Download from `url` and safely write to `path` on flaky filesystems.
63
+ Retries on network and local I/O errors (including ESTALE/Timeout).
64
+ """
65
+ # 1) Make sure the containing dir exists
66
+ os.makedirs(os.path.dirname(path), exist_ok=True)
67
+
68
+ tmp_path = path + ".tmp"
69
+ try:
70
+ # 2) Stream‐download
71
+ with requests.get(url, stream=True) as r:
72
+ r.raise_for_status()
73
+ with open(tmp_path, "wb") as f:
74
+ for chunk in r.iter_content(chunk_size):
75
+ f.write(chunk)
76
+
77
+ # 3) Atomic rename into place
78
+ os.replace(tmp_path, path)
79
+
80
+ except OSError as e:
81
+ # Clean up partial tmp file
82
+ try:
83
+ os.remove(tmp_path)
84
+ except Exception:
85
+ pass
86
+
87
+ # Only retry on transient mount errors
88
+ if e.errno in (errno.ESTALE, errno.ETIMEDOUT, errno.EIO):
89
+ raise
90
+ # Otherwise re-raise without retry
91
+ raise
92
+
93
+
94
+ @retry(
95
+ wait=wait_exponential(multiplier=1, min=4, max=60), # Wait 4s to 10s between retries
96
+ stop=stop_after_attempt(10), # Retry up to 5 times
97
+ retry=retry_if_exception_type(requests.exceptions.RequestException)
98
+ )
99
+ def _download_one(row: pd.Series, dst_folder: str, span_len: int) -> int:
100
+ import rasterio
101
+
102
+ time.sleep(random.uniform(1, 5))
103
+ geom = ee.Geometry.Point([row['lon'], row['lat']]).buffer(2_500)
104
+
105
+ # Define the spans you want, in order:
106
+ spans = [
107
+ (2001, 2001),
108
+ (2002, 2002),
109
+ (2003, 2003),
110
+ (2004, 2004),
111
+ (2005, 2005),
112
+ (2006, 2006),
113
+ (2007, 2007),
114
+ (2008, 2008),
115
+ (2009, 2009),
116
+ (2010, 2010),
117
+ (2011, 2011),
118
+ (2012, 2012),
119
+ (2013, 2013),
120
+ (2014, 2014),
121
+ ]
122
+
123
+ extracted = {}
124
+ zip_paths = []
125
+
126
+ # Loop over each span, download its ZIP and extract the 5 MS bands
127
+ _wait_for_queue_space(1)
128
+ for span_i, (start_year, end_year) in enumerate(spans):
129
+
130
+ # note: cloud handling, etc. is performed in GeeExporter()
131
+ exporter = GeeExporter(
132
+ filterpoly=geom,
133
+ start_year=start_year,
134
+ end_year=end_year,
135
+ ms_bands=_MS_BANDS
136
+ )
137
+ img = exporter.get_timeseries_image(span_len)
138
+
139
+ try:
140
+ bands = img.bandNames().getInfo()
141
+ except Exception as e:
142
+ print(f" ⚠️ Span {start_year}-{end_year}: failed to fetch band names, skipping. ({e})")
143
+ continue
144
+ if not bands:
145
+ print(f" • Span {start_year}-{end_year}: no data, skipping.")
146
+ continue
147
+
148
+ url = img.getDownloadURL({
149
+ 'scale': _SCALE,
150
+ 'crs': _CRS,
151
+ 'region': geom
152
+ })
153
+ print(f"[DEBUG] Download URL for span {start_year}-{end_year}: {url!r}")
154
+
155
+ zip_path = os.path.join(dst_folder, f"{row['dhs_id']}_{start_year}_{end_year}.zip")
156
+ zip_paths.append(zip_path)
157
+
158
+ # safe write
159
+ write_with_retry(zip_path, url)
160
+
161
+ # unsafe write
162
+ #with requests.get(url, stream=True) as r:
163
+ # r.raise_for_status()
164
+ # with open(zip_path, 'wb') as f:
165
+ # for chunk in r.iter_content(1024*1024):
166
+ # f.write(chunk)
167
+
168
+ # Unzip and save each band as its own TIFF
169
+ with zipfile.ZipFile(zip_path, 'r') as z:
170
+ for member in z.namelist():
171
+ if not member.lower().endswith('.tif'):
172
+ continue
173
+ band_name = os.path.splitext(os.path.basename(member))[0].split('_')[-1].upper()
174
+ if band_name not in _MS_BANDS:
175
+ continue
176
+ dst_tif = os.path.join(
177
+ dst_folder,
178
+ f"{row['dhs_id']}_{start_year}_{end_year}_{band_name}.tif"
179
+ )
180
+ with z.open(member) as src, open(dst_tif, 'wb') as out:
181
+ shutil.copyfileobj(src, out)
182
+ extracted[(span_i, band_name)] = dst_tif
183
+
184
+ if not extracted:
185
+ return None
186
+
187
+ # Build the final multi-band TIFF
188
+ first_key = next(iter(extracted))
189
+ with rasterio.open(extracted[first_key]) as src0:
190
+ meta = src0.meta.copy()
191
+
192
+ num_spans = len(spans)
193
+ ms_count = len(_MS_BANDS)
194
+
195
+ # total bands = spans × ms_bands
196
+ meta.update(count = num_spans * ms_count)
197
+
198
+ out_tif = os.path.join(dst_folder, os.path.basename(row['image_file_annual']))
199
+ with rasterio.open(out_tif, 'w', **meta) as dst:
200
+ for span_i in range(num_spans):
201
+ for idx, band_name in enumerate(_MS_BANDS, start=1):
202
+ key = (span_i, band_name)
203
+ if key not in extracted:
204
+ continue
205
+ # and write into contiguous slots
206
+ dest_band = span_i * ms_count + idx
207
+ with rasterio.open(extracted[key]) as src:
208
+ dst.write(src.read(1), dest_band)
209
+
210
+ # — quick QC: did we really get the band‐count we asked for?
211
+ with rasterio.open(out_tif) as chk:
212
+ expected = num_spans * ms_count
213
+ if chk.count != expected:
214
+ raise RuntimeError(f"QC failed: expected {expected} bands, got {chk.count}")
215
+
216
+ # Clean up all intermediate files
217
+ for path in extracted.values():
218
+ os.remove(path)
219
+ for zp in zip_paths:
220
+ os.remove(zp)
221
+
222
+ return row.name
223
+
224
+
225
+ def export_images(df: pd.DataFrame,
226
+ save_dir: str,
227
+ span_length: int = 1,
228
+ num_workers: int = _NUM_WORKERS) -> None:
229
+ """
230
+ For each row in df (must have 'lat','lon','year'), builds a
231
+ span_length-year composite and downloads it locally.
232
+
233
+ Parameters
234
+ ----------
235
+ df : pandas.DataFrame with columns 'lat', 'lon', 'year'
236
+ save_dir : directory to write the unzipped TIFF(s)
237
+ span_length : number of years per composite (e.g. 3)
238
+ num_workers : number of parallel download threads
239
+ """
240
+ os.makedirs(save_dir, exist_ok=True)
241
+
242
+ rows = [row for _, row in df.iterrows()]
243
+
244
+ with ThreadPoolExecutor(max_workers=num_workers) as executor:
245
+ for idx in executor.map(
246
+ lambda r: _download_one(r, save_dir, span_length),
247
+ rows
248
+ ):
249
+ # Only print if the download succeeded (idx is not None)
250
+ if idx is not None:
251
+ print(f' • Finished download for row {idx:05d}')
252
+
253
+ print(f'Downloaded all {len(rows)} composites into:\n {save_dir}')
code/lib/optional/runP_GrabData_EE.sh ADDED
@@ -0,0 +1,42 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ set -ex
3
+ ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../../.." && pwd)"
4
+ cd "${ROOT_DIR}"
5
+ mkdir -p ./logs
6
+
7
+ # make sure your Python scripts are executable
8
+ chmod u+r+x ./code/lib/optional/get_images/GetImageRun_3y.py ./code/lib/optional/get_images/GetImageRun_annual.py
9
+
10
+ # show your resources
11
+ ulimit -a
12
+ parallel --number-of-cpus
13
+ parallel --number-of-cores
14
+ parallel --number-of-threads
15
+ parallel --number-of-sockets
16
+
17
+ # decide how many parallel jobs to run
18
+ export nParallelJobs=1
19
+
20
+ # —————————————————————————————————————————
21
+ # 1) run 3-year image export
22
+ # script: Analysis/GetImages/GetImageRun_3y.py
23
+ # —————————————————————————————————————————
24
+ if false; then
25
+ nohup parallel --jobs ${nParallelJobs} \
26
+ --joblog ./logs/GetImageRun_3y_log.log \
27
+ 'python3 ./code/lib/optional/get_images/GetImageRun_3y.py {}' ::: 1 \
28
+ > ./logs/GetImagesRun_3y_out.out \
29
+ 2> ./logs/GetImagesRun_3y_err.err &
30
+ fi
31
+
32
+ # —————————————————————————————————————————
33
+ # 2) run annual image export
34
+ # script: Analysis/GetImages/GetImageRun_annual.py
35
+ # —————————————————————————————————————————
36
+ if true; then
37
+ nohup parallel --jobs ${nParallelJobs} \
38
+ --joblog ./logs/GetImageRun_annual_log.log \
39
+ 'python3 ./code/lib/optional/get_images/GetImageRun_annual.py {}' ::: 1 \
40
+ > ./logs/GetImagesRun_annual_out.out \
41
+ 2> ./logs/GetImagesRun_annual_err.err &
42
+ fi
code/lib/prep_desc_stats.R ADDED
@@ -0,0 +1,218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #prep_desc_stats.R
2
+ library(dplyr)
3
+ library(tidyr)
4
+
5
+ KeepObjectsAcrossAnalysisStrings <- get0("KeepObjectsAcrossAnalysisStrings", ifnotfound = character())
6
+ rm(list=ls()[!ls() %in% (Keeps <- c("t0",KeepObjectsAcrossAnalysisStrings))] )
7
+ setwd(getOption("replication.root", default = getwd()))
8
+
9
+ #############################################################
10
+ #### Projects by funder
11
+ #############################################################
12
+ oda_sect_group_df <- read.csv("./data/interim/africa_oda_sector_group.csv") %>%
13
+ filter(transactions_start_year >= 2002 &
14
+ transactions_start_year <= 2013)
15
+
16
+ donor_precision_count <- oda_sect_group_df %>%
17
+ group_by(funder, precision_code) %>%
18
+ summarize(n = n_distinct(project_location_id)) %>%
19
+ pivot_wider(names_from = funder, values_from = n, values_fill = 0) %>%
20
+ mutate(precision_code = paste("project_precision",precision_code)) %>%
21
+ rename(description = precision_code)
22
+
23
+ donor_vars_df <- oda_sect_group_df %>%
24
+ dplyr::select(funder, project_id, project_location_id, site_iso3, ad_sector_codes) %>%
25
+ group_by(funder) %>%
26
+ summarize(across(everything(), ~n_distinct(.))) %>%
27
+ pivot_longer(cols = -funder, names_to = "description", values_to = "distinct_count") %>%
28
+ pivot_wider(names_from = funder, values_from = distinct_count, values_fill = 0)
29
+
30
+ # donor_regional_unspecified_df <- oda_sect_group_df %>%
31
+ # select(funder, project_location_id, recipients_iso3) %>%
32
+ # group_by(funder) %>%
33
+ # filter(grepl("regional|Unspecified",recipients_iso3)) %>%
34
+ # summarize(regional_count= n_distinct(project_location_id)) %>%
35
+ # pivot_longer(cols = -funder, names_to = "description", values_to = "distinct_count") %>%
36
+ # pivot_wider(names_from = funder, values_from = distinct_count, values_fill = 0)
37
+ #
38
+ # donor_recipient_site_mismatch_df <- oda_sect_group_df %>%
39
+ # select(funder, project_location_id, recipients_iso3, site_iso3) %>%
40
+ # group_by(funder) %>%
41
+ # filter(!grepl("regional|Unspecified",recipients_iso3) &
42
+ # recipients_iso3 != site_iso3) %>%
43
+ # summarize(mismatch_count= n_distinct(project_location_id)) %>%
44
+ # pivot_longer(cols = -funder, names_to = "description", values_to = "distinct_count") %>%
45
+ # pivot_wider(names_from = funder, values_from = distinct_count, values_fill = 0)
46
+
47
+ no_end_date_df <- oda_sect_group_df %>%
48
+ dplyr::select(funder,end_actual_isodate) %>%
49
+ group_by(funder) %>%
50
+ summarize(portion_no_end_date = mean(end_actual_isodate=="")) %>%
51
+ mutate(portion_no_end_date = round(portion_no_end_date,2)) %>%
52
+ pivot_longer(cols = -funder, names_to = "description", values_to = "distinct_count") %>%
53
+ pivot_wider(names_from = funder, values_from = distinct_count, values_fill = 0)
54
+
55
+ no_funding_df <- oda_sect_group_df %>%
56
+ dplyr::select(funder,total_disbursements) %>%
57
+ group_by(funder) %>%
58
+ summarize(portion_no_funding = mean(is.na(total_disbursements))) %>%
59
+ mutate(portion_no_funding = round(portion_no_funding,2)) %>%
60
+ pivot_longer(cols = -funder, names_to = "description", values_to = "distinct_count") %>%
61
+ pivot_wider(names_from = funder, values_from = distinct_count, values_fill = 0)
62
+
63
+ multisector_df <- oda_sect_group_df %>%
64
+ dplyr::select(funder, geoname_id, transactions_start_year, ad_sector_codes) %>%
65
+ group_by(funder, geoname_id, transactions_start_year, ad_sector_codes) %>%
66
+ count() %>%
67
+ group_by(funder) %>%
68
+ summarize(portion_multisector = mean(n > 1)) %>%
69
+ mutate(portion_multisector = round(portion_multisector,2)) %>%
70
+ pivot_longer(cols = -funder, names_to = "description", values_to = "distinct_count") %>%
71
+ pivot_wider(names_from = funder, values_from = distinct_count, values_fill = 0)
72
+
73
+ desired_order <- c(3, 4, 1, 2, 5, 6, 7, 8, 9, 10)
74
+ donor_comparison_df <- rbind(donor_vars_df,donor_precision_count, no_end_date_df,
75
+ no_funding_df, multisector_df) %>%
76
+ slice(match(desired_order, row_number())) %>%
77
+ mutate(description = case_match(description,
78
+ "site_iso3" ~ "Countries hosting projects count",
79
+ "ad_sector_codes" ~ "Sectors funded",
80
+ "project_id" ~ "Aid project count",
81
+ "project_location_id" ~ "Aid project location count",
82
+ "project_precision 1" ~ "Exact locations available (precision 1)",
83
+ "project_precision 2" ~ "Near (<25km) locations available (precision 2)",
84
+ "project_precision 3" ~ "ADM2 locations available (precision 3)",
85
+ "portion_no_end_date" ~ "Portion lacking end date",
86
+ "portion_no_funding" ~ "Portion lacking funding information",
87
+ "portion_multisector" ~ "Portion with concurrent, co-located, multi-sector projects",
88
+ .default = description))
89
+
90
+ # Table 1: Funder Comparison: China and World Bank
91
+ # 1 Countries hosting projects count 50 44
92
+ # 2 Sectors funded 22 13
93
+ # 3 Aid project count 722 513
94
+ # 4 Aid project location count 1373 7115
95
+ # 5 Exact locations available (precision 1) 987 4149
96
+ # 6 Near (<25km) locations available (precision 2) 169 258
97
+ # 7 ADM2 locations available (precision 3) 217 2708
98
+ # 8 Portion lacking end date 0.68 0.15
99
+ # 9 Portion lacking funding information 1 0.28
100
+ # 10 Portion with concurrent, co-located, multi-sector projects 0.03 0.02
101
+
102
+ #higher than Gehring et al, because they exclude countries with less than 1 million people
103
+
104
+ write.csv(donor_comparison_df,"./tables/funder_comparison.csv",row.names = FALSE)
105
+
106
+ #to do: make a sector level table similar to this, but divided by funders
107
+ #consider limiting to sectors actually included in analysis?
108
+ oda_sect_group_df %>%
109
+ filter(precision_code < 4) %>%
110
+ group_by(funder, ad_sector_codes, ad_sector_names) %>%
111
+ count()
112
+
113
+
114
+ #############################################################
115
+ #### DHS Units of Analysis
116
+ #############################################################
117
+ #read file with all DHS points for one survey round per country
118
+ dhs_est_iwi_df <- read.csv("./data/interim/dhs_est_iwi.csv")
119
+
120
+ #read file that contains confounder data (lower n due to missing confounders)
121
+ dhs_confounders_df <- read.csv("./data/interim/dhs_5k_confounders.csv")
122
+
123
+ #identify locations excluded due to missing confounders, group by country
124
+ excluded_dhs_df <- anti_join(dhs_est_iwi_df,dhs_confounders_df,by="dhs_id") %>%
125
+ group_by(iso3) %>% count() %>% ungroup() %>%
126
+ rename(n_excluded=n)
127
+
128
+ #get formatted country names
129
+ africa_isos_df <- read.csv("./data/interim/africa_isos.csv")
130
+
131
+ #get treated information
132
+ dhs_t_df <- read.csv("./data/interim/dhs_treated_sector_3yr.csv") %>%
133
+ filter(year_group!="2014:2016") %>%
134
+ #exclude DHS points where confounder data not available
135
+ inner_join(dhs_confounders_df %>%
136
+ dplyr::select(dhs_id, ID_adm2), by = join_by(dhs_id))
137
+
138
+ #identify locations that were never treated, group by country
139
+ dhs_never_treated_df <- anti_join(dhs_confounders_df,dhs_t_df,by="dhs_id") %>%
140
+ group_by(iso3) %>% count() %>% rename(n_never_treated=n) %>% ungroup()
141
+
142
+ #create display version of neighborhood descriptive stats
143
+ neighborhoods_df <- dhs_confounders_df %>%
144
+ dplyr::select(iso3,survey_start_year,households,rural.x,dhs_id) %>%
145
+ group_by(iso3,survey_start_year) %>%
146
+ summarize(n_cluster_locations=n_distinct(dhs_id),
147
+ n_households=sum(households),
148
+ portion_rural=round(mean(rural.x),2)) %>%
149
+ ungroup() %>%
150
+ #join to get locations that were never treated
151
+ left_join(dhs_never_treated_df, by="iso3") %>%
152
+ mutate(n_never_treated=ifelse(is.na(n_never_treated),0,n_never_treated)) %>%
153
+ mutate(portion_never_treated=round(n_never_treated/n_cluster_locations,2)) %>%
154
+ #join to get excluded count
155
+ left_join(excluded_dhs_df,by="iso3") %>%
156
+ mutate(n_excluded=ifelse(is.na(n_excluded),0,n_excluded)) %>%
157
+ #join to get country names
158
+ left_join(africa_isos_df %>% dplyr::select(-iso2), by="iso3") %>%
159
+ rename(country=name) %>%
160
+ dplyr::select(country,survey_start_year,n_cluster_locations,n_households,
161
+ portion_rural,portion_never_treated,n_excluded) %>%
162
+ arrange(country)
163
+
164
+ # country survey_start_year n_cluster_l…¹ n_hou…² porti…³ porti…⁴ n_exc…⁵
165
+ # <chr> <int> <int> <int> <dbl> <dbl> <dbl>
166
+ # 1 Angola 2006 62 1377 0.35 0.4 0
167
+ # 2 Benin 1996 190 3152 0.53 0.03 0
168
+ # 3 Burkina Faso 1998 81 754 0.62 0.25 0
169
+ # 4 Burundi 2010 307 7032 0.88 0.49 0
170
+ # 5 Cameroon 2004 464 9254 0.48 0.22 0
171
+ # 6 Central African Republic 1994 66 1142 0.65 0.86 0
172
+ # 7 Chad 2014 235 6499 0.59 0.26 0
173
+ # 8 Comoros 2012 242 4286 0.56 0 0
174
+ # 9 Congo, Democratic Republic of the 2007 286 7947 0.57 0 5
175
+ # 10 Côte d'Ivoire 1998 63 833 0.49 0.1 0
176
+ # 11 Egypt 1995 7 111 0.14 1 0
177
+ # 12 Eswatini 2006 210 3689 0.64 0.52 0
178
+ # 13 Ethiopia 2000 506 8623 0.73 0 0
179
+ # 14 Gabon 2012 332 11151 0.45 0.46 0
180
+ # 15 Ghana 1998 144 1373 0.65 0 0
181
+ # 16 Guinea 1999 290 3567 0.6 0.06 0
182
+ # 17 Kenya 2003 389 7640 0.67 0.45 0
183
+ # 18 Lesotho 2004 344 5350 0.72 0.1 0
184
+ # 19 Liberia 2009 30 855 0.1 0 0
185
+ # 20 Madagascar 1997 260 5610 0.59 0.02 0
186
+ # 21 Malawi 2000 554 14057 0.8 0.6 1
187
+ # 22 Mali 1995 167 2238 0.57 0.01 0
188
+ # 23 Morocco 2003 343 7530 0.42 0.95 1
189
+ # 24 Mozambique 2011 609 13303 0.58 0.12 0
190
+ # 25 Namibia 2000 258 6236 0.6 0.88 2
191
+ # 26 Niger 1998 184 2189 0.51 0.12 0
192
+ # 27 Nigeria 2003 356 5599 0.54 0.42 0
193
+ # 28 Rwanda 2005 447 8504 0.76 0 0
194
+ # 29 Senegal 1997 270 2518 0.63 0.04 0
195
+ # 30 Sierra Leone 2008 349 7138 0.59 0 0
196
+ # 31 South Africa 2016 745 11035 0.38 0.85 1
197
+ # 32 Tanzania, United Republic of 1999 171 2831 0.66 0.05 0
198
+ # 33 Togo 1998 271 5332 0.52 0.03 0
199
+ # 34 Uganda 2000 137 2192 0.55 0.19 0
200
+ # 35 Zambia 2007 318 7552 0.64 0.08 1
201
+ # 36 Zimbabwe 1999 212 3469 0.64 0.5 0
202
+
203
+ write.csv(neighborhoods_df,"./tables/neighborhoods.csv",row.names = FALSE)
204
+
205
+ #get total counts for use in Pipeline Figure
206
+ total_dhs_n_df <- dhs_confounders_df %>%
207
+ dplyr::select(iso3,survey_start_year,households,dhs_id) %>%
208
+ summarize(n_cluster_locations=n_distinct(dhs_id),
209
+ n_households=sum(households),
210
+ n_countries=n_distinct(iso3),
211
+ n_start_year=n_distinct(survey_start_year)
212
+ )
213
+ write.csv(total_dhs_n_df,"./tables/total_dhs_n.csv",row.names = FALSE)
214
+
215
+
216
+
217
+
218
+