R/field.R

Defines functions plot.vol_field print.summary.vol_field summary.vol_field print.vol_field vol_field

Documented in plot.vol_field print.vol_field summary.vol_field vol_field

# ============================ #
# The gridded field            #
# ============================ #

#' Wrap a gridded three-dimensional field
#'
#' @title Wrap a gridded three-dimensional field
#' @description Builds the object every other function in the package takes: a
#'   scalar field on a regular longitude, latitude and depth grid, with the
#'   coordinate vectors, the units and the provenance carried alongside the
#'   values.
#' @param values Numeric array of dimension `c(nz, ny, nx)`, indexed by depth,
#'   then latitude, then longitude. Missing cells are `NA`.
#' @param lon Numeric vector of `nx` longitudes, strictly increasing.
#' @param lat Numeric vector of `ny` latitudes, strictly increasing from south
#'   to north.
#' @param depth Numeric vector of `nz` positions along the third axis, strictly
#'   increasing. For a marine field these are depths in metres, positive
#'   downward, with the surface at or near zero; an axis measured upward is
#'   negated before it gets here, so the values may be negative.
#' @param name Short name of the quantity, used in labels.
#' @param unit Unit of the quantity, used in labels.
#' @param mask Optional logical matrix of dimension `c(ny, nx)`, `TRUE` where an
#'   opaque sheet is drawn at zero depth. Land, for a marine field.
#' @param source Optional named list of provenance strings, carried into the
#'   payload manifest.
#' @param geographic Logical. `TRUE` when the first two axes are longitude and
#'   latitude, which decides the axis names and the tick labels the viewer
#'   draws. `FALSE` for any other pair, which are then reported as X and Y.
#' @return An object of class `vol_field`: a list with the elements `values`,
#'   `lon`, `lat`, `depth`, `name`, `unit`, `mask`, `source` and `geographic`.
#' @details The index order is fixed and is not a matter of taste. A browser
#'   payload is one image per depth level, and an image is a matrix of rows by
#'   columns, so a level of the field has to be contiguous as `values[k, , ]`
#'   with latitude down the rows and longitude across the columns. Row one of a
#'   level is the southernmost latitude and column one the westernmost
#'   longitude, which is the orientation the renderer assumes and the manifest
#'   records.
#'
#'   The constructor checks that the three coordinate vectors match the three
#'   dimensions of `values`, that each is numeric, complete and strictly
#'   increasing, and that `mask`, when given, matches the horizontal grid. It
#'   does not require the depth axis to be
#'   uniform: [vol_resample()] does that, and the browser payload needs it
#'   because the GPU samples a texture on a regular grid.
#'
#'   The value range may be anything the transfer of [vol_encode()] can carry.
#'   For a strictly positive and strongly skewed field, the square-root transfer
#'   spends its 254 codes where the data are.
#' @examples
#' v <- array(NA_real_, c(4, 20, 30))
#' for (k in 1:4) v[k, , ] <- outer(1:20, 1:30, function(i, j) exp(-k / 3) * (i + j))
#' f <- vol_field(v, lon = seq(10, 12.9, by = 0.1), lat = seq(40, 41.9, by = 0.1),
#'                depth = c(0, 10, 25, 50), name = "Tracer", unit = "mg/l")
#' f
#' summary(f)
#' plot(f)
#' plot(f, type = "profile")
#' plot(f, type = "coverage")
#' @seealso [print.vol_field()], [summary.vol_field()] and [plot.vol_field()]
#'   for the methods,
#'   [vol_resample()] to put the depth axis on a uniform grid, [vol_encode()]
#'   for the transfer into 8 bits, [vol_payload()] to write the browser payload,
#'   [vol_read_npy()] and [vol_read_netcdf()] to read a field from a file.
#' @export
vol_field <- function(values, lon, lat, depth, name = "value", unit = "",
                      mask = NULL, source = NULL, geographic = TRUE) {
    if (!is.array(values) || length(dim(values)) != 3L)
        stop("`values` must be a three-dimensional array", call. = FALSE)
    d <- dim(values)
    if (d[1] != length(depth) || d[2] != length(lat) || d[3] != length(lon))
        stop("`values` has dimension ", paste(d, collapse = " x "),
             " and the coordinates say ", length(depth), " x ", length(lat),
             " x ", length(lon), call. = FALSE)
    for (nm in c("lon", "lat", "depth")) {
        v <- get(nm)
        if (!is.numeric(v) || anyNA(v)) stop("`", nm, "` must be numeric and complete",
                                             call. = FALSE)
        if (length(v) > 1L && any(diff(v) <= 0))
            stop("`", nm, "` must be strictly increasing", call. = FALSE)
    }
    if (!is.null(mask)) {
        if (!is.logical(mask) || !identical(dim(mask), d[2:3]))
            stop("`mask` must be a logical matrix of ", d[2], " x ", d[3],
                 call. = FALSE)
    }
    structure(list(values = values, lon = as.numeric(lon), lat = as.numeric(lat),
                   depth = as.numeric(depth), name = name, unit = unit,
                   mask = mask, source = source, geographic = isTRUE(geographic)),
              class = "vol_field")
}

