rspatial / terra

R package for spatial data handling https://rspatial.github.io/terra/reference/terra-package.html
GNU General Public License v3.0
534 stars 88 forks source link

Inconsistent behaviour of mask across resolutions #1463

Open spono opened 6 months ago

spono commented 6 months ago

Hi, dealing with an analysis over a wide area (few squared km), I need to mask some objects making use of the option inverse=TRUE. If I use a 1 metre resolution raster I get what I’m looking for but, in the case of a 0.5 m resolution (20033 x 33316 cells), the result is equal to the input layer. Just in case, I tried to check the CRS and the topology of the vector layer (provided as a SpatVector) but both are ok. Any other idea?

Here the layers and below the code for testing:

wdir = "C:/Users/???"

shp = vect(file.path(wdir,"raster_mask.shp"))

resol = c(0.5, 1)

for( i in resol ){

  r = rast( file.path(wdir,paste0("raster_",i,"m.tif")) )

  r = mask(r,shp, inverse=TRUE)

  writeRaster(r, filename=file.path(wdir,paste0("raster_",i,"m_masked.tif")),
            wopt=list(gdal=c("COMPRESS=LZW", "TFW=YES","of=GTiff")), overwrite=TRUE)

  rm(r)
}

I'm working with terra 1.7.71 and R 4.3.2 on W10.

rhijmans commented 4 months ago

I cannot reproduce this. Perhaps because of a difference in memory availability. But before I dig deeper, can you confirm that this problem persists for you? Specifically, I would expect xm to be incorrect:

library(terra)
shp = vect("raster_mask.shp")
x = rast("raster_0.5m.tif")
xm = mask(x, shp, inverse=TRUE)

Or at least different from

r = rast("raster_1m.tif")
rm = mask(r, shp, inverse=TRUE)

Can you confirm that?

spono commented 4 months ago

yep: the 1m resolution is ok and the 0.5 is not (tested on both 1.7.71 and 1.7.78). BTW, on my side, the available memory is 32 Gb, so it would seem pretty strange to me. anything else I can provide for helping?

comparison

spono commented 2 months ago

I had the chance to test it on another W10 machine using terra 1.7-3 on R 4.2.2 and it worked pretty fine. Nevertheless, updating to 1.7-71 that machine too showed the abovementioned bug. Any idea about what else I can test?