---
title: "Haiti_Biodiv"
author: "Ian Pshea-Smith"
date: "`r Sys.Date()`"
output: html_document
---

```{r Data Import}

  BD_Haiti <-  read.csv("REPLACE W/ YOUR FILE DIRECTORY")
  View(BD_Haiti)

  # As a spatial (sf) object
    library(sf) # Used for spatial objects & plotting
      Points_sf <- st_as_sf(BD_Haiti, coords = c("Longitude", "Latitude"), crs = 4326)  
    
```

```{r Download a Haiti country boundary from geodata}

  library(geodata)
  library(ggplot2)
  library(dplyr)

  # Download Haiti country boundary from geodata
    haiti_country <- gadm(country = "HTI", level = 0, path = tempdir(), resolution = 1)
    haiti_country_sf <- st_as_sf(haiti_country) %>% st_transform(crs = 4326)
  
  # Download Haiti admin-level 3 boundaries
    haiti_admin3 <- gadm(country = "HTI", level = 3, path = tempdir(), resolution = 1)
    haiti_admin3_sf <- st_as_sf(haiti_admin3) %>% st_transform(crs = 4326)
  
  # Identify the ADM3 polygons (communal sections) that contain sample points
    study_communes <- haiti_admin3_sf[
      lengths(st_intersects(haiti_admin3_sf, Points_sf)) > 0,
    ]
  
  # Create a bounding box polygon for cropping
    study_bbox <- st_bbox(study_communes)
    buffer_dist <- 0.03
    bbox_coords <- matrix(c(
      study_bbox[1] - buffer_dist, study_bbox[2] - buffer_dist,  # bottom-left
      study_bbox[3] + buffer_dist, study_bbox[2] - buffer_dist,  # bottom-right
      study_bbox[3] + buffer_dist, study_bbox[4] + buffer_dist,  # top-right
      study_bbox[1] - buffer_dist, study_bbox[4] + buffer_dist,  # top-left
      study_bbox[1] - buffer_dist, study_bbox[2] - buffer_dist   # close polygon
    ), ncol = 2, byrow = TRUE)
  
    bbox_poly <- st_sfc(st_polygon(list(bbox_coords)), crs = 4326)
  
  # Crop Haiti country polygon to bounding box
    haiti_cropped <- st_intersection(haiti_country_sf, bbox_poly)
  
  # Create the map with cropped Haiti background
    study_site_map <- ggplot() +
      # Cropped Haiti polygon
      geom_sf(
        data = haiti_cropped,
        fill = "white",
        color = "gray70", 
        linewidth = 0.5
      ) +
      # Study communes
      geom_sf(
        data = study_communes,
        fill = "gray98",
        color = "black",
        linewidth = 0.5
      ) +
      # Sample points
      geom_sf(
        data = Points_sf,
        color = "black",
        size = 1.2
      ) +
      # Labels
      geom_sf_text(
        data = study_communes, 
        aes(label = NAME_3),
        size = 4.2,
        color = "black"
      ) +
      coord_sf(
        xlim = c(study_bbox[1] - buffer_dist, study_bbox[3] + buffer_dist),
        ylim = c(study_bbox[2] - buffer_dist, study_bbox[4] + buffer_dist),
        expand = FALSE
      ) +
      theme_minimal() +
      theme(
        panel.border = element_rect(color = "black", fill = NA, linewidth = 0.5),
        axis.text = element_text(size = 10),
        plot.caption = element_text(size = 10, hjust = 0),
        panel.grid = element_line(color = "gray90", linewidth = 0.3)
      )
  
  # Make the map
    print(study_site_map)


```

```{r Pie chart of species}
  # Load required libraries
    library(dplyr)

  # Folder path for saving outputs
    output_folder <- "REPLACE WITH YOUR OUTPUT DIRECTORY"

  
  # Summarize total counts for each species (all trap types combined)
    species_totals <- BD_Haiti %>%
      summarise(
        Quinx = sum(Quinx),
        Cxn = sum(Cxn),
        Aeae = sum(Aeae),
        Aealb = sum(Aealb),
        Psc = sum(Psc),
        Aem = sum(Aem)
      )
  
  # Extract species names and counts
    species_names <- c("Quinx", "Cxn", "Aeae", "Aealb", "Psc", "Aem")
    species_counts <- as.numeric(species_totals)
  
  # Define gradient colors: dark purple to light pink
    species_colors <- c("#4B0082", "#6A0DAD", "#8A2BE2", "#BA55D3", "#DA70D6", "#FFB6C1")
  
    
  # Create pie chart
    svg(file.path(output_folder, "species_pie_chart.svg"))  
    pie(species_counts, 
        labels = paste0(species_names, "\n", species_counts, " (", 
                        round(100 * species_counts / sum(species_counts), 1), "%)"),
        col = species_colors,
        main = "Species Composition (All Trap Types Combined)",
        border = NA) # Remove borders
    dev.off()

```

```{r Bar Plot of species by trap type}

  library(dplyr)

  # Summarize species counts by Trap_Type
    species_counts <- BD_Haiti %>%
      group_by(Trap_Type) %>%
      summarise(
        Quinx = sum(Quinx),
        Cxn = sum(Cxn),
        Aeae = sum(Aeae),
        Aealb = sum(Aealb),
        Psc = sum(Psc),
        Aem = sum(Aem)
      )
    
  # Rename and reorder trap types
    species_counts <- species_counts %>%
      mutate(Trap_Type = case_when(
        Trap_Type == "CDC LT" ~ "CDC Light",
        Trap_Type == "CDC Gravid" ~ "CDC Gravid",
        Trap_Type == "BG- Sentinel" ~ "BG Sentinel"
      )) %>%
      arrange(factor(Trap_Type, levels = c("CDC Gravid", "BG Sentinel", "CDC Light")))

  # Convert to matrix
    species_matrix <- as.matrix(species_counts[,-1])  # Remove Trap_Type for matrix
    rownames(species_matrix) <- species_counts$Trap_Type
  
  # Define colours
    species_colours <- c("#4B0082", "#6A0DAD", "#8A2BE2", "#BA55D3", "#DA70D6", "#FFB6C1")
    
  # Set dynamic y-axis scale
    max_count <- max(rowSums(species_matrix))  # Calculate max row sum
    ylim_max <- max(10000, ceiling(max_count / 1000) * 1000)  # Round up to nearest 100, minimum 1200

  
  # Create stacked bar chart with renamed and reordered trap types
    svg(file.path(output_folder, "species_bar_chart.svg"))  
    barplot(t(species_matrix), # Transpose for stacking
            main = "Species Counts by Trap Type",
            border = NA, # No borders
            horiz = TRUE, # Horizontal bars
            col = species_colors, # Custom colors
            xlim = c(0, ylim_max),
            legend.text = c("Quinx", "Cxn", "Aeae", "Aealb", "Psc", "Aem"), # Ordered legend
            args.legend = list(x = "topright", bty = "n")) # Legend placement
    dev.off()    

    
```

```{r Site condensed dataset}

  library(dplyr) # dplyr::select
  
  # Create a new variable for Site based on unique combinations of Latitude and Longitude
    BD_Haiti$Site <- paste(BD_Haiti$Latitude, BD_Haiti$Longitude, sep = "_")
  
  # Create a new variable for sampling effort
    sampling_effort <- BD_Haiti %>%
      group_by(Site) %>%
      summarise(SamplingCount = n(), .groups = "drop")

  # Combine grouping, summarising, and adding sampling effort into one step
    BD_Site <- BD_Haiti %>%
      group_by(Site, Latitude, Longitude) %>%
      summarise(
        across(c(Quinx, Aeae, Aealb, Aem, Cxn, Psc), \(x) sum(x, na.rm = TRUE)),
        .groups = "drop"
      ) %>%
      left_join(
        BD_Haiti %>%
          group_by(Site) %>%
          summarise(SamplingCount = n(), .groups = "drop"),
        by = "Site"
      )
  
    # Define the species columns
      species_cols <- c("Quinx", "Aeae", "Aealb", "Aem", "Cxn", "Psc")
    
    # Create a function to summarize and join sampling effort
      summarise_by_trap <- function(df) {
        df %>%
          group_by(Site, Latitude, Longitude) %>%
          summarise(across(all_of(species_cols), ~sum(.x, na.rm = TRUE)), .groups = "drop") %>%
          left_join(
            df %>%
              group_by(Site) %>%
              summarise(SamplingCount = n(), .groups = "drop"),
            by = "Site"
          )
      }
    
    # Create three site-level summaries by trap type
      BD_Site_BGS <- summarise_by_trap(BD_Haiti %>% filter(Trap_Type == "BG- Sentinel"))
      BD_Site_CDC_G <- summarise_by_trap(BD_Haiti %>% filter(Trap_Type == "CDC Gravid"))
      BD_Site_CDC_LT <- summarise_by_trap(BD_Haiti %>% filter(Trap_Type == "CDC LT"))
    
    
    

    
    # Standardize species data by SamplingCount
      BD_Site_Standardised <- BD_Site
      
      BD_Site_Standardised <- BD_Site_Standardised %>%
        mutate(
          across(c(Quinx, Aeae, Aealb, Aem, Cxn, Psc), ~ . / SamplingCount)
        )

  # View the standardized dataset
    print(BD_Site_Standardised)

  # Species only       
    BD_Site_Species <- BD_Site_Standardised %>%
      dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
    View(BD_Site_Species)

```

```{r Temporally condensed dataset}

  # Convert Date to a proper Date format
    BD_Haiti$Date <- as.Date(BD_Haiti$Date, format = "%m/%d/%Y")

  # Create sampling effor variable
    sampling_effort_days <- BD_Haiti %>%
      group_by(Date) %>%
      summarise(SamplingCount = n(), .groups = "drop")

  # Condense observations by Date
    BD_Days <- BD_Haiti %>%
      group_by(Date) %>%
      summarise(across(c(Quinx, Aeae, Aealb, Aem, Cxn, Psc), \(x) sum(x, na.rm = TRUE)),
                .groups = "drop")
    View(BD_Days)

  # Merge sampling effort with BD_Days
    BD_Days_Standardised <- BD_Days %>%
      left_join(sampling_effort_days, by = "Date") %>%
      mutate(across(c(Quinx, Aeae, Aealb, Aem, Cxn, Psc), ~ . / SamplingCount)) %>%
      dplyr::select(-SamplingCount)   
    
  # Species only by date       
    BD_Days_Species <- BD_Days_Standardised %>%
      dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
    View(BD_Days_Species)    
    
  # Add a new variable for month and year
    BD_Haiti$YearMonth <- format(BD_Haiti$Date, "%Y-%m")
    
  # Create sampling effort variable by month
    sampling_effort_months <- BD_Haiti %>%
      group_by(YearMonth) %>%
      summarise(SamplingCount = n_distinct(Date), .groups = "drop")
  
  # Create a new dataset grouped by YearMonth
    BD_Months <- BD_Haiti %>%
      group_by(YearMonth) %>%
      summarise(sample_days = n_distinct(Date),
                across(c(Quinx, Aeae, Aealb, Aem, Cxn, Psc), \(x) sum(x, na.rm = TRUE)),
                .groups = "drop")
    View(BD_Months) 
    
  # Create a new dataset grouped by YearMonth with standardisation
    BD_Months_Standardised <- BD_Months %>%
      left_join(sampling_effort_months, by = "YearMonth") %>%
      mutate(across(c(Quinx, Aeae, Aealb, Aem, Cxn, Psc), ~ . / SamplingCount)) %>%
      dplyr::select(-SamplingCount)  # Remove SamplingCount if no longer needed
            
  # Species only by Month       
    BD_Months_Species <- BD_Months_Standardised %>%
      dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
    View(BD_Months_Species)
    
    
```

```{r Diversity by site}
  
  library(vegan) # Various diversity metrics
  library(tidyverse) # tidyverse::as.matrix
  
  # Gamma Diversity
    Site_Gamma <- vegan::specnumber(BD_Site_Species, groups="rows")
      print(Site_Gamma)
      print(mean(Site_Gamma))
    
  # Alpha Diversity
    Site_Alpha <- vegan::specnumber(BD_Site_Species)
      print(Site_Alpha)
      print(mean(Site_Alpha))    
    
  # Beta Diversity
    Add_Beta_Site = Site_Gamma - mean(Site_Alpha)
      print(Add_Beta_Site) # The regional pool contains 1.24 more species than on the average site.
    Multi_Beta_Site = Site_Gamma/mean(Site_Alpha)
      print(Multi_Beta_Site) # Our gamma diversity is 1.26 times larger than the average alpha richness.
    Beta_Part_Site = 1 - mean(Site_Alpha)/Site_Gamma
      print(Beta_Part_Site) # 20.59% of the regional richness is not contained in the average site.

  # Hill          
    Hill_N_Sites = vegan::renyi(BD_Site_Species, hill= TRUE)
      print(Hill_N_Sites)
      plot(Hill_N_Sites)
    
  # Matrix of site by site dissimilarity values using Bray-Curtis    
    Sites_Bray = vegan::vegdist(BD_Site_Species, method = "bray", binary = FALSE)
    print(Sites_Bray)
      print(mean(Sites_Bray))
      print(median(Sites_Bray))
      
  # Shannon's Diversity Index for each Site
    Site_Shannon <- vegan::diversity(BD_Site_Species, index = "shannon")
      print(Site_Shannon)
    
  # Simpson's Diversity Index for each Site
    Site_Simpson <- vegan::diversity(BD_Site_Species, index = "simpson")
      print(Site_Simpson)   
    
  # Inverse Simpson's Diversity Index for each Site
    Site_InvSimpson <- vegan::diversity(BD_Site_Species, index = "invsimpson")
      print(Site_InvSimpson) 
    
  # Adding Diversity indices to Dataset
    Site_Shannon <- vegan::diversity(BD_Site[ , c("Quinx", "Aeae", "Aealb", "Aem", "Cxn", "Psc")], index = "shannon")
    Site_Simpson <- vegan::diversity(BD_Site[ , c("Quinx", "Aeae", "Aealb", "Aem", "Cxn", "Psc")], index = "simpson")
    Site_InvSimpson <- vegan::diversity(BD_Site[ , c("Quinx", "Aeae", "Aealb", "Aem", "Cxn", "Psc")], index = "invsimpson")

  BD_Site <- BD_Site %>%
    mutate(
      Shannon = Site_Shannon,
      Simpson = Site_Simpson,
      InvSimpson = Site_InvSimpson
    )
  
# View the updated BD_Site dataset
  View(BD_Site)
```

