diff --git a/.buildlibrary b/.buildlibrary index f9c8633aa..a661a6569 100644 --- a/.buildlibrary +++ b/.buildlibrary @@ -1,4 +1,4 @@ -ValidationKey: '5075889' +ValidationKey: '5115825' AcceptedWarnings: - 'Warning: package ''.*'' was built under R version' - 'Warning: namespace ''.*'' is not available and has been replaced' diff --git a/.zenodo.json b/.zenodo.json index 562af62c1..aff090510 100644 --- a/.zenodo.json +++ b/.zenodo.json @@ -1,6 +1,6 @@ { "title": "mrmagpie: madrat based MAgPIE Input Data Library", - "version": "0.27.3", + "version": "0.27.5", "description": "
Provides functions for MAgPIE country and cellular input data generation.<\/p>",
"creators": [
{
diff --git a/DESCRIPTION b/DESCRIPTION
index 579312ebd..ce4cd64d4 100644
--- a/DESCRIPTION
+++ b/DESCRIPTION
@@ -1,8 +1,8 @@
Package: mrmagpie
Type: Package
Title: madrat based MAgPIE Input Data Library
-Version: 0.27.3
-Date: 2020-11-27
+Version: 0.27.5
+Date: 2020-12-07
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"),
person("David", "Chen", role = "aut"),
diff --git a/R/calcActualIrrigWatRequirements.R b/R/calcActualIrrigWatRequirements.R
deleted file mode 100644
index e6f44ef35..000000000
--- a/R/calcActualIrrigWatRequirements.R
+++ /dev/null
@@ -1,76 +0,0 @@
-#' @title calcActualIrrigWatRequirements
-#' @description This function calculates actual irrigation water requirements per cell given a certain irrigation system
-#'
-#' @param selectyears Years to be returned
-#' @param iniyear Initialization year (for weight by cropland)
-#' @param version Switch between LPJmL4 and LPJmL5
-#' @param climatetype Switch between different climate scenarios (default: "CRU_4")
-#' @param cells Switch between "lpjcell" (67420) and "magpiecell" (59199)
-#' @param crops Selects "magpie" (default) or "lpjml" crops
-#' @param time Time smoothing: average, spline or raw (default)
-#' @param averaging_range only specify if time=="average": number of time steps to average
-#' @param dof only specify if time=="spline": degrees of freedom needed for spline
-#' @param harmonize_baseline FALSE (default): no harmonization, TRUE: if a baseline is specified here data is harmonized to that baseline (from ref_year on)
-#' @param ref_year Reference year for harmonization baseline (just specify when harmonize_baseline=TRUE)
-#' @param irrig_requirement Consumptive (consumption) or non-consumptive (withdrawals) irrigation water requirements
-#' @param irrig_system_source Source of irrigation system initialization data including information about cellular detail (e.g. Jaegermeyr_magpiecell)
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier
-#'
-#' @seealso
-#' \code{\link{calcIrrigationSystem}}, \code{\link{calcIrrigWatRequirements}}
-#'
-#' @examples
-#' \dontrun{ calcOutput("ActualIrrigWatRequirements", aggregate=FALSE) }
-#'
-#' @import magpiesets
-#' @import magclass
-#' @import madrat
-
-calcActualIrrigWatRequirements <- function(selectyears="all", iniyear=1995, cells="magpiecell", crops="magpie",
- version="LPJmL5", climatetype="HadGEM2_ES:rcp2p6:co2", time="raw", averaging_range=NULL, dof=NULL,
- harmonize_baseline=FALSE, ref_year=NULL, irrig_requirement="withdrawal", irrig_system_source="Jaegermeyr_magpiecell"){
-
- if (cells!=gsub(".*_","",irrig_system_source)){
- stop("Cells mismatch. Please select the same cell type in the function arguments cells and irrig_system_source!")
- }
-
- # irrigation water requirement per crop per system (in m^3 per ha per yr)
- irrig_wat_requirement <- calcOutput("IrrigWatRequirements", selectyears=selectyears, cells=cells, crops=crops, irrig_requirement=irrig_requirement,
- version=version, climatetype=climatetype, time=time, averaging_range=averaging_range, dof=dof,
- harmonize_baseline=harmonize_baseline, ref_year=ref_year, aggregate=FALSE)
- names(dimnames(irrig_wat_requirement))[1] <- "iso.cell"
- names(dimnames(irrig_wat_requirement))[3] <- "crop.system"
-
- # irrigation system share (share of irrigated area)
- irrig_system_share <- calcOutput("IrrigationSystem", source=irrig_system_source, aggregate=FALSE)
-
- # composite mean
- mean_irrig_wat_requirement <- dimSums(irrig_system_share*irrig_wat_requirement,dim=3.1)/dimSums(irrig_system_share, dim=3)
-
- # Correction of years
- if(selectyears!="all"){
- years <- sort(findset(selectyears,noset="original"))
- mean_irrig_wat_requirement <- mean_irrig_wat_requirement[,years,]
- }
-
- # Check for NAs and negative values
- if(any(is.na(mean_irrig_wat_requirement))){
- stop("produced NA irrigation water requirements")
- }
- if(any(mean_irrig_wat_requirement<0)){
- stop("produced negative irrigation water requirements")
- }
-
- # irrigated cropland area as weight
- irrig_area <- calcOutput("Croparea", years=iniyear, sectoral="kcr", cells=cells, physical=TRUE, cellular=TRUE, irrigation=TRUE, aggregate=FALSE)
- irrig_area <- collapseNames(irrig_area[,,"irrigated"][,,"pasture",invert=T])+1e-9
-
- return(list(
- x=mean_irrig_wat_requirement,
- weight=irrig_area,
- unit="m^3 per ha per yr",
- description="Irrigation water requirements for irrigation for different crop types under selected irrigation system share per cell",
- isocountries=FALSE))
-}
diff --git a/R/calcBphEffect.R b/R/calcBphEffect.R
index f95478ee7..56ba6df7a 100644
--- a/R/calcBphEffect.R
+++ b/R/calcBphEffect.R
@@ -45,7 +45,7 @@ calcBphEffect <-function(){
cells_NA <- cells[is.na(x[cells,,"ann_bph"])]
#If all cells are NA, use m_glo, otherwise calc mean based on the non NA cells.
if(identical(cells,cells_NA)) {
- x[cells_NA,,"ann_bph"] <- m_glo
+ x[cells_NA,,"ann_bph"] <- m_glo
} else {
m <- mean(x[cells,,"ann_bph"],na.rm=TRUE)
x[cells_NA,,"ann_bph"] <- m
diff --git a/R/calcEnvmtlFlowRequirements.R b/R/calcEnvmtlFlowRequirements.R
deleted file mode 100644
index d4d8fbedc..000000000
--- a/R/calcEnvmtlFlowRequirements.R
+++ /dev/null
@@ -1,96 +0,0 @@
-#' @title calcEnvmtlFlowRequirements
-#' @description This function calculates environmental flow requirements (EFR) for MAgPIE based on LPJmL monthly discharge following Smakthin et al. (2004)
-#'
-#' @param version Switch between LPJmL4 and LPJmL5
-#' @param climatetype Switch between different climate scenarios (default: "CRU_4")
-#' @param cells Number of cells to be reported: lpjcell (67420, default) or magpiecell (59199)
-#' @param LFR_val Strictness of environmental flow requirements
-#' @param HFR_LFR_less10 High flow requirements (share of total water for cells) with LFR<10percent of total water
-#' @param HFR_LFR_10_20 High flow requirements (share of total water for cells) with 10percent < LFR < 20percent of total water
-#' @param HFR_LFR_20_30 High flow requirements (share of total water for cells) with 20percent < LFR < 30percent of total water
-#' @param HFR_LFR_more30 High flow requirements (share of total water for cells) with LFR>30percent of total water
-#' @param EFRyears Long-term reference time frame for EFR calculation
-#'
-#' @import magclass
-#' @import madrat
-#' @importFrom stats quantile
-#' @importFrom mrcommons toolHarmonize2Baseline
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier, Jens Heinke
-#'
-#' @examples
-#' \dontrun{ calcOutput("EnvmtlFlowRequirements", aggregate=FALSE) }
-#'
-
-calcEnvmtlFlowRequirements <- function(version="LPJmL4", climatetype="HadGEM2_ES:rcp2p6:co2", cells="lpjcell",
- LFR_val=0.1, HFR_LFR_less10=0.2, HFR_LFR_10_20=0.15, HFR_LFR_20_30=0.07, HFR_LFR_more30=0.00,
- EFRyears=c(1985:2015)){
-
- # Long-term reference period for EFR calculation
- EFRyears <- paste0("y",EFRyears)
-
- ### Monthly Discharge from LPJmL
- monthly_discharge_magpie <- calcOutput("LPJmL", selectyears=EFRyears, version=version, climatetype=climatetype, subtype="mdischarge_lpjcell", aggregate=FALSE,
- harmonize_baseline=FALSE, ref_year=NULL, time="raw", averaging_range=NULL, dof=NULL)
-
- # Extract years
- years <- getYears(monthly_discharge_magpie, as.integer=TRUE)
- # Transform to array (faster calculation)
- monthly_discharge_magpie <- as.array(collapseNames(monthly_discharge_magpie))
-
- ### Calculate LFRs
- ## Note: LFRs correspond to the Q90-value (i.e. to the discharge that is exceeded in nine out of ten months)
- ## (Bonsch et al. 2015). This is calculated via the 10%-quantile of monthly discharge.
-
- # Get the monthly LFR_val quantile for all cells (across selected long-term reference time period)
- LFR_quant <- apply(monthly_discharge_magpie, MARGIN=c(1), quantile, probs=LFR_val)
-
- # Yearly LFRs
- LFR <- LFR_quant*12
-
- ### Mean annual discharge
- mean_annual_discharge <- apply(monthly_discharge_magpie, MARGIN=c(1), sum)/length(years)
-
- ### Calculate HFR
- ## Note: "For rivers with low Q90 values, high-flow events are important
- ## for river channel maintenance, wetland flooding, and riparian vegetation.
- ## HFRs of 20% of available water are therefore assigned to rivers with a
- ## low fraction of Q90 in total discharge. Rivers with a more stable flow
- ## regime receive a lower HFR." (Bonsch et al. 2015)
- HFR <- LFR
- HFR <- NA
- HFR[LFR<0.1*mean_annual_discharge] <- HFR_LFR_less10 * mean_annual_discharge[LFR<0.1*mean_annual_discharge]
- HFR[LFR>=0.1*mean_annual_discharge] <- HFR_LFR_10_20 * mean_annual_discharge[LFR>=0.1*mean_annual_discharge]
- HFR[LFR>=0.2*mean_annual_discharge] <- HFR_LFR_20_30 * mean_annual_discharge[LFR>=0.2*mean_annual_discharge]
- HFR[LFR>=0.3*mean_annual_discharge] <- HFR_LFR_more30 * mean_annual_discharge[LFR>=0.3*mean_annual_discharge]
- HFR[mean_annual_discharge<=0] <- 0
-
- ### EFR
- EFR <- LFR+HFR
- # Reduce EFR to 50% of available water where it exceeds this threshold (according to Smakhtin 2004)
- EFR <- pmin(EFR, 0.5*mean_annual_discharge)
-
- ### Correct number of cells and transform to magpie object
- if (cells=="lpjcell"){
- EFR <- as.magpie(EFR, spatial=1)
- } else if (cells=="magpiecell"){
- EFR <- EFR[magclassdata$cellbelongings$LPJ_input.Index]
- EFR <- as.magpie(EFR, spatial=1)
- dimnames(EFR)[[1]] <- paste(magclassdata$half_deg$region,1:59199,sep='.')
- } else {
- stop("Cell argument not supported. Select lpjcell for 67420 cells or magpiecell for 59199 cells")
- }
-
- # Check for NAs
- if(any(is.na(EFR))){
- stop("produced NA EFR")
- }
-
- return(list(
- x=EFR,
- weight=NULL,
- unit="mio. m^3",
- description="Environmental flow requirements per cell per year",
- isocountries=FALSE))
-}
diff --git a/R/calcFullIrrigationRequirement.R b/R/calcFullIrrigationRequirement.R
deleted file mode 100644
index 98232ea61..000000000
--- a/R/calcFullIrrigationRequirement.R
+++ /dev/null
@@ -1,83 +0,0 @@
-#' @title calcFullIrrigationRequirement
-#' @description This function calculates the water requirements for full irrigation per cell per crop given potentially available land
-#'
-#' @param selectyears years to be returned
-#' @param version switch between LPJmL4 and LPJmL5
-#' @param climatetype switch between different climate scenarios (default: "CRU_4")
-#' @param cells switch between "lpjcell" (67420) and "magpiecell" (59199)
-#' @param time time smoothing: average, spline or raw (default)
-#' @param averaging_range only specify if time=="average": number of time steps to average
-#' @param dof only specify if time=="spline": degrees of freedom needed for spline
-#' @param harmonize_baseline FALSE (default): no harmonization, TRUE: if a baseline is specified here data is harmonized to that baseline (from ref_year on)
-#' @param ref_year reference year for harmonization baseline (just specify when harmonize_baseline=TRUE)
-#' @param irrig_requirement consumptive (consumption) or non-consumptive (withdrawals) irrigation water requirements
-#' @param iniarea if TRUE (default): already irrigated area is subracted, if FALSE: total potential land area is used
-#' @param iniyear Year of initialization for cropland area
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier
-#'
-#' @examples
-#' \dontrun{ calcOutput("FullIrrigationRequirement", aggregate=FALSE) }
-#'
-#' @import madrat
-#' @import magclass
-
-calcFullIrrigationRequirement <- function(version="LPJmL5", climatetype="HadGEM2_ES:rcp2p6:co2", harmonize_baseline=FALSE, time="spline", dof=4, cells="lpjcell", selectyears=seq(1995,2095,by=5), iniyear=1995, iniarea=TRUE, irrig_requirement="withdrawal"){
-
- # read in irrigation water requirements [in m^3 per hectar per year] (smoothed & harmonized)
- irrig_wat <- calcOutput("IrrigWatRequirements", selectyears=selectyears, version=version, climatetype=climatetype,
- harmonize_baseline=harmonize_baseline, time=time, dof=dof,
- irrig_requirement=irrig_requirement, cells="magpiecell", aggregate=FALSE)
- # pasture is not irrigated in MAgPIE
- irrig_wat <- irrig_wat[,,"pasture",invert=T]
- irrig_wat <- toolCell2isoCell(irrig_wat)
-
- # read in land available for agricultural use (in mio. ha)
- land <- collapseNames(calcOutput("AvlLandSi", aggregate=FALSE)[,,"si0"])
- if (iniarea) {
- # subtract area already reserved for irrigation by committed agricultural uses (in mio. ha)
- crops_grown <- calcOutput("IrrigatedArea", selectyears=selectyears, iniyear=iniyear, cells="magpiecell", aggregate=FALSE)
- crops_grown <- collapseNames(dimSums(crops_grown,dim=3))
- land <- land - crops_grown
- }
- # negative values may occur because AvlLandSi is based on Ramankutty data and Cropara based on LUH -> set to 0
- land[land<0] <- 0
-
- # water requirements for full irrigation in cell per crop (in mio. m^3)
- # Note on unit transformation:
- # land (mio ha -> ha): multiply with 1e6,
- # irrigation water requirements (m^3 per ha -> mio. m^3 per ha): devide by 1e6
- # --> cancels out -> water requirements for full irrigation (mio. m^3)
- tmp <- irrig_wat*land
-
- # cellular dimension
- if (cells=="magpiecell") {
- out <- tmp
- } else if (cells=="lpjcell") {
- lpj_cells_map <- toolGetMapping("LPJ_CellBelongingsToCountries.csv", type="cell")
- getCells(tmp) <- paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep=".")
- out <- new.magpie(1:67420,getYears(tmp),getNames(tmp))
- out[,,] <- 0
- out[paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep="."),,] <- tmp[,,]
- getCells(out) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- } else {
- stop("Cells argument not supported. Please select lpjcell for 67420 cells or magpiecell for 59199 cells")
- }
-
- # dimension names
- getSets(out)[c(1,2)] <- c("iso","cell")
- getSets(out)[c(4,5)] <- c("crop","system")
-
- # Checks
- if(any(is.na(out))){
- stop("produced NA full irrigation requirements")
- }
-
- return(list(
- x=out,
- weight=NULL,
- unit="mio. m^3",
- description="full irrigation requirements per cell per crop per irrigation system",
- isocountries=FALSE))
-}
diff --git a/R/calcIrrigCellranking.R b/R/calcIrrigCellranking.R
deleted file mode 100644
index 4e55b9fd1..000000000
--- a/R/calcIrrigCellranking.R
+++ /dev/null
@@ -1,76 +0,0 @@
-#' @title calcIrrigCellranking
-#' @description This function calculates a cellranking for the river basin discharge allocation based on yield improvement potential through irrigation
-#'
-#' @param version switch between LPJmL version for yields
-#' @param climatetype switch between different climate scenarios for yields
-#' @param time time smoothing: average, spline (default) or raw
-#' @param averaging_range just specify for time=="average": number of time steps to average
-#' @param dof just specify for time=="spline": degrees of freedom
-#' @param harmonize_baseline FALSE (default) no harmonization, harmonization: if a baseline is specified here data is harmonized to that baseline (from ref_year onwards)
-#' @param ref_year just specify for harmonize_baseline != FALSE : Reference year
-#' @param cellrankyear year(s) for which cell rank is calculated
-#' @param cells switch between "lpjcell" (67420) and "magpiecell" (59199)
-#' @param crops switch between "magpie" and "lpjml" (default) crops
-#' @param method method of calculating the rank: "meancellrank" (default): mean over cellrank of proxy crops, "meancroprank": rank over mean of proxy crops
-#' @param proxycrop proxycrop(s) selected for rank calculation
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier
-#'
-#' @examples
-#' \dontrun{ calcOutput("calcIrrigCellranking", aggregate=FALSE) }
-
-calcIrrigCellranking <- function(version="LPJmL5", climatetype="HadGEM2_ES:rcp2p6:co2", time="spline", averaging_range=NULL, dof=4, harmonize_baseline=FALSE, ref_year="y2015",
- cellrankyear="y1995", cells="lpjcell", crops="magpie", method="meancellrank", proxycrop=c("maiz", "rapeseed", "puls_pro")){
-
- ### Read in potential yield gain per cell
- yield_gain <- calcOutput("IrrigYieldImprovementPotential", version=version, climatetype=climatetype, selectyears=cellrankyear,
- harmonize_baseline=harmonize_baseline, ref_year=ref_year, time=time, averaging_range=averaging_range, dof=dof,
- cells=cells, crops=crops, aggregate=FALSE)
- # select proxy crops
- yield_gain <- yield_gain[,,proxycrop]
-
- ### Calculate global cell rank
- # Def. "meancellrank": ranking of cells or proxy crops, then: average over ranks
- if (method=="meancellrank"){
-
- # cell ranking for crop (from highest yield gain (rank=1) to lowest yield gain (rank=1+x))
- cropcellrank <- apply(-yield_gain,c(2,3),rank)
-
- # calculate mean over cropcellranks
- glocellrank <- dimSums(cropcellrank,dim=3)/length(getNames(cropcellrank))
- # ties are solved by first occurrence
- glocellrank <- apply(glocellrank,2,rank,ties.method="first")
-
- # Def. "meancroprank": average over yield gain of proxycrops, then: ranking of resulting average yield gain
- } else if (method=="meancroprank"){
-
- # normalize yield gains of proxy crops (unity-based normalization)
- min_yield <- as.magpie(apply(yield_gain,c(2,3),min))
- max_yield <- as.magpie(apply(yield_gain,c(2,3),max))
- yield_gain <- (yield_gain-min_yield)/(max_yield-min_yield)
-
- # calculate average yield gain over normalized proxy crops
- yield_gain <- dimSums(yield_gain,dim=3)/length(getNames(yield_gain))
-
- # calculate rank (ties are solved by first occurence)
- glocellrank <- apply(-yield_gain,c(2,3),rank,ties.method="first")
-
- } else {
- stop("Please select a method for rank calculation")
- }
-
- glocellrank <- as.magpie(glocellrank,spatial=1)
-
- # Check for NAs
- if(any(is.na(glocellrank))){
- stop("Function YieldImprovementPotential produced NAs")
- }
-
- return(list(
- x=glocellrank,
- weight=NULL,
- unit="1",
- description="Rank of cell according to yield gain potential by irrigation",
- isocountries=FALSE))
-}
diff --git a/R/calcIrrigWatRequirements.R b/R/calcIrrigWatRequirements.R
deleted file mode 100644
index 87db31ada..000000000
--- a/R/calcIrrigWatRequirements.R
+++ /dev/null
@@ -1,128 +0,0 @@
-#' @title calcIrrigWatRequirements
-#' @description This function calculates irrigation water requirements based on LPJmL blue water consumption of plants and considering irrigation efficiencies
-#'
-#' @param selectyears Years to be returned
-#' @param version Switch between LPJmL4 and LPJmL5
-#' @param climatetype Switch between different climate scenarios (default: "CRU_4")
-#' @param cells Switch between "lpjcell" (67420) and "magpiecell" (59199)
-#' @param crops Selects "magpie" (default) or "lpjml" crops
-#' @param time Time smoothing: average, spline or raw (default) of input data to this function
-#' @param averaging_range only specify if time=="average": number of time steps to average
-#' @param dof only specify if time=="spline": degrees of freedom needed for spline
-#' @param harmonize_baseline FALSE (default): no harmonization of input data to this function, TRUE: if a baseline is specified here data is harmonized to that baseline (from ref_year on)
-#' @param ref_year Reference year for harmonization baseline of input data to this function (just specify when harmonize_baseline=TRUE)
-#' @param irrig_requirement Consumptive (consumption) or non-consumptive (withdrawals) irrigation water requirements
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier, Jens Heinke
-#'
-#' @examples
-#' \dontrun{ calcOutput("IrrigWatRequirements", aggregate=FALSE) }
-#'
-#' @import magpiesets
-#' @import magclass
-#' @import madrat
-
-calcIrrigWatRequirements <- function(selectyears="all", cells="lpjcell", crops="magpie",
- version="LPJmL5", climatetype="HadGEM2_ES:rcp2p6:co2", time="spline", averaging_range=NULL, dof=4,
- harmonize_baseline=FALSE, ref_year=NULL, irrig_requirement="withdrawal"){
-
- sizelimit <- getOption("magclass_sizeLimit")
- options(magclass_sizeLimit=1e+12)
- on.exit(options(magclass_sizeLimit=sizelimit))
-
- ##############################
- ######## Read in data ########
- ##############################
- ### Mappings
- lpj_cells_map <- toolGetMapping("LPJ_CellBelongingsToCountries.csv", type="cell")
- LPJ2MAG <- toolGetMapping( "MAgPIE_LPJmL.csv", type = "sectoral", where = "mappingfolder")
-
- ### Read in blue water consumption for irrigated crops (in m^3 per ha per yr):
- blue_water_consumption <- collapseNames(calcOutput("LPJmL", version=version, climatetype=climatetype, harmonize_baseline=harmonize_baseline, ref_year=ref_year,
- time=time, averaging_range=averaging_range, dof=dof,
- selectyears=selectyears, subtype="cwater_b_lpjcell", aggregate=FALSE)[,,"irrigated"])
- names(dimnames(blue_water_consumption))[1] <- "iso.cell"
- names(dimnames(blue_water_consumption))[3] <- "crop"
- years <- getYears(blue_water_consumption)
- cropnames <- getNames(blue_water_consumption)
- systemnames <- c("drip","sprinkler","surface")
-
- ### Field efficiencies from Jägermeyr et al. (global values) [placeholder!]
- field_efficiency <- new.magpie(1:67420,years,sort(paste(systemnames, rep(cropnames,3), sep=".")),sets=c("iso.cell","year","system.crop"))
- getCells(field_efficiency) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- field_efficiency[,,"drip"] <- 0.88
- field_efficiency[,,"sprinkler"] <- 0.78
- field_efficiency[,,"surface"] <- 0.52
- ### Use field efficiency from LPJmL here (by system, by crop, on 0.5 degree) [Does it vary by year?]
-
- ### Conveyance efficiency proxy [placeholder]
- conveyance_efficiency <- new.magpie(1:67420,years,sort(paste(systemnames, rep(cropnames,3), sep=".")),sets=c("iso.cell","year","system.crop"))
- getCells(conveyance_efficiency) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- conveyance_efficiency[,,"drip"] <- 0.95
- conveyance_efficiency[,,"sprinkler"] <- 0.95
- conveyance_efficiency[,,"surface"] <- 0.7
- ### Use field efficiency from LPJmL here (by system, on 0.5 degree) [Does it vary by year?]
-
- ##############################
- ######## Calculations ########
- ##############################
-
- # Calculate project efficiency from given field and conveyance efficiencies
- project_efficiency <- field_efficiency * conveyance_efficiency
-
- # Water withdrawal = crop water consumption + field losses + conveyance losses
- water_withdrawal <- blue_water_consumption/project_efficiency
-
- # Conveyance loss (from river to field)
- conveyance_loss <- water_withdrawal*(1-conveyance_efficiency)
-
- # consumptive irrigation water = consumptive plant transpiration + evaporative conveyance loss
- # (Note: According to Rost et al. (2007) 50% of conveyance loss are evaporative)
- water_consumption <- blue_water_consumption + 0.5*conveyance_loss
-
- # Output: irrigation water requirements (consumption or withdrawals)
- if (irrig_requirement=="consumption"){
- irrig_requirements <- water_consumption
- } else if (irrig_requirement=="withdrawal"){
- irrig_requirements <- water_withdrawal
- } else {
- stop("Specify consumption or withdrawal in irrig_requirement")
- }
-
- # Aggregate to MAgPIE crops
- if (crops=="magpie") {
- irrig_requirements <- toolAggregate(irrig_requirements, LPJ2MAG, from="LPJmL", to="MAgPIE", dim=3.1, partrel=TRUE)
- }
-
- if(selectyears!="all"){
- years <- sort(findset(selectyears,noset="original"))
- irrig_requirements <- irrig_requirements[,years,]
- }
-
- ### Correct number of cells
- if (cells=="lpjcell"){
- out <- irrig_requirements
- } else if (cells=="magpiecell"){
- irrig_requirements <- irrig_requirements[magclassdata$cellbelongings$LPJ_input.Index,,]
- irrig_requirements <- toolCell2isoCell(irrig_requirements)
- out <- irrig_requirements
- } else {
- stop("Cell argument not supported. Select lpjcell for 67420 cells or magpiecell for 59199 cells")
- }
-
- # Check for NAs and negative values
- if(any(is.na(out))){
- stop("produced NA irrigation water requirements")
- }
- if(any(out<0)){
- stop("produced negative irrigation water requirements")
- }
-
- return(list(
- x=out,
- weight=NULL,
- unit="m^3 per ha per yr",
- description="Irrigation water requirements for irrigation for different crop types under different irrigation systems",
- isocountries=FALSE))
-}
diff --git a/R/calcIrrigYieldImprovementPotential.R b/R/calcIrrigYieldImprovementPotential.R
deleted file mode 100644
index 5f880d281..000000000
--- a/R/calcIrrigYieldImprovementPotential.R
+++ /dev/null
@@ -1,60 +0,0 @@
-#' @title calcIrrigYieldImprovementPotential
-#' @description This function calculates the yield improvement potential of irrigation for different crops
-#'
-#' @param version switch between LPJmL4 and LPJmL5 of calcYields function
-#' @param climatetype switch between different climate scenarios (default: "CRU_4") of calcYields function
-#' @param selectyears years to be returned by the function
-#' @param time time smoothing of calcYields function: average, spline (default) or raw
-#' @param averaging_range only specify if time=="average": number of time steps to average
-#' @param dof only specify if time=="spline": degrees of freedom needed for spline
-#' @param harmonize_baseline harmonization in calcYields function: FALSE (default): no harmonization, TRUE: if a baseline is specified here data is harmonized to that baseline (from ref_year onwards)
-#' @param ref_year reference year for harmonization baseline (just specify when harmonize_baseline=TRUE)
-#' @param cells switch between "lpjcell" (67420) and "magpiecell" (59199)
-#' @param crops switch between "magpie" and "lpjml" (default) crops
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier
-#'
-#' @examples
-#' \dontrun{ calcOutput("IrrigYieldImprovementPotential", aggregate=FALSE) }
-#'
-#' @import madrat
-#' @import magclass
-
-calcIrrigYieldImprovementPotential <- function(version="LPJmL5", climatetype="HadGEM2_ES:rcp2p6:co2", time="spline", averaging_range=NULL, dof=4,
- harmonize_baseline=FALSE, ref_year=NULL, selectyears=seq(1995, 2095,by=5), cells="magpiecell", crops="lpjml"){
-
- # read in yields [in tons/ha]
- yields <- calcOutput("Yields", version=version, climatetype=climatetype, selectyears=selectyears, crops=crops,
- time=time, dof=dof, averaging_range=averaging_range, harmonize_baseline=harmonize_baseline, ref_year=ref_year, aggregate=FALSE)
-
- # yield gap (irrigated vs. rainfed) [in tons/ha]
- tmp <- collapseNames(yields[,,"irrigated"])-collapseNames(yields[,,"rainfed"])
- # (Note: under N-stress, irrigation may lead to lower yields; also: irrigation may lead to shift in growing period -> tmp can have negative values)
-
- # cellular dimension
- if (cells=="magpiecell") {
- yield_gain <- tmp
- } else if (cells=="lpjcell") {
- lpj_cells_map <- toolGetMapping("LPJ_CellBelongingsToCountries.csv", type="cell")
- getCells(tmp) <- paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep=".")
- yield_gain <- new.magpie(1:67420,getYears(tmp),getNames(tmp))
- yield_gain[,,] <- 0
- yield_gain[paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep="."),,] <- tmp[,,]
- getCells(yield_gain) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- } else {
- stop("Cells argument not supported. Please select lpjcell for 67420 cells or magpiecell for 59199 cells")
- }
-
- # Check for NAs
- if(any(is.na(yield_gain))){
- stop("Function YieldImprovementPotential produced NAs")
- }
-
- return(list(
- x=yield_gain,
- weight=NULL,
- unit="tons per ha",
- description="Yield improvement potential by irrigation for different crop types.",
- isocountries=FALSE))
-}
diff --git a/R/calcIrrigatedArea.R b/R/calcIrrigatedArea.R
deleted file mode 100644
index 3982265c6..000000000
--- a/R/calcIrrigatedArea.R
+++ /dev/null
@@ -1,74 +0,0 @@
-#' @title calcIrrigatedArea
-#' @description calculates area reserved for irrigation based on area irrigated in initialization year and depreciation parameter
-#'
-#' @param iniyear initialization year
-#' @param selectyears select years
-#' @param depreciation parameter defining yearly depreciation rate at which previously irrigated cropland becomes "unreserved" for irrigation
-#' @param cells cells to be returned by the function (lpjcell or magpiecell)
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier
-#'
-#' @examples
-#' \dontrun{ calcOutput("IrrigatedArea", aggregate=FALSE) }
-#'
-#' @import magclass
-#' @import magpiesets
-
-calcIrrigatedArea <- function(selectyears=seq(1995,2100,by=5), iniyear=1995, depreciation=0.1, cells="lpjcell"){
-
- # Read in data: crop- and water supply type specific crop area (in Mha) in initialization year:
- tmp <- calcOutput("Croparea", years=iniyear, sectoral="kcr", cells="magpiecell", physical=TRUE, cellular=TRUE, irrigation=TRUE, aggregate=FALSE)
- # Retrieve irrigated area (per crop)
- tmp <- collapseNames(tmp[,,"irrigated"])
-
- # Empty object to be filled with area reserved for irrigation in current and future time steps
- irrig_area <- new.magpie(getCells(tmp),selectyears,getNames(tmp))
-
- # Each year certain share (parameter: "depreciation") of irrigated cropland is lost
- for (y in (1:length(selectyears))){
- # irrigated area in respective year
- irrig_area[,selectyears[y],] <- tmp
- # adjust yearly depreciation rate to time steps
- timegap <- selectyears[y+1]-selectyears[y]
- dep_adj <- (1-depreciation)^timegap
- # depreciation of irrigated area
- tmp <- tmp*dep_adj
- }
-
- # Corrections
- # years
- if(selectyears!="all"){
- years <- sort(findset(selectyears,noset="original"))
- irrig_area <- irrig_area[,years,]
- }
-
- # number of cells
- if (cells=="magpiecell") {
- out <- irrig_area
- } else if (cells=="lpjcell") {
- lpj_cells_map <- toolGetMapping("LPJ_CellBelongingsToCountries.csv", type="cell")
- getCells(irrig_area) <- paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep=".")
- out <- new.magpie(1:67420,getYears(irrig_area),getNames(irrig_area))
- out[,,] <- 0
- out[paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep="."),,] <- irrig_area[,,]
- getCells(out) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- } else {
- stop("Cells argument not supported. Please select lpjcell for 67420 cells or magpiecell for 59199 cells")
- }
-
- # check for NAs and negative values
- if(any(is.na(out))){
- stop("produced NA irrigation water requirements")
- }
- if(any(out<0)){
- stop("produced negative irrigation water requirements")
- }
-
- return(list(
- x=out,
- weight=NULL,
- unit="mio. ha",
- description="Cropland area reserved for irrigation per crop",
- isocountries=FALSE))
-}
diff --git a/R/calcIrrigationSystem.R b/R/calcIrrigationSystem.R
deleted file mode 100644
index d64c6104d..000000000
--- a/R/calcIrrigationSystem.R
+++ /dev/null
@@ -1,72 +0,0 @@
-#' @title calcIrrigationSystem
-#' @description This function returns the irrigation system share initialization
-#'
-#' @param source Data source to be used: Jaegermeyr (irrigation system share based on FAO 2014, ICID 2012 and Rohwer et al. 2007) or LPJmL (dominant irrigation system per country) and number of cells (lpjcell or magpiecell) separated by _
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier
-#'
-#' @examples
-#' \dontrun{ calcOutput("IrrigationSystem",source="Jaegermeyr_lpjcell",aggregate = FALSE) }
-#'
-#' @import magclass
-
-calcIrrigationSystem <- function(source="Jaegermeyr_lpjcell"){
-
- # Jägermeyr et al. (2015): Shares of surface, sprinkler and drip irrigated areas
- # (Note: compiled from FAO (2014), ICID (2012), Rohwer et al. (2007))
- if (grepl("Jaegermeyr", source)){
-
- # Read in source
- x <- readSource("IrrigationSystem", convert="onlycorrect", subtype=source)
- getNames(x) <- gsub("shr_AEI_","",getNames(x))
- }
-
- # Irrigation functional type (IFT) from LPJmL representing the dominant irrigation system per country
- # (Note: share of 100% of dominant system assumed)
- if (grepl("LPJmL", source)){
-
- # Read in source
- tmp <- readSource("IrrigationSystem", convert="onlycorrect", subtype=source)
-
- # Merge to obtain one magpie object containing irrigation system shares (share of irrigated area per irrigation system)
- x <- new.magpie(cells_and_regions=getCells(tmp),years=NULL,names=c("surface","sprinkler","drip"),fill=0)
-
- # Surface is dominant system:
- x[,,"surface"][tmp==1] <- 1
- x[,,"sprinkler"][tmp==1] <- 0
- x[,,"drip"][tmp==1] <- 0
-
- # Sprinkler is dominant system:
- x[,,"surface"][tmp==2] <- 0
- x[,,"sprinkler"][tmp==2] <- 1
- x[,,"drip"][tmp==2] <- 0
-
- # Drip is dominant system
- x[,,"surface"][tmp==3] <- 0
- x[,,"sprinkler"][tmp==3] <- 0
- x[,,"drip"][tmp==3] <- 1
- }
-
- # When all three shares are 0, it is assumed that 100% of irrigated land (if any exists) is surface irrigation
- x[,,"surface"][which(x[,,"surface"]==0 & x[,,"sprinkler"]==0 & x[,,"drip"]==0)] <- 1
-
- # dimension names
- getSets(x)[c(1,2)] <- c("iso","cell")
- getSets(x)[4] <- "system"
-
- # Checks
- if(any(is.na(x))){
- stop("produced NA irrigation system share")
- }
- if (any(round(dimSums(x, dim=3))!=1)){
- stop("sum over shares not equal to 1")
- }
-
- return(list(
- x=x,
- weight=NULL,
- unit="1",
- description="irrigation system share (share of irrigated area)",
- isocountries=FALSE))
-}
diff --git a/R/calcWaterAllocation.R b/R/calcWaterAllocation.R
deleted file mode 100644
index 32845e719..000000000
--- a/R/calcWaterAllocation.R
+++ /dev/null
@@ -1,516 +0,0 @@
-#' @title calcWaterAllocation
-#' @description This function calculates water availability for MAgPIE retrieved from LPJmL using a river routing and allocation algorithm for distribution of discharge within the river basin
-#'
-#' @param version Switch between LPJmL4 and LPJmL5
-#' @param climatetype Switch between different climate scenarios (default: "CRU_4")
-#' @param time Time smoothing: average, spline or raw (default)
-#' @param averaging_range only specify if time=="average": number of time steps to average
-#' @param dof only specify if time=="spline": degrees of freedom needed for spline
-#' @param harmonize_baseline FALSE (default): no harmonization, TRUE: if a baseline is specified here data is harmonized to that baseline (from ref_year on)
-#' @param ref_year Reference year for harmonization baseline (just specify when harmonize_baseline=TRUE)
-#' @param selectyears Years to be returned
-#' @param output Water availability output to be returned: withdrawal or consumption
-#' @param allocationrule Rule to be applied for river basin discharge allocation across cells of river basin ("optimization" (default), "upstreamfirst", "equality")
-#' @param allocationshare Share of water to be allocated to cell (only needs to be selected in case of allocationrule=="equality")
-#' @param gainthreshold Threshold of yield improvement potential required for water allocation in upstreamfirst algorithm (in tons per ha)
-#' @param irrigationsystem Irrigation system to be used for river basin discharge allocation algorithm ("surface", "sprinkler", "drip", "initialization")
-#' @param irrigini When "initialization" selected for irrigation system: choose initialization data set for irrigation system initialization ("Jaegermeyr_lpjcell", "LPJmL_lpjcell")
-#'
-#' @import magclass
-#' @import madrat
-#' @importFrom mrcommons toolHarmonize2Baseline
-#'
-#' @return magpie object in cellular resolution
-#' @author Felicitas Beier, Jens Heinke
-#'
-#' @examples
-#' \dontrun{ calcOutput("WaterAllocation", aggregate = FALSE) }
-#'
-
-calcWaterAllocation <- function(selectyears="all", output="consumption",
- version="LPJmL4", climatetype="HadGEM2_ES:rcp2p6:co2", time="raw", averaging_range=NULL, dof=NULL,
- harmonize_baseline=FALSE, ref_year="y2015",
- allocationrule="optimization", allocationshare=NULL, gainthreshold=1,
- irrigationsystem="initialization", irrigini="Jaegermeyr_lpjcell"){
-
- #############################
- ####### Read in Data ########
- #############################
-
- ### Read in river structure
- # Note: river structure derived from LPJmL input (drainage) [maybe later: implement readDrainage function]
- data <- toolGetMapping("River_structure_stn.rda",type="cell")
- for (i in 1:length(data)){
- assign(paste(names(data[[i]])), data[[i]][[1]])
- }
- rm(data,i)
-
- # Number of cells to be used for calculation
- NCELLS <- length(calcorder)
-
- ### LPJ-MAgPIE cell mapping
- magpie2lpj <- magclassdata$cellbelongings$LPJ_input.Index
- lpj_cells_map <- toolGetMapping("LPJ_CellBelongingsToCountries.csv", type="cell")
-
- ### Required inputs for River Routing:
- # Yearly runoff (mio. m^3 per yr) [smoothed & harmonized]
- yearly_runoff <- calcOutput("LPJmL", version="LPJmL4", selectyears=selectyears, climatetype=climatetype, subtype="runoff_lpjcell", aggregate=FALSE,
- harmonize_baseline=harmonize_baseline, ref_year=ref_year, time=time, dof=dof, averaging_range=averaging_range)
- yearly_runoff <- as.array(collapseNames(yearly_runoff))
- yearly_runoff <- yearly_runoff[,,1]
- years <- getYears(yearly_runoff)
-
- # Yearly lake evapotranspiration (in mio. m^3 per year) [smoothed & harmonized]
- lake_evap <- calcOutput("LPJmL", version="LPJmL4", selectyears=selectyears, climatetype=climatetype, subtype="evap_lake_lpjcell", aggregate=FALSE,
- harmonize_baseline=harmonize_baseline, ref_year=ref_year, time=time, dof=dof, averaging_range=averaging_range)
- lake_evap <- as.array(collapseNames(lake_evap))
- lake_evap <- lake_evap[,,1]
-
- # Precipitation/Runoff on lakes and rivers from LPJmL (in mio. m^3 per year) [smoothed & harmonized]
- input_lake <- calcOutput("LPJmL", version="LPJmL4", selectyears=selectyears, climatetype=climatetype, subtype="input_lake_lpjcell", aggregate=FALSE,
- harmonize_baseline=harmonize_baseline, ref_year=ref_year, time=time, dof=dof, averaging_range=averaging_range)
- input_lake <- as.array(collapseNames(input_lake))
- input_lake <- input_lake[,,1]
-
- # runoff (on land and water)
- yearly_runoff <- yearly_runoff + input_lake
-
- # Non-Agricultural Water Withdrawals (in mio. m^3 / yr) [smoothed]
- NAg_ww_magpie <- calcOutput("WaterUseNonAg", source="WATERGAP2020", selectyears=selectyears, time=time, dof=dof, averaging_range=averaging_range, waterusetype="withdrawal", seasonality="total", aggregate=FALSE)
- getCells(NAg_ww_magpie) <- paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep=".")
- NAg_ww <- new.magpie(1:NCELLS,getYears(NAg_ww_magpie),getNames(NAg_ww_magpie))
- NAg_ww[,,] <- 0
- NAg_ww[paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep="."),,] <- NAg_ww_magpie[,,]
- getCells(NAg_ww) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- NAg_ww <- as.array(collapseNames(NAg_ww))
- rm(NAg_ww_magpie)
-
- # Non-Agricultural Water Consumption (in mio. m^3 / yr) [smoothed]
- NAg_wc_magpie <- calcOutput("WaterUseNonAg", source="WATERGAP2020", selectyears=selectyears, time=time, dof=dof, averaging_range=averaging_range, waterusetype="consumption", seasonality="total", aggregate=FALSE)
- getCells(NAg_wc_magpie) <- paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep=".")
- NAg_wc <- new.magpie(1:NCELLS,getYears(NAg_wc_magpie),getNames(NAg_wc_magpie))
- NAg_wc[,,] <- 0
- NAg_wc[paste("GLO",magclassdata$cellbelongings$LPJ_input.Index,sep="."),,] <- NAg_wc_magpie[,,]
- getCells(NAg_wc) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- NAg_wc <- as.array(collapseNames(NAg_wc))
- rm(NAg_wc_magpie)
-
- # Harmonize non-agricultural consumption and withdrawals (withdrawals > consumption)
- NAg_ww <- pmax(NAg_ww, NAg_wc)
- NAg_wc <- pmax(NAg_wc, 0.01*NAg_ww)
-
- # Committed agricultural uses (in mio. m^3 / yr) [for initialization year]
- CAU_magpie <- calcOutput("WaterUseCommittedAg",selectyears=selectyears,iniyear=1995,irrigini="Jaegermeyr_lpjcell",time="raw",dof=NULL,aggregate=FALSE)
- CAW_magpie <- as.array(collapseNames(dimSums(CAU_magpie[,,"withdrawal"],dim=3)))
- CAC_magpie <- as.array(collapseNames(dimSums(CAU_magpie[,,"consumption"],dim=3)))
- rm(CAU_magpie)
- CAW_magpie <- as.array(collapseNames(CAW_magpie))
- CAW_magpie <- CAW_magpie[,,1]
- CAC_magpie <- as.array(collapseNames(CAC_magpie))
- CAC_magpie <- CAC_magpie[,,1]
-
- ### Required inputs for Allocation Algorithm:
- # Required water for full irrigation per cell (in mio. m^3)
- required_wat_fullirrig_ww <- calcOutput("FullIrrigationRequirement", version="LPJmL5", selectyears=seq(1995, 2095,by=5), climatetype="HadGEM2_ES:rcp2p6:co2", harmonize_baseline=FALSE, time="spline", dof=4, iniyear=1995, iniarea=TRUE, irrig_requirement="withdrawal", cells="lpjcell", aggregate=FALSE)[,,c("maiz","rapeseed","puls_pro")]
- required_wat_fullirrig_ww <- pmax(required_wat_fullirrig_ww,0)
- required_wat_fullirrig_wc <- calcOutput("FullIrrigationRequirement", version="LPJmL5", selectyears=seq(1995, 2095,by=5), climatetype="HadGEM2_ES:rcp2p6:co2", harmonize_baseline=FALSE, time="spline", dof=4, iniyear=1995, iniarea=TRUE, irrig_requirement="consumption", cells="lpjcell", aggregate=FALSE)[,,c("maiz","rapeseed","puls_pro")]
- required_wat_fullirrig_wc <- pmax(required_wat_fullirrig_wc,0)
-
- # Full irrigation water requirement depending on irrigation system in use
- if (irrigationsystem=="initialization") {
- # read in irrigation system area initialization [share of AEI by system]
- tmp <- calcOutput("IrrigationSystem", source=irrigini, aggregate=FALSE)
- irrigation_system <- new.magpie(getCells(tmp), getYears(required_wat_fullirrig_ww), getNames(tmp))
- getYears(irrigation_system) <- getYears(required_wat_fullirrig_ww)
- for (y in getYears(required_wat_fullirrig_ww)) {
- irrigation_system[,y,] <- tmp
- }
- # full irrigation water requirements (in mio. m^3)
- required_wat_fullirrig_ww <- dimSums(irrigation_system*required_wat_fullirrig_ww,dim=3.1)
- required_wat_fullirrig_wc <- dimSums(irrigation_system*required_wat_fullirrig_wc,dim=3.1)
- } else {
- # whole area irrigated by one system as selected in argument "irrigationsystem"
- required_wat_fullirrig_ww <- collapseNames(required_wat_fullirrig_ww[,,irrigationsystem])
- required_wat_fullirrig_wc <- collapseNames(required_wat_fullirrig_wc[,,irrigationsystem])
- }
- # average required water for full irrigation across selected proxy crops
- required_wat_fullirrig_ww <- dimSums(required_wat_fullirrig_ww,dim=3)/length(getNames(required_wat_fullirrig_ww))
- required_wat_fullirrig_wc <- dimSums(required_wat_fullirrig_wc,dim=3)/length(getNames(required_wat_fullirrig_wc))
-
- # transform to array for further calculations
- required_wat_fullirrig_ww <- as.array(collapseNames(required_wat_fullirrig_ww))[,,1]
- required_wat_fullirrig_wc <- as.array(collapseNames(required_wat_fullirrig_wc))[,,1]
-
- # Global cell rank based on yield gain potential by irrigation of proxy crops: maize, rapeseed, pulses
- meancellrank <- calcOutput("IrrigCellranking", version="LPJmL5", climatetype="HadGEM2_ES:rcp2p6:co2", time="spline", averaging_range=NULL, dof=4, harmonize_baseline=FALSE, ref_year="y2015",
- cellrankyear=seq(1995, 2095,by=5), cells="lpjcell", crops="magpie", method="meancroprank", proxycrop=c("maiz", "rapeseed", "puls_pro"), aggregate=FALSE)
- meancellrank <- as.array(meancellrank)[,,1]
-
-
- ############################################
- ####### Routing and Allocation Loop ########
- ############################################
- out_tmp1 <- NULL
- out_tmp2 <- NULL
- out <- NULL
-
- for (EFP in c("on", "off")) {
-
- # Environmental Flow Requirements (in mio. m^3 / yr) [long-term average]
- if (EFP=="on"){
- EFR_magpie <- calcOutput("EnvmtlFlowRequirements", version="LPJmL4", climatetype=climatetype, aggregate=FALSE, cells="lpjcell",
- LFR_val=0.1, HFR_LFR_less10=0.2, HFR_LFR_10_20=0.15, HFR_LFR_20_30=0.07, HFR_LFR_more30=0.00,
- EFRyears=c(1980:2010))
- } else if (EFP=="off"){
- EFR_magpie <- new.magpie(1:NCELLS,fill=0)
- getCells(EFR_magpie) <- paste(lpj_cells_map$ISO,1:67420,sep=".")
- }
- EFR_magpie <- as.array(collapseNames(EFR_magpie))
- EFR_magpie <- EFR_magpie[,1,1]
-
- for (scen in c("ssp1","ssp2","ssp3")){
- for (y in selectyears){
-
- #############################
- ####### River routing #######
- #############################
-
- ## Global river routing variables
- # Naturalized discharge
- discharge_nat <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- inflow_nat <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- lake_evap_new <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- # Discharge considering human uses
- discharge <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- inflow <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- avl_wat_act <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- # Water fractions reserved for certain uses
- frac_NAg_fulfilled <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- frac_CAg_fulfilled <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- frac_fullirrig <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
- required_wat_min <- array(data=0,dim=NCELLS,dimnames=list(names(EFR_magpie)))
-
- ### River Routing 1.1: Natural flows ###
- # Determine natural discharge
- for (o in 1:max(calcorder)){
- # Note: the calcorder ensures that upstreamcells are calculated first
- cells <- which(calcorder==o)
-
- for (c in cells){
- ### Natural water balance
- # lake evap that can be fulfilled (if water available: lake evaporation considered; if not: lake evap is reduced respectively):
- lake_evap_new[c] <- min(lake_evap[c,y], inflow_nat[c]+yearly_runoff[c,y])
- # natural discharge
- discharge_nat[c] <- inflow_nat[c] + yearly_runoff[c,y] - lake_evap_new[c]
- # inflow into nextcell
- if (nextcell[c]>0){
- inflow_nat[nextcell[c]] <- inflow_nat[nextcell[c]] + discharge_nat[c]
- }
- }
- }
-
- # Minimum availability of water in river to fulfill local EFRs
- required_wat_min <- EFR_magpie
-
- ### River Routing 2: Non-agricultural uses considering local EFRs ###
- for (o in 1:max(calcorder)) {
- # Note: the calcorder ensures that the upstreamcells are calculated first
- cells <- which(calcorder==o)
-
- for (c in cells){
- # available water in cell
- avl_wat_act[c] <- inflow[c]+yearly_runoff[c,y]-lake_evap_new[c]
-
- # available water in cell not sufficient to fulfill requirements
- # -> no more water can be withdrawn
- if (avl_wat_act[c]