tests/testthat/test-from_df.R

grid_df <- function() {
    d <- expand.grid(lon = 1:6, lat = 1:5, depth = seq(0, 30, by = 10))
    d$value <- with(d, sin(lon) * cos(lat) + depth / 10 + 5)
    d
}

test_that("a long frame becomes a field with the right shape", {
    f <- suppressMessages(vol_field_from_df(grid_df()))
    expect_s3_class(f, "vol_field")
    expect_identical(dim(f$values), c(4L, 5L, 6L))
    expect_equal(f$lon, 1:6)
    expect_equal(f$depth, c(0, 10, 20, 30))
    expect_true(f$geographic)
})

test_that("the values land in the right cells", {
    d <- grid_df()
    f <- suppressMessages(vol_field_from_df(d))
    for (i in c(1L, 7L, 60L)) {
        r <- d[i, ]
        k <- match(r$depth, f$depth); j <- match(r$lat, f$lat); n <- match(r$lon, f$lon)
        expect_equal(f$values[k, j, n], r$value)
    }
})

test_that("x, y and z naming is recognised and is not geographic", {
    d <- stats::setNames(grid_df(), c("x", "y", "z", "v"))
    f <- suppressMessages(vol_field_from_df(d))
    expect_false(f$geographic)
    expect_identical(f$name, "v")
})

test_that("an incomplete frame leaves NA and not a shifted grid", {
    d <- grid_df()
    d <- d[!(d$lon == 3 & d$lat == 2), ]
    f <- suppressMessages(vol_field_from_df(d))
    expect_identical(dim(f$values), c(4L, 5L, 6L))
    expect_true(all(is.na(f$values[, 2, 3])))
    expect_false(anyNA(f$values[, 1, 1]))
})

test_that("a repeated cell is an error and not a silent choice", {
    d <- grid_df()
    expect_error(suppressMessages(vol_field_from_df(rbind(d, d[1, ]))),
                 "same cell|more rows than")
})

test_that("a time column picks one volume", {
    d <- grid_df()
    both <- rbind(cbind(d, time = 1), cbind(d, time = 2))
    both$value[both$time == 2] <- 99
    f <- suppressMessages(vol_field_from_df(both, at = 2))
    expect_true(all(f$values == 99))
    expect_error(suppressMessages(vol_field_from_df(both, at = 7)), "not a value")
})

test_that("an upward axis is turned the right way up", {
    d <- expand.grid(x = 1:3, y = 1:3, elevation = c(0, 100, 200))
    d$v <- d$elevation
    f <- suppressMessages(vol_field_from_df(d))
    expect_equal(f$depth, c(-200, -100, 0))
    expect_equal(as.numeric(f$values[1, 1, 1]), 200)
})

test_that("a frame whose columns cannot be told apart is refused", {
    d <- data.frame(a = 1:3, b = 1:3, c = 1:3)
    expect_error(vol_field_from_df(d), "cannot find the three coordinate")
})

test_that("the automatic transfer follows the sign of the field", {
    pos <- vol_field(array(c(1, 2, 3, 4), c(4L, 1L, 1L)), 1, 1, 0:3)
    neg <- vol_field(array(c(-1, 2, 3, 4), c(4L, 1L, 1L)), 1, 1, 0:3)
    expect_identical(vol_encode(pos)$transfer$kind, "sqrt")
    expect_identical(vol_encode(neg)$transfer$kind, "linear")
})

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.