From e801bcdc3aa3e3f39b521d0e0e11d3b3a6e83482 Mon Sep 17 00:00:00 2001 From: Michael Crawford Date: Wed, 11 Sep 2024 17:31:20 +0200 Subject: [PATCH] Added convertToNetCDF output script --- CHANGELOG.md | 1 + scripts/output/extra/convertToNetCDF.R | 43 ++++++++++++++++++++++++++ 2 files changed, 44 insertions(+) create mode 100644 scripts/output/extra/convertToNetCDF.R diff --git a/CHANGELOG.md b/CHANGELOG.md index d0015d3fd..e856625b7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -18,6 +18,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/). ### added +- **scripts** added output script converting all grid-level .mz files to .nc (netCDF) - **scripts** added output report `EU_report.R` that uses `EU_report.Rmd` - **scripts** added out of bounds check as output script - **70_livestock** added realization `fbask_jan16_sticky` diff --git a/scripts/output/extra/convertToNetCDF.R b/scripts/output/extra/convertToNetCDF.R new file mode 100644 index 000000000..99d9dffec --- /dev/null +++ b/scripts/output/extra/convertToNetCDF.R @@ -0,0 +1,43 @@ +# | (C) 2008-2024 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: Convert all .mz files to NetCDF (.nc) for a magpie directory +# comparison script: FALSE +# --------------------------------------------------------------- + +# Version 1.00 - Michael Crawford +# 1.00: first working version + +library(gms) +library(magclass) + +############################# BASIC CONFIGURATION ####################################### +if (!exists("source_include")) { + + title <- NULL + outputdir <- NULL + + # Define arguments that can be read from command line + readArgs("outputdir", "title") + +} +######################################################################################### + +message("Converting all .mz outputs to .nc for output directory: ", outputdir) + +mzFiles <- list.files(path = outputdir, pattern = "0\\.5(_share)?\\.mz$", full.names = TRUE) + +lapply(X = mzFiles, FUN = function(x) { + tryCatch({ + magObj <- magclass::read.magpie(x) + newName <- sub("\\.[^.]+$", "", x) + write.magpie(x = magObj, file_name = paste0(newName, ".nc"), file_folder = outputdir, append = FALSE) + }, error = function(e) { + message("Error processing file: ", x, " - ", e$message) + }) +}) \ No newline at end of file