#
# New Run 1. Run MaxEnt with 8 Selected Layers
#
# Run MaxEnt with a initial model, with 8 environmental layers selected, that are
#     regarded as of ecologically important on the distribution of tree pests and 
#     pathogens. 
# 
#
# *************************************************
# List of bioclimatic variables: 
#
# BIO1 = Annual Mean Temperature
# BIO5 = Max Temperature of Warmest Month
# BIO6 = Min Temperature of Coldest Month
# BIO12 = Annual Precipitation
# BIO16 = Precipitation of Wettest Quarter
# BIO17 = Precipitation of Driest Quarter
#
# *************************************************

setwd("D:/DPhil/Paper 2 analysis/data")
rm(list = ls())

# install (if not installed) and load packages
install.packages(
  setdiff(c("tidyverse", "dismo", "raster", "sf", "rJava", "corrplot"), rownames(installed.packages()))
)
library(tidyverse)
library(dismo) 
library(raster)
library(sf)
library(rnaturalearth)
library(rnaturalearthdata)
library(ggtext)
library(terra)

# MaxEnt model parameters
random_background <- FALSE # we use bias raster rather than random background to
                           #    improve MaxEnt model accuracy, as random background
                           #    ignores the reality that sampling points can be 
                           #    scattered because human researchers are more 
                           #    accessible to certain places (e.g. roads, villages,
                           #    Global North countries)


# Country borders for visualisation
world <- ne_countries(scale = "medium", returnclass = "sf") %>%
  st_transform(crs = CRS("+proj=longlat +datum=WGS84")) %>%
  st_geometry()




# *****************************************
#   STEP 1: Load Environmental Layers----
# *****************************************

#download WorldClim historical data
if(!dir.exists("layers")){
  dir.create("layers")
  download.file(
    url = "https://geodata.ucdavis.edu/climate/worldclim/2_1/base/wc2.1_10m_bio.zip",
    destfile = "layers/wc2.1_10m_bio.zip",
    mode = "wb",
    quiet = FALSE
  )
  
  unzip(
    zipfile = "layers/wc2.1_10m_bio.zip",
    exdir = "layers",
    overwrite = TRUE
  )
  
  tif_files <- list.files("layers", pattern = "\\.tif$", full.names = TRUE)
  for(f in tif_files){
    r <- rast(f)
    output_file_name <- sub("\\.tif$", ".asc", f)
    writeRaster(
      r,
      filename = output_file_name,
      filetype = "AAIGrid",
      overwrite = TRUE
    )
  }
  
  files <- list.files("layers", full.names = TRUE)
  file.remove(files[!grepl("\\.tif$", files, ignore.case = TRUE)])
}

#download WorldClim future climate data
if(!dir.exists("future")){
  dir.create("future")
  
  GCM_models <- c(
    "ACCESS-CM2", "BCC-CSM2-MR", "CMCC-ESM2", "EC-Earth3-Veg", "GISS-E2-1-G", "INM-CM5-0", "IPSL-CM6A-LR", "MIROC6", "MPI-ESM1-2-HR", "MRI-ESM2-0", "UKESM1-0-LL"
  )
  ssps <- c("ssp126","ssp245","ssp370","ssp585")
  periods <- c("2041-2060", "2061-2080")
  
  for(GCM_model in GCM_models){
    for(ssp in ssps){
      for(period in periods){
        url <- paste0("https://geodata.ucdavis.edu/cmip6/10m/",GCM_model,"/",ssp,"/wc2.1_10m_bioc_",GCM_model,"_",ssp,"_",period,".tif")
        local_file <- paste0("future/wc2.1_10m_bioc_",GCM_model,"_",ssp,"_",period,".tif")
        download.file(
          url = url,
          destfile = local_file,
          mode = "wb",
          quiet = FALSE
        )
      }
    }
  }
  
  tif_files <- list.files("future", pattern = "\\.tif$", full.names = TRUE)
  for(f in tif_files){
    
    r <- rast(f)
    for(i in 1:nlyr(r)){
      
      output_file_name <- sub(
        "bioc",
        paste0("bio_", i),
        f
      ) %>%
        sub("\\.tif$", ".asc", .)
      
      writeRaster(
        r[[i]],
        filename = output_file_name,
        filetype = "AAIGrid",
        overwrite = TRUE
      )
    }
  }
  
  files <- list.files("future", full.names = TRUE)
  file.remove(files[!grepl("\\.tif$", files, ignore.case = TRUE)])
}

# load historical climate data
layers <- list.files("layers/", pattern="asc$", full.names=TRUE) %>% # directory that stores bioclimatic data
  { .[grepl("bio_(1|5|6|12|16|17)\\.asc$", .)] } %>% # select bioclimatic variables
  stack() # Raster Stack
# You can also change 'asc' to 'tif', as the function 'stack' accepts GeoTIFF files


# Calculate Pearson correlation matrix
if(!file.exists("results/correlation_matrix.RData")){
  cor_matrix <- layers %>% 
    as.data.frame() %>% 
    na.omit() %>%
    cor(method = "pearson")
  save(cor_matrix, file = "results/correlation_matrix.RData")
} else{
  load("results/correlation_matrix.RData")
}

# Visualise Pearson correlation matrix
if(!file.exists("results/Figure-1-and-S1-pest-current/S1_layer-correlation.pdf")){
  pdf("results/Figure-1-and-S1-pest-current/S1_layer-correlation.pdf", 
      width = 6.41, height = 5.45)
  corrplot::corrplot(cor_matrix, method = "circle", type = "upper", 
           tl.col = "black", tl.srt = 45)
  dev.off()
  # Results:
  #   All temperature variables are highly correlated with one another (Pearson > 0.7).
  #       Therefore, only of of these variables (BIO1 = Annual Mean Temperature, 
  #       BIO5 = Max Temperature of Warmest Month, BIO6 = Min Temperature of Coldest Month
  #       can be allowed to include in the MaxEnt model.
  #
  #   BIO12 = Annual Precipitation is strongly correlated with BIO16 = Precipitation of Wettest Quarter
  #       and BIO17 = Precipitation of Driest Quarter (Pearson > 0.7), while BIO16 
  #       and BIO17 are not strongly correlated.
}

# *****************************************
#   STEP 2: Define Background Points----
# *****************************************

# Background points are locations within the study area that is used for comparison
#    with "presence" points, representing the environmental conditions that are 
#    available to the species, but not necessarily occupied
#
# When researchers predominantly collect presence data in easily accessible areas 
#    (e.g., near roads, cities, or along trails), these areas are overrepresented 
#    in the occurrence data. If you then sample background points randomly across 
#    the entire study region (including inaccessible areas), the model learns to 
#    associate the presence records with the accessibility of the location rather 
#    than the actual environmental characteristics the species needs to survive.