```{r Diversity by day}

  # Gamma Diversity
    Day_Gamma <- vegan::specnumber(BD_Days_Species, groups = "rows")
    print(Day_Gamma)
  
  # Alpha Diversity
    Day_Alpha <- vegan::specnumber(BD_Days_Species)
      print(Day_Alpha)
      print(mean(Day_Alpha))
  
  # Beta Diversity
    Add_Beta_Day <- Day_Gamma - mean(Day_Alpha)
      print(Add_Beta_Day) # The whole time-period contains 1.59 more species than on the average day.
    Multi_Beta_Day <- Day_Gamma / mean(Day_Alpha)
      print(Multi_Beta_Day) # Our gamma diversity is 1.36 times larger than the average daily alpha richness.
    Beta_Part_Day <- 1 - mean(Day_Alpha) / Day_Gamma
      print(Beta_Part_Day) # 26.5% of the time-period's richness is not contained in the average day.
  
  # Hill
    Hill_N_Days <- vegan::renyi(BD_Days_Species, hill = TRUE)
      print(Hill_N_Days)
      plot(Hill_N_Days)
  
  # Matrix of day-by-day dissimilarity values using Bray-Curtis
    Days_Bray <- vegan::vegdist(BD_Days_Species, method = "bray", binary = FALSE)
      print(Days_Bray)
      print(mean(Days_Bray))
      print(median(Days_Bray))
  
  # Shannon's Diversity Index for each Day
    Day_Shannon <- vegan::diversity(BD_Days_Species, index = "shannon")
      print(Day_Shannon)
  
  # Simpson's Diversity Index for each Day
    Day_Simpson <- vegan::diversity(BD_Days_Species, index = "simpson")
      print(Day_Simpson)
  
  # Inverse Simpson's Diversity Index for each Day
    Day_InvSimpson <- vegan::diversity(BD_Days_Species, index = "invsimpson")
      print(Day_InvSimpson)
  
  # Adding Diversity indices to Dataset
    BD_Days <- BD_Days %>%
      mutate(
        Shannon = Day_Shannon,
        Simpson = Day_Simpson,
        InvSimpson = Day_InvSimpson
      )
  
  # View the updated BD_Days dataset
    View(BD_Days)    
```

```{r Diversity by Month}

  # Gamma Diversity
    Month_Gamma <- vegan::specnumber(BD_Months_Species, groups = "rows")
      print(Month_Gamma)
  
  # Alpha Diversity
    Month_Alpha <- vegan::specnumber(BD_Months_Species)
      print(Month_Alpha)
      print(mean(Month_Alpha))
    
  # Beta Diversity
    Add_Beta_Month <- Month_Gamma - mean(Month_Alpha)
      print(Add_Beta_Month) # The total richness across time contains 0.46 more species than on the average month.
    Multi_Beta_Month <- Month_Gamma / mean(Month_Alpha)
      print(Multi_Beta_Month) # Our gamma diversity is 1.08 times larger than the average monthly alpha richness.
    Beta_Part_Month <- 1 - mean(Month_Alpha) / Month_Gamma
      print(Beta_Part_Month) # 7.69% of the total richness across time is not contained in the average month.
  
  # Hill
    Hill_N_Months <- vegan::renyi(BD_Months_Species, hill = TRUE)
      print(Hill_N_Months)
      plot(Hill_N_Months)
  
  # Matrix of month-by-month dissimilarity values using Bray-Curtis
    Months_Bray <- vegan::vegdist(BD_Months_Species, method = "bray", binary = FALSE)
      print(Months_Bray)
      print(mean(Months_Bray))
      print(median(Months_Bray))
  
  # Shannon's Diversity Index for each Month
    Month_Shannon <- vegan::diversity(BD_Months_Species, index = "shannon")
      print(Month_Shannon)
  
  # Simpson's Diversity Index for each Month
    Month_Simpson <- vegan::diversity(BD_Months_Species, index = "simpson")
      print(Month_Simpson)
  
  # Inverse Simpson's Diversity Index for each Month
    Month_InvSimpson <- vegan::diversity(BD_Months_Species, index = "invsimpson")
      print(Month_InvSimpson)
  
  # Adding Diversity indices to Dataset
    BD_Months <- BD_Months %>%
      mutate(
        Shannon = Month_Shannon,
        Simpson = Month_Simpson,
        InvSimpson = Month_InvSimpson
      )
  
  # View the updated BD_Months dataset
   View(BD_Months)

  
```

```{r Monthly averages based on daily data}

  # Load necessary libraries
    library(dplyr)
    library(vegan)
    library(ggplot2)
    library(patchwork) # For combining plots

  # Extract unique YearMonth values in chronological order
    unique_months <- sort(unique(BD_Haiti$YearMonth))

  # Initialize data frame to store diversity results for plotting
    diversity_results <- data.frame(
      YearMonth = character(),
      Alpha_Mean = numeric(),
      Alpha_SD = numeric(),
      Alpha_Median = numeric(),
      Shannon_Mean = numeric(),
      Shannon_SD = numeric(),
      Shannon_Median = numeric(),
      Simpson_Mean = numeric(),
      Simpson_SD = numeric(),
      Simpson_Median = numeric(),
      stringsAsFactors = FALSE
    )
  
  # Loop through each month to calculate diversity indices
    for (month in unique_months) {
      # Filter data for the current month
        current_data <- BD_Haiti %>%
          filter(YearMonth == month) %>%
          dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
        
      # Calculate diversity indices
        alpha <- vegan::specnumber(current_data)
        shannon <- vegan::diversity(current_data, index = "shannon")
        simpson <- vegan::diversity(current_data, index = "simpson")
        
      # Add results to the data frame
        diversity_results <- rbind(diversity_results, data.frame(
          YearMonth = month,
          Alpha_Mean = mean(alpha, na.rm = TRUE),
          Alpha_SD = sd(alpha, na.rm = TRUE),
          Alpha_Median = median(alpha, na.rm = TRUE),
          Shannon_Mean = mean(shannon, na.rm = TRUE),
          Shannon_SD = sd(shannon, na.rm = TRUE),
          Shannon_Median = median(shannon, na.rm = TRUE),
          Simpson_Mean = mean(simpson, na.rm = TRUE),
          Simpson_SD = sd(simpson, na.rm = TRUE),
          Simpson_Median = median(simpson, na.rm = TRUE)
        ))
    }
  
  # Convert YearMonth to Date for better plotting
    diversity_results$YearMonth <- as.Date(paste0(diversity_results$YearMonth, "-01"))
  
  # Print diversity results for each index
    for (i in seq_along(unique_months)) {
      month <- unique_months[i]
      
      # Extract results for the current month
        alpha_mean <- diversity_results$Alpha_Mean[i]
        alpha_sd <- diversity_results$Alpha_SD[i]
        alpha_median <- diversity_results$Alpha_Median[i]
        shannon_mean <- diversity_results$Shannon_Mean[i]
        shannon_sd <- diversity_results$Shannon_SD[i]
        shannon_median <- diversity_results$Shannon_Median[i]
        simpson_mean <- diversity_results$Simpson_Mean[i]
        simpson_sd <- diversity_results$Simpson_SD[i]
        simpson_median <- diversity_results$Simpson_Median[i]
        
      # Print results to console
        cat("\n--- Results for", month, "---\n")
        cat("Alpha Diversity: Mean =", alpha_mean, ", SD =", alpha_sd, ", Median =", alpha_median, "\n")
        cat("Shannon's Index: Mean =", shannon_mean, ", SD =", shannon_sd, ", Median =", shannon_median, "\n")
        cat("Simpson's Index: Mean =", simpson_mean, ", SD =", simpson_sd, ", Median =", simpson_median, "\n")
    }

  # Reshape the data to long format
    diversity_long <- diversity_results %>%
      pivot_longer(
        cols = c(Alpha_Mean, Shannon_Mean, Simpson_Mean),
        names_to = "Diversity_Metric",
        values_to = "Mean_Value"
      )
  
  # Ensure YearMonth is treated as a factor for ANOVA
    diversity_long$YearMonth <- as.factor(diversity_long$YearMonth)
  
  # Alpha Diversity ANOVA
  alpha_aov <- aov(Alpha_Mean ~ YearMonth, data = diversity_results)
  cat("\n--- ANOVA Summary for Alpha Diversity ---\n")
  print(summary(alpha_aov))
  
  # Shannon Diversity ANOVA
  shannon_aov <- aov(Shannon_Mean ~ YearMonth, data = diversity_results)
  cat("\n--- ANOVA Summary for Shannon Diversity ---\n")
  print(summary(shannon_aov))
  
  # Simpson Diversity ANOVA
  simpson_aov <- aov(Simpson_Mean ~ YearMonth, data = diversity_results)
  cat("\n--- ANOVA Summary for Simpson Diversity ---\n")
  print(summary(simpson_aov))
    
  # Define a shade of gold for plots
    gold_color_1 <- "#6A3467"
    gold_color_2 <- "#996B51"
    gold_color_3 <- "#D4AF37"
  
  # Alpha Diversity Plot
    alpha_plot <- ggplot(diversity_results, aes(x = YearMonth)) +
      geom_ribbon(aes(ymin = Alpha_Mean - Alpha_SD, ymax = Alpha_Mean + Alpha_SD), 
                  fill = gold_color_1, alpha = 0.2) +
      geom_line(aes(y = Alpha_Mean), color = gold_color_1, size = 1) +
      geom_point(aes(y = Alpha_Mean), color = gold_color_1, size = 2) +
      labs(title = "Alpha Diversity Over Time",
           x = "Month",
           y = "Alpha Diversity") +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
  
  # Shannon's Diversity Index Plot
    shannon_plot <- ggplot(diversity_results, aes(x = YearMonth)) +
      geom_ribbon(aes(ymin = Shannon_Mean - Shannon_SD, ymax = Shannon_Mean + Shannon_SD), 
                  fill = gold_color_2, alpha = 0.2) +
      geom_line(aes(y = Shannon_Mean), color = gold_color_2, size = 1) +
      geom_point(aes(y = Shannon_Mean), color = gold_color_2, size = 2) +
      labs(title = "Shannon's Diversity Index Over Time",
           x = "Month",
           y = "Shannon's Index") +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
  
  # Simpson's Diversity Index Plot
    simpson_plot <- ggplot(diversity_results, aes(x = YearMonth)) +
      geom_ribbon(aes(ymin = Simpson_Mean - Simpson_SD, ymax = Simpson_Mean + Simpson_SD), 
                  fill = gold_color_3, alpha = 0.2) +
      geom_line(aes(y = Simpson_Mean), color = gold_color_3, size = 1) +
      geom_point(aes(y = Simpson_Mean), color = gold_color_3, size = 2) +
      labs(title = "Simpson's Diversity Index Over Time",
           x = "Month",
           y = "Simpson's Index") +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
    
  # Combine the plots vertically
    combined_plot <- alpha_plot / shannon_plot / simpson_plot
    plot(combined_plot)
 
# Save the combined plot as an SVG file
  output_folder <- "REPLACE WITH YOUR OUTPUT DIRECTORY"
  svg(filename = file.path(output_folder, "Monthly_Div.svg"), width = 8, height = 12)
  print(combined_plot)
  dev.off()     
```

