Nothing
#' @title Physics-informed constraints for SWRC modelling
#' @name physics
#' @description Functions for defining, building, and evaluating the four
#' physics-based residual constraints of Norouzi et al. (2025).
#'
#' @references
#' Norouzi, S., et al. (2025). Physics-Informed Neural Networks for
#' Estimating a Continuous Form of the Soil Water Retention Curve From
#' Basic Soil Properties. *Water Resources Research*, 61(3),
#' e2024WR038149. \doi{10.1029/2024WR038149}
NULL
# ---------------------------------------------------------------------------
# Lambda configuration
# ---------------------------------------------------------------------------
#' Return default Norouzi et al. (2025) loss weights (lambdas)
#'
#' Table 1 of Norouzi et al. (2025) defines six loss-weight hyperparameters.
#' This function returns them as a named list that can be passed to
#' [fit_swrc()] and [compute_physics_loss()].
#'
#' @param config Character string; either `"norouzi"` (exact replication,
#' default) or `"smooth"` (lambda3 = 10 for a smoother dry-end).
#'
#' @return A named list:
#' \describe{
#' \item{`lambda_wet`}{Weight for wet-end data loss (lambda1 = 1).}
#' \item{`lambda_dry`}{Weight for dry-end data loss (lambda2 = 10).}
#' \item{`lambda3`}{S1 dry-end linearity (lambda3 = 1 or 10).}
#' \item{`lambda4`}{S2 non-negativity at pF0 (lambda4 = 1000).}
#' \item{`lambda5`}{S3 non-positivity at pF1 (lambda5 = 1000).}
#' \item{`lambda6`}{S4 saturated-plateau flatness (lambda6 = 1).}
#' }
#'
#' @examples
#' norouzi_lambdas()
#' norouzi_lambdas("smooth")
#'
#' @export
norouzi_lambdas <- function(config = c("norouzi", "smooth")) {
config <- match.arg(config)
base <- list(
lambda_wet = 1.0,
lambda_dry = 10.0,
lambda4 = 1000.0,
lambda5 = 1000.0,
lambda6 = 1.0
)
base$lambda3 <- if (config == "norouzi") 1.0 else 10.0
base
}
# ---------------------------------------------------------------------------
# Residual sets (collocation points for physics loss)
# ---------------------------------------------------------------------------
#' Build physics residual point sets (S1 – S4)
#'
#' Generates four sets of collocation points (random soil-property vectors
#' and associated pF values) used to evaluate the physics constraints during
#' training.
#'
#' @param df_raw Data frame with covariate columns (training split).
#' @param x_inputs Character vector of covariate column names.
#' @param S1 Number of S1 points — dry-end linearity (default 1500).
#' @param S2 Number of S2 points — non-negativity at pF0 (default 500).
#' @param S3 Number of S3 points — non-positivity at pF1 (default 500).
#' @param S4 Number of S4 points — saturated plateau (default 1500).
#' @param pF_lin_min Lower pF for the S1 linearity constraint (default 5.0).
#' @param pF_lin_max Upper pF for the S1 linearity constraint (default 7.6).
#' @param pF0_pos pF at which theta must be >= 0 — S2 (default 6.2).
#' @param pF1_neg pF at which theta must be <= 0 — S3 (default 7.6).
#' @param pF_sat_min Lower pF for the S4 plateau constraint (default -2.0).
#' @param pF_sat_max Upper pF for the S4 plateau constraint (default -0.3).
#' @param seed Integer random seed (default 123).
#' @param covariates `"rows"` (default) samples whole covariate vectors from
#' `df_raw`; `"uniform"` draws each covariate independently over its range
#' (the pre-0.2.0 behaviour, which breaks sand + silt + clay = 100).
#'
#' @return A named list with four data frames: `set1`, `set2`, `set3`,
#' `set4`. Each data frame has one row per collocation point, with columns
#' corresponding to `x_inputs` (sampled uniformly within training range)
#' and a `pF` column.
#'
#' @examples
#' df <- data.frame(
#' clay = c(20, 30, 10),
#' silt = c(30, 40, 20),
#' sand_total = c(50, 30, 70),
#' Depth_num = c(15, 30, 60)
#' )
#' sets <- build_residual_sets(df, c("clay", "silt", "sand_total", "Depth_num"),
#' S1 = 50L, S2 = 20L, S3 = 20L, S4 = 50L)
#'
#' @export
build_residual_sets <- function(df_raw, x_inputs,
S1 = 1500L, S2 = 500L, S3 = 500L, S4 = 1500L,
pF_lin_min = 5.0, pF_lin_max = 7.6,
pF0_pos = 6.2, pF1_neg = 7.6,
pF_sat_min = -2.0, pF_sat_max = -0.3,
seed = 123L,
covariates = c("rows", "uniform")) {
covariates <- match.arg(covariates)
set.seed(seed)
df_num <- as.data.frame(lapply(df_raw[, x_inputs, drop = FALSE], as.numeric))
mins <- vapply(df_num, min, numeric(1L), na.rm = TRUE)
maxs <- vapply(df_num, max, numeric(1L), na.rm = TRUE)
## n = 0 switches a residual term OFF. It must still yield a well-formed
## zero-row frame with the right columns, because vapply(..., numeric(0))
## does not return a usable matrix and a scalar cannot be assigned into a
## zero-row data frame.
blk <- function(n, pf) {
n <- as.integer(n)
if (n == 0L) {
X <- as.data.frame(matrix(numeric(0), nrow = 0L,
ncol = length(x_inputs) + 1L))
names(X) <- c(x_inputs, "pF")
return(X)
}
## "rows" draws whole covariate vectors from the training data, so a
## collocation point is a soil that exists: sand + silt + clay = 100 and
## the joint structure of texture, carbon and density is preserved.
## "uniform" is the pre-0.2.0 behaviour, kept for replication: each
## covariate independently uniform on its range, which breaks both.
X <- if (covariates == "rows")
df_num[sample.int(nrow(df_num), n, replace = TRUE), , drop = FALSE]
else as.data.frame(vapply(seq_along(x_inputs), function(j)
stats::runif(n, mins[j], maxs[j]), numeric(n)))
X <- as.data.frame(X); rownames(X) <- NULL
names(X) <- x_inputs
X$pF <- if (length(pf) == 1L) rep(pf, n) else pf
X
}
s1 <- blk(S1, stats::runif(max(S1, 0L), pF_lin_min, pF_lin_max))
s2 <- blk(S2, pF0_pos)
s3 <- blk(S3, pF1_neg)
s4 <- blk(S4, stats::runif(max(S4, 0L), pF_sat_min, pF_sat_max))
list(set1 = s1, set2 = s2, set3 = s3, set4 = s4)
}
#' Convert residual point sets to TensorFlow tensors
#'
#' Takes one residual data frame (as returned by [build_residual_sets()])
#' and builds the 3-D sequence array `Xseq` (shape `[N, K, p+1]`) and
#' the `pf` tensor (shape `[N, 1]`) needed by the CNN1D model.
#'
#' @param df_res A residual data frame (one of `set1` – `set4`).
#' @param scaler A scaler object from [fit_minmax()].
#' @param K Number of knot points (default 64).
#' @param knot_grid Numeric vector of knot positions in \[0, 1\]
#' (default `seq(0, 1, length.out = K)`).
#' @param pf_left Left boundary of the pF domain (default -2).
#' @param pf_right Right boundary of the pF domain (default 7.6).
#'
#' @return A named list with TensorFlow tensors:
#' \describe{
#' \item{`Xseq`}{float32 tensor, shape \[N, K, p+1\].}
#' \item{`pf`}{float32 tensor, shape \[N, 1\].}
#' }
#'
#' @examples
#' \donttest{
#' if (reticulate::py_module_available("tensorflow")) {
#' df <- prepare_swrc_data(swrc_example, depth_col = "depth")
#' x <- c("clay", "silt", "bd_gcm3", "soc", "Depth_num")
#' sc <- fit_minmax(df, x)
#' rs <- build_residual_sets(df[, x], x, S1 = 10L, S2 = 10L,
#' S3 = 10L, S4 = 10L)
#' tn <- residual_to_tensors(rs$set2, sc, K = 16L)
#' tn$Xseq$shape
#' }
#' }
#'
#' @keywords internal
#' @export
residual_to_tensors <- function(df_res, scaler,
K = 64L,
knot_grid = seq(0, 1, length.out = K),
pf_left = -2.0,
pf_right = 7.6) {
tf <- tensorflow::tf
Xcov <- apply_minmax(df_res, scaler)
N <- nrow(Xcov)
p <- ncol(Xcov)
K <- as.integer(K)
## knot_grid defaults to seq(0, 1, length.out = K), so the two agree unless
## both are supplied. If they disagree, the knot column is recycled into a
## K-row slice and the mismatch is silent, so refuse it here.
stopifnot(length(knot_grid) == K)
Xseq <- array(0, dim = c(N, K, p + 1L))
for (i in seq_len(N)) {
Xseq[i, , seq_len(p)] <- matrix(rep(Xcov[i, ], each = K),
nrow = K, byrow = FALSE)
Xseq[i, , p + 1L] <- knot_grid
}
pf_norm <- (df_res$pF - pf_left) / (pf_right - pf_left)
list(
Xseq = tf$constant(Xseq, dtype = "float32"),
pf = tf$constant(matrix(pf_norm, ncol = 1L), dtype = "float32")
)
}
# ---------------------------------------------------------------------------
# Physics loss — Equation (4) of Norouzi et al. (2025)
# ---------------------------------------------------------------------------
#' Compute the physics-informed residual loss (Norouzi et al. 2025)
#'
#' Evaluates four physics constraints against the current model weights:
#' \describe{
#' \item{S1 (L_lin)}{Second derivative \eqn{|\partial^2\theta/\partial pF^2|}
#' in the dry end \eqn{pF \in [5, 7.6]} should be near zero (linearity).}
#' \item{S2 (L_pos)}{\eqn{\theta(pF = 6.2) \geq 0} (non-negativity).}
#' \item{S3 (L_neg)}{\eqn{\theta(pF = 7.6) \leq 0} (non-positivity),
#' or \eqn{\theta(pF = 7.6) = 0} when `s3_form = "equality"`.}
#' \item{S4 (L_sat)}{First derivative \eqn{|\partial\theta/\partial pF|}
#' near zero in the saturated plateau \eqn{pF \in [-2, -0.3]}.}
#' }
#'
#' @param theta_model A Keras model with two inputs: `Xseq` and `pf_norm`.
#' @param res_tensors A named list with four sublists (`set1` – `set4`),
#' each containing `Xseq` and `pf` tensors (output of
#' [residual_to_tensors()]).
#' @param lambda3 Weight for S1 linearity loss (default 1.0).
#' @param lambda4 Weight for S2 non-negativity loss (default 1000.0).
#' @param lambda5 Weight for S3 non-positivity loss (default 1000.0).
#' @param s3_form Form of the S3 dry-end residual. `"inequality"` (default)
#' reproduces Norouzi et al. (2025) exactly: only
#' \eqn{\theta(pF_1) > 0} is penalised, through
#' \eqn{\mathrm{mean}\,\mathrm{relu}(\theta)}. `"equality"` penalises
#' \eqn{\mathrm{mean}\,|\theta|} instead, pinning
#' \eqn{\theta(pF_1)} at zero from both sides.
#'
#' The published inequality is satisfied by any non-positive value, and under
#' a monotone decreasing curve it therefore pushes the whole dry end below
#' zero, which in turn forces \eqn{\theta(pF_0)} negative and puts S3 in
#' direct conflict with S2. Since the physical statement is that water
#' content at oven dryness *is* zero, not that it is at most zero, the
#' equality form expresses the intended constraint without that conflict.
#'
#' It does NOT remove the degenerate optimum \eqn{\theta \equiv 0}: the
#' null curve satisfies all four residuals exactly under either form, since
#' its first and second derivatives vanish and \eqn{|\theta| = 0}
#' everywhere. Nothing in the residual set distinguishes the correct curve
#' from the null one -- only the data term does.
#' @param lambda6 Weight for S4 saturation loss (default 1.0).
#' @param pf_left Left boundary of the normalised pF domain (default -2).
#' @param pf_right Right boundary (default 7.6).
#' @param training Logical passed to the model call (default `TRUE`).
#' @param pF_lin_min,pF_lin_max pF range of the S1 linearity term (defaults
#' `5.0`, `7.6`). S1 is evaluated as a discrete second difference at the
#' knot positions inside this range.
#'
#' @return A named list of TensorFlow scalars:
#' `L_phys`, `L_lin`, `L_pos`, `L_neg`, `L_sat`.
#'
#' @examples
#' \donttest{
#' if (reticulate::py_module_available("tensorflow")) {
#' df <- prepare_swrc_data(swrc_example, depth_col = "depth")
#' x <- c("clay", "silt", "bd_gcm3", "soc", "Depth_num")
#' sc <- fit_minmax(df, x)
#' rs <- build_residual_sets(df[, x], x, S1 = 20L, S2 = 20L,
#' S3 = 20L, S4 = 20L)
#' rt <- lapply(rs, residual_to_tensors, scaler = sc, K = 16L)
#' mod <- build_swrc_model(n_covariates = length(x), K = 16L)
#'
#' # The published inequality leaves S3 at zero cost for any negative
#' # theta(pF 7.6); the equality penalises the distance from zero in
#' # either direction. L_neg differs between the two for the same weights.
#' ineq <- compute_physics_loss(mod$theta_model, rt, s3_form = "inequality")
#' eqty <- compute_physics_loss(mod$theta_model, rt, s3_form = "equality")
#' c(inequality = as.numeric(ineq$L_neg), equality = as.numeric(eqty$L_neg))
#' }
#' }
#'
#' @keywords internal
#' @export
compute_physics_loss <- function(theta_model, res_tensors,
lambda3 = 1.0,
lambda4 = 1000.0,
lambda5 = 1000.0,
lambda6 = 1.0,
s3_form = c("inequality", "equality"),
pf_left = -2.0,
pf_right = 7.6,
training = TRUE,
pF_lin_min = 5.0,
pF_lin_max = 7.6) {
tf <- tensorflow::tf
relu <- tf$nn$relu
s3_form <- match.arg(s3_form)
rng_pf <- as.numeric(pf_right - pf_left)
sc1 <- tf$constant(1.0 / rng_pf, tf$float32)
sc2 <- tf$constant(1.0 / rng_pf^2, tf$float32)
zero <- tf$constant(0.0, tf$float32)
## A residual set built with S = 0 is empty, and tf$reduce_mean over an empty
## tensor is NaN, which would poison the total loss. Each term is therefore
## skipped when its collocation set is empty, so S1..S4 = 0 genuinely turns
## that constraint off instead of silently producing NaN. The set sizes are
## fixed when the tensors are built, so this branches at trace time.
n_pts <- function(tns) {
d <- tns$shape$as_list()[[1]]
if (is.null(d)) NA_integer_ else as.integer(d)
}
n1 <- n_pts(res_tensors$set1$pf); n2 <- n_pts(res_tensors$set2$pf)
n3 <- n_pts(res_tensors$set3$pf); n4 <- n_pts(res_tensors$set4$pf)
# --- S1: dry-end linearity, as a DISCRETE second difference ---
## The monotone head is piecewise linear between knots, so its analytic
## second derivative is zero inside every segment and undefined at the
## knots: an autodiff |d2theta/dpF2| at random points sees nothing, and
## before 0.2.0 that is what S1 computed. Theta is instead evaluated at
## the knot positions inside [pF_lin_min, pF_lin_max] and the second
## difference taken there, which for a piecewise-linear curve is exactly
## the change of slope at each knot, and for a smooth one is the usual
## finite-difference second derivative. Same units as before (per pF^2).
## The number of evaluated points is kept near S1, so the cost is too.
L_lin <- if (isTRUE(n1 == 0L)) zero else {
X1 <- res_tensors$set1$Xseq
Kk <- as.integer(X1$shape$as_list()[[2]])
kg <- seq(0, 1, length.out = Kk)
pr <- pf_left + kg * rng_pf
sel <- kg[pr >= pF_lin_min - 1e-9 & pr <= pF_lin_max + 1e-9]
G <- length(sel)
if (G < 3L) zero else {
nr <- min(n1, max(1L, as.integer(ceiling(n1 / G))))
Xs <- tf$gather(X1, 0:(nr - 1L))
Xr <- tf$`repeat`(Xs, repeats = G, axis = 0L)
pfg <- tf$constant(matrix(rep(sel, times = nr), ncol = 1L), tf$float32)
th <- theta_model(list(Xr, pfg), training = training)[, 1L, drop = FALSE]
th <- tf$reshape(th, c(nr, G))
h <- rng_pf / (Kk - 1)
d2 <- tf$gather(th, 2:(G - 1L), axis = 1L) -
2 * tf$gather(th, 1:(G - 2L), axis = 1L) +
tf$gather(th, 0:(G - 3L), axis = 1L)
tf$reduce_mean(tf$abs(d2)) / tf$constant(h^2, tf$float32)
}
}
# --- S2: theta(pF0) >= 0 ---
L_pos <- if (isTRUE(n2 == 0L)) zero else {
th2 <- theta_model(list(res_tensors$set2$Xseq, res_tensors$set2$pf),
training = training)[, 1L, drop = FALSE]
tf$reduce_mean(relu(-th2))
}
# --- S3: theta(pF1) <= 0, or == 0 under s3_form = "equality" ---
L_neg <- if (isTRUE(n3 == 0L)) zero else {
th3 <- theta_model(list(res_tensors$set3$Xseq, res_tensors$set3$pf),
training = training)[, 1L, drop = FALSE]
if (s3_form == "equality") tf$reduce_mean(tf$abs(th3))
else tf$reduce_mean(relu(th3))
}
# --- S4: saturated plateau |dtheta/dpF| ~ 0 ---
L_sat <- if (isTRUE(n4 == 0L)) zero else {
pf4 <- res_tensors$set4$pf
with(tf$GradientTape() %as% t4, {
t4$watch(pf4)
th4 <- theta_model(list(res_tensors$set4$Xseq, pf4),
training = training)[, 1L, drop = FALSE]
})
d4 <- safe_grad(t4, th4, pf4)
tf$reduce_mean(tf$abs(d4 * sc1))
}
l3 <- tf$constant(lambda3, tf$float32)
l4 <- tf$constant(lambda4, tf$float32)
l5 <- tf$constant(lambda5, tf$float32)
l6 <- tf$constant(lambda6, tf$float32)
L_phys <- l3 * L_lin + l4 * L_pos + l5 * L_neg + l6 * L_sat
list(
L_phys = L_phys,
L_lin = L_lin,
L_pos = L_pos,
L_neg = L_neg,
L_sat = L_sat
)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.