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


# Function to fit SDMs


FitSDMs <- function(BioModInputData_GLM_GAM, BioModInputData_BRT,RunFunction,myRespName){
  setwd(file.path(user_dir, base_dir, species_out_dir))
  
  # 2. computing the models
  # 2.1 Defining Models Options using default options.
  myBiomodOption <- BIOMOD_ModelingOptions()
 
  # Computing the single models for 
  # GLM and GAM
  
  tryCatch({  
    if(RunFunction == TRUE){ # only run of there is a minimum number of presence values
      myBiomodModelOut_GAMGLM <- BIOMOD_Modeling(
        BioModInputData_GLM_GAM,               
        models = c('GLM','GAM'),         
        bm.options = myBiomodOption,     
        nb.rep=1,                        
        data.split.perc=100,             
        prevalence=0.5,                  
        var.import=1,                    
        metric.eval = c('ROC','TSS'),    
        scale.models = FALSE,            
        seed.val = 42,                   
        do.full.models = FALSE )         
      
    }
  },
  error = function(e){
    
    error <- geterrmessage()
    WriteLogFile(paste(user_dir, base_dir, species_out_dir, LogFile,sep="/"),
                 ln=paste0("ERROR: error in function of ", myRespName, ": ", error))
    
  })
  
  # look at the summary output
  #myBiomodModelOut_GAMGLM
  
  tryCatch({
    if(RunFunction == TRUE){ # only run of there is a minimum number of presence values
      myBiomodModelOut_BRT <- BIOMOD_Modeling(
        BioModInputData_BRT,
        models = 'GBM',
        bm.options = myBiomodOption,     
        nb.rep=1,                        
        data.split.perc=100,             
        prevalence=0.5,
        var.import=1,                    
        metric.eval = c('ROC','TSS'),    
        scale.models = FALSE,  
        seed.val = 42,                   
        do.full.models = FALSE )
    }
    
    
  },
  error = function(e){
    
    error <- geterrmessage()
    WriteLogFile(paste(user_dir, base_dir, species_out_dir,LogFile,sep="/"),
                 ln=paste0("ERROR: error in function of ", myRespName, ": ", error))
    
  })
  
  # look at the summary output
  #myBiomodModelOut_BRT
  
  # write error message to logfile if not all models converged
  if(myBiomodModelOut_GAMGLM@models.failed != "none" | myBiomodModelOut_BRT@models.failed != "none"){
    WriteLogFile(paste(user_dir, base_dir, species_out_dir,LogFile,sep="/"),
                 ln=paste0("ERROR: error in function of ", myRespName, ": Not all algorithms converged"))
  }
  
  return(list(
    ModelFit_GAMGLM = myBiomodModelOut_GAMGLM, 
    ModelFit_BRT = myBiomodModelOut_BRT))
}


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

