R/lago_check_settings.R

Defines functions lago_as_list.lago_check lago_summary_text.lago_check print.lago_check .lago_checked_settings lago_check_settings

Documented in lago_check_settings

# A dry run of lago_optimization() for programs such as AI agents: the inputs
# are checked, and the outcome model fitted, without the search for the
# recommendation, which is the slow part.

# the state lago_check_settings() sets for lago_optimization() to read
.lago_state <- new.env(parent = emptyenv())

#' Check the settings of a LAGO optimization without running it
#'
#' `lago_check_settings()` takes the arguments of [lago_optimization()] and
#' checks them, as `lago_optimization()` would, but stops before the search
#' for the recommendation, which is the slow part. By default it also fits the
#' outcome model, since a model that cannot be fitted is a common problem. It
#' is meant for programs, such as AI agents, that want to know whether a call
#' will run, and what it will use, before they run it.
#'
#' The check stops at the first problem, as `lago_optimization()` does. Fix
#' that problem and check again to find the next one.
#'
#' @param ... The arguments of [lago_optimization()]. `quiet` is always TRUE.
#' @param fit_model A boolean. Whether to also fit the outcome model. Default
#'   TRUE. With FALSE, only the inputs are checked, which is faster.
#' @return A list of class `"lago_check"` with:
#' \describe{
#'   \item{ok}{TRUE when the settings would run.}
#'   \item{problem}{NULL, or the first problem: a list with `code`,
#'     `argument`, `fix` and `message`, as in [lago_error_codes()]. `code`,
#'     `argument` and `fix` are NULL for an error that has no code.}
#'   \item{warnings}{The warnings the settings give, as text.}
#'   \item{notes}{The notes on how the inputs were read, as text.}
#'   \item{settings}{When `ok`, the settings `lago_optimization()` would use
#'     after it fills in its defaults: the family and link, the goal and its
#'     intention, the components and their bounds and cost coefficients, the
#'     center weights, and, when the model was fitted, the number of rows it
#'     used and its coefficients.}
#' }
#' [lago_as_list()], [lago_to_json()] and [lago_summary_text()] also take it.
#' @examples
#' chk <- lago_check_settings(
#'   data = mtcars, outcome_name = "mpg", outcome_type = "continuous",
#'   intervention_components = c("gear", "qsec"),
#'   intervention_lower_bounds = c(3, 14), intervention_upper_bounds = c(5, 23),
#'   cost_list_of_vectors = list(c(0, 4), c(4, 6)), outcome_goal = 25
#' )
#' chk$ok
#' lago_summary_text(chk)
#' bad <- lago_check_settings(
#'   data = mtcars, outcome_name = "mpg", outcome_type = "continuous",
#'   intervention_components = c("gear", "qsec"),
#'   intervention_lower_bounds = c(5, 14), intervention_upper_bounds = c(3, 23),
#'   cost_list_of_vectors = list(c(0, 4), c(4, 6)), outcome_goal = 25
#' )
#' bad$problem$code
#' bad$problem$fix
#' @export
lago_check_settings <- function(..., fit_model = TRUE) {
  if (!is.logical(fit_model) || length(fit_model) != 1 || is.na(fit_model)) {
    lago_abort("not_true_false",
      "'fit_model' must be TRUE or FALSE.",
      argument = "fit_model",
      fix = "Set fit_model to TRUE or FALSE."
    )
  }
  # the call of the user, so an error names the arguments as they were given
  call <- match.call(expand.dots = TRUE)
  call[[1]] <- quote(LAGOtrials::lago_optimization)
  call$fit_model <- NULL
  call$quiet <- TRUE
  old <- .lago_state$check_only
  .lago_state$check_only <- if (fit_model) "model" else "inputs"
  on.exit(.lago_state$check_only <- old, add = TRUE)
  warned <- character(0)
  noted <- character(0)
  settings <- NULL
  problem <- tryCatch(
    {
      settings <- withCallingHandlers(
        eval(call, parent.frame()),
        warning = function(w) {
          warned <<- c(warned, conditionMessage(w))
          invokeRestart("muffleWarning")
        },
        message = function(m) {
          noted <<- c(noted, trimws(conditionMessage(m)))
          invokeRestart("muffleMessage")
        }
      )
      NULL
    },
    error = function(e) {
      list(
        code = if (inherits(e, "lago_error")) e$code,
        argument = if (inherits(e, "lago_error")) e$argument,
        fix = if (inherits(e, "lago_error")) e$fix,
        message = conditionMessage(e)
      )
    }
  )
  structure(
    list(
      ok = is.null(problem),
      problem = problem,
      warnings = unique(warned),
      notes = unique(noted),
      settings = if (is.null(problem)) settings
    ),
    class = "lago_check"
  )
}