if(random_background){
  bg <- randomPoints(layers %>% raster(1), n = 10000) # Generate 10000 random background points
} else{
  
  # In DPhil paper 1, I collected field survey data for 53 major tree pests and 
  #    pathogens through a systematic review on 339 papers, sourced from an initial 
  #    pool of 16,355 papers. I will use the study locations for these 339 papers
  #    as approximates of sampling intensity. That is, the resource availability to 
  #    conduct research in tree pests and diseases. These locations are used to 
  #    generated background points, so that the MaxEnt model only compare present 
  #    points with points that locate within sampling areas.
  
  if(file.exists("bias/bias_raster.tif")){
    # The following process takes quite a lot of time,
    #   so I save the file rather, to avoid running it repetitively
    bias_raster <- raster("bias/bias_raster.tif")
  } else{
    # import Paper 1 data on distribution of pest and disease field surveys as sampling intensity
    cat("Import sampling data.\n")
    sampling_points <- read.csv("bias/EID - Severity - Measure.csv") %>%
      dplyr::select(Cite, LngLat) %>% # Column 'Cite' - journal papers; Column 'LngLat' - coordinate strings
      filter(LngLat != "") %>% # remove records without longitudes and latitudes
      separate_rows(LngLat, sep = ";") %>% # when a cell contains multiple coordinates, separate them with ";"
      mutate(LngLat = str_trim(LngLat)) %>%
      separate(LngLat, into = c("lat", "lon"), sep = ",\\s*") %>% # separate longitude from latitude
      mutate( # get longitude and latitude values
        lon_value = as.numeric(str_extract(lon, "[0-9.]+")),
        lon_dir   = str_extract(lon, "[EeWw]"),
        lat_value = as.numeric(str_extract(lat, "[0-9.]+")),
        lat_dir   = str_extract(lat, "[NnSs]")
      ) %>%
      mutate( # combine longitude and latitude values with sign (E/W/N/S)
        longitude = if_else(lon_dir %in% c("W","w"), -lon_value, lon_value),
        latitude  = if_else(lat_dir %in% c("S","s"), -lat_value, lat_value)
      ) %>%
      group_by(Cite) %>%
      summarise( # calculate mean longitudes and latitudes for each journal paper
        longitude = mean(longitude),
        latitude  = mean(latitude),
        .groups = "drop"
      ) %>%
      dplyr::select(longitude, latitude) %>%
      SpatialPoints(proj4string = CRS("+proj=longlat +datum=WGS84"))
    # transform to Shapefile/ vector data (which equals to the process in QGIS that
    #   to import CSV data and save it as a Shapefile, or vectorise to point data)
    
    # visualise sampling points
    plot(world, border = "grey", col = NA, lwd = 0.5, main = "Sampling intensity")
    plot(sampling_points, add = TRUE)
    
    # create bias raster
    cat("Create bias raster.\n")
    bias_raster <- sampling_points %>% rasterize(
      layers %>% raster(1), 
      fun = 'count', background = 0
    ) %>%  # rasterise sampling points: take environmental layers for coordinate system reference
      #      'fun = 'count'': count the number of sampling points for each pixel
      #      'background': value to put in the cells that are not covered by any sampling points
      
      focal( # model the sampling efforts using gaussian kernel (return a bias raster)
        w = focalWeight(
          layers %>% raster(1), d = 5, type="Gauss"
          # using Gaussian/ Normal distribution kernel (d = sigma)
          #   f(x) = 1(sigma * sqrt(2 * pi)) * exp(-1/2 * (x/sigma)^2 )
          #   where x is the distance to a sampling point
          #         f(x) is the probability of being sampled by researchers
          #   with increasing sigma (d), the distribution kernel becomes wider and flatter
          # the function returns a weight matrix that cuts probability density distribution at 3*sigma (i.e. 3*d).
          #   Note that the unit of d aligns with the input raster, and the input raster
          #   'layers %>% raster(1)' has a resolution of 0.1666667 degree. So the unit 
          #   of 'd' is degree in this case. The returned matrix is of size
          #   (2*3*sigma/0.1666667 + 1)* (2*3*sigma/0.1666667 + 1)
        ),
        na.rm = TRUE
      ) %>%
      { .[is.na(.)] <- 0; .} # remove NAs
    
    # remove water bodies as they are not valid background regions
    land_mask <- ne_countries(scale = "medium", returnclass = "sf") %>% 
      rasterize(bias_raster, field = 1)
    
    bias_raster <- bias_raster %>%
      { .[is.na(land_mask)] <- 0; .} %>% # assign water bodies to 0
      { ./cellStats(., sum) } # normalised to probability (0-1)
    
    writeRaster(bias_raster, "bias/bias_raster.tif")
  }
  
  plot(bias_raster, main = "Modelled sampling effort")
  plot(world, add = TRUE, border = "grey", col = NA, lwd = 0.5)
  
  # Generate background points
  bg <- randomPoints(
    mask = bias_raster,
    n = 10000,
    prob = TRUE
  )
}

# ************************************************
#   STEP 3: Run MaxEnt with all env varibles----
# ************************************************


if(!file.exists("results/variable_contributions.RData")){
  #Jave Env is required
  # Downloaded from Oracle website https://www.oracle.com/uk/java/technologies/downloads/#jdk27-windows
  
  layer_contributions <- tibble(
    sample_file = c(), layer = c(), metric = c(), value = c()
  )
  for(sample_file in list.files("samples/", full.names = TRUE)){
    cat("Pest or pathogen file =", sample_file, "\n")
    
    # get species occurrence data
    coords <- read.csv(sample_file) %>%
      dplyr::select("dd.long", "dd.lat")
    
    # train MaxEnt model
    mx <- maxent(x = layers, p = coords, a = bg)
    
    layer_contributions <- rbind(
      layer_contributions,
      mx@results %>% # get model training results
        as.data.frame() %>%
        rename(value = V1) %>%
        rownames_to_column(var = "X.Training.samples") %>%
        filter( # get variable percent contribution and permutation importance information
          grepl("contribution", X.Training.samples) |
            grepl("permutation", X.Training.samples)
        ) %>% 
        mutate(sample_file = sample_file) %>% # add pathogen/ pest information
        mutate( # reformat
          metric = if_else(str_detect(X.Training.samples, "contribution"), "contribution", "permutation importance"),
          layer = str_remove(X.Training.samples, regex("\\.(contribution|permutation.*)$"))
        ) %>%
        dplyr::select(sample_file, layer, metric, value)
    )
  }
  save(layer_contributions, file = "results/variable_contributions.RData")
} else{
  load("results/variable_contributions.RData")
}

# convert sample file name to pest name in format ()
file_2_pest <- function(file_name){
  pest_scientific <- tibble(
    common = c(
      "Oak Decline",
      "Ash Dieback",
      "Asian Longhorned Beetle",
      "Beech Bark Disease",
      "Beech Leaf Disease",
      "Bronze Birch Borer",
      "Brown Spruce Longhorn Beetle",
      "Butternut Canker",
      "Dothistroma Needle Blight",
      "Dutch Elm Disease",
      "Eight-Toothed Spruce Bark Beetle",
      "Emerald Ash Borer",
      "Fall Webworm",
      "Forest Tent Caterpillar",
      "Gypsy Moth",
      "Hemlock Woolly Adelgid",
      "Japanese Oak Wilt",
      "Laurel Wilt",
      "Mountain Pine Beetle",
      "Oak Wilt",
      "Oriental Chestnut Gall Wasp",
      "Pine Processionary Moth",
      "Pine Wood Nematode",
      "Red Turpentine Beetle",
      "Red-necked Longhorn Beetle",
      "Spotted Lanternfly",
      "Spruce Budworm",
      "Sudden Oak Death",
      "Sweet Chestnut Blight",
      "White Pine Blister Rust",
      "Xylella"
    ),
    scientific = c(
      "Brenneria goodwinii, Gibbsiella quercinecans",
      "Hymenoscyphus fraxineus",
      "Anoplophora glabripennis",
      "Neonectria faginata",
      "Litylenchus crenatae mccannii",
      "Agrilus anxius",
      "Tetropium fuscum",
      "Sirococcus clavigignenti-juglandacearum",
      "Dothistroma septosporum",
      "Ophiostoma ulmi, Ophiostoma novo-ulmi",
      "Ips typographus",
      "Agrilus planipennis",
      "Hyphantria cunea",
      "Malacosoma disstria",
      "Lymantria dispar",
      "Adelges tsugae",
      "Raffaelea quercivora",
      "Raffaelea lauricola",
      "Dendroctonus ponderosae",
      "Bretziella fagacearum",
      "Dryocosmus kuriphilus",
      "Thaumetopea pityocampa",
      "Bursaphelenchus xylophilus",
      "Dendroctonus valens",
      "Aromia bungii",
      "Lycorma delicatula",
      "Choristoneura fumiferana",
      "Phytophthora ramorum",
      "Cryphonectria parasitica",
      "Cronartium ribicola",
      "Xylella fastidiosa"
    )
  )
  
  file_name %>%
    basename() %>%
    str_remove("\\.csv$") %>%
    str_replace_all("_", " ") %>% # transform file name to pest name
    tibble(common = .) %>%
    left_join(pest_scientific, by = "common") %>% # transform common to scientific name
    mutate(full = str_glue("{common} (<i>{scientific}</i>)")) %>% # stick together
    pull(full)
}

# visualise results of variable importance
theme1 <- theme_bw()+
  theme(axis.text.x=element_text(size=10,angle=45,hjust=1,colour="black"),
        axis.text.y=element_text(size=10,angle=0,colour="black"),
        axis.title=element_text(size=18),
        axis.line=element_blank(),
        axis.ticks = element_line(colour="black"),
        panel.grid.major = element_blank(),
        panel.grid.minor = element_blank(), 
        #strip.background = element_rect(colour = "black",size = 0.8),
        #panel.background = element_rect(colour="black", fill="#E2E2E2"),
        panel.border = element_blank(),
        plot.title=element_text(size=14,angle=0,colour="black", face = "italic"),
        plot.tag=element_text(size=14,angle=0,colour="black", face = "bold"),
        plot.caption=element_text(size=14,angle=0,colour="black",face = "italic"),
        axis.title.y=element_text(vjust=1.9),
        axis.title.x=element_text(vjust=0.5),
        legend.text=element_text(colour="black",size=14),
        legend.background= element_rect(fill = "transparent", color = NA),
        #legend.position = "bottom",
        legend.title = element_text(colour="black", size=14,angle=0,margin = margin(b = 10)))

if(!file.exists("results/Figure4-var-importance/figure 4A.pdf")){
  pdf("results/Figure4-var-importance/figure 4A.pdf", 
      width = 8.68, height = 5.40)
  ggplot(
    layer_contributions %>% 
      filter(metric == "contribution") %>%
      mutate(pest = file_2_pest(sample_file)), 
    aes(x = layer, y = pest, fill = value)
  ) +
    geom_tile(color = "white", alpha = 0.9) +
    scale_fill_gradientn(
      colours = c("#313695", "#4575B4", "#74ADD1", "#ABD9E9", "#E0F3F8", 
                  "#FFFFBF", "#FEE090", "#FDAE61", "#F46D43", "#D73027", "#A50026"),  # 模拟的色阶颜色，可调整
      limits = c(0, 70),  # 贡献度范围
      name = "Percent\nContribution"  # 图例标题
    ) +theme1 +xlab(NULL) + ylab(NULL) +
    theme(axis.text.y = element_markdown())
  dev.off()
}