```{r Diversity within the stratified dataset (daily/trap/site counts)}

  # Isolate species rows into a new dataset
    BD_Haiti_Species <- BD_Haiti %>%
      dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
  
  # Gamma Diversity
    Haiti_Gamma <- vegan::specnumber(BD_Haiti_Species, groups = "rows")
      print(Haiti_Gamma)
  
  # Alpha Diversity
    Haiti_Alpha <- vegan::specnumber(BD_Haiti_Species)
      print(Haiti_Alpha)
      print(mean(Haiti_Alpha))
      print(median(Haiti_Alpha))
  
  # Beta Diversity
    Add_Beta_Haiti <- Haiti_Gamma - mean(Haiti_Alpha)
      print(Add_Beta_Haiti) # The regional pool contains 3.157534 more species than on average.
    Multi_Beta_Haiti <- Haiti_Gamma / mean(Haiti_Alpha)
      print(Multi_Beta_Haiti) # Our gamma diversity is 2.110843 times larger than the average alpha richness.
    Beta_Part_Haiti <- 1 - mean(Haiti_Alpha) / Haiti_Gamma
      print(Beta_Part_Haiti) # 52.62557% of the regional richness is not contained in the average record.
  
  # Hill Numbers
    Hill_N_Haiti <- vegan::renyi(BD_Haiti_Species, hill = TRUE)
      print(Hill_N_Haiti)
      #plot(Hill_N_Haiti) 730 plots :(
  
  # Bray-Curtis Dissimilarity
    Haiti_Bray <- vegan::vegdist(BD_Haiti_Species, method = "bray", binary = FALSE)
      print(Haiti_Bray)
      print(mean(Haiti_Bray))
      print(median(Haiti_Bray))
  
  # Shannon's Diversity Index
    Haiti_Shannon <- vegan::diversity(BD_Haiti_Species, index = "shannon")
      print(Haiti_Shannon)
      print(mean(Haiti_Shannon))
      print(median(Haiti_Shannon))
      
  # Simpson's Diversity Index
    Haiti_Simpson <- vegan::diversity(BD_Haiti_Species, index = "simpson")
     print(Haiti_Simpson)
      print(mean(Haiti_Simpson))
      print(median(Haiti_Simpson))
  
  # Inverse Simpson's Diversity Index
    Haiti_InvSimpson <- vegan::diversity(BD_Haiti_Species, index = "invsimpson")
      print(Haiti_InvSimpson)
      print(mean(Haiti_InvSimpson))
      print(median(Haiti_InvSimpson))
  
  # Add Diversity Indices to the Original Dataset
    BD_Haiti <- BD_Haiti %>%
      mutate(
        Shannon = Haiti_Shannon,
        Simpson = Haiti_Simpson,
        InvSimpson = Haiti_InvSimpson
      )
  
  # View the updated BD_Haiti dataset
    View(BD_Haiti)

```

```{r Biodiversity by Trap Type}

  # Filter out days w/ 0 collected mosqs
    BD_Haiti_filtered <- BD_Haiti %>%
      filter(rowSums(dplyr::select(., Quinx, Aeae, Aealb, Aem, Cxn, Psc)) > 0)

  # Create datasets for each Trap_Type
    BD_Haiti_Spec_Grav <- BD_Haiti_filtered %>%
      filter(Trap_Type == "CDC Gravid") %>%
      dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
    
    BD_Haiti_Spec_Lt <- BD_Haiti_filtered %>%
      filter(Trap_Type == "CDC LT") %>%
      dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
    
    BD_Haiti_Spec_BG <- BD_Haiti_filtered %>%
      filter(Trap_Type == "BG- Sentinel") %>%
      dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)

  # Gravid
    
    # Alpha Diversity
      Gravid_Alpha <- vegan::specnumber(BD_Haiti_Spec_Grav)
        print(Gravid_Alpha)
        print(mean(Gravid_Alpha))
        print(median(Gravid_Alpha))
        
    # Shannon's Diversity Index
      Gravid_Shannon <- vegan::diversity(BD_Haiti_Spec_Grav, index = "shannon")
        print(Gravid_Shannon)
        print(mean(Gravid_Shannon))
        print(median(Gravid_Shannon))
        
    # Simpson's Diversity Index
      Gravid_Simpson <- vegan::diversity(BD_Haiti_Spec_Grav, index = "simpson")
        print(Gravid_Simpson)
        print(mean(Gravid_Simpson))
        print(median(Gravid_Simpson))
        
  # Light
    
    # Alpha Diversity
      Light_Alpha <- vegan::specnumber(BD_Haiti_Spec_Lt)
        print(Light_Alpha)
        print(mean(Light_Alpha))
        print(median(Light_Alpha))
        
    # Shannon's Diversity Index
      Light_Shannon <- vegan::diversity(BD_Haiti_Spec_Lt, index = "shannon")
        print(Light_Shannon)
        print(mean(Light_Shannon))
        print(median(Light_Shannon))
        
    # Simpson's Diversity Index
      Light_Simpson <- vegan::diversity(BD_Haiti_Spec_Lt, index = "simpson")
        print(Light_Simpson)
        print(mean(Light_Simpson))
        print(median(Light_Simpson))
        
  # BG
    
    # Alpha Diversity
      BG_Alpha <- vegan::specnumber(BD_Haiti_Spec_BG)
        print(BG_Alpha)
        print(mean(BG_Alpha))
        print(median(BG_Alpha))
        
    # Shannon's Diversity Index
      BG_Shannon <- vegan::diversity(BD_Haiti_Spec_BG, index = "shannon")
        print(BG_Shannon)
        print(mean(BG_Shannon))
        print(median(BG_Shannon))
        
    # Simpson's Diversity Index
      BG_Simpson <- vegan::diversity(BD_Haiti_Spec_BG, index = "simpson")
        print(BG_Simpson)
        print(mean(BG_Simpson))
        print(median(BG_Simpson))
```

```{r Boxplots of trap biodiversity}

  # Filter out rows with all mosquito counts equal to 0
    BD_Haiti_filtered <- BD_Haiti %>%
      filter(rowSums(dplyr::select(., Quinx, Aeae, Aealb, Aem, Cxn, Psc)) > 0)
  
  # Calculate biodiversity indices and prepare a combined dataset
    trap_types <- c("CDC Gravid", "CDC LT", "BG- Sentinel")
  
  # Initialize a data frame to store results
    biodiversity_data <- data.frame(
      Trap_Type = character(),
      Alpha = numeric(),
      Shannon = numeric(),
      Simpson = numeric(),
      stringsAsFactors = FALSE
    )
  
    for (trap in trap_types) {
      # Filter data by trap type
        current_data <- BD_Haiti_filtered %>%
          filter(Trap_Type == trap) %>%
          dplyr::select(Quinx, Aeae, Aealb, Aem, Cxn, Psc)
        
      # Calculate biodiversity indices
        alpha <- vegan::specnumber(current_data)
        shannon <- vegan::diversity(current_data, index = "shannon")
        simpson <- vegan::diversity(current_data, index = "simpson")
        
      # Append results to the combined dataset
        biodiversity_data <- rbind(biodiversity_data, data.frame(
          Trap_Type = trap,
          Alpha = alpha,
          Shannon = shannon,
          Simpson = simpson
        ))
      }
  
  # Reshape data to long format for ggplot
    biodiversity_long <- biodiversity_data %>%
      pivot_longer(cols = c(Alpha, Shannon, Simpson),
                   names_to = "Metric", 
                   values_to = "Value")
 
  # Boxplots
    boxplot <- ggplot(biodiversity_long, aes(x = Trap_Type, y = Value, fill = Metric)) +
      geom_boxplot(outlier.shape = NA, alpha = 0.3) +
      geom_jitter(width = 0.2, alpha = 0.3, color = "black") +
      facet_wrap(~ Metric, scales = "free_y") +
      scale_fill_manual(values = c("Alpha" = "#6A3467", "Shannon" = "#996B51", "Simpson" = "#D4AF37")) +
      labs(title = "Biodiversity Metrics by Trap Type",
           x = "Trap Type",
           y = "Value",
           fill = "Metric") +
      theme_minimal() +
      theme(axis.text.x = element_text(angle = 45, hjust = 1))
    
    plot(boxplot)
  
  # Save the plot as an SVG file
    output_folder <- "REPLACE WITH YOUR OUTPUT DIRECTORY"
    svg(filename = file.path(output_folder, "Trap_Biodiv.svg"), width = 15, height = 3)
    print(boxplot)
    dev.off()
```

```{r T-tests}

  # Pairwise t-tests for each metric
    t_test_results <- biodiversity_long %>%
      group_by(Metric) %>%
      summarise(
        pairwise_t = list(
          pairwise.t.test(
            x = Value,
            g = Trap_Type,
            p.adjust.method = "bonferroni",
            pool.sd = TRUE
          )
        )
      )
  
  # Extract and display t-test results for each metric
    t_test_alpha <- pairwise.t.test(
      x = biodiversity_long %>% filter(Metric == "Alpha") %>% pull(Value),
      g = biodiversity_long %>% filter(Metric == "Alpha") %>% pull(Trap_Type),
      p.adjust.method = "bonferroni",
      pool.sd = TRUE
    )
    
    t_test_shannon <- pairwise.t.test(
      x = biodiversity_long %>% filter(Metric == "Shannon") %>% pull(Value),
      g = biodiversity_long %>% filter(Metric == "Shannon") %>% pull(Trap_Type),
      p.adjust.method = "bonferroni",
      pool.sd = TRUE
    )
    
    t_test_simpson <- pairwise.t.test(
      x = biodiversity_long %>% filter(Metric == "Simpson") %>% pull(Value),
      g = biodiversity_long %>% filter(Metric == "Simpson") %>% pull(Trap_Type),
      p.adjust.method = "bonferroni",
      pool.sd = TRUE
    )
  
  # Print results
    cat("\n--- Pairwise t-tests for Alpha Diversity ---\n")
    print(t_test_alpha)
    
    cat("\n--- Pairwise t-tests for Shannon Diversity ---\n")
    print(t_test_shannon)
    
    cat("\n--- Pairwise t-tests for Simpson Diversity ---\n")
    print(t_test_simpson)


```

```{r Probabilistic Co-occurence}

  # Load libraries
    library(cooccur)
    library(visNetwork)
  
  # Inspect dataset
    head(BD_Site)
  
  # Subset and reformat BD_Site for cooccurrence
  # Columns 6:11 are species presence-absence data
    Cooc <- as.data.frame(BD_Haiti[, 6:11])  # Select only species data
    rownames(Cooc) <- BD_Haiti$OID_  # Add site names as row names
  
  # Check the structure
    str(Cooc)
  
  # Ensure binary data (presence/absence)
    Cooc[Cooc > 1] <- 1

  # Check the structure
    str(Cooc)
    
  # Transpose dataset to make species rows and sites columns
    Cooc_transposed <- t(Cooc)  # Transpose the matrix

  # Confirm structure
    str(Cooc_transposed)
    
  # Rename rows
    rownames(Cooc_transposed) <- c(
      "Culex quinquefasciatus",
      "Aedes aegypti",
      "Aedes albopictus",
      "Aedes mediovittatus",
      "Culex nigripalpus",
      "Psorophora columbiae"
    )
    
  # Verify the new row names
    rownames(Cooc_transposed)
 
  # Calculate significant pairwise co-occurrences
    co <- cooccur(Cooc_transposed, spp_names = TRUE)
  
  # Extract significant interactions
    significant_co <- as.data.frame(print(co))  # Store significant results
    
  # Create nodes using species names (rows, not columns!)
    nodes <- data.frame(id = 1:nrow(Cooc_transposed),               # Numeric IDs for species
                        label = rownames(Cooc_transposed),          # Species names as labels
                        color = "grey",                          # Node color
                        shadow = TRUE)                              # Add shadow effect    
    
  # Creation of edges for network
    edges <- data.frame(
      from = significant_co$sp1,
      to = significant_co$sp2,
      width = 1,  # Scale edge width inversely with p-value
      color = ifelse(significant_co$p_lt <= 0.05, "#E41A1C",   # Red for negative
                     ifelse(significant_co$p_gt <= 0.05, "#377EB8", "#4DAF4A")) # Blue for positive, Green neutral
      #dashes = ifelse(significant_co$p_lt <= 0.05, TRUE, FALSE)  # Dashed for negative
    )

  # Plot the network using visNetwork
    visNetwork(nodes = nodes, edges = edges) %>%
      visIgraphLayout(layout = "layout_with_kk") %>%  # Kamada-Kawai layout
      visNodes(size = 15) %>%                         # Adjust node size
      visEdges(arrows = "none")                        # No directional arrows
      
```

```{r BG-Sentinel Probabilistic Co-occurence Network}

# Load libraries
library(cooccur)
library(visNetwork)

# Subset BG-Sentinel trap data
BD_BGS <- BD_Haiti %>% filter(Trap_Type == "BG- Sentinel")

# Inspect dataset
head(BD_BGS)

# Subset and reformat BD_BGS for cooccurrence
# Columns 6:11 are species presence-absence data (Quinx, Aeae, Aealb, Aem, Cxn, Psc)
Cooc <- as.data.frame(BD_BGS[, 6:11])  # Select only species data
rownames(Cooc) <- BD_BGS$OID_  # Add site IDs as row names

# Check the structure
str(Cooc)

# Ensure binary data (presence/absence)
Cooc[Cooc > 1] <- 1

# Check the structure after conversion to binary
str(Cooc)
    
# Transpose dataset to make species rows and sites columns
Cooc_transposed <- t(Cooc)  # Transpose the matrix

# Confirm structure of transposed data
str(Cooc_transposed)
    
# Rename rows with full species names
rownames(Cooc_transposed) <- c(
  "Culex quinquefasciatus",
  "Aedes aegypti",
  "Aedes albopictus",
  "Aedes mediovittatus",
  "Culex nigripalpus",
  "Psorophora columbiae"
)
    
# Verify the new row names
rownames(Cooc_transposed)
 
# Calculate significant pairwise co-occurrences
co <- cooccur(Cooc_transposed, spp_names = TRUE)
  
# Extract significant interactions
significant_co <- as.data.frame(print(co))  # Store significant results
    
# Create nodes using species names
nodes <- data.frame(id = 1:nrow(Cooc_transposed),        # Numeric IDs for species
                    label = rownames(Cooc_transposed),    # Species names as labels
                    color = "grey",                       # Node color
                    shadow = TRUE)                        # Add shadow effect    
    
# Creation of edges for network
edges <- data.frame(
  from = significant_co$sp1,
  to = significant_co$sp2,
  width = 1,  # Scale edge width inversely with p-value
  color = ifelse(significant_co$p_lt <= 0.05, "#E41A1C",        # Red for negative associations
                 ifelse(significant_co$p_gt <= 0.05, "#377EB8", # Blue for positive associations 
                        "#4DAF4A"))                             # Green for neutral
)

# Plot the network using visNetwork
visNetwork(nodes = nodes, edges = edges) %>%
  visIgraphLayout(layout = "layout_with_kk") %>%  # Kamada-Kawai layout
  visNodes(size = 15) %>%                         # Adjust node size
  visEdges(arrows = "none")     

```

