R/app.R

Defines functions about_html as_vol_field read_uploaded volumr_server volumr_ui shinyVolumr

Documented in shinyVolumr

# ============================ #
# The dashboard                #
# ============================ #

#' Run the workflow as an application
#'
#' @title Run the workflow as an application
#' @description Puts the whole path from a gridded field to a rendered volume in
#'   one \pkg{shinydashboard} application: read the field, look at it, resample
#'   and quantise it, measure what that costs, write the payload, and render it.
#'   A field of the reader's own can be uploaded at the first step.
#' @param field A `vol_field` the application opens with. Defaults to the case
#'   study, [med_mhw].
#' @param payload A payload the volume tab opens on, as a `vol_payload` or the
#'   path of a payload directory. Defaults to [vol_example_payload()] when
#'   `field` is left at the case study, so that the view opens at the native
#'   grid while the analysis tabs work on the packaged field; ignored once the
#'   reader builds a payload of their own.
#' @param tab Identifier of the tab to open on, one of `"home"`, `"data"`,
#'   `"encoding"`, `"payload"`, `"volume"`, `"theory"`, `"limits"` or `"about"`.
#' @param launch.browser Passed to [shiny::runApp()].
#' @param ... Further arguments for [shiny::runApp()], such as `port` and
#'   `host`.
#' @return Called for its effect. Returns the value of [shiny::runApp()].
#' @details The application keeps three objects in a [shiny::reactiveValues()]
#'   store, one per stage: the field, the encoding and the payload. Each stage
#'   invalidates the ones after it, so a control that changes the transfer
#'   cannot leave a payload on screen that was built under the old one.
#'
#'   The volume tab drives the same page the standalone build writes, through
#'   the widget, so what a reader sees in the application and what they get in
#'   the downloaded file are one renderer and not two. The camera belongs to the
#'   pointer: the controls on the left set everything except the camera, which
#'   the two viewpoint buttons set once each time they are pressed.
#'
#'   An uploaded field is read from an `.rds` holding a `vol_field` or a list
#'   with the four elements the constructor needs, from a NetCDF file through
#'   [vol_read_netcdf()], from a `.csv` of one row per cell through
#'   [vol_field_from_df()], or from an `.rda`. Whatever comes back is put
#'   through [vol_field()], so a file that does not describe a field is refused
#'   with the reason rather than half loaded.
#' @examples
#' if (interactive()) {
#'   shinyVolumr()
#'   shinyVolumr(tab = "volume")
#' }
#' @seealso [vol_field()] for the object the application is built around,
#'   [vol_payload()] and [vol_standalone()] for the two artefacts it writes,
#'   [vol_widget()] for the viewer it embeds, [med_mhw] for the case study.
#' @export
shinyVolumr <- function(field = NULL, payload = NULL, tab = "home",
                        launch.browser = TRUE, ...) {
    require_packages(c("shiny", "shinydashboard"))
    tab <- match.arg(tab, VOLUMR_TABS)
    if (is.null(field)) {
        e <- new.env()
        utils::data("med_mhw", package = "volumr", envir = e)
        field <- e$med_mhw
        # The packaged field keeps every third point of the native grid so that
        # it fits in a package; the payload the package ships is the same field
        # at the native grid, so the view opens at the resolution of the study
        # and not at the one the analysis tabs work on.
        if (is.null(payload)) payload <- vol_example_payload()
    }
    stopifnot(inherits(field, "vol_field"))
    app <- shiny::shinyApp(ui = volumr_ui(tab),
                           server = volumr_server(field, payload))
    shiny::runApp(app, launch.browser = launch.browser, ...)
}

#' @noRd
VOLUMR_TABS <- c("home", "data", "encoding", "payload", "volume", "theory",
                 "limits", "about")

