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)
library(rmapshaper)
library(geojsonsf)
library(jsonlite)

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

# Path to HotspotExplorer countries file
path_origcountries <- "/mnt/hdrive/NaturaConnect/NaturaConnector/scripts/countries.json"

# Path bioregions
# Uses the EU Biogeographical regions boundaries 
# https://www.eea.europa.eu/data-and-maps/data/biogeographical-regions-europe-3
path_ecoregion <- "Inputs/Bioregions_EU28clipped.shp"

# Countries file from 
path_countries <- "Outputs/Vector/PG_gadm_octsaccession_name0_mollweide.gpkg"

# ---- #
# Load in files
origcountries <- sf::st_read(path_origcountries, quiet = TRUE) |> 
  sf::st_make_valid()
ecog <- sf::st_read(path_ecoregion,quiet = TRUE) |> 
  sf::st_make_valid()
countries <- sf::st_read(path_countries, layer = "EU_28plus", quiet = TRUE) |> 
  sf::st_make_valid()

# Security checks
assertthat::assert_that(
  !is.na(sf::st_crs(ecog)),
  inherits(countries, "sf"),
  dir.exists(path_output)
)

# ---- #

# For countries match format where possible
countries$tiny <- ifelse(countries$NAME_0 %in% c("Andorra", "Luxembourg", "Malta", "San Marino",
                                                 "Vatican City"),
                         yes = TRUE, no = FALSE)
countries$dashboard_detail <- FALSE

countries <- countries |> sf::st_transform(crs = sf::st_crs(ecog))

# Simplify the geometries and convert to geojson
co <- countries |> 
  # Simplify polygon
  # st_simplify(preserveTopology = TRUE, dTolerance = 5000) |> 
  ms_simplify(keep_shapes = TRUE, keep = 0.1) 
  # sf_geojson()
  
# Save the output
sf::write_sf(co, paste0(path_output, "countries.shp"))
sf::write_sf(co, paste0(path_output, "countries.geojson"))

# Simplify the geometries and convert to geojson
ec <- ecog |> 
  # Simplify polygon
  # st_simplify(preserveTopology = TRUE, dTolerance = 5000) |> 
  ms_simplify(keep_shapes = TRUE, keep = 0.1) 
# sf_geojson()

sf::write_sf(ec, paste0(path_output, "biogeoregions.shp"))
sf::write_sf(ec, paste0(path_output, "biogeoregions.geojson"))

# ---- #
#### Assess coverage of biogeographic regions per country ####
library(dplyr)

# Loop through and intersect
out <- data.frame()
for(co in countries$NAME_0){
  
  # Subset
  sub <- subset(countries, NAME_0 == co)
  
  # Assess ecoregion coverage
  ints <- sf::st_intersection(sub, ecog)
  
  if(nrow(ints)>0){
    ints <- ints |> dplyr::select(NAME_0, code, name) |> dplyr::rename(countryname = NAME_0,
                                                                       biogeoregion = name) |> 
      sf::st_drop_geometry()
  }
  out <- bind_rows(out, ints)
}

# Save output of intersection somewhere
write.csv(out, paste0(path_output, "Countrybioregion_intersection.csv"),row.names = FALSE)