R/data_prep.R

Defines functions make_profile_array make_obs_matrices prepare_swrc_data

Documented in make_obs_matrices make_profile_array prepare_swrc_data

#' @title Data preparation for CNN1D SWRC modelling
#' @name data_prep
#' @description Functions to prepare soil data for input to the CNN1D
#'   monotone-integral model, including 3-D sequence array construction and
#'   observation matrix creation.
NULL

#' Prepare a soil data frame for SWRC modelling
#'
#' A convenience wrapper that:
#' \enumerate{
#'   \item Renames columns to standard names.
#'   \item Parses the depth column.
#'   \item Fixes bulk-density units.
#'   \item Detects and normalises volumetric water content units.
#'   \item Computes per-profile maximum theta.
#'   \item Drops rows with missing key variables.
#' }
#'
#' @param df            A data frame with soil characterization data.
#' @param x_cols        Named character vector mapping standard names to
#'   actual column names.  Standard names: `"PEDON_ID"`, `"sand"`,
#'   `"silt"`, `"clay"`, `"soc"`, `"bd"`, `"matric_head"`,
#'   `"water_content"`, `"depth"`.  Unneeded variables may be omitted.
#' @param depth_col     Column name for depth (character string, default
#'   `"depth"`).  If already parsed, set to `NULL`.
#' @param fix_bd        Logical; apply [fix_bd_units()] to bulk density
#'   (default `TRUE`).
#' @param fix_theta     Logical; scale theta to m3/m3 if needed (default
#'   `TRUE`).
#'
#' @return A tibble with standardised columns plus `Depth_num`,
#'   `Depth_label`, `bd_gcm3`, `theta_n` (normalised WC), and
#'   `theta_max_n` (per-profile maximum theta).
#'
#' @examples
#' df <- data.frame(
#'   ID           = rep("P01", 3),
#'   sand_pct     = c(50, 50, 50),
#'   silt         = c(30, 30, 30),
#'   clay         = c(20, 20, 20),
#'   soc          = c(1.2, 1.2, 1.2),
#'   bd_gcc       = c(1.3, 1.3, 1.3),
#'   matric_head  = c(10, 100, 1000),
#'   theta        = c(0.40, 0.30, 0.20),
#'   depth        = c("0-30", "0-30", "0-30")
#' )
#' df_prep <- prepare_swrc_data(df,
#'   x_cols = c(PEDON_ID = "ID", sand = "sand_pct", bd = "bd_gcc",
#'              water_content = "theta"))
#'
#' @importFrom dplyr mutate group_by ungroup select left_join
#' @importFrom tidyr drop_na
#' @importFrom purrr map map_dbl map_chr
#' @export
prepare_swrc_data <- function(df,
                              x_cols    = NULL,
                              depth_col = "depth",
                              fix_bd    = TRUE,
                              fix_theta = TRUE) {
  stopifnot(is.data.frame(df))

  # Rename columns if mapping provided
  if (!is.null(x_cols)) {
    stopifnot(is.character(x_cols), !is.null(names(x_cols)))
    for (std in names(x_cols)) {
      actual <- x_cols[[std]]
      if (actual %in% names(df) && !(std %in% names(df))) {
        names(df)[names(df) == actual] <- std
      }
    }
  }

  # Parse depth column
  if (!is.null(depth_col) && depth_col %in% names(df)) {
    df <- parse_depth_column(df, depth_col)
  }

  # Fix bulk density units
  if (fix_bd && "bd" %in% names(df)) {
    df$bd_gcm3 <- fix_bd_units(df$bd)
  } else if ("bd" %in% names(df)) {
    df$bd_gcm3 <- as.numeric(df$bd)
  }

  # Normalise water content
  if (fix_theta && "water_content" %in% names(df)) {
    fac        <- theta_unit_factor(df$water_content)
    df$theta_n <- as.numeric(df$water_content) / fac
    attr(df, "theta_factor") <- fac
  } else if ("water_content" %in% names(df)) {
    df$theta_n <- as.numeric(df$water_content)
    attr(df, "theta_factor") <- 1
  }

  # Compute per-profile maximum theta
  if ("theta_n" %in% names(df) && "PEDON_ID" %in% names(df)) {
    key_cols <- intersect(c("PEDON_ID", "Depth_num"), names(df))
    df <- df |>
      dplyr::group_by(dplyr::across(dplyr::all_of(key_cols))) |>
      dplyr::mutate(theta_max_n = max(theta_n, na.rm = TRUE)) |>
      dplyr::ungroup()
  }

  tibble::as_tibble(df)
}

