I’m encountering problems with the cv_spatial_autocor
function from the blockCV
package. This function is used to measure spatial autocorrelation in spatial response data or predictor raster files. It also helps in choosing the block size for creating train and test folds in k-fold and leave-one-out cross-validation.
When I use the function with spatial response data, it seems to work fine. However, it fails with predictor raster files. I receive the following error message:
in wk_handle.wk_wkb(wkb, s2_geography_writer(oriented = oriented, :
Loop 0 is not valid: Edge 1 crosses edge 3
In addition: Warning messages:
1: In st_is_longlat(x) :
bounding box has potentially an invalid value range for longlat data
2: In st_is_longlat(x) :
bounding box has potentially an invalid value range for longlat data
The issue seems to be related to these lines of code in the cv_spatial_autocor
function:
vis_block <- sf::st_make_grid(x_obj, cellsize = round(size), what = "polygons")
vis_block <- sf::st_sf(vis_block[x_obj])
The problem occurs because round(size)
is set too large, resulting in only one feature for vis_block
. Given that x_obj
has multiple features, this creates an issue.
I haven’t been able to find a solution. I tested the function with projected coordinates, which resolved the error message. However, it produced only one large block, which is not correct. Any help would be greatly appreciated.
Here are the spatial response data and predictor rasters:
https://www.dropbox.com/scl/fo/50xy66tx5ay3mp9uuf563/AK_1HaTS60fnMWSxEIOrcxY?rlkey=fwfrabwqyofedfigll47g9vf4&dl=0
Here is my code to reproduce the issue:
##########################################################
## Spatial autocorrelation of continuous raster files
##########################################################
## Using unprojected coordinates
r <- terra::rast("C:/Users/Downloads/r_bioclimate.tif")
print(r)
set.seed(1)
test <- blockCV::cv_spatial_autocor(r = r, num_sample = 5000, plot = TRUE)
## Using projected coordinates
r_proj <- terra::rast("C:/Users/Downloads/r_bioclimate.tif")
r_proj <- terra::project(r_proj, "+proj=lcc +lat_0=40 +lon_0=-96 +lat_1=20 +lat_2=60 +x_0=0 +y_0=0 +datum=NAD83 +units=m +no_defs +type=crs")
print(r_proj)
set.seed(1)
test <- blockCV::cv_spatial_autocor(r = r_proj, num_sample = 5000, plot = TRUE)
## plot(test$plots$map_plot)
##########################################################
## Spatial autocorrelation of a binary/continuous response
##########################################################
x <- terra::vect("C:/Users/Downloads/presence_absence_data.shp")
x <- sf::st_as_sf(x)
set.seed(1)
test <- blockCV::cv_spatial_autocor(r = r[[1]], x = x, column = "presence", plot = TRUE)