Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creation of FSDP_process & revision of FSDP_collect #450

Merged
merged 20 commits into from
Sep 16, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
bc7e502
Added m4fsdp::appendReportNitrogenSurplus to FSEC_nitrogenPollution
mscrawford Sep 1, 2022
596fe84
Updated nutrient surplus filename in FSDP collect
mscrawford Sep 2, 2022
c9843cb
Deleted undeveloped (dead) fsdp scripts
mscrawford Sep 2, 2022
e5f2328
converted FSEC_mergeDietaryIndicators to comparison script
mscrawford Sep 2, 2022
5311d32
Added output script FSDP_process.R
mscrawford Sep 6, 2022
bc69f98
Revert "Added m4fsdp::appendReportNitrogenSurplus to FSEC_nitrogenPol…
mscrawford Sep 7, 2022
6e55841
Deleted FSEC_mergeDietaryIndicators
mscrawford Sep 7, 2022
05bfa80
Deleted FSEC_reportHealthImpacts.R (now incl in FSDP_process)
mscrawford Sep 8, 2022
3a9834b
Added FSDP_process.R to fsec.R output scripts
mscrawford Sep 8, 2022
6c90630
Added append nutrients and health impacts to FSDP_collect
mscrawford Sep 8, 2022
388809f
Added selection criterion for dietary impacts merge
mscrawford Sep 8, 2022
c010e3a
Added health impacts and nutrient surplus to FSDP_collect.R
mscrawford Sep 13, 2022
57eb672
Updated changelog
mscrawford Sep 13, 2022
cb630ac
Added SimonDietz to output scripts run in the FSEC project
mscrawford Sep 13, 2022
b1fa0ce
Improved documentation in CHANGELOG
mscrawford Sep 13, 2022
3e4b005
Update scripts/output/projects/FSDP_process.R
mscrawford Sep 15, 2022
0c54fde
Update FSDP_process.R
mscrawford Sep 15, 2022
282f62c
Changed ordering of output scripts
mscrawford Sep 15, 2022
6f399f5
Update parameter name in FSDP::collect
mscrawford Sep 15, 2022
87ecf03
Updated FSDP_collect.R based on PR comments
mscrawford Sep 16, 2022
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]

### changed
- **scripts** FSDP_collect handles the health impacts data provided by Marco Springmann, distributed it into the scenario's various reports. It performs a similar operation for global nutrient surplus (which must be calculated on the grid-level and then aggregated).
- **13_tc** relaxed vm_tau upper limit
- **scripts** updated FSEC start and output scripts
- **scripts** update of rds_report to allow gridded intermediate outputs
Expand All @@ -21,9 +22,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **scripts** log files are now written in a subfolder "logs"

### added
- **scripts** added output script creating a merged .csv for dietaryIndicators and caloricSupply outputs
- **scripts** added output script, FSDP_process creating a merged .csv and .gdx for dietaryIndicators and caloricSupply outputs
- **scripts** added output script creating a set of outputs for Simon Dietz in the FSEC context
- **scripts** added output script distributing Marco Springmann's health impacts into the respective output scenario report.mif, report.rds, and report_iso.rds
- **scripts** added output script running MAGICC7 on a MAgPIE scenario
- **scripts** added output script for gridded crop diversity indices
- **scripts** added output scripts for FSEC FSDP runs
Expand Down
81 changes: 70 additions & 11 deletions scripts/output/projects/FSDP_collect.R
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,16 @@
# ---------------------------------------------------------------

# Version 1.0, Florian Humpenoeder
#

library(lucode2)
library(magclass)
library(gms)
library(magpiesets)
library(data.table)
library(gdx)
library(quitte)
library(m4fsdp)
library(stringr)

