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


#10_CacluateandSaveResponseCurves 

CalculateResponseCurves <- function (myBiomodModelOut_GAMGLM_100p,myBiomodModelOut_BRT_100p,response.dir,myRespName){
  
  glm_model <- BIOMOD_LoadModels(myBiomodModelOut_GAMGLM_100p, algo ="GLM",run="allRun")
  gam_model <- BIOMOD_LoadModels(myBiomodModelOut_GAMGLM_100p, algo ="GAM",run="allRun")
  
  
  
  resp_curves_glm <- bm_PlotResponseCurves(bm.out = myBiomodModelOut_GAMGLM_100p, 
                                           models.chosen = glm_model,
                                           new.env = get_formal_data(myBiomodModelOut_GAMGLM_100p, 'expl.var'),
                                           show.variables = get_formal_data(myBiomodModelOut_GAMGLM_100p, 'expl.var.names'),
                                           fixed.var.metric = 'mean',
                                           do.plot = FALSE)
  
  resp_curves_gam <- bm_PlotResponseCurves(bm.out = myBiomodModelOut_GAMGLM_100p, 
                                           models.chosen = gam_model,
                                           new.env = get_formal_data(myBiomodModelOut_GAMGLM_100p, 'expl.var'),
                                           show.variables = get_formal_data(myBiomodModelOut_GAMGLM_100p, 'expl.var.names'),
                                           fixed.var.metric = 'mean',
                                           do.plot = FALSE)
  
  resp_curves_brt <-  bm_PlotResponseCurves(bm.out = myBiomodModelOut_BRT_100p, 
                                            models.chosen = "all", 
                                            new.env = get_formal_data(myBiomodModelOut_GAMGLM_100p, 'expl.var'),
                                            #new.env - use the same set of variables    
                                            show.variables = get_formal_data(myBiomodModelOut_GAMGLM_100p, 'expl.var.names'),
                                            fixed.var.metric = 'mean',
                                            do.plot = FALSE)
  
  response_curves_glmdt <- as.data.table(resp_curves_glm$tab)
  response_curves_gamdt <- as.data.table(resp_curves_gam$tab)
  response_curves_brtdt <- as.data.table(resp_curves_brt$tab)
  
  Vars <- VariableData$Variables
  
  for (i in 1:length(Vars)) {
    
    myVar <- as.character(Vars[i])
    
    #extract value for GLM
    GLMvalue <- response_curves_glmdt[expl.name == myVar, c('expl.val', 'pred.val')]
    
    #extract value for GLM
    GAMvalue <- response_curves_gamdt[expl.name == myVar, c('expl.val', 'pred.val')]
    
    #extract value for GBM
    BRTvalue <- response_curves_brtdt [expl.name == myVar, c('expl.val', 'pred.val')]
    
    respcurvedt <- docall(cbind, list(GLMvalue$expl.val,GLMvalue$pred.val, GAMvalue$pred.val, BRTvalue$pred.val))
    colnames(respcurvedt) <- c("Explanatory var", "GLM", "GAM", "BRT")
    
    write.csv(respcurvedt, file = file.path(response.dir,paste(myVar,"_", myRespName, ".csv",sep="")))
    
    rm(respcurvedt)
  }                               
  
  
}


CalculateMIV <- function(myRespName, response.dir, weights) {
  
  MIVdt <- data.table(Species = myRespName)
  
  Vas <- SpeciesData$dt_species_data[,`Taxon group`=="Vascular plant"]
  
  if (any(SpeciesData$dt_species_data$Species == myRespName)) {
    
    Vars <- VariableData$Variables
    
      for (i in 1:length(Vars)){
        
        #TSS <- as.data.table(CV_Eval_Stats[,c("TSS.GLM.cv","TSS.GAM.cv","TSS.BRT.cv")])
        
        df <- read.csv(file.path(paste0(response.dir, "/", Vars[i], "_", myRespName, ".csv")))
        
        df$ens_curve <- (df$GLM * weights[1] + df$GAM * weights[2] + df$BRT * weights[3]) / 
          (sum(weights))
        
        MIV_myVar <- median(df[df$ens_curve == max(df$ens_curve), 2])
        
        col_name <- paste0(Vars[i], "_MIV")
        MIVdt[,(col_name) := MIV_myVar]
        
      }
    
      
    }
  return(list(MIVdt=MIVdt))
}




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

