R/payload.R

Defines functions plot.vol_payload print.summary.vol_payload summary.vol_payload print.vol_payload decimate default_limits vol_payload

Documented in plot.vol_payload print.vol_payload summary.vol_payload vol_payload

# ============================ #
# The browser payload          #
# ============================ #

#' Write the browser payload of a field
#'
#' @title Write the browser payload of a field
#' @description Writes the directory the renderer reads: one image per depth
#'   level holding the quantised field, the image of the opaque sheet, the
#'   colour lookup image, and a manifest recording the grid, the transfer, the
#'   display defaults and a SHA-256 of every file written.
#' @param field A `vol_field`.
#' @param dir Directory to write into. Created when absent.
#' @param transfer Name of the transfer, passed to [vol_encode()]. The default
#'   takes the square root for a non-negative field and the linear ramp for any
#'   other.
#' @param display Named list of the defaults the viewer opens with: `vmin` and
#'   `vmax`, the ends of the colour scale; `cmap`, a name from
#'   [vol_colormaps()]; `gamma`; `od`, the opacity a ray accumulates across the
#'   full depth; and `ow`, how far that opacity follows the intensity. Any
#'   element left out takes its default, which is the 1st and 99th percentiles
#'   (rounded to integers when they lie ten or more units apart, and to three
#'   significant digits otherwise), `"matter"`, a gamma of 1, an opacity of 12,
#'   which is the top of the slider, and 0.
#' @param step Horizontal decimation. 1 keeps the native grid.
#' @param resample Logical. Put the depth axis on a uniform grid first, when it
#'   is not already uniform.
#' @param dz Spacing of that grid, passed to [vol_resample()].
#' @param created Timestamp written into the manifest. Defaults to the current
#'   time in UTC. Pin it to make two builds of one field give one set of bytes.
#' @param title Heading the viewer shows. Defaults to the name of the field.
#' @param subtitle Line under the heading. Defaults to the name of the field and
#'   the depth span.
#' @param axes Named list with `x`, `y` and `z`, the axis titles. Defaults to
#'   longitude, latitude and depth.
#' @param geographic Logical. When `TRUE`, tick labels carry the compass
#'   letters; when `FALSE`, they are plain numbers. Taken from the field when
#'   left `NULL`.
#' @param depth_unit Unit of the vertical axis, used in the readouts. Defaults
#'   to metres for a geographic field and to none for any other.
#' @return An object of class `vol_payload`: a list with `dir`, `manifest`,
#'   `files`, `encoding` and `field`.
#' @details Every level is written as an 8-bit greyscale PNG, because a browser
#'   decodes PNG natively, the format is lossless, and one image per level lets
#'   the loader build a three-dimensional texture without any custom container.
#'   The whole cube of the case study at its native grid, 1016 by 380 by 21,
#'   travels in about 1.5 MB this way ([vol_example_payload()]).
#'
#'   The horizontal grid is not reduced by default, and `step` exists for the
#'   cases where it must be. A block mean to half the resolution already costs
#'   an error comparable with the width of a plotted colour band, whereas the
#'   transfer into 8 bits costs a small fraction of one; spending the bits on
#'   the vertical and on the value range rather than on the horizontal grid is
#'   what keeps the payload both small and faithful.
#'
#'   The manifest records the SHA-256 of every file it names, and carries
#'   through the digests of the arrays the field came from when the field
#'   carries them, so a rendering can be traced back to its inputs.
#' @examples
#' data(med_mhw)
#' p <- vol_payload(med_mhw, tempfile("payload"))
#' p
#' summary(p)
#' plot(p)
#' plot(p, type = "level", depth = 50)
#' vol_standalone(p, path = tempfile(fileext = ".html"))
#' @seealso [vol_field()] for the input, [vol_encode()] for the transfer,
#'   [vol_standalone()] to carry the payload inside one HTML file,
#'   [vol_widget()] to render it in \pkg{shiny} or R Markdown,
#'   [print.vol_payload()], [summary.vol_payload()] and [plot.vol_payload()]
#'   for the methods.
#' @export
vol_payload <- function(field, dir, transfer = "auto", display = NULL, step = 1L,
                        resample = TRUE, dz = NULL, created = NULL,
                        title = NULL, subtitle = NULL, axes = NULL,
                        geographic = NULL, depth_unit = NULL) {
    stopifnot(inherits(field, "vol_field"))
    if (is.null(geographic)) geographic <- !identical(field$geographic, FALSE)
    if (is.null(depth_unit)) depth_unit <- if (geographic) "m" else ""
    if (step > 1L) field <- decimate(field, step)
    if (resample && !is_uniform(field$depth)) field <- vol_resample(field, dz = dz)
    enc <- vol_encode(field, transfer = transfer)
    d <- dim(enc$codes)
    nz <- d[1]; ny <- d[2]; nx <- d[3]
    dir.create(dir, showWarnings = FALSE, recursive = TRUE)

    slices <- vector("list", nz)
    for (k in seq_len(nz)) {
        name <- sprintf("slice_%02d.png", k - 1L)
        write_png(matrix(enc$codes[k, , ], ny, nx), file.path(dir, name))
        slices[[k]] <- list(file = name, depth = field$depth[k],
                            sha256 = digest::digest(file.path(dir, name),
                                                    algo = "sha256", file = TRUE))
    }
    mask <- if (is.null(field$mask)) matrix(FALSE, ny, nx) else field$mask
    write_png(matrix(as.integer(mask) * 255L, ny, nx), file.path(dir, "land.png"))
    write_png(colormap_table(), file.path(dir, "colormaps.png"))

    if (is.null(display)) display <- list()
    if (is.null(display$vmin) || is.null(display$vmax)) {
        lim <- default_limits(enc$value)
        display$vmin <- display$vmin %||% lim[1]
        display$vmax <- display$vmax %||% lim[2]
    }
    display$cmap <- display$cmap %||% "matter"
    display$gamma <- display$gamma %||% 1
    # The viewer opens opaque, with every cell that carries a value counting the
    # same, which is what the printed figure does and what a reader asking "where
    # is the field" wants to see first. Lowering the density lets the interior
    # show through and is the second thing they reach for, not the first.
    display$od <- display$od %||% 12
    display$ow <- display$ow %||% 0
    display <- display[c("vmin", "vmax", "cmap", "gamma", "od", "ow")]
    if (is.null(created))
        created <- format(as.POSIXct(Sys.time(), tz = "UTC"), "%Y-%m-%dT%H:%M:%S+00:00")

    # Row 0 of every image is the southernmost latitude and column 0 the
    # westernmost longitude. The stated bounds are the coordinates of the
    # outermost texel centres and not the outer edges of those cells.
    man <- list(
        created = created,
        source = if (!is.null(field$source$name)) field$source$name else "field",
        label = field$name,
        unit = field$unit,
        depth_unit = depth_unit,
        axes = if (is.null(axes))
            list(x = if (geographic) "Longitude" else "X",
                 y = if (geographic) "Latitude" else "Y",
                 z = if (geographic) paste0("Depth (", depth_unit, ")") else "Z")
            else axes,
        geographic = isTRUE(geographic),
        title = if (is.null(title)) field$name else title,
        subtitle = if (is.null(subtitle))
            trimws(sprintf("%s, %s to %s %s.", field$name, fmt_m(field$depth[1]),
                           fmt_m(field$depth[nz]), depth_unit)) else subtitle,
        nx = as.integer(nx), ny = as.integer(ny), nz = as.integer(nz),
        step = as.integer(step),
        lon0 = field$lon[1], lon1 = field$lon[nx],
        lat0 = field$lat[1], lat1 = field$lat[ny],
        depths = field$depth,
        transfer = enc$transfer,
        value_range = c(enc$transfer$lo, enc$transfer$hi),
        display = display,
        colormaps = vol_colormaps(),
        slices = slices,
        land = list(file = "land.png",
                    sha256 = digest::digest(file.path(dir, "land.png"),
                                            algo = "sha256", file = TRUE)),
        colormap_file = list(file = "colormaps.png",
                             sha256 = digest::digest(file.path(dir, "colormaps.png"),
                                                     algo = "sha256", file = TRUE)))
    if (!is.null(field$source$sha256))
        man$source_sha256 <- as.list(field$source$sha256)
    writeBin(charToRaw(to_json(man, indent = 1L)), file.path(dir, "manifest.json"))

    files <- c(vapply(slices, function(s) s$file, ""), "land.png", "colormaps.png",
               "manifest.json")
    structure(list(dir = dir, manifest = man, files = files, encoding = enc,
                   field = field), class = "vol_payload")
}

