#Assessing the associations between renewable energy generation and other human-induced threats to terrestrial biodiversity 

#Authors: Antonella Gorosábel*, Harith Farooq, Mark Mulligan, Lars L. Iversen, Jonas Geldmann

# CONSERVATION APPROACH

# setup -------------------------------------------------------------------

library(tidyverse)
library(terra)
library(sf)
library(readxl)
library(sp)
library(gridExtra)
library(tidyr)
library(boot)
library(writexl)

#As an example the script is written with the information of Birds in Europe. For the rest of the tables, change the "sheet name" and follow the same script

table <- terra::vect("data/Birds_EU.shp") %>%
  st_as_sf() %>%
  setNames(gsub("B_", "", colnames(.))) %>%
  st_drop_geometry() %>% 
  as_tibble() %>% 
  select("layer", 
         "SolC",
         "SolF", 
         "WFC",
         "WFF", 
         "HydroC",
         "HydroF", 
         "Agr25", 
         "Hun25", 
         "Inv25",
         "Log25", 
         "Pol25", 
         "Urb25", 
         "VU_spp",
         "EN_spp",
         "CR_spp") %>%
  rename(
    DamC = HydroC,
    DamF = HydroF) %>%
  rename_with(~ sub("25$", "", .),
              everything())
  
#Tables for each situation: present and future
#PRESENT
threat_table <- table[, c("SolC", 
                          "WFC", 
                          "DamC", 
                          "Agr", 
                          "Hun", 
                          "Inv", 
                          "Log", 
                          "Pol", 
                          "Urb")]

#FUTURE
threat_table <- table[, c("SolF", 
                          "WFF", 
                          "DamF", 
                          "Agr",
                          "Hun", 
                          "Inv", 
                          "Log", 
                          "Pol", 
                          "Urb")]

#Threatened species data for present and future
species_info <- table[, c("VU_spp", "EN_spp", "CR_spp")]

####################################################

# Mann-Whitney Test -------------------------------------------------------

#Repeat the same analysis for the future

#Identify all possible overlaps between all threats in a new table
combinations <- combn(colnames(threat_table), 2)

overlap_matrix <- matrix(0, 
                         nrow = nrow(threat_table),
                         ncol = ncol(combinations))

colnames(overlap_matrix) <- apply(combinations, 
                                  2,
                                  paste, 
                                  collapse = "-")

for (i in seq_along(colnames(overlap_matrix))) {
  
  # obtain the indices of the two columns (threat_table) en the combination
  idx1 <- which(colnames(threat_table) == combinations[1, i])
  idx2 <- which(colnames(threat_table) == combinations[2, i])
  
  # verify if there is an overlap for the combination of threats
  overlap_matrix[, i] <- as.integer(threat_table[, idx1] == 1 &
                                      threat_table[, idx2] == 1)}

#Define as a data.frame for the following calculations
table_comb <- as.data.frame(overlap_matrix)

#Create a new data.frame to put the results
results <- data.frame(threat = character(),
                      variable = character(),
                      U_statistic = numeric(),
                      p_value = numeric(),
                      mean_overlap = numeric(),
                      mean_no_overlap = numeric(),
                      max_mean = character(),
                      significance = character(),
                      mean_boost_overlap = numeric(),
                      mean_boost_no_overlap = numeric(),
                      max_mean_boost =  character(),
                      ci_overlap_low = numeric(),
                      ci_overlap_high = numeric(),
                      ci_no_overlap_low = numeric(),
                      ci_no_overlap_high = numeric(),
                      stringsAsFactors = FALSE)

# Define the function for bootstrapping the mean
bootstrap_mean <- function(data, indices) {
  sampled_data <- data[indices]
  return(mean(sampled_data, na.rm = TRUE))}

