R/utils.R

Defines functions map_ratio depth_label regularise even_enough axis_names `%||%` print_source squish_oob fmt_m volumr_theme plot_caption is_uniform require_packages require_package get_colored_symbol

# ============================ #
# Console helpers              #
# ============================ #

#' @noRd
get_colored_symbol <- function(type = c("success", "info", "warning", "error",
                                        "settings", "time", "block"),
                               color = TRUE) {
    type <- match.arg(type)
    sym <- c(success = "\u2714", info = "\u2139", warning = "\u26A0", error = "\u2718",
             settings = "\u2699", time = "\u23F1", block = "\u26D4")
    col <- c(success = "\033[32m", info = "\033[36m", warning = "\033[33m",
             error = "\033[31m", settings = "\033[35m", time = "\033[34m",
             block = "\033[31m")
    if (color && interactive()) paste0(col[type], sym[type], "\033[0m") else sym[type]
}

# A suggested package is checked for and never installed or attached: the
# caller reaches it through `pkg::`, and a missing one stops with the reason.
#' @noRd
require_package <- function(pkg, load = FALSE) {
    if (!requireNamespace(pkg, quietly = TRUE))
        stop(get_colored_symbol("block"), " Package '", pkg, "' is needed here; ",
             "install it with install.packages(\"", pkg, "\")", call. = FALSE)
    invisible(TRUE)
}

#' @noRd
require_packages <- function(pkgs, load = FALSE) invisible(vapply(pkgs, require_package, TRUE))

# ============================ #
# Small shared helpers         #
# ============================ #

#' @noRd
is_uniform <- function(x, tol = 1e-9) {
    length(x) < 3L || diff(range(diff(x))) < tol
}

# A caption must not run off the panel, so every caption this package builds is
# wrapped at a fixed width inside the helper and not at the call site.
#' @noRd
plot_caption <- function(txt, width = 90L) {
    paste(strwrap(txt, width = width), collapse = "\n")
}

#' @noRd
volumr_theme <- function() {
    ggplot2::theme_minimal(base_size = 11) +
        ggplot2::theme(
            plot.caption = ggplot2::element_text(color = "grey40", size = 8, hjust = 0),
            plot.subtitle = ggplot2::element_text(color = "grey30", size = 9),
            panel.grid.minor = ggplot2::element_blank())
}

#' @noRd
fmt_m <- function(v) {
    ifelse(abs(v - round(v)) < 0.05, sprintf("%.0f", v), sprintf("%.1f", v))
}

# ggplot2 takes the out-of-bounds handler from scales; this is the same rule
# without the dependency: a value past a limit is drawn at the limit.
#' @noRd
squish_oob <- function(x, range = c(0, 1), only.finite = TRUE) {
    pmin(pmax(x, range[1]), range[2])
}

# Code 0 marks a missing cell, so the transfer has 254 codes, 1 to 254.
#' @noRd
VOL_CODES <- 254L

# The provenance of a field may carry a digest per input array, which is worth
# recording and is not worth printing. Only the fields a reader can act on are
# shown, with the digests counted.
#' @noRd
print_source <- function(src) {
    if (is.null(src) || !length(src)) return(invisible(NULL))
    labels <- c(name = "Name", product = "Product", doi = "DOI",
                reference_period = "Reference period", file = "File",
                variable = "Variable", step = "Decimation")
    for (k in names(labels))
        if (!is.null(src[[k]]))
            cat(sprintf("%-19s %s\n", paste0(labels[[k]], " ="), src[[k]]))
    if (!is.null(src$sha256))
        cat(sprintf("%-17s %d input arrays\n", "Digests =", length(src$sha256)))
    invisible(NULL)
}

#' @noRd
`%||%` <- function(a, b) if (is.null(a)) b else a

# The three axes are longitude, latitude and depth for a geographic field and
# X, Y and Z for any other, which decides every label the package writes.
#' @noRd
axis_names <- function(field) {
    if (isTRUE(field$geographic) || is.null(field$geographic))
        c("Longitude", "Latitude", "Depth") else c("X", "Y", "Z")
}

# geom_raster() needs a grid whose spacing is even, and a coordinate vector that
# arrived in single precision is even only to about one part in a hundred
# thousand. Where the spacing is even to the tolerance below, the vector is
# rebuilt as an exact sequence, which moves a cell by a small fraction of its
# own width; where it is genuinely uneven, the caller draws tiles instead.
#' @noRd
even_enough <- function(v, tol = 1e-3) {
    if (length(v) < 3L) return(TRUE)
    d <- diff(v)
    diff(range(d)) <= tol * mean(abs(d))
}

#' @noRd
regularise <- function(v) {
    if (length(v) < 2L) v else seq(v[1], v[length(v)], length.out = length(v))
}

#' @noRd
depth_label <- function(field) {
    if (isTRUE(field$geographic) || is.null(field$geographic)) "Depth (m)" else "Z"
}

# The aspect a map wants: one degree of longitude is cos(latitude) as long as one
# degree of latitude, so the y axis is stretched by the reciprocal. A field whose
# axes are not geographic is drawn square.
#' @noRd
map_ratio <- function(field) {
    if (identical(field$geographic, FALSE)) return(1)
    phi <- mean(range(field$lat)) * pi / 180
    1 / max(cos(phi), 1e-6)
}

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.