#' @noRd
volumr_ui <- function(start_tab = "home") {
    item <- function(label, name, icon)
        shinydashboard::menuItem(label, tabName = name, icon = shiny::icon(icon),
                                 selected = identical(name, start_tab))
    shinydashboard::dashboardPage(
        skin = "black",
        shinydashboard::dashboardHeader(title = "volumr"),
        shinydashboard::dashboardSidebar(
            shinydashboard::sidebarMenu(
                id = "tabs",
                item("Home", "home", "house"),
                item("Data", "data", "table"),
                item("Encoding", "encoding", "compress"),
                item("Payload", "payload", "box"),
                item("Volume", "volume", "cube"),
                item("Theory", "theory", "square-root-variable"),
                item("Limitations", "limits", "triangle-exclamation"),
                item("About", "about", "circle-info"))),
        shinydashboard::dashboardBody(
            volumr_css(),
            shinydashboard::tabItems(
                tab_home(), tab_data(), tab_encoding(), tab_payload(),
                tab_volume(), tab_theory(), tab_limits(), tab_about())),
        title = "volumr")
}

#' @noRd
volumr_server <- function(start_field, start_payload = NULL) {
    function(input, output, session) {
        rv <- shiny::reactiveValues(field = start_field, enc = NULL, pay = NULL,
                                    page = NULL, message = NULL, camera = NULL,
                                    view = start_payload, nonce = 0)

        # ------------------------------------------------------------- data
        output$nc_controls <- shiny::renderUI({
            f <- input$upload
            if (is.null(f) || !grepl("\\.nc4?$", f$name, ignore.case = TRUE))
                return(NULL)
            shiny::tagList(
                shiny::textInput("nc_var", "Variable", ""),
                shiny::numericInput("nc_time", "Index along any further axis", 1, 1))
        })

        shiny::observeEvent(input$load, {
            shiny::withProgress(message = "Reading the field", value = 0.3, {
                out <- tryCatch({
                    f <- if (identical(input$source_kind, "packaged")) start_field
                         else read_uploaded(input$upload, input$nc_var, input$nc_time)
                    if (input$step > 1L) f <- decimate(f, input$step)
                    f
                }, error = function(e) e)
            })
            if (inherits(out, "error")) {
                rv$message <- list(stage = "data", text = conditionMessage(out))
            } else {
                rv$message <- NULL
                rv$field <- out
                rv$enc <- NULL; rv$pay <- NULL; rv$page <- NULL; rv$view <- NULL
            }
        })

        stage_message <- function(stage, lead) shiny::renderUI({
            m <- rv$message
            if (is.null(m) || !identical(m$stage, stage)) return(NULL)
            shiny::div(class = "alert alert-danger", shiny::strong(lead), m$text)
        })
        output$data_message <- stage_message("data", "The file could not be read. ")
        output$encode_message <- stage_message("encoding", "The field could not be encoded. ")
        output$payload_message <- stage_message("payload", "The payload could not be written. ")

        output$data_summary <- shiny::renderPrint(print(summary(rv$field)))
        output$home_field <- shiny::renderPrint(print(rv$field))

        output$level_slider <- shiny::renderUI({
            d <- rv$field$depth
            shiny::selectInput("level", "Depth", choices = stats::setNames(
                seq_along(d), paste0(fmt_m(d), " m")), selected = 1)
        })
        output$data_level <- shiny::renderPlot({
            k <- as.integer(input$level %||% 1L)
            plot(rv$field, type = "level", depth = rv$field$depth[k],
                 cmap = input$map_cmap %||% "matter")
        })
        output$data_levels <- shiny::renderTable({
            s <- summary(rv$field)$levels
            data.frame(Depth = fmt_m(s$depth),
                       `Cells present` = sprintf("%.1f %%", 100 * s$coverage),
                       Median = signif(s$median, 4), `99th` = signif(s$q99, 4),
                       check.names = FALSE)
        }, striped = TRUE, spacing = "xs")
        output$home_coverage <- shiny::renderPlot(plot(rv$field, type = "coverage"))
        output$home_profile <- shiny::renderPlot(plot(rv$field, type = "profile"))
        output$home_source <- shiny::renderUI({
            src <- rv$field$source
            if (is.null(src)) return(shiny::p(class = "small-note", "No provenance recorded."))
            shiny::tags$ul(lapply(c("name", "product", "doi", "reference_period"),
                function(k) if (!is.null(src[[k]]))
                    shiny::tags$li(shiny::strong(sub("_", " ", k)), ": ", src[[k]])))
        })

        # --------------------------------------------------------- encoding
        output$dz_control <- shiny::renderUI({
            if (!isTRUE(input$resample)) return(NULL)
            d <- rv$field$depth
            shiny::numericInput("dz", "Spacing of the uniform grid",
                                value = default_dz(d), min = 0, step = 0.5)
        })

        shiny::observeEvent(input$encode, {
            shiny::withProgress(message = "Encoding", value = 0.4, {
                out <- tryCatch({
                    f <- rv$field
                    if (isTRUE(input$resample) && !is_uniform(f$depth))
                        f <- vol_resample(f, dz = input$dz)
                    list(field = f, enc = vol_encode(f, transfer = input$transfer))
                }, error = function(e) e)
            })
            if (inherits(out, "error")) {
                rv$message <- list(stage = "encoding", text = conditionMessage(out))
            } else {
                rv$message <- NULL
                rv$field <- out$field; rv$enc <- out$enc
                rv$pay <- NULL; rv$page <- NULL
            }
        })

        output$encode_summary <- shiny::renderPrint({
            shiny::req(rv$enc)
            print(rv$enc); cat("\n"); print(summary(rv$enc))
        })
        output$encode_value <- shiny::renderPlot({
            shiny::req(rv$enc); plot(rv$enc, type = "value")
        })
        output$encode_depth <- shiny::renderPlot({
            shiny::req(rv$enc); plot(rv$enc, type = "depth")
        })

        # ---------------------------------------------------------- payload
        output$limits_control <- shiny::renderUI({
            v <- rv$field$values
            q <- stats::quantile(v[!is.na(v)], c(0.01, 0.99), names = FALSE)
            r <- range(v, na.rm = TRUE)
            shiny::sliderInput("limits", "Ends of the colour scale",
                               min = signif(r[1], 4), max = signif(r[2], 4),
                               value = signif(q, 4))
        })

        shiny::observeEvent(input$build, {
            shiny::withProgress(message = "Writing the payload", value = 0.2, {
                out <- tryCatch({
                    dir <- file.path(tempdir(), paste0("volumr_", as.integer(Sys.time())))
                    p <- vol_payload(
                        rv$field, dir, transfer = input$transfer %||% "sqrt",
                        display = list(vmin = input$limits[1], vmax = input$limits[2],
                                       cmap = input$cmap, gamma = input$gamma),
                        title = if (nzchar(input$title)) input$title else NULL,
                        subtitle = if (nzchar(input$subtitle)) input$subtitle else NULL)
                    shiny::incProgress(0.6, message = "Building the single file")
                    page <- vol_standalone(p, path = file.path(dir, "viewer.html"))
                    list(pay = p, page = page)
                }, error = function(e) e)
            })
            if (inherits(out, "error"))
                rv$message <- list(stage = "payload", text = conditionMessage(out))
            else { rv$message <- NULL; rv$pay <- out$pay; rv$page <- out$page }
        })

        output$payload_summary <- shiny::renderPrint({
            shiny::req(rv$pay)
            print(rv$pay); cat("\n"); print(summary(rv$pay))
        })
        output$payload_size <- shiny::renderPlot({
            shiny::req(rv$pay); plot(rv$pay, type = "size")
        })
        output$decoded_slider <- shiny::renderUI({
            shiny::req(rv$pay)
            d <- rv$pay$field$depth
            shiny::selectInput("decoded_level", "Depth", choices = stats::setNames(
                seq_along(d), paste0(fmt_m(d), " m")), selected = 1)
        })
        output$payload_level <- shiny::renderPlot({
            shiny::req(rv$pay)
            k <- as.integer(input$decoded_level %||% 1L)
            plot(rv$pay, type = "level", depth = rv$pay$field$depth[k],
                 cmap = input$cmap %||% "matter")
        })
        output$download_page <- shiny::downloadHandler(
            filename = function() "volume_viewer_standalone.html",
            content = function(file) {
                shiny::req(rv$page)
                file.copy(rv$page, file, overwrite = TRUE)
            }, contentType = "text/html")

        # ----------------------------------------------------------- volume
        # The page carries its own panel, so the application shows that and puts
        # nothing beside it. One control surface, and what a reader sets there is
        # what the file they download carries.
        payload_for_view <- shiny::reactive({
            if (!is.null(rv$pay)) return(rv$pay)
            if (!is.null(rv$view)) return(rv$view)
            shiny::withProgress(message = "Writing a payload for the view", value = 0.4, {
                vol_payload(rv$field, file.path(tempdir(), "volumr_view"))
            })
        })

        output$volume <- render_vol_widget({
            vol_widget(payload_for_view(), panel = TRUE, inputId = "volume")
        })

        output$view_source <- shiny::renderText({
            r <- input$volume_ready
            if (is.null(r)) return("Loading the payload.")
            sprintf("Showing %d by %d by %d, %s, built %s.%s", r$nx, r$ny, r$nz,
                    r$label, substr(r$created, 1, 10),
                    if (is.null(rv$pay)) "" else " Written in the payload tab.")
        })

        shiny::observeEvent(input$volume_camera, { rv$camera <- input$volume_camera })
        output$camera_line <- shiny::renderText({
            cam <- rv$camera
            if (is.null(cam)) return("The camera reports its position when it settles.")
            sprintf("Azimuth %.1f, elevation %.1f, distance %.2f%s",
                    cam$azim, cam$elev, cam$dist,
                    if (isTRUE(cam$ortho)) ", orthographic" else "")
        })

        # -------------------------------------------------------------- home
        output$box_grid <- shinydashboard::renderInfoBox({
            d <- dim(rv$field$values)
            shinydashboard::infoBox("Grid", sprintf("%d x %d", d[3], d[2]),
                                    "Longitudes by latitudes", icon = shiny::icon("border-all"),
                                    color = "aqua")
        })
        output$box_levels <- shinydashboard::renderInfoBox({
            d <- rv$field$depth
            shinydashboard::infoBox("Levels", length(d),
                                    sprintf("%s to %s m", fmt_m(d[1]), fmt_m(d[length(d)])),
                                    icon = shiny::icon("layer-group"), color = "blue")
        })
        output$box_coverage <- shinydashboard::renderInfoBox({
            shinydashboard::infoBox(
                "Cells present", sprintf("%.1f %%", 100 * mean(!is.na(rv$field$values))),
                "Of the full box", icon = shiny::icon("percent"), color = "teal")
        })
        output$box_payload <- shinydashboard::renderInfoBox({
            v <- if (is.null(rv$pay)) "not built" else
                sprintf("%.2f MB", sum(file.size(file.path(rv$pay$dir, rv$pay$files))) / 1e6)
            shinydashboard::infoBox("Payload", v, "Images plus the manifest",
                                    icon = shiny::icon("box"), color = "olive")
        })

        # ------------------------------------------------------------- about
        output$about_data <- shiny::renderUI(shiny::HTML(about_html(rv$field)))
        output$about_session <- shiny::renderPrint({
            cat("volumr", as.character(utils::packageVersion("volumr")), "\n")
            cat("zlib", zlib_runtime_version(), "\n")
            cat(R.version.string, "\n")
        })
    }
}

