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


# This function runs the SDMfunction for each species. option to run it in parallel.


RunSDMs <- function(RespNames, SDMfunction){
  if(RunInParallel == TRUE){
    ## Start snowfall
    sfInit(parallel = TRUE, cpus = CPU)
    
    # Export global variables
    sfExportAll()
    
    # Export libraries
    for (i in 1:nrow(library_list)) {
      lib <- library_list[i, "Packages"]
      if(lib != "snowfall"){
        sfLibrary(lib, character.only = TRUE)  
      }
    }

    ## Run the SDMfunction in parallel
    SDM.out <- sfClusterApplyLB(RespNames, SDMfunction)
    
    ## Stop snowfall
    sfStop(nostop = FALSE)
    
  } else {
    ## Run the SDMfunction with lapply
    SDM.out <- lapply(RespNames, SDMfunction) 
    
  }
}





# ====================================================================
#
# 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.
#
# 
# ====================================================================




