#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# PART 1: Fitting tree mortality and defoliation curves
#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Run the script file in the folder "./Ash_dieback_model"
# Required data inputs:
# * "EID - Severity - Measure.csv": raw data for tree defoliation and mortality from field survey papers
#
# Outputs:
# * "p_death_defoliated_model.RData": parameters for describing tree mortality and defoliation curves (input for Part 2 epidemiological model)

library(tidyverse)
setwd("D:/DPhil/Paper 3/Ash_dieback_model")

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ---- STEP1: DATA IMPORT AND DEFINE ESSENTIAL FUNCTIONS
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Data import
# * Raw data on disease infection rate, severity, and tree mortality, summarised 
#     through a systematic review from DPhil Paper 1
df <- read.csv("EID - Severity - Measure.csv")

# Data screening
# * Data points without knowing the first infection time are excluded.
# * Data points that do not focus on disease severity or tree mortality are excluded.
# * Data points that do not focus on natural forests or plantations are excluded.
#
# NOTE: Please change the 'Disease' name when analysing another pest
df_filtered <- df %>% 
  filter(Disease == "Ash dieback") %>%
  filter(First.Confirmed != "") %>%
  filter(Std.Value != "#N/A") %>%
  filter(Std.Measurement %in% c("severity (%)", "mortality (%)")) %>%
  filter(Covariate == "") %>%
  filter(grepl("natural forest", Type) | grepl("plantation", Type))

# Calculating Years
# * To calculate the year since the disease firstly occurred.
df_calc <- df_filtered %>%
  dplyr::select(Cite,Std.Measurement,Std.Value, First.Confirmed, M..Time, LngLat) %>%
  mutate(
    # Extract first 4-digit year from each column
    Year.First.Confirmed = sapply(str_extract_all(First.Confirmed, "\\d{4}"),
                                  function(x) mean(as.numeric(x), na.rm = TRUE)),
    Year.M..time = sapply(str_extract_all(M..Time, "\\d{4}"),
                          function(x) mean(as.numeric(x), na.rm = TRUE)),
    # Compute year difference
    Since.Infected = Year.M..time - Year.First.Confirmed
  ) %>%
  mutate(Std.Value = as.numeric(Std.Value))

# Define the function to make final plots
plot.nls <- function(fit, boot_series = NULL, xlim = NULL){
  data <- fit$data %>% get()
  
  x_max <- ifelse(is.null(xlim), max(data$Since.Infected),max(xlim))
  newdata <- tibble(Since.Infected = seq(min(data$Since.Infected),
                                         x_max,
                                         length.out = 200))
  newdata$fit <- predict(fit, newdata)
  
  y_label <- (fit$data %>% 
             as.character() %>% 
             strsplit("_") %>% 
             .[[1]])[2] %>% 
    str_to_title() %>% 
    paste("(%)")
  
  if(y_label == "Severity (%)"){
    y_label <- "Defoliation (%)"
  }
  
  theme1 <- theme_bw()+
    theme(axis.text.x=element_text(size=16,angle=0,colour="black"),
          axis.text.y=element_text(size=16,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_rect(colour = "black",fill=NA,size = 1.2),
          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))
  
  if(!is.null(boot_series)){
    boot_summary<- boot_series %>%
      group_by(Since.Infected) %>%
      summarise(
        fit_min = min(fit), #quantile(fit, probs = 0.05),
        fit_max = max(fit), #quantile(fit, probs = 0.95)
      )
    
    p <- data %>% ggplot(aes(x = Since.Infected, y = Std.Value)) +
      geom_point(data = data, aes(x = Since.Infected, y = Std.Value), size = 1.5) +
      geom_line(data = newdata, aes(y = fit), color = "red", size = 1) +
      geom_ribbon(data = boot_summary, 
                  aes(x = Since.Infected, ymax = fit_max, ymin = fit_min),
                  inherit.aes = FALSE,
                  alpha = 0.6, fill = "grey") +
      theme_minimal() +
      labs(x = "Years since infection",
           y = y_label) +
      theme1
  } else{
    p <- data %>%
      ggplot(aes(x = Since.Infected, y = Std.Value)) +
      geom_point(size = 1.5) +
      geom_line(data = newdata, aes(y = fit), color = "red", size = 1) +
      theme_minimal() +
      labs(x = "Years since infection",
           y = y_label) +
      theme1
  }
  
  if(!is.null(xlim)){
    p <- p + xlim(xlim)
  }
  p
}