if(!file.exists("results/Figure4-var-importance/figure 4B.pdf")){
  pdf("results/Figure4-var-importance/figure 4B.pdf", 
      width = 8.68, height = 5.40)
  ggplot(
    layer_contributions %>% 
      filter(metric == "permutation importance") %>%
      mutate(pest = file_2_pest(sample_file)), 
    aes(x = layer, y = pest, fill = value)
  ) +
    geom_tile(color = "white", alpha = 0.9) +
    scale_fill_gradientn(
      colours = c("#313695", "#4575B4", "#74ADD1", "#ABD9E9", "#E0F3F8", 
                  "#FFFFBF", "#FEE090", "#FDAE61", "#F46D43", "#D73027", "#A50026"),  # 模拟的色阶颜色，可调整
      limits = c(0, 70),  # 贡献度范围
      name = "Permutation\nImportance"  # 图例标题
    ) +theme1 +xlab(NULL) + ylab(NULL) +
    theme(axis.text.y = element_markdown())
  dev.off()
}


# Selected variables:
#
# 1. Ash Dieback (Hymenoscyphus fraxineus)
# 
# Pick: BIO5 (Max Temperature of Warmest Month), BIO17 (Precipitation of Driest Quarter)
# Why: BIO5 has significantly larger contribution (58.11% in variable contribution and 
#      46.67% in permutation importance) compared with other temperature variables BIO1 and 
#      BIO6. Also, it is known that extremely hot summer prohibit growth of H. fraxineus,
#      while mild and warm summer promote disease progression, while cold temperature in winter
#      does not seem to affect the pathogen, as it has overwintering structure. Also, three 
#      temperature variables are highly correlated with one another, according to the Pearson
#      correlation coefficient. Therefore, BIO1 and BIO6 should not be included.
#     
#      For precipitation variables, BIO17 (Precipitation of Driest Quarter) has significantly 
#      higher contribution (10.13% in variable contribution) than BIO12 and BIO16. BIO17 
#      represents the amount of precipitation in spring and summer which limits the capacity
#      of the fungus to produce spore for reproduction and spread. BIO12 and BIO16 contribute
#      very little to the model
#
# 2. Asian Longhorned Beetle (Anoplophora glabripennis)   
#
# Pick: BIO1 (Annual Mean Temperature), BIO16 (Precipitation of Wettest Quarter), 
#      BIO17 (Precipitation of Driest Quarter)
# Why: BIO1 has a high variable contribution 13.13%, and the highest permutation importance 36.81%.
#      The annual mean temperature affected the beetles' development times and the turnover of 
#      generations. 
#
#      For precipitation variables, BIO16 and BIO17 have significantly higher 
#      contribution to the model than BIO12. They are selected to represent 
#      the effect of excessive moisture and droughts on the efficiency of the pest's
#      ability to infest trees.
#
# 3. Beech Bark Disease (Neonectria faginata)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO17 (Precipitation of Driest Quarter)
# Why: These two variables have significantly larger contribution than other variables. 
#      Neonectria faginata is spread by the beech scale insect (Cryptococcus fagisuga), and
#      this insect's survival is primarily limited by minimum winter temperature becuase of 
#      its limited overwintering capacity.
#
#      Droughts (BIO17) makes host vunlerable to pathogen infection, and increases Neonectria 
#      lesion development.
#
# 4. Beech Leaf Disease (Litylenchus crenatae mccannii)
#
# Pick: BIO1 (Annual Mean Temperature), BIO17 (Precipitation of Driest Quarter)
# Why: BIO1 has the highest contribution and permutation importance among three 
#      temperature variables. Higher mean annual temperatures and warmer dormant 
#      periods may be linked with increased activity of the nematode.
#
#      BIO17 has a significantly higher contribution and permutation importance than 
#      other precipitation variables. Drought conditions  make trees vunlerable to 
#      infections, while also make it less favorable for the nematode itself, which 
#      needs a water film on the leaves to move.
#
# 5. Bronze Birch Borer (Agrilus anxius)
#
# Pick: BIO5 (Max Temperature of Warmest Month), BIO12 (Annual Precipitation)
# Why: Adult borers are more active when it is warm and bask in full sunlight. Though 
#      precipitation of the driest quarter (i.e. droughts)  can increase the tree's 
#      stress levels and thus make the pest attacking the trees, BIO17 shows very low
#      contribution and permutation importance to the model. Instead, BIO12 shows high
#      contribution and permutation importance, working as an approximate for the 
#      effects from drought and excessive moisture.
# 
# 6. Brown Spruce Longhorn Beetle (Tetropium fuscum)
#
# Pick: BIO5 (Max Temperature of Warmest Month)
# Why: This variable contributes significantly to the model. Warmer temperature directly
#      influence the beetle's development rate and voltinism.
#
# 7. Butternut Canker (Ophiognomonia clavigignenti-juglandacearum)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO12 (Annual Precipitation)
# Why: Both BIO5 and BIO6 affect the disease. Maximum temperature poses host 
#      stress on hosts, and at the same time favour spore germination within a 
#      few days. Minimum temperature at the coldest month constraints on the 
#      fungus' ability to spread. Since BIO5 and BIO6 is correlated, we only pick 
#      BIO6 as it has a higher permutation importance to the model.
#
#      Annual precipitation has a significant contribution to the model, especially 
#      for spring and autumn precipitation, which facilitate spore dispersal and 
#      infection.
#
# 8. Dothistroma Needle Blight (Dothistroma septosporum)
#
# Pick: BIO5 (Max Temperature of Warmest Month), 
#       BIO16 (Precipitation of Wettest Quarter),
#       BIO17 (Precipitation of Driest Quarter)
# Why: Dothistroma needle blight is primarily affected by temperature during its active 
#      growing season, namely late spring to summer, and is highly sensitive to 
#      specific optimal temperature ranges combined with high moisture. Also, BIO5
#     (Max Temperature of Warmest Month) have the highest contribution and pemrutation 
#     importance values among temperature variables. Thus it is picked.
#
#     For precipitation variables, the disease is considered to be affected by precipitation 
#     in the wettest quarter, as high levels of precipitation and humidity facilitate spore
#     release, germination, and successful host penetration. However, BIO16 contributes little 
#     to the model. Instead, BIO17 has a high contribution, and dry periods can generally suppress
#     the pathogen development, as the fungus requires moisture for its spore development.
#
# 9. Dutch Elm Disease (Ophiostoma novo-ulmi)
#
# Pick: BIO5 (Max Temperature of Warmest Month)
# Why: The pathogen is primarily affected by summer temperatures, as the fungus and its beetle 
#      vectors thrive in warmer conditions.
#
#      The link between precipitation and dutch elm disease is indirect, and no single precipitation 
#      variable show both high contribution and high permutation importance to the model. Thus 
#      we don't pick any precipitation variables.
#
# 10. Eight Toothed Spruce Bark Beetle (Ips typographus)
#
# Pick: BIO5 (Max Temperature of Warmest Month), BIO17 (Precipitation of Driest Quarter)
# Why: BIO5 has the highest contribution to the model. Warmer conditions accelerate
#      the beetle's development rate and can lead to more generations per year. 
# 
#      BIO17 has the highest contribution to the model in precipitation variables. Droughts
#      weakens the tree's natural defense mechanisms, making it susceptible to beetle's 
#      attacks.
#
# 11. Emerald Ash Borer (Agrilus planipennis)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO12 (Annual Precipitation)
# Why: BIO6 has the highest permutation importance to the model. When the winter 
#      minimum temperature falls beyond a threshold, the borer cannot survive.
#
#      BIO12 (Annual Precipitation) has the highest contribution to the model than 
#      other precipitation variables, thus it is selected. 
#
# 12. Fall Webworm (Hyphantria cunea)
#
# Pick: BIO1 (Annual Mean Temperature), BIO17 (Precipitation of Driest Quarter)
#
# Why: Though minimum winter temperature (affecting the survival of overwintering 
#      pupae) and maximum summer temperature (negatively impact on larval and pupal
#      survival through heatwave stress) can be more correlated, BIO1 has 
#      a significantly higher contribution values to the model than other temperature
#      variables.
#
#      For precipitation variables, BIO17 has the highest contribution value, though 
#      the permutation importance is low. However, the amount of water available in 
#      drier periods is critical to the fall webworm's distribution.
#
# 13. Forest Tent Caterpillar (Malacosoma disstria)
#
# Pick: BIO6 (Min Temperature of Coldest Month),
#       BIO16 (Precipitation of Wettest Quarter),
#       BIO17 (Precipitation of Driest Quarter)
#
# Why:  Extreme cold weather during winter is a primary factor in the mortality 
#       of the overwintering eggs. Also, BIO6 has the highest permutation importance 
#       value to the model in temperature variables.
#
#       Specific timing of precipitation has used because they have higher contribution 
#       to the model than annual precipitation.
#
# 14. Gypsy Moth (Lymantria dispar)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO12 (Annual Precipitation)
# Why: Gypsy moth eggs have a physiological lower lethal temperature. Even short-term 
#      exposure to temperature below this threshold can be lethal.
#
#      Annual precipitation is a major driver of gypsy moth population dynamics.
#      Variable BIO12 has the highest permutation importance in three precipitation 
#      variables.
#
# 15. Hemlock Woolly Adelgid (Adelges tsugae)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO12 (Annual Precipitation)
# Why: The minimum temperature of the coldest month is the most significant factor in
#     determining the insect's northern geographic range and survival is the severity 
#     of cold spells during winter. 
#
#     Variable BIO12 is picked because annual precipitation significantly influences
#     the potential distribution of the pest through affecting host plant presence 
#     range. Also, BIO12 has a relatively high contribution in three precipitation 
#     variables.
#
# 16. Japanese Oak Wilt (Raffaelea quercivora)
#
# Pick: BIO5 (Max Temperature of Warmest Month), BIO12 (Annual Precipitation)
# Why: BIO5 has the highest contribution and permutation importance to the model
#     in three temperature variables. BIO12 has the highest contribution to the 
#     model in precipitation variables, representing  the overall climate zone and
#     available water resources for the pathogen's potential habitat.
#
# 17. Laurel Wilt (Raffaelea lauricola)
#
# Pick: BIO1 (Annual Mean Temperature), BIO12 (Annual Precipitation)
# Why: Though the minimum temperature of the coldest month is the key climatic 
#      variable limiting the northward expansion of laurel wilt disease, annual 
#      mean temperature has the highest contribution to the model.
#
#      For precipitation variables, BIO12 has a significantly higher contribution 
#      and permutation importance to the model.
#      
# 18. Mountain Pine Beetle (Dendroctonus ponderosae)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO17 (Precipitation of Driest Quarter)
# Why: The minimum temperature of the coldest month controls the beetle's survival 
#      as the larvae could not survive in prolonged exposure to extreme low 
#      temperature.
#      
#      Droughts directly impact on host trees, making them more susceptible to beetle 
#      attacks because they cannot produce enough resin to defend themselves.
#
# 19. Oak Decline (Brenneria goodwinii; Gibbsiella quercinecans)
#
# Pick: BIO1 (Annual Mean Temperature), BIO12 (Annual Precipitation)
# Why: The pathogens are more likely to affect warmest regions. Also, the annual 
#      mean temperature contributes significantly to the model compared with other 
#      temperature variables. Similarly, annual precipitation also has the highest 
#      contribution to the model compared with other precipitation variables.
#
# 20. Oak Wilt (Bretziella fagacearum)
#
# Pick: BIO5 (Max Temperature of Warmest Month),
#       BIO12 (Annual Precipitation)
# Why: Summer maximum temperature limits the pathogen's survival as heat can kill
#     the fungus.
#
#     For precipitations variables, though precipitation of the wettest quarter is 
#     known to facilitate fungal sporulation, it has poor contribution to the model.
#     Variable with higher contribution, annual precipitation, is selected.
#
# 21. Oriental Chestnut Gall Wasp (Dryocosmus kuriphilus)
#
# Pick: BIO6 (Min Temperature of Coldest Month)
# Why: BIO6 has the highest contribution to the model in temperature variables. The 
#     minimum temperature of the coldest month significantly reduce wasp population.
#     No single precipitation variables have high contribution to the model, thus 
#     precipitation variables are not selected.
#
# 22. Pine Processionary Moth (Thaumetopea pityocampa)
#
# Pick: BIO6 (Min Temperature of Coldest Month)
# Why: Winter minimum temperature determines the moth's range as cold winter can kill 
#     the larvae. Also, BIO6 has the highest contribution value to the model. No 
#     precipitation variables are selected as all of them contribute little to the 
#     model.
#
# 23. Pine Wood Nematode (Bursaphelenchus xylophilus)
#
# Pick: BIO5 (Max Temperature of Warmest Month), 
#       BIO16 (Precipitation of Wettest Quarter),
#       BIO17 (Precipitation of Driest Quarter)
# Why: BIO5 has the highest contribution value to the model. It is crucial as tree 
#      mortality are highest at warmer temperatures.
#
#      Both BIO16 and BIO17 contribute a lot to the model. Droughts tend to stress 
#      pine trees, making them more susceptible to the disease. In the wettest quarter, 
#      higher precipitation make nematode easier to thrive. 
#
# 24. Red-necked Longhorn Beetle (Dendroctonus valens)
#
# Pick: BIO6 (Min Temperature of Coldest Month)
#       BIO16 (Precipitation of Wettest Quarter)
#       BIO17 (Precipitation of Driest Quarter)
# Why: Studies have consistently identified that the ability of the larvel to tolerant 
#      cold temperature determines its geographical range.
#      
#      Both the precipitation of the wettest quarter and the precipitation of the driest quarter
#      affect the disease through affecting host tree susceptibility and beetles' life 
#      cycle and development rate.
#
# 25. Red Turpentine Beetle (Aromia bungii)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO17 (Precipitation of Driest Quarter)
# Why: BIO6 and BIO17 have the highest contribution to the model. Min temperature of 
#     the coldest month limits the beetles's range and survival. Drought stress make 
#     pine trees less able to produce enough defensive resin to resist beetle attacks.
# 
# 26. Spotted Lanternfly (Lycorma delicatula)
#
# Pick: BIO5 (Max Temperature of Warmest Month), BIO16 (Precipitation of Wettest Quarter)
# Why: BIO5 has the highest contribution and permutation importance to the model. High 
#     summer temperatures are associated with increased mortality of the pest. For 
#     precipitation variables, BIO16 has the highest contribution and permutation importance 
#     to the model.
#
# 27. Spruce Budworm (Choristoneura fumiferana)
#
# Pick: BIO6 (Min Temperature of Coldest Month), BIO16 (Precipitation of Wettest Quarter),
#       BIO17 (Precipitation of Driest Quarter)
# Why: BIO6 has the highest contribution to the model. Extremely low temperatures 
#      cause insect mortality. For precipitation, the pest's population is influenced
#      by seasonal precipitation patterns rather than annual precipitation.
#
# 28. Sudden Oak Death (Phytophthora ramorum)
#
# Pick: BIO5 (Max Temperature of Warmest Month),
#       BIO17 (Precipitation of Driest Quarter)
#       
# Why: The pathogen is strongly affected by the maximum temperature of the warmest 
#      month, as it thrives in cool, moist conditions. For precipitation variables,
#      precipitation of driest quarter contributes significantly to the model. 
#
# 29. Sweet Chestnut Blight (Cryphonectria parasitica)
#
# Pick: BIO5 (Max Temperature of Warmest Month), BIO12 (Annual Precipitation)
# Why: High temperature during the growing season increase the tree's susceptibility 
#      infection and the rate of canker development.
#
#      Annual precipitation has the highest permutation importance to the model 
#      in precipitation variables, although different precipitation variables show 
#      different contribution and permutation importance
#
# 30. White Pine Blister Rust (Cronartium ribicola)
#
# Pick: BIO1 (Annual Mean Temperature), BIO12 (Annual Precipitation)
# Why: Annual mean temperature has a significantly higher contribution value than 
#      other temperature variables. Similarly, annual precipitation has much 
#      larger contribution value than other precipitation variables.
#
# 31. Xylella (Xylella fastidiosa)
#
# Pick: BIO1 (Annual Mean Temperature), BIO16 (Precipitation of Wettest Quarter)
# Why: Annual mean temperature has a significantly higher contribution value than 
#      other temperature variables. Similarly, precipitation of wettest quarter 
#      has the highest contribution value in precipitation variables. 


