tests/testthat/test_sample_region_series.R

# set up data path for this test
data_path <- file.path(tempdir(), "pastclim_data")
unlink(data_path, recursive = TRUE) # it should not exist, but remove it just in case
# set data path
set_data_path(
  path_to_nc = data_path,
  ask = FALSE,
  write_config = FALSE,
  copy_example = TRUE
)
################################################################################

test_that("sample_region_series works correctly", {
  set.seed(123)
  # sample series
  t_steps <- c(-20000, -10000)
  vars <- c("bio01", "bio10", "bio12")
  climate_ts <- region_series(
    time_bp = t_steps,
    bio_variables = vars,
    dataset = "Example",
    ext = terra::ext(region_extent$Europe)
  )
  n_points <- c(10, 15)
  sampled_var <- sample_region_series(climate_ts, size = n_points)
  expect_true(nrow(sampled_var) == sum(n_points))
  # give wrong vector length
  n_points <- c(10, 15, 20)
  expect_error(
    sampled_var <- sample_region_series(climate_ts, size = n_points),
    "size should be the same length as the number of time steps in x"
  )
  # check that it works if we use small numbers and zero
  n_points <- c(1, 0)
  sampled_var <- sample_region_series(climate_ts, size = n_points)
  expect_true(nrow(sampled_var) == sum(n_points))
  # get error if sample sizes are all zero
  n_points <- c(0, 0)
  expect_error(
    sampled_var <- sample_region_series(climate_ts, size = n_points),
    "at least one element of sample size should be larger than zero"
  )
  # now use a single sample size for all layers
  n_points <- 10
  sampled_fixed <- sample_region_series(climate_ts, size = n_points)
  expect_true(nrow(sampled_fixed) == n_points * length(t_steps))
  expect_true(sum(is.na(sampled_fixed)) == 0)
  sampled_fixed <- sample_region_series(climate_ts,
    size = n_points,
    na.rm = FALSE
  )
  expect_true(sum(is.na(sampled_fixed)) > 0)
  climate_ts[1] <- climate_ts[1][[1]]
  expect_error(
    sample_region_series(climate_ts, size = n_points),
    "x is not a valid object generated by region_series"
  )
})

################################################################################
# clean up for the next test
unlink(data_path, recursive = TRUE)
EvolEcolGroup/pastclim documentation built on Nov. 6, 2023, 5:11 a.m.