#' @noRd
read_uploaded <- function(up, nc_var = NULL, nc_time = 1L) {
    if (is.null(up)) stop("no file was chosen", call. = FALSE)
    ext <- tolower(tools::file_ext(up$name))
    obj <- switch(
        ext,
        rds = readRDS(up$datapath),
        nc = , nc4 = vol_read_netcdf(up$datapath,
                                     varid = if (nzchar(nc_var %||% "")) nc_var else NULL,
                                     time = nc_time %||% 1L),
        rda = , rdata = { e <- new.env(); load(up$datapath, envir = e)
                          get(ls(e)[1], envir = e) },
        csv = vol_field_from_df(utils::read.csv(up$datapath)),
        npy = stop("a single .npy file is one level and not a field; build the field with vol_field()",
                   call. = FALSE),
        stop("unknown file type: ", ext, call. = FALSE))
    as_vol_field(obj)
}

# Whatever the file gave back is put through the constructor, so a file that
# does not describe a field is refused with the reason.
#' @noRd
as_vol_field <- function(obj) {
    if (inherits(obj, "vol_field")) return(obj)
    if (is.list(obj) && all(c("values", "lon", "lat", "depth") %in% names(obj)))
        return(do.call(vol_field, obj[intersect(names(obj),
            c("values", "lon", "lat", "depth", "name", "unit", "mask", "source"))]))
    stop("the file holds a ", class(obj)[1],
         ", not a vol_field and not a list with values, lon, lat and depth",
         call. = FALSE)
}