# ************************************************
#   STEP 4: Run MaxEnt with selected varibles----
# ************************************************

if(!file.exists("results/model_info.RData")){ 
  #identify if these codes have been run
  #if so, it will not be run again
  
  cat("Run MaxEnt with selected bioclimatic variables...\n")
  select_var_list <- tibble(
    file_name = list.files("samples/", full.names = TRUE),
    select_var = c(
      "bio_5,bio_17",        #1. Ash Dieback (Hymenoscyphus fraxineus)
      "bio_1,bio_16,bio_17", #2. Asian Longhorned Beetle (Anoplophora glabripennis)   
      "bio_6,bio_17", #3. Beech Bark Disease (Neonectria faginata)
      "bio_1,bio_17", #4. Beech Leaf Disease (Litylenchus crenatae mccannii)
      "bio_5,bio_12", #5. Bronze Birch Borer (Agrilus anxius)
      "bio_5", #6. Brown Spruce Longhorn Beetle (Tetropium fuscum)
      "bio_6,bio_12", #7. Butternut Canker (Ophiognomonia clavigignenti-juglandacearum)
      "bio_5,bio_16,bio_17", #8. Dothistroma Needle Blight (Dothistroma septosporum)
      "bio_5", #9. Dutch Elm Disease (Ophiostoma novo-ulmi)
      "bio_5,bio_17", #10. Eight Toothed Spruce Bark Beetle (Ips typographus)
      "bio_6,bio_12", #11. Emerald Ash Borer (Agrilus planipennis)
      "bio_1,bio_17", #12. Fall Webworm (Hyphantria cunea)
      "bio_6,bio_16,bio_17", #13. Forest Tent Caterpillar (Malacosoma disstria)
      "bio_6,bio_12", #14. Gypsy Moth (Lymantria dispar)
      "bio_6,bio_12", #15. Hemlock Woolly Adelgid (Adelges tsugae)
      "bio_5,bio_12", #16. Japanese Oak Wilt (Raffaelea quercivora)
      "bio_1,bio_12", #17. Laurel Wilt (Raffaelea lauricola)
      "bio_6,bio_17", #18. Mountain Pine Beetle (Dendroctonus ponderosae)
      "bio_1,bio_12", #19. Oak Decline (Brenneria goodwinii; Gibbsiella quercinecans)
      "bio_5,bio_12", #20. Oak Wilt (Bretziella fagacearum)
      "bio_6", #21. Oriental Chestnut Gall Wasp (Dryocosmus kuriphilus)
      "bio_6", #22. Pine Processionary Moth (Thaumetopea pityocampa)
      "bio_5,bio_16,bio_17", #23. Pine Wood Nematode (Bursaphelenchus xylophilus)
      "bio_6,bio_16,bio_17", #24. Red-necked Longhorn Beetle (Dendroctonus valens)
      "bio_6,bio_17", #25. Red Turpentine Beetle (Aromia bungii)x``
      "bio_5,bio_16", #26. Spotted Lanternfly (Lycorma delicatula)
      "bio_6,bio_17,bio_17", #27. Spruce Budworm (Choristoneura fumiferana)
      "bio_5,bio_17", #28. Sudden Oak Death (Phytophthora ramorum)
      "bio_5,bio_12", #29. Sweet Chestnut Blight (Cryphonectria parasitica)
      "bio_1,bio_12", #30. White Pine Blister Rust (Cronartium ribicola)
      "bio_1,bio_16" #31. Xylella (Xylella fastidiosa)
    )
  )
  
  # Define function to apply masks
  apply_mask <- function(proj, sample_file){
    #Get pest name from 'sample_file'
    pest <- sample_file %>%
      basename() %>%
      strsplit("\\.csv") %>%
      .[[1]] %>%
      gsub("_", " ", .)
    
    #Get world boundary data
    world <- ne_countries(scale = "medium", returnclass = "sf") %>%
      mutate(
        sovereignt = ifelse(sovereignt == "Taiwan", "Chinese Taiwan", sovereignt)
      )
    
    #Read information for output mask
    #  Here mask means that MAXENT prediction on pest distribution should be valid in specific area
    mask_info <- read.csv("../data/results/EID - Occurrence - Supplementary Table S1.csv", skip = 2) %>%
      dplyr::select(Pest.common.name, Potential.damaging.area) %>%
      filter(Potential.damaging.area != "")
    
    #Get mask definition
    mask_def <- mask_info %>%
      filter(Pest.common.name==pest) %>%
      pull(Potential.damaging.area)
    
    #Processing mask information
    if(mask_def!="None"){
      mask_shp <- NULL
      
      #Operating continent mask
      mask_def_continent <- unique(world$continent) %>%
        sapply(grepl, mask_def) %>%
        names(.)[.]
      
      if(length(mask_def_continent)>0){
        mask_shp <- rbind(
          mask_shp,
          world %>% filter(continent %in% mask_def_continent)
        )
      }
      
      #Operating country mask
      mask_def_country <- mask_def %>% strsplit(",") %>%
        .[[1]] %>% trimws() %>%
        sapply(
          function(mask_component) !grepl(paste0("\\b(",paste(unique(world$continent), collapse = "|"), ")\\b"), mask_component)
        ) %>%
        names(.)[.]
      
      mask_russia <- mask_def_country[grepl("Russia", mask_def_country)]
      mask_def_country <- mask_def_country[!grepl("Russia", mask_def_country)]
      
      if(length(mask_russia)>0){
        russia_region <- mask_russia %>% strsplit(":") %>%
          sapply(function(component) trimws(component[2]))
        
        russia_shp <- ne_states(country = "russia", returnclass = "sf") %>%
          filter(region %in% russia_region)
        
        if(!is.null(mask_shp)){
          mask_shp <- mask_shp %>%
            filter(sovereignt!="Russia")
        }
      } else{
        russia_shp <- NULL
      }
      
      if(length(mask_def_country)>0){
        if(any(!(mask_def_country %in% unique(world$sovereignt)))){
          warning(pest," :", "One or some countries not recognised by `rnaturaldata`.\n")
        }
        mask_shp <- rbind(
          mask_shp,
          world %>% filter(sovereignt %in% mask_def_country)
        )
      }
      
      #Special operations
      if(grepl("Europe \\(except Iceland and Russia\\)", mask_def)){
        mask_shp <- mask_shp %>%
          filter(sovereignt!="Iceland" & sovereignt!="Russia")
      } else if(grepl("Europe \\(except Iceland\\)", mask_def)){
        mask_shp <- mask_shp %>%
          filter(sovereignt!="Iceland")
      }
    } else{
      return(proj)
    }
    
    #Apply mask to raster file
    mask_raster <- mask(proj, mask_shp, inverse = TRUE)
    if(!is.null(russia_shp)){
      mask_raster <- mask(mask_raster, russia_shp, inverse = TRUE)
    }
    proj[!is.na(mask_raster)] <- 0
    return(proj)
  }
  
  # Run MaxEnt
  model_info <- tibble(sample_file = c(), thr = c(), Training.AUC = c(), Test.AUC = c())
  for(sample_file in list.files("samples/", full.names = TRUE)){
    cat("Pest or pathogen file =", sample_file, "\n")
    #Get pest name from 'sample_file'
    pest <- sample_file %>%
      basename() %>%
      strsplit("\\.csv") %>%
      .[[1]] %>%
      gsub("_", " ", .)
    
    #Get selected environmental variable names
    selected_vars <- select_var_list %>% 
      filter(grepl(sample_file, file_name)) %>%
      pull(select_var) %>%
      strsplit(",") %>%
      { .[[1]] }
    
    #Select environmental layers
    selected_layers <- selected_vars %>% sapply(
      function(x) {
        pattern <- paste0("_", x, "$")
        names(layers)[grepl(pattern, names(layers))]
      }
    ) %>%
      layers[[.]] %>%
      stack()
    
    # get species occurrence data
    coords <- read.csv(sample_file) %>%
      dplyr::select("dd.long", "dd.lat")
    
    # train MaxEnt model
    mx <- maxent(x = selected_layers, p = coords, a = bg,
                 args = c("randomtestpoints=25"))
    
    # get thresholds and AUC values
    model_info <- rbind(
      model_info,
      tibble(
        sample_file = sample_file, 
        thr = mx@results["Balance.training.omission..predicted.area.and.threshold.value.Cloglog.threshold",],
        Training.AUC = mx@results["Training.AUC",],
        Test.AUC = mx@results["Test.AUC", ]
      )
    )
    
    # make predictions (current distribution)
    cat("Generate current distribution...\n")
    proj <- predict(selected_layers, mx, progress="text")
    proj <- apply_mask(proj, sample_file) # apply mask
    writeRaster(
      proj, paste0("results/", gsub(" ", "_", pest), ".tif"), overwrite = TRUE
    )
    # plot(proj, main="MaxEnt predicted suitability") # to visualise  the result
    
    # make future projections (future distribution)
    cat("Generate future distribution...\n")
    for(ssp in c("ssp126", "ssp245", "ssp370", "ssp585")){
      for(period in c("2041-2060", "2061-2080")){
        cat(ssp, period,"\n")
        GCM_models <- c(
          "ACCESS-CM2", "BCC-CSM2-MR", "CMCC-ESM2", "EC-Earth3-Veg", "GISS-E2-1-G", "INM-CM5-0", "IPSL-CM6A-LR", "MIROC6", "MPI-ESM1-2-HR", "MRI-ESM2-0", "UKESM1-0-LL"
        )
        for(GCM_model in GCM_models){
          cat("GCM_model =", GCM_model, "\n")
          
          list.files("future", full.names = TRUE, pattern = "\\.asc") %>%
            .[grepl(ssp, .) & grepl(period, .)]
          
          future_layers <- selected_vars %>% sapply(
            function(x) {
              list.files("future", full.names = TRUE, pattern = "\\.asc$") %>%
                .[grepl(GCM_model, .)] %>%
                .[grepl(ssp, .)] %>%
                .[grepl(period, .)] %>%
                .[grepl(paste0(x,"_"), .)]
            }
          ) %>%
            as.character() %>%
            stack()
          names(future_layers) <- paste0(
            "wc2.1_10m_", selected_vars
          )
          
          future_proj <- predict(future_layers, mx, progress="text")
          future_proj <- apply_mask(future_proj, sample_file) # apply mask
          writeRaster(
            future_proj, paste0("results/", gsub(" ", "_", pest), "_", ssp, "_", period, "_", GCM_model,".tif"), overwrite = TRUE
          )
        }
        
        #calculate average and sd
        cat("Calculate average and sd.\n")
        future_proj <- list.files("results", pattern = "\\.tif$", full.names = TRUE) %>%
          .[grepl(gsub(" ", "_", pest), .)] %>%
          .[grepl(ssp, .)] %>%
          .[grepl(period, .)] %>%
          stack()
        
        calc(future_proj, fun = mean, na.rm = TRUE) %>%
          writeRaster(paste0("results/", gsub(" ", "_", pest), "_", ssp, "_", period,".tif"), overwrite = TRUE)
        calc(future_proj, fun = sd, na.rm = TRUE) %>%
          writeRaster(paste0("results/", gsub(" ", "_", pest), "_", ssp, "_", period,"_sd.tif"), overwrite = TRUE)
      }
    }
  }
  
  save(model_info, file = "results/model_info.RData")
}



