R/npy.R

Defines functions npy_write_logical vol_read_npy

Documented in vol_read_npy

# ============================ #
# NumPy array files            #
# ============================ #

#' Read a NumPy array file
#'
#' @title Read a NumPy array file
#' @description Reads a `.npy` file into an R array, without calling Python.
#'   The format is a short ASCII header followed by the raw buffer, so no
#'   package is needed to parse it.
#' @param path Path to a `.npy` file.
#' @return An array of the shape the header states, of type double for a
#'   floating-point file, integer for an integer file and logical for a boolean
#'   file. A one-dimensional file returns a bare vector.
#' @details The reader covers the little-endian and big-endian floating-point
#'   types `f4` and `f8`, the signed integer types `i1`, `i2`, `i4` and `i8`,
#'   the unsigned integer types `u1`, `u2` and `u4`, and the boolean type `b1`.
#'   An unsigned `u4` file returns doubles, since its values may pass the
#'   largest R integer; any other type is refused.
#'   C order is the default that NumPy writes and is transposed on the way in,
#'   so `dim()` of the result matches the `shape` field of the header. A
#'   Fortran-ordered file is refused rather than read wrongly.
#'
#'   Values are carried across exactly. A `f4` file widens to double with no
#'   loss, since every single-precision number is a double-precision number.
#' @references van der Walt, S., Colbert, S. C., & Varoquaux, G. (2011). The
#'   NumPy array: a structure for efficient numerical computation. *Computing in
#'   Science & Engineering*, 13(2), 22-30. \doi{10.1109/MCSE.2011.37}
#' @examples
#' a <- vol_read_npy(system.file("extdata", "example.npy", package = "volumr"))
#' dim(a)
#' a
#' @seealso [vol_field()] to wrap arrays as a field, [vol_read_netcdf()] for the
#'   other format the reader accepts, [vol_payload()] to build the browser
#'   payload from a field.
#' @export
vol_read_npy <- function(path) {
    con <- file(path, "rb")
    on.exit(close(con))
    magic <- readBin(con, "raw", 6L)
    if (!identical(magic, c(as.raw(0x93), charToRaw("NUMPY"))))
        stop("not a .npy file: ", path, call. = FALSE)
    ver <- readBin(con, "integer", 2L, size = 1L, signed = FALSE)
    hlen <- if (ver[1] == 1L) readBin(con, "integer", 1L, size = 2L, endian = "little")
            else             readBin(con, "integer", 1L, size = 4L, endian = "little")
    hdr <- rawToChar(readBin(con, "raw", hlen))
    descr <- sub(".*'descr': *'([^']+)'.*", "\\1", hdr)
    if (grepl("'fortran_order': *True", hdr))
        stop("Fortran-ordered .npy files are not read here: ", path, call. = FALSE)
    dims <- as.integer(strsplit(gsub("[() ]", "",
        sub(".*'shape': *\\(([^)]*)\\).*", "\\1", hdr)), ",")[[1]])
    n <- prod(dims)
    kind <- substring(descr, 2L, 2L)
    size <- suppressWarnings(as.integer(substring(descr, 3L)))
    ok <- switch(kind, b = identical(size, 1L), f = size %in% c(4L, 8L),
                 i = size %in% c(1L, 2L, 4L, 8L), u = size %in% c(1L, 2L, 4L),
                 FALSE)
    if (!isTRUE(ok))
        stop("the .npy type '", descr, "' is not read here: ", path, call. = FALSE)
    endian <- if (substring(descr, 1L, 1L) == ">") "big" else "little"
    x <- switch(kind,
        b = as.logical(readBin(con, "raw", n)),
        f = readBin(con, "double", n, size = size, endian = endian),
        i = readBin(con, "integer", n, size = size, endian = endian),
        u = if (size < 4L) readBin(con, "integer", n, size = size, signed = FALSE,
                                   endian = endian)
            else {
                # Bytes are combined by hand, since the bit pattern 0x80000000
                # is the integer NA of R and would not survive readBin().
                b <- matrix(as.numeric(readBin(con, "raw", 4L * n)), 4L)
                w <- if (endian == "little") 256^(0:3) else 256^(3:0)
                as.numeric(colSums(b * w))
            })
    if (length(dims) == 1L) x else aperm(array(x, rev(dims)), length(dims):1)
}

# Only the logical case is written, because a mask is the one array this package
# caches. The header is padded to a multiple of 64 bytes, as NumPy does.
#' @noRd
npy_write_logical <- function(x, path) {
    dims <- dim(x)
    shape <- if (length(dims) == 1L) paste0(dims, ",") else paste(dims, collapse = ", ")
    hdr <- sprintf("{'descr': '|b1', 'fortran_order': False, 'shape': (%s), }", shape)
    pad <- 64L - ((10L + nchar(hdr) + 1L) %% 64L)
    hdr <- paste0(hdr, strrep(" ", pad), "\n")
    con <- file(path, "wb")
    on.exit(close(con))
    writeBin(c(as.raw(0x93), charToRaw("NUMPY"), as.raw(1L), as.raw(0L)), con)
    writeBin(as.integer(nchar(hdr)), con, size = 2L, endian = "little")
    writeBin(charToRaw(hdr), con)
    writeBin(as.raw(as.integer(aperm(x, length(dims):1))), con)
    invisible(path)
}

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.