```{r CDC Gravid Probabilistic Co-occurence Network}

# Load libraries
library(cooccur)
library(visNetwork)

# First create a subset of the data where Trap_Type = "CDC Gravid"
BD_CDCG <- subset(BD_Haiti, Trap_Type == "CDC Gravid")

# Inspect the CDC Gravid dataset
head(BD_CDCG)

# Check how many observations we have
nrow(BD_CDCG)

# Subset and reformat BD_CDCG for cooccurrence
# Columns 6:11 are species presence-absence data (Quinx, Aeae, Aealb, Aem, Cxn, Psc)
Cooc <- as.data.frame(BD_CDCG[, 6:11])  # Select only species data
rownames(Cooc) <- BD_CDCG$OID_  # Add site IDs as row names

# Check the structure
str(Cooc)

# Ensure binary data (presence/absence)
Cooc[Cooc > 1] <- 1

# Check the structure after conversion to binary
str(Cooc)
    
# Transpose dataset to make species rows and sites columns
Cooc_transposed <- t(Cooc)  # Transpose the matrix

# Confirm structure of transposed data
str(Cooc_transposed)
    
# Rename rows with full species names
rownames(Cooc_transposed) <- c(
  "Culex quinquefasciatus",
  "Aedes aegypti",
  "Aedes albopictus",
  "Aedes mediovittatus",
  "Culex nigripalpus",
  "Psorophora columbiae"
)
    
# Verify the new row names
rownames(Cooc_transposed)
 
# Calculate significant pairwise co-occurrences
co <- cooccur(Cooc_transposed, spp_names = TRUE)
  
# Extract significant interactions
significant_co <- as.data.frame(print(co))  # Store significant results
    
# Create nodes using species names
nodes <- data.frame(id = 1:nrow(Cooc_transposed),        # Numeric IDs for species
                    label = rownames(Cooc_transposed),    # Species names as labels
                    color = "grey",                       # Node color
                    shadow = TRUE)                        # Add shadow effect    
    
# Creation of edges for network
edges <- data.frame(
  from = significant_co$sp1,
  to = significant_co$sp2,
  width = 1,  # Scale edge width inversely with p-value
  color = ifelse(significant_co$p_lt <= 0.05, "#E41A1C",        # Red for negative associations
                 ifelse(significant_co$p_gt <= 0.05, "#377EB8", # Blue for positive associations 
                        "#4DAF4A"))                             # Green for neutral
)

# Plot the network using visNetwork
visNetwork(nodes = nodes, edges = edges) %>%
  visIgraphLayout(layout = "layout_with_kk") %>%  # Kamada-Kawai layout
  visNodes(size = 15) %>%                         # Adjust node size
  visEdges(arrows = "none")                       # No directional arrows


```

```{r CDC Light Probabilistic Co-occurence Network}

# Load libraries
library(cooccur)
library(visNetwork)

# Create a subset of the data where Trap_Type = "CDC LT"
BD_CDCLT <- subset(BD_Haiti, Trap_Type == "CDC LT")

# Inspect the CDC Light Trap dataset
head(BD_CDCLT)

# Check how many observations we have
nrow(BD_CDCLT)

# Subset and reformat BD_CDCLT for cooccurrence
# Columns 6:11 are species presence-absence data (Quinx, Aeae, Aealb, Aem, Cxn, Psc)
Cooc <- as.data.frame(BD_CDCLT[, 6:11])  # Select only species data
rownames(Cooc) <- BD_CDCLT$OID_  # Add site IDs as row names

# Check the structure
str(Cooc)

# Ensure binary data (presence/absence)
Cooc[Cooc > 1] <- 1

# Check the structure after conversion to binary
str(Cooc)
    
# Transpose dataset to make species rows and sites columns
Cooc_transposed <- t(Cooc)  # Transpose the matrix

# Confirm structure of transposed data
str(Cooc_transposed)
    
# Rename rows with full species names
rownames(Cooc_transposed) <- c(
  "Culex quinquefasciatus",
  "Aedes aegypti",
  "Aedes albopictus",
  "Aedes mediovittatus",
  "Culex nigripalpus",
  "Psorophora columbiae"
)
    
# Verify the new row names
rownames(Cooc_transposed)
 
# Calculate significant pairwise co-occurrences
co <- cooccur(Cooc_transposed, spp_names = TRUE)
  
# Extract significant interactions
significant_co <- as.data.frame(print(co))  # Store significant results
    
# Create nodes using species names
nodes <- data.frame(id = 1:nrow(Cooc_transposed),        # Numeric IDs for species
                    label = rownames(Cooc_transposed),    # Species names as labels
                    color = "grey",                       # Node color
                    shadow = TRUE)                        # Add shadow effect    
    
# Creation of edges for network
edges <- data.frame(
  from = significant_co$sp1,
  to = significant_co$sp2,
  width = 1,  # Scale edge width inversely with p-value
  color = ifelse(significant_co$p_lt <= 0.05, "#E41A1C",        # Red for negative associations
                 ifelse(significant_co$p_gt <= 0.05, "#377EB8", # Blue for positive associations 
                        "#4DAF4A"))                             # Green for neutral
)

# Plot the network using visNetwork
visNetwork(nodes = nodes, edges = edges) %>%
  visIgraphLayout(layout = "layout_with_kk") %>%  # Kamada-Kawai layout
  visNodes(size = 15) %>%                         # Adjust node size
  visEdges(arrows = "none")                       # No directional arrows


```

```{r Coccurence network using igraph}

  # Load libraries
    library(igraph)

  # Set output directory and filename
    output_file <- "REPLACE WITH YOUR OUTPUT DIRECTORY"

  # Create an igraph graph object
    graph <- graph_from_data_frame(d = edges, vertices = nodes, directed = FALSE)
  
  # Set node labels to match the species names
    V(graph)$label <- nodes$label
  
  # Assign node colors
    V(graph)$color <- nodes$color
  
  # Assign edge colors and widths
    E(graph)$color <- edges$color
    E(graph)$width <- edges$width
  
  # Save the plot as a .svg file
    svg(output_file, width = 10, height = 10)  # SVG dimensions in inches
  
  # Plot the graph
    plot(
      graph,
      layout = layout_with_kk,  # Kamada-Kawai layout
      vertex.size = 15,         # Node size
      vertex.label.cex = 0.8,   # Label size
      vertex.label.color = "black",  # Label color
      edge.width = E(graph)$width,   # Edge width
      edge.color = E(graph)$color    # Edge color
    )
  
  # Close the SVG device
    dev.off()
```

```{r matrix using crossprod}
 
  # convert species per movement to a co-occurrence matrix
    spec <- as.matrix(Cooc)
    out <- crossprod(spec)
  
  # change diag to 0 because we dont care if same species co
    diag(out) <- 0
    out
 
```
 
```{r networks}
 
  install.packages("igraph")
  library("igraph")
   
  g <- graph_from_adjacency_matrix(out, weighted = "weight")
  plot(g, layout= layout_with_fr(g), vertex.size=8, vertex.color = rainbow(10, .8, .8, alpha= .8),
    vertex.label.color = "black", vertex.label.cex = 0.4, vertex.label.degree = -pi/4,
    edge.arrow.size = 0.01, edge.arrow.width = 0.4, edge.color = "black", edge.width = E(g)$weight/1000)
 
 
  write.csv(out, "REPLACE WITH YOUR OUTPUT DIRECTORY")
 
```

```{r Downloading temporally explicit weather data using get_power from nasapower package}

  library(nasapower) # get_power() for daily temp, humidity & precip
  
  # Request data for Haiti for 2018-2019
    haiti_weather <- get_power(
      community = "AG",                         # Use 'AG' for agriculture-related parameters
      pars = c("RH2M", "PS", "TS", "TS_RANGE", "TS_MIN", "TS_MAX", "PRECTOTCORR", "WS2M"), 
      # Relative humidity, Atmos. pressure, mean temp, temp range, min temp, max temp, precip & wind speed at 2m above earth's surface
      temporal_api = "DAILY",                   # Retrieve daily data
      lonlat = c(-72.5, 18.5),                  # Longitude and latitude for our location in Haiti
      dates = c("2018-01-01", "2019-12-31"),    # Start and end dates
      time_standard = "LST"                     # Local Solar Time
    )
  
  # View the resulting data
    print(haiti_weather)

```

```{r Downloading spatially modelled & explicit but temporally weak worldclim data}

  library(geodata) # various functions for pulling covariate data
    
  # Define the variables and corresponding paths
    vars <- c("tmin", "tmax", "tavg", "prec", "srad", "wind")
    paths <- paste0(
      "REPLACE WITH YOUR OUTPUT DIRECTORY",
      vars
    )

  # Fetch data for each variable and assign to individual objects
    walk2(
      vars, paths,
      ~ assign(
        x = paste0("Haiti_", .x),  # Name of the object (e.g., Haiti_tmin)
        value = worldclim_tile(
          lon = -74.5,
          lat = 17.5,
          res = 0.5,
          var = .x,
          path = .y
        ),
        envir = .GlobalEnv          # Assign to the global environment
      )
    ) 
  
  # Download vapr globally as function for tile and country don't work?  
      Haiti_vapr <- worldclim_global(
        res = "0.5",
        var = "vapr", 
        path = "REPLACE WITH YOUR OUTPUT DIRECTORY"
      )      
      
  # List of all raster objects
    raster_vars <- c("Haiti_tmin", "Haiti_tmax", "Haiti_tavg", "Haiti_prec", "Haiti_srad", "Haiti_wind", "Haiti_vapr")
  
  # Rename layers in each raster object
    for (var in raster_vars) {
      # Retrieve the raster object
        raster_obj <- get(var)
      
      # Create meaningful names for layers (e.g., Jan, Feb, Mar...)
        month_names <- c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
        layer_names <- paste0(sub("Haiti_", "", var), "_", month_names)  # Strip "Haiti_" prefix for cleaner names
        
      # Rename layers explicitly
        names(raster_obj) <- layer_names
      
      # Reassign the renamed raster back to the global environment
        assign(var, raster_obj, envir = .GlobalEnv)
    }
  
  Haiti_tmin_stack <- raster::stack(Haiti_tmin)
  Haiti_tmax_stack <- raster::stack(Haiti_tmax)
  Haiti_tavg_stack <- raster::stack(Haiti_tavg)
  Haiti_prec_stack <- raster::stack(Haiti_prec)
  Haiti_srad_stack <- raster::stack(Haiti_srad)
  Haiti_wind_stack <- raster::stack(Haiti_wind)
  Haiti_vapr_stack <- raster::stack(Haiti_vapr)   
    
    
```

```{r Download ESA data}

  # Data downloaded for Haiti using WorldCover V2 2021
  # https://viewer.esa-worldcover.org/worldcover/?language=en&bbox=-79.2240964367496,7.145097163076159,-69.50179751649752,22.404614474028136&overlay=false&bgLayer=OSM&date=2024-12-02&layer=WORLDCOVER_2021_MAP

  library(raster)
  
  # Define the folder path
    folder_path <- "REPLACE WITH YOUR OUTPUT DIRECTORY"
  
  # Load the two rasters
    WC_Map_N18W075 <- rast(file.path(folder_path, "ESA_WorldCover_10m_2021_v200_N18W075_Map.tif"))
    WC_Map_N18W072 <- rast(file.path(folder_path, "ESA_WorldCover_10m_2021_v200_N18W072_Map.tif"))
  
  # Combine the two rasters into one
    Haiti_WorldCover <- terra::merge(WC_Map_N18W075, WC_Map_N18W072)
    
    Haiti_WorldCover <- raster(Haiti_WorldCover)
  
  # Check the merged raster
    print(Haiti_WorldCover)
  
  # Rename the layers of the merged raster
    names(Haiti_WorldCover) <- paste0("WorldCover")
  
  # Check the renamed raster
    print(names(Haiti_WorldCover))
  
  # Optional: Plot the renamed raster
    plot(Haiti_WorldCover, main = "WorldCover Map of Haiti")
    Haiti_WCfactor <- as.factor(Haiti_WorldCover)

    
      
```