# The 1st and 99th percentiles, as integers when they lie ten or more units
# apart and to three significant digits otherwise, so that a field of small
# values keeps a colour scale of nonzero width. A field whose percentiles
# coincide takes its full range, and a constant field a unit either side.
#' @noRd
default_limits <- function(v) {
    q <- stats::quantile(v, c(0.01, 0.99), names = FALSE)
    lim <- if (round(q[2]) - round(q[1]) >= 10) as.integer(round(q)) else signif(q, 3)
    if (lim[2] <= lim[1]) lim <- signif(range(v), 3)
    if (lim[2] <= lim[1]) lim <- lim[1] + c(-1, 1) * max(abs(lim[1]), 1) / 2
    lim
}

#' @noRd
decimate <- function(field, step) {
    ix <- seq(1L, length(field$lon), by = step)
    iy <- seq(1L, length(field$lat), by = step)
    field$values <- field$values[, iy, ix, drop = FALSE]
    field$lon <- field$lon[ix]; field$lat <- field$lat[iy]
    if (!is.null(field$mask)) field$mask <- field$mask[iy, ix, drop = FALSE]
    field
}

#' Print a browser payload
#'
#' @title Print a browser payload
#' @description Reports where the payload was written, the grid it covers, the
#'   transfer it used, its size and the settings the viewer will open with.
#' @param x A `vol_payload`.
#' @param ... Ignored.
#' @return `x`, invisibly.
#' @details The size is the whole directory, images and manifest together, which
#'   is what a page fetches over http. The single file that carries the same
#'   payload inline is about a third larger, since base64 costs that.
#' @examples
#' data(med_mhw)
#' vol_payload(med_mhw, tempfile("payload"))
#' @seealso [vol_payload()] for the constructor, [summary.vol_payload()] for the
#'   size level by level, [plot.vol_payload()] for the figures,
#'   [vol_standalone()] for the single-file build.
#' @export
print.vol_payload <- function(x, ...) {
    m <- x$manifest
    total <- sum(file.size(file.path(x$dir, x$files)))
    cat(get_colored_symbol("success"), " Browser payload in ", x$dir, "\n", sep = "")
    cat(sprintf("Grid = %d x %d x %d, depths %g to %g%s\n", m$nx, m$ny, m$nz,
                m$depths[1], m$depths[m$nz],
                if (nzchar(m$depth_unit %||% "")) paste0(" ", m$depth_unit) else ""))
    cat(sprintf("Transfer = %s, error %.4g rms and %.4g at worst\n",
                m$transfer$kind, m$transfer$rms_error, m$transfer$max_error))
    cat(sprintf("Files = %d, %.2f MB in total\n", length(x$files), total / 1e6))
    cat(sprintf("Display = %s from %g to %g, gamma %g\n", m$display$cmap,
                m$display$vmin, m$display$vmax, m$display$gamma))
    invisible(x)
}

