Martin Jung's avatar
Martin Jung committed
# Purpose of this script is just to format the biogeoregion file so
# that it is ready to be used for the NaturaConnector code
library(assertthat)
library(terra)
library(sf)

# Path to raster grids
path_grid <- "Inputs/grid_5km_surf.gpkg"

# Path to idrive folder for ouput
path_output <- "/mnt/idrive/jung/forNaturaConnector/"

# Path bioregions
# Uses the EU Biogeographical regions boundaries 
# https://www.eea.europa.eu/data-and-maps/data/biogeographical-regions-europe-3
path_ecoregion <- "/mnt/pdrive/bec_data/100_rawdata/EU_BiogeoRegions2016_shapefile/BiogeoRegions2016.shp"

# ---- #
# Load in files
fullgrid <- sf::st_read(path_grid, quiet = TRUE)
ecog <- sf::st_read(path_ecoregion,quiet = TRUE)

# Security checks
assertthat::assert_that(
  sf::st_crs(fullgrid) == sf::st_crs(ecog),
  dir.exists(path_output)
)

# ---- #
# Crop them
new <- ecog |> 
  sf::st_crop(sf::st_bbox(fullgrid)) |> 
  sf::st_crop(fullgrid) |> 
  sf::st_make_valid()

# Intersect
new2 <- new |> sf::st_intersects(fullgrid)

# Save the output
sf::write_sf(new2, paste0(path_output, "biogeoregions.shp"))