```{r Population density data}
  
  PopDens <- geodata::population(
    year = 2020,
    res = 0.5,
    path = "REPLACE WITH YOUR OUTPUT DIRECTORY"
  )

  names(PopDens) <- paste0("PopDens")
  PopDens <- raster(PopDens)
  plot(PopDens)
  

```

```{r Human footprint data}

  HuFootprint <- geodata::footprint(
    year = 2009,
    path = "REPLACE WITH YOUR OUTPUT DIRECTORY"
  )
  names(HuFootprint) <- paste0("HumanFootprint")
  HuFootprint <- raster(HuFootprint)  
  plot(HuFootprint)

```

```{r Livestock Data}

  #Gridded livestock data pulled from : https://www.nature.com/articles/sdata2018227#ref-CR36

  # Define the folder path
    folder_path <- "REPLACE WITH YOUR OUTPUT DIRECTORY"
  
  # Load the .tif files into separate variables
    Cattle <- raster(file.path(folder_path, "Cattle.tif"))
    Chicken <- raster(file.path(folder_path, "Chicken.tif"))
    Duck <- raster(file.path(folder_path, "Duck.tif"))
    Goat <- raster(file.path(folder_path, "Goat.tif"))
    Horse <- raster(file.path(folder_path, "Horse.tif"))
    Pig <- raster(file.path(folder_path, "Pig.tif"))
    Sheep <- raster(file.path(folder_path, "Sheep.tif"))
  
    names(Cattle) <- "Cattle"
    names(Chicken) <- "Chicken"
    names(Duck) <- "Duck"
    names(Goat) <- "Goat"
    names(Horse) <- "Horse"
    names(Pig) <- "Pig"
    names(Sheep) <- "Sheep"
    
  # Optional: Plot one or more rasters to confirm
    plot(Cattle, main = "Cattle Distribution")
    plot(Chicken, main = "Chicken Distribution")

 
```

```{r modisfast NDVI}
  
  library(modisfast) # Used to download modis data

  # Login to EOSDIS
    mf_login(credentials = c("REPLACE W/ YOUR USERNAME", "REPLACE W/ YOUR PASSWORD"))

  # Define parameters of interest
    collection <- "MOD13A3.061"  # MODIS NDVI (Monthly, 1-km resolution)
    variables <- c("_1_km_monthly_NDVI", "_1_km_monthly_EVI")  # NDVI and optionally EVI
    time_range <- as.Date(c("2018-01-01", "2019-12-31"))  # Date range
  
  # Define the expanded extent for Haiti (slightly beyond its borders)
    roi <- sf::st_as_sf(
      data.frame(
        id = "haiti_roi",
        geom = "POLYGON ((-74.75 17.75, -71.25 17.75, -71.25 20.25, -74.75 20.25, -74.75 17.75))"
      ),
      wkt = "geom", crs = 4326
    )

  # Get URLs for data download
    urls_modis <- mf_get_url(
      collection = collection,
      variables = variables,
      roi = roi,
      time_range = time_range
    )

  # Download the data
    output_folder <- "REPLACE WITH YOUR OUTPUT DIRECTORY"

    res_dl <- mf_download_data(
      df_to_dl = urls_modis,
      path = output_folder,
      parallel = TRUE,  # Enable parallel downloading
      num_workers = parallel::detectCores() - 1,  # Use available cores
    )

  # Import the downloaded data
    modis_ndvi <- mf_import_data(dirname(res_dl$destfile[1]), collection = collection)

  # Extract the time range (dates corresponding to each layer)
    time_range <- seq.Date(as.Date("2018-01-01"), as.Date("2019-12-01"), by = "month")
  
  # Generate names for NDVI and EVI layers
    ndvi_names <- paste0("NDVI_", format(time_range, "%Y_%b"))
    evi_names <- paste0("EVI_", format(time_range, "%Y_%b"))
  
  # Combine the names
    layer_names <- c(evi_names, ndvi_names)
  
  # Assign the new names to the layers in modis_ndvi
    names(modis_ndvi) <- layer_names
    modis_ndvi_evi <- raster::stack(modis_ndvi)
    
  # Visualize the data
    terra::plot(modis_ndvi$EVI_2018_Jan)

```

```{r WorldPop Data}

  # wpgpDownloadR
    install.packages("devtools")
    devtools::install_github("wpgp/wpgpDownloadR")
    library(wpgpDownloadR) # Downloading WorldPop Data

  # Set the destination directory
    WP_directory <- "REPLACE WITH YOUR OUTPUT DIRECTORY" 
    
  # Download and import SRTM Slope 2000
    Slope <- raster(wpgpGetCountryDataset(ISO3 = "HTI", covariate = "srtm_slope_100m", destDir = WP_directory))
  
  # Download and import Elevation
    Elevation <- raster(wpgpGetCountryDataset(ISO3 = "HTI", covariate = "srtm_topo_100m", destDir = WP_directory))
  
  # Download and import NightLights 2011
    NightLights2011 <- raster(wpgpGetCountryDataset(ISO3 = "HTI", covariate = "dmsp_100m_2011", destDir = WP_directory))
  
  # Download and import Distance to OSM Major Roads 2016
    DstRd <- raster(wpgpGetCountryDataset(ISO3 = "HTI", covariate = "osm_dst_road_100m_2016", destDir = WP_directory))

  # Rename layers for each raster
    names(Slope) <- "Slope"
    names(Elevation) <- "Elevation"
    names(NightLights2011) <- "NightLights2011"
    names(DstRd) <- "DstRd"
    
  # Plots
    plot(Slope)
    plot(Elevation)
    plot(NightLights2011)
    plot(DstRd)
   
```

```{r Reprojecting and stacking}

  # Reproject the shapefile to match the CRS of the rasters (WGS84)
    haiti_sf_reproj <- spTransform(as(haiti_country_sf, "Spatial"), crs(Haiti_WorldCover))
  
    # Crop and mask Haiti_WorldCover
      Haiti_WorldCover_shaped <- mask(crop(Haiti_WorldCover, haiti_sf_reproj), haiti_sf_reproj)
      
    # Crop and mask PopDens
      PopDens_shaped <- mask(crop(PopDens, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask Elevation
      Elevation_shaped <- mask(crop(Elevation, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask NightLights2011
      NightLights2011_shaped <- mask(crop(NightLights2011, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask DstRd
      DstRd_shaped <- mask(crop(DstRd, haiti_sf_reproj), haiti_sf_reproj)
      
    # Crop and mask Human Footprint
      HuFootprint_shaped <- mask(crop(HuFootprint, haiti_sf_reproj), haiti_sf_reproj)    
      
    # Crop and mask Haiti_tmin_stack
      Haiti_tmin_shaped <- mask(crop(Haiti_tmin_stack, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask Haiti_tmax_stack
      Haiti_tmax_shaped <- mask(crop(Haiti_tmax_stack, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask Haiti_tavg_stack
      Haiti_tavg_shaped <- mask(crop(Haiti_tavg_stack, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask Haiti_prec_stack
      Haiti_prec_shaped <- mask(crop(Haiti_prec_stack, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask Haiti_srad_stack
      Haiti_srad_shaped <- mask(crop(Haiti_srad_stack, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask Haiti_wind_stack
      Haiti_wind_shaped <- mask(crop(Haiti_wind_stack, haiti_sf_reproj), haiti_sf_reproj)
    
    # Crop and mask Haiti_vapr_stack
      Haiti_vapr_shaped <- mask(crop(Haiti_vapr_stack, haiti_sf_reproj), haiti_sf_reproj)

    # Crop and mask Haiti_vapr_stack
      ndvi_evi <- raster::projectRaster(modis_ndvi_evi, Haiti_vapr_shaped, method = "bilinear")
      Haiti_ndvi_evi_shaped <- mask(crop(ndvi_evi, haiti_sf_reproj), haiti_sf_reproj)            
      
      
    # Crop and mask livestock
      # Crop and mask Cattle
        Cattle_shaped <- mask(crop(Cattle, haiti_sf_reproj), haiti_sf_reproj)
      
      # Crop and mask Chicken
        Chicken_shaped <- mask(crop(Chicken, haiti_sf_reproj), haiti_sf_reproj)
      
      # Crop and mask Duck
        Duck_shaped <- mask(crop(Duck, haiti_sf_reproj), haiti_sf_reproj)
      
      # Crop and mask Goat
        Goat_shaped <- mask(crop(Goat, haiti_sf_reproj), haiti_sf_reproj)
      
      # Crop and mask Horse
        Horse_shaped <- mask(crop(Horse, haiti_sf_reproj), haiti_sf_reproj)

      # Crop and mask Pig
        Pig_shaped <- mask(crop(Pig, haiti_sf_reproj), haiti_sf_reproj)
      
      # Crop and mask Sheep
        Sheep_shaped <- mask(crop(Sheep, haiti_sf_reproj), haiti_sf_reproj)

        
      
    # Resample to match extents
      Haiti_Elevation <- resample(Elevation_shaped, Cattle_shaped, method = "bilinear")
      Haiti_PopDens <- resample(PopDens_shaped, Cattle_shaped, method = "bilinear")
      Haiti_WC <- resample(Haiti_WorldCover_shaped, Cattle_shaped, method = "bilinear")
      Haiti_NightLights <- resample(NightLights2011_shaped, Cattle_shaped, method = "bilinear")
      Haiti_DstRd <- resample(DstRd_shaped, Cattle_shaped, method = "bilinear")
      Haiti_HuFoot <- resample(HuFootprint_shaped, Cattle_shaped, method = "bilinear")
      Haiti_Cattle <- Cattle_shaped
      

    
  # Stack rasters    
    SpatialStack <- stack(Haiti_WC, Haiti_PopDens, Haiti_Elevation, Haiti_NightLights, Haiti_DstRd, Haiti_HuFoot, Haiti_Cattle)
    

```

```{r EVI/NDVI Renaming}

  # Extract the names of layers in the brick
    layer_names <- names(Haiti_ndvi_evi_shaped)
  
  # Separate NDVI and EVI layer names
    evi_layer_names <- grep("^EVI_", layer_names, value = TRUE)
    ndvi_layer_names <- gsub("EVI_", "NDVI_", evi_layer_names) # Assuming NDVI names follow the same pattern as EVI
  
  # Create EVI Stack
    EVI_rasters <- stack(lapply(evi_layer_names, function(name) Haiti_ndvi_evi_shaped[[name]]))
  
  # Create NDVI Stack
    NDVI_rasters <- stack(lapply(ndvi_layer_names, function(name) Haiti_ndvi_evi_shaped[[name]]))
  
  # Rename layers in the stacks to match the naming scheme
    names(EVI_rasters) <- gsub("EVI_", "EVI_", evi_layer_names)
    names(NDVI_rasters) <- gsub("EVI_", "NDVI_", ndvi_layer_names)
  
  # Print the stacks to confirm
    print(EVI_rasters)
    print(NDVI_rasters)
  
  # Example: Check layer names
    names(EVI_rasters)
    names(NDVI_rasters)
```

```{r Function to create a monthly lag for raster stacks}

  # Function to create a monthly lag for raster stacks
    create_monthly_lag <- function(raster_stack, var_name) {
      # Get the names of the layers
        layer_names <- names(raster_stack)
    
    # Create the lagged names
      lagged_names <- paste0(var_name, "_mlag_", month.abb)
    
    # Create the lagged stack by reordering the layers
      lagged_stack <- raster_stack[[c(12, 1:11)]]
    
    # Assign the new lagged names to the correctly reordered stack
      names(lagged_stack) <- lagged_names
    
      return(lagged_stack)
  }
  
  # Apply the function to each shaped stack
    Haiti_tmin_mlag <- create_monthly_lag(Haiti_tmin_shaped, "tmin")
    Haiti_tmax_mlag <- create_monthly_lag(Haiti_tmax_shaped, "tmax")
    Haiti_tavg_mlag <- create_monthly_lag(Haiti_tavg_shaped, "tavg")
    Haiti_prec_mlag <- create_monthly_lag(Haiti_prec_shaped, "prec")
    Haiti_srad_mlag <- create_monthly_lag(Haiti_srad_shaped, "srad")
    Haiti_wind_mlag <- create_monthly_lag(Haiti_wind_shaped, "wind")
    Haiti_vapr_mlag <- create_monthly_lag(Haiti_vapr_shaped, "vapr")
```

