R/lago_json.R

Defines functions lago_summary_text.lago_budget lago_as_list.lago_budget lago_summary_text.lago_sensitivity lago_as_list.lago_sensitivity lago_summary_text.lago .lago_settings_text lago_as_list.lago .lago_confidence_level .lago_value_names .lago_by_component lago_summary_text.default lago_as_list.default lago_summary_text lago_to_json lago_as_list

Documented in lago_as_list lago_summary_text lago_to_json

# Results that a program, such as an AI agent, can read: a plain list with a
# fixed shape (lago_as_list()), its JSON text (lago_to_json()), and a short
# summary in plain words (lago_summary_text()). The shape is described by the
# JSON Schema in inst/schema/lago-result.schema.json.

# the version of the shape, raised when a field is renamed or removed
.lago_json_schema_version <- "1"

#' A LAGO result as a plain list, as JSON, or as a short summary
#'
#' `lago_as_list()` turns a result of [lago_optimization()],
#' [lago_sensitivity()] or [lago_budget()] into a plain list with a fixed
#' shape, `lago_to_json()` writes that list as JSON text, and
#' `lago_summary_text()` gives a short summary of the result in plain words.
#' They are meant for programs, such as AI agents, that read a result instead
#' of its printout.
#'
#' The list has the fields `schema_version`, `kind` (`"lago_optimization"`,
#' `"lago_sensitivity"` or `"lago_budget"`) and `summary` (the text of
#' `lago_summary_text()`), and then the fields of the result:
#' * a `lago_optimization()` result has `inputs` (the outcome, the goal, the
#'   components and their bounds and costs), `recommendation` (the
#'   interventions by component, the cost, the estimated outcome and its
#'   interval, and whether the goal was reached), `confidence_set` (its size,
#'   and its rows when `confidence_set_rows = TRUE`) and `model` (the
#'   coefficients and their standard errors).
#' * a `lago_sensitivity()` result has `parameter` and `runs`, one entry per
#'   swept value.
#' * a `lago_budget()` result has the budget, whether it is feasible and
#'   binding, the recommendation, and the `frontier`.
#'
#' Numbers are not rounded, and `lago_to_json()` writes them with 17
#' significant digits, so they read back as the same numbers. A missing value
#' is `null`. The shape is described by the JSON Schema in
#' `system.file("schema", "lago-result.schema.json", package = "LAGOtrials")`,
#' and `schema_version` changes only when a field is renamed or removed.
#'
#' @param x A result of [lago_optimization()], [lago_sensitivity()] or
#'   [lago_budget()].
#' @param pretty A boolean. Whether to indent the JSON text. Default `FALSE`.
#' @param ... For a `lago_optimization()` result, `confidence_set_rows`, a
#'   boolean: whether to include the rows of the confidence set, which can be
#'   many. Default `TRUE`. `lago_to_json()` passes `...` on to
#'   `lago_as_list()`.
#' @return `lago_as_list()` gives a list, `lago_to_json()` a JSON string of
#'   class `"json"`, and `lago_summary_text()` a character string.
#' @examples
#' \donttest{
#' res <- lago_optimization(
#'   data = mtcars, outcome_name = "mpg", outcome_type = "continuous",
#'   glm_family = "gaussian", link = "identity",
#'   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,
#'   quiet = TRUE
#' )
#' lago_summary_text(res)
#' str(lago_as_list(res, confidence_set_rows = FALSE), max.level = 1)
#' lago_to_json(res, confidence_set_rows = FALSE, pretty = TRUE)
#' }
#' @export
lago_as_list <- function(x, ...) {
  UseMethod("lago_as_list")
}

#' @rdname lago_as_list
#' @export
lago_to_json <- function(x, ..., pretty = FALSE) {
  jsonlite::toJSON(
    lago_as_list(x, ...),
    auto_unbox = TRUE, digits = I(17), null = "null", na = "null",
    pretty = pretty
  )
}

#' @rdname lago_as_list
#' @export
lago_summary_text <- function(x) {
  UseMethod("lago_summary_text")
}

