R/encode.R

Defines functions plot.vol_encoding print.summary.vol_encoding summary.vol_encoding print.vol_encoding vol_encode

Documented in plot.vol_encoding print.vol_encoding summary.vol_encoding vol_encode

# ============================ #
# The transfer into 8 bits     #
# ============================ #

#' Carry a field into 8 bits
#'
#' @title Carry a field into 8 bits
#' @description Quantises the field to the 254 codes an 8-bit texture channel
#'   can carry, through a monotone transfer, and measures the error the
#'   quantisation costs against the values it started from.
#' @param field A `vol_field`.
#' @param transfer Name of the transfer: `"sqrt"`, `"linear"`, or `"auto"`,
#'   which takes the square root for a non-negative field and the linear ramp
#'   for any other.
#' @return A list of class `vol_encoding` with `codes`, an integer array of the
#'   same shape as the field holding 0 for a missing cell and 1 to 254
#'   otherwise; `transfer`, the record the manifest carries; and `error`, the
#'   absolute error at every cell that carries a value.
#' @details Eight bits per cell is what makes the payload small enough to travel
#'   inside a page, and the transfer decides where those bits are spent. With
#'   \eqn{v} the value, \eqn{v_{lo}} and \eqn{v_{hi}} its extremes and \eqn{N =
#'   254} the codes available, the square-root transfer writes
#'   \deqn{c = 1 + \mathrm{round}\!\left((N-1)\,
#'         \frac{\sqrt{v} - \sqrt{v_{lo}}}{\sqrt{v_{hi}} - \sqrt{v_{lo}}}\right),}
#'   and the renderer inverts it by squaring. A strongly skewed positive field
#'   is served far better by that than by a linear ramp, because the linear ramp
#'   spends most of its codes on a tail that holds few cells.
#'
#'   The error is reported and not assumed. For the case study the root mean
#'   square error is 0.27 and the worst single cell 1.66 degrees Celsius days,
#'   against a field that reaches 580, and the plotted colour bands are 2.5
#'   wide, so the quantisation is well inside the resolution of the picture.
#'
#'   Code 0 is reserved for a missing cell, so the codes that carry data are 1
#'   to 254. The renderer tests the companion mask before it reads a value, so a
#'   missing cell contributes nothing to the ray. A constant field takes code 1
#'   everywhere and decodes to the constant to within rounding.
#' @examples
#' data(med_mhw)
#' e <- vol_encode(vol_resample(med_mhw))
#' e
#' summary(e)
#' plot(e)
#' plot(e, type = "depth")
#' @seealso [vol_field()] for the input, [vol_resample()] for the step before,
#'   [vol_payload()] for the step after, [print.vol_encoding()],
#'   [summary.vol_encoding()] and [plot.vol_encoding()] for the methods that
#'   report the error.
#' @export
vol_encode <- function(field, transfer = c("auto", "sqrt", "linear")) {
    stopifnot(inherits(field, "vol_field"))
    transfer <- match.arg(transfer)
    v <- field$values
    ok <- !is.na(v)
    if (!any(ok)) stop("the field carries no values", call. = FALSE)
    lo <- min(v[ok]); hi <- max(v[ok])
    if (transfer == "auto") transfer <- if (lo >= 0) "sqrt" else "linear"
    if (transfer == "sqrt" && lo < 0)
        stop("the square-root transfer needs a non-negative field; use transfer = \"linear\"",
             call. = FALSE)
    fwd <- if (transfer == "sqrt") sqrt else identity
    inv <- if (transfer == "sqrt") function(x) x ^ 2 else identity
    rlo <- fwd(lo); rhi <- fwd(hi)
    q <- array(0L, dim(v))
    # A constant field has no range to spread over the codes; every cell takes
    # code 1 and decodes to the constant exactly.
    tt <- if (rhi > rlo) (fwd(v[ok]) - rlo) / (rhi - rlo) else numeric(sum(ok))
    q[ok] <- as.integer(pmin(pmax(round(tt * (VOL_CODES - 1L)) + 1, 1), VOL_CODES))
    back <- inv((q[ok] - 1) / (VOL_CODES - 1L) * (rhi - rlo) + rlo)
    err <- abs(v[ok] - back)
    structure(list(
        codes = q,
        transfer = list(kind = transfer, lo = lo, hi = hi, codes = VOL_CODES,
                        nodata = 0L, rms_error = sqrt(mean(err ^ 2)),
                        max_error = max(err)),
        error = err, value = v[ok], depth = field$depth,
        name = field$name, unit = field$unit, geographic = field$geographic),
        class = "vol_encoding")
}