#Define the information in the new table of results and run the Mann-Whitney U
for (col in colnames(table_comb)) {
  
  #Indicate the cells with overlaps
  overlap <- which(table_comb[[col]] == 1) 
  
  #Indicate the cells without overlaps
  no_overlap <- which(table_comb[[col]] == 0)  
  
  for (var in colnames(species_info)) {
    
    # Calculate the mean number of species in each group
    mean_overlap <- mean(species_info[[var]][overlap])
    mean_no_overlap <- mean(species_info[[var]][no_overlap])
    
    #Determine which group has a higher mean value
    if (mean_overlap > mean_no_overlap) {
      max_mean <- "overlap"} else 
      {max_mean <- "no_overlap"}
    
    #Calculate the Mann-Whitney U
    mw_test <- wilcox.test(species_info[[var]][overlap],
                           species_info[[var]][no_overlap])
    
    #Determine the significance of the test
    if (is.na(mw_test$p.value)) 
    {significance <- "NA"} else if (mw_test$p.value > 0.05) {
      significance <- "Non significant"} else 
      {significance <- "Significant"}
    
    #Bootstrap of the mean
    overlap_data <- species_info[[var]][overlap]
    no_overlap_data <- species_info[[var]][no_overlap]
    
    #Bootstrap for overlap data
    boot_overlap <- boot(data = overlap_data,
                         statistic = bootstrap_mean,
                         R = 1000)
    mean_boost_overlap <- boot_overlap$t %>% mean()
    
    #Obtain the CI and its limits for overlap data
    ci_overlap <- boot.ci(boot_overlap, 
                          type = "perc", 
                          conf = 0.95)
    ci_overlap_low <- if (!is.null(ci_overlap$percent))
      ci_overlap$percent[4] else NA
    ci_overlap_high <- if (!is.null(ci_overlap$percent))
      ci_overlap$percent[5] else NA
    
    # Bootstrap for no overlap data
    boot_no_overlap <- boot(data = no_overlap_data,
                            statistic = bootstrap_mean,
                            R = 1000)
    mean_boost_no_overlap <- boot_no_overlap$t %>% mean()
    
    #Obtain the CI and its limits for no_overlap data
    ci_no_overlap <- boot.ci(boot_no_overlap, 
                             type = "perc", 
                             conf = 0.95)
    ci_no_overlap_low <- if (!is.null(ci_no_overlap$percent))
      ci_no_overlap$percent[4] else NA
    ci_no_overlap_high <- if (!is.null(ci_no_overlap$percent))
      ci_no_overlap$percent[5] else NA
    
    #Determine which group has a higher bootstrapping mean value
    if (mean_boost_overlap > mean_boost_no_overlap) {
      max_mean_boost <- "overlap"} else 
      {max_mean_boost <- "no_overlap"}
    
    # Save the results in the table
    results <- rbind(
      results, 
      data.frame(threat = col,
                 variable = var,
                 U_statistic = mw_test$statistic,
                 p_value = mw_test$p.value,
                 mean_overlap = mean_overlap,
                 mean_no_overlap = mean_no_overlap,
                 max_mean = max_mean,
                 significance = significance,
                 mean_boost_overlap = mean_boost_overlap,
                 mean_boost_no_overlap = mean_boost_no_overlap,
                 max_mean_boost =  max_mean_boost,
                 ci_overlap_low = ci_overlap_low,
                 ci_overlap_high = ci_overlap_high,
                 ci_no_overlap_low = ci_no_overlap_low,
                 ci_no_overlap_high = ci_no_overlap_high,
                 stringsAsFactors = FALSE))}
}

#Present
results_final <- results %>%
  separate(threat,
           into = c("Threat1", "Threat2"),
           sep = "-") %>%
  filter(Threat1 %in% 
           c("WFC", "SolC", "DamC") | Threat2 %in% 
           c("WFC", "SolC", "DamC"))



#Future
results_final <- results %>%
  separate(threat,
           into = c("Threat1", "Threat2"),
           sep = "-") %>%
  filter(Threat1 %in% 
           c("WFF", "SolF", "DamF") | Threat2 %in% 
           c("WFF", "SolF", "DamF"))


write_xlsx(results_final, "results_final.xlsx")

#####################################################

# Supplementary Material 2 - Table S2.1 -----------------------------------

# Overlap of threats

#Select the variables of interest
overlap <- table[, c("SolC",
                     "SolF", 
                     "WFC", 
                     "WFF", 
                     "DamC", 
                     "DamF", 
                     "Agr", 
                     "Hun", 
                     "Inv",
                     "Log", 
                     "Pol", 
                     "Urb")]

#Create the pair combination of variables
combinations_variables <- combn(names(overlap), 2)

#Obtain the percentage of cells with overlaps
results <- data.frame(Combination = character(), 
                      Cells_Presence = numeric(),
                      Percenatge_Cells = numeric(),
                      stringsAsFactors = FALSE)

for (i in 1:ncol(combinations_variables)) {
  
  #Obtain each combination
  vars <- combinations_variables[, i]
  
  #Filter the rows that have the presence of both variable
  rows_with_presence <- overlap[overlap[, vars[1]] == 1 & 
                                  overlap[, vars[2]] == 1, ]
  
  #Count the number of rows with the presence of both variables
  cells_presence <- nrow(rows_with_presence)
  
  #Calculate the percentage of cells 
  percentage_cells <- (cells_presence / nrow(overlap)) * 100
  
  #Save the results in the new table
  results <- rbind(results, list(paste(vars[1], vars[2], sep = "-"),
                                 cells_presence,
                                 percentage_cells))
}

# Rename the columns of the result table
colnames(results) <- c("Combination", 
                       "Cells_Presence",
                       "Percenatge_Cells")


print(results)

#####################################################