#' @export
lago_as_list.default <- function(x, ...) {
  lago_abort(
    "not_a_lago_result",
    paste0(
      "lago_as_list() takes a result of lago_optimization(), ",
      "lago_sensitivity() or lago_budget(), not an object of class '",
      paste(class(x), collapse = "', '"), "'."
    ),
    argument = "x",
    fix = "Pass the result of lago_optimization(), lago_sensitivity() or lago_budget()."
  )
}

#' @export
lago_summary_text.default <- function(x) {
  lago_abort(
    "not_a_lago_result",
    paste0(
      "lago_summary_text() takes a result of lago_optimization(), ",
      "lago_sensitivity() or lago_budget(), not an object of class '",
      paste(class(x), collapse = "', '"), "'."
    ),
    argument = "x",
    fix = "Pass the result of lago_optimization(), lago_sensitivity() or lago_budget()."
  )
}

# a numeric vector as a list named by the components, so JSON gives an object
.lago_by_component <- function(v, names) {
  stats::setNames(as.list(unname(as.numeric(v))), names)
}

# the components a result's values are given for: the main components when
# there are interaction terms
.lago_value_names <- function(x) {
  if (isTRUE(x$include_interaction_terms) && !is.null(x$main_components)) {
    x$main_components
  } else {
    x$intervention_components
  }
}

# the confidence level as a number, such as 0.95
.lago_confidence_level <- function(x) {
  alpha <- attr(x, "lago_call_args")$confidence_set_alpha
  if (!is.numeric(alpha) || length(alpha) != 1 || is.na(alpha)) alpha <- 0.05
  signif(1 - alpha, 12)
}

#' @export
lago_as_list.lago <- function(x, confidence_set_rows = TRUE, ...) {
  comps <- .lago_value_names(x)
  args <- attr(x, "lago_call_args")
  goal <- if (!is.null(x$effective_outcome_goal)) x$effective_outcome_goal else x$outcome_goal
  ci <- x$est_outcome_ci
  coefs <- tryCatch(lago_coef_table(x), error = function(e) NULL)
  cs <- x$cs
  list(
    schema_version = .lago_json_schema_version,
    kind = "lago_optimization",
    summary = lago_summary_text(x),
    inputs = list(
      outcome_name = x$outcome_name,
      outcome_type = x$outcome_type,
      family = x$family,
      link = x$link,
      outcome_goal_intention = x$outcome_goal_intention,
      outcome_goal = x$outcome_goal,
      power_goal = x$power_goal,
      effective_outcome_goal = x$effective_outcome_goal,
      intervention_components = as.list(x$intervention_components),
      main_components = if (!is.null(x$main_components)) as.list(x$main_components),
      intervention_lower_bounds = .lago_by_component(x$intervention_lower_bounds, comps),
      intervention_upper_bounds = .lago_by_component(x$intervention_upper_bounds, comps),
      cost_coefficients = stats::setNames(
        lapply(x$cost_list_of_vectors, function(v) as.list(unname(as.numeric(v)))),
        comps
      ),
      include_center_effects = isTRUE(x$include_center_effects),
      include_time_effects = isTRUE(x$include_time_effects),
      include_interaction_terms = isTRUE(x$include_interaction_terms),
      center_characteristics = as.list(x$center_characteristics),
      confidence_level = .lago_confidence_level(x),
      optimization_method = args$optimization_method,
      n_rows = x$input_nrow
    ),
    recommendation = list(
      interventions = .lago_by_component(x$rec_int, comps),
      cost = x$rec_int_cost,
      estimated_outcome = x$est_outcome_goal,
      outcome_ci = if (!is.null(ci)) list(lower = unname(ci[1]), upper = unname(ci[2])),
      goal = goal,
      goal_reached = !isTRUE(x$shrinking_method_used),
      shrinking_method_used = isTRUE(x$shrinking_method_used)
    ),
    confidence_set = list(
      computed = !is.null(x$confidence_set_size_percentage),
      size_fraction = x$confidence_set_size_percentage,
      n_rows = if (is.data.frame(cs)) nrow(cs) else 0L,
      rows = if (isTRUE(confidence_set_rows) && is.data.frame(cs)) {
        unname(lapply(seq_len(nrow(cs)), function(i) as.list(cs[i, , drop = FALSE])))
      }
    ),
    model = list(
      coefficients = if (!is.null(coefs)) {
        unname(lapply(seq_len(nrow(coefs)), function(i) {
          list(
            term = gsub("`", "", rownames(coefs)[i]),
            estimate = coefs$Estimate[i],
            std_error = coefs[["Std. Error"]][i]
          )
        }))
      },
      standard_errors = if (!is.null(x$model)) lago_se_note(x)
    )
  )
}

