#_____________________________________________________________________________
# Script created by Melisa A. Suans, contact at suans.melisa@gmail.com
# R version: 4.4.1
# Version of packages presented in data analysis section of the manuscript
#____________________________________________________________________________

# Set working directory, install and load packages, import dataset from Excel
"Survival_data"

#____________________________________________________________________________

# Data analysis and figures for Experiment 1: Survival in M. nortoni males and females

#____________________________________________________________________________
# Load packages
library(EnvStats) 
library(outliers)
library(flexsurv)
library(dplyr)
library(ggplot2) 
library(sjPlot)
library(ggsurvfit) 
library(survival) 
library(survminer)
library(SurvRegCensCov)
library(gtsummary)
library(lattice)
library(lsmeans)
library(readxl)
library(rstatix)
library(outliers)
library(tidyverse)
library(car)
library(splines)
library(flexsurv)

# Ggplot2 theme for figures
theme_set(theme_classic(base_size = 12, base_family = 'sans') +
             theme(axis.title.x = element_text(size=12, face="plain", 
                                               colour = "black"), 
                   axis.title.y = element_text(size=12, face="plain",
                                               colour = "black"),    
                   axis.line.x = element_line(color="black", linewidth = 0.3),
                   axis.line.y = element_line(color="black", linewidth = 0.3),
                   plot.title=element_text(size=12, face="bold"),
                   panel.spacing = unit(0.9, 'lines'),
                   legend.margin = margin(0, 0, 0, -15)))

# Import data
survival_table <- read_excel("Survival_data.xlsx", 
                             col_types = c("text", "numeric", "numeric", 
                                           "text", "text", "numeric", "numeric", 
                                           "numeric"))
View(survival_table)

# Categorical variables to factors
survival_table$Diet <- factor(survival_table$Diet)
survival_table$Sex <- factor(survival_table$Sex)

# Change the reference
survival_table$Diet = relevel(survival_table$Diet, ref = "Water")
survival_table$Sex = relevel(survival_table$Sex, ref = "Male")

# --> Explore the Hind tibia length covariate ####
# Testing normality and homogeneity
shapiro_test(survival_table$Hind_tibia_length)
survival_table %>% group_by (Diet) %>% shapiro_test(Hind_tibia_length)

levene_test(survival_table, Hind_tibia_length ~ Diet, center=mean)
survival_table %>%  levene_test(Hind_tibia_length ~ Diet)

# Outliers for hind tibia length
ggplot(survival_table) +
   aes(x = Sex, y = Hind_tibia_length, fill = Diet) +
   geom_boxplot() +
   theme_minimal()
ggplot(survival_table) +
  aes(x = Sex, y = Time, fill = Diet) +
  geom_boxplot() +
  theme_minimal()

boxplot.stats(survival_table$Hind_tibia_length)$out
boxplot.stats(survival_table$Time)$out

out <- boxplot.stats(survival_table$Hind_tibia_length)$out
out <- boxplot.stats(survival_table$Time)$out

out_ind <- which(survival_table$Hind_tibia_length %in% c(out))
out_ind <- which(survival_table$Time %in% c(out))
out_ind

# Rosner's test
test <- rosnerTest(survival_table$Hind_tibia_length, k = 10)
test <- rosnerTest(survival_table$Time, k = 100)
test

# Grubbs's test
test <- grubbs.test(survival_table$Hind_tibia_length)
test

test <- grubbs.test(survival_table$Hind_tibia_length, opposite = TRUE)
test

# Distributions 
hist(survival_table$Hind_tibia_length)
hist(survival_table$Head_width)

# Summary stats of hind tibia length
my_sum <- survival_table %>%
   group_by(Sex, Diet) %>%
   get_summary_stats(Hind_tibia_length, type = "full")

print(my_sum)
my_sum
View(my_sum)

# Mean + SE
my_sum <- survival_table %>% 
   group_by(Diet, Sex) %>% 
   summarise(mean= mean(Hind_tibia_length),
             se = sd(Hind_tibia_length)/sqrt(n()), .groups = 'drop')