#' Print the transfer into 8 bits
#'
#' @title Print the transfer into 8 bits
#' @description Reports the transfer, the range it covers and the error it
#'   costs, which is the number that decides whether 8 bits are enough.
#' @param x A `vol_encoding`.
#' @param ... Ignored.
#' @return `x`, invisibly.
#' @details Read the error against the width of a colour band the reader will
#'   see. An error well under one band cannot move a cell into the wrong colour.
#' @examples
#' data(med_mhw)
#' vol_encode(vol_resample(med_mhw))
#' @seealso [vol_encode()] for the constructor, [summary.vol_encoding()] for the
#'   error by decile, [plot.vol_encoding()] for the same as a figure.
#' @export
print.vol_encoding <- function(x, ...) {
    t <- x$transfer
    cat(get_colored_symbol("info"), " Transfer into 8 bits: ", t$kind, "\n", sep = "")
    cat(sprintf("Range = %.4g to %.4g over %d codes, 0 reserved for no data\n",
                t$lo, t$hi, t$codes))
    cat(sprintf("Error = %.4g rms, %.4g at worst%s\n", t$rms_error, t$max_error,
                if (nzchar(x$unit)) paste0(" ", x$unit) else ""))
    cat(sprintf("Cells = %d carrying a value of %d\n", length(x$error), length(x$codes)))
    invisible(x)
}

#' Summarise the cost of the transfer
#'
#' @title Summarise the cost of the transfer
#' @description Reports where in the range of the field the quantisation error
#'   falls, which a single root mean square figure hides.
#' @param object A `vol_encoding`.
#' @param bins Number of value bins the error is summarised over.
#' @param ... Ignored.
#' @return An object of class `summary.vol_encoding`, holding the transfer
#'   record and a data frame of one row per bin with the count, the mean error
#'   and the worst error in that bin.
#' @details A monotone transfer costs more where it is flat. The square-root
#'   transfer is flat at the top of the range, so the worst errors sit in the
#'   tail, and the table below says by how much. Compare the worst error in a
#'   bin against the width of the colour bands a reader will see: an error well
#'   under one band cannot move a cell into the wrong colour.
#' @examples
#' data(med_mhw)
#' summary(vol_encode(vol_resample(med_mhw)))
#' @seealso [vol_encode()] for the constructor, [print.vol_encoding()] and
#'   [plot.vol_encoding()] for the other methods, [vol_payload()] for the step
#'   that writes these codes into images.
#' @export
summary.vol_encoding <- function(object, bins = 10L, ...) {
    v <- object$value; e <- object$error
    br <- stats::quantile(v, seq(0, 1, length.out = bins + 1L), names = FALSE)
    br[1] <- br[1] - 1e-9; br[length(br)] <- br[length(br)] + 1e-9
    br <- unique(br)
    g <- cut(v, br, include.lowest = TRUE)
    df <- data.frame(
        from = br[-length(br)], to = br[-1],
        n = as.integer(table(g)),
        mean_error = as.numeric(tapply(e, g, mean)),
        max_error = as.numeric(tapply(e, g, max)))
    structure(list(transfer = object$transfer, bins = df,
                   name = object$name, unit = object$unit),
              class = "summary.vol_encoding")
}

#' @noRd
#' @export
print.summary.vol_encoding <- function(x, ...) {
    t <- x$transfer
    cat(get_colored_symbol("info"), " Transfer into 8 bits: ", t$kind,
        ", error by decile of the value\n", sep = "")
    df <- x$bins
    df$from <- signif(df$from, 4); df$to <- signif(df$to, 4)
    df$mean_error <- signif(df$mean_error, 3); df$max_error <- signif(df$max_error, 3)
    print(df, row.names = FALSE)
    cat(sprintf("Overall = %.4g rms, %.4g at worst\n", t$rms_error, t$max_error))
    invisible(x)
}