# the components and their values as text, such as "gear = 5 and qsec = 17"
.lago_settings_text <- function(values, comps) {
  parts <- paste0(comps, " = ", .lago_num_text(.lago_fmt_value(values)))
  if (length(parts) <= 2) {
    paste(parts, collapse = " and ")
  } else {
    paste0(paste(parts[-length(parts)], collapse = ", "), " and ", parts[length(parts)])
  }
}

#' @export
lago_summary_text.lago <- function(x) {
  comps <- .lago_value_names(x)
  goal <- if (!is.null(x$effective_outcome_goal)) x$effective_outcome_goal else x$outcome_goal
  reached <- !isTRUE(x$shrinking_method_used)
  intention <- x$outcome_goal_intention
  goal_txt <- .lago_num_text(.lago_fmt_interval(goal))
  est_txt <- .lago_num_text(.lago_fmt_estimate(x$est_outcome_goal, goal, intention, reached))
  cost_txt <- .lago_num_text(.lago_fmt_cost(x$rec_int_cost))
  settings <- .lago_settings_text(x$rec_int, comps)
  direction <- if (identical(intention, "minimize")) "at most" else "at least"
  power_txt <- if (!is.null(x$effective_outcome_goal) && !is.null(x$power_goal)) {
    paste0(
      " The goal comes from the power goal of ",
      .lago_num_text(x$power_goal), " and the outcome goal, whichever asks more."
    )
  } else {
    ""
  }
  if (reached) {
    ci <- x$est_outcome_ci
    ci_txt <- if (!is.null(ci)) {
      paste0(
        " (", .lago_confidence_label(x), " interval ",
        .lago_num_text(.lago_fmt_interval(ci[1])), " to ",
        .lago_num_text(.lago_fmt_interval(ci[2])), ")"
      )
    } else {
      ""
    }
    cs_txt <- if (!is.null(x$confidence_set_size_percentage)) {
      paste0(
        " The ", .lago_confidence_label(x), " confidence set, the interventions ",
        "whose interval includes the goal, covers ",
        .lago_num_text(.lago_round_dec(100 * x$confidence_set_size_percentage, 4, sig = TRUE)),
        "% of the searched grid."
      )
    } else {
      ""
    }
    paste0(
      "The cheapest intervention estimated to bring ", x$outcome_name, " to ",
      direction, " ", goal_txt, " sets ", settings, ". It costs ", cost_txt,
      ", and the estimated outcome is ", est_txt, ci_txt, ".", power_txt, cs_txt
    )
  } else {
    side <- if (identical(intention, "minimize")) "above" else "below"
    paste0(
      "The goal of ", direction, " ", goal_txt, " for ", x$outcome_name,
      " is not estimated to be reachable within the bounds, so the shrinking ",
      "method gave the recommendation: ", settings, ". It costs ", cost_txt,
      ", and the estimated outcome there is ", est_txt, ", ", side,
      " the goal. No confidence set is computed.", power_txt
    )
  }
}

#' @export
lago_as_list.lago_sensitivity <- function(x, ...) {
  comps <- attr(x, "component_names")
  shrunk <- attr(x, "shrinking_method_used")
  if (is.null(shrunk)) shrunk <- rep(FALSE, nrow(x))
  effective <- attr(x, "effective_outcome_goal")
  messages <- attr(x, "error_messages")
  codes <- attr(x, "error_codes")
  failed <- which(x$status != "ok")
  runs <- lapply(seq_len(nrow(x)), function(i) {
    value <- x$value[i]
    if (inherits(value, "Date") || inherits(value, "POSIXt") || is.factor(value)) {
      value <- as.character(value)
    }
    k <- match(i, failed)
    list(
      value = value,
      status = x$status[i],
      interventions = if (length(comps)) {
        .lago_by_component(unlist(x[i, comps, drop = TRUE]), comps)
      },
      cost = x$rec_int_cost[i],
      estimated_outcome = x$est_outcome_goal[i],
      effective_outcome_goal = if (length(effective) >= i) effective[i],
      shrinking_method_used = isTRUE(shrunk[i]),
      error_message = if (!is.na(k) && length(messages) >= k) unname(messages[k]),
      error_code = if (!is.na(k) && length(codes) >= k && !is.na(codes[k])) unname(codes[k])
    )
  })
  list(
    schema_version = .lago_json_schema_version,
    kind = "lago_sensitivity",
    summary = lago_summary_text(x),
    parameter = attr(x, "parameter"),
    components = as.list(comps),
    runs = runs
  )
}