#' Summarise a browser payload
#'
#' @title Summarise a browser payload
#' @description Reports the size of the payload level by level, together with
#'   the grid and the transfer, which is what decides whether it will travel
#'   inside a page.
#' @param object A `vol_payload`.
#' @param ... Ignored.
#' @return An object of class `summary.vol_payload` with `manifest`, a data
#'   frame `levels` of one row per image with its depth, byte count and
#'   coverage, and the totals.
#' @details Compression does the work that decimation would otherwise have to.
#'   A level that is mostly missing compresses to almost nothing, and a level
#'   full of structure does not, so the byte counts in the table below are a
#'   direct read of where the information sits in the water column.
#' @examples
#' data(med_mhw)
#' summary(vol_payload(med_mhw, tempfile("payload")))
#' @seealso [vol_payload()] for the constructor, [print.vol_payload()] for the
#'   one-screen report, [plot.vol_payload()] for the same numbers as a figure,
#'   [vol_standalone()] for the single-file build.
#' @export
summary.vol_payload <- function(object, ...) {
    m <- object$manifest
    sizes <- vapply(m$slices, function(s) file.size(file.path(object$dir, s$file)), 0)
    cov <- vapply(seq_len(m$nz), function(k) mean(object$encoding$codes[k, , ] > 0L), 0)
    structure(list(
        manifest = m,
        levels = data.frame(depth = vapply(m$slices, function(s) s$depth, 0),
                            bytes = sizes, coverage = cov),
        total_bytes = sum(file.size(file.path(object$dir, object$files))),
        dir = object$dir),
        class = "summary.vol_payload")
}