```{r monthly lag for NDVI/EVI raster stacks}

    # Function to create a monthly lag for NDVI/EVI raster stacks
    create_ndvi_evi_lag_corrected <- function(raster_stack, var_name) {
      # Get the names of the layers
      layer_names <- names(raster_stack)
      
      # Parse the years and months from layer names
      parsed_years <- as.numeric(sapply(strsplit(layer_names, "_"), function(x) x[2]))  # Extract the year
      parsed_months <- sapply(strsplit(layer_names, "_"), function(x) x[3])  # Extract the month abbreviation
      
      # Create a new list for lagged layers
      lagged_layers <- list()
      
      for (i in seq_along(layer_names)) {
        # Determine the lagged year and month
        current_year <- parsed_years[i]
        current_month <- parsed_months[i]
        
        if (current_month == "Jan") {
          lagged_year <- current_year - 1
          lagged_month <- "Dec"
        } else {
          lagged_year <- current_year
          lagged_month <- month.abb[match(current_month, month.abb) - 1]
        }
        
        # Construct the lagged layer name
        lagged_layer_name <- paste0(var_name, "_", lagged_year, "_", lagged_month)
        
        if (lagged_layer_name %in% layer_names) {
          # Add the corresponding raster layer to the lagged list
          lagged_layers[[i]] <- raster_stack[[lagged_layer_name]]
        } else {
          # If no lagged layer exists, assign NA
          lagged_layers[[i]] <- raster_stack[[1]] * NA
        }
      }
      
      # Combine the lagged layers into a raster stack
      lagged_stack <- stack(lagged_layers)
      
      # Assign new names to the lagged stack
      lagged_names <- paste0(var_name, "_mlag_", parsed_months, "_", parsed_years)
      names(lagged_stack) <- lagged_names
      
      return(lagged_stack)
    }
  
  # Apply the corrected function to NDVI and EVI stacks
    NDVI_mlag <- create_ndvi_evi_lag_corrected(NDVI_rasters, "NDVI")
    EVI_mlag <- create_ndvi_evi_lag_corrected(EVI_rasters, "EVI")
```

```{r Adding in temporal covariates to the BD dataset}

  # Ensure BD_Haiti_sf is an sf object
    BD_Haiti_sf <- BD_Haiti %>%
      st_as_sf(coords = c("Longitude", "Latitude"), crs = 4326)

    # Helper function to extract raster values for variables with capitalized layer names
    extract_monthly_raster_values_to_dataset <- function(year_month, raster_stack, raster_type, buffer_radius = 1000) {
      # Subset the dataset for the specific YearMonth
      dataset <- BD_Haiti_sf %>% filter(YearMonth == year_month)
      
      # Extract the month index (1 for Jan, 2 for Feb, etc.)
      month_index <- as.numeric(format(as.Date(paste0(year_month, "-01")), "%m"))
      
      # Retrieve the raster layer name using capitalized month abbreviation
      month_abbr <- month.abb[month_index]  # Capitalized month abbreviation
      layer_name <- paste0(raster_type, "_", month_abbr)
      
      # Ensure the layer exists in the raster stack
      if (!(layer_name %in% names(raster_stack))) {
        stop(paste("Layer", layer_name, "not found in the raster stack."))
      }
      
      # Extract raster values with buffer
      coords <- st_coordinates(dataset)
      dataset[[raster_type]] <- raster::extract(raster_stack[[layer_name]], coords, buffer = buffer_radius, fun = mean)
      
      return(dataset)
    }
    
    # Raster stacks and variable names
    raster_stacks <- list(
      Haiti_tmin_shaped = "tmin",
      Haiti_tmax_shaped = "tmax",
      Haiti_tavg_shaped = "tavg",
      Haiti_prec_shaped = "prec",
      Haiti_srad_shaped = "srad",
      Haiti_wind_shaped = "wind",
      Haiti_vapr_shaped = "vapr"
    )
    
    # List of YearMonths
    year_months <- unique(BD_Haiti_sf$YearMonth)
    
    # Extract values for each variable and combine into a single dataset
    BD_Additional_Vars <- do.call(rbind, lapply(year_months, function(year_month) {
      # Initialize dataset for the current YearMonth
      combined_data <- BD_Haiti_sf %>% filter(YearMonth == year_month)
      
      # Loop through each raster stack and append values
      for (stack_name in names(raster_stacks)) {
        raster_stack <- get(stack_name)  # Retrieve the raster stack
        raster_type <- raster_stacks[[stack_name]]  # Variable name
        extracted_data <- extract_monthly_raster_values_to_dataset(year_month, raster_stack, raster_type)
        
        # Append the extracted variable to the dataset
        combined_data[[raster_type]] <- extracted_data[[raster_type]]
      }
      
      return(combined_data)
    }))
  
```

```{r Adding in static covariates to the BD dataset}
# Helper function to extract static raster values
extract_static_raster_values <- function(dataset, raster_stack, variable_name, buffer_radius = 1000) {
  coords <- st_coordinates(dataset)  # Extract coordinates from the dataset
  dataset[[variable_name]] <- raster::extract(raster_stack, coords, buffer = buffer_radius, fun = mean)
  return(dataset)
}

# Static raster variables and their names
static_raster_vars <- list(
  Cattle_shaped = "Cattle",
  Chicken_shaped = "Chicken",
  Duck_shaped = "Duck",
  Goat_shaped = "Goat",
  Horse_shaped = "Horse",
  Pig_shaped = "Pig",
  Sheep_shaped = "Sheep",
  Haiti_WorldCover_shaped = "WorldCover",
  PopDens_shaped = "PopDens",
  Elevation_shaped = "Elevation",
  NightLights2011_shaped = "NightLights",
  DstRd_shaped = "DstRd",
  HuFootprint_shaped = "HumanFootprint"
)

# Start with the previously created BD_Additional_Vars dataset
BD_Full_Dataset <- BD_Additional_Vars

# Add static variables to the dataset
for (stack_name in names(static_raster_vars)) {
  raster_stack <- get(stack_name)  # Retrieve the raster stack
  variable_name <- static_raster_vars[[stack_name]]  # Variable name
  BD_Full_Dataset <- extract_static_raster_values(BD_Full_Dataset, raster_stack, variable_name)
}


```

```{r Adding in NDVI to the BD data}

  # Helper function to extract NDVI/EVI for a specific year-month
    extract_raster_values <- function(year_month, raster_stack, raster_type, buffer_radius = 1000) {
      # Subset the dataset for the specific YearMonth
        dataset <- BD_Haiti_sf %>% filter(YearMonth == year_month)
      
      # Extract the year and month
        year <- as.numeric(substr(year_month, 1, 4))
        month <- substr(year_month, 6, 7)  # Two-digit format
        
      # Convert the month to three-letter abbreviation
        month_abbr <- month.abb[as.numeric(month)]
      
      # Construct the raster layer name
        layer_name <- paste0(raster_type, "_", year, "_", month_abbr)
      
      # Ensure the layer exists
        if (!(layer_name %in% names(raster_stack))) {
          stop(paste("Layer", layer_name, "not found in the raster stack."))
        }
        
      # Extract raster values with buffer
        coords <- st_coordinates(dataset)
        dataset[[raster_type]] <- raster::extract(raster_stack[[layer_name]], coords, buffer = buffer_radius, fun = mean)
        
        return(dataset)
      }
    
  # List of YearMonths
    year_months <- unique(BD_Haiti_sf$YearMonth)
  
  # Extract NDVI and EVI values for each YearMonth and combine the results
    BD_NDVI_EVI <- do.call(rbind, lapply(year_months, function(year_month) {
      ndvi_data <- extract_raster_values(year_month, NDVI_rasters, "NDVI")
      #evi_data <- extract_raster_values(year_month, EVI_rasters, "EVI")
    
    # Combine NDVI and EVI data
      #ndvi_data$EVI <- evi_data$EVI
      return(ndvi_data)
  }))
  

```

```{r Adding in lagged vars to dataset}

  # Helper function to append lagged NDVI/EVI values for a specific year-month
  append_lagged_ndvi_evi_values <- function(dataset, year_month, raster_stack, raster_type, buffer_radius = 1000) {
    # Subset the dataset for the specific YearMonth
    year_dataset <- dataset %>% filter(YearMonth == year_month)
    
    # Extract the year and month
    year <- as.numeric(substr(year_month, 1, 4))
    month <- substr(year_month, 6, 7)  # Two-digit format
    
    # Convert the month to three-letter abbreviation
    month_abbr <- month.abb[as.numeric(month)]
    
    # Construct the lagged raster layer name
    lagged_layer_name <- paste0(raster_type, "_mlag_", month_abbr, "_", year)
    
    # Ensure the layer exists
    if (!(lagged_layer_name %in% names(raster_stack))) {
      stop(paste("Layer", lagged_layer_name, "not found in the raster stack."))
    }
    
    # Extract raster values with buffer
    coords <- st_coordinates(year_dataset)
    year_dataset[[paste0(raster_type, "_mlag")]] <- raster::extract(raster_stack[[lagged_layer_name]], coords, buffer = buffer_radius, fun = mean)
    
    return(year_dataset)
  }
  
  # List of YearMonths
  year_months <- unique(BD_NDVI_EVI$YearMonth)
  
  # Append lagged NDVI values
  BD_NDVI_EVI_Final <- do.call(rbind, lapply(year_months, function(year_month) {
    updated_dataset <- BD_NDVI_EVI %>% filter(YearMonth == year_month)
    
    # Add lagged NDVI values
    lagged_ndvi <- append_lagged_ndvi_evi_values(updated_dataset, year_month, NDVI_mlag, "NDVI")
    
    # Add lagged EVI values
    #lagged_ndvi_evi <- append_lagged_ndvi_evi_values(lagged_ndvi, year_month, EVI_mlag, "EVI")
    
    return(lagged_ndvi)
  }))
  
  # View the final dataset
  print(head(BD_NDVI_EVI_Final))
  
  # Helper function to extract lagged raster values for variables
  extract_lagged_raster_values_to_dataset <- function(year_month, raster_stack, raster_type, buffer_radius = 1000) {
    # Subset the dataset for the specific YearMonth
    dataset <- BD_Haiti_sf %>% filter(YearMonth == year_month)
    
    # Extract the month index (1 for Jan, 2 for Feb, etc.)
    month_index <- as.numeric(format(as.Date(paste0(year_month, "-01")), "%m"))
    
    # Retrieve the raster layer name for lagged variables using capitalized month abbreviation
    month_abbr <- month.abb[month_index]  # Capitalized month abbreviation
    layer_name <- paste0(raster_type, "_mlag_", month_abbr)
    
    # Ensure the layer exists in the raster stack
    if (!(layer_name %in% names(raster_stack))) {
      stop(paste("Layer", layer_name, "not found in the raster stack."))
    }
    
    # Extract raster values with buffer
    coords <- st_coordinates(dataset)
    dataset[[paste0(raster_type, "_mlag")]] <- raster::extract(raster_stack[[layer_name]], coords, buffer = buffer_radius, fun = mean)
    
    return(dataset)
  }
  
  # Raster stacks and variable names for lagged variables
  lagged_raster_stacks <- list(
    Haiti_tmin_mlag = "tmin",
    Haiti_tmax_mlag = "tmax",
    Haiti_tavg_mlag = "tavg",
    Haiti_prec_mlag = "prec",
    Haiti_srad_mlag = "srad",
    Haiti_wind_mlag = "wind",
    Haiti_vapr_mlag = "vapr"
  )
  
  # Extract lagged values for each variable and combine into a single dataset
  BD_Lagged_Vars <- do.call(rbind, lapply(year_months, function(year_month) {
    # Initialize dataset for the current YearMonth
    combined_data <- BD_NDVI_EVI_Final %>% filter(YearMonth == year_month)
    
    # Loop through each lagged raster stack and append values
    for (stack_name in names(lagged_raster_stacks)) {
      raster_stack <- get(stack_name)  # Retrieve the lagged raster stack
      raster_type <- lagged_raster_stacks[[stack_name]]  # Variable name
      extracted_data <- extract_lagged_raster_values_to_dataset(year_month, raster_stack, raster_type)
      
      # Append the extracted lagged variable to the dataset
      combined_data[[paste0(raster_type, "_mlag")]] <- extracted_data[[paste0(raster_type, "_mlag")]]
    }
    
    return(combined_data)
  }))
  
  # View the final dataset with lagged variables
  print(head(BD_Lagged_Vars))
```

```{r Formatting finalised dataset}


  # Convert both BD_Full_Dataset and BD_Lagged_Vars to data frames
    BD_Full_Dataset_df <- as.data.frame(BD_Full_Dataset)
    BD_Lagged_Vars_df <- as.data.frame(BD_Lagged_Vars)

  # Add UniqID to BD_Full_Dataset_df
    BD_Full_Dataset_df <- BD_Full_Dataset_df %>%
      mutate(UniqID = paste(Date, Trap_Type, Site, sep = "_"))

  # Add UniqID to BD_Lagged_Vars_subset_df
    BD_Lagged_Vars_df <- BD_Lagged_Vars_df %>%
      mutate(UniqID = paste(Date, Trap_Type, Site, sep = "_"))
    
  # Select only the specified columns from BD_Lagged_Vars
    vars_to_join <- c("UniqID", "NDVI", "NDVI_mlag",  
                      "tmin_mlag", "tmax_mlag", "tavg_mlag", 
                      "prec_mlag", "srad_mlag", "wind_mlag", "vapr_mlag")

    BD_Lagged_Vars_subset_df <- BD_Lagged_Vars_df %>%
      dplyr::select(all_of(vars_to_join))
  

  # Perform the left join based on UniqID
    BD_Data_df <- BD_Full_Dataset_df %>%
      left_join(BD_Lagged_Vars_subset_df, by = "UniqID")

  # Convert BD_Data_df to sf object using the geometry column
    BD_Data_df <- BD_Data_df %>%
      mutate(
        Latitude = as.numeric(sub("_.*", "", Site)),  # Extract part before the underscore
        Longitude = as.numeric(sub(".*_", "", Site)) # Extract part after the underscore
      )

  # Convert back to an sf object
    BD_Data <- st_as_sf(BD_Data_df, coords = c("Longitude", "Latitude"), crs = 4326)
  
    BD <- BD_Data %>%
      filter(!is.infinite(as.numeric(InvSimpson)))

    BD_df <- BD_Data_df %>%
      filter(!is.infinite(as.numeric(InvSimpson)))

  # Rearrange and subset the dataset for gbm.step
    BD_df$Trap_Type_f <- as.factor(BD_df$Trap_Type)    
    
    gbm.BD.Shannon <- BD_df %>%
      dplyr::select(
        Shannon,
        tmin, tmax, tavg, prec, # Environmental and covariate variables
        srad, wind, vapr, WorldCover, PopDens, Elevation, 
        NightLights, DstRd, HumanFootprint,
        NDVI, NDVI_mlag, 
        tmin_mlag, tmax_mlag, tavg_mlag, prec_mlag, 
        srad_mlag, wind_mlag, vapr_mlag
      )
  
  # Verify the new dataset structure
    head(gbm.BD.Shannon)
```

