Nothing
#' Run a LAGO optimization in a point and click app
#'
#' Opens a Shiny app in your web browser that runs the whole LAGO optimization
#' without writing R code. You load a dataset, choose the outcome and the goal,
#' choose the intervention components with their bounds and costs, and say how
#' the model accounts for centers and time. The app then finds the recommended
#' intervention with [lago_optimization()] and shows the result, the confidence
#' set and the R code that reproduces the run. From that result it can sweep
#' one input with [lago_sensitivity()], find the best outcome for a budget with
#' [lago_budget()], and save a report with [lago_report()].
#'
#' The app runs on your own computer and is reachable only from it, at
#' `127.0.0.1`. Nothing is sent over the network.
#'
#' @details The app has these steps.
#'
#' * **Data:** the `data` you pass, the bundled `BB_data` or
#' `main_pulesa_data`, R's `mtcars`, or a CSV file you upload. Each example
#' opens on a setup that runs as is. Each row is one patient, or one center
#' in one period with a total, which sets `input_data_structure`.
#' * **Outcome and goal:** `outcome_name`, `outcome_type`, `outcome_goal`,
#' `outcome_goal_intention`, and for a binary outcome the power goal:
#' `power_goal`, `num_centers_in_next_stage`,
#' `patients_per_center_in_next_stage`, `power_goal_approach`, `icc` and
#' `power_goal_cluster_id`. The app builds the `group` column from the
#' treatment arm column you choose. For center level data the outcome comes
#' from a successes or proportion column and a total column, from which the
#' app builds the `proportion` and `center_sample_size` columns. Under
#' "Outcome model" are `glm_family`
#' for a continuous outcome, `link`, and `weights` from a column you choose.
#' * **Intervention and costs:** `intervention_components`, their bounds, and
#' the costs as `unit_costs` with `default_cost_fxn_type` and
#' `unit_cost_doses`, or as `cost_list_of_vectors`. The "Shape the costs
#' visually" button opens the cost designer of [visualize_cost()] in a dialog,
#' which starts on the costs in use and puts the shaped costs in as cost
#' coefficients. Interaction terms set
#' `include_interaction_terms` and `main_components`, and the app builds each
#' product column. Under "Confidence set" are `include_confidence_set`,
#' `confidence_set_alpha` as a confidence level, and
#' `confidence_set_grid_step_size`. Under "Optimizer" are
#' `optimization_method` and `optimization_grid_search_step_size`, and under
#' "Previous stage" is `prev_recommended_interventions`.
#' * **Centers, time and covariates:** `center_characteristics` with their
#' values, or fixed center effects with `include_center_effects` and
#' `center_effects_optimization_values` or your own
#' `center_weights_for_outcome_goal`, fixed time effects with
#' `include_time_effects` and `time_effect_optimization_value`, and
#' `additional_covariates`. The app builds the `center` and `period` columns
#' from the columns you choose.
#'
#' A step that needs attention says what to change, and the run button stays
#' off until every step is ready. Warnings from the package are listed with
#' the result.
#'
#' After a run, these tabs start from its result.
#'
#' * **Results:** the recommendation, the confidence set with a CSV download,
#' the outcome model, the intervention test, and the report download of
#' [lago_report()], which needs the rmarkdown, knitr and jsonlite packages
#' and pandoc.
#' * **Sensitivity:** [lago_sensitivity()] with `parameter` and `values`. It
#' varies the outcome goal, a multiplier of all costs, and with a power goal
#' the power goal, the centers and patients of the next stage, and the ICC.
#' With time effects it varies the period. The values are even steps from a
#' start to an end, or a typed list. A plot, a table and a CSV download show
#' the result.
#' * **Budget:** [lago_budget()] with `budget` and `n_grid`. The budget starts
#' at the cost of the recommendation. The best outcome it buys can be put in
#' as the outcome goal.
#' * **R code:** the code of the run, followed by the code of the last sweep
#' and budget search of that result.
#'
#' **Save settings** downloads every setting as an `.rds` file, without the
#' data, and **Load settings** puts them back on the same data. Started from a
#' `lago` result, the app opens on the settings of its call and lists any it
#' cannot show. A grid step that the call left to the package is put in as
#' the step the package used, so a new run gives the same result.
#'
#' A column name of an uploaded file that R cannot use is changed to one it
#' can, and a name with letters that are not ASCII, such as an accent, is
#' changed to ASCII, so the shown code runs in any locale. Step 1 lists the
#' names that changed.
#'
#' @param data A data.frame to start with, a `lago` result of
#' [lago_optimization()] to start from its data and settings, or `NULL` to
#' start with the bundled `BB_data` example.
#' @param launch.browser Whether to open the app in your web browser. By default
#' it opens in an interactive session.
#' @param port The port to listen on, or `NULL` for a free one.
#'
#' @return Invisibly, when you click **Done** or close the browser tab, a list
#' with the last `result` of [lago_optimization()] for the settings in the
#' app (or `NULL` if nothing was run since a reset, a new dataset or loaded
#' settings, or the last run failed), the last `sensitivity` of
#' [lago_sensitivity()] and `budget` of [lago_budget()] run from it (or `NULL`), the R `code` of all of them as a
#' character vector, and the `arguments` of the optimization. The same list
#' is stored in the `lago_app_result` option.
#'
#' @seealso [lago_optimization()] for the function the app runs,
#' [lago_sensitivity()], [lago_budget()] and [lago_report()] for the tabs
#' that start from its result, and [visualize_cost()] for the cost designer.
#'
#' @examples
#' if (interactive()) {
#' out <- lago_app()
#' out$result
#' cat(out$code, sep = "\n")
#' # change a setting of that result and run it again
#' lago_app(out$result)
#' }
#'
#' @export
lago_app <- function(data = NULL,
launch.browser = interactive(),
port = NULL) {
data_name <- if (is.null(data)) NULL else deparse1(substitute(data))
start <- NULL
if (inherits(data, "lago")) {
args <- attr(data, "lago_call_args")
if (is.null(args) || !is.data.frame(args$data)) {
lago_abort("lago_result_without_data",
"This `lago` result does not carry the data of its call. Refit it with the current version of the package.",
argument = "data", fix = "Run lago_optimization() again with the current version of the package and pass its result.",
call = NULL
)
}
start <- .app_spec_from_args(args)
# the code reads the data back from the result, as the call used it
data_name <- sprintf("attr(%s, \"lago_call_args\")$data", data_name)
data <- args$data
}
if (!is.null(data) && !is.data.frame(data)) {
lago_abort("app_data_invalid",
"`data` must be a data.frame or a `lago` result, or NULL to start with the BB_data example.",
argument = "data", fix = "Pass a data frame, a result of lago_optimization(), or NULL.",
call = NULL
)
}
app <- .build_lago_app(data = data, data_name = data_name, start = start)
on.exit(try(shiny::removeResourcePath("lago_cost_assets"), silent = TRUE), add = TRUE)
old <- options(shiny.maxRequestSize = 100 * 1024^2)
on.exit(options(old), add = TRUE)
out <- .lago_run_app(app, port = port, launch.browser = launch.browser)
options(lago_app_result = out)
invisible(out)
}
# Runs the app on the loopback interface only, so no other machine can reach
# it. There is no way to widen the bind.
.lago_run_app <- function(app, port = NULL, launch.browser = interactive()) {
shiny::runApp(app, host = "127.0.0.1", port = port, launch.browser = launch.browser)
}
# A label with a "?" that opens a short explanation.
.app_help <- function(label, text) {
htmltools::tags$span(
label, " ",
bslib::popover(
htmltools::tags$span(
class = "lago-help", tabindex = "0", role = "button",
`aria-label` = paste("Help:", label), "?"
),
text
)
)
}
.app_next <- function(id, label) {
htmltools::div(class = "lago-next", shiny::actionButton(id, label, class = "btn-outline-primary btn-sm"))
}
.app_css <- "
.lago-help { display:inline-block; width:1.25em; height:1.25em; line-height:1.25em;
border-radius:50%; background:#e7eef7; color:#1f4e79; text-align:center;
font-size:.8em; font-weight:600; cursor:pointer; }
.lago-help:focus { outline:2px solid #1f4e79; }
.lago-next { margin-top:1rem; text-align:right; }
.lago-settings { margin-top:.75rem; }
.lago-settings .form-group { margin-top:.5rem; margin-bottom:0; }
.lago-step { display:flex; gap:.5rem; align-items:flex-start; margin-bottom:.5rem; }
.lago-step .lago-mark { width:1.4em; flex:none; text-align:center; font-weight:700; }
.lago-step.ok .lago-mark { color:#1a7f37; }
.lago-step.todo .lago-mark { color:#b35900; }
.lago-step .msg { font-size:.85em; color:#555; }
.lago-stale { opacity:.55; }
.lago-comp { border:1px solid #dee2e6; border-radius:.5rem; padding:.6rem .8rem; margin-bottom:.6rem; }
.lago-comp h6 { margin:0 0 .4rem 0; }
.lago-intro { color:#444; }
.lago-notes li { white-space:pre-line; margin-bottom:.4rem; }
"
.build_lago_app <- function(data = NULL, data_name = NULL, start = NULL) {
# the cost designer's D3 curves, served from the package, with no CDN
shiny::addResourcePath("lago_cost_assets", system.file("js", package = "LAGOtrials"))
sources <- c(
"BetterBirth example (BB_data)" = "BB_data",
"PULESA example, with one row per clinic and period (main_pulesa_data)" = "main_pulesa_data",
"mtcars, an R example with a continuous outcome" = "mtcars",
"Upload a CSV file" = "upload"
)
if (!is.null(data)) {
label <- if (is.null(start)) sprintf("Your data (%s)", data_name) else "The data and settings of your result"
sources <- c(stats::setNames("passed", label), sources)
}
ui <- bslib::page_sidebar(
title = "LAGO trial optimizer",
theme = bslib::bs_theme(version = 5),
sidebar = bslib::sidebar(
width = 330,
shinyjs::useShinyjs(),
htmltools::tags$head(
htmltools::tags$style(htmltools::HTML(.app_css)),
htmltools::tags$script(src = "lago_cost_assets/d3.v7.min.js"),
htmltools::tags$script(src = "lago_cost_assets/cost-curves.js")
),
htmltools::tags$strong("Ready to run"),
shiny::uiOutput("checklist"),
bslib::input_task_button("run", "Find recommendation", label_busy = "Running..."),
shiny::uiOutput("run_hint"),
htmltools::hr(),
shiny::actionButton("reset", "Reset this dataset's settings", class = "btn-outline-secondary btn-sm"),
htmltools::div(
class = "lago-settings",
shiny::downloadButton("save_settings", "Save settings", class = "btn-outline-secondary btn-sm"),
shiny::fileInput("load_settings", .app_help("Load settings", "A settings file saved by this app. Load the data it was saved with first, as the file holds the settings and not the data."), accept = ".rds", buttonLabel = "Choose", placeholder = "No file")
),
shiny::actionButton("done", "Done: return to R", class = "btn-success"),
htmltools::tags$small(class = "text-muted", "Done closes the app and returns the last result to R.")
),
bslib::navset_card_tab(
id = "steps",
bslib::nav_panel(
"1. Data",
value = "data",
htmltools::p(class = "lago-intro", "Choose the data from the first stage of the trial. Each example opens on a setup that runs as it is, so you can press Find recommendation right away."),
shiny::radioButtons("source", .app_help("Data", "The first stage data. The outcome and the components must be numeric columns."), choices = sources, selected = if (is.null(data)) "BB_data" else "passed"),
shiny::radioButtons(
"structure", .app_help("Each row is", "Each row is one patient, with that patient's outcome. Or each row is one center in one period, with the number of its patients who had the outcome and the number of its patients. The outcome of center level data is binary."),
c("One patient" = "individual", "One center and period, with a total" = "center"), inline = TRUE
),
shiny::conditionalPanel(
"input.source == 'upload'",
shiny::fileInput("file", .app_help("CSV file", "A text file with a header row, and one row per patient or one row per center and period. It stays on your computer."), accept = c(".csv", "text/csv")),
bslib::layout_columns(
shiny::selectInput("sep", .app_help("Separator", "The character between the values of a row. Many European files use a semicolon."), c("Comma" = ",", "Semicolon" = ";", "Tab" = "\t")),
shiny::selectInput("dec", .app_help("Decimal mark", "The character before the decimals, such as the point in 2.5 or the comma in 2,5."), c("Point" = ".", "Comma" = ","))
)
),
shiny::uiOutput("data_info"),
bslib::accordion(
open = FALSE,
bslib::accordion_panel("Columns", shiny::tableOutput("data_columns")),
bslib::accordion_panel("First rows", shiny::tableOutput("data_head"))
),
.app_next("next_data", "Next: outcome and goal")
),
bslib::nav_panel(
"2. Outcome and goal",
value = "outcome",
htmltools::p(class = "lago-intro", "Say what the trial measures and what it should reach."),
shiny::conditionalPanel(
"input.structure != 'center'",
bslib::layout_columns(
shiny::selectInput("outcome", .app_help("Outcome column", "The column that holds the outcome of each patient, or of each row."), choices = NULL),
htmltools::div(
shiny::radioButtons("outcome_type", .app_help("Outcome type", "Binary for an outcome that is 0 or 1 for each patient, such as whether a practice was followed. Continuous for a measured value."), c("Binary (0/1)" = "binary", "Continuous" = "continuous"), inline = TRUE),
shiny::uiOutput("outcome_type_note")
)
)
),
shiny::conditionalPanel(
"input.structure == 'center'",
htmltools::p(class = "text-muted", "Each row is a center in one period. The outcome is the share of its patients who had it, and each row counts as many patients as its total."),
bslib::layout_columns(
fill = FALSE,
shiny::radioButtons("cl_kind", .app_help("The data gives", "The number of patients who had the outcome, or the share of patients who had it, as a number between 0 and 1."), c("Successes and a total" = "successes", "A proportion and a total" = "proportion")),
shiny::selectInput("cl_value", .app_help("Successes or proportion column", "The column with the number of patients of the row who had the outcome, or with their share."), choices = NULL, selectize = FALSE),
shiny::selectInput("cl_total", .app_help("Total column", "The column with the number of patients the row stands for."), choices = NULL, selectize = FALSE)
)
),
shiny::radioButtons(
"goal_mode", .app_help("Goal", "An outcome goal is the outcome level the next stage should reach. A power goal asks for enough statistical power in the next stage to show a benefit of the intervention, and works only for a binary outcome. With both, the higher of the two outcome levels is used."),
c("Outcome goal" = "outcome", "Power goal" = "power", "Both (the higher one is used)" = "both"),
inline = TRUE
),
bslib::layout_columns(
shiny::conditionalPanel(
"input.goal_mode != 'power'",
shiny::numericInput("goal", .app_help("Outcome goal", "The outcome level to reach. For a binary outcome it is a probability between 0 and 1."), value = 0.85, step = 0.01)
),
shiny::radioButtons(
"intention", .app_help("Direction", "Maximize when a higher outcome is better, such as adherence. Minimize when a lower outcome is better, such as a complication rate. The goal is the level to reach either way."),
c("Maximize" = "maximize", "Minimize" = "minimize"), inline = TRUE
)
),
shiny::conditionalPanel(
"input.goal_mode != 'outcome'",
bslib::card(
bslib::card_header("Power goal"),
bslib::layout_columns(
shiny::selectInput("arm_col", .app_help("Treatment arm column", "The column that says which patients got the intervention in the first stage."), choices = NULL),
shiny::selectInput("arm_value", .app_help("Value that means treatment", "The value of the treatment arm column for patients who got the intervention."), choices = NULL)
),
bslib::layout_columns(
shiny::numericInput("power_goal", .app_help("Power goal", "The statistical power the next stage should have, such as 0.8."), value = 0.8, min = 0, max = 1, step = 0.05),
shiny::numericInput("n_centers", .app_help("Centers in the next stage", "How many centers the next stage of the trial will have."), value = 10, min = 1, step = 1),
shiny::numericInput("n_patients", .app_help("Patients per center", "How many patients each center of the next stage will enroll."), value = 30, min = 1, step = 1)
),
bslib::accordion(
open = FALSE,
bslib::accordion_panel(
"More power options",
shiny::radioButtons("approach", .app_help("Approach", "Unconditional plans the power of the next stage alone. Conditional also counts the first stage data."), c("Unconditional" = "unconditional", "Conditional" = "conditional"), inline = TRUE),
bslib::layout_columns(
shiny::textInput("icc", .app_help("ICC (optional)", "The intraclass correlation of the outcome within a center, such as 0.05. Give two values, such as 0.04, 0.06, for the control and the treatment arm. Leave it empty to ignore clustering."), value = ""),
shiny::selectInput("cluster_col", .app_help("Center column for the ICC", "The column that says which center each patient was in. Only columns with at least two centers that have an observed outcome in each arm are listed."), choices = NULL, selectize = FALSE)
)
)
)
)
),
bslib::accordion(
open = FALSE,
bslib::accordion_panel(
"Outcome model (optional)",
htmltools::p(class = "text-muted", "The usual model suits most trials. Change it only when you know the model you need."),
bslib::layout_columns(
fill = FALSE,
shiny::conditionalPanel(
"input.outcome_type == 'continuous'",
shiny::selectInput("glm_family", .app_help("Model family", "Normal suits a measured outcome. Proportion suits an outcome between 0 and 1, such as the share of patients in a center who got a treatment, and fits the quasibinomial family."), c("Normal (gaussian)" = "default", "Proportion between 0 and 1 (quasibinomial)" = "quasibinomial"), selectize = FALSE)
),
shiny::selectInput("link", .app_help("Link", "Logit models the outcome on the log odds scale, the usual one for a binary outcome or a proportion. Identity models the outcome as it is, the usual one for a measured outcome. For a binary outcome, identity gives a linear probability model, which cannot always be fitted. Use logit if it fails. For a measured outcome, logit works only when the outcome is between 0 and 1."), c("The usual one for the model" = "default", "Logit" = "logit", "Identity" = "identity"), selectize = FALSE),
shiny::selectInput("weights_col", .app_help("Weights (optional)", "A numeric column that gives each row its weight in the model, such as the number of patients a row stands for. The weights must be finite numbers of 0 or more."), choices = c("No weights" = ""), selectize = FALSE)
)
)
),
shiny::uiOutput("notes_outcome"),
.app_next("next_outcome", "Next: intervention and costs")
),
bslib::nav_panel(
"3. Intervention and costs",
value = "intervention",
htmltools::p(class = "lago-intro", "Choose the parts of the intervention to optimize, the range each may take, and what each costs."),
shiny::selectizeInput("components", .app_help("Intervention components", "The parts of the intervention whose levels LAGO recommends, such as the number of coaching visits."), choices = NULL, multiple = TRUE),
shiny::radioButtons(
"cost_mode", .app_help("Costs", "A cost per unit gives a total cost of unit cost times the level. Cost coefficients give any polynomial: c0 + c1 x + c2 x^2 and so on."),
c("Cost per unit" = "unit", "Cost coefficients" = "coef"), inline = TRUE
),
shiny::conditionalPanel(
"input.cost_mode == 'unit'",
shiny::radioButtons(
"cost_type", .app_help("Cost shape", "Linear keeps the same cost for each unit. Cubic lets the cost per unit change with the level, with the unit cost as its average, or as its value at the dose where it was measured."),
c("Linear" = "linear", "Cubic" = "cubic"), inline = TRUE
)
),
htmltools::div(
class = "mb-3",
shiny::actionButton("open_designer", "Shape the costs visually", icon = shiny::icon("chart-line"), class = "btn-outline-primary btn-sm"),
" ",
.app_help("", "Opens the cost designer, which draws the total and marginal cost of each component and lets you shape them with sliders or by dragging the curve. Its button \"Use these costs\" then puts them in as cost coefficients.")
),
shiny::uiOutput("component_rows"),
shiny::uiOutput("notes_intervention"),
bslib::accordion(
open = FALSE,
bslib::accordion_panel(
"Interactions (optional)",
htmltools::p("Model the product of two components when the effect of one depends on the other. The recommendation is still given for the components themselves."),
shiny::uiOutput("interaction_ui")
),
bslib::accordion_panel(
"Confidence set",
shiny::checkboxInput("include_cs", "Compute the confidence set (slower)", value = TRUE),
htmltools::p(class = "text-muted", "The confidence set holds the interventions whose outcome may reach the goal, given the uncertainty of the first stage. It is found on a grid, with 20 steps across each range unless you set the steps."),
shiny::conditionalPanel(
"input.include_cs",
shiny::selectInput("cs_level", .app_help("Confidence level", "How sure the set is to hold the interventions that reach the goal. 95% is the usual level. A higher level gives a larger set."), c("90%" = "0.9", "95%" = "0.95", "99%" = "0.99"), selected = "0.95", selectize = FALSE),
shiny::uiOutput("cs_steps_ui")
)
),
bslib::accordion_panel(
"Optimizer",
shiny::radioButtons("method", .app_help("Method", "Numerical searches for the cheapest intervention that reaches the goal, and is fast. Grid search tries every intervention on a grid and keeps the cheapest one that reaches the goal, which is slower and finds the best point of the grid only."), c("Numerical" = "numerical", "Grid search" = "grid_search"), inline = TRUE),
shiny::conditionalPanel("input.method == 'grid_search'", shiny::uiOutput("grid_steps_ui"))
),
bslib::accordion_panel(
"Previous stage (optional)",
htmltools::p("When the goal cannot be reached within the bounds, the shrinking method shrinks the recommendation toward a starting intervention. The start is the average intervention in the data, kept within the bounds, or the recommendation of the previous stage when you give it."),
shiny::checkboxInput("prev_on", "Give the recommendation of the previous stage", value = FALSE),
shiny::conditionalPanel(
"input.prev_on",
shiny::uiOutput("prev_ui"),
shiny::actionButton("use_rec_as_prev", "Use the current recommendation", class = "btn-outline-primary btn-sm")
)
)
),
.app_next("next_intervention", "Next: centers, time and covariates")
),
bslib::nav_panel(
"4. Centers, time and covariates",
value = "centers",
htmltools::p(class = "lago-intro", "Optional. Say how the model accounts for differences between centers and over time."),
shiny::radioButtons(
"center_mode", .app_help("Centers", "Center characteristics, such as size, are held at the values you set, so the recommendation is for a center like that. A fixed effect per center fits each center its own level, and the recommendation is for the average center or for the center you choose."),
c("None" = "none", "By center characteristics" = "chars", "Fixed effect per center" = "effects"),
inline = TRUE
),
shiny::conditionalPanel(
"input.center_mode == 'chars'",
shiny::selectizeInput("center_chars", .app_help("Center characteristics", "Numeric columns that describe a center, such as its size. A column with two text values can be used after recoding it as 0 and 1."), choices = NULL, multiple = TRUE),
shiny::uiOutput("center_char_values")
),
shiny::conditionalPanel(
"input.center_mode == 'effects'",
bslib::layout_columns(
shiny::selectInput("center_col", .app_help("Column that identifies the centers", "The column that says which center each row belongs to."), choices = NULL, selectize = FALSE),
shiny::selectInput("center_for", .app_help("Optimize for", "The weighted average center weighs each center by its share of the patients, or by the weights you set below. Or choose one center to plan for."), choices = NULL, selectize = FALSE)
),
shiny::conditionalPanel(
"input.center_for == ''",
shiny::checkboxInput("cw_on", .app_help("Set the weight of each center", "By default each center counts by its share of the patients. Set your own weights to plan for another mix of centers. They must add up to 1, and a center may get 0."), value = FALSE),
shiny::conditionalPanel("input.cw_on", shiny::uiOutput("cw_ui"), shiny::uiOutput("cw_sum"))
)
),
shiny::checkboxInput("time_on", .app_help("Fixed time effects", "Fit each time period its own level, and recommend for the period you choose."), value = FALSE),
shiny::conditionalPanel(
"input.time_on",
bslib::layout_columns(
shiny::selectInput("period_col", .app_help("Column that holds the period", "The column that says in which time period each patient was seen."), choices = NULL, selectize = FALSE),
shiny::selectInput("period_value", .app_help("Period to optimize for", "The period whose effect the recommendation assumes, often the latest one."), choices = NULL, selectize = FALSE)
)
),
shiny::uiOutput("notes_centers"),
shiny::selectizeInput("covariates", .app_help("Additional covariates (optional)", "Other columns the outcome model adjusts for. When recommending, a numeric covariate is held at 0 and a factor at its first level."), choices = NULL, multiple = TRUE),
.app_next("next_centers", "Find recommendation")
),
bslib::nav_panel("Results", value = "results", shiny::uiOutput("results")),
bslib::nav_panel(
"Sensitivity",
value = "sweep",
htmltools::p(class = "lago-intro", "See how the recommendation moves when one input is different. Each value is one optimization of the result in Results, without the confidence set."),
shiny::uiOutput("sweep_gate"),
bslib::layout_columns(
fill = FALSE,
shiny::selectInput("sweep_param", .app_help("Input to vary", "The input whose value changes from run to run. Everything else stays as in Results. A cost multiplier of 1.2 makes every cost 20% higher."), choices = NULL, selectize = FALSE),
shiny::conditionalPanel(
"input.sweep_param != 'time_effect_optimization_value'",
shiny::radioButtons("sweep_how", .app_help("Values", "Even steps from From to To, or a list of the values you want."), c("Even steps" = "steps", "Type the values" = "typed"), inline = TRUE)
)
),
shiny::conditionalPanel(
"input.sweep_param == 'time_effect_optimization_value'",
shiny::selectizeInput("sweep_periods", .app_help("Periods", "The periods to optimize for, one run each."), choices = NULL, multiple = TRUE, width = "100%")
),
shiny::conditionalPanel(
"input.sweep_param != 'time_effect_optimization_value' && input.sweep_how == 'steps'",
bslib::layout_columns(
fill = FALSE,
shiny::numericInput("sweep_from", "From", value = NA),
shiny::numericInput("sweep_to", "To", value = NA),
shiny::numericInput("sweep_steps", .app_help("Steps", "How many values from From to To, ends included. From 2 to 25."), value = 5, min = 2, max = 25, step = 1)
)
),
shiny::conditionalPanel(
"input.sweep_param != 'time_effect_optimization_value' && input.sweep_how == 'typed'",
shiny::textInput("sweep_typed", .app_help("Values", "Numbers separated by commas, such as 0.7, 0.8, 0.9. Up to 25 values."), value = "", width = "100%")
),
shiny::uiOutput("sweep_preview"),
bslib::input_task_button("run_sweep", "Run the sweep", label_busy = "Running..."),
shiny::uiOutput("sweep_results")
),
bslib::nav_panel(
"Budget",
value = "budget",
htmltools::p(class = "lago-intro", "Find the best outcome a budget can buy, and the intervention that reaches it. The search runs the result in Results across a range of outcome goals, without the confidence set."),
shiny::uiOutput("budget_gate"),
shiny::numericInput("budget", .app_help("Budget", "The most the intervention may cost, in the units of the costs in step 3. It starts at the cost of the recommendation when that is above 0."), value = NA, min = 0),
bslib::accordion(
open = FALSE,
bslib::accordion_panel(
"More options",
shiny::numericInput("budget_grid", .app_help("Goals to try", "How many outcome goals the first pass tries, from 2 to 25. A second pass tries as many again near the budget. Fewer goals are faster, and more goals give an answer closer to the best the budget can buy."), value = 25, min = 2, max = 25, step = 1)
)
),
shiny::uiOutput("budget_hint"),
bslib::input_task_button("run_budget", "Find the best outcome for this budget", label_busy = "Searching..."),
shiny::uiOutput("budget_results")
),
bslib::nav_panel(
"R code",
value = "code",
htmltools::p(class = "lago-intro", "This code reproduces the current settings. Copy it into an R script to rerun or change the analysis."),
shiny::verbatimTextOutput("code"),
shiny::downloadButton("download_code", "Download .R file", class = "btn-outline-primary btn-sm")
)
)
)
# Shared by every browser session of this app: the last result, so a page
# refresh keeps it, and the open sessions, so the app stops only when the
# last tab is closed and not on a refresh.
shared <- new.env(parent = emptyenv())
shared$result <- list(result = NULL, sensitivity = NULL, budget = NULL, code = NULL, arguments = NULL)
shared$sessions <- 0L
# the report needs rmarkdown, knitr, jsonlite and pandoc
report_missing <- .app_report_missing()
server <- function(input, output, session) {
shared$sessions <- shared$sessions + 1L
loaded <- shiny::reactiveVal(NULL)
upload_error <- shiny::reactiveVal(NULL)
# TRUE until the first data of this browser session is loaded
first_load <- shiny::reactiveVal(TRUE)
# the spec the inputs start from, and the value it gives one input: field
# of the spec at the place of key in its keys, or the fallback
start_spec <- shiny::reactiveVal(NULL)
interactions_started <- NULL
start_value <- function(field, key, fallback, keys = "components") {
s <- shiny::isolate(start_spec())
k <- if (is.null(s)) NA else match(key, s[[keys]])
v <- if (is.na(k)) NULL else s[[field]]
x <- if (length(v) < k || is.na(k)) NULL else if (is.list(v)) v[[k]] else v[k]
if (is.null(x) || (length(x) == 1 && is.na(x))) fallback else x
}
run_state <- shiny::reactiveVal(NULL)
# counts the runs, so a sweep or budget search knows which result it used
run_id <- shiny::reactiveVal(0L)
sweep_state <- shiny::reactiveVal(NULL)
budget_state <- shiny::reactiveVal(NULL)
# bumped on every load and reset, so the inputs of the component rows get
# new ids and a value typed for another dataset is never reused
generation <- shiny::reactiveVal(0L)
last_outcome <- shiny::reactiveVal(NULL)
# TRUE during the update cycle of a load or reset. The observers below then
# leave every choice to apply_defaults(), as they would otherwise send the
# old selections back. In the next cycle the browser has the new values.
applying_defaults <- shiny::reactiveVal(FALSE)
load_data <- function(source) {
switch(source,
passed = list(data = data, name = data_name, start = start),
BB_data = list(data = as.data.frame(LAGOtrials::BB_data), name = "BB_data"),
main_pulesa_data = list(data = as.data.frame(LAGOtrials::main_pulesa_data), name = "main_pulesa_data"),
mtcars = list(data = datasets::mtcars, name = "mtcars"),
upload = {
f <- input$file
if (is.null(f)) {
NULL
} else {
encoding <- .app_file_encoding(f$datapath)
d <- tryCatch(.app_read_csv(f$datapath, input$sep, input$dec, encoding), error = function(e) e)
if (encoding %in% c("UTF-16", "UTF-32")) {
list(error = sprintf("The file is saved as %s text, which the app cannot read. Save it as CSV UTF-8, for example with Save As and the type CSV UTF-8 in Excel, and upload it again.", encoding))
} else if (.app_has_nul(f$datapath)) {
list(error = .app_nul_message())
} else if (.app_csv_blank(f$datapath, encoding)) {
list(error = "The file is empty. Choose the CSV file that holds the data.")
} else if (is.data.frame(d) && !nrow(d)) {
list(error = "The file has a header row but no rows of data. Add the data and upload the file again.")
} else if (inherits(d, "error")) {
list(error = sprintf(
"The file could not be read with these settings (%s). Check that the separator and the decimal mark match the file.",
conditionMessage(d)
))
} else {
list(
data = d, name = .app_read_csv_code(f$name, input$sep, input$dec, encoding, .app_csv_header(f$datapath, input$sep, encoding)),
hint = .app_csv_hint(d, input$sep, input$dec), renamed = .app_renamed(f$datapath, input$sep, d, encoding),
encoding = encoding
)
}
}
}
)
}
# Put a whole spec into the app: the dataset's defaults on a load or reset,
# or loaded settings. Inputs drawn later, such as the bounds of each
# component, take their first value from start_spec().
apply_defaults <- function(d, name, spec = .app_defaults(d, name), clear_result = TRUE) {
start_spec(spec)
# Done returns the result of the settings in the app, so new settings or
# data drop the last one. The first load of a page keeps it, so a refresh
# still returns the result run before it.
if (clear_result) shared$result <- list(result = NULL, sensitivity = NULL, budget = NULL, code = NULL, arguments = NULL)
generation(generation() + 1L)
last_outcome(spec$outcome)
applying_defaults(TRUE)
session$onFlushed(function() applying_defaults(FALSE), once = TRUE)
ch <- .app_choices(d, spec)
# center level settings name the built proportion, which is no column of the data
shiny::updateSelectInput(session, "outcome", choices = ch$outcomes, selected = if (.app_center_level(spec)) spec$cl_value else spec$outcome)
shiny::updateRadioButtons(session, "outcome_type", selected = spec$outcome_type)
shiny::updateNumericInput(session, "goal", value = spec$goal)
shiny::updateRadioButtons(session, "goal_mode", selected = spec$goal_mode)
shiny::updateRadioButtons(session, "intention", selected = spec$intention)
shiny::updateSelectizeInput(session, "components", choices = ch$components, selected = spec$components)
shiny::updateRadioButtons(session, "cost_mode", selected = spec$cost_mode)
shiny::updateRadioButtons(session, "cost_type", selected = spec$cost_type)
shiny::updateCheckboxInput(session, "include_cs", value = spec$include_cs)
shiny::updateRadioButtons(session, "structure", selected = spec$structure)
shiny::updateRadioButtons(session, "cl_kind", selected = spec$cl_kind)
shiny::updateSelectInput(session, "cl_value", choices = c("Choose a column" = "", ch$counts), selected = spec$cl_value)
shiny::updateSelectInput(session, "cl_total", choices = c("Choose a column" = "", ch$counts), selected = spec$cl_total)
shiny::updateCheckboxInput(session, "cw_on", value = spec$cw_on)
shiny::updateCheckboxGroupInput(session, "interactions", selected = spec$interactions)
shiny::updateSelectInput(session, "arm_col", choices = ch$arms, selected = ch$arm)
shiny::updateSelectInput(session, "arm_value", choices = ch$arm_values, selected = ch$arm_value)
shiny::updateNumericInput(session, "power_goal", value = spec$power_goal)
shiny::updateNumericInput(session, "n_centers", value = spec$n_centers)
shiny::updateNumericInput(session, "n_patients", value = spec$n_patients)
shiny::updateRadioButtons(session, "approach", selected = spec$approach)
shiny::updateTextInput(session, "icc", value = paste(format(spec$icc, digits = 15, trim = TRUE), collapse = ", "))
shiny::updateSelectInput(session, "cluster_col", choices = c("Choose a column" = "", ch$clusters), selected = intersect(spec$cluster_col, ch$clusters))
shiny::updateRadioButtons(session, "center_mode", selected = spec$center_mode)
shiny::updateSelectizeInput(session, "center_chars", choices = ch$center_chars, selected = intersect(spec$center_chars, ch$center_chars))
shiny::updateSelectInput(session, "center_col", choices = c("Choose a column" = "", ch$others), selected = ch$center_col)
shiny::updateSelectInput(session, "center_for", choices = c("The weighted average center" = "", ch$centers), selected = intersect(spec$center_for, ch$centers))
shiny::updateCheckboxInput(session, "time_on", value = spec$time_on)
shiny::updateSelectInput(session, "period_col", choices = c("Choose a column" = "", ch$others), selected = ch$period_col)
shiny::updateSelectInput(session, "period_value", choices = ch$periods, selected = ch$period)
shiny::updateSelectizeInput(session, "covariates", choices = ch$covariates, selected = intersect(spec$covariates, ch$covariates))
shiny::updateSelectInput(session, "glm_family", selected = spec$glm_family)
shiny::updateSelectInput(session, "link", selected = spec$link)
shiny::updateSelectInput(session, "weights_col", choices = c("No weights" = "", ch$weights), selected = intersect(spec$weights_col, ch$weights))
shiny::updateSelectInput(session, "cs_level", selected = as.character(spec$cs_level))
shiny::updateRadioButtons(session, "method", selected = spec$method)
shiny::updateCheckboxInput(session, "prev_on", value = spec$prev_on)
designer_costs(list())
run_state(NULL)
sweep_state(NULL)
budget_state(NULL)
}
shiny::observeEvent(list(input$source, input$file, input$sep, input$dec), {
got <- load_data(input$source)
upload_error(got$error)
if (!is.null(got$error)) got <- NULL
loaded(got)
if (!is.null(got)) {
start_from(got, clear_result = !first_load())
} else if (!first_load()) {
# no data, so Done returns no result, and the tabs show none
shared$result <- list(result = NULL, sensitivity = NULL, budget = NULL, code = NULL, arguments = NULL)
run_state(NULL)
sweep_state(NULL)
budget_state(NULL)
}
first_load(FALSE)
})
shiny::observeEvent(input$reset, {
got <- loaded()
if (!is.null(got)) start_from(got)
})
# a result passed to lago_app() starts, and resets, on its own settings
start_from <- function(got, clear_result = TRUE) {
if (is.null(got$start)) {
apply_defaults(got$data, got$name, clear_result = clear_result)
} else {
spec <- got$start$spec
spec$data_name <- got$name
apply_defaults(got$data, got$name, spec, clear_result = clear_result)
}
}
output$save_settings <- shiny::downloadHandler(
filename = function() "lago_app_settings.rds",
content = function(file) {
got <- loaded()
# how to get this data back, for a message on loading
label <- switch(input$source,
upload = sprintf("the file %s", input$file$name),
passed = if (is.null(got$start)) sprintf("your data %s", got$name) else "the data of the result the app was started from, with lago_app() on that result",
sprintf("the %s example", got$name)
)
saveRDS(list(lago_app_settings = 1L, data_name = got$name, data_label = label, spec = spec()), file)
}
)
shiny::observeEvent(input$load_settings, {
got <- loaded()
f <- input$load_settings
shiny::req(f)
x <- tryCatch(readRDS(f$datapath), error = function(e) NULL)
if (inherits(x, "lago")) {
shiny::showNotification("This file holds a result of lago_optimization(), not settings. To start from it, read it in R with readRDS() and pass it to lago_app().", type = "error", duration = NULL)
return()
}
version <- if (is.list(x) && is.numeric(x$lago_app_settings) && length(x$lago_app_settings) == 1) x$lago_app_settings else NA
if (isTRUE(version > 1)) {
shiny::showNotification("These settings were saved by a newer version of LAGOtrials. Update the package to load them.", type = "error", duration = NULL)
return()
}
if (!identical(version, 1L) || !is.list(x$spec)) {
shiny::showNotification("This file is not a settings file of this app.", type = "error", duration = NULL)
return()
}
if (is.null(got)) {
shiny::showNotification("Load the data first, then the settings.", type = "error", duration = NULL)
return()
}
# each saved field replaces its default whole, so a list such as the
# cost coefficients is kept as it was saved
spec <- .app_empty_spec()
for (nm in names(x$spec)) {
if (!is.null(x$spec[[nm]])) spec[[nm]] <- x$spec[[nm]]
}
missing <- setdiff(.app_spec_columns(spec), names(got$data))
if (length(missing)) {
saved_for <- if (is.character(x$data_label) && length(x$data_label) == 1 && !is.na(x$data_label)) x$data_label else "the data they were saved with"
shiny::showNotification(sprintf(
"These settings name columns that this data does not have: %s. Load %s first, then load the settings again.",
paste(missing, collapse = ", "), saved_for
), type = "error", duration = NULL)
return()
}
misfits <- .app_spec_misfits(spec, got$data)
if (any(grepl("^the center .* to optimize for", misfits))) spec$center_for <- ""
spec$data_name <- got$name
apply_defaults(got$data, got$name, spec)
if (length(misfits)) {
shiny::showNotification(htmltools::tagList(
"The settings are loaded, but these do not fit this data and were changed:",
htmltools::tags$ul(lapply(misfits, htmltools::tags$li)),
"Check each step, then press Find recommendation."
), type = "warning", duration = NULL)
} else {
shiny::showNotification("The settings are loaded. Check each step, then press Find recommendation.", type = "message")
}
})
current_data <- shiny::reactive(loaded()$data)
col_id <- function(prefix, col) paste0(prefix, "_", generation(), "_", match(col, names(current_data())))
# costs applied from the cost designer, by component. The coefficient
# inputs carry the designer version in their ids, so an apply redraws them
# with the new values and keeps the bounds.
designer_costs <- shiny::reactiveVal(list())
designer_version <- shiny::reactiveVal(0L)
designer_count <- 0L
coef_id <- function(col) paste0(col_id("coef", col), "_", designer_version())
designer_text <- function(col) {
v <- designer_costs()[[col]]
if (is.null(v)) NULL else paste(format_coef_code(v), collapse = ", ")
}
# The columns that hold the outcome: the outcome column, or for center level
# data the successes or proportion column and the total column. No other
# role offers them.
outcome_roles <- shiny::reactive({
if (identical(input$structure, "center")) setdiff(c(input$cl_value, input$cl_total), "") else input$outcome
})
# Choices that depend on the outcome and the components.
shiny::observeEvent(list(current_data(), input$outcome, input$structure, input$cl_value, input$cl_total), {
d <- current_data()
shiny::req(d, input$outcome %in% names(d))
if (shiny::isolate(applying_defaults())) {
return()
}
numeric_cols <- .app_numeric_cols(d)
roles <- outcome_roles()
if (!identical(input$structure, "center")) {
auto <- if (.app_is_binary(d[[input$outcome]])) "binary" else "continuous"
shiny::updateRadioButtons(session, "outcome_type", selected = auto)
# a new outcome gets a goal on its own scale
if (!identical(shiny::isolate(last_outcome()), input$outcome)) {
last_outcome(input$outcome)
shiny::updateNumericInput(session, "goal", value = .app_default_goal(d, input$outcome, auto))
}
}
kept <- intersect(shiny::isolate(input$components), setdiff(numeric_cols, roles))
shiny::updateSelectizeInput(session, "components", choices = setdiff(numeric_cols, roles), selected = kept)
two_level <- names(d)[vapply(d, function(v) length(unique(stats::na.omit(v))) == 2, logical(1))]
arm_choices <- setdiff(two_level, roles)
arm_kept <- intersect(shiny::isolate(input$arm_col), arm_choices)
shiny::updateSelectInput(session, "arm_col", choices = arm_choices, selected = if (length(arm_kept)) arm_kept else if ("group" %in% arm_choices) "group" else arm_choices[1])
others <- setdiff(names(d), roles)
keep_col <- function(id, name) {
kept <- intersect(shiny::isolate(input[[id]]), others)
if (length(kept)) kept else if (name %in% others) name else ""
}
shiny::updateSelectInput(session, "center_col", choices = c("Choose a column" = "", others), selected = keep_col("center_col", "center"))
shiny::updateSelectInput(session, "period_col", choices = c("Choose a column" = "", others), selected = keep_col("period_col", "period"))
}, ignoreNULL = FALSE)
# center level data has a binary outcome, so its goal is a probability
shiny::observeEvent(input$structure, {
if (shiny::isolate(applying_defaults()) || !identical(input$structure, "center")) {
return()
}
g <- num(shiny::isolate(input$goal))
if (!is.finite(g) || g <= 0 || g >= 1) shiny::updateNumericInput(session, "goal", value = 0.85)
}, ignoreInit = TRUE)
output$outcome_type_note <- shiny::renderUI({
d <- current_data()
shiny::req(d, input$outcome %in% names(d))
auto <- if (.app_is_binary(d[[input$outcome]])) "binary" else "continuous"
htmltools::tags$small(class = "text-muted", if (identical(input$outcome_type, auto)) "Detected from the data." else "Set by you.")
})
shiny::observeEvent(list(current_data(), input$arm_col), {
d <- current_data()
if (shiny::isolate(applying_defaults())) {
return()
}
shiny::req(d, input$arm_col %in% names(d))
values <- sort(unique(as.character(stats::na.omit(d[[input$arm_col]]))))
pick <- if ("treatment" %in% values) "treatment" else if ("1" %in% values) "1" else values[length(values)]
shiny::updateSelectInput(session, "arm_value", choices = values, selected = pick)
})
shiny::observeEvent(list(current_data(), input$outcome, input$arm_col, input$arm_value, input$components, input$structure, input$cl_value, input$cl_total), {
d <- current_data()
if (shiny::isolate(applying_defaults())) {
return()
}
shiny::req(d)
# center level data has its outcome in the proportion column the app builds
s <- spec()
# the outcome columns of center level data are not centers
center_level <- .app_center_level(s)
outcome_cols <- c(s$cl_value, s$cl_total)[rep(center_level, 2)]
choices <- .app_cluster_choices(.app_center_columns(s, d)$data, s$outcome, input$arm_col, input$arm_value, exclude = c(input$components, outcome_cols), center_level = center_level)
kept <- intersect(shiny::isolate(input$cluster_col), choices)
shiny::updateSelectInput(session, "cluster_col", choices = c("Choose a column" = "", choices), selected = if (length(kept)) kept else "")
}, ignoreNULL = FALSE)
shiny::observeEvent(list(current_data(), input$components, outcome_roles()), {
d <- current_data()
if (shiny::isolate(applying_defaults())) {
return()
}
shiny::req(d)
numeric_cols <- .app_numeric_cols(d)
roles <- outcome_roles()
chars <- setdiff(numeric_cols, c(roles, input$components))
shiny::updateSelectizeInput(session, "center_chars", choices = chars, selected = intersect(shiny::isolate(input$center_chars), chars))
covs <- setdiff(names(d), c(roles, input$components))
shiny::updateSelectizeInput(session, "covariates", choices = covs, selected = intersect(shiny::isolate(input$covariates), covs))
weights <- setdiff(numeric_cols, c(roles, input$components))
kept_w <- intersect(shiny::isolate(input$weights_col), weights)
shiny::updateSelectInput(session, "weights_col", choices = c("No weights" = "", weights), selected = if (length(kept_w)) kept_w else "")
}, ignoreNULL = FALSE)
shiny::observeEvent(list(current_data(), input$center_col), {
d <- current_data()
if (shiny::isolate(applying_defaults())) {
return()
}
shiny::req(d)
centers <- if (isTRUE(input$center_col %in% names(d))) sort(unique(as.character(stats::na.omit(d[[input$center_col]])))) else character(0)
shiny::updateSelectInput(session, "center_for", choices = c("The weighted average center" = "", centers), selected = "")
})
shiny::observeEvent(list(current_data(), input$period_col), {
d <- current_data()
if (shiny::isolate(applying_defaults())) {
return()
}
shiny::req(d)
periods <- if (isTRUE(input$period_col %in% names(d))) .app_periods(d[[input$period_col]])$labels else character(0)
shiny::updateSelectInput(session, "period_value", choices = periods, selected = .app_default_period(shiny::isolate(spec()), d, input$period_col))
})
output$data_info <- shiny::renderUI({
got <- loaded()
if (!is.null(upload_error())) {
return(htmltools::div(class = "alert alert-danger", role = "alert", upload_error()))
}
if (is.null(got)) {
return(htmltools::p(class = "text-muted", "Choose a CSV file. It needs a header row, and numeric columns for the outcome and the components."))
}
d <- got$data
left <- got$start$left
htmltools::tagList(
htmltools::p(sprintf("%d rows and %d columns, %d of them numeric.", nrow(d), ncol(d), length(.app_numeric_cols(d)))),
if (!is.null(got$start)) {
htmltools::div(
class = if (length(left)) "alert alert-warning" else "alert alert-info", role = "status",
"The steps are set from the call of your result. ",
if (length(left)) {
htmltools::tagList(
"The app cannot show these settings of it, so they are left out:",
htmltools::tags$ul(class = "mb-0", lapply(left, htmltools::tags$li))
)
} else {
"Every setting of it is shown."
}
)
},
if (isTRUE(got$encoding %in% c("CP1252", "latin1"))) {
htmltools::div(
class = "alert alert-warning", role = "status",
"The file is not UTF-8 text, so it was read as Windows-1252 (Latin-1). Check that names with accents look right. If they do not, save the file as UTF-8 and upload it again."
)
},
if (!is.null(got$hint)) htmltools::div(class = "alert alert-warning", role = "status", got$hint),
if (length(got$renamed)) {
htmltools::div(
class = "alert alert-info", role = "status",
paste0("These column names were changed to names R can use: ", paste(got$renamed, collapse = ", "), ".")
)
}
)
})
output$data_columns <- shiny::renderTable({
d <- current_data()
shiny::req(d)
data.frame(
Column = names(d),
Type = vapply(d, function(v) class(v)[1], character(1)),
Missing = vapply(d, function(v) sum(is.na(v)), integer(1)),
Min = vapply(d, function(v) if (is.numeric(v) && any(!is.na(v))) format(min(v, na.rm = TRUE), digits = 4) else "", character(1)),
Max = vapply(d, function(v) if (is.numeric(v) && any(!is.na(v))) format(max(v, na.rm = TRUE), digits = 4) else "", character(1))
)
})
output$data_head <- shiny::renderTable(utils::head(current_data(), 8))
# One row per component with its bounds and cost. A value the user already
# typed is kept when the row is redrawn.
output$component_rows <- shiny::renderUI({
d <- current_data()
shiny::req(d)
comps <- intersect(input$components, names(d))
if (!length(comps)) {
return(htmltools::p(class = "text-muted", "Choose at least one component."))
}
cubic <- identical(input$cost_mode, "unit") && identical(input$cost_type, "cubic")
coef_mode <- identical(input$cost_mode, "coef")
keep <- function(id, default) {
v <- shiny::isolate(input[[id]])
if (is.null(v)) default else v
}
rows <- lapply(comps, function(cc) {
rng <- range(d[[cc]], na.rm = TRUE)
cost_ui <- if (coef_mode) {
from_designer <- designer_text(cc)
start_coefs <- start_value("coefs", cc, c(0, 1))
shiny::textInput(coef_id(cc), width = "100%", label = .app_help("Cost coefficients c0, c1, ...", "The total cost at level x is c0 + c1 x + c2 x^2 and so on. Enter the numbers separated by commas, such as 0, 2."), value = keep(coef_id(cc), if (is.null(from_designer)) paste(format_coef_code(start_coefs), collapse = ", ") else from_designer))
} else {
shiny::numericInput(col_id("cost", cc), .app_help("Unit cost", "The cost of one unit of this component, such as the cost of one coaching visit. The defaults of 1 are placeholders: enter your own costs."), value = keep(col_id("cost", cc), start_value("unit_costs", cc, 1)), min = 0)
}
htmltools::div(
class = "lago-comp",
htmltools::h6(cc),
bslib::layout_columns(
shiny::numericInput(col_id("lb", cc), .app_help("Lower bound", "The lowest level the next stage may use. It must be 0 or more."), value = keep(col_id("lb", cc), start_value("lower", cc, max(0, rng[1]))), min = 0),
shiny::numericInput(col_id("ub", cc), .app_help("Upper bound", "The highest level the next stage may use."), value = keep(col_id("ub", cc), start_value("upper", cc, rng[2]))),
cost_ui,
if (cubic) shiny::numericInput(col_id("dose", cc), .app_help("Dose where the unit cost was measured (optional)", "With this dose the cubic cost equals the unit cost there. Without it, the unit cost is the average over the range."), value = keep(col_id("dose", cc), start_value("doses", cc, NA)))
),
htmltools::tags$small(class = "text-muted", sprintf("Observed in the data: %s to %s.", format(rng[1], digits = 4), format(rng[2], digits = 4)))
)
})
htmltools::tagList(rows)
})
output$interaction_ui <- shiny::renderUI({
comps <- input$components
if (length(comps) < 2) {
return(htmltools::p(class = "text-muted", "Choose at least two components to model an interaction."))
}
pairs <- utils::combn(comps, 2, simplify = FALSE)
terms <- vapply(pairs, paste, character(1), collapse = ":")
labels <- vapply(pairs, paste, character(1), collapse = " \u00d7 ")
# the first time the components of loaded settings are all shown, their
# interactions are checked, as an update before the boxes exist is lost
s0 <- shiny::isolate(start_spec())
key <- shiny::isolate(generation())
selected <- if (!identical(interactions_started, key) && !is.null(s0) && all(s0$components %in% comps)) {
interactions_started <<- key
intersect(s0$interactions, terms)
} else {
intersect(shiny::isolate(input$interactions), terms)
}
shiny::checkboxGroupInput("interactions", NULL, choices = stats::setNames(terms, labels), selected = selected)
})
output$center_char_values <- shiny::renderUI({
d <- current_data()
shiny::req(d)
chars <- input$center_chars
if (!length(chars)) {
return(NULL)
}
do.call(bslib::layout_columns, lapply(chars, function(cc) {
v <- shiny::isolate(input[[col_id("cc", cc)]])
start <- start_value("center_char_values", cc, signif(stats::median(d[[cc]], na.rm = TRUE), 4), keys = "center_chars")
shiny::numericInput(col_id("cc", cc), sprintf("Optimize at %s =", cc), value = if (is.null(v)) start else v)
}))
})
# One weight per center, in the order the package reads them. The ids carry
# the center column, so the weights of one column never fill another.
# They also carry the structure and the total column, as those set where
# the weights start, so a change draws them again from the new start.
cw_id <- function(s, k) {
nm <- names(current_data())
paste0("cw_", generation(), "_", match(s$center_col, nm), "_", s$structure, "_", match(s$cl_total, nm, nomatch = 0L), "_", k)
}
output$cw_ui <- shiny::renderUI({
d <- current_data()
shiny::req(d)
key <- list(center_col = input$center_col, structure = input$structure %||% "individual", cl_total = input$cl_total %||% "")
centers <- .app_center_levels(d, key$center_col)
if (!length(centers)) {
return(htmltools::p(class = "text-muted", "Choose the column that identifies the centers."))
}
start <- .app_center_weights_default(utils::modifyList(shiny::isolate(spec()), key), d)
# loaded settings bring their own weights, for the same centers
s0 <- shiny::isolate(start_spec())
# named weights are matched to the centers by name, and weights without
# names, as older settings have, by their order
named <- !is.null(s0) && !is.null(names(s0$cw))
fits <- if (named) setequal(names(s0$cw), centers) else length(s0$cw) == length(centers)
from_settings <- !is.null(s0) && isTRUE(s0$cw_on) && identical(s0$center_col, key$center_col) && fits
if (from_settings) start <- if (named) as.numeric(s0$cw[centers]) else s0$cw
inputs <- lapply(seq_along(centers), function(k) {
id <- cw_id(key, k)
v <- shiny::isolate(input[[id]])
# weights from the settings stay exact, so the run matches them
first <- if (from_settings) start[k] else signif(start[k], 4)
shiny::numericInput(id, centers[k], value = if (is.null(v)) first else v, min = 0, max = 1, step = 0.01)
})
htmltools::tagList(
htmltools::p(class = "text-muted", if (from_settings) "Each center starts at its weight in the settings it was opened with." else "Each center starts at its share of the patients."),
do.call(bslib::layout_column_wrap, c(list(width = "12rem", fill = FALSE), inputs))
)
})
output$cw_sum <- shiny::renderUI({
w <- spec()$cw
shiny::req(length(w))
total <- sum(w)
htmltools::p(
class = if (is.finite(total) && abs(total - 1) < 0.001) "text-muted" else "text-danger",
role = "status",
sprintf("The weights add up to %s.", if (is.finite(total)) format(signif(total, 4)) else "an unknown total, as one is empty")
)
})
# One small input per component, for a grid step or a previous level. They
# are drawn again only when the components change, so typing keeps focus.
per_component <- function(prefix, label, field) {
d <- current_data()
shiny::req(d)
comps <- intersect(input$components, names(d))
if (!length(comps)) {
return(htmltools::p(class = "text-muted", "Choose at least one component."))
}
inputs <- lapply(comps, function(cc) {
id <- col_id(prefix, cc)
v <- shiny::isolate(input[[id]])
shiny::numericInput(id, sprintf(label, cc), value = if (is.null(v)) start_value(field, cc, NA) else v, min = 0)
})
do.call(bslib::layout_columns, c(list(fill = FALSE), inputs))
}
# an empty step takes 1/20 of the range, which this note gives
step_note <- function() {
s <- spec()
ok <- length(s$components) && all(is.finite(s$lower) & is.finite(s$upper) & s$lower <= s$upper)
if (ok) {
htmltools::tags$small(class = "text-muted", sprintf(
"Leave a step empty for 1/20 of the range: %s.",
paste(sprintf("%s %s", s$components, vapply(signif(.app_cs_steps(s$lower, s$upper), 4), format, character(1))), collapse = ", ")
))
}
}
output$cs_steps_ui <- shiny::renderUI(htmltools::tagList(per_component("csstep", "Confidence set step of %s", "cs_steps"), shiny::uiOutput("cs_steps_note")))
output$grid_steps_ui <- shiny::renderUI(htmltools::tagList(per_component("gstep", "Grid search step of %s", "grid_steps"), shiny::uiOutput("grid_steps_note")))
output$cs_steps_note <- shiny::renderUI(step_note())
output$grid_steps_note <- shiny::renderUI(step_note())
output$prev_ui <- shiny::renderUI(per_component("prev", "Previous stage level of %s", "prev"))
shiny::observeEvent(input$use_rec_as_prev, {
r <- run_state()$run$value
comps <- spec()$components
used <- if (is.null(r)) NULL else if (!is.null(r$display_components)) r$display_components else r$intervention_components
if (is.null(r) || stale() || !identical(as.character(used), comps)) {
shiny::showNotification("Press Find recommendation first, so the recommendation is for the current settings and components.", type = "warning")
return()
}
for (k in seq_along(comps)) shiny::updateNumericInput(session, col_id("prev", comps[k]), value = signif(as.numeric(r$rec_int[k]), 6))
shiny::showNotification("The previous stage now holds the current recommendation.", type = "message")
})
# the inputs of a hidden step still have to exist, so the checks and the run
# see them before the user opens that step
for (id in c("component_rows", "interaction_ui", "center_char_values", "cs_steps_ui", "grid_steps_ui", "prev_ui", "cw_ui")) {
shiny::outputOptions(output, id, suspendWhenHidden = FALSE)
}
num <- function(x) {
if (is.null(x) || !length(x)) NA_real_ else suppressWarnings(as.numeric(x[[1]]))
}
spec <- shiny::reactive({
got <- loaded()
shiny::req(got)
d <- got$data
s <- .app_empty_spec()
# an input the browser has not sent yet keeps the default of the spec
pick <- function(x, default) if (is.null(x) || !length(x)) default else x
chr <- function(x) pick(x, "")
comps <- intersect(pick(input$components, character(0)), names(d))
s$data_name <- got$name
s$outcome <- chr(input$outcome)
s$outcome_type <- pick(input$outcome_type, s$outcome_type)
s$goal_mode <- pick(input$goal_mode, s$goal_mode)
s$goal <- num(input$goal)
s$intention <- pick(input$intention, s$intention)
s$components <- comps
s$lower <- vapply(comps, function(cc) num(input[[col_id("lb", cc)]]), numeric(1), USE.NAMES = FALSE)
s$upper <- vapply(comps, function(cc) num(input[[col_id("ub", cc)]]), numeric(1), USE.NAMES = FALSE)
s$cost_mode <- pick(input$cost_mode, s$cost_mode)
s$cost_type <- pick(input$cost_type, s$cost_type)
s$unit_costs <- vapply(comps, function(cc) num(input[[col_id("cost", cc)]]), numeric(1), USE.NAMES = FALSE)
s$doses <- vapply(comps, function(cc) num(input[[col_id("dose", cc)]]), numeric(1), USE.NAMES = FALSE)
s$coefs <- lapply(comps, function(cc) {
text <- input[[coef_id(cc)]]
# until the redrawn input reports, the designer's costs hold
if (is.null(text)) text <- designer_text(cc)
.app_parse_coefs(text)
})
pairs <- if (length(comps) >= 2) vapply(utils::combn(comps, 2, simplify = FALSE), paste, character(1), collapse = ":") else character(0)
s$interactions <- intersect(pick(input$interactions, character(0)), pairs)
s$include_cs <- !isFALSE(input$include_cs)
s$center_mode <- pick(input$center_mode, s$center_mode)
s$center_chars <- intersect(pick(input$center_chars, character(0)), names(d))
s$center_char_values <- vapply(s$center_chars, function(cc) num(input[[col_id("cc", cc)]]), numeric(1), USE.NAMES = FALSE)
s$center_col <- chr(input$center_col)
s$center_for <- chr(input$center_for)
s$time_on <- isTRUE(input$time_on)
s$period_col <- chr(input$period_col)
s$period_value <- chr(input$period_value)
s$covariates <- intersect(pick(input$covariates, character(0)), names(d))
s$arm_col <- chr(input$arm_col)
s$arm_value <- chr(input$arm_value)
s$power_goal <- num(input$power_goal)
s$n_centers <- num(input$n_centers)
s$n_patients <- num(input$n_patients)
s$approach <- pick(input$approach, s$approach)
s$icc <- .app_parse_icc(input$icc)
s$cluster_col <- chr(input$cluster_col)
s$glm_family <- pick(input$glm_family, s$glm_family)
s$link <- pick(input$link, s$link)
s$weights_col <- chr(input$weights_col)
s$method <- pick(input$method, s$method)
s$cs_level <- if (is.finite(num(input$cs_level))) num(input$cs_level) else s$cs_level
s$cs_steps <- vapply(comps, function(cc) num(input[[col_id("csstep", cc)]]), numeric(1), USE.NAMES = FALSE)
s$grid_steps <- vapply(comps, function(cc) num(input[[col_id("gstep", cc)]]), numeric(1), USE.NAMES = FALSE)
s$prev_on <- isTRUE(input$prev_on)
s$prev <- vapply(comps, function(cc) num(input[[col_id("prev", cc)]]), numeric(1), USE.NAMES = FALSE)
s$structure <- pick(input$structure, s$structure)
s$cl_kind <- pick(input$cl_kind, s$cl_kind)
s$cl_value <- chr(input$cl_value)
s$cl_total <- chr(input$cl_total)
s$cw_on <- isTRUE(input$cw_on)
# the weights are named by their centers, so saved settings match them
# to the centers of the data they are loaded for by name
centers <- .app_center_levels(d, s$center_col)
s$cw <- stats::setNames(vapply(seq_along(centers), function(k) num(input[[cw_id(s, k)]]), numeric(1)), centers)
.app_resolve(s)
})
note_box <- function(msgs) {
if (!length(msgs)) {
return(NULL)
}
htmltools::div(class = "alert alert-info", role = "status", htmltools::tags$ul(class = "mb-0", lapply(msgs, htmltools::tags$li)))
}
notes <- shiny::reactive({
got <- loaded()
if (is.null(got)) character(0) else .app_notes(spec(), got$data)
})
output$notes_outcome <- shiny::renderUI(note_box(grep("named group", notes(), value = TRUE)))
output$notes_centers <- shiny::renderUI(note_box(grep("named group", notes(), value = TRUE, invert = TRUE)))
output$notes_intervention <- shiny::renderUI({
s <- spec()
if (identical(s$cost_mode, "unit") && length(s$unit_costs) && all(s$unit_costs %in% 1)) {
note_box("The unit costs are still the placeholder of 1. Enter the real cost of one unit of each component to get a cost you can use.")
}
})
problems <- shiny::reactive({
if (is.null(loaded())) {
msg <- if (is.null(upload_error())) "Choose a CSV file to upload." else "The file could not be read. Step 1 says what to change."
return(data.frame(step = "data", message = msg))
}
.app_problems(spec(), current_data())
})
steps <- c(data = "1. Data", outcome = "2. Outcome and goal", intervention = "3. Intervention and costs", centers = "4. Centers, time and covariates")
output$checklist <- shiny::renderUI({
p <- problems()
htmltools::tagList(lapply(names(steps), function(st) {
msgs <- p$message[p$step == st]
if (is.null(loaded()) && st != "data") msgs <- "Load the data first."
ok <- !length(msgs)
htmltools::div(
class = paste("lago-step", if (ok) "ok" else "todo"),
htmltools::span(class = "lago-mark", `aria-hidden` = "true", if (ok) "\u2713" else "!"),
htmltools::span(class = "visually-hidden", if (ok) "Ready:" else "Needs attention:"),
htmltools::div(
shiny::actionLink(paste0("go_", st), steps[[st]]),
if (!ok) htmltools::div(class = "msg", msgs[1], if (length(msgs) > 1) sprintf(" (and %d more)", length(msgs) - 1))
)
)
}))
})
for (st in names(steps)) {
local({
target <- st
shiny::observeEvent(input[[paste0("go_", target)]], bslib::nav_select("steps", target))
})
}
# The cost designer in a dialog, started on the costs now in use. It runs as
# a module under a new id each time, so no value carries over from an
# earlier opening.
shiny::observeEvent(input$open_designer, {
s <- spec()
comps <- s$components
ok <- length(comps) && all(is.finite(c(s$lower, s$upper))) && all(s$lower < s$upper)
if (!ok) {
shiny::showNotification("Choose the components and give each a lower bound below its upper bound first.", type = "warning")
return()
}
start <- .app_designer_start(s)
designer_count <<- designer_count + 1L
id <- paste0("designer_", designer_count)
parts <- .build_cost_parts(
component_names = comps,
unit_costs = start$unit_costs,
default_cost_fxn_type = start$form,
intervention_lower_bounds = s$lower,
intervention_upper_bounds = s$upper,
ns = shiny::NS(id),
embedded = TRUE,
initial_coefs = start$by_form,
on_apply = function(cost_list, form) {
designer_costs(stats::setNames(cost_list, comps))
shiny::updateRadioButtons(session, "cost_mode", selected = "coef")
designer_version(designer_version() + 1L)
shiny::removeModal(session)
shiny::showNotification("The costs from the designer are now in use, as cost coefficients.", type = "message")
}
)
unfit_note <- if (length(start$unfit)) {
htmltools::div(
class = "alert alert-warning", role = "status",
sprintf(
"The cost coefficients of %s do not fit the %s form of the designer, so it starts on its own curve for them. \"Use these costs\" replaces them.",
paste(start$unfit, collapse = ", "), start$form
)
)
}
shiny::showModal(shiny::modalDialog(
title = "Shape the costs",
unfit_note,
parts$ui,
size = "xl", easyClose = TRUE,
footer = htmltools::tagList(shiny::modalButton("Cancel"), parts$apply_ui)
), session = session)
shiny::moduleServer(id, parts$server)
})
shiny::observeEvent(input$next_data, bslib::nav_select("steps", "outcome"))
shiny::observeEvent(input$next_outcome, bslib::nav_select("steps", "intervention"))
shiny::observeEvent(input$next_intervention, bslib::nav_select("steps", "centers"))
# A task button turns itself on after each update in which the browser
# sent its value, the first one included. Its state is set after that.
set_enabled <- function(id, on) {
force(on)
session$onFlushed(function() shiny::withReactiveDomain(session, shinyjs::toggleState(id, condition = on)), once = TRUE)
}
shiny::observe({
set_enabled("run", !nrow(problems()))
shinyjs::toggleState("next_centers", condition = !nrow(problems()))
# settings are saved for a loaded dataset
shinyjs::toggleState("save_settings", condition = !is.null(loaded()))
})
output$run_hint <- shiny::renderUI({
p <- problems()
if (!nrow(p)) {
return(NULL)
}
htmltools::tags$small(class = "text-muted", role = "status", "Fix the steps marked ! to run.")
})
built <- shiny::reactive({
shiny::req(!nrow(problems()))
.app_build(spec(), current_data())
})
do_run <- function() {
b <- built()
shiny::withProgress(message = "Finding the recommended intervention", value = 0.3, {
res <- .app_run(function() do.call(lago_optimization, c(list(data = b$data), b$args, list(quiet = TRUE))))
shiny::setProgress(1)
})
res$error <- .app_explain_error(res$error, b$args$link)
run_id(run_id() + 1L)
run_state(list(run = res, build = b, id = run_id()))
# a failed run leaves no result, so Done returns none either, as after a
# failed sweep or budget search
shared$result <- if (is.null(res$error)) {
list(result = res$value, sensitivity = NULL, budget = NULL, code = b$code, arguments = b$args)
} else {
list(result = NULL, sensitivity = NULL, budget = NULL, code = NULL, arguments = NULL)
}
bslib::nav_select("steps", "results")
}
shiny::observeEvent(input$run, do_run())
shiny::observeEvent(input$next_centers, do_run())
stale <- shiny::reactive({
st <- run_state()
if (is.null(st)) {
return(FALSE)
}
now <- tryCatch(built(), error = function(e) NULL)
is.null(now) || !identical(now$args, st$build$args) || !identical(now$prep, st$build$prep) ||
!identical(now$code[2], st$build$code[2])
})
# the warnings and notes of a run, a sweep or a budget search
notes_card_for <- function(run) {
notes <- c(run$warnings, run$messages)
if (length(notes)) {
bslib::card(
bslib::card_header(sprintf("Things to check (%d)", length(notes))),
htmltools::tags$ul(class = "lago-notes", lapply(notes, htmltools::tags$li))
)
}
}
output$results <- shiny::renderUI({
st <- run_state()
if (is.null(st)) {
return(htmltools::p(class = "lago-intro", "Press Find recommendation to see the result here."))
}
run <- st$run
notes_card <- notes_card_for(run)
if (!is.null(run$error)) {
return(htmltools::tagList(
bslib::card(
class = "border-danger",
bslib::card_header("The optimization could not run with these settings"),
htmltools::p(run$error),
htmltools::p("Things that often help:"),
htmltools::tags$ul(lapply(.app_error_tips(), htmltools::tags$li)),
htmltools::p(class = "text-muted", "Your settings are kept. Change them and run again.")
),
notes_card
))
}
r <- run$value
comps <- r$display_components
if (is.null(comps)) comps <- r$intervention_components
fmt <- function(v) vapply(.lago_fmt_value(v), format, character(1), big.mark = ",")
rec <- paste(sprintf("%s = %s", comps, fmt(r$rec_int)), collapse = ", ")
goal_used <- if (!is.null(r$effective_outcome_goal)) r$effective_outcome_goal else r$outcome_goal
ci <- r$est_outcome_ci
htmltools::div(
class = if (stale()) "lago-stale",
if (stale()) {
htmltools::div(class = "alert alert-warning", role = "status", "These results are from earlier settings. Press Find recommendation to update them.")
},
htmltools::p(class = "lead", .app_summary_sentence(r, comps)),
if (isTRUE(r$shrinking_method_used)) {
htmltools::div(
class = "alert alert-info",
htmltools::p("The goal cannot be reached within the bounds, so the recommendation was found with the shrinking method. It moves from the first stage intervention toward the bounds by how far the goal is from reach. Lower the goal or widen the bounds to get a recommendation that reaches it."),
shiny::actionButton("fix_goal", "Lower the goal", class = "btn-outline-primary btn-sm"),
" ",
shiny::actionButton("fix_bounds", "Widen the bounds", class = "btn-outline-primary btn-sm")
)
},
bslib::layout_column_wrap(
width = 1 / 3,
bslib::value_box("Recommended intervention", htmltools::span(style = "font-size:1.1rem", rec)),
bslib::value_box("Cost of the recommendation", fmt(r$rec_int_cost)),
bslib::value_box(
"Estimated outcome",
fmt(r$est_outcome_goal),
if (length(ci) == 2 && all(is.finite(ci))) htmltools::p(sprintf("%s CI %s to %s", .lago_confidence_label(r), fmt(ci[1]), fmt(ci[2]))),
if (!is.null(goal_used)) htmltools::p(sprintf("Goal used: %s%s", fmt(goal_used), .app_goal_source(r)))
)
),
notes_card,
bslib::navset_card_underline(
bslib::nav_panel(
"Confidence set",
shiny::uiOutput("cs_ui")
),
bslib::nav_panel("Outcome model", shiny::uiOutput("model_ui")),
if (!is.null(r$test_results)) bslib::nav_panel("Intervention test", shiny::uiOutput("test_ui")),
bslib::nav_panel("Full printout", shiny::verbatimTextOutput("printout"))
),
bslib::card(
bslib::card_header("Report and next steps"),
htmltools::p(
"The Sensitivity tab shows how this recommendation moves when an input changes, and the Budget tab finds the best outcome for a budget. ",
sprintf("The report is one HTML file with the recommendation, %sthe outcome model and interactive cost curves, to keep or share.", if (is.null(r$cs)) "" else "the confidence set, ")
),
if (is.null(report_missing)) {
htmltools::tagList(
shiny::textInput("report_title", "Report title", value = shiny::isolate(input$report_title) %||% "LAGO optimization report"),
shiny::downloadButton("download_report", "Download the report (.html)", class = "btn-outline-primary btn-sm")
)
} else {
htmltools::div(class = "alert alert-warning mb-0", role = "status", report_missing)
}
)
)
})
output$cs_ui <- shiny::renderUI({
st <- run_state()
r <- st$run$value
shiny::req(r)
if (is.null(r$cs)) {
why <- if (isTRUE(r$shrinking_method_used)) {
"There is no confidence set because the shrinking method was used."
} else if (is.null(r$confidence_set_size_percentage)) {
"The confidence set was not computed. Turn it on in step 3."
} else {
"No intervention in the grid is in the confidence set."
}
return(htmltools::p(why))
}
htmltools::tagList(
htmltools::p(sprintf("%s of the grid is in the confidence set.", paste0(format(100 * r$confidence_set_size_percentage, digits = 3), "%"))),
if (length(r$rec_int) <= 2) {
shiny::plotOutput("cs_plot", height = "420px")
} else {
htmltools::tagList(
htmltools::p(if (nrow(r$cs) > 200) {
sprintf("With three or more components the set is listed as a table. The 200 cheapest of its %s interventions are shown. Download the file for all of them.", format(nrow(r$cs), big.mark = ","))
} else {
"With three or more components the set is listed as a table, cheapest first."
}),
shiny::tableOutput("cs_table")
)
},
shiny::downloadButton("download_cs", "Download the confidence set (.csv)", class = "btn-outline-primary btn-sm")
)
})
output$cs_plot <- shiny::renderPlot({
r <- run_state()$run$value
shiny::req(r, r$cs)
plot(r)
})
output$cs_table <- shiny::renderTable({
cs <- run_state()$run$value$cs
shiny::req(cs)
if ("cost" %in% names(cs)) cs <- cs[order(cs$cost), , drop = FALSE]
utils::head(cs, 200)
})
output$model_ui <- shiny::renderUI({
r <- run_state()$run$value
shiny::req(r, r$model)
htmltools::tagList(
htmltools::p(sprintf("The %s model fitted to the first stage data, with the %s link.", r$family, r$link)),
shiny::tableOutput("model_table")
)
})
output$model_table <- shiny::renderTable({
r <- run_state()$run$value
shiny::req(r, r$model)
co <- stats::coef(summary(r$model))
data.frame(Term = rownames(co), signif(as.data.frame(co), 4), check.names = FALSE, row.names = NULL)
}, digits = 4)
output$test_ui <- shiny::renderUI({
r <- run_state()$run$value
shiny::req(r)
b <- lago_blocks(r)$test
shiny::req(b)
htmltools::tagList(
htmltools::p("Whether the first stage shows an effect of the intervention as a whole."),
htmltools::tags$ul(lapply(b$rows, htmltools::tags$li))
)
})
shiny::observeEvent(input$fix_goal, bslib::nav_select("steps", "outcome"))
shiny::observeEvent(input$fix_bounds, bslib::nav_select("steps", "intervention"))
output$download_cs <- shiny::downloadHandler(
filename = function() "lago_confidence_set.csv",
content = function(file) utils::write.csv(run_state()$run$value$cs, file, row.names = FALSE)
)
output$printout <- shiny::renderText({
r <- run_state()$run$value
shiny::req(r)
paste(.app_printout(r), collapse = "\n")
})
output$download_report <- shiny::downloadHandler(
filename = function() "lago_report.html",
content = function(file) {
title <- input$report_title
if (is.null(title) || !nzchar(trimws(title))) title <- "LAGO optimization report"
lago_report(run_state()$run$value, output_file = file, title = title)
}
)
# --- the sensitivity sweep and the budget search ---------------------------
# Both start from the result in Results, through the call it stores, so
# they need a result of the current settings.
current_result <- shiny::reactive({
st <- run_state()
if (is.null(st) || !is.null(st$run$error) || stale()) NULL else st$run$value
})
gate <- function(what) {
st <- run_state()
msg <- if (is.null(st) || !is.null(st$run$error)) {
sprintf("Press Find recommendation first. The %s starts from that result.", what)
} else if (stale()) {
sprintf("The settings changed since the last run. Press Find recommendation to update the result, then run the %s.", what)
}
if (!is.null(msg)) htmltools::div(class = "alert alert-info", role = "status", msg)
}
output$sweep_gate <- shiny::renderUI(gate("sweep"))
output$budget_gate <- shiny::renderUI(gate("search"))
# a sweep or search belongs to the run it used, and to settings that have
# not changed since
current_for <- function(state) {
!is.null(state) && identical(state$run_id, run_id()) && !stale()
}
sweep_choices <- shiny::reactive(.app_sweep_choices(spec()))
shown_choices <- NULL
shiny::observe({
ch <- sweep_choices()
if (identical(ch, shown_choices)) {
return()
}
shown_choices <<- ch
kept <- intersect(shiny::isolate(input$sweep_param), ch)
shiny::updateSelectInput(session, "sweep_param", choices = ch, selected = if (length(kept)) kept else ch[1])
})
# The values start around the current setting of the input, and follow it
# when it changes in the steps, as on a new dataset.
sweep_basis <- shiny::reactive({
s <- spec()
list(input$sweep_param, generation(), s$outcome, s$outcome_type, s$goal, s$power_goal, s$n_centers, s$n_patients, s$icc, s$period_col)
})
shown_basis <- NULL
shiny::observe({
basis <- sweep_basis()
param <- input$sweep_param
if (identical(basis, shown_basis) || is.null(param) || !nzchar(param)) {
return()
}
new_param <- !identical(param, shown_basis[[1]])
# a new dataset starts the values again, as a typed list was for other data
new_data <- !identical(basis[[2]], shown_basis[[2]])
shown_basis <<- basis
start <- .app_sweep_defaults(param, shiny::isolate(spec()), current_data())
if (!is.null(start$periods)) {
shiny::updateSelectizeInput(session, "sweep_periods", choices = start$periods, selected = start$periods)
} else {
# a list the user typed is kept when only the settings change
if (new_param || new_data) shiny::updateRadioButtons(session, "sweep_how", selected = "steps")
if (new_data) shiny::updateTextInput(session, "sweep_typed", value = "")
shiny::updateNumericInput(session, "sweep_from", value = start$from)
shiny::updateNumericInput(session, "sweep_to", value = start$to)
shiny::updateNumericInput(session, "sweep_steps", value = start$steps)
}
})
sweep_values <- shiny::reactive({
param <- input$sweep_param
if (is.null(param) || !nzchar(param)) {
return(list(values = NULL, error = "Choose the input to vary."))
}
if (identical(param, "time_effect_optimization_value")) {
return(.app_sweep_period_values(input$sweep_periods, current_data(), spec()$period_col))
}
.app_sweep_values(
param, input$sweep_how %||% "steps", num(input$sweep_from), num(input$sweep_to),
num(input$sweep_steps), input$sweep_typed, spec()$outcome_type
)
})
output$sweep_preview <- shiny::renderUI({
v <- sweep_values()
if (!is.null(v$error)) {
return(htmltools::p(class = "text-danger", role = "status", v$error))
}
htmltools::p(class = "text-muted", sprintf(
"Runs %d optimizations, at %s.", length(v$values),
paste(if (is.null(v$labels)) format(v$values, trim = TRUE, drop0trailing = TRUE) else v$labels, collapse = ", ")
))
})
shiny::observe({
set_enabled("run_sweep", !is.null(current_result()) && is.null(sweep_values()$error))
})
shiny::observeEvent(input$run_sweep, {
r <- current_result()
v <- sweep_values()
shiny::req(r, is.null(v$error))
s <- spec()
param <- input$sweep_param
extra <- .app_sweep_extra(param, s, r)
shiny::withProgress(message = sprintf("Running %d optimizations", length(v$values)), value = 0.3, {
res <- .app_run(function() {
do.call(lago_sensitivity, c(list(r, parameter = param, values = v$values), extra, list(quiet = TRUE)))
})
shiny::setProgress(1)
})
sweep_state(list(run = res, run_id = run_id(), labels = v$labels, code = .app_sweep_code(param, v$values, s)))
# a failed sweep leaves the code, so Done returns no sweep either
shared$result["sensitivity"] <- list(res$value)
shared$result$code <- code_lines()
})
output$sweep_results <- shiny::renderUI({
st <- sweep_state()
if (is.null(st)) {
return(NULL)
}
run <- st$run
if (!is.null(run$error)) {
return(htmltools::tagList(
bslib::card(
class = "border-danger mt-3",
bslib::card_header("The sweep could not run with these values"),
htmltools::p(run$error)
),
notes_card_for(run)
))
}
s <- run$value
htmltools::div(
class = paste("mt-3", if (!current_for(st)) "lago-stale"),
if (!current_for(st)) {
htmltools::div(class = "alert alert-warning", role = "status", "This sweep is from an earlier result. Run it again to update it.")
},
htmltools::p(class = "lead", .app_sweep_sentence(s, st$labels)),
notes_card_for(run),
shiny::radioButtons("sweep_show", "Plot", c("Cost of the recommendation" = "cost", "Level of each component" = "components"), inline = TRUE),
shiny::plotOutput("sweep_plot", height = "380px"),
shiny::tableOutput("sweep_table"),
shiny::downloadButton("download_sweep", "Download the sweep (.csv)", class = "btn-outline-primary btn-sm")
)
})
output$sweep_plot <- shiny::renderPlot({
s <- sweep_state()$run$value
shiny::req(s, any(s$status == "ok"))
p <- suppressMessages(plot(s, show = input$sweep_show %||% "cost"))
shiny::req(p)
p + ggplot2::labs(x = .app_sweep_label(attr(s, "parameter")))
})
output$sweep_table <- shiny::renderTable({
st <- sweep_state()
shiny::req(st$run$value)
.app_sweep_table(st$run$value, st$labels)
}, digits = 4)
output$download_sweep <- shiny::downloadHandler(
filename = function() "lago_sensitivity.csv",
content = function(file) {
s <- sweep_state()$run$value
utils::write.csv(data.frame(as.data.frame(unclass(s)), note = .app_sweep_notes(s)), file, row.names = FALSE)
}
)
# The budget starts at the cost of each new recommendation, unless the user
# typed their own. A new dataset, a reset or loaded settings start it again
# from the next result, so a budget typed for other data is not kept.
budget_prefill <- shiny::reactiveVal(NULL)
budget_generation <- NULL
shiny::observeEvent(run_id(), {
r <- run_state()$run$value
shiny::req(r)
typed <- input$budget
fresh <- !identical(budget_generation, generation())
if (fresh || is.null(typed) || is.na(typed) || identical(typed, budget_prefill())) {
budget_generation <<- generation()
# rounded up, so the budget still buys the recommendation, and empty
# for a recommendation that costs nothing, as no budget follows from it
budget_prefill(if (is.finite(r$rec_int_cost) && r$rec_int_cost > 0) .app_round_safe(r$rec_int_cost, "up") else NA_real_)
shiny::updateNumericInput(session, "budget", value = budget_prefill())
}
})
budget_problem <- shiny::reactive({
b <- num(input$budget)
g <- num(input$budget_grid)
if (!is.finite(b) || b <= 0) {
r <- current_result()
if (!is.null(r) && isTRUE(r$rec_int_cost == 0)) {
"The recommendation costs nothing, so the budget cannot start from its cost. Give a budget above 0."
} else {
"Give a budget above 0."
}
} else if (!is.finite(g) || g != round(g) || g < 2 || g > 25) {
"Goals to try must be a whole number from 2 to 25."
}
})
output$budget_hint <- shiny::renderUI({
msg <- budget_problem()
if (!is.null(msg)) htmltools::p(class = "text-danger", role = "status", msg)
})
shiny::observe({
set_enabled("run_budget", !is.null(current_result()) && is.null(budget_problem()))
})
shiny::observeEvent(input$run_budget, {
r <- current_result()
shiny::req(r, is.null(budget_problem()))
budget <- num(input$budget)
n_grid <- as.integer(num(input$budget_grid))
shiny::withProgress(message = "Searching the outcome goals for this budget", value = 0.3, {
res <- .app_run(function() lago_budget(r, budget = budget, n_grid = n_grid, quiet = TRUE))
shiny::setProgress(1)
})
budget_state(list(run = res, run_id = run_id(), code = .app_budget_code(budget, n_grid)))
# a failed search leaves the code, so Done returns no budget either
shared$result["budget"] <- list(res$value)
shared$result$code <- code_lines()
})
output$budget_results <- shiny::renderUI({
st <- budget_state()
if (is.null(st)) {
return(NULL)
}
run <- st$run
if (!is.null(run$error)) {
return(htmltools::tagList(
bslib::card(
class = "border-danger mt-3",
bslib::card_header("The search could not run with these settings"),
htmltools::p(run$error)
),
notes_card_for(run)
))
}
b <- run$value
fmt <- function(v) vapply(.lago_fmt_value(v), format, character(1), big.mark = ",")
htmltools::div(
class = paste("mt-3", if (!current_for(st)) "lago-stale"),
if (!current_for(st)) {
htmltools::div(class = "alert alert-warning", role = "status", "This search is from an earlier result. Run it again to update it.")
},
htmltools::p(class = "lead", .app_budget_sentence(b)),
if (isTRUE(b$feasible)) {
htmltools::tagList(
bslib::layout_column_wrap(
width = 1 / 3,
bslib::value_box("Intervention", htmltools::span(style = "font-size:1.1rem", paste(sprintf("%s = %s", b$component_names, fmt(b$rec_int)), collapse = ", "))),
bslib::value_box("Cost", fmt(b$rec_int_cost), htmltools::p(sprintf("of a budget of %s", fmt(b$budget)))),
bslib::value_box("Estimated outcome", fmt(b$est_outcome))
),
if (!identical(spec()$goal_mode, "power")) {
htmltools::p(
shiny::actionButton("use_budget_goal", "Use this outcome as the goal", class = "btn-outline-primary btn-sm"),
" ",
htmltools::tags$small(class = "text-muted", if (isTRUE(spec()$include_cs)) {
"Puts it in step 2, so Find recommendation gives the full result for it, with the confidence set."
} else {
"Puts it in step 2, so Find recommendation gives the full result for it."
})
)
}
)
},
notes_card_for(run),
if (NROW(b$frontier)) {
htmltools::tagList(
htmltools::p("Each point is the cheapest intervention that reaches one outcome goal. The dashed line is the budget. The search tries a grid of goals, so the outcome found can fall a little short of the best the budget can buy. More goals to try, under More options, give a closer answer."),
shiny::plotOutput("budget_plot", height = "380px"),
shiny::tableOutput("budget_table"),
shiny::downloadButton("download_budget", "Download the goals searched (.csv)", class = "btn-outline-primary btn-sm")
)
}
)
})
output$budget_plot <- shiny::renderPlot({
b <- budget_state()$run$value
shiny::req(b)
p <- suppressMessages(plot(b))
shiny::req(p)
p
})
output$budget_table <- shiny::renderTable({
fr <- budget_state()$run$value$frontier
shiny::req(fr)
fr <- fr[order(fr$rec_int_cost), , drop = FALSE]
data.frame(
`Outcome goal` = fr$outcome_goal, Cost = fr$rec_int_cost, `Estimated outcome` = fr$est_outcome,
`Within budget` = ifelse(fr$affordable, "yes", "no"), check.names = FALSE
)
}, digits = 4)
output$download_budget <- shiny::downloadHandler(
filename = function() "lago_budget.csv",
content = function(file) utils::write.csv(budget_state()$run$value$frontier, file, row.names = FALSE)
)
shiny::observeEvent(input$use_budget_goal, {
b <- budget_state()$run$value
shiny::req(b, isTRUE(b$feasible))
# rounded toward the outcome the budget reaches, so the goal stays in reach
toward <- if (identical(b$intention, "minimize")) "up" else "down"
shiny::updateNumericInput(session, "goal", value = .app_round_safe(b$est_outcome, toward))
bslib::nav_select("steps", "outcome")
shiny::showNotification("The outcome goal is now the outcome this budget buys. Press Find recommendation to run it.", type = "message")
})
code_lines <- shiny::reactive({
b <- tryCatch(built(), error = function(e) NULL)
if (is.null(b)) {
return("# Fix the steps marked ! to see the code.")
}
extra <- lapply(list(sweep_state(), budget_state()), function(st) {
if (current_for(st) && is.null(st$run$error)) c("", st$code)
})
c(b$code, unlist(extra))
})
output$code <- shiny::renderText(paste(code_lines(), collapse = "\n"))
output$download_code <- shiny::downloadHandler(
filename = function() "lago_analysis.R",
content = function(file) writeLines(code_lines(), file)
)
shiny::observeEvent(input$done, shiny::stopApp(shared$result))
# closing the last tab ends the app too, after a pause so that a page
# refresh, which opens a new session, does not
session$onSessionEnded(function() {
shared$sessions <- shared$sessions - 1L
if (!shiny::isRunning()) {
return()
}
later::later(function() {
if (shared$sessions == 0L && shiny::isRunning()) shiny::stopApp(shared$result)
}, delay = 5)
})
}
shiny::shinyApp(ui, server)
}
Any scripts or data that you put into this service are public.
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.