#' Print a gridded field
#'
#' @title Print a gridded field
#' @description Reports the grid, the span of each axis, the range of the values
#'   and the fraction of cells that carry one, in one screen.
#' @param x A `vol_field`.
#' @param ... Ignored.
#' @return `x`, invisibly.
#' @details The axis names follow the `geographic` element of the field, so a
#'   field on longitude and latitude is reported as such and a field on an
#'   arbitrary pair of axes is reported as X and Y.
#' @examples
#' data(med_mhw)
#' med_mhw
#' @seealso [vol_field()] for the constructor, [summary.vol_field()] for the
#'   numbers level by level, [plot.vol_field()] for the views.
#' @export
print.vol_field <- function(x, ...) {
    d <- dim(x$values)
    ax <- axis_names(x)
    cat(get_colored_symbol("info"), " Gridded field: ", x$name,
        if (nzchar(x$unit)) paste0(" (", x$unit, ")") else "", "\n", sep = "")
    cat(sprintf("Grid = %d by %d by %d, %s by %s by %s\n", d[3], d[2], d[1],
                tolower(ax[1]), tolower(ax[2]), tolower(ax[3])))
    cat(sprintf("%s = %.4f to %.4f, step %.5f\n", ax[1], x$lon[1], x$lon[d[3]],
                if (d[3] > 1) mean(diff(x$lon)) else NA_real_))
    cat(sprintf("%s = %.4f to %.4f, step %.5f\n", ax[2], x$lat[1], x$lat[d[2]],
                if (d[2] > 1) mean(diff(x$lat)) else NA_real_))
    cat(sprintf("%s = %g to %g over %d levels%s\n", ax[3], x$depth[1], x$depth[d[1]],
                d[1], if (is_uniform(x$depth)) ", uniformly spaced" else
                      ", unevenly spaced"))
    ok <- !is.na(x$values)
    if (any(ok)) cat(sprintf("Values = %.4g to %.4g, %.1f %% of cells present\n",
                             min(x$values[ok]), max(x$values[ok]), 100 * mean(ok)))
    else cat("Values = none present\n")
    if (!is.null(x$mask)) cat(sprintf("Mask = %.1f %% of the surface\n", 100 * mean(x$mask)))
    invisible(x)
}

#' Summarise a gridded field
#'
#' @title Summarise a gridded field
#' @description Reports the grid, the coverage of each depth level and the
#'   distribution of the values, which together say whether the field is ready
#'   for a browser payload.
#' @param object A `vol_field`.
#' @param ... Ignored.
#' @return An object of class `summary.vol_field`: a list with `grid`, a data
#'   frame `levels` of one row per depth with its coverage and quantiles, and
#'   `quantiles` over the whole field.
#' @details Coverage is the fraction of cells that are not `NA`, level by level.
#'   A marine field loses cells with depth as the bathymetry rises to meet it,
#'   and the profile of coverage against depth is the quickest check that the
#'   depth axis has been read in the right direction: coverage must not increase
#'   downward.
#' @examples
#' data(med_mhw)
#' s <- summary(med_mhw)
#' s
#' head(s$levels)
#' @seealso [vol_field()] for the constructor, [print.vol_field()] and
#'   [plot.vol_field()] for the other methods, [vol_encode()] for the transfer
#'   whose error depends on this distribution.
#' @export
summary.vol_field <- function(object, ...) {
    d <- dim(object$values)
    lv <- lapply(seq_len(d[1]), function(k) {
        v <- object$values[k, , ]
        ok <- !is.na(v)
        q <- if (any(ok)) stats::quantile(v[ok], c(0.5, 0.99), names = FALSE)
             else c(NA_real_, NA_real_)
        data.frame(depth = object$depth[k], coverage = mean(ok),
                   median = q[1], q99 = q[2])
    })
    ok <- !is.na(object$values)
    structure(list(
        name = object$name, unit = object$unit,
        grid = c(nx = d[3], ny = d[2], nz = d[1]),
        lon = range(object$lon), lat = range(object$lat), depth = range(object$depth),
        uniform_depth = is_uniform(object$depth),
        coverage = mean(ok),
        quantiles = if (any(ok)) stats::quantile(object$values[ok],
                                                 c(0, 0.5, 0.9, 0.99, 1)) else NULL,
        levels = do.call(rbind, lv),
        axes = axis_names(object),
        depth_unit = if (identical(object$geographic, FALSE)) "" else " m",
        source = object$source),
        class = "summary.vol_field")
}

