R/model.R

Defines functions build_swrc_model

Documented in build_swrc_model

#' @title CNN1D monotone-integral model architecture
#' @name model
#' @description Build the physics-informed 1-D CNN with a monotone integral
#'   output layer, as described in Norouzi et al. (2025).
#'
#' @details
#' ## Architecture
#'
#' The model takes two inputs:
#' \enumerate{
#'   \item `Xseq_knots`: a 3-D tensor of shape `[N, K, p+1]` — for each
#'     observation, `p` scaled covariates are broadcast across `K` knot
#'     positions, and the knot positions themselves form the last channel.
#'   \item `pf_norm`: a 2-D tensor of shape `[N, 1]` — the query pF value
#'     normalised to `[0, 1]`.
#' }
#'
#' The output satisfies:
#' \deqn{\hat{\theta}(pF) = \theta_s - \int_0^{pF} \text{softplus}(s(t))\,dt}
#'
#' where \eqn{s(t)} is a 1-channel convolutional output.  Monotone decrease
#' is guaranteed **by construction** because the integrand is always positive.
#'
#' @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

#' Build the CNN1D monotone-integral SWRC model
#'
#' Constructs a Keras model implementing the monotone-integral architecture
#' of Norouzi et al. (2025).  The returned list contains two models that
#' share weights:
#' * `theta_model` — full prediction model (pF query + covariates → theta).
#' * `param_model` — extracts the saturated water content (theta_s) from
#'   covariates only.
#'
#' @param n_covariates Integer. Number of soil-property covariates (`p`).
#' @param hidden       Integer vector of length 2. Number of filters in the
#'   first and second Conv1D layers (default `c(128L, 64L)`).
#' @param dropout      Numeric dropout rate after each Conv1D layer
#'   (default `0.10`).
#' @param K            Integer. Number of knot points for the cumulative
#'   integration grid (default `64L`).
#' @param free_head    Output head used when `monotone = FALSE`. `"sigmoid"`
#'   (default, the pre-0.2.0 control) reads theta out through a sigmoid unit,
#'   which also bounds it to (0, 1); `"integral"` keeps the integral
#'   construction of the monotone head and removes only the sign constraint
#'   on its increments, so that monotonicity is the single difference.
#' @param monotone     Logical. `TRUE` (default) builds the monotone integral
#'   head, which guarantees \eqn{\partial\theta/\partial pF \le 0} for any
#'   parameter values. `FALSE` replaces it with a dense head that emits
#'   \eqn{\theta} directly and is free to produce a non-monotone curve. The
#'   backbone, knots, scaling and inputs are identical either way, so the two
#'   differ only in the output construction. Use `FALSE` as an ablation
#'   control, to measure what the monotone architecture contributes rather
#'   than assert it; it is not a modelling recommendation.
#'
#' @return A named list:
#'   \describe{
#'     \item{`theta_model`}{Keras model: inputs `[Xseq_knots, pf_norm]`,
#'       output shape `[N, 2]` (theta_hat, theta_s).}
#'     \item{`param_model`}{Keras model: input `Xseq_knots`,
#'       output shape `[N, 1]` (theta_s only).}
#'     \item{`K`}{The `K` value used.}
#'     \item{`dk`}{The knot spacing `1 / (K - 1)`.}
#'     \item{`knot_grid`}{Numeric vector of knot positions.}
#'   }
#'
#' @examples
#' \donttest{
#' # Building the graph needs a working TensorFlow; without one this is a
#' # no-op rather than an error, so the example is safe to run anywhere.
#' if (reticulate::py_module_available("tensorflow")) {
#'   # K = 16 keeps the example well inside CRAN's time budget on a
#'   # machine that does have TensorFlow; the default is K = 64.
#'   mod <- build_swrc_model(n_covariates = 9L, K = 16L)
#'   mod$theta_model$count_params()
#' }
#' }
#'
#' @export
build_swrc_model <- function(n_covariates,
                             hidden   = c(128L, 64L),
                             dropout  = 0.10,
                             K        = 64L,
                             monotone = TRUE,
                             free_head = c("sigmoid", "integral")) {
  free_head <- match.arg(free_head)
  stopifnot(
    is.numeric(n_covariates), n_covariates >= 1L,
    length(hidden) == 2L,
    is.numeric(dropout), dropout >= 0, dropout < 1,
    is.numeric(K), K >= 2L,
    ## monotone selects the output head. Without this check a non-logical
    ## value reaches `if (!monotone)`, which errors opaquely for most inputs
    ## and, for a 1-by-1 data frame, silently selects the free head.
    is.logical(monotone), length(monotone) == 1L, !is.na(monotone)
  )

  tf <- tensorflow::tf
  tf$keras$backend$clear_session()
  gc()

  K   <- as.integer(K)
  p   <- as.integer(n_covariates)
  C   <- as.integer(p + 1L)
  dk  <- 1.0 / (as.numeric(K) - 1.0)

  knot_grid <- seq(0, 1, length.out = K)

  # TF constants (shared across the Lambda layer)
  dk_c  <- tf$constant(dk,               dtype = "float32")
  Km1_c <- tf$constant(as.numeric(K-1L), dtype = "float32")
  Km1_i <- tf$constant(as.integer(K-1L), dtype = "int32")
  one_c <- tf$constant(1.0,              dtype = "float32")
  eps_c <- tf$constant(1e-6,             dtype = "float32")

  tpl <- reticulate::tuple

  # --- Inputs ---
  xseq_in <- tf$keras$Input(shape = tpl(K, C), name = "Xseq_knots")
  pf_in   <- tf$keras$Input(shape = list(1L),  name = "pf_norm")

  # --- Shared feature extraction (2 x Conv1D + Dropout) ---
  z <- xseq_in
  z <- tf$keras$layers$Conv1D(
    filters     = as.integer(hidden[1]),
    kernel_size = 3L,
    padding     = "same",
    activation  = "relu",
    name        = "conv1"
  )(z)
  z <- tf$keras$layers$Dropout(rate = dropout, name = "drop1")(z)
  z <- tf$keras$layers$Conv1D(
    filters     = as.integer(hidden[2]),
    kernel_size = 3L,
    padding     = "same",
    activation  = "relu",
    name        = "conv2"
  )(z)
  z <- tf$keras$layers$Dropout(rate = dropout, name = "drop2")(z)

  # --- Global average pooling -> theta_s (saturated WC) ---
  g       <- tf$keras$layers$GlobalAveragePooling1D(name = "gap")(z)
  theta_s <- tf$keras$layers$Dense(1L, activation = "sigmoid",
                                   name = "theta_s")(g)

  # --- Per-knot slope (monotone integrand) ---
  slope_raw <- tf$keras$layers$Conv1D(
    filters     = 1L,
    kernel_size = 1L,
    padding     = "same",
    activation  = NULL,
    name        = "slope_raw"
  )(z)

  # --- Output head ---
  # monotone = TRUE  : theta_hat = theta_s - CumInt(softplus(slope)), so
  #                    d theta / d pF <= 0 holds for every parameter value.
  # monotone = FALSE : the same backbone emits theta directly and is free to
  #                    produce a non-monotone curve. This exists so that the
  #                    contribution of the architecture can be measured rather
  #                    than asserted: compare a monotone fit against a free one
  #                    trained on identical inputs, knots and scaling. It is an
  #                    ablation control, not a modelling recommendation.
  theta_hat <- if (!monotone && free_head == "sigmoid") {
    tf$keras$layers$Dense(
      1L, activation = "sigmoid", name = "theta_free"
    )(
      tf$keras$layers$Dense(
        as.integer(hidden[2]), activation = "relu", name = "free_head"
      )(
        tf$keras$layers$Concatenate(axis = 1L, name = "free_concat")(
          list(g, pf_in))
      )
    )
  } else tf$keras$layers$Lambda(
    function(inputs) {
      ts  <- inputs[[1]]
      sr  <- inputs[[2]]
      pf  <- inputs[[3]]

      pf    <- tf$clip_by_value(pf, 0.0, 1.0)
      ## monotone: softplus keeps every increment positive, so theta can
      ## only fall. free_head = "integral": the identical construction
      ## with the sign constraint removed -- the clean ablation, differing
      ## from the monotone head in that one respect only.
      s_pos <- if (monotone) tf$nn$softplus(tf$squeeze(sr, axis = 2L)) + eps_c
               else tf$squeeze(sr, axis = 2L)
      I_k   <- (tf$cumsum(s_pos, axis = 1L) - s_pos) * dk_c

      u  <- pf * Km1_c
      i0 <- tf$cast(tf$floor(u), tf$int32)
      i1 <- tf$minimum(i0 + 1L, Km1_i)
      t  <- u - tf$cast(i0, tf$float32)

      i0v <- tf$squeeze(i0, axis = 1L)
      i1v <- tf$squeeze(i1, axis = 1L)
      I0  <- tf$reshape(tf$gather(I_k, i0v, batch_dims = 1L), tpl(-1L, 1L))
      I1  <- tf$reshape(tf$gather(I_k, i1v, batch_dims = 1L), tpl(-1L, 1L))

      ts - ((one_c - t) * I0 + t * I1)
    },
    output_shape = tpl(1L),
    name         = "theta_hat"
  )(list(theta_s, slope_raw, pf_in))

  theta_out <- tf$keras$layers$Concatenate(
    axis = 1L, name = "theta_out"
  )(list(theta_hat, theta_s))

  # --- Assemble models ---
  theta_model <- tf$keras$Model(
    inputs  = list(xseq_in, pf_in),
    outputs = theta_out,
    name    = "CNN1D_SWRC_theta_model"
  )

  param_model <- tf$keras$Model(
    inputs  = xseq_in,
    outputs = theta_s,
    name    = "CNN1D_SWRC_param_model"
  )

  list(
    theta_model = theta_model,
    param_model = param_model,
    K           = K,
    dk          = dk,
    knot_grid   = knot_grid
  )
}

Try the soilFlux package in your browser

Any scripts or data that you put into this service are public.

soilFlux documentation built on Dec. 4, 2026, 5:10 p.m.