```{r BRT for Shannon}

  library(gbm)
  library(MASS)

  # Split the data into training and testing sets
    set.seed(1999)
    train.index <- sample(seq_len(nrow(gbm.BD.Shannon)), size = floor(0.75 * nrow(gbm.BD.Shannon)))
    train <- gbm.BD.Shannon[train.index, ]
    test <- gbm.BD.Shannon[-train.index, ]
  
  # Build the Boosted Regression Model with Cross-Validation
    set.seed(1999)
    brt_model <- gbm(
      Shannon ~ .,                # Response and predictors
      data = train,               # Training data
      distribution = "gaussian",  # Suitable for continuous response
      n.trees = 5000,            # Number of trees
      interaction.depth = 2,     # Tree complexity
      shrinkage = 0.01,           # Learning rate
      bag.fraction = 0.75,        # Fraction of data used in each iteration
      cv.folds = 10,               # Number of cross-validation folds
      keep.data = TRUE            # Retain dataset in model object
    )
  
  # Evaluate the optimal number of trees using cross-validation
    optimal_trees <- gbm.perf(brt_model, method = "cv")
  
  # Print the optimal number of trees
    cat("Optimal number of trees (via cross-validation):", optimal_trees, "\n")
  
  # Model Summary
    summary(brt_model)

  # Evaluate model performance on training data
    train_preds <- predict(brt_model, train, n.trees = brt_model$n.trees)
  
  # Calculate RMSE on training data
    train_rmse <- sqrt(mean((train$Shannon - train_preds)^2))
    cat("Training RMSE:", train_rmse, "\n")
    
  # Evaluate model performance on testing data
    test_preds <- predict(brt_model, test, n.trees = brt_model$n.trees)
  
  # Calculate RMSE on testing data
    test_rmse <- sqrt(mean((test$Shannon - test_preds)^2))
    cat("Testing RMSE:", test_rmse, "\n")
    
  # Visualize variable importance
    importance <- summary(brt_model)
  
  # Plot variable importance
    library(ggplot2)
      ggplot(importance, aes(x = reorder(var, rel.inf), y = rel.inf)) +
        geom_bar(stat = "identity", fill = "orchid") +
        coord_flip() +
        labs(
          title = "Variable Importance",
          x = "Variables",
          y = "Relative Influence (%)"
        ) +
        theme_minimal()
      
  # Partial dependence for the top 3 important variables
    par(mfrow = c(2, 5))  # Arrange plots in one row
  
  # Replace 'Var1', 'Var2', 'Var3' with actual variable names
    plot(brt_model, i.var = "NDVI", main = "Partial Dependence: NDVI")
    plot(brt_model, i.var = "NDVI_mlag", main = "Partial Dependence: NDVI_mlag")
    #plot(brt_model, i.var = "EVI", main = "Partial Dependence: EVI")
    plot(brt_model, i.var = "srad", main = "Partial Dependence: srad")
    #plot(brt_model, i.var = "EVI_mlag", main = "Partial Dependence: EVI_mlag")
    plot(brt_model, i.var = "prec", main = "Partial Dependence: prec")
    plot(brt_model, i.var = "wind", main = "Partial Dependence: wind")
    plot(brt_model, i.var = "wind_mlag", main = "Partial Dependence: wind_mlag")
    plot(brt_model, i.var = "prec_mlag", main = "Partial Dependence: prec_mlag")
    plot(brt_model, i.var = "tmax", main = "Partial Dependence: tmax")
    
  # Predicted vs Observed on Test Data
    ggplot(data.frame(Observed = test$Shannon, Predicted = test_preds), aes(x = Observed, y = Predicted)) +
      geom_point(color = "darkred", alpha = 0.6) +
      geom_abline(intercept = 0, slope = 1, color = "blue", linetype = "dashed") +
      labs(
        title = "Predicted vs Observed (Test Data)",
        x = "Observed Shannon",
        y = "Predicted Shannon"
      ) +
      theme_minimal()
    
  # Plot training error and validation error vs. number of trees
    gbm.perf(brt_model, method = "OOB")  # Out-of-bag error
    gbm.perf(brt_model, method = "cv")   # Cross-validation error (if cv.gbm used)
  
  # Print the optimal number of trees
    optimal_trees <- gbm.perf(brt_model, method = "cv")
    cat("Optimal number of trees:", optimal_trees, "\n")
```

```{r Trim the variables}

  # Function to compute RMSE
    compute_rmse <- function(actual, predicted) {
      sqrt(mean((actual - predicted)^2))
    }
    
  # Initialize variables
    current_model <- brt_model
    current_predictors <- names(train)[names(train) != "Shannon"]
    iteration <- 0
    
  # Store initial model performance
    initial_cv_error <- min(current_model$cv.error)
    cat("Initial CV Error:", initial_cv_error, "\n")
    
  # Stepwise elimination process
    repeat {
      iteration <- iteration + 1
      cat("\nIteration:", iteration, "\n")
      
      # Get relative influence of current model
        rel_inf <- summary(current_model, plot = FALSE)
      
      # Identify predictors with RI < 5%
        low_influence_predictors <- rel_inf[rel_inf$rel.inf < 5, "var"]
        
        if (length(low_influence_predictors) == 0) {
          cat("No predictors with RI < 5% found. Stopping.\n")
          break
        }
        
      # Select the least influential predictor
        predictor_to_remove <- tail(low_influence_predictors, 1)
        cat("Removing predictor:", predictor_to_remove, "\n")
        
      # Update predictor list
        current_predictors <- setdiff(current_predictors, predictor_to_remove)
      
      # Update training data
        train_updated <- train[, c("Shannon", current_predictors)]
      
      # Rebuild the model without the least influential predictor
        set.seed(1999)
        updated_model <- gbm(
          Shannon ~ .,
          data = train_updated,
          distribution = "gaussian",
          n.trees = 5000,
          interaction.depth = 2,
          shrinkage = 0.01,
          bag.fraction = 0.75,
          cv.folds = 10,
          keep.data = TRUE
        )
      
      # Evaluate the optimal number of trees using cross-validation
        optimal_trees <- gbm.perf(updated_model, method = "cv", plot.it = FALSE)
        cat("Optimal number of trees:", optimal_trees, "\n")
        
      # Get minimum CV error of the updated model
        updated_cv_error <- min(updated_model$cv.error)
        cat("Updated CV Error:", updated_cv_error, "\n")
      
      # Compare CV errors and notify
        if (updated_cv_error < initial_cv_error) {
          cat("Model improved. Continuing elimination.\n")
        } else {
          cat("Model performance degraded. Continuing elimination.\n")
        }
      
      # Update current model and CV error for next iteration
        current_model <- updated_model
        initial_cv_error <- updated_cv_error
    }
  
  # Final model summary
    cat("\nFinal Model Summary:\n")
    summary(current_model)
    current_model_Shan <- current_model
  
  # Evaluate final model performance on training data
    train_preds <- predict(current_model, train, n.trees = optimal_trees)
    train_rmse <- compute_rmse(train$Shannon, train_preds)
    cat("Training RMSE:", train_rmse, "\n")
  
  # Evaluate final model performance on testing data
    test_preds <- predict(current_model, test, n.trees = optimal_trees)
    test_rmse <- compute_rmse(test$Shannon, test_preds)
    cat("Testing RMSE:", test_rmse, "\n")
    
  # Plot importance
      importance <- summary(current_model)
      ggplot(importance, aes(x = reorder(var, rel.inf), y = rel.inf)) +
        geom_bar(stat = "identity", fill = "orchid") +
        coord_flip() +
        labs(
          title = "Variable Importance",
          x = "Variables",
          y = "Relative Influence (%)"
        ) +
        theme_minimal()
```

```{r Simpson BRT}

  # Verify the new dataset structure
    gbm.BD.Simpson <- BD_df %>%
      dplyr::select(
        Simpson,
        tmin, tmax, tavg, prec, # Environmental and covariate variables
        srad, wind, vapr, WorldCover, PopDens, Elevation, 
        NightLights, DstRd, HumanFootprint,
        NDVI, NDVI_mlag, tmin_mlag, tmax_mlag, tavg_mlag, prec_mlag, 
        srad_mlag, wind_mlag, vapr_mlag
      )
  
  # Verify the new dataset structure
    head(gbm.BD.Simpson)

  # Split the data into training and testing sets
    set.seed(1999)
    train.index_Simpson <- sample(seq_len(nrow(gbm.BD.Simpson)), size = floor(0.75 * nrow(gbm.BD.Simpson)))
    train_Simp <- gbm.BD.Simpson[train.index_Simpson, ]
    test_Simp <- gbm.BD.Simpson[-train.index_Simpson, ]
  
  # Build the Boosted Regression Model with Cross-Validation
    set.seed(1999)
    brt_model_Simpson <- gbm(
      Simpson ~ .,                # Response and predictors
      data = train_Simp,               # Training data
      distribution = "gaussian",  # Suitable for continuous response
      n.trees = 5000,            # Number of trees
      interaction.depth = 2,     # Tree complexity
      shrinkage = 0.01,           # Learning rate
      bag.fraction = 0.75,        # Fraction of data used in each iteration
      cv.folds = 10,               # Number of cross-validation folds
      keep.data = TRUE            # Retain dataset in model object
    )
  
  # Evaluate the optimal number of trees using cross-validation
    optimal_trees_Simp <- gbm.perf(brt_model_Simpson, method = "cv")
  
  # Print the optimal number of trees
    cat("Optimal number of trees (via cross-validation):", optimal_trees_Simp, "\n")
  
  # Model Summary
    summary(brt_model_Simpson)

  # Evaluate model performance on training data
    train_preds_Simp <- predict(brt_model_Simpson, train_Simp, n.trees = brt_model_Simpson$n.trees)
  
  # Calculate RMSE on training data
    train_rmse_Simpson <- sqrt(mean((train_Simp$Simpson - train_preds_Simp)^2))
    cat("Training RMSE:", train_rmse_Simpson, "\n")
    
  # Evaluate model performance on testing data
    test_preds_Simp <- predict(brt_model_Simpson, test_Simp, n.trees = brt_model_Simpson$n.trees)
  
  # Calculate RMSE on testing data
    test_rmse_Simp <- sqrt(mean((test_Simp$Simpson - test_preds_Simp)^2))
    cat("Testing RMSE:", test_rmse_Simp, "\n")
    
  # Visualize variable importance
    importance_Simp <- summary(brt_model_Simpson)
  
  # Plot variable importance
    library(ggplot2)
      ggplot(importance_Simp, aes(x = reorder(var, rel.inf), y = rel.inf)) +
        geom_bar(stat = "identity", fill = "orchid") +
        coord_flip() +
        labs(
          title = "Variable Importance",
          x = "Variables",
          y = "Relative Influence (%)"
        ) +
        theme_minimal()
      
  # Partial dependence for the top 3 important variables
    par(mfrow = c(2, 5))  # Arrange plots in one row
  
  # Replace 'Var1', 'Var2', 'Var3' with actual variable names
    plot(brt_model, i.var = "NDVI", main = "Partial Dependence: NDVI")
    plot(brt_model, i.var = "NDVI_mlag", main = "Partial Dependence: NDVI_mlag")
    #plot(brt_model, i.var = "EVI", main = "Partial Dependence: EVI")
    plot(brt_model, i.var = "srad", main = "Partial Dependence: srad")
    #plot(brt_model, i.var = "EVI_mlag", main = "Partial Dependence: EVI_mlag")
    plot(brt_model, i.var = "prec", main = "Partial Dependence: prec")
    plot(brt_model, i.var = "wind", main = "Partial Dependence: wind")
    plot(brt_model, i.var = "wind_mlag", main = "Partial Dependence: wind_mlag")
    plot(brt_model, i.var = "prec_mlag", main = "Partial Dependence: prec_mlag")
    plot(brt_model, i.var = "tmax", main = "Partial Dependence: tmax")
    
  # Predicted vs Observed on Test Data
    ggplot(data.frame(Observed = test_Simp$Simpson, Predicted = test_preds), aes(x = Observed, y = Predicted)) +
      geom_point(color = "darkred", alpha = 0.6) +
      geom_abline(intercept = 0, slope = 1, color = "blue", linetype = "dashed") +
      labs(
        title = "Predicted vs Observed (Test Data)",
        x = "Observed Simpson",
        y = "Predicted Simpson"
      ) +
      theme_minimal()
    
  # Plot training error and validation error vs. number of trees
    gbm.perf(brt_model, method = "OOB")  # Out-of-bag error
    gbm.perf(brt_model, method = "cv")   # Cross-validation error (if cv.gbm used)
  
  # Print the optimal number of trees
    optimal_trees <- gbm.perf(brt_model, method = "cv")
    cat("Optimal number of trees:", optimal_trees, "\n")
     
```

