daily pastebin goal
19%
SHARE
TWEET

Untitled

a guest Jan 23rd, 2019 52 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. context("Download NARR via THREDDS")
  2.  
  3. start_date <- "2012-02-20"
  4. end_date <- "2012-03-05"
  5. ntime <- as.numeric(difftime(end_date, start_date) + 1) * 24 / 3 + 1
  6. lat.in <- 43.3724
  7. lon.in <- -89.9071
  8.  
  9. outfolder <- tempfile()
  10. dir.create(outfolder)
  11.  
  12. # Create a fake NARR file the outfolder against which we will test
  13. testfile <- file.path(outfolder, "_dl_narr_test.nc")
  14. time_units <- "hours since 2012-02-20"
  15. time_vals <- seq_len(difftime(end_date, start_date, units = "hours") * 3) - 1
  16. timedim <- ncdf4::ncdim_def("time", units = time_units, vals = time_vals)
  17. reftimedim <- ncdf4::ncdim_def("reftime", units = time_units, vals = time_vals)
  18. flx_vars <- purrr::pmap(list(
  19.   name = narr_flx_vars[["NARR_name"]],
  20.   units = narr_flx_vars[["units"]]
  21. ), ncdf4::ncvar_def, dim = timedim)
  22. sfc_vars <- purrr::pmap(list(
  23.   name = narr_sfc_vars[["NARR_name"]],
  24.   units = narr_sfc_vars[["units"]]
  25. ), ncdf4::ncvar_def, dim = reftimedim)
  26. ncdf4::nc_create(testfile, c(flx_vars, sfc_vars))
  27. nc <- ncdf4::nc_open(testfile, write = TRUE)
  28. purrr::walk(
  29.   flx_vars,
  30.   ncdf4::ncvar_put,
  31.   nc = nc,
  32.   vals = rexp(length(time_vals))
  33. )
  34. purrr::walk(
  35.   sfc_vars,
  36.   ncdf4::ncvar_put,
  37.   nc = nc,
  38.   vals = rexp(length(time_vals))
  39. )
  40.  
  41. teardown({
  42.   ncdf4::nc_close(nc)
  43.   unlink(outfolder, recursive = TRUE, force = TRUE)
  44. })
  45.  
  46. test_that(
  47.   "NARR download works as expected",
  48.   {
  49.  
  50.     # Instead of reading the target NARR file, we read the testfile.
  51.     # This works because the NARR site code only uses nc_open to read
  52.     # the remote file, never to read anything downloaded.
  53.     r <- with_mock(
  54.       "ncdf4::nc_open" = function(filename) ncdf4::nc_open(testfile),
  55.       download.NARR_site(outfolder, start_date, end_date, lat.in, lon.in,
  56.                          progress = FALSE, parallel = FALSE)
  57.     )
  58.  
  59.  
  60.     expect_equal(nrow(r), 1)
  61.     expect_true(file.exists(r$file[1]))
  62.     nc <- ncdf4::nc_open(r$file)
  63.     temp <- ncdf4::ncvar_get(nc, "air_temperature")
  64.     precip <- ncdf4::ncvar_get(nc, "precipitation_flux")
  65.     expect_true(all(!is.na(temp)), all(temp > 0), length(temp) == ntime)
  66.     expect_true(all(!is.na(precip)), length(precip) == ntime)
  67.     ncdf4::nc_close(nc)
  68.   }
  69. )
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top