# **************************
#   STEP 5: Figure 1----
# **************************

# Figure 1. Modelled pest richness under current conditions. 
# Presence-only data for 31 major forest pests and pathogens were 
# used as input for the MaxEnt program. A threshold that balance 
# training omission and predicted area for each pest was selected  
# to determine the predicted presence-absence distribution. Then 
# pest richness was calculated by summing the predicted distribution 
# maps across pests.
#

#calculate pest richness
load("results/model_info.RData")
pest_richness <- NULL
for(i in 1:nrow(model_info)){
  pest_name <- model_info[i,] %>%
    pull(sample_file) %>%
    basename() %>%
    gsub(".csv", "", .)
  
  cat("Pest Name = ", pest_name, "\n")
  
  thr <- model_info[i,] %>%
    pull(thr) %>%
    as.numeric()
  
  binary <- lapply(list.files("results/", pattern = paste0("^", pest_name), full.names = TRUE), function(file){
    raster(file) %>%
      {. > thr}
  }) %>%
    stack()
}

names(binary) <- list.files("results/", pattern = paste0("^", pest_name)) %>% 
  gsub("^.*(ssp[0-9]{3}_[0-9]{4}-[0-9]{4}).*$", "\\1", .) %>%
  { .[1] <- "current"; . }

#Draw Figure 1
theme1 <- theme_bw()+
  theme(axis.text.x=element_text(size=13,colour="black"),
        axis.text.y=element_text(size=13,angle=0,colour="black"),
        axis.title=element_text(size=18),
        axis.line=element_blank(),
        axis.ticks = element_line(colour="black"),
        panel.grid.major = element_line(colour = "black", linewidth = 0.2),
        panel.grid.minor = element_blank(), 
        #strip.background = element_rect(colour = "black",size = 0.8),
        #panel.background = element_rect(colour="black", fill="#E2E2E2"),
        panel.border = element_blank(),
        plot.title=element_text(size=14,angle=0,colour="black", face = "italic"),
        plot.tag=element_text(size=14,angle=0,colour="black", face = "bold"),
        plot.caption=element_text(size=14,angle=0,colour="black",face = "italic"),
        axis.title.y=element_text(vjust=1.9),
        axis.title.x=element_text(vjust=0.5),
        legend.text=element_text(colour="black",size=14),
        legend.background= element_rect(fill = "transparent", color = NA),
        #legend.position = "bottom",
        legend.title = element_text(colour="black", size=14,angle=0,margin = margin(b = 10)))