# Clean unnecessary variables
rm(df, df_filtered)

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ---- STEP2: FIT SEVERSITY CURVE WITH LOGISTIC FUNCTION
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Get disease severity data and visualise it
# * A small percent of studies last for very long time, and may biase the result.
#      They should be excluded
(df_severity <- df_calc %>%
  filter(Std.Measurement == "severity (%)") %>%
  filter(Cite != "Pliura et al. 2017")) %>%
  ggplot(aes(x = Since.Infected, y = Std.Value)) +
  geom_point()

# Fit logistic model
fit_severity <- nls(
  Std.Value ~ SSlogis(Since.Infected, phi1, phi2, phi3),
  data = df_severity,
  start = list(phi1 = 60, phi2 = 1, phi3=1)
)

# Visualisation
plot(fit_severity, xlim = c(0, 30))

# Bootstrap
boot <- 1
boot_series_severity <- tibble()
if(file.exists("boot_series_severity.RData")){
  load("boot_series_severity.RData")
} else{
  while (boot <= 1000) {
    if(boot %% 100 == 0){
      cat("boot =", boot, "\n")
    }
    
    df_boot <- df_severity %>%
      slice(sample(1:nrow(df_severity), replace = TRUE))
    
    fit_boot <- tryCatch(
      nls(
        Std.Value ~ SSlogis(Since.Infected, phi1, phi2, phi3),
        data = df_boot,
        start = list(phi1 = 50, phi2 = 1, phi3 = 1)
      ),
      error = function(e) NULL
    )
    
    if (is.null(fit_boot)) {
      next
    }
    
    newdata <- tibble(
      Since.Infected = seq(min(df_boot$Since.Infected), 30,
                           length.out = 30)
    )
    newdata$fit <- predict(fit_boot, newdata)
    
    boot_series_severity <- rbind(
      boot_series,
      newdata %>%
        mutate(iteration = boot)
    )
    
    boot <- boot + 1
  }
  save(boot_series_severity, file = "boot_series_severity.RData")
}



# Visualise bootstrap result
plot(fit_severity, boot_series = boot_series_severity, xlim = c(0, 30))

# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# ---- STEP3: FIT MORTALITY CURVE WITH LOGISTIC FUNCTION
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

# Get disease mortality data and visualise it
(df_mortality <- df_calc %>%
    filter(
      Std.Measurement == "mortality (%)",
      Cite != "Pliura et al. 2017",
      Since.Infected >=1)
  ) %>%
  ggplot(aes(x = Since.Infected, y = Std.Value)) +
  geom_point()

# Fit logistic model
fit_mortality <- nls(
  Std.Value ~ SSlogis(Since.Infected, phi1, phi2, phi3),
  data = df_mortality,
  start = list(phi1 = 50, phi2 = 1, phi3=1)
)

# Visualisation
plot(fit_mortality, xlim = c(0, 30))

# Bootstrap
boot <- 1
boot_series_mortality <- tibble()
if(file.exists("boot_series_mortality.RData")){
  load("boot_series_mortality.RData")
} else{
  while (boot <= 99999) {
    if(boot %% 100 == 0){
      cat("boot =", boot, "\n")
    }
    
    df_boot <- df_mortality %>%
      slice(sample(1:nrow(df_mortality), replace = TRUE))
    
    fit_boot <- tryCatch(
      nls(
        Std.Value ~ SSlogis(Since.Infected, phi1, phi2, phi3),
        data = df_boot,
        start = list(phi1 = 50, phi2 = 1, phi3 = 1)
      ),
      error = function(e) NULL
    )
    
    if (is.null(fit_boot)) {
      next
    }
    
    newdata <- tibble(
      Since.Infected = seq(min(df_boot$Since.Infected), 30,
                           length.out = 30)
    )
    newdata$fit <- predict(fit_boot, newdata)
    
    boot_series_mortality <- rbind(
      boot_series,
      newdata %>%
        mutate(iteration = boot)
    )
    
    boot <- boot + 1
  }
  save(boot_series_mortality, file = "boot_series_mortality.RData")
}


# Visualise bootstrap result
plot(fit_mortality, boot_series = boot_series_mortality, xlim = c(0, 30))

# Save fitted model
save(fit_severity, fit_mortality, file = "p_death_defoliated_model.RData")

