Skip to content

Commit

Permalink
Major Update including linter and styling
Browse files Browse the repository at this point in the history
  • Loading branch information
k4rst3ns committed Jan 8, 2024
1 parent 84c22be commit f3c5fb4
Show file tree
Hide file tree
Showing 49 changed files with 111 additions and 632 deletions.
2 changes: 1 addition & 1 deletion .buildlibrary
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
ValidationKey: '2310172334175'
ValidationKey: '3946000'
AcceptedWarnings:
- 'Warning: package ''.*'' was built under R version'
- 'Warning: namespace ''.*'' is not available and has been replaced'
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: 'mrsoil: MadRat Soil Organic Carbon Budget Library'
version: 1.17.11.9003
date-released: '2024-01-03'
version: 2.0.0
date-released: '2024-01-08'
abstract: This packages provides functions for soil organic carbon budget for mineral
soils using the steady-state method (Tier 2) of the 2019 Refinement to the 2006
IPP Guidelines for National Greenhouse Gas Inventories.
Expand Down
9 changes: 3 additions & 6 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
Package: mrsoil
Type: Package
Title: MadRat Soil Organic Carbon Budget Library
Version: 1.17.11.9003
Date: 2024-01-03
Version: 2.0.0
Date: 2024-01-08
Authors@R: c(person("Kristine", "Karstens", email = "karstens@pik-potsdam.de", role = c("aut","cre")),
person("Jan Philipp", "Dietrich", email = "dietrich@pik-potsdam.de", role = "aut"))
Description: This packages provides functions for soil organic carbon budget for mineral soils using the steady-state method (Tier 2) of the 2019 Refinement to the 2006 IPP Guidelines for National Greenhouse Gas Inventories.
Expand All @@ -11,14 +11,11 @@ Depends:
magclass(>= 5.15.4),
madrat(>= 1.86.0),
mrcommons(>= 0.11.9),
mrvalidation(>= 2.4.3),
mrmagpie (>= 0.35.0)
mrdrivers(>= 1.0.0)
Imports:
magpiesets,
readxl,
reshape2,
lpjclass,
ncdf4,
utils,
jsonlite
License: LGPL-3 | file LICENSE
Expand Down
13 changes: 1 addition & 12 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -5,29 +5,18 @@ export(toolSoilCarbonCycling)
import(madrat)
import(magclass)
import(mrcommons)
import(mrmagpie)
import(mrvalidation)
import(mrdrivers)
importFrom(jsonlite,fromJSON)
importFrom(lpjclass,read.LPJ_input)
importFrom(madrat,toolSubtypeSelect)
importFrom(madrat,toolTimeAverage)
importFrom(madrat,vcat)
importFrom(magclass,collapseDim)
importFrom(magclass,dimCode)
importFrom(magclass,getYears)
importFrom(magclass,setNames)
importFrom(magclass,setYears)
importFrom(magpiesets,Cell2Country)
importFrom(magpiesets,addLocation)
importFrom(magpiesets,findset)
importFrom(ncdf4,nc_open)
importFrom(ncdf4,ncvar_get)
importFrom(readxl,read_excel)
importFrom(reshape2,colsplit)
importFrom(stats,complete.cases)
importFrom(stats,quantile)
importFrom(utils,download.file)
importFrom(utils,read.csv)
importFrom(utils,tail)
importFrom(utils,untar)
importFrom(utils,write.csv)
7 changes: 5 additions & 2 deletions R/calcCarbonInputMultiplier.R
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,10 @@ calcCarbonInputMultiplier <- function() {
inputProp <- NULL
# get lignin to c and nitrogen to c values for all residues classes
inputProp <- mbind(inputProp,
calcOutput("ParamResidues", source = "IPCC+woody", aggregate = FALSE))
calcOutput("ParamResidues", input = "IPCC+woody", aggregate = FALSE))
# get lignin to c and nitrogen to c values for all manure classes
inputProp <- mbind(inputProp,
calcOutput("ParamManure", source = "IPCC", aggregate = FALSE))
calcOutput("ParamManure", input = "IPCC", aggregate = FALSE))
# get lignin to c and nitrogen to c values for generic input classes
param <- readSource("IPCC", subtype = "residues_table5p5b", convert = FALSE)
generic <- "Generic value for crops not indicated below"
Expand All @@ -49,6 +49,9 @@ calcCarbonInputMultiplier <- function() {
setNames(dimSums(weight, dim = 3), "generic"),
collapseNames(calcOutput("CarbonManure", aggregate = FALSE)[, "y1995", "c"]))

