R/io.R

Defines functions swrc_model_exists load_swrc_model save_swrc_model

Documented in load_swrc_model save_swrc_model swrc_model_exists

#' @title Save and load fitted SWRC models
#' @name io
#' @description Functions to persist a fitted `swrc_fit` object to disk
#'   and reload it for later use (prediction, spatial mapping, etc.).
NULL

#' Save a fitted SWRC model to disk
#'
#' Saves the Keras model weights as an HDF5 file and the R metadata
#' (scalers, hyperparameters, etc.) as an `.rds` file inside `dir`.
#'
#' @param fit  A `swrc_fit` object returned by [fit_swrc()].
#' @param dir  Directory where the model will be saved.  Created if it
#'   does not exist.
#' @param name Stem name for the output files (default `"swrc_model"`).
#'
#' @return Invisibly returns a named list with paths to the two files:
#'   \describe{
#'     \item{`weights_path`}{Path to the `.weights.h5` file.}
#'     \item{`meta_path`}{Path to the `.rds` metadata file.}
#'   }
#'
#' @examples
#' \donttest{
#' if (reticulate::py_module_available("tensorflow")) {
#'   # A deliberately small, fast fit: 20 pedons, K = 16 and 50 collocation
#'   # points per residual set. The point here is the interface, not the
#'   # model -- see the vignette for a realistic configuration.
#'   d  <- prepare_swrc_data(swrc_example, depth_col = "depth")
#'   d  <- d[d$PEDON_ID %in% utils::head(unique(d$PEDON_ID), 20L), ]
#'   x  <- c("clay", "silt", "bd_gcm3", "soc", "Depth_num")
#'   SM <- list(K = 16L, S1 = 50L, S2 = 50L, S3 = 50L, S4 = 50L,
#'              epochs = 2L, verbose = FALSE)
#'   fit <- do.call(fit_swrc, c(list(train_df = d, x_inputs = x), SM))
#'   save_swrc_model(fit, dir = tempdir(), name = "model_test")
#' }
#' }
#'
#' @export
save_swrc_model <- function(fit,
                            dir,
                            name = "swrc_model") {
  stopifnot(inherits(fit, "swrc_fit"))
  dir.create(dir, showWarnings = FALSE, recursive = TRUE)

  wt_path   <- file.path(dir, paste0(name, ".weights.h5"))
  meta_path <- file.path(dir, paste0(name, "_meta.rds"))

  fit$theta_model$save_weights(wt_path)

  ## The metadata must carry EVERY argument build_swrc_model() needs, or the
  ## reconstructed graph will not match the saved weights. monotone, hidden and
  ## dropout are therefore stored alongside K.
  meta <- list(
    x_inputs     = fit$x_inputs,
    n_covariates = length(fit$x_inputs),
    K            = fit$K,
    monotone     = fit$monotone,
    free_head    = fit$free_head,
    hidden       = fit$hidden,
    dropout      = fit$dropout,
    dk           = fit$dk,
    knot_grid    = fit$knot_grid,
    scaler       = fit$scaler,
    theta_factor = fit$theta_factor,
    pf_left      = fit$pf_left,
    pf_right     = fit$pf_right,
    best_epoch   = fit$best_epoch,
    lambdas      = fit$lambdas,
    s3_form      = fit$s3_form
  )
  saveRDS(meta, meta_path)

  message("Model weights saved to : ", wt_path)
  message("Model metadata saved to: ", meta_path)

  invisible(list(weights_path = wt_path, meta_path = meta_path))
}

