rspatial / raster

R raster package https://rspatial.github.io/raster/reference/raster-package.html
GNU General Public License v3.0
161 stars 52 forks source link

Avoid re-opening already opened CDF file. #319

Closed kalibera closed 1 year ago

kalibera commented 1 year ago

The call to brick() in .stopWriteCDF() may result in an attempt to open the CDF file already opened in .stopWriteCDF() before the call to brick(). This results in an error with hdf5 1.12.1 on Windows due to file locking, which on Windows is no longer a no-op from hdf5 1.12.1. This patch avoids this situation by closing the file, first.

The problem can be reproduced using magclass package. This example fails without this change:

  library(magclass)
  md <- magclass:::magclassdata$half_deg
  m05 <- new.magpie(paste0(md$region, ".", seq_len(dim(md)[1])),
                    years = c(2000, 2001), fill = c(md$lon, md$lat))
  m10 <- mbind(m05, m05)
  getNames(m10) <- c("bla", "blub")
  write.magpie(m10, "test.nc")

The example is extracted from magclass package tests, which also fail on Windows with Rtools 5863 (hdf5 1.12.1).

One can also reproduce directly using raster via

 load("rx.xdr")
 raster::writeRaster(rx, filename = "./test.nc",
        format = "CDF", overwrite = TRUE, compression = 9, zname = "Time",
        zunit = "years", varname = "bla", varunit = "not specified")

using the attached file (rx.zip, after unzipping).

For testing, one can also disable hdf5 file locking by setting environment variable HDF5_USE_FILE_LOCKING=FALSE. That makes the examples succeed even without the patch.

rhijmans commented 1 year ago

Awesome, thanks!