if(!file.exists("results/Figure-1-and-S1-pest-current/Pest_Current.pdf")){
  r_df <- pest_richness %>%
    raster(1) %>%
    projectRaster(crs = "+proj=robin") %>%
    as.data.frame(xy = TRUE) %>%
    rename_with(~ c("lon", "lat", "value"), .cols = 1:3)
  
  g <- ggplot() +
    geom_raster(data = r_df, aes(x = lon, y = lat, fill = value)) +  # 绘制栅格
    geom_sf(data = st_read("../data/tools/continent.shp"), fill = NA, color = "#6F4928", linewidth = 0.05) +
    scale_fill_gradientn(
      colors = c("#EAF1F5", "#FEEFA9", "#FEA346", "#EE3222", "#840027"),  # 冷到暖色调
      limits = c(0, 20),  # 限定值范围
      name = "Pest richness",
      na.value = "transparent"
    ) +
    coord_sf(crs = "+proj=robin") +theme1 + xlab(NULL) +ylab(NULL)
  
  ggsave(filename = "results/Figure-1-and-S1-pest-current/Pest_Current.pdf", 
         plot = g,  
         width = 7.39,
         height = 4.55, 
         units = "in")  
}

# **************************
#   STEP 6: Figure 2----
# **************************

# Figure 2. Projections of changes in pest richness for 2041–2060
# and 2061–2080 under four Shared Socio-economic Pathways (SSPs): 
# ssp126 (the most climate-positive scenario, characterised by low 
# greenhouse gas emissions), ssp245, ssp370, and ssp585 (the most 
# high-emission, climate-negative scenario). A threshold that balance
# training omission and predicted area for each pest was selected  
# to determine the predicted presence-absence distribution. Then 
# pest richness was calculated by summing the predicted distribution 
# maps across pests. Blue and red areas represent regions of decrease 
# and increase in pest richness, respectively. 


result_raster <- (pest_richness[[-1]] - pest_richness[[1]])

if(
  length(list.files("results/Figure-2-change-of-pest-number", pattern = "pdf")) !=
  (nlayers(pest_richness)-1)
){
  for(i in 1:(nlayers(pest_richness)-1)){
    cat("Scenario:", names(pest_richness)[i+1], "\n")
    
    if(grepl("2080", names(pest_richness)[i+1])){
      result_raster <- sign(pest_richness[[i+1]] - pest_richness[[i]])
    } else if(!grepl("ssp126", names(pest_richness)[i+1])){
      result_raster <- sign(pest_richness[[i+1]] - pest_richness[[i-1]])
    } else{
      result_raster <- sign(pest_richness[[i+1]] - pest_richness[[i]])
    }
    
    r_df <- result_raster %>%
      projectRaster(crs = "+proj=robin") %>%
      as.data.frame(xy = TRUE) %>%
      rename_with(~ c("lon", "lat", "value"), .cols = 1:3) %>% drop_na()
    
    g <- ggplot() +
      geom_raster(data = r_df, aes(x = lon, y = lat, fill = factor(value))) + 
      geom_sf(data = st_read("../data/tools/continent.shp"), fill = NA, color = "#6F4928", linewidth = 0.05) +
      scale_fill_manual(
        values = c(
          "-1" = "#1E90FF",  # -1对应蓝色
          "0" = "#EAF1F5",   # 0对应指定颜色
          "1" = "#FF4500"    # 1对应红色
        ),
        name = "Pest richness",  # 可以修改图例名称
        labels = c("-1" = "decrease", "0" = "unchanged", "1" = "increase"),  # 可选：修改图例标签
        na.value = "transparent"
      ) +
      coord_sf(crs = "+proj=robin") +
      theme1 + 
      xlab(NULL) + 
      ylab(NULL)
    
    result_figure_path <- names(pest_richness)[i+1] %>% 
      gsub("\\.", "-", .) %>%
      paste0("Pest_", ., ".pdf") %>%
      paste0("results/Figure-2-change-of-pest-number/", .)
    
    ggsave(filename = result_figure_path, 
           plot = g,  
           width = 7.39,
           height = 4.55, 
           units = "in")  
    
  }
}


# **************************
#   STEP 7: Figure 3----
# **************************

# Figure 3. Probability density functions of changes in pest
# richness (number of pests) for the years 2041–2060 and 2061–2080 
# under four Shared Socio-economic Pathways (SSPs): ssp126 
# (the most climate-positive scenario, characterised by low 
# greenhouse gas emissions), ssp245, ssp370, and ssp585 (the most 
# high-emission, climate-negative scenario). The y-axis is the 
# probability density, indicating the relative likelihood of 
# observing a certain change in pest richness in an arbitrary 
# location. Blue and red areas represent geographic regions with 
# decrease and increase in pest richness, respectively. The sum 
# of the areas of blue and red shaded regions equals to 1, the 
# total probability, representing the complete range of possible 
# changes in pest richness.  

