# ====================================================================
#
# Copyright 2025, PBL Netherlands Environmental Assessment Agency
# See the copyright notice at the end of this file.
#
# ====================================================================


# 1. F_Species_Richness: function which creates species richness tables (# of species per grid cell) per desired scenario

F_Species_Richness <- function(RespNames) {
  dt_SpeciesRichness <- NULL
  
  for (RespName in RespNames) {
    
    raster <- terra::rast(file.path(user_dir, base_dir, species_out_dir, "RangeMaps",
                                    ProjectScenarios, paste0(RespName, ".tif")))
    
    names(raster) <-  ProjectScenarios
    
    if(RespName == RespNames[1]){
      df_SpeciesRichness <- as.data.frame(raster, xy = TRUE)   
      df_xy <- df_SpeciesRichness[,c("x","y")]
      dt_xy <- as.data.table(na.omit(df_xy))
      df_SpeciesRichness <- df_SpeciesRichness[,ProjectScenarios]
    } else {
      df_SpeciesRichness <- as.data.frame(raster, xy = FALSE)   
    }
    
    
    dt_CurrentSpecies <- as.data.table(na.omit(df_SpeciesRichness))
    
    # sum the species range maps
    if (is.null(dt_SpeciesRichness)) {
      dt_SpeciesRichness <- dt_CurrentSpecies  
    } else {
      dt_SpeciesRichness <- dt_SpeciesRichness + dt_CurrentSpecies  
    }
    
    rm(raster, df_SpeciesRichness, dt_CurrentSpecies)
  }
  
  # for rasters that include probability values that range between 0 and 1000 
  # the values of the species richness should be devided by 1000
  if(SetValuesUnderThresholdToZero == FALSE | SetValuesAboveThresholdToOne == FALSE){
    dt_SpeciesRichness <- dt_SpeciesRichness/1000
  }
  
  # append xy coordinates
  dt_SpeciesRichness <- cbind(dt_xy, dt_SpeciesRichness)
  
  
  write.csv(dt_SpeciesRichness, file.path(user_dir, base_dir, species_out_dir, 
                                          paste0("Species_Richness", ".csv")))
  
  return(dt_SpeciesRichness)
}





# ====================================================================
#
# Copyright 2025, PBL Netherlands Environmental Assessment Agency
# 
# This source code of the BioScore model is owned by PBL Netherlands Environmental Assessment Agency. 
# It is not permitted to copy, redistribute, remix, transform, and build upon the material without written approval of PBL. 
# Permission for commercial purposes will not be granted. 
# This code is published to improve the transparency of the models used by PBL, 
# but without any warranty for fitness for any other purpose. 
# After approval of PBL to use the code, PBL will not provide any support.
#
# 
# ====================================================================

