diff --git a/.buildlibrary b/.buildlibrary index 925aec17..3e83f256 100644 --- a/.buildlibrary +++ b/.buildlibrary @@ -1,4 +1,4 @@ -ValidationKey: '35643700' +ValidationKey: '35648872' AcceptedWarnings: - 'Warning: package ''.*'' was built under R version' - 'Warning: namespace ''.*'' is not available and has been replaced' diff --git a/.gitignore b/.gitignore index a122acd5..a9f1e335 100644 --- a/.gitignore +++ b/.gitignore @@ -2,7 +2,6 @@ .Rhistory .RData .Ruserdata -.positai *.Rproj .Rproj.user .positai diff --git a/CITATION.cff b/CITATION.cff index 1312a7d4..6622dd86 100644 --- a/CITATION.cff +++ b/CITATION.cff @@ -3,7 +3,7 @@ message: If you use this software, please cite it using the metadata from this f type: software title: 'mrcommons: MadRat commons Input Data Library' version: 1.72.4 -date-released: '2026-08-10' +date-released: '2026-08-13' abstract: Provides useful functions and a common structure to all the input data required to run models like MAgPIE and REMIND of model input data. authors: diff --git a/DESCRIPTION b/DESCRIPTION index fed59ba4..9cf7bfa4 100644 --- a/DESCRIPTION +++ b/DESCRIPTION @@ -2,7 +2,7 @@ Type: Package Package: mrcommons Title: MadRat commons Input Data Library Version: 1.72.4 -Date: 2026-08-10 +Date: 2026-08-13 Authors@R: c( person("Benjamin Leon", "Bodirsky", , "bodirsky@pik-potsdam.de", role = "aut"), person("Kristine", "Karstens", role = "aut"), diff --git a/NAMESPACE b/NAMESPACE index baa2025a..3bc58c93 100644 --- a/NAMESPACE +++ b/NAMESPACE @@ -31,183 +31,147 @@ import(mrfaocore) import(mrlandcore) import(mstools) importFrom(countrycode,countrycode) -importFrom(data.table, - as.data.table, - fread -) -importFrom(dplyr, - "%>%", - across, - arrange, - count, - distinct, - filter, - full_join, - group_by, - inner_join, - last, - left_join, - mutate, - mutate_all, - n, - recode, - relocate, - rename, - right_join, - select, - summarise -) +importFrom(data.table,as.data.table) +importFrom(data.table,fread) +importFrom(dplyr,"%>%") +importFrom(dplyr,across) +importFrom(dplyr,arrange) +importFrom(dplyr,count) +importFrom(dplyr,distinct) +importFrom(dplyr,filter) +importFrom(dplyr,full_join) +importFrom(dplyr,group_by) +importFrom(dplyr,inner_join) +importFrom(dplyr,last) +importFrom(dplyr,left_join) +importFrom(dplyr,mutate) +importFrom(dplyr,mutate_all) +importFrom(dplyr,n) +importFrom(dplyr,recode) +importFrom(dplyr,relocate) +importFrom(dplyr,rename) +importFrom(dplyr,right_join) +importFrom(dplyr,select) +importFrom(dplyr,summarise) importFrom(hdf5r,h5file) -importFrom(luscale, - getAggregationMatrix, - groupAggregate, - rename_dimnames -) -importFrom(madrat, - calcOutput, - metadataGFZ, - readSource, - regionscode, - toolAggregate, - toolConditionalReplace, - toolCountry2isocode, - toolCountryFill, - toolGetMapping, - toolNAreplace, - toolSplitSubtype, - toolSubtypeSelect -) -importFrom(magclass, - "getItems<-", - "getNames<-", - "getYears<-", - add_columns, - add_dimension, - as.magpie, - clean_magpie, - collapseDim, - collapseNames, - convergence, - dimOrder, - dimReduce, - dimSums, - getCPR, - getCells, - getCoords, - getItems, - getNames, - getRegions, - getSets, - getYears, - hasCoords, - magpie_expand, - mbind, - mselect, - new.magpie, - read.magpie, - read.report, - setCells, - setNames, - setYears, - time_interpolate, - where, - wrap -) -importFrom(magpiesets, - FRAnames, - addLocation, - findset, - reporthelper, - reportingnames -) +importFrom(luscale,getAggregationMatrix) +importFrom(luscale,groupAggregate) +importFrom(luscale,rename_dimnames) +importFrom(madrat,calcOutput) +importFrom(madrat,metadataGFZ) +importFrom(madrat,readSource) +importFrom(madrat,regionscode) +importFrom(madrat,toolAggregate) +importFrom(madrat,toolConditionalReplace) +importFrom(madrat,toolCountry2isocode) +importFrom(madrat,toolCountryFill) +importFrom(madrat,toolGetMapping) +importFrom(madrat,toolNAreplace) +importFrom(madrat,toolSplitSubtype) +importFrom(madrat,toolSubtypeSelect) +importFrom(magclass,"getItems<-") +importFrom(magclass,"getNames<-") +importFrom(magclass,"getYears<-") +importFrom(magclass,add_columns) +importFrom(magclass,add_dimension) +importFrom(magclass,as.magpie) +importFrom(magclass,clean_magpie) +importFrom(magclass,collapseDim) +importFrom(magclass,collapseNames) +importFrom(magclass,convergence) +importFrom(magclass,dimOrder) +importFrom(magclass,dimReduce) +importFrom(magclass,dimSums) +importFrom(magclass,getCPR) +importFrom(magclass,getCells) +importFrom(magclass,getCoords) +importFrom(magclass,getItems) +importFrom(magclass,getNames) +importFrom(magclass,getRegions) +importFrom(magclass,getSets) +importFrom(magclass,getYears) +importFrom(magclass,hasCoords) +importFrom(magclass,magpie_expand) +importFrom(magclass,mbind) +importFrom(magclass,mselect) +importFrom(magclass,new.magpie) +importFrom(magclass,read.magpie) +importFrom(magclass,read.report) +importFrom(magclass,setCells) +importFrom(magclass,setNames) +importFrom(magclass,setYears) +importFrom(magclass,time_interpolate) +importFrom(magclass,where) +importFrom(magclass,wrap) +importFrom(magpiesets,FRAnames) +importFrom(magpiesets,addLocation) +importFrom(magpiesets,findset) +importFrom(magpiesets,reporthelper) +importFrom(magpiesets,reportingnames) importFrom(methods,new) importFrom(mstools,toolGetMappingCoord2Country) -importFrom(ncdf4, - nc_close, - nc_open, - ncvar_get -) -importFrom(purrr, - map, - map2, - pmap, - walk -) -importFrom(quitte, - as.quitte, - inline.data.frame -) -importFrom(raster, - "res<-", - aggregate, - area, - as.matrix, - brick, - crs, - extent, - projectRaster, - raster, - res, - resample, - stack, - subset, - writeRaster -) -importFrom(readxl, - read_excel, - read_xlsx -) -importFrom(reshape2, - acast, - dcast, - melt -) +importFrom(ncdf4,nc_close) +importFrom(ncdf4,nc_open) +importFrom(ncdf4,ncvar_get) +importFrom(purrr,map) +importFrom(purrr,map2) +importFrom(purrr,pmap) +importFrom(purrr,walk) +importFrom(quitte,as.quitte) +importFrom(quitte,inline.data.frame) +importFrom(raster,"res<-") +importFrom(raster,aggregate) +importFrom(raster,area) +importFrom(raster,as.matrix) +importFrom(raster,brick) +importFrom(raster,crs) +importFrom(raster,extent) +importFrom(raster,projectRaster) +importFrom(raster,raster) +importFrom(raster,res) +importFrom(raster,resample) +importFrom(raster,stack) +importFrom(raster,subset) +importFrom(raster,writeRaster) +importFrom(readxl,read_excel) +importFrom(readxl,read_xlsx) +importFrom(reshape2,acast) +importFrom(reshape2,dcast) +importFrom(reshape2,melt) importFrom(rlang,.data) -importFrom(stats, - na.omit, - quantile, - reshape, - xtabs -) -importFrom(stringr, - str_detect, - str_extract, - str_sub -) -importFrom(terra, - app, - classify, - focal, - rast, - rasterize, - segregate, - subset, - terraOptions, - tmpFiles, - vect -) -importFrom(tidyr, - expand_grid, - matches, - pivot_longer, - starts_with, - unnest -) -importFrom(utils, - bibentry, - capture.output, - download.file, - head, - person, - read.csv, - read.csv2, - read.table, - tail, - unzip -) -importFrom(withr, - defer, - local_options, - local_tempdir -) +importFrom(stats,na.omit) +importFrom(stats,quantile) +importFrom(stats,reshape) +importFrom(stats,xtabs) +importFrom(stringr,str_detect) +importFrom(stringr,str_extract) +importFrom(stringr,str_sub) +importFrom(terra,app) +importFrom(terra,classify) +importFrom(terra,focal) +importFrom(terra,rast) +importFrom(terra,rasterize) +importFrom(terra,segregate) +importFrom(terra,subset) +importFrom(terra,terraOptions) +importFrom(terra,tmpFiles) +importFrom(terra,vect) +importFrom(tidyr,expand_grid) +importFrom(tidyr,matches) +importFrom(tidyr,pivot_longer) +importFrom(tidyr,starts_with) +importFrom(tidyr,unnest) +importFrom(utils,bibentry) +importFrom(utils,capture.output) +importFrom(utils,download.file) +importFrom(utils,head) +importFrom(utils,person) +importFrom(utils,read.csv) +importFrom(utils,read.csv2) +importFrom(utils,read.table) +importFrom(utils,tail) +importFrom(utils,unzip) +importFrom(withr,defer) +importFrom(withr,local_options) +importFrom(withr,local_tempdir) importFrom(zoo,na.locf) diff --git a/R/calcClimateClass.R b/R/calcClimateClass.R index 6de94cf5..6b5815fb 100644 --- a/R/calcClimateClass.R +++ b/R/calcClimateClass.R @@ -30,8 +30,10 @@ calcClimateClass <- function(datasource = "koeppen") { getNames(x) <- gsub(" ", "_", tolower(getNames(x))) if (grepl("ipccReduced", datasource)) { - reduceIPCC <- toolGetMapping("IPCC2IPCCreduced.csv", type = "sectoral", where = "mappingfolder") - x <- toolAggregate(x, reduceIPCC, from = "ipcc", to = datasource, dim = 3, partrel = TRUE) + reduceIPCC <- toolGetMapping("IPCC2IPCCreduced.csv", type = "sectoral", + where = "mappingfolder") + x <- toolAggregate(x, reduceIPCC, from = "ipcc", + to = datasource, dim = 3, partrel = TRUE) } } else { diff --git a/R/calcFAOIntraYearProd.R b/R/calcFAOIntraYearProd.R index 1d36ceb3..74a2f402 100644 --- a/R/calcFAOIntraYearProd.R +++ b/R/calcFAOIntraYearProd.R @@ -16,7 +16,7 @@ #' #' @author David Chen #' -#' @importFrom dplyr group_by count %>% mutate filter +#' @importFrom dplyr group_by count mutate filter #' @importFrom magpiesets findset #' @importFrom withr local_options @@ -31,7 +31,7 @@ calcFAOIntraYearProd <- function(day = "harvest_day", products = "kcr", convert = FALSE)[, , day][, , "rf"] ## aggregate wheat based on binary mask, note wheat mask is also already - #masked to cropping area, maybe some inconsistencies when masking again to crop area + # masked to cropping area, maybe some inconsistencies when masking again to crop area wheat <- readSource("GGCMICropCalendar", subtype = "wheat_areas", convert = FALSE) cropcal[, , "swh"] <- cropcal[, , "swh"] * wheat[, , "swh"] cropcal[, , "wwh"] <- cropcal[, , "wwh"] * wheat[, , "wwh"] @@ -40,25 +40,25 @@ calcFAOIntraYearProd <- function(day = "harvest_day", products = "kcr", cropcal <- cropcal[, , c("swh", "wwh"), invert = TRUE] ## mask cropcal to current area, assume 2010 area for now to avoid very large dataset - areaMask <- calcOutput("Croparea", cellular = TRUE, - aggregate = FALSE)[, 2010, ] + areaMask <- calcOutput("Croparea", cellular = TRUE, aggregate = FALSE)[, 2010, ] areaMask <- ifelse(areaMask > 0, 1, 0) areaMask <- areaMask[, , c("begr", "betr", "foddr", "oilpalm", "others"), invert = TRUE] ggcmiMapping <- toolGetMapping("MAgPIE_GGCMI.csv", type = "sectoral", where = "mappingfolder") - areaMask <- toolAggregate(areaMask, rel = ggcmiMapping, from = "MagPIE", to = "GGCMI", dim = 3, partrel = TRUE) + areaMask <- toolAggregate(areaMask, rel = ggcmiMapping, from = "MagPIE", + to = "GGCMI", dim = 3, partrel = TRUE) cropcal <- cropcal * setYears(areaMask, NULL) # make data frame to more easily count the share of cropping date within each country - cropcaldf <- as.data.frame(collapseNames(cropcal)) %>% - group_by(.data$Value, .data$Region, .data$Data1) %>% - dplyr::count() %>% - filter(.data$Value != 0) + cropcaldf <- as.data.frame(collapseNames(cropcal)) |> + group_by(.data$Value, .data$Region, .data$Data1) |> + dplyr::count() |> + filter(.data$Value != 0) - cropcaldf <- cropcaldf %>% - group_by(.data$Region, .data$Data1) %>% - mutate("share" = .data$n / sum(.data$n)) + cropcaldf <- cropcaldf |> + group_by(.data$Region, .data$Data1) |> + mutate("share" = .data$n / sum(.data$n)) names(cropcaldf)[names(cropcaldf) == "Value"] <- "day" cropcaldf <- cropcaldf[, c("Region", "day", "Data1", "share")] @@ -88,7 +88,7 @@ calcFAOIntraYearProd <- function(day = "harvest_day", products = "kcr", mapping <- toolGetMappingCoord2Country() mapping$coordiso <- paste(mapping$coords, mapping$iso, sep = ".") rice <- toolAggregate(rice, rel = mapping, from = "coordiso", to = "iso", - weight = new.magpie(cells_and_regions = getItems(rice, dim = 1), years = NULL, + weight = new.magpie(cells_and_regions = getItems(rice, dim = 1), years = NULL, names = getNames(rice), fill = 1)) rice <- toolCountryFill(rice, fill = 0) @@ -99,76 +99,77 @@ calcFAOIntraYearProd <- function(day = "harvest_day", products = "kcr", - if (frequency == "monthly") { - iprod <- add_dimension(prod, dim = 2.2, add = "month", nm = c(unique(daysMapping$month))) - } else if (frequency == "quarterly") { - iprod <- add_dimension(prod, dim = 2.2, add = "quarter", nm = c(unique(daysMapping$quarter))) - } + if (frequency == "monthly") { + iprod <- add_dimension(prod, dim = 2.2, add = "month", nm = c(unique(daysMapping$month))) + } else if (frequency == "quarterly") { + iprod <- add_dimension(prod, dim = 2.2, add = "quarter", nm = c(unique(daysMapping$quarter))) + } - iprod[, , "rice_pro"] <- prod[, , "rice_pro"] * - (setNames(rice[, , "ri1"] * cropcaldf[, , "ri1"], NULL) + - setNames(rice[, , "ri2"] * cropcaldf[, , "ri2"], NULL)) + iprod[, , "rice_pro"] <- prod[, , "rice_pro"] * + (setNames(rice[, , "ri1"] * cropcaldf[, , "ri1"], NULL) + + setNames(rice[, , "ri2"] * cropcaldf[, , "ri2"], NULL)) - tece <- c("44|Barley", "71|Rye", "15|Wheat") - trce <- c("79|Millet", "83|Sorghum") - puls <- c("176|Beans, dry", "181|Broad beans, horse beans, dry", - "187|Peas, dry", "197|Pigeon peas", "191|Chick peas") + tece <- c("44|Barley", "71|Rye", "15|Wheat") + trce <- c("79|Millet", "83|Sorghum") + puls <- c("176|Beans, dry", "181|Broad beans, horse beans, dry", + "187|Peas, dry", "197|Pigeon peas", "191|Chick peas") - regionalProd <- collapseNames(readSource("FAO_online", "Crop")[, getItems(iprod, - dim = 2.1), "production"][, , c(tece, trce, puls)]) + regionalProd <- readSource("FAO_online", subtype = "Crop") + regionalProd <- regionalProd[, getItems(iprod, dim = 2.1), "production"][, , c(tece, trce, puls)] + regionalProd <- collapseNames(regionalProd) - teceRatio <- regionalProd[, , tece] / - dimSums(regionalProd[, , tece], dim = 3) - teceRatio[is.na(teceRatio)] <- 0 + teceRatio <- regionalProd[, , tece] / + dimSums(regionalProd[, , tece], dim = 3) + teceRatio[is.na(teceRatio)] <- 0 - trceRatio <- regionalProd[, , trce] / - dimSums(regionalProd[, , trce], dim = 3) - trceRatio[is.na(trceRatio)] <- 0 + trceRatio <- regionalProd[, , trce] / + dimSums(regionalProd[, , trce], dim = 3) + trceRatio[is.na(trceRatio)] <- 0 - pulsRatio <- regionalProd[, , puls] / - dimSums(regionalProd[, , puls], dim = 3) - pulsRatio[is.na(pulsRatio)] <- 0 + pulsRatio <- regionalProd[, , puls] / + dimSums(regionalProd[, , puls], dim = 3) + pulsRatio[is.na(pulsRatio)] <- 0 - iprod[, , "tece"] <- prod[, , "tece"] * - (setNames(teceRatio[, , "44|Barley"], NULL) * setNames(cropcaldf[, , "bar"], NULL) + - setNames(teceRatio[, , "71|Rye"], NULL) * setNames(cropcaldf[, , "rye"], NULL) + - setNames(teceRatio[, , "15|Wheat"], NULL) * setNames(cropcaldf[, , "wheat"], NULL)) + iprod[, , "tece"] <- prod[, , "tece"] * + (setNames(teceRatio[, , "44|Barley"], NULL) * setNames(cropcaldf[, , "bar"], NULL) + + setNames(teceRatio[, , "71|Rye"], NULL) * setNames(cropcaldf[, , "rye"], NULL) + + setNames(teceRatio[, , "15|Wheat"], NULL) * setNames(cropcaldf[, , "wheat"], NULL)) iprod[, , "trce"] <- prod[, , "trce"] * - (setNames(trceRatio[, , "79|Millet"], NULL) * setNames(cropcaldf[, , "mil"], NULL) + - setNames(trceRatio[, , "83|Sorghum"], NULL) * setNames(cropcaldf[, , "sor"], NULL)) + (setNames(trceRatio[, , "79|Millet"], NULL) * setNames(cropcaldf[, , "mil"], NULL) + + setNames(trceRatio[, , "83|Sorghum"], NULL) * setNames(cropcaldf[, , "sor"], NULL)) iprod[, , "puls_pro"] <- prod[, , "puls_pro"] * (setNames(dimSums(pulsRatio[, , c("176|Beans, dry", "181|Broad beans, horse beans, dry")], dim = 3), NULL) * setNames(cropcaldf[, , "bea"], NULL) + - setNames(dimSums(pulsRatio[, , c("187|Peas, dry", - "197|Pigeon peas", "191|Chick peas")], dim = 3), NULL) * - setNames(cropcaldf[, , "pea"], NULL)) - - productsLeft <- setdiff(findset("kcr"), c("rice_pro", "tece", "trce", "puls_pro")) - calProductsLeft <- setdiff(getNames(cropcaldf), c("bar", - "rye", "wheat", "ri1", "ri2", "mil", "sor", "pea", "bea")) - cropcaldf <- toolAggregate(cropcaldf[, , calProductsLeft], - rel = ggcmiMapping, from = "GGCMI", to = "MagPIE", dim = 3, partrel = TRUE) - - missingProducts <- setdiff(productsLeft, getNames(cropcaldf)) - - if (!is.null(missingProducts)) { - cropcaldf <- add_columns(cropcaldf, addnm = missingProducts, - dim = 3.1, fill = 0) - - if (frequency == "monthly") { - cropcaldf[, "September", missingProducts] <- 1 - } else if (frequency == "quarterly") { - cropcaldf[, "q3", missingProducts] <- 1 + setNames(dimSums(pulsRatio[, , c("187|Peas, dry", + "197|Pigeon peas", "191|Chick peas")], dim = 3), NULL) * + setNames(cropcaldf[, , "pea"], NULL)) + + productsLeft <- setdiff(findset("kcr"), c("rice_pro", "tece", "trce", "puls_pro")) + calProductsLeft <- setdiff(getNames(cropcaldf), c("bar", "rye", "wheat", "ri1", + "ri2", "mil", "sor", "pea", "bea")) + cropcaldf <- toolAggregate(cropcaldf[, , calProductsLeft], + rel = ggcmiMapping, from = "GGCMI", to = "MagPIE", dim = 3, partrel = TRUE) + + missingProducts <- setdiff(productsLeft, getNames(cropcaldf)) + + if (!is.null(missingProducts)) { + cropcaldf <- add_columns(cropcaldf, addnm = missingProducts, + dim = 3.1, fill = 0) + + if (frequency == "monthly") { + cropcaldf[, "September", missingProducts] <- 1 + } else if (frequency == "quarterly") { + cropcaldf[, "q3", missingProducts] <- 1 + } + vcat(1, "Missing calendar information for ", paste(missingProducts, " "), + "These assumed (poorly) for now to have single harvest date in September/quarter 3") } - vcat(1, "Missing calendar information for ", paste(missingProducts, " "), - "These assumed (poorly) for now to have single harvest date in September/quarter 3") - } - iprod[, , productsLeft] <- prod[, , productsLeft] * cropcaldf[, , productsLeft] + iprod[, , productsLeft] <- prod[, , productsLeft] * cropcaldf[, , productsLeft] } else if (products == "staples") { staples <- c("56|Maize", "236|Soybeans", "15|Wheat", "27|Rice, paddy") @@ -179,15 +180,15 @@ calcFAOIntraYearProd <- function(day = "harvest_day", products = "kcr", iprod <- add_dimension(prod, dim = 2.2, add = "month", nm = c(unique(daysMapping$month))) } else if (frequency == "quarterly") { iprod <- add_dimension(prod, dim = 2.2, add = "quarter", nm = c(unique(daysMapping$quarter))) - } + } iprod[, , "rice_pro"] <- prod[, , "rice_pro"] * (setNames(rice[, , "ri1"] * cropcaldf[, , "ri1"], NULL) + setNames(rice[, , "ri2"] * cropcaldf[, , "ri2"], NULL)) iprod[, , c("maiz", "soybean", "wheat")] <- prod[, , c("maiz", "soybean", "wheat")] * - setNames(cropcaldf[, , c("mai", "soy", "wheat")], - c("maiz", "soybean", "wheat")) + setNames(cropcaldf[, , c("mai", "soy", "wheat")], + c("maiz", "soybean", "wheat")) ## convert to Mt iprod <- iprod / 10^6 @@ -198,17 +199,17 @@ calcFAOIntraYearProd <- function(day = "harvest_day", products = "kcr", iprod <- iprod * prodAttributes[, , getItems(iprod, dim = 3)] -} else { - stop("Products so far can only kcr or staples") + } else { + stop("Products so far can only kcr or staples") } out <- iprod return(list(x = out, - weight = NULL, - unit = "Mt DM/Nr/P/K/WM or PJ energy", - description = "Crop production: dry matter: Mt (dm), + weight = NULL, + unit = "Mt DM/Nr/P/K/WM or PJ energy", + description = "Crop production: dry matter: Mt (dm), gross energy: PJ (ge), reactive nitrogen: Mt (nr), phosphor: Mt (p), potash: Mt (k), wet matter: Mt (wm)." - )) + )) - } +} diff --git a/R/calcFAOYield.R b/R/calcFAOYield.R index 01b2af48..4cb5f22c 100644 --- a/R/calcFAOYield.R +++ b/R/calcFAOYield.R @@ -4,7 +4,9 @@ #' @param physical physical area or havested area #' @param attributes in dm, wm, ge, nr, p, k #' @param cellular if TRUE value is calculate on cellular level -#' @param areaSource data source for croparea used in calculation: FAO or Toolbox +#' @param areaSource data source for croparea used in calculation: "LandInG" (default) +#' or "FAOLUH". The latter one is deprecated. The former default +#' "FAO" is no longer accepted. #' @param irrigation distinguish irrigation or not #' @param cut FALSE (default) - do not cut off yields, #' number between 0 and 1 to define percentile value for cut off @@ -14,31 +16,16 @@ #' @importFrom stats quantile calcFAOYield <- function(physical = TRUE, attributes = "dm", irrigation = FALSE, - cellular = FALSE, cut = FALSE, average = 5, areaSource = "FAO") { + cellular = FALSE, cut = FALSE, average = 5, areaSource = "LandInG") { production <- calcOutput("Production", products = "kcr", attributes = attributes, - irrigation = irrigation, cellular = cellular, - cells = "lpjcell", aggregate = FALSE) - selectyears <- getItems(production, dim = "year") + irrigation = irrigation, cellular = cellular, aggregate = FALSE) - if (areaSource == "FAO") { + area <- calcOutput("Croparea", physical = physical, cellular = cellular, + irrigation = irrigation, aggregate = FALSE, datasource = areaSource) - area <- calcOutput("Croparea", sectoral = "kcr", physical = physical, - cellular = cellular, - irrigation = irrigation, aggregate = FALSE) - - } else if (areaSource == "LandInG") { - - area <- calcOutput("CropareaLandInG", sectoral = "kcr", physical = physical, - irrigation = irrigation, selectyears = selectyears, - cellular = cellular, cells = "lpjcell", aggregate = FALSE) - } else { - stop("Please specify which area should be used for calculation. - Note: LandInG should be FAO-consistent.") - } faoyears <- intersect(getYears(production), getYears(area)) - yield <- collapseNames(production[, faoyears, ]) / area[, faoyears, ] yield[yield == Inf | yield == -Inf | is.nan(yield) | yield == 0] <- NA diff --git a/R/calcFertilizerByCrop.R b/R/calcFertilizerByCrop.R index 86815fa2..3f934c76 100644 --- a/R/calcFertilizerByCrop.R +++ b/R/calcFertilizerByCrop.R @@ -1,8 +1,8 @@ #' @title calcFertilizerByCrop #' @description calculates the crop-specific use of different N inputs #' -#' @param indicator total: estimates the inputs per total crop production; by_harvest estimates the inputs -#' per ton harvest; by_area estimates the inputs per area harvested +#' @param indicator total: estimates the inputs per total crop production; by_physical_area and by_area_harvested +#' estimates the inputs per unit of land #' @param deposition if FALSE, deposition is not accounted for in the distribution. Use FALSE to avoid #' circularities in calcNitrogenBudget #' @param cellular cellular disaggreagation or national values @@ -29,7 +29,7 @@ calcFertilizerByCrop <- function(indicator = "total", deposition = "Nsurplus2", dim = 3.1) * withdrawal[, cyears, ] if (indicator == "by_physical_area") { area <- collapseNames(calcOutput("Croparea", aggregate = FALSE, physical = TRUE, - cellular = cellular, sectoral = "kcr")[, cyears, ]) + cellular = cellular)[, cyears, ]) out <- inputsPerCrop[, , getNames(area)] / area weight <- out weight[, , ] <- area @@ -38,7 +38,7 @@ calcFertilizerByCrop <- function(indicator = "total", deposition = "Nsurplus2", out <- data$x } else if (indicator == "by_area_harvested") { area <- collapseNames(calcOutput("Croparea", physical = FALSE, cellular = cellular, - aggregate = FALSE, sectoral = "kcr")[, past, ]) + aggregate = FALSE)[, past, ]) out <- inputsPerCrop[, , getNames(area)] / area weight <- out weight[, , ] <- area diff --git a/R/calcLanduseIntensity.R b/R/calcLanduseIntensity.R index 243714e8..a1ddf167 100644 --- a/R/calcLanduseIntensity.R +++ b/R/calcLanduseIntensity.R @@ -24,7 +24,8 @@ calcLanduseIntensity <- function(sectoral = "kcr", rescale = TRUE) { if (sectoral %in% c("kcr", "lpj")) { # Mappings cropsMAgPIE <- findset("kcr") - mag2lpj <- toolGetMapping(type = "sectoral", name = "MAgPIE_LPJmL.csv", where = "mappingfolder") + mag2lpj <- toolGetMapping(type = "sectoral", name = "MAgPIE_LPJmL.csv", + where = "mappingfolder") mag2lpj <- mag2lpj[mag2lpj$MAgPIE %in% cropsMAgPIE, ] cropsLPJmL <- levels(droplevels(factor(mag2lpj$LPJmL))) diff --git a/R/calcNitrogenBNF.R b/R/calcNitrogenBNF.R index 04ec270e..922ab33f 100644 --- a/R/calcNitrogenBNF.R +++ b/R/calcNitrogenBNF.R @@ -3,8 +3,6 @@ #' @param cellular cellular disaggreagation or national values #' @return List of magpie objects with results on country level, weight on country level, unit and description. #' @author Benjamin Leon Bodirsky -#' @seealso -#' [calcNitrogenFixationPast()] #' @examples #' \dontrun{ #' calcOutput("NitrogenBNF") @@ -24,10 +22,11 @@ calcNitrogenBNF <- function(cellular = FALSE) { bnf <- toolCountryFill(bnf, fill = 0) } - bnfcrop <- dimSums(calcOutput("NitrogenFixationPast", aggregate = FALSE, cellular = cellular, - fixation_types = "both", sum_plantparts = TRUE), - dim = 3) - bnf[, , "crop"] <- bnfcrop[, getYears(bnf), ] + bnfFree <- dimSums(calcOutput("NitrogenFixationFreeliving", + aggregate = FALSE, cellular = cellular), dim = 3) + bnfCrop <- dimSums(calcOutput("NitrogenFixationSymbiotic", + aggregate = FALSE, cellular = cellular), dim = 3) + bnf[, , "crop"] <- bnfFree[, getYears(bnf), ] + bnfCrop[, getYears(bnf), ] return(list(x = bnf, weight = NULL, diff --git a/R/calcNitrogenBudgetCropland.R b/R/calcNitrogenBudgetCropland.R index 77cdb52c..7cc629e4 100644 --- a/R/calcNitrogenBudgetCropland.R +++ b/R/calcNitrogenBudgetCropland.R @@ -23,8 +23,10 @@ calcNitrogenBudgetCropland <- function(cellular = FALSE, bg <- dimSums(collapseNames(calcOutput("ResBiomass", cellular = cellular, plantparts = "bg", aggregate = FALSE)[, , "nr"]), dim = 3.1) seed <- dimSums(calcOutput("Seed", cellular = cellular, products = "kcr", aggregate = FALSE)[, , "nr"], dim = 3) - fixation <- dimSums(calcOutput("NitrogenFixationPast", fixation_types = "both", sum_plantparts = TRUE, - aggregate = FALSE, cellular = cellular), dim = 3.2) + fixationFreeliving <- dimSums(calcOutput("NitrogenFixationFreeliving", aggregate = FALSE, cellular = cellular), + dim = "crop") + fixationCrops <- dimSums(calcOutput("NitrogenFixationSymbiotic", aggregate = FALSE, cellular = cellular), + dim = c(3.2, 3.3)) som <- calcOutput("SOMlossN", cellular = cellular, aggregate = FALSE) if (cellular) { @@ -46,7 +48,8 @@ calcNitrogenBudgetCropland <- function(cellular = FALSE, ag <- ag[, cyears, ] bg <- bg[, cyears, ] seed <- seed[, cyears, ] - fixation <- fixation[, cyears, ] + fixationFreeliving <- fixationFreeliving[, cyears, ] + fixationCrops <- fixationCrops[, cyears, ] som <- som[, cyears, ] manure <- collapseNames(calcOutput("ManureRecyclingCroplandPast", aggregate = FALSE, @@ -67,10 +70,10 @@ calcNitrogenBudgetCropland <- function(cellular = FALSE, setNames(bg, "bg")) inputsDirect <- mbind(setNames(seed, "seed"), - setNames(fixation[, , "fixation_crops"], "fixation_crops")) + setNames(fixationCrops[, , "fixation_crops"], "fixation_crops")) inputs <- mbind( - setNames(fixation[, , "fixation_freeliving"], "fixation_freeliving"), + setNames(fixationFreeliving[, , "fixation_freeliving"], "fixation_freeliving"), setNames(manure, "manure_conf"), setNames(manureCroplandGrazing, "manure_stubble_grazing"), setNames(collapseNames(ag[, , "recycle"]), "ag_recycling"), diff --git a/R/calcNitrogenFixationFreeliving.R b/R/calcNitrogenFixationFreeliving.R new file mode 100644 index 00000000..337b5804 --- /dev/null +++ b/R/calcNitrogenFixationFreeliving.R @@ -0,0 +1,36 @@ +#' @title calcNitrogenFixationFreeliving +#' @description calculates fixation from freeliving bacteria +#' @param cellular cellular estimates optional +#' @param irrigation if TRUE, distinguishes irrigated and non-irrigated crops +#' @return List of magpie objects with results on country level, weight on country level, unit and description. +#' @author Benjamin Leon Bodirsky +#' @examples +#' \dontrun{ +#' calcOutput("NitrogenFixationFreeliving") +#' } +#' @importFrom magpiesets findset +#' + +calcNitrogenFixationFreeliving <- function(cellular = FALSE, irrigation = FALSE) { + + area <- collapseNames(calcOutput("Croparea", cellular = cellular, aggregate = FALSE, + physical = TRUE, irrigation = irrigation, fallow = TRUE)) + + freeliving <- setYears(readSource("Herridge", subtype = "freeliving", convert = FALSE), NULL) + freeliving <- mbind( + freeliving, + setNames(freeliving[, , "tece"], "fallow") # use value of temperate cereals for fallow. + # justification: bare fallow has likely a bit less (as less C for Nfixing bacteria available) + # while green fallow has a bit more, but all not too much different as long as no + # planted green fallow with legumes is present, which is usually not. + ) + freeliving <- area * freeliving + fixFreeliving <- add_dimension(x = freeliving, dim = 3.1, + add = "fixation", nm = "fixation_freeliving") + + return(list(x = fixFreeliving, + weight = NULL, + unit = "Mt Nr", + description = "Nitrogen fixation by freeliving microorganisms", + isocountries = !cellular)) +} diff --git a/R/calcNitrogenFixationPast.R b/R/calcNitrogenFixationPast.R deleted file mode 100644 index 5aa7708f..00000000 --- a/R/calcNitrogenFixationPast.R +++ /dev/null @@ -1,74 +0,0 @@ -#' @title calcNitrogenFixationPast -#' @description calculates fixation from freeliving bacteria and from nitrogen-fixing crops -#' @param fixation_types either "fixation_crops", "fixation_freeliving", or "both" -#' @param sum_plantparts if false, crop residues, belowground residues and harvested organ are reported separately -#' @param cellular cellular estimates optional -#' @param irrigation if TRUE, distinguishes irrigated and non-irrigated crops -#' @return List of magpie objects with results on country level, weight on country level, unit and description. -#' @author Benjamin Leon Bodirsky -#' @seealso -#' [calcNitrogenFixationPast()] -#' @examples -#' \dontrun{ -#' calcOutput("calcNitrogenFixationPast") -#' } -#' @importFrom magpiesets findset -#' - -calcNitrogenFixationPast <- function(fixation_types = "both", # nolint: object_name_linter. - sum_plantparts = TRUE, # nolint: object_name_linter. - cellular = FALSE, - irrigation = FALSE) { - fixBiomass <- NULL - fixFreeliving <- NULL - if ((fixation_types == "both") && !sum_plantparts) { - warning("sum_plantparts set to true") - sum_plantparts <- TRUE # nolint: object_name_linter. - } - if (fixation_types %in% c("both", "fixation_crops")) { - harvest <- collapseNames(calcOutput("Production", products = "kcr", cellular = cellular, - attributes = "nr", irrigation = irrigation, aggregate = FALSE)) - harvest <- add_dimension(harvest, dim = 3.1, add = "data1", nm = "organ") - resAg <- collapseNames(calcOutput("ResBiomass", cellular = cellular, - plantparts = "ag", irrigation = irrigation, - attributes = "nr", aggregate = FALSE), - collapsedim = "attributes") - resBg <- collapseNames(calcOutput("ResBiomass", cellular = cellular, - plantparts = "bg", irrigation = irrigation, - attributes = "nr", aggregate = FALSE), - collapsedim = "attributes") - - commonYears <- intersect(intersect(getYears(resAg), getYears(resBg)), getYears(harvest)) - harvest <- harvest[, commonYears, ] - resAg <- resAg[, commonYears, ] - resBg <- resBg[, commonYears, ] - - biomass <- mbind(harvest, resAg, resBg) - if (sum_plantparts) { - biomass <- dimSums(biomass, dim = 3.1) - } - ndfa <- setYears(readSource("Herridge", subtype = "ndfa"), NULL) - ndfa <- ndfa[getItems(biomass, dim = if (dimExists("iso", biomass)) "iso" else 1.1), , ] - biomass <- biomass * ndfa - fixBiomass <- add_dimension(biomass, dim = 3.1, nm = "fixation_crops") - } - if (fixation_types %in% c("both", "fixation_freeliving")) { - area <- collapseNames(calcOutput("Croparea", cellular = cellular, aggregate = FALSE, - sectoral = "kcr", physical = TRUE, irrigation = irrigation)) - commonYears <- intersect(getYears(area), commonYears) - area <- area[, commonYears, ] - freeliving <- setYears(readSource("Herridge", subtype = "freeliving", convert = FALSE), NULL) - freeliving <- area * freeliving - freeliving <- freeliving[, intersect(getYears(fixBiomass), getYears(freeliving)), ] - fixFreeliving <- add_dimension(freeliving, dim = 3.1, nm = "fixation_freeliving") - } - - out <- collapseNames(mbind(fixBiomass[, intersect(getYears(fixBiomass), getYears(fixFreeliving)), ], - fixFreeliving[, intersect(getYears(fixBiomass), getYears(fixFreeliving)), ])) - - return(list(x = out, - weight = NULL, - unit = "Mt Nr", - description = "Nitrogen fixation by crops and freeliving bacteria", - isocountries = !cellular)) -} diff --git a/R/calcNitrogenFixationRateNatural.R b/R/calcNitrogenFixationRateNatural.R index a7620868..42c52f59 100644 --- a/R/calcNitrogenFixationRateNatural.R +++ b/R/calcNitrogenFixationRateNatural.R @@ -3,9 +3,6 @@ #' @param cells "magpiecell" for 59199 cells or "lpjcell" for 67420 cells #' @return List of magpie objects with results on global level, empty weight, unit and description. #' @author Benjamin Leon Bodirsky -#' @seealso -#' [calcNitrogenFixationPast()] -#' [readHerridge()] #' @examples #' \dontrun{ #' calcOutput("NitrogenFixationRateNatural") diff --git a/R/calcNitrogenFixationSymbiotic.R b/R/calcNitrogenFixationSymbiotic.R new file mode 100644 index 00000000..b2442360 --- /dev/null +++ b/R/calcNitrogenFixationSymbiotic.R @@ -0,0 +1,45 @@ +#' @title calcNitrogenFixationSymbiotic +#' @description calculates fixation from nitrogen-fixing crops +#' @param cellular cellular estimates optional +#' @param irrigation if TRUE, distinguishes irrigated and non-irrigated crops +#' @return List of magpie objects with results on country level, weight on country level, unit and description. +#' @author Benjamin Leon Bodirsky +#' @examples +#' \dontrun{ +#' calcOutput("NitrogenFixationSymbiotic") +#' } +#' @importFrom magpiesets findset +#' + +calcNitrogenFixationSymbiotic <- function(cellular = FALSE, irrigation = FALSE) { + + harvest <- collapseNames(calcOutput("Production", products = "kcr", cellular = cellular, + attributes = "nr", irrigation = irrigation, aggregate = FALSE)) + harvest <- add_dimension(harvest, dim = 3.1, add = "data1", nm = "organ") + resAg <- collapseNames(calcOutput("ResBiomass", cellular = cellular, + plantparts = "ag", irrigation = irrigation, + attributes = "nr", aggregate = FALSE), + collapsedim = "attributes") + resBg <- collapseNames(calcOutput("ResBiomass", cellular = cellular, + plantparts = "bg", irrigation = irrigation, + attributes = "nr", aggregate = FALSE), + collapsedim = "attributes") + + commonYears <- intersect(intersect(getYears(resAg), getYears(resBg)), getYears(harvest)) + harvest <- harvest[, commonYears, ] + resAg <- resAg[, commonYears, ] + resBg <- resBg[, commonYears, ] + + biomass <- mbind(harvest, resAg, resBg) + + ndfa <- setYears(readSource("Herridge", subtype = "ndfa"), NULL) + ndfa <- ndfa[getItems(biomass, dim = if (dimExists("iso", biomass)) "iso" else 1.1), , ] + biomass <- biomass * ndfa + fixBiomass <- add_dimension(biomass, dim = 3.1, add = "fixation", nm = "fixation_crops") + + return(list(x = fixBiomass, + weight = NULL, + unit = "Mt Nr", + description = "Nitrogen fixation by crops", + isocountries = !cellular)) +} diff --git a/R/calcNitrogenWithdrawalByCrop.R b/R/calcNitrogenWithdrawalByCrop.R index a6b58a59..6b734e67 100644 --- a/R/calcNitrogenWithdrawalByCrop.R +++ b/R/calcNitrogenWithdrawalByCrop.R @@ -37,8 +37,9 @@ calcNitrogenWithdrawalByCrop <- function(indicator = "total", cellular = FALSE, irrigation = irrigation, attributes = "nr", aggregate = FALSE)[, past, ]) seed <- collapseNames(calcOutput("Seed", cellular = cellular, products = "kcr", attributes = "nr", irrigation = irrigation, aggregate = FALSE)[, past, ]) - fixation <- calcOutput("NitrogenFixationPast", cellular = cellular, irrigation = irrigation, - fixation_types = "fixation_crops", aggregate = FALSE) + fixation <- calcOutput("NitrogenFixationSymbiotic", cellular = cellular, irrigation = irrigation, + aggregate = FALSE) + fixation <- dimSums(fixation, dim = 3.2) if (irrigation2 != "FALSE") { # again, for size reasons harvest <- harvest[, , irrigation2] @@ -52,13 +53,13 @@ calcNitrogenWithdrawalByCrop <- function(indicator = "total", cellular = FALSE, add_dimension(harvest, nm = "harvest", dim = 3.1), add_dimension(ag, nm = "ag", dim = 3.1), add_dimension(bg, nm = "bg", dim = 3.1), - add_dimension(-fixation[, getYears(harvest),], nm = "fixation_crops", dim = 3.1), + -fixation[, getYears(harvest), ], add_dimension(-seed, nm = "seed", dim = 3.1) ) if (indicator == "by_physical_area") { area <- collapseNames(calcOutput("Croparea", aggregate = FALSE, physical = TRUE, cellular = cellular, - irrigation = irrigation, sectoral = "kcr")[, past, ]) + irrigation = irrigation)[, past, ]) if (irrigation2 != "FALSE") { # again, for size reasons area <- area[, , irrigation2] } @@ -71,7 +72,7 @@ calcNitrogenWithdrawalByCrop <- function(indicator = "total", cellular = FALSE, unit <- "t Nr per ha physical area" } else if (indicator == "by_area_harvested") { area <- collapseNames(calcOutput("Croparea", physical = FALSE, cellular = cellular, irrigation = irrigation, - aggregate = FALSE, sectoral = "kcr")[, past, ]) + aggregate = FALSE)[, past, ]) if (irrigation2 != "FALSE") { # again, for size reasons area <- area[, , irrigation2] } diff --git a/R/calcProduction.R b/R/calcProduction.R index ec51aa54..ec96a01e 100644 --- a/R/calcProduction.R +++ b/R/calcProduction.R @@ -57,7 +57,7 @@ calcProduction <- function(products = "kcr", cellular = FALSE, cells = "lpjcell" yieldsMAG <- toolAggregate(x = yieldsLPJ, rel = mappingMAG2LPJ, from = "LPJmL", to = "MAgPIE", dim = 3.1, partrel = TRUE)[, , magCropTypes] - cropareaMAG <- calcOutput("Croparea", sectoral = "kcr", physical = TRUE, cellular = TRUE, + cropareaMAG <- calcOutput("Croparea", physical = TRUE, cellular = TRUE, irrigation = TRUE, aggregate = FALSE)[, , magCropTypes] commonYears <- intersect(getYears(yieldsLPJ), getYears(cropareaMAG)) @@ -126,8 +126,7 @@ calcProduction <- function(products = "kcr", cellular = FALSE, cells = "lpjcell" } # correct items with no total cropland area for known data mismatches: - # where no LUH croparea at all, but FAO production reported - # Note: Number of countries with mismatch would reduce if we use the croparea of LandInG + # where no croparea at all, but FAO production reported isoMAGTotCrop <- dimSums(isoMAGCroparea, dim = 3) noMAGTotCrop <- (isoMAGTotCrop == 0) * isoMismatch @@ -183,6 +182,10 @@ calcProduction <- function(products = "kcr", cellular = FALSE, cells = "lpjcell" productionMAG["HKG", , "rainfed"] <- productionFAO["HKG", , ] / length(getItems(productionMAG["HKG", , ], dim = 1)) } + if (any(noMAGTotCrop["SYC", , ] != 0)) { + productionMAG["SYC", , "rainfed"] <- productionFAO["SYC", , ] / + length(getItems(productionMAG["SYC", , ], dim = 1)) + } if (any(noMAGTotCrop["MLT", , ] != 0)) { productionMAG["MLT", , "rainfed"] <- productionFAO["MLT", , ] / length(getItems(productionMAG["MLT", , ], dim = 1)) @@ -223,9 +226,13 @@ calcProduction <- function(products = "kcr", cellular = FALSE, cells = "lpjcell" isoproductionMAG <- isoMismatch <- dimSums(productionMAG, dim = c(1.1, 1.2, 3.2)) isoMismatch[] <- abs(round(isoproductionMAG - productionFAO, 4)) > 0 + # Warning if there are still mismatches if (any(isoMismatch != 0)) { - warning(paste0("Cellular data to FAO production mismatch ", - "after generic fix in calcProduction. Please check!")) + # ignore the HKG mismatch for now (since a more generic fix is coming) + if (any(isoMismatch["HKG", , invert = TRUE] != 0)) { + warning(paste0("Cellular data to FAO production mismatch ", + "after generic fix in calcProduction. Please check!")) + } } ##################################################################### @@ -252,7 +259,7 @@ calcProduction <- function(products = "kcr", cellular = FALSE, cells = "lpjcell" } else { #################################### - ### pasture production celluluar ### + ### pasture production cellular ### #################################### areaPasture <- collapseNames(calcOutput("LanduseInitialisation", cellular = TRUE, diff --git a/R/calcResBiomass.R b/R/calcResBiomass.R index 0559cd64..d664b404 100644 --- a/R/calcResBiomass.R +++ b/R/calcResBiomass.R @@ -39,7 +39,7 @@ calcResBiomass <- function(cellular = FALSE, cells = "lpjcell", } else if (plantparts %in% c("ag", "bg")) { # read in area harvested - harvestedArea <- calcOutput("Croparea", sectoral = "kcr", physical = FALSE, + harvestedArea <- calcOutput("Croparea", physical = FALSE, cellular = cellular, irrigation = irrigation, aggregate = FALSE) # cyears here above diff --git a/R/calcSNUpE.R b/R/calcSNUpE.R index a731decb..0deaa5b3 100644 --- a/R/calcSNUpE.R +++ b/R/calcSNUpE.R @@ -18,8 +18,9 @@ #' } #' calcSNUpE <- function( - max_snupe = 0.85, # nolint: object_name_linter. - cellular = FALSE, rev = 0.1, maccbase = TRUE) { + max_snupe = 0.85, # nolint: object_name_linter. + cellular = FALSE, rev = "0.1", maccbase = TRUE +) { a <- calcOutput("NitrogenBudgetCropland", max_snupe = max_snupe, aggregate = FALSE, deposition = "Nsurplus2", cellular = cellular) @@ -27,15 +28,13 @@ calcSNUpE <- function( a[, , "seed"] <- -a[, , "seed"] a[, , "fixation_crops"] <- -a[, , "fixation_crops"] a[, , "som"] <- a[, , "som"] * 1 - outputs <- c( - "fixation_crops", - "harvest", "ag", "bg", "seed") - inputs <- c( - "fixation_freeliving", - "som", "fertilizer", "deposition", - "manure_conf", "manure_stubble_grazing", - "bg_recycling", "ag_recycling", - "ag_ash", "balanceflow") + outputs <- c("fixation_crops", + "harvest", "ag", "bg", "seed") + inputs <- c("fixation_freeliving", + "som", "fertilizer", "deposition", + "manure_conf", "manure_stubble_grazing", + "bg_recycling", "ag_recycling", + "ag_ash", "balanceflow") outputs <- dimSums(a[, , outputs], dim = 3.1) inputs <- dimSums(a[, , inputs], dim = 3.1) sNUpE <- outputs / inputs @@ -172,7 +171,7 @@ calcSNUpE <- function( y2020CHN <- policyEffect + x["CHN", "y2020", "constant"] y2020CHN[y2020CHN > 70] <- 70 x["CHN", , scenarioname] <- convergence(origin = x["CHN", , "constant"], aim = y2020CHN, start_year = "y2010", - end_year = "y2020", type = "linear") + end_year = "y2020", type = "linear") x["CHN", 2015, scenarioname] <- x["CHN", 2015, scenarioname] - 0.0028612 return(x) } @@ -252,10 +251,9 @@ calcSNUpE <- function( out <- x } - return(list( - x = out, - weight = weight, - unit = "Share", - description = "Soil nitrogen uptake efficiency", - isocountries = !cellular)) + return(list(x = out, + weight = weight, + unit = "Share", + description = "Soil nitrogen uptake efficiency", + isocountries = !cellular)) } diff --git a/R/calcSOCLossShare.R b/R/calcSOCLossShare.R index 6fdaa280..264c158c 100644 --- a/R/calcSOCLossShare.R +++ b/R/calcSOCLossShare.R @@ -5,7 +5,8 @@ #' if TRUE crop specific values will be reported, #' if aggregated crop specific factors will be aggregated using crop area #' @param rate if change, change rates will be reported; if loss, loss rates will be reported -#' @param factor switch for different ipcc versions (ipccReduced, ipccReduced2019) +#' @param factor switch for different ipcc versions (ipccReduced, ipccReduced2019, ipccReduced2019Fallow) +#' for the parameters of FLU in Table 5.5 of IPCC Guidelines for National Greenhouse Gas Inventories Chapter 5. #' @param cells "magpiecell" for 59199 cells or "lpjcell" for 67420 cells #' #' @return List of magpie objects with results on cellular level, weight, unit and description. @@ -16,14 +17,17 @@ #' calcOutput("SOCLossShare", aggregate = FALSE) #' } #' -calcSOCLossShare <- function(subsystems = FALSE, rate = "change", factor = "ipccReduced", +calcSOCLossShare <- function(subsystems = FALSE, rate = "change", factor = "ipccReduced2019Fallow", cells = "lpjcell") { + # read in climate class depending on chosen factor + datasource <- gsub("Fallow", "", factor) ipccClimate <- calcOutput("ClimateClass", aggregate = FALSE, - datasource = factor) + datasource = datasource) factor2SCF <- c(ipccReduced = "SCF_sub", - ipccReduced2019 = "SCF_sub2019") + ipccReduced2019 = "SCF_sub2019", + ipccReduced2019Fallow = "SCF_sub2019_2") scf <- toolSubtypeSelect(factor, factor2SCF) scfSub2IPCCclimate <- readSource("IPCC", subtype = scf, convert = FALSE)[, , getNames(ipccClimate)] @@ -38,8 +42,9 @@ calcSOCLossShare <- function(subsystems = FALSE, rate = "change", factor = "ipcc if (subsystems == "aggregated") { magCrop <- calcOutput("Croparea", physical = TRUE, cellular = TRUE, - irrigation = FALSE, aggregate = FALSE) - kcr2all <- data.frame(list(kcr = getNames(socLossShare), all = rep("all", 19))) + irrigation = FALSE, fallow = TRUE, aggregate = FALSE) + kcr2all <- data.frame(list(kcr = getNames(socLossShare), + all = rep("all", length(getNames(socLossShare))))) socLossShare <- toolAggregate(socLossShare, weight = magCrop, rel = kcr2all, from = "kcr", to = "all", dim = 3) getNames(socLossShare) <- "cshare" } diff --git a/R/calcSOM.R b/R/calcSOM.R index c99a67f0..5274e390 100644 --- a/R/calcSOM.R +++ b/R/calcSOM.R @@ -47,11 +47,11 @@ calcSOM <- function(climatetype = "historical", subtype = "stock", cells = "lpjc cropArea <- dimSums(states[, , crops], dim = 3) noncropArea <- dimSums(states, dim = 3) - cropArea - cropshare <- toolFillYears(calcOutput("Croparea", sectoral = "kcr", physical = TRUE, + cropshare <- toolFillYears(calcOutput("Croparea", physical = TRUE, fallow = TRUE, cellular = TRUE, irrigation = FALSE, aggregate = FALSE), cyears) cropshare <- toolConditionalReplace(cropshare / dimSums(cropshare, dim = 3), "is.na()", 0) carbshare <- calcOutput("SOCLossShare", aggregate = FALSE, subsystems = TRUE, - rate = "change", factor = "ipccReduced", cells = "lpjcell") + rate = "change", cells = "lpjcell") cshare <- dimSums(cropshare * carbshare, dim = 3) cshare[cshare == 0] <- 1 # target for cropland in cells without cropland equal to nat veg just as backup. diff --git a/R/convertISIMIP.R b/R/convertISIMIP.R index 7bb2c6ee..ec0bade7 100644 --- a/R/convertISIMIP.R +++ b/R/convertISIMIP.R @@ -19,10 +19,10 @@ convertISIMIP <- function(x, subtype) { if (grepl("^airww", subtype)) { - # read in LUH landarea as weight - luh3 <- calcOutput("LUH3", cellular = TRUE, yrs = 1995, aggregate = FALSE) - landarea <- dimSums(luh3, 3) - landarea <- collapseDim(landarea, dim = "iso") + 10^-10 + # read in Landuse Initialisation landarea as weight + landArea <- calcOutput("LandArea", aggregate = FALSE) + landArea <- collapseDim(landArea, dim = "iso") + 10^-10 + x <- collapseDim(x, dim = "region") @@ -30,6 +30,6 @@ convertISIMIP <- function(x, subtype) { stop("Aggregation rule for given subtype \"", subtype, "\" not defined!") } - return(toolAggregateCell2Country(x, weight = landarea, fill = 0)) + return(toolAggregateCell2Country(x, weight = landArea, fill = 0)) } diff --git a/R/convertSSPResults.R b/R/convertSSPResults.R index 00b51883..1eebe6db 100644 --- a/R/convertSSPResults.R +++ b/R/convertSSPResults.R @@ -74,7 +74,7 @@ convertSSPResults <- function(x) { "Agricultural Demand|Bioenergy|2nd generation (million t DM/yr)") # use harvested area as weight - weightBio <- setYears(dimSums(calcOutput("Croparea", sectoral = "kcr", physical = TRUE, aggregate = FALSE), + weightBio <- setYears(dimSums(calcOutput("Croparea", physical = TRUE, aggregate = FALSE), dim = 3)[, 2010, ], NULL) for (sel in selection) { diff --git a/R/readIPCC.R b/R/readIPCC.R index b6b367e8..6236431b 100644 --- a/R/readIPCC.R +++ b/R/readIPCC.R @@ -50,6 +50,7 @@ readIPCC <- function(subtype) { SCF_input = "ch5_F_I.csv", SCF_sub = "ch5_F_LU.csv", SCF_sub2019 = "ch5_F_LU_2019.csv", + SCF_sub2019_2 = "ch5_F_LU_2019_2.csv", SCF_LU = "ch5_F_LU_raw.csv", SCF_LU2019 = "ch5_F_LU_2019_raw.csv", manure_table5p5c = "19R_V4_Ch05_Cropland_Table5p5C.csv", diff --git a/R/readWCDE.R b/R/readWCDE.R index a4c9d0f1..579c12bb 100644 --- a/R/readWCDE.R +++ b/R/readWCDE.R @@ -26,7 +26,7 @@ readWCDE <- function(subtype = "epop_v3") { files <- sort(list.files(pattern = "\\.rds$")) if (length(files) == 0) { - stop("No WCDE .rds files found. Use ", + stop("No WCDE .rds files found. The readWCDE function requires a subtype: use ", "subtype = \"epop_v3\" (projections 2020-2100) or subtype = \"epop_v2\" ", "(historical reconstruction).") } diff --git a/README.md b/README.md index f16daaf1..5db84e5c 100644 --- a/README.md +++ b/README.md @@ -49,7 +49,7 @@ A BibTeX entry for LaTeX users is title = {mrcommons: MadRat commons Input Data Library}, author = {Benjamin Leon Bodirsky and Kristine Karstens and Lavinia Baumstark and Isabelle Weindl and Xiaoxi Wang and Abhijeet Mishra and Stephen Wirth and Mishko Stevanovic and Nele Steinmetz and Ulrich Kreidenweis and Renato Rodrigues and Roman Popov and Florian Humpenoeder and Anastasis Giannousakis and Antoine Levesque and David Klein and Ewerton Araujo and Eva Bleidorn and Felicitas Beier and Julian Oeser and Michaja Pehl and Debbora Leip and Michael Crawford and Edna {Molina Bacca} and Patrick {von Jeetze} and Eleonora Martinelli and Felix Schreyer and Bjoern Soergel and Pascal Sauer and David Hötten and Robin Hasse and Gabriel Abrahão and Pascal Weigmann and Jan Philipp Dietrich}, doi = {10.5281/zenodo.3822009}, - date = {2026-08-10}, + date = {2026-08-13}, year = {2026}, url = {https://github.com/pik-piam/mrcommons}, note = {Version: 1.72.4}, diff --git a/man/calcFAOYield.Rd b/man/calcFAOYield.Rd index 01632165..76278834 100644 --- a/man/calcFAOYield.Rd +++ b/man/calcFAOYield.Rd @@ -11,7 +11,7 @@ calcFAOYield( cellular = FALSE, cut = FALSE, average = 5, - areaSource = "FAO" + areaSource = "LandInG" ) } \arguments{ @@ -28,7 +28,9 @@ number between 0 and 1 to define percentile value for cut off} \item{average}{averaging period in years (if NULL no averaging is used)} -\item{areaSource}{data source for croparea used in calculation: FAO or Toolbox} +\item{areaSource}{data source for croparea used in calculation: "LandInG" (default) +or "FAOLUH". The latter one is deprecated. The former default +"FAO" is no longer accepted.} } \value{ MAgPIE object of yields diff --git a/man/calcFertilizerByCrop.Rd b/man/calcFertilizerByCrop.Rd index 5c2084e1..10a197d9 100644 --- a/man/calcFertilizerByCrop.Rd +++ b/man/calcFertilizerByCrop.Rd @@ -11,8 +11,8 @@ calcFertilizerByCrop( ) } \arguments{ -\item{indicator}{total: estimates the inputs per total crop production; by_harvest estimates the inputs -per ton harvest; by_area estimates the inputs per area harvested} +\item{indicator}{total: estimates the inputs per total crop production; by_physical_area and by_area_harvested +estimates the inputs per unit of land} \item{deposition}{if FALSE, deposition is not accounted for in the distribution. Use FALSE to avoid circularities in calcNitrogenBudget} diff --git a/man/calcNitrogenBNF.Rd b/man/calcNitrogenBNF.Rd index f07af149..5b92a841 100644 --- a/man/calcNitrogenBNF.Rd +++ b/man/calcNitrogenBNF.Rd @@ -20,9 +20,6 @@ calculates fixation from freeliving bacteria and from nitrogen-fixing crops and calcOutput("NitrogenBNF") } -} -\seealso{ -\code{\link[=calcNitrogenFixationPast]{calcNitrogenFixationPast()}} } \author{ Benjamin Leon Bodirsky diff --git a/man/calcNitrogenFixationFreeliving.Rd b/man/calcNitrogenFixationFreeliving.Rd new file mode 100644 index 00000000..6efa403d --- /dev/null +++ b/man/calcNitrogenFixationFreeliving.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/calcNitrogenFixationFreeliving.R +\name{calcNitrogenFixationFreeliving} +\alias{calcNitrogenFixationFreeliving} +\title{calcNitrogenFixationFreeliving} +\usage{ +calcNitrogenFixationFreeliving(cellular = FALSE, irrigation = FALSE) +} +\arguments{ +\item{cellular}{cellular estimates optional} + +\item{irrigation}{if TRUE, distinguishes irrigated and non-irrigated crops} +} +\value{ +List of magpie objects with results on country level, weight on country level, unit and description. +} +\description{ +calculates fixation from freeliving bacteria +} +\examples{ +\dontrun{ +calcOutput("NitrogenFixationFreeliving") +} +} +\author{ +Benjamin Leon Bodirsky +} diff --git a/man/calcNitrogenFixationPast.Rd b/man/calcNitrogenFixationPast.Rd deleted file mode 100644 index 4d4ad210..00000000 --- a/man/calcNitrogenFixationPast.Rd +++ /dev/null @@ -1,39 +0,0 @@ -% Generated by roxygen2: do not edit by hand -% Please edit documentation in R/calcNitrogenFixationPast.R -\name{calcNitrogenFixationPast} -\alias{calcNitrogenFixationPast} -\title{calcNitrogenFixationPast} -\usage{ -calcNitrogenFixationPast( - fixation_types = "both", - sum_plantparts = TRUE, - cellular = FALSE, - irrigation = FALSE -) -} -\arguments{ -\item{fixation_types}{either "fixation_crops", "fixation_freeliving", or "both"} - -\item{sum_plantparts}{if false, crop residues, belowground residues and harvested organ are reported separately} - -\item{cellular}{cellular estimates optional} - -\item{irrigation}{if TRUE, distinguishes irrigated and non-irrigated crops} -} -\value{ -List of magpie objects with results on country level, weight on country level, unit and description. -} -\description{ -calculates fixation from freeliving bacteria and from nitrogen-fixing crops -} -\examples{ -\dontrun{ -calcOutput("calcNitrogenFixationPast") -} -} -\seealso{ -\code{\link[=calcNitrogenFixationPast]{calcNitrogenFixationPast()}} -} -\author{ -Benjamin Leon Bodirsky -} diff --git a/man/calcNitrogenFixationRateNatural.Rd b/man/calcNitrogenFixationRateNatural.Rd index 7b233a90..dc581ba5 100644 --- a/man/calcNitrogenFixationRateNatural.Rd +++ b/man/calcNitrogenFixationRateNatural.Rd @@ -20,10 +20,6 @@ calculates fixation rates from natural ecosystems based on evapostranspiration calcOutput("NitrogenFixationRateNatural") } -} -\seealso{ -\code{\link[=calcNitrogenFixationPast]{calcNitrogenFixationPast()}} -\code{\link[=readHerridge]{readHerridge()}} } \author{ Benjamin Leon Bodirsky diff --git a/man/calcNitrogenFixationSymbiotic.Rd b/man/calcNitrogenFixationSymbiotic.Rd new file mode 100644 index 00000000..a37cb120 --- /dev/null +++ b/man/calcNitrogenFixationSymbiotic.Rd @@ -0,0 +1,27 @@ +% Generated by roxygen2: do not edit by hand +% Please edit documentation in R/calcNitrogenFixationSymbiotic.R +\name{calcNitrogenFixationSymbiotic} +\alias{calcNitrogenFixationSymbiotic} +\title{calcNitrogenFixationSymbiotic} +\usage{ +calcNitrogenFixationSymbiotic(cellular = FALSE, irrigation = FALSE) +} +\arguments{ +\item{cellular}{cellular estimates optional} + +\item{irrigation}{if TRUE, distinguishes irrigated and non-irrigated crops} +} +\value{ +List of magpie objects with results on country level, weight on country level, unit and description. +} +\description{ +calculates fixation from nitrogen-fixing crops +} +\examples{ +\dontrun{ +calcOutput("NitrogenFixationSymbiotic") +} +} +\author{ +Benjamin Leon Bodirsky +} diff --git a/man/calcSNUpE.Rd b/man/calcSNUpE.Rd index a1a60e8d..7d2b7508 100644 --- a/man/calcSNUpE.Rd +++ b/man/calcSNUpE.Rd @@ -4,7 +4,7 @@ \alias{calcSNUpE} \title{calcSNUpE} \usage{ -calcSNUpE(max_snupe = 0.85, cellular = FALSE, rev = 0.1, maccbase = TRUE) +calcSNUpE(max_snupe = 0.85, cellular = FALSE, rev = "0.1", maccbase = TRUE) } \arguments{ \item{max_snupe}{Maximum realistic SNUPE. All values above will be limited to this value. Only holds diff --git a/man/calcSOCLossShare.Rd b/man/calcSOCLossShare.Rd index a69ba0f1..fad51894 100644 --- a/man/calcSOCLossShare.Rd +++ b/man/calcSOCLossShare.Rd @@ -7,7 +7,7 @@ calcSOCLossShare( subsystems = FALSE, rate = "change", - factor = "ipccReduced", + factor = "ipccReduced2019Fallow", cells = "lpjcell" ) } @@ -18,7 +18,8 @@ if aggregated crop specific factors will be aggregated using crop area} \item{rate}{if change, change rates will be reported; if loss, loss rates will be reported} -\item{factor}{switch for different ipcc versions (ipccReduced, ipccReduced2019)} +\item{factor}{switch for different ipcc versions (ipccReduced, ipccReduced2019, ipccReduced2019Fallow) +for the parameters of FLU in Table 5.5 of IPCC Guidelines for National Greenhouse Gas Inventories Chapter 5.} \item{cells}{"magpiecell" for 59199 cells or "lpjcell" for 67420 cells} } diff --git a/mrcommons_croparea.Rproj b/mrcommons_croparea.Rproj new file mode 100644 index 00000000..ae8066d4 --- /dev/null +++ b/mrcommons_croparea.Rproj @@ -0,0 +1,21 @@ +Version: 1.0 +ProjectId: 47a52aeb-bbed-4ef2-a36f-f670933e0943 + +RestoreWorkspace: Default +SaveWorkspace: Default +AlwaysSaveHistory: Default + +EnableCodeIndexing: Yes +UseSpacesForTab: Yes +NumSpacesForTab: 2 +Encoding: ISO8859-1 + +RnwWeave: Sweave +LaTeX: XeLaTeX + +AutoAppendNewline: Yes +StripTrailingWhitespace: Yes + +BuildType: Package +PackageUseDevtools: Yes +PackageInstallArgs: --no-multiarch --with-keep.source