#' @export
lago_summary_text.lago_sensitivity <- function(x) {
  param <- attr(x, "parameter")
  ok <- x$status == "ok"
  shrunk <- attr(x, "shrinking_method_used")
  if (is.null(shrunk)) shrunk <- rep(FALSE, nrow(x))
  value_text <- function(v) {
    if (is.numeric(v)) .lago_num_text(signif(v, 7)) else as.character(v)
  }
  out <- paste0(
    "The sweep varied ", param, " over ", nrow(x), " value",
    if (nrow(x) == 1) "" else "s", ", and ", sum(!ok), " run",
    if (sum(!ok) == 1) "" else "s", " failed."
  )
  if (any(ok)) {
    first <- which(ok)[1]
    last <- utils::tail(which(ok), 1)
    out <- paste0(
      out, " The cost is ", .lago_num_text(.lago_fmt_cost(x$rec_int_cost[first])),
      " at ", param, " = ", value_text(x$value[first])
    )
    if (last != first) {
      out <- paste0(
        out, " and ", .lago_num_text(.lago_fmt_cost(x$rec_int_cost[last])),
        " at ", param, " = ", value_text(x$value[last])
      )
    }
    out <- paste0(out, ".")
  }
  if (any(ok & shrunk)) {
    out <- paste0(
      out, " The goal was out of reach at ", param, " = ",
      paste(value_text(x$value[ok & shrunk]), collapse = ", "),
      ", where the shrinking method gave the recommendation."
    )
  }
  out
}

#' @export
lago_as_list.lago_budget <- function(x, ...) {
  fr <- x$frontier
  list(
    schema_version = .lago_json_schema_version,
    kind = "lago_budget",
    summary = lago_summary_text(x),
    budget = x$budget,
    intention = x$intention,
    feasible = isTRUE(x$feasible),
    binding = isTRUE(x$binding),
    recommendation = list(
      interventions = if (!is.null(x$rec_int)) as.list(x$rec_int),
      cost = x$rec_int_cost,
      estimated_outcome = x$est_outcome
    ),
    run_error = x$run_error,
    frontier = if (is.data.frame(fr)) {
      unname(lapply(seq_len(nrow(fr)), function(i) as.list(fr[i, , drop = FALSE])))
    }
  )
}

#' @export
lago_summary_text.lago_budget <- function(x) {
  budget_txt <- .lago_num_text(x$budget)
  if (!isTRUE(x$feasible)) {
    return(paste0(
      "No reachable intervention fits the budget of ", budget_txt, ".",
      if (!is.null(x$run_error)) paste0(" Every run failed: ", x$run_error) else ""
    ))
  }
  rec <- x$rec_int
  settings <- if (!is.null(names(rec))) {
    .lago_settings_text(unname(rec), names(rec))
  } else {
    paste(.lago_num_text(.lago_fmt_value(rec)), collapse = ", ")
  }
  best <- if (identical(x$intention, "minimize")) "lowest" else "highest"
  paste0(
    "Within the budget of ", budget_txt, ", the ", best, " estimated outcome is ",
    .lago_num_text(.lago_fmt_interval(x$est_outcome)), ", with ", settings,
    " at a cost of ", .lago_num_text(.lago_fmt_cost_within(x$rec_int_cost, x$budget)), ".",
    if (isTRUE(x$binding)) {
      " The budget binds: a larger budget would buy a better outcome."
    } else {
      " The budget does not bind: the best reachable outcome costs less."
    }
  )
}

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.