my_sum <- survival_table %>% 
  group_by(Diet, Sex) %>% 
  summarise(mean= mean(Torax_width),
            se = sd(Torax_width)/sqrt(n()), .groups = 'drop')

my_sum

# Barplot
barplot <- my_sum %>% 
   ggplot(aes(x = Sex, y = mean, fill = Diet))+
   geom_col( position = "dodge", width = 0.5, alpha = 0.7, color = "black", 
             linewidth = 0.1)+
   geom_errorbar(aes(ymin = mean-se, ymax = mean+se),
                 position =  position_dodge(width = 0.5), width = 0.2)
barplot

# Boxplot
ggplot(survival_table, aes(x=Sex, y=Hind_tibia_length, fill=Diet)) + 
   geom_boxplot()

ggplot(survival_table, aes(x=Diet, y=Time, fill=Sex)) + 
   geom_boxplot()

# ANOVA test for hind tibia length
model <- aov(survival_table$Hind_tibia_length ~ survival_table$Diet + 
               survival_table$Sex)
# model <- aov(survival_table$Head_width ~ survival_table$Diet + 
               # survival_table$Sex)
summary(model)
anova(model)

# Pairwise comparisons
lsm <- lsmeans(model, ~ Diet + Sex)
summary(lsm, type = "response") 

plot(lsm, intervals = TRUE, int.adjust = "none", comparisons = TRUE)

# Interaction plot of the least-squares means based on the fitted model
lsmip(model, Diet ~ Sex) # Observed 
lsmip(lsm, Diet ~ Sex) # Predicted
lsmip(lsm, Diet ~ Sex, type = "response")

# LSmeans post hoc comparisons
pairs <- pairs(lsm, reverse = TRUE, type = "response", 
               infer = c(TRUE, TRUE))
pairs

# Define custom breaks
custom_breaks <- c(4, 6, 10)

# Create a new column variable for Hind tibia length(factor)
survival_table <- survival_table %>% 
  mutate(
    HTL = cut(Hind_tibia_length, 
              breaks = custom_breaks, 
              labels = c("Small", "Large"))) # 0 small, 1 large

# Survival analysis ####
# Explore time variable
hist(survival_table$Time)

# Summary stats of time
my_sum <- survival_table %>%
  group_by(Diet, Sex) %>%
  get_summary_stats(Time, type = "full")

print(my_sum)

# Mean + SE
my_sum <- survival_table %>% 
  group_by(Diet, Sex) %>% 
  summarise(mean= mean(Time),
            se = sd(Time)/sqrt(n()), .groups = 'drop')
my_sum

# Barplot
barplot <- my_sum %>% 
  ggplot(aes(x = Sex, y = mean, fill = Diet))+
  geom_col( position = "dodge", width = 0.5, alpha = 0.7, 
            color = "black", linewidth = 0.1)+
  geom_errorbar(aes(ymin = mean-se, ymax = mean+se),
                position =  position_dodge(width = 0.5), width = 0.2)
barplot

# Centering continuous variables around its mean
survival_table$Hind_tibia_length <- survival_table$Hind_tibia_length - 
  mean(survival_table$Hind_tibia_length , na.rm = T)

# Exclude the most influential value
survival_table <- survival_table[-c(9),] # Huge wasp

# Non-parametric tests ####
levels(survival_table$Sex)
levels(survival_table$Diet)

# The kaplan-Meier survival curves
fit <- survfit(Surv(Time, Status) ~ Diet + Sex, data = survival_table)
print(fit)
summary(fit)

ggsurv <- ggsurvplot(fit, conf.int = FALSE, surv.median.line = "hv")

ggsurv$plot + theme_classic() + facet_wrap(~factor(Sex, c("Male", "Female"))) +
   labs(
      x = "Time (days)",
      y = "Survival probability") +
   theme( 
         axis.line.x = element_line(color="black", linewidth = 0.3),
         axis.line.y = element_line(color="black", linewidth = 0.3))

