Skip to content

Commit

Permalink
updated reportTrade and reportEmmissions to allow for reporting of va…
Browse files Browse the repository at this point in the history
…riables required for AgMIP
  • Loading branch information
FelicitasBeier committed Feb 27, 2024
1 parent fac4326 commit 3d1be60
Show file tree
Hide file tree
Showing 8 changed files with 74 additions and 48 deletions.
2 changes: 1 addition & 1 deletion .buildlibrary
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ValidationKey: '2377813140'
ValidationKey: '2377832920'
AutocreateReadme: yes
AcceptedWarnings:
- 'Warning: package ''.*'' was built under R version'
Expand Down
2 changes: 1 addition & 1 deletion CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ cff-version: 1.2.0
message: If you use this software, please cite it using the metadata from this file.
type: software
title: 'magpie4: MAgPIE outputs R package for MAgPIE version 4.x'
version: 1.202.13
version: 1.202.14
date-released: '2024-02-27'
abstract: Common output routines for extracting results from the MAgPIE framework
(versions 4.x).
Expand Down
2 changes: 1 addition & 1 deletion DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
Type: Package
Package: magpie4
Title: MAgPIE outputs R package for MAgPIE version 4.x
Version: 1.202.13
Version: 1.202.14
Date: 2024-02-27
Authors@R: c(
person("Benjamin Leon", "Bodirsky", , "[email protected]", role = c("aut", "cre")),
Expand Down
6 changes: 5 additions & 1 deletion R/getReportAgMIP.R
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,6 @@ getReportAgMIP <- function(gdx, file = NULL, scenario = NULL, filter = c(1, 2, 7
"reportEmissions(gdx)",
# "reportEmisAerosols(gdx)", #nolint
# "reportEmissionsBeforeTechnicalMitigation(gdx)", #nolint
# "reportEmisPhosphorus(gdx)", #nolint
# "reportCosts(gdx)", #nolint
# "reportCostsPresolve(gdx)", #nolint
# "reportPriceFoodIndex(gdx)", #nolint
Expand All @@ -102,6 +101,7 @@ getReportAgMIP <- function(gdx, file = NULL, scenario = NULL, filter = c(1, 2, 7
# "reportPriceLand(gdx)", #nolint
# "reportPriceWater(gdx)", #nolint
"reportValueTrade(gdx, detail = TRUE)",
"reportFactorCostShares(gdx, type = 'requirements')",
# "reportValueConsumption(gdx)", #nolint
# "reportProcessing(gdx, indicator='primary_to_process')", #nolint
# "reportProcessing(gdx, indicator='secondary_from_primary')", #nolint
Expand All @@ -126,6 +126,10 @@ getReportAgMIP <- function(gdx, file = NULL, scenario = NULL, filter = c(1, 2, 7
x <- .filtermagpie(mbind(output), gdx, filter = filter)
names(dimnames(x)) <- c("i", "year", "data")

# Add non-traded goods with value of zero to trade reporting
nontraded <- findset("k_notrade")


### conversion to AgMIP regions in 3 steps
# Downscaling from MAgPIE regions to country level
# Aggregation from country level to AgMIP regions
Expand Down
40 changes: 25 additions & 15 deletions R/reportEmissions.R
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
#' @return GHG emissions as MAgPIE object (Unit: Mt CO2/yr, Mt N2O/yr, and Mt CH4/yr, for cumulative emissions Gt CO2)
#' @author Florian Humpenoeder, Benjamin Leon Bodirsky, Michael Crawford
#' @examples
#'
#' \dontrun{
#' x <- reportEmissions(gdx)
#' }
Expand All @@ -31,7 +30,6 @@
#' @md
#'
reportEmissions <- function(gdx, storageWood = TRUE) {

# -----------------------------------------------------------------------------------------------------------------
# Calculate CO2 emissions from a MAgPIE .gdx file

Expand All @@ -46,8 +44,8 @@ reportEmissions <- function(gdx, storageWood = TRUE) {
.calcCO2 <- function(.lowpass = 3, .cumulative = FALSE, .raw = FALSE, .landCarbonSink = "grassi") {

co2 <- emisCO2(gdx,
level = "regglo", unit = "gas", sum_land = FALSE, sum_cpool = FALSE,
lowpass = .lowpass, cumulative = .cumulative)
level = "regglo", unit = "gas", sum_land = FALSE, sum_cpool = FALSE,
lowpass = .lowpass, cumulative = .cumulative)

if (.landCarbonSink == "grassi") {
# To ensure consistency with national forest inventories, we replace our estimates of indirect emissions
Expand Down Expand Up @@ -157,7 +155,7 @@ reportEmissions <- function(gdx, storageWood = TRUE) {
if (is.null(peatland)) {
peatland <- new.magpie(getCells(co2), getYears(co2), "peatland", fill = 0)
} else {
peatland <- setNames(dimSums(peatland[,,c("co2","doc")], dim = 3), "peatland")
peatland <- setNames(dimSums(peatland[, , c("co2", "doc")], dim = 3), "peatland")
}

if (!is.null(peatland)) {
Expand Down Expand Up @@ -333,11 +331,10 @@ reportEmissions <- function(gdx, storageWood = TRUE) {
# Calculated indirect emissions from land-use change from a .gdx file

.calcLandCarbonSink <- function(.lowpass = 3, .cumulative = FALSE) {

# Estimate of land-carbon sink from LPJmL
co2 <- emisCO2(gdx,
level = "regglo", unit = "gas", sum_land = FALSE, sum_cpool = FALSE,
lowpass = .lowpass, cumulative = .cumulative)
level = "regglo", unit = "gas", sum_land = FALSE, sum_cpool = FALSE,
lowpass = .lowpass, cumulative = .cumulative)

# Estimate of land-carbon sink from LPJmL
LPJmlLCS <- co2[, , "cc", drop = TRUE]
Expand Down Expand Up @@ -467,15 +464,15 @@ reportEmissions <- function(gdx, storageWood = TRUE) {
peatland_n2o <- c("peatland")

nEmissions <- Emissions(gdx, level = "regglo", type = .type, unit = "gas", subcategories = TRUE, inorg_fert_split = TRUE)
#use PeatlandEmissions for reporting to exclude emissions from intact peatlands
if (.type %in% c("n2o_n","n2o_n_direct")) {
if ("peatland" %in% getItems(nEmissions, dim = 3.1)) nEmissions <- nEmissions[,,"peatland",invert=TRUE]
# use PeatlandEmissions for reporting to exclude emissions from intact peatlands
if (.type %in% c("n2o_n", "n2o_n_direct")) {
if ("peatland" %in% getItems(nEmissions, dim = 3.1)) nEmissions <- nEmissions[, , "peatland", invert = TRUE]
peatlandN2O <- PeatlandEmissions(gdx, unit = "gas", level = "regglo", intact = FALSE)
if (is.null(peatlandN2O)) {
nEmissions <- add_columns(nEmissions, addnm = "peatland", dim = "emis_source", fill = 0)
} else {
nEmissions <- add_columns(nEmissions, addnm = "peatland", dim = "emis_source", fill = 0)
nEmissions[,,"peatland"] <- collapseNames(peatlandN2O[, , "n2o"])
nEmissions[, , "peatland"] <- collapseNames(peatlandN2O[, , "n2o"])
}
}

Expand Down Expand Up @@ -528,8 +525,8 @@ reportEmissions <- function(gdx, storageWood = TRUE) {

# combine all CH4 emissions in one object
ch4 <- collapseNames(Emissions(gdx, level = "regglo", type = "ch4", unit = "gas", subcategories = TRUE), collapsedim = 2)
#use PeatlandEmissions for reporting to exclude emissions from intact peatlands
if ("peatland" %in% getNames(ch4, dim = 1)) ch4 <- ch4[,,"peatland",invert=TRUE]
# use PeatlandEmissions for reporting to exclude emissions from intact peatlands
if ("peatland" %in% getNames(ch4, dim = 1)) ch4 <- ch4[, , "peatland", invert = TRUE]
peatlandCH4 <- PeatlandEmissions(gdx, unit = "gas", level = "regglo", intact = FALSE)
if (is.null(peatlandCH4)) {
ch4 <- add_columns(ch4, addnm = "peatland", dim = "emis_source", fill = 0)
Expand Down Expand Up @@ -564,6 +561,18 @@ reportEmissions <- function(gdx, storageWood = TRUE) {
emissions <- Emissions(gdx, level = "regglo", type = "n2o_n", unit = .unit, subcategories = TRUE)
emissions <- collapseNames(emissions, collapsedim = 2)

# disaggregate N2O emissions to croparea by crop using Nitrogen withdrawals as weight
withdrawalN <- collapseNames(NitrogenBudgetWithdrawals(gdx, kcr = "kcr", net = TRUE, level = "regglo"))
emisCroparea <- dimSums(emissions[, , c("SOM", "inorg_fert", "man_crop", "awms", "resid", "rice")], dim = 3)
mapping <- data.frame(kall = getItems(withdrawalN, dim = 3),
d3 = rep("NULL", length(getItems(withdrawalN, dim = 3))))
emisCropareabycrop <- toolAggregate(x = emisCroparea, rel = mapping,
weight = withdrawalN,
from = "d3", to = "kall", dim = 3)
emisCropareabycrop <- reporthelper(emisCropareabycrop, dim = 3.1,
level_zero_name = "Emissions|N2O_GWP100AR6|Land|Agriculture|Croparea",
detail = TRUE, sort = FALSE, partly = FALSE, version = NULL)

.createReport <- function(.emission, .name = NULL) {
t <- dimSums(emissions[, , .emission], dim = 3)
n <- paste0("Emissions|N2O_", .unit, "|Land", .name, " (Mt CO2e/yr)")
Expand All @@ -586,7 +595,8 @@ reportEmissions <- function(gdx, storageWood = TRUE) {
.createReport(c("resid_burn"), "|+|Biomass Burning"),
.createReport(c("resid_burn"), "|Biomass Burning|+|Burning of Crop Residues"),
.createReport(c("peatland"), "|+|Peatland"),
.createReport(c("peatland"), "|Peatland|+|Managed")
.createReport(c("peatland"), "|Peatland|+|Managed"),
emisCropareabycrop
)
# nolint end

Expand Down
63 changes: 38 additions & 25 deletions R/reportTrade.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,45 +17,58 @@

reportTrade <- function(gdx, detail = FALSE) {

nontraded <- findset("k_notrade")

x <- NULL

# net-exports
out <- trade(gdx,level = "regglo",type = "net-exports")
# add non-traded goods with value of 0
out <- add_columns(out, addnm = nontraded, dim = 3)
out[, , nontraded] <- 0

out <- reporthelper(x=out,dim = 3.1,level_zero_name = "Trade|Net-Trade", detail = detail,partly=TRUE)
getNames(out) <- paste(getNames(out),"(Mt DM/yr)",sep=" ")
out <- reporthelper(x = out, dim = 3.1, level_zero_name = "Trade|Net-Trade",
detail = detail, partly = TRUE)
getNames(out) <- paste(getNames(out), "(Mt DM/yr)", sep = " ")
x <- mbind(x,out)
x <- summationhelper(x,excludeLevels=1)
x <- summationhelper(x, excludeLevels = 1)

# # gross exports
out <- trade(gdx,level = "regglo",type = "exports")
out<-reporthelper(x=out,dim = 3.1,level_zero_name = "Trade|Exports",detail = detail, partly = TRUE)
# add non-traded goods with value of 0
out <- add_columns(out, addnm = nontraded, dim = 3)
out[, , nontraded] <- 0

out <- reporthelper(x = out, dim = 3.1,
level_zero_name = "Trade|Exports", detail = detail, partly = TRUE)
getNames(out) <- paste(getNames(out),"(Mt DM/yr)",sep=" ")
out <- summationhelper(out,excludeLevels=1)
x <- mbind(x,out)
out <- summationhelper(out, excludeLevels = 1)
x <- mbind(x,out)
#
# # gross imports
out<-trade(gdx,level = "regglo",type = "imports")
out<-reporthelper(x=out,dim = 3.1,level_zero_name = "Trade|Imports",detail = detail, partly = TRUE)
getNames(out) <- paste(getNames(out),"(Mt DM/yr)",sep=" ")
out <- summationhelper(out,excludeLevels=1)
x <- mbind(x,out)
out <- trade(gdx,level = "regglo",type = "imports")
# add non-traded goods with value of 0
out <- add_columns(out, addnm = nontraded, dim = 3)
out[, , nontraded] <- 0

out <- reporthelper(x = out, dim = 3.1,level_zero_name = "Trade|Imports", detail = detail, partly = TRUE)
getNames(out) <- paste(getNames(out), "(Mt DM/yr)", sep=" ")
out <- summationhelper(out, excludeLevels = 1)
x <- mbind(x, out)

# self_sufficiency
self_suff<-suppressMessages(trade(gdx,level = "regglo",relative=TRUE,weight=TRUE))
weight<-self_suff$weight
self_suff<-self_suff$x
out<-(
reporthelper(x=self_suff*weight,dim = 3.1,level_zero_name = "Trade|Self-sufficiency",detail = detail)
/ reporthelper(x=weight,dim = 3.1,level_zero_name = "Trade|Self-sufficiency",detail = detail)
)

#correct after report helping here
#x/0 --> 100
#0/0 --> 1

getNames(out) <- paste(getNames(out),"(1)",sep=" ")
x <- mbind(x,out)
self_suff <- suppressMessages(trade(gdx, level = "regglo", relative = TRUE, weight = TRUE))
weight <- self_suff$weight
self_suff <- self_suff$x
out <- (reporthelper(x = self_suff * weight, dim = 3.1,
level_zero_name = "Trade|Self-sufficiency",
detail = detail) / reporthelper(x = weight,
dim = 3.1,
level_zero_name = "Trade|Self-sufficiency",
detail = detail))

getNames(out) <- paste(getNames(out), "(1)", sep = " ")
x <- mbind(x, out)

return(x)
}
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# MAgPIE outputs R package for MAgPIE version 4.x

R package **magpie4**, version **1.202.13**
R package **magpie4**, version **1.202.14**

[![CRAN status](https://www.r-pkg.org/badges/version/magpie4)](https://cran.r-project.org/package=magpie4) [![DOI](https://zenodo.org/badge/DOI/10.5281/zenodo.1158582.svg)](https://doi.org/10.5281/zenodo.1158582) [![R build status](https://github.com/pik-piam/magpie4/workflows/check/badge.svg)](https://github.com/pik-piam/magpie4/actions) [![codecov](https://codecov.io/gh/pik-piam/magpie4/branch/master/graph/badge.svg)](https://app.codecov.io/gh/pik-piam/magpie4) [![r-universe](https://pik-piam.r-universe.dev/badges/magpie4)](https://pik-piam.r-universe.dev/builds)

Expand Down Expand Up @@ -39,7 +39,7 @@ In case of questions / problems please contact Benjamin Leon Bodirsky <bodirsky@

To cite package **magpie4** in publications use:

Bodirsky B, Humpenoeder F, Dietrich J, Stevanovic M, Weindl I, Karstens K, Wang X, Mishra A, Beier F, Breier J, Yalew A, Chen D, Biewald A, Wirth S, von Jeetze P, Leip D, Crawford M, Alves M (2024). _magpie4: MAgPIE outputs R package for MAgPIE version 4.x_. doi: 10.5281/zenodo.1158582 (URL: https://doi.org/10.5281/zenodo.1158582), R package version 1.202.13, <URL: https://github.com/pik-piam/magpie4>.
Bodirsky B, Humpenoeder F, Dietrich J, Stevanovic M, Weindl I, Karstens K, Wang X, Mishra A, Beier F, Breier J, Yalew A, Chen D, Biewald A, Wirth S, von Jeetze P, Leip D, Crawford M, Alves M (2024). _magpie4: MAgPIE outputs R package for MAgPIE version 4.x_. doi:10.5281/zenodo.1158582 <https://doi.org/10.5281/zenodo.1158582>, R package version 1.202.14, <https://github.com/pik-piam/magpie4>.

A BibTeX entry for LaTeX users is

Expand All @@ -48,7 +48,7 @@ A BibTeX entry for LaTeX users is
title = {magpie4: MAgPIE outputs R package for MAgPIE version 4.x},
author = {Benjamin Leon Bodirsky and Florian Humpenoeder and Jan Philipp Dietrich and Miodrag Stevanovic and Isabelle Weindl and Kristine Karstens and Xiaoxi Wang and Abhijeet Mishra and Felicitas Beier and Jannes Breier and Amsalu Woldie Yalew and David Chen and Anne Biewald and Stephen Wirth and Patrick {von Jeetze} and Debbora Leip and Michael Crawford and Marcos Alves},
year = {2024},
note = {R package version 1.202.13},
note = {R package version 1.202.14},
doi = {10.5281/zenodo.1158582},
url = {https://github.com/pik-piam/magpie4},
}
Expand Down
1 change: 0 additions & 1 deletion man/reportEmissions.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit 3d1be60

Please sign in to comment.