mapme-initiative / mapme.biodiversity

Efficient analysis of spatial biodiversity datasets for global portfolios
https://mapme-initiative.github.io/mapme.biodiversity/
GNU General Public License v3.0
24 stars 7 forks source link

Apply precision roundtrip to match raster files with slight differences in their spatial extent #217

Closed goergen95 closed 6 months ago

goergen95 commented 7 months ago

For some resources the raster files show slight differences in their spatial extent (usually beyond 5 decimal points). {terra} seems to be able to stack rasters if the cell numbers are identical and the difference in extent is not larger that 3.6° (see code snippet below). The difference {terra} allows rasters to differ in extent is quite significant, but not of further concern here. The issue is actually with {sf} which compares geometries to a certain level of precision which lead to errrs in .read_raster_source(). To match rasters correctly as overlapping, .read_raster_source() should apply a precision roundtrip before comparing the bounding boxes. A reasonable thresholds seems to be 5 decimal points, irrespective of the units of the CRS (maybe even lower).

This example shows that {terra} still merges raster event if the differences in extent are quite substantial

library(terra)
#> terra 1.7.55

r <- rast()

(e1 <- ext(r))
#> SpatExtent : -180, 180, -90, 90 (xmin, xmax, ymin, ymax)
(e2 <- ext(e1 - 3.6))
#> SpatExtent : -176.4, 176.4, -86.4, 86.4 (xmin, xmax, ymin, ymax)
(e3 <- ext(e1 - 3.61))
#> SpatExtent : -176.39, 176.39, -86.39, 86.39 (xmin, xmax, ymin, ymax)

r1 <- rast(e1, crs = "EPSG:4326")
r1[] <- runif(100)
r2 <- rast(e2, crs = "EPSG:4326")
r2[] <- runif(100)
r3 <- rast(e3, crs = "EPSG:4326")
r3[] <- runif(100)

# works 
r_ok <- c(r1, r2)
# throws error
try(r_error <- c(r1, r3))
#> Error : [rast] extents do not match

Created on 2023-12-04 with reprex v2.0.2