# ---------------------------------------------------------------------------
# Observation matrix builder
# ---------------------------------------------------------------------------

#' Build observation matrices for the CNN1D model
#'
#' Converts a prepared data frame into the arrays needed for training or
#' evaluation: a 3-D sequence array `Xseq` (shape `[N, K, p+1]`) and
#' companion vectors `pf`, `y`, and sample weights `w`.
#'
#' @param df           A prepared data frame (output of [prepare_swrc_data()]
#'   or compatible structure) containing covariate columns, `matric_head`,
#'   `theta_n`, and `theta_max_n`.
#' @param x_inputs     Character vector of covariate column names.
#' @param scaler       A fitted scaler from [fit_minmax()].
#' @param K            Number of knot points (default `64L`).
#' @param knot_grid    Numeric vector of knot positions (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`).
#' @param wet_split_cm Matric head threshold, in centimetres, separating
#'   wet from dry observations, or `NULL` (default) for a single data term
#'   with every observation weighted equally. Before 0.2.0 the default was
#'   `4.2`, read as 4.2 cm (pF 0.62), which put every measured point on the
#'   dry side; a split at pF 4.2 is `10^4.2` cm.
#' @param w_wet        Sample weight for wet-end observations (default `1`).
#' @param w_dry        Sample weight for dry-end observations (default `1`).
#'
#' @return A named list:
#'   \describe{
#'     \item{`Xseq`}{3-D numeric array \[N, K, p+1\].}
#'     \item{`pf`}{Numeric matrix \[N, 1\] of normalised pF values.}
#'     \item{`y`}{Numeric matrix \[N, 2\]: columns are `theta_n` and
#'       `theta_max_n`.}
#'     \item{`w`}{Numeric vector of sample weights.}
#'   }
#'   Rows of `df` with a missing covariate, `matric_head` or `theta_n` are
#'   dropped, with a message, because a non-finite target makes the whole
#'   batch loss NaN and so destroys every weight in one step. `N` is
#'   therefore the number of usable rows, not `nrow(df)`; the attributes
#'   `rows_kept` (indices into `df`) and `n_dropped` record which.
#'
#' @examples
#' df <- prepare_swrc_data(swrc_example, depth_col = "depth")
#' x  <- c("clay", "silt", "bd_gcm3", "soc", "Depth_num")
#' sc <- fit_minmax(df, x)
#' m  <- make_obs_matrices(df, x, sc, K = 16L)
#' dim(m$Xseq)   # [N, K, p + 1]
#' range(m$pf)   # normalised to [0, 1]
#'
#' # swrc_example carries missing water contents by design, so some rows
#' # are dropped and N is smaller than nrow(df):
#' c(rows_in = nrow(df), rows_used = dim(m$Xseq)[1],
#'   dropped = attr(m, "n_dropped"))
#'
#' @keywords internal
#' @export
make_obs_matrices <- function(df, x_inputs, scaler,
                              K            = 64L,
                              knot_grid    = seq(0, 1, length.out = K),
                              pf_left      = -2.0,
                              pf_right     =  7.6,
                              wet_split_cm = NULL,
                              w_wet        = 1.0,
                              w_dry        = 1.0) {
  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)

  for (needed in c("matric_head", "theta_n"))
    if (!needed %in% names(df))
      rlang::abort(paste0("`df` has no `", needed, "` column; ",
                          "run prepare_swrc_data() first."))

  ## Rows with a missing target or covariate cannot be trained on, and must be
  ## removed rather than passed through: the data loss is a sum over the batch,
  ## so a single non-finite target makes the whole loss NaN, every gradient
  ## NaN and every weight NaN after one step. The model then predicts NaN
  ## everywhere while training reports no error -- the failure is invisible.
  ## The bundled `swrc_example` carries 48 missing water contents by design,
  ## so this is the ordinary case, not an edge case.
  cov_mat <- vapply(scaler$cols, function(cc) as.numeric(df[[cc]]),
                    numeric(nrow(df)))
  cov_mat <- matrix(cov_mat, nrow = nrow(df))   # keep 2-D for a single covariate
  keep <- rowSums(!is.finite(cov_mat)) == 0L &
    is.finite(as.numeric(df$matric_head)) &
    is.finite(as.numeric(df$theta_n))

  n_dropped <- sum(!keep)
  if (n_dropped > 0L)
    message(sprintf(
      "make_obs_matrices(): dropped %d of %d rows with a missing covariate, head or theta_n.",
      n_dropped, length(keep)))
  if (!any(keep))
    rlang::abort("No usable observations: every row has a missing covariate, head or theta_n.")

  df <- df[keep, , drop = FALSE]

  Xcov <- apply_minmax(df, scaler)
  N    <- nrow(Xcov)
  p    <- ncol(Xcov)

  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
  }

  h       <- as.numeric(df$matric_head)
  pf_norm <- head_normalize(h, pf_left, pf_right)
  y_theta <- as.numeric(df$theta_n)
  y_max   <- as.numeric(df$theta_max_n)
  y_max[!is.finite(y_max)] <- y_theta[!is.finite(y_max)]
  ## NULL (the default) weights every observation equally: one data term.
  ## The old default of 4.2 was read as centimetres (pF 0.62), which put
  ## every measured point on the dry side; see NEWS for 0.2.0.
  w       <- if (is.null(wet_split_cm)) rep(1, length(h))
             else ifelse(h <= wet_split_cm, w_wet, w_dry)

  ## `rows_kept` indexes into the df that was passed in, so a caller that
  ## needs to align these matrices back to its own data frame can, even
  ## though the row count may be smaller.
  structure(
    list(
      Xseq = Xseq,
      pf   = matrix(pf_norm, ncol = 1L),
      y    = cbind(y_theta, y_max),
      w    = as.numeric(w)
    ),
    rows_kept = which(keep),
    n_dropped = n_dropped
  )
}