theme1 <- theme_bw()+
  theme(axis.text.x=element_text(size=13,colour="black"),
        axis.text.y=element_text(size=13,angle=0,colour="black"),
        axis.title=element_text(size=18),
        axis.line=element_line(linetype=1,color="black",size=0.1),
        axis.ticks = element_line(colour="black"),
        panel.grid.major = element_blank(), #change the major and minor grid lines,
        panel.grid.minor = element_blank(), #if want to change, check this parameters, I think it's easier to dao that
        #strip.background = element_rect(colour = "black",size = 0.8),
        #panel.background = element_rect(colour="black", fill="white"),
        #panel.border = element_blank(),
        panel.border = element_blank(),
        plot.title=element_text(size=14,angle=0,colour="black", face = "italic"),
        plot.tag=element_text(size=14,angle=0,colour="black", face = "bold"),
        plot.caption=element_text(size=14,angle=0,colour="black",face = "italic"),
        axis.title.y=element_text(vjust=1.9),
        axis.title.x=element_text(vjust=0.5),
        legend.text=element_text(colour="black",size=14),
        legend.background= element_rect(fill = "transparent", color = NA),
        legend.title = element_blank())

for(i in 1:(nlayers(pest_richness)-1)){
  cat("Scenario:", names(pest_richness)[i+1], "\n")
  
  if(grepl("2080", names(pest_richness)[i+1])){
    result_raster <- (pest_richness[[i+1]] - pest_richness[[i]])
  } else if(!grepl("ssp126", names(pest_richness)[i+1])){
    result_raster <- (pest_richness[[i+1]] - pest_richness[[i-1]])
  } else{
    result_raster <- (pest_richness[[i+1]] - pest_richness[[i]])
  }
  
  
  d <- result_raster %>%
    as.data.frame() %>%
    drop_na() %>% 
    rename_with(~ c("value"), .cols = 1) %>%
    filter(value >= 1 | value <= -1) %>%
    pull(value) %>%
    table()
  
  df <- tibble(
    x = as.numeric(names(d)),
    value = as.numeric(d/sum(d)*100)
  ) %>%
    mutate(
      direction = ifelse(x > 0, "increase", "decrease"),
      bar_fill = ifelse(x > 0, "#fc9272", "#6baed6"),
      bar_color = ifelse(x > 0, "#cb181d", "#08519c"),
      label_value = ifelse(x > 0, "increase", "decrease")
    ) %>%
    filter(x>=-5 & x<=5)
  
  g <- ggplot(df, aes(x = factor(x), y = value, fill = direction, color = direction)) +
    geom_bar(stat = "identity", width = 0.9) +
    scale_fill_manual(
      name = "Direction",
      values = c("decrease" = "#6baed6", "increase" = "#fc9272"),
      labels = c("decrease", "increase")
    ) +
    scale_color_manual(
      name = "Direction",
      values = c("decrease" = "#08519c", "increase" = "#cb181d"),
      labels = c("decrease", "increase")
    ) +
    labs(
      x = "Change in pest richness",
      y = "Probability density function (%)"
    ) +
    theme1 +ylim(0,52)
  
  result_figure_path <- names(pest_richness)[i+1] %>% 
    gsub("\\.", "-", .) %>%
    paste0("Pest_", ., ".pdf") %>%
    paste0("results/Figure3-density/", .)
  
  ggsave(filename = result_figure_path, 
         plot = g,  
         width = 4.48,
         height = 1.96, 
         units = "in")  
}

# **************************
#   STEP 8: Figure S2----
# **************************

# Supplementary Figure S2. Projections of forest pest richness under 
# four Shared Socio-economic Pathways (SSP126, SSP245, SSP370, SSP585) 
# for two future periods (2041–2060 and 2061–2080). Color intensity 
# represents pest richness.

theme1 <- theme_bw()+
  theme(axis.text.x=element_text(size=13,colour="black"),
        axis.text.y=element_text(size=13,angle=0,colour="black"),
        axis.title=element_text(size=18),
        axis.line=element_blank(),
        axis.ticks = element_line(colour="black"),
        panel.grid.major = element_line(colour = "black", linewidth = 0.2),
        panel.grid.minor = element_blank(), 
        #strip.background = element_rect(colour = "black",size = 0.8),
        #panel.background = element_rect(colour="black", fill="#E2E2E2"),
        panel.border = element_blank(),
        plot.title=element_text(size=14,angle=0,colour="black", face = "italic"),
        plot.tag=element_text(size=14,angle=0,colour="black", face = "bold"),
        plot.caption=element_text(size=14,angle=0,colour="black",face = "italic"),
        axis.title.y=element_text(vjust=1.9),
        axis.title.x=element_text(vjust=0.5),
        legend.text=element_text(colour="black",size=14),
        legend.background= element_rect(fill = "transparent", color = NA),
        #legend.position = "bottom",
        legend.title = element_text(colour="black", size=14,angle=0,margin = margin(b = 10)))

if(
  length(list.files("results/Figure-S2-future-pest-range", pattern = "pdf")) !=
  (nlayers(pest_richness)-1)
){
  for(i in 1:(nlayers(pest_richness)-1)){
    cat("Scenario:", names(pest_richness)[i+1], "\n")
    
    r_df <- pest_richness[[i+1]] %>%
      projectRaster(crs = "+proj=robin") %>%
      as.data.frame(xy = TRUE) %>%
      rename_with(~ c("lon", "lat", "value"), .cols = 1:3)
    
    g <- ggplot() +
      geom_raster(data = r_df, aes(x = lon, y = lat, fill = value)) +  # 绘制栅格
      geom_sf(data = world, fill = NA, color = "#6F4928", linewidth = 0.05) +
      scale_fill_gradientn(
        colors = c("#EAF1F5", "#FEEFA9", "#FEA346", "#EE3222", "#840027"),  # 冷到暖色调
        limits = c(0, 20),  # 限定值范围
        name = "Pest richness",
        na.value = "transparent"
      ) +
      coord_sf(crs = "+proj=robin") +theme1 + xlab(NULL) +ylab(NULL)
    
    result_figure_path <- names(pest_richness)[i+1] %>% 
      gsub("\\.", "-", .) %>%
      paste0("Pest_", ., ".pdf") %>%
      paste0("results/Figure-S2-future-pest-range/", .)
    
    ggsave(filename = result_figure_path, 
           plot = g,  
           width = 7.39,
           height = 4.55, 
           units = "in")  
  }
}

# *******************************
#   STEP 9: Figure 4, S3, S4-----
# *******************************
theme1 <- theme_bw()+
  theme(axis.text.x=element_text(size=13,colour="black"),
        axis.text.y=element_text(size=13,angle=0,colour="black"),
        axis.title=element_text(size=18),
        axis.line=element_blank(),
        axis.ticks = element_line(colour="black"),
        panel.grid.major = element_line(colour = "grey", linewidth = 0.2),
        panel.grid.minor = element_blank(), 
        #strip.background = element_rect(colour = "black",size = 0.8),
        #panel.background = element_rect(colour="black", fill="#E2E2E2"),
        panel.border = element_blank(),
        plot.title=element_text(size=18,angle=0,colour="black", face = "bold",hjust = 0.5),
        plot.tag=element_text(size=14,angle=0,colour="black", face = "bold"),
        plot.caption=element_text(size=14,angle=0,colour="black",face = "italic"),
        axis.title.y=element_text(vjust=1.9),
        axis.title.x=element_text(vjust=0.5),
        legend.text=element_text(colour="black",size=14),
        legend.background= element_rect(fill = "transparent", color = NA),
        #legend.position = "bottom",
        legend.title = element_text(colour="black", size=14,angle=0,margin = margin(b = 10)))