# the settings lago_optimization() would use, read from its environment
.lago_checked_settings <- function(env, model) {
  get_or_null <- function(name) get0(name, envir = env, inherits = FALSE)
  family <- get_or_null("family_object")
  comps <- get_or_null("intervention_components")
  mains <- if (isTRUE(get_or_null("include_interaction_terms"))) get_or_null("main_components")
  values_for <- if (!is.null(mains)) mains else comps
  out <- list(
    outcome_name = get_or_null("outcome_name"),
    outcome_type = get_or_null("outcome_type"),
    family = if (!is.null(family)) family$family,
    link = if (!is.null(family)) family$link,
    outcome_goal = get_or_null("outcome_goal"),
    power_goal = get_or_null("power_goal"),
    outcome_goal_intention = get_or_null("outcome_goal_intention"),
    intervention_components = comps,
    main_components = mains,
    intervention_lower_bounds = stats::setNames(get_or_null("intervention_lower_bounds"), values_for),
    intervention_upper_bounds = stats::setNames(get_or_null("intervention_upper_bounds"), values_for),
    cost_list_of_vectors = stats::setNames(get_or_null("cost_list_of_vectors"), values_for),
    include_center_effects = isTRUE(get_or_null("include_center_effects")),
    include_time_effects = isTRUE(get_or_null("include_time_effects")),
    center_weights_for_outcome_goal = if (isTRUE(get_or_null("include_center_effects"))) {
      get_or_null("center_weights_for_outcome_goal")
    },
    optimization_method = get_or_null("optimization_method"),
    n_rows = nrow(get_or_null("data"))
  )
  if (!is.null(model)) {
    out$n_rows_fitted <- stats::nobs(model)
    out$coefficients <- stats::coef(model)
  }
  out
}

#' @export
print.lago_check <- function(x, ...) {
  cat(lago_summary_text(x), "\n", sep = "")
  invisible(x)
}

#' @export
lago_summary_text.lago_check <- function(x) {
  if (isTRUE(x$ok)) {
    fitted <- !is.null(x$settings$n_rows_fitted)
    return(paste0(
      "The settings are ready to run",
      if (fitted) {
        paste0(", and the outcome model fits on ", x$settings$n_rows_fitted, " rows")
      } else {
        ""
      },
      ".",
      if (length(x$warnings)) {
        paste0(" They give ", length(x$warnings), " warning",
          if (length(x$warnings) == 1) "" else "s", ".")
      } else {
        ""
      }
    ))
  }
  p <- x$problem
  paste0(
    "The settings have a problem",
    if (!is.null(p$code)) paste0(" (", p$code, ")") else "",
    ": ", p$message,
    if (!is.null(p$fix)) paste0(" To fix it: ", p$fix) else ""
  )
}

#' @export
lago_as_list.lago_check <- function(x, ...) {
  s <- x$settings
  list(
    schema_version = .lago_json_schema_version,
    kind = "lago_check",
    summary = lago_summary_text(x),
    ok = isTRUE(x$ok),
    problem = x$problem,
    warnings = as.list(x$warnings),
    notes = as.list(x$notes),
    settings = if (!is.null(s)) {
      s$intervention_components <- as.list(s$intervention_components)
      if (!is.null(s$main_components)) s$main_components <- as.list(s$main_components)
      s$intervention_lower_bounds <- as.list(s$intervention_lower_bounds)
      s$intervention_upper_bounds <- as.list(s$intervention_upper_bounds)
      s$cost_list_of_vectors <- lapply(s$cost_list_of_vectors, function(v) as.list(unname(v)))
      if (!is.null(s$center_weights_for_outcome_goal)) {
        s$center_weights_for_outcome_goal <- as.list(s$center_weights_for_outcome_goal)
      }
      if (!is.null(s$coefficients)) s$coefficients <- as.list(s$coefficients)
      s
    }
  )
}

Try the LAGOtrials package in your browser

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

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