plot(r2, main="material_codes (ground layer)") #correct
r2 = raster(material_codes[,,ground_layer],  xmn=1, xmx=x_extent, ymn=y_extent, ymx=1)
image(material_codes[,,ground_layer])
r2[1:3,]=150
image(r2)
image(material_codes[,,ground_layer])
plot(r2, main="material_codes (ground layer)") #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE) #correct
plot(r2, main="material_codes (ground layer)", axes=1) #correct
plot(r2, main="material_codes (ground layer)", axes="x") #correct
plot(r2, main="material_codes (ground layer)", axes=2) #correct
plot(r2, main="material_codes (ground layer)", axes=3) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE) #correct
axis(side = 1)
axis(side = 2)
plot(r2, main="material_codes (ground layer)", axes=FALSE) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE, ylim=c(1000,1)) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE, ylims=c(1000,1)) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE, ylim=c(1,100)) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE, ylim=c(1,1000)) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE, ylim=rev(c(1,1000))) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE, ylim=rev(c(1,1000))) #correct
image(r2)
plot(r2, main="material_codes (ground layer)", axes=FALSE, ylim=rev(c(1,1000))) #correct
plot(r2, main="material_codes (ground layer)", axes=FALSE) #correct
raster::plot(r2, main="material_codes (ground layer)", axes=FALSE) #correct
r2
r3 = raster(flip(material_codes[,,ground_layer], direction=vertical),  xmn=1, xmx=x_extent, ymn=1, ymx=y_extent)
terra::plot(r2, main="material_codes (ground layer)", axes=FALSE) #correct
terra::plot(flip(r2, direction="vertical"), main="material_codes (ground layer)", axes=FALSE) #correct
terra::plot(flip(r2, direction="y"), main="material_codes (ground layer)", axes=FALSE) #correct
terra::plot(flip(r2, direction="y"), main="material_codes (ground layer)", axes=TRUE) #correct
y_extent
terra::plot(r2, main="material_codes (ground layer)", axes=FALSE) #correct
terra::plot(flip(r2, direction="y"), main="material_codes (ground layer)", axes=TRUE) #correct
terra::plot(flip(r2, direction="y"), main="material_codes (ground layer)", axes=TRUE, ylim=c(1,10)) #correct
terra::plot(flip(r2, direction="y"), main="material_codes (ground layer)", axes=TRUE, ylim=c(10,1)) #correct
terra::plot(r2, main="material_codes (ground layer)", axes=TRUE, xlab="x [m]",  ylab="y [m]") #correct
tticks = seq(from=0, t0=1000, by=100)
tticks = seq(from=0, to=1000, by=100)
axis(side = 3, at=tticks, labels=tticks)
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=tticks, labels=rev(tticks))
# Define spatial dimensions of netcdf. These are the upper boundaries of the layers
y_ = n_y:1 #y-axis points towards north, so it is reversed here
y_
at = seq(from=0, to=1000, by=200)
ticksx = at
ticksy = seq(from=y_[1], to=y_[1], length.out=length(at))
ticksx
ticksy
ticksy = seq(from=y_[1], to=y_[length(y_)], length.out=length(at))
ticksy
at = seq(from=1, to=1000, by=200)
ticksx = at
ticksy = seq(from=y_[1], to=y_[length(y_)], length.out=length(at))
ticksy
length.out=length(at)
at = seq(from=1, to=1000, by=200)
ticksx = at
ticksy = seq(from=y_[1], to=y_[length(y_)], length.out=length(at))
ticksy
ticksx
at
at = seq(from=0, to=1000, by=200)
ticksx = at
at
ticksy = seq(from=y_[1], to=y_[length(y_)], length.out=length(at))
ticksy
ticksy = seq(from=y_[1]-1, to=y_[length(y_)], length.out=length(at))
ticksy
y_[1]
y_[length(y_)]
ticksy = seq(from=y_[1], to=y_[length(y_)]-1, length.out=length(at))
ticksy
terra::plot(r2, main="material_codes (ground layer)", axes=TRUE, xlab="x [m]",  ylab="y [m]") #correct
at = seq(from=0, to=1000, by=200)
ticksx = at
ticksy = seq(from=y_[1], to=y_[length(y_)]-1, length.out=length(at))
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=at, labels=tticksy)
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=at, labels=ticksy)
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=at, labels=ticksy, tick = "y [index]")
terra::plot(r2, main="material_codes (ground layer)", axes=TRUE, xlab="x [m]",  ylab="y [m]") #correct
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=at, labels=ticksy, tick = "y [index]")
par(mar=c(5,4,4,2) + 0.1)
terra::plot(r2, main="material_codes (ground layer)", axes=TRUE, xlab="x [m]",  ylab="y [m]") #correct
par(mar=c(3,4,4,2) + 0.1)
terra::plot(r2, main="material_codes (ground layer)", axes=TRUE, xlab="x [m]",  ylab="y [m]") #correct
par(mar=c(5,4,4,5) + 0.1)
terra::plot(r2, main="material_codes (ground layer)", axes=TRUE, xlab="x [m]",  ylab="y [m]") #correct
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=at, labels=ticksy, tick = "y [index]")
mtext("y [index]", sige=4)
mtext("y [index]", side=4)
mtext("y [index]", side=4, line = 2)
par(mar=c(5,4,4,5) + 0.1)
terra::plot(r2, main="material_codes (ground layer)", axes=TRUE, xlab="x [m]",  ylab="y [m]") #correct
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=at, labels=ticksy)
mtext("y [index]", side=4, line = 2)
r2 = raster(theta_vol[,,ground_layer], xmn=1, xmx=x_extent, ymn=1, ymx=y_extent)
plot(r2, main="soil moisture (ground layer)", xlab="x [m]",  ylab="y [m]") #correct
#axis(side = 3, at=tticks, labels=tticks)
axis(side = 4, at=at, labels=ticksy)
mtext("y [index]", side=4, line = 2)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/hexland_tracks/raw/generate_hexland_soil_moisture.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
setwd("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw")
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
#codes = read.table(paste0(src_dir, "/codes.txt"), sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
codes = read.table(codefile, sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
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)
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
getwd()
# 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
# #hexland
# patternfile        = "../../../patterns/hexland/./pattern.shp" #file holding (hexagonal) pattern without tracks
# patternfile_tracks = ""
# zmin=-2 #lower boundary of lowest layer
#hexland_tracks
patternfile        = "../../../patterns/hexland/./pattern.shp" #file holding (hexagonal) pattern without tracks
patternfile_tracks = "../../../patterns/hexland_tracks/./pattern.shp" #file holding pattern with tracks (leave blank, if not required)
zmin=-2 #lower boundary of lowest layer
codefile = "codes.txt" #codes and properties for the classes in the patternfile
# #hexland_tracks_0
# patternfile        = "../../../patterns/hexland/./pattern.shp" #file holding (hexagonal) pattern without tracks
# patternfile_tracks = "../../../patterns/hexland_tracks/./pattern.shp" #file holding pattern with tracks (leave blank, if not required)
# zmin=-2 #lower boundary of lowest layer
# codefile = "../../hexland_tracks_0/raw/codes.txt" #codes and properties for the classes in the patternfile
# dest_dir = "../../hexland_tracks_0/."
#
# #homogenous_1_2x4
# patternfile        = "../../../patterns/homogenous_1_2x4/./2" #instead of pattern, choose homogenous raster (class 2 (medium	sand))
# patternfile_tracks = ""
# zmin=-4 #lower boundary of lowest layer
# #homogenous_1_2x1
# patternfile        = "../../../patterns/homogenous_1_2x1/./2" #instead of pattern, choose homogenous raster (class 2 (medium	sand))
# patternfile_tracks = ""
# zmin=-1 #lower boundary of lowest layer
# #homogenous_1_2x1000
# patternfile        = "../../../patterns/homogenous_1_2x1000/./2" #instead of pattern, choose homogenous raster (class 2 (medium	sand))
# patternfile_tracks = ""
# zmin=-1000 #lower boundary of lowest layer
if (!exists("dest_dir"))
{
dest_dir_marker = ifelse(patternfile_tracks!="", patternfile_tracks, patternfile)
dest_dir = sub(dirname(dest_dir_marker), pattern = "patterns/([^/]*)", replacement = "soil_physics/\\1")  #destination directory to store the outputs
}
src_dir  = paste0(dirname(dest_dir), "/raw")  #destination directory to get the inputs the outputs
#library(rgeos)
require(sp)
library(sf)
library(raster)
library(fasterize)
#codes = read.table(paste0(src_dir, "/codes.txt"), sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
codes = read.table(codefile, sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
# define topology ####
if (!grepl(x=dest_dir,"/homogenous")) #load from polygons
{
pattern_poly = st_read(patternfile)
#plot(pattern_poly)
# convert to raster ####
#dx = 1 #resolution
#dy = 1
#dy=2
#ny=500
#pattern_rast = raster(pattern_poly, origin=0, layer=1, resolution=c(dx, dy))
rast_temp = raster(pattern_poly, origin=0, resolution=c(dy, dx))
pattern_rast = fasterize(sf=pattern_poly, field = "dens_om", raster = rast_temp)
} else #homogenous, define on the fly
{
#homog_class = as.numeric(sub(x = dest_dir, pattern = ".*/homogenous_(\\d)*.*", replacement = "\\1"))
homog_class = max(codes$ID, na.rm=TRUE)+1
#pattern_poly = data.frame(dens_om=homog_class) # to allow later steps in script, make fake vector layer
dens_val = sub(x = dest_dir, pattern = ".*/homogenous_([^xX]*).*", replacement = "\\1")
dens_val = as.numeric(sub(dens_val, pattern="_", repl="."))
codes[nrow(codes)+1,] = codes[nrow(codes)+1,] #add new row
codes$ID          [nrow(codes)] = homog_class #specify new homogenous class
codes$bulk_density[nrow(codes)] = dens_val #specify new homogenous class
#pattern_poly = data.frame(dens_om=homog_class) # to allow later steps in script, make fake vector layer
pattern_rast = raster(array(homog_class, c(n_y, n_x)), xmn=0, ymn=0, xmx=n_x-1, ymx=n_y-1)
}
#pattern_rast [100:105,] =2
#plot(pattern_rast) #correct
#image(pattern_rast) #correct
#image(as.matrix(pattern_rast)) #rotated 90 deg
#image(raster(as.matrix(pattern_rast))) #correct
# settings2 ####
source("../../../../settings/settings.R") #load desired extents
upper_bounds = 0 #set upper limit(s) of layers
n_z = length(upper_bounds)
# create 3D-grid
bulk_density = array(NA, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
#porosity = bulk_density #we skip porosity, as it is implicitly used via bulk_density
#code_matrix = matrix(pattern_rast@data@values, ncol=n_y) #2-D matrix of IDs in pattern-grid
code_matrix = as.matrix(pattern_rast) #2-D matrix of IDs in pattern-grid
#raster::image(code_matrix) #rotated by 90 deg ccw
# fill grid ####
for (code in codes$ID)
{
cur_row = which(code == codes$ID)
if (length(cur_row)==0) stop(paste0("ID ", cur_row, "not found in codes.txt."))
if (identical(codes$name[cur_row], "track")) next #will be treated separately below
{
#if (veg_height == 0) next #nothing to assign
#layers2assign = which(veg_height <= upper_bounds) #find layers to be assigned
layers2assign = is.finite(upper_bounds) #assign through all layers
cells2assign = which(code_matrix == code, arr.ind = TRUE)
bulk_density[cbind(cells2assign[,1], cells2assign[,2], layers2assign)] = codes$bulk_density[cur_row]
#porosity    [cbind(cells2assign[,1], cells2assign[,2], layers2assign)] = codes$porosity    [cur_row]
}
}
#treat "track"-cells
if (exists("patternfile_tracks") & patternfile_tracks != "") #are there tracks to be added?
{
codes = read.table(paste0(dirname(patternfile_tracks), "/../raw/codes.txt"), sep="\t", header=TRUE) #concrete definition of track-IDs
pattern_poly_tracks = st_read(patternfile_tracks) #load pattern with tracks
track_IDs = na.omit(unique(pattern_poly_tracks$tracktype)) #get all unique tracktypes, if any
pattern_rast = fasterize(sf=pattern_poly_tracks, field = "tracktype", raster = rast_temp)
#code_matrix = matrix(pattern_rast@data@values, ncol=n_y) #2-D matrix of IDs in pattern-grid
code_matrix = as.matrix(pattern_rast) #2-D matrix of IDs in pattern-grid
#codes$thickness..m.[1]=0.0
upper_bounds = sort(-(unique(c(0, codes$thickness..m.)))) #compute upper bounds of
#old_n_z = n_z
n_z = length(c(0, unique(codes$thickness..m.))) - 1
# enlarge 3D-grid to fit additional required number of layers due to tracks
tt = bulk_density #save first layer generated so far
bulk_density = array(NA, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
for (i in 1: n_z)
bulk_density[,, i] = tt
# tt = porosity #save first layer generated so far
# porosity = array(NA, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
#
# for (i in 1: n_z)
#   porosity[,, i] = tt
rm(tt) #discard saved copy
for (code in track_IDs)
{
cur_row = which(code == codes$ID)
if (length(cur_row)==0) stop(paste0("ID ", cur_row, "not found in track-codes.txt."))
{
thickness = codes$thickness..m.[cur_row]
if (thickness == 0) next #nothing to assign
cells2assign = which(code_matrix == code, arr.ind = TRUE)
layers2assign = which(-thickness < upper_bounds) #find layers to be assigned
#layers2assign = is.finite(upper_bounds) #assign through all layers
for (layer in layers2assign)
{
bulk_density[cbind(cells2assign[,1], cells2assign[,2], layer)] = codes$bulk_density[cur_row]
#porosity    [cbind(cells2assign[,1], cells2assign[,2], layer)] = codes$porosity    [cur_row]
}
}
}
}
for (code in codes$ID)
{
cur_row = which(code == codes$ID)
if (length(cur_row)==0) stop(paste0("ID ", cur_row, "not found in codes.txt."))
if (identical(codes$name[cur_row], "track")) next #will be treated separately below
{
#if (veg_height == 0) next #nothing to assign
#layers2assign = which(veg_height <= upper_bounds) #find layers to be assigned
layers2assign = is.finite(upper_bounds) #assign through all layers
cells2assign = which(code_matrix == code, arr.ind = TRUE)
bulk_density[cbind(cells2assign[,1], cells2assign[,2], layers2assign)] = codes$bulk_density[cur_row]
#porosity    [cbind(cells2assign[,1], cells2assign[,2], layers2assign)] = codes$porosity    [cur_row]
}
}
(exists("patternfile_tracks") & patternfile_tracks != "") #are there tracks to be added?
patternfile_tracks
codes = read.table(paste0(dirname(patternfile_tracks), "/../raw/codes.txt"), sep="\t", header=TRUE) #concrete definition of track-IDs
codes = read.table(paste0(dirname(patternfile_tracks), "/../raw/codes.txt"), sep="\t", header=TRUE) #concrete definition of track-IDs
paste0(dirname(patternfile_tracks), "/../raw/codes.txt")
getwd()
codes = read.table(paste0(dirname(patternfile_tracks), "/raw/codes.txt"), sep="\t", header=TRUE) #concrete definition of track-IDs
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
# create soil_physics grid from predesigned shapefile (i.e. hexland)
# set respective number of classes (e.g. three) of different dry bulk density from 0 to 1 m depth
# Till Francke, Feb 2024
# 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
#hexland
patternfile        = "../../../patterns/hexland/./pattern.shp" #file holding (hexagonal) pattern without tracks
patternfile_tracks = ""
zmin=-2 #lower boundary of lowest layer
codefile = "codes.txt" #codes and properties for the classes in the patternfile
# #hexland_tracks
# patternfile        = "../../../patterns/hexland/./pattern.shp" #file holding (hexagonal) pattern without tracks
# patternfile_tracks = "../../../patterns/hexland_tracks/./pattern.shp" #file holding pattern with tracks (leave blank, if not required)
# zmin=-2 #lower boundary of lowest layer
# codefile = "codes.txt" #codes and properties for the classes in the patternfile
# #hexland_tracks_0
# patternfile        = "../../../patterns/hexland/./pattern.shp" #file holding (hexagonal) pattern without tracks
# patternfile_tracks = "../../../patterns/hexland_tracks/./pattern.shp" #file holding pattern with tracks (leave blank, if not required)
# zmin=-2 #lower boundary of lowest layer
# codefile = "../../hexland_tracks_0/raw/codes.txt" #codes and properties for the classes in the patternfile
# dest_dir = "../../hexland_tracks_0/."
#
# #homogenous_1_2x4
# patternfile        = "../../../patterns/homogenous_1_2x4/./2" #instead of pattern, choose homogenous raster (class 2 (medium	sand))
# patternfile_tracks = ""
# zmin=-4 #lower boundary of lowest layer
# #homogenous_1_2x1
# patternfile        = "../../../patterns/homogenous_1_2x1/./2" #instead of pattern, choose homogenous raster (class 2 (medium	sand))
# patternfile_tracks = ""
# zmin=-1 #lower boundary of lowest layer
# #homogenous_1_2x1000
# patternfile        = "../../../patterns/homogenous_1_2x1000/./2" #instead of pattern, choose homogenous raster (class 2 (medium	sand))
# patternfile_tracks = ""
# zmin=-1000 #lower boundary of lowest layer
if (!exists("dest_dir"))
{
dest_dir_marker = ifelse(patternfile_tracks!="", patternfile_tracks, patternfile)
dest_dir = sub(dirname(dest_dir_marker), pattern = "patterns/([^/]*)", replacement = "soil_physics/\\1")  #destination directory to store the outputs
}
src_dir  = paste0(dirname(dest_dir), "/raw")  #destination directory to get the inputs the outputs
#library(rgeos)
require(sp)
library(sf)
library(raster)
library(fasterize)
#codes = read.table(paste0(src_dir, "/codes.txt"), sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
codes = read.table(codefile, sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
# define topology ####
if (!grepl(x=dest_dir,"/homogenous")) #load from polygons
{
pattern_poly = st_read(patternfile)
#plot(pattern_poly)
# convert to raster ####
#dx = 1 #resolution
#dy = 1
#dy=2
#ny=500
#pattern_rast = raster(pattern_poly, origin=0, layer=1, resolution=c(dx, dy))
rast_temp = raster(pattern_poly, origin=0, resolution=c(dy, dx))
pattern_rast = fasterize(sf=pattern_poly, field = "dens_om", raster = rast_temp)
} else #homogenous, define on the fly
{
#homog_class = as.numeric(sub(x = dest_dir, pattern = ".*/homogenous_(\\d)*.*", replacement = "\\1"))
homog_class = max(codes$ID, na.rm=TRUE)+1
#pattern_poly = data.frame(dens_om=homog_class) # to allow later steps in script, make fake vector layer
dens_val = sub(x = dest_dir, pattern = ".*/homogenous_([^xX]*).*", replacement = "\\1")
dens_val = as.numeric(sub(dens_val, pattern="_", repl="."))
codes[nrow(codes)+1,] = codes[nrow(codes)+1,] #add new row
codes$ID          [nrow(codes)] = homog_class #specify new homogenous class
codes$bulk_density[nrow(codes)] = dens_val #specify new homogenous class
#pattern_poly = data.frame(dens_om=homog_class) # to allow later steps in script, make fake vector layer
pattern_rast = raster(array(homog_class, c(n_y, n_x)), xmn=0, ymn=0, xmx=n_x-1, ymx=n_y-1)
}
#pattern_rast [100:105,] =2
#plot(pattern_rast) #correct
#image(pattern_rast) #correct
#image(as.matrix(pattern_rast)) #rotated 90 deg
#image(raster(as.matrix(pattern_rast))) #correct
# settings2 ####
source("../../../../settings/settings.R") #load desired extents
upper_bounds = 0 #set upper limit(s) of layers
n_z = length(upper_bounds)
# create 3D-grid
bulk_density = array(NA, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
#porosity = bulk_density #we skip porosity, as it is implicitly used via bulk_density
#code_matrix = matrix(pattern_rast@data@values, ncol=n_y) #2-D matrix of IDs in pattern-grid
code_matrix = as.matrix(pattern_rast) #2-D matrix of IDs in pattern-grid
#raster::image(code_matrix) #rotated by 90 deg ccw
# fill grid ####
for (code in codes$ID)
{
cur_row = which(code == codes$ID)
if (length(cur_row)==0) stop(paste0("ID ", cur_row, "not found in codes.txt."))
if (identical(codes$name[cur_row], "track")) next #will be treated separately below
{
#if (veg_height == 0) next #nothing to assign
#layers2assign = which(veg_height <= upper_bounds) #find layers to be assigned
layers2assign = is.finite(upper_bounds) #assign through all layers
cells2assign = which(code_matrix == code, arr.ind = TRUE)
bulk_density[cbind(cells2assign[,1], cells2assign[,2], layers2assign)] = codes$bulk_density[cur_row]
#porosity    [cbind(cells2assign[,1], cells2assign[,2], layers2assign)] = codes$porosity    [cur_row]
}
}
#treat "track"-cells
if (exists("patternfile_tracks") & patternfile_tracks != "") #are there tracks to be added?
{
codes = read.table(paste0(dirname(patternfile_tracks), "/raw/codes.txt"), sep="\t", header=TRUE) #concrete definition of track-IDs
pattern_poly_tracks = st_read(patternfile_tracks) #load pattern with tracks
track_IDs = na.omit(unique(pattern_poly_tracks$tracktype)) #get all unique tracktypes, if any
pattern_rast = fasterize(sf=pattern_poly_tracks, field = "tracktype", raster = rast_temp)
#code_matrix = matrix(pattern_rast@data@values, ncol=n_y) #2-D matrix of IDs in pattern-grid
code_matrix = as.matrix(pattern_rast) #2-D matrix of IDs in pattern-grid
#codes$thickness..m.[1]=0.0
upper_bounds = sort(-(unique(c(0, codes$thickness..m.)))) #compute upper bounds of
#old_n_z = n_z
n_z = length(c(0, unique(codes$thickness..m.))) - 1
# enlarge 3D-grid to fit additional required number of layers due to tracks
tt = bulk_density #save first layer generated so far
bulk_density = array(NA, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
for (i in 1: n_z)
bulk_density[,, i] = tt
# tt = porosity #save first layer generated so far
# porosity = array(NA, dim = c(n_y, n_x, n_z)) #x and y reversed because of matrix-raster conversion
#
# for (i in 1: n_z)
#   porosity[,, i] = tt
rm(tt) #discard saved copy
for (code in track_IDs)
{
cur_row = which(code == codes$ID)
if (length(cur_row)==0) stop(paste0("ID ", cur_row, "not found in track-codes.txt."))
{
thickness = codes$thickness..m.[cur_row]
if (thickness == 0) next #nothing to assign
cells2assign = which(code_matrix == code, arr.ind = TRUE)
layers2assign = which(-thickness < upper_bounds) #find layers to be assigned
#layers2assign = is.finite(upper_bounds) #assign through all layers
for (layer in layers2assign)
{
bulk_density[cbind(cells2assign[,1], cells2assign[,2], layer)] = codes$bulk_density[cur_row]
#porosity    [cbind(cells2assign[,1], cells2assign[,2], layer)] = codes$porosity    [cur_row]
}
}
}
}
#range(bulk_density[,,1], na.rm=F)
#range(bulk_density[,,2], na.rm=F)
#porosity = 1-(bulk_density/2.86) #compute porosity according to assumptions in URANOS (particle density of 2.86 g/cm3). Ignored for non-soil materials anyway
#porosity[is.na(porosity)] = 0 #default value
#save as netcdf ####
library(ncdf4)
# Define spatial dimensions of netcdf. These are the upper boundaries of the layers
y_ = n_y:1 #y-axis points towards north, so it is reversed here
dim_x <- ncdim_def(name = "x", units = "m", vals = 1:n_x )
dim_y <- ncdim_def(name = "y", units = "m", vals = 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
if (!dir.exists(dest_dir)) dir.create(dest_dir)
# 2D-grid
ground_layer = which(upper_bounds == 0)-1
#define variable
varBulkdensity <- ncvar_def(name = "dens", units = "g/cm3",
dim= list(dim_y, dim_x), compression=1,
longname="dens", prec="float")
# varPorosity <- ncvar_def(name = "porosity", units = "-",
#                             dim= list(dim_y, dim_x), compression=1,
#                             longname="porosity", prec="float")
# Create a netCDF file with this variable
ncnew <- nc_create( paste0(dest_dir,"/soil_physics_2D.nc"),
vars = list(varBulkdensity))
ncvar_put( nc = ncnew, varid = varBulkdensity, vals = bulk_density[,,ground_layer], start=c(1,1), count=c(n_y, n_x ))
bulk_density
ncvar_put( nc = ncnew, varid = varBulkdensity, vals = bulk_density[,,ground_layer], start=c(1,1), count=c(n_y, n_x ))
ground_layer
upper_bounds
codes
#codes = read.table(paste0(src_dir, "/codes.txt"), sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
codes = read.table(codefile, sep="\t", header=TRUE) #concrete definition of map-IDs (classes of bulk densities)
codes
n_y
n_x
n_z
bulk_density
debugSource("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
debugSource("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
upper_bounds
codes$thickness..m.)
codes$thickness..m.
sort(-(unique(c(0, codes$thickness..m.))))
upper_bounds
layers2assign
upper_bounds
thickness
layers2assign = which(-thickness < upper_bounds) #find layers to be assigned
layers2assign
upper_bounds
upper_bounds
upper_bounds
debugSource("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/soil_physics/hexland_tracks/raw/generate_hexland_soil_phys.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/hexland_tracks/raw/generate_hexland_soil_moisture.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/hexland_tracks/raw/generate_hexland_soil_moisture.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/hexland_tracks/raw/generate_hexland_soil_moisture.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/SM_distribution/hexland_tracks/raw/generate_hexland_soil_moisture.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/vegetation/hexland_tracks/raw/generate_hexland_veg.R", echo=TRUE)
getwd()
source("E:/till/uni/crns/vJFC/0_compartments/vegetation/hexland_tracks/raw/generate_hexland_veg.R", echo=TRUE)
source("E:/till/uni/crns/vJFC/0_compartments/vegetation/hexland_tracks/raw/generate_hexland_veg.R", echo=TRUE)
