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


# 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 <- "VegetationTypes/BS_VegTypes_system_settings.R"
settings_model <- "VegetationTypes/BS_VegTypes_model_settings.R"

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

# Load libraries 
library_list <-data.frame("Packages" = c("snowfall", "raster", "data.table", "git2r",
                                         "randomForestSRC","terra","dplyr","sp",
                                         "ggplot2","pROC"), 
                          "Versions" = c("1.84-6.3", "3.6-26", "1.14.10", "0.33.0",
                                         "3.2.3","1.7-71","1.1.4","2.1-3",
                                         "3.5.1","1.18.5"))

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)
  }
  
}

### read all other functions needed for the habitat model
LoadFunctions <- function(){
  setwd(github_dir)
  source("core/08_EvaluateSDMs.R")
  source("core/02_Create-logfile.R")
  source("VegetationTypes/02_FormatObservations.R")
  source("VegetationTypes/03_FormatSDMs_forRF.R")
  source("VegetationTypes/04_Fit_RF.R")
  source("VegetationTypes/05_Project_RF.R")
  source("VegetationTypes/06_Evaluate_RF.R")
  source("VegetationTypes/07_PostProcessingVegTypes.R")
  setwd(file.path(user_dir,base_dir))
}
  
### clean memory
CleanMemory <- function(){
  rm(list=setdiff(ls(), 
                  c("base_dir",                    
                    "binarized_SDMs",              
                    "bm_CalculateStat",            
                    "bm_FindOptimStat.check.args",
                    "BS_module",                   
                    "contingency_table_check",     
                    "DropHabitats_plots",      
                    "dt_charact_species",
                    "ecospat.boyce",               
                    "ecospat.mpa",                 
                    "Evaluate_CV_SDMs",           
                    "Evaluate_RFmodel",            
                    "Evaluate_RFpredictions",      
                    "FindOptimStat",               
                    "FitRF",                      
                    "FitRF_forCVs",                
                    "FitRF_forProjections",        
                    "FormatObservations_forRF",    
                    "FormatSDMs_forRF",           
                    "FormatSpeciesNames_forRF",    
                    "fun_testIf01",                
                    "fun_testIfPosNum",            
                    "get_optim_value",            
                    "github_dir",                 
                    "guess_scale",
                    "HabitatName",
                    "HabitatNames",
                    "library_list",               
                    "LoadFunctions",               
                    "loadlibraries",               
                    "loadSDMpredictions",          
                    "LogFile",                    
                    "ModelFitting",                
                    "modeltesting",                
                    "Name",                        
                    "OpenLogFile",                
                    "PathPNG",                     
                    "PathTemp",                    
                    "PlotLocations",               
                    "plots",                      
                    "Project_RF",                  
                    "Project_RF_withSDMs",         
                    "ProjectScenarios",            
                    "RescalingPoOs",  
                    "Scenario",
                    "SelectPlots_forRF",           
                    "SelectSpecies_forRF",         
                    "settings_model",             
                    "settings_system",             
                    "species_in_dir",              
                    "species_out_dir",             
                    "species_special",            
                    "taxo_group",                  
                    "user_dir",                    
                    "WriteLogFile"  )))
  gc()
  }





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

