# create grid of homogenous soil moisture
#!! To prevent implausible values, soil moisture is specified in relative saturation.
# Therefore, this script needs to access a grid of bulk densities (variable "bd_grid", generated in "soil_physics") ####
# Till Francke, Apr 2023
# set working directory to source file location ####
rm(list=ls())
if (!require("rstudioapi", quietly = TRUE)) install.packages("rstudioapi")
require(rstudioapi)
wd <- rstudioapi::getActiveDocumentContext()$path
wd <- sub(x=wd, pattern="(.*/)[^/]+$","\\1")
setwd(wd)
# settings ####
source("../../../../settings/settings.R") #load desired extents
#patternfile = "../../../patterns/hexland_tracks/pre_processed/pattern.shp" #file holding (hexagonal) pattern (with tracks)
patternfile = "../../../patterns/hexland/pre_processed/pattern.shp" #file holding (hexagonal) pattern
dest_dir = sub(dirname(patternfile), pattern = "patterns/([^/]*)", replacement = "SM_distribution/\\1")  #destination directory to store the outputs
dest_dir
dest_dir = "../../../SM_distribution/homogenous_10/pre_processed"  #destination directory to store the outputs
bd_grid = "../../../soil_physics/hexland/pre_processed/soil_physics_3D.nc"
compartment_boundaries_reduced = list("soil_moisture"=c(-2, 0))
#zmin = -2 #lower boundary of lowermost layer to create
n_z = length(compartment_boundaries_reduced$soil_moisture)-1
library(ncdf4)
find_match = function(bounds, lvalue, uvalue) #for finding matching layers
return(match(x = TRUE, table = (bounds <= lvalue) & (c(bounds[-1], Inf) >= uvalue)))
# load 2D-grid of bulk density from soil physics compartment, expand to 3D grid ####
#compartment_boundaries_reduced = list()
nc = nc_open(filename = bd_grid)
bulk_density_raw = ncvar_get(nc=nc, varid = "bulk_density", collapse_degen = FALSE) #load content of NetCDF into array
porosity_raw     = ncvar_get(nc=nc, varid = "porosity",     collapse_degen = FALSE) #load content of NetCDF into array
zmin_bd         = ncvar_get(nc=nc, varid = "zmin", collapse_degen = TRUE) #load content of NetCDF into array
if (zmin_bd != compartment_boundaries_reduced$soil_moisture[1])
stop("Non-equal values of zmin for soil-moisture and bulk density. Adjust either.")
compartment_boundaries_reduced[["bulk_density"]] = c(zmin_bd, nc$dim$z$vals) #get boundaries from netcdf-file
nc_close(nc)
non_concommittant_boundaries = setdiff(compartment_boundaries_reduced[["bulk_density"]], compartment_boundaries_reduced[["soil_moisture"]])
if (length(non_concommittant_boundaries)>0)
stop("Non-concommittant boundaries between soil moisture and bulk density. Adjust either.")
#create bulk density grid according to vertical resolution specified above
bulk_density = array(NA, dim = c(dim(bulk_density_raw)[1:2], n_z))
porosity = bulk_density #create equally-sized array
for (i in 1:n_z)
{
lower_bound = compartment_boundaries_reduced$soil_moisture[i  ]
upper_bound = compartment_boundaries_reduced$soil_moisture[i+1]
ix = find_match(lvalue = lower_bound,
uvalue = upper_bound,
bounds = compartment_boundaries_reduced[["bulk_density"]])
if (is.na(ix) | ix == -1)
stop("Couldn't transfer bulk density grid to resolution of desired soil_moisture grid.")
bulk_density[,, i] = bulk_density_raw[,,ix]
porosity[,, i]     = porosity_raw[,,ix]
}
if (sum(is.na(bulk_density)) != 0)
stop("NAs found in bulk density grid.")
if (sum(is.na(porosity)) != 0)
stop("NAs found in porosity grid.")
upper_bounds = compartment_boundaries_reduced$soil_moisture[-1] #set upper limit(s) of layers
n_z = length(upper_bounds)
zmin=compartment_boundaries_reduced$soil_moisture[1] #lower boundary of lowest layer
# create 3D-grid
rel_sat = array(NA, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
code_matrix = rel_sat[,,1] #2-D matrix of IDs
rel_sat_all = 0.1 #relative saturation to assign [-]
# create 3D-grid
rel_sat = array(rel_sat_all, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
theta_vol = porosity * rel_sat   #compute volumetric water contents [cm3/cm3]
range(theta_vol)
print("range of vlumetric water content:")
prnt(range(theta_vol))
if (max(theta_vol) > 0.85)
warning(paste0("Requested soil moisture values result in up to ", max(theta_vol), ", which will be truncated at URANOS' maximum at 0.85" ))
if (min(theta_vol) < 0.01)
warning(paste0("Requested soil moisture values result in down to ", min(theta_vol), ", which will be truncated at URANOS' minimum at 0.01" ))
range(bulk_density)
print("range of bulk density:")
range(bulk_density)
material_codes = theta_vol*100 * 2
#!code 100 is for variable soil moisture (from GUI)
material_codes[ceiling(material_codes) == 100] = 99
material_codes[floor  (material_codes) == 100] = 101
#material_codes = as.integer(material_codes)  #inadvertently converts to vector
storage.mode(material_codes) <- "integer" #convert to integer, preserve shape of array
#2...170 = Soil with predefined Soil Moisture of 1...85 %Vol (= value/2)
material_codes = pmin(material_codes, 170L)  #URANOS material codes: soil moisture is encoded via these IDs
material_codes = pmax(material_codes, 2L)  #URANOS material codes: soil moisture is encoded via these IDs
# Define spatial dimensions of netcdf. These are the upper boundaries of the layers
dim_x <- ncdim_def(name = "x", units = "m", vals = 1:n_x )
dim_y <- ncdim_def(name = "y", units = "m", vals = 1:n_y )
dim_z <- ncdim_def(name = "z", units = "m", vals = upper_bounds)
n_z = length(dim_z$vals)
dim_zmin <- ncdim_def(name = "zmin_", units = "m", vals = zmin) #this is for the lower boundary of the lowermost layer
# 3D-grid
#define variable
varZmin       <- ncvar_def(name = "zmin", units = "m",
dim= list(dim_zmin), prec="float")
varMaterial <- ncvar_def(name = "material_id", units = "id",
dim= list(dim_y, dim_x, dim_z), compression = 1,
longname="material_id", prec="short", missval = 255)
# Create a netCDF file with this variable
ncnew <- nc_create( paste0(dest_dir, "/SM_distribution_3D.nc"), list(varMaterial, varZmin))
nc_close(ncnew)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/homogenous_dry/raw/generate__soil_moisture.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/homogenous_dry/raw/generate__soil_moisture.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/homogenous_dry/raw/generate__soil_moisture.R", echo=TRUE)
dest_dir
paste0(dest_dir, "/SM_distribution_3D.nc")
getwd()
setwd("E:/till/uni/crns/vJFC/0_compartments/relief/realistic/raw")