#' Load a previously saved SWRC model from disk
#'
#' Reconstructs the CNN1D Keras model from the saved weights and metadata
#' and returns a `swrc_fit`-compatible list that can be passed to
#' [predict_swrc()], [predict_swrc_dense()], etc.
#'
#' @param dir  Directory containing the saved files (default
#'   `"./models/swrc"`).
#' @param name Stem name used when saving (default `"swrc_model"`).
#'
#' @return A `swrc_fit` object carrying every field [fit_swrc()] returns
#'   except `history`, which is not persisted. `param_model` is rebuilt, but
#'   on a model saved with `monotone = FALSE` its `theta_s` output was never
#'   trained, which is why [predict_theta_s()] refuses such a model.
#'
#' @examples
#' \donttest{
#' if (reticulate::py_module_available("tensorflow")) {
#'   # A deliberately small, fast fit: 20 pedons, K = 16 and 50 collocation
#'   # points per residual set. The point here is the interface, not the
#'   # model -- see the vignette for a realistic configuration.
#'   d  <- prepare_swrc_data(swrc_example, depth_col = "depth")
#'   d  <- d[d$PEDON_ID %in% utils::head(unique(d$PEDON_ID), 20L), ]
#'   x  <- c("clay", "silt", "bd_gcm3", "soc", "Depth_num")
#'   SM <- list(K = 16L, S1 = 50L, S2 = 50L, S3 = 50L, S4 = 50L,
#'              epochs = 2L, verbose = FALSE)
#'   fit <- do.call(fit_swrc, c(list(train_df = d, x_inputs = x), SM))
#'   save_swrc_model(fit, dir = tempdir(), name = "model_test")
#'   fit2 <- load_swrc_model(tempdir(), "model_test")
#' }
#' }
#'
#' @export
load_swrc_model <- function(dir  = "./models/swrc",
                            name = "swrc_model") {
  wt_path   <- file.path(dir, paste0(name, ".weights.h5"))
  meta_path <- file.path(dir, paste0(name, "_meta.rds"))

  if (!file.exists(wt_path))
    rlang::abort(paste("Weights file not found:", wt_path))
  if (!file.exists(meta_path))
    rlang::abort(paste("Metadata file not found:", meta_path))

  meta <- readRDS(meta_path)

  ## Metadata written before these fields existed implies the old defaults,
  ## which were the only architecture the package could then produce.
  mono <- if (is.null(meta$monotone)) TRUE        else isTRUE(meta$monotone)
  hid  <- if (is.null(meta$hidden))   c(128L, 64L) else meta$hidden
  drp  <- if (is.null(meta$dropout))  0.10         else meta$dropout
  fh   <- if (is.null(meta$free_head)) "sigmoid"   else meta$free_head

  mods <- build_swrc_model(
    n_covariates = meta$n_covariates,
    K            = meta$K,
    monotone     = mono,
    hidden       = hid,
    dropout      = drp,
    free_head    = fh
  )
  mods$theta_model$load_weights(wt_path)

  structure(
    list(
      theta_model  = mods$theta_model,
      param_model  = mods$param_model,
      monotone     = mono,
      free_head    = fh,
      hidden       = hid,
      dropout      = drp,
      x_inputs     = meta$x_inputs,
      scaler       = meta$scaler,
      K            = meta$K,
      dk           = meta$dk,
      knot_grid    = meta$knot_grid,
      pf_left      = meta$pf_left,
      pf_right     = meta$pf_right,
      theta_factor = meta$theta_factor,
      best_epoch   = meta$best_epoch,
      lambdas      = meta$lambdas,
      ## absent in models saved before s3_form existed; they used the
      ## published inequality form
      s3_form      = if (is.null(meta$s3_form)) "inequality" else meta$s3_form,
      history      = NULL
    ),
    class = "swrc_fit"
  )
}

#' Check whether a model directory contains a valid saved model
#'
#' @param dir  Directory path.
#' @param name Model stem name.
#'
#' @examples
#' # FALSE for an empty directory: both the weights and the metadata file
#' # must be present for a model to count as loadable.
#' swrc_model_exists(dir = tempdir(), name = "no_such_model")
#'
#' @return Logical scalar.
#'
#' @export
swrc_model_exists <- function(dir = "./models/swrc", name = "swrc_model") {
  all(file.exists(
    file.path(dir, paste0(name, ".weights.h5")),
    file.path(dir, paste0(name, "_meta.rds"))
  ))
}

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.