getSets(out, fulldim = FALSE)[1] <- "x.y.iso"
getSets(weight, fulldim = FALSE)[1] <- "x.y.iso"

return(list(x = out,
weight = weight,
unit = "tC per ha",
Expand Down
15 changes: 9 additions & 6 deletions R/calcCarbonLitter.R
Original file line number Diff line number Diff line change
Expand Up @@ -27,13 +27,13 @@ calcCarbonLitter <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",

# load and convert LPjmL data
litfallc <- calcOutput("LPJmL_new", version = lpjmlNatveg, climatetype = climatetype, stage = stage,
subtype = "alitterfallc", aggregate = FALSE, )
subtype = "alitterfallc", aggregate = FALSE, )
litburnc <- calcOutput("LPJmL_new", version = lpjmlNatveg, climatetype = climatetype, stage = stage,
subtype = "alitterburnc", aggregate = FALSE)
subtype = "alitterburnc", aggregate = FALSE)
litfallcWood <- calcOutput("LPJmL_new", version = lpjmlNatveg, climatetype = climatetype, stage = stage,
subtype = "alitterfallc_wood", aggregate = FALSE)
subtype = "alitterfallc_wood", aggregate = FALSE)
litburncWood <- calcOutput("LPJmL_new", version = lpjmlNatveg, climatetype = climatetype, stage = stage,
subtype = "alitterburnc_wood", aggregate = FALSE)
subtype = "alitterburnc_wood", aggregate = FALSE)

litfallc <- toolConditionalReplace(litfallc - litburnc, "<0", 0)
litfallcWood <- toolConditionalReplace(litfallcWood - litburncWood, "<0", 0)
Expand Down Expand Up @@ -61,15 +61,15 @@ calcCarbonLitter <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",
climatetype = ifelse(fixFpc, "GSWP3-W5E5:historical", climatetype),
stage = ifelse(fixFpc & (mode != "historicalSpinup"), "smoothed", stage),
subtype = "fpc", aggregate = FALSE)[, , "fraction natural vegetation", invert = TRUE]
if(fixFpc) fpc <- toolFillYears(fpc, years = getYears(out))
if (fixFpc) fpc <- toolFillYears(fpc, years = getYears(out))

woodyPfts <- getNames(fpc[, , "grass", invert = TRUE, pmatch = TRUE])
treeFrac <- dimSums(fpc[, , woodyPfts], dim = 3)

# Use turnover parameters per pft to calculate leaf fraction in soft tissue litter
# (soft tissue = fine roots + leaves)
lpjmlPar <- readSource("LPJmL_par", subtype = "pft_lpjml4",
convert = FALSE)[, , "sapwood", invert = TRUE, pmatch = TRUE]
convert = FALSE)[, , "sapwood", invert = TRUE, pmatch = TRUE]
leafFrac <- collapseDim(lpjmlPar[, , "turnover_root"] / dimSums(lpjmlPar, dim = 3.2))

# Load data from Brovkin et al. on leaf parameters (lignin and nitrogen concentration (per dry matter))
Expand Down Expand Up @@ -113,6 +113,9 @@ calcCarbonLitter <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",
weight <- calcOutput("LanduseInitialisation", aggregate = FALSE, cellular = TRUE, years = "y1995")
weight <- collapseDim(dimSums(weight[, , "crop", invert = TRUE], dim = 3))

getSets(out, fulldim = FALSE)[1] <- "x.y.iso"
getSets(weight, fulldim = FALSE)[1] <- "x.y.iso"