# ---------------------------------------------------------------------------
# Sequence array for profile prediction
# ---------------------------------------------------------------------------

#' Build a sequence array for one or more soil profiles
#'
#' Each row of `df_profiles` (one profile) is expanded over a pF grid to
#' produce the `[N_profiles * N_pf, K, p+1]` array needed for dense
#' curve prediction.
#'
#' @param df_profiles  Data frame with one row per profile (unique PEDON ×
#'   depth combination).
#' @param x_inputs     Character vector of covariate names.
#' @param scaler       Fitted scaler from [fit_minmax()].
#' @param K            Number of knots (default `64L`).
#' @param knot_grid    Knot positions (default `seq(0,1,length.out=K)`).
#'
#' @return Named list:
#'   \describe{
#'     \item{`Xseq`}{3-D array \[Np, K, p+1\].}
#'     \item{`Np`}{Number of profiles.}
#'     \item{`p`}{Number of covariates.}
#'   }
#'
#' @examples
#' df <- prepare_swrc_data(swrc_example, depth_col = "depth")
#' x  <- c("clay", "silt", "bd_gcm3", "soc", "Depth_num")
#' sc <- fit_minmax(df, x)
#' # one row per horizon, de-duplicated: the covariates do not vary with pF
#' prof <- df[!duplicated(df[, c("PEDON_ID", "Depth_num")]), ]
#' a <- make_profile_array(prof, x, sc, K = 16L)
#' a$Np          # profiles
#' a$p           # covariates
#' dim(a$Xseq)   # [Np, K, p + 1]
#'
#' @keywords internal
#' @export
make_profile_array <- function(df_profiles, x_inputs, scaler,
                               K         = 64L,
                               knot_grid = seq(0, 1, length.out = K)) {
  Xcov <- apply_minmax(df_profiles, scaler)
  Np   <- 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(Np, K, p + 1L))
  for (i in seq_len(Np)) {
    Xseq[i, , seq_len(p)] <- matrix(rep(Xcov[i, ], each = K),
                                    nrow = K, byrow = FALSE)
    Xseq[i, , p + 1L]     <- knot_grid
  }

  list(Xseq = Xseq, Np = Np, p = p)
}

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.