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


#BioScore loading libraries and creating directories 
# it includes the following functions
# - loadlibraries
# - create_species_directories
# - CleanMemory_AfterEnvDataExtraction

# set conditions to save tif-files in a compressed format.
tifoptions <- c("COMPRESS=DEFLATE", "PREDICTOR=2", "ZLEVEL=6")

#2. Read model and system settings 
#working directory is already set up in the script to user directory and base directory is also defined 
settings_system <- paste0(github_dir,"/",BS_module,"/","BioScore_system_config.R")
settings_model <- paste0(github_dir,"/",BS_module,"/","BioScore_model_settings.R")

#3. Load libraries 
#Load libraries 
library_list <- data.frame(
  "Packages" = c("snowfall", "raster", "biomod2", "data.table", "usdm", "git2r"), 
  "Versions" = c("1.84-6.3", "3.6-26","4.2-4","1.14.10", "2.1-7", "0.35.0"))

loadlibraries <- function (library_list){
  
  
  # Install and load specific versions of libraries
  for (i in 1:nrow(library_list)) {
    
    lib <- library_list[i, "Packages"]
    version <- library_list[i, "Versions"]
    
    if (requireNamespace(lib, quietly = TRUE)) {
      
      print("package already installed")
      
    } else {
      
      devtools::install_version(lib, version = version, dependencies = TRUE)
      print("packages are now installed")
    }
    
    # Load the library
    library(lib, character.only = TRUE)
  }
  
}

# 4. Creating directories 
create_species_directories <- function(user_dir,base_dir, species_in_dir, species_out_dir, settings_system) {
  
  # Construct paths
  species.dir.in <- file.path(user_dir,base_dir, species_in_dir)
  species.dir.out <- file.path(user_dir,base_dir, species_out_dir)
  output.maps <- file.path(species.dir.out, "RangeMaps")
  response.dir <- file.path(species.dir.out, "ResponseCurves")
  PlotLocations.dir <- file.path(species.dir.out, "PlotLocations")
  SpeciesMetrics.dir <- file.path(species.dir.out, "SpeciesMetrics")
  ImagesOfRangeMaps.dir <- file.path(species.dir.out, "ImagesOfRangeMaps")
  
  # Create output directories if non-existent
  if (!file.exists(species.dir.out)) dir.create(species.dir.out)
  if (!file.exists(output.maps)) dir.create(output.maps)
  if (!file.exists(response.dir)) dir.create(response.dir)
  if (!file.exists(PlotLocations.dir)) dir.create(PlotLocations.dir)
  if (!file.exists(SpeciesMetrics.dir)) dir.create(SpeciesMetrics.dir)
  if (!file.exists(ImagesOfRangeMaps.dir)) dir.create(ImagesOfRangeMaps.dir)
  
  return(list(
    output.maps=output.maps,
    response.dir=response.dir,
    PlotLocations.dir=PlotLocations.dir,
    SpeciesMetrics.dir=SpeciesMetrics.dir,
    ImagesOfRangeMaps.dir=ImagesOfRangeMaps.dir
    ))
  
}


### read all other bioscore functions saved in source files
LoadFunctions <- function(){
  source(file.path(github_dir, "core", "02_Create-logfile.R"))
  source(file.path(github_dir, "core", "03_LoadAndFormatEnvData.R"))
  source(file.path(github_dir, "core", "04_SpeciesSelection.R"))
  source(file.path(github_dir, "core", "05_ObservatiosSelection.R"))
  source(file.path(github_dir, "core", "06_FormatInputData.R"))
  source(file.path(github_dir, "core", "07_FitSDMs.R"))
  source(file.path(github_dir, "core", "08_EvaluateSDMs.R"))
  source(file.path(github_dir, "core", "09_VariableImportance.R"))
  source(file.path(github_dir, "core", "10_CalculateResponseCurves.R"))
  source(file.path(github_dir, "core", "11_ProjectSDMs.R"))
  source(file.path(github_dir, "core", "12_SaveStats.R"))
  source(file.path(github_dir, "core", "13_SDMfunction.R"))
  source(file.path(github_dir, "core", "14_SaveAllMetrics.R"))
  source(file.path(github_dir, "core", "15_RunSDMFunction.R"))
  
  
}




CleanMemory <- function(){
  
  rm(list=setdiff(ls(), c(
    "AllMetricsSave",
    "base_dir",
    "bm_CalculateStat",
    "bm_FindOptimStat.check.args",
    "BS_module",
    "CalculateMIV",
    "CalculateResponseCurves",
    "CleanMemory",
    "contingency_table_check",
    "copyScripts",
    "CPU",
    "create_species_directories",
    "CutOffValue",
    "ecospat.boyce", 
    "ecospat.mpa",
    "ExtractVarValues",
    "Evaluate_CV_SDMs",
    "FindOptimStat",
    "FitSDMs",
    "FormatInputForFitting",
    "FormatInputForProjections",
    "fun_testIf01",
    "fun_testIfPosNum",
    "get_optim_value",
    "github_dir",
    "guess_scale",
    "ImageOfRangeMap",
    "ImagesOfPlotLocations",  
    "library_list",
    "loadlibraries",
    "LogFile",
    "MakeEnsembleMaps",
    "min_obs_per_var",  
    "MinYear",
    "MIVCalc",
    "model_dir", 
    "modelsetup",
    "modeltesting",
    "PerformanceMetric",
    "PlotLocations_Env", 
    "ProjectScenarios",
    "ProjectSDMs",
    "Removeoriginal",
    "RunInParallel",
    "RunSDMs",
    "SaveAllMetrics",
    "SaveIntRes",
    "SDMfunction",
    "SelectSpeciesObservations",
    "SpeciesData",
    "species_in_dir",
    "species_out_dir",
    "TableWithOverviewVariables",
    "taxo_group",
    "user_dir",
    "var_fit_dir",
    "VariableData",
    "VarImpFunction",
    "WriteLogFile")))
  
  gc(verbose = TRUE)
}



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