#' @noRd
#' @export
print.summary.vol_field <- function(x, ...) {
    cat(get_colored_symbol("info"), " Gridded field: ", x$name,
        if (nzchar(x$unit)) paste0(" (", x$unit, ")") else "", "\n", sep = "")
    cat(sprintf("Grid = %d x %d x %d, %.1f %% of cells present\n",
                x$grid[["nx"]], x$grid[["ny"]], x$grid[["nz"]], 100 * x$coverage))
    cat(sprintf("%s = %g to %g%s, %s\n", x$axes[3], x$depth[1], x$depth[2],
                x$depth_unit,
                if (x$uniform_depth) "uniformly spaced" else "unevenly spaced"))
    if (!is.null(x$quantiles)) {
        cat("Quantiles of the values:\n")
        print(signif(x$quantiles, 4))
    }
    cat(sprintf("Coverage is %.1f %% at %g%s and %.1f %% at %g%s\n",
                100 * x$levels$coverage[1], x$levels$depth[1], x$depth_unit,
                100 * x$levels$coverage[nrow(x$levels)],
                x$levels$depth[nrow(x$levels)], x$depth_unit))
    print_source(x$source)
    invisible(x)
}

#' Plot a gridded field
#'
#' @title Plot a gridded field
#' @description Three views of the field outside the browser: a map of one depth
#'   level, the vertical profile of its horizontal statistics, and the coverage
#'   of the grid against depth.
#' @param x A `vol_field`.
#' @param type One of `"level"`, `"profile"` or `"coverage"`.
#' @param depth Depth in metres for `type = "level"`; the nearest level is
#'   drawn. Defaults to the shallowest.
#' @param cmap Name of a colour table, from [vol_colormaps()].
#' @param limits Numeric pair, the ends of the colour scale. Defaults to the
#'   1st and 99th percentiles of the level.
#' @param ... Ignored.
#' @return A `ggplot` object, returned invisibly.
#' @details The map is drawn as an equirectangular projection at the standard
#'   parallel of the domain's own middle, so a degree of longitude is shorter
#'   than a degree of latitude by the cosine of that latitude and the shapes are
#'   the ones an atlas draws. Plain plate carree, which sets the two degrees
#'   equal, stretches the Mediterranean vertically by a factor of 1.27 and a
#'   polar domain by far more. The browser view uses the same convention when it
#'   looks straight down, so the two are directly comparable. The profile shows
#'   the median and the interquartile range of the finite cells at each level,
#'   which for a marine field is taken over a shrinking sample as the bathymetry
#'   rises; the coverage panel is what says by how much.
#' @examples
#' data(med_mhw)
#' plot(med_mhw)
#' plot(med_mhw, depth = 50, cmap = "thermal")
#' plot(med_mhw, type = "profile")
#' plot(med_mhw, type = "coverage")
#' @seealso [vol_field()] for the constructor, [print.vol_field()] for the
#'   one-screen report, [summary.vol_field()] for the numbers behind the profile
#'   panel, [vol_colormaps()] for the colour tables,
#'   [vol_widget()] for the same field in the browser.
#' @export
plot.vol_field <- function(x, type = c("level", "profile", "coverage"),
                           depth = NULL, cmap = "matter", limits = NULL, ...) {
    type <- match.arg(type)
    ax <- axis_names(x)
    lab <- if (nzchar(x$unit)) paste0(x$name, " (", x$unit, ")") else x$name
    if (type == "level") {
        k <- if (is.null(depth)) 1L else which.min(abs(x$depth - depth))
        v <- x$values[k, , ]
        if (is.null(limits)) {
            ok <- !is.na(v)
            limits <- if (any(ok)) stats::quantile(v[ok], c(0.01, 0.99), names = FALSE)
                      else c(0, 1)
        }
        even <- even_enough(x$lon) && even_enough(x$lat)
        lonv <- if (even) regularise(x$lon) else x$lon
        latv <- if (even) regularise(x$lat) else x$lat
        df <- data.frame(lon = rep(lonv, each = length(latv)),
                         lat = rep(latv, times = length(lonv)),
                         value = as.numeric(v))
        p <- ggplot2::ggplot(df, ggplot2::aes(x = lon, y = lat,
                                              fill = value)) +
            (if (even) ggplot2::geom_raster(na.rm = TRUE)
             else ggplot2::geom_tile(na.rm = TRUE)) +
            ggplot2::scale_fill_gradientn(colours = colormap_colours(cmap),
                                          limits = limits, oob = squish_oob,
                                          na.value = "transparent", name = lab) +
            ggplot2::coord_fixed(ratio = map_ratio(x), expand = FALSE) +
            volumr_theme() +
            ggplot2::labs(
                title = paste0(x$name, " at ", fmt_m(x$depth[k]),
                               if (isTRUE(x$geographic) || is.null(x$geographic))
                                   " m" else ""),
                subtitle = sprintf("Level %d of %d, colour scale %.4g to %.4g",
                                   k, length(x$depth), limits[1], limits[2]),
                x = ax[1], y = ax[2],
                caption = plot_caption(sprintf(
                    "%s Cells outside the domain are left blank, and the colour scale is clipped at both ends, so a cell past a limit is drawn in the limit colour. Drawn by plot.vol_field().",
                    if (identical(x$geographic, FALSE)) "Axes in their own units, drawn square."
                    else sprintf("Equirectangular at the standard parallel %.1f degrees, so one degree of longitude is %.3f of one degree of latitude.",
                                 mean(range(x$lat)), cos(mean(range(x$lat)) * pi / 180)))))
        return(invisible(print(p)))
    }
    if (type == "profile") {
        st <- t(vapply(seq_along(x$depth), function(k) {
            v <- x$values[k, , ]; v <- v[!is.na(v)]
            if (!length(v)) return(c(NA_real_, NA_real_, NA_real_))
            stats::quantile(v, c(0.25, 0.5, 0.75), names = FALSE)
        }, numeric(3)))
        df <- data.frame(depth = x$depth, lo = st[, 1], mid = st[, 2], hi = st[, 3])
        p <- ggplot2::ggplot(df, ggplot2::aes(y = depth)) +
            ggplot2::geom_ribbon(ggplot2::aes(xmin = lo, xmax = hi),
                                 fill = "grey80", na.rm = TRUE) +
            ggplot2::geom_path(ggplot2::aes(x = mid), linewidth = 0.7,
                               na.rm = TRUE) +
            ggplot2::scale_y_reverse() +
            ggplot2::labs(title = paste0(x$name, " against ", tolower(ax[3])),
                subtitle = "Median over the finite cells of each level, with the interquartile range",
                x = lab, y = depth_label(x),
                caption = plot_caption("The sample shrinks with depth wherever the bathymetry rises to meet the level, so the statistics of two levels are not taken over the same cells. Drawn by plot.vol_field(type = \"profile\")."))
        return(invisible(print(p + volumr_theme())))
    }
    cov <- vapply(seq_along(x$depth), function(k) mean(!is.na(x$values[k, , ])), 0)
    df <- data.frame(depth = x$depth, coverage = 100 * cov)
    p <- ggplot2::ggplot(df, ggplot2::aes(x = coverage, y = depth)) +
        ggplot2::geom_path(linewidth = 0.7) +
        ggplot2::geom_point(size = 1.6) +
        ggplot2::scale_y_reverse() +
        ggplot2::labs(title = paste0("Coverage of the grid against ", tolower(ax[3])),
            subtitle = sprintf("Percentage of the %d cells of a level that carry a value",
                               length(x$lat) * length(x$lon)),
            x = "Cells present (%)", y = depth_label(x),
            caption = plot_caption("Coverage cannot increase downward for a marine field. A profile that rises with depth says the depth axis was read upside down. Drawn by plot.vol_field(type = \"coverage\")."))
    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.