#' @noRd
#' @export
print.summary.vol_payload <- function(x, ...) {
    m <- x$manifest
    cat(get_colored_symbol("info"), " Browser payload, ", m$nz, " levels\n", sep = "")
    df <- x$levels
    df$bytes <- format(df$bytes, big.mark = ",")
    df$coverage <- sprintf("%.1f %%", 100 * x$levels$coverage)
    print(df, row.names = FALSE)
    cat(sprintf("Total = %.2f MB, %.0f bytes per level on average\n",
                x$total_bytes / 1e6, mean(x$levels$bytes)))
    cat(sprintf("Transfer = %s, %.4g rms\n", m$transfer$kind, m$transfer$rms_error))
    invisible(x)
}

#' Plot a browser payload
#'
#' @title Plot a browser payload
#' @description Draws where the bytes of the payload go, level by level, against
#'   how much of each level carries a value.
#' @param x A `vol_payload`.
#' @param type One of `"size"` or `"level"`.
#' @param depth Depth for `type = "level"`, which draws the level as the browser
#'   will read it, decoded from its image.
#' @param ... Passed to [plot.vol_field()] for `type = "level"`.
#' @return A `ggplot` object, returned invisibly.
#' @details The size panel is the honest picture of what compression is doing.
#'   A level whose cells are mostly absent costs a few kilobytes whatever its
#'   nominal dimensions, so the payload of a marine field is dominated by the
#'   shallow levels where the basin is widest.
#' @examples
#' data(med_mhw)
#' p <- vol_payload(med_mhw, tempfile("payload"))
#' plot(p)
#' plot(p, type = "level", depth = 50)
#' @seealso [vol_payload()] for the constructor, [print.vol_payload()] and
#'   [summary.vol_payload()] for the other methods, [plot.vol_field()] for the
#'   level view it delegates to.
#' @export
plot.vol_payload <- function(x, type = c("size", "level"), depth = NULL, ...) {
    type <- match.arg(type)
    s <- summary(x)
    if (type == "size") {
        df <- s$levels
        df$kb <- df$bytes / 1024
        p <- ggplot2::ggplot(df, ggplot2::aes(x = kb, y = depth)) +
            ggplot2::geom_path(linewidth = 0.7) +
            ggplot2::geom_point(ggplot2::aes(size = coverage)) +
            ggplot2::scale_y_reverse() +
            ggplot2::scale_size_continuous(name = "Cells present",
                                           labels = function(v) sprintf("%.0f %%", 100 * v)) +
            ggplot2::labs(title = "Size of the payload against depth",
                subtitle = sprintf("One 8-bit image per level, %d levels, %.2f MB in total",
                                   nrow(df), s$total_bytes / 1e6),
                x = "Level size (kB)", y = depth_label(x$field),
                caption = plot_caption("A level whose cells are mostly absent compresses to almost nothing, so the size of a level reads as the width of the basin at that depth. Drawn by plot.vol_payload()."))
        return(invisible(print(p + volumr_theme())))
    }
    f <- x$field
    k <- if (is.null(depth)) 1L else which.min(abs(f$depth - depth))
    t <- x$manifest$transfer
    inv <- if (t$kind == "sqrt") function(v) v ^ 2 else identity
    fwd <- if (t$kind == "sqrt") sqrt else identity
    code <- x$encoding$codes[k, , ]
    v <- inv((code - 1) / (t$codes - 1L) * (fwd(t$hi) - fwd(t$lo)) + fwd(t$lo))
    v[code == 0L] <- NA_real_
    g <- f
    g$values <- array(v, c(1L, dim(v)))
    g$depth <- f$depth[k]
    g$name <- paste0(f$name, ", decoded")
    plot(g, type = "level", ...)
}

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.