ggsurv$plot + theme_classic() + facet_wrap(~factor(Sex, c("Male", "Female"))) +
  labs(
    x = "Time (days)",
    y = "Survival probability") +
  theme( 
    axis.line.x = element_line(color="black", linewidth = 0.3),
    axis.line.y = element_line(color="black", linewidth = 0.3))

ggsave(
  "survival_curves.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 20,
  height = 9,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# Median survival times
survfit2(Surv(Time, Status) ~ Diet + Sex, data = survival_table)

summary(fit)$table

survfit2(Surv(Time, Status) ~ Diet + Sex, data = subdata2) %>% 
   tbl_survfit(
      probs = 0.5,
      label_header = "**Median survival (95% CI)**"
   )

# Log-Rank test comparing survival curves: survdiff()
surv_diff <- survdiff(Surv(Time, Status) ~ Diet, data = survival_table)
surv_diff

# Log-log survival curves
fit <- survfit(Surv(Time, Status) ~ Diet, data = survival_table)

plot(fit, fun = "cloglog", xlab = "Time (in days) using log",
     ylab = "log-log survival", main = "log-log curves by Diet") 

ggsurvplot(fit, fun = "cloglog")

# Semiparametric Cox proportional hazard model ####
res.cox1 <- coxph(Surv(Time, Status) ~ Diet*Sex*Hind_tibia_length, 
                  data = survival_table, ties = "efron")
res.cox1
summary(res.cox1)

# Backward model selection
res.cox2 <- update(res.cox1, ~ . - Diet:Sex:Hind_tibia_length)
summary(res.cox2)
anova(res.cox2)

res.cox3 <- update(res.cox2, ~ . - Diet:Sex)
summary(res.cox3)
anova(res.cox3)

# AIC
AIC(res.cox1, res.cox2, res.cox3)

table <- coxph(Surv(Time, Status) ~ Diet + Sex + Hind_tibia_length + 
                 Diet*Hind_tibia_length + Sex*Hind_tibia_length, 
               data =  survival_table) %>% 
  tbl_regression(exp = TRUE) 
table

# Proportionality assumption #
test.ph <- cox.zph(res.cox3, transform="km", terms=TRUE)
test.ph <- cox.zph(res.cox3, transform="identity", terms=TRUE)
test.ph <- cox.zph(res.cox3, transform="rank", terms=TRUE)
print(test.ph) # the proportional hazard assumption is violated

# Diet
par(mfrow=c(1,1)) 
plot((test.ph) [1])
abline(h=0, col=2)

# Sex
plot((test.ph)[2])
abline(h=0, col=2)

# Hind tibia length
plot((test.ph)[3])
abline(h=0, col=2)

# Testing not linearity for continuous covariates #
Y <- resid(res.cox3, type = "martingale")
X <- survival_table$Hind_tibia_length
plot(Y ~ X, pch = 20, col = "darkgray",
     ylab = "Martingale Residual",
     xlab = "Hind tibia length (mm)",
     main = "Residuals vs. Predictor")
abline(h = 0)
lines(smooth.spline(Y ~ X, df = 3), lty = 2, lwd = 2)
lines(smooth.spline(Y ~ X, df = 2), lty = 2, lwd = 2)

# We decided to explore and use parametric tests

# Parametric tests ####
# Exponential distribution
exp1 <- survreg(Surv(Time, Status) ~ Diet*Sex*Hind_tibia_length, 
                  data = survival_table, dist = "exponential")
summary(exp1) # complex model
anova(exp1)

# Backward model selection
exp2 <- update(exp1, ~ . - Diet:Sex:Hind_tibia_length)
anova(exp2, exp1, test="Chisq")
summary(exp2)
anova(exp2)

exp3 <- update(exp2, ~ . - Diet:Sex)
anova(exp3, exp2, test="Chisq")
summary(exp3)

exp4 <- update(exp3, ~ . - Diet:Hind_tibia_length)
anova(exp4, exp3, test="Chisq")
summary(exp4)
anova(exp4)

exp5 <- update(exp4, ~ . - Sex:Hind_tibia_length)
anova(exp5, exp4, test="Chisq")
summary(exp5)
anova(exp5)

exp6 <- update(exp5, ~ . - Sex)
anova(exp6, exp5, test="Chisq")
summary(exp6)
anova(exp6)

exp7 <- update(exp6, ~ . - Hind_tibia_length)
anova(exp7, exp6, test="Chisq")
summary(exp7)
anova(exp7)

# Weibull distribution
wei1 <- survreg(Surv(Time, Status) ~ Diet*Sex*Hind_tibia_length,
                data = survival_table, dist = "weibull")

# Backward model selection
wei2 <- update(wei1, ~ . - Diet:Sex:Hind_tibia_length)
anova(wei2, wei1, test="Chisq")
summary(wei2)
anova(wei2)


# Collinearity?
wei1_col <- survreg(Surv(Time, Status) ~ Diet + Hind_tibia_length +
                  Sex,
                data = survival_table, dist = "weibull")
vif(wei1_col) # There is no collinearity

# Lognormal distribution
lognorm1 <- survreg(Surv(Time, Status) ~ Diet*Sex*Hind_tibia_length, 
                data = survival_table, dist = "lognormal")
summary(lognorm1)
anova(lognorm1)

# Backward model selection
lognorm2 <- update(lognorm1, ~ . - Diet:Sex:Hind_tibia_length)
anova(lognorm2, lognorm1, test="Chisq")
summary(lognorm2)
anova(lognorm2)

lognorm3 <- update(lognorm2, ~ . - Diet:Sex)
anova(lognorm3, lognorm2, test="Chisq")
summary(lognorm3)
anova(lognorm3)

# Gaussian distribution
gauss1 <- survreg(Surv(Time, Status) ~ Diet*Sex*Hind_tibia_length, 
                    data = survival_table, dist = "gaussian")
summary(gauss1) # complex model
anova(gauss1)

step_gauss1 <- step(gauss1)

# Backward model selection
gauss2 <- update(gauss1, ~ . - Diet:Sex:Hind_tibia_length)
anova(gauss2, gauss1, test="Chisq")
summary(gauss2)
anova(gauss2)

gauss3 <- update(gauss2, ~ . - Diet:Sex)
anova(gauss3, gauss2, test="Chisq")
summary(gauss3)
anova(gauss3)

gauss4 <- update(gauss3, ~ . - Diet:Hind_tibia_length)
anova(gauss4, gauss3, test="Chisq")
summary(gauss4)
anova(gauss4)

# Logistic distribution
logis1 <- survreg(Surv(Time, Status) ~ Diet*Sex*Hind_tibia_length, 
                  data = survival_table, dist = "logistic")
summary(logis1) # complex model
anova(logis1)

# Backward model selection
logis2 <- update(logis1, ~ . - Diet:Sex:Hind_tibia_length)
anova(logis2, logis1, test="Chisq")
summary(logis2)
anova(logis2)

logis3 <- update(logis2, ~ . - Diet:Sex)
anova(logis3, logis2, test="Chisq")
summary(logis3)
anova(logis3)

# Loglogistic distribution
loglogis1 <- survreg(Surv(Time, Status) ~ Diet*Sex*Hind_tibia_length, 
                  data = survival_table, dist = "loglogistic")
summary(loglogis1)
anova(loglogis1)

# Backward model selection
loglogis2 <- update(loglogis1, ~ . - Diet:Sex:Hind_tibia_length)
anova(loglogis2, loglogis1, test="Chisq")
summary(loglogis2)
anova(loglogis2)

loglogis3 <- update(loglogis2, ~ . - Diet:Sex)
anova(loglogis3, loglogis2, test="Chisq")
summary(loglogis3)
anova(loglogis3)

# AIC
AIC(exp7, wei2, lognorm3, gauss4, logis3, loglogis3)

# Weibull fitted model with hind tibia length ####
# Weibull distribution
wei1 <- survreg(Surv(Time, Status) ~ Diet*Hind_tibia_length +
                  Sex*Hind_tibia_length,
                data = survival_table, dist = "weibull")
summary(wei1)
anova(wei1)

# Is there collinearity between predictors?
wei1_col <- survreg(Surv(Time, Status) ~ Diet + Hind_tibia_length +
                      Sex,
                    data = survival_table, dist = "weibull")
vif(wei1_col) # There is no collinearity

# We add a natural spline to the hind tibia length covariate with two degree of freedom
wei1_ns <- survreg(Surv(Time, Status) ~ Diet*Sex*ns(Hind_tibia_length, df=2), 
                data = survival_table, dist = "weibull")
summary(wei1_ns)
anova(wei1_ns)

AIC(wei1_ns, wei1)

wei2_ns <- update(wei1_ns, ~ . - Diet:Sex:ns(Hind_tibia_length, df=2))
anova(wei2_ns, wei1_ns, test="Chisq")
summary(wei2_ns)
anova(wei2_ns)

wei3_ns <- update(wei2_ns, ~ . - Sex:ns(Hind_tibia_length, df=2))
anova(wei3_ns, wei2_ns, test="Chisq")
summary(wei3_ns)
anova(wei3_ns)

wei4_ns <- update(wei3_ns, ~ . - Diet:Sex)
anova(wei4_ns, wei3_ns, test="Chisq")
summary(wei4_ns)
anova(wei4_ns)

wei5_ns <- update(wei4_ns, ~ . - Diet:ns(Hind_tibia_length, df=2))
anova(wei5_ns, wei4_ns, test="Chisq")
summary(wei5_ns)
anova(wei5_ns)

wei6_ns <- update(wei5_ns, ~ . - Sex)
anova(wei6_ns, wei5_ns, test="Chisq")
summary(wei6_ns)
anova(wei6_ns)

AIC(wei1_ns, wei2_ns, wei3_ns, wei4_ns, wei5_ns, wei6_ns)

# Plot
plot_wei <- plot_model(wei6_ns, 
                       type="pred", 
                       terms = c("Hind_tibia_length [all]", "Diet"),
                       title = "") +
  ylab("Survival") +
  xlab("Hind tibia length (mm)") +
  theme(legend.position = "top")

plot_wei <- plot_wei +
  aes(linetype=group_col) + 
  scale_fill_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_color_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water")) +
  scale_linetype_discrete(
    limits = c("Honey", "Water"),
    labels = c("Honey", "Water"), name = "Diet")

plot_wei <- plot_wei + theme(text = element_text(family = "sans"))
plot_wei


# Save last plot
ggsave(
  "plot_wei_spline.pdf",
  plot = last_plot(),
  device = NULL,
  path = NULL,
  scale = 1,
  width = 9,
  height = 8,
  units = "cm",
  dpi = 300,
  limitsize = TRUE,
  bg = NULL,
  create.dir = FALSE
)

# Model adequacy for Weibull distribution
# Curves generally parallel
# Plot of log survival time versus log[–log(KM)]
wei_adeq <- flexsurvreg(Surv(Time, Status) ~
                          Diet*ns(Hind_tibia_length, df =2) + Sex*ns(Hind_tibia_length, df =2), 
                              data = survival_table, dist = "weibull")
plot(wei_adeq)

layout(1)
WeibullDiag(Surv(Time, Status) ~ Diet + Sex, data=survival_table)
WeibullDiag(Surv(Time, Status) ~ Diet, data=survival_table)

# Log-log survival curves
fit <- survfit(Surv(Time, Status) ~ Diet + Sex, data = survival_table)

plot(fit, fun = "cloglog", xlab = "Time (in days) using log",
     ylab = "log-log survival", main = "log-log curves by Diet") 

ggsurvplot(fit, fun = "cloglog")

# Convert the Weibull to more clinically relevant parameterization
# Center first HTL on its mean
ConvertWeibull(wei6_ns, conf.level = 0.95)

# First table: parameters of Weibull model
# Second table: HR and 95% CI
# Last table: relative change in survival time (ETR) and 95% CI

# Observed longevity
tapply(survival_table$Time, survival_table$Diet, mean)

# Predicted longevity
tapply(predict(wei1),survival_table$Diet, mean)


R.version.string
citation()

# END #