return(list(x = out,
weight = weight,
unit = "tC per ha, tn per tc, tLn per tC",
Expand Down
3 changes: 2 additions & 1 deletion R/calcCarbonManure.R
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ calcCarbonManure <- function() {
# Cut high input values at 10 tC/ha
manureInput <- toolConditionalReplace(manureInput, conditions = "> 10", replaceby = 10)
# Load parameters for lignin and nitrogen
param <- calcOutput("ParamManure", source = "IPCC", aggregate = FALSE)
param <- calcOutput("ParamManure", input = "IPCC", aggregate = FALSE)

kli <- findset("kli")
attributes <- c("c", "LC", "NC")
Expand All @@ -36,6 +36,7 @@ calcCarbonManure <- function() {

out[, , "c"] <- manureInput
out[, , c("NC", "LC")] <- param
getSets(out, fulldim = FALSE)[1] <- "x.y.iso"

return(list(x = out,
weight = NULL,
Expand Down
9 changes: 6 additions & 3 deletions R/calcCarbonResidues.R
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ calcCarbonResidues <- function() {
kcr2kres <- toolGetMapping("mappingCrop2Residue.csv", type = "sectoral", where = "mrcommons")
residueBiomassBg <- toolAggregate(residueBiomass, rel = kcr2kres, from = "kcr",
to = "kres", dim = 3.2)[, , "bg"][, , "c"]
callResFB <- function() calcOutput("ResFieldBalancePast", cellular = TRUE,
products = "kres", aggregate = FALSE)
callResFB <- function() {
calcOutput("ResFieldBalancePast", cellular = TRUE,
products = "kres", aggregate = FALSE)
}
residueRecyclingAg <- add_dimension(collapseNames(callResFB()[, , "recycle"][, , "c"]),
dim = 3.1, add = "residues", nm = "ag")

Expand All @@ -30,7 +32,7 @@ calcCarbonResidues <- function() {
## Cut high input values at 10 tC/ha
residueRecycling <- toolConditionalReplace(residueRecycling, conditions = "> 10", replaceby = 10)
# Load parameters for lignin and nitrogen and aggregate them to kres
param <- calcOutput("ParamResidues", aggregate = FALSE, source = "IPCC+woody")
param <- calcOutput("ParamResidues", aggregate = FALSE, input = "IPCC+woody")
weight <- collapseNames(dimSums(residueBiomass, dim = "residues"))
param <- toolAggregate(param, weight = weight, rel = kcr2kres, from = "kcr", to = "kres", dim = 3.1)

Expand All @@ -41,6 +43,7 @@ calcCarbonResidues <- function() {

out[, , "c"] <- residueRecycling
out[, , c("LC", "NC")] <- param
getSets(out, fulldim = FALSE)[1] <- "x.y.iso"

return(list(x = out,
weight = NULL,
Expand Down
15 changes: 8 additions & 7 deletions R/calcDecayFuture.R
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@

calcDecayFuture <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",
climatetype = "GSWP3-W5E5:historical") {

# Create settings for LPJmL/GCM from version and climatetype argument
cfg <- toolClimateInputVersion(lpjmlVersion = lpjmlNatveg,
climatetype = climatetype)
Expand All @@ -45,17 +44,19 @@ calcDecayFuture <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",
}

weight <- collapseDim(calcOutput("SoilCarbon", aggregate = FALSE, years = "y1995",
lpjmlNatveg = lpjmlNatveg, climatetype = cfg$baselineHist))
lpjmlNatveg = lpjmlNatveg, climatetype = cfg$baselineHist))
weight <- mbind(add_dimension(collapseDim(weight[, , "crop"] + 10^(-10)),
dim = 3.2, add = "tillage", nm = "fulltill"),
add_dimension(collapseDim(weight[, , "crop"] + 10^(-10)),
dim = 3.2, add = "tillage", nm = "reducedtill"),
add_dimension(collapseDim(weight[, , "natveg"] + 10^(-10)),
dim = 3.2, add = "tillage", nm = "notill"))

return(list(x = out,
weight = weight,
unit = "per yr",
description = "Decay rate for all SOC sub-pool per year",
isocountries = FALSE))
getSets(out, fulldim = FALSE)[1] <- "x.y.iso"
getSets(weight, fulldim = FALSE)[1] <- "x.y.iso"
return(list(x = out,
weight = weight,
unit = "per yr",
description = "Decay rate for all SOC sub-pool per year",
isocountries = FALSE))
}
23 changes: 12 additions & 11 deletions R/calcDecayRaw.R
Original file line number Diff line number Diff line change
Expand Up @@ -43,11 +43,11 @@ calcDecayRaw <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",
# check years and dims
if (!is.null(out) && (is.null(getYears(out)) || is.null(getYears(tmp)))) {
tmp <- magpie_expand(tmp, collapseDim(out[, , 1], dim = 3))
out <- magpie_expand(out, collapseDim(tmp, dim =3))
out <- magpie_expand(out, collapseDim(tmp, dim = 3))
}

years <- intersect(getYears(tmp), getYears(out))
if(!is.null(years)){
if (!is.null(years)) {
out <- out[, years, ]
tmp <- tmp[, years, ]
}
Expand Down Expand Up @@ -95,24 +95,24 @@ calcDecayRaw <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",
cellSandFrac <- calcOutput("SandFrac", aggregate = FALSE)

# harmonize years
.getCommonYears <- function(listOfYearVectors){
nullIndex <- which(sapply(listOfYearVectors, is.null))
if(length(nullIndex) != 0) {
.getCommonYears <- function(listOfYearVectors) {
nullIndex <- which(vapply(listOfYearVectors, is.null, logical(1)))
if (length(nullIndex) != 0) {
vcat(1, "There are objects with no years (NULL) provided.")
listOfYearVectors <- listOfYearVectors[-nullIndex]
}
commonYears <- Reduce(intersect, listOfYearVectors)
if(length(commonYears) == 0) vcat(0, "There are no common years objects provided.")
if (length(commonYears) == 0) vcat(0, "There are no common years objects provided.")
return(commonYears)
}

years <- .getCommonYears(list(getYears(cellTempFactor),
getYears(cellTillFactor),
getYears(cellWfactor)))

if(!is.null(getYears(cellTempFactor))) cellTempFactor <- cellTempFactor[, years, ]
if(!is.null(getYears(cellTillFactor))) cellTillFactor <- cellTillFactor[, years, ]
if(!is.null(getYears(cellWfactor))) cellWfactor <- cellWfactor[, years, ]
if (!is.null(getYears(cellTempFactor))) cellTempFactor <- cellTempFactor[, years, ]
if (!is.null(getYears(cellTillFactor))) cellTillFactor <- cellTillFactor[, years, ]
if (!is.null(getYears(cellWfactor))) cellWfactor <- cellWfactor[, years, ]

activeDecay <- param[, , "kfaca"] * cellWfactor * cellTempFactor * cellTillFactor *
(param[, , "k3par1"] + param[, , "k3par2"] * cellSandFrac)
Expand All @@ -123,12 +123,13 @@ calcDecayRaw <- function(lpjmlNatveg = "LPJmL4_for_MAgPIE_44ac93de",
slowDecay <- .clean(slowDecay, "slow", "sub")
passiveDecay <- .clean(passiveDecay, "passive", "sub")

if(length(getNames(passiveDecay)) != length(getNames(activeDecay))) {
if (length(getNames(passiveDecay)) != length(getNames(activeDecay))) {
passiveDecay <- dimOrder(magpie_expand(passiveDecay,
collapseDim(activeDecay[, , "rainfed"], keepdim = 3.3)),
perm = c(2,3,1), dim = 3)
perm = c(2, 3, 1), dim = 3)
}
decay <- magpiesort(mbind(activeDecay, slowDecay, passiveDecay))
getSets(decay, fulldim = FALSE)[1] <- "x.y.iso"

return(list(x = decay,
weight = NULL,
Expand Down
19 changes: 0 additions & 19 deletions R/calcIrrigationMonth.R

This file was deleted.

2 changes: 2 additions & 0 deletions R/calcLanduse.R
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ calcLanduse <- function(period = "states_1900to2010", output = "total") {
landuse <- toolLanduseChange(calcOutput("Landuse", period = period, aggregate = FALSE))
}

getSets(landuse, fulldim = FALSE)[1] <- "x.y.iso"

return(list(x = landuse,
weight = NULL,
unit = "Mha",
Expand Down
9 changes: 4 additions & 5 deletions R/calcParamManure.R
Original file line number Diff line number Diff line change
@@ -1,20 +1,19 @@
#' @title calcParamManure
#' @description Bring all parameter settings (lignin, nitrogen) for residues together
#'
#' @param source "IPCC" for IPCC Guideline values
#' @param input "IPCC" for IPCC Guideline values
#' @return List of magpie object with results on global level, unit and description.
#' @author Kristine Karstens
#'
#' @examples
#' \dontrun{
#' calcOutput("ParamManure")
#' }

calcParamManure <- function(source = "IPCC") {
calcParamManure <- function(input = "IPCC") {

kli <- magpiesets::findset("kli")
c2dm <- 0.45
if(grepl("IPCC", source)){
if (grepl("IPCC", input)) {

param <- readSource("IPCC", subtype = "manure_table5p5c", convert = FALSE)

Expand All @@ -26,7 +25,7 @@ calcParamManure <- function(source = "IPCC") {
out[, , "LC"] <- param[, , "LC_dm"] / c2dm / 100

} else {
stop("'source' unknown.")
stop("'input' unknown.")
}

return(list(x = out,
Expand Down
Loading

0 comments on commit f3c5fb4

Please sign in to comment.