############################# BASIC CONFIGURATION #############################
if(!exists("source_include")) {
Expand All @@ -27,15 +29,8 @@ if(!exists("source_include")) {
lucode2::readArgs("outputdir")
}
###############################################################################
cat("\nStarting output generation\n")

reg <- NULL
iso <- NULL
grid <- NULL
missing <- NULL

saveRDS(outputdir,"outputdir.rds")

##########
#filter out calibration run
x <- unlist(lapply(strsplit(basename(outputdir),"_"),function(x) x[2]))
outputdir <- outputdir[which(x %in% c("FSECa", "FSECb", "FSECc", "FSECd", "FSECe"))]
Expand All @@ -44,6 +39,71 @@ outputdir <- outputdir[which(x %in% c("FSECa", "FSECb", "FSECc", "FSECd", "FSECe
x <- unlist(lapply(strsplit(basename(outputdir),"_"),function(x) x[1]))
if (length(unique(x)) == 1) rev <- unique(x) else stop("version prefix is not identical. Check your selection of runs")

##########
# Append health impacts reports
hi_datasets_path <- "/p/projects/magpie/data/FSEC_healthImpactsDatasets_raw"
mscrawford marked this conversation as resolved.
Show resolved Hide resolved
hi_datasets <- list.files(hi_datasets_path)
hi_versionToUse <- grep(rev, hi_datasets, value = TRUE)

if (length(hi_versionToUse) == 0) {

message("In FSDP_collect.R: No corresponding version ID was found within the FSEC health impacts datasets.
Using the highest current version.")

highestVersionNr <- max(as.numeric(str_extract(hi_datasets, "(?<=v)(.*?)(?=_)")))
hi_versionToUse <- grep(paste0("v", highestVersionNr), hi_datasets, value = TRUE)

} else if (length(hi_versionToUse) >= 2) {
stop("In FSDP_collect.R: More than one health impacts datasets with this scenario's version ID were found.
Only one is expected.")
}

hi_versionToUse_path <- file.path(hi_datasets_path, hi_versionToUse)
hi_gdx <- suppressWarnings(readGDX(hi_versionToUse_path))

.appendHealthImpacts <- function(.x) {
cfg <- gms::loadConfig(file.path(.x, "config.yml"))
title <- cfg$title

message("Appending health impact report: ", title)
tryCatch(
expr = {
appendReportHealthImpacts(healthImpacts_path = hi_gdx,
scenario = title,
dir = .x)
}, error = function(e) {
message("In FSDP_collect.R: Unable to append health impacts!\n", e)
}
)
}
lapply(X = outputdir, FUN = .appendHealthImpacts)

##########
# Append nutrient surplus reports
.appendNutrientSurplus <- function(.x) {
cfg <- gms::loadConfig(file.path(.x, "config.yml"))
title <- cfg$title

tryCatch(
expr = {
appendReportNutrientSurplus(scenario = title, dir = .x)
mscrawford marked this conversation as resolved.
Show resolved Hide resolved
}, error = function(e) {
message("In FSDP_collect.R: Unable to append the nutrient surplus dataset!\n", e)
}
)
}
lapply(X = outputdir, FUN = .appendNutrientSurplus)

##########
# Generate output files
cat("\nStarting output generation\n")

reg <- NULL
iso <- NULL
grid <- NULL
missing <- NULL

saveRDS(outputdir,"outputdir.rds")

for (i in 1:length(outputdir)) {
print(paste("Processing",outputdir[i]))
Expand Down Expand Up @@ -109,7 +169,7 @@ for (i in 1:length(outputdir)) {
} else missing <- c(missing,outputdir[i])

## Nitrogen
nc_file <- file.path(outputdir[i], paste(cfg$title,"nutrientSurplus_anthropogenic_unaggregated.mz",sep="-"))
nc_file <- file.path(outputdir[i], paste(cfg$title,"nutrientSurplus_intensity.mz",sep="-"))
if(file.exists(nc_file)) {
a <- read.magpie(nc_file)[,years,]
getNames(a) <- "nutrientSurplus (kg N per ha)"
Expand Down Expand Up @@ -156,7 +216,6 @@ val <- as.data.table(read.quitte(val))
saveRDS(val,file = file.path("output",paste(rev,"FSDP_validation.rds",sep="_")), version = 2,compress = "xz")

message("Plotting figures ...")
library(m4fsdp)
heatmapFSDP(reg,tableType=1,file=file.path("output",paste(rev,"FSDP_heatmap1.jpg",sep="_")))
heatmapFSDP(reg,tableType=2,file=file.path("output",paste(rev,"FSDP_heatmap2.jpg",sep="_")))
spatialMapsFSDP(reg,iso,grid,reg2iso,file = file.path("output",paste(rev,"FSDP_spatialMaps.jpg",sep="_")))
112 changes: 112 additions & 0 deletions scripts/output/projects/FSDP_process.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
# | (C) 2008-2022 Potsdam Institute for Climate Impact Research (PIK)
# | authors, and contributors see CITATION.cff file. This file is part
# | of MAgPIE and licensed under AGPL-3.0-or-later. Under Section 7 of
# | AGPL-3.0, you are granted additional permissions described in the
# | MAgPIE License Exception, version 1.0 (see LICENSE file).
# | Contact: magpie@pik-potsdam.de

# -------------------------------------------------------------------------------------------------
# description: Post-processing of FSEC scenarios, specifically generating dietary data
# comparison script: TRUE
# -------------------------------------------------------------------------------------------------

# Version 1.00 - Michael Crawford

library(gms)
library(gdxrrw)
library(withr)

message("Starting FSDP_process output runscript")

############################# BASIC CONFIGURATION #######################################

if (!exists("source_include")) {

outputdir <- file.path("output/", list.dirs("output/", full.names = FALSE, recursive = FALSE))
lucode2::readArgs("outputdir")

}

#########################################################################################

# -----------------------------------------------------------------------------------------------------------------
# Merge dietary outputs from FSEC scenarios into two .csv files
mscrawford marked this conversation as resolved.
Show resolved Hide resolved

message("Merging dietary outputs")

caloricSupply_mergePath <- file.path("output", "caloricSupply.csv")
dietaryIndicators_mergePath <- file.path("output", "dietaryIndicators.csv")

if (file.exists(caloricSupply_mergePath) | file.exists(dietaryIndicators_mergePath)) {
mscrawford marked this conversation as resolved.
Show resolved Hide resolved
message("Merge files are already present for these runs. Removing these old files.")
file.remove(caloricSupply_mergePath, dietaryIndicators_mergePath)
}

message("Creating merge files \"caloricSupply.csv\" and \"dietaryIndicators.csv\"")
file.create(caloricSupply_mergePath, dietaryIndicators_mergePath)

.writeDietaryIndicators <- function(.dir) {

cfg <- gms::loadConfig(file.path(.dir, "config.yml"))
title <- cfg$title

caloricSupply <- read.csv(file.path(.dir, paste0(title, "_caloricSupply.csv")), check.names = FALSE)
dietaryIndicators <- read.csv(file.path(.dir, paste0(title, "_dietaryIndicators.csv")), check.names = FALSE)

if (file.info(caloricSupply_mergePath)$size == 0) {
# Include the header
write.table(caloricSupply, file = caloricSupply_mergePath,
quote = TRUE, sep = ",", row.names = FALSE, col.names = FALSE)
} else {
# Otherwise simply append
write.table(caloricSupply, file = caloricSupply_mergePath,
quote = TRUE, sep = ",", row.names = FALSE, col.names = FALSE,
append = TRUE)
}

if (file.info(dietaryIndicators_mergePath)$size == 0) {
# Include the header
write.table(dietaryIndicators, file = dietaryIndicators_mergePath,
quote = TRUE, sep = ",", row.names = FALSE, col.names = FALSE)
} else {
# Otherwise simply append
write.table(dietaryIndicators, file = dietaryIndicators_mergePath,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

in principle, i recommend using our write.magpie and write.report functions as they have a more standardized format. but now, i would keep it as is.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The difficulty is that I need to run csv2gdx on it, so the .mif format would have been clunkier. Unless write.report can do more than .mifs?

Copy link
Member

@tscheypidi tscheypidi Sep 15, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

wouldn't it be an option to use writeGDX if the aim is to write the data to a gdx file?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I slept on this suggestion, and I think that - although it would greatly improve this entire workflow - I'm going to say that for now I would prefer to leave the code as-is. To do this properly, I would need to re-write the magpie4 function in addition to this function. When we port this code to future projects, I'll do the work of revising it properly. For now we have a working solution. I feel quite silly for not using this in the first place. I guess way back then I wanted to use .csvs because I thought it would be simpler for me and then got locked-in.

quote = TRUE, sep = ",", row.names = FALSE, col.names = FALSE,
append = TRUE)
}
}

message("Writing dietary datasets")

# Only merge dietary indicators from selected, dietary-related, scenarios
dietRelatedScenarios <- c("DietEmptyCals", "DietFish", "DietLegumes", "DietMonogastrics", "DietRuminants", "DietVegFruitsNutsSeeds",
"SoilMonogastric",
"LessFoodWaste",
"NoOverweight", "NoUnderweight",
"BAU",
"FSDP",
"SSP1", "SSP3", "SSP4", "SSP5")

outputdir_diets <- lapply(X = dietRelatedScenarios, FUN = function(.x) grep(x = outputdir, pattern = .x, value = TRUE))
outputdir_diets <- unlist(outputdir_diets)

lapply(X = outputdir_diets, FUN = .writeDietaryIndicators)


# -----------------------------------------------------------------------------------------------------------------
# Produce .gdx files from two .csv files for Marco Springmann

message("Saving dietaryIndicators.csv and caloricSupply.csv as .gdx files")

with_dir(file.path("output"), {
gamsScript <- "csv2gdx_dietaryIndicators.gms"
gamsScriptLst <- "csv2gdx_dietaryIndicators.lst"
file.create(gamsScript)
cat("$call csv2gdx dietaryIndicators.csv output=dietaryIndicators.gdx id=dietaryIndicators index=1..6 values=7..11 useHeader=y\n",
file = gamsScript, append = T)
cat("$call csv2gdx caloricSupply.csv output=caloricSupply.gdx id=caloricSupply index=1,2,3,4 values=5 useHeader=y",
file = gamsScript, append = T)
gams(gamsScript)
file.remove(gamsScript)
file.remove(gamsScriptLst)
})
68 changes: 0 additions & 68 deletions scripts/output/projects/FSEC_mergeDietaryIndicators.R

This file was deleted.

57 changes: 0 additions & 57 deletions scripts/output/projects/FSEC_reportHealthImpacts.R

This file was deleted.

Loading