Skip to content

Commit e31224c

Browse files
committed
Remove model_dir requirement, major claeaning, for v1.0.0 with same function as before package
Now uses witchtools functions and mappings instead, and added historical data for standard region definitions.
1 parent bb12dc2 commit e31224c

36 files changed

+1490
-580
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,3 +33,9 @@ iiasa_credentials.yml
3333
# Development files (optional - remove these lines to track them)
3434
dev_workflow.R
3535
ROXYGEN_WORKFLOW.md
36+
test*
37+
38+
# Source historical data (not released with package)
39+
# Only processed regional files in data/ are released
40+
data-raw/data_historical_values.gdx
41+

DESCRIPTION

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,4 @@ Suggests:
4545
tidytidbits,
4646
gdxrrw,
4747
testthat (>= 3.0.0)
48-
RoxygenNote: 7.2.0
48+
RoxygenNote: 7.3.3

R/RICE50x_plots.R

Lines changed: 0 additions & 61 deletions
This file was deleted.

R/add_historical_values.R

Lines changed: 406 additions & 120 deletions
Large diffs are not rendered by default.

R/emission_plots.R

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,7 @@ Mitigation_Sources <- function(regions=witch_regions, scenario_stringency_order,
9090
MITIGATION_SOURCES <- subset(MITIGATION_SOURCES, file!=scenario_stringency_order[1])
9191
MITIGATION_SOURCES <- MITIGATION_SOURCES[order(match(MITIGATION_SOURCES$file,scenario_stringency_order)),]
9292
MITIGATION_SOURCES <- MITIGATION_SOURCES[order(match(MITIGATION_SOURCES$file,scenario_stringency_order),match(MITIGATION_SOURCES$source,emi_sources)) ,]
93-
MITIGATION_SOURCES$pathdir <- basename(fullpathdir[1]) #to avoid issues when saving data as EXCEL
93+
MITIGATION_SOURCES$pathdir <- basename(results_dir[1]) #to avoid issues when saving data as EXCEL
9494
#to set minimal negative vales to zero
9595
MITIGATION_SOURCES$value <- pmax(MITIGATION_SOURCES$value, 0)
9696
#Stacked Regions Plot

R/energy_plots.R

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11

22

33
Primary_Energy_Mix <- function(PES_y="value", regions="World", years=seq(yearmin, yearmax), plot_type="area", scenplot=scenlist, plot_name="Primary Energy Mix", add_total_tpes = F){
4-
if(length(fullpathdir)!=1){stop("PES mix REGIONAL only for one directory at a time!"); return(invisible(NULL))}
4+
if(length(results_dir)!=1){stop("PES mix REGIONAL only for one directory at a time!"); return(invisible(NULL))}
55
Q_FUEL <- get_witch("Q_FUEL"); Q_FUEL_pes <- Q_FUEL %>% mutate(value=value*0.0036) %>% rename(j=fuel)
66
#if fuel==uranium multiply by the efficiency of 0.3333
77
Q_FUEL_pes <- Q_FUEL_pes %>% mutate(value=ifelse(j=="uranium", value*0.3333, value))
@@ -57,7 +57,7 @@ Primary_Energy_Mix <- function(PES_y="value", regions="World", years=seq(yearmin
5757

5858

5959
Electricity_Mix <- function(Electricity_y="value", regions="World", years=seq(yearmin, yearmax), plot_type="area", plot_name="Electricity Mix", scenplot=scenlist, add_total_elec=F){
60-
if(length(fullpathdir)!=1){stop("Electricity mix only for one directory at a time!"); return(invisible(NULL))}
60+
if(length(results_dir)!=1){stop("Electricity mix only for one directory at a time!"); return(invisible(NULL))}
6161
Q_IN <- get_witch("Q_IN"); Q_IN_el <- Q_IN %>% mutate(value=value * 0.0036)
6262
csi_el <- get_witch("csi") %>% rename(csi=value) %>% mutate(jfed=gsub("_new", "", jfed)) %>% filter(jfed %in% c("eloil", "elpb", "elpc", "elgastr", "elbigcc", "elcigcc", "elgasccs", "elpc_ccs", "elpc_oxy"))
6363
JFED <- merge(Q_IN_el, csi_el, by = c("t", "n", file_group_columns, "pathdir", "fuel", "jfed"), all=TRUE)
@@ -203,7 +203,7 @@ Investment_Plot <- function(regions=witch_regions, scenplot=scenlist, match_hist
203203

204204

205205
Power_capacity <- function(regions="World", years=seq(yearmin, yearmax), plot_name="Power Capacity", scenplot=scenlist){
206-
if(length(fullpathdir)!=1){print("Electricity mix only for one directory at a time!")}else{
206+
if(length(results_dir)!=1){print("Electricity mix only for one directory at a time!")}else{
207207
K_EN <- get_witch("K_EN")
208208
K_EN <- K_EN %>% filter(jreal %in% c("eloil", "elpb", "elpc", "elgastr", "elbigcc", "elcigcc", "elgasccs", "elpc_ccs", "elpv", "elcsp", "elnuclear", "elwindon", "elwindoff", "elhydro"))
209209
K_EN <- K_EN %>% mutate(category = dplyr::recode(jreal, !!!c("elpc" = "Coal w/o CCS", "elpc_ccs" = "Coal w/ CCS", "elgastr" = "Gas w/o CCS", "elgasccs" = "Gas w/ CCS", "eloil" = "Oil", "elnuclear" = "Nuclear", "elpb" = "Biomass w/o CCS", "elbigcc" = "Biomass w/ CCS", "elhydro" = "Hydro", "elwindon" = "Wind Onshore", "elwindoff" = "Wind Offshore", "elpv" = "Solar PV", "elcsp" = "Solar CSP")))

R/gdx_file_loader.R

Lines changed: 12 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,18 @@
1111
#' @keywords internal
1212
.load_gdx_files <- function() {
1313
# Check if we should load GDX files
14-
if(!exists("fullpathdir", envir=.GlobalEnv) ||
15-
is.null(get("fullpathdir", envir=.GlobalEnv)) ||
14+
if(!exists("results_dir", envir=.GlobalEnv) ||
15+
is.null(get("results_dir", envir=.GlobalEnv)) ||
1616
exists("iamc_filename", envir=.GlobalEnv) ||
1717
exists("iamc_databasename", envir=.GlobalEnv)) {
1818
return(invisible(NULL))
1919
}
2020

21-
fullpathdir <- get("fullpathdir", envir=.GlobalEnv)
21+
results_dir <- get("results_dir", envir=.GlobalEnv)
2222

2323
# Discover GDX files
2424
filelist <- gsub(".gdx", "", list.files(
25-
path = fullpathdir[1],
25+
path = results_dir[1],
2626
full.names = FALSE,
2727
pattern = "*.gdx",
2828
recursive = FALSE
@@ -99,7 +99,7 @@
9999
exists("batch_extract", where = asNamespace("gdxtools"), mode = "function")) {
100100
tlen_values <- suppressWarnings(gdxtools::batch_extract(
101101
"tlen",
102-
files = file.path(fullpathdir, paste0(filelist, ".gdx"))
102+
files = file.path(results_dir, paste0(filelist, ".gdx"))
103103
))
104104
flexible_timestep <- length(unique(tlen_values$tlen$value)) > 1
105105
} else {
@@ -125,15 +125,15 @@
125125
}
126126

127127
# Get variable descriptions from first file
128-
mygdx <- gdxtools::gdx(file.path(fullpathdir[1], paste0(filelist[1], ".gdx")))
128+
mygdx <- gdxtools::gdx(file.path(results_dir[1], paste0(filelist[1], ".gdx")))
129129
all_var_descriptions <- rbind(
130130
data.frame(name = mygdx$variables$name, description = mygdx$variables$text),
131131
data.frame(name = mygdx$parameters$name, description = mygdx$parameters$text)
132132
)
133133
assign("all_var_descriptions", all_var_descriptions, envir=.GlobalEnv)
134134

135135
# Set up region information
136-
.setup_region_info(filelist, fullpathdir)
136+
.setup_region_info(filelist, results_dir)
137137

138138
# filelist already assigned earlier
139139
invisible(NULL)
@@ -142,9 +142,9 @@
142142
#' Setup region information
143143
#'
144144
#' @param filelist Character vector of GDX filenames
145-
#' @param fullpathdir Path to results directory
145+
#' @param results_dir Path to results directory
146146
#' @keywords internal
147-
.setup_region_info <- function(filelist, fullpathdir) {
147+
.setup_region_info <- function(filelist, results_dir) {
148148
# Get region ID
149149
if(!exists("reg_id", envir=.GlobalEnv)) {
150150
conf <- get_witch("conf")
@@ -155,7 +155,7 @@
155155
print("Be careful: not all results files were run with the same regional aggregation!")
156156
}
157157
scenlist <- get("scenlist", envir=.GlobalEnv)
158-
reg_id <- subset(conf, file == scenlist[1] & pathdir == basename(fullpathdir[1]) & V1 == "regions")$V2
158+
reg_id <- subset(conf, file == scenlist[1] & pathdir == basename(results_dir[1]) & V1 == "regions")$V2
159159
assign("reg_id", reg_id, envir=.GlobalEnv)
160160
} else {
161161
reg_id <- get("reg_id", envir=.GlobalEnv)
@@ -164,7 +164,7 @@
164164
# Get regions list
165165
if (requireNamespace("gdxtools", quietly = TRUE) &&
166166
exists("batch_extract", where = asNamespace("gdxtools"), mode = "function")) {
167-
n <- suppressWarnings(gdxtools::batch_extract("n", files = file.path(fullpathdir, paste0(filelist, ".gdx"))))
167+
n <- suppressWarnings(gdxtools::batch_extract("n", files = file.path(results_dir, paste0(filelist, ".gdx"))))
168168
if(is.null(n$n)) {
169169
witch_regions <- "World"
170170
} else {
@@ -173,7 +173,7 @@
173173
} else {
174174
# Fallback: try to get regions from first file
175175
tryCatch({
176-
first_gdx <- gdxtools::gdx(file.path(fullpathdir[1], paste0(filelist[1], ".gdx")))
176+
first_gdx <- gdxtools::gdx(file.path(results_dir[1], paste0(filelist[1], ".gdx")))
177177
if("n" %in% names(first_gdx$sets)) {
178178
witch_regions <- first_gdx$sets$n$V1
179179
} else {
@@ -194,28 +194,6 @@
194194
assign("display_regions", display_regions, envir=.GlobalEnv)
195195
assign("witch_regions", witch_regions, envir=.GlobalEnv)
196196

197-
# Check for historical data directory - try to find actual directory
198-
model_dir <- get("model_dir", envir=.GlobalEnv)
199-
if(!is.null(model_dir)) {
200-
data_dir <- file.path(model_dir, paste0("data_", reg_id))
201-
if(!dir.exists(data_dir)) {
202-
# Try to find a directory that starts with data_<reg_id>
203-
potential_dirs <- list.dirs(model_dir, full.names = FALSE, recursive = FALSE)
204-
matching_dirs <- grep(paste0("^data_", reg_id), potential_dirs, value = TRUE)
205-
if (length(matching_dirs) > 0) {
206-
message("Found data directory: ", matching_dirs[1])
207-
# Update reg_id to match actual directory
208-
reg_id <- gsub("^data_", "", matching_dirs[1])
209-
assign("reg_id", reg_id, envir=.GlobalEnv)
210-
} else {
211-
warning(sprintf(
212-
"Historical data directory not found: '%s'\nHistorical data features will be disabled.",
213-
data_dir
214-
))
215-
}
216-
}
217-
}
218-
219197
# Set up color palettes
220198
region_palette <- get_region_palette(witch_regions, reg_id)
221199
if(exists("restrict_regions", envir=.GlobalEnv)) {

R/gdx_loader_new.R

Lines changed: 13 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,15 @@
2323
stop("No GDX files found in: ", results_dir)
2424
}
2525

26-
# Apply inclusion filter
27-
if (!is.null(restrict_files) && restrict_files != "") {
26+
# ALWAYS filter to files starting with "results_" first
27+
all_files <- all_files[stringr::str_starts(all_files, "results_")]
28+
29+
if (length(all_files) == 0) {
30+
stop("No GDX files starting with 'results_' found in: ", results_dir)
31+
}
32+
33+
# Apply additional inclusion filters (if restrict_files is not "results_")
34+
if (!is.null(restrict_files) && restrict_files != "" && restrict_files != "results_") {
2835
patterns <- if (is.character(restrict_files)) restrict_files else unlist(restrict_files)
2936
filtered <- all_files
3037
for (pattern in patterns) {
@@ -82,7 +89,6 @@
8289
#' Returns a list with all session data instead of using global variables.
8390
#'
8491
#' @param results_dir Path to results directory
85-
#' @param model_dir Path to model directory
8692
#' @param restrict_files Pattern to filter GDX files
8793
#' @param exclude_files Pattern to exclude GDX files
8894
#' @param removepattern Pattern to remove from scenario names
@@ -91,7 +97,6 @@
9197
#' @return List containing: filelist, scenlist, regions, palettes, metadata
9298
#' @keywords internal
9399
.load_gdx_session <- function(results_dir,
94-
model_dir = NULL,
95100
restrict_files = "results_",
96101
exclude_files = "",
97102
removepattern = "results_",
@@ -129,23 +134,22 @@
129134
))
130135

131136
# Set filelist globally early so get_witch() can access it
132-
# This is needed because get_witch() depends on filelist being global
137+
# This is needed because get_witch() depends on this being global
138+
# Note: results_dir is already assigned by the caller (run_witch, etc.)
133139
assign("filelist", filelist, envir = .GlobalEnv)
134-
assign("fullpathdir", results_dir, envir = .GlobalEnv)
135140

136141
# Get metadata from first file
137142
first_gdx_path <- file.path(results_dir, paste0(filelist[1], ".gdx"))
138143
metadata <- .extract_gdx_metadata(first_gdx_path, filelist, results_dir)
139144

140145
# Get region information (suppress join messages)
141-
region_info <- suppressMessages(.extract_region_info(filelist, results_dir, reg_id, model_dir))
146+
region_info <- suppressMessages(.extract_region_info(filelist, results_dir, reg_id))
142147

143148
# Return everything as a list
144149
list(
145150
filelist = filelist,
146151
scenlist = scenlist,
147152
results_dir = results_dir,
148-
model_dir = model_dir,
149153
file_group_columns = file_group_columns,
150154
regions = region_info$regions,
151155
reg_id = region_info$reg_id,
@@ -212,10 +216,9 @@
212216
#' @param filelist GDX filenames
213217
#' @param results_dir Results directory
214218
#' @param reg_id Regional aggregation ID
215-
#' @param model_dir Model directory
216219
#' @return List with region info and palettes
217220
#' @keywords internal
218-
.extract_region_info <- function(filelist, results_dir, reg_id = NULL, model_dir = NULL) {
221+
.extract_region_info <- function(filelist, results_dir, reg_id = NULL) {
219222
# Determine reg_id if not provided
220223
if (is.null(reg_id)) {
221224
# Try to read conf directly from the first GDX file
@@ -248,24 +251,6 @@
248251
# Get regions from GDX files
249252
regions <- .get_regions_from_gdx(filelist, results_dir)
250253

251-
# Check for historical data directory - try to find actual directory
252-
if (!is.null(model_dir) && length(model_dir) > 0 && !is.null(reg_id) && length(reg_id) > 0) {
253-
data_dir <- file.path(model_dir, paste0("data_", reg_id[1]))
254-
if (!dir.exists(data_dir)) {
255-
# Try to find a directory that starts with data_<reg_id>
256-
potential_dirs <- list.dirs(model_dir, full.names = FALSE, recursive = FALSE)
257-
matching_dirs <- grep(paste0("^data_", reg_id[1]), potential_dirs, value = TRUE)
258-
if (length(matching_dirs) > 0) {
259-
data_dir <- file.path(model_dir, matching_dirs[1])
260-
message("Found data directory: ", matching_dirs[1])
261-
# Update reg_id to match actual directory
262-
reg_id <- gsub("^data_", "", matching_dirs[1])
263-
} else {
264-
warning("Historical data directory not found: ", data_dir,
265-
"\nHistorical data features will be disabled.")
266-
}
267-
}
268-
}
269254

270255
# Create color palettes
271256
palette <- get_region_palette(regions, reg_id)

0 commit comments

Comments
 (0)