load("results/model_info.RData")
for(i in 1:nrow(model_info)){
  pest_name <- model_info[i,] %>%
    pull(sample_file) %>%
    basename() %>%
    gsub(".csv", "", .)
  
  cat("Pest Name = ", pest_name, "\n")
  
  proboccur <- lapply(list.files("results/", pattern = paste0("^", pest_name), full.names = TRUE), function(file){
    raster(file)
  }) %>%
    stack()
  
  names(proboccur) <- list.files("results/", pattern = paste0("^", pest_name)) %>% 
    gsub("^.*(ssp[0-9]{3}_[0-9]{4}-[0-9]{4}).*$", "\\1", .) %>%
    { .[1] <- "current"; . }
  
  # Figure S3
  r_df <- proboccur[[1]] %>%
    projectRaster(crs = "+proj=robin") %>%
    as.data.frame(xy = TRUE) %>%
    rename_with(~ c("lon", "lat", "value"), .cols = 1:3)
  
  g <- ggplot() +
    geom_raster(data = r_df, aes(x = lon, y = lat, fill = value)) +  # 绘制栅格
    geom_sf(data = st_read("../data/tools/continent.shp"), fill = NA, color = "#6F4928", linewidth = 0.05) +
    scale_fill_gradientn(
      colors = c("#EAF1F5", "#FEEFA9", "#FEA346", "#EE3222", "#840027"),  # 冷到暖色调
      limits = c(0, 1),  # 限定值范围
      name = "Probability\nof occurrence",
      na.value = "transparent"
    ) + ggtitle(pest_name %>% gsub("_"," ",.))+
    coord_sf(crs = "+proj=robin") +theme1 + xlab(NULL) +ylab(NULL)

  result_figure_path <- pest_name %>% 
    paste0(., ".pdf") %>%
    paste0("results/Figure-S3/", .)
  
  ggsave(filename = result_figure_path, 
         plot = g,  
         width = 7.39,
         height = 4.55, 
         units = "in") 
  
  # Figure 4, S4
  for(i in 2:nlayers(proboccur)){
    cat("Scenario =", names(proboccur)[i], "\n")
    
    result_raster <- proboccur[[i]] - proboccur[[1]]
    result_raster[result_raster >= 0.01] <- 1    # areas of increase
    result_raster[result_raster <= -0.01] <- -1   # areas of decrease
    result_raster[result_raster < 0.01 & result_raster > -0.01] <- 0   # areas of unchange
    
    
    r_df <- result_raster %>%
      projectRaster(crs = "+proj=robin") %>%
      as.data.frame(xy = TRUE) %>%
      rename_with(~ c("lon", "lat", "value"), .cols = 1:3) %>%
      drop_na()
    
    g <- ggplot() +
      geom_raster(data = r_df, aes(x = lon, y = lat, fill = factor(value))) + 
      geom_sf(data = st_read("../data/tools/continent.shp"), fill = NA, color = "#6F4928", linewidth = 0.05) +
      scale_fill_manual(
        values = c(
          "-1" = "#1E90FF",  # -1对应蓝色
          "0" = "#EAF1F5",   # 0对应指定颜色
          "1" = "#FF4500"    # 1对应红色
        ),
        name = "Probability\nof occurrence",  # 可以修改图例名称
        labels = c("-1" = "decrease", "0" = "unchanged", "1" = "increase"),  # 可选：修改图例标签
        na.value = "transparent"
      ) +
      coord_sf(crs = "+proj=robin") +
      theme1 + 
      xlab(NULL) + 
      ylab(NULL)
    
    result_figure_path <- pest_name %>%
      paste0(., "_", names(proboccur)[i] %>% gsub("\\.", "-", .), ".pdf") %>%
      paste0("results/Figure-S4/", .)
    
    ggsave(filename = result_figure_path, 
           plot = g,  
           width = 7.39,
           height = 4.55, 
           units = "in") 
    
  }
}

# ****************************************
#   STEP 10: Figure S5 Response Curve-----
# ****************************************

for(
  sample_file in c(
    "samples/Ash_Dieback.csv",
    "samples/Asian_Longhorned_Beetle.csv",
    "samples/Dutch_Elm_Disease.csv",
    "samples/Emerald_Ash_Borer.csv",
    "samples/Sweet_Chestnut_Blight.csv"
  )
){
  cat("Pest or pathogen file =", sample_file, "\n")
  
  pest <- sample_file %>%
    basename() %>%
    strsplit("\\.csv") %>%
    .[[1]] %>%
    gsub("_", " ", .)
  
  #Select environmental layers
  selected_layers <- raster("layers/wc2.1_10m_bio_14.asc")
  
  # get species occurrence data
  coords <- read.csv(sample_file) %>%
    dplyr::select("dd.long", "dd.lat")
  
  # train MaxEnt model
  mx <- maxent(x = selected_layers, p = coords, a = bg,
               args = c("randomtestpoints=25"))
  
  # generate response curve
  response(mx, main = paste0("Response of ", pest, " to ", names(selected_layers)))
}

# ****************************************
#   STEP 11: Estimate spread rate (result text)-----
# ****************************************

## Corresponding text in the paper:
## Between 2041 – 2080 we found that pests and pathogens are expected to expand into new areas at a rate of 
## 11,686 km2/year under the green emissions (SSP126) scenario and 59,663 km2/year under the fossil 
## fuel (SSP585) scenario.
list.files("results")

pests <- list.files("samples") %>%
  sub("\\.csv$", "", .)
load("results/model_info.RData")

#calculate pest area under certain ssp and certain period
calc_pest_new_area <- function(pest = "Ash_Dieback", ssp = "ssp126", thr = 0.1){
  if(pest=="Oak_Wilt"){
    old_st <- list.files("results", pattern = "\\.tif$", full.names = TRUE) %>% #make sure file direction is correct
      .[grepl(pest, .)] %>%
      .[!grepl("Japanese_Oak_Wilt", .)] %>%
      .[grepl("2041-2060", .)] %>%
      .[!grepl(paste0("2041-2060","\\.tif$"), .)] %>%  # remove the file for averaged result from 11 GCM models
      .[grepl(ssp, .)] %>%
      .[!grepl("_sd", .)] %>% #remove sd file
      stack()
    
    new_st <- list.files("results", pattern = "\\.tif$", full.names = TRUE) %>% #make sure file direction is correct
      .[grepl(pest, .)] %>%
      .[!grepl("Japanese_Oak_Wilt", .)] %>%
      .[grepl("2061-2080", .)] %>%
      .[!grepl(paste0("2061-2080","\\.tif$"), .)] %>%  # remove the file for averaged result from 11 GCM models
      .[grepl(ssp, .)] %>%
      .[!grepl("_sd", .)] %>% #remove sd file
      stack()
  } else{
    old_st <- list.files("results", pattern = "\\.tif$", full.names = TRUE) %>% #make sure file direction is correct
      .[grepl(pest, .)] %>%
      .[grepl("2041-2060", .)] %>%
      .[!grepl(paste0("2041-2060","\\.tif$"), .)] %>%  # remove the file for averaged result from 11 GCM models
      .[grepl(ssp, .)] %>%
      .[!grepl("_sd", .)] %>% #remove sd file
      stack()
    
    new_st <- list.files("results", pattern = "\\.tif$", full.names = TRUE) %>% #make sure file direction is correct
      .[grepl(pest, .)] %>%
      .[grepl("2061-2080", .)] %>%
      .[!grepl(paste0("2061-2080","\\.tif$"), .)] %>%  # remove the file for averaged result from 11 GCM models
      .[grepl(ssp, .)] %>%
      .[!grepl("_sd", .)] %>% #remove sd file
      stack()
  }

  
  old_st_binary <- (old_st > thr)
  new_st_binary <- (new_st > thr)
  new_habitat <- (!old_st_binary & new_st_binary)
  cell_area_km2 <- new_habitat[[1]] %>% area()
  sum_area_km2 <- cellStats(new_habitat * cell_area_km2, stat = "sum", na.rm = TRUE) %>%
    as.numeric()
  
  return(sum_area_km2)
}

#tranversing pests
area_km2_summary <- tibble()
for(pest in pests){
  cat("pest =", pest,"\n")
  
  if(pest=="Oak_Wilt"){
    thr <- model_info %>%
      filter(grepl(pest, sample_file)) %>%
      filter(!grepl("Japanese_Oak_Wilt", sample_file)) %>%
      pull(thr) %>%
      as.numeric()
  } else{
    thr <- model_info %>%
      filter(grepl(pest, sample_file)) %>%
      pull(thr) %>%
      as.numeric()
  }

  
  rate_ssp126 <- calc_pest_new_area(pest, ssp = "ssp126", thr = thr)/20
  rate_ssp585 <- calc_pest_new_area(pest, ssp = "ssp585", thr = thr)/20
  
  area_km2_summary <- rbind(
    area_km2_summary,
    tibble(
      pest = pest,
      model = 1:11,
      rate_ssp126 = rate_ssp126,
      rate_ssp585 = rate_ssp585
    )
  )
}

mean_rate_ssp126 <- mean(area_km2_summary$rate_ssp126)
mean_rate_ssp585 <- mean(area_km2_summary$rate_ssp585)
sd_rate_ssp126 <- area_km2_summary %>%
  dplyr::select(pest, model, rate_ssp126) %>%
  group_by(model) %>%
  summarise(
    mean_rate_ssp126 = mean(rate_ssp126, na.rm = TRUE)
  ) %>%
  ungroup() %>%
  summarise(
    sd_rate_ssp126 = sd(mean_rate_ssp126, na.rm = TRUE)
  )
sd_rate_ssp585 <- area_km2_summary %>%
  dplyr::select(pest, model, rate_ssp585) %>%
  group_by(model) %>%
  summarise(
    mean_rate_ssp585 = mean(rate_ssp585, na.rm = TRUE)
  ) %>%
  ungroup() %>%
  summarise(
    sd_rate_ssp585 = sd(mean_rate_ssp585, na.rm = TRUE)
  )
