tests/testthat/test-netcdf.R

write_nc <- function(dims, values, var = "v") {
    path <- tempfile(fileext = ".nc")
    vv <- ncdf4::ncvar_def(var, "u", dims, -999)
    nc <- ncdf4::nc_create(path, vv)
    ncdf4::ncvar_put(nc, vv, values)
    ncdf4::nc_close(nc)
    path
}

test_that("the axes are read in any storage order", {
    # Regression: with the further axis last and depth stored first, the values
    # were reshaped without being permuted.
    skip_if_not_installed("ncdf4")
    xs <- c(10, 11, 12, 13); ys <- c(40, 41, 42); zs <- c(0, 10)
    arr <- array(seq_len(24), c(2L, 3L, 4L))            # depth, lat, lon
    dz <- ncdf4::ncdim_def("depth", "m", zs)
    dy <- ncdf4::ncdim_def("lat", "degrees_north", ys)
    dx <- ncdf4::ncdim_def("lon", "degrees_east", xs)
    dt <- ncdf4::ncdim_def("time", "days", 1:2)
    a <- write_nc(list(dz, dy, dx, dt), array(c(arr, arr + 100), c(2, 3, 4, 2)))
    f <- vol_read_netcdf(a, time = 1)
    expect_identical(dim(f$values), c(2L, 3L, 4L))
    expect_equal(f$values, arr, ignore_attr = TRUE)
    b <- write_nc(list(dx, dt, dy, dz),
                  aperm(array(c(arr, arr + 100), c(2, 3, 4, 2)), c(3, 4, 2, 1)))
    g <- vol_read_netcdf(b, time = 2)
    expect_equal(g$values, arr + 100, ignore_attr = TRUE)
    expect_equal(g$lon, xs); expect_equal(g$lat, ys); expect_equal(g$depth, zs)
})

test_that("decreasing axes and an upward vertical axis are turned round", {
    skip_if_not_installed("ncdf4")
    arr <- array(seq_len(24), c(2L, 3L, 4L))            # depth, lat, lon
    dx <- ncdf4::ncdim_def("lon", "degrees_east", c(13, 12, 11, 10))
    dy <- ncdf4::ncdim_def("lat", "degrees_north", c(40, 41, 42))
    dz <- ncdf4::ncdim_def("depth", "m", c(0, 10))
    p <- write_nc(list(dx, dy, dz), aperm(arr, 3:1)[4:1, , ])
    f <- vol_read_netcdf(p)
    expect_equal(f$lon, c(10, 11, 12, 13))
    expect_equal(f$values, arr, ignore_attr = TRUE)
})

test_that("a variable with two further axes and a wrong name are refused", {
    skip_if_not_installed("ncdf4")
    d <- list(ncdf4::ncdim_def("lon", "deg", 1:2), ncdf4::ncdim_def("lat", "deg", 1:2),
              ncdf4::ncdim_def("depth", "m", 1:2), ncdf4::ncdim_def("time", "d", 1:2),
              ncdf4::ncdim_def("member", "", 1:2))
    p <- write_nc(d, array(1, rep(2, 5)))
    expect_error(vol_read_netcdf(p), "2 axes besides")
    q <- write_nc(d[1:4], array(1, rep(2, 4)))
    expect_error(vol_read_netcdf(q, depth = "level"), "no dimension named level")
    expect_error(vol_read_netcdf(q, time = 3), "between 1 and 2")
})

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.