#' @noRd
about_html <- function(field) {
    src <- field$source
    if (is.null(src$product))
        return("<p>The field in hand carries no recorded provenance.</p>")
    paste0(
      "<p>The case study is marine heatwave cumulative intensity in the
       Mediterranean Sea over the 0 to 250 m layer, computed on a grid of a
       twenty-fourth of a degree and fifteen measured depths against a
       ", src$reference_period, " reference period, following the definition of
       Hobday et al. (2016). The packaged field keeps every third point of that
       grid; the volume tab opens on the payload at the full grid.</p>
       <p>The temperature fields it rests on are the Copernicus Marine Service
       Mediterranean Sea physical reanalysis, product <code>", src$product,
      "</code>, <a href='https://doi.org/", src$doi, "'>doi:", src$doi, "</a>,
       described by Escudier et al. (2021).</p>
       <h4>References</h4>
       <p>Escudier, R., Clementi, E., Cipollone, A., Pistoia, J., Drudi, M.,
       Grandi, A., Lyubartsev, V., Lecci, R., Aydogdu, A., Delrosso, D., Omar, M.,
       Masina, S., Coppini, G., &amp; Pinardi, N. (2021). A high resolution
       reanalysis for the Mediterranean Sea. <i>Frontiers in Earth Science</i>, 9,
       702285. <a href='https://doi.org/10.3389/feart.2021.702285'>doi:10.3389/feart.2021.702285</a></p>
       <p>Hobday, A. J., Alexander, L. V., Perkins, S. E., Smale, D. A., Straub,
       S. C., Oliver, E. C. J., Benthuysen, J. A., Burrows, M. T., Donat, M. G.,
       Feng, M., Holbrook, N. J., Moore, P. J., Scannell, H. A., Sen Gupta, A., &amp;
       Wernberg, T. (2016). A hierarchical approach to defining marine heatwaves.
       <i>Progress in Oceanography</i>, 141, 227-238.
       <a href='https://doi.org/10.1016/j.pocean.2015.12.014'>doi:10.1016/j.pocean.2015.12.014</a></p>
       <p>Thyng, K. M., Greene, C. A., Hetland, R. D., Zimmerle, H. M., &amp;
       DiMarco, S. F. (2016). True colors of oceanography: guidelines for effective
       and accurate colormap selection. <i>Oceanography</i>, 29(3), 9-13.
       <a href='https://doi.org/10.5670/oceanog.2016.66'>doi:10.5670/oceanog.2016.66</a></p>")
}

Try the volumr package in your browser

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

volumr documentation built on Dec. 2, 2026, 5:07 p.m.