```{r Trimming Simpson}
  # Function to compute RMSE
  compute_rmse <- function(actual, predicted) {
    sqrt(mean((actual - predicted)^2))
  }
  
  # Initialize variables
  current_model_Simp <- brt_model_Simpson
  current_predictors_Simp <- names(train_Simp)[names(train_Simp) != "Simpson"]
  iteration <- 0
  
  # Store initial model performance
  initial_cv_error_Simp <- min(current_model_Simp$cv.error)
  cat("Initial CV Error:", initial_cv_error_Simp, "\n")
  
  # Stepwise elimination process
  repeat {
    iteration <- iteration + 1
    cat("\nIteration:", iteration, "\n")
    
    # Get relative influence of current model
    rel_inf_Simp <- summary(current_model_Simp, plot = FALSE)
    
    # Identify predictors with RI < 5%
    low_influence_predictors_Simp <- rel_inf_Simp[rel_inf_Simp$rel.inf < 5, "var"]
    
    if (length(low_influence_predictors_Simp) == 0) {
      cat("No predictors with RI < 5% found. Stopping.\n")
      break
    }
    
    # Select the least influential predictor
    predictor_to_remove_Simp <- tail(low_influence_predictors_Simp, 1)
    cat("Removing predictor:", predictor_to_remove_Simp, "\n")
    
    # Update predictor list
    current_predictors_Simp <- setdiff(current_predictors_Simp, predictor_to_remove_Simp)
    
    # Update training data
    train_updated_Simp <- train_Simp[, c("Simpson", current_predictors_Simp)]
    
    # Rebuild the model without the least influential predictor
    set.seed(1999)
    updated_model_Simp <- gbm(
      Simpson ~ .,
      data = train_updated_Simp,
      distribution = "gaussian",
      n.trees = 5000,
      interaction.depth = 2,
      shrinkage = 0.01,
      bag.fraction = 0.75,
      cv.folds = 10,
      keep.data = TRUE
    )
    
    # Evaluate the optimal number of trees using cross-validation
    optimal_trees_Simp <- gbm.perf(updated_model_Simp, method = "cv", plot.it = FALSE)
    cat("Optimal number of trees:", optimal_trees_Simp, "\n")
    
    # Get minimum CV error of the updated model
    updated_cv_error_Simp <- min(updated_model_Simp$cv.error)
    cat("Updated CV Error:", updated_cv_error_Simp, "\n")
    
    # Compare CV errors and notify
    if (updated_cv_error_Simp < initial_cv_error_Simp) {
      cat("Model improved. Continuing elimination.\n")
    } else {
      cat("Model performance degraded. Continuing elimination.\n")
    }
    
    # Update current model and CV error for next iteration
    current_model_Simp <- updated_model_Simp
    initial_cv_error_Simp <- updated_cv_error_Simp
  }
  
  # Final model summary
  cat("\nFinal Model Summary:\n")
  summary(current_model_Simp)
  
  # Evaluate final model performance on training data
  train_preds_Simp <- predict(current_model_Simp, train_Simp, n.trees = optimal_trees_Simp)
  train_rmse_Simp <- compute_rmse(train_Simp$Simpson, train_preds_Simp)
  cat("Training RMSE:", train_rmse_Simp, "\n")
  
  # Evaluate final model performance on testing data
  test_preds_Simp <- predict(current_model_Simp, test_Simp, n.trees = optimal_trees_Simp)
  test_rmse_Simp <- compute_rmse(test_Simp$Simpson, test_preds_Simp)
  cat("Testing RMSE:", test_rmse_Simp, "\n")
  
  # Visualize variable importance
  importance_Simp <- summary(current_model_Simp, plot = FALSE)
  
  # Plot variable importance
  library(ggplot2)
  ggplot(importance_Simp, aes(x = reorder(var, rel.inf), y = rel.inf)) +
    geom_bar(stat = "identity", fill = "orchid") +
    coord_flip() +
    labs(
      title = "Variable Importance",
      x = "Variables",
      y = "Relative Influence (%)"
    ) +
    theme_minimal()
```

```{r Scaling and preparing variable importance for output}

  # Create the Shannon Importance Plot
    Shan_Imp <- data.frame(
      var = c("PopDens", "tmax", "NDVI_mlag", "tmax_mlag", "prec", "wind_mlag", 
              "NDVI", "vapr_mlag", "DstRd", "srad", "wind", "srad_mlag", "tmin"),
      rel.inf = c(13.55437, 11.69443, 10.44267, 8.502055, 7.625895, 7.339125, 
                  6.669665, 5.993025, 5.973383, 5.764821, 5.540196, 5.452412, 5.447961)
    )
    Shan_Imp$rel.inf_adj <- Shan_Imp$rel.inf - 5
    
    shannon_plot <- ggplot(Shan_Imp, aes(x = reorder(var, rel.inf), y = rel.inf_adj)) +
      geom_bar(stat = "identity", fill = "orchid") +
      geom_text(aes(label = round(rel.inf, 1)), 
                hjust = -0.1, size = 3.5, color = "black") +
      coord_flip() +
      scale_y_continuous(limits = c(0, 10), labels = function(x) x + 5, expand = c(0, 0)) +
      labs(
        title = "Variable Importance (Shannon)",
        x = "Variables",
        y = "Relative Influence (%)"
      ) +
      theme_minimal()
  
  # Create the Simpson Importance Plot
    Simp_Imp <- data.frame(
      var = c("tmax", "PopDens", "NDVI_mlag", "tmax_mlag", "wind_mlag", "prec", 
              "wind", "srad_mlag", "DstRd", "NDVI", "srad", "tmin", "vapr_mlag"),
      rel.inf = c(12.3646, 11.002, 10.29838, 9.108652, 7.483425, 7.193997, 
                  6.502328, 6.334101, 6.162942, 6.145769, 6.018981, 5.740524, 5.644303)
    )
    Simp_Imp$rel.inf_adj <- Simp_Imp$rel.inf - 5
    
    simpson_plot <- ggplot(Simp_Imp, aes(x = reorder(var, rel.inf), y = rel.inf_adj)) +
      geom_bar(stat = "identity", fill = "orchid") +
      geom_text(aes(label = round(rel.inf, 1)), 
                hjust = -0.1, size = 3.5, color = "black") +
      coord_flip() +
      scale_y_continuous(limits = c(0, 10), labels = function(x) x + 5, expand = c(0, 0)) +
      labs(
        title = "Variable Importance (Simpson)",
        x = "Variables",
        y = "Relative Influence (%)"
      ) +
      theme_minimal()
  
  # Combine the plots using patchwork
    library(patchwork)
    combined_plot <- shannon_plot / simpson_plot + plot_layout(heights = c(1, 1))
  
  # Save the combined plot as an .svg file
    output_folder <- "REPLACE WITH YOUR OUTPUT DIRECTORY"
    svg(filename = file.path(output_folder, "BRT_Imp_Plots.svg"), width = 10, height = 12)
    print(combined_plot)
    dev.off()
  
  # Display the plot
    print(combined_plot)
    
  
```

```{r Partial Dependency Plots}
  # Load required library
    library(pdp)
  
  # Variables for each model
    shannon_vars <- c("PopDens", "tmax", "NDVI_mlag", "tmax_mlag")
    simpson_vars <- c("tmax", "PopDens", "NDVI_mlag", "tmax_mlag")
  
  # Create partial dependency plots for Shannon model
    shannon_plots <- lapply(shannon_vars, function(var) {
      pdp_shan <- partial(current_model_Shan, pred.var = var, n.trees = 781, plot = FALSE)
      ggplot(pdp_shan, aes_string(x = var, y = "yhat")) +
        geom_line(color = "orchid", size = 1) +
        labs(
          title = paste("Partial Dependence -", var),
          x = var,
          y = "Predicted Value"
        ) +
        theme_minimal()
    })
  
  # Combine Shannon plots in a 4x4 grid
    library(patchwork)
    shannon_combined <- wrap_plots(shannon_plots, ncol = 2) + 
      plot_annotation(title = "Partial Dependence Plots (Shannon Model)")
  
  # Create partial dependency plots for Simpson model
    simpson_plots <- lapply(simpson_vars, function(var) {
      pdp_simp <- partial(current_model_Simp, pred.var = var, n.trees = 781, plot = FALSE)
      ggplot(pdp_simp, aes_string(x = var, y = "yhat")) +
        geom_line(color = "orchid", size = 1) +
        labs(
          title = paste("Partial Dependence -", var),
          x = var,
          y = "Predicted Value"
        ) +
        theme_minimal()
    })
  
  # Combine Simpson plots in a 4x4 grid
    simpson_combined <- wrap_plots(simpson_plots, ncol = 2) + 
      plot_annotation(title = "Partial Dependence Plots (Simpson Model)")
  
  # Print the combined plots
    print(shannon_combined)
    print(simpson_combined)
    
  # Define the output folder
    output_folder <- "REPLACE WITH YOUR OUTPUT DIRECTORY"
  
  # Save the Shannon Partial Dependency Plots
    svg(filename = file.path(output_folder, "Shannon_Partial_Dependency_Plots.svg"), width = 10, height = 12)
    print(shannon_combined)
    dev.off()
  
  # Save the Simpson Partial Dependency Plots
    svg(filename = file.path(output_folder, "Simpson_Partial_Dependency_Plots.svg"), width = 10, height = 12)
    print(simpson_combined)
    dev.off()

```

```{r Stacking the Rasters}

  # Function to reproject, crop, and mask a raster
    process_raster <- function(r, target_crs, target_shape) {
      # Reproject to match the CRS of haiti_sf
        r <- project(r, target_crs)
      
      # Crop and mask to the extent and boundary of haiti_sf
        r <- crop(r, vect(target_shape))
        r <- mask(r, vect(target_shape))
      
      return(r)
    }
    
  # List of raster objects already loaded in the environment
    vars <- list(
      Haiti_tmin, Haiti_tmax, Haiti_tavg, Haiti_prec, Haiti_srad, Haiti_wind, Haiti_vapr,
      Haiti_WorldCover, PopDens, HuFootprint,
      Cattle, Chicken, Duck, Goat, Horse, Pig, Sheep,
      modis_ndvi, Elevation, NightLights2011, DstRd
    )
  
  # Extract CRS from haiti_sf
    haiti_crs <- crs(haiti_sf)
  
  # Process each raster sequentially
    constrained_vars <- lapply(vars, function(r) process_raster(r, haiti_crs, haiti_sf))
 

  
  # Define the target resolution and extent
    target_resolution <- c(0.08333333, 0.08333333)  # Target resolution
    target_extent <- ext(-74.49167, -71.64167, 18.025, 20.09167)  # Most limiting extent
  
  # Function to align extent and resolution of a raster
    align_raster <- function(r, target_crs, target_res, target_ext) {
      # Create a template raster with the target extent and resolution
        template <- rast(ext = target_ext, resolution = target_res, crs = target_crs)
      
      # Resample the raster to match the template
        aligned_r <- resample(r, template)
      
      return(aligned_r)
  }
  
    # List of raster objects already processed (cropped and masked)
      vars <- list(
        Haiti_tmin, Haiti_tmax, Haiti_tavg, Haiti_prec, Haiti_srad, Haiti_wind, Haiti_vapr,
        Haiti_WorldCover, PopDens, HuFootprint,
        City1, City2, City3, City4, City5, City6, City7, City8, City9,
        Cattle, Chicken, Duck, Goat, Horse, Pig, Sheep,
        modis_ndvi, Elevation, NightLights2011, DstRd
      )
    
    # Extract CRS from one raster (all should have the same CRS at this point)
      haiti_crs <- crs(Haiti_tmin)
    
    # Align each raster sequentially
      aligned_vars <- lapply(vars, function(r) align_raster(r, haiti_crs, target_resolution, target_extent))
    
    # Combine all aligned rasters into a stack
      Haiti_aligned_stack <- rast(aligned_vars)
    
    # Optional: Save the aligned raster stack to disk
      writeRaster(
        Haiti_aligned_stack,
        "REPLACE WITH YOUR OUTPUT DIRECTORY",
        overwrite = TRUE
    )
  
  # Check the aligned raster stack
    print(Haiti_aligned_stack)
    plot(Haiti_aligned_stack)    
     

```

```{r Importing the stack after downloading it}

  # Define the file path of the exported raster stack
    file_path <- "REPLACE WITH YOUR OUTPUT DIRECTORY"
  
  # Import the raster stack
    Haiti_stack_imported <- rast(file_path)
  
  # Check the imported raster stack
    print(Haiti_stack_imported)
    plot(Haiti_stack_imported)
    
    Haiti_stack_imported

```

