R/netcdf.R

Defines functions vol_read_netcdf

Documented in vol_read_netcdf

# ============================ #
# NetCDF files                 #
# ============================ #

#' Read a field from a NetCDF file
#'
#' @title Read a field from a NetCDF file
#' @description Reads one variable of a NetCDF file into a [vol_field()],
#'   guessing the longitude, latitude and depth axes from their names when they
#'   are not given.
#' @param path Path to a NetCDF file.
#' @param varid Name of the variable to read. Defaults to the first variable
#'   that carries three dimensions.
#' @param lon,lat,depth Names of the coordinate variables. Each defaults to the
#'   first dimension name that matches the usual spellings.
#' @param time Index along the time axis, when the variable carries one.
#' @return A `vol_field`.
#' @details The reader is deliberately narrow. It takes a variable on a regular
#'   longitude, latitude and depth grid, with at most one further axis, which it
#'   subsets at `time`; a variable with two or more further axes is refused. The
#'   axes may be stored in any order. The reader puts them into the depth,
#'   latitude, longitude order that [vol_field()] fixes, reverses any axis that
#'   is stored decreasing, and turns the fill value into `NA`.
#'
#'   A file whose vertical axis is positive upward, which the `positive`
#'   attribute states, has its depths negated and its levels reversed, so the
#'   field that comes back is positive downward as the rest of the package
#'   expects.
#'
#'   This function needs \pkg{ncdf4}, which is a suggested package.
#' @references Rew, R., & Davis, G. (1990). NetCDF: an interface for scientific
#'   data access. *IEEE Computer Graphics and Applications*, 10(4), 76-82.
#'   \doi{10.1109/38.56302}
#' @examples
#' if (requireNamespace("ncdf4", quietly = TRUE)) {
#'   path <- tempfile(fileext = ".nc")
#'   dims <- list(ncdf4::ncdim_def("lon", "degrees_east", seq(10, 12, by = 0.5)),
#'                ncdf4::ncdim_def("lat", "degrees_north", c(40, 40.5, 41)),
#'                ncdf4::ncdim_def("depth", "m", c(0, 10, 20, 30)),
#'                ncdf4::ncdim_def("time", "days", 1:2))
#'   var <- ncdf4::ncvar_def("thetao", "degC", dims, -999)
#'   nc <- ncdf4::nc_create(path, var)
#'   ncdf4::ncvar_put(nc, var, array(seq_len(5 * 3 * 4 * 2), c(5, 3, 4, 2)))
#'   ncdf4::nc_close(nc)
#'   f <- vol_read_netcdf(path, varid = "thetao", time = 2)
#'   f
#'   summary(f)
#' }
#' @seealso [vol_read_npy()] for the other format, [vol_field()] for the object
#'   this returns, [vol_resample()] and [vol_payload()] for the steps that
#'   follow.
#' @export
vol_read_netcdf <- function(path, varid = NULL, lon = NULL, lat = NULL,
                            depth = NULL, time = 1L) {
    require_package("ncdf4")
    nc <- ncdf4::nc_open(path)
    on.exit(ncdf4::nc_close(nc))
    if (is.null(varid)) {
        cand <- names(nc$var)[vapply(nc$var, function(v) length(v$dim) >= 3L, TRUE)]
        if (!length(cand)) stop("no variable in ", path, " carries three dimensions",
                                call. = FALSE)
        varid <- cand[1]
    }
    v <- nc$var[[varid]]
    if (is.null(v)) stop("no variable named ", varid, " in ", path, call. = FALSE)
    dnames <- vapply(v$dim, function(d) d$name, "")
    pick <- function(given, patterns) {
        if (!is.null(given)) {
            i <- match(given, dnames)
            if (is.na(i)) stop("no dimension named ", given, " among ",
                               paste(dnames, collapse = ", "), call. = FALSE)
            return(i)
        }
        i <- which(grepl(patterns, dnames, ignore.case = TRUE))
        if (!length(i)) stop("cannot find an axis matching ", patterns,
                             " among ", paste(dnames, collapse = ", "), call. = FALSE)
        i[1]
    }
    ix <- pick(lon, "^(lon|longitude|x)$")
    iy <- pick(lat, "^(lat|latitude|y)$")
    iz <- pick(depth, "^(depth|dep|lev|level|z|elevation)$")
    xs <- v$dim[[ix]]$vals; ys <- v$dim[[iy]]$vals; zs <- v$dim[[iz]]$vals
    a <- ncdf4::ncvar_get(nc, varid, collapse_degen = FALSE)
    extra <- setdiff(seq_along(dim(a)), c(ix, iy, iz))
    if (length(extra) > 1L)
        stop("variable ", varid, " carries ", length(extra), " axes besides ",
             "longitude, latitude and depth (", paste(dnames[extra], collapse = ", "),
             "); subset it to one further axis before reading", call. = FALSE)
    if (length(extra) == 1L) {
        if (time < 1L || time > dim(a)[extra])
            stop("`time` must lie between 1 and ", dim(a)[extra], call. = FALSE)
        idx <- lapply(dim(a), seq_len)
        idx[[extra]] <- time
        a <- do.call(`[`, c(list(a), idx, list(drop = FALSE)))
        # Dropping the further axis keeps the storage order of the other three,
        # so their positions shift down past it.
        keep <- setdiff(seq_along(dim(a)), extra)
        a <- array(a, dim(a)[keep])
        ix <- match(ix, keep); iy <- match(iy, keep); iz <- match(iz, keep)
    }
    a <- aperm(a, c(iz, iy, ix))
    up <- tryCatch(ncdf4::ncatt_get(nc, v$dim[[iz]]$name, "positive")$value,
                   error = function(e) "")
    if (identical(tolower(up), "up")) { zs <- -zs }
    if (length(zs) > 1L && zs[1] > zs[length(zs)]) {
        zs <- rev(zs); a <- a[rev(seq_along(zs)), , , drop = FALSE]
    }
    if (length(ys) > 1L && ys[1] > ys[length(ys)]) {
        ys <- rev(ys); a <- a[, rev(seq_along(ys)), , drop = FALSE]
    }
    if (length(xs) > 1L && xs[1] > xs[length(xs)]) {
        xs <- rev(xs); a <- a[, , rev(seq_along(xs)), drop = FALSE]
    }
    unit <- tryCatch(v$units, error = function(e) "")
    vol_field(a, lon = xs, lat = ys, depth = zs, name = varid,
              unit = if (is.null(unit)) "" else unit,
              source = list(file = basename(path), variable = varid))
}

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.