Repository navigation
Expand file tree
/
Copy pathTestHarness.R
More file actions
319 lines (270 loc) · 10.4 KB
/
Copy pathTestHarness.R
File metadata and controls
319 lines (270 loc) · 10.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
# =============================================================================
# TEST_HARNESS.R - Isolated testing of pipeline components
# =============================================================================
# =============================================================================
# # HiPerGator-specific fix for module conflicts
# if (dir.exists("/apps")) {
# # Manually load UDUNITS without needing the module 'loaded' in the shell
# if (file.exists("/apps/udunits/2.2.17/lib/libudunits2.so.0")) {
# dyn.load("/apps/udunits/2.2.17/lib/libudunits2.so.0")
# }
#
# # Manually load GDAL to bypass the Lmod conflict with R/4.6
# # libgdal.so.30 is typically found in this path on HiPerGator
# gdal_path <- "/apps/gcc/12.2.0/gdal/3.9.0/lib/libgdal.so"
# if (file.exists(gdal_path)) {
# dyn.load(gdal_path)
# }
# }
#
# # Load the personal library path defined in your setup
# .libPaths("~/R/libs")
# library('units')
# library('sf')
# library('stars')
# =============================================================================
library(dplyr)
library(mvgam)
library(glue)
library(future)
# Handle namespace conflicts for the test harness
conflicted::conflicts_prefer(dplyr::filter, .quiet = TRUE)
conflicted::conflicts_prefer(dplyr::select, .quiet = TRUE)
conflicted::conflicts_prefer(mvgam::AR, .quiet = TRUE)
conflicted::conflicts_prefer(mvgam::VAR, .quiet = TRUE)
conflicted::conflicts_prefer(mvgam::RW, .quiet = TRUE)
conflicted::conflicts_prefer(base::as.matrix, .quiet = TRUE)
conflicted::conflicts_prefer(base::get, .quiet = TRUE)
# Load necessary functions
source("data_functions.R")
source("evaluation.R")
# =============================================================================
# CONFIGURATION FOR TESTING
# =============================================================================
# Minimal test configuration
TEST_CONFIG <- list(
# Data settings
spatial = list(
level = "subregion",
include_species = c('all'),
include_unknowns = FALSE,
forecast_totals = TRUE,
run_by_region = FALSE,
exclude_regions = c("bigcypress", "coastal")
),
# Minimal MCMC for fast testing
chains = 2,
burnin = 200,
samples = 200,
# CV settings
train_years = 5,
test_years = 1,
cv_windows = 1,
# Evaluation
use_ordinal = TRUE,
ordinal_years = "All",
ordinal_breaks = c(0.33, 0.67, 0.90),
sliding_window_breaks = FALSE,
# Model settings
family = "nb",
# Parallel
parallel = list(
enabled = TRUE,
workers = 2
),
# Cache
cache = list(
data = TRUE,
models = FALSE
),
# Data type
data_type = "observed"
)
# Make it globally available
CONFIG <- TEST_CONFIG
# =============================================================================
# TEST FUNCTIONS
# =============================================================================
#' Test one or more models in isolation
#' @param model_name Name(s) of the model(s) (e.g., "baseline", "ar", "trait",
#' or c("baseline", "ar") to compare multiple models in the same CV windows)
#' @param framework Either "mvgam" or "fable"
#' @param use_full_data If FALSE, uses only recent years
#' @param parallel If TRUE, runs CV windows in parallel
#' @param workers Number of parallel workers (defaults to auto-detect if NULL)
test_single_model <- function(model_name,
framework = "mvgam",
use_full_data = FALSE,
parallel = FALSE,
workers = NULL) {
cat("\n", paste(rep("=", 70), collapse = ""), "\n", sep = "")
cat(glue("TESTING: {framework}_{paste(model_name, collapse = ', ')} (Parallel: {parallel})\n"))
cat(paste(rep("=", 70), collapse = ""), "\n\n", sep = "")
# Load data
cat("Loading data...\n")
data <- get_wading_bird_data(config = CONFIG, cache = TRUE)
# Optionally subset to recent years for speed
if (!use_full_data) {
recent_years <- 10
min_year <- max(data$year) - recent_years + 1
data <- data |> filter(year >= min_year)
cat(glue("Using recent {recent_years} years: {min_year}-{max(data$year)}\n"))
}
cat(glue("Data: {nrow(data)} rows, {n_distinct(data$species)} species\n\n"))
# === FIX: CREATE A TEST RUN FOLDER AND INJECT INTO CONFIG ===
test_run_folder <- file.path("results", paste0(
"test_", framework, "_", paste(model_name, collapse = "_"), "_",
format(Sys.time(), "%Y%m%d-%H%M%S")
))
dir.create(test_run_folder, recursive = TRUE, showWarnings = FALSE)
CONFIG$output_dir <- test_run_folder
# Make it globally available for the evaluation script
assign("CONFIG", CONFIG, envir = .GlobalEnv)
assign("run_folder", test_run_folder, envir = .GlobalEnv)
cat("Test output directory:", test_run_folder, "\n\n")
# Load the specific model file(s)
if (framework == "mvgam") {
for (m in model_name) {
model_file <- file.path("models", paste0("mvgam_", m, ".R"))
if (!file.exists(model_file)) {
stop("Model file not found: ", model_file)
}
source(model_file)
cat(glue("✓ Loaded {model_file}\n"))
}
cat("\n")
# Run the model(s) through CV with explicit config and framework
results <- fit_sliding_window(
data = data,
make_forecast = function(train, test, ...) {
source("evaluation.R", local = FALSE)
source(file.path("models", "mvgam_baseline.R"), local = FALSE)
for (m in model_name) {
source(file.path("models", paste0("mvgam_", m, ".R")), local = FALSE)
}
make_mvgam_forecasts(train, test, ...)
},
train_years = CONFIG$train_years,
test_years = CONFIG$test_years,
cv_windows = CONFIG$cv_windows,
parallel = parallel,
workers = workers,
framework = framework, # REQUIRED BY NEW EVALUATION
config = CONFIG, # REQUIRED BY NEW EVALUATION
models_to_run = model_name,
use_ordinal = CONFIG$use_ordinal,
precomputed_breaks = NULL
)
} else if (framework == "fable") {
source("models/fable_models.R")
cat("✓ Loaded fable models\n\n")
results <- fit_sliding_window(
data = data,
make_forecast = function(train, test, ...) {
source("evaluation.R", local = FALSE)
source("models/fable_models.R", local = FALSE)
make_fable_forecasts(train, test, ...)
},
train_years = CONFIG$train_years,
test_years = CONFIG$test_years,
cv_windows = CONFIG$cv_windows,
parallel = parallel,
workers = workers,
framework = framework,
config = CONFIG,
models_to_run = model_name,
use_ordinal = CONFIG$use_ordinal
)
}
# Print results
cat("\n", paste(rep("=", 70), collapse = ""), "\n", sep = "")
cat("RESULTS\n")
cat(paste(rep("=", 70), collapse = ""), "\n\n", sep = "")
cat("Forecasts:", nrow(results$forecasts), "rows\n")
cat("Metrics:", nrow(results$metrics), "rows\n\n")
if (nrow(results$metrics) > 0) {
print(results$metrics)
}
return(results)
}
#' Test with a single CV window and custom train/test split
#' @param train_start First year of training data
#' @param test_start First year of test data
test_single_window <- function(model_name,
train_start = 2010,
test_start = 2015,
framework = "mvgam") {
cat("\n", paste(rep("=", 70), collapse = ""), "\n", sep = "")
cat(glue("TESTING SINGLE WINDOW: {train_start}-{test_start-1} → {test_start}\n"))
cat(paste(rep("=", 70), collapse = ""), "\n\n", sep = "")
# Load data
data <- get_wading_bird_data(config = CONFIG, cache = TRUE)
# Split into train/test
train_data <- data |> filter(year >= train_start & year < test_start)
test_data <- data |> filter(year == test_start)
cat(glue("Train: {nrow(train_data)} obs ({min(train_data$year)}-{max(train_data$year)})\n"))
cat(glue("Test: {nrow(test_data)} obs (year {test_start})\n\n"))
# Load model
if (framework == "mvgam") {
model_file <- file.path("models", paste0("mvgam_", model_name, ".R"))
source(model_file)
# Prepare data for mvgam
all_series <- unique(c(train_data$species, test_data$species))
min_year <- min(train_data$year)
train_data <- train_data |>
mutate(
time = as.integer(year - min_year + 1),
series = factor(species, levels = all_series)
) |>
as.data.frame()
test_data <- test_data |>
mutate(
time = as.integer(year - min_year + 1),
series = factor(species, levels = all_series)
) |>
as.data.frame()
# Mock window directory needed by updated evaluation.R
CONFIG$.window_dir <- tempdir()
CONFIG$.window_relative_dir <- "test_single_window"
# Run the forecast
result <- make_mvgam_forecasts(
train_data = train_data,
test_data = test_data,
models_to_run = model_name,
use_ordinal = FALSE,
config = CONFIG
)
}
cat("\nResults:\n")
print(result$metrics)
return(result)
}
#' Test data loading with different configurations
test_data_loading <- function() {
cat("\n", paste(rep("=", 70), collapse = ""), "\n", sep = "")
cat("TESTING DATA LOADING\n")
cat(paste(rep("=", 70), collapse = ""), "\n\n", sep = "")
configs_to_test <- list(
system = list(level = "system", include_species = "top6"),
subregion = list(level = "subregion", include_species = "top6"),
colony = list(level = "colony", include_species = c("gbhe", "greg"))
)
for (name in names(configs_to_test)) {
cat(glue("\n--- Testing: {name} ---\n"))
test_config <- CONFIG
test_config$spatial <- modifyList(CONFIG$spatial, configs_to_test[[name]])
data <- get_wading_bird_data(config = test_config, cache = FALSE)
cat(glue(" Rows: {nrow(data)}\n"))
cat(glue(" Species: {paste(unique(data$species), collapse = ', ')}\n"))
if ("region" %in% names(data)) {
cat(glue(" Regions: {paste(unique(data$region), collapse = ', ')}\n"))
}
cat(glue(" Years: {min(data$year)}-{max(data$year)}\n"))
}
}
# =============================================================================
# EXAMPLE USAGE
# =============================================================================
# Uncomment the test you want to run:
# Test ar model quickly
# test_single_model("ar", framework = "mvgam", use_full_data = FALSE)