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

Master mppalves #33

Merged
merged 4 commits into from
Aug 14, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
2 changes: 1 addition & 1 deletion .buildlibrary
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ValidationKey: '26521208'
ValidationKey: '26555690'
AutocreateReadme: yes
AcceptedWarnings:
- 'Warning: package ''.*'' was built under R version'
Expand Down
4 changes: 2 additions & 2 deletions CITATION.cff
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ cff-version: 1.2.0
message: If you use this software, please cite it using the metadata from this file.
type: software
title: 'mrmagpie: madrat based MAgPIE Input Data Library'
version: 1.35.7
date-released: '2023-07-06'
version: 1.35.8
date-released: '2023-07-17'
abstract: Provides functions for MAgPIE country and cellular input data generation.
authors:
- family-names: Karstens
Expand Down
4 changes: 2 additions & 2 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Type: Package
Package: mrmagpie
Title: madrat based MAgPIE Input Data Library
Version: 1.35.7
Date: 2023-07-06
Version: 1.35.8
Date: 2023-07-17
Authors@R: c(
person("Kristine", "Karstens", , "[email protected]", role = c("aut", "cre")),
person("Jan Philipp", "Dietrich", , "[email protected]", role = "aut"),
Expand Down
83 changes: 42 additions & 41 deletions R/calcPastureSuit.R
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
#' @title calcPastureSuit
#' @description Calculate glassland suitable for pasture management based on population and aridity criteria.
#' @param subtype Select version, climate model and period.
#' @description Calculate glassland suitable for pasture management based
#' on population and aridity criteria.
#' @param datasource Document
#' @param climatetype Document
#' @param lpjml Document
Copy link
Member

Choose a reason for hiding this comment

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

What does the "Document" here stands for? ^^'

#' @param smoothPrecipitation Smooth precipitation climate data over time
#' @param smoothOut smooth the Pasture suitability areas variations over time
#' @return List of magpie object with results on cluster level
Expand All @@ -11,58 +14,54 @@
#' }
#' @importFrom raster area rasterFromXYZ

calcPastureSuit <- function(subtype = "ISIMIP3bv2:IPSL-CM6A-LR:1850-2100", smoothPrecipitation = 10, smoothOut = 10) {
x <- toolSplitSubtype(subtype, list(version = NULL, climatemodel = NULL, period = NULL))

# pasture drivers
calcPastureSuit <- function(datasource = "ISIMIP3bv2", climatetype = "MRI-ESM2-0:ssp126",
lpjml = "LPJmL4_for_MAgPIE_44ac93de", smoothPrecipitation = 10, smoothOut = 10) {
Copy link
Member

Choose a reason for hiding this comment

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

You don't need 'smoothPrecipitation' and 'smoothOut' anymore.
Remove it as parameters here and in the header.

Also the datasource argument is a bit unclear to me. It isn't used anymore, right?
This is now mainly handled by the toolClimateInputVersion and is set automatically (depending on the LPJmL version in the future and for now to a given default). Also consider removing it (but please check maybe I missed where it is used).

x <- toolSplitSubtype(climatetype, list(climatemodel = NULL, scenario = NULL))
# Drivers of managed pastures
population <- calcOutput("GridPop", subtype = "all", cellular = TRUE, FiveYear = TRUE,
harmonize_until = 2015, aggregate = FALSE)

precipitation <- list()
scenarios <- c("ssp126", "ssp245", "ssp370", "ssp460", "ssp585") # Current ISIMIP3bv2 scenarios
for (scenario in scenarios) {
subtype <- paste(x$version, x$climatemodel, scenario, x$period, "pr", "annual_mean", sep = ":")
precipitation[[scenario]] <- setNames(calcOutput("GCMClimate", subtype = subtype,
smooth = smoothPrecipitation, aggregate = FALSE), scenario)
}
precipitation <- collapseNames(mbind(precipitation))

evapotranspiration <- calcOutput("Evapotranspiration", subtype = "H08:mri-esm2-0", aggregate = FALSE)

# temporary mapping of evapotranspiration RCP scenarios unavailable in ISIMIP3bv2
evapotranspiration <- add_columns(evapotranspiration, addnm = "ssp245", dim = 3.1, fill = NA)
evapotranspiration[, , "ssp245"] <- evapotranspiration[, , "ssp370"]
evapotranspiration <- add_columns(evapotranspiration, addnm = "ssp460", dim = 3.1, fill = NA)
evapotranspiration[, , "ssp460"] <- evapotranspiration[, , "ssp370"]

evapotranspiration <- evapotranspiration[, , getItems(precipitation, dim = 3)]

# matching available ssps scenarios
regex <- paste0("[", paste0("+", strtrim(getItems(evapotranspiration, dim = 3), 4), collapse = "|"), "]", "{4}$")
avlSSPs <- grep(regex, getNames(population), ignore.case = TRUE)
population <- population[, , avlSSPs]
harmonize_until = 2015,
aggregate = FALSE)[, , toupper(substring(x$scenario, first = 0, last = 4))]

cellPrep <- calcOutput("LPJmLClimateInput", climatetype = climatetype,
variable = "precipitation:monthlySum",
stage = "smoothed",
Copy link
Member

Choose a reason for hiding this comment

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

stage has to be 'harmonized2020' (as this is future data, right?)

lpjmlVersion = lpjml,
aggregate = FALSE)


cellPet <- calcOutput(type = "LPJmL_new", climatetype = climatetype,
subtype = "mpet",
stage = "smoothed",
Copy link
Member

Choose a reason for hiding this comment

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

stage has to be 'harmonized2020' (as this is future data, right?)

version = lpjml,
aggregate = FALSE)
cellPrep <- mrwater::toolLPJcell2MAgPIEcell(cellPrep)
cellPet <- mrwater::toolLPJcell2MAgPIEcell(cellPet)

yearsCellPet <- intersect(getYears(cellPet), findset("time"))
yearsCellPrep <- intersect(findset("time"), getYears(cellPrep))
years <- intersect(yearsCellPet, yearsCellPrep)
cellPrep <- dimSums(cellPrep[, years, ], dim = 3)
Copy link
Member

Choose a reason for hiding this comment

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

It seems you only need yearly precipitation and pet, is this correct?
We might than already call the function for yearly sums as this would speed up harmonization, but might smooth out more extreme yearly fluctuations. Maybe we ask Jens here once again, what makes sense.

cellPet <- dimSums(cellPet[, years, ], dim = 3)

# Cell area calculation
landcoords <- as.data.frame(toolGetMapping("magpie_coord.rda", type = "cell", where = "mappingfolder"))
landcoords <- cbind(landcoords, rep(1, nrow(landcoords)))
landcoords <- raster::rasterFromXYZ(landcoords)
crs(landcoords) <- "+proj=longlat" # outputs cell are in km2
raster::crs(landcoords) <- "+proj=longlat" # outputs cell are in km2
Copy link
Member

Choose a reason for hiding this comment

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

Do you really need cellsize or landarea size of a given cell?
If you need this to calculate out of total numbers density - maybe landarea size per cell makes more sense?

there is a function already calculating this:
calcOutput("CellArea", aggregate = FALSE)

cellSize <- raster::area(landcoords)
cellSize <- cellSize * landcoords
cellSize <- as.magpie(cellSize)
cellSize <- toolOrderCells(collapseDim(addLocation(cellSize), dim = c("x", "y")))

# population density
population <- population[getCells(cellPet), , ] # fixing the order of the population cells (should not be necessary!)
popDensity <- (population * 1e6) / cellSize # population density in number of people per km2
popDensity[is.infinite(popDensity)] <- 0
popDensity[is.nan(popDensity)] <- 0

years <- intersect(getYears(popDensity), getYears(cellPrep))

yearsCom <- intersect(getYears(popDensity), getYears(precipitation))

# Aridity (the real aridity is measured as the ratio between evapotranspiration
# and precipitarion (I have complete this calculation))
aridity <- precipitation[, yearsCom, ] / (evapotranspiration[, yearsCom, ])
aridity <- cellPrep[, years, ] / cellPet[, years, ]
aridity[is.infinite(aridity) | is.nan(aridity)] <- 0
# 0.5 aridity threshold for managed pastures. Same from HYDE 3.2.
aridity[aridity < 0.5] <- 0
Expand Down Expand Up @@ -90,9 +89,11 @@ calcPastureSuit <- function(subtype = "ISIMIP3bv2:IPSL-CM6A-LR:1850-2100", smoot
map <- toolGetMapping("CountryToCellMapping.csv", type = "cell")
pastureSuitAreaReg <- toolAggregate(pastureSuitArea, rel = map, from = "celliso", to = "iso")
histPastrReg <- toolAggregate(histPastr, rel = map, from = "celliso", to = "iso")
corrReg <- histPastrReg[, pastLy, ] / pastureSuitAreaReg[, pastLy, ]
pastureSuitArea[, future, ] <- toolAggregate(corrReg, rel = map, from = "iso", to = "celliso") *
pastureSuitArea[, future, ]
calibReg <- histPastrReg[, pastLy, ] / pastureSuitAreaReg[, pastLy, ]
calibReg[is.infinite(calibReg)] <- 1
calibReg[is.nan(calibReg)] <- 0
pastureSuitArea[, future, ] <- toolAggregate(calibReg, rel = map,
from = "iso", to = "celliso") * pastureSuitArea[, future, ]

pastureSuitArea[is.infinite(pastureSuitArea) | is.nan(pastureSuitArea) | is.na(pastureSuitArea)] <- 0
pastureSuitArea[pastureSuitArea < 0] <- 0
Expand All @@ -106,7 +107,7 @@ calcPastureSuit <- function(subtype = "ISIMIP3bv2:IPSL-CM6A-LR:1850-2100", smoot
pastureSuitArea <- toolHoldConstant(pastureSuitArea, findset("time"))
pastureSuitArea <- collapseNames(pastureSuitArea)
pastureSuitArea[, pastAll, ] <- histPastr[, pastAll, ]

pastureSuitArea <- setNames(pastureSuitArea, "yields")
return(list(
x = pastureSuitArea,
weight = NULL,
Expand Down
7 changes: 4 additions & 3 deletions R/fullCELLULARMAGPIE.R
Original file line number Diff line number Diff line change
Expand Up @@ -206,12 +206,13 @@ fullCELLULARMAGPIE <- function(rev = 0.1, dev = "",
subtype = "/co2/Nreturn0p5", # nolint
lsu_levels = c(seq(0, 2.2, 0.2), 2.5), past_mngmt = "mdef",
file = paste0("f31_grassl_yld.mz"), years = magYears, aggregate = FALSE)
calcOutput("PastureSuit", subtype = paste("ISIMIP3bv2", "MRI-ESM2-0", "1850_2100", sep = ":"),
calcOutput("PastureSuit", datasource = "ISIMIP3bv2", climatetype = "MRI-ESM2-0:ssp126",
Copy link
Member

Choose a reason for hiding this comment

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

climatetype and lpjml argument has to be set to the flexible arguments as they change with the preprocessing settings.

See e.g.:

calcOutput("Carbon", aggregate = FALSE, lpjml = lpjml, climatetype = climatetype,

My guess how the call should look like:
calcOutput("PastureSuit", climatetype = climatetype, lpjml = lpjml[["natveg"]],
file = paste0("f31_pastr_suitability_", ctype, ".mz"), years = lpjYears, aggregate = "cluster")

Check which years make most sense (magYears or lpjYears) and the lpjml version ('natveg' or 'grass').

lpjml = "LPJmL4_for_MAgPIE_44ac93de",
file = paste0("f31_pastr_suitability_", ctype, ".mz"), years = magYears, aggregate = "cluster")
calcOutput("PastureSuit", subtype = paste("ISIMIP3bv2", "MRI-ESM2-0", "1850_2100", sep = ":"),
calcOutput("PastureSuit", datasource = "ISIMIP3bv2", climatetype = "MRI-ESM2-0:ssp126",
lpjml = "LPJmL4_for_MAgPIE_44ac93de",
file = "f31_pastr_suitability.mz", years = magYears, aggregate = FALSE)


if (grepl("+PastrMngtLevels", dev)) {
calcOutput("PastrMngtLevels", climatetype = paste0("MRI-ESM2-0", ":", climatescen),
options = c("brazil_1", "brazil_2", "brazil_4"), cost_level = c(1, 2, 3),
Expand Down
6 changes: 3 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
# madrat based MAgPIE Input Data Library

R package **mrmagpie**, version **1.35.7**
R package **mrmagpie**, version **1.35.8**

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

Expand Down Expand Up @@ -39,7 +39,7 @@ In case of questions / problems please contact Kristine Karstens <karstens@pik-p

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

Karstens K, Dietrich J, Chen D, Windisch M, Alves M, Beier F, v. Jeetze P, Mishra A, Humpenoeder F, Führlich P (2023). _mrmagpie: madrat based MAgPIE Input Data Library_. doi: 10.5281/zenodo.4319612 (URL: https://doi.org/10.5281/zenodo.4319612), R package version 1.35.7, <URL: https://github.com/pik-piam/mrmagpie>.
Karstens K, Dietrich J, Chen D, Windisch M, Alves M, Beier F, v. Jeetze P, Mishra A, Humpenoeder F, Führlich P (2023). _mrmagpie: madrat based MAgPIE Input Data Library_. doi: 10.5281/zenodo.4319612 (URL: https://doi.org/10.5281/zenodo.4319612), R package version 1.35.8, <URL: https://github.com/pik-piam/mrmagpie>.

A BibTeX entry for LaTeX users is

Expand All @@ -48,7 +48,7 @@ A BibTeX entry for LaTeX users is
title = {mrmagpie: madrat based MAgPIE Input Data Library},
author = {Kristine Karstens and Jan Philipp Dietrich and David Chen and Michael Windisch and Marcos Alves and Felicitas Beier and Patrick {v. Jeetze} and Abhijeet Mishra and Florian Humpenoeder and Pascal Führlich},
year = {2023},
note = {R package version 1.35.7},
note = {R package version 1.35.8},
doi = {10.5281/zenodo.4319612},
url = {https://github.com/pik-piam/mrmagpie},
}
Expand Down
13 changes: 10 additions & 3 deletions man/calcPastureSuit.Rd

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

Loading