R/resample.R

Defines functions gcd_real default_dz vol_resample

Documented in vol_resample

# ============================ #
# The depth axis               #
# ============================ #

#' Resample a field onto a uniform depth grid
#'
#' @title Resample a field onto a uniform depth grid
#' @description Interpolates the field linearly onto depths spaced evenly from
#'   the shallowest measured depth, which is what the browser payload needs,
#'   because the GPU samples a three-dimensional texture on a regular grid.
#' @param field A `vol_field`.
#' @param dz Spacing of the target grid, in metres. Defaults to the largest
#'   spacing that reproduces every measured depth exactly, when one exists, and
#'   otherwise to the smallest spacing of the input.
#' @param zmax Deepest level of the target grid, no shallower than the first
#'   measured depth. Defaults to the deepest level of the input.
#' @param check Logical. When `TRUE`, stop if a measured depth is absent from
#'   the target grid, so that no measured level is silently smoothed away.
#' @return A `vol_field` on the uniform grid, with the other elements carried
#'   over unchanged.
#' @details The interpolation is
#'   \deqn{v(z) = \frac{v_{hi} - v_{lo}}{z_{hi} - z_{lo}}\,(z - z_{lo}) + v_{lo},}
#'   with \eqn{z_{lo}} and \eqn{z_{hi}} the measured depths that bracket
#'   \eqn{z}, so an interpolated level holds no value where either of the two
#'   measured levels around it holds none. A target depth that coincides with a
#'   measured depth, to within \eqn{10^{-9}}, takes that measured level
#'   unchanged, so a cell keeps its value at a measured depth whatever its
#'   neighbours hold; at the first level this keeps the cells of a column that
#'   ends above the second measured depth.
#'
#'   The default `dz` is chosen so that measured levels survive. For the case
#'   study the fifteen measured depths are 0, 12.5, 25, 37.5, 50, 62.5, 75,
#'   87.5, 100, 125, 150, 175, 200 and 225 and 250 m, every one of them a
#'   multiple of 12.5 m, so a grid of 12.5 m reproduces all fifteen exactly and
#'   interpolates only the six levels that lie between 100 and 250 m.
#'
#'   The target grid starts at the shallowest measured depth, so the
#'   interpolation never reaches outside the measured column. Resampling a
#'   field that is already uniform at the requested spacing is a copy, not a
#'   smoothing pass, and a field with a single level is returned unchanged.
#' @examples
#' data(med_mhw)
#' med_mhw$depth
#' u <- vol_resample(med_mhw)
#' u$depth
#' summary(u)$grid
#' @seealso [vol_field()] for the object, [vol_encode()] for the step that
#'   follows, [vol_payload()], which calls this when the depth axis is not
#'   already uniform, [plot.vol_field()] to see the profile before and after.
#' @export
vol_resample <- function(field, dz = NULL, zmax = NULL, check = TRUE) {
    stopifnot(inherits(field, "vol_field"))
    zin <- field$depth
    if (length(zin) < 2L) return(field)
    if (is.null(zmax)) zmax <- zin[length(zin)]
    if (is.null(dz)) dz <- default_dz(zin)
    if (!is.numeric(dz) || length(dz) != 1L || !is.finite(dz) || dz <= 0)
        stop("`dz` must be one positive number", call. = FALSE)
    if (!is.numeric(zmax) || length(zmax) != 1L || !is.finite(zmax) || zmax < zin[1])
        stop("`zmax` must be one number no shallower than the first measured ",
             "depth, ", zin[1], call. = FALSE)
    z <- seq(zin[1], zmax, by = dz)
    if (check) {
        missing <- zin[!vapply(zin, function(d) any(abs(z - d) < 1e-9), TRUE) &
                       zin <= zmax]
        if (length(missing))
            stop("these measured depths are absent from a grid of ", dz, " m: ",
                 paste(missing, collapse = ", "),
                 ". Choose another `dz`, or pass check = FALSE.", call. = FALSE)
    }
    d <- dim(field$values)
    out <- array(NA_real_, c(length(z), d[2], d[3]))
    for (k in seq_along(z)) {
        # A measured level is copied, not recomputed from an interval, because the
        # interval formula is NA wherever the other end of the interval is NA.
        # The tolerance 1e-9 m matches the one of the check above.
        j <- which(abs(zin - z[k]) < 1e-9)
        if (length(j)) {
            out[k, , ] <- field$values[j[1L], , ]
            next
        }
        hi <- min(max(findInterval(z[k], zin, left.open = TRUE) + 1L, 2L), length(zin))
        lo <- hi - 1L
        slope <- (field$values[hi, , ] - field$values[lo, , ]) / (zin[hi] - zin[lo])
        out[k, , ] <- slope * (z[k] - zin[lo]) + field$values[lo, , ]
    }
    field$values <- out
    field$depth <- z
    field
}

# The coarsest spacing that reproduces every measured depth on a grid starting
# at the first of them, when the spacings are commensurable, and otherwise the
# finest spacing present.
#' @noRd
default_dz <- function(z) {
    if (length(z) < 2L) return(1)
    d <- diff(z)
    g <- d[1]
    for (v in d) g <- gcd_real(g, v)
    r <- (z - z[1]) / g
    if (g > 0 && all(abs(r - round(r)) < 1e-6)) g else min(d)
}

#' @noRd
gcd_real <- function(a, b, tol = 1e-9) {
    a <- abs(a); b <- abs(b)
    while (b > tol) { t <- b; b <- a - floor(a / b + tol) * b; a <- t }
    a
}

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.