#' Plot the cost of the transfer
#'
#' @title Plot the cost of the transfer
#' @description Draws the quantisation error against the value it was measured
#'   at, and the depth profile of that error.
#' @param x A `vol_encoding`.
#' @param type One of `"value"` or `"depth"`.
#' @param bins Number of value bins.
#' @param ... Ignored.
#' @return A `ggplot` object, returned invisibly.
#' @details The first view is the diagnostic that decides whether the transfer
#'   was the right one. A square-root transfer on a positive skewed field gives
#'   an error that grows with the value, slowly, and stays flat across the range
#'   where most of the cells are; an error that spikes in the middle of the
#'   range says the transfer is wrong for this field.
#' @examples
#' data(med_mhw)
#' e <- vol_encode(vol_resample(med_mhw))
#' plot(e)
#' plot(e, type = "depth")
#' @seealso [vol_encode()] for the constructor, [print.vol_encoding()] and
#'   [summary.vol_encoding()] for the other methods, [vol_payload()] for the
#'   step that writes these codes into images.
#' @export
plot.vol_encoding <- function(x, type = c("value", "depth"), bins = 40L, ...) {
    type <- match.arg(type)
    lab <- if (nzchar(x$unit)) paste0(" (", x$unit, ")") else ""
    if (type == "value") {
        br <- stats::quantile(x$value, seq(0, 1, length.out = bins + 1L), names = FALSE)
        br <- unique(br); g <- cut(x$value, br, include.lowest = TRUE)
        df <- data.frame(value = as.numeric(tapply(x$value, g, stats::median)),
                         mean_error = as.numeric(tapply(x$error, g, mean)),
                         max_error = as.numeric(tapply(x$error, g, max)))
        p <- ggplot2::ggplot(df, ggplot2::aes(x = value)) +
            ggplot2::geom_ribbon(ggplot2::aes(ymin = 0, ymax = max_error),
                                 fill = "grey85", na.rm = TRUE) +
            ggplot2::geom_path(ggplot2::aes(y = mean_error), linewidth = 0.7,
                               na.rm = TRUE) +
            ggplot2::labs(
                title = "Cost of the transfer into 8 bits",
                subtitle = sprintf("Mean and worst absolute error in %d bins of equal count, %s transfer",
                                   length(levels(g)), x$transfer$kind),
                x = paste0(x$name, lab), y = paste0("Absolute error", lab),
                caption = plot_caption("The line is the mean error in the bin and the band reaches the worst cell in it. A monotone transfer costs most where it is flat, which for the square root is the top of the range. Drawn by plot.vol_encoding()."))
        return(invisible(print(p + volumr_theme())))
    }
    # `error` was extracted in the linear order of the array, whose first index
    # is depth, so the level of each entry comes from that index and not from a
    # scan level by level.
    nz <- dim(x$codes)[1]
    k <- ((which(x$codes > 0L) - 1L) %% nz) + 1L
    df <- data.frame(depth = x$depth[k], error = x$error)
    agg <- stats::aggregate(error ~ depth, df, function(v) c(mean(v), max(v)))
    out <- data.frame(depth = agg$depth, mean_error = agg$error[, 1],
                      max_error = agg$error[, 2])
    p <- ggplot2::ggplot(out, ggplot2::aes(y = depth)) +
        ggplot2::geom_ribbon(ggplot2::aes(xmin = 0, xmax = max_error),
                             fill = "grey85", na.rm = TRUE) +
        ggplot2::geom_path(ggplot2::aes(x = mean_error), linewidth = 0.7, na.rm = TRUE) +
        ggplot2::scale_y_reverse() +
        ggplot2::labs(title = "Cost of the transfer against depth",
            subtitle = "Mean and worst absolute error at each level of the uniform grid",
            x = paste0("Absolute error", lab), y = depth_label(x),
            caption = plot_caption("One transfer serves the whole volume, so a level whose values sit in the flat part of the transfer pays more than a level whose values do not. Drawn by plot.vol_encoding(type = \"depth\")."))
    invisible(print(p + volumr_theme()))
}

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.